{"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n *  Copyright (c) 2015, Rice University\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Rice University nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Ryan Luna */\n\n#include <iostream>\n#include \"PlanarManipulator.h\"\n#include <boost/math/constants/constants.hpp>\n#include <stdexcept>\n\n#define PI boost::math::constants::pi<double>()\n#define TWOPI boost::math::constants::two_pi<double>()\n\nPlanarManipulator::PlanarManipulator(unsigned int numLinks, double linkLength, const std::pair<double, double> &origin)\n  : numLinks_(numLinks), linkLengths_(numLinks_, linkLength)\n{\n    baseFrame_ = Eigen::Affine2d::Identity();\n    baseFrame_.translation()[0] = origin.first;\n    baseFrame_.translation()[1] = origin.second;\n\n    hasBounds_.assign(numLinks_, false);\n    lowerBounds_.assign(numLinks_, std::numeric_limits<double>::min());\n    upperBounds_.assign(numLinks_, std::numeric_limits<double>::max());\n}\n\nPlanarManipulator::PlanarManipulator(unsigned int numLinks, const std::vector<double> &linkLengths,\n                                     const std::pair<double, double> &origin)\n  : numLinks_(numLinks), linkLengths_(linkLengths)\n{\n    if (linkLengths_.size() != numLinks)\n    {\n        std::cerr << \"Length of linkLengths (\" << linkLengths.size() << \") is not equal to the number of links (\"\n                  << numLinks << \")\" << std::endl;\n        throw;\n    }\n\n    baseFrame_ = Eigen::Affine2d::Identity();\n    baseFrame_.translation()[0] = origin.first;\n    baseFrame_.translation()[1] = origin.second;\n\n    hasBounds_.assign(numLinks_, false);\n    lowerBounds_.assign(numLinks_, std::numeric_limits<double>::min());\n    upperBounds_.assign(numLinks_, std::numeric_limits<double>::max());\n}\n\nPlanarManipulator::~PlanarManipulator()\n{\n}\n\n// Return the number of links\nunsigned int PlanarManipulator::getNumLinks() const\n{\n    return numLinks_;\n}\n\nconst Eigen::Affine2d &PlanarManipulator::getBaseFrame() const\n{\n    return baseFrame_;\n}\n\nvoid PlanarManipulator::setBaseFrame(const Eigen::Affine2d &frame)\n{\n    baseFrame_ = frame;\n}\n\n// Return the length of each link\nconst std::vector<double> &PlanarManipulator::getLinkLengths() const\n{\n    return linkLengths_;\n}\n\n// Set the bounds for link # link\nvoid PlanarManipulator::setBounds(unsigned int link, double low, double high)\n{\n    assert(link < hasBounds_.size());\n\n    hasBounds_[link] = true;\n    lowerBounds_[link] = low;\n    upperBounds_[link] = high;\n}\n\n// Set the bounds for ALL links\nvoid PlanarManipulator::setBounds(const std::vector<double> &low, const std::vector<double> &high)\n{\n    assert(low.size() == high.size());\n    assert(low.size() == numLinks_);\n\n    hasBounds_.assign(numLinks_, true);\n    lowerBounds_ = low;\n    upperBounds_ = high;\n}\n\nbool PlanarManipulator::hasBounds(unsigned int link) const\n{\n    return hasBounds_[link];\n}\n\nvoid PlanarManipulator::getBounds(unsigned int link, double &low, double &high) const\n{\n    low = lowerBounds_[link];\n    high = upperBounds_[link];\n}\nconst std::vector<double> &PlanarManipulator::lowerBounds() const\n{\n    return lowerBounds_;\n}\n\nconst std::vector<double> &PlanarManipulator::upperBounds() const\n{\n    return upperBounds_;\n}\n\n// Forward kinematics for the given joint configuration.  The frames for links\n// 1 through the end-effector are returned.\nvoid PlanarManipulator::FK(const std::vector<double> &joints, std::vector<Eigen::Affine2d> &frames) const\n{\n    FK(&joints[0], frames);\n}\n\nvoid PlanarManipulator::FK(const Eigen::VectorXd &joints, std::vector<Eigen::Affine2d> &frames) const\n{\n    FK(&joints(0), frames);\n}\n\nvoid PlanarManipulator::FK(const double *joints, std::vector<Eigen::Affine2d> &frames) const\n{\n    frames.clear();\n    Eigen::Affine2d frame(baseFrame_);\n\n    for (unsigned int i = 0; i < numLinks_; ++i)\n    {\n        // Rotate, then translate.  Just like the old gypsy woman said.\n        Eigen::Affine2d offset(Eigen::Rotation2Dd(joints[i]) * Eigen::Translation2d(linkLengths_[i], 0));\n        frame = frame * offset;\n        frames.push_back(frame);\n    }\n}\n\nvoid PlanarManipulator::FK(const std::vector<double> &joints, Eigen::Affine2d &eeFrame) const\n{\n    FK(&joints[0], eeFrame);\n}\n\nvoid PlanarManipulator::FK(const Eigen::VectorXd &joints, Eigen::Affine2d &eeFrame) const\n{\n    FK(&joints(0), eeFrame);\n}\n\nvoid PlanarManipulator::FK(const double *joints, Eigen::Affine2d &eeFrame) const\n{\n    eeFrame = baseFrame_;\n\n    for (unsigned int i = 0; i < numLinks_; ++i)\n    {\n        // Rotate, then translate.  Just like the old gypsy woman said.\n        Eigen::Affine2d offset(Eigen::Rotation2Dd(joints[i]) * Eigen::Translation2d(linkLengths_[i], 0));\n        eeFrame = eeFrame * offset;\n    }\n}\n\n// Inverse kinematics for the given end effector frame.  Only one solution is returned.\n// Returns false if no solution exists to the given pose.\nbool PlanarManipulator::IK(std::vector<double> &solution, const Eigen::Affine2d &eeFrame) const\n{\n    std::vector<double> seed(numLinks_, M_PI / 2.0);\n    return IK(solution, seed, eeFrame);\n}\n\nbool PlanarManipulator::IK(std::vector<double> &solution, const std::vector<double> &seed,\n                           const Eigen::Affine2d &desiredFrame) const\n{\n    // desired frame is clearly impossible to achieve\n    if (infeasible(desiredFrame))\n        return false;\n\n    // This is the orientation for the end effector\n    double angle = acos(desiredFrame.rotation()(0, 0));\n    // Due to numerical instability, sometimes acos will return nan if\n    // the value is slightly larger than one.  Check for this and try the\n    // asin of the next value\n    if (angle != angle)  // a nan is never equal to itself\n        angle = asin(desiredFrame.rotation()(0, 1));\n\n    // If still nan, return false\n    if (angle != angle)\n        return false;\n\n    // Get the current pose\n    Eigen::Affine2d frame;\n    FK(seed, frame);\n    Eigen::VectorXd current;\n    frameToPose(frame, current);\n\n    // Get the desired pose\n    Eigen::VectorXd desired;\n    frameToPose(desiredFrame, desired);\n\n    // Compute the error\n    Eigen::VectorXd e(desired - current);\n\n    Eigen::VectorXd joints(seed.size());\n    for (size_t i = 0; i < seed.size(); ++i)\n        joints(i) = seed[i];\n\n    double alpha = 0.1;  // step size\n\n    unsigned int iter = 1;\n    double eps = 1e-6;\n\n    Eigen::MatrixXd jac = Eigen::MatrixXd::Zero(3, numLinks_);\n    Eigen::JacobiSVD<Eigen::MatrixXd> svd(3, numLinks_, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::MatrixXd D = Eigen::MatrixXd::Zero(numLinks_, 3);\n\n    // Iterate the jacobian\n    while (e.norm() > eps)\n    {\n        // Get jacobian for this joint configuration\n        Jacobian(joints, jac);\n\n        // Compute inverse of the jacobian\n        // Really unstable\n        // Eigen::MatrixXd jac_inv = ((jac.transpose() * jac).inverse()) * jac.transpose();\n\n        // Moore-Penrose Pseudoinverse\n        svd.compute(jac);\n        const Eigen::JacobiSVD<Eigen::MatrixXd>::SingularValuesType &d = svd.singularValues();\n\n        // \"Invert\" the singular value matrix\n        for (int i = 0; i < d.size(); ++i)\n            if (d(i) > eps)\n                D(i, i) = 1.0 / d(i);\n            else\n                D(i, i) = 0.0;\n\n        // Inverse is V*D^-1*U^t\n        Eigen::MatrixXd jac_inv = svd.matrixV() * D * svd.matrixU().transpose();\n\n        // Get the joint difference\n        Eigen::VectorXd delta_theta = jac_inv * e;\n\n        // Check for failure\n        if (delta_theta(0) != delta_theta(0))  // nan\n        {\n            // std::cout << jac_inv.matrix() << std::endl;\n            return false;\n        }\n\n        // Increment the current joints by a (small) multiple of the difference\n        joints = joints + (alpha * delta_theta);\n\n        // Figure out the current EE pose and update e.\n        FK(joints, frame);\n        frameToPose(frame, current);\n        // double n = e.norm();\n        e = desired - current;\n        iter++;\n\n        if (iter > 5000)\n            return false;  // diverge\n    }\n\n    // Store the solution.  Make sure angles are in range [-pi, pi]\n    solution.resize(numLinks_);\n    for (size_t i = 0; i < solution.size(); ++i)\n    {\n        double angle = joints(i);\n        while (angle > M_PI)\n            angle -= 2.0 * M_PI;\n        while (angle < -M_PI)\n            angle += 2.0 * M_PI;\n        solution[i] = angle;\n    }\n\n    return true;\n}\n\nbool PlanarManipulator::FABRIK(std::vector<double> &solution, const Eigen::Affine2d &eeFrame, double xyTol,\n                               double thetaTol) const\n{\n    std::vector<double> seed(numLinks_, M_PI / 2.0);\n    return FABRIK(solution, seed, eeFrame, xyTol, thetaTol);\n}\n\nbool PlanarManipulator::FABRIK(std::vector<double> &solution, const std::vector<double> &seed,\n                               const Eigen::Affine2d &desiredFrame, double xyTol, double thetaTol) const\n{\n    unsigned int numLinks = getNumLinks();  // have to use this local variable.  Compiler error (bug?) in\n                                            // Eigen::Translation2d when I use numLinks_\n\n    if (seed.size() != numLinks)\n    {\n        std::cerr << \"Seed has length \" << seed.size() << \" but there are \" << numLinks << \" links\" << std::endl;\n        return false;\n    }\n\n    // desired frame is clearly impossible to achieve\n    if (infeasible(desiredFrame))\n        return false;\n\n    // copy the seed into the solution\n    solution.assign(seed.begin(), seed.end());\n\n    // Compute the location of the origin of the last link with the correct rotation\n    // This location will not move\n    Eigen::Vector2d loc(-linkLengths_.back(), 0);\n    loc = desiredFrame * loc;\n\n    // The desired orientation of the end effector\n    double v = desiredFrame.matrix()(0, 0);\n    // Go Go Gadget Numerical Stabilizer!\n    if (v < -1.0)\n        v = -1.0;\n    if (v > 1.0)\n        v = 1.0;\n    double eeTheta = acos(v);\n    if (desiredFrame.matrix()(1, 0) < 0)  // sin is negative, so the angle is negative\n        eeTheta = -eeTheta;\n\n    // The location of each joint, starting with the origin and ending with the end effector\n    // For an n-joint chain, jointPositions with have n+1 entries.\n    std::vector<Eigen::Vector2d> jointPositions;\n    jointPositions.push_back(baseFrame_.translation());  // root position\n\n    // Compute the initial locations of each joint\n    Eigen::Affine2d frame(baseFrame_);\n    for (unsigned int i = 0; i < seed.size(); ++i)\n    {\n        Eigen::Affine2d offset(Eigen::Rotation2Dd(seed[i]) * Eigen::Translation2d(linkLengths_[i], 0));\n        frame = frame * offset;\n        jointPositions.push_back(frame.translation());\n    }\n\n    // Store the errors here\n    double xyError = std::numeric_limits<double>::max();\n    double thetaError = std::numeric_limits<double>::max();\n\n    int numIterations = 0;\n    int maxIter = 250;  // after this many iterations, declare failure.  This is probably WAY too many - tends to\n                        // converge very fast, after 1-3 iterations\n    while ((xyError > xyTol || thetaError > thetaTol) && numIterations++ < maxIter)\n    {\n        xyError = thetaError = 0.0;\n\n        // Placing last link where it must go\n        jointPositions[numLinks] = desiredFrame.translation();  // goal position, nailed it.\n        jointPositions[numLinks - 1] = loc;                     // goal orientation, nailed it.\n\n        // A reverse coordinate frame, working backward along the chain.  Used to resolve joint limits in backward phase\n        // VERY IMPORTANT to translate first, then rotate.  This NOT like the old gypsy woman said.  I'm getting my\n        // money back.\n        Eigen::Affine2d backwardFrame(Eigen::Translation2d(jointPositions[numLinks - 1]) *\n                                      Eigen::Rotation2Dd(PI + eeTheta));  // end of chain, looking down the chain\n\n        // Move backward from the end effector toward the base\n        for (int i = jointPositions.size() - 3; i >= 0;\n             --i)  // -1 is end effector position.  Skip -2 to preserve the end effector orientation.\n        {\n            // draw a line between position i+1 and i, and place pt i at the kinematically feasible place along the line\n            double t = linkLengths_[i] / (jointPositions[i + 1] - jointPositions[i]).norm();\n            jointPositions[i] = (1 - t) * jointPositions[i + 1] + t * jointPositions[i];\n\n            // Ensure the angle for joint i is within bounds.  If not, move the joint position\n            Eigen::Vector2d vec = backwardFrame.inverse() * jointPositions[i];\n            double angle = -atan2(vec(1), vec(0));  // The angle computed is the negative of the real angle (because we\n                                                    // worked backward).\n\n            // If not in bounds, the angle will be one of the joint limits\n            if (hasBounds_[i] && (angle < lowerBounds_[i] || angle > upperBounds_[i]))\n            {\n                double dlow = fabs(angle - lowerBounds_[i]);\n                double dhigh = fabs(angle - upperBounds_[i]);\n                angle = (dlow < dhigh ? lowerBounds_[i] : upperBounds_[i]);\n            }\n\n            Eigen::Affine2d offset(Eigen::Rotation2Dd(-angle) * Eigen::Translation2d(linkLengths_[i], 0));\n            backwardFrame = backwardFrame * offset;\n            jointPositions[i] = backwardFrame.translation();\n        }\n\n        jointPositions[0] = baseFrame_.translation();  // move base back to where it is supposed to be\n        Eigen::Affine2d forwardFrame(baseFrame_);\n\n        // Move forward toward the end effector\n        for (size_t i = 0; i < jointPositions.size() - 1;\n             ++i)  // This pass moves everything except end effector.  Orientation at the end may be violated, but we\n                   // check for this\n        {\n            // draw a line between position i+1 and i and place i+1 at the kinematically feasible place along the line\n            double t = linkLengths_[i] / (jointPositions[i + 1] - jointPositions[i]).norm();\n            jointPositions[i + 1] = (1 - t) * jointPositions[i] + t * jointPositions[i + 1];\n\n            // Figure out the joint angle required for this\n            Eigen::Vector2d vec = forwardFrame.inverse() * jointPositions[i + 1];\n            double angle = atan2(vec(1), vec(0));\n\n            // If not in bounds, the angle will be one of the joint limits\n            if (hasBounds_[i] && (angle < lowerBounds_[i] || angle > upperBounds_[i]))\n            {\n                double dlow = fabs(angle - lowerBounds_[i]);\n                double dhigh = fabs(angle - upperBounds_[i]);\n                angle = (dlow < dhigh ? lowerBounds_[i] : upperBounds_[i]);\n            }\n            solution[i] = angle;\n\n            // Update frame\n            Eigen::Affine2d offset(Eigen::Rotation2Dd(angle) * Eigen::Translation2d(linkLengths_[i], 0));\n            forwardFrame = forwardFrame * offset;\n            jointPositions[i + 1] = forwardFrame.translation();  // joint location is the translation of the frame.  Do\n                                                                 // this here in case joint limits changed the angle\n        }\n\n        // Compute translation and orientation error\n        xyError = (jointPositions.back() - desiredFrame.translation()).norm();\n\n        v = forwardFrame.matrix()(0, 0);\n        // Go Go Gadget Numerical Stabilizer!\n        if (v > 1.0)\n            v = 1.0;\n        if (v < -1.0)\n            v = -1.0;\n\n        // The real angle\n        double thetaActual = acos(v);\n        if (forwardFrame.matrix()(1, 0) < 0)  // sin is negative, so the angle is negative\n            thetaActual = -thetaActual;\n        thetaError = fabs(eeTheta - thetaActual);\n    }\n\n    // Winning.  Extract joint angles.  Oh wait.  Already done BOOM.\n    if (xyError < xyTol && thetaError < thetaTol)\n        return true;\n\n    return false;\n}\n\nvoid PlanarManipulator::Jacobian(const double *joints, Eigen::MatrixXd &jac) const\n{\n    if (jac.rows() != 3 || jac.cols() != numLinks_)\n        jac = Eigen::MatrixXd::Zero(3, numLinks_);\n\n    std::vector<double> sins(numLinks_);\n    std::vector<double> coss(numLinks_);\n    double theta = 0.0;\n    for (size_t i = 0; i < numLinks_; ++i)\n    {\n        theta += joints[i];\n        sins[i] = sin(theta);\n        coss[i] = cos(theta);\n    }\n\n    for (size_t i = 0; i < numLinks_; ++i)\n    {\n        double entry1 = 0.0;\n        double entry2 = 0.0;\n        for (size_t j = numLinks_; j > i; --j)\n        {\n            entry1 += -(linkLengths_[j - 1] * sins[j - 1]);\n            entry2 += linkLengths_[j - 1] * coss[j - 1];\n        }\n        jac(0, i) = entry1;\n        jac(1, i) = entry2;\n        jac(2, i) = 1.0;\n    }\n}\n\n// Return the Jacobian for the manipulator at the given joint state.\nvoid PlanarManipulator::Jacobian(const std::vector<double> &joints, Eigen::MatrixXd &jac) const\n{\n    Jacobian(&joints[0], jac);\n}\n\nvoid PlanarManipulator::Jacobian(const Eigen::VectorXd &joints, Eigen::MatrixXd &jac) const\n{\n    Jacobian(&joints(0), jac);  // TODO: This is untested.  I dunno if an eigen::vector is contiguous.  It probably is.\n}\n\nvoid PlanarManipulator::frameToPose(const Eigen::Affine2d &frame, Eigen::VectorXd &pose)\n{\n    pose = Eigen::VectorXd(3);\n    pose(0) = frame.translation()(0);\n    pose(1) = frame.translation()(1);\n    pose(2) = acos(frame.matrix()(0, 0));\n}\n\nbool PlanarManipulator::infeasible(const Eigen::Affine2d &frame) const\n{\n    // Check for impossible query\n    // Compute the location of the origin of the last link with the correct rotation\n    Eigen::Vector2d loc(-linkLengths_[numLinks_ - 1], 0);\n    loc = frame * loc;\n\n    // Length of the chain, except for the last link\n    double len = 0.0;\n    for (size_t i = 0; i < numLinks_ - 1; ++i)\n        len += linkLengths_[i];\n\n    // Make sure the chain (without the last link) is long enough to reach the\n    // origin of the last link\n    Eigen::Vector2d org(baseFrame_.translation());\n    if ((org - loc).norm() > len)  // infeasible IK request\n        return true;\n\n    return false;\n}\n", "meta": {"hexsha": "9b5207bb47396cdaafa3e7659de1d89c11c1bb3c", "size": 19601, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/PlanarManipulator/PlanarManipulator.cpp", "max_stars_repo_name": "ericpairet/ompl", "max_stars_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 837.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T12:01:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:42:42.000Z", "max_issues_repo_path": "demos/PlanarManipulator/PlanarManipulator.cpp", "max_issues_repo_name": "ericpairet/ompl", "max_issues_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 271.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T22:05:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:16:01.000Z", "max_forks_repo_path": "demos/PlanarManipulator/PlanarManipulator.cpp", "max_forks_repo_name": "ericpairet/ompl", "max_forks_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 452.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T08:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T06:53:33.000Z", "avg_line_length": 36.5690298507, "max_line_length": 120, "alphanum_fraction": 0.6251211673, "num_tokens": 5010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24999510770195077}}
{"text": "//transforms_ex.cpp\n/*\n* the transforms from object to shadow and vice versa\n* .implementation.\n* (C) 2005 olegabr. All rights reserved.\n*/\n#include \"transforms_ex.h\"\n#include \"object3d.h\"\n#include \"shadow2d.h\"\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <set>\n#include <list>\n#include <cmath>\n\n#include <boost/lambda/lambda.hpp>\n\n#include <iostream>\nusing std::cout; using std::endl;\n\nshadow2d& create_mask(const shadow2d& sh, shadow2d& mask)\n{\n\tshadow2d::const_iterator s = sh.begin(), send = sh.end();\n\tshadow2d::iterator m = mask.begin();\n\tfor (; s != send; ++s, ++m)\n\t{\n\t\tsize2d_t sz = m->get_size();\n\t\tprojection2d::const_iterator ps = s->begin(), psend = s->end();\n\t\tint i1(0), i2(0), j1(0), j2(0);\n\t\t{\n\t\t\tprojection1d::const_iterator pps = ps->begin(), ppsend = ps->end();\n\t\t\tfor (; pps != ppsend; ++pps)\n\t\t\t\tif (*pps > 0.) break; else ++i1;\n\t\t}\n\n\t\tfor (; ps != psend; ++ps)\n\t\t\tif (*(ps->end()-1) > 0.) break; else ++i2;\n\n\t\tfor (ps = s->begin(); ps != psend; ++ps, ++j1)\n\t\t\tif (*(ps->begin()) > 0.) break;\n\t\tfor (; ps != psend; ++ps, ++j1)\n\t\t\tif (*(ps->begin()) == 0.) break;\n\n\t\t{\n\t\t\tps = psend-1;\n\t\t\tprojection1d::const_iterator pps = ps->begin(), ppsend = ps->end();\n\t\t\tfor (; pps != ppsend; ++pps, ++j2)\n\t\t\t\tif (*pps > 0.) break;\n\t\t\tfor (; pps != ppsend; ++pps, ++j2)\n\t\t\t\tif (*pps == 0.) break;\n\t\t}\n\n\t\t{\n\t\t\tint offset = 2;\n\t\t\tprojection2d::iterator pm = m->begin(), pmend = m->end();\n\t\t\tpixel2d px(0,0); //i,j\n\t\t\tfor (; pm != pmend; ++pm, ++px.j)\n\t\t\t{\n\t\t\t\tprojection1d::iterator ppm = pm->begin(), ppmend = pm->end();\n\t\t\t\tfor (px.i = 0; ppm != ppmend; ++ppm, ++px.i)\n\t\t\t\t{\n\t\t\t\t\tif\n\t\t\t\t\t(\n\t\t\t\t\t\t(px.i == 0)||\n\t\t\t\t\t\t(px.i == (sz.height - 1))||\n\t\t\t\t\t\t((px.i+px.j) <= i1+offset)||\n\t\t\t\t\t\t((int(sz.height)+px.j-px.i-1) <= i2+offset)||\n\t\t\t\t\t\t((sz.width - 1 + px.i-px.j) <= sz.width - 1 - (j1-offset))||\n\t\t\t\t\t\t((sz.width - 1 + sz.height - 1 - px.i-px.j) <= sz.height - 1 - (j2-offset))\n\t\t\t\t\t) *ppm = 0.;\n\t\t\t\t\telse *ppm = 1.;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn mask;\n}\n\nshadow2d& apply_mask(const shadow2d& mask, shadow2d& sh)\n{\n\t//shadow2d::iterator s = sh.begin(), send = sh.end();\n\t//shadow2d::const_iterator m = mask.begin();\n\t//for (; s != send; ++s, ++m)\n\t//{\n\t//\tprojection2d::iterator ps = s->begin(), psend = s->end();\n\t//\tprojection2d::const_iterator pm = m->begin();\n\t//\tfor (; ps != psend; ++ps, ++pm)\n\t//\t{\n\t//\t\tprojection1d::iterator pps = ps->begin(), ppsend = ps->end();\n\t//\t\tprojection1d::const_iterator ppm = pm->begin();\n\t//\t\tfor (; pps != ppsend; ++pps, ++ppm)\n\t//\t\t\t//if (*ppm < 0.5) *pps = 0.;\n\t//\t\t\t*pps *= *ppm;\n\t//\t}\n\t//}\n\treturn sh;\n}\n\nnamespace {\n\tobject3d::value_type calc_mean(const object3d& o, const pixel3d& px)\n\t{\n\t\tdouble k(1.1);\n\t\tobject3d::value_type value(0);\n\t\tfor (pixel3d d(-1,-1,-1); d.i <= 1; ++d.i)\n\t\t\tfor (d.j = -1; d.j <= 1; ++d.j)\n\t\t\t\tfor (d.k = -1; d.k <= 1; ++d.k)\n\t\t\t\t\tvalue += o(px+d);\n\n\t\treturn k*( value )/27.;\n\t}\n\n\tbool is_hole(const object3d& o, const pixel3d& px)\n\t{\n\t\tconst object3d::value_type z = 0.001;\n\t\tint n(0);\n\t\tfor (pixel3d d(-1,-1,-1); d.i <= 1; ++d.i)\n\t\t\tfor (d.j = -1; d.j <= 1; ++d.j)\n\t\t\t\tfor (d.k = -1; d.k <= 1; ++d.k)\n\t\t\t\t\tn += ((o(px+d) > z) ? 1 : 0);\n\t\treturn\n\t\t(\n\t\t\to(px) < z && /* == 0.*/\n\t\t\tn >= (26 - 23)\n\t\t);\n\t}\n\n\tstruct filled_area\n\t{\n\t\ttypedef std::size_t hash_t;\n\t\ttypedef std::set<hash_t> data_type;\n\n\t\tfilled_area(const size3d_t& sz) : size_(sz)\n\t\t{\n\t\t\t//use size_.depth to store the multiplication for optimization purpose\n\t\t\tsize_.depth = size_.width*size_.height;\n\t\t}\n\t\tfilled_area& add_pixel(const pixel3d& px)\n\t\t{\n\t\t\tdata_.insert(pixel2hash_(px));\n\t\t\treturn *this;\n\t\t}\n\t\tfilled_area& add_area(filled_area& ar)\n\t\t{\n\t\t\tassert(ar.size_ == size_);\n\t\t\tdata_.insert(ar.data_.begin(), ar.data_.end());\n\t\t\tar.data_.clear();\n\t\t\treturn *this;\n\t\t}\n\t\tbool is_adjacent(const pixel3d& px)\n\t\t{\n\t\t\tfor (pixel3d d(-1,-1,-1); d.i <= 1; ++d.i)\n\t\t\t\tfor (d.j = -1; d.j <= 1; ++d.j)\n\t\t\t\t\tfor (d.k = -1; d.k <= 1; ++d.k)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (d == pixel3d()) continue;\n\t\t\t\t\t\tif ( find_pixel_(px+d) ) return true;\n\t\t\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\tstd::size_t size() const { return data_.size(); }\n\t\tvoid clear(object3d& o, object3d::value_type replace_val)\n\t\t{\n\t\t\tfor (data_type::iterator i(data_.begin()); i != data_.end(); ++i)\n\t\t\t\to(hash2pixel_(*i)) = replace_val;\n\t\t\t//data_.clear();\n\t\t}\n\tprivate :\n\t\thash_t pixel2hash_(const pixel3d& px)\n\t\t{\n\t\t\treturn (px.k*size_.height + px.i)*size_.width + px.j;//ind;\n\t\t}\n\t\tpixel3d hash2pixel_(hash_t ind)\n\t\t{\n\t\t\tpixel3d px;\n\t\t\tpx.k = ind/size_.depth;\n\t\t\tpx.i = (ind - px.k*size_.depth)/size_.width;\n\t\t\tpx.j = ind - px.k*size_.depth - px.i*size_.width;\n\t\t\treturn px;\n\t\t}\n\t\tbool find_pixel_(const pixel3d& px)\n\t\t{\n\t\t\treturn data_.find(pixel2hash_(px)) != data_.end();\n\t\t}\n\t\tdata_type data_;\n\t\tsize3d_t size_;\n\t};\n\n\tbool operator < (const filled_area& lh, const filled_area& rh)\n\t{\n\t\treturn lh.size() < rh.size();\n\t}\n\n\tvoid remove_small_areas(object3d& o, object3d::value_type search_val, object3d::value_type replace_val)\n\t{\n\t\ttypedef std::list<filled_area> areas_type;\n\t\ttypedef std::vector<areas_type::iterator> areas_ptrs_type;\n\t\tareas_type areas;\n\t\tsize3d_t sz(o.get_size());\n\t\tlong count(0), COUNT(norm(sz));\n\t\tfor (pixel3d p(0, 0, 0); p.i < sz.height; ++p.i)\n\t\t{\n\t\t\tfor (p.j = 0; p.j < sz.width; ++p.j)\n\t\t\t{\n\t\t\t\tfor (p.k = 0; p.k < sz.depth; ++p.k)\n\t\t\t\t{ ++count;\n\t\t\t\t\tobject3d::value_type v(o(p) - search_val);\n\t\t\t\t\tobject3d::value_type absv(v>0 ? v : -v);\n\t\t\t\t\tif (absv < 0.0001)\n\t\t\t\t\t{\n\t\t\t\t\t\tareas_ptrs_type arp;\n\t\t\t\t\t\tfor (areas_type::iterator a(areas.begin()); a != areas.end(); ++a)\n\t\t\t\t\t\t\tif ( a->is_adjacent(p) ) arp.push_back(a);\n\n\t\t\t\t\t\tif (arp.size() > 1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//cout << \"arp.size = \" << arp.size() << \"\\n\";\n\t\t\t\t\t\t\t//cout << count << '/' << COUNT << \"\\tareas.size = \" << areas.size() << '\\n';\n\t\t\t\t\t\t\tstd::sort(arp.begin(), arp.end(), *boost::lambda::_1 < *boost::lambda::_2);\n\t\t\t\t\t\t\tareas_ptrs_type::iterator a(arp.begin()), big(arp.end()-1), aend(arp.end()-1);\n\t\t\t\t\t\t\tfor (; a != aend; ++a)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t(*big)->add_area(**a);\n\t\t\t\t\t\t\t\tareas.erase(*a);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t(*big)->add_pixel(p);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (arp.empty())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//cout << \"arp.empty\" << \"\\n\\n\";\n\t\t\t\t\t\t\tfilled_area a(sz);\n\t\t\t\t\t\t\ta.add_pixel(p);\n\t\t\t\t\t\t\tareas.push_back(a);\n\t\t\t\t\t\t\tcout << count << '/' << COUNT << \"\\tareas.size = \" << areas.size() << '\\n';\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse /*arp.size() == 1*/\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//cout << \"add_pixel\" << \"\\n\\n\";\n\t\t\t\t\t\t\tarp.front()->add_pixel(p);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << \"areas.size() = \" << areas.size() << endl;\n\t\tareas.sort();\n\t\tareas.reverse();\n\t\tareas.erase(areas.begin());\n\t\tfor (areas_type::iterator a(areas.begin()); a != areas.end(); ++a)\n\t\t\ta->clear(o, replace_val);\n\n\t}\n\tvoid add_mass(object3d& o, object3d::value_type search_val, long V)\n\t{\n\t\t//filled_area area;\n\t\t//size3d_t sz(o.get_size());\n\t\t//long rV(0);\n\t\t//for (pixel3d p(0, 0, 0); p.i < sz.height; ++p.i)\n\t\t//\tfor (p.j = 0; p.j < sz.width; ++p.j)\n\t\t//\t\tfor (p.k = 0; p.k < sz.depth; ++p.k)\n\t\t//\t\t{\n\t\t//\t\t\t++rV;\n\t\t//\t\t\tobject3d::value_type v(o(p) - search_val);\n\t\t//\t\t\tobject3d::value_type absv(v>0 ? v : -v);\n\t\t//\t\t\tif (absv < 0.0001) area.add_pixel(p);\n\t\t//\t\t}\n\t\t//for(; rV < V; ++rV)\n\t\t//{\n\t\t//\tarea.add_pixel_to_border();\n\t\t//}\n\t}\n} //unnamed namespace\n\n/*\n * V = 427437 pixels\n * density = 1.85\n */\nobject3d& apply_filter(const object3d& obj, const point3d& center, object3d& result)\n{\n\tassert(obj.get_size() == result.get_size());\n\tconst pixel3d pc = obj.point2pixel(center);\n\tconst long V = 216600;\n\tconst double d = 1.85;\n\tdouble rd(d); // real density\n\tlong rN(1); // number of pixels in count\n\tresult(pc) = d;\n\tlong rV(1); // number of pixels in new object\n\tconst int rmax(38);\n\tfor (int r(1); r <= rmax; ++r)\n\t{\n\t\t/*\n\t\t * calc main volume\n\t\t */\n\t\t{pixel3d dp(-r, -r, -r);\n\t\t\tfor (; dp.j <= r; ++dp.j)\n\t\t\t{\n\t\t\t\tfor (dp.k = -r; dp.k <= r; ++dp.k)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\trd += obj(px);\n\t\t\t\t\t++rN;\n\t\t\t\t\tif (calc_mean(obj, px) >= (rd/rN))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{pixel3d dp(r, -r, -r);\n\t\t\tfor (; dp.j <= r; ++dp.j)\n\t\t\t{\n\t\t\t\tfor (dp.k = -r; dp.k <= r; ++dp.k)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\trd += obj(px);\n\t\t\t\t\t++rN;\n\t\t\t\t\tif (calc_mean(obj, px) >= (rd/rN))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{pixel3d dp(1-r, -r, -r);\n\t\t\tfor (; dp.i < r; ++dp.i)\n\t\t\t{\n\t\t\t\tfor (dp.k = -r; dp.k <= r; ++dp.k)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\trd += obj(px);\n\t\t\t\t\t++rN;\n\t\t\t\t\tif (calc_mean(obj, px) >= (rd/rN))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{pixel3d dp(1-r, r, -r);\n\t\t\tfor (; dp.i < r; ++dp.i)\n\t\t\t{\n\t\t\t\tfor (dp.k = -r; dp.k <= r; ++dp.k)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\trd += obj(px);\n\t\t\t\t\t++rN;\n\t\t\t\t\tif (calc_mean(obj, px) >= (rd/rN))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{pixel3d dp(1-r, 1-r, -r);\n\t\t\tfor (; dp.j < r; ++dp.j)\n\t\t\t{\n\t\t\t\tfor (dp.i = 1-r; dp.i < r; ++dp.i)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\trd += obj(px);\n\t\t\t\t\t++rN;\n\t\t\t\t\tif (calc_mean(obj, px) >= (rd/rN))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{pixel3d dp(1-r, 1-r, r);\n\t\t\tfor (; dp.j < r; ++dp.j)\n\t\t\t{\n\t\t\t\tfor (dp.i = 1-r; dp.i < r; ++dp.i)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\trd += obj(px);\n\t\t\t\t\t++rN;\n\t\t\t\t\tif (calc_mean(obj, px) >= (rd/rN))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * fill holes\n\t\t */\n\t\t--r;\n\t\t{pixel3d dp(-r, -r, -r);\n\t\t\tfor (; dp.j <= r; ++dp.j)\n\t\t\t{\n\t\t\t\tfor (dp.k = 0; dp.k <= r; ++dp.k)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\tif (is_hole(obj, px))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{pixel3d dp(r, -r, -r);\n\t\t\tfor (; dp.j <= r; ++dp.j)\n\t\t\t{\n\t\t\t\tfor (dp.k = 0; dp.k <= r; ++dp.k)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\tif (is_hole(obj, px))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{pixel3d dp(1-r, -r, -r);\n\t\t\tfor (; dp.i < r; ++dp.i)\n\t\t\t{\n\t\t\t\tfor (dp.k = 0; dp.k <= r; ++dp.k)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\tif (is_hole(obj, px))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{pixel3d dp(1-r, r, -r);\n\t\t\tfor (; dp.i < r; ++dp.i)\n\t\t\t{\n\t\t\t\tfor (dp.k = 0; dp.k <= r; ++dp.k)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\tif (is_hole(obj, px))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{pixel3d dp(1-r, 1-r, -r);\n\t\t\tfor (; dp.j < r; ++dp.j)\n\t\t\t{\n\t\t\t\tfor (dp.i = 0; dp.i < r; ++dp.i)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\tif (is_hole(obj, px))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t{pixel3d dp(1-r, 1-r, r);\n\t\t\tfor (; dp.j < r; ++dp.j)\n\t\t\t{\n\t\t\t\tfor (dp.i = 0; dp.i < r; ++dp.i)\n\t\t\t\t{\n\t\t\t\t\tpixel3d px(pc);\n\t\t\t\t\tpx += dp;\n\t\t\t\t\tif (is_hole(obj, px))\n\t\t\t\t\t{\n\t\t\t\t\t\t++rV;\n\t\t\t\t\t\tresult(px) = d;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t++r;\n\t\t/*\n\t\t * end of fill holes\n\t\t */\n\t\tif (rV >= V) break;\n\t}\n\n\tremove_small_areas(result, d, 0.);\n\tremove_small_areas(result, 0., d);\n\t//add_mass(result, d, V);\n\t//cout << \"new Volume = \" << rV << endl;\n\n\treturn result;\n}\n\n\npoint3d calc_center(const shadow2d& sh)\n{\n\tpoint3d p;\n\tshadow2d::const_iterator pr = sh.begin(), epr = sh.end();\n\tfor (; pr != epr; ++pr)\n\t\tif (abs(pr->get_angle()) <= angle_t(43)) break;\n\tpoint2d p1 = pr->get_mass_center();\n\tangle_t a1 = pr->get_angle();\n\tfor (; pr != epr; ++pr)\n\t\tif (pr->get_angle() == angle_t(0)) break;\n\tpoint2d p2 = pr->get_mass_center();\n\tangle_t a2 = pr->get_angle();\n\n\tp.z = .5*(p1.x + p2.x);\n\tp.y = (p1.y*cos(a2) - p2.y*cos(a1))/(sin(a1)*cos(a2) - sin(a2)*cos(a1));\n\tp.x = (p1.y - p.y*sin(a1))/cos(a1);\n\n\treturn p;\n}\n\nobject3d& filter_object(object3d& object)\n{\n\tconst int mean = 167;\n\tobject3d::iterator o2d(object.begin()), end1(object.end());\n\tfor (; o2d != end1; ++o2d)\n\t{\n\t\tobject2d::iterator o(o2d->begin()), end2(o2d->end());\n\t\tfor (; o != end2; ++o)\n\t\t{\n\t\t\tdouble d(*o-mean);\n\t\t\t*o = std::pow((d>0?d:0.), 10.);\n\t\t}\n\t}\n\treturn object;\n}\n\nvoid black_threshold(shadow2d& sh, double threshold)\n{\n\tshadow2d::iterator s = sh.begin(), send = sh.end();\n\tfor (; s != send; ++s)\n\t{\n\t\tprojection2d::iterator ps = s->begin(), psend = s->end();\n\t\tfor (; ps != psend; ++ps)\n\t\t{\n\t\t\tprojection1d::iterator pps = ps->begin(), ppsend = ps->end();\n\t\t\tfor (; pps != ppsend; ++pps)\n\t\t\t{\n\t\t\t\tprojection1d::value_type val = *pps;\n\t\t\t\t*pps = (val >= threshold) ? val : 0.;\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "703d04cbd588de68b6f73debc988edb2650ae471", "size": 12295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3doptim/transforms_ex.cpp", "max_stars_repo_name": "olegabr/tomo3d", "max_stars_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-01-07T12:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T06:58:42.000Z", "max_issues_repo_path": "3doptim/transforms_ex.cpp", "max_issues_repo_name": "olegabr/tomo3d", "max_issues_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3doptim/transforms_ex.cpp", "max_forks_repo_name": "olegabr/tomo3d", "max_forks_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T10:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T10:22:13.000Z", "avg_line_length": 21.8772241993, "max_line_length": 104, "alphanum_fraction": 0.4978446523, "num_tokens": 4704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2499389747764833}}
{"text": "#include <ctime>\n#include <cmath>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n\n#include <boost/unordered_map.hpp> \n#include <boost/functional.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/algorithm/string/join.hpp>\n\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include \"maybe_omp.h\"\n#include <tclap/CmdLine.h>\n\n#include \"model.h\"\n#include \"propagator.h\"\n#include \"param.h\"\n#include \"neuralClasses.h\"\n#include \"graphClasses.h\"\n#include \"util.h\"\n#include \"multinomial.h\"\n//#include \"gradientCheck.h\"\n\n//#define EIGEN_DONT_PARALLELIZE\n\nusing namespace std;\nusing namespace TCLAP;\nusing namespace Eigen;\nusing namespace boost;\nusing namespace boost::random;\n\nusing namespace nplm;\n\ntypedef unordered_map<Matrix<int,Dynamic,1>, double> vector_map;\n\ntypedef long long int data_size_t; // training data can easily exceed 2G instances\n\nint main(int argc, char** argv)\n{ \n    param myParam;\n    try {\n      // program options //\n      CmdLine cmd(\"Trains a two-layer neural probabilistic language model.\", ' ' , \"0.1\");\n\n      // The options are printed in reverse order\n\n      ValueArg<string> unigram_probs_file(\"\", \"unigram_probs_file\", \"Unigram model (deprecated and ignored).\" , false, \"\", \"string\", cmd);\n\n      ValueArg<int> num_threads(\"\", \"num_threads\", \"Number of threads. Default: maximum.\", false, 0, \"int\", cmd);\n\n      ValueArg<double> final_momentum(\"\", \"final_momentum\", \"Final value of momentum. Default: 0.9.\", false, 0.9, \"double\", cmd);\n      ValueArg<double> initial_momentum(\"\", \"initial_momentum\", \"Initial value of momentum. Default: 0.9.\", false, 0.9, \"double\", cmd);\n      ValueArg<bool> use_momentum(\"\", \"use_momentum\", \"Use momentum (hidden layer weights only). 1 = yes, 0 = no. Default: 0.\", false, 0, \"bool\", cmd);\n\n      ValueArg<double> normalization_init(\"\", \"normalization_init\", \"Initial normalization parameter. Default: 0.\", false, 0.0, \"double\", cmd);\n      ValueArg<bool> normalization(\"\", \"normalization\", \"Learn individual normalization factors during training. 1 = yes, 0 = no. Default: 0.\", false, 0, \"bool\", cmd);\n\n      ValueArg<int> num_noise_samples(\"\", \"num_noise_samples\", \"Number of noise samples for noise-contrastive estimation. Default: 25.\", false, 25, \"int\", cmd);\n\n      ValueArg<double> L2_reg(\"\", \"L2_reg\", \"L2 regularization strength (hidden layer weights only). Default: 0.\", false, 0.0, \"double\", cmd);\n\n      ValueArg<double> learning_rate(\"\", \"learning_rate\", \"Learning rate for stochastic gradient ascent. Default: 0.01.\", false, 0.01, \"double\", cmd);\n\n      ValueArg<int> validation_minibatch_size(\"\", \"validation_minibatch_size\", \"Minibatch size for validation. Default: 64.\", false, 64, \"int\", cmd);\n      ValueArg<int> minibatch_size(\"\", \"minibatch_size\", \"Minibatch size (for training). Default: 64.\", false, 64, \"int\", cmd);\n\n      ValueArg<int> num_epochs(\"\", \"num_epochs\", \"Number of epochs. Default: 10.\", false, 10, \"int\", cmd);\n\n      ValueArg<double> init_range(\"\", \"init_range\", \"Maximum (of uniform) or standard deviation (of normal) for initialization. Default: 0.01\", false, 0.01, \"double\", cmd);\n      ValueArg<bool> init_normal(\"\", \"init_normal\", \"Initialize parameters from a normal distribution. 1 = normal, 0 = uniform. Default: 0.\", false, 0, \"bool\", cmd);\n\n      ValueArg<string> loss_function(\"\", \"loss_function\", \"Loss function (log, nce). Default: nce.\", false, \"nce\", \"string\", cmd);\n      ValueArg<string> activation_function(\"\", \"activation_function\", \"Activation function (identity, rectifier, tanh, hardtanh). Default: rectifier.\", false, \"rectifier\", \"string\", cmd);\n      ValueArg<int> num_hidden(\"\", \"num_hidden\", \"Number of hidden nodes. Default: 100.\", false, 100, \"int\", cmd);\n\n      ValueArg<bool> share_embeddings(\"\", \"share_embeddings\", \"Share input and output embeddings. 1 = yes, 0 = no. Default: 0.\", false, 0, \"bool\", cmd);\n      ValueArg<int> output_embedding_dimension(\"\", \"output_embedding_dimension\", \"Number of output embedding dimensions. Default: 50.\", false, 50, \"int\", cmd);\n      ValueArg<int> input_embedding_dimension(\"\", \"input_embedding_dimension\", \"Number of input embedding dimensions. Default: 50.\", false, 50, \"int\", cmd);\n      ValueArg<int> embedding_dimension(\"\", \"embedding_dimension\", \"Number of input and output embedding dimensions. Default: none.\", false, -1, \"int\", cmd);\n\n      ValueArg<int> vocab_size(\"\", \"vocab_size\", \"Vocabulary size. Default: auto.\", false, 0, \"int\", cmd);\n      ValueArg<int> input_vocab_size(\"\", \"input_vocab_size\", \"Vocabulary size. Default: auto.\", false, 0, \"int\", cmd);\n      ValueArg<int> output_vocab_size(\"\", \"output_vocab_size\", \"Vocabulary size. Default: auto.\", false, 0, \"int\", cmd);\n      ValueArg<int> ngram_size(\"\", \"ngram_size\", \"Size of n-grams. Default: auto.\", false, 0, \"int\", cmd);\n\n      ValueArg<string> model_prefix(\"\", \"model_prefix\", \"Prefix for output model files.\" , false, \"\", \"string\", cmd);\n      ValueArg<string> words_file(\"\", \"words_file\", \"Vocabulary.\" , false, \"\", \"string\", cmd);\n      ValueArg<string> input_words_file(\"\", \"input_words_file\", \"Vocabulary.\" , false, \"\", \"string\", cmd);\n      ValueArg<string> output_words_file(\"\", \"output_words_file\", \"Vocabulary.\" , false, \"\", \"string\", cmd);\n      ValueArg<string> validation_file(\"\", \"validation_file\", \"Validation data (one numberized example per line).\" , false, \"\", \"string\", cmd);\n      ValueArg<string> train_file(\"\", \"train_file\", \"Training data (one numberized example per line).\" , true, \"\", \"string\", cmd);\n\n      cmd.parse(argc, argv);\n\n      // define program parameters //\n      myParam.train_file = train_file.getValue();\n      myParam.validation_file = validation_file.getValue();\n      myParam.input_words_file = input_words_file.getValue();\n      myParam.output_words_file = output_words_file.getValue();\n      if (words_file.getValue() != \"\")\n\t  myParam.input_words_file = myParam.output_words_file = words_file.getValue();\n\n      myParam.model_prefix = model_prefix.getValue();\n\n      myParam.ngram_size = ngram_size.getValue();\n      myParam.vocab_size = vocab_size.getValue();\n      myParam.input_vocab_size = input_vocab_size.getValue();\n      myParam.output_vocab_size = output_vocab_size.getValue();\n      if (vocab_size.getValue() >= 0)\n\t  myParam.input_vocab_size = myParam.output_vocab_size = vocab_size.getValue();\n\n      myParam.num_hidden = num_hidden.getValue();\n      myParam.activation_function = activation_function.getValue();\n      myParam.loss_function = loss_function.getValue();\n\n      myParam.num_threads = num_threads.getValue();\n\n      myParam.num_noise_samples = num_noise_samples.getValue();\n\n      myParam.input_embedding_dimension = input_embedding_dimension.getValue();\n      myParam.output_embedding_dimension = output_embedding_dimension.getValue();\n      if (embedding_dimension.getValue() >= 0)\n\t      myParam.input_embedding_dimension = myParam.output_embedding_dimension = embedding_dimension.getValue();\n\n      myParam.minibatch_size = minibatch_size.getValue();\n      myParam.validation_minibatch_size = validation_minibatch_size.getValue();\n      myParam.num_epochs= num_epochs.getValue();\n      myParam.learning_rate = learning_rate.getValue();\n      myParam.use_momentum = use_momentum.getValue();\n      myParam.share_embeddings = share_embeddings.getValue();\n      myParam.normalization = normalization.getValue();\n      myParam.initial_momentum = initial_momentum.getValue();\n      myParam.final_momentum = final_momentum.getValue();\n      myParam.L2_reg = L2_reg.getValue();\n      myParam.init_normal= init_normal.getValue();\n      myParam.init_range = init_range.getValue();\n      myParam.normalization_init = normalization_init.getValue();\n\n      cerr << \"Command line: \" << endl;\n      cerr << boost::algorithm::join(vector<string>(argv, argv+argc), \" \") << endl;\n\n      const string sep(\" Value: \");\n      cerr << train_file.getDescription() << sep << train_file.getValue() << endl;\n      cerr << validation_file.getDescription() << sep << validation_file.getValue() << endl;\n      cerr << input_words_file.getDescription() << sep << input_words_file.getValue() << endl;\n      cerr << output_words_file.getDescription() << sep << output_words_file.getValue() << endl;\n      cerr << model_prefix.getDescription() << sep << model_prefix.getValue() << endl;\n\n      cerr << ngram_size.getDescription() << sep << ngram_size.getValue() << endl;\n      cerr << input_vocab_size.getDescription() << sep << input_vocab_size.getValue() << endl;\n      cerr << output_vocab_size.getDescription() << sep << output_vocab_size.getValue() << endl;\n\n      if (embedding_dimension.getValue() >= 0)\n      {\n\t  cerr << embedding_dimension.getDescription() << sep << embedding_dimension.getValue() << endl;\n      }\n      else\n      {\n\t  cerr << input_embedding_dimension.getDescription() << sep << input_embedding_dimension.getValue() << endl;\n\t  cerr << output_embedding_dimension.getDescription() << sep << output_embedding_dimension.getValue() << endl;\n      }\n      cerr << share_embeddings.getDescription() << sep << share_embeddings.getValue() << endl;\n      if (share_embeddings.getValue() && input_embedding_dimension.getValue() != output_embedding_dimension.getValue())\n      {\n\t  cerr << \"error: sharing input and output embeddings requires that input and output embeddings have same dimension\" << endl;\n\t  exit(1);\n      }\n\n      cerr << num_hidden.getDescription() << sep << num_hidden.getValue() << endl;\n\n      if (string_to_activation_function(activation_function.getValue()) == InvalidFunction)\n      {\n\t cerr << \"error: invalid activation function: \" << activation_function.getValue() << endl;\n\t  exit(1);\n      }\n      cerr << activation_function.getDescription() << sep << activation_function.getValue() << endl;\n\n      if (string_to_loss_function(loss_function.getValue()) == InvalidLoss)\n      {\n\t cerr << \"error: invalid loss function: \" << loss_function.getValue() << endl;\n\t  exit(1);\n      }\n      cerr << loss_function.getDescription() << sep << loss_function.getValue() << endl;\n\n      cerr << init_normal.getDescription() << sep << init_normal.getValue() << endl;\n      cerr << init_range.getDescription() << sep << init_range.getValue() << endl;\n\n      cerr << num_epochs.getDescription() << sep << num_epochs.getValue() << endl;\n      cerr << minibatch_size.getDescription() << sep << minibatch_size.getValue() << endl;\n      if (myParam.validation_file != \"\")\n\t  cerr << validation_minibatch_size.getDescription() << sep << validation_minibatch_size.getValue() << endl;\n      cerr << learning_rate.getDescription() << sep << learning_rate.getValue() << endl;\n      cerr << L2_reg.getDescription() << sep << L2_reg.getValue() << endl;\n\n      cerr << num_noise_samples.getDescription() << sep << num_noise_samples.getValue() << endl;\n\n      cerr << normalization.getDescription() << sep << normalization.getValue() << endl;\n      if (myParam.normalization)\n\t  cerr << normalization_init.getDescription() << sep << normalization_init.getValue() << endl;\n\n      cerr << use_momentum.getDescription() << sep << use_momentum.getValue() << endl;\n      if (myParam.use_momentum)\n      {\n\t  cerr << initial_momentum.getDescription() << sep << initial_momentum.getValue() << endl;\n\t  cerr << final_momentum.getDescription() << sep << final_momentum.getValue() << endl;\n      }\n\n      cerr << num_threads.getDescription() << sep << num_threads.getValue() << endl;\n\n      if (unigram_probs_file.getValue() != \"\")\n      {\n\t  cerr << \"Note: --unigram_probs_file is deprecated and ignored.\" << endl;\n      }\n    }\n    catch (TCLAP::ArgException &e)\n    {\n      cerr << \"error: \" << e.error() <<  \" for arg \" << e.argId() << endl;\n      exit(1);\n    }\n\n    myParam.num_threads = setup_threads(myParam.num_threads);\n    int save_threads;\n\n    //unsigned seed = std::time(0);\n    unsigned seed = 1234; //for testing only\n    mt19937 rng(seed);\n\n    /////////////////////////READING IN THE TRAINING AND VALIDATION DATA///////////////////\n    /////////////////////////////////////////////////////////////////////////////////////\n\n    // Read training data\n    vector<int> training_data_flat;\n    readDataFile(myParam.train_file, myParam.ngram_size, training_data_flat, myParam.minibatch_size);\n    data_size_t training_data_size = training_data_flat.size() / myParam.ngram_size;\n    cerr << \"Number of training instances: \"<< training_data_size << endl;\n\n    Map< Matrix<int,Dynamic,Dynamic> > training_data(training_data_flat.data(), myParam.ngram_size, training_data_size);\n\n    // If neither --input_vocab_size nor --input_words_file is given, set input_vocab_size to the maximum word index\n    if (myParam.input_vocab_size == 0 and myParam.input_words_file == \"\")\n    {\n        myParam.input_vocab_size = training_data.topRows(myParam.ngram_size-1).maxCoeff()+1;\n    }\n\n    // If neither --output_vocab_size nor --output_words_file is given, set output_vocab_size to the maximum word index\n    if (myParam.output_vocab_size == 0 and myParam.words_file == \"\")\n    {\n        myParam.output_vocab_size = training_data.row(myParam.ngram_size-1).maxCoeff()+1;\n    }\n\n    // Randomly shuffle training data to improve learning\n    for (data_size_t i=training_data_size-1; i>0; i--)\n    {\n        data_size_t j = uniform_int_distribution<data_size_t>(0, i-1)(rng);\n\ttraining_data.col(i).swap(training_data.col(j));\n    }\n\n    // Read validation data\n    vector<int> validation_data_flat;\n    int validation_data_size = 0;\n    \n    if (myParam.validation_file != \"\")\n    {\n\treadDataFile(myParam.validation_file, myParam.ngram_size, validation_data_flat);\n\tvalidation_data_size = validation_data_flat.size() / myParam.ngram_size;\n\tcerr << \"Number of validation instances: \" << validation_data_size << endl;\n    }\n\n    Map< Matrix<int,Dynamic,Dynamic> > validation_data(validation_data_flat.data(), myParam.ngram_size, validation_data_size);\n\n    ///// Read in vocabulary file. We don't actually use it; it just gets reproduced in the output file\n\n    vector<string> input_words;\n    if (myParam.input_words_file != \"\")\n    {\n        readWordsFile(myParam.input_words_file, input_words);\n\tif (myParam.input_vocab_size == 0)\n\t    myParam.input_vocab_size = input_words.size();\n    }\n\n    vector<string> output_words;\n    if (myParam.output_words_file != \"\")\n    {\n        readWordsFile(myParam.output_words_file, output_words);\n\tif (myParam.output_vocab_size == 0)\n\t    myParam.output_vocab_size = output_words.size();\n    }\n\n    ///// Construct unigram model and sampler that will be used for NCE\n\n    vector<data_size_t> unigram_counts(myParam.output_vocab_size);\n    for (data_size_t train_id=0; train_id < training_data_size; train_id++)\n    {\n        int output_word = training_data(myParam.ngram_size-1, train_id);\n\tunigram_counts[output_word] += 1;\n    }\n    multinomial<data_size_t> unigram (unigram_counts);\n\n    ///// Create and initialize the neural network and associated propagators.\n\n    model nn(myParam.ngram_size,\n        myParam.input_vocab_size,\n        myParam.output_vocab_size,\n        myParam.input_embedding_dimension,\n\t      myParam.num_hidden,\n        myParam.output_embedding_dimension,\n        myParam.share_embeddings);\n\n    nn.initialize(rng, myParam.init_normal, myParam.init_range, -log(myParam.output_vocab_size));\n    nn.set_activation_function(string_to_activation_function(myParam.activation_function));\n    loss_function_type loss_function = string_to_loss_function(myParam.loss_function);\n\n    propagator prop(nn, myParam.minibatch_size);\n    propagator prop_validation(nn, myParam.validation_minibatch_size);\n    SoftmaxNCELoss<multinomial<data_size_t> > softmax_loss(unigram);\n    // normalization parameters\n    vector_map c_h, c_h_running_gradient;\n    \n    ///////////////////////TRAINING THE NEURAL NETWORK////////////////////////////////////\n    /////////////////////////////////////////////////////////////////////////////////////\n\n    data_size_t num_batches = (training_data_size-1)/myParam.minibatch_size + 1;\n    cerr<<\"Number of training minibatches: \"<<num_batches<<endl;\n\n    int num_validation_batches = 0;\n    if (validation_data_size > 0)\n    {\n        num_validation_batches = (validation_data_size-1)/myParam.validation_minibatch_size+1;\n\tcerr<<\"Number of validation minibatches: \"<<num_validation_batches<<endl;\n    } \n\n    double current_momentum = myParam.initial_momentum;\n    double momentum_delta = (myParam.final_momentum - myParam.initial_momentum)/(myParam.num_epochs-1);\n    double current_learning_rate = myParam.learning_rate;\n    double current_validation_ll = 0.0;\n\n    int ngram_size = myParam.ngram_size;\n    int input_vocab_size = myParam.input_vocab_size;\n    int output_vocab_size = myParam.output_vocab_size;\n    int minibatch_size = myParam.minibatch_size;\n    int validation_minibatch_size = myParam.validation_minibatch_size;\n    int num_noise_samples = myParam.num_noise_samples;\n\n    if (myParam.normalization)\n    {\n\tfor (data_size_t i=0;i<training_data_size;i++)\n\t{\n\t    Matrix<int,Dynamic,1> context = training_data.block(0,i,ngram_size-1,1);\n\t    if (c_h.find(context) == c_h.end())\n\t    {\n\t        c_h[context] = -myParam.normalization_init;\n\t    }\n\t}\n    }\n\n    for (int epoch=0; epoch<myParam.num_epochs; epoch++)\n    { \n        cerr << \"Epoch \" << epoch+1 << endl;\n        cerr << \"Current learning rate: \" << current_learning_rate << endl;\n\n        if (myParam.use_momentum) \n\t    cerr << \"Current momentum: \" << current_momentum << endl;\n\telse\n            current_momentum = -1;\n\n\tcerr << \"Training minibatches: \";\n\n\tdouble log_likelihood = 0.0;\n\n\tint num_samples = 0;\n\tif (loss_function == LogLoss)\n\t    num_samples = output_vocab_size;\n\telse if (loss_function == NCELoss)\n\t    num_samples = 1+num_noise_samples;\n\n\tMatrix<double,Dynamic,Dynamic> minibatch_weights(num_samples, minibatch_size);\n\tMatrix<int,Dynamic,Dynamic> minibatch_samples(num_samples, minibatch_size);\n\tMatrix<double,Dynamic,Dynamic> scores(num_samples, minibatch_size);\n\tMatrix<double,Dynamic,Dynamic> probs(num_samples, minibatch_size);\n\n        for(data_size_t batch=0;batch<num_batches;batch++)\n        {\n            if (batch > 0 && batch % 10000 == 0)\n            {\n\t        cerr << batch <<\"...\";\n            } \n\n            data_size_t minibatch_start_index = minibatch_size * batch;\n            int current_minibatch_size = min(static_cast<data_size_t>(minibatch_size), training_data_size - minibatch_start_index);\n\t    Matrix<int,Dynamic,Dynamic> minibatch = training_data.middleCols(minibatch_start_index, current_minibatch_size);\n\n            double adjusted_learning_rate = current_learning_rate/current_minibatch_size;\n            //cerr<<\"Adjusted learning rate: \"<<adjusted_learning_rate<<endl;\n\n            /*\n            if (batch == rand() % num_batches)\n            {\n                cerr<<\"we are checking the gradient in batch \"<<batch<<endl;\n                /////////////////////////CHECKING GRADIENTS////////////////////////////////////////\n                gradientChecking(myParam,minibatch_start_index,current_minibatch_size,word_nodes,context_nodes,hidden_layer_node,hidden_layer_to_output_node,\n                              shuffled_training_data,c_h,unif_real_vector,eng_real_vector,unif_int_vector,eng_int_vector,unigram_probs_vector,\n                              q_vector,J_vector,D_prime);\n            }\n            */\n\n            ///// Forward propagation\n\n            prop.fProp(minibatch.topRows(ngram_size-1));\n\n\t    if (loss_function == NCELoss)\n\t    {\n\t        ///// Noise-contrastive estimation\n\n\t        // Generate noise samples. Gather positive and negative samples into matrix.\n\n\t        start_timer(3);\n\n\t\tminibatch_samples.block(0, 0, 1, current_minibatch_size) = minibatch.bottomRows(1);\n\t\t\n\t\tfor (int sample_id = 1; sample_id < num_noise_samples+1; sample_id++)\n\t\t    for (int train_id = 0; train_id < current_minibatch_size; train_id++)\n\t\t        minibatch_samples(sample_id, train_id) = unigram.sample(rng);\n\t    \n\t\tstop_timer(3);\n\n\t\t// Final forward propagation step (sparse)\n\t\tstart_timer(4);\n\t\tprop.output_layer_node.param->fProp(prop.second_hidden_activation_node.fProp_matrix,\n\t\t\t\t\t\t    minibatch_samples, scores);\n\t\tstop_timer(4);\n\n\t\t// Apply normalization parameters\n\t\tif (myParam.normalization)\n\t\t{\n\t\t    for (int train_id = 0;train_id < current_minibatch_size;train_id++)\n\t\t    {\n\t\t\tMatrix<int,Dynamic,1> context = minibatch.block(0, train_id, ngram_size-1, 1);\n\t\t\tscores.col(train_id).array() += c_h[context];\n\t\t    }\n\t\t}\n\n\t\tdouble minibatch_log_likelihood;\n\t\tstart_timer(5);\n\t\tsoftmax_loss.fProp(scores.leftCols(current_minibatch_size), \n\t\t\t\t   minibatch_samples,\n\t\t\t\t   probs, minibatch_log_likelihood);\n\t\tstop_timer(5);\n\t\tlog_likelihood += minibatch_log_likelihood;\n\n\t\t///// Backward propagation\n\n\t\tstart_timer(6);\n\t\tsoftmax_loss.bProp(probs, minibatch_weights);\n\t\tstop_timer(6);\n\t\t\n\t\t// Update the normalization parameters\n\t\t\n\t\tif (myParam.normalization)\n\t\t{\n\t\t    for (int train_id = 0;train_id < current_minibatch_size;train_id++)\n\t\t    {\n\t\t\tMatrix<int,Dynamic,1> context = minibatch.block(0, train_id, ngram_size-1, 1);\n\t\t\tc_h[context] += adjusted_learning_rate * minibatch_weights.col(train_id).sum();\n\t\t    }\n\t\t}\n\n\t\t// Be careful of short minibatch\n\t\tprop.bProp(minibatch.topRows(ngram_size-1),\n\t\t\t   minibatch_samples.leftCols(current_minibatch_size), \n\t\t\t   minibatch_weights.leftCols(current_minibatch_size),\n\t\t\t   adjusted_learning_rate, current_momentum, myParam.L2_reg);\n\t    }\n\t    else if (loss_function == LogLoss)\n\t    {\n\t        ///// Standard log-likelihood\n\t        start_timer(4);\n\t\tprop.output_layer_node.param->fProp(prop.second_hidden_activation_node.fProp_matrix, scores);\n\t\tstop_timer(4);\n\n\t\tdouble minibatch_log_likelihood;\n\t\tstart_timer(5);\n\t\tSoftmaxLogLoss().fProp(scores.leftCols(current_minibatch_size), \n\t\t\t\t       minibatch.row(ngram_size-1), \n\t\t\t\t       probs, \n\t\t\t\t       minibatch_log_likelihood);\n\t\tstop_timer(5);\n\t\tlog_likelihood += minibatch_log_likelihood;\n\n\t\t///// Backward propagation\n\t\t\n\t\tstart_timer(6);\n\t\tSoftmaxLogLoss().bProp(minibatch.row(ngram_size-1).leftCols(current_minibatch_size), \n\t\t\t\t       probs.leftCols(current_minibatch_size), \n\t\t\t\t       minibatch_weights);\n\t\tstop_timer(6);\n\t\t\n\t\tprop.bProp(minibatch.topRows(ngram_size-1).leftCols(current_minibatch_size),\n\t\t\t   minibatch_weights,\n\t\t\t   adjusted_learning_rate, current_momentum, myParam.L2_reg);\n\t    }\n        }\n\tcerr << \"done.\" << endl;\n\n\tif (loss_function == LogLoss)\n\t{\n\t    cerr << \"Training log-likelihood: \" << log_likelihood << endl;\n            cerr << \"         perplexity:     \"<< exp(-log_likelihood/training_data_size) << endl;\n\t}\n\telse if (loss_function == NCELoss)\n\t    cerr << \"Training NCE log-likelihood: \" << log_likelihood << endl;\n\n        current_momentum += momentum_delta;\n\n\t#ifdef USE_CHRONO\n\tcerr << \"Propagation times:\";\n\tfor (int i=0; i<timer.size(); i++)\n\t  cerr << \" \" << timer.get(i);\n\tcerr << endl;\n\t#endif\n\n\tif (myParam.model_prefix != \"\")\n\t{\n\t    cerr << \"Writing model\" << endl;\n\t    if (myParam.input_words_file != \"\")\n\t        nn.write(myParam.model_prefix + \".\" + lexical_cast<string>(epoch+1), input_words, output_words);\n\t    else\n\t        nn.write(myParam.model_prefix + \".\" + lexical_cast<string>(epoch+1));\n\t}\n\n        if (epoch % 1 == 0 && validation_data_size > 0)\n        {\n            //////COMPUTING VALIDATION SET PERPLEXITY///////////////////////\n            ////////////////////////////////////////////////////////////////\n\n            double log_likelihood = 0.0;\n\n\t    Matrix<double,Dynamic,Dynamic> scores(output_vocab_size, validation_minibatch_size);\n\t    Matrix<double,Dynamic,Dynamic> output_probs(output_vocab_size, validation_minibatch_size);\n\t    Matrix<int,Dynamic,Dynamic> minibatch(ngram_size, validation_minibatch_size);\n\n            for (int validation_batch =0;validation_batch < num_validation_batches;validation_batch++)\n            {\n                int validation_minibatch_start_index = validation_minibatch_size * validation_batch;\n\t\tint current_minibatch_size = min(validation_minibatch_size,\n\t\t\t\t\t\t validation_data_size - validation_minibatch_start_index);\n\t\tminibatch.leftCols(current_minibatch_size) = validation_data.middleCols(validation_minibatch_start_index, \n\t\t\t\t\t\t\t\t\t\t\tcurrent_minibatch_size);\n\t\tprop_validation.fProp(minibatch.topRows(ngram_size-1));\n\n\t\t// Do full forward prop through output word embedding layer\n\t\tstart_timer(4);\n\t\tprop_validation.output_layer_node.param->fProp(prop_validation.second_hidden_activation_node.fProp_matrix, scores);\n\t\tstop_timer(4);\n\n\t\t// And softmax and loss. Be careful of short minibatch\n\t\tdouble minibatch_log_likelihood;\n\t\tstart_timer(5);\n\t\tSoftmaxLogLoss().fProp(scores.leftCols(current_minibatch_size), \n\t\t\t\t       minibatch.row(ngram_size-1),\n\t\t\t\t       output_probs,\n\t\t\t\t       minibatch_log_likelihood);\n\t\tstop_timer(5);\n\t\tlog_likelihood += minibatch_log_likelihood;\n\t    }\n\n            cerr << \"Validation log-likelihood: \"<< log_likelihood << endl;\n            cerr << \"           perplexity:     \"<< exp(-log_likelihood/validation_data_size) << endl;\n\n\t    // If the validation perplexity decreases, halve the learning rate.\n            if (epoch > 0 && log_likelihood < current_validation_ll)\n            { \n                current_learning_rate /= 2;\n            }\n            current_validation_ll = log_likelihood;\n\t}\n\n    }\n    return 0;\n}\n", "meta": {"hexsha": "f45bc7141e7a5313a6a77960e8d4a64d8cb1aba5", "size": 25394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/trainNeuralNetwork.cpp", "max_stars_repo_name": "gonzaloiglesiasiglesias/nplm", "max_stars_repo_head_hexsha": "a4a69b83e6ed03e031625a5d3b2e1ab3ad2909ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T10:44:02.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-21T10:44:02.000Z", "max_issues_repo_path": "nplm/src/trainNeuralNetwork.cpp", "max_issues_repo_name": "zaycev/nnsmt", "max_issues_repo_head_hexsha": "a030e51a6679a22b7fdcd03bf2161ee0d08281a7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nplm/src/trainNeuralNetwork.cpp", "max_forks_repo_name": "zaycev/nnsmt", "max_forks_repo_head_hexsha": "a030e51a6679a22b7fdcd03bf2161ee0d08281a7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-09-04T13:20:40.000Z", "max_forks_repo_forks_event_max_datetime": "2015-09-04T13:20:40.000Z", "avg_line_length": 43.4085470085, "max_line_length": 187, "alphanum_fraction": 0.6791761834, "num_tokens": 5862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.24990280524119862}}
{"text": "#include <GL/freeglut.h>\n#include <vector>\n#include <Eigen/Eigen>\n#include <iostream>\n#include <iomanip>\n\n#include \"structures.h\"\n#include \"transformations.h\"\n#include \"relative_pose_tait_bryan_wc_jacobian.h\"\n#include \"relative_pose_rodrigues_wc_jacobian.h\"\n#include \"relative_pose_quaternion_wc_jacobian.h\"\n#include \"quaternion_constraint_jacobian.h\"\n#include \"relative_pose_wc_jacobian.h\"\n#include \"relative_pose_2_tait_bryan_wc_jacobian.h\"\n#include \"relative_pose_2_rodrigues_wc_jacobian.h\"\n#include \"relative_pose_2_quaternion_wc_jacobian.h\"\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -10.0;\nfloat translate_x, translate_y = 0.0;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\n\nstd::vector<Eigen::Affine3d> m_poses;\nstd::vector<Eigen::Affine3d> m_poses_desired;\n\nstd::vector<std::pair<int, int>> odo_edges;\nstd::vector<std::pair<int, int>> loop_edges;\n\nint main(int argc, char *argv[]){\n\n\tfor(size_t i = 0 ; i < 100; i++){\n\t\tTaitBryanPose p;\n\t\tp.px = i;\n\t\tp.py = -1;\n\t\tp.pz = 0.0;\n\t\tp.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\tp.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\tp.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\n\t\tEigen::Affine3d m = affine_matrix_from_pose_tait_bryan(p);\n\t\tm_poses.push_back(m);\n\t}\n\tfor(size_t i = 0 ; i < 100; i++){\n\t\tTaitBryanPose p;\n\t\tp.px = i;\n\t\tp.py = 1;\n\t\tp.pz = 0.0;\n\t\tp.om = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\tp.fi = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\tp.ka = ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\n\t\tEigen::Affine3d m = affine_matrix_from_pose_tait_bryan(p);\n\t\tm_poses.push_back(m);\n\t}\n\tm_poses_desired = m_poses;\n\n\tfor(size_t i = 1; i < 100; i++){\n\t\todo_edges.emplace_back(i-1,i);\n\t}\n\n\tfor(size_t i = 101; i < 200; i++){\n\t\todo_edges.emplace_back(i-1,i);\n\t}\n\n\tfor(size_t i = 0; i < 100; i+=10){\n\t\tloop_edges.emplace_back(i,i+100);\n\t}\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\n\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"relative_pose\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglBegin(GL_LINES);\n\tglColor3f(1.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(1.0f, 0.0f, 0.0f);\n\n\tglColor3f(0.0f, 1.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 1.0f, 0.0f);\n\n\tglColor3f(0.0f, 0.0f, 1.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 1.0f);\n\tglEnd();\n\n\tglColor3f(1,0,0);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0; i < odo_edges.size(); i++){\n\t\tglVertex3f(m_poses[odo_edges[i].first](0,3), m_poses[odo_edges[i].first](1,3), m_poses[odo_edges[i].first](2,3) );\n\t\tglVertex3f(m_poses[odo_edges[i].second](0,3), m_poses[odo_edges[i].second](1,3), m_poses[odo_edges[i].second](2,3) );\n\t}\n\tglEnd();\n\n\tglColor3f(0,1,0);\n\tglBegin(GL_LINES);\n\tfor(size_t i = 0; i < loop_edges.size(); i++){\n\t\tglVertex3f(m_poses[loop_edges[i].first](0,3), m_poses[loop_edges[i].first](1,3), m_poses[loop_edges[i].first](2,3) );\n\t\tglVertex3f(m_poses[loop_edges[i].second](0,3), m_poses[loop_edges[i].second](1,3), m_poses[loop_edges[i].second](2,3) );\n\t}\n\tglEnd();\n\n\n\tglutSwapBuffers();\n}\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'n':{\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\tpose.px += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.py += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.pz += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.1;\n\t\t\t\tpose.om += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\t\t\tpose.fi += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\t\t\tpose.ka += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.01;\n\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\t\t\tstd::vector<TaitBryanPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_tait_bryan_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].om,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].om,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < loop_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].om,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].om,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].om,\n\t\t\t\t\t\tposes[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].om,\n\t\t\t\t\t\tposes[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes[loop_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].om,\n\t\t\t\t\t\tposes[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].om,\n\t\t\t\t\t\tposes[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes[loop_edges[i].second].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 6;\n\t\t\t\tint ic_2 = loop_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 6 , m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with tait bryan finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with tait bryan FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\t\tcase 'r':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<RodriguesPose> poses;\n\t\t\tstd::vector<RodriguesPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_rodrigues_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_rodrigues_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_rodrigues_wc(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sz);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes[odo_edges[i].second].sz,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes[odo_edges[i].second].sz);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < loop_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_rodrigues_wc(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sz);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes[loop_edges[i].second].sz,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes[loop_edges[i].second].sz);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 6;\n\t\t\t\tint ic_2 = loop_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 6 , m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\t\tpose.sz += h_x[counter++];\n\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_rodrigues(pose);\n\n\t\t\t\t\tEigen::Vector3d vx(m_poses[i](0,0), m_poses[i](1,0), m_poses[i](2,0));\n\t\t\t\t\tEigen::Vector3d vy(m_poses[i](0,1), m_poses[i](1,1), m_poses[i](2,1));\n\t\t\t\t\tEigen::Vector3d vz(m_poses[i](0,2), m_poses[i](1,2), m_poses[i](2,2));\n\n\t\t\t\t\tstd::cout << std::setprecision(15);\n\t\t\t\t\tstd::cout << \"norm: \"<< vx.norm() << \" \" << vy.norm() << \" \" << vz.norm() << \" \" <<\n\t\t\t\t\t\t\tvx.dot(vy) << \" \" << vy.dot(vz) << \" \" << vx.dot(vz) << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with rodrigues finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with rodrigues FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 'q':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<QuaternionPose> poses;\n\t\t\tstd::vector<QuaternionPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_quaternion_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_quaternion_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 7, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_quaternion_wc(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q3);\n\n\t\t\t\tEigen::Matrix<double, 7, 1> delta;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes[odo_edges[i].second].q3,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(6,0));\n\n\t\t\t\tEigen::Matrix<double, 7, 14, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes[odo_edges[i].second].q3);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 7;\n\t\t\t\tint ic_2 = odo_edges[i].second * 7;\n\n\t\t\t\tfor(size_t row = 0 ; row < 7; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 6, -jacobian(row,6));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,11));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 6, -jacobian(row,13));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\t\t\t\ttripletListB.emplace_back(ir + 6, 0, delta(6,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 6, ir + 6, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < loop_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 7, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_quaternion_wc(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q3);\n\n\t\t\t\tEigen::Matrix<double, 7, 1> delta;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes[loop_edges[i].second].q3,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(6,0));\n\n\t\t\t\tEigen::Matrix<double, 7, 14, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes[loop_edges[i].second].q3);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 7;\n\t\t\t\tint ic_2 = loop_edges[i].second * 7;\n\n\t\t\t\tfor(size_t row = 0 ; row < 7; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 6, -jacobian(row,6));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,11));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 6, -jacobian(row,13));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\t\t\t\ttripletListB.emplace_back(ir + 6, 0, delta(6,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 6, ir + 6, 1);\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\t\t\ttripletListA.emplace_back(ir + 6 , 6, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 6 , ir + 6, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 6 , 0, 0);\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tint ic = i * 7;\n\t\t\t\tir = tripletListB.size();\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(m_poses[i]);\n\n\t\t\t\tdouble delta;\n\t\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\ttripletListA.emplace_back(ir, ic + 3 , -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 4 , -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 5 , -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 6 , -jacobian(0,3));\n\n\t\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\t\t\t}\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 7);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 7 , m_poses.size() * 7);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 7 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 7 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\t\tpose.q3 += h_x[counter++];\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_quaternion(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with quaternions finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with quaternions FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 'x':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 12, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_wc(relative_pose_measurement_odo,\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](0,3),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](1,3),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](2,3),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](0,0),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](0,1),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](0,2),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](1,0),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](1,1),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](1,2),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](2,0),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](2,1),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].first](2,2),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](0,3),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](1,3),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](2,3),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](0,0),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](0,1),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](0,2),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](1,0),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](1,1),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](1,2),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](2,0),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](2,1),\n\t\t\t\t\t\tm_poses_desired[odo_edges[i].second](2,2));\n\n\t\t\t\tEigen::Matrix<double, 12, 1> delta;\n\t\t\t\trelative_pose_obs_eq_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tm_poses[odo_edges[i].first](0,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](1,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](2,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](0,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](0,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](0,2),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](1,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](1,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](1,2),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](2,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](2,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](2,2),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](0,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](1,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](2,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](0,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](0,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](0,2),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](1,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](1,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](1,2),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](2,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](2,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](2,2),\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(6,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(7,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(8,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(9,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(10,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(11,0));\n\n\t\t\t\tEigen::Matrix<double, 12, 24, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_wc_jacobian(jacobian,\n\t\t\t\t\t\tm_poses[odo_edges[i].first](0,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](1,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](2,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](0,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](0,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](0,2),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](1,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](1,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](1,2),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](2,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](2,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].first](2,2),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](0,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](1,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](2,3),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](0,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](0,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](0,2),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](1,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](1,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](1,2),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](2,0),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](2,1),\n\t\t\t\t\t\tm_poses[odo_edges[i].second](2,2));\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 12;\n\t\t\t\tint ic_2 = odo_edges[i].second * 12;\n\n\t\t\t\tfor(size_t row = 0 ; row < 12; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 6, -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 7, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 8, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 9, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 10, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 11, -jacobian(row,11));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,13));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,14));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,15));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,16));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,17));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 6, -jacobian(row,18));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 7, -jacobian(row,19));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 8, -jacobian(row,20));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 9, -jacobian(row,21));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 10, -jacobian(row,22));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 11, -jacobian(row,23));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\t\t\t\ttripletListB.emplace_back(ir + 6, 0, delta(6,0));\n\t\t\t\ttripletListB.emplace_back(ir + 7, 0, delta(7,0));\n\t\t\t\ttripletListB.emplace_back(ir + 8, 0, delta(8,0));\n\t\t\t\ttripletListB.emplace_back(ir + 9, 0, delta(9,0));\n\t\t\t\ttripletListB.emplace_back(ir + 10, 0, delta(10,0));\n\t\t\t\ttripletListB.emplace_back(ir + 11, 0, delta(11,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 6, ir + 6, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 7, ir + 7, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 8, ir + 8, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 9, ir + 9, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 10, ir + 10, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 11, ir + 11, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < loop_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 12, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_wc(relative_pose_measurement_loop,\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](0,3),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](1,3),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](2,3),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](0,0),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](0,1),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](0,2),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](1,0),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](1,1),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](1,2),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](2,0),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](2,1),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].first](2,2),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](0,3),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](1,3),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](2,3),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](0,0),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](0,1),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](0,2),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](1,0),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](1,1),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](1,2),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](2,0),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](2,1),\n\t\t\t\t\t\tm_poses_desired[loop_edges[i].second](2,2));\n\n\t\t\t\tEigen::Matrix<double, 12, 1> delta;\n\t\t\t\trelative_pose_obs_eq_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tm_poses[loop_edges[i].first](0,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](1,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](2,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](0,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](0,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](0,2),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](1,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](1,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](1,2),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](2,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](2,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](2,2),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](0,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](1,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](2,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](0,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](0,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](0,2),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](1,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](1,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](1,2),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](2,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](2,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](2,2),\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(6,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(7,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(8,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(9,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(10,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(11,0));\n\n\t\t\t\tEigen::Matrix<double, 12, 24, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_wc_jacobian(jacobian,\n\t\t\t\t\t\tm_poses[loop_edges[i].first](0,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](1,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](2,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](0,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](0,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](0,2),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](1,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](1,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](1,2),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](2,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](2,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].first](2,2),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](0,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](1,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](2,3),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](0,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](0,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](0,2),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](1,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](1,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](1,2),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](2,0),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](2,1),\n\t\t\t\t\t\tm_poses[loop_edges[i].second](2,2));\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 12;\n\t\t\t\tint ic_2 = loop_edges[i].second * 12;\n\n\t\t\t\tfor(size_t row = 0 ; row < 12; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 6, -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 7, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 8, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 9, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 10, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 11, -jacobian(row,11));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,13));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,14));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,15));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,16));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,17));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 6, -jacobian(row,18));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 7, -jacobian(row,19));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 8, -jacobian(row,20));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 9, -jacobian(row,21));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 10, -jacobian(row,22));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 11, -jacobian(row,23));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\t\t\t\ttripletListB.emplace_back(ir + 6, 0, delta(6,0));\n\t\t\t\ttripletListB.emplace_back(ir + 7, 0, delta(7,0));\n\t\t\t\ttripletListB.emplace_back(ir + 8, 0, delta(8,0));\n\t\t\t\ttripletListB.emplace_back(ir + 9, 0, delta(9,0));\n\t\t\t\ttripletListB.emplace_back(ir + 10, 0, delta(10,0));\n\t\t\t\ttripletListB.emplace_back(ir + 11, 0, delta(11,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 6, ir + 6, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 7, ir + 7, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 8, ir + 8, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 9, ir + 9, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 10, ir + 10, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 11, ir + 11, 1);\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\t\t\ttripletListA.emplace_back(ir + 6 , 6, 1);\n\t\t\ttripletListA.emplace_back(ir + 7 , 7, 1);\n\t\t\ttripletListA.emplace_back(ir + 8 , 8, 1);\n\t\t\ttripletListA.emplace_back(ir + 9 , 9, 1);\n\t\t\ttripletListA.emplace_back(ir + 10 , 10, 1);\n\t\t\ttripletListA.emplace_back(ir + 11 , 11, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 6 , ir + 6, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 7 , ir + 7, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 8 , ir + 8, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 9 , ir + 9, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 10 , ir + 10, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 11 , ir + 11, 10000000000000);\n\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 6 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 7 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 8 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 9 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 10 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 11 , 0, 0);\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 12);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 12 , m_poses.size() * 12);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 12 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 12 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tm_poses[i](0,3) += h_x[counter++];\n\t\t\t\t\tm_poses[i](1,3) += h_x[counter++];\n\t\t\t\t\tm_poses[i](2,3) += h_x[counter++];\n\t\t\t\t\tm_poses[i](0,0) += h_x[counter++];\n\t\t\t\t\tm_poses[i](0,1) += h_x[counter++];\n\t\t\t\t\tm_poses[i](0,2) += h_x[counter++];\n\t\t\t\t\tm_poses[i](1,0) += h_x[counter++];\n\t\t\t\t\tm_poses[i](1,1) += h_x[counter++];\n\t\t\t\t\tm_poses[i](1,2) += h_x[counter++];\n\t\t\t\t\tm_poses[i](2,0) += h_x[counter++];\n\t\t\t\t\tm_poses[i](2,1) += h_x[counter++];\n\t\t\t\t\tm_poses[i](2,2) += h_x[counter++];\n\n\t\t\t\t\torthogonalize_rotation(m_poses[i]);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing without rotation matrix parametrization finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing without rotation matrix parametrization FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'a':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\t\t\tstd::vector<TaitBryanPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_tait_bryan_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].om,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].om,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_2_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_2_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].om,\n\t\t\t\t\t\tposes[odo_edges[i].first].fi,\n\t\t\t\t\t\tposes[odo_edges[i].first].ka,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].om,\n\t\t\t\t\t\tposes[odo_edges[i].second].fi,\n\t\t\t\t\t\tposes[odo_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < loop_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_tait_bryan_wc_case1(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].om,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].om,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].om,\n\t\t\t\t\t\tposes[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].om,\n\t\t\t\t\t\tposes[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes[loop_edges[i].second].ka,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].om,\n\t\t\t\t\t\tposes[loop_edges[i].first].fi,\n\t\t\t\t\t\tposes[loop_edges[i].first].ka,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].om,\n\t\t\t\t\t\tposes[loop_edges[i].second].fi,\n\t\t\t\t\t\tposes[loop_edges[i].second].ka);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 6;\n\t\t\t\tint ic_2 = loop_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 6 , m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.om += h_x[counter++];\n\t\t\t\t\tpose.fi += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with tait bryan finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with tait bryan FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 's':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<RodriguesPose> poses;\n\t\t\tstd::vector<RodriguesPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_rodrigues_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_rodrigues_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_rodrigues_wc(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].sz);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_2_obs_eq_rodrigues_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes[odo_edges[i].second].sz,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_2_obs_eq_rodrigues_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].sx,\n\t\t\t\t\t\tposes[odo_edges[i].first].sy,\n\t\t\t\t\t\tposes[odo_edges[i].first].sz,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].sx,\n\t\t\t\t\t\tposes[odo_edges[i].second].sy,\n\t\t\t\t\t\tposes[odo_edges[i].second].sz,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0));\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 6;\n\t\t\t\tint ic_2 = odo_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < loop_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 6, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_rodrigues_wc(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].sz);\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes[loop_edges[i].second].sz,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0));\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_rodrigues_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].sx,\n\t\t\t\t\t\tposes[loop_edges[i].first].sy,\n\t\t\t\t\t\tposes[loop_edges[i].first].sz,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].sx,\n\t\t\t\t\t\tposes[loop_edges[i].second].sy,\n\t\t\t\t\t\tposes[loop_edges[i].second].sz);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 6;\n\t\t\t\tint ic_2 = loop_edges[i].second * 6;\n\n\t\t\t\tfor(size_t row = 0 ; row < 6; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,6));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,11));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 6 , m_poses.size() * 6);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 6 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 6 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tRodriguesPose pose = pose_rodrigues_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.sx += h_x[counter++];\n\t\t\t\t\tpose.sy += h_x[counter++];\n\t\t\t\t\tpose.sz += h_x[counter++];\n\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_rodrigues(pose);\n\n\t\t\t\t\tEigen::Vector3d vx(m_poses[i](0,0), m_poses[i](1,0), m_poses[i](2,0));\n\t\t\t\t\tEigen::Vector3d vy(m_poses[i](0,1), m_poses[i](1,1), m_poses[i](2,1));\n\t\t\t\t\tEigen::Vector3d vz(m_poses[i](0,2), m_poses[i](1,2), m_poses[i](2,2));\n\n\t\t\t\t\tstd::cout << std::setprecision(15);\n\t\t\t\t\tstd::cout << \"norm: \"<< vx.norm() << \" \" << vy.norm() << \" \" << vz.norm() << \" \" <<\n\t\t\t\t\t\t\tvx.dot(vy) << \" \" << vy.dot(vz) << \" \" << vx.dot(vz) << std::endl;\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with rodrigues finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with rodrigues FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t\tcase 'd':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<QuaternionPose> poses;\n\t\t\tstd::vector<QuaternionPose> poses_desired;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_quaternion_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\t\t\tfor(size_t i = 0 ; i < m_poses_desired.size(); i++){\n\t\t\t\tposes_desired.push_back(pose_quaternion_from_affine_matrix(m_poses_desired[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < odo_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 7, 1> relative_pose_measurement_odo;\n\t\t\t\trelative_pose_quaternion_wc(relative_pose_measurement_odo,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes_desired[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes_desired[odo_edges[i].second].q3);\n\n\t\t\t\tEigen::Matrix<double, 7, 1> delta;\n\t\t\t\trelative_pose_2_obs_eq_quaternion_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes[odo_edges[i].second].q3,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(6,0));\n\n\t\t\t\tEigen::Matrix<double, 7, 14, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_2_obs_eq_quaternion_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[odo_edges[i].first].px,\n\t\t\t\t\t\tposes[odo_edges[i].first].py,\n\t\t\t\t\t\tposes[odo_edges[i].first].pz,\n\t\t\t\t\t\tposes[odo_edges[i].first].q0,\n\t\t\t\t\t\tposes[odo_edges[i].first].q1,\n\t\t\t\t\t\tposes[odo_edges[i].first].q2,\n\t\t\t\t\t\tposes[odo_edges[i].first].q3,\n\t\t\t\t\t\tposes[odo_edges[i].second].px,\n\t\t\t\t\t\tposes[odo_edges[i].second].py,\n\t\t\t\t\t\tposes[odo_edges[i].second].pz,\n\t\t\t\t\t\tposes[odo_edges[i].second].q0,\n\t\t\t\t\t\tposes[odo_edges[i].second].q1,\n\t\t\t\t\t\tposes[odo_edges[i].second].q2,\n\t\t\t\t\t\tposes[odo_edges[i].second].q3,\n\t\t\t\t\t\trelative_pose_measurement_odo(0,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(1,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(2,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(3,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(4,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(5,0),\n\t\t\t\t\t\trelative_pose_measurement_odo(6,0));\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = odo_edges[i].first * 7;\n\t\t\t\tint ic_2 = odo_edges[i].second * 7;\n\n\t\t\t\tfor(size_t row = 0 ; row < 7; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 6, -jacobian(row,6));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,11));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 6, -jacobian(row,13));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\t\t\t\ttripletListB.emplace_back(ir + 6, 0, delta(6,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 6, ir + 6, 1);\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < loop_edges.size(); i++){\n\t\t\t\tEigen::Matrix<double, 7, 1> relative_pose_measurement_loop;\n\t\t\t\trelative_pose_quaternion_wc(relative_pose_measurement_loop,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes_desired[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].px,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].py,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes_desired[loop_edges[i].second].q3);\n\n\t\t\t\tEigen::Matrix<double, 7, 1> delta;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc(\n\t\t\t\t\t\tdelta,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes[loop_edges[i].second].q3,\n\t\t\t\t\t\trelative_pose_measurement_loop(0,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(1,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(2,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(3,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(4,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(5,0),\n\t\t\t\t\t\trelative_pose_measurement_loop(6,0));\n\n\t\t\t\tEigen::Matrix<double, 7, 14, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_quaternion_wc_jacobian(jacobian,\n\t\t\t\t\t\tposes[loop_edges[i].first].px,\n\t\t\t\t\t\tposes[loop_edges[i].first].py,\n\t\t\t\t\t\tposes[loop_edges[i].first].pz,\n\t\t\t\t\t\tposes[loop_edges[i].first].q0,\n\t\t\t\t\t\tposes[loop_edges[i].first].q1,\n\t\t\t\t\t\tposes[loop_edges[i].first].q2,\n\t\t\t\t\t\tposes[loop_edges[i].first].q3,\n\t\t\t\t\t\tposes[loop_edges[i].second].px,\n\t\t\t\t\t\tposes[loop_edges[i].second].py,\n\t\t\t\t\t\tposes[loop_edges[i].second].pz,\n\t\t\t\t\t\tposes[loop_edges[i].second].q0,\n\t\t\t\t\t\tposes[loop_edges[i].second].q1,\n\t\t\t\t\t\tposes[loop_edges[i].second].q2,\n\t\t\t\t\t\tposes[loop_edges[i].second].q3);\n\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = loop_edges[i].first * 7;\n\t\t\t\tint ic_2 = loop_edges[i].second * 7;\n\n\t\t\t\tfor(size_t row = 0 ; row < 7; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -jacobian(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -jacobian(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -jacobian(row,2));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 3, -jacobian(row,3));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 4, -jacobian(row,4));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 5, -jacobian(row,5));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 6, -jacobian(row,6));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -jacobian(row,7));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -jacobian(row,8));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -jacobian(row,9));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 3, -jacobian(row,10));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 4, -jacobian(row,11));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 5, -jacobian(row,12));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 6, -jacobian(row,13));\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta(2,0));\n\t\t\t\ttripletListB.emplace_back(ir + 3, 0, delta(3,0));\n\t\t\t\ttripletListB.emplace_back(ir + 4, 0, delta(4,0));\n\t\t\t\ttripletListB.emplace_back(ir + 5, 0, delta(5,0));\n\t\t\t\ttripletListB.emplace_back(ir + 6, 0, delta(6,0));\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 3, ir + 3, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 4, ir + 4, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 5, ir + 5, 1);\n\t\t\t\ttripletListP.emplace_back(ir + 6, ir + 6, 1);\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\t\t\ttripletListA.emplace_back(ir + 3 , 3, 1);\n\t\t\ttripletListA.emplace_back(ir + 4 , 4, 1);\n\t\t\ttripletListA.emplace_back(ir + 5 , 5, 1);\n\t\t\ttripletListA.emplace_back(ir + 6 , 6, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 3 , ir + 3, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 4 , ir + 4, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 5 , ir + 5, 10000000000000);\n\t\t\ttripletListP.emplace_back(ir + 6 , ir + 6, 10000000000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 3 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 4 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 5 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 6 , 0, 0);\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tint ic = i * 7;\n\t\t\t\tir = tripletListB.size();\n\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(m_poses[i]);\n\n\t\t\t\tdouble delta;\n\t\t\t\tquaternion_constraint(delta, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\tEigen::Matrix<double, 1, 4> jacobian;\n\t\t\t\tquaternion_constraint_jacobian(jacobian, pose.q0, pose.q1, pose.q2, pose.q3);\n\n\t\t\t\ttripletListA.emplace_back(ir, ic + 3 , -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 4 , -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 5 , -jacobian(0,2));\n\t\t\t\ttripletListA.emplace_back(ir, ic + 6 , -jacobian(0,3));\n\n\t\t\t\ttripletListP.emplace_back(ir, ir, 1000000.0);\n\n\t\t\t\ttripletListB.emplace_back(ir, 0, delta);\n\t\t\t}\n\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 7);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 7 , m_poses.size() * 7);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 7 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tfor(size_t i = 0 ; i < h_x.size(); i++){\n\t\t\t\tstd::cout << h_x[i] << std::endl;\n\t\t\t}\n\n\t\t\tif(h_x.size() == 7 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tQuaternionPose pose = pose_quaternion_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.pz += h_x[counter++];\n\t\t\t\t\tpose.q0 += h_x[counter++];\n\t\t\t\t\tpose.q1 += h_x[counter++];\n\t\t\t\t\tpose.q2 += h_x[counter++];\n\t\t\t\t\tpose.q3 += h_x[counter++];\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_quaternion(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with quaternions finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with quaternions FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"n: add noise to poses\" << std::endl;\n\tstd::cout << \"t: optimize (Tait-Bryan)\" << std::endl;\n\tstd::cout << \"r: optimize (Rodriguez)\" << std::endl;\n\tstd::cout << \"q: optimize (Quaternion)\" << std::endl;\n\tstd::cout << \"x: optimize (Without rotation matrix parametrization)\" << std::endl;\n\tstd::cout << \"a: optimize (Tait-Bryan 2)\" << std::endl;\n\tstd::cout << \"s: optimize (Rodriguez 2)\" << std::endl;\n\tstd::cout << \"d: optimize (Quaternion 2)\" << std::endl;\n\n}\n\n\n\n\n\n\n\n", "meta": {"hexsha": "bba3b74594ebc98daa98ddaac93c17564e20ec0f", "size": 97001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/c++Examples/src/relative_pose.cpp", "max_stars_repo_name": "karolmajek/observation_equations", "max_stars_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/c++Examples/src/relative_pose.cpp", "max_issues_repo_name": "karolmajek/observation_equations", "max_issues_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/c++Examples/src/relative_pose.cpp", "max_forks_repo_name": "karolmajek/observation_equations", "max_forks_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 38.6612196094, "max_line_length": 122, "alphanum_fraction": 0.6487974351, "num_tokens": 33704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.24986272117420633}}
{"text": "// Copyright 2021 Apex.AI, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//\n// Co-developed by Tier IV, Inc. and Apex.AI, Inc.\n\n/// \\copyright Copyright 2021 Apex.AI, Inc.\n/// All rights reserved.\n\n#ifndef STATE_ESTIMATION_NODES__HISTORY_HPP_\n#define STATE_ESTIMATION_NODES__HISTORY_HPP_\n\n#include <common/types.hpp>\n#include <helper_functions/mahalanobis_distance.hpp>\n#include <mpark_variant_vendor/variant.hpp>\n#include <state_estimation_nodes/steady_time_grid.hpp>\n\n#include <Eigen/Cholesky>\n#include <Eigen/Core>\n\n#include <chrono>\n#include <map>\n#include <memory>\n#include <utility>\n\nnamespace autoware\n{\nnamespace common\n{\nnamespace state_estimation\n{\n\nnamespace detail\n{\n\n///\n/// Check if the sample passes the Mahalanobis gate.\n///\n/// @param[in]  sample                     The input sample\n/// @param[in]  mean                       The mean to be compared against\n/// @param[in]  covariance                 Covariance around the given mean\n/// @param[in]  mahalanobis_threshold      The mahalanobis threshold factor\n///\n/// @tparam     kNumOfStates               Number of states in the state vector.\n///\n/// @return     True if the sample passes the gate and false otherwise.\n///\ntemplate<std::int32_t kNumOfStates>\nbool passes_mahalanobis_gate(\n  const Eigen::Matrix<common::types::float32_t, kNumOfStates, 1> & sample,\n  const Eigen::Matrix<common::types::float32_t, kNumOfStates, 1> & mean,\n  const Eigen::Matrix<common::types::float32_t, kNumOfStates, kNumOfStates> & covariance,\n  const common::types::float32_t mahalanobis_threshold)\n{\n  using Matrix = Eigen::Matrix<common::types::float32_t, kNumOfStates, kNumOfStates>;\n  const Matrix L = covariance.llt().matrixL();\n  const auto squared_mahalanobis_distance =\n    autoware::common::helper_functions::calculate_squared_mahalanobis_distance(sample, mean, L);\n  const auto squared_threshold = mahalanobis_threshold * mahalanobis_threshold;\n  return squared_mahalanobis_distance < squared_threshold;\n}\n\n}  // namespace detail\n\n/// @brief      An event to indicate a prediction step.\nstruct PredictionEvent {};\n\n///\n/// @brief      An event to reset the state of the filter.\n///\n/// @tparam     FilterT  Type of the EKF filter used to infer vector and matrix types.\n///\ntemplate<typename FilterT>\nstruct ResetEvent\n{\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  typename FilterT::State state;\n  typename FilterT::State::Matrix covariance;\n};\n\n///\n/// @brief      This class encapsulates a history of events used with EKF.\n///\n///             The class handles adding events to a history of a specified size. It models the\n///             behavior of a circular buffer, meaning that as new events come in, the oldest ones\n///             are removed. The events can be either measurement types or specific events like\n///             reset or prediction. Whenever an event is added to the middle of the history all the\n///             following events get rolled on top of this event to produce a new state.\n///\n/// @tparam     FilterT       Type of EKF filter used.\n/// @tparam     kNumOfStates  Dimensionality of the state in the filter.\n/// @tparam     EventT        A variadic template of all possible events.\n///\ntemplate<typename FilterT, typename ... EventT>\nclass History\n{\n  ///\n  /// @brief      A single entry in the history. Holds state and covariance and a variant of events.\n  ///\n  class HistoryEntry;\n  ///\n  /// @brief      A functor that handles updating the state. It is used with the variant stored\n  ///             within the HistoryEntry.\n  ///\n  class EkfStateUpdater;\n\n  /// Typedef for timestamps.\n  using Timestamp = std::chrono::system_clock::time_point;\n  /// Typedef for history map type.\n  using HistoryMap = std::multimap<Timestamp, HistoryEntry>;\n\npublic:\n  ///\n  /// @brief      Construct history from a filter pointer with a specific size.\n  ///\n  /// @param      filter                 The filter pointer to be used internally.\n  /// @param[in]  max_history_size       The maximum history size.\n  /// @param[in]  mahalanobis_threshold  The mahalanobis threshold\n  ///\n  explicit History(\n    FilterT & filter,\n    const std::size_t max_history_size,\n    const common::types::float32_t mahalanobis_threshold)\n  : m_filter{filter},\n    m_max_history_size{max_history_size},\n    m_mahalanobis_threshold{mahalanobis_threshold} {}\n\n  ///\n  /// @brief      Add an event to history. If it is added to the middle the following ones are\n  ///             automatically replayed on top of it.\n  ///\n  /// @param[in]  timestamp  The timestamp of the event.\n  /// @param[in]  entry      The entry to be added to history.\n  ///\n  void emplace_event(const Timestamp & timestamp, const HistoryEntry & entry);\n  /// @brief      Check if the history is empty.\n  inline bool empty() const noexcept {return m_history.empty();}\n  /// @brief      Get size of history.\n  inline std::size_t size() const noexcept {return m_history.size();}\n  /// @brief      Get last timestamp in history.\n  inline const Timestamp & get_last_timestamp() const noexcept {return m_history.rbegin()->first;}\n  /// @brief      Get last event in history.\n  inline const HistoryEntry & get_last_event() const noexcept {return m_history.rbegin()->second;}\n  /// @brief      Get the filter as a const ref.\n  const FilterT & get_filter() const noexcept {return m_filter;}\n  /// @brief      Get the filter.\n  FilterT & get_filter() noexcept {return m_filter;}\n\nprivate:\n  ///\n  /// @brief      If the history is too large, drop the oldest event from it.\n  ///\n  inline void drop_oldest_event_if_needed()\n  {\n    if ((m_history.size() >= m_max_history_size) && (m_max_history_size > 0U)) {\n      (void) m_history.erase(m_history.begin());\n    }\n  }\n\n  ///\n  /// @brief      Update all the following events as their state is based on the current one.\n  ///\n  /// @param[in]  start_iter  The current iterator with the new state.\n  ///\n  void update_impacted_events(const typename HistoryMap::iterator & start_iter);\n\n  HistoryMap m_history{};  ///< history of events.\n  FilterT & m_filter{};  ///< pointer to the filter implementation.\n  std::size_t m_max_history_size{};  ///< Maximum number of events in history.\n  common::types::float32_t m_mahalanobis_threshold{};  ///< Mahalanobis distance threshold.\n};\n\ntemplate<typename FilterT, typename ... EventT>\nclass History<FilterT, EventT...>::HistoryEntry\n{\npublic:\n  // cppcheck-suppress unknownMacro  // cppcheck seems to be confused due to lots of templates.\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  template<typename SingleEventT>\n  // cppcheck-suppress noExplicitConstructor; Conversion to the variant type takes place.\n  HistoryEntry(const SingleEventT & event) : m_event {event} {}\n\n  /// @brief      Update the stored state.\n  void update_stored_state(const typename FilterT::State & state) noexcept\n  {\n    m_stored_state = state;\n  }\n  /// @brief      Get the stored state.\n  const typename FilterT::State & stored_state() const noexcept {return m_stored_state;}\n  /// @brief      Set the stored covariance.\n  void update_stored_covariance(const typename FilterT::State::Matrix & covariance) noexcept\n  {\n    m_stored_covariance = covariance;\n  }\n  /// @brief      Get the stored covariance.\n  const typename FilterT::State::Matrix & stored_covariance() const noexcept\n  {\n    return m_stored_covariance;\n  }\n  /// @brief      Get the event stored in this history entry.\n  const mpark::variant<EventT...> & event() const {return m_event;}\n\nprivate:\n  /// State stored in this entry.\n  typename FilterT::State m_stored_state{};\n  /// Covariance stored in this entry.\n  typename FilterT::State::Matrix m_stored_covariance{FilterT::State::Matrix::Zero()};\n  /// Event stored in this history entry.\n  mpark::variant<EventT...> m_event;\n};\n\ntemplate<typename FilterT, typename ... EventT>\nclass History<FilterT, EventT...>::EkfStateUpdater\n{\npublic:\n  explicit EkfStateUpdater(\n    FilterT & filter,\n    const common::types::float32_t mahalanobis_threshold,\n    const std::chrono::system_clock::duration & dt = std::chrono::milliseconds{0})\n    : m_filter {filter}, m_mahalanobis_threshold{mahalanobis_threshold}, m_dt{dt}\n  {}\n\n  ///\n  /// @brief      An operator that passes a measurement event to the filter implementation.\n  ///\n  /// @param[in]  event         A measurement event.\n  ///\n  /// @tparam     MeasurementT  Type of measurement event. Can be any measurement type.\n  ///\n  template<typename MeasurementT>\n  void operator()(const MeasurementT & event)\n  {\n    m_filter.predict(m_dt);\n    // TODO(#887): I see a couple of ways to check mahalanobis distance in case the measurement does\n    // not cover the full state. Here I upscale it to the full state, copying the values of the\n    // current state for ones missing in the observation. We can alternatively apply the H matrix\n    // and only compute the distance in the measurement world. Don't really know which one is best\n    // here.\n    const auto measurement_as_state = event.map_into(m_filter.state());\n    if (!detail::passes_mahalanobis_gate(\n        measurement_as_state.vector(),\n        m_filter.state().vector(),\n        m_filter.covariance(),\n        m_mahalanobis_threshold)) {return;}\n    m_filter.correct(event);\n  }\n\n  /// @brief      An operator that resets the state of the filter implementation.\n  void operator()(const ResetEvent<FilterT> & event)\n  {\n    m_filter.reset(event.state, event.covariance);\n  }\n\n  /// @brief      An operator that applies the prediction event to the filter implementation.\n  void operator()(const PredictionEvent &)\n  {\n    m_filter.predict(m_dt);\n  }\n\nprivate:\n  FilterT & m_filter{};  ///< A pointer to the filter implementation.\n  common::types::float32_t m_mahalanobis_threshold{};  ///< Mahalanobis distance threshold.\n  std::chrono::system_clock::duration m_dt{};  ///< Current time step.\n};\n\ntemplate<typename FilterT, typename ... EventT>\nvoid History<FilterT, EventT...>::emplace_event(\n  const Timestamp & timestamp, const HistoryEntry & entry)\n{\n  drop_oldest_event_if_needed();\n  const auto iterator_to_inserted_position = m_history.emplace(timestamp, entry);\n  update_impacted_events(iterator_to_inserted_position);\n}\n\ntemplate<typename FilterT, typename ... EventT>\nvoid History<FilterT, EventT...>::update_impacted_events(\n  const typename HistoryMap::iterator & start_iter)\n{\n  Timestamp previous_timestamp{};\n  if (start_iter == m_history.begin()) {\n    if (!mpark::holds_alternative<ResetEvent<FilterT>>(start_iter->second.event())) {\n      (void) m_history.erase(start_iter);\n      throw std::runtime_error(\n              \"Non-reset event inserted to the beginning of history. This might \"\n              \"happen if a very old event is inserted into the queue. Consider \"\n              \"increasing the queue size or debug program latencies.\");\n    }\n  } else {\n    const auto prev_iter = std::prev(start_iter);\n    previous_timestamp = prev_iter->first;\n    const auto & prev_entry = prev_iter->second;\n    m_filter.reset(\n      typename FilterT::State{prev_entry.stored_state()},\n      prev_entry.stored_covariance());\n  }\n  for (auto iter = start_iter; iter != m_history.end(); ++iter) {\n    const auto current_timestamp = iter->first;\n    auto & entry = iter->second;\n    mpark::visit(\n      EkfStateUpdater{m_filter, m_mahalanobis_threshold, current_timestamp - previous_timestamp},\n      entry.event());\n    entry.update_stored_state(m_filter.state());\n    entry.update_stored_covariance(m_filter.covariance());\n    previous_timestamp = iter->first;\n  }\n}\n\n\n}  // namespace state_estimation\n}  // namespace common\n}  // namespace autoware\n\n\n#endif  // STATE_ESTIMATION_NODES__HISTORY_HPP_\n", "meta": {"hexsha": "64779ecef3d5a8defbe0324d99c17fb5d89f0d4b", "size": 12139, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/state_estimation_nodes/include/state_estimation_nodes/history.hpp", "max_stars_repo_name": "ruvus/auto", "max_stars_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:14:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T10:03:08.000Z", "max_issues_repo_path": "src/common/state_estimation_nodes/include/state_estimation_nodes/history.hpp", "max_issues_repo_name": "ruvus/auto", "max_issues_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2021-10-29T22:00:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T20:56:34.000Z", "max_forks_repo_path": "src/common/state_estimation_nodes/include/state_estimation_nodes/history.hpp", "max_forks_repo_name": "ruvus/auto", "max_forks_repo_head_hexsha": "25ae62d6e575cae40212356eed43ec3e76e9a13e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2021-05-29T14:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T10:03:09.000Z", "avg_line_length": 37.236196319, "max_line_length": 100, "alphanum_fraction": 0.7032704506, "num_tokens": 2877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24981693979236788}}
{"text": "#include \"step_crawling.h\"\n\n#include <fstream>\n#include <cstdlib>  // For srand() and rand()\n\n#include <Eigen/SVD>\n#include <RobotUtilities/utilities.h>\n#include <RobotUtilities/TimerLinux.h>\n\n#include <solvehfvc.h>\n\n#define PI 3.14159265\n\nusing namespace RUT;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\nusing Eigen::Vector2d;\nusing Eigen::Matrix2d;\n\nbool StepCrawlingTaskServer::initStepCrawlingTaskServer() {\n  ROS_INFO_STREAM(\"Step crawling server is starting\");\n  if (_ros_handle_p == nullptr) {\n    ROS_ERROR_STREAM(\"[StepCrawlingTaskServer] You must call .init() before .initStepCrawlingTaskServer().\");\n    exit(1);\n  }\n\n  _ros_handle_p->param(string(\"/task/v_singular_value_threshold\"),\n      _v_singular_value_threshold, 0.1);\n  _ros_handle_p->param(string(\"/task/f_singular_value_threshold\"),\n      _f_singular_value_threshold, 0.1);\n  if (!_ros_handle_p->hasParam(\"/task/v_singular_value_threshold\"))\n      ROS_WARN_STREAM(\"Parameter [/task/v_singular_value_threshold] not found\");\n  if (!_ros_handle_p->hasParam(\"/task/f_singular_value_threshold\"))\n      ROS_WARN_STREAM(\"Parameter [/task/f_singular_value_threshold] not found\");\n\n  _ros_handle_p->param(std::string(\"/task/time_step\"), _kTimeStepSec, 0.1);\n  if (!_ros_handle_p->hasParam(\"/task/time_step\"))\n    ROS_WARN_STREAM(\"Parameter [/task/time_step] not found\");\n  _ros_handle_p->param(std::string(\"/task/number_of_time_steps\"), _kNumOfTimeSteps, 30);\n  if (!_ros_handle_p->hasParam(\"/task/number_of_time_steps\"))\n    ROS_WARN_STREAM(\"Parameter [/task/number_of_time_steps] not found\");\n  _ros_handle_p->param(std::string(\"/task/goal_veloicty_meter\"), _kGoalVelocityM, 0.01);\n  if (!_ros_handle_p->hasParam(\"/task/goal_veloicty_meter\"))\n    ROS_WARN_STREAM(\"Parameter [/task/goal_veloicty_meter] not found\");\n  _ros_handle_p->param(std::string(\"/task/engage_step_length\"), _kEngageStepLength, 0.001);\n  if (!_ros_handle_p->hasParam(\"/task/engage_step_length\"))\n    ROS_WARN_STREAM(\"Parameter [/task/engage_step_length] not found\");\n  _ros_handle_p->param(std::string(\"/task/min_normal_force\"), _kNormalForceMin, 4.0);\n  if (!_ros_handle_p->hasParam(\"/task/min_normal_force\"))\n    ROS_WARN_STREAM(\"Parameter [/task/min_normal_force] not found\");\n\n  _F_W(0) = 0;\n  _F_W(1) = 1;\n  _F_W(2) = 0;\n\n  return true;\n}\n\nbool StepCrawlingTaskServer::hostServices() {\n  // --------------------------------------------------------\n  // Establish Services\n  // --------------------------------------------------------\n  ros::ServiceServer reset_service            = _ros_handle_p->advertiseService(\"reset\", &StepCrawlingTaskServer::SrvReset, (RobotBridge*)this);\n  ros::ServiceServer move_tool_service        = _ros_handle_p->advertiseService(\"move_tool\", &StepCrawlingTaskServer::SrvMoveTool, (RobotBridge*)this);\n  ros::ServiceServer move_until_touch_service = _ros_handle_p->advertiseService(\"move_until_touch\", &StepCrawlingTaskServer::SrvMoveUntilTouch, (RobotBridge*)this);\n  ros::ServiceServer get_pose_service         = _ros_handle_p->advertiseService(\"get_pose\", &StepCrawlingTaskServer::SrvGetPose, (RobotBridge*)this);\n  ros::ServiceServer execute_task_service     = _ros_handle_p->advertiseService(\"execute_task\", &StepCrawlingTaskServer::SrvExecuteTask, this);\n\n  cout << endl << \"[StepCrawlingTaskServer] Service servers are listening..\" << endl;\n  ros::spin();\n\n  ROS_INFO_STREAM(endl << \"[StepCrawlingTaskServer] Service servers stopped.\" << endl);\n  return true;\n}\n\nbool StepCrawlingTaskServer::SrvExecuteTask(std_srvs::Empty::Request  &req,\n    std_srvs::Empty::Response &res) {\n  _controller.reset();\n\n  if (_controller._f_queue.size() < 50) {\n    cout << \"Run update() for \" << _main_loop_rate << \" frames:\" << endl;\n    // first, run update for 1s to populate the data deques\n    ros::Rate pub_rate(_main_loop_rate);\n    for (int i = 0; i < _main_loop_rate; ++i) {\n      bool b_is_safe = _controller.update();\n      // if(!b_is_safe) break;\n      pub_rate.sleep();\n    }\n    cout << \"Done.\" << endl;\n  }\n\n  Timer timer;\n  std::srand(std::time(0));\n  MatrixXd f_data, v_data;\n  for (int fr = 0; fr < _kNumOfTimeSteps; ++fr) {\n    timer.tic();\n    /**\n     * Estimate Natural Constraints\n     */\n    // get the weighted data\n    f_data = MatrixXd::Zero(3, _controller._f_queue.size());\n    v_data = MatrixXd::Zero(3, _controller._v_queue.size());\n    for (int i = 0; i < _controller._f_queue.size(); ++i)\n      f_data.col(i) = _controller._f_queue[i].head(3) * _controller._f_weights[i];\n    for (int i = 0; i < _controller._v_queue.size(); ++i)\n      v_data.col(i) = _controller._v_queue[i].head(3) * _controller._v_weights[i];\n\n    // SVD on velocity data\n    Eigen::JacobiSVD<MatrixXd> svd_v(v_data.transpose(), Eigen::ComputeThinV);\n    VectorXd sigma_v = svd_v.singularValues();\n    int DimV = 0;\n    for (int i = 0; i < 3; ++i)\n      if (sigma_v(i) > _v_singular_value_threshold) DimV ++;\n\n    // get a basis for row space of velocity data\n    MatrixXd rowspace_v = svd_v.matrixV().leftCols(DimV);\n\n    // filter out force data that:\n    //    1. has a small weight\n    std::vector<int> f_id;\n    for (int i = 0; i < f_data.cols(); ++i) {\n      double length = f_data.col(i).norm();\n      if (length > 1.5) { // weighted length in newton\n        f_id.push_back(i);\n      }\n    }\n\n    double pose_fb[7], pose_set[7];\n    _robot.getPose(pose_fb);\n    Matrix3d R_WT = quat2SO3(pose_fb[3], pose_fb[4], pose_fb[5], pose_fb[6]);\n\n    int f_data_length = f_id.size();\n    if (f_data_length < 5) {\n      ROS_WARN_STREAM(\"[StepCrawlingTaskServer] lacks significant force data\");\n      // stabilize onto the surface.\n      Vector3d F_T = R_WT.transpose() * _F_W.normalized() * _kNormalForceMin;\n      double force_temp[6] = {- F_T(0), - F_T(1), - F_T(2), 0, 0, 0};\n      _controller.ExecuteHFVC(6, 0, Matrix6d::Identity(), pose_fb, force_temp,\n          HS_CONTINUOUS, _main_loop_rate, 10*_kTimeStepSec);\n      continue;\n    }\n    int DimF = 1;\n\n    MatrixXd f_data_filtered = MatrixXd::Zero(3, f_data_length);\n    for (int i = 0; i < f_data_length; ++i)\n      f_data_filtered.col(i) = f_data.col(f_id[i]);\n\n    MatrixXd f_data_selected;\n    // SVD on filtered force data, get the prime direction\n    Eigen::JacobiSVD<MatrixXd> svd_f(f_data_filtered.transpose(), Eigen::ComputeThinV);\n    Vector3d F_T = svd_f.matrixV().col(0).normalized();\n    // check sign\n    MatrixXd check_sum = F_T.transpose() * f_data_filtered * VectorXd::Ones(f_data_length);\n    if (check_sum(0,0) < 0) F_T = -F_T;\n    MatrixXd Nf = F_T.transpose();\n\n    /**\n     * Infer Goal\n     */\n    // Transform Nf to world frame\n    _F_W = R_WT * F_T;\n    cout << \"F_W: \" << _F_W.transpose().format(MatlabFmt) << endl;\n    Vector3d goal_direction_W = _F_W.cross(-Vector3d::UnitX());\n    cout << \"goal_direction_W: \" << goal_direction_W.transpose().format(MatlabFmt) << endl;\n\n    MatrixXd G = MatrixXd::Zero(1, 3);\n    VectorXd b_G = VectorXd::Zero(1);\n    G = (R_WT.transpose() * goal_direction_W).transpose();\n    b_G(0) = _kGoalVelocityM;\n\n    /**\n     * Do Hybrid Servoing (3D)\n     */\n    HFVC action;\n    int kDimActualized      = 3;\n    int kDimUnActualized    = 0;\n    int kDimSlidingFriction = 0;\n    int kNumSeeds           = 3;\n    int kDimLambda          = 1;\n    int kPrintLevel         = 2;\n\n    VectorXd F = VectorXd::Zero(3);\n    MatrixXd Aeq(0, 1+3); // dummy\n    VectorXd beq(0); // dummy\n    MatrixXd A = MatrixXd::Zero(1, 1 + 3);\n    VectorXd b_A = VectorXd::Zero(1);\n    A(0, 0) = -1;\n    b_A(0) = -_kNormalForceMin;\n\n    cout << \"Nf: \" << Nf.format(MatlabFmt) << endl;\n    cout << \"G: \" << G.format(MatlabFmt) << endl;\n    cout << \"b_G: \" << b_G.format(MatlabFmt) << endl;\n    cout << \"F: \" << F.format(MatlabFmt) << endl;\n    cout << \"Aeq: \" << Aeq.format(MatlabFmt) << endl;\n    cout << \"beq: \" << beq.format(MatlabFmt) << endl;\n    cout << \"A: \" << A.format(MatlabFmt) << endl;\n    cout << \"b_A: \" << b_A.format(MatlabFmt) << endl;\n\n    solvehfvc(Nf, G, b_G, F, Aeq, beq, A, b_A,\n      kDimActualized, kDimUnActualized,\n      kDimSlidingFriction, kDimLambda,\n      kNumSeeds, kPrintLevel,\n      &action);\n\n    double computation_time_ms = timer.toc();\n\n    /**\n     * Execute the hybrid action (6D)\n     */\n    Vector6d v_Tr = Vector6d::Zero();\n    for (int i = 0; i < action.n_av; ++i)  v_Tr(i+action.n_af) = action.w_av(i);\n\n    // Tool frame velocity\n    Matrix6d R_a;\n    R_a << action.R_a, Matrix3d::Zero(), Matrix3d::Zero(), Matrix3d::Identity();\n    Matrix6d R_a_inv = R_a.inverse();\n    Vector6d v_T = R_a_inv*v_Tr;\n\n    // World frame velocity, set pose\n    _robot.getPose(pose_fb);\n    Matrix4d SE3_WT_fb = posemm2SE3(pose_fb);\n    Matrix6d Adj_WT = SE32Adj(SE3_WT_fb);\n    Vector6d v_W = Adj_WT*v_T;\n    Matrix4d SE3_WT_command;\n    SE3_WT_command = SE3_WT_fb + wedge6(v_W)*SE3_WT_fb*_kTimeStepSec;\n    SE32Posemm(SE3_WT_command, pose_set);\n\n    // Tool frame force\n    Vector6d force_Tr_set = Vector6d::Zero();\n    for (int i = 0; i < action.n_af; ++i)  force_Tr_set[i] = action.eta_af(i);\n    Vector6d force_T = R_a_inv*force_Tr_set;\n    Matrix6d Adj_TW = SE32Adj(SE3Inv(SE3_WT_fb));\n\n    Vector6d force_W = Adj_TW.transpose() * force_T;\n    cout << \"force_Tr_set: \" << force_Tr_set.transpose().format(MatlabFmt) << endl;\n    cout << \"force_T: \" << force_T.transpose().format(MatlabFmt) << endl;\n    printf(\"V in world: %.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\n\", v_W[0], v_W[1],\n        v_W[2],v_W[3],v_W[4],v_W[5]);\n    printf(\"F in world: %.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\t%.3f\\n\", force_W[0],\n        force_W[1], force_W[2],force_W[3],force_W[4],force_W[5]);\n    cout << \"Computation Time: \" << computation_time_ms << endl << endl;\n\n    if (fr == _kNumOfTimeSteps-1) {\n      // print to file\n      std::ofstream fp;\n      // f_queue\n      fp.open(_task_data_file_path + \"f_queue.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      for (int i = 0; i < _controller._f_queue.size(); ++i) {\n        stream_array_in(fp, _controller._f_queue[i].data(), 3);\n        fp << endl;\n      }\n      fp.close();\n      // v_queue\n      fp.open(_task_data_file_path + \"v_queue.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      for (int i = 0; i < _controller._v_queue.size(); ++i) {\n        stream_array_in(fp, _controller._v_queue[i].data(), 3);\n        fp << endl;\n      }\n      fp.close();\n      // f_weights\n      fp.open(_task_data_file_path + \"f_weights.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      for (int i = 0; i < _controller._f_weights.size(); ++i)\n        fp << _controller._f_weights[i] << endl;\n      fp.close();\n\n      // v_weights\n      fp.open(_task_data_file_path + \"v_weights.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      for (int i = 0; i < _controller._v_weights.size(); ++i)\n        fp << _controller._v_weights[i] << endl;\n      fp.close();\n\n      // f_data_filtered\n      fp.open(_task_data_file_path + \"f_data_filtered.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      fp << f_data_filtered.transpose() << endl;\n      fp.close();\n      // f_data_selected\n      fp.open(_task_data_file_path + \"f_data_selected.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      fp << f_data_selected.transpose() << endl;\n      fp.close();\n      // others\n      fp.open(_task_data_file_path + \"process.txt\");\n      if (!fp) {\n        cerr << \"Unable to open file to write.\";\n        return false;\n      }\n      fp << DimV << endl << DimF << endl;\n      stream_array_in(fp, v_T.data(), 3);\n      fp << endl;\n      stream_array_in(fp, force_T.data(), 3);\n      fp.close();\n    }\n\n    if (std::isnan(force_Tr_set[0])) {\n      cout << \"================== NaN =====================\" << endl;\n      cout << \"Press Enter to continue..\" << endl;\n      getchar();\n    }\n\n    cout << \"Current pose: \" << pose_fb[0] << \", \" << pose_fb[1] << \", \" << pose_fb[2] << endl;\n    cout << \"Set pose: \" << pose_set[0] << \", \" << pose_set[1] << \", \" << pose_set[2] << endl;\n    cout << \"Press Enter to begin motion: \\n\";\n    // getchar();\n    // cout << \"motion begins:\" << endl;\n    _controller.ExecuteHFVC(action.n_af, action.n_av+3,\n        R_a, pose_set, force_Tr_set.data(),\n        HS_CONTINUOUS, _main_loop_rate, _kTimeStepSec);\n\n  } // end for\n  return true;\n}", "meta": {"hexsha": "5ddf9ace8e9073f28dcb7557fb8a4e61865ed058", "size": 12494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experiments/step_crawling/cpp_robot_server/step_crawling.cpp", "max_stars_repo_name": "yifan-hou/hybrid_servoing", "max_stars_repo_head_hexsha": "4d3a2cc047a3bad5ded19934247b5ab5e598f911", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-04-15T04:45:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-13T03:28:46.000Z", "max_issues_repo_path": "experiments/step_crawling/cpp_robot_server/step_crawling.cpp", "max_issues_repo_name": "yifan-hou/hybrid_servoing", "max_issues_repo_head_hexsha": "4d3a2cc047a3bad5ded19934247b5ab5e598f911", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experiments/step_crawling/cpp_robot_server/step_crawling.cpp", "max_forks_repo_name": "yifan-hou/hybrid_servoing", "max_forks_repo_head_hexsha": "4d3a2cc047a3bad5ded19934247b5ab5e598f911", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1845238095, "max_line_length": 164, "alphanum_fraction": 0.6246198175, "num_tokens": 3730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24981693395037463}}
{"text": "#include <iostream>\n#include <boost/program_options.hpp>\n#include <boost/filesystem.hpp>\n#include \"bhtsne.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\nnamespace fsys = boost::filesystem;\n\nint main(int argc, char **argv) {\n  // Declare the supported options\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help\", \"produce help message\")\n    (\"input-P\", po::value<string>()->value_name(\"FILE\")->default_value(\"P.dat\"), \"name of binary input file containing P matrix (see ComputeP)\")\n    (\"out-dir\", po::value<string>()->value_name(\"DIR\")->default_value(\"out\"), \"where to create output files; directory will be created if it does not exist\")\n    (\"out-dim\", po::value<int>()->value_name(\"NUM\")->default_value(2), \"number of output dimensions\")\n    (\"max-iter\", po::value<int>()->value_name(\"NUM\")->default_value(1000), \"maximum number of iterations\")\n    (\"rand-seed\", po::value<int>()->value_name(\"NUM\")->default_value(-1), \"seed for random number generator; to use current time as seed set it to -1\")\n    (\"theta\", po::value<double>()->value_name(\"NUM\")->default_value(0.5, \"0.5\"), \"a value between 0 and 1 that controls the accuracy-efficiency tradeoff in SPTree for gradient computation; 0 means exact\")\n    (\"learn-rate\", po::value<double>()->value_name(\"NUM\")->default_value(200, \"200\"), \"learning rate for gradient steps\")\n    (\"mom-init\", po::value<double>()->value_name(\"NUM\")->default_value(0.5, \"0.5\"), \"initial momentum between 0 and 1\")\n    (\"mom-final\", po::value<double>()->value_name(\"NUM\")->default_value(0.8, \"0.8\"), \"final momentum between 0 and 1 (switch point controlled by --mom-switch-iter)\")\n    (\"mom-switch-iter\", po::value<int>()->value_name(\"NUM\")->default_value(250), \"duration (number of iterations) of initial momentum\")\n    (\"early-exag-iter\", po::value<int>()->value_name(\"NUM\")->default_value(250), \"duration (number of iterations) of early exaggeration\")\n    (\"skip-random-init\", po::bool_switch()->default_value(false), \"skip random initialization\")\n    (\"batch-frac\", po::value<double>()->value_name(\"NUM\"), \"what fraction of points to update for each iteration\")\n    (\"cache-iter\", po::value<int>()->value_name(\"NUM\")->default_value(INT_MAX, \"INT_MAX\"), \"After every NUM iterations, write intermediary embeddings to disk. Final embedding is always reported.\")\n  ;\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).\n                options(desc).run(), vm);\n  po::notify(vm);    \n  \n  if (vm.count(\"help\")) {\n    cout << \"Usage: RunBhtsne [options]\" << endl;\n    cout << desc << \"\\n\";\n    return 1;\n  }\n\n  string infile = vm[\"input-P\"].as<string>();\n  string outdir = vm[\"out-dir\"].as<string>();\n\n  fsys::path dir(outdir);\n  if (fsys::is_directory(dir)) {\n    cout << \"Error: Output directory already exists\" << endl;\n    return 1;\n  }\n  if (fsys::create_directory(dir)) {\n    cout << \"Output directory created: \" << outdir << endl; \n  }\n\n  TSNE *tsne = new TSNE();\n\n  fsys::path paramfile = dir;\n  paramfile /= \"param.txt\";\n  ofstream ofs(paramfile.string().c_str());\n  ofs << \"input-P: \" << infile << endl;\n  ofs << \"out-dir: \" << fsys::canonical(dir).string() << endl;\n\n  int no_dims = vm[\"out-dim\"].as<int>(); ofs << \"out-dim: \" << no_dims << endl;\n  double theta = vm[\"theta\"].as<double>(); ofs << \"theta: \" << theta << endl;\n  int rand_seed = vm[\"rand-seed\"].as<int>(); ofs << \"rand-seed: \" << rand_seed << endl;\n  bool skip_random_init = vm[\"skip-random-init\"].as<bool>(); ofs << \"skip-random-init: \" << skip_random_init << endl;\n  int max_iter = vm[\"max-iter\"].as<int>(); ofs << \"max-iter: \" << max_iter << endl;\n  int stop_lying_iter = vm[\"early-exag-iter\"].as<int>(); ofs << \"early-exag-iter: \" << stop_lying_iter << endl;\n  int mom_switch_iter = vm[\"mom-switch-iter\"].as<int>(); ofs << \"mom-switch-iter: \" << mom_switch_iter << endl;\n  double momentum = vm[\"mom-init\"].as<double>(); ofs << \"mom-init: \" << momentum << endl;\n  double final_momentum = vm[\"mom-final\"].as<double>(); ofs << \"mom-final: \" << final_momentum << endl;\n  double eta = vm[\"learn-rate\"].as<double>(); ofs << \"learn-rate: \" << eta << endl;\n  tsne->CACHE_ITER = vm[\"cache-iter\"].as<int>(); ofs << \"cache-iter: \" << tsne->CACHE_ITER << endl;\n\n  if (vm.count(\"batch-frac\")) {\n    double batch_frac = vm[\"batch-frac\"].as<double>(); ofs << \"batch-frac: \" << batch_frac << endl;\n    tsne->BATCH_FLAG = true;\n    tsne->BATCH_FRAC = batch_frac;\n  }\n\n  ofs.close();\n\n  printf(\"Loading input similarities...\\n\");\n  int N;\n  unsigned int *row_P;\n  unsigned int *col_P;\n  double *val_P;\n  if (!tsne->load_P(infile, N, &row_P, &col_P, &val_P)) {\n    cout << \"Error: failed to load P from \" << infile << endl;\n    return 1;\n  }\n\n  double *Y = (double *)malloc(N * no_dims * sizeof(double));\n  if (Y == NULL) {\n    cout << \"Error: Memory allocation for the output failed\" << endl;\n    return 1;\n  }\n\n  if (!tsne->run(N, row_P, col_P, val_P, Y, no_dims, theta, rand_seed,\n           skip_random_init, max_iter, stop_lying_iter, mom_switch_iter,\n           momentum, final_momentum, eta, dir)) {\n    return 1;\n  }\n\n  free(row_P);\n  free(col_P);\n  free(val_P);\n  free(Y);\n  delete(tsne);\n\n  cout << \"Done\" << endl;\n\n  return 0;\n}\n", "meta": {"hexsha": "b9962d1a4d9527ff4b1d0a8e58aac0237beed46e", "size": 5201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RunBhtsne.cpp", "max_stars_repo_name": "hhcho/netsne", "max_stars_repo_head_hexsha": "d928b7f514efe68e91984ba0a51428a30beed647", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2018-04-15T18:25:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-05T13:30:37.000Z", "max_issues_repo_path": "RunBhtsne.cpp", "max_issues_repo_name": "hhcho/netsne", "max_issues_repo_head_hexsha": "d928b7f514efe68e91984ba0a51428a30beed647", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-24T01:38:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-06T00:48:47.000Z", "max_forks_repo_path": "RunBhtsne.cpp", "max_forks_repo_name": "hhcho/netsne", "max_forks_repo_head_hexsha": "d928b7f514efe68e91984ba0a51428a30beed647", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-23T13:10:43.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-28T18:00:59.000Z", "avg_line_length": 45.6228070175, "max_line_length": 204, "alphanum_fraction": 0.6408383003, "num_tokens": 1442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2497560182328059}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_STRATEGIES_STRATEGY_TRANSFORM_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_STRATEGY_TRANSFORM_HPP\r\n\r\n#include <cstddef>\r\n#include <cmath>\r\n#include <functional>\r\n\r\n#include <boost/numeric/conversion/cast.hpp>\r\n\r\n#include <boost/geometry/algorithms/convert.hpp>\r\n#include <boost/geometry/arithmetic/arithmetic.hpp>\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/core/radian_access.hpp>\r\n#include <boost/geometry/core/coordinate_dimension.hpp>\r\n#include <boost/geometry/strategies/transform.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/select_coordinate_type.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace transform\r\n{\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail\r\n{\r\n\r\ntemplate\r\n<\r\n    typename Src, typename Dst,\r\n    std::size_t D, std::size_t N,\r\n    template <typename> class F\r\n>\r\nstruct transform_coordinates\r\n{\r\n    template <typename T>\r\n    static inline void transform(Src const& source, Dst& dest, T value)\r\n    {\r\n        typedef typename select_coordinate_type<Src, Dst>::type coordinate_type;\r\n\r\n        F<coordinate_type> function;\r\n        set<D>(dest, boost::numeric_cast<coordinate_type>(function(get<D>(source), value)));\r\n        transform_coordinates<Src, Dst, D + 1, N, F>::transform(source, dest, value);\r\n    }\r\n};\r\n\r\ntemplate\r\n<\r\n    typename Src, typename Dst,\r\n    std::size_t N,\r\n    template <typename> class F\r\n>\r\nstruct transform_coordinates<Src, Dst, N, N, F>\r\n{\r\n    template <typename T>\r\n    static inline void transform(Src const& , Dst& , T )\r\n    {\r\n    }\r\n};\r\n\r\n} // namespace detail\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n\r\n/*!\r\n    \\brief Transformation strategy to copy one point to another using assignment operator\r\n    \\ingroup transform\r\n    \\tparam P point type\r\n */\r\ntemplate <typename P>\r\nstruct copy_direct\r\n{\r\n    inline bool apply(P const& p1, P& p2) const\r\n    {\r\n        p2 = p1;\r\n        return true;\r\n    }\r\n};\r\n\r\n/*!\r\n    \\brief Transformation strategy to do copy a point, copying per coordinate.\r\n    \\ingroup transform\r\n    \\tparam P1 first point type\r\n    \\tparam P2 second point type\r\n */\r\ntemplate <typename P1, typename P2>\r\nstruct copy_per_coordinate\r\n{\r\n    inline bool apply(P1 const& p1, P2& p2) const\r\n    {\r\n        // Defensive check, dimensions are equal, selected by specialization\r\n        assert_dimension_equal<P1, P2>();\r\n\r\n        geometry::convert(p1, p2);\r\n        return true;\r\n    }\r\n};\r\n\r\n\r\n/*!\r\n    \\brief Transformation strategy to go from degree to radian and back\r\n    \\ingroup transform\r\n    \\tparam P1 first point type\r\n    \\tparam P2 second point type\r\n    \\tparam F additional functor to divide or multiply with d2r\r\n */\r\ntemplate <typename P1, typename P2, template <typename> class F>\r\nstruct degree_radian_vv\r\n{\r\n    inline bool apply(P1 const& p1, P2& p2) const\r\n    {\r\n        // Spherical coordinates always have 2 coordinates measured in angles\r\n        // The optional third one is distance/height, provided in another strategy\r\n        // Polar coordinates having one angle, will be also in another strategy\r\n        assert_dimension<P1, 2>();\r\n        assert_dimension<P2, 2>();\r\n\r\n        detail::transform_coordinates<P1, P2, 0, 2, F>::transform(p1, p2, math::d2r);\r\n        return true;\r\n    }\r\n};\r\n\r\ntemplate <typename P1, typename P2, template <typename> class F>\r\nstruct degree_radian_vv_3\r\n{\r\n    inline bool apply(P1 const& p1, P2& p2) const\r\n    {\r\n        assert_dimension<P1, 3>();\r\n        assert_dimension<P2, 3>();\r\n\r\n        detail::transform_coordinates<P1, P2, 0, 2, F>::transform(p1, p2, math::d2r);\r\n        // Copy height or other third dimension\r\n        set<2>(p2, get<2>(p1));\r\n        return true;\r\n    }\r\n};\r\n\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail\r\n{\r\n\r\n    /// Helper function for conversion, phi/theta are in radians\r\n    template <typename P, typename T, typename R>\r\n    inline void spherical_polar_to_cartesian(T phi, T theta, R r, P& p)\r\n    {\r\n        assert_dimension<P, 3>();\r\n\r\n        // http://en.wikipedia.org/wiki/List_of_canonical_coordinate_transformations#From_spherical_coordinates\r\n        // http://www.vias.org/comp_geometry/math_coord_convert_3d.htm\r\n        // https://moodle.polymtl.ca/file.php/1183/Autres_Documents/Derivation_for_Spherical_Co-ordinates.pdf\r\n        // http://en.citizendium.org/wiki/Spherical_polar_coordinates\r\n        \r\n        // Phi = first, theta is second, r is third, see documentation on cs::spherical\r\n\r\n        // (calculations are splitted to implement ttmath)\r\n\r\n        T r_sin_theta = r;\r\n        T r_cos_theta = r;\r\n        r_sin_theta *= sin(theta);\r\n        r_cos_theta *= cos(theta);\r\n\r\n        set<0>(p, r_sin_theta * cos(phi));\r\n        set<1>(p, r_sin_theta * sin(phi));\r\n        set<2>(p, r_cos_theta);\r\n    }\r\n    \r\n    /// Helper function for conversion, lambda/delta (lon lat) are in radians\r\n    template <typename P, typename T, typename R>\r\n    inline void spherical_equatorial_to_cartesian(T lambda, T delta, R r, P& p)\r\n    {\r\n        assert_dimension<P, 3>();\r\n\r\n        // http://mathworld.wolfram.com/GreatCircle.html\r\n        // http://www.spenvis.oma.be/help/background/coortran/coortran.html WRONG\r\n        \r\n        T r_cos_delta = r;\r\n        T r_sin_delta = r;\r\n        r_cos_delta *= cos(delta);\r\n        r_sin_delta *= sin(delta);\r\n\r\n        set<0>(p, r_cos_delta * cos(lambda));\r\n        set<1>(p, r_cos_delta * sin(lambda));\r\n        set<2>(p, r_sin_delta);\r\n    }\r\n    \r\n\r\n    /// Helper function for conversion\r\n    template <typename P, typename T>\r\n    inline bool cartesian_to_spherical2(T x, T y, T z, P& p)\r\n    {\r\n        assert_dimension<P, 2>();\r\n\r\n        // http://en.wikipedia.org/wiki/List_of_canonical_coordinate_transformations#From_Cartesian_coordinates\r\n\r\n#if defined(BOOST_GEOMETRY_TRANSFORM_CHECK_UNIT_SPHERE)\r\n        // TODO: MAYBE ONLY IF TO BE CHECKED?\r\n        T const r = /*sqrt not necessary, sqrt(1)=1*/ (x * x + y * y + z * z);\r\n\r\n        // Unit sphere, so r should be 1\r\n        if (geometry::math::abs(r - 1.0) > T(1e-6))\r\n        {\r\n            return false;\r\n        }\r\n        // end todo\r\n#endif\r\n\r\n        set_from_radian<0>(p, atan2(y, x));\r\n        set_from_radian<1>(p, acos(z));\r\n        return true;\r\n    }\r\n    \r\n    template <typename P, typename T>\r\n    inline bool cartesian_to_spherical_equatorial2(T x, T y, T z, P& p)\r\n    {\r\n        assert_dimension<P, 2>();\r\n\r\n        set_from_radian<0>(p, atan2(y, x));\r\n        set_from_radian<1>(p, asin(z));\r\n        return true;\r\n    }\r\n    \r\n\r\n    template <typename P, typename T>\r\n    inline bool cartesian_to_spherical3(T x, T y, T z, P& p)\r\n    {\r\n        assert_dimension<P, 3>();\r\n\r\n        // http://en.wikipedia.org/wiki/List_of_canonical_coordinate_transformations#From_Cartesian_coordinates\r\n        T const r = sqrt(x * x + y * y + z * z);\r\n        set<2>(p, r);\r\n        set_from_radian<0>(p, atan2(y, x));\r\n        if (r > 0.0)\r\n        {\r\n            set_from_radian<1>(p, acos(z / r));\r\n            return true;\r\n        }\r\n        return false;\r\n    }\r\n\r\n\ttemplate <typename P, typename T>\r\n\tinline bool cartesian_to_spherical_equatorial3(T x, T y, T z, P& p)\r\n\t{\r\n\t\tassert_dimension<P, 3>();\r\n\r\n\t\t// http://en.wikipedia.org/wiki/List_of_canonical_coordinate_transformations#From_Cartesian_coordinates\r\n\t\tT const r = sqrt(x * x + y * y + z * z);\r\n\t\tset<2>(p, r);\r\n\t\tset_from_radian<0>(p, atan2(y, x));\r\n\t\tif (r > 0.0)\r\n\t\t{\r\n\t\t\tset_from_radian<1>(p, asin(z / r));\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n} // namespace detail\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n\r\n/*!\r\n    \\brief Transformation strategy for 2D spherical (phi,theta) to 3D cartesian (x,y,z)\r\n    \\details on Unit sphere\r\n    \\ingroup transform\r\n    \\tparam P1 first point type\r\n    \\tparam P2 second point type\r\n */\r\ntemplate <typename P1, typename P2>\r\nstruct from_spherical_polar_2_to_cartesian_3\r\n{\r\n    inline bool apply(P1 const& p1, P2& p2) const\r\n    {\r\n        assert_dimension<P1, 2>();\r\n        detail::spherical_polar_to_cartesian(get_as_radian<0>(p1), get_as_radian<1>(p1), 1.0, p2);\r\n        return true;\r\n    }\r\n};\r\n\r\ntemplate <typename P1, typename P2>\r\nstruct from_spherical_equatorial_2_to_cartesian_3\r\n{\r\n    inline bool apply(P1 const& p1, P2& p2) const\r\n    {\r\n        assert_dimension<P1, 2>();\r\n        detail::spherical_equatorial_to_cartesian(get_as_radian<0>(p1), get_as_radian<1>(p1), 1.0, p2);\r\n        return true;\r\n    }\r\n};\r\n\r\n\r\n/*!\r\n    \\brief Transformation strategy for 3D spherical (phi,theta,r) to 3D cartesian (x,y,z)\r\n    \\ingroup transform\r\n    \\tparam P1 first point type\r\n    \\tparam P2 second point type\r\n */\r\ntemplate <typename P1, typename P2>\r\nstruct from_spherical_polar_3_to_cartesian_3\r\n{\r\n    inline bool apply(P1 const& p1, P2& p2) const\r\n    {\r\n        assert_dimension<P1, 3>();\r\n        detail::spherical_polar_to_cartesian(\r\n                    get_as_radian<0>(p1), get_as_radian<1>(p1), get<2>(p1), p2);\r\n        return true;\r\n    }\r\n};\r\n\r\ntemplate <typename P1, typename P2>\r\nstruct from_spherical_equatorial_3_to_cartesian_3\r\n{\r\n    inline bool apply(P1 const& p1, P2& p2) const\r\n    {\r\n        assert_dimension<P1, 3>();\r\n        detail::spherical_equatorial_to_cartesian(\r\n                    get_as_radian<0>(p1), get_as_radian<1>(p1), get<2>(p1), p2);\r\n        return true;\r\n    }\r\n};\r\n\r\n\r\n/*!\r\n    \\brief Transformation strategy for 3D cartesian (x,y,z) to 2D spherical (phi,theta)\r\n    \\details on Unit sphere\r\n    \\ingroup transform\r\n    \\tparam P1 first point type\r\n    \\tparam P2 second point type\r\n    \\note If x,y,z point is not lying on unit sphere, transformation will return false\r\n */\r\ntemplate <typename P1, typename P2>\r\nstruct from_cartesian_3_to_spherical_polar_2\r\n{\r\n    inline bool apply(P1 const& p1, P2& p2) const\r\n    {\r\n        assert_dimension<P1, 3>();\r\n        return detail::cartesian_to_spherical2(get<0>(p1), get<1>(p1), get<2>(p1), p2);\r\n    }\r\n};\r\n\r\ntemplate <typename P1, typename P2>\r\nstruct from_cartesian_3_to_spherical_equatorial_2\r\n{\r\n    inline bool apply(P1 const& p1, P2& p2) const\r\n    {\r\n        assert_dimension<P1, 3>();\r\n        return detail::cartesian_to_spherical_equatorial2(get<0>(p1), get<1>(p1), get<2>(p1), p2);\r\n    }\r\n};\r\n\r\n\r\n/*!\r\n    \\brief Transformation strategy for 3D cartesian (x,y,z) to 3D spherical (phi,theta,r)\r\n    \\ingroup transform\r\n    \\tparam P1 first point type\r\n    \\tparam P2 second point type\r\n */\r\ntemplate <typename P1, typename P2>\r\nstruct from_cartesian_3_to_spherical_polar_3\r\n{\r\n    inline bool apply(P1 const& p1, P2& p2) const\r\n    {\r\n        assert_dimension<P1, 3>();\r\n        return detail::cartesian_to_spherical3(get<0>(p1), get<1>(p1), get<2>(p1), p2);\r\n    }\r\n};\r\n\r\ntemplate <typename P1, typename P2>\r\nstruct from_cartesian_3_to_spherical_equatorial_3\r\n{\r\n\tinline bool apply(P1 const& p1, P2& p2) const\r\n\t{\r\n\t\tassert_dimension<P1, 3>();\r\n\t\treturn detail::cartesian_to_spherical_equatorial3(get<0>(p1), get<1>(p1), get<2>(p1), p2);\r\n\t}\r\n};\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\nnamespace services\r\n{\r\n\r\n/// Specialization for same coordinate system family, same system, same dimension, same point type, can be copied\r\ntemplate <typename CoordSysTag, typename CoordSys, std::size_t D, typename P>\r\nstruct default_strategy<CoordSysTag, CoordSysTag, CoordSys, CoordSys, D, D, P, P>\r\n{\r\n    typedef copy_direct<P> type;\r\n};\r\n\r\n/// Specialization for same coordinate system family and system, same dimension, different point type, copy per coordinate\r\ntemplate <typename CoordSysTag, typename CoordSys, std::size_t D, typename P1, typename P2>\r\nstruct default_strategy<CoordSysTag, CoordSysTag, CoordSys, CoordSys, D, D, P1, P2>\r\n{\r\n    typedef copy_per_coordinate<P1, P2> type;\r\n};\r\n\r\n/// Specialization to transform from degree to radian for any coordinate system / point type combination\r\ntemplate <typename CoordSysTag, template<typename> class CoordSys, typename P1, typename P2>\r\nstruct default_strategy<CoordSysTag, CoordSysTag, CoordSys<degree>, CoordSys<radian>, 2, 2, P1, P2>\r\n{\r\n    typedef degree_radian_vv<P1, P2, std::multiplies> type;\r\n};\r\n\r\n/// Specialization to transform from radian to degree for any coordinate system / point type combination\r\ntemplate <typename CoordSysTag, template<typename> class CoordSys, typename P1, typename P2>\r\nstruct default_strategy<CoordSysTag, CoordSysTag, CoordSys<radian>, CoordSys<degree>, 2, 2, P1, P2>\r\n{\r\n    typedef degree_radian_vv<P1, P2, std::divides> type;\r\n};\r\n\r\n\r\n/// Specialization degree->radian in 3D\r\ntemplate <typename CoordSysTag, template<typename> class CoordSys, typename P1, typename P2>\r\nstruct default_strategy<CoordSysTag, CoordSysTag, CoordSys<degree>, CoordSys<radian>, 3, 3, P1, P2>\r\n{\r\n    typedef degree_radian_vv_3<P1, P2, std::multiplies> type;\r\n};\r\n\r\n/// Specialization radian->degree in 3D\r\ntemplate <typename CoordSysTag, template<typename> class CoordSys, typename P1, typename P2>\r\nstruct default_strategy<CoordSysTag, CoordSysTag, CoordSys<radian>, CoordSys<degree>, 3, 3, P1, P2>\r\n{\r\n    typedef degree_radian_vv_3<P1, P2, std::divides> type;\r\n};\r\n\r\n/// Specialization to transform from unit sphere(phi,theta) to XYZ\r\ntemplate <typename CoordSys1, typename CoordSys2, typename P1, typename P2>\r\nstruct default_strategy<spherical_polar_tag, cartesian_tag, CoordSys1, CoordSys2, 2, 3, P1, P2>\r\n{\r\n    typedef from_spherical_polar_2_to_cartesian_3<P1, P2> type;\r\n};\r\n\r\n/// Specialization to transform from sphere(phi,theta,r) to XYZ\r\ntemplate <typename CoordSys1, typename CoordSys2, typename P1, typename P2>\r\nstruct default_strategy<spherical_polar_tag, cartesian_tag, CoordSys1, CoordSys2, 3, 3, P1, P2>\r\n{\r\n    typedef from_spherical_polar_3_to_cartesian_3<P1, P2> type;\r\n};\r\n\r\ntemplate <typename CoordSys1, typename CoordSys2, typename P1, typename P2>\r\nstruct default_strategy<spherical_equatorial_tag, cartesian_tag, CoordSys1, CoordSys2, 2, 3, P1, P2>\r\n{\r\n    typedef from_spherical_equatorial_2_to_cartesian_3<P1, P2> type;\r\n};\r\n\r\ntemplate <typename CoordSys1, typename CoordSys2, typename P1, typename P2>\r\nstruct default_strategy<spherical_equatorial_tag, cartesian_tag, CoordSys1, CoordSys2, 3, 3, P1, P2>\r\n{\r\n    typedef from_spherical_equatorial_3_to_cartesian_3<P1, P2> type;\r\n};\r\n\r\n/// Specialization to transform from XYZ to unit sphere(phi,theta)\r\ntemplate <typename CoordSys1, typename CoordSys2, typename P1, typename P2>\r\nstruct default_strategy<cartesian_tag, spherical_polar_tag, CoordSys1, CoordSys2, 3, 2, P1, P2>\r\n{\r\n    typedef from_cartesian_3_to_spherical_polar_2<P1, P2> type;\r\n};\r\n\r\ntemplate <typename CoordSys1, typename CoordSys2, typename P1, typename P2>\r\nstruct default_strategy<cartesian_tag, spherical_equatorial_tag, CoordSys1, CoordSys2, 3, 2, P1, P2>\r\n{\r\n    typedef from_cartesian_3_to_spherical_equatorial_2<P1, P2> type;\r\n};\r\n\r\n/// Specialization to transform from XYZ to sphere(phi,theta,r)\r\ntemplate <typename CoordSys1, typename CoordSys2, typename P1, typename P2>\r\nstruct default_strategy<cartesian_tag, spherical_polar_tag, CoordSys1, CoordSys2, 3, 3, P1, P2>\r\n{\r\n    typedef from_cartesian_3_to_spherical_polar_3<P1, P2> type;\r\n};\r\ntemplate <typename CoordSys1, typename CoordSys2, typename P1, typename P2>\r\nstruct default_strategy<cartesian_tag, spherical_equatorial_tag, CoordSys1, CoordSys2, 3, 3, P1, P2>\r\n{\r\n\ttypedef from_cartesian_3_to_spherical_equatorial_3<P1, P2> type;\r\n};\r\n\r\n\r\n} // namespace services\r\n\r\n\r\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\n\r\n\r\n}} // namespace strategy::transform\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_STRATEGY_TRANSFORM_HPP\r\n", "meta": {"hexsha": "d51b5e8bf9c9e050ad381d022173c6b8fc38e09c", "size": 16187, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/geometry/strategies/strategy_transform.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "master/core/third/boost/geometry/strategies/strategy_transform.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/geometry/strategies/strategy_transform.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 32.0534653465, "max_line_length": 123, "alphanum_fraction": 0.6738740965, "num_tokens": 4397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2497560182328059}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Ilias Khairullin <ilias@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_PUBKEY_MODES_CREATE_KEY_HPP\n#define CRYPTO3_PUBKEY_MODES_CREATE_KEY_HPP\n\n#include <type_traits>\n#include <iterator>\n\n#include <boost/assert.hpp>\n#include <boost/concept_check.hpp>\n\n#include <boost/range/concepts.hpp>\n\n#include <nil/crypto3/pubkey/secret_sharing.hpp>\n#include <nil/crypto3/pubkey/dkg.hpp>\n\n#include <nil/crypto3/pubkey/private_key.hpp>\n\n#include <nil/crypto3/pubkey/algorithm/deal_shares.hpp>\n#include <nil/crypto3/pubkey/algorithm/deal_share.hpp>\n#include <nil/crypto3/pubkey/algorithm/verify_share.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        //\n        // CoeffsIterator - coefficients of polynomial\n        //\n        template<typename Scheme, typename CoeffsIterator, typename Number,\n                 typename SecretSharingScheme = typename pubkey::private_key<Scheme>::sss_public_key_group_type,\n                 typename ValueType = typename std::iterator_traits<CoeffsIterator>::value_type,\n                 typename SecretSharingScheme::template check_coeff_type<ValueType> = true>\n        inline typename std::enable_if<\n            std::is_same<pubkey::shamir_sss<typename SecretSharingScheme::group_type>, SecretSharingScheme>::value ||\n                std::is_same<pubkey::feldman_sss<typename SecretSharingScheme::group_type>, SecretSharingScheme>::value,\n            std::pair<pubkey::public_key<Scheme>, std::vector<pubkey::private_key<Scheme>>>>::type\n            create_key(CoeffsIterator first, CoeffsIterator last, Number n) {\n            BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<CoeffsIterator>));\n\n            using privkeys_type = std::vector<pubkey::private_key<Scheme>>;\n            using sss_no_key_ops_type = typename pubkey::private_key<Scheme>::sss_public_key_no_key_ops_type;\n\n            typename sss_no_key_ops_type::shares_type shares =\n                nil::crypto3::deal_shares<SecretSharingScheme>(first, last, n);\n            privkeys_type privkeys;\n            for (const auto &s : shares) {\n                privkeys.emplace_back(s);\n            }\n            auto PK = pubkey::public_key<Scheme>(sss_no_key_ops_type::get_public_coeffs(first, last).front());\n            return std::make_pair(PK, privkeys);\n        }\n\n        //\n        // CoeffsRange - coefficients of polynomial\n        //\n        template<typename Scheme, typename CoeffsRange, typename Number,\n                 typename SecretSharingScheme = typename pubkey::private_key<Scheme>::sss_public_key_group_type,\n                 typename ValueType = typename std::iterator_traits<typename CoeffsRange::iterator>::value_type,\n                 typename SecretSharingScheme::template check_coeff_type<ValueType> = true>\n        inline typename std::enable_if<\n            std::is_same<pubkey::shamir_sss<typename SecretSharingScheme::group_type>, SecretSharingScheme>::value ||\n                std::is_same<pubkey::feldman_sss<typename SecretSharingScheme::group_type>, SecretSharingScheme>::value,\n            std::pair<pubkey::public_key<Scheme>, std::vector<pubkey::private_key<Scheme>>>>::type\n            create_key(const CoeffsRange &r, Number n) {\n            BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<const CoeffsRange>));\n            return create_key<Scheme>(r.begin(), r.end(), n);\n        }\n\n        //\n        // InputIterator - public representation values of polynomial's coefficients\n        //\n        template<typename Scheme, typename CoeffsIterator, typename Number,\n                 typename SecretSharingScheme = typename pubkey::private_key<Scheme>::sss_public_key_group_type,\n                 typename ValueType = typename std::iterator_traits<CoeffsIterator>::value_type,\n                 typename SecretSharingScheme::template check_public_coeff_type<ValueType> = true>\n        inline typename std::enable_if<\n            std::is_same<pubkey::feldman_sss<typename SecretSharingScheme::group_type>, SecretSharingScheme>::value,\n            pubkey::private_key<Scheme>>::type\n            create_key(CoeffsIterator first,\n                       CoeffsIterator last,\n                       typename SecretSharingScheme::share_type share,\n                       Number n) {\n            BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<CoeffsIterator>));\n\n            using privkey_type = pubkey::private_key<Scheme>;\n\n            assert(static_cast<bool>(nil::crypto3::verify_share<SecretSharingScheme>(first, last, share)));\n            return privkey_type(share);\n        }\n\n        //\n        // PublicCoeffsRange - public representation values of polynomial's coefficients\n        //\n        template<typename Scheme, typename PublicCoeffsRange, typename Number,\n                 typename SecretSharingScheme = typename pubkey::private_key<Scheme>::sss_public_key_group_type,\n                 typename ValueType = typename std::iterator_traits<typename PublicCoeffsRange::iterator>::value_type,\n                 typename SecretSharingScheme::template check_public_coeff_type<ValueType> = true>\n        inline typename std::enable_if<\n            std::is_same<pubkey::feldman_sss<typename SecretSharingScheme::group_type>, SecretSharingScheme>::value,\n            pubkey::private_key<Scheme>>::type\n            create_key(const PublicCoeffsRange &r, typename SecretSharingScheme::share_type share, Number n) {\n            BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<const PublicCoeffsRange>));\n            return create_key<Scheme>(r.begin(), r.end(), share, n);\n        }\n\n        //\n        // CoeffsIterator - coefficients of polynomial\n        // InputIterator2 - participants' weights\n        //\n        template<typename Scheme, typename CoeffsIterator, typename WeightsIterator,\n                 typename SecretSharingScheme = typename pubkey::private_key<Scheme>::sss_public_key_group_type,\n                 typename ValueType1 = typename std::iterator_traits<CoeffsIterator>::value_type,\n                 typename ValueType2 = typename std::iterator_traits<WeightsIterator>::value_type,\n                 typename SecretSharingScheme::template check_coeff_type<ValueType1> = true,\n                 typename SecretSharingScheme::template check_weight_type<ValueType2> = true>\n        inline typename std::enable_if<\n            std::is_same<pubkey::weighted_shamir_sss<typename SecretSharingScheme::group_type>,\n                         SecretSharingScheme>::value,\n            std::pair<pubkey::public_key<Scheme>, std::vector<pubkey::private_key<Scheme>>>>::type\n            create_key(CoeffsIterator first1, CoeffsIterator last1, WeightsIterator first2, WeightsIterator last2) {\n            BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<CoeffsIterator>));\n            BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<WeightsIterator>));\n\n            using privkeys_type = std::vector<pubkey::private_key<Scheme>>;\n            using sss_no_key_ops_type = typename pubkey::private_key<Scheme>::sss_public_key_no_key_ops_type;\n\n            typename sss_no_key_ops_type::shares_type shares = nil::crypto3::deal_shares<SecretSharingScheme>(\n                first1, last1, first2, last2, std::distance(first2, last2));\n            privkeys_type privkeys;\n            for (const auto &s : shares) {\n                privkeys.emplace_back(s, std::distance(first1, last1));\n            }\n            auto PK = pubkey::public_key<Scheme>(sss_no_key_ops_type::get_public_coeffs(first1, last1).front(),\n                                                 std::distance(first2, last2));\n            return std::make_pair(PK, privkeys);\n        }\n\n        //\n        // CoeffsRange - coefficients of polynomial\n        // WeightsRange - participants' weights\n        //\n        template<typename Scheme, typename CoeffsRange, typename WeightsRange,\n                 typename SecretSharingScheme = typename pubkey::private_key<Scheme>::sss_public_key_group_type,\n                 typename ValueType1 = typename std::iterator_traits<typename CoeffsRange::iterator>::value_type,\n                 typename ValueType2 = typename std::iterator_traits<typename WeightsRange::iterator>::value_type,\n                 typename SecretSharingScheme::template check_coeff_type<ValueType1> = true,\n                 typename SecretSharingScheme::template check_weight_type<ValueType2> = true>\n        inline typename std::enable_if<\n            std::is_same<pubkey::weighted_shamir_sss<typename SecretSharingScheme::group_type>,\n                         SecretSharingScheme>::value,\n            std::pair<pubkey::public_key<Scheme>, std::vector<pubkey::private_key<Scheme>>>>::type\n            create_key(const CoeffsRange &r1, const WeightsRange &r2) {\n            BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<const CoeffsRange>));\n            BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<const WeightsRange>));\n            return create_key<Scheme>(r1.begin(), r1.end(), r2.begin(), r2.end());\n        }\n\n        //\n        // PublicCoeffsIterators - public representation values of polynomials' coefficients of other participants\n        // SharesIterator - shares generated by other participants\n        //\n        template<typename Scheme, typename PublicCoeffsIterators, typename SharesIterator, typename Number,\n                 typename SecretSharingScheme = typename pubkey::private_key<Scheme>::sss_public_key_group_type,\n                 typename ValueType1 = typename std::iterator_traits<\n                     typename std::iterator_traits<PublicCoeffsIterators>::value_type::iterator>::value_type,\n                 typename ValueType2 = typename std::iterator_traits<SharesIterator>::value_type,\n                 typename SecretSharingScheme::template check_public_coeff_type<ValueType1> = true,\n                 typename SecretSharingScheme::template check_share_type<ValueType2> = true>\n        inline typename std::enable_if<\n            std::is_same<pubkey::pedersen_dkg<typename SecretSharingScheme::group_type>, SecretSharingScheme>::value,\n            std::pair<pubkey::public_key<Scheme>, pubkey::private_key<Scheme>>>::type\n            create_key(PublicCoeffsIterators first1, PublicCoeffsIterators last1, SharesIterator first2,\n                       SharesIterator last2, Number n) {\n            BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<PublicCoeffsIterators>));\n            BOOST_RANGE_CONCEPT_ASSERT((\n                boost::SinglePassRangeConcept<const typename std::iterator_traits<PublicCoeffsIterators>::value_type>));\n            BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<SharesIterator>));\n            assert(n == std::distance(first1, last1));\n            assert(n == std::distance(first2, last2));\n\n            using privkey_type = pubkey::private_key<Scheme>;\n\n            auto it_coeffs = first1;\n            auto it_share = first2;\n            typename SecretSharingScheme::public_element_type PK = SecretSharingScheme::public_element_type::zero();\n            while (it_coeffs != last1 && it_share != last2) {\n                assert(static_cast<bool>(nil::crypto3::verify_share<SecretSharingScheme>(*it_coeffs, *it_share)));\n                PK = PK + *((*it_coeffs).begin());\n                it_coeffs++;\n                it_share++;\n            }\n            return std::make_pair(pubkey::public_key<Scheme>(PK),\n                                  privkey_type(static_cast<typename SecretSharingScheme::share_type>(\n                                      nil::crypto3::deal_share<SecretSharingScheme>(first2, last2))));\n        }\n\n        //\n        // PublicCoeffsRanges - public representation values of polynomials' coefficients of other participants\n        // SharesRange - shares generated by other participants\n        //\n        template<typename Scheme, typename PublicCoeffsRanges, typename SharesRange, typename Number,\n                 typename SecretSharingScheme = typename pubkey::private_key<Scheme>::sss_public_key_group_type,\n                 typename ValueType1 = typename std::iterator_traits<typename std::iterator_traits<\n                     typename PublicCoeffsRanges::iterator>::value_type::iterator>::value_type,\n                 typename ValueType2 = typename std::iterator_traits<typename SharesRange::iterator>::value_type,\n                 typename SecretSharingScheme::template check_public_coeff_type<ValueType1> = true,\n                 typename SecretSharingScheme::template check_share_type<ValueType2> = true>\n        inline typename std::enable_if<\n            std::is_same<pubkey::pedersen_dkg<typename SecretSharingScheme::group_type>, SecretSharingScheme>::value,\n            std::pair<pubkey::public_key<Scheme>, pubkey::private_key<Scheme>>>::type\n            create_key(const PublicCoeffsRanges &r, const SharesRange &shares, Number n) {\n            BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<const PublicCoeffsRanges>));\n            BOOST_RANGE_CONCEPT_ASSERT(\n                (boost::SinglePassRangeConcept<\n                    const typename std::iterator_traits<typename PublicCoeffsRanges::iterator>::value_type>));\n            BOOST_RANGE_CONCEPT_ASSERT((boost::SinglePassRangeConcept<const SharesRange>));\n            return create_key<Scheme>(r.begin(), r.end(), shares.begin(), shares.end(), n);\n        }\n    }    // namespace crypto3\n}    // namespace nil\n\n#endif    // include guard", "meta": {"hexsha": "d263bb84c815c4258438eab36b38aa8651551d8b", "size": 14703, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/pubkey/modes/algorithm/create_key.hpp", "max_stars_repo_name": "JasonCoombs/crypto3-pkmodes", "max_stars_repo_head_hexsha": "0dc8defe1a2199cb798df943b8665ec1a53c295b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/pubkey/modes/algorithm/create_key.hpp", "max_issues_repo_name": "JasonCoombs/crypto3-pkmodes", "max_issues_repo_head_hexsha": "0dc8defe1a2199cb798df943b8665ec1a53c295b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-04-01T15:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-20T03:45:24.000Z", "max_forks_repo_path": "include/nil/crypto3/pubkey/modes/algorithm/create_key.hpp", "max_forks_repo_name": "JasonCoombs/crypto3-pkmodes", "max_forks_repo_head_hexsha": "0dc8defe1a2199cb798df943b8665ec1a53c295b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:40:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T03:13:02.000Z", "avg_line_length": 60.2581967213, "max_line_length": 120, "alphanum_fraction": 0.6729919064, "num_tokens": 3005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24972471497828685}}
{"text": "// This file is part of snark, a generic and flexible library for robotics research\n// Copyright (c) 2011 The University of Sydney\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n// 1. Redistributions of source code must retain the above copyright\n//    notice, this list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright\n//    notice, this list of conditions and the following disclaimer in the\n//    documentation and/or other materials provided with the distribution.\n// 3. Neither the name of the University of Sydney nor the\n//    names of its contributors may be used to endorse or promote products\n//    derived from this software without specific prior written permission.\n//\n// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE\n// GRANTED BY THIS LICENSE.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT\n// HOLDERS AND CONTRIBUTORS \\\"AS IS\\\" AND ANY EXPRESS OR IMPLIED\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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\n// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n// IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"convert.h\"\n#include \"traits.h\"\n\n#include <comma/csv/stream.h>\n#include <Eigen/Dense>\n\nnamespace {\n\n    using namespace snark::imaging;\n\n    typedef std::vector< double > channels;\n\n    // conversion does not have to be a linear operation, but many are; these function simplify setting up such conversions\n    /*\n      commented-out to remove a compiler warning (-Wunused-function)\n    channels linear_combination( const channels & i, const Eigen::Vector3d & before, const Eigen::Matrix3d & m, const Eigen::Vector3d & after )\n    {\n        channels t = { i[0] + before(0), i[1] + before(1), i[2] + before(2) };\n        return channels( { m(0,0) * t[0] + m(0,1) * t[1] + m(0,2) * t[2] + after(0)\n                         , m(1,0) * t[0] + m(1,1) * t[1] + m(1,2) * t[2] + after(1)\n                         , m(2,0) * t[0] + m(2,1) * t[1] + m(2,2) * t[2] + after(2) } );\n    }\n\n    channels linear_combination( const channels & i, const Eigen::Vector3d & before, const Eigen::Matrix3d & m )\n    {\n        channels t = { i[0] + before(0), i[1] + before(1), i[2] + before(2) };\n        return channels( { m(0,0) * t[0] + m(0,1) * t[1] + m(0,2) * t[2]\n                         , m(1,0) * t[0] + m(1,1) * t[1] + m(1,2) * t[2]\n                         , m(2,0) * t[0] + m(2,1) * t[1] + m(2,2) * t[2] } );\n    }\n    */\n    channels linear_combination( const channels & i, const Eigen::Matrix3d & m, const Eigen::Vector3d & after )\n    {\n        return channels( { m(0,0) * i[0] + m(0,1) * i[1] + m(0,2) * i[2] + after(0)\n                         , m(1,0) * i[0] + m(1,1) * i[1] + m(1,2) * i[2] + after(1)\n                         , m(2,0) * i[0] + m(2,1) * i[1] + m(2,2) * i[2] + after(2) } );\n    }\n\n    channels linear_combination( const channels & i, const Eigen::Matrix3d & m )\n    {\n        return channels( { m(0,0) * i[0] + m(0,1) * i[1] + m(0,2) * i[2]\n                         , m(1,0) * i[0] + m(1,1) * i[1] + m(1,2) * i[2]\n                         , m(2,0) * i[0] + m(2,1) * i[1] + m(2,2) * i[2] } );\n    }\n\n    typedef std::function< channels ( const channels & p ) > C;\n    // TODO:\n    // - outr can be duplicate to the explicit convert call in convert (or the other way around); sort out\n    typedef std::pair< colorspace::cspace, range > half_key_t;\n    typedef std::pair< half_key_t, half_key_t > conversion_key_t;\n    typedef std::map< conversion_key_t, C > conversion_map_t;\n\n    C scale( range inr, range outr )\n    {\n        double uin, lin, uout, lout;\n        switch ( inr ) {\n            case ub : uin = limits< ub >::upper(); lin = limits< ub >::lower(); break;\n            case uw : uin = limits< uw >::upper(); lin = limits< uw >::lower(); break;\n            case ui : uin = limits< ui >::upper(); lin = limits< ui >::lower(); break;\n            case f  : uin = limits< f  >::upper(); lin = limits< f  >::lower(); break;\n            case d  : uin = limits< d  >::upper(); lin = limits< d  >::lower(); break;\n            default:\n                COMMA_THROW( comma::exception, \"unknown input range '\" << stringify::from( inr ) << \"'\" );\n        }\n\n        switch ( outr ) {\n            case ub : uout = limits< ub >::upper(); lout = limits< ub >::lower(); break;\n            case uw : uout = limits< uw >::upper(); lout = limits< uw >::lower(); break;\n            case ui : uout = limits< ui >::upper(); lout = limits< ui >::lower(); break;\n            case f  : uout = limits< f  >::upper(); lout = limits< f  >::lower(); break;\n            case d  : uout = limits< d  >::upper(); lout = limits< d  >::lower(); break;\n            default:\n                COMMA_THROW( comma::exception, \"unknown output range '\" << stringify::from( outr ) << \"'\" );\n        }\n\n        double factor = ( uout - lout ) / ( uin - lin );\n        return [ factor, lin, lout ]( const channels & rhs ){\n            return channels( { factor * ( rhs[0] - lin ) + lout\n                             , factor * ( rhs[1] - lin ) + lout\n                             , factor * ( rhs[2] - lin ) + lout } ); };\n    }\n\n    const conversion_map_t & conversions()\n    {\n        static conversion_map_t m;\n        m[ std::make_pair( std::make_pair( colorspace::rgb, ub ), std::make_pair( colorspace::rgb,   ub ) ) ] =\n            []( const channels & i ){ return linear_combination( i, (Eigen::Matrix3d() << 1, 0, 0, 0, 1, 0, 0, 0, 1).finished() ); };\n        m[ std::make_pair( std::make_pair( colorspace::rgb, f  ), std::make_pair( colorspace::ypbpr, f  ) ) ] =\n            []( const channels & i ){ return linear_combination( i, (Eigen::Matrix3d() << 0.299, 0.587, 0.114, -0.168736, -0.331264, 0.5, 0.5, -0.418688, -0.081312).finished(), (Eigen::Vector3d() << 0, 0.5, 0.5).finished() ); };\n        m[ std::make_pair( std::make_pair( colorspace::rgb, d  ), std::make_pair( colorspace::ypbpr, d  ) ) ] = m[ std::make_pair( std::make_pair( colorspace::rgb, f  ), std::make_pair( colorspace::ypbpr, f  ) ) ];\n        m[ std::make_pair( std::make_pair( colorspace::rgb, f  ), std::make_pair( colorspace::ypbpr, d  ) ) ] = m[ std::make_pair( std::make_pair( colorspace::rgb, f  ), std::make_pair( colorspace::ypbpr, f  ) ) ];\n        m[ std::make_pair( std::make_pair( colorspace::rgb, d  ), std::make_pair( colorspace::ypbpr, f  ) ) ] = m[ std::make_pair( std::make_pair( colorspace::rgb, f  ), std::make_pair( colorspace::ypbpr, f  ) ) ];\n        m[ std::make_pair( std::make_pair( colorspace::rgb, f  ), std::make_pair( colorspace::ycbcr, ub ) ) ] =\n            []( const channels & i ){ return linear_combination( i, (Eigen::Matrix3d() << 65.481, 128.553, 24.966, -37.797, -74.203, 112.0, 112.0, -93.786, -18.214).finished(), (Eigen::Vector3d() << 16, 128, 128).finished() ); };\n        m[ std::make_pair( std::make_pair( colorspace::rgb, d  ), std::make_pair( colorspace::ycbcr, ub ) ) ] = m[ std::make_pair( std::make_pair( colorspace::rgb, f  ), std::make_pair( colorspace::ycbcr, ub ) ) ];\n        // this differs from commonly presented values, e.g., wiki@YCbCr page, that rounds numbers to 3 decimal digits\n        m[ std::make_pair( std::make_pair( colorspace::rgb, ub ), std::make_pair( colorspace::ycbcr, ub ) ) ] =\n            []( const channels & i ){ return linear_combination( i, (Eigen::Matrix3d() << 65.481, 128.553, 24.966, -37.797, -74.203, 112.0, 112.0, -93.786, -18.214).finished() / 255., (Eigen::Vector3d() << 16, 128, 128).finished() ); };\n        {\n            m[ std::make_pair( std::make_pair( colorspace::ycbcr, ub ), std::make_pair( colorspace::rgb, ub ) ) ] =\n                []( const channels & i) {\n                    return channels( { 255/219. * ( i[0] - 16 )                                               + 255/112.*0.701             * ( i[2] - 128 )\n                                     , 255/219. * ( i[0] - 16 ) - 255/112.*0.886*0.114/0.587 * ( i[1] - 128 ) - 255/112.*0.701*0.299/0.587 * ( i[2] - 128 )\n                                     , 255/219. * ( i[0] - 16 ) + 255/112.*0.886             * ( i[1] - 128 )                                               } );\n                };\n        }\n        return m;\n    }\n\n    C select( const conversion_map_t & m, const colorspace & inc, range inr, const colorspace & outc, range outr, bool recurse = true )\n    {\n        // the logic for searching for the conversion method:\n        // 0. check for non-conversions: same colorspace, different (or even same) range; handle explicitly\n        if ( inc.value == outc.value )\n        {\n            if ( inr == outr ) { return []( const channels & c ) { return c; }; }\n            return scale( inr, outr );\n        }\n        // 1. if there is a direct conversion from (inc, inr) to (outc, outr) use it (data are stored as doubles on both in and out)\n        {\n            const conversion_key_t & key = std::make_pair( std::make_pair( inc.value, inr ), std::make_pair( outc.value, outr ) );\n            conversion_map_t::const_iterator i = m.find( key );\n            if ( i != m.end() ) { return i->second; }\n        }\n        // 2. if there is a conversion from (inc, inr) to (outc, default-range-of-outc) use it, then change range of outc (chain conversions)\n        {\n            range outdef = colorspace::default_range( outc.value );\n            const conversion_key_t & key = std::make_pair( std::make_pair( inc.value, inr ), std::make_pair( outc.value, outdef ) );\n            conversion_map_t::const_iterator i = m.find( key );\n            if ( i != m.end() ) { return [ i, outdef, outr ]( const channels & c ){ return scale( outdef, outr )( i->second( c ) ); }; }\n        }\n        // 3. if there is a conversion from (inc, default-range-of-inc) to (outc, outr), use it after changing range of inc\n        {\n            range indef = colorspace::default_range( inc.value );\n            const conversion_key_t & key = std::make_pair( std::make_pair( inc.value, indef ), std::make_pair( outc.value, outr ) );\n            conversion_map_t::const_iterator i = m.find( key );\n            if ( i != m.end() ) { return [ i, inr, indef ]( const channels & c ){ return i->second( scale( inr, indef )( c ) ); }; }\n        }\n        // 4. if there is a conversion from (inc, default-range-of-inc) to (outc, default-range-of-outc), change range of inc, apply conversion, then change range of outc\n        {\n            range indef = colorspace::default_range( inc.value );\n            range outdef = colorspace::default_range( outc.value );\n            const conversion_key_t & key = std::make_pair( std::make_pair( inc.value, indef ), std::make_pair( outc.value, outdef ) );\n            conversion_map_t::const_iterator i = m.find( key );\n            if ( i != m.end() ) { return [ i, inr, indef, outdef, outr ]( const channels & c ){ return scale( outdef, outr )( i->second( scale( inr, indef )( c ) ) ); }; }\n        }\n        // 5. if there is a conversion from (inc, inr ) to (rgb, some-range-of-rgb) and also conversion from (rgb, some-range-of-rgb) to (outc, outr)\n        //    ( covering all possible intermediate conversions through a recursive call), convert through the intermediate rgb\n        {\n            if ( recurse )\n            {\n                for ( range r : { ub, f } )\n                {\n                    try {\n                        // do not stuck in infinite recursion\n                        C c0 = select( m, inc, inr, colorspace::rgb, r, false );\n                        C c1 = select( m, colorspace::rgb, r, outc, outr, false );\n                        return [ c0, c1 ]( const channels & c ){ return c1( c0( c ) ); };\n                    }\n                    catch ( comma::exception & )\n                    {}\n                }\n            }\n        }\n        // 6. if all the above fails, throw\n        COMMA_THROW( comma::exception, \"conversion from colorspace \" << inc << \", range \" << stringify::from( inr ) << \" to colorspace \" << outc << \", range \" << stringify::from( outr ) << \" is not known\" );\n    }\n\n    typedef std::function< void ( const comma::csv::options & csv, const C & c ) > F;\n\n    template< colorspace::cspace inc, range inr, colorspace::cspace outc, range outr, typename outt >\n    void convert( const comma::csv::options & csv, const C & c )\n    {\n        pixel< double, inr > sample_in;\n        comma::csv::input_stream< pixel< double, inr > > is( std::cin, csv, sample_in );\n        comma::csv::options output_csv;\n        output_csv.full_xpath = false;\n        output_csv.flush = csv.flush;\n        if( csv.binary() ) { output_csv.format( comma::csv::format::value< pixel< outt, outr > >() ); }\n        pixel< outt, outr > sample_out;\n        comma::csv::output_stream< pixel< outt, outr > > os( std::cout, output_csv, sample_out );\n        comma::csv::tied< pixel< double, inr >, pixel< outt, outr > > tied( is, os );\n        pixel< double, outr > op;\n        while( is.ready() || std::cin.good() )\n        {\n            const pixel< double, inr > * ip = is.read();\n            if( !ip ) { break; }\n            c( ip->channel ).swap( op.channel );\n            tied.append( pixel< outt, outr >( op ) );\n            if ( output_csv.flush ) { std::cout.flush(); }\n        }\n    }\n\n    template< colorspace::cspace inc, range inr, colorspace::cspace outc, range outr, range outt >\n    F resolve_( typename std::enable_if< std::is_integral< typename range_traits< outr >::value_t >::value, typename range_traits< outr >::value_t >::type outr_v\n              , typename std::enable_if< std::is_integral< typename range_traits< outt >::value_t >::value, typename range_traits< outt >::value_t >::type outt_v )\n    {\n        if ( outr_v == ub && outt_v == ub ) { return convert< inc, inr, outc, ub, typename range_traits< ub >::value_t >; }\n        if ( outr_v == ub && outt_v == uw ) { return convert< inc, inr, outc, ub, typename range_traits< uw >::value_t >; }\n        if ( outr_v == ub && outt_v == ui ) { return convert< inc, inr, outc, ub, typename range_traits< ui >::value_t >; }\n        if ( outr_v == uw && outt_v == uw ) { return convert< inc, inr, outc, uw, typename range_traits< uw >::value_t >; }\n        if ( outr_v == uw && outt_v == ui ) { return convert< inc, inr, outc, uw, typename range_traits< ui >::value_t >; }\n        if ( outr_v == ui && outt_v == ui ) { return convert< inc, inr, outc, ui, typename range_traits< ui >::value_t >; }\n        COMMA_THROW( comma::exception, \"unsupported combination of output range \" << stringify::from( outr ) << \" and type \" << stringify::from( outt ) );\n    }\n\n    template< colorspace::cspace inc, range inr, colorspace::cspace outc, range outr, range outt >\n    F resolve_( typename std::enable_if< std::is_floating_point< typename range_traits< outr >::value_t >::value, typename range_traits< outr >::value_t >::type outr_v\n              , typename std::enable_if< std::is_integral< typename range_traits< outt >::value_t >::value, typename range_traits< outt >::value_t >::type outt_v )\n    {\n        COMMA_THROW( comma::exception, \"cannot use integer output type \" << stringify::from( outt ) << \" for \" << stringify::from( outr ) << \" output range\" );\n    }\n\n    template< colorspace::cspace inc, range inr, colorspace::cspace outc, range outr, range outt >\n    F resolve_( typename std::enable_if< std::is_integral< typename range_traits< outr >::value_t >::value, typename range_traits< outr >::value_t >::type outr_v\n              , typename std::enable_if< std::is_floating_point< typename range_traits< outt >::value_t >::value, typename range_traits< outt >::value_t >::type outt_v )\n    {\n        return convert< inc, inr, outc, outr, typename range_traits< outt >::value_t >;\n    }\n\n    template< colorspace::cspace inc, range inr, colorspace::cspace outc, range outr, range outt >\n    F resolve_( typename std::enable_if< std::is_floating_point< typename range_traits< outr >::value_t >::value, typename range_traits< outr >::value_t >::type outr_v\n              , typename std::enable_if< std::is_floating_point< typename range_traits< outt >::value_t >::value, typename range_traits< outt >::value_t >::type outt_v )\n    {\n        return convert< inc, inr, outc, outr, typename range_traits< outt >::value_t >;\n    }\n\n    template< colorspace::cspace inc, range inr, colorspace::cspace outc, range outr, range outt >\n    struct outt_\n    {\n        static F dispatch()\n        {\n            // shall not attempt instantiating if:\n            // - outr is integer, outt is integer and outr > outt\n            // - outr is float, outt is integer\n            typename range_traits< outr >::value_t outr_v( outr );\n            typename range_traits< outt >::value_t outt_v( outt );\n            return resolve_< inc, inr, outc, outr, outt >( outr_v, outt_v );\n        }\n    };\n\n    template< colorspace::cspace inc, range inr, colorspace::cspace outc, range outr >\n    struct outr_\n    {\n        static F dispatch( range outt )\n        {\n            switch ( outt )\n            {\n                case ub: return outt_< inc, inr, outc, outr, ub >::dispatch( ); break;\n                case uw: return outt_< inc, inr, outc, outr, uw >::dispatch( ); break;\n                case ui: return outt_< inc, inr, outc, outr, ui >::dispatch( ); break;\n                case f:  return outt_< inc, inr, outc, outr, f  >::dispatch( ); break;\n                case d:  return outt_< inc, inr, outc, outr, d  >::dispatch( ); break;\n                default:\n                    COMMA_THROW( comma::exception, \"unknown output storage format '\" << stringify::from( outt ) << \"'\" );\n            }\n        }\n    };\n\n    template< colorspace::cspace inc, range inr, colorspace::cspace outc >\n    struct outc_\n    {\n        static F dispatch( range outr, range outt )\n        {\n            switch ( outr )\n            {\n                case ub: return outr_< inc, inr, outc, ub >::dispatch( outt ); break;\n                case uw: return outr_< inc, inr, outc, uw >::dispatch( outt ); break;\n                case ui: return outr_< inc, inr, outc, ui >::dispatch( outt ); break;\n                case f:  return outr_< inc, inr, outc, f  >::dispatch( outt ); break;\n                case d:  return outr_< inc, inr, outc, d  >::dispatch( outt ); break;\n                default:\n                    COMMA_THROW( comma::exception, \"unknown output range '\" << stringify::from( outr ) << \"'\" );\n            }\n        }\n    };\n\n    template< colorspace::cspace inc, range inr >\n    struct inr_\n    {\n        static F dispatch( const colorspace & outc, range outr, range outt )\n        {\n            switch ( outc.value )\n            {\n                case colorspace::rgb:   return outc_< inc, inr, colorspace::rgb   >::dispatch( outr, outt ); break;\n                case colorspace::ypbpr: return outc_< inc, inr, colorspace::ypbpr >::dispatch( outr, outt ); break;\n                case colorspace::ycbcr: return outc_< inc, inr, colorspace::ycbcr >::dispatch( outr, outt ); break;\n                default:\n                    COMMA_THROW( comma::exception, \"unknown colorspace to '\" << std::string( outc ) << \"'\" );\n            }\n        }\n    };\n\n    template< colorspace::cspace inc >\n    struct inc_\n    {\n        static F dispatch( range inr, const colorspace & outc, range outr, range outt )\n        {\n            switch ( inr )\n            {\n                case ub: return inr_< inc, ub >::dispatch( outc, outr, outt ); break;\n                case uw: return inr_< inc, uw >::dispatch( outc, outr, outt ); break;\n                case ui: return inr_< inc, ui >::dispatch( outc, outr, outt ); break;\n                case f:  return inr_< inc, f  >::dispatch( outc, outr, outt ); break;\n                case d:  return inr_< inc, d  >::dispatch( outc, outr, outt ); break;\n                default:\n                    COMMA_THROW( comma::exception, \"unknown input range '\" << stringify::from( inr ) << \"'\" );\n            }\n        }\n    };\n\n} // anonymous\n\nnamespace snark { namespace imaging {\n\n    converter::F converter::dispatch( const colorspace & inc, range inr, const colorspace & outc, range outr, range outt )\n    {\n        const C & conv = select( conversions(), inc, inr, outc, outr );\n\n        switch ( inc.value )\n        {\n            case colorspace::rgb:   return std::bind( inc_< colorspace::rgb   >::dispatch( inr, outc, outr, outt ), std::placeholders::_1, conv ); break;\n            case colorspace::ypbpr: return std::bind( inc_< colorspace::ypbpr >::dispatch( inr, outc, outr, outt ), std::placeholders::_1, conv ); break;\n            case colorspace::ycbcr: return std::bind( inc_< colorspace::ycbcr >::dispatch( inr, outc, outr, outt ), std::placeholders::_1, conv ); break;\n            default:\n                COMMA_THROW( comma::exception, \"unknown colorspace from '\" << std::string( inc ) << \"'\" );\n        }\n    }\n\n    void converter::list( std::ostream & os )\n    {\n        const auto & allc = { colorspace( colorspace::rgb ), colorspace( colorspace::ycbcr ), colorspace( colorspace::ypbpr ) };\n        const auto & allr = { ub, uw, ui, f, d };\n        for ( const auto & inc : allc )\n        {\n            for ( auto inr : allr )\n            {\n                for ( const auto & outc : allc )\n                {\n                    for ( auto outr : allr )\n                    {\n                        try\n                        {\n                            select( conversions(), inc, inr, outc, outr );\n                            os << inc << ',' << stringify::from( inr ) << ',' << outc << ',' << stringify::from( outr ) << std::endl;\n                        }\n                        catch ( comma::exception & )\n                        {}\n                    }\n                }\n            }\n        }\n    }\n\n} } // namespace snark { namespace imaging {\n", "meta": {"hexsha": "ff936e18879f148eef12f6bb1ebcdcbd35052a42", "size": 22384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "imaging/color/convert.cpp", "max_stars_repo_name": "mission-systems-pty-ltd/snark", "max_stars_repo_head_hexsha": "2bc8a20292ee3684d3a9897ba6fee43fed8d89ae", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-27T00:24:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T00:24:37.000Z", "max_issues_repo_path": "imaging/color/convert.cpp", "max_issues_repo_name": "NEU-LC/snark", "max_issues_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imaging/color/convert.cpp", "max_forks_repo_name": "NEU-LC/snark", "max_forks_repo_head_hexsha": "db890f73f4c4bbe679405f3a607fd9ea373deb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-30T02:11:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-30T02:11:55.000Z", "avg_line_length": 58.1402597403, "max_line_length": 236, "alphanum_fraction": 0.5585686204, "num_tokens": 6225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2497192784732513}}
{"text": "/*    Copyright (c) 2010-2018, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/make_shared.hpp>\n#include <memory>\n#include <boost/bind.hpp>\n\n#include \"Tudat/Astrodynamics/Aerodynamics/aerodynamics.h\"\n#include \"Tudat/Astrodynamics/Aerodynamics/flightConditions.h\"\n#include \"Tudat/Astrodynamics/Aerodynamics/standardAtmosphere.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/oblateSpheroidBodyShapeModel.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n\nnamespace tudat\n{\n\nnamespace aerodynamics\n{\n\n\n//! Constructor, sets objects and functions from which relevant environment and state variables are retrieved.\nFlightConditions::FlightConditions( const std::shared_ptr< basic_astrodynamics::BodyShapeModel > shapeModel,\n                  const std::shared_ptr< reference_frames::AerodynamicAngleCalculator >\n                  aerodynamicAngleCalculator ):\n    shapeModel_( shapeModel ),\n    aerodynamicAngleCalculator_( aerodynamicAngleCalculator ),\n    currentTime_( TUDAT_NAN )\n{\n    // Link body-state function.\n    bodyCenteredPseudoBodyFixedStateFunction_ = std::bind(\n                &reference_frames::AerodynamicAngleCalculator::getCurrentAirspeedBasedBodyFixedState, aerodynamicAngleCalculator_ );\n\n    // Check if given body shape is an oblate spheroid and set geodetic latitude function if so\n    if( std::dynamic_pointer_cast< basic_astrodynamics::OblateSpheroidBodyShapeModel >( shapeModel ) != nullptr )\n    {\n        geodeticLatitudeFunction_ = std::bind(\n                    &basic_astrodynamics::OblateSpheroidBodyShapeModel::getGeodeticLatitude,\n                    std::dynamic_pointer_cast< basic_astrodynamics::OblateSpheroidBodyShapeModel >( shapeModel ),\n                    std::placeholders::_1, 1.0E-4 );\n    }\n}\n\n//! Function to update all flight conditions.\nvoid FlightConditions::updateConditions( const double currentTime )\n{\n    if( !( currentTime == currentTime_ ) )\n    {\n        currentTime_ = currentTime;\n\n        // Update aerodynamic angles (but not angles w.r.t. body-fixed frame).\n        if( aerodynamicAngleCalculator_!= nullptr )\n        {\n            aerodynamicAngleCalculator_->update( currentTime, false );\n        }\n\n        // Calculate state of vehicle in global frame and corotating frame.\n        currentBodyCenteredAirspeedBasedBodyFixedState_ = bodyCenteredPseudoBodyFixedStateFunction_( );\n    }\n}\n\n//! Constructor, sets objects and functions from which relevant environment and state variables are retrieved.\nAtmosphericFlightConditions::AtmosphericFlightConditions(\n        const std::shared_ptr< aerodynamics::AtmosphereModel > atmosphereModel,\n        const std::shared_ptr< basic_astrodynamics::BodyShapeModel > shapeModel,\n        const std::shared_ptr< AerodynamicCoefficientInterface > aerodynamicCoefficientInterface,\n        const std::shared_ptr< reference_frames::AerodynamicAngleCalculator > aerodynamicAngleCalculator,\n        const std::function< double( const std::string& ) > controlSurfaceDeflectionFunction ):\n    FlightConditions( shapeModel, aerodynamicAngleCalculator ),\n    atmosphereModel_( atmosphereModel ),\n    aerodynamicCoefficientInterface_( aerodynamicCoefficientInterface ),\n    controlSurfaceDeflectionFunction_( controlSurfaceDeflectionFunction )\n{\n    // Check if atmosphere requires latitude and longitude update.\n    if( std::dynamic_pointer_cast< aerodynamics::StandardAtmosphere >( atmosphereModel_ ) == nullptr )\n    {\n        updateLatitudeAndLongitudeForAtmosphere_ = 1;\n    }\n    else\n    {\n        updateLatitudeAndLongitudeForAtmosphere_ = 0;\n    }\n    isLatitudeAndLongitudeSet_ = 0;\n\n    if( updateLatitudeAndLongitudeForAtmosphere_ && aerodynamicAngleCalculator_== nullptr )\n    {\n        throw std::runtime_error( \"Error when making flight conditions, angles are to be updated, but no calculator is set\" );\n    }\n}\n\n//! Function to set custom dependency of aerodynamic coefficients\nvoid AtmosphericFlightConditions::setAerodynamicCoefficientsIndependentVariableFunction(\n        const AerodynamicCoefficientsIndependentVariables independentVariable,\n        const std::function< double( ) > coefficientDependency )\n{\n    if( ( independentVariable == mach_number_dependent ) ||\n            ( independentVariable == angle_of_attack_dependent ) ||\n            ( independentVariable == angle_of_sideslip_dependent )||\n            ( independentVariable == altitude_dependent ) )\n    {\n        throw std::runtime_error(\n                    std::string( \"Error when setting aerodynamic coefficient function dependency, value of parameter \" ) +\n                    std::to_string( independentVariable ) +\n                    std::string(\", will not  be used.\" ) );\n    }\n    else\n    {\n        customCoefficientDependencies_[ independentVariable ] = coefficientDependency;\n    }\n}\n\n//! Function to update all flight conditions.\nvoid AtmosphericFlightConditions::updateConditions( const double currentTime )\n{\n    if( !( currentTime == currentTime_ ) )\n    {\n        currentTime_ = currentTime;\n\n        // Update aerodynamic angles (but not angles w.r.t. body-fixed frame).\n        if( aerodynamicAngleCalculator_!= nullptr )\n        {\n            aerodynamicAngleCalculator_->update( currentTime, false );\n        }\n\n        // Calculate state of vehicle in global frame and corotating frame.\n        currentBodyCenteredAirspeedBasedBodyFixedState_ = bodyCenteredPseudoBodyFixedStateFunction_( );\n\n        updateAerodynamicCoefficientInput( );\n\n        // Update angles from aerodynamic to body-fixed frame (if relevant).\n        if( aerodynamicAngleCalculator_!= nullptr )\n        {\n            aerodynamicAngleCalculator_->update( currentTime, true );\n            updateAerodynamicCoefficientInput( );\n        }\n\n        // Update aerodynamic coefficients.\n        aerodynamicCoefficientInterface_->updateFullCurrentCoefficients(\n                    aerodynamicCoefficientIndependentVariables_, controlSurfaceAerodynamicCoefficientIndependentVariables_,\n                    currentTime_ );\n    }\n}\n\n//! Function to (compute and) retrieve the value of an independent variable of aerodynamic coefficients\ndouble AtmosphericFlightConditions::getAerodynamicCoefficientIndependentVariable(\n        const AerodynamicCoefficientsIndependentVariables independentVariableType,\n        const std::string& secondaryIdentifier )\n{\n    double currentIndependentVariable;\n    switch( independentVariableType )\n    {\n    //Calculate Mach number if needed.\n    case mach_number_dependent:\n        currentIndependentVariable = getCurrentMachNumber( );\n        break;\n        //Get angle of attack if needed.\n    case angle_of_attack_dependent:\n        if( aerodynamicAngleCalculator_== nullptr )\n        {\n            throw std::runtime_error( \"Error, aerodynamic angle calculator is nullptr, but require angle of attack\" );\n        }\n        currentIndependentVariable = aerodynamicAngleCalculator_->getAerodynamicAngle(\n                    reference_frames::angle_of_attack );\n        break;\n        //Get angle of sideslip if needed.\n    case angle_of_sideslip_dependent:\n        if( aerodynamicAngleCalculator_== nullptr )\n        {\n            throw std::runtime_error( \"Error, aerodynamic angle calculator is nullptr, but require angle of sideslip\" );\n        }\n        currentIndependentVariable = aerodynamicAngleCalculator_->getAerodynamicAngle(\n                    reference_frames::angle_of_sideslip );\n        break;\n    case altitude_dependent:\n        currentIndependentVariable = getCurrentAltitude( );\n        break;\n    case control_surface_deflection_dependent:\n    {\n        try\n        {\n            currentIndependentVariable = controlSurfaceDeflectionFunction_( secondaryIdentifier );\n        }\n        catch( std::runtime_error )\n        {\n            throw std::runtime_error( \"Error, control surface \" + secondaryIdentifier + \"not recognized when updating coefficients\" );\n        }\n        break;\n    }\n    default:\n        if( customCoefficientDependencies_.count( independentVariableType ) == 0 )\n        {\n            throw std::runtime_error( \"Error, did not recognize aerodynamic coefficient dependency \"\n                                      + std::to_string( independentVariableType ) );\n        }\n        else\n        {\n            currentIndependentVariable = customCoefficientDependencies_.at( independentVariableType )( );\n        }\n    }\n\n    return currentIndependentVariable;\n}\n\n//! Function to update the independent variables of the aerodynamic coefficient interface\nvoid AtmosphericFlightConditions::updateAerodynamicCoefficientInput( )\n{\n    aerodynamicCoefficientIndependentVariables_.clear( );\n    // Calculate independent variables for aerodynamic coefficients.\n    for( unsigned int i = 0; i < aerodynamicCoefficientInterface_->getNumberOfIndependentVariables( ); i++ )\n    {\n        aerodynamicCoefficientIndependentVariables_.push_back(\n                    getAerodynamicCoefficientIndependentVariable(\n                        aerodynamicCoefficientInterface_->getIndependentVariableName( i ) ) );\n    }\n\n    controlSurfaceAerodynamicCoefficientIndependentVariables_.clear( );\n    for( unsigned int i = 0; i < aerodynamicCoefficientInterface_->getNumberOfControlSurfaces( ); i++ )\n    {\n        std::string currentControlSurface = aerodynamicCoefficientInterface_->getControlSurfaceName( i );\n        for( unsigned int j = 0; j < aerodynamicCoefficientInterface_->getNumberOfControlSurfaceIndependentVariables( currentControlSurface ); j++ )\n        {\n            controlSurfaceAerodynamicCoefficientIndependentVariables_[ currentControlSurface ].push_back(\n                        getAerodynamicCoefficientIndependentVariable(\n                            aerodynamicCoefficientInterface_->getControlSurfaceIndependentVariableName(\n                                currentControlSurface, j ), currentControlSurface ) );\n        }\n    }\n}\n\n//! Function to set the angle of attack to trimmed conditions.\nstd::shared_ptr< TrimOrientationCalculator > setTrimmedConditions(\n        const std::shared_ptr< AtmosphericFlightConditions > flightConditions )\n{\n    // Create trim object.\n    std::shared_ptr< TrimOrientationCalculator > trimOrientation =\n            std::make_shared< TrimOrientationCalculator >(\n                flightConditions->getAerodynamicCoefficientInterface( ) );\n\n    // Create angle-of-attack function from trim object.\n    std::function< std::vector< double >( ) > untrimmedIndependentVariablesFunction =\n            std::bind( &AtmosphericFlightConditions::getAerodynamicCoefficientIndependentVariables,\n                         flightConditions );\n    std::function< std::map< std::string, std::vector< double > >( ) > untrimmedControlSurfaceIndependentVariablesFunction =\n            std::bind( &AtmosphericFlightConditions::getControlSurfaceAerodynamicCoefficientIndependentVariables,\n                         flightConditions );\n    flightConditions->getAerodynamicAngleCalculator( )->setOrientationAngleFunctions(\n                std::bind( &TrimOrientationCalculator::findTrimAngleOfAttackFromFunction, trimOrientation,\n                             untrimmedIndependentVariablesFunction, untrimmedControlSurfaceIndependentVariablesFunction ) );\n\n    return trimOrientation;\n}\n\n} // namespace aerodynamics\n\n} // namespace tudat\n", "meta": {"hexsha": "a9a9e31ee9ae6443c4c4fd4158d20fddde1001c3", "size": 11677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Aerodynamics/flightConditions.cpp", "max_stars_repo_name": "J-Westin/tudat", "max_stars_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Aerodynamics/flightConditions.cpp", "max_issues_repo_name": "J-Westin/tudat", "max_issues_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Aerodynamics/flightConditions.cpp", "max_forks_repo_name": "J-Westin/tudat", "max_forks_repo_head_hexsha": "82ebe9e6e2dd51d0688b77960e62e980e6b8bcb8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.5687022901, "max_line_length": 148, "alphanum_fraction": 0.7112271988, "num_tokens": 2324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2496586845488787}}
{"text": "/*\n * Adapt3DInterpolator.cpp\n *\n *  Created on: Oct 29, 2010\n *      Author: dberrios\n */\n\n#include \"Adapt3DInterpolator.h\"\n#include \"Adapt3D.h\" //include the smart values structure\n#include \"StringConstants.h\"\n#include \"MathHelper.h\"\n#include <stdio.h>\n#include <iostream>\n//#include <boost/thread.hpp>\n#define MIN_RANGE    -1e9\n#define MAX_RANGE    +1e9\n#define NNODE_ADAPT3D 4\n#define LINEAR_INTERPOL\n\n//#define DEBUG\n//#define DEBUGS\nnamespace ccmc\n{\n\t/**\n\t * @param modelReader Pointer to the Model object containing the appropriate variable maps.  Adapt3DInterpolator\n\t * should be returned by a Adapt3D::createNewInterpolator() call.\n\t */\n\tAdapt3DInterpolator::Adapt3DInterpolator(Model * modelReader)\n\t{\n\t\t// TODO Auto-generated constructor stub\n\t\tthis->modelReader = modelReader;\n\t\t/***  Open should have failed previosly, so they should exist! ***/\n\n\t\tthis->grid_reg_no = (modelReader->getGlobalAttribute(ccmc::strings::variables::grid_reg_no_)).getAttributeInt();\n\t\tthis->ndimn = (modelReader->getGlobalAttribute(ccmc::strings::variables::ndimn_)).getAttributeInt();\n\t\tthis->npoin = (modelReader->getGlobalAttribute(ccmc::strings::variables::npoin_)).getAttributeInt();\n\t\tthis->nelem = (modelReader->getGlobalAttribute(ccmc::strings::variables::nelem_)).getAttributeInt();\n\t\t//->nboun = (modelReader->getGlobalAttribute(ccmc::strings::variables::nboun_)).getAttributeInt();\n\t\t//this->nconi = (modelReader->getGlobalAttribute(ccmc::strings::variables::nconi_)).getAttributeInt();\n\t\tthis->coord = modelReader->getVariableFromMap(ccmc::strings::variables::coord_);\n\t\tthis->intmat = modelReader->getIntVariableFromMap(ccmc::strings::variables::intmat_);\n\t\t//this->unkno = (modelReader->getVariableFromMap(ccmc::strings::variables::unkno_));\n\n\t\tthis->smartSearchValues = ((Adapt3D*)(modelReader))->getSmartGridSearchValues();\n\t\t//indx = new int[nelem];\n\t\t//esup1 = new int[nelem*4];\n\t\t//esup2 = new int[npoin+1];\n\t\tthis->nnode = NNODE_ADAPT3D;\n\t\t//this->unstructured_grid_setup_done = this->setupUnstructuredGridSearch();\n\t\t//this->smartSearchSetup();\n\t\tthis->smartSearchValues->last_element_found = -1;\n//\t\tstd::cout << \"created Adapt3DInterpolator object\" << std::endl;\n\n\t}\n\n\t/**\n\t * @param variable\n\t * @param c0 X component of the position\n\t * @param c1 Y component of the position\n\t * @param c2 Z component of the position\n\t * @return\n\t */\n\tfloat Adapt3DInterpolator::interpolate(const std::string& variable, const float& c0, const float& c1,\n\t\t\tconst float& c2)\n\t{\n\n\t\tfloat dc0, dc1, dc2;\n\t\t//long variable_id = modelReader->getVariableID(variable);\n\t\treturn interpolate(variable, c0, c1, c2, dc0, dc1, dc2);\n\n\t}\n\n\t/**\n\t * @param variable_id\n\t * @param c0 X component of the position\n\t * @param c1 Y component of the position\n\t * @param c2 Z component of the position\n\t * @return\n\t */\n\tfloat Adapt3DInterpolator::interpolate(const long& variable_id, const float& c0, const float& c1, const float& c2)\n\t{\n\n\t\tfloat dc0, dc1, dc2;\n\t\treturn interpolate(variable_id, c0, c1, c2, dc0, dc1, dc2);\n\n\t}\n\n\t/**\n\t * Interpolation method. Note that using the variable ID is significantly faster than using the variable string.\n\t * @param variable_id A long representing the variable ID.\n\t * @param c0 X component of the position\n\t * @param c1 Y component of the position\n\t * @param c2 Z component of the position\n\t * @param dc0 Reference to a variable to store the delta for component 0\n\t * @param dc1 Reference to a variable to store the delta for component 1\n\t * @param dc2 Reference to a variable to store the delta for component 2\n\t * @return The interpolated value at position (c0,c1,c2) with deltas (dc0,dc1,dc2)\n\t */\n\tfloat Adapt3DInterpolator::interpolate(const long& variable_id, const float& c0, const float& c1, const float& c2,\n\t\t\tfloat& dc0, float& dc1, float& dc2)\n\t{\n\n\t\tstd::string variable = this->modelReader->getVariableName(variable_id);\n\t\treturn interpolate(variable, c0,c1,c2,dc0,dc1,dc2);\n\t}\n\n\t/**\n\t * Interpolation method. Note that using the variable ID is significantly faster than using the variable string.\n\t * @param variable The input variable.\n\t * @param c0 X component of the position\n\t * @param c1 Y component of the position\n\t * @param c2 Z component of the position\n\t * @param dc0 Reference to a variable to store the delta for component 0\n\t * @param dc1 Reference to a variable to store the delta for component 1\n\t * @param dc2 Reference to a variable to store the delta for component 2\n\t * @return The interpolated value at position (c0,c1,c2) with deltas (dc0,dc1,dc2)\n\t */\n\tfloat Adapt3DInterpolator::interpolate(const std::string& variable, const float& c0, const float& c1,\n\t\t\tconst float& c2, float& dc0, float& dc1, float& dc2)\n\t{\n\t\tfloat missingValue = this->modelReader->getMissingValue();\n\t\t//this->last_element_found = -1;\n\t\tif (!point_within_grid(c0,c1,c2))\n\t\t\treturn missingValue;\n\t\t//float rsun_in_meters = 7.0e8;\n\t\t//float unkno_local[9];\n\n\t\tlong counts[1] = { 0 };\n\t\tlong intervals[1] = { 1 };\n\n\t\tfloat interpolated_value;\n\n\t\tint clear_cache;\n\n\n\n\n\n\t\tint     array_size;\n\t\tint     istatus;\n\t\tint     ielem;\n\n\t\t//char variable_name0[] = \"intmat\";\n\t\t//char variable_name1[] = \"coord\";\n\n\t\t/**\n\t\t* TODO: figure out what to do about the dc0,dc1,dc2 values\n\t\t*/\n\t\tdc0=dc1=dc2=.02f;\n\n\n\n\n\n\t\t/** lets see if required variables are in memory **/\n\n\n\t\t/****     since the cdf data is stored in r[meters], radians, radians or r, phi theta\n\t\t*         but we are accepting input as r[AU], lon, lat - we must do some coordiante transformations\n\t\t*/\n\n\t\t/* convert rsun to meters */\n\t\t/*\n\t\t   coord1[0] = X * rsun_in_meters;\n\t\t   coord1[1] = Y * rsun_in_meters;\n\t\t   coord1[2] = Z * rsun_in_meters;\n\t\t*/\n\n\n\n\n\t\tcounts[0] = 0; /*reset values after once through */\n\t\tintervals[0] = 1;\n\n\n\t\t/* for field line tracing,etc..., select appropriate variable number ie. bx_cdfNum|by_cdfNum|bz_cdfNum based on *variable_string */\n\t\t/* also select appropriate position arrays x, y , z for bx1, by1,bz1 */\n\n\t\t/* set default grid arrays and change if neccessary */\n\n\n\t\t//char *filename=\"adapt3d_kameleon_soln.cdf\";\n\n\n\n\n\t\tif ( variable == ccmc::strings::variables::bx_ || variable == ccmc::strings::variables::b1_)\n\t\t{\n\t\t  //unkno_index=5;\n\t\t}\n\t\telse if ( variable == \"by\" || variable == \"b2\")\n\t\t{\n\t\t // unkno_index=6;\n\t\t}\n\t\telse if ( variable == \"bz\" || variable == \"b3\")\n\t\t{\n\t\t // unkno_index=7;\n\t\t}\n\t\telse if ( variable == ccmc::strings::variables::ux_ || variable == \"u1\")\n\t\t{\n\t\t  //unkno_index=1;\n\t\t}\n\t\telse if ( variable == ccmc::strings::variables::uy_ || variable == \"u2\")\n\t\t{\n\t\t  //unkno_index=2;\n\t\t}\n\t\telse if ( variable == ccmc::strings::variables::uz_ || variable == \"u3\")\n\t\t{\n\t\t  //unkno_index=3;\n\t\t}\n\t\telse if (variable == ccmc::strings::variables::rho_)\n\t\t{\n\t\t  //unkno_index=0;\n\t\t}\n\t\telse if (variable == ccmc::strings::variables::p_ || variable == ccmc::strings::variables::e_)\n\t\t{\n\t\t  //unkno_index=4;\n\t\t}\n\t\telse if ( variable == ccmc::strings::variables::temp_ )\n\t\t{\n\t\t  //unkno_index=8;\n\t\t}\n\t\telse\n\t\t{\n\t\t  printf(\n\t\t\t\t\"ERROR:\\tcould not find cdf variable number for %s\\n\",\n\t\t\t\tvariable.c_str());\n\t\t  printf(\n\t\t\t\t\"Valid Variable Names for ADAPT3D :\\n bx OR b1 \\n by OR b2 \\n bz OR b3\\n ux OR u1 \\n uy OR u2 \\n uz OR u3 \\n p OR e \\n OR temp\\n----------------------------------------------\\n\"\n\t\t\t\t);\n\t\t  return 0;\n\t\t}\n\n\n\t\tclear_cache = 0;\n\t\t\t/* locate the grid element that contains the point coord1 */\n\t\t//ielem = smartSearch(c0,c1,c2);\n\t\tielem = findElement(c0,c1,c2, clear_cache);\n\t\t//Element * element = this->smartSearchValues->parent->findElement(c0, c1, c2);\n\t\t//if (element != NULL)\n\t\t//\tielem = this->smartSearchValues->parent->findElement(c0, c1, c2)->getIndex();\n\t\t//else ielem = -1;\n#ifdef DEBUG\n\t   std::cerr << \"ielem: \" << ielem << \" for position \" << c0 << \",\" << c1 << \",\" << c2 << std::endl;\n#endif\n\t\tinterpolated_value = missingValue;     /* test value */\n\n\t\tif(ielem > -1)\n\t\t{\n\t\t   interpolated_value = interpolate_adapt3d_solution(c0, c1, c2, ielem, variable);\n#ifdef DEBUG\n\t\t   std::cout << \"MIN_RANGE: \" << MIN_RANGE << \" this->missingValue: \" << this->missingValue << \" interpolated_value: \" << interpolated_value << std::endl;\n#endif\n\t\t   this->smartSearchValues->last_element_found = ielem;\n\t\t} else {\n\t\t\t//printf(\"Failed to find point in grid\\n\");\n\t\t\tthis->smartSearchValues->last_element_found = -1;\n\t\t}\n\n\n\t\t/*  return interpolated_value  */\n\t\tif (interpolated_value >= MIN_RANGE && interpolated_value <= MAX_RANGE && interpolated_value != missingValue)\n\t\t{\n\n\t\t  //std::cerr << \"position: \" << c0 << \",\" << c1 << \",\" << c2 << \": \" << (float)interpolated_value << std::endl;\n\t\t  return (float)interpolated_value;\n\n\t\t}\n\t\telse\n\t\t{\n\t\t  //std::cerr << \"position: \" << c0 << \",\" << c1 << \",\" << c2 << \": \" << this->missingValue << std::endl;\n\t\t  return missingValue;\n\t\t}\n\t}\n\n\n\n\n\n\n\n\tint Adapt3DInterpolator::smartSearch(const float& c0, const float& c1, const float& c2)\n\t{\n//#define DEBUGS\n\t\tint lfound, mask[NNODE_ADAPT3D], try_grid_search;\n\n\t\tint  i,j,k,ielem,inode,jnode ;\n\t\tint  ifound, jelem, kelem;\n\t\tint  node_order[NNODE_ADAPT3D];\n\t\tint  i_node, j_node, k_node, k_node_hi;\n\t\tint  next_node, i_order;\n\n\t\tint  nelems_checked;\n\t\tint  clear_cache;\n\n\t\tfloat  shapex[NNODE_ADAPT3D];\n\t\tfloat  radius;\n\n\t\tfloat  distance[NNODE_ADAPT3D];\n\n\t\tfloat size_of_last_element;\n\n#ifdef DELAUNEY_SEARCH\n       int   iteration, iteration_max;\n       int   next_element, next_element0;\n       int   in0,in1,in2,in3,iselect;\n       int   jnext,jk,jrand;\n       int   i_s,j_s,k_s;\n       float x_last_element,y_last_element,z_last_element,distance0;\n       float x,y,z,r,t,p;\n#endif\n\n//std::cout << \"smart search\" << std::endl;\n/*----------------------------------------------------------------\n!\n! Step A\n!\n! First check the last_element_found to see if the new point is still\n! inside it. If yes, then set ifound=.true'\n*/\n\t\tifound = -1;\n\t\tif( this->smartSearchValues->last_element_found >= 0 )\n\t\t{\n#ifdef DEBUGS\n\t\t\tprintf(\"Checkin if still in last element \\n\");\n#endif\n\n\t\t\tifound = chkineln(c0,c1,c2, this->smartSearchValues->last_element_found ,shapex);\n\t\t\tnelems_checked = 1;\n\t\t}\n//std::cout << \"ifound: \" << ifound << std::endl;\n/*--------*/\n\t\tif( ifound == 0 )\n\t\t{\n/*--------*/\n\n\t\t\t#ifdef DEBUGS\n\t\t\tprintf(\"Point is still in starting element! \\n\");\n\t\t\tstd::cerr << \"this->smartSearchValues->last_element_found: \" << this->smartSearchValues->last_element_found << std::endl;\n\t\t\t#endif\n\t\t\tkelem = this->smartSearchValues->last_element_found;\n\t\t\t//this->smartSearchValues->still_in_same_element++;\n\n\n/*--------*/\n\t\t} else\n\t\t{\n/*--------*/\n\n\n/* If we have a starting_element number set to begin the search  */\n\t\t\tif( this->smartSearchValues->last_element_found >= 0 )\n\t\t\t{\n\n//std::cout << \"starting search\" << std::endl;\n#ifdef DELAUNEY_SEARCH\n/* Delauney algorithm */\n           ifound=1;\n           iteration=0;\n           next_element=this->smartSearchValues->last_element_found;\n           iteration_max=DELAUNEY_ITER_MAX;\n           while ((ifound != 0) && (iteration < iteration_max)) {\n             kelem = chkineln(c0,c1,c2,next_element ,shapex);\n\n             in0=(*intmat)[ index_2d_to_1d(next_element,0,4) ];\n             in1=(*intmat)[ index_2d_to_1d(next_element,1,4) ];\n             in2=(*intmat)[ index_2d_to_1d(next_element,2,4) ];\n             in3=(*intmat)[ index_2d_to_1d(next_element,3,4) ];\n             x_last_element = 0.25*(\n                    (*coord)[ index_2d_to_1d(in0,0,3) ]\n                   +(*coord)[ index_2d_to_1d(in1,0,3) ]\n                   +(*coord)[ index_2d_to_1d(in2,0,3) ]\n                   +(*coord)[ index_2d_to_1d(in3,0,3) ] );\n             y_last_element = 0.25*(\n                    (*coord)[ index_2d_to_1d(in0,1,3) ]\n                   +(*coord)[ index_2d_to_1d(in1,1,3) ]\n                   +(*coord)[ index_2d_to_1d(in2,1,3) ]\n                   +(*coord)[ index_2d_to_1d(in3,1,3) ] );\n             z_last_element = 0.25*(\n                    (*coord)[ index_2d_to_1d(in0,2,3) ]\n                   +(*coord)[ index_2d_to_1d(in1,2,3) ]\n                   +(*coord)[ index_2d_to_1d(in2,2,3) ]\n                   +(*coord)[ index_2d_to_1d(in3,2,3) ] );\n             distance0=std::sqrt( (x_last_element-c0)*(x_last_element-c0)\n                           + (y_last_element-c1)*(y_last_element-c1)\n                           + (z_last_element-c2)*(z_last_element-c2) );\n\n/* If the distance  from last element found is too great compared with the element size then force use of the structured grid */\n\n#ifdef DEBUGS\n             printf(\"Delauney iteration no %d\\n\",iteration);\n             radius=sqrt(x_last_element*x_last_element+y_last_element*y_last_element+z_last_element*z_last_element);\n             printf(\"Center of last element %d in search : radius %e\\n\",next_element,radius);\n             printf(\"Center of last element %d in search %e %e %e\\n\",next_element,x_last_element,y_last_element,z_last_element);\n        x=x_last_element;\n        y=y_last_element;\n        z=z_last_element;\n        Math::convert_xyz_to_rthetaphi(x,y,z,&r,&t,&p);\n             printf(\"Center of last element (rtp) %d in search %e %e %e\\n\",next_element,r,t,p);\n\n           i_s = (int)( (r-this->smartSearchValues->xl_sg)/this->smartSearchValues->dx_sg );\n           j_s = (int)( (t-this->smartSearchValues->yl_sg)/this->smartSearchValues->dy_sg );\n           k_s = (int)( (p-this->smartSearchValues->zl_sg)/this->smartSearchValues->dz_sg );\n           printf(\"Located in structured cell %d %d %d\\n\",i_s,j_s,k_s);\n\n\n             printf(\"Distance from last element to search point is %e\\n\",distance0);\n             printf(\"Search pt coords %e %e %e \\n\",c0,c1,c2);\n             printf(\"Search pt radius %e\\n\",std::sqrt(c0*c0+c1*c1+c2*c2));\n             fflush(stdout);\n#endif\n             next_element0=next_element;\n             jrand=(int)(3.0001 *(float)rand() / (float)RAND_MAX );\n             jk=0;\n             iselect=-1;\n             while ((iselect == -1) && (jk < 4)) {\n               jnext=(jk+jrand)%4;\n               if(shapex[ jnext ] < 0.) {\n                 next_element=(*this->smartSearchValues->facing_elements)[ index_2d_to_1d(next_element0,jnext,4) ];\n                 if(next_element > -1) {\n                   iselect=jnext;\n#ifdef DEBUGS\n                 } else {\n                  printf(\"Loop %d: Face %d is a boundary with next_element=%d. Skip to next face\\n\",jk,jnext,next_element);\n                  printf(\"shapex %e %e %e %e\\n\",shapex[0],shapex[1],shapex[2],shapex[3]);\n                  fflush(stdout);\n#endif\n                 }\n#ifdef DEBUGS\n                 printf(\"jrand=%d\\n\",jrand);\n                 printf(\"iselect=%d\\n\",iselect);\n                 fflush(stdout);\n#endif\n               }\n               jk=jk+1;\n             }\n\n\n             iteration++;\n\n/* If only face in direction of search point is a boundary then end search and reset last-element_found */\n             if(next_element == -999) {\n                iteration=iteration_max;\n                this->smartSearchValues->last_element_found=-1;\n                kelem=-1;\n               // this->smartSearchValues->outside_grid += 1;\n             }\n\n             if(kelem == 0) {\n               ifound=0;\n#ifdef DEBUGS\n                 printf(\"Delauney search successful : found in element %d \\n\",next_element);\n    //             fflush(stdout);\n#endif\n                 if(iteration-1 < DELAUNEY_ITER_MAX) (*this->smartSearchValues->delauney_search_iteration_profile)[iteration-1] += 1;\n             }\n           }\n           if(ifound == 0)  kelem=next_element;\n\n/* End of Delauney algorithm */\n#endif /* ifdef DELAUNEY_SEARCH */\n\n\n       }      /*   if( last_element_found .ge. 0 )  */\n\n/*--------*/\n       }      /*   if( ifound .eq. 0)  */\n/*--------*/\n\n\n#ifdef DEBUGS\n       if( ifound != 0) {\n          printf(\"Smart search failed! \\n\");\n          printf(\"search_point_coords %e %e %e \\n\",c0,c1,c2);\n                 fflush(stdout);\n\n          if(kelem > 0) {\n              printf(\"Found in element %i \\n\",kelem);\n              fflush(stdout);\n          } else {\n              printf(\"Failed to locate element in grid \\n\");\n              fflush(stdout);\n          }\n       }\n#endif\n\n\n\t\treturn kelem;\n\n\t}\n\n\tint Adapt3DInterpolator::findElement(const float& c0, const float& c1, const float& c2, int clear_cache)\n\t{\n\n//#define DEBUGS\n\n\t\t//std::cout << \"entered findElement\" << std::endl;\n\n\t\tint\t\t\tielem,kelem, inode;\n\t\tint         i_s,j_s,k_s,i,j,k,indx_start,indx_end;\n\t\tint         indx1,ifound,just_found,jelem;\n\t\tfloat       x,y,z;\n        //float* shapex = new float[nnode];\n\t\tint\t\t\tnext_element, next_element0, iselect;\n\n\t\tint        in0,in1,in2,in3,iteration;\n\t\tint        delta_i;\n\t\tfloat      x_last_element,y_last_element,z_last_element;\n\t\tfloat      distance;\n\t\tfloat      ddx,ddy,ddz,ss,xx,yy,zz,radius;\n\t\tint        new_del,i_new,j_new,k_new;\n\t\tfloat      r, t, p;\n\t\tfloat      distance0,size_of_last_element;\n\n\t\tint      i_min,i_max;\n\t\tint      j_min,j_max;\n\t\tint      k_min,k_max;\n\t\tint      j0,k0;\n\n\t\tkelem=-1;\n\t\tielem=-1;\n\t\tifound=-1;\n\t\tif ( point_within_grid(c0, c1, c2) == 1)\n\t\t{\n\n\t         if(clear_cache == 1) this->smartSearchValues->last_element_found=-1;\n\t#ifdef DEBUG\n\t       printf(\"0find_element: (*coord)[0][0-2] : %e %e %e \\n\",(*coord)[ index_2d_to_1d(0,0,npoin) ],(*coord)[ index_2d_to_1d(0,1,npoin) ],(*coord)[ index_2d_to_1d(0,2,npoin) ]);\n\t#endif\n\n\t       /* If available, use the last element found to begin the search */\n\t       if(this->smartSearchValues->last_element_found != -1) {\n\t    \t   in0=(*intmat)[ index_2d_to_1d(this->smartSearchValues->last_element_found,0,4) ];\n\t    \t   in1=(*intmat)[ index_2d_to_1d(this->smartSearchValues->last_element_found,1,4) ];\n\t    \t   x_last_element=(*coord)[ index_2d_to_1d(in0,0,3) ];\n\t    \t   y_last_element=(*coord)[ index_2d_to_1d(in0,1,3) ];\n\t    \t   z_last_element=(*coord)[ index_2d_to_1d(in0,2,3) ];\n\t    \t   distance0=std::sqrt( (x_last_element-c0)*(x_last_element-c0)\n\t    \t\t\t   \t   \t      + (y_last_element-c1)*(y_last_element-c1)\n\t    \t\t\t   \t   \t      + (z_last_element-c2)*(z_last_element-c2));\n\t    \t   size_of_last_element=std::sqrt(\n\t    \t\t\t   ( (*coord)[ index_2d_to_1d(in0,0,3) ] -(*coord)[ index_2d_to_1d(in1,0,3) ] )*\n\t    \t\t\t   ( (*coord)[ index_2d_to_1d(in0,0,3) ] -(*coord)[ index_2d_to_1d(in1,0,3) ] )\n\t    \t\t\t   +( (*coord)[ index_2d_to_1d(in0,1,3) ] -(*coord)[ index_2d_to_1d(in1,1,3) ] )*\n\t    \t\t\t   ( (*coord)[ index_2d_to_1d(in0,1,3) ] -(*coord)[ index_2d_to_1d(in1,1,3) ] )\n\t    \t\t\t   +( (*coord)[ index_2d_to_1d(in0,2,3) ] -(*coord)[ index_2d_to_1d(in1,2,3) ] )*\n\t    \t\t\t   ( (*coord)[ index_2d_to_1d(in0,2,3) ] -(*coord)[ index_2d_to_1d(in1,2,3) ] ) );\n\n#ifdef DEBUGS\n\t    \t   printf(\"coords %e %e %e %e %e %e\\n\", (*coord)[ index_2d_to_1d(in0,0,3) ],(*coord)[ index_2d_to_1d(in1,0,3) ],\n\t    \t\t\t   (*coord)[ index_2d_to_1d(in0,1,3) ] ,(*coord)[ index_2d_to_1d(in1,1,3) ],\n\t    \t\t\t   (*coord)[ index_2d_to_1d(in0,2,3) ] ,(*coord)[ index_2d_to_1d(in1,2,3) ] );\n\t    \t   printf(\"distance to element  : %e\\n\",distance0);\n\t    \t   printf(\"element size  : %e\\n\",size_of_last_element);\n\t    \t   printf(\"Ratio of distance to element size  : %e\\n\",distance0/size_of_last_element);\n#endif\n\n\n\t    \t   /* If the distance  from last element found is too great compared with the element size then force use of the structured grid */\n\t    \t   if (distance0/size_of_last_element > 50.) {\n\t    \t\t   this->smartSearchValues->last_element_found = -1;\n#ifdef DEBUGS\n\t    \t\t   printf(\"Force new structured grid search\\n\");\n#endif\n\t    \t   }\n\n\t       }\n\t       /* If necessary generate a first guess element to begin search */\n\t       if(this->smartSearchValues->last_element_found == -1) {\n\n\n#ifdef CARTESIAN_S_GRID\n\t    \t   x = cintp[0];\n\t    \t   y = cintp[1];\n\t    \t   z = cintp[2];\n#endif /* CARTESIAN_S_GRID */\n#ifdef SPHERICAL_S_GRID\n\t    \t   Math::convert_xyz_to_rthetaphi(c0,c1,c2,&r,&t,&p);\n\t    \t   x=r;\n\t    \t   y=t;\n\t    \t   z=p;\n#endif /* SPHERICAL_S_GRID */\n\n#ifdef DEBUGS\n\t    \t   printf(\"find_element: Searching for point x y z = %e %e %e\\n\",x,y,z);\n#endif\n\t    \t   i_s = (int)( (x-this->smartSearchValues->xl_sg)/this->smartSearchValues->dx_sg );\n\t    \t   j_s = (int)( (y-this->smartSearchValues->yl_sg)/this->smartSearchValues->dy_sg );\n\t    \t   k_s = (int)( (z-this->smartSearchValues->zl_sg)/this->smartSearchValues->dz_sg );\n\t    \t   /* pmn fix section */\n\t    \t   i_s = std::min(i_s,nx_sg-1);\n\t    \t   i_s = std::max(i_s,0);\n\t    \t   j_s = std::min(j_s,ny_sg-1);\n\t    \t   j_s = std::max(j_s,0);\n\t    \t   k_s = std::min(k_s,nz_sg-1);\n\t    \t   k_s = std::max(k_s,0);\n\t    \t   /* end pmn fix section */\n#ifdef DEBUGS\n\t    \t   printf(\"Located in structured cell %d %d %d\\n\",i_s,j_s,k_s);\n#endif\n\t    \t   if(this->smartSearchValues->nelems_in_cell[k_s][j_s][i_s] > 0) {\n\t    \t\t   indx_start = this->smartSearchValues->start_index[k_s][j_s][i_s];\n\t    \t\t   indx_end   = this->smartSearchValues->end_index[k_s][j_s][i_s];\n\t    \t\t   delta_i=(int)( (float)(indx_end-indx_start) * ( (float)rand() / (float)RAND_MAX ) );\n\t    \t\t   this->smartSearchValues->last_element_found = (*this->smartSearchValues->indx)[indx_start + delta_i];\n#ifdef DEBUGS\n\t    \t\t   printf(\"Reseting last_element_found from structured grid to %d delta_i %d\\n\",this->smartSearchValues->last_element_found,indx_end-indx_start);\n#endif\n\t    \t   } else {\n\t    \t\t   this->smartSearchValues->last_element_found = -1;\n#ifdef DEBUGS\n\t    \t\t   printf(\"Structured cell has no elements - Trying the node list now\\n\");\n\t    \t\t   printf(\"nnodes_in_cell %d %d %d is %d \\n\",i_s,j_s,k_s,this->smartSearchValues->nnodes_in_cell[k_s][j_s][i_s]);\n\t    \t\t   fflush(stdout);\n#endif\n\t    \t\t   if(this->smartSearchValues->nnodes_in_cell[k_s][j_s][i_s] > 0) {\n\t    \t\t\t   indx_start = this->smartSearchValues->start_index_nodes[k_s][j_s][i_s];\n\t    \t\t\t   indx_end = this->smartSearchValues->end_index_nodes[k_s][j_s][i_s];\n#ifdef DEBUGS\n\t    \t\t\t   printf(\"nnodes_in_cell %d %d %d is %d \\n\",i_s,j_s,k_s,this->smartSearchValues->nnodes_in_cell[k_s][j_s][i_s]);\n\t    \t\t\t   printf(\"indx_start indx_end %d %d\\n\",indx_start,indx_end);\n\t    \t\t\t   fflush(stdout);\n#endif\n\t    \t\t\t   delta_i=(int)( (float)(indx_end-indx_start) * ( (float)rand() / (float)RAND_MAX ) );\n\t    \t\t\t   last_node_found = (*this->smartSearchValues->indx_nodes)[indx_start + delta_i];\n#ifdef DEBUGS\n\t    \t\t\t   printf(\"last_node_found=%d\\n\",last_node_found);\n\t    \t\t\t   printf(\"coords of last node are %e %e %e\\n\",(*coord)[last_node_found*3],\n\t    \t\t\t\t\t   (*coord)[last_node_found*3+1],(*coord)[last_node_found*3+2]);\n\t    \t\t\t   fflush(stdout);\n#endif\n\t    \t\t\t   this->smartSearchValues->last_element_found = this->smartSearchValues->esup1->at( this->smartSearchValues->esup2->at(last_node_found) );\n#ifdef DEBUGS\n\t    \t\t\t   printf(\"Node search found element %d as starting point for search\\n\", this->smartSearchValues->last_element_found);\n\t    \t\t\t   //fflush(stdout);\n#endif\n\t    \t\t   } else {\n\n#ifdef DEBUGS\n\t    \t\t\t   printf(\"Structured cell is empty - Node search also failed\\n\");\n\t    \t\t\t   printf(\"Start scanning neighbor cells using elements\\n\");\n#endif\n\t    \t\t\t   /* search immediate neighbor cells for search starting point */\n\n\t    \t\t\t   /* Locate a neighboring cell of the structured grid that contains a node */\n\t    \t\t\t   iselect = 1 ;\n\n\t    \t\t\t   i_min = std::max(0,i_s-1);\n\t    \t\t\t   i_max = std::min(nx_sg-1,i_s+1);\n#ifdef CARTESIAN_S_GRID\n\t    \t\t\t   j_min = max(0,j_s-1);\n\t    \t\t\t   j_max = min(ny_sg-1,j_s+1);\n\t    \t\t\t   k_min = max(0,k_s-1);\n\t    \t\t\t   k_max = min(nz_sg-1,k_s+1);\n#endif  /* CARTESIAN_S_GRID */\n#ifdef SPHERICAL_S_GRID\n\t    \t\t\t   j_min = std::max(j_s-1, 0);\t\t\t/* pmn fix */\n\t    \t\t\t   j_max = std::min(j_s+1, ny_sg-1); \t/* pmn fix */\n\t    \t\t\t   k_min = k_s-1;\n\t    \t\t\t   k_max = k_s+1;\n#endif  /* SPHERICAL_S_GRID */\n\n\t    \t\t\t   /* if using elements for search */\n\t    \t\t\t   for(k=k_min;k<k_max+1;k++) {\n\t    \t\t\t\t   k0=k;\n#ifdef SPHERICAL_S_GRID\n\t    \t\t\t\t   if(k==-1) k0=nz_sg-1;\n\t    \t\t\t\t   if(k==nz_sg) k0=0;\n#endif  /* SPHERICAL_S_GRID */\n\t    \t\t\t\t   for(j=j_min;j<j_max+1;j++) {\n\t    \t\t\t\t\t   j0=j;\n#ifdef SPHERICAL_S_GRID\n\t    \t\t\t\t\t   if(j==ny_sg) {\n\t    \t\t\t\t\t\t   k0 = (k0+nz_sg/2)%(nz_sg-1);\n\t    \t\t\t\t\t\t   j0 = ny_sg-1;\n\t    \t\t\t\t\t   }\n\t    \t\t\t\t\t   if(j==-1) {\n\t    \t\t\t\t\t\t   k0 = (k0+nz_sg/2)%(nz_sg-1);\n\t    \t\t\t\t\t\t   j0 = 0;\n\t    \t\t\t\t\t   }\n#endif  /* SPHERICAL_S_GRID */\n\t    \t\t\t\t\t   for(i=i_min;i<i_max+1;i++) {\n#ifdef DEBUGS\n\t    \t\t\t\t\t\t   printf(\"cell %d %d %d nelems_in_cell %d\\n\",i,j0,k0,this->smartSearchValues->nelems_in_cell[k0][j0][i]);\n#endif\n\t    \t\t\t\t\t\t   if(this->smartSearchValues->nelems_in_cell[k0][j0][i]>0) {\n\t    \t\t\t\t\t\t\t   iselect=0;\n\t    \t\t\t\t\t\t\t   i_s=i;\n\t    \t\t\t\t\t\t\t   j_s=j0;\n\t    \t\t\t\t\t\t\t   k_s=k0;\n\t    \t\t\t\t\t\t   }\n\t    \t\t\t\t\t   }}}\n\t    \t\t\t   if(iselect==0)  {\n#ifdef DEBUGS\n\t    \t\t\t\t   printf(\"Found a starting element in neighbor %d %d %d\\n\",i_s,j_s,k_s);\n#endif\n\t    \t\t\t\t   indx_start = this->smartSearchValues->start_index[k_s][j_s][i_s];\n\t    \t\t\t\t   indx_end   = this->smartSearchValues->end_index[k_s][j_s][i_s];\n\t    \t\t\t\t   delta_i=(int)( (float)(indx_end-indx_start) * ( (float)rand() / (float)RAND_MAX ) );\n\t    \t\t\t\t   this->smartSearchValues->last_element_found = (*this->smartSearchValues->indx)[indx_start + delta_i];\n#ifdef DEBUGS\n\t    \t\t\t\t   printf(\"Element is %d\\n\",this->smartSearchValues->last_element_found);\n#endif\n\t    \t\t\t   }\n\n\t    \t\t\t   /* if using nodes for search */\n\t    \t\t\t   if(iselect == 1) {\n#ifdef DEBUGS\n\t    \t\t\t\t   printf(\"Neighbor search using elements failed also\\n\");\n\t    \t\t\t\t   printf(\"Start scanning neighbor cells using nodes\\n\");\n#endif\n\t    \t\t\t\t   for(k=k_min;k<k_max+1;k++) {\n\t    \t\t\t\t\t   k0=k;\n#ifdef SPHERICAL_S_GRID\n\t    \t\t\t\t\t   if(k==-1) k0=nz_sg-1;\n\t    \t\t\t\t\t   if(k==nz_sg) k0=0;\n#endif  /* SPHERICAL_S_GRID */\n\t    \t\t\t\t\t   for(j=j_min;j<j_max+1;j++) {\n\t    \t\t\t\t\t\t   j0=j;\n#ifdef SPHERICAL_S_GRID\n\t    \t\t\t\t\t\t   if(j==ny_sg) {\n\t    \t\t\t\t\t\t\t   k0 = (k0+nz_sg/2)%(nz_sg-1);\n\t    \t\t\t\t\t\t\t   j0 = ny_sg-1;\n\t    \t\t\t\t\t\t   }\n\t    \t\t\t\t\t\t   if(j==-1) {\n\t    \t\t\t\t\t\t\t   k0 = (k0+nz_sg/2)%(nz_sg-1);\n\t    \t\t\t\t\t\t\t   j0 = 0;\n\t    \t\t\t\t\t\t   }\n#endif  /* SPHERICAL_S_GRID */\n\t    \t\t\t\t\t\t   for(i=i_min;i<i_max+1;i++) {\n#ifdef DEBUGS\n\t    \t\t\t\t\t\t\t   printf(\"cell %d %d %d nnodes_in_cell %d \\n\",i,j0,k0,this->smartSearchValues->nnodes_in_cell[k0][j0][i]);\n#endif\n\t    \t\t\t\t\t\t\t   if(this->smartSearchValues->nnodes_in_cell[k0][j0][i]>0) {\n\t    \t\t\t\t\t\t\t\t   iselect=0;\n\t    \t\t\t\t\t\t\t\t   i_s=i;\n\t    \t\t\t\t\t\t\t\t   j_s=j0;\n\t    \t\t\t\t\t\t\t\t   k_s=k0;\n\t    \t\t\t\t\t\t\t   }\n\t    \t\t\t\t\t\t   }}}\n\t    \t\t\t\t   if(iselect==0)  {\n#ifdef DEBUGS\n\t    \t\t\t\t\t   printf(\"Found a starting node in neighbor %d %d %d\\n\",i_s,j_s,k_s);\n#endif\n\t    \t\t\t\t\t   indx_start = this->smartSearchValues->start_index_nodes[k_s][j_s][i_s];\n\t    \t\t\t\t\t   indx_end = this->smartSearchValues->end_index_nodes[k_s][j_s][i_s];\n\t    \t\t\t\t\t   delta_i=(int)( (float)(indx_end-indx_start) * ( (float)rand() / (float)RAND_MAX ) );\n\t    \t\t\t\t\t   last_node_found = (*this->smartSearchValues->indx_nodes)[indx_start + delta_i];\n#ifdef DEBUGS\n\t    \t\t\t\t\t   printf(\"Node is %d\\n\",last_node_found);\n#endif\n\t    \t\t\t\t\t   this->smartSearchValues->last_element_found = this->smartSearchValues->esup1->at( this->smartSearchValues->esup2->at(last_node_found) );\n#ifdef DEBUGS\n\t    \t\t\t\t\t   printf(\"Element is %d\\n\",this->smartSearchValues->last_element_found);\n\t    \t\t\t\t   } else {\n\t    \t\t\t\t\t   printf(\"\\n\\n Final part of search failed\\n\\n\\n\");\n#endif\n\t    \t\t\t\t   }\n\n\t    \t\t\t\t   /* end of immediate neighbor search */\n\n\t    \t\t\t\t   /* If still not found search up to 2 neighbors away */\n\t    \t\t\t\t   if(iselect == 1) {\n\n\t    \t\t\t\t\t   i_min = std::max(0,i_s-2);\n\t    \t\t\t\t\t   i_max = std::min(nx_sg-1,i_s+2);\n#ifdef CARTESIAN_S_GRID\n\t    \t\t\t\t\t   j_min = max(0,j_s-2);\n\t    \t\t\t\t\t   j_max = min(ny_sg-1,j_s+2);\n\t    \t\t\t\t\t   k_min = max(0,k_s-2);\n\t    \t\t\t\t\t   k_max = min(nz_sg-1,k_s+2);\n#endif  /* CARTESIAN_S_GRID */\n#ifdef SPHERICAL_S_GRID\n\t    \t\t\t\t\t   j_min = std::max(j_s-2, 0);\n\t    \t\t\t\t\t   j_max = std::min(j_s+2, ny_sg-1);\n\t    \t\t\t\t\t   k_min = k_s-2;\n\t    \t\t\t\t\t   k_max = k_s+2;\n#endif  /* SPHERICAL_S_GRID */\n\n\t    \t\t\t\t\t   /* if using elements for search */\n\t    \t\t\t\t\t   for(k=k_min;k<k_max+1;k++) {\n\t    \t\t\t\t\t\t   k0=k;\n#ifdef SPHERICAL_S_GRID\n\t    \t\t\t\t\t\t   if(k==-1) k0=nz_sg-1;\n\t    \t\t\t\t\t\t   if(k==nz_sg) k0=0;\n\t    \t\t\t\t\t\t   if(k==-2) k0=nz_sg-2;\n\t    \t\t\t\t\t\t   if(k==nz_sg+1) k0=1;\n#endif  /* SPHERICAL_S_GRID */\n\t    \t\t\t\t\t\t   for(j=j_min;j<j_max+1;j++) {\n\t    \t\t\t\t\t\t\t   j0=j;\n#ifdef SPHERICAL_S_GRID\n\t    \t\t\t\t\t\t\t   if(j==ny_sg) {\n\t    \t\t\t\t\t\t\t\t   k0 = (k0+nz_sg/2)%(nz_sg-1);\n\t    \t\t\t\t\t\t\t\t   j0 = ny_sg-1;\n\t    \t\t\t\t\t\t\t   }\n\t    \t\t\t\t\t\t\t   if(j==ny_sg+1) {\n\t    \t\t\t\t\t\t\t\t   k0 = (k0+nz_sg/2)%(nz_sg-1);\n\t    \t\t\t\t\t\t\t\t   j0 = ny_sg-2;\n\t    \t\t\t\t\t\t\t   }\n\t    \t\t\t\t\t\t\t   if(j==-1) {\n\t    \t\t\t\t\t\t\t\t   k0 = (k0+nz_sg/2)%(nz_sg-1);\n\t    \t\t\t\t\t\t\t\t   j0 = 0;\n\t    \t\t\t\t\t\t\t   }\n\t    \t\t\t\t\t\t\t   if(j==-2) {\n\t    \t\t\t\t\t\t\t\t   k0 = (k0+nz_sg/2)%(nz_sg-1);\n\t    \t\t\t\t\t\t\t\t   j0 = 1;\n\t    \t\t\t\t\t\t\t   }\n#endif  /* SPHERICAL_S_GRID */\n\t    \t\t\t\t\t\t\t   for(i=i_min;i<i_max+1;i++) {\n#ifdef DEBUGS\n\t    \t\t\t\t\t\t\t\t   printf(\"cell %d %d %d nelems_in_cell %d\\n\",i,j0,k0,this->smartSearchValues->nelems_in_cell[k0][j0][i]);\n#endif\n\t    \t\t\t\t\t\t\t\t   if(this->smartSearchValues->nelems_in_cell[k0][j0][i]>0) {\n\t    \t\t\t\t\t\t\t\t\t   iselect=0;\n\t    \t\t\t\t\t\t\t\t\t   i_s=i;\n\t    \t\t\t\t\t\t\t\t\t   j_s=j0;\n\t    \t\t\t\t\t\t\t\t\t   k_s=k0;\n\t    \t\t\t\t\t\t\t\t   }\n\t    \t\t\t\t\t\t\t   }}}\n\t    \t\t\t\t\t   if(iselect==0)  {\n#ifdef DEBUGS\n\t    \t\t\t\t\t\t   printf(\"Found a starting element in neighbor %d %d %d\\n\",i_s,j_s,k_s);\n#endif\n\t    \t\t\t\t\t\t   indx_start = this->smartSearchValues->start_index[k_s][j_s][i_s];\n\t    \t\t\t\t\t\t   indx_end   = this->smartSearchValues->end_index[k_s][j_s][i_s];\n\t    \t\t\t\t\t\t   delta_i=(int)( (float)(indx_end-indx_start) * ( (float)rand() / (float)RAND_MAX ) );\n\t    \t\t\t\t\t\t   this->smartSearchValues->last_element_found = (*this->smartSearchValues->indx)[indx_start + delta_i];\n#ifdef DEBUGS\n\t    \t\t\t\t\t\t   printf(\"Element is %d\\n\",this->smartSearchValues->last_element_found);\n#endif\n\t    \t\t\t\t\t   }\n\n\t    \t\t\t\t   }\n\t    \t\t\t\t   /* end of 2 neighbor search */\n\n\n\t    \t\t\t   }\n\t    \t\t\t   /* next cell to pick from should be i_s,j_s,k_s */\n\n\n\t    \t\t   }\n\t    \t   }\n\n\n\t       }\n//\t       std::cout << \"last_element_found = \" << this->smartSearchValues->last_element_found << std::endl;\n\t       /* If available, use the last element found to begin the search */\n\t       if(this->smartSearchValues->last_element_found != -1) kelem = smartSearch(c0,c1,c2);\n\n\n\t       this->smartSearchValues->last_element_found=kelem;\n\t       previous_c0=c0;\n\t       previous_c1=c1;\n\t       previous_c2=c2;\n\n#ifdef DEBUGS\n\t       printf(\"Exiting find element with last_element_found=%d\\n\",this->smartSearchValues->last_element_found);\n#endif\n\n\n\n\t\t} else\n\t\t{\n#ifdef DEBUGS\n\t\t\t//this->smartSearchValues->outside_grid += 1;\n\t\t\tthis->smartSearchValues->last_element_found = -1;\n\t\t\tprevious_c0 = 0.f;\n\t\t\tprevious_c1 = 0.f;\n\t\t\tprevious_c2 = 0.f;\n#endif\n\t\t}\n\t         return kelem;\n\n\t/*       end subroutine find_element  */\n\t}\n\n\tint Adapt3DInterpolator::index_2d_to_1d( int i1, int i2, int n2)\n\t{\n\t/* converts a 2D array index into a flat 1D index */\n\t      int idx = n2*i1 + i2;\n\n\t      return idx;\n\t}\n\n\tint Adapt3DInterpolator::point_within_grid( const float& c0, const float& c1, const float& c2)\n\t{\n\t\t/*\n\t\t!\n\t\t! This function test to see if the given point (coord) is inside\n\t\t! the grid bounds. This function requires specific knowledge of the\n\t\t! grid type and range. It will need a customized function for each model\n\t\t! used with this search.\n\t\t*/\n\n\n\t      float  radius;\n\t      int within_bounds = 1;\n\n\t      radius=std::sqrt(c0*c0+c1*c1+c2*c2);\n\t      if(c0 < this->smartSearchValues->xl_gr)\n\t      {\n\t    \t  return 0;\n\n\t      } else if(c0 > this->smartSearchValues->xr_gr)\n\t      {\n\t    \t  return 0;\n\n\t      } else if (c1 < this->smartSearchValues->yl_gr)\n\t      {\n\t    \t  return 0;\n\n\t      } else if (c1 > this->smartSearchValues->yr_gr)\n\t      {\n\t    \t  return 0;\n\n\n\t      } else if(c2 < this->smartSearchValues->zl_gr)\n\t      {\n\t    \t  return 0;\n\n\n\t      } else if(c2 > this->smartSearchValues->zr_gr)\n\t      {\n\t    \t  return 0;\n\n\n\t      }\n\t      if(radius < INNER_RADIUS) return 0;\n\t      if(radius > OUTER_RADIUS) return 0;\n\n\n\t      return within_bounds;\n\n\n\t}\n\n\tint Adapt3DInterpolator::point_within_grid( const float * scoord )\n\t{\n\t\t/*\n\t\t!\n\t\t! This function test to see if the given point (coord) is inside\n\t\t! the grid bounds. This function requires specific knowledge of the\n\t\t! grid type and range. It will need a customized function for each model\n\t\t! used with this search.\n\t\t*/\n\n\n\t      float  radius;\n\t      int within_bounds = 1;\n\n\t      radius=std::sqrt(scoord[0]*scoord[0]+scoord[1]*scoord[1]+scoord[2]*scoord[2]);\n\t      if(scoord[0] < this->smartSearchValues->xl_gr)\n\t      {\n\t    \t  within_bounds = 0;\n\n\t    \t  std::cerr << \"scoord[0]: \" << scoord[0] << \" < \" << this->smartSearchValues->xl_gr << std::endl;\n\t      } else if(scoord[0] > this->smartSearchValues->xr_gr)\n\t      {\n\t    \t  within_bounds = 0;\n\t    \t  std::cerr << \"scoord[0]: \" << scoord[0] << \" > \" << this->smartSearchValues->xr_gr << std::endl;\n\t      } else if (scoord[1] < this->smartSearchValues->yl_gr)\n\t      {\n\t    \t  within_bounds = 0;\n\t    \t  std::cerr << \"scoord[1]: \" << scoord[1] << \" < \" << this->smartSearchValues->yl_gr << std::endl;\n\t      } else if (scoord[1] > this->smartSearchValues->yr_gr)\n\t      {\n\t    \t  within_bounds = 0;\n\t    \t  std::cerr << \"scoord[1]: \" << scoord[1] << \" > \" << this->smartSearchValues->yr_gr << std::endl;\n\n\t      } else if(scoord[2] < this->smartSearchValues->zl_gr)\n\t      {\n\t    \t  within_bounds = 0;\n\t    \t  std::cerr << \"scoord[2]: \" << scoord[2] << \" < \" << this->smartSearchValues->zl_gr << std::endl;\n\n\t      } else if(scoord[2] > this->smartSearchValues->zr_gr)\n\t      {\n\t    \t  within_bounds = 0;\n\t    \t  std::cerr << \"scoord[2]: \" << scoord[2] << \" > \" << this->smartSearchValues->zr_sg << std::endl;\n\n\t      }\n\t      if(radius < INNER_RADIUS) within_bounds = 0;\n\t      if(radius > OUTER_RADIUS) within_bounds = 0;\n\n\n\t      return within_bounds;\n\n\t}\n\n\tvoid Adapt3DInterpolator::calculation1(const float& a, const float& b, const float& c, const float& d, const float& e, float& result)\n\t{\n\t\tresult = a*(b*c-d*e);\n\n\t}\n\n\n\n    int Adapt3DInterpolator::chkineln( const float& c0, const float& c1, const float& c2, int ielem , float * shapex)\n\t{\n\n    \t//\n//#define DEBUG\n\t/*\n\t!...  mesh arrays\n\t*/\n\t/*\n\t\tinteger,intent(in) ::  ndimn,npoin,nnode,nelem\n\t\tinteger,intent(in) ::  intmat(nnode,nelem)\n\t\tinteger,intent(in) ::  ielem\n\t\treal*8,intent(in)  ::  coord(ndimn,npoin),cintp(ndimn)\n\n\t\treal*8,intent(out) ::  shapex(nnode)\n\t*/\n\n\t\tint   ipa,ipb,ipc,ipd;\n\t\tint   ierro;\n\t\tfloat xa,ya,za,xba,yba,zba,xca,yca,zca,xda,yda,zda;\n\t\tfloat xpa,ypa,zpa;\n\t\tfloat deter,detin,shmin,shmax;\n\t\tfloat rin11,rin12,rin13;\n\t\tfloat rin21,rin22,rin23;\n\t\tfloat rin31,rin32,rin33;\n\n\n\t/*\n\t!       data tolow/ -0.005 /\n\t!       data tolhi/  1.005 /\n\t!       data   c00/  0.0   /\n\t!       data   c10/  1.0   /\n\t!\n\t!...  this sub sees if element ielem contains point cintp,\n\t!     writing the shape-function values into ==> shape\n\t!\n\t!...  find the local coordinates\n\t!\n\t*/\n\t\tipa = intmat->at(index_2d_to_1d(ielem,0,4));\n\t\tipb = intmat->at(index_2d_to_1d(ielem,1,4));\n\t\tipc = intmat->at(index_2d_to_1d(ielem,2,4));\n\t\tipd = intmat->at(index_2d_to_1d(ielem,3,4));\n\n\t\t//std::cerr << \"npoin: \" << npoin << \" ndimn: \" << ndimn << \" ipa: \" << ipa << \" ipb: \" << ipb << \" ipc: \" << ipc << \" ipd: \" << ipd << std::endl;\n\t\txa  = (*coord)[index_2d_to_1d(ipa,0,3)];\n\t\tya  = (*coord)[index_2d_to_1d(ipa,1,3)];\n\t\tza  = (*coord)[index_2d_to_1d(ipa,2,3)];\n\t\txba = (*coord)[index_2d_to_1d(ipb,0,3)] - xa;\n\t\tyba = (*coord)[index_2d_to_1d(ipb,1,3)] - ya;\n\t\tzba = (*coord)[index_2d_to_1d(ipb,2,3)] - za;\n\t\txca = (*coord)[index_2d_to_1d(ipc,0,3)] - xa;\n\t\tyca = (*coord)[index_2d_to_1d(ipc,1,3)] - ya;\n\t\tzca = (*coord)[index_2d_to_1d(ipc,2,3)] - za;\n\t\txda = (*coord)[index_2d_to_1d(ipd,0,3)] - xa;\n\t\tyda = (*coord)[index_2d_to_1d(ipd,1,3)] - ya;\n\t\tzda = (*coord)[index_2d_to_1d(ipd,2,3)] - za;\n\n\t\tfloat t1 = 0.f;\n\t\tfloat t2 = 0.f;\n\t\tfloat t3 = 0.f;\n\t\tt1 = xba*(yca*zda - zca*yda);\n\t\tt2 = yba*(xca*zda - zca*xda);\n\t\tt3 = zba*(xca*yda - yca*xda);\n\t\t//a*(b*c-d*e);\n//\t\tboost::thread thread1(&Adapt3DInterpolator::calculation1,boost::ref(xba),boost::ref(yca),boost::ref(zda),boost::ref(zca),boost::ref(yda), boost::ref(t1));\n//\t\tboost::thread thread2(&Adapt3DInterpolator::calculation1,boost::ref(yba),boost::ref(xca),boost::ref(zda),boost::ref(zca),boost::ref(xda), boost::ref(t2));\n//\t\tboost::thread thread3(&Adapt3DInterpolator::calculation1,boost::ref(zba),boost::ref(xca),boost::ref(yda),boost::ref(yca),boost::ref(xda), boost::ref(t3));\n//\t\tthread1.join();\n//\t\tthread2.join();\n//\t\tthread3.join();\n\t\t//calculation1(xba,yca,zda,zca,yda, t1);\n\t\t//calculation1(yba,xca,zda,zca,xda, t2);\n\t\t//calculation1(zba,xca,yda,yca,xda, t3);\n\t\t//float deter = xba*(yca*zda-zca*yda) - yba*(xca*zda-zca*xda) + zba*(xca*yda-yca*xda);\n\t\tdeter = t1 - t2 + t3;\n\n\n\t#ifdef DEBUG\n//\t\tstd::cerr << \"xa: \" << xa << \" ya: \" << ya << \" za: \" << za << \" xba: \" << xba;\n//\t\tstd::cerr << \" yba: \" << yba << \" zba: \" << zba << \" xca: \" << xca << \" yca: \" << yca;\n//\t\tstd::cerr << \" zca: \" << zca << \" xda: \" << xda << \" yda: \" << yda << \" zda: \" << zda << std::endl;\n\t\t  printf(\"(*coord)[ipa]= %d %e %e %e \\n\",ipa,(*coord)[index_2d_to_1d(ipa,0, 3)],(*coord)[index_2d_to_1d(ipa,1,3)],(*coord)[index_2d_to_1d(ipa,2,3)]);\n\t\t  std::cerr << \"deter= \" << deter << std::endl;\n\t#endif\n\t/*       detin = c10/deter */\n\t\tdetin = 1.0/deter;\n\n\t\trin11 = detin*(yca*zda-zca*yda);\n\t\trin12 =-detin*(xca*zda-zca*xda);\n\t\trin13 = detin*(xca*yda-yca*xda);\n\t\trin21 =-detin*(yba*zda-zba*yda);\n\t\trin22 = detin*(xba*zda-zba*xda);\n\t\trin23 =-detin*(xba*yda-yba*xda);\n\t\trin31 = detin*(yba*zca-zba*yca);\n\t\trin32 =-detin*(xba*zca-zba*xca);\n\t\trin33 = detin*(xba*yca-yba*xca);\n\n\t\txpa = c0-xa;\n\t\typa = c1-ya;\n\t\tzpa = c2-za;\n\t/*\n\t!...  local coordinates & shape-function values\n\t*/\n\t\tshapex[1] = rin11*xpa + rin12*ypa + rin13*zpa;\n\t\tshapex[2] = rin21*xpa + rin22*ypa + rin23*zpa;\n\t\tshapex[3] = rin31*xpa + rin32*ypa + rin33*zpa;\n\t\tshapex[0] = 1.0 - shapex[1] - shapex[2] - shapex[3];\n\t#ifdef DEBUG\n//\t\t  printf(\"cintp= %e %e %e \\n\",cintp[0],cintp[1],cintp[2]);\n//\t\t  printf(\"xa-za= %e %e %e \\n\",xa,ya,za);\n\t\t  //std::cerr << \"rin11: \" << rin11 << \" xpa: \" << xpa << \" rin12: \" << rin12 << \" ypa: \" << ypa << \" rin13: \" << rin13 << \" zpa: \" << zpa << std::endl;\n\t\tstd::cerr << \"cintp: \" << c0 << \",\" << c1 << \",\" << c2 << std::endl;\n\t\tstd::cerr << \"ielem: \" << ielem << \" shapex = \" << shapex[0] << \" \" << shapex[1] << \" \" << shapex[2] << \" \" << shapex[3] << std::endl;\n\t#endif\n\t/*       shape(1) = c10 - shape(2) - shape(3) - shape(4)\n\t!\n\t!...  max/min of these shape-functions\n\t!\n\t*/\n\t\t//float t = shapex[0] + shapex[1] + shapex[2] + shapex[3];\n\t\tshmin = ccmc::Math::ffindmin(shapex,4);\n\t\tshmax = ccmc::Math::ffindmax(shapex,4);\n\t/*\n\t!...  see if in the element\n\t!\n\t!       if(shmin .ge. tolow .and. shmax .le. tolhi) then\n\t*/\n\t\tif ( (shmin > 0.) && (shmax <= 1.0) && !std::isnan(shapex[0])) {\n\t\t\t   ierro = 0;\n\t\t} else {\n\t\t\t   ierro = 1;\n\t\t}\n\n\t/*\n\t!...  control output\n\t!     write(*,*)' ielem,shmin,shmax,ierro=',ielem,shmin,shmax,ierro\n\t*/\n\n\t#ifdef DEBUG\n\t\tif( ierro == 0) {\n\t\t  printf(\"shmin= %e \\n\",shmin);\n\t\t  printf(\"shmax= %e \\n\",shmax);\n\t\t  printf(\"ierro= %d \\n\",ierro);\n\t\t  printf(\"cintp= %e %e %e \\n\",c0,c1,c2);\n\t\t  printf(\"node 1 = %e %e %e %d \\n\",(*coord)[index_2d_to_1d(ipa,0,3)],(*coord)[index_2d_to_1d(ipa,1,3)],(*coord)[index_2d_to_1d(ipa,2,3)],ipa);\n\t\t  printf(\"node 2 = %e %e %e %d \\n\",(*coord)[index_2d_to_1d(ipb,0,3)],(*coord)[index_2d_to_1d(ipb,1,3)],(*coord)[index_2d_to_1d(ipb,2,3)],ipb);\n\t\t  printf(\"node 3 = %e %e %e %d \\n\",(*coord)[index_2d_to_1d(ipc,0,3)],(*coord)[index_2d_to_1d(ipc,1,3)],(*coord)[index_2d_to_1d(ipc,2,3)],ipc);\n\t\t  printf(\"node 4 = %e %e %e %d \\n\",(*coord)[index_2d_to_1d(ipd,0,3)],(*coord)[index_2d_to_1d(ipd,1,3)],(*coord)[index_2d_to_1d(ipd,2,3)],ipd);\n\t\t }\n\t#endif\n\n\t\t return ierro;\n\n\t/*       end subroutine chkineln */\n\t}\n\n    float Adapt3DInterpolator::interpolate_adapt3d_solution(const float& x, const float& y, const float& z, int ielem, const std::string& variable)\n    {\n    \tfloat missingValue = this->modelReader->getMissingValue();\n    /*\n     * Interpolate values of unkno to position coord in element ielem\n    */\n\n\n           int ipa,ipb,ipc,ipd;\n           int iv;\n           float x1,y1,z1;\n           float x2,y2,z2;\n           float x3,y3,z3;\n           float x4,y4,z4;\n           float vol,vol6;\n           float a1,b1,c1,d1;\n           float a2,b2,c2,d2;\n           float a3,b3,c3,d3;\n           float a4,b4,c4,d4;\n           float f1,f2,f3,f4;\n\n\n           ipa = intmat->at(index_2d_to_1d(ielem,0,4));\n           ipb = intmat->at(index_2d_to_1d(ielem,1,4));\n           ipc = intmat->at(index_2d_to_1d(ielem,2,4));\n           ipd = intmat->at(index_2d_to_1d(ielem,3,4));\n           x1 = (*coord)[index_2d_to_1d(ipa,0,3)];\n           y1 = (*coord)[index_2d_to_1d(ipa,1,3)];\n           z1 = (*coord)[index_2d_to_1d(ipa,2,3)];\n           x2 = (*coord)[index_2d_to_1d(ipb,0,3)];\n           y2 = (*coord)[index_2d_to_1d(ipb,1,3)];\n           z2 = (*coord)[index_2d_to_1d(ipb,2,3)];\n           x3 = (*coord)[index_2d_to_1d(ipc,0,3)];\n           y3 = (*coord)[index_2d_to_1d(ipc,1,3)];\n           z3 = (*coord)[index_2d_to_1d(ipc,2,3)];\n           x4 = (*coord)[index_2d_to_1d(ipd,0,3)];\n           y4 = (*coord)[index_2d_to_1d(ipd,1,3)];\n           z4 = (*coord)[index_2d_to_1d(ipd,2,3)];\n\n\n\n    #ifdef TEST_CASE1\n           x1=0.;\n           y1=0.;\n           z1=0.;\n           x2=1.;\n           y2=0.;\n           z2=0.;\n           x3=0.;\n           y3=2.;\n           z3=0.;\n           x4=0.;\n           y4=0.;\n           z4=3.;\n    #endif\n\n//    #ifdef LINEAR_INTERPOL\n           a1 = x2*(y3*z4-z3*y4)+y2*(z3*x4-z4*x3)+z2*(x3*y4-x4*y3);\n           b1 = - ( y3*z4-z3*y4 + y2*(z3-z4) + z2*(y4-y3) );\n           c1 = - ( x2*(z4-z3) + (z3*x4-z4*x3) + z2*(x3-x4) );\n           d1 = - ( x2*(y3-y4) + y2*(x4-x3) + (x3*y4-y3*x4) );\n\n           a2 = x3*(y4*z1-z4*y1)+y3*(z4*x1-z1*x4)+z3*(x4*y1-x1*y4);\n           b2 = - ( y4*z1-z4*y1 + y3*(z4-z1) + z3*(y1-y4) );\n           c2 = - ( x3*(z1-z4) + (z4*x1-z1*x4) + z3*(x4-x1) );\n           d2 = - ( x3*(y4-y1) + y3*(x1-x4) + (x4*y1-y4*x1) );\n\n           a3 = x4*(y1*z2-z1*y2)+y4*(z1*x2-z2*x1)+z4*(x1*y2-x2*y1);\n           b3 = - ( y1*z2-z1*y2 + y4*(z1-z2) + z4*(y2-y1) );\n           c3 = - ( x4*(z2-z1) + (z1*x2-z2*x1) + z4*(x1-x2) );\n           d3 = - ( x4*(y1-y2) + y4*(x2-x1) + (x1*y2-y1*x2) );\n\n           a4 = x1*(y2*z3-z2*y3)+y1*(z2*x3-z3*x2)+z1*(x2*y3-x3*y2);\n           b4 = - ( y2*z3-z2*y3 + y1*(z2-z3) + z1*(y3-y2) );\n           c4 = - ( x1*(z3-z2) + (z2*x3-z3*x2) + z1*(x2-x3) );\n           d4 = - ( x1*(y2-y3) + y1*(x3-x2) + (x2*y3-y2*x3) );\n\n           vol6 = a1 + x1*b1 + y1*c1 + z1*d1;\n           vol  = vol6/6.;\n\n    #ifdef TEST_CASE1\n           printf(\"Volume = %e\\n\",vol);\n           printf(\"Correct Volume should be 1.0\\n\");\n    #endif\n\n           const std::vector<float> * vData = modelReader->getVariableFromMap(variable);\n           if (vData == NULL || vData->size() == 0)\n           {\n        \t   std::cerr << \"missing value\" << std::endl;\n        \t   return missingValue;\n           }\n          /* for ( iv=0; iv<9; iv++) {\n\n             unkno_local[iv] = 0.;\n             f1 =  (a1 + b1*x + c1*y + d1*z)/vol6;\n             f2 = -(a2 + b2*x + c2*y + d2*z)/vol6;\n             f3 =  (a3 + b3*x + c3*y + d3*z)/vol6;\n             f4 = -(a4 + b4*x + c4*y + d4*z)/vol6;\n\n             unkno_local[iv] = f1*(*unkno)[ index_2d_to_1d(ipa,iv,npoin,NVARS_ADAPT3D))+f2*(*unkno)[ index_2d_to_1d(ipb,iv,npoin,NVARS_ADAPT3D) ]\n                              +f3*(*unkno)[ index_2d_to_1d(ipc,iv,npoin,NVARS_ADAPT3D) ]+f4*(*unkno)[ index_2d_to_1d(ipd,iv,npoin,NVARS_ADAPT3D) ] ;\n\n           }*/\n\n           /*\n            * int Adapt3DInterpolator::index_2d_to_1d( int i1, int i2, int n1, int n2)\n\t\t\t{\n\n\t\t\t\t  int idx = n2*i1 + i2;\n\n\t\t\t\t  return idx;\n\t\t\t}\n    */\n           f1 =  (a1 + b1*x + c1*y + d1*z)/vol6;\n           f2 = -(a2 + b2*x + c2*y + d2*z)/vol6;\n           f3 =  (a3 + b3*x + c3*y + d3*z)/vol6;\n           f4 = -(a4 + b4*x + c4*y + d4*z)/vol6;\n//           std::cout << \"a1: \" << a1 << \" a2: \" << a2 << \" a3: \" << a3 << \" a4: \" << a4 << std::endl;\n//           std::cout << \"b1: \" << b1 << \" b2: \" << b2 << \" b3: \" << b3 << \" b4: \" << b4 << std::endl;\n//           std::cout << \"c1: \" << c1 << \" c2: \" << c2 << \" c3: \" << c3 << \" c4: \" << c4 << std::endl;\n//           std::cout << \"d1: \" << d1 << \" d2: \" << d2 << \" d3: \" << d3 << \" d4: \" << d4 << std::endl;\n#ifdef DEBUG\n           std::cout << \"vol6: \" << vol6 << \" vol: \" << vol << std::endl;\n           std::cout << \"f1: \" << f1 << \" f2: \" << f2 << \" f3: \" << f3 << \" f4: \" << f4 << std::endl;\n           std::cout << \"ipa: \" << ipa << \" ipb: \" << ipb << \" ipc: \" << ipc << \" ipd: \" << ipd << std::endl;\n           std::cout << \"(*vData)[\" << ipa << \"] \" << (*vData)[ ipa ] << std::endl;\n           std::cout << \"(*vData)[\" << ipb << \"] \" << (*vData)[ ipb ] << std::endl;\n           std::cout << \"(*vData)[\" << ipc << \"] \" << (*vData)[ ipc ] << std::endl;\n           std::cout << \"(*vData)[\" << ipd << \"] \" << (*vData)[ ipd ] << std::endl;\n#endif\n\n           return f1*(*vData)[ ipa ]+f2*(*vData)[ ipb ]\n\t\t\t\t +f3*(*vData)[ ipc ]+f4*(*vData)[ ipd ] ;\n\n\n\n\n    /*       end subroutine interpolate_solution  */\n    }\n\n\t/**\n\t * Destructor\n\t */\n\tAdapt3DInterpolator::~Adapt3DInterpolator()\n\t{\n\t\t// TODO Auto-generated destructor stub\n\n\t}\n}\n", "meta": {"hexsha": "337c164634c96d1d0cdbea247a162b0a719891a7", "size": 45452, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/kameleon/src/ccmc/Adapt3DInterpolator.cpp", "max_stars_repo_name": "alexanderbock/Kameleon-Converter", "max_stars_repo_head_hexsha": "6c2e66bfea60b17a369a3615bc1a623bba100a6f", "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": "ext/kameleon/src/ccmc/Adapt3DInterpolator.cpp", "max_issues_repo_name": "alexanderbock/Kameleon-Converter", "max_issues_repo_head_hexsha": "6c2e66bfea60b17a369a3615bc1a623bba100a6f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ext/kameleon/src/ccmc/Adapt3DInterpolator.cpp", "max_forks_repo_name": "alexanderbock/Kameleon-Converter", "max_forks_repo_head_hexsha": "6c2e66bfea60b17a369a3615bc1a623bba100a6f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8825786646, "max_line_length": 181, "alphanum_fraction": 0.5681378157, "num_tokens": 15163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.24961891798924274}}
{"text": "#include <boost/python.hpp>\n#include <numpy/arrayobject.h>\n#include <numpy_eigen.h>\n#include \"fouriertransform.h\"\n\nPyObject* ArminForwardFourierTransform(PyObject *py_ftau, const double beta, \n                                  PyObject *py_ftail, const int num_matsubara) {\n  Eigen::VectorXd ftau, ftail;\n  numpy::from_numpy(py_ftau, ftau);\n  numpy::from_numpy(py_ftail, ftail);\n\n  Eigen::VectorXcd fmat;\n  FourierTransformer fourier(beta, ftail);\n  fourier.Armin_forward_ft(ftau, fmat, num_matsubara);\n  \n  return numpy::to_numpy(fmat);\n}\n\nPyObject* ForwardFourierTransform(PyObject *py_ftau, const double beta, \n                                  PyObject *py_ftail, const int num_matsubara) {\n  Eigen::VectorXd ftau, ftail;\n  numpy::from_numpy(py_ftau, ftau);\n  numpy::from_numpy(py_ftail, ftail);\n\n  Eigen::VectorXcd fmat;\n  FourierTransformer fourier(beta, ftail);\n  fourier.forward_ft(ftau, fmat, num_matsubara);\n  \n  return numpy::to_numpy(fmat);\n}\n\nPyObject* BackwardFourierTransform(PyObject *py_fmat, const double beta, \n                                   PyObject *py_ftail, const int num_tau) {\n  Eigen::VectorXcd fmat;\n  Eigen::VectorXd ftail;\n  numpy::from_numpy(py_fmat, fmat);\n  numpy::from_numpy(py_ftail, ftail);\n\n  Eigen::VectorXd ftau;\n  FourierTransformer fourier(beta, ftail);\n  fourier.backward_ft(fmat, ftau, num_tau);\n  return numpy::to_numpy(ftau);\n}\n\nBOOST_PYTHON_MODULE(fourier)\n{\n  boost::python::def(\"Armin_forward_ft\", ArminForwardFourierTransform);\n  boost::python::def(\"forward_ft\", ForwardFourierTransform);\n  boost::python::def(\"backward_ft\", BackwardFourierTransform);\n}\n", "meta": {"hexsha": "cd3b31e14074deba3cdbe92875b28e847380479f", "size": 1606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppext/cubic_spline_ft/main.cpp", "max_stars_repo_name": "hungdt/scf_dmft", "max_stars_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-06-05T17:44:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:55:13.000Z", "max_issues_repo_path": "cppext/cubic_spline_ft/main.cpp", "max_issues_repo_name": "hungdt/scf_dmft", "max_issues_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppext/cubic_spline_ft/main.cpp", "max_forks_repo_name": "hungdt/scf_dmft", "max_forks_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4901960784, "max_line_length": 80, "alphanum_fraction": 0.7117061021, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24945148725570077}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n */\n\n#include <boost/date_time/gregorian/gregorian.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/physicalConstants.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.h\"\n#include \"Tudat/Basics/timeType.h\"\n\nnamespace tudat\n{\nnamespace basic_astrodynamics\n{\n\n//! Function to get the Julian day on J2000, in double precision.\ntemplate< >\ndouble getJulianDayOnJ2000< double >( )\n{\n    return JULIAN_DAY_ON_J2000;\n}\n\n//! Function to get the Julian day on J2000, in long double precision.\ntemplate< >\nlong double getJulianDayOnJ2000< long double >( )\n{\n    return JULIAN_DAY_ON_J2000_LONG;\n}\n\n//! Function to get the Julian day on zero modified Julian day, in double precision.\ntemplate< >\ndouble getJulianDayOnMjd0< double >( )\n{\n    return JULIAN_DAY_AT_0_MJD;\n}\n\n//! Function to get the Julian day on zero modified Julian day, in long double precision.\ntemplate< >\nlong double getJulianDayOnMjd0< long double >( )\n{\n    return JULIAN_DAY_AT_0_MJD_LONG;\n}\n\n//! Function to get the synchronization Julian day of TT, TCG, and TCB, in double precision.\ntemplate< >\ndouble getTimeOfTaiSynchronizationJulianDay< double >( )\n{\n    return TAI_JULIAN_DAY_AT_TIME_SYNCHRONIZATION;\n}\n\n//! Function to get the synchronization Julian day of TT, TCG, and TCB, in long double precision.\ntemplate< >\nlong double getTimeOfTaiSynchronizationJulianDay< long double >( )\n{\n    return TAI_JULIAN_DAY_AT_TIME_SYNCHRONIZATION_LONG;\n}\n\n//! Function to get the difference between TDB and (TT, TCB and TCB) at TAI_JULIAN_DAY_AT_TIME_SYNCHRONIZATION,\n//! in double precision.\ntemplate< >\ndouble getTdbSecondsOffsetAtSynchronization< double >( )\n{\n    return TDB_SECONDS_OFFSET_AT_SYNCHRONIZATION;\n}\n\n//! Function to get the difference between TDB and (TT, TCB and TCB) at TAI_JULIAN_DAY_AT_TIME_SYNCHRONIZATION,\n//! in long double precision.\ntemplate< >\nlong double getTdbSecondsOffsetAtSynchronization< long double >( )\n{\n    return TDB_SECONDS_OFFSET_AT_SYNCHRONIZATION_LONG;\n}\n\n//! Function to get the offset of TT from TAI (constant by definition), in double precision.\ntemplate< >\ndouble getTTMinusTai< double >( )\n{\n    return TT_MINUS_TAI;\n}\n\n//! Function to get the offset of TT from TAI (constant by definition), in long double precision.\ntemplate< >\nlong double getTTMinusTai< long double >( )\n{\n    return TT_MINUS_TAI_LONG;\n}\n\n//! Function to get the offset of TT from TAI (constant by definition), in Time format.\ntemplate< >\nTime getTTMinusTai< Time>( )\n{\n    return Time( TT_MINUS_TAI_LONG );\n}\n\n\n//! Function to convert julian day to gregorian calendar date.\nboost::gregorian::date convertJulianDayToCalendarDate( const double julianDay )\n{\n    // Declare temporary variables.\n    int L, M, N, P, Q;\n\n    // Declare date variables.\n    int day, month, year;\n\n    // Execute algorithm.\n    double shiftedJulianDay = julianDay + 0.5;\n    if( shiftedJulianDay > 2299160 )    // after Oct 4, 1582\n    {\n        L = shiftedJulianDay + 68569;\n        M = (4 * L) / 146097;\n        L = L - ((146097 * M + 3) / 4);\n        N = (4000 * (L + 1)) / 1461001;\n        L = L - ((1461 * N) / 4) + 31;\n        P = (80 * L) / 2447;\n        day = int(L - (2447 * P) / 80);\n        L = P / 11;\n        month = int(P + 2 - 12 * L);\n        year = int(100 * (M - 49) + N + L);\n    }\n    else\n    {\n        P = shiftedJulianDay + 1402;\n        Q = (P - 1) / 1461;\n        L = P - 1461 * Q;\n        M = (L - 1) / 365 - L / 1461;\n        N = L - 365 * M + 30;\n        P = (80 * N) / 2447;\n        day = int(N - (2447 * P) / 80);\n        N = P / 11;\n        month = int( P + 2 - 12 * N );\n        year = int( 4 * Q + M + N - 4716 );\n        if(year <= 0)\n        {\n            --year;\n        }\n    }\n    // catch century/non-400 non-leap years\n    if( year > 1599 && !( year % 100 )\n            && ( year % 400 ) && month == 2 && day == 29 )\n    {\n        month = 3;\n        day = 1;\n    }\n\n    // Create and return date object\n\n    return boost::gregorian::date( year, month, static_cast< double >( day ) );\n}\n\n\n//! Function to determine whether the given year is a leap year (i.e. has 366 days)\nbool isLeapYear( const int year )\n{\n    bool isLeapYear = 0;\n    if( ( year % 4 == 0 ) && !( ( year % 100 == 0 ) && !( year % 400 == 0 ) ) )\n    {\n        isLeapYear = 1;\n    }\n    return isLeapYear;\n}\n\n//! Function that returns number of days in given month number\nint getDaysInMonth( const int month,\n                    const int year )\n{\n    // Declare number of days per month\n    static const int daysPerMonth[ 12 ] =\n    { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n    int numberOfDays = 0;\n\n    // Check input consistency\n    if( month < 1 || month > 12 )\n    {\n        throw std::runtime_error( \"Error, month number \" + std::to_string( month ) +\n                                  \" does not exist, value must be gretaer than 0 and smaller than 13\" );\n    }\n    else\n    {\n        numberOfDays = daysPerMonth[ month - 1 ];\n\n        // Check for leap year.\n        if( month == 2 && isLeapYear( year ) )\n        {\n            numberOfDays++;\n        }\n    }\n    return numberOfDays;\n}\n\n//! Determine number of full days that have passed in current year\nint convertDayMonthYearToDayOfYear( const int day,\n                                    const int month,\n                                    const int year )\n{\n    return convertDayMonthYearToDayOfYear( boost::gregorian::date( year, month, day ) );\n}\n\n//! Determine number of full days that have passed in current year\nint convertDayMonthYearToDayOfYear( const boost::gregorian::date calendarDate )\n{\n    // Calculate and return result (taking into account that this function should return 0 for first day, not 1)\n    return ( calendarDate.day_of_year( ) - 1 );\n}\n\n//! Determine number of seconds into current day of given time\ndouble calculateSecondsInCurrentJulianDay( const double julianDay )\n{\n    // Calculate and return result, taking into accoun the fact that julian day 0.0 is at 12:00 and result starts counting at 00:00\n    return ( julianDay + 0.5 - std::floor( julianDay + 0.5 ) ) * physical_constants::JULIAN_DAY;\n}\n\n//! Function to create the calendar date from the year and the number of days in the year\nboost::gregorian::date convertYearAndDaysInYearToDate( const int year, const int daysInYear )\n{\n    // Go to day 1 at 01-01 convention\n    int daysLeft = daysInYear + 1;\n\n    // Loop over all months (starting at January until month in which daysinYear is situated is found)\n    int currentMonth = 1;\n    int daysInCurrentMonth;\n    bool isConverged = 0;\n    while( !isConverged )\n    {\n        // Determine days in current month\n        daysInCurrentMonth = getDaysInMonth( currentMonth, year );\n        if( daysInCurrentMonth < daysLeft )\n        {\n            // Subtract days in current month from days left.\n            daysLeft -= daysInCurrentMonth;\n\n            // Update month and check consistency\n            currentMonth++;\n            if( currentMonth > 12 )\n            {\n                throw std::runtime_error(\n                            \"Error when converting year and days in year to date, month number has exceeded 12\" );\n            }\n        }\n        else\n        {\n            isConverged = 1;\n        }\n    }\n\n    // Create date and return\n    boost::gregorian::date date( year, currentMonth, daysLeft );\n\n    if( date.day_of_year( ) != daysInYear + 1 )\n    {\n        throw std::runtime_error(\n                    \"Error when converting year and days in year to date, inconsistent output\" );\n    }\n\n    return date;\n}\n\n//! Perform apprixmate conversion of TT to TDB\ndouble approximateConvertTTtoTDB( const double ttSecondsSinceJ2000 )\n{\n    double ttCenturiesSinceJ2000 = ttSecondsSinceJ2000 / ( 100.0 * physical_constants::JULIAN_YEAR );\n    return ttSecondsSinceJ2000 + 0.001657  * std::sin( 628.3076 * ttCenturiesSinceJ2000 + 6.2401 );\n}\n\n\n} // namespace basic_astrodynamics\n} // namespace tudat\n", "meta": {"hexsha": "5767c64f96cbeaa4b300385adcf1baf015e12f2e", "size": 8324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.cpp", "max_stars_repo_name": "sebranchett/tudat", "max_stars_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.cpp", "max_issues_repo_name": "sebranchett/tudat", "max_issues_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/BasicAstrodynamics/timeConversions.cpp", "max_forks_repo_name": "sebranchett/tudat", "max_forks_repo_head_hexsha": "24e5f3cc85c250fcbed0aac37f026c1dd7fd6c44", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3795620438, "max_line_length": 131, "alphanum_fraction": 0.6370735223, "num_tokens": 2273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24943366841632944}}
{"text": "//=============================================================================================================\n/**\n * @file     icp.cpp\n * @author   Ruben Dörfel <doerfelruben@aol.com>\n * @since    0.1.5\n * @date     July, 2020\n *\n * @section  LICENSE\n *\n * Copyright (C) 2020, Ruben Dörfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n *       following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n *       the following disclaimer in the documentation and/or other materials provided with the distribution.\n *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n *       to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, 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 INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief    ICP class definition.\n *\n */\n\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"icp.h\"\n#include <iostream>\n\n#include \"fiff/fiff_coord_trans.h\"\n#include \"mne/mne_project_to_surface.h\"\n\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QSharedPointer>\n#include <QDebug>\n\n//=============================================================================================================\n// EIGEN INCLUDES\n//=============================================================================================================\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Eigenvalues>\n#include <Eigen/Geometry>\n\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace MNELIB;\nusing namespace RTPROCESSINGLIB;\nusing namespace Eigen;\nusing namespace FIFFLIB;\n\n//=============================================================================================================\n// DEFINE GLOBAL METHODS\n//=============================================================================================================\n\nbool RTPROCESSINGLIB::performIcp(const MNEProjectToSurface::SPtr mneSurfacePoints,\n                                 const Eigen::MatrixXf& matPointCloud,\n                                 FiffCoordTrans& transFromTo,\n                                 float& fRMSE,\n                                 bool bScale,\n                                 int iMaxIter,\n                                 float fTol,\n                                 const VectorXf& vecWeitgths)\n/**\n * Follow notation of P.J. Besl and N.D. McKay, A Method for\n * Registration of 3-D Shapes, IEEE Trans. Patt. Anal. Machine Intell., 14,\n * 239 - 255, 1992.\n */\n{\n    if(matPointCloud.rows() == 0){\n        qWarning() << \"[RTPROCESSINGLIB::icp] Passed point cloud is empty.\";\n        return false;\n    }\n\n    // Initialization\n    int iNP = matPointCloud.rows();             // The number of points\n    float fMSEPrev,fMSE = 0.0;                  // The mean square error\n    float fScale = 1.0;\n    MatrixXf matP0 = matPointCloud;             // Initial Set of points\n    MatrixXf matPk = matP0;                     // Transformed Set of points\n    MatrixXf matYk(matPk.rows(),matPk.cols());  // Iterative closest points on the surface\n    MatrixXf matDiff = matYk;\n    VectorXf vecSE(matDiff.rows());\n    Matrix4f matTrans;                          // the transformation matrix\n    VectorXi vecNearest;                        // Triangle of the new point\n    VectorXf vecDist;                           // The Distance between matX and matP\n\n    // Initial transformation - From point cloud To surface\n    FiffCoordTrans transICP = transFromTo;\n    matPk = transICP.apply_trans(matPk);\n\n    // Icp algorithm:\n    for(int iIter = 0; iIter < iMaxIter; ++iIter) {\n\n        // Step a: compute the closest point on the surface; eq 29\n        if(!mneSurfacePoints->mne_find_closest_on_surface(matPk, iNP, matYk, vecNearest, vecDist)) {\n            qWarning() << \"[RTPROCESSINGLIB::icp] mne_find_closest_on_surface was not sucessfull.\";\n            return false;\n        }\n\n        // Step b: compute the registration; eq 30\n        if(!fitMatchedPoints(matP0, matYk, matTrans, fScale, bScale, vecWeitgths)) {\n            qWarning() << \"[RTPROCESSINGLIB::icp] point cloud registration not succesfull\";\n        }\n\n        // Step c: apply registration\n        transICP.trans = matTrans;\n        matPk = transICP.apply_trans(matP0);\n\n        // step d: compute mean-square-error and terminate if below fTol\n        vecDist = vecDist.cwiseProduct(vecDist);\n        fMSE = vecDist.sum() / iNP;\n        fRMSE = std::sqrt(fMSE);\n\n        if(std::sqrt(std::fabs(fMSE - fMSEPrev)) < fTol) {\n            transFromTo = transICP;\n            qInfo() << \"[RTPROCESSINGLIB::icp] ICP was succesfull and exceeded after \" << iIter +1 << \" Iterations with RMSE dist: \" << fRMSE * 1000 << \" mm.\";\n            return true;\n        }\n        fMSEPrev = fMSE;\n        qInfo() << \"[RTPROCESSINGLIB::icp] ICP iteration \" << iIter + 1 << \" with RMSE: \" << fRMSE * 1000 << \" mm.\";\n    }\n    transFromTo = transICP;\n\n    qWarning() << \"[RTPROCESSINGLIB::icp] Maximum number of \" << iMaxIter << \" Iterations exceeded with RMSE: \" << fRMSE * 1000 << \" mm.\";\n    return true;\n}\n\n//=============================================================================================================\n\nbool RTPROCESSINGLIB::fitMatchedPoints(const MatrixXf& matSrcPoint,\n                                       const MatrixXf& matDstPoint,\n                                       Eigen::Matrix4f& matTrans,\n                                       float fScale,\n                                       bool bScale,\n                                       const VectorXf& vecWeitgths)\n/**\n * Follow notation of P.J. Besl and N.D. McKay, A Method for\n * Registration of 3-D Shapes, IEEE Trans. Patt. Anal. Machine Intell., 14,\n * 239 - 255, 1992.\n *\n * The code is further adapted from MNE Python function _fitMatched_points(...).\n */\n{\n    // init values\n    MatrixXf matP = matSrcPoint;\n    MatrixXf matX = matDstPoint;\n    VectorXf vecW = vecWeitgths;\n    VectorXf vecMuP;                                // column wise mean - center of mass\n    VectorXf vecMuX;                                // column wise mean - center of mass\n    MatrixXf matDot;\n    MatrixXf matSigmaPX;                            // cross-covariance\n    MatrixXf matAij;                                // Anti-Symmetric matrix\n    Vector3f vecDelta;                              // column vector, elements of matAij\n    Matrix4f matQ = Matrix4f::Identity(4,4);\n    Matrix3f matScale = Matrix3f::Identity(3,3);    // scaling matrix\n    Matrix3f matRot = Matrix3f::Identity(3,3);\n    Vector3f vecTrans;\n    float fTrace = 0.0;\n    fScale = 1.0;\n\n    // test size of point clouds\n    if(matSrcPoint.size() != matDstPoint.size()) {\n        qWarning() << \"[RTPROCESSINGLIB::fitMatched] Point clouds do not match.\";\n        return false;\n    }\n\n    // get center of mass\n    if(vecWeitgths.isZero()) {\n        vecMuP = matP.colwise().mean(); // eq 23\n        vecMuX = matX.colwise().mean();\n        matDot = matP.transpose() * matX;\n        matDot = matDot / matP.rows();\n    } else {\n        vecW = vecWeitgths / vecWeitgths.sum();\n        vecMuP = vecW.transpose() * matP;\n        vecMuX = vecW.transpose() * matX;\n\n        MatrixXf matXWeighted = matX;\n        for(int i = 0; i < (vecW.size()); ++i) {\n            matXWeighted.row(i) = matXWeighted.row(i) * vecW(i);\n        }\n        matDot = matP.transpose() * (matXWeighted);\n    }\n\n    // get cross-covariance\n    matSigmaPX = matDot - (vecMuP * vecMuX.transpose());  // eq 24\n    matAij = matSigmaPX - matSigmaPX.transpose();\n    vecDelta(0) = matAij(1,2); vecDelta(1) = matAij(2,0); vecDelta(2) = matAij(0,1);\n    fTrace = matSigmaPX.trace();\n    matQ(0,0) = fTrace; // eq 25\n    matQ.block(0,1,1,3) = vecDelta.transpose();\n    matQ.block(1,0,3,1) = vecDelta;\n    matQ.block(1,1,3,3) = matSigmaPX + matSigmaPX.transpose() - fTrace * MatrixXf::Identity(3,3);\n\n    // unit eigenvector coresponding to maximum eigenvalue of matQ is selected as optimal rotation quaterions q0,q1,q2,q3\n    SelfAdjointEigenSolver<MatrixXf> es(matQ);\n    Vector4f vecEigVec = es.eigenvectors().col(matQ.cols()-1);  // only take last Eigen-Vector since this corresponds to the maximum Eigenvalue\n\n    // quatRot(w,x,y,z)\n    Quaternionf quatRot(vecEigVec(0),vecEigVec(1),vecEigVec(2),vecEigVec(3));\n    quatRot.normalize();\n    matRot = quatRot.matrix();\n\n    // get scaling factor and matrix\n    if(bScale) {\n        MatrixXf matDevX = matX.rowwise() - vecMuX.transpose();\n        MatrixXf matDevP = matP.rowwise() - vecMuP.transpose();\n        matDevX = matDevX.cwiseProduct(matDevX);\n        matDevP = matDevP.cwiseProduct(matDevP);\n\n        if(!vecWeitgths.isZero()) {\n            for(int i = 0; i < (vecW.size()); ++i) {\n                matDevX.row(i) = matDevX.row(i) * vecW(i);\n                matDevP.row(i) = matDevP.row(i) * vecW(i);\n            }\n        }\n        // get scaling factor and set scaling matrix\n        fScale = std::sqrt(matDevX.sum() / matDevP.sum());\n        matScale *= fScale;\n    }\n\n    // get translation and Rotation\n    vecTrans = vecMuX - fScale * matRot * vecMuP;\n    matRot *= matScale;\n\n    matTrans.block<3,3>(0,0) = matRot;\n    matTrans.block<3,1>(0,3) = vecTrans;\n    matTrans(3,3) = 1.0f;\n    matTrans.block<1,3>(3,0) = MatrixXf::Zero(1,3);\n    return true;\n}\n\n//=========================================================================================================\n\nbool RTPROCESSINGLIB::discard3DPointOutliers(const QSharedPointer<MNELIB::MNEProjectToSurface> mneSurfacePoints,\n                                             const MatrixXf& matPointCloud,\n                                             const FiffCoordTrans& transFromTo,\n                                             VectorXi& vecTake,\n                                             MatrixXf& matTakePoint,\n                                             float fMaxDist)\n{\n    // Initialization\n    int iNP = matPointCloud.rows();               // The number of points\n    MatrixXf matP = matPointCloud;                // Initial Set of points\n    MatrixXf matYk(matPointCloud.rows(),matPointCloud.cols());  // Iterative losest points on the surface\n    VectorXi vecNearest;                        // Triangle of the new point\n    VectorXf vecDist;                           // The Distance between matX and matP\n\n    // Initial transformation - From point cloud To surface\n    matP = transFromTo.apply_trans(matP);\n\n    int iDiscarded = 0;\n\n    // discard outliers if necessary\n    if(fMaxDist > 0.0) {\n        if(!mneSurfacePoints->mne_find_closest_on_surface(matP, iNP, matYk, vecNearest, vecDist)) {\n            qWarning() << \"[RTPROCESSINGLIB::icp] mne_find_closest_on_surface was not sucessfull.\";\n            return false;\n        }\n\n        for(int i = 0; i < vecDist.size(); ++i) {\n            if(std::fabs(vecDist(i)) < fMaxDist) {\n                vecTake.conservativeResize(vecTake.size()+1);\n                vecTake(vecTake.size()-1) = i;\n                matTakePoint.conservativeResize(matTakePoint.rows()+1,3);\n                matTakePoint.row(matTakePoint.rows()-1) = matPointCloud.row(i);\n            } else {\n                iDiscarded++;\n            }\n        }\n    }\n    qInfo() << \"[RTPROCESSINGLIB::discardOutliers] \" << iDiscarded << \"digitizers discarded.\";\n    return true;\n}\n\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n", "meta": {"hexsha": "1be4bf932cf43c81baa0e150ee8b70e7e56a2e2e", "size": 13115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/rtprocessing/icp.cpp", "max_stars_repo_name": "ultrapre/mne-cpp", "max_stars_repo_head_hexsha": "7036b112a5573bd9ab9c54d9fe22c3eea2c03725", "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": "libraries/rtprocessing/icp.cpp", "max_issues_repo_name": "ultrapre/mne-cpp", "max_issues_repo_head_hexsha": "7036b112a5573bd9ab9c54d9fe22c3eea2c03725", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/rtprocessing/icp.cpp", "max_forks_repo_name": "ultrapre/mne-cpp", "max_forks_repo_head_hexsha": "7036b112a5573bd9ab9c54d9fe22c3eea2c03725", "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": 44.0100671141, "max_line_length": 159, "alphanum_fraction": 0.5245139154, "num_tokens": 3058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.24925380755045357}}
{"text": "/*\n Copyright (C) 2017 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <boost/make_shared.hpp>\n#include <iostream>\n#include <ql/math/interpolations/bilinearinterpolation.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yield/forwardcurve.hpp>\n#include <qle/termstructures/blackvariancesurfacesparse.hpp>\n\nusing namespace std;\n\nnamespace QuantExt {\n\nstruct CloseEnoughComparator {\n    explicit CloseEnoughComparator(const Real v) : v_(v) {}\n    bool operator()(const Real w) const { return close_enough(v_, w); }\n    Real v_;\n};\n\nBlackVarianceSurfaceSparse::BlackVarianceSurfaceSparse(const QuantLib::Date& referenceDate, const Calendar& cal,\n                                                       const std::vector<Date>& dates, const std::vector<Real>& strikes,\n                                                       const std::vector<Volatility>& volatilities,\n                                                       const DayCounter& dayCounter)\n    : BlackVarianceTermStructure(referenceDate, cal), dayCounter_(dayCounter) {\n\n    QL_REQUIRE((strikes.size() == dates.size()) && (dates.size() == volatilities.size()),\n               \"dates, strikes and volatilities vectors not of equal size.\");\n\n    // first get uniques dates and sort\n    set<Date> datesSet(dates.begin(), dates.end());\n    datesSet.insert(this->referenceDate());\n    expiries_ = vector<Date>(datesSet.begin(), datesSet.end());\n    vector<bool> dateDone(expiries_.size(), false);\n    times_ = vector<Time>(expiries_.size());\n    interpolations_ = vector<Interpolation>(expiries_.size());\n    variances_ = vector<vector<Real> >(expiries_.size());\n    strikes_ = vector<vector<Real> >(expiries_.size());\n\n    // Populate expiry info. (Except interpolation obj members)\n    for (Size i = 0; i < dates.size(); i++) {\n        vector<Date>::iterator found = find(expiries_.begin(), expiries_.end(), dates[i]);\n        QL_REQUIRE(found != expiries_.end(), \"Date should already be loaded\" << dates[i]);\n        ptrdiff_t ii;\n        ii = distance(expiries_.begin(), found); // index of expiry\n\n        if (!dateDone[ii]) {\n            // add expiry data if not found\n            QL_REQUIRE(dates[i] > referenceDate,\n                       \"Expiry date:\" << dates[i] << \" not after asof date: \" << referenceDate);\n            times_[ii] = timeFromReference(dates[i]);\n            strikes_[ii].push_back(strikes[i]);\n            variances_[ii].push_back(volatilities[i] * volatilities[i] * times_[ii]);\n            dateDone[ii] = true;\n        } else {\n            // expiry found => add if strike not found\n            Real tmpStrike = strikes[i];\n            vector<Real>::iterator fnd =\n                find_if(strikes_[ii].begin(), strikes_[ii].end(), CloseEnoughComparator(tmpStrike));\n            if (fnd == strikes_[ii].end()) {\n                // add strike/var pairs if strike not found for this expiry\n                strikes_[ii].push_back(strikes[i]);\n                variances_[ii].push_back(volatilities[i] * volatilities[i] * times_[ii]);\n            }\n        }\n    }\n\n    for (Size i = 1; i < expiries_.size(); i++) {\n        QL_REQUIRE(strikes_[i].size() == variances_[i].size(),\n                   \"different number of variances and strikes for date: \" << expiries_[i]);\n    }\n\n    // Short end\n    QL_REQUIRE(expiries_[0] == this->referenceDate(), \"First date should be reference date. Reference date: \"\n                                                       << this->referenceDate() << \"First date: \" << expiries_[0]);\n\n    times_[0] = 0.0;\n    vector<Real> tmpStrkVect;\n    vector<Real> tmpVarVect;\n    tmpStrkVect.push_back(5.0);\n    tmpStrkVect.push_back(100.0);\n    tmpVarVect.push_back(0.0);\n    tmpVarVect.push_back(0.0);\n    strikes_[0] = tmpStrkVect;\n    variances_[0] = tmpVarVect;\n\n    // set expiries' interpolations.\n    for (Size i = 0; i < expiries_.size(); i++) {\n        // sort strikes within this expiry\n        vector<pair<Real, Real> > tmpPairs(strikes_[i].size());\n        vector<Real> sortedStrikes; //(itr->second.expStrikes_.size());\n        vector<Real> sortedVars;    // (sortedStrikes)\n        for (Size j = 0; j < strikes_[i].size(); j++) {\n            tmpPairs[j] = pair<Real, Real>(strikes_[i][j], variances_[i][j]);\n        }\n        sort(tmpPairs.begin(), tmpPairs.end());         // sorts according to frist. (strikes)\n        for (vector<pair<Real, Real> >::iterator it = tmpPairs.begin(); it != tmpPairs.end(); it++) {\n            sortedStrikes.push_back(it->first);\n            sortedVars.push_back(it->second);\n        }\n        strikes_[i] = sortedStrikes;\n        variances_[i] = sortedVars;\n    \n        // set interpolation\n        if (strikes_[i].size() == 1) {\n            // if only one strike => add different strike with same value for interpolation object.\n            strikes_[i].push_back(strikes_[i][0] + strikes_[i][0] * 2);\n            variances_[i].push_back(variances_[i][0]);\n        }\n        LinearInterpolation tmpInterpolation(strikes_[i].begin(), strikes_[i].end(), variances_[i].begin());\n        interpolations_[i] = tmpInterpolation;\n    }\n\n} // namespace QuantExt\n\nReal BlackVarianceSurfaceSparse::getVarForStrike(Real strike, const vector<Real>& strks, const vector<Real>& vars,\n                                                 const Interpolation& intrp) const {\n\n    Real retVar;\n    if (strike > strks.back()) {\n        retVar = vars.back(); // flat extrapolate far stirke\n    } else if (strike < strks.front()) {\n        retVar = vars.front(); // flat extrapolate near stirke\n    } else {\n        retVar = intrp(strike); // interpolate between strikes\n    }\n    return retVar;\n}\n\nReal BlackVarianceSurfaceSparse::blackVarianceImpl(Time t, Real strike) const {\n\n    QL_REQUIRE(t >= 0, \"Variance requested for date before reference date: \" << this->referenceDate());\n    Real varReturn;\n    if (t == 0.0) {\n        //requested at reference date\n        varReturn = variances_[0][0];\n    } else if (t <= times_.back()) {\n        //requested between existing expiries (interpolate between expiries)\n        ptrdiff_t dt;       // index for point after requested\n        ptrdiff_t dtPrev;   // index for point before requested\n        dt = distance(times_.begin(), lower_bound(times_.begin(), times_.end(), t));\n        dtPrev = (dt != 0) ? dt - 1 : 0;\n        // interpolate between expiries\n        vector<Real> tmpVars(2);\n        vector<Time> xAxis;\n        xAxis.push_back(times_[dtPrev]);\n        xAxis.push_back(times_[dt]);\n        tmpVars[1] = getVarForStrike(strike, strikes_[dt], variances_[dt], interpolations_[dt]);\n        tmpVars[0] = getVarForStrike(strike, strikes_[dtPrev], variances_[dtPrev], interpolations_[dtPrev]);\n        LinearInterpolation tmpInterpolation(xAxis.begin(), xAxis.end(), tmpVars.begin());\n        varReturn = tmpInterpolation(t);\n    } else {\n        // far end of expiries\n        varReturn = getVarForStrike(strike, strikes_.back(), variances_.back(), interpolations_.back());\n        varReturn = varReturn * t / times_.back(); // scale\n    } \n    return varReturn;\n}\n} // namespace QuantExt", "meta": {"hexsha": "49c4c7941eba5a586f08348bd1e935a0414af911", "size": 7845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/blackvariancesurfacesparse.cpp", "max_stars_repo_name": "PiotrSiejda/Engine", "max_stars_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "QuantExt/qle/termstructures/blackvariancesurfacesparse.cpp", "max_issues_repo_name": "PiotrSiejda/Engine", "max_issues_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/termstructures/blackvariancesurfacesparse.cpp", "max_forks_repo_name": "PiotrSiejda/Engine", "max_forks_repo_head_hexsha": "8360b5de32408f2a37da5ac3ca7b4e913bf67e9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-07T02:04:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T02:04:10.000Z", "avg_line_length": 44.8285714286, "max_line_length": 120, "alphanum_fraction": 0.6243467177, "num_tokens": 1906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2491749429814666}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2007 Ferdinando Ametrano\n Copyright (C) 2007 Marco Bianchetti\n Copyright (C) 2006, 2007 Giorgio Facchinetti\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/termstructures/volatility/swaption/cmsmarket.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/cashflows/cashflows.hpp>\n#include <ql/instruments/makecms.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/indexes/swapindex.hpp>\n#include <ql/instruments/swap.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing std::vector;\nusing boost::shared_ptr;\n\nnamespace QuantLib {\n\n    CmsMarket::CmsMarket(\n        const vector<Period>& swapLengths,\n        const vector<shared_ptr<SwapIndex> >& swapIndexes,\n        const shared_ptr<IborIndex>& iborIndex,\n        const vector<vector<Handle<Quote> > >& bidAskSpreads,\n        const vector<shared_ptr<CmsCouponPricer> >& pricers,\n        const Handle<YieldTermStructure>& discountingTS)\n    : swapLengths_(swapLengths),\n      swapIndexes_(swapIndexes),\n      iborIndex_(iborIndex),\n      bidAskSpreads_(bidAskSpreads),\n      pricers_(pricers),\n      discTS_(discountingTS),\n\n      nExercise_(swapLengths_.size()),\n      nSwapIndexes_(swapIndexes_.size()),\n      swapTenors_(nSwapIndexes_),\n\n      spotFloatLegNPV_(nExercise_, nSwapIndexes_),\n      spotFloatLegBPS_(nExercise_, nSwapIndexes_),\n\n      mktBidSpreads_(nExercise_, nSwapIndexes_),\n      mktAskSpreads_(nExercise_, nSwapIndexes_),\n\n      mktSpreads_(nExercise_, nSwapIndexes_),\n      mdlSpreads_(nExercise_, nSwapIndexes_),\n      errSpreads_(nExercise_, nSwapIndexes_),\n\n      mktSpotCmsLegNPV_(nExercise_, nSwapIndexes_),\n      mdlSpotCmsLegNPV_(nExercise_, nSwapIndexes_),\n      errSpotCmsLegNPV_(nExercise_, nSwapIndexes_),\n\n      mktFwdCmsLegNPV_(nExercise_, nSwapIndexes_),\n      mdlFwdCmsLegNPV_(nExercise_, nSwapIndexes_),\n      errFwdCmsLegNPV_(nExercise_, nSwapIndexes_),\n\n      spotSwaps_(nExercise_, vector<shared_ptr<Swap> >(nSwapIndexes_)),\n      fwdSwaps_(nExercise_, vector<shared_ptr<Swap> >(nSwapIndexes_))\n    {\n        QL_REQUIRE(2 * nSwapIndexes_ == bidAskSpreads[0].size(),\n                   \"2*nSwapIndexes_ (\" << 2 * nSwapIndexes_\n                                       << \") != bidAskSpreads columns() (\"\n                                       << bidAskSpreads[0].size() << \")\");\n        QL_REQUIRE(nExercise_ == bidAskSpreads.size(),\n                   \"nExercise_ (\" << nExercise_ << \") != bidAskSpreads rows() (\"\n                                  << bidAskSpreads.size() << \")\");\n        QL_REQUIRE(nSwapIndexes_ == pricers.size(),\n                   \"nSwapIndexes_ (\" << nSwapIndexes_ << \") != pricers (\"\n                                     << pricers_.size() << \")\");\n\n        for (Size j=0; j<nSwapIndexes_; ++j) {\n            swapTenors_[j] = swapIndexes_[j]->tenor();\n            // pricers\n            registerWith(pricers_[j]);\n            for (Size i=0; i<nExercise_; ++i) {\n                // market Spread\n                registerWith(bidAskSpreads_[i][j*2]);\n                registerWith(bidAskSpreads_[i][j*2+1]);\n            }\n        }\n\n        Period start(0, Years);\n        for (Size i=0; i<nExercise_; ++i) {\n            if (i>0) start = swapLengths_[i-1];\n            for (Size j=0; j<nSwapIndexes_; ++j) {\n                // never evaluate the spot swap, only its ibor floating leg\n                spotSwaps_[i][j] = MakeCms(swapLengths_[i],\n                                           swapIndexes_[j],\n                                           iborIndex_, 0.0,\n                                           Period())\n                                   .operator shared_ptr<Swap>();\n                fwdSwaps_[i][j]  = MakeCms(swapLengths_[i]-start,\n                                           swapIndexes_[j],\n                                           iborIndex_, 0.0,\n                                           start)\n                                   .withCmsCouponPricer(pricers_[j])\n                                   .withDiscountingTermStructure(discTS_)\n                                   .operator shared_ptr<Swap>();\n            }\n        }\n        // probably useless\n        performCalculations();\n     }\n\n    void CmsMarket::performCalculations() const {\n        for (Size j=0; j<nSwapIndexes_; ++j) {\n          Real mktPrevPart = 0.0, mdlPrevPart = 0.0;\n          for (Size i=0; i<nExercise_; ++i) {\n\n            // **** market\n\n            mktBidSpreads_[i][j] = bidAskSpreads_[i][j*2]->value();\n            mktAskSpreads_[i][j] = bidAskSpreads_[i][j*2+1]->value();\n            mktSpreads_[i][j] = (mktBidSpreads_[i][j]+mktAskSpreads_[i][j])/2;\n\n            const Leg& spotFloatLeg = spotSwaps_[i][j]->leg(1);\n            spotFloatLegNPV_[i][j] = CashFlows::npv(spotFloatLeg,\n                                                    **discTS_,\n                                                    false, discTS_->referenceDate());\n            spotFloatLegBPS_[i][j] = CashFlows::bps(spotFloatLeg,\n                                                    **discTS_,\n                                                    false, discTS_->referenceDate());\n\n            // imply the spot CMS leg NPV from the spot ibor floating leg NPV\n            mktSpotCmsLegNPV_[i][j] = -(spotFloatLegNPV_[i][j] +\n                                spotFloatLegBPS_[i][j]*mktSpreads_[i][j]/1e-4);\n            // fwd CMS legs can be computed as differences between spot legs\n            mktFwdCmsLegNPV_[i][j] = mktSpotCmsLegNPV_[i][j] - mktPrevPart;\n            mktPrevPart = mktSpotCmsLegNPV_[i][j];\n\n            // **** model\n\n            // calculate the forward swap (the time consuming part)\n            mdlFwdCmsLegNPV_[i][j] = fwdSwaps_[i][j]->legNPV(0);\n            errFwdCmsLegNPV_[i][j] = mdlFwdCmsLegNPV_[i][j] -\n                                                mktFwdCmsLegNPV_[i][j];\n\n            // spot CMS legs can be computed as incremental sum of forward legs\n            mdlSpotCmsLegNPV_[i][j] = mdlPrevPart + mdlFwdCmsLegNPV_[i][j];\n            mdlPrevPart = mdlSpotCmsLegNPV_[i][j];\n            errSpotCmsLegNPV_[i][j] = mdlSpotCmsLegNPV_[i][j] -\n                                                mktSpotCmsLegNPV_[i][j];\n\n            // equilibriums spread over ibor leg\n            Real npv = spotFloatLegNPV_[i][j] + mdlSpotCmsLegNPV_[i][j];\n            mdlSpreads_[i][j] = - npv/spotFloatLegBPS_[i][j]*1e-4;\n            errSpreads_[i][j] = mdlSpreads_[i][j] - mktSpreads_[i][j];\n          }\n        }\n    }\n\n    void CmsMarket::reprice(const Handle<SwaptionVolatilityStructure> &v,\n                            Real meanReversion) {\n        Handle<Quote> meanReversionQuote(\n            shared_ptr<Quote>(boost::make_shared<SimpleQuote>(meanReversion)));\n        for (Size j = 0; j < nSwapIndexes_; ++j) {\n            // ??\n            // set new volatility structure and new mean reversion\n            pricers_[j]->setSwaptionVolatility(v);\n            if (meanReversion != Null<Real>()) {\n                boost::shared_ptr<MeanRevertingPricer> p =\n                    boost::dynamic_pointer_cast<MeanRevertingPricer>(\n                        pricers_[j]);\n                QL_REQUIRE(p != NULL, \"mean reverting pricer required at index \"\n                                          << j);\n                p->setMeanReversion(meanReversionQuote);\n            }\n        }\n        performCalculations();\n    }\n\n    Real CmsMarket::weightedFwdNpvError(const Matrix& w) {\n        performCalculations();\n        return weightedMean(errFwdCmsLegNPV_, w);\n    }\n\n    Real CmsMarket::weightedSpotNpvError(const Matrix& w) {\n        performCalculations();\n        return weightedMean(errSpotCmsLegNPV_, w);\n    }\n\n    Real CmsMarket::weightedSpreadError(const Matrix& w) {\n        performCalculations();\n        return weightedMean(errSpreads_, w);\n    }\n\n    // array of errors to be used by Levenberg-Marquardt optimization\n\n    Disposable<Array> CmsMarket::weightedFwdNpvErrors(const Matrix& w) {\n        performCalculations();\n        return weightedMeans(errFwdCmsLegNPV_, w);\n    }\n\n    Disposable<Array> CmsMarket::weightedSpotNpvErrors(const Matrix& w) {\n        performCalculations();\n        return weightedMeans(errSpotCmsLegNPV_, w);\n    }\n\n    Disposable<Array> CmsMarket::weightedSpreadErrors(const Matrix& w) {\n        performCalculations();\n        return weightedMeans(errSpreads_, w);\n    }\n\n    Real CmsMarket::weightedMean(const Matrix& var,\n                                 const Matrix& w) {\n        Real mean = 0.0;\n        for (Size i=0; i<nExercise_; ++i) {\n            for (Size j=0; j<nSwapIndexes_; ++j) {\n                mean += w[i][j]*var[i][j]*var[i][j];\n            }\n        }\n        mean = std::sqrt(mean/(nExercise_*nSwapIndexes_));\n        return mean;\n    }\n\n    Disposable<Array> CmsMarket::weightedMeans(const Matrix& var,\n                                               const Matrix& w) {\n        Array weightedVars(nExercise_*nSwapIndexes_);\n        for (Size i=0; i<nExercise_; ++i) {\n            for (Size j=0; j<nSwapIndexes_; ++j) {\n                weightedVars[i*nSwapIndexes_+j] = std::sqrt(w[i][j])*var[i][j];\n            }\n        }\n        return weightedVars;\n    }\n\n    Matrix CmsMarket::browse() const {\n        calculate();\n        //Matrix result(nExercise_*nSwapIndexes_, 15);\n        Matrix result(nExercise_*nSwapIndexes_, 14);\n            for (Size j=0; j<nSwapIndexes_; ++j) {\n                for (Size i=0; i<nExercise_; ++i) {\n                result[j*nExercise_+i][0] = swapTenors_[j].length();\n                result[j*nExercise_+i][1] = swapLengths_[i].length();\n\n                // Spreads\n                result[j*nExercise_+i][2] = mktBidSpreads_[i][j]*10000;\n                result[j*nExercise_+i][3] = mktAskSpreads_[i][j]*10000;\n                result[j*nExercise_+i][4] = mktSpreads_[i][j]*10000;\n                result[j*nExercise_+i][5] = mdlSpreads_[i][j]*10000;\n                result[j*nExercise_+i][6] = errSpreads_[i][j]*10000;\n                if (mdlSpreads_[i][j]>mktAskSpreads_[i][j])\n                    result[j*nExercise_+i][7] = (mdlSpreads_[i][j] -\n                                                mktAskSpreads_[i][j])*10000;\n                else if (mdlSpreads_[i][j]<mktBidSpreads_[i][j])\n                    result[j*nExercise_+i][7] = (mktBidSpreads_[i][j] -\n                                                mdlSpreads_[i][j])*10000;\n                else\n                    result[j*nExercise_+i][7] = 0.0;\n\n                // spot CMS Leg NPVs\n                result[j*nExercise_+i][ 8] = mktSpotCmsLegNPV_[i][j];\n                result[j*nExercise_+i][ 9] = mdlSpotCmsLegNPV_[i][j];\n                result[j*nExercise_+i][10] = errSpotCmsLegNPV_[i][j];\n\n                // forward CMS Leg NPVs\n                result[j*nExercise_+i][11] = mktFwdCmsLegNPV_[i][j];\n                result[j*nExercise_+i][12] = mdlFwdCmsLegNPV_[i][j];\n                result[j*nExercise_+i][13] = errFwdCmsLegNPV_[i][j];\n            }\n        }\n        return result;\n    }\n}\n", "meta": {"hexsha": "117d3fbabc10480f1c5f67d4f07f88037b8d76e1", "size": 11709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/termstructures/volatility/swaption/cmsmarket.cpp", "max_stars_repo_name": "grandtiger/quantlib", "max_stars_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "ql/termstructures/volatility/swaption/cmsmarket.cpp", "max_issues_repo_name": "grandtiger/quantlib", "max_issues_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-17T18:49:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-17T18:49:22.000Z", "max_forks_repo_path": "ql/termstructures/volatility/swaption/cmsmarket.cpp", "max_forks_repo_name": "grandtiger/quantlib", "max_forks_repo_head_hexsha": "4cf3d80ffc071ae74f026bb25fbb1dd9093e6301", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 41.6690391459, "max_line_length": 85, "alphanum_fraction": 0.55213938, "num_tokens": 3083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2491749363644691}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2013 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2013, 2014.\n// Modifications copyright (c) 2013, 2014 Oracle and/or its affiliates.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n#ifndef BOOST_GEOMETRY_STRATEGY_AGNOSTIC_POINT_IN_POLY_WINDING_HPP\n#define BOOST_GEOMETRY_STRATEGY_AGNOSTIC_POINT_IN_POLY_WINDING_HPP\n\n\n#include <boost/core/ignore_unused.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n#include <boost/geometry/strategies/side.hpp>\n#include <boost/geometry/strategies/covered_by.hpp>\n#include <boost/geometry/strategies/within.hpp>\n\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\nnamespace strategy { namespace within\n{\n\n\n// Fix for https://svn.boost.org/trac/boost/ticket/9628\n// For floating point coordinates, the <1> coordinate of a point is compared\n// with the segment's points using some EPS. If the coordinates are \"equal\"\n// the sides are calculated. Therefore we can treat a segment as a long areal\n// geometry having some width. There is a small ~triangular area somewhere\n// between the segment's effective area and a segment's line used in sides\n// calculation where the segment is on the one side of the line but on the\n// other side of a segment (due to the width).\n// For the s1 of a segment going NE the real side is RIGHT but the point may\n// be detected as LEFT, like this:\n//                     RIGHT\n//                 ___----->\n//                  ^      O Pt  __ __\n//                 EPS     __ __\n//                  v__ __ BUT DETECTED AS LEFT OF THIS LINE\n//             _____7\n//       _____/\n// _____/\ntemplate <typename CSTag>\nstruct winding_side_equal\n{\n    typedef typename strategy::side::services::default_strategy\n        <\n            CSTag\n        >::type strategy_side_type;\n\n    template <size_t D, typename Point, typename PointOfSegment>\n    static inline int apply(Point const& point,\n                            PointOfSegment const& se,\n                            int count)\n    {\n        // Create a vertical segment intersecting the original segment's endpoint\n        // equal to the point, with the derived direction (UP/DOWN).\n        // Set only the 2 first coordinates, the other ones are ignored\n        PointOfSegment ss1, ss2;\n        set<1-D>(ss1, get<1-D>(se));\n        set<1-D>(ss2, get<1-D>(se));\n        if (count > 0) // UP\n        {\n            set<D>(ss1, 0);\n            set<D>(ss2, 1);\n        }\n        else // DOWN\n        {\n            set<D>(ss1, 1);\n            set<D>(ss2, 0);\n        }\n        // Check the side using this vertical segment\n        return strategy_side_type::apply(ss1, ss2, point);\n    }\n};\n\n// The optimization for cartesian\ntemplate <>\nstruct winding_side_equal<cartesian_tag>\n{\n    template <size_t D, typename Point, typename PointOfSegment>\n    static inline int apply(Point const& point,\n                            PointOfSegment const& se,\n                            int count)\n    {\n        return math::equals(get<1-D>(point), get<1-D>(se)) ?\n                0 :\n                get<1-D>(point) < get<1-D>(se) ?\n                    // assuming count is equal to 1 or -1\n                    count : // ( count > 0 ? 1 : -1) :\n                    -count; // ( count > 0 ? -1 : 1) ;\n    }\n};\n\n\ntemplate <typename CSTag>\nstruct winding_side_between\n{\n    typedef typename strategy::side::services::default_strategy\n        <\n            CSTag\n        >::type strategy_side_type;\n\n    template <size_t D, typename Point, typename PointOfSegment>\n    static inline int apply(Point const& point,\n                            PointOfSegment const& s1, PointOfSegment const& s2,\n                            int count)\n    {\n        // Create a vertical segment intersecting the original segment's endpoint\n        // equal to the point, with the derived direction (UP/DOWN).\n        // Set only the 2 first coordinates, the other ones are ignored\n        PointOfSegment ss1, ss2;\n        set<1-D>(ss1, get<1-D>(s1));\n        set<1-D>(ss2, get<1-D>(s1));\n\n        if (count > 0) // UP\n        {\n            set<D>(ss1, 0);\n            set<D>(ss2, 1);\n        }\n        else // DOWN\n        {\n            set<D>(ss1, 1);\n            set<D>(ss2, 0);\n        }\n\n        int const seg_side = strategy_side_type::apply(ss1, ss2, s2);\n\n        if (seg_side != 0) // segment not vertical\n        {\n            if (strategy_side_type::apply(ss1, ss2, point) == -seg_side) // point on the opposite side than s2\n            {\n                return -seg_side;\n            }\n            else\n            {\n                set<1-D>(ss1, get<1-D>(s2));\n                set<1-D>(ss2, get<1-D>(s2));\n\n                if (strategy_side_type::apply(ss1, ss2, point) == seg_side) // point behind s2\n                {\n                    return seg_side;\n                }\n            }\n        }\n\n        // segment is vertical or point is between p1 and p2\n        return strategy_side_type::apply(s1, s2, point);\n    }\n};\n\n// The specialization for cartesian\ntemplate <>\nstruct winding_side_between<cartesian_tag>\n{\n    typedef strategy::side::services::default_strategy\n        <\n            cartesian_tag\n        >::type strategy_side_type;\n\n    template <size_t D, typename Point, typename PointOfSegment>\n    static inline int apply(Point const& point,\n                            PointOfSegment const& s1, PointOfSegment const& s2,\n                            int /*count*/)\n    {\n        return strategy_side_type::apply(s1, s2, point);\n    }\n};\n\n\n/*!\n\\brief Within detection using winding rule\n\\ingroup strategies\n\\tparam Point \\tparam_point\n\\tparam PointOfSegment \\tparam_segment_point\n\\tparam CalculationType \\tparam_calculation\n\\author Barend Gehrels\n\\note The implementation is inspired by terralib http://www.terralib.org (LGPL)\n\\note but totally revised afterwards, especially for cases on segments\n\\note Only dependant on \"side\", -> agnostic, suitable for spherical/latlong\n\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.within.within_3_with_strategy within (with strategy)]\n}\n */\ntemplate\n<\n    typename Point,\n    typename PointOfSegment = Point,\n    typename CalculationType = void\n>\nclass winding\n{\n    typedef typename select_calculation_type\n        <\n            Point,\n            PointOfSegment,\n            CalculationType\n        >::type calculation_type;\n\n\n    typedef typename strategy::side::services::default_strategy\n        <\n            typename cs_tag<Point>::type\n        >::type strategy_side_type;\n\n\n    /*! subclass to keep state */\n    class counter\n    {\n        int m_count;\n        bool m_touches;\n\n        inline int code() const\n        {\n            return m_touches ? 0 : m_count == 0 ? -1 : 1;\n        }\n\n    public :\n        friend class winding;\n\n        inline counter()\n            : m_count(0)\n            , m_touches(false)\n        {}\n\n    };\n\n\n    template <size_t D>\n    static inline int check_touch(Point const& point,\n                PointOfSegment const& seg1, PointOfSegment const& seg2,\n                counter& state)\n    {\n        calculation_type const p = get<D>(point);\n        calculation_type const s1 = get<D>(seg1);\n        calculation_type const s2 = get<D>(seg2);\n        if ((s1 <= p && s2 >= p) || (s2 <= p && s1 >= p))\n        {\n            state.m_touches = true;\n        }\n        return 0;\n    }\n\n\n    template <size_t D>\n    static inline int check_segment(Point const& point,\n                PointOfSegment const& seg1, PointOfSegment const& seg2,\n                counter& state, bool& eq1, bool& eq2)\n    {\n        calculation_type const p = get<D>(point);\n        calculation_type const s1 = get<D>(seg1);\n        calculation_type const s2 = get<D>(seg2);\n\n        // Check if one of segment endpoints is at same level of point\n        eq1 = math::equals(s1, p);\n        eq2 = math::equals(s2, p);\n\n        if (eq1 && eq2)\n        {\n            // Both equal p -> segment is horizontal (or vertical for D=0)\n            // The only thing which has to be done is check if point is ON segment\n            return check_touch<1 - D>(point, seg1, seg2, state);\n        }\n\n        return\n              eq1 ? (s2 > p ?  1 : -1)  // Point on level s1, UP/DOWN depending on s2\n            : eq2 ? (s1 > p ? -1 :  1)  // idem\n            : s1 < p && s2 > p ?  2     // Point between s1 -> s2 --> UP\n            : s2 < p && s1 > p ? -2     // Point between s2 -> s1 --> DOWN\n            : 0;\n    }\n\n\npublic :\n\n    // Typedefs and static methods to fulfill the concept\n    typedef Point point_type;\n    typedef PointOfSegment segment_point_type;\n    typedef counter state_type;\n\n    static inline bool apply(Point const& point,\n                PointOfSegment const& s1, PointOfSegment const& s2,\n                counter& state)\n    {\n        typedef typename cs_tag<Point>::type cs_t;\n\n        bool eq1 = false;\n        bool eq2 = false;\n        geofeatures_boost::ignore_unused(eq2);\n\n        int count = check_segment<1>(point, s1, s2, state, eq1, eq2);\n        if (count != 0)\n        {\n            int side = 0;\n            if (count == 1 || count == -1)\n            {\n                side = winding_side_equal<cs_t>\n                            ::template apply<1>(point, eq1 ? s1 : s2, count);\n            }\n            else // count == 2 || count == -2\n            {\n                side = winding_side_between<cs_t>\n                            ::template apply<1>(point, s1, s2, count);\n            }\n            \n            if (side == 0)\n            {\n                // Point is lying on segment\n                state.m_touches = true;\n                state.m_count = 0;\n                return false;\n            }\n\n            // Side is NEG for right, POS for left.\n            // The count is -2 for down, 2 for up (or -1/1)\n            // Side positive thus means UP and LEFTSIDE or DOWN and RIGHTSIDE\n            // See accompagnying figure (TODO)\n            if (side * count > 0)\n            {\n                state.m_count += count;\n            }\n        }\n        return ! state.m_touches;\n    }\n\n    static inline int result(counter const& state)\n    {\n        return state.code();\n    }\n};\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\nnamespace services\n{\n\n// Register using \"areal_tag\" for ring, polygon, multi-polygon\ntemplate <typename AnyTag, typename Point, typename Geometry>\nstruct default_strategy<point_tag, AnyTag, point_tag, areal_tag, cartesian_tag, cartesian_tag, Point, Geometry>\n{\n    typedef winding<Point, typename geometry::point_type<Geometry>::type> type;\n};\n\ntemplate <typename AnyTag, typename Point, typename Geometry>\nstruct default_strategy<point_tag, AnyTag, point_tag, areal_tag, spherical_tag, spherical_tag, Point, Geometry>\n{\n    typedef winding<Point, typename geometry::point_type<Geometry>::type> type;\n};\n\n// TODO: use linear_tag and pointlike_tag the same way how areal_tag is used\n\ntemplate <typename Point, typename Geometry, typename AnyTag>\nstruct default_strategy<point_tag, AnyTag, point_tag, AnyTag, cartesian_tag, cartesian_tag, Point, Geometry>\n{\n    typedef winding<Point, typename geometry::point_type<Geometry>::type> type;\n};\n\ntemplate <typename Point, typename Geometry, typename AnyTag>\nstruct default_strategy<point_tag, AnyTag, point_tag, AnyTag, spherical_tag, spherical_tag, Point, Geometry>\n{\n    typedef winding<Point, typename geometry::point_type<Geometry>::type> type;\n};\n\n} // namespace services\n\n#endif\n\n\n}} // namespace strategy::within\n\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace strategy { namespace covered_by { namespace services\n{\n\n// Register using \"areal_tag\" for ring, polygon, multi-polygon\ntemplate <typename AnyTag, typename Point, typename Geometry>\nstruct default_strategy<point_tag, AnyTag, point_tag, areal_tag, cartesian_tag, cartesian_tag, Point, Geometry>\n{\n    typedef strategy::within::winding<Point, typename geometry::point_type<Geometry>::type> type;\n};\n\ntemplate <typename AnyTag, typename Point, typename Geometry>\nstruct default_strategy<point_tag, AnyTag, point_tag, areal_tag, spherical_tag, spherical_tag, Point, Geometry>\n{\n    typedef strategy::within::winding<Point, typename geometry::point_type<Geometry>::type> type;\n};\n\n// TODO: use linear_tag and pointlike_tag the same way how areal_tag is used\n\ntemplate <typename Point, typename Geometry, typename AnyTag>\nstruct default_strategy<point_tag, AnyTag, point_tag, AnyTag, cartesian_tag, cartesian_tag, Point, Geometry>\n{\n    typedef strategy::within::winding<Point, typename geometry::point_type<Geometry>::type> type;\n};\n\ntemplate <typename Point, typename Geometry, typename AnyTag>\nstruct default_strategy<point_tag, AnyTag, point_tag, AnyTag, spherical_tag, spherical_tag, Point, Geometry>\n{\n    typedef strategy::within::winding<Point, typename geometry::point_type<Geometry>::type> type;\n};\n\n}}} // namespace strategy::covered_by::services\n#endif\n\n\n}} // namespace geofeatures_boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGY_AGNOSTIC_POINT_IN_POLY_WINDING_HPP\n", "meta": {"hexsha": "43ff5972fc6e50ca9774d70c7812b068dcd4e185", "size": 13595, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Pods/Headers/Private/GeoFeatures/boost/geometry/strategies/agnostic/point_in_poly_winding.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.68997669, "max_line_length": 116, "alphanum_fraction": 0.6176535491, "num_tokens": 3258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.24903629790869672}}
{"text": "/**\n * @file\n * This file is part of SeisSol.\n *\n * @author Sebastian Rettenberger (sebastian.rettenberger @ tum.de, http://www5.in.tum.de/wiki/index.php/Sebastian_Rettenberger)\n *\n * @section LICENSE\n * Copyright (c) 2015, SeisSol Group\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\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 * @section DESCRIPTION\n **/\n\n#include <cassert>\n#include <cmath>\n\n#include <hdf5.h>\n\n#include <Eigen/Dense>\n\n#include \"utils/args.h\"\n\n#include \"Geometry/refinement/RefinerUtils.h\"\n\ntemplate<typename T>\nT pow2(T v)\n{\n\treturn v*v;\n}\n\nint main(int argc, char* argv[])\n{\n\tutils::Args args;\n\targs.addOption(\"diff\", 'd', \"Maximum allowed difference (Default 0.001)\", utils::Args::Required, false);\n\targs.addOption(\"verbose\", 'V', \"Enable verbose output\", utils::Args::No, false);\n\targs.addAdditionalOption(\"output.h5\", \"The SeisSol wave field output file\");\n\n\tswitch (args.parse(argc, argv)) {\n\tcase utils::Args::Error:\n\t\treturn 1;\n\tcase utils::Args::Help:\n\t\treturn 127;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tbool verbose = args.getArgument(\"verbose\", false);\n\n\thid_t hdfFile = H5Fopen(args.getAdditionalArgument<const char*>(\"output.h5\"),\n\t\t\tH5F_ACC_RDONLY, H5P_DEFAULT);\n\n\t// Read vertices\n\thid_t vertData = H5Dopen(hdfFile, \"/geometry\", H5P_DEFAULT);\n\thid_t space = H5Dget_space(vertData);\n\thsize_t dims[2]; // Assuming to dimensions\n\tH5Sget_simple_extent_dims(space, dims, 0L);\n\n\tdouble* vertices = new double[dims[0]*dims[1]];\n\tH5Dread(vertData, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, vertices);\n\n\tH5Sclose(space);\n\tH5Dclose(vertData);\n\n\t// Read cells\n\thid_t cellData = H5Dopen(hdfFile, \"/connect\", H5P_DEFAULT);\n\tspace = H5Dget_space(cellData);\n\tH5Sget_simple_extent_dims(space, dims, 0L);\n\n\tunsigned long* cells = new unsigned long[dims[0]*dims[1]];\n\tH5Dread(cellData, H5T_NATIVE_ULONG, H5S_ALL, H5S_ALL, H5P_DEFAULT, cells);\n\n\thsize_t numCells = dims[0];\n\n\tH5Sclose(space);\n\tH5Dclose(cellData);\n\n\t// Read the 9 variables\n\tdouble* var[9];\n\tconst char* varNames[9] = {\"/sigma_xx\", \"/sigma_yy\", \"/sigma_zz\", \"/sigma_xy\", \"/sigma_yz\", \"/sigma_xz\", \"/u\", \"/v\", \"/w\"};\n\n\thid_t memSpace = H5Screate_simple(1, &numCells, &numCells);\n\tH5Sselect_all(memSpace);\n\n\tfor (unsigned int i = 0; i < 9; i++) {\n\t\thid_t varData = H5Dopen(hdfFile, varNames[i], H5P_DEFAULT);\n\t\tspace = H5Dget_space(varData);\n\t\tH5Sget_simple_extent_dims(space, dims, 0L);\n\n\t\tassert(dims[1] == numCells);\n\t\tvar[i] = new double[dims[1]];\n\n\t\thsize_t start[2] = {0, 0};\n\t\thsize_t count[2] = {1, numCells};\n\t\tH5Sselect_hyperslab(space, H5S_SELECT_SET, start, 0L, count, 0L);\n\n\t\tH5Dread(varData, H5T_NATIVE_DOUBLE, memSpace, space, H5P_DEFAULT, var[i]);\n\n\t\tH5Sclose(space);\n\t\tH5Dclose(varData);\n\t}\n\n\tH5Sclose(memSpace);\n\n\tH5Fclose(hdfFile);\n\n\t// Compute parameters\n\tconst double maxDiff = args.getArgument(\"diff\", 0.001);\n\n      Eigen::Vector3d vec_n(1, 1, 1);\n      const double n = 1.0/(vec_n.norm());\n      const double mu = 1.0;\n      const double lambda = 2.0;\n      const double rho = 1.0;\n\n      const double r1[9] = {\n                      rho * (-2.0*pow2(n)*mu - 2.0*pow2(n)*mu + lambda + 2.0*mu),\n\t\t\trho * (2.0*pow2(n)*mu + lambda),\n\t\t\trho * (2.0*pow2(n)*mu + lambda),\n\t\t\t2.0 * n * mu * n * rho,\n\t\t\t2.0 * mu * n * rho * n,\n\t\t\t2.0 * mu * n * rho * n,\n\t\t\tn * sqrt(rho * (lambda + 2.0*mu)),\n\t\t\tn * sqrt(rho * (lambda + 2.0*mu)),\n\t\t\tsqrt(rho * (lambda + 2.0*mu)) * n\n\t};\n\n\tconst double r8[9] = {\n\t\t\t2.0 * mu * n * rho * pow2(n) * n,\n\t\t\t-2.0 * mu * n * rho * pow2(n) * n,\n\t\t\t0,\n\t\t\tmu * rho * n * (2.0*pow2(n) + pow2(n) - 1) * n,\n\t\t\t-pow2(n) * mu * rho * pow2(n),\n\t\t\tmu * n * pow2(n) * rho * n,\n\t\t\t-n * n * n * sqrt(rho*mu),\n\t\t\tpow2(n) * n * sqrt(rho*mu),\n\t\t\t0\n\t};\n\n\tconst Eigen::Vector3d k = 2.0 * M_PI / 100 * Eigen::Vector3d(1, 1, 1);\n\n\t// Check cells\n\tbool failed = false;\n\n\tfor (unsigned int i = 0; i < numCells; i++) {\n\t\tconst Eigen::Vector3d a = Eigen::Vector3d(&vertices[cells[i*4] * 3]);\n\t\tconst Eigen::Vector3d b = Eigen::Vector3d(&vertices[cells[i*4 + 1] * 3]);\n\t\tconst Eigen::Vector3d c = Eigen::Vector3d(&vertices[cells[i*4 + 2] * 3]);\n\t\tconst Eigen::Vector3d d = Eigen::Vector3d(&vertices[cells[i*4 + 3] * 3]);\n\n\t\tseissol::refinement::Tetrahedron<double> tet(a, b, c, d);\n\t\tconst Eigen::Vector3d center = tet.center();\n\n\t\tconst double kx = k.dot(center);\n\n\t\tfor (unsigned int j = 0; j < 9; j++) {\n\t\t\tconst double value = r1[j]*sin(kx) + r8[j]*sin(kx);\n\n\t\t\tif (fabs(var[j][i] - value) > maxDiff) {\n\t\t\t\tfailed = true;\n\t\t\t\tif (verbose)\n\t\t\t\t\tstd::cout << var[j][i] << ' ' << value << ' ' << fabs(var[j][i] - value) << ' ';\n\t\t\t} else {\n\t\t\t\tif (verbose)\n\t\t\t\t\tstd::cout << \"ok\" << ' ';\n\t\t\t}\n\t\t}\n\n\t\tif (verbose)\n\t\t\tstd::cout << std::endl;\n\n\t\tif (failed && !verbose)\n\t\t\t// We can stop in this case\n\t\t\tbreak;\n\t}\n\n\t// Cleanup\n\tfor (unsigned int i = 0; i < 9; i++) {\n\t\tdelete [] var[i];\n\t}\n\n\tdelete [] vertices;\n\tdelete [] cells;\n\n\treturn failed ? 1 : 0;\n}\n", "meta": {"hexsha": "ed99de2058b6a24dafde35d8fd11abf52b9e2d20", "size": 6301, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "postprocessing/validation/XDMFCubeCheck/src/main.cpp", "max_stars_repo_name": "fabian-kutschera/SeisSol", "max_stars_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 165.0, "max_stars_repo_stars_event_min_datetime": "2015-01-30T18:19:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T17:22:14.000Z", "max_issues_repo_path": "postprocessing/validation/XDMFCubeCheck/src/main.cpp", "max_issues_repo_name": "fabian-kutschera/SeisSol", "max_issues_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 351.0, "max_issues_repo_issues_event_min_datetime": "2015-10-06T15:06:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T11:23:13.000Z", "max_forks_repo_path": "postprocessing/validation/XDMFCubeCheck/src/main.cpp", "max_forks_repo_name": "fabian-kutschera/SeisSol", "max_forks_repo_head_hexsha": "d5656cd38e9eb1d91c05ebcbf173acbc3083da57", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 96.0, "max_forks_repo_forks_event_min_datetime": "2015-07-27T15:13:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T19:19:32.000Z", "avg_line_length": 29.7216981132, "max_line_length": 128, "alphanum_fraction": 0.6564037454, "num_tokens": 1988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.2490259750136175}}
{"text": "//=======================================================================\n// Copyright (c) 2013 Piotr Wygocki\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file facility_location_swap.hpp\n* @brief\n * @author Piotr Wygocki\n * @version 1.0\n * @date 2013-07-08\n */\n#ifndef PAAL_FACILITY_LOCATION_SWAP_HPP\n#define PAAL_FACILITY_LOCATION_SWAP_HPP\n\n#include \"paal/data_structures/facility_location/facility_location_solution_traits.hpp\"\n#include \"paal/utils/type_functions.hpp\"\n#include \"paal/data_structures/combine_iterator.hpp\"\n\n#include <boost/iterator/iterator_adaptor.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n\n#include <cassert>\n#include <vector>\n#include <numeric>\n#include <cstdlib>\n\nnamespace paal {\nnamespace local_search {\n\n/**\n * @brief swap type\n *\n * @tparam T\n */\ntemplate <typename T> class Swap {\n  public:\n    /**\n     * @brief constructor\n     *\n     * @param from\n     * @param to\n     */\n    Swap(T from, T to) : m_from(from), m_to(to) {}\n\n    Swap() = default;\n\n    /**\n     * @brief from getter\n     *\n     * @return\n     */\n    T get_from() const { return m_from; }\n\n    /**\n     * @brief to getter\n     *\n     * @return\n     */\n    T get_to() const { return m_to; }\n\n    /**\n     * @brief form setter\n     *\n     * @param from\n     */\n    void set_from(T from) { m_from = from; }\n\n    /**\n     * @brief from setter\n     *\n     * @param to\n     */\n    void set_to(T to) { m_to = to; }\n\n  private:\n    T m_from;\n    T m_to;\n};\n\n/// operator() creates Swap  from (from, to)\nstruct make_swap {\n    /// operator()\n    template <typename T> Swap<T> operator()(T from, T to) const {\n        return Swap<T>(from, to);\n    }\n};\n\n/**\n * @brief gain functor for swap in facility location problem.\n *\n * @tparam VertexType\n */\nstruct facility_location_gain_swap {\n    /**\n     * @brief operator()\n     *\n     * @tparam Solution\n     * @param sol\n     * @param s\n     *\n     * @return\n     */\n    template <class Solution, class VertexType>\n    auto operator()(Solution &sol, const Swap<VertexType> &s) const {\n\n        auto ret = sol.add_facility_tentative(s.get_to());\n        ret += sol.remove_facility_tentative(s.get_from());\n        auto back = sol.add_facility_tentative(s.get_from());\n        back += sol.remove_facility_tentative(s.get_to());\n        assert(ret == -back);\n        return -ret;\n    }\n};\n\n/**\n * @brief commit functor for facility location problem\n */\nstruct facility_location_commit_swap {\n    /**\n     * @brief operator()\n     *\n     * @tparam Solution\n     * @param sol\n     * @param s\n     */\n    template <typename Solution, typename VertexType>\n    bool operator()(Solution &sol, const Swap<VertexType> &s) const {\n        sol.add_facility(s.get_to());\n        sol.remove_facility(s.get_from());\n        return true;\n    }\n};\n\n/**\n * @brief get moves functor for facility location problem\n */\nstruct facility_locationget_moves_swap {\n\n    /// operator()\n    template <typename Solution>\n    auto operator()(const Solution &s) const  {\n        auto begin = data_structures::make_combine_iterator(\n            make_swap{}, s.getChosenCopy(), s.getUnchosenCopy());\n        decltype(begin) end;\n        return boost::make_iterator_range(begin, end);\n    }\n};\n\n} // local_search\n} // paal\n\n#endif // PAAL_FACILITY_LOCATION_SWAP_HPP\n", "meta": {"hexsha": "870564b9123745203aa91de750f9e8b83581f793", "size": 3471, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/local_search/facility_location/facility_location_swap.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/local_search/facility_location/facility_location_swap.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/local_search/facility_location/facility_location_swap.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 22.25, "max_line_length": 87, "alphanum_fraction": 0.5952175166, "num_tokens": 854, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24902597501361748}}
{"text": "// Copyright 2006. Peter Gottschling, Matthias Troyer, Rolf Bonderer\n// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef LA_CONCEPTS_INCLUDE\n#define LA_CONCEPTS_INCLUDE\n\n#include <boost/config/concept_macros.hpp>\n\n#ifdef __GXX_CONCEPTS__\n#  include <concepts>\n#else\n#  ifdef LA_SHOW_WARNINGS\n#    warning \"Concepts are not used\"\n#  endif\n#endif\n\n\n#include <boost/numeric/linear_algebra/identity.hpp>\n#include <boost/numeric/linear_algebra/is_invertible.hpp>\n#include <boost/numeric/linear_algebra/inverse.hpp>\n#include <boost/numeric/linear_algebra/operators.hpp>\n#include <boost/numeric/linear_algebra/algebraic_concepts.hpp>\n#include <complex>\n\n// If desired one can disable the default concept maps with LA_NO_CONCEPT_MAPS\n\n// We consider to change the namespace from math to numeric\n// More precisely, the concepts may be moved into namespace numeric and the standard functions stay in math\n\n/// Namespace for mathematical concepts\n/** In contrast to the ones in algebra the concepts can require \n    basic implementation concepts like std::CopyAssignable */  \nnamespace math {\n\n#ifdef __GXX_CONCEPTS__\n\n// ==================================\n// Classification of Arithmetic Types\n// ==================================\n\n// We omit this now because it became part of the standard concepts\n\n#if 0\n\n// In addtion to std::Integral\nconcept Float<typename T> \n  : std::DefaultConstructible<T>, std::CopyConstructible<T>,\n    std::LessThanComparable<T>, std::EqualityComparable<T>\n{\n  T operator+(T);\n  T operator+(T, T);\n  T& operator+=(T&, T);\n  T operator-(T, T);\n  T operator-(T);\n  T& operator-=(T&, T);\n  T operator*(T, T);\n  T& operator*=(T&, T);\n  T operator/(T, T);\n  T& operator/=(T&, T);\n\n  requires std::CopyAssignable<T>\n        && std::SameType<std::CopyAssignable<T>::result_type, T&>;\n}\n\nconcept_map Float<float> {}\nconcept_map Float<double> {}\nconcept_map Float<long double> {}\n\n// The difference to Float is the lack of LessThanComparable\nconcept Complex<typename T> \n  : std::DefaultConstructible<T>, std::CopyConstructible<T>,\n    std::EqualityComparable<T>\n{\n  T operator+(T);\n  T operator+(T, T);\n  T& operator+=(T&, T);\n  T operator-(T, T);\n  T operator-(T);\n  T& operator-=(T&, T);\n  T operator*(T, T);\n  T& operator*=(T&, T);\n  T operator/(T, T);\n  T& operator/=(T&, T);\n\n  requires std::CopyAssignable<T> \n        && std::SameType<std::CopyAssignable<T>::result_type, T&>;\n}\n\ntemplate <typename T>\n  requires Float<T>\nconcept_map Complex<std::complex<T> > {}\n\n\n// TBD: Concept Arithmetic is useless like this, it should have operations and then be the base for\n// Integral, Float and Complex\nconcept Arithmetic<typename T> {}\n\ntemplate <typename T>\n  requires std::Integral<T>\nconcept_map Arithmetic<T> {}\n\ntemplate <typename T>\n  requires Float<T>\nconcept_map Arithmetic<T> {}\n\ntemplate <typename T>\n  requires Arithmetic<T>\nconcept_map Arithmetic< std::complex<T> > {}\n\n#endif \n\n// The following concepts are used to classify intrinsic arithmetic types.\n// The standard concepts already define the syntactic requirements,\n// i.e. the interface.\n// However they sey nothing about the semantics.\n// Therefore, user-defined types can model the syntactic/interface\n// requirements while still having a different mathematical behavior.\n// For that reason, we introduce concepts that are only used for intrinsic types.\n// For them we can define concept_maps regarding semantic behavior as monoids.\n\nconcept IntrinsicSignedIntegral<typename T> \n  : std::SignedIntegralLike<T> \n{}\n\nconcept IntrinsicUnsignedIntegral<typename T> \n  : std::UnsignedIntegralLike<T> \n{}\n\nconcept IntrinsicFloatingPoint<typename T>\n  : std::FloatingPointLike<T> \n{}\n\n\n// Intrinsic types are chategorized:\n\nconcept_map IntrinsicSignedIntegral<char> {} \nconcept_map IntrinsicSignedIntegral<signed char> {}\nconcept_map IntrinsicUnsignedIntegral<unsigned char> {}\nconcept_map IntrinsicSignedIntegral<short> {}\nconcept_map IntrinsicUnsignedIntegral<unsigned short> {}\nconcept_map IntrinsicSignedIntegral<int> {}\nconcept_map IntrinsicUnsignedIntegral<unsigned int> {}\nconcept_map IntrinsicSignedIntegral<long> {}\nconcept_map IntrinsicUnsignedIntegral<unsigned long> {}\nconcept_map IntrinsicSignedIntegral<long long> {}\nconcept_map IntrinsicUnsignedIntegral<unsigned long long> {}\n\nconcept_map IntrinsicFloatingPoint<float> {}\nconcept_map IntrinsicFloatingPoint<double> {}\n\n\n\n// ================\n// Utility Concepts\n// ================\n\n// Concepts for functions mapping to same type or convertible\nauto concept UnaryIsoFunction<typename Operation, typename Element>\n{\n    requires std::Callable1<Operation, Element>;\n    requires std::Convertible<std::Callable1<Operation, Element>::result_type, Element>;\n\n    typename result_type = std::Callable1<Operation, Element>::result_type;\n};\n\n\nauto concept BinaryIsoFunction<typename Operation, typename Element>\n{\n    requires std::Callable2<Operation, Element, Element>;\n    requires std::Convertible<std::Callable2<Operation, Element, Element>::result_type, Element>;\n\n    typename result_type = std::Callable2<Operation, Element, Element>::result_type;\n};\n\n#if 0\nauto concept CompatibleBinaryFunction<typename A1, typename A2, typename Result>\n{\n    typename result_type;\n    result_type F(A1, A2);\n    requires std::Convertible<result_type, Result>;\n}\n#endif\n\n// ==================\n// Algebraic Concepts\n// ==================\n\n\nauto concept Magma<typename Operation, typename Element>\n    : BinaryIsoFunction<Operation, Element>\n{\n    requires std::CopyAssignable<Element>\n\t  && std::CopyAssignable<Element, BinaryIsoFunction<Operation, Element>::result_type>;\n};\n\n\n// For algebraic structures that are commutative but not associative\n// As an example floating point numbers are commutative but not associative\n//   w.r.t. addition and multiplication\nauto concept CommutativeMagma<typename Operation, typename Element>\n  : Magma<Operation, Element>, \n    algebra::Commutative<Operation, Element>\n{};\n\n\n// SemiGroup is a refinement which must be nominal\nauto concept SemiGroup<typename Operation, typename Element>\n  : Magma<Operation, Element>, \n    algebra::SemiGroup<Operation, Element>\n{};\n\n\nauto concept CommutativeSemiGroup<typename Operation, typename Element>\n  : SemiGroup<Operation, Element>,\n    CommutativeMagma<Operation, Element>\n{};\n\n\n// Adding identity\n// auto \nconcept Monoid<typename Operation, typename Element>\n  : SemiGroup<Operation, Element>, \n    algebra::Monoid<Operation, Element> \n{\n    requires std::Convertible<identity_result_type, Element>;\n};\n\n\nauto concept CommutativeMonoid<typename Operation, typename Element>\n  : CommutativeSemiGroup<Operation, Element>, \n    Monoid<Operation, Element>\n{};\n\n\nconcept PartiallyInvertibleMonoid<typename Operation, typename Element>\n  : Monoid<Operation, Element>, \n    algebra::Inversion<Operation, Element> \n{\n    typename is_invertible_result_type;\n    is_invertible_result_type is_invertible(Operation, Element);\n    requires std::Convertible<is_invertible_result_type, bool>;\n\n    requires std::Convertible<inverse_result_type, Element>;\n\n    // Does it overwrites the axiom from algebra::Inversion\n    axiom Inversivity(Operation op, Element x)\n    {\n\t// Only for invertible elements:\n\tif (is_invertible(op, x))\n\t    op( x, inverse(op, x) ) == identity(op, x); \n\tif ( is_invertible(op, x) )\n\t    op( inverse(op, x), x ) == identity(op, x); \n    }\n};\n\n\nauto concept PartiallyInvertibleCommutativeMonoid<typename Operation, typename Element>\n  : PartiallyInvertibleMonoid<Operation, Element>, \n    CommutativeMonoid<Operation, Element>   \n{};\n\n\nconcept Group<typename Operation, typename Element>\n  : PartiallyInvertibleMonoid<Operation, Element>,\n    algebra::Group<Operation, Element>\n{\n    axiom AlwaysInvertible(Operation op, Element x)\n    {\n\tis_invertible(op, x);\n    }\n\n    axiom GlobalInversivity(Operation op, Element x)\n    {\n\t// In fact this is implied by AlwaysInvertible and inherited Inversion axiom\n\t// However, we don't rely on the compiler to deduce this\n\top( x, inverse(op, x) ) == identity(op, x);\n\top( inverse(op, x), x ) == identity(op, x);\n    }\n};\n\n\nauto concept AbelianGroup<typename Operation, typename Element>\n  : Group<Operation, Element>, \n    PartiallyInvertibleCommutativeMonoid<Operation, Element>,\n    algebra::AbelianGroup<Operation, Element>\n{};\n\n\n// ========================\n// Additive scalar concepts\n// ========================\n\n\nconcept AdditiveMagma<typename Element>\n  : Magma< math::add<Element>, Element >\n{\n    typename plus_assign_result_type;  \n    plus_assign_result_type operator+=(Element& x, Element y);\n    // requires std::Convertible<plus_assign_result_type, Element>;\n\n    // Operator + is by default defined with +=\n    typename addition_result_type;  \n    addition_result_type operator+(Element x, Element y);\n#if 0\n    {\n\tElement tmp(x);\n\treturn tmp += y;                      defaults NYS\n    }\n#endif \n    requires std::Convertible<addition_result_type, Element>;\n\n    // Type consistency with Magma\n    requires std::Convertible< addition_result_type,   \n                            Magma< math::add<Element>, Element >::result_type>;\n\n    // SameType requires more rigorous specializations on pure algebraic functors\n    // requires std::SameType< addition_result_type, \n    // \t                    Magma< math::add<Element>, Element >::result_type>;\n\n    axiom Consistency(math::add<Element> op, Element x, Element y)\n    {\n\top(x, y) == x + y;     \n               \n\t// Consistency definition between + and += might change later\n        x + y == x += y;\n\t// Element tmp = x; tmp+= y; tmp == x + y; not proposal-compliant\n    }   \n}\n\n\nauto concept AdditiveCommutativeMagma<typename Element>\n  : AdditiveMagma<Element>,\n    CommutativeMagma< math::add<Element>, Element >\n{};\n\n\nauto concept AdditiveSemiGroup<typename Element>\n  : AdditiveMagma<Element>, \n    SemiGroup< math::add<Element>, Element >\n{};\n\n\n// We really need only one of the additive concepts for the requirements, \n// the requirements of the other would be implied.\n// Vice versa, to derive concept maps of nested concepts from\n// concept maps of refined concepts, they are needed all.\nauto concept AdditiveCommutativeSemiGroup<typename Element>\n  : AdditiveSemiGroup<Element>,\n    AdditiveCommutativeMagma<Element>,\n    CommutativeSemiGroup< math::add<Element>, Element >\n{};\n\n\nconcept AdditiveMonoid<typename Element>\n  : AdditiveSemiGroup<Element>,\n    Monoid< math::add<Element>, Element >\n{\n    Element zero(Element v);\n\n    axiom Consistency (math::add<Element> op, Element x)\n    {\n\tzero(x) == identity(op, x);\n    }\n};\n\n\n// We really need only one of the additive concepts for the requirements, \n// the requirements of the other would be implied.\n// Vice versa, to derive concept maps of nested concepts from\n// concept maps of refined concepts, they are needed all.\nauto concept AdditiveCommutativeMonoid<typename Element>\n  : AdditiveMonoid<Element>,\n    AdditiveCommutativeSemiGroup<Element>,\n    CommutativeMonoid< math::add<Element>, Element >\n{};\n\n\nconcept AdditivePartiallyInvertibleMonoid<typename Element>\n  : AdditiveMonoid<Element>,\n    PartiallyInvertibleMonoid< math::add<Element>, Element >\n{\n    typename minus_assign_result_type;  \n    minus_assign_result_type operator-=(Element& x, Element y);\n    // requires std::Convertible<minus_assign_result_type, Element>;\n     \n    // Operator - by default defined with -=\n    typename subtraction_result_type;  \n    subtraction_result_type operator-(Element& x, Element y);\n#if 0\n    {\n\tElement tmp(x);\n\treturn tmp -= y;                      defaults NYS\n    }\n#endif \n    requires std::Convertible<subtraction_result_type, Element>;\n\n\n    typename unary_result_type;  \n    unary_result_type operator-(Element x);\n#if 0\n    {\n\treturn zero(x) - x;      defaults NYS\n    }\n#endif \n    requires std::Convertible<unary_result_type, Element>;\n    \n    axiom Consistency(math::add<Element> op, Element x, Element y)\n    {\n\t// consistency between additive and pure algebraic concept\n\tif ( is_invertible(op, y) )\n\t    op(x, inverse(op, y)) == x - y;            \n\tif ( is_invertible(op, y) )\n\t    inverse(op, y) == -y;                      \n\n\t// consistency between unary and binary -\n\tif ( is_invertible(op, x) )\n\t    identity(op, x) - x == -x;                 \n\n\t// Might change later\n\tif ( is_invertible(op, y) )\n\t    x - y == x -= y;                                                       \n\t// Element tmp = x; tmp-= y; tmp == x - y; not proposal-compliant\n    }  \n\n};\n\n\nauto concept AdditivePartiallyInvertibleCommutativeMonoid<typename Element>\n  : AdditivePartiallyInvertibleMonoid<Element>,\n    AdditiveCommutativeMonoid<Element>, \n    PartiallyInvertibleCommutativeMonoid< math::add<Element>, Element >\n{};\n\n\n\nauto concept AdditiveGroup<typename Element>\n  : AdditivePartiallyInvertibleMonoid<Element>,\n    Group< math::add<Element>, Element >\n{};\n\n\nauto concept AdditiveAbelianGroup<typename Element>\n  : AdditiveGroup<Element>,\n    AdditiveCommutativeMonoid<Element>,\n    AbelianGroup< math::add<Element>, Element >\n{};\n\n\n// ============================\n// Multiplitive scalar concepts\n// ============================\n\n\nconcept MultiplicativeMagma<typename Element>\n  : Magma< math::mult<Element>, Element >\n{\n    typename mult_assign_result_type;  \n    mult_assign_result_type operator*=(Element& x, Element y);\n    // requires std::Convertible<mult_assign_result_type, Element>;\n\n    // Operator * is by default defined with *=\n    typename mult_result_type;  \n    mult_result_type operator*(Element x, Element y);\n#if 0\n    {\n\tElement tmp(x);\n\treturn tmp *= y;                      defaults NYS\n    }\n#endif \n    requires std::Convertible<mult_result_type, Element>;\n    \n    // Type consistency with Magma\n    requires std::Convertible< mult_result_type,   \n                            Magma< math::mult<Element>, Element >::result_type>;\n\n    // SameType requires more rigorous specializations on pure algebraic functors\n    // requires std::SameType< mult_result_type, \n    // \t                    Magma< math::mult<Element>, Element >::result_type>;\n\n\n    axiom Consistency(math::mult<Element> op, Element x, Element y)\n    {\n\top(x, y) == x * y;                 \n   \n\t// Consistency definition between * and *= might change later\n        x * y == x *= y;\n\t// Element tmp = x; tmp*= y; tmp == x * y; not proposal-compliant\n    }  \n\n}\n\n\nauto concept MultiplicativeSemiGroup<typename Element>\n  : MultiplicativeMagma<Element>,\n    SemiGroup< math::mult<Element>, Element >\n{};\n\n\nauto concept MultiplicativeCommutativeSemiGroup<typename Element>\n  : MultiplicativeSemiGroup<Element>,\n    CommutativeSemiGroup< math::mult<Element>, Element >\n{};\n\n\nconcept MultiplicativeMonoid<typename Element>\n  : MultiplicativeSemiGroup<Element>,\n    Monoid< math::mult<Element>, Element >\n{\n    Element one(Element v);\n\n    axiom Consistency (math::mult<Element> op, Element x)\n    {\n\tone(x) == identity(op, x);\n    }\n};\n\n\nauto concept MultiplicativeCommutativeMonoid<typename Element>\n  : MultiplicativeMonoid<Element>,\n    MultiplicativeCommutativeSemiGroup<Element>,\n    CommutativeMonoid< math::mult<Element>, Element >\n{};\n\n\nconcept MultiplicativePartiallyInvertibleMonoid<typename Element>\n  : MultiplicativeMonoid<Element>,\n    PartiallyInvertibleMonoid< math::mult<Element>, Element >\n{\n    typename divide_assign_result_type;  \n    divide_assign_result_type operator/=(Element& x, Element y);\n    // requires std::Convertible<divide_assign_result_type, Element>;\n     \n    // Operator / by default defined with /=\n    typename division_result_type = Element;  \n    division_result_type operator/(Element x, Element y);\n#if 0\n    {\n\tElement tmp(x);\n\treturn tmp /= y;                      defaults NYS\n    }\n#endif \n    requires std::Convertible<division_result_type, Element>;\n    \n    axiom Consistency(math::mult<Element> op, Element x, Element y)\n    {\n\t// consistency between multiplicative and pure algebraic concept\n\tif ( is_invertible(op, y) )\n\t    op(x, inverse(op, y)) == x / y;            \n\n\t// Consistency between / and /=, might change later\n\tif ( is_invertible(op, y) )\n\t    x / y == x /= y;              \n\t// Element tmp = x; tmp/= y; tmp == x / y; not proposal-compliant \n    }  \n};\n \n\nauto concept MultiplicativePartiallyInvertibleCommutativeMonoid<typename Element>\n  : MultiplicativePartiallyInvertibleMonoid<Element>,\n    MultiplicativeCommutativeMonoid<Element>,\n    PartiallyInvertibleCommutativeMonoid< math::mult<Element>, Element >\n{};\n \n\nauto concept MultiplicativeGroup<typename Element>\n  : MultiplicativeMonoid<Element>,\n    Group< math::mult<Element>, Element >\n{};\n\n\nauto concept MultiplicativeAbelianGroup<typename Element>\n  : MultiplicativeGroup<Element>,\n    MultiplicativeCommutativeMonoid<Element>,\n    AbelianGroup< math::mult<Element>, Element >\n{};\n\n\n// ======================================\n// Algebraic concepts with two connectors\n// ======================================\n\n// -----------------\n// Based on functors\n// -----------------\n\n// More generic, less handy to use\n\nauto concept GenericRing<typename AddOp, typename MultOp, typename Element>\n  : AbelianGroup<AddOp, Element>,\n    SemiGroup<MultOp, Element>,\n    algebra::Ring<AddOp, MultOp, Element>\n{};\n\n\nauto concept GenericCommutativeRing<typename AddOp, typename MultOp, typename Element>\n  : GenericRing<AddOp, MultOp, Element>,\n    CommutativeSemiGroup<MultOp, Element>\n{};\n\n\nauto concept GenericRingWithIdentity<typename AddOp, typename MultOp, typename Element>\n  : GenericRing<AddOp, MultOp, Element>,\n    Monoid<MultOp, Element>,\n    algebra::RingWithIdentity<AddOp, MultOp, Element>\n{};\n\n\nauto concept GenericCommutativeRingWithIdentity<typename AddOp, typename MultOp, typename Element>\n  : GenericRingWithIdentity<AddOp, MultOp, Element>,\n    GenericCommutativeRing<AddOp, MultOp, Element>,\n    CommutativeMonoid<MultOp, Element>\n{};\n\n\n// auto\nconcept GenericDivisionRing<typename AddOp, typename MultOp, typename Element>\n  : GenericRingWithIdentity<AddOp, MultOp, Element>,\n    algebra::DivisionRing<AddOp, MultOp, Element>\n{\n    requires std::Convertible<inverse_result_type, Element>;\n};    \n\n\nauto concept GenericField<typename AddOp, typename MultOp, typename Element>\n  : GenericDivisionRing<AddOp, MultOp, Element>,\n    GenericCommutativeRingWithIdentity<AddOp, MultOp, Element>,\n    algebra::Field<AddOp, MultOp, Element>\n{};\n\n\n// ------------------\n// Based on operators \n// ------------------\n\n// Handier, less generic\n\n// Alternative definitions use MultiplicativeMonoid<Element> for Ring\n// and call such concepts Pseudo-Ring\n\n\nauto concept Ring<typename Element>\n  : AdditiveAbelianGroup<Element>,\n    MultiplicativeSemiGroup<Element>,\n    GenericRing<math::add<Element>, math::mult<Element>, Element>\n{};\n\n\nauto concept CommutativeRing<typename Element>\n  : Ring<Element>,\n    MultiplicativeCommutativeSemiGroup<Element>,\n    GenericCommutativeRing<math::add<Element>, math::mult<Element>, Element>    \n{};\n\n\nauto concept RingWithIdentity<typename Element>\n  : Ring<Element>,\n    MultiplicativeMonoid<Element>,\n    GenericRingWithIdentity<math::add<Element>, math::mult<Element>, Element>\n{};\n \n\nauto concept CommutativeRingWithIdentity<typename Element>\n  : RingWithIdentity<Element>,\n    CommutativeRing<Element>,\n    MultiplicativeCommutativeMonoid<Element>,\n    GenericCommutativeRingWithIdentity<math::add<Element>, math::mult<Element>, Element>\n{};\n\n\nconcept DivisionRing<typename Element>\n  : RingWithIdentity<Element>,\n    MultiplicativePartiallyInvertibleMonoid<Element>, \n    GenericDivisionRing<math::add<Element>, math::mult<Element>, Element>\n{\n    axiom NonZeroDivisibility(Element x)\n    {\n\tif (x != zero(x)) \n\t    x / x == one(x);\n    }\n};    \n\n\nauto concept Field<typename Element>\n  : DivisionRing<Element>,\n    CommutativeRingWithIdentity<Element>,\n    GenericField<math::add<Element>, math::mult<Element>, Element>\n{};\n\n\n// ======================\n// Miscellaneous concepts\n// ======================\n\n// that shall find a better place later\n\n\n// EqualityComparable will have the != when defaults are supported\n// At this point the following won't needed anymore\nauto concept FullEqualityComparable<typename T, typename U = T>\n{\n  //requires std::EqualityComparable<T, U>;\n\n    bool operator==(const T&, const U&);\n    bool operator!=(const T&, const U&);\n};\n\n// Closure of EqualityComparable under a binary operation:\n// That is, the result of this binary operation is also EqualityComparable\n// with itself and with the operand type.\nauto concept Closed2EqualityComparable<typename Operation, typename Element>\n  : BinaryIsoFunction<Operation, Element>\n{\n    requires FullEqualityComparable<Element>;\n    requires FullEqualityComparable< BinaryIsoFunction<Operation, Element>::result_type >;\n    requires FullEqualityComparable< Element, BinaryIsoFunction<Operation, Element>::result_type >;\n    requires FullEqualityComparable< BinaryIsoFunction<Operation, Element>::result_type, Element >;\n};\n\n\n// LessThanComparable will have the other operators when defaults are supported\n// At this point the following won't needed anymore\nauto concept FullLessThanComparable<typename T, typename U = T>\n{\n    bool operator<(const T&, const U&);\n    bool operator<=(const T&, const U&);\n    bool operator>(const T&, const U&);\n    bool operator>=(const T&, const U&);\n};\n\n\n// Same for LessThanComparable\nauto concept Closed2LessThanComparable<typename Operation, typename Element>\n  : BinaryIsoFunction<Operation, Element>\n{\n    requires FullLessThanComparable<Element>;\n    requires FullLessThanComparable< BinaryIsoFunction<Operation, Element>::result_type >;\n    requires FullLessThanComparable< Element, BinaryIsoFunction<Operation, Element>::result_type >;\n    requires FullLessThanComparable< BinaryIsoFunction<Operation, Element>::result_type, Element >;\n};\n\n#if 0\nauto concept NumericOperatorResultConvertible<typename T>\n  : AddableWithAssign<T>,\n    SubtractableWithAssign<T>,\n    MultiplicableWithAssign<T>,\n    DivisibleWithAssign<T>\n{\n    requires std::Convertible< AddableWithAssign<T>::result_type, T>;\n    requires std::Convertible< SubtractableWithAssign<T>::result_type, T>;\n    requires std::Convertible< MultiplicableWithAssign<T>::result_type, T>;\n    requires std::Convertible< DivisibleWithAssign<T>::result_type, T>;\n}\n#endif\n\nauto concept AdditionResultConvertible<typename T>\n{\n    typename result_type;\n    result_type operator+(T t, T u);\n    requires std::Convertible<result_type, T>;\n\n    typename result_type;\n    result_type operator+=(T& t, T u);\n    requires std::Convertible<result_type, T>;\n};    \n\n\nauto concept SubtractionResultConvertible<typename T>\n{\n    typename result_type;\n    result_type operator-(T t, T u);\n    requires std::Convertible<result_type, T>;\n\n    typename result_type;\n    result_type operator-=(T& t, T u);\n    requires std::Convertible<result_type, T>;\n};    \n\nauto concept NumericOperatorResultConvertible<typename T>\n  : AdditionResultConvertible<T>,\n    SubtractionResultConvertible<T>\n{};\n\n// ====================\n// Default Concept Maps\n// ====================\n\n#ifndef LA_NO_CONCEPT_MAPS\n\n// ==============\n// Integral Types\n// ==============\n\ntemplate <typename T>\n  requires IntrinsicSignedIntegral<T>\nconcept_map CommutativeRingWithIdentity<T> {}\n\n\ntemplate <typename T>\n  requires IntrinsicUnsignedIntegral<T>\nconcept_map AdditiveCommutativeMonoid<T> {}\n\ntemplate <typename T>\n  requires IntrinsicUnsignedIntegral<T>\nconcept_map MultiplicativeCommutativeMonoid<T> {}\n\n\n// ====================\n// Floating Point Types\n// ====================\n\ntemplate <typename T>\n  requires IntrinsicFloatingPoint<T>\nconcept_map Field<T> {}\n\n\ntemplate <typename T>\n  requires IntrinsicFloatingPoint<T>\nconcept_map Field< std::complex<T> > {}\n\n\n// ===========\n// Min and Max\n// ===========\n\n// Draft version: defined generously unless there will be problems with some types\n\ntemplate <typename Element>\nconcept_map CommutativeMonoid< max<Element>, Element > \n{\n    // Why do we need this?\n    typedef Element identity_result_type;\n}\n\ntemplate <typename Element>\nconcept_map CommutativeMonoid< min<Element>, Element >\n{\n    // Why do we need this?\n    typedef Element identity_result_type;\n}\n\n#endif // LA_NO_CONCEPT_MAPS\n\n// Here come some mathematical concepts to be defined later\n\n/// Specify the semantic Behavior of natural numbers (TBD)\n/** Mathematic properties are in most cases only approximated\n    but not held exactly. Rigorous definition would impede\n    usage of real processors. **/\nconcept NaturalNumber<typename T> {}\n\n/// Specify the semantic Behavior of integral numbers (TBD)\n/** Mathematic properties are in most cases only approximated\n    but not held exactly. Rigorous definition would impede\n    usage of real processors.\n    It is arguable if this is really a refinement **/\nconcept IntegralNumber<typename T> : NaturalNumber<T> {}\n    \n/// Specify the semantic Behavior of complex numbers (TBD)\n/** Mathematic properties are in most cases only approximated\n    but not held exactly. Rigorous definition would impede\n    usage of real processors. **/\nconcept ComplexNumber<typename T> {}\n\n/// Specify the semantic Behavior of real numbers (TBD)\n/** Mathematic properties are in most cases only approximated\n    but not held exactly. Rigorous definition would impede\n    usage of real processors. **/\nconcept RealNumber<typename T> : ComplexNumber<T> {}\n\n#endif // __GXX_CONCEPTS__\n\n\n\n\n// =================================================\n// Concept to specify return type of abs (and norms)\n// =================================================\n\n\n#ifdef __GXX_CONCEPTS__\n\n// Concept to specify to specify projection of scalar value to comparable type\n// For instance as return type of abs\n// Minimalist definition for maximal applicability\nauto concept Magnitude<typename T>\n{\n    typename type = T;\n};\n\ntemplate <typename T>\nconcept_map Magnitude<std::complex<T> >\n{\n    typedef T type;\n}\n\n\n// Concept for norms etc., which are real values in mathematical definitions\nauto concept RealMagnitude<typename T>\n  : Magnitude<T>\n{\n    requires FullEqualityComparable<type>;\n    requires FullLessThanComparable<type>;\n\n    requires Field<type>;\n\n    type sqrt(type);\n    // typename sqrt_result;\n    // sqrt_result sqrt(type);\n    // requires std::Convertible<sqrt_result, type>;\n\n    // using std::abs;\n    type abs(T);\n}\n\n#else  // now without concepts\n\ntemplate <typename T>\nstruct Magnitude\n{\n    typename type = T;\n};\n\ntemplate <typename T>\nstruct Magnitude<std::complex<T> >\n{\n    typedef T type;\n}\n\ntemplate <typename T> struct RealMagnitude\n  : public Magnitude<T>\n{}\n\n#endif  // __GXX_CONCEPTS__\n\n// Type trait version both available with and w/o concepts (TBD: Macro finally :-( )\n// For the moment everything is its own magnitude type, unless stated otherwise\ntemplate <typename T>\nstruct magnitude_type_trait\n{\n    typedef T type;\n};\n\ntemplate <typename T>\nstruct magnitude_type_trait< std::complex<T> >\n{\n    typedef T type;\n};\n\n\n// =========================================\n// Concepts for convenience (many from Rolf)\n// =========================================\n\n\n#ifdef __GXX_CONCEPTS__\n\n//The following concepts Addable, Subtractable etc. differ from std::Addable, std::Subtractable \n//etc. in so far that no default for result_type is provided, thus allowing automated return type deduction\n\nauto concept Addable<typename T, typename U = T>\n{\n    typename result_type;\n    result_type operator+(const T& t, const U& u);\n};\n  \n \n// Usually + and += are both defined\n// + can be efficiently derived from += but not vice versa\nauto concept AddableWithAssign<typename T, typename U = T>\n{\n    typename assign_result_type;  \n    assign_result_type operator+=(T& x, U y);\n\n    // Operator + is by default defined with +=\n    typename result_type;  \n    result_type operator+(T x, U y);\n#if 0\n    {\n\t// Default requires std::CopyConstructible, without default not needed\n\tElement tmp(x);                       \n\treturn tmp += y;                      defaults NYS\n    }\n#endif \n};\n\n\nauto concept Subtractable<typename T, typename U = T>\n{\n    typename result_type;\n    result_type operator-(const T& t, const U& u);\n};\n  \n\n// Usually - and -= are both defined\n// - can be efficiently derived from -= but not vice versa\nauto concept SubtractableWithAssign<typename T, typename U = T>\n{\n    typename assign_result_type;  \n    assign_result_type operator-=(T& x, U y);\n\n    // Operator - is by default defined with -=\n    typename result_type;  \n    result_type operator-(T x, U y);\n#if 0\n    {\n\t// Default requires std::CopyConstructible, without default not needed\n\tElement tmp(x);                       \n\treturn tmp -= y;                      defaults NYS\n    }\n#endif \n};\n\n\nauto concept Multiplicable<typename T, typename U = T>\n{\n    typename result_type;\n    result_type operator*(const T& t, const U& u);\n};\n\n\n// Usually * and *= are both defined\n// * can be efficiently derived from *= but not vice versa\nauto concept MultiplicableWithAssign<typename T, typename U = T>\n{\n    typename assign_result_type;  \n    assign_result_type operator*=(T& x, U y);\n\n    // Operator * is by default defined with *=\n    typename result_type;  \n    result_type operator*(T x, U y);\n#if 0\n    {\n\t// Default requires std::CopyConstructible, without default not needed\n\tElement tmp(x);                       \n\treturn tmp *= y;                      defaults NYS\n    }\n#endif \n};\n\n\nauto concept Divisible<typename T, typename U = T>\n{\n    typename result_type;\n    result_type operator / (const T&, const U&);\n};\n\n\n// Usually * and *= are both defined\n// * can be efficiently derived from *= but not vice versa\nauto concept DivisibleWithAssign<typename T, typename U = T>\n{\n    typename assign_result_type;  \n    assign_result_type operator*=(T& x, U y);\n\n    // Operator * is by default defined with *=\n    typename result_type;  \n    result_type operator*(T x, U y);\n#if 0\n    {\n\t// Default requires std::CopyConstructible, without default not needed\n\tElement tmp(x);                       \n\treturn tmp *= y;                      defaults NYS\n    }\n#endif \n};\n\n\nauto concept Transposable<typename T>\n{\n    typename result_type;\n    result_type trans(T&);\n};  \n\n\n// Unary Negation -> Any suggestions for better names?! Is there a word as \"negatable\"?!\nauto concept Negatable<typename S>\n{\n    typename result_type = S;\n    result_type operator-(const S&);\n};\n\n// Or HasAbs?\nusing std::abs;\nauto concept AbsApplicable<typename S>\n{\n    // There are better ways to define abs than the way it is done in std\n    // Likely we replace the using one day\n    typename result_type;\n    result_type abs(const S&);\n};\n\n\nusing std::conj;\nauto concept HasConjugate<typename S>\n{\n    typename result_type;\n    result_type conj(const S&);\n};\n  \n  \n// We need the following; might be placed somewhere else later\ntemplate <Float T>\nconcept_map HasConjugate<T> \n{ \n    typedef T result_type;\n    result_type conj(const T& s) {return s;}\n}\n\n\n\n// Dot product to be defined:\nauto concept Dottable<typename T, typename U = T>\n{\n    typename result_type = T;\n    result_type dot(const T&t, const U& u);\n};\n    \n\nauto concept OneNormApplicable<typename V> \n{\n    typename result_type;\n    result_type one_norm(const V&);\n};\n\n\nauto concept TwoNormApplicable<typename V> \n{\n    typename result_type;\n    result_type two_norm(const V&);\n};\n\n\nauto concept InfinityNormApplicable<typename V> \n{\n    typename result_type;\n    result_type inf_norm(const V&);\n};\n\n\n\n\n#endif  // __GXX_CONCEPTS__\n\n\n} // namespace math\n\n\n\n#endif // LA_CONCEPTS_INCLUDE\n", "meta": {"hexsha": "128551e701255dd5d236d1499af60eebe9e5037f", "size": 31930, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/linear_algebra/old_concepts.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/linear_algebra/old_concepts.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "lib/mtl4/boost/numeric/linear_algebra/old_concepts.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 27.525862069, "max_line_length": 107, "alphanum_fraction": 0.6964610085, "num_tokens": 7318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.24902597501361742}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n#include <boost/cast.hpp>       //temporary!\n#include <boost/math/special_functions/fpclassify.hpp>\n#include \"probability_distribution.hpp\"\n#include \"relative_rate_distribution.hpp\"\n#include \"model.hpp\"\n#include \"basic_tree_node.hpp\"\n#include \"tree_likelihood.hpp\"\n#include \"xlikelihood.hpp\"\n#include \"mcmc_chain_manager.hpp\"\n#include \"dirichlet_move.hpp\"\n#include \"state_freq_move.hpp\"\n#include \"basic_tree.hpp\"\n#include \"tree_manip.hpp\"\n#include \"gtr.hpp\"\n#include \"hky.hpp\"\n\nusing namespace phycas;\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tThe constructor simply calls the base class (DirichletMove) constructor.\n*/\nStateFreqMove::StateFreqMove() : DirichletMove()\n\t{\n\tdim = 4;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets the state frequencies of the associated HKY or GTR model to those in the supplied vector `v'.\n*/\nvoid StateFreqMove::sendCurrValuesToModel(const double_vect_t & v)\n\t{\n\tPHYCAS_ASSERT(dim == v.size());\n\tmodel->setStateFreqsUnnorm(v);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tObtains the current state frequencies from the model, storing them in the supplied vector `v'.\n*/\nvoid StateFreqMove::getCurrValuesFromModel(double_vect_t & v) const\n\t{\n\tPHYCAS_ASSERT(dim > 0);\n\tif (model)\n\t\t{\n    \tconst std::vector<double> & rfreqs = model->getStateFreqs();\n    \tv.resize(rfreqs.size());\n\t\tPHYCAS_ASSERT(dim == rfreqs.size());\n    \tstd::copy(rfreqs.begin(), rfreqs.end(), v.begin());\n    \t}\n    else\n    \t{\n    \tv.assign(dim, 1.0/(double)dim);\n    \t}\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tObtains the current state frequencies from the model, returning them as an anonymous vector.\n*/\ndouble_vect_t StateFreqMove::listCurrValuesFromModel()\n\t{\n\tPHYCAS_ASSERT(dim > 0);\n\tdouble_vect_t v(dim);\n\tif (model)\n\t\t{\n    \tconst std::vector<double> & rfreqs = model->getStateFreqs();\n\t\tPHYCAS_ASSERT(dim == rfreqs.size());\n    \tstd::copy(rfreqs.begin(), rfreqs.end(), v.begin());\n    \t}\n    else\n    \t{\n    \tv.assign(dim, 1.0/(double)dim);\n    \t}\n\treturn v;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tObtains the current state frequencies from the model, storing them in the data member `orig_params'.\n*/\nvoid StateFreqMove::getParams()\n\t{\n\tgetCurrValuesFromModel(orig_params);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReplaces the state frequencies in the model with those supplied in the vector `v'.\n*/\nvoid StateFreqMove::setParams(\n  const std::vector<double> & v)    /*< is the vector of parameter values to send to the model */\n\t{\n    model->setStateFreqsUnnorm(v);\n\t}\n\n", "meta": {"hexsha": "cf559a1bfa680ecda249d0edd8a29ba460385c0e", "size": 4437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/state_freq_move.cpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/state_freq_move.cpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/state_freq_move.cpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 40.3363636364, "max_line_length": 120, "alphanum_fraction": 0.5057471264, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24901745751771548}}
{"text": "/*\n* Copyright 2019 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés\n*/\n\n#ifndef SYSTEMGEOMETRY_H\n#define SYSTEMGEOMETRY_H\n\n#include <Eigen/Dense>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include \"utils/Constants.hpp\"\n#include \"utils/Exception.hpp\"\n#include \"Attitude.hpp\"\n\n/*!\n* \\brief Survey system class\n* \\author Guillaume Labbe-Morissette, Jordan McManus\n* \\date August 20, 2018, 1:07 PM\n*/\nclass SurveySystem {\npublic:\n\n  /**Creates a Survey system*/\n  SurveySystem();\n\n  /**Destroys the Survey system*/\n  ~SurveySystem();\n\n  /**Returns the MBES model*/\n  std::string & getMBES_model() {\n    return MBES_model;\n  }\n\n  /**Returns the antenna position*/\n  Eigen::Vector3d & getAntennaPosition() {\n    return antennaPosition;\n  }\n\n  /**Returns the attitude accuracy*/\n  Attitude * getAttitudeAccuracy() {\n    return attitudeAccuracy;\n  }\n\n  /**Returns the boresigth patch test*/\n  Attitude * getBoresightPatchTest() {\n    return boresightPatchTest;\n  }\n\n  /**Returns the draft*/\n  double getDraft() {\n    return draft;\n  }\n\n  /**Returns the echo sounder receiver position*/\n  Eigen::Vector3d & getEchosounderReceivererPosition() {\n    return echosounderReceivererPosition;\n  }\n\n  /**Returns the echo sounder transmitter position*/\n  Eigen::Vector3d & getEchosounderTransmitterPosition() {\n    return echosounderTransmitterPosition;\n  }\n\n  /**Returns the position accuracy*/\n  Eigen::Vector3d & getPositionAccuracy() {\n    return positionAccuracy;\n  }\n\n  /**\n  * Change the Survey system values by reading a file\n  * Return false if the file is not valid\n  *\n  * @param filename name of the file that will be read\n  */\n  bool readFile(const std::string & fileName);\n\nprivate:\n\n  /**Name of the Survey system MBES model*/\n  std::string MBES_model;\n\n  /**Value of the Survey system draft (meter)*/\n  double draft; // in meters\n\n  // positions in the IMU reference frame in meters\n\n  /**Vector3d of the Survey system antenna position*/\n  Eigen::Vector3d antennaPosition;\n\n  /**Vector3d of the Survey system echo sounder transmitter position*/\n  Eigen::Vector3d echosounderTransmitterPosition;\n\n  /**Vector3d of the Survey system echo sounder receiver position*/\n  Eigen::Vector3d echosounderReceivererPosition;\n\n  // angles in degrees\n  // will be converted internally to radians\n  /**Value of the Survey system boresigth path test (Attitude)*/\n  Attitude* boresightPatchTest = NULL;\n\n  // accuracy in 2 sigma\n  /**Value of the Survey system attitude accuracy (Attitude)*/\n  Attitude* attitudeAccuracy = NULL;\n\n  /**Vector3d of the Survey system position accuracy*/\n  Eigen::Vector3d positionAccuracy;\n};\n\nSurveySystem::SurveySystem() {\n}\n\nSurveySystem::~SurveySystem() {\n  if (boresightPatchTest) {\n    delete boresightPatchTest;\n  }\n\n  if (attitudeAccuracy) {\n    delete attitudeAccuracy;\n  }\n}\n\nbool SurveySystem::readFile(const std::string & fileName) {\n\n  // Temporary placeholder variables\n  std::string NameDevice;\n  double Patch_Roll = 0, Patch_Pitch = 0, Patch_Heading = 0;\n  double MBES_X = 0, MBES_Y = 0, MBES_Z = 0;\n  double MBES_RX = 0, MBES_RY = 0, MBES_RZ = 0;\n  double AntX = 0, AntY = 0, AntZ = 0;\n  double Draft = 0;\n\n  double PitchRollAcc, HeadingAcc;\n  double PosHorAcc, PosVerAcc;\n\n  //double Eroll = 0, Epitch = 0, Eyaw = 0, Rroll = 0, Rpitch = 0, Ryaw = 0, Mroll = 0, Mpitch = 0, Myaw = 0;\n\n  // Open file\n  std::string line;\n  std::ifstream file(fileName);\n\n  /*\n  * This is cancer, no validation of correctness or presence of data\n  * TODO:\n  * Should return false if data is missing or is invalid\n  */\n  if (!file) {\n    return false;\n  } else {\n    for (std::string line; getline(file, line);) {\n      //make a stream for the line itself\n      std::istringstream in(line);\n\n      std::string type;\n      in >> type;\n\n      if (type == \"MultibeamModel\") {\n        in >> NameDevice;\n      } else if (type == \"AntennaPositionOffsetX\") {\n        in >> AntX;\n      } else if (type == \"AntennaPositionOffsetY\") {\n        in >> AntY;\n      } else if (type == \"AntennaPositionOffsetZ\") {\n        in >> AntZ;\n      } else if (type == \"MBETransmitterOffsetX\") {\n        in >> MBES_X;\n      } else if (type == \"MBETransmitterOffsetY\") {\n        in >> MBES_Y;\n      } else if (type == \"MBETransmitterOffsetZ\") {\n        in >> MBES_Z;\n      } else if (type == \"MBEDraft\") {\n        in >> Draft;\n      } else if (type == \"MBEReceiverOffsetX\") {\n        in >> MBES_RX;\n      } else if (type == \"MBEReceiverOffsetY\") {\n        in >> MBES_RY;\n      } else if (type == \"MBEReceiverOffsetZ\") {\n        in >> MBES_RZ;\n      } else if (type == \"PositionAccuracy\") {\n        in >> PosHorAcc;\n        PosVerAcc = PosHorAcc * 1.5;\n      } else if (type == \"PitchRollAccuracy\") {\n        in >> PitchRollAcc;\n      } else if (type == \"HeadingAccuracy\") {\n        in >> HeadingAcc;\n      } else if (type == \"RollAlignment\") {\n        in >> Patch_Roll;\n      } else if (type == \"PitchAlignment\") {\n        in >> Patch_Pitch;\n      } else if (type == \"HeadingAlignment\") {\n        in >> Patch_Heading;\n      }/* else if (type == \"MBEOffsetR\") {\n        in >> Eroll;\n      } else if (type == \"MBEOffsetP\") {\n      in >> Epitch;\n    } else if (type == \"MBEOffsetH\") {\n    in >> Eyaw;\n  } else if (type == \"MBEOffset2R\") {\n  in >> Rroll;\n} else if (type == \"MBEOffset2P\") {\nin >> Rpitch;\n} else if (type == \"MBEOffset2H\") {\nin >> Ryaw;\n} else if (type == \"MotionSensorR\") {\nin >> Mroll;\n} else if (type == \"MotionSensorP\") {\nin >> Mpitch;\n} else if (type == \"MotionSensorH\") {\nin >> Myaw;\n}*/\n}\n\nfile.close();\n\nMBES_model = NameDevice;\n\ndraft = Draft;\n\nantennaPosition << AntX, AntY, -AntZ;\nechosounderTransmitterPosition << MBES_X, MBES_Y, -MBES_Z;\nechosounderReceivererPosition << MBES_RX, MBES_RY, -MBES_RZ;\n\nboresightPatchTest = new Attitude(0,Patch_Roll, Patch_Pitch, Patch_Heading);\n\nattitudeAccuracy = new Attitude(0,PitchRollAcc, PitchRollAcc, HeadingAcc);\n\npositionAccuracy << PosHorAcc, PosHorAcc, PosVerAcc;\n\nreturn true;\n}\n}\n\n\n\n#endif /* SYSTEMGEOMETRY_H */\n", "meta": {"hexsha": "d126e3470845c4ec350d92badf94a577f12c3e1d", "size": 6053, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/SurveySystem.hpp", "max_stars_repo_name": "CBcidco/MBES-lib", "max_stars_repo_head_hexsha": "6b7759554db48c62d6b350d315283eb3fe0fd009", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T14:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T06:44:37.000Z", "max_issues_repo_path": "src/SurveySystem.hpp", "max_issues_repo_name": "CBcidco/MBES-lib", "max_issues_repo_head_hexsha": "6b7759554db48c62d6b350d315283eb3fe0fd009", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2019-04-16T13:53:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T19:44:23.000Z", "max_forks_repo_path": "src/SurveySystem.hpp", "max_forks_repo_name": "CBcidco/MBES-lib", "max_forks_repo_head_hexsha": "6b7759554db48c62d6b350d315283eb3fe0fd009", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-04-10T19:51:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T21:42:22.000Z", "avg_line_length": 25.5400843882, "max_line_length": 118, "alphanum_fraction": 0.6515777301, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.24896578926620103}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/functional/hash.hpp>  // IWYU pragma: keep\n#include <cstddef>\n#include <limits>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/DataBox/DataBoxTag.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"Domain/Element.hpp\"  // IWYU pragma: keep\n#include \"ErrorHandling/Assert.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/MeanValue.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Utilities/ForceInline.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeArray.hpp\"\n#include \"Utilities/TMPL.hpp\"\n#include \"Utilities/TaggedTuple.hpp\"\n\n/// \\cond\nclass DataVector;\ntemplate <size_t VolumeDim>\nclass Direction;\ntemplate <size_t VolumeDim>\nclass ElementId;\ntemplate <size_t VolumeDim>\nclass Mesh;\ntemplate <size_t VolumeDim>\nclass OrientationMap;\n\nnamespace PUP {\nclass er;\n}  // namespace PUP\n\nnamespace SlopeLimiters {\ntemplate <size_t VolumeDim, typename TagsToLimit>\nclass Minmod;\n}  // namespace SlopeLimiters\n\nnamespace Tags {\ntemplate <size_t Dim, typename Frame>\nstruct Coordinates;\ntemplate <size_t VolumeDim>\nstruct Element;\ntemplate <size_t VolumeDim>\nstruct Mesh;\ntemplate <size_t VolumeDim>\nstruct SizeOfElement;\n}  // namespace Tags\n/// \\endcond\n\nnamespace SlopeLimiters {\n/// \\ingroup SlopeLimitersGroup\n/// \\brief Possible types of the minmod slope limiter.\n///\n/// \\see SlopeLimiters::Minmod\nenum class MinmodType { LambdaPi1, LambdaPiN, Muscl };\n}  // namespace SlopeLimiters\n\nnamespace Minmod_detail {\n// Encodes the return status of the minmod_tvbm function.\nstruct MinmodResult {\n  const double value;\n  const bool activated;\n};\n\n// The TVBM-corrected minmod function, see e.g. Cockburn reference Eq. 2.26.\nMinmodResult minmod_tvbm(double a, double b, double c,\n                         double tvbm_scale) noexcept;\n\n// Implements the minmod limiter for one Tensor<DataVector>.\n//\n// The interface is designed to erase the tensor structure information, because\n// this way the implementation can be moved out of the header file. This is\n// achieved by receiving Tensor<DataVector>::iterators into the tensor to limit,\n// and Tensor<double>::iterators into the neighbor tensors.\n//\n// Note: because the interface erases the tensor structure information, we can\n// no longer rely on the compiler to enforce that the local and neighbor tensors\n// share the same Structure.\ntemplate <size_t VolumeDim>\nbool limit_one_tensor(\n    gsl::not_null<DataVector*> tensor_begin,\n    gsl::not_null<DataVector*> tensor_end,\n    const SlopeLimiters::MinmodType& minmod_type, double tvbm_constant,\n    const Element<VolumeDim>& element, const Mesh<VolumeDim>& mesh,\n    const tnsr::I<DataVector, VolumeDim, Frame::Logical>& logical_coords,\n    const std::array<double, VolumeDim>& element_size,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n        gsl::not_null<const double*>,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_tensor_begin,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n        std::array<double, VolumeDim>,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_sizes) noexcept;\n\ntemplate <typename Tag>\nstruct to_tensor_double : db::PrefixTag, db::SimpleTag {\n  using type = TensorMetafunctions::swap_type<double, db::item_type<Tag>>;\n  using tag = Tag;\n  static std::string name() noexcept {\n    return \"TensorDouble(\" + Tag::name() + \")\";\n  }\n};\n}  // namespace Minmod_detail\n\nnamespace SlopeLimiters {\n/// \\ingroup SlopeLimitersGroup\n/// \\brief A generic Minmod slope limiter\n///\n/// Implements the minmod-based slope limiter from\n/// \\ref cockburn_ref \"Cockburn (1999)\", Section 2.4.\n/// Three types of minmod limiter from the reference are implemented:\n/// \\f$\\Lambda\\Pi^1\\f$, \\f$\\Lambda\\Pi^N\\f$, and MUSCL.\n///\n/// This minmod limiter has a generic implementation that can work on an\n/// arbitrary set of tensors. The minmod limiting algorithm is applied to each\n/// component of each tensor independently. In general, the limiter linearizes\n/// the tensors on every DG element, each time it is applied; additionally, the\n/// limiter may reduce the spatial slope of some tensor components if the data\n/// look like they may contain oscillations.\n///\n/// The key features differentiating the three minmod limiter types are:\n/// 1. The `Muscl` limiter is the most dissipative; it more aggressively reduces\n///    the slopes of the data. This limiter may better handle strong shocks, but\n///    also produces the most broadening of features.\n/// 2. The `LambdaPiN` limiter is the least aggressive; its \"troubled cell\"\n///    detector tries to avoid limiting in DG elements where the data look\n///    smooth enough. Where `LambdaPiN` is able to avoid limiting, the data are\n///    _not_ linearized, and the post-limiter data are identical to the\n///    pre-limiter data.\n/// 3. The `LambdaPi1` limiter is a middle-ground option between the other two.\n///    It does not try to avoid limiting as much as `LambdaPiN`, but it allows\n///    larger slopes in the data than `Muscl`.\n///\n/// For all three types of minmod limiter the \"total variation bound in the\n/// means\" (TVBM) correction is implemented, enabling the limiter to avoid\n/// limiting away smooth extrema in the solution that would otherwise look like\n/// spurious oscillations. The limiter will not reduce the slope (but will still\n/// linearize) on elements where the slope is less than \\f$m h^2\\f$, where\n/// \\f$m\\f$ is the TVBM constant and \\f$h\\f$ is the size of the DG element.\n///\n/// The limiter acts in the `Frame::Logical` coordinates, because in these\n/// coordinates it is straightforward to formulate the algorithm. This means the\n/// limiter can operate on generic deformed grids. However, if the grid is too\n/// strongly deformed, some things can start to break down:\n/// 1. When an element is deformed so that the Jacobian (from `Frame::Logical`\n///    to `Frame::Inertial`) varies across the element, then the limiter fails\n///    to be conservative. In other words, the integral of a tensor `u` over the\n///    element will change after the limiter activates on `u`. This error is\n///    typically small.\n/// 2. When there is a sudden change in the size of the elements (perhaps at an\n///    h-refinement boundary, or at the boundary between two blocks with very\n///    different mappings), a smooth solution in `Frame::Inertial` can appear\n///    to have a kink in `Frame::Logical`. The Minmod implementation includes\n///    some (untested) tweaks that try to reduce spurious limiter activations\n///    near these fake kinks.\n///\n/// When an element has multiple neighbors in any direction, an effective mean\n/// and neighbor size in this direction are computed by averaging over the\n/// multiple neighbors. This simple generalization of the minmod limiter enables\n/// it to operate on h-refined grids.\n///\n/// \\tparam VolumeDim The number of spatial dimensions.\n/// \\tparam Tags A typelist of tags specifying the tensors to limit.\n///\n/// \\anchor cockburn_ref [1] B. Cockburn,\n/// Discontinuous Galerkin Methods for Convection-Dominated Problems,\n/// [Springer (1999)](https://doi.org/10.1007/978-3-662-03882-6_2)\ntemplate <size_t VolumeDim, typename... Tags>\nclass Minmod<VolumeDim, tmpl::list<Tags...>> {\n public:\n  /// \\brief The MinmodType\n  ///\n  /// One of `SlopeLimiters::MinmodType`. See `SlopeLimiters::Minmod`\n  /// documentation for details.\n  struct Type {\n    using type = MinmodType;\n    static constexpr OptionString help = {\"Type of minmod\"};\n  };\n  /// \\brief The TVBM constant\n  ///\n  /// See `SlopeLimiters::Minmod` documentation for details.\n  struct TvbmConstant {\n    using type = double;\n    static type default_value() { return 0.0; }\n    static type lower_bound() { return 0.0; }\n    static constexpr OptionString help = {\"TVBM constant 'm'\"};\n  };\n  using options = tmpl::list<Type, TvbmConstant>;\n  static constexpr OptionString help = {\n      \"A minmod-based slope limiter.\\n\"\n      \"The different types of minmod are more or less aggressive in trying\\n\"\n      \"to reduce slopes. The TVBM correction allows the limiter to ignore\\n\"\n      \"'small' slopes, and helps to avoid limiting of smooth extrema in the\\n\"\n      \"solution.\\n\"};\n\n  /// \\brief Constuct a Minmod slope limiter\n  ///\n  /// \\param minmod_type The type of Minmod slope limiter.\n  /// \\param tvbm_constant The value of the TVBM constant (default: 0).\n  explicit Minmod(const MinmodType minmod_type,\n                  const double tvbm_constant = 0.0) noexcept\n      : minmod_type_(minmod_type), tvbm_constant_(tvbm_constant) {\n    ASSERT(tvbm_constant >= 0.0, \"The TVBM constant must be non-negative.\");\n  }\n\n  Minmod() noexcept = default;\n  Minmod(const Minmod& /*rhs*/) = default;\n  Minmod& operator=(const Minmod& /*rhs*/) = default;\n  Minmod(Minmod&& /*rhs*/) noexcept = default;\n  Minmod& operator=(Minmod&& /*rhs*/) noexcept = default;\n  ~Minmod() = default;\n\n  // clang-tidy: google-runtime-references\n  void pup(PUP::er& p) noexcept {  // NOLINT\n    p | minmod_type_;\n    p | tvbm_constant_;\n  }\n\n  const MinmodType& minmod_type() const noexcept { return minmod_type_; }\n  const double& tvbm_constant() const noexcept { return tvbm_constant_; }\n\n  /// \\brief Data to send to neighbor elements.\n  struct PackagedData {\n    tuples::TaggedTuple<Minmod_detail::to_tensor_double<Tags>...> means_;\n    std::array<double, VolumeDim> element_size_ =\n        make_array<VolumeDim>(std::numeric_limits<double>::signaling_NaN());\n\n    // clang-tidy: google-runtime-references\n    void pup(PUP::er& p) noexcept {  // NOLINT\n      p | means_;\n      p | element_size_;\n    }\n  };\n\n  using package_argument_tags = tmpl::list<Tags..., ::Tags::Mesh<VolumeDim>,\n                                           ::Tags::SizeOfElement<VolumeDim>>;\n\n  /// \\brief Package data for sending to neighbor elements.\n  ///\n  /// The following quantities are stored in `PackagedData` and communicated\n  /// between neighboring elements:\n  /// - the cell-averaged mean of each tensor component, and\n  /// - the size of the cell along each logical coordinate direction.\n  ///\n  /// \\param packaged_data The data package to fill with this element's values.\n  /// \\param tensors The tensors to be averaged and packaged.\n  /// \\param mesh The mesh on which the tensor values are measured.\n  /// \\param element_size The size of the element in inertial coordinates, along\n  ///        each dimension of logical coordinates.\n  /// \\param orientation_map The orientation of the neighbor\n  void package_data(const gsl::not_null<PackagedData*>& packaged_data,\n                    const db::item_type<Tags>&... tensors,\n                    const Mesh<VolumeDim>& mesh,\n                    const std::array<double, VolumeDim>& element_size,\n                    const OrientationMap<VolumeDim>& orientation_map) const\n      noexcept {\n    const auto wrap_compute_means =\n        [&mesh, &packaged_data ](auto tag, const auto& tensor) noexcept {\n      for (size_t i = 0; i < tensor.size(); ++i) {\n        // Compute the mean using the local orientation of the tensor and mesh:\n        // this avoids the work of reorienting the tensor while giving the same\n        // result.\n        get<Minmod_detail::to_tensor_double<decltype(tag)>>(\n            packaged_data->means_)[i] = mean_value(tensor[i], mesh);\n      }\n      return '0';\n    };\n    expand_pack(wrap_compute_means(Tags{}, tensors)...);\n    packaged_data->element_size_ =\n        orientation_map.permute_from_neighbor(element_size);\n  }\n\n  using limit_tags = tmpl::list<Tags...>;\n  using limit_argument_tags =\n      tmpl::list<::Tags::Element<VolumeDim>, ::Tags::Mesh<VolumeDim>,\n                 ::Tags::Coordinates<VolumeDim, Frame::Logical>,\n                 ::Tags::SizeOfElement<VolumeDim>>;\n\n  /// \\brief Limits the solution on the element.\n  ///\n  /// For each component of each tensor, the limiter will (in general) linearize\n  /// the data, then possibly reduce its slope, dimension-by-dimension, until it\n  /// no longer looks oscillatory.\n  ///\n  /// \\param tensors The tensors to be limited.\n  /// \\param element The element on which the tensors to limit live.\n  /// \\param mesh The mesh on which the tensor values are measured.\n  /// \\param logical_coords The logical coordinates of the mesh gridpoints.\n  /// \\param element_size The size of the element, in the inertial coordinates.\n  /// \\param neighbor_data The data from each neighbor.\n  ///\n  /// \\return whether the limiter modified the solution or not.\n  ///\n  /// \\note The return value is false if the limiter knows it has not modified\n  /// the solution. True return values can indicate:\n  /// - The solution was limited to reduce the slope, whether by a large factor\n  ///   or by a factor only roundoff away from unity.\n  /// - The solution was linearized but not limited.\n  /// - The solution is identical to the input, if the input was a linear\n  ///   function on a higher-order mesh, so that the limiter cannot know that\n  ///   the linearization step did not actually modify the data. This is\n  ///   somewhat contrived and is unlikely to occur outside of code tests or\n  ///   test cases with very clean initial data.\n  bool operator()(\n      const gsl::not_null<std::add_pointer_t<db::item_type<Tags>>>... tensors,\n      const Element<VolumeDim>& element, const Mesh<VolumeDim>& mesh,\n      const tnsr::I<DataVector, VolumeDim, Frame::Logical>& logical_coords,\n      const std::array<double, VolumeDim>& element_size,\n      const std::unordered_map<\n          std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,\n          boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n          neighbor_data) const noexcept {\n    bool limiter_activated = false;\n    const auto wrap_limit_one_tensor = [\n      this, &limiter_activated, &element, &mesh, &logical_coords, &element_size,\n      &neighbor_data\n    ](auto tag, const auto& tensor) noexcept {\n      // Because we hide the types of Tags from limit_one_tensor (we do this so\n      // that its implementation isn't templated on Tags and can be moved out of\n      // this header file), we cannot pass it PackagedData as currently\n      // implemented. So we unpack everything from PackagedData. In the future\n      // we may want a PackagedData type that erases types inherently, as this\n      // would avoid the need for unpacking as done here.\n      //\n      // Get iterators into the local and neighbor tensors, because these are\n      // independent from the structure of the tensor being limited.\n      const auto tensor_begin = make_not_null(tensor->begin());\n      const auto tensor_end = make_not_null(tensor->end());\n      const auto neighbor_tensor_begin = [&neighbor_data]() noexcept {\n        std::unordered_map<\n            std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n            gsl::not_null<const double*>,\n            boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n            result;\n        for (const auto& neighbor_and_data : neighbor_data) {\n          result.insert(std::make_pair(\n              neighbor_and_data.first,\n              make_not_null(get<Minmod_detail::to_tensor_double<decltype(tag)>>(\n                                neighbor_and_data.second.means_)\n                                .cbegin())));\n        }\n        return result;\n      }\n      ();\n      const auto neighbor_sizes = [&neighbor_data]() noexcept {\n        std::unordered_map<\n            std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n            std::array<double, VolumeDim>,\n            boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n            result;\n        for (const auto& neighbor_and_data : neighbor_data) {\n          result.insert(std::make_pair(neighbor_and_data.first,\n                                       neighbor_and_data.second.element_size_));\n        }\n        return result;\n      }\n      ();\n\n      limiter_activated =\n          Minmod_detail::limit_one_tensor<VolumeDim>(\n              tensor_begin, tensor_end, minmod_type_, tvbm_constant_, element,\n              mesh, logical_coords, element_size, neighbor_tensor_begin,\n              neighbor_sizes) or\n          limiter_activated;\n      return '0';\n    };\n    expand_pack(wrap_limit_one_tensor(Tags{}, tensors)...);\n    return limiter_activated;\n  }\n\n private:\n  MinmodType minmod_type_;\n  double tvbm_constant_;\n};\n\ntemplate <size_t VolumeDim, typename TagList>\nSPECTRE_ALWAYS_INLINE bool operator==(\n    const Minmod<VolumeDim, TagList>& lhs,\n    const Minmod<VolumeDim, TagList>& rhs) noexcept {\n  return lhs.minmod_type() == rhs.minmod_type() and\n         lhs.tvbm_constant() == rhs.tvbm_constant();\n}\n\ntemplate <size_t VolumeDim, typename TagList>\nSPECTRE_ALWAYS_INLINE bool operator!=(\n    const Minmod<VolumeDim, TagList>& lhs,\n    const Minmod<VolumeDim, TagList>& rhs) noexcept {\n  return not(lhs == rhs);\n}\n\n}  // namespace SlopeLimiters\n\ntemplate <>\nstruct create_from_yaml<SlopeLimiters::MinmodType> {\n  static SlopeLimiters::MinmodType create(const Option& options);\n};\n", "meta": {"hexsha": "e5bbb268b3ac0bdc704ff524604aeef09d8c79ca", "size": 17268, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/DiscontinuousGalerkin/SlopeLimiters/Minmod.hpp", "max_stars_repo_name": "marissawalker/spectre", "max_stars_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Evolution/DiscontinuousGalerkin/SlopeLimiters/Minmod.hpp", "max_issues_repo_name": "marissawalker/spectre", "max_issues_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Evolution/DiscontinuousGalerkin/SlopeLimiters/Minmod.hpp", "max_forks_repo_name": "marissawalker/spectre", "max_forks_repo_head_hexsha": "afc8205e2f697de5e8e4f05e881499e05c9fd8a0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2200488998, "max_line_length": 80, "alphanum_fraction": 0.6964327079, "num_tokens": 4125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.4225046348141883, "lm_q1q2_score": 0.2488083810442777}}
{"text": "#ifdef compile_instructions\n(echo \"#include\\\"\"$0\"\\\"\" > $0x.cpp) && time clang++ -O3 -std=c++14 -Wfatal-errors -Wall -D_TEST_MULTI_INDEX_RANGE $0x.cpp -o $0x.x && $0x.x $@ && rm -rf $0x.cpp $0x.x; exit\n#endif\n\n#ifndef MULTI_INDEX_RANGE_HPP\n#define MULTI_INDEX_RANGE_HPP\n\n//#include<boost/iterator/iterator_facade.hpp>\n\n#include<iterator> // std::random_iterator_tag // std::reverse_iterator\n\nnamespace boost{\n\nnamespace multi{\n\ntemplate<class Self, typename ValueType, class AccessCategory, typename Reference = ValueType&,  typename DifferenceType = typename std::pointer_traits<ValueType*>::difference_type, typename Pointer = ValueType*>\nclass iterator_facade{\n\tusing self_type = Self;\n\tself_type& self(){return *this;}\n\tself_type const& self() const{return static_cast<Self const&>(*this);}\npublic:\n\tusing value_type = ValueType;\n\tusing reference = Reference;\n\tusing pointer = Pointer;\n\tusing difference_type = DifferenceType;\n\tusing iterator_category = AccessCategory;\n\tauto operator!=(self_type const& o) const\n//\t->decltype(not(o == self()))\n\t{\treturn not(o == self());}\n//\tSelf& operator++(){return ++self(); return *this;}\n\tself_type operator+(difference_type n) const{self_type r = self(); r += n; return r;}\n\tself_type operator-(difference_type n) const{self_type r = self(); r -= n; return r;}\n};\n\n//class iterator_core_access{};\n}\n\nnamespace multi{\n\ntemplate<class IndexType>\nclass range{\n\tIndexType first_;\n\tIndexType last_;\npublic:\n\tusing value_type = IndexType;\n\tusing difference_type = std::make_signed_t<value_type>;\n\tusing size_type = difference_type;\n\tusing const_reference = value_type const /*&*/;\n\tusing reference = const_reference;\n\tusing const_pointer = value_type;\n\tusing pointer = value_type;\n\trange() : first_{}, last_{first_}{}\n\ttemplate<class Range, typename = std::enable_if_t<std::is_same<std::decay_t<Range>, value_type>{}> >\n\tconstexpr range(Range&& o) : first_(o.first()), last_(o.last()){}\n\tconstexpr range(value_type fl) : first_{fl}, last_{fl + 1}{}\n\tconstexpr range(value_type f, value_type l) : first_{f}, last_{l}{}\n\tclass const_iterator \n\t\t: public boost::multi::iterator_facade<const_iterator, \n\t\t\tvalue_type, std::random_access_iterator_tag, \n\t\t\tconst_reference, difference_type\n\t\t>\n\t{\n\t\ttypename const_iterator::value_type curr_;\n\t\ttypename const_iterator::reference dereference() const{return curr_;}\n\t\tvoid increment(){++curr_;} void decrement(){--curr_;}\n\t\tvoid advance(typename const_iterator::difference_type n){curr_+=n;}\n\t\tbool equal(const_iterator const& y) const{return curr_ == y.curr_;}\n\t\tauto distance_to(const_iterator const& z) const{return z.curr_-curr_;}\n\t\tconstexpr const_iterator(value_type current) : curr_(current){}\n\t\tfriend class range;\n\t //   friend class boost::iterator_core_access;\n\tpublic:\n\t\tauto operator==(const_iterator const& y) const{return curr_ == y.curr_;}\n\t\tconst_iterator& operator++(){++curr_; return *this;}\n\t\tconst_iterator& operator--(){--curr_; return *this;}\n\t\ttypename const_iterator::reference operator*() const{return curr_;}\n\t};\n\tusing iterator = const_iterator;\n\tusing reverse_iterator = std::reverse_iterator<iterator>;\n\tusing const_reverse_iterator = std::reverse_iterator<const_iterator>;\n\tconstexpr const_reference first() const{return first_;}\n\tconstexpr const_reference last()  const{return last_;}\n\tconstexpr const_reference operator[](difference_type p) const{return first() + p;}\n\tconstexpr const_reference front() const{return first();}\n\tconstexpr const_reference back()  const{return last() - 1;}\n\tconstexpr const_iterator cbegin() const{return const_iterator{first_};}\n\tconstexpr const_iterator cend()   const{return const_iterator{last_};}\n\tconstexpr reverse_iterator rbegin() const{return reverse_iterator{end()};}\n\tconstexpr reverse_iterator rend() const{return reverse_iterator{begin()};}\n\tconstexpr const_iterator begin() const{return cbegin();}\n\tconstexpr const_iterator end() const{return cend();}\n\tconstexpr bool empty() const{return first_ == last_;}\n\tfriend constexpr bool empty(range const& s){return s.empty();}\n\tconstexpr size_type size() const noexcept{return last_ - first_;}\n\tfriend constexpr size_type size(range const& s){return s.size();}\n\tfriend std::ostream& operator<<(std::ostream& os, range const& s){\n\t\treturn s.empty()?os<<\"[)\":os <<\"[\"<< s.first() <<\", \"<< s.last() <<\")\";\n\t}\n\tfriend const_iterator begin(range const& self){return self.begin();}\n\tfriend const_iterator end(range const& self){return self.end();}\n\trange& operator=(range const&) = default;\n\tfriend constexpr bool operator==(range const& a, range const& b){\n\t\treturn(a.empty()&& b.empty())||(a.first_==b.first_ && a.last_==b.last_);\n\t}\n\tfriend constexpr \n\tbool operator!=(range const& r1, range const& r2){return not(r1 == r2);}\n\tsize_type count(value_type const& value) const{\n\t\tif(value >= last_ or value < first_) return 0;\n\t\treturn 1;\n\t}\n\trange::const_iterator find(value_type const& value) const{\n\t\tauto first = begin();\n\t\tif(value >= last_ or value < first_) return end();\n\t\treturn first += value - *first;\n\t}\n\tfriend range intersection(range const& r1, range const& r2){\n\t\tusing std::max; using std::min;\n\t\tauto first = max(r1.first(), r2.first()); \n\t\tauto last = min(r1.last(), r2.last());\n\t\tif(first < last) return {first, last};\n\t\treturn {};\n\t}\n\tbool contains(value_type const& v) const{return (v >= first() and v < last())?true:false;}\n};\n\n//using index_range = range<index>;\n/*\nclass strided_index_range : index_range{\t\n\tindex stride_;\npublic:\n\tstrided_index_range(index first, index last, index stride = 1) : index_range{first, last}, stride_{stride}{}\n//\texplicit operator index_range() const{return *this;}\n\tindex stride() const{return stride_;}\n\tusing index_range::front;\n\tindex back() const{return front() + size()*stride();}\n\tsize_type size() const{return (this->last_ - first_) / stride_;}\n\tfriend std::ostream& operator<<(std::ostream& os, strided_index_range const& self){\n\t\tif(empty() \n\t\tif(self.first_ == self.last_) return os << \"[)\" << '\\n';\n\t\treturn os << '[' << self.first_ << \", \" << self.last_ << ')';\n\t}\n};*/\n\ntemplate<class IndexType>\nclass extension_t : public range<IndexType>{\n\tusing range<IndexType>::range;\n\tpublic:\n\tconstexpr extension_t() noexcept : range<IndexType>(0, 0){}\n\tconstexpr extension_t(typename extension_t::value_type last) noexcept : range<IndexType>(0, last){}\n\tfriend constexpr typename extension_t::size_type size(extension_t const& s){return s.size();}\n\tfriend std::ostream& operator<<(std::ostream& os, extension_t const& self){\n\t\tif(self.empty()) return os << static_cast<range<IndexType> const&>(self);\n\t\tif(self.first() == 0) return os <<\"[\"<< self.last() <<\"]\";\n\t\treturn os << static_cast<range<IndexType> const&>(self);\n\t}\n\tfriend bool operator==(extension_t const& a, extension_t const& b){return static_cast<range<IndexType> const&>(a)==static_cast<range<IndexType> const&>(b);}\n\tfriend bool operator!=(extension_t const& a, extension_t const& b){return not(a==b);}\n};\n\n}}\n\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n\n#ifdef _TEST_MULTI_INDEX_RANGE\n\n//#include <boost/spirit/include/karma.hpp>\n\n#include<cassert>\n#include<iostream>\n\nnamespace multi = boost::multi;\n\nusing std::cout;\nusing std::cerr;\n\nint main(){\n\n\tcout << multi::range<int>{5, 5} <<'\\n';\n\tcout << multi::extension_t<int>{5} <<'\\n';\n\tmulti::extension_t<int> ee{5};\n\tassert( ee == 5 );\n\tassert( multi::extension_t<int>{5} == 5 );\n\tcout << multi::extension_t<int>{5, 7} <<'\\n';\n\t\n\tassert(( multi::extension_t<int>{5, 12}.count(10) == 1 ));\n\n\tassert( size(multi::range<int>{5, 5}) == 0 );\n\tassert( empty(multi::range<int>{5, 5}) );\n\t\n\tassert( size(multi::range<int>{}) == 0 );\n\tassert( empty(multi::range<int>{}) );\n\t\n\tfor(auto const& i : multi::range<int>{5, 12}) cout<< i <<' ';\n\tcout <<'\\n';\n\t\n\tcout << intersection(multi::range<int>{5, 12}, multi::range<int>{14, 16}) << '\\n';\n//\tfor(auto const& i : intersection(multi::range<int>{5, 12}, multi::range<int>{8, 16})) cout<< i <<' ';\n//\tcout <<'\\n';\n\t\n\tmulti::range<int> rr{5, 12};\n\tassert( rr.contains(6) );\n\tassert( not rr.contains(12) );\n\tfor(auto it = rr.begin(); it != rr.end(); ++it) cout<< *it <<' ';\n\tcout<<'\\n';\n\tfor(auto it = rr.rbegin(); it != rr.rend(); ++it) cout<< *it <<' ';\n\tcout<<'\\n';\n\n//\tcout<< *rr.rbegin() <<'\\n';\n//\tfor(auto it = rr.rbegin(); it != rr.rend(); ++it) cout<< *it <<' ';\n//\tcout <<'\\n';\n\t\n//\tmulti::extension<int> ei{5, 10}; \n#if 0\n\tstd::iterator_traits<multi::range<multi::index>::const_iterator>::value_type p = multi::index{4};\n\n\t{\n\t\tmulti::index_range ir{5, 10};\n\t\tcout << ir << \" = {\" << format(index_ % \", \", ir) << \"}\\n\";\n\t\tstd::vector<multi::index_range::value_type> v(5);\n\t\tcopy(begin(ir), end(ir), begin(v));\n\t\tassert(v[0] == 5);\n\t\tfor(auto& i : ir) cout << i << ' ';\n\t\tcout << '\\n';\n\t\tauto f = ir.find(6);\n\t\tcerr << \"*f \" << *f << '\\n';\n\t\tassert(*f == 6);\n\t\tusing std::find;\n\t\tauto f2 = find(ir.begin(), ir.end(), 12);\n\t\tassert(f2 == ir.end());\n\t\tauto f3 = find(ir.begin(), ir.end(), 2);\n\t\tassert(f3 == ir.end());\n\t}\n/*\t{\n\t\tmulti::strided_index_range ir{6, 12, 2};\n\t\tcout << ir << \" = {\" << format(index_ % \", \", ir) << \"}\\n\";\n\t\tstd::vector<multi::index_range::value_type> v(5);\n\t\tcopy(begin(ir), end(ir), begin(v));\n\t\tassert( v[0] == 6 );\n\t\tassert( v[1] == 8 );\n\t\tfor(auto& i : ir) cout << i <<' ';\n\t\tcout <<'\\n';\n\t}*/\n\t{\n\t\tmulti::index_range ir(5);\n\t\tcout << ir << \" = {\" << format(index_ % \", \", ir) << \"}\\n\";\n\t\tassert(*begin(ir) == 5);\n\t\tassert(ir.front() == 5);\n\t\tassert(ir.back() == 5);\n\t}\n\t{\n\t\tmulti::index_range ir; // partially formed\n\t\tir = multi::index_range{8, 8};\n\t\tassert(ir.empty());\n\t}\n\t{\n\t\tmulti::index_range ir = {};\n\t\tassert(ir.empty());\n\t}\n\t{\n\t\tmulti::index_extension ie(5);\n\t\tcout << ie << \" = {\" << format(index_ % \", \", ie) << \"}\";\n\t}\n#endif\n}\n\n#endif\n#endif\n\n", "meta": {"hexsha": "f1b3dab47d54f010240a7ede050a341abdd394f3", "size": 10470, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external_codes/boost_multi/multi/detail/index_range.hpp", "max_stars_repo_name": "prckent/qmcpack", "max_stars_repo_head_hexsha": "127caf219ee99c2449b803821fcc8b1304b66ee1", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "external_codes/boost_multi/multi/detail/index_range.hpp", "max_issues_repo_name": "prckent/qmcpack", "max_issues_repo_head_hexsha": "127caf219ee99c2449b803821fcc8b1304b66ee1", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external_codes/boost_multi/multi/detail/index_range.hpp", "max_forks_repo_name": "prckent/qmcpack", "max_forks_repo_head_hexsha": "127caf219ee99c2449b803821fcc8b1304b66ee1", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6618705036, "max_line_length": 212, "alphanum_fraction": 0.6181470869, "num_tokens": 2619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24875116618628149}}
{"text": "/*\n * author: Sergei Belousov aka BeS\n * email: belbes122@yandex.ru\n */\n#include \"ESOINN.h\"\n\n#include <fstream>\n#include <boost/foreach.hpp>\n#include <boost/utility.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/iteration_macros.hpp>\n\n#define E1(t) 1./t\n#define E2(t) 1./(100*t)\n\nusing namespace soinn;\nusing namespace boost::numeric;\n\nESOINN::ESOINN(int dim, int ageMax, int iterationThreshold, double c1, double c2):\n    dim(dim),\n    ageMax(ageMax),\n    iterationThreshold(iterationThreshold),\n    c1(c1),\n    c2(c2)\n{\n}\n\nESOINN::~ESOINN()\n{\n}\n\nGraph ESOINN::getGraph()\n{\n    return graph;\n}\n\nvoid ESOINN::process(const boost::numeric::ublas::vector<double> &inputSignal)\n{\n    if(inputSignal.size() != dim)\n    {\n        throw ESOINNException(std::string(\"Incorrect dimension of input signal in ESOINN::addSignal().\"));\n    }\n    else\n    {\n        addSignal(inputSignal);\n    }\n}\n\nvoid ESOINN::addSignal(const boost::numeric::ublas::vector<double> &inputSignal)\n{\n    if(boost::num_vertices(graph) < 2)\n    {\n        Vertex vertex = boost::add_vertex(graph);\n        graph[vertex].weight = ublas::vector<double>(inputSignal);\n        graph[vertex].classId = -1;\n        graph[vertex].density = 0.;\n        graph[vertex].numberOfSignals = 0;\n        graph[vertex].S = 0;\n        return;\n    }\n    Vertex firstWinner, secondWinner;\n    boost::tie(firstWinner, secondWinner) = findWinners(inputSignal);\n    if(!isWithinThreshold(inputSignal, firstWinner, secondWinner))\n    {\n        Vertex vertex = boost::add_vertex(graph);\n        graph[vertex].weight = ublas::vector<double>(inputSignal);\n        graph[vertex].classId = -1;\n        graph[vertex].density = 0.;\n        graph[vertex].numberOfSignals = 0;\n        graph[vertex].S = 0;\n        return;\n    }\n    incrementEdgesAge(firstWinner);\n    if(needAddEdge(firstWinner, secondWinner))\n    {\n        Edge e = boost::add_edge(firstWinner, secondWinner, graph).first;\n        graph[e].age = 0;\n    }\n    else\n    {\n        boost::remove_edge(firstWinner, secondWinner, graph);\n    }\n    updateDensity(firstWinner);\n    updateWeights(firstWinner, inputSignal);\n    deleteOldEdges();\n    if(iterationCount % iterationThreshold == 0)\n    {\n        updateClassLabels();\n    }\n    iterationCount++;\n}\n\ndouble ESOINN::distance(const boost::numeric::ublas::vector<double> &x, const boost::numeric::ublas::vector<double> &y)\n{\n    return ublas::norm_2( x - y );\n}\n\nstd::pair<Vertex,Vertex> ESOINN::findWinners(const boost::numeric::ublas::vector<double> &inputSignal)\n{\n    Vertex firstWinner = NULL;\n    Vertex secondWinner = NULL;\n    double firstWinnerDistance = std::numeric_limits<double>::max();\n    double secondWinnerDistance = std::numeric_limits<double>::max();\n    VertexIterator current, end;\n    boost::tie(current, end) = boost::vertices(graph);\n    for(; current != end; current++)\n    {\n        double dist = distance(inputSignal, graph[*current].weight);\n        if(dist < firstWinnerDistance)\n        {\n            secondWinner = firstWinner;\n            secondWinnerDistance = firstWinnerDistance;\n            firstWinner = *current;\n            firstWinnerDistance = dist;\n        }\n        else if(dist < secondWinnerDistance)\n        {\n            secondWinner = *current;\n            secondWinnerDistance = dist;\n        }\n    }\n    return std::pair<Vertex,Vertex>(firstWinner, secondWinner);\n}\n\nbool ESOINN::isWithinThreshold(const boost::numeric::ublas::vector<double>& inputSignal, Vertex& firstWinner, Vertex& secondWinner)\n{\n    if(distance(inputSignal, graph[firstWinner].weight) > getSimilarityThreshold(firstWinner))\n    {\n        return false;\n    }\n    if(distance(inputSignal, graph[secondWinner].weight) > getSimilarityThreshold(secondWinner))\n    {\n        return false;\n    }\n    return true;\n}\n\ndouble ESOINN::getSimilarityThreshold(const Vertex& vertex)\n{\n    double dist = 0.0;\n    if(!boost::out_degree(vertex, graph))\n    {\n        dist = std::numeric_limits<double>::max();\n        VertexIterator current, end;\n        boost::tie(current, end) = boost::vertices(graph);\n        for(; current != end; current++)\n        {\n            if(*current != vertex)\n            {\n                double distCurrent = distance(graph[vertex].weight, graph[*current].weight);\n                if(distCurrent < dist)\n                {\n                    dist = distCurrent;\n                }\n            }\n        }\n    }\n    else\n    {\n        dist = std::numeric_limits<double>::min();\n        AdjacencyIterator current, end;\n        boost::tie(current, end) = boost::adjacent_vertices(vertex, graph);\n        for(; current != end; current++)\n        {\n            double distCurrent = distance(graph[vertex].weight, graph[*current].weight);\n            if(distCurrent > dist)\n            {\n                dist = distCurrent;\n            }\n        }\n    }\n    return dist;\n}\n\nvoid ESOINN::incrementEdgesAge(Vertex& vertex)\n{\n    OutEdgeIterator current, end;\n    boost::tie(current, end) = boost::out_edges(vertex, graph);\n    for(; current != end; current++)\n    {\n        graph[*current].age++;\n    }\n}\n\nbool ESOINN::needAddEdge(Vertex& firstWinner, Vertex &secondWinner)\n{\n    if(graph[firstWinner].classId == -1 || graph[secondWinner].classId == -1)\n    {\n        return true;\n    }\n    else if(graph[firstWinner].classId == graph[secondWinner].classId)\n    {\n        return true;\n    }\n    else if(graph[firstWinner].classId != graph[secondWinner].classId && needMergeClasses(firstWinner, secondWinner))\n    {\n        return true;\n    }\n    return false;\n}\n\nbool ESOINN::needMergeClasses(Vertex &a, Vertex &b)\n{\n    int A = graph[a].classId;\n    double meanA = meanDensity(A);\n    double maxA = maxDensity(A);\n    double thresholdA = densityThershold(meanA, maxA);\n    int B = graph[b].classId;\n    double meanB = meanDensity(B);\n    double maxB = maxDensity(B);\n    double thresholdB = densityThershold(meanB, maxB);\n    double minAB = std::min(graph[a].density, graph[b].density);\n    if(minAB > thresholdA * maxA && minAB > thresholdB * maxB)\n    {\n        return true;\n    }\n    return false;\n}\n\nvoid ESOINN::mergeClasses(int A, int B)\n{\n    int classId = std::min(A, B);\n    VertexIterator current, end;\n    boost::tie(current, end) = boost::vertices(graph);\n    for(; current != end; current++)\n    {\n        if(graph[*current].classId == A || graph[*current].classId == B)\n        {\n            graph[*current].classId = classId;\n        }\n    }\n}\n\ndouble ESOINN::meanDensity(int classId)\n{\n    if(classId == -1) return 0.0;\n    int n = 0;\n    double density = 0.0;\n    VertexIterator current, end;\n    boost::tie(current, end) = boost::vertices(graph);\n    for(; current != end; current++)\n    {\n        if(graph[*current].classId == classId)\n        {\n            n++;\n            density += graph[*current].density;\n        }\n    }\n    density *= 1./double(n);\n    return density;\n}\n\ndouble ESOINN::maxDensity(int classId)\n{\n    double density = std::numeric_limits<double>::min();\n    VertexIterator current, end;\n    boost::tie(current, end) = boost::vertices(graph);\n    for(; current != end; current++)\n    {\n        if(graph[*current].density > density && graph[*current].classId == classId)\n        {\n            density = graph[*current].density;\n        }\n    }\n    return density;\n}\n\ndouble ESOINN::densityThershold(double mean, double max)\n{\n    double threshold;\n    if(2.0 * mean >= max)\n    {\n        threshold = 0.0;\n    }\n    else if(3.0 * mean >= max && max > 2.0 * mean)\n    {\n        threshold = 0.5;\n    }\n    else\n    {\n        threshold = 1.0;\n    }\n    return threshold;\n}\n\nvoid ESOINN::updateDensity(Vertex& vertex)\n{\n    double mDistance = meanDistance(vertex);\n    graph[vertex].numberOfSignals++;\n    graph[vertex].S += 1./((1 + mDistance)*(1 + mDistance));\n    graph[vertex].density = graph[vertex].S/double(graph[vertex].numberOfSignals);\n}\n\nvoid ESOINN::updateWeights(Vertex& firstWinner, const boost::numeric::ublas::vector<double> &inputSignal)\n{\n    graph[firstWinner].weight += E1(graph[firstWinner].numberOfSignals) * (inputSignal - graph[firstWinner].weight);\n    AdjacencyIterator current, end;\n    boost::tie(current, end) = boost::adjacent_vertices(firstWinner, graph);\n    for(; current != end; current++)\n    {\n        graph[*current].weight += E2(graph[firstWinner].numberOfSignals) * (inputSignal - graph[*current].weight);\n    }\n}\n\ndouble ESOINN::meanDistance(Vertex& vertex)\n{\n    double mDistance = 0.0;\n    int m = 0;\n    VertexIterator current, end;\n    boost::tie(current, end) = boost::vertices(graph);\n    for(; current != end; current++)\n    {\n        if(graph[vertex].classId == graph[*current].classId)\n        {\n            mDistance += distance(graph[vertex].weight, graph[*current].weight);\n            m++;\n        }\n    }\n    mDistance *= 1./double(m);\n    return mDistance;\n}\n\nvoid ESOINN::deleteOldEdges()\n{\n    EdgeIterator current, end;\n    boost::tie(current, end) = boost::edges(graph);\n    EdgeIterator next = current;\n    for(;current != end; current = next)\n    {\n        next ++;\n        if(graph[*current].age > ageMax)\n        {\n            Vertex vertexS = boost::source(*current, graph);\n            Vertex vertexT = boost::target(*current, graph);\n            boost::remove_edge(*current, graph);\n        }\n    }\n}\n\nvoid ESOINN::updateClassLabels()\n{\n    markClasses();\n    partitionClasses();\n    deleteNoiseVertex();\n}\n\nvoid ESOINN::markClasses()\n{\n    std::list<VertexIterator> vertexList;\n    VertexIterator begin, end;\n    boost::tie(begin, end) = boost::vertices(graph);\n    for(VertexIterator current = begin; current != end; current++)\n    {\n        graph[*current].classId = -1;\n        vertexList.push_back(current);\n    }\n    vertexList.sort([&](VertexIterator &a, VertexIterator &b) -> bool\n                    {\n                        if(graph[*a].density > graph[*b].density) return true;\n                        return false;\n                    });\n    int classCount = 0;\n    for(std::list<VertexIterator>::iterator current = vertexList.begin(); current != vertexList.end(); current++)\n    {\n        if(graph[**current].classId == -1)\n        {\n            graph[**current].classId = classCount;\n            markAdjacentVertices(**current, classCount++);\n        }\n    }\n}\n\nvoid ESOINN::partitionClasses()\n{\n    EdgeIterator current, end;\n    boost::tie(current, end) = boost::edges(graph);\n    EdgeIterator next = current;\n    for(;current != end; current = next) {\n        next ++;\n        Vertex vertexS = boost::source(*current, graph);\n        Vertex vertexT = boost::target(*current, graph);\n        if(graph[vertexS].classId != graph[vertexT].classId)\n        {\n            if(needMergeClasses(vertexS, vertexT))\n            {\n                mergeClasses(graph[vertexS].classId, graph[vertexT].classId);\n            }\n            else\n            {\n                boost::remove_edge(*current, graph);\n            }\n        }\n    }\n}\n\nvoid ESOINN::markAdjacentVertices(Vertex &vertex, int cID)\n{\n    AdjacencyIterator current, end;\n    boost::tie(current, end) = boost::adjacent_vertices(vertex, graph);\n    for(; current != end; current++){\n        if(graph[*current].classId == -1 && graph[*current].density < graph[vertex].density)\n        {\n            graph[*current].classId = cID;\n            Vertex v = *current;\n            markAdjacentVertices(v, cID);\n        }\n    }\n}\n\nvoid ESOINN::deleteNoiseVertex()\n{\n    VertexIterator begin, end;\n    boost::tie(begin, end) = boost::vertices(graph);\n    VertexIterator next = begin;\n    for(VertexIterator current = begin; current != end; current = next)\n    {\n        next++;\n        double mean = meanDensity(graph[*current].classId);\n        if((boost::out_degree(*current, graph) == 2 && graph[*current].density < c1* mean) ||\n                (boost::out_degree(*current, graph) == 1 && graph[*current].density < c2* mean) ||\n                (boost::out_degree(*current, graph) == 0)) {\n            boost::clear_vertex(*current, graph);\n            boost::remove_vertex(*current, graph);\n        }\n    }\n}\n\nvoid ESOINN::classify()\n{\n    deleteNoiseVertex();\n    size_t index = 0;\n    BGL_FORALL_VERTICES(v, graph, Graph)\n    {\n        boost::put(boost::vertex_index, graph, v, index++);\n    }\n    ComponentMap component;\n    boost::associative_property_map<ComponentMap> componentMap(component);\n    numberOfClasses = connected_components(graph, componentMap);\n    BGL_FORALL_VERTICES(v, graph, Graph)\n    {\n        graph[v].classId = boost::get(componentMap, v);\n    }\n}\n\nvoid ESOINN::save(std::string filename)\n{\n    std::ofstream ofs(filename.c_str());\n    boost::archive::xml_oarchive oa(ofs);\n    oa << BOOST_SERIALIZATION_NVP(*this);\n}\n\nvoid ESOINN::load(std::string filename)\n{\n    clear();\n    std::ifstream ifs(filename.c_str());\n    boost::archive::xml_iarchive ia(ifs);\n    ia >> BOOST_SERIALIZATION_NVP(*const_cast<ESOINN*>(this));\n}\n\nvoid ESOINN::clear()\n{\n    graph.clear();\n    numberOfClasses = 0;\n}\n\nvoid ESOINN::setParams(int dim, int ageMax, int iterationThreshold, double c1, double c2)\n{\n    this->dim = dim;\n    this->ageMax = ageMax;\n    this->iterationThreshold = iterationThreshold;\n    this->c1 = c1;\n    this->c2 = c2;\n}\n\nint ESOINN::getNumberOfClasses()\n{\n    return numberOfClasses;\n}\n\nint ESOINN::getNumberOfVertices()\n{\n    return boost::num_vertices(graph);\n}\n\nboost::numeric::ublas::vector<double> ESOINN::getCenterOfCluster(int classId)\n{\n    double density = -1;\n    Vertex center;\n    BGL_FORALL_VERTICES(v, graph, Graph) {\n        if(graph[v].classId == classId && graph[v].density > density) {\n            center = v;\n            density = graph[center].density;\n        }\n    }\n    return graph[center].weight;\n}\n\nVertexProperties ESOINN::getBestMatch(boost::numeric::ublas::vector<double>& inputSignal)\n{\n    Vertex firstWinner = NULL;\n    double firstWinnerDistance = std::numeric_limits<double>::max();\n    VertexIterator current, end;\n    boost::tie(current, end) = boost::vertices(graph);\n    for(; current != end; current++)\n    {\n        double dist = distance(inputSignal, graph[*current].weight);\n        if(dist < firstWinnerDistance)\n        {\n            firstWinner = *current;\n            firstWinnerDistance = dist;\n        }\n    }\n    return graph[firstWinner];\n}\n", "meta": {"hexsha": "5be81dd1506caee5051ece7ea414ee1df732c0ae", "size": 14343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ESOINN.cpp", "max_stars_repo_name": "Zucker-jex/Thinking-System", "max_stars_repo_head_hexsha": "694643e993d54a75801994a2f1f51ecda814dcc4", "max_stars_repo_licenses": ["BSL-1.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ESOINN.cpp", "max_issues_repo_name": "Zucker-jex/Thinking-System", "max_issues_repo_head_hexsha": "694643e993d54a75801994a2f1f51ecda814dcc4", "max_issues_repo_licenses": ["BSL-1.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ESOINN.cpp", "max_forks_repo_name": "Zucker-jex/Thinking-System", "max_forks_repo_head_hexsha": "694643e993d54a75801994a2f1f51ecda814dcc4", "max_forks_repo_licenses": ["BSL-1.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7965116279, "max_line_length": 131, "alphanum_fraction": 0.6090775988, "num_tokens": 3571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2485793885715133}}
{"text": "#include <boost/detail/algorithm.hpp>\n#include <boost/graph/adjacency_iterator.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/adjacency_list_io.hpp>\n#include <boost/graph/adjacency_matrix.hpp>\n#include <boost/graph/adj_list_serialize.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/bandwidth.hpp>\n#include <boost/graph/bc_clustering.hpp>\n#include <boost/graph/bellman_ford_shortest_paths.hpp>\n#include <boost/graph/betweenness_centrality.hpp>\n#include <boost/graph/biconnected_components.hpp>\n#include <boost/graph/bipartite.hpp>\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include <boost/graph/breadth_first_search.hpp>\n#include <boost/graph/bron_kerbosch_all_cliques.hpp>\n#include <boost/graph/buffer_concepts.hpp>\n#include <boost/graph/chrobak_payne_drawing.hpp>\n#include <boost/graph/circle_layout.hpp>\n#include <boost/graph/closeness_centrality.hpp>\n#include <boost/graph/clustering_coefficient.hpp>\n#include <boost/graph/compressed_sparse_row_graph.hpp>\n#include <boost/graph/connected_components.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/graph/core_numbers.hpp>\n#include <boost/graph/create_condensation_graph.hpp>\n#include <boost/graph/cuthill_mckee_ordering.hpp>\n#include <boost/graph/cycle_canceling.hpp>\n#include <boost/graph/dag_shortest_paths.hpp>\n#include <boost/graph/degree_centrality.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp>\n#include <boost/graph/dimacs.hpp>\n#include <boost/graph/directed_graph.hpp>\n#include <boost/graph/dll_import_export.hpp>\n#include <boost/graph/dominator_tree.hpp>\n#include <boost/graph/eccentricity.hpp>\n#include <boost/graph/edge_coloring.hpp>\n#include <boost/graph/edge_connectivity.hpp>\n#include <boost/graph/edge_list.hpp>\n#include <boost/graph/edmonds_karp_max_flow.hpp>\n#include <boost/graph/erdos_renyi_generator.hpp>\n#include <boost/graph/exception.hpp>\n#include <boost/graph/exterior_property.hpp>\n#include <boost/graph/filtered_graph.hpp>\n#include <boost/graph/find_flow_cost.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n#include <boost/graph/fruchterman_reingold.hpp>\n#include <boost/graph/geodesic_distance.hpp>\n#include <boost/graph/graph_archetypes.hpp>\n#include <boost/graph/graph_as_tree.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/graphml.hpp>\n#include <boost/graph/graph_mutability_traits.hpp>\n#include <boost/graph/graph_selectors.hpp>\n#include <boost/graph/graph_stats.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/graphviz.hpp>\n#include <boost/graph/grid_graph.hpp>\n#include <boost/graph/gursoy_atun_layout.hpp>\n#include <boost/graph/hawick_circuits.hpp>\n#include <boost/graph/howard_cycle_ratio.hpp>\n#include <boost/graph/incremental_components.hpp>\n#include <boost/graph/is_kuratowski_subgraph.hpp>\n#include <boost/graph/isomorphism.hpp>\n#include <boost/graph/is_straight_line_drawing.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/iteration_macros_undef.hpp>\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/kamada_kawai_spring_layout.hpp>\n#include <boost/graph/king_ordering.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/graph/labeled_graph.hpp>\n#include <boost/graph/lookup_edge.hpp>\n#include <boost/graph/loop_erased_random_walk.hpp>\n#include <boost/graph/make_biconnected_planar.hpp>\n#include <boost/graph/make_connected.hpp>\n#include <boost/graph/make_maximal_planar.hpp>\n#include <boost/graph/matrix_as_graph.hpp>\n#include <boost/graph/max_cardinality_matching.hpp>\n#include <boost/graph/maximum_adjacency_search.hpp>\n#include <boost/graph/maximum_weighted_matching.hpp>\n#include <boost/graph/mcgregor_common_subgraphs.hpp>\n#include <boost/graph/mesh_graph_generator.hpp>\n#include <boost/graph/metis.hpp>\n#include <boost/graph/metric_tsp_approx.hpp>\n#include <boost/graph/minimum_degree_ordering.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/named_graph.hpp>\n#include <boost/graph/neighbor_bfs.hpp>\n#include <boost/graph/numeric_values.hpp>\n#include <boost/graph/one_bit_color_map.hpp>\n#include <boost/graph/overloading.hpp>\n#include <boost/graph/page_rank.hpp>\n#include <boost/graph/planar_canonical_ordering.hpp>\n#include <boost/graph/planar_face_traversal.hpp>\n#include <boost/graph/plod_generator.hpp>\n#include <boost/graph/point_traits.hpp>\n#include <boost/graph/prim_minimum_spanning_tree.hpp>\n#include <boost/graph/profile.hpp>\n#include <boost/graph/properties.hpp>\n#include <boost/graph/property_iter_range.hpp>\n#include <boost/graph/push_relabel_max_flow.hpp>\n#include <boost/graph/random.hpp>\n#include <boost/graph/random_layout.hpp>\n#include <boost/graph/random_spanning_tree.hpp>\n#include <boost/graph/r_c_shortest_paths.hpp>\n#include <boost/graph/read_dimacs.hpp>\n#include <boost/graph/relax.hpp>\n#include <boost/graph/reverse_graph.hpp>\n#include <boost/graph/rmat_graph_generator.hpp>\n#include <boost/graph/sequential_vertex_coloring.hpp>\n#include <boost/graph/simple_point.hpp>\n#include <boost/graph/sloan_ordering.hpp>\n#include <boost/graph/smallest_last_ordering.hpp>\n#include <boost/graph/small_world_generator.hpp>\n#include <boost/graph/ssca_graph_generator.hpp>\n#include <boost/graph/st_connected.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/graph/strong_components.hpp>\n#include <boost/graph/subgraph.hpp>\n#include <boost/graph/successive_shortest_path_nonnegative_weights.hpp>\n#include <boost/graph/tiernan_all_cycles.hpp>\n#include <boost/graph/topological_sort.hpp>\n#include <boost/graph/topology.hpp>\n#include <boost/graph/transitive_closure.hpp>\n#include <boost/graph/transitive_reduction.hpp>\n#include <boost/graph/transpose_graph.hpp>\n#include <boost/graph/tree_traits.hpp>\n#include <boost/graph/two_bit_color_map.hpp>\n#include <boost/graph/two_graphs_common_spanning_trees.hpp>\n#include <boost/graph/undirected_dfs.hpp>\n#include <boost/graph/undirected_graph.hpp>\n#include <boost/graph/use_mpi.hpp>\n#include <boost/graph/vector_as_graph.hpp>\n#include <boost/graph/vertex_and_edge_range.hpp>\n#include <boost/graph/vf2_sub_graph_iso.hpp>\n#include <boost/graph/visitors.hpp>\n#include <boost/graph/wavefront.hpp>\n#include <boost/graph/write_dimacs.hpp>\n#include <boost/pending/bucket_sorter.hpp>\n#include <boost/pending/container_traits.hpp>\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/pending/fenced_priority_queue.hpp>\n#include <boost/pending/fibonacci_heap.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/pending/is_heap.hpp>\n#include <boost/pending/mutable_heap.hpp>\n#include <boost/pending/mutable_queue.hpp>\n#include <boost/pending/property.hpp>\n#include <boost/pending/property_serialize.hpp>\n#include <boost/pending/queue.hpp>\n#include <boost/pending/stringtok.hpp>\n\n#include <sstream>\n\nusing namespace std;\nusing namespace boost;\n\nint\nmain ()\n{\n  // This code uses the graphviz parser which is one of the few compiled parts\n  // of Boost.Graph.\n  //\n\n  // Vertex properties.\n  //\n  typedef property<vertex_name_t, string, property<vertex_color_t, float>>\n      vertex_p;\n\n  // Edge properties.\n  //\n  typedef property<edge_weight_t, double> edge_p;\n\n  // Graph properties.\n  //\n  typedef property<graph_name_t, string> graph_p;\n\n  // adjacency_list-based type.\n  //\n  typedef adjacency_list<vecS, vecS, directedS, vertex_p, edge_p, graph_p>\n      graph_t;\n\n  // Construct an empty graph and prepare the dynamic_property_maps.\n  //\n  graph_t graph (0);\n  dynamic_properties dp;\n\n  property_map<graph_t, vertex_name_t>::type name (get (vertex_name, graph));\n  dp.property (\"node_id\", name);\n\n  property_map<graph_t, vertex_color_t>::type mass (get (vertex_color, graph));\n  dp.property (\"mass\", mass);\n\n  property_map<graph_t, edge_weight_t>::type weight (get (edge_weight, graph));\n  dp.property (\"weight\", weight);\n\n  // Use ref_property_map to turn a graph property into a property map.\n  //\n  boost::ref_property_map<graph_t*, string> gname (\n      get_property (graph, graph_name));\n  dp.property (\"name\", gname);\n\n  // Sample graph as an istream.\n  //\n  istringstream gvgraph (\n      \"digraph { graph [name=\\\"graphname\\\"]  a  c e [mass = 6.66] }\");\n\n  return read_graphviz (gvgraph, graph, dp, \"node_id\") ? 0 : 1;\n}\n", "meta": {"hexsha": "56dca089ad79ae10bbe56ab07e78c3cf39b8a998", "size": 8426, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "downstream/libs/graph/test/basics/driver.cpp", "max_stars_repo_name": "build2-packaging/boost", "max_stars_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-02-23T11:24:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T20:10:46.000Z", "max_issues_repo_path": "libboost-graph/tests/basics/driver.cpp", "max_issues_repo_name": "build2-packaging/boost", "max_issues_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libboost-graph/tests/basics/driver.cpp", "max_forks_repo_name": "build2-packaging/boost", "max_forks_repo_head_hexsha": "203d505dd3ba04ea50785bc8b247a295db5fc718", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1906976744, "max_line_length": 79, "alphanum_fraction": 0.7980061714, "num_tokens": 1982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.24848030850481534}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2008 Roland Lichters\n Copyright (C) 2009, 2014 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <boost/make_shared.hpp>\n\n#include <ql/experimental/credit/basket.hpp>\n#include <ql/experimental/credit/loss.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n#include <ql/experimental/credit/defaultlossmodel.hpp>\n\nusing namespace std;\n\nnamespace QuantLib {\n\n    Basket::Basket(const Date& refDate,\n        const vector<string>& names,\n        const vector<Real>& notionals,\n        const boost::shared_ptr<Pool> pool,\n        Real attachment,\n        Real detachment,\n        const boost::shared_ptr<Claim>& claim\n        )\n    : notionals_(notionals),\n      pool_(pool),\n      claim_(claim),\n      attachmentRatio_(attachment),\n      detachmentRatio_(detachment),\n      basketNotional_(0.0),\n      attachmentAmount_(0.0),\n      detachmentAmount_(0.0),\n      trancheNotional_(0.0),\n      refDate_(refDate)\n    {\n        QL_REQUIRE(!notionals_.empty(), \"notionals empty\");\n        QL_REQUIRE (attachmentRatio_ >= 0 &&\n                    attachmentRatio_ <= detachmentRatio_ &&\n                    detachmentRatio_ <= 1,\n                    \"invalid attachment/detachment ratio\");\n        QL_REQUIRE(pool_, \"Empty pool pointer.\");\n        QL_REQUIRE(notionals_.size() == pool_->size(), \n                   \"unmatched data entry sizes in basket\");\n\n        // registrations relevant to the loss status, not to the expected \n        // loss values; those are through models.\n        registerWith(Settings::instance().evaluationDate());\n        registerWith(claim_);\n\n        computeBasket();\n\n        // At this point Issuers in the pool might or might not have\n        //   probability term structures for the defultKeys(eventType+\n        //   currency+seniority) entering in this basket. This is not\n        //   neccessarily a problem.\n        for (Size i = 0; i < notionals_.size(); i++) {\n            basketNotional_ += notionals_[i];\n            attachmentAmount_ += notionals_[i] * attachmentRatio_;\n            detachmentAmount_ += notionals_[i] * detachmentRatio_;\n        }\n        trancheNotional_ = detachmentAmount_ - attachmentAmount_;\n    }\n\n    /*\\todo Alternatively send a relinkable handle so it can be changed from \n    the outside. In that case reconsider the observability chain.\n    */\n    void Basket::setLossModel(\n        const boost::shared_ptr<DefaultLossModel>& lossModel) {\n\n        if (lossModel_)\n            unregisterWith(lossModel_);\n        lossModel_ = lossModel;\n        if (lossModel_) {\n            //recovery quotes, defaults(once Issuer is observable)etc might \n            //  trigger us:\n            registerWith(lossModel_);\n        }\n        LazyObject::update(); //<- just set calc=false\n    }\n\n    void Basket::performCalculations() const {\n        // Calculations for status\n        computeBasket();// or we might be called from an statistic member \n                        // without being intialized yet (first called)\n        QL_REQUIRE(lossModel_, \"Basket has no default loss model assigned.\");\n\n        /* The model must notify us if the another basket calls it for \n        reasignment. The basket works as an argument to the deafult loss models \n        so, even if the models dont cache anything, they will be using the wrong\n        defautl TS. \\todo: This has a possible optimization: the basket \n        incorporates trancheability and many models do their compuations \n        independently of that (some do but do it inefficiently when asked for \n        two tranches on the same basket; e,g, recursive model) so it might be \n        more efficient sending the pool only; however the modtionals and other \n        basket info are still used.*/\n        lossModel_->setBasket(const_cast<Basket*>(this));\n    }\n\n    Disposable<vector<Real> > Basket::probabilities(const Date& d) const {\n        vector<Real> prob(size());\n        vector<DefaultProbKey> defKeys = defaultKeys();\n        for (Size j = 0; j < size(); j++)\n            prob[j] = pool_->get(pool_->names()[j]).defaultProbability(\n                defKeys[j])->defaultProbability(d);\n        return prob;\n    }\n\n    Real Basket::cumulatedLoss(const Date& endDate) const {\n        QL_REQUIRE(endDate >= refDate_, \n            \"Target date lies before basket inception\");\n        Real loss = 0.0;\n        for (Size i = 0; i < size(); i++) {\n            boost::shared_ptr<DefaultEvent> credEvent =\n                pool_->get(pool_->names()[i]).defaultedBetween(refDate_,\n                    endDate, pool_->defaultKeys()[i]);\n            if (credEvent) {\n                /* \\todo If the event has not settled one would need to \n                introduce some model recovery rate (independently of a loss \n                model) This remains to be done.\n                */  \n                if(credEvent->hasSettled())\n                    loss += claim_->amount(credEvent->date(),\n                            // notionals_[i],\n                            exposure(pool_->names()[i], credEvent->date()),\n                            credEvent->settlement().recoveryRate(\n                                pool_->defaultKeys()[i].seniority()));\n            }\n        }\n        return loss;\n    }\n\n    Real Basket::settledLoss(const Date& endDate) const {\n        QL_REQUIRE(endDate >= refDate_, \n            \"Target date lies before basket inception\");\n        \n        Real loss = 0.0;\n        for (Size i = 0; i < size(); i++) {\n            boost::shared_ptr<DefaultEvent> credEvent =\n                pool_->get(pool_->names()[i]).defaultedBetween(refDate_,\n                    endDate, pool_->defaultKeys()[i]);\n            if (credEvent) {\n                if(credEvent->hasSettled()) {\n                    loss += claim_->amount(credEvent->date(),\n                            //notionals_[i],\n                            exposure(pool_->names()[i], credEvent->date()),\n                            //NOtice I am requesting an exposure in the past...\n                            /* also the seniority does not belong to the \n                            counterparty anymore but to the position.....*/\n                            credEvent->settlement().recoveryRate(\n                                pool_->defaultKeys()[i].seniority()));\n                }\n            }\n        }\n        return loss;\n    }\n\n    Real Basket::remainingNotional() const {\n        return evalDateRemainingNot_;\n    }\n\n    Disposable<std::vector<Size> > \n        Basket::liveList(const Date& endDate) const {\n        std::vector<Size> calcBufferLiveList;\n        for (Size i = 0; i < size(); i++)\n            if (!pool_->get(pool_->names()[i]).defaultedBetween(\n                    refDate_,\n                    endDate,\n                    pool_->defaultKeys()[i]))\n                calcBufferLiveList.push_back(i);\n\n        return calcBufferLiveList;\n    }\n\n    Real Basket::remainingNotional(const Date& endDate) const {\n        Real notional = 0;\n        vector<DefaultProbKey> defKeys = defaultKeys();\n        for (Size i = 0; i < size(); i++) {\n            if (!pool_->get(pool_->names()[i]).defaultedBetween(refDate_,\n                                                        endDate,\n                                                        defKeys[i]))\n                notional += notionals_[i];\n        }\n        return notional;\n    }\n\n    Disposable<vector<Real> > \n        Basket::remainingNotionals(const Date& endDate) const \n    {\n        QL_REQUIRE(endDate >= refDate_, \n            \"Target date lies before basket inception\");\n\n        std::vector<Real> calcBufferNotionals;\n        const std::vector<Size>& alive = liveList(endDate);\n        for(Size i=0; i<alive.size(); i++)\n            calcBufferNotionals.push_back(\n                exposure(pool_->names()[i], endDate)\n                );// some better way to trim it? \n        return calcBufferNotionals;\n    }\n\n    Disposable<std::vector<Probability> > \n        Basket::remainingProbabilities(const Date& d) const \n    {\n        QL_REQUIRE(d >= refDate_, \"Target date lies before basket inception\");\n        vector<Real> prob;\n        const std::vector<Size>& alive = liveList();\n\n        for(Size i=0; i<alive.size(); i++)\n            prob.push_back(pool_->get(pool_->names()[i]).defaultProbability(\n                pool_->defaultKeys()[i])->defaultProbability(d, true));\n        return prob;\n    }\n\n    /* It is supossed to return the addition of ALL notionals from the \n    requested ctpty......*/\n    Real Basket::exposure(const std::string& name, const Date& d) const {\n        //'this->names_' contains duplicates, contrary to 'pool->names'\n        std::vector<std::string>::const_iterator match =  \n            std::find(pool_->names().begin(), pool_->names().end(), name);\n        QL_REQUIRE(match != pool_->names().end(), \"Name not in basket.\");\n        Real totalNotional = 0.;\n        do{\n            totalNotional += \n             // NOT IMPLEMENTED YET:\n    //positions_[std::distance(names_.begin(), match)]->expectedExposure(d);\n                notionals_[std::distance(pool_->names().begin(), match)];\n            match++;\n            match = std::find(match, pool_->names().end(), name);\n        }while(match != pool_->names().end());\n\n        return totalNotional;\n        //Size position = std::distance(poolNames.begin(), \n        //    std::find(poolNames.begin(), poolNames.end(), name));\n        //QL_REQUIRE(position < pool_->size(), \"Name not in pool list\");\n\n        //return positions_[position]->expectedExposure(d);\n    }\n\n    Disposable<std::vector<std::string> >\n        Basket::remainingNames(const Date& endDate) const \n    {\n        // maybe return zero directly instead?:\n        QL_REQUIRE(endDate >= refDate_, \n            \"Target date lies before basket inception\");\n\n        const std::vector<Size>& alive = liveList(endDate);\n        std::vector<std::string> calcBufferNames;\n        for(Size i=0; i<alive.size(); i++)\n            calcBufferNames.push_back(pool_->names()[alive[i]]);\n        return calcBufferNames;\n    }\n\n    Disposable<vector<DefaultProbKey> >\n        Basket::remainingDefaultKeys(const Date& endDate) const \n    {\n        QL_REQUIRE(endDate >= refDate_,\n            \"Target date lies before basket inception\");\n\n        const std::vector<Size>& alive = liveList(endDate);\n        vector<DefaultProbKey> defKeys;\n        for(Size i=0; i<alive.size(); i++)\n            defKeys.push_back(pool_->defaultKeys()[alive[i]]);\n        return defKeys;\n    }\n\n    Size Basket::remainingSize() const {\n        return evalDateLiveList_.size();\n    }\n\n    /* computed on the inception values, notice the positions might have \n    amortized or changed in value and the total outstanding notional might \n    differ from the inception one.*/\n    Real Basket::remainingDetachmentAmount(const Date& endDate) const {\n        return detachmentAmount_;\n    }\n\n    Real Basket::remainingAttachmentAmount(const Date& endDate) const {\n        // maybe return zero directly instead?:\n        QL_REQUIRE(endDate >= refDate_, \n            \"Target date lies before basket inception\");\n        Real loss = settledLoss(endDate);\n        return std::min(detachmentAmount_, attachmentAmount_ + \n            std::max(0.0, loss - attachmentAmount_));\n    }\n\n    Probability Basket::probOverLoss(const Date& d, Real lossFraction) const {\n        // convert initial basket fraction to remaining basket fraction\n        calculate();\n        // if eaten up all the tranche the prob of losing any amount is 1 \n        //  (we have already lost it)\n        if(evalDateRemainingNot_ == 0.) return 1.;\n\n        // Turn to live (remaining) tranche units to feed into the model request\n        Real xPtfl = attachmentAmount_ + \n            (detachmentAmount_-attachmentAmount_)*lossFraction;\n        Real xPrim = (xPtfl- evalDateAttachAmount_)/\n            (detachmentAmount_-evalDateAttachAmount_);\n        // in live tranche fractional units\n        // if the level falls within realized losses the prob is 1.\n        if(xPtfl < 0.) return 1.;\n\n        return lossModel_->probOverLoss(d, xPrim);\n    }\n\n    Real Basket::percentile(const Date& d, Probability prob) const {\n        calculate();\n        return lossModel_->percentile(d, prob);\n\n        Real percLiveFract = lossModel_->percentile(d, prob);     \n        return (percLiveFract*(detachmentAmount_-evalDateAttachAmount_) \n            + attachmentAmount_ - evalDateAttachAmount_)\n            /(detachmentAmount_-attachmentAmount_);\n    }\n\n    Real Basket::expectedTrancheLoss(const Date& d) const {\n        calculate();\n        return cumulatedLoss() + lossModel_->expectedTrancheLoss(d);\n    }\n\n    Disposable<std::vector<Real> > \n        Basket::splitVaRLevel(const Date& date, Real loss) const {\n        calculate();\n        return lossModel_->splitVaRLevel(date, loss);\n    }\n\n    Real Basket::expectedShortfall(const Date& d, Probability prob) const {\n        calculate();\n        return lossModel_->expectedShortfall(d, prob);\n    }\n\n    Disposable<std::map<Real, Probability> > \n        Basket::lossDistribution(const Date& d) const {\n        calculate();\n        return lossModel_->lossDistribution(d);\n    }\n\n    std::vector<Probability> \n        Basket::probsBeingNthEvent(Size n, const Date& d) const {\n\n        Size alreadyDefaulted = pool_->size() - remainingNames().size();\n        if(alreadyDefaulted >=n) \n            return std::vector<Probability>(remainingNames().size(), 0.);\n\n        calculate();\n        return lossModel_->probsBeingNthEvent(n-alreadyDefaulted, d);\n    }\n\n    Real Basket::defaultCorrelation(const Date& d, Size iName, Size jName) const{\n        calculate();\n        return lossModel_->defaultCorrelation(d, iName, jName);\n\n    }\n\n    /*! Returns the probaility of having a given or larger number of \n    defaults in the basket portfolio at a given time.\n    */\n    Probability Basket::probAtLeastNEvents(Size n, const Date& d) const{\n        calculate();\n        return lossModel_->probAtLeastNEvents(n, d);\n\n    }\n\n    Real Basket::recoveryRate(const Date& d, Size iName) const {\n        calculate();\n        return \n            lossModel_->expectedRecovery(d, iName, pool_->defaultKeys()[iName]);\n    }\n\n}\n\n", "meta": {"hexsha": "edf1235ad3e54eec4dc965ba25f6493d0d04f169", "size": 14937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLib/ql/experimental/credit/basket.cpp", "max_stars_repo_name": "frannuca/quantlib", "max_stars_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "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": "QuantLib/ql/experimental/credit/basket.cpp", "max_issues_repo_name": "frannuca/quantlib", "max_issues_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLib/ql/experimental/credit/basket.cpp", "max_forks_repo_name": "frannuca/quantlib", "max_forks_repo_head_hexsha": "63e66f5f767397e5b7c79fa78eaed4e3e0a6b7c6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-24T04:54:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T04:54:18.000Z", "avg_line_length": 38.6968911917, "max_line_length": 81, "alphanum_fraction": 0.6014594631, "num_tokens": 3308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.24848030850481534}}
{"text": "#include <string>\n#include <array>\n#include <vector>\n#include <set>\n#include <map>\n#include <queue>\n#include <stack>\n#include <sstream>\n#include <cstdint>\n#include <ostream>\n#include <bitset>\n#include <algorithm>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include \"Action.hpp\"\n#include \"UnionFind.hpp\"\n#include \"DirectedGraph.hpp\"\n#include \"Partition.hpp\"\n\n#ifndef STRATEGY_N3M5_HPP\n#define STRATEGY_N3M5_HPP\n\nclass StrategyN3M5;\n\ntypedef std::bitset<5> HistoM5;\n\nclass StateN3M5 {\n public:\n  StateN3M5(const HistoM5 &a_histo, const HistoM5 &b_histo, const HistoM5 &c_histo) :\n      ha(a_histo), hb(b_histo), hc(c_histo) {};\n  StateN3M5(const std::string &str) { // format \"ccccc_dddcc_cdccd\" (a0,a1,a2,...c3,c4) last action comes first\n    assert(str.size() == 17 && str[5] == '_' && str[11] == '_');\n    std::string sa = str.substr(0, 5), sb = str.substr(6, 5), sc = str.substr(12, 5);\n    auto s_to_binary = [](std::string s)->HistoM5 {\n      std::reverse(s.begin(), s.end());\n      std::replace(s.begin(), s.end(), 'c', '0');\n      std::replace(s.begin(), s.end(), 'd', '1');\n      return HistoM5(s);\n    };\n    ha = s_to_binary(sa); hb = s_to_binary(sb); hc = s_to_binary(sc);\n  }\n  StateN3M5(uint64_t i) { // (c4,c3,c2,....,a1,a0) the lowest bit is a0\n    uint64_t mask = 31ull;\n    ha = HistoM5(i & mask); hb = HistoM5((i>>5ul)&mask); hc = HistoM5((i>>10)&mask);\n  }\n  HistoM5 ha, hb, hc;\n\n  bool operator==(const StateN3M5 &rhs) const {\n    return (ha == rhs.ha && hb == rhs.hb && hc == rhs.hc);\n  }\n  friend std::ostream &operator<<(std::ostream &os, const StateN3M5 &s) {\n    auto to_s = [](const HistoM5 &h)->std::string {\n      std::string s = h.to_string();\n      std::reverse(s.begin(), s.end());\n      std::replace(s.begin(), s.end(), '0', 'c');\n      std::replace(s.begin(), s.end(), '1', 'd');\n      return s;\n    };\n    os << to_s(s.ha) << '_' << to_s(s.hb) << '_' << to_s(s.hc);\n    return os;\n  };\n\n  StateN3M5 NextState(Action act_a, Action act_b, Action act_c) const {\n    HistoM5 nha = ha << 1;\n    HistoM5 nhb = hb << 1;\n    HistoM5 nhc = hc << 1;\n    if (act_a == D) { nha.set(0); }\n    if (act_b == D) { nhb.set(0); }\n    if (act_c == D) { nhc.set(0); }\n    return StateN3M5(nha, nhb, nhc);\n  };\n\n  std::vector<StateN3M5> PossiblePrevStates() const {\n    std::vector<StateN3M5> ans;\n    for (size_t i = 0; i < 2; i++) {\n      for (size_t j = 0; j < 2; j++) {\n        for (size_t k = 0; k < 2; k++) {\n          HistoM5 lha = ha >> 1;\n          HistoM5 lhb = hb >> 1;\n          HistoM5 lhc = hc >> 1;\n          if (i == 1) { lha.set(4); }\n          if (j == 1) { lhb.set(4); }\n          if (k == 1) { lhc.set(4); }\n          ans.emplace_back(lha, lhb, lhc);\n        }\n      }\n    }\n    return std::move(ans);\n  }\n\n  int RelativePayoff(bool against_B = true) const {\n    bool a0 = ha[0];\n    bool b0 = against_B ? hb[0] : hc[0];\n    if (a0 == false && b0 == true) { return -1; } // C,D\n    else if (a0 == true && b0 == false) { return 1; } // D,C\n    else if (a0 == b0) { return 0; }  // C,C or D,D\n    else {\n      assert(false);\n      return -10000;\n    }\n  }\n\n  StateN3M5 StateFromB() const { return StateN3M5(hb, hc, ha); } // state from B's viewpoint\n  StateN3M5 StateFromC() const { return StateN3M5(hc, ha, hb); } // state from C's viewpoint\n\n  std::array<StateN3M5, 3> NoisedStates() const {\n    HistoM5 ha_n = ha, hb_n = hb, hc_n = hc;\n    ha_n ^= HistoM5(1ull);\n    hb_n ^= HistoM5(1ull);\n    hc_n ^= HistoM5(1ull);\n    std::array<StateN3M5, 3> ans = {StateN3M5(ha_n, hb, hc), StateN3M5(ha, hb_n, hc), StateN3M5(ha, hb, hc_n)};\n    return ans;\n  }\n\n  int NumDiffInT1(const StateN3M5 &other) const {\n    const auto b1 = ToBits();\n    const auto b2 = other.ToBits();\n\n    std::bitset<15> mask(\"111101111011110\");\n    if( (b1 & mask) != (b2 & mask) ) { // inconsistent bit is found\n      return -1;\n    } else {\n      return ((b1 & ~mask) ^ (b2 & ~mask)).count(); // number of different bits\n    }\n  }\n\n  std::string ToString() const {\n    std::ostringstream os;\n    os << *this;\n    return os.str();\n  }\n\n  std::bitset<15> ToBits() const {\n    std::bitset<15> bits(0ull);\n    bits ^= ha.to_ullong();\n    bits ^= (hb.to_ullong() << 5);\n    bits ^= (hc.to_ullong() <<10);\n    return bits;\n  }\n\n  uint64_t ID() const {\n    return ToBits().to_ullong();\n  }\n\n  bool operator<(const StateN3M5 &rhs) const {\n    return (ID() < rhs.ID());\n  }\n};\n\n\nclass StrategyN3M5 {\n public:\n  static const size_t N = 1ull << 15ull; // == 32768\n  StrategyN3M5(const std::bitset<N> &actions); // construct a strategy from a list of actions. 0=>c,1=>d\n  StrategyN3M5 &operator=(const StrategyN3M5 & rhs) = default;\n\n  std::string ToString() const;\n  friend std::ostream &operator<<(std::ostream &os, const StrategyN3M5 &strategy);\n  bool operator==(const StrategyN3M5 &rhs) const {\n    for (size_t i = 0; i < 64; i++) { if (actions[i] != rhs.actions[i]) return false; }\n    return true;\n  }\n\n  Action ActionAt(const StateN3M5 &s) const { return actions[s.ID()] ? D : C; }\n  bool IsDefensible() const;  // check defensibility. Not computationally feasible.\n  bool IsDefensibleDFA() const; // check defensibility using DFA minimization\n  // get stationary state. When coplayer is nullptr, it is set to self\n  std::array<double, N> StationaryState(double e = 0.0001, const StrategyN3M5 *B = nullptr, const StrategyN3M5 *C = nullptr) const;\n  // std::array<double, N> StationaryState2(double e = 0.0001, const StrategyN3M5 *B = nullptr, const StrategyN3M5 *C = nullptr) const;\n  // check efficiency. all actions must be fixed\n  bool IsEfficient(double e = 0.00001, double th = 0.95) const { return (StationaryState(e)[0] > th); }\n  bool IsEfficientTopo() const; // check efficiency using ITG\n  bool IsDistinguishable(double e = 0.00001, double th = 0.95) const {\n    const StrategyN3M5 allc(std::bitset<N>(0ull));\n    return (StationaryState(e, &allc, &allc)[0] < th);\n    // return (StationaryState(e, this, &allc)[0] < th);\n  };  // check distinguishability against AllC\n  bool IsDistinguishableTopo() const; // check distinguishability using the transition graph\n  DirectedGraph ITG() const;  // construct g(S,S).\n  std::array<uint64_t , StrategyN3M5::N> DestsOfITG() const; // Trace g(S,S) from node i. Destination is stored in i'th element.\n  uint64_t NextITGState(const StateN3M5 &s) const; // Trace the intra-transition graph by one step\n  std::vector<uint64_t> TraceStates(uint64_t start, const StrategyN3M5 *B = nullptr, const StrategyN3M5 *C = nullptr) const;\n  UnionFind MinimizeDFA(bool noisy = false) const; // DFA minimization using brute-force method. Computationally demanding\n  Partition MinimizeDFAHopcroft(bool noisy = false) const;\n\n  static StrategyN3M5 AllC();\n  static StrategyN3M5 AllD();\n  static StrategyN3M5 TFT();\n  static StrategyN3M5 WSLS();\n  static StrategyN3M5 AON(size_t m);\n  static StrategyN3M5 FUSS_m3();\n  static StrategyN3M5 CAPRI3();\n  static StrategyN3M5 sCAPRI3();\n private:\n  std::bitset<N> actions;\n  std::vector<StateN3M5> NextPossibleStates(StateN3M5 current) const;\n  bool _Equivalent(size_t i, size_t j, UnionFind &uf_0, bool noisy) const;\n  typedef std::pair<size_t, int> splitter_t;\n  std::array<std::set<size_t>,2> _SplitBySplitter(const Partition &partition, size_t org, const std::set<size_t> &Q, int b, bool noisy) const;\n};\n\n\n#endif //STRATEGY_N3M5_HPP\n", "meta": {"hexsha": "04974bd9fc11ed16e99b1a70cd0d9d8d4667ddf7", "size": 7316, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/StrategyN3M5.hpp", "max_stars_repo_name": "yohm/sim_CAPRI_nplayers", "max_stars_repo_head_hexsha": "d58906d7ec654e1d583090741f27a7bc03954053", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/StrategyN3M5.hpp", "max_issues_repo_name": "yohm/sim_CAPRI_nplayers", "max_issues_repo_head_hexsha": "d58906d7ec654e1d583090741f27a7bc03954053", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/StrategyN3M5.hpp", "max_forks_repo_name": "yohm/sim_CAPRI_nplayers", "max_forks_repo_head_hexsha": "d58906d7ec654e1d583090741f27a7bc03954053", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.862745098, "max_line_length": 142, "alphanum_fraction": 0.6268452706, "num_tokens": 2451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.24848030850481534}}
{"text": "// All content Copyright (C) 2018 Genomics plc\n#include \"utils/NeedlemanWunsch.hpp\"\n//#include <boost/numeric/ublas/io.hpp>\n#include <stack>\n#include \"utils/interval.hpp\"\n\nnamespace wecall\n{\nnamespace utils\n{\n    std::vector< NWVariant > NeedlemanWunsch::traceBack() const\n    {\n        std::stack< Backtrace > currentItems;\n\n        const auto lastRefIndex = m_scoreMatrix.size1() - 1;\n        const auto lastAltIndex = m_scoreMatrix.size2() - 1;\n        currentItems.push(\n            Backtrace{{}, lastRefIndex, lastAltIndex, m_traceMatrix( lastRefIndex, lastAltIndex ), false} );\n\n        std::vector< std::vector< NWVariant > > allVariantCombinations;\n\n        while ( not currentItems.empty() )\n        {\n            bool deadEnd = false;\n\n            auto current = currentItems.top();\n            currentItems.pop();\n\n            while ( ( current.refIndex > 0 or current.altIndex > 0 ) and not deadEnd )\n            {\n                auto cache = current;\n                if ( current.trace == 0 )\n                {\n                    // Reached the left side or the top\n                    if ( current.refIndex and current.previousIsDeletion )\n                    {\n                        deadEnd = true;\n                    }\n                    else\n                    {\n                        if ( current.altIndex != 0 )\n                        {\n                            // insertion of the rest of the alt sequence\n                            const auto alt = m_altString.substr( 0, current.altIndex );\n                            current.variants.push_back( NWVariant( 0, 0, alt ) );\n                        }\n                        if ( current.refIndex != 0 )\n                        {\n                            // deletion of the rest of ref sequence\n                            current.variants.push_back( NWVariant( 0, current.refIndex, \"\" ) );\n                        }\n                    }\n                    break;\n                }\n                else if ( current.trace & m_matchBit )\n                {\n                    // No indel\n                    current.trace ^= m_matchBit;\n                    current.previousIsDeletion = false;\n                    current.altIndex -= 1;\n                    current.refIndex -= 1;\n                }\n                else if ( current.trace & m_snpBit )\n                {\n                    // SNP\n                    current.trace ^= m_snpBit;\n                    current.previousIsDeletion = false;\n                    current.altIndex -= 1;\n                    current.refIndex -= 1;\n                    const auto alt = m_altString.substr( current.altIndex, 1 );\n                    current.variants.push_back( NWVariant( current.refIndex, current.refIndex + 1, alt ) );\n                }\n                else if ( current.trace & m_insertSingleBit )\n                {\n                    // insertion of size 1\n                    current.trace ^= m_insertSingleBit;\n                    if ( current.previousIsDeletion )\n                    {\n                        deadEnd = true;\n                    }\n                    else\n                    {\n                        current.previousIsDeletion = false;\n                        current.altIndex -= 1;\n                        const auto alt = m_altString.substr( current.altIndex, 1 );\n                        current.variants.push_back( NWVariant( current.refIndex, current.refIndex, alt ) );\n                    }\n                }\n                else if ( current.trace & m_deleteSingleBit )\n                {\n                    // deletion of size 1\n                    current.trace ^= m_deleteSingleBit;\n                    current.previousIsDeletion = true;\n                    current.refIndex -= 1;\n                    current.variants.push_back( NWVariant( current.refIndex, current.refIndex + 1, \"\" ) );\n                }\n                else if ( current.trace & m_insertMultiBit )\n                {\n                    // insertion of size > 1\n                    current.trace ^= m_insertMultiBit;\n                    if ( current.previousIsDeletion )\n                    {\n                        deadEnd = true;\n                    }\n                    else\n                    {\n                        current.previousIsDeletion = false;\n                        auto targetScore = m_scoreMatrix( current.refIndex, current.altIndex );\n                        auto startingAltIndex = current.altIndex;\n\n                        for ( std::size_t len = 2; len <= startingAltIndex; ++len )\n                        {\n                            current.altIndex = startingAltIndex - len;\n                            auto actualScore = m_scoreMatrix( current.refIndex, current.altIndex ) +\n                                               m_nWPenalties.insertionFunction( current.altIndex, len );\n\n                            if ( targetScore == actualScore )\n                            {\n                                const auto alt = m_altString.substr( current.altIndex, len );\n                                const auto variant = NWVariant( current.refIndex, current.refIndex, alt );\n                                const auto newTrace = m_traceMatrix( current.refIndex, current.altIndex );\n\n                                if ( newTrace == 0 )\n                                {\n                                    // We are at the beginning of the alt sequence, so there can't be any more starting\n                                    // points that achieve the required score after this. Add the new variant to the\n                                    // current variants and continue.\n                                    current.variants.push_back( variant );\n                                    break;\n                                }\n                                else\n                                {\n                                    // There may be more starting points earlier in the alt sequence, so we save the\n                                    // information about starting at this point on the stack rather than continuing with\n                                    // it straight away.\n                                    auto newVariants = current.variants;\n                                    newVariants.push_back( variant );\n                                    currentItems.push( Backtrace{newVariants,\n                                                                 current.refIndex,\n                                                                 current.altIndex,\n                                                                 newTrace,\n                                                                 current.previousIsDeletion} );\n                                }\n                            }\n                            if ( m_traceMatrix( current.refIndex, current.altIndex ) == 0 )\n                            {\n                                // If we get here then we got to the beginning of the alt sequence, and it wasn't a\n                                // possible starting point for the insertion (if it was then we would have broken out of\n                                // the for loop), so we shouldn't continue from the current position. We make this\n                                // happen by setting deadEnd to true.\n                                deadEnd = true;\n                            }\n                        }\n                    }\n                }\n                else if ( current.trace & m_deleteMultiBit )\n                {\n                    // deletion of size > 1\n                    current.trace ^= m_deleteMultiBit;\n                    current.previousIsDeletion = true;\n\n                    auto targetScore = m_scoreMatrix( current.refIndex, current.altIndex );\n                    auto startingRefIndex = current.refIndex;\n\n                    for ( std::size_t len = 2; len <= startingRefIndex; ++len )\n                    {\n                        current.refIndex = startingRefIndex - len;\n                        auto actualScore = m_scoreMatrix( current.refIndex, current.altIndex ) +\n                                           m_nWPenalties.deletionFunction( current.refIndex, len );\n\n                        if ( targetScore == actualScore )\n                        {\n                            const auto variant = NWVariant( current.refIndex, startingRefIndex, \"\" );\n                            const auto newTrace = m_traceMatrix( current.refIndex, current.altIndex );\n\n                            if ( newTrace == 0 )\n                            {\n                                // We are at the beginning of the ref sequence, so there can't be any more starting\n                                // points that achieve the required score after this. Add the new variant to the\n                                // current variants and continue.\n                                current.variants.push_back( variant );\n                                break;\n                            }\n                            else\n                            {\n                                // There may be more starting points earlier in the ref sequence, so we save the\n                                // information about starting at this point on the stack rather than continuing with\n                                // it straight away.\n                                auto newVariants = current.variants;\n                                newVariants.push_back( variant );\n                                currentItems.push( Backtrace{newVariants,\n                                                             current.refIndex,\n                                                             current.altIndex,\n                                                             newTrace,\n                                                             current.previousIsDeletion} );\n                            }\n                        }\n                        if ( m_traceMatrix( current.refIndex, current.altIndex ) == 0 )\n                        {\n                            // If we get here then we got to the beginning of the ref sequence, and it wasn't a\n                            // possible starting point for the insertion (if it was then we would have broken out of\n                            // the for loop), so we shouldn't continue from the current position. We make this\n                            // happen by setting deadEnd to true.\n                            deadEnd = true;\n                        }\n                    }\n                }\n                if ( current.trace != 0 )\n                {\n                    cache.trace = current.trace;\n                    currentItems.push( cache );\n                }\n                current.trace = m_traceMatrix( current.refIndex, current.altIndex );\n            }\n            if ( not deadEnd )\n            {\n                allVariantCombinations.push_back( current.variants );\n            }\n        }\n        if ( allVariantCombinations.size() > 1 )\n        {\n            WECALL_LOG( DEBUG, \"Warning: while normalizing variants we found \"\n                                    << allVariantCombinations.size() << \" possible normalizations\" << std::endl );\n        }\n\n        return allVariantCombinations.back();\n    }\n\n    int32_t NeedlemanWunsch::getScoreMatrix()\n    {\n        const std::size_t refDim = m_referenceString.size() + 1;\n        const std::size_t altDim = m_altString.size() + 1;\n\n        //        scoreMatrix_t m_scoreMatrix( refDim, altDim );\n        //        traceMatrix_t m_traceMatrix( refDim, altDim );\n        m_scoreMatrix = scoreMatrix_t( refDim, altDim );\n        m_traceMatrix = traceMatrix_t( refDim, altDim );\n\n        m_scoreMatrix( 0, 0 ) = 0;\n\n        // Initialise the first column of the matrix\n        //        for ( std::size_t rowIndex = 1; rowIndex < refDim; ++rowIndex )\n        //        {\n        //            m_scoreMatrix( rowIndex, 0 ) = m_nWPenalties.insertionFunction(0, rowIndex);\n        //            m_traceMatrix( rowIndex, 0 ) = 0;\n        //        }\n\n        if ( refDim > 1 )\n        {\n            m_scoreMatrix( 1, 0 ) = m_nWPenalties.insertionOpen();\n            m_traceMatrix( 1, 0 ) = 0;\n        }\n\n        for ( std::size_t rowIndex = 2; rowIndex < refDim; ++rowIndex )\n        {\n            m_scoreMatrix( rowIndex, 0 ) = m_scoreMatrix( rowIndex - 1, 0 ) + m_nWPenalties.extendInsertion();\n            m_traceMatrix( rowIndex, 0 ) = 0;\n        }\n\n        // Initialise the first row of the matrix\n        //        for ( std::size_t colIndex = 1; colIndex < refDim; ++colIndex )\n        //        {\n        //            m_scoreMatrix( 0, colIndex ) = m_nWPenalties.deletionFunction(0, colIndex);\n        //            m_traceMatrix( 0, colIndex ) = 0;\n        //        }\n\n        if ( altDim > 1 )\n        {\n            m_scoreMatrix( 0, 1 ) = m_nWPenalties.deletionOpen();\n            m_traceMatrix( 0, 1 ) = 0;\n        }\n\n        for ( std::size_t colIndex = 2; colIndex < altDim; ++colIndex )\n        {\n            m_scoreMatrix( 0, colIndex ) = m_scoreMatrix( 0, colIndex - 1 ) + m_nWPenalties.extendDeletion();\n            m_traceMatrix( 0, colIndex ) = 0;\n        }\n\n        // Create the colScore matrix we will use when filling in the matrix\n        // It took me a while to work out why we use these values. When we add\n        std::vector< int32_t > colScore( altDim );\n        // Note that colScore[0] is never used, so there's no need to initialise it\n        //        for ( std::size_t colIndex = 1; colIndex < altDim; ++colIndex )\n        //        {\n        //            // When we add n*m_nWPenalties.gapLinear to colScore[colIndex] we want to get the score for having\n        //            // an insertion of size colIndex followed by a deletion of size n\n        //            colScore[colIndex] = m_nWPenalties.insertionFunction(0, colIndex) +\n        //                                 m_nWPenalties.deletionFunction(0, 1) - m_nWPenalties.gapLinear;\n        //        }\n        if ( altDim > 1 )\n        {\n            colScore[1] = m_nWPenalties.insertionOpen() + m_nWPenalties.deletionOpen() - m_nWPenalties.extendDeletion();\n        }\n\n        for ( std::size_t colIndex = 2; colIndex < altDim; ++colIndex )\n        {\n            colScore[colIndex] = colScore[colIndex - 1] + m_nWPenalties.extendDeletion();\n        }\n\n        // Now go through the rest of the matrix, row by row, calculating the correct values\n        for ( int32_t rowIndex = 1; rowIndex < static_cast< int32_t >( refDim ); ++rowIndex )\n        {\n            //            // When we add m_nWPenalties.gapLinear to rowScore we want to get the score for having a\n            //            // deletion of size rowIndex followed by an insertion of size 1\n            auto rowScore = m_nWPenalties.deletionFunction( 0, rowIndex ) + m_nWPenalties.insertionFunction( 0, 1 ) -\n                            m_nWPenalties.extendInsertion();\n            //            auto rowScore = 2 * m_nWPenalties.gapConstant + rowIndex * m_nWPenalties.extendDeletion();\n\n            for ( int32_t colIndex = 1; colIndex < static_cast< int32_t >( altDim ); ++colIndex )\n            {\n                // Calculate score for not having a gap, i.e. sequences match or there is a SNP\n                const auto refBase = m_referenceString.at( rowIndex - 1 );\n                const auto altBase = m_altString.at( colIndex - 1 );\n                const int32_t noGapScore =\n                    m_scoreMatrix( rowIndex - 1, colIndex - 1 ) + m_nWPenalties.matchFunction( refBase, altBase );\n\n                const auto insertSingleScore =\n                    m_scoreMatrix( rowIndex, colIndex - 1 ) + m_nWPenalties.insertionFunction( colIndex - 1, 1 );\n                const auto insertMultiScore = rowScore + m_nWPenalties.extendInsertion();\n                rowScore = std::max( insertSingleScore, insertMultiScore );\n\n                const auto deleteSingleScore =\n                    m_scoreMatrix( rowIndex - 1, colIndex ) + m_nWPenalties.deletionFunction( rowIndex - 1, 1 );\n                const auto deleteMultiScore = colScore[colIndex] + m_nWPenalties.extendDeletion();\n                colScore[colIndex] = std::max( deleteSingleScore, deleteMultiScore );\n\n                const auto bestScore =\n                    std::max( {noGapScore, insertSingleScore, insertMultiScore, deleteSingleScore, deleteMultiScore} );\n\n                m_scoreMatrix( rowIndex, colIndex ) = bestScore;\n\n                bitType_t trace = 0;\n\n                if ( bestScore == noGapScore )\n                {\n                    if ( refBase == altBase )\n                    {\n                        trace |= m_matchBit;\n                    }\n                    else\n                    {\n                        trace |= m_snpBit;\n                    }\n                }\n                if ( bestScore == insertSingleScore )\n                {\n                    trace |= m_insertSingleBit;\n                }\n                if ( bestScore == deleteSingleScore )\n                {\n                    trace |= m_deleteSingleBit;\n                }\n                if ( bestScore == insertMultiScore )\n                {\n                    trace |= m_insertMultiBit;\n                }\n                if ( bestScore == deleteMultiScore )\n                {\n                    trace |= m_deleteMultiBit;\n                }\n\n                m_traceMatrix( rowIndex, colIndex ) = trace;\n            }\n        }\n\n        return m_scoreMatrix( refDim - 1, altDim - 1 );\n    }\n\n    std::ostream & operator<<( std::ostream & out, const NWPenalties & nWPenalties )\n    {\n        out << \"NWPenalties(\" << nWPenalties.m_baseMatch << \", \" << nWPenalties.m_baseMismatch << \", \"\n            << nWPenalties.m_insertionConstant << \", \" << nWPenalties.m_insertionLinear << \", \"\n            << nWPenalties.m_deletionConstant << \", \" << nWPenalties.m_deletionLinear << \", \"\n            << nWPenalties.m_indelPosition << \")\";\n        return out;\n    }\n\n    std::ostream & operator<<( std::ostream & out, const NWVariant & nWVariant )\n    {\n        out << \"NWVariant(\" << nWVariant.m_start << \", \" << nWVariant.m_end << \", \" << nWVariant.m_alt << \")\";\n        return out;\n    }\n}\n}", "meta": {"hexsha": "6d433afa03dd140d11f11c54e437b096877d7bee", "size": 18287, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/utils/NeedlemanWunsch.cpp", "max_stars_repo_name": "dylex/wecall", "max_stars_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-08T15:47:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T07:13:05.000Z", "max_issues_repo_path": "cpp/src/utils/NeedlemanWunsch.cpp", "max_issues_repo_name": "dylex/wecall", "max_issues_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2018-11-05T09:16:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-09T12:32:56.000Z", "max_forks_repo_path": "cpp/src/utils/NeedlemanWunsch.cpp", "max_forks_repo_name": "dylex/wecall", "max_forks_repo_head_hexsha": "35d24cefa4fba549e737cd99329ae1b17dd0156b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-03T15:46:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-04T07:28:33.000Z", "avg_line_length": 47.6223958333, "max_line_length": 120, "alphanum_fraction": 0.4632799256, "num_tokens": 3555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24840810015529}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_LAPACK_GENERAL_GEEV_WVRVL_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_LAPACK_GENERAL_GEEV_WVRVL_HPP_INCLUDED\n\n#include <nt2/linalg/functions/geev_wvrvl.hpp>\n#include <boost/assert.hpp>\n#include <nt2/linalg/details/lapack/declare/geev.hpp>\n#include <boost/dispatch/attributes.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/functions/height.hpp>\n#include <nt2/include/functions/scalar/max.hpp>\n#include <nt2/include/functions/of_size.hpp>\n#include <nt2/include/functions/resize.hpp>\n#include <nt2/include/functions/sqr.hpp>\n#include <nt2/include/functions/width.hpp>\n#include <nt2/linalg/details/utility/envblocksize.hpp>\n#include <nt2/linalg/details/utility/f77_wrapper.hpp>\n#include <nt2/linalg/details/utility/workspace.hpp>\n#include <nt2/linalg/functions/details/combine.hpp>\n#include <nt2/core/container/table/table.hpp>\n\nnamespace nt2 { namespace ext\n{\n\n  // the routines here compute only the eigenvalues and always in a complex colon vector\n  //---------------------------------------------Real-double- wvlvr------------------------------------------------//\n  /// INTERNAL ONLY - Compute the workspace\n  BOOST_DISPATCH_IMPLEMENT  ( geev_wvrvl_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(S2)(A3)(S3)\n                            , ((container_<nt2::tag::table_,  double_<A0>, S0 >))             //a\n                              ((container_<nt2::tag::table_,  complex_<double_<A1> >, S1 >))  //w\n                              ((container_<nt2::tag::table_,  complex_<double_<A2> >, S2 >))  //vr\n                              ((container_<nt2::tag::table_,  complex_<double_<A3> >, S3 >))  //vl\n                             )\n  {\n    typedef nt2_la_int result_type;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a, A2&w, A2& vr, A3& vl) const\n    {\n      char jobvl = 'V';\n      char jobvr = 'V';\n      result_type info = 0;\n      details::workspace<typename A0::value_type> wk;\n      nt2_la_int n = nt2::width(a);\n      BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n      nt2_la_int lda  = nt2::max(a.leading_size(), One<size_t>());\n      nt2_la_int ldvr = n;\n      nt2_la_int ldvl = n;\n      NT2_F77NAME(dgeev) ( &jobvl, &jobvr\n                         , &n\n                         , 0 /*a*/, &lda\n                         , 0/*wr*/, 0/*wi*/\n                         , 0/*vl*/, &ldvl\n                         , 0/*vr*/, &ldvr\n                         , wk.main(), details::query()\n                         , &info);\n      info = nt2::geev_wvrvl(a, w, vr, vl, wk);\n      return info;\n    }\n  };\n\n  //---------------------------------------------Real-single- wvlvr------------------------------------------------//\n  /// INTERNAL ONLY - Compute the workspace\n  BOOST_DISPATCH_IMPLEMENT  ( geev_wvrvl_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(S2)(A3)(S3)\n                            , ((container_<nt2::tag::table_,  single_<A0>, S0 >))             //a\n                              ((container_<nt2::tag::table_,  complex_<single_<A1> >, S1 >))  //w\n                              ((container_<nt2::tag::table_,  complex_<single_<A2> >, S2 >))  //vr\n                              ((container_<nt2::tag::table_,  complex_<single_<A3> >, S3 >))  //vl\n                            )\n  {\n    typedef nt2_la_int result_type;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a, A1& w, A2& vr, A3& vl) const\n    {\n      char jobvl = 'V';\n      char jobvr = 'V';\n      result_type info = 0;\n      details::workspace<typename A0::value_type> wk;\n      nt2_la_int n = nt2::width(a);\n      BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n      nt2_la_int lda  = nt2::max(a.leading_size(), One<size_t>());\n      nt2_la_int ldvr = n;\n      nt2_la_int ldvl = n;\n      NT2_F77NAME(sgeev) ( &jobvl, &jobvr\n                         , &n\n                         , 0 /*a*/, &lda\n                         , 0/*wr*/, 0/*wi*/\n                         , 0/*vl*/, &ldvl\n                         , 0/*vr*/, &ldvr\n                         , wk.main(), details::query()\n                         , &info);\n      info = nt2::geev_wvrvl(a, w, vr, vl, wk);\n      return info;\n     }\n  };\n\n//---------------------------------------------Complex-single- wvlvr------------------------------------------------//\n  /// INTERNAL ONLY - Compute the workspace\n  BOOST_DISPATCH_IMPLEMENT  ( geev_wvrvl_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(S2)(A3)(S3)\n                            , ((container_<nt2::tag::table_,  complex_<single_<A0> >, S0 >))  //a\n                              ((container_<nt2::tag::table_,  complex_<single_<A1> >, S1 >))  //w\n                              ((container_<nt2::tag::table_,  complex_<single_<A2> >, S2 >))  //vr\n                              ((container_<nt2::tag::table_,  complex_<single_<A3> >, S3 >))  //vl\n                            )\n  {\n    typedef nt2_la_int result_type;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a, A1& w, A2& vr, A3& vl) const\n    {\n      char jobvl = 'V';\n      char jobvr = 'V';\n      result_type info = 0;\n      details::workspace<typename A0::value_type> wk;\n      nt2_la_int n = nt2::width(a);\n      BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n      nt2_la_int lda  = nt2::max(a.leading_size(), One<size_t>());\n      nt2_la_int ldvl = n;\n      nt2_la_int ldvr = n;\n      NT2_F77NAME(cgeev) ( &jobvl, &jobvr\n                         , &n\n                         , 0 /*a*/, &lda\n                         , 0 /*w*/\n                         , 0 /*vl*/, &ldvl\n                         , 0 /*vr*/, &ldvr\n                         , wk.main(), details::query()\n                         , wk.reals()\n                         , &info);\n     info = nt2::geev_wvrvl(a, w, vr, vl, wk);\n      return info;\n     }\n  };\n\n  //---------------------------------------------Complex-double- wvlvr------------------------------------------------//\n  /// INTERNAL ONLY - Compute the workspace\n  BOOST_DISPATCH_IMPLEMENT  ( geev_wvrvl_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(S2)(A3)(S3)\n                            , ((container_<nt2::tag::table_,  complex_<double_<A0> >, S0 >))  //a\n                              ((container_<nt2::tag::table_,  complex_<double_<A1> >, S1 >))  //w\n                              ((container_<nt2::tag::table_,  complex_<double_<A2> >, S2 >))  //vr\n                              ((container_<nt2::tag::table_,  complex_<double_<A3> >, S3 >))  //vl\n                           )\n  {\n    typedef nt2_la_int result_type;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a, A1& w, A2& vr, A3& vl) const\n    {\n      char jobvl = 'V';\n      char jobvr = 'V';\n      result_type info = 0;\n      details::workspace<typename A0::value_type> wk;\n      nt2_la_int n = nt2::width(a);\n      BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n      nt2_la_int lda  = nt2::max(a.leading_size(), One<size_t>());\n      nt2_la_int ldvl = n;\n      nt2_la_int ldvr = n;\n      NT2_F77NAME(zgeev) ( &jobvl, &jobvr\n                         , &n\n                         , 0 /*a*/, &lda\n                         , 0 /*w*/\n                         , 0 /*vl*/, &ldvl\n                         , 0 /*vr*/, &ldvr\n                         , wk.main(), details::query()\n                         , wk.reals()\n                         , &info);\n      info = nt2::geev_wvrvl(a, w, vr, vl, wk);\n      return info;\n     }\n  };\n\n  //---------------------------------------------Real-double- wvlvr------------------------------------------------//\n  /// INTERNAL ONLY - Workspace is ready\n  BOOST_DISPATCH_IMPLEMENT  ( geev_wvrvl_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(S2)(A3)(S3)(WK)\n                            , ((container_<nt2::tag::table_,  double_<A0>, S0 >))             //a\n                              ((container_<nt2::tag::table_,  complex_<double_<A1> >, S1 >))  //w\n                              ((container_<nt2::tag::table_,  complex_<double_<A2> >, S2 >))  //vr\n                              ((container_<nt2::tag::table_,  complex_<double_<A3> >, S3 >))  //vl\n                              (unspecified_<WK>)                                              //workspace\n                            )\n  {\n    typedef nt2_la_int result_type;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a, A1& w, A2& vr, A3& vl, WK& wk) const\n    {\n      char jobvl = 'V';\n      char jobvr = 'V';\n      result_type info;\n      nt2_la_int n = nt2::width(a);\n      BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n      nt2::container::table<double> wr(of_size(n, 1)),  wi(of_size(n, 1))\n                                  , rvr(of_size(n, n)), rvl(of_size(n, n));\n      nt2_la_int lda = nt2::max(a.leading_size(), One<size_t>());\n      nt2_la_int wn = wk.main_need();\n      wk.resize_main(wn);\n      nt2_la_int ldvl = rvl.leading_size();\n      nt2_la_int ldvr = rvr.leading_size();\n      NT2_F77NAME(dgeev) ( &jobvl, &jobvr\n                         , &n\n                         , a.data() , &lda\n                         , wr.data(), wi.data()\n                         , rvl.data(), &ldvl\n                         , rvr.data(), &ldvr\n                         , wk.main(), &wn\n                         , &info);\n      details::combine_eigens(wr, wi, w);\n      details::combine_vects(rvr, wi, vr);\n      details::combine_vects(rvl, wi, vl);\n      return info;\n    }\n  };\n\n  //---------------------------------------------Real-single- wvlvr------------------------------------------------//\n  /// INTERNAL ONLY - Workspace is ready\n  BOOST_DISPATCH_IMPLEMENT  ( geev_wvrvl_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(S2)(A3)(S3)(WK)\n                            , ((container_<nt2::tag::table_,  single_<A0>, S0 >))             //a\n                              ((container_<nt2::tag::table_,  complex_<single_<A1> >, S1 >))  //w\n                              ((container_<nt2::tag::table_,  complex_<single_<A2> >, S2 >))  //vr\n                              ((container_<nt2::tag::table_,  complex_<single_<A3> >, S3 >))  //vl\n                               (unspecified_<WK>)                                              //workspace\n                            )\n  {\n    typedef nt2_la_int result_type;\n\n    BOOST_FORCEINLINE result_type operator()( A0& a, A1& w, A2& vr, A3& vl, WK& wk) const\n    {\n      char jobvl = 'V';\n      char jobvr = 'V';\n      result_type info;\n      nt2_la_int n = nt2::width(a);\n      BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n      nt2::container::table<float> wr(of_size(n, 1)),  wi(of_size(n, 1))\n                                 , rvr(of_size(n, n)), rvl(of_size(n, n));\n      nt2_la_int lda = nt2::max(a.leading_size(), One<size_t>());\n      nt2_la_int wn = wk.main_need();\n      wk.resize_main(wn);\n      nt2_la_int ldvl = rvl.leading_size();\n      nt2_la_int ldvr = rvr.leading_size();\n      NT2_F77NAME(sgeev) ( &jobvl, &jobvr\n                         , &n\n                         , a.data() , &lda\n                         , wr.data(), wi.data()\n                         , rvl.data(), &ldvl\n                         , rvr.data(), &ldvr\n                         , wk.main(), &wn\n                         , &info);\n      details::combine_eigens(wr, wi, w);\n      details::combine_vects(rvr, wi, vr);\n      details::combine_vects(rvl, wi, vl);\n      return info;\n    }\n  };\n\n\n\n  //---------------------------------------------Complex-single- wvlvr------------------------------------------------//\n  /// INTERNAL ONLY - Workspace is ready\n  BOOST_DISPATCH_IMPLEMENT  ( geev_wvrvl_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(S2)(A3)(S3)(WK)\n                            , ((container_<nt2::tag::table_,  complex_<single_<A0> >, S0 >))  //a\n                              ((container_<nt2::tag::table_,  complex_<single_<A1> >, S1 >))  //w\n                              ((container_<nt2::tag::table_,  complex_<single_<A2> >, S2 >))  //vr\n                              ((container_<nt2::tag::table_,  complex_<single_<A3> >, S3 >))  //vl\n                              (unspecified_<WK>)                                              //workspace\n                            )\n  {\n     typedef nt2_la_int result_type;\n\n     BOOST_FORCEINLINE result_type operator()( A0& a, A1& w, A2& vr, A3& vl, WK& wk) const\n     {\n       char jobvl = 'V';\n       char jobvr = 'V';\n       result_type info;\n       nt2_la_int n = nt2::width(a);\n       BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n       nt2_la_int lda = nt2::max(a.leading_size(), One<size_t>());\n       vl.resize(of_size(n, n));\n       vr.resize(of_size(n, n));\n       nt2_la_int ldvl = vl.leading_size();\n       nt2_la_int ldvr = vr.leading_size();\n       nt2_la_int wn = wk.main_need();\n       wk.resize_main(wn);\n       wk.resize_reals(2*n);\n       w.resize(of_size(n, 1));\n       NT2_F77NAME(cgeev) ( &jobvl, &jobvr\n                          , &n\n                          , a.data() , &lda\n                          , w.data()\n                          , vl.data(), &ldvl\n                          , vr.data(), &ldvr\n                          , wk.main(), &wn\n                          , wk.reals()\n                          , &info);\n        return info;\n     }\n  };\n\n  //---------------------------------------------Complex-double- wvlvr------------------------------------------------//\n  /// INTERNAL ONLY - Workspace is ready\n  BOOST_DISPATCH_IMPLEMENT  ( geev_wvrvl_, tag::cpu_\n                            , (A0)(S0)(A1)(S1)(A2)(S2)(A3)(S3)(WK)\n                            , ((container_<nt2::tag::table_,  complex_<double_<A0> >, S0 >))  //a\n                              ((container_<nt2::tag::table_,  complex_<double_<A1> >, S1 >))  //w\n                              ((container_<nt2::tag::table_,  complex_<double_<A2> >, S2 >))  //vr\n                              ((container_<nt2::tag::table_,  complex_<double_<A3> >, S3 >))  //vl\n                              (unspecified_<WK>)                                              //workspace\n                            )\n  {\n     typedef nt2_la_int result_type;\n\n     BOOST_FORCEINLINE result_type operator()( A0& a, A1& w, A2& vr, A3& vl, WK& wk) const\n     {\n       char jobvl = 'V';\n       char jobvr = 'V';\n       result_type info;\n       nt2_la_int n = nt2::width(a);\n       BOOST_ASSERT_MSG(n == nt2_la_int(nt2::height(a)), \"input must be square\");\n       nt2_la_int lda = nt2::max(a.leading_size(), One<size_t>());\n       vl.resize(of_size(n, n));\n       vr.resize(of_size(n, n));\n       nt2_la_int ldvl = vl.leading_size();\n       nt2_la_int ldvr = vr.leading_size();\n       nt2_la_int wn = wk.main_need();\n       wk.resize_main(wn);\n       wk.resize_reals(2*n);\n       w.resize(of_size(n, 1));\n       NT2_F77NAME(zgeev) ( &jobvl, &jobvr\n                          , &n\n                          , a.data() , &lda\n                          , w.data()\n                          , vl.data(), &ldvl\n                          , vr.data(), &ldvr\n                          , wk.main(), &wn\n                          , wk.reals()\n                          , &info);\n        return info;\n     }\n  };\n} }\n\n#endif\n", "meta": {"hexsha": "61f933c36d3fbf021996af3bb70599160845cdca", "size": 15784, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/general/geev_wvrvl.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/general/geev_wvrvl.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/linalg/include/nt2/linalg/functions/lapack/general/geev_wvrvl.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 44.9686609687, "max_line_length": 120, "alphanum_fraction": 0.446591485, "num_tokens": 4148, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2484080938995695}}
{"text": "// Copyright (c) 2013 Vasili Baranau\n// Distributed under the MIT software license\n// See the accompanying file License.txt or http://opensource.org/licenses/MIT\n\n#include <stdio.h>\n#include <boost/numeric/odeint.hpp>\n#include \"../Headers/ClosestJammingStep.h\"\n#include \"Core/Headers/Exceptions.h\"\n#include \"Core/Headers/Constants.h\"\n#include \"Generation/PackingServices/DistanceServices/Headers/INeighborProvider.h\"\n#include \"Generation/PackingServices/DistanceServices/Headers/IClosestPairProvider.h\"\n#include \"Generation/Model/Headers/Config.h\"\n#include \"Generation/Geometries/Headers/IGeometry.h\"\n\nusing namespace PackingServices;\nusing namespace Core;\nusing namespace Model;\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\nnamespace PackingGenerators\n{\n    ClosestJammingStep::ClosestJammingStep(GeometryService* geometryService,\n            INeighborProvider* neighborProvider,\n            PackingServices::IClosestPairProvider* closestPairProvider,\n            MathService* mathService) :\n            BasePackingStep(geometryService, neighborProvider, closestPairProvider, mathService),\n            closestJammingVelocityProvider(mathService)\n    {\n        isOuterDiameterChanging = false;\n        canOvercomeTheoreticalDensity = true;\n\n        maxTimeStep = -1.0;\n        integrationTimeStep = 1e-9;\n    }\n\n    ClosestJammingStep::~ClosestJammingStep()\n    {\n\n    }\n\n    const FLOAT_TYPE ClosestJammingStep::GetBondThreshold() const\n    {\n        return bondsProvider.GetBondThreshold();\n    }\n\n    void ClosestJammingStep::SetBondThreshold(Core::FLOAT_TYPE value)\n    {\n        bondsProvider.SetBondThreshold(value);\n    }\n\n    void ClosestJammingStep::SetParticles(Packing* particles)\n    {\n        BasePackingStep::SetParticles(particles);\n        ParticlePair closestPair = closestPairProvider->FindClosestPair();\n        innerDiameterRatio = sqrt(closestPair.normalizedDistanceSquare);\n\n        bondsProvider.Reset(config->particlesCount);\n\n        particleVelocities.clear();\n        particleVelocities.resize(config->particlesCount);\n\n        bondsProvider.UpdateBonds(*neighborProvider, *mathService, *particles, innerDiameterRatio, false);\n        startBondsCountForIntegrationTimeStep = bondsProvider.GetBonds().size();\n    }\n\n    void ClosestJammingStep::DisplaceParticles()\n    {\n        initialInnerDiameterRatio = innerDiameterRatio;\n        clock_t linearSystemSolutionTime = FillVelocities();\n        FLOAT_TYPE timeStep = FindBestMovementTime();\n\n        int odeCyclesCount = 0;\n        if (timeStep <= integrationTimeStep)\n        {\n            MoveParticles(timeStep);\n            innerDiameterRatio += timeStep;\n        }\n        else\n        {\n            odeCyclesCount = DisplaceParticlesForLongTime();\n        }\n\n        // Remove intersections at each iteration\n        innerDiameterRatio = sqrt(closestPairProvider->FindClosestPair().normalizedDistanceSquare);\n\n        // Search for new contacts, update bonds and bonds per particle\n        BondsProvider::Statistics statistics = bondsProvider.UpdateBonds(*neighborProvider, *mathService, *particles, innerDiameterRatio, false);\n        if (statistics.gapsCount > 0)\n        {\n            printf(\"BROKEN: broken bonds count is %d, mean gap length is %g\\n\", statistics.gapsCount, statistics.meanGapLength);\n        }\n        if (statistics.intersectionsCount > 0)\n        {\n            printf(\"INTERSECTIONS: intersections count is %d, mean intersection length is %g\\n\", statistics.intersectionsCount, statistics.meanIntersectionLength);\n        }\n\n        printf(\"Bonds count: %d; bond pairs count: %d; time step: %g; slae solution time: %g (s); ode cycles count: %d; integration time step: %g\\n\",\n                bondsProvider.GetBonds().size(), bondsProvider.GetBondPairsCount(), timeStep, linearSystemSolutionTime / static_cast<FLOAT_TYPE>(CLOCKS_PER_SEC), odeCyclesCount, integrationTimeStep);\n\n        FixIntersections(statistics);\n    }\n\n    // TODO: merge somehow with DoBinarySearchForCollision\n    int ClosestJammingStep::DisplaceParticlesForLongTime()\n    {\n        // OdeObserver is passed by value, that's why need to store reference to odeCyclesCount.\n        int odeCyclesCount = 0;\n        OdeObserver observer(&odeCyclesCount, this);\n\n        ParticleSystemForODE odeSystem(this);\n        vector<FLOAT_TYPE> combinedParticleCoordinates(DIMENSIONS * config->particlesCount);\n        UpdateCombinedCoordinates(&combinedParticleCoordinates);\n\n        FLOAT_TYPE maxTime = maxTimeStep > 0 ? innerDiameterRatio + maxTimeStep : MAX_FLOAT_VALUE;\n\n        try\n        {\n            // Solve ODE to reach the nextCollisionTime\n//            typedef runge_kutta_dopri5< vector<FLOAT_TYPE> > TStepper;\n//            result_of::make_controlled<TStepper>::type stepper = make_controlled(bondsProvider.GetBondThreshold(), bondsProvider.GetBondThreshold(), TStepper());\n//            integrate_adaptive(stepper, odeSystem, combinedParticleCoordinates, innerDiameterRatio, maxTime, integrationTimeStep, observer);\n\n//            bulirsch_stoer< vector<FLOAT_TYPE> > stepper(bondsProvider.GetBondThreshold(), bondsProvider.GetBondThreshold());\n//            integrate_adaptive(stepper, odeSystem, combinedParticleCoordinates, innerDiameterRatio, maxTime, integrationTimeStep, observer);\n\n            typedef runge_kutta_dopri5< vector<FLOAT_TYPE> > TStepper;\n            integrate_const(TStepper(), odeSystem, combinedParticleCoordinates, innerDiameterRatio, maxTime, integrationTimeStep, observer);\n\n            // Integration may end normally only if maxTimeStep is specified and reached.\n            // Observer is called even for the very last time, therefore coordinates and velocities are correctly updated.\n            // In case observer is not called for the last time.\n            if (maxTime != MAX_FLOAT_VALUE && maxTime > innerDiameterRatio)\n            {\n                observer(combinedParticleCoordinates, maxTime);\n            }\n        }\n        catch (const CollisionMissedException& e)\n        {\n            printf((e.GetMessage() + \"\\n\").c_str());\n            DoBinarySearchForCollision(e.nextCollisionTimeEstimate, &observer);\n        }\n        catch (const CollisionIsNearException& e)\n        {\n            printf((e.GetMessage() + \"\\n\").c_str());\n            // All the velocities are set in the observer and are correct.\n            MoveParticles(e.nextCollisionTime - innerDiameterRatio);\n            innerDiameterRatio = e.nextCollisionTime;\n        }\n        return odeCyclesCount;\n    }\n\n    void ClosestJammingStep::DoBinarySearchForCollision(FLOAT_TYPE nextCollisionTimeEstimate, OdeObserver* observer)\n    {\n        printf(\"DoBinarySearchForCollision; innerDiameterRatio: %17.15g, nextCollisionTimeEstimate: %17.15g\\n\", innerDiameterRatio, nextCollisionTimeEstimate);\n        if ((nextCollisionTimeEstimate - innerDiameterRatio) < integrationTimeStep)\n        {\n            printf(\"(nextCollisionTimeEstimate - innerDiameterRatio) < integrationTimeStep\\n\");\n            MoveParticles(nextCollisionTimeEstimate - innerDiameterRatio);\n            innerDiameterRatio = nextCollisionTimeEstimate;\n            return;\n        }\n\n        // Do binary search for collision with support for missing collision detection in the course of integration as well.\n        ParticleSystemForODE odeSystem(this);\n        vector<FLOAT_TYPE> combinedParticleCoordinates(DIMENSIONS * config->particlesCount);\n        UpdateCombinedCoordinates(&combinedParticleCoordinates);\n\n        // Integrate from last valid time (always innerDiameterRatio) to half between valid and invalid times\n        FLOAT_TYPE middleTime = (innerDiameterRatio + nextCollisionTimeEstimate) * 0.5;\n        try\n        {\n            // Solve ODE to reach the middleTime\n//            typedef runge_kutta_dopri5< vector<FLOAT_TYPE> > TStepper;\n//            result_of::make_controlled<TStepper>::type stepper = make_controlled(bondsProvider.GetBondThreshold(), bondsProvider.GetBondThreshold(), TStepper());\n//            integrate_adaptive(stepper, odeSystem, combinedParticleCoordinates, innerDiameterRatio, middleTime, integrationTimeStep, observer);\n\n//            bulirsch_stoer< vector<FLOAT_TYPE> > stepper(bondsProvider.GetBondThreshold(), bondsProvider.GetBondThreshold());\n//            integrate_adaptive(stepper, odeSystem, combinedParticleCoordinates, innerDiameterRatio, middleTime, integrationTimeStep, observer);\n\n            typedef runge_kutta_dopri5< vector<FLOAT_TYPE> > TStepper;\n            integrate_const(TStepper(), odeSystem, combinedParticleCoordinates, innerDiameterRatio, middleTime, integrationTimeStep, *observer);\n\n            // Observer was not called for the last time\n            if (middleTime > innerDiameterRatio)\n            {\n                (*observer)(combinedParticleCoordinates, middleTime);\n            }\n\n            printf(\"innerDiameterRatio after successful integration: %17.15g\\n\", innerDiameterRatio);\n            // Integrated successfully. Observer was also called for the last step,\n            // so innerDiameterRatio, particle coordinates, bonds, and particle velocities have correct values (innerDiameterRatio = middleTime),\n            // collision has not happened in the middle time.\n            // Last valid time is the current time, nextCollisionTimeEstimate is the same.\n            DoBinarySearchForCollision(nextCollisionTimeEstimate, observer);\n        }\n\n        // If integrated not successfully:\n        // a. if collision missed, it can not be too close to the last valid time (otherwise the near exception would be fired).\n        catch (const CollisionMissedException& e)\n        {\n            // innerDiameterRatio, particle coordinates, bonds, and particle velocities have correct values (innerDiameterRatio = last time before collision)\n            printf((e.GetMessage() + \"\\n\").c_str());\n            DoBinarySearchForCollision(e.nextCollisionTimeEstimate, observer);\n        }\n        // b. if collision is near, move particles\n        catch (const CollisionIsNearException& e)\n        {\n            printf((e.GetMessage() + \"\\n\").c_str());\n            // All the velocities are set in the observer and are correct.\n            MoveParticles(e.nextCollisionTime - innerDiameterRatio);\n            innerDiameterRatio = e.nextCollisionTime;\n        }\n    }\n\n    void ClosestJammingStep::FixIntersections(BondsProvider::Statistics statistics)\n    {\n        ParticlePair closestPair = closestPairProvider->FindClosestPair();\n        const FLOAT_TYPE tolerance = 1.0 - 5.0 * bondsProvider.GetBondThreshold();\n        bool intersectionsExist = closestPair.normalizedDistanceSquare < innerDiameterRatio * innerDiameterRatio * tolerance * tolerance;\n        if (intersectionsExist)\n        {\n            printf(\"WARNING: min normalized distance %f is lower than inner diameter ratio %f. Particles pair: %d and %d.\\n\",\n                    std::sqrt(closestPair.normalizedDistanceSquare),\n                    innerDiameterRatio,\n                    closestPair.firstParticleIndex,\n                    closestPair.secondParticleIndex);\n        }\n\n        bool errorIsLarge =\n                statistics.meanGapLength > bondsProvider.GetBondThreshold() * 5.0 ||\n                statistics.meanIntersectionLength > bondsProvider.GetBondThreshold() * 5.0 ||\n                intersectionsExist;\n        if (!errorIsLarge)\n        {\n            return;\n        }\n\n        printf(\"WARNING: meanGapLength or meanIntersectionLength are too large. Updating innerDiameterRatio and bonds.\\n\");\n        // The last bond is added with errors. The last but one is not, because otherwise bonds would be recalculated.\n        int endBondsCountForIntegrationTimeStep = bondsProvider.GetBonds().size() - 1;\n        innerDiameterRatio = sqrt(closestPair.normalizedDistanceSquare);\n        bondsProvider.UpdateBonds(*neighborProvider, *mathService, *particles, innerDiameterRatio, true);\n\n        UpdateIntegrationTimeStep(endBondsCountForIntegrationTimeStep);\n    }\n\n    void ClosestJammingStep::UpdateIntegrationTimeStep(int endBondsCountForIntegrationTimeStep)\n    {\n        FLOAT_TYPE addedBondsCount = endBondsCountForIntegrationTimeStep - startBondsCountForIntegrationTimeStep;\n        bool errorGrowsTooQuickly = addedBondsCount < 10;\n\n        startBondsCountForIntegrationTimeStep = endBondsCountForIntegrationTimeStep;\n\n        // After division by 2 integrationTimeStep should be at least 1e-14, as final particle diameter is about 1\n        const FLOAT_TYPE minIntegrationTimeStep = 2e-14;\n        bool shouldUpdateIntegrationTimeStep = errorGrowsTooQuickly && integrationTimeStep > minIntegrationTimeStep;\n        if (shouldUpdateIntegrationTimeStep)\n        {\n            integrationTimeStep *= 0.5;\n            printf(\"WARNING: error grows too quickly. Updated integrationTimeStep to %g.\\n\", integrationTimeStep);\n        }\n\n        if (addedBondsCount <= 0 && integrationTimeStep <= minIntegrationTimeStep)\n        {\n            throw InvalidOperationException(\"Particles do not grow during integration, integrationTimeStep is too low to be decreased further.\");\n        }\n    }\n\n    clock_t ClosestJammingStep::FillVelocities()\n    {\n        clock_t solutionTime = closestJammingVelocityProvider.FillVelocities(*neighborProvider, bondsProvider, *particles, innerDiameterRatio, &particleVelocities);\n        return solutionTime;\n    }\n\n    void ClosestJammingStep::UpdateCombinedCoordinates(vector<FLOAT_TYPE>* combinedParticleCoordinates)\n    {\n        vector<FLOAT_TYPE>& combinedParticleCoordinatesRef = *combinedParticleCoordinates;\n        const Packing& particlesRef = *particles;\n        for (ParticleIndex particleIndex = 0; particleIndex < config->particlesCount; ++particleIndex)\n        {\n            const DomainParticle& particle = particlesRef[particleIndex];\n            for (int i = 0; i < DIMENSIONS; ++i)\n            {\n                combinedParticleCoordinatesRef[particleIndex * DIMENSIONS + i] = particle.coordinates[i];\n            }\n        }\n    }\n\n    void ClosestJammingStep::UpdateCombinedVelocities(vector<FLOAT_TYPE>* combinedVelocities)\n    {\n        vector<FLOAT_TYPE>& combinedVelocitiesRef = *combinedVelocities;\n        for (ParticleIndex particleIndex = 0; particleIndex < config->particlesCount; ++particleIndex)\n        {\n            const Core::SpatialVector& velocity = particleVelocities[particleIndex];\n            for (int i = 0; i < DIMENSIONS; ++i)\n            {\n                combinedVelocitiesRef[particleIndex * DIMENSIONS + i] = velocity[i];\n            }\n        }\n    }\n\n    void ClosestJammingStep::UpdateParticleCoordinates(const vector<FLOAT_TYPE>& combinedParticleCoordinates)\n    {\n        Model::Packing& particlesRef = *particles;\n        for (ParticleIndex particleIndex = 0; particleIndex < config->particlesCount; ++particleIndex)\n        {\n            DomainParticle& particle = particlesRef[particleIndex];\n\n            closestPairProvider->StartMove(particleIndex);\n            neighborProvider->StartMove(particleIndex);\n\n            for (int i = 0; i < DIMENSIONS; ++i)\n            {\n                particle.coordinates[i] = combinedParticleCoordinates[particleIndex * DIMENSIONS + i];\n            }\n            geometry->EnsureBoundaries(particle, &particle, innerDiameterRatio);\n\n            neighborProvider->EndMove();\n            closestPairProvider->EndMove();\n        }\n    }\n\n    void ClosestJammingStep::ProvideODEDerivative(const vector<FLOAT_TYPE>& x, vector<FLOAT_TYPE>* dxdt, const FLOAT_TYPE t)\n    {\n        // copy x into particles, update innerDiameterRatio\n        UpdateParticleCoordinates(x);\n//        FLOAT_TYPE previousTime = innerDiameterRatio;\n        innerDiameterRatio = t;\n\n        FillVelocities();\n        UpdateCombinedVelocities(dxdt);\n\n//        ////////////////\n//        // Search for new contacts, update bonds and bonds per particle\n//        Nullable<FLOAT_TYPE> meanGapLength = UpdateContacts();\n//\n//        ParticlePair closestPair = closestPairProvider->FindClosestPair();\n//        const FLOAT_TYPE tolerance = 1.0 - bondThreshold;\n//        if (closestPair.normalizedDistanceSquare < innerDiameterRatio * innerDiameterRatio * tolerance * tolerance)\n//        {\n//            printf(\"ODE: WARNING: min normalized distance %f is lower than inner diameter ratio %f. Particles pair: %d and %d; bond existed: %d\\n\",\n//                    std::sqrt(closestPair.normalizedDistanceSquare),\n//                    innerDiameterRatio,\n//                    closestPair.firstParticleIndex,\n//                    closestPair.secondParticleIndex,\n//                    ParticlesShareBond(closestPair.firstParticleIndex, closestPair.secondParticleIndex));\n//        }\n//\n//        printf(\"ODE: Bonds count: %d; bond pairs count: %d; time step: %g; slae solution time: %g (s); ode delta t: %g\\n\",\n//                bonds.size(), bondPairs.size(), timeStep, linearSystemSolutionTime / static_cast<FLOAT_TYPE>(CLOCKS_PER_SEC), t - previousTime);\n//        ////////////////\n    }\n\n    FLOAT_TYPE ClosestJammingStep::FindBestMovementTime()\n    {\n        FLOAT_TYPE movementTime = closestJammingVelocityProvider.FindBestMovementTime();\n        if (maxTimeStep > 0 && (movementTime + innerDiameterRatio - initialInnerDiameterRatio > maxTimeStep))\n        {\n            movementTime = initialInnerDiameterRatio + maxTimeStep - innerDiameterRatio;\n        }\n        return movementTime;\n    }\n\n    void ClosestJammingStep::MoveParticles(FLOAT_TYPE timeStep)\n    {\n        Model::Packing& particlesRef = *particles;\n        for (ParticleIndex particleIndex = 0; particleIndex < config->particlesCount; ++particleIndex)\n        {\n            DomainParticle& particle = particlesRef[particleIndex];\n            if (bondsProvider.GetBondIndexesPerParticle()[particleIndex].size() == 0)\n            {\n                continue;\n            }\n\n            closestPairProvider->StartMove(particleIndex);\n            neighborProvider->StartMove(particleIndex);\n\n            SpatialVector displacement;\n            VectorUtilities::MultiplyByValue(particleVelocities[particleIndex], timeStep, &displacement);\n            VectorUtilities::Add(particle.coordinates, displacement, &particle.coordinates);\n            geometry->EnsureBoundaries(particle, &particle, innerDiameterRatio);\n\n            neighborProvider->EndMove();\n            closestPairProvider->EndMove();\n        }\n    }\n\n    void ClosestJammingStep::ResetGeneration()\n    {\n        throw InvalidOperationException(\"ResetGeneration does nothing for ClosestJammingStep. Always set maxRunsCount = 1 for LS.\");\n    }\n\n    bool ClosestJammingStep::ShouldContinue() const\n    {\n         // 3 degrees of freedom are diminished as one particle can always be considered fixed.\n         return bondsProvider.GetBonds().size() < static_cast<size_t>(DIMENSIONS * (config->particlesCount - 1));\n\n//        // Expected bonds count n = DIMENSIONS * (particlesCount - 1) = 30 000 - 3 = 29997\n//        // Expected coordination number c = 2 * n / particlesCount = 2 * n - 1 / particlesCount = 5.9994 ~ 6 = 2 * n / particlesCount\n//        // Acceptable coordination number = 5.98\n//        // Acceptable bonds count n = 5.98 / 2 * particlesCount = 29900. This difference will matter a lot (each iteration may consume > 1 minute)\n//        size_t acceptableBondsCount = DIMENSIONS * (5.98 / 6.0) * config->particlesCount;\n//        return bondsProvider.GetBonds().size() < acceptableBondsCount;\n    }\n}\n\n", "meta": {"hexsha": "92d01104e3968bb9401e83d5193a98058eba5c50", "size": 19477, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PackingGeneration/Generation/PackingGenerators/Source/ClosestJammingStep.cpp", "max_stars_repo_name": "MINATILO/packing-generation", "max_stars_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2015-08-23T12:05:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:39:56.000Z", "max_issues_repo_path": "PackingGeneration/Generation/PackingGenerators/Source/ClosestJammingStep.cpp", "max_issues_repo_name": "MINATILO/packing-generation", "max_issues_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-07-20T17:57:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T10:31:50.000Z", "max_forks_repo_path": "PackingGeneration/Generation/PackingGenerators/Source/ClosestJammingStep.cpp", "max_forks_repo_name": "MINATILO/packing-generation", "max_forks_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 36.0, "max_forks_repo_forks_event_min_datetime": "2015-10-14T02:43:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T12:51:03.000Z", "avg_line_length": 47.737745098, "max_line_length": 199, "alphanum_fraction": 0.6836781845, "num_tokens": 4212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24828294112005586}}
{"text": "#include \"kalmanfilter.h\"\n#include <Eigen/Cholesky>\n\nconst double KalmanFilter::chi2inv95[10] = {\n    0,\n    3.8415,\n    5.9915,\n    7.8147,\n    9.4877,\n    11.070,\n    12.592,\n    14.067,\n    15.507,\n    16.919\n};\nKalmanFilter::KalmanFilter()\n{\n    int ndim = 4;\n    double dt = 1.;\n\n    _motion_mat = Eigen::MatrixXf::Identity(8, 8);\n    for(int i = 0; i < ndim; i++) {\n        _motion_mat(i, ndim+i) = dt;\n    }\n    _update_mat = Eigen::MatrixXf::Identity(4, 8);\n\n    this->_std_weight_position = 1. / 20;\n    this->_std_weight_velocity = 1. / 160;\n}\n\nKAL_DATA KalmanFilter::initiate(const DETECTBOX &measurement)\n{\n    DETECTBOX mean_pos = measurement;\n    DETECTBOX mean_vel;\n    for(int i = 0; i < 4; i++) mean_vel(i) = 0;\n\n    KAL_MEAN mean;\n    for(int i = 0; i < 8; i++){\n        if(i < 4) mean(i) = mean_pos(i);\n        else mean(i) = mean_vel(i - 4);\n    }\n\n    KAL_MEAN std;\n    std(0) = 2 * _std_weight_position * measurement[3];\n    std(1) = 2 * _std_weight_position * measurement[3];\n    std(2) = 1e-2;\n    std(3) = 2 * _std_weight_position * measurement[3];\n    std(4) = 10 * _std_weight_velocity * measurement[3];\n    std(5) = 10 * _std_weight_velocity * measurement[3];\n    std(6) = 1e-5;\n    std(7) = 10 * _std_weight_velocity * measurement[3];\n\n    KAL_MEAN tmp = std.array().square();\n    KAL_COVA var = tmp.asDiagonal();\n    return std::make_pair(mean, var);\n}\n\nvoid KalmanFilter::predict(KAL_MEAN &mean, KAL_COVA &covariance)\n{\n    //revise the data;\n    DETECTBOX std_pos;\n    std_pos << _std_weight_position * mean(3),\n            _std_weight_position * mean(3),\n            1e-2,\n            _std_weight_position * mean(3);\n    DETECTBOX std_vel;\n    std_vel << _std_weight_velocity * mean(3),\n            _std_weight_velocity * mean(3),\n            1e-5,\n            _std_weight_velocity * mean(3);\n    KAL_MEAN tmp;\n    tmp.block<1,4>(0,0) = std_pos;\n    tmp.block<1,4>(0,4) = std_vel;\n    tmp = tmp.array().square();\n    KAL_COVA motion_cov = tmp.asDiagonal();\n    KAL_MEAN mean1 = this->_motion_mat * mean.transpose();\n    KAL_COVA covariance1 = this->_motion_mat * covariance *(_motion_mat.transpose());\n    covariance1 += motion_cov;\n\n    mean = mean1;\n    covariance = covariance1;\n}\n\nKAL_HDATA KalmanFilter::project(const KAL_MEAN &mean, const KAL_COVA &covariance)\n{\n    DETECTBOX std;\n    std << _std_weight_position * mean(3), _std_weight_position * mean(3),\n            1e-1, _std_weight_position * mean(3);\n    KAL_HMEAN mean1 = _update_mat * mean.transpose();\n    KAL_HCOVA covariance1 = _update_mat * covariance * (_update_mat.transpose());\n    Eigen::Matrix<float, 4, 4> diag = std.asDiagonal();\n    diag = diag.array().square().matrix();\n    covariance1 += diag;\n//    covariance1.diagonal() << diag;\n    return std::make_pair(mean1, covariance1);\n}\n\nKAL_DATA\nKalmanFilter::update(\n        const KAL_MEAN &mean,\n        const KAL_COVA &covariance,\n        const DETECTBOX &measurement)\n{\n    KAL_HDATA pa = project(mean, covariance);\n    KAL_HMEAN projected_mean = pa.first;\n    KAL_HCOVA projected_cov = pa.second;\n\n    //chol_factor, lower =\n    //scipy.linalg.cho_factor(projected_cov, lower=True, check_finite=False)\n    //kalmain_gain =\n    //scipy.linalg.cho_solve((cho_factor, lower),\n    //np.dot(covariance, self._upadte_mat.T).T,\n    //check_finite=False).T\n    Eigen::Matrix<float, 4, 8> B = (covariance * (_update_mat.transpose())).transpose();\n    Eigen::Matrix<float, 8, 4> kalman_gain = (projected_cov.llt().solve(B)).transpose(); // eg.8x4\n    Eigen::Matrix<float, 1, 4> innovation = measurement - projected_mean; //eg.1x4\n    auto tmp = innovation*(kalman_gain.transpose());\n    KAL_MEAN new_mean = (mean.array() + tmp.array()).matrix();\n    KAL_COVA new_covariance = covariance - kalman_gain*projected_cov*(kalman_gain.transpose());\n    return std::make_pair(new_mean, new_covariance);\n}\n\nEigen::Matrix<float, 1, -1>\nKalmanFilter::gating_distance(\n        const KAL_MEAN &mean,\n        const KAL_COVA &covariance,\n        const std::vector<DETECTBOX> &measurements,\n        bool only_position)\n{\n    KAL_HDATA pa = this->project(mean, covariance);\n    if(only_position) {\n        printf(\"not implement!\");\n        exit(0);\n    }\n    KAL_HMEAN mean1 = pa.first;\n    KAL_HCOVA covariance1 = pa.second;\n\n//    Eigen::Matrix<float, -1, 4, Eigen::RowMajor> d(size, 4);\n    DETECTBOXSS d(measurements.size(), 4);\n    int pos = 0;\n    for(DETECTBOX box:measurements) {        \n        d.row(pos++) = box - mean1;\n    }\n    Eigen::Matrix<float, -1, -1, Eigen::RowMajor> factor = covariance1.llt().matrixL();\n    Eigen::Matrix<float, -1, -1> z = factor.triangularView<Eigen::Lower>().solve<Eigen::OnTheRight>(d).transpose();\n    auto zz = ((z.array())*(z.array())).matrix();\n    auto square_maha = zz.colwise().sum();\n    return square_maha;\n}\n\n", "meta": {"hexsha": "9c9fd0d1f73826cfecb26e39a61e66fc3c33d306", "size": 4797, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "track/src/matching/kalmanfilter.cpp", "max_stars_repo_name": "ZhangwenguangHikvision/YoloV5_JDE_TensorRT_for_Track", "max_stars_repo_head_hexsha": "8c2f47b6049a5c4deaa70d4644953f704b768538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 44.0, "max_stars_repo_stars_event_min_datetime": "2021-04-07T06:39:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T18:30:23.000Z", "max_issues_repo_path": "track/src/matching/kalmanfilter.cpp", "max_issues_repo_name": "ZhangwenguangHikvision/YoloV5_JDE_TensorRT_for_Track", "max_issues_repo_head_hexsha": "8c2f47b6049a5c4deaa70d4644953f704b768538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-04-29T15:23:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-17T08:32:30.000Z", "max_forks_repo_path": "KalmanFilter/kalmanfilter.cpp", "max_forks_repo_name": "frankyu-coder/DeepSORT-ssd", "max_forks_repo_head_hexsha": "966a4209b826d7423f371b4e3ae9e5621211a746", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T08:45:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T02:23:17.000Z", "avg_line_length": 31.7682119205, "max_line_length": 115, "alphanum_fraction": 0.6341463415, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24828293525871573}}
{"text": "/*  This file is part of libDAI - http://www.libdai.org/\n *\n *  libDAI is licensed under the terms of the GNU General Public License version\n *  2, or (at your option) any later version. libDAI is distributed without any\n *  warranty. See the file COPYING for more details.\n *\n *  Copyright (C) 2010  Joris Mooij  [joris dot mooij at libdai dot org]\n */\n\n#include <dai/alldai.h>\n#include <fstream>\n#include \"dai/emrun.h\"\n#include <dai/util.h>\n#include <string>\n#include <sys/stat.h>\n#include <time.h>\n#include <iomanip>      // std::setprecision\n#include <sstream>\n#include <cstdlib>\n#include <algorithm>\n#include<math.h>\n#include <string>\n#include <iostream>\n\n#include <boost/lexical_cast.hpp>\n#include <boost/tokenizer.hpp>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/bimap/bimap.hpp>\n#include <boost/bimap/unordered_set_of.hpp>\n#include <boost/bimap/multiset_of.hpp>\n#include <boost/config.hpp>\n#include <boost/bimap.hpp>\n#include <boost/optional.hpp>\n#include <boost/none.hpp>\n#include <boost/foreach.hpp>\n#include <boost/assign/list_inserter.hpp>\nusing namespace std;\nusing namespace dai;\nusing namespace boost;\n// Define a random number generator and initialize it with a reproducible\n// seed.\nmt19937 generator(42);\n\n// Define a uniform random number distribution which produces \"double\"\n// values between 0 and 1 (0 inclusive, 1 exclusive).\nboost::uniform_real<> uni_dist(0,1);\nboost::variate_generator<mt19937&, boost::uniform_real<> > uni(generator, uni_dist);\n\nboost::normal_distribution<> nd(0.0, 1.0);\nboost::variate_generator<mt19937&, boost::normal_distribution<> > normal(generator, nd);\n\n// GA - initialization\nsize_t max_gen = 5; // no. of generations\nsize_t population_size =4; // population size\nReal pc;// = 0.8; // crossover probability - between 0.6 an 0.9\nReal pm;// = 0.3; // mutation probability - between 1/pop.size and 1/chromosome_length\nint population_no=0; // current population id\n\n// 1. Creating initial population of EM runs \nstring alarmfgloc;\nchar* gibbsfile;// = \"/home/priya/libDAI-0.3.1/alarm/500/5.tab\";\nchar* networkname ; //= \"alarm\";\nsize_t maxIters =1000; // maximum number of iterations\nchar* emfile;\nofstream out;\nEMRun* runname;\nvector <EMRun*> layer; \nvector <EMRun*> layer_curr;\nvector <EMRun*> layer_prev;\nvector <EMRun*> layer_parent;\ndai::hash_map<int, FactorGraph> hashmap;\nint *arrval;\n//\n// Generate a random number between 0 and 1\n// return a uniform number in [0,1].\ndouble unifRand()\n{\n    return rand()/double(RAND_MAX);\n}\nvoid initializeEM()\n{\n    size_t i =0,j=0;\n\tcout<<\"Initial start EM\"<<endl;\n\twhile(i<population_size)\n\t{\n        string number;\n        stringstream num;\n        num << i;\n        number = num.str();\n        string dirname;\n        stringstream p_id;\n        p_id << population_no;\n        dirname = p_id.str();\n        string fgfileloc =  alarmfgloc+\"/\"+networkname+\"_\"+number+\".fg\";\n        const char* fgfile = &fgfileloc[0];\n        FactorGraph fg;\n        fg.ReadFromFile(fgfile);\n        runname = new EMRun(networkname, i, fg, gibbsfile,emfile);\n        // 2. Run EM\n        boost::thread threadid(boost::bind(&EMRun::startEM, boost::ref(runname), maxIters));\n        layer.push_back(runname);\n        sleep(1);\n        // 4. Next individual\n        cout<<\" run \"<<i<<\" started\"<<endl;\n        i=i+1;\n    }\n}\nvoid printFactors()\n{\n    vector<EMRun*>::iterator it1;\n    for (int i=0;i<population_size;i++)\n    {\n       FactorGraph fg = hashmap[i];\n    cout<<\"------ Printing ------\"<<i<<endl;\n    for( size_t I = 0; I < fg.nrFactors(); I++ )\n    {\n        Factor P = fg.factor( I );\n        dai::TProb<double> myvector = P.p();\n        for (dai::TProb<double>::iterator it = myvector.begin();it != myvector.end(); ++it)\n            std::cout << ' ' << *it;\n        std::cout << '\\n';\n    }\n    }\n}\nvoid startEM()\n{\n   // printFactors();\n    for (int i=0;i<population_size;i++)\n    {\n        FactorGraph fg = hashmap[i];\n        double runid = i;\n        cout<<\"Starting EM \"<<runid<<endl;\n        runname = new EMRun(networkname, i, fg, gibbsfile,emfile);\n        // 2. Run EM\n        boost::thread threadid(boost::bind(&EMRun::startEM, boost::ref(runname), maxIters));\n        layer.push_back(runname);\n        sleep(1);\n\t}\n\n}\nstd::vector<EMRun*>::iterator compareRuns(std::vector<EMRun*>::iterator *it)\n{\n    if(layer_prev.size() !=0 )\n      {\n        cout<<\" iters = \"<<(**it)->getIters()<<endl;\n        double iters = (**it)->getIters();\n        double val = (**it)->getRun();\n        cout<<\" em run stopped \"<<val<<endl;\n        double ll = (**it)->getLL();\n        vector<EMRun*>::iterator itprev;\n        std::vector<Real> llTraceprev;\n        // get the pervious run\n        \n        for (itprev=layer_prev.begin(); itprev != layer_prev.end(); ++itprev)\n        {\n            double runid = (*itprev)->getRun();\n            if(val==runid)\n            {\n                //out1<<runid<<\" \"<<iters<<\" \";\n                \n                llTraceprev = (*itprev)->lastlog();\n                cout<<val<<\" \"<<\"runid = \"<<(*itprev)->getRun()<<\"  \"<<\" \"<<(*itprev)->getIters()<<endl;\n                break;\n            }\n        }\n        //check if current EM run's LL is greater or equal to prev EM run's LL\n        \n        double llprev;\n        cout<<\" size = \"<<llTraceprev.size()<<endl;\n        if((llTraceprev.size()-1)>iters)\n            llprev = llTraceprev.at(iters);\n        else\n            llprev = llTraceprev.at(llTraceprev.size()-1);\n       // cout<<\" LL for prev run = \"<<llprev<<endl;\n        if(ll>=llprev)\n        {\n            cout<<\" current LL \"<<ll<<\" is good\"<<endl;\n            boost::thread thread7(boost::bind(&EMRun::resumeEM, boost::ref(**it)));\n            cout<<\" em run resumed\"<<val<<endl;\n        }\n        else\n        {\n            cout<<\" current LL \"<<ll<<\" is not good\"<<endl;\n            **it = *itprev;\n            (*itprev)->forceStopped();\n            cout<<\" em run not resumed\"<<val<<endl;\n        }\n        \n    }\n    return *it;\n    ////////////\n}\nvoid checkEMforTermination()\n{\n    layer_prev.assign(layer_curr.begin(), layer_curr.end());\n\tlayer_curr.clear();\n    int i=0;\n\twhile (true){\n\t    //cout<<\"in while loop \"<<layer.size()<<endl;\n        i++;\n\t    vector<EMRun*>::iterator it;\n\t    for (it=layer.begin(); it != layer.end(); ++it){\n//            if((*it)->getIters() > 2*i)\n//            it = compareRuns(&it);\n//            cout<<\" iters = \"<<(*it)->getIters()<<endl;\n//\n\t      //cout<<\"layer size \"<<layer.size()<<endl;\n\t      if((*it)->hasTerminated()) { //if it has terminated, set the run aside\n      \n              double ll = (*it)->getLL();\n              double iters = (*it)->getIters();\n              double runid = (*it)->getRun();\n              //cout<<\"em run \"<<runid<<\" terminated \"<<iters<<endl;\n              std::vector<Real> llTrace = (*it)->lastlog();\n              cout<<\"Run number \"<<runid<<\" ll = \"<<ll<<\" iters = \"<<iters<<endl;\n              InfAlg* inf1 = (*it)->getInf();\n              FactorGraph fg1 = inf1->fg();\n              //cout<<fg1<<endl;\n              sleep(1);\n              out<<pc<<\" \"<<pm<<\" \"<<gibbsfile<<\" \"<<runid<<\" \"<<iters<<\" \"<<ll<<\" \"<<endl;\n              layer_curr.push_back(*it);\n              layer.erase(it);\n              if (layer.size() == 0){break;}\n              else { it = layer.begin(); }\n          }\n            //we stop the run\n        else if(((*it)->getIters()) == maxIters){\n            double ll = (*it)->getLL();\n            double iters = (*it)->getIters();\n            double runid = (*it)->getRun();\n            sleep(1);\t\t\n            //cout<<\"Run number \"<<number<<\" has reached maximum iterations so stopped\"<<endl;\n            //out<<pc<<\" \"<<pm<<\" \"<<gibbsfile<<\" \"<<runid<<\" \"<<iters<<\" \"<<ll<<\" \"<<endl;\n\t\t    layer_curr.push_back(*it);\n            if(!(*it)->isForceStop())\n            {\n                boost::thread thread5(boost::bind(&EMRun::stopEM, boost::ref(*it)));\n                \n            }\n            layer.erase(it);\n            //\tif (layer.size() == 0){break;}\n            //\telse { it = layer.begin(); }\n\t      }\n            \n\t }\n\t if (layer.size() == 0){ //cout<<\"breaking while\"<<endl;\n\t\tbreak; }\n\t else { //cout<<\"iterating\"<<endl;\n\t\t}\n\t  sleep(1); \n\t}\n    layer_parent.assign(layer_curr.begin(), layer_curr.end());\n}\n\nvoid doMutation() // open each child file and apply mutation if required\n{\n    //cout<<\"Mutation Begins\"<<endl;\n    double pmut=0;\n    vector<EMRun*>::iterator it_C;\n    //printFactors();\n    for (it_C=layer_parent.begin(); it_C != layer_parent.end(); ++it_C){\n        double runid = (*it_C)->getRun();\n        InfAlg* inf = (*it_C)->getInf();\n        FactorGraph fg = hashmap[runid];//inf->fg();\n        std::vector<int> mutateFactors;\n        mutateFactors.clear();\n        mutateFactors = (*it_C)->getmutateFactors();\n        int noMutations =0;\n        //cout<<\" Run id \"<<runid;\n        //cout<<\"______\"<<mutateFactors.size()<<endl;\n        cout<<\"Mutation at \";\n        for( size_t I = 0; I < fg.nrFactors(); I++ ) \n            {\n//                std::vector<int>::iterator it;\n//                it = find (mutateFactors.begin(), mutateFactors.end(), I);\n//                if (it != mutateFactors.end())\n//                {\n//                    //std::cout << \"Element found in myvector: \" << *it << '\\n';\n//                    pmut=1;\n//                }\n//                else\n//                {\n//                    //  std::cout << \"Element not found in myvector\\n\";\n//                    pmut=0;\n//                }\n                pmut = uni(); // generates random a value between 0 and 1 for child1\n                //cout<<pmut<<\" \"<<endl;\n                int no_states = fg.factor( I ).nrStates();// total no. of states\n                int no_arr_arrset =0; // factor_states\n                int arr_size =1; //states of parents before factor_pos\n                int arr_set =0; //states of parents after factor_pos\n                int arr_set_states =0; // no. of states till factor_pos\n\n                //cout<<fg.factor( I ).nrStates()<<endl;\n                Factor P = fg.factor( I );\n                VarSet vs = P.vars();\n//                cout<<\"vars = \"<<vs<<endl;\n//                cout << \"{\";\n                for( VarSet::const_iterator v = vs.begin(); v != vs.end(); v++ )\n                {\n                   // cout << (v != vs.begin() ? \", \" : \"\") << *v;\n                    if(v->label()<I)\n                        arr_size = arr_size * v->states();\n                    if(v->label() == I)\n                    {\n                       // cout<<\" states = \"<<v->states()<<endl;\n                        no_arr_arrset = v->states();\n                        arr_set_states = arr_size * v->states();\n                        break;\n                    }\n                }\n                //cout << \"}\"<<endl;\n                arr_set = no_states/arr_set_states;\n                //cout<<\"no. of states \"<<no_states<<\"\\t\"<<\"array set \"<<arr_set<<\"\\t\"<<\"arr_set_states \"<<arr_set_states<<\"\\t\"<<\"no_arr_arrset \"<<no_arr_arrset<<\"\\t\"<<\"array size \"<<arr_size<<endl;\n\n                if(pmut>pm) //do mutation handling the constraint that the states of the random variable sum to 1.\n                {\n                noMutations++;\n                cout<<\" \"<<I;\n                int k=0;\n                while(k<arr_set)\n                {\n                    //Random values are generated---~----~----\n                    std::vector< double * > Arrays1;\n                    for(int l=0; l<no_arr_arrset; l++)\n                    {\n                        Arrays1.push_back( new double[arr_size]);\n                    }\n                    vector<double*>::iterator it;\n                    for(int m=0; m<arr_size; m++)\n                    {\n                        it=Arrays1.begin();\n                        std::vector<double> vec;\n                        for(int i=0; i<no_arr_arrset; i++)\n                        {\n                            vec.push_back(uni());\n                        }\n                        const double total = std::accumulate(vec.begin(), vec.end(), 0.0);\n                        for (double& value: vec)\n                        {\n                            double* arr = *it;\n                            value /= total;\n                            arr[m] = value;\n                            ++it;\n                           // cout<<value <<endl;\n                        }\n                        // cout<<endl;\n                        vec.clear();\n                    }\n                    //Random values are generated---x----x----\n                    //Random or actual values will be updated -----~------~\n                    vector<double*>::iterator it11;\n                    it11=Arrays1.begin();\n                    int stat=0;\n                    for(int l=0; l<no_arr_arrset; l++)\n                    {\n                        double* arr = *it11;\n                        for(int m=0; m<arr_size; m++)\n                        {\n                            stringstream v;\n                            v << fixed << setprecision(12) << arr[m];\n                            //c1<<stat<<\"   \"<<v.str()<<endl;\n                            //cout<< \"replaced\"<<v.str()<<endl;\n                            P.set(stat,arr[m]);\n                            stat++;\n                        }\n                        ++it11;\n                    }\n                    //Random values are updated ------x------x--------\n                    k++;\n                } // end of while\n                } // end of if\n                fg.setFactor(I,P);\n            } // end of factors\n        cout<<\" Total mutations \"<<noMutations<<\" runid \"<<runid<<endl;\n        hashmap[runid]=fg;\n    } // end of factorgraphs\n     //printFactors();\n    //cout<<\"Mutation Done\"<<endl;\n}\n\nvoid doCrossover()\n{\n    //cout<<\"Crossover Begins\"<<endl;\n\t// compute crossover probability\n    double pcross = uni(); // generates random a value between 0 and 1\n\t//cout<<\"Crossover probability \"<<pcross <<endl;\n\t// 4. Select 2 parents randomly\n\tconst int LOW = 0;\n\tconst int HIGH = population_size-1;\n    set<int> myset;\n\tset<int>::iterator it;\n\tsize_t p=0;\n\tarrval = new int[population_size];\n    /*Declare variable to hold seconds on clock.*/\n\ttime_t seconds;\n\t/*Get value from system clock and place in seconds variable.*/\n\ttime(&seconds);\n\t/*Convert seconds to a unsigned integer.*/\n\tsrand(time(0));\n   \n    for (int n=0;n<population_size;n++)\n    {\n        int val = rand() % (HIGH - LOW + 1) + LOW;\n        it=myset.find(val);\n        arrval[n] = val;\n        if(it==myset.end()) // if the value is not in the set\n        {\n            myset.insert(val);\n            p++;\n            if(p == 2)\n            {\n               // cout <<\" Random value is\"<<arrval[n]<<\" and \"<< arrval[n-1];\n                EMRun* r1 = layer_parent.at(n);\n                EMRun* r2 = layer_parent.at(n-1);\n                double runid = (r1)->getRun();\n                InfAlg* inf = (r1)->getInf();\n                FactorGraph fg = inf->fg();\n                double runid1 = (r2)->getRun();\n                InfAlg* inf1 = (r2)->getInf();\n                FactorGraph fg1 = inf1->fg();\n                // randomly select a crossover point\n                int cr_pt = (rand() % fg.nrVars());\n               // cout<<\" Crossover point is \"<< cr_pt<<endl;\n                p=0;\n                if(pcross>pc)\n                {\n                for( size_t I = cr_pt; I < fg.nrFactors(); I++ )\n                {\n                    Factor P = fg.factor( I );\n                    dai::TProb<double> myvector = P.p();\n                    Factor P1 = fg1.factor( I );\n                    dai::TProb<double> myvector1 = P1.p();\n                    dai::TProb<double>::iterator it1 = myvector1.begin();\n                    dai::TProb<double>::iterator it = myvector.begin();\n                    for (int state=0;state<myvector.size();state++)\n                    {\n                        P.set(state,*it1);\n                        P1.set(state,*it);\n                        ++it1;++it;\n                    }\n                    fg.setFactor(I,P);\n                    fg1.setFactor(I,P1);\n                }\n                }\n                int val = arrval[n];int val1 = arrval[n-1];\n                hashmap[val]=fg;\n                hashmap[val1]=fg1;\n            }\n        }\n        else\n        {\n            n=n-1;\n            continue;\n        }\n    }\n    //cout<<\"Crossover Done\"<<endl;\n    //printFactors();\n\n}\n\nvoid replacementStrategy()\n{\n //cout<<\"In replacement strategy\"<<endl;\n double ll, ll1;\n string ssiters,ssiters1,ssll1,ssll,ssrunid, ssrunid1;\n layer_parent.clear();\n for( size_t n = 0; n < population_size; n++ )\n {\n\tint val = arrval[n];\n\t//cout<<\"val = \"<<val<<endl;\n\tvector<EMRun*>::iterator it, it1; \n\tint i=0;\n\tfor (it=layer_prev.begin(); it != layer_prev.end(); ++it)\n    {    \t   \n\t      ll = (*it)->getLL();\n\t      double iters = (*it)->getIters();\n\t      double runid = (*it)->getRun();\n\t      stringstream sll;\n\t      stringstream siters;\t \n              stringstream srunid;\t      \n\t      sll<<ll; ssll = sll.str();\n\t      siters <<iters; ssiters = siters.str();\n\t      srunid <<runid; ssrunid = srunid.str();\n\t     // cout<<\"runid = \"<<ssrunid<<\"  \"<<ssll<<\" \"<<ssiters<<endl;\n\t      if(val==runid)\n\t      {\n              //out1<<runid<<\" \"<<iters<<\" \";\n            //  cout<<val<<\" \"<<\"runid = \"<<ssrunid<<\"  \"<<ssll<<\" \"<<ssiters<<endl;\n              break;\n\t      }\t\n\t}\n    for (it1=layer_curr.begin(); it1 != layer_curr.end(); ++it1)\n    {    \t   \n\t      ll1 = (*it1)->getLL();\n\t      double iters1 = (*it1)->getIters();\n\t      double runid1 = (*it1)->getRun();\n              stringstream sll1;\n              stringstream siters1;\t \n              stringstream srunid1;\n\t      sll1<<ll1; ssll1 = sll1.str();\t      \n\t      siters1 <<iters1; ssiters1 = siters1.str();\n\t      srunid1 <<runid1; ssrunid1 = srunid1.str();\n\t     // cout<<\"runid = \"<<ssrunid1<<\"  \"<<ssll1<<\" \"<<ssiters1<<endl;\n\t      if(val==runid1)\n\t      {\n             // out1<<runid1<<\" \"<<iters1<<\" \";\n             // cout<<val<<\" \"<<\"runid = \"<<ssrunid1<<\"  \"<<ssll1<<\" \"<<ssiters1<<endl;\n              break;\n\t      }\t\n\t      i++;\n\t}\n\tif(ll<=ll1)\n\t{\n\t\t//cout<<\"Child  has a better LL so leave the child as it is.\"<<endl;\n        out<<population_no<<\"  \"<<ssrunid1<<\"  \"<<ssll1<<\" \"<<ssiters1<<endl;\n\t}\t\n\telse\n\t{\n       // cout<<\"Replace child with parent.\"<<endl;\n        out<<population_no<<\"  \"<<ssrunid<<\"  \"<<ssll<<\" \"<<ssiters<<endl;\n\t\t*it1=*it; //replacing the object in the layer_curr vector\n        \n\t}\n  }\n  layer_parent.assign(layer_curr.begin(), layer_curr.end());\n\n}\n\nint main(int argc, char *argv[]) {\n    generator.seed(static_cast<unsigned int>(std::time(0)));\n \n    gibbsfile = argv[1];\n    stringstream ss2(argv[2]);\n    alarmfgloc = ss2.str();\n    istringstream ss( argv[3] );\n    ss >> pm;\n    stringstream ss1( argv[4] );\n    ss1 >> pc;\n    const char* fname =argv[5];\n    networkname = argv[6];\n    emfile = argv[7];\n    out.open(fname);\n\n    time_t timer1, timer2;\n    time(&timer1);\n    clock_t tStart = clock();\n    \n    initializeEM();\n    \n    cout<<\"population no\"<<population_no<<endl;\n    while(population_no<max_gen)\n    {\n          checkEMforTermination();\n         if(population_no>0)\n            replacementStrategy();\n          doCrossover();\n          doMutation();\n          startEM();\n          population_no=population_no+1;\n          cout<<\"population no\"<<population_no<<endl;\n   }\n \n    time(&timer2);\n    double t = difftime(timer2,timer1);\n    double t_c = (clock() - tStart)/CLOCKS_PER_SEC;\n    out<<\"Time taken: \"<<t<<\"s\"<<endl;\n    out<<\" Processor Time taken: \"<<t_c<<\"s\"<<endl;\n    out.close();\n    return 0;\n}\n\n", "meta": {"hexsha": "13bc7474125315fec3edb2188266ced52f07fd83", "size": 20048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example_gaem_deterministic.cpp", "max_stars_repo_name": "Priyaaks/libDAI_P", "max_stars_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/example_gaem_deterministic.cpp", "max_issues_repo_name": "Priyaaks/libDAI_P", "max_issues_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_gaem_deterministic.cpp", "max_forks_repo_name": "Priyaaks/libDAI_P", "max_forks_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5655172414, "max_line_length": 198, "alphanum_fraction": 0.4936153232, "num_tokens": 4998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878414043816, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2482290649264493}}
{"text": "#include <stdlib.h>\n#include <iostream>\n#include <thread>\n#include <string>\n#include <cmath>\n\n#include <inttypes.h>\n\n#include <boost/tr1/random.hpp>\n#include \"utils.h\"\n\n#include \"WordEmbed.h\"\n\n#define EXP_TABLE_SIZE 1000\n#define MAX_EXP 6\n#define MAX_CODE_LENGTH 40\n#define MAX_SENTENCE_LENGTH 1000\n\nclass Word2Vec : public WordEmbed {\n    private:\n        unsigned int layer1_size;\n        int window;\n        real sample;\n        int hs, negative;\n        unsigned int num_threads;\n        unsigned int iter;\n        real alpha;\n        unsigned int classes;\n        int  cbow;\n        std::string wordvector_file;\n\n        int64_t word_count_actual;\n\n        real starting_alpha;\n\n        std::array<real,(EXP_TABLE_SIZE + 1)> expTable;\n\n        clock_t start;\n\n        std::vector<real> syn0, syn1, syn1neg;\n\n        // Tables\n        std::array<int, table_size> table;\n    public:\n        Word2Vec (             \n                std::string train_file, //Use text data from <file> to train the model\n                std::string output_file = \"\", //Use <file> to save the resulting word vectors / word clusters\n                unsigned int min_count = 5, //This will discard words that appear less than <int> times; default is 5\n                int debug_mode = 2, //Set the debug mode (default = 2 = more info during training)\n                int binary = 0, //Save the resulting vectors in binary moded; default is 0 (off)\n                std::string save_vocab_file = \"\", //The vocabulary will be saved to <file>\n                std::string read_vocab_file = \"\", //The vocabulary will be read from <file>, not constructed from the training data\n                unsigned int layer1_size = 100, //Set size of word vectors; default is 100\n                unsigned int window = 5, //Set max skip length between words; default is 5\n                real sample = 1e-3, //Set threshold for occurrence of words. Those that appear with higher frequency in the training data will be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5) \n                int hs = 0, //Use Hierarchical Softmax; default is 0 (not used)\n                int negative = 5, //Number of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n                unsigned int num_threads = 12, //Use <int> threads (default 12)\n                int iter = 5, //Run more training iterations (default 5)\n                real alpha = 0.05, //Set the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n                unsigned int classes = 0,//Output word classes rather than word vectors; default number of classes is 0 (vectors are written)\n                int cbow = 0, //Use the continuous bag of words model; default is 1 (use 0 for skip-gram model)\n                std::string wordvector_file = \"\" //Read the trained word vector file\n                ):\n            WordEmbed (train_file, output_file, min_count, debug_mode, binary,save_vocab_file,read_vocab_file),\n            layer1_size (layer1_size),\n            window (window),\n            sample (sample),\n            hs (hs),\n            negative (negative),\n            num_threads (num_threads),\n            iter (iter),\n            alpha (alpha),\n            classes (classes),\n            cbow (cbow),\n            wordvector_file (wordvector_file)\n        {\n            min_reduce = 1, \n            vocab_size = 0;\n            train_words = 0;\n            word_count_actual=0;\n            file_size = 0;\n\n            ready_to_train = false;\n            if( CheckReady() ) ready_to_train = true;\n        };\n        \n        void TrainModel ();\n\n        void CreateBinaryTree ();\n\n        void InitUnigramTable ();\n        void InitNet ();\n        void TrainModelThread (int tid);\n};\n\n//vocab cn word codelen point code\n\n// Create binary Huffman tree using the word counts\n// Frequent words will have short unique binary codes\nvoid Word2Vec::CreateBinaryTree() {\n    // Words are not sorted at the beginning\n    int64_t a, b, i, min1i, min2i, pos1, pos2;\n    int64_t point[MAX_CODE_LENGTH];\n    char code[MAX_CODE_LENGTH];\n\n    std::vector<int64_t> count;\n    std::vector<int64_t> binary;\n    std::vector<int64_t> parent_node;\n\n    count.reserve(vocab_size * 2 + 1);\n    binary.reserve(vocab_size * 2 + 1);\n    parent_node.reserve(vocab_size * 2 +1);\n\n    for(a = 0; a < vocab_size; a++) count[a] = vocab[a].cn; // count word frequency\n    for(a = vocab_size; a < 2 * vocab_size; a++) count[a] = 1e15; // should be larger than any number in the vocabulary count \n    pos1 = vocab_size - 1;\n    pos2 = vocab_size; //\n\n    // following algorithm constructs the Huffman tree by adding one node at a time\n    for(a = 0; a < vocab_size - 1; a++) {\n        // First, find two smallest nodes 'min1, min2'\n        if(pos1 >= 0) {\n            if(count[pos1] < count[pos2]) {\n                min1i = pos1;\n                pos1--;\n            } else {\n                min1i = pos2;\n                pos2++;\n            }\n        } else {\n            min1i = pos2;\n            pos2++;\n        }\n        if(pos1 >= 0) {\n            if(count[pos1] < count[pos2]) {\n                min2i = pos1;\n                pos1--;\n            } else {\n                min2i = pos2;\n                pos2++;\n            }\n        } else {\n            min2i = pos2;\n            pos2++;\n        }\n        count[vocab_size + a] = count[min1i] + count[min2i]; // Creating parent node with summed frequency\n        parent_node[min1i] = vocab_size + a;\n        parent_node[min2i] = vocab_size + a; // Note that having a common parent node\n        binary[min2i] = 1; // min2i will point to root node at the final state\n    }\n    // Now assign binary code to each vocabulary word\n    for(a = 0; a < vocab_size; a++) {\n        b = a;\n        i = 0;\n        while(1) {\n            code[i] = binary[b];\n            point[i] = b;\n            i++;\n            b = parent_node[b];\n            if(b == vocab_size * 2 - 2) break;\n        }\n        vocab[a].codelen = i;\n        vocab[a].point[0] = vocab_size - 2;\n        for(b = 0; b < i; b++) {\n            vocab[a].code[i - b - 1] = code[b];\n            vocab[a].point[i - b] = point[b] - vocab_size;\n        }\n    }\n}\n\n// Begin of Learning Net\n\nvoid Word2Vec::InitUnigramTable() {\n    unsigned int i;\n    double train_words_pow = 0;\n    double d1, power = 0.75;\n    int64_t sum = 0;\n    for (unsigned int a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power);\n    for (unsigned int a = 0; a < vocab_size; a++) sum += vocab[a].cn;\n    std::cout << sum << std::endl;\n    i = 0;\n    d1 = pow(vocab[i].cn, power) / train_words_pow;\n    for (unsigned int a = 0; a < table_size; a++) {\n        table[a] = i;\n        if (a / (double)table_size > d1) {\n            i++;\n            d1 += pow(vocab[i].cn, power) / train_words_pow;\n        }\n        if (i >= vocab_size) i = vocab_size - 1;\n    }\n}\n\nvoid Word2Vec::InitNet() {\n    // The name EXP_TABLE is totally mis-guiding.\n    for (int i = 0; i < EXP_TABLE_SIZE; i++) {\n        expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP);\n        expTable[i] = expTable[i] / (expTable[i] + 1);\n    }\n\n    syn0.reserve((int64_t)vocab_size * layer1_size);\n    if(hs) {\n        syn1.reserve((int64_t)vocab_size * layer1_size);\n        for(unsigned int a = 0; a < vocab_size; a++)\n            for(unsigned int b = 0; b < layer1_size; b++)\n                syn1[a * layer1_size + b] = 0;\n    }\n    if(negative > 0) {\n        syn1neg.reserve((int64_t)vocab_size * layer1_size);\n        for(unsigned int a = 0; a < vocab_size; a++)\n            for(unsigned int b = 0; b < layer1_size; b++)\n                syn1neg[a * layer1_size + b] = 0;\n    }\n\n    for(unsigned int a = 0; a < vocab_size; a++)\n        for(unsigned int b = 0; b < layer1_size; b++)\n            syn0[a * layer1_size + b] = (rand()/(double)RAND_MAX - 0.5) / layer1_size;\n\n    \n    //CreateBinaryTree();\n}\n\nvoid Word2Vec::TrainModelThread(int tid){\n    int64_t a, b, d, word, last_word, sentence_length = 0, sentence_position = 0;\n    int64_t word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1];\n    int64_t l1, l2, c, target, label, local_iter = iter;\n    uint64_t next_random;\n    real f, g;\n    clock_t now;\n\n    boost::mt19937 rand_engine_int;    // rand engine\n    boost::uniform_int<> rand_int(0, table_size);    // set range.\n    boost::variate_generator<boost::mt19937, boost::uniform_int<>> rand_gen_int(rand_engine_int, rand_int);\n\n    boost::mt19937 rand_engine_double;  // rand engine\n    boost::uniform_real<> rand_double(0.0, 1.0);\n    boost::variate_generator<boost::mt19937, boost::uniform_real<>> rand_gen_double(rand_engine_double, rand_double);\n    \n    std::vector<real> neu1;\n    std::vector<real> neu1e;\n\n    neu1.reserve(layer1_size);\n    neu1e.reserve(layer1_size);\n\n    std::ifstream inFile(train_file, std::ifstream::in | std::ifstream::binary);\n    inFile.seekg(file_size / (int64_t)num_threads * (int64_t)tid);\n    while(1) {\n        if(word_count - last_word_count > 10000) {\n            word_count_actual += word_count - last_word_count;\n            last_word_count = word_count;\n            if((debug_mode > 1)) {\n                now = clock();\n                printf(\"%cAlpha: %f  Progress: %.2f%%  Words/thread/sec: %.2fk   \", 13, alpha,\n                        word_count_actual / (real)(iter * train_words + 1) * 100,\n                        word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));\n                fflush(stdout);\n            }\n            alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1));\n            if(alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001;\n        }\n        if(sentence_length == 0) { \n            while(1) {\n                word = ReadWordIndex(inFile);\n                if(inFile.eof()) break;\n                if(word == -1) continue;\n                word_count++;\n                if(word == 0) break;\n                // The subsampling randomly discards frequent words while keeping the ranking same\n                if(sample > 0) {\n                    real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn;\n                    if(ran < rand_gen_double()) continue;\n                }\n                sen[sentence_length] = word;\n                sentence_length++;\n                if(sentence_length >= MAX_SENTENCE_LENGTH) break;\n            }\n            sentence_position = 0;\n        }\n        if(inFile.eof() || (word_count > train_words / num_threads )) {\n            word_count_actual += word_count - last_word_count;\n            local_iter--;\n            if(local_iter == 0) break;\n            word_count = 0;\n            last_word_count = 0;\n            sentence_length = 0;\n\t    if(inFile.eof()) {\n\t      inFile.clear();\n\t      inFile.seekg(file_size / (int64_t)num_threads * (int64_t)tid);\n\t    }\n\t    else {\n\t      inFile.seekg(file_size / (int64_t)num_threads * (int64_t)tid);\n\t    }\n            continue;\n        }\n        word = sen[sentence_position];\n        if(word == -1) continue;\n        // Network Initialization\n        for(c = 0; c < layer1_size; c++) neu1[c] = 0;\n        for(c = 0; c < layer1_size; c++) neu1e[c] = 0;\n        \n        b = rand_gen_int() % window;\n        // Skip-gram\n        {\n            for(a = b; a < window * 2 + 1 - b; a++) if(a != window) {\n                c = sentence_position - window + a;\n                if(c < 0) continue;\n                if(c >= sentence_length) continue;\n                last_word = sen[c];\n                if(last_word == -1) continue;\n                l1 = last_word * layer1_size;\n                // Hierarchical Softmax\n                if(hs) for(d = 0; d < vocab[word].codelen; d++) {\n                    f = 0;\n                    l2 = vocab[word].point[d] * layer1_size;\n                    // Propagate hidden -> output\n                    for(c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1[c + l2];\n                    if(f <= -MAX_EXP) continue;\n                    else if(f >= MAX_EXP) continue;\n                    else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];\n                    // g is the gradient multiplied by the learning rate\n                    g = (1 - vocab[word].code[d] - f) * alpha;\n                    // Backpropagate errors output -> hidden\n                    for(c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2];\n                    // Learn weights hidden -> output\n                    for(c = 0; c < layer1_size; c++) syn1[c + l2] += g * syn0[c +l1];\n                }\n                // Negative Sampling\n                if(negative > 0) for (d = 0; d < negative + 1 ; d++) {\n                    if(d == 0) {\n\t\t      target = word;\n\t\t      label = 1;\n                    } else {\n\t\t      next_random = rand_gen_int();\n\t\t      target = table[next_random % table_size];\n\t\t      if(target == 0) target = next_random % (vocab_size - 1) + 1;\n\t\t      if(target == word) continue;\n\t\t      label = 0;\n                    }\n                    l2 = target * layer1_size;\n                    f = 0;\n                    for(c = 0; c < layer1_size; c++) f += syn0[c + l1] * syn1neg[c + l2];\n                    if(f > MAX_EXP) g = (label - 1) * alpha;\n                    else if(f < -MAX_EXP) g = (label - 0) * alpha;\n                    else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha;\n                    for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2];\n                    for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * syn0[c + l1];\n                }\n                // Learn weights input -> hidden\n                for(c = 0; c < layer1_size; c++) syn0[c + l1] += neu1e[c];\n            }\n        }\n        sentence_position++;\n        if(sentence_position >= sentence_length) {\n            sentence_length = 0;\n            continue;\n        }\n    }\n    inFile.close();\n}\n\nvoid Word2Vec::TrainModel() {\n    std::ofstream outFile;\n\n    std::vector<std::thread> th;\n    starting_alpha = alpha;\n\n    std::cout << \"Starting training using file \" << train_file << std::endl;\n    if(read_vocab_file != \"\") ReadVocab();\n    else ExtractVocabFromTrainFile();\n    if(save_vocab_file != \"\") SaveVocab();\n    if(output_file[0] == 0) return;\n\n    // Initialization\n    InitNet();\n    if(negative > 0)\n        InitUnigramTable();\n\n    start = clock(); // start to measure time\n\n    for(int i = 0; i < num_threads; i++) {\n      th.push_back(std::thread(&Word2Vec::TrainModelThread, this, i));\n    }\n\n    for(auto &t : th) {\n      t.join();\n    }\n\n    //TrainModelThread(); // For the single thread\n\n    outFile.open(output_file, std::ofstream::out | std::ofstream::binary);\n    if(classes == 0) {\n        outFile << vocab_size << \" \" << layer1_size << std::endl;\n        for(unsigned int a = 0; a < vocab_size; a++) {\n            outFile << vocab[a].word << \" \";\n            if(binary) for(unsigned int b = 0; b < layer1_size; b++) outFile << syn0[a * layer1_size + b] << \" \";\n            else for(unsigned int b = 0; b < layer1_size; b++) outFile << syn0[a * layer1_size + b] << \" \";\n            outFile << std::endl;\n        }\n    } else {\n        // Run K-means on the word vectors\n        unsigned int clcn = classes, iter = 10, closeid;\n        real closev, x;\n\n        std::vector<int> centcn, cl;\n        std::vector<real> cent;\n\n        centcn.reserve(classes);\n        cl.reserve(vocab_size);\n        cent.reserve(classes * layer1_size);\n\n        for (unsigned int a = 0; a < vocab_size; a++) cl[a] = a % clcn;\n        for (unsigned int a = 0; a < iter; a++) {\n            for (unsigned int b = 0; b < clcn * layer1_size; b++) cent[b] = 0;\n            for (unsigned int b = 0; b < clcn; b++) centcn[b] = 1;\n            for (unsigned int c = 0; c < vocab_size; c++) {\n                for (unsigned int d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d];\n                centcn[cl[c]]++;\n            }\n            for (unsigned int b = 0; b < clcn; b++) {\n                closev = 0;\n                for (unsigned int c = 0; c < layer1_size; c++) {\n                    cent[layer1_size * b + c] /= centcn[b];\n                    closev += cent[layer1_size * b + c] * cent[layer1_size * b + c];\n                }\n                closev = sqrt(closev);\n                for (unsigned int c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev;\n            }\n            for (unsigned int c = 0; c < vocab_size; c++) {\n                closev = -10;\n                closeid = 0;\n                for (unsigned int d = 0; d < clcn; d++) {\n                    x = 0;\n                    for (unsigned int b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b];\n                    if (x > closev) {\n                        closev = x;\n                        closeid = d;\n                    }\n                }\n                cl[c] = closeid;\n            }\n        }\n        // Save the K-means classes\n        for (unsigned int a = 0; a < vocab_size; a++) outFile << vocab[a].word << \"    \" << cl[a] << std::endl;\n\n    }\n    outFile.close();\n}\n\n// End of Learning Net\n\n\n// main function arguments\n\nvoid printHelp() {\n    std::cout << \"c++ word2vector implementation \\n\\n\";\n    std::cout << \"Options:\\n\";\n    std::cout << \"Parameters for training:\\n\";\n    std::cout << \"\\t-train <file>\\n\";\n    std::cout << \"\\t\\tUse text data from <file> to train the model\\n\";\n    std::cout << \"\\t-output <file>\\n\";\n    std::cout << \"\\t\\tUse <file> to save the resulting word vectors / word clusters\\n\";\n    std::cout << \"\\t-size <int>\\n\";\n    std::cout << \"\\t\\tSet size of word vectors; default is 100\\n\";\n    std::cout << \"\\t-window <int>\\n\";\n    std::cout << \"\\t\\tSet max skip length between words; default is 5\\n\";\n    std::cout << \"\\t-sample <float>\\n\";\n    std::cout << \"\\t\\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\\n\";\n    std::cout << \"\\t\\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\\n\";\n    std::cout << \"\\t-hs <int>\\n\";\n    std::cout << \"\\t\\tUse Hierarchical Softmax; default is 0 (not used)\\n\";\n    std::cout << \"\\t-negative <int>\\n\";\n    std::cout << \"\\t\\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\\n\";\n    std::cout << \"\\t-threads <int>\\n\";\n    std::cout << \"\\t\\tUse <int> threads (default 12)\\n\";\n    std::cout << \"\\t-iter <int>\\n\";\n    std::cout << \"\\t\\tRun more training iterations (default 5)\\n\";\n    std::cout << \"\\t-min-count <int>\\n\";\n    std::cout << \"\\t\\tThis will discard words that appear less than <int> times; default is 5\\n\";\n    std::cout << \"\\t-alpha <float>\\n\";\n    std::cout << \"\\t\\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\\n\";\n    std::cout << \"\\t-classes <int>\\n\";\n    std::cout << \"\\t\\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\\n\";\n    std::cout << \"\\t-debug <int>\\n\";\n    std::cout << \"\\t\\tSet the debug mode (default = 2 = more info during training)\\n\";\n    std::cout << \"\\t-binary <int>\\n\";\n    std::cout << \"\\t\\tSave the resulting vectors in binary moded; default is 0 (off)\\n\";\n    std::cout << \"\\t-save-vocab <file>\\n\";\n    std::cout << \"\\t\\tThe vocabulary will be saved to <file>\\n\";\n    std::cout << \"\\t-read-vocab <file>\\n\";\n    std::cout << \"\\t\\tThe vocabulary will be read from <file>, not constructed from the training data\\n\";\n    std::cout << \"\\t-cbow <int>\\n\";\n    std::cout << \"\\t\\tUse the continuous bag of words model; default is 1 (use 0 for skip-gram model)\\n\";\n    std::cout << \"\\t-wordvector <file>\\n\";\n    std::cout << \"\\t\\tRead the trained word vector file\\n\";\n    std::cout << \"\\nExamples:\\n\";\n    std::cout << \"./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1 -iter 3\\n\\n\";\n\n}\n\nint argpos(const char *str, int argc, char **argv) {\n    std::string s_str(str);\n    std::vector<std::string> s_argv(argv,argv+argc);\n\n    int i=0;\n    while (i<argc) {\n        if(s_str == s_argv[i]) break;\n        i++;\n    }\n    if(i == argc) i=0;\n\n    return i;\n}\n\nWord2Vec *arg_to_w2v(int argc, char **argv) {\n    int i;\n\n    int layer1_size = 100;\n    std::string train_file =\"\", save_vocab_file = \"\", read_vocab_file = \"\";\n    int debug_mode =2, binary = 0, cbow = 0; \n    real alpha = 0.05;\n    std::string output_file = \"\";\n    int window = 5;\n    real sample = 1e-3;\n    int hs = 0, negative = 5, num_threads = 12;\n    int64_t iter = 5;\n    int min_count = 5;\n    int64_t classes = 0;\n    std::string wordvector_file = \"\";\n\n    if ((i = argpos(\"-size\", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]);\n    if ((i = argpos(\"-train\", argc, argv)) > 0) train_file = argv[i + 1];\n    if ((i = argpos(\"-save-vocab\", argc, argv)) > 0) save_vocab_file = argv[i + 1];\n    if ((i = argpos(\"-read-vocab\", argc, argv)) > 0) read_vocab_file = argv[i + 1];\n    if ((i = argpos(\"-debug\", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]);\n    if ((i = argpos(\"-binary\", argc, argv)) > 0) binary = atoi(argv[i + 1]);\n    if ((i = argpos(\"-cbow\", argc, argv)) > 0) cbow = atoi(argv[i + 1]);\n    if (cbow) alpha = 0.05; else alpha = 0.025;\n    if ((i = argpos(\"-alpha\", argc, argv)) > 0) alpha = atof(argv[i + 1]);\n    if ((i = argpos(\"-output\", argc, argv)) > 0) output_file = argv[i + 1];\n    if ((i = argpos(\"-window\", argc, argv)) > 0) window = atoi(argv[i + 1]);\n    if ((i = argpos(\"-sample\", argc, argv)) > 0) sample = atof(argv[i + 1]);\n    if ((i = argpos(\"-hs\", argc, argv)) > 0) hs = atoi(argv[i + 1]);\n    if ((i = argpos(\"-negative\", argc, argv)) > 0) negative = atoi(argv[i + 1]);\n    if ((i = argpos(\"-threads\", argc, argv)) > 0) num_threads = atoi(argv[i + 1]);\n    if ((i = argpos(\"-iter\", argc, argv)) > 0) iter = atoi(argv[i + 1]);\n    if ((i = argpos(\"-min-count\", argc, argv)) > 0) min_count = atoi(argv[i + 1]);\n    if ((i = argpos(\"-classes\", argc, argv)) > 0) classes = atoi(argv[i + 1]);\n    if ((i = argpos(\"-wordvector\", argc, argv)) > 0) wordvector_file = argv[i + 1];\n\n    Word2Vec *w2v = new Word2Vec (             \n                train_file, \n                output_file, \n                min_count, \n                debug_mode, \n                binary, \n                save_vocab_file, \n                read_vocab_file, \n                layer1_size, \n                window, \n                sample, \n                hs, \n                negative, \n                num_threads, \n                iter, \n                alpha, \n                classes,\n                cbow, \n                wordvector_file );\n\n    return w2v;\n}\n\nint main(int argc, char **argv) {\n\n    std::srand(11596521);\n    Word2Vec *w2v;\n\n    if(argc < 2) { printHelp(); return 1; }\n    else {\n        w2v = arg_to_w2v(argc, argv);\n    }\n\n    w2v->TrainModel();\n\n    return 0;\n}\n", "meta": {"hexsha": "aa20c13771497d03c19f6317876b9bc0f26d3e3b", "size": 22987, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "word2vec/word2vec.cpp", "max_stars_repo_name": "uphere-co/nlp-prototype", "max_stars_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "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": "word2vec/word2vec.cpp", "max_issues_repo_name": "uphere-co/nlp-prototype", "max_issues_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "word2vec/word2vec.cpp", "max_forks_repo_name": "uphere-co/nlp-prototype", "max_forks_repo_head_hexsha": "c4623927e5c5c5f9c3e702eb36497ea1d9fd1ff3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1601362862, "max_line_length": 212, "alphanum_fraction": 0.5286901292, "num_tokens": 6373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24797007252647155}}
{"text": "/*\n * Aircraft.cpp\n *\n *  Created on: 11-Jul-2008\n *      Author: malem303\n */\n\n#include \"Aircraft.h\"\n#include \"Constants.h\"\n#include \"Utils.h\"\n#include \"ControlRigging.h\"\n#include \"AircraftFactory.h\"\n\n#include <math.h>\n#include <boost/numeric/ublas/storage.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <list>\n\nAircraft::Aircraft(bool usePhi) : usePhi(usePhi)\n{\n\tatmosphericConditions = new AtmosphericConditions();\n\tcenterOfGravity = AircraftFactory::createCenterOfGravity(Utils::toVec3(10, 0, 5), Constants::ZERO_VEC_3, Constants::ZERO_VEC_3, Constants::ZERO_VEC_3);\n    fuselage = AircraftFactory::createFuselage();\n\thorizontalStabilizer = AircraftFactory::createHorizontalStabilizer();\n\tverticalStabilizer = AircraftFactory::createVerticalStabilizer();\n\tmainRotor = AircraftFactory::createMainRotor();\n\ttailRotor = AircraftFactory::createTailRotor();\n}\n\nAircraft::~Aircraft() {\n\n\tdelete atmosphericConditions;\n\tdelete fuselage;\n\tdelete mainRotor;\n\tdelete tailRotor;\n\tdelete horizontalStabilizer;\n\tdelete verticalStabilizer;\n\tdelete centerOfGravity;\n}\nvoid Aircraft::updateControls(double collectivePitchStickPosition, double longitudinalSwashplateStickPosition, double lateralSwashplateStickPosition, double tailRotorCollectivePitchStick)\n{\n\tmainRotor->setCollectivePitchStickPosition(collectivePitchStickPosition);\n\tmainRotor->setLongitudinalSwashplateStickPosition(longitudinalSwashplateStickPosition);\n\tmainRotor->setLateralSwashplateStickPosition(lateralSwashplateStickPosition);\n\ttailRotor->setCollectivePitchStickPosition(tailRotorCollectivePitchStick);\n}\n\nvoid Aircraft::updatePhysics()\n{\n\n\tupdateAtmosphericConditions();\n\n\tcenterOfGravity->resetForces();\n\tcenterOfGravity->updateVelocities();\n\n\n\tfuselage->updatePhysics(*centerOfGravity, atmosphericConditions->getDensity());\n\n\n\thorizontalStabilizer->updatePhysics(*centerOfGravity, atmosphericConditions->getDensity());\n\n\n\tverticalStabilizer->updatePhysics(*centerOfGravity, atmosphericConditions->getDensity());\n\n\n\tmainRotor->updatePhysics(*centerOfGravity, atmosphericConditions->getDensity());\n\n\n\ttailRotor->updatePhysics(*centerOfGravity, atmosphericConditions->getDensity());\n\n\tupdateWashVelocities();\n\n\n\n\tcenterOfGravity->addGravityForces();\n\n\n}\n\nvoid Aircraft::updateWashVelocities()\n{\n\t// TODO : find a less hard-coded way to compute that\n\n\n\n\t// Mutual influences :\n\n\n\tdouble density = atmosphericConditions->getDensity();\n\tvector<double> externalWashAgularVelocity = Constants::ZERO_VEC_3;\n\tvector<double> externalWashVelocity(3);\n\n\n\t// mainRotor on fuselage\n\texternalWashVelocity = mainRotor->computeExternalWashInfluence(fuselage, density);\n\tfuselage->updtateWashVelocities(density, externalWashVelocity, externalWashAgularVelocity);\n\n\t// fuselage on mainRotor\n\tvector<double> fuselageSelfInducedWashVelocity = fuselage->computeSelfInducedWashVelocity(density);\n\n\texternalWashVelocity = \tUtils::toVec3(0.0, 0.0, fuselageSelfInducedWashVelocity(2));\n\tmainRotor->updtateWashVelocities(density, externalWashVelocity, externalWashAgularVelocity);\n\n\t// mainRotor and fuselage on horizontalStabilizer\n\texternalWashVelocity = mainRotor->computeExternalWashInfluence(horizontalStabilizer, density) + Utils::toVec3(fuselageSelfInducedWashVelocity(0), 0.0, 0.0);\n\thorizontalStabilizer->updtateWashVelocities(density, externalWashVelocity, externalWashAgularVelocity);\n\n\t// verticalStabilizer on tailRotor\n\tvector<double> verticalStabilizerSelfInducedVelocity = verticalStabilizer->computeSelfInducedWashVelocity(density);\n\n\texternalWashVelocity = \tUtils::toVec3(0.0, verticalStabilizerSelfInducedVelocity(1), 0.0);\n\ttailRotor->updtateWashVelocities(density, externalWashVelocity, externalWashAgularVelocity);\n\n\t// tailRotor on verticalStabilizer\n\tvector<double> tailRotorSelfInducedWashVelocity = tailRotor->computeSelfInducedWashVelocity(density);\n\n\texternalWashVelocity = \tUtils::toVec3(0.0, tailRotorSelfInducedWashVelocity(1), 0.0);\n\tverticalStabilizer->updtateWashVelocities(density, externalWashVelocity, externalWashAgularVelocity);\n\n\n\n}\n\n\n\nvoid Aircraft::updateAtmosphericConditions()\n{\n\t// TODO: this is a stub!\n\t// The atmospheric condition change according to meteo (pressure, wind, temperature) and altitude, see Dreier 2007, chap 5\n}\n\n\nvoid Aircraft::printForces()\n{\n\tusing namespace std;\n\n\tcout << \"----------------------------\" << endl;\n\n\tcout << \"fext\" << centerOfGravity->getForcesIELA() << endl;\n\tcout << \"fuse\" << fuselage->getForcesIELA() << endl;\n\tcout << \"wing\" << horizontalStabilizer->getForcesIELA() << endl;\n\tcout << \"fin \" << verticalStabilizer->getForcesIELA() << endl;\n\tcout << \"main \" << mainRotor->getForcesIELA() << endl;\n\tcout << \"tail \" << tailRotor->getForcesIELA() << endl;\n\n\tcout << \"----------------------------\" << endl;\n}\n\nvoid Aircraft::printWashes()\n{\n\tusing namespace std;\n\tcout << \"----------Wash velocities ------------------\" << endl;\n\n\tcout << \"CoG\" << centerOfGravity->getWashVelocityIELA() << endl;\n\tcout << \"fuse\" << fuselage->getWashVelocityIELA() << endl;\n\tcout << \"wing\" << horizontalStabilizer->getWashVelocityIELA() << endl;\n\tcout << \"fin \" << verticalStabilizer->getWashVelocityIELA() << endl;\n\tcout << \"main \" << mainRotor->getWashVelocityIELA() << endl;\n\tcout << \"tail \" << tailRotor->getWashVelocityIELA() << endl;\n\n\tcout << \"----------------------------\" << endl;\n}\nvector<double> Aircraft::buildTrimVector()\n{\n\tvector<double> trimVector(6);\n\n\ttrimVector(0) = mainRotor->getCollectivePitch();\n\ttrimVector(1) = mainRotor->getLongitudinalSwashplateAngle();\n\ttrimVector(2) = mainRotor->getLateralSwashplateAngle();\n\ttrimVector(3) = tailRotor->getCollectivePitch();\n\n\tvector<double> angularPositionEarthAxes = centerOfGravity->getAngularPositionEarthAxes();\n\tif(usePhi)\n\t\ttrimVector(4) =  angularPositionEarthAxes(0);\n\telse\n\t\ttrimVector(4) =  angularPositionEarthAxes(2);\n\n\ttrimVector(5) =  angularPositionEarthAxes(1);\n\n\treturn trimVector;\n}\n\nvoid Aircraft::applyTrimVector(vector<double> trimVector)\n{\n\tmainRotor->setCollectivePitch(trimVector(0));\n\tmainRotor->setLongitudinalSwashplateAngle(trimVector(1));\n\tmainRotor->setLateralSwashplateAngle(trimVector(2));\n\ttailRotor->setCollectivePitch(trimVector(3));\n\n\tvector<double> angularPositionEarthAxes = centerOfGravity->getAngularPositionEarthAxes();\n\tif(usePhi)\n\t\tangularPositionEarthAxes(0) = trimVector(4);\n\telse\n\t\tangularPositionEarthAxes(2) = trimVector(4);\n\n\tangularPositionEarthAxes(1) = trimVector(5);\n\n\tupdatePhysics();\n\tcenterOfGravity->updateDerivatives();\n\n}\n\nvector<double> Aircraft::buildAccelerationVector()\n{\n\tvector<double> invertialVelocityDerivative = centerOfGravity->getInertialVelocityDerivativeCenterOfGravity();\n\tvector<double> invertialAngularVelocityDerivative = centerOfGravity->getInertialAngularVelocityDerivativeCenterOfGravity();\n\n\tvector<double> accelerationVector(6);\n\n\tfor(int i = 0; i < 3; i++)\n\t{\n\t\taccelerationVector(i) = invertialVelocityDerivative(i);\n\t\taccelerationVector(i + 3) = invertialAngularVelocityDerivative(i);\n\t}\n\treturn accelerationVector;\n\n}\n\ndouble Aircraft::jacobianTrim(vector<double> initialPositionEarthAxes, vector<double> initialAngularPositionEarthAxes, vector<double> initialVelocityEarthAxes, vector<double> initialAngularVelocityEarthAxes)\n{\n\tcenterOfGravity->setPositionEarthAxes(initialPositionEarthAxes);\n\tcenterOfGravity->setAngularPositionEarthAxes(initialAngularPositionEarthAxes);\n\tcenterOfGravity->setVelocityEarthAxes(initialVelocityEarthAxes);\n\tcenterOfGravity->setAngularVelocityEarthAxes(initialAngularVelocityEarthAxes);\n\n\tvector<double> currentTrimVector = buildTrimVector();\n\tvector<double> perturbedTrimVector = currentTrimVector;\n\tapplyTrimVector(perturbedTrimVector);\n\n\tvector<double> currentAccelerationVector = buildAccelerationVector();\n\tvector<double> perturbedAccelerationVector = currentAccelerationVector;\n\tstd::cout << \"acc : \" << currentAccelerationVector << std::endl;\n\n\tdouble accelerationVectorNorm = Utils::vectorNorm(perturbedAccelerationVector);\n\n\n\tmatrix<double> jacobianMatrix(6,6);\n\tmatrix<double> accelerationMatrixMinusPerturbation(6,6);\n\tmatrix<double> accelerationMatrixPlusPerturbation(6,6);\n\n\tint numberOfIterationLeft = 20;\n\tconst double PERTURBATION_SIZE = 0.01;\n\tvector<double> trimGradient = Constants::ZERO_VEC_3;\n\n\twhile (accelerationVectorNorm > 0.001 && numberOfIterationLeft > 0)\n\t{\n\n\t\tfor(int jacobianRowIndex = 0; jacobianRowIndex < 6; jacobianRowIndex++)\n\t\t{\n\t\t\tfor(int jacobianColumnIndex = 0; jacobianColumnIndex < 6; jacobianColumnIndex++)\n\t\t\t{\n\t\t\t\tperturbedTrimVector(jacobianColumnIndex) = currentTrimVector(jacobianColumnIndex) + PERTURBATION_SIZE;\n\t\t\t\tapplyTrimVector(perturbedTrimVector);\n\t\t\t\tprintForces();\n\t\t\t\tprintWashes();\n\t\t\t\tperturbedAccelerationVector = buildAccelerationVector();\n\t\t\t\taccelerationMatrixMinusPerturbation(jacobianRowIndex, jacobianColumnIndex) = perturbedAccelerationVector(jacobianRowIndex);\n\n\n\t\t\t\tperturbedTrimVector(jacobianColumnIndex) = currentTrimVector(jacobianColumnIndex) - PERTURBATION_SIZE;\n\t\t\t\tapplyTrimVector(perturbedTrimVector);\n\t\t\t\tprintForces();\n\t\t\t\tprintWashes();\n\t\t\t\tperturbedAccelerationVector = buildAccelerationVector();\n\t\t\t\taccelerationMatrixPlusPerturbation(jacobianRowIndex, jacobianColumnIndex) = perturbedAccelerationVector(jacobianRowIndex);\n\n\n//\t\t\t\tapplyTrimVector(currentTrimVector);\n\t\t\t\tperturbedTrimVector = currentTrimVector;\n\n\n\t\t\t}\n\t\t}\n\n\t\tjacobianMatrix = (accelerationMatrixPlusPerturbation - accelerationMatrixMinusPerturbation) / (2 * PERTURBATION_SIZE);\n\n\t\tusing namespace std;\n\n//\t\tcout << \"jac : \" << jacobianMatrix << endl;\n\n\t\ttrimGradient = prod(Utils::invertMatrix(jacobianMatrix), currentAccelerationVector);\n\n\t\tcurrentTrimVector -= trimGradient;\n\n\t\tapplyTrimVector(currentTrimVector);\n\t\tcurrentAccelerationVector = buildAccelerationVector();\n\n\n\t\tcout << \"grad : \" << trimGradient << endl;\n\t\tcout << \"trim : \" << perturbedTrimVector << endl;\n\t\tcout << \"acc : \" << currentAccelerationVector << endl;\n\n\t\tnumberOfIterationLeft--;\n\t\taccelerationVectorNorm = Utils::vectorNorm(currentAccelerationVector);\n\n\t\tcout << \"norm = \" << accelerationVectorNorm << endl;\n\n\t}\n\n\treturn accelerationVectorNorm;\n}\n\n\n\n", "meta": {"hexsha": "787a4ae7d92e69b4a78f808346e99b5ed1e7c41b", "size": 10070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Aircraft.cpp", "max_stars_repo_name": "maxlem/SimurotorDreier", "max_stars_repo_head_hexsha": "e83ba08e3b8ed117c594d4782920a3414fd19354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T03:46:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-21T01:16:11.000Z", "max_issues_repo_path": "src/Aircraft.cpp", "max_issues_repo_name": "maxlem/SimurotorDreier", "max_issues_repo_head_hexsha": "e83ba08e3b8ed117c594d4782920a3414fd19354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Aircraft.cpp", "max_forks_repo_name": "maxlem/SimurotorDreier", "max_forks_repo_head_hexsha": "e83ba08e3b8ed117c594d4782920a3414fd19354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.908496732, "max_line_length": 207, "alphanum_fraction": 0.7780536246, "num_tokens": 2504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2479700620096463}}
{"text": "/*\nCopyright Benjamin Perret ESIEE Paris 2017\n\nbenjamin.perret@esiee.fr\n\nThis software is a computer program whose purpose is to compute isotonic/\nmonotonic regression on tree ordering.\n\nThis software is governed by the CeCILL-B license under French law and\nabiding by the rules of distribution of free software.  You can  use,\nmodify and/ or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and  rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty  and the software's author,  the holder of the\neconomic rights,  and the successive licensors  have only  limited\nliability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading,  using,  modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean  that it is complicated to manipulate,  and  that  also\ntherefore means  that it is reserved for developers  and  experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and,  more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL-B license and that you accept its terms.\n\n */\n\n\n#include <vector>\n#include <boost/heap/binomial_heap.hpp>\n\n#include \"morto.h\"\n\n\nnamespace morto {\n\n\n\tusing namespace std;\n\n\n\n\tvoid testOrDie(bool b, string msg)\n\t{\n\t\tif (!b)\n\t\t\tthrow MortoException{ msg };\n\t}\n\n\n\t/**\n\t * Generic UnionFind with path compression and union by rank on integer indicis.\n\t */\n\tclass UnionFind {\n\tprivate:\n\t\tvector<size_t> parent;\n\t\tvector<int> rank;\n\n\tpublic:\n\t\t/**\n\t\tCreate a new family of size singleton sets.\n\t\t*/\n\t\tUnionFind(size_t size = 0)\n\t\t{\n\t\t\tif (size > 0)\n\t\t\t{\n\t\t\t\tfor (size_t i = 0; i < size; ++i)\n\t\t\t\t\tparent.push_back(i);\n\t\t\t\trank.resize(size, 0);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\tCreate a new singleton and return the index of its (single and canonical) node.\n\t\tComplexity O(1) (amortized)\n\t\t*/\n\t\t/*\n\t\tsize_t createSet()\n\t\t{\n\t\t\tsize_t size = parent.size();\n\t\t\tparent.push_back(size);\n\t\t\trank.push_back(0);\n\t\t\treturn size;\n\t\t}\n\t\t*/\n\n\t\t/**\n\t\tFinds and return the canonical node of the given nodeIndex and performs path compression.\n\t\tComplexity O(a(n)) (amortized)\n\t\t*/\n\t\tsize_t findCanonical(size_t nodeIndex)\n\t\t{\n\t\t\tsize_t save = nodeIndex;\n\t\t\twhile (parent[nodeIndex] != nodeIndex)\n\t\t\t\tnodeIndex = parent[nodeIndex];\n\t\t\twhile (parent[save] != save)\n\t\t\t{\n\t\t\t\tsize_t tmp = save;\n\t\t\t\tsave = parent[save];\n\t\t\t\tparent[tmp] = nodeIndex;\n\t\t\t}\n\t\t\treturn nodeIndex;\n\t\t}\n\n\t\t/**\n\t\tPerforms the union of two sets (given by their canonical nodes) with rank optimisation.\n\t\tReturns the index of the canonical node of the union.\n\t\tComplexity O(1)\n\t\t*/\n\t\tauto setUnion(size_t canonicalNodeIndex1, size_t canonicalNodeIndex2)\n\t\t{\n\t\t\tif (rank[canonicalNodeIndex1] > rank[canonicalNodeIndex2])\n\t\t\t{\n\t\t\t\tswap(canonicalNodeIndex1, canonicalNodeIndex2);\n\t\t\t}\n\t\t\telse if (rank[canonicalNodeIndex1] == rank[canonicalNodeIndex2])\n\t\t\t{\n\t\t\t\trank[canonicalNodeIndex2]++;\n\t\t\t}\n\t\t\tparent[canonicalNodeIndex1] = canonicalNodeIndex2;\n\t\t\treturn make_pair(canonicalNodeIndex2, canonicalNodeIndex1);\n\t\t}\n\t};\n\n\n\n\t//forward declaration\n\tstruct HeapNode;\n\n\tusing heap_t = boost::heap::binomial_heap<HeapNode>;\n\n\tstruct HeapNode {\n\t\tdouble value;\n\t\tsize_t nodeIndex;\n\t};\n\n\tbool operator<(const HeapNode & lo, const HeapNode & ro)\n\t{\n\t\treturn lo.value < ro.value;\n\t}\n\n\n\t/**\n\t* Internal tree node, merges information on nodes, blocks and heaps...\n\t*/\n\tstruct TreeNode {\n\t\t/**\n\t\t * Index of the parent node\n\t\t */\n\t\tsize_t parent = 0;\n\n\t\t/**\n\t\t * Weight\n\t\t */\n\t\tdouble weight = 1;\n\n\t\t/**\n\t\t * Input value\n\t\t */\n\t\tdouble value = 0;\n\n\t\t/**\n\t\t * Handle on the HeapNode associated to this node in the heap of its parent\n\t\t */\n\t\theap_t::handle_type handle;\n\n\t\t/**\n\t\t * Heap of HeapNodes associated to every child (only valid if the node is the canonical node associated to its block)\n\t\t */\n\t\theap_t heap;\n\n\t\t/**\n\t\t * Sum of weights of the nodes in the block (only valid if the node is the canonical node associated to its block)\n\t\t */\n\t\tdouble blockTotalWeight = 1;\n\n\t\t/**\n\t\t* Weighted sum of the nodes in the block (only valid if the node is the canonical node associated to its block)\n\t\t*/\n\t\tdouble blockWeightedSum = 0;\n\n\n\t\t/**\n\t\t * \\brief Average weight of the block (only valid if the node is the canonical node associated to its block)\n\t\t * \\return Average weight of the block\n\t\t */\n\t\tdouble getAverageWeight() const {\n\t\t\treturn blockWeightedSum / blockTotalWeight;\n\t\t}\n\n\n\n\t\tvoid mergeWith(TreeNode * node)\n\t\t{\n\t\t\theap.merge(node->heap);\n\t\t\tblockTotalWeight += node->blockTotalWeight;\n\t\t\tblockWeightedSum += node->blockWeightedSum;\n\n\t\t}\n\t};\n\n\n\t/**\n\t * Internal class to represent the tree.\n\t * Essentially a constructor.\n\t */\n\tclass Tree {\n\tprivate:\n\t\tvector<TreeNode> nodes;\n\n\tpublic:\n\t\t/**\n\t\t * \\brief Create a new tree from agnostic representation.\n\t\t * \\param parents Parent relation between nodes.\n\t\t * Preconditions :\n\t\t *\t\t- parents.size() > 0\n\t\t *\t\t- \"node i is the parent of node j\" <=> parents[j] == i\n\t\t *\t\t- \"node i is the root\" <=> parents[i] == i\n\t\t *\t\t- nodes are in topological order : parents[i] >= i\n\t\t * \\param values Input data associated to nodes.\n\t\t * The observed value at node i is values[i].\n\t\t * Preconditions :\n\t\t *\t\t- values.size() == parents.size()\n\t\t * \\param weights Weights associated to nodes.\n\t\t * If weights.size() == 0 , every node is assumed to have the same weight.\n\t\t * Else, the weight of node i is weights[i].\n\t\t * Preconditions :\n\t\t *\t\t- weights.size() == parents.size() || weights.empty()\n\t\t */\n\t\tTree(const vector<size_t> & parents, const vector<double> & values, const vector<double> & weights)\n\t\t{\n\n\t\t\tsize_t nnodes = parents.size();\n\t\t\tnodes.resize(nnodes);\n\n\n\t\t\tif (!weights.empty())\n\t\t\t{\n\t\t\t\tfor (size_t i = 0; i < nnodes; ++i)\n\t\t\t\t{\n\t\t\t\t\tnodes[i].weight = weights[i];\n\t\t\t\t\tnodes[i].blockTotalWeight = weights[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (size_t i = 0; i < nnodes; ++i)\n\t\t\t{\n\t\t\t\tnodes[i].parent = parents[i];\n\t\t\t\tnodes[i].value = values[i];\n\t\t\t\tnodes[i].blockWeightedSum = nodes[i].weight * nodes[i].value;\n\t\t\t\tif (parents[i] != i)\n\t\t\t\t{\n\t\t\t\t\t//nodes[parents[i]].children.push_back(i);\n\t\t\t\t\tnodes[i].handle = nodes[parents[i]].heap.push({ values[i], i });\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * \\brief Get the node of index i\n\t\t * \\param i A valid node index (Precondition 0 <= i < tree.size())\n\t\t * \\return A reference to node i\n\t\t */\n\t\tTreeNode * getNode(size_t i)\n\t\t{\n\t\t\treturn &nodes[i];\n\t\t}\n\n\t\t/**\n\t\t * \\brief Number of nodes in the tree\n\t\t * \\return Number of nodes in the tree\n\t\t */\n\t\tsize_t size() const\n\t\t{\n\t\t\treturn nodes.size();\n\t\t}\n\t};\n\n\n\t/**\n\t * \\brief Compute isotonic regression on the given tree.\n\t * \\param tree Input Tree, properly initialized.\n\t * \\return vector<double> containing the regression values for each node\n\t */\n\tvector<double> IRT_BIN(Tree & tree)\n\t{\n\t\tsize_t nnodes = tree.size();\n\n\t\tUnionFind uf(nnodes); // Block maintenance\n\n\t\tfor (size_t i = 0; i < nnodes; ++i) // from leaves to root\n\t\t{\n\n\n\t\t\tsize_t canonicali = uf.findCanonical(i); // index of the representative tree node for the block containing node i\n\t\t\tTreeNode * canonicalNode = tree.getNode(canonicali);\n\n\n\t\t\t// while we have violators among our children, fuse current block with the block of the most important violator\n\t\t\twhile (!canonicalNode->heap.empty() && canonicalNode->getAverageWeight() < canonicalNode->heap.top().value)\n\t\t\t{\n\t\t\t\tsize_t k = canonicalNode->heap.top().nodeIndex; // index of violator child k\n\t\t\t\tcanonicalNode->heap.pop();\n\n\t\t\t\tsize_t canonicalk = uf.findCanonical(k); // index of the representative tree node for the block containing node k\n\n\n\t\t\t\tauto resUnion = uf.setUnion(canonicali, canonicalk); // merge blocks containing i and k\n\t\t\t\tauto newCanonicalIndex = resUnion.first; // index of the new representative node (either i or k)\n\t\t\t\tauto otherIndex = resUnion.second; // index of the node that is not representative (either i or k)\n\n\t\t\t\t// update local variable after merge\n\t\t\t\tcanonicalNode = tree.getNode(newCanonicalIndex);\n\t\t\t\tcanonicali = newCanonicalIndex;\n\n\t\t\t\t// merge block information\n\t\t\t\tTreeNode * otherNode = tree.getNode(otherIndex);\n\t\t\t\tcanonicalNode->mergeWith(otherNode);\n\n\n\n\t\t\t}\n\n\t\t\t// update parent heap to reflect the new weight of the block containing node i\n\t\t\tTreeNode * currentNode = tree.getNode(i);\n\t\t\tif (currentNode->parent != i)\n\t\t\t{\n\t\t\t\tTreeNode * node = tree.getNode(currentNode->parent);\n\t\t\t\tnode->heap.update(currentNode->handle, { canonicalNode->getAverageWeight(), i });\n\t\t\t}\n\t\t}\n\n\n\t\tvector<double> res;\n\t\tfor (size_t i = 0; i < nnodes; ++i)\n\t\t{\n\t\t\tres.push_back(tree.getNode(uf.findCanonical(i))->getAverageWeight());\n\t\t}\n\t\treturn res;\n\t}\n\n\tbool testRelationDomain(const vector<size_t> & parents)\n\t{\n\t\tsize_t maxV = parents.size() - 1;\n\t\tfor (size_t i = 0; i < parents.size(); ++i)\n\t\t{\n\t\t\tif (parents[i]<0 || parents[i]>maxV) // size_t should be unsigned but well\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tbool testTopologicalOrder(const vector<size_t> & parents)\n\t{\n\t\tfor (size_t i = 0; i < parents.size(); ++i)\n\t\t{\n\t\t\tif (parents[i] < i)\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n    bool testPositiveWeights(const vector<double> & weights)\n    {\n        for (auto v: weights)\n            if(v<=0)\n                return false;\n        return true;\n    }\n\t/*bool testSingleRoot(const vector<int> & parents)\n\t{\n\t\tint nparents = 0;\n\t\tfor (int i = 0; i<parents.size(); ++i)\n\t\t{\n\t\t\tif (parents[i] == i)\n\t\t\t{\n\t\t\t\tnparents++;\n\t\t\t\tif (nparents > 1)\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}*/\n\n\n\tvector<double> monotonicRegressionOnTree(const vector<size_t> & parents, const vector<double> & values, const vector<double> & weights)\n\t{\n\t\ttestOrDie(parents.size() > 0, \"Size of parents must be strictily greater than 0.\");\n\t\ttestOrDie(values.size() == parents.size(), \"values and parents must have the same size.\");\n\t\ttestOrDie(weights.empty() || weights.size() == parents.size(), \"weights must either be empty or have the same size as parents.\");\n\t\ttestOrDie(testRelationDomain(parents), \"The domain of the parents relation is invalid: there exists i such that parents[i]<0 or parents[i]>=parents.size()\");\n\t\ttestOrDie(testTopologicalOrder(parents), \"The parent relation is not given in a topological order: there exists i such that parents[i]<i\");\n\t\tif(weights.size()>0)\n\t\t\ttestOrDie(testPositiveWeights(weights),\"Weights must be strictly positive.\");\n        //testOrDie(testSingleRoot(parents), \"The parent relationcontains more than one root : there exists several i such that parents[i]==i\");\n\n\t\tTree tree = Tree(parents, values, weights);\n\t\treturn IRT_BIN(tree);\n\t}\n\n\n} // namespace morto\n/*\n\nusing namespace morto;\nusing namespace std;\n\n\ntemplate<typename T>\nostream & operator<<(ostream & o, const vector<T> & vec)\n{\n\to << \"{\";\n\tfor (size_t i = 0; i < vec.size() - 1; ++i)\n\t\to << vec[i] << \", \";\n\tif (!vec.empty())\n\t\to << vec.back();\n\to << \"}\";\n\treturn o;\n}\n\nvoid testIncreasing()\n{\n\tvector<size_t> parents = { 4,4,6,6,7,7,7,7 };\n\t//vector<double> values = { 0,1,2,3,4,5,6,7 };\n\tvector<double> values = { 13,14,6,8,11,7,5,10 };\n\tvector<double> result = monotonicRegressionOnTree(parents, values);\n\tcout << result << endl;\n}\n\nint main(int argc, char ** argv)\n{\n\ttestIncreasing();\n\tgetchar();\n\treturn 0;\n}\n*/", "meta": {"hexsha": "67aa5099922eb636f31d56a6369cf38f8c878085", "size": 11597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/morto.cpp", "max_stars_repo_name": "PerretB/MoRTO", "max_stars_repo_head_hexsha": "0b0c89a107fc0c85ad524c1b893342e78070e502", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/morto.cpp", "max_issues_repo_name": "PerretB/MoRTO", "max_issues_repo_head_hexsha": "0b0c89a107fc0c85ad524c1b893342e78070e502", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/morto.cpp", "max_forks_repo_name": "PerretB/MoRTO", "max_forks_repo_head_hexsha": "0b0c89a107fc0c85ad524c1b893342e78070e502", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1193693694, "max_line_length": 159, "alphanum_fraction": 0.6730188842, "num_tokens": 3112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.24795610126175754}}
{"text": "//   https://github.com/dune-community/dune-gdt\n// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.\n// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)\n//          with \"runtime exception\" (http://www.dune-project.org/license.html)\n// Authors:\n//   Rene Milk      (2018)\n//   Tobias Leibner (2017)\n\n#ifndef DUNE_GDT_OPERATORS_FV_REALIZABILITY_HH\n#define DUNE_GDT_OPERATORS_FV_REALIZABILITY_HH\n\n#include \"config.h\"\n\n#include <boost/iostreams/stream.hpp>\n#include <boost/iostreams/device/null.hpp>\n\n#include <dune/geometry/quadraturerules.hh>\n\n#include <dune/xt/common/fvector.hh>\n\n#include <dune/xt/grid/walker.hh>\n\n#if HAVE_QHULL\n#include <dune/xt/common/disable_warnings.hh>\n#include <libqhullcpp/Qhull.h>\n#include <libqhullcpp/QhullFacetList.h>\n#include <dune/xt/common/reenable_warnings.hh>\n#endif // HAVE_QHULL\n\n#if HAVE_CLP\n#include <coin/ClpSimplex.hpp>\n#endif // HAVE_CLP\n\n#include <dune/gdt/operators/fv/reconstruction/reconstructed_function.hh>\n#include <dune/gdt/operators/interfaces.hh>\n#include <dune/gdt/local/fluxes/entropybased.hh>\n\nnamespace Dune {\nnamespace GDT {\n\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nclass LocalRealizabilityLimiterBase\n    : public XT::Grid::Functor::Codim0<typename DiscreteFunctionImp::SpaceType::GridLayerType>\n{\npublic:\n  using AnalyticalFluxType = AnalyticalFluxImp;\n  using DiscreteFunctionType = DiscreteFunctionImp;\n  using BasisfunctionType = BasisfunctionImp;\n  typedef typename DiscreteFunctionType::SpaceType::GridLayerType GridLayerType;\n  typedef typename DiscreteFunctionType::EntityType EntityType;\n  typedef typename GridLayerType::template Codim<0>::Geometry::LocalCoordinate DomainType;\n  typedef typename DiscreteFunctionType::RangeType RangeType;\n  typedef typename GridLayerType::IndexSet IndexSetType;\n  typedef typename DiscreteFunctionType::RangeFieldType RangeFieldType;\n  typedef typename DiscreteFunctionType::DomainFieldType DomainFieldType;\n  static const size_t dimDomain = DiscreteFunctionType::dimDomain;\n  static const size_t dimRange = DiscreteFunctionType::dimRange;\n  typedef typename Dune::QuadratureRule<RangeFieldType, dimDomain> QuadratureType;\n  using ReconstructedFunctionType =\n      ReconstructedLocalizableFunction<GridLayerType, DomainFieldType, dimDomain, RangeFieldType, dimRange>;\n  using EntropyFluxType = EntropyBasedLocalFlux<BasisfunctionType, GridLayerType, DiscreteFunctionType>;\n\n  LocalRealizabilityLimiterBase(const AnalyticalFluxType& analytical_flux,\n                                const DiscreteFunctionType& source,\n                                ReconstructedFunctionType& reconstructed_function,\n                                const BasisfunctionType& basis_functions,\n                                const QuadratureType& quadrature,\n                                const RangeFieldType epsilon,\n                                const std::vector<RangeType>& basis_values,\n                                const XT::Common::Parameter& param,\n                                const std::string filename,\n                                const RangeFieldType psi_vac)\n    : analytical_flux_(analytical_flux)\n    , source_(source)\n    , reconstructed_function_(reconstructed_function)\n    , basis_functions_(basis_functions)\n    , quadrature_(quadrature)\n    , epsilon_(epsilon)\n    , basis_values_(basis_values)\n    , param_(param)\n    , filename_(filename)\n    , psi_vac_(psi_vac)\n    , u_vac_(basis_functions_.integrated() * psi_vac_ / 10.)\n  {\n    param_.set(\"boundary\", {0.});\n  }\n\n  virtual ~LocalRealizabilityLimiterBase()\n  {\n  }\n\n  void apply_limiter(const typename AnalyticalFluxType::EntityType& entity,\n                     const RangeType theta_entity,\n                     std::map<DomainType, RangeType, XT::Common::FieldVectorLess>& local_reconstructed_values,\n                     const RangeType& u_bar,\n                     bool add_epsilon = true)\n  {\n    assert(dynamic_cast<const EntropyFluxType*>(&analytical_flux_) != nullptr\n           && \"analytical_flux_ has to be derived from EntropyBasedLocalFlux\");\n    for (size_t ii = 0; ii < dimRange; ++ii) {\n      auto theta_ii = add_epsilon ? theta_entity[ii] + epsilon_ : theta_entity[ii];\n      if (theta_ii > 0.) {\n        //        std::cout << \"limited with theta: \" << theta_ii << \" and epsilon \" << epsilon_ << std::endl;\n        if (theta_ii > 1.)\n          theta_ii = 1.;\n        for (auto& pair : local_reconstructed_values) {\n          auto& u_ii = pair.second[ii];\n          u_ii = convex_combination(u_ii, u_bar[ii], theta_ii);\n        }\n      } // if (theta_ii > 0)\n    } // ii\n\n    for (auto& pair : local_reconstructed_values) {\n      const auto x_in_inside_coords = entity.geometry().local(pair.first);\n      auto& u = pair.second;\n      const auto s = dynamic_cast<const EntropyFluxType*>(&analytical_flux_)\n                         ->derived_local_function(entity)\n                         ->get_alpha(x_in_inside_coords, u, param_, true, false)\n                         .second;\n\n      // if regularization was needed, we also need to replace u_n in that cell by its regularized version\n      if (s > 0.) {\n        if (!filename_.empty()) {\n          static std::mutex outfile_lock;\n          outfile_lock.lock();\n          std::ofstream outfile(filename_, std::ios_base::app);\n          outfile << param_.get(\"t\")[0];\n          for (size_t ii = 0; ii < dimDomain; ++ii)\n            outfile << \" \" << entity.geometry().center()[ii];\n          outfile << \" \" << s << \" 1\" << std::endl;\n          outfile_lock.unlock();\n        }\n        const auto u_iso = dynamic_cast<const EntropyFluxType*>(&analytical_flux_)\n                               ->basis_functions()\n                               .calculate_isotropic_distribution(u)\n                               .first;\n        u = convex_combination(u, u_iso, s);\n      } // if (s > 0)\n    } // local_reconstructed_values\n  }\n\n  void apply_limiter(const typename AnalyticalFluxType::EntityType& entity,\n                     const RangeFieldType theta_entity,\n                     std::map<DomainType, RangeType, XT::Common::FieldVectorLess>& local_reconstructed_values,\n                     const RangeType& u_bar,\n                     bool add_epsilon = true)\n  {\n    assert(dynamic_cast<const EntropyFluxType*>(&analytical_flux_) != nullptr\n           && \"analytical_flux_ has to be derived from EntropyBasedLocalFlux\");\n    auto theta = add_epsilon ? theta_entity + epsilon_ : theta_entity;\n    if (theta > 0.) {\n      //      std::cout << \"limited with theta: \" << theta << \" and epsilon \" << epsilon_ << std::endl;\n      if (theta > 1.)\n        theta = 1.;\n      for (auto& pair : local_reconstructed_values) {\n        auto& u = pair.second;\n        u = convex_combination(u, u_bar, theta);\n      }\n    }\n\n    for (auto& pair : local_reconstructed_values) {\n      const auto x_in_inside_coords = entity.geometry().local(pair.first);\n      auto& u = pair.second;\n      const auto s = dynamic_cast<const EntropyFluxType*>(&analytical_flux_)\n                         ->derived_local_function(entity)\n                         ->get_alpha(x_in_inside_coords, u, param_, true, false)\n                         .second;\n\n      // if regularization was needed, we also need to replace u_n in that cell by its regularized version\n      if (s > 0.) {\n        if (!filename_.empty()) {\n          static std::mutex outfile_lock;\n          outfile_lock.lock();\n          std::ofstream outfile(filename_, std::ios_base::app);\n          outfile << param_.get(\"t\")[0];\n          for (size_t ii = 0; ii < dimDomain; ++ii)\n            outfile << \" \" << entity.geometry().center()[ii];\n          outfile << \" \" << s << \" 1\" << std::endl;\n          outfile_lock.unlock();\n        }\n        const auto u_iso = dynamic_cast<const EntropyFluxType*>(&analytical_flux_)\n                               ->basis_functions()\n                               .calculate_isotropic_distribution(u)\n                               .first;\n        u = convex_combination(u, u_iso, s);\n      } // if (s > 0)\n    } // local_reconstructed_values\n  } // void apply_limiter(...)\n\nprotected:\n  RangeType convex_combination(const RangeType& u, const RangeType& u_bar, const RangeFieldType& theta)\n  {\n    RangeType u_scaled = u;\n    u_scaled *= 1 - theta;\n    RangeType u_bar_scaled = u_bar;\n    u_bar_scaled *= theta;\n    return u_scaled + u_bar_scaled;\n  }\n\n  RangeFieldType convex_combination(const RangeFieldType& u, const RangeFieldType& u_bar, const RangeFieldType& theta)\n  {\n    return u_bar * theta + u * (1. - theta);\n  }\n\n  const AnalyticalFluxType& analytical_flux_;\n  const DiscreteFunctionType& source_;\n  ReconstructedFunctionType& reconstructed_function_;\n  const BasisfunctionType& basis_functions_;\n  const QuadratureType& quadrature_;\n  const RangeFieldType epsilon_;\n  const std::vector<RangeType>& basis_values_;\n  XT::Common::Parameter param_;\n  const std::string filename_;\n  const RangeFieldType psi_vac_;\n  const RangeType u_vac_;\n};\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp = int>\nclass NonLimitingLocalRealizabilityLimiter\n    : public LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>\n{\n  using BaseType = LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>;\n\npublic:\n  using typename BaseType::EntityType;\n\n  template <class... Args>\n  NonLimitingLocalRealizabilityLimiter(Args&&... args)\n    : BaseType(std::forward<Args>(args)...)\n  {\n  }\n\n  void apply_local(const EntityType& entity)\n  {\n    auto& local_reconstructed_values = reconstructed_function_.local_values(entity);\n    const auto u_bar = source_.local_function(entity)->evaluate(entity.geometry().local(entity.geometry().center()));\n    BaseType::apply_limiter(entity, 0., local_reconstructed_values, u_bar, false);\n  }\n\nprivate:\n  using BaseType::reconstructed_function_;\n  using BaseType::source_;\n}; // class NonLimitingLocalRealizabilityLimiter\n\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nclass PositivityLocalRealizabilityLimiter\n    : public LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>\n{\n  using BaseType = LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>;\n\npublic:\n  using typename BaseType::GridLayerType;\n  using typename BaseType::EntityType;\n  using typename BaseType::DomainType;\n  using typename BaseType::RangeType;\n  using typename BaseType::RangeFieldType;\n  using typename BaseType::QuadratureType;\n  static const size_t dimDomain = BaseType::dimDomain;\n  static const size_t dimRange = BaseType::dimRange;\n\n  template <class... Args>\n  PositivityLocalRealizabilityLimiter(Args&&... args)\n    : BaseType(std::forward<Args>(args)...)\n  {\n  }\n\n  void apply_local(const EntityType& entity)\n  {\n    auto& local_reconstructed_values = reconstructed_function_.local_values(entity);\n\n    // get cell average\n    const RangeType u_bar =\n        source_.local_function(entity)->evaluate(entity.geometry().local(entity.geometry().center()));\n\n    // vector to store thetas for each local reconstructed value\n    RangeType thetas(0.);\n\n    for (const auto& pair : local_reconstructed_values) {\n      const auto& u = pair.second;\n      for (size_t ii = 0; ii < u.size(); ++ii) {\n        if (u[ii] >= u_bar[ii])\n          continue;\n        if (u_bar[ii] < u_vac_[ii])\n          thetas[ii] = 1.;\n        else if (u[ii] < u_vac_[ii])\n          thetas[ii] = std::max(thetas[ii], (u_vac_[ii] - u[ii]) / (u_bar[ii] - u[ii]));\n      } // ii\n    } // ll\n\n    BaseType::apply_limiter(entity, thetas, local_reconstructed_values, u_bar, false);\n  } // void apply_local(...)\n\nprivate:\n  using BaseType::source_;\n  using BaseType::reconstructed_function_;\n  using BaseType::u_vac_;\n}; // class PositivityLocalRealizabilityLimiter\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nclass DgLocalRealizabilityLimiter\n    : public LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>\n{\n  using BaseType = LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>;\n\npublic:\n  using typename BaseType::AnalyticalFluxType;\n  using typename BaseType::DiscreteFunctionType;\n  using typename BaseType::EntityType;\n  using typename BaseType::GridLayerType;\n  using typename BaseType::QuadratureType;\n  using typename BaseType::RangeType;\n  using typename BaseType::RangeFieldType;\n  using typename BaseType::ReconstructedFunctionType;\n  using typename BaseType::BasisfunctionType;\n  static const size_t dimDomain = BaseType::dimDomain;\n  static const size_t dimRange = BaseType::dimRange;\n\n  template <class... Args>\n  DgLocalRealizabilityLimiter(Args&&... args)\n    : BaseType(std::forward<Args>(args)...)\n    , triangulation_(basis_functions_.triangulation())\n  {\n  }\n\n  void apply_local(const EntityType& entity)\n  {\n    auto& local_reconstructed_values = reconstructed_function_.local_values(entity);\n\n    // get cell average\n    const RangeType u_bar =\n        source_.local_function(entity)->evaluate(entity.geometry().local(entity.geometry().center()));\n\n    // vector to store thetas for each local reconstructed value\n    RangeType thetas(0.);\n\n    for (const auto& pair : local_reconstructed_values) {\n      const auto& u = pair.second;\n      for (size_t ii = 0; ii < dimRange / 2; ++ii) {\n        const auto& u0 = u[2 * ii];\n        const auto& u1 = u[2 * ii + 1];\n        const auto& ubar0 = u_bar[2 * ii];\n        const auto& ubar1 = u_bar[2 * ii + 1];\n        const auto& epsilon = u_vac_[2 * ii];\n        const auto& vj = triangulation_[ii];\n        const auto& vjplus1 = triangulation_[ii + 1];\n        FieldVector<RangeFieldType, 3> thetas_ii;\n        if (!is_epsilon_realizable(ubar0, ubar1, vj, vjplus1, epsilon)) {\n          thetas[2 * ii] = 1.;\n        } else {\n          thetas_ii[0] = (epsilon - u0) / (ubar0 - u0);\n          thetas_ii[1] = (u0 * vj - u1 + epsilon * std::sqrt(std::pow(vj, 2) + 1)) / ((ubar1 - u1) - (ubar0 - u0) * vj);\n          thetas_ii[2] = (u0 * vjplus1 - u1 - epsilon * std::sqrt(std::pow(vjplus1, 2) + 1))\n                         / ((ubar1 - u1) - (ubar0 - u0) * vjplus1);\n          for (size_t kk = 0; kk < 3; ++kk)\n            if (thetas_ii[kk] >= 0. && thetas_ii[kk] <= 1.)\n              thetas[2 * ii] = std::max(thetas[2 * ii], thetas_ii[kk]);\n        } // else (!realizable)\n        thetas[2 * ii + 1] = thetas[2 * ii];\n      } // ii\n    } // local_reconstructed_values\n    BaseType::apply_limiter(entity, thetas, local_reconstructed_values, u_bar, false);\n  } // void apply_local(...)\n\nprivate:\n  bool is_epsilon_realizable(const RangeFieldType ubar0,\n                             const RangeFieldType ubar1,\n                             const RangeFieldType v0,\n                             const RangeFieldType v1,\n                             const RangeFieldType eps) const\n  {\n    bool ret = (ubar0 >= eps) && (ubar1 <= v1 * ubar0 - eps * std::sqrt(std::pow(v1, 2) + 1))\n               && (v0 * ubar0 + eps * std::sqrt(std::pow(v0, 2) + 1) <= ubar1);\n    return ret;\n  }\n\n  using BaseType::source_;\n  using BaseType::reconstructed_function_;\n  using BaseType::basis_functions_;\n  using BaseType::u_vac_;\n  typename BasisfunctionImp::TriangulationType triangulation_;\n}; // class DgLocalRealizabilityLimiter\n\n#if HAVE_QHULL\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nclass ConvexHullLocalRealizabilityLimiter\n    : public LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>\n{\n  using BaseType = LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>;\n\npublic:\n  using typename BaseType::GridLayerType;\n  using typename BaseType::EntityType;\n  using typename BaseType::DomainType;\n  using typename BaseType::RangeType;\n  using typename BaseType::RangeFieldType;\n  using typename BaseType::QuadratureType;\n  using typename BaseType::ReconstructedFunctionType;\n  using typename BaseType::BasisfunctionType;\n  static const size_t dimDomain = BaseType::dimDomain;\n  static const size_t dimRange = BaseType::dimRange;\n  typedef typename std::vector<std::pair<RangeType, RangeFieldType>> PlaneCoefficientsType;\n\n  template <class... Args>\n  ConvexHullLocalRealizabilityLimiter(Args&&... args)\n    : BaseType(std::forward<Args>(args)...)\n  {\n    if (is_instantiated_)\n      DUNE_THROW(InvalidStateException,\n                 \"This class uses several static variables to save its state between time \"\n                 \"steps, so using several instances at the same time may result in undefined \"\n                 \"behavior!\");\n    is_instantiated_ = true;\n    if (!plane_coefficients_)\n      calculate_plane_coefficients();\n  }\n\n  ~ConvexHullLocalRealizabilityLimiter()\n  {\n    is_instantiated_ = false;\n  }\n\n  void apply_local(const EntityType& entity)\n  {\n    auto& local_reconstructed_values = reconstructed_function_.local_values(entity);\n\n    // get cell average\n    const RangeType u_bar =\n        source_.local_function(entity)->evaluate(entity.geometry().local(entity.geometry().center()));\n\n    // vector to store thetas for each local reconstructed value\n    std::vector<RangeFieldType> thetas(local_reconstructed_values.size(), -epsilon_);\n\n    size_t ll = -1;\n    for (const auto& pair : local_reconstructed_values) {\n      ++ll;\n      // rescale u_l, u_bar\n      auto u_l = pair.second;\n      auto u_bar_minus_u_l = u_bar - u_l;\n      const auto factor = basis_functions_.realizability_limiter_max(u_l, u_bar);\n      u_l /= factor;\n      u_bar_minus_u_l /= factor;\n\n      for (const auto& coeffs : *plane_coefficients_) {\n        const RangeType& a = coeffs.first;\n        const RangeFieldType& b = coeffs.second;\n        RangeFieldType theta_li = (b - a * u_l) / (a * u_bar_minus_u_l);\n        if (XT::Common::FloatCmp::le(theta_li, 1.))\n          thetas[ll] = std::max(thetas[ll], theta_li);\n      } // coeffs\n    } // ll\n    for (auto& theta : thetas)\n      theta = std::min(epsilon_ + theta, 1.);\n\n    auto theta_entity = *std::max_element(thetas.begin(), thetas.end());\n    if (theta_entity > 0.) {\n      for (auto& pair : local_reconstructed_values) {\n        auto& u = pair.second;\n        auto u_scaled = u;\n        u_scaled *= (1 - theta_entity);\n        auto u_bar_scaled = u_bar;\n        u_bar_scaled *= theta_entity;\n        u = u_scaled + u_bar_scaled;\n      }\n    }\n  } // void apply_local(...)\n\nprivate:\n  // calculate half space representation of realizable set\n  void calculate_plane_coefficients()\n  {\n    using orgQhull::Qhull;\n    Qhull qhull;\n    std::vector<FieldVector<RangeFieldType, dimRange>> points(quadrature_.size() + 1);\n    points[0] = FieldVector<RangeFieldType, dimRange>(0);\n    size_t ii = 1;\n    for (const auto& quad_point : quadrature_)\n      points[ii++] = basis_functions_.evaluate(quad_point.position());\n\n    std::cout << \"Starting qhull...\" << std::endl;\n    qhull.runQhull(\"Realizable set\", int(dimRange), int(points.size()), &(points[0][0]), \"Qt T1\");\n    std::cout << \"qhull done\" << std::endl;\n    //    qhull.outputQhull(\"n\");\n    const auto facet_end = qhull.endFacet();\n    plane_coefficients_ = std::make_shared<PlaneCoefficientsType>(qhull.facetList().count());\n    ii = 0;\n    for (auto facet = qhull.beginFacet(); facet != facet_end; facet = facet.next(), ++ii) {\n      for (size_t jj = 0; jj < dimRange; ++jj)\n        (*plane_coefficients_)[ii].first[jj] = *(facet.hyperplane().coordinates() + jj);\n      (*plane_coefficients_)[ii].second = -facet.hyperplane().offset();\n    }\n  }\n\n  using BaseType::basis_functions_;\n  using BaseType::source_;\n  using BaseType::reconstructed_function_;\n  using BaseType::quadrature_;\n  using BaseType::epsilon_;\n  static bool is_instantiated_;\n  static std::shared_ptr<PlaneCoefficientsType> plane_coefficients_;\n}; // class ConvexHullLocalRealizabilityLimiter\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nbool ConvexHullLocalRealizabilityLimiter<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>::is_instantiated_ =\n    false;\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nstd::shared_ptr<typename ConvexHullLocalRealizabilityLimiter<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>::\n                    PlaneCoefficientsType>\n    ConvexHullLocalRealizabilityLimiter<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>::plane_coefficients_;\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nclass DgConvexHullLocalRealizabilityLimiter\n    : public LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>\n{\n  using ThisType = DgConvexHullLocalRealizabilityLimiter;\n  using BaseType = LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>;\n\npublic:\n  using typename BaseType::GridLayerType;\n  using typename BaseType::EntityType;\n  using typename BaseType::DomainType;\n  using typename BaseType::RangeType;\n  using typename BaseType::RangeFieldType;\n  using typename BaseType::QuadratureType;\n  using typename BaseType::ReconstructedFunctionType;\n  using typename BaseType::BasisfunctionType;\n  static const size_t dimDomain = BaseType::dimDomain;\n  static const size_t dimRange = BaseType::dimRange;\n  static const size_t block_size = (dimDomain == 1) ? 2 : 4;\n  static const size_t num_blocks = dimRange / block_size;\n  typedef FieldVector<RangeFieldType, block_size - 1> BlockRangeType;\n  typedef typename std::vector<std::pair<BlockRangeType, RangeFieldType>> BlockPlaneCoefficientsType;\n  typedef FieldVector<BlockPlaneCoefficientsType, num_blocks> PlaneCoefficientsType;\n\npublic:\n  template <class... Args>\n  DgConvexHullLocalRealizabilityLimiter(Args&&... args)\n    : BaseType(std::forward<Args>(args)...)\n  {\n    if (is_instantiated_)\n      DUNE_THROW(InvalidStateException,\n                 \"This class uses several static variables to save its state between time \"\n                 \"steps, so using several instances at the same time may result in undefined \"\n                 \"behavior!\");\n    is_instantiated_ = true;\n    if (!plane_coefficients_)\n      calculate_plane_coefficients();\n  }\n\n  ~DgConvexHullLocalRealizabilityLimiter()\n  {\n    is_instantiated_ = false;\n  }\n\n  void apply_local(const EntityType& entity)\n  {\n    auto& local_reconstructed_values = reconstructed_function_.local_values(entity);\n\n    // get cell average\n    const RangeType u_bar =\n        source_.local_function(entity)->evaluate(entity.geometry().local(entity.geometry().center()));\n\n    // vector to store thetas for each local reconstructed value\n    std::vector<RangeFieldType> thetas(local_reconstructed_values.size(), -epsilon_);\n\n    size_t ll = -1;\n    for (const auto& pair : local_reconstructed_values) {\n      ++ll;\n      // rescale u_l, u_bar\n      auto u_l = pair.second;\n      if (XT::Common::FloatCmp::eq(u_l, u_bar))\n        continue;\n      const auto factor = basis_functions_.realizability_limiter_max(u_l, u_bar);\n      u_l /= factor;\n      auto u_bar_scaled = u_bar;\n      u_bar_scaled /= factor;\n      // check positivity of first moment on each spherical triangle\n      for (size_t jj = 0; jj < num_blocks; ++jj) {\n        const size_t offset = jj * block_size;\n        if (u_l[offset] >= u_bar_scaled[offset])\n          continue;\n        thetas[ll] = std::max(thetas[ll], u_l[offset] / (u_l[offset] - u_bar_scaled[offset]));\n      }\n      // check convex hull property of other moments\n      for (size_t jj = 0; jj < num_blocks; ++jj) {\n        const size_t offset = jj * block_size;\n        BlockRangeType q_k, q_bar_k;\n        for (size_t mm = 0; mm < block_size - 1; ++mm) {\n          q_k[mm] = u_l[offset + mm + 1];\n          q_bar_k[mm] = u_bar_scaled[offset + mm + 1];\n        }\n        for (const auto& coeffs : (*plane_coefficients_)[jj]) {\n          const BlockRangeType& a = coeffs.first;\n          const RangeFieldType& b = coeffs.second;\n          const auto u0 = u_l[offset];\n          const auto ubar0 = u_bar_scaled[offset];\n          RangeFieldType theta_li = (b * u0 - a * q_k) / (a * (q_bar_k - q_k) - b * (ubar0 - u0));\n          if (!(theta_li > 1.))\n            thetas[ll] = std::max(thetas[ll], theta_li);\n        } // coeffs\n      } // jj\n    } // ll\n\n    auto theta_entity = *std::max_element(thetas.begin(), thetas.end());\n    BaseType::apply_limiter(entity, theta_entity, local_reconstructed_values, u_bar);\n  } // void apply_local(...)\n\nprivate:\n  // calculate half space representation of realizable set\n  void calculate_plane_coefficients()\n  {\n    plane_coefficients_ = std::make_shared<PlaneCoefficientsType>();\n    FieldVector<std::vector<FieldVector<RangeFieldType, block_size - 1>>, num_blocks> points;\n    FieldVector<QuadratureType, num_blocks> blocked_quadrature;\n    for (const auto& quad_point : quadrature_) {\n      const auto face_indices = basis_functions_.get_face_indices(quad_point.position());\n      const size_t num_adjacent_faces = face_indices.size();\n      for (const auto& kk : face_indices)\n        blocked_quadrature[kk].emplace_back(quad_point.position(), quad_point.weight() / num_adjacent_faces);\n    } // ii\n    size_t num_faces;\n    for (size_t jj = 0; jj < num_blocks; ++jj) {\n      points[jj].resize(blocked_quadrature[jj].size() + 1);\n      for (size_t ii = 0; ii < blocked_quadrature[jj].size(); ++ii) {\n        const auto val = basis_functions_.evaluate(blocked_quadrature[jj][ii].position(), false, num_faces);\n        for (size_t ll = 0; ll < block_size - 1; ++ll)\n          points[jj][ii][ll] = val[block_size * jj + 1 + ll];\n      } // ii\n      points[jj][blocked_quadrature[jj].size()] = FieldVector<RangeFieldType, block_size - 1>(0.);\n    }\n    std::vector<std::thread> threads(num_blocks);\n    // Launch a group of threads\n    for (size_t jj = 0; jj < num_blocks; ++jj)\n      threads[jj] = std::thread(&ThisType::calculate_plane_coefficient_block, this, std::ref(points[jj]), jj);\n    // Join the threads with the main thread\n    for (size_t jj = 0; jj < num_blocks; ++jj)\n      threads[jj].join();\n  }\n\n  void calculate_plane_coefficient_block(std::vector<FieldVector<RangeFieldType, block_size - 1>>& points, size_t jj)\n  {\n    orgQhull::Qhull qhull;\n    boost::iostreams::stream<boost::iostreams::null_sink> null_ostream((boost::iostreams::null_sink()));\n    qhull.setOutputStream(&null_ostream);\n    qhull.setErrorStream(&null_ostream);\n    qhull.runQhull(\"Realizable set\", int(block_size) - 1, int(points.size()), &(points[0][0]), \"Qt T1\");\n    const auto facet_end = qhull.endFacet();\n    BlockPlaneCoefficientsType block_plane_coefficients(qhull.facetList().count());\n    //    std::cout << \"num_vertices: \" << qhull.vertexList().count() << std::endl;\n    size_t ii = 0;\n    for (auto facet = qhull.beginFacet(); facet != facet_end; facet = facet.next(), ++ii) {\n      for (size_t ll = 0; ll < block_size - 1; ++ll)\n        block_plane_coefficients[ii].first[ll] = *(facet.hyperplane().coordinates() + ll);\n      block_plane_coefficients[ii].second = -facet.hyperplane().offset();\n    } // ii\n    (*plane_coefficients_)[jj] = block_plane_coefficients;\n  }\n\n\n  using BaseType::basis_functions_;\n  using BaseType::source_;\n  using BaseType::reconstructed_function_;\n  using BaseType::quadrature_;\n  using BaseType::epsilon_;\n  static bool is_instantiated_;\n  static std::shared_ptr<PlaneCoefficientsType> plane_coefficients_;\n}; // class ConvexHullLocalRealizabilityLimiter\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nbool DgConvexHullLocalRealizabilityLimiter<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>::is_instantiated_ =\n    false;\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nstd::shared_ptr<typename DgConvexHullLocalRealizabilityLimiter<AnalyticalFluxImp,\n                                                               DiscreteFunctionImp,\n                                                               BasisfunctionImp>::PlaneCoefficientsType>\n    DgConvexHullLocalRealizabilityLimiter<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>::\n        plane_coefficients_;\n\n#else // HAVE_QHULL\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nclass ConvexHullLocalRealizabilityLimiter\n{\n  static_assert(Dune::AlwaysFalse<DiscreteFunctionImp>::value, \"You are missing Qhull!\");\n};\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nclass DgConvexHullLocalRealizabilityLimiter\n{\n  static_assert(Dune::AlwaysFalse<DiscreteFunctionImp>::value, \"You are missing Qhull!\");\n};\n\n#endif // HAVE_QHULL\n\n#if HAVE_CLP\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nclass ClpLocalRealizabilityLimiter\n    : public LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>\n{\n  using BaseType = LocalRealizabilityLimiterBase<AnalyticalFluxImp, DiscreteFunctionImp, BasisfunctionImp>;\n\npublic:\n  using typename BaseType::GridLayerType;\n  using typename BaseType::EntityType;\n  using typename BaseType::DomainType;\n  using typename BaseType::RangeType;\n  using typename BaseType::RangeFieldType;\n  using typename BaseType::QuadratureType;\n  static const size_t dimDomain = BaseType::dimDomain;\n  static const size_t dimRange = BaseType::dimRange;\n\n  template <class... Args>\n  ClpLocalRealizabilityLimiter(Args&&... args)\n    : BaseType(std::forward<Args>(args)...)\n  {\n  }\n\n  void apply_local(const EntityType& entity)\n  {\n    auto& local_reconstructed_values = reconstructed_function_.local_values(entity);\n    assert(local_reconstructed_values.size() == 2 * dimDomain);\n\n    // get cell average\n    const RangeType u_bar =\n        source_.local_function(entity)->evaluate(entity.geometry().local(entity.geometry().center()));\n\n    RangeFieldType theta_entity(0.);\n\n    // if a component is already really small, we do not want to reconstruct in that direction\n    for (size_t ii = 0; ii < dimRange; ++ii)\n      if (u_bar[ii] < u_vac_[ii])\n        for (auto& pair : local_reconstructed_values)\n          pair.second[ii] = u_bar[ii];\n\n    for (const auto& pair : local_reconstructed_values) {\n      const auto& u = pair.second;\n      if (XT::Common::FloatCmp::eq(u_bar, u))\n        continue;\n\n      // solve LP:\n      // min \\theta s.t.\n      // (\\sum x_i v_i) + \\theta (u - \\bar{u}) = u\n      // x_i, \\theta >= 0\n      theta_entity = std::max(theta_entity, solve_linear_program(u_bar, u));\n    } // ll\n    BaseType::apply_limiter(entity, theta_entity, local_reconstructed_values, u_bar);\n  } // void apply_local(...)\n\nprivate:\n  void setup_linear_program()\n  {\n    if (!*lp_) {\n      // We start with creating a model with dimRange rows and num_quad_points+1 columns */\n      constexpr int num_rows = static_cast<int>(dimRange);\n      assert(quadrature_.size() < std::numeric_limits<int>::max());\n      int num_cols = static_cast<int>(quadrature_.size() + 1); /* variables are x_1, ..., x_{num_quad_points}, theta */\n      *lp_ = std::make_unique<ClpSimplex>(false);\n      auto& lp = **lp_;\n      // set number of rows\n      lp.resize(num_rows, 0);\n\n      // Clp wants the row indices that are non-zero in each column. We have a dense matrix, so provide all indices\n      // 0..num_rows\n      std::array<int, num_rows> row_indices;\n      for (size_t ii = 0; ii < num_rows; ++ii)\n        row_indices[ii] = ii;\n\n      // set columns for quadrature points\n      assert(int(basis_values_.size()) == num_cols - 1);\n      for (int ii = 0; ii < num_cols - 1; ++ii) {\n        const auto& v_i = basis_values_[ii];\n        // First argument: number of elements in column\n        // Second/Third argument: indices/values of column entries\n        // Fourth/Fifth argument: lower/upper column bound, i.e. lower/upper bound for x_i. As all x_i should be\n        // positive, set to 0/inf, which is the default.\n        // Sixth argument: Prefactor in objective for x_i, this is 0 for all x_i, which is also the default;\n        lp.addColumn(num_rows, row_indices.data(), &(v_i[0]));\n      }\n\n      // add theta column (set to random values, will be set correctly in solve_linear_program)\n      // The bounds for theta should be [0,1], but we allow allow theta to be slightly\n      // negative so we can check if u_l is on the boundary and if so, move it a little\n      // away from the boundary\n      // Also sets the prefactor in the objective to 1 for theta.\n      lp.addColumn(num_rows, row_indices.data(), &(basis_values_[0][0]), -0.1, 1., 1.);\n      lp.setLogLevel(0);\n    } // if (!lp_)\n  }\n\n  //  RangeFieldType solve_linear_program(const RangeType& u_bar, const RangeType& u_l, const size_t index)\n  RangeFieldType solve_linear_program(const RangeType& u_bar, const RangeType& u_l)\n  {\n    setup_linear_program();\n    auto& lp = **lp_;\n    constexpr int num_rows = static_cast<int>(dimRange);\n    int num_cols = static_cast<int>(quadrature_.size() + 1); /* variables are x_1, ..., x_{num_quad_points}, theta */\n    RangeFieldType theta;\n    const auto u_l_minus_u_bar = u_l - u_bar;\n\n    // set rhs (equality constraints, so set both bounds equal\n    for (size_t ii = 0; ii < num_rows; ++ii) {\n      lp.setRowLower(ii, u_l[ii]);\n      lp.setRowUpper(ii, u_l[ii]);\n    }\n\n    // Clp wants the row indices that are non-zero in each column. We have a dense matrix, so provide all indices\n    // 0..num_rows\n    std::array<int, num_rows> row_indices;\n    for (size_t ii = 0; ii < num_rows; ++ii)\n      row_indices[ii] = ii;\n\n    // delete and reset theta column\n    const int last_col = num_cols - 1;\n    lp.deleteColumns(1, &last_col);\n    lp.addColumn(num_rows, row_indices.data(), &(u_l_minus_u_bar[0]), -0.1, 1., 1.);\n\n    // Now solve\n    lp.primal();\n    theta = lp.objectiveValue();\n    if (!lp.isProvenOptimal())\n      theta = 1.;\n\n    return theta;\n  }\n\n  using BaseType::source_;\n  using BaseType::reconstructed_function_;\n  using BaseType::quadrature_;\n  using BaseType::epsilon_;\n  using BaseType::basis_values_;\n  using BaseType::u_vac_;\n  XT::Common::PerThreadValue<std::unique_ptr<ClpSimplex>> lp_;\n}; // class ClpLocalRealizabilityLimiter\n\n#else // HAVE_CLP\n\ntemplate <class AnalyticalFluxImp, class DiscreteFunctionImp, class BasisfunctionImp>\nclass ClpLocalRealizabilityLimiter\n{\n  static_assert(Dune::AlwaysFalse<DiscreteFunctionImp>::value, \"You are missing Clp!\");\n};\n\n#endif // HAVE_CLP\n\n\ntemplate <class LocalRealizabilityLimiterImp, class Traits>\nclass RealizabilityLimiter;\n\n\nnamespace internal {\n\n\ntemplate <class LocalRealizabilityLimiterImp>\nstruct RealizabilityLimiterTraits\n{\n  using LocalRealizabilityLimiterType = LocalRealizabilityLimiterImp;\n  using AnalyticalFluxType = typename LocalRealizabilityLimiterImp::AnalyticalFluxType;\n  using BasisfunctionType = typename LocalRealizabilityLimiterImp::BasisfunctionType;\n  using QuadratureType = typename LocalRealizabilityLimiterImp::QuadratureType;\n  using RangeFieldType = typename LocalRealizabilityLimiterImp::RangeFieldType;\n  using FieldType = RangeFieldType;\n  using JacobianType = NoJacobian;\n  using RangeType = typename LocalRealizabilityLimiterImp::RangeType;\n  using ReconstructedFunctionType = typename LocalRealizabilityLimiterImp::ReconstructedFunctionType;\n  using derived_type = RealizabilityLimiter<LocalRealizabilityLimiterType, RealizabilityLimiterTraits>;\n};\n\n\n} // namespace internal\n\n\ntemplate <class LocalRealizabilityLimiterImp,\n          class Traits = internal::RealizabilityLimiterTraits<LocalRealizabilityLimiterImp>>\nclass RealizabilityLimiter : public OperatorInterface<Traits>\n{\npublic:\n  using LocalRealizabilityLimiterType = typename Traits::LocalRealizabilityLimiterType;\n  using AnalyticalFluxType = typename Traits::AnalyticalFluxType;\n  using BasisfunctionType = typename Traits::BasisfunctionType;\n  using QuadratureType = typename Traits::QuadratureType;\n  using RangeFieldType = typename Traits::RangeFieldType;\n  using RangeType = typename Traits::RangeType;\n  using ReconstructedFunctionType = typename Traits::ReconstructedFunctionType;\n\n  RealizabilityLimiter(const AnalyticalFluxType& analytical_flux,\n                       const BasisfunctionType& basis_functions,\n                       const QuadratureType& quadrature,\n                       const RangeFieldType epsilon = 1e-8,\n                       const std::string filename = \"\",\n                       const RangeFieldType psi_vac = 5e-9)\n    : analytical_flux_(analytical_flux)\n    , basis_functions_(basis_functions)\n    , quadrature_(quadrature)\n    , epsilon_(epsilon)\n    , basis_values_(quadrature_.size())\n    , filename_(filename)\n    , psi_vac_(psi_vac)\n  {\n    for (size_t ii = 0; ii < quadrature_.size(); ++ii)\n      basis_values_[ii] = basis_functions_.evaluate(quadrature_[ii].position());\n  }\n\n  template <class SourceType>\n  void apply(const SourceType& source, ReconstructedFunctionType& range, const XT::Common::Parameter& param) const\n  {\n    static_assert(is_discrete_function<SourceType>::value,\n                  \"SourceType has to be derived from DiscreteFunction (use the non-reconstructed values!)\");\n    LocalRealizabilityLimiterType local_realizability_limiter(analytical_flux_,\n                                                              source,\n                                                              range,\n                                                              basis_functions_,\n                                                              quadrature_,\n                                                              epsilon_,\n                                                              basis_values_,\n                                                              param,\n                                                              filename_,\n                                                              psi_vac_);\n    auto walker = XT::Grid::Walker<typename SourceType::SpaceType::GridLayerType>(source.space().grid_layer());\n    walker.append(local_realizability_limiter);\n    walker.walk(true);\n  } // void apply(...)\n\nprivate:\n  const AnalyticalFluxType& analytical_flux_;\n  const BasisfunctionType& basis_functions_;\n  const QuadratureType& quadrature_;\n  const RangeFieldType epsilon_;\n  std::vector<RangeType> basis_values_;\n  const std::string filename_;\n  const RangeFieldType psi_vac_;\n}; // class RealizabilityLimiter<...>\n\n\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_OPERATORS_FV_REALIZABILITY_HH\n", "meta": {"hexsha": "b75fe6de365ef8e607e48f5cbfeac10f469752d9", "size": 38760, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/operators/fv/entropybased/realizability.hh", "max_stars_repo_name": "TiKeil/dune-gdt", "max_stars_repo_head_hexsha": "25c8b987cc07a4b8b966c1a07ea21b78dba7852f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dune/gdt/operators/fv/entropybased/realizability.hh", "max_issues_repo_name": "TiKeil/dune-gdt", "max_issues_repo_head_hexsha": "25c8b987cc07a4b8b966c1a07ea21b78dba7852f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dune/gdt/operators/fv/entropybased/realizability.hh", "max_forks_repo_name": "TiKeil/dune-gdt", "max_forks_repo_head_hexsha": "25c8b987cc07a4b8b966c1a07ea21b78dba7852f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1028632025, "max_line_length": 120, "alphanum_fraction": 0.6784571723, "num_tokens": 9618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.24786533211253592}}
{"text": "#include \"self_adjoint_angular_flux.h\"\n#include <deal.II/dofs/dof_accessor.h>\n\ntemplate <int dim>\nSelfAdjointAngularFlux<dim>::SelfAdjointAngularFlux(\n    const std::string equation_name,\n    const dealii::ParameterHandler &prm,\n    std::shared_ptr<FundamentalData<dim>> &data_ptr)\n    : EquationBase<dim>(equation_name, prm, data_ptr) {}\n\n/*\n * =============================================================================\n * PUBLIC FUNCTIONS\n * =============================================================================\n */\n\ntemplate <int dim>\nvoid SelfAdjointAngularFlux<dim>::AssembleLinearForms (const int &g) {\n  if (have_reflective_bc_) {\n    for (int dir = 0; dir < n_dir_; ++dir) {\n      global_angular_flux_[this->GetCompInd(g, dir)] =\n          *(mat_vec_->sys_flxes[equ_name_][this->GetCompInd(g, dir)]);         \n    }\n  }\n  EquationBase<dim>::AssembleLinearForms(g);\n}\n\ntemplate<int dim>\nvoid SelfAdjointAngularFlux<dim>::IntegrateBoundaryBilinearForm (\n      typename dealii::DoFHandler<dim>::active_cell_iterator &,\n      const int &,\n      dealii::FullMatrix<double> &cell_matrix,\n      const int &,\n      const int &dir) {\n  \n  // Get the boundary ID and the normal vector\n  const dealii::Tensor<1, dim> normal_vector = fvf_->normal_vector(0);\n\n  double normal_dot_omega = normal_vector * omega_[dir];\n  \n  if (normal_dot_omega > 0) {\n    // Integrate bilinear term\n    for (int q = 0; q < n_qf_; ++q) {\n      for (int i = 0; i < dofs_per_cell_; ++i) {\n        for (int j = 0; j < dofs_per_cell_; ++j) {\n          cell_matrix(i,j) += normal_dot_omega *\n                              fvf_->shape_value(i, q) *\n                              fvf_->shape_value(j, q) *\n                              fvf_->JxW(q);\n        }\n      }\n    }\n  }\n}\n\ntemplate<int dim>\nvoid SelfAdjointAngularFlux<dim>::IntegrateBoundaryLinearForm (\n      typename dealii::DoFHandler<dim>::active_cell_iterator &cell,\n      const int &fn,/*face number*/\n      dealii::Vector<double> &cell_rhs,\n      const int &g,\n      const int &dir) {\n\n  // Get boundary id to determine if we have reflective BCs\n  int boundary_id = cell->face(fn)->boundary_id();\n\n  if (have_reflective_bc_ && is_reflective_bc_.at(boundary_id)) {\n  \n    // Get normal vector and dot product with omega\n    const dealii::Tensor<1, dim> normal_vector = fvf_->normal_vector(0);\n    double normal_dot_omega = normal_vector * omega_[dir];\n\n    if (normal_dot_omega < 0) {\n      // Retrieve previous iteration angular flux and get local values for the\n      // reflected angle\n      int reflected_dir = this->ref_dir_ind_[std::make_pair(boundary_id, dir)];\n      \n      std::vector<double> angular_flux(n_qf_);\n      fvf_->get_function_values(\n          global_angular_flux_[this->GetCompInd(g, reflected_dir)],\n          angular_flux);     \n      \n      for (int q = 0; q < n_qf_; ++q) {\n        for (int i = 0; i < dofs_per_cell_; ++i) {\n          cell_rhs(i) -= normal_dot_omega *\n                         fvf_->shape_value(i, q) *\n                         angular_flux[q] *\n                         fvf_->JxW(q);\n        }\n      }\n    }\n  }\n}\n\ntemplate<int dim>\nvoid SelfAdjointAngularFlux<dim>::IntegrateCellBilinearForm (\n      typename dealii::DoFHandler<dim>::active_cell_iterator &cell,\n      dealii::FullMatrix<double> &cell_matrix,\n      const int &g,\n      const int &dir) {\n  // Get material id for the given cell and cross-sections\n  int material_id = cell->material_id();\n  auto sigma_t = xsec_->sigt.at(material_id)[g];\n  auto inv_sigma_t = xsec_->inv_sigt.at(material_id)[g];\n\n  // Integrate and add both bilinear terms using precomputed values\n  for (int q = 0; q < n_q_; ++q) {\n    for (int i = 0; i < dofs_per_cell_; ++i) {\n      for (int j = 0; j < dofs_per_cell_; ++j) {\n\n        cell_matrix(i, j) += (pre_streaming_[{dir, q}](i, j) * inv_sigma_t\n                              +\n                              pre_collision_[q](i, j) * sigma_t) * fv_->JxW(q);\n      }\n    }\n  }\n}\n\ntemplate<int dim>\nvoid SelfAdjointAngularFlux<dim>::IntegrateCellFixedLinearForm (\n    typename dealii::DoFHandler<dim>::active_cell_iterator &cell,\n    dealii::Vector<double> &cell_rhs,\n    const int &g,\n    const int &dir) {\n  // get material id for the given cell\n  int material_id = cell->material_id();\n  \n  // SAAF has two fixed source terms, the first is proportional to q/4pi, the\n  // second contains an additional division by sigma_t. These two vectors hold\n  // these values, respectively, for each quadrature point.\n  std::vector<double> cell_q(n_q_);\n  std::vector<double> cell_q_over_total(n_q_);\n  \n  if (!is_eigen_problem_) {\n    \n    // Fill the two vectors with the appropriate q/4pi and q/4pi*sigma_t values\n    auto q_per_ster = xsec_->q_per_ster.at(material_id)[g];\n    std::fill(cell_q.begin(), cell_q.end(),\n              q_per_ster);\n    std::fill(cell_q_over_total.begin(), cell_q_over_total.end(),\n              q_per_ster * xsec_->inv_sigt.at(material_id)[g]);\n    \n  } else if (xsec_->is_material_fissile.at(material_id)) {    \n\n    // Fill the two vectors with the appropriate fission sources, summed\n    // over all groups\n    for (int group_in = 0; group_in < n_group_; ++group_in) {\n      // Retrieve cell scalar flux, inverse sigma t, fission terms\n      std::vector<double> group_cell_scalar_flux(n_q_);\n      this->GetGroupCellScalarFlux(group_cell_scalar_flux, group_in);\n      auto inv_sigma_t = xsec_->inv_sigt.at(material_id)[g];\n      auto scaled_fission_transfer =\n          scaled_fiss_transfer_.at(material_id)(group_in, g);\n      \n      for (int q = 0; q < n_q_; ++q) {\n        cell_q[q] +=\n            scaled_fission_transfer * group_cell_scalar_flux[q];\n        cell_q_over_total[q] +=\n            cell_q[q] * inv_sigma_t;\n      }\n    }    \n  }\n\n  //Integrate and add both source terms\n  for (int q = 0; q < n_q_; ++q) {\n    \n    cell_q[q] *= fv_->JxW(q);\n    cell_q_over_total[q] *= fv_->JxW(q);\n    \n    for (int i = 0; i < dofs_per_cell_; ++i) {\n      // First scattering term\n      cell_rhs(i) += fv_->shape_value(i, q) * cell_q[q];\n      // Second scattering term\n      cell_rhs(i) +=\n          omega_[dir] * fv_->shape_grad(i, q) * cell_q_over_total[q];\n    }\n  }\n}\n\ntemplate<int dim>\nvoid SelfAdjointAngularFlux<dim>::IntegrateScatteringLinearForm (\n      typename dealii::DoFHandler<dim>::active_cell_iterator &cell,\n      dealii::Vector<double> &cell_rhs,\n      const int &g,\n      const int &dir) {\n  // Get material id for the given cell:\n  int material_id = cell->material_id();\n\n  // SAAF has two scattering terms, the first is proportional to scalar flux\n  // time sigma_s over 4pi, the second has an additional division by sigma_t.\n  // These two vectors hold those values, respectively,  at each quadrature\n  // point:\n  std::vector<double> cell_scatter_flux(n_q_);\n  std::vector<double> cell_scatter_over_total_flux(n_q_);\n  \n  // Iterate over groups to populate cell_scatter_flux\n  for (int group_in = 0; group_in < n_group_; ++group_in) {\n    std::vector<double> group_cell_scalar_flux(n_q_);\n    this->GetGroupCellScalarFlux(group_cell_scalar_flux, group_in);\n\n    // Get needed cross-sections:\n    auto sigma_s_per_ster = xsec_->sigs_per_ster.at(material_id)(group_in, g);\n    auto inv_sigma_t = xsec_->inv_sigt.at(material_id)[g];\n    \n    // Fold group cell scalar flux into total cell scalar flux and multiply by\n    // appropriate cross-sections:\n    for (int q = 0; q < n_q_; ++q) {\n      cell_scatter_flux[q] += sigma_s_per_ster * group_cell_scalar_flux[q];\n      cell_scatter_over_total_flux[q] = cell_scatter_flux[q] * inv_sigma_t;\n    }\n  }\n\n  // Integrate and add both scattering terms\n  for (int q = 0; q < n_q_; ++q) {\n    cell_scatter_flux[q] *= fv_->JxW(q);\n    cell_scatter_over_total_flux[q] *= fv_->JxW(q);\n    for (int i = 0; i < dofs_per_cell_; ++i) {\n      // First scattering term\n      cell_rhs(i) += fv_->shape_value(i, q) * cell_scatter_flux[q];\n      // Second scattering term\n      cell_rhs(i) +=\n          omega_[dir] * fv_->shape_grad(i, q) * cell_scatter_over_total_flux[q];\n    }\n  }\n}\n\ntemplate <int dim>\nvoid SelfAdjointAngularFlux<dim>::PreassembleCellMatrices () {\n  // Reinitialize FEM values to an arbitrary cell (the first one) in the list of\n  // local cells.\n  fv_->reinit(dat_ptr_->local_cells[0]);\n\n  // For each quadrature angle, generate the Collision and Streaming matrices\n  for (int q = 0; q < n_q_; ++q) {\n\n    dealii::FullMatrix<double> temp_matrix(dofs_per_cell_, dofs_per_cell_);\n    \n    for (int i = 0; i < dofs_per_cell_; ++i) {\n      for (int j = 0; j < dofs_per_cell_; ++j) {\n        temp_matrix(i,j) =\n            (fv_->shape_value(i,q) * fv_->shape_value(j,q));\n      }\n    }\n    \n    pre_collision_[q] = temp_matrix;\n\n    temp_matrix = 0;\n    \n    // Streaming terms also depend on direction\n    for (int dir = 0; dir < n_dir_; ++dir) {\n      for (int i = 0; i < dofs_per_cell_; ++i) {\n        for (int j = 0; j < dofs_per_cell_; ++j) {\n          temp_matrix(i,j) =\n              (fv_->shape_grad(i,q) * omega_[dir])\n              *\n              (fv_->shape_grad(j,q) * omega_[dir]);\n        }\n      }\n      pre_streaming_[{dir, q}] = temp_matrix;\n    }\n  }\n}\n\n/*\n * =============================================================================\n * PROTECTED FUNCTIONS\n * =============================================================================\n */  \n\ntemplate <int dim>\nvoid SelfAdjointAngularFlux<dim>::GetGroupCellScalarFlux\n(std::vector<double> &to_fill, int group) {\n\n  // Get the global scalar flux for the current group\n  auto & group_global_scalar_flux =\n      mat_vec_->moments[equ_name_][std::make_tuple(group, 0, 0)];\n  // Evaluate the global scalar flux at the quadrature points of the current\n  // cell and store in return_vector (dealii function in FEValuesBase)\n  fv_->get_function_values(group_global_scalar_flux, to_fill);\n  \n} \n\ntemplate class SelfAdjointAngularFlux<1>;\ntemplate class SelfAdjointAngularFlux<2>;\ntemplate class SelfAdjointAngularFlux<3>;\n\n", "meta": {"hexsha": "d9a4882e35855e3298cd20e6a82fa70a276a4a38", "size": 9963, "ext": "cc", "lang": "C++", "max_stars_repo_path": "legacy_code/equation/self_adjoint_angular_flux.cc", "max_stars_repo_name": "narang-amit/BART", "max_stars_repo_head_hexsha": "22997c4ce6de3e97b39f4da4601edbd4cf73f9e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "legacy_code/equation/self_adjoint_angular_flux.cc", "max_issues_repo_name": "jsrehak/BART", "max_issues_repo_head_hexsha": "0460dfffbcf5671a730448de7f45cce39fd4a485", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "legacy_code/equation/self_adjoint_angular_flux.cc", "max_forks_repo_name": "jsrehak/BART", "max_forks_repo_head_hexsha": "0460dfffbcf5671a730448de7f45cce39fd4a485", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 34.7142857143, "max_line_length": 80, "alphanum_fraction": 0.6184884071, "num_tokens": 2678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24781554514906318}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <boost/algorithm/string.hpp>\n#include <ored/utilities/dategrid.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n#include <ql/settings.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n\nusing namespace QuantLib;\nusing namespace std;\n\nnamespace ore {\nnamespace data {\n\nDateGrid::DateGrid()\n    : dates_(1, Settings::instance().evaluationDate()), tenors_(1, 0 * Days), times_(1, 0.0),\n      timeGrid_(times_.begin(), times_.end()), isValuationDate_(1, true), isCloseOutDate_(1, false) {}\n\nDateGrid::DateGrid(const string& grid, const QuantLib::Calendar& gridCalendar, const QuantLib::DayCounter& dayCounter)\n    : calendar_(gridCalendar), dayCounter_(dayCounter) {\n\n    if (grid == \"ALPHA\") {\n        // ALPHA is\n        // quarterly up to 10Y,\n        // annual up to 30Y,\n        // quinquennial up to 100Y\n        for (Size i = 1; i < 40; i++) { // 3M up to 39*3M = 117M = 9Y9M\n            Period p(i * 3, Months);\n            p.normalize();\n            tenors_.push_back(p);\n        }\n        for (Size i = 10; i < 30; i++) // 10Y up to 29Y\n            tenors_.push_back(Period(i, Years));\n        for (Size i = 30; i < 105; i += 5) // 30Y up to 100Y\n            tenors_.push_back(Period(i, Years));\n    } else if (grid == \"BETA\") {\n        // BETA is\n        // monthly up to 10Y,\n        // quarterly up to 20Y,\n        // annually up to 50Y,\n        // quinquennial up to 100Y\n        for (Size i = 1; i < 119; i++) {\n            Period p = i * Months;\n            p.normalize();\n            tenors_.push_back(p);\n        }\n        for (Size i = 40; i < 80; i++) {\n            Period p = i * 3 * Months;\n            p.normalize();\n            tenors_.push_back(p);\n        }\n        for (Size i = 20; i < 50; i++)\n            tenors_.push_back(i * Years);\n        for (Size i = 50; i <= 100; i += 5)\n            tenors_.push_back(i * Years);\n    } else { // uniform grid of format \"numPillars,spacing\" (e.g. 40,1M)\n        vector<string> tokens;\n        boost::split(tokens, grid, boost::is_any_of(\",\"));\n        if (tokens.size() <= 2) {\n            // uniform grid of format \"numPillars,spacing\" (e.g. 40,1M)\n            Period gridTenor = 1 * Years; // default\n            Size gridSize = atoi(tokens[0].c_str());\n            QL_REQUIRE(gridSize > 0, \"Invalid DateGrid string \" << grid);\n            if (tokens.size() == 2)\n                gridTenor = data::parsePeriod(tokens[1]);\n            if (gridTenor == Period(1, Days)) {\n                // we have a daily grid. Period and Calendar are not consistant with\n                // working & actual days, so we set the tenor grid\n                Date today = Settings::instance().evaluationDate();\n                Date d = today;\n                for (Size i = 0; i < gridSize; i++) {\n                    d = gridCalendar.advance(d, Period(1, Days), Following); // next working day\n                    Size n = d - today;\n                    tenors_.push_back(Period(n, Days));\n                }\n            } else {\n                for (Size i = 0; i < gridSize; i++)\n                    tenors_.push_back((i + 1) * gridTenor);\n            }\n        } else {\n            // New style : 1D,2D,1W,2W,3Y,5Y,....\n            for (Size i = 0; i < tokens.size(); i++)\n                tenors_.push_back(data::parsePeriod(tokens[i]));\n        }\n    }\n    buildDates(gridCalendar, dayCounter);\n}\n\nDateGrid::DateGrid(const vector<Period>& tenors, const QuantLib::Calendar& gridCalendar,\n                   const QuantLib::DayCounter& dayCounter)\n    : calendar_(gridCalendar), dayCounter_(dayCounter), tenors_(tenors) {\n    QL_REQUIRE(!tenors_.empty(), \"DateGrid requires a non-empty vector of tenors\");\n    QL_REQUIRE(is_sorted(tenors_.begin(), tenors_.end()),\n               \"Construction of DateGrid requires a sorted vector of unique tenors\");\n    buildDates(gridCalendar, dayCounter);\n}\n\nDateGrid::DateGrid(const vector<Date>& dates, const QuantLib::Calendar& cal, const DayCounter& dayCounter)\n    : calendar_(cal), dayCounter_(dayCounter), dates_(dates) {\n    QL_REQUIRE(!dates_.empty(), \"Construction of DateGrid requires a non-empty vector of dates\");\n    QL_REQUIRE(is_sorted(dates_.begin(), dates_.end()),\n               \"Construction of DateGrid requires a sorted vector of unique dates\");\n    Date today = Settings::instance().evaluationDate();\n    QL_REQUIRE(today < dates_.front(),\n               \"Construction of DateGrid requires first element to be strictly greater than today\");\n\n    // Populate the tenors, times and timegrid\n    tenors_.resize(dates_.size());\n    times_.resize(dates_.size());\n    for (Size i = 0; i < dates_.size(); i++) {\n        tenors_[i] = (dates_[i] - today) * Days;\n        times_[i] = dayCounter.yearFraction(today, dates_[i]);\n    }\n    timeGrid_ = TimeGrid(times_.begin(), times_.end());\n    isValuationDate_ = std::vector<bool>(dates_.size(), true);\n    isCloseOutDate_ = std::vector<bool>(dates_.size(), false);\n\n    // Log the date grid\n    log();\n}\n\nvoid DateGrid::buildDates(const QuantLib::Calendar& cal, const QuantLib::DayCounter& dc) {\n    // build dates from tenors\n    // this is called by both constructors\n    dates_.resize(tenors_.size());\n    Date today = Settings::instance().evaluationDate();\n    for (Size i = 0; i < tenors_.size(); i++) {\n        if (tenors_[i].units() == Days)\n            dates_[i] = cal.adjust(today + tenors_[i]);\n        else\n            dates_[i] = cal.advance(today, tenors_[i], Following, false);\n        if (i > 0) {\n            QL_REQUIRE(dates_[i] >= dates_[i - 1], \"DateGrid::buildDates(): tenors must be monotonic\");\n            if (dates_[i] == dates_[i - 1]) {\n                dates_.erase(std::next(dates_.begin(), i));\n                tenors_.erase(std::next(tenors_.begin(), i));\n                --i;\n            }\n        }\n    }\n\n    // Build times\n    times_.resize(dates_.size());\n    for (Size i = 0; i < dates_.size(); i++)\n        times_[i] = dc.yearFraction(today, dates_[i]);\n\n    timeGrid_ = TimeGrid(times_.begin(), times_.end());\n    isValuationDate_ = std::vector<bool>(dates_.size(), true);\n    isCloseOutDate_ = std::vector<bool>(dates_.size(), false);\n\n    // Log the date grid\n    log();\n}\n\nvoid DateGrid::log() {\n    DLOG(\"DateGrid constructed, size = \" << size());\n    for (Size i = 0; i < tenors_.size(); i++)\n        DLOG(\"[\" << setw(2) << i << \"] Tenor:\" << tenors_[i] << \", Date:\" << io::iso_date(dates_[i])\n                 << \", Valuation:\" << isValuationDate_[i] << \", CloseOut:\" << isCloseOutDate_[i]);\n}\n\nvoid DateGrid::truncate(const Date& d, bool overrun) {\n    if (d >= dates_.back())\n        return; // no need for any truncation\n    DLOG(\"Truncating DateGrid beyond \" << QuantLib::io::iso_date(d));\n    vector<Date>::iterator it = std::upper_bound(dates_.begin(), dates_.end(), d);\n    if (overrun)\n        ++it;\n    dates_.erase(it, dates_.end());\n    tenors_.resize(dates_.size());\n    times_.resize(dates_.size());\n    timeGrid_ = TimeGrid(times_.begin(), times_.end());\n    DLOG(\"DateGrid size now \" << dates_.size());\n}\n\nvoid DateGrid::truncate(Size len) {\n    // Truncate grid up length len\n    if (dates_.size() > len) {\n        DLOG(\"Truncating DateGrid, removing elements \" << dates_[len] << \" to \" << dates_.back());\n        dates_.resize(len);\n        tenors_.resize(len);\n        times_.resize(len);\n        timeGrid_ = TimeGrid(times_.begin(), times_.end());\n        isValuationDate_.resize(len);\n        isCloseOutDate_.resize(len);\n        DLOG(\"DateGrid size now \" << dates_.size());\n    }\n}\n\nvoid DateGrid::addCloseOutDates(const QuantLib::Period& p) {\n    if (p == QuantLib::Period(0, QuantLib::Days)) {\n        for (Size i = 0; i < dates_.size(); ++i) {\n            if (i == 0) {\n                isCloseOutDate_.front() = false;\n                isValuationDate_.front() = true;\n            } else if (i == dates_.size() - 1) {\n                isCloseOutDate_.back() = true;\n                isValuationDate_.back() = false;\n            } else {\n                isCloseOutDate_[i] = true;\n                isValuationDate_[i] = true;\n            }\n        }\n    } else {\n        std::vector<Date> tmpDates;\n        std::vector<bool> tmpIsCloseOutDate, tmpIsValuationDate;\n        for (Size i = 0; i < dates_.size(); ++i) {\n            Date c;\n            if (p.units() == Days)\n                c = calendar_.adjust(dates_[i] + p);\n            else\n                c = calendar_.advance(dates_[i], p, Following, false);\n            if (i < dates_.size() - 1) {\n                // adjust the grid to ensure no overlap in valuation and closeout dates\n                if (c >= dates_[i + 1]) {\n                    dates_[i + 1] = calendar_.advance(c, QuantLib::Period(1, QuantLib::Days));\n                    std::cout << QuantLib::io::iso_date(dates_[i + 1]) << std::endl;\n                    // check that the grid is still monotonic\n                    if ((i + 2) < dates_.size()) {\n                        QL_REQUIRE(dates_[i + 1] < dates_[i + 2],\n                                   \"date grid is no longer monotonic: \" << dates_[i + 1] << \", \" << dates_[i + 2]);\n                    }\n                }\n                QL_REQUIRE(c < dates_[i + 1],\n                           \"close out date \" << c << \" does not lie before next grid date \" << dates_[i + 1]);\n            }\n            tmpDates.push_back(dates_[i]);\n            tmpDates.push_back(c);\n            tmpIsCloseOutDate.push_back(false);\n            tmpIsCloseOutDate.push_back(true);\n            tmpIsValuationDate.push_back(true);\n            tmpIsValuationDate.push_back(false);\n        }\n        dates_ = tmpDates;\n        isCloseOutDate_ = tmpIsCloseOutDate;\n        isValuationDate_ = tmpIsValuationDate;\n        // FIXME ... (is that needed anywhere ?)\n        tenors_ = std::vector<QuantLib::Period>(dates_.size(), 0 * Days);\n        times_.resize(dates_.size());\n        Date today = Settings::instance().evaluationDate();\n        for (Size i = 0; i < dates_.size(); i++)\n            times_[i] = dayCounter_.yearFraction(today, dates_[i]);\n        timeGrid_ = TimeGrid(times_.begin(), times_.end());\n    }\n    // Log Grid\n    DLOG(\"Added Close Out Dates to DateGrid , size = \" << size());\n    log();\n}\n\nstd::vector<QuantLib::Date> DateGrid::valuationDates() const {\n    std::vector<Date> res;\n    for (Size i = 0; i < dates_.size(); ++i) {\n        if (isValuationDate_[i])\n            res.push_back(dates_[i]);\n    }\n    return res;\n}\n\nstd::vector<QuantLib::Date> DateGrid::closeOutDates() const {\n    std::vector<Date> res;\n    for (Size i = 0; i < dates_.size(); ++i) {\n        if (isCloseOutDate_[i])\n            res.push_back(dates_[i]);\n    }\n    return res;\n}\n\nQuantLib::TimeGrid DateGrid::valuationTimeGrid() const {\n    std::vector<Real> times;\n    Date today = Settings::instance().evaluationDate();\n    for (Size i = 0; i < dates_.size(); ++i) {\n        if (isValuationDate_[i])\n            times.push_back(dayCounter_.yearFraction(today, dates_[i]));\n    }\n    return TimeGrid(times.begin(), times.end());\n}\n\nQuantLib::TimeGrid DateGrid::closeOutTimeGrid() const {\n    std::vector<Real> times;\n    Date today = Settings::instance().evaluationDate();\n    for (Size i = 0; i < dates_.size(); ++i) {\n        if (isCloseOutDate_[i])\n            times.push_back(dayCounter_.yearFraction(today, dates_[i]));\n    }\n    return TimeGrid(times.begin(), times.end());\n}\n\nboost::shared_ptr<DateGrid> generateShiftedDateGrid(const boost::shared_ptr<DateGrid>& dg,\n                                                    const QuantLib::Period& shift) {\n    DLOG(\"Building shifted date grid with shift of \" << shift);\n    vector<Date> defaultDates = dg->dates();\n    vector<Date> closeOutDates;\n    for (auto d : defaultDates) {\n        Date closeOut = dg->calendar().adjust(d + shift);\n        closeOutDates.push_back(closeOut);\n    }\n    boost::shared_ptr<DateGrid> newDg = boost::make_shared<DateGrid>(closeOutDates, dg->calendar(), dg->dayCounter());\n    return newDg;\n}\n\nboost::shared_ptr<DateGrid> combineDateGrids(const boost::shared_ptr<DateGrid>& dg1,\n                                             const boost::shared_ptr<DateGrid>& dg2) {\n    DLOG(\"Combining date grids\");\n    vector<Date> combinedVec;\n    vector<Date> dates1 = dg1->dates();\n    vector<Date> dates2 = dg2->dates();\n    combinedVec.reserve(dates1.size() + dates2.size());\n    combinedVec.insert(combinedVec.end(), dates1.begin(), dates1.end());\n    combinedVec.insert(combinedVec.end(), dates2.begin(), dates2.end());\n    std::sort(combinedVec.begin(), combinedVec.end());\n    auto last = std::unique(combinedVec.begin(), combinedVec.end());\n    combinedVec.erase(last, combinedVec.end());\n    // FIXME: Check that grid calendars and day counters match?\n    boost::shared_ptr<DateGrid> newDg = boost::make_shared<DateGrid>(combinedVec, dg1->calendar(), dg1->dayCounter());\n    return newDg;\n}\n\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "d417062e607c02f0abab58bcbc644a862e2cefd9", "size": 13665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/utilities/dategrid.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "OREData/ored/utilities/dategrid.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "OREData/ored/utilities/dategrid.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 40.5489614243, "max_line_length": 118, "alphanum_fraction": 0.5806073911, "num_tokens": 3576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24781554514906315}}
{"text": "#pragma once\n\n#include <mtao/geometry/volume.h>\n#include <Eigen/Sparse>\n#include <mtao/geometry/mesh/compactify.hpp>\n#include <mtao/eigen/stack.h>\n#include <vector>\n#include \"mandoline/cutface.hpp\"\n#include \"cutmesh.pb.h\"\nnamespace mandoline {\nstruct CutCell : public std::map<int, bool> {\n\n    using coord_type = std::array<int, 3>;\n    int index = -1;\n    int region = -1;\n    coord_type grid_cell;\n\n    operator std::string() const;\n    void serialize(protobuf::CutCell &) const;\n    static CutCell from_proto(const protobuf::CutCell &);\n\n    std::vector<Eigen::Triplet<double>> boundary_triplets() const;\n    mtao::ColVecs3i triangulated(const std::vector<CutFace<3>> &Fs) const;\n    std::tuple<mtao::ColVecs3d, mtao::ColVecs3i> triangulated_with_additional_vertices(const std::vector<CutFace<3>> &Fs, int vertex_offset) const;\n\n    /*\n           coord_type grid_cell(const std::vector<CutFace<3>>& F) const;\n           */\n\n    template<typename Derived>\n    double volume(const Eigen::MatrixBase<Derived> &V, const mtao::vector<CutFace<3>> &Fs) const;\n    double volume(const mtao::VecXd &face_brep_vols) const;\n    template<typename Derived>\n    mtao::Vec3d centroid(const Eigen::MatrixBase<Derived> &V, const mtao::vector<CutFace<3>> &Fs) const;\n    mtao::Vec3d moment(const mtao::ColVecs3d &face_brep_cents) const;\n    template<typename Derived>\n    std::tuple<mtao::ColVecs3d, mtao::ColVecs3i> get_mesh(const Eigen::MatrixBase<Derived> &V, const mtao::vector<CutFace<3>> &Fs) const;\n\n\n    template<typename Derived, typename VecType>\n    bool contains(const Eigen::MatrixBase<Derived> &V, const mtao::vector<CutFace<3>> &Fs, const Eigen::MatrixBase<VecType> &v) const;\n\n    template<typename Derived, typename VecType>\n    double solid_angle(const Eigen::MatrixBase<Derived> &V, const mtao::vector<CutFace<3>> &Fs, const Eigen::MatrixBase<VecType> &v) const;\n\n\n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n};\n\n\ntemplate<typename Derived>\ndouble CutCell::volume(const Eigen::MatrixBase<Derived> &V, const mtao::vector<CutFace<3>> &Fs) const {\n\n    double vol = 0;\n\n    for (auto &&[f, b] : *this) {\n        auto &&F = Fs[f];\n        double sign = b ? 1 : -1;\n        vol += sign * Fs[f].brep_volume(V);\n    }\n    return vol;\n}\ntemplate<typename Derived>\nmtao::Vec3d CutCell::centroid(const Eigen::MatrixBase<Derived> &V, const mtao::vector<CutFace<3>> &Fs) const {\n\n    double vol = 0;\n    mtao::Vec3d mom = mtao::Vec3d::Zero();\n\n    for (auto &&[f, b] : *this) {\n        auto &&F = Fs[f];\n        double sign = b ? 1 : -1;\n        vol += sign * Fs[f].brep_volume(V);\n        mom += sign * Fs[f].brep_centroid(V);\n    }\n    mom /= vol;\n    return mom;\n}\ntemplate<typename Derived>\nstd::tuple<mtao::ColVecs3d, mtao::ColVecs3i> CutCell::get_mesh(const Eigen::MatrixBase<Derived> &V, const mtao::vector<CutFace<3>> &Fs) const {\n    std::vector<mtao::ColVecs3i> FF;\n    for (auto &&[fidx, s] : *this) {\n        auto &&f = Fs[fidx];\n        assert(bool(f.triangulation));\n        FF.push_back(*f.triangulation);\n    }\n    auto F = mtao::eigen::hstack_iter(FF.begin(), FF.end());\n    return mtao::geometry::mesh::compactify(V, F);\n}\n\ntemplate<typename Derived, typename VecType>\nbool CutCell::contains(const Eigen::MatrixBase<Derived> &V, const mtao::vector<CutFace<3>> &Fs, const Eigen::MatrixBase<VecType> &v) const {\n    //> 4 * M_PI, but with some slack\n    return solid_angle(V, Fs, v) > .5;\n}\ntemplate<typename Derived, typename VecType>\ndouble CutCell::solid_angle(const Eigen::MatrixBase<Derived> &V, const mtao::vector<CutFace<3>> &Fs, const Eigen::MatrixBase<VecType> &v) const {\n    double sa = 0;\n    for (auto &&[fid, sgn] : *this) {\n        sa += (sgn ? -1 : 1) * Fs[fid].solid_angle(V, v);\n    }\n    return sa;\n}\n}// namespace mandoline\n", "meta": {"hexsha": "51b2eb351df89853bd5a11e60bcd0831245bf6ba", "size": 3746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mandoline/cutcell.hpp", "max_stars_repo_name": "mtao/mandoline", "max_stars_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 54.0, "max_stars_repo_stars_event_min_datetime": "2019-11-12T11:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T11:09:19.000Z", "max_issues_repo_path": "include/mandoline/cutcell.hpp", "max_issues_repo_name": "mtao/mandoline", "max_issues_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-17T01:49:44.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-29T19:46:36.000Z", "max_forks_repo_path": "include/mandoline/cutcell.hpp", "max_forks_repo_name": "mtao/mandoline", "max_forks_repo_head_hexsha": "79438c5b210a2ca4b9f72cbfd2879a9ae6a665da", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T02:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-19T06:15:22.000Z", "avg_line_length": 36.0192307692, "max_line_length": 147, "alphanum_fraction": 0.6644420715, "num_tokens": 1151, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.24781553845395157}}
{"text": "#include <df/optimization/deformationGraphRegularization.h>\n\n#include <vector>\n#include <Eigen/Core>\n\n#include <df/util/dualQuaternion.h> // TODO\n#include <df/util/typeList.h>\n\nnamespace df {\n\ntemplate <typename Scalar, typename ScalarOpt, int Options, template <typename,int...> class TransformT>\ninline void computeEdgeResidual(const Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> & vertexA, const TransformT<Scalar,Options> & transformA,\n                                const Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> & vertexB, const TransformT<Scalar,Options> & transformB,\n                                Eigen::Matrix<ScalarOpt,3,1,Eigen::DontAlign> & residual,\n                                Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> & vertexADisplacementByTransformA,\n                                Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> & vertexADisplacementByTransformB,\n                                Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> & vertexARelativeToVertexB) {\n\n    typedef Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> Vec3;\n\n    vertexADisplacementByTransformA = transformA.translation();\n\n    vertexARelativeToVertexB = vertexA - vertexB;\n\n    vertexADisplacementByTransformB = transformB * vertexARelativeToVertexB;\n\n    const Vec3 vertexAWarpedByTransformA = vertexA + vertexADisplacementByTransformA;\n\n    const Vec3 vertexAWarpedByTransformB = vertexB + vertexADisplacementByTransformB;\n\n    residual = (vertexAWarpedByTransformA - vertexAWarpedByTransformB).template cast<ScalarOpt>();\n\n}\n\ntemplate <typename Scalar, typename ScalarOpt, template <typename,int...> class TransformT>\ninline void fillEdgeJacobianAndResidual(const Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> & vertexA, const TransformT<Scalar> & transformA,\n                                        const Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> & vertexB, const TransformT<Scalar> & transformB,\n                                        internal::JacobianAndResidual<ScalarOpt,3,12> & jacobianAndResidual,\n                                        const IntToType<internal::TransformUpdateLeftMultiply> ) {\n\n    typedef Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> Vec3;\n\n    Vec3 vertexADisplacementByTransformA, vertexADisplacementByTransformB, vertexARelativeToVertexB;\n\n    computeEdgeResidual(vertexA,transformA,vertexB,transformB,jacobianAndResidual.r,\n                        vertexADisplacementByTransformA, vertexADisplacementByTransformB,\n                        vertexARelativeToVertexB);\n\n    // the first block is for vertex A\n    jacobianAndResidual.J.template block<3,6>(0,0) << 1, 0, 0,  0, vertexADisplacementByTransformA(2), -vertexADisplacementByTransformA(1),\n                                                      0, 1, 0,  -vertexADisplacementByTransformA(2), 0, vertexADisplacementByTransformA(0),\n                                                      0, 0, 1,  vertexADisplacementByTransformA(1), -vertexADisplacementByTransformA(0), 0;\n\n    // the second block is for vertex B\n    jacobianAndResidual.J.template block<3,6>(0,6) << -1,  0,  0,  0, -vertexADisplacementByTransformB(2), vertexADisplacementByTransformB(1),\n                                                       0, -1,  0,  vertexADisplacementByTransformB(2), 0, -vertexADisplacementByTransformB(0),\n                                                       0,  0, -1,  -vertexADisplacementByTransformB(1), vertexADisplacementByTransformB(0), 0;\n\n}\n\ntemplate <typename Scalar, typename ScalarOpt, template <typename,int...> class TransformT>\ninline void fillEdgeJacobianAndResidual(const Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> & vertexA, const TransformT<Scalar> & transformA,\n                                        const Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> & vertexB, const TransformT<Scalar> & transformB,\n                                        internal::JacobianAndResidual<ScalarOpt,3,12> & jacobianAndResidual,\n                                        const IntToType<internal::TransformUpdateRightMultiply> ) {\n\n    typedef Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> Vec3;\n    typedef Eigen::Matrix<ScalarOpt,3,3,Eigen::DontAlign> Mat3;\n\n    Vec3 vertexADisplacementByTransformA, vertexADisplacementByTransformB, vertexARelativeToVertexB;\n\n    computeEdgeResidual(vertexA,transformA,vertexB,transformB,jacobianAndResidual.r,\n                        vertexADisplacementByTransformA, vertexADisplacementByTransformB,\n                        vertexARelativeToVertexB);\n\n    // the first block is for vertex A\n    jacobianAndResidual.J.template block<3,3>(0,0) = transformA.rotationMatrix().template cast<ScalarOpt>();\n    jacobianAndResidual.J.template block<3,3>(0,3) = Mat3::Zero();\n\n    // the second block is for vertex B\n    jacobianAndResidual.J.template block<3,3>(0,6) = -transformB.rotationMatrix().template cast<ScalarOpt>();\n\n    Mat3 partial;\n    partial << 0, vertexARelativeToVertexB(2), -vertexARelativeToVertexB(1),\n               -vertexARelativeToVertexB(2), 0, vertexARelativeToVertexB(0),\n               vertexARelativeToVertexB(1), -vertexARelativeToVertexB(0), 0;\n\n    jacobianAndResidual.J.template block<3,3>(0,9) = -transformB.rotationMatrix().template cast<ScalarOpt>()*partial;\n\n}\n\ntemplate <typename Scalar, uint Rows>\nstruct JacobianFillColUnroller {\n\n    typedef Eigen::Triplet<Scalar> Triplet;\n\n    inline static void fill(std::vector<Triplet> & globalJacobianTriplets,\n                            const Eigen::Matrix<Scalar,Rows,1,Eigen::DontAlign> & localJacobianColumn,\n                            const uint firstRowIndex, const uint columnIndex) {\n\n//        std::cout << \"colFill \" << firstRowIndex << \", \" << columnIndex << \":\" << std::endl << localJacobianColumn << std::endl << std::endl;\n\n        const Scalar & localVal = localJacobianColumn(0);\n\n        if (localVal != Scalar(0)) {\n\n            globalJacobianTriplets.push_back(Triplet(firstRowIndex,columnIndex,localVal));\n\n        }\n\n        JacobianFillColUnroller<Scalar,Rows-1>::fill(globalJacobianTriplets,\n                                                     localJacobianColumn.template tail<Rows-1>(),\n                                                     firstRowIndex+1,columnIndex);\n\n    }\n\n};\n\ntemplate <typename Scalar>\nstruct JacobianFillColUnroller<Scalar,0> {\n\n    typedef Eigen::Triplet<Scalar> Triplet;\n\n    inline static void fill(std::vector<Triplet> & /*globalJacobianTriplets*/,\n                            const Eigen::Matrix<Scalar,0,1,Eigen::DontAlign> & /*localJacobianColumn*/,\n                            const uint /*firstRowIndex*/, const uint /*columnIndex*/) { }\n\n};\n\ntemplate <typename Scalar, uint Rows, uint Cols>\nstruct JacobianFillUnroller {\n\n    typedef Eigen::Triplet<Scalar> Triplet;\n\n    inline static void fill(std::vector<Triplet> & globalJacobianTriplets,\n                            const Eigen::Matrix<Scalar,Rows,Cols,Eigen::DontAlign> & localJacobian,\n                            const uint firstRowIndex, const uint firstColumnIndex) {\n\n//        std::cout << \"matFill \" << firstRowIndex << \", \" << firstColumnIndex << \":\" << std::endl << localJacobian << std::endl << std::endl;\n\n        JacobianFillColUnroller<Scalar,Rows>::fill(globalJacobianTriplets,\n                                                   localJacobian.template block<Rows,1>(0,0),\n                                                   firstRowIndex, firstColumnIndex);\n\n        JacobianFillUnroller<Scalar,Rows,Cols-1>::fill(globalJacobianTriplets,\n                                                       localJacobian.template block<Rows,Cols-1>(0,1),\n                                                       firstRowIndex, firstColumnIndex + 1);\n\n    }\n\n};\n\n\ntemplate <typename Scalar, uint Rows>\nstruct JacobianFillUnroller<Scalar,Rows,0> {\n\n    typedef Eigen::Triplet<Scalar> Triplet;\n\n    inline static void fill(std::vector<Triplet> & /*globalJacobianTriplets*/,\n                            const Eigen::Matrix<Scalar,Rows,0,Eigen::DontAlign> & /*localJacobian*/,\n                            const uint /*firstRowIndex*/, const uint /*firstColumnIndex*/) { }\n\n};\n\ntemplate <typename Scalar, typename ScalarOpt, template <typename,int...> class TransformT, internal::TransformUpdateMethod U>\nvoid fillRegularizationResidualAndJacobianTripletList(std::vector<Eigen::Triplet<ScalarOpt> > & globalJacobianTripletList,\n                                                      Eigen::Matrix<ScalarOpt,Eigen::Dynamic,1> & globalResidual,\n                                                      const NonrigidTransformer<Scalar,TransformT> & transformer) {\n\n    typedef typename NonrigidTransformer<Scalar,TransformT>::Transform Transform;\n    typedef Eigen::Matrix<Scalar,3,1,Eigen::DontAlign> Vec3;\n\n    static constexpr uint ResidualDim = 3;\n    static constexpr uint BlockDim = 6;\n\n    uint runningRowCounter = 0;\n\n    uint lowerLevelParameterStart = 0;\n    uint higherLevelParameterStart;\n\n    for (uint level = 0; level < transformer.numRegularizationTreeLevels() - 1; ++level) {\n\n        const uint numLowerLevelVertices = transformer.numVerticesAtLevel(level);\n\n        higherLevelParameterStart = lowerLevelParameterStart + numLowerLevelVertices*BlockDim;\n\n        for (uint lowerLevelIndex = 0; lowerLevelIndex < numLowerLevelVertices; ++lowerLevelIndex) {\n\n            const Vec3 & lowerLevelVertex = transformer.deformationGraphVertices(level)[lowerLevelIndex];\n\n            const Transform & lowerLevelTransform = transformer.transforms(level)[lowerLevelIndex];\n\n            const uint numNeighbors = transformer.numHigherLevelNeighbors(level,lowerLevelIndex);\n\n            for (uint k = 0; k < numNeighbors; ++k) {\n\n                const uint higherLevelIndex = transformer.higherLevelNeighbors(level,lowerLevelIndex)[k];\n\n                const Vec3 & higherLevelVertex = transformer.deformationGraphVertices(level+1)[higherLevelIndex];\n\n                const Transform & higherLevelTransform = transformer.transforms(level+1)[higherLevelIndex];\n\n                internal::JacobianAndResidual<ScalarOpt,ResidualDim,2*BlockDim> jacobianAndResidual;\n\n                fillEdgeJacobianAndResidual(lowerLevelVertex,lowerLevelTransform,\n                                            higherLevelVertex,higherLevelTransform,\n                                            jacobianAndResidual,IntToType<U>());\n\n//                std::cout << level << \", \" << lowerLevelIndex << \", \" << k << \": \" << std::endl << jacobianAndResidual.J << std::endl << std::endl;\n\n//                std::vector<Eigen::Triplet<ScalarOpt> > localTripletList;\n//                JacobianFillUnroller<ScalarOpt,ResidualDim,BlockDim>::fill(localTripletList,jacobianAndResidual.J.template block<ResidualDim,BlockDim>(0,0),\n//                                                                           0, lowerLevelParameterStart + lowerLevelIndex*BlockDim);\n\n//                JacobianFillUnroller<ScalarOpt,ResidualDim,BlockDim>::fill(localTripletList,jacobianAndResidual.J.template block<ResidualDim,BlockDim>(0,BlockDim),\n//                                                                           0, higherLevelParameterStart + higherLevelIndex*BlockDim);\n//                Eigen::SparseMatrix<ScalarOpt> localJacobian(3,transformer.numVerticesTotal()*BlockDim);\n//                localJacobian.setFromTriplets(localTripletList.begin(),localTripletList.end());\n//                localJacobian.finalize();\n//                std::cout << localJacobian.toDense() << std::endl << std::endl;\n\n                JacobianFillUnroller<ScalarOpt,ResidualDim,BlockDim>::fill(globalJacobianTripletList,jacobianAndResidual.J.template block<ResidualDim,BlockDim>(0,0),\n                                                                           runningRowCounter, lowerLevelParameterStart + lowerLevelIndex*BlockDim);\n\n                JacobianFillUnroller<ScalarOpt,ResidualDim,BlockDim>::fill(globalJacobianTripletList,jacobianAndResidual.J.template block<ResidualDim,BlockDim>(0,BlockDim),\n                                                                           runningRowCounter, higherLevelParameterStart + higherLevelIndex*BlockDim);\n\n//                std::cout << \"(\" << runningRowCounter << \" - \" << (runningRowCounter + ResidualDim) << \") / \" << globalResidual.rows() << std::endl;\n                globalResidual.template block<ResidualDim,1>(runningRowCounter,0) = jacobianAndResidual.r;\n\n                runningRowCounter += ResidualDim;\n\n\n                fillEdgeJacobianAndResidual(higherLevelVertex,higherLevelTransform,\n                                            lowerLevelVertex,lowerLevelTransform,\n                                            jacobianAndResidual,IntToType<U>());\n\n//                std::cout << level << \", \" << lowerLevelIndex << \", \" << k << \": \" << std::endl << jacobianAndResidual.J << std::endl << std::endl;\n\n\n                JacobianFillUnroller<ScalarOpt,ResidualDim,BlockDim>::fill(globalJacobianTripletList,jacobianAndResidual.J.template block<ResidualDim,BlockDim>(0,BlockDim),\n                                                                           runningRowCounter, lowerLevelParameterStart + lowerLevelIndex*BlockDim);\n\n                JacobianFillUnroller<ScalarOpt,ResidualDim,BlockDim>::fill(globalJacobianTripletList,jacobianAndResidual.J.template block<ResidualDim,BlockDim>(0,0),\n                                                                           runningRowCounter, higherLevelParameterStart + higherLevelIndex*BlockDim);\n\n//                std::cout << \"(\" << runningRowCounter << \" - \" << (runningRowCounter + ResidualDim) << \") / \" << globalResidual.rows() << std::endl;\n                globalResidual.template block<ResidualDim,1>(runningRowCounter,0) = jacobianAndResidual.r;\n\n                runningRowCounter += ResidualDim;\n\n            }\n\n        }\n\n        lowerLevelParameterStart = higherLevelParameterStart;\n\n    }\n\n}\n\ntemplate <typename Scalar, typename ScalarOpt, template <typename,int...> class TransformT, internal::TransformUpdateMethod U>\nvoid computeRegularizerNormalEquations(const NonrigidTransformer<Scalar,TransformT> & transformer,\n                                       Eigen::SparseMatrix<ScalarOpt> & JTJ,\n                                       Eigen::Matrix<ScalarOpt,Eigen::Dynamic,1> & JTr) {\n\n    // TODO: come up with a nice way to compute only the upper triangle of JTJ,\n    // as that is the only part used in the solver anyway\n\n    typedef Eigen::Triplet<ScalarOpt> Triplet;\n    typedef Eigen::SparseMatrix<ScalarOpt> SparseMatX;\n    typedef Eigen::Matrix<ScalarOpt,Eigen::Dynamic,1> VecX;\n\n    static constexpr uint ResidualDim = 3;\n    static constexpr uint BlockDim = 6;\n    // TODO TODO TODO:\n    static constexpr uint NumNeighbors = 4;\n\n    const uint numTotalDeformationGraphVertices = transformer.numVerticesTotal();\n\n    const uint numTopLevelVertices = transformer.numVerticesAtLevel(transformer.numRegularizationTreeLevels()-1);\n\n    const uint totalResidualRows = 2 * (numTotalDeformationGraphVertices - numTopLevelVertices) * ResidualDim * NumNeighbors;\n\n    std::vector<Triplet> globalJacobianTriplets;\n    globalJacobianTriplets.reserve(totalResidualRows*2*BlockDim);\n\n    VecX globalResidual(totalResidualRows);\n\n    fillRegularizationResidualAndJacobianTripletList<Scalar,ScalarOpt,TransformT,U>(globalJacobianTriplets,globalResidual,transformer);\n\n    const uint totalModelDimension = numTotalDeformationGraphVertices * BlockDim;\n\n    SparseMatX globalJacobian(totalResidualRows,totalModelDimension);\n\n    globalJacobian.setFromTriplets(globalJacobianTriplets.begin(),globalJacobianTriplets.end());\n\n    globalJacobian.finalize();\n\n    JTJ = globalJacobian.transpose()*globalJacobian;\n\n    JTr = globalJacobian.transpose()*globalResidual;\n}\n\ntemplate void computeRegularizerNormalEquations<float,double,DualQuaternion,internal::TransformUpdateLeftMultiply>\n                                                     (const NonrigidTransformer<float,DualQuaternion> &,\n                                                      Eigen::SparseMatrix<double> &,\n                                                      Eigen::VectorXd &);\n\ntemplate void computeRegularizerNormalEquations<float,double,DualQuaternion,internal::TransformUpdateRightMultiply>\n                                                     (const NonrigidTransformer<float,DualQuaternion> &,\n                                                      Eigen::SparseMatrix<double> &,\n                                                      Eigen::VectorXd &);\n\ntemplate void computeRegularizerNormalEquations<float,double,Sophus::SE3,internal::TransformUpdateLeftMultiply>\n                                                     (const NonrigidTransformer<float,Sophus::SE3> &,\n                                                      Eigen::SparseMatrix<double> &,\n                                                      Eigen::VectorXd &);\n\ntemplate void computeRegularizerNormalEquations<float,double,Sophus::SE3,internal::TransformUpdateRightMultiply>\n                                                     (const NonrigidTransformer<float,Sophus::SE3> &,\n                                                      Eigen::SparseMatrix<double> &,\n                                                      Eigen::VectorXd &);\n\n\n\n\n} // namespace df\n", "meta": {"hexsha": "190bd363cb24ff1988cbb693b0da3418415df9fb", "size": 17251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/kinect_fusion/src/optimization/deformationGraphRegularization.cpp", "max_stars_repo_name": "aditya2592/PoseCNN", "max_stars_repo_head_hexsha": "a763120ce0ceb55cf3432980287ef463728f8052", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 655.0, "max_stars_repo_stars_event_min_datetime": "2018-03-21T19:55:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T20:41:21.000Z", "max_issues_repo_path": "lib/kinect_fusion/src/optimization/deformationGraphRegularization.cpp", "max_issues_repo_name": "yuxng/FCN", "max_issues_repo_head_hexsha": "77fbb50b4272514588a10a9f90b7d5f8d46974fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122.0, "max_issues_repo_issues_event_min_datetime": "2018-04-04T13:57:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T09:28:44.000Z", "max_forks_repo_path": "lib/kinect_fusion/src/optimization/deformationGraphRegularization.cpp", "max_forks_repo_name": "yuxng/FCN", "max_forks_repo_head_hexsha": "77fbb50b4272514588a10a9f90b7d5f8d46974fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 226.0, "max_forks_repo_forks_event_min_datetime": "2018-03-22T01:40:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T11:56:14.000Z", "avg_line_length": 52.4346504559, "max_line_length": 172, "alphanum_fraction": 0.6319633644, "num_tokens": 3766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.24763646629094638}}
{"text": "/******************************************************************************\n * Author:   Laurent Kneip                                                    *\n * Contact:  kneip.laurent@gmail.com                                          *\n * License:  Copyright (c) 2013 Laurent Kneip, ANU. All rights reserved.      *\n *                                                                            *\n * Redistribution and use in source and binary forms, with or without         *\n * modification, are permitted provided that the following conditions         *\n * are met:                                                                   *\n * * 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 ANU nor the names of its contributors may be         *\n *   used to endorse or promote products derived from this software without   *\n *   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 ANU OR THE CONTRIBUTORS BE LIABLE        *\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT         *\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY  *\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF     *\n * SUCH DAMAGE.                                                               *\n ******************************************************************************/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <iomanip>\n#include <opengv/absolute_pose/methods.hpp>\n#include <opengv/absolute_pose/CentralAbsoluteAdapter.hpp>\n#include <opengv/math/cayley.hpp>\n#include <sstream>\n#include <fstream>\n\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n\n#include \"random_generators.hpp\"\n#include \"experiment_helpers.hpp\"\n#include \"time_measurement.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace opengv;\n\nint main(int argc, char **argv)\n{\n  //initialize random seed\n  initializeRandomSeed();\n\n  //set experiment parameters\n  double noise = 0.0;\n  double outlierFraction = 0.0;\n  size_t numberPoints = 10;\n\n  //create a random viewpoint pose\n  translation_t position = generateRandomTranslation(2.0);\n  rotation_t rotation = generateRandomRotation(0.5);\n  // 正規化されている\n\n  //non-existent covariances\n  cov3_mat_t test_cov;\n  cov3_mats_t emptyCovariances;\n  // NOTE　特徴点の数だけ、分散を加味する\n  for (int i{0}; i < 10; ++i)\n    emptyCovariances.push_back(test_cov.Identity() * 1.2);\n  std::cout << test_cov.Identity() * 2 << std::endl;\n\n  //create a fake central camera\n  translations_t camOffsets;\n  rotations_t camRotations;\n  generateCentralCameraSystem(camOffsets, camRotations);\n\n  //derive correspondences based on random point-cloud\n  bearingVectors_t bearingVectors;\n  points_t points;\n  std::vector<int> camCorrespondences; //unused in the central case!\n  Eigen::MatrixXd gt(3, numberPoints);\n  generateRandom2D3DCorrespondences(\n      position, rotation, camOffsets, camRotations, numberPoints, noise, outlierFraction,\n      bearingVectors, points, camCorrespondences, gt);\n  //print the experiment characteristics\n  printExperimentCharacteristics(\n      position, rotation, noise, outlierFraction);\n\n  //create a central absolute adapter\n  absolute_pose::CentralAbsoluteAdapter adapter(\n      bearingVectors,\n      points);\n\n  absolute_pose::CentralAbsoluteAdapter adapter1(\n      bearingVectors,\n      points,\n      emptyCovariances);\n  // NOTE   /** Reference to the covariance-matrix related to the bearing vector */\n\n  //timer\n  struct timeval tic;\n  struct timeval toc;\n  size_t iterations = 50;\n\n  //run the experiments\n  std::cout << \"running Kneip's P2P (first two correspondences)\" << std::endl;\n  translation_t p2p_translation;\n  gettimeofday(&tic, 0);\n  for (size_t i = 0; i < iterations; i++)\n    p2p_translation = absolute_pose::p2p(adapter);\n  gettimeofday(&toc, 0);\n  double p2p_time = TIMETODOUBLE(timeval_minus(toc, tic)) / iterations;\n\n  std::cout << \"running Kneip's P3P (first three correspondences)\" << std::endl;\n  transformations_t p3p_kneip_transformations;\n  gettimeofday(&tic, 0);\n  for (size_t i = 0; i < iterations; i++)\n    p3p_kneip_transformations = absolute_pose::p3p_kneip(adapter);\n  gettimeofday(&toc, 0);\n  double p3p_kneip_time = TIMETODOUBLE(timeval_minus(toc, tic)) / iterations;\n\n  std::cout << \"running Gao's P3P (first three correspondences)\" << std::endl;\n  transformations_t p3p_gao_transformations;\n  gettimeofday(&tic, 0);\n  for (size_t i = 0; i < iterations; i++)\n    p3p_gao_transformations = absolute_pose::p3p_gao(adapter);\n  gettimeofday(&toc, 0);\n  double p3p_gao_time = TIMETODOUBLE(timeval_minus(toc, tic)) / iterations;\n\n  std::cout << \"running epnp (all correspondences)\" << std::endl;\n  transformation_t epnp_transformation;\n  gettimeofday(&tic, 0);\n  for (size_t i = 0; i < iterations; i++)\n    epnp_transformation = absolute_pose::epnp(adapter);\n  gettimeofday(&toc, 0);\n  double epnp_time = TIMETODOUBLE(timeval_minus(toc, tic)) / iterations;\n\n  std::cout << \"running MLPnP (all correspondences w/o covariance)\" << std::endl;\n  transformation_t mlpnp_transformation;\n  transformation_t mlpnp_transformation_;\n  gettimeofday(&tic, 0);\n\n  Eigen::MatrixXd cov_xx;\n  Eigen::MatrixXd cov_ldld;\n  Eigen::MatrixXd cov_xx_;\n  Eigen::MatrixXd cov_ldld_;\n\n  for (size_t i = 0; i < iterations; i++)\n  {\n    mlpnp_transformation = absolute_pose::mlpnp(adapter, cov_xx, cov_ldld);\n    mlpnp_transformation_ = absolute_pose::mlpnp(adapter1, cov_xx_, cov_ldld_);\n  }\n  cout << mlpnp_transformation << endl;\n  cout << \"with cov is ...\" << std::endl;\n  cout << mlpnp_transformation_ << endl;\n  cout << \"cov_xx is \" << std::endl;\n  std::cout << cov_xx << endl;\n  cout << \"cov_xx_ is \" << std::endl;\n  std::cout << cov_xx_ << endl;\n  // cout<<\"cov_xx; \"<<cov_xx<<endl;\n  // cout<<\"cov_ldld; \"<<std::endl;\n  // std::cout<<cov_ldld<<endl;\n  gettimeofday(&toc, 0);\n  double mlpnp_time = TIMETODOUBLE(timeval_minus(toc, tic)) / iterations;\n\n  std::cout << \"running epnp with 6 correspondences\" << std::endl;\n  std::vector<int> indices6 = getNindices(6);\n  transformation_t epnp_transformation_6 =\n      absolute_pose::epnp(adapter, indices6);\n\n  // std::cout << \"running mlpnp with 6 correspondences\" << std::endl;\n  // transformation_t mlpnp_transformation_6 =\n  //   absolute_pose::mlpnp(adapter, indices6);\n\n  std::cout << \"running upnp with all correspondences\" << std::endl;\n  transformations_t upnp_transformations;\n  gettimeofday(&tic, 0);\n  for (size_t i = 0; i < iterations; i++)\n    upnp_transformations = absolute_pose::upnp(adapter);\n  gettimeofday(&toc, 0);\n  double upnp_time = TIMETODOUBLE(timeval_minus(toc, tic)) / iterations;\n\n  std::cout << \"running upnp with 3 correspondences\" << std::endl;\n  std::vector<int> indices3 = getNindices(3);\n  transformations_t upnp_transformations_3 =\n      absolute_pose::upnp(adapter, indices3);\n\n  std::cout << \"setting perturbed pose\";\n  std::cout << \"and performing nonlinear optimization\" << std::endl;\n  //add a small perturbation to the pose\n  translation_t t_perturbed;\n  rotation_t R_perturbed;\n  getPerturbedPose(position, rotation, t_perturbed, R_perturbed, 0.1);\n  transformation_t nonlinear_transformation;\n  gettimeofday(&tic, 0);\n  for (size_t i = 0; i < iterations; i++)\n  {\n    adapter.sett(t_perturbed);\n    adapter.setR(R_perturbed);\n    nonlinear_transformation = absolute_pose::optimize_nonlinear(adapter);\n  }\n  gettimeofday(&toc, 0);\n  double nonlinear_time = TIMETODOUBLE(timeval_minus(toc, tic)) / iterations;\n\n  std::cout << \"setting perturbed pose \";\n  std::cout << \"and performing nonlinear optimization with 10 correspondences\";\n  std::cout << std::endl;\n  std::vector<int> indices10 = getNindices(10);\n  //add a small perturbation to the pose\n  getPerturbedPose(position, rotation, t_perturbed, R_perturbed, 0.1);\n  adapter.sett(t_perturbed);\n  adapter.setR(R_perturbed);\n  transformation_t nonlinear_transformation_10 =\n      absolute_pose::optimize_nonlinear(adapter, indices10);\n}\n", "meta": {"hexsha": "11b5dbd478c84be0d24dc2e41e47cb6fcd5eda58", "size": 8887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_absolute_pose.cpp", "max_stars_repo_name": "Byson-source/opengv", "max_stars_repo_head_hexsha": "a87af73cc5896417fec9e013feef2fa2d9891e8d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_absolute_pose.cpp", "max_issues_repo_name": "Byson-source/opengv", "max_issues_repo_head_hexsha": "a87af73cc5896417fec9e013feef2fa2d9891e8d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_absolute_pose.cpp", "max_forks_repo_name": "Byson-source/opengv", "max_forks_repo_head_hexsha": "a87af73cc5896417fec9e013feef2fa2d9891e8d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5799086758, "max_line_length": 89, "alphanum_fraction": 0.673905705, "num_tokens": 2192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.24759328324530305}}
{"text": "#include <chrono>\n#include <cmath>\n#include <exception>\n#include <thread>\n#include <vector>\n\n#include <boost/log/trivial.hpp>\n\n#include \"mimir/algorithm/Leadline.hpp\"\n#include \"mimir/StateMachineFwd.hpp\"\n#include \"mimir/FkinDds.hpp\"\n\n#include <casadi/casadi.hpp>\n\nnamespace mimir\n{\n  namespace algorithm\n  {\n    class Leadline::Impl\n    {\n    public:\n      Impl(\n          const YAML::Node& config,\n          dds::pub::Publisher publisher,\n          dds::sub::Subscriber subscriber) :\n        inputParameters(dds::core::null),\n        outputWriter(dds::core::null)\n      {\n\n        // Setup input reader for parameters\n        auto input_config = config[\"inputs\"][\"parameters\"];\n        auto readerQos = subscriber.default_datareader_qos();\n        auto topicName = input_config[\"topic\"].as<std::string>();\n        auto id = input_config[\"id\"].as<std::string>();\n        auto topic = dds::topic::Topic<fkin::IdVec2d>(\n            subscriber.participant(),\n            topicName);\n        auto filter = dds::topic::Filter(\"id = %0\", {id});\n\n        inputParameters = dds::sub::DataReader<fkin::IdVec2d>(\n            subscriber,\n            dds::topic::ContentFilteredTopic<fkin::IdVec2d>(\n                topic,\n                topicName + id,\n                filter),\n            readerQos);\n\n        parameters = casadi::DM(config[\"inputs\"][\"parameters\"][\"default\"].as<std::vector<double>>());\n\n        // Setup output writer\n        auto writerQos = publisher.default_datawriter_qos();\n\n        outputWriter = dds::pub::DataWriter<fkin::BatchIdVec1d>(\n            publisher,\n            dds::topic::Topic<fkin::BatchIdVec1d>(\n                publisher.participant(),\n                config[\"outputs\"][\"depth\"][\"topic\"].as<std::string>()),\n            writerQos);\n\n        outputId = config[\"outputs\"][\"depth\"][\"id\"].as<std::string>();\n\n        // Setup model description\n        using namespace casadi;\n        SX x = SX::sym(\"x\", 1);\n        SX tau = SX::sym(\"tau\", 1);\n        SX x_d = SX::sym(\"set_point\", 1);\n        SX param = SX::vertcat({tau,x_d});\n        SX rhs = SX::zeros(1,1);\n        rhs = -(x - x_d)/tau;\n\n        SXDict ode_int = {{\"x\", x}, {\"p\", param}, {\"ode\", rhs}};\n\n        double predHorizonSec = config[\"prediction_horizon_sec\"].as<double>();\n        double timeStepSec = config[\"time_step_ms\"].as<double>()/1000.;\n\n        int32_t steps = static_cast<int32_t>(std::ceil(predHorizonSec/timeStepSec));\n        timeGrid = std::vector<double>(steps+1);\n        prediction = std::vector<fkin::IdVec1d>(timeGrid.size());\n        predictionTime = std::vector<fkin::Timestamp>(timeGrid.size());\n\n        for (size_t i = 0; i < timeGrid.size(); ++i)\n          timeGrid[i] = 0. + i*timeStepSec;\n\n        ode = casadi::integrator(\n            \"leadline\", \"cvodes\", ode_int,\n            {{\"tf\", predHorizonSec}, {\"grid\", timeGrid}});\n\n        xGrid = casadi::DM::zeros(1,timeGrid.size()-1);\n\n      }\n      ~Impl() {}\n      dds::sub::DataReader<fkin::IdVec2d> inputParameters;\n      dds::pub::DataWriter<fkin::BatchIdVec1d> outputWriter;\n      std::chrono::steady_clock::time_point t0;\n      std::vector<double> timeGrid;\n      std::vector<fkin::IdVec1d> prediction;\n      std::vector<fkin::Timestamp> predictionTime;\n      int32_t waitMs;\n      std::string outputId;\n      casadi::Function ode;\n      casadi::DM xGrid;\n      casadi::DM parameters;\n    };\n\n\n    Leadline::Leadline(\n        const YAML::Node& config,\n        boost::statechart::fifo_scheduler<>& scheduler,\n        boost::statechart::fifo_scheduler<>::processor_handle machine,\n        dds::pub::Publisher publisher,\n        dds::sub::Subscriber subscriber) :\n      m_impl( new Leadline::Impl(config, publisher, subscriber)),\n      m_scheduler(scheduler),\n      m_stateMachine(machine),\n      m_time_step(std::chrono::milliseconds(config[\"time_step_ms\"].as<std::int32_t>())),\n      m_next_step(std::chrono::steady_clock::now()),\n      m_config(config)\n    {}\n\n    Leadline::~Leadline() = default;\n    void Leadline::solve(const std::atomic<bool>& cancel_token)\n    {\n      try\n      {\n        BOOST_LOG_TRIVIAL(trace) << \"Leadline solve..\";\n\n        // Fetch current input, sample and hold\n        auto params = m_impl->inputParameters.read();\n\n\n        // Set new desired value\n        if(params.length() > 0)\n        {\n          auto sample = (--params.end());\n          if(sample->info().valid())\n          {\n            auto sD = sample->data();\n            BOOST_LOG_TRIVIAL(debug) << \"Got new params: \"\n                                    << sD.vec().x() << \", \" << sD.vec().y();\n            m_impl->parameters(0) = sD.vec().x();\n            m_impl->parameters(1) = sD.vec().y();\n          }\n        }\n\n        if(cancel_token)\n        {\n          BOOST_LOG_TRIVIAL(info) << name() << \" interrupted\";\n          event(new mimir::EvInterrupt());\n          return;\n        }\n\n        BOOST_LOG_TRIVIAL(debug) << \"Parameters are : \" << m_impl->parameters;\n\n        // Integrate\n        auto result = m_impl->ode(\n            casadi::DMDict( {{\"x0\", casadi::DM::zeros(1,1)}, {\"p\", m_impl->parameters}} ));\n\n\n        if(cancel_token)\n        {\n          BOOST_LOG_TRIVIAL(info) << name() << \" interrupted\";\n          event(new mimir::EvInterrupt());\n          return;\n        }\n\n        using namespace casadi;\n        m_impl->xGrid = result[\"xf\"];\n\n        const auto x_k = std::vector<double>{0};\n        namespace sc = std::chrono;\n\n        auto t0 = m_now; // system clock of time at simulation start\n\n        m_impl->prediction[0] = fkin::IdVec1d(m_impl->outputId, fkin::Vector1d(x_k[0]));\n        m_impl->predictionTime[0] = fkin::Timestamp(\n            sc::duration_cast<sc::milliseconds>(t0.time_since_epoch()).count());\n\n        for(int i = 0; i < static_cast<int>(m_impl->timeGrid.size()-1); ++i)\n        {\n          m_impl->prediction[i+1] = fkin::IdVec1d(\n              m_impl->outputId,\n              fkin::Vector1d(std::vector<double>(m_impl->xGrid(Slice(),Slice(i,i+1)))[0]));\n          m_impl->predictionTime[i+1] = fkin::Timestamp(\n              sc::duration_cast<sc::milliseconds>(\n                  (t0 + (i+1)*m_time_step).time_since_epoch()).count());\n        }\n\n        BOOST_LOG_TRIVIAL(trace) << \"Response: \" << m_impl->xGrid;\n\n        m_impl->outputWriter << fkin::BatchIdVec1d(\n            m_impl->outputId,\n            m_impl->prediction,\n            m_impl->predictionTime);\n\n        step_time();\n        event(new mimir::EvReady());\n\n      }\n      catch(casadi::CasadiException &e)\n      {\n        BOOST_LOG_TRIVIAL(fatal) << name() << \" Casadi Exception: \" << e.what();\n        event(new mimir::EvError());\n        throw;\n      }\n      catch (...)\n      {\n        // Need to post event in case of exception so that the state machine\n        // knows that the job has finished.\n        BOOST_LOG_TRIVIAL(fatal) << name() << \" exception thrown\";\n        event(new mimir::EvError());\n        throw;\n      }\n    }\n    void Leadline::initialize(const std::atomic<bool>&)\n    {\n      try\n      {\n        BOOST_LOG_TRIVIAL(debug) << name() << \" is initializing\";\n        m_next_step = std::chrono::steady_clock::now();\n        m_now = std::chrono::system_clock::now() - m_time_step;\n        event(new mimir::EvReady());\n      }\n      catch (...)\n      {\n        BOOST_LOG_TRIVIAL(fatal) << name() << \" initializing threw exception\";\n        event(new mimir::EvError());\n        throw;\n      }\n    }\n\n    void Leadline::timer(const std::atomic<bool>& cancel_token)\n    {\n      // probably want external time point to wait until.\n      typedef std::chrono::milliseconds scm;\n      auto now = std::chrono::steady_clock::now();\n      auto time_p = m_next_step;\n      auto timeleft = std::chrono::duration_cast<scm>(time_p - now).count();\n      BOOST_LOG_TRIVIAL(trace) << \"Time left: \" << timeleft;\n\n      auto fraction = (m_time_step/100 > scm(0) ? m_time_step/100 :\n       (m_time_step/50 > scm(0) ? m_time_step/50 :\n        (m_time_step/25 > scm(0) ? m_time_step/25 :\n         (m_time_step/10 > scm(0) ? m_time_step/10 :\n          (m_time_step/2 > scm(0) ?  m_time_step/2  : scm(1))))));\n\n      while(now < time_p)\n      {\n        auto diff = time_p - now;\n        std::this_thread::sleep_for(diff < fraction ? diff : fraction);\n        if(cancel_token)\n          break;\n        now = std::chrono::steady_clock::now();\n      }\n\n      if(cancel_token)\n      {\n        BOOST_LOG_TRIVIAL(trace) << \"Timer Canceled\";\n        event(new mimir::EvInterrupt());\n      }\n      else\n      {\n        BOOST_LOG_TRIVIAL(trace) << \"Timeout\";\n        event(new mimir::EvTimeout());\n      }\n    }\n\n    void Leadline::event(boost::statechart::event_base * const event)\n    {\n      // who is responsible for the pointer?\n      m_scheduler.queue_event(\n          m_stateMachine,\n          make_intrusive(event));\n    }\n  }\n}\n", "meta": {"hexsha": "637469a657c044b7db6eab13eedf31d947b42f4e", "size": 8805, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mimir/algorithm/Leadline.cpp", "max_stars_repo_name": "sintef-ocean/mimir", "max_stars_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mimir/algorithm/Leadline.cpp", "max_issues_repo_name": "sintef-ocean/mimir", "max_issues_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mimir/algorithm/Leadline.cpp", "max_forks_repo_name": "sintef-ocean/mimir", "max_forks_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.902173913, "max_line_length": 101, "alphanum_fraction": 0.5630891539, "num_tokens": 2243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2475214992624048}}
{"text": "//| Copyright Inria May 2015\n//| This project has received funding from the European Research Council (ERC) under\n//| the European Union's Horizon 2020 research and innovation programme (grant\n//| agreement No 637972) - see http://www.resibots.eu\n//|\n//| Contributor(s):\n//|   - Jean-Baptiste Mouret (jean-baptiste.mouret@inria.fr)\n//|   - Antoine Cully (antoinecully@gmail.com)\n//|   - Konstantinos Chatzilygeroudis (konstantinos.chatzilygeroudis@inria.fr)\n//|   - Federico Allocati (fede.allocati@gmail.com)\n//|   - Vaios Papaspyros (b.papaspyros@gmail.com)\n//|   - Roberto Rama (bertoski@gmail.com)\n//|\n//| This software is a computer library whose purpose is to optimize continuous,\n//| black-box functions. It mainly implements Gaussian processes and Bayesian\n//| optimization.\n//| Main repository: http://github.com/resibots/limbo\n//| Documentation: http://www.resibots.eu/limbo\n//|\n//| This software is governed by the CeCILL-C license under French law and\n//| abiding by the rules of distribution of free software.  You can  use,\n//| modify and/ or redistribute the software under the terms of the CeCILL-C\n//| license as circulated by CEA, CNRS and INRIA at the following URL\n//| \"http://www.cecill.info\".\n//|\n//| As a counterpart to the access to the source code and  rights to copy,\n//| modify and redistribute granted by the license, users are provided only\n//| with a limited warranty  and the software's author,  the holder of the\n//| economic rights,  and the successive licensors  have only  limited\n//| liability.\n//|\n//| In this respect, the user's attention is drawn to the risks associated\n//| with loading,  using,  modifying and/or developing or reproducing the\n//| software by the user in light of its specific status of free software,\n//| that may mean  that it is complicated to manipulate,  and  that  also\n//| therefore means  that it is reserved for developers  and  experienced\n//| professionals having in-depth computer knowledge. Users are therefore\n//| encouraged to load and test the software's suitability as regards their\n//| requirements in conditions enabling the security of their systems and/or\n//| data to be ensured and,  more generally, to use and operate it in the\n//| same conditions as regards security.\n//|\n//| The fact that you are presently reading this means that you have had\n//| knowledge of the CeCILL-C license and that you accept its terms.\n//|\n\n#ifndef LIMBO_TOOLS_RANDOM_GENERATOR_HPP\n#define LIMBO_TOOLS_RANDOM_GENERATOR_HPP\n\n#include <Eigen/Core>\n\n#include <cmath>\n#include <cstdlib>\n#include <ctime>\n#include <external/rand_utils.hpp>\n#include <list>\n#include <mutex>\n#include <random>\n#include <stdlib.h>\n#include <utility>\n\nnamespace limbo {\n    namespace tools {\n        /// @ingroup tools\n        /// a mt19937-based random generator (mutex-protected)\n        ///\n        /// usage :\n        /// - RandomGenerator<dist<double>>(0.0, 1.0);\n        /// - double r = rgen.rand();\n        template <typename D>\n        class RandomGenerator {\n        public:\n            using result_type = typename D::result_type;\n            RandomGenerator(result_type a, result_type b, int seed = -1) : _dist(a, b) { this->seed(seed); }\n\n            result_type rand() { return _dist(_rgen); }\n\n            void seed(int seed = -1)\n            {\n                if (seed >= 0)\n                    _rgen.seed(seed);\n                else\n                    _rgen.seed(randutils::auto_seed_128{}.base());\n            }\n\n            void reset() { _dist.reset(); }\n\n            void param(const typename D::param_type& param) { _dist.param(param); }\n\n        private:\n            D _dist;\n            std::mt19937 _rgen;\n        };\n\n        /// @ingroup tools\n        using rdist_double_t = std::uniform_real_distribution<double>;\n        /// @ingroup tools\n        using rdist_int_t = std::uniform_int_distribution<int>;\n        /// @ingroup tools\n        using rdist_gauss_t = std::normal_distribution<>;\n\n        /// @ingroup tools\n        /// Double random number generator\n        using rgen_double_t = RandomGenerator<rdist_double_t>;\n\n        /// @ingroup tools\n        /// Double random number generator (gaussian)\n        using rgen_gauss_t = RandomGenerator<rdist_gauss_t>;\n\n        /// @ingroup tools\n        /// integer random number generator\n        using rgen_int_t = RandomGenerator<rdist_int_t>;\n\n        /// @ingroup tools\n        /// random vector by providing custom RandomGenerator\n        template <typename Rng>\n        inline Eigen::VectorXd random_vec(int size, Rng& rng)\n        {\n            Eigen::VectorXd res(size);\n            for (int i = 0; i < size; ++i)\n                res[i] = rng.rand();\n            return res;\n        }\n\n        /// @ingroup tools\n        /// random vector in [0, 1]\n        ///\n        /// - this function is thread safe because we use a random generator for each thread\n        /// - we use a C++11 random number generator\n        inline Eigen::VectorXd random_vector_bounded(int size)\n        {\n            static thread_local rgen_double_t rgen(0.0, 1.0);\n            return random_vec(size, rgen);\n        }\n\n        /// @ingroup tools\n        /// random vector generated with a normal distribution centered on 0, with standard deviation of 10\n        ///\n        /// - this function is thread safe because we use a random generator for each thread\n        /// - we use a C++11 random number generator\n        inline Eigen::VectorXd random_vector_unbounded(int size)\n        {\n            static thread_local rgen_gauss_t rgen(0.0, 10.0);\n            return random_vec(size, rgen);\n        }\n\n        /// @ingroup tools\n        /// random vector wrapper for both bounded and unbounded versions\n        inline Eigen::VectorXd random_vector(int size, bool bounded = true)\n        {\n            if (bounded)\n                return random_vector_bounded(size);\n            return random_vector_unbounded(size);\n        }\n\n        /// @ingroup tools\n        /// generate n random samples with Latin Hypercube Sampling (LHS) in [0, 1]^dim\n        inline Eigen::MatrixXd random_lhs(int dim, int n)\n        {\n            Eigen::VectorXd cut = Eigen::VectorXd::LinSpaced(n + 1, 0., 1.);\n            Eigen::MatrixXd u = Eigen::MatrixXd::Zero(n, dim);\n\n            for (int i = 0; i < n; i++) {\n                u.row(i) = tools::random_vector(dim, true);\n            }\n\n            Eigen::VectorXd a = cut.head(n);\n            Eigen::VectorXd b = cut.tail(n);\n\n            Eigen::MatrixXd rdpoints = Eigen::MatrixXd::Zero(n, dim);\n            for (int i = 0; i < dim; i++) {\n                rdpoints.col(i) = u.col(i).array() * (b - a).array() + a.array();\n            }\n\n            Eigen::MatrixXd H = Eigen::MatrixXd::Zero(n, dim);\n            Eigen::PermutationMatrix<Eigen::Dynamic, Eigen::Dynamic> perm(n);\n            static thread_local std::mt19937 rgen(randutils::auto_seed_128{}.base());\n            for (int i = 0; i < dim; i++) {\n                perm.setIdentity();\n                std::shuffle(perm.indices().data(), perm.indices().data() + perm.indices().size(), rgen);\n                Eigen::MatrixXd tmp = perm * rdpoints;\n                H.col(i) = tmp.col(i);\n            }\n\n            return H;\n        }\n    } // namespace tools\n} // namespace limbo\n\n#endif\n", "meta": {"hexsha": "e44edbd87ef6aff8702be8daf8e97b408324c205", "size": 7275, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "limbo/src/limbo/tools/random_generator.hpp", "max_stars_repo_name": "yjjuan/automl_cplusplus", "max_stars_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-08T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T17:52:18.000Z", "max_issues_repo_path": "limbo/src/limbo/tools/random_generator.hpp", "max_issues_repo_name": "yjjuan/automl_cplusplus", "max_issues_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "limbo/src/limbo/tools/random_generator.hpp", "max_forks_repo_name": "yjjuan/automl_cplusplus", "max_forks_repo_head_hexsha": "7c427584ed94915b549d31a2097f952c3cfdef36", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0890052356, "max_line_length": 108, "alphanum_fraction": 0.6160824742, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.24741215729718052}}
{"text": "//    Copyright 2019 Jij Inc.\n\n//    Licensed under the Apache License, Version 2.0 (the \"License\");\n//    you may not use this file except in compliance with the License.\n//    You may obtain a copy of the License at\n\n//        http://www.apache.org/licenses/LICENSE-2.0\n\n//    Unless required by applicable law or agreed to in writing, software\n//    distributed under the License is distributed on an \"AS IS\" BASIS,\n//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n//    See the License for the specific language governing permissions and\n//    limitations under the License.\n\n#ifndef OPENJIJ_SYSTEM_CLASSICAL_ISING_HPP__\n#define OPENJIJ_SYSTEM_CLASSICAL_ISING_HPP__\n\n#include <cassert>\n#include <utility>\n#include <system/system.hpp>\n#include <graph/all.hpp>\n#include <utility/eigen.hpp>\n#include <type_traits>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n\nnamespace openjij {\n    namespace system {\n\n        /**\n         * @brief naive ClassicalIsing structure (system for classical Ising model)\n         *\n         * @tparam GraphType type of graph\n         * @tparam eigen_impl specify that Eigen implementation is enabled.\n         */\n        template<typename GraphType, bool eigen_impl=false>\n            struct ClassicalIsing {\n                static_assert(!eigen_impl, \"Eigen implementation is not supported.\");\n\n                using system_type = classical_system;\n\n                /**\n                 * @brief Constructor to initialize spin and interaction\n                 *\n                 * @param spin\n                 * @param interaction\n                 */\n                ClassicalIsing(const graph::Spins& init_spin, const GraphType& init_interaction)\n                    : spin{init_spin}, interaction{init_interaction}, num_spins{init_spin.size()} {\n                        assert(init_spin.size() == init_interaction.get_num_spins());\n                    }\n\n                /**\n                 * @brief reset spins\n                 *\n                 * @param init_spin\n                 */\n                void reset_spins(const graph::Spins& init_spin){\n                    this->spin = init_spin;\n                }\n\n                graph::Spins spin;\n                const GraphType interaction;\n                /**\n                 * @brief number of real spins (dummy spin excluded)\n                 */\n                const std::size_t num_spins; //spin.size()\n            };\n\n        //TODO: unify Dense and Sparse Eigen-implemented ClassicalIsing struct\n\n        /**\n         * @brief ClassicalIsing structure for Dense graph (Eigen-based)\n         *\n         * @tparam FloatType type of floating-point\n         */\n        template<typename FloatType>\n            struct ClassicalIsing<graph::Dense<FloatType>, true>{\n                using system_type = classical_system;\n\n                //matrix (row major)\n                using MatrixXx = Eigen::Matrix<FloatType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n                //vector (col major)\n                using VectorXx = Eigen::Matrix<FloatType, Eigen::Dynamic, 1, Eigen::ColMajor>;\n\n                /**\n                 * @brief Constructor to initialize spin and interaction\n                 *\n                 * @param spin\n                 * @param interaction\n                 */\n                ClassicalIsing(const graph::Spins& init_spin, const graph::Dense<FloatType>& init_interaction)\n                    : spin(utility::gen_vector_from_std_vector<FloatType, Eigen::ColMajor>(init_spin)),\n                    interaction(utility::gen_matrix_from_graph<Eigen::RowMajor>(init_interaction)),\n                    num_spins(init_interaction.get_num_spins()){\n                        assert(init_spin.size() == init_interaction.get_num_spins());\n                    }\n\n                /**\n                 * @brief reset spins\n                 *\n                 * @param init_spin\n                 */\n                void reset_spins(const graph::Spins& init_spin){\n                    this->spin = utility::gen_vector_from_std_vector<FloatType, Eigen::ColMajor>(init_spin);\n                }\n\n                VectorXx spin;\n                const MatrixXx interaction;\n\n                /**\n                 * @brief number of real spins (dummy spin excluded)\n                 */\n                const std::size_t num_spins; //spin.size()-1\n            };\n\n        /**\n         * @brief ClassicalIsing structure for Sparse graph (Eigen-based)\n         *\n         * @tparam FloatType type of floating-point\n         */\n        template<typename FloatType>\n            struct ClassicalIsing<graph::Sparse<FloatType>, true>{\n                using system_type = classical_system;\n\n                //matrix (row major)\n                using SparseMatrixXx = Eigen::SparseMatrix<FloatType, Eigen::RowMajor>;\n                //vector (col major)\n                using VectorXx = Eigen::Matrix<FloatType, Eigen::Dynamic, 1, Eigen::ColMajor>;\n\n                /**\n                 * @brief Constructor to initialize spin and interaction\n                 *\n                 * @param spin\n                 * @param interaction\n                 */\n                ClassicalIsing(const graph::Spins& init_spin, const graph::Sparse<FloatType>& init_interaction)\n                    : spin(utility::gen_vector_from_std_vector<FloatType, Eigen::ColMajor>(init_spin)),\n                    interaction(utility::gen_matrix_from_graph<Eigen::RowMajor>(init_interaction)),\n                    num_spins(init_interaction.get_num_spins()){\n                        assert(init_spin.size() == init_interaction.get_num_spins());\n                    }\n\n                /**\n                 * @brief reset spins\n                 *\n                 * @param init_spin\n                 */\n                void reset_spins(const graph::Spins& init_spin){\n                    this->spin = utility::gen_vector_from_std_vector<FloatType, Eigen::ColMajor>(init_spin);\n                }\n\n                VectorXx spin;\n                const SparseMatrixXx interaction;\n\n                /**\n                 * @brief number of real spins (dummy spin excluded)\n                 */\n                const std::size_t num_spins; //spin.size()-1\n            };\n\n        /**\n         * @brief helper function for ClassicalIsing constructor\n         *\n         * @tparam eigen_impl\n         * @tparam GraphType\n         * @param init_spin initial spin\n         -        * @param init_interaction initial interaction\n         *\n         * @return generated object\n         */\n        template<bool eigen_impl=false,typename GraphType>\n            ClassicalIsing<GraphType, eigen_impl> make_classical_ising(const graph::Spins& init_spin, const GraphType& init_interaction){\n                return ClassicalIsing<GraphType, eigen_impl>(init_spin, init_interaction);\n            }\n\n\n\n    } // namespace system\n} // namespace openjij\n\n#endif\n", "meta": {"hexsha": "40eb312f0014a245ec71e289fd1f67247e295079", "size": 6936, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/system/classical_ising.hpp", "max_stars_repo_name": "Atsushi-Machida/OpenJij", "max_stars_repo_head_hexsha": "e4bddebb13536eb26ff0b7b9fc6b1c75659fe934", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/system/classical_ising.hpp", "max_issues_repo_name": "Atsushi-Machida/OpenJij", "max_issues_repo_head_hexsha": "e4bddebb13536eb26ff0b7b9fc6b1c75659fe934", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/system/classical_ising.hpp", "max_forks_repo_name": "Atsushi-Machida/OpenJij", "max_forks_repo_head_hexsha": "e4bddebb13536eb26ff0b7b9fc6b1c75659fe934", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.6956521739, "max_line_length": 137, "alphanum_fraction": 0.5507497116, "num_tokens": 1322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.24741214324102287}}
{"text": "#ifndef SKYLARK_COMBBLAS_SLAB_VIEW_HPP\n#define SKYLARK_COMBBLAS_SLAB_VIEW_HPP\n\n#if SKYLARK_HAVE_COMBBLAS\n#include <CombBLAS.h>\n#include <CommGrid.h>\n#endif\n\n#include <map>\n#include <boost/mpi.hpp>\n#include <boost/serialization/map.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include \"combblas_comm_grid.hpp\"\n\nnamespace skylark {\nnamespace utility {\n\n#if SKYLARK_HAVE_COMBBLAS\n\n/**\n * Slab view for CombBLAS matrices.\n * This are helpers for the panel gemms, where we communicate parts of\n * the CombBLAS matrix and then perform a local Elemental gemm.\n * The communication patterns are dictated by the \"output\" Elemental\n * distribution, e.g. if we want an STAR / MR view, CombBLAS values are\n * redistributed accordingly.\n * Note that due to the CombBLAS distribution we generate slabs in parallel:\n *\n *     [x....|x....]\n *     [x....|x....]\n *     [-----------]\n *     [x....|x....]\n *     [x....|x....]\n *\n * FIXME: - see how we can integrate into base::view\n *        - different comm patterns for _set_view\n *        - compare performance against one-sided value getter for cb matrices\n *        - flag to generate in-order\n *        - transpose case should invert row/col slab view\n */\ntemplate <typename index_type, typename value_type>\nstruct combblas_slab_view_t {\n\n    typedef SpDCCols<index_type, value_type> cb_col_t;\n    typedef SpParMat<index_type, value_type, cb_col_t> sp_par_mat_t;\n    typedef typename cb_col_t::SpColIter cb_col_itr_t;\n    typedef typename cb_col_t::SpColIter::NzIter cb_nz_itr_t;\n\n    /**\n     *  Create a slab view of the CombBLAS matrix B that may be transposed.\n     */\n    combblas_slab_view_t(const sp_par_mat_t &B, bool transp_b = false)\n        : _world(B.getcommgrid()->GetWorld(), boost::mpi::comm_duplicate)\n        , _data((const_cast<sp_par_mat_t &>(B)).seq())\n        , _col_itr(_data.begcol())\n        , _row_itr(_data.begnz(_col_itr))\n        , _transp_b(transp_b)\n        , _offset_row(cb_my_row_offset(B))\n        , _offset_col(cb_my_col_offset(B))\n        , _global_row(0)\n        , _global_col(0) {\n\n        _ncol = B.getncol();\n        _nrow = B.getnrow();\n        if(_transp_b) {\n            _ncol = B.getnrow();\n            _nrow = B.getncol();\n        }\n\n        for(cb_col_itr_t col = _data.begcol(); col != _data.endcol(); col++)\n            _row_itrs.push_back(_data.begnz(col));\n    }\n\n    /**\n     * Extract the value of a global index from the CombBLAS matrix.\n     * TODO: Use this to define a sparse-dense local GEMM that avoids building\n     *       a dense part of the CombBLAS matrix.\n     */\n    value_type operator()(index_type g_row, index_type g_col) {\n\n        index_type map_idx = idx(g_row, g_col);\n        if(_values.count(map_idx) > 0)\n            return _values[map_idx];\n        else\n            return static_cast<value_type>(0);\n    }\n\n    /**\n     *  Extract a Elemental view of CombBLAS COLUMNS. The distribution of the\n     *  Elemental view is determined by the distribution of the input matrix\n     *  A.\n     *  The column_idxs store the global column indices that contain non-zeros.\n     */\n    template<typename dist_elem_matrix_t>\n    void extract_elemental_column_slab_view(\n            const dist_elem_matrix_t &A,\n            std::set<index_type> &column_idxs,\n            size_t width = 1) {\n\n        _values.clear();\n\n        // structure per proc data\n        std::vector< std::map<index_type, value_type> >\n            per_proc_data(_world.size());\n\n        // accumulate locale values\n        for(size_t i = 0; i < width && _col_itr != _data.endcol();\n            _col_itr++, i++) {\n\n            // first accumulate column values, then distribute\n            for(cb_nz_itr_t nz = _data.begnz(_col_itr);\n                nz != _data.endnz(_col_itr); nz++) {\n\n                index_type g_cb_col_idx = _col_itr.colid() + _offset_col;\n                index_type g_cb_row_idx = nz.rowid()  + _offset_row;\n                if(_transp_b) std::swap(g_cb_row_idx, g_cb_col_idx);\n\n                size_t target_proc = A.Owner(g_cb_row_idx, g_cb_col_idx);\n                index_type coords = idx(g_cb_row_idx, g_cb_col_idx);\n                per_proc_data[target_proc].insert(\n                    std::make_pair(coords, nz.value()));\n            }\n        }\n\n        std::set<index_type> indices;\n        _set_view(per_proc_data, indices);\n        typename std::set<index_type>::iterator itr;\n        for(itr = indices.begin(); itr != indices.end(); itr++)\n            column_idxs.insert(col(*itr));\n    }\n\n    /**\n     *  Extract a Elemental view of CombBLAS COLUMNS in sequence. The\n     *  distribution of the Elemental view is determined by the distribution\n     *  of the input matrix A.\n     */\n    template<typename dist_elem_matrix_t>\n    void extract_elemental_column_slab_view(\n            const dist_elem_matrix_t &A,\n            size_t width = 1) {\n\n        _values.clear();\n\n        // structure per proc data\n        std::vector< std::map<index_type, value_type> >\n            per_proc_data(_world.size());\n\n        for(size_t i = 0; i < width && _global_col < _ncol;\n            _global_col++, i++) {\n\n            // if I don't own anything in this column, continue\n            if(_col_itr.colid() + _offset_col != _global_col)\n                    continue;\n\n            // first accumulate column values, then distribute\n            for(cb_nz_itr_t nz = _data.begnz(_col_itr);\n                nz != _data.endnz(_col_itr); nz++) {\n\n                index_type g_cb_col_idx = _col_itr.colid() + _offset_col;\n                index_type g_cb_row_idx = nz.rowid()  + _offset_row;\n                if(_transp_b) std::swap(g_cb_row_idx, g_cb_col_idx);\n\n                size_t target_proc = A.Owner(g_cb_row_idx, g_cb_col_idx);\n                index_type coords = idx(g_cb_row_idx, g_cb_col_idx);\n                per_proc_data[target_proc].insert(\n                    std::make_pair(coords, nz.value()));\n            }\n\n            // this proc can advance to next column\n            _col_itr++;\n        }\n\n        std::set<index_type> indices;\n        _set_view(per_proc_data, indices);\n    }\n\n    /**\n     *  Extract a Elemental view of CombBLAS ROWS. The distribution of the\n     *  Elemental view is determined by the distribution of the input matrix\n     *  A.\n     *  The row_idxs store the global row indices that contain non-zeros.\n     */\n    template<typename dist_elem_matrix_t>\n    void extract_elemental_row_slab_view(\n            const dist_elem_matrix_t &A,\n            std::set<index_type> &row_idxs,\n            size_t height = 1) {\n\n        _values.clear();\n\n        // structure per proc data\n        std::vector< std::map<index_type, value_type> >\n            per_proc_data(_world.size());\n\n        // accumulate locale values\n        cb_col_itr_t col_itr;\n        for(col_itr = _data.begcol(); col_itr != _data.endcol(); col_itr++) {\n\n            // first accumulate column values, then distribute\n            size_t r = 0;\n            for(; r < height && _row_itr != _data.endnz(col_itr); _row_itr++, r++) {\n\n                index_type g_cb_col_idx = col_itr.colid()  + _offset_col;\n                index_type g_cb_row_idx = _row_itr.rowid() + _offset_row;\n                if(_transp_b) std::swap(g_cb_row_idx, g_cb_col_idx);\n\n                size_t target_proc = A.Owner(g_cb_row_idx, g_cb_col_idx);\n                index_type coords = idx(g_cb_row_idx, g_cb_col_idx);\n                per_proc_data[target_proc].insert(\n                    std::make_pair(coords, _row_itr.value()));\n            }\n        }\n\n        std::set<index_type> indices;\n        _set_view(per_proc_data, indices);\n        typename std::set<index_type>::iterator itr;\n        for(itr = indices.begin(); itr != indices.end(); itr++)\n            row_idxs.insert(row(*itr));\n    }\n\n    /**\n     *  Extract a Elemental view of CombBLAS ROWS in sequence. The\n     *  distribution of the Elemental view is determined by the distribution\n     *  of the input matrix A.\n     *  @Note CombBLAS is not well suited for this kind of traversals..\n     */\n    template<typename dist_elem_matrix_t>\n    void extract_elemental_row_slab_view(\n            const dist_elem_matrix_t &A,\n            size_t height = 1) {\n\n        _values.clear();\n\n        // structure per proc data\n        std::vector< std::map<index_type, value_type> >\n            per_proc_data(_world.size());\n\n        for(size_t col = 0; col < _row_itrs.size(); col++) {\n\n            cb_nz_itr_t tmp_row_itr = _row_itrs[col];\n\n            for(size_t i = 0; i < height && _global_row + i < _nrow; i++) {\n\n                if(tmp_row_itr.rowid() + _offset_row != _global_row + i)\n                    continue;\n\n                index_type g_cb_col_idx = col + _offset_col;\n                index_type g_cb_row_idx = tmp_row_itr.rowid() + _offset_row;\n                if(_transp_b) std::swap(g_cb_row_idx, g_cb_col_idx);\n\n                size_t target_proc = A.Owner(g_cb_row_idx, g_cb_col_idx);\n                index_type coords = idx(g_cb_row_idx, g_cb_col_idx);\n                per_proc_data[target_proc].insert(\n                    std::make_pair(coords, tmp_row_itr.value()));\n\n                tmp_row_itr++;\n                _row_itrs[col]++;\n            }\n        }\n\n        _global_row += height;\n\n        std::set<index_type> indices;\n        _set_view(per_proc_data, indices);\n    }\n\n    /**\n     *  Extract the same full (redundantly stored) column view of the CombBLAS\n     *  matrix on all processors.\n     *  @caveat This method uses collective communication.\n     */\n    void extract_full_slab_view(std::set<index_type> &column_idxs,\n                                const size_t slab_size = 1) {\n\n        std::map<index_type, value_type> column_values;\n        _values.clear();\n\n        for(size_t i = 0; i < slab_size && _col_itr != _data.endcol();\n            _col_itr++, i++) {\n\n            // first accumulate column values, then distribute\n            for(cb_nz_itr_t nz = _data.begnz(_col_itr);\n                nz != _data.endnz(_col_itr); nz++) {\n\n                index_type g_cb_col_idx = _col_itr.colid() + _offset_col;\n                index_type g_cb_row_idx = nz.rowid()  + _offset_row;\n                if(_transp_b) std::swap(g_cb_row_idx, g_cb_col_idx);\n\n                index_type coords = idx(g_cb_row_idx, g_cb_col_idx);\n                column_values.insert(std::make_pair(coords, nz.value()));\n            }\n        }\n\n        std::vector< std::map< index_type, value_type> > vector_of_maps;\n        boost::mpi::all_gather< std::map<index_type, value_type> > (\n            _world, column_values, vector_of_maps);\n\n        // gather vectors in one map\n        typename std::map<index_type, value_type>::iterator itr;\n        for(size_t i = 0; i < vector_of_maps.size(); ++i) {\n            for(itr = vector_of_maps[i].begin();\n                itr != vector_of_maps[i].end(); itr++) {\n\n                column_idxs.insert(col(itr->first));\n\n                if(_values.count(itr->first) != 0)\n                    _values[itr->first] += itr->second;\n                else\n                    _values.insert(std::make_pair(itr->first, itr->second));\n            }\n        }\n    }\n\n    void extract_full_slab_view(const size_t width = 1) {\n\n        _values.clear();\n\n        std::map<index_type, value_type> column_values;\n\n        for(size_t i = 0; i < width && _global_col < _ncol;\n            _global_col++, i++) {\n\n            // if I don't own anything in this column, continue\n            if(_col_itr.colid() + _offset_col != _global_col)\n                    continue;\n\n            // first accumulate column values, then distribute\n            for(cb_nz_itr_t nz = _data.begnz(_col_itr);\n                nz != _data.endnz(_col_itr); nz++) {\n\n                index_type g_cb_col_idx = _col_itr.colid() + _offset_col;\n                index_type g_cb_row_idx = nz.rowid()  + _offset_row;\n                if(_transp_b) std::swap(g_cb_row_idx, g_cb_col_idx);\n\n                index_type coords = idx(g_cb_row_idx, g_cb_col_idx);\n                column_values.insert(std::make_pair(coords, nz.value()));\n            }\n\n            // this proc can advance to next column\n            _col_itr++;\n        }\n\n        std::vector< std::map< index_type, value_type> > vector_of_maps;\n        boost::mpi::all_gather< std::map<index_type, value_type> > (\n            _world, column_values, vector_of_maps);\n\n        // gather vectors in one map\n        typename std::map<index_type, value_type>::iterator itr;\n        for(size_t i = 0; i < vector_of_maps.size(); ++i) {\n            for(itr = vector_of_maps[i].begin();\n                itr != vector_of_maps[i].end(); itr++) {\n\n                if(_values.count(itr->first) != 0)\n                    _values[itr->first] += itr->second;\n                else\n                    _values.insert(std::make_pair(itr->first, itr->second));\n            }\n        }\n    }\n\n    /// get the number of columns\n    index_type ncols() { return _ncol; }\n    index_type nrows() { return _nrow; }\n\n\nprivate:\n\n    /// world communicator of the view\n    boost::mpi::communicator _world;\n\n    /// the CombBLAS data\n    cb_col_t &_data;\n\n    /// the iterator holding the current position in iterating the CombBLAS\n    /// matrix. This is used when generating slabs column wise.\n    cb_col_itr_t _col_itr;\n\n    /// the iterator holding the current position in iterating the CombBLAS\n    /// matrix. This is used when generating slabs row wise.\n    cb_nz_itr_t _row_itr;\n    std::vector<cb_nz_itr_t> _row_itrs;\n\n    /// transpose flag\n    const bool _transp_b;\n\n    /// this processors row offset in the CombBLAS matrix\n    const size_t _offset_row;\n\n    /// this processors column offset in the CombBLAS matrix\n    const size_t _offset_col;\n\n    size_t _global_row;\n    size_t _global_col;\n\n    /// number of columns\n    size_t _ncol;\n    /// number of rows\n    size_t _nrow;\n\n    /// holds the values of the current slab view\n    std::map<index_type, value_type> _values;\n\n\n    /// convert an 1D index to the global row index\n    index_type row(index_type value) { return  value / _ncol; }\n\n    /// convert an 1D index to the global column index\n    index_type col(index_type value) { return  value % _ncol; }\n\n    /// convert a (row, col) pair to a 1D index\n    index_type idx(index_type row, index_type col) {\n        return row * _ncol + col;\n    }\n\n    //FIXME: here we use collectives, add existing code for other comm schemes\n    /// This methods takes a mapping from indices to processors and\n    /// communicates the values to the target processor.\n    void _set_view(\n            std::vector< std::map<index_type, value_type> > &per_proc_data,\n            std::set<index_type> &indices) {\n\n        //// first we need to know how many elements we receive from other\n        //// processors:\n        //std::vector<size_t> n_values(_world.size());\n        //for(size_t idx = 0; idx < _world.size(); ++idx)\n            //n_values[idx] = per_proc_data[idx].size();\n\n        //// resulting vector holds expected values: vector_of_sizes[from][to]\n        //std::vector< std::vector<size_t> > vector_of_sizes;\n        //boost::mpi::all_gather< std::vector<size_t> > (\n            //_world, n_values, vector_of_sizes);\n\n        // pre-post receives for all values then\n        //FIXME: this is not working because Boost sends serialized data in\n        // two steps: first the size and then the data, so waiting for one\n        // irecv is not correct.\n        //std::vector<boost::mpi::request> reqs;\n        //std::vector< std::map<index_type, value_type> > vector_of_maps(_world.size());\n        //for(size_t from = 0; from < _world.size(); ++from) {\n            //size_t recv_size = vector_of_sizes[from][_world.rank()];\n            //std::cout << \"from \" << from << \" receive \" << recv_size << std::endl;\n            //if(recv_size > 0)\n                //reqs.push_back(\n                    //_world.irecv(from, 0, &vector_of_maps[from], recv_size));\n        //}\n\n        //// then perform all sends\n        //for(size_t to = 0; to < _world.size(); ++to) {\n            //if(per_proc_data[to].size() > 0)\n                //_world.send(to, 0, per_proc_data[to]);\n        //}\n\n        //// wait for completion\n        //boost::mpi::wait_all(reqs.begin(), reqs.end());\n\n        std::vector<std::map<index_type, value_type> > vector_of_maps;\n        for(int i = 0; i < _world.size(); ++i)\n            boost::mpi::gather(_world, per_proc_data[i], vector_of_maps, i);\n\n        typename std::map<index_type, value_type>::iterator itr;\n        for(size_t i = 0; i < vector_of_maps.size(); ++i) {\n            for(itr = vector_of_maps[i].begin();\n                itr != vector_of_maps[i].end(); itr++) {\n\n                indices.insert(itr->first);\n\n                if(_values.count(itr->first) != 0)\n                    _values[itr->first] += itr->second;\n                else\n                    _values.insert(std::make_pair(itr->first, itr->second));\n            }\n        }\n    }\n};\n\n#endif\n\n} } // namespace skylark::utility\n\n#endif //SKYLARK_COMBBLAS_SLAB_VIEW\n", "meta": {"hexsha": "5e810d3a13584fd79a9d6d03756a915c510b0f9d", "size": 17048, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utility/external/view.hpp", "max_stars_repo_name": "wangg12/libskylark", "max_stars_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "utility/external/view.hpp", "max_issues_repo_name": "cjiyer/libskylark", "max_issues_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "utility/external/view.hpp", "max_forks_repo_name": "cjiyer/libskylark", "max_forks_repo_head_hexsha": "e8836190be854d0284d38772c48e110b3c6d5e51", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 35.3692946058, "max_line_length": 88, "alphanum_fraction": 0.5913303613, "num_tokens": 4203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2473054883831013}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <vector>\n#include <cstdlib>\n#include <fstream>\n#include \"libsnnlfisrm/snn.h\"\n\n/**\n * Calculates initial delays\n*/\narma::Col<double> get_initial_delays();\n\n/**\n * Calculates initial weights for lateral synapses\n*/\narma::Col<double> get_initial_weights();\n\nint main(int argc, const char **argv) {\n    \n    // Test individual LIF/SRM neuron\n    int snn_id = 2;\n    int n_inputs = 2;\n    int n_lateral = 1;\n    std::vector<double> init_d({2, 4});\n    std::vector<double> init_w({4});\n    double tau_m = 1;\n    double u_rest = 3;\n    double init_v = 20;\n    unsigned char t_rest = 2;\n    double kappa_naugh = 3;\n    double round_zero = 0.1;\n    double u_max = 10;\n\n    SpikeResponseModelNeuron neuron(snn_id, n_inputs, init_d, tau_m, \n    u_rest, init_v, t_rest, kappa_naugh, round_zero, u_max);\n\n    printf(\"delay vector: [\");\n    for(unsigned int i = 0; i < neuron.d_j.size(); i++)\n    {\n        printf(\" %f \", neuron.d_j.at(i));\n    }\n    printf(\"]\\n\");\n\n    // test t_pulse is working and making kappas...\n    std::vector<double> u;\n    printf(\"number of kappas: %d\\n\", (int)neuron.k_filter_list.at(K_LIST_INPUT_SYNAPSES).size());\n    neuron.dendrite = std::vector<DelayedSpike>({DelayedSpike(0, true), DelayedSpike(0, 0)});\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.dendrite = std::vector<DelayedSpike>({DelayedSpike(0, false), DelayedSpike(0, 0)});\n    neuron.t_pulse();\n    u.push_back(neuron.membrane_potential());\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.dendrite = std::vector<DelayedSpike>({DelayedSpike(0, true), DelayedSpike(0, 0)});\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"membrane potential: %f\\n\", neuron.membrane_potential());\n    u.push_back(neuron.membrane_potential());\n    neuron.t_pulse();\n    printf(\"number of kappas: %d\\n\", (int)neuron.k_filter_list.at(K_LIST_INPUT_SYNAPSES).size());\n\n    printf(\"u plot: [ %f\", u.at(0));\n    for(unsigned int v = 1; v < u.size(); v++)\n        printf(\", %f\", u.at(v));\n    printf(\"]\\n\");\n\n    // Testing FSTN\n    printf(\"Testing Fisrt spike time neuron\\n\");\n    double alpha = 1;\n    FirstSpikeTimeNeuron fstn(0, alpha);\n    fstn.dendrite = (double)2;\n    fstn.t_pulse();\n    fstn.dendrite = (double)2;\n    fstn.t_pulse();\n    fstn.dendrite = (double)2;\n    fstn.t_pulse();\n    fstn.dendrite = (double)2;\n    fstn.t_pulse();\n    fstn.dendrite = (double)2;\n    fstn.t_pulse();\n    fstn.dendrite = (double)2;\n    fstn.t_pulse();\n    fstn.dendrite = (double)2;\n    fstn.t_pulse();\n    fstn.dendrite = (double)2;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n    fstn.dendrite = (double)5;\n    fstn.t_pulse();\n\n\n    // Testing neural network\n    // parameters:\n    unsigned int i_layer_size = 2;\n    unsigned int h_layer_size = 16;\n    std::vector<std::vector<double>> d_init({\n        {4, 3, 2, 3, 4, 3, 3, 2, 1, 4, 3, 3, 3, 2, 5, 2}, \n        {1, 4, 2, 4, 6, 2, 1, 3, 5, 3, 3, 3, 3, 2, 5, 2}\n    });\n    std::vector<std::vector<double>> w_init({\n        {1, 3, 2, -1, 3, 1, -2, 1, -2, 1, 3, 3, 3, 2, 5, 2},\n        {3, 4, 2, 3, 4, 12, 1, 1, 2, 1, 3, 3, 3, 2, 5, 2},\n        {2, 3, 2, 1, 2, 1, 2, 1, 1, 2, 3, 3, 3, 2, 5, 2},\n        {-1, -2, -1, -2, -3, -4, -9, -1, 2, -2, 3, 3, 3, 2, 5, 2},\n        {3, 4, 2, 1, 3, 6, 3, 1, 2, 3, 3, 3, 3, 2, 5, 2},\n        {1, 3, 1, 3, 5, 3, 1, 0, 3, 1, 3, 3, 3, 2, 5, 2},\n        {-2, -3, -1, -3, -5, 3, 2, 4, 5, 4, 3, 3, 3, 2, 5, 2},\n        {1, 6, 2, 2, 4, 6, 3, 2, 4, 5, 3, 3, 3, 2, 5, 2},\n        {-2, -5, -1, 4, -1, -3, 2, -7, -1, 3, 3, 3, 3, 2, 5, 2},\n        {1, 5, 7, 2, 4, 6, 4, 1, 3, 5, 3, 3, 3, 2, 5, 2},\n        {1, 5, 7, 2, 4, 6, 4, 1, 3, 5, 3, 3, 3, 2, 5, 2},\n        {1, 5, 7, 2, 4, 6, 4, 1, 3, 5, 3, 3, 3, 2, 5, 2},\n        {1, 5, 7, 2, 4, 6, 4, 1, 3, 5, 3, 3, 3, 2, 5, 2},\n        {1, 5, 7, 2, 4, 6, 4, 1, 3, 5, 3, 3, 3, 2, 5, 2},\n        {1, 5, 7, 2, 4, 6, 4, 1, 3, 5, 3, 3, 3, 2, 5, 2},\n        {1, 5, 7, 2, 4, 6, 4, 1, 3, 5, 3, 3, 3, 2, 5, 2},\n    });\n    tau_m = 4;\n    u_rest = 0;\n    init_v = 20;\n    double t_reset = 3;\n    double k_nought = 10;\n    round_zero = 0.1; \n    alpha = 2;\n\n    BaseSNN snn(i_layer_size, d_init, tau_m, u_rest, init_v, t_reset, k_nought, \n    round_zero, alpha, u_max);\n\n    snn.re_process({0, 0});\n    for(int p = 0; p < 20; p++)\n    {\n        snn.process();\n        for(unsigned int i = 0; i < h_layer_size; i++)\n        {\n            double u_i = snn.hidden_layer.at(i).membrane_potential();\n            printf(\"U_%u = %f\\n\", i, u_i);\n            if(snn.hidden_layer.at(i).axon.signal)\n            {\n                // this neuron is the \"winner\"\n                printf(\"Spike %u winner (Reached threshold)\\n\", i);\n                goto next_test;\n            }\n        }\n    }\n    next_test:\n    // Test euclidean_distance_matrix function\n    double distance_unit = 2;\n\n    printf(\"Testing matrices.\\n\");\n    arma::Mat<double> e_mat = euclidean_distance_matrix (&snn, distance_unit);\n    printf(\"Matrix Content\\n\\n\");\n    for(unsigned int i = 0; i < snn.h_layer_size; i++)\n    {\n        for(unsigned int j = 0; j < snn.h_layer_size; j++)\n        {\n            printf(\"%f\\t\", e_mat(i, j));\n        }\n        printf(\"\\n\");\n    }\n\n\n    // Test euclidean initial weight function\n    double sigma_1 = .5;\n    double sigma_2 = 2;\n    std::vector<arma::Col<double>> w_mat = initial_weight_euclidean(e_mat, sigma_1, sigma_2);\n    printf(\"\\nPrinting weight matrix's contents:\\n\\n\");\n    printf(\"Weight Matrix Content\\n\\n\");\n    for(unsigned int i = 0; i < snn.h_layer_size; i++)\n    {\n        for(unsigned int j = 0; j < snn.h_layer_size; j++)\n        {\n            printf(\"%f\\t\", w_mat.at(i).at(j));\n        }\n        printf(\"\\n\");\n    }\n\n \n    // Testing euclidean_distance_matrix without snn\n    std::vector<std::vector<double>> point_list({\n        {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3},\n        {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3}\n    });\n\n    \n\n    printf(\"Testing matrices.\\n\");\n    arma::Mat<double> e_mat_init = euclidean_distance_matrix(&point_list, distance_unit);\n    printf(\"Matrix Content\\n\\n\");\n    for(unsigned int i = 0; i < e_mat_init.n_rows; i++)\n    {\n        for(unsigned int j = 0; j < e_mat_init.n_cols; j++)\n        {\n            printf(\"%f\\t\", e_mat_init(i, j));\n        }\n        printf(\"\\n\");\n    }\n\n    // Testing Random delay generator\n    printf(\"\\nTesting Random Delay generator\\n\");\n    std::vector<std::vector<double>> initial_delays;\n\n    unsigned int n_x = 10;\n    unsigned int n_y = 10;\n    unsigned int delays_per_row = 10;\n    unsigned int delays_per_column = 10;\n\n    initial_delays = initial_delay_vector_2d_map(n_x, n_y, \n    delays_per_row, delays_per_column);\n\n    printf(\"Delay Matrix Content\\n\\n\");\n    for(unsigned int i = 0; i < initial_delays.size(); i++)\n    {\n        for(unsigned int j = 0; j < initial_delays.at(i).size(); j++)\n        {\n            printf(\"%f\\t\", initial_delays.at(i).at(j));\n        }\n        printf(\"\\n\");\n    }\n\n    // Test point map creator\n    printf(\"\\nTesting point map creator.\\n\");\n    unsigned int x_size = 4;\n    unsigned int y_size = 7;\n    std::vector<std::vector<double>> map_ = euclidean_point_map(x_size, y_size);\n    printf(\"Point Map Matrix Content\\n\\n\");\n\n    for(unsigned int j = 0; j < x_size*y_size; j++)\n    {\n        printf(\"(%f, %f)\\t\", map_.at(0).at(j), map_.at(1).at(j));\n    }\n\n\n    // Testing training algorthm\n    unsigned int n_data = 2;\n    tau_m = 1.5;\n    u_rest = 2;\n    init_v = 4.5;\n    t_reset = 3;\n    k_nought = 2.5;\n    round_zero = 0.05;\n    alpha = 4;\n    // note that n_x * n_y = h_layer_size\n    n_x = 10;\n    n_y = 10;\n    double delay_distance = 1;\n    distance_unit = 1;\n    sigma_1 = 0.7;\n    sigma_2 = 1.6;\n\n    double sigma_neighbor = 1;\n\n    double eta_d = .5;\n    unsigned int t_max = 25;\n    unsigned int t_delta = 3;\n    double ltd_max = -0.45;\n    SNN model(n_data, tau_m, u_rest, init_v, \n    t_reset, k_nought, round_zero, alpha, n_x, n_y, delay_distance,\n    distance_unit, sigma_neighbor, eta_d, t_max, u_max);\n\n    std::vector<std::vector<double>> data = {\n        {0, 0, 0, 1, 2, 2, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0},\n        {0, 1, 2, 2, 2, 3, 3, 4, 5, 6, 7, 7, 7, 7, 6, 5, 4, 3, 2, 1, 0}\n    };\n    std::vector<std::vector<double>> data_2 = {\n        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n        {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1},\n    };\n\n    // save delays into file:\n    std::ofstream delay_file;\n    delay_file.open(\"snn_data_delays.txt\");\n    \n    // print out delays\n    delay_file << \"Delays before training:\" << std::endl;\n    for(unsigned int i = 0; i < model.snn->d_ji.size(); i++)\n    {\n        delay_file << \"[ \";\n        for(unsigned int j = 0; j < model.snn->d_ji.at(i).size(); j++)\n        {\n            delay_file << model.snn->d_ji.at(i).at(j) << \", \";\n        }\n        delay_file << \"]\" << std::endl;\n    }\n    // print out weights\n   \n    for(unsigned int p = 0; p < 1; p++)\n        model.train(data);\n\n    delay_file << std::endl << \"Delays after training:\"<< std::endl;\n     for(unsigned int i = 0; i < model.snn->d_ji.size(); i++)\n    {\n        delay_file << \"[ \";\n        for(unsigned int j = 0; j < model.snn->d_ji.at(i).size(); j++)\n        {\n            delay_file << model.snn->d_ji.at(i).at(j) << \", \";\n        }\n        delay_file << \"]\" << std::endl;\n    }\n    delay_file.close();\n    \n\n\n    // Armadillo version printout\n    arma::arma_version ver;\n    printf(\"\\nArmadillo Version: %s\\n\", ver.as_string().c_str());\n    return 0;\n}\n\n\n", "meta": {"hexsha": "c937aa2ee6aa81cd43b0c75134addc3308152edb", "size": 12695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snn_main.cpp", "max_stars_repo_name": "aguilarjose11/world_rep_snn", "max_stars_repo_head_hexsha": "fa519f9cbe32b7ee61ff5514b361b2c73959d57c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-06T18:45:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-06T18:45:33.000Z", "max_issues_repo_path": "snn_main.cpp", "max_issues_repo_name": "aguilarjose11/world_rep_snn", "max_issues_repo_head_hexsha": "fa519f9cbe32b7ee61ff5514b361b2c73959d57c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-19T19:12:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-19T19:12:04.000Z", "max_forks_repo_path": "snn_main.cpp", "max_forks_repo_name": "aguilarjose11/world_rep_snn", "max_forks_repo_head_hexsha": "fa519f9cbe32b7ee61ff5514b361b2c73959d57c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-29T15:38:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T15:38:07.000Z", "avg_line_length": 33.5846560847, "max_line_length": 249, "alphanum_fraction": 0.5630563214, "num_tokens": 4698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2467662459066459}}
{"text": "/* Copyright 2019 The Spin-Scenario Authors. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\n#include \"grape.h\"\n#include <kernel/utilities/ssl_plot.h>\nusing namespace ssl::utility;\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/format.hpp>\n#include <chrono>\nnamespace ssl {\nnamespace oc {\nint g_oc_iteration_save = 0;\nvoid set_oc_iteration_save(const sol::table &t) {\n\t  for (auto &kv : t) {\n    int val = kv.second.as<int>();\n    g_oc_iteration_save = val;\n    break;\n  }\n}\ntypedef struct {\n  size_t i; // step index.\n  size_t j; // channel index.\n  size_t chs; // channel number.\n  double amp;\n} amp_constraint_data;\n\ngrape::grape(spin_system &sys)\n    : rf_(nullptr) {\n  sys_ = &sys;\n  superop_.rf_ctrl = sys.rf_hamiltonian();\n  superop_.L0 = sys.free_hamiltonian();\n  superop_.R = sys.relaxation();\n  superop_.L0s = sys.free_hamiltonians();\n  int bb_size = superop_.L0s.size();\n  //std::cout << bb_size << \"\\n\";\n  if (bb_size) {\n    // superop_.profile = vec::Ones(bb_size);\n    superop_.nominal_offset = sys.nominal_broadband();\n    superop_.grad_bb = std::vector<std::vector<double>>(bb_size);\n  } else {  // no offset case.\n    superop_.L0s.push_back(superop_.L0);\n    superop_.grad_bb = std::vector<std::vector<double>>(1);\n  }\n  opt_model_ = _rho2rho;\n  axis_ = uxuy_;\n}\n\ngrape::~grape() {\n}\n\ndouble grape::maxf() const {\n  return max_val_;\n}\n\nseq_block &grape::optimize(const sol::table &t) {\n  assign_pulse(t);\n  assign_x();\n  assign_nlopt(t);\n  assign_state(t);\n  assign_aux_var();\n\n  if (opt_model_ == _rho2rho) \n      optimizer_->set_max_objective(objfunc_broadband, this);\n  if (opt_model_ == _propagator)\n    optimizer_->set_max_objective(objfunc_propagator, this);\n\n  print();\n  double max_f;\n  nlopt::result result = optimizer_->optimize(x_, max_f);\n  if (result == nlopt::SUCCESS)\n    ssl_color_text(\"info\", \"pulse optimization succeed.\\n\");\n  if (result == nlopt::FAILURE)\n    ssl_color_text(\"err\", \"pulse optimization failed.\\n\");\n  if (result == nlopt::MAXEVAL_REACHED)\n    ssl_color_text(\"warn\", \"pulse optimization terminated due to maximum iterations limitation.\\n\");\n\n  max_val_ = max_f;\n  rf_->update_raw_data(axis_, x_.data());\n\n  grape::h5write();\n  return *rf_;\n}\n\ndouble grape::objfunc_broadband(const std::vector<double> &x, std::vector<double> &grad,\n                                void *func) {\n  return ((grape *)func)->objfunc_broadband(x, grad);\n}\ndouble grape::objfunc_propagator(const std::vector<double> &x, std::vector<double> &grad,\n                                 void *func) {\n  return ((grape *)func)->objfunc_propagator(x, grad);\n}\n\nvoid grape::assign_state(const sol::table &t) {\n  if (is_retrievable(\"targ_op\", t)) {\n    opt_model_ = _propagator;\n    targ_op_ = sys_->smart_op(retrieve_table_str(\"targ_op\", t));\n    targ_op_ = ssl::spinsys::propagator(targ_op_, _pi);\n    int n = targ_op_.rows();\n    init_op_ = sp_cx_mat(n, n);\n    init_op_.setIdentity();\n\n    // in case of unified targ for diff freq offsets.\n    if (superop_.L0s.size())\n      targ_op_list_ = std::vector<sp_cx_mat>(superop_.L0s.size(), targ_op_);\n    return;\n  }\n\n  opt_model_ = _rho2rho;\n  init_state_ = sys_->smart_state(retrieve_table_str(\"init_state\", t));\n  init_state_ = norm_state(init_state_);\n\n  sol::object obj = retrieve_table(\"targ_state\", t);\n  if (obj.get_type() == sol::type::string) {\n    targ_state_ = sys_->smart_state(retrieve_table_str(\"targ_state\", t));\n    targ_state_ = norm_state(targ_state_);\n\n    // in case of unified targ for diff freq offsets.\n    if (superop_.L0s.size())\n      targ_list_ = std::vector<sp_cx_vec>(superop_.L0s.size(), targ_state_);\n  }\n\n  if (obj.get_type() == sol::type::table) {\n    targ_list_.clear();\n    sol::table targ_table = obj.as<sol::table>();\n    for (size_t i = 0; i < targ_table.size(); i++) {\n      sol::object val = targ_table[i + 1];\n      sp_cx_vec targ = val.as<sp_cx_vec>();\n      targ=norm_state(targ);\n      targ_list_.push_back(targ);\n    }\n  }\n}\n\nvoid grape::assign_nlopt(const sol::table &t) {\n  // TO BE REMOVE.\n  epsilon_ = 0;      // default val.\n  epsilon_num_ = 1;  // default val.\n  if (is_retrievable(\"epsilon\", t)) {\n    epsilon_ = retrieve_table_double(\"epsilon\", t);\n  }\n\n  if (is_retrievable(\"epsilon_num\", t)) {\n    epsilon_num_ = retrieve_table_int(\"epsilon_num\", t);\n  }\n  nlopt::algorithm alg = nlopt::LD_LBFGS;\n\n  if (is_retrievable(\"algorithm\", t)) {\n    std::string oc = retrieve_table_str(\"algorithm\", t);\n    boost::to_upper(oc);\n    if (oc == \"MNA\") alg = nlopt::LD_MMA;\n  }\n  optimizer_ = new nlopt::opt(alg, x_dim_);\n\n  if (is_retrievable(\"max_eval\", t)) {\n    int val = retrieve_table_int(\"max_eval\", t);\n    if (val > 0)\n      optimizer_->set_maxeval(val);\n    else\n      throw std::runtime_error(\"max_eval must > 0.\");\n  }\n\n  if (is_retrievable(\"xtol_rel\", t)) {\n    double val = retrieve_table_double(\"xtol_rel\", t);\n    optimizer_->set_xtol_rel(val);\n  } else\n    optimizer_->set_xtol_rel(1e-8);\n\n  assign_constraint(t);\n}\nvoid grape::print() const {\n  if (optimizer_->get_algorithm() == nlopt::LD_MMA)\n    ssl_color_text(\"oc\", \"nlopt algorithm used: LD_MMA.\\n\");\n  if (optimizer_->get_algorithm() == nlopt::LD_LBFGS)\n    ssl_color_text(\"oc\", \"nlopt algorithm used: LD_LBFGS.\\n\");\n  \n  ssl_color_text(\"oc\", \"x dim: \" + boost::lexical_cast<std::string>(x_dim_) +  \".\\n\");\n  ssl_color_text(\"oc\", \"nlopt xtol_rel: \" + boost::lexical_cast<std::string>(optimizer_->get_xtol_rel()) +  \".\\n\");\n\n  \n}\nvoid grape::assign_x() {\n  x_.clear();\n  rf_->convert2(_ux_uy);  // must do it.\n\n  if (axis_ == uxuy_)\n    x_ = rf_->clone_raw_data();\n  else if (axis_ == ux_)\n    x_ = rf_->clone_raw_data_ux();\n  else if (axis_ == uy_)\n    x_ = rf_->clone_raw_data_uy();\n\n  x_dim_ = x_.size();\n}\n\nvoid grape::assign_pulse(const sol::table &t) {\n  double width = retrieve_table_double(\"width\", t); // unit in ms.\n  size_t nsteps = (size_t) (retrieve_table_int(\"step\", t));\n  std::string pattern = \"rand_spline\";\n  if (is_retrievable(\"init_pattern\", t))\n    pattern = retrieve_table_str(\"init_pattern\", t);\n\n  double max_init_amp = 1;\n  if (is_retrievable(\"max_init_amp\", t))\n    max_init_amp = retrieve_table_double(\"max_init_amp\", t);\n\n\n  double dt = width * 1e-3 / double(nsteps); // into s.\n\n  std::string str_chs;\n  if (is_retrievable(\"limit_channel\", t))\n      str_chs = retrieve_table_str(\"limit_channel\", t);\n  else\n  str_chs = boost::algorithm::join(superop_.rf_ctrl.chs, \" \");\n\n  std::string code = \"user_rf = shapedRF{name = 'opt-rf', width = \" +\n                boost::lexical_cast<std::string>(width) +\n                \",  step = \" + boost::lexical_cast<std::string>(nsteps) +\n                \",  max_amp = \" + boost::lexical_cast<std::string>(max_init_amp) +\n                \",  channel = '\" + str_chs + \"',\" + \"pattern = '\" + pattern +\n                \"'}\";\n\n  g_lua->script(code);\n\n   std::string s = str(boost::format(\"pulse width - [%.3f] ms, steps - [%d], step width - [%.3f] us.\\n\") % width % nsteps\n                     % (dt * 1e6));\n  ssl_color_text(\"info\", s);\n\n  sol::object val = (*g_lua)[\"user_rf\"];\n  seq_block &sb = val.as<seq_block &>(); // note the original type should be 'seq_block'.\n  shaped_rf &user_rf = (shaped_rf &) sb; // transfrom into 'shaped_rf'.\n\n  rf_ = &user_rf;\n\n  if (is_retrievable(\"limit_axis\", t)) {\n    std::string s = retrieve_table_str(\"limit_axis\", t);\n    if (s == \"x\")\n      axis_ = ux_;\n    else if (s == \"y\")\n      axis_ = uy_;\n  }\n\n  rf_->convert2(_ux_uy);  // must do it.\n\n  if(axis_==ux_) {\n   std::vector<double>zeros = std::vector<double>(rf_->get_dims() / 2, 0);\n    rf_->update_raw_data_uy(zeros.data());\n  }\n  if (axis_ == uy_) {\n    std::vector<double> zeros = std::vector<double>(rf_->get_dims() / 2, 0);\n    rf_->update_raw_data_ux(zeros.data());\n  }\n}\n\nvoid grape::h5write(std::string file_name) const {\n  if (file_name.empty()) {\n    std::string time_s = sys_time();\n    file_name = \"oc_\" + time_s + \".h5\";\n  }\n  H5File file(file_name, H5F_ACC_TRUNC);\n\n  rf_->switch_rf_mode(\"amp/phase\");\n  rf_->h5write(file, \"opt\");\n\n  ssl::utility::h5write(file, nullptr, \"obj\", stl2vec(obj_val_));\n  file.close();\n}\n\nvoid grape::assign_aux_var() {\n  // traj_ = state_traj(rf_->get_steps());\n  int nbb = superop_.L0s.size();\n  if (nbb >= 1) {\n    omp_set_num_threads(omp_core_num);\n    for (size_t i = 0; i < superop_.grad_bb.size(); i++)\n      superop_.grad_bb[i] = std::vector<double>(rf_->get_dims(), 0);\n\n    if (opt_model_ == _rho2rho) {\n      traj_omp_ = std::vector<state_traj>(omp_core_num);\n      for (int i = 0; i < omp_core_num; i++) {\n        traj_omp_[i] = state_traj(rf_->get_steps());\n      }\n    }\n    if (opt_model_ == _propagator) {\n      op_traj_omp_ = std::vector<op_traj>(omp_core_num);\n      for (int i = 0; i < omp_core_num; i++) {\n        op_traj_omp_[i] = op_traj(rf_->get_steps());\n      }\n    }\n  }\n}\n\nvoid grape::assign_constraint(const sol::table &t) {\n  if (is_retrievable(\"max_amp\", t)) {\n    double val = retrieve_table_double(\"max_amp\", t);  // unit in hz.\n    val *= 2 * _pi;\n\n    size_t dim = rf_->get_dims();\n    size_t nsteps = rf_->get_steps();\n    size_t nchannels = rf_->get_channels();\n    std::vector<double> up_bound(dim);\n    std::vector<double> low_bound(dim);\n\n    // only for ux/uy mode.\n    if (rf_->mode() == _ux_uy)\n      for (size_t i = 0; i < nsteps; i++) {\n        for (size_t j = 0; j < nchannels; j++) {\n          // ux.\n          up_bound[2 * nchannels * i + 2 * j] = val;\n          low_bound[2 * nchannels * i + 2 * j] = -val;\n\n          // uy.\n          up_bound[2 * nchannels * i + 2 * j + 1] = val;\n          low_bound[2 * nchannels * i + 2 * j + 1] = -val;\n        }\n      }\n\n    optimizer_->set_upper_bounds(up_bound);\n    optimizer_->set_lower_bounds(low_bound);\n  }\n}\n\ndouble grape::objfunc_broadband(const std::vector<double> &x, std::vector<double> &grad) {\n  auto start = std::chrono::system_clock::now();\n  rf_->update_raw_data(axis_, x.data());\n  int N = superop_.L0s.size();\n  vec phi = vec::Zero(N);\n\n  size_t nsteps = rf_->get_steps();\n  size_t nchannels = rf_->get_channels();\n  double dt = rf_->get_dt() * 1e-6;  // into s.\n  std::vector<std::string> chs = rf_->get_channels_str();\n\n  // double alpha = alpha0;\n  vec rf_scaling =\n      vec::LinSpaced(epsilon_num_, -epsilon_, epsilon_);  // e.g. -10% - 10%\n\n#pragma omp parallel for\n  for (int p = 0; p < N; p++) {\n    int id = omp_get_thread_num();\n    traj_omp_[id].forward[0] = init_state_;\n    traj_omp_[id].backward[nsteps] = targ_list_[p];\n    sp_cx_mat L;\n    sp_cx_mat L0 = superop_.L0s[p] + ci * superop_.R;\n\n    int dim = rf_->get_dims();\n    if (axis_ != uxuy_) dim /= 2;\n    superop_.grad_bb[p] = std::vector<double>(dim, 0);\n    // start rf inhom.\n\n    for (int q = 0; q < rf_scaling.size();\n         q++) {  // for each rf scaling factor, do\n\n      double kx = 1 + rf_scaling[q], ky = 1 + rf_scaling[q];\n\n      sp_cx_vec rho = traj_omp_[id].forward[0];\n      for (size_t i = 0; i < nsteps; i++) {\n        L = L0;\n        for (size_t j = 0; j < nchannels; j++)\n          L += update_rf_ham(x.data(), i, j, chs[j], nchannels, kx, ky);\n        traj_omp_[id].forward[i + 1] = ssl::spinsys::step(rho, L, dt);\n        rho = traj_omp_[id].forward[i + 1];\n      }\n      rho = traj_omp_[id].backward[nsteps];\n      for (int i = nsteps - 1; i >= 0; i--) {\n        L = L0.adjoint();\n        for (size_t j = 0; j < nchannels; j++)\n          L += update_rf_ham(x.data(), i, j, chs[j], nchannels, kx, ky);\n        traj_omp_[id].backward[i] = ssl::spinsys::step(rho, L, -dt);\n        rho = traj_omp_[id].backward[i];\n      }\n      sp_cx_mat Gx, Gy, tmp;\n      int k = 0;\n      for (size_t i = 0; i < nsteps; i++) {\n        L = L0;\n        for (size_t j = 0; j < nchannels; j++)\n          L += update_rf_ham(x.data(), i, j, chs[j], nchannels, kx, ky);\n        tmp = traj_omp_[id].backward[i + 1].adjoint() *\n              ssl::spinsys::propagator(L, dt);\n        for (size_t j = 0; j < nchannels; j++) {\n          if (axis_ == uxuy_) {\n            Gx = propagator_derivative(L, superop_.rf_ctrl.Lx[j], dt);\n            Gy = propagator_derivative(L, superop_.rf_ctrl.Ly[j], dt);\n\n            superop_.grad_bb[p][k] +=\n                traced(tmp * Gx * traj_omp_[id].forward[i]).real();\n            superop_.grad_bb[p][k + 1] +=\n                traced(tmp * Gy * traj_omp_[id].forward[i]).real();\n            k += 2;\n          } else if (axis_ == ux_) {\n            Gx = propagator_derivative(L, superop_.rf_ctrl.Lx[j], dt);\n\n            superop_.grad_bb[p][k] +=\n                traced(tmp * Gx * traj_omp_[id].forward[i]).real();\n            k += 1;\n          } else if (axis_ == uy_) {\n            Gy = propagator_derivative(L, superop_.rf_ctrl.Ly[j], dt);\n\n            superop_.grad_bb[p][k] +=\n                traced(tmp * Gy * traj_omp_[id].forward[i]).real();\n            k += 1;\n          }\n        }\n      }\n      phi[p] += transfer_fidelity(traj_omp_[id].forward[nsteps], targ_list_[p]);\n    }\n\n    /// transfer_fidelity(targ_list_[p], targ_list_[p]);\n  }  // end parallel for.\n\n  double val = phi.sum() / (double)N / (double)rf_scaling.size();\n\n  int k = 0;\n  for (size_t i = 0; i < nsteps; i++) {\n    for (size_t j = 0; j < nchannels; j++) {\n      double gx = 0;\n      double gy = 0;\n      if (axis_ == uxuy_) {\n        for (int p = 0; p < N; p++) {\n          gx += superop_.grad_bb[p][k];\n          gy += superop_.grad_bb[p][k + 1];\n        }\n        grad[k] = gx / (double)N / (double)rf_scaling.size();\n        grad[k + 1] = gy / (double)N / (double)rf_scaling.size();\n\n        // rf power reduction.\n        /*if (alpha != 0) {\n          double ux, uy;\n          ux = x[2 * nchannels * i + 2 * j];\n          uy = x[2 * nchannels * i + 2 * j + 1];\n          grad[k] -= 2.0 * alpha * ux * dt;\n          grad[k + 1] -= 2.0 * alpha * uy * dt;\n        }*/\n        k += 2;\n      } else if (axis_ == ux_) {\n        for (int p = 0; p < N; p++) {\n          gx += superop_.grad_bb[p][k];\n        }\n        grad[k] = gx / (double)N / (double)rf_scaling.size();\n\n        k += 1;\n      } else if (axis_ == uy_) {\n        for (int p = 0; p < N; p++) {\n          gy += superop_.grad_bb[p][k];\n        }\n        grad[k] = gy / (double)N / (double)rf_scaling.size();\n\n        k += 1;\n      }\n    }\n  }\n  auto end = std::chrono::system_clock::now();\n  auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);\n  if(double(duration.count()) * std::chrono::microseconds::period::num / std::chrono::microseconds::period::den>2){\n    g_oc_iteration_save = 1;\n  }\n  iteration_shape(x, optimizer_->get_numevals());\n  //double PHI1 = val;\n  //double PHI2 = 0;\n  // double PHI2 = alpha * rf_->rf_power();\n  // std::cout << boost::format(\"==> %04d  [%.8f] [%.8f]\\n\") %\n  // (++opt_.iter_count) % PHI1 % PHI2;\n  std::cout << boost::format(\"==> %04d  [%.8f]\\n\") % (optimizer_->get_numevals()) % val;\n obj_val_.push_back(val);\n  //std::cout << \"Use Time:\" << double(duration.count()) * microseconds::period::num / microseconds::period::den << \" s.\\n\";\n  return val;\n}\nvoid grape::iteration_shape(const std::vector<double> &x, int iter) {\n  if (!g_oc_iteration_save) return;\n  rf_->update_raw_data(axis_, x_.data());\n  std::string file = \"iteration_\" + std::to_string(iter) + \"_rf_shape.RF\";\n  std::ofstream ofstr(file.c_str());\n  ofstr << \"# \" << sys_time()<<\"\\n\";\n   rf_->write(ofstr);\n  ofstr.close();\n}\ndouble grape::objfunc_propagator(const std::vector<double> &x,\n                                 std::vector<double> &grad) {\n  auto start = std::chrono::system_clock::now();\n  rf_->update_raw_data(x.data());\n  int N = superop_.L0s.size();\n  vec phi = vec::Zero(N);\n\n  size_t nsteps = rf_->get_steps();\n  size_t nchannels = rf_->get_channels();\n  double dt = rf_->get_dt() * 1e-6;  // into s.\n  std::vector<std::string> chs = rf_->get_channels_str();\n\n  // double alpha = alpha0;\n  vec rf_scaling =\n      vec::LinSpaced(epsilon_num_, -epsilon_, epsilon_);  // e.g. -10% - 10%\n\n#pragma omp parallel for\n  for (int p = 0; p < N; p++) {\n    int id = omp_get_thread_num();\n    op_traj_omp_[id].forward[0] = init_op_;\n    op_traj_omp_[id].backward[nsteps] = targ_op_list_[p];\n    sp_cx_mat L;\n    sp_cx_mat L0 = superop_.L0s[p] + ci * superop_.R;\n\n     int dim = rf_->get_dims();\n    if (axis_ != uxuy_) dim /= 2;\n    superop_.grad_bb[p] = std::vector<double>(dim, 0);\n    // start rf inhom.\n\n    for (int q = 0; q < rf_scaling.size();\n         q++) {  // for each rf scaling factor, do\n\n      double kx = 1 + rf_scaling[q], ky = 1 + rf_scaling[q];\n\n      sp_cx_mat rho = op_traj_omp_[id].forward[0];\n      for (size_t i = 0; i < nsteps; i++) {\n        L = L0;\n        for (size_t j = 0; j < nchannels; j++)\n          L += update_rf_ham(x.data(), i, j, chs[j], nchannels, kx, ky);\n        op_traj_omp_[id].forward[i + 1] = ssl::spinsys::propagator(L, dt) * rho;\n        rho = op_traj_omp_[id].forward[i + 1];\n      }\n      rho = op_traj_omp_[id].backward[nsteps];\n      for (int i = nsteps - 1; i >= 0; i--) {\n        L = L0;\n        for (size_t j = 0; j < nchannels; j++)\n          L += update_rf_ham(x.data(), i, j, chs[j], nchannels, kx, ky);\n        op_traj_omp_[id].backward[i] =\n            ssl::spinsys::propagator(L, dt).adjoint() * rho;\n        rho = op_traj_omp_[id].backward[i];\n      }\n      sp_cx_mat Gx, Gy, tmp;\n      int k = 0;\n      for (size_t i = 0; i < nsteps; i++) {\n        L = L0;\n        for (size_t j = 0; j < nchannels; j++)\n          L += update_rf_ham(x.data(), i, j, chs[j], nchannels, kx, ky);\n        tmp = op_traj_omp_[id].backward[i + 1].adjoint() *\n              ssl::spinsys::propagator(L, dt);\n        for (size_t j = 0; j < nchannels; j++) {\n          if (axis_ == uxuy_) {\n            Gx = propagator_derivative(L, superop_.rf_ctrl.Lx[j], dt);\n            Gy = propagator_derivative(L, superop_.rf_ctrl.Ly[j], dt);\n\n            superop_.grad_bb[p][k] +=\n                traced(tmp * Gx * op_traj_omp_[id].forward[i]).real();\n            superop_.grad_bb[p][k + 1] +=\n                traced(tmp * Gy * op_traj_omp_[id].forward[i]).real();\n            k += 2;\n          } else if (axis_ == ux_) {\n            Gx = propagator_derivative(L, superop_.rf_ctrl.Lx[j], dt);\n\n            superop_.grad_bb[p][k] +=\n                traced(tmp * Gx * op_traj_omp_[id].forward[i]).real();\n            k += 1;\n          } else if (axis_ == uy_) {\n            Gy = propagator_derivative(L, superop_.rf_ctrl.Ly[j], dt);\n            superop_.grad_bb[p][k] +=\n                traced(tmp * Gy * op_traj_omp_[id].forward[i]).real();\n            k += 2;\n          }\n        }\n      }\n      phi[p] += transfer_fidelity(op_traj_omp_[id].forward[nsteps],\n                                  targ_op_list_[p]) /\n                transfer_fidelity(targ_op_list_[p], targ_op_list_[p]);\n    }\n\n    /// transfer_fidelity(targ_list_[p], targ_list_[p]);\n  }  // end parallel for.\n\n  double val = phi.sum() / (double)N / (double)rf_scaling.size();\n\n  int k = 0;\n  for (size_t i = 0; i < nsteps; i++) {\n    for (size_t j = 0; j < nchannels; j++) {\n      double gx = 0;\n      double gy = 0;\n     if (axis_ == uxuy_) {\n        for (int p = 0; p < N; p++) {\n          gx += superop_.grad_bb[p][k];\n          gy += superop_.grad_bb[p][k + 1];\n        }\n        grad[k] = gx / (double)N / (double)rf_scaling.size();\n        grad[k + 1] = gy / (double)N / (double)rf_scaling.size();\n\n        // rf power reduction.\n        /*if (alpha != 0) {\n          double ux, uy;\n          ux = x[2 * nchannels * i + 2 * j];\n          uy = x[2 * nchannels * i + 2 * j + 1];\n          grad[k] -= 2.0 * alpha * ux * dt;\n          grad[k + 1] -= 2.0 * alpha * uy * dt;\n        }*/\n        k += 2;\n      } else if (axis_ == ux_) {\n        for (int p = 0; p < N; p++) {\n          gx += superop_.grad_bb[p][k];\n        }\n        grad[k] = gx / (double)N / (double)rf_scaling.size();\n\n        k += 1;\n      } else if (axis_ == uy_) {\n        for (int p = 0; p < N; p++) {\n          gy += superop_.grad_bb[p][k];\n        }\n        grad[k] = gy / (double)N / (double)rf_scaling.size();\n\n        k += 1;\n      }\n    }\n  }\n\n  //double PHI1 = val;\n  //double PHI2 = 0;\n  // double PHI2 = alpha * rf_->rf_power();\n  // std::cout << boost::format(\"==> %04d  [%.8f] [%.8f]\\n\") %\n  // (++opt_.iter_count) % PHI1 % PHI2;\n\n  auto end = std::chrono::system_clock::now();\n  auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);\n  if(double(duration.count()) * std::chrono::microseconds::period::num / std::chrono::microseconds::period::den>2){\n    g_oc_iteration_save = 1;\n  }\n  iteration_shape(x, optimizer_->get_numevals());\n\n  std::cout << boost::format(\"==> %04d  [%.8f]\\n\") % (optimizer_->get_numevals()) % val;\n  obj_val_.push_back(val);\n  return (val);\n}\n// void grape::cartesian2polar(double amp, double phase, double gx, double gy,\n//                            double &g_amp, double &g_phase) {\n//  double ux = amp * cos(phase);\n//  double uy = amp * sin(phase);\n//  g_amp = gx * ux + gy * uy;\n//  g_amp /= amp;\n//  g_phase = -gx * uy + gy * ux;\n//}\n\ndouble grape::amplitude_constraint(unsigned n, const double *x, double *grad,\n                                   void *data) {\n  amp_constraint_data *d = reinterpret_cast<amp_constraint_data *>(data);\n\n  double ux = x[2 * d->chs * d->i + 2 * d->j];\n  double uy = x[2 * d->chs * d->i + 2 * d->j + 1];\n\n  return ux * ux + uy * uy - d->amp * d->amp;\n}\n\nsp_cx_mat grape::update_rf_ham(const double *x, size_t step, size_t channel, std::string ch_str,\n                               size_t nchannels, double kx, double ky) {\n  int ch = superop_.rf_ctrl.channel_index(ch_str);\n  if (axis_ == uxuy_) {\n    double ux = x[2 * nchannels * step + 2 * channel];\n    double uy = x[2 * nchannels * step + 2 * channel + 1];\n    // Rf inhom\n    ux *= kx;\n    uy *= ky;\n    return ux * superop_.rf_ctrl.Lx[ch] + uy * superop_.rf_ctrl.Ly[ch];\n  } else if (axis_ == ux_) {\n    double ux = x[nchannels * step + channel];\n    // Rf inhom\n    ux *= kx;\n    return ux * superop_.rf_ctrl.Lx[ch];\n  } else if (axis_ == uy_) {\n    double uy = x[nchannels * step + channel];\n    // Rf inhom\n    uy *= ky;\n    return uy * superop_.rf_ctrl.Ly[ch];\n  }\n}\nsp_cx_mat grape::propagator_derivative(const sp_cx_mat &L, const sp_cx_mat &Lrf, double dt) {\n  sp_cx_mat commu1, commu2, commu3;\n  commu1 = commutator(L, Lrf);\n  commu2 = commutator(L, commu1);\n  commu3 = commutator(L, commu2);\n  return -ci * dt * Lrf + 1 / 2.0 * dt * dt * commu1 + 1 / 6.0 * dt * dt * dt * commu2\n      - 1 / 24.0 * dt * dt * dt * dt * commu3;\n}\n\nvoid grape::projection(const sol::table &t) {\n  epsilon_ = 0;\n  epsilon_num_ = 1;  // default val.\n  if (is_retrievable(\"epsilon\", t)) {\n    epsilon_ = retrieve_table_double(\"epsilon\", t);\n  }\n  if (is_retrievable(\"epsilon_num\", t)) {\n    epsilon_num_ = retrieve_table_int(\"epsilon_num\", t);\n  }\n  sol::object val = retrieve_table(\"init_state\", t);\n  sp_cx_vec init_state = sys_->smart_state(val.as<std::string>());\n  init_state = norm_state(init_state);\n  //init_state = levante_ernst(init_state);\n\n  val = retrieve_table(\"rf\", t);\n  seq_block &sb = val.as<seq_block &>();\n shaped_rf &user_rf = (shaped_rf &) sb; // transfrom into 'shaped_rf'.\n  user_rf.convert2(_ux_uy);\n\n  size_t nsteps = user_rf.get_steps();\n  size_t nchannels = user_rf.get_channels();\n  double dt = user_rf.width_in_ms() * 1e-3 / double(nsteps); // into s.\n\n  std::map<std::string, sp_cx_vec> obsrv_state_map;\n  std::vector<std::string> expr;\n  std::vector<sp_cx_vec> obsrv_state;\n  if (is_retrievable(\"observ_states\", t)) {\n    val = retrieve_table(\"observ_states\", t);\n    sol::table expr_table = val.as<sol::table>();\n    if (expr_table.size() == 0) {\n      obsrv_state_map = sys_->cartesian_basis_states();\n    } else {\n      for (size_t i = 0; i < expr_table.size(); i++) {\n        sol::object val = expr_table[i + 1];\n        std::string exp = val.as<std::string>();\n        sp_cx_vec rho = sys_->smart_state(exp);\n        obsrv_state_map.insert(std::pair<std::string, sp_cx_vec>(exp, rho));\n      }\n    }\n\n  } else if (is_retrievable(\"ignore_states\", t)) {\n    val = retrieve_table(\"ignore_states\", t);\n    sol::table expr_table = val.as<sol::table>();\n    if (expr_table.size() == 0) {\n      obsrv_state_map = sys_->cartesian_basis_states();\n    } else {\n      obsrv_state_map = sys_->cartesian_basis_states();\n\n      for (size_t i = 0; i < expr_table.size(); i++) {\n        sol::object val = expr_table[i + 1];\n        std::string exp = val.as<std::string>();\n        std::map<std::string, sp_cx_vec>::iterator key = obsrv_state_map.find(exp);\n        if (key != obsrv_state_map.end()) obsrv_state_map.erase(key);\n      }\n    }\n  } else {\n    obsrv_state_map = sys_->cartesian_basis_states();\n  }\n\n  std::map<std::string, sp_cx_vec>::iterator iter;\n  for (iter = obsrv_state_map.begin(); iter != obsrv_state_map.end(); iter++) {\n    obsrv_state.push_back(norm_state(iter->second));\n    // obsrv_state.push_back(levante_ernst(iter->second));\n    expr.push_back(iter->first);\n  }\n  std::string dim1 = \"observed states\\n\";\n  std::string dim2 = \"\";\n  std::string dim3 = \"rf scaling\\n\";\n  std::string s;\n  for (size_t p = 0; p < expr.size(); p++)\n    s += std::to_string(p + 1) + \"-\" + expr[p] + \"\\n\";\n  dim1 += s;\n\n  std::string str_opt = \"step\";\n  if (is_retrievable(\"option\", t)) str_opt = retrieve_table_str(\"option\", t);\n\n  if (str_opt != \"step\" && str_opt != \"broadband\") {\n    std::string s = \"unknown projection option ** \" + str_opt +\n               \" ** using 'step' or 'broadband' instead.\";\n    throw std::runtime_error(s.c_str());\n  }\n\n  std::vector<double> x = user_rf.clone_raw_data();\n  vec rf_scaling =\n      vec::LinSpaced(epsilon_num_, -epsilon_, epsilon_);  // e.g. -10% - 10%\n\n  size_t n = rf_scaling.size();\n  if (n == 1)\n    dim3 += \"no rf inhomogeneity\";\n  else\n    dim3 += boost::lexical_cast<std::string>(rf_scaling[0] * 100) + \":\" +\n            boost::lexical_cast<std::string>(rf_scaling[n - 1] * 100) + \" \" +\n            boost::lexical_cast<std::string>(n) + \" %\\n\";\n\n  cube comp_dist;\n  // for BROADBAND case: states, freq offsets, rf scalings\n  // for STEP case: states, steps, rf scalings\n  std::vector<std::string> chs = rf_->get_channels_str();\n\n  if (str_opt == \"step\") {\n    dim2 = \"pulse steps\\n\";\n    dim2 += \"interval: \" + boost::lexical_cast<std::string>(dt) + \" s\\n\";\n    comp_dist = cube(obsrv_state.size(), nsteps,\n                     rf_scaling.size());  // states, steps, rf scalings\n    sp_cx_mat L;\n    sp_cx_mat L0 = superop_.L0 + ci * superop_.R;\n    sp_cx_vec *forward = new sp_cx_vec[nsteps + 1];\n    forward[0] = init_state;\n\n    for (int q = 0; q < rf_scaling.size();\n         q++) {  // for each rf scaling factor, do\n      double kx = 1 + rf_scaling[q], ky = 1 + rf_scaling[q];\n      sp_cx_vec rho = forward[0];\n\n      for (size_t i = 0; i < nsteps; i++) {\n        L = L0;\n        for (size_t j = 0; j < nchannels; j++)\n          L += update_rf_ham(x.data(), i, j, chs[j], nchannels, kx, ky);\n        forward[i + 1] = ssl::spinsys::step(rho, L, dt);\n        rho = forward[i + 1];\n\n        for (size_t k = 0; k < obsrv_state.size(); k++) {\n          sp_cx_vec compo = obsrv_state[k];\n          comp_dist(k, i, q) = transfer_fidelity(rho, compo);\n        }\n      }\n    }\n  } else if (str_opt == \"broadband\") {\n    dim2 = \"freq offsets\\n\";\n    int n = superop_.nominal_offset.size();\n    dim2 += boost::lexical_cast<std::string>(superop_.nominal_offset[0]) + \":\" +\n            boost::lexical_cast<std::string>(superop_.nominal_offset[n - 1]) + \" \" +\n            boost::lexical_cast<std::string>(n) + \" Hz\\n\";\n\n    comp_dist = cube(obsrv_state.size(), superop_.L0s.size(),\n                     rf_scaling.size());  // states, freq offsets, rf scalings\n\n    omp_set_num_threads(omp_core_num);\n\n    std::vector<sp_cx_vec *> forward_trajs_parfor =\n        std::vector<sp_cx_vec *>(omp_core_num);\n    for (int i = 0; i < omp_core_num; i++) {\n      sp_cx_vec *forward = new sp_cx_vec[nsteps + 1];\n      forward[0] = init_state;\n      forward_trajs_parfor[i] = forward;\n    }\n\n#pragma omp parallel for\n    for (int p = 0; p < superop_.L0s.size(); p++) {\n      int id = omp_get_thread_num();\n\n      for (int q = 0; q < rf_scaling.size();\n           q++) {  // for each rf scaling factor, do\n        double kx = 1 + rf_scaling[q], ky = 1 + rf_scaling[q];\n        sp_cx_mat L;\n        sp_cx_mat L0 = superop_.L0s[p] + ci * superop_.R;\n        sp_cx_vec rho = forward_trajs_parfor[id][0];\n\n        for (size_t i = 0; i < nsteps; i++) {\n          L = L0;\n          for (size_t j = 0; j < nchannels; j++)\n            L += update_rf_ham(x.data(), i, j, chs[j], nchannels, kx, ky);\n          forward_trajs_parfor[id][i + 1] = ssl::spinsys::step(rho, L, dt);\n          rho = forward_trajs_parfor[id][i + 1];\n        }\n\n        for (size_t k = 0; k < obsrv_state.size(); k++) {\n          sp_cx_vec compo = obsrv_state[k];\n          // transfer_wave(p, k) = transfer_fidelity(rho, compo);  // /\n          // transfer_fidelity(compo, compo);\n          comp_dist(k, p, q) = transfer_fidelity(rho, compo);\n        }\n      }\n    }\n  }\n\n  std::string time_s = sys_time();\n  H5File file(\"proj_\" + time_s + \".h5\", H5F_ACC_TRUNC);\n  ssl::utility::h5write(file, nullptr, \"projection\", comp_dist);\n  ssl::utility::h5write(file, nullptr, \"dim1\", dim1);\n  ssl::utility::h5write(file, nullptr, \"dim2\", dim2);\n  ssl::utility::h5write(file, nullptr, \"dim3\", dim3);\n  file.close();\n\n  if (rf_scaling.size() == 1) {  // no rf inhomogeneity.\n    Eigen::Tensor<double, 2> sub =\n        comp_dist.chip(0, 2);  // rf scaling at dim 2.\n    Eigen::Map<mat> m(sub.data(), sub.dimension(0), sub.dimension(1));\n    mat grid = m.matrix();\n\n    sol::table lines;\n\n    lines = g_lua->create_table();\n    for (int i = 0; i < grid.rows(); i++) {  // each state.\n      vec line = grid.row(i).transpose();\n      lines.add(line);\n    }\n\n    std::string fig_spec;\n    vec xval;\n    if (str_opt == \"step\") {\n      xval = vec::LinSpaced(grid.cols(), 0, user_rf.width_in_ms()); // transfer trajectories of basis operators\n\t  std::string s = retrieve_table_str(\"init_state\", t);\n      fig_spec = \"title<initial state: \" + s + \"> \";\n      fig_spec +=\n          \"xlabel<pulse \" //initial state I_{1y}\n          \"duration \"\n          \"/ ms> ylabel<magnetization>\";\n      fig_spec +=\n          \"xrange<0:\" + boost::lexical_cast<std::string>(user_rf.width_in_ms()) +\n          \"> \";\n    } else if (str_opt == \"broadband\") {\n      int n = superop_.nominal_offset.size();\n      xval = vec::LinSpaced(grid.cols(), superop_.nominal_offset[0],\n                            superop_.nominal_offset[n - 1]);\n      xval *= 1e-3;\n      fig_spec = \"xlabel<frequency offset / kHz> ylabel<magnetization>\"; // title<scan 1> \n      fig_spec += \"xrange<\" + boost::lexical_cast<std::string>(xval[0]) + \":\" +\n                  boost::lexical_cast<std::string>(xval[xval.size() - 1]) + \"> \";\n    }\n    if (expr.size() > 5)\n        fig_spec += \" gnuplot<set key outside>\";\n      //fig_spec += \" gnuplot<set label 'Scan 2' at graph 0.5,0.5 center font 'Arial,26'\\n set ytics 0.2\\n set key horizontal above>\";\n\t  //fig_spec += \" gnuplot<set label 'Scan 2' at graph 0.5,0.5 center font 'Arial,26'\\n set ytics 0.2\\n unset key>\";\n\t  //fig_spec += \" gnuplot<set ytics 0.2\\n unset key>\";\n\n    fig_spec += \" lw<7>\";\n    fig_spec += \" color<YiZhang16,16>\";\n    std::string lege;\n    for (size_t i = 0; i < expr.size(); i++) lege += expr[i] + \";\";\n    fig_spec += \" legend<\" + lege + \">\";\n    plot(fig_spec, line_series(xval, lines));\n    return;\n  }\n\n  // rf scaling case.\n\n  Eigen::Tensor<double, 2> sub =\n      comp_dist.chip(0, 0);  // observed states at dim 0, by default, plot the\n                             // map for first state.\n  std::string state_name = expr[0];\n  Eigen::Map<mat> m(sub.data(), sub.dimension(0), sub.dimension(1));\n  mat grid = m.matrix();\n\n  vec2 xrange, yrange;\n  yrange[0] = superop_.nominal_offset[0];\n  yrange[1] = superop_.nominal_offset[superop_.nominal_offset.size() - 1];\n  yrange *= 1e-3;  // into kHz.\n  xrange[0] = rf_scaling[0];\n  xrange[1] = rf_scaling[rf_scaling.size() - 1];\n  xrange *= 100;  // into %\n\n  utility::map gnu(grid, \"style<3d>\");\n  gnu.xrange = xrange;\n  gnu.yrange = yrange;\n  std::string fig_spec =\n      \"'ylabel<freq offset / kHz> xlabel<rf inhomogeneity / %> color<Spectral> \"\n      \"gnuplot<set xlabel offset -1,-1; set ylabel offset -2,-2; set palette \"\n      \"negative; set zrange [0.8:1]; set cbrange [0.8:1]> \";\n\n  (*g_lua)[\"_comp_dist\"] = gnu;\n  g_lua->script(\"plot(\" + fig_spec + \" title<magnetization map [\" + state_name +\n                \"]>', _comp_dist)\");\n}\n\n} /* namespace oc */\n} /* namespace ssl */\n", "meta": {"hexsha": "1e04d057e1cfdcc4f1a75b986371dc027d34f94a", "size": 33165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kernel/oc/grape.cpp", "max_stars_repo_name": "spin-scenario/spin-scenario", "max_stars_repo_head_hexsha": "1872b30cb229fd28033181568ffbc800f45d8a7a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-02-26T09:31:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:47:03.000Z", "max_issues_repo_path": "src/kernel/oc/grape.cpp", "max_issues_repo_name": "spin-scenario/spin-scenario", "max_issues_repo_head_hexsha": "1872b30cb229fd28033181568ffbc800f45d8a7a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-04-23T03:44:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T15:23:18.000Z", "max_forks_repo_path": "src/kernel/oc/grape.cpp", "max_forks_repo_name": "spin-scenario/spin-scenario", "max_forks_repo_head_hexsha": "1872b30cb229fd28033181568ffbc800f45d8a7a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-09T02:45:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-28T09:11:57.000Z", "avg_line_length": 34.8371848739, "max_line_length": 134, "alphanum_fraction": 0.5788331072, "num_tokens": 10310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.24676624590664586}}
{"text": "/* Software License Agreement (BSD License)\n*\n* Copyright (c) 2014, Ross Linscott (rossklin@gmail.com)\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions are\n* met:\n*\n*     Redistributions of source code must retain the above copyright\n*     notice, this list of conditions and the following disclaimer.\n*\n*     Redistributions in binary form must reproduce the above copyright\n*     notice, this list of conditions and the following disclaimer in\n*     the documentation and/or other materials provided with the\n*     distribution.\n*\n*     The names of its contributors may not be used to endorse or promote products\n*     derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#if defined(NDEBUG)\n#undef NDEBUG\n#endif\n\n#include <cstdlib>\n#include <cmath>\n#include <cstring>\n\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/date_time/posix_time/posix_time.hpp>\n\n#ifdef STANDALONE\n#include <RInside.h>\n#endif\n\n#include \"../inst/include/SimpleSDESampler.h\"\n  \nlpoly_evaluator::lpoly_evaluator(NumericMatrix cm, NumericMatrix trm) : terms(trm), coef_matrix(as_ublas_matrix(cm)){}\n\nvoid lpoly_evaluator::set_h(double v){\n  h = v;\n}\n\nNumericMatrix lpoly_evaluator::build(NumericMatrix data){\n  double value;\n  NumericMatrix result(data.nrow(), terms.nrow());\n  int i,j,k;\n\n  for (i = 0; i < data.nrow(); i++){\n    for (j = 0; j < terms.nrow(); j++){\n      value = 1;\n      for (k = 0; k < terms.ncol(); k++){\n\tvalue *= pow(data(i, k), terms(j,k));\n      }\n      result(i,j) = value;\n    }\n\n  }\n  return result;\n}\n\n// compute evaluation function\nvoid lpoly_evaluator::operator()(uvector &query, uvector &out, double t) {\n  if (query.size() != terms.ncol()){\n    Rcpp::Rcout << \"lpoly_evaluator::(): dimension mismatch: \" << query.size() << \" != \" << terms.ncol() << endl;\n    exit(-1);\n  }\n\n  NumericMatrix state(1, query.size(), query.begin());\n  NumericMatrix state_model = build(state);\n  uvector state_vector = as_ublas_vector(NumericVector(state_model.begin(), state_model.end()));\n\n  uvector dpart = prod(coef_matrix, state_vector);\n  out = dpart + (1 / sqrt(h)) * noise(t);\n}\n\nuvector lpoly_evaluator::noise(double t){\n  int idx = t / h + 0.5;\n  int dim = noise_precache.size2();\n  uvector x(dim);\n\n  if (idx >= noise_precache.size1()){\n    Rcpp::Rcout << \"Invalid time index: \" << idx << endl;\n    exit(1);\n  }\n\n  memcpy(&x[0], &noise_precache(idx,0), dim * sizeof(double));\n  return x;\n}\n\nvoid lpoly_evaluator::set_noise(umatrix m){\n  noise_precache = m;\n}\n\nvoid lpoly_evaluator::build_noise(int n, int d, double sigma){\n  int i;\n  int size = n * d;\n  double *p;\n\n  boost::mt19937 gener;\n  boost::normal_distribution<> normal(0,sigma*sigma);\n  boost::variate_generator<boost::mt19937&,boost::normal_distribution<> > rng(gener, normal);\n\n  boost::posix_time::time_duration diff_time = boost::posix_time::microsec_clock::local_time() - boost::posix_time::second_clock::local_time();\n  unsigned int the_seed = diff_time.total_microseconds();\n\n  rng.engine().seed(the_seed);\n  rng.distribution().reset();\n\n  noise_precache.resize(n, d);\n  p = &noise_precache(0,0);\n    \n  for (i = 0; i < size; i++){\n    p[i] = rng();\n  }\n}\n\nuvector lpoly_evaluator::evalfun(uvector query){\n  NumericMatrix state(1, query.size(), query.begin());\n  NumericMatrix state_model = build(state);\n  uvector state_vector = as_ublas_vector(NumericVector(state_model.begin(), state_model.end()));\n  return prod(coef_matrix, state_vector);\n}\n \nlpoly_jacobian::lpoly_jacobian(NumericMatrix cm, NumericMatrix trm) : terms(trm), coef_matrix(as_ublas_matrix(cm)){}\n\n// compute jacobian\nvoid lpoly_jacobian::operator()(uvector &q, umatrix &out, double t){\n  int i,j,k;\n  umatrix term_derivs = umatrix(terms.nrow(), terms.ncol());\n  double x;\n\n  for (i = 0; i < terms.nrow(); i++){\n    for (j = 0; j < terms.ncol(); j++){\n      // compute derivative of term i with respect to variable j\n      term_derivs(i,j) = 1;\n      for (k = 0; k < terms.ncol(); k++){\n\t// do something about corny case: q = 0, terms(i,k) = 0, j = k\n\t// which causes NAN but should actually be zero\n\tterm_derivs(i,j) *= pow(terms(i, k), j == k) * pow(q(k), terms(i,k) - (j == k));\n      }\n    }\n  }\n\n  out = prod(coef_matrix, term_derivs);\n}\n", "meta": {"hexsha": "3cf4afef4ed58019450fa3e2a150292023792803", "size": 5174, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/lpoly_evaluator.cc", "max_stars_repo_name": "rossklin/SimpleSDESampler", "max_stars_repo_head_hexsha": "bb45a818f2ee38065f41a2fa222207172eb61007", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lpoly_evaluator.cc", "max_issues_repo_name": "rossklin/SimpleSDESampler", "max_issues_repo_head_hexsha": "bb45a818f2ee38065f41a2fa222207172eb61007", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lpoly_evaluator.cc", "max_forks_repo_name": "rossklin/SimpleSDESampler", "max_forks_repo_head_hexsha": "bb45a818f2ee38065f41a2fa222207172eb61007", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1366459627, "max_line_length": 143, "alphanum_fraction": 0.6961731736, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24676623963613123}}
{"text": "#include <iostream>\n#include <fstream>\n\n#include <boost/algorithm/hex.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/marshalling.hpp>\n\n#include \"./types.h\"\n\n\nstd::string convert_byteblob_to_hex_string(std::vector<std::uint8_t> 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<std::uint8_t> 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<std::uint8_t> load_byteblob(boost::filesystem::path fname) {\n    boost::filesystem::ifstream stream(fname, std::ios::in | std::ios::binary);\n    std::vector<std::uint8_t> contents((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());\n    if (contents.size() == 0) {\n        throw std::ios_base::failure(\"Empty file\");\n    }\n    return contents;\n}\n\n// proving key\n\nvoid save_proving_key(scheme_type::proving_key_type pk, boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(pk);\n    save_byteblob(byteblob, fname);\n}\n\nscheme_type::proving_key_type load_proving_key(boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = load_byteblob(fname);\n    nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n    return nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::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<std::uint8_t> byteblob = nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(vk);\n    save_byteblob(byteblob, fname);\n}\n\nscheme_type::verification_key_type load_verification_key(boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = load_byteblob(fname);\n    nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n    return nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::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<std::uint8_t> byteblob = nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(proof);\n    save_byteblob(byteblob, fname);\n}\n\nscheme_type::proof_type load_proof(boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = load_byteblob(fname);\n    nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n    return nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::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<field_type> primary_input, boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = nil::marshalling::verifier_input_serializer_tvm<scheme_type>::process(primary_input);\n    save_byteblob(byteblob, fname);\n}\n\nzk::snark::r1cs_primary_input<field_type> load_primary_input(boost::filesystem::path fname) {\n    std::vector<std::uint8_t> byteblob = load_byteblob(fname);\n    nil::marshalling::status_type processingStatus = nil::marshalling::status_type::success;\n    return nil::marshalling::verifier_input_deserializer_tvm<scheme_type>::primary_input_process(\n        byteblob.cbegin(),\n        byteblob.cend(),\n        processingStatus);\n}\n", "meta": {"hexsha": "3e68ec0e2ae3a36cb483fc347a0c545a550792f9", "size": 3958, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "zkp/bin/utils.cpp", "max_stars_repo_name": "idealatom/zkp-covid-tracker", "max_stars_repo_head_hexsha": "18929551b93e3c274f4deffd7a7b6202aca8a962", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-03T09:16:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-03T09:16:00.000Z", "max_issues_repo_path": "zkp/bin/utils.cpp", "max_issues_repo_name": "idealatom/zkp-covid-tracker", "max_issues_repo_head_hexsha": "18929551b93e3c274f4deffd7a7b6202aca8a962", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "zkp/bin/utils.cpp", "max_forks_repo_name": "idealatom/zkp-covid-tracker", "max_forks_repo_head_hexsha": "18929551b93e3c274f4deffd7a7b6202aca8a962", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-08-30T05:23:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T10:45:19.000Z", "avg_line_length": 38.427184466, "max_line_length": 126, "alphanum_fraction": 0.7362304194, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.600188359260205, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2467439580784916}}
{"text": "#include \"Delaunay3D.hpp\"\n#include \"Predicates3D.hpp\"\n#include <limits>\n#include <algorithm>\n#include <fstream>\n#include \"HilbertOrder3D.hpp\"\n#include <boost/foreach.hpp>\n#include <iostream>\n//#define runcheks 1\n\nnamespace\n{\n\tbool InsideBigTetra(Vector3D const& tocheck, vector<Vector3D> const& cor, size_t Norg)\n\t{\n\t\tint sum = 0;\n#ifdef __INTEL_COMPILER\n#pragma omp simd reduction(+:sum)\n#endif \n\t\tfor (size_t i = 0; i < 4; ++i)\n\t\t{\n\t\t\tVector3D normal = CrossProduct(cor[Norg + (1 + i) % 4] - cor[Norg + i], cor[Norg + (2 + i) % 4] - cor[Norg + i]);\n\t\t\tdouble s1 = ScalarProd(normal, cor[Norg + (3 + i) % 4] - cor[Norg + i]);\n\t\t\tdouble s2 = ScalarProd(normal, tocheck - cor[Norg + i]);\n\t\t\tsum += (s1*s2 < 0) ? 1 : 0;\n\t\t}\n\t\treturn (sum==0);\n\t}\n\n\tbool PlaneLineIntersection(std::array<Vector3D, 3> &plane, Vector3D const& A, Vector3D const& B, Vector3D &res)\n\t{\n\t\tplane[1] -= plane[0];\n\t\tplane[2] -= plane[0];\n\t\tVector3D N = CrossProduct(plane[1], plane[2]);\n\t\tdouble Nsize = ScalarProd(N, N);\n\t\tdouble Rmin = std::min(ScalarProd(plane[1], plane[1]),ScalarProd(plane[2], plane[2]));\n\t\tplane[1] -= plane[2];\n\t\tRmin = std::min(Rmin,ScalarProd(plane[1], plane[1]));\n\t\tif (Nsize > (Rmin*Rmin * 1e4))\n\t\t\treturn false;\n\t\tplane[1] += plane[2];\n\t\tplane[1] += plane[0];\n\t\tplane[2] += plane[0];\n\t\tVector3D mu = B;\n\t\tmu -= A;\n\t\tdouble sp = ScalarProd(mu, N);\n\t\tif (sp*sp < ScalarProd(mu,mu)*Nsize*1e-8)\n\t\t\treturn false;\n\t\tdouble m = ScalarProd(N, plane[0] - A) / sp;\n\t\tres = A + m*mu;\n\t\treturn true;\n\t}\n\n\t\n\tvoid GetOppositePoint(Tetrahedron const& tetra, std::size_t neighbor,size_t &res)\n\t{\n#ifdef __INTEL_COMPILER\n#pragma ivdep\n#endif\n\t\tfor (size_t i=0; i < 4; i++)\n\t\t\tif (tetra.neighbors[i] == neighbor)\n\t\t\t{\n\t\t\t\tres = i;\n\t\t\t\treturn;\n\t\t\t}\n\t}\n\n\tvoid GetPointLocationInTetra(Tetrahedron const& tetra, std::size_t point,size_t &res)\n\t{\n#ifdef __INTEL_COMPILER\n#pragma ivdep\n#endif\n\t\tfor (size_t i = 0; i < 4; i++)\n\t\t\tif (tetra.points[i] == point)\n\t\t\t{\n\t\t\t\tres = i;\n\t\t\t\treturn;\n\t\t\t}\n\t}\n\n\tstd::pair<std::size_t,double> InTriangle(std::array<Vector3D, 3> &triangle, Vector3D &p)\n\t{\n\t\t// returns the smallest area of the cross product in units of the triangle area, negative if outside\n\t\tVector3D temp,d;\n\t\ttriangle[1] -= triangle[0];\n\t\ttriangle[2] -= triangle[0];\n\t\tCrossProduct(triangle[1], triangle[2], d);\n\t\tp -= triangle[0];\n\t\tCrossProduct(triangle[1], p, temp);\n\t\tdouble ad = ScalarProd(d, temp);\n\t\tp -= triangle[1];\n\t\ttriangle[2] -= triangle[1];\n\t\tCrossProduct(triangle[2], p, temp);\n\t\tdouble bd = ScalarProd(d, temp);\n\t\tp -= triangle[2];\n\t\ttriangle[2] += triangle[1];\n\t\tCrossProduct(p, triangle[2], temp);\n\t\tdouble cd = ScalarProd(d, temp);\n\n\t\tstd::pair<std::size_t, double> res(0, 0);\n\t\tif (ad < 0)\n\t\t\t++res.first;\n\t\tif (bd < 0)\n\t\t\t++res.first;\n\t\tif (cd < 0)\n\t\t\t++res.first;\n\t\tres.second = std::min(std::min(std::abs(ad), std::abs(bd)), std::abs(cd)) / (ScalarProd(d, d));\n\t\treturn res;\n\t}\n\n\tbool Are44(Tetrahedron const& T0, Tetrahedron const& T1, std::size_t loc_in_0, vector<Tetrahedron> const& tetras,\n\t\tstd::size_t &N3,std::size_t &N4)\n\t{\n\t\tN3 = T0.neighbors[loc_in_0];\n\t\tsize_t loc1=0;\n\t\tGetPointLocationInTetra(T1, T0.points[loc_in_0], loc1);\n\t\tN4 = T1.neighbors[loc1];\n\t\tfor (std::size_t i = 0; i < 4; ++i)\n\t\t\tif (tetras[N3].neighbors[i] == N4)\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\n}\n\nDelaunay3D& Delaunay3D::operator=(Delaunay3D const& other)\n{\n\tif (this == &other)\n\t\treturn *this;\n\ttetras_ = other.tetras_;\n\tpoints_ = other.points_;\n\tempty_tetras_ = other.empty_tetras_;\n\tNorg_ = other.Norg_;\n\toutside_neighbor_ = other.outside_neighbor_;\n\treturn *this;\n}\n\nDelaunay3D::Delaunay3D(Delaunay3D const& other) :  tetras_(other.tetras_),points_(other.points_),empty_tetras_(other.empty_tetras_),Norg_(other.Norg_),\n\toutside_neighbor_(other.outside_neighbor_),b3_temp_(std::array<Vector3D, 3> ()),b3_temp2_(std::array<Vector3D, 3> ()),\n\tb4_temp_(std::array<Vector3D, 4>()), b5_temp_(std::array<Vector3D, 5>()),b4s_temp_(std::array<std::size_t, 4> ()),\n\tb4s_temp2_(std::array<std::size_t, 4> ()),b8s_temp_(std::array<std::size_t, 8> ()),to_check_(vector<std::size_t>()),\n\tlast_checked_(0), tet_temp0_(Tetrahedron()), tet_temp1_(Tetrahedron()), newtet_(Tetrahedron()) {}\n\nvoid Delaunay3D::flip23(std::size_t tetra0, std::size_t tetra1, std::size_t location0,bool flat_check)\n{\n\tbool used_empty = false;\n\tstd::size_t Nloc = tetras_.size();\n\tif (!empty_tetras_.empty())\n\t{\n\t\tused_empty = true;\n\t\tNloc = *empty_tetras_.begin();\n\t\tempty_tetras_.erase(empty_tetras_.begin());\n\t}\n\n\t// location is the location of the point in tetra that is not in the joint triangle\n\ttet_temp0_ = tetras_[tetra0];\n\ttet_temp1_ = tetras_[tetra1];\n\tsize_t location1=0;\n\tGetOppositePoint(tet_temp1_, tetra0, location1);\n\n\tnewtet_.points[1] = tet_temp0_.points[(location0 + 1) % 4];\n\tnewtet_.points[2] = tet_temp0_.points[(location0 + 2) % 4];\n\n\tif (location0 % 2 == 1)\n\t{\n\t\tnewtet_.points[0] = tet_temp1_.points[location1];\n\t\tnewtet_.points[3] = tet_temp0_.points[location0];\n\t\tsize_t loctemp=0;\n\t\tGetPointLocationInTetra(tet_temp1_, tet_temp0_.points[(location0 + 3) % 4], loctemp);\n\t\tnewtet_.neighbors[3] = tet_temp1_.neighbors[loctemp];\n\t\tnewtet_.neighbors[0] = tet_temp0_.neighbors[(location0 + 3) % 4];\n\t\tif (newtet_.neighbors[0] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[newtet_.neighbors[0]], tetra0, loctemp);\n\t\t\ttetras_[newtet_.neighbors[0]].neighbors[loctemp] = Nloc;\n\t\t}\n\t\tif (newtet_.neighbors[3] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[newtet_.neighbors[3]], tetra1, loctemp);\n\t\t\ttetras_[newtet_.neighbors[3]].neighbors[loctemp] = Nloc;\n\t\t}\n\t}\n\telse\n\t{\n\t\tnewtet_.points[3] = tet_temp1_.points[location1];\n\t\tnewtet_.points[0] = tet_temp0_.points[location0];\n\t\tsize_t loctemp=0;\n\t\tGetPointLocationInTetra(tet_temp1_, tet_temp0_.points[(location0 + 3) % 4], loctemp);\n\t\tnewtet_.neighbors[0] = tet_temp1_.neighbors[loctemp];\n\t\tnewtet_.neighbors[3] = tet_temp0_.neighbors[(location0 + 3) % 4];\n\t\tif (newtet_.neighbors[0] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[newtet_.neighbors[0]], tetra1, loctemp);\n\t\t\ttetras_[newtet_.neighbors[0]].neighbors[loctemp] = Nloc;\n\t\t}\n\t\tif (newtet_.neighbors[3] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[newtet_.neighbors[3]], tetra0, loctemp);\n\t\t\ttetras_[newtet_.neighbors[3]].neighbors[loctemp] = Nloc;\n\t\t}\n\t}\n\tnewtet_.neighbors[1] = tetra0;\n\tnewtet_.neighbors[2] = tetra1;\n\t\n\tif (used_empty)\n\t\ttetras_[Nloc] = newtet_;\n\telse\n\t\ttetras_.push_back(newtet_);\n\n\tif (location0 % 2 == 0)\n\t{\n\t\ttetras_[tetra0].points[0] = tet_temp0_.points[location0];\n\t\ttetras_[tetra0].points[3] = tet_temp1_.points[location1];\n\t\tsize_t loctemp=0;\n\t\tGetPointLocationInTetra(tet_temp1_, tet_temp0_.points[(location0 + 1) % 4], loctemp);\n\t\ttetras_[tetra0].neighbors[0] = tet_temp1_.neighbors[loctemp];\n\t\ttetras_[tetra0].neighbors[3] = tet_temp0_.neighbors[(location0 + 1) % 4];\n\t\tif (tetras_[tetra0].neighbors[0] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[tetras_[tetra0].neighbors[0]], tetra1, loctemp);\n\t\t\ttetras_[tetras_[tetra0].neighbors[0]].neighbors[loctemp] = tetra0;\n\t\t}\n\t}\n\telse\n\t{\n\t\ttetras_[tetra0].points[3] = tet_temp0_.points[location0];\n\t\ttetras_[tetra0].points[0] = tet_temp1_.points[location1];\n\t\ttetras_[tetra0].neighbors[0] = tet_temp0_.neighbors[(location0 + 1) % 4];\n\t\tsize_t loctemp=0;\n\t\tGetPointLocationInTetra(tet_temp1_, tet_temp0_.points[(location0 + 1) % 4], loctemp);\n\t\ttetras_[tetra0].neighbors[3] = tet_temp1_.neighbors[loctemp];\n\t\tif (tetras_[tetra0].neighbors[3] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[tetras_[tetra0].neighbors[3]], tetra1, loctemp);\n\t\t\ttetras_[tetras_[tetra0].neighbors[3]].neighbors[loctemp] = tetra0;\n\t\t}\n\t}\n\ttetras_[tetra0].points[1] = tet_temp0_.points[(location0 + 2) % 4];\n\ttetras_[tetra0].points[2] = tet_temp0_.points[(location0 + 3) % 4];\n\ttetras_[tetra0].neighbors[1] = tetra1;\n\ttetras_[tetra0].neighbors[2] = Nloc;\n\n\tif (location0 % 2 == 0)\n\t{\n\t\ttetras_[tetra1].points[0] = tet_temp0_.points[location0];\n\t\ttetras_[tetra1].points[3] = tet_temp1_.points[location1];\n\t\tsize_t loctemp=0;\n\t\tGetPointLocationInTetra(tet_temp1_, tet_temp0_.points[(location0 + 2) % 4], loctemp);\n\t\ttetras_[tetra1].neighbors[0] = tet_temp1_.neighbors[loctemp];\n\t\ttetras_[tetra1].neighbors[3] = tet_temp0_.neighbors[(location0 + 2) % 4];\n\t\tif (tetras_[tetra1].neighbors[3] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[tetras_[tetra1].neighbors[3]], tetra0, loctemp);\n\t\t\ttetras_[tetras_[tetra1].neighbors[3]].neighbors[loctemp] = tetra1;\n\t\t}\n\t}\n\telse\n\t{\n\t\ttetras_[tetra1].points[0] = tet_temp1_.points[location1];\n\t\ttetras_[tetra1].points[3] = tet_temp0_.points[location0];\n\t\tsize_t loctemp=0;\n\t\tGetPointLocationInTetra(tet_temp1_, tet_temp0_.points[(location0 + 2) % 4], loctemp);\n\t\ttetras_[tetra1].neighbors[0] = tet_temp0_.neighbors[(location0 + 2) % 4];\n\t\ttetras_[tetra1].neighbors[3] = tet_temp1_.neighbors[loctemp];\n\t\tif (tetras_[tetra1].neighbors[0] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[tetras_[tetra1].neighbors[0]], tetra0, loctemp);\n\t\t\ttetras_[tetras_[tetra1].neighbors[0]].neighbors[loctemp] = tetra1;\n\t\t}\n\t}\n\ttetras_[tetra1].points[1] = tet_temp0_.points[(location0 + 3) % 4];\n\ttetras_[tetra1].points[2] = tet_temp0_.points[(location0 + 1) % 4];\n\ttetras_[tetra1].neighbors[1] = Nloc;\n\ttetras_[tetra1].neighbors[2] = tetra0;\n\n\tif(flat_check)\n\t{\n\t\tfor (size_t i = 0; i < 4; ++i)\n\t\t\tb4_temp_[i] = points_[tetras_[Nloc].points[i]];\n\t\tdouble orient = orient3d(b4_temp_);\n\t\tif (std::abs(orient) == 0)\n\t\t{\n\t\t\tstd::size_t my_loc=0; \n\t\t\tGetPointLocationInTetra(tetras_[Nloc], tet_temp0_.points[location0],my_loc);\n\t\t\tstd::size_t neigh = tetras_[Nloc].neighbors[my_loc];\n\t\t\tstd::size_t opp=0; \n\t\t\tGetOppositePoint(tetras_[neigh], Nloc,opp);\n\t\t\tfor (size_t i = 0; i < 3; ++i)\n\t\t\t\tb4_temp_[i] = points_[tetras_[Nloc].points[(my_loc + (i) + 1) % 4]];\n\t\t\tb4_temp_[3] = points_[tetras_[neigh].points[opp]];\n\t\t\tdouble o = orient3d(b4_temp_);\n\t\t\to *= 1.0 - static_cast<double>(2 * (location0 % 2));\n\t\t\tif (o > 0)\n\t\t\t{\n\t\t\t\tstd::size_t temp = tetras_[Nloc].points[0];\n\t\t\t\ttetras_[Nloc].points[0] = tetras_[Nloc].points[1];\n\t\t\t\ttetras_[Nloc].points[1] = temp;\n\t\t\t\ttemp = tetras_[Nloc].neighbors[0];\n\t\t\t\ttetras_[Nloc].neighbors[0] = tetras_[Nloc].neighbors[1];\n\t\t\t\ttetras_[Nloc].neighbors[1] = temp;\n\t\t\t}\n\t\t}\n\t\n\t\tfor (size_t i = 0; i < 4; ++i)\n\t\t\tb4_temp_[i] = points_[tetras_[tetra0].points[i]];\n\t\torient = orient3d(b4_temp_);\n\t\tif (std::abs(orient) == 0)\n\t\t{\n\t\t\tstd::size_t my_loc=0; \n\t\t\tGetPointLocationInTetra(tetras_[tetra0], tet_temp0_.points[location0],my_loc);\n\t\t\tstd::size_t neigh = tetras_[tetra0].neighbors[my_loc];\n\t\t\tstd::size_t opp=0; \n\t\t\tGetOppositePoint(tetras_[neigh], tetra0,opp);\n\t\t\tfor (size_t i = 0; i < 3; ++i)\n\t\t\t\tb4_temp_[i] = points_[tetras_[tetra0].points[(my_loc + i + 1) % 4]];\n\t\t\tb4_temp_[3] = points_[tetras_[neigh].points[opp]];\n\t\t\tdouble o = orient3d(b4_temp_);\n\t\t\to *= 1.0 - static_cast<double>(2 * (location0 % 2));\n\t\t\tif (o > 0)\n\t\t\t{\n\t\t\t\tstd::size_t temp = tetras_[tetra0].points[0];\n\t\t\t\ttetras_[tetra0].points[0] = tetras_[tetra0].points[1];\n\t\t\t\ttetras_[tetra0].points[1] = temp;\n\t\t\t\ttemp = tetras_[tetra0].neighbors[0];\n\t\t\t\ttetras_[tetra0].neighbors[0] = tetras_[tetra0].neighbors[1];\n\t\t\t\ttetras_[tetra0].neighbors[1] = temp;\n\t\t\t}\n\t\t}\n\t\tfor (size_t i = 0; i < 4; ++i)\n\t\t\tb4_temp_[i] = points_[tetras_[tetra1].points[i]];\n\t\torient = orient3d(b4_temp_);\n\t\tif (std::abs(orient) == 0)\n\t\t{\n\t\t\tstd::size_t my_loc=0;\n\t\t\tGetPointLocationInTetra(tetras_[tetra1], tet_temp0_.points[location0],my_loc);\n\t\t\tstd::size_t neigh = tetras_[tetra1].neighbors[my_loc];\n\t\t\tstd::size_t opp=0; \n\t\t\tGetOppositePoint(tetras_[neigh], tetra1,opp);\n\t\t\tfor (size_t i = 0; i < 3; ++i)\n\t\t\t\tb4_temp_[i] = points_[tetras_[tetra1].points[(my_loc + i + 1) % 4]];\n\t\t\tb4_temp_[3] = points_[tetras_[neigh].points[opp]];\n\t\t\tdouble o = orient3d(b4_temp_);\n\t\t\to *= 1.0 - static_cast<double>(2 * (location0 % 2));\n\t\t\tif (o > 0)\n\t\t\t{\n\t\t\t\tstd::size_t temp = tetras_[tetra1].points[0];\n\t\t\t\ttetras_[tetra1].points[0] = tetras_[tetra1].points[1];\n\t\t\t\ttetras_[tetra1].points[1] = temp;\n\t\t\t\ttemp = tetras_[tetra1].neighbors[0];\n\t\t\t\ttetras_[tetra1].neighbors[0] = tetras_[tetra1].neighbors[1];\n\t\t\t\ttetras_[tetra1].neighbors[1] = temp;\n\t\t\t}\n\t\t}\n\t}\n\n\tto_check_.push_back(tetra0);\n\tto_check_.push_back(tetra1);\n\tto_check_.push_back(Nloc);\n}\n\nvoid Delaunay3D::flip32(std::size_t tetra0, std::size_t tetra1, std::size_t location0,std::size_t shared_loction,\n\tbool flat_check)\n{\n\t// shared_loction is the point that is to be shared in the 2 new tetras. It is the point opposite to the shared edge by the three tetras in the triangle joint with the two tetras to check\n\tstd::size_t other_point = 20, other_point2 = 20;\n\tfor (std::size_t i = 0; i < 4; ++i)\n\t{\n\t\tif (i == location0 || i == shared_loction)\n\t\t\tcontinue;\n\t\tif (other_point == 20)\n\t\t\tother_point = i;\n\t\telse\n\t\t\tother_point2 = i;\n\t}\n\n\tstd::size_t location1=0;\n\tGetOppositePoint(tetras_[tetra1], tetra0,location1);\n\tstd::size_t third_tetra = tetras_[tetra0].neighbors[shared_loction];\n\ttet_temp0_ = tetras_[tetra0];\n\n\tif (location0 % 2 == 0)\n\t{\n\t\tnewtet_.points[0] = tetras_[tetra0].points[location0];\n\t\tnewtet_.points[1] = tetras_[tetra0].points[shared_loction];\n\t\tsize_t loctemp=0;\n\t\tGetPointLocationInTetra(tetras_[tetra1], tetras_[tetra0].points[other_point2], loctemp);\n\t\tnewtet_.neighbors[0] = tetras_[tetra1].neighbors[loctemp];\n\t\tGetPointLocationInTetra(tetras_[third_tetra], tetras_[tetra0].points[other_point2], loctemp);\n\t\tnewtet_.neighbors[1] = tetras_[third_tetra].neighbors[loctemp];\n\t\tif (newtet_.neighbors[0] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[newtet_.neighbors[0]], tetra1, loctemp);\n\t\t\ttetras_[newtet_.neighbors[0]].neighbors[loctemp] = tetra0;\n\t\t}\n\t\tif (newtet_.neighbors[1] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[newtet_.neighbors[1]], third_tetra, loctemp);\n\t\t\ttetras_[newtet_.neighbors[1]].neighbors[loctemp] = tetra0;\n\t\t}\n\t}\n\telse\n\t{\n\t\tnewtet_.points[0] = tetras_[tetra0].points[shared_loction];\n\t\tnewtet_.points[1] = tetras_[tetra0].points[location0];\t\t\n\t\tsize_t loctemp=0;\n\t\tGetPointLocationInTetra(tetras_[tetra1], tetras_[tetra0].points[other_point2], loctemp);\n\t\tnewtet_.neighbors[1] = tetras_[tetra1].neighbors[loctemp];\n\t\tGetPointLocationInTetra(tetras_[third_tetra], tetras_[tetra0].points[other_point2], loctemp);\n\t\tnewtet_.neighbors[0] = tetras_[third_tetra].neighbors[loctemp];\n\t\tif (newtet_.neighbors[1] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[newtet_.neighbors[1]], tetra1, loctemp);\n\t\t\ttetras_[newtet_.neighbors[1]].neighbors[loctemp] = tetra0;\n\t\t}\n\t\tif (newtet_.neighbors[0] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[newtet_.neighbors[0]], third_tetra, loctemp);\n\t\t\ttetras_[newtet_.neighbors[0]].neighbors[loctemp] = tetra0;\n\t\t}\n\t}\n\tnewtet_.points[2] = tetras_[tetra0].points[other_point];\n\tnewtet_.points[3] = tetras_[tetra1].points[location1];\n\n\tnewtet_.neighbors[2] = tetra1;\n\tnewtet_.neighbors[3] = tetras_[tetra0].neighbors[other_point2];\n\tif (flat_check)\n\t{\n\t\tfor (size_t i = 0; i < 4; ++i)\n\t\t\tb4_temp_[i] = points_[newtet_.points[i]];\n\t\tif (orient3d(b4_temp_) > 0)\n\t\t{\n\t\t\tstd::size_t temp = newtet_.points[0];\n\t\t\tnewtet_.points[0] = newtet_.points[1];\n\t\t\tnewtet_.points[1] = temp;\n\t\t\ttemp = newtet_.neighbors[0];\n\t\t\tnewtet_.neighbors[0] = newtet_.neighbors[1];\n\t\t\tnewtet_.neighbors[1] = temp;\n\t\t}\n\t}\n\ttetras_[tetra0] = newtet_;\n\t\n\tif (location0 % 2 == 1)\n\t{\n\t\tnewtet_.points[0] = tet_temp0_.points[location0];\n\t\tnewtet_.points[1] = tet_temp0_.points[shared_loction];\n\t\tsize_t loctemp=0;\n\t\tGetPointLocationInTetra(tetras_[tetra1], tet_temp0_.points[other_point], loctemp);\n\t\tnewtet_.neighbors[0] = tetras_[tetra1].neighbors[loctemp];\n\t\tGetPointLocationInTetra(tetras_[third_tetra], tet_temp0_.points[other_point], loctemp);\n\t\tnewtet_.neighbors[1] = tetras_[third_tetra].neighbors[loctemp];\n\t\tif (newtet_.neighbors[1] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[newtet_.neighbors[1]], third_tetra, loctemp);\n\t\t\ttetras_[newtet_.neighbors[1]].neighbors[loctemp] = tetra1;\n\t\t}\n\t}\n\telse\n\t{\n\t\tnewtet_.points[0] = tet_temp0_.points[shared_loction];\n\t\tnewtet_.points[1] = tet_temp0_.points[location0];\n\t\tsize_t loctemp=0;\n\t\tGetPointLocationInTetra(tetras_[tetra1], tet_temp0_.points[other_point], loctemp);\n\t\tnewtet_.neighbors[1] = tetras_[tetra1].neighbors[loctemp];\n\t\tGetPointLocationInTetra(tetras_[third_tetra], tet_temp0_.points[other_point], loctemp);\n\t\tnewtet_.neighbors[0] = tetras_[third_tetra].neighbors[loctemp];\n\t\tif (newtet_.neighbors[0] != outside_neighbor_)\n\t\t{\n\t\t\tGetOppositePoint(tetras_[newtet_.neighbors[0]], third_tetra, loctemp);\n\t\t\ttetras_[newtet_.neighbors[0]].neighbors[loctemp] = tetra1;\n\t\t}\n\t}\t\n\tnewtet_.points[2] = tet_temp0_.points[other_point2];\n\tnewtet_.points[3] = tetras_[tetra1].points[location1];\n\n\tnewtet_.neighbors[2] = tetra0;\n\tnewtet_.neighbors[3] = tet_temp0_.neighbors[other_point];\n\tif (newtet_.neighbors[3] != outside_neighbor_)\n\t{\n\t\tsize_t loctemp=0;\n\t\tGetOppositePoint(tetras_[newtet_.neighbors[3]], tetra0, loctemp);\n\t\ttetras_[newtet_.neighbors[3]].neighbors[loctemp] = tetra1;\n\t}\n\tif (flat_check)\n\t{\n\t\tfor (int i = 0; i < 4; ++i)\n\t\t\tb4_temp_[static_cast<size_t>(i)] = points_[newtet_.points[static_cast<size_t>(i)]];\n\t\tif (orient3d(b4_temp_) > 0)\n\t\t{\n\t\t\tstd::size_t temp = newtet_.points[0];\n\t\t\tnewtet_.points[0] = newtet_.points[1];\n\t\t\tnewtet_.points[1] = temp;\n\t\t\ttemp = newtet_.neighbors[0];\n\t\t\tnewtet_.neighbors[0] = newtet_.neighbors[1];\n\t\t\tnewtet_.neighbors[1] = temp;\n\t\t}\n\t}\n\ttetras_[tetra1] = newtet_;\n\n\tto_check_.push_back(tetra0);\n\tto_check_.push_back(tetra1);\n\n\tempty_tetras_.insert(third_tetra);\n\tif (third_tetra == last_checked_)\n\t\tlast_checked_ = tetra0;\n}\n\nvoid Delaunay3D::flip44(std::size_t tetra0, std::size_t tetra1, std::size_t location0, std::size_t neigh0,std::size_t neigh1)\n{\n\tstd::size_t shared_location = 20;\n\tfor (std::size_t i = 0; i < 4; ++i)\n\t{\n\t\tif (tetras_[neigh0].neighbors[i] == tetra0)\n\t\t{\n\t\t\tshared_location = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tassert(shared_location != 20);\n\n\tflip23(tetra0, tetra1, location0,true);\n\tlocation0 = 20;\n\tfor (std::size_t i = 0; i < 4; ++i)\n\t{\n\t\tif (tetras_[neigh0].neighbors[i] == neigh1)\n\t\t{\n\t\t\tlocation0 = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tassert(location0 != 20);\n\t\n\tflip32(neigh0, neigh1, location0, shared_location,true);\n}\n\nDelaunay3D::Delaunay3D() :tetras_(vector<Tetrahedron> ()),points_(vector<Vector3D> ()),empty_tetras_(boost::container::flat_set<size_t> ()),Norg_(0),outside_neighbor_(0),\n\tb3_temp_(std::array<Vector3D, 3> ()),b3_temp2_(std::array<Vector3D, 3> ()),b4_temp_(std::array<Vector3D, 4> ()),b5_temp_(std::array<Vector3D, 5> ()),\n\tb4s_temp_(std::array<std::size_t, 4>()),b4s_temp2_(std::array<std::size_t, 4>()),b8s_temp_(std::array<std::size_t, 8>()),\n\tto_check_(vector<std::size_t>()),last_checked_(0), tet_temp0_(Tetrahedron()),tet_temp1_(Tetrahedron()), newtet_(Tetrahedron())\n{\n\tempty_tetras_.reserve(15);\n\tto_check_.reserve(100);\n}\n\n\nDelaunay3D::~Delaunay3D()\n{}\n\nvoid Delaunay3D::BuildExtra(vector<Vector3D> const& points)\n{\n\tsize_t Nstart = points_.size();\n\tpoints_.insert(points_.end(), points.begin(), points.end());\n\tstd::vector<size_t> order = HilbertOrder3D(points);\n\tassert(to_check_.empty());\n\tfor (std::size_t i = 0; i < points.size(); ++i)\n\t{\n\t\tif(InsideBigTetra(points_[order[i] + Nstart],points_,Norg_))\n\t\t\tInsertPoint(order[i] + Nstart);\n\t}\n}\n\nvoid Delaunay3D::Build(vector<Vector3D> const & points, Vector3D const& maxv, Vector3D const& minv,\n\tstd::vector<size_t> &order)\n{\n\tempty_tetras_.clear();\n\tstd::size_t Norg = points.size();\n\tNorg_ = Norg;\n\tpoints_.reserve(Norg+ static_cast<std::size_t>(std::pow(Norg,0.6666)*14));\n\tpoints_.assign(points.begin(), points.end());\n\t// Create large tetra points\n\tdouble factor = 500;\n\tdouble dx = std::max(std::max(maxv.x - minv.x,maxv.y-minv.y),maxv.z-minv.z);\n\tpoints_.push_back(Vector3D(minv.x - 1.01*factor * dx, minv.y - factor * dx, minv.z - factor * dx));\n\tpoints_.push_back(Vector3D(0.5*(minv.x + maxv.x), maxv.y + 1.02*factor *dx, minv.z - factor * dx));\n\tpoints_.push_back(Vector3D(maxv.x + 0.99*factor * dx, minv.y - factor * dx, minv.z - factor * dx));\n\tpoints_.push_back(Vector3D(0.5*(minv.x + maxv.x), 0.5*(minv.y + maxv.y), maxv.z + factor * dx));\n\t// Create large tetra\n\toutside_neighbor_=std::numeric_limits<std::size_t>::max();\n\tTetrahedron tetra;\n\ttetra.points[0] = Norg;\n\ttetra.points[1] = Norg+2;\n\ttetra.points[2] = Norg+1;\n\ttetra.points[3] = Norg+3;\n\ttetra.neighbors[0] = outside_neighbor_;\n\ttetra.neighbors[1] = outside_neighbor_;\n\ttetra.neighbors[2] = outside_neighbor_;\n\ttetra.neighbors[3] = outside_neighbor_;\n\ttetras_.reserve(points_.capacity() * 7);\n\ttetras_.push_back(tetra);\n\tlast_checked_ = 0;\n\t\n\tassert(to_check_.empty());\n\tif (order.empty())\n\t\torder = HilbertOrder3D(points);\n\tfor (std::size_t i = 0; i < Norg; ++i)\n\t\tInsertPoint(order[i]);\n}\n\nvoid Delaunay3D::output(string const & filename) const\n{\n\tstd::ofstream fh(filename.c_str(), std::ios::out | std::ostream::binary);\n\n\tstd::size_t temp = tetras_.size() - empty_tetras_.size();\n\tfh.write(reinterpret_cast<const char*>(&temp), sizeof(std::size_t));\n\ttemp = points_.size();\n\tfh.write(reinterpret_cast<const char*>(&Norg_), sizeof(std::size_t));\n\tfh.write(reinterpret_cast<const char*>(&temp), sizeof(std::size_t));\n\n\tfor (std::size_t i = 0; i<points_.size(); ++i) \n\t{\n\t\tfh.write(reinterpret_cast<const char*>(&points_[i].x), sizeof(double));\n\t\tfh.write(reinterpret_cast<const char*>(&points_[i].y), sizeof(double));\n\t\tfh.write(reinterpret_cast<const char*>(&points_[i].z), sizeof(double));\n\t}\n\n\tfor (std::size_t i = 0; i<tetras_.size(); ++i) \n\t{\n\t\tif (empty_tetras_.find(i) == empty_tetras_.end())\n\t\t{\n\t\t\tfor (std::size_t j = 0; j < 4; ++j)\n\t\t\t{\n\t\t\t\tfh.write(reinterpret_cast<const char*>(&tetras_[i].points[j]), sizeof(std::size_t));\n\t\t\t}\n\t\t}\n\t}\n\n\tfh.close();\n}\n\nstd::size_t Delaunay3D::FindThirdNeighbor(std::size_t tetra0,std::size_t tetra1)\n{\n\tfor (size_t i = 0; i < 4; ++i)\n\t{\n\t\tfor (size_t j = 0; j < 4; ++j)\n\t\t{\n\t\t\tif (tetras_[tetra0].neighbors[i] == tetras_[tetra1].neighbors[j])\n\t\t\t{\n\t\t\t\tb8s_temp_[0] = tetras_[tetra1].neighbors[j];\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n\nvoid Delaunay3D::ExactFlip(std::size_t tetra0, std::size_t tetra1, std::size_t p)\n{\n\tstd::size_t out_counter = 0;\n\tstd::size_t other_point = 0;\n\tstd::size_t in_counter = 0;\n\tstd::size_t flat_counter = 0;\n\tstd::array<std::size_t, 3> out_check;\n\tTetrahedron const& T0 = tetras_[tetra0];\n\tTetrahedron const& T1 = tetras_[tetra1];\n\tstd::size_t p_loc=0;\n\tGetPointLocationInTetra(T0, p, p_loc);\n\tfor (int i = 0; i < 3; ++i)\n\t\tb3_temp_[i] = points_[T0.points[(p_loc + 1 + static_cast<size_t>(i)) % 4]];\n\n\tfor (size_t i = 0; i < 4; i++)\n\t{\n\t\tif (T1.neighbors[i] == tetra0)\n\t\t{\n\t\t\tother_point = T1.points[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tb4_temp_[0] = b3_temp_[1];\n\tb4_temp_[1] = b3_temp_[2];\n\tb4_temp_[2] = points_[p];\n\tb4_temp_[3] = b3_temp_[0];\n\tdouble test0 = orient3d(b4_temp_);\n\tif (std::abs(test0) == 0)\n\t\tin_counter++;\n\tb4_temp_[3] = points_[other_point];\n\tdouble test1 = orient3d(b4_temp_);\n\tif (std::abs(test1) == 0)\n\t\tflat_counter++;\n\tif (test0*test1 > 0)\n\t\tout_check[0] = 0;\n\telse\n\t{\n\t\tout_check[0] = 1;\n\t\t++out_counter;\n\t}\t\n\n\tb4_temp_[0] = b3_temp_[2];\n\tb4_temp_[1] = b3_temp_[0];\n\tb4_temp_[2] = points_[p];\n\tb4_temp_[3] = b3_temp_[1];\n\ttest0 = orient3d(b4_temp_);\n\tif (std::abs(test0) == 0)\n\t\tin_counter++;\n\tb4_temp_[3] = points_[other_point];\n\ttest1 = orient3d(b4_temp_);\n\tif (std::abs(test1) == 0)\n\t\tflat_counter++;\n\tif (test0*test1 > 0)\n\t\tout_check[1] = 0;\n\telse\n\t{\n\t\tout_check[1] = 1;\n\t\t++out_counter;\n\t}\n\n\tb4_temp_[0] = b3_temp_[0];\n\tb4_temp_[1] = b3_temp_[1];\n\tb4_temp_[2] = points_[p];\n\tb4_temp_[3] = b3_temp_[2];\n\ttest0 = orient3d(b4_temp_);\n\tif (std::abs(test0) == 0)\n\t\tin_counter++;\n\tb4_temp_[3] = points_[other_point];\n\ttest1 = orient3d(b4_temp_);\n\tif (std::abs(test1) == 0)\n\t\tflat_counter++;\n\tif (test0*test1 > 0)\n\t\tout_check[2] = 0;\n\telse\n\t{\n\t\tout_check[2] = 1;\n\t\t++out_counter;\n\t}\n\t\t\n\tif (out_counter == 0)\n\t\tflip23(tetra0, tetra1, p_loc,true);\n\telse\n\t{\n\t\tif (out_counter == 1)\n\t\t{\n\t\t\tstd::size_t N_shared = FindThirdNeighbor(tetra0, tetra1);\n\t\t\tif (N_shared == 1)\n\t\t\t{\n\t\t\t\tstd::size_t shared_loc=0;\n\t\t\t\tGetOppositePoint(tetras_[tetra0], b8s_temp_[0],shared_loc);\n\t\t\t\tflip32(tetra0, tetra1, p_loc, shared_loc,true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (flat_counter > 0)\n\t\t\t\t{\n\t\t\t\t\tfor (std::size_t i = 0; i < 3; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::size_t N3=0, N4=0;\n\t\t\t\t\t\tif (out_check[i] == 1 && Are44(T0, T1, (p_loc + i + 1) % 4, tetras_, N3, N4))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tflip44(tetra0, tetra1, p_loc, N3, N4);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (in_counter == 3) // tetra0 is flat\n\t\t\t{\n\t\t\t\t//is a 32 flip possible?\n\t\t\t\tstd::size_t N_shared = FindThirdNeighbor(tetra0, tetra1);\n\t\t\t\tif (N_shared == 1)\n\t\t\t\t{\n\t\t\t\t\tstd::size_t shared_loc=0;\n\t\t\t\t\tGetOppositePoint(tetras_[tetra0], b8s_temp_[0],shared_loc);\n\t\t\t\t\tflip32(tetra0, tetra1, p_loc, shared_loc,true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tflip23(tetra0, tetra1, p_loc,true);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Delaunay3D::FindFlip(std::size_t tetra0,std::size_t tetra1,std::size_t p,size_t p_loc,size_t other_point_loc)\n{\n\tsize_t *tetcheck = tetras_[tetra0].points;\n#ifdef __INTEL_COMPILER\n#pragma ivdep\n#endif\n\tfor (std::size_t i = 0; i < 3;++i)\n\t\t//b3_temp_[i] = points_[tetras_[tetra0].points[(p_loc + i + 1) % 4]];\n\t\tb3_temp_[i] = points_[tetcheck[(p_loc + i + 1) % 4]];\n\tVector3D intersection;\n\tbool good_intersection = PlaneLineIntersection(b3_temp_, points_[p],\n\t\tpoints_[tetras_[tetra1].points[other_point_loc]],intersection);\n\tstd::pair<std::size_t, double> outside_intersection;\n\tif (!good_intersection)\n\t\toutside_intersection.second = 0;\n\telse\n\t\toutside_intersection= InTriangle(b3_temp_, intersection);\n\tif (outside_intersection.second<1e-6)\n\t{\n\t\tExactFlip(tetra0, tetra1, p);\n\t\treturn;\n\t}\n\tif (outside_intersection.first == 0)\n\t{\n\t\tflip23(tetra0, tetra1, p_loc,false);\n\t\treturn;\n\t}\n\tif (outside_intersection.first == 1)\n\t{\n\t\t// Do we have a shared neighbor?\n\t\tstd::size_t Nshared = FindThirdNeighbor(tetra0, tetra1);\n\t\tif (Nshared == 1)\n\t\t{\n\t\t\tstd::size_t shared_loc=0;\n\t\t\tGetOppositePoint(tetras_[tetra0], b8s_temp_[0],shared_loc);\n\t\t\tflip32(tetra0, tetra1, p_loc, shared_loc,false);\n\t\t}\n\t}\t\n}\n\nvoid Delaunay3D::InsertPoint(std::size_t index)\n{\n\tstd::size_t to_split = Walk(index, last_checked_);\n\tlast_checked_ = to_split;\n\tflip14(index, to_split);\n\twhile (!to_check_.empty())\n\t{\n\t\tstd::size_t cur_check = to_check_.back();\n\t\tto_check_.pop_back();\n\t\tsize_t p_loc=0;\n\t\tGetPointLocationInTetra(tetras_[cur_check], index,p_loc);\n\t\tstd::size_t to_flip = tetras_[cur_check].neighbors[p_loc];\n\t\tif (to_flip == outside_neighbor_ || (empty_tetras_.find(cur_check) != empty_tetras_.end()))\n\t\t\tcontinue;\n\t\tsize_t other_point_loc=0;\n\t\tGetOppositePoint(tetras_[to_flip], cur_check,other_point_loc);\n\t\tb5_temp_[4] = points_[tetras_[to_flip].points[other_point_loc]];\n\t\tb5_temp_[0] = points_[tetras_[cur_check].points[0]];\n\t\tb5_temp_[1] = points_[tetras_[cur_check].points[1]];\n\t\tb5_temp_[2] = points_[tetras_[cur_check].points[2]];\n\t\tb5_temp_[3] = points_[tetras_[cur_check].points[3]];\n\t\tif (insphere(b5_temp_) < -0)\n\t\t{\n\t\t\tFindFlip(cur_check, to_flip,index,p_loc,other_point_loc);\n\t\t}\n\t}\n}\n\nstd::size_t Delaunay3D::Walk(std::size_t point, std::size_t first_guess) \n{\n\tbool good = false;\n\tstd::size_t cur_facet = first_guess;\n\tstd::size_t counter=0;\n\tb4_temp_[3] = points_[point];\n\twhile (!good)\n\t{\n\t\t++counter;\n\t\tgood = true;\n\t\tfor (size_t i = 0; i < 4; ++i)\n\t\t{\n\t\t\tfor (size_t j = 0; j < 3; j++)\n\t\t\t\tb4_temp_[j] = points_[tetras_[cur_facet].points[(i + j + 1) % 4]];\n\t\t\tint sign = 2 * static_cast<int>(i % 2) - 1;\n\t\t\tif ((orient3d(b4_temp_)*sign)>0)\n\t\t\t{\n\t\t\t\tgood = false;\n\t\t\t\tsize_t old_facet = cur_facet;\n\t\t\t\tcur_facet = tetras_[cur_facet].neighbors[i];\n\t\t\t\tif(cur_facet == outside_neighbor_)\n\t\t\t\t{\n\t\t\t\t\tstd::cout<<\"Walk wanted to goto outside neighbor\"<<std::endl;\n\t\t\t\t\tstd::cout << \"Total of \"<< Norg_ << \" points\" << std::endl;\n\t\t\t\t\tstd::cout<<\"point \"<<point<<\" \"<<points_[point].x<<\" \"<<points_[point].y<<\" \"<<points_[point].z<<\" \"<<std::endl;\n\t\t\t\t\tstd::cout<<\"Big tetrahedron \"<<points_[Norg_].x<<\" \"<<points_[Norg_].y<<\" \"<<points_[Norg_].z<<\" \"<<std::endl;\n\t\t\t\t\tstd::cout<<\"Big tetrahedron \"<<points_[Norg_+1].x<<\" \"<<points_[Norg_+1].y<<\" \"<<points_[Norg_+1].z<<\" \"<<std::endl;\n\t\t\t\t\tstd::cout<<\"Big tetrahedron \"<<points_[Norg_+2].x<<\" \"<<points_[Norg_+2].y<<\" \"<<points_[Norg_+2].z<<\" \"<<std::endl;\n\t\t\t\t\tstd::cout<<\"Big tetrahedron \"<<points_[Norg_+3].x<<\" \"<<points_[Norg_+3].y<<\" \"<<points_[Norg_+3].z<<\" \"<<std::endl;\n\t\t\t\t\tstd::cout << \"Came from face \" << old_facet << std::endl;\n\t\t\t\t\tfor (size_t j = 0; j < 3; ++j)\n\t\t\t\t\t\tstd::cout <<\"point \"<< tetras_[old_facet].points[(i + static_cast<size_t>(j) + 1) % 4]<<\" \"<< b4_temp_[j].x << \" \" << b4_temp_[j].y << \" \" << b4_temp_[j].z << std::endl;\n\t\t\t\t\tUniversalError eo(\"Bad Walk\");\n\t\t\t\t\tthrow eo;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tassert(counter < 100000);\n\t}\n\treturn cur_facet;\n}\n\nvoid Delaunay3D::flip14(std::size_t point, std::size_t tetra)\n{\n\tTetrahedron toadd;\n\tstd::array<std::size_t, 3> Nloc;\n\tbool cleared_empty = false;\n\tif (empty_tetras_.size()>3)\n\t{\n\t\tcleared_empty = true;\n\t\tfor (size_t i = 0; i < 3; i++)\n\t\t{\n\t\t\tNloc[i] = *empty_tetras_.begin();\n\t\t\tempty_tetras_.erase(empty_tetras_.begin());\n\t\t}\t\n\t}\n\telse\n\t{\n\t\tsize_t Ntet = tetras_.size();\n\t\tfor (size_t i = 0; i < 3; i++)\n\t\t\tNloc[i] = Ntet + i;\n\t}\n\n\ttoadd.neighbors[0] = Nloc[1];\n\ttoadd.neighbors[1] = Nloc[2];\n\ttoadd.neighbors[2] = tetras_[tetra].neighbors[0];\n\ttoadd.neighbors[3] = tetra;\n\ttoadd.points[0] = tetras_[tetra].points[1];\n\ttoadd.points[1] = tetras_[tetra].points[2];\n\ttoadd.points[2] = point;\n\ttoadd.points[3] = tetras_[tetra].points[3];\n\tif (toadd.neighbors[2] != outside_neighbor_)\n\t{\n\t\tsize_t temploc = toadd.neighbors[2];\n\t\tsize_t loctemp=0;\n\t\tGetOppositePoint(tetras_[temploc], tetra, loctemp);\n\t\ttetras_[toadd.neighbors[2]].neighbors[loctemp] = Nloc[0];\n\t}\n\tif (!cleared_empty)\n\t\ttetras_.push_back(toadd);\n\telse\n\t\ttetras_[Nloc[0]] = toadd;\n\n\ttoadd.neighbors[0] = Nloc[0];\n\ttoadd.neighbors[1] = Nloc[2];\n\ttoadd.neighbors[2] = tetra;\n\ttoadd.neighbors[3] = tetras_[tetra].neighbors[1];\n\ttoadd.points[0] = tetras_[tetra].points[0];\n\ttoadd.points[1] = tetras_[tetra].points[2];\n\ttoadd.points[2] = tetras_[tetra].points[3];\n\ttoadd.points[3] = point;\n\tif (toadd.neighbors[3] != outside_neighbor_)\n\t{\n\t\tsize_t loctemp=0;\n\t\tGetOppositePoint(tetras_[toadd.neighbors[3]], tetra, loctemp);\n\t\ttetras_[toadd.neighbors[3]].neighbors[loctemp] = Nloc[1];\n\t}\n\tif (!cleared_empty)\n\t\ttetras_.push_back(toadd);\n\telse\n\t\ttetras_[Nloc[1]] = toadd;\n\n\ttoadd.neighbors[0] = Nloc[0];\n\ttoadd.neighbors[1] = tetra;\n\ttoadd.neighbors[2] = Nloc[1];\n\ttoadd.neighbors[3] = tetras_[tetra].neighbors[2];\n\ttoadd.points[0] = tetras_[tetra].points[0];\n\ttoadd.points[1] = tetras_[tetra].points[3];\n\ttoadd.points[2] = tetras_[tetra].points[1];\n\ttoadd.points[3] = point;\n\tif (toadd.neighbors[3] != outside_neighbor_)\n\t{\n\t\tsize_t loctemp=0;\n\t\tGetOppositePoint(tetras_[toadd.neighbors[3]], tetra, loctemp);\n\t\ttetras_[toadd.neighbors[3]].neighbors[loctemp] = Nloc[2];\n\t}\n\tif (!cleared_empty)\n\t\ttetras_.push_back(toadd);\n\telse\n\t\ttetras_[Nloc[2]] = toadd;\n\n\t\n\ttetras_[tetra].neighbors[0] = Nloc[0];\n\ttetras_[tetra].neighbors[1] = Nloc[1];\n\ttetras_[tetra].neighbors[2] = Nloc[2];\n\ttetras_[tetra].points[3] = point;\n\t\n\tto_check_.push_back(tetra);\n\tto_check_.push_back(Nloc[0]);\n\tto_check_.push_back(Nloc[1]);\n\tto_check_.push_back(Nloc[2]);\n#ifdef runcheks\n\tfor (std::size_t i = 0; i < 4; ++i)\n\t\tb4_temp_[i] = points_[tetras_[tetras_.size() - 1].points[i]];\n\tassert(orient3d(b4_temp_) <= 0);\n\tfor (std::size_t i = 0; i < 4; ++i)\n\t\tb4_temp_[i] = points_[tetras_[tetras_.size()-2].points[i]];\n\tassert(orient3d(b4_temp_) <= 0);\n\tfor (std::size_t i = 0; i < 4; ++i)\n\t\tb4_temp_[i] = points_[tetras_[tetras_.size() - 3].points[i]];\n\tassert(orient3d(b4_temp_) <= 0);\n\tfor (std::size_t i = 0; i < 4; ++i)\n\t\tb4_temp_[i] = points_[tetras_[tetra].points[i]];\n\tassert(orient3d(b4_temp_) <= 0);\n#endif\n}\n\nbool Delaunay3D::CheckCorrect(void)\n{\n\tstd::size_t Ntetra = tetras_.size();\n\t\n\tfor (std::size_t i = 0; i < Ntetra; ++i)\n\t{\n\t\tif (empty_tetras_.find(i) != empty_tetras_.end())\n\t\t\tcontinue;\n\t\tTetrahedron const& T = tetras_[i];\t\t\n\t\tb5_temp_[0] = points_[T.points[0]];\n\t\tb5_temp_[1] = points_[T.points[1]];\n\t\tb5_temp_[2] = points_[T.points[2]];\n\t\tb5_temp_[3] = points_[T.points[3]];\n\t\tfor (std::size_t j = 0; j < 4; ++j)\n\t\t{\n\t\t\tsize_t loctemp=4;\n\t\t\t// Check same neighbors\n\t\t\tif (T.neighbors[j] != outside_neighbor_)\n\t\t\t{\n\t\t\t\tGetOppositePoint(tetras_[T.neighbors[j]], i, loctemp);\n\t\t\t\tassert(loctemp < 4);\n\t\t\t}\n\t\t\t// Check insphere\n\t\t\tif (T.neighbors[j] != outside_neighbor_)\n\t\t\t{\n\t\t\t\tstd::size_t other=4;\n\t\t\t\tGetOppositePoint(tetras_[T.neighbors[j]], i,other);\n\t\t\t\tassert(other < 4);\n\t\t\t\tb5_temp_[4] = points_[tetras_[T.neighbors[j]].points[other]];\n\t\t\t\tassert(!(insphere(b5_temp_) < 0));\n\t\t\t}\n\t\t}\t\t\t\n\t}\n\treturn true;\n}\n\nvoid Delaunay3D::Clean(void)\n{\n\ttetras_.clear();\n\tpoints_.clear();\n\tempty_tetras_.clear();\n}\n", "meta": {"hexsha": "f36fab8f9cf73097012f5d9292d98adca8b31e02", "size": 32851, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/3D/GeometryCommon/Delaunay3D.cpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/3D/GeometryCommon/Delaunay3D.cpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/3D/GeometryCommon/Delaunay3D.cpp", "max_forks_repo_name": "GalaxyHunters/Vivid", "max_forks_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-29T09:39:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-25T19:17:49.000Z", "avg_line_length": 31.8323643411, "max_line_length": 188, "alphanum_fraction": 0.6728866701, "num_tokens": 12047, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.24673349367764888}}
{"text": "#include \"Kernels/TimeBase.h\"\n#include \"Kernels/Time.h\"\n\n#ifndef NDEBUG\nextern long long libxsmm_num_total_flops;\n#endif\n\n#include <Kernels/common.hpp>\n#include <Kernels/denseMatrixOps.hpp>\n\n#include <cstring>\n#include <cassert>\n#include <stdint.h>\n#include <omp.h>\n#include <Eigen/Dense>\n\n#include \"Equations/poroelastic/Model/PoroelasticSetup.h\"\n\n#include <yateto.h>\n\nGENERATE_HAS_MEMBER(ET)\nGENERATE_HAS_MEMBER(sourceMatrix)\n\nseissol::kernels::TimeBase::TimeBase(){\n  m_derivativesOffsets[0] = 0;\n  for (int order = 0; order < CONVERGENCE_ORDER; ++order) {\n    if (order > 0) {\n      m_derivativesOffsets[order] = tensor::dQ::size(order-1) + m_derivativesOffsets[order-1];\n    }\n  }\n}\n\nvoid seissol::kernels::Time::setHostGlobalData(GlobalData const* global) {\n  for (int n = 0; n < CONVERGENCE_ORDER; ++n) {\n    if (n > 0) {\n      for (int d = 0; d < 3; ++d) {\n        m_krnlPrototype.kDivMTSub(d,n) = init::kDivMTSub::Values[tensor::kDivMTSub::index(d,n)];\n      }\n    }\n    m_krnlPrototype.selectModes(n) = init::selectModes::Values[tensor::selectModes::index(n)];\n  }\n  for (int k = 0; k < NUMBER_OF_QUANTITIES; k++) {\n    m_krnlPrototype.selectQuantity(k) = init::selectQuantity::Values[tensor::selectQuantity::index(k)];\n    m_krnlPrototype.selectQuantityG(k) = init::selectQuantityG::Values[tensor::selectQuantityG::index(k)];\n  }\n  m_krnlPrototype.timeInt = init::timeInt::Values;\n  m_krnlPrototype.wHat = init::wHat::Values;\n}\n\nvoid seissol::kernels::Time::setGlobalData(const CompoundGlobalData& global) {\n  setHostGlobalData(global.onHost);\n\n#ifdef ACL_DEVICE\n  logError() << \"Poroelasticity does not work on GPUs.\";\n#endif\n}\n\nvoid seissol::kernels::Time::executeSTP( double                      i_timeStepWidth,\n                                         LocalData&                  data,\n                                         real                        o_timeIntegrated[tensor::I::size()],\n                                         real*                       stp )\n\n{\n  alignas(PAGESIZE_STACK) real stpRhs[tensor::spaceTimePredictorRhs::size()];\n  assert( ((uintptr_t)stp) % PAGESIZE_STACK  == 0);\n  std::fill(std::begin(stpRhs), std::end(stpRhs), 0);\n  std::fill(stp, stp + tensor::spaceTimePredictor::size(), 0);\n  kernel::spaceTimePredictor krnl = m_krnlPrototype;\n \n  //libxsmm can not generate GEMMs with alpha!=1. As a workaround we multiply the \n  //star matrices with dt before we execute the kernel.\n  real A_values[init::star::size(0)];\n  real B_values[init::star::size(1)];\n  real C_values[init::star::size(2)];\n  for (size_t i = 0; i < init::star::size(0); i++) {\n    A_values[i] = i_timeStepWidth * data.localIntegration.starMatrices[0][i];\n    B_values[i] = i_timeStepWidth * data.localIntegration.starMatrices[1][i];\n    C_values[i] = i_timeStepWidth * data.localIntegration.starMatrices[2][i];\n  }\n  krnl.star(0) = A_values;\n  krnl.star(1) = B_values;\n  krnl.star(2) = C_values;\n\n  //The matrix Zinv depends on the timestep\n  //If the timestep is not as expected e.g. when approaching a sync point\n  //we have to recalculate it\n  if (i_timeStepWidth != data.localIntegration.specific.typicalTimeStepWidth) {\n    auto sourceMatrix = init::ET::view::create(data.localIntegration.specific.sourceMatrix);\n    real ZinvData[NUMBER_OF_QUANTITIES][CONVERGENCE_ORDER*CONVERGENCE_ORDER];\n    model::zInvInitializerForLoop<0, NUMBER_OF_QUANTITIES, decltype(sourceMatrix)>(ZinvData, sourceMatrix, i_timeStepWidth);\n    for (size_t i = 0; i < NUMBER_OF_QUANTITIES; i++) {\n      krnl.Zinv(i) = ZinvData[i];\n    }\n  } else {\n    for (size_t i = 0; i < NUMBER_OF_QUANTITIES; i++) {\n      krnl.Zinv(i) = data.localIntegration.specific.Zinv[i];\n    }\n  }\n  krnl.Gk = data.localIntegration.specific.G[10] * i_timeStepWidth;\n  krnl.Gl = data.localIntegration.specific.G[11] * i_timeStepWidth;\n  krnl.Gm = data.localIntegration.specific.G[12] * i_timeStepWidth;\n\n  krnl.Q = const_cast<real*>(data.dofs);\n  krnl.I = o_timeIntegrated;\n  krnl.timestep = i_timeStepWidth;\n  krnl.spaceTimePredictor = stp;\n  krnl.spaceTimePredictorRhs = stpRhs;\n  krnl.execute();\n}\n                                          \n\nvoid seissol::kernels::Time::computeAder( double i_timeStepWidth,\n                                          LocalData& data,\n                                          LocalTmp& tmp,\n                                          real o_timeIntegrated[tensor::I::size()],\n                                          real* o_timeDerivatives,\n                                          double startTime,\n                                          bool updateDisplacement)\n{\n  /*\n   * assert alignments.\n   */\n  assert( ((uintptr_t)data.dofs)              % ALIGNMENT == 0 );\n  assert( ((uintptr_t)o_timeIntegrated )      % ALIGNMENT == 0 );\n  assert( ((uintptr_t)o_timeDerivatives)      % ALIGNMENT == 0 || o_timeDerivatives == NULL );\n\n  alignas(PAGESIZE_STACK) real temporaryBuffer[tensor::spaceTimePredictor::size()];\n  real* stpBuffer = (o_timeDerivatives != nullptr) ? o_timeDerivatives : temporaryBuffer;\n  executeSTP( i_timeStepWidth, data, o_timeIntegrated, stpBuffer );\n}\n\nvoid seissol::kernels::Time::flopsAder( unsigned int        &o_nonZeroFlops,\n                                        unsigned int        &o_hardwareFlops ) {\n  // reset flops\n  o_nonZeroFlops = 0; o_hardwareFlops =0;\n\n  o_nonZeroFlops = kernel::spaceTimePredictor::NonZeroFlops;\n  o_hardwareFlops = kernel::spaceTimePredictor::HardwareFlops;\n  //we multiply the star matrices with dt before we execute the kernel\n  o_nonZeroFlops += 3*init::star::size(0);\n  o_hardwareFlops += 3*init::star::size(0);\n}\n\nunsigned seissol::kernels::Time::bytesAder()\n{\n  unsigned reals = 0;\n  \n  // DOFs load, tDOFs load, tDOFs write\n  reals += tensor::Q::size() + 2 * tensor::I::size();\n  // star matrices, source matrix\n  reals += yateto::computeFamilySize<tensor::star>();\n  // Zinv\n  reals += yateto::computeFamilySize<tensor::Zinv>();\n  // G\n  reals += 3;\n           \n  /// \\todo incorporate derivatives\n\n  return reals * sizeof(real);\n}\n\nvoid seissol::kernels::Time::computeIntegral( double                            i_expansionPoint,\n                                              double                            i_integrationStart,\n                                              double                            i_integrationEnd,\n                                              const real*                       i_timeDerivatives,\n                                              real                              o_timeIntegrated[tensor::I::size()])\n{\n  /*\n   * assert alignments.\n   */\n  assert( ((uintptr_t)i_timeDerivatives)  % ALIGNMENT == 0 );\n  assert( ((uintptr_t)o_timeIntegrated)   % ALIGNMENT == 0 );\n\n  // assert that this is a forwared integration in time\n  assert( i_integrationStart + (real) 1.E-10 > i_expansionPoint   );\n  assert( i_integrationEnd                   > i_integrationStart );\n\n  /*\n   * compute time integral.\n   */\n  // compute lengths of integration intervals\n  real l_deltaTLower = i_integrationStart - i_expansionPoint;\n  real l_deltaTUpper = i_integrationEnd   - i_expansionPoint;\n\n  // initialization of scalars in the taylor series expansion (0th term)\n  real l_firstTerm  = (real) 1;\n  real l_secondTerm = (real) 1;\n  real l_factorial  = (real) 1;\n  \n  kernel::derivativeTaylorExpansion intKrnl;\n  intKrnl.I = o_timeIntegrated;\n  for (unsigned i = 0; i < yateto::numFamilyMembers<tensor::dQ>(); ++i) {\n    intKrnl.dQ(i) = i_timeDerivatives + m_derivativesOffsets[i];\n  }\n \n  // iterate over time derivatives\n  for(int der = 0; der < CONVERGENCE_ORDER; ++der ) {\n    l_firstTerm  *= l_deltaTUpper;\n    l_secondTerm *= l_deltaTLower;\n    l_factorial  *= (real)(der+1);\n\n    intKrnl.power  = l_firstTerm - l_secondTerm;\n    intKrnl.power /= l_factorial;\n\n    intKrnl.execute(der);\n  }\n}\n\nvoid seissol::kernels::Time::computeTaylorExpansion( real         time,\n                                                     real         expansionPoint,\n                                                     real const*  timeDerivatives,\n                                                     real         timeEvaluated[tensor::Q::size()] ) {\n  /*\n   * assert alignments.\n   */\n  assert( ((uintptr_t)timeDerivatives)  % ALIGNMENT == 0 );\n  assert( ((uintptr_t)timeEvaluated)    % ALIGNMENT == 0 );\n\n  // assert that this is a forward evaluation in time\n  assert( time >= expansionPoint );\n\n  real deltaT = time - expansionPoint;\n\n  static_assert(tensor::I::size() == tensor::Q::size(), \"Sizes of tensors I and Q must match\");\n\n  kernel::derivativeTaylorExpansion intKrnl;\n  intKrnl.I = timeEvaluated;\n  for (unsigned i = 0; i < yateto::numFamilyMembers<tensor::dQ>(); ++i) {\n    intKrnl.dQ(i) = timeDerivatives + m_derivativesOffsets[i];\n  }\n  intKrnl.power = 1.0;\n \n  // iterate over time derivatives\n  for(int derivative = 0; derivative < CONVERGENCE_ORDER; ++derivative) {\n    intKrnl.execute(derivative);\n    intKrnl.power *= deltaT / real(derivative+1);\n  }\n}\n\nvoid seissol::kernels::Time::flopsTaylorExpansion(long long& nonZeroFlops, long long& hardwareFlops) {\n  // reset flops\n  nonZeroFlops = 0; hardwareFlops = 0;\n\n  // interate over derivatives\n  for (unsigned der = 0; der < CONVERGENCE_ORDER; ++der) {\n    nonZeroFlops  += kernel::derivativeTaylorExpansion::nonZeroFlops(der);\n    hardwareFlops += kernel::derivativeTaylorExpansion::hardwareFlops(der);\n  }\n}\n", "meta": {"hexsha": "00d7418b6536035783f72c91e88fa29099eac00a", "size": 9368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Equations/poroelastic/Kernels/Time.cpp", "max_stars_repo_name": "LukasvdWiel/SeisSol", "max_stars_repo_head_hexsha": "875af02663d6d5e5355af37891d746299b69e145", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Equations/poroelastic/Kernels/Time.cpp", "max_issues_repo_name": "LukasvdWiel/SeisSol", "max_issues_repo_head_hexsha": "875af02663d6d5e5355af37891d746299b69e145", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Equations/poroelastic/Kernels/Time.cpp", "max_forks_repo_name": "LukasvdWiel/SeisSol", "max_forks_repo_head_hexsha": "875af02663d6d5e5355af37891d746299b69e145", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.472, "max_line_length": 124, "alphanum_fraction": 0.6246797609, "num_tokens": 2535, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324416, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24673349367764882}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if defined(_MSC_VER)\n#\tpragma warning(disable : 4267) // boost's builtin_converters.hpp casts size_t to int rather than unsigned\n#endif\n\n#if defined(USING_NUMARRAY)\n#\tdefine PY_ARRAY_UNIQUE_SYMBOL PyArrayHandle\n#endif\n\n#include <boost/python.hpp>\n\n#include \"basic_lot.hpp\"\n#include \"probability_distribution.hpp\"\n#include \"mvnormal_distribution.hpp\"\n#include \"relative_rate_distribution.hpp\"\n#include \"lognormal.hpp\"\n#include \"stop_watch.hpp\"\n#include \"slice_sampler.hpp\"\n#include \"square_matrix.hpp\"\n#include \"rectangular_matrix.hpp\"\n#include \"xprobdist.hpp\"\n\nusing namespace boost::python;\nusing namespace phycas;\n\ndouble getEffectiveLnZero()\n\t{\n\treturn -DBL_MAX;\n\t}\n\ndouble lnGamma(double x)\n\t{\n\treturn CDF().LnGamma(x);\n\t}\n\n// The following wrapper struct is needed because we will potentially be deriving Python classes from AdHocDensity\n// This struct is thus only necessary if we plan to do something like this in Python:\n//\t\tMyFunctor(AdhocDensity):\n//\t\t\t...\n// See http://wiki.python.org/moin/boost.python/InternalDataStructures\n//\nstruct AdHocDensityWrapper : AdHocDensity\n\t{\n\tAdHocDensityWrapper(PyObject * p) : self(p) {}\n\tvirtual ~AdHocDensityWrapper()\n\t\t{\n\t\t//std::cerr << \"(ProbDist)AdHocDensityWrapper dying...\" << std::endl;\n\t\t}\n\tdouble operator()(double x) { return boost::python::call_method<double>(self, \"__call__\", x); }\n    PyObject * self;\n\t};\n\nvoid translateXProbDist(const XProbDist &e)\n\t{\n    // Use the Python 'C' API to set up an exception object\n    PyErr_SetString(PyExc_Exception, e.what());\n    }\n\nBOOST_PYTHON_MODULE(_ProbDistExt)\n{\n\tdef(\"getEffectiveLnZero\", getEffectiveLnZero);\n\tdef(\"lnGamma\", lnGamma);\n\n#if defined(USING_NUMARRAY)\n\t// these lines required by num_util\n\timport_array();\n\tnumeric::array::set_module_and_type(\"numarray\", \"NDArray\");\n#endif\n\n\tclass_<AdHocDensity, boost::noncopyable, boost::shared_ptr<AdHocDensityWrapper> >(\"AdHocDensityBase\")\n\t\t;\n\n\tclass_<ProbabilityDistribution, bases<AdHocDensity>, boost::shared_ptr<ProbabilityDistribution>, boost::noncopyable>(\"ProbabilityDistribution\", no_init)\n        .def(\"lnGamma\", &ProbabilityDistribution::LnGamma)\n\t\t;\n\n\tclass_<MultivariateProbabilityDistribution, boost::shared_ptr<MultivariateProbabilityDistribution>, boost::noncopyable>(\"MultivariateProbabilityDistribution\", no_init)\n\t\t;\n\n\tclass_<SliceSampler, boost::shared_ptr<SliceSampler> >(\"SliceSamplerBase\")\n\t\t.def(init<boost::shared_ptr<phycas::Lot>, boost::shared_ptr<AdHocDensity> >())\n\t\t.def(\"attachFunc\", &SliceSampler::AttachFunc)\n\t\t.def(\"sample\", &SliceSampler::Sample)\n\t\t.def(\"debugSample\", &SliceSampler::DebugSample)\n\t\t.def(\"overrelaxedSample\", &SliceSampler::OverrelaxedSample)\n\t\t.def(\"debugOverrelaxedSample\", &SliceSampler::DebugOverrelaxedSample)\n\t\t.def(\"attachRandomNumberGenerator\", &SliceSampler::AttachRandomNumberGenerator)\n\t\t.def(\"adaptSimple\", &SliceSampler::AdaptSimple)\n\t\t.def(\"adaptNeal\", &SliceSampler::AdaptNeal)\n\t\t.def(\"getSliceUnitWidth\", &SliceSampler::GetSliceUnitWidth)\n\t\t.def(\"setSliceUnitWidth\", &SliceSampler::SetSliceUnitWidth)\n\t\t.def(\"getMinX\", &SliceSampler::GetMinX)\n\t\t.def(\"getMaxX\", &SliceSampler::GetMaxX)\n\t\t.def(\"setMaxUnits\", &SliceSampler::SetMaxUnits)\n\t\t.def(\"getOrigLeftEdgeOfSlice\", &SliceSampler::GetOrigLeftEdgeOfSlice)\n\t\t.def(\"getOrigRightEdgeOfSlice\", &SliceSampler::GetOrigRightEdgeOfSlice)\n\t\t.def(\"getLeftEdgeOfSlice\", &SliceSampler::GetLeftEdgeOfSlice)\n\t\t.def(\"getRightEdgeOfSlice\", &SliceSampler::GetRightEdgeOfSlice)\n\t\t.def(\"getSliceYValue\", &SliceSampler::GetSliceYValue)\n\t\t.def(\"getNumFuncEvals\", &SliceSampler::GetNumFuncEvals)\n\t\t.def(\"getNumFailedSamples\", &SliceSampler::GetNumFailedSamples)\n\t\t.def(\"getNumUnitsRequired\", &SliceSampler::GetNumUnitsRequired)\n\t\t.def(\"getNumSamples\", &SliceSampler::GetNumSamples)\n\t\t.def(\"resetDiagnostics\", &SliceSampler::ResetDiagnostics)\n\t\t.def(\"adaptYConditional\", &SliceSampler::AdaptYConditional)\n\t\t.def(\"calcW\", &SliceSampler::CalcW)\n\t\t.def(\"getMode\", &SliceSampler::GetMode)\n\t\t.def(\"getLnDensityAtMode\", &SliceSampler::GetLnDensityAtMode)\n\t\t.def(\"getLastSampledXValue\", &SliceSampler::GetLastSampledXValue)\n\t\t.def(\"getLastSampledYValue\", &SliceSampler::GetLastSampledYValue)\n\t\t.def(\"setXValue\", &SliceSampler::SetXValue)\n\t\t.def(\"useDoublingMethod\", &SliceSampler::UseDoublingMethod)\n\t\t;\n\n\tclass_<phycas::StopWatch, boost::shared_ptr<phycas::StopWatch>, boost::noncopyable>(\"StopWatchBase\")\n\t\t.def(\"start\", &phycas::StopWatch::start)\n\t\t.def(\"stop\", &phycas::StopWatch::stop)\n\t\t.def(\"reset\", &phycas::StopWatch::reset)\n\t\t.def(\"normalize\", &phycas::StopWatch::normalize)\n\t\t.def(\"elapsedSeconds\", &phycas::StopWatch::elapsedSeconds)\n\t\t.def(\"split\", &phycas::StopWatch::split)\n\t\t.def(\"stopTicks\", &phycas::StopWatch::stopTicks)\n\t\t//.def(\"doofus\", &phycas::StopWatch::doofus)\n\t\t;\n\n\tclass_<phycas::SubsetProportions, boost::shared_ptr<phycas::SubsetProportions>, boost::noncopyable>(\"SubsetProportionsBase\")\n\t\t.def(\"getSubsetProportions\", &phycas::SubsetProportions::getSubsetProportions, return_value_policy<copy_const_reference>())\n\t\t.def(\"setSubsetProportions\", &phycas::SubsetProportions::setSubsetProportions)\n\t\t.def(\"setSubsetProportionsFromNumSites\", &phycas::SubsetProportions::setSubsetProportionsFromNumSites)\n        .def(\"getLogProdProportions\", &phycas::SubsetProportions::getLogProdProportions)\n\t\t;\n\n\tclass_<phycas::SquareMatrix, boost::shared_ptr<phycas::SquareMatrix>, boost::noncopyable>(\"SquareMatrixBase\", init<unsigned, double>())\n\t\t.def(init<const phycas::SquareMatrix &>())\n\t\t.def(\"duplicate\", &phycas::SquareMatrix::Duplicate, return_value_policy<manage_new_object>())\n\t\t.def(\"pow\", &phycas::SquareMatrix::Power, return_value_policy<manage_new_object>())\n\t\t.def(\"inverse\", &phycas::SquareMatrix::Inverse, return_value_policy<manage_new_object>())\n\t\t.def(\"LUDecomposition\", &phycas::SquareMatrix::LUDecomposition, return_value_policy<manage_new_object>())\n\t\t.def(\"CholeskyDecomposition\", &phycas::SquareMatrix::CholeskyDecomposition, return_value_policy<manage_new_object>())\n\t\t.def(\"rightMultiplyMatrix\", &phycas::SquareMatrix::RightMultiplyMatrix, return_value_policy<manage_new_object>())\n\t\t.def(\"leftMultiplyMatrix\", &phycas::SquareMatrix::LeftMultiplyMatrix, return_value_policy<manage_new_object>())\n\t\t.def(\"rightMultiplyVector\", &phycas::SquareMatrix::RightMultiplyVector)\n\t\t.def(\"leftMultiplyVector\", &phycas::SquareMatrix::LeftMultiplyVector)\n\t\t.def(\"identity\", &phycas::SquareMatrix::Identity)\n\t\t.def(\"trace\", &phycas::SquareMatrix::Trace)\n\t\t.def(\"logProdMainDiag\", &phycas::SquareMatrix::LogProdMainDiag)\n\t\t.def(\"logDeterminant\", &phycas::SquareMatrix::LogDeterminant)\n\t\t.def(\"getDimension\", &phycas::SquareMatrix::GetDimension)\n\t\t.def(\"__repr__\", &phycas::SquareMatrix::GetStringRepresentation)\n\t\t.def(\"addToElement\", &phycas::SquareMatrix::AddToElement)\n\t\t.def(\"setElement\", &phycas::SquareMatrix::SetElement)\n\t\t.def(\"getElement\", &phycas::SquareMatrix::GetElement)\n\t\t.def(\"setMatrix\", &phycas::SquareMatrix::SetMatrix)\n\t\t.def(\"getMatrix\", &phycas::SquareMatrix::GetMatrix)\n\t\t;\n\n\tclass_<phycas::RectangularMatrix, boost::shared_ptr<phycas::RectangularMatrix>, boost::noncopyable>(\"RectangularMatrixBase\", init<unsigned, unsigned, double>())\n\t\t.def(init<const phycas::RectangularMatrix &>())\n        .def(\"getDimensions\", &phycas::RectangularMatrix::GetDimensions)\n        .def(\"getNRows\", &phycas::RectangularMatrix::GetNRows)\n        .def(\"getNCols\", &phycas::RectangularMatrix::GetNCols)\n\t\t.def(\"__repr__\", &phycas::RectangularMatrix::GetStringRepresentation)\n        .def(\"addToElement\", &phycas::RectangularMatrix::AddToElement)\n        .def(\"setElement\", &phycas::RectangularMatrix::SetElement)\n        .def(\"getElement\", &phycas::RectangularMatrix::GetElement)\n        .def(\"setMatrix\", &phycas::RectangularMatrix::SetMatrix)\n        .def(\"getMatrix\", &phycas::RectangularMatrix::GetMatrix)\n        .def(\"setRow\", &phycas::RectangularMatrix::SetRow)\n        .def(\"getRow\", &phycas::RectangularMatrix::GetRow)\n        .def(\"getMean\", &phycas::RectangularMatrix::GetMean)\n        .def(\"getVarCovMatrix\", &phycas::RectangularMatrix::GetVarCovMatrix, return_value_policy<manage_new_object>())\n\t\t;\n\n//We tell boost::python the smart pointer type we're using, like this:\n//class_<DrawableInterface, DrawablePtr, boost::noncopyable>\n//(\"DrawableInterface\", no_init)\n//    ;\n//where DrawablePtr is a typedef for the smart pointer type.\n\n\tclass_<phycas::Lot, boost::shared_ptr<phycas::Lot>, boost::noncopyable>(\"LotBase\", init<unsigned>())\n\t\t.def(\"getSeed\", &phycas::Lot::GetSeed)\n\t\t.def(\"setSeed\", &phycas::Lot::SetSeed)\n\t\t.def(\"getInitSeed\", &phycas::Lot::GetInitSeed)\n\t\t.def(\"uniform\", &phycas::Lot::Uniform)\n\t\t.def(\"normal\", &phycas::Lot::Normal)\n\t\t.def(\"getrandbits\", &phycas::Lot::GetRandBits)\n\t\t.def(\"sampleUInt\", &phycas::Lot::SampleUInt)\n\t\t;\n\n\tclass_<MVNormalDistribution, bases<MultivariateProbabilityDistribution> >(\"MVNormalDistBase\")\n\t\t.def(init<const std::vector<double> &, const std::vector<double> &>())\n\t\t.def(init<const MVNormalDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &MVNormalDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &MVNormalDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"fit\", &MVNormalDistribution::Fit)\n\t\t.def(\"isDiscrete\", &MVNormalDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &MVNormalDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &MVNormalDistribution::GetDescriptionForPython)\n\t\t.def(\"__repr__\", &MVNormalDistribution::GetDescriptionForPython)\n\t\t.def(\"setLot\", &MVNormalDistribution::SetLot)\n\t\t.def(\"setSeed\", &MVNormalDistribution::SetSeed)\n\t\t.def(\"resetLot\", &MVNormalDistribution::ResetLot)\n\t\t.def(\"getMean\", &MVNormalDistribution::GetMean)\n\t\t.def(\"getVar\", &MVNormalDistribution::GetVar)\n\t\t.def(\"getStdDev\", &MVNormalDistribution::GetStdDev)\n\t\t.def(\"approxCDF\", &MVNormalDistribution::ApproxCDF)\n\t\t.def(\"sample\", &MVNormalDistribution::Sample)\n\t\t.def(\"getLnPDF\", &MVNormalDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &MVNormalDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &MVNormalDistribution::SetMeanAndVariance)\n\t\t.def(\"getVarCovarMatrix\", &MVNormalDistribution::GetVarCovarMatrix)\n\t\t.def(\"getNParams\", &MVNormalDistribution::GetNParams)\n\t\t.def(\"debugMVNorm\", &MVNormalDistribution::DebugMVNorm)\n\t\t;\n\n\tclass_<DirichletDistribution, bases<MultivariateProbabilityDistribution> >(\"DirichletDistBase\")\n\t\t.def(init<const std::vector<double> &>())\n\t\t.def(init<const DirichletDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &DirichletDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &DirichletDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &DirichletDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &DirichletDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &DirichletDistribution::GetDescriptionForPython)\n\t\t.def(\"__repr__\", &DirichletDistribution::GetDescriptionForPython)\n\t\t.def(\"setLot\", &DirichletDistribution::SetLot)\n\t\t.def(\"setSeed\", &DirichletDistribution::SetSeed)\n\t\t.def(\"resetLot\", &DirichletDistribution::ResetLot)\n\t\t.def(\"getMean\", &DirichletDistribution::GetMean)\n\t\t.def(\"getVar\", &DirichletDistribution::GetVar)\n\t\t.def(\"getStdDev\", &DirichletDistribution::GetStdDev)\n\t\t.def(\"approxCDF\", &DirichletDistribution::ApproxCDF)\n\t\t.def(\"sample\", &DirichletDistribution::Sample)\n\t\t.def(\"getLnPDF\", &DirichletDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &DirichletDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &DirichletDistribution::SetMeanAndVariance)\n\t\t.def(\"getVarCovarMatrix\", &DirichletDistribution::GetVarCovarMatrix)\n\t\t.def(\"getNParams\", &DirichletDistribution::GetNParams)\n\t\t;\n\n\tclass_<RelativeRateDistribution, bases<MultivariateProbabilityDistribution> >(\"RelRateDistBase\")\n\t\t.def(init<const std::vector<double> &, const std::vector<double> &>())\n\t\t.def(init<const RelativeRateDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &RelativeRateDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &RelativeRateDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &RelativeRateDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &RelativeRateDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &RelativeRateDistribution::GetDescriptionForPython)\n\t\t.def(\"__repr__\", &RelativeRateDistribution::GetDescriptionForPython)\n\t\t.def(\"setLot\", &RelativeRateDistribution::SetLot)\n\t\t.def(\"setSeed\", &RelativeRateDistribution::SetSeed)\n\t\t.def(\"resetLot\", &RelativeRateDistribution::ResetLot)\n\t\t.def(\"getMean\", &RelativeRateDistribution::GetMean)\n\t\t.def(\"getVar\", &RelativeRateDistribution::GetVar)\n\t\t.def(\"getStdDev\", &RelativeRateDistribution::GetStdDev)\n\t\t.def(\"approxCDF\", &RelativeRateDistribution::ApproxCDF)\n\t\t.def(\"sample\", &RelativeRateDistribution::Sample)\n\t\t.def(\"getLnPDF\", &RelativeRateDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &RelativeRateDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &RelativeRateDistribution::SetMeanAndVariance)\n\t\t.def(\"getVarCovarMatrix\", &RelativeRateDistribution::GetVarCovarMatrix)\n\t\t.def(\"getNParams\", &RelativeRateDistribution::GetNParams)\n\t\t.def(\"setSubsetProportions\", &RelativeRateDistribution::setSubsetProportions)\n\t\t//.def(\"setCoefficients\", &RelativeRateDistribution::SetCoefficients)\n\t\t;\n\n\tclass_<BetaDistribution, bases<ProbabilityDistribution, AdHocDensity> >(\"BetaDistBase\")\n\t\t.def(init<double, double>())\n\t\t.def(init<const BetaDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &BetaDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &BetaDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &BetaDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &BetaDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &BetaDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &BetaDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &BetaDistribution::SetLot)\n\t\t.def(\"setSeed\", &BetaDistribution::SetSeed)\n\t\t.def(\"resetLot\", &BetaDistribution::ResetLot)\n\t\t.def(\"getMean\", &BetaDistribution::GetMean)\n\t\t.def(\"getVar\", &BetaDistribution::GetVar)\n\t\t.def(\"getStdDev\", &BetaDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &BetaDistribution::GetCDF)\n\t\t.def(\"getQuantile\", &BetaDistribution::GetQuantile)\n\t\t.def(\"sample\", &BetaDistribution::Sample)\n\t\t.def(\"getLnPDF\", &BetaDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &BetaDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &BetaDistribution::SetMeanAndVariance)\n\t\t;\n\n\tclass_<BetaPrimeDistribution, bases<ProbabilityDistribution, AdHocDensity> >(\"BetaPrimeDistBase\")\n\t\t.def(init<double, double>())\n\t\t.def(init<const BetaPrimeDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &BetaPrimeDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &BetaPrimeDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &BetaPrimeDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &BetaPrimeDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &BetaPrimeDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &BetaPrimeDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &BetaPrimeDistribution::SetLot)\n\t\t.def(\"setSeed\", &BetaPrimeDistribution::SetSeed)\n\t\t.def(\"resetLot\", &BetaPrimeDistribution::ResetLot)\n\t\t.def(\"getMean\", &BetaPrimeDistribution::GetMean)\n\t\t.def(\"getVar\", &BetaPrimeDistribution::GetVar)\n\t\t.def(\"getStdDev\", &BetaPrimeDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &BetaPrimeDistribution::GetCDF)\n\t\t.def(\"getQuantile\", &BetaPrimeDistribution::GetQuantile)\n\t\t.def(\"sample\", &BetaPrimeDistribution::Sample)\n\t\t.def(\"getLnPDF\", &BetaPrimeDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &BetaPrimeDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &BetaPrimeDistribution::SetMeanAndVariance)\n\t\t;\n\tclass_<BernoulliDistribution, bases<ProbabilityDistribution> >(\"BernoulliDistBase\")\n\t\t.def(init<double>())\n\t\t.def(init<const BernoulliDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &BernoulliDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &BernoulliDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &BernoulliDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &BernoulliDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &BernoulliDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &BernoulliDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &BernoulliDistribution::SetLot)\n\t\t.def(\"setSeed\", &BernoulliDistribution::SetSeed)\n\t\t.def(\"resetLot\", &BernoulliDistribution::ResetLot)\n\t\t.def(\"getMean\", &BernoulliDistribution::GetMean)\n\t\t.def(\"getVar\", &BernoulliDistribution::GetVar)\n\t\t.def(\"getStdDev\", &BernoulliDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &BernoulliDistribution::GetCDF)\n\t\t.def(\"sample\", &BernoulliDistribution::Sample)\n\t\t.def(\"getLnPDF\", &BernoulliDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &BernoulliDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &BernoulliDistribution::SetMeanAndVariance)\n\t\t;\n\tclass_<BinomialDistribution, bases<ProbabilityDistribution> >(\"BinomialDistBase\")\n\t\t.def(init<double, double>())\n\t\t.def(init<const BinomialDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &BinomialDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &BinomialDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &BinomialDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &BinomialDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &BinomialDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &BinomialDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &BinomialDistribution::SetLot)\n\t\t.def(\"setSeed\", &BinomialDistribution::SetSeed)\n\t\t.def(\"resetLot\", &BinomialDistribution::ResetLot)\n\t\t.def(\"getMean\", &BinomialDistribution::GetMean)\n\t\t.def(\"getVar\", &BinomialDistribution::GetVar)\n\t\t.def(\"getStdDev\", &BinomialDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &BinomialDistribution::GetCDF)\n\t\t.def(\"sample\", &BinomialDistribution::Sample)\n\t\t.def(\"getLnPDF\", &BinomialDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &BinomialDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &BernoulliDistribution::SetMeanAndVariance)\n\t\t;\n\tclass_<ImproperUniformDistribution, bases<ProbabilityDistribution, AdHocDensity> >(\"ImproperUniformDistBase\")\n\t\t.def(init<const ImproperUniformDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &ImproperUniformDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &ImproperUniformDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &ImproperUniformDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &ImproperUniformDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &ImproperUniformDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &ImproperUniformDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &ImproperUniformDistribution::SetLot)\n\t\t.def(\"setSeed\", &ImproperUniformDistribution::SetSeed)\n\t\t.def(\"resetLot\", &ImproperUniformDistribution::ResetLot)\n\t\t.def(\"getMean\", &ImproperUniformDistribution::GetMean)\n\t\t.def(\"getVar\", &ImproperUniformDistribution::GetVar)\n\t\t.def(\"getStdDev\", &ImproperUniformDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &ImproperUniformDistribution::GetCDF)\n\t\t.def(\"sample\", &ImproperUniformDistribution::Sample)\n\t\t.def(\"getLnPDF\", &ImproperUniformDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &ImproperUniformDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &ImproperUniformDistribution::SetMeanAndVariance)\n\t\t;\n\tclass_<UniformDistribution, bases<ProbabilityDistribution, AdHocDensity> >(\"UniformDistBase\")\n\t\t.def(init<double, double>())\n\t\t.def(init<const UniformDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &UniformDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &UniformDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &UniformDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &UniformDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &UniformDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &UniformDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &UniformDistribution::SetLot)\n\t\t.def(\"setSeed\", &UniformDistribution::SetSeed)\n\t\t.def(\"resetLot\", &UniformDistribution::ResetLot)\n\t\t.def(\"getMean\", &UniformDistribution::GetMean)\n\t\t.def(\"getVar\", &UniformDistribution::GetVar)\n\t\t.def(\"getStdDev\", &UniformDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &UniformDistribution::GetCDF)\n\t\t.def(\"sample\", &UniformDistribution::Sample)\n\t\t.def(\"getLnPDF\", &UniformDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &UniformDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &UniformDistribution::SetMeanAndVariance)\n\t\t;\n\tclass_<GammaDistribution, bases<ProbabilityDistribution, AdHocDensity> >(\"GammaDistBase\")\n\t\t.def(init<double, double>())\n\t\t.def(init<const GammaDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &GammaDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &GammaDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &GammaDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &GammaDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &GammaDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &GammaDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &GammaDistribution::SetLot)\n\t\t.def(\"setSeed\", &GammaDistribution::SetSeed)\n\t\t.def(\"resetLot\", &GammaDistribution::ResetLot)\n\t\t.def(\"getMean\", &GammaDistribution::GetMean)\n\t\t.def(\"getVar\", &GammaDistribution::GetVar)\n\t\t.def(\"getStdDev\", &GammaDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &GammaDistribution::GetCDF)\n\t\t.def(\"sample\", &GammaDistribution::Sample)\n\t\t.def(\"getLnPDF\", &GammaDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &GammaDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &GammaDistribution::SetMeanAndVariance)\n\t\t;\n\tclass_<ExponentialDistribution, bases<GammaDistribution, ProbabilityDistribution, AdHocDensity> >(\"ExponentialDistBase\")\n\t\t.def(init<double>())\n\t\t.def(init<const ExponentialDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &ExponentialDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &ExponentialDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &ExponentialDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &ExponentialDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &ExponentialDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &ExponentialDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &ExponentialDistribution::SetLot)\n\t\t.def(\"setSeed\", &ExponentialDistribution::SetSeed)\n\t\t.def(\"resetLot\", &ExponentialDistribution::ResetLot)\n\t\t.def(\"getMean\", &ExponentialDistribution::GetMean)\n\t\t.def(\"getVar\", &ExponentialDistribution::GetVar)\n\t\t.def(\"getStdDev\", &ExponentialDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &ExponentialDistribution::GetCDF)\n\t\t.def(\"sample\", &ExponentialDistribution::Sample)\n\t\t.def(\"getLnPDF\", &ExponentialDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &ExponentialDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &ExponentialDistribution::SetMeanAndVariance)\n\t\t;\n\tclass_<InverseGammaDistribution, bases<ProbabilityDistribution, AdHocDensity> >(\"InverseGammaDistBase\")\n\t\t.def(init<double, double>())\n\t\t.def(init<const InverseGammaDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &InverseGammaDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &InverseGammaDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &InverseGammaDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &InverseGammaDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &InverseGammaDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &InverseGammaDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &InverseGammaDistribution::SetLot)\n\t\t.def(\"setSeed\", &InverseGammaDistribution::SetSeed)\n\t\t.def(\"resetLot\", &InverseGammaDistribution::ResetLot)\n\t\t.def(\"getMean\", &InverseGammaDistribution::GetMean)\n\t\t.def(\"getVar\", &InverseGammaDistribution::GetVar)\n\t\t.def(\"getStdDev\", &InverseGammaDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &InverseGammaDistribution::GetCDF)\n\t\t.def(\"sample\", &InverseGammaDistribution::Sample)\n\t\t.def(\"getLnPDF\", &InverseGammaDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &InverseGammaDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &InverseGammaDistribution::SetMeanAndVariance)\n\t\t;\n\tclass_<NormalDistribution, bases<ProbabilityDistribution, AdHocDensity> >(\"NormalDistBase\")\n\t\t.def(init<double, double>())\n\t\t.def(init<const NormalDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &NormalDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &NormalDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &NormalDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &NormalDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &NormalDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &NormalDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &NormalDistribution::SetLot)\n\t\t.def(\"setSeed\", &NormalDistribution::SetSeed)\n\t\t.def(\"resetLot\", &NormalDistribution::ResetLot)\n\t\t.def(\"getMean\", &NormalDistribution::GetMean)\n\t\t.def(\"getVar\", &NormalDistribution::GetVar)\n\t\t.def(\"getStdDev\", &NormalDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &NormalDistribution::GetCDF)\n\t\t.def(\"sample\", &NormalDistribution::Sample)\n\t\t.def(\"getLnPDF\", &NormalDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &NormalDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &NormalDistribution::SetMeanAndVariance)\n\t\t;\n\tclass_<LognormalDistribution, bases<ProbabilityDistribution, AdHocDensity> >(\"LognormalDistBase\")\n\t\t.def(init<double, double>())\n\t\t.def(init<const LognormalDistribution &>())\n\t\t.def(\"cloneAndSetLot\", &LognormalDistribution::cloneAndSetLot, return_value_policy<manage_new_object>())\n\t\t.def(\"clone\", &LognormalDistribution::Clone, return_value_policy<manage_new_object>())\n\t\t.def(\"isDiscrete\", &LognormalDistribution::IsDiscrete)\n\t\t.def(\"getDistName\", &LognormalDistribution::GetDistributionName)\n\t\t.def(\"__str__\", &LognormalDistribution::GetDistributionDescription)\n\t\t.def(\"__repr__\", &LognormalDistribution::GetDistributionDescription)\n\t\t.def(\"setLot\", &LognormalDistribution::SetLot)\n\t\t.def(\"setSeed\", &LognormalDistribution::SetSeed)\n\t\t.def(\"resetLot\", &LognormalDistribution::ResetLot)\n\t\t.def(\"getMean\", &LognormalDistribution::GetMean)\n\t\t.def(\"getVar\", &LognormalDistribution::GetVar)\n\t\t.def(\"getStdDev\", &LognormalDistribution::GetStdDev)\n\t\t.def(\"getCDF\", &LognormalDistribution::GetCDF)\n\t\t.def(\"sample\", &LognormalDistribution::Sample)\n\t\t.def(\"getLnPDF\", &LognormalDistribution::GetLnPDF)\n\t\t.def(\"getRelativeLnPDF\", &LognormalDistribution::GetRelativeLnPDF)\n\t\t.def(\"setMeanAndVariance\", &LognormalDistribution::SetMeanAndVariance)\n\t\t;\n\tregister_exception_translator<XProbDist>(&translateXProbDist);\n}\n", "meta": {"hexsha": "aa06944020f5e7ad926099a57e6af1bd9f05a3ca", "size": 28382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/probdist_pymod.cpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/probdist_pymod.cpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/probdist_pymod.cpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 54.6859344894, "max_line_length": 168, "alphanum_fraction": 0.7526953703, "num_tokens": 7655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24668935418052157}}
{"text": "// This file is part of the dune-hdd project:\n//   http://users.dune-project.org/projects/dune-hdd\n// Copyright holders: Felix Schindler\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n#ifndef DUNE_HDD_LINEARELLIPTIC_ESTIMATORS_SWIPDG_HH\n#define DUNE_HDD_LINEARELLIPTIC_ESTIMATORS_SWIPDG_HH\n\n#include <map>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#if HAVE_ALUGRID\n# include <dune/grid/alugrid.hh>\n#endif\n\n#include <dune/stuff/common/memory.hh>\n#include <dune/stuff/common/tmp-storage.hh>\n#include <dune/stuff/grid/walker.hh>\n#include <dune/stuff/grid/walker/functors.hh>\n#include <dune/stuff/playground/functions/ESV2007.hh>\n\n#include <dune/pymor/common/exceptions.hh>\n#include <dune/pymor/parameters/base.hh>\n\n#include <dune/gdt/discretefunction/default.hh>\n#include <dune/gdt/localevaluation/elliptic.hh>\n#include <dune/gdt/localevaluation/product.hh>\n#include <dune/gdt/localoperator/codim0.hh>\n#include <dune/gdt/operators/oswaldinterpolation.hh>\n#include <dune/gdt/operators/projections.hh>\n#include <dune/gdt/playground/localevaluation/ESV2007.hh>\n#include <dune/gdt/playground/operators/fluxreconstruction.hh>\n#include <dune/gdt/spaces/fv/default.hh>\n#include <dune/gdt/spaces/rt/pdelab.hh>\n\nnamespace Dune {\nnamespace HDD {\nnamespace LinearElliptic {\nnamespace Estimators {\nnamespace internal {\nnamespace SWIPDG {\n\n\nstatic const size_t over_integrate = 2;\n\n\nclass LocalNonconformityESV2007Base\n{\npublic:\n  static std::string id() { return \"eta_NC_ESV2007\"; }\n};\n\n\ntemplate< class SpaceType, class VectorType, class ProblemType, class GridType >\nclass LocalNonconformityESV2007\n  : public LocalNonconformityESV2007Base\n{\npublic:\n  static const bool available = false;\n};\n\n#if HAVE_ALUGRID\n\n/**\n *  \\brief computes the local nonconformity estimator as defined in ESV2007\n */\ntemplate< class SpaceType, class VectorType, class ProblemType >\nclass LocalNonconformityESV2007< SpaceType, VectorType, ProblemType, ALUGrid< 2, 2, simplex, conforming > >\n  : public LocalNonconformityESV2007Base\n  , public Stuff::Grid::Functor::Codim0< typename SpaceType::GridViewType >\n{\n  typedef LocalNonconformityESV2007< SpaceType, VectorType, ProblemType, ALUGrid< 2, 2, simplex, conforming > >\n    ThisType;\n  typedef Stuff::Grid::Functor::Codim0< typename SpaceType::GridViewType > FunctorBaseType;\npublic:\n  static const bool available = true;\n\n  typedef std::map< std::string, Pymor::Parameter > ParametersMapType;\n\n  typedef typename FunctorBaseType::GridViewType GridViewType;\n  typedef typename FunctorBaseType::EntityType   EntityType;\n\n  typedef typename ProblemType::RangeFieldType   RangeFieldType;\n\nprivate:\n  typedef GDT::ConstDiscreteFunction< SpaceType, VectorType > ConstDiscreteFunctionType;\n  typedef GDT::DiscreteFunction< SpaceType, VectorType > DiscreteFunctionType;\n  typedef typename ConstDiscreteFunctionType::DifferenceType DifferenceType;\n\n  typedef typename ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;\n  typedef typename ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;\n\n  typedef GDT::LocalOperator::Codim0Integral< GDT::LocalEvaluation::Elliptic< DiffusionFactorType,\n                                                                              DiffusionTensorType > > LocalOperatorType;\n  typedef Stuff::Common::TmpMatricesStorage< RangeFieldType > TmpStorageProviderType;\n\n  static const ProblemType& assert_problem(const ProblemType& problem, const Pymor::Parameter& mu_bar)\n  {\n    if (mu_bar.type() != problem.parameter_type())\n      DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,\n                 \"Given mu_bar is of type \" << mu_bar.type() << \" and should be of type \" << problem.parameter_type()\n                 << \"!\");\n    if (problem.diffusion_tensor()->parametric())\n      DUNE_THROW(NotImplemented, \"Not implemented for parametric diffusion_tensor!\");\n    return problem;\n  } // ... assert_problem(...)\n\npublic:\n  static RangeFieldType estimate(const SpaceType& space,\n                                 const VectorType& vector,\n                                 const ProblemType& problem,\n                                 const ParametersMapType parameters = ParametersMapType())\n  {\n    if (problem.diffusion_factor()->parametric() && parameters.find(\"mu_bar\") == parameters.end())\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Given parameters are missing 'mu_bar'!\");\n    const Pymor::Parameter mu_bar = problem.parametric() ? parameters.at(\"mu_bar\") : Pymor::Parameter();\n    ThisType estimator(space, vector, problem, mu_bar);\n    Stuff::Grid::Walker< GridViewType > grid_walker(space.grid_view());\n    grid_walker.add(estimator);\n    grid_walker.walk();\n    return std::sqrt(estimator.result_);\n  } // ... estimate(...)\n\n  LocalNonconformityESV2007(const SpaceType& space,\n                            const VectorType& vector,\n                            const ProblemType& problem,\n                            const Pymor::Parameter mu_bar = Pymor::Parameter())\n    : space_(space)\n    , vector_(vector)\n    , problem_(assert_problem(problem, mu_bar))\n    , problem_mu_bar_(problem_.with_mu(mu_bar))\n    , discrete_solution_(space_, vector_)\n    , oswald_interpolation_(space_)\n    , difference_(Stuff::Common::make_unique< DifferenceType >(discrete_solution_ - oswald_interpolation_))\n    , local_operator_(over_integrate,\n                      *problem_mu_bar_->diffusion_factor()->affine_part(),\n                      *problem_.diffusion_tensor()->affine_part())\n    , tmp_local_matrices_({1, local_operator_.numTmpObjectsRequired()}, 1, 1)\n    , prepared_(false)\n    , result_(0.0)\n  {}\n\n  virtual void prepare()\n  {\n    if (!prepared_) {\n      const GDT::Operators::OswaldInterpolation< GridViewType > oswald_interpolation_operator(space_.grid_view());\n      oswald_interpolation_operator.apply(discrete_solution_, oswald_interpolation_);\n      result_ = 0.0;\n      prepared_ = true;\n    }\n  } // ... prepare(...)\n\n  RangeFieldType compute_locally(const EntityType& entity)\n  {\n    const auto local_difference = difference_->local_function(entity);\n    local_operator_.apply(*local_difference,\n                          *local_difference,\n                          tmp_local_matrices_.matrices()[0][0],\n                          tmp_local_matrices_.matrices()[1]);\n    assert(tmp_local_matrices_.matrices()[0][0].rows() >= 1);\n    assert(tmp_local_matrices_.matrices()[0][0].cols() >= 1);\n    return tmp_local_matrices_.matrices()[0][0][0][0];\n  } // ... compute_locally(...)\n\n  virtual void apply_local(const EntityType &entity)\n  {\n    result_ += compute_locally(entity);\n  }\n\nprivate:\n  const SpaceType& space_;\n  const VectorType& vector_;\n  const ProblemType& problem_;\n  const std::shared_ptr< const typename ProblemType::NonparametricType > problem_mu_bar_;\n  const ConstDiscreteFunctionType discrete_solution_;\n  DiscreteFunctionType oswald_interpolation_;\n  std::unique_ptr< const DifferenceType > difference_;\n  const LocalOperatorType local_operator_;\n  TmpStorageProviderType tmp_local_matrices_;\n  bool prepared_;\npublic:\n  RangeFieldType result_;\n}; // class LocalNonconformityESV2007< ..., ALUGrid< 2, 2, simplex, conforming >, ... >\n\n#endif // HAVE_ALUGRID\n\n\nclass LocalResidualESV2007Base\n{\npublic:\n  static std::string id() { return \"eta_R_ESV2007\"; }\n};\n\n\ntemplate< class SpaceType, class VectorType, class ProblemType, class GridType >\nclass LocalResidualESV2007\n  : public LocalResidualESV2007Base\n{\npublic:\n  static const bool available = false;\n};\n\n#if HAVE_ALUGRID\n\n/**\n *  \\brief computes the local residual estimator as defined in ESV2007\n */\ntemplate< class SpaceType, class VectorType, class ProblemType >\nclass LocalResidualESV2007< SpaceType, VectorType, ProblemType, ALUGrid< 2, 2, simplex, conforming > >\n  : public LocalResidualESV2007Base\n  , public Stuff::Grid::Functor::Codim0< typename SpaceType::GridViewType >\n{\n  typedef LocalResidualESV2007< SpaceType, VectorType, ProblemType, ALUGrid< 2, 2, simplex, conforming > >\n      ThisType;\n  typedef Stuff::Grid::Functor::Codim0< typename SpaceType::GridViewType > FunctorBaseType;\npublic:\n  static const bool available = true;\n\n  typedef typename FunctorBaseType::GridViewType GridViewType;\n  typedef typename FunctorBaseType::EntityType   EntityType;\n\n  typedef typename ProblemType::RangeFieldType RangeFieldType;\n\nprivate:\n  typedef GDT::Spaces::FV::Default< GridViewType, RangeFieldType, 1, 1 > P0SpaceType;\n  typedef GDT::DiscreteFunction< P0SpaceType, VectorType > DiscreteFunctionType;\n  typedef typename DiscreteFunctionType::DifferenceType DifferenceType;\n\n  typedef typename ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;\n  typedef typename ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;\n\n  typedef typename Stuff::Functions::ESV2007::Cutoff< DiffusionFactorType, DiffusionTensorType > CutoffFunctionType;\n  typedef GDT::LocalOperator::Codim0Integral< GDT::LocalEvaluation::Product< CutoffFunctionType > > LocalOperatorType;\n  typedef DSC::TmpMatricesStorage< RangeFieldType > TmpStorageProviderType;\n\n  static const ProblemType& assert_problem(const ProblemType& problem)\n  {\n    if (problem.parametric())\n      DUNE_THROW(NotImplemented, \"Not implemented yet for parametric problems!\");\n    assert(problem.diffusion_factor()->has_affine_part());\n    assert(problem.diffusion_tensor()->has_affine_part());\n    assert(problem.force()->has_affine_part());\n    return problem;\n  } // ... assert_problem(...)\n\npublic:\n  static RangeFieldType estimate(const SpaceType& space, const VectorType& /*vector*/, const ProblemType& problem)\n  {\n    ThisType estimator(space, problem);\n    Stuff::Grid::Walker< GridViewType > grid_walker(space.grid_view());\n    grid_walker.add(estimator);\n    grid_walker.walk();\n    return std::sqrt(estimator.result_);\n  } // ... estimate(...)\n\n  LocalResidualESV2007(const SpaceType& space, const ProblemType& problem)\n    : space_(space)\n    , problem_(assert_problem(problem))\n    , p0_space_(space_.grid_view())\n    , p0_force_(p0_space_)\n    , difference_(Stuff::Common::make_unique< DifferenceType >(*problem_.force()->affine_part() - p0_force_))\n    , cutoff_function_(*problem_.diffusion_factor()->affine_part(),\n                       *problem_.diffusion_tensor()->affine_part())\n    , local_operator_(over_integrate, cutoff_function_)\n    , tmp_local_matrices_({1, local_operator_.numTmpObjectsRequired()}, 1, 1)\n    , prepared_(false)\n    , result_(0.0)\n  {}\n\n  virtual void prepare()\n  {\n    if (!prepared_) {\n      const GDT::Operators::Projection< GridViewType > projection_operator(space_.grid_view(), over_integrate);\n      projection_operator.apply(*problem_.force()->affine_part(), p0_force_);\n      result_ = 0.0;\n      prepared_ = true;\n    }\n  } // ... prepare(...)\n\n  RangeFieldType compute_locally(const EntityType& entity)\n  {\n    const auto local_difference = difference_->local_function(entity);\n    local_operator_.apply(*local_difference,\n                          *local_difference,\n                          tmp_local_matrices_.matrices()[0][0],\n                          tmp_local_matrices_.matrices()[1]);\n    assert(tmp_local_matrices_.matrices()[0][0].rows() >= 1);\n    assert(tmp_local_matrices_.matrices()[0][0].cols() >= 1);\n    return tmp_local_matrices_.matrices()[0][0][0][0];\n  } // ... compute_locally(...)\n\n  virtual void apply_local(const EntityType &entity)\n  {\n    result_ += compute_locally(entity);\n  }\n\nprivate:\n  const SpaceType& space_;\n  const ProblemType& problem_;\n  const P0SpaceType p0_space_;\n  DiscreteFunctionType p0_force_;\n  std::unique_ptr< const DifferenceType > difference_;\n  const CutoffFunctionType cutoff_function_;\n  const LocalOperatorType local_operator_;\n  TmpStorageProviderType tmp_local_matrices_;\n  bool prepared_;\npublic:\n  RangeFieldType result_;\n}; // class LocalResidualESV2007< ..., ALUGrid< 2, 2, simplex, conforming >, ... >\n\n#endif // HAVE_ALUGRID\n\n\nclass LocalResidualESV2007StarBase\n{\npublic:\n  static std::string id() { return \"eta_R_ESV2007_*\"; }\n};\n\n\ntemplate< class SpaceType, class VectorType, class ProblemType, class GridType >\nclass LocalResidualESV2007Star\n  : public LocalResidualESV2007StarBase\n{\npublic:\n  static const bool available = false;\n};\n\n#if HAVE_ALUGRID\n\n/**\n *  \\brief computes the local residual estimator as defined in ESV2007\n */\ntemplate< class SpaceType, class VectorType, class ProblemType >\nclass LocalResidualESV2007Star< SpaceType, VectorType, ProblemType, ALUGrid< 2, 2, simplex, conforming > >\n  : public LocalResidualESV2007StarBase\n  , public Stuff::Grid::Functor::Codim0< typename SpaceType::GridViewType >\n{\n  typedef LocalResidualESV2007Star< SpaceType, VectorType, ProblemType, ALUGrid< 2, 2, simplex, conforming > >\n      ThisType;\n  typedef Stuff::Grid::Functor::Codim0< typename SpaceType::GridViewType > FunctorBaseType;\npublic:\n  static const bool available = true;\n\n  typedef std::map< std::string, Pymor::Parameter > ParametersMapType;\n\n  typedef typename FunctorBaseType::GridViewType GridViewType;\n  typedef typename FunctorBaseType::EntityType   EntityType;\n\n  typedef typename ProblemType::RangeFieldType RangeFieldType;\n\n  static const unsigned int dimDomain = SpaceType::dimDomain;\n\nprivate:\n  typedef GDT::ConstDiscreteFunction< SpaceType, VectorType > ConstDiscreteFunctionType;\n  typedef GDT::Spaces::RT::PdelabBased< GridViewType, 0, RangeFieldType, dimDomain > RTN0SpaceType;\n  typedef GDT::DiscreteFunction< RTN0SpaceType, VectorType > RTN0DiscreteFunctionType;\n  typedef typename RTN0DiscreteFunctionType::DivergenceType DivergenceType;\n  typedef typename DivergenceType::DifferenceType DifferenceType;\n\n  typedef typename ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;\n  typedef typename ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;\n\n  typedef typename Stuff::Functions::ESV2007::Cutoff< DiffusionFactorType, DiffusionTensorType > CutoffFunctionType;\n  typedef GDT::LocalOperator::Codim0Integral< GDT::LocalEvaluation::Product< CutoffFunctionType > > LocalOperatorType;\n  typedef DSC::TmpMatricesStorage< RangeFieldType > TmpStorageProviderType;\n\n  static const ProblemType& assert_problem(const ProblemType& problem, const Pymor::Parameter& mu)\n  {\n    if (mu.type() != problem.parameter_type())\n      DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,\n                 \"Given mu is of type \" << mu.type() << \" and should be of type \" << problem.parameter_type()\n                 << \"!\");\n    if (problem.diffusion_tensor()->parametric())\n      DUNE_THROW(NotImplemented, \"Not implemented for parametric diffusion_tensor!\");\n    if (problem.force()->parametric())\n      DUNE_THROW(NotImplemented, \"Not implemented for parametric force!\");\n    return problem;\n  } // ... assert_problem(...)\n\npublic:\n  static RangeFieldType estimate(const SpaceType& space,\n                                 const VectorType& vector,\n                                 const ProblemType& problem,\n                                 const ParametersMapType parameters = ParametersMapType())\n  {\n    if (problem.diffusion_factor()->parametric() && parameters.find(\"mu\") == parameters.end())\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Given parameters are missing 'mu'!\");\n    const Pymor::Parameter mu = problem.parametric() ? parameters.at(\"mu\") : Pymor::Parameter();\n    ThisType estimator(space, vector, problem, mu);\n    Stuff::Grid::Walker< GridViewType > grid_walker(space.grid_view());\n    grid_walker.add(estimator);\n    grid_walker.walk();\n    return std::sqrt(estimator.result_);\n  } // ... estimate(...)\n\n  LocalResidualESV2007Star(const SpaceType& space,\n                           const VectorType& vector,\n                           const ProblemType& problem,\n                           const Pymor::Parameter mu = Pymor::Parameter())\n    : space_(space)\n    , vector_(vector)\n    , problem_(assert_problem(problem, mu))\n    , problem_mu_(problem_.with_mu(mu))\n    , discrete_solution_(space_, vector_)\n    , rtn0_space_(space_.grid_view())\n    , diffusive_flux_(rtn0_space_)\n    , divergence_(diffusive_flux_.divergence())\n    , difference_(*problem_.force()->affine_part() - divergence_)\n    , cutoff_function_(*problem_.diffusion_factor()->affine_part(),\n                       *problem_.diffusion_tensor()->affine_part())\n    , local_operator_(over_integrate, cutoff_function_)\n    , tmp_local_matrices_({1, local_operator_.numTmpObjectsRequired()}, 1, 1)\n    , prepared_(false)\n    , result_(0.0)\n  {}\n\n  virtual ~LocalResidualESV2007Star() = default;\n\n  virtual void prepare()\n  {\n    if (!prepared_) {\n      const GDT::Operators::DiffusiveFluxReconstruction< GridViewType, DiffusionFactorType, DiffusionTensorType >\n        diffusive_flux_reconstruction(space_.grid_view(),\n                                      *problem_mu_->diffusion_factor()->affine_part(),\n                                      *problem_.diffusion_tensor()->affine_part(),\n                                      over_integrate);\n      diffusive_flux_reconstruction.apply(discrete_solution_, diffusive_flux_);\n      result_ = 0.0;\n      prepared_ = true;\n    }\n  } // ... prepare(...)\n\n  RangeFieldType compute_locally(const EntityType& entity)\n  {\n    const auto local_difference = difference_.local_function(entity);\n    local_operator_.apply(*local_difference,\n                          *local_difference,\n                          tmp_local_matrices_.matrices()[0][0],\n                          tmp_local_matrices_.matrices()[1]);\n    assert(tmp_local_matrices_.matrices()[0][0].rows() >= 1);\n    assert(tmp_local_matrices_.matrices()[0][0].cols() >= 1);\n    return tmp_local_matrices_.matrices()[0][0][0][0];\n  } // ... compute_locally(...)\n\n  virtual void apply_local(const EntityType &entity)\n  {\n    result_ += compute_locally(entity);\n  }\n\nprivate:\n  const SpaceType& space_;\n  const VectorType& vector_;\n  const ProblemType& problem_;\n  const std::shared_ptr< typename ProblemType::NonparametricType > problem_mu_;\n  const ConstDiscreteFunctionType discrete_solution_;\n  const RTN0SpaceType rtn0_space_;\n  RTN0DiscreteFunctionType diffusive_flux_;\n  const DivergenceType divergence_;\n  const DifferenceType difference_;\n  const CutoffFunctionType cutoff_function_;\n  const LocalOperatorType local_operator_;\n  TmpStorageProviderType tmp_local_matrices_;\n  bool prepared_;\npublic:\n  RangeFieldType result_;\n}; // class LocalResidualESV2007Star< ..., ALUGrid< 2, 2, simplex, conforming >, ... >\n\n#endif // HAVE_ALUGRID\n\n\nclass LocalDiffusiveFluxESV2007Base\n{\npublic:\n  static std::string id() { return \"eta_DF_ESV2007\"; }\n};\n\n\ntemplate< class SpaceType, class VectorType, class ProblemType, class GridType >\nclass LocalDiffusiveFluxESV2007\n  : public LocalDiffusiveFluxESV2007Base\n{\npublic:\n  static const bool available = false;\n};\n\n#if HAVE_ALUGRID\n\n/**\n *  \\brief computes the local diffusive flux estimator as defined in ESV2007\n */\ntemplate< class SpaceType, class VectorType, class ProblemType >\nclass LocalDiffusiveFluxESV2007< SpaceType, VectorType, ProblemType, ALUGrid< 2, 2, simplex, conforming > >\n  : public LocalDiffusiveFluxESV2007Base\n  , public Stuff::Grid::Functor::Codim0< typename SpaceType::GridViewType >\n{\n  typedef LocalDiffusiveFluxESV2007< SpaceType, VectorType, ProblemType, ALUGrid< 2, 2, simplex, conforming > >\n      ThisType;\n  typedef Stuff::Grid::Functor::Codim0< typename SpaceType::GridViewType > FunctorBaseType;\npublic:\n  static const bool available = true;\n\n  typedef std::map< std::string, Pymor::Parameter > ParametersMapType;\n\n  typedef typename FunctorBaseType::GridViewType GridViewType;\n  typedef typename FunctorBaseType::EntityType   EntityType;\n\n  typedef typename ProblemType::RangeFieldType RangeFieldType;\n\n  static const unsigned int dimDomain = SpaceType::dimDomain;\n\nprivate:\n  typedef GDT::ConstDiscreteFunction< SpaceType, VectorType > ConstDiscreteFunctionType;\n  typedef GDT::Spaces::RT::PdelabBased< GridViewType, 0, RangeFieldType, dimDomain > RTN0SpaceType;\n  typedef GDT::DiscreteFunction< RTN0SpaceType, VectorType > RTN0DiscreteFunctionType;\n\n  typedef typename ProblemType::DiffusionFactorType::NonparametricType DiffusionFactorType;\n  typedef typename ProblemType::DiffusionTensorType::NonparametricType DiffusionTensorType;\n\n  typedef GDT::LocalOperator::Codim0Integral<\n      GDT::LocalEvaluation::ESV2007::DiffusiveFluxEstimate< DiffusionFactorType,\n                                                            RTN0DiscreteFunctionType,\n                                                            DiffusionTensorType > > LocalOperatorType;\n  typedef DSC::TmpMatricesStorage< RangeFieldType > TmpStorageProviderType;\n\n  static const ProblemType& assert_problem(const ProblemType& problem,\n                                           const Pymor::Parameter& mu,\n                                           const Pymor::Parameter& mu_hat)\n  {\n    if (mu.type() != problem.parameter_type())\n      DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,\n                 \"Given mu is of type \" << mu.type() << \" and should be of type \" << problem.parameter_type()\n                 << \"!\");\n    if (mu_hat.type() != problem.parameter_type())\n      DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,\n                 \"Given mu_hat is of type \" << mu_hat.type() << \" and should be of type \" << problem.parameter_type()\n                 << \"!\");\n    if (problem.diffusion_tensor()->parametric())\n      DUNE_THROW(NotImplemented, \"Not implemented for parametric diffusion_tensor!\");\n    return problem;\n  } // ... assert_problem(...)\n\npublic:\n  static RangeFieldType estimate(const SpaceType& space,\n                                 const VectorType& vector,\n                                 const ProblemType& problem,\n                                 const ParametersMapType parameters = ParametersMapType())\n  {\n    if (problem.diffusion_factor()->parametric() && parameters.find(\"mu\") == parameters.end())\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Given parameters are missing 'mu'!\");\n    if (problem.diffusion_factor()->parametric() && parameters.find(\"mu_hat\") == parameters.end())\n      DUNE_THROW(Stuff::Exceptions::wrong_input_given, \"Given parameters are missing 'mu_hat'!\");\n    const Pymor::Parameter mu =     problem.parametric() ? parameters.at(\"mu\")     : Pymor::Parameter();\n    const Pymor::Parameter mu_hat = problem.parametric() ? parameters.at(\"mu_hat\") : Pymor::Parameter();\n    ThisType estimator(space, vector, problem, mu, mu_hat);\n    Stuff::Grid::Walker< GridViewType > grid_walker(space.grid_view());\n    grid_walker.add(estimator);\n    grid_walker.walk();\n    return std::sqrt(estimator.result_);\n  } // ... estimate(...)\n\n  LocalDiffusiveFluxESV2007(const SpaceType& space,\n                            const VectorType& vector,\n                            const ProblemType& problem,\n                            const Pymor::Parameter mu = Pymor::Parameter(),\n                            const Pymor::Parameter mu_hat = Pymor::Parameter())\n    : space_(space)\n    , vector_(vector)\n    , problem_(assert_problem(problem, mu, mu_hat))\n    , problem_mu_(problem_.with_mu(mu))\n    , problem_mu_hat_(problem.with_mu(mu_hat))\n    , discrete_solution_(space_, vector_)\n    , rtn0_space_(space.grid_view())\n    , diffusive_flux_(rtn0_space_)\n    , local_operator_(over_integrate,\n                      *problem_mu_hat_->diffusion_factor()->affine_part(),\n                      *problem_.diffusion_tensor()->affine_part(),\n                      diffusive_flux_)\n    , tmp_local_matrices_({1, local_operator_.numTmpObjectsRequired()}, 1, 1)\n    , prepared_(false)\n    , result_(0.0)\n  {}\n\n  virtual void prepare()\n  {\n    if (!prepared_) {\n      const GDT::Operators::DiffusiveFluxReconstruction< GridViewType, DiffusionFactorType, DiffusionTensorType >\n        diffusive_flux_reconstruction(space_.grid_view(),\n                                      *problem_mu_->diffusion_factor()->affine_part(),\n                                      *problem_.diffusion_tensor()->affine_part(),\n                                      over_integrate);\n      diffusive_flux_reconstruction.apply(discrete_solution_, diffusive_flux_);\n      result_ = 0.0;\n      prepared_ = true;\n    }\n  } // ... prepare(...)\n\n  RangeFieldType compute_locally(const EntityType& entity)\n  {\n    const auto local_discrete_solution = discrete_solution_.local_function(entity);\n    local_operator_.apply(*local_discrete_solution,\n                          *local_discrete_solution,\n                          tmp_local_matrices_.matrices()[0][0],\n                          tmp_local_matrices_.matrices()[1]);\n    assert(tmp_local_matrices_.matrices()[0][0].rows() >= 1);\n    assert(tmp_local_matrices_.matrices()[0][0].cols() >= 1);\n    return tmp_local_matrices_.matrices()[0][0][0][0];\n  } // ... compute_locally(...)\n\n  virtual void apply_local(const EntityType &entity)\n  {\n    result_ += compute_locally(entity);\n  }\n\nprivate:\n  const SpaceType& space_;\n  const VectorType& vector_;\n  const ProblemType& problem_;\n  const std::shared_ptr< const typename ProblemType::NonparametricType > problem_mu_;\n  const std::shared_ptr< const typename ProblemType::NonparametricType > problem_mu_hat_;\n  const ConstDiscreteFunctionType discrete_solution_;\n  const RTN0SpaceType rtn0_space_;\n  RTN0DiscreteFunctionType diffusive_flux_;\n  const LocalOperatorType local_operator_;\n  TmpStorageProviderType tmp_local_matrices_;\n  bool prepared_;\npublic:\n  RangeFieldType result_;\n}; // class LocalDiffusiveFluxESV2007< ..., ALUGrid< 2, 2, simplex, conforming >, ... >\n\n#endif // HAVE_ALUGRID\n\n\nclass ESV2007Base\n{\npublic:\n  static std::string id()\n  {\n    return \"eta_ESV2007\";\n  }\n};\n\n\ntemplate< class SpaceType, class VectorType, class ProblemType, class GridType >\nclass ESV2007\n  : public ESV2007Base\n{\npublic:\n  static const bool available = false;\n};\n\n\n#if HAVE_ALUGRID\n\ntemplate< class SpaceType, class VectorType, class ProblemType >\nclass ESV2007< SpaceType, VectorType, ProblemType, ALUGrid< 2, 2, simplex, conforming > >\n  : public ESV2007Base\n{\n  typedef ALUGrid< 2, 2, simplex, conforming > GridType;\npublic:\n  static const bool available = true;\n\n  typedef typename ProblemType::RangeFieldType RangeFieldType;\n\n  static RangeFieldType estimate(const SpaceType& space, const VectorType& vector, const ProblemType& problem)\n  {\n    LocalNonconformityESV2007< SpaceType, VectorType, ProblemType, GridType > eta_nc(space, vector, problem);\n    LocalResidualESV2007< SpaceType, VectorType, ProblemType, GridType >      eta_r(space, problem);\n    LocalDiffusiveFluxESV2007< SpaceType, VectorType, ProblemType, GridType > eta_df(space, vector, problem);\n    eta_nc.prepare();\n    eta_r.prepare();\n    eta_df.prepare();\n\n    RangeFieldType eta_squared(0.0);\n\n    const auto& grid_view = space.grid_view();\n    const auto entity_it_end = grid_view.template end< 0 >();\n    for (auto entity_it = grid_view.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {\n      const auto& entity = *entity_it;\n      eta_squared += eta_nc.compute_locally(entity)\n                   + std::pow(std::sqrt(eta_r.compute_locally(entity)) + std::sqrt(eta_df.compute_locally(entity)), 2);\n    }\n    return std::sqrt(eta_squared);\n  } // ... estimate(...)\n\n  static Stuff::LA::CommonDenseVector< RangeFieldType > estimate_local(const SpaceType& space,\n                                                                       const VectorType& vector,\n                                                                       const ProblemType& problem)\n  {\n    LocalNonconformityESV2007< SpaceType, VectorType, ProblemType, GridType > eta_nc(space, vector, problem);\n    LocalResidualESV2007< SpaceType, VectorType, ProblemType, GridType >      eta_r(space, problem);\n    LocalDiffusiveFluxESV2007< SpaceType, VectorType, ProblemType, GridType > eta_df(space, vector, problem);\n    eta_nc.prepare();\n    eta_r.prepare();\n    eta_df.prepare();\n\n    const auto& grid_view = space.grid_view();\n    Stuff::LA::CommonDenseVector< RangeFieldType >\n        local_indicators(boost::numeric_cast< size_t >(grid_view.indexSet().size(0)), 0.0);\n    RangeFieldType eta_squared = 0.0;\n\n    const auto entity_it_end = grid_view.template end< 0 >();\n    for (auto entity_it = grid_view.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {\n      const auto& entity = *entity_it;\n      const auto index = grid_view.indexSet().index(entity);\n      const RangeFieldType eta_t_squared\n          = eta_nc.compute_locally(entity)\n            + std::pow(std::sqrt(eta_r.compute_locally(entity)) + std::sqrt(eta_df.compute_locally(entity)), 2);\n      local_indicators[index] = eta_t_squared;\n      eta_squared += eta_t_squared;\n    }\n    for (auto& element : local_indicators)\n      element /= eta_squared;\n    return local_indicators;\n  } // ... estimate_local(...)\n}; // class ESV2007< ..., ALUGrid< 2, 2, simplex, conforming >, ... >\n\n#endif // HAVE_ALUGRID\n\n\nclass ESV2007AlternativeSummationBase\n{\npublic:\n  static std::string id()\n  {\n    return \"eta_ESV2007_alt\";\n  }\n};\n\n\ntemplate< class SpaceType, class VectorType, class ProblemType, class GridType >\nclass ESV2007AlternativeSummation\n  : public ESV2007AlternativeSummationBase\n{\npublic:\n  static const bool available = false;\n};\n\n\n#if HAVE_ALUGRID\n\ntemplate< class SpaceType, class VectorType, class ProblemType >\nclass ESV2007AlternativeSummation< SpaceType, VectorType, ProblemType, ALUGrid< 2, 2, simplex, conforming > >\n  : public ESV2007AlternativeSummationBase\n{\n  typedef ALUGrid< 2, 2, simplex, conforming > GridType;\npublic:\n  static const bool available = true;\n\n  typedef typename ProblemType::RangeFieldType RangeFieldType;\n\n  static RangeFieldType estimate(const SpaceType& space, const VectorType& vector, const ProblemType& problem)\n  {\n    LocalNonconformityESV2007< SpaceType, VectorType, ProblemType, GridType > eta_nc(space, vector, problem);\n    LocalResidualESV2007< SpaceType, VectorType, ProblemType, GridType >      eta_r(space, problem);\n    LocalDiffusiveFluxESV2007< SpaceType, VectorType, ProblemType, GridType > eta_df(space, vector, problem);\n    eta_nc.prepare();\n    eta_r.prepare();\n    eta_df.prepare();\n\n    RangeFieldType eta_nc_squared(0.0);\n    RangeFieldType eta_r_squared(0.0);\n    RangeFieldType eta_df_squared(0.0);\n\n    const auto& grid_view = space.grid_view();\n    const auto entity_it_end = grid_view.template end< 0 >();\n    for (auto entity_it = grid_view.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {\n      const auto& entity = *entity_it;\n      eta_nc_squared += eta_nc.compute_locally(entity);\n      eta_r_squared += eta_r.compute_locally(entity);\n      eta_df_squared += eta_df.compute_locally(entity);\n    }\n    return std::sqrt(eta_nc_squared) + std::sqrt(eta_r_squared) + std::sqrt(eta_df_squared);\n  } // ... estimate(...)\n\n  static Stuff::LA::CommonDenseVector< RangeFieldType > estimate_local(const SpaceType& space,\n                                                                       const VectorType& vector,\n                                                                       const ProblemType& problem)\n  {\n    LocalNonconformityESV2007< SpaceType, VectorType, ProblemType, GridType > eta_nc(space, vector, problem);\n    LocalResidualESV2007< SpaceType, VectorType, ProblemType, GridType >      eta_r(space, problem);\n    LocalDiffusiveFluxESV2007< SpaceType, VectorType, ProblemType, GridType > eta_df(space, vector, problem);\n    eta_nc.prepare();\n    eta_r.prepare();\n    eta_df.prepare();\n\n    const auto grid_view = space.grid_view();\n    Stuff::LA::CommonDenseVector< RangeFieldType >\n        local_indicators(boost::numeric_cast< size_t >(grid_view.indexSet().size(0)), 0.0);\n    RangeFieldType eta_nc_squared(0.0);\n    RangeFieldType eta_r_squared(0.0);\n    RangeFieldType eta_df_squared(0.0);\n\n    const auto entity_it_end = grid_view.template end< 0 >();\n    for (auto entity_it = grid_view.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {\n      const auto& entity = *entity_it;\n      const auto index = grid_view.indexSet().index(entity);\n      const RangeFieldType eta_nc_t_squared = eta_nc.compute_locally(entity);\n      const RangeFieldType eta_r_t_squared = eta_r.compute_locally(entity);\n      const RangeFieldType eta_df_t_squared = eta_df.compute_locally(entity);\n      eta_nc_squared += eta_nc_t_squared;\n      eta_r_squared += eta_r_t_squared;\n      eta_df_squared += eta_df_t_squared;\n      local_indicators[index] = 3.0 *(eta_nc_t_squared + eta_r_t_squared + eta_df_t_squared);\n    }\n    const RangeFieldType eta_squared\n        = std::pow(std::sqrt(eta_nc_squared) + std::sqrt(eta_r_squared) + std::sqrt(eta_df_squared), 2);\n    for (auto& element : local_indicators)\n      element /= eta_squared;\n    return local_indicators;\n  } // ... estimate_local(...)\n}; // class ESV2007AlternativeSummation< ..., ALUGrid< 2, 2, simplex, conforming >, ... >\n\n#endif // HAVE_ALUGRID\n\n\n} // namespace SWIPDG\n} // namespace internal\n\n\ntemplate< class SpaceType, class VectorType, class ProblemType, class GridType >\nclass SWIPDG\n{\npublic:\n  typedef typename ProblemType::RangeFieldType RangeFieldType;\n\nprivate:\n  template< class IndividualEstimator, bool available = false >\n  class Caller\n  {\n  public:\n    static std::vector< std::string > append(std::vector< std::string > in)\n    {\n      return in;\n    }\n\n    static bool equals(const std::string& /*type*/)\n    {\n      return false;\n    }\n\n    static RangeFieldType estimate(const SpaceType& /*space*/,\n                                   const VectorType& /*vector*/,\n                                   const ProblemType& /*problem*/)\n    {\n      DUNE_THROW(Stuff::Exceptions::internal_error, \"This should not happen!\");\n      return RangeFieldType(0);\n    }\n\n    static Stuff::LA::CommonDenseVector< RangeFieldType > estimate_local(const SpaceType& /*space*/,\n                                                                         const VectorType& /*vector*/,\n                                                                         const ProblemType& /*problem*/)\n    {\n      DUNE_THROW(Stuff::Exceptions::internal_error, \"This should not happen!\");\n      return Stuff::LA::CommonDenseVector< RangeFieldType >();\n    }\n  }; // class Caller\n\n  template< class IndividualEstimator >\n  class Caller< IndividualEstimator, true >\n  {\n  public:\n    static std::vector< std::string > append(std::vector< std::string > in)\n    {\n      in.push_back(IndividualEstimator::id());\n      return in;\n    }\n\n    static bool equals(const std::string& type)\n    {\n      return IndividualEstimator::id() == type;\n    }\n\n    static RangeFieldType estimate(const SpaceType& space, const VectorType& vector, const ProblemType& problem)\n    {\n      return IndividualEstimator::estimate(space, vector, problem);\n    }\n\n    static Stuff::LA::CommonDenseVector< RangeFieldType > estimate_local(const SpaceType& space,\n                                                                         const VectorType& vector,\n                                                                         const ProblemType& problem)\n    {\n      return IndividualEstimator::estimate_local(space, vector, problem);\n    }\n  }; // class Caller< ..., true >\n\n  template< class IndividualEstimator >\n  static std::vector< std::string > call_append(std::vector< std::string > in)\n  {\n    return Caller< IndividualEstimator, IndividualEstimator::available >::append(in);\n  }\n\n  template< class IndividualEstimator >\n  static bool call_equals(const std::string& type)\n  {\n    return Caller< IndividualEstimator, IndividualEstimator::available >::equals(type);\n  }\n\n  template< class IndividualEstimator >\n  static RangeFieldType call_estimate(const SpaceType& space, const VectorType& vector, const ProblemType& problem)\n  {\n    return Caller< IndividualEstimator, IndividualEstimator::available >::estimate(space, vector, problem);\n  }\n\n  template< class IndividualEstimator >\n  static Stuff::LA::CommonDenseVector< RangeFieldType > call_estimate_local(const SpaceType& space,\n                                                                            const VectorType& vector,\n                                                                            const ProblemType& problem)\n  {\n    return Caller< IndividualEstimator, IndividualEstimator::available >::estimate_local(space, vector, problem);\n  }\n\n  typedef internal::SWIPDG::LocalNonconformityESV2007\n      < SpaceType, VectorType, ProblemType, GridType >              LocalNonconformityESV2007Type;\n  typedef internal::SWIPDG::LocalResidualESV2007\n      < SpaceType, VectorType, ProblemType, GridType >              LocalResidualESV2007Type;\n  typedef internal::SWIPDG::LocalResidualESV2007Star\n      < SpaceType, VectorType, ProblemType, GridType >              LocalResidualESV2007StarType;\n  typedef internal::SWIPDG::LocalDiffusiveFluxESV2007\n      < SpaceType, VectorType, ProblemType, GridType >              LocalDiffusiveFluxESV2007Type;\n  typedef internal::SWIPDG::ESV2007\n      < SpaceType, VectorType, ProblemType, GridType >              ESV2007Type;\n  typedef internal::SWIPDG::ESV2007AlternativeSummation\n      < SpaceType, VectorType, ProblemType, GridType >              ESV2007AlternativeSummationType;\n\npublic:\n  static std::vector< std::string > available()\n  {\n    std::vector< std::string > tmp;\n    tmp = call_append< LocalNonconformityESV2007Type >(tmp);\n    tmp = call_append< LocalResidualESV2007Type >(tmp);\n    tmp = call_append< LocalResidualESV2007StarType >(tmp);\n    tmp = call_append< LocalDiffusiveFluxESV2007Type >(tmp);\n    tmp = call_append< ESV2007Type >(tmp);\n    tmp = call_append< ESV2007AlternativeSummationType >(tmp);\n    return tmp;\n  } // ... available(...)\n\n  static std::vector< std::string > available_local()\n  {\n    std::vector< std::string > tmp;\n    tmp = call_append< ESV2007Type >(tmp);\n    tmp = call_append< ESV2007AlternativeSummationType >(tmp);\n    return tmp;\n  } // ... available_local(...)\n\n  static RangeFieldType estimate(const SpaceType& space,\n                                 const VectorType& vector,\n                                 const ProblemType& problem,\n                                 const std::string type)\n  {\n    if (call_equals< LocalNonconformityESV2007Type >(type))\n      return call_estimate< LocalNonconformityESV2007Type >(space, vector, problem);\n    else if (call_equals< LocalResidualESV2007Type >(type))\n      return call_estimate< LocalResidualESV2007Type >(space, vector, problem);\n    else if (call_equals< LocalResidualESV2007StarType >(type))\n      return call_estimate< LocalResidualESV2007StarType >(space, vector, problem);\n    else if (call_equals< LocalDiffusiveFluxESV2007Type >(type))\n      return call_estimate< LocalDiffusiveFluxESV2007Type >(space, vector, problem);\n    else if (call_equals< ESV2007Type >(type))\n      return call_estimate< ESV2007Type >(space, vector, problem);\n    else if (call_equals< ESV2007AlternativeSummationType >(type))\n      return call_estimate< ESV2007AlternativeSummationType >(space, vector, problem);\n    else\n      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,\n                 \"Requested type '\" << type << \"' is not one of available()!\");\n  } // ... estimate(...)\n\n  static Stuff::LA::CommonDenseVector< RangeFieldType > estimate_local(const SpaceType& space,\n                                                                       const VectorType& vector,\n                                                                       const ProblemType& problem,\n                                                                       const std::string type)\n  {\n    if (call_equals< ESV2007Type >(type))\n      return call_estimate_local< ESV2007Type >(space, vector, problem);\n    else if (call_equals< ESV2007AlternativeSummationType >(type))\n      return call_estimate_local< ESV2007AlternativeSummationType >(space, vector, problem);\n    else\n      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,\n                 \"Requested type '\" << type << \"' is not one of available_local()!\");\n  } // ... estimate_local(...)\n}; // class SWIPDG\n\n\n} // namespace Discretizations\n} // namespace Estimators\n} // namespace HDD\n} // namespace Dune\n\n#endif // DUNE_HDD_LINEARELLIPTIC_ESTIMATORS_SWIPDG_HH\n", "meta": {"hexsha": "3c99a4a041a6b5fbecab0293f1879d1f71640d7c", "size": 40379, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/hdd/linearelliptic/estimators/swipdg.hh", "max_stars_repo_name": "pymor/dune-hdd", "max_stars_repo_head_hexsha": "1ded1451a04a44c035db4cff7905661813afa935", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T04:10:59.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-08T04:10:59.000Z", "max_issues_repo_path": "dune/hdd/linearelliptic/estimators/swipdg.hh", "max_issues_repo_name": "dune-community/dune-hdd", "max_issues_repo_head_hexsha": "1ded1451a04a44c035db4cff7905661813afa935", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2018-07-31T08:29:42.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-28T08:53:34.000Z", "max_forks_repo_path": "dune/hdd/linearelliptic/estimators/swipdg.hh", "max_forks_repo_name": "pymor/dune-hdd", "max_forks_repo_head_hexsha": "1ded1451a04a44c035db4cff7905661813afa935", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-08T04:11:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-08T04:11:02.000Z", "avg_line_length": 40.5819095477, "max_line_length": 120, "alphanum_fraction": 0.6887243369, "num_tokens": 9584, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369905, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.24659795523992178}}
{"text": "#include \"GraphSampler.h\"\n#include <random>\n#include <cassert>\n#include <iostream>\n#include <cmath>\n#include <boost/math/distributions/hypergeometric.hpp>\n#include <boost/math/distributions/hypergeometric.hpp>\n#include <boost/math/policies/policy.hpp>\n\n\nusing namespace std;\n\nGraphSampler::GraphSampler(TriangleCounter* counter) : counter_(counter) {\n\tif (counter_){\n\t\tcounter_->clear();\n\t}\n}\n\nGraphSampler::~GraphSampler(){}\n\nFixedPSampler::FixedPSampler(double p, bool use_sample_and_hold, TriangleCounter* counter)\n\t: GraphSampler(counter), p_(p), use_sample_and_hold_(use_sample_and_hold){\n}\n\nFixedPSampler::~FixedPSampler(){}\n\nvoid FixedPSampler::exec_operation(const EdgeUpdate& update){\n\n\tcounter_->new_update(update);\n\n\tif (update.is_add){\n\t\tdouble u_rand = (double)rand() / ((double)RAND_MAX+1.0);\n\n\t\tif(use_sample_and_hold_){ // always count first\n\t\t\tcounter_->add_triangles(update.node_u, update.node_v, 1.0); //Weight not used\n\t\t}\n\n\t\tif (u_rand < p_){\n\t\t\t// Undirected graph\n\t\t\tif(!use_sample_and_hold_){ // count only if sampled\n\t\t\t\tcounter_->add_triangles(update.node_u, update.node_v, 1.0); //Weight not used\n\t\t\t}\n\t\t\tcounter_->add_edge_sample(update.node_u, update.node_v);\n\n\t\t}\n\t} else { // Remove are always executed (if not present no effect)\n\t\tassert(!use_sample_and_hold_); // Not supported.\n\t\tbool succeed = counter_->remove_edge_sample(update.node_u, update.node_v);\n\t\t// Here !use_sample_and_hold_\n\t\tif (succeed){ // it was present\n\t\t\tcounter_->remove_triangles(update.node_u, update.node_v, 1.0); //Weight not used\n\t\t}\n\t}\n}\n\ndouble FixedPSampler::get_triangle_est(){\n\tif (!use_sample_and_hold_){\n\t\treturn (double)counter_->triangles()*pow(1.0/p_,3);\n\t} else {\n\t\treturn (double)counter_->triangles()*pow(1.0/p_,2);\n\t}\n}\n\n\ndouble FixedPSampler::get_triangle_est_local(int node){\n\tassert(counter_->is_local());\n\tif (!use_sample_and_hold_){\n\t\treturn (double)counter_->triangles_local(node)*pow(1.0/p_,3);\n\t} else {\n\t\treturn (double)counter_->triangles_local(node)*pow(1.0/p_,2);\n\t}\n}\n\n//RESERVOIR SAMPLER\n\nReservoirSampler::ReservoirSampler(size_t reservoir_size, bool use_sample_and_hold, TriangleCounter* counter)\n\t: GraphSampler(counter), reservoir_size_(reservoir_size), use_sample_and_hold_(use_sample_and_hold){\n\t\treservoir_.reserve(reservoir_size);\n}\n\nReservoirSampler::~ReservoirSampler(){}\n\n\nvoid ReservoirSampler::add_reservoir(const pair<int,int> edge){\n\t//cout<<\"ADD RES\"<<edge.first<<\" \"<<edge.second<<endl;\n\tassert(reservoir_map_.find(edge) == reservoir_map_.end());\n\treservoir_.push_back(edge);\n\treservoir_map_.insert(make_pair(edge, reservoir_.size()-1));\n\tcounter_->add_edge_sample(edge.first, edge.second);\n\tif (!use_sample_and_hold_){\n\t\tcounter_->add_triangles(edge.first, edge.second, 1.0); //Weight not used\n\t}\n}\n\nvoid ReservoirSampler::delete_reservoir(const pair<int,int> edge){\n\tif (reservoir_map_.find(edge) == reservoir_map_.end()){\n\t\treturn;\n\t}\n\tint pos = reservoir_map_.at(edge);\n\treservoir_map_.erase(edge);\n\tif (pos < reservoir_.size() -1){ // not the last item\n\t\tpair<int, int> last_edge = reservoir_.back();\n\t\treservoir_[pos] = last_edge;\n\t\treservoir_map_[last_edge] = pos;\n\t}\n\treservoir_.pop_back();\n\tbool succ = counter_->remove_edge_sample(edge.first, edge.second);\n\tif (!use_sample_and_hold_){\n\t\tcounter_->remove_triangles(edge.first, edge.second, 1.0); //Weight not used\n\t}\n\n\tassert(succ);\n\tassert(reservoir_.size()<=reservoir_size_);\n\tassert(reservoir_.size()==reservoir_map_.size());\n}\n\nvoid ReservoirSampler::exec_operation(const EdgeUpdate& update){\n\tassert(update.is_add); //only add supported\n\tassert(update.node_u != update.node_v);\n\tint max_n = (int)max(update.node_u, update.node_v);\n\tint min_n = (int)min(update.node_u, update.node_v);\n\n\tpair<int,int> edge = make_pair(min_n, max_n);\n\n\tcounter_->new_update(update);\n\n\t//if(update.is_add){\n\tassert(reservoir_map_.find(edge) == reservoir_map_.end());\n\n\t// Prob of sampling at this step if using sample and hold\n  double p = 0;\n  unsigned long long int t = counter_->edges_present_original();\n\n  if (t >= 2 && use_sample_and_hold_){\n    p = ((double)reservoir_size_/t)*((double)(reservoir_size_-1)/(t-1));\n    p = min(p, 1.0);\n  }\n\n\n\tif (use_sample_and_hold_){ // Always count and rever remove.\n\t\tcounter_->add_triangles(update.node_u, update.node_v, (double)1.0/p);\n\t}\n\n\n\t// Enough space\n\tif (reservoir_.size() < reservoir_size_){\n\t\tadd_reservoir(edge);\n\t} else {\n\t\tdouble u_rand = (double)rand() / ((double)RAND_MAX+1.0);\n\t\tdouble thres = ((double)reservoir_size_)/counter_->edges_present_original();\n\t\tif (u_rand < thres){\n\t\t\t// Doing the exchange\n\t\t\tint rand_pos = rand()%reservoir_size_;\n\t\t\tconst pair<int,int>& to_remove = reservoir_[rand_pos];\n\t\t\tdelete_reservoir(to_remove);\n\t\t\tadd_reservoir(edge);\n\t\t}\n\t}\n\t//} else { // is remove\n\t//\tdelete_reservoir(edge);\n\t//}\n}\n\n double ReservoirSampler::get_triangle_est(){\n\tif (!use_sample_and_hold_){\n\n    double p = 0;\n    unsigned long long int t = counter_->edges_present_original();\n\n    if (t >= 3){\n      p = ((double)reservoir_size_/t)*((double)(reservoir_size_-1)/(t-1))\n          *((double)(reservoir_size_-2)/(t-2));\n      p = min(p, 1.0);\n      return (double)counter_->triangles()/p;\n\n    } else {\n      return 0; // no triangles possible;\n    }\n\n\n\t} else {\n\t\treturn counter_->triangles_weight();\n\t}\n}\n\n\n double ReservoirSampler::get_triangle_est_local(int node){\n\tassert(counter_->is_local());\n\n\tif (!use_sample_and_hold_){\n    unsigned long long int t = counter_->edges_present_original();\n    if (t >= 3){\n      double p = ((double)reservoir_size_/t)*((double)(reservoir_size_-1)/(t-1))\n          *((double)(reservoir_size_-2)/(t-2));\n      p = min(p, 1.0);\n      return (double)counter_->triangles_local(node)/p;\n\n    } else {\n      return 0; // no triangles possible;\n    }\n\t} else {\n\t\treturn counter_->triangles_weight_local(node);\n\t}\n}\n\n\n// ****************************************\n// Reservoir add & remove\n\n\n\nReservoirAddRemSampler::ReservoirAddRemSampler(size_t reservoir_size, TriangleCounter* counter)\n\t: GraphSampler(counter), reservoir_size_(reservoir_size), d_i_(0), d_o_(0){\n\t\treservoir_.reserve(reservoir_size);\n}\n\nReservoirAddRemSampler::~ReservoirAddRemSampler(){}\n\n\nvoid ReservoirAddRemSampler::add_reservoir(const pair<int,int> edge){\n\t//cout<<\"ADD RES\"<<edge.first<<\" \"<<edge.second<<endl;\n  int before_size = reservoir_.size();\n\n\tassert(reservoir_map_.find(edge) == reservoir_map_.end());\n\treservoir_.push_back(edge);\n\treservoir_map_.insert(make_pair(edge, reservoir_.size()-1));\n\tbool succ = counter_->add_edge_sample(edge.first, edge.second);\n\n  assert (succ);\n  assert(reservoir_.size()<=reservoir_size_);\n  assert(reservoir_.size()==reservoir_map_.size());\n  assert (reservoir_map_.find(edge) != reservoir_map_.end());\n  assert(reservoir_.size()== before_size +1);\n}\n\nvoid ReservoirAddRemSampler::delete_reservoir(const pair<int,int> edge){\n  //cout<<\"REM RES\"<<edge.first<<\" \"<<edge.second<<endl;\n\n  assert (reservoir_map_.find(edge) != reservoir_map_.end());\n  int before_size = reservoir_.size();\n\n\tint pos = reservoir_map_.at(edge);\n\treservoir_map_.erase(edge);\n\tif (pos < reservoir_.size() -1){ // not the last item\n\t\tpair<int, int> last_edge = reservoir_.back();\n\t\treservoir_[pos] = last_edge;\n\t\treservoir_map_[last_edge] = pos;\n\t}\n\treservoir_.pop_back();\n\tbool succ = counter_->remove_edge_sample(edge.first, edge.second);\n\tcounter_->remove_triangles(edge.first, edge.second, 1.0); //Weight not used\n\n\tassert(succ);\n\tassert(reservoir_.size()<=reservoir_size_);\n\tassert(reservoir_.size()==reservoir_map_.size());\n  assert (reservoir_map_.find(edge) == reservoir_map_.end());\n  assert(reservoir_.size()== before_size -1);\n}\n\nvoid ReservoirAddRemSampler::exec_operation(const EdgeUpdate& update){\n\tassert(update.node_u != update.node_v);\n\tint max_n = (int)max(update.node_u, update.node_v);\n\tint min_n = (int)min(update.node_u, update.node_v);\n\n\tpair<int,int> edge = make_pair(min_n, max_n);\n\n\tcounter_->new_update(update);\n\n\tif(update.is_add){\n\t\tassert(reservoir_map_.find(edge) == reservoir_map_.end());\n\n    if (d_o_ + d_i_ > 0) { // case d_o + d_i > 0\n      double u_rand = (double)rand() / ((double)RAND_MAX+1.0);\n\t\t\tdouble thres = ((double)d_i_)/(d_i_+d_o_);\n      if (u_rand < thres){ //with pro d_i / (d_i + d_o)\n        d_i_ --;\n        assert(reservoir_.size() < reservoir_size_);\n\n        add_reservoir(edge);\n        counter_->add_triangles(edge.first, edge.second, 1.0); //Weight not used\n      } else {\n        d_o_ --;\n      }\n    } else if (reservoir_.size() < reservoir_size_){ // enough space and d_i + d_o = 0\n\n\t\t\tadd_reservoir(edge);\n      counter_->add_triangles(edge.first, edge.second, 1.0); //Weight not used\n\n\t\t} else { // reservoid full and d_i + d_o = 0\n      assert (counter_->edges_present_original()>reservoir_size_);\n\n\t\t\tdouble u_rand = (double)rand() / ((double)RAND_MAX+1.0);\n\t\t\tdouble thres = ((double)reservoir_size_)/(counter_->edges_present_original());\n\t\t\tif (u_rand < thres){\n\t\t\t\t// Doing the exchange\n\t\t\t\tint rand_pos = rand()%reservoir_size_;\n\t\t\t\tpair<int,int> to_remove = reservoir_[rand_pos];\n\n        size_t before_size = reservoir_.size();\n\n\t\t\t\tdelete_reservoir(to_remove);\n\t\t\t\tadd_reservoir(edge);\n\n        assert(reservoir_.size()<=reservoir_size_);\n        assert(reservoir_.size()==reservoir_map_.size());\n        assert (reservoir_map_.find(to_remove) == reservoir_map_.end());\n        assert (reservoir_map_.find(edge) != reservoir_map_.end());\n        assert(reservoir_.size()== before_size);\n\n\n\t\t\t\tcounter_->add_triangles(edge.first, edge.second, 1.0); //Weight not used\n\t\t\t}\n\t\t}\n\t} else { // is remove\n    assert(counter_->edges_present_original()>=0);\n\n\t\tif (reservoir_map_.find(edge) != reservoir_map_.end()){//Was present\n      d_i_ ++; // deletion in sample\n\n\t\t\tdelete_reservoir(edge);\n\t\t} else { // the edge deleted was not in the reservoir\n      d_o_ ++; // deletion in sample\n\n    }\n\t}\n}\n\ndouble ReservoirAddRemSampler::prob_sampling_triangle() const{\n  if (counter_->edges_present_original() < 3 || reservoir_.size() < 3) {\n    return 0;\n  }\n  unsigned long long int s = counter_->edges_present_original();\n\n  //cout<<\"SIZES: \"<<reservoir_.size()<< \" \" <<s<<endl;\n  assert ((unsigned long long int)reservoir_.size()<=s);\n\n  double mt = reservoir_.size();\n\n  double p = 0;\n\n  if (reservoir_.size() == s) {\n    p = 1;\n  } else {\n    p = (mt/s)*((mt-1)/(s-1))*((mt-2)/(s-2));\n  }\n\n  assert (p<=1);\n\n  unsigned long long int n = min((unsigned long long int)reservoir_size_, s+d_i_+d_o_);\n\n  boost::math::hypergeometric_distribution<double> hyper(s, n, d_i_+d_o_+s);\n  double kt = 0;\n\n  for (int i = 0; i<=2 ; i++){\n    if (i >= max(0ull, (unsigned long long int)(n) +  - d_i_-d_o_) && i <= min((unsigned long long int)(n), s)){\n      kt += boost::math::pdf<double>(hyper, i);\n    }\n  }\n\n  return p*(1-kt);\n}\n\n\ndouble ReservoirAddRemSampler::get_triangle_est(){\n\n  double prob = prob_sampling_triangle();\n\treturn counter_->triangles() / prob;\n}\n\ndouble ReservoirAddRemSampler::get_triangle_est_local(int node){\n\tassert(counter_->is_local());\n\n  double prob = prob_sampling_triangle();\n\treturn counter_->triangles_local(node) / prob;\n}\n\n\n// ALI PINAR Paper\n\nPinarSampler::PinarSampler(size_t edge_res_size, size_t wedge_res_size)\n\t: GraphSampler(NULL/* no need of TriangleCounter*/), t_(0), tot_wedges_(0), fraction_closed_(0.0), edge_res_size_(edge_res_size), wedge_res_size_(wedge_res_size){\n\t\tedge_reservoir_.resize(edge_res_size);\n\t\twedge_reservoir_.resize(wedge_res_size);\n\t\twedge_closed_.resize(wedge_res_size);\n}\n\nPinarSampler::~PinarSampler(){}\n\n\ndouble PinarSampler::get_triangle_est(){\n\treturn fraction_closed_*t_*t_/\n\t\t(static_cast<double>(edge_res_size_)*(edge_res_size_-1))*tot_wedges_;\n}\n\n\nvoid PinarSampler::exec_operation(const EdgeUpdate& update){\n\tassert(update.is_add); //only add supported\n\tassert(update.node_u != update.node_v);\n\tint max_n = (int)max(update.node_u, update.node_v);\n\tint min_n = (int)min(update.node_u, update.node_v);\n\n\tt_+=1;\n\n\tpair<int,int> edge = make_pair(min_n, max_n);\n\n\tlong long int closed = 0;\n\n\t// Check if closing wedges\n\tfor (int i = 0; i<wedge_reservoir_.size(); i++){\n\t\tconst pair<int,pair<int,int>> &wedge = wedge_reservoir_[i];\n\n\t\tif ((wedge.second.first == max_n && wedge.second.second == min_n)\n\t\t\t\t||(wedge.second.first == min_n && wedge.second.second == max_n)\n\t\t){\n\t\t\t\twedge_closed_[i] = true;\n\n\t\t}\n\t\tclosed += (wedge_closed_[i] ? 1 : 0);\n\t}\n\n\n\n\t// Update edge reservoir\n\tbool updated = false;\n\tfor (int i = 0; i<edge_reservoir_.size(); i++){\n\t\tdouble u_rand = (double)rand() / ((double)RAND_MAX+1.0);\n\t\tif (u_rand <= 1.0/t_){\n\t\t\tedge_reservoir_[i] = edge;\n\t\t\tupdated = true;\n\t\t}\n\t}\n\n\tif(updated){\n\t\t// count total num of wedges\n\t\tUDynGraph sub_graph;\n\t\tfor (const auto& e: edge_reservoir_){\n\t\t\tsub_graph.add_edge(e.first, e.second);\n\t\t}\n\t\tvector<int> nodes;\n\t\tsub_graph.nodes(&nodes);\n\n\t\ttot_wedges_ = 0;\n\t\tfor (const auto& n:nodes){\n\t\t\tint deg = sub_graph.degree(n);\n\t\t\ttot_wedges_+= (deg*(deg-1))/2;\n\t\t}\n\n\t\t// get new wedges with this edge...\n\t\tvector<pair<int,pair<int,int>>> new_wedges;\n\t\tvector<int> neighbors_min;\n\t\tsub_graph.neighbors(min_n, &neighbors_min);\n\t\tfor (const auto & neighbor: neighbors_min){\n\t\t\t// wedge min_n-neighbor, min_n-max_n\n\t\t\tif (neighbor != max_n){\n\t\t\t\tnew_wedges.push_back(make_pair(min_n, make_pair(neighbor, max_n)));\n\t\t\t}\n\t\t}\n\t\tvector<int> neighbors_max;\n\t\tsub_graph.neighbors(max_n, &neighbors_max);\n\t\tfor (const auto & neighbor: neighbors_max){\n\t\t\t// wedge max_n-neighbor, max_n-min_n\n\t\t\tif (neighbor != min_n){\n\t\t\t\tnew_wedges.push_back(make_pair(max_n, make_pair(neighbor, min_n)));\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i<wedge_reservoir_.size(); i++){\n\t\t\tdouble u_rand = (double)rand() / ((double)RAND_MAX+1.0);\n\t\t\tif (u_rand <= 1.0*new_wedges.size()/tot_wedges_){\n\t\t\t\twedge_reservoir_[i] = new_wedges[rand()%new_wedges.size()];\n\t\t\t\tclosed -= (wedge_closed_[i] ? 1 : 0);\n\t\t\t\twedge_closed_[i] = false; // This make absolutely no sense but it is done in ali pinar paper So I implemented it as stated. ****\n\t\t\t\tclosed += (wedge_closed_[i] ? 1 : 0);\n\t\t\t}\n\t\t}\n\n\t\tfraction_closed_ = 1.0*closed/ wedge_reservoir_.size();\n\t}\n\n}\n", "meta": {"hexsha": "04467ced03cc5e64b09609dfe8e8b4ac01aae62b", "size": 14072, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphSampler.cpp", "max_stars_repo_name": "aepasto/triest", "max_stars_repo_head_hexsha": "c28f52569aefe41993a3d0b9260fc3c95796493d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-06-28T12:06:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-23T06:36:39.000Z", "max_issues_repo_path": "GraphSampler.cpp", "max_issues_repo_name": "aepasto/triest", "max_issues_repo_head_hexsha": "c28f52569aefe41993a3d0b9260fc3c95796493d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphSampler.cpp", "max_forks_repo_name": "aepasto/triest", "max_forks_repo_head_hexsha": "c28f52569aefe41993a3d0b9260fc3c95796493d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-06-29T21:52:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-17T18:08:54.000Z", "avg_line_length": 29.2557172557, "max_line_length": 163, "alphanum_fraction": 0.6893831723, "num_tokens": 3925, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678319, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24656605900564801}}
{"text": "//\n//  bpp.cpp\n//  PhyloAcc\n//\n//  Created by hzr on 3/8/16.\n//  Copyright © 2016 hzr. All rights reserved.\n//\n\n#include \"bpp.hpp\"\n#include <armadillo>\n#include <sys/types.h>\n#include <dirent.h>\n#include<queue>\n\n#include <cmath>\n#include <cassert>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_cdf.h>\n\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <ctype.h>\n\n\n#include \"newick.h\"\n#include \"utils.h\"\n#include \"bpp_c.hpp\"\n\n\nusing namespace std;\nusing namespace arma;\n\n// load the phylogenetic tree\nvoid BPP::InitPhyloTree(PhyloTree & tree) //, double indel_pi), double indel, double indel2\n{\n   \n//    cx_mat bvec;\n//    cx_vec aval;\n//   \n//    if(num_base <= 4)  // no indel\n//    {\n//       \n//    }else{\n//        tree.subs_rate *= (1-indel);\n//        mat B = ones<mat>(4,1) * indel;\n//        mat C = ones<mat>(1,5) * indel2;\n//        //tree.subs_rate.diag() -= indel;\n//        tree.subs_rate.insert_cols(4, B);\n//        tree.subs_rate.insert_rows(4, C);\n//        //tree.subs_rate(4,4) = -0.04;\n//        colvec c = sum(tree.subs_rate,1);\n//        tree.subs_rate.diag() -=c;\n//        \n////        tree.pi.insert_rows(4,1);\n////        tree.pi.head(4) *= 1 - indel_pi;\n////        tree.pi[4] = indel_pi;\n//        \n//    }\n//    \n//    eig_gen(aval, bvec, tree.subs_rate);\n//    eigenval = conv_to<mat>::from(aval);\n//    eigenvec = conv_to<mat>::from(bvec).t();\n//    eigeninv = inv(eigenvec);\n//    submat = tree.subs_rate;\n//    \n//    //cout <<eigenval;\n//    //cout <<\"eigenvec: \" << eigenvec;\n//    //cout <<tree.subs_rate;\n//    \n//    mat a = null(tree.subs_rate.t());\n//    \n//    \n//    pi = a/accu(a); //tree.pi;\n//    //cout <<\"pi: \" <<  pi.t();\n//    \n//    log_pi = log(pi);\n    \n    submat = tree.subs_rate;\n    children    = new int[N][2];\n    parent      = new int[N];\n    distances   = new double[N];\n  \n    \n    for(int s=0; s<N; s++)\n    {\n        distances[s] = tree.distances[s];\n        \n    }\n    \n    \n    \n    for(int i=0; i<N; i++)\n    {\n        children[i][0] = -1;\n        children[i][1] = -1;\n        parent[i] = -1;\n    }\n    \n    for(int i=0; i<N; i++)\n    {\n        int p = -1;\n        for(int j=0; j<N; j++)\n        {\n            if (tree.dag[i][j])\n            {\n                p++;\n                children[i][p] = j;\n                parent[j] = i;\n            }\n        }\n    }\n    \n    \n//    distances[children[N-1][1]] += distances[children[N-1][0]];\n//    distances[children[N-1][0]] = 0;\n//    moveroot = children[N-1][0];\n    \n    \n    //distances[83] += distances[42];  // modify distance for root!\n    //distances[42] =0 ;\n    \n    \n}\n\n\n// try to match the phylogenetic profile and tree\nvoid BPP::MatchProfAndTree(PhyloProf & _prof, PhyloTree & _tree)\n{\n    \n    // try to match the species\n    bool success_match = true;\n    int S = _tree.S;\n    int S2 = _prof.S;\n    vector<int> reorder(S);  //each species in the tree where is in prof\n    for(int s1=0; s1<S; s1++)\n    {\n        bool has_same_species = false;\n        string sname1 = _tree.species_names[s1];\n        for(int s2=0; s2<S2; s2++)\n        {\n            string sname2 = _prof.species_names[s2];\n            //            cout << sname1 << \" ? \" << sname2 << endl;\n            if (sname1 == sname2)\n            {\n                has_same_species = true;\n                reorder[s1] = s2;\n                break;\n            }\n        }\n        if (!has_same_species)\n        {\n            cout << \"No matrix species \" << _prof.species_names[s1] << \" found in tree.\" << endl;\n            success_match = false;\n            break;\n        }\n    }\n    \n    if (!success_match) // if cannot match literally\n    {\n        cout << endl << \"The species in phylogenetic profile and tree cannot be matched literally:\" << endl;\n        cout << \"The program will use the default mapping in data:\" << endl;\n        for(int s=0; s<S; s++)\n            cout << \"(\" << _prof.species_names[s] << \"\\t=  \" << _tree.species_names[s] << \")\" << endl;\n        cout << endl;\n    }\n    else                // if successully matched\n    {\n        cout << \"The species in profile and tree match perfectly. Reorder the species in profile matrix by the tree.\" << endl << endl;\n        vector<string> old_X = _prof.X;\n        for(int s=0; s<S; s++)\n        {\n            int reorder_s = reorder[s];\n            _prof.X[s] = old_X[reorder_s];\n        }\n        _prof.species_names = _tree.species_names;\n    }\n    \n}\n\nvoid BPP::InitMCMC(int _num_burn, int _num_mcmc, int _num_thin)\n{\n    // init parameters\n    num_burn = _num_burn;\n    \n    num_mcmc = _num_mcmc;\n    num_thin = _num_thin;\n    \n    \n    last_time = time(NULL);\n    \n    \n    \n    // init MCMC sampling storage\n    Max_Z = vector<vector < vector <int > >> (3,vector < vector <int >>  (C,vector <int > (N,0)));\n    cur_Z = vector<vector < vector <int > >> (3,vector < vector <int >>  (C,vector <int > (N,0)));\n    \n    log_liks_null = vector <double>(C,0);\n    log_liks_Z = vector<vector <double>>(3,vector <double>(C,0));\n    log_liks_sgl = vector <double>(C,0);\n    log_liks_resZ = vector <double>(C,0);\n    \n    log_liks_curZ = vector <double>(C,0);\n    log_liks_propZ = vector <double>(C,0);\n    MH_ratio_gain = vector <double>(C,0);\n    MH_ratio_loss = vector <double>(C,0);\n    \n    \n    \n    cur_crate = vector <double>(C,ratio0);\n    cur_nrate = vector <double>(C,ratio1);\n    \n    cur_lrate = vector <double>(C,ind_lrate);\n    cur_lrate2 = vector <double>(C,ind_lrate2);\n    cur_grate = vector <double>(C, ind_grate);\n    \n    \n    \n}\n\nvoid BPP::sample_proposal(int iter, double & lrate_prop, double & grate_prop, ofstream & output)\n{\n    //indel_prop =gsl_ran_gamma(RNG,20 ,indel/20);\n    //indel2_prop =gsl_ran_gamma(RNG,10 ,indel2/10);\n    lrate_prop =gsl_ran_beta(RNG, ind_lrate * vlr, (1 - ind_lrate) *vlr); // let vlr == vgr!!\n    grate_prop =gsl_ran_beta(RNG, ind_grate * vgr, (1 - ind_grate - ind_lrate) *vgr); //gsl_ran_gamma(RNG, vgr, ind_grate/vgr);\n    grate_prop = grate_prop * (1 - lrate_prop);\n   \n//    submat.submat(0,0,3,3) *= (1 - indel_prop)/(1 - indel);\n//    submat.col(4) = ones<mat>(5,1) * indel_prop;\n//    submat.row(4) = ones<mat>(1,5) * indel2_prop;\n//    colvec c = sum(submat,1);\n//    submat.diag() -=c;\n//    \n//    cx_mat bvec;\n//    cx_vec aval;\n//    eig_gen(aval, bvec, submat);\n//    eigenvalprop = conv_to<mat>::from(aval);\n//    eigenvecprop = conv_to<mat>::from(bvec).t();\n//    eigeninvprop = inv(eigenvecprop);\n//    \n//    mat a = null(submat.t());\n//    piprop = a/accu(a);\n//    //log_piprop = log(a/accu(a));\n//    \n//    //cout <<\"proposed subs matrix: \" << submat << endl;\n//    //cout <<\"piprop: \" <<  piprop.t();\n    \n    output << iter << \"\\t\"<< nprior_a<< \"\\t\"<< nprior_b <<\"\\t\"<< cprior_a << \"\\t\"<< cprior_b << \"\\t\"<< indel << \"\\t\"<< indel2 << \"\\t\"<<ind_grate<< \"\\t\"<< ind_lrate <<endl;\n}\n\n\n\ndouble BPP::log_lik(vector< vector<vec> > & lambda, double _indel, double _indel2, int start1, int end1, vector<unsigned int> & v, double p)\n{\n    // compute loglik\n    double result =0;\n    mat x(2,2);\n    \n    int rr = *subtree.rbegin();\n    // 1. sending the lambda msg from leaves bottom up through the network\n    for(vector<int>::iterator it = subtree.begin(); it!=subtree.end(); it++) //int s=S; s<N; s++)\n    {\n        int s = *it;\n        if(s<S) continue;\n        int* p = children[s];\n        for(int it = start1; it < end1; it++)  lambda[v[it]][s].fill(0);\n       \n        \n        for(int cc=0;cc<2;cc++)\n        {\n            int chi = p[cc];\n            assert(chi != -1);\n            if(distances[chi]>0 )\n            {\n                double tt = (1 - exp(-(_indel + _indel2) * distances[chi]))/(_indel + _indel2);\n                x.at(1,0) = _indel * tt;\n                x.at(0,0) = 1 - x.at(1,0);\n                \n                x.at(0,1) = _indel2 * tt;\n                x.at(1,1) = 1 - x.at(0,1);\n                \n                //cout << x;\n                x = log(x);\n                \n\n            }\n            else{\n                x.fill(-INFINITY); //83, root\n                x.diag().fill(0);\n            }\n            \n            #pragma omp parallel for schedule (guided)\n            for(int it = start1; it < end1; it++)  lambda[v[it]][s] +=  BPP::log_multi(x,lambda[v[it]][chi]);\n        }\n        \n    }\n    \n    // 2. processing the distribution of root species\n    \n    for(int it = start1; it < end1; it++)\n    {\n        \n//        if(lambda[v[it]][N-1][1] < -1e3)\n//        {\n//            cout <<v[it]<<\": \"<< lambda[v[it]][N-1].t();\n//            cout <<children[N-1][0]<<\": \" << lambda[v[it]][children[N-1][0]].t();\n//            cout <<children[N-1][1]<<\": \" << lambda[v[it]][children[N-1][1]].t();\n//            \n//        }\n        lambda[v[it]][rr][0] += log(1-p); //N-1\n        lambda[v[it]][rr][1] += log(p) ;\n        result += BPP::log_exp_sum(lambda[v[it]][rr]);\n    }\n    \n    return(result);\n}\n\nvoid BPP::sample_hyperparam(int iter, vector<int> & ids, ofstream & output) // recompute log_TM, double indel_prop, double indel2_prop,\n{\n// 0702 no sample rates\n    //indepent MH to sample hyperparam of rates\n    double p=1,r = 1; //hyperparam for shape\n    double q=0.1,s = 0.1; // hyperparam for scale\n\n    double vna = 100, vnb = 100, vca = 100, vcb = 100;\n    double nprior_a_prop =gsl_ran_gamma(RNG, vna, nprior_a/vna);\n    double cprior_a_prop =gsl_ran_gamma(RNG, vca, cprior_a/vca);\n\n    double nprior_b_prop =gsl_ran_gamma(RNG, vnb, nprior_b/vnb);\n    double cprior_b_prop =gsl_ran_gamma(RNG, vcb, cprior_b/vcb);\n\n    //MH proposal\n    double sum_r = 0;\n    double log_prod_r = 0;\n    //double var_r = 0;\n    //for(vector<double>::iterator it = cur_nrate.begin(); it< cur_nrate.end(); it++)\n    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702\n    {\n        int c = ids[i];\n        sum_r += cur_nrate[c];\n        //var_r += pow(*it, 2);\n        log_prod_r += log(cur_nrate[c]);\n    }\n\n\n    double M_ratio = (nprior_a_prop - 1) * (log(p) + log_prod_r) - (q + sum_r)/nprior_b_prop - (ids.size() + r)*lgamma(nprior_a_prop) - log(nprior_b_prop) * nprior_a_prop * (s + ids.size());\n    M_ratio -= (nprior_a - 1) * (log(p) + log_prod_r) - (q + sum_r)/nprior_b - (ids.size() + r)*lgamma(nprior_a) - log(nprior_b) * nprior_a * (s + ids.size());\n\n    double H_ratio = log(gsl_ran_gamma_pdf(nprior_a,vna,nprior_a_prop/vna)) - log(gsl_ran_gamma_pdf(nprior_a_prop,vna,nprior_a/vna)) + log(gsl_ran_gamma_pdf(nprior_b,vnb,nprior_b_prop/vnb)) - log(gsl_ran_gamma_pdf(nprior_b_prop,vnb,nprior_b/vnb));\n\n    cout << \"nrate_MH_ratio: \" << M_ratio <<\", \" << H_ratio << \", \" << nprior_a << \", \" << nprior_a_prop << \", \" << nprior_b << \", \" << nprior_b_prop << endl;\n\n    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)\n    {\n        nprior_a = nprior_a_prop;\n        nprior_b = nprior_b_prop;\n    }\n\n\n    sum_r = 0;\n    log_prod_r = 0;\n    //for(vector<double>::iterator it = cur_crate.begin(); it< cur_crate.end(); it++)\n    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702\n    {\n        int c = ids[i];\n        sum_r += cur_crate[c];\n        //var_r += pow(*it, 2);\n        log_prod_r += log(cur_crate[c]);\n    }\n\n    M_ratio = (cprior_a_prop - 1) * (log(p) + log_prod_r) - (q + sum_r)/cprior_b_prop - (ids.size() + r)*lgamma(cprior_a_prop) - log(cprior_b_prop) * cprior_a_prop * (s + ids.size()) - ((cprior_a - 1) * (log(p) + log_prod_r) - (q + sum_r)/cprior_b - (ids.size() + r)*lgamma(cprior_a) - log(cprior_b) * cprior_a * (s + ids.size()));\n\n    H_ratio = log(gsl_ran_gamma_pdf(cprior_a,vca,cprior_a_prop/vca)) - log(gsl_ran_gamma_pdf(cprior_a_prop,vca,cprior_a/vca)) + log(gsl_ran_gamma_pdf(cprior_b,vcb,cprior_b_prop/vcb)) - log(gsl_ran_gamma_pdf(cprior_b_prop,vcb,cprior_b/vcb));\n\n    cout << \"crate_MH_ratio: \" << M_ratio + H_ratio << \", \" << cprior_a << \", \" << cprior_a_prop <<\", \" << cprior_b << \", \" << cprior_b_prop << endl;\n\n    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)\n    {\n        cprior_a = cprior_a_prop;\n        cprior_b = cprior_b_prop;\n    }\n\n\n  // sample hyperparameters of lrate and grate, exponential prior for prior_l_a and prior_l_b, prior_g_a and prior_g_b\n    double u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);\n    double prior_l_a_prop = prior_l_a *  u;\n    \n    u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);\n    double prior_l_b_prop = prior_l_b *  u;\n    double log_p = 0, log_pc = 0;\n    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702\n    {\n        int c = ids[i];\n        log_p += log(cur_lrate[c]);\n        log_pc += log(1 - cur_lrate[c]);\n    }\n    \n    \n    M_ratio = (prior_l_a_prop - prior_l_a) * (log_p - 1) + (prior_l_b_prop - prior_l_b) * (log_pc - 1);\n    M_ratio += ids.size() * (gsl_sf_lnbeta(prior_l_a, prior_l_b) - gsl_sf_lnbeta(prior_l_a_prop, prior_l_b_prop));\n    \n    H_ratio = log(prior_l_a) - log(prior_l_a_prop) + log(prior_l_b) - log(prior_l_b_prop);\n    \n    cout << \"lrate_MH_ratio: \" << M_ratio + H_ratio << \", \" << prior_l_a << \", \" << prior_l_a_prop <<\", \" << prior_l_b << \", \" << prior_l_b_prop  << endl;\n    \n    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)\n    {\n        prior_l_a = prior_l_a_prop;\n        prior_l_b = prior_l_b_prop;\n    }\n    \n    // sample grate\n    u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);\n    double prior_g_a_prop = prior_g_a *  u;\n    \n    u = gsl_rng_uniform(RNG)*(1.3 - 0.7) + 0.7; // generate uniform from (1/prop_n, prop_n);\n    double prior_g_b_prop = prior_g_b *  u;\n    log_p = 0; log_pc = 0;\n    for(std::size_t i = 0; i < ids.size(); i++ )  // 0702\n    {\n        int c = ids[i];\n        log_p += log(cur_grate[c]);\n        log_pc += log(1 - cur_grate[c]);\n    }\n    \n    \n    M_ratio = (prior_g_a_prop - prior_g_a) * (log_p - 1) + (prior_g_b_prop - prior_g_b) * (log_pc - 1);\n    M_ratio += ids.size() * (gsl_sf_lnbeta(prior_g_a, prior_g_b) - gsl_sf_lnbeta(prior_g_a_prop, prior_g_b_prop));\n    \n    H_ratio = log(prior_g_a) - log(prior_g_a_prop) + log(prior_g_b) - log(prior_g_b_prop);\n    \n    cout << \"grate_MH_ratio: \" << M_ratio + H_ratio << \", \" << prior_g_a << \", \" << prior_g_a_prop <<\", \" << prior_g_b << \", \" << prior_g_b_prop  << endl;\n    \n    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)\n    {\n        prior_g_a = prior_g_a_prop;\n        prior_g_b = prior_g_b_prop;\n    }\n    \n     output << iter << \"\\t\"<< nprior_a<< \"\\t\"<< nprior_b <<\"\\t\"<< cprior_a << \"\\t\"<< cprior_b << \"\\t\"<< prior_l_a << \"\\t\"<< prior_l_b << \"\\t\"<< prior_g_a << \"\\t\"<< prior_g_b <<endl;\n    \n   \n}\n\n\n\n\n\n\n\n\nvoid BPP::getUppertree(int root, vector<int>& child, set<int> & visited_init)  // include root!\n{\n    for(vector<int>::iterator it = child.begin(); it!=child.end(); it++)\n    {\n        int p = *it;\n       while(p!=root)\n       {\n           visited_init.insert(p);\n           p = parent[p];\n       }\n        \n        \n    }\n    \n    visited_init.insert(root);\n    \n    \n    \n}\n\n\n\n\n\nvoid BPP::getSubtree(int root, vector<int> & visited_init)  // traverse from root to children, include root\n{\n    \n    \n    int j = root;\n    \n    //cout << nodes_names[j]<<\"\\t\";\n    \n    if(children[j][0]!=-1)\n    {\n        \n        for(int chi=0;chi<2;chi++)\n        {\n            getSubtree(children[j][chi], visited_init);\n            \n            \n        }\n        \n    }\n   \n    visited_init.push_back(j);\n    \n}\n\nvoid BPP::getSubtree(int root, set<int>& child, vector<int> & visited_init)  // traverse from root, stop at children, 74 & 64; do include 1-S!\n{\n    \n    \n    int j = root;\n    \n    //cout << nodes_names[j]<<\"\\t\";\n    if(child.find(j) != child.end())\n    {\n        \n        visited_init.push_back(j);\n        \n        return;\n    }\n    \n    if(children[j][0]!=-1)\n    {\n        \n        for(int chi=0;chi<2;chi++)\n        {\n            getSubtree(children[j][chi], child, visited_init);\n            \n            \n        }\n        \n      //  visited_init.push_back(j);\n        \n    }\n    \n     visited_init.push_back(j);\n       \n    \n}\n\nvoid BPP::Output_init(PhyloProf & prof, string output_path, vector<int> & ids){\n    \n        string outpath_elem = output_path+ \"_elem_lik.txt\";\n        ofstream out_lik(outpath_elem.c_str());\n        out_lik.precision(8);\n        out_lik << \"No.\\tID\\tloglik_Null\\tloglik_Acc\\tloglik_Full\\tlogBF1\\tlogBF2\\tloglik_Max_M0\\tloglik_Max_M1\\tloglik_Max_M2\"<<endl;\n        //for(int cc=0; cc<C;cc++)\n        for(vector<int>::iterator it = ids.begin(); it !=ids.end(); it++)\n        {\n            int cc = *it;\n            out_lik <<cc << \"\\t\" << prof.element_names[cc] << \"\\t\" << log_liks_null[cc] <<\"\\t\"  <<log_liks_resZ[cc] <<\"\\t\"  <<log_liks_sgl[cc]<< \"\\t\";\n            out_lik << log_liks_resZ[cc] -  log_liks_null[cc] << \"\\t\" << log_liks_resZ[cc] -  log_liks_sgl[cc];\n            //for(int r=0;r<3;r++) \n            out_lik <<\"\\t\" <<log_liks_Z[0][cc] << \"\\t\" <<log_liks_Z[2][cc]<<\"\\t\" <<log_liks_Z[1][cc];\n            out_lik << endl;\n        }\n        \n        out_lik.close();\n        \n    ofstream out_z;\n    for(int r =0;r<3;r++)\n    {\n            if(r == 2)\n            {\n                outpath_elem = output_path+\"_M\" +to_string(1) + \"_elem_Z.txt\";\n            }else if(r == 1)\n            {\n                outpath_elem = output_path+\"_M\" +to_string(2) + \"_elem_Z.txt\";\n            }else{\n                outpath_elem = output_path+\"_M\" +to_string(0) + \"_elem_Z.txt\";\n            }\n            \n            out_z.open(outpath_elem.c_str());\n            out_z<<\"No.\"; \n            for(int s =0 ;s<N;s++){  // header: species name\n                out_z<< \"\\t\" << nodes_names[s] ;\n            }\n            out_z <<endl;\n            \n            for(vector<int>::iterator it = ids.begin(); it !=ids.end(); it++)\n            {\n                int c = *it;\n                out_z<<c; \n                for(int s=0; s<N;s++)\n                    out_z <<\"\\t\" << Max_Z[r][c][s];\n                out_z <<endl;\n            }\n        out_z.close();\n    }\n    \n    \n}\n\n\nvoid BPP::Output_init0(PhyloProf & prof, ofstream& out_lik, vector<int> & ids){\n    \n    //for(int cc=0; cc<C;cc++)\n    for(vector<int>::iterator it = ids.begin(); it !=ids.end(); it++)\n    {\n        int cc = *it;\n        out_lik <<cc << \"\\t\" << prof.element_names[cc] << \"\\t\"  <<log_liks_sgl[cc]<< \"\\t\"<<log_liks_Z[1][cc];\n        out_lik << endl;\n    }\n    \n    //out_lik.close();\n    \n    \n}\n\n\n\n\n", "meta": {"hexsha": "6554908b6e1dfb3b6a4a2d6418b1f74aa101e229", "size": 18422, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SRC/bpp.cpp", "max_stars_repo_name": "beyondpie/PhyloAcc", "max_stars_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-11T14:34:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T06:58:59.000Z", "max_issues_repo_path": "SRC/bpp.cpp", "max_issues_repo_name": "beyondpie/PhyloAcc", "max_issues_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T03:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T09:54:35.000Z", "max_forks_repo_path": "SRC/bpp.cpp", "max_forks_repo_name": "beyondpie/PhyloAcc", "max_forks_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-03T18:49:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T04:39:30.000Z", "avg_line_length": 30.1013071895, "max_line_length": 331, "alphanum_fraction": 0.5274671588, "num_tokens": 5738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.36296920551961687, "lm_q1q2_score": 0.24652095284553924}}
{"text": "/**\n * \\file\n * \\copyright\n * Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"LocalLinearLeastSquaresExtrapolator.h\"\n\n#include <Eigen/SVD>\n\n#include \"BaseLib/Logging.h\"\n#include \"ExtrapolatableElementCollection.h\"\n#include \"MathLib/LinAlg/Eigen/EigenMapTools.h\"\n#include \"MathLib/LinAlg/LinAlg.h\"\n#include \"MathLib/LinAlg/MatrixVectorTraits.h\"\n#include \"NumLib/Assembler/SerialExecutor.h\"\n#include \"NumLib/Function/Interpolation.h\"\n\nnamespace NumLib\n{\nLocalLinearLeastSquaresExtrapolator::LocalLinearLeastSquaresExtrapolator(\n    NumLib::LocalToGlobalIndexMap const& dof_table)\n    : _dof_table_single_component(dof_table)\n{\n    /* Note in case the following assertion fails:\n     * If you copied the extrapolation code, for your processes from\n     * somewhere, note that the code from the groundwater flow process might\n     * not suit your needs: It is a special case and is therefore most\n     * likely too simplistic. You better adapt the extrapolation code from\n     * some more advanced process, like the TES process.\n     */\n    if (dof_table.getNumberOfGlobalComponents() != 1)\n    {\n        OGS_FATAL(\n            \"The d.o.f. table passed must be for one variable that has only \"\n            \"one component!\");\n    }\n}\n\nvoid LocalLinearLeastSquaresExtrapolator::extrapolate(\n    const unsigned num_components,\n    ExtrapolatableElementCollection const& extrapolatables,\n    const double t,\n    std::vector<GlobalVector*> const& x,\n    std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table)\n{\n    auto const num_nodal_dof_result =\n        _dof_table_single_component.dofSizeWithoutGhosts() * num_components;\n\n    std::vector<GlobalIndexType> ghost_indices;\n    {  // Create num_components times version of ghost_indices arranged by\n       // location. For example for 3 components and ghost_indices {5,6,10} we\n       // compute {15, 16, 17,  18, 19, 20,  30, 31, 32}.\n        auto const& single_component_ghost_indices =\n            _dof_table_single_component.getGhostIndices();\n        auto const single_component_ghost_indices_size =\n            single_component_ghost_indices.size();\n        ghost_indices.reserve(single_component_ghost_indices_size *\n                              num_components);\n        for (unsigned i = 0; i < single_component_ghost_indices_size; ++i)\n        {\n            for (unsigned c = 0; c < num_components; ++c)\n            {\n                ghost_indices.push_back(\n                    single_component_ghost_indices[i] * num_components + c);\n            }\n        }\n    }\n\n    if (!_nodal_values ||\n#ifdef USE_PETSC\n        _nodal_values->getLocalSize() + _nodal_values->getGhostSize()\n#else\n        _nodal_values->size()\n#endif\n            != static_cast<GlobalIndexType>(num_nodal_dof_result))\n    {\n        _nodal_values = MathLib::MatrixVectorTraits<GlobalVector>::newInstance(\n            {num_nodal_dof_result, num_nodal_dof_result, &ghost_indices,\n             nullptr});\n    }\n    _nodal_values->setZero();\n\n    // counts the writes to each nodal value, i.e., the summands in order to\n    // compute the average afterwards\n    auto counts =\n        MathLib::MatrixVectorTraits<GlobalVector>::newInstance(*_nodal_values);\n    counts->setZero();\n\n    auto const size = extrapolatables.size();\n    for (std::size_t i = 0; i < size; ++i)\n    {\n        extrapolateElement(i, num_components, extrapolatables, t, x, dof_table,\n                           *counts);\n    }\n    MathLib::LinAlg::finalizeAssembly(*_nodal_values);\n\n    MathLib::LinAlg::componentwiseDivide(*_nodal_values, *_nodal_values,\n                                         *counts);\n}\n\nvoid LocalLinearLeastSquaresExtrapolator::calculateResiduals(\n    const unsigned num_components,\n    ExtrapolatableElementCollection const& extrapolatables,\n    const double t,\n    std::vector<GlobalVector*> const& x,\n    std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table)\n{\n    auto const num_element_dof_result = static_cast<GlobalIndexType>(\n        _dof_table_single_component.size() * num_components);\n\n    if (!_residuals || _residuals->size() != num_element_dof_result)\n    {\n#ifndef USE_PETSC\n        _residuals.reset(new GlobalVector{num_element_dof_result});\n#else\n        _residuals.reset(new GlobalVector{num_element_dof_result, false});\n#endif\n    }\n\n    if (static_cast<std::size_t>(num_element_dof_result) !=\n        extrapolatables.size() * num_components)\n    {\n        OGS_FATAL(\"mismatch in number of D.o.F.\");\n    }\n\n    auto const size = extrapolatables.size();\n    for (std::size_t i = 0; i < size; ++i)\n    {\n        calculateResidualElement(i, num_components, extrapolatables, t, x,\n                                 dof_table);\n    }\n    MathLib::LinAlg::finalizeAssembly(*_residuals);\n}\n\nvoid LocalLinearLeastSquaresExtrapolator::extrapolateElement(\n    std::size_t const element_index,\n    const unsigned num_components,\n    ExtrapolatableElementCollection const& extrapolatables,\n    const double t,\n    std::vector<GlobalVector*> const& x,\n    std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table,\n    GlobalVector& counts)\n{\n    auto const& integration_point_values =\n        extrapolatables.getIntegrationPointValues(\n            element_index, t, x, dof_table, _integration_point_values_cache);\n\n    // Empty vector means to ignore the values and not to change the counts.\n    if (integration_point_values.empty())\n    {\n        return;\n    }\n\n    auto const& N_0 = extrapolatables.getShapeMatrix(element_index, 0);\n    auto const num_nodes = static_cast<unsigned>(N_0.cols());\n    auto const num_values =\n        static_cast<unsigned>(integration_point_values.size());\n\n    if (num_values % num_components != 0)\n    {\n        OGS_FATAL(\n            \"The number of computed integration point values is not divisible \"\n            \"by the number of num_components. Maybe the computed property is \"\n            \"not a {:d}-component vector for each integration point.\",\n            num_components);\n    }\n\n    // number of integration points in the element\n    const auto num_int_pts = num_values / num_components;\n\n    if (num_int_pts < num_nodes)\n    {\n        OGS_FATAL(\n            \"Least squares is not possible if there are more nodes than \"\n            \"integration points.\");\n    }\n\n    auto const pair_it_inserted = _qr_decomposition_cache.emplace(\n        std::make_pair(num_nodes, num_int_pts), CachedData{});\n\n    auto& cached_data = pair_it_inserted.first->second;\n    if (pair_it_inserted.second)\n    {\n        DBUG(\"Computing new singular value decomposition\");\n\n        // interpolation_matrix * nodal_values = integration_point_values\n        // We are going to pseudo-invert this relation now using singular value\n        // decomposition.\n        auto& interpolation_matrix = cached_data.A;\n        interpolation_matrix.resize(num_int_pts, num_nodes);\n\n        interpolation_matrix.row(0) = N_0;\n        for (unsigned int_pt = 1; int_pt < num_int_pts; ++int_pt)\n        {\n            auto const& shp_mat =\n                extrapolatables.getShapeMatrix(element_index, int_pt);\n            assert(shp_mat.cols() == num_nodes);\n\n            // copy shape matrix to extrapolation matrix row-wise\n            interpolation_matrix.row(int_pt) = shp_mat;\n        }\n\n        // JacobiSVD is extremely reliable, but fast only for small matrices.\n        // But we usually have small matrices and we don't compute very often.\n        // Cf.\n        // http://eigen.tuxfamily.org/dox/group__TopicLinearAlgebraDecompositions.html\n        //\n        // Decomposes interpolation_matrix = U S V^T.\n        Eigen::JacobiSVD<Eigen::MatrixXd> svd(\n            interpolation_matrix, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n        auto const& S = svd.singularValues();\n        auto const& U = svd.matrixU();\n        auto const& V = svd.matrixV();\n\n        // Compute and save the pseudo inverse V * S^{-1} * U^T.\n        auto const rank = svd.rank();\n        assert(rank == num_nodes);\n\n        // cf. http://eigen.tuxfamily.org/dox/JacobiSVD_8h_source.html\n        cached_data.A_pinv.noalias() = V.leftCols(rank) *\n                                       S.head(rank).asDiagonal().inverse() *\n                                       U.leftCols(rank).transpose();\n    }\n    else if (cached_data.A.row(0) != N_0)\n    {\n        OGS_FATAL(\"The cached and the passed shapematrices differ.\");\n    }\n\n    auto const& global_indices =\n        _dof_table_single_component(element_index, 0).rows;\n\n    if (num_components == 1)\n    {\n        auto const integration_point_values_vec =\n            MathLib::toVector(integration_point_values);\n\n        // Apply the pre-computed pseudo-inverse.\n        Eigen::VectorXd const nodal_values =\n            cached_data.A_pinv * integration_point_values_vec;\n\n        // TODO does that give rise to PETSc problems? E.g., writing to ghost\n        // nodes? Furthermore: Is ghost nodes communication necessary for PETSc?\n        _nodal_values->add(global_indices, nodal_values);\n        counts.add(global_indices,\n                   std::vector<double>(global_indices.size(), 1.0));\n    }\n    else\n    {\n        auto const integration_point_values_mat = MathLib::toMatrix(\n            integration_point_values, num_components, num_int_pts);\n\n        // Apply the pre-computed pseudo-inverse.\n        Eigen::MatrixXd const nodal_values =\n            cached_data.A_pinv * integration_point_values_mat.transpose();\n\n        std::vector<GlobalIndexType> indices;\n        indices.reserve(num_components * global_indices.size());\n\n        // _nodal_values is ordered location-wise\n        for (unsigned comp = 0; comp < num_components; ++comp)\n        {\n            transform(cbegin(global_indices), cend(global_indices),\n                      back_inserter(indices),\n                      [&](auto const i) { return num_components * i + comp; });\n        }\n\n        // Nodal_values are passed as a raw pointer, because PETScVector and\n        // EigenVector implementations differ slightly.\n        _nodal_values->add(indices, nodal_values.data());\n        counts.add(indices, std::vector<double>(indices.size(), 1.0));\n    }\n}\n\nvoid LocalLinearLeastSquaresExtrapolator::calculateResidualElement(\n    std::size_t const element_index,\n    const unsigned num_components,\n    ExtrapolatableElementCollection const& extrapolatables,\n    const double t,\n    std::vector<GlobalVector*> const& x,\n    std::vector<NumLib::LocalToGlobalIndexMap const*> const& dof_table)\n{\n    auto const& int_pt_vals = extrapolatables.getIntegrationPointValues(\n        element_index, t, x, dof_table, _integration_point_values_cache);\n\n    auto const num_values = static_cast<unsigned>(int_pt_vals.size());\n    if (num_values % num_components != 0)\n    {\n        OGS_FATAL(\n            \"The number of computed integration point values is not divisible \"\n            \"by the number of num_components. Maybe the computed property is \"\n            \"not a {:d}-component vector for each integration point.\",\n            num_components);\n    }\n\n    // number of integration points in the element\n    const auto num_int_pts = num_values / num_components;\n\n    const auto& global_indices =\n        _dof_table_single_component(element_index, 0).rows;\n    const auto num_nodes = static_cast<unsigned>(global_indices.size());\n\n    auto const& interpolation_matrix =\n        _qr_decomposition_cache.find({num_nodes, num_int_pts})->second.A;\n\n    Eigen::VectorXd nodal_vals_element(num_nodes);\n    auto const int_pt_vals_mat =\n        MathLib::toMatrix(int_pt_vals, num_components, num_int_pts);\n\n    MathLib::LinAlg::setLocalAccessibleVector(\n        *_nodal_values);  // For access in the for-loop.\n    for (unsigned comp = 0; comp < num_components; ++comp)\n    {\n        // filter nodal values of the current element\n        for (unsigned i = 0; i < num_nodes; ++i)\n        {\n            // TODO PETSc negative indices?\n            auto const idx = num_components * global_indices[i] + comp;\n            nodal_vals_element[i] = _nodal_values->get(idx);\n        }\n\n        double const residual = (interpolation_matrix * nodal_vals_element -\n                                 int_pt_vals_mat.row(comp).transpose())\n                                    .squaredNorm();\n\n        auto const eidx =\n            static_cast<GlobalIndexType>(num_components * element_index + comp);\n        // The residual is set to the root mean square value.\n        auto const root_mean_square = std::sqrt(residual / num_int_pts);\n        _residuals->set(eidx, root_mean_square);\n    }\n}\n\n}  // namespace NumLib\n", "meta": {"hexsha": "3b6c67cdd9b7fcf5e6a2e7e384bf90d439646a27", "size": 12768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "NumLib/Extrapolation/LocalLinearLeastSquaresExtrapolator.cpp", "max_stars_repo_name": "ufz/ogs", "max_stars_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2015-03-20T22:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:37:21.000Z", "max_issues_repo_path": "NumLib/Extrapolation/LocalLinearLeastSquaresExtrapolator.cpp", "max_issues_repo_name": "ufz/ogs", "max_issues_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3015.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T21:55:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T01:09:17.000Z", "max_forks_repo_path": "NumLib/Extrapolation/LocalLinearLeastSquaresExtrapolator.cpp", "max_forks_repo_name": "ufz/ogs", "max_forks_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 250.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T15:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:37:20.000Z", "avg_line_length": 37.5529411765, "max_line_length": 86, "alphanum_fraction": 0.6593828321, "num_tokens": 2919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.24635188534928787}}
{"text": "/*\n(***********************************************************************)\n(*                                                                     *)\n(* The ACME project                                                    *)\n(*                                                                     *)\n(* Copyright (c) 2020-2021, Davide Stocco and Enrico Bertolazzi.       *)\n(*                                                                     *)\n(* The ACME project and its components are supplied under the terms of *)\n(* the open source BSD 2-Clause License. The contents of the ACME      *)\n(* project and its components may not be copied or disclosed except in *)\n(* accordance with the terms of the BSD 2-Clause License.              *)\n(*                                                                     *)\n(* URL: https://opensource.org/licenses/BSD-2-Clause                   *)\n(*                                                                     *)\n(*    Davide Stocco                                                    *)\n(*    Department of Industrial Engineering                             *)\n(*    University of Trento                                             *)\n(*    e-mail: davide.stocco@unitn.it                                   *)\n(*                                                                     *)\n(*    Enrico Bertolazzi                                                *)\n(*    Department of Industrial Engineering                             *)\n(*    University of Trento                                             *)\n(*    e-mail: enrico.bertolazzi@unitn.it                               *)\n(*                                                                     *)\n(***********************************************************************)\n*/\n\n///\n/// file: acme_point.hh\n///\n\n#pragma once\n\n#ifndef INCLUDE_ACME_POINT\n#define INCLUDE_ACME_POINT\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\n\n#include \"acme.hh\"\n#include \"acme_entity.hh\"\n#include \"acme_math.hh\"\n\nnamespace acme\n{\n\n  /*\\\n   |               _       _\n   |   _ __   ___ (_)_ __ | |_\n   |  | '_ \\ / _ \\| | '_ \\| __|\n   |  | |_) | (_) | | | | | |_\n   |  | .__/ \\___/|_|_| |_|\\__|\n   |  |_|\n  \\*/\n\n  //! Point class container\n  /**\n   * Specialization of Eigen::Matrix class\n   */\n  class point : public vec3, public entity\n  {\n  public:\n    using vec3::Matrix;\n\n    //! Point class destructor\n    ~point(void);\n\n    //! Point class constructor\n    point(void);\n\n    //! This constructor allows you to construct matrix from Eigen expressions\n    template <typename derived>\n    point(\n      Eigen::MatrixBase<derived> const &other //!< Eigen matrix object\n      ) : vec3(other)\n    {\n    }\n\n    //! This method allows you to assign Eigen expressions to matrix\n    template <typename derived>\n    point &\n    operator=(\n      Eigen::MatrixBase<derived> const &other //!< Eigen matrix object\n    )\n    {\n      this->vec3::operator=(other);\n      return *this;\n    }\n\n    //! Translate point by vector\n    void\n    translate(\n      vec3 const &vector_in //!< Input translation vector\n      ) override;\n\n    //! Transform point with affine transformation matrix\n    void\n    transform(\n      affine const &affine_in //!< 4x4 affine transformation matrix\n      ) override;\n\n    //! Check if entity is degenerated\n    bool\n    isDegenerated(\n      acme::real tolerance = EPSILON //!< Tolerance\n    ) const override;\n\n    //! Return object hierarchical level\n    integer\n    level(void) const override\n    {\n      return 1;\n    }\n\n    //! Return object type as string\n    std::string\n    type(void) const override\n    {\n      return \"point\";\n    }\n\n    //! Check whether the object is no entity\n    bool\n    isNone(void) const override\n    {\n      return false;\n    }\n\n    //! Check whether the object is a point\n    bool\n    isPoint(void) const override\n    {\n      return true;\n    }\n\n    //! Check whether the object is a line\n    bool\n    isLine(void) const override\n    {\n      return false;\n    }\n\n    //! Check whether the object is a ray\n    bool\n    isRay(void) const override\n    {\n      return false;\n    }\n\n    //! Check whether the object is a plane\n    bool\n    isPlane(void) const override\n    {\n      return false;\n    }\n\n    //! Check whether the object is a segment\n    bool\n    isSegment(void) const override\n    {\n      return false;\n    }\n\n    //! Check whether the object is a triangle\n    bool\n    isTriangle(void) const override\n    {\n      return false;\n    }\n\n    //! Check whether the object is a disk\n    bool\n    isDisk(void) const override\n    {\n      return false;\n    }\n\n    //! Check whether the object is a ball\n    bool\n    isBall(void) const override\n    {\n      return false;\n    }\n\n    //! Check whether in the point is clampable\n    bool\n    isClampable(void) const override\n    {\n      return true;\n    }\n\n    //! Check whether in the point is non-clampable\n    bool\n    isNonClampable(void) const override\n    {\n      return false;\n    }\n\n    //! Get minumum and maximum values along axes\n    bool\n    clamp(\n      acme::vec3 &min, //!< Input minimum point\n      acme::vec3 &max  //!< Input maximum point\n    ) const override;\n\n    //! Get minumum and maximum values along axes\n    bool\n    clamp(\n      acme::real &min_x, //!< Input x value of minimum point\n      acme::real &min_y, //!< Input y value of minimum point\n      acme::real &min_z, //!< Input z value of minimum point\n      acme::real &max_x, //!< Input x value of maximum point\n      acme::real &max_y, //!< Input y value of maximum point\n      acme::real &max_z  //!< Input z value of maximum point\n    ) const override;\n\n  }; // class point\n\n  static point const NAN_POINT       = point::Constant(QUIET_NAN); //!< Not-a-Number static const point object\n  static point       THROWAWAY_POINT = point(NAN_POINT);           //!< Throwaway static non-const point object\n\n} // namespace acme\n\n#endif\n\n///\n/// eof: acme_point.hh\n///", "meta": {"hexsha": "0d9aab9bb1a3cb97bf1be77e73f129d0d292cced", "size": 5950, "ext": "hh", "lang": "C++", "max_stars_repo_path": "toolbox/src/acme_point.hh", "max_stars_repo_name": "StoccoDavide/ddd", "max_stars_repo_head_hexsha": "673a96628dc0aa606e86252f1daf4611d9a83486", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-16T09:17:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-16T09:17:10.000Z", "max_issues_repo_path": "toolbox/src/acme_point.hh", "max_issues_repo_name": "StoccoDavide/ddd", "max_issues_repo_head_hexsha": "673a96628dc0aa606e86252f1daf4611d9a83486", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "toolbox/src/acme_point.hh", "max_forks_repo_name": "StoccoDavide/ddd", "max_forks_repo_head_hexsha": "673a96628dc0aa606e86252f1daf4611d9a83486", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-24T08:06:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-24T08:06:28.000Z", "avg_line_length": 25.9825327511, "max_line_length": 111, "alphanum_fraction": 0.4989915966, "num_tokens": 1272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24619874377480977}}
{"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//\n#include <vw/Core/Exception.h>\n#include <vw/Core/Log.h>\n#include <vw/Core/TypeDeduction.h>\n#include <vw/Math/Matrix.h>\n#include <vw/Math/Quaternion.h>\n#include <vw/Math/Vector.h>\n#include <vw/Camera/CAHVModel.h>\n#include <vw/Camera/PinholeModel.h>\n\n#include <boost/algorithm/string/predicate.hpp>\n\nnamespace vw {\nnamespace camera {\n\n  /// This constructor takes a filename and reads in a camera model\n  /// from the file.  The file may contain either CAHV parameters or\n  /// pinhole camera parameters.\n  CAHVModel::CAHVModel(std::string const& filename) {\n    if (filename.empty())\n      vw_throw( IOErr() << \"CAHVModel: null file name passed to constructor.\" );\n\n    if (boost::ends_with(filename, \".cahv\"))\n      read_cahv(filename);\n    else if (boost::ends_with(filename, \".pin\"))\n      read_pinhole(filename);\n    else\n      vw_throw( IOErr() << \"CAHVModel: Unknown camera file suffix.\" );\n  }\n\n  /// Initialize the CAHV vectors directly in the native CAHV format.\n  CAHVModel::CAHVModel(Vector3 const& C_vec,\n                       Vector3 const& A_vec,\n                       Vector3 const& H_vec,\n                       Vector3 const& V_vec) :\n    C(C_vec), A(A_vec), H(H_vec), V(V_vec) {}\n\n  /// Initialize a CAHV model from a pinhole model\n  CAHVModel::CAHVModel(PinholeModel const& pin_model) {\n    //  Intrinsic parametes (in pixel units)\n    Vector2 focal = pin_model.focal_length();\n    Vector2 offset = pin_model.point_offset();\n\n    Vector3 u,v,w;\n    pin_model.coordinate_frame(u,v,w);\n\n    Matrix<double,3,3> R = pin_model.camera_pose().rotation_matrix();\n\n    Vector3 Hvec = R*u;\n    Vector3 Vvec = R*v;\n\n    C = pin_model.camera_center();\n    A = R*w;\n    H = focal[0]*Hvec + offset[0]*A;\n    V = focal[1]*Vvec + offset[1]*A;\n  }\n\n  std::string\n  CAHVModel::type() const { return \"CAHV\"; }\n\n  // FIXME -- Double check anything related to PinholeModel\n  CAHVModel CAHVModel::operator= (PinholeModel const& pin_model) {\n\n    //  Pinhole model parameters (in pixel units)\n    double fH, fV, Hc, Vc;\n    pin_model.intrinsic_parameters(fH, fV, Hc, Vc);\n\n    //  Unit vectors defining camera coordinate frame\n    Vector3 u,v,w;\n    pin_model.coordinate_frame(u,v,w);\n\n    //  The true rotation between world and camera coordinate\n    //  frames includes the rotation R --AND-- a rotation from\n    //  specifying the directions of increasing u,v,w pixels\n    Matrix<double,3,3> R = pin_model.camera_pose().rotation_matrix();\n\n    //  Now create the components of the CAHV model...\n    Vector3 Hvec = R*u;\n    Vector3 Vvec = R*v;\n\n    C = pin_model.camera_center();\n    A = R*w;\n    H = fH*Hvec + Hc*A;\n    V = fV*Vvec + Vc*A;\n\n    return *this;\n  }\n\n  CAHVModel::CAHVModel(double f, Vector2 const& pixel_size,\n                       double xmin, double /*xmax*/, double ymin, double /*ymax*/,\n                       Matrix<double, 4, 4> const& view_matrix) {\n\n    double fH = f/pixel_size.x();\n    double fV = f/pixel_size.y();\n    double Hc = -xmin;\n    double Vc = -ymin;\n\n    Vector3 Hvec(view_matrix[0][0], view_matrix[0][1], view_matrix[0][2]);\n    Vector3 Vvec(view_matrix[1][0], view_matrix[1][1], view_matrix[1][2]);\n\n    C = Vector3(view_matrix[3][0], view_matrix[3][1], view_matrix[3][2]);\n    A = Vector3(view_matrix[2][0], view_matrix[2][1], view_matrix[2][2]);\n    H = fH*Hvec + Hc*A;\n    V = fV*Vvec + Vc*A;\n  }\n\n  CAHVModel::CAHVModel(double f, Vector2 const& pixel_size, double Hc, double Vc,\n                       Vector3 const& Cinit, Vector3 const& Ainit,\n                       Vector3 const& Hvec, Vector3 const& Vvec) {\n    double fH = f/pixel_size.x();\n    double fV = f/pixel_size.y();\n    C = Cinit;\n    A = Ainit;\n    H = fH*Hvec + Hc*A;\n    V = fV*Vvec + Vc*A;\n  }\n\n  Vector2 CAHVModel::point_to_pixel(Vector3 const& point) const {\n    double dDot = dot_prod(point-C, A);\n    return Vector2( dot_prod(point-C, H) / dDot,\n                    dot_prod(point-C, V) / dDot );\n  }\n\n  Vector3 CAHVModel::pixel_to_vector(Vector2 const& pix) const {\n\n    // Find vector\n    Vector3 vec =\n      normalize(cross_prod(V - pix.y() * A,\n                           H - pix.x() * A));\n\n    // The vector VxH should be pointing in the same directions as A,\n    // if it isn't (because we have a left handed system), flip the\n    // vector.\n    if (dot_prod(cross_prod(V, H), A) < 0.0)\n      vec *= -1.0;\n    return vec;\n  }\n\n  Vector3 CAHVModel::camera_center(Vector2 const& pix) const {\n    return C;\n  };\n\n  // --------------------------------------------------\n  //                 Private Methods\n  // --------------------------------------------------\n  void CAHVModel::read_cahv(std::string const& filename) {\n\n    try {\n      std::ifstream input(filename.c_str(), std::ifstream::in);\n      input.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n      vw_out(InfoMessage, \"camera\") << \"Reading CAHV file: \"\n                                    << filename << \".\\n\";\n\n      char r1, r2;\n\n      while (true) {\n        input.ignore(1024, 'C');\n        input >> r1;\n        if (r1 == '=')\n          break;\n      }\n      input >> C[0] >> C[1] >> C[2];\n\n      input >> r1 >> r2;\n      if (r1 != 'A' || r2 != '=')\n        vw_throw( IOErr() << \"CAHVModel: Could not read A vector\\n\" );\n      input >> A(0) >> A(1) >> A(2);\n\n      input >> r1 >> r2;\n      if (r1 != 'H' || r2 != '=')\n        vw_throw( IOErr() << \"CAHVModel: Could not read H vector\\n\" );\n      input >> H(0) >> H(1) >> H(2);\n\n      input >> r1 >> r2;\n      if (r1 != 'V' || r2 != '=')\n        vw_throw( IOErr() << \"CAHVModel: Could not read V vector\\n\" );\n      input >> V(0) >> V(1) >> V(2);\n\n    } catch ( const std::ifstream::failure& e ) {\n      vw_throw( IOErr() << \"CAHVModel: Could not read file: \" << filename << \" (\" << e.what() << \")\" );\n    }\n  }\n\n  void CAHVModel::read_pinhole(std::string const& filename) {\n    FILE *camFP = fopen(filename.c_str(), \"r\");\n\n    if (camFP == 0)\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not open file\\n\" );\n\n    char line[2048];\n    double f, fH, fV, Hc, Vc;\n    Vector2 pixelSize;\n    Vector3 Hvec, Vvec;\n\n    // Read intrinsic parameters\n    if (!fgets(line, sizeof(line), camFP) ||\n        sscanf(line,\"f = %lf\", &f) != 1) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read focal length\\n\" );\n      fclose(camFP);\n    }\n\n    if (!fgets(line, sizeof(line), camFP) ||\n        sscanf(line,\"SP = %lf %lf\", &pixelSize.x(), &pixelSize.y()) != 2) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read pixel size\\n\" );\n      fclose(camFP);\n    }\n\n    if (!fgets(line, sizeof(line), camFP) ||\n        sscanf(line,\"IC = %lf %lf\", &Hc, &Vc) != 2) {\n      vw_throw( IOErr() << \"CAHVModel::ReadPinhole: Could not read image center pos\\n\" );\n      fclose(camFP);\n    }\n\n    // Read extrinsic parameters\n    if (!fgets(line, sizeof(line), camFP) ||\n        sscanf(line,\"C = %lf %lf %lf\", &C(0), &C(1), &C(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read C vector\\n\" );\n      fclose(camFP);\n    }\n\n    if (!fgets(line, sizeof(line), camFP) ||\n        sscanf(line,\"A = %lf %lf %lf\", &A(0), &A(1), &A(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read A vector\\n\" );\n      fclose(camFP);\n    }\n\n    if (!fgets(line, sizeof(line), camFP) ||\n        sscanf(line,\"Hv = %lf %lf %lf\", &Hvec(0), &Hvec(1), &Hvec(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read Hvec\\n\" );\n      fclose(camFP);\n    }\n\n    if (!fgets(line, sizeof(line), camFP) ||\n        sscanf(line,\"Vv = %lf %lf %lf\", &Vvec(0), &Vvec(1), &Vvec(2)) != 3) {\n      vw_throw( IOErr() << \"CAHVModel::read_pinhole: Could not read Vvec\\n\" );\n      fclose(camFP);\n    }\n\n    // In the future, we should also read in a view matrix -- LJE\n    //     double dummy\n    //     if (sscanf(line, \"VM = %lf %lf %lf %f %lf %lf %lf %f \"\n    //        \"%lf %lf %lf %f %lf %lf %lf %f \",\n    //        &Hvec(0), &Hvec(1), &Hvec(2), &dummy,\n    //        &Vvec(0), &Vvec(1), &Vvec(2), &dummy,\n    //        &A(0), &A(1), &A(2), &dummy,\n    //        &C(0), &C(1), &C(2), &dummy) != 16)\n    //     {\n    //       vw_throw( IOErr()\n    //  << \"CAHVModel::ReadPinhole: Could not read view matrix\\n\" );\n    //       fclose(camFP);\n    //     }\n\n    fH = f/pixelSize.x();\n    fV = f/pixelSize.y();\n\n    H = fH*Hvec + Hc*A;\n    V = fV*Vvec + Vc*A;\n\n    fclose(camFP);\n  }\n\n  void epipolar(CAHVModel const src_camera0, CAHVModel const src_camera1,\n                CAHVModel &dst_camera0, CAHVModel &dst_camera1) {\n\n    // Compute a common image center and scale for the two models\n    double hc = dot_prod(src_camera0.H, src_camera0.A) / 2.0 +\n      dot_prod(src_camera1.H, src_camera1.A) / 2.0;\n    double vc = dot_prod(src_camera0.V, src_camera0.A) / 2.0 +\n      dot_prod(src_camera1.V, src_camera1.A) / 2.0;\n\n    double hs = norm_2(cross_prod(src_camera0.A, src_camera0.H))/2.0 +\n      norm_2(cross_prod(src_camera1.A, src_camera1.H))/2.0;\n\n    double vs = norm_2(cross_prod(src_camera0.A, src_camera0.V))/2.0 +\n      norm_2(cross_prod(src_camera1.A, src_camera1.V))/2.0;\n\n    // Use common center and scale to construct common A, H, V\n    Vector3 app  = src_camera0.A + src_camera1.A;\n\n    // Note the directionality of 1 to 0, for consistency later\n    Vector3 f = cross_prod(cross_prod(app, src_camera1.C - src_camera0.C), app);\n\n    Vector3 hp;\n    if (dot_prod(f, src_camera0.H) > 0)\n      hp = f * hs / (norm_2(f));\n    else\n      hp = -f * hs / (norm_2(f));\n\n    app *= 0.5;\n    Vector3 g = hp * dot_prod(app,hp) / (hs * hs);\n    Vector3 a = normalize(app - g);\n    Vector3 vp = cross_prod(a, hp) * vs / hs;\n\n    dst_camera0.C = src_camera0.C;\n    dst_camera1.C = src_camera1.C;\n\n    dst_camera0.A = dst_camera1.A = a;\n    dst_camera0.H = dst_camera1.H = hp + hc * a;\n    dst_camera0.V = dst_camera1.V = vp + vc * a;\n  }\n\n  void CAHVModel::write(std::string const& filename ) {\n    try {\n      std::ofstream output(filename.c_str(), std::ofstream::out);\n      output.exceptions(std::ofstream::failbit | std::ofstream::badbit);\n      output.precision(20);\n\n      vw_out(InfoMessage, \"camera\") << \"Writing CAHV file: \" << filename << \"\\n\";\n\n      output << \"C = \" << C[0] << \" \" << C[1] << \" \" << C[2] << \"\\n\"\n             << \"A = \" << A[0] << \" \" << A[1] << \" \" << A[2] << \"\\n\"\n             << \"H = \" << H[0] << \" \" << H[1] << \" \" << H[2] << \"\\n\"\n             << \"V = \" << V[0] << \" \" << V[1] << \" \" << V[2] << \"\\n\";\n    } catch ( const std::ofstream::failure& e ) {\n      vw_throw( IOErr() << \"CAHVModel: Could not write file: \" << filename << \"(\" << e.what() << \")\" );\n    }\n  }\n\n  std::ostream& operator<<(std::ostream& str, CAHVModel const& model) {\n    str << \"CAHV camera: \\n\";\n    str << \"\\tC: \" << model.C << \"\\n\";\n    str << \"\\tA: \" << model.A << \"\\n\";\n    str << \"\\tH: \" << model.H << \"\\n\";\n    str << \"\\tV: \" << model.V << \"\\n\";\n    return str;\n  }\n\n}} // namespace vw::camera\n", "meta": {"hexsha": "fed9dacb286ca83960988726420538c84556dce9", "size": 11710, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Camera/CAHVModel.cc", "max_stars_repo_name": "mdhancher/visionworkbench", "max_stars_repo_head_hexsha": "d2074e1186a81777e64000a62c4f6cd9a47d3c36", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-12T19:42:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-12T19:42:48.000Z", "max_issues_repo_path": "src/vw/Camera/CAHVModel.cc", "max_issues_repo_name": "maxsu/visionworkbench", "max_issues_repo_head_hexsha": "34eb3009152d3696471056e65b313d964e658ee8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vw/Camera/CAHVModel.cc", "max_forks_repo_name": "maxsu/visionworkbench", "max_forks_repo_head_hexsha": "34eb3009152d3696471056e65b313d964e658ee8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-26T00:44:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T00:44:27.000Z", "avg_line_length": 33.6494252874, "max_line_length": 103, "alphanum_fraction": 0.5694278395, "num_tokens": 3594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2461546467657137}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n#include <vw/Core/Log.h>\n#include <vw/Camera/CAHVOREModel.h>\n#include <fstream>\n#include <boost/foreach.hpp>\n\nusing namespace vw;\nusing namespace vw::camera;\n\nbool CAHVOREModel::check_line( std::istream& istream, char letter ) {\n  char r1,r2;\n  istream >> r1 >> r2;\n  if ( r1 != letter || r2 != '=' )\n    return false;\n  return true;\n}\n\n// Overloaded constructor - this one reads in the file name\n// where the CAHVORE camera model is saved.\nCAHVOREModel::CAHVOREModel(std::string const& filename) {\n\n  try {\n    std::ifstream input(filename.c_str(), std::ifstream::in);\n    input.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n    vw_out(InfoMessage, \"camera\") << \"Reading CAHVORE file: \"\n                                  << filename << \".\\n\";\n\n    char r1;\n\n    while (true) {\n      input.ignore(1024, 'C');\n      input >> r1;\n      if (r1 == '=')\n        break;\n    }\n    input >> C(0) >> C(1) >> C(2);\n\n    if ( !check_line( input, 'A') )\n      vw_throw( IOErr() << \"CAHVOREModel: Could not read A vector\\n\" );\n    input >> A(0) >> A(1) >> A(2);\n\n    if ( !check_line( input, 'H') )\n      vw_throw( IOErr() << \"CAHVOREModel: Could not read H vector\\n\" );\n    input >> H(0) >> H(1) >> H(2);\n\n    if ( !check_line( input, 'V') )\n      vw_throw( IOErr() << \"CAHVOREModel: Could not read V vector\\n\" );\n    input >> V(0) >> V(1) >> V(2);\n\n    if ( !check_line( input, 'O') )\n      vw_throw( IOErr() << \"CAHVOREModel: Could not read O vector\\n\" );\n    input >> O(0) >> O(1) >> O(2);\n\n    if ( !check_line( input, 'R') )\n      vw_throw( IOErr() << \"CAHVOREModel: Could not read R vector\\n\" );\n    input >> R(0) >> R(1) >> R(2);\n\n    if ( !check_line( input, 'E') )\n      vw_throw( IOErr() << \"CAHVOREModel: could not read R vector\\n\" );\n    input >> E(0) >> E(1) >> E(2);\n\n    if ( !check_line( input, 'T') )\n      vw_throw( IOErr() << \"CAHVOREModel: could not read T element\\n\" );\n    int T;\n    input >> T;\n\n    if ( !check_line( input, 'P') )\n      vw_throw( IOErr() << \"CAHVOREModel: could not read P element\\n\" );\n    input >> P;\n\n    switch( T ) {\n    case 1: P = 1.0; break;\n    case 2: P = 0.0; break;\n    case 3:\n      if ( P < 0 || P > 1 ) vw_throw( ArgumentErr() << \"Invalid P value: \"\n                                      << P << \"\\n\" );\n      break;\n    default: vw_throw( ArgumentErr() << \"Unknown CAHVORE type: \" << T << \"\\n\" );\n    }\n\n  } catch (const std::ifstream::failure& e) {\n    vw_throw( IOErr() << \"CAHVOREModel: Could not read file: \" << filename << \" (\" << e.what() << \")\" );\n  }\n}\n\n// Write CAHVOR model to file.\nvoid vw::camera::CAHVOREModel::write(std::string const& filename) {\n  try {\n    std::ofstream output(filename.c_str(), std::ofstream::out);\n    output.exceptions(std::ofstream::failbit | std::ofstream::badbit);\n    output.precision(20);\n\n    vw_out(InfoMessage, \"camera\") << \"Writing CAHVORE file: \" << filename << \"\\n\";\n\n    output << \"C = \" << C(0) << \" \" << C(1) << \" \" << C(2) << \"\\n\"\n           << \"A = \" << A(0) << \" \" << A(1) << \" \" << A(2) << \"\\n\"\n           << \"H = \" << H(0) << \" \" << H(1) << \" \" << H(2) << \"\\n\"\n           << \"V = \" << V(0) << \" \" << V(1) << \" \" << V(2) << \"\\n\"\n           << \"O = \" << O(0) << \" \" << O(1) << \" \" << O(2) << \"\\n\"\n           << \"R = \" << R(0) << \" \" << R(1) << \" \" << R(2) << \"\\n\"\n           << \"E = \" << E(0) << \" \" << E(1) << \" \" << E(2) << \"\\n\";\n    if ( P == 0 ) {\n      output << \"T = 2\\n\";\n    } else if ( P == 1 ) {\n      output << \"T = 1\\n\";\n    } else {\n      output << \"T = 3\\n\";\n    }\n    output << \"P = \" << P << \"\\n\";\n  } catch ( const std::ofstream::failure& e ) {\n    vw_throw( IOErr() << \"CAHVOREModel: Could not write file: \" << filename << \" (\" << e.what() << \")\" );\n  }\n}\n\nvw::Vector3 CAHVOREModel::pixel_to_vector(vw::Vector2 const& pix) const {\n  // Based on JPL's cmod_cahvore_2d_to_3d\n  Vector3 result;\n\n  // Calculate initial terms\n  Vector3 w3 = cross_prod(V - pix[1]*A,\n                          H - pix[0]*A);\n  Vector3 rp = (1/dot_prod(A,cross_prod(V,H))) * w3;\n\n  double zetap = dot_prod(rp,O);\n  Vector3 lambdap3 = rp - zetap*O;\n  double lambdap = norm_2(lambdap3);\n  double chip = lambdap / zetap;\n\n  if (chip < 1e-8) {\n    // Approximations for small angles\n    result = O;\n  } else {\n    // Full calculations\n\n    // Calculate chi using Newton's Method\n    double chi = chip;\n    double dchi = 1;\n    for (int32 n = 0;; ++n) {\n      // Checking exit conditions\n      if (n > 100)\n        vw_throw( PixelToRayErr() << \"CAHVOREModel: Did not converge.\\n\" );\n      if (fabs(dchi) < 1e-8)\n        break;\n\n      // Compute terms from the current value of chi\n      double chi2 = chi * chi;\n      double chi3 = chi * chi2;\n      double chi4 = chi * chi3;\n      double chi5 = chi * chi4;\n\n      // Update chi\n      double deriv = (1 + R[0]) + 3*R[1]*chi2 + 5*R[2]*chi4;\n      dchi = ((1 + R[0])*chi + R[1]*chi3 + R[2]*chi5 - chip) / deriv;\n      chi -= dchi;\n    }\n\n    // Compute the incoming ray's angle\n    double linchi, theta;\n    linchi = P * chi;\n    if (P < -1e-15)\n      theta = asin(linchi) / P;\n    else if (P > 1e-15)\n      theta = atan(linchi) / P;\n    else\n      theta = chi;\n\n    double theta2 = theta*theta;\n    double mu = E[2];\n    mu = E[1] + theta2*mu;\n    mu = E[0] + theta2*mu;\n\n    result = sin(theta)*normalize(lambdap3) + cos(theta)*O;\n  }\n\n  return result;\n}\n\nVector2 CAHVOREModel::point_to_pixel(vw::Vector3 const& point) const {\n  // Base on JPL's cmod_cahvore_3d_to_2d_general\n\n  // Calculate initial terms\n  Vector3 p_c = point - C;\n  double zeta = dot_prod(p_c, O);\n  Vector3 lambda3 = p_c - zeta * O;\n  double lambda = norm_2(lambda3);\n\n  // Calculate theta using Newton's Method\n  double theta = atan2(lambda, zeta);\n  double dtheta = 1;\n  for (int32 n = 0;;++n) {\n\n    // Checking exit conditions\n    if (n > 100)\n      vw_throw( PointToPixelErr() << \"CAHVOREModel: Did not converge.\\n\" );\n    if (fabs(dtheta) < 1e-8)\n      break;\n\n    // Compute terms from the current value of theta\n    double costh = cos(theta);\n    double sinth = sin(theta);\n    double theta2 = theta * theta;\n    double theta3 = theta * theta2;\n    double theta4 = theta * theta3;\n    double upsilon = zeta*costh + lambda*sinth\n      - (1     - costh) * (E[0] +  E[1]*theta2 +   E[2]*theta4)\n      - (theta - sinth) * (      2*E[1]*theta  + 4*E[2]*theta3);\n\n    // Update theta\n    dtheta = (\n              zeta*sinth - lambda*costh\n              - (theta - sinth) * (E[0] + E[1]*theta2 + E[2]*theta4)\n              ) / upsilon;\n    theta -= dtheta;\n  }\n\n  // Check the value of theta\n  if ((theta * fabs(P)) > M_PI/2)\n    vw_throw( PointToPixelErr() << \"CAHVOREModel: Theta out of bounds.\\n\" );\n\n  // Approximations for small theta\n  Vector3 rp;\n  if (theta < 1e-8) {\n    rp = p_c;\n  } else {\n    // Full calculations\n    double linth, chi;\n\n    linth = P * theta;\n    if (P < -1e-15)\n      chi = sin(linth) / P;\n    else if (P > 1e-15)\n      chi = tan(linth) / P;\n    else\n      chi = theta;\n\n    double chi2 = chi*chi;\n    double mu = R[2];\n    mu = R[1] + chi2 * mu;\n    mu = R[0] + chi2 * mu;\n    rp = (lambda / chi) * O + (1+mu)*lambda3;\n  }\n\n  // Calculate the projection\n  double alpha  = dot_prod(rp, A);\n  return Vector2( dot_prod(rp,H) / alpha,\n                  dot_prod(rp,V) / alpha );\n}\n\nCAHVModel camera::linearize_camera( CAHVOREModel const& camera_model,\n                                    Vector2i const& cahvore_image_size,\n                                    Vector2i const& cahv_image_size ) {\n  // Limit to field of view\n  const static double limfov = M_PI * 3/4; // 135 degrees field of view.\n  const bool minfov          = true;       // Yes, minimize the common field of view\n\n  CAHVModel cahv_model;\n  cahv_model.C = camera_model.C;\n\n  // Record the landmark 2D coordinates around the perimeter of the image\n  Vector2 hpts[6], vpts[6];\n  hpts[0] = Vector2();\n  hpts[1] = Vector2(0,(cahvore_image_size[1]-1)/2);\n  hpts[2] = Vector2(0,cahvore_image_size[1]-1);\n  hpts[3] = Vector2(cahvore_image_size[0]-1,0);\n  hpts[4] = Vector2(cahvore_image_size[0]-1,(cahvore_image_size[1]-1)/2);\n  hpts[5] = cahvore_image_size - Vector2(1,1);\n  vpts[0] = Vector2();\n  vpts[1] = Vector2((cahvore_image_size[0]-1)/2,0);\n  vpts[2] = Vector2(cahvore_image_size[0]-1,0);\n  vpts[3] = Vector2(0,cahvore_image_size[1]-1);\n  vpts[4] = Vector2((cahvore_image_size[0]-1)/2,cahvore_image_size[1]-1);\n  vpts[5] = cahvore_image_size - Vector2(1,1);\n\n  // Choose a camera axis in the middle of the image\n  Vector2 p2 = (cahvore_image_size-Vector2i(1,1))/2.0;\n  cahv_model.A = camera_model.pixel_to_vector( p2 );\n\n  // Compute the original right and down vectors\n  Vector3 dn = cross_prod(camera_model.A, camera_model.H);\n  Vector3 rt = normalize(cross_prod(dn,   camera_model.A));\n  dn = normalize( dn );\n\n  // Adjust the right and down vectors to be orthogonal to new axis\n  rt = cross_prod(dn, cahv_model.A);\n  dn = normalize(cross_prod(cahv_model.A, rt));\n  rt = normalize( rt );\n\n  // Find horizontal and vertical fields of view\n  double hmin = 1, hmax = -1;\n  BOOST_FOREACH( Vector2 const& loop, hpts ) {\n    const Vector3 u3 = camera_model.pixel_to_vector(loop);\n    double cs = dot_prod(cahv_model.A, normalize(u3 - dot_prod(dn, u3) * dn));\n    if (hmin > cs) hmin = cs;\n    if (hmax < cs) hmax = cs;\n  }\n  double vmin = 1, vmax = -1;\n  BOOST_FOREACH( Vector2 const& loop, vpts ) {\n    const Vector3 u3 = camera_model.pixel_to_vector(loop);\n    double cs = dot_prod(cahv_model.A,normalize(u3 - dot_prod(rt, u3)*rt));\n    if (vmin > cs) vmin = cs;\n    if (vmax < cs) vmax = cs;\n  }\n\n  // Compute the all-encompassing scale factors\n  Vector2 cosines;\n  if ( minfov ) {\n    // use max\n    cosines = Vector2(hmax,vmax);\n  } else {\n    // use min\n    cosines = Vector2(hmin,vmin);\n  }\n  if ( acos(cosines[0]) > limfov ) cosines[0] = cos(limfov);\n  if ( acos(cosines[1]) > limfov ) cosines[1] = cos(limfov);\n  Vector2 scalars =\n    elem_quot(elem_prod(cahv_image_size/2.0,cosines),\n              sqrt(Vector2(1,1) - elem_prod(cosines,cosines)));\n\n  // Assign idealized image centers and coordinate angles\n  Vector2 centers = (cahv_image_size - Vector2(1,1))/2.0;\n\n  // Construct H and V\n  cahv_model.H = scalars[0] * rt + centers[0] * cahv_model.A;\n  cahv_model.V = scalars[1] * dn + centers[1] * cahv_model.A;\n\n  return cahv_model;\n}\n", "meta": {"hexsha": "74b077dd01e181e56a47de213a705f1b481443cc", "size": 10475, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Camera/CAHVOREModel.cc", "max_stars_repo_name": "digimatronics/ComputerVision", "max_stars_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-16T23:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T23:57:32.000Z", "max_issues_repo_path": "src/vw/Camera/CAHVOREModel.cc", "max_issues_repo_name": "rkrishnasanka/visionworkbench", "max_issues_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vw/Camera/CAHVOREModel.cc", "max_forks_repo_name": "rkrishnasanka/visionworkbench", "max_forks_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-18T04:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T10:34:39.000Z", "avg_line_length": 31.2686567164, "max_line_length": 105, "alphanum_fraction": 0.5673508353, "num_tokens": 3477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.24613408273759838}}
{"text": "// Copyright (c) 2020 fortiss GmbH\n//\n// Authors: Julian Bernhard, Klemens Esterle, Patrick Hart and\n// Tobias Kessler\n//\n// This work is licensed under the terms of the MIT license.\n// For a copy, see <https://opensource.org/licenses/MIT>.\n\n#ifndef BARK_GEOMETRY_LINE_HPP_\n#define BARK_GEOMETRY_LINE_HPP_\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <tuple>\n#include <utility>\n#include <vector>\n\n#include <boost/geometry.hpp>\n#include <boost/geometry/geometries/geometries.hpp>\n#include <boost/tuple/tuple.hpp>\n\n#include \"bark/geometry/angle.hpp\"\n#include \"bark/geometry/commons.hpp\"\n\n#include \"src/spline.h\"\n\nnamespace bark {\nnamespace geometry {\n\n//! templated line class with a boost polygon as a member function\ntemplate <typename T>\nclass Line_t : public Shape<bg::model::linestring<T>, T> {\n public:\n  Line_t()\n      : Shape<bg::model::linestring<T>, T>(Pose(0, 0, 0), std::vector<T>(), 0) {\n  }\n\n  explicit Line_t(const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& points);\n\n  virtual Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> ToArray() const;\n\n  virtual std::shared_ptr<Shape<bg::model::linestring<T>, T>> Clone() const;\n\n  //! TODO(@all): do not recompute full s but only add one point\n  bool AddPoint(const T& p) {\n    return Shape<bg::model::linestring<T>, T>::AddPoint(p) && RecomputeS();\n  }\n\n  bool AddPoints(const std::vector<T>& pts) {\n    for (const auto& p : pts) {\n      Shape<bg::model::linestring<T>, T>::AddPoint(p);\n    }\n    return RecomputeS();\n  }\n\n  auto Length() const {\n    return bg::length(Shape<bg::model::linestring<T>, T>::obj_);\n  }\n\n  unsigned int size() const {\n    return Shape<bg::model::linestring<T>, T>::obj_.size();\n  }\n\n  void AppendLinestring(const Line_t& ls) {\n    bg::append(Shape<bg::model::linestring<T>, T>::obj_, ls.obj_);\n    RecomputeS();\n  }\n\n  std::vector<T> GetPointsInSInterval(double begin, double end) const {\n    std::vector<T> points;\n    uint begin_idx = std::upper_bound(s_.begin(), s_.end(), begin) - s_.begin();\n    uint end_idx = std::lower_bound(s_.begin(), s_.end(), end) - s_.begin();\n    std::copy(Shape<bg::model::linestring<T>, T>::obj_.begin() + begin_idx,\n              Shape<bg::model::linestring<T>, T>::obj_.begin() + end_idx,\n              std::back_inserter(points));\n    return points;\n  }\n\n  virtual bool Valid() const {\n    return Shape<bg::model::linestring<T>, T>::Valid() && s_.size() == size();\n  }\n\n  void Reverse() {\n    boost::geometry::reverse(Shape<bg::model::linestring<T>, T>::obj_);\n  }\n\n  typedef typename std::vector<T>::iterator point_iterator;\n  typedef typename std::vector<T>::const_iterator const_point_iterator;\n  point_iterator begin() {\n    return Shape<bg::model::linestring<T>, T>::obj_.begin();\n  }\n  const_point_iterator begin() const {\n    return Shape<bg::model::linestring<T>, T>::obj_.begin();\n  }\n  point_iterator end() {\n    return Shape<bg::model::linestring<T>, T>::obj_.end();\n  }\n  const_point_iterator end() const {\n    return Shape<bg::model::linestring<T>, T>::obj_.end();\n  }\n\n  typedef typename std::vector<T>::reverse_iterator reverse_point_iterator;\n  typedef typename std::vector<T>::const_reverse_iterator\n      const_reverse_point_iterator;  // NOLINT\n\n  reverse_point_iterator rbegin() {\n    return Shape<bg::model::linestring<T>, T>::obj_.rbegin();\n  }\n  const_reverse_point_iterator rbegin() const {\n    return Shape<bg::model::linestring<T>, T>::obj_.rbegin();\n  }\n  reverse_point_iterator rend() {\n    return Shape<bg::model::linestring<T>, T>::obj_.rend();\n  }\n  const_reverse_point_iterator rend() const {\n    return Shape<bg::model::linestring<T>, T>::obj_.rend();\n  }\n\n  //! local coordinates 0..[total distance] along the lines\n  std::vector<double> s_;\n\n  //! @todo free function, s_ private?\n  bool RecomputeS() {\n    s_.clear();\n    // edge case no points\n    if (Shape<bg::model::linestring<T>, T>::obj_.empty()) {\n      return true;\n    } else if (Shape<bg::model::linestring<T>, T>::obj_.size() == 1) {\n      // edge case one point\n      s_.push_back(0.0);\n      return true;\n    } else {  // nominal case\n      // compute distance from last point to next point and\n      // store these on vector s_ (avoid additional tmp vector)\n      T last_pt = Shape<bg::model::linestring<T>, T>::obj_.front();\n      s_.reserve(Shape<bg::model::linestring<T>, T>::obj_.size());\n      double distance_until_now = 0.0;\n      for (const T& next_pt : Shape<bg::model::linestring<T>, T>::obj_) {\n        distance_until_now += bg::distance(next_pt, last_pt);\n        s_.push_back(distance_until_now);\n        last_pt = next_pt;\n      }\n      return true;\n    }\n  }\n\n  void RemoveDuplicates() {\n    bg::unique(Shape<bg::model::linestring<T>, T>::obj_);\n    RecomputeS();\n  }\n  bool operator==(const Line_t& rhs) const {\n    return bg::equals(this->obj_, rhs.obj_);\n  }\n  bool operator!=(const Line_t& rhs) const { return !(rhs == *this); }\n};\n\n//! for better usage simple double defines\nusing LinePoint = Point2d;\nusing Line = Line_t<LinePoint>;\n\ntemplate <typename T>\ninline Line_t<T>::Line_t(\n    const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>& points)\n    : Shape<bg::model::linestring<T>, T>(points, 0) {\n  RecomputeS();\n}\n\ntemplate <>\ninline Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Line::ToArray()\n    const {\n  Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(obj_.size(), 2);\n  for (uint32_t i = 0; i < obj_.size(); i++) {\n    mat.row(i) << bg::get<0>(obj_[i]), bg::get<1>(obj_[i]);\n  }\n  return mat;\n}\n\ntemplate <typename T>\ninline std::shared_ptr<Shape<bg::model::linestring<T>, T>> Line_t<T>::Clone()\n    const {\n  std::shared_ptr<Line_t<T>> new_line = std::make_shared<Line_t<T>>(*this);\n  return new_line;\n}\n\ntemplate <typename T>\ninline Line Reverse(const T& l) {\n  T lr = l;\n  lr.Reverse();\n  return lr;\n}\n\ninline double Distance(const Line& line, const Point2d& p) {\n  return bg::distance(line.obj_, p);\n}\n\ninline double Distance(const Line& line, const Line& line2) {\n  return bg::distance(line.obj_, line2.obj_);\n}\n\ntemplate <typename T>\ninline T Length(const Line& line) {\n  return bg::length<T>(line.obj_);\n}\n\ninline Line Rotate(const Line& line, double hdg) {\n  using boost::geometry::strategy::transform::rotate_transformer;\n  rotate_transformer<boost::geometry::radian, double, 2, 2> rotate(hdg);\n  Line line_rotated;\n  boost::geometry::transform(line.obj_, line_rotated.obj_, rotate);\n  line_rotated.RecomputeS();\n  return line_rotated;\n}\n\ninline Line Translate(const Line& line, double x, double y) {\n  using boost::geometry::strategy::transform::translate_transformer;\n  translate_transformer<double, 2, 2> translate(x, y);\n  Line line_translated;\n  boost::geometry::transform(line.obj_, line_translated.obj_, translate);\n  return line_translated;\n}\n\ninline Line Simplify(const Line& line, double max_distance) {\n  Line temp_line;\n  boost::geometry::simplify(line.obj_, temp_line.obj_, max_distance);\n  temp_line.RecomputeS();\n  return temp_line;\n}\n\ninline int GetSegmentEndIdx(Line l, double s) {\n  std::vector<double>::iterator up =\n      std::upper_bound(l.s_.begin(), l.s_.end(), s);\n  if (up != l.s_.end()) {\n    int retval = up - l.s_.begin();\n    return retval;\n  } else {\n    return l.s_.size() - 1;  // last point if s is larger then line length\n  }\n}\n\ninline bool CheckSForSegmentIntersection(Line l, double s) {\n  int start_it = GetSegmentEndIdx(l, s);\n  std::vector<double>::iterator low =\n      std::lower_bound(l.s_.begin(), l.s_.end(), s);\n  int start_it_low = low - l.s_.begin();\n  return start_it != start_it_low;\n}\n\ninline Point2d GetPointAtIdx(const Line& l, const uint idx) {\n  if (idx > l.obj_.size() - 1) {\n    LOG(WARNING) << \"idx is outside line\";\n    return l.obj_.back();\n  } else {\n    return l.obj_.at(idx);\n  }\n}\n\ninline Eigen::VectorXd Gradient(Eigen::VectorXd vec) {\n  // calculating central difference\n  Eigen::VectorXd g(vec.size());\n  for (int i = 1; i < vec.size() - 1; i++) {\n    g(i) = (vec(i + 1) - vec(i - 1)) / 2;\n  }\n  // TODO: find better solution for first and last point\n  g(0) = g(1);\n  g(vec.size() - 1) = g(vec.size() - 2);\n  return g;\n}\n\ninline Eigen::VectorXd GetCurvature(const Line& l) {\n  Eigen::MatrixXd larray = l.ToArray();\n  Eigen::VectorXd dx = Gradient(larray.col(0));\n  Eigen::VectorXd ddx = Gradient(dx);\n  Eigen::VectorXd dy = Gradient(larray.col(1));\n  Eigen::VectorXd ddy = Gradient(dy);\n\n  // elementwise, as pow(vector, scalar) does not work\n  Eigen::VectorXd curvature(larray.rows());\n  for (int i = 0; i < curvature.size(); i++) {\n    double n = dx(i) * ddy(i) - ddx(i) * dy(i);\n    double r = pow(dx(i), 2) + pow(dy(i), 2);\n    double d = pow(r, 1.5);\n    if (d == 0) {\n      curvature(i) = 0;\n    } else {\n      curvature(i) = n / d;\n    }\n  }\n  return curvature;\n}\n\ninline Point2d GetPointAtS(Line l, double s) {\n  const size_t& length = l.obj_.size();\n  if (length <= 1) {  // this is an error Line consist of 0 or 1 element\n    return Point2d(0, 0);\n  } else if (s <= 0.0) {  // edge case begin\n    return l.obj_.at(0);\n  } else if (s >= l.s_.back()) {  // edge case end\n    return l.obj_.at(length - 1);\n  } else {  // nominal case\n    int segment_end_idx = GetSegmentEndIdx(l, s);\n    int segment_begin_idx = segment_end_idx - 1;\n\n    double s_on_segment =\n        (s - l.s_.at(segment_begin_idx)) /\n        (l.s_.at(segment_end_idx) - l.s_.at(segment_begin_idx));\n    double interp_pt_x =\n        bg::get<0>(l.obj_.at(segment_begin_idx)) +\n        s_on_segment * (bg::get<0>(l.obj_.at(segment_end_idx)) -\n                        bg::get<0>(l.obj_.at(segment_begin_idx)));\n    double interp_pt_y =\n        bg::get<1>(l.obj_.at(segment_begin_idx)) +\n        s_on_segment * (bg::get<1>(l.obj_.at(segment_end_idx)) -\n                        bg::get<1>(l.obj_.at(segment_begin_idx)));\n    return Point2d(interp_pt_x, interp_pt_y);\n  }\n}\n\ninline double GetTangentAngleAtS(Line l, double s) {\n  if (s >= l.s_.back()) {\n    Point2d p1 = l.obj_.at(l.obj_.size() - 2);\n    Point2d p2 = l.obj_.at(l.obj_.size() - 1);\n    double angle =\n        atan2(bg::get<1>(p2) - bg::get<1>(p1), bg::get<0>(p2) - bg::get<0>(p1));\n    return angle;\n  } else if (s <= 0.0) {\n    Point2d p1 = l.obj_.at(0);\n    Point2d p2 = l.obj_.at(1);\n    return atan2(bg::get<1>(p2) - bg::get<1>(p1),\n                 bg::get<0>(p2) - bg::get<0>(p1));\n  } else {  // not start or end\n    int end_segment_it = GetSegmentEndIdx(l, s);\n    // check if s is at intersection, if true then calculate the angle\n    if (CheckSForSegmentIntersection(l, s)) {\n      Point2d p1 = l.obj_.at(end_segment_it - 2);\n      Point2d p2 = l.obj_.at(end_segment_it - 1);\n      Point2d p3 = l.obj_.at(end_segment_it);\n      double sin_mean = 0.5 * (sin(atan2(bg::get<1>(p2) - bg::get<1>(p1),\n                                         bg::get<0>(p2) - bg::get<0>(p1))) +\n                               sin(atan2(bg::get<1>(p3) - bg::get<1>(p2),\n                                         bg::get<0>(p3) - bg::get<0>(p2))));\n      double cos_mean = 0.5 * (cos(atan2(bg::get<1>(p2) - bg::get<1>(p1),\n                                         bg::get<0>(p2) - bg::get<0>(p1))) +\n                               cos(atan2(bg::get<1>(p3) - bg::get<1>(p2),\n                                         bg::get<0>(p3) - bg::get<0>(p2))));\n      return atan2(sin_mean, cos_mean);\n    } else {  // every s not start, end or intersection\n      Point2d p1 = l.obj_.at(end_segment_it - 1);\n      Point2d p2 = l.obj_.at(end_segment_it);\n      return atan2(bg::get<1>(p2) - bg::get<1>(p1),\n                   bg::get<0>(p2) - bg::get<0>(p1));\n    }\n  }\n}\n\ninline Point2d GetNormalAtS(const Line& l, double s) {\n  double tangent = GetTangentAngleAtS(l, s);\n  // rotate unit vector anti-clockwise with angle = tangent by 1/2 pi\n  Point2d t(cos(tangent + asin(1)), sin(tangent + asin(1)));\n  return t;\n}\n\ninline Line GetLineFromSInterval(const Line& line, double begin, double end) {\n  Line new_line;\n  new_line.AddPoint(GetPointAtS(line, begin));\n  std::vector<Point2d> points = line.GetPointsInSInterval(begin, end);\n  for (auto const& point : points) {\n    new_line.AddPoint(point);\n  }\n  new_line.AddPoint(GetPointAtS(line, end));\n  return new_line;\n}\n\ninline Line GetLineShiftedLaterally(const Line& line, double lateral_shift) {\n  Line new_line;\n  for (const auto& s : line.s_) {\n    const Point2d normal = GetNormalAtS(line, s);\n    const Point2d point_at_s = GetPointAtS(line, s);\n    const Point2d shifted = point_at_s + (normal * lateral_shift);\n    new_line.AddPoint(shifted);\n  }\n  return new_line;\n}\n\ninline std::tuple<Point2d, double, uint> GetNearestPointAndS(\n    const Line& l, const Point2d& p) {  // GetNearestPoint\n  // edge cases: empty or one-point line\n  if (l.obj_.empty()) {\n    return std::make_tuple(Point2d(0, 0), 0.0, 0);\n  } else if (l.obj_.size() == 1) {\n    return std::make_tuple(l.obj_.at(0), 0.0, 0);\n  }\n\n  // nominal case:\n  // check distance to each line segment and find closest segment\n  double min_dist = boost::numeric::bounds<double>::highest();\n  int min_segment_idx = 0;\n  for (uint line_idx = 0; line_idx < l.obj_.size() - 1; ++line_idx) {\n    bg::model::linestring<Point2d> current_segment;\n    bg::append(current_segment, l.obj_.at(line_idx));\n    bg::append(current_segment, l.obj_.at(line_idx + 1));\n    double d = bg::comparable_distance(current_segment, p);\n    if (d < min_dist) {\n      min_dist = d;\n      min_segment_idx = line_idx;\n    }\n  }\n\n  const double a1 = bg::get<0>(l.obj_.at(min_segment_idx));\n  const double a2 = bg::get<1>(l.obj_.at(min_segment_idx));\n  const double b1 = bg::get<0>(l.obj_.at(min_segment_idx + 1));\n  const double b2 = bg::get<1>(l.obj_.at(min_segment_idx + 1));\n  const double p1 = bg::get<0>(p);\n  const double p2 = bg::get<1>(p);\n\n  const double lambda = -(a1 * b1 + a2 * b2 + a1 * p1 + a2 * p2 - b1 * p1 -\n                          b2 * p2 - a1 * a1 - a2 * a2)  // NOLINT\n                        / (a1 * a1 - 2 * a1 * b1 + a2 * a2 - 2 * a2 * b2 +\n                           b1 * b1 + b2 * b2);  // NOLINT\n\n  // calculate interpolated s value\n  double s;\n  // double dist;  // unused\n  Point2d retval;\n\n  if (lambda < 0) {  // extrapolation front\n    s = l.s_.at(min_segment_idx);\n    retval = Point2d(a1, a2);\n    // debug\n    // dist = sqrt(pow(p1 - a1, 2) + pow(p2 - a2, 2));\n  } else if (lambda > 1) {  // extrapolation end\n    s = l.s_.at(min_segment_idx + 1);\n    retval = Point2d(b1, b2);\n    // debug\n    // dist = sqrt(pow(p1 - b1, 2) + pow(p2 - b2, 2));\n  } else {  // real interpolation\n    s = (1 - lambda) * l.s_.at(min_segment_idx) +\n        lambda * l.s_.at(min_segment_idx + 1);  // NOLINT\n\n    const double s1 =\n        (p1 * a1 * a1 - a1 * a2 * b2 + p2 * a1 * a2 - 2 * p1 * a1 * b1 +\n         a1 * b2 * b2 - p2 * a1 * b2 + a2 * a2 * b1 - a2 * b1 * b2 -\n         p2 * a2 * b1 + p1 * b1 * b1 + p2 * b1 * b2)  // NOLINT\n        / (a1 * a1 - 2 * a1 * b1 + a2 * a2 - 2 * a2 * b2 + b1 * b1 +\n           b2 * b2);  // NOLINT\n    const double s2 =\n        (a1 * a1 * b2 - a1 * a2 * b1 + p1 * a1 * a2 - a1 * b1 * b2 -\n         p1 * a1 * b2 + p2 * a2 * a2 + a2 * b1 * b1 - p1 * a2 * b1 -\n         2 * p2 * a2 * b2 + p1 * b1 * b2 + p2 * b2 * b2)  // NOLINT\n        / (a1 * a1 - 2 * a1 * b1 + a2 * a2 - 2 * a2 * b2 + b1 * b1 +\n           b2 * b2);  // NOLINT\n\n    // debug\n    // dist = sqrt(pow(p1 - s1, 2) + pow(p2 - s2, 2));\n    retval = Point2d(s1, s2);\n  }\n\n  // debug\n  // const double dist_boost = bg::distance(l.obj_, p);\n\n  // return\n  return std::make_tuple(retval, s, min_segment_idx);\n}\ninline Point2d GetNearestPoint(const Line& l, const Point2d& p) {\n  return std::get<0>(GetNearestPointAndS(l, p));\n}\ninline double GetNearestS(const Line& l, const Point2d& p) {\n  return std::get<1>(GetNearestPointAndS(l, p));\n}\ninline uint FindNearestIdx(const Line& l, const Point2d& p) {\n  return std::get<2>(GetNearestPointAndS(l, p));\n}\n//! Point - Line collision checker using boost::intersection\ninline bool Collide(const Line& l, const LinePoint& p) {\n  std::vector<LinePoint> shape_intersect;\n  bg::intersection(l.obj_, p, shape_intersect);\n  return !shape_intersect.empty();\n}\n\n//! Line - Point collision checker\ninline bool Collide(const LinePoint& p, const Line& l) { return Collide(l, p); }\n\n//! Line - Line collision checker using boost::intersection\ninline bool Collide(const Line& l1, const Line& l2) {\n  std::vector<bg::model::linestring<LinePoint>> shape_intersect;\n  bg::intersection(l1.obj_, l2.obj_, shape_intersect);\n  return !shape_intersect.empty();\n}\n\n// An oriented point can have a linestring (the nearest point on it)\n// on the left or right side, left side < 0, right side > 0\ninline double SignedDistance(const Line& line, const Point2d& p,\n                             const double& orientation) {\n  auto closest_point = GetNearestPoint(line, p);\n  auto direction_vector = closest_point - p;\n\n  double diff = SignedAngleDiff(\n      orientation,\n      atan2(bg::get<1>(direction_vector), bg::get<0>(direction_vector)));\n  double sign = (diff > 0) ? 1 : ((diff < 0) ? -1 : 0);\n\n  return bg::distance(line.obj_, p) * sign;\n}\n\ninline Line AppendLinesNoIntersect(const Line& ls1, const Line& ls2) {\n  std::vector<Point2d> intersecting_points;\n  bg::intersection(ls1.obj_, ls2.obj_, intersecting_points);\n  Line lout;\n  if (intersecting_points.size() == 1) {\n    // get s value for both lines\n    double s_i1 = GetNearestS(ls1, intersecting_points.at(0));\n    double s_i2 = GetNearestS(ls2, intersecting_points.at(0));\n    double rel_s_i1 = s_i1 / ls1.Length();\n    double rel_s_i2 = s_i2 / ls2.Length();\n\n    Line ls1_part, ls2_part;\n    if (rel_s_i1 < 0.3) {\n      // take latter part of line\n      ls1_part = GetLineFromSInterval(ls1, s_i1, ls1.Length());\n    } else if (rel_s_i1 > 0.7) {\n      // take front part of line\n      ls1_part = GetLineFromSInterval(ls1, 0, s_i1);\n    } else {\n      LOG(WARNING) << \"Lines intersecting too much, only appending\";\n      ls1_part = ls1;\n    }\n\n    if (rel_s_i2 < 0.3) {\n      // take latter part of line\n      ls2_part = GetLineFromSInterval(ls2, s_i2, ls2.Length());\n    } else if (rel_s_i2 > 0.7) {\n      // take front part of line\n      ls2_part = GetLineFromSInterval(ls2, 0, s_i2);\n    } else {\n      LOG(WARNING) << \"Lines intersecting too much, only appending\";\n      ls2_part = ls2;\n    }\n\n    lout = ls1_part;\n    lout.AppendLinestring(ls2_part);\n  } else if (intersecting_points.size() > 1) {\n    // do something\n    LOG(ERROR) << \"two intersecting points\";\n    lout = ls1;\n    lout.AppendLinestring(ls2);\n  } else {\n    lout = ls1;\n    lout.AppendLinestring(ls2);\n  }\n\n  lout.RemoveDuplicates();\n\n  if (boost::geometry::intersects(lout.obj_)) {\n    const double tol = 1e-6;\n    LOG(WARNING) << \"AppendLinesNoIntersect yields self intersecting line, \"\n                    \"will simplify it with \"\n                 << tol;\n    VLOG(5) << \"ls1: \" << ls1.ToArray();\n    VLOG(5) << \"ls2: \" << ls2.ToArray();\n    VLOG(5) << \"lout: \" << lout.ToArray();\n\n    lout = Simplify(lout, tol);\n  }\n  return lout;\n}\n\ninline Line ConcatenateLinestring(const Line& ls1, const Line& ls2) {\n  // Get first and last points\n  auto first_point_this = *ls1.begin();\n  auto last_point_this = *(ls1.end() - 1);\n  auto first_point_other = *ls2.begin();\n  auto last_point_other = *(ls2.end() - 1);\n\n  double d_first_first = Distance(first_point_this, first_point_other);\n  double d_first_last = Distance(first_point_this, last_point_other);\n  double d_last_first = Distance(last_point_this, first_point_other);\n  double d_last_last = Distance(last_point_this, last_point_other);\n\n  Line lconcat;\n  if (d_first_first <= std::min({d_first_last, d_last_first, d_last_last})) {\n    // Reverse this\n    lconcat = AppendLinesNoIntersect(Reverse(ls1), ls2);\n  } else if (d_first_last <=\n             std::min({d_first_first, d_last_first, d_last_last})) {\n    // Reverse both\n    lconcat = AppendLinesNoIntersect(Reverse(ls1), Reverse(ls2));\n  } else if (d_last_first <=\n             std::min({d_first_first, d_first_last, d_last_last})) {\n    // No reversing\n    lconcat = AppendLinesNoIntersect(ls1, ls2);\n  } else {\n    // Reverse other\n    lconcat = AppendLinesNoIntersect(ls1, Reverse(ls2));\n  }\n  return lconcat;\n}\n\n// Subsampling using spline\ninline Line SmoothLine(const Line& l, const double ds) {\n  if (l.size() < 3) {\n    LOG(WARNING) << \"cannot subsample line with only 3 points\";\n    return l;\n  } else {\n    int num_points = l.Length() / ds;\n\n    tk::spline splineX, splineY;\n    std::vector<double> xVec, yVec;\n    for (size_t i = 0; i < l.obj_.size(); i++) {\n      xVec.push_back(bg::get<0>(l.obj_[i]));\n      yVec.push_back(bg::get<1>(l.obj_[i]));\n    }\n    std::vector<double> sVec(l.s_.begin(), l.s_.end());\n    splineX.set_points(sVec, xVec);\n    splineY.set_points(sVec, yVec);\n\n    Line lss;\n    for (size_t j = 0; j <= num_points; ++j) {\n      double x = splineX(j * ds);\n      double y = splineY(j * ds);\n      lss.AddPoint(geometry::Point2d(x, y));\n    }\n    if (l.Length() > num_points * ds) {\n      lss.AddPoint(l.obj_.at(l.size() - 1));\n    }\n    return lss;\n  }\n}\n\ninline Line ComputeCenterLine(const Line& outer_line, const Line& inner_line) {\n  if (boost::geometry::intersects(outer_line.obj_)) {\n    LOG(WARNING) << \"Computing center line, but outer line self-intersects\";\n  }\n  if (boost::geometry::intersects(inner_line.obj_)) {\n    LOG(WARNING) << \"Computing center line, but inner line self-intersects\";\n  }\n\n  Line center_line_;\n  Line line_more_points = outer_line;\n  Line line_less_points = inner_line;\n  if (inner_line.obj_.size() > outer_line.obj_.size()) {\n    line_more_points = inner_line;\n    line_less_points = outer_line;\n  }\n  for (Point2d& point_loop : line_more_points.obj_) {\n    Point2d nearest_point_other =\n        geometry::GetNearestPoint(line_less_points, point_loop);\n    geometry::Point2d middle_point = (point_loop + nearest_point_other) / 2;\n    center_line_.AddPoint(middle_point);\n  }\n  return center_line_;\n}\n\ntemplate <typename T>\nstd::pair<T, T> MergeBoundingBoxes(std::pair<T, T> bb1, std::pair<T, T> bb2) {\n  Line_t<T> line;  // just use a line and add all points\n  line.AddPoint(bb1.first);\n  line.AddPoint(bb1.second);\n  line.AddPoint(bb2.first);\n  line.AddPoint(bb2.second);\n  return line.BoundingBox();\n}\n\n}  // namespace geometry\n}  // namespace bark\n\n#endif  // BARK_GEOMETRY_LINE_HPP_\n", "meta": {"hexsha": "babb685006747afa9227a0df5381fb0589554b78", "size": 22314, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bark/geometry/line.hpp", "max_stars_repo_name": "xmyqsh/bark", "max_stars_repo_head_hexsha": "452bf2360bcd8c84cbb11c4b56e6e9b8473eb969", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 174.0, "max_stars_repo_stars_event_min_datetime": "2019-04-03T11:37:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T09:14:38.000Z", "max_issues_repo_path": "bark/geometry/line.hpp", "max_issues_repo_name": "xmyqsh/bark", "max_issues_repo_head_hexsha": "452bf2360bcd8c84cbb11c4b56e6e9b8473eb969", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 192.0, "max_issues_repo_issues_event_min_datetime": "2019-04-05T09:41:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T14:14:28.000Z", "max_forks_repo_path": "bark/geometry/line.hpp", "max_forks_repo_name": "xmyqsh/bark", "max_forks_repo_head_hexsha": "452bf2360bcd8c84cbb11c4b56e6e9b8473eb969", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 55.0, "max_forks_repo_forks_event_min_datetime": "2019-04-05T13:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T07:03:41.000Z", "avg_line_length": 33.4542728636, "max_line_length": 87, "alphanum_fraction": 0.6270054674, "num_tokens": 6800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24613408273759835}}
{"text": "#include <boost/function_output_iterator.hpp>\n#include <boost/geometry/geometry.hpp>\n#include <chrono>\n#include <iostream>\n#include <random>\n#include <vector>\n#include <string>\n#include <fstream>\n\n// using cxxopts for CLI argument parsing\n#include \"packages/cxxopts.hpp\"\n\n// using prakhar1989's ProgressBar for CLI progress indicator\n#include \"packages/ProgressBar.hpp\"\n\n// using tinyobjloader for OBJ file parsing\n#define TINYOBJLOADER_IMPLEMENTATION\n#define EPSILON 0.00000001\n#include \"packages/tiny_obj_loader.h\"\n\nusing namespace std;\n\n// full 3D model to inhibit growth\nstring fullModelFilename = \"\";\ntinyobj::attrib_t fullModelAttrib;\nvector<tinyobj::shape_t> fullModelShapes;\nvector<tinyobj::material_t> fullModelMaterials;\n\n// 3D model of selected faces to seed growth\nstring seedModelFilename = \"\";\ntinyobj::attrib_t seedModelAttrib;\nvector<tinyobj::shape_t> seedModelShapes;\nvector<tinyobj::material_t> seedModelMaterials;\n\n// number of particles\nconst int DefaultNumberOfParticles = 1000000;\nint numParticles = DefaultNumberOfParticles;\n\n// progress bar\nProgressBar progressBar(numParticles, 40);\n\n// output file\nstring filename = \"points\";\nofstream file;\n\n// interval (in iterations) that point data is outputted\nint lastOutputIteration = 0;\nint interval = numParticles;\n\n// number of dimensions (must be 2 or 3)\nconst int D = 3;\n\n// default parameters (documented below)\nconst double DefaultParticleSpacing = 1;\nconst double DefaultAttractionDistance = 3;\nconst double DefaultMinMoveDistance = 1;\nconst int DefaultStubbornness = 0;\nconst double DefaultStickiness = 1;\nconst double DefaultBoundingRadius = 0;\n\n// boost is used for its spatial index\nusing BoostPoint = boost::geometry::model::point<double, D, boost::geometry::cs::cartesian>;\nusing IndexValue = pair<BoostPoint, int>;\nusing Index = boost::geometry::index::rtree<IndexValue, boost::geometry::index::linear<4>>;\n\n// Vector represents a point or a vector\nclass Vector {\npublic:\n    Vector() :\n        m_X(0), m_Y(0), m_Z(0) {}\n\n    Vector(double x, double y) :\n        m_X(x), m_Y(y), m_Z(0) {}\n\n    Vector(double x, double y, double z) :\n        m_X(x), m_Y(y), m_Z(z) {}\n\n    double X() const {\n        return m_X;\n    }\n\n    double Y() const {\n        return m_Y;\n    }\n\n    double Z() const {\n        return m_Z;\n    }\n\n    BoostPoint ToBoost() const {\n        return BoostPoint(m_X, m_Y, m_Z);\n    }\n\n    double Length() const {\n        return sqrt(m_X * m_X + m_Y * m_Y + m_Z * m_Z);\n    }\n\n    double LengthSquared() const {\n        return m_X * m_X + m_Y * m_Y + m_Z * m_Z;\n    }\n\n    double Distance(const Vector &v) const {\n        const double dx = m_X - v.m_X;\n        const double dy = m_Y - v.m_Y;\n        const double dz = m_Z - v.m_Z;\n        return sqrt(dx * dx + dy * dy + dz * dz);\n    }\n\n    Vector Normalized() const {\n        const double m = 1 / Length();\n        return Vector(m_X * m, m_Y * m, m_Z * m);\n    }\n\n    Vector GetCrossed(const Vector &v) const {\n        return Vector(m_Y * v.m_Z - m_Z * v.m_Y, \n                      m_Z * v.m_X - m_X * v.m_Z,\n                      m_X * v.m_Y - m_Y * v.m_X);\n    }\n\n    double GetDot(const Vector &v) const {\n        return m_X * v.m_X +\n               m_Y * v.m_Y +\n               m_Z * v.m_Z;\n    }\n\n    Vector operator+(const Vector &v) const {\n        return Vector(m_X + v.m_X, m_Y + v.m_Y, m_Z + v.m_Z);\n    }\n\n    Vector operator-(const Vector &v) const {\n        return Vector(m_X - v.m_X, m_Y - v.m_Y, m_Z - v.m_Z);\n    }\n\n    Vector operator*(const double a) const {\n        return Vector(m_X * a, m_Y * a, m_Z * a);\n    }\n\n    Vector &operator+=(const Vector &v) {\n        m_X += v.m_X; m_Y += v.m_Y; m_Z += v.m_Z;\n        return *this;\n    }\n\n    bool operator==(const Vector &v) const {\n        return m_X == v.m_X && m_Y == v.m_Y && m_Z == v.m_Z;\n    }\n\nprivate:\n    double m_X;\n    double m_Y;\n    double m_Z;\n};\n\n// Lerp linearly interpolates from a to b by distance.\nVector Lerp(const Vector &a, const Vector &b, const double d) {\n    return a + (b - a).Normalized() * d;\n}\n\n// Random returns a uniformly distributed random number between lo and hi\ndouble Random(const double lo = 0, const double hi = 1) {\n    static thread_local mt19937 gen(chrono::high_resolution_clock::now().time_since_epoch().count());\n    uniform_real_distribution<double> dist(lo, hi);\n    return dist(gen);\n}\n\n// RandomInUnitSphere returns a random, uniformly distributed point inside the\n// unit sphere (radius = 1)\nVector RandomInUnitSphere() {\n    while (true) {\n        const Vector p = Vector(\n            Random(-1, 1),\n            Random(-1, 1),\n            D == 2 ? 0 : Random(-1, 1));\n        if (p.LengthSquared() < 1) {\n            return p;\n        }\n    }\n}\n\n// IsIntersectingFace checks for intersection of a ray (O) with random direction (D) and a triangle face defined by vertices V1, V2, and V3\n// Adapted from Amnon Owed's ofxPointInMesh::triangleIntersection: https://github.com/AmnonOwed/ofxPointInMesh\n// Uses Möller–Trumbore: http://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm\nbool IsIntersectingFace(const Vector &V1, const Vector &V2, const Vector &V3, const Vector &O, const Vector &D, Vector &R) {\n\tVector e1, e2; // Edge1, Edge2\n\tVector P, Q, T;\n\tfloat det, inv_det, u, v;\n\tfloat t;\n\n\t// Find vectors for two edges sharing V1\n\te1 = V2 - V1;\n\te2 = V3 - V1;\n\n\t// Begin calculating determinant - also used to calculate u parameter\n\tP = D.GetCrossed(e2);\n\n\t// if determinant is near zero, ray lies in plane of triangle\n\tdet = e1.GetDot(P);\n\n\t// NOT CULLING\n\tif(det > -EPSILON && det < EPSILON){\n\t\treturn false;\n\t}\n\n\tinv_det = 1.f / det;\n\n\t// calculate distance from V1 to ray origin\n\tT = O - V1;\n\n\t// calculate u parameter and test bound\n\tu = T.GetDot(P) * inv_det;\n\n\t// the intersection lies outside of the triangle\n\tif(u < 0.f || u > 1.f){\n\t\treturn false;\n\t}\n\n\t// prepare to test v parameter\n\tQ = T.GetCrossed(e1);\n\n\t// calculate V parameter and test bound\n\tv = D.GetDot(Q) * inv_det;\n\n\t// the intersection lies outside of the triangle\n\tif(v < 0.f || u + v  > 1.f){\n\t\treturn false;\n\t}\n\n\tt = e2.GetDot(Q) * inv_det;\n\n\tif(t > EPSILON){ // ray intersection\n\t\tR = O + D * t; // store intersection point\n\t\treturn true;\n\t}\n\n\t// no hit, no win\n\treturn false;\n}\n\n// IsInsideMesh determines if a given point is inside of the base model mesh\n// Adapted from Amnon Owed's ofxPointInMesh::isInside: https://github.com/AmnonOwed/ofxPointInMesh\nbool IsInsideMesh(Vector &p) {\n    // if no mesh was provided, skip this test\n    if(fullModelFilename.empty()) {\n        return false;\n    }\n\n    Vector foundIntersection; // variable to store a single found intersection\n\tvector<Vector> results;  // vector to store all found intersections\n\tVector randomDirection = Vector(0.1, 0.2, 0.3); // a random direction\n\n    // go over all the shapes in the mesh\n    for (size_t s = 0; s < fullModelShapes.size(); s++) {\n        size_t index_offset = 0;\n\n        // go over all the faces in the shape\n        for (size_t f = 0; f < fullModelShapes[s].mesh.num_face_vertices.size(); f++) {\n            unsigned int fv = fullModelShapes[s].mesh.num_face_vertices[f];\n            vector<Vector> vertices;\n\n            // collect the vertices\n            for (size_t v = 0; v < fv; v++) {\n                tinyobj::index_t idx = fullModelShapes[s].mesh.indices[index_offset + v];\n                tinyobj::real_t vx = fullModelAttrib.vertices[3*idx.vertex_index+0];\n                tinyobj::real_t vy = fullModelAttrib.vertices[3*idx.vertex_index+1];\n                tinyobj::real_t vz = fullModelAttrib.vertices[3*idx.vertex_index+2];\n                vertices.push_back(Vector(vx, vy, vz));\n            }\n\n            index_offset += fv;\n\n            // do a triangle-ray intersection on each face in the mesh\n            // store the intersection (if any) in the variable foundIntersection\n            if(IsIntersectingFace(vertices[0], vertices[1], vertices[2], p, randomDirection, foundIntersection)) {\n                // store all found intersections\n                results.push_back(foundIntersection);\n            }\n        }\n    }\n\n    // handle multiple mesh intersections at the same point (by removing duplicates)\n    vector<Vector> unique_results;\n    unique_copy(results.begin(), results.end(), back_inserter(unique_results));\n\n    // // determine if the point is inside or outside the mesh, based on the number of unique intersections\n    if(unique_results.size() % 2 == 1) {\n        return true;\n    } else {\n        return false;\n    }\n}\n\n// GetDot2 calculates the dot product of a vector with itself\ndouble GetDot2(const Vector &p) {\n    return p.GetDot(p);\n}\n\n// GetSign returns -1 for negative numbers, 1 for positive numbers, and 0 for 0\nint GetSign(const double &v) {\n    int result = 0;\n    if(v < 0) {\n        result = -1;\n    } else if(v > 0) {\n        result = 1;\n    }\n    return result;\n}\n\n// clamp ensures that a value (x) is within the range defined by [lower] and [upper]\ndouble clamp(double x, double lower, double upper) {\n    return min(upper, max(x, lower));\n}\n\n// DistanceToTriangle calculates the shortest distance between a point (p) and a 3D triangle defined by vertices v1, v2, and v3\n// Adapted from: https://iquilezles.org/www/articles/triangledistance/triangledistance.htm\ndouble DistanceToTriangle(const Vector &v1, const Vector &v2, const Vector &v3, const Vector &p) {\n    Vector v21 = v2 - v1;\n    Vector v32 = v3 - v2;\n    Vector v13 = v1 - v3;\n    Vector p1 = p - v1;\n    Vector p2 = p - v2;\n    Vector p3 = p - p3;\n    Vector nor = v21.GetCrossed(v13);\n\n    return sqrt(\n        // inside/outside test\n        (GetSign(p1.GetDot(v21.GetCrossed(nor))) +\n         GetSign(p2.GetDot(v32.GetCrossed(nor))) +\n         GetSign(p3.GetDot(v13.GetCrossed(nor))) < 2.0)\n        ?\n        // 3 edges\n        min( \n            min( \n                GetDot2(v21 * clamp(p1.GetDot(v21) / GetDot2(v21), 0.0, 1.0) - p1),\n                GetDot2(v32 * clamp(p2.GetDot(v32) / GetDot2(v32), 0.0, 1.0) - p2)\n            ),\n            GetDot2(v13 * clamp(p3.GetDot(v13) / GetDot2(v13), 0.0, 1.0) - p3)\n        )\n        :\n        // 1 face\n        p1.GetDot(nor) * p1.GetDot(nor) / GetDot2(nor)\n    );\n}\n\n// Model holds all of the particles and defines their behavior.\nclass Model {\npublic:\n    Model() :\n        m_ParticleSpacing(DefaultParticleSpacing),\n        m_AttractionDistance(DefaultAttractionDistance),\n        m_MinMoveDistance(DefaultMinMoveDistance),\n        m_Stubbornness(DefaultStubbornness),\n        m_Stickiness(DefaultStickiness),\n        m_BoundingRadius(DefaultBoundingRadius) {}\n\n    void SetParticleSpacing(const double a) {\n        m_ParticleSpacing = a;\n    }\n\n    void SetAttractionDistance(const double a) {\n        m_AttractionDistance = a;\n    }\n\n    void SetMinMoveDistance(const double a) {\n        m_MinMoveDistance = a;\n    }\n\n    void SetStubbornness(const int a) {\n        m_Stubbornness = a;\n    }\n\n    void SetStickiness(const double a) {\n        m_Stickiness = a;\n    }\n\n    void SetBoundingRadius(const double a) {\n        m_BoundingRadius = a;\n    }\n\n    // Add adds a new particle with the specified parent particle\n    void Add(const Vector &p, const int parent = -1) {\n        const int id = m_Points.size();\n        m_Index.insert(make_pair(p.ToBoost(), id));\n        m_Points.push_back(p);\n        m_Parents.push_back(parent);\n        m_JoinAttempts.push_back(0);\n        m_BoundingRadius = max(m_BoundingRadius, p.Length() + m_AttractionDistance);\n\n        // update and display progress bar\n        ++progressBar;\n        progressBar.display();\n\n        // wrap up the progress bar when last particle is placed\n        if(id == numParticles) {\n            progressBar.done();\n        }\n    }\n\n    // Nearest returns the index of the particle nearest the specified point\n    int Nearest(const Vector &point) const {\n        int result = -1;\n        m_Index.query(\n            boost::geometry::index::nearest(point.ToBoost(), 1),\n            boost::make_function_output_iterator([&result](const auto &value) {\n                result = value.second;\n            }));\n        return result;\n    }\n\n    // DistanceToNearestFace calculates the shortest distance from a particle (p) and \n    // TODO: if needed, consider putting mesh vertices in spatial index, then doing knn search search within radius defined by largest edge found in mesh (precomputed)\n    double DistanceToNearestFace(const Vector &p) {\n        double distance = m_AttractionDistance;\n\n        // go over all the shapes in the mesh\n        for (size_t s = 0; s < seedModelShapes.size(); s++) {\n            size_t index_offset = 0;\n\n            // go over all the faces in the shape\n            for (size_t f = 0; f < seedModelShapes[s].mesh.num_face_vertices.size(); f++) {\n                unsigned int fv = seedModelShapes[s].mesh.num_face_vertices[f];\n                vector<Vector> vertices;\n\n                // collect the vertices\n                for (size_t v = 0; v < fv; v++) {\n                    tinyobj::index_t idx = seedModelShapes[s].mesh.indices[index_offset + v];\n                    tinyobj::real_t vx = seedModelAttrib.vertices[3*idx.vertex_index+0];\n                    tinyobj::real_t vy = seedModelAttrib.vertices[3*idx.vertex_index+1];\n                    tinyobj::real_t vz = seedModelAttrib.vertices[3*idx.vertex_index+2];\n                    vertices.push_back(Vector(vx, vy, vz));\n                }\n\n                index_offset += fv;\n\n                // calculate distance from point to face\n                distance = min(distance, DistanceToTriangle(vertices[0], vertices[1], vertices[2], p));\n            }\n        }\n\n        return distance;\n    }\n\n    // RandomStartingPosition returns a random point to start a new particle\n    Vector RandomStartingPosition() const {\n        const double d = m_BoundingRadius;\n        return RandomInUnitSphere().Normalized() * d;\n    }\n\n    // ShouldReset returns true if the particle has gone too far away and\n    // should be reset to a new random starting position\n    bool ShouldReset(const Vector &p) const {\n        return p.Length() > m_BoundingRadius * 2;\n    }\n\n    // ShouldJoin returns true if the point should attach to the specified\n    // parent particle. This is only called when the point is already within\n    // the required attraction distance.\n    bool ShouldJoin(const Vector &p, const int parent) {\n        m_JoinAttempts[parent]++;\n        if (m_JoinAttempts[parent] < m_Stubbornness) {\n            return false;\n        }\n        return Random() <= m_Stickiness;\n    }\n\n    // PlaceParticle computes the final placement of the particle.\n    Vector PlaceParticle(const Vector &p, const int parent) const {\n        return Lerp(m_Points[parent], p, m_ParticleSpacing);\n    }\n\n    // MotionVector returns a vector specifying the direction that the\n    // particle should move for one iteration. The distance that it will move\n    // is determined by the algorithm.\n    Vector MotionVector(const Vector &p) const {\n        return RandomInUnitSphere();\n    }\n\n    // AddParticle diffuses one new particle and adds it to the model\n    void AddParticle() {\n        // compute particle starting location\n        Vector p = RandomStartingPosition();\n\n        // do the random walk\n        while (true) {\n            // get distance to nearest other particle\n            const int parent = Nearest(p);\n            const double d = p.Distance(m_Points[parent]);\n\n            // do not allow particle to stick when its inside of the base model mesh\n            if(!IsInsideMesh(p)) {\n                // check for particle-particle collisions\n                if (d < m_AttractionDistance) {\n                    if (!ShouldJoin(p, parent)) {\n                        // push particle away a bit\n                        p = Lerp(m_Points[parent], p, m_AttractionDistance + m_MinMoveDistance);\n                        continue;\n                    }\n\n                    // adjust particle position in relation to its parent\n                    p = PlaceParticle(p, parent);\n\n                    // add the point\n                    Add(p);\n                    return;\n                }\n\n                // get distance to the nearest seed face\n                const double df = DistanceToNearestFace(p);\n\n                // check for particle-face collisions\n                if (df < m_AttractionDistance) {\n                    Add(p, -1);\n                    return;\n                }\n            }\n\n            // move randomly\n            const double m = max(m_MinMoveDistance, d - m_AttractionDistance);\n            p += MotionVector(p).Normalized() * m;\n\n            // check if particle is too far away, reset if so\n            if (ShouldReset(p)) {\n                p = RandomStartingPosition();\n            }\n        }\n    }\n\n    // OutputPointData creates a new point data file and fills it with most current point data\n    void OutputPointData(const int iteration) const {\n        file.open(\"data/\" + filename + \"-\" + to_string(iteration) + \".csv\");\n\n        for(unsigned int id = 0; id < m_Points.size(); id++) {\n            file << id << \",\" << m_Parents[id] << \",\" << m_Points[id].X() << \",\" << m_Points[id].Y() << \",\" << m_Points[id].Z() << endl;\n        }\n\n        file.close();\n    }\n\nprivate:\n    // m_ParticleSpacing defines the distance between particles that are\n    // joined together\n    double m_ParticleSpacing;\n\n    // m_AttractionDistance defines how close together particles must be in\n    // order to join together\n    double m_AttractionDistance;\n\n    // m_MinMoveDistance defines the minimum distance that a particle will move\n    // during its random walk\n    double m_MinMoveDistance;\n\n    // m_Stubbornness defines how many interactions must occur before a\n    // particle will allow another particle to join to it.\n    int m_Stubbornness;\n\n    // m_Stickiness defines the probability that a particle will allow another\n    // particle to join to it.\n    double m_Stickiness;\n\n    // m_BoundingRadius defines the radius of the bounding sphere that bounds\n    // all of the particles\n    double m_BoundingRadius;\n\n    // m_Points stores the final particle positions\n    vector<Vector> m_Points;\n\n    // m_Parents stores the parent IDs of each clustered particle\n    vector<int> m_Parents;\n\n    // m_JoinAttempts tracks how many times other particles have attempted to\n    // join with each finalized particle\n    vector<int> m_JoinAttempts;\n\n    // m_Index is the spatial index used to accelerate nearest neighbor queries\n    Index m_Index;\n};\n\n\n// create the model in global scope so that parseArgs can configure it\nModel model;\n\n\n// Parses CLI arguments and configures simulation with what is passed\nvoid ParseArgs(int argc, char* argv[]) {\n    try {\n        cxxopts::Options options(argv[0]);\n\n        options\n        .allow_unrecognised_options()\n        .add_options()\n            (\"p,particles\", \"Number of walker particles\", cxxopts::value<int>())\n            (\"i,input\", \"Full 3D model filename (.obj)\", cxxopts::value<string>())\n            (\"f,faces\", \"Seed faces 3D model filename (.obj)\", cxxopts::value<string>())\n            (\"o,output\", \"Point data output filename\", cxxopts::value<string>())\n            (\"n,interval\", \"Point data capture interval\", cxxopts::value<int>())\n            (\"s,spacing\", \"Particle spacing\", cxxopts::value<double>())\n            (\"a,attraction\", \"Attraction distance\", cxxopts::value<double>())\n            (\"m,move\", \"Minimum move distance\", cxxopts::value<double>())\n            (\"b,stubbornness\", \"Stubbornness\", cxxopts::value<int>())\n            (\"k,stickiness\", \"Stickiness\", cxxopts::value<double>())\n            (\"r,radius\", \"Initial bounding radius\", cxxopts::value<double>())\n        ;\n\n        auto result = options.parse(argc, argv);\n\n        if(result.count(\"particles\")) {\n            numParticles = result[\"particles\"].as<int>();\n            interval = numParticles;\n            progressBar.setTotal(numParticles);\n        }\n\n        if(result.count(\"input\")) {\n            fullModelFilename = result[\"input\"].as<string>();\n            \n            // throw error when filename doesn't end in `.obj`\n            if(fullModelFilename.substr(fullModelFilename.length() - 4, fullModelFilename.length() - 1).compare(\".obj\") != 0) {\n                cerr << \"Base model file must be an OBJ file\" << endl;\n                exit(1);\n            }\n        }\n\n        if(result.count(\"faces\")) {\n            seedModelFilename = result[\"faces\"].as<string>();\n            \n            // throw error when filename doesn't end in `.obj`\n            if(seedModelFilename.substr(seedModelFilename.length() - 4, seedModelFilename.length() - 1).compare(\".obj\") != 0) {\n                cerr << \"Seed model file must be an OBJ file\" << endl;\n                exit(1);\n            }\n        }\n\n        if(result.count(\"output\")) {\n            filename = result[\"output\"].as<string>();\n        }\n\n        if(result.count(\"interval\")) {\n            interval = result[\"interval\"].as<int>();\n        }\n        \n        if(result.count(\"spacing\")) {\n            model.SetParticleSpacing(result[\"spacing\"].as<double>());\n        }\n\n        if(result.count(\"attraction\")) {\n            model.SetAttractionDistance(result[\"attraction\"].as<double>());\n        }\n\n        if(result.count(\"move\")) {\n            model.SetMinMoveDistance(result[\"move\"].as<double>());\n        }\n\n        if(result.count(\"stubbornness\")) {\n            model.SetStubbornness(result[\"stubbornness\"].as<int>());\n        }\n\n        if(result.count(\"stickiness\")) {\n            model.SetStickiness(result[\"stickiness\"].as<double>());\n        }\n\n        if(result.count(\"radius\")) {\n            model.SetBoundingRadius(result[\"radius\"].as<double>());\n        }\n    } catch(const cxxopts::OptionException& e) {\n        cout << \"Error parsing options: \" << e.what() << endl;\n        exit(1);\n    }\n}\n\n// LoadFullModel loads the 3D model passed with the `-i` option\nvoid LoadFullModel() {\n    string warn;\n    string err;\n\n    bool ret = tinyobj::LoadObj(&fullModelAttrib, &fullModelShapes, &fullModelMaterials, &warn, &err, fullModelFilename.c_str());\n\n    if (!warn.empty()) {\n        cout << warn << endl;\n    }\n\n    if (!err.empty()) {\n        cerr << err << endl;\n    }\n\n    if (!ret) {\n        exit(1);\n    }\n}\n\n// LoadSeedModel loads the 3D model passed with the `-f` option\nvoid LoadSeedModel() {\n    string warn;\n    string err;\n\n    bool ret = tinyobj::LoadObj(&seedModelAttrib, &seedModelShapes, &seedModelMaterials, &warn, &err, seedModelFilename.c_str());\n\n    if (!warn.empty()) {\n        cout << warn << endl;\n    }\n\n    if (!err.empty()) {\n        cerr << err << endl;\n    }\n\n    if (!ret) {\n        exit(1);\n    }\n}\n\nint main(int argc, char* argv[]) {\n    // parse the CLI arguments\n    ParseArgs(argc, argv);\n\n    // load the full 3D model for inhibiting growth\n    if(!fullModelFilename.empty()) {\n        LoadFullModel();\n    }\n\n    // load the seed faces 3D model\n    if(!seedModelFilename.empty()) {\n        LoadSeedModel();\n    }\n\n    // add seed point at origin (a single point is necessary for now)\n    model.Add(Vector());\n\n    // {\n    //     const int n = 3600;\n    //     const double r = 1000;\n    //     for (int i = 0; i < n; i++) {\n    //         const double t = (double)i / n;\n    //         const double a = t * 2 * M_PI;\n    //         const double x = cos(a) * r;\n    //         const double y = sin(a) * r;\n    //         model.Add(Vector(x, y, 0));\n    //     }\n    // }\n\n    // run diffusion-limited aggregation\n    for (int i = 1; i <= numParticles; i++) {\n        model.AddParticle();\n        \n        // output current point data based on interval\n        if(i - lastOutputIteration >= interval) {\n            model.OutputPointData(i);\n            lastOutputIteration = i;\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "b02fa83945bccb813dee8c4afb0ea1082c73a41c", "size": 23860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlaf.cpp", "max_stars_repo_name": "jasonwebb/dla-of", "max_stars_repo_head_hexsha": "9e8120d8630ae15ac70524db73840d71ff2c0d44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-11-11T16:38:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T03:42:36.000Z", "max_issues_repo_path": "dlaf.cpp", "max_issues_repo_name": "jasonwebb/dla-of", "max_issues_repo_head_hexsha": "9e8120d8630ae15ac70524db73840d71ff2c0d44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dlaf.cpp", "max_forks_repo_name": "jasonwebb/dla-of", "max_forks_repo_head_hexsha": "9e8120d8630ae15ac70524db73840d71ff2c0d44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-31T05:26:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-31T05:26:41.000Z", "avg_line_length": 31.8558077437, "max_line_length": 167, "alphanum_fraction": 0.605364627, "num_tokens": 5882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.24605921495046956}}
{"text": "/*\r\n\r\nCopyright (c) 2013, Project OSRM, Dennis Luxen, others\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without modification,\r\nare permitted provided that the following conditions are met:\r\n\r\nRedistributions of source code must retain the above copyright notice, this list\r\nof conditions and the following disclaimer.\r\nRedistributions in binary form must reproduce the above copyright notice, this\r\nlist of conditions and the following disclaimer in the documentation and/or\r\nother materials provided with the distribution.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\r\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\r\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\n*/\r\n\r\n#include <osrm/Coordinate.h>\r\n#include \"../Util/MercatorUtil.h\"\r\n#ifndef NDEBUG\r\n#include \"../Util/simple_logger.hpp\"\r\n#endif\r\n#include \"../Util/string_util.hpp\"\r\n\r\n#include <boost/assert.hpp>\r\n\r\n#ifndef NDEBUG\r\n#include <bitset>\r\n#endif\r\n#include <iostream>\r\n#include <limits>\r\n\r\nFixedPointCoordinate::FixedPointCoordinate()\r\n    : lat(std::numeric_limits<int>::min()), lon(std::numeric_limits<int>::min())\r\n{\r\n}\r\n\r\nFixedPointCoordinate::FixedPointCoordinate(int lat, int lon) : lat(lat), lon(lon)\r\n{\r\n#ifndef NDEBUG\r\n    if (0 != (std::abs(lat) >> 30))\r\n    {\r\n        std::bitset<32> y_coordinate_vector(lat);\r\n        SimpleLogger().Write(logDEBUG) << \"broken lat: \" << lat\r\n                                       << \", bits: \" << y_coordinate_vector;\r\n    }\r\n    if (0 != (std::abs(lon) >> 30))\r\n    {\r\n        std::bitset<32> x_coordinate_vector(lon);\r\n        SimpleLogger().Write(logDEBUG) << \"broken lon: \" << lon\r\n                                       << \", bits: \" << x_coordinate_vector;\r\n    }\r\n#endif\r\n}\r\n\r\nvoid FixedPointCoordinate::Reset()\r\n{\r\n    lat = std::numeric_limits<int>::min();\r\n    lon = std::numeric_limits<int>::min();\r\n}\r\nbool FixedPointCoordinate::isSet() const\r\n{\r\n    return (std::numeric_limits<int>::min() != lat) && (std::numeric_limits<int>::min() != lon);\r\n}\r\nbool FixedPointCoordinate::is_valid() const\r\n{\r\n    if (lat > 90 * COORDINATE_PRECISION || lat < -90 * COORDINATE_PRECISION ||\r\n        lon > 180 * COORDINATE_PRECISION || lon < -180 * COORDINATE_PRECISION)\r\n    {\r\n        return false;\r\n    }\r\n    return true;\r\n}\r\nbool FixedPointCoordinate::operator==(const FixedPointCoordinate &other) const\r\n{\r\n    return lat == other.lat && lon == other.lon;\r\n}\r\n\r\ndouble FixedPointCoordinate::ApproximateDistance(const int lat1,\r\n                                                 const int lon1,\r\n                                                 const int lat2,\r\n                                                 const int lon2)\r\n{\r\n    BOOST_ASSERT(lat1 != std::numeric_limits<int>::min());\r\n    BOOST_ASSERT(lon1 != std::numeric_limits<int>::min());\r\n    BOOST_ASSERT(lat2 != std::numeric_limits<int>::min());\r\n    BOOST_ASSERT(lon2 != std::numeric_limits<int>::min());\r\n    double RAD = 0.017453292519943295769236907684886;\r\n    double lt1 = lat1 / COORDINATE_PRECISION;\r\n    double ln1 = lon1 / COORDINATE_PRECISION;\r\n    double lt2 = lat2 / COORDINATE_PRECISION;\r\n    double ln2 = lon2 / COORDINATE_PRECISION;\r\n    double dlat1 = lt1 * (RAD);\r\n\r\n    double dlong1 = ln1 * (RAD);\r\n    double dlat2 = lt2 * (RAD);\r\n    double dlong2 = ln2 * (RAD);\r\n\r\n    double dLong = dlong1 - dlong2;\r\n    double dLat = dlat1 - dlat2;\r\n\r\n    double aHarv = pow(sin(dLat / 2.0), 2.0) + cos(dlat1) * cos(dlat2) * pow(sin(dLong / 2.), 2);\r\n    double cHarv = 2. * atan2(sqrt(aHarv), sqrt(1.0 - aHarv));\r\n    // earth radius varies between 6,356.750-6,378.135 km (3,949.901-3,963.189mi)\r\n    // The IUGG value for the equatorial radius is 6378.137 km (3963.19 miles)\r\n    const double earth = 6372797.560856;\r\n    return earth * cHarv;\r\n}\r\n\r\ndouble FixedPointCoordinate::ApproximateDistance(const FixedPointCoordinate &coordinate_1,\r\n                                                 const FixedPointCoordinate &coordinate_2)\r\n{\r\n    return ApproximateDistance(\r\n        coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, coordinate_2.lon);\r\n}\r\n\r\nfloat FixedPointCoordinate::ApproximateEuclideanDistance(const FixedPointCoordinate &coordinate_1,\r\n                                                         const FixedPointCoordinate &coordinate_2)\r\n{\r\n    return ApproximateEuclideanDistance(\r\n        coordinate_1.lat, coordinate_1.lon, coordinate_2.lat, coordinate_2.lon);\r\n}\r\n\r\nfloat FixedPointCoordinate::ApproximateEuclideanDistance(const int lat1,\r\n                                                         const int lon1,\r\n                                                         const int lat2,\r\n                                                         const int lon2)\r\n{\r\n    BOOST_ASSERT(lat1 != std::numeric_limits<int>::min());\r\n    BOOST_ASSERT(lon1 != std::numeric_limits<int>::min());\r\n    BOOST_ASSERT(lat2 != std::numeric_limits<int>::min());\r\n    BOOST_ASSERT(lon2 != std::numeric_limits<int>::min());\r\n\r\n    const float RAD = 0.017453292519943295769236907684886f;\r\n    const float float_lat1 = (lat1 / COORDINATE_PRECISION) * RAD;\r\n    const float float_lon1 = (lon1 / COORDINATE_PRECISION) * RAD;\r\n    const float float_lat2 = (lat2 / COORDINATE_PRECISION) * RAD;\r\n    const float float_lon2 = (lon2 / COORDINATE_PRECISION) * RAD;\r\n\r\n    const float x_value = (float_lon2 - float_lon1) * cos((float_lat1 + float_lat2) / 2.f);\r\n    const float y_value = float_lat2 - float_lat1;\r\n    const float earth_radius = 6372797.560856f;\r\n    return sqrt(x_value * x_value + y_value * y_value) * earth_radius;\r\n}\r\n\r\nfloat\r\nFixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordinate &source_coordinate,\r\n                                                   const FixedPointCoordinate &target_coordinate,\r\n                                                   const FixedPointCoordinate &point)\r\n{\r\n    // initialize values\r\n    const float x_value = static_cast<float>(lat2y(point.lat / COORDINATE_PRECISION));\r\n    const float y_value = point.lon / COORDINATE_PRECISION;\r\n    float a = static_cast<float>(lat2y(source_coordinate.lat / COORDINATE_PRECISION));\r\n    float b = source_coordinate.lon / COORDINATE_PRECISION;\r\n    float c = static_cast<float>(lat2y(target_coordinate.lat / COORDINATE_PRECISION));\r\n    float d = target_coordinate.lon / COORDINATE_PRECISION;\r\n    float p, q;\r\n    if (std::abs(a - c) > std::numeric_limits<float>::epsilon())\r\n    {\r\n        const float slope = (d - b) / (c - a); // slope\r\n        // Projection of (x,y) on line joining (a,b) and (c,d)\r\n        p = ((x_value + (slope * y_value)) + (slope * slope * a - slope * b)) /\r\n            (1.f + slope * slope);\r\n        q = b + slope * (p - a);\r\n    }\r\n    else\r\n    {\r\n        p = c;\r\n        q = y_value;\r\n    }\r\n\r\n    float ratio;\r\n    bool inverse_ratio = false;\r\n\r\n    // straight line segment on equator\r\n    if (std::abs(c) < std::numeric_limits<float>::epsilon() &&\r\n        std::abs(a) < std::numeric_limits<float>::epsilon())\r\n    {\r\n        ratio = (q - b) / (d - b);\r\n    }\r\n    else\r\n    {\r\n        if (std::abs(c) < std::numeric_limits<float>::epsilon())\r\n        {\r\n            // swap start/end\r\n            std::swap(a, c);\r\n            std::swap(b, d);\r\n            inverse_ratio = true;\r\n        }\r\n\r\n        float nY = (d * p - c * q) / (a * d - b * c);\r\n        // discretize the result to coordinate precision. it's a hack!\r\n        if (std::abs(nY) < (1.f / COORDINATE_PRECISION))\r\n        {\r\n            nY = 0.f;\r\n        }\r\n\r\n        // compute ratio\r\n        ratio = (p - nY * a) / c;\r\n    }\r\n\r\n    if (std::isnan(ratio))\r\n    {\r\n        ratio = (target_coordinate == point ? 1.f : 0.f);\r\n    }\r\n    else if (std::abs(ratio) <= std::numeric_limits<float>::epsilon())\r\n    {\r\n        ratio = 0.f;\r\n    }\r\n    else if (std::abs(ratio - 1.f) <= std::numeric_limits<float>::epsilon())\r\n    {\r\n        ratio = 1.f;\r\n    }\r\n\r\n    // we need to do this, if we switched start/end coordinates\r\n    if (inverse_ratio)\r\n    {\r\n        ratio = 1.0f - ratio;\r\n    }\r\n\r\n    // compute the nearest location\r\n    FixedPointCoordinate nearest_location;\r\n    BOOST_ASSERT(!std::isnan(ratio));\r\n    if (ratio <= 0.f)\r\n    { // point is \"left\" of edge\r\n        nearest_location = source_coordinate;\r\n    }\r\n    else if (ratio >= 1.f)\r\n    { // point is \"right\" of edge\r\n        nearest_location = target_coordinate;\r\n    }\r\n    else\r\n    { // point lies in between\r\n        nearest_location.lat = static_cast<int>(y2lat(p) * COORDINATE_PRECISION);\r\n        nearest_location.lon = static_cast<int>(q * COORDINATE_PRECISION);\r\n    }\r\n\r\n    BOOST_ASSERT(nearest_location.is_valid());\r\n    return FixedPointCoordinate::ApproximateEuclideanDistance(point, nearest_location);\r\n}\r\n\r\nfloat FixedPointCoordinate::ComputePerpendicularDistance(const FixedPointCoordinate &segment_source,\r\n                                                         const FixedPointCoordinate &segment_target,\r\n                                                         const FixedPointCoordinate &query_location,\r\n                                                         FixedPointCoordinate &nearest_location,\r\n                                                         float &ratio)\r\n{\r\n    BOOST_ASSERT(query_location.is_valid());\r\n\r\n    // initialize values\r\n    const double x = lat2y(query_location.lat / COORDINATE_PRECISION);\r\n    const double y = query_location.lon / COORDINATE_PRECISION;\r\n    const double a = lat2y(segment_source.lat / COORDINATE_PRECISION);\r\n    const double b = segment_source.lon / COORDINATE_PRECISION;\r\n    const double c = lat2y(segment_target.lat / COORDINATE_PRECISION);\r\n    const double d = segment_target.lon / COORDINATE_PRECISION;\r\n    double p, q /*,mX*/, nY;\r\n    if (std::abs(a - c) > std::numeric_limits<double>::epsilon())\r\n    {\r\n        const double m = (d - b) / (c - a); // slope\r\n        // Projection of (x,y) on line joining (a,b) and (c,d)\r\n        p = ((x + (m * y)) + (m * m * a - m * b)) / (1.f + m * m);\r\n        q = b + m * (p - a);\r\n    }\r\n    else\r\n    {\r\n        p = c;\r\n        q = y;\r\n    }\r\n    nY = (d * p - c * q) / (a * d - b * c);\r\n\r\n    // discretize the result to coordinate precision. it's a hack!\r\n    if (std::abs(nY) < (1.f / COORDINATE_PRECISION))\r\n    {\r\n        nY = 0.f;\r\n    }\r\n\r\n    // compute ratio\r\n    ratio = (p - nY * a) / c; // These values are actually n/m+n and m/m+n , we need\r\n    // not calculate the explicit values of m an n as we\r\n    // are just interested in the ratio\r\n    if (std::isnan(ratio))\r\n    {\r\n        ratio = (segment_target == query_location ? 1.f : 0.f);\r\n    }\r\n    else if (std::abs(ratio) <= std::numeric_limits<double>::epsilon())\r\n    {\r\n        ratio = 0.f;\r\n    }\r\n    else if (std::abs(ratio - 1.f) <= std::numeric_limits<double>::epsilon())\r\n    {\r\n        ratio = 1.f;\r\n    }\r\n\r\n    // compute nearest location\r\n    BOOST_ASSERT(!std::isnan(ratio));\r\n    if (ratio <= 0.f)\r\n    {\r\n        nearest_location = segment_source;\r\n    }\r\n    else if (ratio >= 1.f)\r\n    {\r\n        nearest_location = segment_target;\r\n    }\r\n    else\r\n    {\r\n        // point lies in between\r\n        nearest_location.lat = static_cast<int>(y2lat(p) * COORDINATE_PRECISION);\r\n        nearest_location.lon = static_cast<int>(q * COORDINATE_PRECISION);\r\n    }\r\n    BOOST_ASSERT(nearest_location.is_valid());\r\n\r\n    const float approximate_distance =\r\n        FixedPointCoordinate::ApproximateEuclideanDistance(query_location, nearest_location);\r\n    BOOST_ASSERT(0. <= approximate_distance);\r\n    return approximate_distance;\r\n}\r\n\r\nvoid FixedPointCoordinate::convertInternalLatLonToString(const int value, std::string &output)\r\n{\r\n    char buffer[12];\r\n    buffer[11] = 0; // zero termination\r\n    output = printInt<11, 6>(buffer, value);\r\n}\r\n\r\nvoid FixedPointCoordinate::convertInternalCoordinateToString(const FixedPointCoordinate &coord,\r\n                                                             std::string &output)\r\n{\r\n    std::string tmp;\r\n    tmp.reserve(23);\r\n    convertInternalLatLonToString(coord.lon, tmp);\r\n    output = tmp;\r\n    output += \",\";\r\n    convertInternalLatLonToString(coord.lat, tmp);\r\n    output += tmp;\r\n}\r\n\r\nvoid\r\nFixedPointCoordinate::convertInternalReversedCoordinateToString(const FixedPointCoordinate &coord,\r\n                                                                std::string &output)\r\n{\r\n    std::string tmp;\r\n    tmp.reserve(23);\r\n    convertInternalLatLonToString(coord.lat, tmp);\r\n    output = tmp;\r\n    output += \",\";\r\n    convertInternalLatLonToString(coord.lon, tmp);\r\n    output += tmp;\r\n}\r\n\r\nvoid FixedPointCoordinate::Output(std::ostream &out) const\r\n{\r\n    out << \"(\" << lat / COORDINATE_PRECISION << \",\" << lon / COORDINATE_PRECISION << \")\";\r\n}\r\n\r\nfloat FixedPointCoordinate::GetBearing(const FixedPointCoordinate &first_coordinate,\r\n                                       const FixedPointCoordinate &second_coordinate)\r\n{\r\n    const float lon_diff =\r\n        second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION;\r\n    const float lon_delta = DegreeToRadian(lon_diff);\r\n    const float lat1 = DegreeToRadian(first_coordinate.lat / COORDINATE_PRECISION);\r\n    const float lat2 = DegreeToRadian(second_coordinate.lat / COORDINATE_PRECISION);\r\n    const float y = sin(lon_delta) * cos(lat2);\r\n    const float x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(lon_delta);\r\n    float result = RadianToDegree(std::atan2(y, x));\r\n    while (result < 0.f)\r\n    {\r\n        result += 360.f;\r\n    }\r\n\r\n    while (result >= 360.f)\r\n    {\r\n        result -= 360.f;\r\n    }\r\n    return result;\r\n}\r\n\r\nfloat FixedPointCoordinate::GetBearing(const FixedPointCoordinate &other) const\r\n{\r\n    const float lon_delta =\r\n        DegreeToRadian(lon / COORDINATE_PRECISION - other.lon / COORDINATE_PRECISION);\r\n    const float lat1 = DegreeToRadian(other.lat / COORDINATE_PRECISION);\r\n    const float lat2 = DegreeToRadian(lat / COORDINATE_PRECISION);\r\n    const float y_value = std::sin(lon_delta) * std::cos(lat2);\r\n    const float x_value =\r\n        std::cos(lat1) * std::sin(lat2) - std::sin(lat1) * std::cos(lat2) * std::cos(lon_delta);\r\n    float result = RadianToDegree(std::atan2(y_value, x_value));\r\n\r\n    while (result < 0.f)\r\n    {\r\n        result += 360.f;\r\n    }\r\n\r\n    while (result >= 360.f)\r\n    {\r\n        result -= 360.f;\r\n    }\r\n    return result;\r\n}\r\n\r\nfloat FixedPointCoordinate::DegreeToRadian(const float degree)\r\n{\r\n    return degree * (static_cast<float>(M_PI) / 180.f);\r\n}\r\n\r\nfloat FixedPointCoordinate::RadianToDegree(const float radian)\r\n{\r\n    return radian * (180.f * static_cast<float>(M_1_PI));\r\n}\r\n\r\n// This distance computation does integer arithmetic only and is a lot faster than\r\n// the other distance function which are numerically correct('ish).\r\n// It preserves some order among the elements that make it useful for certain purposes\r\nint FixedPointCoordinate::OrderedPerpendicularDistanceApproximation(\r\n    const FixedPointCoordinate &input_point,\r\n    const FixedPointCoordinate &segment_source,\r\n    const FixedPointCoordinate &segment_target)\r\n{\r\n    // initialize values\r\n    const float x = static_cast<float>(lat2y(input_point.lat / COORDINATE_PRECISION));\r\n    const float y = input_point.lon / COORDINATE_PRECISION;\r\n    const float a = static_cast<float>(lat2y(segment_source.lat / COORDINATE_PRECISION));\r\n    const float b = segment_source.lon / COORDINATE_PRECISION;\r\n    const float c = static_cast<float>(lat2y(segment_target.lat / COORDINATE_PRECISION));\r\n    const float d = segment_target.lon / COORDINATE_PRECISION;\r\n\r\n    float p, q;\r\n    if (a == c)\r\n    {\r\n        p = c;\r\n        q = y;\r\n    }\r\n    else\r\n    {\r\n        const float m = (d - b) / (c - a); // slope\r\n        // Projection of (x,y) on line joining (a,b) and (c,d)\r\n        p = ((x + (m * y)) + (m * m * a - m * b)) / (1.f + m * m);\r\n        q = b + m * (p - a);\r\n    }\r\n\r\n    const float nY = (d * p - c * q) / (a * d - b * c);\r\n    float ratio = (p - nY * a) / c; // These values are actually n/m+n and m/m+n , we need\r\n    // not calculate the explicit values of m an n as we\r\n    // are just interested in the ratio\r\n    if (std::isnan(ratio))\r\n    {\r\n        ratio = (segment_target == input_point) ? 1.f : 0.f;\r\n    }\r\n\r\n    // compute target quasi-location\r\n    int dx, dy;\r\n    if (ratio < 0.f)\r\n    {\r\n        dx = input_point.lon - segment_source.lon;\r\n        dy = input_point.lat - segment_source.lat;\r\n    }\r\n    else if (ratio > 1.f)\r\n    {\r\n        dx = input_point.lon - segment_target.lon;\r\n        dy = input_point.lat - segment_target.lat;\r\n    }\r\n    else\r\n    {\r\n        // point lies in between\r\n        dx = input_point.lon - static_cast<int>(q * COORDINATE_PRECISION);\r\n        dy = input_point.lat - static_cast<int>(y2lat(p) * COORDINATE_PRECISION);\r\n    }\r\n\r\n    // return an approximation in the plane\r\n    return static_cast<int>(sqrt(dx * dx + dy * dy));\r\n}\r\n", "meta": {"hexsha": "4305256ef63884d38cbcfc4e6e3467053862fb9b", "size": 17532, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data_structures/Coordinate.cpp", "max_stars_repo_name": "cypox/devacus-backend", "max_stars_repo_head_hexsha": "ba3d2ca8d72843560c4ff754780482dfe8a67c6b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data_structures/Coordinate.cpp", "max_issues_repo_name": "cypox/devacus-backend", "max_issues_repo_head_hexsha": "ba3d2ca8d72843560c4ff754780482dfe8a67c6b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T18:27:19.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-25T18:27:19.000Z", "max_forks_repo_path": "data_structures/Coordinate.cpp", "max_forks_repo_name": "VRPTools/pkg-osrm-backend", "max_forks_repo_head_hexsha": "9b130cfb757b32e6799620babfb085398268156e", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2231404959, "max_line_length": 101, "alphanum_fraction": 0.6036960986, "num_tokens": 4279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4882833952958347, "lm_q1q2_score": 0.2460490158564613}}
{"text": "/*! \\file Peridigm_EnergyReleaseDamageCorrepondenceModel.cpp */\n\n//@HEADER\n// ************************************************************************\n//\n//                             Peridigm\n//                 Copyright (2011) Sandia Corporation\n//\n// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n// the U.S. Government retains certain rights in this software.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// 1. Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above 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// 3. Neither the name of the Corporation nor the names of the\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION \"AS IS\" AND ANY\n// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE\n// CONTRIBUTORS 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\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Questions?\n// David J. Littlewood   djlittl@sandia.gov\n// John A. Mitchell      jamitch@sandia.gov\n// Michael L. Parks      mlparks@sandia.gov\n// Stewart A. Silling    sasilli@sandia.gov\n//\n// ************************************************************************\n// Author of this Routine\n// Christian Willberg   christian.willberg@dlr.de\n// German Aerospace Center\n//@HEADER\n\n#include \"Peridigm_EnergyReleaseDamageCorrepondenceModel.hpp\"\n#include \"Peridigm_Field.hpp\"\n#include \"material_utilities.h\"\n#include \"correspondence.h\"\n#include <thread>\n#include <Teuchos_Assert.hpp>\n#include <Epetra_SerialComm.h>\n#include <Sacado.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n\nusing namespace std;\n\nPeridigmNS::EnergyReleaseDamageCorrepondenceModel::EnergyReleaseDamageCorrepondenceModel(const Teuchos::ParameterList& params)\n: DamageModel(params), \nm_applyThermalStrains(false),\nm_modelCoordinatesFieldId(-1),\nm_coordinatesFieldId(-1),\nm_damageFieldId(-1),\nm_bondDamageFieldId(-1),\nm_deltaTemperatureFieldId(-1),\nm_dilatationFieldId(-1),\nm_weightedVolumeFieldId(-1),\nm_horizonFieldId(-1),\nm_piolaStressTimesInvShapeTensorXId(-1),\nm_piolaStressTimesInvShapeTensorYId(-1),\nm_piolaStressTimesInvShapeTensorZId(-1),\nm_detachedNodesFieldId(-1),\nm_forceDensityFieldId(-1),\nm_deformationGradientFieldId(-1),\nm_hourglassStiffId(-1),\nm_OMEGA(PeridigmNS::InfluenceFunction::self().getInfluenceFunction()) {\n\n    \n    if (params.isParameter(\"Critical Energy\")) {\n        m_criticalEnergyTension = params.get<double>(\"Critical Energy\");\n          \n    } \n    if (params.isParameter(\"Degradation Factor\")){\n        degradationFactor = 1;\n        degradationFactor = params.get<double>(\"Degradation Factor\");\n        \n    }else{\n        degradationFactor = 1; \n    }\n    m_incremental = true;\n    if (params.isParameter(\"Incremental\")){\n       m_incremental = params.get<bool>(\"Incremental\");\n    }\n    m_criticalEnergyTension = params.get<double>(\"Critical Energy\");\n    m_hourglassCoefficient = params.get<double>(\"Hourglass Coefficient\");\n    m_planeStrain=false;\n    m_planeStress=false;\n    detachedNodesCheck = false;\n    if (params.isParameter(\"Detached Nodes Check\"))\n        detachedNodesCheck = params.get<bool>(\"Detached Nodes Check\");\n    if (params.isParameter(\"Plane Strain\"))\n      m_planeStrain = params.get<bool>(\"Plane Strain\");\n    if (params.isParameter(\"Plane Stress\"))\n      m_planeStress = params.get<bool>(\"Plane Stress\");\n    m_plane = false;\n   \n    m_onlyTension = false;\n    if(params.isParameter(\"Only Tension\")){\n        m_onlyTension = params.get<bool>(\"Only Tension\");\n\n    }\n\n  //************************************\n  // wie komme ich an den Namen??\n  //************************************\n  //if (params.isParameter(\"Linear Elastic Correspondence\")){\n   \n    //std::cout<<\"Use Material: Linear Elastic Correspondence\"<<std::endl;\n\n    if (m_planeStrain==true){\n        //m_plane=true;\n        m_plane = true;\n        m_Thickness = params.get<double>(\"Thickness\");\n        //std::cout<<\"Method 2D Plane Strain\"<<std::endl;\n    }\n    if (m_planeStress==true){\n       // m_plane=true;\n        m_plane = true;\n        m_Thickness = params.get<double>(\"Thickness\");\n        //std::cout<<\"WRN: Method 2D Plane Stress --> not fully implemented yet\"<<std::endl;\n    }\n   \n// Params anpassen. Irgendwo muss das befuellt werden, da bspw. die thermische Verformung bei Material\n// und Schaden existiert\n//\n//\n\n    m_pi = 3.14159;\n\n    if (params.isParameter(\"Thermal Expansion Coefficient\")) {\n        m_alpha = params.get<double>(\"Thermal Expansion Coefficient\");\n        m_applyThermalStrains = true;\n    }\n\n    PeridigmNS::FieldManager& fieldManager = PeridigmNS::FieldManager::self();\n    m_modelCoordinatesFieldId = fieldManager.getFieldId(PeridigmField::NODE, PeridigmField::VECTOR, PeridigmField::CONSTANT,\"Model_Coordinates\");\n    m_coordinatesFieldId = fieldManager.getFieldId(PeridigmField::NODE, PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"Coordinates\");\n    m_volumeFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::CONSTANT, \"Volume\");\n    m_weightedVolumeFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::CONSTANT, \"Weighted_Volume\");\n    m_dilatationFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::TWO_STEP, \"Dilatation\");\n    m_damageFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::TWO_STEP, \"Damage\");\n    m_bondDamageFieldId = fieldManager.getFieldId(PeridigmField::BOND, PeridigmField::SCALAR, PeridigmField::TWO_STEP, \"Bond_Damage\");\n    m_horizonFieldId = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::SCALAR, PeridigmField::CONSTANT, \"Horizon\");\n    m_piolaStressTimesInvShapeTensorXId   = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"PiolaStressTimesInvShapeTensorX\");\n    m_piolaStressTimesInvShapeTensorYId   = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"PiolaStressTimesInvShapeTensorY\");\n    m_piolaStressTimesInvShapeTensorZId   = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"PiolaStressTimesInvShapeTensorZ\");\n    m_detachedNodesFieldId              = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::SCALAR, PeridigmField::TWO_STEP, \"Detached_Nodes\");\n    m_forceDensityFieldId               = fieldManager.getFieldId(PeridigmField::NODE,    PeridigmField::VECTOR, PeridigmField::TWO_STEP, \"Force_Density\");\n    m_deformationGradientFieldId        = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::CONSTANT, \"Deformation_Gradient\");\n    m_hourglassStiffId                  = fieldManager.getFieldId(PeridigmField::ELEMENT, PeridigmField::FULL_TENSOR, PeridigmField::CONSTANT, \"Hourglass_Stiffness\");\n \n    \n    m_fieldIds.push_back(m_volumeFieldId);\n    m_fieldIds.push_back(m_modelCoordinatesFieldId);\n    m_fieldIds.push_back(m_coordinatesFieldId);\n    m_fieldIds.push_back(m_weightedVolumeFieldId);\n    m_fieldIds.push_back(m_dilatationFieldId);\n    m_fieldIds.push_back(m_volumeFieldId);\n    m_fieldIds.push_back(m_damageFieldId);\n    m_fieldIds.push_back(m_detachedNodesFieldId);\n    m_fieldIds.push_back(m_bondDamageFieldId);\n    m_fieldIds.push_back(m_horizonFieldId);\n    m_fieldIds.push_back(m_piolaStressTimesInvShapeTensorXId);\n    m_fieldIds.push_back(m_piolaStressTimesInvShapeTensorYId);\n    m_fieldIds.push_back(m_piolaStressTimesInvShapeTensorZId);\n    m_fieldIds.push_back(m_forceDensityFieldId);\n    m_fieldIds.push_back(m_hourglassStiffId);\n    m_fieldIds.push_back(m_deformationGradientFieldId);\n\n}\n\nPeridigmNS::EnergyReleaseDamageCorrepondenceModel::~EnergyReleaseDamageCorrepondenceModel() {\n}\n\nvoid\nPeridigmNS::EnergyReleaseDamageCorrepondenceModel::initialize(const double dt,\n        const int numOwnedPoints,\n        const int* ownedIDs,\n        const int* neighborhoodList,\n        PeridigmNS::DataManager& dataManager) const {\n    double *damage, *bondDamage;\n\n\n    dataManager.getData(m_damageFieldId, PeridigmField::STEP_NP1)->ExtractView(&damage);\n    dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage);\n    \n    dataManager.getData(m_piolaStressTimesInvShapeTensorXId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n    dataManager.getData(m_piolaStressTimesInvShapeTensorYId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n    dataManager.getData(m_piolaStressTimesInvShapeTensorZId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n    dataManager.getData(m_detachedNodesFieldId, PeridigmField::STEP_NP1)->PutScalar(0.0);\n    // Initialize damage to zero\n    int neighborhoodListIndex(0);\n    int bondIndex(0);\n    int nodeId, numNeighbors;\n    int iID, iNID;\n\n    for (iID = 0; iID < numOwnedPoints; ++iID) {\n        nodeId = ownedIDs[iID];\n        damage[nodeId] = 0.0;\n        numNeighbors = neighborhoodList[neighborhoodListIndex++];\n        neighborhoodListIndex += numNeighbors;\n        for (iNID = 0; iNID < numNeighbors; ++iNID) {\n            bondDamage[bondIndex] = 0.0;\n            bondIndex += 1;\n        }\n    }\n\n}\n\nvoid\nPeridigmNS::EnergyReleaseDamageCorrepondenceModel::computeDamage(const double dt,\n        const int numOwnedPoints,\n        const int* ownedIDs,\n        const int* neighborhoodList,\n        PeridigmNS::DataManager& dataManager) const {\n\n    double *x, *y, *damage, *bondDamageNP1, *horizon, *vol, *detachedNodes;\n    \n    \n    double criticalEnergyTension(-1.0);\n    // for temperature dependencies easy to extent\n    double *deltaTemperature = NULL;\n    double *tempStressX, *tempStressY, *tempStressZ;\n    dataManager.getData(m_damageFieldId, PeridigmField::STEP_NP1)->ExtractView(&damage);\n\n    dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&x);\n\n    dataManager.getData(m_coordinatesFieldId, PeridigmField::STEP_NP1)->ExtractView(&y);\n    dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&vol);\n\n    dataManager.getData(m_horizonFieldId, PeridigmField::STEP_NONE)->ExtractView(&horizon);\n    dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamageNP1);\n\n\n    \n    dataManager.getData(m_piolaStressTimesInvShapeTensorXId, PeridigmField::STEP_NP1)->ExtractView(&tempStressX);\n    dataManager.getData(m_piolaStressTimesInvShapeTensorYId, PeridigmField::STEP_NP1)->ExtractView(&tempStressY);\n    dataManager.getData(m_piolaStressTimesInvShapeTensorZId, PeridigmField::STEP_NP1)->ExtractView(&tempStressZ);\n    dataManager.getData(m_detachedNodesFieldId, PeridigmField::STEP_NP1)->ExtractView(&detachedNodes);\n    ////////////////////////////////////////////////////////\n    // Hourglass control\n    // not synchronized yet; Hourglass correction is used only from nodeId site\n    //\n    double *defGrad, *hourglassStiff;\n    vector<double> TSvector(3), hourglassStiffVector(9);\n    double* hStiff = &hourglassStiffVector[0];\n    double* TS = &TSvector[0];\n    ///////////////////////////////////////////////////////\n    dataManager.getData(m_hourglassStiffId, PeridigmField::STEP_NONE)->ExtractView(&hourglassStiff);\n    dataManager.getData(m_deformationGradientFieldId, PeridigmField::STEP_NONE)->ExtractView(&defGrad);\n    //std::cout<< \"heredam\"<<std::endl;\n    // Set the bond damage to the previous value --> needed for iteration in implicit time integration\n    *(dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)) = *(dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_N));\n     double *forceDensity;\n    dataManager.getData(m_forceDensityFieldId, PeridigmField::STEP_NP1)->ExtractView(&forceDensity);\n    \n    ////////////////////////////////////////////////////\n    double trialDamage(0.0);\n    int neighborhoodListIndex(0), bondIndex(0);\n    int nodeId, numNeighbors, neighborID, iID, iNID;\n    double totalDamage;\n    double nodeInitialX[3], nodeCurrentX[3];\n    double omegaP1, omegaP2;\n    double critIso;\n    \n    double quadhorizon;\n    // bond force density state\n    double TX, TY, TZ, TXN, TYN, TZN;\n    // bond force density state projected to deformed bond\n    double TPX, TPY, TPZ, TPXN, TPYN, TPZN;\n    double factor, factorN;\n    // deformed state\n    double Y_dx, Y_dy, Y_dz;\n    // initial state\n    double X_dx, X_dy, X_dz;\n    // displacement vector state and abolute value\n    double etaX, etaY, etaZ, dEta, normEtaSq;\n    double bondEnergy;\n    double dX, dY;//, dYSq;\n\n    //---------------------------\n    // INITIALIZE PROCESS STEP t\n    //---------------------------\n    // Foster 2009 Journal for Multiscale Computational Engineering\n    // m_criticalEnergy = 4 G / (pi delta^4)\n    // what if two horizons meet? two criterions will hit the same bond..\n    //double quadhorizon =  4 /( m_pi * m_horizon * m_horizon * m_horizon * m_horizon );\n    \n    if (m_criticalEnergyTension > 0.0)\n        criticalEnergyTension = m_criticalEnergyTension;\n \n    // Update the bond damage\n    // Break bonds if the bond energy potential is greater than the critical bond energy potential\n    //---------------------------\n    // DAMAGE ANALYSIS\n    //---------------------------\n    bondIndex = 0;\n\n    for (iID = 0; iID < numOwnedPoints; ++iID, defGrad+=9, hourglassStiff+=9) {\n        numNeighbors = neighborhoodList[neighborhoodListIndex++];\n        \n        nodeId = ownedIDs[iID];\n        nodeInitialX[0] = x[nodeId*3];\n        nodeInitialX[1] = x[nodeId*3+1];\n        nodeInitialX[2] = x[nodeId*3+2];\n        nodeCurrentX[0] = y[nodeId*3];\n        nodeCurrentX[1] = y[nodeId*3+1];\n        nodeCurrentX[2] = y[nodeId*3+2];\n        \n        for (iNID = 0; iNID < numNeighbors; ++iNID) {\n            \n            \n            neighborID = neighborhoodList[neighborhoodListIndex++];\n            if (detachedNodes[nodeId]!=0) continue;\n            if (detachedNodes[neighborID]!=0) continue;\n            X_dx = x[neighborID*3]   - nodeInitialX[0];\n            X_dy = x[neighborID*3+1] - nodeInitialX[1];\n            X_dz = x[neighborID*3+2] - nodeInitialX[2];\n \n            Y_dx = y[neighborID*3]   - nodeCurrentX[0];\n            Y_dy = y[neighborID*3+1] - nodeCurrentX[1];\n            Y_dz = y[neighborID*3+2] - nodeCurrentX[2];\n            etaX  = (Y_dx-X_dx);\n            etaY  = (Y_dy-X_dy);\n            etaZ  = (Y_dz-X_dz);\n            \n                         \n            //double uNx = y[neighborID*3]   - x[neighborID*3];\n            //double uNy = y[neighborID*3+1] - x[neighborID*3+1];\n            //double uNz = y[neighborID*3+2] - x[neighborID*3+2];\n            \n            \n            dX = distance(nodeInitialX[0], nodeInitialX[1], nodeInitialX[2], x[neighborID*3], x[neighborID*3+1], x[neighborID*3+2]);\n            dY = distance(nodeCurrentX[0], nodeCurrentX[1], nodeCurrentX[2], y[neighborID*3], y[neighborID*3+1], y[neighborID*3+2]);\n            dEta = dY-dX;\n            \n\n            normEtaSq = etaX*etaX+etaY*etaY+etaZ*etaZ;\n\n            bool Tension = true;\n            \n            if (m_onlyTension == true && dEta<0) Tension = false;\n            if (Tension == true){\n                if (normEtaSq>0){\n                    omegaP1 = MATERIAL_EVALUATION::scalarInfluenceFunction(dX, horizon[nodeId]); \n                    omegaP2 = MATERIAL_EVALUATION::scalarInfluenceFunction(-dX, horizon[neighborID]); \n                    // average Force has to be taken\n                    // if not the case where \n                    if (m_plane == true) X_dz = 0;\n                    double temp = 0.5*(1-bondDamageNP1[bondIndex]);\n                    \n                    double FxsiX = *(defGrad)   * X_dx + *(defGrad+1) * X_dy + *(defGrad+2) * X_dz;\n                    double FxsiY = *(defGrad+3) * X_dx + *(defGrad+4) * X_dy + *(defGrad+5) * X_dz;\n                    double FxsiZ = *(defGrad+6) * X_dx + *(defGrad+7) * X_dy + *(defGrad+8) * X_dz;\n                    hStiff[0] = *(hourglassStiff  ); hStiff[1] = *(hourglassStiff+1);  hStiff[2] = *(hourglassStiff+2);\n                    hStiff[3] = *(hourglassStiff+3); hStiff[4] = *(hourglassStiff+4);  hStiff[5] = *(hourglassStiff+5);\n                    hStiff[6] = *(hourglassStiff+6); hStiff[7] = *(hourglassStiff+7);  hStiff[8] = *(hourglassStiff+8);\n                    CORRESPONDENCE::computeCorrespondenceStabilityWanEtAlShort(FxsiX,FxsiY,FxsiZ,Y_dx,Y_dy,Y_dz,hStiff,TS);\n               // std::cout<< TS[0]<<\" dam\"<< TS[1]<<std::endl;\n                    // volumes, or volume relation to include? should be inside via the shape tensor, which is included in tempStress\n                    TX  =   omegaP1 * ( tempStressX[3*nodeId]     * X_dx + tempStressX[3*nodeId+1]     * X_dy + tempStressX[3*nodeId+2]     * X_dz + m_hourglassCoefficient*TS[0]);\n                    TY  =   omegaP1 * ( tempStressY[3*nodeId]     * X_dx + tempStressY[3*nodeId+1]     * X_dy + tempStressY[3*nodeId+2]     * X_dz + m_hourglassCoefficient*TS[1]);\n                    TZ  =   omegaP1 * ( tempStressZ[3*nodeId]     * X_dx + tempStressZ[3*nodeId+1]     * X_dy + tempStressZ[3*nodeId+2]     * X_dz + m_hourglassCoefficient*TS[2]);\n                    // undeformedBondX, undeformedBondY, undeformedBondZ of bond 1-2 equal to -undeformedBondX, -undeformedBondY, -undeformedBondZ of bond 2-1\n                    TXN =   omegaP2 * ( tempStressX[3*neighborID] * X_dx + tempStressX[3*neighborID+1] * X_dy + tempStressX[3*neighborID+2] * X_dz + m_hourglassCoefficient*TS[0]);\n                    TYN =   omegaP2 * ( tempStressY[3*neighborID] * X_dx + tempStressY[3*neighborID+1] * X_dy + tempStressY[3*neighborID+2] * X_dz + m_hourglassCoefficient*TS[1]);\n                    TZN =   omegaP2 * ( tempStressZ[3*neighborID] * X_dx + tempStressZ[3*neighborID+1] * X_dy + tempStressZ[3*neighborID+2] * X_dz + m_hourglassCoefficient*TS[2]);\n                    //std::cout<< \"here2\"<<std::endl;\n                    // orthogonal projection of T and TN to the relative displacement vector Foster et al. \"An energy based ..\"\n                    // --> die senkrecht zur Projektion stehenden Anteile entsprechen eventuell den Schubanteilen. D.h. man könnte das Kriterium hier splitten.\n                    factor = (etaX*TX + etaY*TY + etaZ*TZ)/normEtaSq;\n                    TPX = factor*etaX; TPY = factor*etaY; TPZ = factor*etaZ;\n                    \n                    //factor = (Y_dx*TX + Y_dy*TY + Y_dz*TZ)/dYSq;\n                    //TPX = factor*Y_dx; TPY = factor*Y_dy; TPZ = factor*Y_dz;\n                    \n                    factorN = (etaX*TXN + etaY*TYN + etaZ*TZN)/normEtaSq;\n                    TPXN = factorN*etaX; TPYN = factorN*etaY; TPZN = factorN*etaZ;\n                    \n                    //factorN = (Y_dx*TXN + Y_dy*TYN + Y_dz*TZN)/dYSq;\n                    //TPXN = factorN*Y_dx; TPYN = factorN*Y_dy; TPZN = factorN*Y_dz;\n                    \n                    bondEnergy = 0.5*temp*(abs(TPX*etaX)+abs(TPXN*etaX)+abs(TPY*etaY)+abs(TPYN*etaY)+abs(TPZ*etaZ)+abs(TPZN*etaZ)) ;\n                    //if (iID == 1) std::cout<<bondEnergy<<std::endl;\n                }\n                else\n                {\n                    bondEnergy = 0;\n                }\n                //bondEnergy = 0.5*(sqrt(TX*TX)+sqrt(TXN*TXN))*sqrt((uNx-ux)*(uNx-ux)) + 0.5*(sqrt(TY*TY)+sqrt(TYN*TYN))*sqrt((uNy-uy)*(uNy-uy)) + 0.5*(sqrt(TZ*TZ)+sqrt(TZN*TZN))*sqrt((uNz-uz)*(uNz-uz));\n                \n\n                double avgHorizon = 0.5*(horizon[nodeId]+horizon[neighborID]);\n                if (bondEnergy<0){\n                    std::cout<<TPX<<\" \"<< TPXN<<\" BE \"<<bondEnergy<<std::endl;\n                }\n                ////////////////////////////////////////////////////////////////\n                //--> to check, depth is not included yet. How to handle??\n                ////////////////////////////////////////////////////////////////\n                if (m_planeStrain==false&&m_planeStress==false){\n                   quadhorizon =  4 /( m_pi * avgHorizon * avgHorizon * avgHorizon * avgHorizon );\n                }\n                else\n                {\n\n                   quadhorizon =  3 /( avgHorizon * avgHorizon * avgHorizon * m_Thickness );\n                }\n                //quadhorizon =  4 /( m_pi * avgHorizon * avgHorizon * avgHorizon * avgHorizon ); \n                critIso = bondEnergy/(criticalEnergyTension*quadhorizon);\n                //critIso = 0;\n                \n                //critIso = bondEnergy/(criticalEnergyTension*quadhorizon);\n                \n               // std::cout<<bondEnergy<<\" EE \"<<criticalEnergyTension*quadhorizon<<\" Stress1 \"<<dEta<<std::endl;\n                trialDamage = 0.0;\n                if (criticalEnergyTension > 0.0 && critIso > 1.0) {\n                    trialDamage = bondDamageNP1[bondIndex] + degradationFactor;\n                }\n\n                if (trialDamage > bondDamageNP1[bondIndex]) {\n                    if (trialDamage>1)trialDamage = 1;\n                    bondDamageNP1[bondIndex] = trialDamage;\n\n                }\n            }\n            bondIndex += 1;\n\n            }\n\n        }\n    //  Update the element damage (percent of bonds broken)\n    if (detachedNodesCheck == true){\n        int check = 1;  //set check = 1 to start the loop\n        //std::cout<< \"detached\"<<std::endl;\n        while (check != 0){\n            check = checkDetachedNodes(numOwnedPoints, ownedIDs, neighborhoodList, dataManager);\n        }\n    }\n    neighborhoodListIndex = 0;\n    bondIndex = 0;\n    double volume;\n    for (iID = 0; iID < numOwnedPoints; ++iID) {\n        nodeId = ownedIDs[iID];\n        numNeighbors = neighborhoodList[neighborhoodListIndex++];\n        //neighborhoodListIndex += numNeighbors;\n        totalDamage = 0.0;\n        volume = vol[nodeId];\n        for (iNID = 0; iNID < numNeighbors; ++iNID) {\n            \n            neighborID = neighborhoodList[neighborhoodListIndex++];\n            // must be zero to avoid synchronization errors\n            \n            totalDamage += bondDamageNP1[bondIndex]*vol[neighborID];\n            volume += vol[neighborID];\n            bondIndex += 1;\n        }\n        if (numNeighbors > 0)\n            totalDamage /= numNeighbors;\n        else\n            totalDamage = 0.0;\n\n        damage[nodeId] = totalDamage/volume;\n\n    }\n}\n\nint PeridigmNS::EnergyReleaseDamageCorrepondenceModel::checkDetachedNodes(\n                                                      const int numOwnedPoints,\n                                                      const int* ownedIDs,\n                                                      const int* neighborhoodList,                                                     \n                                                      PeridigmNS::DataManager& dataManager\n                                                      ) const\n{\n  double *bondDamage, *detachedNodes, *x, *volume, *horizon;\n  dataManager.getData(m_modelCoordinatesFieldId, PeridigmField::STEP_NONE)->ExtractView(&x);\n  dataManager.getData(m_volumeFieldId, PeridigmField::STEP_NONE)->ExtractView(&volume);\n  dataManager.getData(m_horizonFieldId, PeridigmField::STEP_NONE)->ExtractView(&horizon);\n  dataManager.getData(m_bondDamageFieldId, PeridigmField::STEP_NP1)->ExtractView(&bondDamage);\n  dataManager.getData(m_detachedNodesFieldId, PeridigmField::STEP_NP1)->ExtractView(&detachedNodes);\n \n  int neighborhoodListIndex(0), bondIndex(0);\n  int nodeId, numNeighbors, neighborID, iID, iNID;\n  double nodeInitialX[3],  initialDistance;\n  double checkShapeTensor[9], neighborVolume, checkShapeTensorInv[9];\n  double omega;\n  double determinant;\n  int check = 0, matrixInversionReturnCode = 0;\n\n  for(iID=0 ; iID<numOwnedPoints ; ++iID){\n      nodeId = ownedIDs[iID];\n      nodeInitialX[0] = x[nodeId*3];\n      nodeInitialX[1] = x[nodeId*3+1];\n      nodeInitialX[2] = x[nodeId*3+2];\n\n      numNeighbors = neighborhoodList[neighborhoodListIndex++];\n      \n      checkShapeTensor[0] = 0.0;\n      checkShapeTensor[1] = 0.0;\n      checkShapeTensor[2] = 0.0;\n      checkShapeTensor[3] = 0.0;\n      checkShapeTensor[4] = 0.0;\n      checkShapeTensor[5] = 0.0;\n      checkShapeTensor[6] = 0.0;\n      checkShapeTensor[7] = 0.0;\n      checkShapeTensor[8] = 0.0;\n  \n      for(iNID=0 ; iNID<numNeighbors ; ++iNID){\n          \n          neighborID = neighborhoodList[neighborhoodListIndex++];\n          \n          if (detachedNodes[nodeId]==0){\n          \n              neighborVolume = volume[neighborID];\n              initialDistance = distance(nodeInitialX[0], nodeInitialX[1], nodeInitialX[2],\n                                  x[neighborID*3], x[neighborID*3+1], x[neighborID*3+2]);\n              omega = MATERIAL_EVALUATION::scalarInfluenceFunction(initialDistance, horizon[iID]);\n              //double omega = 1.0;\n              double temp = (1.0 - bondDamage[bondIndex]) * omega * neighborVolume;\n              \n              double undeformedBondX =  x[neighborID*3]   - nodeInitialX[0];\n              double undeformedBondY =  x[neighborID*3+1] - nodeInitialX[1];\n              double undeformedBondZ =  x[neighborID*3+2] - nodeInitialX[2];\n              \n              checkShapeTensor[0]  += temp * undeformedBondX * undeformedBondX;\n              checkShapeTensor[1]  += temp * undeformedBondX * undeformedBondY;\n              checkShapeTensor[2]  += temp * undeformedBondX * undeformedBondZ;\n              checkShapeTensor[3]  += temp * undeformedBondY * undeformedBondX;\n              checkShapeTensor[4]  += temp * undeformedBondY * undeformedBondY;\n              checkShapeTensor[5]  += temp * undeformedBondY * undeformedBondZ;\n              checkShapeTensor[6]  += temp * undeformedBondZ * undeformedBondX;\n              checkShapeTensor[7]  += temp * undeformedBondZ * undeformedBondY;\n              checkShapeTensor[8]  += temp * undeformedBondZ * undeformedBondZ;\n          }\n          if (detachedNodes[neighborID]!=0&&bondDamage[bondIndex] != 1.0){// bondDamage check to avoid infinite loop; all bonds then destroyed\n              bondDamage[bondIndex] = 1.0;\n              check = 1;\n          }\n          \n          bondIndex += 1;\n      }\n      \n      if (detachedNodes[nodeId]!=0) continue;\n      \n      if (m_plane==true){\n        matrixInversionReturnCode =\n        CORRESPONDENCE::Invert2by2Matrix(checkShapeTensor, determinant, checkShapeTensorInv);\n        }\n      else{\n        matrixInversionReturnCode =\n        CORRESPONDENCE::Invert3by3Matrix(checkShapeTensor, determinant, checkShapeTensorInv);\n        }\n      \n      if (matrixInversionReturnCode != 0){// to be checked\n          check = 1;\n          detachedNodes[nodeId]=1.;\n          int bondIndex2 = bondIndex-numNeighbors; // set index back, to have the same correct bonds\n          // delete all connected bonds\n          for(iNID=0 ; iNID<numNeighbors ; ++iNID){\n                  bondDamage[bondIndex2] = 1.0;\n                  bondIndex2 += 1;\n          }   \n        matrixInversionReturnCode = 0;\n      }\n  }\n\n  return check;\n}\n\n\n", "meta": {"hexsha": "1272b35cdfbde75053803860c8158bf2a2375d9a", "size": 27893, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Peridigm/Code/Anisotropic_Material/damage/Peridigm_EnergyReleaseDamageCorrepondenceModel.cpp", "max_stars_repo_name": "oldninja/PeriDoX", "max_stars_repo_head_hexsha": "f31bccc7b8ea60cd814d00732aebdbbe876a2ac7", "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": "Peridigm/Code/Anisotropic_Material/damage/Peridigm_EnergyReleaseDamageCorrepondenceModel.cpp", "max_issues_repo_name": "oldninja/PeriDoX", "max_issues_repo_head_hexsha": "f31bccc7b8ea60cd814d00732aebdbbe876a2ac7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Peridigm/Code/Anisotropic_Material/damage/Peridigm_EnergyReleaseDamageCorrepondenceModel.cpp", "max_forks_repo_name": "oldninja/PeriDoX", "max_forks_repo_head_hexsha": "f31bccc7b8ea60cd814d00732aebdbbe876a2ac7", "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": 47.6803418803, "max_line_length": 203, "alphanum_fraction": 0.6289033091, "num_tokens": 7492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.24597395361641355}}
{"text": "#ifndef VIENNACL_LINALG_QR_METHOD_HPP_\n#define VIENNACL_LINALG_QR_METHOD_HPP_\n\n/* =========================================================================\n   Copyright (c) 2010-2016, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/matrix.hpp\"\n\n#include \"viennacl/linalg/qr-method-common.hpp\"\n#include \"viennacl/linalg/tql2.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n\n/** @file viennacl/linalg/qr-method.hpp\n    @brief Implementation of the QR method for eigenvalue computations. Experimental.\n*/\n\nnamespace viennacl\n{\nnamespace linalg\n{\nnamespace detail\n{\ntemplate <typename SCALARTYPE>\nvoid final_iter_update_gpu(matrix_base<SCALARTYPE> & A,\n                        int n,\n                        int last_n,\n                        SCALARTYPE q,\n                        SCALARTYPE p\n                        )\n{\n  (void)A; (void)n; (void)last_n; (void)q; (void)p;\n#ifdef VIENNACL_WITH_OPENCL\n    viennacl::ocl::context & ctx = const_cast<viennacl::ocl::context &>(viennacl::traits::opencl_handle(A).context());\n\n    if(A.row_major())\n    {\n        viennacl::ocl::kernel& kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::svd<SCALARTYPE, row_major>::program_name(), SVD_FINAL_ITER_UPDATE_KERNEL);\n\n        viennacl::ocl::enqueue(kernel(\n                                      A,\n                                      static_cast<cl_uint>(A.internal_size1()),\n                                      static_cast<cl_uint>(n),\n                                      static_cast<cl_uint>(last_n),\n                                      q,\n                                      p\n                              ));\n    }\n    else\n    {\n        viennacl::ocl::kernel& kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::svd<SCALARTYPE, column_major>::program_name(), SVD_FINAL_ITER_UPDATE_KERNEL);\n\n        viennacl::ocl::enqueue(kernel(\n                                      A,\n                                      static_cast<cl_uint>(A.internal_size1()),\n                                      static_cast<cl_uint>(n),\n                                      static_cast<cl_uint>(last_n),\n                                      q,\n                                      p\n                              ));\n    }\n#endif\n}\ntemplate <typename SCALARTYPE, typename VectorType>\nvoid update_float_QR_column_gpu(matrix_base<SCALARTYPE> & A,\n                        const VectorType& buf,\n                        viennacl::vector<SCALARTYPE>& buf_vcl,\n                        int m,\n                        int n,\n                        int last_n,\n                        bool //is_triangular\n                        )\n{\n  (void)A; (void)buf; (void)buf_vcl; (void)m; (void)n; (void)last_n;\n#ifdef VIENNACL_WITH_OPENCL\n  viennacl::ocl::context & ctx = const_cast<viennacl::ocl::context &>(viennacl::traits::opencl_handle(A).context());\n\n    viennacl::fast_copy(buf, buf_vcl);\n\n    if(A.row_major())\n    {\n        viennacl::ocl::kernel& kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::svd<SCALARTYPE, row_major>::program_name(), SVD_UPDATE_QR_COLUMN_KERNEL);\n\n        viennacl::ocl::enqueue(kernel(\n                                      A,\n                                      static_cast<cl_uint>(A.internal_size1()),\n                                      buf_vcl,\n                                      static_cast<cl_uint>(m),\n                                      static_cast<cl_uint>(n),\n                                      static_cast<cl_uint>(last_n)\n                              ));\n    }\n    else\n    {\n        viennacl::ocl::kernel& kernel = ctx.get_kernel(viennacl::linalg::opencl::kernels::svd<SCALARTYPE, column_major>::program_name(), SVD_UPDATE_QR_COLUMN_KERNEL);\n\n        viennacl::ocl::enqueue(kernel(\n                                      A,\n                                      static_cast<cl_uint>(A.internal_size1()),\n                                      buf_vcl,\n                                      static_cast<cl_uint>(m),\n                                      static_cast<cl_uint>(n),\n                                      static_cast<cl_uint>(last_n)\n                              ));\n    }\n\n#endif\n}\n\n    template<typename SCALARTYPE, typename MatrixT>\n    void final_iter_update(MatrixT& A,\n                            int n,\n                            int last_n,\n                            SCALARTYPE q,\n                            SCALARTYPE p\n                            )\n    {\n        for (int i = 0; i < last_n; i++)\n        {\n            SCALARTYPE v_in = A(i, n);\n            SCALARTYPE z = A(i, n - 1);\n            A(i, n - 1) = q * z + p * v_in;\n            A(i, n) = q * v_in - p * z;\n        }\n    }\n\n    template<typename SCALARTYPE, typename MatrixT>\n    void update_float_QR_column(MatrixT& A,\n                            const std::vector<SCALARTYPE>& buf,\n                            int m,\n                            int n,\n                            int last_i,\n                            bool is_triangular\n                            )\n    {\n        for (int i = 0; i < last_i; i++)\n        {\n            int start_k = is_triangular?std::max(i + 1, m):m;\n\n            SCALARTYPE* a_row = A.row(i);\n\n            SCALARTYPE a_ik   = a_row[start_k];\n            SCALARTYPE a_ik_1 = 0;\n            SCALARTYPE a_ik_2 = 0;\n\n            if (start_k < n)\n                a_ik_1 = a_row[start_k + 1];\n\n            for (int k = start_k; k < n; k++)\n            {\n                bool notlast = (k != n - 1);\n\n                SCALARTYPE p = buf[5 * static_cast<vcl_size_t>(k)] * a_ik + buf[5 * static_cast<vcl_size_t>(k) + 1] * a_ik_1;\n\n                if (notlast)\n                {\n                    a_ik_2 = a_row[k + 2];\n                    p = p + buf[5 * static_cast<vcl_size_t>(k) + 2] * a_ik_2;\n                    a_ik_2 = a_ik_2 - p * buf[5 * static_cast<vcl_size_t>(k) + 4];\n                }\n\n                a_row[k] = a_ik - p;\n                a_ik_1 = a_ik_1 - p * buf[5 * static_cast<vcl_size_t>(k) + 3];\n\n                a_ik = a_ik_1;\n                a_ik_1 = a_ik_2;\n            }\n\n            if (start_k < n)\n                a_row[n] = a_ik;\n        }\n    }\n\n    /** @brief Internal helper class representing a row-major dense matrix used for the QR method for the purpose of computing eigenvalues. */\n    template<typename SCALARTYPE>\n    class FastMatrix\n    {\n    public:\n        FastMatrix()\n        {\n            size_ = 0;\n        }\n\n        FastMatrix(vcl_size_t sz, vcl_size_t internal_size) : size_(sz), internal_size_(internal_size)\n        {\n            data.resize(internal_size * internal_size);\n        }\n\n        SCALARTYPE& operator()(int i, int j)\n        {\n            return data[static_cast<vcl_size_t>(i) * internal_size_ + static_cast<vcl_size_t>(j)];\n        }\n\n        SCALARTYPE* row(int i)\n        {\n            return &data[static_cast<vcl_size_t>(i) * internal_size_];\n        }\n\n        SCALARTYPE* begin()\n        {\n            return &data[0];\n        }\n\n        SCALARTYPE* end()\n        {\n            return &data[0] + data.size();\n        }\n\n        std::vector<SCALARTYPE> data;\n    private:\n        vcl_size_t size_;\n        vcl_size_t internal_size_;\n    };\n\n    // Nonsymmetric reduction from Hessenberg to real Schur form.\n    // This is derived from the Algol procedure hqr2, by Martin and Wilkinson, Handbook for Auto. Comp.,\n    // Vol.ii-Linear Algebra, and the corresponding  Fortran subroutine in EISPACK.\n    template <typename SCALARTYPE, typename VectorType>\n    void hqr2(viennacl::matrix<SCALARTYPE>& vcl_H,\n                viennacl::matrix<SCALARTYPE>& V,\n                VectorType & d,\n                VectorType & e)\n    {\n        transpose(V);\n\n        int nn = static_cast<int>(vcl_H.size1());\n\n        FastMatrix<SCALARTYPE> H(vcl_size_t(nn), vcl_H.internal_size2());//, V(nn);\n\n        std::vector<SCALARTYPE>  buf(5 * vcl_size_t(nn));\n        //boost::numeric::ublas::vector<float>  buf(5 * nn);\n        viennacl::vector<SCALARTYPE> buf_vcl(5 * vcl_size_t(nn));\n\n        viennacl::fast_copy(vcl_H, H.begin());\n\n\n        int n = nn - 1;\n\n        SCALARTYPE eps = 2 * static_cast<SCALARTYPE>(EPS);\n        SCALARTYPE exshift = 0;\n        SCALARTYPE p = 0;\n        SCALARTYPE q = 0;\n        SCALARTYPE r = 0;\n        SCALARTYPE s = 0;\n        SCALARTYPE z = 0;\n        SCALARTYPE t;\n        SCALARTYPE w;\n        SCALARTYPE x;\n        SCALARTYPE y;\n\n        SCALARTYPE out1, out2;\n\n        // compute matrix norm\n        SCALARTYPE norm = 0;\n        for (int i = 0; i < nn; i++)\n        {\n            for (int j = std::max(i - 1, 0); j < nn; j++)\n                norm = norm + std::fabs(H(i, j));\n        }\n\n        // Outer loop over eigenvalue index\n        int iter = 0;\n        while (n >= 0)\n        {\n            // Look for single small sub-diagonal element\n            int l = n;\n            while (l > 0)\n            {\n                s = std::fabs(H(l - 1, l - 1)) + std::fabs(H(l, l));\n                if (s <= 0)\n                  s = norm;\n                if (std::fabs(H(l, l - 1)) < eps * s)\n                  break;\n\n                l--;\n            }\n\n            // Check for convergence\n            if (l == n)\n            {\n                // One root found\n                H(n, n) = H(n, n) + exshift;\n                d[vcl_size_t(n)] = H(n, n);\n                e[vcl_size_t(n)] = 0;\n                n--;\n                iter = 0;\n            }\n            else if (l == n - 1)\n            {\n                // Two roots found\n                w = H(n, n - 1) * H(n - 1, n);\n                p = (H(n - 1, n - 1) - H(n, n)) / 2;\n                q = p * p + w;\n                z = static_cast<SCALARTYPE>(std::sqrt(std::fabs(q)));\n                H(n, n) = H(n, n) + exshift;\n                H(n - 1, n - 1) = H(n - 1, n - 1) + exshift;\n                x = H(n, n);\n\n                if (q >= 0)\n                {\n                    // Real pair\n                    z = (p >= 0) ? (p + z) : (p - z);\n                    d[vcl_size_t(n) - 1] = x + z;\n                    d[vcl_size_t(n)] = d[vcl_size_t(n) - 1];\n                    if (z <= 0 && z >= 0) // z == 0 without compiler complaints\n                      d[vcl_size_t(n)] = x - w / z;\n                    e[vcl_size_t(n) - 1] = 0;\n                    e[vcl_size_t(n)] = 0;\n                    x = H(n, n - 1);\n                    s = std::fabs(x) + std::fabs(z);\n                    p = x / s;\n                    q = z / s;\n                    r = static_cast<SCALARTYPE>(std::sqrt(p * p + q * q));\n                    p = p / r;\n                    q = q / r;\n\n                    // Row modification\n                    for (int j = n - 1; j < nn; j++)\n                    {\n                        SCALARTYPE h_nj = H(n, j);\n                        z = H(n - 1, j);\n                        H(n - 1, j) = q * z + p * h_nj;\n                        H(n, j) = q * h_nj - p * z;\n                    }\n\n                    final_iter_update(H, n, n + 1, q, p);\n                    final_iter_update_gpu(V, n, nn, q, p);\n                }\n                else\n                {\n                    // Complex pair\n                    d[vcl_size_t(n) - 1] = x + p;\n                    d[vcl_size_t(n)] = x + p;\n                    e[vcl_size_t(n) - 1] = z;\n                    e[vcl_size_t(n)] = -z;\n                }\n\n                n = n - 2;\n                iter = 0;\n            }\n            else\n            {\n                // No convergence yet\n\n                // Form shift\n                x = H(n, n);\n                y = 0;\n                w = 0;\n                if (l < n)\n                {\n                    y = H(n - 1, n - 1);\n                    w = H(n, n - 1) * H(n - 1, n);\n                }\n\n                // Wilkinson's original ad hoc shift\n                if (iter == 10)\n                {\n                    exshift += x;\n                    for (int i = 0; i <= n; i++)\n                        H(i, i) -= x;\n\n                    s = std::fabs(H(n, n - 1)) + std::fabs(H(n - 1, n - 2));\n                    x = y = SCALARTYPE(0.75) * s;\n                    w = SCALARTYPE(-0.4375) * s * s;\n                }\n\n                // MATLAB's new ad hoc shift\n                if (iter == 30)\n                {\n                    s = (y - x) / 2;\n                    s = s * s + w;\n                    if (s > 0)\n                    {\n                        s = static_cast<SCALARTYPE>(std::sqrt(s));\n                        if (y < x) s = -s;\n                        s = x - w / ((y - x) / 2 + s);\n                        for (int i = 0; i <= n; i++)\n                            H(i, i) -= s;\n                        exshift += s;\n                        x = y = w = SCALARTYPE(0.964);\n                    }\n                }\n\n                iter = iter + 1;\n\n                // Look for two consecutive small sub-diagonal elements\n                int m = n - 2;\n                while (m >= l)\n                {\n                    SCALARTYPE h_m1_m1 = H(m + 1, m + 1);\n                    z = H(m, m);\n                    r = x - z;\n                    s = y - z;\n                    p = (r * s - w) / H(m + 1, m) + H(m, m + 1);\n                    q = h_m1_m1 - z - r - s;\n                    r = H(m + 2, m + 1);\n                    s = std::fabs(p) + std::fabs(q) + std::fabs(r);\n                    p = p / s;\n                    q = q / s;\n                    r = r / s;\n                    if (m == l)\n                        break;\n                    if (std::fabs(H(m, m - 1)) * (std::fabs(q) + std::fabs(r)) < eps * (std::fabs(p) * (std::fabs(H(m - 1, m - 1)) + std::fabs(z) + std::fabs(h_m1_m1))))\n                        break;\n                    m--;\n                }\n\n                for (int i = m + 2; i <= n; i++)\n                {\n                    H(i, i - 2) = 0;\n                    if (i > m + 2)\n                        H(i, i - 3) = 0;\n                }\n\n                // float QR step involving rows l:n and columns m:n\n                for (int k = m; k < n; k++)\n                {\n                    bool notlast = (k != n - 1);\n                    if (k != m)\n                    {\n                        p = H(k, k - 1);\n                        q = H(k + 1, k - 1);\n                        r = (notlast ? H(k + 2, k - 1) : 0);\n                        x = std::fabs(p) + std::fabs(q) + std::fabs(r);\n                        if (x > 0)\n                        {\n                            p = p / x;\n                            q = q / x;\n                            r = r / x;\n                        }\n                    }\n\n                    if (x <= 0 && x >= 0) break;  // x == 0 without compiler complaints\n\n                    s = static_cast<SCALARTYPE>(std::sqrt(p * p + q * q + r * r));\n                    if (p < 0) s = -s;\n\n                    if (s < 0 || s > 0)\n                    {\n                        if (k != m)\n                            H(k, k - 1) = -s * x;\n                        else\n                            if (l != m)\n                                H(k, k - 1) = -H(k, k - 1);\n\n                        p = p + s;\n                        y = q / s;\n                        z = r / s;\n                        x = p / s;\n                        q = q / p;\n                        r = r / p;\n\n                        buf[5 * vcl_size_t(k)] = x;\n                        buf[5 * vcl_size_t(k) + 1] = y;\n                        buf[5 * vcl_size_t(k) + 2] = z;\n                        buf[5 * vcl_size_t(k) + 3] = q;\n                        buf[5 * vcl_size_t(k) + 4] = r;\n\n\n                        SCALARTYPE* a_row_k = H.row(k);\n                        SCALARTYPE* a_row_k_1 = H.row(k + 1);\n                        SCALARTYPE* a_row_k_2 = H.row(k + 2);\n                        // Row modification\n                        for (int j = k; j < nn; j++)\n                        {\n                            SCALARTYPE h_kj = a_row_k[j];\n                            SCALARTYPE h_k1_j = a_row_k_1[j];\n\n                            p = h_kj + q * h_k1_j;\n                            if (notlast)\n                            {\n                                SCALARTYPE h_k2_j = a_row_k_2[j];\n                                p = p + r * h_k2_j;\n                                a_row_k_2[j] = h_k2_j - p * z;\n                            }\n\n                            a_row_k[j] = h_kj - p * x;\n                            a_row_k_1[j] = h_k1_j - p * y;\n                        }\n\n                        //H(k + 1, nn - 1) = h_kj;\n\n\n                        // Column modification\n                        for (int i = k; i < std::min(nn, k + 4); i++)\n                        {\n                            p = x * H(i, k) + y * H(i, k + 1);\n                            if (notlast)\n                            {\n                                p = p + z * H(i, k + 2);\n                                H(i, k + 2) = H(i, k + 2) - p * r;\n                            }\n\n                            H(i, k) = H(i, k) - p;\n                            H(i, k + 1) = H(i, k + 1) - p * q;\n                        }\n                    }\n                    else\n                    {\n                        buf[5 * vcl_size_t(k)] = 0;\n                        buf[5 * vcl_size_t(k) + 1] = 0;\n                        buf[5 * vcl_size_t(k) + 2] = 0;\n                        buf[5 * vcl_size_t(k) + 3] = 0;\n                        buf[5 * vcl_size_t(k) + 4] = 0;\n                    }\n                }\n\n                // Timer timer;\n                // timer.start();\n\n                update_float_QR_column<SCALARTYPE>(H, buf, m, n, n, true);\n                update_float_QR_column_gpu(V, buf, buf_vcl, m, n, nn, false);\n\n                // std::cout << timer.get() << \"\\n\";\n            }\n        }\n\n        // Backsubstitute to find vectors of upper triangular form\n        if (norm <= 0)\n        {\n            return;\n        }\n\n        for (n = nn - 1; n >= 0; n--)\n        {\n            p = d[vcl_size_t(n)];\n            q = e[vcl_size_t(n)];\n\n            // Real vector\n            if (q <= 0 && q >= 0)\n            {\n                int l = n;\n                H(n, n) = 1;\n                for (int i = n - 1; i >= 0; i--)\n                {\n                    w = H(i, i) - p;\n                    r = 0;\n                    for (int j = l; j <= n; j++)\n                        r = r + H(i, j) * H(j, n);\n\n                    if (e[vcl_size_t(i)] < 0)\n                    {\n                        z = w;\n                        s = r;\n                    }\n                    else\n                    {\n                        l = i;\n                        if (e[vcl_size_t(i)] <= 0) // e[i] == 0 with previous if\n                        {\n                            H(i, n) = (w > 0 || w < 0) ? (-r / w) : (-r / (eps * norm));\n                        }\n                        else\n                        {\n                            // Solve real equations\n                            x = H(i, i + 1);\n                            y = H(i + 1, i);\n                            q = (d[vcl_size_t(i)] - p) * (d[vcl_size_t(i)] - p) + e[vcl_size_t(i)] * e[vcl_size_t(i)];\n                            t = (x * s - z * r) / q;\n                            H(i, n) = t;\n                            H(i + 1, n) = (std::fabs(x) > std::fabs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z);\n                        }\n\n                        // Overflow control\n                        t = std::fabs(H(i, n));\n                        if ((eps * t) * t > 1)\n                            for (int j = i; j <= n; j++)\n                                H(j, n) /= t;\n                    }\n                }\n            }\n            else if (q < 0)\n            {\n                // Complex vector\n                int l = n - 1;\n\n                // Last vector component imaginary so matrix is triangular\n                if (std::fabs(H(n, n - 1)) > std::fabs(H(n - 1, n)))\n                {\n                    H(n - 1, n - 1) = q / H(n, n - 1);\n                    H(n - 1, n) = -(H(n, n) - p) / H(n, n - 1);\n                }\n                else\n                {\n                    cdiv<SCALARTYPE>(0, -H(n - 1, n), H(n - 1, n - 1) - p, q, out1, out2);\n\n                    H(n - 1, n - 1) = out1;\n                    H(n - 1, n) = out2;\n                }\n\n                H(n, n - 1) = 0;\n                H(n, n) = 1;\n                for (int i = n - 2; i >= 0; i--)\n                {\n                    SCALARTYPE ra, sa, vr, vi;\n                    ra = 0;\n                    sa = 0;\n                    for (int j = l; j <= n; j++)\n                    {\n                        SCALARTYPE h_ij = H(i, j);\n                        ra = ra + h_ij * H(j, n - 1);\n                        sa = sa + h_ij * H(j, n);\n                    }\n\n                    w = H(i, i) - p;\n\n                    if (e[vcl_size_t(i)] < 0)\n                    {\n                        z = w;\n                        r = ra;\n                        s = sa;\n                    }\n                    else\n                    {\n                        l = i;\n                        if (e[vcl_size_t(i)] <= 0) // e[i] == 0 with previous if\n                        {\n                            cdiv<SCALARTYPE>(-ra, -sa, w, q, out1, out2);\n                            H(i, n - 1) = out1;\n                            H(i, n) = out2;\n                        }\n                        else\n                        {\n                            // Solve complex equations\n                            x = H(i, i + 1);\n                            y = H(i + 1, i);\n                            vr = (d[vcl_size_t(i)] - p) * (d[vcl_size_t(i)] - p) + e[vcl_size_t(i)] * e[vcl_size_t(i)] - q * q;\n                            vi = (d[vcl_size_t(i)] - p) * 2 * q;\n                            if ( (vr <= 0 && vr >= 0) && (vi <= 0 && vi >= 0) )\n                                vr = eps * norm * (std::fabs(w) + std::fabs(q) + std::fabs(x) + std::fabs(y) + std::fabs(z));\n\n                            cdiv<SCALARTYPE>(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi, out1, out2);\n\n                            H(i, n - 1) = out1;\n                            H(i, n) = out2;\n\n\n                            if (std::fabs(x) > (std::fabs(z) + std::fabs(q)))\n                            {\n                                H(i + 1, n - 1) = (-ra - w * H(i, n - 1) + q * H(i, n)) / x;\n                                H(i + 1, n) = (-sa - w * H(i, n) - q * H(i, n - 1)) / x;\n                            }\n                            else\n                            {\n                                cdiv<SCALARTYPE>(-r - y * H(i, n - 1), -s - y * H(i, n), z, q, out1, out2);\n\n                                H(i + 1, n - 1) = out1;\n                                H(i + 1, n) = out2;\n                            }\n                        }\n\n                        // Overflow control\n                        t = std::max(std::fabs(H(i, n - 1)), std::fabs(H(i, n)));\n                        if ((eps * t) * t > 1)\n                        {\n                            for (int j = i; j <= n; j++)\n                            {\n                                H(j, n - 1) /= t;\n                                H(j, n) /= t;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n        viennacl::fast_copy(H.begin(), H.end(),  vcl_H);\n        // viennacl::fast_copy(V.begin(), V.end(),  vcl_V);\n\n        viennacl::matrix<SCALARTYPE> tmp = V;\n\n        V = viennacl::linalg::prod(trans(tmp), vcl_H);\n    }\n\n\n    template <typename SCALARTYPE>\n    bool householder_twoside(\n                        matrix_base<SCALARTYPE>& A,\n                        matrix_base<SCALARTYPE>& Q,\n                        vector_base<SCALARTYPE>& D,\n                        vcl_size_t start)\n    {\n        vcl_size_t A_size1 = static_cast<vcl_size_t>(viennacl::traits::size1(A));\n        if(start + 2 >= A_size1)\n            return false;\n\n        prepare_householder_vector(A, D, A_size1, start + 1, start, start + 1, true);\n        viennacl::linalg::house_update_A_left(A, D, start);\n        viennacl::linalg::house_update_A_right(A, D);\n        viennacl::linalg::house_update_QL(Q, D, A_size1);\n\n        return true;\n    }\n\n    template <typename SCALARTYPE>\n    void tridiagonal_reduction(matrix_base<SCALARTYPE>& A,\n                               matrix_base<SCALARTYPE>& Q)\n    {\n        vcl_size_t sz = A.size1();\n\n        viennacl::vector<SCALARTYPE> hh_vector(sz);\n\n        for(vcl_size_t i = 0; i < sz; i++)\n        {\n            householder_twoside(A, Q, hh_vector, i);\n        }\n\n    }\n\n    template <typename SCALARTYPE>\n    void qr_method(viennacl::matrix<SCALARTYPE> & A,\n                   viennacl::matrix<SCALARTYPE> & Q,\n                   std::vector<SCALARTYPE> & D,\n                   std::vector<SCALARTYPE> & E,\n                   bool is_symmetric = true)\n    {\n\n        assert(A.size1() == A.size2() && bool(\"Input matrix must be square for QR method!\"));\n    /*    if (!viennacl::is_row_major<F>::value && !is_symmetric)\n        {\n          std::cout << \"qr_method for non-symmetric column-major matrices not implemented yet!\" << std::endl;\n          exit(EXIT_FAILURE);\n        }\n\n        */\n        vcl_size_t mat_size = A.size1();\n        D.resize(A.size1());\n        E.resize(A.size1());\n\n        viennacl::vector<SCALARTYPE> vcl_D(mat_size), vcl_E(mat_size);\n        //std::vector<SCALARTYPE> std_D(mat_size), std_E(mat_size);\n\n        Q = viennacl::identity_matrix<SCALARTYPE>(Q.size1());\n\n        // reduce to tridiagonal form\n        detail::tridiagonal_reduction(A, Q);\n\n        // pack diagonal and super-diagonal\n        viennacl::linalg::bidiag_pack(A, vcl_D, vcl_E);\n        copy(vcl_D, D);\n        copy(vcl_E, E);\n\n        // find eigenvalues of symmetric tridiagonal matrix\n        if(is_symmetric)\n        {\n          viennacl::linalg::tql2(Q, D, E);\n\n        }\n        else\n        {\n              detail::hqr2(A, Q, D, E);\n        }\n\n\n        boost::numeric::ublas::matrix<SCALARTYPE> eigen_values(A.size1(), A.size1());\n        eigen_values.clear();\n\n        for (vcl_size_t i = 0; i < A.size1(); i++)\n        {\n            if(std::fabs(E[i]) < EPS)\n            {\n                eigen_values(i, i) = D[i];\n            }\n            else\n            {\n                eigen_values(i, i) = D[i];\n                eigen_values(i, i + 1) = E[i];\n                eigen_values(i + 1, i) = -E[i];\n                eigen_values(i + 1, i + 1) = D[i];\n                i++;\n            }\n        }\n\n        copy(eigen_values, A);\n    }\n}\n\ntemplate <typename SCALARTYPE>\nvoid qr_method_nsm(viennacl::matrix<SCALARTYPE>& A,\n                   viennacl::matrix<SCALARTYPE>& Q,\n                   std::vector<SCALARTYPE>& D,\n                   std::vector<SCALARTYPE>& E\n                  )\n{\n    detail::qr_method(A, Q, D, E, false);\n}\n\ntemplate <typename SCALARTYPE>\nvoid qr_method_sym(viennacl::matrix<SCALARTYPE>& A,\n                   viennacl::matrix<SCALARTYPE>& Q,\n                   std::vector<SCALARTYPE>& D\n                  )\n{\n    std::vector<SCALARTYPE> E(A.size1());\n\n    detail::qr_method(A, Q, D, E, true);\n}\n\ntemplate <typename SCALARTYPE>\nvoid qr_method_sym(viennacl::matrix<SCALARTYPE>& A,\n                   viennacl::matrix<SCALARTYPE>& Q,\n                   viennacl::vector_base<SCALARTYPE>& D\n                  )\n{\n    std::vector<SCALARTYPE> std_D(D.size());\n    std::vector<SCALARTYPE> E(A.size1());\n\n    viennacl::copy(D, std_D);\n    detail::qr_method(A, Q, std_D, E, true);\n    viennacl::copy(std_D, D);\n}\n\n}\n}\n\n#endif\n", "meta": {"hexsha": "a7e07db28e7dd2e1ed495326dda129236c6c0e18", "size": 28413, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "viennacl/linalg/qr-method.hpp", "max_stars_repo_name": "yuchengs/viennacl-dev", "max_stars_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224.0, "max_stars_repo_stars_event_min_datetime": "2015-02-15T21:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:27:03.000Z", "max_issues_repo_path": "viennacl/linalg/qr-method.hpp", "max_issues_repo_name": "yuchengs/viennacl-dev", "max_issues_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 189.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T17:08:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T06:23:22.000Z", "max_forks_repo_path": "viennacl/linalg/qr-method.hpp", "max_forks_repo_name": "yuchengs/viennacl-dev", "max_forks_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 84.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T14:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:51:17.000Z", "avg_line_length": 34.0683453237, "max_line_length": 169, "alphanum_fraction": 0.3582163094, "num_tokens": 7277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.24591929035501642}}
{"text": "#ifndef PARMCB_MPI_SVA_SIGNED_HPP_\n#define PARMCB_MPI_SVA_SIGNED_HPP_\n\n//    Copyright (C) Dimitrios Michail 2019 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#include <cstddef>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <set>\n#include <vector>\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/tuple/detail/tuple_basic.hpp>\n\n#include <boost/mpi/environment.hpp>\n#include <boost/mpi/communicator.hpp>\n#include <boost/mpi/collectives.hpp>\n#include <boost/mpi/timer.hpp>\n\n#include <tbb/concurrent_vector.h>\n#include <tbb/parallel_for.h>\n#include <tbb/parallel_reduce.h>\n\n#include <parmcb/detail/signed_dijkstra.hpp>\n#include <parmcb/mpi/sptrees.hpp>\n#include <parmcb/forestindex.hpp>\n#include <parmcb/spvecgf2.hpp>\n#include <parmcb/util.hpp>\n\nnamespace parmcb {\n\n    namespace detail {\n\n        template<class Graph, class WeightMap>\n        std::tuple<std::set<typename boost::graph_traits<Graph>::edge_descriptor>,\n                typename boost::property_traits<WeightMap>::value_type, bool> find_shortest_odd_cycle_mpi(\n                const Graph &g, const WeightMap &weight_map,\n                const std::vector<typename boost::graph_traits<Graph>::vertex_descriptor> &allVertices,\n                const ForestIndex<Graph> &forest_index,\n                const std::set<typename boost::graph_traits<Graph>::edge_descriptor> &signed_edges,\n                boost::mpi::communicator &world) {\n\n            typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n            typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n            typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n            std::less<WeightType> compare = std::less<WeightType>();\n            std::tuple<std::set<Edge>, WeightType, bool> best = std::make_tuple(std::set<Edge> { },\n                    (std::numeric_limits<WeightType>::max)(), false);\n            typedef std::tuple<std::set<Edge>, WeightType, bool> cycle_t;\n            auto cycle_min = [compare](const cycle_t &c1, const cycle_t &c2) {\n                if (!std::get<2>(c1) || !std::get<2>(c2)) {\n                    if (std::get<2>(c1)) {\n                        return c1;\n                    } else {\n                        return c2;\n                    }\n                }\n                // both valid, compare\n                if (!compare(std::get<1>(c2), std::get<1>(c1))) {\n                    return c1;\n                }\n                return c2;\n            };\n\n            if (signed_edges.size() == 1) {\n                if (world.rank() == 0) {\n                    auto se = *signed_edges.begin();\n                    auto se_v = boost::source(se, g);\n                    auto se_u = boost::target(se, g);\n                    auto res = bidirectional_signed_dijkstra(g, weight_map, std::set<Edge> { }, signed_edges, true,\n                            se_v, true, se_u, true, std::get<2>(best), std::get<1>(best));\n                    if (std::get<2>(res) && std::get<0>(res).find(se) == std::get<0>(res).end()) {\n                        std::get<1>(res) += boost::get(weight_map, se);\n                        if (!std::get<2>(best) || compare(std::get<1>(res), std::get<1>(best))) {\n                            std::get<0>(res).insert(se);\n                            best = res;\n                            assert(std::get<2>(best));\n                        }\n                    }\n                }\n            } else if (signed_edges.size() < boost::num_vertices(g)) {\n                /*\n                 * Heuristic in case number of signed edges is small compared to the number of vertices.\n                 */\n                std::map<Edge, std::set<Edge>> hidden_edges_per_edge;\n                std::vector<Edge> signed_edges_as_vector;\n                std::set<Edge> tmp_signed_edges = signed_edges;\n                while (!tmp_signed_edges.empty()) {\n                    auto bit = tmp_signed_edges.begin();\n                    hidden_edges_per_edge.insert(std::make_pair(*bit, tmp_signed_edges));\n                    signed_edges_as_vector.push_back(*bit);\n                    tmp_signed_edges.erase(bit);\n                }\n\n                std::vector<Edge> local_signed_edges_as_vector;\n                std::size_t total = signed_edges_as_vector.size();\n                std::size_t stride = ceil((double) total / world.size());\n                std::size_t istart = world.rank() * stride;\n                std::size_t iend = istart + stride;\n                for (std::size_t i = istart; i < iend && i < total; i++) {\n                    local_signed_edges_as_vector.push_back(signed_edges_as_vector[i]);\n                }\n\n                std::tuple<std::set<Edge>, WeightType, bool> best_local_cycle = tbb::parallel_reduce(\n                        tbb::blocked_range<std::size_t>(0, local_signed_edges_as_vector.size()),\n                        std::make_tuple(std::set<Edge>(), (std::numeric_limits<WeightType>::max)(), false),\n                        [&](tbb::blocked_range<std::size_t> r, auto running_min) {\n                            for (std::size_t i = r.begin(); i < r.end(); i++) {\n                                auto se = local_signed_edges_as_vector.at(i);\n                                auto se_v = boost::source(se, g);\n                                auto se_u = boost::target(se, g);\n                                auto hidden_edges = hidden_edges_per_edge.at(se);\n                                auto res = bidirectional_signed_dijkstra(g, weight_map, signed_edges, hidden_edges,\n                                        true, se_v, true, se_u, true, std::get<2>(running_min),\n                                        std::get<1>(running_min));\n                                if (std::get<2>(res) && std::get<0>(res).find(se) == std::get<0>(res).end()) {\n                                    std::get<1>(res) += boost::get(weight_map, se);\n                                    if (!std::get<2>(running_min)\n                                            || compare(std::get<1>(res), std::get<1>(running_min))) {\n                                        std::get<0>(res).insert(se);\n                                        running_min = res;\n                                    }\n                                }\n                            }\n                            return running_min;\n                        },\n                        cycle_min);\n\n                std::vector<typename ForestIndex<Graph>::size_type> best_local_cycle_as_indices;\n                convert_edges(std::get<0>(best_local_cycle),\n                        std::inserter(best_local_cycle_as_indices, best_local_cycle_as_indices.end()), forest_index);\n                SerializableMinOddCycle<Graph, WeightMap> local_min_odd_cycle(best_local_cycle_as_indices,\n                        std::get<1>(best_local_cycle), std::get<2>(best_local_cycle));\n                SerializableMinOddCycle<Graph, WeightMap> global_min_odd_cycle;\n\n                boost::mpi::reduce(world, local_min_odd_cycle, global_min_odd_cycle,\n                        SerializableMinOddCycleMinOp<Graph, WeightMap>(), 0);\n\n                convert_edges(global_min_odd_cycle.edges, std::inserter(std::get<0>(best), std::get<0>(best).end()),\n                        forest_index);\n                std::get<1>(best) = global_min_odd_cycle.weight;\n                std::get<2>(best) = global_min_odd_cycle.exists;\n            } else {\n                // split implicitly all vertices\n                std::vector<Vertex> localVertices;\n                std::size_t stride = ceil((double) allVertices.size() / world.size());\n                std::size_t istart = world.rank() * stride;\n                std::size_t iend = istart + stride;\n                std::size_t total = allVertices.size();\n                for (std::size_t i = istart; i < iend && i < total; i++) {\n                    localVertices.push_back(allVertices[i]);\n                }\n\n                std::tuple<std::set<Edge>, WeightType, bool> best_local_cycle = tbb::parallel_reduce(\n                        tbb::blocked_range<std::size_t>(0, localVertices.size()),\n                        std::make_tuple(std::set<Edge>(), (std::numeric_limits<WeightType>::max)(), false),\n                        [&](tbb::blocked_range<std::size_t> r, auto running_min) {\n                            for (std::size_t i = r.begin(); i < r.end(); i++) {\n                                auto v = localVertices[i];\n                                const bool use_hidden_edges = false;\n                                auto res = bidirectional_signed_dijkstra(g, weight_map, signed_edges,\n                                        std::set<Edge> { }, use_hidden_edges, v, true, v, false,\n                                        std::get<2>(running_min), std::get<1>(running_min));\n                                if (std::get<2>(res)\n                                        && (!std::get<2>(running_min)\n                                                || compare(std::get<1>(res), std::get<1>(running_min)))) {\n                                    running_min = res;\n                                }\n                            }\n                            return running_min;\n                        },\n                        cycle_min);\n\n                std::vector<typename ForestIndex<Graph>::size_type> best_local_cycle_as_indices;\n                convert_edges(std::get<0>(best_local_cycle),\n                        std::inserter(best_local_cycle_as_indices, best_local_cycle_as_indices.end()), forest_index);\n                SerializableMinOddCycle<Graph, WeightMap> local_min_odd_cycle(best_local_cycle_as_indices,\n                        std::get<1>(best_local_cycle), std::get<2>(best_local_cycle));\n                SerializableMinOddCycle<Graph, WeightMap> global_min_odd_cycle;\n\n                boost::mpi::reduce(world, local_min_odd_cycle, global_min_odd_cycle,\n                        SerializableMinOddCycleMinOp<Graph, WeightMap>(), 0);\n\n                convert_edges(global_min_odd_cycle.edges, std::inserter(std::get<0>(best), std::get<0>(best).end()),\n                        forest_index);\n                std::get<1>(best) = global_min_odd_cycle.weight;\n                std::get<2>(best) = global_min_odd_cycle.exists;\n            }\n\n            return best;\n        }\n\n    } // detail\n\n    template<class Graph, class WeightMap, class CycleOutputIterator>\n    typename boost::property_traits<WeightMap>::value_type mcb_sva_signed_mpi(const Graph &g, WeightMap weight_map,\n            CycleOutputIterator out, boost::mpi::communicator &world, const std::size_t hardware_concurrency_hint = 0) {\n\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIt;\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n        /*\n         * Index the graph\n         */\n        ForestIndex<Graph> forest_index(g);\n        auto csd = forest_index.cycle_space_dimension();\n        std::vector<Vertex> vertices;\n        {\n            VertexIt vi, viend;\n            for (boost::tie(vi, viend) = boost::vertices(g); vi != viend; ++vi) {\n                vertices.push_back(*vi);\n            }\n        }\n\n        /*\n         * Initialize support vectors\n         */\n        tbb::concurrent_vector<SpVecGF2<std::size_t>> support;\n        tbb::parallel_for(tbb::blocked_range<std::size_t>(0, csd), [&](const tbb::blocked_range<std::size_t> &r) {\n            for (std::size_t i = r.begin(); i != r.end(); ++i) {\n                support.push_back(SpVecGF2<std::size_t> { i });\n            }\n        });\n\n        boost::mpi::timer total_timer;\n\n        /*\n         * Main loop\n         */\n        WeightType mcb_weight = WeightType();\n        for (std::size_t k = 0; k < csd; k++) {\n            if (k % 250 == 0) {\n                std::cout << \"Rank \" << world.rank() << \" at cycle \" << k << std::endl;\n            }\n\n            // TODO: check if sparsest support heuristic makes sense here\n\n            // broadcast support vector\n            if (world.rank() == 0) {\n                boost::mpi::broadcast(world, support[k], 0);\n            } else {\n                SpVecGF2<std::size_t> received;\n                boost::mpi::broadcast(world, received, 0);\n                support[k] = received;\n            }\n\n            std::set<Edge> signed_edges;\n            convert_edges(support[k], std::inserter(signed_edges, signed_edges.end()), forest_index);\n            std::tuple<std::set<Edge>, WeightType, bool> best = parmcb::detail::find_shortest_odd_cycle_mpi(g, weight_map,\n                    vertices, forest_index, signed_edges, world);\n\n            if (world.rank() == 0) {\n                /*\n                 * Update support vectors\n                 */\n                std::set<std::size_t> cyclek;\n                convert_edges(std::get<0>(best), std::inserter(cyclek, cyclek.end()), forest_index);\n                tbb::parallel_for(tbb::blocked_range<std::size_t>(k + 1, csd),\n                        [&](const tbb::blocked_range<std::size_t> &r) {\n                            auto e = r.end();\n                            for (std::size_t i = r.begin(); i != e; ++i) {\n                                if (support[i] * cyclek == 1) {\n                                    support[i] += support[k];\n                                }\n                            }\n                        });\n\n                /*\n                 * Output cycles\n                 */\n                std::list<Edge> cyclek_edgelist;\n                std::copy(std::get<0>(best).begin(), std::get<0>(best).end(), std::back_inserter(cyclek_edgelist));\n                *out++ = cyclek_edgelist;\n                mcb_weight += std::get<1>(best);\n            }\n\n        }\n\n        if (world.rank() == 0) {\n            std::cout << \"Total time: \" << total_timer.elapsed() << \" (sec)\" << std::endl;\n        }\n\n        return mcb_weight;\n    }\n\n} // namespace parmcb\n\n#endif\n", "meta": {"hexsha": "f25fa338cbb8b42d8641b77cd2b8ddc1967b3aa8", "size": 14313, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/parmcb/mpi/parmcb_sva_signed.hpp", "max_stars_repo_name": "d-michail/parmcb", "max_stars_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/parmcb/mpi/parmcb_sva_signed.hpp", "max_issues_repo_name": "d-michail/parmcb", "max_issues_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/parmcb/mpi/parmcb_sva_signed.hpp", "max_forks_repo_name": "d-michail/parmcb", "max_forks_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.0302013423, "max_line_length": 122, "alphanum_fraction": 0.51247118, "num_tokens": 3079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.2459129654649641}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017, 2018.\n// Modifications copyright (c) 2017, 2018, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 5.0.0\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_VANDG_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_VANDG_HPP\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace srs { namespace par4\n{\n    struct vandg {};\n\n}} //namespace srs::par4\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace vandg\n    {\n\n            static const double tolerance = 1.e-10;\n\n            template <typename T>\n            inline T C2_27() { return .07407407407407407407407407407407; }\n            template <typename T>\n            inline T PI4_3() { return boost::math::constants::four_thirds_pi<T>(); }\n            template <typename T>\n            inline T TPISQ() { return 19.739208802178717237668981999752; }\n            template <typename T>\n            inline T HPISQ() { return 4.9348022005446793094172454999381; }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_vandg_spheroid\n                : public base_t_fi<base_vandg_spheroid<T, Parameters>, T, Parameters>\n            {\n                inline base_vandg_spheroid(const Parameters& par)\n                    : base_t_fi<base_vandg_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n                    static const T pi = detail::pi<T>();\n\n                    T  al, al2, g, g2, p2;\n\n                    p2 = fabs(lp_lat / half_pi);\n                    if ((p2 - tolerance) > 1.) {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                    }\n                    if (p2 > 1.)\n                        p2 = 1.;\n                    if (fabs(lp_lat) <= tolerance) {\n                        xy_x = lp_lon;\n                        xy_y = 0.;\n                    } else if (fabs(lp_lon) <= tolerance || fabs(p2 - 1.) < tolerance) {\n                        xy_x = 0.;\n                        xy_y = pi * tan(.5 * asin(p2));\n                        if (lp_lat < 0.) xy_y = -xy_y;\n                    } else {\n                        al = .5 * fabs(pi / lp_lon - lp_lon / pi);\n                        al2 = al * al;\n                        g = sqrt(1. - p2 * p2);\n                        g = g / (p2 + g - 1.);\n                        g2 = g * g;\n                        p2 = g * (2. / p2 - 1.);\n                        p2 = p2 * p2;\n                        xy_x = g - p2; g = p2 + al2;\n                        xy_x = pi * (al * xy_x + sqrt(al2 * xy_x * xy_x - g * (g2 - p2))) / g;\n                        if (lp_lon < 0.) xy_x = -xy_x;\n                        xy_y = fabs(xy_x / pi);\n                        xy_y = 1. - xy_y * (xy_y + 2. * al);\n                        if (xy_y < -tolerance) {\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                        }\n                        if (xy_y < 0.)\n                            xy_y = 0.;\n                        else\n                            xy_y = sqrt(xy_y) * (lp_lat < 0. ? -pi : pi);\n                    }\n                }\n\n                // INVERSE(s_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n                    static const T pi = detail::pi<T>();\n                    static const T pi_sqr = detail::pi_sqr<T>();\n                    static const T third = detail::third<T>();\n                    static const T two_pi = detail::two_pi<T>();\n\n                    static const T C2_27 = vandg::C2_27<T>();\n                    static const T PI4_3 = vandg::PI4_3<T>();                    \n                    static const T TPISQ = vandg::TPISQ<T>();\n                    static const T HPISQ = vandg::HPISQ<T>();\n                    \n                    T t, c0, c1, c2, c3, al, r2, r, m, d, ay, x2, y2;\n\n                    x2 = xy_x * xy_x;\n                    if ((ay = fabs(xy_y)) < tolerance) {\n                        lp_lat = 0.;\n                        t = x2 * x2 + TPISQ * (x2 + HPISQ);\n                        lp_lon = fabs(xy_x) <= tolerance ? 0. :\n                           .5 * (x2 - pi_sqr + sqrt(t)) / xy_x;\n                            return;\n                    }\n                    y2 = xy_y * xy_y;\n                    r = x2 + y2;    r2 = r * r;\n                    c1 = - pi * ay * (r + pi_sqr);\n                    c3 = r2 + two_pi * (ay * r + pi * (y2 + pi * (ay + half_pi)));\n                    c2 = c1 + pi_sqr * (r - 3. *  y2);\n                    c0 = pi * ay;\n                    c2 /= c3;\n                    al = c1 / c3 - third * c2 * c2;\n                    m = 2. * sqrt(-third * al);\n                    d = C2_27 * c2 * c2 * c2 + (c0 * c0 - third * c2 * c1) / c3;\n                    if (((t = fabs(d = 3. * d / (al * m))) - tolerance) <= 1.) {\n                        d = t > 1. ? (d > 0. ? 0. : pi) : acos(d);\n                        lp_lat = pi * (m * cos(d * third + PI4_3) - third * c2);\n                        if (xy_y < 0.) lp_lat = -lp_lat;\n                        t = r2 + TPISQ * (x2 - y2 + HPISQ);\n                        lp_lon = fabs(xy_x) <= tolerance ? 0. :\n                           .5 * (r - pi_sqr + (t <= 0. ? 0. : sqrt(t))) / xy_x;\n                    } else {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"vandg_spheroid\";\n                }\n\n            };\n\n            // van der Grinten (I)\n            template <typename Parameters>\n            inline void setup_vandg(Parameters& par)\n            {\n                par.es = 0.;\n            }\n\n    }} // namespace detail::vandg\n    #endif // doxygen\n\n    /*!\n        \\brief van der Grinten (I) projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Miscellaneous\n         - Spheroid\n        \\par Example\n        \\image html ex_vandg.gif\n    */\n    template <typename T, typename Parameters>\n    struct vandg_spheroid : public detail::vandg::base_vandg_spheroid<T, Parameters>\n    {\n        inline vandg_spheroid(const Parameters& par) : detail::vandg::base_vandg_spheroid<T, Parameters>(par)\n        {\n            detail::vandg::setup_vandg(this->m_par);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::vandg, vandg_spheroid, vandg_spheroid)\n\n        // Factory entry(s)\n        template <typename T, typename Parameters>\n        class vandg_entry : public detail::factory_entry<T, Parameters>\n        {\n            public :\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<vandg_spheroid<T, Parameters>, T, Parameters>(par);\n                }\n        };\n\n        template <typename T, typename Parameters>\n        inline void vandg_init(detail::base_factory<T, Parameters>& factory)\n        {\n            factory.add_to_factory(\"vandg\", new vandg_entry<T, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_VANDG_HPP\n\n", "meta": {"hexsha": "4124ca2354177e6d46fffc5ce90f1ff20ab5264c", "size": 10085, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/srs/projections/proj/vandg.hpp", "max_stars_repo_name": "jonasdmentia/geometry", "max_stars_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2018-08-16T03:03:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T23:27:34.000Z", "max_issues_repo_path": "include/boost/geometry/srs/projections/proj/vandg.hpp", "max_issues_repo_name": "jonasdmentia/geometry", "max_issues_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2022-02-02T11:45:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T19:19:24.000Z", "max_forks_repo_path": "include/boost/geometry/srs/projections/proj/vandg.hpp", "max_forks_repo_name": "jonasdmentia/geometry", "max_forks_repo_head_hexsha": "097f6fdbe98118be82cd1917cc72c3c6a37bdf30", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-10-23T05:16:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T04:44:34.000Z", "avg_line_length": 40.6653225806, "max_line_length": 109, "alphanum_fraction": 0.5183936539, "num_tokens": 2464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.24591295634123253}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/functional/hash.hpp>  // IWYU pragma: keep\n#include <cstddef>\n#include <limits>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/SizeOfElement.hpp\"\n#include \"Domain/Structure/Element.hpp\"  // IWYU pragma: keep\n#include \"Domain/Structure/OrientationMapHelpers.hpp\"\n#include \"Domain/Tags.hpp\"  // IWYU pragma: keep\n#include \"Evolution/DiscontinuousGalerkin/Limiters/HwenoImpl.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodTci.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodType.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/SimpleWenoImpl.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoGridHelpers.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoHelpers.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoType.hpp\"\n#include \"NumericalAlgorithms/Interpolation/RegularGridInterpolant.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/MeanValue.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Utilities/Algorithm.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeArray.hpp\"\n#include \"Utilities/TMPL.hpp\"\n#include \"Utilities/TaggedTuple.hpp\"\n\n/// \\cond\ntemplate <size_t VolumeDim>\nclass Direction;\ntemplate <size_t VolumeDim>\nclass ElementId;\n\nnamespace PUP {\nclass er;\n}  // namespace PUP\n/// \\endcond\n\nnamespace Limiters {\n/// \\ingroup LimitersGroup\n/// \\brief A compact-stencil WENO limiter for DG\n///\n/// Implements the simple WENO limiter of \\cite Zhong2013 and the Hermite WENO\n/// (HWENO) limiter of \\cite Zhu2016. The implementation is system-agnostic and\n/// can act on an arbitrary set of tensors.\n///\n/// #### Summary of the compact-stencil WENO algorithms:\n//\n/// The compact-stencil WENO limiters require communication only between\n/// nearest-neighbor elements, but aim to preserve the full order of the DG\n/// solution when the solution is smooth. To achieve this, full volume data is\n/// communicated between neighbors.\n//\n/// For each tensor component to limit, the new solution is obtained by a\n/// standard WENO procedure --- the new solution is a linear combination of\n/// different polynomials, with weights chosen so that the smoother (i.e., less\n/// oscillatory) polynomials contribute the most to the sum.\n///\n/// For the simple WENO and HWENO limiters, the polynomials used are the local\n/// DG solution as well as a \"modified\" solution from each neighbor element. For\n/// the simple WENO limiter, the modified solution is obtained by simply\n/// extrapolating the neighbor solution onto the troubled element. For the HWENO\n/// limiter, the modified solution is obtained by a least-squares fit to the\n/// solution across multiple neighboring elements.\n///\n/// #### Notes on the SpECTRE implemention of the WENO limiters:\n///\n/// There are a few differences between the limiters as implemented in SpECTRE\n/// and as presented in the references. We list them here and discuss them\n/// further below.\n/// 1. The choice of basis to represent the DG solution\n/// 2. The system-agnostic implementation\n/// 3. The oscillation indicator\n///\n/// Finally, in 4., we will discuss the geometric limitations of the\n/// implementation (which are not a deviation from the references).\n///\n/// ##### 1. The choice of basis\n///\n/// SpECTRE uses a Legendre basis, rather than the polynomial basis that we\n/// understand to be used in the references. Because the construction of the\n/// modified neighbor solutions and the WENO sum is geometrically motivated, the\n/// overall algorithm should work similarly. However, the precise numerics may\n/// differ.\n///\n/// ##### 2. The system-agnostic implementation\n//\n/// This implementation can act on an arbitrary set of tensors. To reach this\n/// generality, our HWENO implementation uses a different troubled-cell\n/// indicator (TCI) than the reference, which instead specializes the TCI to the\n/// Newtonian Euler system of equations.\n///\n/// This implementation uses the minmod-based TVB TCI of \\cite Cockburn1999 to\n/// identify elements that need limiting. The simple WENO implementation follows\n/// its reference: it checks the TCI independently for each tensor component, so\n/// that only certain tensor components may be limited. The HWENO implementation\n/// checks the TVB TCI for all tensor components, and if any single component is\n/// troubled, then all components of all tensors are limited.\n///\n/// When the evolution system has multiple evolved variables, the recommendation\n/// of the references is to apply the limiter to the system's characteristic\n/// variables to reduce spurious post-limiting oscillations. In SpECTRE,\n/// applying the limiter to the characteristic variables requires specializing\n/// the limiter to each evolution system. The system-specific limiter can also\n/// implement a system-specific TCI (as the HWENO reference does) to more\n/// precisely trigger the limiter.\n///\n/// ##### 3. The oscillation indicator\n///\n/// We use the oscillation indicator of \\cite Dumbser2007, modified for use on\n/// the square/cube grids of SpECTRE. We favor this indicator because portions\n/// of the work can be precomputed, leading to an oscillation measure that is\n/// efficient to evaluate.\n///\n/// ##### 4. The geometric limitations\n///\n/// Does not support non-Legendre bases; this is checked in DEBUG mode. In\n/// principle other bases could be supported, but this would require\n/// generalizing the many internal algorithms that assume a Legendre basis.\n///\n/// Does not support h- or p-refinement; this is checked always. In principle\n/// this could be supported. The modified neighbor solution algorithm would\n/// need to be generalized (reasonable for simple WENO, extremely tedious for\n/// HWENO), and the sum of neighbor solutions may need to be updated as well.\n///\n/// Does not support curved elements; this is not enforced. The code will run\n/// but we make no guarantees about the results. Specifically, the limiter acts\n/// in the `Frame::ElementLogical` coordinates, because in these coordinates it\n/// is straightforward to formulate the algorithm. This means the limiter can\n/// operate on generic deformed grids --- however, some things can start to\n/// break down, especially on strongly deformed grids:\n/// 1. When the Jacobian (from `Frame::ElementLogical` to `Frame::Inertial`)\n///    varies across the element, then the limiter fails to be conservative.\n///    This is because the integral of a tensor `u` over the element will change\n///    after the limiter activates on `u`.\n/// 2. When computing the modified neighbor solution for the WENO sum, the\n///    extrapolation or fitting procedure may not properly account for the\n///    coordinates of the source data. If the coordinate map of the neighbor\n///    differs from that of the local element, then the logical-coordinate\n///    representation of the neighbor data may be incorrect. This may be a\n///    large error at Block boundaries with discontinuous map changes, and may\n///    be a small error from smoothly-varying maps that are not sufficiently\n///    resolved from one element to the next.\ntemplate <size_t VolumeDim, typename TagsToLimit>\nclass Weno;\n\ntemplate <size_t VolumeDim, typename... Tags>\nclass Weno<VolumeDim, tmpl::list<Tags...>> {\n public:\n  /// \\brief The WenoType\n  ///\n  /// One of `Limiters::WenoType`. See the `Limiters::Weno`\n  /// documentation for details.\n  struct Type {\n    using type = WenoType;\n    static constexpr Options::String help = {\"Type of WENO limiter\"};\n  };\n  /// \\brief The linear weight given to each neighbor\n  ///\n  /// This linear weight gets combined with the oscillation indicator to\n  /// compute the weight for each WENO estimated solution. The standard value\n  /// in the literature is 0.001; larger values may be better suited for\n  /// problems with strong shocks, and smaller values may be better suited to\n  /// smooth problems.\n  struct NeighborWeight {\n    using type = double;\n    static type lower_bound() noexcept { return 1e-6; }\n    static type upper_bound() noexcept { return 0.1; }\n    static constexpr Options::String help = {\n        \"Linear weight for each neighbor element's solution\"};\n  };\n  /// \\brief The TVB constant for the minmod TCI\n  ///\n  /// See `Limiters::Minmod` documentation for details.\n  struct TvbConstant {\n    using type = double;\n    static type lower_bound() noexcept { return 0.0; }\n    static constexpr Options::String help = {\"TVB constant 'm'\"};\n  };\n  /// \\brief Turn the limiter off\n  ///\n  /// This option exists to temporarily disable the limiter for debugging\n  /// purposes. For problems where limiting is not needed, the preferred\n  /// approach is to not compile the limiter into the executable.\n  struct DisableForDebugging {\n    using type = bool;\n    static type suggested_value() noexcept { return false; }\n    static constexpr Options::String help = {\"Disable the limiter\"};\n  };\n  using options =\n      tmpl::list<Type, NeighborWeight, TvbConstant, DisableForDebugging>;\n  static constexpr Options::String help = {\"A WENO limiter for DG\"};\n\n  Weno(WenoType weno_type, double neighbor_linear_weight, double tvb_constant,\n       bool disable_for_debugging = false) noexcept;\n\n  Weno() noexcept = default;\n  Weno(const Weno& /*rhs*/) = default;\n  Weno& operator=(const Weno& /*rhs*/) = default;\n  Weno(Weno&& /*rhs*/) noexcept = default;\n  Weno& operator=(Weno&& /*rhs*/) noexcept = default;\n  ~Weno() = default;\n\n  // NOLINTNEXTLINE(google-runtime-references)\n  void pup(PUP::er& p) noexcept;\n\n  /// \\brief Data to send to neighbor elements\n  struct PackagedData {\n    Variables<tmpl::list<Tags...>> volume_data;\n    tuples::TaggedTuple<::Tags::Mean<Tags>...> means;\n    Mesh<VolumeDim> mesh;\n    std::array<double, VolumeDim> element_size =\n        make_array<VolumeDim>(std::numeric_limits<double>::signaling_NaN());\n\n    // NOLINTNEXTLINE(google-runtime-references)\n    void pup(PUP::er& p) noexcept {\n      p | volume_data;\n      p | means;\n      p | mesh;\n      p | element_size;\n    }\n  };\n\n  using package_argument_tags =\n      tmpl::list<Tags..., domain::Tags::Mesh<VolumeDim>,\n                 domain::Tags::SizeOfElement<VolumeDim>>;\n\n  /// \\brief Package data for sending to neighbor elements\n  void package_data(gsl::not_null<PackagedData*> packaged_data,\n                    const typename Tags::type&... tensors,\n                    const Mesh<VolumeDim>& mesh,\n                    const std::array<double, VolumeDim>& element_size,\n                    const OrientationMap<VolumeDim>& orientation_map) const\n      noexcept;\n\n  using limit_tags = tmpl::list<Tags...>;\n  using limit_argument_tags =\n      tmpl::list<domain::Tags::Mesh<VolumeDim>,\n                 domain::Tags::Element<VolumeDim>,\n                 domain::Tags::SizeOfElement<VolumeDim>>;\n\n  /// \\brief Limit the solution on the element\n  bool operator()(\n      const gsl::not_null<std::add_pointer_t<typename Tags::type>>... tensors,\n      const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n      const std::array<double, VolumeDim>& element_size,\n      const std::unordered_map<\n          std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,\n          boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n          neighbor_data) const noexcept;\n\n private:\n  template <size_t LocalDim, typename LocalTagList>\n  // NOLINTNEXTLINE(readability-redundant-declaration) false positive\n  friend bool operator==(const Weno<LocalDim, LocalTagList>& lhs,\n                         const Weno<LocalDim, LocalTagList>& rhs) noexcept;\n\n  WenoType weno_type_;\n  double neighbor_linear_weight_;\n  double tvb_constant_;\n  bool disable_for_debugging_;\n};\n\ntemplate <size_t VolumeDim, typename... Tags>\nWeno<VolumeDim, tmpl::list<Tags...>>::Weno(\n    const WenoType weno_type, const double neighbor_linear_weight,\n    const double tvb_constant, const bool disable_for_debugging) noexcept\n    : weno_type_(weno_type),\n      neighbor_linear_weight_(neighbor_linear_weight),\n      tvb_constant_(tvb_constant),\n      disable_for_debugging_(disable_for_debugging) {}\n\ntemplate <size_t VolumeDim, typename... Tags>\n// NOLINTNEXTLINE(google-runtime-references)\nvoid Weno<VolumeDim, tmpl::list<Tags...>>::pup(PUP::er& p) noexcept {\n  p | weno_type_;\n  p | neighbor_linear_weight_;\n  p | tvb_constant_;\n  p | disable_for_debugging_;\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nvoid Weno<VolumeDim, tmpl::list<Tags...>>::package_data(\n    const gsl::not_null<PackagedData*> packaged_data,\n    const typename Tags::type&... tensors, const Mesh<VolumeDim>& mesh,\n    const std::array<double, VolumeDim>& element_size,\n    const OrientationMap<VolumeDim>& orientation_map) const noexcept {\n  // By always initializing the PackagedData Variables member, we avoid an\n  // assertion that arises from having a default-constructed Variables in a\n  // disabled limiter. There is a performance cost, because the package_data()\n  // function does non-zero work even for a disabled limiter... but since the\n  // limiter should never be disabled in a production simulation, this cost\n  // should never matter.\n  (packaged_data->volume_data).initialize(mesh.number_of_grid_points());\n\n  if (UNLIKELY(disable_for_debugging_)) {\n    // Do not initialize packaged_data\n    // (except for the Variables member \"volume_data\", see above)\n    return;\n  }\n\n  const auto wrap_compute_means = [&mesh, &packaged_data](\n                                      auto tag, const auto tensor) noexcept {\n    for (size_t i = 0; i < tensor.size(); ++i) {\n      // Compute the mean using the local orientation of the tensor and mesh.\n      get<::Tags::Mean<decltype(tag)>>(packaged_data->means)[i] =\n          mean_value(tensor[i], mesh);\n    }\n    return '0';\n  };\n  expand_pack(wrap_compute_means(Tags{}, tensors)...);\n\n  packaged_data->element_size =\n      orientation_map.permute_from_neighbor(element_size);\n\n  const auto wrap_copy_tensor = [&packaged_data](auto tag,\n                                                 const auto tensor) noexcept {\n    get<decltype(tag)>(packaged_data->volume_data) = tensor;\n    return '0';\n  };\n  expand_pack(wrap_copy_tensor(Tags{}, tensors)...);\n  packaged_data->volume_data = orient_variables(\n      packaged_data->volume_data, mesh.extents(), orientation_map);\n\n  packaged_data->mesh = orientation_map(mesh);\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nbool Weno<VolumeDim, tmpl::list<Tags...>>::operator()(\n    const gsl::not_null<std::add_pointer_t<typename Tags::type>>... tensors,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const std::array<double, VolumeDim>& element_size,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data) const noexcept {\n  if (UNLIKELY(disable_for_debugging_)) {\n    // Do not modify input tensors\n    return false;\n  }\n\n  // Check that basis is LGL or LG\n  // A Legendre basis is assumed for the oscillation indicator (used in both\n  // SimpleWeno and Hweno) and in the Hweno reconstruction.\n  ASSERT(mesh.basis() == make_array<VolumeDim>(Spectral::Basis::Legendre),\n         \"Unsupported basis: \" << mesh);\n  ASSERT(mesh.quadrature() ==\n                 make_array<VolumeDim>(Spectral::Quadrature::GaussLobatto) or\n             mesh.quadrature() ==\n                 make_array<VolumeDim>(Spectral::Quadrature::Gauss),\n         \"Unsupported quadrature: \" << mesh);\n\n  // Enforce restrictions on h-refinement, p-refinement\n  if (UNLIKELY(alg::any_of(element.neighbors(),\n                           [](const auto& direction_neighbors) noexcept {\n                             return direction_neighbors.second.size() != 1;\n                           }))) {\n    ERROR(\"The Weno limiter does not yet support h-refinement\");\n    // Removing this limitation will require:\n    // - Generalizing the computation of the modified neighbor solutions.\n    // - Generalizing the WENO weighted sum for multiple neighbors in each\n    //   direction.\n  }\n  alg::for_each(neighbor_data, [&mesh](const auto& neighbor_and_data) noexcept {\n    if (UNLIKELY(neighbor_and_data.second.mesh != mesh)) {\n      ERROR(\"The Weno limiter does not yet support p-refinement\");\n      // Removing this limitation will require generalizing the\n      // computation of the modified neighbor solutions.\n    }\n  });\n\n  if (weno_type_ == WenoType::Hweno) {\n    // Troubled-cell detection for HWENO flags the element for limiting if any\n    // component of any tensor needs limiting.\n    const bool cell_is_troubled =\n        Tci::tvb_minmod_indicator<VolumeDim, PackagedData, Tags...>(\n            tvb_constant_, (*tensors)..., mesh, element, element_size,\n            neighbor_data);\n    if (not cell_is_troubled) {\n      // No limiting is needed\n      return false;\n    }\n\n    std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, DataVector,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n        modified_neighbor_solution_buffer{};\n    for (const auto& neighbor_and_data : neighbor_data) {\n      const auto& neighbor = neighbor_and_data.first;\n      modified_neighbor_solution_buffer.insert(\n          make_pair(neighbor, DataVector(mesh.number_of_grid_points())));\n    }\n\n    EXPAND_PACK_LEFT_TO_RIGHT(Weno_detail::hweno_impl<Tags>(\n        make_not_null(&modified_neighbor_solution_buffer), tensors,\n        neighbor_linear_weight_, mesh, element, neighbor_data));\n    return true;  // cell_is_troubled\n\n  } else if (weno_type_ == WenoType::SimpleWeno) {\n    // Buffers and pre-computations for TCI\n    Minmod_detail::BufferWrapper<VolumeDim> tci_buffer(mesh);\n    const auto effective_neighbor_sizes =\n        Minmod_detail::compute_effective_neighbor_sizes(element, neighbor_data);\n\n    // Buffers for simple WENO implementation\n    std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n        intrp::RegularGrid<VolumeDim>,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n        interpolator_buffer{};\n    std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, DataVector,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n        modified_neighbor_solution_buffer{};\n\n    bool some_component_was_limited = false;\n\n    const auto wrap_minmod_tci_and_simple_weno_impl =\n        [this, &some_component_was_limited, &tci_buffer, &interpolator_buffer,\n         &modified_neighbor_solution_buffer, &mesh, &element, &element_size,\n         &neighbor_data,\n         &effective_neighbor_sizes](auto tag, const auto tensor) noexcept {\n          for (size_t tensor_storage_index = 0;\n               tensor_storage_index < tensor->size(); ++tensor_storage_index) {\n            // Check TCI\n            const auto effective_neighbor_means =\n                Minmod_detail::compute_effective_neighbor_means<decltype(tag)>(\n                    tensor_storage_index, element, neighbor_data);\n            const bool component_needs_limiting = Tci::tvb_minmod_indicator(\n                make_not_null(&tci_buffer), tvb_constant_,\n                (*tensor)[tensor_storage_index], mesh, element, element_size,\n                effective_neighbor_means, effective_neighbor_sizes);\n\n            if (component_needs_limiting) {\n              if (modified_neighbor_solution_buffer.empty()) {\n                // Allocate the neighbor solution buffers only if the limiter is\n                // triggered. This reduces allocation when no limiting occurs.\n                for (const auto& neighbor_and_data : neighbor_data) {\n                  const auto& neighbor = neighbor_and_data.first;\n                  modified_neighbor_solution_buffer.insert(make_pair(\n                      neighbor, DataVector(mesh.number_of_grid_points())));\n                }\n              }\n              Weno_detail::simple_weno_impl<decltype(tag)>(\n                  make_not_null(&interpolator_buffer),\n                  make_not_null(&modified_neighbor_solution_buffer), tensor,\n                  neighbor_linear_weight_, tensor_storage_index, mesh, element,\n                  neighbor_data);\n              some_component_was_limited = true;\n            }\n          }\n          return '0';\n        };\n    expand_pack(wrap_minmod_tci_and_simple_weno_impl(Tags{}, tensors)...);\n    return some_component_was_limited;  // cell_is_troubled\n  } else {\n    ERROR(\"WENO limiter not implemented for WenoType: \" << weno_type_);\n  }\n\n  return false;  // cell_is_troubled\n}\n\ntemplate <size_t LocalDim, typename LocalTagList>\nbool operator==(const Weno<LocalDim, LocalTagList>& lhs,\n                const Weno<LocalDim, LocalTagList>& rhs) noexcept {\n  return lhs.weno_type_ == rhs.weno_type_ and\n         lhs.neighbor_linear_weight_ == rhs.neighbor_linear_weight_ and\n         lhs.tvb_constant_ == rhs.tvb_constant_ and\n         lhs.disable_for_debugging_ == rhs.disable_for_debugging_;\n}\n\ntemplate <size_t VolumeDim, typename TagList>\nbool operator!=(const Weno<VolumeDim, TagList>& lhs,\n                const Weno<VolumeDim, TagList>& rhs) noexcept {\n  return not(lhs == rhs);\n}\n\n}  // namespace Limiters\n", "meta": {"hexsha": "174d08fd0b67dc6b466c9e18598e2d56a3142884", "size": 21566, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Weno.hpp", "max_stars_repo_name": "GAcuna001/spectre", "max_stars_repo_head_hexsha": "645a7f203b2ced1b1205e346d3abaf2adaf0e6ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Weno.hpp", "max_issues_repo_name": "GAcuna001/spectre", "max_issues_repo_head_hexsha": "645a7f203b2ced1b1205e346d3abaf2adaf0e6ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Weno.hpp", "max_forks_repo_name": "GAcuna001/spectre", "max_forks_repo_head_hexsha": "645a7f203b2ced1b1205e346d3abaf2adaf0e6ba", "max_forks_repo_licenses": ["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.9226069246, "max_line_length": 80, "alphanum_fraction": 0.7062969489, "num_tokens": 4962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2459129512309476}}
{"text": "// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//    http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef NETKET_METROPOLISLOCAL_HPP\n#define NETKET_METROPOLISLOCAL_HPP\n\n#include <mpi.h>\n#include <Eigen/Dense>\n#include <iostream>\n#include <limits>\n#include \"Utils/parallel_utils.hpp\"\n#include \"Utils/random_utils.hpp\"\n#include \"abstract_sampler.hpp\"\n\nnamespace netket {\n\n// Metropolis sampling generating local moves in hilbert space\ntemplate <class WfType>\nclass MetropolisLocal : public AbstractSampler<WfType> {\n  WfType& psi_;\n\n  const AbstractHilbert& hilbert_;\n\n  // number of visible units\n  const int nv_;\n\n  netket::default_random_engine rgen_;\n\n  // states of visible units\n  Eigen::VectorXd v_;\n\n  Eigen::VectorXd accept_;\n  Eigen::VectorXd moves_;\n\n  int mynode_;\n  int totalnodes_;\n\n  // Look-up tables\n  typename WfType::LookupType lt_;\n\n  int nstates_;\n  std::vector<double> localstates_;\n\n public:\n  explicit MetropolisLocal(WfType& psi)\n      : psi_(psi), hilbert_(psi.GetHilbert()), nv_(hilbert_.Size()) {\n    Init();\n  }\n\n  void Init() {\n    v_.resize(nv_);\n\n    MPI_Comm_size(MPI_COMM_WORLD, &totalnodes_);\n    MPI_Comm_rank(MPI_COMM_WORLD, &mynode_);\n\n    if (!hilbert_.IsDiscrete()) {\n      throw InvalidInputError(\n          \"Local Metropolis sampler works only for discrete \"\n          \"Hilbert spaces\");\n    }\n\n    accept_.resize(1);\n    moves_.resize(1);\n\n    nstates_ = hilbert_.LocalSize();\n    localstates_ = hilbert_.LocalStates();\n\n    Seed();\n\n    Reset(true);\n\n    InfoMessage() << \"Local Metropolis sampler is ready \" << std::endl;\n  }\n\n  void Seed(int baseseed = 0) {\n    std::random_device rd;\n    std::vector<int> seeds(totalnodes_);\n\n    if (mynode_ == 0) {\n      for (int i = 0; i < totalnodes_; i++) {\n        seeds[i] = rd() + baseseed;\n      }\n    }\n\n    SendToAll(seeds);\n\n    rgen_.seed(seeds[mynode_]);\n  }\n\n  void Reset(bool initrandom = false) override {\n    if (initrandom) {\n      hilbert_.RandomVals(v_, rgen_);\n    }\n\n    psi_.InitLookup(v_, lt_);\n\n    accept_ = Eigen::VectorXd::Zero(1);\n    moves_ = Eigen::VectorXd::Zero(1);\n  }\n\n  void Sweep() override {\n    std::vector<int> tochange(1);\n    std::vector<double> newconf(1);\n\n    std::uniform_real_distribution<double> distu;\n    std::uniform_int_distribution<int> distrs(0, nv_ - 1);\n    std::uniform_int_distribution<int> diststate(0, nstates_ - 1);\n\n    for (int i = 0; i < nv_; i++) {\n      // picking a random site to be changed\n      int si = distrs(rgen_);\n      assert(si < nv_);\n      tochange[0] = si;\n\n      // picking a random state\n      int newstate = diststate(rgen_);\n      newconf[0] = localstates_[newstate];\n\n      // make sure that the new state is not equal to the current one\n      while (std::abs(newconf[0] - v_(si)) <\n             std::numeric_limits<double>::epsilon()) {\n        newstate = diststate(rgen_);\n        newconf[0] = localstates_[newstate];\n      }\n\n      const auto lvd = psi_.LogValDiff(v_, tochange, newconf, lt_);\n      double ratio = std::norm(std::exp(lvd));\n\n#ifndef NDEBUG\n      const auto psival1 = psi_.LogVal(v_);\n      if (std::abs(std::exp(psi_.LogVal(v_) - psi_.LogVal(v_, lt_)) - 1.) >\n          1.0e-8) {\n        std::cerr << psi_.LogVal(v_) << \"  and LogVal with Lt is \"\n                  << psi_.LogVal(v_, lt_) << std::endl;\n        std::abort();\n      }\n#endif\n\n      // Metropolis acceptance test\n      if (ratio > distu(rgen_)) {\n        accept_[0] += 1;\n        psi_.UpdateLookup(v_, tochange, newconf, lt_);\n        hilbert_.UpdateConf(v_, tochange, newconf);\n\n#ifndef NDEBUG\n        const auto psival2 = psi_.LogVal(v_);\n        if (std::abs(std::exp(psival2 - psival1 - lvd) - 1.) > 1.0e-8) {\n          std::cerr << psival2 - psival1 << \" and logvaldiff is \" << lvd\n                    << std::endl;\n          std::cerr << psival2 << \" and LogVal with Lt is \"\n                    << psi_.LogVal(v_, lt_) << std::endl;\n          std::abort();\n        }\n#endif\n      }\n      moves_[0] += 1;\n    }\n  }\n\n  Eigen::VectorXd Visible() override { return v_; }\n\n  void SetVisible(const Eigen::VectorXd& v) override { v_ = v; }\n\n  WfType& GetMachine() noexcept override { return psi_; }\n\n  const AbstractHilbert& GetHilbert() const noexcept override {\n    return hilbert_;\n  }\n\n  Eigen::VectorXd Acceptance() const override {\n    Eigen::VectorXd acc = accept_;\n    for (int i = 0; i < 1; i++) {\n      acc(i) /= moves_(i);\n    }\n    return acc;\n  }\n};\n\n}  // namespace netket\n\n#endif\n", "meta": {"hexsha": "7dfa08d6743cba778db0303260bbd110cb25bfc0", "size": 4971, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NetKet/Sampler/metropolis_local.hpp", "max_stars_repo_name": "GTorlai/netket", "max_stars_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NetKet/Sampler/metropolis_local.hpp", "max_issues_repo_name": "GTorlai/netket", "max_issues_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetKet/Sampler/metropolis_local.hpp", "max_forks_repo_name": "GTorlai/netket", "max_forks_repo_head_hexsha": "0c35bfaadeb1253f611f8052b53c9b3d3d9aec9f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7564766839, "max_line_length": 75, "alphanum_fraction": 0.6278414806, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24573395951675675}}
{"text": "//\n//  sequence.cpp\n//  express\n//\n//  Created by Adam Roberts on 1/24/12.\n//  Copyright 2012 Adam Roberts. All rights reserved.\n//\n\n#include \"sequence.h\"\n#include <cassert>\n#include <boost/math/distributions/binomial.hpp>\n\nusing namespace std;\nusing namespace boost::math;\n\nstring Sequence::serialize() {\n  vector<char> seq;\n  for (size_t i = 0; i < length(); i++) {\n    if (i/4 == seq.size()) {\n      seq.push_back(0);\n    }\n    seq.back() += operator[](i) << (2 * (i % 4));\n  }\n  \n  return string(seq.begin(), seq.end());\n}\n\nSequenceFwd::SequenceFwd():  _ref_seq(NULL), _prob(0), _len(0) {}\n\nSequenceFwd::SequenceFwd(const std::string& seq, bool rev, bool prob)\n    : _prob(prob), _len(seq.length()) {\n  if (prob) {\n    _est_seq = FrequencyMatrix<float>(seq.length(), NUM_NUCS, 0.001);\n    _obs_seq = FrequencyMatrix<float>(seq.length(), NUM_NUCS, LOG_0);\n    _exp_seq = FrequencyMatrix<float>(seq.length(), NUM_NUCS, LOG_0);\n  }\n  set(seq, rev);\n}\n\nSequenceFwd::SequenceFwd(const SequenceFwd& other)\n    : _obs_seq(other._obs_seq), _exp_seq(other._exp_seq),\n      _prob(other._prob), _len(other.length()) {\n  if (other._ref_seq) {\n    char* ref_seq = new char[_len];\n    std::copy(other._ref_seq.get(), other._ref_seq.get() + _len, ref_seq);\n    _ref_seq.reset(ref_seq);\n  }\n}\n\nSequenceFwd& SequenceFwd::operator=(const SequenceFwd& other) {\n  if (other._ref_seq) {\n    _len = other.length();\n    char* ref_seq = new char[_len];\n    std::copy(other._ref_seq.get(), other._ref_seq.get() + _len, ref_seq);\n    _ref_seq.reset(ref_seq);\n    _obs_seq = other._obs_seq;\n    _exp_seq = other._exp_seq;\n    _prob = other._prob;\n  }\n  return *this;\n}\n\nvoid SequenceFwd::set(const std::string& seq, bool rev) {\n  char* ref_seq = new char[seq.length()];\n  for (size_t i = 0; i < seq.length(); i++) {\n    ref_seq[i] = (rev) ? complement(ctoi(seq[seq.length()-1-i])) : ctoi(seq[i]);\n    if (_prob) {\n      _est_seq.increment(i, ref_seq[i], log((float)2));\n    }\n  }\n  _ref_seq.reset(ref_seq);\n  _len = seq.length();\n}\n\nsize_t SequenceFwd::operator[](const size_t index) const {\n  assert(index < _len);\n  if (_prob) {\n    return _est_seq.argmax(index);\n  }\n  return _ref_seq[index];\n}\n\nsize_t SequenceFwd::get_ref(const size_t index) const {\n  assert(index < _len);\n  //assert(_ref_seq[index] == operator[](index));\n  return _ref_seq[index];\n}\n\nfloat SequenceFwd::get_prob(const size_t index, const size_t nuc) const {\n  assert(_prob);\n  return _est_seq(index, nuc);\n}\n\nfloat SequenceFwd::get_obs(const size_t index, const size_t nuc) const {\n  assert(index < _len);\n  return _obs_seq(index,nuc, false);\n}\n\nfloat SequenceFwd::get_exp(const size_t index, const size_t nuc) const {\n  assert(index < _len);\n  return _exp_seq(index,nuc, false);\n}\n\nvoid SequenceFwd::update_est(const size_t index, const size_t nuc, float mass) {\n  assert(_prob);\n  _est_seq.increment(index, nuc, mass);\n}\n\nvoid SequenceFwd::update_obs(const size_t index, const size_t nuc, float mass) {\n  assert(_prob);\n  _obs_seq.increment(index, nuc, mass);\n}\n\nvoid SequenceFwd::update_exp(const size_t index, const size_t nuc, float mass) {\n  assert(_prob);\n  _exp_seq.increment(index, nuc, mass);\n}\n\nvoid SequenceFwd::calc_p_vals(vector<double>& p_vals) const {\n  p_vals = vector<double>(_len, 1.0);\n  for (size_t i = 0; i < _len; ++i) {\n    double N = round(sexp(_obs_seq.sum(i)));\n    if (N<5) {\n      continue;\n    }\n    size_t ref_nuc = get_ref(i);\n    double max_obs = 0;\n    for (size_t nuc = 0; nuc < NUM_NUCS; ++nuc) {\n      if (nuc == ref_nuc) {\n        continue;\n      }\n\n      double obs_n = round(sexp(_obs_seq(i,nuc,false)));\n      max_obs = max(max_obs, obs_n);\n    }\n    \n    double p_val = 0;\n\n    for (size_t nuc = 0; nuc < NUM_NUCS; ++nuc) {\n      if (nuc == ref_nuc) {\n        continue;\n      }\n\n      double exp_p = sexp(_exp_seq(i, nuc));\n      binomial binom(N, exp_p);\n      p_val += log(cdf(binom, max_obs));\n    }\n    p_vals[i] -= sexp(p_val);\n  }\n}\n\nvoid SequenceRev::calc_p_vals(vector<double>& p_vals) const\n{\n  vector<double> temp;\n  _seq->calc_p_vals(temp);\n  p_vals = vector<double>(length());\n  for(size_t i = 0; i < length(); i++) {\n    p_vals[i] = temp[length()-i-1];\n  }\n}\n\n/*\nvoid SequenceFwd::calc_p_vals(vector<double>& p_vals) const\n{\n    p_vals = vector<double>(_len, 1);\n    for (size_t i = 0; i < _len; ++i)\n    {\n        double N = sexp(_obs_seq.sum(i));\n\n        if (N==0)\n            continue;\n\n        size_t ref_nuc = get_ref(i);\n        double p_val = LOG_0;\n\n        vector<double> cdfs(4);\n        for (size_t nuc = 0; nuc < NUM_NUCS; ++nuc)\n        {\n            if (nuc == ref_nuc)\n                continue;\n\n            double p = sexp(_exp_seq(i,nuc));\n            double obs_n = sexp(_obs_seq(i,nuc,false));\n            normal norm (N*p, sqrt(N*p*(1-p)));\n            cdfs[nuc] = cdf(norm, obs_n);\n        }\n\n        for (size_t nuc1 = 0; nuc1 < NUM_NUCS; ++nuc1)\n        {\n            if (nuc1 == ref_nuc)\n                continue;\n\n            double term = log(1-cdfs[nuc1]);\n\n            for(size_t nuc2 = 0; nuc2 < NUM_NUCS; ++nuc2)\n            {\n                if (nuc2 == nuc1 || nuc2 == ref_nuc)\n                    continue;\n                term += log(cdfs[nuc2]);\n            }\n            p_val = log_add(p_val, term);\n        }\n\n        p_vals[i] = sexp(p_val);\n    }\n}\n*/\n\n/*\nvoid SequenceFwd::calc_p_vals(vector<double>& p_vals) const\n{\n    p_vals = vector<double>(_len, 1.0);\n    boost::math::chi_squared_distribution<double> chisq(3);\n    double obs_n,exp_n;\n    for (size_t i = 0; i < _len; ++i)\n    {\n        if (_obs_seq.sum(i)==LOG_0)\n            continue;\n\n        double S = 0;\n        for (size_t nuc = 0; nuc < NUM_NUCS; ++nuc)\n        {\n            obs_n = sexp(_obs_seq(i,nuc,false));\n            exp_n = sexp(_exp_seq(i,nuc,false));\n            S += (obs_n-exp_n)*(obs_n-exp_n)/exp_n;\n        }\n\n        p_vals[i] -= boost::math::cdf(chisq,S);\n    }\n}\n */\n", "meta": {"hexsha": "e1cbe0997265b6ce66e97f3eda4c6e44721b6ce1", "size": 5897, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sequence.cpp", "max_stars_repo_name": "hartzell/eXpress", "max_stars_repo_head_hexsha": "99487d22e8bdc5e717a28c4ce4bfeb573453c5dd", "max_stars_repo_licenses": ["Artistic-2.0"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2015-02-13T21:21:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T11:44:40.000Z", "max_issues_repo_path": "src/sequence.cpp", "max_issues_repo_name": "hartzell/eXpress", "max_issues_repo_head_hexsha": "99487d22e8bdc5e717a28c4ce4bfeb573453c5dd", "max_issues_repo_licenses": ["Artistic-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T17:47:37.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T15:37:26.000Z", "max_forks_repo_path": "src/sequence.cpp", "max_forks_repo_name": "hartzell/eXpress", "max_forks_repo_head_hexsha": "99487d22e8bdc5e717a28c4ce4bfeb573453c5dd", "max_forks_repo_licenses": ["Artistic-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2015-11-25T10:48:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-29T14:41:28.000Z", "avg_line_length": 25.4181034483, "max_line_length": 80, "alphanum_fraction": 0.5913176191, "num_tokens": 1805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.626124191181315, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.24565158045902172}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n/// @file\n/// Definitions corresponding to qpoint_grid.hpp.\n\n#include <map>\n#include <unordered_set>\n#if BOOST_VERSION >= 106700\n#include <boost/container_hash/hash.hpp>\n#else\n#include <boost/functional/hash.hpp>\n#endif\n#include <utilities.hpp>\n#include <exceptions.hpp>\n#include <qpoint_grid.hpp>\n\nnamespace std {\n/// Trivial implementation of std::hash for arrays,\n/// required to create an unordered_set of arrays.\ntemplate <typename T, std::size_t S> struct hash<std::array<T, S>> {\n    std::size_t operator()(const array<T, S>& key) const {\n        hash<T> backend;\n        std::size_t nruter = 0;\n\n        for (auto& e : key)\n            boost::hash_combine(nruter, backend(e));\n        return nruter;\n    }\n};\n} // namespace std\n\nnamespace alma {\nGamma_grid::Gamma_grid(const Crystal_structure& poscar,\n                       const Symmetry_operations& symms,\n                       const Harmonic_ifcs& force_constants,\n                       int _na,\n                       int _nb,\n                       int _nc)\n    : na(_na), nb(_nb), nc(_nc), nqpoints(_na * _nb * _nc),\n      rlattvec(poscar.rlattvec),\n      dq(rlattvec.array().rowwise() /\n         Eigen::Map<Eigen::Array3i>(\n             std::array<int, 3>({{_na, _nb, _nc}}).data())\n             .cast<double>()\n             .transpose()) {\n    if (std::min({_na, _nb, _nc}) <= 0)\n        throw value_error(\"all grid dimensions must be positive\");\n    this->initialize_cpos();\n    this->fill_equivalences(symms);\n    this->fill_map(symms);\n    Dynamical_matrix_builder builder(poscar, symms, force_constants);\n    boost::mpi::communicator world;\n    auto my_spectrum = this->compute_my_spectrum(builder, symms, world);\n    std::vector<decltype(my_spectrum)> all_spectra;\n    boost::mpi::all_gather(world, my_spectrum, all_spectra);\n\n    for (auto& s : all_spectra)\n        this->spectrum.insert(this->spectrum.end(), s.begin(), s.end());\n}\n\nGamma_grid::Gamma_grid(const Crystal_structure& poscar,\n                       const Symmetry_operations& symms,\n                       const Harmonic_ifcs& force_constants,\n                       const Dielectric_parameters& born,\n                       int _na,\n                       int _nb,\n                       int _nc)\n    : na(_na), nb(_nb), nc(_nc), nqpoints(_na * _nb * _nc),\n      rlattvec(poscar.rlattvec),\n      dq(rlattvec.array().rowwise() /\n         Eigen::Map<Eigen::Array3i>(\n             std::array<int, 3>({{_na, _nb, _nc}}).data())\n             .cast<double>()\n             .transpose()) {\n    if (std::min({_na, _nb, _nc}) <= 0)\n        throw value_error(\"all grid dimensions must be positive\");\n    this->initialize_cpos();\n    this->fill_equivalences(symms);\n    this->fill_map(symms);\n    Dynamical_matrix_builder builder(poscar, symms, force_constants, born);\n    boost::mpi::communicator world;\n    auto my_spectrum = this->compute_my_spectrum(builder, symms, world);\n    std::vector<decltype(my_spectrum)> all_spectra;\n    boost::mpi::all_gather(world, my_spectrum, all_spectra);\n\n    for (auto& s : all_spectra)\n        this->spectrum.insert(this->spectrum.end(), s.begin(), s.end());\n}\n\nvoid Gamma_grid::initialize_cpos() {\n    this->cpos.resize(3, this->nqpoints);\n    std::size_t iq = 0;\n\n    for (auto ia = 0; ia < this->na; ++ia)\n        for (auto ib = 0; ib < this->nb; ++ib)\n            for (auto ic = 0; ic < this->nc; ++ic) {\n                this->cpos(0, iq) = ia;\n                this->cpos(1, iq) = ib;\n                this->cpos(2, iq) = ic;\n                ++iq;\n            }\n    this->cpos.row(0) /= this->na;\n    this->cpos.row(1) /= this->nb;\n    this->cpos.row(2) /= this->nc;\n    this->cpos = this->rlattvec * this->cpos;\n}\n\n\nstd::vector<Spectrum_at_point> Gamma_grid::compute_my_spectrum(\n    const Dynamical_matrix_builder& factory,\n    const Symmetry_operations& symms,\n    const boost::mpi::communicator& communicator) {\n    auto nprocs = communicator.size();\n    auto my_id = communicator.rank();\n    auto limits = my_jobs(this->nqpoints, nprocs, my_id);\n\n    std::vector<Spectrum_at_point> my_spectrum;\n    my_spectrum.reserve(limits[1] - limits[0]);\n\n    // Compute the spectrum for each q point assigned to this\n    // MPI process.\n    for (auto iq = limits[0]; iq < limits[1]; ++iq) {\n        my_spectrum.emplace_back(*factory.get_spectrum(this->cpos.col(iq)));\n    }\n    // Symmetrize the group velocities at each point.\n    for (auto iq = limits[0]; iq < limits[1]; ++iq) {\n        my_spectrum[iq - limits[0]].vg =\n            this->copy_symmetry(\n                    iq, symms, my_spectrum[iq - limits[0]].vg.matrix())\n                .array();\n    }\n\n    return my_spectrum;\n}\n\n\nvoid Gamma_grid::fill_map(const Symmetry_operations& symms) {\n    auto nops = symms.get_nsym();\n    Eigen::Vector3d q;\n    Eigen::Vector3d newq;\n    Eigen::Vector3i intq;\n\n    for (std::size_t iq = 0; iq < this->nqpoints; ++iq) {\n        // A value of nqpoints in the this->symmetry map\n        // signals an invalid symmetry operation.\n        std::vector<std::size_t> images(2 * nops, this->nqpoints);\n        auto indices = this->one_to_three(iq);\n        q << indices[0] / static_cast<double>(this->na),\n            indices[1] / static_cast<double>(this->nb),\n            indices[2] / static_cast<double>(this->nc);\n\n        // Try all the symmetry operations on each q point.\n        for (decltype(nops) iop = 0; iop < nops; ++iop) {\n            newq = symms.rotate_q(q, iop);\n            newq(0) *= this->na;\n            newq(1) *= this->nb;\n            newq(2) *= this->nc;\n\n            for (auto i = 0; i < 3; ++i)\n                intq(i) = static_cast<int>(std::round(newq(i)));\n\n            // Discard an operation if it does not map the q point\n            // onto another valid q point. Some symmetry operations\n            // may be incompatible with the q-point grid.\n            if (!almost_equal(0., (newq - intq.cast<double>()).squaredNorm()))\n                continue;\n            // Compute the index of the q point obtained as the\n            // image of q through the symmetry operation, as well\n            // as the index of the q point obtained through time\n            // reversal symmetry. Append both to the images vector.\n            images[2 * iop] = this->three_to_one({{intq(0), intq(1), intq(2)}});\n            images[2 * iop + 1] =\n                this->three_to_one({{-intq(0), -intq(1), -intq(2)}});\n        }\n        this->symmetry_map.emplace_back(images);\n    }\n}\n\n\nvoid Gamma_grid::fill_equivalences(const Symmetry_operations& symms) {\n    auto nops = symms.get_nsym();\n    Eigen::Vector3d q;\n    Eigen::Vector3d newq;\n    Eigen::Vector3i intq;\n\n    this->equivalences.emplace_back(std::vector<std::size_t>{0});\n\n    // For each q point.\n    for (std::size_t iq = 1; iq < this->nqpoints; ++iq) {\n        auto indices = this->one_to_three(iq);\n        q << indices[0] / static_cast<double>(this->na),\n            indices[1] / static_cast<double>(this->nb),\n            indices[2] / static_cast<double>(this->nc);\n        // Try all the symmetry operations.\n        bool found = false;\n\n        for (decltype(nops) iop = 0; iop < nops; ++iop) {\n            newq = symms.rotate_q(q, iop);\n            newq(0) *= this->na;\n            newq(1) *= this->nb;\n            newq(2) *= this->nc;\n\n            for (auto i = 0; i < 3; ++i)\n                intq(i) = static_cast<int>(std::round(newq(i)));\n\n            // Discard an operation if it does not map the q point\n            // onto another valid q point. Some symmetry operations\n            // may be incompatible with the q-point grid.\n            if (!almost_equal(0., (newq - intq.cast<double>()).squaredNorm()))\n                continue;\n            // Compute the index of the q point obtained as the\n            // image of q through the symmetry operation.\n            auto candidate1 = this->three_to_one({{intq(0), intq(1), intq(2)}});\n            // And the index of the q point obtained through time\n            // reversal symmetry.\n            auto candidate2 =\n                this->three_to_one({{-intq(0), -intq(1), -intq(2)}});\n\n            // If either of candidate1 or candidate2 are the first\n            // elements of an existing equivalence class, add iq\n            // to that class.\n            for (auto& c : this->equivalences)\n                if ((candidate1 == c[0]) || (candidate2 == c[0])) {\n                    c.emplace_back(iq);\n                    found = true;\n                    break;\n                }\n\n            if (found)\n                break;\n        }\n\n        // If iq cannot be assigned to any existing equivalence class,\n        // start a new one.\n        if (!found) {\n            auto size = this->equivalences.size();\n            this->equivalences.resize(size + 1);\n            this->equivalences[size].emplace_back(iq);\n        }\n    }\n\n    this->fill_parentlookup();\n}\n\n\nvoid Gamma_grid::fill_parentlookup() {\n    this->parentlookup.resize(this->nqpoints);\n\n    for (std::size_t nclass = 0; nclass < this->equivalences.size(); nclass++) {\n        for (std::size_t nmember = 0;\n             nmember < this->equivalences[nclass].size();\n             nmember++) {\n            this->parentlookup.at(this->equivalences[nclass].at(nmember)) =\n                this->equivalences[nclass].at(0);\n        }\n    }\n}\n\n\nstd::size_t Gamma_grid::getParentIdx(std::size_t iq) const {\n    if (iq >= this->nqpoints)\n        throw value_error(\"invalid q point index\");\n\n    return this->parentlookup.at(iq);\n}\n\n\nstd::size_t Gamma_grid::getSymIdxToParent(std::size_t iq) const {\n    if (iq >= this->nqpoints)\n        throw value_error(\"invalid q point index\");\n\n    std::size_t iq_parent = this->parentlookup.at(iq);\n\n    std::size_t i;\n\n    for (i = 0; i < this->symmetry_map[iq].size(); ++i) {\n        auto iq_image = this->symmetry_map[iq][i];\n        if (iq_image == iq_parent)\n            return i;\n    }\n    throw exception(\"some point is not in symmetry_map\");\n}\n\n\nGamma_grid::Gamma_grid(const Crystal_structure& poscar,\n                       const Symmetry_operations& symms,\n                       int _na,\n                       int _nb,\n                       int _nc)\n    : na(_na), nb(_nb), nc(_nc), nqpoints(_na * _nb * _nc),\n      rlattvec(poscar.rlattvec),\n      dq(rlattvec.array().rowwise() /\n         Eigen::Map<Eigen::Array3i>(\n             std::array<int, 3>({{_na, _nb, _nc}}).data())\n             .cast<double>()\n             .transpose()) {\n    if (std::min({_na, _nb, _nc}) <= 0)\n        throw value_error(\"all grid dimensions must be positive\");\n    this->initialize_cpos();\n    this->fill_equivalences(symms);\n    this->fill_map(symms);\n}\n\nstd::vector<std::array<std::size_t, 2>> Gamma_grid::equivalent_qpairs(\n    const std::array<std::size_t, 2>& original) const {\n    auto iq1 = original[0];\n    auto iq2 = original[1];\n\n    if ((iq1 >= this->nqpoints) || (iq2 >= this->nqpoints))\n        throw value_error(\"invalid q point index\");\n\n    std::unordered_set<std::array<std::size_t, 2>> unique;\n\n    // Loop over the images of both q points looking\n    // for all unique equivalent pairs.\n    for (std::size_t i = 0; i < this->symmetry_map[0].size(); ++i) {\n        auto jq1 = this->symmetry_map[iq1][i];\n        auto jq2 = this->symmetry_map[iq2][i];\n        std::array<std::size_t, 2> candidate({{jq1, jq2}});\n        unique.emplace(candidate);\n    }\n\n    return std::vector<std::array<std::size_t, 2>>(unique.begin(),\n                                                   unique.end());\n}\n\n\nstd::vector<std::array<std::size_t, 3>> Gamma_grid::equivalent_qtriplets(\n    const std::array<std::size_t, 3>& original) const {\n    auto iq1 = original[0];\n    auto iq2 = original[1];\n    auto iq3 = original[2];\n\n    if ((iq1 >= this->nqpoints) || (iq2 >= this->nqpoints) ||\n        (iq3 >= this->nqpoints))\n        throw value_error(\"invalid q point index\");\n\n    std::unordered_set<std::array<std::size_t, 3>> unique;\n\n    // Loop over the images of all three q points looking\n    // for all unique equivalent triplets.\n    for (std::size_t i = 0; i < this->symmetry_map[0].size(); ++i) {\n        auto jq1 = this->symmetry_map[iq1][i];\n        auto jq2 = this->symmetry_map[iq2][i];\n        auto jq3 = this->symmetry_map[iq3][i];\n        std::array<std::size_t, 3> candidate({{jq1, jq2, jq3}});\n        if (jq1 < this->nqpoints && jq2 < this->nqpoints &&\n            jq3 < this->nqpoints) {\n            unique.emplace(candidate);\n        }\n    }\n\n    return std::vector<std::array<std::size_t, 3>>(unique.begin(),\n                                                   unique.end());\n}\n\n\nstd::vector<Triangle> Gamma_grid::get_triangles(std::size_t ia) const {\n    std::vector<Triangle> triangles;\n    int itriangle = 0;\n\n    for (int ib = 0; ib < this->nb; ++ib)\n        for (int ic = 0; ic < this->nc; ++ic) {\n            std::array<int, 3> indices({{static_cast<int>(ia), ib, ic}});\n            std::size_t i000 =\n                this->three_to_one({{indices[0], indices[1], indices[2]}});\n            std::size_t i010 =\n                this->three_to_one({{indices[0], indices[1] + 1, indices[2]}});\n            std::size_t i001 =\n                this->three_to_one({{indices[0], indices[1], indices[2] + 1}});\n            std::size_t i011 = this->three_to_one(\n                {{indices[0], indices[1] + 1, indices[2] + 1}});\n            triangles.emplace_back(Triangle({{i000, i010, i011}}));\n            triangles.emplace_back(Triangle({{i000, i001, i011}}));\n            itriangle += 2;\n        }\n    return triangles;\n}\n} // namespace alma\n", "meta": {"hexsha": "7862c0bd3f0d3216286bfa16f06aa82217c6e935", "size": 14153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/qpoint_grid.cpp", "max_stars_repo_name": "sousaw/BTE-Barna", "max_stars_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T03:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:11:20.000Z", "max_issues_repo_path": "src/qpoint_grid.cpp", "max_issues_repo_name": "sousaw/BTE-Barna", "max_issues_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qpoint_grid.cpp", "max_forks_repo_name": "sousaw/BTE-Barna", "max_forks_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.1045918367, "max_line_length": 80, "alphanum_fraction": 0.5730233873, "num_tokens": 3778, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.24564155301056115}}
{"text": "/*\n  SPDX-License-Identifier: MIT\n\n*/\n\n#ifndef TOKEN_H\n#define TOKEN_H\n\n/**\n * @file\n * Token scanner.\n * This file declares the token scanner class, tokenizer_t, plus the\n * different possible tokens that it can return.\n * @par\n * The token scanner interface is trivial, it only has a constructor and\n * a method for providing the next token, if any.\n */\n\n#include <memory>\n#include <system_error>\n#include \"environment.hh\"\n#include \"sbucket.hh\"\n#include \"position.hh\"\n#include \"mmap_file.hh\"\n#include <boost/multiprecision/mpfr.hpp>\n#include <boost/multiprecision/gmp.hpp>\n\n/**\n * Multi-precision integer type.\n * This type is used to store Sisdel integers, which are by default multi-\n * precision integers. This means that the integer can be as large as the\n * available memory allows.\n */\ntypedef boost::multiprecision::number<boost::multiprecision::gmp_int> mp_int;\n\n/**\n * Multi-precision floating point type.\n * This type is used to store Sisdel floating point numbers, which are by\n * default multi-precision floating point numbers. This means that the\n * value can be as large, and with selectable precision, as the available\n * memory allows.\n */\ntypedef boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<0> > mp_float;\n\nclass token_t;\n\n/**\n * Token scanner.\n * Reads the given file and split it into a stream of tokens.\n *\n * @todo Implement support for standard input as source.\n */\nclass tokenizer_t {\npublic:\n\n\t/**\n\t * Construct the scanner.\n\t *\n\t * @todo When environment object has been made thread local, the\n\t *       env parameter should be removed.\n\t */\n\ttokenizer_t(\n\t\tenvironment_t& env, /**< Reference to environment object. */\n\t\tconst char* file    /**< Name of file in UTF8 format. */\n\t\t);\n\n\t/**\n\t * Return next token.\n\t *\n\t * @returns Next token in the token stream, or NULL if end of file.\n\t */\n\tconst token_t* next(void);\n\nprivate:\n\tvoid get_number(mp_int& nr, char base,\n\t\t\tconst char *valid_digits, size_t& nr_digits);\n\n\tenvironment_t& m_env;\n\tmmap_file_t m_file;\n\tposition_t m_startofline;\n};\n\n/**\n * Base class for tokens.\n * This class provides the interface provided by all inherited tokens.\n * This is a virtual class, so no token is of this type.\n * @par\n * Use constructs like \"typeid(returned_token) == typeid(token_eol_t)\"\n * to determine what kind of token this is, and then use\n * dynamic_cast to cast it to the correct type.\n */\nclass token_t {\npublic:\n\t/**\n\t * Destructor.\n\t * Virtual destructor since this class will be inherited by other\n\t * classes.\n\t */\n\tvirtual ~token_t() noexcept {};\n\n\t/**\n\t * Determine where in the input stream this token was found.\n\t *\n\t * @returns Position in input stream.\n\t */\n\tvirtual const position_t& position(void) const noexcept = 0;\n};\n\n/**\n * End of line token.\n * This token is returned when an end of line character is found.\n * Any multiple end of line characters are skipped, as are empty lines or\n * lines with only comments.\n * The token provides indentation level, i.e. how many tab characters that\n * were found right after the end of line character.\n */\nclass token_eol_t : public token_t {\npublic:\n\t/**\n\t * Constructor, used by the scanner.\n\t */\n\ttoken_eol_t(\n\t\tconst position_t& pos, /**< Position in input stream where\n\t\t\t\t\t* this token was found. */\n\t\tsize_t indent_level    /**< Indentation level, i.e. number of\n\t\t\t\t\t* tab characters right after the\n\t\t\t\t\t* end of line character. */\n\t\t)\n\t\t: m_position(pos), m_indent_level(indent_level) {}\n\n\t/**\n\t * Return indentation level.\n\t *\n\t * @returns The indentation level, i.e. number of tab characters,\n\t *          right after the end of line character.\n\t */\n\tconstexpr size_t indent_level(void) const noexcept\n\t\t{ return m_indent_level; }\n\n\t//\n\t// Inherited from token_t\n\t//\n\n\tconst position_t& position(void) const noexcept\n\t\t{ return m_position; }\n\nprivate:\n\tposition_t m_position;\n\tsize_t m_indent_level;\n};\n\n/**\n * String token.\n * This token represents a string immediate value.\n */\nclass token_string_t : public token_t {\npublic:\n\t/**\n\t * Constructor, used by scanner.\n\t */\n\ttoken_string_t(\n\t\tconst position_t& pos, /**< Position in input stream where\n\t\t\t\t\t* this token was found. */\n\t\tstring_idx_t str       /**< String content as a string_idx_t. */\n\t\t)\n\t\t: m_position(pos), m_string(str) {}\n\n\tconstexpr string_idx_t string(void) const noexcept\n\t\t{ return m_string; }\n\n\n\t//\n\t// Inherited from token_t\n\t//\n\n\tconst position_t& position(void) const noexcept\n\t\t{ return m_position; }\n\nprivate:\n\tposition_t m_position;\n\tstring_idx_t m_string;\n};\n\nclass token_identifier_t : public token_t {\npublic:\n\ttoken_identifier_t(const position_t& pos, string_idx_t name)\n\t\t: m_position(pos), m_name(name) {}\n\n\tconstexpr string_idx_t name(void) const noexcept\n\t\t{ return m_name; }\n\n\t//\n\t// Inherited from token_t\n\t//\n\n\tconst position_t& position(void) const noexcept\n\t\t{ return m_position; }\n\nprivate:\n\tposition_t m_position;\n\tstring_idx_t m_name;\n};\n\nclass token_integer_t : public token_t {\npublic:\n\ttoken_integer_t(const position_t& pos, const mp_int& value)\n\t\t: m_position(pos), m_integer(value) {}\n\n\tconstexpr const mp_int& value(void) const noexcept\n\t\t{ return m_integer; }\n\n\t//\n\t// Inherited from token_t\n\t//\n\n\tconst position_t& position(void) const noexcept\n\t\t{ return m_position; }\n\nprivate:\n\tposition_t m_position;\n\tmp_int m_integer;\n};\n\nclass token_float_t : public token_t {\npublic:\n\ttoken_float_t(const position_t& pos, const mp_float& floating)\n\t\t: m_position(pos), m_float(floating) {}\n\n\tconstexpr const mp_float& value(void) const noexcept\n\t\t{ return m_float; }\n\n\t//\n\t// Inherited from token_t\n\t//\n\n\tconst position_t& position(void) const noexcept\n\t\t{ return m_position; }\n\nprivate:\n\tposition_t m_position;\n\tmp_float m_float;\n};\n\nstd::ostream& operator<<(std::ostream& os, const token_t& t);\n\n#endif /* TOKEN_H */\n", "meta": {"hexsha": "a6dfed55fb693512e883ba2f3592de7e541da9db", "size": 5785, "ext": "hh", "lang": "C++", "max_stars_repo_path": "lib/include/token.hh", "max_stars_repo_name": "matslil/sisdel", "max_stars_repo_head_hexsha": "7252e1e7a032a72c32d6ce7f6c7fd285f45ea809", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/include/token.hh", "max_issues_repo_name": "matslil/sisdel", "max_issues_repo_head_hexsha": "7252e1e7a032a72c32d6ce7f6c7fd285f45ea809", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/include/token.hh", "max_forks_repo_name": "matslil/sisdel", "max_forks_repo_head_hexsha": "7252e1e7a032a72c32d6ce7f6c7fd285f45ea809", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4210526316, "max_line_length": 94, "alphanum_fraction": 0.7109766638, "num_tokens": 1408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2453118435562797}}
{"text": "#include \"path.h\"\n\n#include <boost/log/trivial.hpp>\n\nnamespace WorldEngine\n{\n\nstruct Node;\ntypedef std::shared_ptr<Node> NodePtr;\ntypedef std::list<NodePtr>    NodeList;\n\nconst uint32_t MAX_PATH_ITERATIONS = 10000u;\n\n/**\n * @brief The basic unit, pixel or location\n */\nstruct Node\n{\n   Point   location_;     /**< Where the node is located */\n   float   movementCost_; /**< Total move cost to reach this node */\n   float   score_;        /**< Calculated score for this node */\n   NodePtr parent_;       /**< Parent node */\n\n   Node(Point location, float movementCost, NodePtr parent = nullptr) :\n       location_(location),\n       movementCost_(movementCost),\n       score_(0.0f),\n       parent_(parent)\n   {\n   }\n};\n\nstruct Path\n{\n   NodeList nodes_;\n   float    totalCost_;\n\n   Path(NodeList nodes, float totalCost) : nodes_(nodes), totalCost_(totalCost)\n   {\n   }\n};\n\nbool operator==(const Node& lhs, const Node& rhs)\n{\n   return lhs.location_ == rhs.location_;\n}\n\n/**\n * @brief A simple square map implementation\n */\nstruct SQMapHandler\n{\n   const ElevationArrayType& mapData_;\n   const int32_t             width_;\n   const int32_t             height_;\n\n   SQMapHandler(const ElevationArrayType& mapData,\n                int32_t                   width,\n                int32_t                   height) :\n       mapData_(mapData), width_(width), height_(height)\n   {\n   }\n\n   NodeList GetAdjacentNodes(NodePtr currentNode, Point destination) const\n   {\n      NodeList result;\n\n      const Point& cl = currentNode->location_;\n      const Point& dl = destination;\n\n      NodePtr n;\n\n      n = HandleNode(cl.first + 1, cl.second, currentNode, dl.first, dl.second);\n      if (n != nullptr)\n      {\n         result.push_back(n);\n      }\n\n      n = HandleNode(cl.first - 1, cl.second, currentNode, dl.first, dl.second);\n      if (n != nullptr)\n      {\n         result.push_back(n);\n      }\n\n      n = HandleNode(cl.first, cl.second + 1, currentNode, dl.first, dl.second);\n      if (n != nullptr)\n      {\n         result.push_back(n);\n      }\n\n      n = HandleNode(cl.first, cl.second - 1, currentNode, dl.first, dl.second);\n      if (n != nullptr)\n      {\n         result.push_back(n);\n      }\n\n      return result;\n   }\n\n   NodePtr GetNode(Point location) const\n   {\n      int32_t x = location.first;\n      int32_t y = location.second;\n      if (x < 0 || x >= width_ || y < 0 || y >= height_)\n      {\n         return nullptr;\n      }\n      float d = mapData_[y][x];\n      return std::make_shared<Node>(location, d);\n   }\n\n   NodePtr HandleNode(int32_t x,\n                      int32_t y,\n                      NodePtr fromNode,\n                      int32_t destX,\n                      int32_t destY) const\n   {\n      NodePtr n = GetNode({x, y});\n\n      if (n != nullptr)\n      {\n         int32_t dx     = std::max(x, destX) - std::min(x, destX);\n         int32_t dy     = std::max(y, destY) - std::min(y, destY);\n         int32_t emCost = dx + dy;\n         n->movementCost_ += fromNode->movementCost_;\n         n->score_  = n->movementCost_ + emCost;\n         n->parent_ = fromNode;\n      }\n\n      return n;\n   }\n};\n\n/**\n * @brief The A* Search Algorithm\n *\n * https://en.wikipedia.org/wiki/A*_search_algorithm\n *\n * TODO: Use Boost implementation\n */\nstruct AStar\n{\n   const SQMapHandler& mapHandler_;\n   NodeList            openSet;\n   NodeList            closedSet;\n\n   AStar(const SQMapHandler& mapHandler) : mapHandler_(mapHandler) {}\n\n   NodePtr GetBestOpenNode()\n   {\n      NodePtr bestNode = nullptr;\n\n      for (NodePtr n : openSet)\n      {\n         if (bestNode == nullptr || n->score_ <= bestNode->score_)\n         {\n            bestNode = n;\n         }\n      }\n\n      return bestNode;\n   }\n\n   static Path TracePath(NodePtr n)\n   {\n      NodeList nodes;\n      NodePtr  p         = n->parent_;\n      float    totalCost = n->movementCost_;\n\n      nodes.push_front(n);\n\n      while (p->parent_ != nullptr)\n      {\n         nodes.push_front(p);\n         p = p->parent_;\n      }\n\n      return Path(nodes, totalCost);\n   }\n\n   NodePtr HandleNode(NodePtr node, Point end)\n   {\n      openSet.remove_if([&node](const NodePtr o) { return *node == *o; });\n      closedSet.push_back(node);\n\n      NodeList nodes = mapHandler_.GetAdjacentNodes(node, end);\n\n      NodeList::iterator openNode;\n\n      for (NodePtr n : nodes)\n      {\n         if (n->location_ == end)\n         {\n            // Reached the destination\n            return n;\n         }\n         else if (std::find_if(closedSet.begin(), //\n                               closedSet.end(),\n                               [&n](const NodePtr o) { return *n == *o; }) !=\n                  closedSet.end())\n         {\n            // Already in closed set, skip this\n            continue;\n         }\n         else if ((openNode = std::find_if(openSet.begin(), //\n                                           openSet.end(),\n                                           [&n](const NodePtr o) {\n                                              return *n == *o;\n                                           })) != openSet.end())\n         {\n            // Already in open set, check if better score\n            if (n->movementCost_ < (*openNode)->movementCost_)\n            {\n               openSet.erase(openNode);\n               openSet.push_back(n);\n            }\n         }\n         else\n         {\n            // New node, append to open set\n            openSet.push_back(n);\n         }\n      }\n\n      return nullptr;\n   }\n\n   Path FindPath(Point fromLocation, Point toLocation)\n   {\n      NodePtr nextNode = mapHandler_.GetNode(fromLocation);\n      openSet.push_back(nextNode);\n\n      uint32_t counter = 0;\n\n      while (nextNode != nullptr)\n      {\n         if (counter > MAX_PATH_ITERATIONS)\n         {\n            BOOST_LOG_TRIVIAL(warning) << \"FindPath: Exceeded trial limit\";\n            break;\n         }\n\n         NodePtr finish = HandleNode(nextNode, toLocation);\n         if (finish != nullptr)\n         {\n            return TracePath(finish);\n         }\n\n         nextNode = GetBestOpenNode();\n         counter++;\n      }\n\n      return Path(NodeList(), 0.0f);\n   }\n};\n\nstd::list<Point>\nFindPath(const ElevationArrayType& elevation, Point source, Point destination)\n{\n   std::list<Point> path;\n\n   const int32_t width  = static_cast<int32_t>(elevation.shape()[1]);\n   const int32_t height = static_cast<int32_t>(elevation.shape()[0]);\n\n   SQMapHandler mapHandler(elevation, width, height);\n   AStar        pathFinder(mapHandler);\n   Path         p = pathFinder.FindPath(source, destination);\n\n   for (NodePtr n : p.nodes_)\n   {\n      path.push_back(n->location_);\n   }\n\n   return path;\n}\n\n} // namespace WorldEngine\n", "meta": {"hexsha": "756c70590df9c018a9e5da4d9349879fad9f6b44", "size": 6672, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "worldengine/source/path.cpp", "max_stars_repo_name": "dpaulat/worldengine-cpp", "max_stars_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T12:44:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T21:52:10.000Z", "max_issues_repo_path": "worldengine/source/path.cpp", "max_issues_repo_name": "dpaulat/worldengine-cpp", "max_issues_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-09T12:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T15:28:37.000Z", "max_forks_repo_path": "worldengine/source/path.cpp", "max_forks_repo_name": "dpaulat/worldengine-cpp", "max_forks_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.0, "max_line_length": 80, "alphanum_fraction": 0.5370203837, "num_tokens": 1577, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.24531184355627966}}
{"text": "#include <cmath>\n#include <algorithm>\n#include <armadillo>\n#include <thread>\n#include \"RHF.hpp\"\n#include \"RHFGrad.hpp\"\n\nusing namespace std;\nusing namespace libint2;\n\n\n\nnamespace willow {  namespace qcmol {\n\n\nstatic unsigned int num_threads;\n\nstatic arma::vec compute_nuclear_gradient (const vector<Atom>& atoms,\n\t\t\t\t\t   const vector<QAtom>& atoms_Q,\n\t\t\t\t\t   arma::vec& grd_Q);\n\n\nvoid compute_2body_deriv_ints (const int thread_id,\n\t\t\t       const BasisSet& obs,\n\t\t\t       const vector<Atom>& atoms,\n\t\t\t       const arma::mat& Dm,\n\t\t\t       const arma::mat& Schwartz,\n\t\t\t       arma::vec& result);\n\n\ntemplate <libint2::Operator obtype>\nvoid compute_1body_deriv_ints (const int thread_id,\n\t\t\t       const BasisSet& obs,\n\t\t\t       const vector<Atom>& atoms,\n\t\t\t       const arma::mat& Dm,\n\t\t\t       arma::vec& result);\n\nvoid compute_1body_deriv_nuclear (const int thread_id,\n\t\t\t\t  const BasisSet& obs,\n\t\t\t\t  const vector<Atom>& atoms,\n\t\t\t\t  const arma::mat& Dm,\n\t\t\t\t  const vector<QAtom>& atoms_Q,\n\t\t\t\t  arma::vec& grd,\n\t\t\t\t  arma::vec& grd_Q);\n\n//-----\n//\n//----\nRHFGrad::RHFGrad (const vector<Atom>& atoms,\n\t\t  const BasisSet& bs,\n\t\t  const Integrals& ints,\n\t\t  const int qm_chg,\n\t\t  const bool l_print,\n\t\t  const vector<QAtom>& atoms_Q )\n  : RHF (atoms, bs, ints, qm_chg, l_print, atoms_Q)\n{\n\n  num_threads = std::thread::hardware_concurrency();\n  if (num_threads == 0) num_threads = 1;\n  \n  arma::mat D = densityMatrix ();\n  arma::mat W = energyWeightDensityMatrix ();\n  \n  const auto natom = atoms.size();\n  const auto nbf   = bs.nbf();\n\n  vector<arma::vec> grd_kin_t (num_threads);\n  vector<arma::vec> grd_nuc_t (num_threads);\n  vector<arma::vec> grd_nuc_Q_t(num_threads);\n  vector<arma::vec> frc_orth_t(num_threads);\n\n  vector<std::thread> t_grd_kin (num_threads);\n  vector<std::thread> t_grd_nuc (num_threads);\n  vector<std::thread> t_frc_orth(num_threads);\n\n  vector<QAtom> bq_Q;\n  \n  for (int id = 0; id < num_threads; ++id) {\n    // Kinetic \n    t_grd_kin[id] =\n      std::thread (compute_1body_deriv_ints<libint2::Operator::kinetic>,\n\t\t   id,\n\t\t   std::cref(bs),\n\t\t   std::cref(atoms),\n\t\t   std::cref(D),\n\t\t   std::ref(grd_kin_t[id]) );\n    // Nuclear Der \n    t_grd_nuc[id] =\n      std::thread (compute_1body_deriv_nuclear,\n\t\t   id,\n\t\t   std::cref(bs),\n\t\t   std::cref(atoms),\n\t\t   std::cref(D),\n\t\t   std::cref(atoms_Q), \n\t\t   std::ref(grd_nuc_t[id]),\n\t\t   std::ref(grd_nuc_Q_t[id]) );\n    \n    // Overlap\n    t_frc_orth[id] =\n      std::thread (compute_1body_deriv_ints<libint2::Operator::overlap>,\n\t\t   id,\n\t\t   std::cref(bs),\n\t\t   std::cref(atoms),\n\t\t   std::cref(W),\n\t\t   std::ref(frc_orth_t[id]) );\n  }\n\n\n  // Join\n  for (auto id = 0; id < num_threads; ++id) {\n    t_grd_kin[id].join();\n    t_grd_nuc[id].join();\n    t_frc_orth[id].join();\n  }\n\n  for (auto id = 1; id < num_threads; ++id) {\n    grd_kin_t[0]  += grd_kin_t[id];\n    grd_nuc_t[0]  += grd_nuc_t[id];\n    grd_nuc_Q_t[0] += grd_nuc_Q_t[id];\n    frc_orth_t[0] += frc_orth_t[id];\n  }\n  \n  // Nuclear Repulsion\n  arma::vec grd_rep_Q (3*atoms_Q.size(), arma::fill::zeros);\n  arma::vec grd_rep  = compute_nuclear_gradient (atoms, atoms_Q, grd_rep_Q);\n\n  // Two electron Integral\n  vector<arma::vec>   grd_eri_t (num_threads);\n  vector<std::thread> t_grd_eri (num_threads);\n\n  for (auto id = 0; id < num_threads; ++id) {\n    t_grd_eri[id] =\n      std::thread (compute_2body_deriv_ints,\n\t\t   id,\n\t\t   std::cref(bs),\n\t\t   std::cref(atoms),\n\t\t   std::cref(D),\n\t\t   std::cref(ints.Km),\n\t\t   std::ref(grd_eri_t[id]) );\n  }\n\n  for (auto id = 0; id < num_threads; ++id)\n    t_grd_eri[id].join();\n\n\n  for (auto id = 1; id < num_threads; ++id)\n    grd_eri_t[0] += grd_eri_t[id];\n\n  m_grad = grd_kin_t[0] + grd_nuc_t[0] - frc_orth_t[0] + grd_rep + grd_eri_t[0];\n  m_grad_Q = grd_nuc_Q_t[0] + grd_rep_Q;\n  \n  if (l_print) {\n    cout << \"Total Gradient (QM): \" << endl;\n  \n    for (auto i = 0; i < natom; ++i)\n      cout << (i + 1)\n\t   << \"  \" << m_grad(3*i)\n\t   << \"  \" << m_grad(3*i+1) \n\t   << \"  \" << m_grad(3*i+2) << endl;\n\n    auto natom_Q = atoms_Q.size();\n\n    if (natom_Q > 0) {\n      cout << \"Total Gradient (BQ): \" << endl;\n      for (auto i = 0; i < natom_Q; ++i)\n\tcout << (i + 1)\n\t     << \"  \" << m_grad_Q(3*i)\n\t     << \"  \" << m_grad_Q(3*i+1) \n\t     << \"  \" << m_grad_Q(3*i+2) << endl;\n    }\n    \n  }\n}\n\n\n\n\ntemplate<libint2::Operator obtype>\nvoid compute_1body_deriv_ints (const int thread_id,\n\t\t\t       const BasisSet& bs,\n\t\t\t       const vector<Atom>& atoms,\n\t\t\t       const arma::mat& Dm,\n\t\t\t       arma::vec& grd)\n{\n  const auto nshl = bs.size();\n  const auto nbf  = bs.nbf();\n  const auto natom = atoms.size();\n\n  const unsigned deriv_order = 1;\n  \n  constexpr auto nopers = libint2::operator_traits<obtype>::nopers;\n\n  const auto nresults = nopers * libint2::num_geometrical_derivatives (natom, deriv_order);\n\n  grd = arma::vec(nresults, arma::fill::zeros);\n\n  libint2::Engine engine (obtype,\n\t\t\t  bs.max_nprim(),\n\t\t\t  bs.max_l(),\n\t\t\t  deriv_order);\n\n  const auto& buf = engine.results();\n  \n  auto shell2bf = bs.shell2bf();\n  auto shell2atom = bs.shell2atom(atoms);\n\n  for (auto s1 = 0, s12 = 0; s1 != nshl; ++s1){\n    auto bf1  = shell2bf[s1];\n    auto nbf1 = bs[s1].size();\n    auto at1  = shell2atom[s1];\n    \n    assert (at1 != -1);\n    \n    for (auto s2 = 0; s2 <= s1; ++s2, ++s12){\n\n      if (s12 % num_threads != thread_id) continue;\n      \n      auto bf2  = shell2bf[s2];\n      auto nbf2 = bs[s2].size();\n      auto at2  = shell2atom[s2];\n      \n      auto nbf12 = nbf1*nbf2;\n      \n      engine.compute (bs[s1], bs[s2]);\n      \n      assert(deriv_order == 1);\n      \n      // 1. Process derivatives with respect to the Gaussian origins first\n      //\n      for (unsigned int d = 0; d != 6; ++d) { // 2 centers x 3 axes\n\tauto iat = d < 3 ? at1 : at2;\n\tauto op_start = (3*iat + d%3)*nopers;\n\tauto op_fence = op_start + nopers;\n\tconst auto* buf_idx = buf[d];\n\tif (buf_idx == nullptr) continue;\n\n\tfor (unsigned int op = op_start; op != op_fence; ++op) {\n\n\t  for (auto ib = 0, ij = 0; ib < nbf1; ib++)\n\t    for (auto jb = 0; jb < nbf2; jb++, ij++) {\n\t      const auto val = buf_idx[ij];\n\t\t\n\t      grd(op) += Dm(bf1+ib,bf2+jb)*val;\n\t      \n\t      if (s1 != s2) {\n\t\tgrd(op) += Dm(bf2+jb,bf1+ib)*val;\n\t      }\n\t\t\n\t    }\n\t} // exit op\n      } // exit d\n\t\n      \n    }\n  }\n\n}\n\n\n\nvoid compute_1body_deriv_nuclear (const int thread_id,\n\t\t\t\t  const BasisSet& bs,\n\t\t\t\t  const vector<Atom>& atoms,\n\t\t\t\t  const arma::mat& Dm,\n\t\t\t\t  const vector<QAtom>& atoms_Q,\n\t\t\t\t  arma::vec& grd,\n\t\t\t\t  arma::vec& grd_Q)\n{\n  const auto nshl = bs.size();\n  const auto nbf  = bs.nbf();\n  const auto natom = atoms.size();\n  const auto natom_Q = atoms_Q.size();\n\n  const unsigned deriv_order = 1;\n  constexpr auto nopers = libint2::operator_traits<Operator::nuclear>::nopers;\n\n  const auto nresults = nopers * libint2::num_geometrical_derivatives (natom, deriv_order);\n\n  grd   = arma::vec(nresults, arma::fill::zeros);\n  grd_Q = arma::vec(atoms_Q.size()*3, arma::fill::zeros);\n  \n  libint2::Engine engine (Operator::nuclear,\n\t\t\t  bs.max_nprim(),\n\t\t\t  bs.max_l(),\n\t\t\t  deriv_order);\n\n  const auto& buf = engine.results ();\n  \n  // nuclear attraction ints engine\n  vector<pair<double, array<double,3>>> q;\n  for (const auto& atom : atoms){\n    q.push_back( {static_cast<double> (atom.atomic_number), \n\t  {{atom.x, atom.y, atom.z}}} );\n  }\n\n  for (auto iq = 0; iq < natom_Q; ++iq) {\n    q.push_back ( {atoms_Q[iq].charge,\n\t  {{atoms_Q[iq].x, atoms_Q[iq].y, atoms_Q[iq].z}}} );\n  }\n  \n  engine.set_params(q);\n  \n  \n  auto shell2bf = bs.shell2bf();\n  auto shell2atom = bs.shell2atom(atoms);\n  \n  for (auto s1 = 0, s12 = 0; s1 != nshl; ++s1){\n    auto bf1  = shell2bf[s1];\n    auto nbf1 = bs[s1].size();\n    auto at1  = shell2atom[s1];\n    \n    assert (at1 != -1);\n    \n    for (auto s2 = 0; s2 <= s1; ++s2, ++s12){\n\n      if (s12 % num_threads != thread_id) continue;\n      \n      auto bf2  = shell2bf[s2];\n      auto nbf2 = bs[s2].size();\n      auto at2  = shell2atom[s2];\n      \n      auto nbf12 = nbf1*nbf2;\n      \n      engine.compute (bs[s1], bs[s2]);\n      \n      assert(deriv_order == 1);\n      \n      // 1. Process derivatives with respect to the Gaussian origins first\n      //\n      for (unsigned int d=0; d != 6; ++d){ // 2 centers x 3 axes = 6 cartesian geometric derivatives\n\t\n\tauto iat = d < 3 ? at1 : at2;\n\tauto op_start = (3*iat + d%3)*nopers;\n\tauto op_fence = op_start + nopers;\n\n\tconst auto* buf_idx = buf[d];\n\tif (buf_idx == nullptr) continue;\n\t\n\tfor (unsigned int op = op_start; op != op_fence; ++op) {\n\t  \n\t  for (auto ib = 0, ij = 0; ib < nbf1; ib++)\n\t    for (auto jb = 0; jb < nbf2; jb++, ij++) {\n\t      const auto val = buf_idx[ij];\n\n\t      grd(op) += Dm(bf1+ib,bf2+jb)*val;\n\t      \n\t      if (s1 != s2) {\n\t\tgrd(op) += Dm(bf2+jb,bf1+ib)*val;\n\t      }\n\t      \n\t    }\n\t}\n\t\n      } // d\n      \n      // 2. Process derivatives of nuclear Coulomb operators,\n      for (unsigned int iat = 0; iat != natom; ++iat) {\n\tfor (unsigned int ixyz = 0; ixyz != 3; ++ixyz) {\n\t    \n\t  const auto* buf_idx = buf[6 + iat*3 + ixyz];\n\t  \n\t  auto op_start = (3*iat + ixyz) * nopers;\n\t  auto op_fence = op_start + nopers;\n\t    \n\t  for (unsigned int op = op_start;\n\t       op != op_fence; ++op) {\n\t      \n\t    for (auto ib = 0, ij = 0; ib < nbf1; ib++)\n\t      for (auto jb = 0; jb < nbf2; jb++, ij++) {\n\t\tconst double val = buf_idx[ij];\n\t\t\n\t\tgrd(op) += Dm(bf1+ib,bf2+jb)*val;\n\t\tif (s1 != s2) \n\t\t  grd(op) += Dm(bf2+jb,bf1+ib)*val;\n\t\t\n\t      }\n\t  }\n\t}\n      } // iat =\n\n      for (unsigned int iq = 0; iq != natom_Q; ++iq) {\n\tfor (unsigned int ixyz = 0; ixyz != 3; ++ixyz) {\n\t    \n\t  const auto* buf_idx = buf[6 + (natom + iq)*3 + ixyz];\n\t  auto op_start = (3*iq + ixyz) * nopers;\n\t  auto op_fence = op_start + nopers;\n\t    \n\t  for (unsigned int op = op_start;\n\t       op != op_fence; ++op) {\n\t      \n\t    for (auto ib = 0, ij = 0; ib < nbf1; ib++)\n\t      for (auto jb = 0; jb < nbf2; jb++, ij++) {\n\t\tconst double val = buf_idx[ij];\n\t\t\n\t\tgrd_Q(op) += Dm(bf1+ib,bf2+jb)*val;\n\t\tif (s1 != s2) \n\t\t  grd_Q(op) += Dm(bf2+jb,bf1+ib)*val;\n\t\t\n\t      }\n\t  }\n\t}\n      } // iQ =\n\n      \n    }\n  \n  }\n\n}\n\n\n\narma::vec compute_nuclear_gradient (const vector<Atom>& atoms,\n\t\t\t\t    const vector<QAtom>& atoms_Q,\n\t\t\t\t    arma::vec& grd_Q)\n{\n  arma::vec grd (3*atoms.size(), arma::fill::zeros);\n  if (atoms_Q.size() > 0) \n    grd_Q.zeros();\n  \n  for (auto i = 0; i < atoms.size(); ++i) {\n    double chg_i = (double)atoms[i].atomic_number;\n    double xi = atoms[i].x;\n    double yi = atoms[i].y;\n    double zi = atoms[i].z;\n\n    for (auto j = 0; j < i; ++j) {\n      double chg_j = (double)atoms[j].atomic_number;\n      // calculate distance\n      \n      double dx = xi - atoms[j].x;\n      double dy = yi - atoms[j].y;\n      double dz = zi - atoms[j].z;\n  \n      double rij2 = dx*dx + dy*dy + dz*dz;\n      double rij3 = sqrt(rij2)*rij2;\n\n      arma::vec tmp(3);\n      \n      tmp(0) = chg_i*chg_j/rij3*dx;\n      tmp(1) = chg_i*chg_j/rij3*dy;\n      tmp(2) = chg_i*chg_j/rij3*dz;\n\n      grd(3*i  ) -= tmp(0);\n      grd(3*i+1) -= tmp(1);\n      grd(3*i+2) -= tmp(2);\n      grd(3*j  ) += tmp(0);\n      grd(3*j+1) += tmp(1);\n      grd(3*j+2) += tmp(2);\n    }\n\n\n    for (auto j = 0; j < atoms_Q.size(); ++j) {\n      double chg_j = atoms_Q[j].charge;\n      // calculate distance\n      \n      double dx = xi - atoms_Q[j].x;\n      double dy = yi - atoms_Q[j].y;\n      double dz = zi - atoms_Q[j].z;\n  \n      double rij2 = dx*dx + dy*dy + dz*dz;\n      double rij3 = sqrt(rij2)*rij2;\n\n      arma::vec tmp(3);\n      \n      tmp(0) = chg_i*chg_j/rij3*dx;\n      tmp(1) = chg_i*chg_j/rij3*dy;\n      tmp(2) = chg_i*chg_j/rij3*dz;\n\n      grd(3*i  ) -= tmp(0);\n      grd(3*i+1) -= tmp(1);\n      grd(3*i+2) -= tmp(2);\n\n      grd_Q(3*j  ) += tmp(0);\n      grd_Q(3*j+1) += tmp(1);\n      grd_Q(3*j+2) += tmp(2);\n    }\n    \n  }\n\n  return grd;\n\n}\n\n\n\n// --\n\n\nvoid compute_2body_deriv_ints (const int thread_id,\n\t\t\t       const BasisSet& bs,\n\t\t\t       const vector<Atom>& atoms,\n\t\t\t       const arma::mat& Dm,\n\t\t\t       const arma::mat& Schwartz,\n\t\t\t       arma::vec& grd)\n{\n\n  const auto nbf     = bs.nbf();\n  const auto nshells = bs.size();\n  const auto natom   = atoms.size();\n  const auto shell2atom = bs.shell2atom(atoms);\n\n  grd =  arma::vec(3*natom, arma::fill::zeros);\n\n  libint2::Engine engine  (libint2::Operator::coulomb,\n\t\t\t   bs.max_nprim(),\n\t\t\t   bs.max_l(),\n\t\t\t   1);\n  \n  const auto precision = numeric_limits<double>::epsilon();\n  engine.set_precision (precision);\n  const auto& buf = engine.results();\n  \n  auto shell2bf = bs.shell2bf();\n\n  // loop over permutationally-unique set of shells\n  for (auto s1 = 0, s1234 = 0; s1 != nshells; ++s1) {\n    auto bf1_first = shell2bf[s1];\n    auto nbf1      = bs[s1].size();\n    auto iat       = shell2atom[s1];\n    \n    for (auto s2 = 0; s2 <= s1; ++s2) {\n      auto bf2_first = shell2bf[s2];\n      auto nbf2      = bs[s2].size();\n      auto jat       = shell2atom[s2];\n      auto s12_cut   = Schwartz(s1,s2);\n\n      for (auto s3 = 0; s3 <= s1; ++s3) {\n\tauto bf3_first = shell2bf[s3];\n\tauto nbf3      = bs[s3].size();\n\tauto kat       = shell2atom[s3];\n\n\tconst auto s4_max = (s1 == s3) ? s2 : s3;\n\tfor (auto s4 = 0; s4 <= s4_max; ++s4, ++s1234) {\n\n\t  if (s1234 % num_threads != thread_id) continue;\n\t  \n\t  auto bf4_first = shell2bf[s4];\n\t  auto nbf4      = bs[s4].size();\n\t  auto lat       = shell2atom[s4];\n\t  auto s34_cut   = Schwartz(s3,s4);\n\t  \n\t  if (s12_cut*s34_cut < precision) {\n\t    continue;\n\t  }\n\n\t  auto s12_deg = (s1 == s2) ? 1.0 : 2.0;\n\t  auto s34_deg = (s3 == s4) ? 1.0 : 2.0;\n\t  auto s13_s24_deg = (s1 == s3) ? ((s2 == s4) ? 1.0 : 2.0) : 2.0;\n\t  auto s1234_deg = s12_deg*s34_deg*s13_s24_deg;\n\t  \n\t  engine.compute2<Operator::coulomb,BraKet::xx_xx,1>\n\t    (bs[s1], bs[s2], bs[s3], bs[s4]);\n\n\t  arma::vec tmp(12, arma::fill::zeros);\n\t  \n\t  \n\t  for (auto di = 0; di != 12; di++) {\n\t    const auto shset = buf[di];\n\n\t    if (shset == nullptr) continue;\n\n\t    double sum = 0.0;\n\t    for (auto f1 = 0, f1234 = 0; f1 != nbf1; ++f1) {\n\t      const auto bf1 = f1 + bf1_first;\n\t      \n\t      for (auto f2 = 0; f2 != nbf2; ++f2) {\n\t\tconst auto bf2 = f2 + bf2_first;\n\t\t\n\t\tfor (auto f3 = 0; f3 != nbf3; ++f3) {\n\t\t  const auto bf3 = f3 + bf3_first;\n\t\t  \n\t\t  for (auto f4 = 0; f4 != nbf4; ++f4, ++f1234) {\n\t\t    const auto bf4 = f4 + bf4_first;\n\t\t    \n\t\t    const auto eri4  = shset[f1234];\n\t\t    const auto value = eri4*s1234_deg;\n\t\t    \n\t\t    sum += 2.0*Dm(bf1,bf2)*Dm(bf3,bf4)*value;\n\t\t    sum -= 0.5*Dm(bf1,bf3)*Dm(bf2,bf4)*value;\n\t\t    sum -= 0.5*Dm(bf1,bf4)*Dm(bf2,bf3)*value;\n\t\t  }\n\t\t}\n\t      }\n\t    }\n\t    \n\t    tmp(di) = 0.25*sum;\n\t  }// end di\n\t  \n\t  // store the gradient\n\n\t  grd(3*iat  ) += tmp(0);\n\t  grd(3*iat+1) += tmp(1);\n\t  grd(3*iat+2) += tmp(2);\n\t  grd(3*jat  ) += tmp(3);\n\t  grd(3*jat+1) += tmp(4);\n\t  grd(3*jat+2) += tmp(5);\n\t  grd(3*kat  ) += tmp(6);\n\t  grd(3*kat+1) += tmp(7);\n\t  grd(3*kat+2) += tmp(8);\n\t  grd(3*lat  ) += tmp(9);\n\t  grd(3*lat+1) += tmp(10);\n\t  grd(3*lat+2) += tmp(11);\n\n\t}\n      }\n    }\n  }\n\n}\n\n\n} }  // namespace willow::qcmol\n", "meta": {"hexsha": "f05937254afa7f812b9fc96de956e44c373779f9", "size": 14929, "ext": "cc", "lang": "C++", "max_stars_repo_path": "RHFGrad.cc", "max_stars_repo_name": "swillow/w-qcmol", "max_stars_repo_head_hexsha": "b278417ca8b9eaf08c4a0712e295bdf5ac18595a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-02-19T22:13:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-19T22:13:42.000Z", "max_issues_repo_path": "RHFGrad.cc", "max_issues_repo_name": "swillow/w-qcmol", "max_issues_repo_head_hexsha": "b278417ca8b9eaf08c4a0712e295bdf5ac18595a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RHFGrad.cc", "max_forks_repo_name": "swillow/w-qcmol", "max_forks_repo_head_hexsha": "b278417ca8b9eaf08c4a0712e295bdf5ac18595a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3143322476, "max_line_length": 100, "alphanum_fraction": 0.5514100074, "num_tokens": 5210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737214979745, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.24529252193486906}}
{"text": "#include <math.h>\n#include <limits.h>\n\n#include <cstdint>\n#include <map>\n\n// C++11\n#include <memory>\n\n#include <boost/make_shared.hpp>\n#include <pcl/io/pcd_io.h>\n#include <pcl/visualization/cloud_viewer.h>\n#include <opencv2/opencv.hpp>\n#include <Eigen/Eigen>\n\n#include <ros/ros.h>\n#include <sensor_msgs/Image.h>\n#include <sensor_msgs/PointCloud2.h>\n\n#include \"myutility.h\"\n#include \"MyCalibration.h\"\n\n#define INVALID_PIXEL_VALUE 0\n\nextern bool g_DebugFlg;\n\nEigen::Vector2i g_points[4];\nint g_picking_counter = -1;\nEigen::Vector2i g_picked_points[CORRESPOND_POINTS];\n\n<<<<<<< HEAD\nvoid mouseCallback(int event, int x, int y, int flag, void*)\n=======\nvoid mouseCallback(int event, int x,int y, int flag, void*)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n{\n  static int point = 0;\n  std::string desc;\n  switch (event)\n  {\n<<<<<<< HEAD\n    case cv::EVENT_LBUTTONUP:\n      if (flag & cv::EVENT_FLAG_LBUTTON)\n      {\n        g_points[point][0] = x;\n        g_points[point][1] = y;\n        point++;\n        if (point == 4)\n        {\n          point = 0;\n        }\n      }\n      break;\n    case cv::EVENT_RBUTTONUP:\n      if (g_picking_counter >= 0 && (flag & cv::EVENT_FLAG_RBUTTON))\n      {\n        g_picked_points[g_picking_counter][0] = x;\n        g_picked_points[g_picking_counter][1] = y;\n        std::cout << \"Picked [\" << g_picking_counter << \"]: \"\n                  << \"(\" << x << \", \" << y << \")\" << std::endl;\n        g_picking_counter++;\n        if (g_picking_counter >= CORRESPOND_POINTS)\n        {\n          g_picking_counter = -1;\n        }\n      }\n      break;\n=======\n  case cv::EVENT_LBUTTONUP:\n    if (flag & cv::EVENT_FLAG_LBUTTON)\n    {\n      g_points[point][0] = x;\n      g_points[point][1] = y;\n      point++;\n      if(point == 4)\n      {\n        point = 0;\n      }\n    }\n    break;\n  case cv::EVENT_RBUTTONUP:\n    if (g_picking_counter >=0 && (flag & cv::EVENT_FLAG_RBUTTON))\n    {\n      g_picked_points[g_picking_counter][0] = x;\n      g_picked_points[g_picking_counter][1] = y;\n      std::cout << \"Picked [\" << g_picking_counter << \"]: \"\n        << \"(\" << x << \", \" << y  << \")\" << std::endl;\n      g_picking_counter++;\n      if (g_picking_counter >= CORRESPOND_POINTS)\n      {\n        g_picking_counter = -1;\n      }\n    }\n    break;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  }\n  return;\n}\n\n<<<<<<< HEAD\nint MyCalibration::initialize(pcl::visualization::CloudViewer& viewer, uint8_t* depth_frame_region,\n                              uint8_t* color_frame_region)\n{\n  // correct_mirroring << -1,0,0,0,1,0,0,0,1;\n  {  // Setting streams\n=======\nint MyCalibration::initialize(\n    pcl::visualization::CloudViewer& viewer,\n    uint8_t *depth_frame_region,\n    uint8_t *color_frame_region)\n{\n  //correct_mirroring << -1,0,0,0,1,0,0,0,1;\n  { // Setting streams\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    if (depth_frame_region != NULL)\n    {\n      depth_frame = depth_frame_region;\n    }\n    else\n    {\n      std::cout << \"Failed to set pointer of depth frame.\" << std::endl;\n      return -1;\n    }\n    if (color_frame_region != NULL)\n    {\n      color_frame = color_frame_region;\n    }\n    else\n    {\n      std::cout << \"Failed to set pointer of color frame.\" << std::endl;\n      return -1;\n    }\n  }\n  cloud->width = CAMERA_RESOLUTION_X;\n<<<<<<< HEAD\n  cloud->height = CAMERA_RESOLUTION_Y;\n=======\n  cloud->height= CAMERA_RESOLUTION_Y;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  cloud->is_dense = false;\n  cloud->points.resize(cloud->height * cloud->width);\n  this->viewer = &viewer;\n\n  int i;\n  g_picking_counter = 0;\n<<<<<<< HEAD\n  for (i = 0; i < CORRESPOND_POINTS; i++)\n=======\n  for (i=0; i<CORRESPOND_POINTS; i++)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  {\n    g_picked_points[i] = Eigen::Vector2i::Zero();\n  }\n  return 0;\n}\n\nint MyCalibration::extractPlanePoints()\n{\n  int i, j;\n<<<<<<< HEAD\n  std::vector< Eigen::Vector3f > all_points;\n=======\n  std::vector<Eigen::Vector3f> all_points;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n\n  // Sort points\n  int min_cross;\n  int tmp_cross;\n  int min_cross_num;\n  Eigen::Vector2i tmp_vec[3];\n<<<<<<< HEAD\n  for (i = 0; i < 4; i++)\n  {\n    min_cross_num = i;\n    min_cross = INT_MAX;\n    for (j = i; j < 4; j++)\n=======\n  for (i = 0; i<4; i++)\n  {\n    min_cross_num = i;\n      min_cross = INT_MAX;\n    for (j = i; j<4; j++)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    {\n      if (i == 0)\n      {\n        tmp_vec[0] = g_points[j];\n        tmp_vec[1] = g_points[i];\n      }\n      else\n      {\n<<<<<<< HEAD\n        tmp_vec[0] = g_points[j] - g_points[i - 1];\n        tmp_vec[1] = g_points[i] - g_points[i - 1];\n=======\n        tmp_vec[0] = g_points[j] - g_points[i-1];\n        tmp_vec[1] = g_points[i] - g_points[i-1];\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n      }\n\n      tmp_cross = tmp_vec[0][0] * tmp_vec[1][1] - tmp_vec[0][1] * tmp_vec[1][0];\n      if (tmp_cross < min_cross)\n      {\n        min_cross = tmp_cross;\n        min_cross_num = j;\n      }\n    }\n    tmp_vec[3] = g_points[i];\n    g_points[i] = g_points[min_cross_num];\n    g_points[min_cross_num] = tmp_vec[3];\n  }\n\n  // Detect closed region\n  tmp_vec[0] = Eigen::Vector2i::Zero(2);\n  for (i = 0; i < 4; i++)\n  {\n    tmp_vec[0] += g_points[i] / 4;\n  }\n\n<<<<<<< HEAD\n  // Setting points\n  int check;\n  bool check_flg;\n  std::vector< char > points_attribute;\n=======\n\n  // Setting points\n  int check;\n  bool check_flg;\n  std::vector<char> points_attribute;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  Eigen::Vector3f tmp_vec3[1];\n\n  points_on_plane.clear();\n  all_points.clear();\n<<<<<<< HEAD\n  all_points.resize(CAMERA_RESOLUTION_X * CAMERA_RESOLUTION_Y, Eigen::Vector3f(0, 0, 0));\n=======\n  all_points.resize(CAMERA_RESOLUTION_X * CAMERA_RESOLUTION_Y, Eigen::Vector3f(0,0,0));\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  other_points.clear();\n  points_attribute.clear();\n  points_attribute.resize(CAMERA_RESOLUTION_X * CAMERA_RESOLUTION_Y, (char)0x00);\n\n  // Get static point cloud\n<<<<<<< HEAD\n  for (i = 0; i < CAMERA_RESOLUTION_Y; i++)\n  {\n    for (j = 0; j < CAMERA_RESOLUTION_X; j++)\n    {\n      float* p;\n      p = (float*)&points->data[(i * CAMERA_RESOLUTION_X + j) * sizeof(float) * 4];\n      all_points[i * CAMERA_RESOLUTION_X + j][0] = *p * 1000;\n      p++;\n      all_points[i * CAMERA_RESOLUTION_X + j][1] = *p * 1000;\n      p++;\n      all_points[i * CAMERA_RESOLUTION_X + j][2] = *p * 1000;\n    }\n  }\n\n  std::vector< Eigen::Vector2i > loop_stack;\n  loop_stack.clear();\n  loop_stack.push_back(Eigen::Vector2i(tmp_vec[0][0], tmp_vec[0][1]));\n  while (!loop_stack.empty())\n  {  // Detecting points on plane : 0x01\n    tmp_vec[0] = loop_stack.back();\n    loop_stack.pop_back();\n    if (points_attribute[tmp_vec[0][0] + tmp_vec[0][1] * CAMERA_RESOLUTION_X] & 0x01)\n    {\n      continue;\n    }\n    for (i = 0; i < 4; i++)\n=======\n  for (i=0; i<CAMERA_RESOLUTION_Y; i++)\n  {\n    for (j=0; j<CAMERA_RESOLUTION_X; j++)\n    {\n      float *p;\n      p = (float*)&points->data[(i*CAMERA_RESOLUTION_X+j)*sizeof(float)*4];\n      all_points[i*CAMERA_RESOLUTION_X+j][0] = *p*1000; p++;\n      all_points[i*CAMERA_RESOLUTION_X+j][1] = *p*1000; p++;\n      all_points[i*CAMERA_RESOLUTION_X+j][2] = *p*1000;\n    }\n  }\n\n  std::vector<Eigen::Vector2i> loop_stack;\n  loop_stack.clear();\n  loop_stack.push_back(Eigen::Vector2i(tmp_vec[0][0], tmp_vec[0][1]));\n  while (!loop_stack.empty())\n  { // Detecting points on plane : 0x01\n    tmp_vec[0] = loop_stack.back();\n    loop_stack.pop_back();\n    if (points_attribute[tmp_vec[0][0]+tmp_vec[0][1]*CAMERA_RESOLUTION_X]&0x01)\n    {\n      continue;\n    }\n    for (i = 0; i<4; i++)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    {\n      check = 0;\n      check_flg = true;\n      tmp_vec[1] = tmp_vec[0] - g_points[i];\n      if (i == 3)\n      {\n        tmp_vec[2] = g_points[0] - g_points[i];\n      }\n      else\n      {\n<<<<<<< HEAD\n        tmp_vec[2] = g_points[i + 1] - g_points[i];\n      }\n      check = (tmp_vec[2][0] * tmp_vec[1][1] - tmp_vec[2][1] * tmp_vec[1][0]);\n=======\n        tmp_vec[2] = g_points[i+1] - g_points[i];\n      }\n      check = (tmp_vec[2][0]*tmp_vec[1][1] - tmp_vec[2][1] * tmp_vec[1][0]);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n      if (check > 0)\n      {\n        check_flg = false;\n        break;\n      }\n    }\n    if (check_flg)\n    {\n      // This point is on the plane. (because user chooses a region of a plane)\n<<<<<<< HEAD\n      points_attribute[tmp_vec[0][0] + tmp_vec[0][1] * CAMERA_RESOLUTION_X] |= 0x01;\n      if (!(points_attribute[tmp_vec[0][0] + 1 + tmp_vec[0][1] * CAMERA_RESOLUTION_X] & 0x01))\n      {\n        loop_stack.push_back(Eigen::Vector2i(tmp_vec[0][0] + 1, tmp_vec[0][1]));\n      }\n      if (!(points_attribute[tmp_vec[0][0] - 1 + tmp_vec[0][1] * CAMERA_RESOLUTION_X] & 0x01))\n      {\n        loop_stack.push_back(Eigen::Vector2i(tmp_vec[0][0] - 1, tmp_vec[0][1]));\n      }\n      if (!(points_attribute[tmp_vec[0][0] + (tmp_vec[0][1] + 1) * CAMERA_RESOLUTION_X] & 0x01))\n      {\n        loop_stack.push_back(Eigen::Vector2i(tmp_vec[0][0], tmp_vec[0][1] + 1));\n      }\n      if (!(points_attribute[tmp_vec[0][0] + (tmp_vec[0][1] - 1) * CAMERA_RESOLUTION_X] & 0x01))\n      {\n        loop_stack.push_back(Eigen::Vector2i(tmp_vec[0][0], tmp_vec[0][1] - 1));\n=======\n      points_attribute[tmp_vec[0][0]+tmp_vec[0][1]*CAMERA_RESOLUTION_X] |= 0x01;\n      if (!(points_attribute[tmp_vec[0][0]+1+tmp_vec[0][1]*CAMERA_RESOLUTION_X]&0x01) )\n      {\n        loop_stack.push_back(Eigen::Vector2i(tmp_vec[0][0]+1, tmp_vec[0][1]));\n      }\n      if (!(points_attribute[tmp_vec[0][0]-1+tmp_vec[0][1]*CAMERA_RESOLUTION_X]&0x01) )\n      {\n        loop_stack.push_back(Eigen::Vector2i(tmp_vec[0][0]-1, tmp_vec[0][1]));\n      }\n      if (!(points_attribute[tmp_vec[0][0]+(tmp_vec[0][1]+1)*CAMERA_RESOLUTION_X]&0x01) )\n      {\n        loop_stack.push_back(Eigen::Vector2i(tmp_vec[0][0], tmp_vec[0][1]+1));\n      }\n      if (!(points_attribute[tmp_vec[0][0]+(tmp_vec[0][1]-1)*CAMERA_RESOLUTION_X]&0x01) )\n      {\n        loop_stack.push_back(Eigen::Vector2i(tmp_vec[0][0], tmp_vec[0][1]-1));\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n      }\n    }\n  }\n\n  const int radius = 3;\n  int k;\n  int now;\n<<<<<<< HEAD\n  for (k = 0; k < CORRESPOND_POINTS; k++)\n  {  // Detecting points around picked points : 0x02\n    unsigned int _cnt = 0;\n    picked_points[k] = Eigen::Vector3f::Zero();\n    for (i = g_picked_points[k][1] - radius; i <= g_picked_points[k][1] + radius; i++)\n    {\n      for (j = -sqrt(pow(radius, 2.0) - pow((i - g_picked_points[k][1]), 2.0)) + g_picked_points[k][0];\n           j <= sqrt(pow(radius, 2.0) - pow((i - g_picked_points[k][1]), 2.0)) + g_picked_points[k][0]; j++)\n      {\n        if (i >= 0 && i < CAMERA_RESOLUTION_Y && j >= 0 && j < CAMERA_RESOLUTION_X)\n        {  // picked_points_around\n          now = i * CAMERA_RESOLUTION_X + j;\n=======\n  for (k=0; k<CORRESPOND_POINTS; k++)\n  { // Detecting points around picked points : 0x02\n    unsigned int _cnt = 0;\n    picked_points[k] = Eigen::Vector3f::Zero();\n    for (i=g_picked_points[k][1]-radius; i<=g_picked_points[k][1]+radius; i++)\n    {\n      for (j=-sqrt(pow(radius,2.0)-pow((i-g_picked_points[k][1]),2.0))+g_picked_points[k][0];\n           j<=sqrt(pow(radius,2.0)-pow((i-g_picked_points[k][1]),2.0))+g_picked_points[k][0]; j++)\n      {\n        if(i>=0 && i<CAMERA_RESOLUTION_Y && j>=0 && j<CAMERA_RESOLUTION_X)\n        { // picked_points_around\n          now = i*CAMERA_RESOLUTION_X+j;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n          points_attribute[now] |= 0x02;\n          picked_points[k] += all_points[now];\n          _cnt++;\n        }\n      }\n    }\n<<<<<<< HEAD\n    picked_points[k] = picked_points[k] / (double)_cnt;\n  }\n\n  for (i = 0; i < CAMERA_RESOLUTION_Y; i++)\n  {  // Add to vector as attribute\n    for (j = 0; j < CAMERA_RESOLUTION_X; j++)\n    {\n      now = (i * CAMERA_RESOLUTION_X + j);\n=======\n    picked_points[k] = picked_points[k]/(double)_cnt;\n  }\n\n  for (i=0; i<CAMERA_RESOLUTION_Y; i++)\n  { // Add to vector as attribute\n    for (j=0; j<CAMERA_RESOLUTION_X; j++)\n    {\n      now = (i*CAMERA_RESOLUTION_X+j);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n      if (points_attribute[now] == 0x00)\n      {\n        other_points.push_back(&all_points[now]);\n      }\n      if (points_attribute[now] & 0x01)\n      {\n        points_on_plane.push_back(&all_points[now]);\n<<<<<<< HEAD\n        if ((i + j) % 2 == 0)\n        {\n          image.at< uchar >(i, j) = 255;\n=======\n        if ((i+j)%2==0)\n        {\n          image.at<uchar>(i,j) = 255;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n        }\n      }\n      if (points_attribute[now] & 0x02)\n      {\n        picked_points_around.push_back(&all_points[now]);\n      }\n    }\n  }\n\n  std::cout << \"Extracted number of points: \" << points_on_plane.size() << std::endl;\n\n  cv::imshow(\"Depth image\", image);\n\n  return 0;\n}\n\nint MyCalibration::viewPoints()\n{\n  int i;\n<<<<<<< HEAD\n  std::vector< Eigen::Vector3f* >::iterator it;\n  Eigen::Vector3f* ptmp;\n=======\n  std::vector<Eigen::Vector3f*>::iterator it;\n  Eigen::Vector3f *ptmp;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  Eigen::Vector3f tmp;\n\n  cloud->clear();\n  pcl::PointXYZRGB point;\n\n<<<<<<< HEAD\n  for (it = other_points.begin(); it != other_points.end(); it++)\n=======\n  for (it = other_points.begin();\n      it != other_points.end(); it++)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  {\n    ptmp = *it;\n    tmp = *ptmp;\n    point.x = tmp[0] / 1000.0;\n    point.y = tmp[1] / 1000.0;\n    point.z = tmp[2] / 1000.0;\n    point.r = 255;\n    point.g = tmp[2] / 5;\n    point.b = 255;\n    if (point.z < 10.0)\n    {\n      cloud->push_back(point);\n    }\n  }\n<<<<<<< HEAD\n  for (it = points_on_plane.begin(); it != points_on_plane.end(); it++)\n=======\n  for (it = points_on_plane.begin();\n      it != points_on_plane.end(); it++)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  {\n    ptmp = *it;\n    tmp = *ptmp;\n    point.x = tmp[0] / 1000.0;\n    point.y = tmp[1] / 1000.0;\n    point.z = tmp[2] / 1000.0;\n    point.r = 255;\n    point.g = 255;\n    point.b = tmp[2] / 5;\n    cloud->push_back(point);\n  }\n#ifdef _DEBUG\n<<<<<<< HEAD\n  for (it = picked_points_around.begin(); it != picked_points_around.end(); it++)\n  {  // Draw around of picked points\n=======\n  for (it = picked_points_around.begin();\n      it != picked_points_around.end(); it++)\n  { // Draw around of picked points\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    ptmp = *it;\n    tmp = *ptmp;\n    point.x = tmp[0] / 1000.0;\n    point.y = tmp[1] / 1000.0;\n    point.z = tmp[2] / 1000.0;\n    point.r = tmp[2] / 5;\n    point.g = 255;\n    point.b = 255;\n    cloud->push_back(point);\n  }\n<<<<<<< HEAD\n#endif  // _DEBUG\n  for (i = 0; i < CORRESPOND_POINTS; i++)\n  {  // Draw picked points\n=======\n#endif // _DEBUG\n  for (i=0; i<CORRESPOND_POINTS; i++)\n  { // Draw picked points\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    point.x = picked_points[i][0] / 1000.0;\n    point.y = picked_points[i][1] / 1000.0;\n    point.z = picked_points[i][2] / 1000.0;\n    point.r = picked_points[i][2] / 5;\n    point.g = picked_points[i][2] / 5;\n    point.b = 255;\n    cloud->push_back(point);\n  }\n  viewer->showCloud(cloud);\n  return 0;\n}\n\ninline double _E(double phi_x, double phi_y, double phi_z, double t_x, double t_y, double t_z,\n<<<<<<< HEAD\n                 const Eigen::Vector3f* X_w, const Eigen::Vector3f* X_c)\n=======\n    const Eigen::Vector3f* X_w,\n    const Eigen::Vector3f* X_c)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n{\n  int i;\n  double ret;\n  Eigen::Matrix3d rot;\n<<<<<<< HEAD\n  rot = Eigen::AngleAxisd(phi_z, Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(phi_y, Eigen::Vector3d::UnitY()) *\n        Eigen::AngleAxisd(phi_x, Eigen::Vector3d::UnitX());\n  ret = 0.0;\n  for (i = 0; i < CORRESPOND_POINTS; i++)\n  {\n    Eigen::Vector3d tmp;\n    tmp = X_w[i].cast< double >() - (rot * (X_c[i].cast< double >()) + Eigen::Vector3d(t_x, t_y, t_z));\n    ret += pow(tmp.norm(), 2.0);\n=======\n  rot = Eigen::AngleAxisd(phi_z, Eigen::Vector3d::UnitZ())\n    * Eigen::AngleAxisd(phi_y, Eigen::Vector3d::UnitY())\n    * Eigen::AngleAxisd(phi_x, Eigen::Vector3d::UnitX());\n  ret = 0.0;\n  for (i=0; i < CORRESPOND_POINTS; i++)\n  {\n    Eigen::Vector3d tmp;\n    tmp = X_w[i].cast<double>()-(rot*(X_c[i].cast<double>())+Eigen::Vector3d(t_x,t_y,t_z));\n    ret += pow(tmp.norm(),2.0);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  }\n  return ret;\n}\n\n<<<<<<< HEAD\ninline int find_corner(const cv::Mat& image, const cv::Size pattern_size, std::vector< cv::Point2f >& corners,\n                       bool& pattern_found)\n{\n  cv::Mat gray(image.rows, image.cols, CV_8UC1);\n  switch (image.type())\n  {\n    case CV_8UC1:\n      gray = image;\n      break;\n    case CV_8UC3:\n      cv::cvtColor(image, gray, CV_BGR2GRAY);\n      break;\n    default:\n      std::cerr << \"Unexpected image type.\" << std::endl;\n      return -1;\n  }\n  pattern_found =\n      cv::findChessboardCorners(gray, pattern_size, corners,\n                                cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE | cv::CALIB_CB_FAST_CHECK);\n  if (pattern_found)\n  {\n    cv::cornerSubPix(gray, corners, cv::Size(15, 15), cv::Size(-1, -1),\n                     cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 15, 0.01));\n=======\ninline int find_corner(const cv::Mat& image, const cv::Size pattern_size,\n    std::vector<cv::Point2f>& corners, bool& pattern_found)\n{\n  cv::Mat gray(image.rows, image.cols, CV_8UC1);\n  switch(image.type())\n  {\n  case CV_8UC1:\n    gray = image;\n    break;\n  case CV_8UC3:\n    cv::cvtColor(image, gray, CV_BGR2GRAY);\n    break;\n  default:\n    std::cerr << \"Unexpected image type.\" << std::endl;\n    return -1;\n  }\n  pattern_found = cv::findChessboardCorners(gray, pattern_size, corners,\n      cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_NORMALIZE_IMAGE | cv::CALIB_CB_FAST_CHECK);\n  if (pattern_found)\n  {\n    cv::cornerSubPix(gray, corners, cv::Size(15,15), cv::Size(-1,-1),\n        cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 15, 0.01));\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  }\n  return 0;\n}\n\npcl::PointXYZRGB _s, _ex, _ey, _ez;\nvoid viewerDrawAxis(pcl::visualization::PCLVisualizer& viewer)\n{\n  viewer.removeShape(\"axis-x\");\n  viewer.removeShape(\"axis-y\");\n  viewer.removeShape(\"axis-z\");\n<<<<<<< HEAD\n  viewer.addLine< pcl::PointXYZRGB >(_s, _ex, 255, 0, 0, \"axis-x\");\n  viewer.addLine< pcl::PointXYZRGB >(_s, _ey, 0, 255, 0, \"axis-y\");\n  viewer.addLine< pcl::PointXYZRGB >(_s, _ez, 0, 0, 255, \"axis-z\");\n=======\n  viewer.addLine<pcl::PointXYZRGB>(_s,_ex, 255, 0, 0, \"axis-x\");\n  viewer.addLine<pcl::PointXYZRGB>(_s,_ey, 0, 255, 0, \"axis-y\");\n  viewer.addLine<pcl::PointXYZRGB>(_s,_ez, 0, 0, 255, \"axis-z\");\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  return;\n}\n\nextern double d_roll, d_pitch, d_yaw;\nextern double d_tx, d_ty, d_tz;\n<<<<<<< HEAD\nint MyCalibration::calcurateExtrinsicParameters(double convertion_th, int convertion_method, const float pattern_width)\n=======\nint MyCalibration::calcurateExtrinsicParameters(double convertion_th,\n    int convertion_method,\n    const float pattern_width)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n{\n  int i, j, k;\n  double t_x, t_y, t_z;\n  double phi_x, phi_y, phi_z;\n  Eigen::Vector3d avg_vec;\n  Eigen::Matrix3d cov_mat;\n\n  Eigen::Vector3d tmp;\n\n  avg_vec = Eigen::Vector3d::Zero();\n  cov_mat = Eigen::Matrix3d::Zero();\n\n  Eigen::Vector3d ax[3];\n  Eigen::Vector3d ax_cam[3];\n  ax_cam[0] = Eigen::Vector3d::UnitX();\n  ax_cam[1] = Eigen::Vector3d::UnitY();\n  ax_cam[2] = Eigen::Vector3d::UnitZ();\n\n<<<<<<< HEAD\n  {  // calcuration of average\n    for (i = 0; i < 3; i++)\n    {\n      for (k = 0; k < points_on_plane.size(); k++)\n      {\n        tmp = points_on_plane[k]->cast< double >();\n=======\n  { // calcuration of average\n    for (i=0; i < 3; i++)\n    {\n      for (k=0; k < points_on_plane.size(); k++)\n      {\n        tmp = points_on_plane[k]->cast<double>();\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n        avg_vec[i] += tmp[i] / points_on_plane.size();\n      }\n    }\n\n    // calcuration of covariance\n<<<<<<< HEAD\n    for (i = 0; i < 3; i++)\n    {\n      for (j = 0; j < 3; j++)\n      {\n        for (k = 0; k < points_on_plane.size(); k++)\n        {\n          tmp = points_on_plane[k]->cast< double >();\n          cov_mat(i, j) += ((tmp[i] - avg_vec[i]) * (tmp[j] - avg_vec[j])) / points_on_plane.size();\n=======\n    for (i=0; i < 3; i++)\n    {\n      for (j=0; j < 3; j++)\n      {\n        for (k=0; k < points_on_plane.size(); k++)\n        {\n          tmp = points_on_plane[k]->cast<double>();\n          cov_mat(i,j) += ((tmp[i] - avg_vec[i])\n              * (tmp[j] - avg_vec[j])) / points_on_plane.size();\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n        }\n      }\n    }\n  }\n\n<<<<<<< HEAD\n  {  // Calcurate Z-axis\n    Eigen::EigenSolver< Eigen::Matrix3d > solver(cov_mat);\n    double eigen_min = std::numeric_limits< double >::infinity();\n    for (i = 0; i < 3; i++)\n=======\n  { // Calcurate Z-axis\n    Eigen::EigenSolver<Eigen::Matrix3d> solver(cov_mat);\n    double eigen_min = std::numeric_limits<double>::infinity();\n    for (i=0; i<3; i++)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    {\n      if (solver.eigenvalues()(i).real() < eigen_min)\n      {\n        j = i;\n        eigen_min = solver.eigenvalues()(i).real();\n      }\n    }\n<<<<<<< HEAD\n    Eigen::Matrix3cd axis_world;\n    axis_world = solver.eigenvectors();\n\n    ax[2][0] = axis_world(0, j).real();\n    ax[2][1] = axis_world(1, j).real();\n    ax[2][2] = axis_world(2, j).real();\n=======\n    Eigen::Matrix3cd  axis_world;\n    axis_world = solver.eigenvectors();\n\n    ax[2][0] = axis_world(0,j).real();\n    ax[2][1] = axis_world(1,j).real();\n    ax[2][2] = axis_world(2,j).real();\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    if (ax[2].dot(ax_cam[2]) > 0)\n    {\n      ax[2] = -ax[2];\n    }\n<<<<<<< HEAD\n    ax[2] = ax[2] / ax[2].norm();\n  }\n\n  // Estimate other 4 parameters\n  {  // Set world points\n    for (int x = 0; x < 5; x++)\n    {\n      for (int y = 0; y < 6; y++)\n      {\n        world_points[x * 6 + y] = Eigen::Vector3f(x * pattern_width, y * pattern_width, 0.0);\n=======\n    ax[2] = ax[2]/ax[2].norm();\n  }\n\n  // Estimate other 4 parameters\n  { // Set world points\n    for (int x=0; x < 5; x++)\n    {\n      for (int y=0; y < 6; y++)\n      {\n        world_points[x*6+y] = Eigen::Vector3f(x*pattern_width,y*pattern_width,0.0);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n      }\n    }\n  }\n\n<<<<<<< HEAD\n  // For Debug ===\n  if (g_DebugFlg)\n  {\n    Eigen::Matrix3d _debug_mat = Eigen::Matrix3d::Zero();\n    _debug_mat = Eigen::AngleAxisd(d_yaw / 180 * M_PI, Eigen::Vector3d::UnitZ()) *\n                 Eigen::AngleAxisd(d_pitch / 180 * M_PI, Eigen::Vector3d::UnitY()) *\n                 Eigen::AngleAxisd(d_roll / 180 * M_PI, Eigen::Vector3d::UnitX());\n\n    Eigen::Vector3d _debug_vec = Eigen::Vector3d(d_tx, d_ty, d_tz);\n\n    for (i = 0; i < CORRESPOND_POINTS; i++)\n    {\n      picked_points[i] = _debug_mat.cast< float >().inverse() * (world_points[i] - _debug_vec.cast< float >());\n      std::cout << \"i: \" << i << \"\\t\" << picked_points[i][0] << \", \" << picked_points[i][1] << \", \"\n                << picked_points[i][2] << std::endl;\n    }\n    ax[2] = _debug_mat.inverse() * Eigen::Vector3d::UnitZ();\n  }\n  // === For Debug\n\n  double n;\n  phi_x = atan2(ax[2](1), ax[2](2));\n  phi_y = atan2(-ax[2](0), sqrt(pow(ax[2][1], 2.0) + pow(ax[2][2], 2.0)));\n  Eigen::Matrix3d rot_rp;\n  rot_rp = Eigen::AngleAxisd(phi_y, Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(phi_x, Eigen::Vector3d::UnitX());\n  Eigen::Vector3d rotatedRP_point;\n\n  t_z = 0.0;\n  for (i = 0; i < CORRESPOND_POINTS; i++)\n  {\n    rotatedRP_point = rot_rp * picked_points[i].cast< double >();\n=======\n// For Debug ===\n  if (g_DebugFlg)\n  {\n    Eigen::Matrix3d _debug_mat = Eigen::Matrix3d::Zero();\n    _debug_mat = Eigen::AngleAxisd(d_yaw / 180 * M_PI, Eigen::Vector3d::UnitZ())\n      * Eigen::AngleAxisd(d_pitch / 180 * M_PI, Eigen::Vector3d::UnitY())\n      * Eigen::AngleAxisd(d_roll / 180 * M_PI, Eigen::Vector3d::UnitX());\n\n    Eigen::Vector3d _debug_vec = Eigen::Vector3d(d_tx,d_ty,d_tz);\n\n    for (i=0; i < CORRESPOND_POINTS; i++)\n    {\n      picked_points[i] = _debug_mat.cast<float>().inverse()\n        * (world_points[i]-_debug_vec.cast<float>());\n      std::cout << \"i: \" << i << \"\\t\" <<\n        picked_points[i][0] << \", \" <<\n        picked_points[i][1] << \", \" <<\n        picked_points[i][2] << std::endl;\n    }\n    ax[2] = _debug_mat.inverse() * Eigen::Vector3d::UnitZ();\n  }\n// === For Debug\n\n  double n;\n  phi_x = atan2(ax[2](1), ax[2](2));\n  phi_y = atan2(-ax[2](0), sqrt(pow(ax[2][1],2.0)+pow(ax[2][2],2.0)));\n  Eigen::Matrix3d rot_rp;\n  rot_rp = Eigen::AngleAxisd(phi_y, Eigen::Vector3d::UnitY())\n    * Eigen::AngleAxisd(phi_x, Eigen::Vector3d::UnitX());\n  Eigen::Vector3d rotatedRP_point;\n\n  t_z = 0.0;\n  for (i=0; i<CORRESPOND_POINTS; i++)\n  {\n    rotatedRP_point = rot_rp*picked_points[i].cast<double>();\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    // t_z\n    t_z += (world_points[i][2] - rotatedRP_point[2]) / CORRESPOND_POINTS;\n  }\n\n  /* Convertion calcuration */\n  phi_z = 0.0;\n<<<<<<< HEAD\n  t_x = 0.0;\n  t_y = 0.0;\n=======\n  t_x   = 0.0;\n  t_y   = 0.0;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  Eigen::Vector3d grad_E = Eigen::Vector3d::Ones();\n\n  unsigned long long int cnt;\n  // Steepest descent method\n  if (convertion_method == 1)\n  {\n    const double step = 0.00000002;\n    const double grad_th = convertion_th;\n    cnt = 0;\n    while (grad_E.norm() > grad_th)\n    {\n      Eigen::Matrix3d rot;\n<<<<<<< HEAD\n      rot = Eigen::AngleAxisd(phi_z, Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(phi_y, Eigen::Vector3d::UnitY()) *\n            Eigen::AngleAxisd(phi_x, Eigen::Vector3d::UnitX());\n\n      grad_E = Eigen::Vector3d::Zero();\n      for (i = 0; i < CORRESPOND_POINTS; i++)\n      {\n        Eigen::Vector3d rotated_point = rot * (picked_points[i].cast< double >());\n        Eigen::Vector3d world_point = world_points[i].cast< double >();\n        grad_E[0] += 2.0 * ((world_point[0] - t_x) * rotated_point[1] - (world_point[1] - t_y) * rotated_point[0]);\n=======\n      rot = Eigen::AngleAxisd(phi_z, Eigen::Vector3d::UnitZ())\n        * Eigen::AngleAxisd(phi_y, Eigen::Vector3d::UnitY())\n        * Eigen::AngleAxisd(phi_x, Eigen::Vector3d::UnitX());\n\n      grad_E = Eigen::Vector3d::Zero();\n      for (i=0; i<CORRESPOND_POINTS; i++)\n      {\n        Eigen::Vector3d rotated_point = rot * (picked_points[i].cast<double>());\n        Eigen::Vector3d world_point = world_points[i].cast<double>();\n        grad_E[0] += 2.0 * ((world_point[0]-t_x)*rotated_point[1]\n            - (world_point[1]-t_y)*rotated_point[0]);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n        grad_E[1] -= 2.0 * (world_point[0] - (rotated_point[0] + t_x));\n        grad_E[2] -= 2.0 * (world_point[1] - (rotated_point[1] + t_y));\n      }\n      phi_z -= step * grad_E[0];\n<<<<<<< HEAD\n      t_x -= step * grad_E[1];\n      t_y -= step * grad_E[2];\n      if (phi_z > M_PI)\n      {\n        phi_z -= 2.0 * M_PI;\n      }\n      if (phi_z <= -M_PI)\n      {\n        phi_z += 2.0 * M_PI;\n=======\n      t_x   -= step * grad_E[1];\n      t_y   -= step * grad_E[2];\n      if (phi_z > M_PI)\n      {\n        phi_z -= 2.0*M_PI;\n      }\n      if (phi_z <= -M_PI)\n      {\n        phi_z += 2.0*M_PI;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n      }\n      cnt++;\n\n      std::cout << \"k: \" << cnt << \"---\" << std::endl\n<<<<<<< HEAD\n                << \"phi_z: \" << phi_z << \"\\t\"\n                << \"t_x: \" << t_x << \"\\t\"\n                << \"t_y: \" << t_y << std::endl\n                << \"E: \" << _E(phi_x, phi_y, phi_z, t_x, t_y, t_z, world_points, picked_points) << \"\\t\"\n                << \"grad_E: \" << grad_E[0] << \"\\t\" << grad_E[1] << \"\\t\" << grad_E[2] << std::endl\n                << \"|grad_E|: \" << grad_E.norm() << std::endl\n                << std::endl;\n=======\n        << \"phi_z: \" << phi_z << \"\\t\"\n        << \"t_x: \" << t_x << \"\\t\"\n        << \"t_y: \" << t_y << std::endl\n        << \"E: \" << _E(phi_x, phi_y, phi_z, t_x, t_y, t_z, world_points, picked_points) << \"\\t\"\n        << \"grad_E: \" << grad_E[0] << \"\\t\" << grad_E[1] << \"\\t\" << grad_E[2] << std::endl\n        << \"|grad_E|: \" << grad_E.norm() << std::endl\n        << std::endl;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    }\n  }\n  // Perturbation method\n  else if (convertion_method == 2)\n  {\n<<<<<<< HEAD\n    double E = _E(phi_x, phi_y, phi_z, t_x, t_y, t_z, world_points, picked_points);\n=======\n    double E = _E(phi_x,phi_y,phi_z,t_x,t_y,t_z,world_points,picked_points);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    const double _th = convertion_th;\n    const double alpha = 0.001;\n    const double beta = 0.01;\n    const double gamma = 0.01;\n    double E_prev;\n    cnt = 0;\n    do\n    {\n      E_prev = E;\n\n      double min;\n<<<<<<< HEAD\n      min = std::numeric_limits< double >::infinity();\n      for (i = 0; i < 6; i++)\n      {\n        switch (i)\n        {\n          case 0:\n            E = _E(phi_x, phi_y, phi_z + alpha, t_x, t_y, t_z, world_points, picked_points);\n            if (min > E)\n            {\n              min = E;\n              j = i;\n            }\n            break;\n          case 1:\n            E = _E(phi_x, phi_y, phi_z - alpha, t_x, t_y, t_z, world_points, picked_points);\n            if (min > E)\n            {\n              min = E;\n              j = i;\n            }\n            break;\n          case 2:\n            E = _E(phi_x, phi_y, phi_z, t_x + beta, t_y, t_z, world_points, picked_points);\n            if (min > E)\n            {\n              min = E;\n              j = i;\n            }\n            break;\n          case 3:\n            E = _E(phi_x, phi_y, phi_z, t_x - beta, t_y, t_z, world_points, picked_points);\n            if (min > E)\n            {\n              min = E;\n              j = i;\n            }\n            break;\n          case 4:\n            E = _E(phi_x, phi_y, phi_z, t_x, t_y + gamma, t_z, world_points, picked_points);\n            if (min > E)\n            {\n              min = E;\n              j = i;\n            }\n            break;\n          case 5:\n            E = _E(phi_x, phi_y, phi_z, t_x, t_y - gamma, t_z, world_points, picked_points);\n            if (min > E)\n            {\n              min = E;\n              j = i;\n            }\n            break;\n        }\n        E = min;\n      }\n      switch (j)\n      {\n        case 0:\n          phi_z += alpha;\n          if (phi_z > M_PI)\n          {\n            phi_z -= 2.0 * M_PI;\n          }\n          break;\n        case 1:\n          phi_z -= alpha;\n          if (phi_z < -M_PI)\n          {\n            phi_z += 2.0 * M_PI;\n          }\n          break;\n        case 2:\n          t_x += beta;\n          break;\n        case 3:\n          t_x -= beta;\n          break;\n        case 4:\n          t_y += gamma;\n          break;\n        case 5:\n          t_y -= gamma;\n          break;\n=======\n      min = std::numeric_limits<double>::infinity();\n      for (i=0; i<6; i++)\n      {\n        switch(i)\n        {\n        case 0:\n          E = _E(phi_x,phi_y,phi_z+alpha,t_x,t_y,t_z,world_points,picked_points);\n          if (min > E)\n          {\n            min = E;\n            j = i;\n          }\n          break;\n        case 1:\n          E = _E(phi_x,phi_y,phi_z-alpha,t_x,t_y,t_z,world_points,picked_points);\n          if (min > E)\n          {\n            min = E;\n            j = i;\n          }\n          break;\n        case 2:\n          E = _E(phi_x,phi_y,phi_z,t_x+beta,t_y,t_z,world_points,picked_points);\n          if (min > E)\n          {\n            min = E;\n            j = i;\n          }\n          break;\n        case 3:\n          E = _E(phi_x,phi_y,phi_z,t_x-beta,t_y,t_z,world_points,picked_points);\n          if (min > E)\n          {\n            min = E;\n            j = i;\n          }\n          break;\n        case 4:\n          E = _E(phi_x,phi_y,phi_z,t_x,t_y+gamma,t_z,world_points,picked_points);\n          if (min > E)\n          {\n            min = E;\n            j = i;\n          }\n          break;\n        case 5:\n          E = _E(phi_x,phi_y,phi_z,t_x,t_y-gamma,t_z,world_points,picked_points);\n          if (min > E)\n          {\n            min = E;\n            j = i;\n          }\n          break;\n        }\n        E = min;\n      }\n      switch(j)\n      {\n      case 0:\n        phi_z += alpha;\n        if (phi_z > M_PI)\n        {\n          phi_z -= 2.0 * M_PI;\n        }\n        break;\n      case 1:\n        phi_z -= alpha;\n        if (phi_z < -M_PI)\n        {\n          phi_z += 2.0 * M_PI;\n        }\n        break;\n      case 2:\n        t_x += beta;\n        break;\n      case 3:\n        t_x -= beta;\n        break;\n      case 4:\n        t_y += gamma;\n        break;\n      case 5:\n        t_y -= gamma;\n        break;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n      }\n      cnt++;\n      if (cnt % 1000 == 0)\n      {\n        std::cout << \"delta_E \" << cnt << \"-> \" << E_prev - E << std::endl;\n      }\n    } while (E_prev - E > _th);\n  }\n  else\n  {\n    std::cerr << \"Error::Requrered unexpected method.\" << std::endl;\n    return 1;\n  }\n\n  std::cout << \"Tried \" << cnt << \" times for convertion calcuration of extrinsic parameters\" << std::endl;\n<<<<<<< HEAD\n  std::cout << \"rpy[deg]: \" << phi_x * 180.0 / M_PI << \", \" << phi_y * 180.0 / M_PI << \", \" << phi_z * 180.0 / M_PI\n            << std::endl;\n\n  std::cout << \"t[mm]: \" << t_x << \", \" << t_y << \", \" << t_z << std::endl;\n\n  {  // Draw axis on cloud viewer for certification\n    Eigen::Matrix3d rotation = Eigen::Matrix3d::Zero();\n    rotation =\n        Eigen::AngleAxisd(phi_z, ax_cam[2]) * Eigen::AngleAxisd(phi_y, ax_cam[1]) * Eigen::AngleAxisd(phi_x, ax_cam[0]);\n    Eigen::Vector3d translation = Eigen::Vector3d(t_x, t_y, t_z);\n    tmp = Eigen::Vector3d::Zero();\n    // tmp = rotation * tmp + translation;\n    tmp = rotation.inverse() * (tmp - translation);\n=======\n  std::cout << \"rpy[deg]: \" <<\n    phi_x*180.0/M_PI << \", \" <<\n    phi_y*180.0/M_PI << \", \" <<\n    phi_z*180.0/M_PI << std::endl;\n\n  std::cout << \"t[mm]: \" <<\n    t_x << \", \" <<\n    t_y << \", \" <<\n    t_z << std::endl;\n\n\n  { // Draw axis on cloud viewer for certification\n    Eigen::Matrix3d rotation = Eigen::Matrix3d::Zero();\n    rotation = Eigen::AngleAxisd(phi_z, ax_cam[2])\n      * Eigen::AngleAxisd(phi_y, ax_cam[1])\n      * Eigen::AngleAxisd(phi_x, ax_cam[0]);\n    Eigen::Vector3d translation = Eigen::Vector3d(t_x,t_y,t_z);\n    tmp = Eigen::Vector3d::Zero();\n    //tmp = rotation * tmp + translation;\n    tmp = rotation.inverse() * ( tmp - translation );\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    _s.x = (tmp[0]) / 1000.0;\n    _s.y = (tmp[1]) / 1000.0;\n    _s.z = (tmp[2]) / 1000.0;\n    _s.r = 0;\n    _s.g = 0;\n    _s.b = 0;\n    // axis 1\n<<<<<<< HEAD\n    tmp = Eigen::Vector3d::UnitX() * 50;\n=======\n    tmp = Eigen::Vector3d::UnitX()*50;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    tmp = rotation.inverse() * (tmp - translation);\n    _ex.x = (tmp[0]) / 1000.0;\n    _ex.y = (tmp[1]) / 1000.0;\n    _ex.z = (tmp[2]) / 1000.0;\n    _ex.r = 255;\n    _ex.g = 0;\n    _ex.b = 0;\n    // axis 2\n<<<<<<< HEAD\n    tmp = Eigen::Vector3d::UnitY() * 50;\n=======\n    tmp = Eigen::Vector3d::UnitY()*50;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    tmp = rotation.inverse() * (tmp - translation);\n    _ey.x = (tmp[0]) / 1000.0;\n    _ey.y = (tmp[1]) / 1000.0;\n    _ey.z = (tmp[2]) / 1000.0;\n    _ey.r = 0;\n    _ey.g = 255;\n    _ey.b = 0;\n    // axis 3\n<<<<<<< HEAD\n    tmp = Eigen::Vector3d::UnitZ() * 50;\n=======\n    tmp = Eigen::Vector3d::UnitZ()*50;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    tmp = rotation.inverse() * (tmp - translation);\n    _ez.x = (tmp[0]) / 1000.0;\n    _ez.y = (tmp[1]) / 1000.0;\n    _ez.z = (tmp[2]) / 1000.0;\n    _ez.r = 0;\n    _ez.g = 0;\n    _ez.b = 255;\n    viewer->runOnVisualizationThread(viewerDrawAxis);\n    viewer->showCloud(cloud);\n  }\n\n  return 0;\n}\n\nint MyCalibration::startPickingPoints()\n{\n  g_picking_counter = 0;\n  return 0;\n}\n\nint MyCalibration::pickPointsAutomatically(int pattern_rows, int pattern_cols)\n{\n<<<<<<< HEAD\n  int i, j;\n  int key;\n  cv::Mat image_chess(CAMERA_RESOLUTION_Y, CAMERA_RESOLUTION_X, CV_8UC3);\n\n  // openni::VideoFrameRef frame;\n  bool pattern_found;\n  std::vector< cv::Point2f > corners;\n  cv::namedWindow(\"Detecting points\");\n  for (i = 0; i < image.rows; i++)\n  {\n    for (j = 0; j < image.cols; j++)\n    {\n      image_chess.at< cv::Vec3b >(i, j) = cv::Vec3b(255, 255, 255);\n=======\n  int i,j;\n  int key;\n  cv::Mat image_chess(CAMERA_RESOLUTION_Y, CAMERA_RESOLUTION_X, CV_8UC3);\n\n  //openni::VideoFrameRef frame;\n  bool pattern_found;\n  std::vector<cv::Point2f> corners;\n  cv::namedWindow(\"Detecting points\");\n  for (i=0; i<image.rows; i++)\n  {\n    for (j=0; j<image.cols; j++)\n    {\n      image_chess.at<cv::Vec3b>(i,j) = cv::Vec3b(255,255,255);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    }\n  }\n\n  if (color_frame != NULL)\n<<<<<<< HEAD\n  {  // Detect corners with color image.\n    image_chess = cv::Mat(CAMERA_RESOLUTION_Y, CAMERA_RESOLUTION_X, CV_8UC3, color_frame);\n    cv::cvtColor(image_chess, image_chess, CV_BGR2RGB);\n  }\n  else\n  {                      // Detect corners with depth image.\n    if (key == 1048681)  // key == 'i' ?\n    {                    // Clean image\n      for (i = 0; i < CAMERA_RESOLUTION_Y; i++)\n      {\n        for (j = 0; j < CAMERA_RESOLUTION_X; j++)\n        {\n          image.at< cv::Vec3b >(i, j) = cv::Vec3b(255, 255, 255);\n=======\n  { // Detect corners with color image.\n    image_chess = cv::Mat(CAMERA_RESOLUTION_Y,CAMERA_RESOLUTION_X,CV_8UC3,color_frame);\n    cv::cvtColor(image_chess,image_chess,CV_BGR2RGB);\n  }\n  else\n  { // Detect corners with depth image.\n    if (key == 1048681) // key == 'i' ?\n    { // Clean image\n      for (i=0; i<CAMERA_RESOLUTION_Y; i++)\n      {\n        for (j=0; j<CAMERA_RESOLUTION_X; j++)\n        {\n          image.at<cv::Vec3b>(i,j) = cv::Vec3b(255,255,255);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n        }\n      }\n    }\n    // Fill with brack at invalid pixel\n<<<<<<< HEAD\n    float* dp;\n    // dp = (openni::DepthPixel*)depth_frame;\n    for (i = 0; i < image.rows; i++)\n    {\n      for (j = 0; j < image.cols; j++)\n      {\n        int now = (i * CAMERA_RESOLUTION_X + j);\n        if (*(float*)(dp + now) == INVALID_PIXEL_VALUE)\n        {\n          image.at< cv::Vec3b >(i, j) = cv::Vec3b(0, 0, 0);\n=======\n    float *dp;\n    //dp = (openni::DepthPixel*)depth_frame;\n    for (i=0; i<image.rows; i++)\n    {\n      for (j=0; j<image.cols; j++)\n      {\n        int now = (i*CAMERA_RESOLUTION_X+j);\n        if (*(float*)(dp+now) == INVALID_PIXEL_VALUE)\n        {\n          image.at<cv::Vec3b>(i,j) = cv::Vec3b(0,0,0);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n        }\n      }\n    }\n  }\n<<<<<<< HEAD\n  find_corner(image_chess, cv::Size(pattern_cols, pattern_rows), corners, pattern_found);\n  cv::drawChessboardCorners(image_chess, cv::Size(pattern_cols, pattern_rows), (cv::Mat)corners, pattern_found);\n  cv::imshow(\"Detecting points\", image_chess);\n  if (!pattern_found)\n=======\n  find_corner(image_chess, cv::Size(pattern_cols,pattern_rows), corners, pattern_found);\n  cv::drawChessboardCorners( image_chess, cv::Size(pattern_cols,pattern_rows),\n      (cv::Mat)corners, pattern_found);\n  cv::imshow(\"Detecting points\", image_chess);\n  if(!pattern_found)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  {\n    int key = cv::waitKey(10);\n    return key;\n  }\n\n  std::cout << \"Detected corners\" << std::endl;\n  key = cv::waitKey(0);\n  cv::destroyWindow(\"Detecting points\");\n\n<<<<<<< HEAD\n  g_points[0][0] = (int)corners[0].x;\n  g_points[0][1] = (int)corners[0].y;\n  g_points[1][0] = (int)corners[(pattern_rows - 1) * pattern_cols].x;\n  g_points[1][1] = (int)corners[(pattern_rows - 1) * pattern_cols].y;\n  g_points[2][0] = (int)corners[pattern_cols - 1].x;\n  g_points[2][1] = (int)corners[pattern_cols - 1].y;\n  g_points[3][0] = (int)corners[pattern_rows * pattern_cols - 1].x;\n  g_points[3][1] = (int)corners[pattern_rows * pattern_cols - 1].y;\n\n  for (i = 0; i < pattern_rows; i++)\n  {\n    for (j = 0; j < pattern_cols; j++)\n    {\n      g_picked_points[i * pattern_cols + j][0] = (int)corners[i * pattern_cols + j].x;\n      g_picked_points[i * pattern_cols + j][1] = (int)corners[i * pattern_cols + j].y;\n=======\n  g_points[0][0] = (int)corners[ 0].x;\n  g_points[0][1] = (int)corners[ 0].y;\n  g_points[1][0] = (int)corners[(pattern_rows-1)*pattern_cols].x;\n  g_points[1][1] = (int)corners[(pattern_rows-1)*pattern_cols].y;\n  g_points[2][0] = (int)corners[pattern_cols-1].x;\n  g_points[2][1] = (int)corners[pattern_cols-1].y;\n  g_points[3][0] = (int)corners[pattern_rows*pattern_cols-1].x;\n  g_points[3][1] = (int)corners[pattern_rows*pattern_cols-1].y;\n\n  for(i=0; i<pattern_rows; i++)\n  {\n    for(j=0; j<pattern_cols; j++)\n    {\n      g_picked_points[i*pattern_cols+j][0] = (int)corners[i*pattern_cols+j].x;\n      g_picked_points[i*pattern_cols+j][1] = (int)corners[i*pattern_cols+j].y;\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n    }\n  }\n\n  return 0;\n}\n\nvoid MyCalibration::getDepthFrameCallback(const sensor_msgs::Image::ConstPtr& frame)\n{\n  int i, j;\n<<<<<<< HEAD\n  uint8_t* p;\n  for (i = 0, p = depth_frame; i < frame->height * frame->step; i++, p++)\n=======\n  uint8_t *p;\n  for (i=0, p = depth_frame; i < frame->height*frame->step; i++, p++)\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  {\n    *p = frame->data[i];\n  }\n  cv::Mat image_tmp = cv::Mat(frame->height, frame->width, CV_16UC1, depth_frame);\n<<<<<<< HEAD\n  image_tmp.convertTo(image, CV_8UC1, 255.0 / 10000.0);\n  // cv::imshow(\"Depth image\", image);\n=======\n  image_tmp.convertTo(image, CV_8UC1, 255.0/10000.0);\n  //cv::imshow(\"Depth image\", image);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  return;\n}\n\nvoid MyCalibration::getColorFrameCallback(const sensor_msgs::Image::ConstPtr& frame)\n{\n  int i;\n<<<<<<< HEAD\n  uint8_t* p;\n  for (i = 0, p = color_frame; i < frame->height * frame->step; i++, p++)\n  {\n    *p = frame->data[i];\n  }\n  // cv::Mat image_tmp = cv::Mat(frame->height, frame->width, CV_8UC3, color_frame);\n  // cv::cvtColor(image_tmp,image_tmp,CV_BGR2RGB);\n  // cv::imshow(\"Color image\", image_tmp);\n  // cv::waitKey(10);\n=======\n  uint8_t *p;\n  for (i=0, p = color_frame; i < frame->height*frame->step; i++, p++)\n  {\n    *p = frame->data[i];\n  }\n  //cv::Mat image_tmp = cv::Mat(frame->height, frame->width, CV_8UC3, color_frame);\n  //cv::cvtColor(image_tmp,image_tmp,CV_BGR2RGB);\n  //cv::imshow(\"Color image\", image_tmp);\n  //cv::waitKey(10);\n>>>>>>> 51ecc3540900cfe208d8c2ca1ecaf2184d407ca7\n  return;\n}\n\nvoid MyCalibration::getPointsCallback(const sensor_msgs::PointCloud2::ConstPtr& points)\n{\n  this->points = points;\n  return;\n}\n", "meta": {"hexsha": "810a131c08f8c75c3d80f79438f297fcd3a944e1", "size": 42733, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tms_ss/tms_ss_xtion/estimateExtrinsicParameters/src/MyCalibration.cpp", "max_stars_repo_name": "SigmaHayashi/ros_tms_for_smart_previewed_reality", "max_stars_repo_head_hexsha": "4ace908bd3da0519246b3c45d0230cbd02e49da0", "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": "tms_ss/tms_ss_xtion/estimateExtrinsicParameters/src/MyCalibration.cpp", "max_issues_repo_name": "SigmaHayashi/ros_tms_for_smart_previewed_reality", "max_issues_repo_head_hexsha": "4ace908bd3da0519246b3c45d0230cbd02e49da0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tms_ss/tms_ss_xtion/estimateExtrinsicParameters/src/MyCalibration.cpp", "max_forks_repo_name": "SigmaHayashi/ros_tms_for_smart_previewed_reality", "max_forks_repo_head_hexsha": "4ace908bd3da0519246b3c45d0230cbd02e49da0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2491444216, "max_line_length": 120, "alphanum_fraction": 0.5606439988, "num_tokens": 14274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.24523270784553378}}
{"text": "/*\n * MIT License\n *\n * Copyright (c) 2020 Robert Grupp\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include \"xregRayCastSurRenderOCL.h\"\n\n#include <boost/compute/utility/source.hpp>\n#include <boost/compute/types/struct.hpp>\n\n#include \"xregAssert.h\"\n\n//////////////////////////////////////////////////////////////////////\n\nBOOST_COMPUTE_ADAPT_STRUCT(xreg::RayCasterSurRenderOCL::RayCastSurRenderArgs, RayCastSurRenderArgs,\n                           (thresh,\n                            pad1,\n                            num_backtracking_steps,\n                            ambient_reflection_ratio,\n                            diffuse_reflection_ratio,\n                            specular_reflection_ratio,\n                            alpha_shininess))\n\n//////////////////////////////////////////////////////////////////////\n\nnamespace  // un-named\n{\n\nconst char* kRAY_CASTING_SUR_RENDER_OPENCL_SRC = BOOST_COMPUTE_STRINGIZE_SOURCE(\n\n__kernel void xregSurRenderKernel1(const RayCastArgs args,\n                                   const RayCastSurRenderArgs sur_render_args,\n                                   __global const float4* det_pts,\n                                   image3d_t vol_tex,\n                                   __global const float16* cam_to_itk_phys_xforms,\n                                   __global float8* dst_step_vecs_and_intersect_pts_wrt_itk_idx,\n                                   __global const ulong* cam_model_for_proj,\n                                   __global const float4* cam_focal_pts)\n{\n  const ulong idx = get_global_id(0);\n\n  const ulong num_rays = args.num_projs * args.num_det_pts;\n\n  if (idx < num_rays)\n  {\n    const ulong proj_idx   = idx / args.num_det_pts;\n    const ulong det_pt_idx = idx - (proj_idx * args.num_det_pts);\n    const ulong cam_idx    = cam_model_for_proj[proj_idx];\n\n    const float4 focal_pt_wrt_cam = cam_focal_pts[cam_idx];\n\n    const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_LINEAR;\n    \n    const float4 tex_coords_off = (float4) (0.5f, 0.5f, 0.5f, 0);\n\n    const float16 xform_cam_to_itk_idx = xregFrm4x4Composition(args.itk_phys_pt_to_itk_idx_xform,\n                                                               cam_to_itk_phys_xforms[proj_idx]);\n\n    const float4 pinhole_wrt_itk_idx = xregFrm4x4XformFloat4Pt(xform_cam_to_itk_idx, focal_pt_wrt_cam);\n\n    const float4 cur_det_pt_wrt_cam = det_pts[(cam_idx * args.num_det_pts) + det_pt_idx];\n\n    const float4 pinhole_to_det_wrt_itk_idx = xregFrm4x4XformFloat4Pt(xform_cam_to_itk_idx, cur_det_pt_wrt_cam)\n                                                  - pinhole_wrt_itk_idx;\n\n    // check intersection with the image/volume boundary\n    // these pointer were passed as float4's since boost::compute does not have a float3\n    float2 t = xregRayRectIntersect(xregFloat4HmgToFloat3(args.img_aabb_min),\n                                    xregFloat4HmgToFloat3(args.img_aabb_max),\n                                    xregFloat4HmgToFloat3(pinhole_wrt_itk_idx),\n                                    xregFloat4HmgToFloat3(pinhole_to_det_wrt_itk_idx));\n    // t.x indicates the first intersection with the volume along the source to detector ray,\n    // t.y indicates the exit of the volume along the source to detector ray\n    // t.x, t.y are in [0,inf)\n\n    const float4 start_pt_wrt_itk_idx = pinhole_wrt_itk_idx + (t.x * pinhole_to_det_wrt_itk_idx);\n\n    const float pinhole_to_det_len_wrt_itk_idx = xregFloat4HmgNorm(pinhole_to_det_wrt_itk_idx);\n    const float intersect_len_wrt_itk_idx = (t.y - t.x) * pinhole_to_det_len_wrt_itk_idx;\n\n    const float4 focal_pt_to_det_wrt_cam = cur_det_pt_wrt_cam - focal_pt_wrt_cam;\n    // NOTE: since we are transforming a vector with a scaling transform (points to indices),\n    //       the output vector may not have the same norm, thus we take the norm\n    const float step_len_wrt_itk_idx = xregFloat4HmgNorm(\n                      xregFrm4x4XformFloat4Vec(xform_cam_to_itk_idx,\n                         (focal_pt_to_det_wrt_cam / xregFloat4HmgNorm(focal_pt_to_det_wrt_cam)) * args.step_size));\n\n    const ulong num_steps = (ulong)(intersect_len_wrt_itk_idx / step_len_wrt_itk_idx);\n\n    float4 cur_cont_vol_idx = (float4) (start_pt_wrt_itk_idx.x, start_pt_wrt_itk_idx.y, start_pt_wrt_itk_idx.z, 0);\n\n    // \"/ pinhole_to_det_len_wrt_itk_idx\" makes pinhole_to_det_wrt_itk_idx a unit vector\n    const float scale_to_step = step_len_wrt_itk_idx / pinhole_to_det_len_wrt_itk_idx;\n\n    const float4 step_vec_wrt_itk_idx = (float4) (pinhole_to_det_wrt_itk_idx.x * scale_to_step, pinhole_to_det_wrt_itk_idx.y * scale_to_step, pinhole_to_det_wrt_itk_idx.z * scale_to_step, 0);\n\n    // The first three elements will store the step direction in ITK index space\n    dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s0 = step_vec_wrt_itk_idx.x;\n    dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s1 = step_vec_wrt_itk_idx.y;\n    dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s2 = step_vec_wrt_itk_idx.z;\n\n    // The fourth element will indicate whether this ray intersected the surface.\n    dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s3 = 0;  //  0 -> no intersection found\n\n    for (ulong step_idx = 0; step_idx <= num_steps; ++step_idx, cur_cont_vol_idx += step_vec_wrt_itk_idx)\n    {\n      if (read_imagef(vol_tex, sampler, cur_cont_vol_idx + tex_coords_off).x >= sur_render_args.thresh)\n      {\n        // The 5th, 6th, and 7th elements will store the initial point of intersection, before any backtracking\n        dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s4 = cur_cont_vol_idx.x;\n        dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s5 = cur_cont_vol_idx.y;\n        dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s6 = cur_cont_vol_idx.z;\n        dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s7 = 0;\n\n        dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s3 = 1;  // 1 -> intersection found\n        break;\n      }\n    }\n  }\n}\n\n__kernel void xregSurRenderKernel2(const RayCastArgs args,\n                                   const RayCastSurRenderArgs sur_render_args,\n                                   image3d_t vol_tex,\n                                   __global const float8* dst_step_vecs_and_intersect_pts_wrt_itk_idx,\n                                   __global float* dst_intensities)\n{\n  const ulong idx = get_global_id(0);\n\n  const ulong num_rays = args.num_projs * args.num_det_pts;\n\n  if (idx < num_rays)\n  {\n    if (dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s3 > 1.0e-6)\n    {\n      const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_LINEAR;\n      \n      const float4 tex_coords_off = (float4) (0.5f, 0.5f, 0.5f, 0);\n\n      float3 light_src_vec = (float3) (dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s0, dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s1, dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s2);\n      // right now, this light source vector points from the light source, it needs to be negated, and it is when normalizing a few lines below\n\n      // This vector will always point towards the pinhole.\n      float4 step_vec_wrt_itk_idx = (float4) (light_src_vec.x, light_src_vec.y, light_src_vec.z, 0);\n      step_vec_wrt_itk_idx *= 0.5f;\n\n      // normalize the direction vector to the light source, and negate to get the right orientation\n      light_src_vec /= -xregFloat3Norm(light_src_vec);\n\n      float4 cur_cont_vol_idx = (float4) (dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s4, dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s5, dst_step_vecs_and_intersect_pts_wrt_itk_idx[idx].s6, 0);\n      \n      cur_cont_vol_idx += tex_coords_off;\n\n      // we know that we should start out backtracking.\n      cur_cont_vol_idx -= step_vec_wrt_itk_idx;\n\n      for (ulong backtrack_idx = 0; backtrack_idx < sur_render_args.num_backtracking_steps; ++backtrack_idx)\n      {\n        step_vec_wrt_itk_idx *= 0.5f;\n\n        cur_cont_vol_idx += (read_imagef(vol_tex, sampler, cur_cont_vol_idx).x >= sur_render_args.thresh) ?\n                                  step_vec_wrt_itk_idx : -step_vec_wrt_itk_idx;\n      }\n\n      // compute lighting/shading according to the phong model\n\n      // approximate the derivative at this point with finite differencing adjacent indices\n      // NOTE: these are wrt image (index) axes.\n\n      float3 tmp_vec;\n\n      // Gradient in X Direction:\n      tmp_vec.x = read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x + 1, cur_cont_vol_idx.y, cur_cont_vol_idx.z, cur_cont_vol_idx.w)).x -\n                  read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x - 1, cur_cont_vol_idx.y, cur_cont_vol_idx.z, cur_cont_vol_idx.w)).x;\n\n      // Gradient in Y Direction:\n      tmp_vec.y = read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x, cur_cont_vol_idx.y + 1, cur_cont_vol_idx.z, cur_cont_vol_idx.w)).x -\n                  read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x, cur_cont_vol_idx.y - 1, cur_cont_vol_idx.z, cur_cont_vol_idx.w)).x;\n\n      // Gradient in Z Direction:\n      tmp_vec.z = read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x, cur_cont_vol_idx.y, cur_cont_vol_idx.z + 1, cur_cont_vol_idx.w)).x -\n                  read_imagef(vol_tex, sampler, (float4) (cur_cont_vol_idx.x, cur_cont_vol_idx.y, cur_cont_vol_idx.z - 1, cur_cont_vol_idx.w)).x;\n\n      tmp_vec /= (-0.5f * xregFloat3Norm(tmp_vec));\n\n      float val = sur_render_args.ambient_reflection_ratio;\n\n      // Treating the pinhole as the light source\n\n      float tmp_dot = xregFloat3Inner(light_src_vec, tmp_vec);\n      const int diffuse_valid = tmp_dot > 1.0e-6;\n\n      val += diffuse_valid ? (sur_render_args.diffuse_reflection_ratio * tmp_dot) : 0;\n\n      tmp_vec *= 2 * tmp_dot;\n      tmp_vec -= light_src_vec;\n\n      tmp_dot = xregFloat3Inner(light_src_vec, tmp_vec);\n\n      val += (tmp_dot > 1.0e-6) ?\n              (sur_render_args.specular_reflection_ratio * pow(tmp_dot, sur_render_args.alpha_shininess)) : 0;\n\n      dst_intensities[idx] += val;\n    }\n  }\n}\n\n);\n\n//////////////////////////////////////////////////////////////////////\n\n}  // un-named\n\nxreg::RayCasterSurRenderOCL::RayCasterSurRenderOCL()\n  : RayCasterOCL(), step_vecs_and_intersect_pts_wrt_itk_idx_dev_(ctx_)\n{ }\n\nxreg::RayCasterSurRenderOCL::RayCasterSurRenderOCL(const boost::compute::device& dev)\n  : RayCasterOCL(dev), step_vecs_and_intersect_pts_wrt_itk_idx_dev_(ctx_)\n{ }\n\nxreg::RayCasterSurRenderOCL::RayCasterSurRenderOCL(const boost::compute::context& ctx,\n                                                   const boost::compute::command_queue& queue)\n  : RayCasterOCL(ctx, queue), step_vecs_and_intersect_pts_wrt_itk_idx_dev_(ctx_)\n{ }\n\nvoid xreg::RayCasterSurRenderOCL::allocate_resources()\n{\n  namespace bc = boost::compute;\n\n  RayCasterOCL::allocate_resources();\n\n  // Build the surface rendering ray casting program\n  std::stringstream ss;\n  ss << RayCastBaseOCLStr()\n     << boost::compute::type_definition<RayCasterSurRenderOCL::RayCastSurRenderArgs>()\n     << kRAY_CASTING_SUR_RENDER_OPENCL_SRC;\n\n  bc::program prog = bc::program::create_with_source(ss.str(), ctx_);\n  prog.build();\n\n  dev_kernel1_ = prog.create_kernel(\"xregSurRenderKernel1\");\n\n  dev_kernel2_ = prog.create_kernel(\"xregSurRenderKernel2\");\n\n  step_vecs_and_intersect_pts_wrt_itk_idx_dev_.resize(this->camera_models_[0].num_det_rows *\n                                                      this->camera_models_[0].num_det_cols *\n                                                      this->num_projs_,\n                                                      cmd_queue_);\n}\n\nvoid xreg::RayCasterSurRenderOCL::compute(const size_type vol_idx)\n{\n  xregASSERT(this->resources_allocated_);\n  \n  compute_helper_pre_kernels(vol_idx);\n\n  RayCastSurRenderArgs sur_args;\n  \n  sur_args.thresh = render_thresh();\n  \n  sur_args.num_backtracking_steps = num_backtracking_steps();\n  \n  sur_args.ambient_reflection_ratio =\n                  surface_render_params().ambient_reflection_ratio;\n  \n  sur_args.diffuse_reflection_ratio =\n                  surface_render_params().diffuse_reflection_ratio;\n  \n  sur_args.specular_reflection_ratio =\n                  surface_render_params().specular_reflection_ratio;\n  \n  sur_args.alpha_shininess = surface_render_params().alpha_shininess;\n\n  // setup kernel arguments and launch\n\n  dev_kernel1_.set_arg(0, sizeof(ray_cast_kernel_args_), &ray_cast_kernel_args_);\n\n  dev_kernel1_.set_arg(1, sizeof(sur_args), &sur_args);\n\n  dev_kernel1_.set_arg(2, det_pts_dev_);\n\n  dev_kernel1_.set_arg(3, vol_texs_dev_[vol_idx]);\n\n  dev_kernel1_.set_arg(4, cam_to_itk_phys_xforms_dev_);\n\n  dev_kernel1_.set_arg(5, step_vecs_and_intersect_pts_wrt_itk_idx_dev_);\n\n  dev_kernel1_.set_arg(6, cam_model_for_proj_dev_);\n\n  dev_kernel1_.set_arg(7, focal_pts_dev_);\n\n  std::size_t global_work_size = ray_cast_kernel_args_.num_det_pts * this->num_projs_;\n  //std::size_t local_work_size = 512;  passing null lets open CL pick a local size\n\n  cmd_queue_.enqueue_nd_range_kernel(dev_kernel1_,\n                                     1, // dim\n                                     0, // null offset -> start at 0\n                                     &global_work_size,\n                                     0  // passing null lets open CL pick a local size\n                                    ).wait();\n\n\n  dev_kernel2_.set_arg(0, sizeof(ray_cast_kernel_args_), &ray_cast_kernel_args_);\n\n  dev_kernel2_.set_arg(1, sizeof(sur_args), &sur_args);\n\n  dev_kernel2_.set_arg(2, vol_texs_dev_[vol_idx]);\n\n  dev_kernel2_.set_arg(3, step_vecs_and_intersect_pts_wrt_itk_idx_dev_);\n\n  dev_kernel2_.set_arg(4, *proj_pixels_dev_to_use_);\n\n  cmd_queue_.enqueue_nd_range_kernel(dev_kernel2_,\n                                     1, // dim\n                                     0, // null offset -> start at 0\n                                     &global_work_size,\n                                     0  // passing null lets open CL pick a local size\n                                    ).wait();\n\n  compute_helper_post_kernels(vol_idx);\n}\n\n", "meta": {"hexsha": "1045ea08c3a14f05f0fff883eb579db4ffc21509", "size": 15051, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/ray_cast/xregRayCastSurRenderOCL.cpp", "max_stars_repo_name": "rg2/xreg", "max_stars_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-09-29T18:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:25:13.000Z", "max_issues_repo_path": "lib/ray_cast/xregRayCastSurRenderOCL.cpp", "max_issues_repo_name": "rg2/xreg", "max_issues_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-09T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T15:39:44.000Z", "max_forks_repo_path": "lib/ray_cast/xregRayCastSurRenderOCL.cpp", "max_forks_repo_name": "rg2/xreg", "max_forks_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-05-25T05:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T12:29:50.000Z", "avg_line_length": 43.8804664723, "max_line_length": 204, "alphanum_fraction": 0.676034815, "num_tokens": 3805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.24515028723720897}}
{"text": "// Copyright (C) 2006-2009 Dmitry Bufistov and Andrey Parfenov\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GRAPH_CYCLE_RATIO_HOWARD_HPP\n#define BOOST_GRAPH_CYCLE_RATIO_HOWARD_HPP\n\n#include <vector>\n#include <list>\n#include <algorithm>\n#include <limits>\n\n#include <boost/bind.hpp>\n#include <boost/type_traits/is_same.hpp>\n#include <boost/type_traits/remove_const.hpp>\n#include <boost/concept_check.hpp>\n#include <boost/pending/queue.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n\n/** @file howard_cycle_ratio.hpp\n * @brief The implementation of the maximum/minimum cycle ratio/mean algorithm.\n * @author Dmitry Bufistov\n * @author Andrey Parfenov\n */\n\nnamespace boost {\n\n  /**\n   * The mcr_float is like numeric_limits, but only for floating point types\n   * and only defines infinity() and epsilon(). This class is primarily used\n   * to encapsulate a less-precise epsilon than natively supported by the\n   * floating point type.\n   */\n  template <typename Float = double> struct mcr_float {\n    typedef Float value_type;\n\n    static Float infinity()\n    { return std::numeric_limits<value_type>::infinity(); }\n\n    static Float epsilon()\n    { return Float(-0.005); }\n  };\n\n  namespace detail {\n\n    template <typename FloatTraits> struct\n    min_comparator_props {\n      typedef std::greater<typename FloatTraits::value_type> comparator;\n      static const int multiplier = 1;\n    };\n\n    template <typename FloatTraits> struct\n    max_comparator_props {\n      typedef std::less<typename FloatTraits::value_type> comparator;\n      static const int multiplier = -1;\n    };\n\n    template <typename FloatTraits, typename ComparatorProps>\n    struct float_wrapper {\n      typedef typename FloatTraits::value_type value_type;\n      typedef ComparatorProps comparator_props_t;\n      typedef typename ComparatorProps::comparator comparator;\n\n      static value_type infinity()\n      { return FloatTraits::infinity() * ComparatorProps::multiplier; }\n\n      static value_type epsilon()\n      { return FloatTraits::epsilon() * ComparatorProps::multiplier; }\n\n    };\n\n    /*! @class mcr_howard\n     * @brief Calculates optimum (maximum/minimum) cycle ratio of a directed graph.\n     * Uses  Howard's iteration policy algorithm. </br>(It is described in the paper\n     * \"Experimental Analysis of the Fastest Optimum Cycle Ratio and Mean Algorithm\"\n     * by Ali Dasdan).\n     */\n    template <typename FloatTraits,\n              typename Graph, typename VertexIndexMap,\n              typename EdgeWeight1, typename EdgeWeight2>\n    class mcr_howard\n    {\n    public:\n      typedef typename FloatTraits::value_type float_t;\n      typedef typename FloatTraits::comparator_props_t cmp_props_t;\n      typedef typename FloatTraits::comparator comparator_t;\n      typedef enum{ my_white = 0, my_black } my_color_type;\n      typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;\n      typedef typename graph_traits<Graph>::edge_descriptor edge_t;\n      typedef typename graph_traits<Graph>::vertices_size_type vn_t;\n      typedef std::vector<float_t> vp_t;\n      typedef typename boost::iterator_property_map<\n        typename vp_t::iterator, VertexIndexMap\n      > distance_map_t; //V -> float_t\n\n      typedef typename std::vector<edge_t> ve_t;\n      typedef std::vector<my_color_type> vcol_t;\n      typedef typename ::boost::iterator_property_map<\n        typename ve_t::iterator, VertexIndexMap\n      > policy_t; //Vertex -> Edge\n      typedef typename ::boost::iterator_property_map<\n        typename vcol_t::iterator, VertexIndexMap\n      > color_map_t;\n\n      typedef typename std::list<vertex_t> pinel_t;// The in_edges list of the policy graph\n      typedef typename std::vector<pinel_t> inedges1_t;\n      typedef typename ::boost::iterator_property_map<\n        typename inedges1_t::iterator, VertexIndexMap\n      > inedges_t;\n      typedef typename std::vector<edge_t> critical_cycle_t;\n\n      //Bad  vertex flag. If true, then the vertex is \"bad\".\n      // Vertex is \"bad\" if its out_degree is equal to zero.\n      typedef typename boost::iterator_property_map<\n        std::vector<int>::iterator, VertexIndexMap\n      > badv_t;\n\n      /*!\n       * Constructor\n       * \\param g = (V, E) - a directed multigraph.\n       * \\param vim  Vertex Index Map. Read property Map: V -> [0, num_vertices(g)).\n       * \\param ewm  edge weight map. Read property map: E -> R\n       * \\param ew2m  edge weight map. Read property map: E -> R+\n       * \\param infty A big enough value to guaranty that there exist a cycle with\n       *  better ratio.\n       * \\param cmp The compare operator for float_ts.\n       */\n      mcr_howard(const Graph &g, VertexIndexMap vim,\n                  EdgeWeight1 ewm, EdgeWeight2 ew2m) :\n        m_g(g), m_vim(vim), m_ew1m(ewm), m_ew2m(ew2m),\n        m_bound(mcr_bound()),\n        m_cr(m_bound),\n        m_V(num_vertices(m_g)),\n        m_dis(m_V, 0), m_dm(m_dis.begin(), m_vim),\n        m_policyc(m_V), m_policy(m_policyc.begin(), m_vim),\n        m_inelc(m_V), m_inel(m_inelc.begin(), m_vim),\n        m_badvc(m_V, false), m_badv(m_badvc.begin(), m_vim),\n        m_colcv(m_V),\n        m_col_bfs(m_V)\n      { }\n\n      /*!\n       * \\return maximum/minimum_{for all cycles C}\n       *         [sum_{e in C} w1(e)] / [sum_{e in C} w2(e)],\n       * or FloatTraits::infinity() if graph has no cycles.\n       */\n      float_t ocr_howard()\n      {\n        construct_policy_graph();\n        int k = 0;\n        float_t mcr = 0;\n        do\n          {\n            mcr = policy_mcr();\n            ++k;\n          }\n        while (try_improve_policy(mcr) && k < 100); //To avoid infinite loop\n\n        const float_t eps_ =  -0.00000001 * cmp_props_t::multiplier;\n        if (m_cmp(mcr, m_bound + eps_))\n          {\n            return FloatTraits::infinity();\n          }\n        else\n          {\n            return  mcr;\n          }\n      }\n      virtual ~mcr_howard() {}\n\n    protected:\n      virtual void store_critical_edge(edge_t ed, critical_cycle_t &cc) {}\n      virtual void store_critical_cycle(critical_cycle_t &cc) {}\n\n    private:\n      /*!\n       * \\return lower/upper bound for the maximal/minimal cycle ratio\n       */\n      float_t mcr_bound()\n      {\n        typename  graph_traits<Graph>::vertex_iterator  vi, vie;\n        typename  graph_traits<Graph>::out_edge_iterator  oei, oeie;\n        float_t cz = (std::numeric_limits<float_t>::max)(); //Closest to zero value\n        float_t s = 0;\n        const float_t eps_ = std::numeric_limits<float_t>::epsilon();\n        for (tie(vi, vie) = vertices(m_g); vi != vie; ++vi)\n          {\n            for (tie(oei, oeie) = out_edges(*vi, m_g); oei != oeie; ++oei)\n              {\n                s += std::abs(m_ew1m[*oei]);\n                float_t a = std::abs(m_ew2m[*oei]);\n                if ( a > eps_ && a < cz)\n                {\n                  cz = a;\n                }\n              }\n          }\n        return  cmp_props_t::multiplier * (s / cz);\n      }\n\n\n      /*!\n       *  Constructs an arbitrary policy graph.\n       */\n      void construct_policy_graph()\n      {\n        m_sink = graph_traits<Graph>().null_vertex();\n        typename  graph_traits<Graph>::vertex_iterator  vi, vie;\n        typename  graph_traits<Graph>::out_edge_iterator  oei, oeie;\n        for ( tie(vi, vie) = vertices(m_g); vi != vie; ++vi )\n          {\n            tie(oei, oeie) = out_edges(*vi, m_g);\n            typename graph_traits<Graph>::out_edge_iterator mei =\n              std::max_element(oei, oeie,\n                               bind(m_cmp,\n                                    bind(&EdgeWeight1::operator[], m_ew1m, _1),\n                                    bind(&EdgeWeight1::operator[], m_ew1m, _2)\n                                    )\n                               );\n            if (mei == oeie)\n              {\n                if (m_sink == graph_traits<Graph>().null_vertex())\n                  {\n                    m_sink = *vi;\n                  }\n                m_badv[*vi] = true;\n                m_inel[m_sink].push_back(*vi);\n              }\n            else\n              {\n                m_inel[target(*mei, m_g)].push_back(*vi);\n                m_policy[*vi] = *mei;\n              }\n          }\n      }\n      /*! Sets the distance value for all vertices \"v\" such that there is\n       * a path from \"v\" to \"sv\". It does \"inverse\" breadth first visit of the policy\n       * graph, starting from the vertex \"sv\".\n       */\n      void mcr_bfv(vertex_t sv, float_t cr, color_map_t c)\n      {\n        boost::queue<vertex_t> Q;\n        c[sv] = my_black;\n        Q.push(sv);\n        while (!Q.empty())\n          {\n            vertex_t v = Q.top(); Q.pop();\n            for (typename pinel_t::const_iterator itr = m_inel[v].begin();\n                 itr != m_inel[v].end(); ++itr)\n              //For all in_edges of the policy graph\n              {\n                if (*itr != sv)\n                  {\n                    if (m_badv[*itr])\n                      {\n                        m_dm[*itr] = m_dm[v] + m_bound - cr;\n                      }\n                    else\n                      {\n                        m_dm[*itr] = m_dm[v] + m_ew1m[m_policy[*itr]] -\n                          m_ew2m[m_policy[*itr]] * cr;\n                      }\n                    c[*itr] = my_black;\n                    Q.push(*itr);\n                  }\n              }\n          }\n      }\n\n      /*!\n       * \\param sv an arbitrary (undiscovered) vertex of the policy graph.\n       * \\return a vertex in the policy graph that belongs to a cycle.\n       * Performs a depth first visit until a cycle edge is found.\n       */\n      vertex_t find_cycle_vertex(vertex_t sv)\n      {\n        vertex_t gv = sv;\n        std::fill(m_colcv.begin(), m_colcv.end(), my_white);\n        color_map_t cm(m_colcv.begin(), m_vim);\n        do\n          {\n            cm[gv] = my_black;\n            if (! m_badv[gv])\n              {\n                gv = target(m_policy[gv], m_g);\n              }\n            else\n              {\n                gv = m_sink;\n              }\n          }\n        while (cm[gv] != my_black);\n        return gv;\n      }\n\n      /*!\n       * \\param sv - vertex that belongs to a cycle in the policy graph.\n       */\n      float_t cycle_ratio(vertex_t sv)\n      {\n        if (sv == m_sink) return m_bound;\n        std::pair<float_t, float_t> sums_(float_t(0), float_t(0));\n        vertex_t v = sv;\n        critical_cycle_t cc;\n        do\n          {\n            store_critical_edge(m_policy[v], cc);\n            sums_.first += m_ew1m[m_policy[v]];\n            sums_.second += m_ew2m[m_policy[v]];\n            v = target(m_policy[v], m_g);\n          }\n        while (v != sv);\n        float_t cr = sums_.first / sums_.second;\n        if ( m_cmp(m_cr, cr) )\n          {\n            m_cr = cr;\n            store_critical_cycle(cc);\n          }\n        return cr;\n      }\n\n      /*!\n       *  Finds the optimal cycle ratio of the policy graph\n       */\n      float_t policy_mcr()\n      {\n        std::fill(m_col_bfs.begin(), m_col_bfs.end(), my_white);\n        color_map_t vcm_ = color_map_t(m_col_bfs.begin(), m_vim);\n        typename graph_traits<Graph>::vertex_iterator uv_itr, vie;\n        tie(uv_itr, vie) = vertices(m_g);\n        float_t mcr = m_bound;\n        while ( (uv_itr = std::find_if(uv_itr, vie,\n                                       bind(std::equal_to<my_color_type>(),\n                                            my_white,\n                                            bind(&color_map_t::operator[], vcm_, _1)\n                                            )\n                                       )\n                 ) != vie )\n          ///While there are undiscovered vertices\n          {\n            vertex_t gv = find_cycle_vertex(*uv_itr);\n            float_t cr = cycle_ratio(gv) ;\n            mcr_bfv(gv, cr, vcm_);\n            if ( m_cmp(mcr, cr) )  mcr = cr;\n            ++uv_itr;\n          }\n        return mcr;\n      }\n\n      /*!\n       * Changes the edge m_policy[s] to the new_edge.\n       */\n      void improve_policy(vertex_t s, edge_t new_edge)\n      {\n        vertex_t t = target(m_policy[s], m_g);\n        typename property_traits<VertexIndexMap>::value_type ti = m_vim[t];\n        m_inelc[ti].erase( std::find(m_inelc[ti].begin(), m_inelc[ti].end(), s));\n        m_policy[s] = new_edge;\n        t = target(new_edge, m_g);\n        m_inel[t].push_back(s); ///Maintain in_edge list\n      }\n\n      /*!\n       * A negative cycle detector.\n       */\n      bool try_improve_policy(float_t cr)\n      {\n        bool improved = false;\n        typename  graph_traits<Graph>::vertex_iterator  vi, vie;\n        typename  graph_traits<Graph>::out_edge_iterator  oei, oeie;\n        const float_t eps_ =  FloatTraits::epsilon();\n        for (tie(vi, vie) = vertices(m_g); vi != vie; ++vi)\n          {\n            if (!m_badv[*vi])\n              {\n                for (tie(oei, oeie) = out_edges(*vi, m_g); oei != oeie; ++oei)\n                  {\n                    vertex_t t = target(*oei, m_g);\n                    //Current distance from *vi to some vertex\n                    float_t dis_ = m_ew1m[*oei] - m_ew2m[*oei] * cr + m_dm[t];\n                    if ( m_cmp(m_dm[*vi] + eps_, dis_) )\n                      {\n                        improve_policy(*vi, *oei);\n                        m_dm[*vi] = dis_;\n                        improved = true;\n                      }\n                  }\n              }\n            else\n              {\n                float_t dis_ = m_bound - cr + m_dm[m_sink];\n                if ( m_cmp(m_dm[*vi] + eps_, dis_) )\n                  {\n                    m_dm[*vi] = dis_;\n                  }\n              }\n          }\n        return improved;\n      }\n    private:\n      const Graph &m_g;\n      VertexIndexMap m_vim;\n      EdgeWeight1 m_ew1m;\n      EdgeWeight2 m_ew2m;\n      comparator_t m_cmp;\n      float_t m_bound; //> The lower/upper bound to the maximal/minimal cycle ratio\n      float_t m_cr; //>The best cycle ratio that has been found so far\n\n      vn_t m_V; //>The number of the vertices in the graph\n      vp_t m_dis; //>Container for the distance map\n      distance_map_t m_dm; //>Distance map\n\n      ve_t m_policyc; //>Container for the policy graph\n      policy_t m_policy; //>The interface for the policy graph\n\n      inedges1_t m_inelc; //>Container fot in edges list\n      inedges_t m_inel; //>Policy graph, input edges list\n\n      std::vector<int> m_badvc;\n      badv_t m_badv; //Marks \"bad\" vertices\n\n      vcol_t m_colcv, m_col_bfs; //Color maps\n      vertex_t m_sink; //To convert any graph to \"good\"\n    };\n\n    /*! \\class mcr_howard1\n  * \\brief Finds optimum cycle raio and a critical cycle\n     */\n    template <typename FloatTraits,\n              typename Graph, typename VertexIndexMap,\n              typename EdgeWeight1, typename EdgeWeight2>\n    class mcr_howard1  : public\n    mcr_howard<FloatTraits, Graph, VertexIndexMap,\n               EdgeWeight1, EdgeWeight2>\n    {\n    public:\n      typedef mcr_howard<FloatTraits, Graph, VertexIndexMap,\n        EdgeWeight1, EdgeWeight2> inhr_t;\n      mcr_howard1(const Graph &g, VertexIndexMap vim,\n        EdgeWeight1 ewm, EdgeWeight2 ew2m) :\n        inhr_t(g, vim, ewm, ew2m)\n      { }\n\n      void get_critical_cycle(typename inhr_t::critical_cycle_t &cc)\n      { return cc.swap(m_cc); }\n\n    protected:\n      void store_critical_edge(typename inhr_t::edge_t ed,\n        typename inhr_t::critical_cycle_t &cc)\n      { cc.push_back(ed); }\n\n      void store_critical_cycle(typename inhr_t::critical_cycle_t &cc)\n      { m_cc.swap(cc); }\n\n    private:\n      typename inhr_t::critical_cycle_t m_cc; //Critical cycle\n    };\n\n    /*!\n     * \\param g a directed multigraph.\n     * \\param vim Vertex Index Map. A map V->[0, num_vertices(g))\n     * \\param ewm Edge weight1 map.\n     * \\param ew2m Edge weight2 map.\n     * \\param pcc  pointer to the critical edges list.\n     * \\return Optimum cycle ratio of g or FloatTraits::infinity() if g has no cycles.\n     */\n    template <typename FT,\n              typename TG, typename TVIM,\n              typename TEW1, typename TEW2,\n              typename EV>\n    typename FT::value_type\n optimum_cycle_ratio(const TG &g, TVIM vim, TEW1 ewm, TEW2 ew2m, EV* pcc)\n    {\n      typedef typename graph_traits<TG>::directed_category DirCat;\n      BOOST_STATIC_ASSERT((is_convertible<DirCat*, directed_tag*>::value == true));\n      function_requires< IncidenceGraphConcept<TG> >();\n      function_requires< VertexListGraphConcept<TG> >();\n      typedef typename graph_traits<TG>::vertex_descriptor Vertex;\n      function_requires< ReadablePropertyMapConcept<TVIM, Vertex> >();\n      typedef typename graph_traits<TG>::edge_descriptor Edge;\n      function_requires< ReadablePropertyMapConcept<TEW1, Edge> >();\n      function_requires< ReadablePropertyMapConcept<TEW2, Edge> >();\n\n      if(pcc == 0) {\n          return detail::mcr_howard<FT,TG, TVIM, TEW1, TEW2>(\n            g, vim, ewm, ew2m\n          ).ocr_howard();\n      }\n\n      detail::mcr_howard1<FT, TG, TVIM, TEW1, TEW2> obj(g, vim, ewm, ew2m);\n      double ocr = obj.ocr_howard();\n      obj.get_critical_cycle(*pcc);\n      return ocr;\n    }\n  } // namespace detail\n\n// Algorithms\n// Maximum Cycle Ratio\n\ntemplate <\n    typename FloatTraits,\n    typename Graph,\n    typename VertexIndexMap,\n    typename EdgeWeight1Map,\n    typename EdgeWeight2Map>\ninline typename FloatTraits::value_type\nmaximum_cycle_ratio(const Graph &g, VertexIndexMap vim, EdgeWeight1Map ew1m,\n                    EdgeWeight2Map ew2m,\n                    std::vector<typename graph_traits<Graph>::edge_descriptor>* pcc = 0,\n                    FloatTraits = FloatTraits())\n{\n    typedef detail::float_wrapper<\n        FloatTraits, detail::max_comparator_props<FloatTraits>\n    > Traits;\n    return detail::optimum_cycle_ratio<Traits>(g, vim, ew1m, ew2m, pcc);\n}\n\ntemplate <\n    typename Graph,\n    typename VertexIndexMap,\n    typename EdgeWeight1Map,\n    typename EdgeWeight2Map>\ninline double\nmaximum_cycle_ratio(const Graph &g, VertexIndexMap vim,\n                    EdgeWeight1Map ew1m, EdgeWeight2Map ew2m,\n                    std::vector<typename graph_traits<Graph>::edge_descriptor>* pcc = 0)\n{ return maximum_cycle_ratio(g, vim, ew1m, ew2m, pcc, mcr_float<>()); }\n\n// Minimum Cycle Ratio\n\ntemplate <\n    typename FloatTraits,\n    typename Graph,\n    typename VertexIndexMap,\n    typename EdgeWeight1Map,\n    typename EdgeWeight2Map>\ntypename FloatTraits::value_type\nminimum_cycle_ratio(const Graph &g, VertexIndexMap vim,\n                    EdgeWeight1Map ew1m, EdgeWeight2Map ew2m,\n                    std::vector<typename graph_traits<Graph>::edge_descriptor> *pcc = 0,\n                    FloatTraits = FloatTraits())\n{\n    typedef detail::float_wrapper<\n        FloatTraits, detail::min_comparator_props<FloatTraits>\n    > Traits;\n    return detail::optimum_cycle_ratio<Traits>(g, vim, ew1m, ew2m, pcc);\n}\n\ntemplate <\n    typename Graph,\n    typename VertexIndexMap,\n    typename EdgeWeight1Map,\n    typename EdgeWeight2Map>\ninline double\nminimum_cycle_ratio(const Graph &g, VertexIndexMap vim,\n                    EdgeWeight1Map ew1m, EdgeWeight2Map ew2m,\n                    std::vector<typename graph_traits<Graph>::edge_descriptor>* pcc = 0)\n{ return minimum_cycle_ratio(g, vim, ew1m, ew2m, pcc, mcr_float<>()); }\n\n// Maximum Cycle Mean\n\ntemplate <\n    typename FloatTraits,\n    typename Graph,\n    typename VertexIndexMap,\n    typename EdgeWeightMap,\n    typename EdgeIndexMap>\ninline typename FloatTraits::value_type\nmaximum_cycle_mean(const Graph &g, VertexIndexMap vim,\n                   EdgeWeightMap ewm, EdgeIndexMap eim,\n                   std::vector<typename graph_traits<Graph>::edge_descriptor>* pcc = 0,\n                   FloatTraits ft = FloatTraits())\n{\n    typedef typename remove_const<\n        typename property_traits<EdgeWeightMap>::value_type\n    >::type Weight;\n    typename std::vector<Weight> ed_w2(boost::num_edges(g), 1);\n    return maximum_cycle_ratio(g, vim, ewm,\n                               make_iterator_property_map(ed_w2.begin(), eim),\n                               pcc, ft);\n}\n\ntemplate <\n    typename Graph,\n    typename VertexIndexMap,\n    typename EdgeWeightMap,\n    typename EdgeIndexMap>\ninline double\nmaximum_cycle_mean(const Graph& g, VertexIndexMap vim,\n                   EdgeWeightMap ewm, EdgeIndexMap eim,\n                   std::vector<typename graph_traits<Graph>::edge_descriptor>* pcc = 0)\n{ return maximum_cycle_mean(g, vim, ewm, eim, pcc, mcr_float<>()); }\n\n// Minimum Cycle Mean\n\ntemplate <\n    typename FloatTraits,\n    typename Graph,\n    typename VertexIndexMap,\n    typename EdgeWeightMap,\n    typename EdgeIndexMap>\ninline typename FloatTraits::value_type\nminimum_cycle_mean(const Graph &g, VertexIndexMap vim,\n                   EdgeWeightMap ewm, EdgeIndexMap eim,\n                   std::vector<typename graph_traits<Graph>::edge_descriptor>* pcc = 0,\n                   FloatTraits ft = FloatTraits())\n{\n    typedef typename remove_const<\n        typename property_traits<EdgeWeightMap>::value_type\n    >::type Weight;\n    typename std::vector<Weight> ed_w2(boost::num_edges(g), 1);\n    return minimum_cycle_ratio(g, vim, ewm,\n                               make_iterator_property_map(ed_w2.begin(), eim),\n                               pcc, ft);\n}\n\ntemplate <\n    typename Graph,\n    typename VertexIndexMap,\n    typename EdgeWeightMap,\n    typename EdgeIndexMap>\ninline double\nminimum_cycle_mean(const Graph &g, VertexIndexMap vim,\n                   EdgeWeightMap ewm, EdgeIndexMap eim,\n                   std::vector<typename graph_traits<Graph>::edge_descriptor>* pcc = 0)\n{ return minimum_cycle_mean(g, vim, ewm, eim, pcc, mcr_float<>()); }\n\n} //namespace boost\n\n#endif\n", "meta": {"hexsha": "709499ff02ae998bf9199ba6994d4c83d90e2799", "size": 21984, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lib/boost/graph/howard_cycle_ratio.hpp", "max_stars_repo_name": "EricBoittier/vina-carb-docker", "max_stars_repo_head_hexsha": "e8730d1ef90395e3d7ed3ad00264702313b0766a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-01-18T20:27:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T03:58:47.000Z", "max_issues_repo_path": "src/lib/boost/graph/howard_cycle_ratio.hpp", "max_issues_repo_name": "EricBoittier/vina-carb-docker", "max_issues_repo_head_hexsha": "e8730d1ef90395e3d7ed3ad00264702313b0766a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2016-11-22T13:14:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T00:56:51.000Z", "max_forks_repo_path": "src/lib/boost/graph/howard_cycle_ratio.hpp", "max_forks_repo_name": "EricBoittier/vina-carb-docker", "max_forks_repo_head_hexsha": "e8730d1ef90395e3d7ed3ad00264702313b0766a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2015-02-03T19:24:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-20T10:59:50.000Z", "avg_line_length": 34.6204724409, "max_line_length": 91, "alphanum_fraction": 0.5838791849, "num_tokens": 5351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.24515028033031291}}
{"text": "/* Author: Yaqi Wang, Texas A&M University, 2009, 2010 */\n\n/*    $Id: step-28.cc 27661 2012-11-21 14:38:52Z bangerth $       */\n/*                                                                */\n/*    Copyright (C) 2009-2012 by the deal.II authors */\n/*                                                                */\n/*    This file is subject to QPL and may not be  distributed     */\n/*    without copyright and license information. Please refer     */\n/*    to the file deal.II/doc/license.html for the  text  and     */\n/*    further information on this license.                        */\n\n// @sect3{Include files}\n\n// We start with a bunch of include files that have already been explained in\n// previous tutorial programs:\n#include <deal.II/base/timer.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/base/function.h>\n#include <deal.II/base/logstream.h>\n#include <deal.II/base/thread_management.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/lac/vector.h>\n#include <deal.II/lac/full_matrix.h>\n#include <deal.II/lac/sparsity_pattern.h>\n#include <deal.II/lac/sparse_matrix.h>\n#include <deal.II/lac/solver_cg.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/constraint_matrix.h>\n#include <deal.II/grid/tria.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/grid/grid_out.h>\n#include <deal.II/grid/grid_generator.h>\n#include <deal.II/grid/tria_accessor.h>\n#include <deal.II/grid/tria_iterator.h>\n#include <deal.II/grid/tria_boundary_lib.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/dofs/dof_accessor.h>\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_q.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/numerics/vector_tools.h>\n#include <deal.II/numerics/matrix_tools.h>\n#include <deal.II/numerics/data_out.h>\n#include <deal.II/numerics/error_estimator.h>\n\n#include <fstream>\n#include <iostream>\n\n#include <deal.II/base/utilities.h>\n\n// We use the next include file to access block vectors which provide us a\n// convenient way to manage solution and right hand side vectors of all energy\n// groups:\n#include <deal.II/lac/block_vector.h>\n\n// This include file is for transferring solutions from one mesh to another\n// different mesh. We use it when we are initializing solutions after each\n// mesh iteration:\n#include <deal.II/numerics/solution_transfer.h>\n\n// When integrating functions defined on one mesh against shape functions\n// defined on a different mesh, we need a function @p get_finest_common_cells\n// (as discussed in the introduction) which is defined in the following header\n// file:\n#include <deal.II/grid/grid_tools.h>\n\n// Here are two more C++ standard headers that we use to define list data\n// types as well as to fine-tune the output we generate:\n#include <list>\n#include <iomanip>\n\n// The last step is as in all previous programs:\nnamespace Step28\n{\n  using namespace dealii;\n\n\n  // @sect3{Material data}\n\n  // First up, we need to define a class that provides material data\n  // (including diffusion coefficients, removal cross sections, scattering\n  // cross sections, fission cross sections and fission spectra) to the main\n  // class.\n  //\n  // The parameter to the constructor determines for how many energy groups we\n  // set up the relevant tables. At present, this program only includes data\n  // for 2 energy groups, but a more sophisticated program may be able to\n  // initialize the data structures for more groups as well, depending on how\n  // many energy groups are selected in the parameter file.\n  //\n  // For each of the different coefficient types, there is one function that\n  // returns the value of this coefficient for a particular energy group (or\n  // combination of energy groups, as for the distribution cross section\n  // $\\chi_g\\nu\\Sigma_{f,g'}$ or scattering cross section $\\Sigma_{s,g'\\to\n  // g}$). In addition to the energy group or groups, these coefficients\n  // depend on the type of fuel or control rod, as explained in the\n  // introduction. The functions therefore take an additional parameter, @p\n  // material_id, that identifies the particular kind of rod. Within this\n  // program, we use <code>n_materials=8</code> different kinds of rods.\n  //\n  // Except for the scattering cross section, each of the coefficients\n  // therefore can be represented as an entry in a two-dimensional array of\n  // floating point values indexed by the energy group number as well as the\n  // material ID. The Table class template is the ideal way to store such\n  // data. Finally, the scattering coefficient depends on both two energy\n  // group indices and therefore needs to be stored in a three-dimensional\n  // array, for which we again use the Table class, where this time the first\n  // template argument (denoting the dimensionality of the array) of course\n  // needs to be three:\n  class MaterialData\n  {\n  public:\n    MaterialData (const unsigned int n_groups);\n\n    double get_diffusion_coefficient (const unsigned int group,\n                                      const unsigned int material_id) const;\n    double get_removal_XS (const unsigned int group,\n                           const unsigned int material_id) const;\n    double get_fission_XS (const unsigned int group,\n                           const unsigned int material_id) const;\n    double get_fission_dist_XS (const unsigned int group_1,\n                                const unsigned int group_2,\n                                const unsigned int material_id) const;\n    double get_scattering_XS (const unsigned int group_1,\n                              const unsigned int group_2,\n                              const unsigned int material_id) const;\n    double get_fission_spectrum (const unsigned int group,\n                                 const unsigned int material_id) const;\n\n  private:\n    const unsigned int n_groups;\n    const unsigned int n_materials;\n\n    Table<2,double> diffusion;\n    Table<2,double> sigma_r;\n    Table<2,double> nu_sigma_f;\n    Table<3,double> sigma_s;\n    Table<2,double> chi;\n  };\n\n  // The constructor of the class is used to initialize all the material data\n  // arrays. It takes the number of energy groups as an argument (an throws an\n  // error if that value is not equal to two, since at presently only data for\n  // two energy groups is implemented; however, using this, the function\n  // remains flexible and extendible into the future). In the member\n  // initialization part at the beginning, it also resizes the arrays to their\n  // correct sizes.\n  //\n  // At present, material data is stored for 8 different types of\n  // material. This, as well, may easily be extended in the future.\n  MaterialData::MaterialData (const unsigned int n_groups)\n    :\n    n_groups (n_groups),\n    n_materials (8),\n    diffusion (n_materials, n_groups),\n    sigma_r (n_materials, n_groups),\n    nu_sigma_f (n_materials, n_groups),\n    sigma_s (n_materials, n_groups, n_groups),\n    chi (n_materials, n_groups)\n  {\n    switch (n_groups)\n      {\n      case 2:\n      {\n        for (unsigned int m=0; m<n_materials; ++m)\n          {\n            diffusion[m][0] = 1.2;\n            diffusion[m][1] = 0.4;\n            chi[m][0]       = 1.0;\n            chi[m][1]       = 0.0;\n            sigma_r[m][0]   = 0.03;\n            for (unsigned int group_1=0; group_1<n_groups; ++group_1)\n              for (unsigned int group_2=0; group_2<n_groups; ++ group_2)\n                sigma_s[m][group_1][group_2]   = 0.0;\n          }\n\n\n        diffusion[5][1]  = 0.2;\n\n        sigma_r[4][0]    = 0.026;\n        sigma_r[5][0]    = 0.051;\n        sigma_r[6][0]    = 0.026;\n        sigma_r[7][0]    = 0.050;\n\n        sigma_r[0][1]    = 0.100;\n        sigma_r[1][1]    = 0.200;\n        sigma_r[2][1]    = 0.250;\n        sigma_r[3][1]    = 0.300;\n        sigma_r[4][1]    = 0.020;\n        sigma_r[5][1]    = 0.040;\n        sigma_r[6][1]    = 0.020;\n        sigma_r[7][1]    = 0.800;\n\n        nu_sigma_f[0][0] = 0.0050;\n        nu_sigma_f[1][0] = 0.0075;\n        nu_sigma_f[2][0] = 0.0075;\n        nu_sigma_f[3][0] = 0.0075;\n        nu_sigma_f[4][0] = 0.000;\n        nu_sigma_f[5][0] = 0.000;\n        nu_sigma_f[6][0] = 1e-7;\n        nu_sigma_f[7][0] = 0.00;\n\n        nu_sigma_f[0][1] = 0.125;\n        nu_sigma_f[1][1] = 0.300;\n        nu_sigma_f[2][1] = 0.375;\n        nu_sigma_f[3][1] = 0.450;\n        nu_sigma_f[4][1] = 0.000;\n        nu_sigma_f[5][1] = 0.000;\n        nu_sigma_f[6][1] = 3e-6;\n        nu_sigma_f[7][1] = 0.00;\n\n        sigma_s[0][0][1] = 0.020;\n        sigma_s[1][0][1] = 0.015;\n        sigma_s[2][0][1] = 0.015;\n        sigma_s[3][0][1] = 0.015;\n        sigma_s[4][0][1] = 0.025;\n        sigma_s[5][0][1] = 0.050;\n        sigma_s[6][0][1] = 0.025;\n        sigma_s[7][0][1] = 0.010;\n\n        break;\n      }\n\n\n      default:\n        Assert (false,\n                ExcMessage (\"Presently, only data for 2 groups is implemented\"));\n      }\n  }\n\n\n  // Next are the functions that return the coefficient values for given\n  // materials and energy groups. All they do is to make sure that the given\n  // arguments are within the allowed ranges, and then look the respective\n  // value up in the corresponding tables:\n  double\n  MaterialData::get_diffusion_coefficient (const unsigned int group,\n                                           const unsigned int material_id) const\n  {\n    Assert (group < n_groups,\n            ExcIndexRange (group, 0, n_groups));\n    Assert (material_id < n_materials,\n            ExcIndexRange (material_id, 0, n_materials));\n\n    return diffusion[material_id][group];\n  }\n\n\n\n  double\n  MaterialData::get_removal_XS (const unsigned int group,\n                                const unsigned int material_id) const\n  {\n    Assert (group < n_groups,\n            ExcIndexRange (group, 0, n_groups));\n    Assert (material_id < n_materials,\n            ExcIndexRange (material_id, 0, n_materials));\n\n    return sigma_r[material_id][group];\n  }\n\n\n  double\n  MaterialData::get_fission_XS (const unsigned int group,\n                                const unsigned int material_id) const\n  {\n    Assert (group < n_groups,\n            ExcIndexRange (group, 0, n_groups));\n    Assert (material_id < n_materials,\n            ExcIndexRange (material_id, 0, n_materials));\n\n    return nu_sigma_f[material_id][group];\n  }\n\n\n\n  double\n  MaterialData::get_scattering_XS (const unsigned int group_1,\n                                   const unsigned int group_2,\n                                   const unsigned int material_id) const\n  {\n    Assert (group_1 < n_groups,\n            ExcIndexRange (group_1, 0, n_groups));\n    Assert (group_2 < n_groups,\n            ExcIndexRange (group_2, 0, n_groups));\n    Assert (material_id < n_materials,\n            ExcIndexRange (material_id, 0, n_materials));\n\n    return sigma_s[material_id][group_1][group_2];\n  }\n\n\n\n  double\n  MaterialData::get_fission_spectrum (const unsigned int group,\n                                      const unsigned int material_id) const\n  {\n    Assert (group < n_groups,\n            ExcIndexRange (group, 0, n_groups));\n    Assert (material_id < n_materials,\n            ExcIndexRange (material_id, 0, n_materials));\n\n    return chi[material_id][group];\n  }\n\n\n  // The function computing the fission distribution cross section is slightly\n  // different, since it computes its value as the product of two other\n  // coefficients. We don't need to check arguments here, since this already\n  // happens when we call the two other functions involved, even though it\n  // would probably not hurt either:\n  double\n  MaterialData::get_fission_dist_XS (const unsigned int group_1,\n                                     const unsigned int group_2,\n                                     const unsigned int material_id) const\n  {\n    return (get_fission_spectrum(group_1, material_id) *\n            get_fission_XS(group_2, material_id));\n  }\n\n\n\n  // @sect3{The <code>EnergyGroup</code> class}\n\n  // The first interesting class is the one that contains everything that is\n  // specific to a single energy group. To group things that belong together\n  // into individual objects, we declare a structure that holds the\n  // Triangulation and DoFHandler objects for the mesh used for a single\n  // energy group, and a number of other objects and member functions that we\n  // will discuss in the following sections.\n  //\n  // The main reason for this class is as follows: for both the forward\n  // problem (with a specified right hand side) as well as for the eigenvalue\n  // problem, one typically solves a sequence of problems for a single energy\n  // group each, rather than the fully coupled problem. This becomes\n  // understandable once one realizes that the system matrix for a single\n  // energy group is symmetric and positive definite (it is simply a diffusion\n  // operator), whereas the matrix for the fully coupled problem is generally\n  // nonsymmetric and not definite. It is also very large and quite full if\n  // more than a few energy groups are involved.\n  //\n  // Let us first look at the equation to solve in the case of an external\n  // right hand side (for the time independent case): @f{eqnarray*} -\\nabla\n  // \\cdot(D_g(x) \\nabla \\phi_g(x)) + \\Sigma_{r,g}(x)\\phi_g(x) =\n  // \\chi_g\\sum_{g'=1}^G\\nu\\Sigma_{f,g'}(x)\\phi_{g'}(x) + \\sum_{g'\\ne\n  // g}\\Sigma_{s,g'\\to g}(x)\\phi_{g'}(x) + s_{\\mathrm{ext},g}(x) @f}\n  //\n  // We would typically solve this equation by moving all the terms on the\n  // right hand side with $g'=g$ to the left hand side, and solving for\n  // $\\phi_g$. Of course, we don't know $\\phi_{g'}$ yet, since the equations\n  // for those variables include right hand side terms involving\n  // $\\phi_g$. What one typically does in such situations is to iterate:\n  // compute @f{eqnarray*} -\\nabla \\cdot(D_g(x) \\nabla \\phi^{(n)}_g(x)) &+&\n  // \\Sigma_{r,g}(x)\\phi^{(n)}_g(x) \\\\ &=&\n  // \\chi_g\\sum_{g'=1}^{g-1}\\nu\\Sigma_{f,g'}(x)\\phi^{(n)}_{g'}(x) +\n  // \\chi_g\\sum_{g'=g}^G\\nu\\Sigma_{f,g'}(x)\\phi^{(n-1)}_{g'}(x) + \\sum_{g'\\ne\n  // g, g'<g}\\Sigma_{s,g'\\to g}(x)\\phi^{(n)}_{g'}(x) + \\sum_{g'\\ne g,\n  // g'>g}\\Sigma_{s,g'\\to g}(x)\\phi^{(n-1)}_{g'}(x) + s_{\\mathrm{ext},g}(x)\n  // @f}\n  //\n  // In other words, we solve the equation one by one, using values for\n  // $\\phi_{g'}$ from the previous iteration $n-1$ if $g'\\ge g$ and already\n  // computed values for $\\phi_{g'}$ from the present iteration if $g'<g$.\n  //\n  // When computing the eigenvalue, we do a very similar iteration, except\n  // that we have no external right hand side and that the solution is scaled\n  // after each iteration as explained in the introduction.\n  //\n  // In either case, these two cases can be treated jointly if all we do is to\n  // equip the following class with these abilities: (i) form the left hand\n  // side matrix, (ii) form the in-group right hand side contribution,\n  // i.e. involving the extraneous source, and (iii) form that contribution to\n  // the right hand side that stems from group $g'$. This class does exactly\n  // these tasks (as well as some book-keeping, such as mesh refinement,\n  // setting up matrices and vectors, etc). On the other hand, the class\n  // itself has no idea how many energy groups there are, and in particular\n  // how they interact, i.e. the decision of how the outer iteration looks\n  // (and consequently whether we solve an eigenvalue or a direct problem) is\n  // left to the NeutronDiffusionProblem class further down below in this\n  // program.\n  //\n  // So let us go through the class and its interface:\n  template <int dim>\n  class EnergyGroup\n  {\n  public:\n\n    // @sect5{Public member functions}\n    //\n    // The class has a good number of public member functions, since its the\n    // way it operates is controlled from the outside, and therefore all\n    // functions that do something significant need to be called from another\n    // class. Let's start off with book-keeping: the class obviously needs to\n    // know which energy group it represents, which material data to use, and\n    // from what coarse grid to start. The constructor takes this information\n    // and initializes the relevant member variables with that (see below).\n    //\n    // Then we also need functions that set up the linear system,\n    // i.e. correctly size the matrix and its sparsity pattern, etc, given a\n    // finite element object to use. The <code>setup_linear_system</code>\n    // function does that. Finally, for this initial block, there are two\n    // functions that return the number of active cells and degrees of freedom\n    // used in this object -- using this, we can make the triangulation and\n    // DoF handler member variables private, and do not have to grant external\n    // use to it, enhancing encapsulation:\n    EnergyGroup (const unsigned int        group,\n                 const MaterialData       &material_data,\n                 const Triangulation<dim> &coarse_grid,\n                 const FiniteElement<dim> &fe);\n\n    void setup_linear_system ();\n\n    unsigned int n_active_cells () const;\n    unsigned int n_dofs () const;\n\n    // Then there are functions that assemble the linear system for each\n    // iteration and the present energy group. Note that the matrix is\n    // independent of the iteration number, so only has to be computed once\n    // for each refinement cycle. The situation is a bit more involved for the\n    // right hand side that has to be updated in each inverse power iteration,\n    // and that is further complicated by the fact that computing it may\n    // involve several different meshes as explained in the introduction. To\n    // make things more flexible with regard to solving the forward or the\n    // eigenvalue problem, we split the computation of the right hand side\n    // into a function that assembles the extraneous source and in-group\n    // contributions (which we will call with a zero function as source terms\n    // for the eigenvalue problem) and one that computes contributions to the\n    // right hand side from another energy group:\n    void assemble_system_matrix ();\n    void assemble_ingroup_rhs (const Function<dim> &extraneous_source);\n    void assemble_cross_group_rhs (const EnergyGroup<dim> &g_prime);\n\n    // Next we need a set of functions that actually compute the solution of a\n    // linear system, and do something with it (such as computing the fission\n    // source contribution mentioned in the introduction, writing graphical\n    // information to an output file, computing error indicators, or actually\n    // refining the grid based on these criteria and thresholds for refinement\n    // and coarsening). All these functions will later be called from the\n    // driver class <code>NeutronDiffusionProblem</code>, or any other class\n    // you may want to implement to solve a problem involving the neutron flux\n    // equations:\n    void   solve ();\n\n    double get_fission_source () const;\n\n    void   output_results (const unsigned int cycle) const;\n\n    void   estimate_errors (Vector<float> &error_indicators) const;\n\n    void   refine_grid (const Vector<float> &error_indicators,\n                        const double         refine_threshold,\n                        const double         coarsen_threshold);\n\n    // @sect5{Public data members}\n    //\n    // As is good practice in object oriented programming, we hide most data\n    // members by making them private. However, we have to grant the class\n    // that drives the process access to the solution vector as well as the\n    // solution of the previous iteration, since in the power iteration, the\n    // solution vector is scaled in every iteration by the present guess of\n    // the eigenvalue we are looking for:\n  public:\n\n    Vector<double> solution;\n    Vector<double> solution_old;\n\n\n    // @sect5{Private data members}\n    //\n    // The rest of the data members are private. Compared to all the previous\n    // tutorial programs, the only new data members are an integer storing\n    // which energy group this object represents, and a reference to the\n    // material data object that this object's constructor gets passed from\n    // the driver class. Likewise, the constructor gets a reference to the\n    // finite element object we are to use.\n    //\n    // Finally, we have to apply boundary values to the linear system in each\n    // iteration, i.e. quite frequently. Rather than interpolating them every\n    // time, we interpolate them once on each new mesh and then store them\n    // along with all the other data of this class:\n  private:\n\n    const unsigned int            group;\n    const MaterialData           &material_data;\n\n    Triangulation<dim>            triangulation;\n    const FiniteElement<dim>     &fe;\n    DoFHandler<dim>               dof_handler;\n\n    SparsityPattern               sparsity_pattern;\n    SparseMatrix<double>          system_matrix;\n\n    Vector<double>                system_rhs;\n\n    std::map<unsigned int,double> boundary_values;\n    ConstraintMatrix              hanging_node_constraints;\n\n\n    // @sect5{Private member functionss}\n    //\n    // There is one private member function in this class. It recursively\n    // walks over cells of two meshes to compute the cross-group right hand\n    // side terms. The algorithm for this is explained in the introduction to\n    // this program. The arguments to this function are a reference to an\n    // object representing the energy group against which we want to integrate\n    // a right hand side term, an iterator to a cell of the mesh used for the\n    // present energy group, an iterator to a corresponding cell on the other\n    // mesh, and the matrix that interpolates the degrees of freedom from the\n    // coarser of the two cells to the finer one:\n  private:\n\n    void\n    assemble_cross_group_rhs_recursive (const EnergyGroup<dim>                        &g_prime,\n                                        const typename DoFHandler<dim>::cell_iterator &cell_g,\n                                        const typename DoFHandler<dim>::cell_iterator &cell_g_prime,\n                                        const FullMatrix<double>                       prolongation_matrix);\n  };\n\n\n  // @sect4{Implementation of the <code>EnergyGroup</code> class}\n\n  // The first few functions of this class are mostly self-explanatory. The\n  // constructor only sets a few data members and creates a copy of the given\n  // triangulation as the base for the triangulation used for this energy\n  // group. The next two functions simply return data from private data\n  // members, thereby enabling us to make these data members private.\n  template <int dim>\n  EnergyGroup<dim>::EnergyGroup (const unsigned int        group,\n                                 const MaterialData       &material_data,\n                                 const Triangulation<dim> &coarse_grid,\n                                 const FiniteElement<dim> &fe)\n    :\n    group (group),\n    material_data (material_data),\n    fe (fe),\n    dof_handler (triangulation)\n  {\n    triangulation.copy_triangulation (coarse_grid);\n    dof_handler.distribute_dofs (fe);\n  }\n\n\n\n  template <int dim>\n  unsigned int\n  EnergyGroup<dim>::n_active_cells () const\n  {\n    return triangulation.n_active_cells ();\n  }\n\n\n\n  template <int dim>\n  unsigned int\n  EnergyGroup<dim>::n_dofs () const\n  {\n    return dof_handler.n_dofs ();\n  }\n\n\n\n  // @sect5{<code>EnergyGroup::setup_linear_system</code>}\n  //\n  // The first \"real\" function is the one that sets up the mesh, matrices,\n  // etc, on the new mesh or after mesh refinement. We use this function to\n  // initialize sparse system matrices, and the right hand side vector. If the\n  // solution vector has never been set before (as indicated by a zero size),\n  // we also initialize it and set it to a default value. We don't do that if\n  // it already has a non-zero size (i.e. this function is called after mesh\n  // refinement) since in that case we want to preserve the solution across\n  // mesh refinement (something we do in the\n  // <code>EnergyGroup::refine_grid</code> function).\n  template <int dim>\n  void\n  EnergyGroup<dim>::setup_linear_system ()\n  {\n    const unsigned int n_dofs = dof_handler.n_dofs();\n\n    hanging_node_constraints.clear ();\n    DoFTools::make_hanging_node_constraints (dof_handler,\n                                             hanging_node_constraints);\n    hanging_node_constraints.close ();\n\n    system_matrix.clear ();\n\n    sparsity_pattern.reinit (n_dofs, n_dofs,\n                             dof_handler.max_couplings_between_dofs());\n    DoFTools::make_sparsity_pattern (dof_handler, sparsity_pattern);\n    hanging_node_constraints.condense (sparsity_pattern);\n    sparsity_pattern.compress ();\n\n    system_matrix.reinit (sparsity_pattern);\n\n    system_rhs.reinit (n_dofs);\n\n    if (solution.size() == 0)\n      {\n        solution.reinit (n_dofs);\n        solution_old.reinit(n_dofs);\n        solution_old = 1.0;\n        solution = solution_old;\n      }\n\n\n    // At the end of this function, we update the list of boundary nodes and\n    // their values, by first clearing this list and the re-interpolating\n    // boundary values (remember that this function is called after first\n    // setting up the mesh, and each time after mesh refinement).\n    //\n    // To understand the code, it is necessary to realize that we create the\n    // mesh using the <code>GridGenerator::subdivided_hyper_rectangle</code>\n    // function (in <code>NeutronDiffusionProblem::initialize_problem</code>)\n    // where we set the last parameter to <code>true</code>. This means that\n    // boundaries of the domain are \"colored\", i.e. the four (or six, in 3d)\n    // sides of the domain are assigned different boundary indicators. As it\n    // turns out, the bottom boundary gets indicator zero, the top one\n    // boundary indicator one, and left and right boundaries get indicators\n    // two and three, respectively.\n    //\n    // In this program, we simulate only one, namely the top right, quarter of\n    // a reactor. That is, we want to interpolate boundary conditions only on\n    // the top and right boundaries, while do nothing on the bottom and left\n    // boundaries (i.e. impose natural, no-flux Neumann boundary\n    // conditions). This is most easily generalized to arbitrary dimension by\n    // saying that we want to interpolate on those boundaries with indicators\n    // 1, 3, ..., which we do in the following loop (note that calls to\n    // <code>VectorTools::interpolate_boundary_values</code> are additive,\n    // i.e. they do not first clear the boundary value map):\n    boundary_values.clear();\n\n    for (unsigned int i=0; i<dim; ++i)\n      VectorTools::interpolate_boundary_values (dof_handler,\n                                                2*i+1,\n                                                ZeroFunction<dim>(),\n                                                boundary_values);\n  }\n\n\n\n  // @sect5{<code>EnergyGroup::assemble_system_matrix</code>}\n  //\n  // Next we need functions assembling the system matrix and right hand\n  // sides. Assembling the matrix is straightforward given the equations\n  // outlined in the introduction as well as what we've seen in previous\n  // example programs. Note the use of <code>cell->material_id()</code> to get\n  // at the kind of material from which a cell is made up of. Note also how we\n  // set the order of the quadrature formula so that it is always appropriate\n  // for the finite element in use.\n  //\n  // Finally, note that since we only assemble the system matrix here, we\n  // can't yet eliminate boundary values (we need the right hand side vector\n  // for this). We defer this to the <code>EnergyGroup::solve</code> function,\n  // at which point all the information is available.\n  template <int dim>\n  void\n  EnergyGroup<dim>::assemble_system_matrix ()\n  {\n    const QGauss<dim>  quadrature_formula(fe.degree + 1);\n\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values    |  update_gradients |\n                             update_JxW_values);\n\n    const unsigned int dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int n_q_points    = quadrature_formula.size();\n\n    FullMatrix<double> cell_matrix (dofs_per_cell, dofs_per_cell);\n    Vector<double>     cell_rhs (dofs_per_cell);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n\n    for (; cell!=endc; ++cell)\n      {\n        cell_matrix = 0;\n\n        fe_values.reinit (cell);\n\n        const double diffusion_coefficient\n          = material_data.get_diffusion_coefficient (group, cell->material_id());\n        const double removal_XS\n          = material_data.get_removal_XS (group,cell->material_id());\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            for (unsigned int j=0; j<dofs_per_cell; ++j)\n              cell_matrix(i,j) += ((diffusion_coefficient *\n                                    fe_values.shape_grad(i,q_point) *\n                                    fe_values.shape_grad(j,q_point)\n                                    +\n                                    removal_XS *\n                                    fe_values.shape_value(i,q_point) *\n                                    fe_values.shape_value(j,q_point))\n                                   *\n                                   fe_values.JxW(q_point));\n\n        cell->get_dof_indices (local_dof_indices);\n\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          for (unsigned int j=0; j<dofs_per_cell; ++j)\n            system_matrix.add (local_dof_indices[i],\n                               local_dof_indices[j],\n                               cell_matrix(i,j));\n      }\n\n    hanging_node_constraints.condense (system_matrix);\n  }\n\n\n\n  // @sect5{<code>EnergyGroup::assemble_ingroup_rhs</code>}\n  //\n  // As explained in the documentation of the <code>EnergyGroup</code> class,\n  // we split assembling the right hand side into two parts: the ingroup and\n  // the cross-group couplings. First, we need a function to assemble the\n  // right hand side of one specific group here, i.e. including an extraneous\n  // source (that we will set to zero for the eigenvalue problem) as well as\n  // the ingroup fission contributions.  (In-group scattering has already been\n  // accounted for with the definition of removal cross section.) The\n  // function's workings are pretty standard as far as assembling right hand\n  // sides go, and therefore does not require more comments except that we\n  // mention that the right hand side vector is set to zero at the beginning\n  // of the function -- something we are not going to do for the cross-group\n  // terms that simply add to the right hand side vector.\n  template <int dim>\n  void EnergyGroup<dim>::assemble_ingroup_rhs (const Function<dim> &extraneous_source)\n  {\n    system_rhs.reinit (dof_handler.n_dofs());\n\n    const QGauss<dim>  quadrature_formula (fe.degree + 1);\n\n    const unsigned int dofs_per_cell = fe.dofs_per_cell;\n    const unsigned int n_q_points = quadrature_formula.size();\n\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values    |  update_quadrature_points  |\n                             update_JxW_values);\n\n    Vector<double>            cell_rhs (dofs_per_cell);\n    std::vector<double>       extraneous_source_values (n_q_points);\n    std::vector<double>       solution_old_values (n_q_points);\n\n    std::vector<unsigned int> local_dof_indices (dofs_per_cell);\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n\n    for (; cell!=endc; ++cell)\n      {\n        cell_rhs = 0;\n\n        fe_values.reinit (cell);\n\n        const double fission_dist_XS\n          = material_data.get_fission_dist_XS (group, group, cell->material_id());\n\n        extraneous_source.value_list (fe_values.get_quadrature_points(),\n                                      extraneous_source_values);\n\n        fe_values.get_function_values (solution_old, solution_old_values);\n\n        cell->get_dof_indices (local_dof_indices);\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<dofs_per_cell; ++i)\n            cell_rhs(i) += ((extraneous_source_values[q_point]\n                             +\n                             fission_dist_XS *\n                             solution_old_values[q_point]) *\n                            fe_values.shape_value(i,q_point) *\n                            fe_values.JxW(q_point));\n\n        for (unsigned int i=0; i<dofs_per_cell; ++i)\n          system_rhs(local_dof_indices[i]) += cell_rhs(i);\n      }\n  }\n\n\n\n  // @sect5{<code>EnergyGroup::assemble_cross_group_rhs</code>}\n  //\n  // The more interesting function for assembling the right hand side vector\n  // for the equation of a single energy group is the one that couples energy\n  // group $g$ and $g'$. As explained in the introduction, we first have to\n  // find the set of cells common to the meshes of the two energy\n  // groups. First we call <code>get_finest_common_cells</code> to obtain this\n  // list of pairs of common cells from both meshes. Both cells in a pair may\n  // not be active but at least one of them is. We then hand each of these\n  // cell pairs off to a function tha computes the right hand side terms\n  // recursively.\n  //\n  // Note that ingroup coupling is handled already before, so we exit the\n  // function early if $g=g'$.\n  template <int dim>\n  void EnergyGroup<dim>::assemble_cross_group_rhs (const EnergyGroup<dim> &g_prime)\n  {\n    if (group == g_prime.group)\n      return;\n\n    const std::list<std::pair<typename DoFHandler<dim>::cell_iterator,\n          typename DoFHandler<dim>::cell_iterator> >\n          cell_list\n          = GridTools::get_finest_common_cells (dof_handler,\n                                                g_prime.dof_handler);\n\n    typename std::list<std::pair<typename DoFHandler<dim>::cell_iterator,\n             typename DoFHandler<dim>::cell_iterator> >\n             ::const_iterator\n             cell_iter = cell_list.begin();\n\n    for (; cell_iter!=cell_list.end(); ++cell_iter)\n      {\n        FullMatrix<double> unit_matrix (fe.dofs_per_cell);\n        for (unsigned int i=0; i<unit_matrix.m(); ++i)\n          unit_matrix(i,i) = 1;\n        assemble_cross_group_rhs_recursive (g_prime,\n                                            cell_iter->first,\n                                            cell_iter->second,\n                                            unit_matrix);\n      }\n  }\n\n\n\n  // @sect5{<code>EnergyGroup::assemble_cross_group_rhs_recursive</code>}\n  //\n  // This is finally the function that handles assembling right hand side\n  // terms on potentially different meshes recursively, using the algorithm\n  // described in the introduction. The function takes a reference to the\n  // object representing energy group $g'$, as well as iterators to\n  // corresponding cells in the meshes for energy groups $g$ and $g'$. At\n  // first, i.e. when this function is called from the one above, these two\n  // cells will be matching cells on two meshes; however, one of the two may\n  // be further refined, and we will call the function recursively with one of\n  // the two iterators replaced by one of the children of the original cell.\n  //\n  // The last argument is the matrix product matrix $B_{c^{(k)}}^T \\cdots\n  // B_{c'}^T B_c^T$ from the introduction that interpolates from the coarser\n  // of the two cells to the finer one. If the two cells match, then this is\n  // the identity matrix -- exactly what we pass to this function initially.\n  //\n  // The function has to consider two cases: that both of the two cells are\n  // not further refined, i.e. have no children, in which case we can finally\n  // assemble the right hand side contributions of this pair of cells; and\n  // that one of the two cells is further refined, in which case we have to\n  // keep recursing by looping over the children of the one cell that is not\n  // active. These two cases will be discussed below:\n  template <int dim>\n  void\n  EnergyGroup<dim>::\n  assemble_cross_group_rhs_recursive (const EnergyGroup<dim>                        &g_prime,\n                                      const typename DoFHandler<dim>::cell_iterator &cell_g,\n                                      const typename DoFHandler<dim>::cell_iterator &cell_g_prime,\n                                      const FullMatrix<double>                       prolongation_matrix)\n  {\n    // The first case is that both cells are no further refined. In that case,\n    // we can assemble the relevant terms (see the introduction). This\n    // involves assembling the mass matrix on the finer of the two cells (in\n    // fact there are two mass matrices with different coefficients, one for\n    // the fission distribution cross section $\\chi_g\\nu\\Sigma_{f,g'}$ and one\n    // for the scattering cross section $\\Sigma_{s,g'\\to g}$). This is\n    // straight forward, but note how we determine which of the two cells is\n    // the finer one by looking at the refinement level of the two cells:\n    if (!cell_g->has_children() && !cell_g_prime->has_children())\n      {\n        const QGauss<dim>  quadrature_formula (fe.degree+1);\n        const unsigned int n_q_points = quadrature_formula.size();\n\n        FEValues<dim> fe_values (fe, quadrature_formula,\n                                 update_values  |  update_JxW_values);\n\n        if (cell_g->level() > cell_g_prime->level())\n          fe_values.reinit (cell_g);\n        else\n          fe_values.reinit (cell_g_prime);\n\n        const double fission_dist_XS\n          = material_data.get_fission_dist_XS (group, g_prime.group,\n                                               cell_g_prime->material_id());\n\n        const double scattering_XS\n          = material_data.get_scattering_XS (g_prime.group, group,\n                                             cell_g_prime->material_id());\n\n        FullMatrix<double>    local_mass_matrix_f (fe.dofs_per_cell,\n                                                   fe.dofs_per_cell);\n        FullMatrix<double>    local_mass_matrix_g (fe.dofs_per_cell,\n                                                   fe.dofs_per_cell);\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          for (unsigned int i=0; i<fe.dofs_per_cell; ++i)\n            for (unsigned int j=0; j<fe.dofs_per_cell; ++j)\n              {\n                local_mass_matrix_f(i,j) += (fission_dist_XS *\n                                             fe_values.shape_value(i,q_point) *\n                                             fe_values.shape_value(j,q_point) *\n                                             fe_values.JxW(q_point));\n                local_mass_matrix_g(i,j) += (scattering_XS *\n                                             fe_values.shape_value(i,q_point) *\n                                             fe_values.shape_value(j,q_point) *\n                                             fe_values.JxW(q_point));\n              }\n\n        // Now we have all the interpolation (prolongation) matrices as well\n        // as local mass matrices, so we only have to form the product @f[\n        // F_i|_{K_{cc'\\cdots c^{(k)}}} = [B_c B_{c'} \\cdots B_{c^{(k)}}\n        // M_{K_{cc'\\cdots c^{(k)}}}]^{ij} \\phi_{g'}^j, @f] or @f[\n        // F_i|_{K_{cc'\\cdots c^{(k)}}} = [(B_c B_{c'} \\cdots B_{c^{(k)}}\n        // M_{K_{cc'\\cdots c^{(k)}}})^T]^{ij} \\phi_{g'}^j, @f] depending on\n        // which of the two cells is the finer. We do this using either the\n        // matrix-vector product provided by the <code>vmult</code> function,\n        // or the product with the transpose matrix using <code>Tvmult</code>.\n        // After doing so, we transfer the result into the global right hand\n        // side vector of energy group $g$.\n        Vector<double>       g_prime_new_values (fe.dofs_per_cell);\n        Vector<double>       g_prime_old_values (fe.dofs_per_cell);\n        cell_g_prime->get_dof_values (g_prime.solution_old, g_prime_old_values);\n        cell_g_prime->get_dof_values (g_prime.solution,     g_prime_new_values);\n\n        Vector<double>       cell_rhs (fe.dofs_per_cell);\n        Vector<double>       tmp (fe.dofs_per_cell);\n\n        if (cell_g->level() > cell_g_prime->level())\n          {\n            prolongation_matrix.vmult (tmp, g_prime_old_values);\n            local_mass_matrix_f.vmult (cell_rhs, tmp);\n\n            prolongation_matrix.vmult (tmp, g_prime_new_values);\n            local_mass_matrix_g.vmult_add (cell_rhs, tmp);\n          }\n        else\n          {\n            local_mass_matrix_f.vmult (tmp, g_prime_old_values);\n            prolongation_matrix.Tvmult (cell_rhs, tmp);\n\n            local_mass_matrix_g.vmult (tmp, g_prime_new_values);\n            prolongation_matrix.Tvmult_add (cell_rhs, tmp);\n          }\n\n        std::vector<unsigned int> local_dof_indices (fe.dofs_per_cell);\n        cell_g->get_dof_indices (local_dof_indices);\n\n        for (unsigned int i=0; i<fe.dofs_per_cell; ++i)\n          system_rhs(local_dof_indices[i]) += cell_rhs(i);\n      }\n\n    // The alternative is that one of the two cells is further refined. In\n    // that case, we have to loop over all the children, multiply the existing\n    // interpolation (prolongation) product of matrices from the left with the\n    // interpolation from the present cell to its child (using the\n    // matrix-matrix multiplication function <code>mmult</code>), and then\n    // hand the result off to this very same function again, but with the cell\n    // that has children replaced by one of its children:\n    else\n      for (unsigned int child=0; child<GeometryInfo<dim>::max_children_per_cell; ++child)\n        {\n          FullMatrix<double>   new_matrix (fe.dofs_per_cell, fe.dofs_per_cell);\n          fe.get_prolongation_matrix(child).mmult (new_matrix,\n                                                   prolongation_matrix);\n\n          if (cell_g->has_children())\n            assemble_cross_group_rhs_recursive (g_prime,\n                                                cell_g->child(child), cell_g_prime,\n                                                new_matrix);\n          else\n            assemble_cross_group_rhs_recursive (g_prime,\n                                                cell_g, cell_g_prime->child(child),\n                                                new_matrix);\n        }\n  }\n\n\n  // @sect5{<code>EnergyGroup::get_fission_source</code>}\n  //\n  // In the (inverse) power iteration, we use the integrated fission source to\n  // update the $k$-eigenvalue. Given its definition, the following function\n  // is essentially self-explanatory:\n  template <int dim>\n  double EnergyGroup<dim>::get_fission_source () const\n  {\n    const QGauss<dim>  quadrature_formula (fe.degree + 1);\n    const unsigned int n_q_points    = quadrature_formula.size();\n\n    FEValues<dim> fe_values (fe, quadrature_formula,\n                             update_values  |  update_JxW_values);\n\n    std::vector<double>       solution_values (n_q_points);\n\n    double fission_source = 0;\n\n    typename DoFHandler<dim>::active_cell_iterator\n    cell = dof_handler.begin_active(),\n    endc = dof_handler.end();\n    for (; cell!=endc; ++cell)\n      {\n        fe_values.reinit (cell);\n\n        const double fission_XS\n          = material_data.get_fission_XS(group, cell->material_id());\n\n        fe_values.get_function_values (solution, solution_values);\n\n        for (unsigned int q_point=0; q_point<n_q_points; ++q_point)\n          fission_source += (fission_XS *\n                             solution_values[q_point] *\n                             fe_values.JxW(q_point));\n      }\n\n    return fission_source;\n  }\n\n\n  // @sect5{<code>EnergyGroup::solve</code>}\n  //\n  // Next a function that solves the linear system assembled before. Things\n  // are pretty much standard, except that we delayed applying boundary values\n  // until we get here, since in all the previous functions we were still\n  // adding up contributions the right hand side vector.\n  template <int dim>\n  void\n  EnergyGroup<dim>::solve ()\n  {\n    hanging_node_constraints.condense (system_rhs);\n    MatrixTools::apply_boundary_values (boundary_values,\n                                        system_matrix,\n                                        solution,\n                                        system_rhs);\n\n    SolverControl           solver_control (system_matrix.m(),\n                                            1e-12*system_rhs.l2_norm());\n    SolverCG<>              cg (solver_control);\n\n    PreconditionSSOR<> preconditioner;\n    preconditioner.initialize(system_matrix, 1.2);\n\n    cg.solve (system_matrix, solution, system_rhs, preconditioner);\n\n    hanging_node_constraints.distribute (solution);\n  }\n\n\n\n  // @sect5{<code>EnergyGroup::estimate_errors</code>}\n  //\n  // Mesh refinement is split into two functions. The first estimates the\n  // error for each cell, normalizes it by the magnitude of the solution, and\n  // returns it in the vector given as an argument. The calling function\n  // collects all error indicators from all energy groups, and computes\n  // thresholds for refining and coarsening cells.\n  template <int dim>\n  void EnergyGroup<dim>::estimate_errors (Vector<float> &error_indicators) const\n  {\n    KellyErrorEstimator<dim>::estimate (dof_handler,\n                                        QGauss<dim-1> (fe.degree + 1),\n                                        typename FunctionMap<dim>::type(),\n                                        solution,\n                                        error_indicators);\n    error_indicators /= solution.linfty_norm();\n  }\n\n\n\n  // @sect5{<code>EnergyGroup::refine_grid</code>}\n  //\n  // The second part is to refine the grid given the error indicators compute\n  // in the previous function and error thresholds above which cells shall be\n  // refined or below which cells shall be coarsened. Note that we do not use\n  // any of the functions in <code>GridRefinement</code> here, but rather set\n  // refinement flags ourselves.\n  //\n  // After setting these flags, we use the SolutionTransfer class to move the\n  // solution vector from the old to the new mesh. The procedure used here is\n  // described in detail in the documentation of that class:\n  template <int dim>\n  void EnergyGroup<dim>::refine_grid (const Vector<float> &error_indicators,\n                                      const double         refine_threshold,\n                                      const double         coarsen_threshold)\n  {\n    typename Triangulation<dim>::active_cell_iterator\n    cell = triangulation.begin_active(),\n    endc = triangulation.end();\n\n    for (unsigned int cell_index=0; cell!=endc; ++cell, ++cell_index)\n      if (error_indicators(cell_index) > refine_threshold)\n        cell->set_refine_flag ();\n      else if (error_indicators(cell_index) < coarsen_threshold)\n        cell->set_coarsen_flag ();\n\n    SolutionTransfer<dim> soltrans(dof_handler);\n\n    triangulation.prepare_coarsening_and_refinement();\n    soltrans.prepare_for_coarsening_and_refinement(solution);\n\n    triangulation.execute_coarsening_and_refinement ();\n    dof_handler.distribute_dofs (fe);\n\n    solution.reinit (dof_handler.n_dofs());\n    soltrans.interpolate(solution_old, solution);\n\n    solution_old.reinit (dof_handler.n_dofs());\n    solution_old = solution;\n  }\n\n\n  // @sect5{<code>EnergyGroup::output_results</code>}\n  //\n  // The last function of this class outputs meshes and solutions after each\n  // mesh iteration. This has been shown many times before. The only thing\n  // worth pointing out is the use of the\n  // <code>Utilities::int_to_string</code> function to convert an integer into\n  // its string representation. The second argument of that function denotes\n  // how many digits we shall use -- if this value was larger than one, then\n  // the number would be padded by leading zeros.\n  template <int dim>\n  void\n  EnergyGroup<dim>::output_results (const unsigned int cycle) const\n  {\n    {\n      const std::string filename = std::string(\"grid-\") +\n                                   Utilities::int_to_string(group,1) +\n                                   \".\" +\n                                   Utilities::int_to_string(cycle,1) +\n                                   \".eps\";\n      std::ofstream output (filename.c_str());\n\n      GridOut grid_out;\n      grid_out.write_eps (triangulation, output);\n    }\n\n    {\n      const std::string filename = std::string(\"solution-\") +\n                                   Utilities::int_to_string(group,1) +\n                                   \".\" +\n                                   Utilities::int_to_string(cycle,1) +\n                                   \".gmv\";\n\n      DataOut<dim> data_out;\n\n      data_out.attach_dof_handler (dof_handler);\n      data_out.add_data_vector (solution, \"solution\");\n      data_out.build_patches ();\n\n      std::ofstream output (filename.c_str());\n      data_out.write_gmv (output);\n    }\n  }\n\n\n\n  // @sect3{The <code>NeutronDiffusionProblem</code> class template}\n\n  // This is the main class of the program, not because it implements all the\n  // functionality (in fact, most of it is implemented in the\n  // <code>EnergyGroup</code> class) but because it contains the driving\n  // algorithm that determines what to compute and when. It is mostly as shown\n  // in many of the other tutorial programs in that it has a public\n  // <code>run</code> function and private functions doing all the rest. In\n  // several places, we have to do something for all energy groups, in which\n  // case we will start threads for each group to let these things run in\n  // parallel if deal.II was configured for multithreading.  For strategies of\n  // parallelization, take a look at the @ref threads module.\n  //\n  // The biggest difference to previous example programs is that we also\n  // declare a nested class that has member variables for all the run-time\n  // parameters that can be passed to the program in an input file. Right now,\n  // these are the number of energy groups, the number of refinement cycles,\n  // the polynomial degree of the finite element to be used, and the tolerance\n  // used to determine when convergence of the inverse power iteration has\n  // occurred. In addition, we have a constructor of this class that sets all\n  // these values to their default values, a function\n  // <code>declare_parameters</code> that described to the ParameterHandler\n  // class already used in step-19 what parameters are accepted in the input\n  // file, and a function <code>get_parameters</code> that can extract the\n  // values of these parameters from a ParameterHandler object.\n  template <int dim>\n  class NeutronDiffusionProblem\n  {\n  public:\n    class Parameters\n    {\n    public:\n      Parameters ();\n\n      static void declare_parameters (ParameterHandler &prm);\n      void get_parameters (ParameterHandler &prm);\n\n      unsigned int n_groups;\n      unsigned int n_refinement_cycles;\n\n      unsigned int fe_degree;\n\n      double convergence_tolerance;\n    };\n\n\n\n    NeutronDiffusionProblem (const Parameters &parameters);\n    ~NeutronDiffusionProblem ();\n\n    void run ();\n\n  private:\n    // @sect5{Private member functions}\n\n    // There are not that many member functions in this class since most of\n    // the functionality has been moved into the <code>EnergyGroup</code>\n    // class and is simply called from the <code>run()</code> member function\n    // of this class. The ones that remain have self-explanatory names:\n    void initialize_problem();\n\n    void refine_grid ();\n\n    double get_total_fission_source () const;\n\n\n    // @sect5{Private member variables}\n\n    // Next, we have a few member variables. In particular, these are (i) a\n    // reference to the parameter object (owned by the main function of this\n    // program, and passed to the constructor of this class), (ii) an object\n    // describing the material parameters for the number of energy groups\n    // requested in the input file, and (iii) the finite element to be used by\n    // all energy groups:\n    const Parameters &parameters;\n    const MaterialData material_data;\n    FE_Q<dim>          fe;\n\n    // Furthermore, we have (iv) the value of the computed eigenvalue at the\n    // present iteration. This is, in fact, the only part of the solution that\n    // is shared between all energy groups -- all other parts of the solution,\n    // such as neutron fluxes are particular to one or the other energy group,\n    // and are therefore stored in objects that describe a single energy\n    // group:\n    double k_eff;\n\n    // Finally, (v), we have an array of pointers to the energy group\n    // objects. The length of this array is, of course, equal to the number of\n    // energy groups specified in the parameter file.\n    std::vector<EnergyGroup<dim>*> energy_groups;\n  };\n\n\n  // @sect4{Implementation of the <code>NeutronDiffusionProblem::Parameters</code> class}\n\n  // Before going on to the implementation of the outer class, we have to\n  // implement the functions of the parameters structure. This is pretty\n  // straightforward and, in fact, looks pretty much the same for all such\n  // parameters classes using the ParameterHandler capabilities. We will\n  // therefore not comment further on this:\n  template <int dim>\n  NeutronDiffusionProblem<dim>::Parameters::Parameters ()\n    :\n    n_groups (2),\n    n_refinement_cycles (5),\n    fe_degree (2),\n    convergence_tolerance (1e-12)\n  {}\n\n\n\n  template <int dim>\n  void\n  NeutronDiffusionProblem<dim>::Parameters::\n  declare_parameters (ParameterHandler &prm)\n  {\n    prm.declare_entry (\"Number of energy groups\", \"2\",\n                       Patterns::Integer (),\n                       \"The number of energy different groups considered\");\n    prm.declare_entry (\"Refinement cycles\", \"5\",\n                       Patterns::Integer (),\n                       \"Number of refinement cycles to be performed\");\n    prm.declare_entry (\"Finite element degree\", \"2\",\n                       Patterns::Integer (),\n                       \"Polynomial degree of the finite element to be used\");\n    prm.declare_entry (\"Power iteration tolerance\", \"1e-12\",\n                       Patterns::Double (),\n                       \"Inner power iterations are stopped when the change in k_eff falls \"\n                       \"below this tolerance\");\n  }\n\n\n\n  template <int dim>\n  void\n  NeutronDiffusionProblem<dim>::Parameters::\n  get_parameters (ParameterHandler &prm)\n  {\n    n_groups              = prm.get_integer (\"Number of energy groups\");\n    n_refinement_cycles   = prm.get_integer (\"Refinement cycles\");\n    fe_degree             = prm.get_integer (\"Finite element degree\");\n    convergence_tolerance = prm.get_double (\"Power iteration tolerance\");\n  }\n\n\n\n\n  // @sect4{Implementation of the <code>NeutronDiffusionProblem</code> class}\n\n  // Now for the <code>NeutronDiffusionProblem</code> class. The constructor\n  // and destructor have nothing of much interest:\n  template <int dim>\n  NeutronDiffusionProblem<dim>::\n  NeutronDiffusionProblem (const Parameters &parameters)\n    :\n    parameters (parameters),\n    material_data (parameters.n_groups),\n    fe (parameters.fe_degree)\n  {}\n\n\n\n  template <int dim>\n  NeutronDiffusionProblem<dim>::~NeutronDiffusionProblem ()\n  {\n    for (unsigned int group=0; group<energy_groups.size(); ++group)\n      delete energy_groups[group];\n\n    energy_groups.resize (0);\n  }\n\n  // @sect5{<code>NeutronDiffusionProblem::initialize_problem</code>}\n  //\n  // The first function of interest is the one that sets up the geometry of\n  // the reactor core. This is described in more detail in the introduction.\n  //\n  // The first part of the function defines geometry data, and then creates a\n  // coarse mesh that has as many cells as there are fuel rods (or pin cells,\n  // for that matter) in that part of the reactor core that we simulate. As\n  // mentioned when interpolating boundary values above, the last parameter to\n  // the <code>GridGenerator::subdivided_hyper_rectangle</code> function\n  // specifies that sides of the domain shall have unique boundary indicators\n  // that will later allow us to determine in a simple way which of the\n  // boundaries have Neumann and which have Dirichlet conditions attached to\n  // them.\n  template <int dim>\n  void NeutronDiffusionProblem<dim>::initialize_problem()\n  {\n    const unsigned int rods_per_assembly_x = 17,\n                       rods_per_assembly_y = 17;\n    const double pin_pitch_x = 1.26,\n                 pin_pitch_y = 1.26;\n    const double assembly_height = 200;\n\n    const unsigned int assemblies_x = 2,\n                       assemblies_y = 2,\n                       assemblies_z = 1;\n\n    const Point<dim> bottom_left = Point<dim>();\n    const Point<dim> upper_right = (dim == 2\n                                    ?\n                                    Point<dim> (assemblies_x*rods_per_assembly_x*pin_pitch_x,\n                                                assemblies_y*rods_per_assembly_y*pin_pitch_y)\n                                    :\n                                    Point<dim> (assemblies_x*rods_per_assembly_x*pin_pitch_x,\n                                                assemblies_y*rods_per_assembly_y*pin_pitch_y,\n                                                assemblies_z*assembly_height));\n\n    std::vector<unsigned int> n_subdivisions;\n    n_subdivisions.push_back (assemblies_x*rods_per_assembly_x);\n    if (dim >= 2)\n      n_subdivisions.push_back (assemblies_y*rods_per_assembly_y);\n    if (dim >= 3)\n      n_subdivisions.push_back (assemblies_z);\n\n    Triangulation<dim> coarse_grid;\n    GridGenerator::subdivided_hyper_rectangle (coarse_grid,\n                                               n_subdivisions,\n                                               bottom_left,\n                                               upper_right,\n                                               true);\n\n\n    // The second part of the function deals with material numbers of pin\n    // cells of each type of assembly. Here, we define four different types of\n    // assembly, for which we describe the arrangement of fuel rods in the\n    // following tables.\n    //\n    // The assemblies described here are taken from the benchmark mentioned in\n    // the introduction and are (in this order): <ol> <li>'UX' Assembly: UO2\n    // fuel assembly with 24 guide tubes and a central Moveable Fission\n    // Chamber <li>'UA' Assembly: UO2 fuel assembly with 24 AIC and a central\n    // Moveable Fission Chamber <li>'PX' Assembly: MOX fuel assembly with 24\n    // guide tubes and a central Moveable Fission Chamber <li>'R' Assembly: a\n    // reflector.  </ol>\n    //\n    // Note that the numbers listed here and taken from the benchmark\n    // description are, in good old Fortran fashion, one-based. We will later\n    // subtract one from each number when assigning materials to individual\n    // cells to convert things into the C-style zero-based indexing.\n    const unsigned int n_assemblies=4;\n    const unsigned int\n    assembly_materials[n_assemblies][rods_per_assembly_x][rods_per_assembly_y]\n    =\n    {\n      {\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 5, 1, 1, 5, 1, 1, 5, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 5, 1, 1, 5, 1, 1, 5, 1, 1, 5, 1, 1, 5, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 5, 1, 1, 5, 1, 1, 7, 1, 1, 5, 1, 1, 5, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 5, 1, 1, 5, 1, 1, 5, 1, 1, 5, 1, 1, 5, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 5, 1, 1, 5, 1, 1, 5, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }\n      },\n      {\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 8, 1, 1, 8, 1, 1, 8, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 8, 1, 1, 8, 1, 1, 8, 1, 1, 8, 1, 1, 8, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 8, 1, 1, 8, 1, 1, 7, 1, 1, 8, 1, 1, 8, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 8, 1, 1, 8, 1, 1, 8, 1, 1, 8, 1, 1, 8, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 8, 1, 1, 8, 1, 1, 8, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },\n        { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }\n      },\n      {\n        { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 },\n        { 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2 },\n        { 2, 3, 3, 3, 3, 5, 3, 3, 5, 3, 3, 5, 3, 3, 3, 3, 2 },\n        { 2, 3, 3, 5, 3, 4, 4, 4, 4, 4, 4, 4, 3, 5, 3, 3, 2 },\n        { 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 2 },\n        { 2, 3, 5, 4, 4, 5, 4, 4, 5, 4, 4, 5, 4, 4, 5, 3, 2 },\n        { 2, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2 },\n        { 2, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2 },\n        { 2, 3, 5, 4, 4, 5, 4, 4, 7, 4, 4, 5, 4, 4, 5, 3, 2 },\n        { 2, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2 },\n        { 2, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2 },\n        { 2, 3, 5, 4, 4, 5, 4, 4, 5, 4, 4, 5, 4, 4, 5, 3, 2 },\n        { 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 2 },\n        { 2, 3, 3, 5, 3, 4, 4, 4, 4, 4, 4, 4, 3, 5, 3, 3, 2 },\n        { 2, 3, 3, 3, 3, 5, 3, 3, 5, 3, 3, 5, 3, 3, 3, 3, 2 },\n        { 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2 },\n        { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }\n      },\n      {\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 },\n        { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 }\n      }\n    };\n\n    // After the description of the materials that make up an assembly, we\n    // have to specify the arrangement of assemblies within the core. We use a\n    // symmetric pattern that in fact only uses the 'UX' and 'PX' assemblies:\n    const unsigned int core[assemblies_x][assemblies_y][assemblies_z]\n    =  {{{0}, {2}}, {{2}, {0}}};\n\n    // We are now in a position to actually set material IDs for each cell. To\n    // this end, we loop over all cells, look at the location of the cell's\n    // center, and determine which assembly and fuel rod this would be in. (We\n    // add a few checks to see that the locations we compute are within the\n    // bounds of the arrays in which we have to look up materials.) At the end\n    // of the loop, we set material identifiers accordingly:\n    for (typename Triangulation<dim>::active_cell_iterator\n         cell = coarse_grid.begin_active();\n         cell!=coarse_grid.end();\n         ++cell)\n      {\n        const Point<dim> cell_center = cell->center();\n\n        const unsigned int tmp_x = int(cell_center[0]/pin_pitch_x);\n        const unsigned int ax = tmp_x/rods_per_assembly_x;\n        const unsigned int cx = tmp_x - ax * rods_per_assembly_x;\n\n        const unsigned tmp_y = int(cell_center[1]/pin_pitch_y);\n        const unsigned int ay = tmp_y/rods_per_assembly_y;\n        const unsigned int cy = tmp_y - ay * rods_per_assembly_y;\n\n        const unsigned int az = (dim == 2\n                                 ?\n                                 0\n                                 :\n                                 int (cell_center[dim-1]/assembly_height));\n\n        Assert (ax < assemblies_x, ExcInternalError());\n        Assert (ay < assemblies_y, ExcInternalError());\n        Assert (az < assemblies_z, ExcInternalError());\n\n        Assert (core[ax][ay][az] < n_assemblies, ExcInternalError());\n\n        Assert (cx < rods_per_assembly_x, ExcInternalError());\n        Assert (cy < rods_per_assembly_y, ExcInternalError());\n\n        cell->set_material_id(assembly_materials[core[ax][ay][az]][cx][cy] - 1);\n      }\n\n    // With the coarse mesh so initialized, we create the appropriate number\n    // of energy group objects and let them initialize their individual meshes\n    // with the coarse mesh generated above:\n    energy_groups.resize (parameters.n_groups);\n    for (unsigned int group=0; group<parameters.n_groups; ++group)\n      energy_groups[group] = new EnergyGroup<dim> (group, material_data,\n                                                   coarse_grid, fe);\n  }\n\n\n  // @sect5{<code>NeutronDiffusionProblem::get_total_fission_source</code>}\n  //\n  // In the eigenvalue computation, we need to calculate total fission neutron\n  // source after each power iteration. The total power then is used to renew\n  // k-effective.\n  //\n  // Since the total fission source is a sum over all the energy groups, and\n  // since each of these sums can be computed independently, we actually do\n  // this in parallel. One of the problems is that the function in the\n  // <code>EnergyGroup</code> class that computes the fission source returns a\n  // value. If we now simply spin off a new thread, we have to later capture\n  // the return value of the function run on that thread. The way this can be\n  // done is to use the return value of the Threads::new_thread function,\n  // which returns an object of type Threads::Thread@<double@> if the function\n  // spawned returns a double. We can then later ask this object for the\n  // returned value (when doing so, the Threads::Thread::return_value function\n  // first waits for the thread to finish if it hasn't done so already).\n  //\n  // The way this function then works is to first spawn one thread for each\n  // energy group we work with, then one-by-one collecting the returned values\n  // of each thread and return the sum.\n  template <int dim>\n  double NeutronDiffusionProblem<dim>::get_total_fission_source () const\n  {\n    std::vector<Threads::Thread<double> > threads;\n    for (unsigned int group=0; group<parameters.n_groups; ++group)\n      threads.push_back (Threads::new_thread (&EnergyGroup<dim>::get_fission_source,\n                                              *energy_groups[group]));\n\n    double fission_source = 0;\n    for (unsigned int group=0; group<parameters.n_groups; ++group)\n      fission_source += threads[group].return_value ();\n\n    return fission_source;\n  }\n\n\n\n\n  // @sect5{<code>NeutronDiffusionProblem::refine_grid</code>}\n  //\n  // The next function lets the individual energy group objects refine their\n  // meshes. Much of this, again, is a task that can be done independently in\n  // parallel: first, let all the energy group objects calculate their error\n  // indicators in parallel, then compute the maximum error indicator over all\n  // energy groups and determine thresholds for refinement and coarsening of\n  // cells, and then ask all the energy groups to refine their meshes\n  // accordingly, again in parallel.\n  template <int dim>\n  void NeutronDiffusionProblem<dim>::refine_grid ()\n  {\n    std::vector<unsigned int> n_cells (parameters.n_groups);\n    for (unsigned int group=0; group<parameters.n_groups; ++group)\n      n_cells[group] = energy_groups[group]->n_active_cells();\n\n    BlockVector<float>  group_error_indicators(n_cells);\n\n    {\n      Threads::ThreadGroup<> threads;\n      for (unsigned int group=0; group<parameters.n_groups; ++group)\n        threads += Threads::new_thread (&EnergyGroup<dim>::estimate_errors,\n                                        *energy_groups[group],\n                                        group_error_indicators.block(group));\n      threads.join_all ();\n    }\n\n    const float max_error         = group_error_indicators.linfty_norm();\n    const float refine_threshold  = 0.3*max_error;\n    const float coarsen_threshold = 0.01*max_error;\n\n    {\n      Threads::ThreadGroup<> threads;\n      for (unsigned int group=0; group<parameters.n_groups; ++group)\n        threads += Threads::new_thread (&EnergyGroup<dim>::refine_grid,\n                                        *energy_groups[group],\n                                        group_error_indicators.block(group),\n                                        refine_threshold,\n                                        coarsen_threshold);\n      threads.join_all ();\n    }\n  }\n\n\n  // @sect5{<code>NeutronDiffusionProblem::run</code>}\n  //\n  // Finally, this is the function where the meat is: iterate on a sequence of\n  // meshes, and on each of them do a power iteration to compute the\n  // eigenvalue.\n  //\n  // Given the description of the algorithm in the introduction, there is\n  // actually not much to comment on:\n  template <int dim>\n  void NeutronDiffusionProblem<dim>::run ()\n  {\n    std::cout << std::setprecision (12) << std::fixed;\n\n    double k_eff_old = k_eff;\n\n    Timer timer;\n    timer.start ();\n\n    for (unsigned int cycle=0; cycle<parameters.n_refinement_cycles; ++cycle)\n      {\n        std::cout << \"Cycle \" << cycle << ':' << std::endl;\n\n        if (cycle == 0)\n          initialize_problem();\n        else\n          {\n            refine_grid ();\n            for (unsigned int group=0; group<parameters.n_groups; ++group)\n              energy_groups[group]->solution *= k_eff;\n          }\n\n        for (unsigned int group=0; group<parameters.n_groups; ++group)\n          energy_groups[group]->setup_linear_system ();\n\n        std::cout << \"   Numbers of active cells:       \";\n        for (unsigned int group=0; group<parameters.n_groups; ++group)\n          std::cout << energy_groups[group]->n_active_cells()\n                    << ' ';\n        std::cout << std::endl;\n        std::cout << \"   Numbers of degrees of freedom: \";\n        for (unsigned int group=0; group<parameters.n_groups; ++group)\n          std::cout << energy_groups[group]->n_dofs()\n                    << ' ';\n        std::cout << std::endl << std::endl;\n\n\n        Threads::ThreadGroup<> threads;\n        for (unsigned int group=0; group<parameters.n_groups; ++group)\n          threads += Threads::new_thread\n                     (&EnergyGroup<dim>::assemble_system_matrix,\n                      *energy_groups[group]);\n        threads.join_all ();\n\n        double error;\n        unsigned int iteration = 1;\n        do\n          {\n            for (unsigned int group=0; group<parameters.n_groups; ++group)\n              {\n                energy_groups[group]->assemble_ingroup_rhs (ZeroFunction<dim>());\n\n                for (unsigned int bgroup=0; bgroup<parameters.n_groups; ++bgroup)\n                  energy_groups[group]->assemble_cross_group_rhs (*energy_groups[bgroup]);\n\n                energy_groups[group]->solve ();\n              }\n\n            k_eff = get_total_fission_source();\n            error = fabs(k_eff-k_eff_old)/fabs(k_eff);\n            std::cout << \"   Iteration \" << iteration\n                      << \": k_eff=\" << k_eff\n                      << std::endl;\n            k_eff_old=k_eff;\n\n            for (unsigned int group=0; group<parameters.n_groups; ++group)\n              {\n                energy_groups[group]->solution_old = energy_groups[group]->solution;\n                energy_groups[group]->solution_old /= k_eff;\n              }\n\n            ++iteration;\n          }\n        while ((error > parameters.convergence_tolerance)\n               &&\n               (iteration < 500));\n\n        for (unsigned int group=0; group<parameters.n_groups; ++group)\n          energy_groups[group]->output_results (cycle);\n\n        std::cout << std::endl;\n        std::cout << \"   Cycle=\" << cycle\n                  << \", n_dofs=\" << energy_groups[0]->n_dofs() + energy_groups[1]->n_dofs()\n                  << \",  k_eff=\" << k_eff\n                  << \", time=\" << timer()\n                  << std::endl;\n\n\n        std::cout << std::endl << std::endl;\n      }\n  }\n}\n\n\n\n// @sect3{The <code>main()</code> function}\n//\n// The last thing in the program in the <code>main()</code> function. The\n// structure is as in most other tutorial programs, with the only exception\n// that we here handle a parameter file.  To this end, we first look at the\n// command line arguments passed to this function: if no input file is\n// specified on the command line, then use \"project.prm\", otherwise take the\n// filename given as the first argument on the command line.\n//\n// With this, we create a ParameterHandler object, let the\n// <code>NeutronDiffusionProblem::Parameters</code> class declare all the\n// parameters it wants to see in the input file (or, take the default values,\n// if nothing is listed in the parameter file), then read the input file, ask\n// the parameters object to extract the values, and finally hand everything\n// off to an object of type <code>NeutronDiffusionProblem</code> for\n// computation of the eigenvalue:\nint main (int argc, char **argv)\n{\n  try\n    {\n      using namespace dealii;\n      using namespace Step28;\n\n      deallog.depth_console (0);\n\n      std::string filename;\n      if (argc < 2)\n        filename = \"project.prm\";\n      else\n        filename = argv[1];\n\n\n      const unsigned int dim = 2;\n\n      ParameterHandler parameter_handler;\n\n      NeutronDiffusionProblem<dim>::Parameters parameters;\n      parameters.declare_parameters (parameter_handler);\n\n      parameter_handler.read_input (filename);\n\n      parameters.get_parameters (parameter_handler);\n\n\n      NeutronDiffusionProblem<dim> neutron_diffusion_problem (parameters);\n      neutron_diffusion_problem.run ();\n    }\n  catch (std::exception &exc)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Exception on processing: \" << std::endl\n                << exc.what() << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n\n      return 1;\n    }\n  catch (...)\n    {\n      std::cerr << std::endl << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      std::cerr << \"Unknown exception!\" << std::endl\n                << \"Aborting!\" << std::endl\n                << \"----------------------------------------------------\"\n                << std::endl;\n      return 1;\n    }\n\n  return 0;\n}\n", "meta": {"hexsha": "f6edf971443d0cd24afebf59e69586e9ca6d2a2c", "size": 75904, "ext": "cc", "lang": "C++", "max_stars_repo_path": "MHD/examples/step-28/step-28.cc", "max_stars_repo_name": "wathen/PhD", "max_stars_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-25T13:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T21:27:30.000Z", "max_issues_repo_path": "MHD/examples/step-28/step-28.cc", "max_issues_repo_name": "wathen/PhD", "max_issues_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MHD/examples/step-28/step-28.cc", "max_forks_repo_name": "wathen/PhD", "max_forks_repo_head_hexsha": "35524f40028541a4d611d8c78574e4cf9ddc3278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-10-28T16:12:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-13T13:59:44.000Z", "avg_line_length": 42.3335192415, "max_line_length": 108, "alphanum_fraction": 0.6156197302, "num_tokens": 20101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2451502803303129}}
{"text": "/*\n For more information, please see: http://software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2015 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n../../src//Core/Algorithms/Math/ConvertMatrixType.cc:\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n */\n \n#include <Core/Algorithms/Base/AlgorithmPreconditions.h>\n#include <Core/Algorithms/BrainStimulator/BiotSavartSolverAlgorithm.h>\n#include <Core/Datatypes/DenseMatrix.h>\n#include <Core/Datatypes/Legacy/Field/Field.h>\n#include <Core/Datatypes/Legacy/Field/VField.h>\n#include <Core/Datatypes/Legacy/Field/VMesh.h>\n#include <Core/Math/MiscMath.h>\n#include <Core/Datatypes/Legacy/Field/FieldInformation.h>\n#include <Core/Thread/Barrier.h>\n#include <Core/Thread/Parallel.h>\n#include <string>\n#include <cassert>\n#include <memory>\n#include <Core/Logging/Log.h>\n#include <boost/lexical_cast.hpp>\n\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::BrainStimulator;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Thread;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun::Core::Logging;\nusing namespace SCIRun;\n\nALGORITHM_PARAMETER_DEF(BrainStimulator, Mesh);\nALGORITHM_PARAMETER_DEF(BrainStimulator, Coil);\nALGORITHM_PARAMETER_DEF(BrainStimulator, VectorBField);\nALGORITHM_PARAMETER_DEF(BrainStimulator, VectorAField);\nALGORITHM_PARAMETER_DEF(BrainStimulator, OutType);\n\n\tclass KernelBase\n\t\t{\n\n\t\tpublic:\n\t\t\tKernelBase(const AlgorithmBase* algo, int t) :\n\t\t\t  ref_cnt(0),\n\t\t\t  algo_(algo),\n\t\t\t  numprocessors_(Parallel::NumCores()),\n\t\t\t  barrier_(\"BSV KernelBase Barrier\", numprocessors_),\n\t\t\t  typeOut(t),\n\t\t\t  matOut(0)\n\t\t\t{\n\t\t\t}\n\t\t\t\n\t\t\tvirtual ~KernelBase()\n\t\t\t{\n\t\t\t}\n\t\t\t\n\t\t\t//! Local entry function, must be implemented by each specific kernel\n\t\t\tvirtual bool Integrate(FieldHandle& mesh, FieldHandle& coil, MatrixHandle& outdata) = 0;\n\n\t\n\t\t\t//! Global reference counting\n\t\t\tint ref_cnt;\n\t\t\t\n\t\tprotected:\n\n\t\t\t//! ref to the executing algorithm context\n\t\t\tconst AlgorithmBase* algo_;\n\t\t\tunsigned int numprocessors_;\n\t\t\t\n\t\t\t//! model miscs.\n\t\t\tVMesh* vmesh;\n\t\t\tVField* vfield;\n\t\t\tsize_type modelSize;\n\n\t\t\t//! coil miscs.\n\t\t\tVMesh* vcoil;\n\t\t\tVField* vcoilField;\n\t\t\tsize_type coilSize;\n\n\t\t\t//! parallel essential primitives \n\t\t\tBarrier barrier_;\n\t\t\tstd::vector<bool> success;\n\t\t\t\n\t\t\t//! output Field\n\t\t\tint typeOut;\n\t\t\tDenseMatrix *matOut;\n\t\t\tMatrixHandle matOutHandle;\n\n\t\t\tbool PreIntegration( FieldHandle& mesh, FieldHandle& coil )\n\t\t\t{\n\t\t\t\t\tthis->vmesh = mesh->vmesh();\n\t\t\t\t\tassert(vmesh);\n\n\t\t\t\t\tthis->vcoil = coil->vmesh();\n\t\t\t\t\tassert(vcoil);\n\n\t\t\t\t\tthis->vfield = mesh->vfield();\n\t\t\t\t\tassert(vfield);\n\n\t\t\t\t\tthis->vcoilField = coil->vfield();\n\t\t\t\t\tassert(vcoilField);\n\n\n\t\t\t\t\tthis->numprocessors_ = Parallel::NumCores();\n\n                    int numproc = Parallel::NumCores();\n\n\t\t\t\t\tif (numproc > 0) \n\t\t\t\t\t{ \n\t\t\t\t\t\tnumprocessors_ = numproc; \n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t#ifdef _DEBUG\n\t\t\t\t\t\t//! DEBUG when we want to test with one CPU only\n\t\t\t\t\t\tnumprocessors_ = 1;\n\t\t\t\t\t#endif\n\t\t\t\t\t\n\t\t\t\t\talgo_->remark(\"number of processors:  \" + boost::lexical_cast<std::string>(this->numprocessors_));\n\t\t\t\t\t\n\t\t\t\t\tsuccess.resize(numprocessors_,true);\n\t\t\t\t\t\n\t\t\t\t\t//! get number of nodes for the model\n\t\t\t\t\tmodelSize = vmesh->num_nodes();\n\t\t\t\t\tassert(modelSize > 0);\n\t\t\t\t\t\n\t\t\t\t\ttry\n\t\t\t\t\t{\t\t\t\n\t\t\t\t\t\tmatOut = new DenseMatrix(static_cast<int>(modelSize),3);\n\t\t\t\t\t\tmatOutHandle = static_cast<MatrixHandle>(matOut);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (...)\n\t\t\t\t\t{\n\t\t\t\t\t\talgo_->error(\"Error alocating output matrix\");\n\t\t\t\t\t\treturn (false);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\treturn (true);\n\t\t\t}\n\t\t\t\n\t\t\tbool PostIntegration( MatrixHandle& outdata )\n\t\t\t{\n\t\t\t\t//! check for error\n\t\t\t\tfor (size_t j=0; j<success.size(); j++)\n\t\t\t\t{\n\t\t\t\t\tif (success[j] == false) return (false);\n\t\t\t\t}\n\n\t\t\t\toutdata = matOutHandle;\n\t\t\t\t\n\t\t\t\treturn (true);\n\t\t\t}\n\t\t};\n\t\t\n\n\tclass PieceWiseKernel : public KernelBase\n\t\t{\n\t\t\tpublic:\n\t\t\t\n\t\t\t\tPieceWiseKernel(const AlgorithmBase* algo, int t ) : KernelBase(algo,t)\n\t\t\t\t{\n\t\t\t\t\t//we keep last calculated step\n\t\t\t\t\t//however if segments lenght varies,\n\t\t\t\t\t//it makes more sense to keep a look-up table of previous steps for given lenght\n\t\t\t\t\tautostep = 0.1;\n\t\t\t\t\textstep = -1.0;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t~PieceWiseKernel()\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//! Complexity O(M*N) ,where M is the number of nodes of the model and N is the numbder of nodes of the coil\n\t\t\t\tvirtual bool Integrate(FieldHandle& mesh, FieldHandle& coil, MatrixHandle& outdata)\n\t\t\t\t{\n\n\t\t\t\t\tif(!PreIntegration(mesh,coil))\n\t\t\t\t\t{\n\t\t\t\t\t\treturn (false);\n\t\t\t\t\t}\n\n\t\t\t\t\tvmesh->synchronize(Mesh::NODES_E | Mesh::EDGES_E);\n\t\t\t\t\t\n\t\t\t\t\tVMesh::Node::array_type enodes;\n\t\t\t\t\tPoint enode1;\n\t\t\t\t\tPoint enode2;\n\t\t\t\t\t\n\t\t\t\t\t//! get numbder of nodes for the coil\n\t\t\t\t\tcoilSize = vcoil->num_nodes();\n\n\t\t\t\t\t//! basic assumption\n\t\t\t\t\tassert(modelSize > 0 && coilSize > 1);\n\t\t\t\t\t\n\t\t\t\t\tcoilNodes.clear();\n\t\t\t\t\tcoilNodes.reserve(coilSize);\n\t\t\t\t\t\n\n\t\t\t\t\tfor(VMesh::Edge::index_type i = 0; i < vcoil->num_edges(); i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tvcoil->get_nodes(enodes,i);\n\t\t\t\t\t\tvcoil->get_point(enode1,enodes[0]);\n\t\t\t\t\t\tvcoil->get_point(enode2,enodes[1]);\n\t\t\t\t\t\tcoilNodes.push_back(Vector(enode1));\n\t\t\t\t\t\tcoilNodes.push_back(Vector(enode2));\n\t\t\t\t\t}\n\n\t\t\t\t\t//! Start the multi threaded\n\t\t\t\t\tParallel::RunTasks([this](int i) { ParallelKernel(i); }, numprocessors_);\n\t\t\t\t\t\n\t\t\t\t\treturn PostIntegration(outdata);\n\t\t\t\t}\n\n\t\t\t\tvoid SetIntegrationStep(double step)\n\t\t\t\t{\n\t\t\t\t\tassert(step >= 0.0);\n\t\t\t\t\textstep = step;\n\t\t\t\t}\n                \n\t\t\t\tdouble GetIntegrationStep() const\n\t\t\t\t{\n\t\t\t\t\treturn extstep;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\n\t\t\tprivate:\n\n\t\t\t\t//! integration step, will auto adapt\n\t\t\t\tdouble autostep;\n\n\t\t\t\t//! integration step, externally provided\n\t\t\t\tdouble extstep;\n\n\t\t\t\t//! keep nodes on the coil cached\n\t\t\t\tstd::vector<Vector> coilNodes;\n\t\t\t\t\n\t\t\t\t//! execute in parallel\n\t\t\t\tvoid ParallelKernel(int proc_num)\n\t\t\t\t{\n\n\t\t\t\t\tassert(proc_num >= 0);\n\n\t\t\t\t\tint cnt = 0;\n\t\t\t\t\tdouble current = 1.0; \n\t\t\t\t\tPoint modelNode;\n\n\t\t\t\t\tconst index_type begins = (modelSize * proc_num) / numprocessors_;\n\t\t\t\t\tconst index_type ends  = (modelSize * (proc_num+1)) / numprocessors_;\n\n\t\t\t\t\tassert( begins <= ends );\n\n\t\t\t\t\t//! buffer of points used for integration\n\t\t\t\t\tstd::vector<Vector> integrPoints;\n\t\t\t\t\tintegrPoints.reserve(256);\n\n\t\t\t\t\t//! keep previous step length\n\t\t\t\t\t//! used for optimization purpose\n\t\t\t\t\tdouble prevSegLen = 123456789.12345678;\n\n\t\t\t\t\t//! number of integration points\n\t\t\t\t\tint nips = 0;\n\t\t\t\t\tindex_type helpme=0;\n\n\t\t\t\t\ttry{\n\n\t\t\t\t\t\tfor(index_type iM = begins; \n\t\t\t\t\t\t\tiM < ends; \n\t\t\t\t\t\t\tiM++)\n\t\t\t\t\t\t{      \n\t\t\t\t\t\t        helpme++;\n\t\t\t\t\t\t\tvmesh->get_node(modelNode,iM); \n\n\t\t\t\t\t\t\t// result\n\t\t\t\t\t\t\tVector F;\n\n\t\t\t\t\t\t\tfor( size_t iC0 = 0, iC1 =1, iCV = 0; \n\t\t\t\t\t\t\t\tiC0 < coilNodes.size(); \n\t\t\t\t\t\t\t\tiC0+=2, iC1+=2, iCV++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvcoilField->get_value(current,iCV);\n\n\t\t\t\t\t\t\t\tcurrent = current == 0.0 ? 1.0 : current;\n\n\t\t\t\t\t\t\t\tVector coilNodeThis;\n\t\t\t\t\t\t\t\tVector coilNodeNext;\n\n\t\t\t\t\t\t\t\tif(current >= 0.0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcoilNodeThis = coilNodes[iC0];\n\t\t\t\t\t\t\t\t\tcoilNodeNext = coilNodes[iC1];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcoilNodeThis = coilNodes[iC1];\n\t\t\t\t\t\t\t\t\tcoilNodeNext = coilNodes[iC0];\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t//! Length of the curve element\n\t\t\t\t\t\t\t\tVector diffNodes = coilNodeNext - coilNodeThis;\n\t\t\t\t\t\t\t\tdouble newSegLen = diffNodes.length();\n\n\t\t\t\t\t\t\t\t//first check if externally suplied integration step is available and use it\n\t\t\t\t\t\t\t\tif(extstep > 0)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tnips = newSegLen / extstep;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//! optimization\n\t\t\t\t\t\t\t\t\t//! only rexompute integration step only if segment length changes\n\t\t\t\t\t\t\t\t\tif( Abs(prevSegLen - newSegLen ) > 0.00000001 )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tprevSegLen = newSegLen;\n\n\t\t\t\t\t\t\t\t\t\t//auto adaptive integration step calculation\n\t\t\t\t\t\t\t\t\t\tnips =  AdjustNumberOfIntegrationPoints(newSegLen);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif( nips < 3 )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\talgo_->warning(\"integration step too big\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tintegrPoints.clear();\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t//! curve segment discretization\n\t\t\t\t\t\t\t\tfor(int iip = 0; iip < nips; iip++)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdouble interpolant = static_cast<double>(iip) / static_cast<double>(nips);\n\t\t\t\t\t\t\t\t\tVector v = Interpolate( coilNodeThis, coilNodeNext, interpolant );\n\t\t\t\t\t\t\t\t\tintegrPoints.push_back( v );\n\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\t//! integration step over line segment\t\t\t\t\n\t\t\t\t\t\t\t\tfor(int iip = 0; iip < nips -1; iip++)\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//! Vector connecting the infinitesimal curve-element\t\t\t\n\t\t\t\t\t\t\t\t\tVector Rxyz = (integrPoints[iip] + integrPoints[iip+1] ) / 2  - Vector(modelNode);\n\n\t\t\t\t\t\t\t\t\t//! Infinitesimal curve-element components\n\t\t\t\t\t\t\t\t\tVector dLxyz = integrPoints[iip+1] - integrPoints[iip];\n\n\t\t\t\t\t\t\t\t\tdouble Rn = Rxyz.length();\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t//! check for distance between coil and model close to zero\n\t\t\t\t\t\t\t\t\t//! it might cause numerical stability issues with respect to the cross-product\n\t\t\t\t\t\t\t\t\tif(Rn < 0.00001)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\talgo_->warning(\"coil<->model distance approaching zero!\");\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif(typeOut == 1)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//! Biot-Savart Magnetic Field\n\t\t\t\t\t\t\t\t\t\tF +=  1.0e-7 * Cross( Rxyz, dLxyz ) * ( Abs(current) / (Rn*Rn*Rn) );\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif(typeOut == 2)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t//! Biot-Savart Magnetic Vector Potential Field\n\t\t\t\t\t\t\t\t\t\tF += 1.0e-7 * dLxyz * ( Abs(current) / (Rn) );\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tmatOut->put(iM,0, F[0]);\n\t\t\t\t\t\t\tmatOut->put(iM,1, F[1]);\n\t\t\t\t\t\t\tmatOut->put(iM,2, F[2]);\n\n\t\t\t\t\t\t\t//! progress reporter\n\t\t\t\t\t\t\tif (proc_num == 0) \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcnt++;\n\t\t\t\t\t\t\t\tif (cnt == 200) \n\t\t\t\t\t\t\t\t{ \n\t\t\t\t\t\t\t\t\tcnt = 0; \n\t\t\t\t\t\t\t\t\talgo_->update_progress(iM/(ends-begins)); \n\t\t\t\t\t\t                  /// The progress bar update does not work ... and it also counts to iM/2 in other classes strange!\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsuccess[proc_num] = true;\n\t\t\t\t\t}\n\t\t\t\t\tcatch (...)\n\t\t\t\t\t{\n\t\t\t\t\t\talgo_->error(std::string(\"PieceWiseKernel crashed while integrating\"));\n\t\t\t\t\t\tsuccess[proc_num] = false;\n\t\t\t\t\t}\n\t\t\t  \n\t\t\t\t\t//! check point\n\t\t\t\t\tbarrier_.wait();\n\n\t\t\t\t\t// Bail out if one of the processes failed\n\t\t\t\t\tfor (size_t q=0; q<numprocessors_;q++) \n\t\t\t\t\t\tif (success[q] == false) return;\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t//! Auto adjust accuracy of integration\n\t\t\t\tint AdjustNumberOfIntegrationPoints(double len)\n\t\t\t\t{\n\t\t\t\t\t//assert(step < len);\n\t\t\t\t\t\n\t\t\t\t\tint minNP = 100;//more than 1 for sure\n\t\t\t\t\tint maxNP = 200;//no more than 1000\n\t\t\t\t\tint NP = 0;\n\t\t\t\t\tbool over = false;\n\t\t\t\t\tbool under = false;\n\n\t\t\t\t\tdo\n\t\t\t\t\t{\n\t\t\t\t\t\tNP = ceil( len / autostep );\n\n\t\t\t\t\t\tunder = NP < minNP ? true : false;\n\t\t\t\t\t\tover = NP > maxNP ? true : false; \n\n\t\t\t\t\t\tif(under) autostep *= 0.5;\n\t\t\t\t\t\tif(over) autostep *= 1.5;\n\n\t\t\t\t\t}while( under || over );\n\n\t\t\t\t\treturn NP;\n\t\t\t\t}\n\t\t\t\n\t\t};\n\n//! TODO\n\t\tclass VolumetricKernel : public KernelBase\n\t\t{\n\t\t\tpublic:\n\t\t\t\n\t\t\t\tVolumetricKernel(const AlgorithmBase* algo, int t) : KernelBase(algo,t)\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t~VolumetricKernel()\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvirtual bool Integrate(FieldHandle& mesh, FieldHandle& coil, MatrixHandle& outdata)\n\t\t\t\t{\n\t\t\t\t\tif(!PreIntegration(mesh,coil))\n\t\t\t\t\t{\n\t\t\t\t\t\treturn (false);\n\t\t\t\t\t}\n\t\t\t\t\t\n\n\t\t\t\t\t//! get numbder of nodes for the coil\n\t\t\t\t\tcoilSize = vcoil->num_elems();\n\n\t\t\t\t\t//! basic assumption\n\t\t\t\t\tassert(modelSize > 0 && coilSize > 1);\n\t\t\t\t\t\n\t\t\t\t\tvmesh->synchronize(Mesh::NODES_E | Mesh::EDGES_E);\t\t\t\t\t\n\n\t\t\t\t\t//! Start the multi threaded\n\t\t\t\t\tParallel::RunTasks([this](int i) { ParallelKernel(i); }, numprocessors_);\n\t\t\t\t\t\n\t\t\t\t\treturn PostIntegration(outdata);\n\t\t\t\t}\n\t\t\t\t\n\t\t\tprivate:\n\t\t\t\t\n\t\t\t\t//! execute in parallel\n\t\t\t\tvoid ParallelKernel(int proc_num)\n\t\t\t\t{\n\t\t\t\t\tassert(proc_num >= 0);\n\n\t\t\t\t\tint cnt = 0;\n\t\t\t\t\tPoint modelNode;\n\t\t\t\t\tPoint coilCenter;\n\t\t\t\t\tVector current;\n\t\t\t\t\t\n\t\t\t\t\tconst VMesh::Node::index_type begins = (modelSize * proc_num) / numprocessors_;\n\t\t\t\t\tconst VMesh::Node::index_type ends  = (modelSize * (proc_num+1)) / numprocessors_;\n\n\t\t\t\t\tassert( begins <= ends );\n\n\t\t\t\t\ttry{\n\n\t\t\t\t\t\tfor(VMesh::Node::index_type iM = begins; iM < ends;\tiM++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvmesh->get_node(modelNode,iM); \n\n\t\t\t\t\t\t\t//! accumulatedresult\n\t\t\t\t\t\t\tVector F;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tVector R;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdouble evol = 0.0;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdouble Rl;\n\n\t\t\t\t\t\t\tfor(VMesh::Elem::index_type  iC = 0; iC < coilSize; iC++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvcoilField->get_value(current,iC);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvcoilField->get_center(coilCenter, iC);//auto resolve based on basis_order\n\n\t\t\t\t\t\t\t\tevol = vcoil->get_volume(iC);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tR = coilCenter - modelNode;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tRl = R.length();\n\n\t\t\t\t\t\t\t\tif(typeOut == 1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//! Biot-Savart Magnetic Field\t\n\t\t\t\t\t\t\t\t\tF += Cross ( current , R ) * ( evol / (4.0 * M_PI * Rl) );\n\t\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(typeOut == 2)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//! Biot-Savart Magnetic Vector Potential Field\n\t\t\t\t\t\t\t\t\tF += current * ( evol / (4.0 * M_PI * Rl) );\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tmatOut->put(iM,0, F[0]);\n\t\t\t\t\t\t\tmatOut->put(iM,1, F[1]);\n\t\t\t\t\t\t\tmatOut->put(iM,2, F[2]);\n\n\t\t\t\t\t\t\t//! progress reporter\n\t\t\t\t\t\t\tif (proc_num == 0) \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcnt++;\n\t\t\t\t\t\t\t\tif (cnt == 200) \n\t\t\t\t\t\t\t\t{ \n\t\t\t\t\t\t\t\t\tcnt = 0; \n\t\t\t\t\t\t\t\t\talgo_->update_progress(iM/2*(begins-ends)); \n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsuccess[proc_num] = true;\n\t\t\t\t\t}\n\t\t\t\t\tcatch (...)\n\t\t\t\t\t{\n\t\t\t\t\t\talgo_->error(std::string(\"VolumetricKernel crashed while integrating\"));\n\t\t\t\t\t\tsuccess[proc_num] = false;\n\t\t\t\t\t}\n\t\t\t  \n\t\t\t\t\t//! check point\n\t\t\t\t\tbarrier_.wait();\n\n\t\t\t\t\t// Bail out if one of the processes failed\n\t\t\t\t\tfor (size_t q=0; q<numprocessors_;q++) \n\t\t\t\t\t\tif (success[q] == false) return;\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t};\n\t\t\n\n\t\t//! Magnetic Dipoles solver\n\t\tclass DipolesKernel : public KernelBase\n\t\t{\n\t\t\tpublic:\n\t\t\t\n\t\t\t\tDipolesKernel(const AlgorithmBase* algo, int t) : KernelBase(algo,t)\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t~DipolesKernel()\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tvirtual bool Integrate(FieldHandle& mesh, FieldHandle& coil, MatrixHandle& outdata)\n\t\t\t\t{\n\t\t\t\t\tif(!PreIntegration(mesh,coil))\n\t\t\t\t\t{\n\t\t\t\t\t\treturn (false);\n\t\t\t\t\t}\n\n\t\t\t\t\t//! get numbder of nodes for the coil\n\t\t\t\t\tcoilSize = vcoil->num_elems();\n\n\t\t\t\t\t//! basic assumption\n\t\t\t\t\tassert(modelSize > 0 && coilSize > 1);\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t//needed?\n\t\t\t\t\tvmesh->synchronize(Mesh::NODES_E | Mesh::EDGES_E);\n\t\t\t\t\t\t\t\t\t\t\n\n\t\t\t\t\t//! Start the multi threaded\n\t\t\t\t\tParallel::RunTasks([this](int i) { ParallelKernel(i); }, numprocessors_);\n\t\t\t\t\t\n\t\t\t\t\treturn PostIntegration(outdata);\n\t\t\t\t}\n\t\t\t\t\n\t\t\tprivate:\n\t\t\t\t\n\t\t\t\t//! execute in parallel\n\t\t\t\tvoid ParallelKernel(int proc_num)\n\t\t\t\t{\n\t\t\t\t\tassert(proc_num >= 0);\n\n\t\t\t\t\tint cnt = 0;\n\t\t\t\t\tPoint modelNode;\n\t\t\t\t\tPoint dipoleLocation;\n\t\t\t\t\tVector dipoleMoment;\n\t\t\t\t\t\n\t\t\t\t\tconst VMesh::Node::index_type begins = (modelSize * proc_num) / numprocessors_;\n\t\t\t\t\tconst VMesh::Node::index_type ends  = (modelSize * (proc_num+1)) / numprocessors_;\n\n\t\t\t\t\tassert( begins <= ends );\n\n\t\t\t\t\ttry{\n\n\n\t\t\t\t\t\tfor(VMesh::Node::index_type iM = begins; iM < ends;\tiM++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvmesh->get_node(modelNode,iM); \n\n\t\t\t\t\t\t\t//! accumulated result\n\t\t\t\t\t\t\tVector F;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tVector R;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tdouble Rl;\n\n\t\t\t\t\t\t\tfor(VMesh::Elem::index_type  iC = 0; iC < coilSize; iC++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvcoilField->get_value(dipoleMoment,iC);\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvcoilField->get_center(dipoleLocation, iC);//auto resolve based on basis_order\n\n\t\t\t\t\t\t\t\tR = dipoleLocation - modelNode;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tRl = R.length();\n\n\t\t\t\t\t\t\t\tif(typeOut == 1)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//! Biot-Savart Magnetic Field\n\t\t\t\t\t\t\t\t\tF += 1.0e-7 * ( 3 * R * Dot ( dipoleMoment, R ) / (Rl*Rl*Rl*Rl*Rl) - dipoleMoment / (Rl*Rl*Rl) ) ; \n\t\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tif(typeOut == 2)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t//! Biot-Savart Magnetic Vector Potential Field\n\t\t\t\t\t\t\t\t\tF += 1.0e-7 * Cross ( dipoleMoment , R ) / (Rl*Rl*Rl) ;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tmatOut->put(iM,0, F[0]);\n\t\t\t\t\t\t\tmatOut->put(iM,1, F[1]);\n\t\t\t\t\t\t\tmatOut->put(iM,2, F[2]);\n\n\t\t\t\t\t\t\t//! progress reporter\n\t\t\t\t\t\t\tif (proc_num == 0) \n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcnt++;\n\t\t\t\t\t\t\t\tif (cnt == 200) \n\t\t\t\t\t\t\t\t{ \n\t\t\t\t\t\t\t\t\tcnt = 0; \n\t\t\t\t\t\t\t\t\talgo_->update_progress(iM/2*(begins-ends)); \n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} \n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tsuccess[proc_num] = true;\n\t\t\t\t\t}\n\t\t\t\t\tcatch (...)\n\t\t\t\t\t{\n\t\t\t\t\t\talgo_->error(std::string(\"DipoleKernel crashed while integrating\"));\n\t\t\t\t\t\tsuccess[proc_num] = false;\n\t\t\t\t\t}\n\t\t\t  \n\t\t\t\t\t//! check point\n\t\t\t\t\tbarrier_.wait();\n\n\t\t\t\t\t// Bail out if one of the processes failed\n\t\t\t\t\tfor (size_t q=0; q<numprocessors_;q++) \n\t\t\t\t\t\tif (success[q] == false) return;\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t};\n\t\nbool BiotSavartSolverAlgorithm::run(FieldHandle mesh, FieldHandle coil, MatrixHandle &outdata, int outtype) const\n{\n  if (!mesh)\n  {\n    error(\"No input domain field\");\n    return (false);\n  }\n    \n  if (!coil)\n  {\n    error(\"No input coil source field\");\n    return (false);\n  }\n  \n  if (coil->vfield()->basis_order()  == -1)\n  {\n   error(\"Need data on coil mesh.\");\n   return (false);\n  }\n\t  \n  if( coil->vmesh()->is_curvemesh() )\n  {\n    if(coil->vfield()->is_constantdata() && coil->vfield()->is_scalar())\n    {\n      auto pwk = std::unique_ptr<KernelBase>(new PieceWiseKernel(this, outtype));\n      //pwk->SetIntegrationStep(this->istep);\n      if( !pwk->Integrate(mesh,coil,outdata) )\n      {\n       error(\"Aborted during integration\");\n       return (false);\n      }\n    }\n    else\n    {\n      error(\"Curve mesh expected with constant scalar data.\");\n      return (false); \n    }\n  }\n  else if(coil->vmesh()->is_pointcloudmesh())\n  {\n   if((coil->vfield()->is_lineardata() || coil->vfield()->is_constantdata() ) && coil->vfield()->is_vector())\n   {\n    auto dp = std::unique_ptr<KernelBase>(new DipolesKernel(this, outtype));\n    if( !dp->Integrate(mesh,coil,outdata) )\n      {\n       error(\"Aborted during integration\");\n       return (false);\n      }\n   }\n   else\n   {\n    error(\"Pointcloud expected with linear vector data.\");\n    return (false);\n   }\n  }\n  else if( coil->vmesh()->is_volume() )\n  {\n   if(  coil->vfield()->is_constantdata() && coil->vfield()->is_vector() )\n   {\n   auto vp = std::unique_ptr<KernelBase>(new VolumetricKernel(this, outtype));\n   if( !vp->Integrate(mesh,coil,outdata) )\n      {\n       error(\"Aborted during integration\");\n       return (false);\n      }\n   }\n   else\n   { \n    error(\"Volumetric mesh expected with constant vector data.\");\n    return (false);\n   }\n  }\n  else\n  {\n   error(\"Unsupported mesh type! Only curve or volumetric.\");\n   return (false);\n  }\n  \n  return (true);\n}\n\nAlgorithmOutput BiotSavartSolverAlgorithm::run(const AlgorithmInput& input) const\n{\n AlgorithmOutput output;\n \n auto mesh = input.get<Field>(Parameters::Mesh);\n auto coil = input.get<Field>(Parameters::Coil);\n\n MatrixHandle outdata1,outdata2;\n \n auto oports = get(Parameters::OutType).toInt();\n \n if (oports==3) //both are output ports\n {\n  if(!run(mesh, coil, outdata1, 1))\n  {\n    error(\"Error: Algorithm of BiotSavartSolver failed.\");\n  }\n  output[Parameters::VectorBField] = outdata1;\n  \n  if(!run(mesh, coil, outdata2, 2))\n  {\n    error(\"Error: Algorithm of BiotSavartSolver failed.\");\n  }\n  output[Parameters::VectorAField] = outdata2;\n  \n  return output;\n } else\n {\n  if(oports==1)\n  {\n   if(!run(mesh, coil, outdata1, oports))\n   {\n    error(\"Error: Algorithm of BiotSavartSolver failed.\"); \n   }\n   output[Parameters::VectorBField] = outdata1;\n  } else\n  if (oports==2)\n  {\n   if(!run(mesh, coil, outdata2, oports))\n   {\n    error(\"Error: Algorithm of BiotSavartSolver failed.\"); \n   }\n   output[Parameters::VectorAField] = outdata2;\n  }\n }\n\n return output;\n}\n", "meta": {"hexsha": "9ee6dd2c569291718ec2f39859f2077007b5c82c", "size": 20402, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Core/Algorithms/BrainStimulator/BiotSavartSolverAlgorithm.cc", "max_stars_repo_name": "Nahusa/SCIRun", "max_stars_repo_head_hexsha": "c54e714d4c7e956d053597cf194e07616e28a498", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T06:00:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T06:00:15.000Z", "max_issues_repo_path": "src/Core/Algorithms/BrainStimulator/BiotSavartSolverAlgorithm.cc", "max_issues_repo_name": "manual123/SCIRun", "max_issues_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Core/Algorithms/BrainStimulator/BiotSavartSolverAlgorithm.cc", "max_forks_repo_name": "manual123/SCIRun", "max_forks_repo_head_hexsha": "3816b1dc4ebd0c5bd4539b7e50e08592acdac903", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4628297362, "max_line_length": 122, "alphanum_fraction": 0.5865111264, "num_tokens": 5648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24512060080581896}}
{"text": "#include <Rcpp.h>\n\n//[[Rcpp::depends(RcppEigen)]]\n#include <RcppEigen.h>\n\n#include \"experimentalSetup.hpp\"\n#include \"individual.hpp\"\n#include \"encodingScheme.hpp\"\n#include \"logLikelihoods.hpp\"\n#include \"estimatePoissonGammaParameters.hpp\"\n\n#include \"AuxiliaryFunctions.hpp\"\n#include <boost/math/special_functions/sign.hpp>\n#include <boost/math/special_functions/factorials.hpp>\n\nIndividual::Individual()\n{\n    Fitness = -HUGE_VAL;\n}\n\nIndividual::Individual(const ExperimentalSetup & ES)\n{\n    if ((ES.NumberOfContributors - ES.NumberOfKnownContributors) == 0)\n    {\n        Eigen::MatrixXd decodedProfile = decoding(EncodedProfile, ES.NumberOfAlleles, ES.NumberOfMarkers, ES.NumberOfContributors - ES.NumberOfKnownContributors);\n\n        CreateReducedElements(ES, decodedProfile);\n        EstimateParameters(ES);\n        CalculateFitness(ES, decodedProfile);\n    }\n    else\n    {\n        Rcpp::stop(\"The only use of this contructor is when the number of contributors equals the number of known contributors under the proposed hypothesis.\");\n    }\n}\n\nIndividual::Individual(const Eigen::VectorXd & encodedGenotype, const ExperimentalSetup & ES)\n{\n    EncodedProfile = encodedGenotype;\n\n    Eigen::MatrixXd decodedProfile = decoding(EncodedProfile, ES.NumberOfAlleles, ES.NumberOfMarkers, ES.NumberOfContributors - ES.NumberOfKnownContributors);\n    CreateReducedElements(ES, decodedProfile);\n\n    EstimateParameters(ES);\n    CalculateFitness(ES, decodedProfile);\n}\n\nIndividual::Individual(const Eigen::VectorXd & encodedGenotype, const Eigen::VectorXd & sampleParameters, const Eigen::VectorXd & noiseParameters,\n                       const Eigen::VectorXd & mixtureParameters, const Eigen::VectorXd & markerParameters, const ExperimentalSetup & ES)\n{\n    EncodedProfile = encodedGenotype;\n\n    SampleParameters = sampleParameters;\n    MixtureParameters = mixtureParameters;\n    MarkerImbalanceParameters = markerParameters;\n    NoiseParameters = noiseParameters;\n\n    Eigen::MatrixXd decodedProfile = decoding(EncodedProfile, ES.NumberOfAlleles, ES.NumberOfMarkers, ES.NumberOfContributors - ES.NumberOfKnownContributors);\n\n    CreateReducedElements(ES, decodedProfile);\n    CalculateFitness(ES, decodedProfile);\n}\n\nIndividual::Individual(const Eigen::VectorXd & encodedGenotype, const Eigen::VectorXd & sampleParameters, const Eigen::VectorXd & noiseParameters,\n                       const Eigen::VectorXd & mixtureParameters, const Eigen::VectorXd & markerParameters, const double & fitness, const ExperimentalSetup & ES)\n{\n    EncodedProfile = encodedGenotype;\n\n    SampleParameters = sampleParameters;\n    MixtureParameters = mixtureParameters;\n    MarkerImbalanceParameters = markerParameters;\n    NoiseParameters = noiseParameters;\n\n    Eigen::MatrixXd decodedProfile = decoding(EncodedProfile, ES.NumberOfAlleles, ES.NumberOfMarkers, ES.NumberOfContributors - ES.NumberOfKnownContributors);\n    CreateReducedElements(ES, decodedProfile);\n\n    CalculateFitness(ES, decodedProfile);\n}\n\nIndividual::Individual(const Eigen::VectorXd & encodedGenotype, const std::vector<Eigen::MatrixXd> reducedExpectedContributionMatrix,\n                       const std::vector<Eigen::VectorXd> reducedAlleleIndex, const std::vector<Eigen::VectorXd> reducedNoiseIndex,\n                       const ExperimentalSetup & ES)\n{\n    EncodedProfile = encodedGenotype;\n\n    ReducedExpectedContributionMatrix = reducedExpectedContributionMatrix;\n    ReducedAlleleIndex = reducedAlleleIndex;\n    ReducedNoiseIndex = reducedNoiseIndex;\n\n    Eigen::MatrixXd decodedProfile = decoding(EncodedProfile, ES.NumberOfAlleles, ES.NumberOfMarkers, ES.NumberOfContributors - ES.NumberOfKnownContributors);\n    EstimateParameters(ES);\n    CalculateFitness(ES, decodedProfile);\n}\n\ndouble ParentStutterContribution(const std::size_t & currentAllele, const std::size_t & stutterRecursion, const double & levelOfRecursion,\n                                 const Eigen::VectorXd & decodedProfile_mu, const std::vector<Eigen::MatrixXd> & potentialParents_m, const double & numberOfAlleles_m)\n{\n    if (stutterRecursion == 0)\n    {\n        return 0.0;\n    }\n\n    Eigen::MatrixXd potentialParents_ma = potentialParents_m[currentAllele];\n    Eigen::VectorXd potentialParentIndex = potentialParents_ma.col(1);\n    Eigen::VectorXd stutterContribution = potentialParents_ma.col(2);\n\n    Eigen::VectorXd potentialParentContribution = Eigen::VectorXd::Zero(potentialParentIndex.size());\n    if (potentialParentIndex[0] != -1)\n    {\n        for (std::size_t i = 0; i < potentialParentIndex.size(); i++)\n        {\n            double parentContribution = ParentStutterContribution(potentialParentIndex[i] - 1, stutterRecursion - 1, levelOfRecursion + 1, decodedProfile_mu, potentialParents_m, numberOfAlleles_m);\n            potentialParentContribution[i] = stutterContribution[i] * (decodedProfile_mu[potentialParentIndex[i] - 1] + parentContribution) / levelOfRecursion; // ;\n        }\n    }\n\n    double totalParentContribition = potentialParentContribution.sum();\n    return totalParentContribition;\n}\n\n\nEigen::MatrixXd Individual::GenerateExpectedContributionProfile(const ExperimentalSetup & ES, const Eigen::MatrixXd & decodedProfile)\n{\n    std::size_t numberOfUnknownContributors = ES.NumberOfContributors - ES.NumberOfKnownContributors;\n    Eigen::VectorXd partialSumAlleles = partialSumEigen(ES.NumberOfAlleles);\n\n    Eigen::MatrixXd profile(ES.Coverage.size(), ES.NumberOfContributors);\n    if (ES.NumberOfKnownContributors > 0)\n    {\n        profile = bindColumns(ES.KnownProfiles, decodedProfile);\n    }\n    else\n    {\n        profile = decodedProfile;\n    }\n\n    Eigen::MatrixXd expectedContributionProfile = Eigen::MatrixXd::Zero(decodedProfile.rows(), ES.NumberOfContributors);\n    for (std::size_t m = 0; m < ES.NumberOfMarkers; m++)\n    {\n        std::vector<Eigen::MatrixXd> potentialParents_m = ES.PotentialParents[m];\n        Eigen::MatrixXd expectedContributionProfile_m = Eigen::MatrixXd::Zero(ES.NumberOfAlleles[m], ES.NumberOfContributors);\n        Eigen::MatrixXd decodedProfile_m = profile.block(partialSumAlleles[m], 0, ES.NumberOfAlleles[m], ES.NumberOfContributors);\n        for (std::size_t u = 0; u < ES.NumberOfContributors; u++)\n        {\n            Eigen::VectorXd decodedProfile_mu = decodedProfile_m.col(u);\n            Eigen::VectorXd stutterContribution = Eigen::VectorXd::Zero(ES.NumberOfAlleles[m]);\n            for (std::size_t a = 0; a < ES.NumberOfAlleles[m]; a++)\n            {\n                stutterContribution[a] = ParentStutterContribution(a, ES.LevelsOfStutterRecursion, 1, decodedProfile_mu, potentialParents_m, ES.NumberOfAlleles[m]);\n            }\n\n            expectedContributionProfile_m.col(u) = decodedProfile_mu + stutterContribution;\n        }\n\n        expectedContributionProfile.block(partialSumAlleles[m], 0, ES.NumberOfAlleles[m], ES.NumberOfContributors) = expectedContributionProfile_m;\n    }\n\n    return expectedContributionProfile;\n}\n\n\nEigen::VectorXd Individual::GenerateNoiseProfile(const ExperimentalSetup & ES, const Eigen::MatrixXd & expectedContributionProfile)\n{\n    Eigen::VectorXd Ones = Eigen::VectorXd::Ones(expectedContributionProfile.cols());\n    Eigen::VectorXd ExpectedContributionProfileRowSum = expectedContributionProfile * Ones;\n\n    std::size_t N = ExpectedContributionProfileRowSum.size();\n    Eigen::VectorXd identifiedNoise = Eigen::VectorXd::Zero(N);\n    for (std::size_t n = 0; n < N; n++)\n    {\n        if (!(ExpectedContributionProfileRowSum[n] > 0.0) & (ES.Coverage[n] > 0.0))\n        {\n            identifiedNoise[n] = 1.0;\n        }\n    }\n\n    return identifiedNoise;\n}\n\nvoid Individual::CreateReducedElements(const ExperimentalSetup & ES, const Eigen::MatrixXd & decodedProfile)\n{\n    Eigen::MatrixXd expectedContributionProfile = GenerateExpectedContributionProfile(ES, decodedProfile);\n    Eigen::VectorXd noiseProfile = GenerateNoiseProfile(ES, expectedContributionProfile);\n\n    std::vector<Eigen::MatrixXd> reducedExpectedContributionMatrix(ES.NumberOfMarkers);\n    std::vector<Eigen::VectorXd> reducedAlleleIndex(ES.NumberOfMarkers);\n    std::vector<Eigen::VectorXd> reducedNoiseIndex(ES.NumberOfMarkers);\n\n    std::size_t n = 0;\n    for (std::size_t m = 0; m < ES.NumberOfMarkers; m++)\n    {\n        Eigen::VectorXd noiseProfile_m = noiseProfile.segment(ES.PartialSumAlleles[m], ES.NumberOfAlleles[m]);\n        std::size_t noiseProfileSize_m = noiseProfile_m.size();\n        std::size_t noiseProfileSum_m = noiseProfile_m.sum();\n\n        Eigen::MatrixXd reducedExpectedContributionMatrix_m = Eigen::MatrixXd::Zero(noiseProfileSize_m - noiseProfileSum_m, ES.NumberOfContributors);\n        Eigen::VectorXd reducedAlleleIndex_m = Eigen::VectorXd::Zero(noiseProfileSize_m - noiseProfileSum_m);\n        Eigen::VectorXd reducedNoiseIndex_m = Eigen::VectorXd::Zero(noiseProfileSum_m);\n\n        std::size_t i = 0, j = 0;\n        for (std::size_t a = 0; a < ES.NumberOfAlleles[m]; a++)\n        {\n            if (noiseProfile[n] == 0)\n            {\n                reducedExpectedContributionMatrix_m.row(i) = expectedContributionProfile.row(n);\n                reducedAlleleIndex_m[i] = a;\n                i++;\n            }\n            else\n            {\n                reducedNoiseIndex_m[j] = a;\n                j++;\n            }\n\n            n++;\n        }\n\n        reducedExpectedContributionMatrix[m] = reducedExpectedContributionMatrix_m;\n        reducedAlleleIndex[m] = reducedAlleleIndex_m;\n        reducedNoiseIndex[m] = reducedNoiseIndex_m;\n    }\n\n    ReducedExpectedContributionMatrix = reducedExpectedContributionMatrix;\n    ReducedAlleleIndex = reducedAlleleIndex;\n    ReducedNoiseIndex = reducedNoiseIndex;\n}\n\nvoid Individual::EstimateParameters(const ExperimentalSetup & ES)\n{\n    //// Estimating parameters\n    // Allele parameters\n    EstimatePoissonGammaAlleleParameters EPGA(ES.Coverage, ReducedExpectedContributionMatrix, ReducedAlleleIndex,\n                                              ES.MarkerImbalances, ES.PartialSumAlleles,\n                                              ES.ConvexMarkerImbalanceInterpolation, ES.Tolerance);\n\n    estimateParametersAlleleCoverage(EPGA);\n    SampleParameters = EPGA.SampleParameters;\n    MixtureParameters = EPGA.MixtureParameters;\n    MarkerImbalanceParameters = EPGA.MarkerImbalancesParameters;\n\n    // Noise parameters\n    if (ES.DualEstimation) {\n        const double varianceUpperLimit = SampleParameters[1];\n        EstimatePoissonGammaNoiseParameters EPGN(ES.Coverage, ReducedNoiseIndex, ES.PartialSumAlleles, ES.Tolerance, varianceUpperLimit);\n        estimateParametersNoiseCoverage(EPGN);\n\n        NoiseParameters = EPGN.NoiseParameters;\n    }\n    else {\n        NoiseParameters = ES.NoiseParameters;\n    }\n}\n\nvoid Individual::CalculateFitness(const ExperimentalSetup & ES, const Eigen::MatrixXd & decodedProfile)\n{\n    LogLikelihoodAlleleMarker = logLikelihoodAlleleCoverage(ES.Coverage, ReducedExpectedContributionMatrix, ReducedAlleleIndex,\n                                                            ES.PartialSumAlleles, SampleParameters, MixtureParameters,\n                                                            MarkerImbalanceParameters);\n    LogLikelihoodAllele = LogLikelihoodAlleleMarker.sum();\n\n    LogLikelihoodNoiseMarker = logLikelihoodNoiseCoverage(ES.Coverage, ReducedNoiseIndex, ES.PartialSumAlleles, NoiseParameters[0], NoiseParameters[1], NoiseParameters[2]);\n    LogLikelihoodNoise = LogLikelihoodNoiseMarker.sum();\n\n    if ((ES.Theta < 0.0) | (ES.AlleleFrequencies.sum() == 0))\n    {\n        LogPriorGenotypeProbabilityMarker = Eigen::VectorXd::Zero(ES.NumberOfMarkers);\n        LogPriorGenotypeProbability = 0.0;\n    }\n    else\n    {\n        LogPriorGenotypeProbabilityMarker = logPriorGenotypeProbability(ES.AlleleFrequencies, ES.Theta, decodedProfile, ES.AllKnownProfiles, ES.NumberOfMarkers, ES.NumberOfAlleles);\n        LogPriorGenotypeProbability = LogPriorGenotypeProbabilityMarker.sum();\n    }\n\n    Fitness = LogLikelihoodAllele + LogLikelihoodNoise + LogPriorGenotypeProbability;\n}\n\nEigen::VectorXd Individual::CalculateResiduals(const ExperimentalSetup & ES, const Eigen::MatrixXd & expectedContributionProfile,\n                                               const Eigen::VectorXd & noiseProfile)\n{\n    const double & referenceMarkerAverage = SampleParameters[0];\n    double dispersion;\n    const Eigen::VectorXd & Coverage = ES.Coverage;\n    const Eigen::VectorXd & MarkerImbalance = ES.MarkerImbalances;\n    const Eigen::VectorXd EC = expectedContributionProfile * MixtureParameters;\n\n    std::size_t N = Coverage.size();\n    Eigen::VectorXd devianceResiduals = Eigen::VectorXd::Zero(N);\n    for (std::size_t n = 0; n < N; n++)\n    {\n        double mu_ma;\n        if (noiseProfile[n] == 0)\n        {\n            mu_ma = referenceMarkerAverage * MarkerImbalance[n] * EC[n];\n            dispersion = SampleParameters[1];\n        }\n        else\n        {\n            mu_ma = NoiseParameters[0];\n            dispersion = NoiseParameters[1];\n        }\n\n        double deviance_ma = (Coverage[n] + dispersion) * (std::log(mu_ma + dispersion) - std::log(Coverage[n] + dispersion));\n        if (Coverage[n] > 0)\n        {\n            deviance_ma += Coverage[n] * (std::log(Coverage[n]) - std::log(mu_ma));\n        }\n\n        devianceResiduals[n] = boost::math::sign(Coverage[n] - mu_ma) * std::pow(deviance_ma, 0.5);\n    }\n\n    return devianceResiduals;\n}\n\nRcpp::List Individual::ReturnRcppList(const ExperimentalSetup & ES)\n{\n    Eigen::MatrixXd decodedProfile = decoding(EncodedProfile, ES.NumberOfAlleles, ES.NumberOfMarkers, ES.NumberOfContributors - ES.NumberOfKnownContributors);\n    Eigen::MatrixXd expectedContributionProfile = GenerateExpectedContributionProfile(ES, decodedProfile);\n\n    Eigen::VectorXd noiseProfile = GenerateNoiseProfile(ES, expectedContributionProfile);\n\n    CalculateFitness(ES, decodedProfile);\n    return Rcpp::List::create(Rcpp::Named(\"EncodedUnknownProfiles\") = EncodedProfile,\n                              Rcpp::Named(\"DecodedUnknownProfiles\") = decodedProfile,\n                              Rcpp::Named(\"ExpectedContributionMatrix\") = expectedContributionProfile,\n                              Rcpp::Named(\"NoiseVector\") = noiseProfile,\n                              Rcpp::Named(\"Parameters\") = Rcpp::List::create(\n                                  Rcpp::Named(\"SampleParameters\") = SampleParameters,\n                                  Rcpp::Named(\"MixtureParameters\") = MixtureParameters,\n                                  Rcpp::Named(\"MarkerImbalanceParameters\") = MarkerImbalanceParameters,\n                                  Rcpp::Named(\"NoiseParameters\") = NoiseParameters),\n                                  Rcpp::Named(\"LogLikelihoodAlleleCoverage\") = LogLikelihoodAlleleMarker,\n                                  Rcpp::Named(\"LogLikelihoods\") = Rcpp::NumericVector::create(LogLikelihoodAllele, LogLikelihoodNoise, LogPriorGenotypeProbability),\n                                  Rcpp::Named(\"Fitness\") = Fitness);\n}\n\nRcpp::List Individual::ReturnRcppListSimplified()\n{\n    return Rcpp::List::create(Rcpp::Named(\"SampleParameters\") = SampleParameters,\n                              Rcpp::Named(\"MarkerImbalanceParameters\") = MarkerImbalanceParameters,\n                              Rcpp::Named(\"MixtureParameters\") = MixtureParameters,\n                              Rcpp::Named(\"NoiseParameters\") = NoiseParameters,\n                              Rcpp::Named(\"Fitness\") = Fitness);\n}\n\n//[[Rcpp::export(.setupIndividual)]]\nRcpp::List setupIndividual(const std::size_t & numberOfMarkers,\n                           const Eigen::VectorXd & numberOfAlleles,\n                           const std::size_t & numberOfContributors,\n                           const std::size_t & numberOfKnownContributors,\n                           const Eigen::MatrixXd & knownProfiles,\n                           const Eigen::VectorXd & coverage,\n                           const std::vector< std::vector < Eigen::MatrixXd > > & potentialParents,\n                           const Eigen::VectorXd & markerImbalances,\n                           const double & convexMarkerImbalanceInterpolation,\n                           const Eigen::VectorXd & noiseParameters,\n                           const Eigen::VectorXd & tolerance,\n                           const double & theta,\n                           const Eigen::VectorXd & alleleFrequencies,\n                           const std::size_t & levelsOfStutterRecursion,\n                           const bool & dualEstimation)\n{\n    const Eigen::MatrixXd allProfilesEmpty;\n    const ExperimentalSetup ES(numberOfMarkers, numberOfAlleles, numberOfContributors, numberOfKnownContributors,\n                               knownProfiles, allProfilesEmpty, coverage, potentialParents, markerImbalances,\n                               convexMarkerImbalanceInterpolation, noiseParameters, tolerance, theta, alleleFrequencies,\n                               levelsOfStutterRecursion, dualEstimation);\n    Individual I(ES);\n\n    Eigen::MatrixXd decodedProfile = decoding(I.EncodedProfile, ES.NumberOfAlleles, ES.NumberOfMarkers, ES.NumberOfContributors - ES.NumberOfKnownContributors);\n    Eigen::MatrixXd expectedContributionProfile = I.GenerateExpectedContributionProfile(ES, decodedProfile);\n    Eigen::VectorXd noiseProfile = I.GenerateNoiseProfile(ES, expectedContributionProfile);\n\n    return Rcpp::List::create(Rcpp::Named(\"EncodedUnknownProfiles\") = I.EncodedProfile,\n                              Rcpp::Named(\"DecodedUnknownProfiles\") = decodedProfile,\n                              Rcpp::Named(\"ExpectedContributionMatrix\") = expectedContributionProfile,\n                              Rcpp::Named(\"NoiseVector\") = noiseProfile,\n                              Rcpp::Named(\"Parameters\") = Rcpp::List::create(\n                                  Rcpp::Named(\"SampleParameters\") = I.SampleParameters,\n                                  Rcpp::Named(\"MixtureParameters\") = I.MixtureParameters,\n                                  Rcpp::Named(\"MarkerImbalanceParameters\") = I.MarkerImbalanceParameters,\n                                  Rcpp::Named(\"NoiseParameters\") = I.NoiseParameters),\n                              Rcpp::Named(\"LogLikelihoodAlleleCoverage\") = I.LogLikelihoodAlleleMarker,\n                              Rcpp::Named(\"LogLikelihoods\") = Rcpp::NumericVector::create(I.LogLikelihoodAllele, I.LogLikelihoodNoise, I.LogPriorGenotypeProbability),\n                              Rcpp::Named(\"Fitness\") = I.Fitness);\n}\n", "meta": {"hexsha": "ae0026ffd086dc3f7582de0bfded12a60083cd8e", "size": 18530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/individual.cpp", "max_stars_repo_name": "svilsen/MPSMixtures", "max_stars_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/individual.cpp", "max_issues_repo_name": "svilsen/MPSMixtures", "max_issues_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/individual.cpp", "max_forks_repo_name": "svilsen/MPSMixtures", "max_forks_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.8811369509, "max_line_length": 197, "alphanum_fraction": 0.676848354, "num_tokens": 3993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.24498004492533793}}
{"text": "/*\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n\n#ifndef KINDR_ROTATIONS_EIGEN_ROTATIONMATRIX_HPP_\n#define KINDR_ROTATIONS_EIGEN_ROTATIONMATRIX_HPP_\n\n#include <cmath>\n\n#include <Eigen/Geometry>\n\n#include \"kindr/common/common.hpp\"\n#include \"kindr/common/assert_macros_eigen.hpp\"\n#include \"kindr/rotations/RotationBase.hpp\"\n#include \"kindr/rotations/eigen/RotationEigenFunctions.hpp\"\n\nnamespace kindr {\nnamespace rotations {\nnamespace eigen_impl {\n\n\n/*! \\class RotationMatrix\n *  \\brief Implementation of matrix rotation based on Eigen::Matrix<Scalar, 3, 3>\n *\n *  The following four typedefs are provided for convenience:\n *   - \\ref eigen_impl::RotationMatrixAD \"RotationMatrixAD\" for active rotation and double primitive type\n *   - \\ref eigen_impl::RotationMatrixAF \"RotationMatrixAF\" for active rotation and float primitive type\n *   - \\ref eigen_impl::RotationMatrixPD \"RotationMatrixPD\" for passive rotation and double primitive type\n *   - \\ref eigen_impl::RotationMatrixPF \"RotationMatrixPF\" for passive rotation and float primitive type\n *\n *  \\tparam PrimType_ the primitive type of the data (double or float)\n *  \\tparam Usage_ the rotation usage which is either active or passive\n *\n *  \\ingroup rotations\n */\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass RotationMatrix : public RotationMatrixBase<RotationMatrix<PrimType_, Usage_>, Usage_>, private Eigen::Matrix<PrimType_, 3, 3> {\n private:\n  /*! \\brief The base type.\n   */\n  typedef Eigen::Matrix<PrimType_, 3, 3> Base;\n public:\n  /*! \\brief The implementation type.\n   *  The implementation type is always an Eigen object.\n   */\n  typedef Base Implementation;\n  /*! \\brief The primitive type.\n   *  Float/Double\n   */\n  typedef PrimType_ Scalar;\n\n  /*! \\brief Default constructor using identity rotation.\n   */\n  RotationMatrix()\n    : Base(Base::Identity()) {\n  }\n\n  /*! \\brief Constructor using nine scalars.\n   *  In debug mode, an assertion is thrown if the matrix is not a rotation matrix.\n   *  \\param r11     entry in row 1, col 1\n   *  \\param r12     entry in row 1, col 2\n   *  \\param r13     entry in row 1, col 3\n   *  \\param r21     entry in row 2, col 1\n   *  \\param r22     entry in row 2, col 2\n   *  \\param r23     entry in row 2, col 3\n   *  \\param r31     entry in row 3, col 1\n   *  \\param r32     entry in row 3, col 2\n   *  \\param r33     entry in row 3, col 3\n   */\n  RotationMatrix(Scalar r11, Scalar r12, Scalar r13,\n                 Scalar r21, Scalar r22, Scalar r23,\n                 Scalar r31, Scalar r32, Scalar r33) {\n    if(Usage_ == RotationUsage::ACTIVE)\n    {\n      *this << r11,r12,r13,r21,r22,r23,r31,r32,r33;\n    } else {\n      *this << r11,r21,r31,r12,r22,r32,r13,r23,r33;\n    }\n    KINDR_ASSERT_MATRIX_NEAR_DBG(std::runtime_error, this->toImplementation() * this->toImplementation().transpose(), Base::Identity(), static_cast<Scalar>(1e-4), \"Input matrix is not orthogonal.\");\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, this->determinant(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input matrix determinant is not 1.\");\n  }\n\n  /*! \\brief Constructor using Eigen::Matrix.\n   *  In debug mode, an assertion is thrown if the rotation vector has not unit length.\n   *  \\param other   Eigen::Matrix<PrimType_,3,3>\n   */\n  explicit RotationMatrix(const Base& other)\n  // : Base(other)\n  {\n    if(Usage_ == RotationUsage::ACTIVE)\n    {\n      this->toImplementation() = other;\n    } else {\n      this->toImplementation() = other.transpose();\n    }\n    KINDR_ASSERT_MATRIX_NEAR_DBG(std::runtime_error, other * other.transpose(), Base::Identity(), static_cast<Scalar>(1e-4), \"Input matrix is not orthogonal.\");\n    KINDR_ASSERT_SCALAR_NEAR_DBG(std::runtime_error, other.determinant(), static_cast<Scalar>(1), static_cast<Scalar>(1e-4), \"Input matrix determinant is not 1.\");\n  }\n\n  /*! \\brief Constructor using another rotation.\n   *  \\param other   other rotation\n   */\n  template<typename OtherDerived_>\n  inline explicit RotationMatrix(const RotationBase<OtherDerived_, Usage_>& other)\n  // : Base(internal::ConversionTraits<RotationMatrix, OtherDerived_>::convert(other.derived()).toImplementation())\n  {\n    this->toImplementation() = internal::ConversionTraits<RotationMatrix, OtherDerived_>::convert(other.derived()).toImplementation();\n  }\n\n  /*! \\brief Assignment operator using another rotation.\n   *  \\param other   other rotation\n   *  \\returns referece\n   */\n  template<typename OtherDerived_>\n  RotationMatrix& operator =(const RotationBase<OtherDerived_, Usage_>& other) {\n    this->toImplementation() = internal::ConversionTraits<RotationMatrix, OtherDerived_>::convert(other.derived()).toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Parenthesis operator to convert from another rotation.\n   *  \\param other   other rotation\n   *  \\returns reference\n   */\n  template<typename OtherDerived_>\n  RotationMatrix& operator ()(const RotationBase<OtherDerived_, Usage_>& other) {\n    this->toImplementation() = internal::ConversionTraits<RotationMatrix, OtherDerived_>::convert(other.derived()).toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Returns the inverse of the rotation.\n   *  \\returns the inverse of the rotation\n   */\n  RotationMatrix inverted() const {\n    RotationMatrix matrix;\n    matrix.toImplementation() = this->toImplementation().transpose();\n    return matrix;\n  }\n\n  /*! \\brief Inverts the rotation.\n   *  \\returns reference\n   */\n  RotationMatrix& invert() {\n    *this = this->inverted();\n    return *this;\n  }\n\n  /*! \\brief Returns the transpose of the rotation matrix.\n   *  \\returns the inverse of the rotation\n   */\n  RotationMatrix transposed() const {\n    RotationMatrix matrix;\n    matrix.toImplementation() = this->toImplementation().transpose();\n    return matrix;\n  }\n\n  /*! \\brief Transposes the rotation matrix.\n   *  \\returns reference\n   */\n  RotationMatrix& transpose() {\n    *this = this->transposed();\n    return *this;\n  }\n\n  /*! \\brief Returns the determinant of the rotation matrix.\n   *  \\returns determinant of the rotation matrix\n   */\n  Scalar determinant() const {\n  return toImplementation().determinant();\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline Implementation& toImplementation() {\n    return static_cast<Implementation&>(*this);\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline const Implementation& toImplementation() const {\n    return static_cast<const Implementation&>(*this);\n  }\n\n  /*! \\brief Reading access to the rotation matrix.\n   *  \\returns rotation matrix (matrix) with reading access\n   */\n  inline Implementation matrix() const {\n    if(Usage_ == RotationUsage::ACTIVE)\n    {\n      return this->toImplementation();\n    } else {\n      return this->toImplementation().transpose();\n    }\n  }\n\n  /*! \\brief  Writing access to the rotation matrix.\n   */\n  inline void setMatrix(const Implementation & input) {\n    if(Usage_ == RotationUsage::ACTIVE)\n    {\n      this->toImplementation() = input;\n    } else {\n      this->toImplementation() = input.transpose();\n    }\n  }\n\n  /*! \\brief  Writing access to the rotation matrix.\n   */\n  inline void setMatrix(Scalar r11, Scalar r12, Scalar r13,\n                        Scalar r21, Scalar r22, Scalar r23,\n                        Scalar r31, Scalar r32, Scalar r33) {\n    if(Usage_ == RotationUsage::ACTIVE)\n    {\n      *this << r11,r12,r13,r21,r22,r23,r31,r32,r33;\n    } else {\n      *this << r11,r21,r31,r12,r22,r32,r13,r23,r33;\n    }\n  }\n\n  /*! \\brief Sets the rotation to identity.\n   *  \\returns reference\n   */\n  RotationMatrix& setIdentity() {\n    this->Implementation::setIdentity();\n    return *this;\n  }\n\n  /*! \\brief Returns a unique matrix rotation.\n   *  A rotation matrix is always unique.\n   *  This function is used to compare different rotations.\n   *  \\returns copy of the matrix rotation which is unique\n   */\n  RotationMatrix getUnique() const {\n    return *this;\n  }\n\n  /*! \\brief Modifies the matrix rotation such that it becomes unique.\n   *  A rotation matrix is always unique.\n   *  \\returns reference\n   */\n  RotationMatrix& setUnique() {\n    return *this;\n  }\n\n  /*! \\brief Concenation operator.\n   *  This is explicitly specified, because Eigen::Matrix provides also an operator*.\n   *  \\returns the concenation of two rotations\n   */\n  using RotationMatrixBase<RotationMatrix<PrimType_, Usage_>, Usage_>::operator*; // otherwise ambiguous RotationBase and Eigen\n\n  /*! \\brief Equivalence operator.\n   *  This is explicitly specified, because Eigen::Matrix provides also an operator==.\n   *  \\returns true if two rotations are similar.\n   */\n  using RotationMatrixBase<RotationMatrix<PrimType_, Usage_>, Usage_>::operator==; // otherwise ambiguous RotationBase and Eigen\n\n  /*! \\brief Used for printing the object with std::cout.\n   *  \\returns std::stream object\n   */\n  friend std::ostream& operator << (std::ostream& out, const RotationMatrix& rotationMatrix) {\n    if(Usage_ == RotationUsage::ACTIVE) {\n      out << rotationMatrix.toImplementation();\n    } else {\n      out << rotationMatrix.inverted().toImplementation();\n    }\n    return out;\n  }\n};\n\n//! \\brief Active matrix rotation with double primitive type\ntypedef RotationMatrix<double, RotationUsage::ACTIVE>  RotationMatrixAD;\n//! \\brief Active matrix rotation with float primitive type\ntypedef RotationMatrix<float,  RotationUsage::ACTIVE>  RotationMatrixAF;\n//! \\brief Passive matrix rotation with double primitive type\ntypedef RotationMatrix<double, RotationUsage::PASSIVE> RotationMatrixPD;\n//! \\brief Passive matrix rotation with float primitive type\ntypedef RotationMatrix<float,  RotationUsage::PASSIVE> RotationMatrixPF;\n\n} // namespace eigen_impl\n\n\nnamespace internal {\n\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass get_scalar<eigen_impl::RotationMatrix<PrimType_, Usage_>> {\n public:\n  typedef PrimType_ Scalar;\n};\n\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass get_matrix3X<eigen_impl::RotationMatrix<PrimType_, Usage_>>{\n public:\n  typedef int  IndexType;\n\n  template <IndexType Cols>\n  using Matrix3X = Eigen::Matrix<PrimType_, 3, Cols>;\n};\n\ntemplate<typename PrimType_>\nclass get_other_usage<eigen_impl::RotationMatrix<PrimType_, RotationUsage::ACTIVE>> {\n public:\n  typedef eigen_impl::RotationMatrix<PrimType_, RotationUsage::PASSIVE> OtherUsage;\n};\n\ntemplate<typename PrimType_>\nclass get_other_usage<eigen_impl::RotationMatrix<PrimType_, RotationUsage::PASSIVE>> {\n public:\n  typedef eigen_impl::RotationMatrix<PrimType_, RotationUsage::ACTIVE> OtherUsage;\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Conversion Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationMatrix<DestPrimType_, Usage_>, eigen_impl::AngleAxis<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationMatrix<DestPrimType_, Usage_> convert(const eigen_impl::AngleAxis<SourcePrimType_, Usage_>& aa) {\n    eigen_impl::RotationMatrix<DestPrimType_, Usage_> matrix;\n    matrix.toImplementation() = eigen_impl::eigen_internal::getRotationMatrixFromAngleAxis<SourcePrimType_, DestPrimType_>(aa.toImplementation());\n    return matrix;\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationMatrix<DestPrimType_, Usage_>, eigen_impl::RotationVector<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationMatrix<DestPrimType_, Usage_> convert(const eigen_impl::RotationVector<SourcePrimType_, Usage_>& rotationVector) {\n    typename eigen_impl::RotationMatrix<DestPrimType_, Usage_>::Implementation matrixdata;\n    typedef typename eigen_impl::RotationVector<SourcePrimType_, Usage_>::Scalar Scalar;\n    const  typename eigen_impl::RotationVector<DestPrimType_, Usage_>::Implementation rv = rotationVector.toImplementation().template cast<DestPrimType_>();\n    const SourcePrimType_ v1 = rv.x();\n    const SourcePrimType_ v2 = rv.y();\n    const SourcePrimType_ v3 = rv.z();\n    const SourcePrimType_ v = rv.norm();\n\n    if (v < common::internal::NumTraits<Scalar>::dummy_precision())  {\n\n      // active to passive\n//      matrixdata << 1.0,  v3, -v2,\n//                        -v3, 1.0,  v1,\n//                          v2, -v1, 1.0;\n      // active to active\n      matrixdata << 1.0,  -v3, v2,\n                    v3, 1.0,  -v1,\n                   -v2, v1, 1.0;\n    } else {\n      // active rotation vector to active matrix // not matlab code (is transposed)\n      const DestPrimType_ t3 = v*(1.0/2.0);\n      const DestPrimType_ t2 = sin(t3);\n      const DestPrimType_ t4 = cos(t3);\n      const DestPrimType_ t5 = 1.0/(v*v);\n      const DestPrimType_ t6 = t4*v*v3;\n      const DestPrimType_ t7 = t2*v1*v2;\n      const DestPrimType_ t8 = t2*t2;\n      const DestPrimType_ t9 = v1*v1;\n      const DestPrimType_ t10 = v2*v2;\n      const DestPrimType_ t11 = v3*v3;\n      const DestPrimType_ t12 = v*v;\n      const DestPrimType_ t13 = t4*t4;\n      const DestPrimType_ t14 = t12*t13;\n      const DestPrimType_ t15 = t2*v1*v3;\n      const DestPrimType_ t16 = t4*v*v1;\n      const DestPrimType_ t17 = t2*v2*v3;\n      matrixdata(0,0) = t5*(t14-t8*(-t9+t10+t11));\n      matrixdata(1,0) = t2*t5*(t6+t7)*2.0;\n      matrixdata(2,0) = t2*t5*(t15-t4*v*v2)*2.0;\n      matrixdata(0,1) = t2*t5*(t6-t7)*-2.0;\n      matrixdata(1,1) = t5*(t14-t8*(t9-t10+t11));\n      matrixdata(2,1) = t2*t5*(t16+t17)*2.0;\n      matrixdata(0,2) = t2*t5*(t15+t4*v*v2)*2.0;\n      matrixdata(1,2) = t2*t5*(t16-t17)*-2.0;\n      matrixdata(2,2) = t5*(t14-t8*(t9+t10-t11));\n\n\n\n    }\n\n    eigen_impl::RotationMatrix<DestPrimType_, Usage_> matrix;\n    matrix.toImplementation() = matrixdata;\n    return matrix;\n\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationMatrix<DestPrimType_, Usage_>, eigen_impl::RotationQuaternion<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationMatrix<DestPrimType_, Usage_> convert(const eigen_impl::RotationQuaternion<SourcePrimType_, Usage_>& q) {\n    eigen_impl::RotationMatrix<DestPrimType_, Usage_> matrix;\n    matrix.toImplementation() = eigen_impl::eigen_internal::getRotationMatrixFromQuaternion<SourcePrimType_, DestPrimType_>(q.toImplementation());\n    return matrix;\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationMatrix<DestPrimType_, Usage_>, eigen_impl::RotationMatrix<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationMatrix<DestPrimType_, Usage_> convert(const eigen_impl::RotationMatrix<SourcePrimType_, Usage_>& R) {\n    eigen_impl::RotationMatrix<DestPrimType_, Usage_> matrix;\n    matrix.toImplementation() = R.toImplementation().template cast<DestPrimType_>();\n    return matrix;\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationMatrix<DestPrimType_, Usage_>, eigen_impl::EulerAnglesXyz<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationMatrix<DestPrimType_, Usage_> convert(const eigen_impl::EulerAnglesXyz<SourcePrimType_, Usage_>& xyz) {\n    eigen_impl::RotationMatrix<DestPrimType_, Usage_> matrix;\n    matrix.toImplementation() = eigen_impl::eigen_internal::getRotationMatrixFromRpy<SourcePrimType_, DestPrimType_>(xyz.toImplementation());\n    return matrix;\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::RotationMatrix<DestPrimType_, Usage_>, eigen_impl::EulerAnglesZyx<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::RotationMatrix<DestPrimType_, Usage_> convert(const eigen_impl::EulerAnglesZyx<SourcePrimType_, Usage_>& zyx) {\n    eigen_impl::RotationMatrix<DestPrimType_, Usage_> matrix;\n    matrix.toImplementation() = eigen_impl::eigen_internal::getRotationMatrixFromYpr<SourcePrimType_, DestPrimType_>(zyx.toImplementation());\n    return matrix;\n  }\n};\n\n\n\n/*! \\brief Multiplication of two rotation matrices\n */\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass MultiplicationTraits<RotationBase<eigen_impl::RotationMatrix<PrimType_, Usage_>, Usage_>, RotationBase<eigen_impl::RotationMatrix<PrimType_, Usage_>, Usage_>> {\n public:\n  inline static eigen_impl::RotationMatrix<PrimType_, Usage_> mult(const eigen_impl::RotationMatrix<PrimType_, Usage_>& lhs, const eigen_impl::RotationMatrix<PrimType_, Usage_>& rhs) {\n    if(Usage_ == RotationUsage::ACTIVE) {\n      eigen_impl::RotationMatrix<PrimType_, Usage_> result;\n      result.toImplementation() = lhs.toImplementation() * rhs.toImplementation();\n      return result;\n    } else {\n      eigen_impl::RotationMatrix<PrimType_, Usage_> result;\n      result.toImplementation() = rhs.toImplementation() * lhs.toImplementation();\n      return result;\n    }\n  }\n};\n\n\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Rotation Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n//template<typename PrimType_, enum RotationUsage Usage_>\n//class RotationTraits<eigen_impl::RotationMatrix<PrimType_, Usage_>> {\n// public:\n//  template<typename get_matrix3X<eigen_impl::RotationMatrix<PrimType_, Usage_>>::IndexType Cols>\n//  inline static typename get_matrix3X<eigen_impl::RotationMatrix<PrimType_, Usage_>>::template Matrix3X<Cols> rotate(const eigen_impl::RotationMatrix<PrimType_, Usage_>& R, const typename get_matrix3X<eigen_impl::RotationMatrix<PrimType_, Usage_>>::template Matrix3X<Cols>& m){\n//    return R.toImplementation() * m;\n//  }\n//};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Comparison Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Usage Conversion Traits - required?\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\ntemplate<typename PrimType_>\nclass UsageConversionTraits<eigen_impl::RotationMatrix<PrimType_, RotationUsage::PASSIVE>,RotationUsage::PASSIVE> {\n public:\n  inline static typename get_other_usage<eigen_impl::RotationMatrix<PrimType_, RotationUsage::PASSIVE>>::OtherUsage getActive(const eigen_impl::RotationMatrix<PrimType_,RotationUsage::PASSIVE>& in) {\n    return typename get_other_usage<eigen_impl::RotationMatrix<PrimType_, RotationUsage::PASSIVE>>::OtherUsage(in.inverted().toImplementation());\n  }\n\n  // getPassive() does not exist (on purpose)\n};\n\ntemplate<typename PrimType_>\nclass UsageConversionTraits<eigen_impl::RotationMatrix<PrimType_, RotationUsage::ACTIVE>,RotationUsage::ACTIVE> {\n public:\n  inline static typename get_other_usage<eigen_impl::RotationMatrix<PrimType_, RotationUsage::ACTIVE>>::OtherUsage getPassive(const eigen_impl::RotationMatrix<PrimType_, RotationUsage::ACTIVE>& in) {\n    return typename get_other_usage<eigen_impl::RotationMatrix<PrimType_, RotationUsage::ACTIVE>>::OtherUsage(in.toImplementation());\n  }\n\n  // getActive() does not exist (on purpose)\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Box Operations - required?\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n//template<typename LeftPrimType_, typename RightPrimType_, enum RotationUsage Usage_>\n//class BoxOperationTraits<RotationBase<eigen_impl::RotationMatrix<LeftPrimType_, Usage_>, Usage_>, RotationBase<eigen_impl::RotationMatrix<RightPrimType_, Usage_>, Usage_>> {\n// public:\n//  inline static typename internal::get_matrix3X<eigen_impl::RotationMatrix<LeftPrimType_, Usage_>>::template Matrix3X<1> box_minus(const eigen_impl::RotationMatrix<LeftPrimType_, Usage_>& lhs, const eigen_impl::RotationMatrix<RightPrimType_, Usage_>& rhs) {\n//    return (lhs*rhs.inverted()).getLogarithmicMap();\n//  }\n//\n//  inline static  eigen_impl::RotationMatrix<LeftPrimType_, Usage_> box_plus(const eigen_impl::RotationMatrix<RightPrimType_, Usage_>& rotation, const typename internal::get_matrix3X<eigen_impl::RotationMatrix<RightPrimType_, Usage_>>::template Matrix3X<1>& vector) {\n//    return eigen_impl::RotationMatrix<LeftPrimType_, Usage_>((MapTraits<RotationBase<eigen_impl::RotationMatrix<RightPrimType_,Usage_>, Usage_>>::set_exponential_map(vector)).toImplementation()*rotation.toImplementation());\n//  }\n//};\n\n\n//template<typename PrimType_, enum RotationUsage Usage_>\n//class MapTraits<eigen_impl::RotationMatrix<PrimType_, Usage_>> {\n// public:\n//\n//  inline static eigen_impl::RotationMatrix<PrimType_, Usage_> set_exponential_map(const typename internal::get_matrix3X<eigen_impl::RotationMatrix<PrimType_, Usage_>>::template Matrix3X<1>& vector) {\n//    typedef typename get_scalar<eigen_impl::RotationMatrix<PrimType_, Usage_>>::Scalar Scalar;\n//    if (Usage_ == RotationUsage::ACTIVE) {\n//      return eigen_impl::RotationMatrix<PrimType_, Usage_>(eigen_impl::RotationVector<Scalar, Usage_>(vector));\n//    }\n//    if (Usage_ == RotationUsage::PASSIVE) {\n//      return eigen_impl::RotationMatrix<PrimType_, Usage_>(eigen_impl::RotationVector<Scalar, Usage_>(vector));\n//    }\n//  }\n//\n////  inline static typename internal::get_matrix3X<Rotation_>::template Matrix3X<1> get_logarithmic_map(const Rotation_& rotation) {\n////    typedef typename get_scalar<Rotation_>::Scalar Scalar;\n////    eigen_impl::RotationVector<Scalar, Rotation_::Usage> rotationVector(rotation);\n////    return rotationVector.getUnique().toImplementation();\n////  }\n//\n//  inline static typename internal::get_matrix3X<eigen_impl::RotationMatrix<PrimType_, Usage_>>::template Matrix3X<1> get_logarithmic_map(const eigen_impl::RotationMatrix<PrimType_, Usage_>& rotation) {\n//    typedef typename get_scalar<eigen_impl::RotationMatrix<PrimType_, Usage_>>::Scalar Scalar;\n//\n//\n//\n//    if (Usage_ == RotationUsage::ACTIVE) {\n//      return eigen_impl::RotationVector<Scalar, Usage_>(rotation).toImplementation();\n//    }\n//    if (Usage_ == RotationUsage::PASSIVE) {\n//      return eigen_impl::RotationVector<Scalar, Usage_>(rotation).toImplementation();\n//    }\n//  }\n//\n//};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Fixing Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass FixingTraits<eigen_impl::RotationMatrix<PrimType_, Usage_>> {\n public:\n  inline static void fix(eigen_impl::RotationMatrix<PrimType_, Usage_>& R) {\n    const PrimType_ factor = 1/pow(R.determinant(), 1.0/3.0);\n    R.setMatrix(factor*R.matrix()(0,0),\n                factor*R.matrix()(0,1),\n                factor*R.matrix()(0,2),\n                factor*R.matrix()(1,0),\n                factor*R.matrix()(1,1),\n                factor*R.matrix()(1,2),\n                factor*R.matrix()(2,0),\n                factor*R.matrix()(2,1),\n                factor*R.matrix()(2,2));\n  }\n};\n\n\n} // namespace internal\n} // namespace rotations\n} // namespace kindr\n\n\n#endif /* KINDR_ROTATIONS_EIGEN_ROTATIONMATRIX_HPP_ */\n", "meta": {"hexsha": "f7e274a7e60de6530918c6132e1ec15942ab488a", "size": 26708, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/RotationMatrix.hpp", "max_stars_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_stars_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 170.0, "max_stars_repo_stars_event_min_datetime": "2016-02-01T18:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:28:01.000Z", "max_issues_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/RotationMatrix.hpp", "max_issues_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_issues_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 162.0, "max_issues_repo_issues_event_min_datetime": "2016-01-29T17:04:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T16:25:37.000Z", "max_forks_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/RotationMatrix.hpp", "max_forks_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_forks_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2016-01-28T22:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:11:24.000Z", "avg_line_length": 45.1148648649, "max_line_length": 279, "alphanum_fraction": 0.6528381009, "num_tokens": 6078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2448964344532826}}
{"text": "/*  \n * Copyright (c) 2009 Carnegie Mellon University. \n *     All rights reserved.\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing,\n *  software distributed under the License is distributed on an \"AS\n *  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n *  express or implied.  See the License for the specific language\n *  governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n *      http://www.graphlab.ml.cmu.edu\n *\n */\n\n\n/**\n *\n * \\brief This application performs MAP inference on Markov Nets \n * provided in standard UAI file format via Dual-Decomposition. \n *\n *\n *  \\authors Dhruv Batra, André Martins, Aroma Mahendru\n */\n\n\n\n#ifndef _AD3_QP_HPP_\n#define _AD3_QP_HPP_\n\n\n#include <Eigen/Eigenvalues>\n#include <math.h>\n#include <limits>\n#include \"dd_grlab.hpp\"\n\n\n#define NEARLY_ZERO_TOL(a,tol) (((a)<=(tol)) && ((a)>=(-(tol))))\n#define NEARLY_EQ_TOL(a,b,tol) (((a)-(b))*((a)-(b))<=(tol))\n#define num_max_iterations_QP_ 10\n\n\n/**\n * \\brief ADMM vertex program  general implements Alternating direction dual \n * decomposition for general dense factors.\n */\n\nstruct admm_vertex_program_general:public admm_vertex_program {\n\n/**\n * \\brief Maximize returns the maximum value and configuration with reference to \n * input additional and variable log potentials. addtional log potential corresponds \n * factor potentials and variable potential corresponds to sum of lagrange \n * multipliers and unary potentials divided by degree of the unary vertex.\n */\n\n\nvoid Maximize(vertex_type& vertex, vec additional_log_potentials, vec variable_log_potentials,\n                Configuration &configuration,\n                double *value) {\n          \n    vector <Configuration> states(vertex.data().nvars,-1);\n    int best = -1;\n    *value = -1e12;\n    for (int index = 0;\n         index < additional_log_potentials.size();\n         ++index) {\n      double score = additional_log_potentials[index];\n      get_configuration_states(vertex,index, &states);\n      int offset = 0;\n      for (int i = 0; i < vertex.data().nvars; ++i) {\n        score += variable_log_potentials[offset+states[i]];\n        offset = vertex.data().cards[i];\n        \n      }\n      \n      if (configuration < 0 || score > *value) {\n        configuration = index;\n        *value = score;\n      }\n    }\n    assert(configuration >= 0);\n    \n  }\n\n \n void DeleteConfiguration(Configuration &configuration) {\n    configuration = -1;\n  }\n\n/**\n * \\brief InvertAfterInsertion function is used to invert the matrix. Used in solveQP\n */\n\n bool InvertAfterInsertion(vertex_type& vertex, vector <double> & inverse_A_,\n        const vector<Configuration> &active_set, const Configuration &inserted_element) {\n\n  vector<double> inverse_A = inverse_A_;\n  int size_A = active_set.size() + 1;\n  vector<double> r(size_A);\n\n  r[0] = 1.0;\n  for (int i = 0; i < active_set.size(); ++i) {\n    // Count how many variable values the new assignment\n    // have in common with the i-th assignment.\n    int num_common_values = CountCommonValues(vertex, active_set[i], inserted_element);\n    r[i+1] = static_cast<double>(num_common_values);\n  }\n\n  double r0 = static_cast<double>(CountCommonValues(vertex,\n      inserted_element, inserted_element));\n  double s = r0;\n  for (int i = 0; i < size_A; ++i) {\n    if (r[i] == 0.0) continue;\n    s -= r[i] * r[i] * inverse_A[i * size_A + i];\n    for (int j = i+1; j < size_A; ++j) {\n      if (r[j] == 0.0) continue;\n      s -= 2 * r[i] * r[j] * inverse_A[i * size_A + j];\n    }\n  }\n\n    if (NEARLY_ZERO_TOL(s, 1e-9)) {\n         if (opts.verbose> 2) {\n      cout << \"Warning: updated matrix will become singular after insertion.\"\n           << endl;\n    }\n    return false;\n  }\n\n  double invs = 1.0 / s;\n  vector<double> d(size_A, 0.0);\n  for (int i = 0; i < size_A; ++i) {\n    if (r[i] == 0.0) continue;\n    for (int j = 0; j < size_A; ++j) {\n      d[j] += inverse_A[i * size_A + j] * r[i];\n    }\n  }\n\n  int size_A_after = size_A + 1;\n  inverse_A_.resize(size_A_after * size_A_after);\n  for (int i = 0; i < size_A; ++i) {\n    for (int j = 0; j < size_A; ++j) {\n      inverse_A_[i * size_A_after + j] = inverse_A[i * size_A + j] +\n          invs * d[i] * d[j];\n    }\n    inverse_A_[i * size_A_after + size_A] = -invs * d[i];\n    inverse_A_[size_A * size_A_after + i] = -invs * d[i];\n  }\n  inverse_A_[size_A * size_A_after + size_A] = invs;\n\n  return true;\n}\n\n/**\n * \\brief InvertAfterRemoval function is used to invert the matrix. Used in solveQP\n */\nvoid InvertAfterRemoval(vector <double> &inverse_A_,const vector<Configuration> &active_set,\n                                       int removed_index) {\n  vector<double> inverse_A = inverse_A_;\n  int size_A = active_set.size() + 1;\n  vector<double> r(size_A);\n\n  ++removed_index; // Index in A has an offset of 1.\n  double invs = inverse_A[removed_index * size_A + removed_index];\n  assert(!NEARLY_ZERO_TOL(invs, 1e-12));\n  double s = 1.0 / invs;\n  vector<double> d(size_A - 1, 0.0);\n  int k = 0;\n  for (int i = 0; i < size_A; ++i) {\n    if (i == removed_index) continue;\n    d[k] = -s * inverse_A[removed_index * size_A + i];\n    ++k;\n  }\n\n  int size_A_after = size_A - 1;\n  inverse_A_.resize(size_A_after * size_A_after);\n  k = 0;\n  for (int i = 0; i < size_A; ++i) {\n    if (i == removed_index) continue;\n    int l = 0;\n    for (int j = 0; j < size_A; ++j) {\n      if (j == removed_index) continue;\n      inverse_A_[k * size_A_after + l] = inverse_A[i * size_A + j] -\n          invs * d[k] * d[l];\n      ++l;\n    }\n    ++k;\n  }\n}\n\n/**\n * \\brief ComputeActiveSetSimilarities computes Mnz'*Mnz. Used in solveQP\n */\nvoid ComputeActiveSetSimilarities(vertex_type& vertex,\n    const vector<Configuration> &active_set,\n    vector<double> *similarities) {\n  int size = active_set.size();\n\n  // Compute similarity matrix.\n  similarities->resize(size * size);\n  (*similarities)[0] = 0.0;\n  for (int i = 0; i < active_set.size(); ++i) {\n    (*similarities)[i*size + i] = static_cast<double>(\n        CountCommonValues(vertex,active_set[i], active_set[i]) );\n    for (int j = i+1; j < active_set.size(); ++j) {\n      // Count how many variable values the i-th and j-th \n      // assignments have in common.\n      int num_common_values = CountCommonValues(vertex,active_set[i], active_set[j]);\n      (*similarities)[i*size + j] = num_common_values;\n      (*similarities)[j*size + i] = num_common_values;\n    }\n  }\n}\n\n/**\n * \\brief  ComputeMarginalsFromSparseDistribution computes marginalvalues for unary \n * factor from given factor distribution.\n */\n \nvoid ComputeMarginalsFromSparseDistribution( vertex_type& vertex, \n    const vector<Configuration> &active_set,\n    const vector<double> &distribution,\n    vec  &variable_posteriors,\n    vec &additional_posteriors) {\n    variable_posteriors.setZero();           \n    additional_posteriors.setZero();  \n    for (int i = 0; i < active_set.size(); ++i) {\n    UpdateMarginalsFromConfiguration(vertex,active_set[i],\n                                       distribution[i],\n                                       variable_posteriors,\n                                       additional_posteriors);\n    }\n  }\n  \n  \n   // Given a configuration with a probability (weight), \n  // increment the vectors of variable and additional posteriors.\n  void UpdateMarginalsFromConfiguration(vertex_type& vertex,\n    const Configuration &configuration,\n    double weight,\n    vec &variable_posteriors,\n    vec &additional_posteriors) {\n    \n     vector <Configuration> states(vertex.data().nvars, -1);\n     get_configuration_states(vertex, configuration, &states);\n     \n            int offset = 0;\n            \n            for (int k = 0; k < vertex.data().nvars; ++k) \n            {   variable_posteriors[offset + states[k]] += weight;\n                offset += vertex.data().cards[k];\n            }\n    additional_posteriors[configuration] += weight;\n \n  }\n  // Count how many common values two configurations have.\n  int CountCommonValues(vertex_type& vertex,Configuration configuration1,\n                        Configuration configuration2) {\n    \n    //assert(states1->size() == states2->size());\n    int count = 0;\n    vector <Configuration> states1(vertex.data().nvars, -1); \n    vector <Configuration> states2(vertex.data().nvars, -1);\n    get_configuration_states(vertex, configuration1, &states1);\n    get_configuration_states(vertex, configuration2, &states2);\n    for(int i = 0; i< vertex.data().nvars; i++)\n    {  if (states1[i] == states2[i])\n      { count++;} }\n    return count;\n  }\n  \n\n/**\n * \\brief Evaluate returns the maximum value  with reference to \n * input additional and variable log potentials and configuration. addtional \n * log potential corresponds factor potentials and variable potential corresponds \n * to sum of lagrange  * multipliers and unary potentials divided by degree of \n * the unary vertex.\n */\n  \n  \nvoid Evaluate(vertex_type& vertex, vec additional_log_potentials, vec variable_log_potentials,\n                const Configuration configuration,\n                double *value) {\n          \n    vector<Configuration> states(vertex.data().nvars, -1);\n    get_configuration_states(vertex, configuration, &states);\n    *value = 0.0;\n    int offset = 0;\n    for (int i = 0;i<vertex.data().nvars; ++i) {\n      *value += variable_log_potentials[offset + states[i]];\n      offset = vertex.data().cards[i]; \n    }\n    *value += additional_log_potentials[configuration];\n  }\n  \n  \n  \n  void EigenDecompose(vector<double> *similarities,\n                            vector<double> *eigenvalues) {\n\n  int size = sqrt(similarities->size());\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;\n  Eigen::MatrixXd sim(size, size);\n  int t = 0;\n  for (int i = 0; i < size; ++i) {\n    for (int j = 0; j < size; ++j) {\n      sim(i, j) = (*similarities)[t];\n      ++t;\n    }\n  }\n  es.compute(sim);\n  const Eigen::VectorXd &eigvals = es.eigenvalues(); \n  eigenvalues->resize(size);\n  for (int i = 0; i < size; ++i) {\n    (*eigenvalues)[i] = eigvals[i];\n  }\n  const Eigen::MatrixXd &eigvectors = es.eigenvectors().transpose();\n  t = 0;\n  for (int i = 0; i < size; ++i) {\n    for (int j = 0; j < size; ++j) {\n      (*similarities)[t] = eigvectors(i, j);\n      ++t;\n    }\n  }\n\n}\n\n\n// Function to solve each quadratic sub problem for dense factors. \n// It uses active set method. Caching is deactivated\n// TODO: Activate caching feature\n\nvoid SolveQP_dense(vertex_type& vertex,const gather_type& total,\n            vec& variable_posteriors, vec& additional_posteriors) {\n   vertex_data& vdata = vertex.data();                        \n   //cout<<\"loop 1 in solveQP ..\"<<endl;\n   vec additional_log_potentials = vdata.potentials;\n   vec variable_log_potentials = total.neighbor_distribution + total.messages;      \n   vector <Configuration> active_set_;\n   vector<double> distribution_;\n   vector<double> inverse_A_;\n  // Initialize the active set.\n  \n   if (active_set_.size() == 0) {\n    variable_posteriors.resize(variable_log_potentials.size());     \n    additional_posteriors.resize(additional_log_potentials.size()); \n    distribution_.clear();\n    // Initialize by solving the LP, discarding the quadratic\n    // term.\n    Configuration configuration = -1;\n    double value;\n    Maximize(vertex, additional_log_potentials, variable_log_potentials,\n             configuration,\n             &value);\n    active_set_.push_back(configuration);\n    distribution_.push_back(1.0);\n\n    // Initialize inv(A) as [-M,1;1,0].\n    inverse_A_.resize(4);\n    inverse_A_[0] = static_cast<double>(\n        -CountCommonValues(vertex,configuration, configuration));\n    inverse_A_[1] = 1;\n    inverse_A_[2] = 1;\n    inverse_A_[3] = 0;\n  }\n\n  bool changed_active_set = true;\n  vector<double> z;\n  int num_max_iterations = num_max_iterations_QP_;\n  double tau = 0;\n  for (int iter = 0; iter < num_max_iterations; ++iter) {\n    bool same_as_before = true;\n    bool unbounded = false;\n    if (changed_active_set) {\n      // Recompute vector b.\n      vector<double> b(active_set_.size() + 1, 0.0);\n      b[0] = 1.0;\n      for (int i = 0; i < active_set_.size(); ++i) {\n        const Configuration &configuration = active_set_[i];\n        double score;\n        Evaluate(vertex, additional_log_potentials, variable_log_potentials,\n                 configuration,\n                 &score);\n        b[i+1] = score;\n      }\n      // Solve the system Az = b.\n      z.resize(active_set_.size());\n      int size_A = active_set_.size() + 1;\n      for (int i = 0; i < active_set_.size(); ++i) {\n        z[i] = 0.0;\n        for (int j = 0; j < size_A; ++j) {\n          z[i] += inverse_A_[(i+1) * size_A + j] * b[j];\n        }\n      }\n      tau = 0.0;\n      for (int j = 0; j < size_A; ++j) {\n        tau += inverse_A_[j] * b[j];\n      }\n\n      same_as_before = false;\n    }\n\n    if (same_as_before) {\n      // Compute the variable marginals from the full distribution\n      // stored in z.\n      ComputeMarginalsFromSparseDistribution(vertex, active_set_,\n                                             z,\n                                             variable_posteriors,\n                                             additional_posteriors);\n      // Get the most violated constraint\n      // (by calling the black box that computes the MAP).\n      vec scores = variable_log_potentials;               \n      for (int i = 0; i < scores.size(); ++i) {\n        scores[i] -= variable_posteriors[i];\n      }\n      Configuration configuration = -1;\n      double value = 0.0;\n      \n      Maximize(vertex,\n                additional_log_potentials, scores,\n               configuration,\n               &value);\n      double very_small_threshold = 1e-9;\n      if (value <= tau + very_small_threshold) { // value <= tau.\n        // We have found the solution;\n        // the distribution, active set, and inv(A) are cached for the next round.\n        DeleteConfiguration(configuration);\n        return;\n      } else {\n        for (int k = 0; k < active_set_.size(); ++k) {\n          // This is expensive and should just be a sanity check.\n          // However, in practice, numerical issues force an already existing\n          // configuration to try to be added. Therefore, we always check\n          // if a configuration already exists before inserting it.\n          // If it does, that means the active set method converged to a\n          // solution (but numerical issues had prevented us to see it.)\n          if (active_set_[k] == configuration) {                         \n            if (opts.verbose > 2) {\n              cout << \"Warning: value - tau = \"\n                   << value - tau << \" \" << value << \" \" << tau\n                   << endl;\n            }\n            // We have found the solution;\n            // the distribution, active set, and inv(A)\n            // are cached for the next round.\n            DeleteConfiguration(configuration);\n\n            // Just in case, clean the cache.\n            // This may prevent eventual numerical problems in the future.\n            for (int j = 0; j < active_set_.size(); ++j) {\n              if (j == k) continue; // This configuration was deleted already.\n              DeleteConfiguration(active_set_[j]);\n            }\n            active_set_.clear();\n            inverse_A_.clear();\n            distribution_.clear();\n\n            // Return.\n            return;\n          }\n        }\n        z.push_back(0.0);\n        distribution_ = z;\n\n        // Update inv(A).\n        bool singular = !InvertAfterInsertion(vertex, inverse_A_, active_set_, configuration);\n        if (singular) {\n          // If adding a new configuration causes the matrix to be singular,\n          // don't just add it. Instead, look for a configuration in the null\n          // space and remove it before inserting the new one.\n          // Right now, if more than one such configuration exists, we just\n          // remove the first one we find. There's a chance this could cause\n          // some cyclic behaviour. If that is the case, we should randomize\n          // this choice.\n          // Note: This step is expensive and requires an eigendecomposition.\n          // TODO: I think there is a graph interpretation for this problem.\n          // Maybe some specialized graph algorithm is cheaper than doing\n          // the eigendecomposition.\n          vector<double> similarities(active_set_.size() * active_set_.size());\n          ComputeActiveSetSimilarities(vertex, active_set_, &similarities);\n          \n          //cout<<\"compute active similarities in solveQP ..\"<<endl;\n          vector<double> padded_similarities((active_set_.size()+2) * \n                                             (active_set_.size()+2), 1.0);\n          for (int i = 0; i < active_set_.size(); ++i) {\n            for (int j = 0; j < active_set_.size(); ++j) {\n              padded_similarities[(i+1)*(active_set_.size()+2) + (j+1)] =\n                  similarities[i*active_set_.size() + j];\n            }\n          }\n          padded_similarities[0] = 0.0;\n          for (int i = 0; i < active_set_.size(); ++i) {\n            double value = static_cast<double>(\n                CountCommonValues(vertex, configuration, active_set_[i]));\n            padded_similarities[(i+1)*(active_set_.size()+2) +\n                                (active_set_.size()+1)] = value;\n            padded_similarities[(active_set_.size()+1)*(active_set_.size()+2) +\n                                (i+1)] = value;\n          }\n          double value = static_cast<double>(\n              CountCommonValues(vertex, configuration, configuration));\n          padded_similarities[(active_set_.size()+1)*(active_set_.size()+2) +\n                              (active_set_.size()+1)] = value;\n\n          vector<double> eigenvalues(active_set_.size()+2);\n          EigenDecompose(&padded_similarities, &eigenvalues);\n          int zero_eigenvalue = -1;\n          for (int i = 0; i < active_set_.size()+2; ++i) {\n            if (NEARLY_EQ_TOL(eigenvalues[i], 0.0, 1e-9)) {\n              if (zero_eigenvalue >= 0) {\n                // If this happens, something failed. Maybe a numerical problem\n                // may cause this. In that case, just give up, clean the cache\n                // and return. Hopefully the next iteration will fix it.\n                cout << \"Multiple zero eigenvalues: \"\n                     << eigenvalues[zero_eigenvalue] << \" and \"\n                     << eigenvalues[i] << endl;\n                cout << \"Warning: Giving up.\" << endl;\n                // Clean the cache.\n                for (int j = 0; j < active_set_.size(); ++j) {\n                  DeleteConfiguration(active_set_[j]);\n                }\n                active_set_.clear();\n                inverse_A_.clear();\n                distribution_.clear();\n                return;\n              }\n              zero_eigenvalue = i;\n            }\n          }\n          assert(zero_eigenvalue >= 0);\n          vector<int> configurations_to_remove;\n          for (int j = 1; j < active_set_.size()+1; ++j) {\n            double value = padded_similarities[zero_eigenvalue*(active_set_.size()+2) + j];\n            if (!NEARLY_EQ_TOL(value, 0.0, 1e-9)) {\n              configurations_to_remove.push_back(j-1);\n            }\n          }\n          if (opts.verbose > 2) {\n            cout << \"Pick a configuration to remove (\" << configurations_to_remove.size()\n                 << \" out of \" << active_set_.size() << \").\" << endl;\n          }\n\n          assert(configurations_to_remove.size() >= 1);\n          int j = configurations_to_remove[0];\n\n          // Update inv(A).\n          InvertAfterRemoval(inverse_A_, active_set_, j);\n\n          // Remove blocking constraint from the active set.\n          DeleteConfiguration(active_set_[j]); // Delete configutation.\n          active_set_.erase(active_set_.begin() + j);\n\n          singular = !InvertAfterInsertion(vertex, inverse_A_, active_set_, configuration);\n          assert(!singular);\n        }\n\n        // Insert configuration to active set.\n        if (opts.verbose > 2) {\n          cout << \"Inserted one element to the active set (iteration \"\n               << iter << \").\" << endl;\n        }\n        active_set_.push_back(configuration);\n        changed_active_set = true;\n      }      \n    } else {\n      // Solution has changed from the previous iteration.\n      // Look for blocking constraints.\n      int blocking = -1;\n      bool exist_blocking = false;\n      double alpha = 1.0;\n      for (int i = 0; i < active_set_.size(); ++i) {\n        assert(distribution_[i] >= -1e-12);\n        if (z[i] >= distribution_[i]) continue;\n        if (z[i] < 0) exist_blocking = true;\n        double tmp = distribution_[i] / (distribution_[i] - z[i]);\n        if (blocking < 0 || tmp < alpha) {\n          alpha = tmp;\n          blocking = i;\n        }\n      }\n\n      if (!exist_blocking) {\n        // No blocking constraints.\n        assert(!unbounded);\n        distribution_ = z;\n        alpha = 1.0;\n        changed_active_set = false;\n      } else {\n        if (alpha > 1.0 && !unbounded) alpha = 1.0;\n        // Interpolate between factor_posteriors_[i] and z.\n        if (alpha == 1.0) {\n          distribution_ = z;\n        } else {\n          for (int i = 0; i < active_set_.size(); ++i) {\n            z[i] = (1 - alpha) * distribution_[i] + alpha * z[i];\n            distribution_[i] = z[i];\n          }\n        }\n\n        // Update inv(A).\n        InvertAfterRemoval(inverse_A_, active_set_, blocking);\n\n        // Remove blocking constraint from the active set.\n        if (opts.verbose > 2) {\n          cout << \"Removed one element to the active set (iteration \"\n               << iter << \").\" << endl;\n        }\n\n        DeleteConfiguration(active_set_[blocking]); // Delete configutation.\n        active_set_.erase(active_set_.begin() + blocking);\n\n        z.erase(z.begin() + blocking);\n        distribution_.erase(distribution_.begin() + blocking);\n        changed_active_set = true;\n        for (int i = 0; i < distribution_.size(); ++i) {\n          assert(distribution_[i] > -1e-16);\n        }\n      }\n    }\n  }\n\n  // Maximum number of iterations reached.\n  // Return the best existing solution by computing the variable marginals \n  // from the full distribution stored in z.\n  //assert(false);\n  ComputeMarginalsFromSparseDistribution(vertex, active_set_,\n                                         z,\n                                         variable_posteriors,\n                                         additional_posteriors); \n  }\n  \n  \n  void InsertionSort(pair<double, int> arr[], int length) {\n  int i, j;\n  pair<double, int> tmp;\n\n  for (i = 1; i < length; i++) {\n    j = i;\n    while (j > 0 && arr[j - 1].first > arr[j].first) {\n      tmp = arr[j];\n      arr[j] = arr[j - 1];\n      arr[j - 1] = tmp;\n      j--;\n    }\n  }\n}\n\n  \n  int project_onto_budget_constraint_cached(vec& x,\n                                          int d,\n                                          double budget, \n                                          vector<pair<double,int> >& y) {\n  int j, k, l, level;\n  double s = 0.0;\n  double tau = 0.0, tightsum;\n  double left, right = -std::numeric_limits<double>::infinity();\n\n  // Load x into a reordered y (the reordering is cached).\n  if (y.size() != d) {\n    y.resize(d);\n    for (j = 0; j < d; j++) {\n      s -= x[j];\n      y[j].first = -x[j];\n      y[j].second = j;\n    }\n    sort(y.begin(), y.end());\n  } else {\n    for (j = 0; j < d; j++) {\n      s -= x[j];\n      y[j].first = -x[y[j].second];\n    }\n    // If reordering is cached, use a sorting algorithm \n    // which is fast when the vector is almost sorted.\n    InsertionSort(&y[0], d);\n  }\n\n  tightsum = s;\n  s += budget;\n  \n  k = l = level = 0;\n  bool found = false;\n  double val_a, val_b;\n  while (k < d && l < d) {\n    if (level != 0) {\n      tau = (s - tightsum) / static_cast<double>(level);\n    }\n    if (k < d) val_a = y[k].first;\n    val_b = 1.0 + y[l].first;\n    left = right;\n    if (k == d || val_b <= val_a) {\n      right = val_b;\n    } else {\n      right = val_a;\n    }\n    if ((level == 0 && s == tightsum) || (level != 0 && tau <= right)) {\n      // Found the right split-point!\n      found = true;\n      break;\n    }\n    if (k == d || val_b <= val_a) {\n      tightsum += val_b;\n      --level;\n      ++l;\n    } else {\n      tightsum -= val_a;\n      ++level;\n      ++k;\n    }\n  }\n\n  if (!found) {\n    left = right;\n    right = std::numeric_limits<double>::infinity();\n  }\n      \n  for (j = 0; j < d; j++) {\n    if (-x[j] >= right) {\n      x[j] = 0.0;\n    } else if (1.0 - x[j] <= left) {\n      x[j] = 1.0;\n    } else {\n      x[j] += tau;\n    }\n  }\n\n  return 0;\n}\n\n  \n  \n  \n  // Solve the QP subproblem for budget factor.\n  // TODO Enable caching\nvoid SolveQP_budget(vertex_type& vertex,const gather_type& total,\n            vec& variable_posteriors, vec& additional_posteriors){\n            \n  vertex_data& vdata =  vertex.data();\n  vec variable_log_potentials = total.neighbor_distribution + total.messages;\n  vector<pair<double,int> > last_sort_;\n  for (int f = 0; f < variable_log_potentials.size(); ++f) {\n    variable_posteriors[f] = variable_log_potentials[f];\n    if (variable_posteriors[f] < 0.0) {\n      variable_posteriors[f] = 0.0;\n    } else if (variable_posteriors[f] > 1.0) {\n      variable_posteriors[f] = 1.0;\n    }\n  }\n\n  double s = 0.0;\n  for (int f = 0; f < vdata.nvars; ++f) {\n    s += variable_posteriors[f];\n  }\n\n  if (s > static_cast<double>(vdata.budget)) {\n    for (int f = 0; f < variable_log_potentials.size(); ++f) {\n      variable_posteriors[f] = variable_log_potentials[f];\n    }\n    project_onto_budget_constraint_cached(variable_posteriors, \n                                          variable_log_potentials.size(), \n                                          static_cast<double>(vdata.budget), \n                                          last_sort_);\n  }\n\n}\n\n// Finds best configuration ofr budget factors\nvoid SolveMAP_budget(vertex_type& vertex,const gather_type& total,\n            vec& variable_posteriors, vec& additional_posteriors, double& value) {\n \n   vertex_data& vdata = vertex.data();\n  // Create a local copy of the log potentials.\n   vec log_potentials(total.messages); \n  double valaux;\n \n  value = 0.0;\n  \n  int num_active = 0;\n  double sum = 0.0;\n\n  for (int f = 0; f < vdata.nvars; ++f) {\n    valaux = log_potentials[f];\n    if (valaux < 0.0) {\n      variable_posteriors[f] =  0.0;\n    } else {\n      sum += valaux;\n      variable_posteriors[f] = 1.0;\n    }\n    ++num_active;\n  }\n  if (num_active > vdata.budget) {\n    vector<pair<double,int> > scores(vdata.nvars);\n    for (int f = 0; f < vdata.nvars; ++f) {\n      scores[f].first = -log_potentials[f];\n      scores[f].second = f;\n    }\n\n    sort(scores.begin(), scores.end());\n    num_active = 0;\n    sum = 0.0;\n    for (int k = 0; k < vdata.budget; ++k) {\n      valaux = -scores[k].first;\n      if (valaux < 0.0) break;\n      int f = scores[k].second;\n      variable_posteriors[f] = 1.0;\n      sum += valaux;\n      ++num_active;      \n    }\n\n    for (int k = num_active; k < vdata.nvars; ++k) {\n      int f = scores[k].second;\n      variable_posteriors[f] = 0.0;\n    }    \n   // cout<<\"third inner loop ...\"<<endl;\n  }\n  \n  value += sum;\n  \n  \n}\n\n// Finds best configuration for dense factors\nvoid SolveMAP_dense(vertex_type& vertex,const gather_type& total,\n            vec& variable_posteriors, vec& additional_posteriors, double& value){\n     vertex_data& vdata = vertex.data();\n     vec beliefs = vdata.potentials;         \n     int num_configurations = vdata.potentials.size();\n     for (int index_configuration = 0;\n           index_configuration < num_configurations;\n            ++index_configuration) {\n        vector<int> states(vdata.nvars, -1);\n        get_configuration_states(vertex, index_configuration, &states);\n        int offset = 0;\n        for (int k = 0; k < vdata.nvars; ++k) {\n             beliefs[index_configuration] += total.messages[offset + states[k]];\n             offset += vdata.cards[k];}\n    } \n            \n        value = beliefs.maxCoeff();\n \n }\n\n// Finds beliefs using dense and budget factors\nvoid compute_beliefs(vertex_type& vertex,const gather_type& total,\n            vec& variable_posteriors, vec& additional_posteriors){\nswitch(vertex.data().factor_type){\n\ncase 0: SolveQP_dense(vertex,total, variable_posteriors, additional_posteriors);\n        break;\ncase 1: SolveQP_budget(vertex,total, variable_posteriors, additional_posteriors);\n\n}\n};\n\n// General solvMAP function\nvoid SolveMAP(vertex_type& vertex,const gather_type& total,\n            vec& variable_posteriors, vec& additional_posteriors, double& value){\nswitch(vertex.data().factor_type){\n\ncase 0: SolveMAP_dense(vertex,total, variable_posteriors, additional_posteriors, value);\n        break;\ncase 1: SolveMAP_budget(vertex,total, variable_posteriors, additional_posteriors, value);\n  }\n };\n\n};\n\n#endif\n", "meta": {"hexsha": "86eef04981f7e7ec3305b456428320bb947c37d9", "size": 29117, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "toolkits/graphical_models/ad3_qp.hpp", "max_stars_repo_name": "xcgoner/powerlore", "max_stars_repo_head_hexsha": "c95ab1ca5a3636eaf5fb9c4feeaddcb96bb2d6ee", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-20T07:41:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T00:52:29.000Z", "max_issues_repo_path": "toolkits/graphical_models/ad3_qp.hpp", "max_issues_repo_name": "kesinger/graphlab", "max_issues_repo_head_hexsha": "5acb39d816f33e59433e88a9d3621eb4cf7cb05e", "max_issues_repo_licenses": ["ECL-2.0", "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": "toolkits/graphical_models/ad3_qp.hpp", "max_forks_repo_name": "kesinger/graphlab", "max_forks_repo_head_hexsha": "5acb39d816f33e59433e88a9d3621eb4cf7cb05e", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-27T12:40:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-27T12:40:52.000Z", "avg_line_length": 33.2006841505, "max_line_length": 94, "alphanum_fraction": 0.5816533297, "num_tokens": 7401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2448946368113344}}
{"text": "//\n// Copyright (c) 2009, Markus Rickert\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright notice,\n//   this list of conditions and the following disclaimer in the documentation\n//   and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n\n#include <iostream>\n#include <memory>\n#include <stdexcept>\n#include <boost/lexical_cast.hpp>\n#include <rl/math/Unit.h>\n#include <rl/mdl/Body.h>\n#include <rl/mdl/Dynamic.h>\n#include <rl/mdl/Fixed.h>\n#include <rl/mdl/Frame.h>\n#include <rl/mdl/Revolute.h>\n#include <rl/mdl/RungeKuttaNystromIntegrator.h>\n#include <rl/mdl/World.h>\n\nstd::shared_ptr<rl::mdl::Dynamic>\ncreatePlanar2()\n{\n\tstd::shared_ptr<rl::mdl::Dynamic> dynamic = std::make_shared<rl::mdl::Dynamic>();\n\tdynamic->setName(\"planar2\");\n\t\n\t// frames\n\t\n\tstd::shared_ptr<rl::mdl::World> world = std::make_shared<rl::mdl::World>();\n\tworld->setName(\"world\");\n\tworld->setGravity(rl::math::Vector3(0, 0, rl::math::constants::gravity));\n\tdynamic->add(world);\n\t\n\tstd::shared_ptr<rl::mdl::Body> link0 = std::make_shared<rl::mdl::Body>();\n\tlink0->setName(\"link0\");\n\tdynamic->add(link0);\n\t\n\tstd::shared_ptr<rl::mdl::Body> link1 = std::make_shared<rl::mdl::Body>();\n\tlink1->setCenterOfMass(static_cast<rl::math::Real>(0.5), 0, 0);\n\tlink1->setInertia(static_cast<rl::math::Real>(0.01), static_cast<rl::math::Real>(0.083333333), static_cast<rl::math::Real>(0.083333333), 0, 0, 0);\n\tlink1->setMass(1);\n\tlink1->setName(\"link1\");\n\tdynamic->add(link1);\n\t\n\tstd::shared_ptr<rl::mdl::Frame> frame0 = std::make_shared<rl::mdl::Frame>();\n\tframe0->setName(\"frame0\");\n\tdynamic->add(frame0);\n\t\n\tstd::shared_ptr<rl::mdl::Body> link2 = std::make_shared<rl::mdl::Body>();\n\tlink2->setCenterOfMass(static_cast<rl::math::Real>(0.5), 0, 0);\n\tlink2->setInertia(static_cast<rl::math::Real>(0.01), static_cast<rl::math::Real>(0.083333333), static_cast<rl::math::Real>(0.083333333), 0, 0, 0);\n\tlink2->setMass(1);\n\tlink2->setName(\"link2\");\n\tdynamic->add(link2);\n\t\n\tstd::shared_ptr<rl::mdl::Frame> frame1 = std::make_shared<rl::mdl::Frame>();\n\tframe1->setName(\"frame1\");\n\tdynamic->add(frame1);\n\t\n\t// selfcollision\n\t\n\tlink0->setCollision(false);\n\tlink1->setCollision(link0.get(), false);\n\tlink1->setCollision(link2.get(), false);\n\tlink2->setCollision(link1.get(), false);\n\t\n\t// transforms\n\t\n\tstd::shared_ptr<rl::mdl::Fixed> fixed0 = std::make_shared<rl::mdl::Fixed>();\n\tfixed0->setName(\"fixed0\");\n\tdynamic->add(fixed0, world.get(), link0.get());\n\t\n\tstd::shared_ptr<rl::mdl::Revolute> joint0 = std::make_shared<rl::mdl::Revolute>();\n\tjoint0->setMaximum(rl::math::Vector::Constant(1, 360 * rl::math::constants::deg2rad));\n\tjoint0->setMinimum(rl::math::Vector::Constant(1, -360 * rl::math::constants::deg2rad));\n\tjoint0->setName(\"joint0\");\n\tdynamic->add(joint0, link0.get(), link1.get());\n\t\n\tstd::shared_ptr<rl::mdl::Fixed> fixed1 = std::make_shared<rl::mdl::Fixed>();\n\tfixed1->setName(\"fixed1\");\n\tfixed1->setTransform(rl::math::Transform(rl::math::Translation(rl::math::Vector3(1, 0, 0))));\n\tdynamic->add(fixed1, link1.get(), frame0.get());\n\t\n\tstd::shared_ptr<rl::mdl::Revolute> joint1 = std::make_shared<rl::mdl::Revolute>();\n\tjoint1->setMaximum(rl::math::Vector::Constant(1, 360 * rl::math::constants::deg2rad));\n\tjoint1->setMinimum(rl::math::Vector::Constant(1, -360 * rl::math::constants::deg2rad));\n\tjoint1->setName(\"joint1\");\n\tdynamic->add(joint1, frame0.get(), link2.get());\n\t\n\tstd::shared_ptr<rl::mdl::Fixed> fixed2 = std::make_shared<rl::mdl::Fixed>();\n\tfixed2->setName(\"fixed2\");\n\tfixed2->setTransform(rl::math::Transform(rl::math::Translation(rl::math::Vector3(1, 0, 0))));\n\tdynamic->add(fixed2, link2.get(), frame1.get());\n\t\n\t// initialize\n\t\n\tdynamic->update();\n\t\n\treturn dynamic;\n}\n\nint\nmain(int argc, char** argv)\n{\n\tif (argc < 7)\n\t{\n\t\tstd::cout << \"Usage: rlDynamics1Planar2Demo Q1 Q2 QD1 QD2 QDD1 QDD2\" << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\ttry\n\t{\n\t\tstd::shared_ptr<rl::mdl::Dynamic> dynamic = createPlanar2();\n\t\t\n\t\trl::math::Vector q(dynamic->getDofPosition());\n\t\trl::math::Vector qd(dynamic->getDof());\n\t\trl::math::Vector qdd(dynamic->getDof());\n\t\t\n\t\tfor (std::size_t i = 0; i < dynamic->getDofPosition(); ++i)\n\t\t{\n\t\t\tq(i) = boost::lexical_cast<rl::math::Real>(argv[i + 1]);\n\t\t}\n\t\t\n\t\tfor (std::size_t i = 0; i < dynamic->getDof(); ++i)\n\t\t{\n\t\t\tqd(i) = boost::lexical_cast<rl::math::Real>(argv[i + 1 + dynamic->getDofPosition()]);\n\t\t\tqdd(i) = boost::lexical_cast<rl::math::Real>(argv[i + 1 + dynamic->getDofPosition() + dynamic->getDof()]);\n\t\t}\n\t\t\n\t\tdynamic->setPosition(q);\n\t\tdynamic->setVelocity(qd);\n\t\tdynamic->setAcceleration(qdd);\n\t\t\n\t\tdynamic->inverseDynamics();\n\t\tstd::cout << \"tau = \" << dynamic->getTorque().transpose() << std::endl;\n\t\t\n\t\tdynamic->forwardDynamics();\n\t\tstd::cout << \"qdd = \" << dynamic->getAcceleration().transpose() << std::endl;\n\t\t\n\t\trl::mdl::RungeKuttaNystromIntegrator integrator(dynamic.get());\n\t\tintegrator.integrate(1);\n\t\tstd::cout << \"q = \" << dynamic->getPosition().transpose() << std::endl;\n\t\tstd::cout << \"qd = \" << dynamic->getVelocity().transpose() << std::endl;\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tstd::cout << e.what() << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\t\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "5fc8bf67cdc9ad155dd7dd6dfb5734f339a884e4", "size": 6234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "demos/rlDynamics1Demo/rlDynamics1Planar2Demo.cpp", "max_stars_repo_name": "mcx/rl", "max_stars_repo_head_hexsha": "aa6eb334b5279ece8523258957b70e3b8c0c42ce", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 568.0, "max_stars_repo_stars_event_min_datetime": "2015-01-23T03:38:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T16:12:56.000Z", "max_issues_repo_path": "demos/rlDynamics1Demo/rlDynamics1Planar2Demo.cpp", "max_issues_repo_name": "mcx/rl", "max_issues_repo_head_hexsha": "aa6eb334b5279ece8523258957b70e3b8c0c42ce", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 53.0, "max_issues_repo_issues_event_min_datetime": "2016-03-23T13:16:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-17T05:58:06.000Z", "max_forks_repo_path": "demos/rlDynamics1Demo/rlDynamics1Planar2Demo.cpp", "max_forks_repo_name": "mcx/rl", "max_forks_repo_head_hexsha": "aa6eb334b5279ece8523258957b70e3b8c0c42ce", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 169.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T12:59:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:44:54.000Z", "avg_line_length": 36.2441860465, "max_line_length": 147, "alphanum_fraction": 0.6883221046, "num_tokens": 1875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.388618026705849, "lm_q1q2_score": 0.24474175979819987}}
{"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/*                                                                           */\n/*  This file is part of the tsppd program and library for solving           */\n/*  Traveling Salesman Problems with Pickup and Delivery. tsppd requires     */\n/*  other commercial and open source software to build. tsppd is decribed    */\n/*  in the paper \"Exact Methods for Solving Traveling Salesman Problems      */\n/*  with Pickup and Delivery in Real Time\".                                  */\n/*                                                                           */\n/*  Copyright (C) 2017 Ryan J. O'Neil <roneil1@gmu.edu>                      */\n/*                                                                           */\n/*  tsppd is distributed under the terms of the ZIB Academic License.        */\n/*  You should have received a copy of the ZIB Academic License along with   */\n/*  tsppd. See the file LICENSE. If not, email roneil1@gmu.edu.              */\n/*                                                                           */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n#include <algorithm>\n#include <cmath>\n#include <iterator>\n#include <limits>\n#include <utility>\n\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n\n#include <tsppd/solver/focacci/filter/one_tree/focacci_tsp_one_tree.h>\n\nusing namespace Gecode;\nusing namespace TSPPD::Data;\nusing namespace TSPPD::Solver;\nusing namespace std;\n\nOneTree::OneTree(\n    ViewArray<Int::IntView>& next,\n    const TSPPDProblem& problem,\n    const unsigned int max_iterations) :\n    OneTree(next, problem, max_iterations, nullptr) { }\n\nOneTree::OneTree(\n    ViewArray<Int::IntView>& next,\n    const TSPPDProblem& problem,\n    const unsigned int max_iterations,\n    TSPPD::AP::PrimalDualAPSolver* ap) :\n    next(next),\n    problem(problem),\n    max_iterations(max_iterations),\n    ap(ap),\n    graph(next.size() - 2),\n    potentials(next.size(), 0),\n    edges(next.size(), set<int>()),\n    start_index(problem.index(\"+0\")),\n    end_index(problem.index(\"-0\")),\n    iteration(1),\n    w(0) {\n\n    weights = boost::get(boost::edge_weight, graph);\n    initialize_one_tree();\n}\n\n\ndouble OneTree::bound() {\n    double best_w = 0;\n    vector<set<int>> best_edges;\n\n    while (!done) {\n        improve();\n        \n        if (iteration == 1 || w > best_w) {\n            best_w = w;\n            best_edges = edges;\n        }\n\n        if (done)\n            break;\n    }\n    \n    w = best_w;\n    edges = best_edges;\n    return w;\n}\n\nvoid OneTree::improve() {\n    // Find the max min 1-tree by updating node potentials based on violation of degree constraints.\n    bool is_tour = true;\n\n    // Compute optimal 1-tree.\n    edges = vector<set<int>>(next.size(), set<int>());\n    auto new_w = minimize_one_tree();\n\n    // Update step size\n    auto M = max_iterations;\n    auto m = iteration;\n    if (m == 1) {\n        t1 = new_w / (2.0 * next.size());\n        ti = t1;\n    } else {\n        ti = t1*(m - 1)*(2*M - 5)/(2*(M-1)) - t1*(m-2) + t1*(m-1)*(m-2)/(2*(M-1)*(M-2));\n    }\n\n    // Remove node potentials from tour.\n    for (auto pi : potentials)\n        new_w -= 2 * pi;\n\n    // Update node potentials.\n    for (int node = 0; node < next.size(); ++node) {\n        if (node != start_index && node != end_index && edges[node].size() != 2)\n            is_tour = false;\n        potentials[node] += (((int) edges[node].size()) - 2) * ti;\n    }\n\n    if (is_tour || iteration++ > max_iterations)\n        done = true;\n    else\n        update_one_tree();\n\n    w = new_w;\n}\n\nbool OneTree::has_edge(int from, int to) {\n    return edges[from].find(to) != edges[from].end();\n}\n\nint OneTree::marginal_cost(int from, int to) {\n    vector<bool> seen(edges.size(), false);\n    seen[to] = true;\n    return marginal_cost(from, to, seen, to, 0);\n}\n\nvoid OneTree::initialize_one_tree() {\n    for (int i = 0; i < next.size(); ++i) {\n        // Arcs are undirected for MST.\n        if (i == start_index || i == end_index)\n            continue;\n\n        for (int j = i + 1; j < next.size(); ++j) {\n            if (j == start_index || j == end_index)\n                continue;\n\n            if (!(next[i].in(j) || next[j].in(i)))\n                continue;\n\n            OneTreeEdge e;\n            bool inserted;\n            boost::tie(e, inserted) = boost::add_edge(i, j, graph);\n            weights[e] = undirected_cost(i, j);\n        }\n    }\n}\n\nvoid OneTree::update_one_tree() {\n    auto es = boost::edges(graph);\n    for (auto eit = es.first; eit != es.second; ++eit) {\n        auto e = *eit;\n        weights[e] = transformed_cost(e.m_source, e.m_target);\n    }\n}\n\ndouble OneTree::minimize_one_tree() {\n    vector<OneTreeEdge> mst;\n    boost::kruskal_minimum_spanning_tree(graph, back_inserter(mst));\n\n    // Calculate cost of the MST and pull out edges.\n    double z = 0;\n    for (auto e : mst) {\n        edges[e.m_source].insert(e.m_target);\n        edges[e.m_target].insert(e.m_source);\n        z += weights[e];\n    }\n\n    // Add cheapest arc connecting +0.\n    int min_p0_idx = -1;\n    double min_p0 = numeric_limits<double>::max();\n    for (auto to = next[start_index].min(); to <= next[start_index].max(); ++to) {\n        if (!next[start_index].in(to))\n            continue;\n\n        auto c = transformed_cost(start_index, to);\n        if (c < min_p0) {\n            min_p0_idx = to;\n            min_p0 = c;\n        }\n    }\n    edges[start_index].insert(min_p0_idx);\n    edges[min_p0_idx].insert(start_index);\n\n    // Add cheapest arc connecting -0.\n    int min_d0_idx = -1;\n    double min_d0 = numeric_limits<double>::max();\n    for (int from = 0; from < next.size(); ++from) {\n        if (!next[from].in(end_index))\n            continue;\n\n        auto c = transformed_cost(from, end_index);\n        if (c < min_d0) {\n            min_d0_idx = from;\n            min_d0 = c;\n        }\n    }\n    edges[end_index].insert(min_d0_idx);\n    edges[min_d0_idx].insert(end_index);\n\n    edges[start_index].insert(end_index);\n    edges[end_index].insert(start_index);\n\n    return z + min_p0 + min_d0;\n}\n\nint OneTree::undirected_cost(int i, int j) {\n    auto c_ij = next[i].in(j) ? cost(i, j) : numeric_limits<int>::max();\n    auto c_ji = next[j].in(i) ? cost(j, i) : numeric_limits<int>::max();\n    return min(c_ij, c_ji);\n}\n\ndouble OneTree::transformed_cost(int i, int j) {\n    return undirected_cost(i, j) + potentials[i] + potentials[j];\n}\n\nint OneTree::marginal_cost(\n    int from,\n    int to,\n    vector<bool> seen,\n    int node,\n    int max_edge_cost) {\n\n    // Introducing a nonbasic arc into the basis would create a cycle.\n    // The marginal cost of this operation is the cost of the new arc\n    // minus the max cost in the cycle. This can be found using DFS.\n    for (auto next : edges[node]) {\n        if ((node == start_index && next == end_index) || (node == end_index && next == start_index))\n            continue;\n\n        if (seen[next])\n            continue;\n\n        // If we loop back to the from node, then compute marginal cost.\n        if (next == from && node != to)\n            return cost(from, to) - max_edge_cost;\n\n        vector<bool> new_seen(seen);\n        new_seen[next] = true;\n\n        int new_max = max(max_edge_cost, undirected_cost(node, next));\n        auto cost = marginal_cost(from, to, new_seen, next, new_max);\n        if (cost > -1)\n            return cost;\n    }\n\n    return -1;\n}\n\nint OneTree::cost(int i, int j) {\n    if (ap == nullptr)\n        return problem.cost(i, j);\n    return ap->get_rc({i, j});\n}\n", "meta": {"hexsha": "6a2e307d0c01b508050f8d8464aba95f5f9804c2", "size": 7585, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/tsppd/solver/focacci/filter/one_tree/focacci_tsp_one_tree.cpp", "max_stars_repo_name": "ryanjoneil/tsppd", "max_stars_repo_head_hexsha": "f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4", "max_stars_repo_licenses": ["AFL-1.1"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-03-30T20:58:57.000Z", "max_stars_repo_stars_event_max_datetime": "2018-04-25T01:48:09.000Z", "max_issues_repo_path": "src/tsppd/solver/focacci/filter/one_tree/focacci_tsp_one_tree.cpp", "max_issues_repo_name": "ryanjoneil/tsppd", "max_issues_repo_head_hexsha": "f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4", "max_issues_repo_licenses": ["AFL-1.1"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2019-04-21T13:42:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-09T15:49:56.000Z", "max_forks_repo_path": "src/tsppd/solver/focacci/filter/one_tree/focacci_tsp_one_tree.cpp", "max_forks_repo_name": "ryanjoneil/tsppd-hybrid", "max_forks_repo_head_hexsha": "f0e1e5e867e13c8fa0dcddf4d2ffa2aae7f46da4", "max_forks_repo_licenses": ["AFL-1.1"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-01T16:19:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-01T16:19:18.000Z", "avg_line_length": 29.7450980392, "max_line_length": 101, "alphanum_fraction": 0.5450230719, "num_tokens": 1991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.24461314562022252}}
{"text": "/*Copyright (c) 2021 James Gayvert\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include \"TrajectoryAnalysis.h\"\n\n#include <cmath>\n#include <complex>\n#include <Eigen/Dense>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <sstream>\n#include <string>\n\n\n#include \"utils.h\"\n\nvoid CAPHamiltonian::set_eta_list(std::map<std::string, std::string> params)\n{\n\tdouble eta_step;\n\tsize_t nsteps;\n\tstd::stringstream stepss(params[\"eta_step\"]);\n\tstd::stringstream nstepss(params[\"nsteps\"]);\n\tstd::istringstream save_traj(params[\"save_trajectory\"]);\n\tstepss >> eta_step;\n\tnstepss >> nsteps;\n\tsave_traj >> std::boolalpha >> do_output;\n\teta_step*=1E-5;\n\tfor(size_t i=0;i<=nsteps;i++)\n\t\teta_list.push_back(i*eta_step);\n}\n\nCAPHamiltonian::CAPHamiltonian(Eigen::MatrixXd h0,Eigen::MatrixXd cap,std::map<std::string,\n\t\tstd::string> params,std::string filename)\n{\n\tCAP_MAT = cap;\n\tZERO_ORDER_H = h0;\n\tnstates = h0.cols();\n\tset_eta_list(params);\n\tfiname = filename;\n}\n\nvoid CAPHamiltonian::track_state(size_t state_idx)\n{\n\tstd::cout << \"Results for state:\" << state_idx << std::endl;\n\tstd::cout << \"----------------------\" << std::endl;\n\tEigenvalueTrajectory traj(all_roots[0],state_idx);\n\tfor(size_t i=1;i<all_roots.size();i++)\n\t\ttraj.add_state(all_roots[i]);\n\ttraj.analyze();\n\tstd::cout << \"----------------------\" << std::endl;\n\ttrajectories.push_back(traj);\n}\n\nvoid CAPHamiltonian::track_states()\n{\n\tstd::cout << \"---------------------\" << std::endl;\n\tstd::cout << \"Trajectory Analysis:\" << std::endl;\n\tstd::cout << \"--------------------\" << std::endl;\n\tfor(size_t i=0;i<nstates;i++)\n\t\ttrack_state(i);\n}\n\nvoid CAPHamiltonian::save_trajectory()\n{\n\tstd::ofstream trajFile;\n\tstd::string data_finame = finame + \".data\";\n\ttrajFile.open(data_finame);\n    trajFile << std::left << std::setw(18) << std::setfill(' ')\n    << \"State\" << std::left << std::setw(18) << std::setfill(' ')\n    << \"eta\" << std::left << std::setw(18) << std::setfill(' ')\n    << \"Uncorr_Re\" << std::left << std::setw(18) << std::setfill(' ')\n    << \"Uncorr_Im\" << std::left << std::setw(18) << std::setfill(' ');\n    trajFile << \"Corr_Re\" << std::left << std::setw(18) << std::setfill(' ') << \"Corr_Im\" << std::endl;\n    trajFile.close();\n}\n\nvoid CAPHamiltonian::run_trajectory()\n{\n\tsize_t nstates = CAP_MAT.rows();\n\tfor(size_t i=0;i<eta_list.size();i++)\n\t{\n\t\tstd::vector<root> roots;\n\t\tEigen::MatrixXcd CAPH(nstates,nstates);\n\t\tCAPH.real() = ZERO_ORDER_H;\n\t\tCAPH.imag() = eta_list[i]*CAP_MAT;\n\t\tEigen::ComplexEigenSolver<Eigen::MatrixXcd> ces;\n\t\tces.compute(CAPH);\n\t\tfor(size_t j=0;j<nstates;j++)\n\t\t{\n\t\t\tstd::complex<double> energy =  ces.eigenvalues()[j];\n\t\t\tEigen::VectorXcd vec = ces.eigenvectors().col(j);\n\t\t\troot r1(eta_list[i],energy,vec);\n\t\t\troots.push_back(r1);\n\t\t}\n\t\tall_roots.push_back(roots);\n\t}\n\ttrack_states();\n\tif(do_output)\n\t\tsave_trajectory();\n}\n\nEigenvalueTrajectory::EigenvalueTrajectory(std::vector<root> initial_states, size_t state_idx)\n{\n\tprev = initial_states[state_idx];\n\tstates.push_back(prev);\n\tuncorrected_energies.push_back(prev.energy);\n\tcorrected_energies.push_back(prev.energy);\n}\n\nvoid EigenvalueTrajectory::add_state(std::vector<root> new_states)\n{\n\tdouble max_overlap=0.0;\n\troot best=new_states[0];\n\tfor(auto cur: new_states)\n\t{\n\t\tdouble overlap = abs(prev.eigv.dot(cur.eigv));\n\t\tif(overlap>max_overlap)\n\t\t{\n\t\t\tbest = cur;\n\t\t\tmax_overlap = overlap;\n\t\t}\n\t}\n\tstates.push_back(best);\n\tprev = best;\n\tuncorrected_energies.push_back(best.energy);\n}\n\nvoid EigenvalueTrajectory::analyze()\n{\n\t// get corrections, find minimum of logarithmic velocity of uncorrected trajectory\n\n\tsize_t num_points = uncorrected_energies.size();\n\tstd::vector<double> grad;\n\tstd::vector<double> corr_grad;\n\tdouble step = states[1].eta;\n\n\tgrad.push_back(0.0);\n\tcorrected_energies.push_back(uncorrected_energies[0]);\n\tfor (int i=1;i<uncorrected_energies.size()-1;i++)\n\t{\n\t\tstd::complex<double> log_velo = states[i].eta*(uncorrected_energies[i+1]-uncorrected_energies[i-1])/(2.0*step);\n\t    grad.push_back(std::abs(log_velo));\n\t    corrected_energies.push_back(uncorrected_energies[i]-log_velo);\n\t}\n\t// last point\n\tstd::complex<double> last_deriv = states[num_points-1].eta*(uncorrected_energies[num_points-1]-uncorrected_energies[num_points-2])/step;\n\tgrad.push_back(std::abs(last_deriv));\n\tcorrected_energies.push_back(uncorrected_energies[num_points-1]-last_deriv);\n\n\tcorr_grad.push_back(0.0);\n\tfor (int i=1;i<corrected_energies.size();i++)\n\t    corr_grad.push_back(states[i].eta*std::abs((corrected_energies[i+1]-corrected_energies[i-1])/(2.0*step)));\n\n\tdouble min_deriv=1000;\n\tsize_t min_idx = 0;\n\tdouble min_deriv_corr=1000;\n\tsize_t min_idx_corr;\n\tfor(size_t i=10;i<grad.size()-1;i++)\n\t{\n\t\tif(grad[i]<min_deriv)\n\t\t{\n\t\t\tmin_deriv = grad[i];\n\t\t\tmin_idx = i;\n\t\t}\n\t\tif(corr_grad[i]<min_deriv_corr)\n\t\t{\n\t\t\tmin_deriv_corr=corr_grad[i];\n\t\t\tmin_idx_corr = i;\n\t\t}\n\t}\n\n\n\t//uncorrected results\n\tstd::cout << \"Results from uncorrected trajectory:\" << std::endl;\n\tstd::cout << \"Uncorrected energy: \" << std::noshowpos << uncorrected_energies[min_idx] << std::endl;\n\tstd::cout << \"Eta: \" << states[min_idx].eta << \" Logarithmic velocity: \" << min_deriv << std::endl;\n\tuc_opt_eta = states[min_idx].eta;\n\tuc_opt = uncorrected_energies[min_idx];\n\n\t// corrected results\n\tstd::cout << \"Results from corrected trajectory:\" << std::endl;\n\tstd::cout << \"Corrected energy: \" << std::noshowpos << corrected_energies[min_idx_corr] << std::endl;\n\tstd::cout << \"Eta: \" << states[min_idx_corr].eta << \" Logarithmic velocity: \" << min_deriv_corr << std::endl;\n\tcorr_opt_eta = states[min_idx].eta;\n\tcorr_opt = uncorrected_energies[min_idx];\n}\n", "meta": {"hexsha": "ac3837c2ea78b08518ff2f4b8bca0f7ed7eea061", "size": 6586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "opencap/src/TrajectoryAnalysis.cpp", "max_stars_repo_name": "SoubhikM/opencap", "max_stars_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2020-08-24T15:06:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T20:51:26.000Z", "max_issues_repo_path": "opencap/src/TrajectoryAnalysis.cpp", "max_issues_repo_name": "SoubhikM/opencap", "max_issues_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 21.0, "max_issues_repo_issues_event_min_datetime": "2020-08-04T07:03:53.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T22:37:39.000Z", "max_forks_repo_path": "opencap/src/TrajectoryAnalysis.cpp", "max_forks_repo_name": "SoubhikM/opencap", "max_forks_repo_head_hexsha": "08706ea07e576c96eed32dc224070201781981b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-09-15T20:38:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T18:54:52.000Z", "avg_line_length": 31.8164251208, "max_line_length": 137, "alphanum_fraction": 0.7017916793, "num_tokens": 1868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24457149227526195}}
{"text": "#include \"nodehyperplane.h\"\n#include \"nodegini.h\"\n#include \"nodeinfogain.h\"\n#include \"utilities.h\"\n#include <boost/foreach.hpp>\n#include <algorithm>\n#include <boost/lexical_cast.hpp>\n\n#ifdef WIN32\ninline double round(double x)\n{\n\treturn (x-floor(x))>0.5 ? ceil(x) : floor(x);\n}\n#endif\nusing namespace std;\n\nNodeHyperPlane::NodeHyperPlane(const HyperParameters &hp, int depth) : Node(hp, depth), m_bestThreshold( 0.0 )\n{\n}\n\nNodeHyperPlane::NodeHyperPlane(const HyperParameters &hp, int depth, int reset) : Node(hp, depth, reset), m_bestThreshold( 0.0 )\n{\n}\n\nNodeHyperPlane::NodeHyperPlane(const HyperParameters &hp, int reset, const xmlNodePtr nodeNode) : Node(hp,0,reset)\n{\n\tm_isLeaf = (readStringProp(nodeNode,\"isLeaf\") == \"true\") ? true : false;\n\n\tif (m_isLeaf)\n\t{\n\t\tm_nodeLabel = readIntProp( nodeNode, \"label\", 0 );\n\t\txmlNodePtr cur = nodeNode->xmlChildrenNode;\n\t\twhile ( cur != 0 )\n\t\t{\n\t\t\tif ( xmlStrcmp( cur->name, reinterpret_cast<const xmlChar*>( \"confidence\" ) ) == 0 )\n\t\t\t{\n\t\t\t\tm_nodeConf.push_back( static_cast<float>(readDoubleProp( cur, \"conf\", 0 )) );\n\t\t\t}\n\t\t\tcur = cur->next;\n\t\t}\n\t}\n\telse\n\t{\n\t\txmlNodePtr cur = nodeNode->xmlChildrenNode;\n\t\twhile ( cur != 0 )\n\t\t{\n\t\t\tif ( xmlStrcmp( cur->name, reinterpret_cast<const xmlChar*>( \"feature\" ) ) == 0 )\n\t\t\t{\n                for (int i=0;i<m_hp.numRandomFeatures;++i){\n                    string s = \"feat\"+boost::lexical_cast<string>( i );\n                    int tmp = readIntProp( cur, s.c_str(), 0 );\n                    m_bestFeatures[i]=tmp;\n                    string s2 = \"weight\"+boost::lexical_cast<string>( i );\n                    double tmpW=(float)readDoubleProp(cur,s2.c_str(), 0);\n                    m_bestWeights[i]=tmpW;\n                }\n\t\t\t\t\n\t\t\t\tm_bestThreshold = (float)readDoubleProp( cur, \"threshold\", 0 );\n\t\t\t}\n\t\t\telse if ( xmlStrcmp( cur->name, reinterpret_cast<const xmlChar*>( \"node\" ) ) == 0 )\n\t\t\t{\n\t\t\t\tconst std::string childNode = readStringProp(cur,\"child\");\n\t\t\t\tif ( childNode == \"left\" )\n\t\t\t\t{\n\t\t\t\t\tconst std::string type = readStringProp(cur,\"type\");\n\t\t\t\t\tif (type == NODE_GINI)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_leftChildNode = NodeGini::Ptr(new NodeGini(m_hp,-1,cur));\n\t\t\t\t\t}\n\t\t\t\t\telse if (type == NODE_INFO_GAIN)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_leftChildNode = NodeInfoGain::Ptr(new NodeInfoGain(m_hp,-1, cur));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tconst std::string type = readStringProp(nodeNode,\"type\");\n\t\t\t\t\tif (type == NODE_GINI)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_rightChildNode = NodeGini::Ptr(new NodeGini(m_hp,-1,cur));\n\t\t\t\t\t}\n\t\t\t\t\telse if (type == NODE_INFO_GAIN)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_rightChildNode = NodeInfoGain::Ptr(new NodeInfoGain(m_hp,-1,cur));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcur = cur->next;\n\t\t}\n\t}\n}\n\nxmlNodePtr NodeHyperPlane::saveFeature() const\n{\n\txmlNodePtr node = xmlNewNode( NULL, reinterpret_cast<const xmlChar*>( \"feature\" ) );\n    //std::cout<<m_hp.numRandomFeatures<<\" \"<< m_bestFeatures.size()<<std::endl;\n    for (int i=0;i<m_hp. numRandomFeatures;++i){\n        string s = \"feat\"+boost::lexical_cast<string>( i );\n        addIntProp(node, s.c_str(), m_bestFeatures[i]);\n        string s2 = \"weight\"+boost::lexical_cast<string>( i );\n        addDoubleProp(node, s2.c_str(), m_bestWeights[i]);\n    }\n\taddDoubleProp(node, \"threshold\", m_bestThreshold);\n\n\treturn node;\n}\n\n\nxmlNodePtr NodeHyperPlane::save() const\n{\n\txmlNodePtr node = xmlNewNode( NULL, reinterpret_cast<const xmlChar*>( \"node\" ) );\n\txmlNewProp( node, reinterpret_cast<const xmlChar*>( \"type\" ),\n\t\t\treinterpret_cast<const xmlChar*>( NODE_GINI ) );\n\tconst char* isLeaf = (m_isLeaf) ? \"true\" : \"false\";\n\txmlNewProp( node, reinterpret_cast<const xmlChar*>( \"isLeaf\" ),\n\t\t\treinterpret_cast<const xmlChar*>( isLeaf ) );\n\tif (!m_isLeaf)\n\t{\n\t\txmlAddChild(node, saveFeature());\n\t\txmlNodePtr leftChildNode = m_leftChildNode->save();\n\t\txmlNewProp( leftChildNode, reinterpret_cast<const xmlChar*>( \"child\" ),\n\t\t\t\treinterpret_cast<const xmlChar*>( LEFT_CHILD_NODE ) );\n\t\txmlAddChild( node, leftChildNode );\n\n\t\txmlNodePtr rightChildNode = m_rightChildNode->save();\n\t\txmlNewProp( rightChildNode, reinterpret_cast<const xmlChar*>( \"child\" ),\n\t\t\t\treinterpret_cast<const xmlChar*>( RIGHT_CHILD_NODE ) );\n\t\txmlAddChild( node, rightChildNode );\n\t}\n\telse\n\t{\n\t\taddIntProp( node, \"label\", m_nodeLabel);\n\t\tstd::vector<float>::const_iterator it(m_nodeConf.begin()),end(m_nodeConf.end());\n\t\tint idx = 0;\n\t\tfor (;it != end;it++,idx++)\n\t\t{\n\t\t\txmlAddChild(node,saveConfidence(idx,*it));\n\t\t}\n\t}\n\n\treturn node;\n}\n\nstd::pair<float, float> NodeHyperPlane::calcGiniAndThreshold(const std::vector<int>& labels,\n\t\tconst std::vector<std::pair<float, int> >& responses)\n{\n\t// Initialize the counters: left takes all at the begining\n\tdouble DGini, LGini, RGini, LTotal, RTotal, bestW0 = 0, bestDGini = 1e10;\n\tstd::vector<double> LCount(m_hp.numClasses, 0.0), RCount(m_hp.numClasses, 0.0);\n\n\tif (m_hp.isExtreme)\n\t{\n\t\tstd::vector<std::pair<float, int> >::const_iterator resIt(responses.begin()), resEnd(responses.end());\n\t\tbestW0 = 2.0 * randomDouble( 1.0 ) - 1.0;\n\t\tRTotal = 0;\n\t\tLTotal = 0;\n\t\tfor (; resIt != resEnd; resIt++)\n\t\t{\n\t\t\tif (resIt->first > bestW0)\n\t\t\t{\n\t\t\t\tRTotal++;\n\t\t\t\tRCount[labels[resIt->second]]++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLTotal++;\n\t\t\t\tLCount[labels[resIt->second]]++;\n\t\t\t}\n\t\t}\n\n\t\tLGini = 0;\n\t\tRGini = 0;\n\t\tstd::vector<double>::iterator LIt = LCount.begin(), RIt = RCount.begin(), end = LCount.end(), REnd = RCount.end();\n\t\tfor (; LIt != end; LIt++, RIt++)      // Calculate Gini index\n\t\t\t\t{\n\t\t\tif (LTotal)\n\t\t\t{\n\t\t\t\tLGini += (*LIt/LTotal)*(1 - *LIt/LTotal);\n\t\t\t}\n\t\t\tif (RTotal)\n\t\t\t{\n\t\t\t\tRGini += (*RIt/RTotal)*(1 - *RIt/RTotal);\n\t\t\t}\n\t\t\t\t}\n\n\t\tbestDGini = (LTotal*LGini + RTotal*RGini)/responses.size();\n\t}\n\telse\n\t{\n\t\tRTotal = responses.size();\n\t\tLTotal = 0;\n\n\t\t// Count the number of samples in each class\n\t\tstd::vector<std::pair<float, int> >::const_iterator resIt(responses.begin()), resEnd(responses.end()), tmpResIt;\n\t\tfor (; resIt != resEnd; resIt++)\n\t\t{\n\t\t\tRCount[labels[resIt->second]]++;\n\t\t}\n\n\t\t// Loop over the sorted values and find the min DGini\n\t\tstd::vector<double>::iterator LIt = LCount.begin(), RIt = RCount.begin(), end = LCount.end(), REnd = RCount.end();\n\t\tresIt = responses.begin();\n\t\t++resIt;\n\t\tfor (; resIt != resEnd; resIt++)\n\t\t{\n\t\t\ttmpResIt = resIt;\n\t\t\t--tmpResIt;\n\n\t\t\tRTotal--;\n\t\t\tLTotal++;\n\t\t\tRCount[labels[tmpResIt->second]]--;\n\t\t\tLCount[labels[tmpResIt->second]]++;\n\n\t\t\tif (resIt->first != tmpResIt->first)\n\t\t\t{\n\t\t\t\tLGini = 0;\n\t\t\t\tRGini = 0;\n\t\t\t\tLIt = LCount.begin();\n\t\t\t\tRIt = RCount.begin();\n\t\t\t\tfor (; LIt != end; LIt++, RIt++)      // Calculate Gini index\n\t\t\t\t\t\t{\n\t\t\t\t\tLGini += (*LIt/LTotal)*(1 - *LIt/LTotal);\n\t\t\t\t\tRGini += (*RIt/RTotal)*(1 - *RIt/RTotal);\n\t\t\t\t\t\t}\n\n\t\t\t\tDGini = (LTotal*LGini + RTotal*RGini)/responses.size();\n\t\t\t\tif (DGini < bestDGini)\n\t\t\t\t{\n\t\t\t\t\tbestDGini = DGini;\n\t\t\t\t\tbestW0 = (resIt->first + tmpResIt->first)*0.5;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn std::pair<float,float>((float)bestDGini,(float)bestW0);\n}\n\nstd::pair<float, float> NodeHyperPlane::calcInfoGainAndThreshold(const std::vector<int>& labels,\n\t\tconst std::vector<std::pair<float, int> >& responses)\n{\n\t// Initialize the counters: left takes all at the begining\n\tdouble DInfo, LInfo, RInfo, LTotal, RTotal, bestW0 = 0.0, bestDInfo = 1e10;\n\tstd::vector<double> LCount(m_hp.numClasses, 0.0), RCount(m_hp.numClasses, 0.0);\n\n\tRTotal = responses.size();\n\tLTotal = 0.0;\n\t// Count the number of samples in each class\n\tstd::vector<std::pair<float, int> >::const_iterator resIt(responses.begin()), resEnd(responses.end()), tmpResIt;\n\tfor (; resIt != resEnd; resIt++)\n\t{\n\t\tRCount[labels[resIt->second]]++;\n\t}\n\n\t// Loop over the sorted values and find the max DInfo\n\tstd::vector<double>::iterator LIt = LCount.begin(), RIt = RCount.begin(), end = LCount.end(), REnd = RCount.end();\n\tresIt = responses.begin();\n\t++resIt;\n\tfor (; resIt != resEnd; resIt++)\n\t{\n\t\ttmpResIt = resIt;\n\t\t--tmpResIt;\n\n\t\tRTotal--;\n\t\tLTotal++;\n\t\tRCount[labels[tmpResIt->second]]--;\n\t\tLCount[labels[tmpResIt->second]]++;\n\n\t\tif (resIt->first != tmpResIt->first)\n\t\t{\n\t\t\tLInfo = 0.0;\n\t\t\tRInfo = 0.0;\n\t\t\tLIt = LCount.begin();\n\t\t\tRIt = RCount.begin();\n\t\t\tfor (; LIt != end; LIt++, RIt++)      // Calculate Info index\n\t\t\t\t\t{\n\t\t\t\tif (*LIt)\n\t\t\t\t{\n\t\t\t\t\tLInfo -= (*LIt/LTotal)*log(*LIt/LTotal);\n\t\t\t\t}\n\t\t\t\tif (*RIt)\n\t\t\t\t{\n\t\t\t\t\tRInfo -= (*RIt/RTotal)*log(*RIt/RTotal);\n\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\tDInfo = (LTotal*LInfo + RTotal*RInfo)/responses.size();\n\t\t\tif (DInfo < bestDInfo)\n\t\t\t{\n\t\t\t\tbestDInfo = DInfo;\n\t\t\t\tbestW0 = (resIt->first + tmpResIt->first)*0.5;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn std::pair<float,float>((float)bestDInfo,(float)bestW0);\n}\n\nstd::pair<float, float> NodeHyperPlane::calcInfoGainAndThreshold(const std::vector<int>& labels, const std::vector<double>& weights,\n\t\tconst std::vector<std::pair<float, int> >& responses)\n{\n\t// Initialize the counters: left takes all at the begining\n\tdouble DInfo, LInfo, RInfo, LTotal, RTotal, bestW0 = 0.0, bestDInfo = 1e10;\n\tstd::vector<double> LCount(m_hp.numClasses, 0.0), RCount(m_hp.numClasses, 0.0);\n\n\tRTotal = 0.0;\n\tLTotal = 0.0;\n\t// Count the number of samples in each class\n\tstd::vector<std::pair<float, int> >::const_iterator resIt(responses.begin()), resEnd(responses.end()), tmpResIt;\n\tfor (; resIt != resEnd; resIt++)\n\t{\n\t\tRCount[labels[resIt->second]] += weights[resIt->second];\n\t\tRTotal += weights[resIt->second];\n\t}\n\n\t// Loop over the sorted values and find the max DInfo\n\tstd::vector<double>::iterator LIt = LCount.begin(), RIt = RCount.begin(), end = LCount.end(), REnd = RCount.end();\n\tresIt = responses.begin();\n\t++resIt;\n\tfor (; resIt != resEnd; resIt++)\n\t{\n\t\ttmpResIt = resIt;\n\t\t--tmpResIt;\n\n\t\tRTotal -= weights[tmpResIt->second];\n\t\tLTotal += weights[tmpResIt->second];\n\t\tRCount[labels[tmpResIt->second]] -= weights[tmpResIt->second];\n\t\tLCount[labels[tmpResIt->second]] += weights[tmpResIt->second];\n\n\t\tif (resIt->first != tmpResIt->first)\n\t\t{\n\t\t\tLInfo = 0.0;\n\t\t\tRInfo = 0.0;\n\t\t\tLIt = LCount.begin();\n\t\t\tRIt = RCount.begin();\n\t\t\tfor (; LIt != end; LIt++, RIt++)      // Calculate Info index\n\t\t\t\t\t{\n\t\t\t\tif (*LIt)\n\t\t\t\t{\n\t\t\t\t\tLInfo -= (*LIt/LTotal)*log(*LIt/LTotal);\n\t\t\t\t}\n\t\t\t\tif (*RIt)\n\t\t\t\t{\n\t\t\t\t\tRInfo -= (*RIt/RTotal)*log(*RIt/RTotal);\n\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\tDInfo = (LTotal*LInfo + RTotal*RInfo)/(LTotal + RTotal);\n\t\t\tif (DInfo < bestDInfo)\n\t\t\t{\n\t\t\t\tbestDInfo = DInfo;\n\t\t\t\tbestW0 = (resIt->first + tmpResIt->first)*0.5;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn std::pair<float,float>((float)bestDInfo,(float)bestW0);\n}\n\n\nstd::pair<float, float> NodeHyperPlane::calcGiniAndThreshold(const std::vector<int>& labels, const std::vector<double>& weights,\n\t\tconst std::vector<std::pair<float, int> >& responses, const bool useUnlabeledData)\n{\n\t// Initialize the counters: left takes all at the begining\n\tdouble DGini, LGini, RGini, LTotal, RTotal, bestW0 = 0, bestDGini = 1e10;\n\tstd::vector<double> LCount(m_hp.numClasses, 0.0), RCount(m_hp.numClasses, 0.0);\n\n\tRTotal = 0;\n\tLTotal = 0;\n\n\t// Count the number of samples in each class\n\tstd::vector<std::pair<float, int> >::const_iterator resIt(responses.begin()), resEnd(responses.end()), tmpResIt;\n\tfor (; resIt != resEnd; resIt++)\n\t{\n\t\tif (useUnlabeledData || resIt->second < m_hp.numLabeled)\n\t\t{\n\t\t\tRCount[labels[resIt->second]] += weights[resIt->second];\n\t\t\tRTotal += weights[resIt->second];\n\t\t}\n\t}\n\n\t// Loop over the sorted values and find the min DGini\n\tstd::vector<double>::iterator LIt = LCount.begin(), RIt = RCount.begin(), end = LCount.end(), REnd = RCount.end();\n\tresIt = responses.begin();\n\t++resIt;\n\tfor (; resIt != resEnd; resIt++)\n\t{\n\t\tif (useUnlabeledData || resIt->second < m_hp.numLabeled)\n\t\t{\n\t\t\ttmpResIt = resIt;\n\t\t\t--tmpResIt;\n\n\t\t\tRTotal -= weights[tmpResIt->second];\n\t\t\tLTotal += weights[tmpResIt->second];\n\t\t\tRCount[labels[tmpResIt->second]] -= weights[tmpResIt->second];\n\t\t\tLCount[labels[tmpResIt->second]] += weights[tmpResIt->second];\n\n\t\t\tif (resIt->first != tmpResIt->first)\n\t\t\t{\n\t\t\t\tLGini = 0;\n\t\t\t\tRGini = 0;\n\t\t\t\tLIt = LCount.begin();\n\t\t\t\tRIt = RCount.begin();\n\t\t\t\tfor (; LIt != end; LIt++, RIt++)      // Calculate Gini index\n\t\t\t\t\t\t{\n\t\t\t\t\tLGini += (*LIt/LTotal)*(1 - *LIt/LTotal);\n\t\t\t\t\tRGini += (*RIt/RTotal)*(1 - *RIt/RTotal);\n\t\t\t\t\t\t}\n\n\t\t\t\tDGini = (LTotal*LGini + RTotal*RGini)/(LTotal + RTotal);\n\t\t\t\tif (DGini < bestDGini)\n\t\t\t\t{\n\t\t\t\t\tbestDGini = DGini;\n\t\t\t\t\tbestW0 = (resIt->first + tmpResIt->first)*0.5;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn std::pair<float,float>((float)bestDGini,(float)bestW0);\n}\n\n\nvoid NodeHyperPlane::findHypotheses(const matrix<float>& data, const std::vector<int>& labels,\n\t\tconst std::vector<int>& inBagSamples, const std::vector<int>& randFeatures, int numTries)\n{\n\tstd::vector<double> gini(m_hp.numRandomFeatures), thresholds(m_hp.numRandomFeatures);\n\tstd::vector<int>::const_iterator it(randFeatures.begin());\n\tstd::vector<int>::const_iterator end(randFeatures.end());\n\n\tstd::vector<int>::const_iterator bagIt;\n\tstd::vector<int>::const_iterator bagEnd(inBagSamples.end());\n\n\tdouble bestDGini = 1e10, bestThreshold = 0;\n\tstd::pair<float,float> curGiniThresh;\n\tstd::vector<std::pair<float, int> > responses;\n\tstd::vector<float> bestWeights(randFeatures.size(),0.0);\n\tstd::vector<float> tmpWeights(randFeatures.size(),0.0);\n\tfloat tmp = 0.0;\n\tfor ( int i = 0; i < numTries; i++)\n\t{\n\t\tfillWithRandomNumbers(tmpWeights);\n\t\tresponses.clear();\n\t\tresponses.reserve(inBagSamples.size());\n\t\tbagIt = inBagSamples.begin();\n\t\twhile ( bagIt != bagEnd )\n\t\t{\n\t\t\ttmp = 0.0;\n\t\t\tint counter = 0;\n\t\t\tBOOST_FOREACH(int feat, randFeatures)\n\t\t\t{\n\t\t\t\ttmp += data(*bagIt,feat)*tmpWeights[counter];\n\t\t\t\tcounter++;\n\t\t\t}\n\n\t\t\tresponses.push_back(std::pair<float, int>(tmp,*bagIt));\n\t\t\t++bagIt;\n\t\t}\n\n\t\tsort(responses.begin(), responses.end());\n\n\t\tif (m_hp.useInfoGain)\n\t\t{\n\t\t\tcurGiniThresh = calcInfoGainAndThreshold(labels, responses);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcurGiniThresh = calcGiniAndThreshold(labels, responses);\n\t\t}\n\n\t\tif (curGiniThresh.first < bestDGini)\n\t\t{\n\t\t\tbestDGini = curGiniThresh.first;\n\t\t\tbestThreshold = curGiniThresh.second;\n\t\t\tbestWeights = tmpWeights;\n\t\t}\n\t}\n\n\tm_bestWeights = bestWeights;\n\tm_bestFeatures = randFeatures;\n\tm_bestThreshold = (float) bestThreshold;\n}\n\nvoid NodeHyperPlane::findHypothesesLU(const matrix<float>& data, const std::vector<int>& labels,\n\t\tconst std::vector<int>& inBagSamples, const std::vector<int>& randFeatures, int numTries)\n{\n\tstd::vector<double> gini(m_hp.numRandomFeatures), thresholds(m_hp.numRandomFeatures);\n\tstd::vector<int>::const_iterator it(randFeatures.begin());\n\tstd::vector<int>::const_iterator end(randFeatures.end());\n\n\tstd::vector<int>::const_iterator bagIt;\n\tstd::vector<int>::const_iterator bagEnd(inBagSamples.end());\n\n\tdouble bestDGini = 1e10, bestThreshold = 0;\n\tstd::pair<float,float> curGiniThresh;\n\tstd::vector<std::pair<float, int> > responses;\n\tstd::vector<float> bestWeights(randFeatures.size(),0.0);\n\tstd::vector<float> tmpWeights(randFeatures.size(),0.0);\n\tfloat tmp = 0.0;\n\tfor ( int i = 0; i < numTries; i++)\n\t{\n\t\tfillWithRandomNumbers(tmpWeights);\n\t\tresponses.clear();\n\t\tresponses.reserve(inBagSamples.size());\n\t\tbagIt = inBagSamples.begin();\n\t\twhile ( bagIt != bagEnd )\n\t\t{\n\t\t\ttmp = 0.0;\n\t\t\tint counter = 0;\n\t\t\tBOOST_FOREACH(int feat, randFeatures)\n\t\t\t{\n\t\t\t\ttmp += data(*bagIt,feat)*tmpWeights[counter];\n\t\t\t\tcounter++;\n\t\t\t}\n\n\t\t\tresponses.push_back(std::pair<float, int>(tmp,*bagIt));\n\t\t\t++bagIt;\n\t\t}\n\n\t\tsort(responses.begin(), responses.end());\n\n\t\tif (inBagSamples[0] < m_hp.numLabeled)\n\t\t{\n\t\t\tcurGiniThresh = calcGiniAndThreshold(labels, responses);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcurGiniThresh = calcClusterScoreAndThreshold(data, inBagSamples, responses);\n\t\t}\n\t\tif (curGiniThresh.first < bestDGini)\n\t\t{\n\t\t\tbestDGini = curGiniThresh.first;\n\t\t\tbestThreshold = curGiniThresh.second;\n\t\t\tbestWeights = tmpWeights;\n\t\t}\n\t}\n\n\tm_bestWeights = bestWeights;\n\tm_bestFeatures = randFeatures;\n\tm_bestThreshold = (float) bestThreshold;\n}\n\nstd::pair<float, float> NodeHyperPlane::calcClusterScoreAndThreshold(const matrix<float>& data, const std::vector<int>& inBagSamples,\n\t\tconst std::vector<double>& weights,\n\t\tconst std::vector<std::pair<float, int> >& responses)\n{\n\t// Find the mid-point using responsess\n\t\t\tint numResponse = responses.size();\n\tint midPointIndex = (int) round(numResponse/2 - 1);\n\tfloat threshold = (responses[midPointIndex].first + responses[midPointIndex + 1].first)/2;\n\n\t// Calculate the weighted cluster center for left and right splits\n\tdouble LWeight = 0, RWeight = 0;\n\tstd::vector<float> LCenter(data.size2(), 0.0), RCenter(data.size2(), 0.0);\n\tfor (int m = 0; m < (int) data.size2(); m++)\n\t{\n\t\tfor (int n = 0; n < midPointIndex; n++)\n\t\t{\n\t\t\tLCenter[m] += (float)weights[responses[n].second]*data(responses[n].second, m);\n\t\t\tif (m == 0)\n\t\t\t{\n\t\t\t\tLWeight += weights[responses[n].second];\n\t\t\t}\n\t\t}\n\t\tLCenter[m] /= (float)LWeight;\n\n\t\tfor (int n = midPointIndex; n < (int) responses.size(); n++)\n\t\t{\n\t\t\tRCenter[m] += (float)weights[responses[n].second]*data(responses[n].second, m);\n\t\t\tif (m == 0)\n\t\t\t{\n\t\t\t\tRWeight += weights[responses[n].second];\n\t\t\t}\n\t\t}\n\t\tRCenter[m] /= (float)RWeight;\n\t}\n\n\t// Calculate the weighted distance from each point to the centers\n\tfloat LScore = 0, RScore = 0;\n\tfor (int m = 0; m < (int) data.size2(); m++)\n\t{\n\t\tfor (int n = 0; n < midPointIndex; n++)\n\t\t{\n\t\t\tLScore += weights[responses[n].second]*pow((double) (data(responses[n].second, m) - LCenter[m]), 2.0);\n\t\t}\n\t\tLScore /= (float)LWeight;\n\t\tfor (int n = midPointIndex; n < (int) responses.size(); n++)\n\t\t{\n\t\t\tRScore += (float)weights[responses[n].second]*pow((double) (data(responses[n].second, m) - RCenter[m]), 2.0);\n\t\t}\n\t\tRScore /= (float)RWeight;\n\t}\n\n\treturn std::pair<float,float>(0.5f*(LScore + RScore), threshold);\n}\n\nstd::pair<float, float> NodeHyperPlane::calcClusterScoreAndThreshold(const matrix<float>& data, const std::vector<int>& inBagSamples,\n\t\tconst std::vector<std::pair<float, int> >& responses)\n{\n\t// Find the mid-point using responsess\n\tint numResponse = responses.size();\n\tint midPointIndex = (int) round(numResponse/2 - 1);\n\tfloat threshold = (responses[midPointIndex].first + responses[midPointIndex + 1].first)/2;\n\n\t// Calculate the weighted cluster center for left and right splits\n\tdouble LWeight = 0, RWeight = 0;\n\tstd::vector<float> LCenter(data.size2(), 0.0), RCenter(data.size2(), 0.0);\n\tfor (int m = 0; m < (int) data.size2(); m++)\n\t{\n\t\tfor (int n = 0; n < midPointIndex; n++)\n\t\t{\n\t\t\tLCenter[m] += data(responses[n].second, m);\n\t\t\tif (m == 0)\n\t\t\t{\n\t\t\t\tLWeight++;\n\t\t\t}\n\t\t}\n\t\tLCenter[m] /= LWeight;\n\n\t\tfor (int n = midPointIndex; n < (int) responses.size(); n++)\n\t\t{\n\t\t\tRCenter[m] += data(responses[n].second, m);\n\t\t\tif (m == 0)\n\t\t\t{\n\t\t\t\tRWeight++;\n\t\t\t}\n\t\t}\n\t\tRCenter[m] /= RWeight;\n\t}\n\n\t// Calculate the weighted distance from each point to the centers\n\tfloat LScore = 0, RScore = 0;\n\tfor (int m = 0; m < (int) data.size2(); m++)\n\t{\n\t\tfor (int n = 0; n < midPointIndex; n++)\n\t\t{\n\t\t\tLScore += pow((double) (data(responses[n].second, m) - LCenter[m]), 2.0);\n\t\t}\n\t\tLScore /= LWeight;\n\t\tfor (int n = midPointIndex; n < (int) responses.size(); n++)\n\t\t{\n\t\t\tRScore += pow((double) (data(responses[n].second, m) - RCenter[m]), 2.0);\n\t\t}\n\t\tRScore /= RWeight;\n\t}\n\n\treturn std::pair<float,float>(0.5*(LScore + RScore), threshold);\n}\n\nvoid NodeHyperPlane::findHypotheses(const matrix<float>& data, const std::vector<int>& labels,\n\t\tconst std::vector<double>& weights,\n\t\tconst std::vector<int>& inBagSamples, const std::vector<int>& randFeatures, int numTries)\n{\n\tstd::vector<double> gini(m_hp.numRandomFeatures), thresholds(m_hp.numRandomFeatures);\n\tstd::vector<int>::const_iterator it(randFeatures.begin());\n\tstd::vector<int>::const_iterator end(randFeatures.end());\n\tstd::vector<int>::const_iterator bagIt;\n\tstd::vector<int>::const_iterator bagEnd(inBagSamples.end());\n\n\tdouble bestDGini = 1e10, bestThreshold = 0.0;\n\tstd::pair<float,float> curGiniThresh;\n\tstd::vector<std::pair<float, int> > responses;\n\n\tstd::vector<float> bestWeights(randFeatures.size(),0.0);\n\tstd::vector<float> tmpWeights(randFeatures.size(),0.0);\n\tfloat tmp = 0.0;\n\tbool doClustering = clusterOrGini(), useUnlabeledData = true;\n\tfor ( int i = 0; i < numTries; i++)\n\t{\n\t\tfillWithRandomNumbers(tmpWeights);\n\t\tresponses.clear();\n\t\tresponses.reserve(inBagSamples.size());\n\t\tbagIt = inBagSamples.begin();\n\t\twhile ( bagIt != bagEnd )\n\t\t{\n\t\t\ttmp = 0.0;\n\t\t\tint counter = 0;\n\t\t\tBOOST_FOREACH(int feat, randFeatures)\n\t\t\t{\n\t\t\t\ttmp += data(*bagIt,feat)*tmpWeights[counter];\n\t\t\t\tcounter++;\n\t\t\t}\n\n\t\t\tresponses.push_back(std::pair<float, int>(tmp,*bagIt));\n\t\t\t++bagIt;\n\t\t}\n\t\tsort(responses.begin(), responses.end());\n\n\t\tif (!doClustering)\n\t\t{\n\t\t\tif (m_hp.useInfoGain)\n\t\t\t{\n\t\t\t\tcurGiniThresh = calcInfoGainAndThreshold(labels, weights, responses);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcurGiniThresh = calcGiniAndThreshold(labels, weights, responses, useUnlabeledData);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcurGiniThresh = calcClusterScoreAndThreshold(data, inBagSamples, weights, responses);\n\t\t}\n\n\t\tif (curGiniThresh.first < bestDGini)\n\t\t{\n\t\t\tbestDGini = curGiniThresh.first;\n\t\t\tbestThreshold = curGiniThresh.second;\n\t\t\tbestWeights = tmpWeights;\n\t\t}\n\t}\n\n\tm_bestFeatures = randFeatures;\n\tm_bestWeights = bestWeights;\n\tm_bestThreshold = (float) bestThreshold;\n}\n\nNODE_TRAIN_STATUS NodeHyperPlane::trainLU(const matrix<float>& data, const std::vector<int>& labels,\n\t\tstd::vector<int>& inBagSamples, matrix<float>& confidences, std::vector<int>& predictions)\n{\n\tbool doSplit = shouldISplitLU(labels,inBagSamples);\n\tNODE_TRAIN_STATUS myTrainingStatus = IS_NOT_LEAF;\n\n\tif ( doSplit )\n\t{\n\t\tm_isLeaf = false;\n\n\t\t//train here the node: Select random features and evaluate them\n\t\tstd::vector<int> randFeatures = randPerm(data.size2(), m_hp.numProjFeatures );\n\t\tint numTries = m_hp.numRandomFeatures;// * (m_depth+1);\n\t\tfindHypothesesLU(data, labels, inBagSamples, randFeatures, numTries);\n\t\tif (m_hp.verbose)\n\t\t{\n\t\t\tcout << \"Node #: \" << m_nodeIndex;\n\t\t\tcout << \" and the threshold is: \" << m_bestThreshold << \" at depth \" << m_depth << endl;\n\t\t}\n\n\t\t// split the data\n\t\tstd::vector<int> leftNodeSamples, rightNodeSamples;\n\t\tevalNode(data,inBagSamples,leftNodeSamples,rightNodeSamples);\n\n\t\t// pass them to the left and right child, respectively\n\t\tm_leftChildNode = Ptr(new NodeHyperPlane(m_hp,m_depth + 1));\n\t\tm_rightChildNode = Ptr(new NodeHyperPlane(m_hp,m_depth + 1));\n\n\t\tm_leftChildNode->train(data,labels,leftNodeSamples,confidences,predictions);\n\t\tm_rightChildNode->train(data,labels,rightNodeSamples,confidences,predictions);\n\t}\n\telse\n\t{\n\t\tif (m_hp.verbose)\n\t\t{\n\t\t\tcout << \"Node #: \" << m_nodeIndex << \" is terminal, at depth \" << m_depth << endl;\n\t\t}\n\n\t\t// calc confidence, labels, etc\n\t\tm_isLeaf = true;\n\t\tmyTrainingStatus = IS_LEAF;\n\t\tm_nodeConf.resize(m_hp.numClasses, 0.0);\n\t\tint numNodeLabeled = 0;\n\t\tBOOST_FOREACH(int n, inBagSamples)\n\t\t{\n\t\t\tif (n < m_hp.numLabeled)\n\t\t\t{\n\t\t\t\tm_nodeConf[labels[n]]++;\n\t\t\t\tnumNodeLabeled++;\n\t\t\t}\n\t\t}\n\n\t\tint bestClass = 0, tmpN = 0;\n\t\tfloat bestConf = 0;\n\t\tstd::vector<float>::iterator confItr = m_nodeConf.begin(), confEnd = m_nodeConf.end();\n\t\tfor (; confItr != confEnd; confItr++)\n\t\t{\n\t\t\tif (numNodeLabeled)\n\t\t\t{\n\t\t\t\t*confItr /= numNodeLabeled;\n\t\t\t\tif (*confItr > bestConf)\n\t\t\t\t{\n\t\t\t\t\tbestConf = *confItr;\n\t\t\t\t\tbestClass = tmpN;\n\t\t\t\t}\n\t\t\t\ttmpN++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t*confItr = 1.0/m_hp.numClasses;\n\t\t\t}\n\t\t}\n\t\tm_nodeLabel = bestClass;\n\n\t\tBOOST_FOREACH(int n, inBagSamples)\n\t\t{\n\t\t\tpredictions[n] = m_nodeLabel;\n\t\t\ttmpN = 0;\n\t\t\tBOOST_FOREACH(float conf, m_nodeConf)\n\t\t\t{\n\t\t\t\tconfidences(n, tmpN) = conf;\n\t\t\t\ttmpN++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn myTrainingStatus;\n}\n\nbool NodeHyperPlane::clusterOrGini()\n{\n\treturn false;\n}\n\nvoid NodeHyperPlane::evalNode(const matrix<float>& data, const std::vector<int>& inBagSamples,\n\t\tstd::vector<int>& leftNodeSamples, std::vector<int>& rightNodeSamples)\n{\n\tfloat tmp;\n\tBOOST_FOREACH(int n, inBagSamples)\n\t{\n\t\ttmp = 0.0;\n\t\tint counter = 0;\n\t\tBOOST_FOREACH(int feat, m_bestFeatures)\n\t\t{\n\t\t\ttmp += data(n,feat)*m_bestWeights[counter];\n\t\t\tcounter++;\n\t\t}\n\n\t\tif (tmp > m_bestThreshold)\n\t\t{\n\t\t\trightNodeSamples.push_back(n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tleftNodeSamples.push_back(n);\n\t\t}\n\t}\n}\n\nNODE_TRAIN_STATUS NodeHyperPlane::train(const matrix<float>& data, const std::vector<int>& labels,\n\t\tstd::vector<int>& inBagSamples, matrix<float>& confidences, std::vector<int>& predictions)\n{\n\tbool doSplit = shouldISplit(labels,inBagSamples);\n\tNODE_TRAIN_STATUS myTrainingStatus = IS_NOT_LEAF;\n\n\tif ( doSplit )\n\t{\n\t\tm_isLeaf = false;\n\n\t\t//train here the node: Select random features and evaluate them\n\t\tstd::vector<int> randFeatures = randPerm(data.size2(), m_hp.numProjFeatures );\n\t\tint numTries = m_hp.numRandomFeatures;// * (m_depth+1);\n\t\tfindHypotheses(data, labels, inBagSamples, randFeatures, numTries);\n\t\tif (m_hp.verbose)\n\t\t{\n\t\t\tcout << \"Node #: \" << m_nodeIndex;\n\t\t\tcout << \" and the threshold is: \" << m_bestThreshold << \" at depth \" << m_depth << endl;\n\t\t}\n\n\t\t// split the data\n\t\tstd::vector<int> leftNodeSamples, rightNodeSamples;\n\t\tevalNode(data,inBagSamples,leftNodeSamples,rightNodeSamples);\n\n\t\t// pass them to the left and right child, respectively\n\t\tm_leftChildNode = Ptr(new NodeHyperPlane(m_hp,m_depth + 1));\n\t\tm_rightChildNode = Ptr(new NodeHyperPlane(m_hp,m_depth + 1));\n\n\t\tNODE_TRAIN_STATUS leftChildStatus = m_leftChildNode->train(data,labels,leftNodeSamples,confidences,predictions);\n\t\tNODE_TRAIN_STATUS rightChildStatus= m_rightChildNode->train(data,labels,rightNodeSamples,confidences,predictions);\n\n\t}\n\telse\n\t{\n\t\tif (m_hp.verbose)\n\t\t{\n\t\t\tcout << \"Node #: \" << m_nodeIndex << \" is terminal, at depth \" << m_depth << endl;\n\t\t}\n\n\t\t// calc confidence, labels, etc\n\t\tm_isLeaf = true;\n\t\tmyTrainingStatus = IS_LEAF;\n\t\tm_nodeConf.resize(m_hp.numClasses, 0.0);\n\n\t\tBOOST_FOREACH(int n, inBagSamples)\n\t\t{\n\t\t\tm_nodeConf[labels[n]]++;\n\t\t}\n\n\t\tint bestClass = 0, tmpN = 0;\n\t\tfloat bestConf = 0;\n\t\tstd::vector<float>::iterator confItr = m_nodeConf.begin(), confEnd = m_nodeConf.end();\n\t\tfor (; confItr != confEnd; confItr++)\n\t\t{\n\t\t\t*confItr /= inBagSamples.size();\n\t\t\tif (*confItr > bestConf)\n\t\t\t{\n\t\t\t\tbestConf = *confItr;\n\t\t\t\tbestClass = tmpN;\n\t\t\t}\n\t\t\ttmpN++;\n\t\t}\n\t\tm_nodeLabel = bestClass;\n\n\t\tBOOST_FOREACH(int n, inBagSamples)\n\t\t{\n\t\t\tpredictions[n] = m_nodeLabel;\n\t\t\ttmpN = 0;\n\t\t\tBOOST_FOREACH(float conf, m_nodeConf)\n\t\t\t{\n\t\t\t\tconfidences(n, tmpN) = conf;\n\t\t\t\ttmpN++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn myTrainingStatus;\n}\n\nNODE_TRAIN_STATUS NodeHyperPlane::train(const matrix<float>& data, const std::vector<int>& labels, const std::vector<double>& weights,\n\t\tstd::vector<int>& inBagSamples, matrix<float>& confidences, std::vector<int>& predictions)\n{\n\tbool doSplit = shouldISplit(labels,inBagSamples);\n\tNODE_TRAIN_STATUS myTrainingStatus = IS_NOT_LEAF;\n\n\tif ( doSplit )\n\t{\n\t\tm_isLeaf = false;\n\n\t\t//train here the node: Select random features and evaluate them\n\t\tstd::vector<int> randFeatures = randPerm(data.size2(),m_hp.numProjFeatures );\n\t\tint numTries = m_hp.numRandomFeatures * (m_depth+1);\n\t\tfindHypotheses(data, labels, weights, inBagSamples, randFeatures,numTries);\n\t\tif (m_hp.verbose)\n\t\t{\n\t\t\tcout << \"Node #: \" << m_nodeIndex;\n\t\t\tcout << \" and the threshold is: \" << m_bestThreshold << \" at depth \" << m_depth << endl;\n\t\t}\n\n\t\t// split the data\n\t\tstd::vector<int> leftNodeSamples, rightNodeSamples;\n\t\tevalNode(data,inBagSamples,leftNodeSamples,rightNodeSamples);\n\n\t\t// pass them to the left and right child, respectively\n\t\tm_leftChildNode = Ptr(new NodeHyperPlane(m_hp,m_depth + 1));\n\t\tm_rightChildNode = Ptr(new NodeHyperPlane(m_hp,m_depth + 1));\n\n\t\tNODE_TRAIN_STATUS leftChildStatus = m_leftChildNode->train(data,labels,weights,leftNodeSamples,confidences,predictions);\n\t\tNODE_TRAIN_STATUS rightChildStatus= m_rightChildNode->train(data,labels,weights,rightNodeSamples,confidences,predictions);\n\n\t}\n\telse\n\t{\n\t\tif (m_hp.verbose)\n\t\t{\n\t\t\tcout << \"Node #: \" << m_nodeIndex << \" is terminal, at depth \" << m_depth << endl;\n\t\t}\n\n\t\t// calc confidence, labels, etc\n\t\tm_isLeaf = true;\n\t\tmyTrainingStatus = IS_LEAF;\n\t\tm_nodeConf.resize(m_hp.numClasses, 0.0);\n\n\t\tdouble totalW = 0;\n\t\tBOOST_FOREACH(int n, inBagSamples)\n\t\t{\n\t\t\tm_nodeConf[labels[n]] += weights[n];\n\t\t\ttotalW += weights[n];\n\t\t}\n\n\t\tint bestClass = 0, tmpN = 0;\n\t\tfloat bestConf = 0;\n\t\tstd::vector<float>::iterator confItr = m_nodeConf.begin(), confEnd = m_nodeConf.end();\n\t\tfor (; confItr != confEnd; confItr++)\n\t\t{\n\t\t\t*confItr /= (totalW + 1e-10);\n\t\t\tif (*confItr > bestConf)\n\t\t\t{\n\t\t\t\tbestConf = *confItr;\n\t\t\t\tbestClass = tmpN;\n\t\t\t}\n\t\t\ttmpN++;\n\t\t}\n\t\tm_nodeLabel = bestClass;\n\n\t\tBOOST_FOREACH(int n, inBagSamples)\n\t\t{\n\t\t\tpredictions[n] = m_nodeLabel;\n\t\t\ttmpN = 0;\n\t\t\tBOOST_FOREACH(float conf, m_nodeConf)\n\t\t\t{\n\t\t\t\tconfidences(n, tmpN) = conf;\n\t\t\t\ttmpN++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn myTrainingStatus;\n}\n\n\nvoid NodeHyperPlane::eval(const matrix<float>& data, const std::vector<int>& sampleIndeces,\n\t\tmatrix<float>& confidences, std::vector<int>& predictions)\n{\n\tif (m_isLeaf)\n\t{\n\t\t// Make predictions and confidences\n\t\tint tmpN;\n\t\tBOOST_FOREACH( int n, sampleIndeces)\n\t\t{\n\t\t\tpredictions[n] = m_nodeLabel;\n\t\t\ttmpN = 0;\n\t\t\tBOOST_FOREACH(float conf, m_nodeConf)\n\t\t\t{\n\t\t\t\tconfidences(n, tmpN) = conf;\n\t\t\t\ttmpN++;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t// split the data\n\t\tstd::vector<int> leftNodeSamples, rightNodeSamples;\n\t\tevalNode(data,sampleIndeces,leftNodeSamples,rightNodeSamples);\n\n\t\tm_leftChildNode->eval(data,leftNodeSamples,confidences,predictions);\n\t\tm_rightChildNode->eval(data,rightNodeSamples,confidences,predictions);\n\t}\n}\n\nvoid NodeHyperPlane::getPath(const matrix<float>& data, const std::vector<int>& sampleIndeces, std::vector<std::vector<int> >& path)\n{\n\tBOOST_FOREACH(int n, sampleIndeces)\n    \t\t{\n\t\tpath[n].push_back(m_nodeIndex);\n    \t\t}\n\n\tif (!m_isLeaf)\n\t{\n\t\t// split the data\n\t\tstd::vector<int> leftNodeSamples, rightNodeSamples;\n\t\tevalNode(data,sampleIndeces,leftNodeSamples,rightNodeSamples);\n\n\t\tm_leftChildNode->getPath(data,leftNodeSamples,path);\n\t\tm_rightChildNode->getPath(data,rightNodeSamples,path);\n\t}\n}\n\nvoid NodeHyperPlane::refine(const matrix<float>& data, const std::vector<int>& labels,\n\t\tstd::vector<int>& samples, matrix<float>& confidences, std::vector<int>& predictions)\n{\n\tif ( !m_isLeaf )\n\t{\n\t\t// split the data\n\t\tstd::vector<int> leftNodeSamples, rightNodeSamples;\n\t\tevalNode(data,samples,leftNodeSamples,rightNodeSamples);\n\n\t\tm_leftChildNode->refine(data,labels,leftNodeSamples,confidences,predictions);\n\t\tm_rightChildNode->refine(data,labels,rightNodeSamples,confidences,predictions);\n\t}\n\telse\n\t{\n\t\t// calc confidence, labels, etc\n\t\tm_nodeConf.resize(m_hp.numClasses,0.0);\n\t\tBOOST_FOREACH(int n, samples)\n\t\t{\n\t\t\tm_nodeConf[labels[n]]++;\n\t\t}\n\n\t\tint bestClass = 0, tmpN = 0;\n\t\tfloat bestConf = 0;\n\t\tstd::vector<float>::iterator confItr = m_nodeConf.begin(), confEnd = m_nodeConf.end();\n\t\tfor (; confItr != confEnd; confItr++)\n\t\t{\n\t\t\t*confItr /= samples.size();\n\t\t\tif (*confItr > bestConf)\n\t\t\t{\n\t\t\t\tbestConf = *confItr;\n\t\t\t\tbestClass = tmpN;\n\t\t\t}\n\t\t\ttmpN++;\n\t\t}\n\t\tm_nodeLabel = bestClass;\n\n\t\tBOOST_FOREACH(int n, samples)\n\t\t{\n\t\t\tpredictions[n] = m_nodeLabel;\n\t\t\ttmpN = 0;\n\t\t\tBOOST_FOREACH(float conf, m_nodeConf)\n\t\t\t{\n\t\t\t\tconfidences(n, tmpN) = conf;\n\t\t\t\ttmpN++;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid NodeHyperPlane::refine(const matrix<float>& data, const std::vector<int>& labels, const std::vector<double>& weights,\n\t\tstd::vector<int>& samples, matrix<float>& confidences, std::vector<int>& predictions)\n{\n\t// calc confidence, labels, etc\n\tif (!m_isLeaf)\n\t{\n\t\t// split the data\n\t\tstd::vector<int> leftNodeSamples, rightNodeSamples;\n\t\tevalNode(data,samples,leftNodeSamples,rightNodeSamples);\n\n\t\tm_leftChildNode->refine(data,labels,weights,leftNodeSamples,confidences,predictions);\n\t\tm_rightChildNode->refine(data,labels,weights,rightNodeSamples,confidences,predictions);\n\t}\n\telse\n\t{\n\t\tm_nodeConf.resize(m_hp.numClasses,0.0);\n\t\tstd::vector<float>::iterator confItr2 = m_nodeConf.begin(), confEnd2 = m_nodeConf.end();\n\t\tfor (; confItr2 != confEnd2; confItr2++)\n\t\t{\n\t\t\t*confItr2=0;\n//\t\t\tstd::cout<<*confItr2<<std::endl;\n\t\t}\n\t\tdouble totalW = 0;\n\t\tBOOST_FOREACH(int n, samples)\n\t\t{\n\t\t\tm_nodeConf[labels[n]] += weights[n];\n\t\t\ttotalW += weights[n];\n//\t\t\tstd::cout<<n<<\" \"<<labels[n]<<\" \"<<weights[n]<<\" \"<<m_nodeConf[labels[n]]<<\" \"<<(totalW + 1e-10)<<\" \"<<m_nodeConf[labels[n]]/(totalW + 1e-10)<<std::endl;\n\n\t\t}\n\n\t\tint bestClass = 0, tmpN = 0;\n\t\tfloat bestConf = 0;\n\t\tstd::vector<float>::iterator confItr = m_nodeConf.begin(), confEnd = m_nodeConf.end();\n\t\tfor (; confItr != confEnd; confItr++)\n\t\t{\n\t\t\t*confItr /= (totalW + 1e-10);\n\t\t\tif (*confItr > bestConf)\n\t\t\t{\n\t\t\t\tbestConf = *confItr;\n\t\t\t\tbestClass = tmpN;\n\t\t\t}\n\t\t\ttmpN++;\n\t\t}\n\t\tm_nodeLabel = bestClass;\n\n\t\tBOOST_FOREACH(int n, samples)\n\t\t{\n\t\t\tpredictions[n] = m_nodeLabel;\n\t\t\ttmpN = 0;\n\t\t\tBOOST_FOREACH(float conf, m_nodeConf)\n\t\t\t{\n\t\t\t\tconfidences(n, tmpN) = conf;\n\t\t\t\ttmpN++;\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "5b0673486680e5e4be9face468bea88dcf1eeac2", "size": 32398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/External/RF/nodehyperplane.cpp", "max_stars_repo_name": "tschuls/ETH-SegReg-DLL", "max_stars_repo_head_hexsha": "34bd10464dc5e8b3c7bf3371ca1e190d692385b7", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-04-15T06:49:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-01T09:09:50.000Z", "max_issues_repo_path": "source/External/RF/nodehyperplane.cpp", "max_issues_repo_name": "tschuls/ETH-SegReg-DLL", "max_issues_repo_head_hexsha": "34bd10464dc5e8b3c7bf3371ca1e190d692385b7", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2015-03-09T19:09:47.000Z", "max_issues_repo_issues_event_max_datetime": "2015-09-04T15:31:12.000Z", "max_forks_repo_path": "source/External/RF/nodehyperplane.cpp", "max_forks_repo_name": "tschuls/ETH-SegReg-DLL", "max_forks_repo_head_hexsha": "34bd10464dc5e8b3c7bf3371ca1e190d692385b7", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-04-08T09:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-12T17:30:15.000Z", "avg_line_length": 28.1232638889, "max_line_length": 158, "alphanum_fraction": 0.6618309772, "num_tokens": 9953, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.24457149227526195}}
{"text": "/*  This file is part of libDAI - http://www.libdai.org/\n *\n *  libDAI is licensed under the terms of the GNU General Public License version\n *  2, or (at your option) any later version. libDAI is distributed without any\n *  warranty. See the file COPYING for more details.\n *\n *  Copyright (C) 2010  Joris Mooij  [joris dot mooij at libdai dot org]\n */\n\n#include <dai/alldai.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include \"dai/emrun.h\"\n#include <dai/util.h>\n#include <string>\n#include <sys/stat.h>\n#include <time.h>\n#include <boost/random/linear_congruential.hpp>\n#include <boost/random/uniform_int.hpp>\n#include <boost/random/uniform_real.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <boost/generator_iterator.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n#include <boost/random/normal_distribution.hpp>\n#include <iomanip>      // std::setprecision\n#include <sstream>\n#include <string>\n#include <cstdlib>\n#include <boost/lexical_cast.hpp>\n#include <boost/tokenizer.hpp>\n#include <algorithm>\n#include<math.h>\n#include <boost/bimap/bimap.hpp>\n#include <boost/bimap/unordered_set_of.hpp>\n#include <boost/bimap/multiset_of.hpp>\n#include <boost/config.hpp>\n\n#include <string>\n#include <iostream>\n\n#include <boost/bimap.hpp>\n#include <boost/optional.hpp>\n#include <boost/none.hpp>\n#include <boost/foreach.hpp>\n#include <boost/assign/list_inserter.hpp>\nusing namespace std;\nusing namespace dai;\nusing namespace boost;\n// Define a random number generator and initialize it with a reproducible\n// seed.\nmt19937 generator(42);\n\n// Define a uniform random number distribution which produces \"double\"\n// values between 0 and 1 (0 inclusive, 1 exclusive).\nboost::uniform_real<> uni_dist(0,1);\nboost::variate_generator<mt19937&, boost::uniform_real<> > uni(generator, uni_dist);\n\nboost::normal_distribution<> nd(0.0, 1.0);\nboost::variate_generator<mt19937&, boost::normal_distribution<> > normal(generator, nd);\n\n// GA - initialization\nsize_t max_gen = 10; // no. of generations\nsize_t population_size =4; // population size\nReal pc;// = 0.8; // crossover probability - between 0.6 an 0.9\nReal pm;// = 0.3; // mutation probability - between 1/pop.size and 1/chromosome_length\nint population_no=0; // current population id\n\n// 1. Creating initial population of EM runs \n\t\nchar* gibbsfile;// = \"/home/priya/libDAI-0.3.1/alarm/500/5.tab\";\n//const char* gibbsfile = argv[1];\nstring alarmfgloc;// = \"/home/priya/libDAI-0.3.1/alarm_learned_factor_graphs/\"; \nstring alarmlearnedfgloc;// = \"/home/priya/libDAI-0.3.1/alarm_learned_factor_graphs/\";\nchar* networkname ; //= \"alarm\";\nsize_t maxIters =1000; // maximum number of iterations\nchar* emfile;\nofstream out,out1;\nEMRun* runname;\nvector <EMRun*> layer; \nvector <EMRun*> layer_curr;\nvector <EMRun*> layer_prev;\nint noVars;\nint *arrval;\n//\n// Generate a random number between 0 and 1\n// return a uniform number in [0,1].\ndouble unifRand()\n{\n    return rand()/double(RAND_MAX);\n}\n// Reset the random number generator with the system clock.\nvoid seed()\n{\n\t/*Declare variable to hold seconds on clock.*/\n\t//time_t seconds;\n\t/*Get value from system clock and place in seconds variable.*/\n//\ttime(&seconds);\n\t/*Convert seconds to a unsigned integer.*/\n//     struct timeval time;\n//     gettimeofday(&time,NULL);\n\n     // microsecond has 1 000 000\n     //srand((time.tv_sec * 1000) + (time.tv_usec / 10));\n    //srand((unsigned)time(0));\n}\nstd::string& trim(std::string& s, const char* t = \" \\t\\n\\r\\f\\v\")\n{\n\ts.erase(0, s.find_first_not_of(t));\n\ts.erase(s.find_last_not_of(t) + 1);\n\treturn s;\n}\ndouble euclideanDist(double v1[],double v2[],int length)\n{\n    double distance=0;\n    for(int i=0;i<length;i++)\n    {\n        distance = distance+ pow((v1[i]-v2[i]),2); //Euclidean distance\n    }\n    distance = sqrt(distance);\n    return distance;\n}\ndouble klDist(double v1[],double v2[],int length)\n{\n    double distance=0;\n    for(int i=0;i<length;i++)\n    {\n        distance = distance + (v1[i]* log2( v1[i]/v2[i])); // KL distance\n    }\n    return distance;\n}\ndouble calculateDistance(string child, string child1)\n{\n    \n    const char* childfgfile = &child[0];\n    const char* childfgfile1 = &child1[0];\n    //cout<<\"child file \"<< childfgfile<<\" \"<<childfgfile1<<endl;\n    string line1,line2;\n    ifstream p1 (childfgfile);\n    ifstream c1 (childfgfile1);\n    getline(p1,line1);\n    getline(c1,line2);\n    \n    int factor =0;\n    int no_factors = 0;\n    int* factor_names;\n    int factor_pos=0;\n    int* states_arr;\n    int no_states = 1;\n    int arr_size =1;\n    int factor_states =0;\n    int tot_arrays =0;\n    int arr_set =0;\n    int arr_set_states =0;\n    int no_arr_arrset =0;\n    int stat =0;\n    int p_c = 0;\n    double pmut=0,pm=0,distval=0;\n    while(getline(p1,line1)&&getline(c1,line2))\n    {\n        line1 = trim(line1);\n        line2 = trim(line2);\n        //cout<<p_c<<\" \"<<pmut<<\" \"<<pm<<\" \"<<line1<<endl;\n        stringstream ss(line1);\n        stringstream ss1(line2);\n        if(line1.empty())\n        {\n            p_c = 0;\n            stat =0;\n            //cout<<\"factor variable \"<<factor<<endl;\n            //seed();\n            //pmut = unifRand(); // generates random a value between 0 and 1 for child1\n            //cout<<\"Mutation probability \"<<pmut<<endl;\n            no_states = 1;\n            arr_size =1;\n            factor++;\n        }\n        if(pmut>pm)\n        {\n            //c1<<line1<<endl;\n            //cout<<\"No mutation\"<<endl;\n            //p_c++;\n            //continue;\n        }\n        if(pmut<=pm) //do mutation handling the constraint that the states of the random variable sum to 1.\n        {\n            //cout<<\"Mutation happening \"<<endl;\n            double sumo=0,sumo1=0;\n            if(p_c == 0)\n            {\n                //c1<<line1<<endl;\n            }\n            if(p_c == 1)\n            {\n                ss>>no_factors;\n                //cout<<\"no. of factors \"<<no_factors<<endl;\n                //c1<<no_factors<<endl;\n            }\n            if(p_c == 2)\n            {\n                factor_names = new int[no_factors];\n                std::vector<std::string> fields;\n                fields = tokenizeString( line1, true,\"  \");\n                for( size_t i = 0; i < fields.size(); ++i )\n                {\n                    stringstream n;\n                    n << fields[i];\n                    string s = n.str();\n                    if( s.find_first_not_of(\" \")!= std::string::npos)\n                    {\n                        //c1<<s<<\" \";\n                        n >> factor_names[i];\n                        if(factor_names[i] == (factor-1))\n                            factor_pos =i;\n                    }\n                }\n                //c1<<endl;\n                //cout<<\"factor position \"<<factor_pos<<endl;\n            }\n            if(p_c == 3)\n            {\n                states_arr = new int[no_factors];\n                std::vector<std::string> fields1;\n                fields1 = tokenizeString( line1, true,\"  \");\n                for( size_t j = 0; j < fields1.size(); ++j )\n                {\n                    stringstream n1;\n                    n1 << fields1[j];\n                    string state = n1.str();\n                    if( state.find_first_not_of(\" \")!= std::string::npos)\n                    {\n                        //c1<<state<<\" \";\n                        n1 >> states_arr[j];\n                        no_states = no_states * states_arr[j];\n                        if(j < factor_pos)\n                            arr_size = arr_size * states_arr[j];\n                        if(j == factor_pos)\n                        {\n                            factor_states = states_arr[j];\n                            arr_set_states = arr_size*states_arr[j];\n                        }\n                    }\n                }\n                //c1<<endl;\n                tot_arrays = no_states/arr_size;\n                arr_set = no_states/arr_set_states;\n                no_arr_arrset = factor_states;\n                //cout<<\"array size \"<<arr_size<<endl;\n                //cout<<no_states<<\"\\t\"<<\"no. of states \"<<no_states<<\"\\t\"<<\"total arrays \"<<tot_arrays<<\"\\t\"<<\"array set \"<<arr_set<<\"\\t\"<<\"no. arrays \"<<no_arr_arrset<<\"\\t\"<<\"factor states \"<<factor_states<<endl;\n                //c1<<no_states<<endl;\n            }\n            if(p_c >= 5)\n            {\n                int k=0;\n                while(k<arr_set)\n                {\n                    std::vector< double * > Arrays, Arrays1;\n                    for(int l=0; l<no_arr_arrset; l++)\n                    {\n                        Arrays.push_back( new double[arr_size]);\n                        Arrays1.push_back( new double[arr_size]);\n                    }\n                    vector<double*>::iterator it2,it21;\n                    it2=Arrays.begin();\n                    it21=Arrays1.begin();\n                    //get the current cpt values and copy them in the array\n                    int l=0;\n                    while(l<no_arr_arrset)\n                    {\n                        double* arr = *it2;\n                        double* arr1 = *it21;\n                        // cout<<\"new arr\"<<endl;\n                        int m=0;\n                        while(m<arr_size)\n                        {\n                            line1 = trim(line1);\n                            line2 = trim(line2);\n                            //cout<<line1 <<\" \"<<line2<<endl;\n                            std::vector<std::string> values,values1;\n                            //                                values = tokenizeString( line1, true,\" +\");\n                            //                                values1 = tokenizeString( line2, true,\" +\");\n//                            split(values, line1, is_any_of(\" +\")); // here it is\n//                            split(values1, line2, is_any_of(\" +\")); // here it is\n                            char_separator<char> sep(\"   \");\n                            tokenizer<char_separator<char>> tokens(line1, sep);\n                            for (const auto& t : tokens) {\n                                //cout<<t;\n                                if(t!=\" \")\n                                {\n                                    values.push_back(t);\n                                   // cout<<\"pushed \"<<t<<endl;\n                                }\n                            }\n                            //cout<<endl;\n                            tokenizer<char_separator<char>> tokens1(line2, sep);\n                            for (const auto& t : tokens1) {\n                                //cout<<t;\n                                if(t!=\" \")\n                                {\n                                    values1.push_back(t);\n                                    //cout<<\"pushed \"<<t<<endl;\n                                }\n                            }\n                            //cout<<endl;\n                            int ii=0;\n                           // cout<<values.size()<<\" \"<<values1.size()<<endl;\n                            for( size_t j = 0; j < values.size(); ++j )\n                            {\n                                stringstream n1,n2;\n                                n1 << values[j];\n                                n2 << values1[j];\n                                string state = n1.str();\n                                string state1 = n2.str();\n                                //cout<<state<<\" !! \"<<state1<<\" !! \"<<endl;\n                                if( state.find_first_not_of(\" \")!= std::string::npos && state1.find_first_not_of(\" \")!= std::string::npos)\n                                {\n                                    if(ii==1)\n                                    {\n                                        n1 >> arr[m];\n                                        n2 >> arr1[m];\n                                        //cout<<p_c<<\" \"<<line1<<\" \"<<\"arrval = \"<<values[0]<<\"\\tarr[m]\"<<arr[m]<<\" m = \"<<m<<endl;\n                                        m++;\n                                        if(m<arr_size)\n                                        {\n                                            getline(p1,line1);\n                                            getline(c1,line2);\n                                        }\n                                        ii=0;\n                                    }\n                                    else\n                                        ii=1;\n                                } //end of if\n                            } // end of for\n                        } // end of while -m\n                        l++;\n                        if(l<no_arr_arrset)\n                        {\n                            getline(p1,line1);\n                            getline(c1,line2);\n                        }\n                        ++it2; ++it21;\n                    } //end of while -l\n                    // cout<<\"new val\"<<endl;\n                    vector<double*>::iterator it,it1;\n                    double sumarr[arr_size];\n                    for(int m=0; m<arr_size; m++)\n                    {\n                        it=Arrays.begin();\n                        it1=Arrays1.begin();\n                        double valarr[no_arr_arrset],valarr1[no_arr_arrset];\n                        for(int l=0; l<no_arr_arrset; l++) // stdnormal rand values are generated and sum is found\n                        {\n                            double* arr = *it;\n                            double* arr1 = *it1;\n                            double val = arr[m];\n                            double val1 =  arr1[m];\n                            valarr[l]=val;\n                            valarr1[l]=val1;\n                            //cout<<val<<\" \"<<val1<<endl;\n                            ++it; ++it1;\n                        }\n                        \n                        sumo+=euclideanDist(valarr,valarr1,no_arr_arrset);\n                        sumo1+=klDist(valarr,valarr1,no_arr_arrset);\n                        // cout<<endl;\n                    }\n                    k++;\n                    if(k<arr_set)\n                    {\n                        getline(p1,line1);\n                        getline(c1,line2);\n                    }\n                }// end of while -k\n                //cout<<\" \"<<sumo<<\" \"<<sumo1<<endl;\n                distval = distval+sumo;\n            }// end of if p_c>=5\n            \n        } // end of if pmut<p_m\n        p_c++;\n    } // end of while loop\n    c1.close();\n    p1.close();\n    //cout<<distval<<endl;\n    return distval;\n}\n\nvoid startEM()\n{\n\tsize_t i =0,j=0;\n\t//cout<<\"In start EM\"<<endl;\n\twhile(i<population_size)\n\t{\n\t string number;\n\t stringstream num;\n\t num << i;\n\t number = num.str();\n\t string dirname;\n\t stringstream p_id;\n\t p_id << population_no;\n\t dirname = p_id.str();\n\t string fgfileloc =  alarmfgloc + dirname+\"/\"+networkname+\"_\"+number+\".fg\";\n\t const char* fgfile = &fgfileloc[0];\n\t cout<<\"Starting EM \"<<fgfileloc<<endl;\n\t runname = new EMRun(networkname, i, fgfile, gibbsfile,emfile); // args are -1.network name 2.factor-graph number 3. evidencefile\n\n\t // 2. Run EM\n\t boost::thread threadid(boost::bind(&EMRun::startEM, boost::ref(runname), maxIters)); // args - max iters\n\t layer.push_back(runname);\n\t sleep(1);\n\t // 4. Next individual3a\n\t i=i+1;\n\t}\n\n}\n\n\nvoid checkEMforTermination()\n{\n         string dirname; \n\t stringstream p_id; \n\t p_id << population_no; \n\t dirname = p_id.str();\n\tstring loc =  alarmlearnedfgloc + \"learned/\"+dirname+\"/\";\n\tconst char* learnedloc = &loc[0];\n\tmkdir(learnedloc,0755);\n\tlayer_prev.assign(layer_curr.begin(), layer_curr.end());\n\tlayer_curr.clear();\n\twhile (true){\n\t    //cout<<\"in while loop \"<<layer.size()<<endl;\n\t    vector<EMRun*>::iterator it; \n\t    for (it=layer.begin(); it != layer.end(); ++it){    \n\t      //cout<<\"layer size \"<<layer.size()<<endl;\t\n\t      if((*it)->hasTerminated()) { //if it has terminated, set the run aside\n//        ////////////\n//              if(layer_prev.size() !=0 )\n//              {\n//                  boost::thread thread6(boost::bind(&EMRun::stopEM, boost::ref(*it)));\n//                  \n//                  cout<<\" iters = \"<<(*it)->getIters()<<endl;\n//                  double iters = (*it)->getIters();\n//                  double val = (*it)->getRun();\n//                  cout<<\" em run stopped \"<<val<<endl;\n//                  double ll = (*it)->getLL();\n//                  vector<EMRun*>::iterator itprev;\n//                  std::vector<Real> llTraceprev;\n//                  // get the pervious run\n//                  \n//                  for (itprev=layer_prev.begin(); itprev != layer_prev.end(); ++itprev)\n//                  {\n//                      double runid = (*itprev)->getRun();\n//                      if(val==runid)\n//                      {\n//                          //out1<<runid<<\" \"<<iters<<\" \";\n//                          \n//                          llTraceprev = (*itprev)->lastlog();\n//                          cout<<val<<\" \"<<\"runid = \"<<(*itprev)->getRun()<<\"  \"<<\" \"<<(*itprev)->getIters()<<endl;\n//                          break;\n//                      }\n//                  }\n//                  //check if current EM run's LL is greater or equal to prev EM run's LL\n//                  \n//                  double llprev;\n//                  cout<<\" size = \"<<llTraceprev.size()<<endl;\n//                  if((llTraceprev.size()-1)>iters)\n//                      llprev = llTraceprev.at(iters);\n//                  else\n//                      llprev = llTraceprev.at(llTraceprev.size()-1);\n//                  cout<<\" LL for prev run = \"<<llprev<<endl;\n//                  if(ll>=llprev)\n//                  {\n//                      cout<<\" current LL \"<<ll<<\" is good\"<<endl;\n//                      boost::thread thread7(boost::bind(&EMRun::resumeEM, boost::ref(*it)));\n//                      cout<<\" em run resumed\"<<val<<endl;\n//                  }\n//                  else\n//                  {\n//                      cout<<\" current LL \"<<ll<<\" is not good\"<<endl;\n//                      *it = *itprev;\n//                      (*itprev)->forceStopped();\n//                      cout<<\" em run not resumed\"<<val<<endl;\n//                  }\n//                  \n//              }\n//      \n//        ////////////\n        double ll = (*it)->getLL();\n\t\tdouble iters = (*it)->getIters();\n\t\tdouble runid = (*it)->getRun();\n        //cout<<\"em run \"<<runid<<\" terminated \"<<iters<<endl;\n        std::vector<Real> llTrace = (*it)->lastlog();\n\t\tstring number; \n\t\tstringstream num; \n\t\tnum << runid; \n\t\tnumber = num.str();\n\t \tstring fglearnedfileloc =  alarmlearnedfgloc + \"learned/\"+dirname+\"/\"+networkname+\"_\"+number+\".fg\";\n        const char* fglearnedfile = &fglearnedfileloc[0];\n\t\tcout<<\"Run number \"<<number<<\" ll = \"<<ll<<\" iters = \"<<iters<<endl;\t\n\t\t// 3. Store the learned factor graphs\n\t\tInfAlg* inf = (*it)->getInf();\n\t\tofstream learnedstream;\n\t\tcout<<\"learned file = \"<<fglearnedfile<<endl;\n\t\tlearnedstream.open(fglearnedfile);\n\t\tlearnedstream.precision(2);\n\t\tlearnedstream << inf->fg();  \n\t\tlearnedstream.flush();\n\t\tlearnedstream.close();\n\t\t//delete inf;\n\t\tsleep(1);\n\t\tcout<<\"Run number \"<<number<<\" has terminated\"<<endl;\n\t\tout<<pc<<\" \"<<pm<<\" \"<<gibbsfile<<\" \"<<fglearnedfile<<\" \"<<runid<<\" \"<<iters<<\" \"<<ll<<\" \"<<endl;\n//        out1<<runid<<\" \"<<iters<<\" \";\n//        for(std::vector<Real>::iterator logval = llTrace.begin(); logval != llTrace.end(); ++logval)\n//        {\n//                  out1 << *logval<<\" \";\n//        }\n//        out1<<\" \"<<endl;\n        std::vector<int> mutateFactors;\n        mutateFactors = (*it)->getmutateFactors();\n        cout<<\" Run id \"<<runid;\n        cout<<\" iiiii \"<<mutateFactors.size()<<endl;\n\t\tlayer_curr.push_back(*it); \n\t\tlayer.erase(it);\t\n\t\tif (layer.size() == 0){break;}\n\t\telse { it = layer.begin(); }\n        }\n            //we stop the run\n        else if(((*it)->getIters()) == maxIters){\n\t\tdouble ll = (*it)->getLL();\n\t\tdouble iters = (*it)->getIters();\n\t\tdouble runid = (*it)->getRun();\n\t\tstring number; \n\t\tstringstream num; \n\t\tnum << runid; \n\t\tnumber = num.str();\n\t \tstring fglearnedfileloc =  alarmlearnedfgloc + \"learned/\"+dirname+\"/\"+networkname+\"_\"+number+\".fg\";\n\t    \tconst char* fglearnedfile = &fglearnedfileloc[0];\n\t\t//cout<<\"Run number \"<<number<<\" ll = \"<<ll<<\" iters = \"<<iters<<endl;\t\n\t\t//cout<<\"Run \"<<(*it)->getRun()<<\" has reached maximum iterations, so stopping the run\"<<endl;\n        \n\t \t// 3. Store the learned factor graphs\n\t\tInfAlg *inf = (*it)->getInf();\n\t    \tofstream learnedstream;\n\t    \t//cout<<\"learned file = \"<<fglearnedfile<<endl;\n\t    \tlearnedstream.open(fglearnedfile);\n\t    \tlearnedstream.precision(12);\n\t    \tlearnedstream << inf->fg();  \n\t    \tlearnedstream.close();\n\t\t//delete inf;\n\t\tsleep(1);\t\t\n\t\t//cout<<\"Run number \"<<number<<\" has reached maximum iterations so stopped\"<<endl;\n\t\tout<<pc<<\" \"<<pm<<\" \"<<gibbsfile<<\" \"<<fglearnedfile<<\" \"<<runid<<\" \"<<iters<<\" \"<<ll<<\" \"<<endl; \n\t\tlayer_curr.push_back(*it);\n            if(!(*it)->isForceStop())\n            {\n                boost::thread thread5(boost::bind(&EMRun::stopEM, boost::ref(*it)));\n                \n            }\n            layer.erase(it);\n\t//\tif (layer.size() == 0){break;}\n\t//\telse { it = layer.begin(); }\n\t      }\n        else \n        {\n            //*it=compareRuns(it);\n            if(layer_prev.size() !=0 )\n            {\n                boost::thread thread6(boost::bind(&EMRun::stopEM, boost::ref(*it)));\n                \n                cout<<\" iters = \"<<(*it)->getIters()<<endl;\n                double iters = (*it)->getIters();\n                double val = (*it)->getRun();\n                cout<<\" em run stopped \"<<val<<endl;\n                double ll = (*it)->getLL();\n                vector<EMRun*>::iterator itprev;\n                std::vector<Real> llTraceprev;\n                // get the pervious run\n                \n                for (itprev=layer_prev.begin(); itprev != layer_prev.end(); ++itprev)\n                {\n                    double runid = (*itprev)->getRun();\n                    if(val==runid)\n                    {\n                        //out1<<runid<<\" \"<<iters<<\" \";\n                        \n                        llTraceprev = (*itprev)->lastlog();\n                        cout<<val<<\" \"<<\"runid = \"<<(*itprev)->getRun()<<\"  \"<<\" \"<<(*itprev)->getIters()<<endl;\n                        break;\n                    }\n                }\n                //check if current EM run's LL is greater or equal to prev EM run's LL\n                \n                double llprev;\n                cout<<\" size = \"<<llTraceprev.size()<<endl;\n                if((llTraceprev.size()-1)>iters)\n                    llprev = llTraceprev.at(iters);\n                else\n                    llprev = llTraceprev.at(llTraceprev.size()-1);\n                cout<<\" LL for prev run = \"<<llprev<<endl;\n                if(ll>=llprev)\n                {\n                    cout<<\" current LL \"<<ll<<\" is good\"<<endl;\n                    boost::thread thread7(boost::bind(&EMRun::resumeEM, boost::ref(*it)));\n                    cout<<\" em run resumed\"<<val<<endl;\n                }\n                else\n                {\n                    cout<<\" current LL \"<<ll<<\" is not good\"<<endl;\n                    *it = *itprev;\n                    (*itprev)->forceStopped();\n                    cout<<\" em run not resumed\"<<val<<endl;\n                }\n                \n            }\n\n            \n        }\n\t      //cout<<\"Going ..\"<<endl;\n\t }\n\t if (layer.size() == 0){ //cout<<\"breaking while\"<<endl;\n\t\tbreak; }\n\t else { //cout<<\"iterating\"<<endl;\n\t\t}\n\t  sleep(1); \n\t}\n}\nvoid doMutation() // open each child file and apply mutation if required\n{\n    string dirname2;\n    stringstream p_id2;\n    p_id2 << population_no+1;\n    dirname2 = p_id2.str();\n    string childloc =  alarmlearnedfgloc + dirname2+\"/\";\n    const char* childfgloc = &childloc[0];\n    //int t=2;\n    //cout<<\"In Mutation\"<<endl;\n    //cout<<\"declarations done \"<<arrval[0]<<endl;\n    vector<EMRun*>::iterator it = layer_curr.begin();\n       \n    for( size_t n = 0; n < population_size; n++ )\n    {\n        string number1;\n        stringstream num1;\n        num1 << n;//arrval[n];\n        number1 = num1.str();\n        string child =  childloc+ networkname+\"C_\"+number1+\".fg\";\n        string child1 =  childloc+ networkname+\"_\"+number1+\".fg\";\n        const char* childfgfile = &child[0];         \n        const char* childfgfile1 = &child1[0];         \n        //cout<<\"child file \"<< childfgfile<<endl;\n        //cout<<\"parent file \"<<childfgfile1<<endl;\n        string line1;\n        ifstream p1 (childfgfile); \n        ofstream c1 (childfgfile1); \n        getline(p1,line1);\n        c1<<line1<<endl;\n        int factor =0;\n        int no_factors = 0;\n        int* factor_names;\n        int factor_pos=0;\n        int* states_arr;\n        int no_states = 1;\n        int arr_size =1;\n        int factor_states =0;\n        int tot_arrays =0;\n        int arr_set =0;\n        int arr_set_states =0;\n        int no_arr_arrset =0;\n        int stat =0;\n        int p_c = 0;\n        double pmut=0;\n        \n        dai::hash_map<int, double> hashmap = (*it)->getParams();\n        double runid = (*it)->getRun();\n        std::vector<int> mutateFactors;\n        mutateFactors.clear();\n        mutateFactors = (*it)->getmutateFactors();\n        cout<<\" Run id \"<<runid;\n        cout<<\"______\"<<mutateFactors.size()<<endl;\n        while(getline(p1,line1))\n        {\n            line1 = trim(line1);\n            //cout<<p_c<<\" \"<<pmut<<\" \"<<pm<<\" \"<<line1<<endl;\n            stringstream ss(line1);\n            //cout<<params.length()<<endl;\n            if(line1.empty())\n            {\n              p_c = 0;\n              stat =0;\n             // cout<<\"factor variable \"<<factor;\n                std::vector<int>::iterator it;\n                \n                it = find (mutateFactors.begin(), mutateFactors.end(), factor);\n                if (it != mutateFactors.end())\n                {\n                    //std::cout << \"Element found in myvector: \" << *it << '\\n';\n                    pmut=1;\n                }\n                else\n                {\n                  //  std::cout << \"Element not found in myvector\\n\";\n                    pmut=0;\n                }\n             // cout<<params[factor]<<endl;\n              //pmut = uni(); // generates random a value between 0 and 1 for child1\n              //cout<<factor<<\" \"<<hashmap[factor]<<endl;\n              //pmut = hashmap[factor];\n              no_states = 1;\n              arr_size =1;  \n              factor++;\n            }\n            if(pmut<=pm)\n            {\n             c1<<line1<<endl;\n             //cout<<\"No mutation\"<<endl;\n                //p_c++;       \n             //continue;\n            }\n            if(pmut>pm) //do mutation handling the constraint that the states of the random variable sum to 1.\n            {\n                \n                if(p_c == 0)\n                {\n                 c1<<line1<<endl;\n                }\n                if(p_c == 1)\n                {\n                 ss>>no_factors;\n                 //cout<<\"no. of factors \"<<no_factors<<endl;\n                 c1<<no_factors<<endl;\n                }\n                if(p_c == 2)\n                {\n                 factor_names = new int[no_factors];\n                 std::vector<std::string> fields;\n                  fields = tokenizeString( line1, true,\"  \");         \n                 for( size_t i = 0; i < fields.size(); ++i )\n                 {\n                  stringstream n;\n                  n << fields[i];\n                  string s = n.str();      \n                  if( s.find_first_not_of(\" \")!= std::string::npos)        \n                  {\n                    c1<<s<<\" \";   \n                    n >> factor_names[i];\n                    if(factor_names[i] == (factor-1))\n                     factor_pos =i;\n                  }\n                  }\n                 c1<<endl;\n                 //cout<<\"factor position \"<<factor_pos<<endl;\n                }\n                if(p_c == 3)\n                {\n                 states_arr = new int[no_factors];\n                 std::vector<std::string> fields1;\n                  fields1 = tokenizeString( line1, true,\"  \");         \n                 for( size_t j = 0; j < fields1.size(); ++j )\n                 {\n                  stringstream n1;\n                  n1 << fields1[j];\n                  string state = n1.str();      \n                  if( state.find_first_not_of(\" \")!= std::string::npos)        \n                  {\n                    c1<<state<<\" \";   \n                    n1 >> states_arr[j];\n                    no_states = no_states * states_arr[j];\n                    if(j < factor_pos)\n                     arr_size = arr_size * states_arr[j];\n                    if(j == factor_pos)\n                     {\n                      factor_states = states_arr[j];\n                      arr_set_states = arr_size*states_arr[j];             \n                     }\n                  }\n                  }\n                 c1<<endl;\n                 tot_arrays = no_states/arr_size;\n                 arr_set = no_states/arr_set_states;\n                 no_arr_arrset = factor_states;\n                  //  cout<< factor_states<<endl;\n                 //cout<<\"array size \"<<arr_size<<endl;\n                 //cout<<no_states<<\"\\t\"<<\"no. of states \"<<no_states<<\"\\t\"<<\"total arrays \"<<tot_arrays<<\"\\t\"<<\"array set \"<<arr_set<<\"\\t\"<<\"no. arrays \"<<no_arr_arrset<<\"\\t\"<<\"factor states \"<<factor_states<<endl;\n                c1<<no_states<<endl;\n                }               \n                if(p_c == 5)\n                {\n                    cout<<childfgfile<<\"  Mutation happening at \"<<(factor-1)<<endl;\n                    int k=0;\n                   while(k<arr_set)\n                    {\n//                         //Random values are generated ----~------~-----\n//                        std::vector< double * > Arrays1;\n//                        for(int l=0; l<no_arr_arrset; l++)\n//                        {\n//                            Arrays1.push_back( new double[arr_size]);\n//                        }\n//                        vector<double*>::iterator it;\n//                        for(int m=0; m<arr_size; m++)\n//                        {\n//                            it=Arrays1.begin();\n//                            std::vector<double> vec;\n//                            for(int i=0; i<no_arr_arrset; i++)\n//                            {\n//                                vec.push_back(uni());\n//                            }\n//                            const double total = std::accumulate(vec.begin(), vec.end(), 0.0);\n//                            for (double& value: vec)\n//                            {\n//                                double* arr = *it;\n//                                value /= total;\n//                                arr[m] = value;\n//                                ++it;\n//                                //cout<<value <<endl;\n//                            }\n//                            // cout<<endl;\n//                            vec.clear();\n//                        }\n//                        //Random values are generated---x----x----\n                        //Actual values are retrieved ----~------~-----\n                        std::vector< double * > Arrays2;\n                        for(int lll=0; lll<no_arr_arrset; lll++)\n                        {\n                            Arrays2.push_back( new double[arr_size]);\n                        }\n                        vector<double*>::iterator it2;\n                        it2=Arrays2.begin();\n                        //get the current cpt values and copy them in the array\n                        int ll=0;\n                        while(ll<no_arr_arrset)\n                        {\n                            double* arrl = *it2;\n                           // cout<<\"new arr\"<<endl;\n                            int ml=0;\n                            while(ml<arr_size)\n                            {\n                                line1 = trim(line1);\n                                char_separator<char> sep(\"   \");\n                                tokenizer<char_separator<char>> tokens(line1, sep);\n                                std::vector<std::string> valuesl;\n                                for (const auto& t : tokens) {\n                                 //   cout<<t;\n                                    if(t!=\" \")\n                                    {\n                                        valuesl.push_back(t);\n                                    //    cout<<\"pushed \"<<t<<endl;\n                                    }\n                                }\n                                stringstream n1;\n                                n1 << valuesl[1];\n                                string state = n1.str();\n                                n1 >> arrl[ml];\n                                ml++;\n                                if(ml<arr_size)\n                                 getline(p1,line1);\n                            } // end of while -m\n                            ll++;\n                            if(ll<no_arr_arrset)\n                                getline(p1,line1);\n                            ++it2;\n                        } //end of while -l\n                        //Actual values are retrieved --------x------x------\n                        //Normal Random values are generated ----~------~-----\n                        std::vector< double * > Arrays1;\n                        vector<double*>::iterator a_it,nor_it;\n                        for(int l=0; l<no_arr_arrset; l++)\n                        {\n                            Arrays1.push_back( new double[arr_size]);\n                        }\n\n                        for(int m=0; m<arr_size; m++)\n                        {\n                            a_it=Arrays2.begin();\n                            nor_it=Arrays1.begin();\n                            std::vector<double> vec;\n                            for(int i=0; i<no_arr_arrset; i++)\n                            {\n                                double* arr = *a_it;\n                                double val = arr[m];\n                                double rval = normal();\n                                while((val+rval)<0) //boundary condition, negative cpt is not allowed\n                                {\n                                    rval = normal();\n                                }\n                                //cout<<\"val = \"<<val<<\" rval =\"<<rval<<endl;\n                                val = val+rval;\n                                ++a_it;\n                                vec.push_back(val);\n                            }\n                            const double total = std::accumulate(vec.begin(), vec.end(), 0.0);\n                            for (double& value: vec)\n                            {\n                                double* nor_arr = *nor_it;\n                                value /= total;\n                                nor_arr[m] = value;\n                                ++nor_it;\n                                //cout<<value <<endl;\n                            }\n                            // cout<<endl;\n                            vec.clear();\n                        }\n                        //Normal Random values are generated---x----x----\n\n                        //Check if actual value or random value should be updated ------~------~-----\n                        std::vector< double * > Arrays3;\n                        for(int l=0; l<no_arr_arrset; l++)\n                        {\n                            Arrays3.push_back( new double[arr_size]);\n                        }\n                        vector<double*>::iterator it3;\n                        for(int m=0; m<arr_size; m++)\n                        {\n                            it3=Arrays3.begin();\n                            std::vector<double> vec2;\n                            double pmut1 = uni();\n                            for(int i=0; i<no_arr_arrset; i++)\n                            {\n                                if(true)//if(pmut1>pm)\n                                    vec2.push_back(1);\n                                else\n                                    vec2.push_back(0);\n                            }\n                            for (double& value: vec2)\n                            {\n                                double* arr_rd = *it3;\n                                arr_rd[m] = value;\n                                ++it3;\n                                //cout<<value <<endl;\n                            }\n                            // cout<<endl;\n                            vec2.clear();\n                        }\n                        //Done checking-----x--------x--------\n                        //Random or actual values will be updated -----~------~\n                        vector<double*>::iterator it11,it22,it33;\n                        it11=Arrays1.begin();\n                        it22=Arrays2.begin();\n                        it33=Arrays3.begin();\n                        for(int l=0; l<no_arr_arrset; l++)\n                        {\n                            double* arr = *it11;double* arrl = *it22;double* arr_rd = *it33;\n                            for(int m=0; m<arr_size; m++)\n                            {\n                                stringstream v;\n                                if(true)//arr_rd[m]==1\n                                {\n                                    v << fixed << setprecision(12) << arr[m];\n                                    c1<<stat<<\"   \"<<v.str()<<endl;\n                                    stat++;\n                                  //  cout<< \"replaced\"<<v.str()<<endl;\n                                }\n                                else\n                                {\n                                    v << fixed << setprecision(12) << arrl[m];\n                                    c1<<stat<<\"   \"<<v.str()<<endl;\n                                    stat++;\n                                   // cout<<\"not replaced \"<<v.str()<<endl;\n                                }\n                            }\n                            ++it11;++it22;++it33;\n                        }\n                        //Random values are updated ------x------x--------\n                        Arrays1.clear();\n                        Arrays2.clear();\n                        Arrays3.clear();\n                        k++;\n                        if(k<arr_set)\n                        {\n                            getline(p1,line1);\n                        }\n                    }// end of while -k\n                }// end of if p_c==5\n            } // end of if pmut<p_m\n            p_c++;\n        } // end of while loop\n        c1.close();\n        p1.close();\n        remove(childfgfile);\n        *it++;\n    } // end of for loop\n    //cout<<\"Mutation Done\"<<endl;\n}\n\n\nvoid doCrossover()\n{\n\t// compute crossover probability\n\t double pcross = uni(); // generates random a value between 0 and 1\t\n\tcout<<\"Crossover probability \"<<pcross;\n\t// 4. Select 2 parents randomly\n\tconst int LOW = 0;\n\tconst int HIGH = population_size-1;\n\t//int t =2;\n\t//int t=40;\n\t// Generate the random variables to select as parents where 't' is the number of variables\n\t/*Declare variable to hold seconds on clock.*/\n\ttime_t seconds;\n\t/*Get value from system clock and place in seconds variable.*/\n\ttime(&seconds);\n\t/*Convert seconds to a unsigned integer.*/\n\tsrand(time(0));\n\tset<int> myset;\n\tset<int>::iterator it;\n\tsize_t k =0,p=0;\n\tarrval = new int[population_size];\n\tstring dirname; \n\tstringstream p_id; \n\tp_id << population_no; \n\tdirname = p_id.str();\n\tstring dirname2; \n\tstringstream p_id2; \n\tp_id2 << population_no+1; \n\tdirname2 = p_id2.str();\n\tstring childloc =  alarmlearnedfgloc + dirname2+\"/\";\n\tconst char* childfgloc = &childloc[0];\n\tmkdir(childfgloc,0755);\n\tfor( size_t n = 0; n < population_size; n++ )\n\t{ \n\t   int val = rand() % (HIGH - LOW + 1) + LOW;\n\t   it=myset.find(val);\n\t   arrval[n] = val;\n\t   if(it==myset.end()) // if the value is not in the set\n\t   {\n\t\tmyset.insert(val);\n\t\tp++;\n\t\tif(p == 2)\n\t\t{\n\t\t cout <<\" Random value is\"<<arrval[n]<<\" and \"<< arrval[n-1];\n\t\t string number1; \n\t\t stringstream num1; \n\t\t num1 << arrval[n];\n\t\t number1 = num1.str();\n\t\t string parent1 =  alarmlearnedfgloc +\"learned/\"+dirname+\"/\"+ networkname+\"_\"+number1+\".fg\";\n\t\t string child1 =  childloc+ networkname+\"C_\"+number1+\".fg\";\n\t\t const char* parentfgfile1 = &parent1[0];\n\t\t const char* childfgfile1 = &child1[0];\n\t\t string number2; \n\t\t stringstream num2; \n\t\t num2 << arrval[n-1]; \n\t\t number2 = num2.str();\n\t\t string parent2 = alarmlearnedfgloc +\"learned/\"+dirname+\"/\"+ networkname+\"_\"+number2+\".fg\";\n\t\t string child2 =  childloc+ networkname+\"C_\"+number2+\".fg\";\n\t\t const char* parentfgfile2 = &parent2[0];\n\t\t const char* childfgfile2 = &child2[0];\t \n\t\t //cout<<\"parent files are \"<< parentfgfile1<< \" and \"<< parentfgfile2<<endl;\n\t\t //cout<<\"child files are \"<< childfgfile1<<\" and \"<<childfgfile2<<endl;\n\t \n\t\t string line1,line2;\n\t\t ifstream p1 (parentfgfile1);  ifstream p2 (parentfgfile2);\n\t\t ofstream c1 (childfgfile1);  ofstream c2 (childfgfile2);\n\t\t// 5. Do crossover and create two children\n\t\t// randomly select a crossover point\n\t\t int cr_pt = (rand() % 4) +1;\n\t\t int c = 0; // count of parameters\n\t \t int p_c1 = 0, p_c2 =0; // counter to skip the first four config lines in the cpt of the fg file\n\t\t cout<<\" Crossover point is \"<< cr_pt<<endl;\n\t\t double pmut1=0, pmut2 =0;\n\t\t if (p1.is_open() && p2.is_open())\n\t\t {\n\t\t\t getline(p1,line1); getline(p2,line2);\n\t\t\t c1<< line1<<endl;\n\t\t\t c2<< line2<<endl;\t\t\t\t\t\n\n\t\t\t while(getline(p1,line1) && getline(p2,line2))\n\t\t\t {\n\t\t\t\t//////cout<<line1 << \" \"<< line2 <<endl;\n\t\t\t\tline1 = trim(line1); line2 = trim(line2);\n\t\t\t\tif(line1.empty())\n\t\t\t\t{\n\t\t\t\t\tc++; \t\n\t\t\t\t\tseed();\n\t\t\t\t \tc1<< line1<<endl;\n\t\t\t\t\tc2<< line2<<endl;\t\n\t\t\t\t\t//cout<<\"empty line\"<<endl;\t\t\t\t\t\t\t\t\t\t\t \n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t \t//cout<<\"Line number: \"<<p_c1<<\" \"<<p_c2<<endl;\n\t\t\t\t\t//cout<<\"Crossover point \"<<cr_pt<<\"our pt \"<<c<<\"pcross \"<<pcross<<\"pc \"<<pc<<endl;\n\t\t\t\t\tif(c <= cr_pt || pcross <= pc) // checking crossover probability\n\t\t\t\t\t{\t\t\t\t\n\t\t\t\t \t\tc1<< line1<<endl;\n\t\t\t\t\t\tc2<< line2<<endl;\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t//cout<<\"crossover happening\"<<endl;\n\t\t\t\t\t\tc2<< line1<<endl;\n\t\t\t\t\t\tc1<< line2<<endl;\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t }\n\t\t }\n\t\t p1.close(); p2.close();\n\t \t c1.close(); c2.close(); \n\t\t p=0;\t\n\t\t//break;\n\t\t}\n\n\t   }\n\t   else\n\t   {\n\t\tn=n-1;\n\t\tcontinue;\n\t   }   \n\t}\n}\n\nvoid replacementStrategy()\n{\n //int t=2;\n //cout<<\"In replacement strategy\"<<endl;\n\n double ll, ll1; \n\n\n string ssiters,ssiters1,ssll1,ssll,ssrunid, ssrunid1;\n //cout<<\"declarations done \"<<arrval[0]<<endl;\n for( size_t n = 0; n < population_size; n++ )\n {\n\tint val = arrval[n];\n\t//cout<<\"val = \"<<val<<endl;\n\tvector<EMRun*>::iterator it, it1; \n\tint i=0;\n\tfor (it=layer_prev.begin(); it != layer_prev.end(); ++it)\n        {    \n\t     // cout<<\"layer size \"<<layer.size()<<endl;\t\t   \n\t      ll = (*it)->getLL();\n\t      double iters = (*it)->getIters();\n\t      double runid = (*it)->getRun();\n\t      stringstream sll;\n\t      stringstream siters;\t \n              stringstream srunid;\t      \n\t      sll<<ll; ssll = sll.str();\n\t      siters <<iters; ssiters = siters.str();\n\t      srunid <<runid; ssrunid = srunid.str();\n\t     // cout<<\"runid = \"<<ssrunid<<\"  \"<<ssll<<\" \"<<ssiters<<endl;\n\t      if(val==runid)\n\t      {\n              //out1<<runid<<\" \"<<iters<<\" \";\n \t\t//cout<<val<<\" \"<<\"runid = \"<<ssrunid<<\"  \"<<ssll<<\" \"<<ssiters<<endl;\n\t\tbreak;\n\t      }\t\n\t}\n        for (it1=layer_curr.begin(); it1 != layer_curr.end(); ++it1)\n        {    \n\t     // cout<<\"layer size \"<<layer.size()<<endl;\t\t   \n\t      ll1 = (*it1)->getLL();\n\t      double iters1 = (*it1)->getIters();\n\t      double runid1 = (*it1)->getRun();\n              stringstream sll1;\n              stringstream siters1;\t \n              stringstream srunid1;\n\t      sll1<<ll1; ssll1 = sll1.str();\t      \n\t      siters1 <<iters1; ssiters1 = siters1.str();\n\t      srunid1 <<runid1; ssrunid1 = srunid1.str();\n\t     // cout<<\"runid = \"<<ssrunid1<<\"  \"<<ssll1<<\" \"<<ssiters1<<endl;\n\t      if(val==runid1)\n\t      {\n             // out1<<runid1<<\" \"<<iters1<<\" \";\n\t\t//cout<<val<<\" \"<<\"runid = \"<<ssrunid1<<\"  \"<<ssll1<<\" \"<<ssiters1<<endl;\n\t\tbreak;\n\t      }\t\n\t      i++;\n\t}\n\tif(ll<=ll1)\n\t{\n\t\tcout<<\"Child  has a better LL so leave the child as it is.\"<<endl;\n        //Writing the selected file to 0.log\n//        std::vector<Real> llTrace = (*it)->lastlog();\n//        \n//        for(std::vector<Real>::iterator logval = llTrace.begin(); logval != llTrace.end(); ++logval)\n//        {\n//            out1 << *logval<<\" \";\n//        }\n     //   out1<<\" \"<<endl;\n       out1<<population_no<<\"  \"<<ssrunid1<<\"  \"<<ssll1<<\" \"<<ssiters1<<endl;\n\t}\t\n\telse\n\t{\n\t\tstring dirname; \n\t\tstringstream p_id; \n\t\tp_id << population_no; \n\t\tdirname = p_id.str();\n\t\tstring dirname1; \n\t\tstringstream p_id1; \n\t\tp_id1 << population_no-1; \n\t\tdirname1 = p_id1.str();\n\t\t\n\t\tstring parentloc =  alarmlearnedfgloc + \"learned/\"+dirname1+\"/\"+networkname+\"_\"+ssrunid+\".fg\";\n\t\tstring childloc =  alarmlearnedfgloc + \"learned/\"+dirname+\"/\"+networkname+\"_\"+ssrunid1+\".fg\";\n\t\t//cout<<\"Copying files from \"<<parentloc<<\" to \"<<childloc<<endl;\n\t\tchar *ploc = &parentloc[0];\n\t\tchar *cloc = &childloc[0];\n\t\tcout<<\"Replace the child with the parent.\"<<childloc<<endl;\n\t\tremove(cloc);// remove the child file from the child folder inside the learned folder\n\t\tifstream parent(ploc);\n\t\tofstream child(cloc);\n\t\tchild << parent.rdbuf();// copy the parent file to the child folder location inside the learned folder\n\t\tchild.close(); parent.close();\n\t\tout1<<population_no<<\"  \"<<ssrunid<<\"  \"<<ssll<<\" \"<<ssiters<<endl;\n\t\t*it1=*it; //replacing the object in the layer_curr vector\n        //Writing the selected file to 0.log\n//        std::vector<Real> llTrace = (*it1)->lastlog();\n//        for(std::vector<Real>::iterator logval = llTrace.begin(); logval != llTrace.end(); ++logval)\n//        {\n//            out1 << *logval<<\" \";\n//        }\n//        out1<<\" \"<<endl;\n        \n\t}\n     \n }\n \n}\nbool myfn(int i, int j) { return i<j; }\n\nint indexofSmallestElement(double array[], int size)\n{\n    int index = 0 ;\n    double n = array[0] ;\n    for (int i = 1; i < size; ++i)\n    {\n        if (array[i] < n)\n        {\n            n = array[i] ;\n            index = i ;\n        }\n    }\n    return index;\n}\n\nint main(int argc, char *argv[]) {\ngenerator.seed(static_cast<unsigned int>(std::time(0)));\nconst char* fname =argv[2];\nconst char* fname1 =argv[6];\ngibbsfile = argv[1];\nemfile = argv[8];\nstringstream ss9( argv[9] );\nss9 << noVars;\nistringstream ss( argv[3] );\nss >> pm;\nstringstream ss1( argv[4] );\nss1 >> pc;\nstringstream ss2(argv[5]);\nalarmfgloc = ss2.str();\nalarmlearnedfgloc = ss2.str();\nnetworkname = argv[7];\nout.open(fname);\nout1.open(fname1);\ntime_t timer1, timer2;\ntime(&timer1);\nclock_t tStart = clock();\nwhile(population_no<max_gen)\n{\n\tstartEM();\n\tcheckEMforTermination(); \n\tcout<<\"population no\"<<population_no<<endl;\n\tif(population_no > 0)\n\t{\n\t  replacementStrategy();\n\t}\n\tdoCrossover();\n\tdoMutation();\n\t//cout<<\"Next population\"<<endl;\n\tpopulation_no=population_no+1;\n    int nocompare_gens = 4;\n//    if(population_no>=nocompare_gens)\n//    {\n//      \n//            for (int j=0; j<population_size; j++) {\n//                string number1;\n//                stringstream n_id1;\n//                n_id1<<j;\n//                number1 = n_id1.str();\n//                string dirname1;\n//                stringstream p_id1;\n//                p_id1<<population_no;\n//                dirname1 = p_id1.str();\n//                string fglearnedfileloc =  alarmlearnedfgloc + dirname1+\"/\"+networkname+\"_\"+number1+\".fg\";\n//                int n =nocompare_gens*population_size;\n//                double* distance = new double[n];\n//                int p=0;\n//                for (int i=0; i<nocompare_gens; i++)\n//                {\n//                    string dirname;\n//                    stringstream p_id;\n//                    p_id << i;\n//                    p_id1<<population_no;\n//                    dirname = p_id.str();\n//                    \n//                for (int k=0; k<population_size; k++) {\n//                    string number;\n//                    stringstream n_id;\n//                    n_id<<k;\n//                    number = n_id.str();\n//                    string fgfileloc =  alarmfgloc +dirname+\"/\"+networkname+\"_\"+number+\".fg\";\n//                    distance[p] = calculateDistance(fgfileloc,fglearnedfileloc);\n//                     out1<<distance[p]<<\" \";\n//                    cout<< dirname1+\"/\"+networkname+\"_\"+number1+\".fg and \"<<dirname+\"/\"+networkname+\"_\"+number+\".fg \"<<distance[p]<<endl;\n//                     p++;\n//                }\n//            }\n//                int index = indexofSmallestElement(distance,n);\n//                int dir = index/population_size;\n//                int fg = index % population_size;\n//                //cout<<\"index \"<<index;\n//                string sdir,sfg;\n//                stringstream ssdir,ssfg;\n//                ssdir<<dir; ssfg<<fg;\n//                sdir = ssdir.str();sfg = ssfg.str();\n//                string neighbor =  sdir+\"/\"+networkname+\"_\"+sfg+\".fg\";\n//                out1<<\"nearest neighbor of \"<<dirname1+\"/\"+networkname+\"_\"+number1+\".fg\"<<\" is \"<<neighbor << \" \"<<distance[index]<<endl;\n//                cout<<\" nearest neighbor of \"<<dirname1+\"/\"+networkname+\"_\"+number1+\".fg\"<<\" is \"<<neighbor << \" \"<<distance[index]<<endl;\n//        }\n//    }\n//    out1<<endl;\n    \n}\ntime(&timer2);\ndouble t = difftime(timer2,timer1);\ndouble t_c = (clock() - tStart)/CLOCKS_PER_SEC;\nout<<\"Time taken: \"<<t<<\"s\"<<endl;\nout<<\" Processor Time taken: \"<<t_c<<\"s\"<<endl;\nout.close();\nout1.close();\nreturn 0;\n}\n\n", "meta": {"hexsha": "f055777298f9b8f51ae36bd2901c946f44216231", "size": 49960, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/example_gaem_deterministic copy.cpp", "max_stars_repo_name": "Priyaaks/libDAI_P", "max_stars_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/example_gaem_deterministic copy.cpp", "max_issues_repo_name": "Priyaaks/libDAI_P", "max_issues_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/example_gaem_deterministic copy.cpp", "max_forks_repo_name": "Priyaaks/libDAI_P", "max_forks_repo_head_hexsha": "9f43da31b530bdf1d81d59213823029ff8902e4f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5639097744, "max_line_length": 215, "alphanum_fraction": 0.4350280224, "num_tokens": 11446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2444767708714831}}
{"text": "/////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\file  /utils/lmyengine/block_mat.cpp\n///\n/// \\brief  Implementation file for block recursive matrix class\n///\n/////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <vector>\n#include <list>\n#include <string>\n#include <numeric>\n#include <cassert>\n#include <algorithm>\n#include <cmath>\n#include <sstream>\n#include \"formic/utils/openmp.h\"\n\n#include <boost/format.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"formic/utils/matrix.h\"\n#include \"formic/utils/mpi_interface.h\"\n#include \"block_mat.h\"\n#include \"formic/utils/lmyengine/block_detail.h\"\n\n//////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief  Function that contracts each block's previous update components with derivative ratios\n///\n/// \\param[in]   dr        derivative ratio(bare or energy) for this sample\n/// \\param[in]   ou_mat    matrix holds old updates, size num_old_update * num_variables\n/// \\param[out]  cont_vec  contracted results\n///\n//////////////////////////////////////////////////////////////////////////////////////////////////\nvoid cqmc::engine::LMBlockerMatData::prep_block_ou_contractions(const std::vector<double> & dr, \n                                                                const formic::Matrix<double> & ou_mat, \n                                                                std::vector<formic::ColVec<double> > & cont_vec) {\n  \n  // loop over blocks\n  for (int b = 0; b < this->nb(); b++) {\n    \n    const int ibeg = 1 + m_block_beg.at(b);\n    const int len = m_block_len.at(b);\n\n    formic::ColVec<double> & cont = cont_vec.at(b);\n    for (int i = 0; i < cont.size(); i++)\n      cont.at(i) = 0.0;\n\n    for (int k = 0; k < m_nou; k++) {\n      for (int j = ibeg; j < ibeg+len; j++) {\n        cont.at(k) += dr.at(j) * ou_mat.at(j-1,k);\n      }\n    }\n  }\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief  Function that create a matrix in the basis of a block of variables and older updates \n///         from a different block\n///\n/// \\param[in]   b     block index\n/// \\param[in]   x     block index\n/// \\param[out]  mat   output matrix\n///\n////////////////////////////////////////////////////////////////////////////////////////////////\nvoid cqmc::engine::LMBlockerMatData::prep_lm_block_plus_other_ou_matrix(const int b, const int x, formic::Matrix<double> & mat) {\n\n  // first check that if x and b is the same block\n  if ( x == b ) \n    throw formic::Exception(\"b and x must be different in prep_lm_block_plus_other_ou_matrix\");\n\n  // get the length of this block\n  const int len = this->bl(b);\n\n  // get the dimension of this matrix \n  const int dim = 1 + len + m_nou;\n\n  const int y = x - ( x > b ? 1 : 0 ); \n  \n  // size the output matrix correctly\n  mat.reset(dim, dim);\n\n  // <wfn|wfn> element\n  mat.at(0,0) = m_ww[0]; \n  //std::cout << \"in prep_lm_block_plus_other_ou_matrix mat(0,0) is \" << m_ww << std::endl;\n\n  // <wfn|var>\n  for (int i = 0; i < len; i++) \n    mat.at(0, 1+i) = m_wv[0].at(b).at(i);\n\n  // <var|wfn>\n  for (int i = 0; i < len; i++)\n    mat.at(1+i, 0) = m_vw[0].at(b).at(i);\n\n  // <var|var>\n  for (int i = 0; i < len; i++) {\n    for (int j = 0; j < len; j++) {\n      mat.at(1+i,1+j) = m_vv[0].at(b).at(i,j);\n    }\n  }\n\n  // <wfn|old_update>\n  for (int k = 0; k < m_nou; k++) \n    mat.at(0, 1+len+k) = m_wo[0].at(x).at(k);\n\n  // <old_update_wfn>\n  for (int k = 0; k < m_nou; k++)\n    mat.at(1+len+k, 0) = m_ow[0].at(x).at(k);\n\n  // <var|old_update>\n  for (int i = 0; i < len; i++) {\n    for (int k = 0; k < m_nou; k++) {\n      mat.at(1+i, 1+len+k) = m_vo[0].at(b).at(i, y*m_nou+k);\n    }\n  }\n\n  // <old_update|var>\n  for (int k = 0; k < m_nou; k++) {\n    for (int i = 0; i < len; i++) {\n      mat.at(1+len+k, 1+i) = m_ov[0].at(b).at(y*m_nou+k, i);\n    }\n  }\n\n  // <old_update|old_update>\n  for (int k = 0; k < m_nou; k++) {\n    for (int l = 0; l < m_nou; l++) {\n      mat.at(1+len+k, 1+len+l) = m_oo[0].at(x).at(k,l);\n    }\n  }\n}\n\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief  Function that accumulates contribution to block matrices for this sample\n///\n/// \\param[in]   d        weight for this sample\n/// \\param[in]   lr       left vector for outer product\n/// \\param[in]   rr       right vector for outer product\n/// \\param[in]   ou_mat   matrix storing the old update coefficients\n///\n////////////////////////////////////////////////////////////////////////////////////////////////\nvoid cqmc::engine::LMBlockerMatData::acc(const double d, const std::vector<double> & lr, const std::vector<double> &rr, const formic::Matrix<double> & ou_mat) {\n  \n  // get the thread number \n  int myThread = omp_get_thread_num();\n\n  // check to see if the input vector is of the correct size\n  if ( lr.size() != 1 + this->tot_rows(m_vv[myThread]) )\n    throw formic::Exception(\"lr vector length was %i but should be %i LMBlockerMatData::acc\") % lr.size() % ( 1 + this->tot_rows(m_vv[myThread]) );\n  if ( rr.size() != 1 + this->tot_rows(m_vv[myThread]) )\n    throw formic::Exception(\"rr vector length was %i but should be %i LMBlockerMatData::acc\") % rr.size() % ( 1 + this->tot_rows(m_vv[myThread]) );\n\n  // prep intermediates for old updates\n  this->prep_block_ou_contractions(lr, ou_mat, m_boulr[myThread]);\n  this->prep_block_ou_contractions(rr, ou_mat, m_bourr[myThread]);\n\n  // <wfn|wfn>\n  m_ww[myThread] += d * lr.at(0) * rr.at(0);\n\n  // loop over blocks\n  for (int b = 0; b < this->nb(); b++) {\n    \n    // beginning index\n    const int ibeg = 1 + m_block_beg.at(b);\n\n    // block length\n    const int len = m_block_len.at(b);\n\n    for (int i = 0; i < len; i++) {\n\n      // <wfn|var>\n      m_wv[myThread].at(b).at(i) += d * lr.at(0) * rr.at(ibeg + i);\n\n      // <var|wfn>\n      m_vw[myThread].at(b).at(i) += d * lr.at(ibeg + i) * rr.at(0);\n\n    }\n\n    for (int k = 0; k < m_nou; k++) {\n\n      // <wfn|old_updates>\n      m_wo[myThread].at(b).at(k) += d * lr.at(0) * m_bourr[myThread].at(b).at(k);\n      \n      // <old_updates|wfn>\n      m_ow[myThread].at(b).at(k) += d * m_boulr[myThread].at(b).at(k) * rr.at(0);\n    }\n\n    // <var|var>\n    { formic::Matrix<double> & vv_mat = m_vv[myThread].at(b);\n      for (int i = 0; i < len; i++) {\n        for (int j = 0; j < len; j++) {\n          vv_mat.at(i,j) += d * lr.at(ibeg+i) * rr.at(ibeg+j);\n        }\n      }\n    }\n\n    // <var|old_update> note this is for var in the current block and old-update in all other blocks\n    { formic::Matrix<double> & vo_mat = m_vo[myThread].at(b);\n      for (int x = 0, y = 0; x < this->nb(); x++) {\n        if ( x == b )\n          continue;\n        const formic::ColVec<double> & rr_vec = m_bourr[myThread].at(x);\n        for (int o = 0; o < m_nou; o++) {\n          for (int i = 0; i < len; i++) {\n            vo_mat.at(i,y*m_nou+o) += d * lr.at(ibeg+i) * rr_vec.at(o);\n           }\n         } \n         y++;\n       } \n     } \n\n     // <old_update|var> note this is for var in the current block and old-update in all other blocks\n     { formic::Matrix<double> & ov_mat = m_ov[myThread].at(b);\n       for (int i = 0; i < len; i++) {\n         for (int x = 0, y = 0; x < this->nb(); x++) {\n           if ( x == b ) \n             continue;\n           const formic::ColVec<double> & lr_vec = m_boulr[myThread].at(x);\n           for (int k = 0; k < m_nou; k++) {\n             ov_mat.at(m_nou*y+k, i) += d * lr_vec.at(k) * rr.at(ibeg+i);\n           }\n           y++;\n         }\n       }\n     }\n\n     // <old_update|old_update>\n     { formic::Matrix<double> & oo_mat = m_oo[myThread].at(b);\n       for (int k = 0; k < m_nou; k++) {\n         for (int l = 0; l < m_nou; l++) {\n           oo_mat.at(k,l) += d * m_boulr[myThread].at(b).at(k) * m_bourr[myThread].at(b).at(l);\n         }\n       }\n     }\n   }\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief  Function that finalizes the accumulation by dividing matrices total weight\n///\n////////////////////////////////////////////////////////////////////////////////////////////////\nvoid cqmc::engine::LMBlockerMatData::finalize(const double total_weight) {\n  \n  // get the number of threads\n  int NumThreads = omp_get_max_threads();\n\n  // sum over threads\n  for (int ip = 1; ip < NumThreads; ip++) {\n    m_ww[0] += m_ww[ip];\n    for (int b = 0; b < this->nb(); b++) {\n      m_wv[0].at(b) += m_wv[ip].at(b);\n      m_vw[0].at(b) += m_vw[ip].at(b);\n      m_wo[0].at(b) += m_wo[ip].at(b);\n      m_ow[0].at(b) += m_ow[ip].at(b);\n      m_ov[0].at(b) += m_ov[ip].at(b);\n      m_vo[0].at(b) += m_vo[ip].at(b);\n      m_oo[0].at(b) += m_oo[ip].at(b);\n    }\n  }\n  \n  // <wfn|wfn>\n  m_ww[0] /= total_weight;\n\n  // loop over blocks\n  for (int b = 0; b < this->nb(); b++) {\n    m_wv[0].at(b) /= total_weight;\n    m_vw[0].at(b) /= total_weight;\n    m_vv[0].at(b) /= total_weight;\n    m_wo[0].at(b) /= total_weight;\n    m_ow[0].at(b) /= total_weight;\n    m_ov[0].at(b) /= total_weight;\n    m_vo[0].at(b) /= total_weight;\n    m_oo[0].at(b) /= total_weight;\n  }\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief  Function that finalizes the accumulation by dividing matrices total weight \n///         across the whole processes\n///\n////////////////////////////////////////////////////////////////////////////////////////////////\nvoid cqmc::engine::LMBlockerMatData::mpi_finalize(const double total_weight) {\n  \n  // get rank number and number of ranks\n  int my_rank = formic::mpi::rank();\n\n  // get the number of threads \n  int NumThreads = omp_get_max_threads();\n\n  // loop over blocks\n  //for (int b = 0; b < this->nb(); b++) {\n  //  // print out to debug\n  //  for (int i = 0; i < m_ow.at(b).size(); i++) {\n  //    std::cout << m_ow.at(b).at(i) << \"   \";\n  //  }\n  //  std::cout << std::endl;\n  //}\n  //std::cout << std::endl;\n\n  // sum over threads\n  for (int ip = 1; ip < NumThreads; ip++) {\n    m_ww[0] += m_ww[ip];\n    for (int b = 0; b < this->nb(); b++) {\n      m_wv[0].at(b) += m_wv[ip].at(b);\n      m_vw[0].at(b) += m_vw[ip].at(b);\n      m_vv[0].at(b) += m_vv[ip].at(b);\n      m_wo[0].at(b) += m_wo[ip].at(b);\n      m_ow[0].at(b) += m_ow[ip].at(b);\n      m_ov[0].at(b) += m_ov[ip].at(b);\n      m_vo[0].at(b) += m_vo[ip].at(b);\n      m_oo[0].at(b) += m_oo[ip].at(b);\n    }\n  }\n\n  // <wfn|wfn>\n  double m_ww_tot = 0.0;\n  formic::mpi::reduce(&m_ww[0], &m_ww_tot, 1, MPI_SUM);\n  //MPI_Reduce(&m_ww, &m_ww_tot, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);\n  m_ww[0] = m_ww_tot / total_weight;\n\n  // get space for MPI reduce \n  std::vector<formic::ColVec<double> > m_wv_tot, m_vw_tot, m_wo_tot, m_ow_tot;\n  std::vector<formic::Matrix<double> > m_vv_tot, m_vo_tot, m_ov_tot, m_oo_tot;\n  for (int i = 0; i < this->nb(); i++) {\n    m_wv_tot.push_back(formic::ColVec<double>(this->bl(i), 0.0));\n    m_vw_tot.push_back(formic::ColVec<double>(this->bl(i), 0.0));\n    m_vv_tot.push_back(formic::Matrix<double>(this->bl(i), this->bl(i), 0.0));\n    m_wo_tot.push_back(formic::ColVec<double>(m_nou, 0.0));\n    m_ow_tot.push_back(formic::ColVec<double>(m_nou, 0.0));\n    m_ov_tot.push_back(formic::Matrix<double>((this->nb()-1)*m_nou, this->bl(i), 0.0));\n    m_vo_tot.push_back(formic::Matrix<double>(this->bl(i), (this->nb()-1)*m_nou, 0.0));\n    m_oo_tot.push_back(formic::Matrix<double>(m_nou, m_nou, 0.0));\n  }\n\n  // do MPI reduce\n  for (int i = 0; i < this->nb(); i++) {\n    formic::mpi::reduce(&m_wv[0].at(i).at(0), &m_wv_tot.at(i).at(0), this->bl(i), MPI_SUM);\n    formic::mpi::reduce(&m_vw[0].at(i).at(0), &m_vw_tot.at(i).at(0), this->bl(i), MPI_SUM);\n    formic::mpi::reduce(&m_vv[0].at(i).at(0,0), &m_vv_tot.at(i).at(0,0), m_vv[0].at(i).size(), MPI_SUM);\n    formic::mpi::reduce(&m_wo[0].at(i).at(0), &m_wo_tot.at(i).at(0), m_nou, MPI_SUM);\n    formic::mpi::reduce(&m_ow[0].at(i).at(0), &m_ow_tot.at(i).at(0), m_nou, MPI_SUM);\n    formic::mpi::reduce(&m_ov[0].at(i).at(0,0), &m_ov_tot.at(i).at(0,0), m_ov[0].at(i).size(), MPI_SUM);\n    formic::mpi::reduce(&m_vo[0].at(i).at(0,0), &m_vo_tot.at(i).at(0,0), m_vo[0].at(i).size(), MPI_SUM);\n    formic::mpi::reduce(&m_oo[0].at(i).at(0,0), &m_oo_tot.at(i).at(0,0), m_oo[0].at(i).size(), MPI_SUM);\n  }\n\n  // evaluate the average across all processors\n  if ( my_rank == 0 ) {\n    \n    // loop over blocks\n    for (int b = 0; b < this->nb(); b++) {\n      m_vw[0].at(b) = m_vw_tot.at(b) / total_weight;\n      m_wv[0].at(b) = m_wv_tot.at(b) / total_weight;\n      m_vv[0].at(b) = m_vv_tot.at(b) / total_weight;\n      m_ow[0].at(b) = m_ow_tot.at(b) / total_weight;\n      m_wo[0].at(b) = m_wo_tot.at(b) / total_weight;\n      m_vo[0].at(b) = m_vo_tot.at(b) / total_weight;\n      m_ov[0].at(b) = m_ov_tot.at(b) / total_weight;\n      m_oo[0].at(b) = m_oo_tot.at(b) / total_weight;\n      // print out to debug\n      //for (int i = 0; i < m_ow.at(b).size(); i++) {\n      //  std::cout << m_ow.at(b).at(i) << \"   \";\n      //}\n      //std::cout << std::endl;\n    }\n  }\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////\n/// \\brief  Function that resets the matrices\n///\n/////////////////////////////////////////////////////////////////////////////////////////////////\nvoid cqmc::engine::LMBlockerMatData::reset(const int nv, const int nblock, const int nou) {\n  \n  m_nou = nou;\n\n  // get block information\n  cqmc::engine::brlm_get_block_info(nv, nblock, m_block_beg, m_block_end, m_block_len);\n\n  // get the maximum number of threads \n  int NumThreads = omp_get_max_threads();\n  \n  m_ww.assign(NumThreads, 0.0);\n\n  m_wv.clear();\n  m_wv.resize(NumThreads);\n  for (int ip = 0; ip < NumThreads; ip++) {\n    for (int i = 0; i < this->nb(); i++) {\n      m_wv[ip].push_back(formic::ColVec<double>(this->bl(i), 0.0));\n    }\n  }\n\n  m_vw.clear();\n  m_vw.resize(NumThreads);\n  for (int ip = 0; ip < NumThreads; ip++) {\n    for (int i = 0; i < this->nb(); i++) {\n      m_vw[ip].push_back(formic::ColVec<double>(this->bl(i), 0.0));\n    }\n  }\n\n  m_vv.clear();\n  m_vv.resize(NumThreads);\n  for (int ip = 0; ip < NumThreads; ip++) {\n    for (int i = 0; i < this->nb(); i++) {\n      m_vv[ip].push_back(formic::Matrix<double>(this->bl(i), this->bl(i), 0.0));\n    }\n  }\n\n  m_wo.clear();\n  m_wo.resize(NumThreads);\n  for (int ip = 0; ip < NumThreads; ip++) {\n    for (int i = 0; i < this->nb(); i++) {\n      m_wo[ip].push_back(formic::ColVec<double>(m_nou, 0.0));\n    }\n  }\n\n  m_ow.clear();\n  m_ow.resize(NumThreads);\n  for (int ip = 0; ip < NumThreads; ip++) {\n    for (int i = 0; i < this->nb(); i++) {\n      m_ow[ip].push_back(formic::ColVec<double>(m_nou, 0.0));\n    }\n  }\n\n  m_vo.clear();\n  m_vo.resize(NumThreads);\n  for (int ip = 0; ip < NumThreads; ip++) {\n    for (int i = 0; i < this->nb(); i++) {\n      m_vo[ip].push_back(formic::Matrix<double>(this->bl(i), (this->nb()-1)*m_nou, 0.0));\n    }\n  }\n\n  m_ov.clear();\n  m_ov.resize(NumThreads);\n  for (int ip = 0; ip < NumThreads; ip++) {\n    for (int i = 0; i < this->nb(); i++) {\n      m_ov[ip].push_back(formic::Matrix<double>((this->nb()-1)*m_nou, this->bl(i), 0.0));\n    }\n  }\n\n  m_oo.clear();\n  m_oo.resize(NumThreads);\n  for (int ip = 0; ip < NumThreads; ip++) {\n    for (int i = 0; i < this->nb(); i++) {\n      m_oo[ip].push_back(formic::Matrix<double>(m_nou, m_nou, 0.0));\n    }\n  }\n\n  m_boulr.clear();\n  m_bourr.clear();\n  m_boulr.resize(NumThreads);\n  m_bourr.resize(NumThreads);\n  for (int ip = 0; ip < NumThreads; ip++) {\n    for (int i = 0; i < this->nb(); i++) {\n      m_boulr[ip].push_back(formic::ColVec<double>(m_nou, 0.0));\n      m_bourr[ip].push_back(formic::ColVec<double>(m_nou, 0.0));\n    }\n  }\n}\n\n", "meta": {"hexsha": "c28bdeaee153bf73d131a6d73fbec0ac8c843544", "size": 15715, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/formic/utils/lmyengine/block_mat.cpp", "max_stars_repo_name": "eugeneswalker/qmcpack", "max_stars_repo_head_hexsha": "352ff27f163bb92e0c232c48bec8ae7951ed9d8c", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/formic/utils/lmyengine/block_mat.cpp", "max_issues_repo_name": "eugeneswalker/qmcpack", "max_issues_repo_head_hexsha": "352ff27f163bb92e0c232c48bec8ae7951ed9d8c", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-09T20:57:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T00:00:17.000Z", "max_forks_repo_path": "src/formic/utils/lmyengine/block_mat.cpp", "max_forks_repo_name": "williamfgc/qmcpack", "max_forks_repo_head_hexsha": "732b473841e7823a21ab55ff397eed059f0f2e96", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1630434783, "max_line_length": 160, "alphanum_fraction": 0.5101495387, "num_tokens": 5159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24444867830982886}}
{"text": "/*!\n * @file swp_surfvol_cubic_primary.cpp\n * @author Robert Patterson\n *\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n  \n  Copyright (C) 2013 Robert I A Patterson\n\n  File purpose:\n    Implementation of a particle the approximates cuboidal crystals by\n    storing their surface area and volume\n    @brief Implementation of cuboidal crystals described by volume and surface area.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU General Public License\n    as published by the Free Software Foundation; either version 2\n    of the License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Prof Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_surfvol_cubic_primary.h\"\n\n#include \"swp_aggmodel_type.h\"\n#include \"swp_model_factory.h\"\n\n#include <stdexcept>\n#include <boost/random/poisson_distribution.hpp>\n\nusing namespace Sweep;\nusing namespace Sweep::AggModels;\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor (protected).\nSurfVolCubicPrimary::SurfVolCubicPrimary(void)\n{\n}\n\n// Initialising constructor.\nSurfVolCubicPrimary::SurfVolCubicPrimary(double time, const Sweep::ParticleModel &model)\n: Primary(time, model)\n{\n}\n\n// Copy constructor.\nSurfVolCubicPrimary::SurfVolCubicPrimary(const SurfVolCubicPrimary &copy)\n{\n    *this = copy;\n}\n\n// Stream-reading constructor.\nSurfVolCubicPrimary::SurfVolCubicPrimary(std::istream &in, const Sweep::ParticleModel &model)\n{\n    Deserialize(in, model);\n}\n\n// Default destructor.\nSurfVolCubicPrimary::~SurfVolCubicPrimary()\n{\n    releaseMem();\n}\n\n\n// OPERATOR OVERLOADS.\n\n// Assignment operator (Primary RHS).\nSurfVolCubicPrimary &SurfVolCubicPrimary::operator=(const Primary &rhs)\n{\n    operator=(dynamic_cast<const SurfVolCubicPrimary&>(rhs));\n    return *this;\n}\n\n// AGGREGATION MODEL.\n\n// Returns the aggregation model which this primary describes.\nAggModels::AggModelType SurfVolCubicPrimary::AggID(void) const {return AggModels::SurfVolCubic_ID;}\n\n// BASIC DERIVED PARTICLE PROPERTIES.\n\n// Calculates the derived properties from the unique properties.  This\n// function is broadly similar to the version in the spherical Primary\n// class except that it uses the surface-volume model.  Therefore the\n// surface area is not altered and the collision diameter is calculated\n// using the arithmetic mean function.\n//\n// Mobility diameter:\n// This calculation is based on the work of Rogak et al., 1993 Aer. Sci.\n// Tech. 18:25-47, who give the calculation of dmob in the FM, SF and\n// transition regime.\nvoid SurfVolCubicPrimary::UpdateCache(void)\n{\n    // Store the old surface area, this value may be 0 if the particle is in\n    // the process of initialisation\n    double s = m_surf;\n\n    // Pretend that the primary is spherical and set the cache\n    // accordingly.\n    Primary::UpdateCache();\n\n    m_surf = std::max(s, m_surf);\n\n   \n    // Calculate diameters.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n\n    // Calculate mobility diameter\n    m_dmob = PP_Diameter();\n    if (false) {\n        // SF regime mobility diameter\n        m_dmob *= 0.9 * sqrt(m_pmodel->GetFractDim() / (m_pmodel->GetFractDim() + 2));\n        m_dmob *= pow(PP_Count(), (1.0/m_pmodel->GetFractDim()));\n    } else {\n        // FM regime mobility diameter\n        m_dmob *= sqrt(0.802*(PP_Count()-1) + 1);\n    }\n\n    if (m_dmob < m_diam) m_dmob = m_diam;\n}\n\n// Returns the number of primary particles if the aggregate is assumed\n// to consist of mono-sized primaries.\nunsigned int SurfVolCubicPrimary::PP_Count(void) const\n{\n    // Note the minimum number of primary particles must be 1.\n    return std::max(1u, (unsigned int)((m_surf * m_surf * m_surf) /\n                                       (36.0 * PI * m_vol * m_vol)));\n}\n\n// Returns the primary particle diameter if the aggregate is assumed\n// to consist of mono-sized primaries.\ndouble SurfVolCubicPrimary::PP_Diameter(void) const\n{\n    // This should always be <= equiv. sphere diameter.\n    return 6.0 * m_vol / m_surf;\n}\n\n\n// OPERATIONS.\n\n// Adjusts the primary with the given composition and \n// tracker values changes n times.  If the particle cannot be adjust\n// n times, then this function returns the number of times\n// it was adjusted.\nunsigned int SurfVolCubicPrimary::Adjust(const fvector &dcomp, const fvector &dvalues, rng_type &rng,\n                                    unsigned int n)\n{\n    // Store initial surface and volume\n    double surfOld = m_surf;\n    double volOld  = m_vol;\n\n    // Adjust the particle assuming that it is spherical.\n    n = Primary::Adjust(dcomp, dvalues, rng, n);\n\n\n    // Calculate change in volume.\n    double dvol = 0.0;\n    for (unsigned int i=0; i!=dcomp.size(); ++i) {\n        dvol += dcomp[i] * m_pmodel->Components(i)->MolWt() / \n                m_pmodel->Components(i)->Density();\n    }\n    dvol *= (double)n / NA;\n\n    // Calculate change in surface area.\n    double invRadius = 0.0;\n    if (dvol > 0.0) {\n        // Inverse growth radius.\n        invRadius = sqrt(4.0 * PI / surfOld);\n    } else {\n        // Inverse oxidation radius.    \n        invRadius = surfOld / (3.0 * volOld);\n    }\n\n    // Save new surface area.\n    double s = surfOld + (2.0 * dvol * invRadius);\n\n    // Set correct surface area, which was incorrectly set by\n    // Primary::Adjust.\n    m_surf    = s;\n\n    // This has a knock-on affect of changing the collision diameter.\n    // Note, we can avoid recalling UpdateCache() here, because only\n    // a couple of cached values will have changed.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n    m_dmob = m_dcol;\n\n    return n;\n}\n\n/*!\n * Combines this primary with another.\n *\n * \\param[in]       rhs         Particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      Reference to the current instance after rhs has been added\n */\nSurfVolCubicPrimary &SurfVolCubicPrimary::Coagulate(const Primary &rhs, rng_type &rng)\n\n{\n    // Store the resultant surface area.\n    double s = m_surf + rhs.SurfaceArea();\n\n    // Perform the coagulation.\n    Primary::Coagulate(rhs, rng);\n\n    // One sixth of the surface area is assumed to be lost as a result of two faces, one\n    // from each incoming particle covering each other.  More sophisticated formulae\n    // could be implemented here.\n    m_surf = s * 0.8333333333333333333;\n\n    // This has a knock-on affect of changing the collision diameter.\n    // Note, we can avoid recalling UpdateCache() here, because only\n    // a couple of cached values will have changed.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n    m_dmob = m_dcol;\n\n    return *this;\n}\n\n/*!\n * Combines this primary with another.\n *\n * \\param[in]       rhs         Particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      Reference to the current instance after rhs has been added\n */\nSurfVolCubicPrimary &SurfVolCubicPrimary::Fragment(const Primary &rhs, rng_type &rng)\n\n{\n    // Store the resultant surface area.\n    double s = m_surf + rhs.SurfaceArea();\n\n    // Perform the coagulation.\n    Primary::Fragment(rhs, rng);\n\n    // One sixth of the surface area is assumed to be lost as a result of two faces, one\n    // from each incoming particle covering each other.  More sophisticated formulae\n    // could be implemented here.\n    m_surf = s * 0.8333333333333333333;\n\n    // This has a knock-on affect of changing the collision diameter.\n    // Note, we can avoid recalling UpdateCache() here, because only\n    // a couple of cached values will have changed.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n    m_dmob = m_dcol;\n\n    return *this;\n}\n\n// READ/WRITE/COPY.\n\n//! Returns a copy of the model data.\nSurfVolCubicPrimary *const SurfVolCubicPrimary::Clone(void) const\n{\n    return new SurfVolCubicPrimary(*this);\n}\n\n// Writes the object to a binary stream.\nvoid SurfVolCubicPrimary::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output base class.\n        Primary::Serialize(out);\n    } else {\n        throw std::invalid_argument(\"Output stream not ready \"\n                                    \"(Sweep, SurfVolCubicPrimary::Serialize).\");\n    }\n}\n\n// Reads the object from a binary stream.\nvoid SurfVolCubicPrimary::Deserialize(std::istream &in, const Sweep::ParticleModel &model)\n{\n    if (in.good()) {\n        // Read base class.\n        Primary::Deserialize(in, model);\n    } else {\n        throw std::invalid_argument(\"Input stream not ready \"\n                                    \"(Sweep, SurfVolCubicPrimary::Deserialize).\");\n    }\n}\n", "meta": {"hexsha": "32b9feb24bc440649f537695a59b1afdef8901f7", "size": 9308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_surfvol_cubic_primary.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_surfvol_cubic_primary.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_surfvol_cubic_primary.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 30.319218241, "max_line_length": 101, "alphanum_fraction": 0.6773743017, "num_tokens": 2348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.2444486783098288}}
{"text": "#include <sstream>\n#include <limits>\n#include <cstdlib> /* srand, rand */\n#include <cmath>\n\n#include <boost/math/distributions/negative_binomial.hpp>\n#include <boost/log/trivial.hpp>\n\n#include \"kmergraphwithcoverage.h\"\n#include \"localPRG.h\"\n\nusing namespace prg;\n\nvoid KmerGraphWithCoverage::set_exp_depth_covg(const uint32_t edp)\n{\n    const bool exp_depth_covg_parameter_is_valid = edp > 0;\n    if (!exp_depth_covg_parameter_is_valid) {\n        fatal_error(\n            \"Error setting exp_depth_covg: exp_depth_covg is invalid, must be > 0, is \",\n            edp);\n    }\n    exp_depth_covg = edp;\n}\n\nvoid KmerGraphWithCoverage::set_binomial_parameter_p(const float e_rate)\n{\n    BOOST_LOG_TRIVIAL(debug) << \"Set p in kmergraph\";\n\n    const bool valid_parameters_to_set_p\n        = (kmer_prg->k != 0) && (0 < e_rate and e_rate < 1);\n    if (!valid_parameters_to_set_p) {\n        fatal_error(\"Error setting binomial parameter p, invalid parameters: \",\n            \"kmer_prg->k = \", kmer_prg->k, \", e_rate = \", e_rate);\n    }\n\n    binomial_parameter_p = 1 / exp(e_rate * kmer_prg->k);\n}\n\nvoid KmerGraphWithCoverage::increment_covg(\n    uint32_t node_id, pandora::Strand strand, uint32_t sample_id)\n{\n    const bool sample_is_valid\n        = this->node_index_to_sample_coverage[node_id].size() > sample_id;\n    if (!sample_is_valid) {\n        fatal_error(\n            \"Error incrementing coverage: sample_id is invalid (\", sample_id, \")\");\n    }\n\n    // get a pointer to the value we want to increment\n    uint16_t* coverage_ptr = nullptr;\n    if (strand == pandora::Strand::Forward) {\n        coverage_ptr = &(this->node_index_to_sample_coverage[node_id][sample_id].first);\n    } else {\n        coverage_ptr\n            = &(this->node_index_to_sample_coverage[node_id][sample_id].second);\n    }\n\n    const bool safe_to_increase_covg { (*coverage_ptr) < UINT16_MAX };\n    if (safe_to_increase_covg) {\n        ++(*coverage_ptr);\n    }\n}\n\nuint32_t KmerGraphWithCoverage::get_covg(\n    uint32_t node_id, pandora::Strand strand, uint32_t sample_id) const\n{\n\n    if (this->node_index_to_sample_coverage[node_id].size() <= sample_id)\n        return 0;\n\n    if (strand == pandora::Strand::Forward) {\n        return (uint32_t)(\n            this->node_index_to_sample_coverage[node_id][sample_id].first);\n    } else {\n        return (uint32_t)(\n            this->node_index_to_sample_coverage[node_id][sample_id].second);\n    }\n}\n\nvoid KmerGraphWithCoverage::set_covg(\n    uint32_t node_id, uint16_t value, pandora::Strand strand, uint32_t sample_id)\n{\n    const bool sample_is_valid\n        = this->node_index_to_sample_coverage[node_id].size() > sample_id;\n    if (!sample_is_valid) {\n        fatal_error(\"Error setting coverage: sample_id is invalid (\", sample_id, \")\");\n    }\n\n    if (strand == pandora::Strand::Forward) {\n        this->node_index_to_sample_coverage[node_id][sample_id].first = value;\n    } else {\n        this->node_index_to_sample_coverage[node_id][sample_id].second = value;\n    }\n}\n\nvoid KmerGraphWithCoverage::set_negative_binomial_parameters(\n    const float& nbin_prob, const float& nb_fail)\n{\n    if (nbin_prob == 0 and nb_fail == 0)\n        return;\n\n    const bool negative_binomial_parameters_were_previously_set\n        = (negative_binomial_parameter_p > 0 and negative_binomial_parameter_p < 1)\n        && (negative_binomial_parameter_r > 0);\n    if (!(negative_binomial_parameters_were_previously_set)) {\n        fatal_error(\"Error setting negative_binomial_parameters: \"\n                    \"negative_binomial_parameter_p (\",\n            negative_binomial_parameter_p, \")\", \" or negative_binomial_parameter_r (\",\n            negative_binomial_parameter_r, \") \", \"were not correctly set\");\n    }\n\n    negative_binomial_parameter_p += nbin_prob;\n    negative_binomial_parameter_r += nb_fail;\n}\n\nfloat KmerGraphWithCoverage::nbin_prob(uint32_t node_id, const uint32_t& sample_id)\n{\n    auto k = this->get_forward_covg(node_id, sample_id)\n        + this->get_reverse_covg(node_id, sample_id);\n    float return_prob\n        = log(pdf(boost::math::negative_binomial(\n                      negative_binomial_parameter_r, negative_binomial_parameter_p),\n            k));\n    return_prob = std::max(return_prob, std::numeric_limits<float>::lowest() / 1000);\n    return return_prob;\n}\n\nfloat KmerGraphWithCoverage::lin_prob(uint32_t node_id, const uint32_t& sample_id)\n{\n    const bool reads_were_mapped_to_this_kmer_graph = num_reads != 0;\n    if (!reads_were_mapped_to_this_kmer_graph) {\n        fatal_error(\n            \"Impossible to compute lin_prob, no reads were mapped to this kmer graph\");\n    }\n    auto k = this->get_forward_covg(node_id, sample_id)\n        + this->get_reverse_covg(node_id, sample_id);\n    return log(float(k) / num_reads);\n}\n\nfloat KmerGraphWithCoverage::bin_prob(uint32_t node_id, const uint32_t& sample_id)\n{\n    const bool reads_were_mapped_to_this_kmer_graph = num_reads != 0;\n    if (!reads_were_mapped_to_this_kmer_graph) {\n        fatal_error(\n            \"Impossible to compute bin_prob, no reads were mapped to this kmer graph\");\n    }\n    return bin_prob(node_id, num_reads, sample_id);\n}\n\nfloat KmerGraphWithCoverage::bin_prob(\n    const uint32_t& node_id, const uint32_t& num, const uint32_t& sample_id)\n{\n    const bool binomial_parameter_p_is_set_correctly = binomial_parameter_p != 1;\n    if (!binomial_parameter_p_is_set_correctly) {\n        fatal_error(\"Error when computing bin_prob: binomial_parameter_p (\",\n            binomial_parameter_p, \") is not correctly set\");\n    }\n\n    const bool node_exists = node_id < kmer_prg->nodes.size();\n    if (!node_exists) {\n        fatal_error(\"Error when computing bin_prob: attempt to access inexistent node \",\n            node_id);\n    }\n\n    uint32_t sum_coverages = this->get_forward_covg(node_id, sample_id)\n        + this->get_reverse_covg(node_id, sample_id);\n\n    float return_prob;\n    if (node_id == (*(kmer_prg->sorted_nodes.begin()))->id\n        or node_id == (*(kmer_prg->sorted_nodes.rbegin()))->id) {\n        return_prob = 0; // is really undefined\n    } else if (sum_coverages > num) {\n        // under model assumptions this can't happen, but it inevitably will, so bodge\n        return_prob\n            = lognchoosek2(sum_coverages, this->get_forward_covg(node_id, sample_id),\n                  this->get_reverse_covg(node_id, sample_id))\n            + sum_coverages * log(binomial_parameter_p / 2);\n        // note this may give disadvantage to repeat kmers\n    } else {\n        return_prob = lognchoosek2(num, this->get_forward_covg(node_id, sample_id),\n                          this->get_reverse_covg(node_id, sample_id))\n            + sum_coverages * log(binomial_parameter_p / 2)\n            + (num - sum_coverages) * log(1 - binomial_parameter_p);\n    }\n    return return_prob;\n}\n\nfloat KmerGraphWithCoverage::get_prob(\n    const std::string& prob_model, const uint32_t& node_id, const uint32_t& sample_id)\n{\n    if (prob_model == \"nbin\") {\n        // is there no parameter check here?\n        return nbin_prob(node_id, sample_id);\n    } else if (prob_model == \"bin\") {\n        const bool binomial_parameters_are_ok\n            = (binomial_parameter_p < 1) && (num_reads > 0);\n        if (!binomial_parameters_are_ok) {\n            fatal_error(\"Error when computing kmer prob: binomial parameters are not \"\n                        \"ok (binomial_parameter_p = \",\n                binomial_parameter_p, \", \", \"num_reads = \", num_reads);\n        }\n        return bin_prob(node_id, sample_id);\n    } else if (prob_model == \"lin\") {\n        // is there no parameter check here?\n        return lin_prob(node_id, sample_id);\n    } else {\n        fatal_error(\"Invalid probability model for kmer coverage distribution: \",\n            prob_model, \". Should be nbin, bin or lin\");\n    }\n}\n\nbool KmerGraphWithCoverage::coverage_is_zeroes(const uint32_t& sample_id)\n{\n    bool all_zero = true;\n    for (const auto& node_ptr : kmer_prg->nodes) {\n        const auto covg { this->get_forward_covg(node_ptr->id, sample_id)\n            + this->get_reverse_covg(node_ptr->id, sample_id) };\n        if (covg > 0) {\n            BOOST_LOG_TRIVIAL(debug) << \"Found non-zero coverage in kmer graph\";\n            all_zero = false;\n            break;\n        }\n    }\n    if (all_zero) {\n        BOOST_LOG_TRIVIAL(debug) << \"ALL ZEROES in kmer graph coverages\";\n    }\n    return all_zero;\n}\n\nfloat KmerGraphWithCoverage::find_max_path(std::vector<KmerNodePtr>& maxpath,\n    const std::string& prob_model, const uint32_t& max_num_kmers_to_average,\n    const uint32_t& sample_id)\n{\n    // TODO: FIX THIS INNEFICIENCY I INTRODUCED\n    const std::vector<KmerNodePtr> sorted_nodes(\n        this->kmer_prg->sorted_nodes.begin(), this->kmer_prg->sorted_nodes.end());\n    this->kmer_prg->check();\n\n    // also check not all 0 covgs\n    auto coverages_all_zero = coverage_is_zeroes(sample_id);\n    if (coverages_all_zero)\n        return std::numeric_limits<float>::lowest();\n\n    // create vectors to hold the intermediate values\n    std::vector<float> max_sum_of_log_probs_from_node(sorted_nodes.size(), 0);\n    std::vector<uint32_t> length_of_maxpath_from_node(sorted_nodes.size(), 0);\n    std::vector<uint32_t> prev_node_along_maxpath(\n        sorted_nodes.size(), sorted_nodes.size() - 1);\n    float max_mean;\n    int max_length;\n    const float tolerance = 0.000001;\n\n    for (uint32_t j = sorted_nodes.size() - 1; j != 0; --j) {\n        max_mean = std::numeric_limits<float>::lowest();\n        max_length = 0; // tie break with longest kmer path\n        const auto& current_node = sorted_nodes[j - 1];\n        for (uint32_t i = 0; i != current_node->out_nodes.size(); ++i) {\n            const auto& considered_outnode = current_node->out_nodes[i].lock();\n            const bool is_terminus_and_most_likely\n                = considered_outnode->id == sorted_nodes.back()->id\n                and thresh > max_mean + tolerance;\n            const bool avg_log_likelihood_is_most_likely\n                = max_sum_of_log_probs_from_node[considered_outnode->id]\n                    / length_of_maxpath_from_node[considered_outnode->id]\n                > max_mean + tolerance;\n            const bool avg_log_likelihood_is_close_to_most_likely = max_mean\n                    - max_sum_of_log_probs_from_node[considered_outnode->id]\n                        / length_of_maxpath_from_node[considered_outnode->id]\n                <= tolerance;\n            const bool is_longer_path\n                = length_of_maxpath_from_node[considered_outnode->id]\n                > (uint)max_length;\n\n            if (is_terminus_and_most_likely or avg_log_likelihood_is_most_likely\n                or (avg_log_likelihood_is_close_to_most_likely and is_longer_path)) {\n                max_sum_of_log_probs_from_node[current_node->id]\n                    = get_prob(prob_model, current_node->id, sample_id)\n                    + max_sum_of_log_probs_from_node[considered_outnode->id];\n                length_of_maxpath_from_node[current_node->id]\n                    = 1 + length_of_maxpath_from_node[considered_outnode->id];\n                prev_node_along_maxpath[current_node->id] = considered_outnode->id;\n\n                if (length_of_maxpath_from_node[current_node->id]\n                    > max_num_kmers_to_average) {\n                    uint32_t prev_node = prev_node_along_maxpath[current_node->id];\n                    for (uint step = 0; step < max_num_kmers_to_average; step++) {\n                        prev_node = prev_node_along_maxpath[prev_node];\n                    }\n                    max_sum_of_log_probs_from_node[current_node->id]\n                        -= get_prob(prob_model, sorted_nodes[prev_node]->id, sample_id);\n                    length_of_maxpath_from_node[current_node->id] -= 1;\n\n                    // this remains as an assert, as it is a code check\n                    // Note: I think we might even be able to remove this\n                    assert(length_of_maxpath_from_node[current_node->id]\n                        == max_num_kmers_to_average);\n                }\n\n                if (considered_outnode->id != sorted_nodes.back()->id) {\n                    max_mean = max_sum_of_log_probs_from_node[considered_outnode->id]\n                        / length_of_maxpath_from_node[considered_outnode->id];\n                    max_length = length_of_maxpath_from_node[considered_outnode->id];\n                } else {\n                    max_mean = thresh;\n                }\n            }\n        }\n    }\n\n    // extract path\n    uint32_t prev_node = prev_node_along_maxpath[sorted_nodes[0]->id];\n    while (prev_node < sorted_nodes.size() - 1) {\n        maxpath.push_back(this->kmer_prg->nodes[prev_node]);\n        prev_node = prev_node_along_maxpath[prev_node];\n\n        if (maxpath.size() > 1000000) {\n            fatal_error(\"I think I've found an infinite loop - is \"\n                        \"something wrong with this kmergraph?\");\n        }\n    }\n\n    const bool path_was_found_through_the_kmer_PRG = length_of_maxpath_from_node[0] > 0;\n    if (!path_was_found_through_the_kmer_PRG) {\n        fatal_error(\"Error when finding max path: found no path through kmer prg\");\n    }\n\n    return prob_path(maxpath, sample_id, prob_model);\n}\n\nstd::vector<std::vector<KmerNodePtr>> KmerGraphWithCoverage::get_random_paths(\n    uint32_t num_paths)\n{\n    // find a random path through kmergraph picking ~uniformly from the outnodes at each\n    // point\n    std::vector<std::vector<KmerNodePtr>> rpaths;\n    std::vector<KmerNodePtr> rpath;\n    uint32_t i;\n\n    time_t now;\n    now = time(nullptr);\n    srand((unsigned int)now);\n\n    if (!kmer_prg->nodes.empty()) {\n        for (uint32_t j = 0; j != num_paths; ++j) {\n            i = rand() % kmer_prg->nodes[0]->out_nodes.size();\n            rpath.push_back(kmer_prg->nodes[0]->out_nodes[i].lock());\n            while (rpath.back() != kmer_prg->nodes[kmer_prg->nodes.size() - 1]) {\n                if (rpath.back()->out_nodes.size() == 1) {\n                    rpath.push_back(rpath.back()->out_nodes[0].lock());\n                } else {\n                    i = rand() % rpath.back()->out_nodes.size();\n                    rpath.push_back(rpath.back()->out_nodes[i].lock());\n                }\n            }\n            rpath.pop_back();\n            rpaths.push_back(rpath);\n            rpath.clear();\n        }\n    }\n    return rpaths;\n}\n\nfloat KmerGraphWithCoverage::prob_path(const std::vector<KmerNodePtr>& kpath,\n    const uint32_t& sample_id, const std::string& prob_model)\n{\n    float return_prob_path = 0;\n    for (uint32_t i = 0; i != kpath.size(); ++i) {\n        return_prob_path += get_prob(prob_model, kpath[i]->id, sample_id);\n    }\n    uint32_t len = kpath.size();\n    if (kpath[0]->path.length() == 0) {\n        len -= 1;\n    }\n    if (kpath.back()->path.length() == 0) {\n        len -= 1;\n    }\n    if (len == 0) {\n        len = 1;\n    }\n    return return_prob_path / len;\n}\n\nvoid KmerGraphWithCoverage::save_covg_dist(const std::string& filepath)\n{\n    std::ofstream handle;\n    handle.open(filepath);\n\n    for (const auto& kmer_node_ptr : kmer_prg->nodes) {\n        const KmerNode& kmer_node = *kmer_node_ptr;\n\n        uint32_t sample_id = 0;\n        for (const auto& sample_coverage :\n            node_index_to_sample_coverage[kmer_node.id]) {\n            handle << kmer_node.id << \" \" << sample_id << \" \" << sample_coverage.first\n                   << \" \" << sample_coverage.second;\n\n            sample_id++;\n        }\n    }\n    handle.close();\n}\n\n// save the KmerGraph as gfa\n// TODO: THIS SHOULD BE RECODED, WE ARE DUPLICATING CODE HERE (SEE KmerGraph::save())!!!\nvoid KmerGraphWithCoverage::save(\n    const fs::path& filepath, const std::shared_ptr<LocalPRG> localprg) const\n{\n    uint32_t sample_id = 0;\n\n    fs::ofstream handle(filepath);\n    if (handle.is_open()) {\n        handle << \"H\\tVN:Z:1.0\\tbn:Z:--linear --singlearr\" << std::endl;\n        for (const auto& c : kmer_prg->nodes) {\n            handle << \"S\\t\" << c->id << \"\\t\";\n\n            if (localprg != nullptr) {\n                handle << localprg->string_along_path(c->path);\n            } else {\n                handle << c->path;\n            }\n\n            handle << \"\\tFC:i:\" << this->get_forward_covg(c->id, sample_id)\n                   << \"\\tRC:i:\" << this->get_reverse_covg(c->id, sample_id)\n                   << std::endl;\n\n            for (uint32_t j = 0; j < c->out_nodes.size(); ++j) {\n                handle << \"L\\t\" << c->id << \"\\t+\\t\" << c->out_nodes[j].lock()->id\n                       << \"\\t+\\t0M\" << std::endl;\n            }\n        }\n        handle.close();\n    } else {\n        fatal_error(\"Unable to open kmergraph file \", filepath);\n    }\n}\n\n// TODO: THIS SHOULD BE RECODED, WE ARE DUPLICATING CODE HERE (SEE KmerGraph::load())!!!\n// TODO: remove this method?\nvoid KmerGraphWithCoverage::load(const std::string& filepath)\n{\n    // TODO: this might be dangerous, recode this?\n    auto kmer_prg = const_cast<KmerGraph*>(this->kmer_prg);\n    kmer_prg->clear();\n    uint32_t sample_id = 0;\n\n    std::string line;\n    std::vector<std::string> split_line;\n    std::stringstream ss;\n    uint32_t id = 0, from, to;\n    uint16_t covg;\n    prg::Path p;\n    uint32_t num_nodes = 0;\n\n    std::ifstream myfile(filepath);\n    if (myfile.is_open()) {\n\n        while (getline(myfile, line).good()) {\n            if (line[0] == 'S') {\n                split_line = split(line, \"\\t\");\n\n                const bool line_is_consistent = split_line.size() >= 4;\n                if (!line_is_consistent) {\n                    fatal_error(\"Error reading GFA. Offending line: \", line);\n                }\n\n                id = std::stoi(split_line[1]);\n                num_nodes = std::max(num_nodes, id);\n            }\n        }\n        myfile.clear();\n        myfile.seekg(0, myfile.beg);\n        kmer_prg->nodes.reserve(num_nodes);\n        std::vector<uint16_t> outnode_counts(num_nodes + 1, 0),\n            innode_counts(num_nodes + 1, 0);\n\n        while (getline(myfile, line).good()) {\n            if (line[0] == 'S') {\n                split_line = split(line, \"\\t\");\n\n                const bool line_is_consistent = split_line.size() >= 4;\n                if (!line_is_consistent) {\n                    fatal_error(\"Error reading GFA. Offending line: \", line);\n                }\n\n                id = stoi(split_line[1]);\n                ss << split_line[2];\n                char c = ss.peek();\n\n                if (!isdigit(c)) {\n                    fatal_error(\"Error reading GFA: cannot read in this sort of \"\n                                \"kmergraph GFA as it \",\n                        \"does not label nodes with their PRG path. \",\n                        \"Offending line: \", line);\n                }\n\n                ss >> p;\n                ss.clear();\n                // add_node(p);\n                KmerNodePtr n = std::make_shared<KmerNode>(id, p);\n\n                const bool id_is_consistent = (id == kmer_prg->nodes.size()\n                    or num_nodes - id == kmer_prg->nodes.size());\n                if (!id_is_consistent) {\n                    fatal_error(\"Error reading GFA: node ID is inconsistent.\",\n                        \"id = \", id, \", \", \"nodes.size() = \", kmer_prg->nodes.size(),\n                        \", \", \"num_nodes = \", num_nodes);\n                }\n\n                kmer_prg->nodes.push_back(n);\n                kmer_prg->sorted_nodes.insert(n);\n                if (kmer_prg->k == 0 and p.length() > 0) {\n                    kmer_prg->k = p.length();\n                }\n                covg = (uint16_t)(stoul(split(split_line[3], \"FC:i:\")[0]));\n                this->set_forward_covg(n->id, covg, sample_id);\n                covg = (uint16_t)(stoul(split(split_line[4], \"RC:i:\")[0]));\n                this->set_reverse_covg(n->id, covg, sample_id);\n                if (split_line.size() >= 6) {\n                    n->num_AT = std::stoi(split_line[5]);\n                }\n            } else if (line[0] == 'L') {\n                split_line = split(line, \"\\t\");\n\n                const bool line_is_consistent = split_line.size() >= 5;\n                if (!line_is_consistent) {\n                    fatal_error(\"Error reading GFA. Offending line: \", line);\n                }\n\n                const int from_node = stoi(split_line[1]);\n                const int to_node = stoi(split_line[3]);\n                const bool from_node_in_range = from_node < (int)outnode_counts.size();\n                const bool to_node_in_range = to_node < (int)innode_counts.size();\n                if (!from_node_in_range) {\n                    fatal_error(\n                        \"Error reading GFA: from_node out of range: \", from_node,\n                        \">=\", outnode_counts.size(), \". Offending line: \", line);\n                }\n                if (!to_node_in_range) {\n                    fatal_error(\"Error reading GFA: to_node out of range: \", to_node,\n                        \">=\", innode_counts.size(), \". Offending line: \", line);\n                }\n\n                outnode_counts[stoi(split_line[1])] += 1;\n                innode_counts[stoi(split_line[3])] += 1;\n            }\n        }\n\n        if (id == 0) {\n            reverse(kmer_prg->nodes.begin(), kmer_prg->nodes.end());\n        }\n\n        id = 0;\n        for (const auto& n : kmer_prg->nodes) {\n            const bool id_is_consistent = (kmer_prg->nodes[id]->id == id)\n                && (n->id < outnode_counts.size()) && (n->id < innode_counts.size());\n            if (!id_is_consistent) {\n                fatal_error(\"Error reading GFA: node: \", n,\n                    \" has inconsistent id, should be \", id);\n            }\n            id++;\n            n->out_nodes.reserve(outnode_counts[n->id]);\n            n->in_nodes.reserve(innode_counts[n->id]);\n        }\n\n        myfile.clear();\n        myfile.seekg(0, myfile.beg);\n\n        while (getline(myfile, line).good()) {\n            if (line[0] == 'L') {\n                split_line = split(line, \"\\t\");\n\n                const bool line_is_consistent = split_line.size() >= 5;\n                if (!line_is_consistent) {\n                    fatal_error(\"Error reading GFA. Offending line: \", line);\n                }\n\n                if (split_line[2] == split_line[4]) {\n                    from = std::stoi(split_line[1]);\n                    to = std::stoi(split_line[3]);\n                } else {\n                    // never happens\n                    from = std::stoi(split_line[3]);\n                    to = std::stoi(split_line[1]);\n                }\n                kmer_prg->add_edge(kmer_prg->nodes[from], kmer_prg->nodes[to]);\n            }\n        }\n    } else {\n        fatal_error(\"Error reading GFA: unable to open kmergraph file: \", filepath);\n    }\n}", "meta": {"hexsha": "b09e0568cf51d6928bf227af6eb81ba7f78d0f93", "size": 22761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kmergraphwithcoverage.cpp", "max_stars_repo_name": "rmcolq/pandora", "max_stars_repo_head_hexsha": "93c541017a5c1ea45f999f5eabdb58be061711e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2018-07-06T00:13:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-19T03:58:20.000Z", "max_issues_repo_path": "src/kmergraphwithcoverage.cpp", "max_issues_repo_name": "rmcolq/pandora", "max_issues_repo_head_hexsha": "93c541017a5c1ea45f999f5eabdb58be061711e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 215.0, "max_issues_repo_issues_event_min_datetime": "2018-07-09T16:41:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T22:44:36.000Z", "max_forks_repo_path": "src/kmergraphwithcoverage.cpp", "max_forks_repo_name": "mbhall88/pandora", "max_forks_repo_head_hexsha": "16de553795267a55af223748b24510a904ca5ef9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-07-06T13:09:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T15:01:09.000Z", "avg_line_length": 38.5126903553, "max_line_length": 88, "alphanum_fraction": 0.5884627213, "num_tokens": 5617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24432941467075914}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// tail_variate_means.hpp\r\n//\r\n//  Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost\r\n//  Software License, Version 1.0. (See accompanying file\r\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_ACCUMULATORS_STATISTICS_TAIL_VARIATE_MEANS_HPP_DE_01_01_2006\r\n#define BOOST_ACCUMULATORS_STATISTICS_TAIL_VARIATE_MEANS_HPP_DE_01_01_2006\r\n\r\n#include <numeric>\r\n#include <vector>\r\n#include <limits>\r\n#include <functional>\r\n#include <sstream>\r\n#include <stdexcept>\r\n#include <boost/throw_exception.hpp>\r\n#include <boost/parameter/keyword.hpp>\r\n#include <boost/mpl/placeholders.hpp>\r\n#include <boost/type_traits/is_same.hpp>\r\n#include <boost/accumulators/framework/accumulator_base.hpp>\r\n#include <boost/accumulators/framework/extractor.hpp>\r\n#include <boost/accumulators/numeric/functional.hpp>\r\n#include <boost/accumulators/framework/parameters/sample.hpp>\r\n#include <boost/accumulators/statistics_fwd.hpp>\r\n#include <boost/accumulators/statistics/tail.hpp>\r\n#include <boost/accumulators/statistics/tail_variate.hpp>\r\n#include <boost/accumulators/statistics/tail_mean.hpp>\r\n#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>\r\n#include <boost/serialization/vector.hpp>\r\n\r\n#ifdef _MSC_VER\r\n# pragma warning(push)\r\n# pragma warning(disable: 4127) // conditional expression is constant\r\n#endif\r\n\r\nnamespace boost { namespace accumulators\r\n{\r\n\r\nnamespace impl\r\n{\r\n    /**\r\n        @brief Estimation of the absolute and relative tail variate means (for both left and right tails)\r\n\r\n        For all \\f$j\\f$-th variates associated to the \\f$\\lceil n(1-\\alpha)\\rceil\\f$ largest samples (or the\r\n        \\f$\\lceil n(1-\\alpha)\\rceil\\f$ smallest samples in case of the left tail), the absolute tail means\r\n        \\f$\\widehat{ATM}_{n,\\alpha}(X, j)\\f$ are computed and returned as an iterator range. Alternatively,\r\n        the relative tail means \\f$\\widehat{RTM}_{n,\\alpha}(X, j)\\f$ are returned, which are the absolute\r\n        tail means normalized with the (non-coherent) sample tail mean \\f$\\widehat{NCTM}_{n,\\alpha}(X)\\f$.\r\n\r\n        \\f[\r\n            \\widehat{ATM}_{n,\\alpha}^{\\mathrm{right}}(X, j) =\r\n                \\frac{1}{\\lceil n(1-\\alpha) \\rceil}\r\n                \\sum_{i=\\lceil \\alpha n \\rceil}^n \\xi_{j,i}\r\n        \\f]\r\n\r\n        \\f[\r\n            \\widehat{ATM}_{n,\\alpha}^{\\mathrm{left}}(X, j) =\r\n                \\frac{1}{\\lceil n\\alpha \\rceil}\r\n                \\sum_{i=1}^{\\lceil n\\alpha \\rceil} \\xi_{j,i}\r\n        \\f]\r\n\r\n        \\f[\r\n            \\widehat{RTM}_{n,\\alpha}^{\\mathrm{right}}(X, j) =\r\n                \\frac{\\sum_{i=\\lceil n\\alpha \\rceil}^n \\xi_{j,i}}\r\n            {\\lceil n(1-\\alpha)\\rceil\\widehat{NCTM}_{n,\\alpha}^{\\mathrm{right}}(X)}\r\n        \\f]\r\n\r\n        \\f[\r\n            \\widehat{RTM}_{n,\\alpha}^{\\mathrm{left}}(X, j) =\r\n                \\frac{\\sum_{i=1}^{\\lceil n\\alpha \\rceil} \\xi_{j,i}}\r\n            {\\lceil n\\alpha\\rceil\\widehat{NCTM}_{n,\\alpha}^{\\mathrm{left}}(X)}\r\n        \\f]\r\n    */\r\n\r\n    ///////////////////////////////////////////////////////////////////////////////\r\n    // tail_variate_means_impl\r\n    //  by default: absolute tail_variate_means\r\n    template<typename Sample, typename Impl, typename LeftRight, typename VariateTag>\r\n    struct tail_variate_means_impl\r\n      : accumulator_base\r\n    {\r\n        typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;\r\n        typedef std::vector<float_type> array_type;\r\n        // for boost::result_of\r\n        typedef iterator_range<typename array_type::iterator> result_type;\r\n\r\n        tail_variate_means_impl(dont_care) {}\r\n\r\n        template<typename Args>\r\n        result_type result(Args const &args) const\r\n        {\r\n            std::size_t cnt = count(args);\r\n\r\n            std::size_t n = static_cast<std::size_t>(\r\n                std::ceil(\r\n                    cnt * ( ( is_same<LeftRight, left>::value ) ? args[quantile_probability] : 1. - args[quantile_probability] )\r\n                )\r\n            );\r\n\r\n            std::size_t num_variates = tail_variate(args).begin()->size();\r\n\r\n            this->tail_means_.clear();\r\n            this->tail_means_.resize(num_variates, Sample(0));\r\n\r\n            // If n is in a valid range, return result, otherwise return NaN or throw exception\r\n            if (n < static_cast<std::size_t>(tail(args).size()))\r\n            {\r\n                this->tail_means_ = std::accumulate(\r\n                    tail_variate(args).begin()\r\n                  , tail_variate(args).begin() + n\r\n                  , this->tail_means_\r\n                  , numeric::plus\r\n                );\r\n\r\n                float_type factor = n * ( (is_same<Impl, relative>::value) ? non_coherent_tail_mean(args) : 1. );\r\n\r\n                std::transform(\r\n                    this->tail_means_.begin()\r\n                  , this->tail_means_.end()\r\n                  , this->tail_means_.begin()\r\n#ifdef BOOST_NO_CXX98_BINDERS\r\n                  , std::bind(std::divides<float_type>(), std::placeholders::_1, factor)\r\n#else\r\n                  , std::bind2nd(std::divides<float_type>(), factor)\r\n#endif\r\n                );\r\n            }\r\n            else\r\n            {\r\n                if (std::numeric_limits<float_type>::has_quiet_NaN)\r\n                {\r\n                    std::fill(\r\n                        this->tail_means_.begin()\r\n                      , this->tail_means_.end()\r\n                      , std::numeric_limits<float_type>::quiet_NaN()\r\n                    );\r\n                }\r\n                else\r\n                {\r\n                    std::ostringstream msg;\r\n                    msg << \"index n = \" << n << \" is not in valid range [0, \" << tail(args).size() << \")\";\r\n                    boost::throw_exception(std::runtime_error(msg.str()));\r\n                }\r\n            }\r\n            return make_iterator_range(this->tail_means_);\r\n        }\r\n\r\n        // make this accumulator serializeable\r\n        template<class Archive>\r\n        void serialize(Archive & ar, const unsigned int file_version)\r\n        { \r\n            ar & tail_means_;\r\n        }\r\n\r\n    private:\r\n\r\n        mutable array_type tail_means_;\r\n\r\n    };\r\n\r\n} // namespace impl\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// tag::absolute_tail_variate_means\r\n// tag::relative_tail_variate_means\r\n//\r\nnamespace tag\r\n{\r\n    template<typename LeftRight, typename VariateType, typename VariateTag>\r\n    struct absolute_tail_variate_means\r\n      : depends_on<count, non_coherent_tail_mean<LeftRight>, tail_variate<VariateType, VariateTag, LeftRight> >\r\n    {\r\n        typedef accumulators::impl::tail_variate_means_impl<mpl::_1, absolute, LeftRight, VariateTag> impl;\r\n    };\r\n    template<typename LeftRight, typename VariateType, typename VariateTag>\r\n    struct relative_tail_variate_means\r\n      : depends_on<count, non_coherent_tail_mean<LeftRight>, tail_variate<VariateType, VariateTag, LeftRight> >\r\n    {\r\n        typedef accumulators::impl::tail_variate_means_impl<mpl::_1, relative, LeftRight, VariateTag> impl;\r\n    };\r\n    struct abstract_absolute_tail_variate_means\r\n      : depends_on<>\r\n    {\r\n    };\r\n    struct abstract_relative_tail_variate_means\r\n      : depends_on<>\r\n    {\r\n    };\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n// extract::tail_variate_means\r\n// extract::relative_tail_variate_means\r\n//\r\nnamespace extract\r\n{\r\n    extractor<tag::abstract_absolute_tail_variate_means> const tail_variate_means = {};\r\n    extractor<tag::abstract_relative_tail_variate_means> const relative_tail_variate_means = {};\r\n\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(tail_variate_means)\r\n    BOOST_ACCUMULATORS_IGNORE_GLOBAL(relative_tail_variate_means)\r\n}\r\n\r\nusing extract::tail_variate_means;\r\nusing extract::relative_tail_variate_means;\r\n\r\n// tail_variate_means<LeftRight, VariateType, VariateTag>(absolute) -> absolute_tail_variate_means<LeftRight, VariateType, VariateTag>\r\ntemplate<typename LeftRight, typename VariateType, typename VariateTag>\r\nstruct as_feature<tag::tail_variate_means<LeftRight, VariateType, VariateTag>(absolute)>\r\n{\r\n    typedef tag::absolute_tail_variate_means<LeftRight, VariateType, VariateTag> type;\r\n};\r\n\r\n// tail_variate_means<LeftRight, VariateType, VariateTag>(relative) ->relative_tail_variate_means<LeftRight, VariateType, VariateTag>\r\ntemplate<typename LeftRight, typename VariateType, typename VariateTag>\r\nstruct as_feature<tag::tail_variate_means<LeftRight, VariateType, VariateTag>(relative)>\r\n{\r\n    typedef tag::relative_tail_variate_means<LeftRight, VariateType, VariateTag> type;\r\n};\r\n\r\n// Provides non-templatized extractor\r\ntemplate<typename LeftRight, typename VariateType, typename VariateTag>\r\nstruct feature_of<tag::absolute_tail_variate_means<LeftRight, VariateType, VariateTag> >\r\n  : feature_of<tag::abstract_absolute_tail_variate_means>\r\n{\r\n};\r\n\r\n// Provides non-templatized extractor\r\ntemplate<typename LeftRight, typename VariateType, typename VariateTag>\r\nstruct feature_of<tag::relative_tail_variate_means<LeftRight, VariateType, VariateTag> >\r\n  : feature_of<tag::abstract_relative_tail_variate_means>\r\n{\r\n};\r\n\r\n// So that absolute_tail_means can be automatically substituted\r\n// with absolute_weighted_tail_means when the weight parameter is non-void.\r\ntemplate<typename LeftRight, typename VariateType, typename VariateTag>\r\nstruct as_weighted_feature<tag::absolute_tail_variate_means<LeftRight, VariateType, VariateTag> >\r\n{\r\n    typedef tag::absolute_weighted_tail_variate_means<LeftRight, VariateType, VariateTag> type;\r\n};\r\n\r\ntemplate<typename LeftRight, typename VariateType, typename VariateTag>\r\nstruct feature_of<tag::absolute_weighted_tail_variate_means<LeftRight, VariateType, VariateTag> >\r\n  : feature_of<tag::absolute_tail_variate_means<LeftRight, VariateType, VariateTag> >\r\n{\r\n};\r\n\r\n// So that relative_tail_means can be automatically substituted\r\n// with relative_weighted_tail_means when the weight parameter is non-void.\r\ntemplate<typename LeftRight, typename VariateType, typename VariateTag>\r\nstruct as_weighted_feature<tag::relative_tail_variate_means<LeftRight, VariateType, VariateTag> >\r\n{\r\n    typedef tag::relative_weighted_tail_variate_means<LeftRight, VariateType, VariateTag> type;\r\n};\r\n\r\ntemplate<typename LeftRight, typename VariateType, typename VariateTag>\r\nstruct feature_of<tag::relative_weighted_tail_variate_means<LeftRight, VariateType, VariateTag> >\r\n  : feature_of<tag::relative_tail_variate_means<LeftRight, VariateType, VariateTag> >\r\n{\r\n};\r\n\r\n}} // namespace boost::accumulators\r\n\r\n#ifdef _MSC_VER\r\n# pragma warning(pop)\r\n#endif\r\n\r\n#endif\r\n", "meta": {"hexsha": "d525df2ce1f34ef52a8bc4f25153d9ad2dba62f5", "size": 10733, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/accumulators/statistics/tail_variate_means.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/accumulators/statistics/tail_variate_means.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/accumulators/statistics/tail_variate_means.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 39.6051660517, "max_line_length": 135, "alphanum_fraction": 0.643342961, "num_tokens": 2508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2443005306581844}}
{"text": "/*******************************************************************************\n\n  Copyright (c) 2017, Honda Research Institute Europe GmbH\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions are\n  met:\n\n  1. Redistributions of source code must retain the above copyright notice,\n   this list of conditions and the following disclaimer.\n\n  2. Redistributions in binary form must reproduce the above copyright\n   notice, this list of conditions and the following disclaimer in the\n   documentation and/or other materials provided with the distribution.\n\n  3. Neither the name of the copyright holder nor the names of its\n   contributors may be used to endorse or promote products derived from\n   this software without specific prior written permission.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n  CONTRIBUTORS 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\n  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*******************************************************************************/\n\n/******************************************************************************\n\n  http://eigen.tuxfamily.org/dox/TopicPreprocessorDirectives.html:\n\n  EIGEN_NO_MALLOC - if defined, any request from inside the Eigen to allocate\n                    memory from the heap results in an assertion failure. This\n                    is useful to check that some routine does not allocate\n                    memory dynamically. Not defined by default.\n\n  EIGEN_RUNTIME_NO_MALLOC - if defined, a new switch is introduced which can be\n                            turned on and off by calling set_is_malloc_allowed\n                            (bool). If malloc is not allowed and Eigen tries to\n                            allocate memory dynamically anyway, an assertion\n                            failure results. Not defined by default.\n\n  Mapping C-Arrays:\n   http://eigen.tuxfamily.org/dox/group__TutorialMapClass.html#\n          TutorialMapPlacementNew\n\n  Malloc checking:\n   Eigen::internal::set_is_malloc_allowed(true, false) will create a fatal\n   error if set to true, and disable checking for false. However, this is\n   not thread-safe, and therefore should only be used for testing.\n\n******************************************************************************/\n\n#include <Rcs_eigen.h>\n#include <Rcs_macros.h>\n\n#define EIGEN_RUNTIME_NO_MALLOC\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n\n#include <Eigen/QR>\n#include <Eigen/SVD>\n#include <Eigen/Cholesky>\n#include <Eigen/LU>\n\n#include <iostream>\n#include <cstdio>\n\nusing namespace Eigen;\n\n#if defined (MATND_MAX_STACK_VECTOR_SIZE)\n#undef MATND_MAX_STACK_VECTOR_SIZE\n#endif\n\n#if defined (MATND_MAX_STACK_MATRIX_SIZE)\n#undef MATND_MAX_STACK_MATRIX_SIZE\n#endif\n\n#define MATND_MAX_STACK_VECTOR_SIZE (25)\n#define MATND_MAX_STACK_MATRIX_SIZE (25*25)\n\n\n// These types have an unknown size at compile time, and therefore are\n// allocated on the heap. The storage order of the matrices is set to row\n// major, so that the Eigen's Map class can be used to cast them over a MatNd\n// type without any additional memory allocation.\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor> HeapMat;\ntypedef Matrix<double, Dynamic, 1, ColMajor> HeapVec;\n\n\n\n// These types have a known size at compile time, and therefore are allocated\n// on the stack. The storage order of the matrices is set to row major, so that\n// the Eigen's Map class can be used to cast them over a MatNd type without any\n// additional memory allocation.\ntypedef Matrix<double, Dynamic, Dynamic, RowMajor,\n        MATND_MAX_STACK_VECTOR_SIZE,\n        MATND_MAX_STACK_VECTOR_SIZE> StackMat;\ntypedef Matrix<double, Dynamic, 1, ColMajor,\n        MATND_MAX_STACK_VECTOR_SIZE, 1> StackVec;\n\n\n\ntemplate <typename T>\nstatic inline void MatNd_fromEigen3(MatNd* dst, const T& src,\n                                    bool reshape=false)\n{\n  if (reshape==false)\n  {\n    RCHECK_EQ((int)dst->m, src.rows());\n    RCHECK_EQ((int)dst->n, src.cols());\n  }\n  else\n  {\n    MatNd_reshape(dst, src.rows(), src.cols());\n  }\n\n  for (size_t m=0; m<dst->m; m++)\n  {\n    for (size_t n=0; n<dst->n; n++)\n    {\n      MatNd_set2(dst, m, n, src(m,n));\n    }\n  }\n}\n\ntemplate <typename T>\nstatic inline double CholDet(const T& L)\n{\n  double det = 1.0;\n\n  for (int i=0; i<L.rows(); i++)\n  {\n    det *= L(i, i)*L(i, i);\n  }\n\n  return det;\n}\n\ntemplate <typename MatT>\nstatic inline double CholDC(MatNd* L_, const MatNd* A_)\n{\n  Map<MatT> A(A_->ele, A_->m, A_->n);\n  LLT<MatT> llt;\n  llt.compute(A);\n\n  if (llt.info() != Eigen::Success)\n  {\n    RLOG(1, \"Error on LLT!\");\n    MatNd_setZero(L_);\n    return 0.0;\n  }\n\n  MatT L(llt.matrixL());\n  double det = CholDet<MatT>(L);\n  MatNd_fromEigen3<MatT>(L_, L);\n\n  return det;\n}\n\ntemplate <typename MatT>\nstatic inline double CholSolve(MatNd* x_, const MatNd* A_, const MatNd* b_)\n{\n  Map<const MatT> A(A_->ele, A_->m, A_->n);\n  LLT<MatT> llt;\n  llt.compute(A);\n\n  if (llt.info() != Eigen::Success)\n  {\n    RLOG(1, \"Error on LLT!\");\n    return 0.0;\n  }\n\n  Map<MatT> x(x_->ele, x_->m, x_->n);\n  Map<const MatT> b(b_->ele, b_->m, b_->n);\n  x = llt.solve(b);\n\n  // Compute determinant\n  MatT L(llt.matrixL());\n\n  return CholDet<MatT>(L);\n}\n\ntemplate <typename MatT>\nstatic inline double CholInv(MatNd* A_inv_, const MatNd* A_)\n{\n  size_t n = A_->m;\n  Map<const MatT> A(A_->ele, n, n);\n\n  LLT<MatT> llt;\n  llt.compute(A);\n\n  if (llt.info() != Eigen::Success)\n  {\n    RLOG(1, \"Error on LLT!\");\n    MatNd_setZero(A_inv_);\n    return 0.0;\n  }\n\n  Map<MatT> invA(A_inv_->ele, n, n);\n  invA = llt.solve(MatT::Identity(n,n));\n\n  MatT L(llt.matrixL());\n\n  return CholDet<MatT>(L);\n}\n\ntemplate <typename MatT>\nstatic inline int SvdDC(MatNd* U, MatNd* S, MatNd* V, const MatNd* J,\n                        double eps)\n{\n  Map<MatT> mapJ(J->ele, J->m, J->n);\n\n  // We need to compute the full SVD, since otherwise there will dynamic\n  // memory allocation for the StackMat types due to the QR preconditioning\n  // (on Linux)\n  JacobiSVD<MatT> svd(mapJ, ComputeFullU | ComputeFullV);\n\n  // Cut off singular values smaller than eps\n  int rank = svd.nonzeroSingularValues();\n\n  for (int i=0; i<svd.nonzeroSingularValues(); ++i)\n  {\n    if (svd.singularValues()(i) < eps)\n    {\n      rank = i;\n      break;\n    }\n  }\n\n  if (S != NULL)\n  {\n    MatNd_fromEigen3<MatT>(S, svd.singularValues(), true);\n    S->m = rank;\n  }\n\n  if (U != NULL)\n  {\n    MatT svdU = svd.matrixU();\n    MatNd_reshape(U, svdU.rows(), rank);\n\n    for (unsigned int m=0; m<U->m; m++)\n    {\n      for (unsigned int n=0; n<U->n; n++)\n      {\n        MatNd_set2(U, m, n, svdU(m,n));\n      }\n    }\n  }\n\n  if (V != NULL)\n  {\n    MatT svdV = svd.matrixV();\n    MatNd_reshape(V, svdV.rows(), rank);\n\n    for (unsigned int m=0; m<V->m; m++)\n    {\n      for (unsigned int n=0; n<V->n; n++)\n      {\n        MatNd_set2(V, m, n, svdV(m,n));\n      }\n    }\n  }\n\n  return rank;\n}\n\ntemplate <typename MatT>\nstatic inline double SvdSolve(MatNd* x_, const MatNd* A_, const MatNd* b_)\n{\n  Map<MatT> x(x_->ele, x_->m, x_->n);\n  Map<MatT> A(A_->ele, A_->m, A_->n);\n  Map<MatT> b(b_->ele, b_->m, b_->n);\n\n  // We need to compute the full SVD, since otherwise there will dynamic\n  // memory allocation for the StackMat types due to the QR preconditioning\n  // (on Linux)\n  JacobiSVD<MatT> svd(A, ComputeFullU | ComputeFullV);\n  x = svd.solve(b);\n\n  // Compute determinant\n  double det = 1.0;\n  MatT S = svd.singularValues();\n\n  // Cut off singular values smaller than eps\n  for (int i=0; i<S.rows(); ++i)\n  {\n    det *= S(i);\n  }\n\n  return det;\n}\n\ntemplate <typename MatT>\nstatic inline size_t SvdInverse(MatNd* A_, double eps=1.0e-12)\n{\n  Map<MatT> A(A_->ele, A_->m, A_->n);\n\n  // We need to compute the full SVD, since otherwise there will dynamic\n  // memory allocation for the StackMat types due to the QR preconditioning\n  // (on Linux)\n  JacobiSVD<MatT> svd;\n  //  svd.setThreshold(eps);\n  svd.compute(A, ComputeThinU | ComputeThinV);\n\n  MatT invS = svd.singularValues();\n\n  // Cut off singular values smaller than eps\n  size_t rank = 0;\n  for (int i=0; i<invS.rows(); ++i)\n  {\n    if (invS(i) > eps)\n    {\n      invS(i) = 1.0/invS(i);\n      rank++;\n    }\n  }\n\n  // inv = V diag(S^-1) U^T\n  A.noalias() = svd.matrixV()*invS.asDiagonal()*svd.matrixU().transpose();\n\n  return rank;\n}\n\ntemplate <typename MatT>\nstatic inline void QRDC(MatNd* Q_, MatNd* R_, const MatNd* A_)\n{\n  Map<const MatT> A(A_->ele, A_->m, A_->n);\n  Map<MatT> Q(Q_->ele, Q_->m, Q_->n);\n  Map<MatT> R(R_->ele, R_->m, R_->n);\n\n  HouseholderQR<MatT> qr(A);\n\n  Q = qr.householderQ();\n  R = qr.matrixQR().template triangularView<Eigen::Upper>();\n}\n\ntemplate <typename MatT>\nstatic inline bool EigenVectors(MatNd* V_, double* d_, const MatNd* A_)\n{\n  Map<const MatT> A(A_->ele, A_->m, A_->n);\n\n  Eigen::SelfAdjointEigenSolver<MatT> eigensolver(A);\n\n  if (eigensolver.info() != Eigen::Success)\n  {\n    return false;\n  }\n\n  Map<MatT> V(V_->ele, V_->m, V_->n);\n  Map<MatT> d(d_, A_->m, 1);\n  V = eigensolver.eigenvectors();\n  d = eigensolver.eigenvalues();\n\n  return true;\n}\n\ntemplate <typename MatT>\nstatic inline void ColPivHhQR(MatNd* X_, const MatNd* A_, const MatNd* B_)\n{\n  Map<const MatT> A(A_->ele, A_->m, A_->n);\n  Map<const MatT> B(B_->ele, B_->m, B_->n);\n  Map<MatT> X(X_->ele, X_->m, X_->n);\n\n  // A X = B\n  X = A.colPivHouseholderQr().solve(B);\n}\n\n\n\n\n\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\ndouble MatNd_choleskyDecomposition_E3(MatNd* L, const MatNd* A)\n{\n  RCHECK_EQ(A->m, A->n);\n  RCHECK_EQ(L->m, L->n);\n  RCHECK_EQ(A->m, L->m);\n\n  if (A->m > MATND_MAX_STACK_VECTOR_SIZE)\n  {\n    return CholDC<HeapMat>(L, A);\n  }\n  else\n  {\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(false);\n#endif\n    double det = CholDC<StackMat>(L, A);\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(true);\n#endif\n    return det;\n  }\n}\n\ndouble MatNd_choleskySolve_E3(MatNd* x, const MatNd* A, const MatNd* b)\n{\n  RCHECK_EQ(A->m, A->n);\n  RCHECK_EQ(x->m, A->m);\n  RCHECK_EQ(b->m, x->m);\n  RCHECK_EQ(b->n, x->n);\n\n  if (A->m > MATND_MAX_STACK_VECTOR_SIZE)\n  {\n    return CholSolve<HeapMat>(x, A, b);\n  }\n  else\n  {\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(false);\n#endif\n    double det = CholSolve<StackMat>(x, A, b);\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(true);\n#endif\n    return det;\n  }\n}\n\ndouble MatNd_choleskyInverse_E3(MatNd* invA, const MatNd* A)\n{\n  RCHECK_EQ(A->m, A->n);\n  RCHECK_EQ(invA->m, invA->n);\n  RCHECK_EQ(A->m, invA->m);\n\n  if (A->m > MATND_MAX_STACK_VECTOR_SIZE)\n  {\n    return CholInv<HeapMat>(invA,A);\n  }\n  else\n  {\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(false);\n#endif\n    double det = CholInv<StackMat>(invA,A);\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(true);\n#endif\n    return det;\n  }\n}\n\nvoid MatNd_mul_E3(MatNd* C_, const MatNd* A_, const MatNd* B_)\n{\n  if ((A_->m > MATND_MAX_STACK_VECTOR_SIZE) ||\n      (B_->n > MATND_MAX_STACK_VECTOR_SIZE))\n  {\n    Map<HeapMat> C(C_->ele, C_->m, C_->n);\n    Map<HeapMat> A(A_->ele, A_->m, A_->n);\n    Map<HeapMat> B(B_->ele, B_->m, B_->n);\n\n    // The noalias function inhibits the creation of a temporary object which\n    // would lead to dynamic memory alllocation.\n    C.noalias() = A*B;\n  }\n  else\n  {\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(false);\n#endif\n\n    Map<StackMat> C(C_->ele, C_->m, C_->n);\n    Map<StackMat> A(A_->ele, A_->m, A_->n);\n    Map<StackMat> B(B_->ele, B_->m, B_->n);\n\n    C.noalias() = A*B;\n\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(true);\n#endif\n  }\n}\n\n\n\n\n\n\n\nunsigned int MatNd_SVD(MatNd* U, MatNd* S, MatNd* V, const MatNd* J,\n                       double eps)\n{\n  if ((J->m > MATND_MAX_STACK_VECTOR_SIZE) ||\n      (J->n > MATND_MAX_STACK_VECTOR_SIZE))\n  {\n    return SvdDC<HeapMat>(U, S, V, J, eps);\n  }\n  else\n  {\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(false);\n#endif\n    int rank = SvdDC<StackMat>(U, S, V, J, eps);\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(true);\n#endif\n    return rank;\n  }\n}\n\ndouble MatNd_SVDSolve(MatNd* x, const MatNd* A, const MatNd* b)\n{\n  if ((A->m > MATND_MAX_STACK_VECTOR_SIZE) ||\n      (A->n > MATND_MAX_STACK_VECTOR_SIZE))\n  {\n    return SvdSolve<HeapMat>(x, A, b);\n  }\n  else\n  {\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(false);\n#endif\n    double det = SvdSolve<StackMat>(x, A, b);\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(true);\n#endif\n    return det;\n  }\n}\n\nunsigned int MatNd_SVDInverse(MatNd* inv, const MatNd* src)\n{\n  MatNd_copy(inv, src);\n  return MatNd_SVDInverseSelf(inv);\n}\n\nunsigned int MatNd_SVDInverseSelf(MatNd* A)\n{\n  if ((A->m > MATND_MAX_STACK_VECTOR_SIZE) ||\n      (A->n > MATND_MAX_STACK_VECTOR_SIZE))\n  {\n    return SvdInverse<HeapMat>(A);\n  }\n  else\n  {\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(false);\n#endif\n    int rank = SvdInverse<StackMat>(A);\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(true);\n#endif\n    return rank;\n  }\n}\n\nunsigned int MatNd_rank(const MatNd* J, double eps)\n{\n  return MatNd_SVD(NULL, NULL, NULL, J, eps);\n}\n\nvoid MatNd_QRDecomposition(MatNd* Q, MatNd* R, const MatNd* A)\n{\n  if ((A->m > MATND_MAX_STACK_VECTOR_SIZE) ||\n      (A->n > MATND_MAX_STACK_VECTOR_SIZE) ||\n      (A->n > A->m))   // That's a bug in Eigen3\n  {\n    QRDC<HeapMat>(Q, R, A);\n  }\n  else\n  {\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(false);\n#endif\n    QRDC<StackMat>(Q, R, A);\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(true);\n#endif\n  }\n}\n\nbool MatNd_getEigenVectors(MatNd* V, double* d, const MatNd* A)\n{\n  RCHECK_EQ(A->m, A->n);\n  RCHECK_EQ(A->n, V->m);\n  RCHECK_EQ(V->m, V->n);\n\n  bool success;\n\n  if (A->m > MATND_MAX_STACK_VECTOR_SIZE)\n  {\n    success = EigenVectors<HeapMat>(V, d, A);\n  }\n  else\n  {\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(false);\n#endif\n    success = EigenVectors<StackMat>(V, d, A);\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(true);\n#endif\n  }\n\n  return success;\n}\n\nvoid MatNd_HouseholderQR(MatNd* X, const MatNd* A, const MatNd* B)\n{\n  if ((A->m > MATND_MAX_STACK_VECTOR_SIZE) ||\n      (A->n > MATND_MAX_STACK_VECTOR_SIZE))\n  {\n    return ColPivHhQR<HeapMat>(X, A, B);\n  }\n  else\n  {\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(false);\n#endif\n    return ColPivHhQR<StackMat>(X, A, B);\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n    Eigen::internal::set_is_malloc_allowed(true);\n#endif\n  }\n}\n\n\n\n\n#ifdef __cplusplus\n}\n#endif\n", "meta": {"hexsha": "929c99a2491c0b522d044a358cac1cd10b1fc362", "size": 15402, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RcsCore/Rcs_eigen.cpp", "max_stars_repo_name": "famura/Rcs", "max_stars_repo_head_hexsha": "4f8b997d2649a2cd7a1945ea079e07a71ee215fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-03-20T12:28:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T08:39:32.000Z", "max_issues_repo_path": "src/RcsCore/Rcs_eigen.cpp", "max_issues_repo_name": "famura/Rcs", "max_issues_repo_head_hexsha": "4f8b997d2649a2cd7a1945ea079e07a71ee215fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-04-19T08:49:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-11T09:47:09.000Z", "max_forks_repo_path": "src/RcsCore/Rcs_eigen.cpp", "max_forks_repo_name": "famura/Rcs", "max_forks_repo_head_hexsha": "4f8b997d2649a2cd7a1945ea079e07a71ee215fc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2018-03-28T11:52:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T19:34:01.000Z", "avg_line_length": 24.1789638932, "max_line_length": 80, "alphanum_fraction": 0.6495909622, "num_tokens": 4580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.24430053065818438}}
{"text": "/*\n * Copyright 2008-2016 Jan Gasthaus\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"libplump/hpyp_model.h\"\n\n#include <cmath>\n#include <boost/bind.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include \"libplump/utils.h\"\n#include \"libplump/subseq.h\"\n#include \"libplump/stirling.h\"\n#include \"libplump/random.h\"\n#include \"libplump/hpyp_restaurants.h\"\n\n\nnamespace gatsby { namespace libplump {\n\nHPYPModel::HPYPModel(seq_type& seq,\n                     INodeManager& nodeManager,\n                     const IAddRemoveRestaurant& restaurant,\n                     IParameters& parameters,\n                     int numTypes) \n    : seq(seq), \n      contextTree_(new ContextTree(nodeManager, seq)), \n      contextTree(*contextTree_), \n      restaurant(restaurant),\n      parameters(parameters), \n      numTypes(numTypes) {\n    baseProb = 1./((double) numTypes);\n  }\n \n\nvoid HPYPModel::insertRoot(e_type obs) {\n  WrappedNodeList root_path = this->contextTree.findLongestSuffix(0,0);\n  d_vec discount_path = this->parameters.getDiscounts(root_path);\n  d_vec concentration_path = this->parameters.getConcentrations(root_path,\n                                                                discount_path);\n  d_vec prob_path = this->computeProbabilityPath(root_path,\n                                                 discount_path,\n                                                 concentration_path,\n                                                 obs);\n  this->updatePath(root_path,\n                   prob_path,\n                   discount_path,\n                   concentration_path,\n                   obs);\n}\n\n\n/**\n * Insert a context into the tree and handle a potentially occuring \n * split.\n */\nWrappedNodeList HPYPModel::insertContext(l_type start, l_type stop) {\n  typedef ContextTree::InsertionResult InsertionResult;\n\n  // insert context\n  InsertionResult insertionResult = contextTree.insert(start, stop);\n\n  // handle split if one occurred\n  if (insertionResult.action != InsertionResult::INSERT_ACTION_NO_SPLIT) { \n    WrappedNode nodeA, nodeC;\n    WrappedNodeList::iterator i = insertionResult.path.end();\n\n    // move iterator to point to the split node which is either the \n    // last or second to last element on the path, depending on \n    // whether the inserted node was a suffix\n    switch (insertionResult.action) {\n      case InsertionResult::INSERT_ACTION_SPLIT :\n        // split where inserted node is not a suffix of a node in \n        // the tree\n        i--; i--; // split node is above the newly inserted node\n        break;\n      case InsertionResult::INSERT_ACTION_SPLIT_SUFFIX :\n        // split where inserted node is a suffix -> inserted node\n        // is the shorter node\n        i--; // split node is the newly inserted node\n        break;\n      case InsertionResult::INSERT_ACTION_NO_SPLIT :\n        break;\n    }\n    nodeC = *i;\n    i--; // move iterator to parent\n    nodeA = *i;\n    this->handleSplit(nodeA, \n                      insertionResult.splitChild,\n                      nodeC); \n  }\n  return insertionResult.path;    \n}\n\n\nd_vec HPYPModel::insertContextAndObservation(l_type start, \n                                             l_type stop,\n                                             e_type obs) {\n  // insert context (and handle a potential split)\n  WrappedNodeList path = insertContext(start, stop);\n\n  // insert observation\n  d_vec discountPath = this->parameters.getDiscounts(path);\n  d_vec concentrationPath = this->parameters.getConcentrations(path,\n                                                               discountPath);\n  d_vec probabilityPath = this->computeProbabilityPath(path,\n                                                       discountPath,\n                                                       concentrationPath,\n                                                       obs);\n  this->parameters.accumulateParameterGradient(this->restaurant, \n      path, probabilityPath, discountPath, concentrationPath, obs);\n\n  this->updatePath(path, probabilityPath, discountPath,\n                   concentrationPath, obs);\n\n  // static int j = 0;\n  //if (j == 1) {\n    this->parameters.stepParameterGradient(10e-4);\n  //  j = 0;\n  //}\n  \n\n  return probabilityPath; \n}\n\n\nd_vec HPYPModel::insertObservation(l_type start, l_type stop, e_type obs, \n    WrappedNodeList* cached_path) {\n  tracer << \"HPYPModel::insertObservation(\" << start << \", \" << stop \n         << \", \" << obs << \")\" << std::endl;\n\n  WrappedNodeList path;\n  if (cached_path != NULL) {\n    path = *cached_path;\n  } else {\n    path = this->contextTree.findLongestSuffix(start,stop);\n  }\n  \n  tracer << \"  HPYPModel::insertObservation: longest suffix path: \" \n         << std::endl << this->contextTree.pathToString(path) << std::endl;\n  \n  d_vec discount_path = this->parameters.getDiscounts(path);\n  d_vec concentration_path = this->parameters.getConcentrations(path,\n                                                                discount_path);\n  d_vec prob_path = this->computeProbabilityPath(path,\n                                                 discount_path,\n                                                 concentration_path,\n                                                 obs);\n  this->updatePath(path, prob_path, discount_path,\n                   concentration_path, obs);\n  return prob_path; \n}\n\n\nvoid HPYPModel::removeObservation(\n    l_type start, l_type stop, e_type obs, \n    const HPYPModel::PayloadDataPath& payloadDataPath,\n    WrappedNodeList* cached_path) {\n  tracer << \"HPYPModel::removeObservation(\" << start << \", \" << stop \n         << \", \" << obs << \")\" << std::endl;\n\n  WrappedNodeList path;\n  if (cached_path != NULL) {\n    path = *cached_path;\n  } else {\n    path = this->contextTree.findLongestSuffix(start,stop);\n  }\n  assert(path.back().end == (*cached_path).back().end);\n  \n  tracer << \"  HPYPModel::removeObservation: longest suffix path: \" \n         << std::endl << contextTree.pathToString(path) << std::endl;\n  \n  d_vec discountPath = this->parameters.getDiscounts(path);\n  \n  this->removeObservationFromPath(path, \n                                  discountPath,\n                                  obs,\n                                  payloadDataPath);\n}\n\n\nvoid HPYPModel::removeAddSweep(l_type start, l_type stop) {\n  // start timer\n  clock_t start_t,end_t;\n  start_t = clock();\n  for (int i = start; i < stop; ++i) {\n    HPYPModel::PayloadDataPath payloadDataPath;\n    WrappedNodeList path = this->contextTree.findNode(start, i);\n    //WrappedNodeList p2 = this->contextTree.findLongestSuffix(start, i);\n    //std::cout << path.back().end << \", \" << p2.back().end\n    //          << \", \" << path.size() << \", \" << p2.size() <<std::endl;\n    //assert(path.back().end == p2.back().end);\n    this->removeObservation(start, i, this->seq[i], payloadDataPath, &path);\n    this->insertObservation(start, i, this->seq[i], &path);\n\n    if (i%10000==0) {\n      end_t = clock();\n      std::cerr << makeProgressBarString(i/(double)stop) << \" \" \n                << ((double)i*CLOCKS_PER_SEC)/(end_t-start_t) << \" chars/sec\" \n                <<  \"\\r\";\n    }\n  }\n}\n\n\nd_vec HPYPModel::computeLosses(l_type start, l_type stop) {\n  d_vec losses;\n\n  // deal with first symbol: add loss and insert customer\n  losses.push_back(log2((double) this->numTypes));\n  insertRoot(this->seq[start]);\n\n  // start timer\n  clock_t start_t,end_t;\n  start_t = clock();\n\n  for (l_type i=start+1; i < stop; i++) {\n    d_vec prob_path = this->insertContextAndObservation(start,i,this->seq[i]);\n    double prob = prob_path[prob_path.size()-2];\n    losses.push_back(-log2(prob));\n    \n    if (i%10000==0) {\n      end_t = clock();\n      std::cerr << makeProgressBarString(i/(double)stop) << \" \" \n                << ((double)i*CLOCKS_PER_SEC)/(end_t-start_t) << \" chars/sec\" \n                <<  \"\\r\";\n    }\n\n  }\n  end_t = clock();\n\n  std::cerr << makeProgressBarString(1) << \" \" \n            << ((double)stop*CLOCKS_PER_SEC)/(end_t-start_t) << \" chars/sec\" \n            <<  std::endl;\n  \n  return losses;\n}\n\n\nd_vec HPYPModel::computeLossesWithDeletion(l_type start, l_type stop, l_type lag) {\n  d_vec losses;\n\n  // deal with first symbol: add loss and insert customer\n  losses.push_back(log2((double) this->numTypes));\n  insertRoot(this->seq[start]);\n\n  // start timer\n  clock_t start_t,end_t;\n  start_t = clock();\n\n  for (l_type i=start+1; i < stop; i++) {\n    d_vec prob_path = this->insertContextAndObservation(start,i,this->seq[i]);\n    double prob = prob_path[prob_path.size()-2];\n    losses.push_back(-log2(prob));\n    if (i - lag >= start) {\n      HPYPModel::PayloadDataPath payloadDataPath;\n      WrappedNodeList path = this->contextTree.findNode(start, i - lag);\n      this->removeObservation(start, i - lag, this->seq[i - lag], payloadDataPath, &path);\n    }\n\n    if (i%10000==0) {\n      end_t = clock();\n      std::cerr << makeProgressBarString(i/(double)stop) << \" \" \n        << ((double)i*CLOCKS_PER_SEC)/(end_t-start_t) << \" chars/sec\" \n        <<  \"\\r\";\n    }\n\n  }\n  end_t = clock();\n\n  std::cerr << makeProgressBarString(1) << \" \" \n    << ((double)stop*CLOCKS_PER_SEC)/(end_t-start_t) << \" chars/sec\" \n    <<  std::endl;\n\n  return losses;\n}\n\n\nd_vec HPYPModel::predictSequence(l_type start, l_type stop, PredictMode mode) {\n  d_vec probs;\n  for (l_type i = start; i < stop; i++) {\n    switch(mode) {\n      case ABOVE:\n        probs.push_back(this->predict(start, i, this->seq[i]));\n        break;\n      case FRAGMENT:\n        probs.push_back(this->predictWithFragmentation(start, i, this->seq[i]));\n        break;\n      case BELOW:\n        probs.push_back(this->predictBelow(start, i, this->seq[i]));\n        break;\n    }\n  }\n  return probs;\n}\n\n\nvoid HPYPModel::buildTree(l_type stop) {\n  this->insertRoot(this->seq[0]);\n  for (l_type i=1; i < stop; ++i) {\n    this->insertContextAndObservation(0, i, this->seq[i]);\n  }\n}\n\n\nvoid HPYPModel::updateTree(l_type start, l_type stop) {\n  for (l_type i = start; i < stop; ++i) {\n    this->insertContextAndObservation(0, i, this->seq[i]);\n  }\n}\n\n\ndouble HPYPModel::predict(l_type start, l_type stop, e_type obs) {\n  WrappedNodeList path = this->contextTree.findLongestSuffix(start,stop);\n  d_vec discount_path = this->parameters.getDiscounts(path);\n  d_vec concentration_path = this->parameters.getConcentrations(path,\n                                                                discount_path);\n\n  d_vec prob_path = this->computeProbabilityPath(path,\n                                                 discount_path,\n                                                 concentration_path,\n                                                 obs);\n  return prob_path.back();\n}\n\n\n/**\n * Predict prob; in the case of required fragmentation, predict form \n * _below_ the split point!\n */\ndouble HPYPModel::predictBelow(l_type start, l_type stop, e_type obs) {\n  WrappedNodeList path = \n      this->contextTree.findLongestSuffixVirtual(start,stop).second;\n  d_vec discount_path = this->parameters.getDiscounts(path);\n  d_vec concentration_path = this->parameters.getConcentrations(path,\n                                                                discount_path);\n\n  d_vec prob_path = this->computeProbabilityPath(path,\n                                                 discount_path,\n                                                 concentration_path,\n                                                 obs);\n  return prob_path.back();\n}\n\n\ndouble HPYPModel::predictWithFragmentation(l_type start, \n                                           l_type stop,\n                                           e_type obs) {\n  std::pair<int, WrappedNodeList> path = contextTree.findLongestSuffixVirtual(\n      start, stop);\n\n  d_vec discountPath = parameters.getDiscounts(path.second);\n  d_vec concentrationPath = parameters.getConcentrations(path.second,\n                                                         discountPath);\n  d_vec probabilityPath = this->computeProbabilityPath(path.second,\n                                                       discountPath,\n                                                       concentrationPath,\n                                                       obs);\n\n  double probability = 0;\n  if (path.first != 0) {\n    // create a new payload for the node we are predicting from\n    // fragmentation -- last probability on the path needs to be recomputed\n    // by creating a new, split node of length path.second. \n    void* splitNode = this->restaurant.getFactory().make();\n    WrappedNodeList::iterator it = path.second.end();\n    it--; it--; // one before last; parent of node we need to split\n    int parentLength = it->end - it->start; \n    // path.first is length of parent after split\n    double discountAfter = parameters.getDiscount(path.first, it->end - it->start);\n    it++; // last node\n    double discountFragmented = this->parameters.getDiscount(parentLength,\n                                                             path.first);\n    this->restaurant.updateAfterSplit(\n        it->payload,\n        splitNode,\n        discountPath.back(),\n        discountFragmented,\n        true); // update splitNode only\n    double concentrationFragmented = this->parameters.getConcentration(\n        discountFragmented, parentLength, path.first);\n    probability = this->restaurant.computeProbability(\n        splitNode, obs, probabilityPath[probabilityPath.size()-2],\n        discountFragmented, concentrationFragmented);\n    this->restaurant.getFactory().recycle(splitNode);\n  } else {\n    probability = probabilityPath.back();\n  }\n  return probability;\n}\n\n\nd_vec HPYPModel::predictiveDistribution(l_type start, l_type stop) {\n  d_vec predictive;\n  predictive.reserve(this->numTypes);\n  WrappedNodeList path = this->contextTree.findLongestSuffix(start,stop);\n  d_vec discount_path = this->parameters.getDiscounts(path);\n  d_vec concentration_path = this->parameters.getConcentrations(path,\n                                                                discount_path);\n\n  for(int i = 0; i < this->numTypes; ++i) {\n    d_vec prob_path = this->computeProbabilityPath(path,\n                                                   discount_path,\n                                                   concentration_path,\n                                                   i);\n    predictive.push_back(prob_path.back());\n  }\n\n  return predictive;\n}\n\n\nd_vec HPYPModel::predictiveDistributionWithMixing(l_type start, \n                                                  l_type stop, \n                                                  d_vec& mixingWeights) {\n  d_vec predictive;\n  predictive.reserve(this->numTypes);\n  const WrappedNodeList path = this->contextTree.findLongestSuffix(start, stop);\n  const d_vec discount_path = this->parameters.getDiscounts(path);\n  const d_vec concentration_path \n      = this->parameters.getConcentrations(path, discount_path);\n\n  for(int i = 0; i < this->numTypes; ++i) {\n    d_vec prob_path = this->computeProbabilityPath(path,\n                                                   discount_path,\n                                                   concentration_path,\n                                                   i);\n    double prob = 0;\n    double sum = 0;\n    for (int j = 0; \n         j < std::min<int>(mixingWeights.size(), prob_path.size());\n         ++j) {\n      prob += mixingWeights[j]*prob_path[j];\n      sum += mixingWeights[j];\n    }\n    predictive.push_back(prob + (1 - sum)*prob_path.back());\n  }\n\n  return predictive;\n}\n        \n\n/**\n * Given a path from the root to some node (not a leaf), \n * perform add/remove Gibbs sampling of the last node by repeatedly \n * removing and adding customers, cus times for each type s.\n */\nvoid HPYPModel::addRemoveSamplePath(\n    const WrappedNodeList& path, \n    const d_vec& discountPath, \n    const d_vec& concentrationPath, \n    const HPYPModel::PayloadDataPath& payloadDataPath,\n    double baseProb) {\n  assert(path.size() > 0);\n  assert(path.size() == discountPath.size());\n  assert(path.size() == concentrationPath.size());\n\n  bool useAdditionalData = payloadDataPath.size() == path.size();\n  void* main = path.back().payload;\n  const IAddRemoveRestaurant& r = this->restaurant; // shortcut\n  \n  IHPYPBaseRestaurant::TypeVector types = r.getTypeVector(main);\n  for(IHPYPBaseRestaurant::TypeVectorIterator it = types.begin(); \n      it != types.end(); ++it) { // for each type of customer \n\n    e_type type = *it;\n    l_type cw = r.getC(main, type);\n    \n    if (cw == 1) {\n      continue; // no point in reseating in a 1 customer restaurant\n    }\n\n    d_vec probabilityPath = this->computeProbabilityPath(path,\n                                                         discountPath,\n                                                         concentrationPath,\n                                                         type);\n    WrappedNodeList::const_iterator current;\n    for (l_type i = 0; i < cw; ++i) { // for each customer of this type\n      current = --path.end(); // set current to last restaurant in path\n      \n      // index into d/alpha vectors for current restaurant\n      int j = discountPath.size() - 1;\n      \n      bool goUp = true;\n      while(goUp && j != -1) {\n        void* additionalData = NULL;\n        if (useAdditionalData) {\n          additionalData = payloadDataPath[j].get();\n        }\n        bool removed = r.removeCustomer(current->payload,\n                                        type,\n                                        discountPath[j],\n                                        additionalData);\n        if (removed) {\n          --current;\n          --j;\n        } else {\n          goUp = false;\n        }\n      }\n\n      // recompute probabilities back down; need not recompute last probability\n      while(j < (int)probabilityPath.size() - 1) {\n        if (j == -1) {\n          // can't recompute base distribution probabilities at prob_path[0]\n          j = 0; // \n          ++current;\n        }\n        probabilityPath[j+1] = r.computeProbability(current->payload, \n                                                    type,\n                                                    probabilityPath[j],\n                                                    discountPath[j],\n                                                    concentrationPath[j]);\n        ++j; \n        ++current;\n      }\n\n      // set current and j to the last restaurant on path\n      current = --path.end(); \n      j = discountPath.size() - 1; \n      goUp = true;\n      while(goUp && j != -1) {\n        void* additionalData = NULL;\n        if (useAdditionalData) {\n          additionalData = payloadDataPath[j].get();\n        }\n        bool inserted = r.addCustomer(current->payload, \n                                      type,\n                                      probabilityPath[j],\n                                      discountPath[j],\n                                      concentrationPath[j], \n                                      additionalData);\n        if (inserted) {\n          current--;\n          j--;\n        } else {\n          goUp = false;\n        }\n      }\n\n    }\n\n  }\n\n}\n\n\n/**\n * Given a path from the root to some node (not a leaf), \n * perform add/remove Gibbs sampling of the last node by repeatedly \n * removing and adding customers, cus times for each type s.\n */\nvoid HPYPModel::directGibbsSamplePath(\n    const WrappedNodeList& path, \n    const d_vec& discountPath, \n    const d_vec& concentrationPath, \n    const HPYPModel::PayloadDataPath& payloadDataPath,\n    double baseProb) {\n  assert(path.size() > 0);\n  assert(path.size() == discountPath.size());\n  assert(path.size() == concentrationPath.size());\n\n  bool useAdditionalData = payloadDataPath.size() == path.size();\n  // XXX: HACK! We assume this is the type of addData for the used restaurant\n  stirling_generator_full_log *stirlingGenCurrent = NULL;\n  stirling_generator_full_log *stirlingGenParent = NULL;\n  void* main = path.back().payload;\n  const BaseCompactRestaurant& r = (BaseCompactRestaurant&)this->restaurant; // shortcut\n  \n  IHPYPBaseRestaurant::TypeVector types = r.getTypeVector(main);\n  for(IHPYPBaseRestaurant::TypeVectorIterator it = types.begin(); \n      it != types.end(); ++it) { // for each type of customer \n\n    e_type type = *it;\n    l_type cw = r.getC(main, type);\n    \n    if (cw == 1) {\n      continue; // no point in reseating in a 1 customer restaurant\n    }\n\n    WrappedNodeList::const_iterator current;\n    current = --path.end(); // set current to last restaurant in path\n\n    // index into d/alpha vectors for current restaurant\n    int j = discountPath.size() - 1;\n\n    bool goUp = true;\n    while(goUp && j != -1) {\n      goUp = false;\n      stirlingGenCurrent = (stirling_generator_full_log*)payloadDataPath[j].get();\n      void* currentPayload = (*current).payload;\n      void* parentPayload = NULL; // initialized below\n      int currentCw = r.getC(currentPayload, type);\n      int currentTw = r.getT(currentPayload, type);\n      int otherT = r.getT(currentPayload) - currentTw;\n      std::vector<double> logProbs(currentCw, 0);\n      std::vector<double> logProbs1(currentCw, 0);\n      std::vector<double> logProbs2(currentCw, 0);\n      std::vector<double> logProbs3(currentCw, 0);\n      std::vector<double> logProbs4(currentCw, 0);\n      if (j > 0) { // not at the top, so we have a CRP parent\n        stirlingGenParent = (stirling_generator_full_log*)payloadDataPath[j-1].get();\n        current--; // move to parent\n        parentPayload = (*current).payload;\n        current++;\n        \n        int parentTw = r.getT(parentPayload, type);\n        int parentCw = r.getC(parentPayload, type);\n        int parentOtherC = r.getC(parentPayload) - currentTw;\n        for (int tw = 1; tw <= currentCw; ++tw) {\n          int newParentCw = parentCw - currentTw + tw;\n          if (newParentCw < parentTw) {\n            logProbs4[tw-1] = -INFINITY;\n          } else {\n            logProbs1[tw-1] = logKramp(concentrationPath[j] + discountPath[j], discountPath[j], otherT + tw - 1);\n            logProbs2[tw-1] = - logKramp(concentrationPath[j-1] + 1, 1, parentOtherC + tw - 1);\n            logProbs3[tw-1] = stirlingGenCurrent->getLog(currentCw, tw);\n            logProbs4[tw-1] = stirlingGenParent->getLog(newParentCw, parentTw);\n            //std::cerr <<  logKramp(concentrationPath[j] + discountPath[j], discountPath[j], otherT + tw - 1) << std::endl;\n            //std::cerr <<  logKramp(concentrationPath[j-1], 1, parentOtherC + tw - 1)<< std::endl;\n            //std::cerr <<  stirlingGenCurrent->getLog(cw, tw)<< std::endl;\n            //std::cerr << cw << \", \" << tw << std::endl;\n            //std::cerr <<  stirlingGenParent->getLog(newParentCw, parentTw)<< std::endl;\n            //std::cerr << newParentCw << \", \" << parentTw << std::endl;\n          }\n        }\n        //std::cerr << parentCw << \", \" << parentTw << \", \" << parentOtherC << \", \" << currentTw << \", \" << otherT << std::endl;\n      } else { // at the root, take base prob into account\n        for (int tw = 1; tw <= currentCw; ++tw) {\n          logProbs1[tw-1] = logKramp(concentrationPath[j] + discountPath[j], discountPath[j], otherT + tw - 1);\n          logProbs2[tw-1] = stirlingGenCurrent->getLog(currentCw, tw);\n          logProbs3[tw-1] = tw * log(baseProb);\n        }\n      }\n      // subtract max for stability\n      //std::cerr << iterableToString(logProbs1) << std::endl;\n      //std::cerr << iterableToString(logProbs2) << std::endl;\n      //std::cerr << iterableToString(logProbs3) << std::endl;\n      //std::cerr << iterableToString(logProbs4) << std::endl;\n      subMax_vec(logProbs1);\n      subMax_vec(logProbs2);\n      subMax_vec(logProbs3);\n      subMax_vec(logProbs4);\n      add_vec(logProbs, logProbs1);\n      add_vec(logProbs, logProbs2);\n      add_vec(logProbs, logProbs3);\n      add_vec(logProbs, logProbs4);\n      subMax_vec(logProbs);\n\n\n      //std::cerr << iterableToString(logProbs1) << std::endl;\n      //std::cerr << iterableToString(logProbs2) << std::endl;\n      //std::cerr << iterableToString(logProbs3) << std::endl;\n      //std::cerr << iterableToString(logProbs4) << std::endl;\n      //std::cerr << iterableToString(logProbs) << std::endl;\n      exp_vec(logProbs);\n      //std::cerr << iterableToString(logProbs) << std::endl;\n      // if (max == -INFINITY) { // if all choices are improbable, choose uniformly\n      //     // we can do better by normalizing the component individually\n      //   for (int ii = 0; ii < logProbs.size(); ++ii)\n      //     logProbs[ii] = 1.0;\n      // }\n      //std::cerr << iterableToString(logProbs) << std::endl;\n      int sampledTw = sample_unnormalized_pdf(logProbs, 0) + 1;\n      //std::cerr << \"Old tw: \" << currentTw << \", newTw: \" << sampledTw << std::endl;\n\n\n      r.setT(currentPayload, type, sampledTw);\n      if (j > 0) { \n        int newCw =  r.getC(parentPayload, type) - currentTw + sampledTw;\n        assert(newCw >= r.getT(parentPayload, type));\n        r.setC(parentPayload, type, newCw);\n      }\n\n      if (sampledTw != currentTw) {\n        --current;\n        --j;\n      } else {\n        goUp = false;\n      }\n    }\n\n  }\n\n}\n\n\nboost::shared_ptr<void> HPYPModel::makeAdditionalDataPtr(void* payload, \n                                                         double discount, \n                                                         double concentration) const {\n  return boost::shared_ptr<void>(\n      this->restaurant.createAdditionalData(payload,\n        discount,\n        concentration),\n      boost::bind(&IAddRemoveRestaurant::freeAdditionalData, \n        &(this->restaurant),\n        _1));\n}\n\n\nvoid HPYPModel::runGibbsSampler(bool directGibbs) {\n  ContextTree::DFSPathIterator pathIterator = contextTree.getDFSPathIterator();\n  d_vec discountPath = parameters.getDiscounts(*pathIterator);\n  d_vec concentrationPath = parameters.getConcentrations(*pathIterator, \n                                                         discountPath);\n\n  // initialize payloadDataPath; by using shared_ptr with the proper\n  // destruction function, all clean-up should be automatic.\n  HPYPModel::PayloadDataPath payloadDataPath;\n  int j = 0;\n  for (WrappedNodeList::const_iterator it = (*pathIterator).begin();\n       it != (*pathIterator).end(); ++it) {\n      payloadDataPath.push_back(this->makeAdditionalDataPtr(\n            it->payload, discountPath[j], concentrationPath[j]));\n    j++;\n  }\n\n  if (directGibbs) {\n    this->directGibbsSamplePath(*pathIterator, discountPath, concentrationPath,\n                                payloadDataPath, baseProb);\n  } else {\n    this->addRemoveSamplePath(*pathIterator, discountPath, concentrationPath,\n                              payloadDataPath, baseProb);\n  }\n\n  size_t pathLength = (*pathIterator).size();\n  \n  while(pathIterator.hasMore()) { // loop over all paths in the tree\n    ++pathIterator;\n    if ((*pathIterator).size() == 0) {\n      break;\n    }\n\n    if ((*pathIterator).size() == pathLength) {\n      // sibling\n      discountPath.pop_back();\n      parameters.extendDiscounts(*pathIterator, discountPath);\n      concentrationPath.pop_back();\n      parameters.extendConcentrations(*pathIterator,\n                                      discountPath, \n                                      concentrationPath);\n      payloadDataPath.pop_back();\n      payloadDataPath.push_back(\n          this->makeAdditionalDataPtr((*pathIterator).back().payload, \n                                      discountPath.back(), \n                                      concentrationPath.back()));\n\n    } else {\n      if ((*pathIterator).size() == pathLength - 1) {\n        // we went up -- just drop the last term\n        discountPath.pop_back();\n        concentrationPath.pop_back();\n        payloadDataPath.pop_back();\n      } else {\n        // we went up one and then down some number of levels -- recompute\n        discountPath.pop_back();\n        concentrationPath.pop_back();\n        parameters.extendDiscounts(*pathIterator, discountPath);\n        parameters.extendConcentrations(*pathIterator,\n                                        discountPath,\n                                        concentrationPath);\n        payloadDataPath.pop_back();\n        WrappedNodeList::const_iterator it = (*pathIterator).begin();\n        // move it to the first item not covered by the payloadDataPath\n        for (size_t i = 0; i < payloadDataPath.size(); ++i) {\n          ++it;\n        }\n        for (size_t i = payloadDataPath.size(); i < discountPath.size(); ++i) {\n          payloadDataPath.push_back(\n              this->makeAdditionalDataPtr(it->payload, \n                                          discountPath[i], \n                                          concentrationPath[i]));\n\n          ++it;\n        }\n        assert(it == (*pathIterator).end());\n      }\n    }\n    pathLength = (*pathIterator).size();\n    \n    tracer << (*pathIterator).size() << \" \" << discountPath.size() << \" \" \n           << concentrationPath.size() << \" \" <<  payloadDataPath.size() \n           << std::endl;\n    \n    \n    if (directGibbs) {\n      this->directGibbsSamplePath(*pathIterator, discountPath, concentrationPath,\n                                  payloadDataPath, baseProb);\n    } else {\n      this->addRemoveSamplePath(*pathIterator, discountPath, concentrationPath,\n                                payloadDataPath, baseProb);\n    }\n  }\n}\n\n\nd_vec HPYPModel::computeProbabilityPath(const WrappedNodeList& path, \n                                        const d_vec& discount_path, \n                                        const d_vec& concentration_path,\n                                        e_type obs) {\n  d_vec out;\n  out.reserve(path.size() + 1);\n  \n  double prob = this->baseProb; // base distribution\n  out.push_back(prob);\n  \n  int j = 0;\n  for(WrappedNodeList::const_iterator it = path.begin();\n      it!= path.end();\n      ++it) {\n    prob = this->restaurant.computeProbability(it->payload, \n                                               obs,\n                                               prob,\n                                               discount_path[j],\n                                               concentration_path[j]);\n    out.push_back(prob);\n    j++;\n  } \n  return out;\n}\n\n\nvoid HPYPModel::updatePath(const WrappedNodeList& path, \n                           const d_vec& prob_path, \n                           const d_vec& discount_path, \n                           const d_vec& concentration_path, \n                           e_type obs) {\n\n  unsigned int j=path.size()-1;\n  double newTable = 1;\n  for(WrappedNodeList::const_reverse_iterator it = path.rbegin(); \n      it != path.rend();\n      ++it) {\n    newTable = this->restaurant.addCustomer(it->payload,\n                                            obs,\n                                            prob_path[j],\n                                            discount_path[j],\n                                            concentration_path[j],\n                                            NULL,\n                                            newTable);\n    if (newTable==0) {\n      break;\n    }\n    j--;\n  }\n}\n    \n\nvoid HPYPModel::removeObservationFromPath(\n    const WrappedNodeList& path,\n    const d_vec& discountPath,\n    e_type obs,\n    const HPYPModel::PayloadDataPath& payloadDataPath) {\n  int j = path.size()-1;\n\n\n  double frac_t = 1;\n\n  for(WrappedNodeList::const_reverse_iterator it = path.rbegin();\n    it != path.rend(); it++) {\n\n    void* payloadData = NULL;\n    if (payloadDataPath.size() == path.size()) {\n      payloadData = payloadDataPath[j].get();\n    }\n\n    frac_t = this->restaurant.removeCustomer(it->payload,\n                                             obs,\n                                             discountPath[j],\n                                             payloadData, frac_t);\n    if (frac_t == 0.)\n      break;\n    j--;\n  }\n}\n        \n\nvoid HPYPModel::handleSplit(const WrappedNode& nodeA,\n                            const WrappedNode& nodeB, \n                            const WrappedNode& nodeC) {\n    int lengthA = nodeA.end - nodeA.start;\n    int lengthB = nodeB.end - nodeB.start;\n    int lengthC = nodeC.end - nodeC.start;\n    \n    // parent context should be shorter than both its children \n    assert(lengthA < lengthB && lengthA < lengthC);\n    // length of node that required splitting should be longer than the result\n    assert(lengthC < lengthB);\n\n    double discBBeforeSplit = this->parameters.getDiscount(lengthA, lengthB);\n    double discBAfterSplit  = this->parameters.getDiscount(lengthC, lengthB);\n    this->restaurant.updateAfterSplit(nodeB.payload, \n                                      nodeC.payload, \n                                      discBBeforeSplit,\n                                      discBAfterSplit);\n}\n\n\nbool HPYPModel::checkConsistency(const WrappedNode& node, \n                      const std::list<WrappedNode>& children) const {\n  bool consistent = this->restaurant.checkConsistency(node.payload);\n  std::map<e_type, int> table_counts;\n  for(std::list<WrappedNode>::const_iterator it = children.begin();\n      it != children.end(); ++it) {\n    IHPYPBaseRestaurant::TypeVector keys = \n        this->restaurant.getTypeVector(it->payload);\n    for(IHPYPBaseRestaurant::TypeVectorIterator key_it = keys.begin();\n        key_it != keys.end(); ++key_it) {\n      table_counts[*key_it] += this->restaurant.getT(it->payload, *key_it);\n    }\n  }\n\n  for(std::map<e_type, int>::iterator it = table_counts.begin();\n      it != table_counts.end(); ++it) {\n    consistent = (this->restaurant.getC(node.payload, (*it).first) \n                  >= (*it).second) && consistent;\n    if (!consistent) {\n      std::cerr << \"Child table sum is: \" << (*it).second \n                << \", parent customers is: \" \n                << this->restaurant.getC(node.payload, (*it).first) \n                << std::endl;\n    }\n  }\n  return consistent;\n}\n\n\nvoid HPYPModel::prunePath(WrappedNodeList& path) {\n\n}\n\n\nbool HPYPModel::checkConsistency() const {\n  CheckConsistencyVisitor v(*this);\n  this->contextTree.visitDFSWithChildren(v);\n  return v.consistent;\n}\n \n\ndouble HPYPModel::computeLogRestaurantProb(\n    const WrappedNodeList& path, \n    const d_vec& discountPath, \n    const d_vec& concentrationPath, \n    const HPYPModel::PayloadDataPath& payloadDataPath,\n    double baseProb) const {\n  assert(path.size() > 0);\n  assert(path.size() == discountPath.size());\n  assert(path.size() == concentrationPath.size());\n\n  void* payload = path.back().payload;\n  const BaseCompactRestaurant& r = (BaseCompactRestaurant&)this->restaurant; // shortcut\n  double logProb = 0;\n  int j = discountPath.size() - 1;\n  l_type c = r.getC(payload); \n  if (c == 1) {\n      // deterministic restaurant\n      return 0;\n  }\n  l_type t = r.getT(payload);\n  //std::cerr << \"c: \" << c << \", t: \" << t << std::endl;\n  //std::cerr << \"a: \" << concentrationPath[j] << \", d: \" << discountPath[j] << std::endl;\n  logProb += logKramp(concentrationPath[j] + discountPath[j], discountPath[j], t - 1);\n  //std::cerr << logProb << std::endl;\n  logProb -= logKramp(concentrationPath[j] + 1, 1, c - 1);\n  //std::cerr << logProb << std::endl;\n\n  \n  stirling_generator_full_log *stirlingGen = (stirling_generator_full_log*)payloadDataPath[j].get();\n  IHPYPBaseRestaurant::TypeVector types = r.getTypeVector(payload);\n  for(IHPYPBaseRestaurant::TypeVectorIterator it = types.begin(); \n      it != types.end(); ++it) { // for each type of customer \n\n    e_type type = *it;\n    l_type cw = r.getC(payload, type);\n    l_type tw = r.getT(payload, type);\n    \n    logProb += stirlingGen->getLog(cw, tw);\n\n    if (j == 0) { // at the root, take base prob into account\n      logProb += tw * log(baseProb);\n    }\n  }\n  //std::cerr << logProb << std::endl;\n  return logProb;\n}\n\ndouble HPYPModel::computeLogJoint() const {\n  double logJoint = 0;\n  ContextTree::DFSPathIterator pathIterator = contextTree.getDFSPathIterator();\n  d_vec discountPath = parameters.getDiscounts(*pathIterator);\n  d_vec concentrationPath = parameters.getConcentrations(*pathIterator, \n                                                         discountPath);\n\n  // initialize payloadDataPath; by using shared_ptr with the proper\n  // destruction function, all clean-up should be automatic.\n  HPYPModel::PayloadDataPath payloadDataPath;\n  int j = 0;\n  for (WrappedNodeList::const_iterator it = (*pathIterator).begin();\n       it != (*pathIterator).end(); ++it) {\n      payloadDataPath.push_back(this->makeAdditionalDataPtr(\n            it->payload, discountPath[j], concentrationPath[j]));\n    j++;\n  }\n\n  logJoint += computeLogRestaurantProb(*pathIterator, discountPath, concentrationPath, payloadDataPath, baseProb);\n\n  size_t pathLength = (*pathIterator).size();\n  \n  while(pathIterator.hasMore()) { // loop over all paths in the tree\n    ++pathIterator;\n    if ((*pathIterator).size() == 0) {\n      break;\n    }\n\n    if ((*pathIterator).size() == pathLength) {\n      // sibling\n      discountPath.pop_back();\n      parameters.extendDiscounts(*pathIterator, discountPath);\n      concentrationPath.pop_back();\n      parameters.extendConcentrations(*pathIterator,\n                                      discountPath, \n                                      concentrationPath);\n      payloadDataPath.pop_back();\n      payloadDataPath.push_back(\n          this->makeAdditionalDataPtr((*pathIterator).back().payload, \n                                      discountPath.back(), \n                                      concentrationPath.back()));\n\n    } else {\n      if ((*pathIterator).size() == pathLength - 1) {\n        // we went up -- just drop the last term\n        discountPath.pop_back();\n        concentrationPath.pop_back();\n        payloadDataPath.pop_back();\n      } else {\n        // we went up one and then down some number of levels -- recompute\n        discountPath.pop_back();\n        concentrationPath.pop_back();\n        parameters.extendDiscounts(*pathIterator, discountPath);\n        parameters.extendConcentrations(*pathIterator,\n                                        discountPath,\n                                        concentrationPath);\n        payloadDataPath.pop_back();\n        WrappedNodeList::const_iterator it = (*pathIterator).begin();\n        // move it to the first item not covered by the payloadDataPath\n        for (size_t i = 0; i < payloadDataPath.size(); ++i) {\n          ++it;\n        }\n        for (size_t i = payloadDataPath.size(); i < discountPath.size(); ++i) {\n          payloadDataPath.push_back(\n              this->makeAdditionalDataPtr(it->payload, \n                                          discountPath[i], \n                                          concentrationPath[i]));\n\n          ++it;\n        }\n        assert(it == (*pathIterator).end());\n      }\n    }\n    pathLength = (*pathIterator).size();\n\n    logJoint += computeLogRestaurantProb(*pathIterator, discountPath, concentrationPath, payloadDataPath, baseProb);\n    \n  }\n  return logJoint;\n}\n\n\nHPYPModel::ToStringVisitor::ToStringVisitor(seq_type& seq, \n    const IHPYPBaseRestaurant& restaurant) \n    : outstream(), seq(seq), restaurant(restaurant) {}\n\n\nvoid HPYPModel::ToStringVisitor::operator()(const WrappedNode& n) {\n  for (l_type i = 0; i < n.depth; ++i) {\n    this->outstream << \" \"; \n  }\n  this->outstream << SubSeq::toString(n.start, n.end, seq);\n  this->outstream << \" \" << this->restaurant.toString(n.payload);\n  this->outstream << std::endl;\n}\n\n\nHPYPModel::CheckConsistencyVisitor::CheckConsistencyVisitor(\n    const HPYPModel& model) : consistent(true), model(model) {}\n\n\nvoid HPYPModel::CheckConsistencyVisitor::operator()(\n    WrappedNode& n, std::list<WrappedNode>& children) {\n  bool nodeConsistent = this->model.checkConsistency(n, children);\n  if (!nodeConsistent) {\n    std::cerr << \"Node \" << n.toString() << \" not consistent!\" << std::endl;\n  }\n  consistent = consistent && nodeConsistent;\n}\n\n\nHPYPModel::LogJointVisitor::LogJointVisitor(\n    const HPYPModel& model) : logJoint(0), model(model) {}\n\n\nvoid HPYPModel::LogJointVisitor::operator()(\n    // FIXME\n    WrappedNode& n, std::list<WrappedNode>& children) {\n    int c = model.restaurant.getC(n.payload);\n    int t = model.restaurant.getT(n.payload);\n    IHPYPBaseRestaurant::TypeVector keys = \n        model.restaurant.getTypeVector(n.payload);\n    for(IHPYPBaseRestaurant::TypeVectorIterator key_it = keys.begin();\n        key_it != keys.end(); ++key_it) {\n      int cw = model.restaurant.getC(n.payload, *key_it);\n      int tw = model.restaurant.getT(n.payload, *key_it);\n    }\n}\n\nstd::string HPYPModel::toString() {\n  HPYPModel::ToStringVisitor visitor(this->seq, this->restaurant);\n  this->contextTree.visitDFS(visitor);\n  return visitor.outstream.str();\n}\n\n\n}} // namespace gatsby::libplump\n", "meta": {"hexsha": "7df68b97e1263dbed69fbebf1ccd0cbc8fc20f13", "size": 41222, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libplump/hpyp_model.cc", "max_stars_repo_name": "jgasthaus/libPLUMP", "max_stars_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T21:46:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-16T03:50:37.000Z", "max_issues_repo_path": "src/libplump/hpyp_model.cc", "max_issues_repo_name": "jgasthaus/libPLUMP", "max_issues_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libplump/hpyp_model.cc", "max_forks_repo_name": "jgasthaus/libPLUMP", "max_forks_repo_head_hexsha": "18e5911575e3c9a054482b08d637dc91b0cd05b9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-17T19:19:37.000Z", "max_forks_repo_forks_event_max_datetime": "2016-11-20T00:56:17.000Z", "avg_line_length": 36.3189427313, "max_line_length": 128, "alphanum_fraction": 0.5781378875, "num_tokens": 9418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.24430053065818438}}
{"text": "/// Causal Dynamical Triangulations in C++ using CGAL\n///\n/// Copyright © 2016-2017 Adam Getchell\n///\n/// Data structures for operations on simplicial manifolds\n///\n/// \\done Classify cells as (3,1), (2,2), or (1,3) based on their foliation.\n/// A tuple of vectors contain cell handles to the simplices of type (3,1),\n/// (2,2), and (1,3) respectively.\n/// \\done Classify edges as timelike or spacelike so that action can be\n/// calculated.\n/// \\done SimplicialManifold data structure holding a std::unique_ptr to\n/// the Delaunay triangulation and a std::tuple of geometry information.\n/// \\done Move constructor recalculates geometry.\n///\n/// @file  SimplicialManifold.hpp\n/// @brief Data structures for simplicial manifolds\n/// @author Adam Getchell\n/// @todo Deprecated in favor of Manifold.hpp\n\n#ifndef INCLUDE_SIMPLICIALMANIFOLD_HPP_\n#define INCLUDE_SIMPLICIALMANIFOLD_HPP_\n\n#include <S3Triangulation.hpp>\n#include <boost/optional.hpp>\n#include <map>\n#include <memory>\n#include <set>\n#include <utility>\n#include <vector>\n\nusing Facet = Delaunay3::Facet;\n\n/// @brief A tuple of the geometric values of the Simplicial Manifold\n///\n/// The first element is the vector of (3,1) simplices\n/// The second element is the vector of (2,2) simplices\n/// The third element is the vector of (1,3) simplices\n/// The fourth element is the vector of timelike edges\n/// The fifth element is the vector of spacelike edges\n/// The sixth element is the vector of vertices\n///\n/// Useful for constructing GeometryInfo, which contains this and other\n/// information, and in comparing the results of moves, which will change one or\n/// more elements of the Geometry_tuple.\nusing Geometry_tuple =\n    std::tuple<std::vector<Cell_handle>, std::vector<Cell_handle>,\n               std::vector<Cell_handle>, std::vector<Edge_handle>,\n               std::vector<Edge_handle>, std::vector<Vertex_handle>>;\n\n// Non-member non-friend functions\n\n/// @brief Classifies edges\n///\n/// This function iterates over all edges in the triangulation\n/// and classifies them as timelike or spacelike.\n/// Timelike edges are stored in the **timelike_edges** vector as an Edge_handle\n/// (tuple of Cell_handle, std::size_t, std::size_t) for later use by\n/// ergodic moves on timelike edges. Spacelike edges are also stored as a\n/// vector of Edge_handle **spacelike_edges**, for use by (4,4) moves as\n/// well as the distance-finding algorithms.\n/// @param[in] universe_ptr A std::unique_ptr<Delaunay> to the triangulation\n/// @returns A std::pair<std::vector<Edge_handle>, std::vector<Edge_handle>> of\n/// timelike edges and spacelike edges\ntemplate <typename T>\n[[deprecated]] auto classify_edges(T&& universe_ptr)\n{\n#ifndef NDEBUG\n  std::cout << \"Classifying edges....\\n\";\n#endif\n  Delaunay3::Finite_edges_iterator eit;\n  std::vector<Edge_handle>         timelike_edges;\n  std::vector<Edge_handle>         spacelike_edges;\n\n  // Iterate over all edges in the Delaunay triangulation\n  for (eit = universe_ptr->finite_edges_begin();\n       eit != universe_ptr->finite_edges_end(); ++eit)\n  {\n    Cell_handle ch = eit->first;\n    // Get timevalues of vertices at the edge ends\n    auto time1 = ch->vertex(eit->second)->info();\n    auto time2 = ch->vertex(eit->third)->info();\n\n    // Make Edge_handle\n    Edge_handle thisEdge{\n        ch, static_cast<std::size_t>(ch->index(ch->vertex(eit->second))),\n        static_cast<std::size_t>(ch->index(ch->vertex(eit->third)))};\n\n    if (time1 != time2)\n    {  // We have a timelike edge\n      timelike_edges.emplace_back(thisEdge);\n\n#ifdef DETAILED_DEBUGGING\n      std::cout << \"First vertex of edge is \" << std::get<1>(thisEdge)\n                << \" and second vertex of edge is \" << std::get<2>(thisEdge)\n                << std::endl;\n#endif\n    }\n    else\n    {  // We have a spacelike edge\n      spacelike_edges.emplace_back(thisEdge);\n    }  // endif\n  }    // Finish iterating over edges\n\n// Display results if debugging\n#ifndef NDEBUG\n  std::cout << \"There are \" << timelike_edges.size() << \" timelike edges and \"\n            << spacelike_edges.size() << \" spacelike edges.\\n\";\n#endif\n  return std::make_pair(timelike_edges, spacelike_edges);\n}  // classify_edges()\n\n/// @brief Classify simplices as (3,1), (2,2), or (1,3)\n///\n/// This function iterates over all cells in the triangulation\n/// and classifies them as:\n/// \\f{eqnarray*}{\n///   31 &=& (3, 1) \\\\\n///   22 &=& (2, 2) \\\\\n///   13 &=& (1, 3)\n/// \\f}\n/// The vectors **three_one**, **two_two**, and **one_three** contain\n/// Cell_handles to all the simplices in the triangulation of that corresponding\n/// type.\n///\n/// @param[in] universe_ptr A std::unique_ptr<Delaunay> to the triangulation\n/// @returns A std::tuple<std::vector, std::vector, std::vector> of\n/// **three_one**, **two_two**, and **one_three**\ntemplate <typename T>\n[[deprecated]] auto classify_simplices(T&& universe_ptr)\n{\n#ifndef NDEBUG\n  std::cout << \"Classifying simplices....\\n\";\n#endif\n  Delaunay3::Finite_cells_iterator cit;\n  std::vector<Cell_handle>         three_one;\n  std::vector<Cell_handle>         two_two;\n  std::vector<Cell_handle>         one_three;\n\n  // Iterate over all cells in the Delaunay triangulation\n  for (cit = universe_ptr->finite_cells_begin();\n       cit != universe_ptr->finite_cells_end(); ++cit)\n  {\n    int max_values{0};\n    int min_values{0};\n    // Push every time value of every vertex into a list\n    int timevalues[4] = {\n        cit->vertex(0)->info(),\n        cit->vertex(1)->info(),\n        cit->vertex(2)->info(),\n        cit->vertex(3)->info(),\n    };\n    int max_time =\n        *std::max_element(std::begin(timevalues), std::end(timevalues));\n    for (auto elt : timevalues)\n    {\n      if (elt == max_time) { ++max_values; }\n      else\n      {\n        ++min_values;\n      }\n    }\n\n    // Classify simplex using max_values and write to cit->info()\n    if (min_values == 1 && max_values == 3)\n    {\n      cit->info() = 13;\n      one_three.emplace_back(cit);\n    }\n    else if (min_values == 2 && max_values == 2)\n    {\n      cit->info() = 22;\n      two_two.emplace_back(cit);\n    }\n    else if (min_values == 3 && max_values == 1)\n    {\n      cit->info() = 31;\n      three_one.emplace_back(cit);\n    }\n    else\n    {\n      throw std::runtime_error(\"Invalid simplex in classify_simplices()!\");\n    }  // endif\n  }    // Finish iterating over cells\n\n// Display results if debugging\n#ifndef NDEBUG\n  std::cout << \"There are \" << three_one.size() << \" (3,1) simplices and \"\n            << two_two.size() << \" (2,2) simplices\\n\";\n  std::cout << \"and \" << one_three.size() << \" (1,3) simplices.\\n\";\n#endif\n  return std::make_tuple(three_one, two_two, one_three);\n}  // classify_simplices()\n\ntemplate <typename T>\n[[deprecated]] auto classify_all_simplices(T&& universe_ptr)\n{\n#ifndef NDEBUG\n  std::cout << \"Classifying all simplices....\\n\";\n#endif\n\n  auto                       cells = classify_simplices(universe_ptr);\n  auto                       edges = classify_edges(universe_ptr);\n  std::vector<Vertex_handle> vertices;\n  for (auto vit = universe_ptr->finite_vertices_begin();\n       vit != universe_ptr->finite_vertices_end(); ++vit)\n  { vertices.emplace_back(vit); }\n  return std::make_tuple(std::get<0>(cells), std::get<1>(cells),\n                         std::get<2>(cells), edges.first, edges.second,\n                         vertices);\n}\n\n/// @struct\n/// @brief A struct containing detailed geometry information\n///\n/// GeometryInfo contains information about the geometry of\n/// a triangulation. In addition, it defines convenient functions to\n/// retrieve commonly used values. This is to save the expense of\n/// calculating manually from the triangulation. GeometryInfo() is\n/// recalculated using the move assignment operator anytime a\n/// SimplicialManifold() is move constructed.\n/// The default constructor, destructor, move constructor, copy\n/// constructor, and copy assignment operator are explicitly defaulted.\n/// See http://en.cppreference.com/w/cpp/language/rule_of_three\nstruct [[deprecated]] GeometryInfo\n{\n private:\n  /// @brief (3,1) cells in the foliation\n  std::vector<Cell_handle> three_one;\n\n  /// @brief (2,2) cells in the foliation\n  std::vector<Cell_handle> two_two;\n\n  /// @brief (1,3) cells in the foliation\n  std::vector<Cell_handle> one_three;\n\n  /// @brief Edges spanning two adjacent time slices in the foliation\n  std::vector<Edge_handle> timelike_edges;\n\n  /// @brief Non-spanning edges in the foliation\n  std::vector<Edge_handle> spacelike_edges;\n\n  /// @brief Vertices of the foliation\n  std::vector<Vertex_handle> vertices;\n\n  /// @brief Spacelike facets for each timeslice\n  boost::optional<std::multimap<std::size_t, Facet>> spacelike_facets;\n\n  /// @brief Actual timevalues of simulation\n  boost::optional<std::set<std::size_t>> timevalues;\n\n public:\n  /// @brief Getter for spacelike facets\n  /// @return The multimap of facets\n  const boost::optional<std::multimap<std::size_t, Facet>>&\n  getSpacelike_facets() const\n  {\n    return spacelike_facets;\n  }\n\n  /// @brief Setter for spacelike facets\n  /// @param spacelike_facets The multimap of facets\n  void setSpacelike_facets(\n      const boost::optional<std::multimap<std::size_t, Facet>>&\n          spacelike_facets)\n  {\n    GeometryInfo::spacelike_facets = spacelike_facets;\n  }\n\n  /// @brief Getter for timevalues\n  /// @return The set of timevalues\n  const boost::optional<std::set<std::size_t>>& getTimevalues() const\n  {\n    return timevalues;\n  }\n\n  /// @brief Setter for timevalues\n  /// @param timevalues The set of timevalues\n  void setTimevalues(const boost::optional<std::set<std::size_t>>& timevalues)\n  {\n    GeometryInfo::timevalues = timevalues;\n  }\n\n  /// @brief Default constructor\n  GeometryInfo() = default;\n\n  /// @brief Constructor from Geometry_tuple\n  ///\n  /// This is usually called as a result of classify_all_simplices(),\n  /// which itself takes a std::unique_ptr<Delaunay>\n  /// @param geometry Geometry_tuple initializing values\n  /// @return A populated GeometryInfo{}\n  explicit GeometryInfo(const Geometry_tuple&& geometry) noexcept\n      : three_one{std::get<0>(geometry)}\n      , two_two{std::get<1>(geometry)}\n      , one_three{std::get<2>(geometry)}\n      , timelike_edges{std::get<3>(geometry)}\n      , spacelike_edges{std::get<4>(geometry)}\n      , vertices{std::get<5>(geometry)}\n  {}\n\n  /// @brief Default destructor\n  ~GeometryInfo() = default;\n\n  /// @brief Default move constructor\n  GeometryInfo(GeometryInfo&&) = default;\n\n  /// @brief Default move assignment operator\n  //  GeometryInfo& operator=(GeometryInfo&&) = default;\n  GeometryInfo& operator=(Geometry_tuple&& other)\n  {\n#ifndef NDEBUG\n    std::cout << \"GeometryInfo move assignment operator.\" << std::endl;\n#endif\n    three_one       = std::move(std::get<0>(other));\n    two_two         = std::move(std::get<1>(other));\n    one_three       = std::move(std::get<2>(other));\n    timelike_edges  = std::move(std::get<3>(other));\n    spacelike_edges = std::move(std::get<4>(other));\n    vertices        = std::move(std::get<5>(other));\n    return *this;\n  }\n\n  /// @brief Default copy constructor\n  GeometryInfo(const GeometryInfo&) = default;\n\n  /// @brief Default copy assignment operator\n  GeometryInfo& operator=(const GeometryInfo&) = default;\n\n  /// @brief Timelike edges\n  /// @return The number of edges spanning timeslices\n  auto N1_TL() { return static_cast<std::size_t>(timelike_edges.size()); }\n\n  /// @brief Spacelike edges\n  /// @return The number of edges on same timeslice\n  auto N1_SL() { return static_cast<std::size_t>(spacelike_edges.size()); }\n\n  /// @brief (3,1) simplices\n  /// @return The total number of simplices with 3 vertices on the t\n  /// timeslice and 1 vertex on the t+1 timeslice\n  auto N3_31() { return static_cast<std::size_t>(three_one.size()); }\n\n  /// @brief (1,3) simplices\n  /// @return The total number of simplices with 1 vertex on the t timeslice\n  /// and 3 vertices on the t+1 timeslice\n  auto N3_13() { return static_cast<std::size_t>(one_three.size()); }\n\n  /// @brief (3,1) and (1,3) simplices\n  /// @return The total number of simplices with 3 vertices on one\n  /// timeslice and 1 vertex on the adjacent timeslice. Used to\n  /// calculate the change in action.\n  auto N3_31_13() { return N3_31() + N3_13(); }\n\n  /// @brief (2,2) simplices\n  /// @return The total number of simplices with 2 vertices on one\n  /// timeslice and 2 vertices on the adjacent timeslice. Used to\n  /// calculate the change in action.\n  auto N3_22() { return static_cast<std::size_t>(two_two.size()); }\n\n  /// @brief Number of cells\n  ///\n  /// This should be the equivalent of\n  /// SimplicialManifold::triangulation->number_of_finite_cells(),\n  /// and is used as a check to ensure that GeometryInfo{} matches.\n  /// @return The number of cells in GeometryInfo{}\n  auto number_of_cells() { return N3_31() + N3_22() + N3_13(); }\n\n  /// @brief Number of edges\n  ///\n  /// This should be the equivalent of\n  /// SimplicialManifold::triangulation->number_of_finite_edges(),\n  /// and is used as a check to ensure that GeometryInfo{} matches.\n  /// @return The number of edges in the triangulation\n  auto number_of_edges() { return N1_TL() + N1_SL(); }\n\n  //  auto max_timevalue() { return *timevalues.crbegin();}\n  boost::optional<std::size_t> max_timevalue()\n  {\n    return timevalues ? *timevalues->crbegin() : 0;\n  }\n\n  boost::optional<std::size_t> min_timevalue()\n  {\n    return timevalues ? *timevalues->begin() : 0;\n  }\n  /// @brief Number of vertices\n  /// @return The number of vertices in the triangulation\n  auto N0() { return static_cast<std::size_t>(vertices.size()); }\n\n  template <typename T1, typename T2>\n  friend auto make_23_move(T1&& universe, T2&& attempted_moves)\n      -> decltype(universe);\n\n  template <typename T1, typename T2>\n  friend auto make_32_move(T1&& universe, T2&& attempted_moves)\n      -> decltype(universe);\n\n  template <typename T1, typename T2>\n  friend auto make_26_move(T1&& universe, T2&& attempted_moves)\n      -> decltype(universe);\n\n  template <typename T1, typename T2>\n  friend auto make_62_move(T1&& universe, T2&& attempted_moves)\n      -> decltype(universe);\n\n  template <typename T1, typename T2>\n  friend auto make_44_move(T1&& universe, T2&& attempted_moves)\n      -> decltype(universe);\n\n  template <typename T>\n  friend auto VolumePerTimeslice(T&& manifold) -> decltype(manifold);\n};\n\n/// @struct\n/// @brief A struct to hold triangulation and geometry information\n///\n/// SimplicialManifold contains information about the triangulation and\n/// its geometry. In addition, it defines convenient constructors.\nstruct [[deprecated]] SimplicialManifold\n{\n  /// @brief Owning pointer to the Delaunay triangulation\n  std::unique_ptr<Delaunay3> triangulation;\n\n  /// @brief Owning pointer to GeometryInfo\n  std::unique_ptr<GeometryInfo> geometry;\n\n  /// @brief Default constructor\n  SimplicialManifold()\n      : triangulation{std::make_unique<Delaunay3>()}\n      , geometry{std::make_unique<GeometryInfo>()}\n  {\n#ifndef NDEBUG\n    std::cout << \"SimplicialManifold default ctor.\\n\";\n#endif\n  }\n\n  /// @brief Constructor with std::unique_ptr<Delaunay>\n  ///\n  /// Constructor taking a std::unique_ptr<Delaunay> which should be created\n  /// using make_triangulation(). If you wish to default initialize a\n  /// SimplicialManifold with no values, use the default\n  /// constructor SimplicialManifold::SimplicialManifold() instead.\n  /// Non-static data members are initialized in the order they are declared,\n  /// (see http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/n4594.pdf,\n  ///  \\f$\\S\\f$ 12.6.2.13.3), so **geometry** depending upon **triangulation**\n  /// is fine.\n  /// @param manifold A std::unique_ptr<Delaunay>\n  /// @return A SimplicialManifold{}\n  explicit SimplicialManifold(std::unique_ptr<Delaunay3>&& manifold)\n      : triangulation{std::move(manifold)}\n      , geometry{std::make_unique<GeometryInfo>(\n            classify_all_simplices(triangulation))}\n  {\n#ifndef NDEBUG\n    std::cout << \"SimplicialManifold std::unique_ptr<Delaunay> ctor.\\n\";\n#endif\n  }\n\n  /// @brief make_triangulation constructor\n  ///\n  /// Constructor that initializes **triangulation** by calling\n  /// make_triangulation() and **geometry** by calling\n  /// classify_all_simplices().\n  /// @param simplices The number of desired simplices in the triangulation\n  /// @param timeslices The number of timeslices in the triangulation\n  /// @return A populated SimplicialManifold{}\n  SimplicialManifold(std::size_t simplices, std::size_t timeslices)\n      : triangulation{make_triangulation(simplices, timeslices)}\n      , geometry{std::make_unique<GeometryInfo>(\n            classify_all_simplices(triangulation))}\n  {\n#ifndef NDEBUG\n    std::cout << \"SimplicialManifold make_triangulation ctor.\\n\";\n#endif\n  }\n\n  /// @brief Destructor\n  ~SimplicialManifold()\n  {\n#ifndef NDEBUG\n    std::cout << \"SimplicialManifold dtor.\\n\";\n#endif\n    this->triangulation = nullptr;\n    this->geometry      = nullptr;\n  }\n\n  /// @brief Move constructor\n  /// @param other The SimplicialManifold to be move-constructed from\n  /// @return A moved-to SimplicialManifold{}\n  SimplicialManifold(SimplicialManifold&& other)\n      : triangulation{std::move(other.triangulation)}\n      , geometry{std::make_unique<GeometryInfo>(\n            classify_all_simplices(triangulation))}\n  //      , geometry{std::move(other.geometry)}\n  {\n#ifndef NDEBUG\n    std::cout << \"SimplicialManifold move ctor.\\n\";\n#endif\n  }\n  //  SimplicialManifold(SimplicialManifold&&) = default;\n\n  /// @brief Move assignment operator\n  /// @param other The SimplicialManifold to be moved from\n  /// @return A moved-assigned SimplicialManifold{}\n  SimplicialManifold& operator=(SimplicialManifold&& other) noexcept\n  {\n#ifndef NDEBUG\n    std::cout << \"SimplicialManifold move assignment operator.\\n\";\n#endif\n    triangulation = std::move(other.triangulation);\n    geometry      = std::make_unique<GeometryInfo>(\n        classify_all_simplices(std::move(triangulation)));\n    //      geometry = std::move(other.geometry);\n    return *this;\n  }\n  //  SimplicialManifold& operator=(SimplicialManifold&&) = default;\n\n  /// @brief SimplicialManifold copy constructor\n  /// @param other The SimplicialManifold to copy\n  /// @return A copied SimplicialManifold{}\n  SimplicialManifold(const SimplicialManifold& other)\n      : triangulation{std::make_unique<Delaunay3>(*(other.triangulation))}\n      , geometry{std::make_unique<GeometryInfo>(*(other.geometry))}\n  {\n#ifndef NDEBUG\n    std::cout << \"SimplicialManifold copy ctor.\\n\";\n#endif\n  }\n\n  /// @brief Copy assignment operator\n  /// @return A copy-assigned SimplicialManifold{}\n  //    SimplicialManifold& operator=(const SimplicialManifold&) = default;\n  SimplicialManifold& operator=(const SimplicialManifold& other) noexcept\n  {\n#ifndef NDEBUG\n    std::cout << \"SimplicialManifold copy assignment operator.\\n\";\n#endif\n    SimplicialManifold temp(other);\n    swap(triangulation, temp.triangulation);\n    swap(geometry, temp.geometry);\n    return *this;\n  }\n\n  /// @brief Exception-safe swap\n  /// @param first  The first SimplicialManifold to be swapped\n  /// @param second The second SimplicialManifold to be swapped with.\n  friend void swap(SimplicialManifold& first,\n                   SimplicialManifold& second) noexcept\n  {\n#ifndef NDEBUG\n    std::cout << \"SimplicialManifold swapperator.\\n\";\n#endif\n    using std::swap;\n    swap(first.triangulation, second.triangulation);\n    swap(first.geometry, second.geometry);\n  }\n\n  bool reconcile()\n  {\n    return (this->triangulation->number_of_vertices() == this->geometry->N0() &&\n            this->triangulation->number_of_finite_edges() ==\n                this->geometry->number_of_edges() &&\n            this->triangulation->number_of_finite_cells() ==\n                this->geometry->number_of_cells());\n  }\n\n  void update()\n  {\n    geometry = std::make_unique<GeometryInfo>(\n        classify_all_simplices(std::move(triangulation)));\n  }\n};\n\n#endif  // INCLUDE_SIMPLICIALMANIFOLD_HPP_\n", "meta": {"hexsha": "c08c3f3f2724cb78262cf3314e15e406721b2ae8", "size": 19992, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/SimplicialManifold.hpp", "max_stars_repo_name": "jefftrull/CDT-plusplus", "max_stars_repo_head_hexsha": "d66e82d2fcc459151c3bbcaa8eab74253e40c3cf", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/SimplicialManifold.hpp", "max_issues_repo_name": "jefftrull/CDT-plusplus", "max_issues_repo_head_hexsha": "d66e82d2fcc459151c3bbcaa8eab74253e40c3cf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/SimplicialManifold.hpp", "max_forks_repo_name": "jefftrull/CDT-plusplus", "max_forks_repo_head_hexsha": "d66e82d2fcc459151c3bbcaa8eab74253e40c3cf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7686956522, "max_line_length": 80, "alphanum_fraction": 0.6821728691, "num_tokens": 5351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24430053065818436}}
{"text": "/*\n *  Copyright 2010 CNRS\n *\n *  Florent Lamiraux\n */\n\n#include <boost/format.hpp>\n#include <boost/numeric/ublas/io.hpp>\n\n#include <dynamic-graph/factory.h>\n#include <dynamic-graph/command-setter.h>\n#include <dynamic-graph/command-getter.h>\n#include \"dynamic-graph/tutorial/inverted-pendulum.hh\"\n#include \"command-increment.hh\"\n#include \"constant.hh\"\n\nusing namespace dynamicgraph;\nusing namespace dynamicgraph::tutorial;\n\nconst double Constant::gravity = 9.81;\n\n// Register new Entity type in the factory\n// Note that the second argument is the type name of the python class\n// that will be created when importing the python module.\nDYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(InvertedPendulum, \"InvertedPendulum\");\n\nInvertedPendulum::InvertedPendulum(const std::string& inName)\n    : Entity(inName),\n      forceSIN(NULL, \"InvertedPendulum(\" + inName + \")::input(double)::force\"),\n      stateSOUT(\"InvertedPendulum(\" + inName + \")::output(vector)::state\"),\n      cartMass_(1.0),\n      pendulumMass_(1.0),\n      pendulumLength_(1.0),\n      viscosity_(0.1) {\n  // Register signals into the entity.\n  signalRegistration(forceSIN);\n  signalRegistration(stateSOUT);\n\n  // Set signals as constant to size them\n  Vector state(4);\n  state.fill(0.);\n  double input = 0.;\n  stateSOUT.setConstant(state);\n  forceSIN.setConstant(input);\n\n  // Commands\n  std::string docstring;\n\n  // Incr\n  docstring =\n      \"\\n\"\n      \"    Integrate dynamics for time step provided as input\\n\"\n      \"\\n\"\n      \"      take one floating point number as input\\n\"\n      \"\\n\";\n  addCommand(std::string(\"incr\"), new command::Increment(*this, docstring));\n\n  // setCartMass\n  docstring =\n      \"\\n\"\n      \"    Set cart mass\\n\"\n      \"\\n\";\n  addCommand(std::string(\"setCartMass\"), new ::dynamicgraph::command::Setter<InvertedPendulum, double>(\n                                             *this, &InvertedPendulum::setCartMass, docstring));\n\n  // getCartMass\n  docstring =\n      \"\\n\"\n      \"    Get cart mass\\n\"\n      \"\\n\";\n  addCommand(std::string(\"getCartMass\"), new ::dynamicgraph::command::Getter<InvertedPendulum, double>(\n                                             *this, &InvertedPendulum::getCartMass, docstring));\n\n  // setPendulumMass\n  docstring =\n      \"\\n\"\n      \"    Set pendulum mass\\n\"\n      \"\\n\";\n  addCommand(std::string(\"setPendulumMass\"), new ::dynamicgraph::command::Setter<InvertedPendulum, double>(\n                                                 *this, &InvertedPendulum::setPendulumMass, docstring));\n\n  // getPendulumMass\n  docstring =\n      \"\\n\"\n      \"    Get pendulum mass\\n\"\n      \"\\n\";\n  addCommand(std::string(\"getPendulumMass\"), new ::dynamicgraph::command::Getter<InvertedPendulum, double>(\n                                                 *this, &InvertedPendulum::getPendulumMass, docstring));\n\n  // setPendulumLength\n  docstring =\n      \"\\n\"\n      \"    Set pendulum length\\n\"\n      \"\\n\";\n  addCommand(std::string(\"setPendulumLength\"), new ::dynamicgraph::command::Setter<InvertedPendulum, double>(\n                                                   *this, &InvertedPendulum::setPendulumLength, docstring));\n\n  // getPendulumLength\n  docstring =\n      \"\\n\"\n      \"    Get pendulum length\\n\"\n      \"\\n\";\n  addCommand(std::string(\"getPendulumLength\"), new ::dynamicgraph::command::Getter<InvertedPendulum, double>(\n                                                   *this, &InvertedPendulum::getPendulumLength, docstring));\n}\n\nInvertedPendulum::~InvertedPendulum() {}\n\nVector InvertedPendulum::computeDynamics(const Vector& inState, const double& inControl, double inTimeStep) {\n  if (inState.size() != 4)\n    throw dynamicgraph::ExceptionSignal(dynamicgraph::ExceptionSignal::GENERIC, \"state signal size is \",\n                                        \"%d, should be 4.\", inState.size());\n\n  double dt = inTimeStep;\n  double dt2 = dt * dt;\n  double g = Constant::gravity;\n  double x = inState(0);\n  double th = inState(1);\n  double dx = inState(2);\n  double dth = inState(3);\n  double F = inControl;\n  double m = pendulumMass_;\n  double M = cartMass_;\n  double l = pendulumLength_;\n  double lambda = viscosity_;\n  double l2 = l * l;\n  double dth2 = dth * dth;\n  double sth = sin(th);\n  double cth = cos(th);\n  double sth2 = sth * sth;\n\n  double b1 = F - m * l * dth2 * sth - lambda * dx;\n  double b2 = m * l * g * sth - lambda * dth;\n\n  double det = m * l2 * (M + m * sth2);\n\n  double ddx = (b1 * m * l2 + b2 * m * l * cth) / det;\n  double ddth = ((M + m) * b2 + m * l * cth * b1) / det;\n\n  Vector nextState(4);\n  nextState(0) = x + dx * dt + .5 * ddx * dt2;\n  nextState(1) = th + dth * dt + .5 * ddth * dt2;\n  nextState(2) = dx + dt * ddx;\n  nextState(3) = dth + dt * ddth;\n\n  return nextState;\n}\n\nvoid InvertedPendulum::incr(double inTimeStep) {\n  int t = stateSOUT.getTime();\n  Vector nextState = computeDynamics(stateSOUT(t), forceSIN(t), inTimeStep);\n  stateSOUT.setConstant(nextState);\n  stateSOUT.setTime(t + 1);\n  forceSIN(t + 1);\n}\n", "meta": {"hexsha": "40031b8b40104b1a6fccf54f5ff2a548c2029d52", "size": 4935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/inverted-pendulum.cpp", "max_stars_repo_name": "Rascof/dynamic-graph-tutorial", "max_stars_repo_head_hexsha": "8b3df91f8ba86e41841c8b14bb300e4444e240cd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T15:37:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T12:59:08.000Z", "max_issues_repo_path": "src/inverted-pendulum.cpp", "max_issues_repo_name": "Rascof/dynamic-graph-tutorial", "max_issues_repo_head_hexsha": "8b3df91f8ba86e41841c8b14bb300e4444e240cd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-08-24T20:55:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-24T20:55:04.000Z", "max_forks_repo_path": "src/inverted-pendulum.cpp", "max_forks_repo_name": "Rascof/dynamic-graph-tutorial", "max_forks_repo_head_hexsha": "8b3df91f8ba86e41841c8b14bb300e4444e240cd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-12-14T14:57:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-22T08:40:33.000Z", "avg_line_length": 31.6346153846, "max_line_length": 109, "alphanum_fraction": 0.6216818642, "num_tokens": 1373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24430053065818436}}
{"text": "#include <iostream>\n#include <memory>\n#include <string>\n#include <chrono>\n\n#include <boost/program_options.hpp>\n#include <algorithms/Grover.hpp>\n#include <algorithms/QFT.hpp>\n#include <algorithms/Entanglement.hpp>\n\n\n#include \"Simulator.hpp\"\n#include \"QFRSimulator.hpp\"\n#include \"GroverSimulator.hpp\"\n#include \"ShorFastSimulator.hpp\"\n#include \"ShorSimulator.hpp\"\n\n\nint main(int argc, char** argv) {\n    namespace po = boost::program_options;\n    unsigned long long seed;\n\n    po::options_description description(\"JKQ DDSIM by https://iic.jku.at/eda/ -- Allowed options\");\n    description.add_options()\n            (\"help,h\", \"produce help message\")\n            (\"seed\", po::value<unsigned long long>(&seed)->default_value(0), \"seed for random number generator (default zero is possibly directly used as seed!)\")\n            (\"shots\", po::value<unsigned int>()->default_value(0), \"number of measurements (if the algorithm does not contain non-unitary gates, weak simulation is used)\")\n            (\"display_vector\", \"display the state vector\")\n            (\"ps\", \"print simulation stats (applied gates, sim. time, and maximal size of the DD)\")\n            (\"verbose\", \"Causes some simulators to print additional information to STDERR\")\n            (\"benchmark\", \"print simulation stats in a single CSV style line (overrides --ps and suppresses most other output, please don't rely on the format across versions)\")\n\n            (\"simulate_file\", po::value<std::string>(), \"simulate a quantum circuit given by file (detection by the file extension)\")\n            (\"simulate_qft\", po::value<unsigned int>(), \"simulate Quantum Fourier Transform for given number of qubits\")\n            (\"simulate_ghz\", po::value<unsigned int>(), \"simulate state preparation of GHZ state for given number of qubits\")\n            (\"step_fidelity\", po::value<double>()->default_value(1.0), \"target fidelity for each approximation run (>=1 = disable approximation)\")\n            (\"steps\", po::value<unsigned int>()->default_value(1), \"number of approximation steps\")\n            (\"initial_reorder\", po::value<int>()->default_value(0), \"Try to find a good initial variable order (0=None, 1=Most affected qubits to the top, 2=Most affected targets to the top)\")\n            (\"dynamic_reorder\", po::value<int>()->default_value(0), \"Apply reordering strategy during simulation (0=None, 1=Sifting, 2=Move2Top)\")\n            (\"post_reorder\", po::value<int>()->default_value(0), \"Apply a reordering strategy after simulation (0=None, 1=Sifting)\")\n\n            (\"simulate_grover\", po::value<unsigned int>(), \"simulate Grover's search for given number of qubits with random oracle\")\n            (\"simulate_grover_emulated\", po::value<unsigned int>(), \"simulate Grover's search for given number of qubits with random oracle and emulation\")\n            (\"simulate_grover_oracle_emulated\", po::value<std::string>(), \"simulate Grover's search for given number of qubits with given oracle and emulation\")\n\n            (\"simulate_shor\", po::value<unsigned int>(), \"simulate Shor's algorithm factoring this number\")\n            (\"simulate_shor_coprime\", po::value<unsigned int>()->default_value(0), \"coprime number to use with Shor's algorithm (zero randomly generates a coprime)\")\n            (\"simulate_shor_no_emulation\", \"Force Shor simulator to do modular exponentiation instead of using emulation (you'll usually want emulation)\")\n\n            (\"simulate_fast_shor\", po::value<unsigned int>(), \"simulate Shor's algorithm factoring this number with intermediate measurements\")\n            (\"simulate_fast_shor_coprime\", po::value<unsigned int>()->default_value(0), \"coprime number to use with Shor's algorithm (zero randomly generates a coprime)\")\n            (\"noise_effects\", po::value<std::string>(),\n             \"Noise effects (A (=amplitude damping),D (=depolarization),P (=phase flip)) in the form of a character string describing the noise effects (default=\\\" \\\")\")\n            (\"noise_prob\", po::value<double>(), \"Probability for applying noise (default=0.001)\")\n            (\"confidence\", po::value<double>(),\n             \"Confidence in the error bound of the stochastic simulation (default= 0.05)\")\n            (\"error_bound\", po::value<double>(), \"Error bound of the stochastic simulation (default=0.1)\")\n            (\"stoch_runs\", po::value<long>()->default_value(0), \"Number of stochastic runs. When the value is 0 the value is calculated using the confidence, error_bound and number of tracked properties. (default = 0)\")\n            (\"properties\", po::value<std::string>(), R\"(Comma separated list of tracked properties. Note that -1 is the fidelity and \"-\" can be used to specify a range.  (default=\"0-1000\"))\")\n            ;\n    po::variables_map vm;\n    try {\n        po::store(po::parse_command_line(argc, argv, description), vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << description;\n            return 0;\n        }\n        po::notify(vm);\n    } catch (const po::error &e) {\n        std::cerr << \"[ERROR] \" << e.what() << \"! Try option '--help' for available commandline options.\\n\";\n        std::exit(1);\n    }\n\n    std::unique_ptr<qc::QuantumComputation> quantumComputation;\n    std::unique_ptr<Simulator> ddsim{nullptr};\n\n    if (vm.count(\"simulate_file\")) {\n        const std::string fname = vm[\"simulate_file\"].as<std::string>();\n    \tquantumComputation = std::make_unique<qc::QuantumComputation>(fname);\n        ddsim = std::make_unique<QFRSimulator>(quantumComputation,\n                                               vm[\"steps\"].as<unsigned int>(), vm[\"step_fidelity\"].as<double>(),\n                                               vm[\"initial_reorder\"].as<int>(), vm[\"dynamic_reorder\"].as<int>(), vm[\"post_reorder\"].as<int>(),\n                                               seed);\n    } else {\n        std::cerr << \"Did not find anything to simulate. See help below.\\n\"\n                  << description << \"\\n\";\n        return 1;\n    }\n\n    if (quantumComputation && quantumComputation->getNqubits() > dd::MAXN) {\n        std::cerr << \"Quantum computation contains to many qubits (limit is set to \" << dd::MAXN << \"). See documentation for details.\\n\";\n        std::exit(1);\n    }\n        if (vm.count(\"noise_effects\")) {\n            ddsim->setNoiseEffects((char *) &vm[\"noise_effects\"].as<std::string>()[0]);\n    } else {\n            ddsim->setNoiseEffects((char *) &std::string(\"0\")[0]);\n    }\n    if (vm.count(\"noise_prob\")) {\n        ddsim->setAmplitudeDampingProbability(vm[\"noise_prob\"].as<double>());\n    } else {\n        ddsim->setAmplitudeDampingProbability(0.001);\n    }\n\n    if (vm.count(\"confidence\")) {\n        ddsim->stoch_confidence = vm[\"confidence\"].as<double>();\n    }\n\n    if (vm.count(\"properties\")) {\n        ddsim->setRecordedProperties((char *) &vm[\"properties\"].as<std::string>()[0]);\n    } else {\n        ddsim->setRecordedProperties(\"0-1000\");\n    }\n\n    if (vm.count(\"error_bound\")) {\n        ddsim->stoch_error_margin = vm[\"error_bound\"].as<double>();\n    } else {\n        ddsim->stoch_error_margin = 0.01;\n    }\n    ddsim->stochastic_runs = vm[\"stoch_runs\"].as<long>();\n\n    auto t1 = std::chrono::high_resolution_clock::now();\n    ddsim->StochSimulate();\n    auto t2 = std::chrono::high_resolution_clock::now();\n\n    std::chrono::duration<float> duration_simulation = t2-t1;\n\n    if (vm.count(\"benchmark\")) {\n        auto more_info = ddsim->AdditionalStatistics();\n        std::cout << ddsim->getName() << \", \"\n                  << ddsim->getNumberOfQubits() << \", \"\n                  //<< vm[\"approximate\"].as<float>() << \", \"\n                  << std::fixed << duration_simulation.count() << std::defaultfloat << \", \"\n                  //<< more_info[\"approximation_runs\"] << \",\"\n                  //<< more_info[\"final_fidelity\"] << \", \"\n                  << more_info[\"coprime_a\"] << \", \"\n                  << more_info[\"sim_result\"] << \", \"\n                  << more_info[\"polr_result\"] << \", \"\n                  << ddsim->getSeed() << \", \"\n                  << ddsim->getNumberOfOps() << \", \"\n                  << ddsim->getMaxNodeCount()\n                  << \"\\n\";\n        return 0;\n    }\n\n    std::cout << \"{\\n\";\n\n    if (vm.count(\"ps\")) {\n        std::cout << \"  \\\"statistics\\\": {\\n\"\n                  << \"    \\\"simulation_time\\\": \" << std::fixed << duration_simulation.count() << std::defaultfloat << \",\\n\"\n                  << \"    \\\"benchmark\\\": \\\"\" << ddsim->getName() << \"\\\",\\n\"\n                  << \"    \\\"shots\\\": \" << vm[\"shots\"].as<unsigned int>() << \",\\n\"\n//                  << \"    \\\"distinct_results\\\": \" << m.size() << \",\\n\"\n                  << \"    \\\"n_qubits\\\": \" << ddsim->getNumberOfQubits() << \",\\n\"\n                  << \"    \\\"applied_gates\\\": \" << ddsim->getNumberOfOps() << \",\\n\"\n                  << \"    \\\"max_nodes\\\": \" << ddsim->getMaxNodeCount() << \",\\n\"\n                  ;\n        for(const auto& item : ddsim->AdditionalStatistics()) {\n            std::cout << \"    \\\"\" << item.first << \"\\\": \\\"\" << item.second << \"\\\",\\n\";\n        }\n        std::cout << \"    \\\"seed\\\": \" << ddsim->getSeed() << \"\\n\"\n                  << \"  },\\n\";\n    }\n    std::cout << \"  \\\"dummy\\\": 0\\n}\\n\"; // trailing element to make json printout easier\n}\n", "meta": {"hexsha": "7cb54f47c1098cc7dd094fc5e41c8b8f03fe03a5", "size": 9205, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/noise_aware.cpp", "max_stars_repo_name": "Tonanguyxiro/ddsim", "max_stars_repo_head_hexsha": "ff6d8afba6e72f4795394688872a9081f871d320", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-05T09:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-05T09:17:39.000Z", "max_issues_repo_path": "apps/noise_aware.cpp", "max_issues_repo_name": "Tonanguyxiro/ddsim", "max_issues_repo_head_hexsha": "ff6d8afba6e72f4795394688872a9081f871d320", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/noise_aware.cpp", "max_forks_repo_name": "Tonanguyxiro/ddsim", "max_forks_repo_head_hexsha": "ff6d8afba6e72f4795394688872a9081f871d320", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.119760479, "max_line_length": 219, "alphanum_fraction": 0.5900054318, "num_tokens": 2217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.2439927732459154}}
{"text": "/*\n * Copyright (c) 2011, Mattia Penati <mattia.penati@gmail.com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright notice,\n *       this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright notice,\n *       this list of conditions and the following disclaimer in the documentation\n *       and/or other materials provided with the distribution.\n *     * Neither the name of the Politecnico di Milano nor the names of its\n *       contributors may be used to endorse or promote products derived from\n *       this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef AMA_TENSOR_DETAIL_TENSOR_OUTER_HPP\n#define AMA_TENSOR_DETAIL_TENSOR_OUTER_HPP 1\n\n#include <ama/tensor/detail/tensor_base.hpp>\n#include <boost/mpl/advance.hpp>\n#include <boost/mpl/assert.hpp>\n#include <boost/mpl/begin_end.hpp>\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/plus.hpp>\n#include <boost/mpl/push_back.hpp>\n#include <boost/mpl/vector/vector0_c.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    /* forward declaration*/\n    template <typename LEFT, typename RIGHT> class tensor_outer;\n\n\n    /* traits definition */\n    template <typename LEFT, typename RIGHT>\n    struct tensor_traits< tensor_outer<LEFT, RIGHT> >\n    {\n      typedef typename LEFT::value_type value_type;\n\n      typedef typename LEFT::dimension_type dimension_type;\n\n      typedef typename ::boost::mpl::plus<\n                             typename LEFT::controvariant_type\n                           , typename RIGHT::controvariant_type\n                           >::type controvariant_type;\n      typedef typename ::boost::mpl::plus<\n                             typename LEFT::covariant_type\n                           , typename RIGHT::covariant_type\n                           >::type covariant_type;\n\n      typedef ::boost::mpl::false_ is_assignable;\n      typedef ::boost::mpl::true_ is_temporary;\n    };\n\n\n    /* class declaration */\n    template <typename LEFT, typename RIGHT>\n    class tensor_outer:\n        public tensor_base< tensor_outer<LEFT, RIGHT> >\n    {\n    protected:\n      typedef tensor_base< tensor_outer<LEFT, RIGHT> > base_type;\n      typedef tensor_outer<LEFT, RIGHT> derived_type;\n\n    protected:\n      typedef LEFT left_operand_type;\n      typedef RIGHT right_operand_type;\n\n    public:\n      typedef typename base_type::value_type value_type;\n\n    public:\n      /* costructor */\n      tensor_outer(left_operand_type const & left,\n                   right_operand_type const & right)\n          : m_left(left),\n            m_right(right) { }\n\n    public:\n      /* retrieve the value */\n      template <typename ILIST>\n      value_type at() const\n      {\n        namespace mpl = ::boost::mpl;\n\n        /* iterator */\n        typedef typename mpl::begin<ILIST>::type begin1;\n        typedef typename mpl::advance<begin1, typename LEFT::controvariant_type>::type begin2;\n        typedef typename mpl::advance<begin2, typename RIGHT::controvariant_type>::type begin3;\n        typedef typename mpl::advance<begin3, typename LEFT::covariant_type>::type begin4;\n        typedef typename mpl::advance<begin4, typename RIGHT::covariant_type>::type begin5;\n        typedef typename mpl::end<ILIST>::type end;\n\n        /* check for no errors in the code */\n        BOOST_MPL_ASSERT((mpl::equal_to<mpl::distance<end,begin5>,mpl::size_t<0> >));\n\n        /* split multi-index */\n        typedef typename mpl::fold<\n              mpl::iterator_range<begin1, begin2>\n            , mpl::vector0_c<size_t>\n            , mpl::push_back<mpl::_1, mpl::_2>\n            >::type controvariant_left;\n\n        typedef typename mpl::fold<\n              mpl::iterator_range<begin2, begin3>\n            , mpl::vector0_c<size_t>\n            , mpl::push_back<mpl::_1, mpl::_2>\n            >::type controvariant_right;\n\n        typedef typename mpl::fold<\n              mpl::iterator_range<begin3, begin4>\n            , mpl::vector0_c<size_t>\n            , mpl::push_back<mpl::_1, mpl::_2>\n            >::type covariant_left;\n\n        typedef typename mpl::fold<\n              mpl::iterator_range<begin4, begin5>\n            , mpl::vector0_c<size_t>\n            , mpl::push_back<mpl::_1, mpl::_2>\n            >::type covariant_right;\n\n        /* append the splittend multi-index */\n        typedef typename mpl::fold<\n              covariant_left\n            , controvariant_left\n            , mpl::push_back<mpl::_1, mpl::_2>\n            >::type left_ilist;\n\n        typedef typename mpl::fold<\n              covariant_right\n            , controvariant_right\n            , mpl::push_back<mpl::_1, mpl::_2>\n            >::type right_ilist;\n\n        return (m_left.template at<left_ilist>()) *\n            (m_right.template at<right_ilist>());\n      }\n\n    protected:\n      /* if the operand is temporary we save a copy, otherwise a reference */\n      typedef typename LEFT::is_temporary left_operand_is_temporary;\n      typedef typename ::boost::mpl::if_<\n            left_operand_is_temporary\n          , left_operand_type const\n          , left_operand_type const &\n          >::type const_left_operand_type;\n\n      /* if the operand is temporary we save a copy, otherwise a reference */\n      typedef typename RIGHT::is_temporary right_operand_is_temporary;\n      typedef typename ::boost::mpl::if_<\n            right_operand_is_temporary\n          , right_operand_type const\n          , right_operand_type const &\n          >::type const_right_operand_type;\n\n      /* members */\n      const_left_operand_type m_left;\n      const_right_operand_type m_right;\n    };\n\n  }\n}\n\n#endif /* AMA_TENSOR_DETAIL_TENSOR_OUTER_HPP */\n", "meta": {"hexsha": "c2ea500f37bd476a634ce845d45bb46be48aca23", "size": 6707, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/detail/tensor_outer.hpp", "max_stars_repo_name": "mattiapenati/amanita", "max_stars_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ama/tensor/detail/tensor_outer.hpp", "max_issues_repo_name": "mattiapenati/amanita", "max_issues_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ama/tensor/detail/tensor_outer.hpp", "max_forks_repo_name": "mattiapenati/amanita", "max_forks_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.650273224, "max_line_length": 95, "alphanum_fraction": 0.6536454451, "num_tokens": 1447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118493816807, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2439927660879728}}
{"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    SelectivelyDampedLeastSquaresSolver.cpp\n *\n * \\author  Stefan Scherzinger <scherzin@fzi.de>\n * \\date    2020/03/27\n *\n */\n//-----------------------------------------------------------------------------\n\n// this package\n#include <cartesian_controller_base/SelectivelyDampedLeastSquaresSolver.h>\n\n// Pluginlib\n#include <pluginlib/class_list_macros.h>\n\n// other\n#include <boost/algorithm/clamp.hpp>\n\n/**\n * \\class cartesian_controller_base::SelectivelyDampedLeastSquaresSolver \n *\n * Users may explicitly specify this solver with \\a \"selectively_damped_least_squares\" as \\a\n * ik_solver in their controllers.yaml configuration file for each controller:\n *\n * \\code{.yaml}\n * <name_of_your_controller>:\n *     type: \"<type_of_your_controller>\"\n *     ik_solver: \"selectively_damped_least_squares\"\n *     ...\n * \\endcode\n *\n */\nPLUGINLIB_EXPORT_CLASS(cartesian_controller_base::SelectivelyDampedLeastSquaresSolver, cartesian_controller_base::IKSolver)\n\n\n\n\n\nnamespace cartesian_controller_base{\n\n  SelectivelyDampedLeastSquaresSolver::SelectivelyDampedLeastSquaresSolver()\n  {\n  }\n\n  SelectivelyDampedLeastSquaresSolver::~SelectivelyDampedLeastSquaresSolver(){}\n\n  trajectory_msgs::JointTrajectoryPoint SelectivelyDampedLeastSquaresSolver::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    Eigen::JacobiSVD<Eigen::Matrix<double, 6, Eigen::Dynamic> > JSVD(\n      m_jnt_jacobian.data, Eigen::ComputeFullU | Eigen::ComputeFullV);\n    Eigen::Matrix<double, 6, 6> U = JSVD.matrixU();\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> V = JSVD.matrixV();\n    Eigen::Matrix<double, Eigen::Dynamic, 1> s = JSVD.singularValues();\n\n    // Default recommendation by Buss and Kim.\n    const double gamma_max = 3.141592653 / 4;\n\n    Eigen::Matrix<double, Eigen::Dynamic, 1> sum_phi =\n      Eigen::Matrix<double, Eigen::Dynamic, 1>::Zero(m_number_joints);\n\n    // Compute each joint velocity with the SDLS method.  This implements the\n    // algorithm as described in the paper (but for only one end-effector).\n    // Also see Buss' own implementation:\n    // https://www.math.ucsd.edu/~sbuss/ResearchWeb/ikmethods/index.html\n\n    for (int i = 0; i < m_number_joints; ++i)\n    {\n      double alpha = U.col(i).transpose() * net_force;\n\n      double N = U.col(i).head(3).norm();\n      double M = 0;\n      for (int j = 0; j < m_number_joints; ++j)\n      {\n        double rho = m_jnt_jacobian.data.col(j).head(3).norm();\n        M += std::abs(V.col(i)[j]) * rho;\n      }\n      M *= 1.0 / s[i];\n\n      double gamma = std::min(1.0, N / M) * gamma_max;\n\n      Eigen::Matrix<double, Eigen::Dynamic, 1> phi = clampMaxAbs(1.0 / s[i] * alpha * V.col(i), gamma);\n      sum_phi += phi;\n    }\n\n    m_current_velocities.data = clampMaxAbs(sum_phi, gamma_max);\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 SelectivelyDampedLeastSquaresSolver::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    return true;\n  }\n\n  Eigen::Matrix<double, Eigen::Dynamic, 1> SelectivelyDampedLeastSquaresSolver::clampMaxAbs(\n    const Eigen::Matrix<double, Eigen::Dynamic, 1>& w, double d)\n  {\n    if (w.cwiseAbs().maxCoeff() <= d)\n    {\n      return w;\n    }\n    else\n    {\n      return d * w / w.cwiseAbs().maxCoeff();\n    }\n  }\n\n} // namespace\n", "meta": {"hexsha": "7394e7346c0a607ff5d8de32a0432ee387b19243", "size": 6320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cartesian_controller_base/src/SelectivelyDampedLeastSquaresSolver.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/SelectivelyDampedLeastSquaresSolver.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/SelectivelyDampedLeastSquaresSolver.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": 36.9590643275, "max_line_length": 123, "alphanum_fraction": 0.6693037975, "num_tokens": 1478, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2439741813327488}}
{"text": "#include \"BootstrapRunner.h\"\n#include <vector>\n#include <boost/timer.hpp>\nusing namespace std;\n\nBootstrapRunner::BootstrapRunner(BoostrapConfig* bootstrapConfig, CftConfig cftConfig)\n{\n    this->bootstrapConfig = bootstrapConfig;\n    this->cftData = new CftData(cftConfig);\n    this->correlatorSet = new CorrelatorSet(cftData, bootstrapConfig->NumberOfScalarsToBootstrap);\n}\n\nBootstrapRunner::~BootstrapRunner()\n{\n    if (this->cftData != 0) {\n        delete cftData;\n    }\n\n    if (this->correlatorSet != 0) {\n        delete this->correlatorSet;\n    }\n}\n\nfloat_type BootstrapRunner::ConstraintCost(CftData* cftData)\n{\n    float_type ret = .0;\n    float_type lastDim = .0, dim;\n    int lastSpin = -1;\n\n    for (uint i = 1; i <= cftData->MaxPrimaryId(); i++) {\n        dim = cftData->GetPrimaryDim(i);\n        if (cftData->GetPrimarySpin(i) != lastSpin) {\n            lastSpin = cftData->GetPrimarySpin(i);\n            if (lastSpin == 0) {\n                if (dim < cftData->D / 2.0 - 1) ret += (cftData->D / 2.0 - 1 - dim);\n            } else {\n                if (dim < lastSpin + cftData->D - 2) ret += (lastSpin + cftData->D - 2 - dim);\n            }\n        } else if (dim < lastDim) {\n            ret += (lastDim - dim);\n        }\n\n        lastDim = dim;\n    }\n\n    return ret * bootstrapConfig->ConstraintFactor;\n}\n\nvoid BootstrapRunner::ConstraintCostDerivative(CftData* cftData, vector<int>& ops, vector<float_type>& opsDerivatives)\n{\n    assert(ops.size() == opsDerivatives.size());\n\n    float_type dim, lastDim, nextDim;\n\n    for (uint i = 0; i < ops.size(); i++) {\n        int l = cftData->GetPrimarySpin(ops[i]);\n        dim = cftData->GetPrimaryDim(ops[i]);\n\n        if (ops[i] > 1 && cftData->GetPrimarySpin(ops[i] - 1) == l) {\n            lastDim = cftData->GetPrimaryDim(ops[i] - 1);\n            if (dim < lastDim) {\n                opsDerivatives[i] -= bootstrapConfig->ConstraintFactor;\n            }\n        }\n\n        if (ops[i] < cftData->MaxPrimaryId() && cftData->GetPrimarySpin(ops[i] + 1) == l) {\n            nextDim = cftData->GetPrimaryDim(ops[i] + 1);\n            if (dim > nextDim) {\n                opsDerivatives[i] += bootstrapConfig->ConstraintFactor;\n            }\n        }\n\n        if (ops[i] == 1 || cftData->GetPrimarySpin(ops[i] - 1) != l) {\n            if (l == 0 && dim <= cftData->D / 2.0 - 1) {\n                opsDerivatives[i] -= bootstrapConfig->ConstraintFactor;\n            }\n\n            if (l > 0 && dim <= cftData->D + l - 2.0) {\n                opsDerivatives[i] -= bootstrapConfig->ConstraintFactor;\n            }\n        }\n    }\n}\n\nvoid BootstrapRunner::Run()\n{\n    vector<OpeCoefficientKey> coefs;\n    vector<int> ops;\n\n    for (uint op = 1; op <= cftData->MaxPrimaryId(); op++) {\n        if (op != cftData->StressTensorId) {\n            ops.push_back(op);\n        }\n    }\n\n    for (uint op1 = 1; op1 <= bootstrapConfig->NumberOfScalarsToBootstrap; op1++) {\n        for (uint op2 = op1; op2 <= bootstrapConfig->NumberOfScalarsToBootstrap; op2++) {\n            for (uint op3 = op2; op3 <= cftData->MaxPrimaryId(); op3++) {\n                if (op3 != cftData->StressTensorId) {\n                    coefs.push_back(OpeCoefficientKey(op1, op2, op3));\n                }\n            }\n        }\n    }\n\n    vector<cpx_t> zs;\n    zs.reserve(bootstrapConfig->SamplesEachStep);\n    for (uint i = 0; i < bootstrapConfig->SamplesEachStep; i++) {\n        float_type dr = random(0.0, 0.2);\n        float_type theta = random(0.0, 2 * acos(-1.0));\n        zs.push_back(cpx_t(dr * cos(theta), dr * sin(theta)) + 0.5);\n    }\n\n    vector<float_type> opsDerivatives(ops.size(), .0);\n    vector<float_type> opsDerivativeTot(ops.size(), .0);\n    vector<float_type> coefsDerivatives(coefs.size(), .0);\n    vector<float_type> coefsDerivativeTot(coefs.size(), .0);\n\n    float_type lastCost = std::numeric_limits<float_type>::max();\n    vector<int> scalarIds;\n    for (uint i = 1; i <= cftData->MaxScalarId(); i++) scalarIds.push_back(i);\n\n    boost::timer stopwatch;\n\n    while (true) {\n        std::cout << \"Time elapsed: \" << stopwatch.elapsed() << \" seconds.\" << endl;\n        cftData->Output(scalarIds);\n\n        opsDerivativeTot.resize(ops.size(), .0);\n        coefsDerivativeTot.resize(coefs.size(), .0);\n\n        float_type cost = .0;\n\n        for (uint i = 0; i < zs.size(); i++) {\n            this->correlatorSet->CostDerivatives(zs[i], ops, coefs, opsDerivatives, coefsDerivatives);\n            cost += this->correlatorSet->Cost(zs[i]);\n\n            for (uint j = 0; j < opsDerivatives.size(); j++) {\n                opsDerivativeTot[j] += opsDerivatives[j];\n            }\n\n            for (uint j = 0; j < coefsDerivatives.size(); j++) {\n                coefsDerivativeTot[j] += coefsDerivatives[j];\n            }\n        }\n\n        cost /= zs.size();\n        std::cout << \"pure cost = \" << cost << \"\\t\";\n        cost += ConstraintCost(cftData);\n        std::cout << \"total cost = \" << cost << std::endl;\n        \n        if (cost < bootstrapConfig->Accuracy) break;\n\n        float_type gradNorm = .0;\n        for (uint j = 0; j < coefsDerivativeTot.size(); j++) {\n            coefsDerivativeTot[j] /= zs.size();\n            gradNorm += coefsDerivativeTot[j] * coefsDerivativeTot[j];\n        }\n\n        std::cout << \"Coefs Derivative: \" << coefsDerivativeTot << std::endl;\n\n        for (uint j = 0; j < opsDerivativeTot.size(); j++) {\n            opsDerivativeTot[j] /= zs.size();\n        }\n\n        std::cout << \"Ops Derivative: \" << opsDerivativeTot << std::endl;\n\n        ConstraintCostDerivative(cftData, ops, opsDerivativeTot);\n\n        std::cout << \"Ops Derivative with constraints: \" << opsDerivativeTot << std::endl;\n\n        for (uint j = 0; j < opsDerivativeTot.size(); j++) {\n            gradNorm += opsDerivativeTot[j] * opsDerivativeTot[j];\n        }\n\n        float_type factor = gradNorm / ((ops.size() + coefs.size()));\n        factor = sqrt(factor);\n\n        for (uint j = 0; j < coefsDerivativeTot.size(); j++) {\n            coefsDerivativeTot[j] /= factor;\n        }\n\n        for (uint j = 0; j < opsDerivativeTot.size(); j++) {\n            opsDerivativeTot[j] /= factor;\n        }\n\n        std::cout << \"Coefs Derivative normalized: \" << coefsDerivativeTot << std::endl;\n        std::cout << \"Ops Derivative normalized: \" << opsDerivativeTot << std::endl;\n\n        for (uint j = 0; j < opsDerivativeTot.size(); j++) {\n            float_type dim = cftData->GetPrimaryDim(ops[j]);\n            cftData->SetPrimaryDim(ops[j], dim - opsDerivativeTot[j] * bootstrapConfig->Step);\n        }\n\n        for (uint j = 0; j < coefsDerivativeTot.size(); j++) {\n            float_type coef = cftData->GetOpeCoefficient(coefs[j]);\n            cftData->SetOpeCoefficient(coefs[j], coef - coefsDerivativeTot[j] * bootstrapConfig->Step);\n        }\n\n        this->correlatorSet->UpdateCftData(cftData);\n        lastCost = cost;\n    }\n}\n\n\n", "meta": {"hexsha": "667247bb1ee2a35171e5d9ac89da415cb24d5d5d", "size": 6879, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BootstrapRunner.cpp", "max_stars_repo_name": "gaolichen/cftbtsp", "max_stars_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BootstrapRunner.cpp", "max_issues_repo_name": "gaolichen/cftbtsp", "max_issues_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BootstrapRunner.cpp", "max_forks_repo_name": "gaolichen/cftbtsp", "max_forks_repo_head_hexsha": "e764b6ca339d6d68a5c6b6acd9f58ef64c628d47", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3932038835, "max_line_length": 118, "alphanum_fraction": 0.5596743713, "num_tokens": 1948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2439741813327488}}
{"text": "#include \"../is_valid_char.hxx\"\n#include \"../parse_vector.hxx\"\n#include \"../parse_number.hxx\"\n#include \"../../../../Damped_Rational.hxx\"\n\n#include <boost/algorithm/string.hpp>\n\n#include <algorithm>\n#include <iterator>\n#include <string>\n\nconst char *parse_damped_rational(const char *begin, const char *end,\n                                  Damped_Rational &damped_rational)\n{\n  const std::string damped_literal(\"DampedRational[\");\n\n  // Parse constant numbers\n  for(auto current = begin; current != end; ++current)\n    {\n      if(*current == damped_literal.front())\n        {\n          break;\n        }\n      if(is_valid_char(*current))\n        {\n          damped_rational.base = 1;\n          auto comma(std::find(current, end, ','));\n          if(comma == end)\n            {\n              throw std::runtime_error(\n                \"Missing a comma when parsing a constant as a DampedRational. \"\n                \" The parsed string is\\n\\t'\"\n                + std::string(current, end) + \"'\");\n            }\n          damped_rational.constant = Boost_Float(parse_number(current, comma));\n          return comma;\n        }\n    }\n\n  auto damped_start(\n    std::search(begin, end, damped_literal.begin(), damped_literal.end()));\n  if(damped_start == end)\n    {\n      throw std::runtime_error(\"Could not find '\" + damped_literal + \"'\");\n    }\n\n  auto comma(std::find(damped_start, end, ','));\n  if(comma == end)\n    {\n      throw std::runtime_error(\"Missing comma after DampedRational.constant\");\n    }\n  auto constant_start(std::next(damped_start, damped_literal.size()));\n  damped_rational.constant = Boost_Float(parse_number(constant_start, comma));\n\n  auto start_poles(std::next(comma));\n  auto end_poles(parse_vector(start_poles, end, damped_rational.poles));\n\n  comma = std::find(end_poles, end, ',');\n  if(comma == end)\n    {\n      throw std::runtime_error(\"Missing comma after DampedRational.poles\");\n    }\n\n  auto start_base(std::next(comma));\n  comma = std::find(start_base, end, ',');\n  if(comma == end)\n    {\n      throw std::runtime_error(\"Missing comma after DampedRational.base\");\n    }\n  damped_rational.base = Boost_Float(parse_number(start_base, comma));\n\n  auto start_variable(std::next(comma));\n  const auto close_bracket(std::find(start_variable, end, ']'));\n  if(close_bracket == end)\n    {\n      throw std::runtime_error(\"Missing ']' at end of DampedRational\");\n    }\n\n  return std::next(close_bracket);\n}\n", "meta": {"hexsha": "69ccf86aa2d6aa2bfb90cad62b7acdafd4ab357e", "size": 2425, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/sdp_read/read_input/read_mathematica/parse_SDP/parse_matrix/parse_damped_rational.cxx", "max_stars_repo_name": "ChrisPattison/sdpb", "max_stars_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-02-10T15:45:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T07:45:01.000Z", "max_issues_repo_path": "src/sdp_read/read_input/read_mathematica/parse_SDP/parse_matrix/parse_damped_rational.cxx", "max_issues_repo_name": "ChrisPattison/sdpb", "max_issues_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58.0, "max_issues_repo_issues_event_min_datetime": "2015-02-27T10:03:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-10T04:21:42.000Z", "max_forks_repo_path": "src/sdp_read/read_input/read_mathematica/parse_SDP/parse_matrix/parse_damped_rational.cxx", "max_forks_repo_name": "ChrisPattison/sdpb", "max_forks_repo_head_hexsha": "4668f72c935e7feba705dd8247d9aacb23185f1c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 38.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T11:11:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T20:59:42.000Z", "avg_line_length": 29.9382716049, "max_line_length": 79, "alphanum_fraction": 0.6239175258, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24395876097908092}}
{"text": "#include <fenv.h>\n#include <algorithm>\n#include <boost/python/numpy.hpp>\n#include <iomanip>\n#include <iostream>\n#include <list>\n#include <memory>\n#include <random>\n#include <stdexcept>\n#include <vector>\n\nfloat gen_gaussian() {\n    static std::random_device r;\n    static std::default_random_engine generator(r());\n    static std::normal_distribution<float> distribution;\n    return distribution(generator);\n}\n\ntemplate <typename T>\nint sgn(T val) {\n    return (T(0) < val) - (val < T(0));\n}\n\nenum class Optimizer { Sgd, Sgdm, PowerSign };\n\nstruct Dims {\n    int w;\n    int h;\n    int c;\n\n    int sz() const { return w * h * c; }\n};\n\nstruct Settings {\n    float lr;\n    int batch_size;\n    int epochs;\n    float l2;\n    float grad_max;\n    float lr_decay;\n    Optimizer optimizer;\n\n    Settings()\n        : lr(0.1),\n          batch_size(8),\n          epochs(10),\n          l2(0.0001),\n          grad_max(5),\n          lr_decay(1),\n          optimizer(Optimizer::Sgdm) {}\n};\n\ntemplate <class T>\nclass Pool {\n   public:\n    class PoolAlloc {\n        std::unique_ptr<T> x_;\n        int sz_;\n        int owners_;\n\n       public:\n        PoolAlloc(std::unique_ptr<T>&& x, int sz)\n            : x_(std::move(x)), sz_(sz), owners_(0) {}\n\n        bool is_free() const { return owners_ == 0; }\n\n        void add_owner() { ++owners_; }\n        void remove_owner() {\n#if _GLIBCXX_DEBUG\n            if (owners_ == 0)\n                throw std::runtime_error(\n                    \"trying to deown something that was said to have zero \"\n                    \"wner\");\n#endif\n            --owners_;\n        }\n\n        auto* get() { return x_.get(); }\n        const auto* get() const { return x_.get(); }\n\n        int sz() const { return sz_; }\n    };\n\n    class Recyclable {\n       public:\n        Recyclable(PoolAlloc* alloc) : alloc_(alloc) { alloc_->add_owner(); }\n\n        Recyclable(Recyclable&& o) {\n            alloc_ = o.alloc_;\n            o.alloc_ = nullptr;\n        }\n\n        Recyclable() : alloc_(nullptr) {}\n\n        Recyclable(const Recyclable& o) {\n            alloc_ = o.alloc_;\n            if (alloc_) {\n                alloc_->add_owner();\n            }\n        }\n\n        ~Recyclable() {\n            if (alloc_) {\n                alloc_->remove_owner();\n            }\n        }\n\n        Recyclable& operator=(Recyclable&& o) {\n            if (alloc_) {\n                alloc_->remove_owner();\n            }\n            alloc_ = o.alloc_;\n            o.alloc_ = nullptr;\n            return *this;\n        }\n\n        Recyclable& operator=(const Recyclable& o) {\n            if (alloc_) {\n                alloc_->remove_owner();\n            }\n            alloc_ = o.alloc_;\n            if (alloc_) {\n                alloc_->add_owner();\n            }\n            return *this;\n        }\n\n        auto& operator*() { return *alloc_->get(); }\n        const auto& operator*() const { return *alloc_->get(); }\n\n        auto& operator-> () { return alloc_->get().operator->(); }\n        const auto& operator-> () const { return alloc_->get().operator->(); }\n\n        auto& operator[](int i) { return alloc_->get()[i]; }\n        const auto& operator[](int i) const { return alloc_->get()[i]; }\n\n        int sz() const { return alloc_->sz_; }\n\n       private:\n        PoolAlloc* alloc_;\n    };\n\n    Recyclable alloc(int sz) {\n        auto found = std::find_if(pool_.begin(), pool_.end(), [=](auto& r) {\n            return r.sz() == sz && r.is_free();\n        });\n\n        if (found != pool_.end()) {\n            PoolAlloc* p = &*found;\n            return Recyclable(p);\n        }\n\n        pool_.emplace_back(std::make_unique<T>(sz), sz);\n        return Recyclable(&pool_.back());\n    }\n\n   private:\n    std::list<PoolAlloc> pool_;\n};\n\nstatic Pool<float[]> float_pool_;\n\nclass Volume {\n   public:\n    Volume(int w, int h, int c)\n        : w_(w), h_(h), c_(c), sz_(h * w * c), res_(float_pool_.alloc(sz_)) {}\n    Volume(const Dims& sz) : Volume(sz.w, sz.h, sz.c) {}\n\n    Volume() = default;\n    Volume(Volume&& o) = default;\n\n    Volume from_shape() const { return Volume(w_, h_, c_); }\n    void zero() {\n        for (int i = 0; i < sz_; ++i) {\n            res_[i] = 0;\n        }\n    }\n\n    Volume& operator=(Volume&& o) = default;\n\n    float& operator[](int i) {\n#if _GLIBCXX_DEBUG\n        if (i >= sz_) {\n            throw std::runtime_error(\"volume bound checks fail\");\n        }\n#endif\n        return res_[i];\n    }\n    float operator[](int i) const {\n#if _GLIBCXX_DEBUG\n        if (i >= sz_) {\n            throw std::runtime_error(\"volume bound checks fail\");\n        }\n#endif\n        return res_[i];\n    }\n\n    int w() const { return w_; }\n    int h() const { return h_; }\n    int c() const { return c_; }\n    int sz() const { return sz_; }\n\n    int row_idx(int i) const { return i * w_; };\n    int cha_idx(int i) const { return i * w_ * h_; }\n\n    void show() const {\n        std::cout << \"[\";\n        for (int c = 0; c < c_; ++c) {\n            std::cout << \"[\\n\";\n            for (int h = 0; h < h_; ++h) {\n                std::cout << \"  [\";\n                std::cout << res_[h_ * c * w_ + h * w_];\n                for (int w = 1; w < w_; ++w) {\n                    std::cout << \", \" << res_[w + w_ * h + w_ * h_ * c];\n                }\n                std::cout << \"],\\n\";\n            }\n            std::cout << \"]\";\n        }\n        std::cout << \"]\\n\";\n    }\n\n    void share_with(Volume& v) const {\n        v.res_ = res_;\n        v.w_ = w_;\n        v.h_ = h_;\n        v.c_ = c_;\n        v.sz_ = sz_;\n    }\n\n    void gaussian() {\n        for (int i = 0; i < sz_; ++i) {\n            res_[i] = gen_gaussian();\n        }\n    }\n\n    std::pair<float, float> mean_std() const {\n        float m = 0;\n        for (int i = 0; i < sz_; ++i) {\n            m += res_[i];\n        }\n        m = m / sz_;\n\n        float s = 0;\n        for (int i = 0; i < sz_; ++i) {\n            s += (res_[i] - m) * (res_[i] - m);\n        }\n        s = std::sqrt(s / (sz_ - 1));\n        return std::make_pair(m, s);\n    }\n\n    float min() const {\n        float m = res_[0];\n        for (int i = 1; i < sz_; ++i) {\n            m = m < res_[i] ? m : res_[i];\n        }\n        return m;\n    }\n\n    float max() const {\n        float m = res_[0];\n        for (int i = 1; i < sz_; ++i) {\n            m = m > res_[i] ? m : res_[i];\n        }\n        return m;\n    }\n\n    int nonzero() const {\n        int count = 0;\n        for (int i = 1; i < sz_; ++i) {\n            count += res_[i] == 0 ? 0 : 1;\n        }\n        return count;\n    }\n\n    float norm() const {\n        float len = 0;\n        for (int i = 0; i < sz_; ++i) {\n            len += res_[i] * res_[i];\n        }\n        len = std::sqrt(len + 1e-6);\n        return len;\n    }\n\n   private:\n    int w_;\n    int h_;\n    int c_;\n    int sz_;\n    Pool<float[]>::Recyclable res_;\n};\n\nclass Param {\n   public:\n    Param() = default;\n    Param(Param&&) = default;\n    Param(Dims d) : Param(d.w, d.h, d.c) {}\n    Param(int w, int h, int c) : val_(w, h, c), grad_(w, h, c), mem_(w, h, c) {\n        val_.gaussian();\n        grad_.zero();\n        mem_.zero();\n    }\n\n    float& operator[](int i) { return val_[i]; }\n    float operator[](int i) const { return val_[i]; }\n\n    void reset_grad() { grad_.zero(); }\n    Volume& grad() { return grad_; }\n    const Volume& grad() const { return grad_; }\n\n    int sz() const { return val_.sz(); }\n    Volume& vol() { return val_; }\n    const Volume& vol() const { return val_; }\n\n    Param& operator=(Param&& o) = default;\n\n    void reinit(Volume& v) {\n        v.share_with(val_);\n        grad_ = v.from_shape();\n        grad_.zero();\n        mem_ = v.from_shape();\n        mem_.zero();\n    }\n\n    int w() const { return val_.w(); }\n    int h() const { return val_.h(); }\n    int c() const { return val_.c(); }\n    int cha_idx(int c) const { return val_.cha_idx(c); }\n\n    void descend(const Settings& s) {\n        switch (s.optimizer) {\n            case Optimizer::Sgdm:\n                sgdm(s);\n                break;\n            case Optimizer::Sgd:\n                sgd(s);\n                break;\n            case Optimizer::PowerSign:\n                power_sign(s);\n                break;\n        }\n    }\n\n   private:\n    void sgd(const Settings& s) {\n        float len = grad_.norm();\n        for (int i = 0; i < val_.sz(); ++i) {\n            val_[i] = val_[i] - s.lr * grad_[i] - s.l2 * 2 * val_[i];\n        }\n        grad_.zero();\n    }\n\n    void sgdm(const Settings& s) {\n        float len = grad_.norm();\n        for (int i = 0; i < val_.sz(); ++i) {\n            grad_[i] =\n                len > s.grad_max ? grad_[i] / len * s.grad_max : grad_[i];\n            mem_[i] = 0.9 * mem_[i] + 0.1 * grad_[i];\n            val_[i] = val_[i] - s.lr * mem_[i] - s.l2 * 2 * val_[i];\n        }\n        grad_.zero();\n    }\n\n    void power_sign(const Settings& s) {\n        float len = grad_.norm();\n        for (int i = 0; i < val_.sz(); ++i) {\n            grad_[i] =\n                len > s.grad_max ? grad_[i] / len * s.grad_max : grad_[i];\n            mem_[i] = 0.9 * mem_[i] + 0.1 * grad_[i];\n            val_[i] -= s.lr * exp(sgn(grad_[i]) * sgn(mem_[i])) * grad_[i];\n        }\n        grad_.zero();\n    }\n\n    Volume val_;\n    Volume grad_;\n    Volume mem_;\n};\n\nclass Layer {\n   public:\n    virtual Volume& forward(const Volume&) = 0;\n    virtual Volume backward(const Volume& grad) = 0;\n    virtual void update(const Settings&) {}\n    virtual Dims out_shape() const = 0;\n    virtual void set_train_mode(bool train) {}\n};\n\nclass Tanh : public Layer {\n   public:\n    Tanh(Dims d) : out_shape_(d) {}\n\n    virtual Volume& forward(const Volume& input) {\n        res_ = input.from_shape();\n        for (int i = 0; i < res_.sz(); ++i) {\n            res_[i] = std::tanh(input[i]);\n        }\n        return res_;\n    }\n    virtual Volume backward(const Volume& pgrad) {\n        Volume grad = pgrad.from_shape();\n        for (int i = 0; i < res_.sz(); ++i) {\n            grad[i] = pgrad[i] * (1 - res_[i] * res_[i]);\n        }\n        return grad;\n    }\n    virtual Dims out_shape() const override { return out_shape_; }\n\n   private:\n    Volume res_;\n    Dims out_shape_;\n};\n\nclass Verbose : public Layer {\n   public:\n    Verbose(Dims d, std::string name)\n        : out_shape_(d), name_(name), train_(false) {}\n\n    virtual Volume& forward(const Volume& x) override {\n        if (train_) {\n            fwd_.emplace_back();\n            x.share_with(fwd_.back());\n            return fwd_.back();\n        } else {\n            x.share_with(test_thru_);\n            return test_thru_;\n        }\n    }\n\n    virtual Volume backward(const Volume& x) override {\n        bwd_.emplace_back();\n        x.share_with(bwd_.back());\n        Volume v;\n        bwd_.back().share_with(v);\n        return v;\n    }\n\n    virtual void update(const Settings&) override {\n        float statsfwd[] = {0, 0, 0, 0, 0, 0};\n        for (auto& v : fwd_) {\n            auto local = v.mean_std();\n            statsfwd[0] += local.first;\n            statsfwd[1] += local.second;\n            statsfwd[2] += v.max();\n            statsfwd[3] += v.min();\n            statsfwd[4] += float(v.nonzero()) / v.sz();\n            statsfwd[5] += v.norm();\n        }\n        float statsbwd[] = {0, 0, 0, 0, 0, 0};\n        for (auto& v : bwd_) {\n            auto local = v.mean_std();\n            statsbwd[0] += local.first;\n            statsbwd[1] += local.second;\n            statsbwd[2] += v.max();\n            statsbwd[3] += v.min();\n            statsbwd[4] += float(v.nonzero()) / v.sz();\n            statsbwd[5] += v.norm();\n        }\n\n        std::cout << \"               Statistics for \" << name_ << \":\\n\";\n        std::cout << \"  Batch size: \" << fwd_.size() << \"\\n\";\n        std::cout << \"  Forward pass:                       Backward Pass:\\n\";\n        std::cout << \"    Shape: (\" << std::setw(3) << fwd_[0].w() << \", \"\n                  << std::setw(3) << fwd_[0].h() << \", \" << std::setw(3)\n                  << fwd_[0].c() << \")            \"\n                  << \"  Shape: (\" << std::setw(3) << bwd_[0].w() << \", \"\n                  << std::setw(3) << bwd_[0].h() << \", \" << std::setw(3)\n                  << bwd_[0].c() << \")\\n\";\n\n        std::cout << \"    Mean:     \" << std::setw(8)\n                  << statsfwd[0] / fwd_.size()\n                  << \"                  Mean:     \" << statsbwd[0] / bwd_.size()\n                  << \"\\n\";\n        std::cout << \"    Std:      \" << std::setw(8)\n                  << statsfwd[1] / fwd_.size()\n                  << \"                  Std:      \" << statsbwd[1] / bwd_.size()\n                  << \"\\n\";\n        std::cout << \"    Max:      \" << std::setw(8)\n                  << statsfwd[2] / fwd_.size()\n                  << \"                  Max:      \" << statsbwd[2] / bwd_.size()\n                  << \"\\n\";\n        std::cout << \"    Min:      \" << std::setw(8)\n                  << statsfwd[3] / fwd_.size()\n                  << \"                  Min:      \" << statsbwd[3] / bwd_.size()\n                  << \"\\n\";\n        std::cout << \"    Non-Zero: \" << std::setw(8)\n                  << statsfwd[4] / fwd_.size()\n                  << \"                  Non-Zero: \" << statsbwd[4] / fwd_.size()\n                  << \"\\n\";\n        std::cout << \"    Norm:     \" << statsfwd[5] / fwd_.size()\n                  << \"                  Norm: \" << statsbwd[5] / bwd_.size()\n                  << \"\\n\";\n\n        fwd_.clear();\n        bwd_.clear();\n    }\n\n    virtual Dims out_shape() const override { return out_shape_; }\n    virtual void set_train_mode(bool b) override { train_ = b; }\n\n   private:\n    std::vector<Volume> fwd_;\n    std::vector<Volume> bwd_;\n    Dims out_shape_;\n    std::string name_;\n    Volume test_thru_;\n    bool train_;\n};\n\nclass BatchNorm : public Layer {\n   public:\n    BatchNorm(Dims d)\n        : mu_(d), sigma_(d), out_shape_(d), beta_(d), gamma_(d), train_(false) {\n        beta_.vol().zero();\n        mu_.zero();\n        for (int i = 0; i < gamma_.sz(); ++i) {\n            gamma_.vol()[i] = 1;\n            sigma_[i] = 1;\n        }\n    }\n\n    virtual Volume& forward(const Volume& input) {\n        if (train_) {\n            memory_.emplace_back();\n            input.share_with(memory_.back());\n        }\n        scaled_ = input.from_shape();\n        centered_ = input.from_shape();\n        for (int i = 0; i < scaled_.sz(); ++i) {\n            centered_[i] = (input[i] - mu_[i]) / sigma_[i];\n            scaled_[i] = gamma_[i] * centered_[i] + beta_[i];\n        }\n        return scaled_;\n    }\n\n    virtual Volume backward(const Volume& pgrad) {\n        Volume out = pgrad.from_shape();\n        for (int i = 0; i < out.sz(); ++i) {\n            gamma_.grad()[i] += pgrad[i] * centered_[i];\n            beta_.grad()[i] += pgrad[i];\n            out[i] = pgrad[i] * gamma_[i] / sigma_[i];\n        }\n        return out;\n    }\n\n    virtual void update(const Settings& s) {\n        beta_.descend(s);\n        gamma_.descend(s);\n        Volume avg = mu_.from_shape();\n        avg.zero();\n        // compute average\n        for (auto& m : memory_) {\n            for (int i = 0; i < m.sz(); ++i) {\n                avg[i] += m[i];\n            }\n        }\n        for (int i = 0; i < mu_.sz(); ++i) {\n            avg[i] /= memory_.size();\n        }\n\n        // compute std\n        Volume std = mu_.from_shape();\n        std.zero();\n        for (auto& m : memory_) {\n            for (int i = 0; i < m.sz(); ++i) {\n                float x = m[i] - avg[i];\n                std[i] += x * x;\n            }\n        }\n        for (int i = 0; i < mu_.sz(); ++i) {\n            std[i] /= memory_.size() - 1;\n        }\n\n        // update\n        for (int i = 0; i < mu_.sz(); ++i) {\n            mu_[i] = 0.9 * mu_[i] + 0.1 * avg[i];\n            sigma_[i] = 0.9 * sigma_[i] + 0.1 * std[i];\n        }\n\n        memory_.clear();\n    }\n\n    virtual Dims out_shape() const { return out_shape_; }\n    virtual void set_train_mode(bool train) override { train_ = train; }\n\n   private:\n    Volume mu_;\n    Volume sigma_;\n    Param beta_;\n    Param gamma_;\n    std::vector<Volume> memory_;\n    Dims out_shape_;\n    Volume centered_;\n    Volume scaled_;\n    bool train_;\n};\n\nclass Input : public Layer {\n   public:\n    Input(Dims d) : out_shape_(d) {}\n    virtual Volume& forward(const Volume& x) override {\n        x.share_with(out_);\n        return out_;\n    }\n    virtual Volume backward(const Volume& grad) override {\n        Volume out;\n        grad.share_with(out);\n        return out;\n    }\n    virtual void update(const Settings&) {}\n    virtual Dims out_shape() const { return out_shape_; }\n    virtual void set_train_mode(bool train) override {}\n\n   private:\n    Dims out_shape_;\n    Volume out_;\n};\n\nclass Relu : public Layer {\n   public:\n    Relu() = default;\n    Relu(Dims d) : out_shape_(d){};\n    virtual Volume& forward(const Volume& input) override {\n        auto res = input.from_shape();\n        for (int i = 0; i < input.sz(); ++i) {\n            float x = input[i];\n            res[i] = x < 0 ? 0 : x;\n        }\n        res_ = std::move(res);\n        return res_;\n    }\n\n    virtual Volume backward(const Volume& pgrad) override {\n        Volume grad = pgrad.from_shape();\n        for (int i = 0; i < grad.sz(); ++i) {\n            grad[i] = res_[i] > 0 ? pgrad[i] : 0;\n        }\n        return std::move(grad);\n    }\n\n    virtual Dims out_shape() const { return out_shape_; }\n\n   private:\n    Volume res_;\n    Dims out_shape_;\n};\n\nclass FullyConn : public Layer {\n   public:\n    FullyConn() = default;\n    FullyConn(Dims in_sz, int c) : w_(in_sz.sz(), c, 1), b_(1, c, 1) {\n        b_.vol().zero();\n    }\n\n    virtual Volume& forward(const Volume& input) override {\n        input.share_with(x_);\n        res_ = Volume(b_.sz(), 1, 1);\n\n        for (int c = 0, wptr = 0; c < b_.sz(); ++c, wptr += input.sz()) {\n            float sum = b_[c];\n            for (int i = 0; i < input.sz(); ++i) {\n                sum += input[i] * w_[wptr + i];\n            }\n            res_[c] = sum;\n        }\n        return res_;\n    }\n\n    virtual Volume backward(const Volume& pgrad) override {\n        Volume x_grad = x_.from_shape();\n        x_grad.zero();\n\n        for (int c = 0, wptr = 0; c < b_.sz(); ++c, wptr += x_.sz()) {\n            float d = pgrad[c];\n            auto& dw = w_.grad();\n\n            b_.grad()[c] += d;\n            for (int i = 0; i < x_.sz(); ++i) {\n                dw[wptr + i] += d * x_[i];\n            }\n\n            for (int i = 0; i < x_.sz(); ++i) {\n                x_grad[i] += d * w_[wptr + i];\n            }\n        }\n        return x_grad;\n    }\n\n    virtual void update(const Settings& s) override {\n        w_.descend(s);\n        b_.descend(s);\n    }\n\n    void set_weights(std::vector<Volume>&& w, Volume b) {\n        Volume v(w[0].sz(), w.size(), 1);\n        for (int i = 0; i < w.size(); ++i) {\n            for (int j = 0; j < w[i].sz(); ++j) {\n                v[v.w() * i + j] = w[i][j];\n            }\n        }\n        w_.reinit(v);\n        b_.reinit(b);\n    }\n\n    std::vector<Volume> grads() const {\n        std::vector<Volume> gs;\n        for (int i = 0; i < b_.sz(); ++i) {\n            gs.emplace_back(x_.w(), x_.h(), x_.c());\n            for (int j = 0; j < w_.w(); ++j) {\n                gs.back()[j] = w_.grad()[w_.w() * i + j];\n            }\n        }\n        return gs;\n    }\n    float bias() const { return b_.vol()[0]; }\n    std::vector<Volume> weights() const {\n        std::vector<Volume> gs;\n        for (int i = 0; i < b_.sz(); ++i) {\n            gs.emplace_back(x_.w(), x_.h(), x_.c());\n            for (int j = 0; j < w_.w(); ++j) {\n                gs.back()[j] = w_[w_.w() * i + j];\n            }\n        }\n        return gs;\n    }\n\n    virtual void set_train_mode(bool train) override {}\n    virtual Dims out_shape() const override { return Dims{b_.h(), 1, 1}; }\n\n   private:\n    Param w_;\n    Param b_;\n    Volume res_;\n    Volume x_;\n};\n\nclass MaxPool : public Layer {\n   public:\n    MaxPool(Dims d) : out_shape_(Dims{d.w / 2, d.h / 2, d.c}) {}\n\n    virtual Volume& forward(const Volume& input) override {\n        input.share_with(x_);\n        res_ = Volume(input.w() / 2, input.h() / 2, input.c());\n        if (!cache_) {\n            cache_ = std::make_unique<int[]>(res_.sz());\n            std::fill(cache_.get(), cache_.get() + res_.sz(), 0);\n        }\n\n        for (int c = 0; c < input.c(); ++c) {\n            int src_row_idx = input.cha_idx(c);\n            int dst_row_idx = res_.cha_idx(c);\n            for (int h = 0; h < res_.h(); ++h) {\n                for (int w = 0; w < res_.w(); ++w) {\n                    int dst_idx = dst_row_idx + w;\n                    int src_idx = src_row_idx + 2 * w;\n                    int max_pos = std::max(\n                        {src_idx,\n                         src_idx + 1,\n                         src_idx + input.w(),\n                         src_idx + input.w() + 1},\n                        [&](int a, int b) { return input[a] < input[b]; });\n                    cache_[dst_idx] = max_pos;\n                    res_[dst_idx] = input[max_pos];\n                }\n                src_row_idx += 2 * input.w();\n                dst_row_idx += res_.w();\n            }\n        }\n\n        return res_;\n    }\n\n    virtual Volume backward(const Volume& pgrad) override {\n        Volume grad = x_.from_shape();\n        grad.zero();\n        for (int i = 0; i < res_.sz(); ++i) {\n            grad[cache_[i]] = pgrad[i];\n        }\n        return grad;\n    }\n\n    virtual void set_train_mode(bool train) override {}\n    virtual void update(const Settings&) override {}\n\n    virtual Dims out_shape() const override { return out_shape_; }\n\n   private:\n    Volume x_;\n    std::unique_ptr<int[]> cache_;\n    Volume res_;\n    Dims out_shape_;\n};\n\nclass MSE : public Layer {\n   public:\n    void set_target(const Volume& target) { target.share_with(target_); }\n\n    virtual Volume& forward(const Volume& input) override {\n        input.share_with(x_);\n        res_ = Volume(1, 1, 1);\n\n        float total = 0;\n\n        for (int i = 0; i < input.sz(); ++i) {\n            float err = input[i] - target_[i];\n            total += err * err;\n        }\n\n        res_[0] = total / (2 * input.sz());\n\n        return res_;\n    }\n\n    virtual Volume backward(const Volume& pgrad) override {\n        Volume grad = x_.from_shape();\n        for (int i = 0; i < grad.sz(); ++i) {\n            grad[i] = pgrad[0] * (x_[i] - target_[i]);\n        }\n        return grad;\n    }\n\n    virtual void set_train_mode(bool train) override {}\n    virtual void update(const Settings&) override {}\n    virtual Dims out_shape() const override { return Dims{1, 1, 1}; }\n\n   private:\n    Volume target_;\n    Volume x_;\n    Volume res_;\n};\n\nclass Conv : public Layer {\n   public:\n    Conv() = default;\n    Conv(Dims in, Dims kerns) : in_sz_(in), kern_sz_(kerns) {\n        for (int i = 0; i < kern_sz_.c; ++i) {\n            filters_.emplace_back(kern_sz_.w, kern_sz_.h, in.c);\n            biases_.emplace_back(1, 1, 1);\n            biases_.back().vol().zero();\n        }\n    }\n\n    virtual Volume& forward(const Volume& input) override {\n        input.share_with(x_);\n        res_ = Volume(input.w(), input.h(), filters_.size());\n\n        for (int filter = 0; filter < int(filters_.size()); ++filter) {\n            for (int i = res_.cha_idx(filter), end = res_.cha_idx(filter + 1);\n                 i < end;\n                 ++i) {\n                res_[i] = biases_[filter][0];\n            }\n            for (int wptr = 0; wptr < filters_[0].sz(); ++wptr) {\n                auto& f = filters_[filter].vol();\n\n                float weight = f[wptr];\n\n                int channel = wptr / (f.w() * f.h());\n                int hoffset = (wptr - f.cha_idx(channel)) / f.w() - f.h() / 2;\n                int woffset = (wptr - f.cha_idx(channel)) % f.w() - f.w() / 2;\n\n                int dst_row_ptr = res_.cha_idx(filter) +\n                                  std::max(0, hoffset) * res_.w() +\n                                  std::max(0, woffset);\n                int src_row_ptr = input.cha_idx(channel) +\n                                  std::max(0, -hoffset) * input.w() +\n                                  std::max(0, -woffset);\n                for (int h = 0; h < input.h() - std::abs(hoffset); ++h) {\n                    for (int w = 0; w < input.w() - std::abs(woffset); ++w) {\n                        int dst_ptr = dst_row_ptr + w;\n                        int src_ptr = src_row_ptr + w;\n\n                        res_[dst_ptr] += weight * input[src_ptr];\n                    }\n                    dst_row_ptr += res_.w();\n                    src_row_ptr += input.w();\n                }\n            }\n        }\n\n        return res_;\n    }\n\n    virtual Volume backward(const Volume& pgrad) override {\n        Volume dx = x_.from_shape();\n        dx.zero();\n\n        for (int filter = 0; filter < int(filters_.size()); ++filter) {\n            for (int i = pgrad.cha_idx(filter), end = pgrad.cha_idx(filter + 1);\n                 i < end;\n                 ++i) {\n                biases_[filter].grad()[0] += pgrad[i];\n            }\n            auto& f = filters_[filter].vol();\n            auto& df = filters_[filter].grad();\n            for (int wptr = 0; wptr < filters_[0].sz(); ++wptr) {\n                float weight = f[wptr];\n\n                int channel = wptr / (f.w() * f.h());\n                int hoffset = (wptr - f.cha_idx(channel)) / f.w() - f.h() / 2;\n                int woffset = (wptr - f.cha_idx(channel)) % f.w() - f.w() / 2;\n\n                int dst_row_ptr = res_.cha_idx(filter) +\n                                  std::max(0, -hoffset) * res_.w() +\n                                  std::max(0, -woffset);\n                int src_row_ptr = dx.cha_idx(channel) +\n                                  std::max(0, hoffset) * dx.w() +\n                                  std::max(0, woffset);\n                for (int h = 0; h < dx.h() - std::abs(hoffset); ++h) {\n                    for (int w = 0; w < dx.w() - std::abs(woffset); ++w) {\n                        int dst_ptr = dst_row_ptr + w;\n                        int src_ptr = src_row_ptr + w;\n\n                        dx[src_ptr] += pgrad[dst_ptr] * weight;\n                        df[wptr] += pgrad[dst_ptr] * x_[src_ptr];\n                    }\n                    dst_row_ptr += dx.w();\n                    src_row_ptr += dx.w();\n                }\n            }\n        }\n        return dx;\n    }\n\n    void set_filters(std::vector<Volume>&& fs, std::vector<float>&& bs) {\n        if (fs.size() != bs.size()) {\n            throw std::runtime_error(\"filters and biases of a different size\");\n        }\n\n        filters_.clear();\n        for (auto& v : fs) {\n            filters_.emplace_back();\n            filters_.back().reinit(v);\n        }\n\n        biases_.clear();\n        for (auto& v : bs) {\n            biases_.emplace_back(1, 1, 1);\n            biases_.back()[0] = v;\n        }\n    }\n\n    std::vector<Volume> filters_grad() const {\n        std::vector<Volume> vs;\n        for (auto& f : filters_) {\n            vs.emplace_back();\n            f.grad().share_with(vs.back());\n        }\n        return vs;\n    }\n\n    virtual void update(const Settings& s) override {\n        for (int i = 0; i < int(filters_.size()); ++i) {\n            filters_[i].descend(s);\n            biases_[i].descend(s);\n        }\n    }\n\n    virtual Dims out_shape() const override {\n        return Dims{in_sz_.w, in_sz_.h, kern_sz_.c};\n    }\n    virtual void set_train_mode(bool train) override {}\n\n   private:\n    int nb_f_;\n    std::vector<Param> filters_;\n    std::vector<Param> biases_;\n    Volume res_;\n    Volume x_;\n    Dims in_sz_;\n    Dims kern_sz_;\n};\n\nclass Net {\n   public:\n    void set_lr(float x) { settings_.lr = x; }\n    void set_batch_size(int x) { settings_.batch_size = x; }\n    void set_epochs(int e) { settings_.epochs = e; }\n    void set_l2(float x) { settings_.l2 = x; }\n    void set_lr_decay(float x) { settings_.lr_decay = x; }\n    void set_grad_max(float x) { settings_.grad_max = x; }\n    void set_optimizer(Optimizer o) { settings_.optimizer = o; }\n    void set_train_mode(bool train) {\n        for (auto& l : layers_) {\n            l->set_train_mode(train);\n        }\n    }\n\n    void train(std::vector<Volume>&& xs, std::vector<Volume>&& ys) {\n        xs_ = std::move(xs);\n        ys_ = std::move(ys);\n\n        set_train_mode(true);\n        std::vector<float> errs(xs_.size() / settings_.batch_size + 1);\n        for (int e = 0; e < settings_.epochs; ++e) {\n            settings_.lr *= settings_.lr_decay;\n            std::cout << \"Epoch \" << e << \"\\n\";\n            for (int i = 0; i < int(xs_.size()); i += settings_.batch_size) {\n                errs.clear();\n                for (int j = i;\n                     j < std::min(int(xs_.size()), i + settings_.batch_size);\n                     ++j) {\n                    mse_.set_target(ys_[j]);\n                    errs.push_back(forward(xs_[j])[0]);\n                    backward();\n                }\n                update();\n                float total = 0;\n                for (float x : errs) {\n                    total += x;\n                }\n                total /= errs.size();\n                std::cout << \"loss: \" << total << \"\\n\";\n            }\n        }\n    }\n\n    void conv(int kw, int kh, int nb) {\n        if (layers_.empty()) {\n            throw std::invalid_argument(\"input() must be the first layer\");\n        }\n        auto c = std::make_unique<Conv>(layers_.back()->out_shape(),\n                                        Dims{kw, kh, nb});\n        layers_.emplace_back(std::move(c));\n    }\n\n    void input(int w, int h, int c) {\n        if (!layers_.empty()) {\n            throw std::invalid_argument(\"input() must be the first layer\");\n        }\n        layers_.emplace_back(std::make_unique<Input>(Dims{w, h, c}));\n    }\n\n    void relu() {\n        layers_.emplace_back(\n            std::make_unique<Relu>(layers_.back()->out_shape()));\n    }\n\n    void maxpool() {\n        layers_.emplace_back(\n            std::make_unique<MaxPool>(layers_.back()->out_shape()));\n    }\n\n    void fc(int out) {\n        layers_.emplace_back(\n            std::make_unique<FullyConn>(layers_.back()->out_shape(), out));\n    }\n\n    void verbose(std::string name) {\n        layers_.emplace_back(\n            std::make_unique<Verbose>(layers_.back()->out_shape(), name));\n    }\n\n    void batch_norm() {\n        layers_.emplace_back(\n            std::make_unique<BatchNorm>(layers_.back()->out_shape()));\n    }\n\n    void tanh() {\n        layers_.emplace_back(\n            std::make_unique<Tanh>(layers_.back()->out_shape()));\n    }\n\n    const Volume predict(const Volume& x) {\n        set_train_mode(false);\n        Volume it;\n        x.share_with(it);\n        for (int i = 0; i < int(layers_.size()); ++i) {\n            layers_[i]->forward(it).share_with(it);\n        }\n        return std::move(it);\n    }\n    const Volume& forward(const Volume& x) {\n        Volume it;\n        x.share_with(it);\n        for (int i = 0; i < int(layers_.size()); ++i) {\n            layers_[i]->forward(it).share_with(it);\n        }\n        return mse_.forward(it);\n    }\n\n    Volume backward() {\n        Volume one(1, 1, 1);\n        one[0] = 1;\n        Volume it = mse_.backward(one);\n        for (int i = layers_.size(); i-- > 0;) {\n            layers_[i]->backward(it).share_with(it);\n        }\n        return it;\n    }\n\n    void update() {\n        for (auto& l : layers_) {\n            l->update(settings_);\n        }\n    }\n\n   private:\n    std::vector<std::unique_ptr<Layer>> layers_;\n    std::vector<Volume> xs_;\n    std::vector<Volume> ys_;\n    MSE mse_;\n    Settings settings_;\n};\n\nnamespace p = boost::python;\nnamespace np = boost::python::numpy;\n\nVolume from_array(np::ndarray arr) {\n    if (arr.get_nd() != 3) {\n        throw std::runtime_error(\"volume doesn't have 3 dimensions\");\n    }\n    auto as_f = arr.astype(np::dtype::get_builtin<float>());\n    Volume v(arr.shape(1), arr.shape(0), arr.shape(2));\n    const int channel_size = v.cha_idx(1);\n    const int img_size = v.w() * v.h();\n\n    for (int dst = 0, src = 0; dst < img_size; ++dst, src += arr.shape(2)) {\n        int channel_dst = dst;\n        for (int j = 0; j < arr.shape(2); ++j) {\n            float x = reinterpret_cast<float*>(as_f.get_data())[src + j];\n            v[channel_dst] = x;\n            channel_dst += channel_size;\n        }\n    }\n    return v;\n}\n\nnp::ndarray to_array(const Volume& v) {\n    auto res = np::empty(p::make_tuple(v.h(), v.w(), v.c()),\n                         np::dtype::get_builtin<float>());\n    float* dat = reinterpret_cast<float*>(res.get_data());\n\n    int img_sz = v.w() * v.h();\n    for (int src = 0, dst = 0; src < img_sz; ++src, dst += v.c()) {\n        for (int c = 0, src_c = 0; c < v.c(); ++c, src_c += v.cha_idx(1)) {\n            dat[dst + c] = v[src + src_c];\n        }\n    }\n\n    return res;\n}\n\nBOOST_PYTHON_MODULE(miniconv) {\n    using namespace boost::python;\n    class_<Conv, boost::noncopyable>(\"Conv\")\n        .def(\"forward\",\n             +[](Conv* conv, np::ndarray arr) {\n                 return to_array(conv->forward(from_array(arr)));\n             })\n        .def(\"backward\",\n             +[](Conv* conv, np::ndarray arr) {\n                 return to_array(conv->backward(from_array(arr)));\n             })\n        .def(\"set_filters\",\n             +[](Conv* conv, p::list kerns, p::list biases) {\n                 std::vector<Volume> ks;\n                 std::vector<float> bs;\n                 for (int i = 0; i < p::len(kerns); ++i) {\n                     ks.emplace_back(\n                         from_array(p::extract<np::ndarray>(kerns[i])));\n                     bs.push_back(p::extract<float>(biases[i]));\n                 }\n                 conv->set_filters(std::move(ks), std::move(bs));\n             })\n        .def(\"filters_grad\",\n             +[](Conv* conv) {\n                 p::list res;\n                 for (auto& vol : conv->filters_grad()) {\n                     res.append(to_array(vol));\n                 }\n                 return res;\n             })\n        .def(\"update\", &Conv::update);\n\n    class_<MSE, boost::noncopyable>(\"MSE\")\n        .def(\"forward\",\n             +[](MSE* mse, np::ndarray arr) {\n                 return to_array(mse->forward(from_array(arr)));\n             })\n        .def(\"backward\",\n             +[](MSE* mse, np::ndarray arr) {\n                 return to_array(mse->backward(from_array(arr)));\n             })\n        .def(\"set_target\",\n             +[](MSE* mse, np::ndarray arr) {\n                 return mse->set_target(from_array(arr));\n             })\n        .def(\"update\", &MSE::update);\n\n    class_<Relu, boost::noncopyable>(\"Relu\")\n        .def(\"forward\",\n             +[](Relu* relu, np::ndarray arr) {\n                 return to_array(relu->forward(from_array(arr)));\n             })\n        .def(\"backward\",\n             +[](Relu* relu, np::ndarray arr) {\n                 return to_array(relu->backward(from_array(arr)));\n             })\n        .def(\"update\", &Relu::update);\n\n    class_<FullyConn, boost::noncopyable>(\"FullyConn\")\n        .def(\"forward\",\n             +[](FullyConn* relu, np::ndarray arr) {\n                 return to_array(relu->forward(from_array(arr)));\n             })\n        .def(\"backward\",\n             +[](FullyConn* fc, np::ndarray arr) {\n                 return to_array(fc->backward(from_array(arr)));\n             })\n        .def(\"set_weights\",\n             +[](FullyConn* fc, p::list weights, np::ndarray b) {\n                 std::vector<Volume> ws;\n                 for (int i = 0; i < p::len(weights); ++i) {\n                     ws.emplace_back(\n                         from_array(p::extract<np::ndarray>(weights[i])));\n                 }\n                 fc->set_weights(std::move(ws), from_array(b));\n             })\n        .def(\"grads\",\n             +[](FullyConn* fc) {\n                 p::list ws;\n                 auto ws2 = fc->grads();\n                 for (auto& w : ws2) {\n                     ws.append(to_array(w));\n                 }\n                 return ws;\n             })\n        .def(\"bias\", +[](FullyConn* fc) { return fc->bias(); })\n        .def(\"weights\",\n             +[](FullyConn* fc) {\n                 p::list ws;\n                 auto ws2 = fc->weights();\n                 for (auto& w : ws2) {\n                     ws.append(to_array(w));\n                 }\n                 return ws;\n             })\n        .def(\"update\", &FullyConn::update);\n    class_<Net, boost::noncopyable>(\"Net\")\n        .def(\"conv\", &Net::conv)\n        .def(\"fc\", &Net::fc)\n        .def(\"backward\", +[](Net* net) { return to_array(net->backward()); })\n        .def(\"forward\",\n             +[](Net* net, np::ndarray arr) {\n                 return to_array(net->forward(from_array(arr)));\n             })\n        .def(\"predict\",\n             +[](Net* net, np::ndarray arr) {\n                 return to_array(net->predict(from_array(arr)));\n             })\n        .def(\"input\", &Net::input)\n        .def(\"maxpool\", &Net::maxpool)\n        .def(\"relu\", &Net::relu)\n        .def(\"verbose\", &Net::verbose)\n        .def(\"tanh\", &Net::tanh)\n        .def(\"batch_norm\", &Net::batch_norm)\n        .def(\"set_batch_size\", &Net::set_batch_size)\n        .def(\"set_l2\", &Net::set_l2)\n        .def(\"set_epochs\", &Net::set_epochs)\n        .def(\"set_lr\", &Net::set_lr)\n        .def(\"set_lr_decay\", &Net::set_lr_decay)\n        .def(\"set_optimizer\", &Net::set_optimizer)\n        .def(\"set_grad_max\", &Net::set_grad_max)\n        .def(\"set_train_mode\", &Net::set_train_mode)\n        .def(\"train\",\n             +[](Net* net, p::list xs, p::list ys) {\n                 std::vector<Volume> vxs;\n                 std::vector<Volume> vys;\n                 if (p::len(xs) != p::len(ys)) {\n                     throw std::invalid_argument(\n                         \"ys and xs must be of equal size\");\n                 }\n                 for (int i = 0; i < p::len(xs); ++i) {\n                     vxs.emplace_back(\n                         from_array(p::extract<np::ndarray>(xs[i])));\n                     vys.emplace_back(\n                         from_array(p::extract<np::ndarray>(ys[i])));\n                 }\n                 net->train(std::move(vxs), std::move(vys));\n             })\n        .def(\"update\", &Net::update);\n\n    class_<Settings>(\"Settings\")\n        .def_readwrite(\"lr\", &Settings::lr)\n        .def_readwrite(\"lr_decay\", &Settings::lr_decay)\n        .def_readwrite(\"l2\", &Settings::l2)\n        .def_readwrite(\"epochs\", &Settings::epochs)\n        .def_readwrite(\"grad_max\", &Settings::grad_max)\n        .def_readwrite(\"batch_size\", &Settings::batch_size);\n\n    enum_<Optimizer>(\"Optimizer\")\n        .value(\"sgd\", Optimizer::Sgd)\n        .value(\"sgdm\", Optimizer::Sgdm)\n        .value(\"powersign\", Optimizer::PowerSign);\n\n    np::initialize();\n    //    feenableexcept(FE_ALL_EXCEPT & ~FE_INEXACT);\n}\n", "meta": {"hexsha": "171669077bc1ba28f67da917105ba785aa1f9b26", "size": 38845, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "conv.cpp", "max_stars_repo_name": "Vermeille/miniconv", "max_stars_repo_head_hexsha": "24ab1f8aa276acff22356c4d4af0f3e87bec5f19", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "conv.cpp", "max_issues_repo_name": "Vermeille/miniconv", "max_issues_repo_head_hexsha": "24ab1f8aa276acff22356c4d4af0f3e87bec5f19", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "conv.cpp", "max_forks_repo_name": "Vermeille/miniconv", "max_forks_repo_head_hexsha": "24ab1f8aa276acff22356c4d4af0f3e87bec5f19", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8807692308, "max_line_length": 80, "alphanum_fraction": 0.4603938731, "num_tokens": 10406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.24395876097908092}}
{"text": "/*******************************************************************************\n*\n*  Filename    : RooFit_MCTemplate.cc\n*  Description : Plotting to file for template methods.cc\n*  Author      : Yi-Mu \"Enoch\" Chen [ ensc@hep1.phys.ntu.edu.tw ]\n*\n*******************************************************************************/\n#include \"TstarAnalysis/LimitCalc/interface/Common.hpp\"\n#include \"TstarAnalysis/LimitCalc/interface/MakeKeysPdf.hpp\"\n#include \"TstarAnalysis/LimitCalc/interface/SampleRooFitMgr.hpp\"\n#include \"TstarAnalysis/LimitCalc/interface/SimFit.hpp\"\n#include \"TstarAnalysis/LimitCalc/interface/Template.hpp\"\n\n#include \"ManagerUtils/Maths/interface/RooFitExt.hpp\"\n#include \"ManagerUtils/PlotUtils/interface/Common.hpp\"\n#include \"ManagerUtils/PlotUtils/interface/RooFitUtils.hpp\"\n#include \"TstarAnalysis/Common/interface/PlotStyle.hpp\"\n\n#include <boost/format.hpp>\n#include <fstream>\n#include <string>\n\n#include \"RooDataSet.h\"\n#include \"RooNLLVar.h\"\n#include \"RooMinimizer.h\"\n\nusing namespace std;\nusing namespace mgr;\n\n/*******************************************************************************\n*   Object naming convention\n*******************************************************************************/\nstring\nTemplatePdfName( const std::string& datasetname )\n{\n  return datasetname + \"template\";\n}\n\nextern const string StitchTemplatePdfName = \"templatemaster\";\n\n/*******************************************************************************\n*   Main control flow to be caleed by main function\n*******************************************************************************/\nvoid\nMakeTemplate(\n  SampleRooFitMgr*          data,\n  SampleRooFitMgr*          bg,\n  vector<SampleRooFitMgr*>& signal_list\n  )\n{\n  vector<RooAbsPdf*> pdflist;\n  vector<RooAbsReal*> funclist;\n\n  for( auto& sig : signal_list ){\n    pdflist.push_back( MakeFullKeysPdf( sig ) );\n    // funclist.push_back( sig->Func(StitchKeyNormName));\n  }\n\n  auto fitresultlist = MakeFullTemplate( bg );\n  MakeTemplatePlot( data, bg, signal_list.front(), fitresultlist.front(), true );\n  MakeTemplatePlot( data, bg, signal_list.front(), fitresultlist.front(), false );\n  pdflist.push_back( bg->Pdf( StitchTemplatePdfName ) );\n\n  SaveRooWorkSpace(\n    data->DataSet( \"\" ),\n    pdflist,\n    {}\n    );\n\n  for( auto& signal : signal_list ){\n    MakeTemplateCardFile( data, bg, signal );\n  }\n}\n\n\n/*******************************************************************************\n*   Fitting function implementations\n*******************************************************************************/\nRooFitResult*\nFitBackgroundTemplate( SampleRooFitMgr* bg, const string& datatag )\n{\n  const string bgpdfname = TemplatePdfName( datatag );\n\n  RooAbsPdf* bgpdf = bg->NewPdf( bgpdfname, limnamer.GetInput<string>( \"fitfunc\" ) );\n  // Manually calling NNL minizer functions\n  static RooCmdArg min    = RooFit::Minimizer( \"Minuit\", \"Migrad\" );\n  static RooCmdArg sumerr = RooFit::SumW2Error( kTRUE );\n  static RooCmdArg hesse  = RooFit::Minos( kTRUE );\n  static RooCmdArg save   = RooFit::Save();\n  //static RooCmdArg ncpu   = RooFit::NumCPU( 6 );\n  static RooCmdArg verb   = RooFit::Verbose( kFALSE );\n  static RooCmdArg printl = RooFit::PrintLevel( -1 );\n  static RooCmdArg printe = RooFit::PrintEvalErrors( -1 );\n  static RooCmdArg printw = RooFit::Warnings( kFALSE );\n\n  RooLinkedList fitopt;\n  fitopt.Add( &min    );\n  fitopt.Add( &sumerr );\n  fitopt.Add( &hesse  );\n  fitopt.Add( &save   );\n  //fitopt.Add( &ncpu   );\n  fitopt.Add( &verb   );\n  fitopt.Add( &printl );\n  fitopt.Add( &printe );\n  fitopt.Add( &printw );\n\n  const unsigned maxiter = 30;\n  unsigned iter = 0 ;\n  RooFitResult* ans = NULL ;\n  while( !ans ){\n    ans = bgpdf->fitTo( *( bg->DataSet(datatag) ), fitopt );\n    if( ans->status() ){ // Not properly converged\n      iter++;\n      if( iter > maxiter ) { break; }\n      delete ans;\n      ans = NULL;\n    }\n  }\n  cout << \">>>> BKG FIT iteration: \" << iter << endl;\n  bg->SetConstant( kTRUE );// Freezing all constants\n\n  return ans;\n}\n\n/******************************************************************************/\n\nvector<RooFitResult*>\nMakeFullTemplate( SampleRooFitMgr* bg )\n{\n  vector<string> bgpdflist;\n  vector<RooFitResult*> ans;\n\n  for( const auto& datasetname : bg->SetNameList() ){\n    ans.push_back( FitBackgroundTemplate( bg, datasetname ) );\n    bgpdflist.push_back( TemplatePdfName( datasetname ) );\n  }\n\n  MakeSimpleStitchPdf( bg, StitchTemplatePdfName, bgpdflist );\n  return ans;\n}\n\n/******************************************************************************/\n\nvoid\nMakeTemplateCardFile( SampleRooFitMgr* data, SampleRooFitMgr* bg, SampleRooFitMgr* sig )\n{\n  RooAbsData* dataobs = data->DataSet( \"\" );\n  RooAbsPdf* bgpdf    = bg->Pdf( StitchTemplatePdfName );\n  RooAbsPdf* sigpdf   = sig->Pdf( StitchKeyPdfName );\n\n  ofstream cardfile( limnamer.TextFileName( \"card\", {sig->Name()} ) );\n\n  MakeCardCommon( cardfile, dataobs, bgpdf, sigpdf );\n\n  cardfile << boost::format( \"%12s %15lf %15lf\" )\n    % \"rate\"\n    % sig->DataSet()->sumEntries()\n    % bg->DataSet()->sumEntries()\n           << endl;\n\n  cardfile << \"----------------------------------------\" << endl;\n\n  const Parameter null( 0, 0, 0 );\n  const Parameter lumi( 1, 0.062, 0.062 );\n  const Parameter lepunc( 1, 0.03, 0.03 );\n  const Parameter sigstatunc = sig->Sample().SelectionEfficiency();\n  const Parameter bkgstatunc( 1, 0.03, 0.03 );// includes uncertaintly from cross section and selection effiency\n\n  const Parameter sigjecunc  = GetMCNormError( sig, \"jecUp\",    \"jecDown\"    );\n  const Parameter sigjerunc  = GetMCNormError( sig, \"jetresUp\", \"jetresDown\" );\n  const Parameter siglepunc  = GetMCNormError( sig, \"lepUp\",    \"lepDown\"    );\n  const Parameter sigbtagunc = GetMCNormError( sig, \"btagUp\",   \"btagDown\"   );\n  const Parameter sigpuunc   = GetMCNormError( sig, \"puUp\",     \"puDown\"     );\n  const Parameter sigpdfunc  = GetMCNormError( sig, \"pdfUp\",    \"pdfDown\"    );\n\n  const Parameter bkgjecunc  = GetMCNormError( bg, \"jecUp\",    \"jecDown\"    );\n  const Parameter bkgjerunc  = GetMCNormError( bg, \"jetresUp\", \"jetresDown\" );\n  const Parameter bkglepunc  = GetMCNormError( bg, \"lepUp\",    \"lepDown\"    );\n  const Parameter bkgbtagunc = GetMCNormError( bg, \"btagUp\",   \"btagDown\"   );\n  const Parameter bkgpuunc   = GetMCNormError( bg, \"puUp\",     \"puDown\"     );\n  const Parameter bkgpdfunc  = GetMCNormError( bg, \"pdfUp\",    \"pdfDown\"    );\n\n  PrintNuisanceFloats( cardfile, \"Lumi\",    \"lnN\", lumi,       lumi        );\n  PrintNuisanceFloats( cardfile, \"lepsys\",  \"lnN\", lepunc,     lepunc      );\n  PrintNuisanceFloats( cardfile, \"sigstat\", \"lnN\", sigstatunc, null        );\n  PrintNuisanceFloats( cardfile, \"bkgstat\", \"lnN\", null,       bkgstatunc  );\n  PrintNuisanceFloats( cardfile, \"jec\",     \"lnN\", sigjecunc,  bkgjecunc   );\n  PrintNuisanceFloats( cardfile, \"jer\",     \"lnN\", sigjerunc,  bkgjerunc   );\n  PrintNuisanceFloats( cardfile, \"lep\",     \"lnN\", siglepunc,  bkglepunc   );\n  PrintNuisanceFloats( cardfile, \"btag\",    \"lnN\", sigbtagunc, bkgbtagunc  );\n  PrintNuisanceFloats( cardfile, \"pileup\",  \"lnN\", sigpuunc,   bkgpuunc    );\n  PrintNuisanceFloats( cardfile, \"pdf\",     \"lnN\", sigpdfunc,  bkgpdfunc   );\n\n  // Getting fitting parameters\n  for( const auto& var : bg->VarContains( \"template\" ) ){\n    const string varname = var->GetName();\n    if( varname.find( \"coeff\" ) == string::npos ){\n      PrintFloatParam( cardfile, var );\n    }\n  }\n\n  // Getting stitching co-efficiencts\n  for( const auto& var : bg->VarContains( \"coeff\" ) ){\n    PrintFlatParam( cardfile, var );\n  }\n\n  for( const auto& var : sig->VarContains( \"coeff\" ) ){\n    PrintFlatParam( cardfile, var );\n  }\n\n  cardfile.close();\n}\n\n\n/*******************************************************************************\n*   Plotting fit results\n*******************************************************************************/\nvoid\nMakeTemplatePlot(\n  SampleRooFitMgr* data,\n  SampleRooFitMgr* mc,\n  SampleRooFitMgr* signal,\n  RooFitResult*    fitresult,\n  const bool       use_data )\n{\n  // First plot against MC\n  const double TotalLuminosity = mgr::SampleMgr::TotalLuminosity();\n  const double xmin            = SampleRooFitMgr::x().getMin();\n  const double xmax            = SampleRooFitMgr::x().getMax();\n\n  TCanvas* c     = mgr::NewCanvas();\n  TPad* toppad   = mgr::NewTopPad();\n  TPad* botpad   = mgr::NewBottomPad();\n  RooPlot* frame = SampleRooFitMgr::x().frame();\n\n  // Objects to draw\n  RooDataSet* set   = (RooDataSet*)( use_data ? data->DataSet() : mc->DataSet() );\n  RooAbsPdf* bkgpdf = mc->Pdf( TemplatePdfName( \"\" ) );// Taking central value only\n  RooAbsPdf* sigpdf = signal->Pdf( StitchKeyPdfName );\n\n  /*******************************************************************************\n  *   Objects for drawing top pad\n  *******************************************************************************/\n  toppad->Draw();\n  toppad->cd();\n\n  TGraph* setplot = mgr::PlotOn(\n    frame,\n    set,\n    RooFit::DrawOption( PGS_DATA )\n    );\n\n  TGraph* pdfplot = mgr::PlotFitErrorOn(\n    frame, bkgpdf, fitresult,\n    RooFit::Normalization( set->sumEntries(), RooAbsReal::NumEvent )\n    );\n\n  TGraph* sigplot = mgr::PlotOn(\n    frame,\n    sigpdf,\n    RooFit::DrawOption( PGS_SIGNAL ),\n    RooFit::Normalization( signal->ExpectedYield(), RooAbsReal::NumEvent )\n    );\n  tstar::RemoveDataXBar( (TGraphAsymmErrors*)setplot );\n\n  // Typical styling options\n  frame->Draw();\n  frame->SetMinimum( 0.3 );\n  mgr::SetTopPlotAxis( frame );\n  frame->SetTitle(\"\");\n\n  c->cd();\n  /*******************************************************************************\n  *   Objects for drawing bottom pad\n  *******************************************************************************/\n  botpad->Draw();\n  botpad->cd();\n\n  TGraphAsymmErrors* bgrelplot = mgr::DividedGraph(\n    (TGraphAsymmErrors*)pdfplot,\n    pdfplot\n    );\n  TGraphAsymmErrors* datarelplot = mgr::DividedGraph(\n    (TGraphAsymmErrors*)setplot,\n    pdfplot\n    );\n  tstar::RemoveDataXBar( datarelplot );\n  bgrelplot->Draw( \"AL3\" );\n  datarelplot->Draw( PGS_DATA );\n\n  TLine cen( xmin, 1, xmax, 1 );\n  TLine lineup( xmin, 1.5, xmax, 1.5 );\n  TLine linedown( xmin, 0.5, xmax, 0.5 );\n  cen.Draw();\n  cen.SetLineColor( KBLUE );\n  cen.SetLineWidth( 2 );\n  lineup.Draw();\n  lineup.SetLineColor( kBlack );\n  lineup.SetLineStyle( 3 );\n  linedown.Draw();\n  linedown.SetLineColor( kBlack );\n  linedown.SetLineStyle( 3 );\n\n  // Title setting\n  bgrelplot->GetXaxis()->SetTitle( frame->GetXaxis()->GetTitle() );\n  bgrelplot->GetXaxis()->SetRangeUser( xmin, xmax );\n  bgrelplot->GetYaxis()->SetTitle( \"Data/Bkg.fit\" );\n  bgrelplot->SetMaximum( 1.6 );\n  bgrelplot->SetMinimum( 0.4 );\n  mgr::SetBottomPlotAxis( bgrelplot );\n\n  c->cd();\n  /*******************************************************************************\n  *   Common styling and additiona objects\n  *******************************************************************************/\n  tstar::SetSignalStyle( sigplot );\n  tstar::SetFitBGStyle( pdfplot );\n  tstar::SetSignalStyle( sigplot );\n\n  tstar::SetFitBGStyle( bgrelplot );\n  tstar::SetDataStyle( datarelplot );\n  tstar::SetDataStyle( setplot );\n\n  // Legend entries\n  const double legend_x_min = 0.65;\n  const double legend_y_min = 0.70;\n  TLegend* l                = mgr::NewLegend( legend_x_min, legend_y_min );\n  boost::format sigfmt( \"%s\" );\n  const string sigentry  = str( sigfmt % signal->RootName() );\n  const string dataentry = ( use_data ) ? \"Data\" : \"M.C. Bkg.\";\n  const string fitentry  = string( \"Bkg. fit to MC\" ) + ( use_data ? \"(Norm.)\" : \"\" );\n\n\n  l->AddEntry( setplot, dataentry.c_str(), \"pe\" );\n  l->AddEntry( pdfplot, fitentry.c_str(),  \"l\"  );\n  l->AddEntry( sigplot, sigentry.c_str(),  \"l\"  );\n  l->Draw();\n\n  // Additional information plotting\n  boost::format goffmt( \"K = %.3lf\" );\n  const double ksprob   = KSTest( *( set ), *( bkgpdf ), SampleRooFitMgr::x() );\n  const string gofentry = str( goffmt % ksprob );\n\n  mgr::DrawCMSLabel();\n  mgr::DrawLuminosity( TotalLuminosity );\n\n  LatexMgr latex;\n  latex.SetOrigin( PLOT_X_MIN, PLOT_Y_MAX + TEXT_MARGIN/2, TOP_LEFT )\n  .WriteLine( limnamer.GetChannelEXT( \"Root Name\" ) )\n  .SetOrigin( PLOT_X_TEXT_MAX, legend_y_min-TEXT_MARGIN, TOP_RIGHT )\n  .WriteLine( gofentry );\n\n  // Range setting and saving\n  const double ymax = mgr::GetYmax( pdfplot, setplot, sigplot );\n  frame->SetMaximum( ymax * 1.5 );\n\n  const string rootfile = limnamer.PlotRootFile();\n  const string lastag   = use_data ? \"fitmc-vs-data\" : \"fitmc-vs-mc\";\n  mgr::SaveToPDF( c, limnamer.PlotFileName( \"\", \"fitplot\", signal->Name(), lastag ) );\n  mgr::SaveToROOT( c, rootfile, limnamer.PlotFileName( \"fitplot\", signal->Name(), lastag ) );\n  frame->SetMaximum( ymax * 300 );\n  toppad->SetLogy( kTRUE );\n  mgr::SaveToPDF( c, limnamer.PlotFileName( \"fitplot\", signal->Name(), lastag, \"log\" ) );\n\n  // Cleaning up\n  delete frame;\n  delete c;\n  delete l;\n}\n", "meta": {"hexsha": "df9cc0448607443a4e72992352d4f2aae9fe0805", "size": 12910, "ext": "cc", "lang": "C++", "max_stars_repo_path": "LimitCalc/src/RooFit_MCTemplate.cc", "max_stars_repo_name": "NTUHEP-Tstar/TstarAnalysis", "max_stars_repo_head_hexsha": "d3bcdf6f0fd19b9a34bbacb1052143856917bea7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LimitCalc/src/RooFit_MCTemplate.cc", "max_issues_repo_name": "NTUHEP-Tstar/TstarAnalysis", "max_issues_repo_head_hexsha": "d3bcdf6f0fd19b9a34bbacb1052143856917bea7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LimitCalc/src/RooFit_MCTemplate.cc", "max_forks_repo_name": "NTUHEP-Tstar/TstarAnalysis", "max_forks_repo_head_hexsha": "d3bcdf6f0fd19b9a34bbacb1052143856917bea7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8918918919, "max_line_length": 112, "alphanum_fraction": 0.5899302866, "num_tokens": 3588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.37022539259558657, "lm_q1q2_score": 0.24376288260024254}}
{"text": "/*\n * Copyright (C) 2022 Agtonomy\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#ifndef TRELLIS_CONTAINERS_TRANSFORMS_HPP\n#define TRELLIS_CONTAINERS_TRANSFORMS_HPP\n\n#include <Eigen/Geometry>\n#include <string>\n#include <unordered_map>\n#include <utility>\n\n#include \"trellis/core/time.hpp\"\n\nnamespace trellis {\nnamespace containers {\n\n/**\n * Transforms a container to hold rigid coordinate frame transformations\n *\n * This class holds transforms with associated timestamps. Lookups are done based on a timestamp. The algorithm will\n * find the transform with the timestamp nearest the requested one.\n *\n * Future improvements:\n * - Support a graph structure to allow lookups that are transitive. Say we know A -> B -> C, we should support a lookup\n * of A -> C\n */\nclass Transforms {\n public:\n  /**\n   * Tranlsation represents a translation in 3D space\n   */\n  using Translation = Eigen::Vector3d;\n\n  /**\n   * Rotation represents a rotation in 3D space represented as a quaternion\n   */\n  using Rotation = Eigen::Vector4d;\n\n  /**\n   * AffineTransform3D an Eigen 3-dimensional affine transform representation\n   */\n  using AffineTransform3D = Eigen::Transform<double, 3, Eigen::Affine>;\n\n  /**\n   * RigidTransform represents a transformation comprised of a translation and rotation\n   *\n   * NOTE: The convention is such that the translation is performed before the rotation\n   */\n  struct RigidTransform {\n    RigidTransform() = default;\n\n    /**\n     * RigidTransform construct a rigid transfrom from an Eigen affine transform representation\n     *\n     * @param transform the Eigen affine transform\n     */\n    RigidTransform(const AffineTransform3D& transform)\n        : translation{GetTranslationFromAffineTransform(transform)},\n          rotation{GetRotationFromAffineTransform(transform)} {}\n\n    /**\n     * GetAffineRepresentation return an Eigen affine transform representation of this rigid transform\n     *\n     * @return the Eigen affine transform\n     */\n    AffineTransform3D GetAffineRepresentation() const {\n      return AffineTransform3D(Eigen::Translation<double, 3>(translation.x(), translation.y(), translation.z()) *\n                               Eigen::Quaterniond(rotation.w(), rotation.x(), rotation.y(), rotation.z()));\n    }\n\n    /**\n     * Inverse retrieve the inverse transform\n     *\n     * @return the inverse transform\n     */\n    RigidTransform Inverse() const { return Transforms::RigidTransform(GetAffineRepresentation().inverse()); }\n\n    /**\n     * Exact quality operator.\n     *\n     * Note: for approximations use Eigen's GetAffineRepresentation().isApprox() instead\n     *\n     * @returns true if both operands are exact copies of each other\n     */\n    bool operator==(const RigidTransform& other) const {\n      return this->translation.x() == other.translation.x() && this->translation.y() == other.translation.y() &&\n             this->translation.z() == other.translation.z() && this->rotation.w() == other.rotation.w() &&\n             this->rotation.x() == other.rotation.x() && this->rotation.y() == other.rotation.y() &&\n             this->rotation.z() == other.rotation.z();\n    }\n\n    bool operator!=(const RigidTransform& other) const { return !(*this == other); }\n\n    Translation translation;\n    Rotation rotation;\n\n   private:\n    static Translation GetTranslationFromAffineTransform(const AffineTransform3D& transform) {\n      return Translation{transform.translation().x(), transform.translation().y(), transform.translation().z()};\n    }\n    static Rotation GetRotationFromAffineTransform(const AffineTransform3D& transform) {\n      const Eigen::Quaterniond q(transform.rotation());\n      return Rotation{q.x(), q.y(), q.z(), q.w()};\n    }\n  };\n\n  struct Sample {\n    const trellis::core::time::TimePoint& timestamp;\n    const RigidTransform& transform;\n  };\n\n  static constexpr std::size_t kMaxTransformLengthDefault = 100U;\n\n  Transforms(std::size_t max_transform_length = kMaxTransformLengthDefault)\n      : max_transform_length_{max_transform_length} {}\n\n  /**\n   * UpdateTransform update a transform associated with the current time\n   *\n   * @param from the starting reference frame for the transform\n   * @param to the ending reference frame for the transform\n   * @param transform the actual transformation in terms of a translation and a rotation\n   */\n  void UpdateTransform(const std::string& from, const std::string& to, const RigidTransform& transform);\n\n  /**\n   * UpdateTransform update a transform associated with the given time\n   *\n   * @param from the starting reference frame for the transform\n   * @param to the ending reference frame for the transform\n   * @param transform the actual transformation in terms of a translation and a rotation\n   * @param when the time point to associate with the transform\n   */\n  void UpdateTransform(const std::string& from, const std::string& to, const RigidTransform& transform,\n                       const trellis::core::time::TimePoint& when);\n\n  /**\n   * HasTransform determine if a transform for a given pair of reference frames exists and is within the valid time\n   * window\n   *\n   * @param from the starting reference frame for the transform\n   * @param to the ending reference frame for the transform\n   * @return true if the transform exists and is valid\n   *\n   */\n  bool HasTransform(const std::string& from, const std::string& to) const;\n\n  /**\n   * HasTransform determine if a transform for a given pair of reference frames exists and is within the valid time\n   * window relative to the given time\n   *\n   * @param from the starting reference frame for the transform\n   * @param to the ending reference frame for the transform\n   * @param when the time point to associate with the transform\n   * @return true if the transform exists and is valid\n   *\n   */\n  bool HasTransform(const std::string& from, const std::string& to, const trellis::core::time::TimePoint& when) const;\n\n  /**\n   * GetTransform retrieve the most recent transform for a given pair of reference frames\n   *\n   * @param from the starting reference frame for the transform\n   * @param to the ending reference frame for the transform\n   * @return the rigid transformation between the two reference frames with associated timestamp\n   * @throws std::runtime_error if no valid transform exists\n   */\n  Sample GetTransform(const std::string& from, const std::string& to) const;\n\n  /**\n   * GetTransform retrieve the transform for a given pair of reference frames nearest the given time\n   *\n   * @param from the starting reference frame for the transform\n   * @param to the ending reference frame for the transform\n   * @param when the time point with which to find the nearest transform\n   * @return the rigid transformation between the two reference frames with associated timestamp\n   * @throws std::runtime_error if no valid transform exists\n   */\n  Sample GetTransform(const std::string& from, const std::string& to, const trellis::core::time::TimePoint& when) const;\n\n private:\n  std::optional<trellis::core::time::TimePoint> FindNearestTransformTimestamp(\n      const std::string& from, const std::string& to, const trellis::core::time::TimePoint& when) const;\n\n  void Insert(const std::string& from, const std::string& to, const RigidTransform& transform,\n              const trellis::core::time::TimePoint& when);\n\n  static void ValidateFrameName(const std::string& frame);\n\n  using KeyType = std::string;\n\n  struct FrameNames {\n    const std::string from;\n    const std::string to;\n  };\n\n  static KeyType CalculateKeyFromFrames(const std::string& from, const std::string& to);\n  static FrameNames GetFrameNamesFromKey(const KeyType& key);\n\n  static constexpr char kDelimiter = '|';\n\n  using TransformHistoryContainer = std::map<trellis::core::time::TimePoint, RigidTransform>;\n  std::unordered_map<KeyType, TransformHistoryContainer> transforms_;\n  const std::size_t max_transform_length_;\n};\n}  // namespace containers\n}  // namespace trellis\n\n#endif  // TRELLIS_CONTAINERS_TRANSFORMS_HPP\n", "meta": {"hexsha": "34c44d08e74f2941c3b696f0a094ea0c9b1449c5", "size": 8513, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trellis/containers/transforms.hpp", "max_stars_repo_name": "agtonomy/trellis", "max_stars_repo_head_hexsha": "ef50dc85d11af5badae9ca1487df100817c2b97f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-10-18T00:48:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T06:23:47.000Z", "max_issues_repo_path": "trellis/containers/transforms.hpp", "max_issues_repo_name": "agtonomy/trellis", "max_issues_repo_head_hexsha": "ef50dc85d11af5badae9ca1487df100817c2b97f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-11-24T18:26:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T00:08:18.000Z", "max_forks_repo_path": "trellis/containers/transforms.hpp", "max_forks_repo_name": "agtonomy/trellis", "max_forks_repo_head_hexsha": "ef50dc85d11af5badae9ca1487df100817c2b97f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-05T16:39:59.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T16:39:59.000Z", "avg_line_length": 38.0044642857, "max_line_length": 120, "alphanum_fraction": 0.714201809, "num_tokens": 1886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.24372687000742033}}
{"text": "//\n// Created by philipp on 26.12.19.\n//\n\n#ifndef FUNNELS_CPP_DYNAMICS_HH\n#define FUNNELS_CPP_DYNAMICS_HH\n\n#include <Eigen/Core>\n#include <cmath>\n#include <cassert>\n#include <memory>\n\n\nusing namespace Eigen;\n\nnamespace dynamics {\n  \n  class kinematic_2d_sys_t {\n  public:\n    constexpr static const size_t dimx = 4, dimp = 2, dimv = 2, dimu = 2;\n  \n    using matrix_t = Eigen::Matrix<double, dimx, Eigen::Dynamic>;\n    using vector_x_t = Eigen::Matrix<double, dimx, 1>;\n    using vector_u_t = Eigen::Matrix<double, dimu, 1>;\n    using vector_t_t = Eigen::Matrix<double, Eigen::Dynamic, 1>;\n    using matrix_ptr_t = std::shared_ptr<matrix_t>;\n    using vector_x_ptr_t = std::shared_ptr<vector_x_t>;\n    using vector_u_ptr_t = std::shared_ptr<vector_u_t>;\n    using vector_t_ptr_t = std::shared_ptr<vector_t_t>;\n    \n    static void\n    compute(matrix_t &x, const vector_u_t &u, const vector_t_t &t);\n  };\n}\n#endif //FUNNELS_CPP_DYNAMICS_HH\n", "meta": {"hexsha": "e5be840fd0087e03b27521d1e36cdcb2a8fdbc12", "size": 939, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/funnels/dynamics.hh", "max_stars_repo_name": "schlepil/funnels_cpp_2", "max_stars_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/funnels/dynamics.hh", "max_issues_repo_name": "schlepil/funnels_cpp_2", "max_issues_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/funnels/dynamics.hh", "max_forks_repo_name": "schlepil/funnels_cpp_2", "max_forks_repo_head_hexsha": "1ed746a90019f7f6aff7a54fd4b63bfbd58fa2ac", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0833333333, "max_line_length": 73, "alphanum_fraction": 0.7060702875, "num_tokens": 275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.2436516810719912}}
{"text": "#pragma once\n/** @file KDTree\n * @brief A binary tree constructed by splitting each box by a median.\n */\n\n#include <vector>\n#include <algorithm>\n#include <type_traits>\n#include <iterator>\n\n#include <iostream>\n#include <iomanip>\n\n#include <boost/range.hpp>\n#include <boost/iterator/permutation_iterator.hpp>\n\n#include \"fmmtl/tree/util/CountedProxyIterator.hpp\"\n\n#include \"fmmtl/util/Logger.hpp\"\n#include \"fmmtl/numeric/Vec.hpp\"\n#include \"fmmtl/tree/BoundingSphere.hpp\"\n\n#include \"fmmtl/numeric/bits.hpp\"\n\nnamespace fmmtl {\nusing boost::has_range_iterator;\n\n\n//! Class for tree structure\ntemplate <unsigned DIM>\nclass BallTree {\n  // Predeclarations\n  struct Box;\n  struct Body;\n  struct BoxData;\n\n  // The type of this tree\n  typedef BallTree<DIM> tree_type;\n\n public:\n  //! The type of indices and integers in this tree\n  typedef unsigned size_type;\n\n  //! The spacial point type used for centers and extents\n  typedef Vec<DIM,double> point_type;\n\n  //! Public type declarations\n  typedef Box           box_type;\n  typedef Body          body_type;\n  using box_iterator  = CountedProxyIterator<Box,  const BallTree, size_type>;\n  using body_iterator = CountedProxyIterator<Body, const BallTree, size_type>;\n\n private:\n  // Tree representation\n\n  // Permutation: permute_[i] is the current idx of originally ith point\n  std::vector<size_type> permute_;\n  // Vector of data describing a box\n  std::vector<BoxData> box_data_;\n\n  struct BoxData {\n    typedef BoundingSphere<point_type> bounding_sphere_type;\n\n    // Index of the first body in this box\n    size_type body_begin_;\n    // Index of one-past-last body in this box\n    size_type body_end_;\n    // Bounding sphere\n    bounding_sphere_type bounding_sphere_;\n\n    // Constructor\n    BoxData(size_type bb, size_type be, const bounding_sphere_type& bs)\n        : body_begin_(bb), body_end_(be), bounding_sphere_(bs) {}\n  };\n\n  struct Body {\n    /** Construct an invalid Body */\n    Body() {}\n    //! The original order this body was seen\n    size_type number() const {\n      return tree_->permute_[idx_];\n    }\n    //! The current order of this body\n    size_type index() const {\n      return idx_;\n    }\n   private:\n    size_type idx_;\n    tree_type* tree_;\n    friend body_iterator;\n    Body(size_type idx, const tree_type* tree)\n        : idx_(idx), tree_(const_cast<tree_type*>(tree)) {\n      FMMTL_ASSERT(idx_ < tree_->size());\n    }\n    friend class BallTree;\n  };\n\n  // A box of the tree\n  struct Box {\n    typedef typename tree_type::box_iterator  box_iterator;\n    typedef typename tree_type::body_iterator body_iterator;\n\n    //! Construct an invalid Box\n    Box() {}\n    //! The index of this box\n    size_type index() const {\n      return idx_;\n    }\n    //! The level of this box (root level is 0)\n    size_type level() const {\n      return std::log2(idx_+1);  // XXX: Slow? do this with bits\n    }\n\n    //! The dimension of each side of this box\n    point_type extents() const {\n      point_type e;\n      e.fill(2*std::sqrt(radius_sq()));\n      return e;\n    }\n    //! The squared radius of this box\n    double radius_sq() const {\n      return data().bounding_sphere_.radius_sq();\n    }\n    //! The center of this box\n    point_type center() const {\n      return data().bounding_sphere_.center();\n    }\n\n    //! The parent box of this box\n    Box parent() const {\n      FMMTL_ASSERT(!(*this == tree_->root()));\n      return Box((idx_-1)/2, tree_);\n    }\n\n    //! True if this box is a leaf and has no children\n    bool is_leaf() const {\n      return 2*idx_+1 >= tree_->box_data_.size();\n    }\n    //! The begin iterator to the child boxes contained in this box\n    box_iterator child_begin() const {\n      FMMTL_ASSERT(!is_leaf());\n      return box_iterator(2*idx_+1, tree_);\n    }\n    //! The end iterator to the child boxes contained in this box\n    box_iterator child_end() const {\n      FMMTL_ASSERT(!is_leaf());\n      return box_iterator(2*idx_+3, tree_);\n    }\n    //! The number of children this box has\n    static constexpr size_type num_children() {\n      return 2;\n    }\n\n    //! The begin iterator to the bodies contained in this box\n    body_iterator body_begin() const {\n      return body_iterator(data().body_begin_, tree_);\n    }\n    //! The end iterator to the bodies contained in this box\n    body_iterator body_end() const {\n      return body_iterator(data().body_end_, tree_);\n    }\n    //! The number of bodies this box contains\n    size_type num_bodies() const {\n      return std::distance(body_begin(), body_end());\n    }\n\n    //! Equality comparison operator\n    bool operator==(const Box& b) const {\n      FMMTL_ASSERT(tree_ == b.tree_);\n      return idx_ == b.idx_;\n    }\n    //! Comparison operator for std:: containers and algorithms\n    bool operator<(const Box& b) const {\n      FMMTL_ASSERT(tree_ == b.tree_);\n      return idx_ < b.idx_;\n    }\n\n    //! Write a Box to an output stream\n    friend std::ostream& operator<<(std::ostream& s, const box_type& b) {\n      size_type num_bodies = b.num_bodies();\n      size_type first_body = b.body_begin()->index();\n      size_type last_body = first_body + num_bodies - 1;\n      size_type parent_idx = b.index()==0 ? 0 : b.parent().index();\n\n      return s << \"Box \" << b.index()\n               << \" (L\" << b.level() << \", P\" << parent_idx\n               << \", \" << num_bodies << (num_bodies == 1 ? \" body\" : \" bodies\")\n               << \" \" << first_body << \"-\" << last_body\n               << \"): Center: \" << b.center()\n               << \"; Radius: \" << std::sqrt(b.radius_sq());\n    }\n\n   private:\n    size_type idx_;\n    tree_type* tree_;\n    friend box_iterator;\n    Box(size_type idx, const tree_type* tree)\n        : idx_(idx), tree_(const_cast<tree_type*>(tree)) {\n      FMMTL_ASSERT(idx_ < tree_->boxes());\n    }\n    inline BoxData& data() const {\n      return tree_->box_data_[idx_];\n    }\n    friend class BallTree;\n  };\n\n public:\n\n  /** Construct a tree encompassing a bounding box\n   * and insert a range of points */\n  template <typename Range>\n  BallTree(const Range& rng, size_type n_crit = 256,\n           typename std::enable_if<has_range_iterator<Range>::value>::type* = 0)\n      : BallTree(rng.begin(), rng.end(), n_crit) {\n  }\n\n  /** Construct an tree encompassing a bounding box\n   * and insert a range of points */\n  template <typename PointIter>\n  BallTree(PointIter first, PointIter last, size_type n_crit = 256) {\n    insert(first, last, n_crit);\n  }\n\n  /** Return the Bounding Box that this BallTree encompasses */\n  BoundingSphere<point_type> bounding_sphere() const {\n    return box_data_[0].bounding_sphere_;\n  }\n\n  /** Return the center of this BallTree */\n  point_type center() const {\n    return root().center();\n  }\n\n  /** The number of bodies contained in this tree */\n  inline size_type size() const {\n    return permute_.size();\n  }\n  /** The number of bodies contained in this tree */\n  inline size_type bodies() const {\n    return size();\n  }\n\n  /** The number of boxes contained in this tree */\n  inline size_type boxes() const {\n    return box_data_.size();\n  }\n\n  /** The number of boxes contained in level L of this tree */\n  inline size_type boxes(size_type L) const {\n    return (1 << L);\n  }\n\n  /** The maximum level of any box in this tree */\n  inline size_type levels() const {\n    return std::log2(boxes());  // XXX: Slow?\n  }\n\n  /** Returns true if the box is contained in this tree, false otherwise */\n  inline bool contains(const box_type& box) const {\n    return this == box.tree_;\n  }\n  /** Returns true if the body is contained in this tree, false otherwise */\n  inline bool contains(const body_type& body) const {\n    return this == body.tree_;\n  }\n\n  /** Return the root box of this tree */\n  box_type root() const {\n    return Box(0, this);\n  }\n  /** Return a box given its index */\n  box_type box(const size_type idx) const {\n    FMMTL_ASSERT(idx < box_data_.size());\n    return Box(idx, this);\n  }\n  /** Return a body given its index */\n  body_type body(const size_type idx) const {\n    FMMTL_ASSERT(idx < size());\n    return Body(idx, this);\n  }\n  /** Return an iterator to the first body in this tree */\n  body_iterator body_begin() const {\n    return body_iterator(0, this);\n  }\n  /** Return an iterator one past the last body in this tree */\n  body_iterator body_end() const {\n    return body_iterator(bodies(), this);\n  }\n  /** Return an iterator to the first box in this tree */\n  box_iterator box_begin() const {\n    return box_iterator(0, this);\n  }\n  /** Return an iterator one past the last box in this tree */\n  box_iterator box_end() const {\n    return box_iterator(boxes(), this);\n  }\n  /** Return an iterator to the first box at level L in this tree\n   * @pre L < levels()\n   */\n  box_iterator box_begin(size_type L) const {\n    FMMTL_ASSERT(L < levels());\n    return box_iterator((1 << L) - 1, this);\n  }\n  /** Return an iterator one past the last box at level L in this tree\n   * @pre L < levels()\n   */\n  box_iterator box_end(size_type L) const {\n    FMMTL_ASSERT(L < levels());\n    return box_iterator((1 << (L+1)) - 1, this);\n  }\n\n  template <typename RandomAccessIter>\n  struct body_permuted_iterator {\n    typedef typename std::vector<size_type>::const_iterator permute_iter;\n    typedef boost::permutation_iterator<RandomAccessIter, permute_iter> type;\n  };\n\n  /** Tranform (permute) an iterator so its traversal follows the same order as\n   * the bodies contained in this tree\n   */\n  template <typename RandomAccessIter>\n  typename body_permuted_iterator<RandomAccessIter>::type\n  body_permute(RandomAccessIter it, const body_iterator& bi) const {\n    return boost::make_permutation_iterator(it, permute_.cbegin() + bi.index());\n  }\n\n  /** Tranform (permute) an iterator so its traversal follows the same order as\n   * the bodies contained in this tree\n   *\n   * Specialized for bi = body_begin().\n   */\n  template <typename RandomAccessIter>\n  typename body_permuted_iterator<RandomAccessIter>::type\n  body_permute(RandomAccessIter it) const {\n    return body_permute(it, body_begin());\n  }\n\n  /** Write a BallTree to an output stream */\n  friend std::ostream& operator<<(std::ostream& s, const BallTree& t) {\n    struct {\n      std::ostream& print(std::ostream& s, const box_type& box) {\n        s << std::string(2*box.level(), ' ') << box;\n        if (!box.is_leaf())\n          for (auto ci = box.child_begin(); ci != box.child_end(); ++ci)\n            print(s << \"\\n\", *ci);\n        return s;\n      }\n    } recursive_box;\n\n    return recursive_box.print(s, t.root());\n  }\n\n private:\n  //! TODO: Make dynamic and public?\n  template <typename PointIter>\n  void insert(PointIter p_first, PointIter p_last, size_type NCRIT) {\n    FMMTL_LOG(\"BallTree Insert\");\n\n    assert(p_first != p_last);\n\n    // Create a point-idx pair vector\n    typedef typename std::iterator_traits<PointIter>::value_type point_i_type;\n\n    // XXX: Generalize?\n    static_assert(std::is_same<point_i_type, point_type>::value,\n                  \"PointIter value_type must be point_type\");\n\n    typedef std::pair<point_type, unsigned> point_t;\n\n    std::vector<point_t> point;\n    // If iterators are random access, we can reserve space efficiently\n    if (std::is_same<typename std::iterator_traits<PointIter>::iterator_category,\n        std::random_access_iterator_tag>::value)\n      point.reserve(std::distance(p_first, p_last));\n\n    // Copy to point-idx pair\n    unsigned idx = 0;\n    for (PointIter pi = p_first; pi != p_last; ++pi, ++idx) {\n      point.emplace_back(*pi, idx);\n    }\n    permute_.reserve(point.size());\n\n    // Helper std::pair projection operator\n    struct pair2point {\n      point_type& operator()(point_t& p) const { return p.first; }\n    };\n    using proj = boost::transform_iterator<pair2point, decltype(point.begin())>;\n\n    // The number of leaf boxes that will be created\n    // (Smallest power of two greater than or equal to ceil(N/NCRIT))\n    unsigned leaves = ceil_pow_2((point.size() + NCRIT - 1) / NCRIT);\n    unsigned levels = std::log2(leaves);\n\n    // Reserve the number of boxes that will be added\n    box_data_.reserve(2*leaves - 1);\n\n    // Push the root sphere which contains all points\n    box_data_.emplace_back(0, size_type(point.size()),\n                           approx_bounding_sphere(proj(point.begin()),\n                                                  proj(point.end())));\n\n    // For every box that is created\n    unsigned end_k = (1 << levels) - 1;\n    for (unsigned k = 0; k < end_k; ++k) {\n      // The range of points in this box\n      auto p_begin = point.begin() + box_data_[k].body_begin_;\n      auto p_end   = point.begin() + box_data_[k].body_end_;\n\n      // Invariant of helper functions\n      assert(p_begin != p_end);\n\n      // Compute the furthest point from the center\n      const point_type& p1 = furthest_point_from(proj(p_begin), proj(p_end),\n                                                 box(k).center());\n      // Compute the furthest point from point1\n      const point_type& p2 = furthest_point_from(proj(p_begin), proj(p_end),\n                                                 p1);\n\n      // Partition on the median: balanced tree, but worse spheres\n      auto p_mid = p_begin + (p_end - p_begin) / 2;\n      point_type r = p2 - p1;\n      std::nth_element(p_begin, p_mid, p_end,\n                       [&](const point_t& a, const point_t& b) {\n           return inner_prod(a.first-p1, r) < inner_prod(b.first-p1, r);\n        });\n\n      /*\n      // Partition on proximity: better spheres, potentially unbalanced\n      // Would need to account for the possibility of empty boxes\n      auto p_mid = std::partition(p_begin, p_end, [&] (const point_t& a) {\n          return norm_2_sq(a.first-p1) < norm_2_sq(a.first-p2);\n        });\n      */\n\n      // Record the child boxes\n      size_type mid = p_mid - point.begin();\n      box_data_.emplace_back(box_data_[k].body_begin_, mid,\n                             approx_bounding_sphere(proj(p_begin), proj(p_mid)));\n\n      box_data_.emplace_back(mid, box_data_[k].body_end_,\n                             approx_bounding_sphere(proj(p_mid), proj(p_end)));\n    }\n\n    // Assert no re-allocation\n    assert(box_data_.size() <= 2*leaves-1);\n\n    // Extract the permutation idx\n    for (const point_t& p : point)\n      permute_.push_back(p.second);\n  }\n\n  /** Calculate the approximate bounding sphere of a set of points\n   * using the Points Closest to Furthest Pair approach.\n   */\n  template <typename PointIter>\n  BoundingSphere<point_type> approx_bounding_sphere(PointIter first,\n                                                    PointIter last) {\n    auto n = std::distance(first, last);\n    point_type center = std::accumulate(first, last, point_type{}) / n;\n\n    double r_sq = std::accumulate(first, last, double{},\n                                  [&] (double r_sq, point_type& p) {\n                                    return std::max(r_sq, norm_2_sq(center-p));\n                                  });\n\n    return {center, r_sq};\n  }\n\n  /** Find the point in a set of points that is furthest away from a target point\n   */\n  template <typename PointIter>\n  const point_type& furthest_point_from(PointIter first,\n                                        PointIter last,\n                                        const point_type& target) {\n    using pair = std::pair<double, const point_type*>;\n    return *std::accumulate(first, last, pair{},\n                            [&] (const pair& r, const point_type& p) {\n                              return std::max(r, pair{norm_2_sq(target-p), &p});\n                            }).second;\n  }\n\n  // Just making sure for now\n  BallTree(const BallTree&) {};\n  void operator=(const BallTree&) {};\n};\n\n\n} // end namespace fmmtl\n", "meta": {"hexsha": "1c8992e9110511071932ac05acb9908ef1ebd89f", "size": 15686, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/fmmtl/fmmtl/tree/BallTree.hpp", "max_stars_repo_name": "sergeneren/BubbleH", "max_stars_repo_head_hexsha": "e018e5a008e101221a4f8a3bbb25e7ec03fc9662", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2019-10-06T17:25:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T23:01:13.000Z", "max_issues_repo_path": "source/fmmtl/fmmtl/tree/BallTree.hpp", "max_issues_repo_name": "sergeneren/BubbleH", "max_issues_repo_head_hexsha": "e018e5a008e101221a4f8a3bbb25e7ec03fc9662", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-08T18:44:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T07:48:31.000Z", "max_forks_repo_path": "source/fmmtl/fmmtl/tree/BallTree.hpp", "max_forks_repo_name": "sergeneren/BubbleH", "max_forks_repo_head_hexsha": "e018e5a008e101221a4f8a3bbb25e7ec03fc9662", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-10-07T16:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T01:09:47.000Z", "avg_line_length": 32.0777096115, "max_line_length": 81, "alphanum_fraction": 0.6310085426, "num_tokens": 3816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24347137846299532}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n#ifndef BOOST_MP_INTEGER_HPP\n#define BOOST_MP_INTEGER_HPP\n\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/multiprecision/detail/bitscan.hpp>\n\nnamespace boost{\nnamespace multiprecision{\n\ntemplate <class Integer, class I2>\ntypename enable_if_c<is_integral<Integer>::value && is_integral<I2>::value, Integer&>::type\n   multiply(Integer& result, const I2& a, const I2& b)\n{\n   return result = static_cast<Integer>(a) * static_cast<Integer>(b);\n}\ntemplate <class Integer, class I2>\ntypename enable_if_c<is_integral<Integer>::value && is_integral<I2>::value, Integer&>::type\n   add(Integer& result, const I2& a, const I2& b)\n{\n   return result = static_cast<Integer>(a) + static_cast<Integer>(b);\n}\ntemplate <class Integer, class I2>\ntypename enable_if_c<is_integral<Integer>::value && is_integral<I2>::value, Integer&>::type\n   subtract(Integer& result, const I2& a, const I2& b)\n{\n   return result = static_cast<Integer>(a) - static_cast<Integer>(b);\n}\n\ntemplate <class Integer>\ntypename enable_if_c<is_integral<Integer>::value>::type divide_qr(const Integer& x, const Integer& y, Integer& q, Integer& r)\n{\n   q = x / y;\n   r = x % y;\n}\n\ntemplate <class I1, class I2>\ntypename enable_if_c<is_integral<I1>::value && is_integral<I2>::value, I2>::type integer_modulus(const I1& x, I2 val)\n{\n   return static_cast<I2>(x % val);\n}\n\nnamespace detail{\n//\n// Figure out the kind of integer that has twice as many bits as some builtin\n// integer type I.  Use a native type if we can (including types which may not\n// be recognised by boost::int_t because they're larger than boost::long_long_type),\n// otherwise synthesize a cpp_int to do the job.\n//\ntemplate <class I>\nstruct double_integer\n{\n   static const unsigned int_t_digits =\n      2 * sizeof(I) <= sizeof(boost::long_long_type) ? std::numeric_limits<I>::digits * 2 : 1;\n\n   typedef typename mpl::if_c<\n      2 * sizeof(I) <= sizeof(boost::long_long_type),\n      typename mpl::if_c<\n         is_signed<I>::value,\n         typename boost::int_t<int_t_digits>::least,\n         typename boost::uint_t<int_t_digits>::least\n      >::type,\n      typename mpl::if_c<\n         2 * sizeof(I) <= sizeof(double_limb_type),\n         typename mpl::if_c<\n            is_signed<I>::value,\n            signed_double_limb_type,\n            double_limb_type\n         >::type,\n         number<cpp_int_backend<sizeof(I)*CHAR_BIT*2, sizeof(I)*CHAR_BIT*2, (is_signed<I>::value ? signed_magnitude : unsigned_magnitude), unchecked, void> >\n      >::type\n   >::type type;\n};\n\n}\n\ntemplate <class I1, class I2, class I3>\ntypename enable_if_c<is_integral<I1>::value && is_unsigned<I2>::value && is_integral<I3>::value, I1>::type\n   powm(const I1& a, I2 b, I3 c)\n{\n   typedef typename detail::double_integer<I1>::type double_type;\n\n   I1 x(1), y(a);\n   double_type result;\n\n   while(b > 0)\n   {\n      if(b & 1)\n      {\n         multiply(result, x, y);\n         x = integer_modulus(result, c);\n      }\n      multiply(result, y, y);\n      y = integer_modulus(result, c);\n      b >>= 1;\n   }\n   return x % c;\n}\n\ntemplate <class I1, class I2, class I3>\ninline typename enable_if_c<is_integral<I1>::value && is_signed<I2>::value && is_integral<I3>::value, I1>::type\n   powm(const I1& a, I2 b, I3 c)\n{\n   if(b < 0)\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"powm requires a positive exponent.\"));\n   }\n   return powm(a, static_cast<typename make_unsigned<I2>::type>(b), c);\n}\n\ntemplate <class Integer>\ntypename enable_if_c<is_integral<Integer>::value, unsigned>::type lsb(const Integer& val)\n{\n   if(val <= 0)\n   {\n      if(val == 0)\n      {\n         BOOST_THROW_EXCEPTION(std::range_error(\"No bits were set in the operand.\"));\n      }\n      else\n      {\n         BOOST_THROW_EXCEPTION(std::range_error(\"Testing individual bits in negative values is not supported - results are undefined.\"));\n      }\n   }\n   return detail::find_lsb(val);\n}\n\ntemplate <class Integer>\ntypename enable_if_c<is_integral<Integer>::value, unsigned>::type msb(Integer val)\n{\n   if(val <= 0)\n   {\n      if(val == 0)\n      {\n         BOOST_THROW_EXCEPTION(std::range_error(\"No bits were set in the operand.\"));\n      }\n      else\n      {\n         BOOST_THROW_EXCEPTION(std::range_error(\"Testing individual bits in negative values is not supported - results are undefined.\"));\n      }\n   }\n   return detail::find_msb(val);\n}\n\ntemplate <class Integer>\ntypename enable_if_c<is_integral<Integer>::value, bool>::type bit_test(const Integer& val, unsigned index)\n{\n   Integer mask = 1;\n   if(index >= sizeof(Integer) * CHAR_BIT)\n      return 0;\n   if(index)\n      mask <<= index;\n   return val & mask ? true : false;\n}\n\ntemplate <class Integer>\ntypename enable_if_c<is_integral<Integer>::value, Integer&>::type bit_set(Integer& val, unsigned index)\n{\n   Integer mask = 1;\n   if(index >= sizeof(Integer) * CHAR_BIT)\n      return val;\n   if(index)\n      mask <<= index;\n   val |= mask;\n   return val;\n}\n\ntemplate <class Integer>\ntypename enable_if_c<is_integral<Integer>::value, Integer&>::type bit_unset(Integer& val, unsigned index)\n{\n   Integer mask = 1;\n   if(index >= sizeof(Integer) * CHAR_BIT)\n      return val;\n   if(index)\n      mask <<= index;\n   val &= ~mask;\n   return val;\n}\n\ntemplate <class Integer>\ntypename enable_if_c<is_integral<Integer>::value, Integer&>::type bit_flip(Integer& val, unsigned index)\n{\n   Integer mask = 1;\n   if(index >= sizeof(Integer) * CHAR_BIT)\n      return val;\n   if(index)\n      mask <<= index;\n   val ^= mask;\n   return val;\n}\n\ntemplate <class Integer>\ntypename enable_if_c<is_integral<Integer>::value, Integer>::type sqrt(const Integer& x, Integer& r)\n{\n   //\n   // This is slow bit-by-bit integer square root, see for example\n   // http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_.28base_2.29\n   // There are better methods such as http://hal.inria.fr/docs/00/07/28/54/PDF/RR-3805.pdf\n   // and http://hal.inria.fr/docs/00/07/21/13/PDF/RR-4475.pdf which should be implemented\n   // at some point.\n   //\n   Integer s = 0;\n   if(x == 0)\n   {\n      r = 0;\n      return s;\n   }\n   int g = msb(x);\n   if(g == 0)\n   {\n      r = 1;\n      return s;\n   }\n\n   Integer t = 0;\n   r = x;\n   g /= 2;\n   bit_set(s, g);\n   bit_set(t, 2 * g);\n   r = x - t;\n   --g;\n   do\n   {\n      t = s;\n      t <<= g + 1;\n      bit_set(t, 2 * g);\n      if(t <= r)\n      {\n         bit_set(s, g);\n         r -= t;\n      }\n      --g;\n   }\n   while(g >= 0);\n   return s;\n}\n\ntemplate <class Integer>\ntypename enable_if_c<is_integral<Integer>::value, Integer>::type sqrt(const Integer& x)\n{\n   Integer r;\n   return sqrt(x, r);\n}\n\n}} // namespaces\n\n#endif\n", "meta": {"hexsha": "29699d1b2411aec2e5f723d8cc729aaf32f17f0a", "size": 6849, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/multiprecision/integer.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/multiprecision/integer.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/multiprecision/integer.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 27.1785714286, "max_line_length": 157, "alphanum_fraction": 0.6403854577, "num_tokens": 1842, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2431884100770308}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_INTEGRATION_FUNCTIONS_COMMON_QUADGK_HPP_INCLUDED\n#define NT2_INTEGRATION_FUNCTIONS_COMMON_QUADGK_HPP_INCLUDED\n\n#include <nt2/integration/functions/quadgk.hpp>\n#include <nt2/integration/output.hpp>\n#include <nt2/integration/options.hpp>\n#include <nt2/integration/waypoints.hpp>\n#include <nt2/integration/fudge.hpp>\n#include <nt2/integration/order.hpp>\n#include <nt2/integration/split.hpp>\n#include <nt2/integration/midparea.hpp>\n#include <nt2/integration/int_transforms.hpp>\n\n#include <nt2/include/constants/half.hpp>\n#include <nt2/include/constants/two.hpp>\n#include <nt2/include/constants/zero.hpp>\n\n\n#include <nt2/include/functions/abs.hpp>\n#include <nt2/include/functions/asin.hpp>\n#include <nt2/include/functions/asinh.hpp>\n#include <nt2/include/functions/average.hpp>\n#include <nt2/include/functions/cast.hpp>\n#include <nt2/include/functions/diff.hpp>\n#include <nt2/include/functions/fliplr.hpp>\n#include <nt2/include/functions/flipud.hpp>\n#include <nt2/include/functions/globalsum.hpp>\n#include <nt2/include/functions/isempty.hpp>\n#include <nt2/include/functions/is_finite.hpp>\n#include <nt2/include/functions/is_inf.hpp>\n#include <nt2/include/functions/is_not_finite.hpp>\n#include <nt2/include/functions/linspace.hpp>\n#include <nt2/include/functions/logical_not.hpp>\n#include <nt2/include/functions/max.hpp>\n#include <nt2/include/functions/mean.hpp>\n#include <nt2/include/functions/mtimes.hpp>\n#include <nt2/include/functions/globalasum1.hpp>\n#include <nt2/include/functions/numel.hpp>\n#include <nt2/include/functions/rowvect.hpp>\n#include <nt2/include/functions/size.hpp>\n#include <nt2/include/functions/sin.hpp>\n#include <nt2/include/functions/sx.hpp>\n#include <nt2/include/functions/tanh.hpp>\n#include <nt2/include/functions/vertcat.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/sdk/complex/meta/is_complex.hpp>\n\n#include <boost/mpl/bool.hpp>\n\nnamespace nt2 { namespace details\n{\n  template<class T, class V> class quadgk_impl\n  {\n  public :\n    typedef T                                                                input_t;\n    typedef typename meta::as_logical<input_t>::type                            bi_t;\n    typedef V                                                                value_t;\n    typedef typename meta::is_complex<value_t>::type                     v_is_cplx_t;\n    typedef typename boost::mpl::if_<v_is_cplx_t,value_t,input_t>::type     result_t;\n    typedef typename meta::as_real<value_t>::type                             real_t;\n    typedef details::integration_settings<T, V, tag::quadgk_>                    o_t;\n    typedef container::table<value_t>                                         vtab_t;\n    typedef container::table<input_t>                                         itab_t;\n    typedef container::table<real_t>                                          rtab_t;\n    typedef container::table<result_t>                                      restab_t;\n    typedef container::table<bi_t>                                           bitab_t;\n\n    quadgk_impl() :  errbnd_(Nan<real_t>()),\n                     fcnt_(0),\n                     maxfcnt_(Valmax<size_t>()),\n                     warn_(0),\n                     res_(){}\n    ~quadgk_impl() {}\n\n    size_t nbeval()           const { return fcnt_;             }\n    real_t lasterror()        const { return errbnd_;           }\n    bool   ok()               const { return warn_ == 0;        }\n    const restab_t & result() const { return res_;              }\n    void setwarn(size_t w)          { if(w > warn_) warn_ =  w; }\n    size_t  warn()            const { return warn_;             }\n\n    template < class FUNC, class X>\n    void compute( const FUNC& f, const X & x, const o_t & o,\n                  const boost::mpl::false_ & choice) // cplx path integration\n    {\n      init(o, x,  choice);\n      interval_ = tinterval_;\n      vadapt(transform<FUNC, details::no_transform, input_t, value_t>(f, a_, b_, interval_));\n    }\n\n    template < class FUNC, class X>\n    void compute( const FUNC& f, const X & x, const o_t & o,\n                  const boost::mpl::true_ & choice) // real interval integration\n    {\n      init(o, x, choice);\n      if (a_ == b_) //quick return\n      {\n        result_t r = nt2::multiplies(f(a_), Zero<input_t>());\n          //result_t r = details::midparea<result_t, value_t>(f, tinterval_(begin_), tinterval_(end_));\n        res_ = r;\n        errbnd_ = nt2::abs(r);\n        return;\n      }\n      interval_ = tinterval_;\n      adjust_and_call(f);\n      if(reversedir_) res_ = -res_;\n    }\n  private :\n    real_t      errbnd_;\n    size_t        fcnt_;\n    size_t     maxfcnt_;\n    size_t  maxintvcnt_;\n    size_t        warn_;\n    real_t      abstol_;\n    real_t      reltol_;\n    restab_t       res_;\n    real_t        hmin_;\n    bool    reversedir_;\n    itab_t   tinterval_; //original points\n    itab_t    interval_; //transformed points,  to reduce integration to a subinterval of [-1, 1]\n    input_t      a_, b_;\n    bool firstfunceval_;\n    size_t          nb_;\n    static const size_t minintervalcount_ = 10; // Minimum number subintervals to start.\n\n//  Gauss-Kronrod (7,15) pair. Use symmetry in defining nodes and weights.\n    static const itab_t& nodes()\n    {\n      static const input_t gk[7] = {\n        input_t(0.2077849550078985), input_t(0.4058451513773972), input_t(0.5860872354676911),\n        input_t(0.7415311855993944), input_t(0.8648644233597691), input_t(0.9491079123427585),\n        input_t(0.9914553711208126)};\n      static const itab_t k(of_size(7, 1), &gk[0], &gk[7]);\n      static const itab_t k15 =  nt2::catv(nt2::catv(-flipud(k), nt2::Zero<input_t>()),k);\n      return k15;\n    }\n\n    static const vtab_t& wt()\n    {\n      static const value_t pwt[7] = {\n        value_t(0.2044329400752989), value_t(0.1903505780647854), value_t(0.1690047266392679),\n        value_t(0.1406532597155259), value_t(0.1047900103222502), value_t(0.06309209262997855),\n        value_t(0.02293532201052922) };\n      static const vtab_t wt(of_size(1, 7), &pwt[0], &pwt[7]);\n      static const vtab_t wt15 = nt2::cath(nt2::cath(fliplr(wt),value_t(0.2094821410847278)),wt);\n      return wt15;\n    }\n\n    static const vtab_t& ewt()\n    {\n      static const value_t pwt7[7] = {\n        value_t(0),value_t(0.3818300505051189),value_t(0),value_t(0.2797053914892767),\n        value_t(0),value_t(0.1294849661688697),value_t(0)\n      };\n      static const vtab_t wt7(of_size(1, 7), &pwt7[0], &pwt7[7]);\n      static const vtab_t ewt15 = wt()-nt2::cath(nt2::cath(fliplr(wt7),value_t(0.4179591836734694)),wt7);\n      return ewt15;\n    }\n\n    template < class X >\n    void init( const o_t & o, const X& x, const boost::mpl::false_ & )\n    {\n      details::prepare_waypoints(o, x, tinterval_);\n      a_ = tinterval_(begin_);\n      b_ = tinterval_(end_);\n      abstol_ = o.abstol;\n      reltol_ = o.reltol;\n      warn_ = 0;\n      fcnt_ = 0;\n      maxfcnt_ = Valmax<size_t>();\n      maxintvcnt_ = o.maxintvcnt;\n      errbnd_ = nt2::Inf<real_t>();\n    }\n\n    template < class X >\n    void init( const o_t & o, const X& x, const boost::mpl::true_ & )//real path integration\n    {\n      details::prepare_waypoints(o, x, tinterval_);\n      reversedir_ = details::order_points(tinterval_, true);\n      a_ = tinterval_(begin_);\n      b_ = tinterval_(end_);\n      abstol_ = o.abstol;\n      reltol_ = o.reltol;\n      warn_ = 0;\n      fcnt_ = 0;\n      maxfcnt_ = Valmax<size_t>();\n      maxintvcnt_ = o.maxintvcnt;\n      errbnd_ = nt2::Inf<real_t>();\n      firstfunceval_ = true;\n    }\n\n    template < class FUNC >\n    inline bool check(FUNC f, bool t, size_t w, const result_t& q)\n    {\n      if (t)\n      {\n        fcnt_ = f.fcnt();\n        res_ = q;\n        setwarn(w);\n      }\n      return t;\n    }\n    template < class FUNC >\n    void vadapt(FUNC f)\n    {\n      real_t pathlen;\n      itab_t tmp0;\n      details::split(f.interval_, minintervalcount_, tmp0, pathlen);\n      interval_ = tmp0;\n      if (pathlen == 0)\n      {\n        input_t tmp =  nt2::multiplies(f.interval_(end_), nt2::Half<real_t>());\n        input_t xx =  nt2::fma(f.interval_(begin_), nt2::Half<real_t>(), tmp);\n        input_t d = (f.interval_(end_)-f.interval_(begin_));\n\n        result_t r = nt2::multiplies(f(xx), d);\n        res_ = r;\n        errbnd_ =  nt2::abs(r);\n        return;\n      }\n      // Initialize array of subintervals of [a,b].\n      itab_t subs = nt2::catv(interval_(nt2::_(begin_, end_-1)),\n                              interval_(nt2::_(begin_+1, end_)));\n      // Initialize partial sums.\n      result_t q_ok = nt2::Zero<result_t>();\n      result_t err_ok = nt2::Zero<result_t>();\n      // Initialize main loop\n      nb_ = 0;\n      while (true)\n      {\n        ++nb_;\n        // subs contains subintervals of [a,b] where the integral is not\n        // sufficiently accurate. The first row of SUBS holds the left end\n        // points and the second row, the corresponding right endpoints.\n        itab_t midpt = nt2::mean(subs);             // midpoints of the subintervals\n        itab_t halfh = diff(subs)*Half<input_t>();  // half the lengths of the subintervals\n\n        itab_t x = nt2::rowvect(nt2::sx(nt2::tag::plus_(),nt2::mtimes(nodes(), halfh),midpt));\n        //        BOOST_AUTO_TPL(fx, f(x));\n        vtab_t fx = f(x);\n        // Quit if mesh points are too close.\n        fx.resize(nt2::of_size(nt2::numel(wt()), numel(fx)/numel(wt())));\n        // Quantities for subintervals.\n        restab_t qsubs = nt2::mtimes(wt(), fx)*halfh;\n        restab_t errsubs = nt2::mtimes(ewt(), fx)* halfh;\n        // Calculate current values of q and tol.\n        result_t q = nt2::globalsum(qsubs) + q_ok;\n        if (check(f, f.tooclose(), 6, q)) break;\n        real_t  tol = max(abstol_,reltol_*nt2::abs(q));\n        // Locate subintervals where the approximate integrals are\n        // sufficiently accurate and use them to update the partial\n        // error sum.\n        bitab_t ff= nt2::le(nt2::abs(errsubs), (Two<real_t>()*tol/pathlen)*nt2::abs(halfh));\n        bitab_t notff = nt2::logical_not(ff);\n        err_ok += nt2::globalsum(errsubs(ff));\n        // Remove errsubs entries for subintervals with accurate\n        // approximations.\n        restab_t errsubs1 = nt2::rowvect(errsubs(notff)); errsubs =  errsubs1; //ALIASING CAN BE AVOIDED PERHAPS\n        // The approximate error bound is constructed by adding the\n        // approximate error bounds for the subintervals with accurate\n        // approximations to the 1-norm of the approximate error bounds\n        // for the remaining subintervals.  This guards against\n        // excessive cancellation of the errors of the remaining\n        // subintervals.\n        errbnd_ = nt2::abs(err_ok) + nt2::globalasum1(errsubs);\n        // Check for nonfinites.\n        if (check(f, is_not_finite(q) && is_finite(errbnd_), 3, q)) break; // Infinite or Not-a-Number value encountered.\n        if (check(f, errbnd_ <= tol, 0, q)) break;                         // tolerance reached: convergence\n        //        if (check(f, f.fcnt() > maxfcnt_, 5, q)) break;          // Max evaluation number reached\n        // Remove subintervals with accurate approximations.\n        itab_t subs_tmp = subs(nt2::_, notff); subs = subs_tmp;\n        if (check(f, nt2::isempty(subs), 0, q)) break;                     // All subs got required precision\n        // Update the partial sum for the integral.\n        q_ok +=  nt2::globalsum(qsubs(ff));\n        // Split the remaining subintervals in half. Quit if splitting\n        // results in too many subintervals.\n        size_t nsubs = 2*nt2::size(subs,2);\n        if (check(f, nsubs > maxintvcnt_, 2, q)) break;                    //Reached the limit on the maximum number of intervals in use.\n        itab_t midpt1 = nt2::rowvect(midpt(notff)); midpt = midpt1;\n        itab_t z = catv(catv(catv(subs(begin_,nt2::_),midpt),midpt),subs(end_,nt2::_));\n        subs = reshape(z,2,numel(z)/2);\n      }\n    }\n\n    template < class F >\n    inline void adjust_and_call(const  F &f)\n    {\n      bool fina = nt2::is_finite(a_);\n      bool finb = nt2::is_finite(b_);\n      if(fina && finb)\n      {\n        vadapt(transform<F, details::fina_finb, input_t, value_t>(f, a_, b_, interval_));\n      }\n      else\n      {\n        bool infb = nt2::is_inf(b_);\n        if (fina && infb)\n        {\n          vadapt(transform<F, details::fina_infb, input_t, value_t>(f, a_, b_, interval_));\n        }\n        else\n        {\n          bool infa = nt2::is_inf(a_);\n          if (infa && finb)\n          {\n            vadapt(transform<F, details::infa_finb, input_t, value_t>(f, a_, b_, interval_));\n          }\n          else if (infa && infb)\n          {\n            vadapt(transform<F, details::infa_infb, input_t, value_t>(f, a_, b_, interval_));\n          }\n          else //is_nan(a) || is_nan(b)\n          {\n            result_t r = Nan<result_t>();\n            errbnd_ = nt2::abs(r);\n            fcnt_ = 1;\n          }\n        }\n      }\n    }\n  };\n} }\n\n\nnamespace nt2 { namespace ext\n                {\n                  BOOST_DISPATCH_IMPLEMENT  ( quadgk_, tag::cpu_\n                                              , (F)(X)(O)\n                                              , (unspecified_< F >)\n                                              ((ast_<X, nt2::container::domain>))\n                                              (unspecified_<O>)\n    )\n  {\n    typedef typename O::value_t                                             value_t;\n    typedef typename O::input_t                                             input_t;\n    typedef typename O::real_t                                               real_t;\n    typedef typename O::result_t                                           result_t;\n    typedef typename O::restab_t                                           restab_t;\n    typedef typename boost::is_same<input_t,real_t>::type           input_is_real_t;\n    typedef nt2::integration::output<restab_t,real_t>                   result_type;\n\n    result_type operator()(F f, X const& x, O const& o)\n    {\n      details::quadgk_impl<input_t, value_t> q;\n      q.compute(f, x, o, input_is_real_t());\n      result_type that = {q.result(), q.lasterror(),q.nbeval(),q.ok(),q.warn()};\n      return that;\n    }\n  };\n} }\n#endif\n", "meta": {"hexsha": "8809dcf21bdfcfce59b4c87b5a6d4d4394dc4fd9", "size": 14750, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/integration/include/nt2/integration/functions/common/quadgk.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/integration/include/nt2/integration/functions/common/quadgk.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/integration/include/nt2/integration/functions/common/quadgk.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 40.9722222222, "max_line_length": 137, "alphanum_fraction": 0.573220339, "num_tokens": 3964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352403, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.24318841007703074}}
{"text": "#include <cstdlib>\n#include <sstream>\n#include <iostream>\n#include <vector>\n#include <limits>\n#include <cmath>\n\n#if HAVE_NEW_CXX\n# include <unordered_map>\n# include <unordered_set>\n#else\n# include <tr1/unordered_map>\n# include <tr1/unordered_set>\nnamespace std { using std::tr1::unordered_map; using std::tr1::unordered_set; }\n#endif\n\n#include <signal.h>\n\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"json_feature_map_lexer.h\"\n#include \"fdict.h\"\n#include \"feature_map.h\"\n#include \"prob.h\"\n#include \"filelib.h\"\n\n#include <adept.h>\n#include <Eigen/Eigen>\n\nusing adept::adouble;\n\n#define INPUT_DIM 20\ntemplate <typename F> using FVector = Eigen::Matrix<F,INPUT_DIM,1>;\n\nusing namespace std;\nnamespace po = boost::program_options;\n\nvolatile bool* requested_stop = NULL;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"x,x\", po::value<vector<string> >(), \"Files containing training instance features\")\n        (\"y,y\", po::value<string>(), \"File containing training instance responses (if unspecified, do prediction only)\")\n        (\"tx\", po::value<vector<string> >(), \"Files containing training instance features\")\n        (\"ty\", po::value<string>(), \"File containing training instance responses (if unspecified, do prediction only)\")\n        (\"z,z\", po::value<string>(), \"Write learned weights to this file (optional)\")\n        (\"l1\",po::value<double>()->default_value(0.0), \"l_1 regularization strength\")\n        (\"l2\",po::value<double>()->default_value(1e-10), \"l_2 regularization strength\")\n        (\"help,h\", \"Help\");\n  po::options_description dcmdline_options;\n  dcmdline_options.add(opts);\n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"help\")) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nenum RegressionType { kLINEAR, kLOGISTIC };\n\nstruct TrainingInstance {\n  FrozenFeatureMap x;\n  union {\n    unsigned label;  // for categorical & ordinal predictions\n    float value;     // for continuous predictions\n  } y;\n};\n\nstruct ReaderHelper {\n  explicit ReaderHelper(vector<TrainingInstance>* xyp,\n                        bool h,\n                        vector<string>* iids) : xy_pairs(xyp), lc(), flag(), has_labels(h), ids(iids), merge() {}\n  unordered_map<string, unsigned> id2ind;\n  FeatureMapStorage* fms;\n  vector<TrainingInstance>* xy_pairs;\n  int lc;\n  bool flag;\n  bool has_labels;\n  vector<string>* ids;\n  vector<bool> merged;\n  bool merge;\n};\n\nvoid ReaderCB(const string& id,\n              const std::pair<int,float>* begin,\n              const std::pair<int,float>* end,\n              void* extra) {\n  ReaderHelper& rh = *reinterpret_cast<ReaderHelper*>(extra);\n  ++rh.lc;\n  if (rh.lc % 1000  == 0) { cerr << '.'; rh.flag = true; }\n  if (rh.lc % 50000 == 0) { cerr << \" [\" << rh.lc << \"]\\n\"; rh.flag = false; }\n  if (rh.ids && !rh.merge) rh.ids->push_back(id);\n  if (rh.has_labels) {\n    const unordered_map<string, unsigned>::iterator it = rh.id2ind.find(id);\n    if (it == rh.id2ind.end()) {\n      cerr << \"\\nUnlabeled example in line \" << rh.lc << \" (key=\" << id << ')' << endl;\n      abort();\n    } else {\n      if (rh.merge) {\n        rh.merged[it->second - 1] = true;\n        const FrozenFeatureMap& prev = (*rh.xy_pairs)[it->second - 1].x;\n        (*rh.xy_pairs)[it->second - 1].x = rh.fms->AddFeatureMap(begin,end,prev);\n      } else {\n        (*rh.xy_pairs)[it->second - 1].x = rh.fms->AddFeatureMap(begin,end);\n      }\n    }\n  } else {\n    TrainingInstance x_no_y;\n    if (rh.merge) {\n      if (!rh.ids) {\n        cerr << \"Missing IDs\\n\";\n        abort();\n      }\n      unsigned& ind = rh.id2ind[id];\n      rh.merged[ind - 1] = true;\n      const FrozenFeatureMap& prev = (*rh.xy_pairs)[ind - 1].x;\n      (*rh.xy_pairs)[ind - 1].x = rh.fms->AddFeatureMap(begin,end,prev);\n    } else {\n      x_no_y.x = rh.fms->AddFeatureMap(begin,end);\n      unsigned& ind = rh.id2ind[id];\n      assert(ind == 0);\n      rh.xy_pairs->push_back(x_no_y);\n      ind = rh.xy_pairs->size();\n    }\n  }\n}\n\nvoid ReadLabeledInstances(const vector<string>& ffeats,\n                          const string& fresp,\n                          const RegressionType resptype,\n                          FeatureMapStorage* fms,\n                          vector<TrainingInstance>* xy_pairs,\n                          vector<string>* labels,\n                          vector<string>* instance_ids = NULL) {\n  bool flag = false;\n  xy_pairs->clear();\n  int lc = 0;\n  ReaderHelper rh(xy_pairs, fresp.size() > 0, instance_ids);\n  rh.merge = false;\n  unordered_map<string, unsigned> label2id;\n  if (fresp.size() == 0) {\n    cerr << \"No gold standard responses provided to learn from!\" << endl;\n  } else {\n    cerr << \"Reading responses from \" << fresp << \" ...\" << endl;\n    ReadFile fr(fresp);\n    for (unsigned i = 0; i < labels->size(); ++i)\n      label2id[(*labels)[i]] = i;\n    istream& in = *fr.stream();\n    string line;\n    while(getline(in, line)) {\n      ++lc;\n      if (lc % 1000 == 0) { cerr << '.'; flag = true; }\n      if (lc % 40000 == 0) { cerr << \" [\" << lc << \"]\\n\"; flag = false; }\n      if (line.size() == 0) continue;\n      if (line[0] == '#') {\n        if (line.size() > 1 && line[1] == '#') {\n          if (lc != 1) {\n            cerr << \"[WARNING] Line \" << lc << \" appears to be label declaration ... ignoring\\n\";\n          } else {\n            istringstream is(line);\n            string label;\n            is >> label;\n            while(is >> label) {\n              unordered_map<string, unsigned>::iterator it = label2id.find(label);\n              if (it == label2id.end()) {\n                it = label2id.insert(make_pair(label, labels->size())).first;\n                labels->push_back(label);\n              }\n            }\n          }\n        }\n        continue;\n      }\n      unsigned p = 0;\n      while (p < line.size() && line[p] != ' ' && line[p] != '\\t') { ++p; }\n      unsigned& ind = rh.id2ind[line.substr(0, p)];\n      if (ind != 0) { cerr << \"ID \" << line.substr(0, p) << \" duplicated in line \" << lc << endl; abort(); }\n      while (p < line.size() && (line[p] == ' ' || line[p] == '\\t')) { ++p; }\n      assert(p < line.size());\n      xy_pairs->push_back(TrainingInstance());\n      ind = xy_pairs->size();\n      switch (resptype) {\n        case kLINEAR:\n          xy_pairs->back().y.value = strtof(&line[p], 0);\n          break;\n        case kLOGISTIC:\n          {\n            unordered_map<string, unsigned>::iterator it = label2id.find(line.substr(p));\n            if (it == label2id.end()) {\n              const string label = line.substr(p);\n              it = label2id.insert(make_pair(label, labels->size())).first;\n              labels->push_back(label);\n            }\n            xy_pairs->back().y.label = it->second;  // label id\n          }\n          break;\n      }\n    }\n    if (flag) cerr << endl;\n    if (resptype == kLOGISTIC) {\n      cerr << \"LABELS:\";\n      for (unsigned j = 0; j < labels->size(); ++j)\n        cerr << \" \" << (*labels)[j];\n      cerr << endl;\n    }\n  }\n  FeatureMapStorage* pfms = NULL;\n  FeatureMapStorage* tfms = NULL;\n  for (unsigned i = 0; i < ffeats.size(); ++i) {\n    if (i == ffeats.size() - 1) {\n      pfms = tfms;\n      rh.fms = fms;\n    } else {\n      delete pfms;\n      pfms = tfms;\n      tfms = new FeatureMapStorage;\n      rh.fms = tfms;\n    }\n    if (pfms) {\n      rh.merge = true;\n      rh.merged.clear();\n      rh.merged.resize(rh.xy_pairs->size(), false);\n    }\n    const string& ffeat = ffeats[i];\n    cerr << \"Reading features from \" << ffeat << \" ...\" << endl;\n    ReadFile ff(ffeat);\n    JSONFeatureMapLexer::ReadRules(ff.stream(), ReaderCB, &rh);\n    if (pfms) {\n      for (unsigned j = 0; j < rh.xy_pairs->size(); ++j)\n        if (!rh.merged[j])\n          (*rh.xy_pairs)[j].x = rh.fms->AddFeatureMap(NULL, NULL, (*rh.xy_pairs)[j].x);\n    }\n    if (rh.flag) cerr << endl;\n  }\n  delete pfms;\n}\n\nvoid signal_callback_handler(int /* signum */) {\n  if (!requested_stop || *requested_stop) {\n    cerr << \"\\nReceived SIGINT again, quitting.\\n\";\n    _exit(1);\n  }\n  cerr << \"\\nReceived SIGINT terminating optimization early.\\n\";\n  *requested_stop = true;\n}\n\ntemplate <typename F>\nstruct Model {\n  Model(unsigned feats, unsigned labels) :\n      input_reps(feats, FVector<F>::Zero()), output_reps(labels, FVector<F>::Zero()) {}\n\n  // number of parameters\n  size_t size() const {\n    return input_reps.size() * input_reps[0].size() + output_reps.size() * output_reps[0].size();\n  }\n\n  void Randomize() {\n    for (auto& iv: input_reps)\n      iv = FVector<F>::Random() / 5.;\n    for (auto& ov: output_reps)\n      ov = FVector<F>::Random() / 2.;\n  }\n\n  template <typename T>\n  void copyfrom(const Model<T>& o) {\n    for (unsigned i = 0; i < input_reps.size(); ++i)\n      for (unsigned j = 0; j < INPUT_DIM; ++j)\n        input_reps[i](j,0) = o.input_reps[i](j,0);\n    for (unsigned i = 0; i < output_reps.size(); ++i)\n      for (unsigned j = 0; j < INPUT_DIM; ++j)\n        output_reps[i](j,0) = o.output_reps[i](j,0);\n  }\n\n  void update(const Model<adouble>& g, Model<double>& h) {\n    double eta = 0.1;\n    for (unsigned i = 0; i < input_reps.size(); ++i)\n      for (unsigned j = 0; j < INPUT_DIM; ++j) {\n        double d = g.input_reps[i](j,0).get_gradient();\n        if (d) {\n          double s = h.input_reps[i](j,0) += d * d;\n          input_reps[i](j,0) -= eta * d / sqrt(s);\n        }\n      }\n    for (unsigned i = 0; i < output_reps.size(); ++i)\n      for (unsigned j = 0; j < INPUT_DIM; ++j) {\n        double d = g.output_reps[i](j,0).get_gradient();\n        if (d) {\n          double s = h.output_reps[i](j,0) += d * d;\n          output_reps[i](j,0) -= eta * d / sqrt(s);\n        }\n      }\n  }\n\n  inline static void nonlinearity(FVector<F>& v) {\n    for (unsigned i = 0; i < v.size(); ++i)\n      v(i,0) = tanh(v(i,0));\n  }\n\n  F log_prob(const FrozenFeatureMap& x, unsigned y) const {\n    FVector<F> h = FVector<F>::Zero();\n    for (auto& it : x)\n      h += input_reps[it.first] * it.second;\n    nonlinearity(h);\n    F z = 0;\n    F res = 0;\n    unsigned c = 0;\n    for (auto& ov : output_reps) {\n      F s = h.dot(ov);\n      if (c == y) res = s;\n      z += exp(s);\n      ++c;\n    }\n    return res - log(z);\n  }\n\n  unsigned predict(const FrozenFeatureMap& x) const {\n    FVector<F> h = FVector<F>::Zero();\n    for (auto& it : x)\n      h += input_reps[it.first] * it.second;\n    nonlinearity(h);\n    unsigned c = 0;\n    F cur_best = 0.0;\n    unsigned cur_best_i = output_reps.size();\n    for (auto& ov : output_reps) {\n      F s = h.dot(ov);\n      if (s > cur_best || cur_best_i == output_reps.size()) {\n        cur_best = s; cur_best_i = c;\n      }\n      ++c;\n    }\n    return cur_best_i;\n  }\n\n  vector<FVector<F>> input_reps;\n  vector<FVector<F>> output_reps;\n};\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n  string line;\n  double l1 = conf[\"l1\"].as<double>();\n  double l2 = conf[\"l2\"].as<double>();\n  if (l1 < 0.0) {\n    cerr << \"L1 strength must be >= 0\\n\";\n    return 1;\n  }\n  if (l2 < 0.0) {\n    cerr << \"L2 strength must be >= 0\\n\";\n    return 2;\n  }\n  bool stop = false;\n  requested_stop = &stop;\n  RegressionType resptype = kLOGISTIC;\n  if (conf.count(\"linear\")) {\n    resptype = kLINEAR;\n  }\n  if (!(conf.count(\"x\") && conf.count(\"y\"))) {\n    cerr << \"You must specify both training_features (-x) and training_responses (-y)!\\n\";\n    return 1;\n  }\n  vector<string> labels; // only populated for non-continuous models\n  vector<TrainingInstance> training, test;\n  FeatureMapStorage fms;\n  vector<string> xfile = conf[\"x\"].as<vector<string> >();\n  string yfile = conf[\"y\"].as<string>();\n  ReadLabeledInstances(xfile, yfile, resptype, &fms, &training, &labels);\n  if (conf.count(\"tx\") && conf.count(\"ty\")) {\n    vector<string> xfile = conf[\"tx\"].as<vector<string> >();\n    string yfile = conf[\"ty\"].as<string>();\n    ReadLabeledInstances(xfile, yfile, resptype, &fms, &test, &labels);\n  }\n\n  adept::Stack s;\n  cerr << \"         Number of features: \" << FD::NumFeats() << endl;\n  cerr << \"Number of training examples: \" << training.size() << endl;\n  const unsigned p = FD::NumFeats();\n\n  Model<double> dmodel(p,labels.size());\n  dmodel.Randomize();\n  Model<double> hmodel(p,labels.size());\n  Model<adouble> amodel(p,labels.size());\n  cout.precision(15);\n  ostream* out = &cout;\n  cerr << \"Model size: \" << dmodel.size() << \" parameters\\n\";\n  // set up signal handler to catch SIGINT\n  signal(SIGINT, signal_callback_handler);\n\n  if (conf.count(\"linear\")) {  // linear regression\n    cerr << \"Not implemented!\\n\";\n    return 1;\n  } else {                     // logistic regression\n    for (unsigned iter = 0; !stop && iter < 100000; ++iter) {\n      amodel.copyfrom(dmodel);\n      s.new_recording();\n      adouble llh = 0;\n      double right = 0;\n      for (auto& xy: training) {\n        adouble lp = amodel.log_prob(xy.x, xy.y.label);\n        unsigned pred_y = dmodel.predict(xy.x);\n        if (pred_y == xy.y.label) right++;\n        //cerr << xy.y.label << \" ||| \" << lp << endl;\n        llh -= lp;\n      }\n      llh.set_gradient(1.0);\n      s.compute_adjoint();\n      double hright = 0.0;\n      double hllh = 0;\n      unsigned lc = 0;\n      for (auto& xy: test) {\n        ++lc;\n        double lp = dmodel.log_prob(xy.x, xy.y.label);\n        unsigned pred_y = dmodel.predict(xy.x);\n        if (pred_y == xy.y.label) hright++;\n        else if (lc < 100) {\n          cerr << \"line \" << lc << \" which is in \" << labels[xy.y.label] << \" was confused for \" << labels[pred_y] << endl;\n        }\n        //cerr << xy.y.label << \" ||| \" << lp << endl;\n        hllh -= lp;\n      }\n      double perp = exp(llh.value() / training.size());\n      double perpho = exp(hllh / test.size());\n      cerr << \"i=\" << iter << \"\\tPerplexity: \" << perp << \"\\ttrain-acc: \" << (right / training.size());\n      if (test.size()) cerr << \"\\td-perp: \" << perpho << \"\\ttd-acc: \" << (hright / test.size());\n      cerr << endl;\n      dmodel.update(amodel, hmodel);\n    }\n  }\n  for (unsigned i = 0; i < labels.size(); ++i) {\n    cerr << labels[i] << \" \" << dmodel.output_reps[i].transpose() << endl;\n  }\n  if (out && out != &cout)\n    delete out;\n\n  return 0;\n}\n", "meta": {"hexsha": "39fc8bbe3dae36b9ca740ffdf66c6bac06f15f89", "size": 14279, "ext": "cc", "lang": "C++", "max_stars_repo_path": "creg/cnlreg.cc", "max_stars_repo_name": "redpony/creg", "max_stars_repo_head_hexsha": "33d59a85fe3f87a12e9658d36eee2a04c4058f25", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T21:38:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T19:13:26.000Z", "max_issues_repo_path": "creg/cnlreg.cc", "max_issues_repo_name": "redpony/creg", "max_issues_repo_head_hexsha": "33d59a85fe3f87a12e9658d36eee2a04c4058f25", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-16T17:46:10.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-17T02:50:09.000Z", "max_forks_repo_path": "creg/cnlreg.cc", "max_forks_repo_name": "redpony/creg", "max_forks_repo_head_hexsha": "33d59a85fe3f87a12e9658d36eee2a04c4058f25", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T13:56:04.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-11T02:47:42.000Z", "avg_line_length": 32.5261958998, "max_line_length": 123, "alphanum_fraction": 0.55921283, "num_tokens": 4090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24310177213579648}}
{"text": "// Author: Francesco Regazzoni - MOX, Politecnico di Milano\n// Email:  francesco.regazzoni@polimi.it\n// Date:   2020\n\n#include <cmath>\n\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n#include \"model_RDQ18.hpp\"\n\nmodel_RDQ18::model_RDQ18(std::string parameters_file) : sarcomere(\"RDQ18\") {\n  // Read JSON options file\n  boost::property_tree::ptree root;\n  boost::property_tree::read_json(parameters_file, root);\n\n  prm_n_RU = root.get_child(\"geometry\")\n                 .get_child(\"n_RU\")\n                 .get_value<unsigned int>(); // [-]\n  prm_LA = root.get_child(\"geometry\")\n               .get_child(\"LA\")\n               .get_value<double>(); // [micro m]\n  prm_LM = root.get_child(\"geometry\")\n               .get_child(\"LM\")\n               .get_value<double>(); // [micro m]\n  prm_LB = root.get_child(\"geometry\")\n               .get_child(\"LB\")\n               .get_value<double>(); // [micro m]\n  prm_Lsmooth = root.get_child(\"geometry\")\n                    .get_child(\"Lsmooth\")\n                    .get_value<double>(); // [micro m]\n  prm_Q0 = root.get_child(\"RU_steady_state\")\n               .get_child(\"Q0\")\n               .get_value<double>(); // [-]\n  prm_SLQ = root.get_child(\"RU_steady_state\")\n                .get_child(\"SLQ\")\n                .get_value<double>(); // [micro m]\n  prm_alphaQ = root.get_child(\"RU_steady_state\")\n                   .get_child(\"alphaQ\")\n                   .get_value<double>(); // [1 / micro m]\n  prm_mu = root.get_child(\"RU_steady_state\")\n               .get_child(\"mu\")\n               .get_value<double>(); // [-]\n  prm_gamma = root.get_child(\"RU_steady_state\")\n                  .get_child(\"gamma\")\n                  .get_value<double>(); // [-]\n  prm_Kon = root.get_child(\"RU_kinetics\")\n                .get_child(\"Kon\")\n                .get_value<double>(); // [micro M^-1 * s^-1]\n  prm_Koff = root.get_child(\"RU_kinetics\")\n                 .get_child(\"Koff\")\n                 .get_value<double>(); // [s^-1]\n  prm_Kbasic = root.get_child(\"RU_kinetics\")\n                   .get_child(\"Kbasic\")\n                   .get_value<double>(); // [s^-1]\n  prm_TaMax = root.get_child(\"upscaling\")\n                  .get_child(\"TaMax\")\n                  .get_value<double>(); // [kPa]\n\n  allocate_variables();\n\n  initialize_rates();\n}\n\nvoid model_RDQ18::allocate_variables() {\n  // Variable numbers\n  n_variables = (prm_n_RU - 2) * 4 * 4 * 4;\n\n  // Allocation of state_RU\n  std::array<std::array<std::array<double, 4>, 4>, 4> base_RU_state;\n  for (RU_L = 0; RU_L < 4; ++RU_L)\n    for (RU_C = 0; RU_C < 4; ++RU_C)\n      for (RU_R = 0; RU_R < 4; ++RU_R)\n        base_RU_state[RU_L][RU_C][RU_R] = 0.0;\n  base_RU_state[0][0][0] = 1.0;\n\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU)\n    state_RU.push_back(base_RU_state);\n\n  // Allocation of initial_state\n  for (unsigned int i = 0; i < n_variables; ++i)\n    initial_state.push_back(0.0);\n  serialize_state(initial_state);\n\n  // Allocation of rates_RU\n  std::array<std::array<std::array<std::array<double, 4>, 4>, 4>, 4>\n      base_RU_rates_or_flux;\n  for (RU_L = 0; RU_L < 4; ++RU_L)\n    for (RU_C = 0; RU_C < 4; ++RU_C)\n      for (RU_R = 0; RU_R < 4; ++RU_R)\n        for (RU_new = 0; RU_new < 4; ++RU_new)\n          base_RU_rates_or_flux[RU_L][RU_C][RU_R][RU_new] = 0.0;\n\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU) {\n    rates_RU.push_back(base_RU_rates_or_flux);\n  }\n\n  // Allocation of flux_RU_*\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU) {\n    flux_RU_L.push_back(base_RU_rates_or_flux);\n    flux_RU_C.push_back(base_RU_rates_or_flux);\n    flux_RU_R.push_back(base_RU_rates_or_flux);\n  }\n}\n\nvoid model_RDQ18::solve_time_step(std::vector<double> &state,\n                                  const double &calcium,\n                                  const double &sarcomere_length,\n                                  const double & /*dSL_dt*/, const double &dt) {\n  // Deserialize state\n  deserialize_state(state);\n\n  // Update RU transition rates\n  RU_update_rates(calcium, sarcomere_length);\n\n  // Advance RU state\n  double RU_dt = 0.0;\n  double time_advanced = 0.0;\n  while (time_advanced <=\n         dt - 1e-10) // Cover the time-step up to a given tolerance\n  {\n    RU_dt = std::min(prm_time_step_update_RU_state, dt - time_advanced);\n    RU_update_state(RU_dt);\n    time_advanced += RU_dt;\n  }\n\n  // Re-serialize state\n  serialize_state(state);\n}\n\nvoid model_RDQ18::deserialize_state(const std::vector<double> &state) {\n  unsigned int i_current = 0;\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R) {\n          state_RU[i_RU][RU_L][RU_C][RU_R] = state[i_current];\n          i_current++;\n        }\n}\n\nvoid model_RDQ18::serialize_state(std::vector<double> &state) {\n  unsigned int i_current = 0;\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R) {\n          state[i_current] = state_RU[i_RU][RU_L][RU_C][RU_R];\n          i_current++;\n        }\n}\n\ndouble model_RDQ18::get_active_tension(const std::vector<double> &state,\n                                       const double & /*sarcomere_length*/) {\n  return prm_TaMax * get_permissivity(state);\n}\n\ndouble model_RDQ18::get_permissivity(const std::vector<double> &state) {\n  deserialize_state(state);\n\n  double permissivity = 0;\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU) {\n    if (i_RU == 0) // First RU\n    {\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R)\n          permissivity +=\n              state_RU[0][2][RU_C][RU_R] + state_RU[0][3][RU_C][RU_R];\n    } else if (i_RU == prm_n_RU - 1) // Last RU\n    {\n      for (RU_L = 0; RU_L < 4; ++RU_L)\n        for (RU_C = 0; RU_C < 4; ++RU_C)\n          permissivity += state_RU[prm_n_RU - 3][RU_L][RU_C][2] +\n                          state_RU[prm_n_RU - 3][RU_L][RU_C][3];\n    } else // Intermediate RUs\n    {\n      for (RU_L = 0; RU_L < 4; ++RU_L)\n        for (RU_R = 0; RU_R < 4; ++RU_R)\n          permissivity += state_RU[i_RU - 1][RU_L][2][RU_R] +\n                          state_RU[i_RU - 1][RU_L][3][RU_R];\n    }\n  }\n  return permissivity / prm_n_RU;\n}\n\nvoid model_RDQ18::initialize_rates() {\n  int permissive_neighbors;\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_R = 0; RU_R < 4; ++RU_R) {\n        permissive_neighbors =\n            permissivity_of_state[RU_L] + permissivity_of_state[RU_R];\n        rates_RU[i_RU][RU_L][1][RU_R][0] = prm_Koff;\n        rates_RU[i_RU][RU_L][2][RU_R][3] = prm_Koff / prm_mu;\n        rates_RU[i_RU][RU_L][3][RU_R][0] =\n            prm_Kbasic * std::pow(prm_gamma, 2 - permissive_neighbors);\n        rates_RU[i_RU][RU_L][2][RU_R][1] =\n            prm_Kbasic * std::pow(prm_gamma, 2 - permissive_neighbors);\n      }\n}\n\nvoid model_RDQ18::RU_update_rates(const double &calcium,\n                                  const double &sarcomere_length) {\n  int permissive_neighbors;\n  double ChiRA_i_RU, ChiLA_i_RU;\n  double Q_SL = Q(sarcomere_length);\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU) {\n    ChiRA_i_RU = ChiRA(sarcomere_length, i_RU);\n    ChiLA_i_RU = ChiLA(sarcomere_length, i_RU);\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_R = 0; RU_R < 4; ++RU_R) {\n        permissive_neighbors =\n            permissivity_of_state[RU_L] + permissivity_of_state[RU_R];\n        rates_RU[i_RU][RU_L][0][RU_R][1] = prm_Kon * calcium * ChiRA_i_RU;\n        rates_RU[i_RU][RU_L][1][RU_R][2] =\n            ChiRA_i_RU * ChiLA_i_RU *\n            std::pow(prm_gamma, permissive_neighbors) * Q_SL * prm_Kbasic;\n        rates_RU[i_RU][RU_L][3][RU_R][2] = prm_Kon * calcium * ChiRA_i_RU;\n        rates_RU[i_RU][RU_L][0][RU_R][3] =\n            ChiRA_i_RU * ChiLA_i_RU *\n            std::pow(prm_gamma, permissive_neighbors) * Q_SL * prm_Kbasic /\n            prm_mu;\n      }\n  }\n}\n\nvoid model_RDQ18::RU_update_state(const double &dt) {\n  // Compute fluxes associated with center units\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R)\n          for (RU_new = 0; RU_new < 4; ++RU_new) {\n            flux_RU_C[i_RU][RU_L][RU_C][RU_R][RU_new] =\n                rates_RU[i_RU + 1][RU_L][RU_C][RU_R][RU_new] *\n                state_RU[i_RU][RU_L][RU_C][RU_R];\n          }\n\n  double prob_tot;\n  double rate_tot;\n\n  // Compute fluxes associated with left units\n  // --- Most left-ward triplet\n  for (RU_L = 0; RU_L < 4; ++RU_L)\n    for (RU_C = 0; RU_C < 4; ++RU_C)\n      for (RU_R = 0; RU_R < 4; ++RU_R)\n        for (RU_new = 0; RU_new < 4; ++RU_new) {\n          flux_RU_L[0][RU_L][RU_C][RU_R][RU_new] =\n              rates_RU[0][0][RU_L][RU_C][RU_new] *\n              state_RU[0][RU_L][RU_C][RU_R];\n        }\n\n  // --- Other triplets\n  for (i_RU = 1; i_RU < prm_n_RU - 2; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_C = 0; RU_C < 4; ++RU_C) {\n        prob_tot = 0.0;\n        for (RU_dummy = 0; RU_dummy < 4; ++RU_dummy)\n          prob_tot += state_RU[i_RU - 1][RU_dummy][RU_L][RU_C];\n\n        for (RU_new = 0; RU_new < 4; ++RU_new) {\n          rate_tot = 0.0;\n          if (prob_tot > 1e-12) {\n            for (RU_dummy = 0; RU_dummy < 4; ++RU_dummy)\n              rate_tot += flux_RU_C[i_RU - 1][RU_dummy][RU_L][RU_C][RU_new];\n\n            rate_tot /= prob_tot;\n          }\n\n          for (RU_R = 0; RU_R < 4; ++RU_R) {\n            flux_RU_L[i_RU][RU_L][RU_C][RU_R][RU_new] =\n                rate_tot * state_RU[i_RU][RU_L][RU_C][RU_R];\n          }\n        }\n      }\n\n  // Compute fluxes associated with right units\n  // --- Most right-ward triplet\n  for (RU_L = 0; RU_L < 4; ++RU_L)\n    for (RU_C = 0; RU_C < 4; ++RU_C)\n      for (RU_R = 0; RU_R < 4; ++RU_R)\n        for (RU_new = 0; RU_new < 4; ++RU_new) {\n          flux_RU_R[prm_n_RU - 3][RU_L][RU_C][RU_R][RU_new] =\n              rates_RU[prm_n_RU - 1][RU_C][RU_R][0][RU_new] *\n              state_RU[prm_n_RU - 3][RU_L][RU_C][RU_R];\n        }\n\n  // --- Other triplets\n  for (i_RU = 0; i_RU < prm_n_RU - 3; ++i_RU)\n    for (RU_R = 0; RU_R < 4; ++RU_R)\n      for (RU_C = 0; RU_C < 4; ++RU_C) {\n        prob_tot = 0.0;\n        for (RU_dummy = 0; RU_dummy < 4; ++RU_dummy)\n          prob_tot += state_RU[i_RU + 1][RU_C][RU_R][RU_dummy];\n\n        for (RU_new = 0; RU_new < 4; ++RU_new) {\n          rate_tot = 0.0;\n          if (prob_tot > 1e-12) {\n            for (RU_dummy = 0; RU_dummy < 4; ++RU_dummy)\n              rate_tot += flux_RU_C[i_RU + 1][RU_C][RU_R][RU_dummy][RU_new];\n\n            rate_tot /= prob_tot;\n          }\n\n          for (RU_L = 0; RU_L < 4; ++RU_L) {\n            flux_RU_R[i_RU][RU_L][RU_C][RU_R][RU_new] =\n                rate_tot * state_RU[i_RU][RU_L][RU_C][RU_R];\n          }\n        }\n      }\n\n  // Forward Euler advance\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R)\n          for (RU_new = 0; RU_new < 4; ++RU_new) {\n            state_RU[i_RU][RU_L][RU_C][RU_R] +=\n                dt * (flux_RU_L[i_RU][RU_new][RU_C][RU_R][RU_L] +\n                      flux_RU_C[i_RU][RU_L][RU_new][RU_R][RU_C] +\n                      flux_RU_R[i_RU][RU_L][RU_C][RU_new][RU_R] -\n                      flux_RU_L[i_RU][RU_L][RU_C][RU_R][RU_new] -\n                      flux_RU_C[i_RU][RU_L][RU_C][RU_R][RU_new] -\n                      flux_RU_R[i_RU][RU_L][RU_C][RU_R][RU_new]);\n          }\n}", "meta": {"hexsha": "d792272619c67c7dd59f945404abdb28f897d8f0", "size": 11540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "models_cpp/model_RDQ18.cpp", "max_stars_repo_name": "FrancescoRegazzoni/cardiac-activation", "max_stars_repo_head_hexsha": "26f05df28891df7b3c69f16bb136cdced6b63c4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T00:26:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T00:26:28.000Z", "max_issues_repo_path": "models_cpp/model_RDQ18.cpp", "max_issues_repo_name": "FrancescoRegazzoni/cardiac-activation", "max_issues_repo_head_hexsha": "26f05df28891df7b3c69f16bb136cdced6b63c4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models_cpp/model_RDQ18.cpp", "max_forks_repo_name": "FrancescoRegazzoni/cardiac-activation", "max_forks_repo_head_hexsha": "26f05df28891df7b3c69f16bb136cdced6b63c4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3987730061, "max_line_length": 80, "alphanum_fraction": 0.5491334489, "num_tokens": 3934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.24295080894803314}}
{"text": "// Copyright 2019 Victor Hugo Schulz\n\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n\n//     http://www.apache.org/licenses/LICENSE-2.0\n\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <cmath>\n#include <limits>\n#include <algorithm>\n#include <stdlib.h>\n#include <sys/stat.h>\n\n#include <opencv2/core.hpp>\n#include <boost/qvm/all.hpp>\n#include \"structures.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace boost::qvm;\n\n// Function declarations:\nvoid load_config(string filename_common, string filename_dut, catalog_parameters &cp, grid_parameters &gp, optical_parameters &op, database_parameters &db);\nvector<db> initialize_database(catalog_parameters &cp);\nvector<db> visible_stars(vector<db> &database, optical_parameters &op);\nvoid next_neighbor(vector<db> &database, database_parameters &db);\nvector<db> reference_stars(vector<db> &vstars);\nvoid calculate_descriptors (vector<db> &vstars, vector<db> &rstars, database_parameters &db, grid_parameters &gp);\ndouble fov(double size, optical_parameters op);\ndouble vangle (vec<double,3> p1, vec<double,3> p2);\nquat<double> rot_quat (vec<double,3> v1, vec<double,3> v2);\nvoid proper_motion_correction (hip2 entry, int time_y, db *output);\nvector<db> rotate3d(vector<db> visible_stars, vector<db> reference_stars, uint reference_star_id);\ndouble angle_to_origin (db &star);\nvector<db> relevant_fov(vector<db> &lf_list, uint reference_star_id, uint reference_nn_id, database_parameters &db);\ndouble angle2d (db &star);\nvoid rotate2d (vector<db> &star_list, double &theta);\nvoid z_norm (vector<db> &star_list, database_parameters &db, grid_parameters &gp);\nvector<int> cells (vector<db> &star_list, grid_parameters &gp);\nuint bucket_size(int g);\nvector<unsigned long> bit_descriptor (vector<int> &cells, grid_parameters &gp);\nvoid sort_nn (vector<db> &stars);\nvoid create_ref(string &ref_db_filename, vector<db> &stars, FileStorage &fs);\nvoid create_index(string &index_filename, vector<db> &stars, FileStorage &fs);\nvoid create_lut(string &lut_db_filename, string &lut_nn_db_filename, vector<db> &stars, grid_parameters &gp, FileStorage &fs);\nvoid create_bin(string &bin_db_filename, vector<db> &stars, grid_parameters &gp, FileStorage &fs);\n\nint main (/*int argc, char **argv*/)\n{// Main function.\n    catalog_parameters cp; grid_parameters gp; optical_parameters op; database_parameters dp;\n    load_config(\"config/common.yml\",\"config/dut.yml\",cp,gp,op,dp);\n\n    vector<db> database = initialize_database(cp);\n    vector<db> vstars = visible_stars(database,op);\n    next_neighbor(vstars,dp);\n    vector<db> rstars = reference_stars(vstars);\n\n    calculate_descriptors(vstars,rstars,dp,gp);\n    sort_nn(rstars);\n\n    mkdir(\"config\", S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH);\n    mkdir(\"config/database/\", S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH);\n    string ref_db_filename =    \"config/database/ref_db.bin\";\n    string lut_db_filename =    \"config/database/lut_db.bin\";\n    string lut_nn_db_filename = \"config/database/lut_nn_db.bin\";\n    string bin_db_filename =    \"config/database/bin_db.bin\";\n    string index_filename =     \"config/database/index.bin\";\n\n    FileStorage fs(\"config/database.yml\", FileStorage::WRITE);\n\n    fs << \"ref_db_filename\" << ref_db_filename;\n    create_ref(ref_db_filename,rstars,fs);\n\n    fs << \"lut_db_filename\" << lut_db_filename;\n    fs << \"lut_nn_db_filename\" << lut_nn_db_filename;\n    create_lut(lut_db_filename,lut_nn_db_filename,rstars,gp,fs);\n\n    fs << \"bin_db_filename\" << bin_db_filename;\n    create_bin(bin_db_filename,rstars,gp,fs);\n\n    fs << \"index_filename\" << index_filename;\n    create_index(index_filename,rstars,fs);\n    fs.release();\n    return 0;\n}\n\nvoid load_config(string filename_common, string filename_dut, catalog_parameters &cp, grid_parameters &gp, optical_parameters &op, database_parameters &dp)\n{// Load configuration from file.\n    double dtmp;\n    Mat mtmp;\n    FileStorage fs(filename_common, FileStorage::READ);\n    fs[\"cp_hipparcos_filename\"]  >> cp.hipparcos;\n    fs[\"cp_hipparcos2_filename\"] >> cp.hipparcos2;\n    fs[\"cp_hipparcos_size\"]      >> dtmp; cp.hipparcos_size = (int)dtmp;\n    fs[\"cp_epoch\"]               >> dtmp; cp.epoch = (int)dtmp;\n    fs[\"op_resolution\"]          >> mtmp; op.resolution = Point2i(mtmp);\n    fs[\"op_pixel_size\"]          >> mtmp; op.pixel_size = Point2d(mtmp);\n    fs[\"op_sensor_size\"]         >> mtmp; op.sensor_size = Point2d(mtmp);\n    fs[\"op_focus\"]               >> op.focus;\n    fs[\"op_center\"]              >> mtmp; op.center = Point2i(mtmp);\n    fs[\"op_max_mag\"]             >> op.max_mag;\n    fs.release();\n    FileStorage fs2(filename_dut, FileStorage::READ);\n    fs2[\"gp_g\"]                     >> dtmp; gp.g = (int)dtmp;\n    fs2[\"gp_pattern_radius\"]        >> dtmp; gp.pattern_radius = (int)dtmp;\n    fs2[\"gp_buffer_radius\"]         >> gp.buffer_radius;\n    fs2[\"gp_confidence_factor\"]     >> dtmp; gp.confidence_factor = (int)dtmp;\n    fs2[\"gp_expercted_false_stars\"] >> dtmp; gp.expected_false_stars = (int)dtmp;\n    fs2[\"gp_minimim_match\"]         >> dtmp; gp.minimum_match = (int)dtmp;\n    fs2[\"gp_nn_error_angle\"]        >> gp.error;\n    fs2.release();\n    dp.pattern_radius   = fov(gp.pattern_radius*op.pixel_size.y, op);\n    dp.buffer_radius    = fov(gp.buffer_radius*op.pixel_size.y, op);\n    dp.min_dist         = fov(norm(op.pixel_size), op);\n    dp.relevance_radius = fov((norm(op.sensor_size)),op);\n}\n\nvector<db> initialize_database(catalog_parameters &cp)\n{// Read information from Hipparcos and Hipparcos 2 catalogs for initializing the database.\n    hip *hipparcos = new hip [cp.hipparcos_size];\n    hip initial = {0,'\\0',0};\n    for(int i=0;i<cp.hipparcos_size;i++)\n        hipparcos[i] = initial;\n\n    double time_y = cp.epoch - 1991.25;\n\n    // Hipparcos\n    string line;\n    ifstream myfile (cp.hipparcos);\n    if (myfile.is_open()) {\n        while ( getline (myfile,line) ) {\n            hip data;\n            string sstr;\n            int HIP      = stoi(line.substr(8,6));\n            data.Proxy   = line.substr(15,1).compare(\" \") ? 1:0;\n            sstr = line.substr(41,5);\n            if (!sstr.compare(\"     \")){\n\t        // cerr << \"Warning: Empty Vmag (HIP=\" << HIP << \")\" << endl;\n                continue;\n            }\n            data.Vmag    = stod(sstr);\n            sstr = line.substr(47,1);\n            if (sstr.compare(\" \"))\n                data.VarFlag = stoi(sstr);\n            else\n                data.VarFlag = 0;\n            hipparcos[HIP] = data;\n        }\n        myfile.close();\n    }\n    else {\n        cout << \"Unable to open file \\\"\" << cp.hipparcos2 << \"\\\".\" << endl;\n        exit(1);\n    }\n\n    // Hipparcos 2\n    vector<hip2> hipparcos2;\n    ifstream myfile2 (cp.hipparcos2);\n    if (myfile2.is_open()) {\n        while ( getline (myfile2,line) ) {\n            hip2 data;\n            data.HIP   = stoi(line.substr(0,6));\n            data.RArad = stod(line.substr(15,13));\n            data.DErad = stod(line.substr(29,13));\n            data.pmRA  = stod(line.substr(51,8));\n            data.pmDE  = stod(line.substr(60,8));\n            hipparcos2.push_back(data);\n        }\n        myfile2.close();\n    }\n    else {\n        cout << \"Unable to open file \\\"\" << cp.hipparcos2 << \"\\\".\" << endl;\n        exit(1);\n    }\n\n    // Database\n    vector<db> database;\n    for(uint i=0;i<hipparcos2.size();i++){\n        db entry;\n        entry.id         = hipparcos2[i].HIP;\n        entry.mag        = hipparcos[entry.id].Vmag;\n        entry.proxy_flag = hipparcos[entry.id].Proxy;\n        entry.var_flag   = hipparcos[entry.id].VarFlag;\n        proper_motion_correction(hipparcos2[i],time_y,&entry);\n        entry.nn = -1;\n        entry.angle_nn = DBL_MAX;\n        database.push_back(entry);\n    }\n    delete [] hipparcos;\n    return database;\n}\n\nvector<db> visible_stars(vector<db> &database, optical_parameters &op)\n{// Extract only the visible stars from the database.\n    vector<db> output;\n    for(uint i=0;i<database.size();i++){\n        if(database[i].mag <= op.max_mag)\n            output.push_back(database[i]);\n    }\n    return output;\n}\n\nvoid next_neighbor(vector<db> &database, database_parameters &db)\n{// Calculate the next neighbor pointer and distance, populating the database entries.\n    for(uint i=0;i<database.size()-1;i++){\n        for(uint j=i+1;j<database.size();j++){\n            double angle = vangle(database[i].uv,database[j].uv);\n            if(angle < db.buffer_radius){\n                database[i].proxy_flag = 1;\n                database[j].proxy_flag = 1;\n            }\n            else{\n                if(angle < database[i].angle_nn){\n                    database[i].nn = j;\n                    database[i].angle_nn = angle;\n                }\n                if(angle < database[j].angle_nn){\n                    database[j].nn = i;\n                    database[j].angle_nn = angle;\n                }\n            }\n        }\n    }\n}\n\nvector<db> reference_stars(vector<db> &vstars)\n{// Remove variable stars and stars with very close neighbors (double, triple...).\n    vector<db> output;\n    for(uint i=0;i<vstars.size();i++){\n        if (!((vstars[i].var_flag >= 3) || vstars[i].proxy_flag))\n            output.push_back(vstars[i]);\n    }\n    return output;\n}\n\nvoid calculate_descriptors (vector<db> &vstars, vector<db> &rstars, database_parameters &dp, grid_parameters &gp)\n{// Populate the descriptor entries of the reference stars in the database.\n    for(uint ref_star_id=0; ref_star_id<rstars.size(); ref_star_id++){\n        int ref_nn_id = rstars[ref_star_id].nn;\n        vector<db> rotated = rotate3d(vstars,rstars,ref_star_id);\n        vector<db> cropped = relevant_fov(rotated,ref_star_id,ref_nn_id,dp);\n        double theta = angle2d(rotated[rstars[ref_star_id].nn]);\n        rotate2d(cropped,theta);\n        z_norm(cropped,dp,gp);\n        rstars[ref_star_id].angle_2d = theta;\n        rstars[ref_star_id].cells_descriptor = cells(cropped,gp);\n        rstars[ref_star_id].bit_descriptor = bit_descriptor(rstars[ref_star_id].cells_descriptor,gp);\n    }\n}\n\ndouble vangle (vec<double,3> p1, vec<double,3> p2)\n{// Angle between two vectors.\n    return atan2(mag(cross(p1,p2)), dot(p1,p2));\n}\n\nquat<double> rot_quat (vec<double,3> v1, vec<double,3> v2)\n{// Rotation quaternion between two unit vectors. V1 must be different than V2.\n    double theta = vangle(v1,v2);\n    double angle = cos(theta/2);\n    vec<double,3> v = cross(v1,v2);\n    normalize(v);\n    v *= sin(theta/2);\n    quat<double> output;\n    output = {angle,v.a[0],v.a[1],v.a[2]};\n    return output;\n}\n\ndouble fov(double size, optical_parameters op)\n{// Field of view calculation.\n    return 2*atan2(size,2*op.focus);\n}\n\nvoid proper_motion_correction(hip2 entry, int time_y, db *output)\n{// Proper motion conversion, with output as an unit vector.\n    double mu_alpha_rad = (entry.pmRA * M_PI) / (3600 * 1000 * 180 * cos(entry.DErad));\n    double mu_delta_rad = (entry.pmDE * M_PI) / (3600 * 1000 * 180);\n    double alpha        = entry.RArad + mu_alpha_rad * time_y;\n    double delta        = entry.DErad + mu_delta_rad * time_y;\n    output->uv = {cos(alpha) * cos(delta),\n                  sin(alpha) * cos(delta),\n                  sin(delta)};\n}\n\nvector<db> rotate3d(vector<db> visible_stars, vector<db> reference_stars, uint reference_star_id)\n{// Rotate the database so that the reference star will appear on the origin.\n    vec<double,3> origin = {0,0,1};\n    quat<double> q = rot_quat(reference_stars[reference_star_id].uv, origin);\n    for(uint i = 0; i<visible_stars.size(); i++){\n        vec<double,3> p_ = visible_stars[i].uv;\n        quat<double> p = {0,p_.a[0],p_.a[1],p_.a[2]};\n        quat<double> rot_uv = q * p * inverse(q);\n        visible_stars[i].uv = V(rot_uv);\n    }\n    return visible_stars;\n}\n\ndouble angle_to_origin (db &star)\n{// Angle between the star in local frame and the coordinate system origin.\n    vec<double,3> origin = {0,0,1};\n    return vangle(star.uv, origin);\n}\n\nvector<db> relevant_fov(vector<db> &lf_list, uint reference_star_id, uint reference_nn_id, database_parameters &dp)\n{// Remove stars which are outside of the field of view.\n    vector<db> fov;\n    for(uint i = 0; i<lf_list.size(); i++){\n        if((i != reference_star_id)\n                && (i != reference_nn_id)\n                && (angle_to_origin(lf_list[i]) < dp.relevance_radius))\n        { // Reference star and its next neighbor are excluded.\n            fov.push_back(lf_list[i]);\n        }\n    }\n    return fov;\n}\n\ndouble angle2d (db &star)\n{// Returns the angle needed to rotate a given star so that it will fall in the x axis.\n    return -atan2(star.uv.a[1], star.uv.a[0]);\n}\n\nvoid rotate2d (vector<db> &star_list, double &theta)\n{// In-place rotation of a list of stars by a given angle.\n    quat<double> q = rotz_quat(theta);\n    for(uint i=0; i<star_list.size();i++){\n        quat<double> p = {0,\n                          star_list[i].uv.a[0],\n                          star_list[i].uv.a[1],\n                          star_list[i].uv.a[2]};\n        star_list[i].uv = V(q*p*inverse(q));\n    }\n}\n\nvoid z_norm (vector<db> &star_list, database_parameters &dp, grid_parameters &gp)\n{// In-place linear transformation so that points fall within x=[0,g] and y=[0,g].\n // Since pr =! rr, out of bound values must be filtered later.\n // The z coordinate remains unchanged.\n    for(uint i=0; i<star_list.size(); i++){\n        double norm = star_list[i].uv.a[2] * tan(dp.pattern_radius) * 2;\n        star_list[i].uv.a[0] /= norm;\n        star_list[i].uv.a[1] /= norm;\n        star_list[i].uv.a[0] += 0.5;\n        star_list[i].uv.a[1] += 0.5;\n        star_list[i].uv.a[0] *= gp.g;\n        star_list[i].uv.a[1] *= gp.g;\n        star_list[i].uv.a[0] = floor(star_list[i].uv.a[0]);\n        star_list[i].uv.a[1] = floor(star_list[i].uv.a[1]);\n    }\n}\n\nvector<int> cells (vector<db> &star_list, grid_parameters &gp)\n{// Returns a list with the cells present on the descriptor.\n    vector<int> cells;\n    for(uint i=0; i<star_list.size(); i++){\n        if((star_list[i].uv.a[0] >= 0) &&\n                (star_list[i].uv.a[0] < gp.g) &&\n                (star_list[i].uv.a[1] >= 0) &&\n                (star_list[i].uv.a[1] < gp.g)){\n            cells.push_back(gp.g*star_list[i].uv.a[1] + star_list[i].uv.a[0]);\n        }\n    }\n    // Duplicates are removed (next 2 lines).\n    sort(cells.begin(),cells.end());\n    cells.erase(unique(cells.begin(),cells.end()), cells.end());\n    return cells;\n}\n\nuint bucket_size(int g)\n{// Calculates the number of buckets for the descriptor calculation from the grid size g; ex. ceil(g*g/64) for 64 bits.\n    int g2 = g*g;\n    int divisor = sizeof(long) << 3;\n    return g2/divisor + (g2%divisor ? 1 : 0);\n}\n\nvector<unsigned long> bit_descriptor (vector<int> &cells, grid_parameters &gp)\n{// Calculates a bit descriptor from the on cells.\n    static unsigned int bit_size = sizeof(long) * 8; // Architecture dependent result\n    // Since the needed bits usually exceed the architecture word lenghts, multiple 'buckets' hold the values.\n    uint bsize = bucket_size(gp.g);\n    unsigned long bucket[bsize];\n    unsigned int i;\n    for(i=0;i<bsize;i++)\n        bucket[i] = 0;\n    for(i=0;i<cells.size();i++){\n        unsigned int n = cells[i]/bit_size;\n        bucket[n] |= (unsigned long)1<<(cells[i]%bit_size);\n    }\n    vector<unsigned long> output(bucket, bucket + sizeof bucket / sizeof bucket[0]);\n    return output;\n}\n\nvoid sort_nn (vector<db> &stars)\n{// Sorts the database by the next neighbor angle.\n    qsort(stars.data(),stars.size(),sizeof(db),[](const void *a_, const void *b_){\n        db *a = (db*) a_;\n        db *b = (db*) b_;\n        return (int)(a->angle_nn > b->angle_nn);\n    });\n}\n\nvoid create_ref(string &ref_db_filename, vector<db> &stars, FileStorage &fs)\n{// Produces the reference database and writes it to a file. Format: {id, angle_nn, uv_x, uv_y, uv_z}\n    int rows = stars.size();\n    int cols = 5;\n    double ref_db[rows][cols];\n    for(uint i=0;i<stars.size();i++){\n        ref_db[i][0] = stars[i].id;\n        ref_db[i][1] = stars[i].angle_nn;\n        ref_db[i][2] = stars[i].uv.a[0];\n        ref_db[i][3] = stars[i].uv.a[1];\n        ref_db[i][4] = stars[i].uv.a[2];\n    }\n    fs << \"ref_db_rows\" << rows;\n    fs << \"ref_db_cols\" << cols;\n    FILE *fp;\n    fp = fopen(ref_db_filename.data(), \"w\");\n    fwrite(ref_db,1,sizeof(ref_db),fp);\n    fclose(fp);\n}\n\nint binSearch2(double what, double *data, double len)\n{// Binary search method.\n    int low = 0;\n    int high = len - 1;\n    int mid = 0;\n    while (low <= high) {\n        mid = (low + high) / 2;\n        if (data[mid] > what)\n            high = mid - 1;\n        else if (data[mid] < what)\n            low = mid + 1;\n        else\n            return mid;\n    }\n    return mid;\n}\n\nvoid create_index(string &index_filename, vector<db> &stars, FileStorage &fs)\n{// Creates an index to speed up the lookup of elements by their nn distance.\n    double last = stars[stars.size()-1].angle_nn;\n    double data[stars.size()];\n    for(uint i=0; i<stars.size();i++){\n        data[i] = stars[i].angle_nn;\n    }\n    int multiplier = 1;\n    while(true){\n        multiplier *= 2;\n        last *= 2;\n        if(last > stars.size()) break;\n    }\n    int real_size = (int)(last+1);\n    short index[real_size];\n    for(int i=0; i<real_size; i++){\n        index[i] = (short)binSearch2((double)i/multiplier,data,stars.size());\n    }\n    fs << \"index_size\" << real_size;\n    fs << \"index_multiplier\" << multiplier;\n    FILE *fp;\n    fp = fopen(index_filename.data(), \"w\");\n    fwrite(index,sizeof(short),sizeof(index),fp);\n    fclose(fp);\n}\n\nvoid create_lut(string &lut_db_filename, string &lut_nn_db_filename, vector<db> &stars, grid_parameters &gp, FileStorage &fs)\n{// Produces the (inverted) lookup table and writes it to a file.\n    uint rows = (uint)gp.g*gp.g;\n    vector<vector <short> > lut(rows, vector<short>());\n    vector<vector <float> > lut_nn(rows, vector<float>());\n    for(uint i=0;i<stars.size();i++){\n        for(uint j=0;j<stars[i].cells_descriptor.size();j++){\n            lut[ stars[i].cells_descriptor[j] ].push_back((short)i);\n            lut_nn[ stars[i].cells_descriptor[j] ].push_back((float)stars[i].angle_nn);\n        }\n    }\n    uint cols = 0;\n    for(uint i=0;i<lut.size();i++){\n        if(lut[i].size() > cols){\n            cols = lut[i].size();\n        }\n    }\n//    short lut_array[rows][cols];\n//    for(uint i=0;i<rows;i++){\n//        for(uint j=0;j<cols;j++){\n//            lut_array[i][j] = -1;\n//        }\n//    }\n    short * lut_array = new short[rows*cols];\n    for(uint i=0; i<rows*cols;i++){\n        lut_array[i] = -1;\n    }\n    float *lut_array_nn = new float[rows*cols];\n    for(uint i=0; i<rows*cols;i++){\n        lut_array_nn[i] = DBL_MAX;\n    }\n    for(uint i=0;i<rows;i++){\n        //memcpy(&lut_array[i],lut[i].data(),lut[i].size()*sizeof(short));\n        memcpy(&lut_array[i*cols],lut[i].data(),lut[i].size()*sizeof(short));\n        memcpy(&lut_array_nn[i*cols],lut_nn[i].data(),lut_nn[i].size()*sizeof(float));\n    }\n    fs << \"lut_db_rows\" << (int)rows;\n    fs << \"lut_db_cols\" << (int)cols;\n    FILE *fp;\n    fp = fopen(lut_db_filename.data(), \"w\");\n//    fwrite(lut_array,sizeof(short),sizeof(lut_array),fp);\n    fwrite(lut_array,sizeof(short),rows*cols,fp);\n    fclose(fp);\n    fp = fopen(lut_nn_db_filename.data(), \"w\");\n    fwrite(lut_array_nn,sizeof(float),rows*cols,fp);\n    fclose(fp);\n    delete lut_array_nn;\n}\n\nvoid create_bin(string &bin_db_filename, vector<db> &stars, grid_parameters &gp, FileStorage &fs)\n{// Produces the bit descriptor and writes it to a file.\n    uint rows = stars.size();\n    uint cols = bucket_size(gp.g);\n    unsigned long bin_db[rows][cols];\n    for(uint i=0;i<rows;i++){\n        memcpy(&bin_db[i],stars[i].bit_descriptor.data(),cols*sizeof(unsigned long));\n    }\n    fs << \"bin_db_rows\" << (int)rows;\n    fs << \"bin_db_cols\" << (int)cols;\n    FILE *fp;\n    fp = fopen(bin_db_filename.data(), \"w\");\n    fwrite(bin_db,1,sizeof(bin_db),fp);\n    fclose(fp);\n}\n", "meta": {"hexsha": "8c72a611f0fd86f51b60a008e4ed2de0f6657cb5", "size": 20418, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/grid_database/main.cpp", "max_stars_repo_name": "schulz89/Verification-Platform-for-Star-Trackers", "max_stars_repo_head_hexsha": "5216feb8036506503713c0c1f89728ecc40b3d5c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-06T10:32:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T21:14:26.000Z", "max_issues_repo_path": "src/grid_database/main.cpp", "max_issues_repo_name": "schulz89/Verification-Platform-for-Star-Trackers", "max_issues_repo_head_hexsha": "5216feb8036506503713c0c1f89728ecc40b3d5c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-30T06:25:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-30T06:25:21.000Z", "max_forks_repo_path": "src/grid_database/main.cpp", "max_forks_repo_name": "schulz89/Verification-Platform-for-Star-Trackers", "max_forks_repo_head_hexsha": "5216feb8036506503713c0c1f89728ecc40b3d5c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9516728625, "max_line_length": 156, "alphanum_fraction": 0.6217553139, "num_tokens": 5600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2429471413680615}}
{"text": "#include <stdlib.h>\n#include <ctype.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <time.h>\n#include <boost/optional/optional_io.hpp>\n\n#include \"snark.hpp\"\n#include \"lib_zero_knowledge.h\"\n\n#define VK_PATH \"./vk\"\n#define PK_PATH \"./pk\"\n\n\n\n#define CHECK_STR_LEN(p, max, ret) if (strlen(p) > max) return ret;\n\n\n\n\nusing namespace libsnark;\nusing namespace std;\n\nstatic r1cs_ppzksnark_proving_key<default_r1cs_ppzksnark_pp> proving_key;\nstatic r1cs_ppzksnark_verification_key<default_r1cs_ppzksnark_pp> verifycation_key;\n\n\nstatic void write_debug_vector(ofstream& out, vector<bool> &v, const char *prefix)\n{\n\tif (strlen(prefix)) {\n\t\tout << prefix << \"\\n\";\n\t}\n\n\tfor(int i=0; i<v.size(); i++) {\n\t\tif (v[i]) {\n\t\t\tout << '1';\n\t\t} else {\n\t\t\tout << '0';\n\t\t}\n\t\tif (i && !(i % 8)) {\n\t\t\tout << ' ';\n\t\t\tif ( !(i % 32) ) {\n\t\t\t\tout << '\\n';\n\t\t\t}\n\t\t}\n\t}\n\tout << \"\\n\";\n\n}\n\nstatic void write_debug_array(ofstream& out, int *jw, const char *prefix)\n{\n\tif (strlen(prefix)) {\n\t\tout << prefix << \"\\n\";\n\t}\n\n\tfor(int i=0; i<32; i++) {\n\t\tout << jw[i];\n\t\tif (i && !(i % 8)) {\n\t\t\tout << ' ';\n\t\t\tif ( !(i % 32) ) {\n\t\t\t\tout << '\\n';\n\t\t\t}\n\t\t}\n\t}\n\tout << \"\\n\";\n}\n\n\nstatic void write_debug(vector<bool> &h1_bv, vector<bool> &h2_bv, vector<bool> &h3_bv, \n\tvector<bool> &r1_bv, vector<bool> &r2_bv, vector<bool> &r3_bv, \n\tint *jw, const char *file_name)\n{\n\tofstream out;\n\tout.open(file_name);\n\t\n    write_debug_vector(out, h1_bv, \"h1\");\n\twrite_debug_vector(out, h2_bv, \"h2\");\n\twrite_debug_vector(out, h3_bv, \"h3\");\n\twrite_debug_vector(out, r1_bv, \"r1\");\n\twrite_debug_vector(out, r2_bv, \"r2\");\n\twrite_debug_vector(out, r3_bv, \"r3\");\n\n\twrite_debug_array(out, jw, \"jw\");\n\t\n    out.close();\n}\n\nstatic bool file_exist (const std::string& name) {\n\tifstream f(name.c_str());\n\treturn f.good();\n}\n\n\n\n//called once\nvoid init_setup()\n{\n\tint jw_neg[2][32];\n\n\t// Initialize the curve parameters.\n    default_r1cs_ppzksnark_pp::init_public_params();\n\n\tbool need_gen = true;\t\n\tif (file_exist(PK_PATH) && file_exist(VK_PATH)) { //only read \n\t\tneed_gen = false;\n\t} \n\t\n\tif (need_gen) {\n\t\t//generate key\n\t\tauto keypair = generate_keypair_neg<default_r1cs_ppzksnark_pp>(jw_neg);\n\t\t//pk\n\t\tstringstream provingKey;\n\t\tprovingKey << keypair.pk;\n\t\tofstream pkOf;\n\t\tpkOf.open(PK_PATH);\n\t\tpkOf << provingKey.rdbuf();\n\t\tpkOf.close();\n\t\t//vk\n\t\tofstream vkOf;\n\t\tstringstream verificationKey;\n    \tverificationKey << keypair.vk;\n    \tvkOf.open(VK_PATH);\n    \tvkOf << verificationKey.rdbuf();\n    \tvkOf.close();\n\t}\n\t\n\t//read\n\tifstream vkIf, pkIf; \n\tpkIf.open(PK_PATH); \n    stringstream provingKeyFromFile;\n\tprovingKeyFromFile << pkIf.rdbuf();\n\tpkIf.close();\n\tprovingKeyFromFile >> proving_key;\n\n    vkIf.open(VK_PATH);  \n    stringstream verifycationKeyFromFile;\n    verifycationKeyFromFile << vkIf.rdbuf();\n    vkIf.close();\n    verifycationKeyFromFile >> verifycation_key;\n}\n\n\nstatic void hex_str_to_bytes(const char* source, unsigned char* dest, int source_len)\n{\n    unsigned char high, low;\n\n    for (int i = 0; i < source_len; i += 2)\n    {\n        high = toupper(source[i]);\n        low  = toupper(source[i + 1]);\n\n        if (high > 0x39)\n            high -= 0x37;\n        else\n            high -= 0x30;\n\n        if (low > 0x39)\n            low -= 0x37;\n        else\n            low -= 0x30;\n\n        dest[i / 2] = (high << 4) | low;\n    }\n    return;\n}\n\nstatic void bytes_to_hex_str(const unsigned char* source, unsigned char* dest, int source_len)\n{\n    unsigned char high, low;\n\n    for (int i = 0; i < source_len; i++)\n    {\n        high = source[i] >> 4;\n        low = source[i] & 0x0f ;\n\n        high += 0x30;\n\n        if (high > 0x39)\n                dest[i * 2] = high + 0x07;\n        else\n                dest[i * 2] = high;\n\n        low += 0x30;\n        if (low > 0x39)\n            dest[i * 2 + 1] = low + 0x07;\n        else\n            dest[i * 2 + 1] = low;\n    }\n\tdest[(source_len-1)*2+1+1] = 0;\n    return ;\n}\n\n\n\nstatic void hex_str_to_vector(const char *source, std::vector<bool>& dest)\n{\n\tunsigned char bytes[32];\n\tmemset(bytes, 0, sizeof(bytes));\n\thex_str_to_bytes(source, bytes, strlen(source));\n\tsize_t wordsize = 8;\n\tfor (size_t i = 0; i < sizeof(bytes); ++i)\n\t{\n\t\tfor (size_t j = 0; j<wordsize ; ++j)\n\t\t{\n\t\t\tdest[i*wordsize + j] = (bytes[i] & (1ul<<(wordsize-1-j)));\n\t\t}\n\t}\n\n}\n\nstatic char *list_to_str(const std::initializer_list<unsigned char> &list)\n{\n\tchar *dest = (char *)malloc( list.size()*2 + 1);\n\tfor (size_t i = 0; i < list.size(); ++i)\n    {\n\t\tunsigned char c = *(list.begin()+i);\n\t\tsprintf(dest+i*2, \"%02x\", c);\n    }\n\tdest[ list.size()*2 ] = 0;\n\treturn dest;\n\n}\n\nstatic void set_flag(char *r1, char *r2, int *jw)\n{\n\tunsigned char bytes_r1[32];\n\tmemset(bytes_r1, 0, sizeof(bytes_r1));\n\thex_str_to_bytes(r1, bytes_r1, strlen(r1));\n\t\n\tunsigned char bytes_r2[32];\n\tmemset(bytes_r2, 0, sizeof(bytes_r2));\n\thex_str_to_bytes(r2, bytes_r2, strlen(r2));\n\n\tint fv=0;\n    for(int i=31;i>0;i--){\n    \tfv=((int)bytes_r1[i]+(int)bytes_r2[i]+fv)/256;\n    \tjw[i-1]=fv;\n    }\n\n}\n\n//r1 + x = r2 + r3\nchar *get_prove_data(char *r1, char *r2, char *r3, char *h1, char *h2, char *h3, char *x)\n{\n\tstd::vector<bool> h1_bv(256);\n\tstd::vector<bool> h2_bv(256);\n\tstd::vector<bool> h3_bv(256);\n\tstd::vector<bool> r1_bv(256);\n\tstd::vector<bool> r2_bv(256);\n\tstd::vector<bool> r3_bv(256);\n\tstd::vector<bool> x_bv(256);\n\n\tconst int max_len = (256 / 8) * 2;\n\tCHECK_STR_LEN(r1, max_len, NULL);\n\tCHECK_STR_LEN(r2, max_len, NULL);\n\tCHECK_STR_LEN(r3, max_len, NULL);\n\tCHECK_STR_LEN(h1, max_len, NULL);\n\tCHECK_STR_LEN(h2, max_len, NULL);\n\tCHECK_STR_LEN(h3, max_len, NULL);\n\tCHECK_STR_LEN(x, max_len, NULL);\n\n\thex_str_to_vector(r1, r1_bv);\n\thex_str_to_vector(r2, r2_bv);\n\thex_str_to_vector(r3, r3_bv);\n\thex_str_to_vector(h1, h1_bv);\n\thex_str_to_vector(h2, h2_bv);\n\thex_str_to_vector(h3, h3_bv);\n\thex_str_to_vector(x, x_bv);\n\n    int jw_neg[2][32];\n\t//memset((char *)jw, 0, sizeof(jw));\n\t//set_flag(r1, r2, jw);\n\n\t//write_debug(h1_bv, h2_bv, h3_bv, r1_bv, r2_bv, r3_bv, (int *)jw, \"debug_lib.txt\");\n\n\tauto proof_neg = generate_proof_neg<default_r1cs_ppzksnark_pp>(proving_key, h1_bv, h2_bv, h3_bv, r1_bv, r2_bv, r3_bv,x_bv,jw_neg);\n\tif (!proof_neg) {\n\t\treturn NULL;\n\t}\n\t\n\tcout << \"Proof_neg: \" <<  proof_neg << endl;\n\tstringstream proofStream;\n\tproofStream << *proof_neg;\n\n\tstd::string s = proofStream.str();\n\tunsigned char *dest = (unsigned char *)malloc( s.length() * 2 + 1 );\n\tbytes_to_hex_str((unsigned char *)s.c_str(), dest, s.length());\n\treturn (char *)dest;\n}\n\n\n//if right, return 1. else return 0\nint is_prove_right(char *h1, char *h2, char *h3, char *x, char *prove_data)\n{\n\tstd::vector<bool> h1_bv(256);\n\tstd::vector<bool> h2_bv(256);\n\tstd::vector<bool> h3_bv(256);\n\tstd::vector<bool> x_bv(256);\n \n\tconst int max_len = (256 / 8) * 2;\n\tCHECK_STR_LEN(h1, max_len, 0);\n\tCHECK_STR_LEN(h2, max_len, 0);\n \tCHECK_STR_LEN(h3, max_len, 0);\n \tCHECK_STR_LEN(x, max_len, 0);\n\n\thex_str_to_vector(h1, h1_bv);\n\thex_str_to_vector(h2, h2_bv);\n\thex_str_to_vector(h3, h3_bv);\n\thex_str_to_vector(x, x_bv);\n\n\tr1cs_ppzksnark_proof<default_r1cs_ppzksnark_pp> prove;\n\tunsigned char *bytes = (unsigned char *)malloc(strlen(prove_data) / 2);\n\thex_str_to_bytes(prove_data, bytes, strlen(prove_data));\n\n\tstring s((const char *)bytes, strlen(prove_data)/2);\n\tstringstream proofStream;\n\tproofStream << s;\n\tproofStream >> prove;\n\t\n\n\tint ret;\n\t if(verify_proof(verifycation_key, prove, h1_bv, h2_bv, h3_bv,x_bv)){\n\t \tret = 1;\n    \tcout<<\"verify succ neg\"<<endl;\n     }else{\n\t \tret = 0;\n    \tcout<<\"verify fail neg\"<<endl;\n     }\n\n\tfree(bytes);\n\treturn ret;\n}\n\n\n#ifdef TEST_LIB\n\nint main(int argc, char *argv[])\n{\n\t//init\n    double dur;\n    clock_t start = clock();\n\tinit_setup();\n\tdur = (double)(clock() - start);\n    printf(\"Generate&Load keypair Use Time:%f\\n\\n\",(dur/CLOCKS_PER_SEC));\n\n\t//gen prove\n\tstart = clock();\n\tchar *h1 = list_to_str({39,138,11,164,115,142,207,155,162,115,90,128,61,136,218,78,14,163,205,250,61,5,190,154,54,62,43,131,247,199,132,241});\n\tchar *h2 = list_to_str({199,37,84,153,55,245,80,58,123,28,33,1,179,207,118,141,159,81,118,51,237,63,204,94,143,122,77,36,99,36,207,67});\n\tchar *h3 = list_to_str({209,106,65,239,64,45,254,86,69,25,32,179,2,57,97,164,9,179,130,82,69,202,226,204,227,179,199,101,168,2,103,4});\n\tprintf(\"h1=%s\\n\", h1);\n\tprintf(\"h2=%s\\n\", h2);\n\tprintf(\"h3=%s\\n\", h3);\n\n\tchar *r1 = list_to_str({0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,51,49,49,49,122,49,49,49,122,49,49,49,122,49,49,49});\n\tchar *r2 = list_to_str({0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,50,49,54,54,49,49,54,54,97,98,99,100,97,98,99,100});\n\tchar *r3 = list_to_str({0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,50,97,98,99,100,101,102,103,122,97,98,99,100,101,102,103});\n\tchar *x = list_to_str({0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,49,97,103,104,27,101,107,108,97,146,148,150,75,150,152,154});\n\tprintf(\"r1=%s\\n\", r1);\n\tprintf(\"r2=%s\\n\", r2);\n\tprintf(\"r3=%s\\n\", r3);\n\tprintf(\"x=%s\\n\", x);\n\n\tchar *prove = get_prove_data(r1, r2, r3, h1, h2, h3, x);\n\tprintf(\"prove=%s\\n\", prove);\n\tdur = (double)(clock() - start);\n    printf(\"Generate proof Use Time:%f\\n\\n\",(dur/CLOCKS_PER_SEC));\n\n\t//verify prove\n\tstart = clock();\n\tint is_right = is_prove_right(h1, h2, h3, x, prove);\n\t//int is_right = is_prove_right(h1, h3, h2, prove);\n\tprintf(\"is_right=%d\\n\", is_right);\n\tdur = (double)(clock() - start);\n\tprintf(\"Verify proof Use Time:%f\\n\\n\",(dur/CLOCKS_PER_SEC));\n\n\tfree(prove);\n\n\t\n}\n\n#endif\n\n", "meta": {"hexsha": "f5c793baceedff24f954a172756f4c48400cb7b4", "size": 9295, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/lib_zero_knowledge.cpp", "max_stars_repo_name": "dasenlinCode/lightning_circuit", "max_stars_repo_head_hexsha": "e6eb12623e13bfe62489726c732bf563c17c5169", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-19T02:54:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-01T05:11:27.000Z", "max_issues_repo_path": "src/lib/lib_zero_knowledge.cpp", "max_issues_repo_name": "dasenlinCode/lightning_circuit", "max_issues_repo_head_hexsha": "e6eb12623e13bfe62489726c732bf563c17c5169", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/lib_zero_knowledge.cpp", "max_forks_repo_name": "dasenlinCode/lightning_circuit", "max_forks_repo_head_hexsha": "e6eb12623e13bfe62489726c732bf563c17c5169", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-06-28T12:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-15T08:48:53.000Z", "avg_line_length": 24.0803108808, "max_line_length": 143, "alphanum_fraction": 0.6314147391, "num_tokens": 3361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.2429404898682933}}
{"text": "//---------------------------------------------------------------------------//\n//  MIT License\n//\n//  Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n//  Copyright (c) 2020-2021 Nikita Kaskov <nemo@nil.foundation>\n\n//\n//  Permission is hereby granted, free of charge, to any person obtaining a copy\n//  of this software and associated documentation files (the \"Software\"), to deal\n//  in the Software without restriction, including without limitation the rights\n//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n//  copies of the Software, and to permit persons to whom the Software is\n//  furnished to do so, subject to the following conditions:\n//\n//  The above copyright notice and this permission notice shall be included in all\n//  copies or substantial portions of the Software.\n//\n//  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n//  SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef FILECOIN_STORAGE_PROOFS_POST_ELECTION_VANILLA_HPP\n#define FILECOIN_STORAGE_PROOFS_POST_ELECTION_VANILLA_HPP\n\n#include <boost/log/trivial.hpp>\n\n#include <nil/crypto3/hash/sha2.hpp>\n\n#include <algorithm>\n#include <nil/filecoin/storage/proofs/core/merkle/proof.hpp>\n#include <nil/filecoin/storage/proofs/core/btree/map.hpp>\n#include <nil/filecoin/storage/proofs/core/parameter_cache.hpp>\n#include <nil/filecoin/storage/proofs/core/sector.hpp>\n\nnamespace nil {\n    namespace filecoin {\n        namespace post {\n            namespace election {\n                struct SetupParams {\n                    /// Size of the sector in bytes.\n                    std::uint64_t sector_size;\n                    std::size_t challenge_count;\n                    std::size_t challenged_nodes;\n                };\n\n                struct PublicParams : public parameter_set_metadata {\n                    virtual std::string identifier() const override {\n                        return \"ElectionPoSt::PublicParams{{sector_size: \" + sector_size +\n                               \", count: \" + challenge_count + \", nodes: \" + challenged_nodes + \"}}\";\n                    }\n\n                    /// Size of the sector in bytes.\n                    std::uint64_t sector_size;\n                    std::size_t challenge_count;\n                    std::size_t challenged_nodes;\n                };\n\n                template<typename Domain>\n                struct PublicInputs {\n                    Domain randomness;\n                    sector_id_type sector_id;\n                    Domain prover_id;\n                    Domain comm_r;\n                    Fr partial_ticket;\n                    std::uint64_t sector_challenge_index;\n                };\n\n                template<typename MerkleTreeType>\n                struct PrivateInputs {\n                    MerkleTreeWrapper<typename MerkleTreeType::hash_type, MerkleTreeType::Store,\n                                      MerkleTreeType::base_arity, MerkleTreeType::sub_tree_arity,\n                                      MerkleTreeType::top_tree_arity>\n                        tree;\n                    typename MerkleTreeType::hash_type::digest_type comm_c;\n                    typename MerkleTreeType::hash_type::digest_type comm_r_last;\n                };\n\n                struct Candidate {\n                    sector_id_type sector_id;\n                    Fr partial_ticket;\n                    std::array<std::uint8_t, 32> ticket;\n                    std::uint64_t sector_challenge_index;\n                };\n\n                template<typename BasicMerkleProof>\n                struct Proof {\n                    std::vector<typename BasicMerkleProof::hash_type::digest_type> leafs() {\n                        std::vector<typename BasicMerkleProof::hash_type::digest_type> result;\n                        for (const auto &proof : inclusion_proofs) {\n                            result.emplace_back(proof.leaf());\n                        }\n                        return result;\n                    }\n\n                    typename BasicMerkleProof::hash_type::digest_type comm_r_last() {\n                        return inclusion_proofs[0].root();\n                    }\n\n                    std::vector<typename BasicMerkleProof::hash_type::digest_type> commitments() {\n                        std::vector<typename BasicMerkleProof::hash_type::digest_type> result;\n                        for (const auto &proof : inclusion_proofs) {\n                            result.emplace_back(proof.root());\n                        }\n                        return result;\n                    }\n\n                    std::vector<std::vector<\n                        std::pair<std::vector<typename BasicMerkleProof::hash_type::digest_type>, std::size_t>>>\n                        paths() {\n                        std::vector<std::vector<\n                            std::pair<std::vector<typename BasicMerkleProof::hash_type::digest_type>, std::size_t>>>\n                            result;\n                        for (const auto &proof : inclusion_proofs) {\n                            result.emplace_back(proof.path());\n                        }\n                        return result;\n                    }\n\n                    std::vector<merkletree::MerkleProof<typename BasicMerkleProof::hash, BasicMerkleProof::BaseArity,\n                                                        BasicMerkleProof::SubTreeArity, BasicMerkleProof::TopTreeArity>>\n                        inclusion_proofs;\n\n                    std::array<std::uint8_t, 32> ticket;\n                    typename BasicMerkleProof::hash_type::digest_type comm_c;\n                };\n\n                template<typename MerkleTreeType>\n                class ElectionPoSt\n                    : public proof_scheme<\n                          PublicParams, SetupParams, PublicInputs<typename MerkleTreeType::hash_type::digest_type>,\n                          PrivateInputs<MerkleTreeType>, Proof<typename MerkleTreeType::proof_type>, no_requirements> {\n                    typedef proof_scheme<\n                        PublicParams, SetupParams, PublicInputs<typename MerkleTreeType::hash_type::digest_type>,\n                        PrivateInputs<MerkleTreeType>, Proof<typename MerkleTreeType::proof_type>, no_requirements>\n                        policy_type;\n\n                public:\n                    typedef typename policy_type::public_params_type public_params_type;\n                    typedef typename policy_type::setup_params setup_params_type;\n                    typedef typename policy_type::public_inputs public_inputs_type;\n                    typedef typename policy_type::private_inputs private_inputs_type;\n                    typedef typename policy_type::proof_type proof_type;\n                    typedef typename policy_type::requirements_type requirements_type;\n\n                    virtual public_params_type setup(const setup_params_type &p) override {\n                        return {p.sector_size, p.challenge_count, p.challenged_nodes};\n                    }\n                    virtual proof_type prove(const public_params_type &params, const public_inputs_type &inputs,\n                                             const private_inputs_type &pinputs) override {\n                        // 1. Inclusions proofs of all challenged leafs in all challenged ranges\n                        const auto tree = pinputs.tree;\n                        std::size_t tree_leafs = tree.leafs();\n\n                        BOOST_LOG_TRIVIAL(trace)\n                            << std::format(\"Generating proof for tree of len {} with leafs {}\", tree.len(), tree_leafs);\n\n                        const auto inclusion_proofs =\n                            (0..pub_params.challenge_count)\n                                .into_par_iter()\n                                .flat_map(\n                                    | n |\n                                    {\n                                        // TODO: replace unwrap with proper error handling\n                                        const auto challenged_leaf_start = generate_leaf_challenge(\n                                            pub_params, pub_inputs.randomness, pub_inputs.sector_challenge_index,\n                                            std::uint64_t(n));\n                                        (0..pub_params.challenged_nodes)\n                                            .into_par_iter()\n                                            .map(move | i |\n                                                 {tree.gen_cached_proof(std::uint(challenged_leaf_start) + i, None)})\n                                    })\n                                .collect::<Result<Vec<_>>>();\n\n                        // 2. correct generation of the ticket from the partial_ticket (add this to the candidate)\n                        const auto ticket = finalize_ticket(inputs.partial_ticket);\n\n                        return {inclusion_proofs, ticket, pinputs.comm_c};\n                    }\n                    virtual bool verify(const public_params_type &pub_params, const public_inputs_type &pub_inputs,\n                                        const proof_type &pr) override {\n                        // verify that H(Comm_c || Comm_r_last) == Comm_R\n                        // comm_r_last is the root of the proof\n                        const auto comm_r_last = pr.inclusion_proofs[0].root();\n                        const auto comm_c = pr.comm_c;\n                        const auto comm_r = &pub_inputs.comm_r;\n\n                        if (AsRef ::<[u8]>::as_ref(&<typename MerkleTreeType::hash_type>::Function::hash2(\n                                &comm_c, &comm_r_last, )) != AsRef::<[u8]>::as_ref(comm_r)) {\n                            return false;\n                        }\n\n                        for (int n = 0; n < pub_params.challenge_count; n++) {\n                            const auto challenged_leaf_start = generate_leaf_challenge(\n                                pub_params, pub_inputs.randomness, pub_inputs.sector_challenge_index, n);\n                            for (int i = 0; i < pub_params.challenged_nodes; i++) {\n                                const auto merkle_proof = &proof.inclusion_proofs[n * pub_params.challenged_nodes + i];\n\n                                // validate all comm_r_lasts match\n                                if (merkle_proof.root() != comm_r_last) {\n                                    return false;\n                                }\n\n                                // validate the path length\n                                const auto expected_path_length =\n                                    merkle_proof.expected_len(pub_params.sector_size / NODE_SIZE);\n\n                                if (expected_path_length != merkle_proof.path().size()) {\n                                    return false;\n                                }\n\n                                if (!merkle_proof.validate(challenged_leaf_start + i)) {\n                                    return false;\n                                }\n                            }\n                        }\n\n                        return true;\n                    }\n                };\n\n                template<typename MerkleTreeType>\n                std::vector<Candidate> generate_candidates(\n                    const PublicParams &pub_params, const std::vector<sector_id_type> &challenged_sectors,\n                    const btree::map<sector_id_type,\n                                     MerkleTreeWrapper<typename MerkleTreeType::hash_type,\n                                                       typename MerkleTreeType::store_type, MerkleTreeType::BaseArity,\n                                                       MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity>>\n                        &trees,\n                    const typename MerkleTreeType::hash_type::digest_type &prover_id,\n                    const typename MerkleTreeType::hash_type::digest_type &randomness) {\n                    challenged_sectors.par_iter()\n                        .enumerate()\n                        .map(| (sector_challenge_index, sector_id) |\n                             {\n                                 auto tree;\n                                 switch (trees.get(sector_id)) {\n                                     case Some(tree):\n                                         tree = tree;\n                                         break;\n                                     case None:\n                                         tree = bail !(Error::MissingPrivateInput(\"tree\", (*sector_id).into()));\n                                         break;\n                                 };\n\n                                 generate_candidate::<Tree>(pub_params, tree, prover_id, *sector_id, randomness,\n                                                            std::uint64_t(sector_challenge_index), )\n                             })\n                        .collect()\n                }\n\n                template<typename MerkleTreeType>\n                Candidate generate_candidate(\n                    const PublicParams &pub_params,\n                    const MerkleTreeWrapper<typename MerkleTreeType::hash_type, typename MerkleTreeType::store_type,\n                                            MerkleTreeType::BaseArity, MerkleTreeType::sub_tree_arity,\n                                            MerkleTreeType::top_tree_arity> &tree,\n                    const typename MerkleTreeType::hash_type::digest_type &prover_id, sector_id_type sector_id,\n                    const typename MerkleTreeType::hash_type::digest_type &randomness,\n                    std::uint64_t sector_challenge_index) {\n                    Fr randomness_fr = randomness.into();\n                    Fr prover_id_fr = prover_id.into();\n                    std::vector<MerkleTreeType::hash_type::digest_type> data = {\n                        randomness_fr.into(), prover_id_fr.into(), Fr::from(sector_id).into()};\n\n                    for (int n = 0; n < pub_params.challenge_count; n++) {\n                        const auto challenge =\n                            generate_leaf_challenge(pub_params, randomness, sector_challenge_index, n);\n\n                        Fr val = tree.read_at(challenge as usize).into();\n                        data.push_back(val.into());\n                    }\n\n                    // pad for md\n                    std::size_t arity = PoseidonMDArity;\n                    while (data.size() % arity) {\n                        data.push(MerkleTreeType::hash_type::digest_type::default());\n                    }\n\n                    Fr partial_ticket = PoseidonFunction::hash_md(&data).into();\n\n                    // ticket = sha256(partial_ticket)\n                    std::array<std::uint8_t, 32> ticket = finalize_ticket(&partial_ticket);\n\n                    return {sector_challenge_index, sector_id, partial_ticket, ticket};\n                }\n\n                template<typename FinalizationHash = crypto3::hashes::sha2<256>>\n                std::array<std::uint8_t, 32> finalize_ticket(const Fr &partial_ticket) {\n                    const auto bytes = fr_into_bytes(partial_ticket);\n                    const auto ticket_hash = Sha256::digest(&bytes);\n                    std::array<std::uint8_t, 32> ticket;\n                    ticket.fill(0);\n                    ticket.copy_from_slice(&ticket_hash[..]);\n                    return ticket;\n                }\n\n                bool is_valid_sector_challenge_index(std::uint64_t challenge_count, std::uint64_t index) {\n                    return index < challenge_count;\n                }\n\n                template<typename Domain, typename FinalizationHash = crypto3::hashes::sha2<256>>\n                sector_id_type generate_sector_challenge(const Domain &randomness, std::size_t n,\n                                                         const ordered_sector_set &sectors) {\n                    using namespace crypto3::hashes;\n\n                    accumulator_set<FinalizationHash> acc;\n                    hash<FinalizationHash>(randomness, acc);\n                    hash<FinalizationHash>(n, acc);\n                    const auto hash = accumulators::extract<FinalizationHash>(acc);\n\n                    const auto sector_challenge = LittleEndian::read_u64(&hash[..8]);\n                    std::uint sector_index = (std::uint64_t(sector_challenge % sectors.size()));\n                    const auto sector = *sectors.iter().nth(sector_index).context(\"invalid challenge generated\");\n\n                    return sector;\n                }\n\n                template<typename Domain>\n                std::vector<sector_id_type> generate_sector_challenges(const Domain &randomness,\n                                                                       std::uint64_t challenge_count,\n                                                                       const ordered_sector_set &sectors) {\n                    std::vector<sector_id_type> result(challenge_count);\n                    for (int i = 0; i < challenge_count; i++) {\n                        result[i] = generate_sector_challenge(randomness, i, sectors);\n                    }\n                    return result;\n                }\n\n                /// Generate all challenged leaf ranges for a single sector, such that the range fits into the sector.\n                template<typename Domain>\n                std::vector<std::uint64_t>\n                    generate_leaf_challenges(const PublicParams &pub_params, const Domain &randomness,\n                                             std::uint64_t sector_challenge_index, std::size_t challenge_count) {\n                    std::vector<std::uint64_t> challenges(challenge_count);\n\n                    for (int leaf_challenge_index = 0; leaf_challenge_index < challenge_count; leaf_challenge_index++) {\n                        challenges.emplace_back(generate_leaf_challenge(pub_params, randomness, sector_challenge_index,\n                                                                        leaf_challenge_index));\n                    }\n\n                    return challenges;\n                }\n\n                /// Generates challenge, such that the range fits into the sector.\n                template<typename Domain, typename LeafHash = crypto3::hashes::sha2<256>>\n                std::uint64_t generate_leaf_challenge(const PublicParams &pub_params, const Domain &randomness,\n                                                      std::uint64_t sector_challenge_index,\n                                                      std::uint64_t leaf_challenge_index) {\n                    BOOST_ASSERT_MSG(pub_params.sector_size > pub_params.challenged_nodes * NODE_SIZE,\n                                     \"sector size is too small\");\n\n                    auto hasher = Sha256();\n                    hasher.input(AsRef::<[u8]>::as_ref(&randomness));\n                    hasher.input(&sector_challenge_index.to_le_bytes()[..]);\n                    hasher.input(&leaf_challenge_index.to_le_bytes()[..]);\n                    const auto hash = hasher.result();\n\n                    const auto leaf_challenge = LittleEndian::read_u64(&hash[..8]);\n\n                    std::uint64_t challenged_range_index =\n                        leaf_challenge % (pub_params.sector_size / (pub_params.challenged_nodes * NODE_SIZE));\n\n                    return challenged_range_index * pub_params.challenged_nodes;\n                }\n            }    // namespace election\n        }        // namespace post\n    }            // namespace filecoin\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "1110c4184c0878954bb71f63e6e347e440e36cea", "size": 20088, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/post/election/vanilla.hpp", "max_stars_repo_name": "NilFoundation/crypto3-fil-proofs", "max_stars_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/post/election/vanilla.hpp", "max_issues_repo_name": "NilFoundation/crypto3-fil-proofs", "max_issues_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-06T13:07:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T12:38:09.000Z", "max_forks_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/post/election/vanilla.hpp", "max_forks_repo_name": "NilFoundation/crypto3-fil-proofs", "max_forks_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.4255319149, "max_line_length": 120, "alphanum_fraction": 0.5056252489, "num_tokens": 3450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.24284260700061214}}
{"text": "//\n// Copyright (c) 2018 CNRS\n//\n\n#ifndef __pinocchio_lie_group_collection_hpp__\n#define __pinocchio_lie_group_collection_hpp__\n\n#include \"pinocchio/multibody/liegroup/vector-space.hpp\"\n#include \"pinocchio/multibody/liegroup/cartesian-product.hpp\"\n#include \"pinocchio/multibody/liegroup/special-orthogonal.hpp\"\n#include \"pinocchio/multibody/liegroup/special-euclidean.hpp\"\n\n#include <boost/variant.hpp>\n\nnamespace pinocchio\n{\n  template<typename _Scalar, int _Options = 0>\n  struct LieGroupCollectionDefaultTpl\n  {\n    typedef _Scalar Scalar;\n    enum { Options = _Options };\n    \n    typedef boost::variant<\n     SpecialOrthogonalOperationTpl<2,Scalar,Options>\n    ,SpecialOrthogonalOperationTpl<3,Scalar,Options>\n    ,SpecialEuclideanOperationTpl<2,Scalar,Options>\n    ,SpecialEuclideanOperationTpl<3,Scalar,Options>\n    ,VectorSpaceOperationTpl<1,Scalar,Options>\n    ,VectorSpaceOperationTpl<2,Scalar,Options>\n    ,VectorSpaceOperationTpl<3,Scalar,Options>\n    ,VectorSpaceOperationTpl<Eigen::Dynamic,Scalar,Options>\n    > LieGroupVariant;\n    \n  };\n  \n  typedef LieGroupCollectionDefaultTpl<double> LieGroupCollectionDefault;\n  \n}\n\n#endif // ifndef __pinocchio_lie_group_collection_hpp__\n\n", "meta": {"hexsha": "21362a8b530e8bb89fdd3d21ceeba4d988370ba4", "size": 1193, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/multibody/liegroup/liegroup-collection.hpp", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "src/multibody/liegroup/liegroup-collection.hpp", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "src/multibody/liegroup/liegroup-collection.hpp", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 28.4047619048, "max_line_length": 73, "alphanum_fraction": 0.7845766974, "num_tokens": 311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24277035394449054}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_SCONICS_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_SCONICS_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Original copyright notice:\n \n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/concept_check.hpp>\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace sconics{ \n            static const int EULER = 0;\n            static const int MURD1 = 1;\n            static const int MURD2 = 2;\n            static const int MURD3 = 3;\n            static const int PCONIC = 4;\n            static const int TISSOT = 5;\n            static const int VITK1 = 6;\n            static const double EPS10 = 1.e-10;\n            static const double EPS = 1e-10;\n\n            struct par_sconics\n            {\n                double    n;\n                double    rho_c;\n                double    rho_0;\n                double    sig;\n                double    c1, c2;\n                int        type;\n            };\n            /* get common factors for simple conics */\n            template <typename Parameters>\n                inline int\n            phi12(Parameters& par, par_sconics& proj_parm, double *del) {\n                double p1, p2;\n                int err = 0;\n            \n                if (!pj_param(par.params, \"tlat_1\").i ||\n                    !pj_param(par.params, \"tlat_2\").i) {\n                    err = -41;\n                } else {\n                    p1 = pj_param(par.params, \"rlat_1\").f;\n                    p2 = pj_param(par.params, \"rlat_2\").f;\n                    *del = 0.5 * (p2 - p1);\n                    proj_parm.sig = 0.5 * (p2 + p1);\n                    err = (fabs(*del) < EPS || fabs(proj_parm.sig) < EPS) ? -42 : 0;\n                    *del = *del;\n                }\n                return err;\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_sconics_spheroid : public base_t_fi<base_sconics_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_sconics m_proj_parm;\n\n                inline base_sconics_spheroid(const Parameters& par)\n                    : base_t_fi<base_sconics_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    double rho;\n                \n                    switch (this->m_proj_parm.type) {\n                    case MURD2:\n                        rho = this->m_proj_parm.rho_c + tan(this->m_proj_parm.sig - lp_lat);\n                        break;\n                    case PCONIC:\n                        rho = this->m_proj_parm.c2 * (this->m_proj_parm.c1 - tan(lp_lat - this->m_proj_parm.sig));\n                        // rho = this->m_proj_parm.c2 * (this->m_proj_parm.c1 - tan(lp_lat)); BUG STILL IN proj (reported 2012-03-03)\n                        break;\n                    default:\n                        rho = this->m_proj_parm.rho_c - lp_lat;\n                        break;\n                    }\n                    xy_x = rho * sin( lp_lon *= this->m_proj_parm.n );\n                    xy_y = this->m_proj_parm.rho_0 - rho * cos(lp_lon);\n                }\n\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    double rho;\n                \n                    rho = boost::math::hypot(xy_x, xy_y = this->m_proj_parm.rho_0 - xy_y);\n                    if (this->m_proj_parm.n < 0.) {\n                        rho = - rho;\n                        xy_x = - xy_x;\n                        xy_y = - xy_y;\n                    }\n                    lp_lon = atan2(xy_x, xy_y) / this->m_proj_parm.n;\n                    switch (this->m_proj_parm.type) {\n                    case PCONIC:\n                        lp_lat = atan(this->m_proj_parm.c1 - rho / this->m_proj_parm.c2) + this->m_proj_parm.sig;\n                        break;\n                    case MURD2:\n                        lp_lat = this->m_proj_parm.sig - atan(rho - this->m_proj_parm.rho_c);\n                        break;\n                    default:\n                        lp_lat = this->m_proj_parm.rho_c - rho;\n                    }\n                }\n            };\n\n            template <typename Parameters>\n            void setup(Parameters& par, par_sconics& proj_parm) \n            {\n                boost::ignore_unused_variable_warning(par);\n                boost::ignore_unused_variable_warning(proj_parm);\n                double del, cs;\n                int i;\n                if( (i = phi12(par, proj_parm, &del)) )\n                    throw proj_exception(i);\n                switch (proj_parm.type) {\n                case TISSOT:\n                    proj_parm.n = sin(proj_parm.sig);\n                    cs = cos(del);\n                    proj_parm.rho_c = proj_parm.n / cs + cs / proj_parm.n;\n                    proj_parm.rho_0 = sqrt((proj_parm.rho_c - 2 * sin(par.phi0))/proj_parm.n);\n                    break;\n                case MURD1:\n                    proj_parm.rho_c = sin(del)/(del * tan(proj_parm.sig)) + proj_parm.sig;\n                    proj_parm.rho_0 = proj_parm.rho_c - par.phi0;\n                    proj_parm.n = sin(proj_parm.sig);\n                    break;\n                case MURD2:\n                    proj_parm.rho_c = (cs = sqrt(cos(del))) / tan(proj_parm.sig);\n                    proj_parm.rho_0 = proj_parm.rho_c + tan(proj_parm.sig - par.phi0);\n                    proj_parm.n = sin(proj_parm.sig) * cs;\n                    break;\n                case MURD3:\n                    proj_parm.rho_c = del / (tan(proj_parm.sig) * tan(del)) + proj_parm.sig;\n                    proj_parm.rho_0 = proj_parm.rho_c - par.phi0;\n                    proj_parm.n = sin(proj_parm.sig) * sin(del) * tan(del) / (del * del);\n                    break;\n                case EULER:\n                    proj_parm.n = sin(proj_parm.sig) * sin(del) / del;\n                    del *= 0.5;\n                    proj_parm.rho_c = del / (tan(del) * tan(proj_parm.sig)) + proj_parm.sig;\n                \n                    proj_parm.rho_0 = proj_parm.rho_c - par.phi0;\n                    break;\n                case PCONIC:\n                    proj_parm.n = sin(proj_parm.sig);\n                    proj_parm.c2 = cos(del);\n                    proj_parm.c1 = 1./tan(proj_parm.sig);\n                    if (fabs(del = par.phi0 - proj_parm.sig) - EPS10 >= HALFPI)\n                        throw proj_exception(-43);\n                    proj_parm.rho_0 = proj_parm.c2 * (proj_parm.c1 - tan(del));\n                    break;\n                case VITK1:\n                    proj_parm.n = (cs = tan(del)) * sin(proj_parm.sig) / del;\n                    proj_parm.rho_c = del / (cs * tan(proj_parm.sig)) + proj_parm.sig;\n                    proj_parm.rho_0 = proj_parm.rho_c - par.phi0;\n                    break;\n                }\n                // par.inv = s_inverse;\n                // par.fwd = s_forward;\n                par.es = 0;\n            }\n\n\n            // Tissot\n            template <typename Parameters>\n            void setup_tissot(Parameters& par, par_sconics& proj_parm)\n            {\n                proj_parm.type = TISSOT;\n                setup(par, proj_parm);\n            }\n\n            // Murdoch I\n            template <typename Parameters>\n            void setup_murd1(Parameters& par, par_sconics& proj_parm)\n            {\n                proj_parm.type = MURD1;\n                setup(par, proj_parm);\n            }\n\n            // Murdoch II\n            template <typename Parameters>\n            void setup_murd2(Parameters& par, par_sconics& proj_parm)\n            {\n                proj_parm.type = MURD2;\n                setup(par, proj_parm);\n            }\n\n            // Murdoch III\n            template <typename Parameters>\n            void setup_murd3(Parameters& par, par_sconics& proj_parm)\n            {\n                proj_parm.type = MURD3;\n                setup(par, proj_parm);\n            }\n\n            // Euler\n            template <typename Parameters>\n            void setup_euler(Parameters& par, par_sconics& proj_parm)\n            {\n                proj_parm.type = EULER;\n                setup(par, proj_parm);\n            }\n\n            // Perspective Conic\n            template <typename Parameters>\n            void setup_pconic(Parameters& par, par_sconics& proj_parm)\n            {\n                proj_parm.type = PCONIC;\n                setup(par, proj_parm);\n            }\n\n            // Vitkovsky I\n            template <typename Parameters>\n            void setup_vitk1(Parameters& par, par_sconics& proj_parm)\n            {\n                proj_parm.type = VITK1;\n                setup(par, proj_parm);\n            }\n\n        }} // namespace detail::sconics\n    #endif // doxygen \n\n    /*!\n        \\brief Tissot projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n         - lat_1= and lat_2=\n        \\par Example\n        \\image html ex_tissot.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct tissot_spheroid : public detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline tissot_spheroid(const Parameters& par) : detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::sconics::setup_tissot(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Murdoch I projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n         - lat_1= and lat_2=\n        \\par Example\n        \\image html ex_murd1.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct murd1_spheroid : public detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline murd1_spheroid(const Parameters& par) : detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::sconics::setup_murd1(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Murdoch II projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n         - lat_1= and lat_2=\n        \\par Example\n        \\image html ex_murd2.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct murd2_spheroid : public detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline murd2_spheroid(const Parameters& par) : detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::sconics::setup_murd2(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Murdoch III projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n         - lat_1= and lat_2=\n        \\par Example\n        \\image html ex_murd3.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct murd3_spheroid : public detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline murd3_spheroid(const Parameters& par) : detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::sconics::setup_murd3(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Euler projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n         - lat_1= and lat_2=\n        \\par Example\n        \\image html ex_euler.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct euler_spheroid : public detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline euler_spheroid(const Parameters& par) : detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::sconics::setup_euler(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Perspective Conic projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n         - lat_1= and lat_2=\n        \\par Example\n        \\image html ex_pconic.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct pconic_spheroid : public detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline pconic_spheroid(const Parameters& par) : detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::sconics::setup_pconic(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Vitkovsky I projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n         - lat_1= and lat_2=\n        \\par Example\n        \\image html ex_vitk1.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct vitk1_spheroid : public detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline vitk1_spheroid(const Parameters& par) : detail::sconics::base_sconics_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::sconics::setup_vitk1(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Factory entry(s)\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class tissot_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<tissot_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class murd1_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<murd1_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class murd2_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<murd2_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class murd3_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<murd3_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class euler_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<euler_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class pconic_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<pconic_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class vitk1_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<vitk1_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void sconics_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"tissot\", new tissot_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"murd1\", new murd1_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"murd2\", new murd2_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"murd3\", new murd3_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"euler\", new euler_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"pconic\", new pconic_entry<Geographic, Cartesian, Parameters>);\n            factory.add_to_factory(\"vitk1\", new vitk1_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail \n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_SCONICS_HPP\n\n", "meta": {"hexsha": "f5a536af00c02abc5e1b4cbb693c753f37fbf291", "size": 21391, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/gis/projections/proj/sconics.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "boost/geometry/extensions/gis/projections/proj/sconics.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "boost/geometry/extensions/gis/projections/proj/sconics.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 41.6167315175, "max_line_length": 134, "alphanum_fraction": 0.5808985087, "num_tokens": 4716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24277035394449054}}
{"text": "/* Copyright (c) 2016 - 2020, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#ifndef ADAMANTINE_HH\n#define ADAMANTINE_HH\n\n#include <Geometry.hh>\n#include <PostProcessor.hh>\n#include <ThermalPhysics.hh>\n#include <Timer.hh>\n#include <utils.hh>\n\n#include <deal.II/base/mpi.h>\n#include <deal.II/distributed/solution_transfer.h>\n#include <deal.II/grid/filtered_iterator.h>\n#include <deal.II/grid/grid_refinement.h>\n#include <deal.II/numerics/error_estimator.h>\n\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <boost/property_tree/info_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n#include <cmath>\n#include <iostream>\n\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value,\n              int> = 0>\nvoid output_pvtu(\n    adamantine::PostProcessor<dim> &post_processor, unsigned int cycle,\n    unsigned int n_time_step, double time,\n    dealii::AffineConstraints<double> const &affine_constraints,\n    dealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType>\n        &solution)\n{\n  affine_constraints.distribute(solution);\n  post_processor.output_pvtu(cycle, n_time_step, time, solution);\n}\n\n#ifdef ADAMANTINE_HAVE_CUDA\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\nvoid output_pvtu(\n    adamantine::PostProcessor<dim> &post_processor, unsigned int cycle,\n    unsigned int n_time_step, double time,\n    dealii::AffineConstraints<double> const &affine_constraints,\n    dealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType>\n        &solution)\n{\n  dealii::LinearAlgebra::distributed::Vector<double, dealii::MemorySpace::Host>\n      solution_host(solution.get_partitioner());\n  solution_host.import(solution, dealii::VectorOperation::insert);\n  affine_constraints.distribute(solution_host);\n  post_processor.output_pvtu(cycle, n_time_step, time, solution_host);\n}\n#endif\n\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value,\n              int> = 0>\ndealii::Vector<float> estimate_error(\n    dealii::parallel::distributed::Triangulation<dim> const &triangulation,\n    dealii::DoFHandler<dim> const &dof_handler, int fe_degree,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &solution)\n{\n  dealii::Vector<float> estimated_error_per_cell(\n      triangulation.n_active_cells());\n  dealii::KellyErrorEstimator<dim>::estimate(\n      dof_handler, dealii::QGauss<dim - 1>(fe_degree + 1),\n      std::map<dealii::types::boundary_id,\n               const dealii::Function<dim, double> *>(),\n      solution, estimated_error_per_cell, dealii::ComponentMask(), nullptr, 0,\n      triangulation.locally_owned_subdomain());\n\n  return estimated_error_per_cell;\n}\n\n#ifdef ADAMANTINE_HAVE_CUDA\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\ndealii::Vector<float> estimate_error(\n    dealii::parallel::distributed::Triangulation<dim> const &triangulation,\n    dealii::DoFHandler<dim> const &dof_handler, int fe_degree,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &solution)\n{\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>\n      solution_host(solution.get_partitioner());\n  solution_host.import(solution, dealii::VectorOperation::insert);\n  dealii::Vector<float> estimated_error_per_cell(\n      triangulation.n_active_cells());\n  dealii::KellyErrorEstimator<dim>::estimate(\n      dof_handler, dealii::QGauss<dim - 1>(fe_degree + 1),\n      std::map<dealii::types::boundary_id,\n               const dealii::Function<dim, double> *>(),\n      solution_host, estimated_error_per_cell, dealii::ComponentMask(), nullptr,\n      0, triangulation.locally_owned_subdomain());\n\n  return estimated_error_per_cell;\n}\n#endif\n\n// inlining this function so we can have in the header\ninline void initialize_timers(MPI_Comm const &communicator,\n                              std::vector<adamantine::Timer> &timers)\n{\n  timers.push_back(adamantine::Timer(communicator, \"Main\"));\n  timers.push_back(adamantine::Timer(communicator, \"Refinement\"));\n  timers.push_back(adamantine::Timer(communicator, \"Evolve One Time Step\"));\n  timers.push_back(adamantine::Timer(\n      communicator, \"Evolve One Time Step: evaluate_thermal_physics\"));\n  timers.push_back(adamantine::Timer(\n      communicator, \"Evolve One Time Step: id_minus_tau_J_inverse\"));\n  timers.push_back(adamantine::Timer(\n      communicator, \"Evolve One Time Step: evaluate_material_properties\"));\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nstd::vector<std::unique_ptr<adamantine::ElectronBeam<dim>>> &initialize(\n    MPI_Comm const &communicator, boost::property_tree::ptree const &database,\n    adamantine::Geometry<dim> &geometry,\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics)\n{\n  thermal_physics.reset(\n      new adamantine::ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                                     QuadratureType>(communicator, database,\n                                                     geometry));\n  return static_cast<adamantine::ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                                                QuadratureType> *>(\n             thermal_physics.get())\n      ->get_electron_beams();\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nstd::vector<std::unique_ptr<adamantine::ElectronBeam<dim>>> &\ninitialize_quadrature(\n    std::string const &quadrature_type, MPI_Comm const &communicator,\n    boost::property_tree::ptree const &database,\n    adamantine::Geometry<dim> &geometry,\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics)\n{\n  if (quadrature_type.compare(\"gauss\") == 0)\n    return initialize<dim, fe_degree, MemorySpaceType, dealii::QGauss<1>>(\n        communicator, database, geometry, thermal_physics);\n  else\n  {\n    adamantine::ASSERT_THROW(quadrature_type.compare(\"lobatto\") == 0,\n                             \"quadrature should be Gauss or Lobatto.\");\n    return initialize<dim, fe_degree, MemorySpaceType,\n                      dealii::QGaussLobatto<1>>(communicator, database,\n                                                geometry, thermal_physics);\n  }\n}\n\ntemplate <int dim, typename MemorySpaceType>\nstd::vector<std::unique_ptr<adamantine::ElectronBeam<dim>>> &\ninitialize_thermal_physics(\n    unsigned int fe_degree, std::string const &quadrature_type,\n    MPI_Comm const &communicator, boost::property_tree::ptree const &database,\n    adamantine::Geometry<dim> &geometry,\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics)\n{\n  switch (fe_degree)\n  {\n  case 1:\n  {\n    return initialize_quadrature<dim, 1, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 2:\n  {\n    return initialize_quadrature<dim, 2, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 3:\n  {\n    return initialize_quadrature<dim, 3, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 4:\n  {\n    return initialize_quadrature<dim, 4, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 5:\n  {\n    return initialize_quadrature<dim, 5, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 6:\n  {\n    return initialize_quadrature<dim, 6, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 7:\n  {\n    return initialize_quadrature<dim, 7, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 8:\n  {\n    return initialize_quadrature<dim, 8, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  case 9:\n  {\n    return initialize_quadrature<dim, 9, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  default:\n  {\n    adamantine::ASSERT_THROW(fe_degree == 10,\n                             \"fe_degree should be between 1 and 10.\");\n    return initialize_quadrature<dim, 10, MemorySpaceType>(\n        quadrature_type, communicator, database, geometry, thermal_physics);\n  }\n  }\n}\n\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value,\n              int> = 0>\nvoid refine_and_transfer(\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics,\n    dealii::DoFHandler<dim> &dof_handler,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &solution)\n{\n  dealii::parallel::distributed::Triangulation<dim> &triangulation =\n      dynamic_cast<dealii::parallel::distributed::Triangulation<dim> &>(\n          const_cast<dealii::Triangulation<dim> &>(\n              dof_handler.get_triangulation()));\n\n  std::shared_ptr<adamantine::MaterialProperty<dim>> material_property =\n      thermal_physics->get_material_property();\n\n  dealii::parallel::distributed::SolutionTransfer<\n      dim, dealii::LA::distributed::Vector<double, MemorySpaceType>>\n      solution_transfer(dof_handler);\n  std::vector<dealii::parallel::distributed::SolutionTransfer<\n      dim, dealii::LA::distributed::Vector<double, MemorySpaceType>>>\n  material_state(\n      static_cast<unsigned int>(adamantine::MaterialState::SIZE),\n      dealii::parallel::distributed::SolutionTransfer<\n          dim, dealii::LA::distributed::Vector<double, MemorySpaceType>>(\n          material_property->get_dof_handler()));\n\n  // We need to update the ghost values before we can do the interpolation on\n  // the new mesh.\n  solution.update_ghost_values();\n\n  // Prepare the Triangulation and the diffent SolutionTransfers for refinement\n  triangulation.prepare_coarsening_and_refinement();\n  solution_transfer.prepare_for_coarsening_and_refinement(solution);\n  for (unsigned int i = 0;\n       i < static_cast<unsigned int>(adamantine::MaterialState::SIZE); ++i)\n    material_state[i].prepare_for_coarsening_and_refinement(\n        material_property->get_state()[i]);\n\n  // Execute the refinement\n  triangulation.execute_coarsening_and_refinement();\n\n  // Update the AffineConstraints and resize the solution\n  thermal_physics->setup_dofs();\n  thermal_physics->initialize_dof_vector(solution);\n\n  // Update MaterialProperty DoFHandler and resize the state vectors\n  material_property->reinit_dofs();\n\n  // Interpolate the solution and the state onto the new mesh\n  solution_transfer.interpolate(solution);\n  for (unsigned int i = 0;\n       i < static_cast<unsigned int>(adamantine::MaterialState::SIZE); ++i)\n    material_state[i].interpolate(material_property->get_state()[i]);\n\n#if ADAMANTINE_DEBUG\n  // Check that we are not losing material\n  std::array<dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>,\n             static_cast<unsigned int>(adamantine::MaterialState::SIZE)>\n      state = material_property->get_state();\n  unsigned int const local_size = state[0].local_size();\n  unsigned int constexpr n_material_states =\n      static_cast<unsigned int>(adamantine::MaterialState::SIZE);\n  for (unsigned int i = 0; i < local_size; ++i)\n  {\n    double material_ratio = 0.;\n    for (unsigned int j = 0; j < n_material_states; ++j)\n      material_ratio += state[j].local_element(i);\n    adamantine::ASSERT(std::abs(material_ratio - 1.) < 1e-14,\n                       \"Material is lost.\");\n  }\n#endif\n}\n\n#ifdef ADAMANTINE_HAVE_CUDA\ntemplate <int dim, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\nvoid refine_and_transfer(\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics,\n    dealii::DoFHandler<dim> &dof_handler,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &solution)\n{\n  dealii::parallel::distributed::Triangulation<dim> &triangulation =\n      dynamic_cast<dealii::parallel::distributed::Triangulation<dim> &>(\n          const_cast<dealii::Triangulation<dim> &>(\n              dof_handler.get_triangulation()));\n\n  std::shared_ptr<adamantine::MaterialProperty<dim>> material_property =\n      thermal_physics->get_material_property();\n\n  dealii::parallel::distributed::SolutionTransfer<\n      dim, dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>>\n      solution_transfer(dof_handler);\n  std::vector<dealii::parallel::distributed::SolutionTransfer<\n      dim, dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>>>\n  material_state(\n      static_cast<unsigned int>(adamantine::MaterialState::SIZE),\n      dealii::parallel::distributed::SolutionTransfer<\n          dim,\n          dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>>(\n          material_property->get_dof_handler()));\n\n  // We need to update the ghost values before we can do the interpolation on\n  // the new mesh.\n  solution.update_ghost_values();\n\n  // Prepare the Triangulation and the diffent SolutionTransfers for refinement\n  triangulation.prepare_coarsening_and_refinement();\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>\n      solution_host(solution.get_partitioner());\n  solution_host.import(solution, dealii::VectorOperation::insert);\n  solution_transfer.prepare_for_coarsening_and_refinement(solution_host);\n  for (unsigned int i = 0;\n       i < static_cast<unsigned int>(adamantine::MaterialState::SIZE); ++i)\n    material_state[i].prepare_for_coarsening_and_refinement(\n        material_property->get_state()[i]);\n\n  // Execute the refinement\n  triangulation.execute_coarsening_and_refinement();\n\n  // Update MaterialProperty DoFHandler and resize the state vectors\n  material_property->reinit_dofs();\n\n  // Update the AffineConstraints and resize the solution\n  thermal_physics->setup_dofs();\n  thermal_physics->initialize_dof_vector(solution);\n  solution_host.reinit(solution.get_partitioner());\n\n  // Interpolate the solution and the state onto the new mesh\n  solution_transfer.interpolate(solution_host);\n  solution.import(solution_host, dealii::VectorOperation::insert);\n  for (unsigned int i = 0;\n       i < static_cast<unsigned int>(adamantine::MaterialState::SIZE); ++i)\n    material_state[i].interpolate(material_property->get_state()[i]);\n\n#if ADAMANTINE_DEBUG\n  // Check that we are not losing material\n  std::array<dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>,\n             static_cast<unsigned int>(adamantine::MaterialState::SIZE)>\n      state = material_property->get_state();\n  unsigned int const local_size = state[0].local_size();\n  unsigned int constexpr n_material_states =\n      static_cast<unsigned int>(adamantine::MaterialState::SIZE);\n  for (unsigned int i = 0; i < local_size; ++i)\n  {\n    double material_ratio = 0.;\n    for (unsigned int j = 0; j < n_material_states; ++j)\n      material_ratio += state[j].local_element(i);\n    adamantine::ASSERT(std::abs(material_ratio - 1.) < 1e-14,\n                       \"Material is lost.\");\n  }\n#endif\n}\n#endif\n\ntemplate <int dim>\nstd::vector<typename dealii::parallel::distributed::Triangulation<\n    dim>::active_cell_iterator>\ncompute_cells_to_refine(\n    dealii::parallel::distributed::Triangulation<dim> &triangulation,\n    double const time, double const next_refinement_time,\n    unsigned int const n_time_steps,\n    std::vector<std::unique_ptr<adamantine::ElectronBeam<dim>>> &electron_beams)\n{\n  // The save_time()/rewind_time() functions are used to save the current time\n  // and row in the list of beam positions. It does nothing when the position is\n  // given by an analytic formula.\n  for (auto &beam : electron_beams)\n    beam->save_time();\n\n  // Compute the position of the beams between time and next_refinement_time and\n  // refine the mesh where the source is greater than 1e-15. This cut-off is due\n  // to the fact that the source is gaussian and thus never strictly zero. If\n  // the beams intersect, some cells will appear twice in the vector. This is\n  // not a problem.\n  std::vector<typename dealii::parallel::distributed::Triangulation<\n      dim>::active_cell_iterator>\n      cells_to_refine;\n  for (unsigned int i = 0; i < n_time_steps; ++i)\n  {\n    double const current_time = time + static_cast<double>(i) /\n                                           static_cast<double>(n_time_steps) *\n                                           (next_refinement_time - time);\n    for (auto &beam : electron_beams)\n    {\n      beam->set_time(current_time);\n      for (auto cell : dealii::filter_iterators(\n               triangulation.active_cell_iterators(),\n               dealii::IteratorFilters::LocallyOwnedCell()))\n        if (beam->value(cell->center()) > 1e-15)\n          cells_to_refine.push_back(cell);\n    }\n  }\n\n  for (auto &beam : electron_beams)\n    beam->rewind_time();\n\n  return cells_to_refine;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType>\nvoid refine_mesh(\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &solution,\n    std::vector<std::unique_ptr<adamantine::ElectronBeam<dim>>> &electron_beams,\n    double const time, double const next_refinement_time,\n    unsigned int const time_steps_refinement,\n    boost::property_tree::ptree const &refinement_database)\n{\n  dealii::DoFHandler<dim> &dof_handler = thermal_physics->get_dof_handler();\n  // Use the Kelly error estimator to refine the mesh. This is done so that the\n  // part of the domain that were heated stay refined.\n  unsigned int const n_kelly_refinements =\n      refinement_database.get(\"n_heat_refinements\", 2);\n  double coarsening_fraction = 0.3;\n  double refining_fraction = 0.6;\n  double cells_fraction = refinement_database.get(\"heat_cell_ratio\", 1.);\n  dealii::parallel::distributed::Triangulation<dim> &triangulation =\n      dynamic_cast<dealii::parallel::distributed::Triangulation<dim> &>(\n          const_cast<dealii::Triangulation<dim> &>(\n              dof_handler.get_triangulation()));\n  // Number of times the mesh on the beam paths will be refined and maximum\n  // number of time a cell can be refined.\n  unsigned int const n_beam_refinements =\n      refinement_database.get(\"n_beam_refinements\", 2);\n  int max_level = refinement_database.get<int>(\"max_level\");\n  for (unsigned int i = 0; i < n_kelly_refinements; ++i)\n  {\n    // Estimate the error. For simplicity, always use dealii::QGauss\n    dealii::Vector<float> estimated_error_per_cell =\n        estimate_error(triangulation, dof_handler, fe_degree, solution);\n\n    // Flag the cells for refinement.\n    unsigned int new_n_cells = static_cast<unsigned int>(\n        cells_fraction *\n        static_cast<double>(triangulation.n_global_active_cells()));\n    dealii::GridRefinement::refine_and_coarsen_fixed_fraction(\n        triangulation, estimated_error_per_cell, refining_fraction,\n        coarsening_fraction, new_n_cells);\n\n    // Don't refine cells that are already as much refined as it is allowed.\n    for (auto cell :\n         dealii::filter_iterators(triangulation.active_cell_iterators(),\n                                  dealii::IteratorFilters::LocallyOwnedCell()))\n      if (cell->level() >= max_level)\n        cell->clear_refine_flag();\n\n    // Execute the refinement and transfer the solution onto the new mesh.\n    refine_and_transfer(thermal_physics, dof_handler, solution);\n  }\n\n  // Refine the mesh along the trajectory of the sources.\n  for (unsigned int i = 0; i < n_beam_refinements; ++i)\n  {\n    // Compute the cells to be refined.\n    std::vector<typename dealii::parallel::distributed::Triangulation<\n        dim>::active_cell_iterator>\n        cells_to_refine =\n            compute_cells_to_refine(triangulation, time, next_refinement_time,\n                                    time_steps_refinement, electron_beams);\n\n    // Flag the cells for refinement.\n    for (auto &cell : cells_to_refine)\n      if (cell->level() < max_level)\n        cell->set_refine_flag();\n\n    // Execute the refinement and transfer the solution onto the new mesh.\n    refine_and_transfer(thermal_physics, dof_handler, solution);\n  }\n\n  // Recompute the inverse of the mass matrix\n  thermal_physics->compute_inverse_mass_matrix();\n}\n\ntemplate <int dim, typename MemorySpaceType>\nvoid refine_mesh(\n    std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> &thermal_physics,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> &solution,\n    std::vector<std::unique_ptr<adamantine::ElectronBeam<dim>>> &electron_beams,\n    double const time, double const next_refinement_time,\n    unsigned int const time_steps_refinement,\n    boost::property_tree::ptree const &refinement_database,\n    unsigned int const fe_degree)\n{\n  switch (fe_degree)\n  {\n  case 1:\n  {\n    refine_mesh<dim, 1>(thermal_physics, solution, electron_beams, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 2:\n  {\n    refine_mesh<dim, 2>(thermal_physics, solution, electron_beams, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 3:\n  {\n    refine_mesh<dim, 3>(thermal_physics, solution, electron_beams, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 4:\n  {\n    refine_mesh<dim, 4>(thermal_physics, solution, electron_beams, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 5:\n  {\n    refine_mesh<dim, 5>(thermal_physics, solution, electron_beams, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 6:\n  {\n    refine_mesh<dim, 6>(thermal_physics, solution, electron_beams, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 7:\n  {\n    refine_mesh<dim, 7>(thermal_physics, solution, electron_beams, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 8:\n  {\n    refine_mesh<dim, 8>(thermal_physics, solution, electron_beams, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 9:\n  {\n    refine_mesh<dim, 9>(thermal_physics, solution, electron_beams, time,\n                        next_refinement_time, time_steps_refinement,\n                        refinement_database);\n    break;\n  }\n  case 10:\n  {\n    refine_mesh<dim, 10>(thermal_physics, solution, electron_beams, time,\n                         next_refinement_time, time_steps_refinement,\n                         refinement_database);\n    break;\n  }\n  default:\n  {\n    adamantine::ASSERT_THROW(false, \"fe_degree should be between 1 and 10.\");\n  }\n  }\n}\n\ntemplate <int dim, typename MemorySpaceType>\ndealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType>\nrun(MPI_Comm const &communicator, boost::property_tree::ptree const &database,\n    std::vector<adamantine::Timer> &timers)\n{\n  // Extract property tree children\n  boost::property_tree::ptree geometry_database =\n      database.get_child(\"geometry\");\n  boost::property_tree::ptree discretization_database =\n      database.get_child(\"discretization\");\n  boost::property_tree::ptree time_stepping_database =\n      database.get_child(\"time_stepping\");\n  boost::property_tree::ptree post_processor_database =\n      database.get_child(\"post_processor\");\n  boost::property_tree::ptree refinement_database =\n      database.get_child(\"refinement\");\n\n  unsigned int const fe_degree =\n      discretization_database.get<unsigned int>(\"fe_degree\");\n  std::string quadrature_type =\n      discretization_database.get(\"quadrature\", \"gauss\");\n  std::transform(quadrature_type.begin(), quadrature_type.end(),\n                 quadrature_type.begin(),\n                 [](unsigned char c) { return std::tolower(c); });\n  double const initial_temperature =\n      database.get(\"materials.initial_temperature\", 300.);\n\n  adamantine::Geometry<dim> geometry(communicator, geometry_database);\n  std::unique_ptr<adamantine::Physics<dim, MemorySpaceType>> thermal_physics;\n  std::vector<std::unique_ptr<adamantine::ElectronBeam<dim>>> &electron_beams =\n      initialize_thermal_physics<dim>(fe_degree, quadrature_type, communicator,\n                                      database, geometry, thermal_physics);\n  adamantine::PostProcessor<dim> post_processor(\n      communicator, post_processor_database, thermal_physics->get_dof_handler(),\n      thermal_physics->get_material_property());\n\n  thermal_physics->setup_dofs();\n  thermal_physics->compute_inverse_mass_matrix();\n  dealii::LA::distributed::Vector<double, MemorySpaceType> solution;\n  thermal_physics->initialize_dof_vector(initial_temperature, solution);\n  unsigned int progress = 0;\n  unsigned int cycle = 0;\n  unsigned int n_time_step = 0;\n  double time = 0.;\n  // Output the initial solution\n  dealii::AffineConstraints<double> &affine_constraints =\n      thermal_physics->get_affine_constraints();\n  output_pvtu(post_processor, cycle, n_time_step, time, affine_constraints,\n              solution);\n  ++n_time_step;\n\n  bool const verbose_refinement = refinement_database.get(\"verbose\", false);\n  unsigned int const time_steps_refinement =\n      refinement_database.get(\"time_steps_between_refinement\", 10);\n  double next_refinement_time = time;\n  double time_step = time_stepping_database.get<double>(\"time_step\");\n  double const duration = time_stepping_database.get<double>(\"duration\");\n  while (time < duration)\n  {\n    if ((time + time_step) > duration)\n      time_step = duration - time;\n    unsigned int rank = dealii::Utilities::MPI::this_mpi_process(communicator);\n\n    // Refine the mesh after time_steps_refinement time steps or when time is\n    // greater or equal than the next predicted time for refinement. This is\n    // necessary when using an embedded method.\n    if (((n_time_step % time_steps_refinement) == 0) ||\n        (time >= next_refinement_time))\n    {\n      next_refinement_time = time + time_steps_refinement * time_step;\n      timers[adamantine::refine].start();\n      refine_mesh(thermal_physics, solution, electron_beams, time,\n                  next_refinement_time, time_steps_refinement,\n                  refinement_database, fe_degree);\n      timers[adamantine::refine].stop();\n      if ((rank == 0) && (verbose_refinement == true))\n        std::cout << \"n_dofs: \" << thermal_physics->get_dof_handler().n_dofs()\n                  << std::endl;\n    }\n\n    // time can be different than time + time_step if an embedded scheme is\n    // used.\n    timers[adamantine::evol_time].start();\n    time = thermal_physics->evolve_one_time_step(time, time_step, solution,\n                                                 timers);\n    timers[adamantine::evol_time].stop();\n\n    // Get the new time step\n    time_step = thermal_physics->get_delta_t_guess();\n\n    // Output progress on screen\n    if (rank == 0)\n    {\n      double adim_time = time / (duration / 10.);\n      double int_part = 0;\n      std::modf(adim_time, &int_part);\n      if (int_part > progress)\n      {\n        std::cout << int_part * 10 << '%' << \" completed\" << std::endl;\n        ++progress;\n      }\n    }\n\n    // Output the solution\n    output_pvtu(post_processor, cycle, n_time_step, time, affine_constraints,\n                solution);\n    ++n_time_step;\n  }\n  post_processor.output_pvd();\n\n  // This is only used for integration test\n  return solution;\n}\n#endif\n", "meta": {"hexsha": "7604278c53c266b4cd0d58bf5d643687c680f3dc", "size": 28378, "ext": "hh", "lang": "C++", "max_stars_repo_path": "application/adamantine.hh", "max_stars_repo_name": "stvdwtt/adamantine", "max_stars_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "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": "application/adamantine.hh", "max_issues_repo_name": "stvdwtt/adamantine", "max_issues_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "application/adamantine.hh", "max_forks_repo_name": "stvdwtt/adamantine", "max_forks_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9127988748, "max_line_length": 80, "alphanum_fraction": 0.6986045528, "num_tokens": 6650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24276020557110273}}
{"text": "/********************************************************************\n\tcreated:\t2013/01/10\n\tcreated:\t10:1:2013   9:15\n\tfilename: \tSimpleFinder.cpp\n\tfile path:\tGAG\\src\\GAGPL\\SPECTRUM\n\tfile base:\tSimpleFinder\n\tfile ext:\tcpp\n\tauthor:\t\tHan Hu\n\t\n\tpurpose:\t\n*********************************************************************/\n\n#include <algorithm>\n#include \"GAGPL/SPECTRUM/SimpleFinder.h\"\n#include <boost/foreach.hpp>\n#include <boost/lambda/lambda.hpp>\n\nnamespace gag\n{\n\tSimpleFinder::SimpleFinder(RichList& spec)\n\t\t: spectrum(spec), param(Param::Instance()), pt(PeriodicTable::Instance())\n\t{\n\t\tint precursor_charge = param.getParameter<int>(\"precursor_charge\").first;\n\n\t\tdouble pre_mz = param.getParameter<double>(\"precursor_mz\").first;\n\t\tprecursor_mass = calculateMass(pre_mz, precursor_charge);\n\n\t\t/* \n\t\tGuess the range of average formula. Usually we assume the difference between composition estimated from the base peak and the one estimated from monoisotopic peak can be safely ignored.\n\t\t\tNo Sulfur (100D)\t\tHigh Sulfur (100D) \n\t\t\tC: 3.7238523        1.9961864\n\t\t\tH: 5.4425534        2.9942796\n\t\t\tO: 2.8645018        3.1938983\n\t\t\tN: 0.2864502        0.1996186\n\t\t\tS: 0                0.5988559\n\t\t*/\n\t\tno_sulfur_ave.insert(std::make_pair(\"C\", 3.7238523));\n\t\tno_sulfur_ave.insert(std::make_pair(\"H\", 5.4425534));\n\t\tno_sulfur_ave.insert(std::make_pair(\"O\", 2.8645018));\n\t\tno_sulfur_ave.insert(std::make_pair(\"N\", 0.2864502));\n\t\tno_sulfur_ave.insert(std::make_pair(\"S\", 0.0));\n\n\t\tmax_sulfur_ave.insert(std::make_pair(\"C\", 1.9961864));\n\t\tmax_sulfur_ave.insert(std::make_pair(\"H\", 2.9942796));\n\t\tmax_sulfur_ave.insert(std::make_pair(\"O\", 3.1938983));\n\t\tmax_sulfur_ave.insert(std::make_pair(\"N\", 0.1996186));\n\t\tmax_sulfur_ave.insert(std::make_pair(\"S\", 0.5988559));\n\t\trun();\n\t}\n\t\n\tvoid SimpleFinder::run()\n\t{\n\t\t// There is a need to divide the spectrum into separate islands at this moment.\n\t\tRichPeakListBySignalOverNoise& pks_sn = spectrum.getPeakListByType<peak_signal_noise>();\n\n\t\t// The S/N threshold for monoisotopic peak.\n\t\tdouble mono_sn_threshold = param.getParameter<double>(\"signal_noise\").first;\n\n\t\tRichPeakListBySignalOverNoise::iterator end_sn = pks_sn.upper_bound(mono_sn_threshold);\t\t\n\t\tRichPeakListBySignalOverNoise::iterator iter_sn = pks_sn.begin();\n\t\t//end_iter--;\n\n\t\t// Start from the peak with highest s/n\n\t\tfor(; iter_sn != end_sn; iter_sn++) {\n\t\t\tthis->findNextEnvelop(spectrum, *iter_sn);\n\t\t}\n\n\t\tstd::cout << \"Before optimizing, output all the envelop information...\" << std::endl;\n\t\tBOOST_FOREACH(EnvelopPtr env, env_pool)\n\t\t\tthis->printEnvelop(env);\n\n\t\tstd::cout << std::endl;\n\n\t\t//std::cout << \"After optimizing...\" << std::endl;\n\t\t//Estimate parameters for each envelop and update the peak information.\n\t\tthis->optimizeEnvelopSet(env_pool);\n\t\tthis->optimizeSuspiciousPeaks();\n\n\t}\n\n\tvoid SimpleFinder::findNextEnvelop(RichList& pk_list, RichPeakPtr base_pk, bool raw_spec /* = true */)\n\t{\n\t\t// Remove the neighbor peak.\n\t\tstd::cout << \"Check if peak \" << base_pk->mz << \" is in the black list\" << std::endl;\n\t\n\t\tif(!base_pk->pk_status) {\n\t\t\tstd::cout << \"Peak \" << base_pk->mz << \" is a noise peak.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tdouble mz = base_pk->mz;\n\n\t\t// Process the apodization problem.\n\t\tthis->cleanNeighborNoise(pk_list, base_pk);\n\n\t\tint precursor_charge = param.getParameter<int>(\"precursor_charge\").first;\n\t\t\n\t\tdouble signal_noise = param.getParameter<double>(\"signal_noise\").first;\n\n\t\tint sign = (precursor_charge > 0 ? 1 : -1);\n\t\tbool suspicious_pk = true;\n\n\t\tfor(int z = abs(precursor_charge); z>=1; z--) {\n\t\n\t\t\t// The actual mass is allowed to be larger than precursor mass.\n\t\t\t//double mass = calculateMass((*iter_intensity)->mz, sign * z);\n\t\t\t//if(mass > precursor_mass) continue;\n\n\t\t\t// Not a qualified peak due to its poor intensity.\n\t\t\tif(base_pk->signal_noise < signal_noise) continue;\n\t\t\t\n\t\t\tstd::cout << \"Identify base peak: \" << base_pk->mz << \" Charge: \" << z;\n\t\t\tstd::cout << (precursor_charge > 0 ? \"+\" : \"-\") << std::endl;\n\n\t\t\tbool status = this->extendEnvelop(pk_list, base_pk, z, raw_spec);\n\t\t\t\n\t\t\tif(status) { \n\t\t\t\tsuspicious_pk = false;\n\t\t\t\t// If the S/N of the base peak is higher than 200.\n\t\t\t\tif(base_pk->signal_noise > 200)\n\t\t\t\t\tthis->detectHarmonicCluster(base_pk, sign * z);\n\t\t\t}\n\n\t\t}\n\n\t\tif(suspicious_pk)\n\t\t\tsetPeakType(base_pk, \"ISO\");\n\t}\n\n\tvoid SimpleFinder::optimizeEnvelopSet(std::set<EnvelopPtr>& env_set)\n\t{\n\t\t// Start from low m/z to high m/z.\n\t\tRichList pk_list = env_ref.getRichPeakList(env_set);\n\t\tRichPeakListByMZ& pk_mz = pk_list.getPeakListByType<peak_mz>();\n\n\t\t// Guess the number of sulfate.\n\t\tBOOST_FOREACH(EnvelopPtr env, env_set)\n\t\t\tthis->updateEnvelopParameter(env);\n\n\t\tfor(RichPeakListByMZ::iterator mz_iter = pk_mz.begin(); \n\t\t\tmz_iter != pk_mz.end(); mz_iter++)\n\t\t{\n\t\t\tRichPeakPtr pk = *mz_iter;\n\t\t\tdouble mz = pk->mz;\n\t\t\tstd::cout << \"Check peak \" << pk->mz << std::endl;\n\n\t\t\t// 1. For each peak, check if there is any new envelop occurred at this peak.\n\t\t\tstd::vector<EnvEntry> new_env_entries = env_ref.getOccurredEnvelopEntries(pk, NEW);\n\t\t\tif(new_env_entries.size() == 0) \n\t\t\t\tcontinue;\n\n\t\t\t// Update the fitting score for all the new envelop set.\n\t\t\tBOOST_FOREACH(EnvEntry& env_entry, new_env_entries) {\n\t\t\t\tthis->calculateFittingScore(env_entry.env);\n\t\t\t}\n\n\t\t\t// Check if this is a peak from previously identified envelop.\n\t\t\tstd::vector<EnvEntry> old_env_entries = env_ref.getOccurredEnvelopEntries(pk, OLD);\n\t\t\t\t\n\t\t\t// 1. Sort the envelop vector by their fitting scores.\n\t\t\t// Since the value of the fitting score will be frequently updated,\t\t\t\t// it might not be a good idea to keep it in a multi-index container\n\t\t\tstd::sort(new_env_entries.begin(), new_env_entries.end(), EnvEntry::scoreLarger);\n\n\t\t\t// Check if the new envelops are actually just subset of the old \n\t\t\t// envelops.\n\t\t\tif(old_env_entries.size() != 0) {\n\t\t\t\t// a. Declared as abnormal by old_env_entry.\n\t\t\t\t// b. Identified new peak.\n\t\t\t\t// c. Meet the threshold of the envelop.\n\t\t\t\tBOOST_FOREACH(EnvEntry& new_entry, new_env_entries)\n\t\t\t\t{\n\t\t\t\t\t\tbool fake_envelop = false;\n\t\t\t\t\t\tBOOST_FOREACH(EnvEntry old_entry, old_env_entries)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbool false_positive = this->isRedundantEnvelop(new_entry.env, old_entry.env, old_entry.getShift());\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t// If this peak is considered by any of the old envelops as\t\t\t\t\t\t\t\t// a true one, move to the next step. \n\t\t\t\t\t\t\tif(false_positive) {\n\t\t\t\t\t\t\t\tfake_envelop = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(fake_envelop) new_entry.info->entry_status = FALSE;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Rule of thumb */\n\t\t\t// 1. If there is only one new envelop, just accept the new envelop.\n\t\t\tif(new_env_entries.size()==1) {\n\t\t\t\t// No longer new envelop.\n\t\t\t\tif(new_env_entries[0].info->entry_status != FALSE) {\n\t\t\t\t\t// Identify if this is a noise envelop.\n\t\t\t\t\tif(!isNoiseEnvelop(new_env_entries[0].env))\n\t\t\t\t\t\tthis->acceptEnvelop(new_env_entries[0].env);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// 2. If there is more than one new envelop, which means multiple charge states, select the one with higher fitting score as the basis, sequentially merge the other into it, and see if the overall fitting score will be improved.\n\n\t\t\t// Upgrade the score of the system.\n\t\t\t// Calculate the previous system score.\n\t\t\tdouble system_score = 0.0;\n\t\t\t\n\t\t\t// 2. Sequentially merge one into the basis and decide if the performance is improved.\n\t\t\tstd::vector<EnvEntry> added_entries;\n\t\t\tBOOST_FOREACH(EnvEntry& new_entry, new_env_entries)\n\t\t\t{\n\t\t\t\tif(new_entry.info->entry_status == FALSE)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// Assign the fitting score to the system score.\n\t\t\t\tif(system_score == 0.0) {\n\t\t\t\t\tsystem_score = new_entry.env->fitting_score;\n\t\t\t\t\tthis->acceptEnvelop(new_entry.env);\n\n\t\t\t\t\tadded_entries.push_back(new_entry);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// 2.a Find the corresponding fitting score. Only considering the situation where there are multiple charge states for the same mono-isotopic peak. \n\t\t\t\tdouble new_score = updateEnvelopTree(old_env_entries, added_entries, new_entry, pk);\t\n\n\t\t\t\t// Decide if the envelop is proper to be added into the \n\t\t\t\t// envelop set.\n\t\t\t\tif(new_score <= system_score) {\n\t\t\t\t\tnew_entry.info->entry_status = FALSE;\n\t\t\t\t}else {\n\t\t\t\t\t/* Accept the candidate envelop.*/\n\t\t\t\t\t// No longer new envelop.\n\t\t\t\t\tthis->acceptEnvelop(new_entry.env);\n\t\t\t\t\tadded_entries.push_back(new_entry);\n\t\t\t\t\tsystem_score = new_score;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\tbool SimpleFinder::extendEnvelop( RichList& pk_list, RichPeakPtr base_pk, int charge, bool raw_spec)\n\t{\n\t\t// a. Using A+1 and A+2 peak to identify the most likely composition.\n\t\t// b. Try to extend the peak using the estimated composition.\n\t\t// c. Notice that sometimes, the A+2 peak might have missing information due to the defective peak picking algorithm.\n\t\t// d. This algorithm requires that A peak has to present.\n\t\t\n\t\t/* A + 1 peak */\n\t\t// Assume it follows the no sulfate model, get the boundary.\n\t\t// Guess the number of sulfate. Notice that there might be overlapping.\n\t\t// Calculate the no sulfate model. Notice that the information has been corrected by charge.\n\n\t\tAggregatedIsotopicVariants higher_theo = this->estimateDistribution(base_pk->mz, charge);\n\t\t//AggregatedIsotopicVariants lower_theo = this->estimateDistribution(base_pk->mz, charge, ave2);\n\n\t\t// Get the isotope information.\n\t\tconst Isotope s32 = pt.getIsotopeByNominalMass(\"S\", 32);\n\t\tconst Isotope s34 = pt.getIsotopeByNominalMass(\"S\", 34);\n\t\tconst Isotope c12 = pt.getIsotopeByNominalMass(\"C\", 12);\n\t\tconst Isotope c13 = pt.getIsotopeByNominalMass(\"C\", 13);\n\t\tconst Isotope h = pt.getIsotopeByNominalMass(\"H\",1);\n\t\tdouble electron_mass = param.getParameter<double>(\"electron_mass\").first;\n\t\tdouble low_sn_threshold = param.getParameter<double>(\"lower_bound_sn\").first;\n\n\t\t// The difference between mass of H and peak(A -> A+1). This variable is for re-use convinience.\n\t\tdouble mz_diff = (h.mass + electron_mass)/(double)charge - higher_theo.getMassDifferenceByShift<peak_intensity>(0, 1);\n\n\t\t// Temporary variable for storing the peak information.\n\t\t// 1. Shift;\n\t\t// 2. Peak;\n\t\t// 3. Status.\n\t\tstd::multimap<int, std::pair<RichPeakPtr, std::string> > pk_map;\n\t\tpk_map.insert(std::make_pair(0, std::make_pair(base_pk, \"Normal\")));\n\n\t\tint shift = 1;\n\n\t\twhile(1) {\n\t\t\t// Theoretically, the (A+n)' should always be present.\n\t\t\tdouble mz0 = base_pk->mz + higher_theo.getMassDifferenceByShift<peak_intensity>(0,shift);\n\n\t\t\tstd::string status = \"Normal\";\n\t\t\tif(shift == 1) {\t\t\t\n\t\t\t\tstd::set<RichPeakPtr> pks_set = this->getClosestRichPeaks(pk_list, mz0, raw_spec, low_sn_threshold);\n\t\t\t\t\n\t\t\t\tif(pks_set.size() == 0) { // C+H peak for different shift.\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\tdouble mz1 = mz0 + mz_diff;\n\t\t\t\t\t\n\t\t\t\t\tpks_set = this->getClosestRichPeaks(pk_list, mz1, raw_spec, low_sn_threshold);\n\t\t\t\t\tstatus = \"C+H\";\n\n\t\t\t\t\tif(pks_set.size() == 0 && shift > 1) { // C+2H\n\t\t\t\t\t\tdouble mz2 = mz0 + 2.0 * mz_diff;\n\t\t\t\t\t\tpks_set = this->getClosestRichPeaks(pk_list, mz2, raw_spec, low_sn_threshold);\n\t\t\t\t\t\tstatus = \"C+2H\";\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(pks_set.size() == 0)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if(pks_set.size() == 0 && shift == 1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tBOOST_FOREACH(RichPeakPtr pk, pks_set) {\n\t\t\t\t\tpk_map.insert(std::make_pair(shift, std::make_pair(pk, status)));\n\t\t\t\t}\n\n\t\t\t} else if(shift == 2) {\n\t\t\t\t// If 34S peak is present.\n\t\t\t\tdouble mz1 = base_pk->mz + (s34.mass - s32.mass)/(double)charge;\n\t\t\t\tstd::set<RichPeakPtr> pks_set1 = this->getClosestRichPeaks(pk_list, mz1, raw_spec, low_sn_threshold);\n\n\t\t\t\tBOOST_FOREACH(RichPeakPtr pk, pks_set1) {\n\t\t\t\t\tpk_map.insert(std::make_pair(shift, std::make_pair(pk, \"Sulfur\")));\n\t\t\t\t}\n\n\t\t\t\t// (A+n)' peak.\n\t\t\t\tstd::set<RichPeakPtr> pks_set2 = this->getClosestRichPeaks(pk_list, mz0, raw_spec, low_sn_threshold);\n\n\t\t\t\tBOOST_FOREACH(RichPeakPtr pk, pks_set2) {\n\t\t\t\t\tpk_map.insert(std::make_pair(shift, std::make_pair(pk, \"Normal\")));\n\t\t\t\t}\t\t\n\n\t\t\t\tif(pks_set1.size() == 0 && pks_set2.size() == 0) {\n\t\t\t\t\t// C+H peak.\n\t\t\t\t\tdouble mz2 = mz0 + mz_diff;\n\n\t\t\t\t\tstd::set<RichPeakPtr> pks_set3 = this->getClosestRichPeaks(pk_list, mz2, raw_spec, low_sn_threshold);\n\t\t\t\t\tBOOST_FOREACH(RichPeakPtr pk, pks_set3) {\n\t\t\t\t\t\tpk_map.insert(std::make_pair(shift, std::make_pair(pk, \"C+H\")));\n\t\t\t\t\t}\n\n\t\t\t\t\tif(pks_set3.size() == 0) {\n\t\t\t\t\t\t// C + 2H\n\t\t\t\t\t\tdouble mz3 = mz0 + 2.0 * mz_diff;\n\t\t\t\t\t\tstd::set<RichPeakPtr> pks_set4 = this->getClosestRichPeaks(pk_list, mz3, raw_spec, low_sn_threshold);\n\t\t\t\t\t\tBOOST_FOREACH(RichPeakPtr pk, pks_set4) {\n\t\t\t\t\t\t\tpk_map.insert(std::make_pair(shift, std::make_pair(pk, \"C+2H\")));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(pks_set4.size() == 0) \n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\t\t\n\n\t\t\t} else { // Shift >= 2.\n\t\t\t\t// Left boundary.\n\t\t\t\tint sulfur_multiplier = shift / 2;\n\t\t\t\tsize_t count = 0;\n\t\t\t\tfor(int i = sulfur_multiplier; i>=0; i--) {\n\t\t\t\t\tint carbon_multiplier = shift - i * 2;\n\t\t\t\t\tdouble mzx = base_pk->mz + i * (s34.mass - s32.mass)/(double)charge + carbon_multiplier * (c13.mass - c12.mass)/(double)charge;\n\t\t\t\t\tstd::set<RichPeakPtr> pks_set = this->getClosestRichPeaks(pk_list, mzx, raw_spec, low_sn_threshold);\n\t\t\t\t\tcount += pks_set.size();\n\t\t\t\t\tBOOST_FOREACH(RichPeakPtr pk, pks_set) {\n\t\t\t\t\t\tpk_map.insert(std::make_pair(shift, std::make_pair(pk, \"C+S\")));\n\t\t\t\t\t}\n          \n          // Also consider the H shift.\n          double mz1 = mzx + mz_diff;\n          pks_set = this->getClosestRichPeaks(pk_list, mz1, raw_spec, low_sn_threshold);\n          if(pks_set.size() != 0) {\n            status = \"C+H\";\n            BOOST_FOREACH(RichPeakPtr pk, pks_set) {\n              pk_map.insert(std::make_pair(shift, std::make_pair(pk, status)));\n            }\n            //pk_map.insert(std::make_pair(shift, std::make_pair(pk, \"C+S\")));\n          } \n\t\t\t\t}\n\t\t\t\t// No peak has been found in this range.\n\t\t\t\tif(count == 0) {\n          break;\n        }\n\t\t\t\t\t\n\t\t\t}\n\n\t\t\tshift++;\n\t\t}\n\n\t\t// No additional peak has been found.\n\t\tif(pk_map.size() == 1)\n\t\t\treturn false;\n\t\t\n\t\tEnvelopPtr env_ptr = createEnvelop(charge);\n\n\t\tdouble param_confidence = 0.0;\n\n\t\tstd::multimap<int, std::pair<RichPeakPtr, std::string> >::iterator map_iter = pk_map.begin();\n\t\tfor(; map_iter != pk_map.end(); map_iter++)\n\t\t{\n\t\t\tint pk_pos = map_iter->first; \n\t\t\tRichPeakPtr pk_ptr = map_iter->second.first;\n\t\t\tthis->cleanNeighborNoise(pk_list, pk_ptr);\n\t\t\tstd::string pk_status = map_iter->second.second;\n\n\t\t\tEntryStatus entry_status = (pk_pos == 0 ? NEW : OLD);\n\t\t\t\n\t\t\tInfoPeakPtr pk_infor = boost::make_shared<InfoPeak>(pk_ptr->intensity, pk_status, entry_status);\n\n\t\t\tenv_ref.addDictionaryReference(pk_ptr, env_ptr, pk_pos, pk_infor);\n\t\t}\n\n\t\tint max_shift = shift - 1; \n\t\tenv_ptr->max_shift = max_shift;\n\n\t\tstd::cout << \"Found candidate envelop -- mono peak: \" << base_pk->mz << \" charge: \" << env_ptr->charge_state << std::endl;\n\t\tenv_pool.insert(env_ptr);\n\n\t\t//calculateFittingScore(env_ptr);\n\n\t\treturn true;\n\n\t}\n\n\tAggregatedIsotopicVariants SimpleFinder::estimateDistribution( double mz, int charge, bool sulfur)\n\t{\n\t\tdouble mass = calculateMass(mz, charge);\n\t\tdouble coef = mass / 100.0;\n\t\tComposition compo;\n\n\t\tif(sulfur) {\n\t\t\t// Correct sulfur number. \n\t\t\tAveragineFormulae::iterator sulfur_iter = max_sulfur_ave.find(\"S\");\n\t\t\tint num = (int)ceil(sulfur_iter->second * coef);\n\n\t\t\tdouble new_mass = mass - (double)num * Composition(\"SO3\").getMass();\n\t\t\t\n\t\t\tdouble new_coef = new_mass / 100.0;\n\t\t\t\n\t\t\tAveragineFormulae::iterator iter = max_sulfur_ave.begin();\n\t\t\tfor(; iter != max_sulfur_ave.end(); iter++) {\n\t\t\t\tif(iter->first != \"S\") {\n\t\t\t\t\tcompo.addElement(iter->first, (int)floor(iter->second * new_coef + 0.5));\n\t\t\t\t} else {\n\t\t\t\t\tcompo.addElement(iter->first, num);\n\t\t\t\t}\n\t\t\t}\n\t\t\tIsotopicDistribution iso(compo);\n\t\t\treturn iso.getAggregatedIsotopicVariants(charge);\n\t\t} else {\n\t\t\tAveragineFormulae::iterator iter = no_sulfur_ave.begin();\n\t\t\tfor(; iter != no_sulfur_ave.end(); iter++)\n\t\t\t\tcompo.addElement(iter->first, (int)floor(iter->second * coef + 0.5));\n\n\t\t\tIsotopicDistribution iso(compo);\n\t\t\treturn iso.getAggregatedIsotopicVariants(charge);\n\t\t}\n\n\n\t}\n\n\tAggregatedIsotopicVariants SimpleFinder::estimateDistribution( double mz, int charge, int sulfur_num )\n\t{\n\t\tdouble mass = calculateMass(mz, charge);\n\t\tdouble new_mass = mass - (double)sulfur_num * Composition(\"SO3\").getMass();\n\n\t\tdouble new_coef = new_mass / 100.0;\n\n\t\tAveragineFormulae::iterator iter = no_sulfur_ave.begin();\n\t\tComposition compo;\n\t\tfor(; iter != no_sulfur_ave.end(); iter++) {\n\t\t\tif(iter->first == \"S\") {\n\t\t\t\tcompo.addElement(iter->first, sulfur_num);\n\t\t\t} else if(iter->first == \"O\") {\n\t\t\t\tcompo.addElement(iter->first, sulfur_num * 3);\n\t\t\t} else {\n\t\t\t\tcompo.addElement(iter->first, (int)floor(iter->second * new_coef + 0.5));\n\t\t\t}\n\t\t}\n\t\tIsotopicDistribution iso(compo);\n    //AggregatedIsotopicVariants agr_var = iso.getAggregatedIsotopicVariants(charge);\n\t\treturn iso.getAggregatedIsotopicVariants(charge);\n\t}\n\n\n\tstd::set<RichPeakPtr> SimpleFinder::getClosestRichPeaks(RichList& pk_list, double expected_mz, bool raw_spec, double sn_threshold, double error)\n\t{\n\t\tRichPeakListByMZ& pks_mz = pk_list.getPeakListByType<peak_mz>();\n\n\t\tRichPeakListByMZ::iterator mz_increase_iter, mz_decrease_iter;\n\t\tmz_increase_iter = pks_mz.lower_bound(expected_mz);\n\t\tmz_decrease_iter = mz_increase_iter;\n\n\t\tstd::set<RichPeakPtr> pk_set;\n\t\tstd::map<double, RichPeakPtr> pk_map;\n\n\t\t// Examine the peak towards two directions.\n\t\twhile(1) {\n\t\t\tif(mz_increase_iter == pks_mz.end())\n\t\t\t\tbreak;\n\n\t\t\tRichPeakPtr pk = *mz_increase_iter;\n\n\t\t\tbool meet_threshold = raw_spec ? true : (pk->signal_noise > sn_threshold); \n\n\t\t\tdouble win_error = this->getWindowError(pk, error);\n\t\t\t\n\t\t\tif(abs(pk->mz - expected_mz) < win_error) {\n\t\t\t\tif(meet_threshold)\n\t\t\t\t\tpk_map.insert(std::make_pair(pk->intensity, pk));\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tmz_increase_iter++;\n\t\t\tif(mz_increase_iter == pks_mz.end())\n\t\t\t\tbreak;\n\t\t}\n\n\t\tmz_decrease_iter--;\n\t\twhile(1) {\n\t\t\tRichPeakPtr pk = *mz_decrease_iter;\n\n\t\t\tdouble win_error = this->getWindowError(pk, error);\n\t\t\t\n\t\t\tbool meet_threshold = raw_spec ? true : (pk->signal_noise > sn_threshold);\n\n\t\t\tif(abs(pk->mz - expected_mz) < win_error)\t{\t\t\n\t\t\t\tif(meet_threshold)\n\t\t\t\t\tpk_map.insert(std::make_pair(pk->intensity, pk));\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif(mz_decrease_iter == pks_mz.begin())\n\t\t\t\tbreak;\n\t\t\telse\n\t\t\t\tmz_decrease_iter--;\n\t\t}\n\n\t\t//pk_set.insert(selected_pk);\n\t\tif(pk_map.size()>0) {\n\t\t\tRichPeakPtr selected_pk = pk_map.rbegin()->second;\n\t\t\tpk_set.insert(selected_pk);\n\t\t}\n\t\t\n\t\treturn pk_set;\n\t}\n\n\n\tvoid SimpleFinder::updateEnvelopParameter( EnvelopPtr env )\n\n\t{\n\t\t// 0. Check env id.\n\t\tunsigned int env_id = env->id;\n\t\tstd::cout << \"Check env #\" << env_id << std::endl;\n\n\t\t// 1. Get all the peaks.\n\t\tEnvEntry base_entry = env_ref.getEntryByShift(env, 0);\n\t\t\n\t\tstd::vector<EnvEntry> entry_vec = env_ref.getEntryByEnvelop(env);\n\n\t\tAggregatedIsotopicVariants higher_theo = this->estimateDistribution(base_entry.pk->mz, env->charge_state);\n\t\tAggregatedIsotopicVariants lower_theo = this->estimateDistribution(base_entry.pk->mz, env->charge_state, true);\n\n\t\tint max_sulfur = this->guessMaxSulfurNumber(base_entry.pk->mz, env->charge_state);\n\t\tint max_num = param.getParameter<int>(\"max_sulfur_num\").first;\n\n\t\tconst Isotope s34 = pt.getIsotopeByNominalMass(\"S\", 34);\n\t \n\t\tstd::pair<int, int> sulfur_range = std::make_pair(0,max_sulfur);\n\n\t\t// Gradually estimate the sulfur number. The default value is 0.\n\t\tBOOST_FOREACH(EnvEntry entry, entry_vec)\n\t\t{\n\t\t\t// For given shift, estimate the range of the intensities.\n\t\t\tint pk_pos = entry.getShift();\n\t\t\t\n\t\t\tif(pk_pos == 0) continue;\n\n\t\t\t// Expected abundance.\n\t\t\tdouble non_sulfur_model_abundance = base_entry.pk->intensity * higher_theo.getPeakByShift<peak_intensity>(pk_pos)->intensity;\n\t\t\tdouble sulfur_model_abundance = base_entry.pk->intensity * lower_theo.getPeakByShift<peak_intensity>(pk_pos)->intensity;\n\n\t\t\tdouble max_abundance = non_sulfur_model_abundance;\n\t\t\tdouble min_abundance = sulfur_model_abundance;\n\t\t\tif(min_abundance > max_abundance)\n\t\t\t\tswap(max_abundance, min_abundance);\n\n\t\t\t// Narrow down the range of sulfur_range.\n\t\t\t// For tandem ms analysis, only use A+1 and A+2 peak.\n\t\t\t// The information from A+1 peak might help increase the lower limit \n\t\t\tif(pk_pos == 1) { // odd peak, increase the lower limit of sulfur number.\n\t\t\t\t\n\t\t\t\tif(entry.info->status != \"Normal\") continue;\n\n\t\t\t\tif((entry.info->adjusted_abundance-max_abundance)/max_abundance >0.2 ) {\n\t\t\t\t\t// Significantly higher than upper boundary.\n\t\t\t\t\t// Nothing to do with the range.\n\t\t\t\t} else if((entry.info->adjusted_abundance-min_abundance)/min_abundance < -0.2) {\n\t\t\t\t\t// Significantly lower than expected.\n\t\t\t\t\t// env->suspicious = true;\n\t\t\t\t} else {\n\t\t\t\t\t// Normal situation. Estimate sulfur_num from the abundance.\n\t\t\t\t\tdouble lambda = (entry.info->adjusted_abundance-min_abundance)/(max_abundance - min_abundance);\n\n\t\t\t\t\t// Convert lambda to sulfur_num.\n\t\t\t\t\tif(sulfur_model_abundance == min_abundance)\n\t\t\t\t\t\tlambda = 1.0 - lambda;\n\n\t\t\t\t\tint sulfur_num = (int)floor(lambda * max_sulfur + 0.5);\n\n\t\t\t\t\t//entry.env->sulfur_num = sulfur_num > max_num ? max_num : sulfur_num;\n\t\t\t\t\tif(sulfur_num < sulfur_range.second)\n\t\t\t\t\t\tsulfur_range.second = sulfur_num;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t} else if(pk_pos == 2) { // even peak, decrease the upper limit of sulfur number. Notice that one of the peak might be missing.\n\t\t\t\tif(entry.info->status == \"Sulfur\") {\n\t\t\t\t\t// TBD: decide if the sulfur peak and non-sulfur peak will separate.\n\t\t\t\t\t// If present, estimate sulfur using this information.\n\t\t\t\t\tint sulfur_num = (int)floor(entry.info->adjusted_abundance/base_entry.info->adjusted_abundance / pow(s34.abundance, pk_pos/2) + 0.5);\n\t\t\t\t\n\t\t\t\t\tif(sulfur_num > sulfur_range.first && sulfur_num < max_num)\n\t\t\t\t\t\tsulfur_range.first = sulfur_num;\n\t\t\t\t\t//entry.env->sulfur_num = sulfur_num > max_num ? max_num : sulfur_num;\n\t\t\t\t\t// The information from sulfur peak have enough confidence.\n\t\t\t\t\tbreak;\n\n\t\t\t\t} else if(entry.info->status == \"Normal\") {\n\t\t\t\t\t// Assume the peak and 34S peak are able to be resolved.\n\t\t\t\t\t// Define the intensity range for current peak.\n\n\n\t\t\t\t\t// Expected abundance of the non-sulfur-peak.\n\t\t\t\t\tdouble non_sulfur_peak_abundance = sulfur_model_abundance - base_entry.info->adjusted_abundance * pow(s34.abundance, pk_pos);\n\t\t\t\t\t// Do the same thing for A+1 peak.\n\t\t\t\t\tmax_abundance = non_sulfur_model_abundance;\n\t\t\t\t\tmin_abundance = non_sulfur_peak_abundance;\n\n\t\t\t\t\tif(max_abundance < min_abundance) \n\t\t\t\t\t\tswap(max_abundance, min_abundance);\n\t\t\t\t\t\n\t\t\t\t\tif((entry.info->adjusted_abundance - max_abundance)/max_abundance > 0.2) {\n\t\t\t\t\t\t// Significantly higher than expected.\n\t\t\t\t\t\t// Do nothing.\n\t\t\t\t\t} else if((entry.info->adjusted_abundance - min_abundance)/min_abundance < -0.2) {\n\t\t\t\t\t\t// Significantly lower than expected.\n\t\t\t\t\t\t// Do nothing.\n\t\t\t\t\t} else {\n\n\t\t\t\t\t\tdouble lambda = (entry.info->adjusted_abundance-min_abundance)/(max_abundance - min_abundance);\n\n\t\t\t\t\t\t// Sometimes, the distance between max_abundance and min_abundance is too small, which will cause a lot of troubles.\n\t\t\t\t\t\tif(lambda < 0.0) continue;\n\n\t\t\t\t\t\tif(non_sulfur_peak_abundance == min_abundance)\n\t\t\t\t\t\t\tlambda = 1.0 - lambda;\n\n\t\t\t\t\t\t// Convert lambda to sulfur_num.\n\t\t\t\t\t\tint sulfur_num = (int)floor(lambda * max_sulfur + 0.5);\n\t\t\t\t\t\tif(sulfur_num < sulfur_range.second)\n\t\t\t\t\t\t\tsulfur_range.second = sulfur_num;\n\t\t\t\t\t\t//entry.env->sulfur_num = sulfur_num > max_num ? max_num : sulfur_num;\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\t// C+H peak. Nothing to do with the sulfur number.\n\t\t\t\t}\n\t\t\t} \n\t\t}\n\t\t\n\t\t// Get the sulfur number estimation by averaing all possible \n\t\tenv->sulfur_num = (sulfur_range.first + sulfur_range.second)/2;\n\n\t\t// Unlikely situation.\n\t\tif(sulfur_range.first > sulfur_range.second) \n\t\t\tenv->env_status = FP;\n\n\t\t// Update the theoretical distribution for current envelop.\n\t\tenv->theo_dist = this->estimateDistribution(base_entry.pk->mz, env->charge_state, env->sulfur_num);\n\n\t\tstd::map<int, PeakPtr> pk_map = env->getTheoreticalPeaks();\n\n\t\tfor(std::map<int, PeakPtr>::iterator iter = pk_map.begin(); \n\t\t\titer != pk_map.end(); iter++)\n\t\t{\n\t\t\t// Theo peak information.\n\t\t\tint shift = iter->first; PeakPtr theo_pk = iter->second;\n\t\t\tdouble theo_abundance = base_entry.info->adjusted_abundance * theo_pk->intensity;\n\t\t\t\n\t\t\t// No need to estimate base peak.\n\t\t\tif(shift == 0) continue;\n\n\t\t\t// Be careful of the situation that the shift for the envelop cannot be observed.\n\t\t\tstd::vector<EnvEntry> exp_pks = env_ref.getPeaksByShift(env, shift);\n\n\t\t\t// Depending on the status of the peak, the theoretical information will be recalculated. It might be possible that some of the peaks are missing, it is better to calculate the mean of the shift for each position.\n\t\t\t// If the sulfur number is 0, we assume there is no peak split.\n\t\t\tif(env->sulfur_num == 0) {\n\t\t\t\tBOOST_FOREACH(EnvEntry& pk_entry, exp_pks) {\n\t\t\t\t\tif(pk_entry.info->status == \"Normal\") {\n\t\t\t\t\t\tpk_entry.info->relative_shift = (pk_entry.info->adjusted_abundance - theo_abundance) / theo_abundance;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif(shift == 1 || shift == 2) {\n\t\t\t\t\tBOOST_FOREACH(EnvEntry& pk_entry, exp_pks) {\n\t\t\t\t\t\tif(shift == 1) {\n\t\t\t\t\t\t\tif(pk_entry.info->status == \"Normal\") {\n\t\t\t\t\t\t\t\tpk_entry.info->relative_shift = (pk_entry.info->adjusted_abundance - theo_abundance)/ theo_abundance;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if(shift == 2){\n\t\t\t\t\t\t\t// Here we assume the peak will split.\n\t\t\t\t\t\t\tif(pk_entry.info->status == \"Sulfur\") {\n\t\t\t\t\t\t\t\t// Calculate the theoretical abundance and update the relative shift.\n\t\t\t\t\t\t\t\ttheo_abundance = base_entry.info->adjusted_abundance * pow(s34.abundance, env->sulfur_num);\n\t\t\t\t\t\t\t\tpk_entry.info->relative_shift = (pk_entry.info->adjusted_abundance - theo_abundance) / theo_abundance;\n\t\t\t\t\t\t\t} else if(pk_entry.info->status == \"Normal\"){\n\t\t\t\t\t\t\t\t// Notice that theo_abundance should be larger than 0.\n\t\t\t\t\t\t\t\ttheo_abundance = base_entry.info->adjusted_abundance * (theo_pk->intensity - pow(s34.abundance, env->sulfur_num));\n\t\t\t\t\t\t\t\tpk_entry.info->relative_shift = (pk_entry.info->adjusted_abundance - theo_abundance) / theo_abundance;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// C+H peak. Nothing to do with the relative shift.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} \n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// A + n peak\n\t\t\t\t\tdouble total_shift_abundance = 0.0;\n\t\t\t\t\tBOOST_FOREACH(EnvEntry& pk_entry, exp_pks) {\n\t\t\t\t\t\tif(pk_entry.info->status == \"Normal\" \n\t\t\t\t\t\t\t|| pk_entry.info->status == \"Sulfur\") {\n\t\t\t\t\t\t\t\ttotal_shift_abundance += pk_entry.info->adjusted_abundance; \n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tBOOST_FOREACH(EnvEntry& pk_entry, exp_pks) {\n\t\t\t\t\t\tpk_entry.info->relative_shift = (pk_entry.info->adjusted_abundance - theo_abundance)/ theo_abundance;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\n\t}\n\n\tbool SimpleFinder::isRedundantEnvelop( EnvelopPtr new_env, EnvelopPtr old_env, int old_shift)\n\t{\n\t\tbool state = false;\n\n    std::set<RichPeakPtr> old_pks = env_ref.getPeaksByEnvelop(old_env);\n    std::set<RichPeakPtr> new_pks = env_ref.getPeaksByEnvelop(new_env);\n\n    if(std::includes(old_pks.begin(), old_pks.end(), new_pks.begin(), new_pks.end())) {\n      // Calculate the sub fitting score of the subset from old_pks.\n      if(new_env->fitting_score < old_env->fitting_score)\n        state = true;\n\n    } else {\n      if(new_env->fitting_score < old_env->fitting_score && (old_env->charge_state % new_env->charge_state == 0))\n        state = true;\n\n      EnvEntry base_entry = env_ref.getEntryByShift(old_env, 0);\n      //  //EnvEntry new_base = env_ref.getEntryByShift(new_env, 0);\n      EnvEntry current_entry = env_ref.getEntryByShift(old_env, old_shift);\n      //  // Check if it is different from theoretical abundance.\n      AggregatedIsotopicVariants higher_theo = this->estimateDistribution(base_entry.pk->mz, old_env->charge_state);\n      AggregatedIsotopicVariants lower_theo = this->estimateDistribution(base_entry.pk->mz, old_env->charge_state, true);\n\n      double non_sulfur_abundance = higher_theo.getPeakByShift<peak_intensity>(old_shift)->intensity * base_entry.info->adjusted_abundance;\n      double sulfur_abundance = lower_theo.getPeakByShift<peak_intensity>(old_shift)->intensity * base_entry.info->adjusted_abundance;\n\n      double expected_abundance(0.0);\n      if(current_entry.info->status == \"Normal\") {\n        expected_abundance = std::max(non_sulfur_abundance,sulfur_abundance);\n      } else {\n        if(current_entry.info->status == \"Sulfur\")\n          state = true;\n\n        return state;\n      }\n\n      double upper_shift = (current_entry.pk->intensity - expected_abundance)/(expected_abundance);\n\n      double max_intensity_shift = param.getParameter<double>(\"max_intensity_shift\").first;\n      \n      if(upper_shift < max_intensity_shift)\n      \tstate = true;\n    }\n\n\t\treturn state;\n\t}\n\n\tvoid SimpleFinder::printEnvelop( EnvelopPtr env )\n\t{\n\t\tstd::cout << \"Envelop ID: \" << env->id << std::endl;\n\t\tstd::cout << \"Charge: \" << env->charge_state << std::endl;\n    std::cout << \"Fitting score: \" << env->fitting_score << std::endl;\n\t\tstd::cout << std::endl;\n\t\t// Peak information.\n\t\tstd::cout << \"Covered peaks:\" << std::endl;\n\t\tstd::cout << \"Shift\\tMZ\\tEXP_ABD\\tSTATUS\\tSTATUS2\" << std::endl;\n    \n\t\t// Get all peaks.\n\t\tstd::vector<EnvEntry> pk_entries = env_ref.getEntryByEnvelop(env);\n\t\tstd::cout.precision(5);\n\t\tBOOST_FOREACH(EnvEntry& pk_entry, pk_entries)\n\t\t{\n\t\t\tstd::cout << pk_entry.getShift() << \"\\t\" ;\n\t\t\tstd::cout << std::fixed << pk_entry.pk->mz << \"\\t\";\n\t\t\tstd::cout\t<< pk_entry.pk->intensity << \"\\t\" << pk_entry.info->status << std::endl;\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\tstd::multimap<RichPeakPtr, EnvelopPtr> SimpleFinder::getEnvelops(EntryStatus status)\n\t{\n\t\tstd::vector<EnvEntry> entry_vec = env_ref.getBaseEntriesByStatus();\n\t\t\n\t\t//EnvDictByEnvID& env_by_eid = env_\n\t\tstd::multimap<RichPeakPtr, EnvelopPtr> env_map;\n\t\tBOOST_FOREACH(EnvEntry& env_entry, entry_vec)\n\t\t{\n\t\t\t// Get the base peak for the envelop.\n\t\t\tRichPeakPtr base_pk = env_entry.pk;\n\t\t\tenv_map.insert(std::make_pair(base_pk, env_entry.env));\n\t\t}\n\t\treturn env_map;\n\t}\n\n\tdouble SimpleFinder::getWindowError( RichPeakPtr pk, double error )\n\t{\n\t\t// If error is specified.\n\t\tif(error != -1.0) return error * pk->mz;\n\n\t\tdouble internal_accuracy = param.getParameter<double>(\"internal_accuracy\").first;\n\t\t\n\t\t//double resolving_power = pk->resolution;\n\t\t//double coef = pk->mz / resolving_power;\n\t\tdouble coef = (pk->signal_noise > 15 && pk->mz > 400.0) ? 1.2 : 1.5;\n    //double coef = 1.5;\n\t\treturn 2e-6 * internal_accuracy * pk->mz * coef;\n\t}\n\n\tbool SimpleFinder::isNoiseEnvelop( EnvelopPtr env )\n\t{\t\n\t\tunsigned int env_id = env->id;\n\t\t// Identification of noise envelop.\n\t\t// Situation 1. Weired cluster shape. envelop size has to be larger than 3. This is not noise envelop.\n\t\tstd::set<int> shift_set = env_ref.getShiftSet(env);\n\t\tRichPeakPtr base_pk = env_ref.getBasePeakForEnvelop(env);\n\n\t\tif(shift_set.size() > 2) {\n\t\t\tBOOST_FOREACH(int shift, shift_set)\n\t\t\t{\n\t\t\t\tstd::vector<EnvEntry> pk_entry_vec = env_ref.getPeaksByShift(env, shift);\n\t\t\t\tBOOST_FOREACH(EnvEntry& pk_entry, pk_entry_vec)\n\t\t\t\t{\n\t\t\t\t\tif(pk_entry.info->relative_shift < -0.3) {\n\t\t\t\t\t\tenv->env_status = MISC;\n\t\t\t\t\t\t// Misc envelop is not noise envelop.\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Situation 2. Matching to noise peak.\n\t\t// 2.a size == 2\n\t\tif(shift_set.size() == 2) {\n\t\t\t// Get A+1 peak.\n\t\t\tstd::vector<EnvEntry> pk_entry_vec = env_ref.getPeaksByShift(env, 1);\n\t\t\tif(pk_entry_vec.size() == 1 && pk_entry_vec[0].info->status == \"C+H\") {\n\t\t\t\t// Get theoretical abundance.\n\t\t\t\tdouble theo_abundance = env_ref.getTheoreticalPeak(env, 1)->intensity;\n\t\t\t\tif(theo_abundance - pk_entry_vec[0].info->adjusted_abundance > 0)\n\t\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tRichPeakPtr base_pk = env_ref.getBasePeakForEnvelop(env);\n\t\t\tstd::vector<EnvEntry> old_env_entries = env_ref.getOccurredEnvelopEntries(base_pk, OLD);\n\t\t\t// 2.b A + 1 peak is significantly lower than expected.\n\t\t\tif(pk_entry_vec[0].info->relative_shift < -0.2 || old_env_entries.size() > 0)\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\n\t}\n\n\tvoid SimpleFinder::cleanNeighborNoise( RichList& pk_list, RichPeakPtr pk/*, std::set<RichPeakPtr>& blacklist*/ )\n\t{\n\t\tRichPeakListByMZ& pks_mz = pk_list.getPeakListByType<peak_mz>();\n\n\t\tRichPeakListByMZ::iterator mz_increase_iter, mz_decrease_iter;\n\t\tmz_increase_iter = pks_mz.lower_bound(pk->mz);\n\t\tmz_decrease_iter = mz_increase_iter;\n\n\t\tmz_increase_iter++;\n\n\t\tdouble win_error = 0.012;\n\n\t\twhile(1) {\n\t\t\tif(mz_increase_iter == pks_mz.end())\n\t\t\t\tbreak;\n\n\t\t\tRichPeakPtr neighbor_pk = *mz_increase_iter;\n\n\t\t\tif(abs(neighbor_pk->mz - pk->mz) < win_error && (neighbor_pk->intensity / pk->intensity < 0.1)) {\n\t\t\t\t//blacklist.insert(neighbor_pk);\n\t\t\t\t//neighbor_pk->pk_status = false;\n\t\t\t\tthis->setNoisePeak(neighbor_pk);\n\t\t\t} else if(abs(neighbor_pk->mz - pk->mz) >= win_error)\n\t\t\t\tbreak;\n\n\t\t\tmz_increase_iter++;\n\t\t\tif(mz_increase_iter == pks_mz.end())\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// This is the begin of the peak list.\n\t\tif(mz_decrease_iter == pks_mz.begin())\n\t\t\treturn;\n\n\t\t\tmz_decrease_iter--;\n\t\twhile(1) {\n\t\t\tRichPeakPtr neighbor_pk = *mz_decrease_iter;\n\n\t\t\tif(abs(neighbor_pk->mz - pk->mz) < win_error && (neighbor_pk->intensity / pk->intensity < 0.1)) {\n\t\t\t\t\n\t\t\t\t//neighbor_pk->pk_status = false;\n\t\t\t\tthis->setNoisePeak(neighbor_pk);\n\t\t\t} else if(abs(neighbor_pk->mz - pk->mz) >= win_error)\n\t\t\t\tbreak;\n\n\t\t\tif(mz_decrease_iter == pks_mz.begin())\n\t\t\t\tbreak;\n\t\t\telse\n\t\t\t\tmz_decrease_iter--;\n\t\t}\n\t}\n\n\tdouble SimpleFinder::updateEnvelopTree( std::vector<EnvEntry>& old_entries, std::vector<EnvEntry>& added_entries, EnvEntry& test_entry, RichPeakPtr pk )\n\t{\n\t\tdouble rest_intensity = 0.0;\n\t\tBOOST_FOREACH(EnvEntry& entry, old_entries)\n\t\t\trest_intensity += entry.info->adjusted_abundance;\n\n\t\trest_intensity = test_entry.pk->intensity - rest_intensity;\n\n\t\t// Construct the vector using theoretical isotopic distributions. Scale the second one and get the best fit.\n\t\tdouble scaling_factor = 0.0; \n\t\tdouble scaling_range[2] = {0.0, 1.0};\n\n\t\tdouble total_score = this->calculateLinearAssociationScore(added_entries);\n\t\t\n\t\tstd::vector<EnvEntry> temp_entries = *(&added_entries);\n\t\ttemp_entries.push_back(test_entry);\n\n\t\twhile(1)\n\t\t{\n\t\t\t// Based on scaling factor, update the peak abundance.\n\t\t\tstd::vector<EnvEntry> pk_entry_vec = env_ref.getEntryByEnvelop(test_entry.env);\n\t\t\tBOOST_FOREACH(EnvEntry& pk_entry, pk_entry_vec)\n\t\t\t{\n\t\t\t\tpk_entry.info->adjusted_abundance *= scaling_factor;\n\t\t\t}\n\n\t\t\tBOOST_FOREACH(EnvEntry& env_entry, added_entries)\n\t\t\t{\n\t\t\t\tstd::vector<EnvEntry> pk_entry_vec2 = env_ref.getEntryByEnvelop(env_entry.env);\n\t\t\t\tBOOST_FOREACH(EnvEntry& pk_entry, pk_entry_vec2)\n\t\t\t\t{\n\t\t\t\t\tpk_entry.info->adjusted_abundance *= (1-scaling_factor);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update scaling factor. It depends on the peaks associated with the second test_entry.\n\t\t\tdouble new_score = this->calculateLinearAssociationScore(temp_entries);\n\n\t\t\tdouble ratio0 = this->calculateScalingRatio(temp_entries);\n\t\t\tdouble ratio1 = this->calculateScalingRatio(test_entry);\n\t\t\t\n\t\t\tint scale_index = ratio0 > ratio1 ? 1 : 0;\n\n\t\t\t// Keep a copy of the current scaling factor.\n\t\t\tdouble old_scaling_factor = scaling_factor;\n\n\t\t\t// Update the scaling factor of the new envelop.\n\t\t\tscaling_factor = (scaling_range[scale_index] + scaling_factor)/2.0;\n\t\t\t\n\t\t\t// Update the boundary of the scale range.\n\t\t\tscaling_range[1-scale_index] = old_scaling_factor;\n\n\t\t\tif(abs(new_score - total_score) < 1e-6) \n\t\t\t\tbreak;\n\t\t\telse \n\t\t\t\ttotal_score = new_score;\n\t\t}\n\n\t\tdouble total_fitting_score = 0.0;\n\t\tBOOST_FOREACH(EnvEntry& env_entry, temp_entries) {\n\t\t\t// Reset the scaling factor to 1.\n\t\t\tenv_entry.env->scaling_factor = 1.0;\n\t\t\ttotal_fitting_score += this->calculateFittingScore(env_entry.env);\n\t\t}\n\t\treturn total_fitting_score;\n\t\t\n\t}\n\n\tdouble SimpleFinder::calculateFittingScore( EnvelopPtr env )\n\t{\t\n\t\t// Get base entry.\n\t\tdouble fitting_score = 0.0;\n\n\t\tstd::set<int> shift_set = env_ref.getShiftSet(env);\n\n\t\t// If sulfur peak is present, re-estimate the abundance.\n\n\t\tBOOST_FOREACH(int shift, shift_set)\n\t\t{\n\t\t\tdouble expected_abundance = env_ref.getTheoreticalPeak(env, shift)->intensity;\n\t\t\tdouble experimental_abundance = env_ref.getExperimentalAbundanceByShift(env, shift);\n\n\t\t\t// The fitting score comes from 3 parts: \n\t\t\t//1. the shift of intensity: abs(E-T)/T.\n\t\t\tdouble intensity_shift = (expected_abundance - experimental_abundance)/ expected_abundance;\n\t\t\tif(intensity_shift > 0.0 && intensity_shift <= 1.0)\n\t\t\t\tintensity_shift = 1.0 - intensity_shift;\n\t\t\telse if(intensity_shift <= 0.0 && intensity_shift >= -1.0)\n\t\t\t\tintensity_shift = sqrt(1.0 + intensity_shift);\n\t\t\telse if(intensity_shift > 1)\n\t\t\t\tintensity_shift = 1.0;\n\t\t\telse\n\t\t\t\tintensity_shift = 0.0;\n\n\t\t\t// 2. the shift of m/z. Since this is for high resolution data, the shift of m/z should be ignored.\n\n\t\t\t// 3. the square root of expected_abundance.\n\t\t\tdouble weight = sqrt(expected_abundance);\n\n\t\t\tfitting_score += weight * intensity_shift;\n\t\t}\n\n\t\tenv->fitting_score = fitting_score;\n\t\treturn fitting_score;\n\n\t}\n\n\tdouble SimpleFinder::calculateFittingScore(std::set<EnvelopPtr>& env_set)\n\t{\n\t\tdouble total_fitting_score = 0.0;\n\t\tBOOST_FOREACH(EnvelopPtr env, env_set)\n\t\t\ttotal_fitting_score += this->calculateFittingScore(env);\n\t\treturn total_fitting_score;\n\t}\n\n\tdouble SimpleFinder::calculateLinearAssociationScore( std::vector<EnvEntry>& entries )\n\t{\n\t\t// Calculate the value of cos theta.\n\t\tdouble inner_prod = 0.0; double norm_term[2] = {0.0,0.0};\n\t\tBOOST_FOREACH(EnvEntry& env_entry, entries)\n\t\t{\n\t\t\tstd::set<int> shift_set = env_ref.getShiftSet(env_entry.env);\n\n\t\t\tBOOST_FOREACH(int shift, shift_set)\n\t\t\t{\n\t\t\t\t// Calculate the accumulated abundance for multiple peaks mapped into the same shift position.\n\t\t\t\tstd::vector<EnvEntry> pk_entry_vec = env_ref.getPeaksByShift(env_entry.env, shift);\n\t\t\t\tdouble accumulated_abundance = 0.0;\n\t\t\t\tBOOST_FOREACH(EnvEntry& pk_entry, pk_entry_vec)\n\t\t\t\t\taccumulated_abundance += pk_entry.info->adjusted_abundance;\n\n\t\t\t\tdouble theo_abundance = env_entry.env->getTheoreticalPeak(shift)->intensity;\n\t\t\t\tinner_prod += theo_abundance * accumulated_abundance;\n\n\t\t\t\tnorm_term[0] += pow(theo_abundance, 2);\n\t\t\t\tnorm_term[1] += pow(accumulated_abundance, 2);\n\n\t\t\t}\n\t\t}\n\n\t\treturn inner_prod / (sqrt(norm_term[0]) * sqrt(norm_term[1]));\n\n\t}\n\n\tdouble SimpleFinder::calculateScalingRatio( std::vector<EnvEntry>& entries )\n\t{\n\t\tdouble adjusted_total = 0.0; double theo_total = 0.0;\n\n\t\tBOOST_FOREACH(EnvEntry& env_entry, entries)\n\t\t{\n\t\t\tstd::set<int> shift_set = env_ref.getShiftSet(env_entry.env);\n\t\t\tBOOST_FOREACH(int shift, shift_set) {\n\t\t\t\t// Get the acutal peaks for given position. There might be more than 1 which can be mapped into one peak.\n\t\t\t\tstd::vector<EnvEntry> pk_entry_vec = env_ref.getPeaksByShift(env_entry.env, shift);\n\n\t\t\t\tBOOST_FOREACH(EnvEntry& pk_entry, pk_entry_vec)\n\t\t\t\t\tadjusted_total += pk_entry.info->adjusted_abundance;\n\n\t\t\t\t// There will be only one theoretical peak for each shift position.\n\t\t\t\ttheo_total += env_entry.env->getTheoreticalPeak(shift)->intensity;\n\t\t\t}\n\t\t}\n\n\t\treturn adjusted_total / theo_total;\n\t}\n\n\tdouble SimpleFinder::calculateScalingRatio( EnvEntry& env_entry )\n\t{\n\t\t// Compare the total intensity of the suggested envleop over the theoretical intensity.\n\t\tdouble adjusted_total = 0.0; double theo_total = 0.0;\n\t\t\n\t\tstd::set<int> shift_set = env_ref.getShiftSet(env_entry.env);\n\t\tBOOST_FOREACH(int shift, shift_set) {\n\t\t\t// Get the acutal peaks for given position. There might be more \n\t\t\t// than 1 which can be mapped into one peak.\n\t\t\tstd::vector<EnvEntry> pk_entry_vec = env_ref.getPeaksByShift(env_entry.env, shift);\n\n\t\t\tBOOST_FOREACH(EnvEntry& pk_entry, pk_entry_vec)\n\t\t\t\tadjusted_total += pk_entry.info->adjusted_abundance;\n\t\t\t\n\t\t\t// There will be only one theoretical peak for each shift position.\n\t\t\ttheo_total += env_entry.env->getTheoreticalPeak(shift)->intensity;\n\t\t}\n\n\t\treturn adjusted_total/theo_total;\n\n\t}\n\n\tint SimpleFinder::guessMaxSulfurNumber( double mz, int charge_state )\n\t{\n\t\tdouble mass = calculateMass(mz, charge_state);\n\t\tdouble coef = mass / 100.0;\n\n\t\tAveragineFormulae::iterator sulfur_iter = max_sulfur_ave.find(\"S\");\n\t\treturn (int)ceil(sulfur_iter->second * coef);\n\t}\n\n\tvoid SimpleFinder::acceptEnvelop( EnvelopPtr env )\n\t{\n\t\t// 1. Set the status of the envelop as true positive.\n\t\tenv->env_status = TP;\n\t\t// 2. Set all the peaks associated to the envelop as OLD and the peak type as ENV.\n\t\tstd::vector<EnvEntry> pk_entry_vec = env_ref.getEntryByEnvelop(env);\n\t\t\n\t\t\n\t\tBOOST_FOREACH(EnvEntry& pk_entry, pk_entry_vec) {\n\t\t\tpk_entry.info->entry_status = OLD;\n\t\t\tsetPeakType(pk_entry.pk, \"ENV\");\n\t\t\t//pk_entry.pk->pk_type = \"ENV\";\n\t\t}\n\t\t\n\t}\n\n\tvoid SimpleFinder::setNoisePeak( RichPeakPtr pk )\n\t{\n\t\tpk->pk_status = false;\n\t\tsetPeakType(pk, \"NOISE\");\n\t}\n\n\tvoid SimpleFinder::optimizeSuspiciousPeaks()\n\t{\n\t\t// 1. For each suspicious peak, iterate over all charge state, try to decide if there is any peak that can follow into the range.\n\t\tRichPeakListBySignalOverNoise& pks_sn = spectrum.getPeakListByType<peak_signal_noise>();\n\n\t\t// The S/N threshold for monoisotopic peawk.\n\t\tdouble mono_sn_threshold = param.getParameter<double>(\"signal_noise\").first;\n\n\t\tRichPeakListBySignalOverNoise::iterator end_sn = pks_sn.upper_bound(mono_sn_threshold);\t\t\n\t\tRichPeakListBySignalOverNoise::iterator iter = pks_sn.begin();\n\t\t//RichPeakListBySignalOverNoise::iterator iter;\n\n\n\t\t/*RichPeakListByType& pks_type = spectrum.getPeakListByType<peak_type>();\n\n\t\tstd::pair<RichPeakListByType::iterator, RichPeakListByType::iterator> p = pks_type.equal_range(\"ISO\");*/\n\n\t\tint precursor_z = param.getParameter<int>(\"precursor_charge\").first;\n\t\tint charge_sign = precursor_z > 0 ? 1 : -1;\n\n\t\t//for(RichPeakListByType::iterator iter = p.first; iter != p.second; iter++)\n\t\tfor(; iter != end_sn; iter++ )\n\t\t{\n\t\t\tRichPeakPtr base_pk = *iter;\n\t\t\tif(base_pk->pk_type != \"ISO\")\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint count = 0;\n\t\t\tfor(int z = 1; z < abs(precursor_z); z++)\n\t\t\t{\n\t\t\t\t// Consider only A+1 peak.\n\t\t\t\tstd::pair<PeakPtr, PeakPtr> pk_pair = getPeakRangeByShift(base_pk, charge_sign*z, 1, -1);\n\t\t\t\tdouble mz0 = pk_pair.second->mz;\n\t\t\t\tstd::set<RichPeakPtr> pk_set = getClosestRichPeaks(spectrum, mz0, true, 0.0);\n\n\t\t\t\tif(pk_set.size() == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// Estimate the intensity shift.\n\t\t\t\tRichPeakPtr pk0 = *(pk_set.begin());\n\n\t\t\t\tdouble intensity_shift = (pk0->intensity - pk_pair.first->intensity) / pk_pair.first->intensity;\n\n\t\t\t\tif(intensity_shift > -0.2) {\n\t\t\t\t\tcount++;\n\t\t\t\t\t// A candidate envelop.\n\t\t\t\t\tund_pk.insert(std::make_pair(base_pk, z));\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif(count == 0)\n\t\t\t\tsetPeakType(base_pk, \"NOISE\");\n\n\t\t}\n\t}\n\n\tstd::pair<PeakPtr, PeakPtr> SimpleFinder::getPeakRangeByShift( RichPeakPtr base_pk, int charge, int shift, int sulfur /*= -1*/ )\n\t{\n\t\tdouble pre_mass = calculateMass(base_pk->mz, charge);\n\n\t\tAggregatedIsotopicVariants iso_no_sulfur = this->estimateDistribution(base_pk->mz, charge, 0);\n\t\tint max_sulfur = (sulfur == -1 ? guessMaxSulfurNumber(base_pk->mz, charge) : sulfur);\n\t\tAggregatedIsotopicVariants iso_max_sulfur = this->estimateDistribution(base_pk->mz, charge, max_sulfur);\n\n\t\tdouble mz_max_sulfur = base_pk->mz + iso_max_sulfur.getMassDifferenceByShift<peak_intensity>(0, shift)/(float)abs(charge);\n\t\tdouble mz_no_sulfur = base_pk->mz + iso_no_sulfur.getMassDifferenceByShift<peak_intensity>(0, shift)/(float)abs(charge);\n\n\t\tdouble int_max_sulfur = base_pk->intensity * iso_max_sulfur.getPeakByShift<peak_intensity>(shift)->intensity;\n\t\tdouble int_no_sulfur = base_pk->intensity * iso_no_sulfur.getPeakByShift<peak_intensity>(shift)->intensity;\n\n\t\tPeakPtr pk_max_sulfur = boost::make_shared<Peak>(mz_max_sulfur, int_max_sulfur);\n\t\tPeakPtr pk_no_sulfur = boost::make_shared<Peak>(mz_no_sulfur, int_no_sulfur);\n\n\t\treturn std::make_pair(pk_max_sulfur, pk_no_sulfur);\n\n\t}\n\n\tvoid SimpleFinder::setPeakType( RichPeakPtr pk, const std::string& new_type )\n\t{\n\t\t// 1. Find the iterator of the peak.\n\t\tRichPeakListByID& pks_id = spectrum.getPeakListByType<peak_id>();\n\t\tRichPeakListByID::iterator id_iter = pks_id.find(pk->id);\n\n\t\t// 2. Project the iterator to type.\n\t\tRichPeakListByType::iterator type_iter = spectrum.getPeakContainer().project<peak_type>(id_iter);\n\n\t\t// 2. Modify the type of the element referred by the iterator.\n\t\tspectrum.modifyType(type_iter, new_type);\n\t}\n\n\tvoid SimpleFinder::detectHarmonicCluster(RichPeakPtr base_pk, int charge)\n\t{\n\t\t//std::set<RichPeakPtr> harmonic_cluster;\n\n\t\t// The S/N threshold for monoisotopic peawk.\n\t\tdouble mono_sn_threshold = param.getParameter<double>(\"signal_noise\").first;\n\n\t\t/*double cur_mz = param.getParameter<double>(\"precursor_mz\").first;\n\t\tint cur_charge = param.getParameter<int>(\"precursor_charge\").first;*/\n\n\t\tdouble cur_mass = calculateMass(base_pk->mz, charge);\n\n\t\tint coef = 2;\n\t\t// Get the minimum m/z.\n\t\tRichPeakListByMZ& pks_mz = spectrum.getPeakListByType<peak_mz>();\n\t\tdouble min_mz = (*(pks_mz.begin()))->mz;\n\n\t\twhile(1)\n\t\t{\n\t\t\t// Get new m/z based on adjusted charge state.\n\t\t\t\n\t\t\tint new_charge = coef * charge;\n\t\t\tdouble new_mz = calculateMZ(cur_mass, new_charge, charge);\n\n\t\t\tcoef++;\n\n\t\t\tif(new_mz < min_mz)\n\t\t\t\tbreak;\n\n\t\t\t// Find the base peak.\n\t\t\tstd::set<RichPeakPtr> pk_set = getClosestRichPeaks(spectrum, new_mz, false, mono_sn_threshold, 3e-5);\n\n\t\t\tif(pk_set.size() == 0)\n\t\t\t\tcontinue;\n\t\t\t\n\t\t\tRichPeakPtr base_pk = *(pk_set.begin());\n\t\t\tthis->cleanNeighborNoise(spectrum, base_pk);\n\n\t\t\tif(base_pk->signal_noise < mono_sn_threshold)\n\t\t\t\tcontinue;\n\n\t\t\tbool status = extendEnvelop(spectrum, base_pk, abs(new_charge), false);\n\n\t\t\tif(status) {\n\t\t\t\t//harmonic_cluster.insert(base_pk);\n\t\t\t\tstd::cout << \"Find harmonic cluster: \" << base_pk->mz << \" \" << new_charge << std::endl;\n\t\t\t}\n\t\t}\n\t\t\n\t\t//return harmonic_cluster;\n\t}\n\n}", "meta": {"hexsha": "1a999b4e1a431189541f2528525349947f275f30", "size": 45390, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GAG/src/GAGPL/SPECTRUM/SimpleFinder.cpp", "max_stars_repo_name": "hh1985/multi_hs_seq", "max_stars_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-03T14:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-15T13:38:39.000Z", "max_issues_repo_path": "GAG/src/GAGPL/SPECTRUM/SimpleFinder.cpp", "max_issues_repo_name": "hh1985/multi_hs_seq", "max_issues_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GAG/src/GAGPL/SPECTRUM/SimpleFinder.cpp", "max_forks_repo_name": "hh1985/multi_hs_seq", "max_forks_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8617511521, "max_line_length": 231, "alphanum_fraction": 0.6893148271, "num_tokens": 13005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24275779355327787}}
{"text": "#ifndef SPLX_PIECEWISECURVE_QP_GENERATOR_HPP\n#define SPLX_PIECEWISECURVE_QP_GENERATOR_HPP\n\n#include <qp_wrappers/problem.hpp>\n#include <splx/opt/QPOperations.hpp>\n#include <splx/opt/BezierQPOperations.hpp>\n#include <splx/types.hpp>\n#include <splx/curve/PiecewiseCurve.hpp>\n#include <splx/opt/BezierQPOperations.hpp>\n#include <absl/strings/str_cat.h>\n#include <Eigen/StdVector>\n\nnamespace splx {\n\ntemplate<typename T, unsigned int DIM>\nclass PiecewiseCurveQPGenerator {\npublic:\n    using _BezierQPOperations = BezierQPOperations<T, DIM>;\n    using _Problem = QPWrappers::Problem<T>;\n    using Row = splx::Row<T>;\n    using VectorDIM = splx::VectorDIM<T, DIM>;\n    using Vector = splx::Vector<T>;\n    using Hyperplane = splx::Hyperplane<T, DIM>;\n    using AlignedBox = splx::AlignedBox<T, DIM>;\n    using Index = splx::Index;\n    using Matrix = splx::Matrix<T>;\n    using _QPOperations = QPOperations<T, DIM>;\n    using _PiecewiseCurve = PiecewiseCurve<T, DIM>;\n    using StdVectorVectorDIM\n        = std::vector<VectorDIM, Eigen::aligned_allocator<VectorDIM>>;\n    using Constraint = splx::Constraint<T>;\n\n    PiecewiseCurveQPGenerator() : m_problem(0) {}\n\n    void addPiece(std::shared_ptr<_QPOperations> opt_ptr) {\n        m_operations.push_back(opt_ptr);\n        \n        if(m_cumulativeMaxParameters.empty()) {\n            m_cumulativeMaxParameters.push_back(opt_ptr->maxParameter());\n        } else {\n            m_cumulativeMaxParameters.push_back(\n                m_cumulativeMaxParameters.back() + opt_ptr->maxParameter()\n            );\n        }\n\n        if(m_cumulativeDecisionVars.empty()) {\n            m_cumulativeDecisionVars.push_back(opt_ptr->numDecisionVariables());\n        } else {\n            m_cumulativeDecisionVars.push_back(\n                m_cumulativeDecisionVars.back() \n                + opt_ptr->numDecisionVariables()\n            );\n        }\n\n        m_problem = QPWrappers::Problem<T>(this->numDecisionVariables());\n    }\n\n    void setPiece(std::size_t idx, std::shared_ptr<_QPOperations> opt_ptr) {\n        m_operations[idx] = opt_ptr;\n        this->fixCumulativeStructures(idx);\n        m_problem = QPWrappers::Problem<T>(this->numDecisionVariables());\n    }\n\n    void removePiece(std::size_t idx) {\n        m_operations.erase(m_operations.begin() + idx);\n        m_cumulativeDecisionVars.erase(\n                m_cumulativeDecisionVars.begin() + idx\n        );\n        m_cumulativeMaxParameters.erase(\n                m_cumulativeMaxParameters.begin() + idx\n        );\n        this->fixCumulativeStructures(idx);\n        m_problem = QPWrappers::Problem<T>(this->numDecisionVariables());\n    }\n\n    void removeAllPieces() {\n        m_operations.clear();\n        m_cumulativeMaxParameters.clear();\n        m_cumulativeDecisionVars.clear();\n        m_problem = QPWrappers::Problem<T>(0);\n    }\n\n    void addBezier(Index ncpts, T a) {\n        auto bezptr = std::make_shared<_BezierQPOperations>(ncpts, a);\n        auto optptr = std::static_pointer_cast<_QPOperations>(bezptr);\n        this->addPiece(optptr);\n    }\n\n    void setBezier(std::size_t idx, Index ncpts, T a) {\n        auto bezptr = std::make_shared<_BezierQPOperations>(ncpts, a);\n        auto optptr = std::static_pointer_cast<_QPOperations>(bezptr);\n        this->setPiece(idx, optptr);\n    }\n\n    std::size_t numPieces() const {\n        return m_cumulativeDecisionVars.size();\n    }\n\n    std::vector<T> pieceMaxParameters() const {\n        std::vector<T> piece_max_params;\n        for(const auto piece_opt : m_operations) {\n            piece_max_params.push_back(piece_opt->maxParameter());\n        }\n        return piece_max_params;\n    }\n\n    T maxParameter() const {\n        if(m_operations.empty()) {\n            throw std::domain_error(\n                absl::StrCat(\n                    \"piecewise curve has no pieces\"\n                )\n            );\n        }\n\n        return m_cumulativeMaxParameters.back();\n    }\n\n    void setPieceMaxParameters(const std::vector<T>& new_max_params) {\n        if(new_max_params.size() != m_operations.size()) {\n            throw std::domain_error(\n                absl::StrCat(\n                    \"new max parameters size does not match number of pieces\",\n                    \", number of pieces: \",\n                    m_operations.size(),\n                    \", given number of max parameters: \",\n                    new_max_params.size()\n                )\n            );\n        }\n\n        for(std::size_t i = 0; i < m_operations.size(); i++) {\n            m_operations[i]->maxParameter(new_max_params[i]);\n        }\n\n        this->fixCumulativeStructures(0);\n        m_problem = QPWrappers::Problem<T>(this->numDecisionVariables());\n    }\n\n    Index numDecisionVariables() const {\n        if(m_cumulativeDecisionVars.empty()) return 0;\n\n        return m_cumulativeDecisionVars.back();\n    }\n    \n    void addIntegratedSquaredDerivativeCost(unsigned int k, T lambda) {\n        Matrix Q(this->numDecisionVariables(), this->numDecisionVariables());\n        Vector c(this->numDecisionVariables());\n        Q.setZero();\n        c.setZero();\n\n        for(std::size_t i = 0; i < this->numPieces(); i++) {\n            Index dvar_start_idx = (i == 0 ? 0 : m_cumulativeDecisionVars[i-1]);\n            Index dvar_count = m_operations[i]->numDecisionVariables();\n\n            auto [Qs, cs]\n                = m_operations[i]->integratedSquaredDerivativeCost(k, lambda);\n            \n            Q.block(dvar_start_idx, dvar_start_idx, dvar_count, dvar_count) = Qs;\n            c.block(dvar_start_idx, 0, dvar_count, 1) = cs;\n        }\n\n        m_problem.add_Q(Q);\n        m_problem.add_c(c);\n    }\n\n    void addEvalCost(T u, unsigned int k, const VectorDIM& target, T lambda) {\n        Matrix Q(this->numDecisionVariables(), this->numDecisionVariables());\n        Vector c(this->numDecisionVariables());\n        Q.setZero();\n        c.setZero();\n\n        auto [idx, param, first_dvar_index, dvar_count] = pieceInfo(u);\n        auto [Qs, cs] = m_operations[idx]->evalCost(param, k, target, lambda);\n        Q.block(first_dvar_index, first_dvar_index, \n                dvar_count, dvar_count) = Qs;\n        c.block(first_dvar_index, 0, dvar_count, 1) = cs;\n\n        m_problem.add_Q(Q);\n        m_problem.add_c(c);\n    }\n\n    void addEvalConstraint(T u, unsigned int k, const VectorDIM& target,\n                           bool soft_convertible = false,\n                           T soft_convertible_weight = T(1)) {\n        auto [idx, param, first_dvar_index, dvar_count] = pieceInfo(u);\n        auto constraints = m_operations[idx]->evalConstraint(param, k, target,\n                soft_convertible, soft_convertible_weight);\n\n        this->addConstraints(constraints, first_dvar_index, dvar_count);\n    }\n\n    void addHyperplaneConstraintForPiece(std::size_t idx, const Hyperplane& hp,\n                                         bool soft_convertible = false,\n                                         T soft_convertible_weight = T(1)) {\n        Index first_dvar_index = \n                (idx == 0 ? 0 : m_cumulativeDecisionVars[idx-1]);\n        Index dvar_count = m_operations[idx]->numDecisionVariables();\n\n        auto constraints = m_operations[idx]->hyperplaneConstraintAll(hp,\n                                  soft_convertible, soft_convertible_weight);\n\n        this->addConstraints(constraints, first_dvar_index, dvar_count);\n    }\n\n    void addHyperplaneConstraintAll(const Hyperplane& hp,\n                                    bool soft_convertible = false,\n                                    T soft_convertible_weight = T(1)) {\n        for(std::size_t i = 0; i < this->numPieces(); i++) {\n            this->addHyperplaneConstraintForPiece(i, hp,\n                                  soft_convertible, soft_convertible_weight);\n        }\n    }\n\n    void addHyperplaneConstraintAt(T u, const Hyperplane& hp,\n                                   bool soft_convertible = false,\n                                   T soft_convertible_weight = T(1)) {\n        auto [idx, param, first_dvar_index, dvar_count] = pieceInfo(u);\n        auto constraints = m_operations[idx]->hyperplaneConstraintAt(param, hp,\n                                 soft_convertible, soft_convertible_weight);\n        this->addConstraints(constraints, first_dvar_index, dvar_count);\n    }\n\n    void addBoundingBoxConstraint(const AlignedBox& bbox) {\n        for(std::size_t i = 0; i < this->numPieces(); i++) {\n            auto [lbx, ubx] = m_operations[i]->boundingBoxConstraint(bbox);\n            Index first_dvar_index = \n                    (i == 0 ? 0 : m_cumulativeDecisionVars[i-1]);\n            Index dvar_count = m_operations[i]->numDecisionVariables();\n\n            assert(lbx.rows() == dvar_count);\n\n            for(Index j = 0; j < dvar_count; j++) {\n                m_problem.set_var_limits(first_dvar_index + j, lbx(j), ubx(j));\n            }\n        }\n    }\n\n    // adds continueity constraint between piece idx and piece idx + 1\n    // in their kth derivatives\n    void addContinuityConstraint(std::size_t idx, unsigned int k,\n                                 bool soft_convertible = false,\n                                 T soft_convertible_weight = T(1)) {\n        Index first_piece_numdvars = m_operations[idx]->numDecisionVariables();\n        Index second_piece_numdvars = \n                m_operations[idx+1]->numDecisionVariables();\n        Index first_piece_dvars_start \n            = (idx == 0 ? 0 : m_cumulativeDecisionVars[idx-1]);\n        Index second_piece_dvars_start = m_cumulativeDecisionVars[idx];\n\n        for(unsigned int d = 0; d < DIM; d++) {\n            Row coeff1 = m_operations[idx]->evalBasisRow(\n                            d, m_operations[idx]->maxParameter(), k\n            );\n            Row coeff2 = m_operations[idx+1]->evalBasisRow(\n                            d, 0, k\n            );\n\n            Row coeff(this->numDecisionVariables());\n            coeff.setZero();\n            coeff.block(0, first_piece_dvars_start, 1, first_piece_numdvars) \n                                = coeff1;\n            coeff.block(0, second_piece_dvars_start, 1, second_piece_numdvars)\n                                = -coeff2;\n\n            m_problem.add_constraint(coeff, 0, 0, soft_convertible, soft_convertible_weight);\n        }\n    }\n\n    Vector getDVarsForSegments(const StdVectorVectorDIM& segments) const {\n        if(segments.size() != this->numPieces() + 1) {\n            throw std::domain_error\n            (\n                absl::StrCat\n                (\n                    \"number of segments is not equal to the number of pieces\",\n                    \", segment count: \",\n                    segments.size() - 1,\n                    \", piece count: \",\n                    this->numPieces()\n                )\n            );\n        }\n\n        Vector res(this->numDecisionVariables());\n\n        for(std::size_t i = 0; i < segments.size() - 1; i++) {\n            Index piece_dvars_start\n                = (i == 0 ? 0: m_cumulativeDecisionVars[i-1]);\n            Index piece_numdvars = m_operations[i]->numDecisionVariables();\n            res.block(piece_dvars_start, 0, piece_numdvars, 1)\n                = m_operations[i]->getDVarsForSegment\n            (\n                        segments[i],\n                        segments[i+1]\n            );\n        }\n\n        return res;\n    }\n    _PiecewiseCurve extractCurve(const Vector& soln) {\n        if(soln.rows() != this->numDecisionVariables()) {\n            throw std::domain_error(\n                absl::StrCat(\n                    \"number of decision variables does not match. given: \",\n                    soln.rows(),\n                    \", required: \",\n                    this->numDecisionVariables()\n                )\n            );\n        }\n\n        _PiecewiseCurve piecewise;\n        for(std::size_t i = 0; i < this->numPieces(); i++) {\n            Index piece_numdvars = m_operations[i]->numDecisionVariables();\n            Index piece_dvars_start = \n                    (i==0 ? 0 : m_cumulativeDecisionVars[i-1]);\n            \n            Vector dvars = soln.block(piece_dvars_start, 0, piece_numdvars, 1);\n            piecewise.addPiece(m_operations[i]->extractCurve(dvars));\n        }\n\n        return piecewise;\n    }\n\n\n    void resetProblem() {\n        m_problem.reset();\n    }\n\n    void resetGenerator() {\n        m_operations.clear();\n        m_cumulativeMaxParameters.clear();\n        m_cumulativeDecisionVars.clear();\n        this->resetProblem();\n    }\n\n    const QPWrappers::Problem<T>& getProblem() const {\n        return this->m_problem;\n    }\n\nprivate:\n    std::vector<std::shared_ptr<_QPOperations>> m_operations;\n    std::vector<T> m_cumulativeMaxParameters;\n    std::vector<Index> m_cumulativeDecisionVars;\n    QPWrappers::Problem<T> m_problem;\n\n    /*\n    * fix cumulative structures starting from the given index\n    */\n    void fixCumulativeStructures(std::size_t idx) {\n        for(std::size_t i = idx; i < this->numPieces(); i++) {\n            if(i == 0) {\n                m_cumulativeMaxParameters[i] = m_operations[i]->maxParameter();\n                m_cumulativeDecisionVars[i] =\n                    m_operations[i]->numDecisionVariables();\n            } else {\n                m_cumulativeMaxParameters[i] =\n                      m_operations[i]->maxParameter()\n                    + m_cumulativeMaxParameters[i-1];\n                m_cumulativeDecisionVars[i] =\n                      m_operations[i]->numDecisionVariables()\n                    + m_cumulativeDecisionVars[i-1];\n            }\n        }\n    }\n\n    /*\n    * Given a parameter, return the piece index, piece parameter corresponding\n    * to the given parameter, first decision variable index and decision\n    * variable count for the piece\n    */\n    std::tuple<std::size_t, T, Index, Index> pieceInfo(T param) const {\n        std::size_t idx = std::lower_bound(\n                    m_cumulativeMaxParameters.begin(),\n                    m_cumulativeMaxParameters.end(),\n                    param) - m_cumulativeMaxParameters.begin();\n\n        Index first_dvar_index = 0;\n        Index dvar_count = m_operations[idx]->numDecisionVariables();\n        if(idx != 0) {\n            param -= m_cumulativeMaxParameters[idx-1];\n            first_dvar_index = m_cumulativeDecisionVars[idx-1];\n        }\n\n        return {\n            idx,\n            std::min(param, m_operations[idx]->maxParameter()),\n            first_dvar_index,\n            dvar_count\n        };\n    }\n\n    void addConstraints(const std::vector<Constraint>& cons,\n                        Index first_dvar_index, Index dvar_count) {\n\n        Row coeff(this->numDecisionVariables());\n\n        for(const auto& constraint: cons) {\n            coeff.setZero();\n            coeff.block(0, first_dvar_index, 1, dvar_count) \n                        = constraint.coeff;\n            m_problem.add_constraint(coeff, \n                                     constraint.lb,\n                                     constraint.ub,\n                                     constraint.soft_convertible,\n                                     constraint.soft_weight\n            );   \n        }\n    }\n\n\n};\n\n}\n\n#endif", "meta": {"hexsha": "25f06bd4e4f81d3a5f157e55744bb93750727c9d", "size": 15132, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/splx/opt/PiecewiseCurveQPGenerator.hpp", "max_stars_repo_name": "baskinburak/splx", "max_stars_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/splx/opt/PiecewiseCurveQPGenerator.hpp", "max_issues_repo_name": "baskinburak/splx", "max_issues_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-21T00:30:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-27T01:39:41.000Z", "max_forks_repo_path": "include/splx/opt/PiecewiseCurveQPGenerator.hpp", "max_forks_repo_name": "baskinburak/splx", "max_forks_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-12T08:17:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T08:17:37.000Z", "avg_line_length": 36.2877697842, "max_line_length": 93, "alphanum_fraction": 0.5724292889, "num_tokens": 3377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24275779355327787}}
{"text": "// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n// Copyright (c) 2012, 2013 Pierre MOULON.\n\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this\n// file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\n#ifndef OPENMVG_NUMERIC_LM_HPP\n#define OPENMVG_NUMERIC_LM_HPP\n\n// Levenberg Marquardt Non Linear Optimization\n#include <Eigen/Core>\n\nnamespace openMVG\n{\nusing namespace Eigen;\n\n/**\n * @brief Generic functor Levenberg-Marquardt minimization\n * @tparam _Scalar Type of internal computation\n * @tparam NX Number of values per sample at compile time\n * @tparam NY Number of samples at compile time\n */\ntemplate<typename _Scalar, int NX = Dynamic, int NY = Dynamic>\nstruct Functor\n{\n  using Scalar = _Scalar;\n  enum\n  {\n    InputsAtCompileTime = NX,\n    ValuesAtCompileTime = NY\n  };\n  using InputType = Matrix<Scalar, InputsAtCompileTime, 1>;\n  using ValueType = Matrix<Scalar, ValuesAtCompileTime, 1>;\n  using JacobianType = Matrix<Scalar, ValuesAtCompileTime, InputsAtCompileTime>;\n\n\n  /// Number of values per sample\n  const int m_inputs;\n\n  // Number of sample\n  const int m_values;\n\n  /**\n  * @brief Default constructor\n  */\n  Functor()\n    : m_inputs( InputsAtCompileTime ),\n      m_values( ValuesAtCompileTime )\n  {\n\n  }\n\n  /**\n  * @brief Constructor\n  * @param inputs Number of column per sample\n  * @param values Number of sample\n  */\n  Functor( int inputs, int values ) : m_inputs( inputs ), m_values( values ) {}\n\n  /**\n  * @brief Get number of samples\n  * @return Number of samples\n  */\n  int inputs() const\n  {\n    return m_inputs;\n  }\n\n  /**\n  * @brief Get number of samples\n  * @return Number of samples\n  */\n  int values() const\n  {\n    return m_values;\n  }\n\n  // you should define that in the subclass :\n  //  void operator() (const InputType& x, ValueType* v, JacobianType* _j=0) const;\n};\n\n}; // namespace openMVG\n\n#endif // OPENMVG_NUMERIC_LM_HPP\n", "meta": {"hexsha": "6a48a30e8725e0159c831bd20c7f8ebb287b75e9", "size": 1988, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/numeric/lm.hpp", "max_stars_repo_name": "Aurelio93/satellite-pose-estimation", "max_stars_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2019-05-19T03:48:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:20:49.000Z", "max_issues_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/numeric/lm.hpp", "max_issues_repo_name": "Aurelio93/satellite-pose-estimation", "max_issues_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:45:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-20T01:48:26.000Z", "max_forks_repo_path": "pose_refinement/SA-LMPE/ba/openMVG/numeric/lm.hpp", "max_forks_repo_name": "Aurelio93/satellite-pose-estimation", "max_forks_repo_head_hexsha": "46957a9bc9f204d468f8fe3150593b3db0f0726a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2019-05-19T03:48:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-29T18:19:16.000Z", "avg_line_length": 22.8505747126, "max_line_length": 83, "alphanum_fraction": 0.6966800805, "num_tokens": 529, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2425397026294272}}
{"text": "\n\n#include <NTL/GF2X.h>\n#include <NTL/vec_long.h>\n\n#include <NTL/new.h>\n\n#if (defined(NTL_WIZARD_HACK) && defined(NTL_GF2X_LIB))\n#undef NTL_GF2X_LIB\n#endif\n\n\n// some crossover points...choice depends\n// if we are using the gf2x lib or not\n\n#ifdef NTL_GF2X_LIB\n\n#define NTL_GF2X_GCD_CROSSOVER (400L*NTL_BITS_PER_LONG) \n#define NTL_GF2X_HalfGCD_CROSSOVER (6L*NTL_BITS_PER_LONG)\n#define NTL_GF2X_BERMASS_CROSSOVER (200L*NTL_BITS_PER_LONG)\n\n#else\n\n#define NTL_GF2X_GCD_CROSSOVER (900L*NTL_BITS_PER_LONG) \n#define NTL_GF2X_HalfGCD_CROSSOVER (6L*NTL_BITS_PER_LONG)\n#define NTL_GF2X_BERMASS_CROSSOVER (450L*NTL_BITS_PER_LONG)\n\n#endif\n\n\nNTL_START_IMPL\n\n/********** data structures for accesss to GF2XRegisters ************/\n\nstatic GF2X GF2XRegisterVec[32];\nstatic long GF2XRegisterTop = 0;\n\n\nclass GF2XRegisterType {\npublic:\n\nGF2X *xrep;\n\nGF2XRegisterType()\n{ xrep = &GF2XRegisterVec[GF2XRegisterTop]; GF2XRegisterTop++; }\n\n~GF2XRegisterType()\n{ xrep->xrep.release();  \n  GF2XRegisterTop--; }\n\noperator GF2X& () { return *xrep; }\n\n};\n\n#define GF2XRegister(a) GF2XRegisterType GF2XReg__ ## a ; GF2X& a = GF2XReg__ ## a\n\n\n\n\n\n\n\nstatic vec_GF2X stab;  // used by PlainDivRem and PlainRem\n\nstatic WordVector GF2X_rembuf;\n\n\nvoid PlainDivRem(GF2X& q, GF2X& r, const GF2X& a, const GF2X& b)\n{\n   long da, sa, posa, db, sb, posb, dq, sq, posq;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) Error(\"GF2X: division by zero\");\n\n   if (da < db) {\n      r = a;\n      clear(q);\n      return;\n   }\n\n   sa = a.xrep.length();\n   posa = da - NTL_BITS_PER_LONG*(sa-1);\n   sb = b.xrep.length();\n   posb = db - NTL_BITS_PER_LONG*(sb-1);\n\n   dq = da - db;\n   sq = dq/NTL_BITS_PER_LONG + 1;\n   posq = dq - NTL_BITS_PER_LONG*(sq-1);\n\n   _ntl_ulong *ap;\n   if (&r == &a)\n      ap = r.xrep.elts();\n   else {\n      GF2X_rembuf = a.xrep;\n      ap = GF2X_rembuf.elts();\n   }\n\n   stab.SetLength(NTL_BITS_PER_LONG);\n   long i;\n\n   stab[posb] = b;\n   for (i = 1; i <= min(dq, NTL_BITS_PER_LONG-1); i++) \n      MulByX(stab[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG], \n             stab[((_ntl_ulong)(posb+i-1))%NTL_BITS_PER_LONG]);\n\n   _ntl_ulong *stab_ptr[NTL_BITS_PER_LONG];\n   long stab_cnt[NTL_BITS_PER_LONG];\n\n   for (i = 0; i <= min(dq, NTL_BITS_PER_LONG-1); i++) {\n      WordVector& st = stab[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG].xrep;\n      long k = st.length();\n      stab_ptr[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG] = &st[k-1];\n      stab_cnt[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG] = -k+1;\n   }\n\n   q.xrep.SetLength(sq);\n   _ntl_ulong *qp = q.xrep.elts();\n   for (i = 0; i < sq; i++)\n      qp[i] = 0;\n\n   _ntl_ulong *atop = &ap[sa-1];\n   _ntl_ulong *qtop = &qp[sq-1];\n   _ntl_ulong *stab_top;\n\n   while (1) {\n      if (atop[0] & (1UL << posa)) {\n         qtop[0] |= (1UL << posq);\n         stab_top = stab_ptr[posa];\n         for (i = stab_cnt[posa]; i <= 0; i++)\n            atop[i] ^= stab_top[i];\n      }\n\n      da--;\n      if (da < db) break;\n\n      posa--;\n      if (posa < 0) {\n         posa = NTL_BITS_PER_LONG-1;\n         atop--;\n      }\n\n      posq--;\n      if (posq < 0) {\n         posq = NTL_BITS_PER_LONG-1;\n         qtop--;\n      }\n   }\n\n   if (posb == 0) sb--;\n\n   r.xrep.SetLength(sb);\n   if (&r != &a) {\n      _ntl_ulong *rp = r.xrep.elts();\n      for (i = 0; i < sb; i++)\n         rp[i] = ap[i];\n   }\n   r.normalize();\n\n   GF2X_rembuf.release();\n   for (i = 0; i <= min(dq, NTL_BITS_PER_LONG-1); i++) {\n      WordVector& st = stab[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG].xrep;\n      st.release();\n   }\n}\n\n\n\nvoid PlainDiv(GF2X& q, const GF2X& a, const GF2X& b)\n{\n   GF2XRegister(r);\n   PlainDivRem(q, r, a, b);\n}\n\n\nvoid PlainRem(GF2X& r, const GF2X& a, const GF2X& b)\n{\n   long da, sa, posa, db, sb, posb;\n\n   da = deg(a);\n   db = deg(b);\n\n   if (db < 0) Error(\"GF2X: division by zero\");\n\n   if (da < db) {\n      r = a;\n      return;\n   }\n\n   sa = a.xrep.length();\n   posa = da - NTL_BITS_PER_LONG*(sa-1);\n   sb = b.xrep.length();\n   posb = db - NTL_BITS_PER_LONG*(sb-1);\n\n   _ntl_ulong *ap;\n   if (&r == &a)\n      ap = r.xrep.elts();\n   else {\n      GF2X_rembuf = a.xrep;\n      ap = GF2X_rembuf.elts();\n   }\n\n   stab.SetLength(NTL_BITS_PER_LONG);\n   long i;\n\n   stab[posb] = b;\n   for (i = 1; i <= min(da-db, NTL_BITS_PER_LONG-1); i++) \n      MulByX(stab[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG], \n             stab[((_ntl_ulong)(posb+i-1))%NTL_BITS_PER_LONG]);\n\n   _ntl_ulong *stab_ptr[NTL_BITS_PER_LONG];\n   long stab_cnt[NTL_BITS_PER_LONG];\n\n   for (i = 0; i <= min(da-db, NTL_BITS_PER_LONG-1); i++) {\n      WordVector& st = stab[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG].xrep;\n      long k = st.length();\n      stab_ptr[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG] = &st[k-1];\n      stab_cnt[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG] = -k+1;\n   }\n\n\n   _ntl_ulong *atop = &ap[sa-1];\n   _ntl_ulong *stab_top;\n\n   while (1) {\n      if (atop[0] & (1UL << posa)) {\n         stab_top = stab_ptr[posa];\n         for (i = stab_cnt[posa]; i <= 0; i++)\n            atop[i] ^= stab_top[i];\n      }\n\n      da--;\n      if (da < db) break;\n\n      posa--;\n      if (posa < 0) {\n         posa = NTL_BITS_PER_LONG-1;\n         atop--;\n      }\n   }\n\n   if (posb == 0) sb--;\n\n   r.xrep.SetLength(sb);\n   if (&r != &a) {\n      _ntl_ulong *rp = r.xrep.elts();\n      for (i = 0; i < sb; i++)\n         rp[i] = ap[i];\n   }\n   r.normalize();\n\n   GF2X_rembuf.release();\n   for (i = 0; i <= min(da-db, NTL_BITS_PER_LONG-1); i++) {\n      WordVector& st = stab[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG].xrep;\n      st.release();\n   }\n}\n\n#define MASK8 ((1UL << 8)-1UL)\n\nstatic _ntl_ulong invtab[128] = {\n1UL, 255UL, 85UL, 219UL, 73UL, 151UL, 157UL, 51UL, 17UL, 175UL,\n69UL, 139UL, 89UL, 199UL, 141UL, 99UL, 33UL, 95UL, 117UL, 123UL,\n105UL, 55UL, 189UL, 147UL, 49UL, 15UL, 101UL, 43UL, 121UL, 103UL,\n173UL, 195UL, 65UL, 191UL, 21UL, 155UL, 9UL, 215UL, 221UL, 115UL,\n81UL, 239UL, 5UL, 203UL, 25UL, 135UL, 205UL, 35UL, 97UL, 31UL,\n53UL, 59UL, 41UL, 119UL, 253UL, 211UL, 113UL, 79UL, 37UL, 107UL,\n57UL, 39UL, 237UL, 131UL, 129UL, 127UL, 213UL, 91UL, 201UL, 23UL,\n29UL, 179UL, 145UL, 47UL, 197UL, 11UL, 217UL, 71UL, 13UL, 227UL,\n161UL, 223UL, 245UL, 251UL, 233UL, 183UL, 61UL, 19UL, 177UL, 143UL,\n229UL, 171UL, 249UL, 231UL, 45UL, 67UL, 193UL, 63UL, 149UL, 27UL,\n137UL, 87UL, 93UL, 243UL, 209UL, 111UL, 133UL, 75UL, 153UL, 7UL,\n77UL, 163UL, 225UL, 159UL, 181UL, 187UL, 169UL, 247UL, 125UL, 83UL,\n241UL, 207UL, 165UL, 235UL, 185UL, 167UL, 109UL, 3UL };\n\n\n\nvoid NewtonInvTrunc(GF2X& c, const GF2X& a, long e)\n{\n   if (e == 1) {\n      set(c);\n      return;\n   }\n\n   static vec_long E;\n   E.SetLength(0);\n   append(E, e);\n   while (e > 8) {\n      e = (e+1)/2;\n      append(E, e);\n   }\n\n   long L = E.length();\n\n   GF2XRegister(g);\n   GF2XRegister(g0);\n   GF2XRegister(g1);\n   GF2XRegister(g2);\n\n   g.xrep.SetMaxLength((E[0]+NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG + 1);\n   g0.xrep.SetMaxLength((E[0]+NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG + 1);\n   g1.xrep.SetMaxLength(((3*E[0]+1)/2+NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG+1);\n   g2.xrep.SetMaxLength((E[0]+NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG + 1);\n\n   g.xrep.SetLength(1);\n   g.xrep[0] = invtab[(a.xrep[0] & MASK8) >> 1] & ((1UL<<e)-1UL);\n\n   long i;\n\n   for (i = L-1; i > 0; i--) {\n      // lift from E[i] to E[i-1]\n\n      long k = E[i];\n      long l = E[i-1]-E[i];\n\n      trunc(g0, a, k+l);\n\n      mul(g1, g0, g);\n      RightShift(g1, g1, k);\n      trunc(g1, g1, l);\n\n      mul(g2, g1, g);\n      trunc(g2, g2, l);\n      LeftShift(g2, g2, k);\n\n      add(g, g, g2);\n   }\n\n   c = g;\n}\n\nvoid InvTrunc(GF2X& c, const GF2X& a, long e)\n{\n   if (ConstTerm(a) == 0 || e < 0)\n      Error(\"inv: bad args\");\n\n   if (NTL_OVERFLOW(e, 1, 0))\n      Error(\"overflow in InvTrunc\");\n\n   if (e == 0) {\n      clear(c);\n      return;\n   }\n\n   NewtonInvTrunc(c, a, e);\n}\n\n\n\nstatic \nlong weight1(_ntl_ulong a)\n{\n   long res = 0;\n   while (a) {\n      if (a & 1) res ++;\n      a >>= 1;\n   }\n   return res;\n}\n\nlong weight(const GF2X& a)\n{\n   long wlen = a.xrep.length();\n   long res = 0;\n   long i;\n   for (i = 0; i < wlen; i++)\n      res += weight1(a.xrep[i]);\n\n   return res;\n}\n\n\n\nstatic\nvoid SparsityCheck(const GF2X& f, long& k3, long& k2, long& k1)\n{\n   long w = weight(f);\n   if (w != 3 && w != 5) {\n      k3 = 0;\n      return;\n   }\n\n   if (ConstTerm(f) != 1) {\n      k3 = 0;\n      return;\n   }\n\n   GF2X g = f;\n\n   long n = deg(f);\n\n   trunc(g, g, n);\n   \n   long t = deg(g);\n\n   if (n-t < NTL_BITS_PER_LONG || t > (n+1)/2) {\n      k3 = 0;\n      return;\n   }\n\n   if (w == 3) {\n      k3 = t;\n      k2 = 0;\n      return;\n   }\n\n   k3 = t;\n   trunc(g, g, t);\n   t = deg(g);\n   k2 = t;\n   trunc(g, g, t);\n   t = deg(g);\n   k1 = t;\n}\n\n\n\n\nconst long GF2X_MOD_PLAIN = 0;\nconst long GF2X_MOD_MUL = 1;\nconst long GF2X_MOD_SPECIAL = 2;\nconst long GF2X_MOD_TRI = 3;\nconst long GF2X_MOD_PENT = 4;\n\nvoid build(GF2XModulus& F, const GF2X& f)\n{\n   long n = deg(f);\n   long i;\n\n   if (n <= 0) Error(\"build(GF2XModulus,GF2X): deg(f) <= 0\");\n\n   F.tracevec.SetLength(0);\n\n   F.f = f;\n   F.n = n;\n   F.sn = f.xrep.length();\n\n   long sb = F.sn;\n   long posb = n - NTL_BITS_PER_LONG*(sb-1);\n\n   F.posn = posb; \n\n   if (F.posn > 0) {\n      F.size = F.sn;\n      F.msk = (1UL << F.posn) - 1UL;\n   }\n   else {\n      F.size = F.sn-1;\n      F.msk = ~0UL;\n   }\n\n   SparsityCheck(f, F.k3, F.k2, F.k1);\n\n   if (F.k3 != 0) {\n      if (F.k2 == 0)\n         F.method = GF2X_MOD_TRI;\n      else\n         F.method = GF2X_MOD_PENT;\n\n      return;\n   }\n\n\n   GF2X f0;\n   trunc(f0, f, n);\n   long deg_f0 = deg(f0);\n\n   if (F.sn > 1 && deg_f0 < NTL_BITS_PER_LONG \n       && deg_f0 >= NTL_BITS_PER_LONG/2) {\n      if (F.size >= 6)\n         F.method = GF2X_MOD_MUL;\n      else\n         F.method = GF2X_MOD_SPECIAL;\n   }\n   else if (F.sn > 1 && deg_f0 < NTL_BITS_PER_LONG/2) {\n      if (F.size >= 4)\n         F.method = GF2X_MOD_MUL;\n      else\n         F.method = GF2X_MOD_SPECIAL;\n   }\n   else if (F.size >= 8)\n      F.method = GF2X_MOD_MUL;\n   else \n      F.method = GF2X_MOD_PLAIN;\n      \n\n   if (F.method == GF2X_MOD_SPECIAL) {\n      if (!F.stab_cnt) F.stab_cnt = NTL_NEW_OP long[NTL_BITS_PER_LONG];\n      long *stab_cnt = F.stab_cnt;\n      if (!stab_cnt) Error(\"out of memory\");\n\n      if (!F.stab1) F.stab1 = NTL_NEW_OP _ntl_ulong[2*NTL_BITS_PER_LONG];\n      _ntl_ulong *stab1 = F.stab1;\n      if (!stab1) Error(\"out of memory\");\n\n      stab1[posb<<1] = f.xrep[0];\n      stab1[(posb<<1)+1] = 0;\n\n      stab_cnt[posb] = -sb+1;\n\n      for (i = 1; i < NTL_BITS_PER_LONG; i++) {\n         long kk0 = ((_ntl_ulong)(posb+i-1))%NTL_BITS_PER_LONG;\n         long kk1 = ((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG;\n\n         stab1[kk1<<1] = stab1[kk0<<1] << 1;\n         stab1[(kk1<<1)+1] = (stab1[(kk0<<1)+1] << 1) \n                          | (stab1[kk0<<1] >> (NTL_BITS_PER_LONG-1));\n\n         if (kk1 < posb) \n            stab_cnt[kk1] = -sb;\n         else\n            stab_cnt[kk1] = -sb+1;\n      }\n   }\n   else if (F.method == GF2X_MOD_PLAIN) {\n      vec_GF2X& stab = F.stab;\n      stab.SetLength(NTL_BITS_PER_LONG);\n\n\n      if (!F.stab_ptr) F.stab_ptr = NTL_NEW_OP _ntl_ulong_ptr[NTL_BITS_PER_LONG];\n      _ntl_ulong **stab_ptr = F.stab_ptr;\n      if (!stab_ptr) Error(\"out of memory\");\n\n      if (!F.stab_cnt) F.stab_cnt = NTL_NEW_OP long[NTL_BITS_PER_LONG];\n      long *stab_cnt = F.stab_cnt;\n      if (!stab_cnt) Error(\"out of memory\");\n      \n   \n      stab[posb] = f;\n      for (i = 1; i < NTL_BITS_PER_LONG; i++) \n         MulByX(stab[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG], \n                stab[((_ntl_ulong)(posb+i-1))%NTL_BITS_PER_LONG]);\n   \n   \n      for (i = 0; i < NTL_BITS_PER_LONG; i++) {\n         WordVector& st = stab[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG].xrep;\n         long k = st.length();\n         stab_ptr[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG] = &st[k-1];\n         stab_cnt[((_ntl_ulong)(posb+i))%NTL_BITS_PER_LONG] = -k+1;\n      }\n   }\n   else if (F.method == GF2X_MOD_MUL) {\n      GF2X P1, P2;\n\n      CopyReverse(P1, f, n);\n      InvTrunc(P2, P1, n-1);\n      CopyReverse(P1, P2, n-2);\n      trunc(F.h0, P1, n-2);\n      F.f0 = f0;\n   }\n}\n\nGF2XModulus::GF2XModulus()\n{\n   n = -1;\n   method = GF2X_MOD_PLAIN;\n   stab_ptr = 0;\n   stab_cnt = 0;\n   stab1 = 0;\n}\n\n\n// The following two routines are total spaghetti...unfortunately,\n// cleaning them up would require too much re-coding in other\n// places.\n\nGF2XModulus::GF2XModulus(const GF2XModulus& F) :\n   f(F.f), n(F.n), sn(F.sn), posn(F.posn), k3(F.k3), k2(F.k2), k1(F.k1),\n   size(F.size), \n   msk(F.msk), method(F.method), stab(F.stab), h0(F.h0), f0(F.f0),\n   stab_cnt(0), stab_ptr(0), stab1(0), tracevec(F.tracevec)\n{\n   if (method == GF2X_MOD_SPECIAL) {\n      long i;\n      stab1 = NTL_NEW_OP _ntl_ulong[2*NTL_BITS_PER_LONG];\n      if (!stab1) Error(\"GF2XModulus: out of memory\");\n      for (i = 0; i < 2*NTL_BITS_PER_LONG; i++)\n         stab1[i] = F.stab1[i];\n      stab_cnt = NTL_NEW_OP long[NTL_BITS_PER_LONG];\n      if (!stab_cnt) Error(\"GF2XModulus: out of memory\");\n      for (i = 0; i < NTL_BITS_PER_LONG; i++)\n         stab_cnt[i] = F.stab_cnt[i];\n   }\n   else if (method == GF2X_MOD_PLAIN) {\n      long i;\n\n      if (F.stab_cnt) {\n         stab_cnt = NTL_NEW_OP long[NTL_BITS_PER_LONG];\n         if (!stab_cnt) Error(\"GF2XModulus: out of memory\");\n         for (i = 0; i < NTL_BITS_PER_LONG; i++)\n            stab_cnt[i] = F.stab_cnt[i];\n      }\n\n      if (F.stab_ptr) {\n         stab_ptr = NTL_NEW_OP _ntl_ulong_ptr[NTL_BITS_PER_LONG];\n         if (!stab_ptr) Error(\"GF2XModulus: out of memory\");\n      \n         for (i = 0; i < NTL_BITS_PER_LONG; i++) {\n            WordVector& st = stab[((_ntl_ulong)(posn+i))%NTL_BITS_PER_LONG].xrep;\n            long k = st.length();\n            stab_ptr[((_ntl_ulong)(posn+i))%NTL_BITS_PER_LONG] = &st[k-1];\n            stab_cnt[((_ntl_ulong)(posn+i))%NTL_BITS_PER_LONG] = -k+1;\n         }\n      }\n   }\n}\n\nGF2XModulus& GF2XModulus::operator=(const GF2XModulus& F)\n{\n   if (this == &F) return *this;\n\n   f=F.f; n=F.n; sn=F.sn; posn=F.posn; \n   k3=F.k3; k2=F.k2; k1=F.k1;\n   size=F.size; \n   msk=F.msk; method=F.method; stab=F.stab; h0=F.h0; f0 = F.f0;\n   tracevec=F.tracevec;\n\n   if (method == GF2X_MOD_SPECIAL) {\n      long i;\n      if (!stab1) stab1 = NTL_NEW_OP _ntl_ulong[2*NTL_BITS_PER_LONG];\n      if (!stab1) Error(\"GF2XModulus: out of memory\");\n      for (i = 0; i < 2*NTL_BITS_PER_LONG; i++)\n         stab1[i] = F.stab1[i];\n      if (!stab_cnt) stab_cnt = NTL_NEW_OP long[NTL_BITS_PER_LONG];\n      if (!stab_cnt) Error(\"GF2XModulus: out of memory\");\n      for (i = 0; i < NTL_BITS_PER_LONG; i++)\n         stab_cnt[i] = F.stab_cnt[i];\n   }\n   else if (method == GF2X_MOD_PLAIN) {\n      long i;\n\n      if (F.stab_cnt) {\n         if (!stab_cnt) stab_cnt = NTL_NEW_OP long[NTL_BITS_PER_LONG];\n         if (!stab_cnt) Error(\"GF2XModulus: out of memory\");\n         for (i = 0; i < NTL_BITS_PER_LONG; i++)\n            stab_cnt[i] = F.stab_cnt[i];\n      }\n\n      if (F.stab_ptr) {\n         if (!stab_ptr) stab_ptr = NTL_NEW_OP _ntl_ulong_ptr[NTL_BITS_PER_LONG];\n         if (!stab_ptr) Error(\"GF2XModulus: out of memory\");\n      \n         for (i = 0; i < NTL_BITS_PER_LONG; i++) {\n            WordVector& st = stab[((_ntl_ulong)(posn+i))%NTL_BITS_PER_LONG].xrep;\n            long k = st.length();\n            stab_ptr[((_ntl_ulong)(posn+i))%NTL_BITS_PER_LONG] = &st[k-1];\n            stab_cnt[((_ntl_ulong)(posn+i))%NTL_BITS_PER_LONG] = -k+1;\n         }\n      }\n   }\n\n   return *this;\n}\n   \n\n\nGF2XModulus::~GF2XModulus() \n{ \n   delete [] stab_ptr; \n   delete [] stab_cnt; \n   delete [] stab1; \n}\n\n\n\nGF2XModulus::GF2XModulus(const GF2X& ff)\n{\n   n = -1;\n   method = GF2X_MOD_PLAIN;\n   stab_ptr = 0;\n   stab_cnt = 0;\n   stab1 = 0;\n\n   build(*this, ff);\n}\n\n\n\n\n\nvoid UseMulRem21(GF2X& r, const GF2X& a, const GF2XModulus& F)\n{\n   GF2XRegister(P1);\n   GF2XRegister(P2);\n\n   RightShift(P1, a, F.n);\n   mul(P2, P1, F.h0);\n   RightShift(P2, P2, F.n-2);\n   add(P2, P2, P1);\n   mul(P1, P2, F.f0);\n   trunc(P1, P1, F.n);\n   trunc(r, a, F.n);\n   add(r, r, P1);\n}\n\nvoid UseMulDivRem21(GF2X& q, GF2X& r, const GF2X& a, const GF2XModulus& F)\n{\n   GF2XRegister(P1);\n   GF2XRegister(P2);\n\n   RightShift(P1, a, F.n);\n   mul(P2, P1, F.h0);\n   RightShift(P2, P2, F.n-2);\n   add(P2, P2, P1);\n   mul(P1, P2, F.f0);\n   trunc(P1, P1, F.n);\n   trunc(r, a, F.n);\n   add(r, r, P1);\n   q = P2;\n}\n\nvoid UseMulDiv21(GF2X& q, const GF2X& a, const GF2XModulus& F)\n{\n   GF2XRegister(P1);\n   GF2XRegister(P2);\n\n   RightShift(P1, a, F.n);\n   mul(P2, P1, F.h0);\n   RightShift(P2, P2, F.n-2);\n   add(P2, P2, P1);\n   q = P2;\n}\n\n\nvoid UseMulRemX1(GF2X& r, const GF2X& aa, const GF2XModulus& F)\n{\n   GF2XRegister(buf);\n   GF2XRegister(tmp);\n   GF2XRegister(a);\n\n   clear(buf);\n   a = aa;\n\n   long n = F.n;\n   long a_len = deg(a) + 1;\n\n   while (a_len > 0) {\n      long old_buf_len = deg(buf) + 1;\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      LeftShift(buf, buf, amt);\n      RightShift(tmp, a, a_len-amt);\n      add(buf, buf, tmp);\n      trunc(a, a, a_len-amt);\n\n      UseMulRem21(buf, buf, F);\n      a_len -= amt;\n   }\n\n   r = buf;\n}\n   \n\nvoid UseMulDivRemX1(GF2X& q, GF2X& r, const GF2X& aa, const GF2XModulus& F)\n{\n   GF2XRegister(buf);\n   GF2XRegister(tmp);\n   GF2XRegister(a);\n   GF2XRegister(qq);\n   GF2XRegister(qbuf);\n\n   clear(buf);\n   a = aa;\n   clear(qq);\n\n   long n = F.n;\n   long a_len = deg(a) + 1;\n\n   while (a_len > 0) {\n      long old_buf_len = deg(buf) + 1;\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      LeftShift(buf, buf, amt);\n      RightShift(tmp, a, a_len-amt);\n      add(buf, buf, tmp);\n      trunc(a, a, a_len-amt);\n\n      UseMulDivRem21(qbuf, buf, buf, F);\n      a_len -= amt;\n\n      ShiftAdd(qq, qbuf, a_len);\n   }\n\n   r = buf;\n   q = qq;\n}\n\n\nvoid UseMulDivX1(GF2X& q, const GF2X& aa, const GF2XModulus& F)\n{\n   GF2XRegister(buf);\n   GF2XRegister(tmp);\n   GF2XRegister(a);\n   GF2XRegister(qq);\n   GF2XRegister(qbuf);\n   \n   clear(buf);\n   a = aa;\n   clear(qq);\n\n   long n = F.n;\n   long a_len = deg(a) + 1;\n\n   while (a_len > 0) {\n      long old_buf_len = deg(buf) + 1;\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      LeftShift(buf, buf, amt);\n      RightShift(tmp, a, a_len-amt);\n      add(buf, buf, tmp);\n      trunc(a, a, a_len-amt);\n\n      UseMulDivRem21(qbuf, buf, buf, F);\n      a_len -= amt;\n\n      ShiftAdd(qq, qbuf, a_len);\n   }\n\n   q = qq;\n}\n\nstatic\nvoid TrinomReduce(GF2X& x, const GF2X& a, long n, long k)\n{\n   long wn = n / NTL_BITS_PER_LONG;\n   long bn = n - wn*NTL_BITS_PER_LONG;\n\n   long wdiff = (n-k)/NTL_BITS_PER_LONG;\n   long bdiff = (n-k) - wdiff*NTL_BITS_PER_LONG;\n\n   long m = a.xrep.length()-1;\n\n   if (wn > m) {\n      x = a;\n      return;\n   }\n\n   GF2XRegister(r);\n\n   r = a;\n\n   _ntl_ulong *p = r.xrep.elts();\n\n   _ntl_ulong *pp;\n\n\n   _ntl_ulong w;\n\n   if (bn == 0) {\n      if (bdiff == 0) {\n         // bn == 0 && bdiff == 0\n\n         while (m >= wn) {\n            w = p[m];\n            p[m-wdiff] ^= w;\n            p[m-wn] ^= w;\n            m--;\n         }\n      }\n      else {\n         // bn == 0 && bdiff != 0\n\n         while (m >= wn) {\n            w = p[m];\n            pp = &p[m-wdiff];\n            *pp ^= (w >> bdiff);\n            *(pp-1) ^= (w << (NTL_BITS_PER_LONG-bdiff));\n            p[m-wn] ^= w;\n            m--;\n         }\n      }\n   }\n   else {\n      if (bdiff == 0) {\n         // bn != 0 && bdiff == 0\n\n         while (m > wn) {\n            w = p[m];\n            p[m-wdiff] ^= w;\n            pp = &p[m-wn];\n            *pp ^= (w >> bn);\n            *(pp-1) ^= (w << (NTL_BITS_PER_LONG-bn));\n            m--;\n         }\n\n         w = (p[m] >> bn) << bn;;\n\n         p[m-wdiff] ^= w;\n         p[0] ^= (w >> bn);\n\n         p[m] &= ((1UL<<bn)-1UL); \n      }\n      else {\n         // bn != 0 && bdiff != 0\n\n         while (m > wn) {\n            w = p[m];\n            pp = &p[m-wdiff];\n            *pp ^= (w >> bdiff);;\n            *(pp-1) ^= (w << (NTL_BITS_PER_LONG-bdiff));\n            pp = &p[m-wn];\n            *pp ^= (w >> bn);\n            *(pp-1) ^= (w << (NTL_BITS_PER_LONG-bn));\n            m--;\n         }\n\n         w = (p[m] >> bn) << bn;;\n\n         p[m-wdiff] ^= (w >> bdiff);\n         if (m-wdiff-1 >= 0) p[m-wdiff-1] ^= (w << (NTL_BITS_PER_LONG-bdiff));\n         p[0] ^= (w >> bn);\n         p[m] &= ((1UL<<bn)-1UL); \n      }\n   }\n\n   if (bn == 0)\n      wn--;\n\n   while (wn >= 0 && p[wn] == 0)\n      wn--;\n\n   r.xrep.QuickSetLength(wn+1);\n\n   x = r;\n}\n\nstatic\nvoid PentReduce(GF2X& x, const GF2X& a, long n, long k3, long k2, long k1)\n{\n   long wn = n / NTL_BITS_PER_LONG;\n   long bn = n - wn*NTL_BITS_PER_LONG;\n\n   long m = a.xrep.length()-1;\n\n   if (wn > m) {\n      x = a;\n      return;\n   }\n\n   long wdiff1 = (n-k1)/NTL_BITS_PER_LONG;\n   long bdiff1 = (n-k1) - wdiff1*NTL_BITS_PER_LONG;\n\n   long wdiff2 = (n-k2)/NTL_BITS_PER_LONG;\n   long bdiff2 = (n-k2) - wdiff2*NTL_BITS_PER_LONG;\n\n   long wdiff3 = (n-k3)/NTL_BITS_PER_LONG;\n   long bdiff3 = (n-k3) - wdiff3*NTL_BITS_PER_LONG;\n\n   GF2XRegister(r);\n   r = a;\n\n   _ntl_ulong *p = r.xrep.elts();\n\n   _ntl_ulong *pp;\n\n   _ntl_ulong w;\n\n   while (m > wn) {\n      w = p[m];\n\n      if (bn == 0) \n         p[m-wn] ^= w;\n      else {\n         pp = &p[m-wn];\n         *pp ^= (w >> bn);\n         *(pp-1) ^= (w << (NTL_BITS_PER_LONG-bn));\n      }\n\n      if (bdiff1 == 0) \n         p[m-wdiff1] ^= w;\n      else {\n         pp = &p[m-wdiff1];\n         *pp ^= (w >> bdiff1);\n         *(pp-1) ^= (w << (NTL_BITS_PER_LONG-bdiff1));\n      }\n\n      if (bdiff2 == 0) \n         p[m-wdiff2] ^= w;\n      else {\n         pp = &p[m-wdiff2];\n         *pp ^= (w >> bdiff2);\n         *(pp-1) ^= (w << (NTL_BITS_PER_LONG-bdiff2));\n      }\n\n      if (bdiff3 == 0) \n         p[m-wdiff3] ^= w;\n      else {\n         pp = &p[m-wdiff3];\n         *pp ^= (w >> bdiff3);\n         *(pp-1) ^= (w << (NTL_BITS_PER_LONG-bdiff3));\n      }\n\n      m--;\n   }\n\n   w = (p[m] >> bn) << bn;\n\n   p[0] ^= (w >> bn); \n\n   if (bdiff1 == 0)\n      p[m-wdiff1] ^= w;\n   else {\n      p[m-wdiff1] ^= (w >> bdiff1);\n      if (m-wdiff1-1 >= 0) p[m-wdiff1-1] ^= (w << (NTL_BITS_PER_LONG-bdiff1));\n   }\n\n   if (bdiff2 == 0)\n      p[m-wdiff2] ^= w;\n   else {\n      p[m-wdiff2] ^= (w >> bdiff2);\n      if (m-wdiff2-1 >= 0) p[m-wdiff2-1] ^= (w << (NTL_BITS_PER_LONG-bdiff2));\n   }\n\n   if (bdiff3 == 0)\n      p[m-wdiff3] ^= w;\n   else {\n      p[m-wdiff3] ^= (w >> bdiff3);\n      if (m-wdiff3-1 >= 0) p[m-wdiff3-1] ^= (w << (NTL_BITS_PER_LONG-bdiff3));\n   }\n\n   if (bn != 0)\n      p[m] &= ((1UL<<bn)-1UL);\n\n   \n   if (bn == 0)\n      wn--;\n\n   while (wn >= 0 && p[wn] == 0)\n      wn--;\n\n   r.xrep.QuickSetLength(wn+1);\n\n   x = r;\n}\n\n\n\n\nstatic\nvoid RightShiftAdd(GF2X& c, const GF2X& a, long n)\n{\n   if (n < 0) {\n      Error(\"RightShiftAdd: negative shamt\");\n   }\n\n   if (n == 0) {\n      add(c, c, a);\n      return;\n   }\n\n   long sa = a.xrep.length();\n   long wn = n/NTL_BITS_PER_LONG;\n   long bn = n - wn*NTL_BITS_PER_LONG;\n\n   if (wn >= sa) {\n      return;\n   }\n\n   long sc = c.xrep.length();\n   long i;\n\n   if (sa-wn > sc)\n      c.xrep.SetLength(sa-wn);\n\n   _ntl_ulong *cp = c.xrep.elts();\n   const _ntl_ulong *ap = a.xrep.elts();\n\n   for (i = sc; i < sa-wn; i++)\n      cp[i] = 0;\n\n\n   if (bn == 0) {\n      for (i = 0; i < sa-wn; i++)\n         cp[i] ^= ap[i+wn];\n   }\n   else {\n      for (i = 0; i < sa-wn-1; i++)\n         cp[i] ^= (ap[i+wn] >> bn) | (ap[i+wn+1] << (NTL_BITS_PER_LONG - bn));\n\n      cp[sa-wn-1] ^= ap[sa-1] >> bn;\n   }\n\n   c.normalize();\n}\n\n\nstatic\nvoid TriDiv21(GF2X& q, const GF2X& a, long n, long k)\n{\n   GF2XRegister(P1);\n\n   RightShift(P1, a, n);\n   if (k != 1) \n      RightShiftAdd(P1, P1, n-k);\n\n   q = P1;\n}\n\nstatic \nvoid TriDivRem21(GF2X& q, GF2X& r, const GF2X& a, long n, long k)\n{\n   GF2XRegister(Q);\n   TriDiv21(Q, a, n, k);\n   TrinomReduce(r, a, n, k);\n   q = Q;\n}\n\n\nstatic\nvoid PentDiv21(GF2X& q, const GF2X& a, long n, long k3, long k2, long k1)\n{\n   if (deg(a) < n) {\n      clear(q);\n      return;\n   }\n\n   GF2XRegister(P1);\n   GF2XRegister(P2);\n\n   RightShift(P1, a, n);\n   \n   RightShift(P2, P1, n-k3);\n   RightShiftAdd(P2, P1, n-k2);\n   if (k1 != 1) {\n      RightShiftAdd(P2, P1, n-k1);\n   }\n\n   add(P2, P2, P1);\n\n   q = P2;\n}\n\nstatic \nvoid PentDivRem21(GF2X& q, GF2X& r, const GF2X& a, long n, \n                  long k3, long k2, long k1)\n{\n   GF2XRegister(Q);\n   PentDiv21(Q, a, n, k3, k2, k1);\n   PentReduce(r, a, n, k3, k2, k1);\n   q = Q;\n}\n\nstatic\nvoid TriDivRemX1(GF2X& q, GF2X& r, const GF2X& aa, long n, long k)\n{\n   GF2XRegister(buf);\n   GF2XRegister(tmp);\n   GF2XRegister(a);\n   GF2XRegister(qq);\n   GF2XRegister(qbuf);\n\n   clear(buf);\n   a = aa;\n   clear(qq);\n\n   long a_len = deg(a) + 1;\n\n   while (a_len > 0) {\n      long old_buf_len = deg(buf) + 1;\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      LeftShift(buf, buf, amt);\n      RightShift(tmp, a, a_len-amt);\n      add(buf, buf, tmp);\n      trunc(a, a, a_len-amt);\n\n      TriDivRem21(qbuf, buf, buf, n, k);\n      a_len -= amt;\n\n      ShiftAdd(qq, qbuf, a_len);\n   }\n\n   r = buf;\n   q = qq;\n}\n\n\nstatic\nvoid TriDivX1(GF2X& q, const GF2X& aa, long n, long k)\n{\n   GF2XRegister(buf);\n   GF2XRegister(tmp);\n   GF2XRegister(a);\n   GF2XRegister(qq);\n   GF2XRegister(qbuf);\n   \n   clear(buf);\n   a = aa;\n   clear(qq);\n\n   long a_len = deg(a) + 1;\n\n   while (a_len > 0) {\n      long old_buf_len = deg(buf) + 1;\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      LeftShift(buf, buf, amt);\n      RightShift(tmp, a, a_len-amt);\n      add(buf, buf, tmp);\n      trunc(a, a, a_len-amt);\n\n      TriDivRem21(qbuf, buf, buf, n, k);\n      a_len -= amt;\n\n      ShiftAdd(qq, qbuf, a_len);\n   }\n\n   q = qq;\n}\n\nstatic\nvoid PentDivRemX1(GF2X& q, GF2X& r, const GF2X& aa, long n, \n                  long k3, long k2, long k1)\n{\n   GF2XRegister(buf);\n   GF2XRegister(tmp);\n   GF2XRegister(a);\n   GF2XRegister(qq);\n   GF2XRegister(qbuf);\n\n   clear(buf);\n   a = aa;\n   clear(qq);\n\n   long a_len = deg(a) + 1;\n\n   while (a_len > 0) {\n      long old_buf_len = deg(buf) + 1;\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      LeftShift(buf, buf, amt);\n      RightShift(tmp, a, a_len-amt);\n      add(buf, buf, tmp);\n      trunc(a, a, a_len-amt);\n\n      PentDivRem21(qbuf, buf, buf, n, k3, k2, k1);\n      a_len -= amt;\n\n      ShiftAdd(qq, qbuf, a_len);\n   }\n\n   r = buf;\n   q = qq;\n}\n\n\nstatic\nvoid PentDivX1(GF2X& q, const GF2X& aa, long n, long k3, long k2, long k1)\n{\n   GF2XRegister(buf);\n   GF2XRegister(tmp);\n   GF2XRegister(a);\n   GF2XRegister(qq);\n   GF2XRegister(qbuf);\n   \n   clear(buf);\n   a = aa;\n   clear(qq);\n\n   long a_len = deg(a) + 1;\n\n   while (a_len > 0) {\n      long old_buf_len = deg(buf) + 1;\n      long amt = min(2*n-1-old_buf_len, a_len);\n\n      LeftShift(buf, buf, amt);\n      RightShift(tmp, a, a_len-amt);\n      add(buf, buf, tmp);\n      trunc(a, a, a_len-amt);\n\n      PentDivRem21(qbuf, buf, buf, n, k3, k2, k1);\n      a_len -= amt;\n\n      ShiftAdd(qq, qbuf, a_len);\n   }\n\n   q = qq;\n}\n\n\n\nvoid rem(GF2X& r, const GF2X& a, const GF2XModulus& F)\n{\n   long n = F.n;\n\n   if (n < 0) Error(\"rem: uninitialized modulus\");\n\n   if (F.method == GF2X_MOD_TRI) {\n      TrinomReduce(r, a, n, F.k3);\n      return;\n   }\n\n   if (F.method == GF2X_MOD_PENT) {\n      PentReduce(r, a, n, F.k3, F.k2, F.k1);\n      return;\n   }\n\n   long da = deg(a);\n\n\n   if (da < n) {\n      r = a;\n   }\n   else if (F.method == GF2X_MOD_MUL) {\n      if (da <= 2*(n-1)) \n         UseMulRem21(r, a, F);\n      else\n         UseMulRemX1(r, a, F);\n   }\n   else if (F.method == GF2X_MOD_SPECIAL) {\n      long sa = a.xrep.length();\n      long posa = da - NTL_BITS_PER_LONG*(sa-1);\n   \n      _ntl_ulong *ap;\n      if (&r == &a)\n         ap = r.xrep.elts();\n      else {\n         GF2X_rembuf = a.xrep;\n         ap = GF2X_rembuf.elts();\n      }\n   \n      _ntl_ulong *atop = &ap[sa-1];\n      _ntl_ulong *stab_top;\n   \n      long i;\n   \n      while (1) {\n         if (atop[0] & (1UL << posa)) {\n            stab_top = &F.stab1[posa << 1];\n            i = F.stab_cnt[posa];\n            atop[i] ^= stab_top[0];\n            atop[i+1] ^= stab_top[1];\n         }\n\n         da--;\n         if (da < n) break;\n\n         posa--;\n         if (posa < 0) {\n            posa = NTL_BITS_PER_LONG-1;\n            atop--;\n         }\n      }\n   \n      long sn = F.size;\n      r.xrep.SetLength(sn);\n      if (&r != &a) {\n         _ntl_ulong *rp = r.xrep.elts();\n         for (i = 0; i < sn; i++)\n            rp[i] = ap[i];\n      }\n      r.xrep[sn-1] &= F.msk;\n      r.normalize();\n   }\n   else {\n      long sa = a.xrep.length();\n      long posa = da - NTL_BITS_PER_LONG*(sa-1);\n   \n   \n      _ntl_ulong *ap;\n      if (&r == &a)\n         ap = r.xrep.elts();\n      else {\n         GF2X_rembuf = a.xrep;\n         ap = GF2X_rembuf.elts();\n      }\n   \n      _ntl_ulong *atop = &ap[sa-1];\n      _ntl_ulong *stab_top;\n   \n      long i;\n   \n      while (1) {\n         if (atop[0] & (1UL << posa)) {\n            stab_top = F.stab_ptr[posa];\n            for (i = F.stab_cnt[posa]; i <= 0; i++)\n               atop[i] ^= stab_top[i];\n         }\n   \n         da--;\n         if (da < n) break;\n\n         posa--;\n         if (posa < 0) {\n            posa = NTL_BITS_PER_LONG-1;\n            atop--;\n         }\n      }\n   \n      long sn = F.size;\n      r.xrep.SetLength(sn);\n      if (&r != &a) {\n         _ntl_ulong *rp = r.xrep.elts();\n         for (i = 0; i < sn; i++)\n            rp[i] = ap[i];\n      }\n      r.normalize();\n   }\n\n   GF2X_rembuf.release();\n}\n\nvoid DivRem(GF2X& q, GF2X& r, const GF2X& a, const GF2XModulus& F)\n{\n   long da = deg(a);\n   long n = F.n;\n\n   if (n < 0) Error(\"DivRem: uninitialized modulus\");\n\n   if (da < n) {\n      r = a;\n      clear(q);\n   }\n   else if (F.method == GF2X_MOD_TRI) {\n      if (da <= 2*(n-1)) \n         TriDivRem21(q, r, a, F.n, F.k3);\n      else\n         TriDivRemX1(q, r, a, F.n, F.k3);\n   }\n   else if (F.method == GF2X_MOD_PENT) {\n      if (da <= 2*(n-1)) \n         PentDivRem21(q, r, a, F.n, F.k3, F.k2, F.k1);\n      else\n         PentDivRemX1(q, r, a, F.n, F.k3, F.k2, F.k1);\n   }\n   else if (F.method == GF2X_MOD_MUL) {\n      if (da <= 2*(n-1)) \n         UseMulDivRem21(q, r, a, F);\n      else\n         UseMulDivRemX1(q, r, a, F);\n   }\n   else if (F.method == GF2X_MOD_SPECIAL) {\n      long sa = a.xrep.length();\n      long posa = da - NTL_BITS_PER_LONG*(sa-1);\n   \n      long dq = da - n;\n      long sq = dq/NTL_BITS_PER_LONG + 1;\n      long posq = dq - NTL_BITS_PER_LONG*(sq-1);\n   \n      _ntl_ulong *ap;\n      if (&r == &a)\n         ap = r.xrep.elts();\n      else {\n         GF2X_rembuf = a.xrep;\n         ap = GF2X_rembuf.elts();\n      }\n   \n      _ntl_ulong *atop = &ap[sa-1];\n      _ntl_ulong *stab_top;\n\n      long i;\n\n      q.xrep.SetLength(sq);\n      _ntl_ulong *qp = q.xrep.elts();\n      for (i = 0; i < sq; i++)\n         qp[i] = 0;\n\n      _ntl_ulong *qtop = &qp[sq-1];\n\n   \n      while (1) {\n         if (atop[0] & (1UL << posa)) {\n            qtop[0] |= (1UL << posq);\n            stab_top = &F.stab1[posa << 1];\n            i = F.stab_cnt[posa];\n            atop[i] ^= stab_top[0];\n            atop[i+1] ^= stab_top[1];\n         }\n   \n         da--;\n         if (da < n) break;\n\n         posa--;\n         if (posa < 0) {\n            posa = NTL_BITS_PER_LONG-1;\n            atop--;\n         }\n\n         posq--;\n         if (posq < 0) {\n            posq = NTL_BITS_PER_LONG-1;\n            qtop--;\n         }\n      }\n   \n      long sn = F.size;\n      r.xrep.SetLength(sn);\n      if (&r != &a) {\n         _ntl_ulong *rp = r.xrep.elts();\n         for (i = 0; i < sn; i++)\n            rp[i] = ap[i];\n      }\n      r.xrep[sn-1] &= F.msk;\n      r.normalize();\n   }\n   else {\n      long sa = a.xrep.length();\n      long posa = da - NTL_BITS_PER_LONG*(sa-1);\n   \n      long dq = da - n;\n      long sq = dq/NTL_BITS_PER_LONG + 1;\n      long posq = dq - NTL_BITS_PER_LONG*(sq-1);\n   \n      _ntl_ulong *ap;\n      if (&r == &a)\n         ap = r.xrep.elts();\n      else {\n         GF2X_rembuf = a.xrep;\n         ap = GF2X_rembuf.elts();\n      }\n   \n      _ntl_ulong *atop = &ap[sa-1];\n      _ntl_ulong *stab_top;\n   \n      long i;\n\n      q.xrep.SetLength(sq);\n      _ntl_ulong *qp = q.xrep.elts();\n      for (i = 0; i < sq; i++)\n         qp[i] = 0;\n\n      _ntl_ulong *qtop = &qp[sq-1];\n   \n      while (1) {\n         if (atop[0] & (1UL << posa)) {\n            qtop[0] |= (1UL << posq);\n            stab_top = F.stab_ptr[posa];\n            for (i = F.stab_cnt[posa]; i <= 0; i++)\n               atop[i] ^= stab_top[i];\n         }\n   \n         da--;\n         if (da < n) break;\n\n         posa--;\n         if (posa < 0) {\n            posa = NTL_BITS_PER_LONG-1;\n            atop--;\n         }\n\n         posq--;\n         if (posq < 0) {\n            posq = NTL_BITS_PER_LONG-1;\n            qtop--;\n         }\n      }\n   \n      long sn = F.size;\n      r.xrep.SetLength(sn);\n      if (&r != &a) {\n         _ntl_ulong *rp = r.xrep.elts();\n         for (i = 0; i < sn; i++)\n            rp[i] = ap[i];\n      }\n      r.normalize();\n   }\n\n   GF2X_rembuf.release();\n}\n\n\n\nvoid div(GF2X& q, const GF2X& a, const GF2XModulus& F)\n{\n   long da = deg(a);\n   long n = F.n;\n\n   if (n < 0) Error(\"div: uninitialized modulus\");\n\n\n   if (da < n) {\n      clear(q);\n   }\n   else if (F.method == GF2X_MOD_TRI) {\n      if (da <= 2*(n-1)) \n         TriDiv21(q, a, F.n, F.k3);\n      else\n         TriDivX1(q, a, F.n, F.k3);\n   }\n   else if (F.method == GF2X_MOD_PENT) {\n      if (da <= 2*(n-1)) \n         PentDiv21(q, a, F.n, F.k3, F.k2, F.k1);\n      else\n         PentDivX1(q, a, F.n, F.k3, F.k2, F.k1);\n   }\n   else if (F.method == GF2X_MOD_MUL) {\n      if (da <= 2*(n-1)) \n         UseMulDiv21(q, a, F);\n      else\n         UseMulDivX1(q, a, F);\n   }\n   else if (F.method == GF2X_MOD_SPECIAL) {\n      long sa = a.xrep.length();\n      long posa = da - NTL_BITS_PER_LONG*(sa-1);\n   \n      long dq = da - n;\n      long sq = dq/NTL_BITS_PER_LONG + 1;\n      long posq = dq - NTL_BITS_PER_LONG*(sq-1);\n   \n      _ntl_ulong *ap;\n      GF2X_rembuf = a.xrep;\n      ap = GF2X_rembuf.elts();\n\n   \n      _ntl_ulong *atop = &ap[sa-1];\n      _ntl_ulong *stab_top;\n\n      long i;\n\n      q.xrep.SetLength(sq);\n      _ntl_ulong *qp = q.xrep.elts();\n      for (i = 0; i < sq; i++)\n         qp[i] = 0;\n\n      _ntl_ulong *qtop = &qp[sq-1];\n   \n      while (1) {\n         if (atop[0] & (1UL << posa)) {\n            qtop[0] |= (1UL << posq);\n            stab_top = &F.stab1[posa << 1];\n            i = F.stab_cnt[posa];\n            atop[i] ^= stab_top[0];\n            atop[i+1] ^= stab_top[1];\n         }\n   \n         da--;\n         if (da < n) break;\n\n         posa--;\n         if (posa < 0) {\n            posa = NTL_BITS_PER_LONG-1;\n            atop--;\n         }\n\n         posq--;\n         if (posq < 0) {\n            posq = NTL_BITS_PER_LONG-1;\n            qtop--;\n         }\n      }\n   }\n   else {\n      long sa = a.xrep.length();\n      long posa = da - NTL_BITS_PER_LONG*(sa-1);\n   \n      long dq = da - n;\n      long sq = dq/NTL_BITS_PER_LONG + 1;\n      long posq = dq - NTL_BITS_PER_LONG*(sq-1);\n   \n      _ntl_ulong *ap;\n      GF2X_rembuf = a.xrep;\n      ap = GF2X_rembuf.elts();\n   \n      _ntl_ulong *atop = &ap[sa-1];\n      _ntl_ulong *stab_top;\n   \n      long i;\n\n      q.xrep.SetLength(sq);\n      _ntl_ulong *qp = q.xrep.elts();\n      for (i = 0; i < sq; i++)\n         qp[i] = 0;\n\n      _ntl_ulong *qtop = &qp[sq-1];\n   \n      while (1) {\n         if (atop[0] & (1UL << posa)) {\n            qtop[0] |= (1UL << posq);\n            stab_top = F.stab_ptr[posa];\n            for (i = F.stab_cnt[posa]; i <= 0; i++)\n               atop[i] ^= stab_top[i];\n         }\n   \n         da--;\n         if (da < n) break;\n\n         posa--;\n         if (posa < 0) {\n            posa = NTL_BITS_PER_LONG-1;\n            atop--;\n         }\n\n         posq--;\n         if (posq < 0) {\n            posq = NTL_BITS_PER_LONG-1;\n            qtop--;\n         }\n      }\n   }\n\n   GF2X_rembuf.release();\n}\n\n\nvoid MulMod(GF2X& c, const GF2X& a, const GF2X& b, const GF2XModulus& F)\n{\n   if (F.n < 0) Error(\"MulMod: uninitialized modulus\");\n\n   GF2XRegister(t);\n   mul(t, a, b);\n   rem(c, t, F);\n}\n\n\nvoid SqrMod(GF2X& c, const GF2X& a, const GF2XModulus& F)\n{\n   if (F.n < 0) Error(\"SqrMod: uninitialized modulus\");\n\n   GF2XRegister(t);\n   sqr(t, a);\n   rem(c, t, F);\n}\n\n\n// we need these two versions to prevent a GF2XModulus\n// from being constructed.\n\n\nvoid MulMod(GF2X& c, const GF2X& a, const GF2X& b, const GF2X& f)\n{\n   GF2XRegister(t);\n   mul(t, a, b);\n   rem(c, t, f);\n}\n\nvoid SqrMod(GF2X& c, const GF2X& a, const GF2X& f)\n{\n   GF2XRegister(t);\n   sqr(t, a);\n   rem(c, t, f);\n}\n\n\nstatic\nlong OptWinSize(long n)\n// finds k that minimizes n/(k+1) + 2^{k-1}\n\n{\n   long k;\n   double v, v_new;\n\n\n   v = n/2.0 + 1.0;\n   k = 1;\n\n   for (;;) {\n      v_new = n/(double(k+2)) + double(1L << k);\n      if (v_new >= v) break;\n      v = v_new;\n      k++;\n   }\n\n   return k;\n}\n      \n\n\nvoid PowerMod(GF2X& h, const GF2X& g, const ZZ& e, const GF2XModulus& F)\n// h = g^e mod f using \"sliding window\" algorithm\n{\n   if (deg(g) >= F.n) Error(\"PowerMod: bad args\");\n\n   if (e == 0) {\n      set(h);\n      return;\n   }\n\n   if (e == 1) {\n      h = g;\n      return;\n   }\n\n   if (e == -1) {\n      InvMod(h, g, F);\n      return;\n   }\n\n   if (e == 2) {\n      SqrMod(h, g, F);\n      return;\n   }\n\n   if (e == -2) {\n      SqrMod(h, g, F);\n      InvMod(h, h, F);\n      return;\n   }\n\n\n   long n = NumBits(e);\n\n   GF2X res;\n   res.SetMaxLength(F.n);\n   set(res);\n\n   long i;\n\n   if (n < 16) {\n      // plain square-and-multiply algorithm\n\n      for (i = n - 1; i >= 0; i--) {\n         SqrMod(res, res, F);\n         if (bit(e, i))\n            MulMod(res, res, g, F);\n      }\n\n      if (e < 0) InvMod(res, res, F);\n\n      h = res;\n      return;\n   }\n\n   long k = OptWinSize(n);\n\n   k = min(k, 9);\n\n   vec_GF2X v;\n\n   v.SetLength(1L << (k-1));\n\n   v[0] = g;\n \n   if (k > 1) {\n      GF2X t;\n      SqrMod(t, g, F);\n\n      for (i = 1; i < (1L << (k-1)); i++)\n         MulMod(v[i], v[i-1], t, F);\n   }\n\n\n   long val;\n   long cnt;\n   long m;\n\n   val = 0;\n   for (i = n-1; i >= 0; i--) {\n      val = (val << 1) | bit(e, i); \n      if (val == 0)\n         SqrMod(res, res, F);\n      else if (val >= (1L << (k-1)) || i == 0) {\n         cnt = 0;\n         while ((val & 1) == 0) {\n            val = val >> 1;\n            cnt++;\n         }\n\n         m = val;\n         while (m > 0) {\n            SqrMod(res, res, F);\n            m = m >> 1;\n         }\n\n         MulMod(res, res, v[val >> 1], F);\n\n         while (cnt > 0) {\n            SqrMod(res, res, F);\n            cnt--;\n         }\n\n         val = 0;\n      }\n   }\n\n   if (e < 0) InvMod(res, res, F);\n\n   h = res;\n}\n\n   \n\n\nvoid PowerXMod(GF2X& hh, const ZZ& e, const GF2XModulus& F)\n{\n   if (F.n < 0) Error(\"PowerXMod: uninitialized modulus\");\n\n   if (IsZero(e)) {\n      set(hh);\n      return;\n   }\n\n   long n = NumBits(e);\n   long i;\n\n   GF2X h;\n\n   h.SetMaxLength(F.n+1);\n   set(h);\n\n   for (i = n - 1; i >= 0; i--) {\n      SqrMod(h, h, F);\n      if (bit(e, i)) {\n         MulByX(h, h);\n         if (coeff(h, F.n) != 0)\n            add(h, h, F.f);\n      }\n   }\n\n   if (e < 0) InvMod(h, h, F);\n\n   hh = h;\n}\n\n\n      \n\n\nvoid UseMulRem(GF2X& r, const GF2X& a, const GF2X& b)\n{\n   GF2XRegister(P1);\n   GF2XRegister(P2);\n\n   long da = deg(a);\n   long db = deg(b);\n\n   CopyReverse(P1, b, db);\n   InvTrunc(P2, P1, da-db+1);\n   CopyReverse(P1, P2, da-db);\n\n   RightShift(P2, a, db);\n   mul(P2, P1, P2);\n   RightShift(P2, P2, da-db);\n   mul(P1, P2, b);\n   add(P1, P1, a);\n   \n   r = P1;\n}\n\nvoid UseMulDivRem(GF2X& q, GF2X& r, const GF2X& a, const GF2X& b)\n{\n   GF2XRegister(P1);\n   GF2XRegister(P2);\n\n   long da = deg(a);\n   long db = deg(b);\n\n   CopyReverse(P1, b, db);\n   InvTrunc(P2, P1, da-db+1);\n   CopyReverse(P1, P2, da-db);\n\n   RightShift(P2, a, db);\n   mul(P2, P1, P2);\n   RightShift(P2, P2, da-db);\n   mul(P1, P2, b);\n   add(P1, P1, a);\n   \n   r = P1;\n   q = P2;\n}\n\nvoid UseMulDiv(GF2X& q, const GF2X& a, const GF2X& b)\n{\n   GF2XRegister(P1);\n   GF2XRegister(P2);\n\n   long da = deg(a);\n   long db = deg(b);\n\n   CopyReverse(P1, b, db);\n   InvTrunc(P2, P1, da-db+1);\n   CopyReverse(P1, P2, da-db);\n\n   RightShift(P2, a, db);\n   mul(P2, P1, P2);\n   RightShift(P2, P2, da-db);\n   \n   q = P2;\n}\n\n\nconst long GF2X_DIV_CROSS = 100; \n\nvoid DivRem(GF2X& q, GF2X& r, const GF2X& a, const GF2X& b)\n{\n   long sa = a.xrep.length();\n   long sb = b.xrep.length();\n\n   if (sb < GF2X_DIV_CROSS || sa-sb < GF2X_DIV_CROSS)\n      PlainDivRem(q, r, a, b);\n   else if (sa < 4*sb)\n      UseMulDivRem(q, r, a, b);\n   else {\n      GF2XModulus B;\n      build(B, b);\n      DivRem(q, r, a, B);\n   }\n}\n\nvoid div(GF2X& q, const GF2X& a, const GF2X& b)\n{\n   long sa = a.xrep.length();\n   long sb = b.xrep.length();\n\n   if (sb < GF2X_DIV_CROSS || sa-sb < GF2X_DIV_CROSS)\n      PlainDiv(q, a, b);\n   else if (sa < 4*sb)\n      UseMulDiv(q, a, b);\n   else {\n      GF2XModulus B;\n      build(B, b);\n      div(q, a, B);\n   }\n}\n\nvoid rem(GF2X& r, const GF2X& a, const GF2X& b)\n{\n   long sa = a.xrep.length();\n   long sb = b.xrep.length();\n\n   if (sb < GF2X_DIV_CROSS || sa-sb < GF2X_DIV_CROSS)\n      PlainRem(r, a, b);\n   else if (sa < 4*sb)\n      UseMulRem(r, a, b);\n   else {\n      GF2XModulus B;\n      build(B, b);\n      rem(r, a, B);\n   }\n}\n\n\nstatic inline \nvoid swap(_ntl_ulong_ptr& a, _ntl_ulong_ptr& b)  \n{  _ntl_ulong_ptr t;  t = a; a = b; b = t; }\n\n\n\n\nstatic\nvoid BaseGCD(GF2X& d, const GF2X& a_in, const GF2X& b_in)\n{\n   GF2XRegister(a);\n   GF2XRegister(b);\n   \n   if (IsZero(a_in)) {\n      d = b_in;\n      return;\n   }\n\n   if (IsZero(b_in)) {\n      d = a_in;\n      return;\n   }\n      \n   a.xrep.SetMaxLength(a_in.xrep.length()+1);\n   b.xrep.SetMaxLength(b_in.xrep.length()+1);\n\n   a = a_in;\n   b = b_in;\n\n   _ntl_ulong *ap = a.xrep.elts();\n   _ntl_ulong *bp = b.xrep.elts();\n\n   long da = deg(a);\n   long wa = da/NTL_BITS_PER_LONG;\n   long ba = da - wa*NTL_BITS_PER_LONG;\n\n   long db = deg(b);\n   long wb = db/NTL_BITS_PER_LONG;\n   long bb = db - wb*NTL_BITS_PER_LONG;\n\n   long parity = 0;\n\n   for (;;) {\n      if (da < db) {\n         swap(ap, bp);\n         swap(da, db);\n         swap(wa, wb);\n         swap(ba, bb);\n         parity = 1 - parity;\n      }\n\n      // da >= db\n\n      if (db == -1) break;\n\n      ShiftAdd(ap, bp, wb+1, da-db);\n\n      _ntl_ulong msk = 1UL << ba;\n      _ntl_ulong aa = ap[wa];\n\n      while ((aa & msk) == 0) {\n         da--;\n         msk = msk >> 1;\n         ba--;\n         if (!msk) {\n            wa--;\n            ba = NTL_BITS_PER_LONG-1;\n            msk = 1UL << (NTL_BITS_PER_LONG-1);\n            if (wa < 0) break;\n            aa = ap[wa];\n         }\n      }\n   }\n\n   a.normalize();\n   b.normalize();\n\n   if (!parity) {\n      d = a;\n   }\n   else {\n      d = b;\n   }\n}\n\n\nvoid OldGCD(GF2X& d, const GF2X& a, const GF2X& b)\n{\n   long sa = a.xrep.length();\n   long sb = b.xrep.length();\n\n   if (sb >= 10 && 2*sa > 3*sb) {\n      GF2XRegister(r);\n\n      rem(r, a, b);\n      BaseGCD(d, b, r);\n   }\n   else if (sa >= 10 && 2*sb > 3*sa) {\n      GF2XRegister(r);\n\n      rem(r, b, a);\n      BaseGCD(d, a, r);\n   }\n   else {\n      BaseGCD(d, a, b);\n   }\n}\n\n\n\n\n\n#define XX_STEP(ap,da,wa,ba,rp,sr,bp,db,wb,bb,sp,ss)  \\\n      long delta = da-db;  \\\n  \\\n      if (delta == 0) {  \\\n         long i;  \\\n         for (i = wb; i >= 0; i--) ap[i] ^= bp[i];  \\\n         for (i = ss-1; i >= 0; i--) rp[i] ^= sp[i];  \\\n         if (ss > sr) sr = ss; \\\n      }  \\\n      else if (delta == 1) {  \\\n         long i; \\\n         _ntl_ulong tt, tt1;  \\\n  \\\n         tt = bp[wb] >> (NTL_BITS_PER_LONG-1);  \\\n         if (tt) ap[wb+1] ^= tt;  \\\n         tt = bp[wb];  \\\n         for (i = wb; i >= 1; i--)  \\\n            tt1 = bp[i-1], ap[i] ^= (tt << 1) | (tt1 >> (NTL_BITS_PER_LONG-1)),  \\\n            tt = tt1; \\\n         ap[0] ^= tt << 1;  \\\n  \\\n         if (ss > 0) {  \\\n            long t = ss; \\\n            tt = sp[ss-1] >> (NTL_BITS_PER_LONG-1);  \\\n            if (tt) rp[ss] ^= tt, t++;  \\\n            tt = sp[ss-1]; \\\n            for (i = ss-1; i >= 1; i--)  \\\n               tt1=sp[i-1],  \\\n               rp[i] ^= (tt << 1) | (tt1 >> (NTL_BITS_PER_LONG-1)),  \\\n               tt = tt1; \\\n            rp[0] ^= tt << 1;  \\\n            if (t > sr) sr = t; \\\n         }  \\\n      }  \\\n      else if (delta < NTL_BITS_PER_LONG) {  \\\n         long i; \\\n         _ntl_ulong tt, tt1;  \\\n         long rdelta = NTL_BITS_PER_LONG-delta; \\\n  \\\n         tt = bp[wb] >> rdelta;  \\\n         if (tt) ap[wb+1] ^= tt;  \\\n         tt=bp[wb]; \\\n         for (i = wb; i >= 1; i--)  \\\n            tt1=bp[i-1], ap[i] ^= (tt << delta) | (tt1 >> rdelta),  \\\n            tt=tt1; \\\n         ap[0] ^= tt << delta;  \\\n  \\\n         if (ss > 0) {  \\\n            long t = ss; \\\n            tt = sp[ss-1] >> rdelta;  \\\n            if (tt) rp[ss] ^= tt, t++;  \\\n            tt=sp[ss-1]; \\\n            for (i = ss-1; i >= 1; i--)  \\\n               tt1=sp[i-1], rp[i] ^= (tt << delta) | (tt1 >> rdelta),  \\\n               tt=tt1; \\\n            rp[0] ^= tt << delta;  \\\n            if (t > sr) sr = t; \\\n         }  \\\n      }  \\\n      else {  \\\n         ShiftAdd(ap, bp, wb+1, da-db);  \\\n         ShiftAdd(rp, sp, ss, da-db);  \\\n         long t = ss + (da-db+NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG;  \\\n         if (t > sr) {  \\\n            while (t > 0 && rp[t-1] == 0) t--;   \\\n            sr = t;  \\\n         }  \\\n      } \\\n  \\\n      _ntl_ulong msk = 1UL << ba;  \\\n      _ntl_ulong aa = ap[wa];  \\\n  \\\n      while ((aa & msk) == 0) {  \\\n         da--;  \\\n         msk = msk >> 1;  \\\n         ba--;  \\\n         if (!msk) {  \\\n            wa--;  \\\n            ba = NTL_BITS_PER_LONG-1;  \\\n            msk = 1UL << (NTL_BITS_PER_LONG-1);  \\\n            if (wa < 0) break;  \\\n            aa = ap[wa];  \\\n         }  \\\n      }  \\\n\n\n\n\nstatic\nvoid XXGCD(GF2X& d, GF2X& r_out, const GF2X& a_in, const GF2X& b_in)\n{\n   GF2XRegister(a);\n   GF2XRegister(b);\n   GF2XRegister(r);\n   GF2XRegister(s);\n\n   if (IsZero(b_in)) {\n      d = a_in;\n      set(r_out);\n      return;\n   }\n\n   if (IsZero(a_in)) {\n      d = b_in;\n      clear(r_out);\n      return;\n   }\n      \n   a.xrep.SetMaxLength(a_in.xrep.length()+1);\n   b.xrep.SetMaxLength(b_in.xrep.length()+1);\n\n   long max_sz = max(a_in.xrep.length(), b_in.xrep.length());\n   r.xrep.SetLength(max_sz+1);\n   s.xrep.SetLength(max_sz+1);\n\n   _ntl_ulong *rp = r.xrep.elts();\n   _ntl_ulong *sp = s.xrep.elts();\n\n   long i;\n   for (i = 0; i <= max_sz; i++) {\n      rp[i] = sp[i] = 0;\n   }\n\n   rp[0] = 1;\n\n   long sr = 1;\n   long ss = 0;\n\n   a = a_in;\n   b = b_in;\n\n   _ntl_ulong *ap = a.xrep.elts();\n   _ntl_ulong *bp = b.xrep.elts();\n\n   long da = deg(a);\n   long wa = da/NTL_BITS_PER_LONG;\n   long ba = da - wa*NTL_BITS_PER_LONG;\n\n   long db = deg(b);\n   long wb = db/NTL_BITS_PER_LONG;\n   long bb = db - wb*NTL_BITS_PER_LONG;\n\n   long parity = 0;\n\n\n   for (;;) {\n      if (da == -1 || db == -1) break;\n\n      if (da < db || (da == db && parity)) {\n         if (da < db && !parity) parity = 1;\n         XX_STEP(bp,db,wb,bb,sp,ss,ap,da,wa,ba,rp,sr)\n\n      }\n      else {\n         parity = 0;\n         XX_STEP(ap,da,wa,ba,rp,sr,bp,db,wb,bb,sp,ss)\n      }\n   }\n\n   a.normalize();\n   b.normalize();\n   r.normalize();\n   s.normalize();\n\n   if (db == -1) {\n      d = a;\n      r_out = r;\n   }\n   else {\n      d = b;\n      r_out = s;\n   }\n}\n\n\n\nstatic\nvoid BaseXGCD(GF2X& d, GF2X& s, GF2X& t, const GF2X& a, const GF2X& b)\n{\n   if (IsZero(b)) {\n      d = a;\n      set(s);\n      clear(t);\n   }\n   else {\n      GF2XRegister(t1);\n      GF2XRegister(b1);\n\n      b1 = b;\n      XXGCD(d, s, a, b);\n      mul(t1, a, s);\n      add(t1, t1, d);\n      div(t, t1, b1);\n   }\n}\n\n\n\n\nvoid OldXGCD(GF2X& d, GF2X& s, GF2X& t, const GF2X& a, const GF2X& b)\n{\n   long sa = a.xrep.length();\n   long sb = b.xrep.length();\n\n\n   if (sb >= 10 && 2*sa > 3*sb) {\n      GF2XRegister(r);\n      GF2XRegister(q);\n      GF2XRegister(s1);\n      GF2XRegister(t1);\n\n\n      DivRem(q, r, a, b);\n      BaseXGCD(d, s1, t1, b, r);\n\n      \n      mul(r, t1, q);\n      add(r, r, s1);  // r = s1 - t1*q, but sign doesn't matter\n\n      s = t1;\n      t = r;   \n   }\n   else if (sa >= 10 && 2*sb > 3*sa) {\n      GF2XRegister(r);\n      GF2XRegister(q);\n      GF2XRegister(s1);\n      GF2XRegister(t1);\n\n\n      DivRem(q, r, b, a);\n      BaseXGCD(d, s1, t1, a, r);\n\n      \n      mul(r, t1, q);\n      add(r, r, s1);  // r = s1 - t1*q, but sign doesn't matter\n\n      t = t1;\n      s = r;  \n   }\n   else {\n      BaseXGCD(d, s, t, a, b);\n   }\n\n}\n\n\n\n\nstatic\nvoid BaseInvMod(GF2X& d, GF2X& s, const GF2X& a, const GF2X& f)\n{\n   if (deg(a) >= deg(f) || deg(f) == 0) Error(\"InvMod: bad args\");\n\n   long sa = a.xrep.length();\n   long sf = f.xrep.length();\n\n   if ((sa >= 10 && 2*sf > 3*sa) || \n       sf > NTL_GF2X_GCD_CROSSOVER/NTL_BITS_PER_LONG) {\n      GF2XRegister(t);\n\n      XGCD(d, s, t, a, f);\n   }\n   else {\n      XXGCD(d, s, a, f);\n   }\n\n}\n\n\n\nvoid InvMod(GF2X& c, const GF2X& a, const GF2X& f)\n{ \n   GF2XRegister(d);\n   GF2XRegister(s);\n   BaseInvMod(d, s, a, f);\n\n   if (!IsOne(d)) Error(\"InvMod: inverse undefined\");\n\n   c = s;\n}\n\n\n\nlong InvModStatus(GF2X& c, const GF2X& a, const GF2X& f)\n{ \n   GF2XRegister(d);\n   GF2XRegister(s);\n   BaseInvMod(d, s, a, f);\n\n   if (!IsOne(d)) {\n      c = d;\n      return 1;\n   }\n\n   c = s;\n   return 0;\n}\n\n\n\n   \nvoid diff(GF2X& c, const GF2X& a)\n{\n   RightShift(c, a, 1);\n   \n   // clear odd coeffs\n\n   long dc = deg(c);\n   long i;\n   for (i = 1; i <= dc; i += 2)\n      SetCoeff(c, i, 0);\n}\n\nvoid conv(GF2X& c, long a)\n{\n   if (a & 1)\n      set(c);\n   else\n      clear(c);\n}\n\nvoid conv(GF2X& c, GF2 a)\n{\n   if (a == 1)\n      set(c);\n   else\n      clear(c);\n}\n\nvoid conv(GF2X& x, const vec_GF2& a)\n{\n   x.xrep = a.rep;\n   x.normalize();\n}\n\nvoid conv(vec_GF2& x, const GF2X& a)\n{\n   VectorCopy(x, a, deg(a)+1);\n}\n\nvoid VectorCopy(vec_GF2& x, const GF2X& a, long n)\n{\n   if (n < 0) Error(\"VectorCopy: negative length\"); \n\n   if (NTL_OVERFLOW(n, 1, 0))\n      Error(\"overflow in VectorCopy\");\n\n   long wa = a.xrep.length();\n   long wx = (n + NTL_BITS_PER_LONG - 1)/NTL_BITS_PER_LONG;\n\n   long wmin = min(wa, wx);\n\n   x.SetLength(n);\n\n   const _ntl_ulong *ap = a.xrep.elts();\n   _ntl_ulong *xp = x.rep.elts();\n\n   long i;\n   for (i = 0; i < wmin; i++)\n      xp[i] = ap[i];\n\n   if (wa < wx) {\n      for (i = wa; i < wx; i++)\n         xp[i] = 0;\n   }\n   else {\n      long p = n % NTL_BITS_PER_LONG;\n      if (p != 0)\n         xp[wx-1] &= (1UL << p) - 1UL;\n   }\n}\n\n\nvoid add(GF2X& c, const GF2X& a, long b)\n{\n   c = a;\n   if (b & 1) {\n      long n = c.xrep.length();\n      if (n == 0) \n         set(c);\n      else {\n         c.xrep[0] ^= 1;\n         if (n == 1 && !c.xrep[0]) c.xrep.SetLength(0);\n      }\n   }\n}\n\nvoid add(GF2X& c, const GF2X& a, GF2 b)\n{\n   add(c, a, rep(b));\n}\n\n\nvoid MulTrunc(GF2X& c, const GF2X& a, const GF2X& b, long n)\n{\n   GF2XRegister(t);\n\n   mul(t, a, b);\n   trunc(c, t, n);\n}\n\nvoid SqrTrunc(GF2X& c, const GF2X& a, long n)\n{\n   GF2XRegister(t);\n\n   sqr(t, a);\n   trunc(c, t, n);\n}\n\n\nlong divide(GF2X& q, const GF2X& a, const GF2X& b)\n{\n   if (IsZero(b)) {\n      if (IsZero(a)) {\n         clear(q);\n         return 1;\n      }\n      else\n         return 0;\n   }\n\n   GF2XRegister(lq);\n   GF2XRegister(r);\n\n   DivRem(lq, r, a, b);\n   if (!IsZero(r)) return 0;\n   q = lq;\n   return 1;\n}\n\nlong divide(const GF2X& a, const GF2X& b)\n{\n   if (IsZero(b)) return IsZero(a);\n   GF2XRegister(r);\n   rem(r, a, b);\n   if (!IsZero(r)) return 0;\n   return 1;\n}\n\n\n\n/*** modular composition routines and data structures ***/\n\n\nvoid InnerProduct(GF2X& x, const GF2X& v, long dv, long low, long high, \n                   const vec_GF2X& H, long n, WordVector& t)\n{\n   long i, j;\n\n   _ntl_ulong *tp = t.elts();\n\n   for (i = 0; i < n; i++)\n      tp[i] = 0;\n\n\n   long w_low = low/NTL_BITS_PER_LONG;\n   long b_low = low - w_low*NTL_BITS_PER_LONG;\n\n   \n   const _ntl_ulong *vp = &v.xrep[w_low];\n   _ntl_ulong msk = 1UL << b_low;\n   _ntl_ulong vv = *vp;\n\n   high = min(high, dv);\n\n   i = low;\n   for (;;) {\n      if (vv & msk) {\n         const WordVector& h = H[i-low].xrep;\n         long m = h.length();\n         const _ntl_ulong *hp = h.elts();\n         for (j = 0; j < m; j++)\n            tp[j] ^= hp[j];\n      }\n\n      i++;\n      if (i > high) break;\n\n      msk = msk << 1;\n      if (!msk) {\n         msk = 1UL;\n         vp++;\n         vv = *vp;\n      }\n   }\n\n   x.xrep = t;\n   x.normalize();\n}\n\n\nvoid CompMod(GF2X& x, const GF2X& g, const GF2XArgument& A, const GF2XModulus& F)\n{\n   long dg = deg(g);\n   if (dg <= 0) {\n      x = g;\n      return;\n   }\n\n   GF2X s, t;\n   WordVector scratch(INIT_SIZE, F.size);\n\n   long m = A.H.length() - 1;\n   long l = (((dg+1)+m-1)/m) - 1;\n\n   InnerProduct(t, g, dg, l*m, l*m + m - 1, A.H, F.size, scratch);\n   for (long i = l-1; i >= 0; i--) {\n      InnerProduct(s, g, dg, i*m, i*m + m - 1, A.H, F.size, scratch);\n      MulMod(t, t, A.H[m], F);\n      add(t, t, s);\n   }\n\n   x = t;\n}\n\nvoid build(GF2XArgument& A, const GF2X& h, const GF2XModulus& F, long m)\n{\n   if (m <= 0 || deg(h) >= F.n) Error(\"build GF2XArgument: bad args\");\n\n   if (m > F.n) m = F.n;\n\n   long i;\n\n   A.H.SetLength(m+1);\n\n   set(A.H[0]);\n   A.H[1] = h;\n   for (i = 2; i <= m; i++) \n      MulMod(A.H[i], A.H[i-1], h, F);\n}\n\n\nvoid CompMod(GF2X& x, const GF2X& g, const GF2X& h, const GF2XModulus& F)\n   // x = g(h) mod f\n{\n   long m = SqrRoot(deg(g)+1);\n\n   if (m == 0) {\n      clear(x);\n      return;\n   }\n\n   GF2XArgument A;\n\n   build(A, h, F, m);\n\n   CompMod(x, g, A, F);\n}\n\n\n\n\nvoid Comp2Mod(GF2X& x1, GF2X& x2, const GF2X& g1, const GF2X& g2,\n              const GF2X& h, const GF2XModulus& F)\n\n{\n   long m = SqrRoot(deg(g1) + deg(g2) + 2);\n\n   if (m == 0) {\n      clear(x1);\n      clear(x2);\n      return;\n   }\n\n   GF2XArgument A;\n\n   build(A, h, F, m);\n\n   GF2X xx1, xx2;\n\n   CompMod(xx1, g1, A, F);\n   CompMod(xx2, g2, A, F);\n\n   x1 = xx1;\n   x2 = xx2;\n}\n\nvoid Comp3Mod(GF2X& x1, GF2X& x2, GF2X& x3, \n              const GF2X& g1, const GF2X& g2, const GF2X& g3,\n              const GF2X& h, const GF2XModulus& F)\n\n{\n   long m = SqrRoot(deg(g1) + deg(g2) + deg(g3) + 3);\n\n   if (m == 0) {\n      clear(x1);\n      clear(x2);\n      clear(x3);\n      return;\n   }\n\n   GF2XArgument A;\n\n   build(A, h, F, m);\n\n   GF2X xx1, xx2, xx3;\n\n   CompMod(xx1, g1, A, F);\n   CompMod(xx2, g2, A, F);\n   CompMod(xx3, g3, A, F);\n\n   x1 = xx1;\n   x2 = xx2;\n   x3 = xx3;\n}\n\n\n\nvoid build(GF2XTransMultiplier& B, const GF2X& b, const GF2XModulus& F)\n{\n   long db = deg(b);\n\n   if (db >= F.n) Error(\"build TransMultiplier: bad args\");\n\n   GF2X t;\n\n   LeftShift(t, b, F.n-1);\n   div(t, t, F);\n\n   // we optimize for low degree b\n\n   long d;\n\n   d = deg(t);\n   if (d < 0)\n      B.shamt_fbi = 0;\n   else\n      B.shamt_fbi = F.n-2 - d; \n\n   CopyReverse(B.fbi, t, d);\n\n   if (F.method != GF2X_MOD_TRI && F.method != GF2X_MOD_PENT) {\n   \n      // The following code optimizes the case when \n      // f = X^n + low degree poly\n   \n      trunc(t, F.f, F.n);\n      d = deg(t);\n      if (d < 0)\n         B.shamt = 0;\n      else\n         B.shamt = d;\n\n      CopyReverse(B.f0, t, d);\n   }\n\n\n   if (db < 0)\n      B.shamt_b = 0;\n   else\n      B.shamt_b = db;\n\n   CopyReverse(B.b, b, db);\n}\n\nvoid TransMulMod(GF2X& x, const GF2X& a, const GF2XTransMultiplier& B,\n               const GF2XModulus& F)\n{\n   if (deg(a) >= F.n) Error(\"TransMulMod: bad args\");\n\n   GF2XRegister(t1);\n   GF2XRegister(t2);\n   GF2XRegister(t3);\n\n   mul(t1, a, B.b);\n   RightShift(t1, t1, B.shamt_b);\n\n   if (F.method == GF2X_MOD_TRI) {\n      RightShift(t2, a, F.k3);\n      add(t2, t2, a);\n   }\n   else if (F.method == GF2X_MOD_PENT) {\n      RightShift(t2, a, F.k3);\n      RightShift(t3, a, F.k2);\n      add(t2, t2, t3);\n      RightShift(t3, a, F.k1);\n      add(t2, t2, t3);\n      add(t2, t2, a);\n   }\n   else {\n      mul(t2, a, B.f0);\n      RightShift(t2, t2, B.shamt);\n   }\n\n   trunc(t2, t2, F.n-1);\n\n   mul(t2, t2, B.fbi);\n   if (B.shamt_fbi > 0) LeftShift(t2, t2, B.shamt_fbi);\n   trunc(t2, t2, F.n-1);\n   MulByX(t2, t2);\n\n   add(x, t1, t2);\n}\n\nvoid UpdateMap(vec_GF2& x, const vec_GF2& a, const GF2XTransMultiplier& B,\n       const GF2XModulus& F)\n{\n   GF2XRegister(xx);\n   GF2XRegister(aa);\n   conv(aa, a);\n   TransMulMod(xx, aa, B, F);\n   conv(x, xx);\n}\n   \n\nvoid ProjectPowers(GF2X& x, const GF2X& a, long k, const GF2XArgument& H,\n                   const GF2XModulus& F)\n{\n   long n = F.n;\n\n   if (deg(a) >= n || k < 0 || NTL_OVERFLOW(k, 1, 0)) \n      Error(\"ProjectPowers: bad args\");\n\n   long m = H.H.length()-1;\n   long l = (k+m-1)/m - 1;\n\n   GF2XTransMultiplier M;\n   build(M, H.H[m], F);\n\n   GF2X s;\n   s = a;\n\n   x.SetMaxLength(k);\n   clear(x);\n\n   long i;\n\n   for (i = 0; i <= l; i++) {\n      long m1 = min(m, k-i*m);\n      for (long j = 0; j < m1; j++)\n         SetCoeff(x, i*m+j, InnerProduct(H.H[j].xrep, s.xrep));\n      if (i < l)\n         TransMulMod(s, s, M, F);\n   }\n}\n\n\nvoid ProjectPowers(vec_GF2& x, const vec_GF2& a, long k, \n                   const GF2XArgument& H, const GF2XModulus& F)\n{\n   GF2X xx;\n   ProjectPowers(xx, to_GF2X(a), k, H, F);\n   VectorCopy(x, xx, k);\n}\n\n\nvoid ProjectPowers(GF2X& x, const GF2X& a, long k, const GF2X& h, \n                   const GF2XModulus& F)\n{\n   if (deg(a) >= F.n || k < 0) Error(\"ProjectPowers: bad args\");\n\n   if (k == 0) {\n      clear(x);\n      return;\n   }\n\n   long m = SqrRoot(k);\n\n   GF2XArgument H;\n   build(H, h, F, m);\n\n   ProjectPowers(x, a, k, H, F);\n}\n\nvoid ProjectPowers(vec_GF2& x, const vec_GF2& a, long k, const GF2X& H,\n                   const GF2XModulus& F)\n{\n   GF2X xx;\n   ProjectPowers(xx, to_GF2X(a), k, H, F);\n   VectorCopy(x, xx, k);\n}\n\n\nvoid OldMinPolyInternal(GF2X& h, const GF2X& x, long m)\n{\n   GF2X a, b, r, s;\n   GF2X a_in, b_in;\n\n   if (IsZero(x)) {\n      set(h);\n      return;\n   }\n\n   clear(a_in);\n   SetCoeff(a_in, 2*m);\n\n   CopyReverse(b_in, x, 2*m-1);\n      \n   a.xrep.SetMaxLength(a_in.xrep.length()+1);\n   b.xrep.SetMaxLength(b_in.xrep.length()+1);\n\n   long max_sz = max(a_in.xrep.length(), b_in.xrep.length());\n   r.xrep.SetLength(max_sz+1);\n   s.xrep.SetLength(max_sz+1);\n\n   _ntl_ulong *rp = r.xrep.elts();\n   _ntl_ulong *sp = s.xrep.elts();\n\n   long i;\n   for (i = 0; i <= max_sz; i++) {\n      rp[i] = sp[i] = 0;\n   }\n\n   sp[0] = 1;\n\n   long sr = 0;\n   long ss = 1;\n\n   a = a_in;\n   b = b_in;\n\n   _ntl_ulong *ap = a.xrep.elts();\n   _ntl_ulong *bp = b.xrep.elts();\n\n   long da = deg(a);\n   long wa = da/NTL_BITS_PER_LONG;\n   long ba = da - wa*NTL_BITS_PER_LONG;\n\n   long db = deg(b);\n   long wb = db/NTL_BITS_PER_LONG;\n   long bb = db - wb*NTL_BITS_PER_LONG;\n\n   long parity = 0;\n\n   for (;;) {\n      if (da < db) {\n         swap(ap, bp);\n         swap(da, db);\n         swap(wa, wb);\n         swap(ba, bb);\n         parity = 1 - parity;\n\n         swap(rp, sp);\n         swap(sr, ss);\n      }\n\n      // da >= db\n\n      if (db < m) break;\n\n      ShiftAdd(ap, bp, wb+1, da-db);\n      ShiftAdd(rp, sp, ss, da-db);\n      long t = ss + (da-db+NTL_BITS_PER_LONG-1)/NTL_BITS_PER_LONG;\n      if (t > sr) {\n         while (t > 0 && rp[t-1] == 0) t--; \n         sr = t;\n      }\n\n      _ntl_ulong msk = 1UL << ba;\n      _ntl_ulong aa = ap[wa];\n\n      while ((aa & msk) == 0) {\n         da--;\n         msk = msk >> 1;\n         ba--;\n         if (!msk) {\n            wa--;\n            ba = NTL_BITS_PER_LONG-1;\n            msk = 1UL << (NTL_BITS_PER_LONG-1);\n            if (wa < 0) break;\n            aa = ap[wa];\n         }\n      }\n   }\n\n   a.normalize();\n   b.normalize();\n   r.normalize();\n   s.normalize();\n\n   if (!parity) {\n      h = s;\n   }\n   else {\n      h = r;\n   }\n}\n\n\nvoid DoMinPolyMod(GF2X& h, const GF2X& g, const GF2XModulus& F, long m, \n               const GF2X& R)\n{\n   GF2X x;\n\n   ProjectPowers(x, R, 2*m, g, F);\n   MinPolyInternal(h, x, m);\n}\n\nvoid MinPolySeq(GF2X& h, const vec_GF2& a, long m)\n{\n   if (m < 0 || NTL_OVERFLOW(m, 1, 0)) Error(\"MinPoly: bad args\");\n   if (a.length() < 2*m) Error(\"MinPoly: sequence too short\");\n   GF2X x;\n   x.xrep = a.rep;\n   x.normalize();\n   MinPolyInternal(h, x, m);\n}\n\nvoid ProbMinPolyMod(GF2X& h, const GF2X& g, const GF2XModulus& F, long m)\n{\n   long n = F.n;\n   if (m < 1 || m > n) Error(\"ProbMinPoly: bad args\");\n\n   GF2X R;\n   random(R, n);\n\n   DoMinPolyMod(h, g, F, m, R);\n}\n\nvoid ProbMinPolyMod(GF2X& h, const GF2X& g, const GF2XModulus& F)\n{\n   ProbMinPolyMod(h, g, F, F.n);\n}\n\nvoid MinPolyMod(GF2X& hh, const GF2X& g, const GF2XModulus& F, long m)\n{\n   GF2X h, h1;\n   long n = F.n;\n   if (m < 1 || m > n) Error(\"MinPoly: bad args\");\n\n   /* probabilistically compute min-poly */\n\n   ProbMinPolyMod(h, g, F, m);\n   if (deg(h) == m) { hh = h; return; }\n   CompMod(h1, h, g, F);\n   if (IsZero(h1)) { hh = h; return; }\n\n   /* not completely successful...must iterate */\n\n\n   GF2X h2, h3;\n   GF2X R;\n   GF2XTransMultiplier H1;\n   \n\n   for (;;) {\n      random(R, n);\n      build(H1, h1, F);\n      TransMulMod(R, R, H1, F);\n      DoMinPolyMod(h2, g, F, m-deg(h), R);\n\n      mul(h, h, h2);\n      if (deg(h) == m) { hh = h; return; }\n      CompMod(h3, h2, g, F);\n      MulMod(h1, h3, h1, F);\n      if (IsZero(h1)) { hh = h; return; }\n   }\n}\n\nvoid IrredPolyMod(GF2X& h, const GF2X& g, const GF2XModulus& F, long m)\n{\n   if (m < 1 || m > F.n) Error(\"IrredPoly: bad args\");\n\n   GF2X R;\n   set(R);\n\n   DoMinPolyMod(h, g, F, m, R);\n}\n\n\n\nvoid IrredPolyMod(GF2X& h, const GF2X& g, const GF2XModulus& F)\n{\n   IrredPolyMod(h, g, F, F.n);\n}\n\n\n\nvoid MinPolyMod(GF2X& hh, const GF2X& g, const GF2XModulus& F)\n{\n   MinPolyMod(hh, g, F, F.n);\n}\n\n\n\nvoid MulByXMod(GF2X& c, const GF2X& a, const GF2XModulus& F)\n{\n   long da = deg(a);\n   long df = deg(F);\n   if (da >= df) Error(\"MulByXMod: bad args\"); \n\n   MulByX(c, a);\n\n   if (da >= 0 && da == df-1)\n      add(c, c, F);\n}\n\nstatic\nvoid MulByXModAux(GF2X& c, const GF2X& a, const GF2X& f)\n{\n   long da = deg(a);\n   long df = deg(f);\n   if (da >= df) Error(\"MulByXMod: bad args\"); \n\n   MulByX(c, a);\n\n   if (da >= 0 && da == df-1)\n      add(c, c, f);\n}\n\nvoid MulByXMod(GF2X& h, const GF2X& a, const GF2X& f)\n{\n   if (&h == &f) {\n      GF2X hh;\n      MulByXModAux(hh, a, f);\n      h = hh;\n   }\n   else\n      MulByXModAux(h, a, f);\n}\n\n\n\n\nvoid power(GF2X& x, const GF2X& a, long e)\n{\n   if (e < 0) {\n      Error(\"power: negative exponent\");\n   }\n\n   if (e == 0) {\n      x = 1;\n      return;\n   }\n\n   if (a == 0 || a == 1) {\n      x = a;\n      return;\n   }\n\n   long da = deg(a);\n\n   if (da > (NTL_MAX_LONG-1)/e)\n      Error(\"overflow in power\");\n\n   GF2X res;\n   res.SetMaxLength(da*e + 1);\n   res = 1;\n   \n   long k = NumBits(e);\n   long i;\n\n   for (i = k - 1; i >= 0; i--) {\n      sqr(res, res);\n      if (bit(e, i))\n         mul(res, res, a);\n   }\n\n   x = res;\n}\n\n\nstatic\nvoid FastTraceVec(vec_GF2& S, const GF2XModulus& f)\n{\n   long n = deg(f);\n\n   if (n <= 0) Error(\"TraceVec: bad args\");\n\n   GF2X x = reverse(-LeftShift(reverse(diff(reverse(f)), n-1), n-1)/f, n-1);\n\n   VectorCopy(S, x, n);\n   S.put(0, to_GF2(n));\n}\n\nstatic\nvoid PlainTraceVec(vec_GF2& S, const GF2X& f)\n{\n   long n = deg(f);\n\n   if (n <= 0) \n      Error(\"TraceVec: bad args\");\n\n   if (n == 0) {\n      S.SetLength(0);\n      return;\n   }\n\n   GF2X x = reverse(-LeftShift(reverse(diff(reverse(f)), n-1), n-1)/f, n-1);\n\n   VectorCopy(S, x, n); \n   S.put(0, to_GF2(n));\n}\n\n\nvoid TraceVec(vec_GF2& S, const GF2X& f)\n{\n   PlainTraceVec(S, f);\n}\n\nstatic\nvoid ComputeTraceVec(const GF2XModulus& F)\n{\n   vec_GF2& S = *((vec_GF2 *) &F.tracevec);\n\n   if (S.length() > 0)\n      return;\n\n   if (F.method == GF2X_MOD_PLAIN) {\n      PlainTraceVec(S, F.f);\n   }\n   else {\n      FastTraceVec(S, F);\n   }\n}\n\nvoid TraceMod(GF2& x, const GF2X& a, const GF2XModulus& F)\n{\n   long n = F.n;\n\n   if (deg(a) >= n)\n      Error(\"trace: bad args\");\n\n   if (F.tracevec.length() == 0) \n      ComputeTraceVec(F);\n\n   project(x, F.tracevec, a);\n}\n\nvoid TraceMod(GF2& x, const GF2X& a, const GF2X& f)\n{\n   if (deg(a) >= deg(f) || deg(f) <= 0)\n      Error(\"trace: bad args\");\n\n   project(x, TraceVec(f), a);\n}\n\n\n\n// New versions of GCD, XGCD, and MinPolyInternal\n// and support routines\n\nclass _NTL_GF2XMatrix {\nprivate:\n\n   _NTL_GF2XMatrix(const _NTL_GF2XMatrix&);  // disable\n   GF2X elts[2][2];\n\npublic:\n\n   _NTL_GF2XMatrix() { }\n   ~_NTL_GF2XMatrix() { }\n\n   void operator=(const _NTL_GF2XMatrix&);\n   GF2X& operator() (long i, long j) { return elts[i][j]; }\n   const GF2X& operator() (long i, long j) const { return elts[i][j]; }\n};\n\n\nvoid _NTL_GF2XMatrix::operator=(const _NTL_GF2XMatrix& M)\n{\n   elts[0][0] = M.elts[0][0];\n   elts[0][1] = M.elts[0][1];\n   elts[1][0] = M.elts[1][0];\n   elts[1][1] = M.elts[1][1];\n}\n\n\nstatic\nvoid mul(GF2X& U, GF2X& V, const _NTL_GF2XMatrix& M)\n// (U, V)^T = M*(U, V)^T\n{\n   GF2X t1, t2, t3;\n\n   mul(t1, M(0,0), U);\n   mul(t2, M(0,1), V);\n   add(t3, t1, t2);\n   mul(t1, M(1,0), U);\n   mul(t2, M(1,1), V);\n   add(V, t1, t2);\n   U = t3;\n}\n\n\nstatic\nvoid mul(_NTL_GF2XMatrix& A, _NTL_GF2XMatrix& B, _NTL_GF2XMatrix& C)\n// A = B*C, B and C are destroyed\n{\n   GF2X t1, t2;\n\n   mul(t1, B(0,0), C(0,0));\n   mul(t2, B(0,1), C(1,0));\n   add(A(0,0), t1, t2);\n\n   mul(t1, B(1,0), C(0,0));\n   mul(t2, B(1,1), C(1,0));\n   add(A(1,0), t1, t2);\n\n   mul(t1, B(0,0), C(0,1));\n   mul(t2, B(0,1), C(1,1));\n   add(A(0,1), t1, t2);\n\n   mul(t1, B(1,0), C(0,1));\n   mul(t2, B(1,1), C(1,1));\n   add(A(1,1), t1, t2);\n\n   long i, j;\n   for (i = 0; i < 2; i++) {\n      for (j = 0; j < 2; j++) {\n          B(i,j).kill();\n          C(i,j).kill();\n      }\n   }\n}\n\nstatic\nvoid IterHalfGCD(_NTL_GF2XMatrix& M_out, GF2X& U, GF2X& V, long d_red)\n{\n   M_out(0,0).SetMaxLength(d_red);\n   M_out(0,1).SetMaxLength(d_red);\n   M_out(1,0).SetMaxLength(d_red);\n   M_out(1,1).SetMaxLength(d_red);\n\n   set(M_out(0,0));   clear(M_out(0,1));\n   clear(M_out(1,0)); set(M_out(1,1));\n\n   long goal = deg(U) - d_red;\n\n   if (deg(V) <= goal)\n      return;\n\n   GF2X Q, t(INIT_SIZE, d_red);\n\n   while (deg(V) > goal) {\n      DivRem(Q, U, U, V);\n      swap(U, V);\n\n      mul(t, Q, M_out(1,0));\n      sub(t, M_out(0,0), t);\n      M_out(0,0) = M_out(1,0);\n      M_out(1,0) = t;\n\n      mul(t, Q, M_out(1,1));\n      sub(t, M_out(0,1), t);\n      M_out(0,1) = M_out(1,1);\n      M_out(1,1) = t;\n   }\n}\n\n\n\nstatic\nvoid HalfGCD(_NTL_GF2XMatrix& M_out, const GF2X& U, const GF2X& V, long d_red)\n{\n   if (IsZero(V) || deg(V) <= deg(U) - d_red) {\n      set(M_out(0,0));   clear(M_out(0,1));\n      clear(M_out(1,0)); set(M_out(1,1));\n\n      return;\n   }\n\n\n   long n = deg(U) - 2*d_red + 2;\n   if (n < 0) n = 0;\n\n   GF2X U1, V1;\n\n   RightShift(U1, U, n);\n   RightShift(V1, V, n);\n\n   if (d_red <= NTL_GF2X_HalfGCD_CROSSOVER) {\n      IterHalfGCD(M_out, U1, V1, d_red);\n      return;\n   }\n\n   long d1 = (d_red + 1)/2;\n   if (d1 < 1) d1 = 1;\n   if (d1 >= d_red) d1 = d_red - 1;\n\n   _NTL_GF2XMatrix M1;\n\n   HalfGCD(M1, U1, V1, d1);\n   mul(U1, V1, M1);\n\n\n   long d2 = deg(V1) - deg(U) + n + d_red;\n\n   if (IsZero(V1) || d2 <= 0) {\n      M_out = M1;\n      return;\n   }\n\n\n   GF2X Q;\n   _NTL_GF2XMatrix M2;\n\n   DivRem(Q, U1, U1, V1);\n   swap(U1, V1);\n\n   HalfGCD(M2, U1, V1, d2);\n\n   GF2X t(INIT_SIZE, deg(M1(1,1))+deg(Q)+1);\n\n   mul(t, Q, M1(1,0));\n   sub(t, M1(0,0), t);\n   swap(M1(0,0), M1(1,0));\n   swap(M1(1,0), t);\n\n   t.kill();\n\n   t.SetMaxLength(deg(M1(1,1))+deg(Q)+1);\n\n   mul(t, Q, M1(1,1));\n   sub(t, M1(0,1), t);\n   swap(M1(0,1), M1(1,1));\n   swap(M1(1,1), t);\n\n   t.kill();\n\n   mul(M_out, M2, M1);\n}\n\nstatic\nvoid HalfGCD(GF2X& U, GF2X& V)\n{\n   long d_red = (deg(U)+1)/2;\n\n   if (IsZero(V) || deg(V) <= deg(U) - d_red) {\n      return;\n   }\n\n   long du = deg(U);\n\n\n   long d1 = (d_red + 1)/2;\n   if (d1 < 1) d1 = 1;\n   if (d1 >= d_red) d1 = d_red - 1;\n\n   _NTL_GF2XMatrix M1;\n\n   HalfGCD(M1, U, V, d1);\n   mul(U, V, M1);\n\n   long d2 = deg(V) - du + d_red;\n\n   if (IsZero(V) || d2 <= 0) {\n      return;\n   }\n\n   M1(0,0).kill();\n   M1(0,1).kill();\n   M1(1,0).kill();\n   M1(1,1).kill();\n\n\n   GF2X Q;\n\n   DivRem(Q, U, U, V);\n   swap(U, V);\n\n   HalfGCD(M1, U, V, d2);\n\n   mul(U, V, M1);\n}\n\n\nvoid GCD(GF2X& d, const GF2X& u, const GF2X& v)\n{\n   long su = u.xrep.length();\n   long sv = v.xrep.length();\n\n   if (su <= NTL_GF2X_GCD_CROSSOVER/NTL_BITS_PER_LONG &&\n       sv <= NTL_GF2X_GCD_CROSSOVER/NTL_BITS_PER_LONG) {\n      OldGCD(d, u, v);\n      return;\n   }\n    \n   GF2X u1, v1;\n\n   u1 = u;\n   v1 = v;\n\n   long du1 = deg(u1);\n   long dv1 = deg(v1);\n\n   if (du1 == dv1) {\n      if (IsZero(u1)) {\n         clear(d);\n         return;\n      }\n\n      rem(v1, v1, u1);\n   }\n   else if (du1 < dv1) {\n      swap(u1, v1);\n      du1 = dv1;\n   }\n\n   // deg(u1) > deg(v1)\n\n   while (du1 >= NTL_GF2X_GCD_CROSSOVER && !IsZero(v1)) {\n      HalfGCD(u1, v1);\n\n      if (!IsZero(v1)) {\n         rem(u1, u1, v1);\n         swap(u1, v1);\n      }\n\n      du1 = deg(u1);\n   }\n\n   OldGCD(d, u1, v1);\n}\n\nstatic\nvoid XHalfGCD(_NTL_GF2XMatrix& M_out, GF2X& U, GF2X& V, long d_red)\n{\n   if (IsZero(V) || deg(V) <= deg(U) - d_red) {\n      set(M_out(0,0));   clear(M_out(0,1));\n      clear(M_out(1,0)); set(M_out(1,1));\n\n      return;\n   }\n\n   long du = deg(U);\n\n   if (d_red <= NTL_GF2X_HalfGCD_CROSSOVER) {\n      IterHalfGCD(M_out, U, V, d_red);\n      return;\n   }\n\n   long d1 = (d_red + 1)/2;\n   if (d1 < 1) d1 = 1;\n   if (d1 >= d_red) d1 = d_red - 1;\n\n   _NTL_GF2XMatrix M1;\n\n   HalfGCD(M1, U, V, d1);\n   mul(U, V, M1);\n\n   long d2 = deg(V) - du + d_red;\n\n   if (IsZero(V) || d2 <= 0) {\n      M_out = M1;\n      return;\n   }\n\n\n   GF2X Q;\n   _NTL_GF2XMatrix M2;\n\n   DivRem(Q, U, U, V);\n   swap(U, V);\n\n   XHalfGCD(M2, U, V, d2);\n\n\n   GF2X t(INIT_SIZE, deg(M1(1,1))+deg(Q)+1);\n\n   mul(t, Q, M1(1,0));\n   sub(t, M1(0,0), t);\n   swap(M1(0,0), M1(1,0));\n   swap(M1(1,0), t);\n\n   t.kill();\n\n   t.SetMaxLength(deg(M1(1,1))+deg(Q)+1);\n\n   mul(t, Q, M1(1,1));\n   sub(t, M1(0,1), t);\n   swap(M1(0,1), M1(1,1));\n   swap(M1(1,1), t);\n\n   t.kill();\n\n   mul(M_out, M2, M1);\n}\n\n\n\n\nvoid XGCD(GF2X& d, GF2X& s, GF2X& t, const GF2X& a, const GF2X& b)\n{\n   // GF2 w;\n\n   long sa = a.xrep.length();\n   long sb = b.xrep.length();\n\n   if (sa <= NTL_GF2X_GCD_CROSSOVER/NTL_BITS_PER_LONG &&\n       sb <= NTL_GF2X_GCD_CROSSOVER/NTL_BITS_PER_LONG) {\n      OldXGCD(d, s, t, a, b);\n      return;\n   }\n\n   GF2X U, V, Q;\n\n   U = a;\n   V = b;\n\n   long flag = 0;\n\n   if (deg(U) == deg(V)) {\n      DivRem(Q, U, U, V);\n      swap(U, V);\n      flag = 1;\n   }\n   else if (deg(U) < deg(V)) {\n      swap(U, V);\n      flag = 2;\n   }\n\n   _NTL_GF2XMatrix M;\n\n   XHalfGCD(M, U, V, deg(U)+1);\n\n   d = U;\n\n\n   if (flag == 0) {\n      s = M(0,0);\n      t = M(0,1);\n   }\n   else if (flag == 1) {\n      s = M(0,1);\n      mul(t, Q, M(0,1));\n      sub(t, M(0,0), t);\n   }\n   else {  /* flag == 2 */\n      s = M(0,1);\n      t = M(0,0);\n   }\n\n   // normalize\n\n   // inv(w, LeadCoeff(d));\n   // mul(d, d, w);\n   // mul(s, s, w);\n   // mul(t, t, w);\n}\n\n\nvoid MinPolyInternal(GF2X& h, const GF2X& x, long m)\n{  \n   if (m < NTL_GF2X_BERMASS_CROSSOVER) {\n      OldMinPolyInternal(h, x, m);\n      return;\n   }\n\n   GF2X a, b;\n   _NTL_GF2XMatrix M;\n      \n   SetCoeff(b, 2*m);\n   CopyReverse(a, x, 2*m-1);\n   HalfGCD(M, b, a, m+1);\n\n   h = M(1,1);\n}\n\n\n\nNTL_END_IMPL\n", "meta": {"hexsha": "3bda90a27174baf704853db37bb619e8d0e846fb", "size": 70530, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/src/GF2X1.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/src/GF2X1.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/src/GF2X1.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-07-02T12:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T14:58:30.000Z", "avg_line_length": 19.1345632122, "max_line_length": 82, "alphanum_fraction": 0.492400397, "num_tokens": 26707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.24253969590858088}}
{"text": "#include <iostream>\n#include <vector>\n#include <cassert>\n#include <cstring>\n#include <limits>\n#include <mpi.h>\n//#include <Eigen/Eigenvalues>\n\nenum KernelType {CubicSpline = 0, WendlandC2 = 1, WendlandC4 = 2};\n\n#include \"particle_simulator.hpp\"\n#include \"hdr_time.hpp\"\n#include \"hdr_run.hpp\"\n#ifdef USE_INTRINSICS\n#include \"vector_x86.hpp\"\n#endif\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\nnamespace Alert{\n    bool    BeyondBoundary   = false;\n    //PS::F64 MinimumOfDensity = 1.;\n    PS::F64 MinimumOfDensity = 1e-6;\n    //PS::F64 MaximumOfZCoordinate = 1e8;\n    PS::F64 MaximumOfZCoordinate = 5e8;\n}\n\nvoid debugByPrintf(char * str) {\n    for(PS::S64 i = 0; i < PS::Comm::getNumberOfProc(); i++) {\n        if(i == PS::Comm::getRank()) {\n            fprintf(stderr, \"Process %8d %s\\n\", PS::Comm::getRank(), str);\n        }\n        PS::Comm::barrier();\n    }\n}\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    bool judgeCriterion() {\n        /*\n        if(this->divv > 0.) {\n            return true;\n        } else {\n            return false;\n        }\n        */\n        PS::F64 vzovercs = ((this->pos[2] > 0.) ? (- this->vel[2] / this->vsnd)\n                            : (this->vel[2] / this->vsnd));\n        if(vzovercs > 4.) {\n        //if(vzovercs > 8.) {\n            return true;\n        } else {\n            return false;\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    void writeAscii(FILE *fp) const {\n        fprintf(fp, \"%6d %2d %+e\", this->id, this->istar, this->mass);         //  3\n        fprintf(fp, \" %+e %+e %+e\", this->pos[0], this->pos[1], this->pos[2]); //  6\n        fprintf(fp, \" %+e %+e %+e\", this->vel[0], this->vel[1], this->vel[2]); //  9\n        fprintf(fp, \" %+e %+e %+e\", this->acc[0], this->acc[1], this->acc[2]); // 12\n        fprintf(fp, \" %+e %+e %+e\", this->uene, this->alph, this->alphu);      // 15\n        fprintf(fp, \" %+e %+e %6d\", this->dens, this->ksr,  this->np);         // 18\n        fprintf(fp, \" %+e %+e %+e\", this->vsnd, this->pres, this->temp);       // 21\n        fprintf(fp, \" %+e %+e %+e\", this->divv, this->rotv, this->bswt);       // 24\n        fprintf(fp, \" %+e %+e %+e\", this->pot, this->abar, this->zbar);        // 27\n        fprintf(fp, \" %+e\",         this->enuc);                               // 28\n        fprintf(fp, \" %+e %+e %+e\", this->vsmx, this->udot, this->dnuc);       // 31\n        for(PS::S32 k = 0; k < NuclearReaction::NumberOfNucleon; k++) {        // 32 -- 44\n            fprintf(fp, \" %+.3e\", this->cmps[k]);\n        }\n        fprintf(fp, \" %+e\", this->pot3);                                       // 45\n        fprintf(fp, \" %+e %+e %+e\", this->tempmax[0], this->tempmax[1], this->tempmax[2]);\n                                                                               // 46 -- 48\n        fprintf(fp, \" %+e\", this->entr);                                       // 49\n        fprintf(fp, \"\\n\");\n    }\n\n    void writeAscii1Dimension(FILE *fp) const {\n        fprintf(fp, \"%+e %+e %+e\", this->pos[2], this->dens, this->vel[2]);\n        fprintf(fp, \"\\n\");\n    }\n\n    void clear() {\n        this->dens   = 0.;\n        this->vel[2] = 0.;\n    }\n\n    void copyFromForce(const SPHAnalysis & tmpsph) {\n        this->dens   = tmpsph.dens;\n        this->vel[2] = tmpsph.vel[2];\n    }\n\n    void copyFromFP(const SPHAnalysis & sph) {\n        (*this) = sph;\n    }\n\n    PS::F64 getRSearch() const {\n        return this->ksr;\n    }\n\n};\n\nclass SPHFitting {\npublic:\n    PS::S64    id;\n    PS::F64    mass;\n    PS::F64vec pos;\n    PS::F64vec vel;\n    PS::F64    ksr;\n    PS::F64    dens;\n\n    SPHFitting() {\n        this->id   = 0;\n        this->mass = 0.;\n        this->pos  = 0.;\n        this->vel  = 0.;\n        this->ksr  = 0.;\n        this->dens = 0.;\n    }\n\n    void copyFromSPHAnalysis(const SPHAnalysis & sph) {\n        this->id   = sph.id;\n        this->mass = sph.mass;\n        this->pos  = sph.pos;\n        this->vel  = sph.vel;\n        this->ksr  = sph.ksr;\n        this->dens = sph.dens;\n    }\n\n    void copyToSPHAnalysis(SPHAnalysis & sph) const {\n        sph.id   = this->id;\n        sph.mass = this->mass;\n        sph.pos  = this->pos;\n        sph.vel  = this->vel;\n        sph.ksr  = this->ksr;\n        sph.dens = this->dens;\n    }\n\n    PS::F64vec getPos() const {\n        return this->pos;\n    }\n\n    void setPos(PS::F64vec pos_new) {        \n        this->pos = pos_new;\n    }\n\n    void clear() {\n        this->dens   = 0.;\n        this->vel[2] = 0.;\n    }\n\n    void copyFromForce(const SPHFitting & tmpsph) {\n        this->dens   = tmpsph.dens;\n        this->vel[2] = tmpsph.vel[2];\n    }\n\n    void copyFromFP(const SPHFitting & sph) {\n        (*this) = sph;\n    }\n\n    PS::F64 getRSearch() const {\n        return this->ksr;\n    }\n\n    void writeAscii(FILE *fp) const {\n        fprintf(fp, \"%6d\", this->id);\n        fprintf(fp, \"\\n\");\n    }\n};\n\n#if 1\ntemplate <class Tsph>\nstruct calcFitting {\n    void operator () (const Tsph * epi,\n                      const PS::S32 nip,\n                      const Tsph * epj,\n                      const PS::S32 njp,\n                      Tsph * back) {\n        for(PS::S32 i = 0; i < nip; i++) {\n            if(epi[i].mass != 0.) {\n                continue;\n            }\n            PS::F64vec ipos = epi[i].pos;\n            PS::F64    dn   = 0.;\n            PS::F64    vz   = 0.;\n            for(PS::S32 j = 0; j < njp; j++) {\n                PS::F64vec dx  = ipos - epj[j].pos;\n                PS::F64    r2  = dx * dx;\n                PS::F64    r1  = sqrt(r2);\n                PS::F64    hi  = (epj[j].ksr  != 0.) ? 1. / epj[j].ksr  : 0.;\n                PS::F64    di  = (epj[j].dens != 0.) ? 1. / epj[j].dens : 0.;\n                PS::F64    qj  = r1 * hi;\n                PS::F64    dnj = epj[j].mass * ND::calcVolumeInverse(hi) * SK::kernel0th(qj);\n                PS::F64    vzj = epj[j].vel[2] * epj[j].mass * di\n                    * ND::calcVolumeInverse(hi) * SK::kernel0th(qj);\n                dn += dnj;\n                vz += vzj;\n            }\n            back[i].dens   = (dn > Alert::MinimumOfDensity) ? dn : Alert::MinimumOfDensity;\n            back[i].vel[2] = vz;\n        }\n    }\n};\n#else\ntemplate <class Tsph>\nstruct calcFitting {\n    void operator () (const Tsph * epi,\n                      const PS::S32 nip,\n                      const Tsph * epj,\n                      const PS::S32 njp,\n                      Tsph * back) {\n        for(PS::S32 i = 0; i < nip; i++) {\n            if(epi[i].mass != 0.) {\n                continue;\n            }\n            PS::F64 r2min_m = 1e60;\n            PS::F64 r2min_p = 1e60;\n            bool    prsns_m = false;\n            bool    prsns_p = false;\n            PS::S64 id_m    = -100;\n            PS::S64 id_p    = -100;\n            for(PS::S32 j = 0; j < njp; j++) {\n                if(epj[j].mass == 0.) {\n                    continue;\n                }\n                if(epj[j].pos[2] < 0.) {\n                    continue;\n                }\n                PS::F64vec dx = epj[j].pos - epi[i].pos;\n                PS::F64    r2 = dx * dx;\n                if(dx[2] < 0.) {\n                    if(r2 < r2min_m) {\n                        r2min_m = r2;\n                        id_m    = j;\n                    }\n                    prsns_m = true;\n                } else {\n                    if(r2 < r2min_p) {\n                        r2min_p = r2;\n                        id_p    = j;\n                    }\n                    prsns_p = true;\n                }\n            }\n            PS::F64 pzm = epj[id_m].pos[2];\n            PS::F64 pzp = epj[id_p].pos[2];\n            PS::F64 pzi = epi[i].pos[2];\n            PS::F64 dnm = epj[id_m].dens;\n            PS::F64 dnp = epj[id_p].dens;\n            PS::F64 vzm = epj[id_m].vel[2];\n            PS::F64 vzp = epj[id_p].vel[2];\n            if(prsns_m && prsns_p) {\n                back[i].dens   = ((pzp - pzi) * dnm + (pzi - pzm) * dnp) / (pzp - pzm);\n                back[i].vel[2] = ((pzp - pzi) * vzm + (pzi - pzm) * vzp) / (pzp - pzm);\n            } else if(prsns_p) {\n                back[i].dens   = dnp;\n                back[i].vel[2] = 0.;\n            } else {\n                back[i].dens   = Alert::MinimumOfDensity;\n                back[i].vel[2] = 0.;\n            }\n        }\n    }\n};\n#endif\n\ntemplate <class Tsph,\n          class Tzsph>\nvoid insertMassLessParticle(Tsph & sph,\n                            Tzsph & zsph,\n                            const PS::S64 nx,\n                            const PS::S64 ny,\n                            const PS::F64 bx,\n                            const PS::F64 by,\n                            const PS::F64 wx,\n                            bool maxornot,\n                            bool rightornot,\n                            const PS::S32 rkglb,\n                            const PS::S32 idglb) {\n\n    PS::S64 nzsph = zsph.size();\n    PS::F64 zpmax = 0.;\n    for(PS::S64 i = 0; i < nzsph; i++) {\n        if(fabs(zsph[i].pos[2]) > zpmax) {\n            zpmax = fabs(zsph[i].pos[2]);\n        }\n    }\n    PS::F64 zmmax = Alert::MaximumOfZCoordinate;\n    PS::F64 zmmin = - zmmax;\n    assert(zmmax > zpmax);\n    PS::S64 nmesh = 800;\n    PS::F64 msize = (zmmax - zmmin) / (PS::F64)nmesh;\n    \n    PS::F64 posx = bx + (PS::F64(idglb % nx) + 0.5) * wx;\n    PS::F64 posy = by + (PS::F64(idglb / nx) + 0.5) * wx;\n    PS::S64 nloc = sph.getNumberOfParticleLocal();\n    sph.setNumberOfParticleLocal(nloc+nmesh);\n    for(PS::S64 i = 0; i < nmesh; i++) {\n        SPHAnalysis tmpsph;\n        if(maxornot) {\n            tmpsph.id = -1;\n        } else if (rightornot) {\n            tmpsph.id = -2;\n        } else {\n            tmpsph.id = -3;\n        }\n        tmpsph.mass   = 0.;\n        tmpsph.pos[0] = posx;\n        tmpsph.pos[1] = posy;\n        tmpsph.pos[2] = zmmin + (PS::F64)i * msize;\n        tmpsph.vel    = 0.;\n        tmpsph.ksr    = 0.;\n        sph[nloc+i]   = tmpsph;\n    }\n\n}\n\ntemplate <class Tsph>\nvoid search1Dpoint(Tsph & sph,\n                   const PS::S64 nx,\n                   const PS::S64 ny,\n                   const PS::F64 bx,\n                   const PS::F64 by,\n                   const PS::F64 wx,\n                   PS::S64 * nptcl,\n                   PS::S64 * pcrit,\n                   PS::F64 * dnmax,\n                   bool maxornot,\n                   bool rightornot,\n                   PS::F64 dnlimit,\n                   PS::F64 r2limit,\n                   char * filename,\n                   PS::F64 * _dnglb,\n                   PS::F64 * _r2glb) {\n    PS::F64 dnloc = -1.;\n    PS::S64 idloc = -1;\n    for(PS::S64 i = 0; i < nx * ny; i++) {\n        PS::F64 fracpcrit = (PS::F64)pcrit[i] / (PS::F64)nptcl[i];\n        if(fracpcrit < 0.01 || 0.02 < fracpcrit) {\n            continue;\n        }\n        if(dnmax[i] > dnlimit && (!maxornot)) {\n            continue;\n        }\n#if 0\n        if(!((bx + (PS::F64)(i % nx) * wx - pxlimit > 0.) ^ (!rightornot)) && (!maxornot)) {\n            continue;\n        }\n#else\n        PS::F64 tmpx  = bx + (PS::F64)(i % nx) * wx;\n        PS::F64 tmpy  = by + (PS::F64)(i / nx) * wx;\n        PS::F64 tmpr2 = tmpx * tmpx + tmpy * tmpy;\n        if(!((tmpr2 - r2limit > 0.) ^ (!rightornot)) && (!maxornot)) {\n            continue;\n        }\n#endif\n        if(bx + (PS::F64)(i % nx) * wx < 0.) {\n            continue;\n        }\n        if(dnloc < dnmax[i]) {\n            dnloc = dnmax[i];\n            idloc = i;\n        }\n    }\n\n    PS::F64 dnglb = -1.;\n    PS::S32 rkglb = -1;\n    PS::Comm::getMaxValue(dnloc, PS::Comm::getRank(), dnglb, rkglb);\n    PS::S64 idglb = ((PS::Comm::getRank() == rkglb) ? idloc : -1);\n    PS::F64 pxglb = bx + (PS::F64)(idloc % nx) * wx;\n    PS::F64 pyglb = by + (PS::F64)(idloc / nx) * wx;\n    PS::F64 r2glb = pxglb * pxglb + pyglb * pyglb;\n    PS::Comm::broadcast(&r2glb, 1, rkglb);\n\n#if 1\n    if(maxornot) {\n        // run.hewd0.45_bh3e2_b05.00\n        // t0096_0\n        //rkglb =   71;\n        //idglb =  771;\n        // t0097_0\n        rkglb =   72;\n        idglb =  770;\n        // run.hewd0.45_bh3e2_b06.00\n        // t0095_0\n        //rkglb =   70;\n        //idglb =  810;\n        // t0096_0\n        //rkglb =   71;\n        //idglb =  800;\n        // t0097_0\n        //rkglb =   71;\n        //idglb =  796;\n        // t0098_0\n        //rkglb =   70;\n        //idglb =  795;\n    }\n#else\n#endif\n\n    if(PS::Comm::getRank() == rkglb) {\n\n        if(maxornot) {\n            printf(\"max:   %8d %8d\\n\", rkglb, idglb);\n        } else if(rightornot){\n            printf(\"right: %8d %8d\\n\", rkglb, idglb);\n        } else {\n            printf(\"left:  %8d %8d\\n\", rkglb, idglb);\n        }\n\n        PS::ReallocatableArray<SPHAnalysis> zsph;\n        char ofile[1024];\n        sprintf(ofile, filename);\n        FILE * fp = fopen(ofile, \"w\");\n        assert(fp);\n        for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n            PS::F64 dx = sph[i].pos[0] - bx;\n            PS::F64 dy = sph[i].pos[1] - by;\n            PS::S64 id = 0;\n            id  = (PS::S64)(dy / wx) * nx;\n            id += (PS::S64)(dx / wx) % nx;\n            //assert(id < nx * ny);\n            if(id >= nx * ny) {\n                continue;\n            }\n            if(id == idglb) {\n                sph[i].writeAscii(fp);\n                zsph.push_back(sph[i]);\n            }\n        }\n        fclose(fp);\n        insertMassLessParticle(sph, zsph, nx, ny, bx, by, wx, maxornot, rightornot, rkglb, idglb);\n    }\n\n    *_dnglb = dnglb;\n    *_r2glb = r2glb;\n}\n    \nint main(int argc, char ** argv) {\n    PS::Initialize(argc, argv);\n\n    PS::DomainInfo dinfo;\n    dinfo.initialize();\n    dinfo.setDomain(PS::Comm::getNumberOfProc(), 1);\n    PS::ParticleSystem<SPHAnalysis> sph;\n    sph.initialize();\n    sph.createParticle(0);\n    sph.setNumberOfParticleLocal(0);\n\n    char itype[1024];\n    PS::S32 fflag, nfile;\n    PS::S64 ibgn, iend;\n    PS::F64vec xmin;\n    PS::F64    xmax;\n    PS::F64    wdth;\n    PS::S64    nnxx;\n    char       otype[1024];\n    FILE * fp = fopen(argv[1], \"r\");\n    fscanf(fp, \"%s\", itype);\n    fscanf(fp, \"%d %d\", &fflag, &nfile);\n    fscanf(fp, \"%lf%lf%lf\", &xmin[0], &xmin[1], &xmax);\n    fscanf(fp, \"%lf%lld\", &wdth, &nnxx);\n    fscanf(fp, \"%s\", otype);\n    fclose(fp);\n\n    if(PS::Comm::getRank() == 0) {\n        fprintf(stderr, \"itype: %s\\n\", itype);\n        fprintf(stderr, \"fflag: %d nfile: %d\\n\", fflag, nfile);\n        fprintf(stderr, \"xmin[0]: %+e xmin[1]: %+e\\n\", xmin[0], xmin[1]);\n        fprintf(stderr, \"xmax: %+e\\n\", xmax);\n        fprintf(stderr, \"width: %+e nnxx: %lld\\n\", wdth, nnxx);\n        fprintf(stderr, \"otype: %s\\n\", otype);\n        fprintf(stderr, \"nproc: %d\\n\", PS::Comm::getNumberOfProc());\n        fprintf(stderr, \"nthrd: %d\\n\", PS::Comm::getNumberOfThread());\n    }\n\n    // input\n    if(fflag == 0) {\n        char sfile[1024];\n        sprintf(sfile, \"%s.dat\",  itype);\n        fp = fopen(sfile, \"r\");\n        assert(fp);\n        fprintf(stderr, \"Reading file...\\n\");\n        sph.readParticleAscii(sfile);\n        fclose(fp);\n    } else {\n        PS::S64 ntot = 0;\n        PS::S64 nrank = PS::Comm::getNumberOfProc();\n        PS::S64 irank = PS::Comm::getRank();\n        PS::S64 ihead = nfile *  irank      / nrank;\n        PS::S64 itail = nfile * (irank + 1) / nrank;\n        for(PS::S64 ifile = ihead; ifile < itail; ifile++) {\n            char sfile[1024];\n            sprintf(sfile, \"%s_p%06d_i%06d.dat\",  itype, nfile, ifile);\n            fp = fopen(sfile, \"r\");\n            assert(fp);\n            PS::S64 ntmp = 0;\n            for(PS::S32 c; (c = getc(fp)) != EOF; ntmp += ('\\n' == c ? 1 : 0)) {\n                ;\n            }\n            fclose(fp);\n            sph.setNumberOfParticleLocal(ntot+ntmp);\n            fp = fopen(sfile, \"r\");\n            for(PS::S64 i = 0; i < ntmp; i++) {\n                sph[ntot+i].readAscii(fp);\n            }\n            fclose(fp);\n            ntot += ntmp;\n        }\n    }\n\n    // Data distribution\n    {\n        PS::S64 nrank = PS::Comm::getNumberOfProc();\n        PS::F64 dx    = wdth / (PS::F64)nrank;\n        for(PS::S64 i = 0; i < nrank; i++) {\n            PS::F64ort pos;\n            pos.low_[0]  = xmin[0] + dx * i;\n            pos.low_[1]  = - xmax;\n            pos.low_[2]  = - xmax;\n            pos.high_[0] = xmin[0] + dx * (i + 1);\n            pos.high_[1] = + xmax;\n            pos.high_[2] = + xmax;\n            dinfo.setPosDomain(i, pos);\n        }\n        sph.exchangeParticle(dinfo);\n    }\n\n    // Analyse divergence v\n    {\n        const PS::F64 wx = wdth / (PS::F64)nnxx;\n        const PS::F64 bx = xmin[0] + (wdth / (PS::F64)PS::Comm::getNumberOfProc())\n            * PS::Comm::getRank();\n        const PS::F64 by = xmin[1];\n        const PS::S64 nx = nnxx / PS::Comm::getNumberOfProc();\n        const PS::S64 ny = nnxx;\n        PS::S64 *nptcl = (PS::S64 *)malloc(sizeof(PS::S64) * nx * ny);\n        assert(nptcl);\n        PS::S64 *pcrit = (PS::S64 *)malloc(sizeof(PS::S64) * nx * ny);\n        assert(pcrit);\n        PS::F64 *dnmax = (PS::F64 *)malloc(sizeof(PS::F64) * nx * ny);\n        assert(dnmax);\n        for(PS::S64 i = 0; i < nx * ny; i++) {\n            nptcl[i] = 0;\n            pcrit[i] = 0;\n            dnmax[i] = 0.;\n        }        \n        for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n            PS::F64 dx = sph[i].pos[0] - bx;\n            PS::F64 dy = sph[i].pos[1] - by;\n            PS::S64 id = 0;\n            id  = (PS::S64)(dy / wx) * nx;\n            id += (PS::S64)(dx / wx) % nx;\n            //assert(id < nx * ny);\n            if(id >= nx * ny) {\n                if(Alert::BeyondBoundary == false) {\n                    fprintf(stderr, \"Caution! A particle is beyond the boundary!\\n\");\n                    Alert::BeyondBoundary = true;\n                }\n                continue;\n            }\n            nptcl[id]++;\n            if(sph[i].judgeCriterion()) {\n                pcrit[id]++;\n            }\n            if(dnmax[id] < sph[i].dens) {\n                dnmax[id] = sph[i].dens;\n            }\n        }\n\n        PS::F64 dncen, r2cen;\n        char ofile[1024];\n        sprintf(ofile, \"%s_0.log\", otype);\n        search1Dpoint(sph, nx, ny, bx, by, wx, nptcl, pcrit, dnmax,\n                      true, false, 0., 0., ofile, &dncen, &r2cen);\n        PS::F64 dntmp, r2tmp;\n        sprintf(ofile, \"%s_1.log\", otype);\n        search1Dpoint(sph, nx, ny, bx, by, wx, nptcl, pcrit, dnmax,\n                      false, true,  0.5*dncen, r2cen, ofile, &dntmp, &r2tmp);\n        sprintf(ofile, \"%s_2.log\", otype);\n        search1Dpoint(sph, nx, ny, bx, by, wx, nptcl, pcrit, dnmax,\n                      false, false, 0.5*dncen, r2cen, ofile, &dntmp, &r2tmp);\n\n        free(nptcl);\n        free(pcrit);\n        free(dnmax);\n    }\n\n    PS::ParticleSystem<SPHFitting> fsph;\n    fsph.initialize();\n    fsph.createParticle(0);\n    fsph.setNumberOfParticleLocal(sph.getNumberOfParticleLocal());\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        fsph[i].copyFromSPHAnalysis(sph[i]);\n    }\n    dinfo.decomposeDomainAll(fsph);\n    fsph.exchangeParticle(dinfo);\n    PS::TreeForForceShort<SPHFitting, SPHFitting, SPHFitting>::Scatter fitting;\n    fitting.initialize(0);\n    //fsph.writeParticleAscii(\"hoge\", \"%s_p%06d_i%06d.dat\");\n    //debugByPrintf(\"hoge a\");\n    fitting.calcForceAllAndWriteBack(calcFitting<SPHFitting>(), fsph, dinfo);\n    //debugByPrintf(\"hoge b\");\n    sph.setNumberOfParticleLocal(fsph.getNumberOfParticleLocal());\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        fsph[i].copyToSPHAnalysis(sph[i]);\n    }\n\n    // output fitting funciton\n    {\n        for(PS::S64 irank = 0; irank < PS::Comm::getNumberOfProc(); irank++) {\n            if(irank == PS::Comm::getRank()) {\n                char ofile0[1024];\n                char ofile1[1024];\n                char ofile2[1024];\n                sprintf(ofile0, \"%s_0.dat\", otype);\n                sprintf(ofile1, \"%s_1.dat\", otype);\n                sprintf(ofile2, \"%s_2.dat\", otype);\n                FILE * fp0 = fopen(ofile0, \"a\");\n                FILE * fp1 = fopen(ofile1, \"a\");\n                FILE * fp2 = fopen(ofile2, \"a\");\n                for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n                    if(sph[i].id == -1) {\n                        sph[i].writeAscii1Dimension(fp0);\n                    } else if(sph[i].id == -2) {\n                        sph[i].writeAscii1Dimension(fp1);\n                    } else if(sph[i].id == -3) {\n                        sph[i].writeAscii1Dimension(fp2);\n                    }\n                }\n                fclose(fp0);\n                fclose(fp1);\n                fclose(fp2);\n            }\n            PS::Comm::barrier();\n        }\n    }\n\n    PS::Finalize();\n\n    return 0;\n}\n", "meta": {"hexsha": "8e13735524fc2fa04a3a951292f8b9385d3960b0", "size": 22382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool.imbh/search/bounce/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.imbh/search/bounce/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.imbh/search/bounce/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": 32.8181818182, "max_line_length": 98, "alphanum_fraction": 0.4407112859, "num_tokens": 7149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24240789467756008}}
{"text": "// Copyright (c) 2015-2021 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#include \"coalescent_model.hpp\"\n\n#include <memory>\n#include <cmath>\n#include <complex>\n#include <numeric>\n#include <stdexcept>\n\n#include <boost/math/special_functions/binomial.hpp>\n\n#include \"utils/maths.hpp\"\n#include \"utils/mappable_algorithms.hpp\"\n\nnamespace octopus {\n\nCoalescentModel::CoalescentModel(Haplotype reference, Parameters params,\n                                 std::size_t num_haplotyes_hint, CachingStrategy caching)\n: reference_ {std::move(reference)}\n, reference_repeats_ {}\n, indel_heterozygosity_model_ {make_indel_model(reference_, {params.indel_heterozygosity}, reference_repeats_)}\n, params_ {params}\n, haplotypes_ {}\n, caching_ {caching}\n, index_cache_ {}\n, index_flag_buffer_ {}\n, k_indel_zero_result_cache_ {2 * num_haplotyes_hint, std::vector<boost::optional<LogProbability>> {}}\n{\n    if (params_.snp_heterozygosity <= 0 || params_.indel_heterozygosity <= 0) {\n        throw std::domain_error {\"CoalescentModel: snp and indel heterozygosity must be > 0\"};\n    }\n    site_buffer1_.reserve(128);\n    site_buffer2_.reserve(128);\n    if (caching == CachingStrategy::address) {\n        difference_address_cache_.reserve(num_haplotyes_hint);\n    } else if (caching_ == CachingStrategy::value) {\n        difference_value_cache_.reserve(num_haplotyes_hint);\n        difference_value_cache_.emplace(std::piecewise_construct,\n                                        std::forward_as_tuple(reference_),\n                                        std::forward_as_tuple());\n    }\n    k_indel_pos_result_cache_.reserve(2 * num_haplotyes_hint);\n}\n\nvoid CoalescentModel::set_reference(Haplotype reference)\n{\n    reference_ = std::move(reference);\n    if (caching_ == CachingStrategy::address) {\n        difference_address_cache_.clear();\n    } else if (caching_ == CachingStrategy::value) {\n        difference_value_cache_.clear();\n        difference_value_cache_.emplace(std::piecewise_construct,\n                                        std::forward_as_tuple(reference_),\n                                        std::forward_as_tuple());\n    }\n}\n\nvoid CoalescentModel::prime(MappableBlock<Haplotype> haplotypes)\n{\n    haplotypes_ = std::move(haplotypes);\n    index_cache_.assign(haplotypes_.size(), boost::none);\n    index_flag_buffer_.assign(haplotypes_.size(), false);\n}\n\nvoid CoalescentModel::unprime() noexcept\n{\n    haplotypes_.clear();\n    haplotypes_.shrink_to_fit();\n    index_cache_.clear();\n    index_cache_.shrink_to_fit();\n    index_flag_buffer_.clear();\n    index_flag_buffer_.shrink_to_fit();\n}\n\nbool CoalescentModel::is_primed() const noexcept\n{\n    return !index_cache_.empty();\n}\n\nCoalescentModel::LogProbability CoalescentModel::evaluate(const Haplotype& haplotype) const\n{\n    return evaluate(count_segregating_sites(haplotype));\n}\n\nCoalescentModel::LogProbability CoalescentModel::evaluate(const std::vector<unsigned>& haplotype_indices) const\n{\n    return evaluate(count_segregating_sites(haplotype_indices));\n}\n\nnamespace {\n\nauto powm1(const unsigned i) noexcept // std::pow(-1, i)\n{\n    return (i % 2 == 0) ? 1 : -1;\n}\n\ntemplate <typename RealType>\nauto coalescent_real_space(const unsigned n, const unsigned k, const RealType theta)\n{\n    RealType result {0};\n    for (unsigned i {2}; i <= n; ++i) {\n        result += powm1(i) * maths::binomial_coefficient<RealType>(n - 1, i - 1) * ((i - 1) / (theta + i - 1)) * std::pow(theta / (theta + i - 1), k);\n    }\n    return std::log(result);\n}\n\ntemplate <typename ForwardIt>\nauto complex_log_sum_exp(ForwardIt first, ForwardIt last)\n{\n    using ComplexType = typename std::iterator_traits<ForwardIt>::value_type;\n    const auto l = [] (const auto& lhs, const auto& rhs) { return lhs.real() < rhs.real(); };\n    const auto max = *std::max_element(first, last, l);\n    return max + std::log(std::accumulate(first, last, ComplexType {},\n                                          [max] (const auto curr, const auto x) { return curr + std::exp(x - max); }));\n}\n\ntemplate <typename Container>\nauto complex_log_sum_exp(const Container& logs)\n{\n    return complex_log_sum_exp(std::cbegin(logs), std::cend(logs));\n}\n\ntemplate <typename RealType>\nauto coalescent_log_space(const unsigned n, const unsigned k, const RealType theta)\n{\n    std::vector<std::complex<RealType>> tmp(n - 1, std::log(std::complex<RealType> {-1}));\n    for (unsigned i {2}; i <= n; ++i) {\n        auto& cur = tmp[i - 2];\n        cur *= i;\n        cur += maths::log_binomial_coefficient<RealType>(n - 1, i - 1);\n        cur += std::log((i - 1) / (theta + i - 1));\n        cur += k * std::log(theta / (theta + i - 1));\n    }\n    return complex_log_sum_exp(tmp).real();\n}\n\ntemplate <typename RealType>\nauto coalescent(const unsigned n, const unsigned k, const RealType theta)\n{\n    if (n < 30 && k <= 80) {\n        auto result = coalescent_real_space(n, k, theta);\n        if (std::isnan(result)) {\n            result = coalescent_log_space(n, k, theta);\n        }\n        return result;\n    } else {\n        return coalescent_log_space(n, k, theta);\n    }\n}\n\ntemplate <typename RealType>\nauto coalescent(const unsigned n, const unsigned k_snp, const unsigned k_indel,\n                const RealType theta_snp, const RealType theta_indel)\n{\n    const auto theta = theta_snp + theta_indel;\n    const auto k_tot = k_snp + k_indel;\n    auto result = coalescent(n, k_tot, theta);\n    result += k_snp * std::log(theta_snp / theta);\n    result += k_indel * std::log(theta_indel / theta);\n    result += maths::log_binomial_coefficient<RealType>(k_tot, k_snp);\n    return result;\n}\n\ntemplate <typename RealType, std::size_t N>\nauto coalescent(const unsigned n, \n                const std::array<unsigned, N>& k,\n                const std::array<RealType, N>& theta)\n{\n    const auto theta_tot = std::accumulate(std::cbegin(theta), std::cend(theta), RealType {0});\n    const auto k_tot = std::accumulate(std::cbegin(k), std::cend(k), 0u);\n    auto result = coalescent(n, k_tot, theta_tot);\n    for (std::size_t i {0}; i < N; ++i) {\n        result += k[i] * std::log(theta[i] / theta_tot);\n    }\n    result += maths::log_multinomial_coefficient<RealType>(k);\n    return result;\n}\n\n} // namespace\n\nCoalescentModel::LogProbability CoalescentModel::evaluate(const SegregatingSiteCounts& counts) const\n{\n    if (counts.repeat_indels + counts.complex_indels == 0) {\n        return evaluate_no_indels(counts.snps, counts.haplotypes);\n    } else {\n        const auto indel_heterozygosities = calculate_buffered_indel_heterozygosities();\n        const auto repeat_indel_heterozygosity = maths::round_sf(indel_heterozygosities.second, 6);\n        const auto complex_indel_heterozygosity = maths::round_sf(indel_heterozygosities.first, 6);\n        SegregatingSiteCountsWithIndelHeterozygosities sites {counts, repeat_indel_heterozygosity, complex_indel_heterozygosity};\n        auto itr = k_indel_pos_result_cache_.find(sites);\n        if (itr != std::cend(k_indel_pos_result_cache_)) {\n            return itr->second;\n        }\n        const std::array<unsigned, 3> site_counts {counts.snps, counts.repeat_indels, counts.complex_indels};\n        const std::array<double, 3> site_heterozygosities {params_.snp_heterozygosity, repeat_indel_heterozygosity, complex_indel_heterozygosity};\n        const auto result = coalescent(counts.haplotypes, site_counts, site_heterozygosities);\n        k_indel_pos_result_cache_.emplace(sites, result);\n        return result;\n    }\n}\n\nCoalescentModel::LogProbability CoalescentModel::evaluate_no_indels(const unsigned k_snp, const unsigned n) const\n{\n    if (k_indel_zero_result_cache_.size() > n) {\n        if (k_indel_zero_result_cache_[n].size() > k_snp) {\n            auto& result = k_indel_zero_result_cache_[n][k_snp];\n            if (!result) {\n                result = coalescent(n, k_snp, 0, params_.snp_heterozygosity, params_.indel_heterozygosity);\n            }\n            return *result;\n        } else {\n            k_indel_zero_result_cache_[n].resize(k_snp + 1, boost::none);\n        }\n    } else {\n        k_indel_zero_result_cache_.resize(n + 1);\n        k_indel_zero_result_cache_[n].assign(k_snp + 1, boost::none);\n    }\n    const auto result = coalescent(n, k_snp, 0, params_.snp_heterozygosity, params_.indel_heterozygosity);\n    k_indel_zero_result_cache_[n][k_snp] = result;\n    return result;\n}\n\nvoid CoalescentModel::fill_site_buffer(const Haplotype& haplotype) const\n{\n    assert(site_buffer2_.empty());\n    site_buffer1_.clear();\n    if (caching_ == CachingStrategy::address) {\n        fill_site_buffer_from_address_cache(haplotype);\n    } else {\n        fill_site_buffer_from_value_cache(haplotype);\n    }\n    site_buffer1_ = std::move(site_buffer2_);\n    site_buffer2_.clear();\n}\n\nvoid CoalescentModel::fill_site_buffer_uncached(const Haplotype& haplotype) const\n{\n    // Although we won't retrieve from the cache, we need to make sure all the variants\n    // stay in existence as we populate the buffers by reference.\n    auto itr = difference_value_cache_.find(reference_);\n    if (itr == std::cend(difference_value_cache_)) {\n        itr = difference_value_cache_.emplace(reference_, haplotype.difference(reference_)).first;\n    } else {\n        itr->second = haplotype.difference(reference_);\n    }\n    std::set_union(std::begin(site_buffer1_), std::end(site_buffer1_),\n                   std::cbegin(itr->second), std::cend(itr->second),\n                   std::back_inserter(site_buffer2_));\n}\n\nvoid CoalescentModel::fill_site_buffer_from_value_cache(const Haplotype& haplotype) const\n{\n    auto itr = difference_value_cache_.find(haplotype);\n    if (itr == std::cend(difference_value_cache_)) {\n        itr = difference_value_cache_.emplace(haplotype, haplotype.difference(reference_)).first;\n    }\n    std::set_union(std::begin(site_buffer1_), std::end(site_buffer1_),\n                   std::cbegin(itr->second), std::cend(itr->second),\n                   std::back_inserter(site_buffer2_));\n}\n\nvoid CoalescentModel::fill_site_buffer_from_address_cache(const Haplotype& haplotype) const\n{\n    auto itr = difference_address_cache_.find(std::addressof(haplotype));\n    if (itr == std::cend(difference_address_cache_)) {\n        itr = difference_address_cache_.emplace(std::addressof(haplotype), haplotype.difference(reference_)).first;\n    }\n    std::set_union(std::begin(site_buffer1_), std::end(site_buffer1_),\n                   std::cbegin(itr->second), std::cend(itr->second),\n                   std::back_inserter(site_buffer2_));\n}\n\nCoalescentModel::SegregatingSiteCounts CoalescentModel::count_segregating_sites(const Haplotype& haplotype) const\n{\n    fill_site_buffer(haplotype);\n    return count_segregating_sites_in_buffer(1);\n}\n\nCoalescentModel::SegregatingSiteCounts CoalescentModel::count_segregating_sites_in_buffer(const unsigned num_haplotypes) const\n{\n    unsigned repeat_indels {0}, complex_indels {0};\n    for (const auto& site : site_buffer1_) {\n        if (is_indel(site)) {\n            if (has_overlapped(reference_repeats_, site.get())) {\n                ++repeat_indels;\n            } else {\n                ++complex_indels;\n            }\n        }\n    }\n    const auto num_indels = repeat_indels + complex_indels;\n    const auto num_snps = static_cast<unsigned>(site_buffer1_.size()) - num_indels;\n    return {num_haplotypes + 1, num_snps, repeat_indels, complex_indels};\n}\n\nstd::pair<double, double> CoalescentModel::calculate_buffered_indel_heterozygosities() const\n{\n    boost::optional<double> min_heterozygosity {}, max_heterozygosity {};\n    for (const auto& site : site_buffer1_) {\n        if (is_indel(site)) {\n            auto site_heterozygosity = calculate_heterozygosity(site);\n            if (min_heterozygosity) {\n                min_heterozygosity = std::min(*min_heterozygosity, site_heterozygosity);\n            } else {\n                min_heterozygosity = site_heterozygosity;\n            }\n            if (max_heterozygosity) {\n                max_heterozygosity = std::max(*max_heterozygosity, site_heterozygosity);\n            } else {\n                max_heterozygosity = site_heterozygosity;\n            }\n        }\n    }\n    if (!min_heterozygosity) min_heterozygosity = params_.indel_heterozygosity;\n    if (!max_heterozygosity) max_heterozygosity = params_.indel_heterozygosity;\n    return std::make_pair(*min_heterozygosity, *max_heterozygosity);\n}\n\ndouble CoalescentModel::calculate_heterozygosity(const Variant& indel) const\n{\n    assert(is_indel(indel));\n    const auto offset = static_cast<std::size_t>(begin_distance(reference_, indel));\n    return calculate_indel_probability(indel_heterozygosity_model_, offset, indel_size(indel));\n}\n\nCoalescentProbabilityGreater::CoalescentProbabilityGreater(CoalescentModel model)\n: model_ {std::move(model)}\n, buffer_ {}\n, cache_ {}\n{\n    buffer_.reserve(1);\n    cache_.reserve(100);\n}\n\nbool CoalescentProbabilityGreater::operator()(const Haplotype& lhs, const Haplotype& rhs) const\n{\n    if (have_same_alleles(lhs, rhs)) return true;\n    auto cache_itr = cache_.find(lhs);\n    if (cache_itr == std::cend(cache_)) {\n        buffer_.assign({lhs});\n        cache_itr = cache_.emplace(lhs, model_.evaluate(buffer_)).first;\n    }\n    const auto lhs_probability = cache_itr->second;\n    cache_itr = cache_.find(rhs);\n    if (cache_itr == std::cend(cache_)) {\n        buffer_.assign({rhs});\n        cache_itr = cache_.emplace(rhs, model_.evaluate(buffer_)).first;\n    }\n    const auto rhs_probability = cache_itr->second;\n    return lhs_probability > rhs_probability;\n}\n\nbool operator==(const CoalescentModel::SegregatingSiteCounts& lhs, const CoalescentModel::SegregatingSiteCounts& rhs) noexcept\n{\n    return lhs.haplotypes == rhs.haplotypes && lhs.snps == rhs.snps && lhs.repeat_indels == rhs.repeat_indels && lhs.complex_indels == rhs.complex_indels;\n}\n\nstd::size_t CoalescentModel::SegregatingSiteCountsHash::operator()(const SegregatingSiteCounts& counts) const noexcept\n{\n    return boost::hash_value(std::make_tuple(counts.haplotypes, counts.snps, counts.repeat_indels, counts.complex_indels));\n}\n\nstd::size_t CoalescentModel::SegregatingSiteCountsWithIndelHeterozygositiesHash::operator()(const SegregatingSiteCountsWithIndelHeterozygosities& sites) const noexcept\n{\n    using boost::hash_combine;\n    std::size_t result {};\n    hash_combine(result, SegregatingSiteCountsHash{}(sites.counts));\n    hash_combine(result, std::hash<decltype(sites.repeat_heterozygosity)>()(sites.repeat_heterozygosity));\n    hash_combine(result, std::hash<decltype(sites.complex_heterozygosity)>()(sites.complex_heterozygosity));\n    return result;\n}\n\nbool CoalescentModel::SegregatingSiteCountsWithIndelHeterozygositiesEqual::operator()(const SegregatingSiteCountsWithIndelHeterozygosities& lhs, const SegregatingSiteCountsWithIndelHeterozygosities& rhs) const noexcept\n{\n    return lhs.counts == rhs.counts && lhs.repeat_heterozygosity == rhs.repeat_heterozygosity && lhs.complex_heterozygosity == rhs.complex_heterozygosity;\n}\n\n} // namespace octopus\n", "meta": {"hexsha": "9b954c05b036b9f70b277c5f8969e16525630a34", "size": 15069, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/models/mutation/coalescent_model.cpp", "max_stars_repo_name": "Schaudge/octopus", "max_stars_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T16:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:59:32.000Z", "max_issues_repo_path": "src/core/models/mutation/coalescent_model.cpp", "max_issues_repo_name": "Schaudge/octopus", "max_issues_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T14:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:59:58.000Z", "max_forks_repo_path": "src/core/models/mutation/coalescent_model.cpp", "max_forks_repo_name": "Schaudge/octopus", "max_forks_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-10-28T22:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:28:43.000Z", "avg_line_length": 39.5511811024, "max_line_length": 218, "alphanum_fraction": 0.6937421196, "num_tokens": 3959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.24240788932830792}}
{"text": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include \"Molassembler/Interpret.h\"\n\n#include \"Utils/Geometry/AtomCollection.h\"\n#include \"Utils/Bonds/BondOrderCollection.h\"\n\n#include \"Molassembler/BondOrders.h\"\n#include \"Molassembler/Detail/Cartesian.h\"\n#include \"Molassembler/Graph.h\"\n#include \"Molassembler/Graph/GraphAlgorithms.h\"\n#include \"Molassembler/Graph/PrivateGraph.h\"\n#include \"Molassembler/Molecule.h\"\n#include \"Molassembler/Shapes/ContinuousMeasures.h\"\n#include \"Molassembler/Temple/Adaptors/AllPairs.h\"\n#include \"Molassembler/Temple/Functional.h\"\n#include \"Molassembler/Temple/Optionals.h\"\n\n#include <Eigen/Geometry>\n\nnamespace Scine {\nnamespace Molassembler {\nnamespace Interpret {\nnamespace {\n\nUtils::PositionCollection paste(const std::vector<Utils::Position>& positions) {\n  const unsigned N = positions.size();\n  auto matrix = Utils::PositionCollection(N, 3);\n  for(unsigned i = 0; i < N; ++i) {\n    matrix.row(i) = positions.at(i);\n  }\n  return matrix;\n}\n\ndouble vectorAngle(const Eigen::Vector3d& a, const Eigen::Vector3d& b) {\n  return std::acos(\n    a.dot(b) / (\n      a.norm() * b.norm()\n    )\n  );\n}\n\nstruct HapticPlaneGeometry {\n  double angle;\n  double rmsd;\n};\n\nHapticPlaneGeometry hapticPlaneGeometry(\n  const std::vector<Utils::Position>& positions,\n  const AtomIndex v,\n  const std::vector<AtomIndex>& site\n) {\n  const unsigned siteSize = site.size();\n\n  assert(siteSize >= 1 && \"Passed hapticPlaneGeometry a non-haptic site!\");\n\n  Eigen::Vector3d siteCentroid = Eigen::Vector3d::Zero();\n  for(AtomIndex siteAtom : site) {\n    siteCentroid += positions.at(siteAtom);\n  }\n  siteCentroid /= siteSize;\n\n  if(siteSize == 2) {\n    const double frontAngle = Cartesian::angle(\n      positions.at(v),\n      siteCentroid,\n      positions.at(site.front())\n    );\n    const double backAngle = Cartesian::angle(\n      positions.at(v),\n      siteCentroid,\n      positions.at(site.back())\n    );\n\n    return HapticPlaneGeometry {\n      M_PI / 2.0 - std::min(frontAngle, backAngle),\n      0.0\n    };\n  }\n\n  const Eigen::Vector3d centroidAxis = siteCentroid - positions.at(v).transpose();\n\n  Utils::PositionCollection hapticAtoms(siteSize, 3);\n  for(unsigned i = 0; i < siteSize; ++i) {\n    hapticAtoms.row(i) = positions.at(site.at(i));\n  }\n  const auto plane = Cartesian::planeOfBestFit(hapticAtoms);\n  const double firstAngle = vectorAngle(plane.normal(), centroidAxis);\n  const double secondAngle = vectorAngle(plane.normal(), -centroidAxis);\n  return HapticPlaneGeometry {\n    std::min(firstAngle, secondAngle),\n    Cartesian::planeRmsd(plane, hapticAtoms, Temple::iota<AtomIndex>(siteSize))\n  };\n}\n\nboost::optional<double> minimumClassificationProbability(\n  const PrivateGraph& graph,\n  const std::vector<Utils::Position>& positions,\n  const AtomIndex v\n) {\n  auto sites = GraphAlgorithms::sites(graph, v);\n  if(sites.size() <= 1) {\n    return boost::none;\n  }\n\n  const unsigned S = sites.size();\n  Eigen::Matrix<double, 3, Eigen::Dynamic> sitePositions(3, S + 1);\n  for(unsigned i = 0; i < S; ++i) {\n    Eigen::Vector3d averagePosition = Eigen::Vector3d::Zero();\n    for(unsigned j : sites[i]) {\n      averagePosition += positions.at(j);\n    }\n    sitePositions.col(i) = averagePosition / sites[i].size();\n  }\n  sitePositions.col(S) = positions.at(v);\n\n  auto normalizedPositions = Shapes::Continuous::normalize(sitePositions);\n\n  // Classify all suitable shapes\n  std::vector<Shapes::Shape> viableShapes;\n  for(const Shapes::Shape shape : Shapes::allShapes) {\n    if(Shapes::size(shape) == S) {\n      viableShapes.push_back(shape);\n    }\n  }\n\n  const auto classifications = Temple::map(viableShapes,\n    [&](const Shapes::Shape shape) -> boost::optional<double> {\n      const double measure = Shapes::Continuous::shapeCentroidLast(normalizedPositions, shape).measure;\n      return Shapes::Continuous::probabilityRandomCloud(measure, shape);\n    }\n  );\n\n  if(Temple::all_of(classifications)) {\n    const double minimumProbability = std::min_element(\n      std::begin(classifications),\n      std::end(classifications),\n      [](const auto& a, const auto& b) -> bool {\n        return a.value() < b.value();\n      }\n    )->value();\n\n    return minimumProbability;\n  }\n\n  return boost::none;\n}\n\nstruct BestRemovals {\n  std::vector<AtomIndex> removals;\n  double certainty;\n};\n\nboost::optional<BestRemovals> bestRemovalFromHapticSite(\n  const PrivateGraph& graph,\n  const std::vector<Utils::Position>& positions,\n  const AtomIndex v,\n  const std::vector<std::vector<AtomIndex>>& sites,\n  const unsigned hapticSiteIndex\n) {\n  const unsigned S = sites.size();\n  const std::vector<AtomIndex>& hapticSite = sites.at(hapticSiteIndex);\n  const unsigned hapticSiteSize = hapticSite.size();\n  return Temple::accumulate(\n    hapticSite,\n    boost::optional<BestRemovals>(boost::none),\n    [&](const auto& carry, const AtomIndex siteVertexToRemove) -> boost::optional<BestRemovals> {\n      auto graphCopy = graph;\n      graphCopy.removeEdge(graphCopy.edge(v, siteVertexToRemove));\n      GraphAlgorithms::updateEtaBonds(graphCopy);\n      const auto newSites = GraphAlgorithms::sites(graphCopy, v);\n\n      /* Possible effects of bond removal\n       * - Separating a haptic ligand into two single-atom ligands,\n       *   changing shapes\n       *   - recognizable by size change\n       *   - accept if new certainty is low or significantly\n       *     lower than old (factor 0.5)\n       * - Improves the haptic plane angle by removing a bad bond\n       *   - recognized by matching sites and comparing angles\n       *   - accept if angle halves\n       *\n       * How to compare cases?\n       */\n      if(newSites.size() > S) {\n        const auto priorCertainty = minimumClassificationProbability(graph, positions, v);\n        const auto posteriorCertainty = minimumClassificationProbability(graphCopy, positions, v);\n\n        if(priorCertainty && posteriorCertainty) {\n          if(\n            posteriorCertainty.value() <= 0.01\n            || posteriorCertainty.value() <= 0.5 * priorCertainty.value()\n          ) {\n            return BestRemovals {{siteVertexToRemove}, 1 - *posteriorCertainty};\n          }\n        }\n      } else {\n        const auto siteFindIter = Temple::find_if(\n          newSites,\n          [&](const auto& newSite) -> bool {\n            if(newSite.size() != hapticSiteSize - 1) {\n              return false;\n            }\n\n            // Match all vertices except the one to remove\n            for(const AtomIndex oldSiteAtomIndex : hapticSite) {\n              if(oldSiteAtomIndex == siteVertexToRemove) {\n                continue;\n              }\n\n              if(Temple::find(newSite, oldSiteAtomIndex) == std::end(newSite)) {\n                return false;\n              }\n            }\n\n            return true;\n          }\n        );\n\n        if(siteFindIter != std::end(newSites)) {\n          const double newHapticAngle = hapticPlaneGeometry(positions, v, *siteFindIter).angle;\n          const double newHapticAngleCertainty = 1 - newHapticAngle * 2 / M_PI;\n          const double carryCertainty = Temple::Optionals::map(carry,\n            [](const auto& removal) { return removal.certainty; }\n          ).value_or(0.0);\n          if(newHapticAngleCertainty > carryCertainty) {\n            return BestRemovals {{siteVertexToRemove}, newHapticAngleCertainty};\n          }\n        }\n      }\n\n      return carry;\n    }\n  );\n}\n\n} // namespace\n\nstd::vector<std::vector<unsigned>> ComponentMap::invert() const {\n  const unsigned nComponents = *std::max_element(\n    std::begin(map),\n    std::end(map)\n  ) + 1;\n\n  std::vector<\n    std::vector<unsigned>\n  > inverseMaps (nComponents);\n\n  const unsigned N = map.size();\n  for(unsigned i = 0; i < N; ++i) {\n    inverseMaps.at(map.at(i)).push_back(i);\n  }\n\n  return inverseMaps;\n}\n\nstd::vector<Utils::AtomCollection> ComponentMap::apply(\n  const Utils::AtomCollection& atomCollection\n) const {\n  const unsigned nComponents = *std::max_element(\n    std::begin(map),\n    std::end(map)\n  ) + 1;\n  std::vector<unsigned> componentSizes(nComponents, 0);\n  for(unsigned i : map) {\n    componentSizes.at(i) += 1;\n  }\n\n  /* Allocate the collections */\n  std::vector<Utils::AtomCollection> collections = Temple::map(\n    componentSizes,\n    [](const unsigned size) { return Utils::AtomCollection(size); }\n  );\n  std::vector<unsigned> collectionSizeCount(nComponents, 0);\n\n  for(unsigned i = 0; i < map.size(); ++i) {\n    unsigned moleculeIndex = map.at(i);\n    Utils::AtomCollection& collection = collections.at(moleculeIndex);\n    unsigned& collectionSize = collectionSizeCount.at(moleculeIndex);\n    collection.setElement(\n      collectionSize,\n      atomCollection.getElement(i)\n    );\n    collection.setPosition(\n      collectionSize,\n      atomCollection.getPosition(i)\n    );\n    ++collectionSize;\n  }\n\n  return collections;\n}\n\nComponentMap::ComponentIndexPair ComponentMap::apply(const unsigned index) const {\n  ComponentIndexPair pair;\n  pair.component = map.at(index);\n  pair.atomIndex = std::count(\n    std::begin(map),\n    std::begin(map) + index,\n    pair.component\n  );\n  return pair;\n}\n\nunsigned ComponentMap::invert(const ComponentIndexPair& pair) const {\n  unsigned count = 0;\n  const unsigned N = map.size();\n  for(unsigned i = 0; i < N; ++i) {\n    if(map[i] == pair.component) {\n      ++count;\n    }\n\n    if(count == pair.atomIndex + 1) {\n      return i;\n    }\n  }\n\n  throw std::out_of_range(\"No match found in component map!\");\n}\n\nstruct MoleculeParts {\n  PrivateGraph graph;\n  std::vector<Utils::Position> angstromPositions;\n  boost::optional<\n    std::vector<BondIndex>\n  > bondStereopermutatorCandidatesOptional;\n};\n\nstruct Parts {\n  std::vector<MoleculeParts> precursors;\n  ComponentMap componentMap;\n  unsigned nZeroLengthPositions = 0;\n};\n\n// Yields a graph structure without element type annotations\nPrivateGraph discretize(\n  const Utils::BondOrderCollection& bondOrders,\n  const BondDiscretizationOption discretization\n) {\n  const PrivateGraph::Vertex N = bondOrders.getSystemSize();\n  PrivateGraph graph {N};\n\n  if(discretization == BondDiscretizationOption::Binary) {\n    for(unsigned i = 0; i < N; ++i) {\n      for(unsigned j = i + 1; j < N; ++j) {\n        double bondOrder = bondOrders.getOrder(i, j);\n\n        if(bondOrder > 0.5) {\n          graph.addEdge(i, j, BondType::Single);\n        }\n      }\n    }\n  } else if(discretization == BondDiscretizationOption::RoundToNearest) {\n    for(unsigned i = 0; i < N; ++i) {\n      for(unsigned j = i + 1; j < N; ++j) {\n        double bondOrder = bondOrders.getOrder(i, j);\n\n        if(bondOrder > 0.5) {\n          auto bond = static_cast<BondType>(\n            std::round(bondOrder) - 1\n          );\n\n          if(bondOrder > 6.5) {\n            bond = BondType::Sextuple;\n          }\n\n          graph.addEdge(i, j, bond);\n        }\n      }\n    }\n  }\n\n  return graph;\n}\n\nParts construeParts(\n  const Utils::ElementTypeCollection& elements,\n  const AngstromPositions& angstromWrapper,\n  const Utils::BondOrderCollection& bondOrders,\n  const BondDiscretizationOption discretization,\n  const boost::optional<double>& stereopermutatorThreshold\n) {\n  const unsigned N = elements.size();\n\n  // Check preconditions\n  if(angstromWrapper.positions.rows() != N) {\n    throw std::invalid_argument(\n      \"Number of positions in angstrom wrapper do not match number of elements\"\n    );\n  }\n\n  if(bondOrders.getSystemSize<unsigned>() != N) {\n    throw std::invalid_argument(\n      \"Bond order argument system size does not match number of elements\"\n    );\n  }\n\n  PrivateGraph atomCollectionGraph = discretize(bondOrders, discretization);\n\n  Parts parts;\n  const unsigned numComponents = atomCollectionGraph.connectedComponents(parts.componentMap.map);\n  parts.precursors.resize(numComponents);\n\n  if(stereopermutatorThreshold) {\n    for(auto& precursor : parts.precursors) {\n      // Empty-vector-initialize the candidate optionals\n      precursor.bondStereopermutatorCandidatesOptional = std::vector<BondIndex> {};\n    }\n  }\n\n  // Map from original index to component index\n  std::vector<PrivateGraph::Vertex> indexInComponentMap (N);\n\n  /* Maybe\n   * - filtered_graph using predicate of componentMap number\n   * - copy_graph to new Graph keeping element types and bond orders\n   *\n   * - alternately, must keep a map of atomcollection index to precursor index\n   *   and new precursor atom index in order to transfer edges too\n   */\n\n  for(unsigned i = 0; i < N; ++i) {\n    auto& precursor = parts.precursors.at(\n      parts.componentMap.apply(i).component\n    );\n\n    // Add a new vertex with element information\n    PrivateGraph::Vertex newIndex = precursor.graph.addVertex(elements.at(i));\n\n    // Save new index in precursor graph\n    indexInComponentMap.at(i) = newIndex;\n\n    if(angstromWrapper.positions.row(i).norm() <= 1e-14) {\n      parts.nZeroLengthPositions += 1;\n    }\n\n    // Copy over position information\n    precursor.angstromPositions.emplace_back(\n      angstromWrapper.positions.row(i)\n    );\n  }\n\n  // Copy over edges and bond orders\n  for(const PrivateGraph::Edge& edge : atomCollectionGraph.edges()) {\n    const PrivateGraph::Vertex source = atomCollectionGraph.source(edge);\n    const PrivateGraph::Vertex target = atomCollectionGraph.target(edge);\n\n    // Both source and target are part of the same component (since they are bonded)\n    auto& precursor = parts.precursors.at(\n      parts.componentMap.apply(source).component\n    );\n\n    // Copy over the edge\n    precursor.graph.addEdge(\n      indexInComponentMap.at(source),\n      indexInComponentMap.at(target),\n      atomCollectionGraph.bondType(edge)\n    );\n\n    // If the edge's bond order exceeds the threshold optional\n    if(\n      stereopermutatorThreshold\n      && bondOrders.getOrder(source, target) >= *stereopermutatorThreshold\n    ) {\n      precursor.bondStereopermutatorCandidatesOptional->emplace_back(\n        indexInComponentMap.at(source),\n        indexInComponentMap.at(target)\n      );\n    }\n  }\n\n  return parts;\n}\n\nMoleculesResult molecules(\n  const Utils::ElementTypeCollection& elements,\n  const AngstromPositions& angstromWrapper,\n  const Utils::BondOrderCollection& bondOrders,\n  const BondDiscretizationOption discretization,\n  const boost::optional<double>& stereopermutatorThreshold\n) {\n  Parts parts = construeParts(\n    elements,\n    angstromWrapper,\n    bondOrders,\n    discretization,\n    stereopermutatorThreshold\n  );\n\n  // Collect results\n  MoleculesResult result;\n\n  /* Transform precursors into Molecules. Positions may only be used if there\n   * is at most one position very close to (0, 0, 0). Otherwise, we assume that\n   * the given positions are faulty or no positional information is present,\n   * and only the graph is used to create the Molecules.\n   */\n  if(parts.nZeroLengthPositions < 2) {\n    result.molecules.reserve(parts.precursors.size());\n    for(auto& precursor : parts.precursors) {\n      result.molecules.emplace_back(\n        Graph {std::move(precursor.graph)},\n        AngstromPositions(paste(precursor.angstromPositions), LengthUnit::Angstrom),\n        precursor.bondStereopermutatorCandidatesOptional\n      );\n    }\n  } else {\n    result.molecules.reserve(parts.precursors.size());\n    for(auto& precursor : parts.precursors) {\n      result.molecules.emplace_back(\n        Graph {std::move(precursor.graph)}\n      );\n    }\n  }\n\n  result.componentMap = std::move(parts.componentMap);\n\n  return result;\n}\n\nMoleculesResult molecules(\n  const Utils::ElementTypeCollection& elements,\n  const AngstromPositions& angstromWrapper,\n  const BondDiscretizationOption discretization,\n  const boost::optional<double>& stereopermutatorThreshold\n) {\n  return molecules(\n    elements,\n    angstromWrapper,\n    uffBondOrders(elements, angstromWrapper),\n    discretization,\n    stereopermutatorThreshold\n  );\n}\n\nMoleculesResult molecules(\n  const Utils::AtomCollection& atomCollection,\n  const Utils::BondOrderCollection& bondOrders,\n  const BondDiscretizationOption discretization,\n  const boost::optional<double>& stereopermutatorThreshold\n) {\n  return molecules(\n    atomCollection.getElements(),\n    AngstromPositions {atomCollection.getPositions(), LengthUnit::Bohr},\n    bondOrders,\n    discretization,\n    stereopermutatorThreshold\n  );\n}\n\nMoleculesResult molecules(\n  const Utils::AtomCollection& atomCollection,\n  const BondDiscretizationOption discretization,\n  const boost::optional<double>& stereopermutatorThreshold\n) {\n  AngstromPositions angstromWrapper {atomCollection.getPositions(), LengthUnit::Bohr};\n\n  return molecules(\n    atomCollection.getElements(),\n    angstromWrapper,\n    uffBondOrders(atomCollection.getElements(), angstromWrapper),\n    discretization,\n    stereopermutatorThreshold\n  );\n}\n\nGraphsResult graphs(\n  const Utils::ElementTypeCollection& elements,\n  const AngstromPositions& angstromWrapper,\n  const Utils::BondOrderCollection& bondOrders,\n  BondDiscretizationOption discretization\n) {\n  Parts parts = construeParts(\n    elements,\n    angstromWrapper,\n    bondOrders,\n    discretization,\n    boost::none\n  );\n\n  GraphsResult result;\n  result.graphs.reserve(parts.precursors.size());\n  for(auto& precursor : parts.precursors) {\n    result.graphs.emplace_back(std::move(precursor.graph));\n  }\n  result.componentMap = std::move(parts.componentMap);\n  return result;\n}\n\nGraphsResult graphs(\n  const Utils::AtomCollection& atomCollection,\n  const Utils::BondOrderCollection& bondOrders,\n  BondDiscretizationOption discretization\n) {\n  return graphs(\n    atomCollection.getElements(),\n    AngstromPositions {atomCollection.getPositions(), LengthUnit::Bohr},\n    bondOrders,\n    discretization\n  );\n}\n\nstd::vector<FalsePositive> uncertainBonds(\n  const Utils::AtomCollection& atomCollection,\n  const Utils::BondOrderCollection& bondOrders\n) {\n  std::vector<FalsePositive> falsePositives;\n\n  Parts parts = construeParts(\n    atomCollection.getElements(),\n    AngstromPositions {atomCollection.getPositions(), LengthUnit::Bohr},\n    bondOrders,\n    BondDiscretizationOption::Binary,\n    boost::none\n  );\n\n  for(unsigned component = 0; component < parts.precursors.size(); ++component) {\n    MoleculeParts& part = parts.precursors[component];\n    GraphAlgorithms::updateEtaBonds(part.graph);\n\n    std::vector<std::pair<PrivateGraph::Vertex, double>> sketchyClassifications;\n\n    for(const PrivateGraph::Vertex v : part.graph.vertices()) {\n      /* Detect high uncertainty shape classifications. Adjacent pairs with high\n       * uncertainties are candidates for false positives.\n       */\n      auto classificationUncertainty = minimumClassificationProbability(part.graph, part.angstromPositions, v);\n      if(classificationUncertainty && *classificationUncertainty >= 0.5) {\n        sketchyClassifications.emplace_back(v, *classificationUncertainty);\n      }\n    }\n\n    // NOTE: Cannot remove bonds with overlapping constituent atoms!\n    for(const auto& sketchyPair : Temple::Adaptors::allPairs(sketchyClassifications)) {\n      const unsigned i = sketchyPair.first.first;\n      const unsigned j = sketchyPair.second.first;\n      const double i_random = sketchyPair.first.second;\n      const double j_random = sketchyPair.second.second;\n\n      if(part.graph.edgeOption(i, j)) {\n        falsePositives.push_back(\n          FalsePositive {\n            parts.componentMap.invert(ComponentMap::ComponentIndexPair {component, i}),\n            parts.componentMap.invert(ComponentMap::ComponentIndexPair {component, j}),\n            i_random * j_random\n          }\n        );\n      }\n    }\n  }\n\n  return falsePositives;\n}\n\nstd::vector<FalsePositive> badHapticLigandBonds(\n  const Utils::AtomCollection& atomCollection,\n  const Utils::BondOrderCollection& bondOrders\n) {\n  std::vector<FalsePositive> falsePositives;\n\n  // Avoid duplicate bonds in list with reverse i-j\n  auto addFalsePositive = [&](unsigned i, unsigned j, double p) {\n    if(i > j) {\n      std::swap(i, j);\n    }\n    auto findIter = std::find_if(\n      std::begin(falsePositives),\n      std::end(falsePositives),\n      [=](const FalsePositive& fp) -> bool {\n        return fp.i == i && fp.j == j;\n      }\n    );\n    if(findIter == std::end(falsePositives)) {\n      falsePositives.push_back(FalsePositive {i, j, p});\n    }\n  };\n\n  Parts parts = construeParts(\n    atomCollection.getElements(),\n    AngstromPositions {atomCollection.getPositions(), LengthUnit::Bohr},\n    bondOrders,\n    BondDiscretizationOption::Binary,\n    boost::none\n  );\n\n  for(unsigned component = 0; component < parts.precursors.size(); ++component) {\n    MoleculeParts& part = parts.precursors[component];\n    GraphAlgorithms::updateEtaBonds(part.graph);\n\n    for(const PrivateGraph::Vertex v : part.graph.vertices()) {\n      /* Detect haptic shape planes with large angles to the axis defined by the\n       * site position and the central atom or with high rms deviations on\n       * their plane fit\n       */\n      const auto sites = GraphAlgorithms::sites(part.graph, v);\n      const unsigned S = sites.size();\n      for(unsigned siteIndex = 0; siteIndex < S; ++siteIndex) {\n        const auto& site = sites.at(siteIndex);\n        const unsigned siteSize = site.size();\n        if(siteSize == 1) {\n          continue;\n        }\n\n        const auto geometry = hapticPlaneGeometry(part.angstromPositions, v, site);\n\n        // Less than 30° and a good plane fit indicate the haptic site is fine\n        if(geometry.angle < M_PI / 6 && geometry.rmsd < 0.2) {\n          continue;\n        }\n\n        if(siteSize == 2) {\n          // Suggest the vertex further from the center\n          const double frontDistance = (\n            part.angstromPositions.at(v)\n            - part.angstromPositions.at(site.front())\n          ).norm();\n          const double backDistance = (\n            part.angstromPositions.at(v)\n            - part.angstromPositions.at(site.back())\n          ).norm();\n          const AtomIndex toRemove = frontDistance < backDistance ? site.back() : site.front();\n          addFalsePositive(\n            parts.componentMap.invert(\n              ComponentMap::ComponentIndexPair {component, v}\n            ),\n            parts.componentMap.invert(\n              ComponentMap::ComponentIndexPair {component, toRemove}\n            ),\n            geometry.angle * 2 / M_PI\n          );\n        } else {\n          const auto suggestedRemovalOption = bestRemovalFromHapticSite(\n            part.graph,\n            part.angstromPositions,\n            v,\n            sites,\n            siteIndex\n          );\n          if(suggestedRemovalOption) {\n            for(const AtomIndex w : suggestedRemovalOption->removals) {\n              addFalsePositive(\n                parts.componentMap.invert(\n                  ComponentMap::ComponentIndexPair {component, v}\n                ),\n                parts.componentMap.invert(\n                  ComponentMap::ComponentIndexPair {component, w}\n                ),\n                suggestedRemovalOption->certainty\n              );\n            }\n          }\n        }\n      }\n    }\n  }\n  return falsePositives;\n}\n\nUtils::BondOrderCollection removeFalsePositives(\n  const Utils::AtomCollection& atoms,\n  Utils::BondOrderCollection bonds\n) {\n  // First do bad haptic bond orders\n  auto haptics = badHapticLigandBonds(atoms, bonds);\n  while(!haptics.empty()) {\n    Temple::sort(haptics);\n    FalsePositive& mostLikely = haptics.back();\n    bonds.setOrder(mostLikely.i, mostLikely.j, 0.0);\n    haptics = badHapticLigandBonds(atoms, bonds);\n  }\n\n  // Then do uncertain bonds\n  auto uncertains = uncertainBonds(atoms, bonds);\n  while(!uncertains.empty()) {\n    Temple::sort(uncertains);\n    FalsePositive& mostLikely = uncertains.back();\n    bonds.setOrder(mostLikely.i, mostLikely.j, 0.0);\n    uncertains = uncertainBonds(atoms, bonds);\n  }\n\n  return bonds;\n}\n\n} // namespace Interpret\n} // namespace Molassembler\n} // namespace Scine\n", "meta": {"hexsha": "036ca3a450456e94927488318cf1eaafaee74a3b", "size": 23939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Molassembler/Interpret.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Molassembler/Interpret.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Molassembler/Interpret.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2642225032, "max_line_length": 111, "alphanum_fraction": 0.67220853, "num_tokens": 5711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3849121303722487, "lm_q1q2_score": 0.24240788044112735}}
{"text": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <orea/aggregation/staticcreditxvacalculator.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/error_of_mean.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\n\nusing namespace boost::accumulators;\n\nnamespace ore {\nnamespace analytics {\n\nStaticCreditXvaCalculator::StaticCreditXvaCalculator(\n    const boost::shared_ptr<Portfolio> portfolio, const boost::shared_ptr<Market> market,\n    const string& configuration, const string& baseCurrency, const string& dvaName,\n    const string& fvaBorrowingCurve, const string& fvaLendingCurve,\n    const bool applyDynamicInitialMargin,\n    const boost::shared_ptr<DynamicInitialMarginCalculator> dimCalculator,\n    const boost::shared_ptr<NPVCube> tradeExposureCube,\n    const boost::shared_ptr<NPVCube> nettingSetExposureCube,\n    const Size tradeEpeIndex, const Size tradeEneIndex, \n    const Size nettingSetEpeIndex, const Size nettingSetEneIndex,\n    const bool flipViewXVA, const string& flipViewBorrowingCurvePostfix, const string& flipViewLendingCurvePostfix)\n    : ValueAdjustmentCalculator(portfolio, market, configuration, baseCurrency, dvaName,\n                                fvaBorrowingCurve, fvaLendingCurve, applyDynamicInitialMargin,\n                                dimCalculator, tradeExposureCube, nettingSetExposureCube, tradeEpeIndex, tradeEneIndex, \n                                nettingSetEpeIndex, nettingSetEneIndex, \n                                flipViewXVA, flipViewBorrowingCurvePostfix, flipViewLendingCurvePostfix) {\n    for (Size i = 0; i < dates().size(); i++) {\n        dateIndexMap_.emplace(dates()[i], i);\n    }\n}\n\n\nconst Real StaticCreditXvaCalculator::calculateCvaIncrement(\n    const string& tid, const string& cid, const Date& d0, const Date& d1, const Real& rr) {\n    Handle<DefaultProbabilityTermStructure> dts = market_->defaultCurve(cid, configuration_);\n    QL_REQUIRE(!dts.empty(), \"Default curve missing for counterparty \" << cid);\n    Real increment = 0.0;\n    Real s0 = dts->survivalProbability(d0);\n    Real s1 = dts->survivalProbability(d1);\n    Real epe = tradeExposureCube_->get(tid, d1, 0, tradeEpeIndex_);\n    increment = (1.0 - rr) * (s0 - s1) * epe;\n    return increment;\n}\n\nconst Real StaticCreditXvaCalculator::calculateDvaIncrement(\n    const string& tid, const Date& d0, const Date& d1, const Real& rr) {\n    Handle<DefaultProbabilityTermStructure> dts = market_->defaultCurve(dvaName_, configuration_);\n    QL_REQUIRE(!dts.empty(), \"Default curve missing for counterparty \" << dvaName_);\n    Real increment = 0.0;\n    Real s0 = dts->survivalProbability(d0);\n    Real s1 = dts->survivalProbability(d1);\n    Real ene = tradeExposureCube_->get(tid, d1, 0, tradeEneIndex_);\n    increment = (1.0 - rr) * (s0 - s1) * ene;\n    return increment;\n}\n\nconst Real StaticCreditXvaCalculator::calculateNettingSetCvaIncrement(\n    const string& nid, const string& cid, const Date& d0, const Date& d1, const Real& rr) {\n    Handle<DefaultProbabilityTermStructure> dts = market_->defaultCurve(cid, configuration_);\n    QL_REQUIRE(!dts.empty(), \"Default curve missing for counterparty \" << cid);\n    Real increment = 0.0;\n    Real s0 = dts->survivalProbability(d0);\n    Real s1 = dts->survivalProbability(d1);\n    Real epe = nettingSetExposureCube_->get(nid, d1, 0, nettingSetEpeIndex_);\n    increment = (1.0 - rr) * (s0 - s1) * epe;\n    return increment;\n}\n\nconst Real StaticCreditXvaCalculator::calculateNettingSetDvaIncrement(\n    const string& nid, const Date& d0, const Date& d1, const Real& rr) {\n    Handle<DefaultProbabilityTermStructure> dts = market_->defaultCurve(dvaName_, configuration_);\n    QL_REQUIRE(!dts.empty(), \"Default curve missing for counterparty \" << dvaName_);\n    Real increment = 0.0;\n    Real s0 = dts->survivalProbability(d0);\n    Real s1 = dts->survivalProbability(d1);\n    Real ene = nettingSetExposureCube_->get(nid, d1, 0, nettingSetEneIndex_);\n    increment = (1.0 - rr) * (s0 - s1) * ene;\n    return increment;\n}\n\nconst Real StaticCreditXvaCalculator::calculateFbaIncrement(\n    const string& tid, const string& cid, const string& dvaName,\n    const Date& d0, const Date& d1, const Real& dcf) {\n    Handle<DefaultProbabilityTermStructure> dts_cid;\n    Handle<DefaultProbabilityTermStructure> dts_dvaName;\n    if (cid != \"\") {\n        dts_cid = market_->defaultCurve(cid, configuration_);\n        QL_REQUIRE(!dts_cid.empty(), \"Default curve missing for counterparty \" << cid);\n    }\n    if (dvaName != \"\") {\n        dts_dvaName = market_->defaultCurve(dvaName, configuration_);\n        QL_REQUIRE(!dts_dvaName.empty(), \"Default curve missing for counterparty \" << cid);\n    }\n\n    Real increment = 0.0;\n    Real s0 = cid == \"\" ? 1.0 : dts_cid->survivalProbability(d0);\n    Real s1 = dvaName == \"\" ? 1.0 : dts_dvaName->survivalProbability(d0);\n    Real ene = tradeExposureCube_->get(tid, d1, 0, tradeEneIndex_);\n    increment = s0 * s1 * ene * dcf;\n    return increment;\n}\n\nconst Real StaticCreditXvaCalculator::calculateFcaIncrement(\n    const string& tid, const string& cid, const string& dvaName,\n    const Date& d0, const Date& d1, const Real& dcf) {\n    Handle<DefaultProbabilityTermStructure> dts_cid;\n    Handle<DefaultProbabilityTermStructure> dts_dvaName;\n    if (cid != \"\") {\n        dts_cid = market_->defaultCurve(cid, configuration_);\n        QL_REQUIRE(!dts_cid.empty(), \"Default curve missing for counterparty \" << cid);\n    }\n    if (dvaName != \"\") {\n        dts_dvaName = market_->defaultCurve(dvaName, configuration_);\n        QL_REQUIRE(!dts_dvaName.empty(), \"Default curve missing for counterparty \" << cid);\n    }\n\n    Real increment = 0.0;\n    Real s0 = cid == \"\" ? 1.0 : dts_cid->survivalProbability(d0);\n    Real s1 = dvaName == \"\" ? 1.0 : dts_dvaName->survivalProbability(d0);\n    Real epe = tradeExposureCube_->get(tid, d1, 0, tradeEpeIndex_);\n    increment = s0 * s1 * epe * dcf;\n    return increment;\n}\n\nconst Real StaticCreditXvaCalculator::calculateNettingSetFbaIncrement(\n    const string& nid, const string& cid, const string& dvaName,\n    const Date& d0, const Date& d1, const Real& dcf) {\n    Handle<DefaultProbabilityTermStructure> dts_cid;\n    Handle<DefaultProbabilityTermStructure> dts_dvaName;\n    if (cid != \"\") {\n        dts_cid = market_->defaultCurve(cid, configuration_);\n        QL_REQUIRE(!dts_cid.empty(), \"Default curve missing for counterparty \" << cid);\n    }\n    if (dvaName != \"\") {\n        dts_dvaName = market_->defaultCurve(dvaName, configuration_);\n        QL_REQUIRE(!dts_dvaName.empty(), \"Default curve missing for counterparty \" << cid);\n    }\n\n    Real increment = 0.0;\n    Real s0 = cid == \"\" ? 1.0 : dts_cid->survivalProbability(d0);\n    Real s1 = dvaName == \"\" ? 1.0 : dts_dvaName->survivalProbability(d0);\n    Real ene = nettingSetExposureCube_->get(nid, d1, 0, nettingSetEneIndex_);\n    increment = s0 * s1 * ene * dcf;\n    return increment;\n}\n\nconst Real StaticCreditXvaCalculator::calculateNettingSetFcaIncrement(\n    const string& nid, const string& cid, const string& dvaName,\n    const Date& d0, const Date& d1, const Real& dcf) {\n    Handle<DefaultProbabilityTermStructure> dts_cid;\n    Handle<DefaultProbabilityTermStructure> dts_dvaName;\n    if (cid != \"\") {\n        dts_cid = market_->defaultCurve(cid, configuration_);\n        QL_REQUIRE(!dts_cid.empty(), \"Default curve missing for counterparty \" << cid);\n    }\n    if (dvaName != \"\") {\n        dts_dvaName = market_->defaultCurve(dvaName, configuration_);\n        QL_REQUIRE(!dts_dvaName.empty(), \"Default curve missing for counterparty \" << cid);\n    }\n\n    Real increment = 0.0;\n    Real s0 = cid == \"\" ? 1.0 : dts_cid->survivalProbability(d0);\n    Real s1 = dvaName == \"\" ? 1.0 : dts_dvaName->survivalProbability(d0);\n    Real epe = nettingSetExposureCube_->get(nid, d1, 0, nettingSetEpeIndex_);\n    increment = s0 * s1 * epe * dcf;\n    return increment;\n}\n\nconst Real StaticCreditXvaCalculator::calculateNettingSetMvaIncrement(\n    const string& nid, const string& cid, const Date& d0, const Date& d1, const Real& dcf) {\n    Handle<DefaultProbabilityTermStructure> dts_cid = market_->defaultCurve(cid, configuration_);\n    QL_REQUIRE(cid == \"\" || !dts_cid.empty(), \"Default curve missing for counterparty \" << cid);\n    Handle<DefaultProbabilityTermStructure> dts_dvaName = market_->defaultCurve(dvaName_, configuration_);\n    QL_REQUIRE(dvaName_ == \"\" || !dts_dvaName.empty(), \"Default curve missing for counterparty \" << dvaName_);\n\n    Real increment = 0.0;\n    Real s0 = cid == \"\" ? 1.0 : dts_cid->survivalProbability(d0);\n    Real s1 = dvaName_ == \"\" ? 1.0 : dts_dvaName->survivalProbability(d0);\n    increment = s0 * s1 * dimCalculator_->expectedIM(nid)[dateIndexMap_[d1]] * dcf;\n    return increment;\n}\n\n} // namespace analytics\n} // namespace ore\n", "meta": {"hexsha": "948bb2818df45c5a06d2b025ad6ab33c22644137", "size": 9612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/orea/aggregation/staticcreditxvacalculator.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "OREAnalytics/orea/aggregation/staticcreditxvacalculator.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "OREAnalytics/orea/aggregation/staticcreditxvacalculator.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 46.2115384615, "max_line_length": 120, "alphanum_fraction": 0.7059925094, "num_tokens": 2653, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.24219608720751604}}
{"text": "/*\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n\n#ifndef KINDR_ROTATIONS_EIGEN_EULERANGLESZYX_HPP_\n#define KINDR_ROTATIONS_EIGEN_EULERANGLESZYX_HPP_\n\n#include <cmath>\n\n#include <Eigen/Geometry>\n\n#include \"kindr/common/common.hpp\"\n#include \"kindr/common/assert_macros_eigen.hpp\"\n#include \"kindr/rotations/RotationBase.hpp\"\n#include \"kindr/rotations/eigen/RotationEigenFunctions.hpp\"\n\n\nnamespace kindr {\nnamespace rotations {\nnamespace eigen_impl {\n\n\n/*! \\class EulerAnglesZyx\n *  \\brief Implementation of Euler angles (Z-Y'-X'' / yaw-pitch-roll) rotation based on Eigen::Matrix<Scalar, 3, 1>\n *\n *  The following typedefs are provided for convenience:\n *   - \\ref eigen_impl::EulerAnglesZyxAD \"EulerAnglesZyxAD\" for active rotation and double primitive type\n *   - \\ref eigen_impl::EulerAnglesZyxAF \"EulerAnglesZyxAF\" for active rotation and float primitive type\n *   - \\ref eigen_impl::EulerAnglesZyxPD \"EulerAnglesZyxPD\" for passive rotation and double primitive type\n *   - \\ref eigen_impl::EulerAnglesZyxPF \"EulerAnglesZyxPF\" for passive rotation and float primitive type\n *   - EulerAnglesYprAD = EulerAnglesZyxAD\n *   - EulerAnglesYprAF = EulerAnglesZyxAF\n *   - EulerAnglesYprPD = EulerAnglesZyxPD\n *   - EulerAnglesYprPF = EulerAnglesZyxPF\n *\n *  \\tparam PrimType_ the primitive type of the data (double or float)\n *  \\tparam Usage_ the rotation usage which is either active or passive\n *  \\ingroup rotations\n */\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass EulerAnglesZyx : public EulerAnglesZyxBase<EulerAnglesZyx<PrimType_, Usage_>, Usage_> {\n private:\n  /*! \\brief The base type.\n   */\n  typedef Eigen::Matrix<PrimType_, 3, 1> Base;\n\n  /*! \\brief vector of Euler angles [yaw; pitch; roll]\n   */\n  Base zyx_;\n public:\n  /*! \\brief The implementation type.\n   *  The implementation type is always an Eigen object.\n   */\n  typedef Base Implementation;\n  /*! \\brief The primitive type.\n   *  Float/Double\n   */\n  typedef PrimType_ Scalar;\n\n  /*! \\brief Euler angles as 3x1-matrix\n   */\n  typedef Base Vector;\n\n  /*! \\brief Default constructor using identity rotation.\n   */\n  EulerAnglesZyx()\n    : zyx_(Base::Zero()) {\n  }\n\n  /*! \\brief Constructor using three scalars.\n   *  \\param yaw      first rotation angle around Z axis\n   *  \\param pitch    second rotation angle around Y' axis\n   *  \\param roll     third rotation angle around X'' axis\n   */\n  EulerAnglesZyx(Scalar yaw, Scalar pitch, Scalar roll)\n    : zyx_(yaw,pitch,roll) {\n  }\n\n  /*! \\brief Constructor using Eigen::Matrix.\n   *  \\param other   Eigen::Matrix<PrimType_,3,1> [roll; pitch; yaw]\n   */\n  explicit EulerAnglesZyx(const Base& other)\n    : zyx_(other) {\n  }\n\n  /*! \\brief Constructor using another rotation.\n   *  \\param other   other rotation\n   */\n  template<typename OtherDerived_>\n  inline explicit EulerAnglesZyx(const RotationBase<OtherDerived_, Usage_>& other)\n    : zyx_(internal::ConversionTraits<EulerAnglesZyx, OtherDerived_>::convert(other.derived()).toImplementation()) {\n  }\n\n  /*! \\brief Assignment operator using another rotation.\n   *  \\param other   other rotation\n   *  \\returns referece\n   */\n  template<typename OtherDerived_>\n  EulerAnglesZyx& operator =(const RotationBase<OtherDerived_, Usage_>& other) {\n    this->toImplementation() = internal::ConversionTraits<EulerAnglesZyx, OtherDerived_>::convert(other.derived()).toImplementation();\n    return *this;\n  }\n\n\n  /*! \\brief Parenthesis operator to convert from another rotation.\n   *  \\param other   other rotation\n   *  \\returns reference\n   */\n  template<typename OtherDerived_>\n  EulerAnglesZyx& operator ()(const RotationBase<OtherDerived_, Usage_>& other) {\n    this->toImplementation() = internal::ConversionTraits<EulerAnglesZyx, OtherDerived_>::convert(other.derived()).toImplementation();\n    return *this;\n  }\n\n  /*! \\brief Returns the inverse of the rotation.\n   *  \\returns the inverse of the rotation\n   */\n  EulerAnglesZyx inverted() const {\n    return EulerAnglesZyx(eigen_internal::getInverseYpr<PrimType_, PrimType_>(this->toImplementation()));\n  }\n\n  /*! \\brief Inverts the rotation.\n   *  \\returns reference\n   */\n  EulerAnglesZyx& invert() {\n    *this = this->inverted();\n    return *this;\n  }\n\n  /*! \\brief Returns the Euler angles in a vector.\n   *  \\returns  vector Eigen::Matrix<Scalar,3, 1>\n   */\n  inline const Vector vector() const {\n    return this->toImplementation();\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline Base& toImplementation() {\n    return static_cast<Base&>(zyx_);\n  }\n\n  /*! \\brief Cast to the implementation type.\n   *  \\returns the implementation for direct manipulation (recommended only for advanced users)\n   */\n  inline const Base& toImplementation() const {\n    return static_cast<const Base&>(zyx_);\n  }\n\n  /*! \\brief Gets yaw (Z) angle.\n   *  \\returns yaw angle (scalar)\n   */\n  inline Scalar yaw() const {\n    return zyx_(0);\n  }\n\n  /*! \\brief Gets pitch (Y') angle.\n   *  \\returns pitch angle (scalar)\n   */\n  inline Scalar pitch() const {\n    return zyx_(1);\n  }\n\n  /*! \\brief Gets roll (X'') angle.\n   *  \\returns roll angle (scalar)\n   */\n  inline Scalar roll() const {\n    return zyx_(2);\n  }\n\n  /*! \\brief Sets yaw (Z) angle.\n   */\n  inline void setYaw(Scalar yaw) {\n    zyx_(0) = yaw;\n  }\n\n  /*! \\brief Sets pitch (Y') angle.\n   */\n  inline void setPitch(Scalar pitch) {\n    zyx_(1) = pitch;\n  }\n\n  /*! \\brief Sets roll (X'') angle.\n   */\n  inline void setRoll(Scalar roll) {\n    zyx_(2) = roll;\n  }\n\n  /*! \\brief Reading access to yaw (Z) angle.\n   *  \\returns yaw angle (scalar) with reading access\n   */\n  inline Scalar z() const {\n    return zyx_(0);\n  }\n\n  /*! \\brief Reading access to pitch (Y') angle.\n   *  \\returns pitch angle (scalar) with reading access\n   */\n  inline Scalar y() const {\n    return zyx_(1);\n  }\n\n  /*! \\brief Reading access to roll (X'') angle.\n   *  \\returns roll angle (scalar) with reading access\n   */\n  inline Scalar x() const {\n    return zyx_(2);\n  }\n\n  /*! \\brief Writing access to yaw (Z) angle.\n   *  \\returns yaw angle (scalar) with writing access\n   */\n  inline void setZ(Scalar z) {\n    zyx_(0) = z;\n  }\n\n  /*! \\brief Writing access to pitch (Y') angle.\n   *  \\returns pitch angle (scalar) with writing access\n   */\n  inline void setY(Scalar y) {\n    zyx_(1) = y;\n  }\n\n  /*! \\brief Writing access to roll (X'') angle.\n   *  \\returns roll angle (scalar) with writing access\n   */\n  inline void setX(Scalar x) {\n    zyx_(2) = x;\n  }\n\n  /*! \\brief Sets the rotation to identity.\n   *  \\returns reference\n   */\n  EulerAnglesZyx& setIdentity() {\n    zyx_.setZero();\n    return *this;\n  }\n\n  /*! \\brief Returns a unique Euler angles rotation with angles in [-pi,pi),[-pi/2,pi/2),[-pi,pi).\n   *  This function is used to compare different rotations.\n   *  \\returns copy of the Euler angles rotation which is unique\n   */\n  EulerAnglesZyx getUnique() const {\n    Base zyx(kindr::common::floatingPointModulo(z()+M_PI,2*M_PI)-M_PI,\n             kindr::common::floatingPointModulo(y()+M_PI,2*M_PI)-M_PI,\n             kindr::common::floatingPointModulo(x()+M_PI,2*M_PI)-M_PI); // wrap all angles into [-pi,pi)\n\n    const double tol = 1e-3;\n\n    // wrap angles into [-pi,pi),[-pi/2,pi/2),[-pi,pi)\n    if(zyx.y() < -M_PI/2 - tol)\n    {\n      if(zyx.z() < 0) {\n        zyx.z() = zyx.z() + M_PI;\n      } else {\n        zyx.z() = zyx.z() - M_PI;\n      }\n\n      zyx.y() = -(zyx.y() + M_PI);\n\n      if(zyx.x() < 0) {\n        zyx.x() = zyx.x() + M_PI;\n      } else {\n        zyx.x() = zyx.x() - M_PI;\n      }\n    }\n    else if(-M_PI/2 - tol <= zyx.y() && zyx.y() <= -M_PI/2 + tol)\n    {\n      zyx.z() += zyx.x();\n      zyx.x() = 0;\n    }\n    else if(-M_PI/2 + tol < zyx.y() && zyx.y() < M_PI/2 - tol)\n    {\n      // ok\n    }\n    else if(M_PI/2 - tol <= zyx.y() && zyx.y() <= M_PI/2 + tol)\n    {\n      // todo: M_PI/2 should not be in range, other formula?\n      zyx.z() -= zyx.x();\n      zyx.x() = 0;\n    }\n    else // M_PI/2 + tol < zyx.y()\n    {\n      if(zyx.z() < 0) {\n        zyx.z() = zyx.z() + M_PI;\n      } else {\n        zyx.z() = zyx.z() - M_PI;\n      }\n\n      zyx.y() = -(zyx.y() - M_PI);\n\n      if(zyx.x() < 0) {\n        zyx.x() = zyx.x() + M_PI;\n      } else {\n        zyx.x() = zyx.x() - M_PI;\n      }\n    }\n\n    return EulerAnglesZyx(zyx);\n  }\n\n  /*! \\brief Modifies the Euler angles rotation such that the angles lie in [-pi,pi),[-pi/2,pi/2),[-pi,pi).\n   *  \\returns reference\n   */\n  EulerAnglesZyx& setUnique() {  // wraps angles into [-pi,pi),[-pi/2,pi/2),[-pi,pi)\n    *this = getUnique();\n    return *this;\n  }\n\n  /*! \\brief Concenation operator.\n   *  This is explicitly specified, because Eigen::Matrix provides also an operator*.\n   *  \\returns the concenation of two rotations\n   */\n  using EulerAnglesZyxBase<EulerAnglesZyx<PrimType_, Usage_>, Usage_>::operator*;\n\n  /*! \\brief Equivalence operator.\n   *  This is explicitly specified, because Eigen::Matrix provides also an operator==.\n   *  \\returns true if two rotations are similar.\n   */\n  using EulerAnglesZyxBase<EulerAnglesZyx<PrimType_, Usage_>, Usage_>::operator==;\n\n  /*! \\brief Used for printing the object with std::cout.\n   *  \\returns std::stream object\n   */\n  friend std::ostream& operator << (std::ostream& out, const EulerAnglesZyx& zyx) {\n    out << zyx.toImplementation().transpose();\n    return out;\n  }\n};\n\n//! \\brief Active Euler angles rotation (Z,Y',X'' / yaw,pitch,roll) with double primitive type\ntypedef EulerAnglesZyx<double, RotationUsage::ACTIVE>  EulerAnglesZyxAD;\n//! \\brief Active Euler angles rotation (Z,Y',X'' / yaw,pitch,roll) with float primitive type\ntypedef EulerAnglesZyx<float,  RotationUsage::ACTIVE>  EulerAnglesZyxAF;\n//! \\brief Passive Euler angles rotation (Z,Y',X'' / yaw,pitch,roll) with double primitive type\ntypedef EulerAnglesZyx<double, RotationUsage::PASSIVE> EulerAnglesZyxPD;\n//! \\brief Passive Euler angles rotation (Z,Y',X'' / yaw,pitch,roll) with float primitive type\ntypedef EulerAnglesZyx<float,  RotationUsage::PASSIVE> EulerAnglesZyxPF;\n\n//! \\brief Equivalent Euler angles rotation (Z,Y',X'' / yaw,pitch,roll) class\ntemplate <typename PrimType_, enum RotationUsage Usage_>\nusing EulerAnglesYpr = EulerAnglesZyx<PrimType_, Usage_>;\n\n//! \\brief Active Euler angles rotation (Z,Y',X'' / yaw,pitch,roll) with double primitive type\ntypedef EulerAnglesYpr<double, RotationUsage::ACTIVE>  EulerAnglesYprAD;\n//! \\brief Active Euler angles rotation (Z,Y',X'' / yaw,pitch,roll) with float primitive type\ntypedef EulerAnglesYpr<float,  RotationUsage::ACTIVE>  EulerAnglesYprAF;\n//! \\brief Passive Euler angles rotation (Z,Y',X'' / yaw,pitch,roll) with double primitive type\ntypedef EulerAnglesYpr<double, RotationUsage::PASSIVE> EulerAnglesYprPD;\n//! \\brief Passive Euler angles rotation (Z,Y',X'' / yaw,pitch,roll) with float primitive type\ntypedef EulerAnglesYpr<float,  RotationUsage::PASSIVE> EulerAnglesYprPF;\n\n} // namespace eigen_impl\n\n\nnamespace internal {\n\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass get_scalar<eigen_impl::EulerAnglesZyx<PrimType_, Usage_>> {\n public:\n  typedef PrimType_ Scalar;\n};\n\ntemplate<typename PrimType_, enum RotationUsage Usage_>\nclass get_matrix3X<eigen_impl::EulerAnglesZyx<PrimType_, Usage_>>{\n public:\n  typedef int  IndexType;\n\n  template <IndexType Cols>\n  using Matrix3X = Eigen::Matrix<PrimType_, 3, Cols>;\n};\n\ntemplate<typename PrimType_>\nclass get_other_usage<eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::ACTIVE>> {\n public:\n  typedef eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::PASSIVE> OtherUsage;\n};\n\ntemplate<typename PrimType_>\nclass get_other_usage<eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::PASSIVE>> {\n public:\n  typedef eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::ACTIVE> OtherUsage;\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Conversion Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>, eigen_impl::AngleAxis<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_> convert(const eigen_impl::AngleAxis<SourcePrimType_, Usage_>& aa) {\n//    return eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>(eigen_impl::getYprFromAngleAxis<SourcePrimType_, DestPrimType_>(aa.toImplementation()));\n    return eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>(eigen_impl::RotationQuaternion<DestPrimType_, Usage_>(aa));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>, eigen_impl::RotationVector<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_> convert(const eigen_impl::RotationVector<SourcePrimType_, Usage_>& rotationVector) {\n    return eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>(eigen_impl::AngleAxis<SourcePrimType_, Usage_>(rotationVector));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>, eigen_impl::RotationQuaternion<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_> convert(const eigen_impl::RotationQuaternion<SourcePrimType_, Usage_>& q) {\n    return eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getYprFromQuaternion<SourcePrimType_, DestPrimType_>(q.toImplementation()));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>, eigen_impl::RotationMatrix<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_> convert(const eigen_impl::RotationMatrix<SourcePrimType_, Usage_>& R) {\n    return eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getYprFromRotationMatrix<SourcePrimType_, DestPrimType_>(R.toImplementation().transpose()));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>, eigen_impl::EulerAnglesXyz<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_> convert(const eigen_impl::EulerAnglesXyz<SourcePrimType_, Usage_>& xyz) {\n    return eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>(eigen_impl::eigen_internal::getYprFromRpy<SourcePrimType_, DestPrimType_>(xyz.toImplementation()));\n  }\n};\n\ntemplate<typename DestPrimType_, typename SourcePrimType_, enum RotationUsage Usage_>\nclass ConversionTraits<eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>, eigen_impl::EulerAnglesZyx<SourcePrimType_, Usage_>> {\n public:\n  inline static eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_> convert(const eigen_impl::EulerAnglesZyx<SourcePrimType_, Usage_>& zyx) {\n    return eigen_impl::EulerAnglesZyx<DestPrimType_, Usage_>(zyx.toImplementation().template cast<DestPrimType_>());\n  }\n};\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Multiplication Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n//template<typename PrimType_>\n//class MultiplicationTraits<RotationBase<eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::ACTIVE>, RotationUsage::ACTIVE>, RotationBase<eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::ACTIVE>, RotationUsage::ACTIVE>> {\n// public:\n//  inline static eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::ACTIVE> mult(const eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::ACTIVE>& a, const eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::ACTIVE>& b) {\n//    return eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::ACTIVE>(eigen_impl::RotationQuaternion<PrimType_, RotationUsage::ACTIVE>(\n//                                                                 eigen_impl::RotationQuaternion<PrimType_, RotationUsage::ACTIVE>(a).toImplementation()*\n//                                                                 eigen_impl::RotationQuaternion<PrimType_, RotationUsage::ACTIVE>(b).toImplementation()));\n//  }\n//};\n//\n//template<typename PrimType_>\n//class MultiplicationTraits<RotationBase<eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::PASSIVE>, RotationUsage::PASSIVE>, RotationBase<eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::PASSIVE>, RotationUsage::PASSIVE>> {\n// public:\n//  inline static eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::PASSIVE> mult(const eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::PASSIVE>& a, const eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::PASSIVE>& b) {\n//    return eigen_impl::EulerAnglesZyx<PrimType_, RotationUsage::PASSIVE>(eigen_impl::RotationQuaternion<PrimType_, RotationUsage::PASSIVE>(\n//                                                                 eigen_impl::RotationQuaternion<PrimType_, RotationUsage::PASSIVE>(a).toImplementation()*\n//                                                                 eigen_impl::RotationQuaternion<PrimType_, RotationUsage::PASSIVE>(b).toImplementation()));\n//  }\n//};\n\n//template<typename PrimType_, enum RotationUsage Usage_>\n//class MultiplicationTraits<RotationBase<eigen_impl::EulerAnglesZyx<PrimType_, Usage_>, Usage_>, RotationBase<eigen_impl::EulerAnglesZyx<PrimType_, Usage_>, Usage_>> {\n// public:\n//  inline static eigen_impl::EulerAnglesZyx<PrimType_, Usage_> mult(const eigen_impl::EulerAnglesZyx<PrimType_, Usage_>& a, const eigen_impl::EulerAnglesZyx<PrimType_, Usage_>& b) {\n//    return eigen_impl::EulerAnglesZyx<PrimType_, Usage_>(eigen_impl::RotationQuaternion<PrimType_, Usage_>(\n//                                                                 eigen_impl::RotationQuaternion<PrimType_, Usage_>(a).toImplementation()*\n//                                                                 eigen_impl::RotationQuaternion<PrimType_, Usage_>(b).toImplementation()));\n//  }\n//};\n\n\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Rotation Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n\n/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n * Comparison Traits\n * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */\n\n\n} // namespace internal\n} // namespace rotations\n} // namespace kindr\n\n\n#endif /* KINDR_ROTATIONS_EIGEN_EULERANGLESZYX_HPP_ */\n", "meta": {"hexsha": "f3efa074919d4c15cb0d7f73316025a6cce87a25", "size": 21417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/EulerAnglesZyx.hpp", "max_stars_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_stars_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 170.0, "max_stars_repo_stars_event_min_datetime": "2016-02-01T18:58:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T05:28:01.000Z", "max_issues_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/EulerAnglesZyx.hpp", "max_issues_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_issues_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 162.0, "max_issues_repo_issues_event_min_datetime": "2016-01-29T17:04:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T16:25:37.000Z", "max_forks_repo_path": "IHMCPerception/third-party/kindr/include/kindr/rotations/eigen/EulerAnglesZyx.hpp", "max_forks_repo_name": "wxmerkt/ihmc-open-robotics-software", "max_forks_repo_head_hexsha": "2c47c9a9bd999e7811038e99c3888683f9973a2a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2016-01-28T22:49:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T03:11:24.000Z", "avg_line_length": 41.7485380117, "max_line_length": 232, "alphanum_fraction": 0.6471027688, "num_tokens": 5186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.47657965106367595, "lm_q1q2_score": 0.24201280108417797}}
{"text": "/*\n scph.cpp\n\n Copyright (c) 2015 Terumasa Tadano\n\n This file is distributed under the terms of the MIT license.\n Please see the file 'LICENCE.txt' in the root directory \n or http://opensource.org/licenses/mit-license.php for information.\n*/\n\n#include \"mpi_common.h\"\n#include \"scph.h\"\n#include \"dynamical.h\"\n#include \"kpoint.h\"\n#include \"anharmonic_core.h\"\n#include \"dielec.h\"\n#include \"ewald.h\"\n#include \"memory.h\"\n#include \"thermodynamics.h\"\n#include \"write_phonons.h\"\n#include \"constants.h\"\n#include \"system.h\"\n#include \"error.h\"\n#include \"mathfunctions.h\"\n#include \"integration.h\"\n#include \"parsephon.h\"\n#include \"phonon_dos.h\"\n#include \"symmetry_core.h\"\n#include <iostream>\n#include <iomanip>\n#include <complex>\n#include <algorithm>\n#include <fftw3.h>\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n#include <boost/lexical_cast.hpp>\n#include \"timer.h\"\n#include <cmath>\n#include <cstdlib>\n#include <vector>\n\n#if defined(WIN32) || defined(_WIN32)\n#pragma comment(lib, \"libfftw3-3.lib\")\n#pragma comment(lib, \"libfftw3f-3.lib\")\n#pragma comment(lib, \"libfftw3l-3.lib\")\n#endif\n\nusing namespace PHON_NS;\n\nScph::Scph(PHON *phon) : Pointers(phon)\n{\n    set_default_variables();\n}\n\nScph::~Scph()\n{\n    deallocate_variables();\n}\n\n\nvoid Scph::set_default_variables()\n{\n    im = std::complex<double>(0.0, 1.0);\n    restart_scph = false;\n    warmstart_scph = false;\n    lower_temp = true;\n    tolerance_scph = 1.0e-10;\n    mixalpha = 0.1;\n    maxiter = 100;\n    print_self_consistent_fc2 = false;\n    selfenergy_offdiagonal = true;\n    relax_coordinate = false;\n\n    xk_scph = nullptr;\n    kvec_na_scph = nullptr;\n    xk_interpolate = nullptr;\n    relvec_v3 = nullptr;\n    relvec_v4 = nullptr;\n    invmass_v3 = nullptr;\n    invmass_v4 = nullptr;\n    evec_index_v3 = nullptr;\n    evec_index_v4 = nullptr;\n    kmap_interpolate_to_scph = nullptr;\n    evec_harmonic = nullptr;\n    fcs_group_v3 = nullptr;\n    fcs_group_v4 = nullptr;\n    omega2_harmonic = nullptr;\n    mat_transform_sym = nullptr;\n    small_group_at_k = nullptr;\n    symop_minus_at_k = nullptr;\n    kpoint_map_symmetry = nullptr;\n    exp_phase = nullptr;\n    exp_phase3 = nullptr;\n    mindist_list_scph = nullptr;\n\n    bubble = 0;\n    phi3_reciprocal = nullptr;\n    compute_Cv_anharmonic = 0;\n}\n\n\nvoid Scph::deallocate_variables()\n{\n    if (xk_scph) {\n        memory->deallocate(xk_scph);\n    }\n    if (kvec_na_scph) {\n        memory->deallocate(kvec_na_scph);\n    }\n    if (xk_interpolate) {\n        memory->deallocate(xk_interpolate);\n    }\n    if (kmap_interpolate_to_scph) {\n        memory->deallocate(kmap_interpolate_to_scph);\n    }\n    if (mindist_list_scph) {\n        memory->deallocate(mindist_list_scph);\n    }\n    if (evec_harmonic) {\n        memory->deallocate(evec_harmonic);\n    }\n    if (omega2_harmonic) {\n        memory->deallocate(omega2_harmonic);\n    }\n    if (relvec_v3) {\n        memory->deallocate(relvec_v3);\n    }\n    if (relvec_v4) {\n        memory->deallocate(relvec_v4);\n    }\n    if (invmass_v3) {\n        memory->deallocate(invmass_v3);\n    }\n    if (invmass_v4) {\n        memory->deallocate(invmass_v4);\n    }\n    if (evec_index_v3) {\n        memory->deallocate(evec_index_v3);\n    }\n    if (evec_index_v4) {\n        memory->deallocate(evec_index_v4);\n    }\n    if (fcs_group_v3) {\n        memory->deallocate(fcs_group_v3);\n    }\n    if (fcs_group_v4) {\n        memory->deallocate(fcs_group_v4);\n    }\n    if (exp_phase) {\n        memory->deallocate(exp_phase);\n    }\n    if (exp_phase3) {\n        memory->deallocate(exp_phase3);\n    }\n    if (mat_transform_sym) {\n        memory->deallocate(mat_transform_sym);\n    }\n    if (small_group_at_k) {\n        memory->deallocate(small_group_at_k);\n    }\n    if (symop_minus_at_k) {\n        memory->deallocate(symop_minus_at_k);\n    }\n    if (kpoint_map_symmetry) {\n        memory->deallocate(kpoint_map_symmetry);\n    }\n    if (phi3_reciprocal) {\n        memory->deallocate(phi3_reciprocal);\n    }\n}\n\nvoid Scph::setup_scph()\n{\n    relax_coordinate = false;\n    MPI_Bcast(&relax_coordinate, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&bubble, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n\n    setup_kmesh();\n    setup_eigvecs();\n    setup_transform_ifc();\n    setup_pp_interaction();\n    setup_transform_symmetry();\n}\n\nvoid Scph::exec_scph()\n{\n    const auto nk_ref = kpoint->nk;\n    const auto ns = dynamical->neval;\n    const auto Tmin = system->Tmin;\n    const auto Tmax = system->Tmax;\n    const auto dT = system->dT;\n\n    std::complex<double> ****delta_dymat_scph = nullptr;\n    std::complex<double> ****delta_dymat_scph_plus_bubble = nullptr;\n\n    const auto NT = static_cast<unsigned int>((Tmax - Tmin) / dT) + 1;\n\n    MPI_Bcast(&restart_scph, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&selfenergy_offdiagonal, 1, MPI_LOGICAL, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&ialgo, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n\n    memory->allocate(delta_dymat_scph, NT, ns, ns, nk_interpolate);\n\n    if (restart_scph) {\n\n        // Read anharmonic correction to the dynamical matrix from the existing file\n        load_scph_dymat_from_file(delta_dymat_scph);\n\n    } else {\n\n        if (dynamical->nonanalytic == 3) {\n            error->exit(\"exec_scph\",\n                        \"Sorry, NONANALYTIC=3 can't be used for the main loop of the SCPH calculation.\");\n        }\n        // Solve the SCPH equation and obtain the correction to the dynamical matrix\n        exec_scph_main(delta_dymat_scph);\n\n        if (mympi->my_rank == 0) {\n            store_scph_dymat_to_file(delta_dymat_scph);\n            write_anharmonic_correction_fc2(delta_dymat_scph, NT);\n        }\n    }\n\n    if (kpoint->kpoint_mode == 2) {\n        if (thermodynamics->calc_FE_bubble) {\n            compute_free_energy_bubble_SCPH(kmesh_interpolate,\n                                            delta_dymat_scph);\n        }\n    }\n\n    if (bubble) {\n        memory->allocate(delta_dymat_scph_plus_bubble, NT, ns, ns, nk_interpolate);\n        bubble_correction(delta_dymat_scph,\n                          delta_dymat_scph_plus_bubble);\n        if (mympi->my_rank == 0) {\n            write_anharmonic_correction_fc2(delta_dymat_scph_plus_bubble, NT, bubble);\n        }\n    }\n\n    postprocess(delta_dymat_scph,\n                delta_dymat_scph_plus_bubble);\n\n    memory->deallocate(delta_dymat_scph);\n    if (delta_dymat_scph_plus_bubble) memory->deallocate(delta_dymat_scph_plus_bubble);\n\n}\n\nvoid Scph::postprocess(std::complex<double> ****delta_dymat_scph,\n                       std::complex<double> ****delta_dymat_scph_plus_bubble)\n{\n    double ***eval_anharm = nullptr;\n    const auto nk_ref = kpoint->nk;\n    const auto ns = dynamical->neval;\n    const auto Tmin = system->Tmin;\n    const auto Tmax = system->Tmax;\n    const auto dT = system->dT;\n    const auto NT = static_cast<unsigned int>((Tmax - Tmin) / dT) + 1;\n\n    unsigned int nomega_dielec;\n\n    if (mympi->my_rank == 0) {\n\n        std::cout << '\\n';\n        std::cout << \" Running postprocess of SCPH (calculation of free energy, MSD, DOS)\" << std::endl;\n        std::cout << \" The number of temperature points: \" << std::setw(4) << NT << std::endl;\n        std::cout << \"   \";\n\n        std::complex<double> ***evec_tmp = nullptr;\n        double **eval_gam = nullptr;\n        std::complex<double> ***evec_gam = nullptr;\n        double **xk_gam = nullptr;\n        memory->allocate(eval_anharm, NT, nk_ref, ns);\n        memory->allocate(evec_tmp, nk_ref, ns, ns);\n\n        double **dos_scph = nullptr;\n        double ***pdos_scph = nullptr;\n        double *heat_capacity = nullptr;\n        double *heat_capacity_correction = nullptr;\n        double *FE_QHA = nullptr;\n        double *dFE_scph = nullptr;\n        double **msd_scph = nullptr;\n        double ***ucorr_scph = nullptr;\n        double ****dielec_scph = nullptr;\n        double *omega_grid = nullptr;\n\n        if (kpoint->kpoint_mode == 2) {\n            if (dos->compute_dos) {\n                memory->allocate(dos_scph, NT, dos->n_energy);\n\n                if (dos->projected_dos) {\n                    memory->allocate(pdos_scph, NT, ns, dos->n_energy);\n                }\n            }\n            memory->allocate(heat_capacity, NT);\n            memory->allocate(FE_QHA, NT);\n            memory->allocate(dFE_scph, NT);\n\n            if (writes->getPrintMSD()) {\n                memory->allocate(msd_scph, NT, ns);\n            }\n            if (writes->getPrintUcorr()) {\n                memory->allocate(ucorr_scph, NT, ns, ns);\n            }\n            if (compute_Cv_anharmonic) {\n                memory->allocate(heat_capacity_correction, NT);\n            }\n        }\n        if (dielec->calc_dielectric_constant) {\n            omega_grid = dielec->get_omega_grid(nomega_dielec);\n            memory->allocate(dielec_scph, NT, nomega_dielec, 3, 3);\n            memory->allocate(eval_gam, 1, ns);\n            memory->allocate(evec_gam, 1, ns, ns);\n            memory->allocate(xk_gam, 1, 3);\n            for (auto i = 0; i < 3; ++i) xk_gam[0][i] = 0.0;\n        }\n\n        for (auto iT = 0; iT < NT; ++iT) {\n            auto T = Tmin + dT * static_cast<double>(iT);\n\n            exec_interpolation(kmesh_interpolate,\n                               delta_dymat_scph[iT],\n                               nk_ref,\n                               kpoint->xk,\n                               kpoint->kvec_na,\n                               eval_anharm[iT],\n                               evec_tmp);\n\n            if (kpoint->kpoint_mode == 2) {\n\n                if (dos->compute_dos) {\n                    dos->calc_dos_from_given_frequency(eval_anharm[iT],\n                                                       dos_scph[iT]);\n                }\n\n                heat_capacity[iT] = thermodynamics->Cv_tot(T,\n                                                           kpoint->nk_irred,\n                                                           ns,\n                                                           kpoint->kpoint_irred_all,\n                                                           &kpoint->weight_k[0],\n                                                           eval_anharm[iT]);\n\n                FE_QHA[iT] = thermodynamics->free_energy_QHA(T,\n                                                             kpoint->nk_irred,\n                                                             ns,\n                                                             kpoint->kpoint_irred_all,\n                                                             &kpoint->weight_k[0],\n                                                             eval_anharm[iT]);\n\n                dFE_scph[iT] = thermodynamics->FE_scph_correction(iT,\n                                                                  eval_anharm[iT],\n                                                                  evec_tmp);\n\n                if (writes->getPrintMSD()) {\n                    double shift[3]{0.0, 0.0, 0.0};\n\n                    for (auto is = 0; is < ns; ++is) {\n                        msd_scph[iT][is] = thermodynamics->disp_corrfunc(T, is, is,\n                                                                         shift, kpoint->nk,\n                                                                         ns,\n                                                                         kpoint->xk,\n                                                                         eval_anharm[iT],\n                                                                         evec_tmp);\n                    }\n                }\n\n                if (writes->getPrintUcorr()) {\n                    double shift[3];\n                    for (auto i = 0; i < 3; ++i) shift[i] = static_cast<double>(writes->getShiftUcorr()[i]);\n\n                    for (auto is = 0; is < ns; ++is) {\n                        for (auto js = 0; js < ns; ++js) {\n                            ucorr_scph[iT][is][js] = thermodynamics->disp_corrfunc(T, is, js,\n                                                                                   shift, kpoint->nk,\n                                                                                   ns,\n                                                                                   kpoint->xk,\n                                                                                   eval_anharm[iT],\n                                                                                   evec_tmp);\n                        }\n                    }\n                }\n            }\n\n            if (dielec->calc_dielectric_constant) {\n                exec_interpolation(kmesh_interpolate,\n                                   delta_dymat_scph[iT],\n                                   1,\n                                   xk_gam,\n                                   xk_gam,\n                                   eval_gam,\n                                   evec_gam);\n\n                for (auto is = 0; is < ns; ++is) {\n                    if (eval_gam[0][is] < 0.0) {\n                        eval_gam[0][is] = -std::pow(eval_gam[0][is], 2.0);\n                    } else {\n                        eval_gam[0][is] = std::pow(eval_gam[0][is], 2.0);\n                    }\n                }\n\n                dielec->compute_dielectric_function(nomega_dielec,\n                                                    omega_grid,\n                                                    eval_gam[0],\n                                                    evec_gam[0],\n                                                    dielec_scph[iT]);\n            }\n\n            std::cout << '.' << std::flush;\n            if (iT % 25 == 24) {\n                std::cout << std::endl;\n                std::cout << std::setw(3);\n            }\n        }\n        std::cout << \"\\n\\n\";\n\n        if (kpoint->kpoint_mode == 2 && compute_Cv_anharmonic > 0) {\n            double **domega_dt = nullptr;\n            memory->allocate(domega_dt, nk_ref, ns);\n            if (compute_Cv_anharmonic == 1) {\n                // Use central difference to evaluate temperature derivative of\n                // anharmonic frequencies\n\n                heat_capacity_correction[0] = 0.0;\n                heat_capacity_correction[NT - 1] = 0.0;\n\n                for (auto iT = 1; iT < NT - 1; ++iT) {\n                    auto T = Tmin + dT * static_cast<double>(iT);\n\n                    get_derivative_central_diff(dT, nk_ref,\n                                                eval_anharm[iT - 1],\n                                                eval_anharm[iT + 1],\n                                                domega_dt);\n\n                    heat_capacity_correction[iT] = thermodynamics->Cv_anharm_correction(T,\n                                                                                        kpoint->nk_irred,\n                                                                                        ns,\n                                                                                        kpoint->kpoint_irred_all,\n                                                                                        &kpoint->weight_k[0],\n                                                                                        eval_anharm[iT],\n                                                                                        domega_dt);\n                }\n            }\n        }\n\n        if (kpoint->kpoint_mode == 0) {\n            writes->write_scph_energy(eval_anharm);\n        } else if (kpoint->kpoint_mode == 1) {\n            writes->write_scph_bands(eval_anharm);\n        } else if (kpoint->kpoint_mode == 2) {\n            if (dos->compute_dos) {\n                writes->write_scph_dos(dos_scph);\n            }\n            writes->write_scph_thermodynamics(heat_capacity,\n                                              heat_capacity_correction,\n                                              FE_QHA,\n                                              dFE_scph);\n            if (writes->getPrintMSD()) {\n                writes->write_scph_msd(msd_scph);\n            }\n            if (writes->getPrintUcorr()) {\n                writes->write_scph_ucorr(ucorr_scph);\n            }\n        }\n        if (dielec->calc_dielectric_constant) {\n            writes->write_scph_dielec(dielec_scph);\n        }\n\n        // If delta_dymat_scph_plus_bubble != nullptr, run postprocess again with\n        // delta_dymat_scph_plus_bubble.\n        if (bubble > 0) {\n            std::cout << std::endl;\n            std::cout << \"   \";\n\n            for (auto iT = 0; iT < NT; ++iT) {\n                auto T = Tmin + dT * static_cast<double>(iT);\n\n                exec_interpolation(kmesh_interpolate,\n                                   delta_dymat_scph_plus_bubble[iT],\n                                   nk_ref,\n                                   kpoint->xk,\n                                   kpoint->kvec_na,\n                                   eval_anharm[iT],\n                                   evec_tmp);\n\n                if (kpoint->kpoint_mode == 2) {\n\n                    if (dos->compute_dos) {\n                        dos->calc_dos_from_given_frequency(eval_anharm[iT],\n                                                           dos_scph[iT]);\n                    }\n\n                    heat_capacity[iT] = thermodynamics->Cv_tot(T,\n                                                               kpoint->nk_irred,\n                                                               ns,\n                                                               kpoint->kpoint_irred_all,\n                                                               &kpoint->weight_k[0],\n                                                               eval_anharm[iT]);\n\n                    if (writes->getPrintMSD()) {\n                        double shift[3]{0.0, 0.0, 0.0};\n\n                        for (auto is = 0; is < ns; ++is) {\n                            msd_scph[iT][is] = thermodynamics->disp_corrfunc(T, is, is,\n                                                                             shift, kpoint->nk,\n                                                                             ns,\n                                                                             kpoint->xk,\n                                                                             eval_anharm[iT],\n                                                                             evec_tmp);\n                        }\n                    }\n\n                    if (writes->getPrintUcorr()) {\n                        double shift[3];\n                        for (auto i = 0; i < 3; ++i) shift[i] = static_cast<double>(writes->getShiftUcorr()[i]);\n\n                        for (auto is = 0; is < ns; ++is) {\n                            for (auto js = 0; js < ns; ++js) {\n                                ucorr_scph[iT][is][js] = thermodynamics->disp_corrfunc(T, is, js,\n                                                                                       shift, kpoint->nk,\n                                                                                       ns,\n                                                                                       kpoint->xk,\n                                                                                       eval_anharm[iT],\n                                                                                       evec_tmp);\n                            }\n                        }\n                    }\n                }\n\n                std::cout << '.' << std::flush;\n                if (iT % 25 == 24) {\n                    std::cout << std::endl;\n                    std::cout << std::setw(3);\n                }\n            }\n\n            std::cout << \"\\n\\n\";\n\n            if (kpoint->kpoint_mode == 0) {\n                writes->write_scph_energy(eval_anharm, bubble);\n            } else if (kpoint->kpoint_mode == 1) {\n                writes->write_scph_bands(eval_anharm, bubble);\n            } else if (kpoint->kpoint_mode == 2) {\n                if (dos->compute_dos) {\n                    writes->write_scph_dos(dos_scph, bubble);\n                }\n                if (writes->getPrintMSD()) {\n                    writes->write_scph_msd(msd_scph, bubble);\n                }\n                if (writes->getPrintUcorr()) {\n                    writes->write_scph_ucorr(ucorr_scph, bubble);\n                }\n            }\n        }\n\n        memory->deallocate(eval_anharm);\n        memory->deallocate(evec_tmp);\n\n        if (dos_scph) memory->deallocate(dos_scph);\n        if (pdos_scph) memory->deallocate(pdos_scph);\n        if (heat_capacity) memory->deallocate(heat_capacity);\n        if (heat_capacity_correction) memory->deallocate(heat_capacity_correction);\n        if (FE_QHA) memory->deallocate(FE_QHA);\n        if (dFE_scph) memory->deallocate(dFE_scph);\n        if (dielec_scph) memory->deallocate(dielec_scph);\n\n        if (eval_gam) memory->deallocate(eval_gam);\n        if (evec_gam) memory->deallocate(evec_gam);\n        if (xk_gam) memory->deallocate(xk_gam);\n    }\n}\n\n\nvoid Scph::load_scph_dymat_from_file(std::complex<double> ****dymat_out)\n{\n    const auto ns = dynamical->neval;\n    const auto Tmin = system->Tmin;\n    const auto Tmax = system->Tmax;\n    const auto dT = system->dT;\n    const auto NT = static_cast<unsigned int>((Tmax - Tmin) / dT) + 1;\n    std::vector<double> Temp_array(NT);\n\n    for (int i = 0; i < NT; ++i) {\n        Temp_array[i] = Tmin + dT * static_cast<double>(i);\n    }\n\n    if (mympi->my_rank == 0) {\n\n        const auto consider_offdiagonal = selfenergy_offdiagonal;\n        double temp;\n        std::ifstream ifs_dymat;\n        auto file_dymat = input->job_title + \".scph_dymat\";\n        bool consider_offdiag_tmp;\n        unsigned int nk_interpolate_ref[3];\n        unsigned int nk_scph_tmp[3];\n        double Tmin_tmp, Tmax_tmp, dT_tmp;\n        double dymat_real, dymat_imag;\n        std::string str_dummy;\n        int nonanalytic_tmp;\n\n        std::cout << \" RESTART_SCPH is true.\" << std::endl;\n        std::cout << \" Dynamical matrix is read from file ...\";\n\n        ifs_dymat.open(file_dymat.c_str(), std::ios::in);\n\n        if (!ifs_dymat) {\n            error->exit(\"load_scph_dymat_from_file\",\n                        \"Cannot open scph_dymat file\");\n        }\n\n        // Read computational settings from file and check the consistency.\n        ifs_dymat >> nk_interpolate_ref[0] >> nk_interpolate_ref[1] >> nk_interpolate_ref[2];\n        ifs_dymat >> nk_scph_tmp[0] >> nk_scph_tmp[1] >> nk_scph_tmp[2];\n        ifs_dymat >> Tmin_tmp >> Tmax_tmp >> dT_tmp;\n        ifs_dymat >> nonanalytic_tmp >> consider_offdiag_tmp;\n\n        if (nk_interpolate_ref[0] != kmesh_interpolate[0] ||\n            nk_interpolate_ref[1] != kmesh_interpolate[1] ||\n            nk_interpolate_ref[2] != kmesh_interpolate[2]) {\n            error->exit(\"load_scph_dymat_from_file\",\n                        \"The number of KMESH_INTERPOLATE is not consistent\");\n        }\n        if (nk_scph_tmp[0] != kmesh_scph[0] ||\n            nk_scph_tmp[1] != kmesh_scph[1] ||\n            nk_scph_tmp[2] != kmesh_scph[2]) {\n            error->exit(\"load_scph_dymat_from_file\",\n                        \"The number of KMESH_SCPH is not consistent\");\n        }\n        if (nonanalytic_tmp != dynamical->nonanalytic) {\n            error->warn(\"load_scph_dymat_from_file\",\n                        \"The NONANALYTIC tag is not consistent\");\n        }\n        if (consider_offdiag_tmp != consider_offdiagonal) {\n            error->exit(\"load_scph_dymat_from_file\",\n                        \"The SELF_OFFDIAG tag is not consistent\");\n        }\n\n        // Check if the precalculated data for the given temperature range exists\n        const auto NT_ref = static_cast<unsigned int>((Tmax_tmp - Tmin_tmp) / dT_tmp) + 1;\n        std::vector<double> Temp_array_ref(NT_ref);\n        for (int i = 0; i < NT_ref; ++i) {\n            Temp_array_ref[i] = Tmin_tmp + dT_tmp * static_cast<double>(i);\n        }\n        std::vector<int> flag_load(NT_ref);\n        for (int i = 0; i < NT_ref; ++i) {\n            flag_load[i] = 0;\n            for (int j = 0; j < NT; ++j) {\n                if (std::abs(Temp_array_ref[i] - Temp_array[j]) < eps6) {\n                    flag_load[i] = 1;\n                    break;\n                }\n            }\n        }\n        int icount = 0;\n        for (int iT = 0; iT < NT_ref; ++iT) {\n            ifs_dymat >> str_dummy >> temp;\n            for (int is = 0; is < ns; ++is) {\n                for (int js = 0; js < ns; ++js) {\n                    for (int ik = 0; ik < nk_interpolate; ++ik) {\n                        ifs_dymat >> dymat_real >> dymat_imag;\n                        if (flag_load[iT]) {\n                            dymat_out[icount][is][js][ik]\n                                    = std::complex<double>(dymat_real, dymat_imag);\n                        }\n                    }\n                }\n            }\n            if (flag_load[iT]) icount += 1;\n        }\n\n        ifs_dymat.close();\n\n        if (icount != NT) {\n            error->exit(\"load_scph_dymat_from_file\",\n                        \"The temperature information is not consistent\");\n        }\n        std::cout << \" done.\" << std::endl;\n    }\n    // Broadcast to all MPI threads\n    mpi_bcast_complex(dymat_out, NT, nk_interpolate, ns);\n}\n\nvoid Scph::store_scph_dymat_to_file(std::complex<double> ****dymat_in)\n{\n    int i;\n    const auto ns = dynamical->neval;\n    const auto Tmin = system->Tmin;\n    const auto Tmax = system->Tmax;\n    const auto dT = system->dT;\n    std::ofstream ofs_dymat;\n    auto file_dymat = input->job_title + \".scph_dymat\";\n\n    const auto NT = static_cast<unsigned int>((Tmax - Tmin) / dT) + 1;\n\n    ofs_dymat.open(file_dymat.c_str(), std::ios::out);\n\n    if (!ofs_dymat) {\n        error->exit(\"store_scph_dymat_to_file\",\n                    \"Cannot open scph_dymat file\");\n    }\n    for (i = 0; i < 3; ++i) {\n        ofs_dymat << std::setw(5) << kmesh_interpolate[i];\n    }\n    ofs_dymat << std::endl;\n    for (i = 0; i < 3; ++i) {\n        ofs_dymat << std::setw(5) << kmesh_scph[i];\n    }\n    ofs_dymat << std::endl;\n    ofs_dymat << std::setw(10) << Tmin;\n    ofs_dymat << std::setw(10) << Tmax;\n    ofs_dymat << std::setw(10) << dT << std::endl;\n    ofs_dymat << std::setw(5) << dynamical->nonanalytic;\n    ofs_dymat << std::setw(5) << selfenergy_offdiagonal << std::endl;\n\n    for (auto iT = 0; iT < NT; ++iT) {\n        const auto temp = Tmin + static_cast<double>(iT) * dT;\n        ofs_dymat << \"# \" << temp << std::endl;\n        for (auto is = 0; is < ns; ++is) {\n            for (auto js = 0; js < ns; ++js) {\n                for (auto ik = 0; ik < nk_interpolate; ++ik) {\n                    ofs_dymat << std::setprecision(15)\n                              << std::setw(25) << dymat_in[iT][is][js][ik].real();\n                    ofs_dymat << std::setprecision(15)\n                              << std::setw(25) << dymat_in[iT][is][js][ik].imag();\n                    ofs_dymat << std::endl;\n                }\n            }\n        }\n    }\n    ofs_dymat.close();\n    std::cout << \"  \" << std::setw(input->job_title.length() + 12) << std::left << file_dymat;\n    std::cout << \" : Anharmonic dynamical matrix (restart file)\" << std::endl;\n}\n\nvoid Scph::exec_scph_main(std::complex<double> ****dymat_anharm)\n{\n    int ik, is;\n    const auto nk = nk_scph;\n    const auto ns = dynamical->neval;\n    const auto nk_reduced_scph = kp_irred_scph.size();\n    const auto nk_irred_interpolate = kp_irred_interpolate.size();\n    const auto Tmin = system->Tmin;\n    const auto Tmax = system->Tmax;\n    const auto dT = system->dT;\n    double ***omega2_anharm;\n    std::complex<double> ***evec_anharm_tmp;\n    std::complex<double> ***v3_array_all;\n    std::complex<double> ***v4_array_all;\n\n    std::vector<double> vec_temp;\n\n    const auto NT = static_cast<unsigned int>((Tmax - Tmin) / dT) + 1;\n\n    // Compute matrix element of 4-phonon interaction\n\n    memory->allocate(omega2_anharm, NT, nk, ns);\n    memory->allocate(evec_anharm_tmp, nk, ns, ns);\n    memory->allocate(v4_array_all, nk_irred_interpolate * nk_scph,\n                     ns * ns, ns * ns);\n\n    // Calculate v4 array. \n    // This operation is the most expensive part of the calculation.\n    if (selfenergy_offdiagonal & (ialgo == 1)) {\n        compute_V4_elements_mpi_over_band(v4_array_all,\n                                          evec_harmonic,\n                                          selfenergy_offdiagonal);\n    } else {\n        compute_V4_elements_mpi_over_kpoint(v4_array_all,\n                                            evec_harmonic,\n                                            selfenergy_offdiagonal,\n                                            relax_coordinate);\n    }\n\n    if (relax_coordinate) {\n        memory->allocate(v3_array_all, nk, ns, ns * ns);\n        compute_V3_elements_mpi_over_kpoint(v3_array_all,\n                                            evec_harmonic,\n                                            selfenergy_offdiagonal);\n    }\n\n    if (mympi->my_rank == 0) {\n\n        std::complex<double> ***cmat_convert;\n        memory->allocate(cmat_convert, nk, ns, ns);\n\n        vec_temp.clear();\n\n        if (lower_temp) {\n            for (int i = NT - 1; i >= 0; --i) {\n                vec_temp.push_back(Tmin + static_cast<double>(i) * dT);\n            }\n        } else {\n            for (int i = 0; i < NT; ++i) {\n                vec_temp.push_back(Tmin + static_cast<double>(i) * dT);\n            }\n        }\n\n        auto converged_prev = false;\n\n        for (double temp : vec_temp) {\n            auto iT = static_cast<unsigned int>((temp - Tmin) / dT);\n\n            // Initialize phonon eigenvectors with harmonic values\n\n            for (ik = 0; ik < nk; ++ik) {\n                for (is = 0; is < ns; ++is) {\n                    for (int js = 0; js < ns; ++js) {\n                        evec_anharm_tmp[ik][is][js] = evec_harmonic[ik][is][js];\n                    }\n                }\n            }\n            if (converged_prev) {\n                if (lower_temp) {\n                    for (ik = 0; ik < nk; ++ik) {\n                        for (is = 0; is < ns; ++is) {\n                            omega2_anharm[iT][ik][is] = omega2_anharm[iT + 1][ik][is];\n                        }\n                    }\n                } else {\n                    for (ik = 0; ik < nk; ++ik) {\n                        for (is = 0; is < ns; ++is) {\n                            omega2_anharm[iT][ik][is] = omega2_anharm[iT - 1][ik][is];\n                        }\n                    }\n                }\n            }\n\n            compute_anharmonic_frequency(v4_array_all,\n                                         omega2_anharm[iT],\n                                         evec_anharm_tmp,\n                                         temp,\n                                         converged_prev,\n                                         cmat_convert,\n                                         selfenergy_offdiagonal,\n                                         writes->getVerbosity());\n\n            calc_new_dymat_with_evec(dymat_anharm[iT],\n                                     omega2_anharm[iT],\n                                     evec_anharm_tmp);\n\n            if (!warmstart_scph) converged_prev = false;\n        }\n\n        memory->deallocate(cmat_convert);\n\n    }\n\n    mpi_bcast_complex(dymat_anharm, NT, nk_interpolate, ns);\n\n    memory->deallocate(omega2_anharm);\n    memory->deallocate(v4_array_all);\n    memory->deallocate(evec_anharm_tmp);\n}\n\n\nvoid Scph::compute_V3_elements_mpi_over_kpoint(std::complex<double> ***v3_out,\n                                               std::complex<double> ***evec_in,\n                                               const bool self_offdiag)\n{\n    // Calculate the matrix elements of quartic terms in reciprocal space.\n    // This is the most expensive part of the SCPH calculation.\n\n    auto ns = dynamical->neval;\n    auto ns2 = ns * ns;\n    auto ns3 = ns * ns * ns;\n    unsigned int is, js, ks;\n    double phase3[3];\n    int loc3[3];\n    unsigned int **ind;\n    unsigned int i, j;\n    std::complex<double> ret;\n    long int ii;\n\n    const auto inv2pi = 1.0 / (2.0 * pi);\n    const auto dnk_represent = static_cast<double>(nk_represent);\n    const auto factor = std::pow(0.5, 2) / static_cast<double>(nk_scph);\n    static auto complex_zero = std::complex<double>(0.0, 0.0);\n    std::complex<double> *v3_array_at_kpair;\n    std::complex<double> ***v3_mpi;\n\n    //  nk2_prod = nk_reduced_interpolate * nk_scph;\n\n    if (mympi->my_rank == 0) {\n        if (self_offdiag) {\n            std::cout << \" SELF_OFFDIAG = 1: Calculating all components of v3_array ... \";\n        } else {\n            std::cout << \" SELF_OFFDIAG = 0: Calculating diagonal components of v3_array ... \";\n        }\n    }\n\n    memory->allocate(v3_array_at_kpair, ngroup_v3);\n    memory->allocate(ind, ngroup_v3, 3);\n    memory->allocate(v3_mpi, nk_scph, ns, ns2);\n\n    for (unsigned int ik = mympi->my_rank; ik < nk_scph; ik += mympi->nprocs) {\n\n        for (is = 0; is < ngroup_v3; ++is) v3_array_at_kpair[is] = complex_zero;\n\n        for (i = 0; i < ngroup_v3; ++i) {\n\n            std::complex<double> sum_tmp = std::complex<double>(0.0, 0.0);\n            for (j = 0; j < 3; ++j) ind[i][j] = evec_index_v3[i][j];\n\n            if (tune_type == 0) {\n                for (j = 0; j < fcs_group_v3[i].size(); ++j) {\n                    const auto phase = xk_scph[ik][0] * (relvec_v3[i][j].vecs[0][0] - relvec_v3[i][j].vecs[1][0])\n                                       + xk_scph[ik][1] * (relvec_v3[i][j].vecs[0][1] - relvec_v3[i][j].vecs[1][1])\n                                       + xk_scph[ik][2] * (relvec_v3[i][j].vecs[0][2] - relvec_v3[i][j].vecs[1][2]);\n\n                    const int loc = nint(phase * dnk_represent * inv2pi) % nk_represent + nk_represent - 1;\n\n                    sum_tmp += fcs_group_v3[i][j] * invmass_v3[i] * exp_phase[loc];\n                }\n            } else if (tune_type == 1) {\n                for (j = 0; j < fcs_group_v4[i].size(); ++j) {\n\n                    for (ii = 0; ii < 3; ++ii) {\n                        phase3[ii] = xk_scph[ik][ii] * (relvec_v3[i][j].vecs[0][ii] - relvec_v3[i][j].vecs[1][ii]);\n                        loc3[ii] = nint(phase3[ii] * dnk[ii] * inv2pi) % nk_grid[ii] + nk_grid[ii] - 1;\n                    }\n\n                    sum_tmp += fcs_group_v3[i][j] * invmass_v3[i]\n                               * exp_phase3[loc3[0]][loc3[1]][loc3[2]];\n                }\n            }\n            v3_array_at_kpair[i] = sum_tmp;\n        }\n\n#pragma omp parallel for private(is)\n        for (ii = 0; ii < ns; ++ii) {\n            for (is = 0; is < ns2; ++is) {\n                v3_mpi[ik][ii][is] = complex_zero;\n                v3_out[ik][ii][is] = complex_zero;\n            }\n        }\n\n        if (self_offdiag) {\n\n            // All matrix elements will be calculated when considering the off-diagonal\n            // elements of the phonon self-energy (i.e., when considering polarization mixing).\n\n#pragma omp parallel for private(is, js, ks, ret, i)\n            for (ii = 0; ii < ns3; ++ii) {\n                is = ii / ns2;\n                js = (ii - ns2 * is) / ns;\n                ks = ii % ns;\n\n                ret = std::complex<double>(0.0, 0.0);\n\n                for (i = 0; i < ngroup_v3; ++i) {\n\n                    ret += v3_array_at_kpair[i]\n                           * evec_in[0][is][ind[i][0]]\n                           * evec_in[ik][js][ind[i][1]]\n                           * std::conj(evec_in[ik][ks][ind[i][2]]);\n                }\n\n                v3_mpi[ik][is][ns * js + ks] = factor * ret;\n            }\n\n        } else {\n\n            // Only diagonal elements will be computed when neglecting the polarization mixing.\n\n            if (ik == 0) {\n#pragma omp parallel for private(is, js, ks, ret, i)\n                for (ii = 0; ii < ns3; ++ii) {\n                    is = ii / ns2;\n                    js = (ii - ns2 * is) / ns;\n                    ks = ii % ns;\n\n                    ret = std::complex<double>(0.0, 0.0);\n\n                    for (i = 0; i < ngroup_v3; ++i) {\n\n                        ret += v3_array_at_kpair[i]\n                               * evec_in[0][is][ind[i][0]]\n                               *evec_in[ik][js][ind[i][1]]\n                               * std::conj(evec_in[ik][ks][ind[i][2]]);\n                    }\n\n                    v3_mpi[ik][is][ns * js + ks] = factor * ret;\n                }\n            } else {\n\n#pragma omp parallel for private(is, js, ret, i)\n                for (ii = 0; ii < ns2; ++ii) {\n                    is = ii / ns;\n                    js = ii % ns;\n\n                    ret = std::complex<double>(0.0, 0.0);\n\n                    for (i = 0; i < ngroup_v3; ++i) {\n\n                        ret += v3_array_at_kpair[i]\n                               * evec_in[0][is][ind[i][0]]\n                               * evec_in[ik][js][ind[i][1]]\n                               * std::conj(evec_in[ik][js][ind[i][2]]);\n                    }\n\n                    v3_mpi[ik][is][(ns + 1) * js] = factor * ret;\n                }\n            }\n        }\n    }\n\n    memory->deallocate(v3_array_at_kpair);\n    memory->deallocate(ind);\n#ifdef MPI_CXX_DOUBLE_COMPLEX\n    MPI_Allreduce(&v3_mpi[0][0][0], &v3_out[0][0][0],\n                  static_cast<int>(nk_scph) * ns3,\n                  MPI_CXX_DOUBLE_COMPLEX, MPI_SUM, MPI_COMM_WORLD);\n#else\n    MPI_Allreduce(&v3_mpi[0][0][0], &v3_out[0][0][0], static_cast<int>(nk_scph) * ns3,\n                  MPI_COMPLEX16, MPI_SUM, MPI_COMM_WORLD);\n#endif\n\n    memory->deallocate(v3_mpi);\n\n    zerofill_elements_acoustic_at_gamma(omega2_harmonic, v3_out, 3);\n\n    if (mympi->my_rank == 0) {\n        std::cout << \" done !\" << std::endl;\n        timer->print_elapsed();\n    }\n}\n\nvoid Scph::compute_V4_elements_mpi_over_kpoint(std::complex<double> ***v4_out,\n                                               std::complex<double> ***evec_in,\n                                               const bool self_offdiag,\n                                               const bool relax)\n{\n    // Calculate the matrix elements of quartic terms in reciprocal space.\n    // This is the most expensive part of the SCPH calculation.\n\n    const size_t nk_reduced_interpolate = kp_irred_interpolate.size();\n    const size_t ns = dynamical->neval;\n    const size_t ns2 = ns * ns;\n    const size_t ns3 = ns * ns * ns;\n    const size_t ns4 = ns * ns * ns * ns;\n    size_t is, js, ks, ls;\n    double phase3[3];\n    int loc3[3];\n    unsigned int **ind;\n    unsigned int i, j;\n    std::complex<double> ret;\n    long int ii;\n\n    const auto inv2pi = 1.0 / (2.0 * pi);\n    const auto dnk_represent = static_cast<double>(nk_represent);\n    const auto factor = std::pow(0.5, 2) / static_cast<double>(nk_scph);\n    static auto complex_zero = std::complex<double>(0.0, 0.0);\n    std::complex<double> *v4_array_at_kpair;\n    std::complex<double> ***v4_mpi;\n\n    const size_t nk2_prod = nk_reduced_interpolate * nk_scph;\n\n    if (mympi->my_rank == 0) {\n        if (self_offdiag) {\n            std::cout << \" SELF_OFFDIAG = 1: Calculating all components of v4_array ... \";\n        } else {\n            std::cout << \" SELF_OFFDIAG = 0: Calculating diagonal components of v4_array ... \";\n        }\n    }\n\n    memory->allocate(v4_array_at_kpair, ngroup_v4);\n    memory->allocate(ind, ngroup_v4, 4);\n    memory->allocate(v4_mpi, nk2_prod, ns2, ns2);\n\n    for (size_t ik_prod = mympi->my_rank; ik_prod < nk2_prod; ik_prod += mympi->nprocs) {\n        const auto ik = ik_prod / nk_scph;\n        const auto jk = ik_prod % nk_scph;\n\n        const unsigned int knum = kmap_interpolate_to_scph[kp_irred_interpolate[ik][0].knum];\n\n        for (is = 0; is < ngroup_v4; ++is) v4_array_at_kpair[is] = complex_zero;\n\n        for (i = 0; i < ngroup_v4; ++i) {\n\n            auto sum_tmp = std::complex<double>(0.0, 0.0);\n            for (j = 0; j < 4; ++j) ind[i][j] = evec_index_v4[i][j];\n\n            if (tune_type == 0) {\n                for (j = 0; j < fcs_group_v4[i].size(); ++j) {\n                    const auto phase =  xk_scph[knum][0] * relvec_v4[i][j].vecs[0][0]\n                                       + xk_scph[knum][1] * relvec_v4[i][j].vecs[0][1]\n                                       + xk_scph[knum][2] * relvec_v4[i][j].vecs[0][2]\n                                       + xk_scph[jk][0] * (relvec_v4[i][j].vecs[1][0] - relvec_v4[i][j].vecs[2][0])\n                                       + xk_scph[jk][1] * (relvec_v4[i][j].vecs[1][1] - relvec_v4[i][j].vecs[2][1])\n                                       + xk_scph[jk][2] * (relvec_v4[i][j].vecs[1][2] - relvec_v4[i][j].vecs[2][2]);\n\n                    const auto loc = nint(phase * dnk_represent * inv2pi) % nk_represent + nk_represent - 1;\n\n                    sum_tmp += fcs_group_v4[i][j] * invmass_v4[i] * exp_phase[loc];\n                }\n            } else if (tune_type == 1) {\n                for (j = 0; j < fcs_group_v4[i].size(); ++j) {\n\n                    for (ii = 0; ii < 3; ++ii) {\n                        phase3[ii] = xk_scph[knum][ii] * relvec_v4[i][j].vecs[0][ii]\n                                     + xk_scph[jk][ii] * (relvec_v4[i][j].vecs[1][ii] - relvec_v4[i][j].vecs[2][ii]);\n                        loc3[ii] = nint(phase3[ii] * dnk[ii] * inv2pi) % nk_grid[ii] + nk_grid[ii] - 1;\n                    }\n\n                    sum_tmp += fcs_group_v4[i][j] * invmass_v4[i]\n                               * exp_phase3[loc3[0]][loc3[1]][loc3[2]];\n                }\n            }\n            v4_array_at_kpair[i] = sum_tmp;\n        }\n\n#pragma omp parallel for private(is)\n        for (ii = 0; ii < ns2; ++ii) {\n            for (is = 0; is < ns2; ++is) {\n                v4_mpi[ik_prod][ii][is] = complex_zero;\n                v4_out[ik_prod][ii][is] = complex_zero;\n            }\n        }\n\n        if (self_offdiag) {\n\n            // All matrix elements will be calculated when considering the off-diagonal\n            // elements of the phonon self-energy (loop diagram).\n\n#pragma omp parallel for private(is, js, ks, ls, ret, i)\n            for (ii = 0; ii < ns4; ++ii) {\n                is = ii / ns3;\n                js = (ii - ns3 * is) / ns2;\n                ks = (ii - ns3 * is - ns2 * js) / ns;\n                ls = ii % ns;\n\n                if (is < js) continue;\n\n                ret = std::complex<double>(0.0, 0.0);\n\n                for (i = 0; i < ngroup_v4; ++i) {\n\n                    ret += v4_array_at_kpair[i]\n                           * std::conj(evec_in[knum][is][ind[i][0]])\n                           * evec_in[knum][js][ind[i][1]]\n                           * evec_in[jk][ks][ind[i][2]]\n                           * std::conj(evec_in[jk][ls][ind[i][3]]);\n                }\n\n                v4_mpi[ik_prod][ns * is + js][ns * ks + ls] = factor * ret;\n            }\n\n        } else {\n\n            // Only diagonal elements will be computed when neglecting the polarization mixing.\n\n            if (relax && (knum == 0 || jk == 0)) {\n\n#pragma omp parallel for private(is, js, ks, ls, ret, i)\n                for (ii = 0; ii < ns4; ++ii) {\n                    is = ii / ns3;\n                    js = (ii - ns3 * is) / ns2;\n                    ks = (ii - ns3 * is - ns2 * js) / ns;\n                    ls = ii % ns;\n\n                    if (is < js) continue;\n\n                    ret = std::complex<double>(0.0, 0.0);\n\n                    for (i = 0; i < ngroup_v4; ++i) {\n\n                        ret += v4_array_at_kpair[i]\n                               * std::conj(evec_in[knum][is][ind[i][0]])\n                               * evec_in[knum][js][ind[i][1]]\n                               * evec_in[jk][ks][ind[i][2]]\n                               * std::conj(evec_in[jk][ls][ind[i][3]]);\n                    }\n\n                    v4_mpi[ik_prod][ns * is + js][ns * ks + ls] = factor * ret;\n                }\n\n            } else {\n\n#pragma omp parallel for private(is, js, ret, i)\n                for (ii = 0; ii < ns2; ++ii) {\n                    is = ii / ns;\n                    js = ii % ns;\n\n                    ret = std::complex<double>(0.0, 0.0);\n\n                    for (i = 0; i < ngroup_v4; ++i) {\n\n                        ret += v4_array_at_kpair[i]\n                               * std::conj(evec_in[knum][is][ind[i][0]])\n                               * evec_in[knum][is][ind[i][1]]\n                               * evec_in[jk][js][ind[i][2]]\n                               * std::conj(evec_in[jk][js][ind[i][3]]);\n                    }\n\n                    v4_mpi[ik_prod][(ns + 1) * is][(ns + 1) * js] = factor * ret;\n                }\n            }\n        }\n    }\n\n    memory->deallocate(v4_array_at_kpair);\n    memory->deallocate(ind);\n\n// Now, communicate the calculated data.\n// When the data count is larger than 2^31-1, split it.\n\n    long maxsize = 1;\n    maxsize = (maxsize << 31) - 1;\n\n    const size_t count = nk2_prod * ns4;\n    const size_t count_sub = ns4;\n\n    if (count <= maxsize) {\n#ifdef MPI_CXX_DOUBLE_COMPLEX\n        MPI_Allreduce(&v4_mpi[0][0][0], &v4_out[0][0][0], count,\n                      MPI_CXX_DOUBLE_COMPLEX, MPI_SUM, MPI_COMM_WORLD);\n#else\n        MPI_Allreduce(&v4_mpi[0][0][0], &v4_out[0][0][0], count,\n                      MPI_COMPLEX16, MPI_SUM, MPI_COMM_WORLD);\n#endif\n    } else if (count_sub <= maxsize) {\n        for (size_t ik_prod = 0; ik_prod < nk2_prod; ++ik_prod) {\n#ifdef MPI_CXX_DOUBLE_COMPLEX\n            MPI_Allreduce(&v4_mpi[ik_prod][0][0], &v4_out[ik_prod][0][0],\n                          count_sub,\n                          MPI_CXX_DOUBLE_COMPLEX, MPI_SUM, MPI_COMM_WORLD);\n#else\n            MPI_Allreduce(&v4_mpi[ik_prod][0][0], &v4_out[ik_prod][0][0],\n                          count_sub,\n                          MPI_COMPLEX16, MPI_SUM, MPI_COMM_WORLD);\n#endif\n        }\n    } else {\n        for (size_t ik_prod = 0; ik_prod < nk2_prod; ++ik_prod) {\n            for (is = 0; is < ns2; ++is) {\n#ifdef MPI_CXX_DOUBLE_COMPLEX\n                MPI_Allreduce(&v4_mpi[ik_prod][is][0], &v4_out[ik_prod][is][0],\n                              ns2,\n                              MPI_CXX_DOUBLE_COMPLEX, MPI_SUM, MPI_COMM_WORLD);\n#else\n                MPI_Allreduce(&v4_mpi[ik_prod][is][0], &v4_out[ik_prod][is][0],\n                              ns2,\n                              MPI_COMPLEX16, MPI_SUM, MPI_COMM_WORLD);\n#endif\n            }\n        }\n    }\n\n    memory->deallocate(v4_mpi);\n\n    zerofill_elements_acoustic_at_gamma(omega2_harmonic, v4_out, 4);\n\n\n    if (mympi->my_rank == 0) {\n        std::cout << \" done !\" << std::endl;\n        timer->print_elapsed();\n    }\n}\n\nvoid Scph::compute_V4_elements_mpi_over_band(std::complex<double> ***v4_out,\n                                             std::complex<double> ***evec_in,\n                                             const bool self_offdiag)\n{\n    // Calculate the matrix elements of quartic terms in reciprocal space.\n    // This is the most expensive part of the SCPH calculation.\n\n    size_t ik_prod;\n    const size_t nk_reduced_interpolate = kp_irred_interpolate.size();\n    const size_t ns = dynamical->neval;\n    const size_t ns2 = ns * ns;\n    const size_t ns4 = ns * ns * ns * ns;\n    int is, js;\n    unsigned int knum;\n    double phase3[3];\n    int loc3[3];\n    unsigned int **ind;\n    unsigned int i, j;\n    long int *nset_mpi;\n\n    auto inv2pi = 1.0 / (2.0 * pi);\n    auto dnk_represent = static_cast<double>(nk_represent);\n    auto factor = std::pow(0.5, 2) / static_cast<double>(nk_scph);\n    static auto complex_zero = std::complex<double>(0.0, 0.0);\n    std::complex<double> *v4_array_at_kpair;\n    std::complex<double> ***v4_mpi;\n\n    std::vector<int> ik_vec, jk_vec, is_vec, js_vec;\n\n    auto nk2_prod = nk_reduced_interpolate * nk_scph;\n\n    if (mympi->my_rank == 0) {\n        if (self_offdiag) {\n            std::cout << \" IALGO = 1 : Use different algorithm efficient when nbands >> nk\\n\";\n            std::cout << \" SELF_OFFDIAG = 1: Calculating all components of v4_array ... \\n\";\n        } else {\n            error->exit(\"compute_V4_elements_mpi_over_kpoint\",\n                        \"This function can be used only when SELF_OFFDIAG = 1\");\n        }\n    }\n\n    memory->allocate(nset_mpi, mympi->nprocs);\n\n    long int nset_tot = nk2_prod * ((ns2 - ns) / 2 + ns);\n    long int nset_each = nset_tot / mympi->nprocs;\n    long int nres = nset_tot - nset_each * mympi->nprocs;\n\n    for (i = 0; i < mympi->nprocs; ++i) {\n        nset_mpi[i] = nset_each;\n        if (nres > i) {\n            nset_mpi[i] += 1;\n        }\n    }\n\n    MPI_Bcast(&nset_mpi[0], mympi->nprocs, MPI_LONG, 0, MPI_COMM_WORLD);\n    long int nstart = 0;\n    for (i = 0; i < mympi->my_rank; ++i) {\n        nstart += nset_mpi[i];\n    }\n    long int nend = nstart + nset_mpi[mympi->my_rank];\n    nset_each = nset_mpi[mympi->my_rank];\n    memory->deallocate(nset_mpi);\n\n    ik_vec.clear();\n    jk_vec.clear();\n    is_vec.clear();\n    js_vec.clear();\n\n    long int icount = 0;\n    for (ik_prod = 0; ik_prod < nk2_prod; ++ik_prod) {\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                if (is < js) continue;\n\n                if (icount >= nstart && icount < nend) {\n                    ik_vec.push_back(ik_prod / nk_scph);\n                    jk_vec.push_back(ik_prod % nk_scph);\n                    is_vec.push_back(is);\n                    js_vec.push_back(js);\n                }\n                ++icount;\n            }\n        }\n    }\n\n    memory->allocate(v4_array_at_kpair, ngroup_v4);\n    memory->allocate(ind, ngroup_v4, 4);\n    memory->allocate(v4_mpi, nk2_prod, ns2, ns2);\n\n    for (ik_prod = 0; ik_prod < nk2_prod; ++ik_prod) {\n#pragma omp parallel for private (js)\n        for (is = 0; is < ns2; ++is) {\n            for (js = 0; js < ns2; ++js) {\n                v4_mpi[ik_prod][is][js] = complex_zero;\n                v4_out[ik_prod][is][js] = complex_zero;\n            }\n        }\n    }\n\n    int ik_old = -1;\n    int jk_old = -1;\n\n    if (mympi->my_rank == 0) {\n        std::cout << \" Total number of sets to compute : \" << nset_each << std::endl;\n    }\n\n    for (long int ii = 0; ii < nset_each; ++ii) {\n\n        auto ik_now = ik_vec[ii];\n        auto jk_now = jk_vec[ii];\n        auto is_now = is_vec[ii];\n        auto js_now = js_vec[ii];\n\n        if (!(ik_now == ik_old && jk_now == jk_old)) {\n\n            // Update v4_array_at_kpair and ind\n\n            knum = kmap_interpolate_to_scph[kp_irred_interpolate[ik_now][0].knum];\n\n            for (is = 0; is < ngroup_v4; ++is) v4_array_at_kpair[is] = complex_zero;\n\n            for (i = 0; i < ngroup_v4; ++i) {\n\n                std::complex<double> sum_tmp = std::complex<double>(0.0, 0.0);\n                for (j = 0; j < 4; ++j) ind[i][j] = evec_index_v4[i][j];\n\n                if (tune_type == 0) {\n                    for (j = 0; j < fcs_group_v4[i].size(); ++j) {\n                        auto phase = xk_scph[knum][0] * relvec_v4[i][j].vecs[0][0]\n                                     + xk_scph[knum][1] * relvec_v4[i][j].vecs[0][1]\n                                     + xk_scph[knum][2] * relvec_v4[i][j].vecs[0][2]\n                                     + xk_scph[jk_now][0] * (relvec_v4[i][j].vecs[1][0] - relvec_v4[i][j].vecs[2][0])\n                                     + xk_scph[jk_now][1] * (relvec_v4[i][j].vecs[1][1] - relvec_v4[i][j].vecs[2][1])\n                                     + xk_scph[jk_now][2] * (relvec_v4[i][j].vecs[1][2] - relvec_v4[i][j].vecs[2][2]);\n\n                        auto loc = nint(phase * dnk_represent * inv2pi) % nk_represent + nk_represent - 1;\n\n                        sum_tmp += fcs_group_v4[i][j] * invmass_v4[i] * exp_phase[loc];\n                    }\n                } else if (tune_type == 1) {\n                    for (j = 0; j < fcs_group_v4[i].size(); ++j) {\n\n                        for (unsigned int k = 0; k < 3; ++k) {\n                            phase3[k] =  xk_scph[knum][k] * relvec_v4[i][j].vecs[0][k]\n                                        + xk_scph[jk_now][k] * (relvec_v4[i][j].vecs[1][k]\n                                                                - relvec_v4[i][j].vecs[2][k]);\n                            loc3[k] = nint(phase3[k] * dnk[k] * inv2pi) % nk_grid[k] + nk_grid[k] - 1;\n                        }\n\n                        sum_tmp += fcs_group_v4[i][j] * invmass_v4[i]\n                                   * exp_phase3[loc3[0]][loc3[1]][loc3[2]];\n                    }\n                }\n                v4_array_at_kpair[i] = sum_tmp;\n            }\n            ik_old = ik_now;\n            jk_old = jk_now;\n        }\n\n        ik_prod = ik_now * nk_scph + jk_now;\n        int is_prod = ns * is_now + js_now;\n\n#pragma omp parallel for private (i)\n        for (js = 0; js < ns2; ++js) {\n\n            unsigned int ks = js / ns;\n            unsigned int ls = js % ns;\n\n            auto ret = std::complex<double>(0.0, 0.0);\n\n            for (i = 0; i < ngroup_v4; ++i) {\n\n                ret += v4_array_at_kpair[i]\n                       * std::conj(evec_in[knum][is_now][ind[i][0]])\n                       * evec_in[knum][js_now][ind[i][1]]\n                       * evec_in[jk_now][ks][ind[i][2]]\n                       * std::conj(evec_in[jk_now][ls][ind[i][3]]);\n            }\n\n            v4_mpi[ik_prod][is_prod][js] = factor * ret;\n        }\n\n        if (mympi->my_rank == 0) {\n            std::cout << \" SET \" << ii + 1 << \" done. \" << std::endl;\n        }\n\n    } // loop over nk2_prod*ns2\n\n    memory->deallocate(v4_array_at_kpair);\n    memory->deallocate(ind);\n\n// Now, communicate the calculated data.\n// When the data count is larger than 2^31-1, split it.\n\n    long maxsize = 1;\n    maxsize = (maxsize << 31) - 1;\n\n    const size_t count = nk2_prod * ns4;\n    const size_t count_sub = ns4;\n\n    if (mympi->my_rank == 0) {\n        std::cout << \"Communicating v4_array over MPI ...\";\n    }\n    if (count <= maxsize) {\n#ifdef MPI_CXX_DOUBLE_COMPLEX\n        MPI_Allreduce(&v4_mpi[0][0][0], &v4_out[0][0][0], count,\n                      MPI_CXX_DOUBLE_COMPLEX, MPI_SUM, MPI_COMM_WORLD);\n#else\n        MPI_Allreduce(&v4_mpi[0][0][0], &v4_out[0][0][0], count,\n                      MPI_COMPLEX16, MPI_SUM, MPI_COMM_WORLD);\n#endif\n    } else if (count_sub <= maxsize) {\n        for (size_t ik_prod = 0; ik_prod < nk2_prod; ++ik_prod) {\n#ifdef MPI_CXX_DOUBLE_COMPLEX\n            MPI_Allreduce(&v4_mpi[ik_prod][0][0], &v4_out[ik_prod][0][0],\n                          count_sub,\n                          MPI_CXX_DOUBLE_COMPLEX, MPI_SUM, MPI_COMM_WORLD);\n#else\n            MPI_Allreduce(&v4_mpi[ik_prod][0][0], &v4_out[ik_prod][0][0],\n                          count_sub,\n                          MPI_COMPLEX16, MPI_SUM, MPI_COMM_WORLD);\n#endif\n        }\n    } else {\n        for (size_t ik_prod = 0; ik_prod < nk2_prod; ++ik_prod) {\n            for (is = 0; is < ns2; ++is) {\n#ifdef MPI_CXX_DOUBLE_COMPLEX\n                MPI_Allreduce(&v4_mpi[ik_prod][is][0], &v4_out[ik_prod][is][0],\n                              ns2,\n                              MPI_CXX_DOUBLE_COMPLEX, MPI_SUM, MPI_COMM_WORLD);\n#else\n                MPI_Allreduce(&v4_mpi[ik_prod][is][0], &v4_out[ik_prod][is][0],\n                              ns2,\n                              MPI_COMPLEX16, MPI_SUM, MPI_COMM_WORLD);\n#endif\n            }\n        }\n    }\n    if (mympi->my_rank == 0) {\n        std::cout << \"done.\\n\";\n    }\n\n    memory->deallocate(v4_mpi);\n\n    zerofill_elements_acoustic_at_gamma(omega2_harmonic, v4_out, 4);\n\n    if (mympi->my_rank == 0) {\n        std::cout << \" done !\" << std::endl;\n        timer->print_elapsed();\n    }\n}\n\nvoid Scph::zerofill_elements_acoustic_at_gamma(double **omega2,\n                                               std::complex<double> ***v_elems,\n                                               const int fc_order) const\n{\n    // Set V3 or V4 elements involving acoustic modes at Gamma point\n    // exactly zero.\n\n    int jk;\n    int is, js, ks, ls;\n    const auto ns = dynamical->neval;\n    bool *is_acoustic;\n    memory->allocate(is_acoustic, ns);\n    int nacoustic;\n    auto threshould = 1.0e-24;\n    const auto nk_reduced_interpolate = kp_irred_interpolate.size();\n    static auto complex_zero = std::complex<double>(0.0, 0.0);\n\n\n    if (!(fc_order == 3 || fc_order == 4)) {\n        error->exit(\"zerofill_elements_acoustic_at_gamma\",\n                    \"The fc_order must be either 3 or 4.\");\n    }\n\n    do {\n        nacoustic = 0;\n        for (is = 0; is < ns; ++is) {\n            if (std::abs(omega2[0][is]) < threshould) {\n                is_acoustic[is] = true;\n                ++nacoustic;\n            } else {\n                is_acoustic[is] = false;\n            }\n        }\n        if (nacoustic > 3) {\n            error->exit(\"zerofill_elements_acoustic_at_gamma\",\n                        \"Could not assign acoustic modes at Gamma.\");\n        }\n        threshould *= 2.0;\n    } while (nacoustic < 3);\n\n\n    if (fc_order == 3) {\n\n        // Set V3 to zeros so as to avoid mixing with gamma acoustic modes\n        // jk = 0;\n        for (is = 0; is < ns; ++is) {\n            for (ks = 0; ks < ns; ++ks) {\n                for (ls = 0; ls < ns; ++ls) {\n                    if (is_acoustic[ks] || is_acoustic[ls]) {\n                        v_elems[0][is][ns * ks + ls] = complex_zero;\n                    }\n                }\n            }\n        }\n\n        // ik = 0;\n        for (jk = 0; jk < nk_scph; ++jk) {\n            for (is = 0; is < ns; ++is) {\n                if (is_acoustic[is]) {\n                    for (ks = 0; ks < ns; ++ks) {\n                        for (ls = 0; ls < ns; ++ls) {\n                            v_elems[jk][is][ns * ks + ls] = complex_zero;\n                        }\n                    }\n                }\n            }\n        }\n\n    } else if (fc_order == 4) {\n        // Set V4 to zeros so as to avoid mixing with gamma acoustic modes\n        // jk = 0;\n        for (int ik = 0; ik < nk_reduced_interpolate; ++ik) {\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    for (ks = 0; ks < ns; ++ks) {\n                        for (ls = 0; ls < ns; ++ls) {\n                            if (is_acoustic[ks] || is_acoustic[ls]) {\n                                v_elems[nk_scph * ik][ns * is + js][ns * ks + ls] = complex_zero;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        // ik = 0;\n        for (jk = 0; jk < nk_scph; ++jk) {\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    if (is_acoustic[is] || is_acoustic[js]) {\n                        for (ks = 0; ks < ns; ++ks) {\n                            for (ls = 0; ls < ns; ++ls) {\n                                v_elems[jk][ns * is + js][ns * ks + ls] = complex_zero;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n\n    }\n\n    memory->deallocate(is_acoustic);\n}\n\n\nvoid Scph::setup_kmesh()\n{\n    unsigned int ik;\n    unsigned int i;\n    double xtmp[3];\n\n    // Setup k points for SCPH equation\n    MPI_Bcast(&kmesh_scph[0], 3, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n    MPI_Bcast(&kmesh_interpolate[0], 3, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n\n    // Set up k points for Fourier interpolation\n    nk_scph = kmesh_scph[0] * kmesh_scph[1] * kmesh_scph[2];\n    nk_interpolate = kmesh_interpolate[0] * kmesh_interpolate[1] * kmesh_interpolate[2];\n\n    memory->allocate(xk_scph, nk_scph, 3);\n    memory->allocate(xk_interpolate, nk_interpolate, 3);\n    memory->allocate(kvec_na_scph, nk_scph, 3);\n\n    kpoint->gen_kmesh(true,\n                      kmesh_scph,\n                      xk_scph,\n                      kp_irred_scph);\n\n    kpoint->gen_kmesh(true,\n                      kmesh_interpolate,\n                      xk_interpolate,\n                      kp_irred_interpolate);\n\n\n    for (ik = 0; ik < nk_scph; ++ik) {\n        for (i = 0; i < 3; ++i) {\n            kvec_na_scph[ik][i] = 0.0;\n        }\n    }\n\n    for (ik = 0; ik < nk_scph; ++ik) {\n\n        for (i = 0; i < 3; ++i) xtmp[i] = xk_scph[ik][i];\n        rotvec(xtmp, xtmp, system->rlavec_p, 'T');\n        const auto norm = xtmp[0] * xtmp[0] + xtmp[1] * xtmp[1] + xtmp[2] * xtmp[2];\n\n        if (norm > eps) {\n            for (i = 0; i < 3; ++i) kvec_na_scph[ik][i] = xk_scph[ik][i] / std::sqrt(norm);\n        }\n    }\n\n    if (mympi->my_rank == 0) {\n//        if (verbosity > 0) {\n        std::cout << \" Setting up the SCPH calculations ...\" << std::endl << std::endl;\n        std::cout << \"  Gamma-centered uniform grid with the following mesh density:\" << std::endl;\n        std::cout << \"  nk1:\" << std::setw(5) << kmesh_scph[0] << std::endl;\n        std::cout << \"  nk2:\" << std::setw(5) << kmesh_scph[1] << std::endl;\n        std::cout << \"  nk3:\" << std::setw(5) << kmesh_scph[2] << std::endl;\n        std::cout << std::endl;\n        std::cout << \"  Number of k points : \" << nk_scph << std::endl;\n        std::cout << \"  Number of irreducible k points : \" << kp_irred_scph.size() << std::endl;\n        std::cout << std::endl;\n        std::cout << \"  Fourier interpolation from reciprocal to real space\" << std::endl;\n        std::cout << \"  will be performed with the following mesh density:\" << std::endl;\n        std::cout << \"  nk1:\" << std::setw(5) << kmesh_interpolate[0] << std::endl;\n        std::cout << \"  nk2:\" << std::setw(5) << kmesh_interpolate[1] << std::endl;\n        std::cout << \"  nk3:\" << std::setw(5) << kmesh_interpolate[2] << std::endl;\n        std::cout << std::endl;\n        std::cout << \"  Number of k points : \" << nk_interpolate << std::endl;\n        std::cout << \"  Number of irreducible k points : \"\n                  << kp_irred_interpolate.size() << std::endl;\n//        }\n    }\n\n    memory->allocate(kmap_interpolate_to_scph, nk_interpolate);\n\n    for (ik = 0; ik < nk_interpolate; ++ik) {\n        for (i = 0; i < 3; ++i) xtmp[i] = xk_interpolate[ik][i];\n\n        const auto loc = kpoint->get_knum(xtmp, kmesh_scph);\n\n        if (loc == -1)\n            error->exit(\"setup_kmesh\",\n                        \"KMESH_INTERPOLATE should be a integral multiple of KMESH_SCPH\");\n        kmap_interpolate_to_scph[ik] = loc;\n    }\n}\n\n\nvoid Scph::setup_transform_symmetry()\n{\n    // Construct small_group_at_k, symop_minus_at_k, and\n    // mat_transport_sym.\n\n    unsigned int ik;\n    unsigned int is, js;\n    unsigned int icrd, jcrd;\n    double x1[3], x2[3], k[3], k_minus[3], Sk[3], xtmp[3];\n    double S_cart[3][3], S_frac[3][3], S_frac_inv[3][3];\n    double S_recip[3][3];\n    std::complex<double> im(0.0, 1.0);\n    std::complex<double> **gamma_tmp;\n    bool *flag;\n\n    const auto natmin = system->natmin;\n    const auto ns = dynamical->neval;\n    const auto nk_irred_interpolate = kp_irred_interpolate.size();\n\n    memory->allocate(gamma_tmp, ns, ns);\n    memory->allocate(mat_transform_sym, nk_irred_interpolate,\n                     symmetry->nsym, ns, ns);\n    memory->allocate(small_group_at_k, nk_irred_interpolate);\n    memory->allocate(symop_minus_at_k, nk_irred_interpolate);\n    memory->allocate(kpoint_map_symmetry, nk_interpolate);\n    memory->allocate(flag, nk_interpolate);\n\n    for (ik = 0; ik < nk_interpolate; ++ik) {\n        flag[ik] = false;\n    }\n\n    for (ik = 0; ik < kp_irred_interpolate.size(); ++ik) {\n\n        small_group_at_k[ik].clear();\n        symop_minus_at_k[ik].clear();\n\n        const auto knum = kp_irred_interpolate[ik][0].knum;\n        for (icrd = 0; icrd < 3; ++icrd) {\n            k[icrd] = xk_interpolate[knum][icrd];\n            k_minus[icrd] = -k[icrd];\n        }\n        const auto knum_minus = kpoint->get_knum(k_minus, kmesh_interpolate);\n\n        unsigned int isym = 0;\n\n        for (const auto &it : symmetry->SymmListWithMap) {\n\n            for (icrd = 0; icrd < 3; ++icrd) {\n                for (jcrd = 0; jcrd < 3; ++jcrd) {\n                    S_cart[icrd][jcrd] = it.rot[3 * icrd + jcrd];\n                    S_frac[icrd][jcrd] = it.rot_real[3 * icrd + jcrd];\n                    S_recip[icrd][jcrd] = it.rot_reciprocal[3 * icrd + jcrd];\n                }\n            }\n\n            invmat3(S_frac_inv, S_frac);\n            rotvec(Sk, k, S_recip);\n\n            for (auto i = 0; i < 3; ++i) Sk[i] = Sk[i] - nint(Sk[i]);\n\n            const auto knum_sym = kpoint->get_knum(Sk, kmesh_interpolate);\n            if (knum_sym == -1)\n                error->exit(\"setup_transform_symmetry\",\n                            \"kpoint not found\");\n\n            if (knum_sym == knum) small_group_at_k[ik].push_back(isym);\n            if (knum_sym == knum_minus) symop_minus_at_k[ik].push_back(isym);\n\n            if (!flag[knum_sym]) {\n                kpoint_map_symmetry[knum_sym].symmetry_op = isym;\n                kpoint_map_symmetry[knum_sym].knum_irred_orig = ik;\n                kpoint_map_symmetry[knum_sym].knum_orig = knum;\n                flag[knum_sym] = true;\n            }\n\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    gamma_tmp[is][js] = std::complex<double>(0.0, 0.0);\n                }\n            }\n\n            for (unsigned int jat = 0; jat < natmin; ++jat) {\n                const auto iat = it.mapping[jat];\n\n                // Fractional coordinates of x1 and x2\n                for (icrd = 0; icrd < 3; ++icrd) {\n                    x1[icrd] = system->xr_p[system->map_p2s[iat][0]][icrd];\n                    x2[icrd] = system->xr_p[system->map_p2s[jat][0]][icrd];\n                }\n\n                rotvec(xtmp, x1, S_frac_inv);\n                for (icrd = 0; icrd < 3; ++icrd) {\n                    xtmp[icrd] = xtmp[icrd] - x2[icrd];\n                }\n\n                auto phase = 2.0 * pi * (k[0] * xtmp[0] + k[1] * xtmp[1] + k[2] * xtmp[2]);\n\n                for (icrd = 0; icrd < 3; ++icrd) {\n                    for (jcrd = 0; jcrd < 3; ++jcrd) {\n                        gamma_tmp[3 * iat + icrd][3 * jat + jcrd]\n                                = S_cart[icrd][jcrd] * std::exp(im * phase);\n                    }\n                }\n            }\n\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    mat_transform_sym[ik][isym][is][js] = gamma_tmp[is][js];\n                }\n            }\n\n            ++isym;\n        }\n    }\n\n    memory->deallocate(gamma_tmp);\n    memory->deallocate(flag);\n}\n\n\nvoid Scph::symmetrize_dynamical_matrix(const unsigned int ik,\n                                       Eigen::MatrixXcd &dymat) const\n{\n    // Symmetrize the dynamical matrix of given index ik.\n    using namespace Eigen;\n    unsigned int i, isym;\n    unsigned int is, js;\n    const auto ns = dynamical->neval;\n    MatrixXcd dymat_sym = MatrixXcd::Zero(ns, ns);\n    MatrixXcd dymat_tmp(ns, ns), gamma(ns, ns);\n\n    const auto nsym_small = small_group_at_k[ik].size();\n    const auto nsym_minus = symop_minus_at_k[ik].size();\n\n    for (i = 0; i < nsym_minus; ++i) {\n        isym = symop_minus_at_k[ik][i];\n\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                gamma(is, js) = mat_transform_sym[ik][isym][is][js];\n            }\n        }\n\n        dymat_tmp = gamma * dymat * gamma.transpose().conjugate();\n        dymat_sym += dymat_tmp.conjugate();\n    }\n\n    for (i = 0; i < nsym_small; ++i) {\n        isym = small_group_at_k[ik][i];\n\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                gamma(is, js) = mat_transform_sym[ik][isym][is][js];\n            }\n        }\n\n        dymat_tmp = gamma * dymat * gamma.transpose().conjugate();\n        dymat_sym += dymat_tmp;\n    }\n\n\n    dymat = dymat_sym / static_cast<double>(nsym_small + nsym_minus);\n}\n\nvoid Scph::replicate_dymat_for_all_kpoints(std::complex<double> ***dymat_inout) const\n{\n    using namespace Eigen;\n    unsigned int i;\n    unsigned int is, js;\n    const auto ns = dynamical->neval;\n    MatrixXcd dymat_tmp(ns, ns), gamma(ns, ns), dymat(ns, ns);\n\n    std::complex<double> ***dymat_all;\n\n    memory->allocate(dymat_all, ns, ns, nk_interpolate);\n\n    for (i = 0; i < nk_interpolate; ++i) {\n\n        const auto ik_irred = kpoint_map_symmetry[i].knum_irred_orig;\n        const auto ik_orig = kpoint_map_symmetry[i].knum_orig;\n        const auto isym = kpoint_map_symmetry[i].symmetry_op;\n\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                gamma(is, js) = mat_transform_sym[ik_irred][isym][is][js];\n                dymat(is, js) = dymat_inout[is][js][ik_orig];\n            }\n        }\n        dymat_tmp = gamma * dymat * gamma.transpose().conjugate();\n\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                dymat_all[is][js][i] = dymat_tmp(is, js);\n            }\n        }\n    }\n\n    for (is = 0; is < ns; ++is) {\n        for (js = 0; js < ns; ++js) {\n            for (i = 0; i < nk_interpolate; ++i) {\n                dymat_inout[is][js][i] = dymat_all[is][js][i];\n            }\n        }\n    }\n    memory->deallocate(dymat_all);\n}\n\nvoid Scph::setup_eigvecs()\n{\n    const auto ns = dynamical->neval;\n\n    if (mympi->my_rank == 0) {\n        std::cout << std::endl\n                  << \" Diagonalizing dynamical matrices for all k points ... \";\n    }\n\n    memory->allocate(evec_harmonic, nk_scph, ns, ns);\n    memory->allocate(omega2_harmonic, nk_scph, ns);\n\n    // Calculate phonon eigenvalues and eigenvectors for all k-points for scph\n\n#pragma omp parallel for\n    for (int ik = 0; ik < nk_scph; ++ik) {\n\n        dynamical->eval_k(xk_scph[ik], kvec_na_scph[ik],\n                          fcs_phonon->fc2_ext, omega2_harmonic[ik],\n                          evec_harmonic[ik], true);\n    }\n\n    if (mympi->my_rank == 0) {\n        std::cout << \"done !\" << std::endl;\n    }\n}\n\nvoid Scph::setup_pp_interaction()\n{\n    // Prepare information for calculating ph-ph interaction coefficients.\n\n    unsigned int i, j;\n    double *invsqrt_mass_p;\n\n    if (mympi->my_rank == 0) {\n        if (relax_coordinate || bubble > 0) {\n            std::cout << \" Preparing for calculating V3 & V4  ...\";\n        } else {\n            std::cout << \" Preparing for calculating V4  ...\";\n        }\n    }\n\n    if (anharmonic_core->quartic_mode != 1) {\n        error->exit(\"setup_pp_interaction\",\n                    \"quartic_mode should be 1 for SCPH\");\n    }\n\n    memory->allocate(invsqrt_mass_p, system->natmin);\n\n    for (i = 0; i < system->natmin; ++i) {\n        invsqrt_mass_p[i] = std::sqrt(1.0 / system->mass[system->map_p2s[i][0]]);\n    }\n\n    // Setup for V3 if relax_coordinate = True.\n    if (relax_coordinate || bubble > 0) {\n\n        std::sort(fcs_phonon->force_constant_with_cell[1].begin(),\n                  fcs_phonon->force_constant_with_cell[1].end());\n\n        anharmonic_core->prepare_group_of_force_constants(fcs_phonon->force_constant_with_cell[1], 3,\n                                                          ngroup_v3, fcs_group_v3);\n        memory->allocate(invmass_v3, ngroup_v3);\n        memory->allocate(evec_index_v3, ngroup_v3, 3);\n        memory->allocate(relvec_v3, ngroup_v3);\n        memory->allocate(phi3_reciprocal, ngroup_v3);\n\n        anharmonic_core->prepare_relative_vector(fcs_phonon->force_constant_with_cell[1],\n                                                 3,\n                                                 ngroup_v3,\n                                                 fcs_group_v3,\n                                                 relvec_v3);\n\n        int k = 0;\n        for (i = 0; i < ngroup_v3; ++i) {\n            for (int j = 0; j < 3; ++j) {\n                evec_index_v3[i][j] = fcs_phonon->force_constant_with_cell[1][k].pairs[j].index;\n            }\n            invmass_v3[i]\n                    = invsqrt_mass_p[evec_index_v3[i][0] / 3]\n                      * invsqrt_mass_p[evec_index_v3[i][1] / 3]\n                      * invsqrt_mass_p[evec_index_v3[i][2] / 3];\n            k += fcs_group_v3[i].size();\n        }\n    }\n\n    std::sort(fcs_phonon->force_constant_with_cell[2].begin(),\n              fcs_phonon->force_constant_with_cell[2].end());\n\n    anharmonic_core->prepare_group_of_force_constants(fcs_phonon->force_constant_with_cell[2], 4,\n                                                      ngroup_v4, fcs_group_v4);\n\n    memory->allocate(invmass_v4, ngroup_v4);\n    memory->allocate(evec_index_v4, ngroup_v4, 4);\n    memory->allocate(relvec_v4, ngroup_v4);\n    // memory->allocate(phi4_reciprocal, ngroup_v4);\n\n    anharmonic_core->prepare_relative_vector(fcs_phonon->force_constant_with_cell[2],\n                                             4,\n                                             ngroup_v4,\n                                             fcs_group_v4,\n                                             relvec_v4);\n\n    int k = 0;\n    for (i = 0; i < ngroup_v4; ++i) {\n        for (int j = 0; j < 4; ++j) {\n            evec_index_v4[i][j] = fcs_phonon->force_constant_with_cell[2][k].pairs[j].index;\n        }\n        invmass_v4[i]\n                = invsqrt_mass_p[evec_index_v4[i][0] / 3]\n                  * invsqrt_mass_p[evec_index_v4[i][1] / 3]\n                  * invsqrt_mass_p[evec_index_v4[i][2] / 3]\n                  * invsqrt_mass_p[evec_index_v4[i][3] / 3];\n        k += fcs_group_v4[i].size();\n    }\n\n    memory->deallocate(invsqrt_mass_p);\n\n    nk_grid[0] = kmesh_scph[0];\n    nk_grid[1] = kmesh_scph[1];\n    nk_grid[2] = kmesh_scph[2];\n\n    for (i = 0; i < 3; ++i) dnk[i] = static_cast<double>(nk_grid[i]);\n\n    if (nk_grid[0] == nk_grid[1] && nk_grid[1] == nk_grid[2]) {\n        nk_represent = nk_grid[0];\n        tune_type = 0;\n\n    } else if (nk_grid[0] == nk_grid[1] && nk_grid[2] == 1) {\n        nk_represent = nk_grid[0];\n        tune_type = 0;\n\n    } else if (nk_grid[1] == nk_grid[2] && nk_grid[0] == 1) {\n        nk_represent = nk_grid[1];\n        tune_type = 0;\n\n    } else if (nk_grid[2] == nk_grid[0] && nk_grid[1] == 1) {\n        nk_represent = nk_grid[2];\n        tune_type = 0;\n\n    } else if (nk_grid[0] == 1 && nk_grid[1] == 1) {\n        nk_represent = nk_grid[2];\n        tune_type = 0;\n\n    } else if (nk_grid[1] == 1 && nk_grid[2] == 1) {\n        nk_represent = nk_grid[0];\n        tune_type = 0;\n\n    } else if (nk_grid[2] == 1 && nk_grid[0] == 1) {\n        nk_represent = nk_grid[1];\n        tune_type = 0;\n\n    } else {\n        tune_type = 1;\n    }\n\n    int ii;\n\n    if (tune_type == 0) {\n\n        memory->allocate(exp_phase, 2 * nk_represent - 1);\n        for (ii = 0; ii < 2 * nk_represent - 1; ++ii) {\n            const auto phase = 2.0 * pi * static_cast<double>(ii - nk_represent + 1)\n                               / static_cast<double>(nk_represent);\n            exp_phase[ii] = std::exp(im * phase);\n        }\n\n    } else if (tune_type == 1) {\n        double phase[3];\n\n        tune_type = 1;\n        memory->allocate(exp_phase3, 2 * nk_grid[0] - 1, 2 * nk_grid[1] - 1, 2 * nk_grid[2] - 1);\n\n        for (ii = 0; ii < 2 * nk_grid[0] - 1; ++ii) {\n            phase[0] = 2.0 * pi * static_cast<double>(ii - nk_grid[0] + 1) / dnk[0];\n            for (int jj = 0; jj < 2 * nk_grid[1] - 1; ++jj) {\n                phase[1] = 2.0 * pi * static_cast<double>(jj - nk_grid[1] + 1) / dnk[1];\n                for (int kk = 0; kk < 2 * nk_grid[2] - 1; ++kk) {\n                    phase[2] = 2.0 * pi * static_cast<double>(kk - nk_grid[2] + 1) / dnk[2];\n                    exp_phase3[ii][jj][kk] = std::exp(im * (phase[0] + phase[1] + phase[2]));\n                }\n            }\n        }\n    }\n\n    if (mympi->my_rank == 0) {\n        std::cout << \" done!\" << std::endl;\n    }\n}\n\nvoid Scph::setup_transform_ifc()\n{\n    // Compute mindist_list_scph necessary to calculate dynamical matrix\n    // from the real-space force constants\n\n    int i, j;\n    int ix, iy, iz;\n    const auto nk = nk_interpolate;\n    const auto nat = system->natmin;\n    unsigned int iat;\n\n    int **shift_cell, **shift_cell_super;\n    double **xf_p;\n    double ****x_all;\n\n    const int nkx = kmesh_interpolate[0];\n    const int nky = kmesh_interpolate[1];\n    const int nkz = kmesh_interpolate[2];\n\n    const auto ncell = nk;\n    const auto ncell_s = 27;\n\n    memory->allocate(shift_cell, ncell, 3);\n    memory->allocate(shift_cell_super, ncell_s, 3);\n    memory->allocate(xf_p, nat, 3);\n    memory->allocate(x_all, ncell_s, ncell, nat, 3);\n\n    unsigned int icell = 0;\n    for (ix = 0; ix < nkx; ++ix) {\n        for (iy = 0; iy < nky; ++iy) {\n            for (iz = 0; iz < nkz; ++iz) {\n\n                shift_cell[icell][0] = ix;\n                shift_cell[icell][1] = iy;\n                shift_cell[icell][2] = iz;\n\n                ++icell;\n            }\n        }\n    }\n\n    for (i = 0; i < 3; ++i) shift_cell_super[0][i] = 0;\n    icell = 1;\n    for (ix = -1; ix <= 1; ++ix) {\n        for (iy = -1; iy <= 1; ++iy) {\n            for (iz = -1; iz <= 1; ++iz) {\n                if (ix == 0 && iy == 0 && iz == 0) continue;\n\n                shift_cell_super[icell][0] = ix;\n                shift_cell_super[icell][1] = iy;\n                shift_cell_super[icell][2] = iz;\n\n                ++icell;\n            }\n        }\n    }\n\n    for (i = 0; i < nat; ++i) {\n        rotvec(xf_p[i], system->xr_s[system->map_p2s[i][0]], system->lavec_s);\n        rotvec(xf_p[i], xf_p[i], system->rlavec_p);\n        for (j = 0; j < 3; ++j) xf_p[i][j] /= 2.0 * pi;\n    }\n\n    for (i = 0; i < ncell_s; ++i) {\n        for (j = 0; j < ncell; ++j) {\n            for (iat = 0; iat < nat; ++iat) {\n                x_all[i][j][iat][0] = xf_p[iat][0] + static_cast<double>(shift_cell[j][0])\n                                      + static_cast<double>(nkx * shift_cell_super[i][0]);\n                x_all[i][j][iat][1] = xf_p[iat][1] + static_cast<double>(shift_cell[j][1])\n                                      + static_cast<double>(nky * shift_cell_super[i][1]);\n                x_all[i][j][iat][2] = xf_p[iat][2] + static_cast<double>(shift_cell[j][2])\n                                      + static_cast<double>(nkz * shift_cell_super[i][2]);\n\n                rotvec(x_all[i][j][iat], x_all[i][j][iat], system->lavec_p);\n            }\n        }\n    }\n\n    double dist;\n    std::vector <DistList> dist_tmp;\n    ShiftCell shift_tmp{};\n    std::vector<int> vec_tmp;\n\n    memory->allocate(mindist_list_scph, nat, nat, ncell);\n\n    for (iat = 0; iat < nat; ++iat) {\n        for (unsigned int jat = 0; jat < nat; ++jat) {\n            for (icell = 0; icell < ncell; ++icell) {\n\n                dist_tmp.clear();\n                for (i = 0; i < ncell_s; ++i) {\n                    dist = distance(x_all[0][0][iat], x_all[i][icell][jat]);\n                    dist_tmp.emplace_back(i, dist);\n                }\n                std::sort(dist_tmp.begin(), dist_tmp.end());\n\n                const auto dist_min = dist_tmp[0].dist;\n                mindist_list_scph[iat][jat][icell].dist = dist_min;\n\n                for (i = 0; i < ncell_s; ++i) {\n                    dist = dist_tmp[i].dist;\n\n                    if (std::abs(dist_min - dist) < eps8) {\n\n                        shift_tmp.sx = shift_cell[icell][0]\n                                       + nkx * shift_cell_super[dist_tmp[i].cell_s][0];\n                        shift_tmp.sy = shift_cell[icell][1]\n                                       + nky * shift_cell_super[dist_tmp[i].cell_s][1];\n                        shift_tmp.sz = shift_cell[icell][2]\n                                       + nkz * shift_cell_super[dist_tmp[i].cell_s][2];\n\n                        mindist_list_scph[iat][jat][icell].shift.push_back(shift_tmp);\n                    }\n                }\n\n            }\n        }\n    }\n\n    memory->deallocate(shift_cell);\n    memory->deallocate(shift_cell_super);\n    memory->deallocate(xf_p);\n    memory->deallocate(x_all);\n}\n\n\nvoid Scph::exec_interpolation(const unsigned int kmesh_orig[3],\n                              std::complex<double> ***dymat_r,\n                              const unsigned int nk_dense,\n                              double **xk_dense,\n                              double **kvec_dense,\n                              double **eval_out,\n                              std::complex<double> ***evec_out)\n{\n    unsigned int i, j, is;\n    const auto ns = dynamical->neval;\n    const auto nk1 = kmesh_orig[0];\n    const auto nk2 = kmesh_orig[1];\n    const auto nk3 = kmesh_orig[2];\n\n    double *eval_real;\n    std::complex<double> **mat_tmp;\n    std::complex<double> **mat_harmonic, **mat_harmonic_na;\n    std::vector<double> eval_vec(ns);\n\n    memory->allocate(mat_tmp, ns, ns);\n    memory->allocate(eval_real, ns);\n    memory->allocate(mat_harmonic, ns, ns);\n\n    if (dynamical->nonanalytic) {\n        memory->allocate(mat_harmonic_na, ns, ns);\n    }\n\n    for (int ik = 0; ik < nk_dense; ++ik) {\n\n        if (dynamical->nonanalytic == 3) {\n            dynamical->calc_analytic_k(xk_dense[ik],\n                                       ewald->fc2_without_dipole,\n                                       mat_harmonic);\n        } else {\n            dynamical->calc_analytic_k(xk_dense[ik],\n                                       fcs_phonon->fc2_ext,\n                                       mat_harmonic);\n        }\n\n        r2q(xk_dense[ik], nk1, nk2, nk3, ns, dymat_r, mat_tmp);\n\n        for (i = 0; i < ns; ++i) {\n            for (j = 0; j < ns; ++j) {\n                mat_tmp[i][j] += mat_harmonic[i][j];\n            }\n        }\n\n        if (dynamical->nonanalytic) {\n\n            if (dynamical->nonanalytic == 1) {\n                dynamical->calc_nonanalytic_k(xk_dense[ik],\n                                              kvec_dense[ik],\n                                              mat_harmonic_na);\n            } else if (dynamical->nonanalytic == 2) {\n                dynamical->calc_nonanalytic_k2(xk_dense[ik],\n                                               kvec_dense[ik],\n                                               mat_harmonic_na);\n\n            } else if (dynamical->nonanalytic == 3) {\n                ewald->add_longrange_matrix(xk_dense[ik],\n                                            kvec_dense[ik],\n                                            mat_harmonic_na);\n            }\n\n            for (i = 0; i < ns; ++i) {\n                for (j = 0; j < ns; ++j) {\n                    mat_tmp[i][j] += mat_harmonic_na[i][j];\n                }\n            }\n        }\n\n        diagonalize_interpolated_matrix(mat_tmp, eval_real, evec_out[ik], true);\n\n        for (is = 0; is < ns; ++is) {\n            const auto eval_tmp = eval_real[is];\n\n            if (eval_tmp < 0.0) {\n                eval_vec[is] = -std::sqrt(-eval_tmp);\n            } else {\n                eval_vec[is] = std::sqrt(eval_tmp);\n            }\n        }\n\n        for (is = 0; is < ns; ++is) eval_out[ik][is] = eval_vec[is];\n\n    }\n\n    memory->deallocate(eval_real);\n    memory->deallocate(mat_tmp);\n    memory->deallocate(mat_harmonic);\n\n    if (dynamical->nonanalytic) {\n        memory->deallocate(mat_harmonic_na);\n    }\n}\n\n\nvoid Scph::r2q(const double *xk_in,\n               const unsigned int nx,\n               const unsigned int ny,\n               const unsigned int nz,\n               const unsigned int ns,\n               std::complex<double> ***dymat_r_in,\n               std::complex<double> **dymat_k_out) const\n{\n    std::complex<double> im(0.0, 1.0);\n\n    const auto ncell = nx * ny * nz;\n\n    for (unsigned int i = 0; i < ns; ++i) {\n\n        const auto iat = i / 3;\n\n        for (unsigned int j = 0; j < ns; ++j) {\n\n            const auto jat = j / 3;\n\n            dymat_k_out[i][j] = std::complex<double>(0.0, 0.0);\n\n            for (unsigned int icell = 0; icell < ncell; ++icell) {\n\n                auto exp_phase = std::complex<double>(0.0, 0.0);\n\n                // This operation is necessary for the Hermiticity of the dynamical matrix.\n                for (const auto &it : mindist_list_scph[iat][jat][icell].shift) {\n\n                    auto phase = 2.0 * pi\n                                 * (static_cast<double>(it.sx) * xk_in[0]\n                                    + static_cast<double>(it.sy) * xk_in[1]\n                                    + static_cast<double>(it.sz) * xk_in[2]);\n\n                    exp_phase += std::exp(im * phase);\n                }\n                exp_phase /= static_cast<double>(mindist_list_scph[iat][jat][icell].shift.size());\n\n                dymat_k_out[i][j] += dymat_r_in[i][j][icell] * exp_phase;\n            }\n\n        }\n    }\n}\n\n\nvoid Scph::diagonalize_interpolated_matrix(std::complex<double> **mat_in,\n                                           double *eval_out,\n                                           std::complex<double> **evec_out,\n                                           const bool require_evec) const\n{\n    unsigned int i, j;\n    char JOBZ;\n    int INFO;\n    double *RWORK;\n    std::complex<double> *amat;\n    std::complex<double> *WORK;\n\n    int ns = dynamical->neval;\n\n    int LWORK = (2 * ns - 1) * 10;\n    memory->allocate(RWORK, 3 * ns - 2);\n    memory->allocate(WORK, LWORK);\n\n\n    if (require_evec) {\n        JOBZ = 'V';\n    } else {\n        JOBZ = 'N';\n    }\n\n    char UPLO = 'U';\n\n    memory->allocate(amat, ns * ns);\n\n    unsigned int k = 0;\n    for (j = 0; j < ns; ++j) {\n        for (i = 0; i < ns; ++i) {\n            amat[k++] = mat_in[i][j];\n        }\n    }\n\n    zheev_(&JOBZ, &UPLO, &ns, amat, &ns, eval_out, WORK, &LWORK, RWORK, &INFO);\n\n    k = 0;\n\n    if (require_evec) {\n        // Here we transpose the matrix evec_out so that \n        // evec_out[i] becomes phonon eigenvector of i-th mode.\n        for (j = 0; j < ns; ++j) {\n            for (i = 0; i < ns; ++i) {\n                evec_out[j][i] = amat[k++];\n            }\n        }\n    }\n\n    memory->deallocate(amat);\n    memory->deallocate(WORK);\n    memory->deallocate(RWORK);\n}\n\nvoid Scph::find_degeneracy(std::vector<int> *degeneracy_out,\n                           const unsigned int nk_in,\n                           double **eval_in) const\n{\n    // eval is omega^2 in atomic unit\n\n    const auto ns = dynamical->neval;\n    const auto tol_omega = 1.0e-7;\n\n    for (unsigned int ik = 0; ik < nk_in; ++ik) {\n\n        degeneracy_out[ik].clear();\n\n        auto omega_prev = eval_in[ik][0];\n        auto ideg = 1;\n\n        for (unsigned int is = 1; is < ns; ++is) {\n            const auto omega_now = eval_in[ik][is];\n\n            if (std::abs(omega_now - omega_prev) < tol_omega) {\n                ++ideg;\n            } else {\n                degeneracy_out[ik].push_back(ideg);\n                ideg = 1;\n                omega_prev = omega_now;\n            }\n\n        }\n        degeneracy_out[ik].push_back(ideg);\n    }\n}\n\nvoid Scph::calc_new_dymat_with_evec(std::complex<double> ***dymat_out,\n                                    double **omega2_in,\n                                    std::complex<double> ***evec_in)\n{\n    std::complex<double> *polarization_matrix, *mat_tmp;\n    std::complex<double> *eigval_matrix, *dmat;\n    std::complex<double> *beta;\n    std::complex<double> ***dymat_q, **dymat_harmonic;\n    std::complex<double> im(0.0, 1.0);\n\n    unsigned int ik, is, js;\n    int ns = dynamical->neval;\n\n    const unsigned int ns2 = ns * ns;\n\n    auto alpha = std::complex<double>(1.0, 0.0);\n\n    char TRANSA[] = \"N\";\n    char TRANSB[] = \"C\";\n\n    memory->allocate(polarization_matrix, ns2);\n    memory->allocate(mat_tmp, ns2);\n    memory->allocate(eigval_matrix, ns2);\n    memory->allocate(beta, ns);\n    memory->allocate(dmat, ns2);\n    memory->allocate(dymat_q, ns, ns, nk_interpolate);\n    memory->allocate(dymat_harmonic, ns, ns);\n\n    for (is = 0; is < ns; ++is) beta[is] = std::complex<double>(0.0, 0.0);\n\n    for (ik = 0; ik < nk_interpolate; ++ik) {\n\n        const auto knum = kmap_interpolate_to_scph[ik];\n\n        // create eigval matrix\n\n        for (is = 0; is < ns2; ++is) eigval_matrix[is] = std::complex<double>(0.0, 0.0);\n\n        unsigned int m = 0;\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                if (is == js) {\n                    eigval_matrix[m] = omega2_in[knum][is];\n                }\n                ++m;\n            }\n        }\n\n        // create polarization matrix\n\n        m = 0;\n\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                polarization_matrix[m++] = evec_in[knum][is][js];\n            }\n        }\n\n        zgemm_(TRANSA, TRANSB, &ns, &ns, &ns, &alpha,\n               eigval_matrix, &ns, polarization_matrix, &ns, beta, mat_tmp, &ns);\n        zgemm_(TRANSA, TRANSA, &ns, &ns, &ns, &alpha,\n               polarization_matrix, &ns, mat_tmp, &ns, beta, dmat, &ns);\n\n        m = 0;\n\n        for (js = 0; js < ns; ++js) {\n            for (is = 0; is < ns; ++is) {\n                dymat_q[is][js][ik] = dmat[m];\n                ++m;\n            }\n        }\n\n\n        // Subtract harmonic contribution\n        dynamical->calc_analytic_k(xk_interpolate[ik],\n                                   fcs_phonon->fc2_ext,\n                                   dymat_harmonic);\n\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                dymat_q[is][js][ik] -= dymat_harmonic[is][js];\n            }\n        }\n    }\n\n    memory->deallocate(polarization_matrix);\n    memory->deallocate(mat_tmp);\n    memory->deallocate(eigval_matrix);\n    memory->deallocate(beta);\n    memory->deallocate(dmat);\n    memory->deallocate(dymat_harmonic);\n\n    const auto nk1 = kmesh_interpolate[0];\n    const auto nk2 = kmesh_interpolate[1];\n    const auto nk3 = kmesh_interpolate[2];\n\n    std::vector <std::vector<double>> xk_dup;\n\n    int icell = 0;\n\n    for (int ix = 0; ix < nk1; ++ix) {\n        for (int iy = 0; iy < nk2; ++iy) {\n            for (int iz = 0; iz < nk3; ++iz) {\n\n                for (is = 0; is < ns; ++is) {\n                    for (js = 0; js < ns; ++js) {\n                        dymat_out[is][js][icell] = std::complex<double>(0.0, 0.0);\n                    }\n                }\n\n                for (ik = 0; ik < nk_interpolate; ++ik) {\n\n                    duplicate_xk_boundary(xk_interpolate[ik], xk_dup);\n\n                    auto cexp_phase = std::complex<double>(0.0, 0.0);\n\n                    for (const auto &i : xk_dup) {\n\n                        auto phase = 2.0 * pi * (i[0] * static_cast<double>(ix)\n                                                 + i[1] * static_cast<double>(iy)\n                                                 + i[2] * static_cast<double>(iz));\n                        cexp_phase += std::exp(-im * phase);\n\n                    }\n                    cexp_phase /= static_cast<double>(xk_dup.size());\n\n                    for (is = 0; is < ns; ++is) {\n                        for (js = 0; js < ns; ++js) {\n                            dymat_out[is][js][icell] += dymat_q[is][js][ik] * cexp_phase;\n                        }\n                    }\n\n\n                }\n                for (is = 0; is < ns; ++is) {\n                    for (js = 0; js < ns; ++js) {\n                        dymat_out[is][js][icell] /= static_cast<double>(nk_interpolate);\n                    }\n                }\n\n                ++icell;\n            }\n        }\n    }\n\n\n    memory->deallocate(dymat_q);\n}\n\n\nvoid Scph::compute_anharmonic_frequency(std::complex<double> ***v4_array_all,\n                                        double **omega2_out,\n                                        std::complex<double> ***evec_anharm_scph,\n                                        const double temp,\n                                        bool &flag_converged,\n                                        std::complex<double> ***cmat_convert,\n                                        const bool offdiag,\n                                        const unsigned int verbosity)\n{\n    // This is the main function of the SCPH equation.\n    // The detailed algorithm can be found in PRB 92, 054301 (2015).\n    // Eigen3 library is used for the compact notation of matrix-matrix products.\n\n    using namespace Eigen;\n\n    int ik, jk;\n    unsigned int i;\n    unsigned int is, js, ks;\n    unsigned int kk;\n    const auto nk = nk_scph;\n    const auto ns = dynamical->neval;\n    unsigned int knum, knum_interpolate;\n    const auto nk_irred_interpolate = kp_irred_interpolate.size();\n    const auto nk1 = kmesh_interpolate[0];\n    const auto nk2 = kmesh_interpolate[1];\n    const auto nk3 = kmesh_interpolate[2];\n    int iloop;\n\n    MatrixXd omega_now(nk, ns), omega_old(nk, ns);\n    MatrixXd omega2_HA(nk, ns);\n    MatrixXcd mat_tmp(ns, ns), evec_tmp(ns, ns);\n\n    VectorXd eval_tmp(ns);\n    MatrixXcd Dymat(ns, ns);\n    MatrixXcd Fmat(ns, ns);\n    MatrixXcd Qmat = MatrixXcd::Zero(ns, ns);\n    MatrixXcd Cmat(ns, ns), Dmat(ns, ns);\n\n    double diff;\n    double conv_tol = tolerance_scph;\n    double alpha = mixalpha;\n\n    double **eval_interpolate;\n    double re_tmp, im_tmp;\n    bool has_negative;\n\n    std::complex<double> ctmp;\n    std::complex<double> ***mat_omega2_harmonic;\n    std::complex<double> ***evec_initial;\n    std::complex<double> ***dmat_convert;\n    std::complex<double> ***dmat_convert_old;\n    std::complex<double> ***evec_new;\n    std::complex<double> ***dymat_new, ***dymat_harmonic;\n    std::complex<double> ***dymat_q;\n    std::complex<double> ***Fmat0;\n\n    const auto complex_one = std::complex<double>(1.0, 0.0);\n    const auto complex_zero = std::complex<double>(0.0, 0.0);\n\n    SelfAdjointEigenSolver <MatrixXcd> saes;\n\n    memory->allocate(mat_omega2_harmonic, nk_interpolate, ns, ns);\n    memory->allocate(eval_interpolate, nk, ns);\n    memory->allocate(evec_initial, nk, ns, ns);\n    memory->allocate(evec_new, nk, ns, ns);\n    memory->allocate(dmat_convert, nk, ns, ns);\n    memory->allocate(dmat_convert_old, nk, ns, ns);\n    memory->allocate(dymat_new, ns, ns, nk_interpolate);\n    memory->allocate(dymat_q, ns, ns, nk_interpolate);\n    memory->allocate(dymat_harmonic, nk_interpolate, ns, ns);\n    memory->allocate(Fmat0, nk_irred_interpolate, ns, ns);\n\n    const auto T_in = temp;\n\n    std::cout << \" Temperature = \" << T_in << \" K\" << std::endl;\n\n    // Set initial values\n\n    for (ik = 0; ik < nk; ++ik) {\n        for (is = 0; is < ns; ++is) {\n\n            if (flag_converged) {\n                if (omega2_out[ik][is] < 0.0 && std::abs(omega2_out[ik][is]) > 1.0e-16 && verbosity > 0) {\n                    std::cout << \"Warning : Large negative frequency detected\" << std::endl;\n                }\n\n                if (omega2_out[ik][is] < 0.0) {\n                    omega_now(ik, is) = std::sqrt(-omega2_out[ik][is]);\n                } else {\n                    omega_now(ik, is) = std::sqrt(omega2_out[ik][is]);\n                }\n            } else {\n                if (omega2_harmonic[ik][is] < 0.0) {\n                    omega_now(ik, is) = std::sqrt(-omega2_harmonic[ik][is]);\n                } else {\n                    omega_now(ik, is) = std::sqrt(omega2_harmonic[ik][is]);\n                }\n            }\n\n            omega2_HA(ik, is) = omega2_harmonic[ik][is];\n\n            for (js = 0; js < ns; ++js) {\n                evec_initial[ik][is][js] = evec_harmonic[ik][is][js];\n\n                if (!flag_converged) {\n                    // Initialize Cmat with identity matrix\n                    if (is == js) {\n                        cmat_convert[ik][is][js] = complex_one;\n                    } else {\n                        cmat_convert[ik][is][js] = complex_zero;\n                    }\n                }\n\n            }\n        }\n    }\n\n    // Set initial harmonic dymat and eigenvalues\n\n    for (ik = 0; ik < nk_interpolate; ++ik) {\n        knum = kmap_interpolate_to_scph[ik];\n\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                mat_omega2_harmonic[ik][is][js] = complex_zero;\n            }\n            mat_omega2_harmonic[ik][is][is] = std::complex<double>(omega2_HA(knum, is), 0.0);\n            eval_interpolate[knum][is] = omega2_HA(knum, is);\n        }\n\n        dynamical->calc_analytic_k(xk_interpolate[ik],\n                                   fcs_phonon->fc2_ext,\n                                   dymat_harmonic[ik]);\n    }\n\n    for (ik = 0; ik < nk_irred_interpolate; ++ik) {\n\n        knum_interpolate = kp_irred_interpolate[ik][0].knum;\n\n        // Fmat harmonic\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                if (is == js) {\n                    Fmat0[ik][is][js] = mat_omega2_harmonic[knum_interpolate][is][is];\n                } else {\n                    Fmat0[ik][is][js] = complex_zero;\n                }\n            }\n        }\n    }\n\n    int icount = 0;\n\n    // Main loop\n    for (iloop = 0; iloop < maxiter; ++iloop) {\n\n        for (ik = 0; ik < nk; ++ik) {\n            for (is = 0; is < ns; ++is) {\n                auto omega1 = omega_now(ik, is);\n                if (std::abs(omega1) < eps8) {\n                    Qmat(is, is) = complex_zero;\n                } else {\n                    // Note that the missing factor 2 in the denominator of Qmat is \n                    // already considered in the v4_array_all.\n                    if (thermodynamics->classical) {\n                        Qmat(is, is) = std::complex<double>(2.0 * T_in * thermodynamics->T_to_Ryd / (omega1 * omega1),\n                                                            0.0);\n                    } else {\n                        auto n1 = thermodynamics->fB(omega1, T_in);\n                        Qmat(is, is) = std::complex<double>((2.0 * n1 + 1.0) / omega1, 0.0);\n                    }\n                }\n            }\n\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    Cmat(is, js) = cmat_convert[ik][is][js];\n                }\n            }\n\n            Dmat = Cmat * Qmat * Cmat.adjoint();\n\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    dmat_convert[ik][is][js] = Dmat(is, js);\n                }\n            }\n        }\n\n        // Mixing dmat\n        if (iloop > 0) {\n#pragma omp parallel for private(is, js)\n            for (ik = 0; ik < nk; ++ik) {\n                for (is = 0; is < ns; ++is) {\n                    for (js = 0; js < ns; ++js) {\n                        dmat_convert[ik][is][js] = alpha * dmat_convert[ik][is][js]\n                                                   + (1.0 - alpha) * dmat_convert_old[ik][is][js];\n                    }\n                }\n            }\n        }\n\n        for (ik = 0; ik < nk_irred_interpolate; ++ik) {\n\n            knum_interpolate = kp_irred_interpolate[ik][0].knum;\n            knum = kmap_interpolate_to_scph[knum_interpolate];\n\n            // Fmat harmonic\n\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    Fmat(is, js) = Fmat0[ik][is][js];\n                }\n            }\n\n            // Anharmonic correction to Fmat\n\n            if (!offdiag) {\n                for (is = 0; is < ns; ++is) {\n                    i = (ns + 1) * is;\n\n                    re_tmp = 0.0;\n                    im_tmp = 0.0;\n\n#pragma omp parallel for private(jk, kk, ks), reduction(+:re_tmp, im_tmp)\n                    for (jk = 0; jk < nk; ++jk) {\n\n                        kk = nk * ik + jk;\n\n                        for (ks = 0; ks < ns; ++ks) {\n                            ctmp = v4_array_all[kk][i][(ns + 1) * ks]\n                                   * dmat_convert[jk][ks][ks];\n                            re_tmp += ctmp.real();\n                            im_tmp += ctmp.imag();\n                        }\n                    }\n                    Fmat(is, is) += std::complex<double>(re_tmp, im_tmp);\n                }\n            } else {\n\n                // Anharmonic correction to Fmat\n\n                for (is = 0; is < ns; ++is) {\n                    for (js = 0; js <= is; ++js) {\n\n                        i = ns * is + js;\n\n                        re_tmp = 0.0;\n                        im_tmp = 0.0;\n\n#pragma omp parallel for private(jk, kk, ks), reduction(+:re_tmp, im_tmp)\n                        for (jk = 0; jk < nk; ++jk) {\n\n                            kk = nk * ik + jk;\n\n                            for (ks = 0; ks < ns; ++ks) {\n                                for (unsigned int ls = 0; ls < ns; ++ls) {\n                                    ctmp = v4_array_all[kk][i][ns * ks + ls]\n                                           * dmat_convert[jk][ks][ls];\n                                    re_tmp += ctmp.real();\n                                    im_tmp += ctmp.imag();\n                                }\n                            }\n                        }\n                        Fmat(is, js) += std::complex<double>(re_tmp, im_tmp);\n                    }\n                }\n\n            }\n\n            saes.compute(Fmat);\n            eval_tmp = saes.eigenvalues();\n\n            for (is = 0; is < ns; ++is) {\n\n                double omega2_tmp = eval_tmp(is);\n\n                if (omega2_tmp < 0.0 && std::abs(omega2_tmp) > 1.0e-16) {\n\n                    if (verbosity > 1) {\n                        std::cout << \" Detect imaginary : \";\n                        std::cout << \"  knum = \" << knum + 1 << \" is = \" << is + 1 << '\\n';\n                        for (int j = 0; j < 3; ++j) {\n                            std::cout << \"  xk = \" << std::setw(15) << xk_scph[knum][j];\n                        }\n                        std::cout << '\\n';\n                    }\n\n                    if (v4_array_all[nk * ik + knum][(ns + 1) * is][(ns + 1) * is].real() > 0.0) {\n                        if (verbosity > 1) {\n                            std::cout << \"  onsite V4 is positive\\n\\n\";\n                        }\n\n                        if (flag_converged) {\n                            ++icount;\n                            eval_tmp(is) = omega2_out[knum][is] * std::pow(0.99, icount);\n                        } else {\n                            ++icount;\n                            eval_tmp(is) = -eval_tmp(is) * std::pow(0.99, icount);\n                        }\n                    } else {\n                        if (verbosity > 1) {\n                            std::cout << \"  onsite V4 is negative\\n\\n\";\n                        }\n                        eval_tmp(is) = std::abs(omega2_tmp);\n                    }\n                }\n            }\n\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    evec_tmp(is, js) = evec_initial[knum][is][js];\n\n                    if (is == js) {\n                        Dymat(is, js) = std::complex<double>(eval_tmp(is), 0.0);\n                    } else {\n                        Dymat(is, js) = complex_zero;\n                    }\n                }\n            }\n\n            // New eigenvector matrix E_{new}= E_{old} * C\n            mat_tmp = evec_tmp.transpose() * saes.eigenvectors();\n            Dymat = mat_tmp * Dymat * mat_tmp.adjoint();\n\n#ifdef _DEBUG2\n            Dymat_sym = Dymat;\n            symmetrize_dynamical_matrix(ik, Dymat_sym);\n            std::complex<double> **dymat_exact;\n            memory->allocate(dymat_exact, ns, ns);\n            std::cout << \"ik = \" << ik + 1 << std::endl;\n            std::cout << \"Dymat\" << std::endl;\n            std::cout << Dymat << std::endl;\n            std::cout << \"Dymat_sym\" << std::endl;\n            std::cout << Dymat_sym << std::endl;\n            dynamical->calc_analytic_k(xk_interpolate[knum_interpolate], fcs_phonon->fc2_ext, dymat_exact);\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    Dymat_sym(is,js) = dymat_exact[is][js];\n                }\n            }\n            std::cout << \"Dymat_exact\" << std::endl;\n            std::cout << Dymat_sym << std::endl;\n            memory->deallocate(dymat_exact);\n\n#endif\n            symmetrize_dynamical_matrix(ik, Dymat);\n\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    dymat_q[is][js][knum_interpolate] = Dymat(is, js);\n                }\n            }\n        } // close loop ik\n\n        replicate_dymat_for_all_kpoints(dymat_q);\n\n#ifdef _DEBUG2\n        for (ik = 0; ik < nk_interpolate; ++ik) {\n\n            knum = kmap_interpolate_to_scph[ik];\n                \n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    Dymat(is,js) = dymat_q[is][js][ik];\n                }\n            }\n\n            saes.compute(Dymat);\n            eval_tmp = saes.eigenvalues();\n\n            for (is = 0; is < ns; ++is) {\n                eval_orig(is) = omega2_harmonic(knum,is);\n            }\n\n            std::cout << \" ik = \" << std::setw(4) << ik + 1 << \" : \";\n            for (i = 0; i < 3; ++i)  std::cout << std::setw(15) << xk_scph[knum][i];\n            std::cout << std::endl;\n\n            for (is = 0; is < ns; ++is) {\n                std::cout << std::setw(15) << eval_tmp(is);\n                std::cout << std::setw(15) << eval_orig(is);\n                std::cout << std::setw(15) << eval_tmp(is) - eval_orig(is) << std::endl;\n            }\n            \n        }\n#endif\n\n        // Subtract harmonic contribution to the dynamical matrix\n        for (ik = 0; ik < nk_interpolate; ++ik) {\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    dymat_q[is][js][ik] -= dymat_harmonic[ik][is][js];\n                }\n            }\n        }\n\n        for (is = 0; is < ns; ++is) {\n            for (js = 0; js < ns; ++js) {\n                fftw_plan plan = fftw_plan_dft_3d(nk1, nk2, nk3,\n                                                  reinterpret_cast<fftw_complex *>(dymat_q[is][js]),\n                                                  reinterpret_cast<fftw_complex *>(dymat_new[is][js]),\n                                                  FFTW_FORWARD, FFTW_ESTIMATE);\n                fftw_execute(plan);\n                fftw_destroy_plan(plan);\n\n                for (ik = 0; ik < nk_interpolate; ++ik)\n                    dymat_new[is][js][ik] /= static_cast<double>(nk_interpolate);\n            }\n        }\n\n        exec_interpolation(kmesh_interpolate,\n                           dymat_new,\n                           nk,\n                           xk_scph,\n                           kvec_na_scph,\n                           eval_interpolate, evec_new);\n\n        for (ik = 0; ik < nk; ++ik) {\n\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    mat_tmp(is, js) = evec_initial[ik][js][is];\n                    evec_tmp(is, js) = evec_new[ik][js][is];\n                }\n            }\n\n            Cmat = mat_tmp.adjoint() * evec_tmp;\n\n            for (is = 0; is < ns; ++is) {\n                omega_now(ik, is) = eval_interpolate[ik][is];\n                for (js = 0; js < ns; ++js) {\n                    cmat_convert[ik][is][js] = Cmat(is, js);\n                }\n            }\n        }\n\n        if (iloop == 0) {\n            if (verbosity > 0) {\n                std::cout << \"  SCPH ITER \" << std::setw(5) << iloop + 1 << \" :  DIFF = N/A\" << std::endl;\n            }\n\n            for (ik = 0; ik < nk; ++ik) {\n                for (is = 0; is < ns; ++is) {\n                    omega_old(ik, is) = omega_now(ik, is);\n                }\n            }\n\n        } else {\n\n            diff = 0.0;\n\n            for (ik = 0; ik < nk_interpolate; ++ik) {\n                knum = kmap_interpolate_to_scph[ik];\n                for (is = 0; is < ns; ++is) {\n                    diff += std::pow(omega_now(knum, is) - omega_old(knum, is), 2.0);\n                }\n            }\n            diff /= static_cast<double>(nk_interpolate * ns);\n            if (verbosity > 0) {\n                std::cout << \"  SCPH ITER \" << std::setw(5) << iloop + 1 << \" : \";\n                std::cout << \" DIFF = \" << std::setw(15) << std::sqrt(diff) << std::endl;\n            }\n            for (ik = 0; ik < nk; ++ik) {\n                for (is = 0; is < ns; ++is) {\n                    omega_old(ik, is) = omega_now(ik, is);\n                }\n            }\n            if (std::sqrt(diff) < conv_tol) {\n                has_negative = false;\n\n                for (ik = 0; ik < nk_interpolate; ++ik) {\n                    knum = kmap_interpolate_to_scph[ik];\n                    for (is = 0; is < ns; ++is) {\n                        if (omega_now(knum, is) < 0.0 && std::abs(omega_now(knum, is)) > eps8) {\n                            has_negative = true;\n                            break;\n                        }\n                    }\n                }\n                if (!has_negative) {\n                    if (verbosity > 0) std::cout << \"  DIFF < SCPH_TOL : break SCPH loop\\n\";\n                    break;\n                }\n                if (verbosity > 0) std::cout << \"  DIFF < SCPH_TOL but a negative frequency is detected.\\n\";\n            }\n        }\n\n        for (ik = 0; ik < nk; ++ik) {\n            for (is = 0; is < ns; ++is) {\n                for (js = 0; js < ns; ++js) {\n                    dmat_convert_old[ik][is][js] = dmat_convert[ik][is][js];\n                }\n            }\n        }\n    } // end loop iteration\n\n    if (std::sqrt(diff) < conv_tol) {\n        if (verbosity > 0) {\n            std::cout << \" Temp = \" << T_in;\n            std::cout << \" : convergence achieved in \" << std::setw(5)\n                      << iloop + 1 << \" iterations.\" << std::endl;\n        }\n        flag_converged = true;\n    } else {\n        if (verbosity > 0) {\n            std::cout << \"Temp = \" << T_in;\n            std::cout << \" : not converged.\" << std::endl;\n        }\n        flag_converged = false;\n    }\n\n    for (ik = 0; ik < nk; ++ik) {\n        for (is = 0; is < ns; ++is) {\n            if (eval_interpolate[ik][is] < 0.0) {\n                if (std::abs(eval_interpolate[ik][is]) <= eps10) {\n                    omega2_out[ik][is] = 0.0;\n                } else {\n                    omega2_out[ik][is] = -std::pow(eval_interpolate[ik][is], 2.0);\n                }\n            } else {\n                omega2_out[ik][is] = std::pow(eval_interpolate[ik][is], 2.0);\n            }\n            for (js = 0; js < ns; ++js) {\n                evec_anharm_scph[ik][is][js] = evec_new[ik][is][js];\n            }\n        }\n    }\n\n    if (verbosity > 1) {\n        std::cout << \"New eigenvalues\" << std::endl;\n        for (ik = 0; ik < nk_interpolate; ++ik) {\n            knum = kmap_interpolate_to_scph[ik];\n            for (is = 0; is < ns; ++is) {\n                std::cout << \" ik_interpolate = \" << std::setw(5) << ik + 1;\n                std::cout << \" is = \" << std::setw(5) << is + 1;\n                std::cout << \" omega2 = \" << std::setw(15) << omega2_out[knum][is] << std::endl;\n            }\n            std::cout << std::endl;\n        }\n    }\n\n    memory->deallocate(mat_omega2_harmonic);\n    memory->deallocate(eval_interpolate);\n    memory->deallocate(evec_initial);\n    memory->deallocate(dmat_convert);\n    memory->deallocate(dmat_convert_old);\n    memory->deallocate(evec_new);\n    memory->deallocate(dymat_new);\n    memory->deallocate(dymat_q);\n    memory->deallocate(dymat_harmonic);\n    memory->deallocate(Fmat0);\n}\n\n\nvoid Scph::compute_free_energy_bubble_SCPH(const unsigned int kmesh[3],\n                                           std::complex<double> ****delta_dymat_scph)\n{\n    const auto NT = static_cast<unsigned int>((system->Tmax - system->Tmin) / system->dT) + 1;\n    const auto nk_ref = kpoint->nk;\n    const auto ns = dynamical->neval;\n    double ***eval;\n    std::complex<double> ****evec;\n\n    if (mympi->my_rank == 0) {\n        std::cout << std::endl;\n        std::cout << \" -----------------------------------------------------------------\"\n                  << std::endl;\n        std::cout << \" Calculating the vibrational free energy from the Bubble diagram \" << std::endl;\n        std::cout << \" on top of the SCPH calculation.\" << std::endl;\n        std::cout << '\\n';\n        std::cout << \" This calculation requires allocation of additional memory:\" << std::endl;\n\n        size_t nsize = nk_ref * ns * ns * NT * sizeof(std::complex < double > )\n                       + nk_ref * ns * NT * sizeof(double);\n\n        const auto nsize_dble = static_cast<double>(nsize) / 100000000.0;\n        std::cout << \"  Estimated memory usage per MPI process: \" << std::setw(10)\n                  << std::fixed << std::setprecision(4) << nsize_dble << \" GByte.\" << std::endl;\n\n        std::cout << \"  To avoid possible faults associated with insufficient memory,\\n\"\n                     \"  please reduce the number of MPI processes per node and/or\\n\"\n                     \"  the number of temperagure grids.\\n\\n\";\n    }\n\n    memory->allocate(thermodynamics->FE_bubble, NT);\n    memory->allocate(eval, NT, nk_ref, ns);\n    memory->allocate(evec, NT, nk_ref, ns, ns); // This requires lots of RAM\n\n    for (auto iT = 0; iT < NT; ++iT) {\n        const auto temp = system->Tmin + system->dT * float(iT);\n\n        exec_interpolation(kmesh,\n                           delta_dymat_scph[iT],\n                           nk_ref,\n                           kpoint->xk,\n                           kpoint->kvec_na,\n                           eval[iT],\n                           evec[iT]);\n    }\n\n    thermodynamics->compute_FE_bubble_SCPH(eval, evec, thermodynamics->FE_bubble);\n\n    memory->deallocate(eval);\n    memory->deallocate(evec);\n\n    if (mympi->my_rank == 0) {\n        std::cout << \" done!\" << std::endl << std::endl;\n    }\n}\n\nvoid Scph::bubble_correction(std::complex<double> ****delta_dymat_scph,\n                             std::complex<double> ****delta_dymat_scph_plus_bubble)\n{\n    const auto NT = static_cast<unsigned int>((system->Tmax - system->Tmin) / system->dT) + 1;\n    const auto ns = dynamical->neval;\n    unsigned int i;\n    double xk_tmp[3];\n\n    auto epsilon = integration->epsilon;\n    const auto nk_irred_interpolate = kp_irred_interpolate.size();\n\n    double **eval = nullptr;\n    double ***eval_bubble = nullptr;\n    std::complex<double> ***evec;\n    double *real_self = nullptr;\n    std::vector <std::complex<double>> omegalist;\n\n    if (mympi->my_rank == 0) {\n        std::cout << std::endl;\n        std::cout << \" -----------------------------------------------------------------\"\n                  << std::endl;\n        std::cout << \" Calculating the bubble self-energy \" << std::endl;\n        std::cout << \" on top of the SCPH calculation.\" << std::endl;\n        std::cout << '\\n';\n    }\n\n    epsilon *= time_ry / Hz_to_kayser;\n    MPI_Bcast(&epsilon, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);\n\n    memory->allocate(eval, nk_scph, ns);\n    memory->allocate(evec, nk_scph, ns, ns);\n\n    if (mympi->my_rank == 0) {\n        memory->allocate(eval_bubble, NT, nk_scph, ns);\n        for (auto iT = 0; iT < NT; ++iT) {\n            for (auto ik = 0; ik < nk_scph; ++ik) {\n                for (auto is = 0; is < ns; ++is) {\n                    eval_bubble[iT][ik][is] = 0.0;\n                }\n            }\n        }\n        memory->allocate(real_self, ns);\n    }\n\n    const auto nk_reduced_scph = kp_irred_scph.size();\n\n    std::vector<int> *degeneracy_at_k;\n    memory->allocate(degeneracy_at_k, nk_scph);\n\n\n    for (auto iT = 0; iT < NT; ++iT) {\n        const auto temp = system->Tmin + system->dT * float(iT);\n\n        exec_interpolation(kmesh_interpolate,\n                           delta_dymat_scph[iT],\n                           nk_scph,\n                           xk_scph,\n                           kvec_na_scph,\n                           eval,\n                           evec);\n\n        find_degeneracy(degeneracy_at_k,\n                        nk_scph,\n                        eval);\n\n        if (mympi->my_rank == 0) std::cout << \" Temperature (K) : \" << std::setw(6) << temp << '\\n';\n\n        for (auto ik = 0; ik < nk_irred_interpolate; ++ik) {\n\n            auto knum_interpolate = kp_irred_interpolate[ik][0].knum;\n            auto knum = kmap_interpolate_to_scph[knum_interpolate];\n\n            for (auto m = 0; m < 3; ++m) xk_tmp[m] = -xk_scph[knum][m];\n            auto knum_minus = kpoint->get_knum(xk_tmp, kmesh_scph);\n\n            if (mympi->my_rank == 0) {\n                std::cout << \"  Irred. k: \" << std::setw(5) << ik + 1 << \" (\";\n                for (auto m = 0; m < 3; ++m) std::cout << std::setw(15) << xk_scph[knum][m];\n                std::cout << \")\\n\";\n            }\n\n            for (unsigned int snum = 0; snum < ns; ++snum) {\n\n\n                if (eval[knum][snum] < eps8) {\n                    if (mympi->my_rank == 0) real_self[snum] = 0.0;\n                } else {\n                    omegalist.clear();\n\n                    if (bubble == 1) {\n\n                        omegalist.push_back(im * epsilon);\n\n                        auto se_bubble = get_bubble_selfenergy(nk_scph,\n                                                               ns,\n                                                               kmesh_scph,\n                                                               xk_scph,\n                                                               eval,\n                                                               evec,\n                                                               knum,\n                                                               snum,\n                                                               temp,\n                                                               omegalist);\n\n                        if (mympi->my_rank == 0) real_self[snum] = se_bubble[0].real();\n\n                    } else if (bubble == 2) {\n\n                        omegalist.push_back(eval[knum][snum] + im * epsilon);\n\n                        auto se_bubble = get_bubble_selfenergy(nk_scph,\n                                                               ns,\n                                                               kmesh_scph,\n                                                               xk_scph,\n                                                               eval,\n                                                               evec,\n                                                               knum,\n                                                               snum,\n                                                               temp,\n                                                               omegalist);\n\n                        if (mympi->my_rank == 0) real_self[snum] = se_bubble[0].real();\n\n                    } else if (bubble == 3) {\n\n                        auto maxfreq = eval[knum][snum] + 50.0 * time_ry / Hz_to_kayser;\n                        auto minfreq = eval[knum][snum] - 50.0 * time_ry / Hz_to_kayser;\n\n                        if (minfreq < 0.0) minfreq = 0.0;\n\n                        const auto domega = 0.1 * time_ry / Hz_to_kayser;\n                        auto nomega = static_cast<unsigned int>((maxfreq - minfreq) / domega) + 1;\n\n                        for (auto iomega = 0; iomega < nomega; ++iomega) {\n                            omegalist.push_back(minfreq + static_cast<double>(iomega) * domega + im * epsilon);\n                        }\n\n                        auto se_bubble = get_bubble_selfenergy(nk_scph,\n                                                               ns,\n                                                               kmesh_scph,\n                                                               xk_scph,\n                                                               eval,\n                                                               evec,\n                                                               knum,\n                                                               snum,\n                                                               temp,\n                                                               omegalist);\n\n                        if (mympi->my_rank == 0) {\n\n                            std::vector<double> nonlinear_func(nomega);\n                            for (auto iomega = 0; iomega < nomega; ++iomega) {\n                                nonlinear_func[iomega] = omegalist[iomega].real() * omegalist[iomega].real()\n                                                         - eval[knum][snum] * eval[knum][snum]\n                                                         + 2.0 * eval[knum][snum] * se_bubble[iomega].real();\n                            }\n\n                            // find a root of nonlinear_func = 0 from the sign change.\n                            int count_root = 0;\n                            std::vector<unsigned int> root_index;\n\n                            for (auto iomega = 0; iomega < nomega - 1; ++iomega) {\n                                if (nonlinear_func[iomega] * nonlinear_func[iomega + 1] < 0.0) {\n                                    ++count_root;\n                                    root_index.push_back(iomega);\n                                }\n                            }\n\n                            if (count_root == 0) {\n                                error->warn(\"bubble_correction\",\n                                            \"Could not find a root in the nonlinear equation at this temperature. \"\n                                            \"Use the w=0 component.\");\n\n                                real_self[snum] = se_bubble[0].real();\n\n                            } else {\n                                if (count_root > 1) {\n                                    error->warn(\"bubble_correction\",\n                                                \"Multiple roots were found in the nonlinear equation at this temperature. \"\n                                                \"Use the lowest-frequency solution\");\n                                    std::cout << \"   solution found at the following frequencies:\\n\";\n                                    for (auto iroot = 0; iroot < count_root; ++iroot) {\n                                        std::cout << std::setw(15)\n                                                  << writes->in_kayser(omegalist[root_index[iroot]].real());\n                                    }\n                                    std::cout << '\\n';\n                                }\n\n                                // Instead of performing a linear interpolation (secant method) of nonlinear_func,\n                                // we interpolate the bubble self-energy. Since the frequency grid is dense (0.1 cm^-1 step),\n                                // this approximation should not make any problems (hopefully).\n\n                                double omega_solution = omegalist[root_index[0] + 1].real()\n                                                        - nonlinear_func[root_index[0] + 1]\n                                                          * domega / (nonlinear_func[root_index[0] + 1] -\n                                                                      nonlinear_func[root_index[0]]);\n\n                                real_self[snum] = (se_bubble[root_index[0] + 1].real()\n                                                   - se_bubble[root_index[0]].real())\n                                                  * (omega_solution - omegalist[root_index[0] + 1].real()) / domega\n                                                  + se_bubble[root_index[0] + 1].real();\n                            }\n                        }\n                    }\n                }\n                if (mympi->my_rank == 0) {\n                    std::cout << \"   branch : \" << std::setw(5) << snum + 1;\n                    std::cout << \" omega = \" << std::setw(15) << writes->in_kayser(eval[knum][snum]) << \" (cm^-1); \";\n                    std::cout << \" Re[Self] = \" << std::setw(15) << writes->in_kayser(real_self[snum]) << \" (cm^-1)\\n\";\n                }\n            }\n\n            if (mympi->my_rank == 0) {\n                // average self energy of degenerate modes\n                int ishift = 0;\n                double real_self_avg = 0.0;\n\n                for (const auto &it : degeneracy_at_k[knum]) {\n                    for (auto m = 0; m < it; ++m) {\n                        real_self_avg += real_self[m + ishift];\n                    }\n                    real_self_avg /= static_cast<double>(it);\n\n                    for (auto m = 0; m < it; ++m) {\n                        real_self[m + ishift] = real_self_avg;\n                    }\n                    real_self_avg = 0.0;\n                    ishift += it;\n                }\n\n                for (unsigned int snum = 0; snum < ns; ++snum) {\n                    eval_bubble[iT][knum][snum] = eval[knum][snum] * eval[knum][snum]\n                                                  - 2.0 * eval[knum][snum] * real_self[snum];\n                    for (auto jk = 1; jk < kp_irred_interpolate[ik].size(); ++jk) {\n                        auto knum2 = kmap_interpolate_to_scph[kp_irred_interpolate[ik][jk].knum];\n                        eval_bubble[iT][knum2][snum] = eval_bubble[iT][knum][snum];\n                    }\n                }\n\n                std::cout << '\\n';\n            }\n        }\n\n        if (mympi->my_rank == 0) {\n            calc_new_dymat_with_evec(delta_dymat_scph_plus_bubble[iT],\n                                     eval_bubble[iT],\n                                     evec);\n        }\n    }\n\n    memory->deallocate(eval);\n    memory->deallocate(evec);\n    memory->deallocate(degeneracy_at_k);\n\n    if (eval_bubble) memory->deallocate(eval_bubble);\n\n    if (mympi->my_rank == 0) {\n        std::cout << \" done!\" << std::endl << std::endl;\n    }\n}\n\nstd::vector <std::complex<double>> Scph::get_bubble_selfenergy(const unsigned int nk_in,\n                                                               const unsigned int ns_in,\n                                                               const unsigned int kmesh_in[3],\n                                                               double **xk_in,\n                                                               double **eval_in,\n                                                               std::complex<double> ***evec_in,\n                                                               const unsigned int knum,\n                                                               const unsigned int snum,\n                                                               const double temp_in,\n                                                               const std::vector <std::complex<double>> &omegalist)\n{\n    unsigned int arr_cubic[3];\n    double xk_tmp[3];\n    std::complex<double> omega_sum[2], omega_shift;\n\n    double factor = 1.0 / (static_cast<double>(nk_in) * std::pow(2.0, 4));\n    const auto ns2 = ns_in * ns_in;\n    const auto nks = nk_in * ns2;\n\n    std::complex<double> im(0.0, 1.0);\n\n    double n1, n2;\n    double f1, f2;\n    for (auto m = 0; m < 3; ++m) xk_tmp[m] = -xk_in[knum][m];\n    auto knum_minus = kpoint->get_knum(xk_tmp, kmesh_in);\n\n    arr_cubic[0] = ns_in * knum_minus + snum;\n\n    std::vector <std::complex<double>> se_bubble(omegalist.size());\n\n    const auto nomega = omegalist.size();\n\n    std::complex<double> *ret_sum, *ret_mpi;\n    memory->allocate(ret_sum, nomega);\n    memory->allocate(ret_mpi, nomega);\n\n    for (auto iomega = 0; iomega < nomega; ++iomega) {\n        ret_sum[iomega] = std::complex<double>(0.0, 0.0);\n        ret_mpi[iomega] = std::complex<double>(0.0, 0.0);\n    }\n\n    for (auto iks = mympi->my_rank; iks < nks; iks += mympi->nprocs) {\n\n        auto ik1 = iks / ns2;\n        auto is1 = (iks % ns2) / ns_in;\n        auto is2 = iks % ns_in;\n\n        for (auto m = 0; m < 3; ++m) xk_tmp[m] = xk_in[knum][m] - xk_in[ik1][m];\n        auto ik2 = kpoint->get_knum(xk_tmp, kmesh_in);\n\n        double omega1 = eval_in[ik1][is1];\n        double omega2 = eval_in[ik2][is2];\n\n        arr_cubic[1] = ns_in * ik1 + is1;\n        arr_cubic[2] = ns_in * ik2 + is2;\n\n        double v3_tmp = std::norm(V3_this(arr_cubic, eval_in, evec_in));\n\n        if (thermodynamics->classical) {\n            n1 = thermodynamics->fC(omega1, temp_in);\n            n2 = thermodynamics->fC(omega2, temp_in);\n            f1 = n1 + n2;\n            f2 = n2 - n1;\n        } else {\n            n1 = thermodynamics->fB(omega1, temp_in);\n            n2 = thermodynamics->fB(omega2, temp_in);\n            f1 = n1 + n2 + 1.0;\n            f2 = n2 - n1;\n        }\n        for (auto iomega = 0; iomega < nomega; ++iomega) {\n            omega_sum[0] = 1.0 / (omegalist[iomega] + omega1 + omega2) - 1.0 / (omegalist[iomega] - omega1 - omega2);\n            omega_sum[1] = 1.0 / (omegalist[iomega] + omega1 - omega2) - 1.0 / (omegalist[iomega] - omega1 + omega2);\n            ret_mpi[iomega] += v3_tmp * (f1 * omega_sum[0] + f2 * omega_sum[1]);\n        }\n    }\n    for (auto iomega = 0; iomega < nomega; ++iomega) {\n        ret_mpi[iomega] *= factor;\n    }\n    MPI_Reduce(&ret_mpi[0], &ret_sum[0], nomega, MPI_COMPLEX16, MPI_SUM, 0, MPI_COMM_WORLD);\n\n    for (auto iomega = 0; iomega < nomega; ++iomega) {\n        se_bubble[iomega] = ret_sum[iomega];\n    }\n\n    memory->deallocate(ret_mpi);\n    memory->deallocate(ret_sum);\n\n    return se_bubble;\n}\n\nstd::complex<double> Scph::V3_this(const unsigned int ks[3],\n                                   double **eval,\n                                   std::complex<double> ***evec)\n{\n    int i;\n    unsigned int kn[3], sn[3];\n    const int ns = dynamical->neval;\n\n    double omega[3];\n    auto ret = std::complex<double>(0.0, 0.0);\n    auto ret_re = 0.0;\n    auto ret_im = 0.0;\n\n    for (i = 0; i < 3; ++i) {\n        kn[i] = ks[i] / ns;\n        sn[i] = ks[i] % ns;\n        omega[i] = eval[kn[i]][sn[i]];\n    }\n\n    // Return zero if any of the involving phonon has imaginary frequency\n    if (omega[0] < eps8 || omega[1] < eps8 || omega[2] < eps8) return 0.0;\n\n    if (kn[1] != kindex_phi3_stored[0] || kn[2] != kindex_phi3_stored[1]) {\n        calc_phi3_reciprocal_this(kn[1], kn[2], phi3_reciprocal);\n        kindex_phi3_stored[0] = kn[1];\n        kindex_phi3_stored[1] = kn[2];\n    }\n#ifdef _OPENMP\n#pragma omp parallel for private(ret), reduction(+: ret_re, ret_im)\n#endif\n    for (i = 0; i < ngroup_v3; ++i) {\n        ret = evec[kn[0]][sn[0]][evec_index_v3[i][0]]\n              * evec[kn[1]][sn[1]][evec_index_v3[i][1]]\n              * evec[kn[2]][sn[2]][evec_index_v3[i][2]]\n              * invmass_v3[i] * phi3_reciprocal[i];\n        ret_re += ret.real();\n        ret_im += ret.imag();\n    }\n\n    return std::complex<double>(ret_re, ret_im)\n           / std::sqrt(omega[0] * omega[1] * omega[2]);\n}\n\nvoid Scph::calc_phi3_reciprocal_this(const unsigned int ik1,\n                                     const unsigned int ik2,\n                                     std::complex<double> *ret)\n{\n    int i, j;\n    unsigned int iloc;\n    double phase;\n    const auto dnk_represent = static_cast<double>(nk_represent) / (2.0 * pi);\n    std::complex<double> ret_in;\n    unsigned int nsize_group;\n\n\n    if (tune_type == 0) {\n\n#pragma omp parallel for private(ret_in, nsize_group, j, phase, iloc)\n        for (i = 0; i < ngroup_v3; ++i) {\n\n            ret_in = std::complex<double>(0.0, 0.0);\n            nsize_group = fcs_group_v3[i].size();\n\n            for (j = 0; j < nsize_group; ++j) {\n\n                phase = relvec_v3[i][j].vecs[0][0] * xk_scph[ik1][0]\n                        + relvec_v3[i][j].vecs[0][1] * xk_scph[ik1][1]\n                        + relvec_v3[i][j].vecs[0][2] * xk_scph[ik1][2]\n                        + relvec_v3[i][j].vecs[1][0] * xk_scph[ik2][0]\n                        + relvec_v3[i][j].vecs[1][1] * xk_scph[ik2][1]\n                        + relvec_v3[i][j].vecs[1][2] * xk_scph[ik2][2];\n\n                unsigned int iloc = nint(phase * dnk_represent) % nk_represent + nk_represent - 1;\n                ret_in += fcs_group_v3[i][j] * exp_phase[iloc];\n            }\n            ret[i] = ret_in;\n        }\n\n    } else if (tune_type == 1) {\n\n        // Tuned version is used when nk1=nk2=nk3 doesn't hold.\n\n        int loc[3];\n        double phase3[3];\n        const auto inv2pi = 1.0 / (2.0 * pi);\n\n#pragma omp parallel for private(ret_in, nsize_group, j, phase3, loc)\n        for (i = 0; i < ngroup_v3; ++i) {\n\n            ret_in = std::complex<double>(0.0, 0.0);\n            nsize_group = fcs_group_v3[i].size();\n\n            for (j = 0; j < nsize_group; ++j) {\n\n                for (auto ii = 0; ii < 3; ++ii) {\n                    phase3[ii]\n                            = relvec_v3[i][j].vecs[0][ii] * xk_scph[ik1][ii]\n                              + relvec_v3[i][j].vecs[1][ii] * xk_scph[ik2][ii];\n\n                    loc[ii] = nint(phase3[ii] * dnk[ii] * inv2pi) % nk_grid[ii] + nk_grid[ii] - 1;\n                }\n\n                ret_in += fcs_group_v3[i][j] * exp_phase3[loc[0]][loc[1]][loc[2]];\n            }\n            ret[i] = ret_in;\n        }\n    }\n}\n\n\ndouble Scph::distance(double *x1,\n                      double *x2)\n{\n    auto dist = std::pow(x1[0] - x2[0], 2)\n                + std::pow(x1[1] - x2[1], 2)\n                + std::pow(x1[2] - x2[2], 2);\n    dist = std::sqrt(dist);\n\n    return dist;\n}\n\nvoid Scph::duplicate_xk_boundary(double *xk_in,\n                                 std::vector <std::vector<double>> &vec_xk)\n{\n    int i;\n    int n[3];\n    double sign[3];\n    std::vector<double> vec_tmp;\n\n    vec_xk.clear();\n\n    for (i = 0; i < 3; ++i) {\n        if (std::abs(std::abs(xk_in[i]) - 0.5) < eps) {\n            n[i] = 2;\n        } else {\n            n[i] = 1;\n        }\n    }\n\n    for (i = 0; i < n[0]; ++i) {\n        sign[0] = 1.0 - 2.0 * static_cast<double>(i);\n        for (int j = 0; j < n[1]; ++j) {\n            sign[1] = 1.0 - 2.0 * static_cast<double>(j);\n            for (int k = 0; k < n[2]; ++k) {\n                sign[2] = 1.0 - 2.0 * static_cast<double>(k);\n\n                vec_tmp.clear();\n                for (int l = 0; l < 3; ++l) {\n                    vec_tmp.push_back(sign[l] * xk_in[l]);\n                }\n                vec_xk.push_back(vec_tmp);\n\n            }\n        }\n    }\n}\n\nvoid Scph::write_anharmonic_correction_fc2(std::complex<double> ****delta_dymat,\n                                           const unsigned int NT,\n                                           const int type)\n{\n    unsigned int i, j;\n    const auto Tmin = system->Tmin;\n    const auto dT = system->dT;\n    double ***delta_fc2;\n    double **xtmp;\n    const auto ns = dynamical->neval;\n    unsigned int is, js, icell;\n    unsigned int iat, jat;\n\n    std::string file_fc2;\n    std::ofstream ofs_fc2;\n\n    if (type == 0) {\n        file_fc2 = input->job_title + \".scph_dfc2\";\n    } else if (type == 1) {\n        file_fc2 = input->job_title + \".scph+bubble(0)_dfc2\";\n    } else if (type == 2) {\n        file_fc2 = input->job_title + \".scph+bubble(w)_dfc2\";\n    } else if (type == 3) {\n        file_fc2 = input->job_title + \".scph+bubble(wQP)_dfc2\";\n    }\n\n    ofs_fc2.open(file_fc2.c_str(), std::ios::out);\n    if (!ofs_fc2)\n        error->exit(\"write_anharmonic_correction_fc2\",\n                    \"Cannot open file_fc2\");\n\n    const auto ncell = kmesh_interpolate[0] * kmesh_interpolate[1] * kmesh_interpolate[2];\n\n    memory->allocate(delta_fc2, ns, ns, ncell);\n\n    memory->allocate(xtmp, system->natmin, 3);\n\n    ofs_fc2.precision(10);\n\n    for (i = 0; i < system->natmin; ++i) {\n        rotvec(xtmp[i], system->xr_s[system->map_p2s[i][0]], system->lavec_s);\n        rotvec(xtmp[i], xtmp[i], system->rlavec_p);\n        for (j = 0; j < 3; ++j) xtmp[i][j] /= 2.0 * pi;\n    }\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            ofs_fc2 << std::setw(20) << system->lavec_p[j][i];\n        }\n        ofs_fc2 << std::endl;\n    }\n    ofs_fc2 << std::setw(5) << system->natmin << std::setw(5) << system->nkd << std::endl;\n    for (i = 0; i < system->nkd; ++i) {\n        ofs_fc2 << std::setw(5) << system->symbol_kd[i];\n    }\n    ofs_fc2 << std::endl;\n\n    for (i = 0; i < system->natmin; ++i) {\n        for (j = 0; j < 3; ++j) {\n            ofs_fc2 << std::setw(20) << xtmp[i][j];\n        }\n        ofs_fc2 << std::setw(5) << system->kd[system->map_p2s[i][0]] + 1 << std::endl;\n    }\n\n    memory->deallocate(xtmp);\n\n    for (unsigned int iT = 0; iT < NT; ++iT) {\n        const auto temp = Tmin + dT * static_cast<double>(iT);\n\n        ofs_fc2 << \"# Temp = \" << temp << std::endl;\n\n        for (is = 0; is < ns; ++is) {\n            iat = is / 3;\n\n            for (js = 0; js < ns; ++js) {\n                jat = js / 3;\n\n                for (icell = 0; icell < ncell; ++icell) {\n                    delta_fc2[is][js][icell]\n                            = delta_dymat[iT][is][js][icell].real()\n                              * std::sqrt(system->mass[system->map_p2s[iat][0]]\n                                          * system->mass[system->map_p2s[jat][0]]);\n                }\n\n            }\n        }\n\n\n        for (icell = 0; icell < ncell; ++icell) {\n\n            for (is = 0; is < ns; ++is) {\n                iat = is / 3;\n                const auto icrd = is % 3;\n\n                for (js = 0; js < ns; ++js) {\n                    jat = js / 3;\n                    const auto jcrd = js % 3;\n\n                    const auto nmulti = mindist_list_scph[iat][jat][icell].shift.size();\n\n                    for (auto it = mindist_list_scph[iat][jat][icell].shift.cbegin();\n                         it != mindist_list_scph[iat][jat][icell].shift.cend(); ++it) {\n\n                        ofs_fc2 << std::setw(4) << (*it).sx;\n                        ofs_fc2 << std::setw(4) << (*it).sy;\n                        ofs_fc2 << std::setw(4) << (*it).sz;\n                        ofs_fc2 << std::setw(5) << iat << std::setw(3) << icrd;\n                        ofs_fc2 << std::setw(4) << jat << std::setw(3) << jcrd;\n                        ofs_fc2 << std::setprecision(15) << std::setw(25)\n                                << delta_fc2[is][js][icell] / static_cast<double>(nmulti) << std::endl;\n\n                    }\n\n                }\n            }\n        }\n\n        ofs_fc2 << std::endl;\n    }\n\n    memory->deallocate(delta_fc2);\n\n    ofs_fc2.close();\n    std::cout << \"  \" << std::setw(input->job_title.length() + 12) << std::left << file_fc2;\n\n    if (type == 0) {\n        std::cout << \" : Anharmonic corrections to the second-order IFCs (SCPH)\" << std::endl;\n    } else if (type == 1) {\n        std::cout << \" : Anharmonic corrections to the second-order IFCs (SCPH+Bubble(0))\" << std::endl;\n    } else if (type == 2) {\n        std::cout << \" : Anharmonic corrections to the second-order IFCs (SCPH+Bubble(w))\" << std::endl;\n    } else if (type == 3) {\n        std::cout << \" : Anharmonic corrections to the second-order IFCs (SCPH+Bubble(wQP))\" << std::endl;\n    }\n}\n\nvoid Scph::mpi_bcast_complex(std::complex<double> ****data,\n                             const unsigned int NT,\n                             const unsigned int nk,\n                             const unsigned int ns)\n{\n    const int _NT = static_cast<int>(NT);\n    const int _nk = static_cast<int>(nk);\n    const int _ns = static_cast<int>(ns);\n\n#ifdef MPI_CXX_DOUBLE_COMPLEX\n    MPI_Bcast(&data[0][0][0][0], _NT * _nk * _ns * _ns,\n              MPI_CXX_DOUBLE_COMPLEX, 0, MPI_COMM_WORLD);\n#elif defined MPI_DOUBLE_COMPLEX\n    MPI_Bcast(&data[0][0][0][0], _NT * _nk * _ns * _ns, MPI_DOUBLE_COMPLEX, 0, MPI_COMM_WORLD);\n#else\n    MPI_Bcast(&data[0][0][0][0], _NT * _nk * _ns * _ns, MPI_COMPLEX16, 0, MPI_COMM_WORLD);\n#endif\n}\n\nvoid Scph::get_derivative_central_diff(const double delta_t,\n                                       const unsigned int nk,\n                                       double **omega0,\n                                       double **omega2,\n                                       double **domega_dt)\n{\n    const auto ns = dynamical->neval;\n    const auto inv_dt = 1.0 / (2.0 * delta_t);\n    for (auto ik = 0; ik < nk; ++ik) {\n        for (auto is = 0; is < ns; ++is) {\n            domega_dt[ik][is] = (omega2[ik][is] - omega0[ik][is]) * inv_dt;\n        //    std::cout << \"domega_dt = \" << domega_dt[ik][is] << '\\n';\n        }\n    }\n}\n", "meta": {"hexsha": "5fc0486b1dc8620df6206d6cc17b5f268f6b1f7f", "size": 139852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "anphon/scph.cpp", "max_stars_repo_name": "jochym/alamode", "max_stars_repo_head_hexsha": "128cc2315a661f2440a2f264f0b9dd75ed42dd39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "anphon/scph.cpp", "max_issues_repo_name": "jochym/alamode", "max_issues_repo_head_hexsha": "128cc2315a661f2440a2f264f0b9dd75ed42dd39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "anphon/scph.cpp", "max_forks_repo_name": "jochym/alamode", "max_forks_repo_head_hexsha": "128cc2315a661f2440a2f264f0b9dd75ed42dd39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9516709512, "max_line_length": 125, "alphanum_fraction": 0.4576838372, "num_tokens": 37581, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.24189891699630717}}
{"text": "/**\n * \\file\n * \\copyright\n * Copyright (c) 2012-2021, OpenGeoSys Community (http://www.opengeosys.org)\n *            Distributed under a Modified BSD License.\n *              See accompanying file LICENSE.txt or\n *              http://www.opengeosys.org/project/license\n *\n */\n\n#include \"BHE_1P.h\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"FlowAndTemperatureControl.h\"\n#include \"Physics.h\"\n#include \"ThermoMechanicalFlowProperties.h\"\n\nnamespace ProcessLib\n{\nnamespace HeatTransportBHE\n{\nnamespace BHE\n{\nBHE_1P::BHE_1P(BoreholeGeometry const& borehole,\n               RefrigerantProperties const& refrigerant,\n               GroutParameters const& grout,\n               FlowAndTemperatureControl const& flowAndTemperatureControl,\n               PipeConfiguration1PType const& pipes,\n               bool const use_python_bcs)\n    : BHECommon{borehole, refrigerant, grout, flowAndTemperatureControl,\n                use_python_bcs},\n      _pipe(pipes)\n{\n    _thermal_resistances.fill(std::numeric_limits<double>::quiet_NaN());\n\n    // Initialize thermal resistances.\n    auto values = visit(\n        [&](auto const& control) {\n            return control(refrigerant.reference_temperature,\n                           0. /* initial time */);\n        },\n        flowAndTemperatureControl);\n    updateHeatTransferCoefficients(values.flow_rate);\n}\n\nstd::array<double, BHE_1P::number_of_unknowns> BHE_1P::pipeHeatCapacities()\n    const\n{\n    double const rho_r = refrigerant.density;\n    double const specific_heat_capacity = refrigerant.specific_heat_capacity;\n    double const rho_g = grout.rho_g;\n    double const porosity_g = grout.porosity_g;\n    double const heat_cap_g = grout.heat_cap_g;\n\n    return {{\n        /*pipe*/ rho_r * specific_heat_capacity,\n        /*grout*/ (1.0 - porosity_g) * rho_g * heat_cap_g,\n    }};\n}\n\nstd::array<double, BHE_1P::number_of_unknowns> BHE_1P::pipeHeatConductions()\n    const\n{\n    double const lambda_r = refrigerant.thermal_conductivity;\n    double const rho_r = refrigerant.density;\n    double const Cp_r = refrigerant.specific_heat_capacity;\n    double const alpha_L = _pipe.longitudinal_dispersion_length;\n    double const porosity_g = grout.porosity_g;\n    double const lambda_g = grout.lambda_g;\n\n    // Here we calculate the laplace coefficients in the governing\n    // equations of the BHE.\n    return {{\n        // pipe, Eq. 19\n        (lambda_r + rho_r * Cp_r * alpha_L * _flow_velocity),\n        // grout, Eq. 21\n        (1.0 - porosity_g) * lambda_g,\n    }};\n}\n\nstd::array<Eigen::Vector3d, BHE_1P::number_of_unknowns>\nBHE_1P::pipeAdvectionVectors(Eigen::Vector3d const& elem_direction) const\n{\n    double const& rho_r = refrigerant.density;\n    double const& Cp_r = refrigerant.specific_heat_capacity;\n    Eigen::Vector3d adv_vector = rho_r * Cp_r * _flow_velocity * elem_direction;\n\n    return {// pipe, Eq. 19\n            adv_vector,\n            // grout, Eq. 21\n            {0, 0, 0}};\n}\n\ndouble BHE_1P::compute_R_gs(double const chi, double const R_g)\n{\n    return (1 - chi) * R_g;\n}\n\nvoid BHE_1P::updateHeatTransferCoefficients(double const flow_rate)\n\n{\n    auto const tm_flow_properties = calculateThermoMechanicalFlowPropertiesPipe(\n        _pipe.single_pipe, borehole_geometry.length, refrigerant, flow_rate);\n\n    _flow_velocity = tm_flow_properties.velocity;\n    _thermal_resistances =\n        calcThermalResistances(tm_flow_properties.nusselt_number);\n}\n\n// Nu is the Nusselt number.\nstd::array<double, BHE_1P::number_of_unknowns> BHE_1P::calcThermalResistances(\n    double const Nu)\n{\n    constexpr double pi = boost::math::constants::pi<double>();\n\n    double const lambda_r = refrigerant.thermal_conductivity;\n    double const lambda_g = grout.lambda_g;\n    double const lambda_p = _pipe.single_pipe.wall_thermal_conductivity;\n\n    // thermal resistances due to advective flow of refrigerant in the pipe\n    double const R_adv_i1 = 1.0 / (Nu * lambda_r * pi);\n\n    // thermal resistance due to thermal conductivity of the pipe wall material\n    double const R_con_a = std::log(_pipe.single_pipe.outsideDiameter() /\n                                    _pipe.single_pipe.diameter) /\n                           (2.0 * pi * lambda_p);\n\n    // thermal resistances of the grout\n    double const D = borehole_geometry.diameter;\n    double const pipe_outside_diameter = _pipe.single_pipe.outsideDiameter();\n\n    double const chi = std::log(std::sqrt(D * D + pipe_outside_diameter *\n                                                      pipe_outside_diameter) /\n                                std::sqrt(2) / pipe_outside_diameter) /\n                       std::log(D / pipe_outside_diameter);\n    double const R_g =\n        std::log(D / pipe_outside_diameter) / 2 / (pi * lambda_g);\n\n    double const R_con_b = chi * R_g;\n\n    // thermal resistances due to grout-soil exchange\n    double const R_gs = compute_R_gs(chi, R_g);\n\n    // Eq. 29 and 30\n    double const R_fg = R_adv_i1 + R_con_a + R_con_b;\n\n    return {{R_fg, R_gs}};\n}\n\nstd::array<std::pair<std::size_t /*node_id*/, int /*component*/>, 2>\nBHE_1P::getBHEInflowDirichletBCNodesAndComponents(\n    std::size_t const top_node_id,\n    std::size_t const bottom_node_id,\n    int const in_component_id)\n{\n    return {std::make_pair(top_node_id, in_component_id),\n            std::make_pair(bottom_node_id, in_component_id)};\n}\n\nstd::optional<\n    std::array<std::pair<std::size_t /*node_id*/, int /*component*/>, 2>>\nBHE_1P::getBHEBottomDirichletBCNodesAndComponents(\n    std::size_t const /*bottom_node_id*/,\n    int const /*in_component_id*/,\n    int const /*out_component_id*/)\n{\n    return {};\n}\n\nstd::array<double, BHE_1P::number_of_unknowns> BHE_1P::crossSectionAreas() const\n{\n    return {{_pipe.single_pipe.area(),\n             borehole_geometry.area() - _pipe.single_pipe.outsideArea()}};\n}\n\ndouble BHE_1P::updateFlowRateAndTemperature(double const T_out,\n                                            double const current_time)\n{\n    auto values =\n        visit([&](auto const& control) { return control(T_out, current_time); },\n              flowAndTemperatureControl);\n    updateHeatTransferCoefficients(values.flow_rate);\n    return values.temperature;\n}\n}  // namespace BHE\n}  // namespace HeatTransportBHE\n}  // namespace ProcessLib\n", "meta": {"hexsha": "80e41d3b300488f5310d1253d029ee50b05a8d32", "size": 6268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ProcessLib/HeatTransportBHE/BHE/BHE_1P.cpp", "max_stars_repo_name": "ufz/ogs", "max_stars_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2015-03-20T22:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T04:37:21.000Z", "max_issues_repo_path": "ProcessLib/HeatTransportBHE/BHE/BHE_1P.cpp", "max_issues_repo_name": "ufz/ogs", "max_issues_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3015.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T21:55:16.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-15T01:09:17.000Z", "max_forks_repo_path": "ProcessLib/HeatTransportBHE/BHE/BHE_1P.cpp", "max_forks_repo_name": "ufz/ogs", "max_forks_repo_head_hexsha": "97d0249e0c578c3055730f4e9d994b9970885098", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 250.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T15:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:37:20.000Z", "avg_line_length": 33.164021164, "max_line_length": 80, "alphanum_fraction": 0.6727823867, "num_tokens": 1586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.24189891699630717}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)\n#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)\n#define EACH(e, a) for(auto&& e : a)\n#define ALL(a) std::begin(a), std::end(a)\n#define RALL(a) std::rbegin(a), std::rend(a)\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n#define INT(x) (static_cast<int>(x))\n#define PRECISION(x) std::fixed << std::setprecision(x)\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = std::vector<int>;\nusing VI2D = std::vector<vector<int>>;\nusing VLL = std::vector<long long>;\nusing VLL2D = std::vector<vector<long long>>;\n\nconstexpr int INF = 2e9;\nconstexpr double EPS = 1e-10;\nconstexpr double PI = acos(-1.0);\n\nconstexpr int dx[] = {-1, 0, 1, 0};\nconstexpr int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T, std::size_t N>\nstruct make_vector_type {\n\tusing type =\n\t\ttypename std::vector<typename make_vector_type<T, (N - 1)>::type>;\n};\n\ntemplate <typename T>\nstruct make_vector_type<T, 0> {\n\tusing type = typename std::vector<T>;\n};\n\ntemplate <typename T, size_t N>\nauto make_vector_impl(const std::vector<std::size_t>& ls, T init_value) {\n\tif constexpr(N == 0) {\n\t\treturn std::vector<T>(ls[N], init_value);\n\t} else {\n\t\treturn typename make_vector_type<T, N>::type(\n\t\t\tls[N], make_vector_impl<T, (N - 1)>(ls, init_value));\n\t}\n}\n\ntemplate <typename T, std::size_t N>\nauto make_vector(const std::size_t (&ls)[N], T init_value) {\n\tstd::vector<std::size_t> dimensions(N);\n\tfor(int i = 0; i < N; i++) {\n\t\tdimensions[N - i - 1] = ls[i];\n\t}\n\treturn make_vector_impl<T, N - 1>(dimensions, init_value);\n}\n\ntemplate <typename T>\nstd::vector<T> make_vector(std::size_t size, T init_value) {\n\treturn std::vector<T>(size, init_value);\n}\n\ntemplate <typename T>\nconstexpr int sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nconstexpr int sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmax(T& m, U x) {\n\tm = max<T>(m, x);\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmin(T& m, U x) {\n\tm = min<T>(m, x);\n}\n\ntemplate <typename T>\nconstexpr T square(T x) {\n\treturn x * x;\n}\n\ntemplate <long long MOD = 1000000007>\nclass ModInt {\n\tpublic:\n\tlong long n;\n\n\tconstexpr ModInt() : n(0) {}\n\tconstexpr ModInt(long long n) : n(n < 0 ? n + MOD : n % MOD) {}\n\n\tconstexpr long long get() const { return this->n; }\n\tconstexpr long long get_mod() const { return MOD; }\n\n\tconstexpr ModInt inv() const { return pow<ModInt<MOD>>(*this, MOD - 2); }\n\n\tconstexpr ModInt& operator=(const long long rhs) {\n\t\treturn *this = ModInt(rhs);\n\t}\n\tconstexpr ModInt& operator+=(const ModInt rhs) {\n\t\treturn *this = ModInt(this->n + rhs.n);\n\t}\n\tconstexpr ModInt& operator-=(const ModInt rhs) {\n\t\treturn *this = ModInt(this->n - rhs.n);\n\t}\n\tconstexpr ModInt& operator*=(const ModInt rhs) {\n\t\treturn *this = ModInt(this->n * rhs.n);\n\t}\n\tconstexpr ModInt& operator/=(const ModInt rhs) {\n\t\treturn *this *= rhs.inv();\n\t}\n\tconstexpr bool operator==(const ModInt rhs) const {\n\t\treturn this->n == rhs.n;\n\t}\n};\n\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator+(const ModInt<MOD>& lhs,\n\t\t\t\t\t\t\t\tconst ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) += rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator+(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) += rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator+(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) += rhs;\n}\n\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator-(const ModInt<MOD>& lhs,\n\t\t\t\t\t\t\t\tconst ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) -= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator-(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) -= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator-(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) -= rhs;\n}\n\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator*(const ModInt<MOD>& lhs,\n\t\t\t\t\t\t\t\tconst ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) *= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator*(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) *= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator*(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) *= rhs;\n}\n\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator/(const ModInt<MOD>& lhs,\n\t\t\t\t\t\t\t\tconst ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) /= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator/(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) /= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator/(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) /= rhs;\n}\n\ntemplate <long long MOD>\nstd::ostream& operator<<(std::ostream& os, const ModInt<MOD>& x) {\n\treturn os << x.n;\n}\n\ntemplate <long long MOD>\nstd::istream& operator>>(std::istream& is, const ModInt<MOD>& x) {\n\treturn is >> x.n;\n}\n\nint roundup_pow2(int n) {\n\tif(!(n & (n - 1))) {\n\t\treturn n;\n\t}\n\n\tint ret = 1;\n\twhile(n > ret) {\n\t\tret <<= 1;\n\t}\n\treturn ret;\n}\n\ntemplate <typename T, typename U>\nclass LazySegmentTree {\n\tusing F = std::function<T(T, T)>;\n\tusing G = std::function<T(T, U)>;\n\tusing H = std::function<U(U, U)>;\n\n\tstd::vector<T> tree;\n\tstd::vector<U> lazy;\n\tF merge;\n\tG mapping;\n\tH composition;\n\tT id1;\n\tU id2;\n\tstd::size_t size;\n\n\tpublic:\n\tLazySegmentTree(const vector<T>& a,\n\t\t\t\t\tconst F f,\n\t\t\t\t\tconst T id1,\n\t\t\t\t\tconst G g,\n\t\t\t\t\tconst H h,\n\t\t\t\t\tconst U id2)\n\t\t: tree(roundup_pow2(a.size()) * 2 - 1, id1),\n\t\t  lazy(roundup_pow2(a.size()) * 2 - 1, id2), merge(f), id1(id1),\n\t\t  mapping(g), composition(h), id2(id2), size(roundup_pow2(a.size())) {\n\t\tint offset = this->size - 1;\n\t\tfor(int i = 0; i < a.size(); i++) {\n\t\t\tthis->tree[i + offset] = a[i];\n\t\t}\n\t\tfor(int i = offset - 1; i >= 0; i--) {\n\t\t\tthis->tree[i] =\n\t\t\t\tthis->merge(this->tree[i * 2 + 1], this->tree[i * 2 + 2]);\n\t\t}\n\t}\n\n\tvoid debug_print() {\n\t\tcout << \"tree: \";\n\t\tREP(i, this->size * 2 - 1) {\n\t\t\tif(i == this->size - 1) {\n\t\t\t\tcout << \"| \";\n\t\t\t}\n\t\t\tcout << \"(\" << this->tree[i].first << \",\" << this->tree[i].second\n\t\t\t\t << \") \";\n\t\t}\n\t\tcout << \"\\nlazy: \";\n\t\tREP(i, this->size * 2 - 1) {\n\t\t\tif(i == this->size - 1) {\n\t\t\t\tcout << \"| \";\n\t\t\t}\n\t\t\tcout << this->lazy[i] << \" \";\n\t\t}\n\t\tcout << endl;\n\t}\n\n\tvoid\n\tupdate(const std::size_t left, const std::size_t right, const U value) {\n\t\tthis->update_impl(left, right, 0, 0, this->size, value);\n\t}\n\n\tT find(const std::size_t left, const std::size_t right) {\n\t\treturn this->find_impl(left, right, 0, 0, this->size);\n\t}\n\n\tprivate:\n\tvoid update_impl(std::size_t query_left,\n\t\t\t\t\t std::size_t query_right,\n\t\t\t\t\t std::size_t node,\n\t\t\t\t\t std::size_t node_left,\n\t\t\t\t\t std::size_t node_right,\n\t\t\t\t\t U value) {\n\t\tthis->force(node);\n\t\tif(node_right <= query_left || query_right <= node_left) {\n\t\t\treturn;\n\t\t}\n\t\tif(query_left <= node_left && node_right <= query_right) {\n\t\t\tthis->lazy[node] = this->composition(this->lazy[node], value);\n\t\t\tthis->force(node);\n\t\t\treturn;\n\t\t}\n\t\tthis->update_impl(query_left,\n\t\t\t\t\t\t  query_right,\n\t\t\t\t\t\t  node * 2 + 1,\n\t\t\t\t\t\t  node_left,\n\t\t\t\t\t\t  node_left + (node_right - node_left) / 2,\n\t\t\t\t\t\t  value);\n\t\tthis->update_impl(query_left,\n\t\t\t\t\t\t  query_right,\n\t\t\t\t\t\t  node * 2 + 2,\n\t\t\t\t\t\t  node_left + (node_right - node_left) / 2,\n\t\t\t\t\t\t  node_right,\n\t\t\t\t\t\t  value);\n\t\tthis->tree[node] =\n\t\t\tthis->merge(this->tree[node * 2 + 1], this->tree[node * 2 + 2]);\n\t}\n\n\tT find_impl(size_t query_left,\n\t\t\t\tsize_t query_right,\n\t\t\t\tsize_t node,\n\t\t\t\tsize_t node_left,\n\t\t\t\tsize_t node_right) {\n\t\tthis->force(node);\n\t\tif(node_right <= query_left || query_right <= node_left) {\n\t\t\treturn this->id1;\n\t\t}\n\t\tif(query_left <= node_left && node_right <= query_right) {\n\t\t\treturn this->tree[node];\n\t\t}\n\n\t\treturn this->merge(find_impl(query_left,\n\t\t\t\t\t\t\t\t\t query_right,\n\t\t\t\t\t\t\t\t\t node * 2 + 1,\n\t\t\t\t\t\t\t\t\t node_left,\n\t\t\t\t\t\t\t\t\t node_left + (node_right - node_left) / 2),\n\t\t\t\t\t\t   find_impl(query_left,\n\t\t\t\t\t\t\t\t\t query_right,\n\t\t\t\t\t\t\t\t\t node * 2 + 2,\n\t\t\t\t\t\t\t\t\t node_left + (node_right - node_left) / 2,\n\t\t\t\t\t\t\t\t\t node_right));\n\t}\n\n\tvoid force(std::size_t node) {\n\t\tif(this->lazy[node] == this->id2) {\n\t\t\treturn;\n\t\t}\n\t\tif(node * 2 + 1 < this->size * 2 - 1) {\n\t\t\tthis->lazy[node * 2 + 1] =\n\t\t\t\tthis->composition(lazy[node * 2 + 1], lazy[node]);\n\t\t\tthis->lazy[node * 2 + 2] =\n\t\t\t\tthis->composition(lazy[node * 2 + 2], lazy[node]);\n\t\t}\n\t\tthis->tree[node] = this->mapping(this->tree[node], lazy[node]);\n\t\tthis->lazy[node] = this->id2;\n\t}\n};\n\nusing mint = ModInt<998244353>;\n\nint main() {\n\tint n, q;\n\tcin >> n >> q;\n\tVI l(q), r(q);\n\tVI d(q);\n\tREP(i, q) {\n\t\tcin >> l[i] >> r[i] >> d[i];\n\t\tl[i] = n - l[i] + 1;\n\t\tr[i] = n - r[i];\n\t\tswap(l[i], r[i]);\n\t}\n\n\tvector<mint> keta(n + 1, 0);\n\tketa[0] = 1;\n\tREP(i, n) { keta[i + 1] = keta[i] * 10; }\n\n\tvector<mint> repunit(n + 1, 0);\n\trepunit[0] = 1;\n\tREP(i, n) { repunit[i + 1] = repunit[i] * 10 + 1; }\n\n\tvector<pair<mint, int>> s(n, {1, 1});\n\n\tLazySegmentTree<pair<mint, int>, int> lst(\n\t\ts,\n\t\t[&](pair<mint, int> a, pair<mint, int> b) {\n\t\t\treturn make_pair(a.first + b.first * keta[a.second],\n\t\t\t\t\t\t\t a.second + b.second);\n\t\t},\n\t\t{0, 1},\n\t\t[&](pair<mint, int> a, int b) {\n\t\t\treturn make_pair(b ? b * repunit[a.second - 1] : a.first, a.second);\n\t\t},\n\t\t[](int a, int b) { return b ? b : a; },\n\t\t0);\n\t// lst.debug_print();\n\tREP(i, q) {\n\t\tlst.update(l[i], r[i], d[i]);\n\t\tcout << lst.find(0, n).first << endl;\n\t\t// lst.debug_print();\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "8733664c920ea2e7f7be2ca1335c51f73a3a902f", "size": 9904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABL/E.cpp", "max_stars_repo_name": "arlechann/atcoder", "max_stars_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AtCoder/ABL/E.cpp", "max_issues_repo_name": "arlechann/atcoder", "max_issues_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AtCoder/ABL/E.cpp", "max_forks_repo_name": "arlechann/atcoder", "max_forks_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.76, "max_line_length": 79, "alphanum_fraction": 0.6114701131, "num_tokens": 3145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.24187998375596864}}
{"text": "/*\r\n * Copyright Nick Thompson, 2020\r\n * Use, modification and distribution are subject to the\r\n * Boost Software License, Version 1.0. (See accompanying file\r\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#ifndef BOOST_MATH_SPECIAL_DAUBECHIES_WAVELET_HPP\r\n#define BOOST_MATH_SPECIAL_DAUBECHIES_WAVELET_HPP\r\n#include <vector>\r\n#include <array>\r\n#include <cmath>\r\n#include <thread>\r\n#include <future>\r\n#include <iostream>\r\n#include <boost/math/constants/constants.hpp>\r\n#include <boost/math/special_functions/detail/daubechies_scaling_integer_grid.hpp>\r\n#include <boost/math/special_functions/daubechies_scaling.hpp>\r\n#include <boost/math/filters/daubechies.hpp>\r\n#include <boost/math/interpolators/detail/cubic_hermite_detail.hpp>\r\n#include <boost/math/interpolators/detail/quintic_hermite_detail.hpp>\r\n#include <boost/math/interpolators/detail/septic_hermite_detail.hpp>\r\n\r\nnamespace boost::math {\r\n\r\n   template<class Real, int p, int order>\r\n   std::vector<Real> daubechies_wavelet_dyadic_grid(int64_t j_max)\r\n   {\r\n      if (j_max == 0)\r\n      {\r\n         throw std::domain_error(\"The wavelet dyadic grid is refined from the scaling integer grid, so its minimum amount of data is half integer widths.\");\r\n      }\r\n      auto phijk = daubechies_scaling_dyadic_grid<Real, p, order>(j_max - 1);\r\n      //psi_j[l] = psi(-p+1 + l/2^j) = \\sum_{k=0}^{2p-1} (-1)^k c_k \\phi(1-2p+k + l/2^{j-1})\r\n      //For derivatives just map c_k -> 2^order c_k.\r\n      auto d = boost::math::filters::daubechies_scaling_filter<Real, p>();\r\n      Real scale = boost::math::constants::root_two<Real>() * (1 << order);\r\n      for (size_t i = 0; i < d.size(); ++i)\r\n      {\r\n         d[i] *= scale;\r\n         if (!(i & 1))\r\n         {\r\n            d[i] = -d[i];\r\n         }\r\n      }\r\n\r\n      std::vector<Real> v(2 * p + (2 * p - 1) * ((int64_t(1) << j_max) - 1), std::numeric_limits<Real>::quiet_NaN());\r\n      v[0] = 0;\r\n      v[v.size() - 1] = 0;\r\n\r\n      for (int64_t l = 1; l < static_cast<int64_t>(v.size() - 1); ++l)\r\n      {\r\n         Real term = 0;\r\n         for (int64_t k = 0; k < static_cast<int64_t>(d.size()); ++k)\r\n         {\r\n            int64_t idx = (int64_t(1) << (j_max - 1)) * (1 - 2 * p + k) + l;\r\n            if (idx < 0 || idx >= static_cast<int64_t>(phijk.size()))\r\n            {\r\n               continue;\r\n            }\r\n            term += d[k] * phijk[idx];\r\n         }\r\n         v[l] = term;\r\n      }\r\n\r\n      return v;\r\n   }\r\n\r\n\r\n   template<class Real, int p>\r\n   class daubechies_wavelet {\r\n      //\r\n      // Some type manipulation so we know the type of the interpolator, and the vector type it requires:\r\n      //\r\n      typedef std::vector < std::array < Real, p < 6 ? 2 : p < 10 ? 3 : 4>> vector_type;\r\n      //\r\n      // List our interpolators:\r\n      //\r\n      typedef std::tuple<\r\n         detail::null_interpolator, detail::matched_holder_aos<vector_type>, detail::linear_interpolation_aos<vector_type>,\r\n         interpolators::detail::cardinal_cubic_hermite_detail_aos<vector_type>, interpolators::detail::cardinal_quintic_hermite_detail_aos<vector_type>,\r\n         interpolators::detail::cardinal_septic_hermite_detail_aos<vector_type> > interpolator_list;\r\n      //\r\n      // Select the one we need:\r\n      //\r\n      typedef std::tuple_element_t<\r\n         p == 1 ? 0 :\r\n         p == 2 ? 1 :\r\n         p == 3 ? 2 :\r\n         p <= 5 ? 3 :\r\n         p <= 9 ? 4 : 5, interpolator_list> interpolator_type;\r\n   public:\r\n      daubechies_wavelet(int grid_refinements = -1)\r\n      {\r\n         static_assert(p < 20, \"Daubechies wavelets are only implemented for p < 20.\");\r\n         static_assert(p > 0, \"Daubechies wavelets must have at least 1 vanishing moment.\");\r\n         if (grid_refinements == 0)\r\n         {\r\n            throw std::domain_error(\"The wavelet requires at least 1 grid refinement.\");\r\n         }\r\n         if constexpr (p == 1)\r\n         {\r\n            return;\r\n         }\r\n         else\r\n         {\r\n            if (grid_refinements < 0)\r\n            {\r\n               if (std::is_same_v<Real, float>)\r\n               {\r\n                  if (grid_refinements == -2)\r\n                  {\r\n                     // Control absolute error:\r\n                     //                          p= 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19\r\n                     std::array<int, 20> r{ -1, -1, 18, 19, 16, 11,  8,  7,  7,  7,  5,  5,  4,  4,  4,  4,  3,  3,  3,  3 };\r\n                     grid_refinements = r[p];\r\n                  }\r\n                  else\r\n                  {\r\n                     // Control relative error:\r\n                     //                          p= 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19\r\n                     std::array<int, 20> r{ -1, -1, 21, 21, 21, 17, 16, 15, 14, 13, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11 };\r\n                     grid_refinements = r[p];\r\n                  }\r\n               }\r\n               else if (std::is_same_v<Real, double>)\r\n               {\r\n                  //                          p= 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19\r\n                  std::array<int, 20> r{ -1, -1, 21, 21, 21, 21, 21, 21, 21, 21, 20, 20, 19, 18, 18, 18, 18, 18, 18, 18 };\r\n                  grid_refinements = r[p];\r\n               }\r\n               else\r\n               {\r\n                  grid_refinements = 21;\r\n               }\r\n            }\r\n\r\n            // Compute the refined grid:\r\n            // In fact for float precision I know the grid must be computed in double precision and then cast back down, or else parts of the support are systematically inaccurate.\r\n            std::future<std::vector<Real>> t0 = std::async(std::launch::async, [&grid_refinements]() {\r\n               // Computing in higher precision and downcasting is essential for 1ULP evaluation in float precision:\r\n               auto v = daubechies_wavelet_dyadic_grid<typename detail::daubechies_eval_type<Real>::type, p, 0>(grid_refinements);\r\n               return detail::daubechies_eval_type<Real>::vector_cast(v);\r\n               });\r\n            // Compute the derivative of the refined grid:\r\n            std::future<std::vector<Real>> t1 = std::async(std::launch::async, [&grid_refinements]() {\r\n               auto v = daubechies_wavelet_dyadic_grid<typename detail::daubechies_eval_type<Real>::type, p, 1>(grid_refinements);\r\n               return detail::daubechies_eval_type<Real>::vector_cast(v);\r\n               });\r\n\r\n            // if necessary, compute the second and third derivative:\r\n            std::vector<Real> d2ydx2;\r\n            std::vector<Real> d3ydx3;\r\n            if constexpr (p >= 6) {\r\n               std::future<std::vector<Real>> t3 = std::async(std::launch::async, [&grid_refinements]() {\r\n                  auto v = daubechies_wavelet_dyadic_grid<typename detail::daubechies_eval_type<Real>::type, p, 2>(grid_refinements);\r\n                  return detail::daubechies_eval_type<Real>::vector_cast(v);\r\n                  });\r\n\r\n               if constexpr (p >= 10) {\r\n                  std::future<std::vector<Real>> t4 = std::async(std::launch::async, [&grid_refinements]() {\r\n                     auto v = daubechies_wavelet_dyadic_grid<typename detail::daubechies_eval_type<Real>::type, p, 3>(grid_refinements);\r\n                     return detail::daubechies_eval_type<Real>::vector_cast(v);\r\n                     });\r\n                  d3ydx3 = t4.get();\r\n               }\r\n               d2ydx2 = t3.get();\r\n            }\r\n\r\n\r\n            auto y = t0.get();\r\n            auto dydx = t1.get();\r\n\r\n            if constexpr (p >= 2)\r\n            {\r\n               vector_type data(y.size());\r\n               for (size_t i = 0; i < y.size(); ++i)\r\n               {\r\n                  data[i][0] = y[i];\r\n                  data[i][1] = dydx[i];\r\n                  if constexpr (p >= 6)\r\n                     data[i][2] = d2ydx2[i];\r\n                  if constexpr (p >= 10)\r\n                     data[i][3] = d3ydx3[i];\r\n               }\r\n               if constexpr (p <= 3)\r\n                  m_interpolator = std::make_shared<interpolator_type>(std::move(data), grid_refinements, Real(-p + 1));\r\n               else\r\n                  m_interpolator = std::make_shared<interpolator_type>(std::move(data), Real(-p + 1), Real(1) / (1 << grid_refinements));\r\n            }\r\n            else\r\n               m_interpolator = std::make_shared<detail::null_interpolator>();\r\n         }\r\n      }\r\n\r\n\r\n      inline Real operator()(Real x) const\r\n      {\r\n         if (x <= -p + 1 || x >= p)\r\n         {\r\n            return 0;\r\n         }\r\n         if constexpr (p == 1)\r\n         {\r\n            if (x < Real(1) / Real(2))\r\n            {\r\n               return 1;\r\n            }\r\n            else if (x == Real(1) / Real(2))\r\n            {\r\n               return 0;\r\n            }\r\n            return -1;\r\n         }\r\n         return (*m_interpolator)(x);\r\n      }\r\n\r\n      inline Real prime(Real x) const\r\n      {\r\n         static_assert(p > 2, \"The 3-vanishing moment Daubechies wavelet is the first which is continuously differentiable.\");\r\n         if (x <= -p + 1 || x >= p)\r\n         {\r\n            return 0;\r\n         }\r\n         return m_interpolator->prime(x);\r\n      }\r\n\r\n      inline Real double_prime(Real x) const\r\n      {\r\n         static_assert(p >= 6, \"Second derivatives of Daubechies wavelets require at least 6 vanishing moments.\");\r\n         if (x <= -p + 1 || x >= p)\r\n         {\r\n            return Real(0);\r\n         }\r\n         return m_interpolator->double_prime(x);\r\n      }\r\n\r\n      std::pair<Real, Real> support() const\r\n      {\r\n         return { Real(-p + 1), Real(p) };\r\n      }\r\n\r\n      int64_t bytes() const\r\n      {\r\n         return m_interpolator->bytes() + sizeof(*this);\r\n      }\r\n\r\n   private:\r\n      std::shared_ptr<interpolator_type> m_interpolator;\r\n   };\r\n\r\n}\r\n#endif\r\n", "meta": {"hexsha": "7eae27daa5a856b88b3d21b323e8d1c9f5011a6f", "size": 9924, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/math/special_functions/daubechies_wavelet.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/math/special_functions/daubechies_wavelet.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/math/special_functions/daubechies_wavelet.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 39.0708661417, "max_line_length": 181, "alphanum_fraction": 0.5020153164, "num_tokens": 2704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.24187998375596861}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Sat 26 May 2018 14:35:26\n\n/**\n * @file ScalarSingletDM_Z2_two_scale_ewsb_solver.hpp\n *\n * @brief contains class for solving EWSB when two-scale algorithm is used\n *\n * This file was generated at Sat 26 May 2018 14:35:26 with FlexibleSUSY\n * 2.0.1 (git commit: unknown) and SARAH 4.12.2 .\n */\n\n#ifndef ScalarSingletDM_Z2_TWO_SCALE_EWSB_SOLVER_H\n#define ScalarSingletDM_Z2_TWO_SCALE_EWSB_SOLVER_H\n\n#include \"ScalarSingletDM_Z2_ewsb_solver.hpp\"\n#include \"ScalarSingletDM_Z2_ewsb_solver_interface.hpp\"\n#include \"error.hpp\"\n\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass EWSB_solver;\nclass Two_scale;\n\nclass ScalarSingletDM_Z2_mass_eigenstates;\n\ntemplate<>\nclass ScalarSingletDM_Z2_ewsb_solver<Two_scale> : public ScalarSingletDM_Z2_ewsb_solver_interface {\npublic:\n   ScalarSingletDM_Z2_ewsb_solver() = default;\n   ScalarSingletDM_Z2_ewsb_solver(const ScalarSingletDM_Z2_ewsb_solver&) = default;\n   ScalarSingletDM_Z2_ewsb_solver(ScalarSingletDM_Z2_ewsb_solver&&) = default;\n   virtual ~ScalarSingletDM_Z2_ewsb_solver() {}\n   ScalarSingletDM_Z2_ewsb_solver& operator=(const ScalarSingletDM_Z2_ewsb_solver&) = default;\n   ScalarSingletDM_Z2_ewsb_solver& operator=(ScalarSingletDM_Z2_ewsb_solver&&) = default;\n\n   virtual void set_loop_order(int l) override { loop_order = l; }\n   virtual void set_number_of_iterations(int n) override { number_of_iterations = n; }\n   virtual void set_precision(double p) override { precision = p; }\n\n   virtual int get_loop_order() const override { return loop_order; }\n   virtual int get_number_of_iterations() const override { return number_of_iterations; }\n   virtual double get_precision() const override { return precision; }\n\n   virtual int solve(ScalarSingletDM_Z2_mass_eigenstates&) override;\nprivate:\n   static const int number_of_ewsb_equations = 1;\n   using EWSB_vector_t = Eigen::Matrix<double,number_of_ewsb_equations,1>;\n\n   class EEWSBStepFailed : public Error {\n   public:\n      virtual ~EEWSBStepFailed() {}\n      virtual std::string what() const { return \"Could not perform EWSB step.\"; }\n   };\n\n   int number_of_iterations{100}; ///< maximum number of iterations\n   int loop_order{2};             ///< loop order to solve EWSB at\n   double precision{1.e-5};       ///< precision goal\n\n   void set_ewsb_solution(ScalarSingletDM_Z2_mass_eigenstates&, const EWSB_solver*);\n   template <typename It> void set_best_ewsb_solution(ScalarSingletDM_Z2_mass_eigenstates&, It, It);\n\n   int solve_tree_level(ScalarSingletDM_Z2_mass_eigenstates&);\n   int solve_iteratively(ScalarSingletDM_Z2_mass_eigenstates&);\n   int solve_iteratively_at(ScalarSingletDM_Z2_mass_eigenstates&, int);\n   int solve_iteratively_with(ScalarSingletDM_Z2_mass_eigenstates&, EWSB_solver*, const EWSB_vector_t&);\n\n   EWSB_vector_t initial_guess(const ScalarSingletDM_Z2_mass_eigenstates&) const;\n   EWSB_vector_t tadpole_equations(const ScalarSingletDM_Z2_mass_eigenstates&) const;\n   EWSB_vector_t ewsb_step(const ScalarSingletDM_Z2_mass_eigenstates&) const;\n};\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "757c601df1021d0e98a5cffacaf0614e3e318fca", "size": 3874, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/ScalarSingletDM_Z2/ScalarSingletDM_Z2_two_scale_ewsb_solver.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/ScalarSingletDM_Z2/ScalarSingletDM_Z2_two_scale_ewsb_solver.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/ScalarSingletDM_Z2/ScalarSingletDM_Z2_two_scale_ewsb_solver.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 40.7789473684, "max_line_length": 104, "alphanum_fraction": 0.7527103769, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2418660890923267}}
{"text": "// Copyright (c) 2012 Andre Martins\n// All Rights Reserved.\n//\n// This file is part of AD3 2.0.\n//\n// AD3 2.0 is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Lesser General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// AD3 2.0 is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public License\n// along with AD3 2.0.  If not, see <http://www.gnu.org/licenses/>.\n\n\n\n#ifndef _AD3_QP_HPP_\n#define _AD3_QP_HPP_\n\n\n#include <Eigen/Eigenvalues>\n#include <math.h>\n#include <limits>\n#include \"dd_grlab.hpp\"\n\n\n#define NEARLY_ZERO_TOL(a,tol) (((a)<=(tol)) && ((a)>=(-(tol))))\n#define NEARLY_EQ_TOL(a,b,tol) (((a)-(b))*((a)-(b))<=(tol))\n#define num_max_iterations_QP_ 10\n\nstruct admm_vertex_program_general:public admm_vertex_program {\n\nvoid Maximize(vertex_type& vertex, vec additional_log_potentials, vec variable_log_potentials,\n                Configuration &configuration,\n                double *value) {\n          \n    vector <Configuration> states(vertex.data().nvars,-1);\n    int best = -1;\n    *value = -1e12;\n    for (int index = 0;\n         index < additional_log_potentials.size();\n         ++index) {\n      //cout<<\"enter loop 1 in  Maximize ..\"<<endl;\n      double score = additional_log_potentials[index];\n      //cout<<\"score in Maximize ..\"<<endl;\n      get_configuration_states(vertex,index, &states);\n      //cout<<\"get config state Maximize\"<<endl;\n      int offset = 0;\n      for (int i = 0; i < vertex.data().nvars; ++i) {\n      //cout<<\"enter loop 2 in  Maximize ..\"<<endl;\n        score += variable_log_potentials[offset+states[i]];\n        offset = vertex.data().cards[i];\n        \n      }\n      \n      //cout<<\"exit loop 2 in  Maximize ..\"<<endl;\n      if (configuration < 0 || score > *value) {\n        configuration = index;\n        *value = score;\n      }\n    }\n    //cout<<\"exit loop 1 in  Maximize ..\"<<endl;\n    assert(configuration >= 0);\n    \n  }\n\n\n \n//Configuration CreateConfiguration()\n//{ Configuration *configuration = new Configuration;\n//  return *Configuration;\n //}\n \n void DeleteConfiguration(Configuration &configuration) {\n    configuration = -1;\n  }\n\n\n bool InvertAfterInsertion(vertex_type& vertex, vector <double> & inverse_A_,\n        const vector<Configuration> &active_set, const Configuration &inserted_element) {\n\n  vector<double> inverse_A = inverse_A_;\n  int size_A = active_set.size() + 1;\n  vector<double> r(size_A);\n\n  r[0] = 1.0;\n  for (int i = 0; i < active_set.size(); ++i) {\n    // Count how many variable values the new assignment\n    // have in common with the i-th assignment.\n    int num_common_values = CountCommonValues(vertex, active_set[i], inserted_element);\n    r[i+1] = static_cast<double>(num_common_values);\n  }\n\n  double r0 = static_cast<double>(CountCommonValues(vertex,\n      inserted_element, inserted_element));\n  double s = r0;\n  for (int i = 0; i < size_A; ++i) {\n    if (r[i] == 0.0) continue;\n    s -= r[i] * r[i] * inverse_A[i * size_A + i];\n    for (int j = i+1; j < size_A; ++j) {\n      if (r[j] == 0.0) continue;\n      s -= 2 * r[i] * r[j] * inverse_A[i * size_A + j];\n    }\n  }\n\n    if (NEARLY_ZERO_TOL(s, 1e-9)) {\n         if (opts.verbose> 2) {\n      cout << \"Warning: updated matrix will become singular after insertion.\"\n           << endl;\n    }\n    return false;\n  }\n\n  double invs = 1.0 / s;\n  vector<double> d(size_A, 0.0);\n  for (int i = 0; i < size_A; ++i) {\n    if (r[i] == 0.0) continue;\n    for (int j = 0; j < size_A; ++j) {\n      d[j] += inverse_A[i * size_A + j] * r[i];\n    }\n  }\n\n  int size_A_after = size_A + 1;\n  inverse_A_.resize(size_A_after * size_A_after);\n  for (int i = 0; i < size_A; ++i) {\n    for (int j = 0; j < size_A; ++j) {\n      inverse_A_[i * size_A_after + j] = inverse_A[i * size_A + j] +\n          invs * d[i] * d[j];\n    }\n    inverse_A_[i * size_A_after + size_A] = -invs * d[i];\n    inverse_A_[size_A * size_A_after + i] = -invs * d[i];\n  }\n  inverse_A_[size_A * size_A_after + size_A] = invs;\n\n  return true;\n}\n\nvoid InvertAfterRemoval(vector <double> &inverse_A_,const vector<Configuration> &active_set,\n                                       int removed_index) {\n  vector<double> inverse_A = inverse_A_;\n  int size_A = active_set.size() + 1;\n  vector<double> r(size_A);\n\n  ++removed_index; // Index in A has an offset of 1.\n  double invs = inverse_A[removed_index * size_A + removed_index];\n  assert(!NEARLY_ZERO_TOL(invs, 1e-12));\n  double s = 1.0 / invs;\n  vector<double> d(size_A - 1, 0.0);\n  int k = 0;\n  for (int i = 0; i < size_A; ++i) {\n    if (i == removed_index) continue;\n    d[k] = -s * inverse_A[removed_index * size_A + i];\n    ++k;\n  }\n\n  int size_A_after = size_A - 1;\n  inverse_A_.resize(size_A_after * size_A_after);\n  k = 0;\n  for (int i = 0; i < size_A; ++i) {\n    if (i == removed_index) continue;\n    int l = 0;\n    for (int j = 0; j < size_A; ++j) {\n      if (j == removed_index) continue;\n      inverse_A_[k * size_A_after + l] = inverse_A[i * size_A + j] -\n          invs * d[k] * d[l];\n      ++l;\n    }\n    ++k;\n  }\n}\n\n// Compute Mnz'*Mnz\nvoid ComputeActiveSetSimilarities(vertex_type& vertex,\n    const vector<Configuration> &active_set,\n    vector<double> *similarities) {\n  int size = active_set.size();\n\n  // Compute similarity matrix.\n  similarities->resize(size * size);\n  (*similarities)[0] = 0.0;\n  for (int i = 0; i < active_set.size(); ++i) {\n    (*similarities)[i*size + i] = static_cast<double>(\n        CountCommonValues(vertex,active_set[i], active_set[i]) );\n    for (int j = i+1; j < active_set.size(); ++j) {\n      // Count how many variable values the i-th and j-th \n      // assignments have in common.\n      int num_common_values = CountCommonValues(vertex,active_set[i], active_set[j]);\n      (*similarities)[i*size + j] = num_common_values;\n      (*similarities)[j*size + i] = num_common_values;\n    }\n  }\n}\n\nvoid ComputeMarginalsFromSparseDistribution( vertex_type& vertex, \n    const vector<Configuration> &active_set,\n    const vector<double> &distribution,\n    vec  &variable_posteriors,\n    vec &additional_posteriors) {\n    //cout<<\"enter cmfsp ...\"<<endl;\n    variable_posteriors.setZero();           \n    additional_posteriors.setZero();  \n    for (int i = 0; i < active_set.size(); ++i) {\n    UpdateMarginalsFromConfiguration(vertex,active_set[i],\n                                       distribution[i],\n                                       variable_posteriors,\n                                       additional_posteriors);\n    }\n  }\n  \n  \n  \n  \n   // Given a configuration with a probability (weight), \n  // increment the vectors of variable and additional posteriors.\n  void UpdateMarginalsFromConfiguration(vertex_type& vertex,\n    const Configuration &configuration,\n    double weight,\n    vec &variable_posteriors,\n    vec &additional_posteriors) {\n    \n     vector <Configuration> states(vertex.data().nvars, -1);\n     get_configuration_states(vertex, configuration, &states);\n     \n            int offset = 0;\n            \n            for (int k = 0; k < vertex.data().nvars; ++k) \n            {   //cout<<\"loop enter update marginals..\"<<offset<<\" \"<<states[k]<<\" \"<<variable_posteriors.size()<<endl;        \n                variable_posteriors[offset + states[k]] += weight;\n                //cout<<\"till here ...\";\n                offset += vertex.data().cards[k];\n                //cout<<\"loop exit update marginals..\"<<endl; \n            }\n    additional_posteriors[configuration] += weight;\n \n  }\n  // Count how many common values two configurations have.\n  int CountCommonValues(vertex_type& vertex,Configuration configuration1,\n                        Configuration configuration2) {\n    \n    //assert(states1->size() == states2->size());\n    int count = 0;\n    vector <Configuration> states1(vertex.data().nvars, -1); \n    vector <Configuration> states2(vertex.data().nvars, -1);\n    get_configuration_states(vertex, configuration1, &states1);\n    get_configuration_states(vertex, configuration2, &states2);\n    for(int i = 0; i< vertex.data().nvars; i++)\n    { //cout<<\"enter loop  in get count common values...\"<<endl;\n    if (states1[i] == states2[i])\n      { count++;} }\n    return count;\n  }\n  \n  \nvoid Evaluate(vertex_type& vertex, vec additional_log_potentials, vec variable_log_potentials,\n                const Configuration configuration,\n                double *value) {\n          \n    vector<Configuration> states(vertex.data().nvars, -1);\n    get_configuration_states(vertex, configuration, &states);\n    *value = 0.0;\n    int offset = 0;\n    for (int i = 0;i<vertex.data().nvars; ++i) {\n     //cout<<\"enter loop in eval ..\"<<\" \"<<offset<<\" \"<<states[i]<<\" \"<<variable_log_potentials.size()<<endl;\n      *value += variable_log_potentials[offset + states[i]];\n      offset = vertex.data().cards[i]; \n    }\n    *value += additional_log_potentials[configuration];\n  }\n  \n  \n  \n  void EigenDecompose(vector<double> *similarities,\n                            vector<double> *eigenvalues) {\n\n  int size = sqrt(similarities->size());\n\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;\n  Eigen::MatrixXd sim(size, size);\n  int t = 0;\n  for (int i = 0; i < size; ++i) {\n    for (int j = 0; j < size; ++j) {\n      sim(i, j) = (*similarities)[t];\n      ++t;\n    }\n  }\n  es.compute(sim);\n  const Eigen::VectorXd &eigvals = es.eigenvalues(); \n  eigenvalues->resize(size);\n  for (int i = 0; i < size; ++i) {\n    (*eigenvalues)[i] = eigvals[i];\n  }\n  const Eigen::MatrixXd &eigvectors = es.eigenvectors().transpose();\n  t = 0;\n  for (int i = 0; i < size; ++i) {\n    for (int j = 0; j < size; ++j) {\n      (*similarities)[t] = eigvectors(i, j);\n      ++t;\n    }\n  }\n\n}\n\n\nvoid SolveQP(vertex_type& vertex,const gather_type& total,\n                            vec& beliefs, vec& variable_posteriors,\n                            vec& additional_posteriors) {\n  vertex_data& vdata = vertex.data();                        \n  beliefs = vdata.potentials;\n  int num_configurations = vdata.potentials.size();\n     for (int index_configuration = 0;\n         index_configuration < num_configurations;\n         ++index_configuration) {\n         vector<int> states(vdata.nvars, -1);\n         // This could be made more efficient by defining an iterator over factor\n         // configurations.\n        get_configuration_states(vertex, index_configuration, &states);\n        int offset = 0;\n        for (int k = 0; k < vdata.nvars; ++k) {\n        //cout<<index_configuration<<\" \"<<offset<<\" \"<<states[k]<<endl;\n        //cout<<beliefs.size()<<\" \"<<total.messages.size()<<endl;\n        beliefs[index_configuration] += total.messages[offset + states[k]];\n        offset += vdata.cards[k];\n       \n             }\n             \n          }\n   //cout<<\"loop 1 in solveQP ..\"<<endl;\n   vec additional_log_potentials = beliefs;\n   vec variable_log_potentials = total.neighbor_distribution;      \n   vector <Configuration> active_set_;\n   vector<double> distribution_;\n   vector<double> inverse_A_;\n  // Initialize the active set.\n  \n  if (active_set_.size() == 0) {\n    variable_posteriors.resize(variable_log_potentials.size());     \n    additional_posteriors.resize(additional_log_potentials.size()); \n    distribution_.clear();\n    // Initialize by solving the LP, discarding the quadratic\n    // term.\n    Configuration configuration = -1;\n    double value;\n    //cout<<\"Before Maximize ..\"<<endl;\n    Maximize(vertex, additional_log_potentials, variable_log_potentials,\n             configuration,\n             &value);\n    //cout<<\"Maximize in solveQP ..\"<<endl;\n    active_set_.push_back(configuration);\n    distribution_.push_back(1.0);\n\n    // Initialize inv(A) as [-M,1;1,0].\n    inverse_A_.resize(4);\n    inverse_A_[0] = static_cast<double>(\n        -CountCommonValues(vertex,configuration, configuration));\n    //cout<<\"count common vals in solve QP ...\"<<endl;\n    inverse_A_[1] = 1;\n    inverse_A_[2] = 1;\n    inverse_A_[3] = 0;\n  }\n\n  bool changed_active_set = true;\n  vector<double> z;\n  int num_max_iterations = num_max_iterations_QP_;\n  double tau = 0;\n  for (int iter = 0; iter < num_max_iterations; ++iter) {\n    bool same_as_before = true;\n    bool unbounded = false;\n    if (changed_active_set) {\n      // Recompute vector b.\n      vector<double> b(active_set_.size() + 1, 0.0);\n      b[0] = 1.0;\n      for (int i = 0; i < active_set_.size(); ++i) {\n        const Configuration &configuration = active_set_[i];\n        double score;\n     //   cout<<\"Before eval in solveQP ...\"<<endl;\n        Evaluate(vertex, additional_log_potentials, variable_log_potentials,\n                 configuration,\n                 &score);\n        b[i+1] = score;\n      }\n   //cout<<\"Eval in solveQP ..\"<<endl;\n      // Solve the system Az = b.\n      z.resize(active_set_.size());\n      int size_A = active_set_.size() + 1;\n      for (int i = 0; i < active_set_.size(); ++i) {\n        z[i] = 0.0;\n        for (int j = 0; j < size_A; ++j) {\n          z[i] += inverse_A_[(i+1) * size_A + j] * b[j];\n        }\n      }\n      tau = 0.0;\n      for (int j = 0; j < size_A; ++j) {\n        tau += inverse_A_[j] * b[j];\n      }\n\n      same_as_before = false;\n    }\n\n    if (same_as_before) {\n      // Compute the variable marginals from the full distribution\n      // stored in z.\n      ComputeMarginalsFromSparseDistribution(vertex, active_set_,\n                                             z,\n                                             variable_posteriors,\n                                             additional_posteriors);\n    //cout<<\"ComputeMarginals 1 in solveQP ..\"<<endl;\n      // Get the most violated constraint\n      // (by calling the black box that computes the MAP).\n      vec scores = variable_log_potentials;               \n      for (int i = 0; i < scores.size(); ++i) {\n        scores[i] -= variable_posteriors[i];\n      }\n      Configuration configuration = -1;\n      double value = 0.0;\n      \n      Maximize(vertex,\n                additional_log_potentials, scores,\n               configuration,\n               &value);\n     //cout<<\"Maximize 2 in SolveQP\"<<endl;\n      double very_small_threshold = 1e-9;\n      if (value <= tau + very_small_threshold) { // value <= tau.\n        // We have found the solution;\n        // the distribution, active set, and inv(A) are cached for the next round.\n        DeleteConfiguration(configuration);\n        return;\n      } else {\n        for (int k = 0; k < active_set_.size(); ++k) {\n          // This is expensive and should just be a sanity check.\n          // However, in practice, numerical issues force an already existing\n          // configuration to try to be added. Therefore, we always check\n          // if a configuration already exists before inserting it.\n          // If it does, that means the active set method converged to a\n          // solution (but numerical issues had prevented us to see it.)\n          if (active_set_[k] == configuration) {                         ////////\n            if (opts.verbose > 2) {\n              cout << \"Warning: value - tau = \"\n                   << value - tau << \" \" << value << \" \" << tau\n                   << endl;\n            }\n            // We have found the solution;\n            // the distribution, active set, and inv(A)\n            // are cached for the next round.\n            DeleteConfiguration(configuration);\n\n            // Just in case, clean the cache.\n            // This may prevent eventual numerical problems in the future.\n            for (int j = 0; j < active_set_.size(); ++j) {\n              if (j == k) continue; // This configuration was deleted already.\n              DeleteConfiguration(active_set_[j]);\n            }\n            active_set_.clear();\n            inverse_A_.clear();\n            distribution_.clear();\n\n            // Return.\n            return;\n          }\n        }\n        z.push_back(0.0);\n        distribution_ = z;\n\n        // Update inv(A).\n        bool singular = !InvertAfterInsertion(vertex, inverse_A_, active_set_, configuration);\n        //cout<<\"Invertafterinsertion in solveQP ..\"<<endl;\n        if (singular) {\n          // If adding a new configuration causes the matrix to be singular,\n          // don't just add it. Instead, look for a configuration in the null\n          // space and remove it before inserting the new one.\n          // Right now, if more than one such configuration exists, we just\n          // remove the first one we find. There's a chance this could cause\n          // some cyclic behaviour. If that is the case, we should randomize\n          // this choice.\n          // Note: This step is expensive and requires an eigendecomposition.\n          // TODO: I think there is a graph interpretation for this problem.\n          // Maybe some specialized graph algorithm is cheaper than doing\n          // the eigendecomposition.\n          vector<double> similarities(active_set_.size() * active_set_.size());\n          ComputeActiveSetSimilarities(vertex, active_set_, &similarities);\n          \n          //cout<<\"compute active similarities in solveQP ..\"<<endl;\n          vector<double> padded_similarities((active_set_.size()+2) * \n                                             (active_set_.size()+2), 1.0);\n          for (int i = 0; i < active_set_.size(); ++i) {\n            for (int j = 0; j < active_set_.size(); ++j) {\n              padded_similarities[(i+1)*(active_set_.size()+2) + (j+1)] =\n                  similarities[i*active_set_.size() + j];\n            }\n          }\n          padded_similarities[0] = 0.0;\n          for (int i = 0; i < active_set_.size(); ++i) {\n            double value = static_cast<double>(\n                CountCommonValues(vertex, configuration, active_set_[i]));\n            padded_similarities[(i+1)*(active_set_.size()+2) +\n                                (active_set_.size()+1)] = value;\n            padded_similarities[(active_set_.size()+1)*(active_set_.size()+2) +\n                                (i+1)] = value;\n          }\n          double value = static_cast<double>(\n              CountCommonValues(vertex, configuration, configuration));\n          padded_similarities[(active_set_.size()+1)*(active_set_.size()+2) +\n                              (active_set_.size()+1)] = value;\n\n          vector<double> eigenvalues(active_set_.size()+2);\n          EigenDecompose(&padded_similarities, &eigenvalues);\n          int zero_eigenvalue = -1;\n          for (int i = 0; i < active_set_.size()+2; ++i) {\n            if (NEARLY_EQ_TOL(eigenvalues[i], 0.0, 1e-9)) {\n              if (zero_eigenvalue >= 0) {\n                // If this happens, something failed. Maybe a numerical problem\n                // may cause this. In that case, just give up, clean the cache\n                // and return. Hopefully the next iteration will fix it.\n                cout << \"Multiple zero eigenvalues: \"\n                     << eigenvalues[zero_eigenvalue] << \" and \"\n                     << eigenvalues[i] << endl;\n                cout << \"Warning: Giving up.\" << endl;\n                // Clean the cache.\n                for (int j = 0; j < active_set_.size(); ++j) {\n                  DeleteConfiguration(active_set_[j]);\n                }\n                active_set_.clear();\n                inverse_A_.clear();\n                distribution_.clear();\n                return;\n              }\n              zero_eigenvalue = i;\n            }\n          }\n          assert(zero_eigenvalue >= 0);\n          vector<int> configurations_to_remove;\n          for (int j = 1; j < active_set_.size()+1; ++j) {\n            double value = padded_similarities[zero_eigenvalue*(active_set_.size()+2) + j];\n            if (!NEARLY_EQ_TOL(value, 0.0, 1e-9)) {\n              configurations_to_remove.push_back(j-1);\n            }\n          }\n          if (opts.verbose > 2) {\n            cout << \"Pick a configuration to remove (\" << configurations_to_remove.size()\n                 << \" out of \" << active_set_.size() << \").\" << endl;\n          }\n\n          assert(configurations_to_remove.size() >= 1);\n          int j = configurations_to_remove[0];\n\n          // Update inv(A).\n          InvertAfterRemoval(inverse_A_, active_set_, j);\n\n          // Remove blocking constraint from the active set.\n          DeleteConfiguration(active_set_[j]); // Delete configutation.\n          active_set_.erase(active_set_.begin() + j);\n\n          singular = !InvertAfterInsertion(vertex, inverse_A_, active_set_, configuration);\n          assert(!singular);\n        }\n\n        // Insert configuration to active set.\n        if (opts.verbose > 2) {\n          cout << \"Inserted one element to the active set (iteration \"\n               << iter << \").\" << endl;\n        }\n        active_set_.push_back(configuration);\n        changed_active_set = true;\n      }      \n    } else {\n      // Solution has changed from the previous iteration.\n      // Look for blocking constraints.\n      int blocking = -1;\n      bool exist_blocking = false;\n      double alpha = 1.0;\n      for (int i = 0; i < active_set_.size(); ++i) {\n        assert(distribution_[i] >= -1e-12);\n        if (z[i] >= distribution_[i]) continue;\n        if (z[i] < 0) exist_blocking = true;\n        double tmp = distribution_[i] / (distribution_[i] - z[i]);\n        if (blocking < 0 || tmp < alpha) {\n          alpha = tmp;\n          blocking = i;\n        }\n      }\n\n      if (!exist_blocking) {\n        // No blocking constraints.\n        assert(!unbounded);\n        distribution_ = z;\n        alpha = 1.0;\n        changed_active_set = false;\n      } else {\n        if (alpha > 1.0 && !unbounded) alpha = 1.0;\n        // Interpolate between factor_posteriors_[i] and z.\n        if (alpha == 1.0) {\n          distribution_ = z;\n        } else {\n          for (int i = 0; i < active_set_.size(); ++i) {\n            z[i] = (1 - alpha) * distribution_[i] + alpha * z[i];\n            distribution_[i] = z[i];\n          }\n        }\n\n        // Update inv(A).\n        InvertAfterRemoval(inverse_A_, active_set_, blocking);\n\n        // Remove blocking constraint from the active set.\n        if (opts.verbose > 2) {\n          cout << \"Removed one element to the active set (iteration \"\n               << iter << \").\" << endl;\n        }\n\n        DeleteConfiguration(active_set_[blocking]); // Delete configutation.\n        active_set_.erase(active_set_.begin() + blocking);\n\n        z.erase(z.begin() + blocking);\n        distribution_.erase(distribution_.begin() + blocking);\n        changed_active_set = true;\n        for (int i = 0; i < distribution_.size(); ++i) {\n          assert(distribution_[i] > -1e-16);\n        }\n      }\n    }\n  }\n\n  // Maximum number of iterations reached.\n  // Return the best existing solution by computing the variable marginals \n  // from the full distribution stored in z.\n  //assert(false);\n  ComputeMarginalsFromSparseDistribution(vertex, active_set_,\n                                         z,\n                                         variable_posteriors,\n                                         additional_posteriors); \n  };\n\n};\n#endif\n", "meta": {"hexsha": "dae0cf069b987f1d3129d6a3e83846f2fb73eea4", "size": 23305, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "toolkits/graphical_models/ad3_qp.hpp", "max_stars_repo_name": "zgdahai/graphlabapi", "max_stars_repo_head_hexsha": "7d66bbda82d4d44cded35f9438e1c9359b0ca64e", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-11-07T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-07T05:47:18.000Z", "max_issues_repo_path": "toolkits/graphical_models/ad3_qp.hpp", "max_issues_repo_name": "keerthanashanmugam/graphlabapi", "max_issues_repo_head_hexsha": "7d66bbda82d4d44cded35f9438e1c9359b0ca64e", "max_issues_repo_licenses": ["ECL-2.0", "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": "toolkits/graphical_models/ad3_qp.hpp", "max_forks_repo_name": "keerthanashanmugam/graphlabapi", "max_forks_repo_head_hexsha": "7d66bbda82d4d44cded35f9438e1c9359b0ca64e", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5855572998, "max_line_length": 127, "alphanum_fraction": 0.5738253594, "num_tokens": 5794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24186162614190215}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2011-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2015.\n// Modifications copyright (c) 2015 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_PARTITION_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_PARTITION_HPP\n\n#include <cstddef>\n#include <vector>\n#include <boost/range.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/coordinate_type.hpp>\n#include <boost/geometry/algorithms/assign.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace detail { namespace partition\n{\n\ntemplate <int Dimension, typename Box>\ninline void divide_box(Box const& box, Box& lower_box, Box& upper_box)\n{\n    typedef typename coordinate_type<Box>::type ctype;\n\n    // Divide input box into two parts, e.g. left/right\n    ctype two = 2;\n    ctype mid = (geometry::get<min_corner, Dimension>(box)\n            + geometry::get<max_corner, Dimension>(box)) / two;\n\n    lower_box = box;\n    upper_box = box;\n    geometry::set<max_corner, Dimension>(lower_box, mid);\n    geometry::set<min_corner, Dimension>(upper_box, mid);\n}\n\n// Divide forward_range into three subsets: lower, upper and oversized\n// (not-fitting)\n// (lower == left or bottom, upper == right or top)\ntemplate <typename OverlapsPolicy, typename Box, typename IteratorVector>\ninline void divide_into_subsets(Box const& lower_box,\n        Box const& upper_box,\n        IteratorVector const& input,\n        IteratorVector& lower,\n        IteratorVector& upper,\n        IteratorVector& exceeding)\n{\n    typedef typename boost::range_iterator\n        <\n            IteratorVector const\n        >::type it_type;\n\n    for(it_type it = boost::begin(input); it != boost::end(input); ++it)\n    {\n        bool const lower_overlapping = OverlapsPolicy::apply(lower_box, **it);\n        bool const upper_overlapping = OverlapsPolicy::apply(upper_box, **it);\n\n        if (lower_overlapping && upper_overlapping)\n        {\n            exceeding.push_back(*it);\n        }\n        else if (lower_overlapping)\n        {\n            lower.push_back(*it);\n        }\n        else if (upper_overlapping)\n        {\n            upper.push_back(*it);\n        }\n        else\n        {\n            // Is nowhere. That is (since 1.58) possible, it might be\n            // skipped by the OverlapsPolicy to enhance performance\n        }\n    }\n}\n\ntemplate\n<\n    typename ExpandPolicy,\n    typename Box,\n    typename IteratorVector\n>\ninline void expand_with_elements(Box& total, IteratorVector const& input)\n{\n    typedef typename boost::range_iterator<IteratorVector const>::type it_type;\n    for(it_type it = boost::begin(input); it != boost::end(input); ++it)\n    {\n        ExpandPolicy::apply(total, **it);\n    }\n}\n\n\n// Match forward_range with itself\ntemplate <typename Policy, typename IteratorVector>\ninline void handle_one(IteratorVector const& input, Policy& policy)\n{\n    if (boost::size(input) == 0)\n    {\n        return;\n    }\n\n    typedef typename boost::range_iterator<IteratorVector const>::type it_type;\n\n    // Quadratic behaviour at lowest level (lowest quad, or all exceeding)\n    for (it_type it1 = boost::begin(input); it1 != boost::end(input); ++it1)\n    {\n        it_type it2 = it1;\n        for (++it2; it2 != boost::end(input); ++it2)\n        {\n            policy.apply(**it1, **it2);\n        }\n    }\n}\n\n// Match forward range 1 with forward range 2\ntemplate\n<\n    typename Policy,\n    typename IteratorVector1,\n    typename IteratorVector2\n>\ninline void handle_two(IteratorVector1 const& input1,\n        IteratorVector2 const& input2,\n        Policy& policy)\n{\n    typedef typename boost::range_iterator\n        <\n            IteratorVector1 const\n        >::type iterator_type1;\n\n    typedef typename boost::range_iterator\n        <\n            IteratorVector2 const\n        >::type iterator_type2;\n\n    if (boost::size(input1) == 0 || boost::size(input2) == 0)\n    {\n        return;\n    }\n\n    for(iterator_type1 it1 = boost::begin(input1);\n        it1 != boost::end(input1);\n        ++it1)\n    {\n        for(iterator_type2 it2 = boost::begin(input2);\n            it2 != boost::end(input2);\n            ++it2)\n        {\n            policy.apply(**it1, **it2);\n        }\n    }\n}\n\ntemplate <typename IteratorVector>\ninline bool recurse_ok(IteratorVector const& input,\n                std::size_t min_elements, std::size_t level)\n{\n    return boost::size(input) >= min_elements\n        && level < 100;\n}\n\ntemplate <typename IteratorVector1, typename IteratorVector2>\ninline bool recurse_ok(IteratorVector1 const& input1,\n                IteratorVector2 const& input2,\n                std::size_t min_elements, std::size_t level)\n{\n    return boost::size(input1) >= min_elements\n        && recurse_ok(input2, min_elements, level);\n}\n\ntemplate\n<\n    typename IteratorVector1,\n    typename IteratorVector2,\n    typename IteratorVector3\n>\ninline bool recurse_ok(IteratorVector1 const& input1,\n                IteratorVector2 const& input2,\n                IteratorVector3 const& input3,\n                std::size_t min_elements, std::size_t level)\n{\n    return boost::size(input1) >= min_elements\n        && recurse_ok(input2, input3, min_elements, level);\n}\n\ntemplate\n<\n    int Dimension,\n    typename Box,\n    typename OverlapsPolicy1,\n    typename OverlapsPolicy2,\n    typename ExpandPolicy1,\n    typename ExpandPolicy2,\n    typename VisitBoxPolicy\n>\nclass partition_two_ranges;\n\n\ntemplate\n<\n    int Dimension,\n    typename Box,\n    typename OverlapsPolicy,\n    typename ExpandPolicy,\n    typename VisitBoxPolicy\n>\nclass partition_one_range\n{\n    template <typename IteratorVector>\n    static inline Box get_new_box(IteratorVector const& input)\n    {\n        Box box;\n        geometry::assign_inverse(box);\n        expand_with_elements<ExpandPolicy>(box, input);\n        return box;\n    }\n\n    template <typename Policy, typename IteratorVector>\n    static inline void next_level(Box const& box,\n            IteratorVector const& input,\n            std::size_t level, std::size_t min_elements,\n            Policy& policy, VisitBoxPolicy& box_policy)\n    {\n        if (recurse_ok(input, min_elements, level))\n        {\n            partition_one_range\n            <\n                1 - Dimension,\n                Box,\n                OverlapsPolicy,\n                ExpandPolicy,\n                VisitBoxPolicy\n            >::apply(box, input, level + 1, min_elements, policy, box_policy);\n        }\n        else\n        {\n            handle_one(input, policy);\n        }\n    }\n\n    // Function to switch to two forward ranges if there are\n    // geometries exceeding the separation line\n    template <typename Policy, typename IteratorVector>\n    static inline void next_level2(Box const& box,\n            IteratorVector const& input1,\n            IteratorVector const& input2,\n            std::size_t level, std::size_t min_elements,\n            Policy& policy, VisitBoxPolicy& box_policy)\n    {\n        if (recurse_ok(input1, input2, min_elements, level))\n        {\n            partition_two_ranges\n            <\n                1 - Dimension,\n                Box,\n                OverlapsPolicy, OverlapsPolicy,\n                ExpandPolicy, ExpandPolicy,\n                VisitBoxPolicy\n            >::apply(box, input1, input2, level + 1, min_elements,\n                policy, box_policy);\n        }\n        else\n        {\n            handle_two(input1, input2, policy);\n        }\n    }\n\npublic :\n    template <typename Policy, typename IteratorVector>\n    static inline void apply(Box const& box,\n            IteratorVector const& input,\n            std::size_t level,\n            std::size_t min_elements,\n            Policy& policy, VisitBoxPolicy& box_policy)\n    {\n        box_policy.apply(box, level);\n\n        Box lower_box, upper_box;\n        divide_box<Dimension>(box, lower_box, upper_box);\n\n        IteratorVector lower, upper, exceeding;\n        divide_into_subsets<OverlapsPolicy>(lower_box, upper_box,\n                    input, lower, upper, exceeding);\n\n        if (boost::size(exceeding) > 0)\n        {\n            // Get the box of exceeding-only\n            Box exceeding_box = get_new_box(exceeding);\n\n            // Recursively do exceeding elements only, in next dimension they\n            // will probably be less exceeding within the new box\n            next_level(exceeding_box, exceeding, level, min_elements,\n                policy, box_policy);\n\n            // Switch to two forward ranges, combine exceeding with\n            // lower resp upper, but not lower/lower, upper/upper\n            next_level2(exceeding_box, exceeding, lower, level, min_elements,\n                policy, box_policy);\n            next_level2(exceeding_box, exceeding, upper, level, min_elements,\n                policy, box_policy);\n        }\n\n        // Recursively call operation both parts\n        next_level(lower_box, lower, level, min_elements, policy, box_policy);\n        next_level(upper_box, upper, level, min_elements, policy, box_policy);\n    }\n};\n\ntemplate\n<\n    int Dimension,\n    typename Box,\n    typename OverlapsPolicy1,\n    typename OverlapsPolicy2,\n    typename ExpandPolicy1,\n    typename ExpandPolicy2,\n    typename VisitBoxPolicy\n>\nclass partition_two_ranges\n{\n    template\n    <\n        typename Policy,\n        typename IteratorVector1,\n        typename IteratorVector2\n    >\n    static inline void next_level(Box const& box,\n            IteratorVector1 const& input1,\n            IteratorVector2 const& input2,\n            std::size_t level, std::size_t min_elements,\n            Policy& policy, VisitBoxPolicy& box_policy)\n    {\n        partition_two_ranges\n        <\n            1 - Dimension,\n            Box,\n            OverlapsPolicy1,\n            OverlapsPolicy2,\n            ExpandPolicy1,\n            ExpandPolicy2,\n            VisitBoxPolicy\n        >::apply(box, input1, input2, level + 1, min_elements,\n                 policy, box_policy);\n    }\n\n    template <typename ExpandPolicy, typename IteratorVector>\n    static inline Box get_new_box(IteratorVector const& input)\n    {\n        Box box;\n        geometry::assign_inverse(box);\n        expand_with_elements<ExpandPolicy>(box, input);\n        return box;\n    }\n\n    template <typename IteratorVector1, typename IteratorVector2>\n    static inline Box get_new_box(IteratorVector1 const& input1,\n                    IteratorVector2 const& input2)\n    {\n        Box box = get_new_box<ExpandPolicy1>(input1);\n        expand_with_elements<ExpandPolicy2>(box, input2);\n        return box;\n    }\n\npublic :\n    template\n    <\n        typename Policy,\n        typename IteratorVector1,\n        typename IteratorVector2\n    >\n    static inline void apply(Box const& box,\n            IteratorVector1 const& input1,\n            IteratorVector2 const& input2,\n            std::size_t level,\n            std::size_t min_elements,\n            Policy& policy, VisitBoxPolicy& box_policy)\n    {\n        box_policy.apply(box, level);\n\n        Box lower_box, upper_box;\n        divide_box<Dimension>(box, lower_box, upper_box);\n\n        IteratorVector1 lower1, upper1, exceeding1;\n        IteratorVector2 lower2, upper2, exceeding2;\n        divide_into_subsets<OverlapsPolicy1>(lower_box, upper_box,\n                    input1, lower1, upper1, exceeding1);\n        divide_into_subsets<OverlapsPolicy2>(lower_box, upper_box,\n                    input2, lower2, upper2, exceeding2);\n\n        if (boost::size(exceeding1) > 0)\n        {\n            // All exceeding from 1 with 2:\n\n            if (recurse_ok(exceeding1, exceeding2, min_elements, level))\n            {\n                Box exceeding_box = get_new_box(exceeding1, exceeding2);\n                next_level(exceeding_box, exceeding1, exceeding2, level,\n                           min_elements, policy, box_policy);\n            }\n            else\n            {\n                handle_two(exceeding1, exceeding2, policy);\n            }\n\n            // All exceeding from 1 with lower and upper of 2:\n\n            // (Check sizes of all three forward ranges to avoid recurse into\n            // the same combinations again and again)\n            if (recurse_ok(lower2, upper2, exceeding1, min_elements, level))\n            {\n                Box exceeding_box = get_new_box<ExpandPolicy1>(exceeding1);\n                next_level(exceeding_box, exceeding1, lower2, level,\n                           min_elements, policy, box_policy);\n                next_level(exceeding_box, exceeding1, upper2, level,\n                           min_elements, policy, box_policy);\n            }\n            else\n            {\n                handle_two(exceeding1, lower2, policy);\n                handle_two(exceeding1, upper2, policy);\n            }\n        }\n\n        if (boost::size(exceeding2) > 0)\n        {\n            // All exceeding from 2 with lower and upper of 1:\n            if (recurse_ok(lower1, upper1, exceeding2, min_elements, level))\n            {\n                Box exceeding_box = get_new_box<ExpandPolicy2>(exceeding2);\n                next_level(exceeding_box, lower1, exceeding2, level,\n                    min_elements, policy, box_policy);\n                next_level(exceeding_box, upper1, exceeding2, level,\n                    min_elements, policy, box_policy);\n            }\n            else\n            {\n                handle_two(lower1, exceeding2, policy);\n                handle_two(upper1, exceeding2, policy);\n            }\n        }\n\n        if (recurse_ok(lower1, lower2, min_elements, level))\n        {\n            next_level(lower_box, lower1, lower2, level,\n                       min_elements, policy, box_policy);\n        }\n        else\n        {\n            handle_two(lower1, lower2, policy);\n        }\n        if (recurse_ok(upper1, upper2, min_elements, level))\n        {\n            next_level(upper_box, upper1, upper2, level,\n                       min_elements, policy, box_policy);\n        }\n        else\n        {\n            handle_two(upper1, upper2, policy);\n        }\n    }\n};\n\nstruct visit_no_policy\n{\n    template <typename Box>\n    static inline void apply(Box const&, std::size_t )\n    {}\n};\n\nstruct include_all_policy\n{\n    template <typename Item>\n    static inline bool apply(Item const&)\n    {\n        return true;\n    }\n};\n\n\n}} // namespace detail::partition\n\ntemplate\n<\n    typename Box,\n    typename ExpandPolicy1,\n    typename OverlapsPolicy1,\n    typename ExpandPolicy2 = ExpandPolicy1,\n    typename OverlapsPolicy2 = OverlapsPolicy1,\n    typename IncludePolicy1 = detail::partition::include_all_policy,\n    typename IncludePolicy2 = detail::partition::include_all_policy,\n    typename VisitBoxPolicy = detail::partition::visit_no_policy\n>\nclass partition\n{\n    template\n    <\n        typename ExpandPolicy,\n        typename IncludePolicy,\n        typename ForwardRange,\n        typename IteratorVector\n    >\n    static inline void expand_to_range(ForwardRange const& forward_range,\n                Box& total, IteratorVector& iterator_vector)\n    {\n        for(typename boost::range_iterator<ForwardRange const>::type it\n            = boost::begin(forward_range);\n            it != boost::end(forward_range);\n            ++it)\n        {\n            if (IncludePolicy::apply(*it))\n            {\n                ExpandPolicy::apply(total, *it);\n                iterator_vector.push_back(it);\n            }\n        }\n    }\n\npublic :\n    template <typename ForwardRange, typename VisitPolicy>\n    static inline void apply(ForwardRange const& forward_range,\n            VisitPolicy& visitor,\n            std::size_t min_elements = 16,\n            VisitBoxPolicy box_visitor = detail::partition::visit_no_policy()\n            )\n    {\n        typedef typename boost::range_iterator\n            <\n                ForwardRange const\n            >::type iterator_type;\n\n        if (std::size_t(boost::size(forward_range)) > min_elements)\n        {\n            std::vector<iterator_type> iterator_vector;\n            Box total;\n            assign_inverse(total);\n            expand_to_range<ExpandPolicy1, IncludePolicy1>(forward_range,\n                    total, iterator_vector);\n\n            detail::partition::partition_one_range\n                <\n                    0, Box,\n                    OverlapsPolicy1,\n                    ExpandPolicy1,\n                    VisitBoxPolicy\n                >::apply(total, iterator_vector, 0, min_elements,\n                         visitor, box_visitor);\n        }\n        else\n        {\n            for(iterator_type it1 = boost::begin(forward_range);\n                it1 != boost::end(forward_range);\n                ++it1)\n            {\n                iterator_type it2 = it1;\n                for(++it2; it2 != boost::end(forward_range); ++it2)\n                {\n                    visitor.apply(*it1, *it2);\n                }\n            }\n        }\n    }\n\n    template\n    <\n        typename ForwardRange1,\n        typename ForwardRange2,\n        typename VisitPolicy\n    >\n    static inline void apply(ForwardRange1 const& forward_range1,\n                ForwardRange2 const& forward_range2,\n                VisitPolicy& visitor,\n                std::size_t min_elements = 16,\n                VisitBoxPolicy box_visitor\n                    = detail::partition::visit_no_policy()\n                )\n    {\n        typedef typename boost::range_iterator\n            <\n                ForwardRange1 const\n            >::type iterator_type1;\n\n        typedef typename boost::range_iterator\n            <\n                ForwardRange2 const\n            >::type iterator_type2;\n\n        if (std::size_t(boost::size(forward_range1)) > min_elements\n            && std::size_t(boost::size(forward_range2)) > min_elements)\n        {\n            std::vector<iterator_type1> iterator_vector1;\n            std::vector<iterator_type2> iterator_vector2;\n            Box total;\n            assign_inverse(total);\n            expand_to_range<ExpandPolicy1, IncludePolicy1>(forward_range1,\n                    total, iterator_vector1);\n            expand_to_range<ExpandPolicy2, IncludePolicy2>(forward_range2,\n                    total, iterator_vector2);\n\n            detail::partition::partition_two_ranges\n                <\n                    0, Box, OverlapsPolicy1, OverlapsPolicy2,\n                    ExpandPolicy1, ExpandPolicy2, VisitBoxPolicy\n                >::apply(total, iterator_vector1, iterator_vector2,\n                         0, min_elements, visitor, box_visitor);\n        }\n        else\n        {\n            for(iterator_type1 it1 = boost::begin(forward_range1);\n                it1 != boost::end(forward_range1);\n                ++it1)\n            {\n                for(iterator_type2 it2 = boost::begin(forward_range2);\n                    it2 != boost::end(forward_range2);\n                    ++it2)\n                {\n                    visitor.apply(*it1, *it2);\n                }\n            }\n        }\n    }\n};\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_PARTITION_HPP\n", "meta": {"hexsha": "8b19add47956fd9181a63fab3c2d37437134ff4a", "size": 19312, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "nheqminer/3rdparty/boost/geometry/algorithms/detail/partition.hpp", "max_stars_repo_name": "EuroLine/nheqminer", "max_stars_repo_head_hexsha": "81c7ef889bb502d16f7d1e7ef020d0592f8af945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/algorithms/detail/partition.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 369.0, "max_issues_repo_issues_event_min_datetime": "2016-10-21T07:42:54.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-19T10:49:29.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/algorithms/detail/partition.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 30.2695924765, "max_line_length": 79, "alphanum_fraction": 0.5945008285, "num_tokens": 4196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24186162614190215}}
{"text": "/*\n * Copyright (c) 2020, The Regents of the University of California (Regents).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *    1. Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *\n *    2. Redistributions in binary form must reproduce the above\n *       copyright notice, this list of conditions and the following\n *       disclaimer in the documentation and/or other materials provided\n *       with the distribution.\n *\n *    3. Neither the name of the copyright holder nor the names of its\n *       contributors may be used to endorse or promote products derived\n *       from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Please contact the author(s) of this library if you have any questions.\n * Authors: David Fridovich-Keil   ( dfk@eecs.berkeley.edu )\n */\n\n///////////////////////////////////////////////////////////////////////////////\n//\n// Core open-loop LQ game solver based on Basar and Olsder, Chapter 6. All\n// notation matches the text, though we shall assume that `c` (additive drift in\n// dynamics) is always `0`, which holds because these dynamics are for delta x,\n// delta us. Also, we have modified terms slightly to account for linear terms\n// in the stage cost for control, i.e.\n//       control penalty i = 0.5 \\sum_j du_j^T R_ij (du_j + 2 r_ij)\n//\n// Solve a time-varying, finite horizon LQ game (finds open-loop Nash\n// feedback strategies for both players).\n//\n// Assumes that dynamics are given by\n//           ``` dx_{k+1} = A_k dx_k + \\sum_i Bs[i]_k du[i]_k ```\n//\n// Returns strategies Ps, alphas. Here, all the Ps are zero (by default), and\n// only the alphas are nonzero.\n//\n// Notation is based on derivation which may be found in the PDF included in\n// this repository named \"open_loop_lq_derivation.pdf\".\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <ilqgames/dynamics/multi_player_integrable_system.h>\n#include <ilqgames/solver/lq_feedback_solver.h>\n#include <ilqgames/solver/lq_open_loop_solver.h>\n#include <ilqgames/utils/linear_dynamics_approximation.h>\n#include <ilqgames/utils/quadratic_cost_approximation.h>\n#include <ilqgames/utils/strategy.h>\n\n#include <glog/logging.h>\n#include <Eigen/Core>\n#include <vector>\n\nnamespace ilqgames {\n\nstd::vector<Strategy> LQOpenLoopSolver::Solve(\n    const std::vector<LinearDynamicsApproximation>& linearization,\n    const std::vector<std::vector<QuadraticCostApproximation>>&\n        quadraticization,\n    const VectorXf& x0, std::vector<VectorXf>* delta_xs,\n    std::vector<std::vector<VectorXf>>* costates) {\n  CHECK_EQ(linearization.size(), num_time_steps_);\n  CHECK_EQ(quadraticization.size(), num_time_steps_);\n\n  // Make sure delta_xs and costates are the right size.\n  if (delta_xs) CHECK_NOTNULL(costates);\n  if (costates) CHECK_NOTNULL(delta_xs);\n  if (delta_xs) {\n    delta_xs->resize(num_time_steps_);\n    costates->resize(num_time_steps_);\n    for (size_t kk = 0; kk < num_time_steps_; kk++) {\n      (*delta_xs)[kk].resize(dynamics_->XDim());\n      (*costates)[kk].resize(dynamics_->NumPlayers());\n      for (PlayerIndex ii = 0; ii < dynamics_->NumPlayers(); ii++)\n        (*costates)[kk][ii].resize(dynamics_->XDim());\n    }\n  }\n\n  // List of player-indexed strategies (each of which is a time-indexed\n  // affine state error-feedback controller). Since this is an open-loop\n  // strategy, we will not change the default zero value of the P matrix.\n  std::vector<Strategy> strategies;\n  for (PlayerIndex ii = 0; ii < dynamics_->NumPlayers(); ii++)\n    strategies.emplace_back(num_time_steps_, dynamics_->XDim(),\n                            dynamics_->UDim(ii));\n\n  // Initialize m^i and M^i and index first by time and then by player.\n  for (PlayerIndex ii = 0; ii < dynamics_->NumPlayers(); ii++) {\n    ms_.back()[ii] = quadraticization.back()[ii].state.grad;\n    Ms_.back()[ii] = quadraticization.back()[ii].state.hess;\n  }\n\n  // (1) Work backward in time and cache \"special\" terms.\n  // NOTE: time starts from the second-to-last entry since we'll treat the\n  // final entry as a terminal cost as in Basar and Olsder, ch. 6.\n  for (int kk = num_time_steps_ - 2; kk >= 0; kk--) {\n    // Unpack linearization and quadraticization at this time step.\n    const auto& lin = linearization[kk];\n    const auto& quad = quadraticization[kk];\n\n    // Campute capital lambdas.\n    capital_lambdas_[kk].setIdentity();\n    for (PlayerIndex ii = 0; ii < dynamics_->NumPlayers(); ii++) {\n      const auto control_iter = quad[ii].control.find(ii);\n      CHECK(control_iter != quad[ii].control.end());\n\n      chol_Rs_[kk][ii].compute(control_iter->second.hess);\n      warped_Bs_[kk][ii] = chol_Rs_[kk][ii].solve(lin.Bs[ii].transpose());\n      warped_rs_[kk][ii] = chol_Rs_[kk][ii].solve(control_iter->second.grad);\n      capital_lambdas_[kk] += lin.Bs[ii] * warped_Bs_[kk][ii] * Ms_[kk + 1][ii];\n    }\n\n    // Compute inv(capital lambda).\n    qr_capital_lambdas_[kk].compute(capital_lambdas_[kk]);\n\n    // Compute Ms and ms.\n    intermediate_terms_[kk].setZero();\n    for (PlayerIndex ii = 0; ii < dynamics_->NumPlayers(); ii++) {\n      intermediate_terms_[kk] -=\n          lin.Bs[ii] *\n          (warped_Bs_[kk][ii] * ms_[kk + 1][ii] + warped_rs_[kk][ii]);\n    }\n\n    for (PlayerIndex ii = 0; ii < dynamics_->NumPlayers(); ii++) {\n      Ms_[kk][ii] =\n          quad[ii].state.hess + lin.A.transpose() * Ms_[kk + 1][ii] *\n                                    qr_capital_lambdas_[kk].solve(lin.A);\n      ms_[kk][ii] =\n          quad[ii].state.grad +\n          lin.A.transpose() * (ms_[kk + 1][ii] +\n                               Ms_[kk + 1][ii] * qr_capital_lambdas_[kk].solve(\n                                                     intermediate_terms_[kk]));\n    }\n  }\n\n  // (2) Now compute optimal state and control trajectory forward in time.\n  VectorXf x_star = x0;\n  VectorXf last_x_star;\n  for (size_t kk = 0; kk < num_time_steps_ - 1; kk++) {\n    // Maybe set delta_x.\n    if (delta_xs) (*delta_xs)[kk] = x_star;\n\n    // Unpack linearization at this time step.\n    const auto& lin = linearization[kk];\n\n    // Compute optimal x.\n    last_x_star = x_star;\n    x_star = qr_capital_lambdas_[kk].solve(lin.A * last_x_star +\n                                           intermediate_terms_[kk]);\n\n    // Compute optimal u and store (sign flipped) in alpha.\n    // Also maybe compute costates.\n    for (PlayerIndex ii = 0; ii < dynamics_->NumPlayers(); ii++) {\n      const VectorXf intermediate_term =\n          Ms_[kk + 1][ii] * x_star + ms_[kk + 1][ii];\n      strategies[ii].alphas[kk] =\n          warped_Bs_[kk][ii] * intermediate_term + warped_rs_[kk][ii];\n\n      if (costates) (*costates)[kk][ii] = lin.A.transpose() * intermediate_term;\n    }\n\n    // Check dynamic feasibility.\n    // VectorXf check_x = lin.A * last_x_star;\n    // for (PlayerIndex ii = 0; ii < dynamics_->NumPlayers(); ii++)\n    //   check_x -= lin.Bs[ii] * strategies[ii].alphas[kk];\n\n    // CHECK_LE((x_star - check_x).cwiseAbs().maxCoeff(), 1e-1);\n  }\n\n  // Set delta_x and costate for last time step.\n  if (delta_xs) {\n    delta_xs->back() = x_star;\n    for (PlayerIndex ii = 0; ii < dynamics_->NumPlayers(); ii++)\n      costates->back()[ii].setZero();\n  }\n\n  return strategies;\n}\n\n}  // namespace ilqgames\n", "meta": {"hexsha": "03dd91ad6c7e61d443f23047868ab171e736bc8c", "size": 8242, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lq_open_loop_solver.cpp", "max_stars_repo_name": "anjianli21/ilqgames", "max_stars_repo_head_hexsha": "2be8e2bc6d34a9a6296d341b75d59e37c9057ad5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2019-11-25T02:51:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T18:30:02.000Z", "max_issues_repo_path": "src/lq_open_loop_solver.cpp", "max_issues_repo_name": "anjianli21/ilqgames", "max_issues_repo_head_hexsha": "2be8e2bc6d34a9a6296d341b75d59e37c9057ad5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 42.0, "max_issues_repo_issues_event_min_datetime": "2019-10-05T20:22:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T20:10:35.000Z", "max_forks_repo_path": "src/lq_open_loop_solver.cpp", "max_forks_repo_name": "anjianli21/ilqgames", "max_forks_repo_head_hexsha": "2be8e2bc6d34a9a6296d341b75d59e37c9057ad5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2020-01-02T13:33:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T01:55:28.000Z", "avg_line_length": 41.6262626263, "max_line_length": 80, "alphanum_fraction": 0.654816792, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.24186162614190215}}
{"text": "/*\n * Copyright (c) 2021 Abit More, and contributors.\n *\n * The MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <graphene/chain/market_object.hpp>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include <functional>\n\n#include <fc/io/raw.hpp>\n\nusing namespace graphene::chain;\n\n/*\ntarget_CR = max( target_CR, MCR )\n\ntarget_CR = new_collateral / ( new_debt / feed_price )\n          = ( collateral - max_amount_to_sell ) * feed_price\n            / ( debt - amount_to_get )\n          = ( collateral - max_amount_to_sell ) * feed_price\n            / ( debt - round_down(max_amount_to_sell * match_price ) )\n          = ( collateral - max_amount_to_sell ) * feed_price\n            / ( debt - (max_amount_to_sell * match_price - x) )\n\nNote: x is the fraction, 0 <= x < 1\n\n=>\n\nmax_amount_to_sell = ( (debt + x) * target_CR - collateral * feed_price )\n                     / (target_CR * match_price - feed_price)\n                   = ( (debt + x) * tCR / DENOM - collateral * fp_debt_amt / fp_coll_amt )\n                     / ( (tCR / DENOM) * (mp_debt_amt / mp_coll_amt) - fp_debt_amt / fp_coll_amt )\n                   = ( (debt + x) * tCR * fp_coll_amt * mp_coll_amt - collateral * fp_debt_amt * DENOM * mp_coll_amt)\n                     / ( tCR * mp_debt_amt * fp_coll_amt - fp_debt_amt * DENOM * mp_coll_amt )\n\nmax_debt_to_cover = max_amount_to_sell * match_price\n                  = max_amount_to_sell * mp_debt_amt / mp_coll_amt\n                  = ( (debt + x) * tCR * fp_coll_amt * mp_debt_amt - collateral * fp_debt_amt * DENOM * mp_debt_amt)\n                    / (tCR * mp_debt_amt * fp_coll_amt - fp_debt_amt * DENOM * mp_coll_amt)\n*/\nshare_type call_order_object::get_max_debt_to_cover( price match_price,\n                                                     price feed_price,\n                                                     const uint16_t maintenance_collateral_ratio,\n                                                     const optional<price>& maintenance_collateralization )const\n{ try {\n   // be defensive here, make sure feed_price is in collateral / debt format\n   if( feed_price.base.asset_id != call_price.base.asset_id )\n      feed_price = ~feed_price;\n\n   FC_ASSERT( feed_price.base.asset_id == call_price.base.asset_id\n              && feed_price.quote.asset_id == call_price.quote.asset_id );\n\n   bool after_core_hardfork_1270 = maintenance_collateralization.valid();\n\n   // be defensive here, make sure maintenance_collateralization is in collateral / debt format\n   if( after_core_hardfork_1270 )\n   {\n      FC_ASSERT( maintenance_collateralization->base.asset_id == call_price.base.asset_id\n                 && maintenance_collateralization->quote.asset_id == call_price.quote.asset_id );\n   }\n\n   // According to the feed protection rule (https://github.com/cryptonomex/graphene/issues/436),\n   // a call order should only be called when its collateral ratio is not higher than required maintenance collateral ratio.\n   // Although this should be guaranteed by the caller of this function, we still check here to be defensive.\n   // Theoretically this check can be skipped for better performance.\n   //\n   // Before core-1270 hard fork, we check with call_price; afterwards, we check with collateralization().\n   if( ( !after_core_hardfork_1270 && call_price > feed_price )\n       || ( after_core_hardfork_1270 && collateralization() > *maintenance_collateralization ) )\n      return 0;\n\n   if( !target_collateral_ratio.valid() ) // target cr is not set\n      return debt;\n\n   uint16_t tcr = std::max( *target_collateral_ratio, maintenance_collateral_ratio ); // use mcr if target cr is too small\n\n   price target_collateralization = ( after_core_hardfork_1270 ?\n                                      feed_price * ratio_type( tcr, GRAPHENE_COLLATERAL_RATIO_DENOM ) :\n                                      price() );\n\n   // be defensive here, make sure match_price is in collateral / debt format\n   if( match_price.base.asset_id != call_price.base.asset_id )\n      match_price = ~match_price;\n\n   FC_ASSERT( match_price.base.asset_id == call_price.base.asset_id\n              && match_price.quote.asset_id == call_price.quote.asset_id );\n\n   typedef boost::multiprecision::int256_t i256;\n   i256 mp_debt_amt = match_price.quote.amount.value;\n   i256 mp_coll_amt = match_price.base.amount.value;\n   i256 fp_debt_amt = feed_price.quote.amount.value;\n   i256 fp_coll_amt = feed_price.base.amount.value;\n\n   // firstly we calculate without the fraction (x), the result could be a bit too small\n   i256 numerator = fp_coll_amt * mp_debt_amt * debt.value * tcr\n                  - fp_debt_amt * mp_debt_amt * collateral.value * GRAPHENE_COLLATERAL_RATIO_DENOM;\n   if( numerator < 0 ) // feed protected, actually should not be true here, just check to be safe\n      return 0;\n\n   i256 denominator = fp_coll_amt * mp_debt_amt * tcr - fp_debt_amt * mp_coll_amt * GRAPHENE_COLLATERAL_RATIO_DENOM;\n   if( denominator <= 0 ) // black swan\n      return debt;\n\n   // note: if add 1 here, will result in 1.5x imperfection rate;\n   //       however, due to rounding, the result could still be a bit too big, thus imperfect.\n   i256 to_cover_i256 = ( numerator / denominator );\n   if( to_cover_i256 >= debt.value ) // avoid possible overflow\n      return debt;\n   share_type to_cover_amt = static_cast< int64_t >( to_cover_i256 );\n\n   // stabilize\n   // note: rounding up-down results in 3x imperfection rate in comparison to down-down-up\n   asset to_pay = asset( to_cover_amt, debt_type() ) * match_price;\n   asset to_cover = to_pay * match_price;\n   to_pay = to_cover.multiply_and_round_up( match_price );\n\n   if( to_cover.amount >= debt || to_pay.amount >= collateral ) // to be safe\n      return debt;\n   FC_ASSERT( to_pay.amount < collateral && to_cover.amount < debt );\n\n   // Check whether the collateral ratio after filled is high enough\n   // Before core-1270 hard fork, we check with call_price; afterwards, we check with collateralization().\n   std::function<bool()> result_is_good = after_core_hardfork_1270 ?\n      std::function<bool()>( [this,&to_cover,&to_pay,target_collateralization]() -> bool\n      {\n         price new_collateralization = ( get_collateral() - to_pay ) / ( get_debt() - to_cover );\n         return ( new_collateralization > target_collateralization );\n      }) :\n      std::function<bool()>( [this,&to_cover,&to_pay,tcr,feed_price]() -> bool\n      {\n         price new_call_price = price::call_price( get_debt() - to_cover, get_collateral() - to_pay, tcr );\n         return ( new_call_price > feed_price );\n      });\n\n   // if the result is good, we return.\n   if( result_is_good() )\n      return to_cover.amount;\n\n   // be here, to_cover is too small due to rounding. deal with the fraction\n   numerator += fp_coll_amt * mp_debt_amt * tcr; // plus the fraction\n   to_cover_i256 = ( numerator / denominator ) + 1;\n   if( to_cover_i256 >= debt.value ) // avoid possible overflow\n      to_cover_i256 = debt.value;\n   to_cover_amt = static_cast< int64_t >( to_cover_i256 );\n\n   asset max_to_pay = ( ( to_cover_amt == debt.value ) ? get_collateral()\n                        : asset( to_cover_amt, debt_type() ).multiply_and_round_up( match_price ) );\n   if( max_to_pay.amount > collateral )\n      max_to_pay.amount = collateral;\n\n   asset max_to_cover = ( ( max_to_pay.amount == collateral ) ? get_debt() : ( max_to_pay * match_price ) );\n   if( max_to_cover.amount >= debt ) // to be safe\n   {\n      max_to_pay.amount = collateral;\n      max_to_cover.amount = debt;\n   }\n\n   if( max_to_pay <= to_pay || max_to_cover <= to_cover ) // strange data. should skip binary search and go on, but doesn't help much\n      return debt;\n   FC_ASSERT( max_to_pay > to_pay && max_to_cover > to_cover );\n\n   asset min_to_pay = to_pay;\n   asset min_to_cover = to_cover;\n\n   // try with binary search to find a good value\n   // note: actually binary search can not always provide perfect result here,\n   //       due to rounding, collateral ratio is not always increasing while to_pay or to_cover is increasing\n   bool max_is_ok = false;\n   while( true )\n   {\n      // get the mean\n      if( match_price.base.amount < match_price.quote.amount ) // step of collateral is smaller\n      {\n         to_pay.amount = ( min_to_pay.amount + max_to_pay.amount + 1 ) / 2; // should not overflow. round up here\n         if( to_pay.amount == max_to_pay.amount )\n            to_cover.amount = max_to_cover.amount;\n         else\n         {\n            to_cover = to_pay * match_price;\n            if( to_cover.amount >= max_to_cover.amount ) // can be true when max_is_ok is false\n            {\n               to_pay.amount = max_to_pay.amount;\n               to_cover.amount = max_to_cover.amount;\n            }\n            else\n            {\n               to_pay = to_cover.multiply_and_round_up( match_price ); // stabilization, no change or become smaller\n               FC_ASSERT( to_pay.amount < max_to_pay.amount );\n            }\n         }\n      }\n      else // step of debt is smaller or equal\n      {\n         to_cover.amount = ( min_to_cover.amount + max_to_cover.amount ) / 2; // should not overflow. round down here\n         if( to_cover.amount == max_to_cover.amount )\n            to_pay.amount = max_to_pay.amount;\n         else\n         {\n            to_pay = to_cover.multiply_and_round_up( match_price );\n            if( to_pay.amount >= max_to_pay.amount ) // can be true when max_is_ok is false\n            {\n               to_pay.amount = max_to_pay.amount;\n               to_cover.amount = max_to_cover.amount;\n            }\n            else\n            {\n               to_cover = to_pay * match_price; // stabilization, to_cover should have increased\n               if( to_cover.amount >= max_to_cover.amount ) // to be safe\n               {\n                  to_pay.amount = max_to_pay.amount;\n                  to_cover.amount = max_to_cover.amount;\n               }\n            }\n         }\n      }\n\n      // check again to see if we've moved away from the minimums, if not, use the maximums directly\n      if( to_pay.amount <= min_to_pay.amount || to_cover.amount <= min_to_cover.amount\n            || to_pay.amount > max_to_pay.amount || to_cover.amount > max_to_cover.amount )\n      {\n         to_pay.amount = max_to_pay.amount;\n         to_cover.amount = max_to_cover.amount;\n      }\n\n      // check the mean\n      if( to_pay.amount == max_to_pay.amount && ( max_is_ok || to_pay.amount == collateral ) )\n         return to_cover.amount;\n      FC_ASSERT( to_pay.amount < collateral && to_cover.amount < debt );\n\n      // Check whether the result is good\n      if( result_is_good() ) // good\n      {\n         if( to_pay.amount == max_to_pay.amount )\n            return to_cover.amount;\n         max_to_pay.amount = to_pay.amount;\n         max_to_cover.amount = to_cover.amount;\n         max_is_ok = true;\n      }\n      else // not good\n      {\n         if( to_pay.amount == max_to_pay.amount )\n            break;\n         min_to_pay.amount = to_pay.amount;\n         min_to_cover.amount = to_cover.amount;\n      }\n   }\n\n   // be here, max_to_cover is too small due to rounding. search forward\n   for( uint64_t d1 = 0, d2 = 1, d3 = 1; ; d1 = d2, d2 = d3, d3 = d1 + d2 ) // 1,1,2,3,5,8,...\n   {\n      if( match_price.base.amount > match_price.quote.amount ) // step of debt is smaller\n      {\n         to_pay.amount += d2;\n         if( to_pay.amount >= collateral )\n            return debt;\n         to_cover = to_pay * match_price;\n         if( to_cover.amount >= debt )\n            return debt;\n         to_pay = to_cover.multiply_and_round_up( match_price ); // stabilization\n         if( to_pay.amount >= collateral )\n            return debt;\n      }\n      else // step of collateral is smaller or equal\n      {\n         to_cover.amount += d2;\n         if( to_cover.amount >= debt )\n            return debt;\n         to_pay = to_cover.multiply_and_round_up( match_price );\n         if( to_pay.amount >= collateral )\n            return debt;\n         to_cover = to_pay * match_price; // stabilization\n         if( to_cover.amount >= debt )\n            return debt;\n      }\n\n      // defensive check\n      FC_ASSERT( to_pay.amount < collateral && to_cover.amount < debt );\n\n      // Check whether the result is good\n      if( result_is_good() ) // good\n         return to_cover.amount;\n   }\n\n} FC_CAPTURE_AND_RETHROW( (*this)(feed_price)(match_price)(maintenance_collateral_ratio) ) }\n\nFC_REFLECT_DERIVED_NO_TYPENAME( graphene::chain::limit_order_object,\n                    (graphene::db::object),\n                    (expiration)(seller)(for_sale)(sell_price)(deferred_fee)(deferred_paid_fee)\n                  )\n\nFC_REFLECT_DERIVED_NO_TYPENAME( graphene::chain::call_order_object, (graphene::db::object),\n                    (borrower)(collateral)(debt)(call_price)(target_collateral_ratio) )\n\nFC_REFLECT_DERIVED_NO_TYPENAME( graphene::chain::force_settlement_object,\n                    (graphene::db::object),\n                    (owner)(balance)(settlement_date)\n                  )\n\nFC_REFLECT_DERIVED_NO_TYPENAME( graphene::chain::collateral_bid_object, (graphene::db::object),\n                    (bidder)(inv_swan_price) )\n\nGRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::chain::limit_order_object )\nGRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::chain::call_order_object )\nGRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::chain::force_settlement_object )\nGRAPHENE_IMPLEMENT_EXTERNAL_SERIALIZATION( graphene::chain::collateral_bid_object )\n", "meta": {"hexsha": "b36f43984af5f713ce94ffb3617a7917a28e84a6", "size": 14556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/market_object.cpp", "max_stars_repo_name": "karthikskkk/core", "max_stars_repo_head_hexsha": "b3e4d09552ca82bb8c4df2a9860cc8e7cc5165fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libraries/chain/market_object.cpp", "max_issues_repo_name": "karthikskkk/core", "max_issues_repo_head_hexsha": "b3e4d09552ca82bb8c4df2a9860cc8e7cc5165fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/chain/market_object.cpp", "max_forks_repo_name": "karthikskkk/core", "max_forks_repo_head_hexsha": "b3e4d09552ca82bb8c4df2a9860cc8e7cc5165fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6503067485, "max_line_length": 133, "alphanum_fraction": 0.6482550151, "num_tokens": 3398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.24181873129329282}}
{"text": "#ifndef HW4_RENDER_HPP\n#define HW4_RENDER_HPP\n\n#include <algorithm>\n#include <functional>\n#include <memory>\n\n#include <boost/filesystem.hpp>\n#include <glm/glm.hpp>\n\n#include \"scene.hpp\"\n\nnamespace hw4 {\n    class Image {\n        struct pixel {\n            unsigned char r;\n            unsigned char g;\n            unsigned char b;\n        };\n\n        glm::ivec2 m_size;\n        std::unique_ptr<pixel[]> m_data;\n    public:\n        Image() : m_size(glm::ivec2(0)), m_data(nullptr) {}\n        Image(glm::ivec2 size)\n            : m_size(size), m_data(std::make_unique<pixel[]>(size.x * size.y)) {}\n\n        glm::ivec2 size() const { return this->m_size; }\n\n        Image& fill(glm::vec3 value) {\n            std::fill(\n                &this->m_data[0],\n                &this->m_data[this->m_size.x * this->m_size.y],\n                pixel {\n                    static_cast<unsigned char>(std::round(glm::clamp(value.r, 0.0f, 1.0f) * 255.0f)),\n                    static_cast<unsigned char>(std::round(glm::clamp(value.g, 0.0f, 1.0f) * 255.0f)),\n                    static_cast<unsigned char>(std::round(glm::clamp(value.b, 0.0f, 1.0f) * 255.0f))\n                }\n            );\n\n            return *this;\n        }\n\n        Image& set_pixel(glm::ivec2 pos, glm::vec3 value) {\n            assert(pos.x >= 0 && pos.x < this->m_size.x);\n            assert(pos.y >= 0 && pos.y < this->m_size.y);\n\n            this->m_data[static_cast<size_t>(pos.x + pos.y * this->m_size.x)] = pixel {\n                static_cast<unsigned char>(std::round(glm::clamp(value.r, 0.0f, 1.0f) * 255.0f)),\n                static_cast<unsigned char>(std::round(glm::clamp(value.g, 0.0f, 1.0f) * 255.0f)),\n                static_cast<unsigned char>(std::round(glm::clamp(value.b, 0.0f, 1.0f) * 255.0f))\n            };\n\n            return *this;\n        }\n\n        glm::vec3 get_pixel(glm::ivec2 pos) const {\n            assert(pos.x >= 0 && pos.x < this->m_size.x);\n            assert(pos.y >= 0 && pos.y < this->m_size.y);\n\n            pixel p = this->m_data[static_cast<size_t>(pos.x + pos.y * this->m_size.x)];\n\n            return glm::vec3(p.r / 255.0f, p.g / 255.0f, p.b / 255.0f);\n        }\n\n        Image& copy_data(const Image& img, glm::ivec2 pos) {\n            assert(pos.x >= 0 && pos.x + img.m_size.x <= this->m_size.x);\n            assert(pos.y >= 0 && pos.y + img.m_size.y <= this->m_size.y);\n\n            // Since image rows are stored separately, each row needs to be copied individually.\n            for (int y = 0; y < img.m_size.y; y++) {\n                std::copy(\n                    &img.m_data[y * img.m_size.x],\n                    &img.m_data[(y + 1) * img.m_size.x],\n                    &this->m_data[pos.x + (y + pos.y) * this->m_size.x]\n                );\n            }\n\n            return *this;\n        }\n\n        void save_as_ppm(const boost::filesystem::path& path) const;\n    };\n\n    class RayTraceRenderer {\n        glm::ivec2 m_size;\n        int m_max_recursion;\n        int m_supersample_level;\n        float m_bias;\n        Camera m_camera;\n\n        float m_img_plane_distance;\n        float m_sample_spacing;\n        float m_sample_mult;\n\n        void update_params();\n    public:\n        RayTraceRenderer(\n            glm::ivec2 size,\n            int max_recursion,\n            int supersample_level,\n            float bias,\n            Camera camera\n        )\n            : m_size(size), m_max_recursion(max_recursion), m_supersample_level(supersample_level),\n              m_bias(bias), m_camera(camera) {\n            this->update_params();\n        }\n\n        glm::ivec2 size() const { return this->m_size; }\n        int max_recursion() const { return this->m_max_recursion; }\n        int supersample_level() const { return this->m_supersample_level; }\n        const Camera& camera() const { return this->m_camera; }\n\n        Image render(\n            const Scene& scene,\n            std::function<void (float)> progress_callback\n        ) const;\n        Image render_patch(\n            const Scene& scene,\n            const glm::mat4& inv_view_matrix,\n            glm::ivec2 start,\n            glm::ivec2 size\n        ) const;\n        glm::vec3 render_pixel(\n            const Scene& scene,\n            const glm::mat4& inv_view_matrix,\n            glm::ivec2 pos\n        ) const;\n        glm::vec3 render_ray(\n            const Scene& scene,\n            const Ray& ray\n        ) const {\n            return this->render_ray(scene, ray, 0);\n        }\n    private:\n        glm::vec3 render_ray(\n            const Scene& scene,\n            const Ray& ray,\n            int recursion\n        ) const;\n        glm::vec3 render_point_light(\n            const Scene& scene,\n            const Ray& ray,\n            const Intersection& intersection,\n            const PointMaterial& material,\n            const PointLight& point_light\n        ) const;\n        float get_visibility(const Scene& scene, glm::vec3 from, glm::vec3 to) const;\n    };\n}\n\n#endif\n", "meta": {"hexsha": "103c4bec891ccb57b2fa48bb4ad62d8dba97546f", "size": 4957, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/render.hpp", "max_stars_repo_name": "wasmjit-omr/raytracer", "max_stars_repo_head_hexsha": "f816b3992863b3e204c9e13394d14f292c4bbd98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/render.hpp", "max_issues_repo_name": "wasmjit-omr/raytracer", "max_issues_repo_head_hexsha": "f816b3992863b3e204c9e13394d14f292c4bbd98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/render.hpp", "max_forks_repo_name": "wasmjit-omr/raytracer", "max_forks_repo_head_hexsha": "f816b3992863b3e204c9e13394d14f292c4bbd98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-03T08:27:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-03T08:27:48.000Z", "avg_line_length": 32.1883116883, "max_line_length": 101, "alphanum_fraction": 0.5245107928, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2417177833927635}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MAP_TRANSFORMER_HPP\n#define BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MAP_TRANSFORMER_HPP\n\n\n#include <cstddef>\n\n#include <boost/geometry/strategies/transform/matrix_transformers.hpp>\n\nnamespace boost { namespace geometry\n{\n\n// Silence warning C4127: conditional expression is constant\n#if defined(_MSC_VER)\n#pragma warning(push)  \n#pragma warning(disable : 4127)  \n#endif\n\nnamespace strategy { namespace transform\n{\n\n/*!\n\\brief Transformation strategy to map from one to another Cartesian coordinate system\n\\ingroup strategies\n\\tparam Mirror if true map is mirrored upside-down (in most cases pixels\n    are from top to bottom, while map is from bottom to top)\n */\ntemplate\n<\n    typename CalculationType,\n    std::size_t Dimension1,\n    std::size_t Dimension2,\n    bool Mirror = false,\n    bool SameScale = true\n>\nclass map_transformer\n    : public ublas_transformer<CalculationType, Dimension1, Dimension2>\n{\n    typedef boost::numeric::ublas::matrix<CalculationType> M;\n\npublic :\n    template <typename B, typename D>\n    explicit inline map_transformer(B const& box, D const& width, D const& height)\n    {\n        set_transformation(\n                get<min_corner, 0>(box), get<min_corner, 1>(box),\n                get<max_corner, 0>(box), get<max_corner, 1>(box),\n                width, height);\n    }\n\n    template <typename W, typename D>\n    explicit inline map_transformer(W const& wx1, W const& wy1, W const& wx2, W const& wy2,\n                        D const& width, D const& height)\n    {\n        set_transformation(wx1, wy1, wx2, wy2, width, height);\n    }\n\n\nprivate :\n    template <typename W, typename P, typename S>\n    inline void set_transformation_point(W const& wx, W const& wy,\n        P const& px, P const& py,\n        S const& scalex, S const& scaley)\n    {\n\n        // Translate to a coordinate system centered on world coordinates (-wx, -wy)\n        M t1(3,3);\n        t1(0,0) = 1;   t1(0,1) = 0;   t1(0,2) = -wx;\n        t1(1,0) = 0;   t1(1,1) = 1;   t1(1,2) = -wy;\n        t1(2,0) = 0;   t1(2,1) = 0;   t1(2,2) = 1;\n\n        // Scale the map\n        M s(3,3);\n        s(0,0) = scalex;   s(0,1) = 0;   s(0,2) = 0;\n        s(1,0) = 0;    s(1,1) = scaley;  s(1,2) = 0;\n        s(2,0) = 0;    s(2,1) = 0;      s(2,2) = 1;\n\n        // Translate to a coordinate system centered on the specified pixels (+px, +py)\n        M t2(3, 3);\n        t2(0,0) = 1;   t2(0,1) = 0;   t2(0,2) = px;\n        t2(1,0) = 0;   t2(1,1) = 1;   t2(1,2) = py;\n        t2(2,0) = 0;   t2(2,1) = 0;   t2(2,2) = 1;\n\n        // Calculate combination matrix in two steps\n        this->m_matrix = boost::numeric::ublas::prod(s, t1);\n        this->m_matrix = boost::numeric::ublas::prod(t2, this->m_matrix);\n    }\n\n\n    template <typename W, typename D>\n    void set_transformation(W const& wx1, W const& wy1, W const& wx2, W const& wy2,\n                    D const& width, D const& height)\n    {\n        D px1 = 0;\n        D py1 = 0;\n        D px2 = width;\n        D py2 = height;\n\n        // Get the same type, but at least a double\n        typedef typename select_most_precise<D, double>::type type;\n\n\n        // Calculate appropriate scale, take min because whole box must fit\n        // Scale is in PIXELS/MAPUNITS (meters)\n        W wdx = wx2 - wx1;\n        W wdy = wy2 - wy1;\n        type sx = (px2 - px1) / boost::numeric_cast<type>(wdx);\n        type sy = (py2 - py1) / boost::numeric_cast<type>(wdy);\n\n        if (SameScale)\n        {\n            type scale = (std::min)(sx, sy);\n            sx = scale;\n            sy = scale;\n        }\n\n        // Calculate centerpoints\n        W wtx = wx1 + wx2;\n        W wty = wy1 + wy2;\n        W two = 2;\n        W wmx = wtx / two;\n        W wmy = wty / two;\n        type pmx = (px1 + px2) / 2.0;\n        type pmy = (py1 + py2) / 2.0;\n\n        set_transformation_point(wmx, wmy, pmx, pmy, sx, sy);\n\n        if (Mirror)\n        {\n            // Mirror in y-direction\n            M m(3,3);\n            m(0,0) = 1;   m(0,1) = 0;   m(0,2) = 0;\n            m(1,0) = 0;   m(1,1) = -1;  m(1,2) = 0;\n            m(2,0) = 0;   m(2,1) = 0;   m(2,2) = 1;\n\n            // Translate in y-direction such that it fits again\n            M y(3, 3);\n            y(0,0) = 1;   y(0,1) = 0;   y(0,2) = 0;\n            y(1,0) = 0;   y(1,1) = 1;   y(1,2) = height;\n            y(2,0) = 0;   y(2,1) = 0;   y(2,2) = 1;\n\n            // Calculate combination matrix in two steps\n            this->m_matrix = boost::numeric::ublas::prod(m, this->m_matrix);\n            this->m_matrix = boost::numeric::ublas::prod(y, this->m_matrix);\n        }\n    }\n};\n\n\n}} // namespace strategy::transform\n\n#if defined(_MSC_VER)\n#pragma warning(pop)  \n#endif\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MAP_TRANSFORMER_HPP\n", "meta": {"hexsha": "baf7216582eda61f38aa21f07ecba5e96129e8d7", "size": 5376, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/transform/map_transformer.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-02-24T14:48:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T21:37:26.000Z", "max_issues_repo_path": "boost/geometry/strategies/transform/map_transformer.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-02-25T20:45:09.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-28T18:05:45.000Z", "max_forks_repo_path": "boost/geometry/strategies/transform/map_transformer.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 24.0, "max_forks_repo_forks_event_min_datetime": "2017-11-01T03:30:09.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-28T21:57:33.000Z", "avg_line_length": 31.2558139535, "max_line_length": 91, "alphanum_fraction": 0.5770089286, "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.24152627893750805}}
{"text": "#include <stdio.h>\n#include <cfloat>\n#include <list>\n#include <vector>\n#include <math.h>\n#include <iostream>\n#include <algorithm>\n#include <numeric>\n#include <boost/algorithm/clamp.hpp>\n#include <random>\n#include \"third_party/eigen3/unsupported/Eigen/CXX11/Tensor\"\n#include \"unsupported/Eigen/CXX11/src/Tensor/TensorDeviceCuda.h\"\n//#include \"unsupported/Eigen/CXX11/Tensor\"\n#include \"tensorflow/core/framework/op.h\"\n#include \"tensorflow/core/framework/op_kernel.h\"\n#include \"tensorflow/core/framework/tensor_shape.h\"\n#include \"tensorflow/core/framework/common_shape_fns.h\"\n#include \"tensorflow/core/util/work_sharder.h\"\n#include \"bboxes.h\"\n#include \"wtoolkit.h\"\n#include \"wtoolkit_cuda.h\"\n#include <future>\n\nusing namespace tensorflow;\nusing namespace std;\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;\n/*\n * num_classes: 类别数，不含背景\n * gaussian_iou: 一般为0.7\n * gbboxes: groundtruth bbox, [B,N,4] 相对坐标\n * glabels: 标签[B,N], 背景为0\n * glength: 有效的groundtruth bbox数量\n * output_size: 输出图的大小[2]=(OH,OW) \n *\n * output:\n * output_heatmaps_c: center heatmaps [B,OH,OW,num_classes]\n * output_hw_offset: [B,OH,OW,4], (h,w,yoffset,xoffset)\n * output_mask: [B,OH,OW,2] (hw_mask,offset_mask)\n */\nREGISTER_OP(\"Center2BoxesEncode\")\n    .Attr(\"T: {float,double,int32,int64}\")\n\t.Attr(\"num_classes:int\")\n\t.Attr(\"gaussian_iou:float=0.7\")\n    .Input(\"gbboxes: T\")\n    .Input(\"glabels: int32\")\n    .Input(\"glength: int32\")\n    .Input(\"output_size: int32\")\n\t.Output(\"output_heatmaps_c:T\")\n\t.Output(\"output_hw_offset:T\")\n\t.Output(\"output_hw_offset_mask:T\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n            const auto input_shape0 = c->input(0);\n            const auto batch_size = c->Dim(input_shape0,0);\n            int num_classes;\n            c->GetAttr(\"num_classes\",&num_classes);\n            auto shape0 = c->MakeShape({batch_size,-1,-1,num_classes});\n            auto shape1 = c->MakeShape({batch_size,-1,-1,4});\n            auto shape2 = c->MakeShape({batch_size,-1,-1,2});\n\n\t\t\tc->set_output(0, shape0);\n\t\t\tc->set_output(1, shape1);\n\t\t\tc->set_output(2, shape2);\n\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device,typename T>\nclass Center2BoxesEncodeOp: public OpKernel {\n\tpublic:\n\t\texplicit Center2BoxesEncodeOp(OpKernelConstruction* context) : OpKernel(context) {\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"num_classes\", &num_classes_));\n\t\t\tOP_REQUIRES_OK(context, context->GetAttr(\"gaussian_iou\", &gaussian_iou_));\n\t\t}\n\n\t\tvoid Compute(OpKernelContext* context) override\n        {\n            TIME_THISV1(\"Center2BoxesEncode\");\n            const Tensor &_gbboxes    = context->input(0);\n            const Tensor &_glabels    = context->input(1);\n            const Tensor &_gsize      = context->input(2);\n            auto          gbboxes     = _gbboxes.template tensor<T,3>();\n            auto          glabels     = _glabels.template tensor<int,2>();\n            auto          gsize       = _gsize.template tensor<int,1>();\n            auto          output_size = context->input(3).template flat<int>().data();\n            const auto    batch_size  = _gbboxes.dim_size(0);\n\n            OP_REQUIRES(context, _gbboxes.dims() == 3, errors::InvalidArgument(\"box data must be 3-dimension\"));\n            OP_REQUIRES(context, _glabels.dims() == 2, errors::InvalidArgument(\"labels data must be 2-dimension\"));\n            OP_REQUIRES(context, _gsize.dims() == 1, errors::InvalidArgument(\"gsize data must be 1-dimension\"));\n\n            int           dims_4d0[4]            = {int(batch_size),output_size[0],output_size[1],num_classes_};\n            int           dims_4d1[4]            = {int(batch_size),output_size[0],output_size[1],4};\n            int           dims_4d2[4]            = {int(batch_size),output_size[0],output_size[1],2};\n            TensorShape  outshape0;\n            TensorShape  outshape1;\n            TensorShape  outshape2;\n            Tensor      *output_heatmaps_c  = NULL;\n            Tensor      *output_hw_offset      = NULL;\n            Tensor      *output_mask = NULL;\n\n            TensorShapeUtils::MakeShape(dims_4d0, 4, &outshape0);\n            TensorShapeUtils::MakeShape(dims_4d1, 4, &outshape1);\n            TensorShapeUtils::MakeShape(dims_4d2, 4, &outshape2);\n\n\n            OP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_heatmaps_c));\n            OP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_hw_offset));\n            OP_REQUIRES_OK(context, context->allocate_output(2, outshape2, &output_mask));\n\n            auto heatmaps_c  = output_heatmaps_c->template tensor<T,4>();\n            auto hw_offsets     = output_hw_offset->template tensor<T,4>();\n            auto o_mask = output_mask->template tensor<T,4>();\n            Eigen::Tensor<float,2,Eigen::RowMajor> max_probs(output_size[0],output_size[1]);\n\n            heatmaps_c.setZero();\n            hw_offsets.setZero();\n            o_mask.setZero();\n\n            for(auto i=0; i<batch_size; ++i) {\n                max_probs.setZero();\n                for(auto j=0; j<gsize(i); ++j) {\n                    const auto fytl = gbboxes(i,j,0)*(output_size[0]-1);\n                    const auto fxtl = gbboxes(i,j,1)*(output_size[1]-1);\n                    const auto fybr = gbboxes(i,j,2)*(output_size[0]-1);\n                    const auto fxbr = gbboxes(i,j,3)*(output_size[1]-1);\n                    const auto fyc = (fytl+fybr)/2;\n                    const auto fxc = (fxtl+fxbr)/2;\n                    const auto yc = int(fyc+0.5);\n                    const auto xc = int(fxc+0.5);\n                    const auto r0 = get_gaussian_radius(fybr-fytl,fxbr-fxtl,gaussian_iou_);\n                    const auto label = glabels(i,j);\n                    const auto h = fybr-fytl;\n                    const auto w = fxbr-fxtl;\n\n                    if(yc<0||xc<0||yc>=output_size[0]||xc>=output_size[1]) {\n                        cout<<\"ERROR bboxes data: \"<<gbboxes(i,j,0)<<\",\"<<gbboxes(i,j,1)<<\",\"<<gbboxes(i,j,2)<<\",\"<<gbboxes(i,j,3)<<endl;\n                        continue;\n                    }\n\n                    draw_gaussian(heatmaps_c,xc,yc,r0,i,label,5);\n                    draw_gaussianv2(max_probs,hw_offsets,xc,yc,r0,h,w,i,5);\n\n                    hw_offsets(i,yc,xc,2) = fyc-yc;\n                    hw_offsets(i,yc,xc,3) = fxc-xc;\n                    o_mask(i,yc,xc,1) = 1.0;\n                }\n                o_mask.chip(i,0).chip(0,2) = max_probs;\n            }\n        }\n        template<typename DT>\n        static void draw_gaussian(DT& data,int cx,int cy,float radius,int batch_index,int class_index,float delta=6,float k=1.0)\n        {\n            const auto width   = data.dimension(2);\n            const auto height  = data.dimension(1);\n            const auto xtl     = max(0,int(cx-radius));\n            const auto ytl     = max(0,int(cy-radius));\n            const auto xbr     = min<int>(width,int(cx+radius+1));\n            const auto ybr     = min<int>(height,int(cy+radius+1));\n            const auto sigma   = (2*radius+1)/delta;\n            const auto c_index = class_index-1;\n\n            for(auto x=xtl; x<xbr; ++x) {\n                for(auto y=ytl; y<ybr; ++y) {\n                    auto dx = x-cx;\n                    auto dy = y-cy;\n                    auto v = exp(-(dx*dx+dy*dy)/(2*sigma*sigma))*k;\n                    data(batch_index,y,x,c_index) = max(data(batch_index,y,x,c_index),v);\n                }\n            }\n        }\n        template<typename DT0,typename DT1>\n        static void draw_gaussianv2(DT0& data0,DT1& data1,int cx,int cy,float radius,float h,float w,int batch_index,int class_index,float delta=6,float k=1.0)\n        {\n            const auto width   = data1.dimension(2);\n            const auto height  = data1.dimension(1);\n            const auto xtl     = max(0,int(cx-radius));\n            const auto ytl     = max(0,int(cy-radius));\n            const auto xbr     = min<int>(width,int(cx+radius+1));\n            const auto ybr     = min<int>(height,int(cy+radius+1));\n            const auto sigma   = (2 *radius+1)/delta;\n            const auto c_index = class_index-1;\n\n            for(auto x=xtl; x<xbr; ++x) {\n                for(auto y=ytl; y<ybr; ++y) {\n                    auto dx = x-cx;\n                    auto dy = y-cy;\n                    auto v = exp(-(dx*dx+dy*dy)/(2*sigma*sigma))*k;\n                    if(data0(y,x)<v) {\n                        data0(y,x) = v;    \n                        data1(batch_index,y,x,0) = h;\n                        data1(batch_index,y,x,1) = w;\n                    }\n                }\n            }\n        }\n\tprivate:\n        int   num_classes_  = 80;\n        float gaussian_iou_ = 0.7f;\n};\nREGISTER_KERNEL_BUILDER(Name(\"Center2BoxesEncode\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), Center2BoxesEncodeOp<CPUDevice, float>);\n\nREGISTER_OP(\"Center2BoxesDecode\")\n    .Attr(\"T: {float,double,int32,int64}\")\n    .Attr(\"k:int\")\n    .Attr(\"threshold:float\")\n    .Input(\"heatmaps: T\")\n    .Input(\"offset: T\")\n    .Input(\"hw: T\")\n\t.Output(\"output_bboxes:T\")\n\t.Output(\"output_labels:int32\")\n\t.Output(\"output_probs:T\")\n\t.Output(\"output_index:int32\")\n\t.Output(\"output_lens:int32\")\n\t.SetShapeFn([](shape_inference::InferenceContext* c) {\n            int k;\n            c->GetAttr(\"k\",&k);\n            const auto input_shape0 = c->input(0);\n            const auto batch_size = c->Dim(input_shape0,0);\n            auto shape0 = c->MakeShape({batch_size,k,4});\n            auto shape1 = c->MakeShape({batch_size,k});\n            auto shape2 = c->MakeShape({batch_size});\n\n\t\t\tc->set_output(0, shape0);\n\t\t\tc->set_output(1, shape1);\n\t\t\tc->set_output(2, shape1);\n\t\t\tc->set_output(3, shape1);\n\t\t\tc->set_output(4, shape2);\n\t\t\treturn Status::OK();\n\t\t\t});\n\ntemplate <typename Device,typename T>\nclass Center2BoxesDecodeOp: public OpKernel {\n    private:\n        struct InterData{\n            InterData(int y,int x,int z,float s):y(y),x(x),z(z),score(s){}\n            float score;\n            int y,x,z;\n            bool operator<(const InterData& rhv)const{\n                return score<rhv.score;\n            }\n        };\n        struct Box\n        {\n            float ymin;\n            float xmin;\n            float ymax;\n            float xmax;\n            float prob;\n            int classes;\n            int index;\n        };\n    public:\n        explicit Center2BoxesDecodeOp(OpKernelConstruction* context) : OpKernel(context) {\n            OP_REQUIRES_OK(context, context->GetAttr(\"k\", &k_));\n            OP_REQUIRES_OK(context, context->GetAttr(\"threshold\", &threshold_));\n        }\n        void Compute(OpKernelContext* context) override\n        {\n            TIME_THISV1(\"Center2BoxesDecode\");\n            const Tensor &_heatmaps_c = context->input(0);\n            const Tensor &_offset_c   = context->input(1);\n            const Tensor &_hw         = context->input(2);\n\n            OP_REQUIRES(context, _heatmaps_c.dims() == 4, errors::InvalidArgument(\"heatmap data must be 4-dimension\"));\n            OP_REQUIRES(context, _offset_c.dims() == 4, errors::InvalidArgument(\"offset data must be 4-dimension\"));\n            OP_REQUIRES(context, _hw.dims() == 4, errors::InvalidArgument(\"hw data must be 4-dimension\"));\n\n            auto          heatmaps_c_r  = _heatmaps_c.template tensor<T,4>();\n            auto          offset_c    = _offset_c.template tensor<T,4>();\n            auto          hw          = _hw.template tensor<T,4>();\n\n            const auto batch_size = _heatmaps_c.dim_size(0);\n            vector<vector<Box>> res_boxes;\n\n            auto heatmaps_c = batch_sim_max_pool(heatmaps_c_r);\n\n            for(auto i=0; i<batch_size; ++i) {\n                auto c = get_top_k(heatmaps_c, i,k_);\n                auto tboxes = get_boxes(c,i,hw,offset_c);\n                res_boxes.push_back(std::move(tboxes));\n            }\n\n            auto         box_nr        = k_;\n            int          dims_3d[3]    = {int(batch_size),box_nr,4};\n            int          dims_2d[2]    = {int(batch_size),box_nr};\n            int          dims_1d[1]    = {int(batch_size)};\n            TensorShape  outshape0;\n            TensorShape  outshape1;\n            TensorShape  outshape2;\n            Tensor      *output_boxes  = NULL;\n            Tensor      *output_labels = NULL;\n            Tensor      *output_probs  = NULL;\n            Tensor      *output_indexs = NULL;\n            Tensor      *output_lens   = NULL;\n\n            TensorShapeUtils::MakeShape(dims_3d, 3, &outshape0);\n            TensorShapeUtils::MakeShape(dims_2d, 2, &outshape1);\n            TensorShapeUtils::MakeShape(dims_1d, 1, &outshape2);\n\n\n            OP_REQUIRES_OK(context, context->allocate_output(0, outshape0, &output_boxes));\n            OP_REQUIRES_OK(context, context->allocate_output(1, outshape1, &output_labels));\n            OP_REQUIRES_OK(context, context->allocate_output(2, outshape1, &output_probs));\n            OP_REQUIRES_OK(context, context->allocate_output(3, outshape1, &output_indexs));\n            OP_REQUIRES_OK(context, context->allocate_output(4, outshape2, &output_lens));\n\n            auto o_boxes = output_boxes->template tensor<T,3>();\n            auto o_labels = output_labels->template tensor<int,2>();\n            auto o_probs = output_probs->template tensor<T,2>();\n            auto o_indexs = output_indexs->template tensor<int,2>();\n            auto o_lens = output_lens->template tensor<int,1>();\n\n            o_boxes.setZero();\n            o_labels.setZero();\n            o_probs.setZero();\n            o_lens.setZero();\n            o_indexs.setZero();\n\n            for(auto i=0; i<batch_size; ++i) {\n                auto b_it = next(res_boxes.begin(),i);\n                for(auto j=0; j<b_it->size(); ++j) {\n                    auto& box = (*b_it)[j];\n                    o_boxes(i,j,0) = box.ymin;\n                    o_boxes(i,j,1) = box.xmin;\n                    o_boxes(i,j,2) = box.ymax;\n                    o_boxes(i,j,3) = box.xmax;\n                    o_labels(i,j) = box.classes;\n                    o_probs(i,j) = box.prob;\n                    o_indexs(i,j) = box.index;\n                }\n                o_lens(i) = b_it->size();\n            }\n        }\n\n        template<typename DT>\n        Eigen::Tensor<T,4,Eigen::RowMajor> batch_sim_max_pool(DT& data,int k=3,float neg_value = 0.0f) {\n            Eigen::Tensor<T,4,Eigen::RowMajor> res_data(Eigen::array<Eigen::Index,4>(data.dimensions()));\n            for(auto i=0; i<data.dimension(0); ++i) {\n                for(auto j=0; j<data.dimension(3); ++j) {\n                    Eigen::Tensor<T,2,Eigen::RowMajor> ldata = data.chip(i,0).chip(j,2);\n                    sim_max_pool(ldata,k,neg_value);\n                    res_data.chip(i,0).chip(j,2) = ldata;\n                }\n            }\n            return res_data;\n        }\n        template<typename DT>\n        void sim_max_pool(DT& data,int k=3,float neg_value = 0.0f) {\n\n            float buffer[k *k];\n            int   nr;\n            auto  H            = data.dimension(0);\n            auto  W            = data.dimension(1);\n            auto  max_i        = -1;\n            auto  max_j        = -1;\n            auto  max_v        = neg_value;\n\n            for(auto i=0; i<H; ++i) {\n                for(auto j=0; j<W; ++j) {\n                    auto i_min = max<int>(0,i-k);\n                    auto j_min = max<int>(0,j-k);\n                    auto i_max = min<int>(H-1,i+k+1);\n                    auto j_max = min<int>(W-1,j+k+1);\n\n                    max_i = -1; \n                    max_v = neg_value;\n                    for(auto ii=i_min; ii<i_max; ++ii) {\n                        for(auto jj=j_min; jj<j_max; ++jj) {\n                            if(data(ii,jj)>max_v) {\n                                max_i = ii;\n                                max_j = jj;\n                                max_v = data(ii,jj);\n                            }\n                        }\n                    }//end ii\n                    if((max_i != i) || (max_j != j)) {\n                        data(i,j) = neg_value;\n                    }\n                }\n            }\n        }\n\n        template<typename DT>\n            vector<InterData> get_top_k(const DT& heatmaps,int batch_index,int k) {\n                const auto H = heatmaps.dimension(1);\n                const auto W = heatmaps.dimension(2);\n                const auto C = heatmaps.dimension(3);\n                vector<InterData> res;\n                res.reserve(H*W/4);\n                for(auto y=0; y<H; ++y) {\n                    for(auto x=0; x<W; ++x) {\n                        for(auto z=0; z<C; ++z) {\n                            auto score = heatmaps(batch_index,y,x,z);\n                            if(score>threshold_)\n                                res.emplace_back(y,x,z,heatmaps(batch_index,y,x,z));\n                        }\n                    }\n                }\n                auto mid = res.begin()+min<int>(k,res.size());\n                partial_sort(res.begin(),mid,res.end(),[this](auto lhv,auto rhv){ return lhv.score>rhv.score;});\n                res.erase(mid,res.end());\n                return res;\n            }\n\n        template<typename DT0,typename DT1>\n        vector<Box> get_boxes(const vector<InterData>& c,int batch_index,const DT0& HW,const DT1& offset) {\n            vector<Box> boxes;\n            const auto H = HW.dimension(1);\n            const auto W = HW.dimension(2);\n\n            for(auto& id:c) {\n                auto cx = id.x+offset(batch_index,id.y,id.x,1);\n                auto cy = id.y+offset(batch_index,id.y,id.x,0);\n                auto hh = HW(batch_index,id.y,id.x,0)/2;\n                auto hw = HW(batch_index,id.y,id.x,1)/2;\n                Box box;\n                box.xmin = (cx-hw)/(W-1);\n                box.ymin = (cy-hh)/(H-1);\n                box.xmax = (cx+hw)/(W-1);\n                box.ymax = (cy+hh)/(H-1);\n                box.prob = id.score;\n                box.index = id.x+id.y*W;\n                box.classes = id.z+1;\n                boxes.push_back(box);\n            }\n            return boxes;\n        }\n        static inline pair<int,int> index_to_yx(int index,int H,int W) {\n            return make_pair(index/W,index%W);\n        }\n\tprivate:\n        int k_ = 0;\n        float threshold_ = 1e-3;\n};\nREGISTER_KERNEL_BUILDER(Name(\"Center2BoxesDecode\").Device(DEVICE_CPU).TypeConstraint<float>(\"T\"), Center2BoxesDecodeOp<CPUDevice, float>);\n", "meta": {"hexsha": "4a198b56b45678d77c9622a3d6e0bf236ed94a5f", "size": 18385, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tfop/center_net2_encode_decode.cc", "max_stars_repo_name": "vghost2008/wml", "max_stars_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-12-10T17:18:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T01:00:35.000Z", "max_issues_repo_path": "tfop/center_net2_encode_decode.cc", "max_issues_repo_name": "vghost2008/wml", "max_issues_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-08-25T16:16:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-10T05:21:19.000Z", "max_forks_repo_path": "tfop/center_net2_encode_decode.cc", "max_forks_repo_name": "vghost2008/wml", "max_forks_repo_head_hexsha": "d0c5a1da6c228e321ae59a563e9ac84aa66266ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-07T09:57:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-06T04:58:10.000Z", "avg_line_length": 41.9748858447, "max_line_length": 159, "alphanum_fraction": 0.5296165352, "num_tokens": 4694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.3486451217982255, "lm_q1q2_score": 0.24148624857257453}}
{"text": "#ifndef TVTML_FUNCTIONAL2D_HPP\n#define TVTML_FUNCTIONAL2D_HPP\n\n// Eigen includes\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n// video++ includes\n#include <vpp/vpp.hh>\n\n// system includes\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <vector>\n\nnamespace tvmtl{\n\n\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA>\nclass Functional<FIRSTORDER, disc, MANIFOLD, DATA>{\n\n    public:\n\t// Manifold typedefs and constants\n\tstatic const MANIFOLD_TYPE mf_type = MANIFOLD::MyType;\n\tstatic const int value_dim = MANIFOLD::value_dim; \n\tstatic const int manifold_dim = MANIFOLD::manifold_dim; \n\ttypedef typename MANIFOLD::scalar_type scalar_type;\n\ttypedef typename MANIFOLD::value_type value_type;\n\ttypedef typename MANIFOLD::ref_type ref_type;\n\ttypedef typename MANIFOLD::cref_type cref_type;\n\ttypedef typename MANIFOLD::deriv1_type deriv1_type;\n\ttypedef typename MANIFOLD::deriv2_type deriv2_type;\n\ttypedef typename MANIFOLD::restricted_deriv2_type restricted_deriv2_type;\n\ttypedef typename MANIFOLD::tm_base_type tm_base_type;\n\n\t// Data typedef and constants\n\tstatic const int img_dim = DATA::img_dim;\n\ttypedef typename DATA::storage_type img_type;\n\ttypedef typename DATA::weights_type weights_type;\n\ttypedef typename DATA::weights_mat weights_mat;\n\ttypedef typename DATA::inp_mat inp_mat;\n\n\ttypedef vpp::box_nbh2d<value_type,3,3> nbh_type;\n\n\t// Functional parameters and return types\n\tstatic const FUNCTIONAL_DISC disc_type;\n\ttypedef double param_type;\n\ttypedef double result_type;\n\t\n\t// Tangent space transformation matrix types\n\ttypedef vpp::imageNd<tm_base_type, img_dim> tm_base_mat_type; \n\t\n\t// Gradient and Hessian types\n\ttypedef Eigen::Matrix<scalar_type, Eigen::Dynamic, 1> gradient_type;\n\ttypedef vpp::imageNd<deriv2_type, img_dim> hessian_type;\n\ttypedef Eigen::SparseMatrix<scalar_type> sparse_hessian_type;\n\n\t//Constructor\n\tFunctional(param_type lambda, DATA& dat):\n\t    lambda_(lambda),\n\t    data_(dat)\n\t{\n\t    eps2_=1e-10;\n\t   static_assert(img_dim == 2, \"Dimension of data and functional must match!\");\n\t}\n\t\n\tvoid updateWeights();\n\n\tvoid updateTMBase();\n\t\n\t\n\t// Evaluation functions\n\tresult_type evaluateJ();\n\tvoid  evaluateDJ();\n\tvoid  evaluateHJ();\n\t\n\ttemplate <class IMG>\n\tvoid output_img(const IMG& img, const char* filename) const;\n\ttemplate <class IMG>\n\tvoid output_matval_img(const IMG& img, const char* filename) const;\n\n\t// Getter and Setter \n\tinline param_type getlambda() const { return lambda_; }\n\tinline void setlambda(param_type lam) { lambda_=lam; }\n\tinline param_type geteps2() const { return eps2_; }\n\tinline void seteps2(param_type eps) { eps2_=eps; }\n\n\tinline const weights_mat& getweightsX() const { return weightsX_; }\n\tinline const weights_mat& getweightsY() const { return weightsY_; }\n\n\tinline const gradient_type& getDJ() const { return DJ_; }\n\tinline const sparse_hessian_type& getHJ() const { return HJ_; }\n\tinline const tm_base_mat_type& getT() const { return T_; }\n\n    private:\n\tDATA& data_;\n\n\tparam_type lambda_, eps2_;\n\tweights_mat weightsX_, weightsY_;\n\n\ttm_base_mat_type T_;\n\tgradient_type DJ_;\n\tsparse_hessian_type HJ_;\n};\n\n\n//--------Implementation FIRSTORDER-----/\n\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\nconst FUNCTIONAL_DISC Functional<FIRSTORDER, disc, MANIFOLD, DATA >::disc_type = disc;\n\n// Update the Weights 2D\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA >::updateWeights(){\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t Update Weights...\" << std::endl;\n    #endif\n\n    int nr = data_.img_.nrows();\n    int nc = data_.img_.ncols();\n    \n    // Subimage boxes\n    vpp::box2d without_last_col(vpp::vint2(0,0), vpp::vint2(nr-1, nc-2)); // subdomain without last column\n    vpp::box2d without_first_col(vpp::vint2(0,1), vpp::vint2(nr-1, nc-1)); // subdomain without first column\n    vpp::box2d without_last_row(vpp::vint2(0,0), vpp::vint2(nr-2, nc-1)); // subdomain without last row\n    vpp::box2d without_first_row(vpp::vint2(1,0), vpp::vint2(nr-1, nc-1)); // subdomain without first row\n\n    weightsX_ = weights_mat(data_.img_.domain());\n    weightsY_ = weights_mat(data_.img_.domain());\n\n    auto calc_dist = [&] (weights_type& w, const value_type i, const value_type n) {\n\tw = MANIFOLD::dist_squared(i, n);\n    };\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Horizontal neighbours \" << std::endl;\n    #endif\n\n    // Horizontal Neighbours\n    vpp::fill(weightsX_, 0.0);\n    vpp::pixel_wise(weightsX_ | without_last_col, data_.img_ | without_last_col, data_.img_ | without_first_col )(/*vpp::_no_threads*/) | calc_dist;\n\n    #ifdef TV_FUNC_DEBUG \n\tdata_.output_weights(weightsX_,\"XWeights.csv\");\n    #endif\t\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Vertical neighbours\" << std::endl;\n    #endif\n\n    // Vertical Neighbours\n    vpp::fill(weightsY_, 0.0);\n    vpp::pixel_wise(weightsY_ | without_last_row, data_.img_ | without_last_row, data_.img_ | without_first_row )(/*vpp::_no_threads*/) | calc_dist;\n\n    #ifdef TV_FUNC_DEBUG \n\tdata_.output_weights(weightsY_,\"YWeights.csv\");\n    #endif\t\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Reweighting\" << std::endl;\n    #endif\n\n    if(disc==ISO){\n\tauto g =  [&] (const weights_type& ew, weights_type& x, weights_type& y) { x = ew / std::sqrt(x+y+eps2_); y = x; };\n\tvpp::pixel_wise(data_.edge_weights_, weightsX_, weightsY_) | g ;\n    }\n    else{\n\tauto g =  [&] (const weights_type& ew, weights_type& w) { w = ew / std::sqrt(w+eps2_); };\n\tvpp::pixel_wise(data_.edge_weights_, weightsX_) | g ;\n\tvpp::pixel_wise(data_.edge_weights_, weightsY_) | g ;\n    }\n}\n\n// Update the Tangent space ONB\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA >::updateTMBase(){\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tUpdate tangent space basis...\" << std::endl;\n    #endif\n\n\n   tm_base_mat_type T(data_.img_.domain());\n   vpp::pixel_wise(T, data_.img_)(/*vpp::_no_threads*/) | [&] (tm_base_type& t, const value_type& i) { MANIFOLD::tangent_plane_base(i,t); };\n   T_=T;\n    \n    #ifdef TV_FUNC_DEBUG \n        output_img(T_,\"T.csv\");\n    #endif\n}\n\n// Evaluation of J\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\ntypename Functional<FIRSTORDER, disc, MANIFOLD, DATA >::result_type Functional<FIRSTORDER, disc, MANIFOLD, DATA >::evaluateJ(){\n\n    // sum d^2(img, img_noise)\n    result_type J1, J2;\n    J1 = J2 = 0.0;\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tFunctional evaluation...\" << std::endl;\n\tstd::cout << \"\\t\\t...Fidelity part\" << std::endl;\n    #endif\n\n\n    if(data_.doInpaint()){\n\tauto f = [] (const value_type& i, const value_type& n, const bool inp ) { return MANIFOLD::dist_squared(i,n)*(1-inp); };\n\tJ1 = vpp::sum(vpp::pixel_wise(data_.img_, data_.noise_img_, data_.inp_) | f);\n    }\n    else{\n\tauto f = [] (const value_type& i, const value_type& n) { return MANIFOLD::dist_squared(i,n); };\n\tJ1 = vpp::sum(vpp::pixel_wise(data_.img_, data_.noise_img_)(/*vpp::_no_threads*/)| f);\n    }\n\n\tupdateWeights();\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...TV part.\" << std::endl;\n    #endif\n\n    if(disc==ISO)\n\tJ2 = vpp::sum( vpp::pixel_wise(weightsX_) | [&] (const weights_type& w) {return 1.0/w;} );\n    else\n\tJ2 = vpp::sum( vpp::pixel_wise(weightsX_, weightsY_) | [&] (const weights_type& wx, const weights_type& wy) {return 1.0/wx +1.0/wy;} );\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"J1: \" << J1 << std::endl;\n\tstd::cout << \"J2: \" << J2 << std::endl;\n    #endif\n\n    return 0.5 * J1 + lambda_* J2;\n}\n\n// Evaluation of J'\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA >::evaluateDJ(){\n\n    #ifdef TV_FUNC_WONES_DEBUG \n\toutput_img(data_.img_,\"img.csv\");\n\tvpp::fill(weightsX_, 1.0); // Reset for Debugging\n\tvpp::fill(weightsY_, 1.0); // Reset for Debugging\n    #endif\n\n    img_type grad = img_type(data_.img_.domain());\n    int nr = data_.img_.nrows();\n    int nc = data_.img_.ncols();\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tGradient evaluation...\" << std::endl;\n\tstd::cout << \"\\t\\t...Fidelity part\" << std::endl;\n    #endif\n    //GRADIENT OF FIDELITY TERM\n    if(data_.doInpaint()){\n\tauto f = [] (value_type& g, const value_type& i, const value_type& n, const bool inp ) { MANIFOLD::deriv1x_dist_squared(i,n,g); g*=(1-inp); };\n\tvpp::pixel_wise(grad, data_.img_, data_.noise_img_, data_.inp_) | f;\n    }\n    else{\n\tauto f = [] (value_type& g, const value_type& i, const value_type& n) { MANIFOLD::deriv1x_dist_squared(i,n,g); };\n\tvpp::pixel_wise(grad, data_.img_, data_.noise_img_)(/*vpp::_no_threads*/) | f;\n    }\n    \n    //GRADIENT OF TV TERM\n\n    // Subimage boxes\n    vpp::box2d without_last_col(vpp::vint2(0,0), vpp::vint2(nr-1, nc-2)); // subdomain without last column\n    vpp::box2d without_first_col(vpp::vint2(0,1), vpp::vint2(nr-1, nc-1)); // subdomain without first column\n    vpp::box2d without_last_row(vpp::vint2(0,0), vpp::vint2(nr-2, nc-1)); // subdomain without last row\n    vpp::box2d without_first_row(vpp::vint2(1,0), vpp::vint2(nr-1, nc-1)); // subdomain without first row\n\n    auto calc_first_arg_deriv = [&] (value_type& x, const weights_type& w, const value_type& i, const value_type& n) { MANIFOLD::deriv1x_dist_squared(i, n, x); x *= w; };\n    auto calc_second_arg_deriv = [&] (value_type& y, const weights_type& w, const value_type& i, const value_type& n) { MANIFOLD::deriv1y_dist_squared(i, n, y); y *= w; };\n    auto add_to_gradient = [&] (value_type& g, const value_type& d) { g+=d*lambda_; };\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tGradient evaluation...\" << std::endl;\n\tstd::cout << \"\\t\\t...TV part\" << std::endl;\n\tstd::cout << \"\\t\\t...-> XD1\" << std::endl;\n    #endif\n    // Horizontal derivatives and weighting\n    // ... w.r.t. to first argument\n    { // Temporary image XD1 is deallocated after this scope \n\timg_type XD1 = img_type(without_last_col);\n\tvpp::pixel_wise(XD1, weightsX_ | without_last_col, data_.img_ | without_last_col, data_.img_ | without_first_col) | calc_first_arg_deriv;\n\t#ifdef TV_FUNC_DEBUG \n\t    output_img(XD1,\"XD1.csv\");\n\t#endif\n\tauto grad_subX1  = grad | without_last_col;\n\tvpp::pixel_wise(grad_subX1, XD1) | add_to_gradient;\n    } \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...-> XD2\" << std::endl;\n    #endif\n    // ... w.r.t. second argument\n    {\n\timg_type XD2 = img_type(without_last_col);\n\tvpp::pixel_wise(XD2, weightsX_ | without_last_col, data_.img_ | without_last_col, data_.img_ | without_first_col) | calc_second_arg_deriv;\n\t#ifdef TV_FUNC_DEBUG \n\t    output_img(XD2,\"XD2.csv\");\n\t#endif\n\tauto grad_subX2  = grad | without_first_col;\n\tvpp::pixel_wise(grad_subX2, XD2) | add_to_gradient;\n    }\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...-> YD1\" << std::endl;\n    #endif\n    // Vertical derivatives and weighting\n    // ... w.r.t. first argument\n    {\n\timg_type YD1 = img_type(without_last_row);\n\tvpp::pixel_wise(YD1, weightsY_ | without_last_row, data_.img_ | without_last_row, data_.img_ | without_first_row) | calc_first_arg_deriv;\n\t#ifdef TV_FUNC_DEBUG \n\t    output_img(YD1,\"YD1.csv\");\n\t#endif\n\tauto grad_subY1  = grad | without_last_row;\n\tvpp::pixel_wise(grad_subY1, YD1) | add_to_gradient;\n    }\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...-> YD2\" << std::endl;\n    #endif\n    // ... w.r.t second argument\n    {\n\timg_type YD2 = img_type(without_last_row);\n\tvpp::pixel_wise(YD2, weightsY_ | without_last_row, data_.img_ | without_last_row, data_.img_ | without_first_row) | calc_second_arg_deriv;\n\t#ifdef TV_FUNC_DEBUG \n\t    output_img(YD2,\"YD2.csv\");\n\t#endif\n        auto grad_subY2  = grad | without_first_row;\n        vpp::pixel_wise(grad_subY2, YD2) | add_to_gradient;\n    }\n\n    \n    #ifdef TV_FUNC_DEBUG \n\toutput_img(grad,\"grad.csv\");\n    #endif\n\n    DJ_ = gradient_type::Zero(nr*nc*manifold_dim); \n    \n    // flatten rowwise\n    //vpp::pixel_wise(grad, grad.domain()) | [&] (value_type& p, vpp::vint2 coord) { DJ_.segment(3*(nc*coord[0]+coord[1]), value_dim) = p; };\n    \n    // Apply tangent space restriction and flatten colwise (as in Matlab code)\n    updateTMBase();\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Local to global insert\" << std::endl;\n    #endif\n    auto insert2grad = [&] (const tm_base_type& t, const value_type& p, const vpp::vint2 coord) { \n\tDJ_.segment(manifold_dim * (coord[0] + nr * coord[1]), manifold_dim) = t.transpose() * Eigen::Map<const Eigen::VectorXd>(p.data(), p.size()); \n\t//DJ_.segment(manifold_dim * (coord[0] + nr * coord[1]), manifold_dim) = t.transpose()*p; //remove: does not work for matrix valued pixel\n    };\n\n    vpp::pixel_wise(T_, grad, grad.domain()) | insert2grad; \n\n    #ifdef TV_FUNC_DEBUG \n\tstd::fstream f;\n\tf.open(\"gradJ.csv\",std::fstream::out);\n\tf << DJ_;\n\tf.close();\n    #endif\n}\n\n// Evaluation of Hessian J\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA >::evaluateHJ(){\n    #ifdef TV_FUNC_WONES_DEBUG \n\tvpp::fill(weightsX_, 1.0); // Reset for Debugging\n\tvpp::fill(weightsY_, 1.0); // Reset for Debugging\n    #endif\n\n    hessian_type hessian(data_.img_.domain());\n    int nr = data_.img_.nrows();\n    int nc = data_.img_.ncols();\n    int sparsedim = nr*nc*manifold_dim;\n    \n        \n    //HESSIAN OF FIDELITY TERM\n     #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tHessian evaluation...\" << std::endl;\n\tstd::cout << \"\\t\\t...Fidelity part\" << std::endl;\n    #endif\n\n    sparse_hessian_type HF(sparsedim,sparsedim);\n\n    //HF.reserve(Eigen::VectorXi::Constant(nc,manifold_dim));\n    typedef Eigen::Triplet<double> Trip;\n    std::vector<Trip> triplist;\n    triplist.reserve(sparsedim*manifold_dim);\n\t\n    if(data_.doInpaint()){\n\tauto f = [] (deriv2_type& h, const value_type& i, const value_type& n, const bool inp ) { MANIFOLD::deriv2xx_dist_squared(i,n,h); h*=(1-inp); };\n\tvpp::pixel_wise(hessian, data_.img_, data_.noise_img_, data_.inp_) | f;\n    }\n    else{\n\tauto f = [] (deriv2_type& h, const value_type& i, const value_type& n) { MANIFOLD::deriv2xx_dist_squared(i,n,h); };\n\tvpp::pixel_wise(hessian, data_.img_, data_.noise_img_) | f;\n    }\n    \n    #ifdef TV_FUNC_DEBUG\n\toutput_matval_img(hessian,\"HF0.csv\");\n    #endif\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Local to global insert\" << std::endl;\n    #endif\n   //TODO: Check whether all 2nd-derivative matrices are symmetric s.t. only half the matrix need to be traversed. e.g. local_col=local_row instead of 0\n    auto local2globalInsert = [&](const tm_base_type& t, const deriv2_type& h, const vpp::vint2 coord) { \n\tint pos = manifold_dim * (coord[0] + nr * coord[1]); // columnwise flattening\n\trestricted_deriv2_type ht=t.transpose()*h*t;\n\tfor(int local_row = 0; local_row<ht.rows(); local_row++)\n\t    for(int local_col = local_row; local_col < ht.cols(); local_col++){\n\t\tscalar_type e = ht(local_row, local_col);\n\t\tif(e!=0){\n\t\t    int global_row = pos + local_row;\n\t\t    int global_col = pos + local_col;\n\t\t    triplist.push_back(Trip(global_row,global_col,e));\n\t\t    if(global_row != global_col)\n\t\t\ttriplist.push_back(Trip(global_col,global_row,e));\n\t\t    //HF.insert(global_row, global_col) = e;\n\t\t    //if(global_row != global_col)\n\t\t    //\tHF.insert(global_col, global_row) = e;\n\t\t    }\n\t    }\n    };\n\n    vpp::pixel_wise(T_, hessian, hessian.domain())(vpp::_no_threads) | local2globalInsert;\n     #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Triplet list created\" << std::endl;\n    #endif\n    HF.setFromTriplets(triplist.begin(),triplist.end());              \n    HF.makeCompressed();\n\n    //HESSIAN OF TV TERM\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tHessian evaluation...\" << std::endl;\n\tstd::cout << \"\\t\\t...TV part\" << std::endl;\n    #endif\n\n    sparse_hessian_type HTV(sparsedim,sparsedim);\n    \n    //HTV.reserve(Eigen::VectorXi::Constant(nc,5*manifold_dim));\n    triplist.clear();\n    triplist.reserve(3*sparsedim*manifold_dim);\n\n    // Subimage boxes\n    vpp::box2d without_last_col(vpp::vint2(0,0), vpp::vint2(nr-1, nc-2)); // subdomain without last column\n    vpp::box2d without_first_col(vpp::vint2(0,1), vpp::vint2(nr-1, nc-1)); // subdomain without first column\n    vpp::box2d without_last_row(vpp::vint2(0,0), vpp::vint2(nr-2, nc-1)); // subdomain without last row\n    vpp::box2d without_first_row(vpp::vint2(1,0), vpp::vint2(nr-1, nc-1)); // subdomain without first row\n\n    auto calc_xx_der = [&] (deriv2_type& x, const weights_type& w, const value_type& i, const value_type& n) { MANIFOLD::deriv2xx_dist_squared(i, n, x); x*=w; };\n    auto calc_xy_der = [&] (deriv2_type& xy, const weights_type& w, const value_type& i, const value_type& n) { MANIFOLD::deriv2xy_dist_squared(i, n, xy); xy*=w; };\n    auto calc_yy_der = [&] (deriv2_type& y, const weights_type& w, const value_type& i, const value_type& n) { MANIFOLD::deriv2yy_dist_squared(i, n, y); y*=w; };\n    auto add_to_hessian =  [&] (deriv2_type& h, const deriv2_type& d) { h += d; };\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->XD11\" << std::endl;\n    #endif\n    // Horizontal Second Derivatives and weighting\n    // ... w.r.t. first arguments\n    { // Temporary image XD11 is deallocated after this scope\n\thessian_type XD11(without_last_col);\n        vpp::pixel_wise(XD11, weightsX_ | without_last_col, data_.img_ | without_last_col, data_.img_ | without_first_col) | calc_xx_der;\n        #ifdef TV_FUNC_DEBUG \n\t\toutput_matval_img(XD11,\"XD11.csv\");\n        #endif\n\tauto hess_subX11  = hessian | without_last_col;\n\tvpp::pixel_wise(hess_subX11, XD11) | [&] (deriv2_type& h, const deriv2_type& d) { h=d; };\n    }\n\t#pragma omp parallel for\n\tfor(int r=0; r< nr; r++) \n\t    hessian(r,nc-1)=deriv2_type::Zero(); // set last column to zero\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->XD22\" << std::endl;\n    #endif\n    //... w.r.t. second arguments\n    {\n\thessian_type XD22(without_last_col);\n        vpp::pixel_wise(XD22, weightsX_ | without_last_col, data_.img_ | without_last_col, data_.img_ | without_first_col) | calc_yy_der;\n\t#ifdef TV_FUNC_DEBUG \n\t    output_matval_img(XD22,\"XD22.csv\");\n\t#endif\n\tauto hess_subX22  = hessian | without_first_col;\n\tvpp::pixel_wise(hess_subX22, XD22) | add_to_hessian;\n    }\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->YD11\" << std::endl;\n    #endif\n    // Vertical Second Derivatives weighting\n    //... w.r.t. first arguments\n    {\n\thessian_type YD11(without_last_row);\n        vpp::pixel_wise(YD11, weightsY_ | without_last_row, data_.img_ | without_last_row, data_.img_ | without_first_row) | calc_xx_der;\n\t#ifdef TV_FUNC_DEBUG \n\t    output_matval_img(YD11,\"YD11.csv\");\n\t#endif\n\tauto hess_subY11  = hessian | without_last_row;\n\tvpp::pixel_wise(hess_subY11, YD11) | add_to_hessian;\n    }\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->YD22\" << std::endl;\n    #endif\n    //... w.r.t. second arguments\n    {\n\thessian_type YD22(without_last_row);\n        vpp::pixel_wise(YD22, weightsY_ | without_last_row, data_.img_ | without_last_row, data_.img_ | without_first_row) | calc_yy_der;\n\t#ifdef TV_FUNC_DEBUG \n\t    output_matval_img(YD22,\"YD22.csv\");\n\t#endif\n\tauto hess_subY22  = hessian | without_first_row;\n\tvpp::pixel_wise(hess_subY22, YD22) | [&] (deriv2_type& h, const deriv2_type& d) { h+=d; };\n    }\n    \n    #ifdef TV_FUNC_DEBUG\n        output_matval_img(T_, \"T.csv\");\n\toutput_matval_img(hessian, \"NonMixedHessian.csv\");\n    #endif\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Local to global insert\" << std::endl;\n    #endif\n    // Insert elementwise into sparse Hessian\n    // NOTE: Eventually make single version for both cases, including an offset\n    // --> additional parameters sparse_mat, offset\n    int row_offset=0;\n    int col_offset=0;\n    auto local2globalInsertHTV = [&](const tm_base_type& t1, const tm_base_type& t2, const deriv2_type& h, const vpp::vint2 coord) { \n\tint pos = manifold_dim*(coord[0]+nr*coord[1]); // columnwise flattening\n\trestricted_deriv2_type ht = t1.transpose()*h*t2;\n\t     #ifdef TV_FUNC_DEBUG_VERBOSE2\n\t\tstd::cout << \"\\n\\nPos: \" << pos << \" coord[0]=\" << coord[0] << \" coord[1]=\" << coord[1] << std::endl;\n\t\tstd::cout << \"\\t\\tT_left:\" << std::endl;\n\t\tstd::cout << t1 << std::endl;\n\t\tstd::cout << \"\\t\\tHbig:\" << std::endl;\n\t\tstd::cout << h << std::endl;\n\t\tstd::cout << \"\\t\\tT_right:\" << std::endl;\n\t\tstd::cout << t2 << std::endl;\n\t\tstd::cout << \"\\t\\tHsmall:\" << std::endl;\n\t\tstd::cout << ht << std::endl;\n\t    #endif\n\tfor(int local_row=0; local_row<ht.rows(); local_row++)\n\t    for(int local_col=0; local_col<ht.cols(); local_col++){\n\t\tscalar_type e = ht(local_row, local_col);\n\t\tif(e!=0){\n\t\t    int global_row = pos + row_offset + local_row;\n\t\t    int global_col = pos + col_offset + local_col;\n\t\t    triplist.push_back(Trip(global_row,global_col,e));\n\t\t    if(row_offset > 0 || col_offset > 0)\n\t\t\ttriplist.push_back(Trip(global_col,global_row,e));\n\t\t    //HTV.insert(global_row, global_col) = e;\n\t\t    //if(global_col != global_row)\n\t\t    //\tHTV.insert(global_col, global_row)  = e;\n\t\t}\n\t    }\n    };\n    vpp::pixel_wise(T_, T_, hessian, hessian.domain())(vpp::_no_threads) | local2globalInsertHTV;\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->XD12\" << std::endl;\n    #endif              \n    // Horizontal Second Derivatives and weighting\n    // ... w.r.t. first and second arguments \n    {\n\thessian_type XD12(without_last_col);\n\tvpp::pixel_wise(XD12, weightsX_ | without_last_col, data_.img_ | without_last_col, data_.img_ | without_first_col ) | calc_xy_der;\n\t#ifdef TV_FUNC_DEBUG \n\t    output_matval_img(XD12,\"XD12.csv\");\n\t#endif\n\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Local to global insert:\" << std::endl;\n\t#endif\n\t// Offsets for upper nyth subdiagonal\n\trow_offset=0;\n\tcol_offset=manifold_dim*nr;\n\tvpp::pixel_wise(T_ | without_last_col, T_ | without_first_col, XD12, XD12.domain())(vpp::_no_threads) | local2globalInsertHTV;\n    }\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->YD12\" << std::endl;\n    #endif\n    // Vertical Second Derivatives and weighting\n    //... w.r.t. second arguments\n    {\n\thessian_type YD12(data_.img_.domain());\n\tvpp::pixel_wise(YD12 | without_last_row, weightsY_ | without_last_row, data_.img_ | without_last_row, data_.img_ | without_first_row) | calc_xy_der;\n\t#ifdef TV_FUNC_DEBUG \n\t    output_matval_img(YD12,\"YD12.csv\");\n        #endif\n\t\n\t//Set last row to zero\n\tderiv2_type *lastrow = &YD12(nr-1,0);\n\tfor(int c=0; c< nc; c++) \n\t    lastrow[c]=deriv2_type::Zero();\n\n\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Local to global insert:\" << std::endl;\n\t#endif\n\t// Offsets for first upper subdiagonal\n\trow_offset=0;\n\tcol_offset=manifold_dim;\n\tvpp::pixel_wise(T_ | without_last_row, T_ | without_first_row, YD12 | without_last_row, without_last_row)(vpp::_no_threads) | local2globalInsertHTV;\n\t\n\t//Manually insert last row\n\tfor(int c=0; c<nc-1; c++) \n\t    local2globalInsertHTV(T_(nr-1,c), T_(nr-1,c + 1), YD12(nr-1,c), vpp::vint2(nr-1, c));\n\t    //local2globalInsertHTV(firstrow[c], lastrow[c], vpp::vint2(nr-1,c));\n\t\n\tHTV.setFromTriplets(triplist.begin(),triplist.end());              \n\tHTV.makeCompressed();\n\ttriplist.clear();\n    }\n       \t\n\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Combine Fidelity and TV parts:\" << std::endl;\n\t#endif \n\t\n\tHJ_= HF + lambda_*HTV;\n\t\n\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Output Hessian (stats):\" << std::endl;\n\t#endif\n    #ifdef TV_FUNC_DEBUG\n\tif (sparsedim<200){\n\t    if(sparsedim<70){\n\t\tstd::cout << \"\\nFidelity\\n\" << HF << std::endl; \n\t\tstd::cout << \"\\nTV\\n\" << HTV << std::endl; \n\t\tstd::cout << \"\\nHessian\\n\" << HJ_ << std::endl; \n\t    }\n\n\t    std::fstream f;\n\t    f.open(\"H.csv\",std::fstream::out);\n\t    Eigen::IOFormat CommaInitFmt(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \", \", \"\", \"\", \"\", \"\");\n\t    //f << HJ_.format(CommaInitFmt).;\n\t    f << HJ_;\n\t    f.close();\n\n\t}\n\telse{\n\t    std::cout << \"\\nFidelity Non-Zeros: \" << HJ_.nonZeros() << std::endl; \n\t    std::cout << \"\\nTV Non-Zeros: \" << HJ_.nonZeros() << std::endl; \n\t    std::cout << \"\\nHessian Non-Zeros: \" << HJ_.nonZeros() << std::endl; \n\t}\n    // Test Solver:\n/*\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Test Solve\" << std::endl;\n\t#endif\n\tgradient_type x;\n    \n\tEigen::SparseLU<sparse_hessian_type> solver;\n\tsolver.analyzePattern(HJ_);\n\tsolver.factorize(HJ_);\n\tx = solver.solve(DJ_);\n\n\tstd::fstream f;\n\tf.open(\"Sol.csv\",std::fstream::out);\n\tf << x;\n\tf.close();*/\n    #endif\n\n}\n\n\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\ntemplate < class IMG >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA >::output_img(const IMG& img, const char* filename) const{\n    int nr = img.nrows();\n    int nc = img.ncols();\n\n    std::fstream f;\n    f.open(filename, std::fstream::out);\n    Eigen::IOFormat CommaInitFmt(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \", \", \"\", \"\", \"\", \"\");\n    for (int r=0; r<nr; r++){\n\tconst auto* cur = &img(r,0);\n\tfor (int c=0; c<nc; c++){\n\t    f << cur[c].format(CommaInitFmt);\n\t    if(c != nc-1) f << \",\";\n\t}\n\tf <<  std::endl;\n    }\n    f.close();\n}\n\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\ntemplate < class IMG >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA >::output_matval_img(const IMG& img, const char* filename) const{\n    int nr = img.nrows();\n    int nc = img.ncols();\n\n    std::fstream f;\n    f.open(filename, std::fstream::out);\n    Eigen::IOFormat CommaInitFmt(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \", \", \"\", \"\", \"\", \"\\n\");\n    for (int r=0; r<nr; r++){\n\tconst auto* cur = &img(r,0);\n\tfor (int c=0; c<nc; c++)\n\t    f << cur[c].format(CommaInitFmt);\n    }\n    f.close();\n}\n\n}// end namespace tvtml\n\n#endif\n", "meta": {"hexsha": "9b942e92d2ed17505a6bbe983348e33142bf7004", "size": 25729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/functional2d.hpp", "max_stars_repo_name": "pdebus/MTVMTL", "max_stars_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T12:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T05:11:01.000Z", "max_issues_repo_path": "mtvmtl/core/functional2d.hpp", "max_issues_repo_name": "pdebus/MTVMTL", "max_issues_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mtvmtl/core/functional2d.hpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4433427762, "max_line_length": 171, "alphanum_fraction": 0.6717322865, "num_tokens": 7832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.24145897733696844}}
{"text": "#include <unordered_map>\n#include <memory>\n#include <iterator>\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include \"./parser.hpp\"\n#include \"./lattice.hpp\"\n#include \"./site.hpp\"\n#include \"./search_equiv_sites.hpp\"\n#include \"./myhash.hpp\"\n#include \"./myindex.hpp\"\n#include \"./input.hpp\"\n#include \"./metroconf.hpp\"\n\nusing allclusters = std::vector<std::vector<std::vector<std::vector<int>>>>;\n\nvoid dispInput(std::shared_ptr<Input> in){\n\t//  [INPUT]\n\tstd::cout << \"MAXBODY     : \" << in->getDataByString(\"MAXBODY\") << std::endl;\n\tstd::cout << \"TRUNCATION  : \" << in->getDataByString(\"TRUNCATION\") << std::endl;\n\tstd::cout << \"SPINCE      : \" << in->getDataByString(\"SPINCE\") << std::endl;\n\tstd::cout << \"SPINPOSCAR  : \" << in->getDataByString(\"SPINPOSCAR\") << std::endl;\n\t//  [OPTION]\n\tstd::cout << \"PAIRTRUNC   : \" << in->getDataByString(\"PAIRTRUNC\")  << std::endl;\n\tstd::cout << \"TRITRUNC    : \" << in->getDataByString(\"TRITRUNC\") << std::endl;\n\tstd::cout << \"QUADTRUNC   : \" << in->getDataByString(\"QUADTRUNC\") << std::endl;\n\tstd::cout << \"CLUSTEROUT  : \" << in->getDataByString(\"CLUSTEROUT\") << std::endl;\n\tstd::cout << \"CORRDUMP    : \" << in->getDataByString(\"CORRDUMP\") << std::endl;\n}\n\nvoid showResult(int is_corrdump, const std::shared_ptr<Input>& in){\n\n\tconst ParseClusterOut parse_cluster_out(\"./cluster.out\");\n\n\tif( is_corrdump>0 ){\n\t\tConf2corr PoscarSpin(\"./poscar.spin\", in, parse_cluster_out.getLabel(), parse_cluster_out.getCluster());\n\n\t\tfor(int i=0; i<PoscarSpin.getSpins().size(); ++i ){\n\t\t\tbool isin = PoscarSpin.isInNthNearestNeighborPair(i);\n\t\t\tif( isin ) {std::cout << std::endl; return;}\n\t\t}\n\n\t\tfor(const auto& corrs : PoscarSpin.getCorrelationFunctions() ) {\n\t\t\tfor(const auto& corr : corrs){\n\t\t\t\tstd::cout << corr << \" \";\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t}\n\t} else {\n\t\tconst ParseEcicar ecicar(\"./ecicar\");\n\t\tstd::shared_ptr<allclusters> pall_clusters_dummy(new allclusters());\n\t\tfor(int i=0; i<parse_cluster_out.getCluster()->size(); ++i){\n\t\t\tfor(const auto eci : ecicar.getEci() ){\n\t\t\t\tif( (i+1) == eci.first ) {\n\t\t\t\t\tpall_clusters_dummy->push_back((*(parse_cluster_out.getCluster()))[i]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tMetroconf PoscarSpin(\"./poscar.spin\", in, parse_cluster_out.getLabel(), pall_clusters_dummy, ecicar.getEci(), nullptr, nullptr);\n\t\tPoscarSpin.setTotalEnergy();\n\t\tauto compositions = PoscarSpin.getCompositions();\n\n\t\tfor(int i=0; i<PoscarSpin.getSpins().size(); ++i ){\n\t\t\tbool isin = PoscarSpin.isInNthNearestNeighborPair(i);\n\t\t\tif( isin ) {std::cout << std::endl; return;}\n\t\t}\n\n\t\tfor(const auto c : compositions) std::cout << c << \" \";\n\t\tstd::cout << PoscarSpin.getTotalEnergy() << std::endl;\n\t}\n\n}\n\n\nint main(int argc, char* argv[]){\n\tint is_corrdump = -1;\n\tint is_read     = -1;\n\n\tint num_max_body = 0;\n\tdouble truncation = 0;\n\tdouble precision  = 0.00001;\n\tdouble pair_truncation = 0;\n\tdouble triplet_truncation = 0;\n\tdouble quadruplet_truncation = 0;\n\tstd::shared_ptr<Input> in(new Input(\"getconf.ini\"));\n\n\tin->setData(\"MAXBODY\",      num_max_body, true);\n\tin->setData(\"TRUNCATION\",   truncation, true);\n\n\tin->setData(\"PRECISION\", precision);\n\tin->setData(\"PAIRTRUNC\", pair_truncation);\n\tin->setData(\"TRITRUNC\",  triplet_truncation);\n\tin->setData(\"QUADTRUNC\", quadruplet_truncation);\n\n\tin->setData(\"CLUSTEROUT\",  is_read);\n\tin->setData(\"CORRDUMP\",    is_corrdump);\n\n\tif( pair_truncation == 0 ) pair_truncation = truncation;\n\tif( triplet_truncation == 0 ) triplet_truncation = truncation;\n\tif( quadruplet_truncation == 0 ) quadruplet_truncation = truncation;\n\n\tif( pair_truncation < triplet_truncation or triplet_truncation < quadruplet_truncation ) {\n\t\tstd::cerr << \"ERROR : TRITRUNC <= PAIRTRUNC(orTRUNATION) and QUADTRUNC <= TRITRUNC(orTRUNATION)\" << std::endl;\n\t\texit(1);\n\t}\n\n\tif( is_read>0 ){\n\t\tshowResult(is_corrdump, in);\n\t\treturn 1;\n\t}\n\n\tstd::string filename_poscar_in = \"poscar.spin\";\n\n\tParsePoscar poscar(filename_poscar_in.c_str());\n\tconst auto atoms_unit = poscar.getAtoms();\n\n\tEigen::Vector3d unit_x, unit_y, unit_z;\n\tunit_x << 1, 0, 0;\n\tunit_y << 0, 1, 0;\n\tunit_z << 0, 0, 1;\n\n\tdouble unit_length_x = (poscar.getLatticeBasis() * unit_x).norm();\n\tdouble unit_length_y = (poscar.getLatticeBasis() * unit_y).norm();\n\tdouble unit_length_z = (poscar.getLatticeBasis() * unit_z).norm();\n\n\tint N_unit = poscar.getAtoms().size();\n\t/* if use ceil, integer distance cannot be correctly handled. */\n\tint expand_x = std::ceil((pair_truncation*3.)/unit_length_x);\n\tint expand_y = std::ceil((pair_truncation*3.)/unit_length_y);\n\tint expand_z = std::ceil((pair_truncation*3.)/unit_length_z);\n\n\tposcar.expandPoscar(expand_x, expand_y, expand_z);\n\n\tconst auto atoms = poscar.getAtoms();\n\tconst int N = atoms.size();\n\n\t/*  setting lattice and site */\n\tstd::vector<std::shared_ptr<Lattice>> vec_lattices;\n\tstd::vector<std::shared_ptr<Site>> vec_sites;\n\tsetSiteAndLattice(vec_lattices, vec_sites, poscar);\n\n\tstd::ofstream cluster_info(\"cluster.info\", std::ios::out );\n\tstd::ofstream cluster_out( \"cluster.out\", std::ios::out );\n\n\tfor( int i=0; i<atoms_unit.size(); ++i){\n\t\tcluster_out << atoms_unit[i].first << \" \" <<  atoms_unit[i].second.transpose() << std::endl;\n\t}\n\tcluster_out << \"--\" << std::endl;\n\n\t/*  set nbody = 1 */\n\tcluster_info << \" -- point cluster\" << std::endl;\n\tint num_index = 1;\n\tfor( const auto& lattice : vec_lattices ){\n\t\tcluster_info << num_index << \" : \"  << \"[\" << lattice->getLatticeNum() << \"] : 0 : 1 : 0 0 0 \" << std::endl;\n\t\tcluster_out << num_index << \" \";\n\t\tcluster_out << \"1\" << \" \";\n\t\tcluster_out << N_unit << \" \";\n\t\tcluster_out << N_unit << \" \";\n\t\tfor( int i=0; i<N_unit; ++i){\n\t\t\tcluster_out << vec_sites[i]->getSiteNum() << \" \";\n\t\t}\n\t\tcluster_out << std::endl;\n\t\t++num_index;\n\t}\n\n\t/*  set nbody = 2 */\n\tcluster_info << \" -- 2 body cluster\" << std::endl;\n\tstd::unordered_map<PairIndex , Eigen::Vector3d, hash_pairindex> index_pair_clusters;\n\tif( pair_truncation == 0 ) pair_truncation = truncation;\n\tsetSiteReferencesAndPairIndex(vec_lattices, vec_sites, index_pair_clusters, pair_truncation, precision);\n\n\tstd::vector<PairIndex> sorted_vec_pairindex;\n\tfor(const auto& index_pair : index_pair_clusters){\n\t\tsorted_vec_pairindex.push_back(index_pair.first);\n\t}\n\tsort(sorted_vec_pairindex.begin(), sorted_vec_pairindex.end());\n\n\tcluster_info << \" # [index] : distance : multiplicity : coordination \" << std::endl;\n\tfor( const auto& pairindex : sorted_vec_pairindex ){\n\t\tcluster_info << num_index << \" : \";\n\t\tcluster_info << \"[\" << pairindex.lattice_index[0] << \",\" << pairindex.lattice_index[1]  << \"] : \";\n\t\tconst auto pair_itr = vec_sites[0]->getLinkedSiteIterator(pairindex.distance);\n\t\tcluster_info << pairindex.distance << \" : \" << std::distance(pair_itr.first, pair_itr.second) << \" : \";\n\t\tcluster_info << index_pair_clusters[pairindex].transpose() << std::endl;\n\n\t\tfor( const auto& site : vec_sites ) {\n\t\t\tconst auto test_pair_itr = site->getLinkedSiteIterator(pairindex.distance);\n\t\t\tassert( std::distance(pair_itr.first, pair_itr.second) == std::distance(test_pair_itr.first, test_pair_itr.second) );\n\t\t}\n\n\t\tcluster_out << num_index << \" \";\n\t\tcluster_out << \"2\" << \" \";\n\t\tcluster_out << N_unit << \" \";\n\t\tcluster_out << N_unit * std::distance(pair_itr.first, pair_itr.second) << \" \";\n\t\tfor(int i=0; i<N_unit; ++i){\n\t\t\tauto pair_itr = vec_sites[i]->getLinkedSiteIterator(pairindex.distance);\n\t\t\twhile( pair_itr.first != pair_itr.second ){\n\t\t\t\tcluster_out << vec_sites[i]->getSiteNum() << \" \" << (*(pair_itr.first)).site->getSiteNum() << \" \";\n\t\t\t\t++pair_itr.first;\n\t\t\t}\n\t\t}\n\t\tcluster_out << std::endl;\n\t\t++num_index;\n\t}\n\tif( num_max_body == 2 ){\n\t\tcluster_out.close();\n\t\tcluster_info.close();\n\t\tshowResult(is_corrdump, in);\n\t\treturn 1;\n\t}\n\n\t/*  set nbody = 3 */\n\tcluster_info << \" -- 3 body cluster\" << std::endl;\n\tstd::vector<TripletIndex> keys_index_triplet_cluster;\n\tstd::unordered_map<TripletIndex, std::vector<std::vector<Eigen::Vector3d>>, hash_tripletindex> index_triplet_cluster;\n\tsetTripletIndex(vec_lattices, vec_sites, sorted_vec_pairindex, keys_index_triplet_cluster, index_triplet_cluster, triplet_truncation, precision);\n\n\tfor(int i=2; i>=0; --i){\n\t\tstable_sort(keys_index_triplet_cluster.begin(), keys_index_triplet_cluster.end(), [i](const TripletIndex& lhs, const TripletIndex& rhs){\n\t\t\t\treturn lhs.vec_pairindex[i] < rhs.vec_pairindex[i];\n\t\t});\n\t}\n\n\tfor(const auto& tripletindex : keys_index_triplet_cluster){\n\n\t\tcluster_info << num_index << \" : \";\n\t\tcluster_info << \"[] : \";\n\t\tcluster_info << \" [ \";\n\t\tcluster_info << tripletindex.vec_pairindex[0].distance << \",\";\n\t\tcluster_info << tripletindex.vec_pairindex[1].distance << \",\";\n\t\tcluster_info << tripletindex.vec_pairindex[2].distance;\n\t\tcluster_info << \" ] : \";\n\t\tcluster_info << index_triplet_cluster[tripletindex].size() <<  \" : \";\n\n\t\tcluster_info << index_triplet_cluster[tripletindex][0][0].transpose() << \",\";\n\t\tcluster_info << index_triplet_cluster[tripletindex][0][1].transpose() << std::endl;\n\n\t\tcluster_out << num_index << \" \";\n\t\tcluster_out << \"3\" << \" \";\n\t\tcluster_out << N_unit << \" \";\n\t\tcluster_out << N_unit*index_triplet_cluster[tripletindex].size() << \" \";\n\t\tfor(int i=0; i<N_unit; ++i){\n\t\t\tfor(int j=0; j<index_triplet_cluster[tripletindex].size(); ++j){\n\t\t\t\tcluster_out  << vec_sites[i]->getSiteNum() << \" \";\n\t\t\t\tcluster_out  << vec_sites[i]->getLinkedSite(index_triplet_cluster[tripletindex][j][0])->getSiteNum() << \" \";\n\t\t\t\tcluster_out  << vec_sites[i]->getLinkedSite(index_triplet_cluster[tripletindex][j][1])->getSiteNum() << \" \";\n\t\t\t}\n\t\t}\n\t\tcluster_out << std::endl;\n\t\t++num_index;\n\t}\n\n\tif( num_max_body == 3 ){\n\t\tcluster_out.close();\n\t\tcluster_info.close();\n\t\tshowResult(is_corrdump, in);\n\t\treturn 1;\n\t}\n\n\t// /*  set nbody = 4 */\n\tcluster_info << \" -- 4 body cluster\" << std::endl;\n\tstd::vector<QuadrupletIndex> keys_index_quadruplet_cluster;\n\tstd::unordered_map<QuadrupletIndex, std::vector<std::vector<Eigen::Vector3d>>, hash_quadrupletindex> index_quadruplet_cluster;\n\tsetQuadrupletIndex(vec_lattices, vec_sites, sorted_vec_pairindex,  index_triplet_cluster, keys_index_quadruplet_cluster, index_quadruplet_cluster, quadruplet_truncation, precision);\n\n\tfor(int i=3; i>=0; --i){\n\t\tfor(int j=2; j>=0; --j){\n\t\tstable_sort(keys_index_quadruplet_cluster.begin(), keys_index_quadruplet_cluster.end(),\n\t\t\t[i,j](const QuadrupletIndex& lhs, const QuadrupletIndex& rhs){\n\t\t\t\treturn lhs.vec_tripletindex[i].vec_pairindex[j] < rhs.vec_tripletindex[i].vec_pairindex[j];\n\t\t\t});\n\t\t}\n\t}\n\n\tfor(const auto& key_index_quadruplet_cluster : keys_index_quadruplet_cluster){\n\n\t\tcluster_info << num_index << \" : \";\n\t\tcluster_info << \"[] : \";\n\t\tcluster_info << \" [ \";\n\t\tfor( const auto distance : key_index_quadruplet_cluster.getVecDistance() ){\n\t\t\tcluster_info << distance << \",\";\n\t\t}\n\t\tcluster_info << \" ] : \";\n\t\tcluster_info << index_quadruplet_cluster[key_index_quadruplet_cluster].size() <<  \" : \";\n\n\t\tcluster_info << index_quadruplet_cluster[key_index_quadruplet_cluster][0][0].transpose() << \",\";\n\t\tcluster_info << index_quadruplet_cluster[key_index_quadruplet_cluster][0][1].transpose() << \",\";\n\t\tcluster_info << index_quadruplet_cluster[key_index_quadruplet_cluster][0][2].transpose() << std::endl;\n\n\t\tcluster_out << num_index << \" \";\n\t\tcluster_out << \"4\" << \" \";\n\t\tcluster_out << N_unit << \" \";\n\t\tcluster_out << N_unit*index_quadruplet_cluster[key_index_quadruplet_cluster].size() << \" \";\n\t\tfor(int i=0; i<N_unit; ++i){\n\t\t\tfor(int j=0; j<index_quadruplet_cluster[key_index_quadruplet_cluster].size(); ++j){\n\t\t\t\tcluster_out  << vec_sites[i]->getSiteNum() << \" \";\n\t\t\t\tcluster_out  << vec_sites[i]->getLinkedSite(index_quadruplet_cluster[key_index_quadruplet_cluster][j][0])->getSiteNum() << \" \";\n\t\t\t\tcluster_out  << vec_sites[i]->getLinkedSite(index_quadruplet_cluster[key_index_quadruplet_cluster][j][1])->getSiteNum() << \" \";\n\t\t\t\tcluster_out  << vec_sites[i]->getLinkedSite(index_quadruplet_cluster[key_index_quadruplet_cluster][j][2])->getSiteNum() << \" \";\n\t\t\t}\n\t\t}\n\t\tcluster_out << std::endl;\n\t\t++num_index;\n\t}\n\tcluster_out.close();\n\tcluster_info.close();\n\n\tshowResult(is_corrdump, in);\n\treturn 1;\n}\n", "meta": {"hexsha": "c022457776593a1a625c2c8802781b612a991bd1", "size": 11965, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/getconf.cpp", "max_stars_repo_name": "KazuhitoT/wlce", "max_stars_repo_head_hexsha": "0ec6551340756f46f7cc634576af63e1cc81bba8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/getconf.cpp", "max_issues_repo_name": "KazuhitoT/wlce", "max_issues_repo_head_hexsha": "0ec6551340756f46f7cc634576af63e1cc81bba8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/getconf.cpp", "max_forks_repo_name": "KazuhitoT/wlce", "max_forks_repo_head_hexsha": "0ec6551340756f46f7cc634576af63e1cc81bba8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2268370607, "max_line_length": 182, "alphanum_fraction": 0.6830756373, "num_tokens": 3560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6584175005616829, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.24136909792080288}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2020 Madhur Chauhan. \n//  Copyright 2020 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#ifndef BOOST_MP_ADD_UNSIGNED_ADDC_32_HPP\n#define BOOST_MP_ADD_UNSIGNED_ADDC_32_HPP\n\n#include <boost/multiprecision/cpp_int/intel_intrinsics.hpp>\n#include <boost/multiprecision/detail/assert.hpp>\n\nnamespace boost { namespace multiprecision { namespace backends {\n\ntemplate <class CppInt1, class CppInt2, class CppInt3>\ninline BOOST_MP_CXX14_CONSTEXPR void add_unsigned_constexpr(CppInt1& result, const CppInt2& a, const CppInt3& b) noexcept(is_non_throwing_cpp_int<CppInt1>::value)\n{\n   using ::boost::multiprecision::std_constexpr::swap;\n   //\n   // This is the generic, C++ only version of addition.\n   // It's also used for all constexpr branches, hence the name.\n   // Nothing fancy, just let uintmax_t take the strain:\n   //\n   double_limb_type carry = 0;\n   std::size_t         m(0), x(0);\n   std::size_t         as = a.size();\n   std::size_t         bs = b.size();\n   minmax(as, bs, m, x);\n   if (x == 1)\n   {\n      bool s = a.sign();\n      result = static_cast<double_limb_type>(*a.limbs()) + static_cast<double_limb_type>(*b.limbs());\n      result.sign(s);\n      return;\n   }\n   result.resize(x, x);\n   typename CppInt2::const_limb_pointer pa     = a.limbs();\n   typename CppInt3::const_limb_pointer pb     = b.limbs();\n   typename CppInt1::limb_pointer       pr     = result.limbs();\n   typename CppInt1::limb_pointer       pr_end = pr + m;\n\n   if (as < bs)\n      swap(pa, pb);\n\n   // First where a and b overlap:\n   while (pr != pr_end)\n   {\n      carry += static_cast<double_limb_type>(*pa) + static_cast<double_limb_type>(*pb);\n#ifdef __MSVC_RUNTIME_CHECKS\n      *pr = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n#else\n      *pr = static_cast<limb_type>(carry);\n#endif\n      carry >>= CppInt1::limb_bits;\n      ++pr, ++pa, ++pb;\n   }\n   pr_end += x - m;\n   // Now where only a has digits:\n   while (pr != pr_end)\n   {\n      if (!carry)\n      {\n         if (pa != pr)\n            std_constexpr::copy(pa, pa + (pr_end - pr), pr);\n         break;\n      }\n      carry += static_cast<double_limb_type>(*pa);\n#ifdef __MSVC_RUNTIME_CHECKS\n      *pr = static_cast<limb_type>(carry & ~static_cast<limb_type>(0));\n#else\n      *pr = static_cast<limb_type>(carry);\n#endif\n      carry >>= CppInt1::limb_bits;\n      ++pr, ++pa;\n   }\n   if (carry)\n   {\n      // We overflowed, need to add one more limb:\n      result.resize(x + 1, x + 1);\n      if (result.size() > x)\n         result.limbs()[x] = static_cast<limb_type>(1u);\n   }\n   result.normalize();\n   result.sign(a.sign());\n}\n//\n// Core subtraction routine for all non-trivial cpp_int's:\n//\ntemplate <class CppInt1, class CppInt2, class CppInt3>\ninline BOOST_MP_CXX14_CONSTEXPR void subtract_unsigned_constexpr(CppInt1& result, const CppInt2& a, const CppInt3& b) noexcept(is_non_throwing_cpp_int<CppInt1>::value)\n{\n   using ::boost::multiprecision::std_constexpr::swap;\n   //\n   // This is the generic, C++ only version of subtraction.\n   // It's also used for all constexpr branches, hence the name.\n   // Nothing fancy, just let uintmax_t take the strain:\n   //\n   double_limb_type borrow = 0;\n   std::size_t         m(0), x(0);\n   minmax(a.size(), b.size(), m, x);\n   //\n   // special cases for small limb counts:\n   //\n   if (x == 1)\n   {\n      bool      s  = a.sign();\n      limb_type al = *a.limbs();\n      limb_type bl = *b.limbs();\n      if (bl > al)\n      {\n         ::boost::multiprecision::std_constexpr::swap(al, bl);\n         s = !s;\n      }\n      result = al - bl;\n      result.sign(s);\n      return;\n   }\n   // This isn't used till later, but comparison has to occur before we resize the result,\n   // as that may also resize a or b if this is an inplace operation:\n   int c = a.compare_unsigned(b);\n   // Set up the result vector:\n   result.resize(x, x);\n   // Now that a, b, and result are stable, get pointers to their limbs:\n   typename CppInt2::const_limb_pointer pa      = a.limbs();\n   typename CppInt3::const_limb_pointer pb      = b.limbs();\n   typename CppInt1::limb_pointer       pr      = result.limbs();\n   bool                                 swapped = false;\n   if (c < 0)\n   {\n      swap(pa, pb);\n      swapped = true;\n   }\n   else if (c == 0)\n   {\n      result = static_cast<limb_type>(0);\n      return;\n   }\n\n   std::size_t i = 0;\n   // First where a and b overlap:\n   while (i < m)\n   {\n      borrow = static_cast<double_limb_type>(pa[i]) - static_cast<double_limb_type>(pb[i]) - borrow;\n      pr[i]  = static_cast<limb_type>(borrow);\n      borrow = (borrow >> CppInt1::limb_bits) & 1u;\n      ++i;\n   }\n   // Now where only a has digits, only as long as we've borrowed:\n   while (borrow && (i < x))\n   {\n      borrow = static_cast<double_limb_type>(pa[i]) - borrow;\n      pr[i]  = static_cast<limb_type>(borrow);\n      borrow = (borrow >> CppInt1::limb_bits) & 1u;\n      ++i;\n   }\n   // Any remaining digits are the same as those in pa:\n   if ((x != i) && (pa != pr))\n      std_constexpr::copy(pa + i, pa + x, pr + i);\n   BOOST_MP_ASSERT(0 == borrow);\n\n   //\n   // We may have lost digits, if so update limb usage count:\n   //\n   result.normalize();\n   result.sign(a.sign());\n   if (swapped)\n      result.negate();\n}\n\n\n#ifdef BOOST_MP_HAS_IMMINTRIN_H\n//\n// This is the key addition routine where all the argument types are non-trivial cpp_int's:\n//\n//\n// This optimization is limited to: GCC, LLVM, ICC (Intel), MSVC for x86_64 and i386.\n// If your architecture and compiler supports ADC intrinsic, please file a bug\n//\n// As of May, 2020 major compilers don't recognize carry chain though adc\n// intrinsics are used to hint compilers to use ADC and still compilers don't\n// unroll the loop efficiently (except LLVM) so manual unrolling is done.\n//\n// Also note that these intrinsics were only introduced by Intel as part of the\n// ADX processor extensions, even though the addc instruction has been available\n// for basically all x86 processors.  That means gcc-9, clang-9, msvc-14.2 and up\n// are required to support these intrinsics.\n//\ntemplate <class CppInt1, class CppInt2, class CppInt3>\ninline BOOST_MP_CXX14_CONSTEXPR void add_unsigned(CppInt1& result, const CppInt2& a, const CppInt3& b) noexcept(is_non_throwing_cpp_int<CppInt1>::value)\n{\n#ifndef BOOST_MP_NO_CONSTEXPR_DETECTION\n   if (BOOST_MP_IS_CONST_EVALUATED(a.size()))\n   {\n      add_unsigned_constexpr(result, a, b);\n   }\n   else\n#endif\n   {\n      using std::swap;\n\n      // Nothing fancy, just let uintmax_t take the strain:\n      std::size_t m(0), x(0);\n      std::size_t as = a.size();\n      std::size_t bs = b.size();\n      minmax(as, bs, m, x);\n      if (x == 1)\n      {\n         bool s = a.sign();\n         result = static_cast<double_limb_type>(*a.limbs()) + static_cast<double_limb_type>(*b.limbs());\n         result.sign(s);\n         return;\n      }\n      result.resize(x, x);\n      typename CppInt2::const_limb_pointer pa = a.limbs();\n      typename CppInt3::const_limb_pointer pb = b.limbs();\n      typename CppInt1::limb_pointer       pr = result.limbs();\n\n      if (as < bs)\n         swap(pa, pb);\n      // First where a and b overlap:\n      std::size_t      i = 0;\n      unsigned char carry = 0;\n#if defined(BOOST_MSVC) && !defined(BOOST_HAS_INT128) && defined(_M_X64)\n      //\n      // Special case for 32-bit limbs on 64-bit architecture - we can process\n      // 2 limbs with each instruction.\n      //\n      for (; i + 8 <= m; i += 8)\n      {\n         carry = _addcarry_u64(carry, *(unsigned long long*)(pa + i + 0), *(unsigned long long*)(pb + i + 0), (unsigned long long*)(pr + i));\n         carry = _addcarry_u64(carry, *(unsigned long long*)(pa + i + 2), *(unsigned long long*)(pb + i + 2), (unsigned long long*)(pr + i + 2));\n         carry = _addcarry_u64(carry, *(unsigned long long*)(pa + i + 4), *(unsigned long long*)(pb + i + 4), (unsigned long long*)(pr + i + 4));\n         carry = _addcarry_u64(carry, *(unsigned long long*)(pa + i + 6), *(unsigned long long*)(pb + i + 6), (unsigned long long*)(pr + i + 6));\n      }\n#else\n      for (; i + 4 <= m; i += 4)\n      {\n         carry = ::boost::multiprecision::detail::addcarry_limb(carry, pa[i + 0], pb[i + 0], pr + i);\n         carry = ::boost::multiprecision::detail::addcarry_limb(carry, pa[i + 1], pb[i + 1], pr + i + 1);\n         carry = ::boost::multiprecision::detail::addcarry_limb(carry, pa[i + 2], pb[i + 2], pr + i + 2);\n         carry = ::boost::multiprecision::detail::addcarry_limb(carry, pa[i + 3], pb[i + 3], pr + i + 3);\n      }\n#endif\n      for (; i < m; ++i)\n         carry = ::boost::multiprecision::detail::addcarry_limb(carry, pa[i], pb[i], pr + i);\n      for (; i < x && carry; ++i)\n         // We know carry is 1, so we just need to increment pa[i] (ie add a literal 1) and capture the carry:\n         carry = ::boost::multiprecision::detail::addcarry_limb(0, pa[i], 1, pr + i);\n      if (i == x && carry)\n      {\n         // We overflowed, need to add one more limb:\n         result.resize(x + 1, x + 1);\n         if (result.size() > x)\n            result.limbs()[x] = static_cast<limb_type>(1u);\n      }\n      else if ((x != i) && (pa != pr))\n         // Copy remaining digits only if we need to:\n         std_constexpr::copy(pa + i, pa + x, pr + i);\n      result.normalize();\n      result.sign(a.sign());\n   }\n}\n\ntemplate <class CppInt1, class CppInt2, class CppInt3>\ninline BOOST_MP_CXX14_CONSTEXPR void subtract_unsigned(CppInt1& result, const CppInt2& a, const CppInt3& b) noexcept(is_non_throwing_cpp_int<CppInt1>::value)\n{\n#ifndef BOOST_MP_NO_CONSTEXPR_DETECTION\n   if (BOOST_MP_IS_CONST_EVALUATED(a.size()))\n   {\n      subtract_unsigned_constexpr(result, a, b);\n   }\n   else\n#endif\n   {\n      using std::swap;\n\n      // Nothing fancy, just let uintmax_t take the strain:\n      std::size_t         m(0), x(0);\n      minmax(a.size(), b.size(), m, x);\n      //\n      // special cases for small limb counts:\n      //\n      if (x == 1)\n      {\n         bool      s = a.sign();\n         limb_type al = *a.limbs();\n         limb_type bl = *b.limbs();\n         if (bl > al)\n         {\n            ::boost::multiprecision::std_constexpr::swap(al, bl);\n            s = !s;\n         }\n         result = al - bl;\n         result.sign(s);\n         return;\n      }\n      // This isn't used till later, but comparison has to occur before we resize the result,\n      // as that may also resize a or b if this is an inplace operation:\n      int c = a.compare_unsigned(b);\n      // Set up the result vector:\n      result.resize(x, x);\n      // Now that a, b, and result are stable, get pointers to their limbs:\n      typename CppInt2::const_limb_pointer pa = a.limbs();\n      typename CppInt3::const_limb_pointer pb = b.limbs();\n      typename CppInt1::limb_pointer       pr = result.limbs();\n      bool                                 swapped = false;\n      if (c < 0)\n      {\n         swap(pa, pb);\n         swapped = true;\n      }\n      else if (c == 0)\n      {\n         result = static_cast<limb_type>(0);\n         return;\n      }\n\n      std::size_t i = 0;\n      unsigned char borrow = 0;\n      // First where a and b overlap:\n#if defined(BOOST_MSVC) && !defined(BOOST_HAS_INT128) && defined(_M_X64)\n      //\n      // Special case for 32-bit limbs on 64-bit architecture - we can process\n      // 2 limbs with each instruction.\n      //\n      for (; i + 8 <= m; i += 8)\n      {\n         borrow = _subborrow_u64(borrow, *reinterpret_cast<const unsigned long long*>(pa + i), *reinterpret_cast<const unsigned long long*>(pb + i), reinterpret_cast<unsigned long long*>(pr + i));\n         borrow = _subborrow_u64(borrow, *reinterpret_cast<const unsigned long long*>(pa + i + 2), *reinterpret_cast<const unsigned long long*>(pb + i + 2), reinterpret_cast<unsigned long long*>(pr + i + 2));\n         borrow = _subborrow_u64(borrow, *reinterpret_cast<const unsigned long long*>(pa + i + 4), *reinterpret_cast<const unsigned long long*>(pb + i + 4), reinterpret_cast<unsigned long long*>(pr + i + 4));\n         borrow = _subborrow_u64(borrow, *reinterpret_cast<const unsigned long long*>(pa + i + 6), *reinterpret_cast<const unsigned long long*>(pb + i + 6), reinterpret_cast<unsigned long long*>(pr + i + 6));\n      }\n#else\n      for(; i + 4 <= m; i += 4)\n      {\n         borrow = boost::multiprecision::detail::subborrow_limb(borrow, pa[i], pb[i], pr + i);\n         borrow = boost::multiprecision::detail::subborrow_limb(borrow, pa[i + 1], pb[i + 1], pr + i + 1);\n         borrow = boost::multiprecision::detail::subborrow_limb(borrow, pa[i + 2], pb[i + 2], pr + i + 2);\n         borrow = boost::multiprecision::detail::subborrow_limb(borrow, pa[i + 3], pb[i + 3], pr + i + 3);\n      }\n#endif\n      for (; i < m; ++i)\n         borrow = boost::multiprecision::detail::subborrow_limb(borrow, pa[i], pb[i], pr + i);\n\n      // Now where only a has digits, only as long as we've borrowed:\n      while (borrow && (i < x))\n      {\n         borrow = boost::multiprecision::detail::subborrow_limb(borrow, pa[i], 0, pr + i);\n         ++i;\n      }\n      // Any remaining digits are the same as those in pa:\n      if ((x != i) && (pa != pr))\n         std_constexpr::copy(pa + i, pa + x, pr + i);\n      BOOST_MP_ASSERT(0 == borrow);\n\n      //\n      // We may have lost digits, if so update limb usage count:\n      //\n      result.normalize();\n      result.sign(a.sign());\n      if (swapped)\n         result.negate();\n   }  // constepxr.\n}\n\n#else\n\ntemplate <class CppInt1, class CppInt2, class CppInt3>\ninline BOOST_MP_CXX14_CONSTEXPR void add_unsigned(CppInt1& result, const CppInt2& a, const CppInt3& b) noexcept(is_non_throwing_cpp_int<CppInt1>::value)\n{\n   add_unsigned_constexpr(result, a, b);\n}\n\ntemplate <class CppInt1, class CppInt2, class CppInt3>\ninline BOOST_MP_CXX14_CONSTEXPR void subtract_unsigned(CppInt1& result, const CppInt2& a, const CppInt3& b) noexcept(is_non_throwing_cpp_int<CppInt1>::value)\n{\n   subtract_unsigned_constexpr(result, a, b);\n}\n\n#endif\n\n} } }  // namespaces\n\n\n#endif\n\n\n", "meta": {"hexsha": "1087e1f15e117a3835f1abcc0137949d8952d45f", "size": 14144, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/multiprecision/cpp_int/add_unsigned.hpp", "max_stars_repo_name": "mariospr/multiprecision", "max_stars_repo_head_hexsha": "4720edda9e3058ba68be8ae6c29342536b9ce142", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/multiprecision/cpp_int/add_unsigned.hpp", "max_issues_repo_name": "mariospr/multiprecision", "max_issues_repo_head_hexsha": "4720edda9e3058ba68be8ae6c29342536b9ce142", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/multiprecision/cpp_int/add_unsigned.hpp", "max_forks_repo_name": "mariospr/multiprecision", "max_forks_repo_head_hexsha": "4720edda9e3058ba68be8ae6c29342536b9ce142", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4536082474, "max_line_length": 208, "alphanum_fraction": 0.604638009, "num_tokens": 4046, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24130556349315269}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_PERIMETER_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_PERIMETER_HPP\n\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/geometries/concepts/check.hpp>\n#include <boost/geometry/strategies/default_length_result.hpp>\n#include <boost/geometry/algorithms/length.hpp>\n#include <boost/geometry/algorithms/detail/calculate_null.hpp>\n#include <boost/geometry/algorithms/detail/calculate_sum.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n// Default perimeter is 0.0, specializations implement calculated values\ntemplate <typename Tag, typename Geometry, typename Strategy>\nstruct perimeter : detail::calculate_null\n    <\n        typename default_length_result<Geometry>::type,\n        Geometry,\n        Strategy\n    >\n{};\n\ntemplate <typename Geometry, typename Strategy>\nstruct perimeter<ring_tag, Geometry, Strategy>\n    : detail::length::range_length\n        <\n            Geometry,\n            Strategy,\n            closure<Geometry>::value\n        >\n{};\n\ntemplate <typename Polygon, typename Strategy>\nstruct perimeter<polygon_tag, Polygon, Strategy>\n    : detail::calculate_polygon_sum\n        <\n            typename default_length_result<Polygon>::type,\n            Polygon,\n            Strategy,\n            detail::length::range_length\n                <\n                    typename ring_type<Polygon>::type,\n                    Strategy,\n                    closure<Polygon>::value\n                >\n        >\n{};\n\n\n// box,n-sphere: to be implemented\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\n/*!\n\\brief \\brief_calc{perimeter}\n\\ingroup perimeter\n\\details The function perimeter returns the perimeter of a geometry,\n    using the default distance-calculation-strategy\n\\tparam Geometry \\tparam_geometry\n\\param geometry \\param_geometry\n\\return \\return_calc{perimeter}\n\n\\qbk{[include reference/algorithms/perimeter.qbk]}\n */\ntemplate<typename Geometry>\ninline typename default_length_result<Geometry>::type perimeter(\n        Geometry const& geometry)\n{\n    concept::check<Geometry const>();\n\n    typedef typename point_type<Geometry>::type point_type;\n    typedef typename strategy::distance::services::default_strategy\n        <\n            point_tag, point_type\n        >::type strategy_type;\n\n    return dispatch::perimeter\n        <\n            typename tag<Geometry>::type,\n            Geometry,\n            strategy_type\n        >::apply(geometry, strategy_type());\n}\n\n/*!\n\\brief \\brief_calc{perimeter} \\brief_strategy\n\\ingroup perimeter\n\\details The function perimeter returns the perimeter of a geometry,\n    using specified strategy\n\\tparam Geometry \\tparam_geometry\n\\tparam Strategy \\tparam_strategy{distance}\n\\param geometry \\param_geometry\n\\param strategy strategy to be used for distance calculations.\n\\return \\return_calc{perimeter}\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/perimeter.qbk]}\n */\ntemplate<typename Geometry, typename Strategy>\ninline typename default_length_result<Geometry>::type perimeter(\n        Geometry const& geometry, Strategy const& strategy)\n{\n    concept::check<Geometry const>();\n\n    return dispatch::perimeter\n        <\n            typename tag<Geometry>::type,\n            Geometry,\n            Strategy\n        >::apply(geometry, strategy);\n}\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_PERIMETER_HPP\n\n", "meta": {"hexsha": "a0536d1da2fcfeec9907b1b5ecde853a6572500b", "size": 4025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_47_0/boost/geometry/algorithms/perimeter.hpp", "max_stars_repo_name": "zigaosolin/Raytracer", "max_stars_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:37:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-25T07:38:07.000Z", "max_issues_repo_path": "external/boost_1_47_0/boost/geometry/algorithms/perimeter.hpp", "max_issues_repo_name": "zigaosolin/Raytracer", "max_issues_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2016-01-11T05:20:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T11:37:24.000Z", "max_forks_repo_path": "external/boost_1_47_0/boost/geometry/algorithms/perimeter.hpp", "max_forks_repo_name": "zigaosolin/Raytracer", "max_forks_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-01-05T15:10:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T04:59:16.000Z", "avg_line_length": 28.75, "max_line_length": 79, "alphanum_fraction": 0.7095652174, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.24130556349315269}}
{"text": "// This file is distributed under the MIT license.\n// See the LICENSE file for details.\n\n#include <common/config.h>\n\n#include <exception>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <ostream>\n#include <string>\n\n#include <boost/filesystem.hpp>\n\n#include <GL/glew.h>\n\n#include <pbrtParser/Scene.h>\n\n#include <Support/CmdLine.h>\n#include <Support/CmdLineUtil.h>\n\n#include <visionaray/detail/platform.h>\n\n#include <visionaray/math/io.h>\n\n#include <visionaray/bvh.h>\n#include <visionaray/cpu_buffer_rt.h>\n#include <visionaray/kernels.h>\n#include <visionaray/material.h>\n#include <visionaray/scheduler.h>\n#include <visionaray/thin_lens_camera.h>\n\n#include <common/manip/arcball_manipulator.h>\n#include <common/manip/pan_manipulator.h>\n#include <common/manip/zoom_manipulator.h>\n\n#include <common/image.h>\n#include <common/make_materials.h>\n#include <common/model.h>\n#include <common/obj_loader.h>\n#include <common/viewer_glut.h>\n\nusing namespace visionaray;\n\nusing viewer_type = viewer_glut;\n\n\n//-------------------------------------------------------------------------------------------------\n// Phantom Ray-Hair Intersector (Reshetov and Luebke, 2018)\n//\n\n//-------------------------------------------------------------------------------------------------\n// Ray/cone intersection from appendix A\n//\n\nstruct RayConeIntersection\n{\n    inline bool intersect(float r, float dr)\n    {\n        float r2  = r * r;\n        float drr = r * dr;\n\n        float ddd = cd.x * cd.x + cd.y * cd.y;\n        dp        = c0.x * c0.x + c0.y * c0.y;\n        float cdd = c0.x * cd.x + c0.y * cd.y;\n        float cxd = c0.x * cd.y - c0.y * cd.x;\n\n        float c = ddd;\n        float b = cd.z * (drr - cdd);\n        float cdz2 = cd.z * cd.z;\n        ddd += cdz2;\n        float a = 2.0f * drr * cdd + cxd * cxd - ddd * r2 + dp * cdz2;\n\n        float discr = b * b - a * c;\n        s   = (b - (discr > 0.0f ? sqrtf(discr) : 0.0f)) / c;\n        dt  = (s * cd.z - cdd) / ddd;\n        dc  = s * s + dp;\n        sp  = cdd / cd.z;\n        dp += sp * sp;\n\n        return discr > 0.0f;\n    }\n\n    vec3  c0;\n    vec3  cd;\n    float s;\n    float dt;\n    float dp;\n    float dc;\n    float sp;\n};\n\n\ninline bool intersectCylinder(basic_ray<float> const& ray, vec3 p0, vec3 p1, float ra)\n{\n    vec3  ba = p1 - p0;\n    vec3  oc = ray.ori - p0;\n\n    float baba = dot(ba, ba);\n    float bard = dot(ba, ray.dir);\n    float baoc = dot(ba, oc);\n\n    float k2 = baba - bard * bard;\n    float k1 = baba * dot(oc, ray.dir) - baoc * bard;\n    float k0 = baba * dot(oc, oc) - baoc * baoc - ra * ra * baba;\n\n    float h = k1 * k1 - k2 * k0;\n\n    if (h < 0.0f)\n    {\n        return false;\n    }\n\n    h = sqrtf(h);\n    float t = (-k1 - h) / k2;\n\n    // body\n    float y = baoc + t * bard;\n    if (y > 0.0f && y < baba)\n    {\n        return true;\n    }\n\n    // caps\n    t = ((y < 0.0f ? 0.0f : baba) - baoc) / bard;\n    if (fabsf(k1 + k2 * t) < h)\n    {\n        return true;\n    }\n\n    return false;\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Curve class\n//\n\nstruct Curve : primitive<unsigned>\n{\n    vec3 w0;\n    vec3 w1;\n    vec3 w2;\n    vec3 w3;\n\n    float r;\n\n    vec3 f(float t) const\n    {\n        float tinv = 1.0f - t;\n        return tinv * tinv * tinv * w0\n         + 3.0f * tinv * tinv * t * w1\n            + 3.0f * tinv * t * t * w2\n                      + t * t * t * w3;\n    }\n\n    vec3 dfdt(float t) const\n    {\n        float tinv = 1.0f - t;\n        return                 -3.0f * tinv * tinv * w0\n         + 3.0f * (3.0f * t * t - 4.0f * t + 1.0f) * w1\n                    + 3.0f * (2.0f - 3.0f * t) * t * w2\n                                    + 3.0f * t * t * w3;\n    }\n};\n\nCurve make_curve(vec3 const& w0, vec3 const& w1, vec3 const& w2, vec3 const& w3, float r)\n{\n    Curve curve;\n    curve.w0 = w0;\n    curve.w1 = w1;\n    curve.w2 = w2;\n    curve.w3 = w3;\n    curve.r = r;\n    return curve;\n}\n\n\n// That's from here: https://www.shadertoy.com/view/MdKBWt\naabb get_bounds(Curve const& curve)\n{\n    vec3 p0 = curve.w0;\n    vec3 p1 = curve.w1;\n    vec3 p2 = curve.w2;\n    vec3 p3 = curve.w3;\n\n    // extremes\n    vec3 mi = min(p0,p3);\n    vec3 ma = max(p0,p3);\n\n    // note pascal triangle coefficnets\n    vec3 c = -1.0f*p0 + 1.0f*p1;\n    vec3 b =  1.0f*p0 - 2.0f*p1 + 1.0f*p2;\n    vec3 a = -1.0f*p0 + 3.0f*p1 - 3.0f*p2 + 1.0f*p3;\n\n    vec3 h = b*b - a*c;\n\n    // real solutions\n    if (h.x > 0.0f || h.y > 0.0f || h.z > 0.0f)\n    {\n        vec3 g(\n            sqrtf(fabsf(h.x)),\n            sqrtf(fabsf(h.y)),\n            sqrtf(fabsf(h.z))\n            );\n        vec3 t1 = clamp((-b - g)/a,vec3(0.0f),vec3(1.0f)); vec3 s1 = 1.0f-t1;\n        vec3 t2 = clamp((-b + g)/a,vec3(0.0f),vec3(1.0f)); vec3 s2 = 1.0f-t2;\n        vec3 q1 = s1*s1*s1*p0 + 3.0f*s1*s1*t1*p1 + 3.0f*s1*t1*t1*p2 + t1*t1*t1*p3;\n        vec3 q2 = s2*s2*s2*p0 + 3.0f*s2*s2*t2*p1 + 3.0f*s2*t2*t2*p2 + t2*t2*t2*p3;\n\n        if (h.x > 0.0f)\n        {\n            mi.x = min(mi.x,min(q1.x,q2.x));\n            ma.x = max(ma.x,max(q1.x,q2.x));\n        }\n        if (h.y > 0.0f)\n        {\n            mi.y = min(mi.y,min(q1.y,q2.y));\n            ma.y = max(ma.y,max(q1.y,q2.y));\n        }\n        if (h.z > 0.0f)\n        {\n            mi.z = min(mi.z,min(q1.z,q2.z));\n            ma.z = max(ma.z,max(q1.z,q2.z));\n        }\n    }\n\n    return aabb(mi - vec3(curve.r), ma + vec3(curve.r));\n}\n\n\nstd::pair<Curve, Curve> split(Curve const& curve)\n{\n    std::pair<Curve, Curve> result;\n\n    vec3 p0 = curve.w0;\n    vec3 p1 = curve.w1;\n    vec3 p2 = curve.w2;\n    vec3 p3 = curve.w3;\n\n    vec3 q0 = (p0 + p1) / 2.0f;\n    vec3 q1 = (p1 + p2) / 2.0f;\n    vec3 q2 = (p2 + p3) / 2.0f;\n\n    vec3 r0 = (q0 + q1) / 2.0f;\n    vec3 r1 = (q1 + q2) / 2.0f;\n\n    vec3 s0 = (r0 + r1) / 2.0f;\n\n    result.first  = make_curve(p0, q0, r0, s0, curve.r);\n    result.second = make_curve(s0, r1, q2, p3, curve.r);\n\n    return result;\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Transform entities to ray-centric coordinate system RCC\n//\n\nstruct TransformToRCC\n{\n    inline TransformToRCC(basic_ray<float> const& r)\n    {\n        vec3 e1;\n        vec3 e2;\n        vec3 e3 = normalize(r.dir);\n        make_orthonormal_basis(e1, e2, e3);\n        xformInv = mat4(\n            vec4(e1,    0.0f),\n            vec4(e2,    0.0f),\n            vec4(e3,    0.0f),\n            vec4(r.ori, 1.0f)\n            );\n        xform = inverse(xformInv);\n    }\n\n    inline vec3 xfmPoint(vec3 point)\n    {\n        return (xform * vec4(point, 1.0f)).xyz();\n    }\n\n    inline vec3 xfmVector(vec3 vector)\n    {\n        return (xform * vec4(vector, 0.0f)).xyz();\n    }\n\n    inline vec3 xfmPointInv(vec3 point)\n    {\n        return (xformInv * vec4(point, 1.0f)).xyz();\n    }\n\n    inline vec3 xfmVectorInv(vec3 vector)\n    {\n        return (xformInv * vec4(vector, 0.0f)).xyz();\n    }\n\n    mat4 xform;\n    mat4 xformInv;\n};\n\ninline hit_record<basic_ray<float>, primitive<unsigned>> intersect(basic_ray<float> const& r, Curve const& curve)\n{\n    hit_record<basic_ray<float>, primitive<unsigned>> result;\n    result.hit = false;\n\n    // Early exit check against enclosing cylinder\n    auto distToCylinder = [&curve](vec3 pt) {\n        return length(cross(pt - curve.w0, pt - curve.w3)) / length(curve.w3 - curve.w0);\n    };\n\n    // TODO: could compute tighter bounding cylinder than this one!\n    float rmax = distToCylinder(curve.f(0.33333f));\n    rmax = fmaxf(rmax, distToCylinder(curve.f(0.66667f)));\n    rmax += curve.r;\n\n    vec3 axis = normalize(curve.w3 - curve.w0);\n    vec3 p0   = curve.w0 - axis * curve.r;\n    vec3 p1   = curve.w3 + axis * curve.r;\n\n    if (!intersectCylinder(r, p0, p1, rmax))\n    {\n        return result;\n    }\n\n    // Transform curve to RCC\n    TransformToRCC rcc(r);\n    Curve xcurve = make_curve(\n        rcc.xfmPoint(curve.w0),\n        rcc.xfmPoint(curve.w1),\n        rcc.xfmPoint(curve.w2),\n        rcc.xfmPoint(curve.w3),\n        curve.r\n        );\n\n    // \"Test for convergence. If the intersection is found,\n    // report it, otherwise start at the other endpoint.\"\n\n    // Compute curve end to start at\n    float tstart = dot(xcurve.w3 - xcurve.w0, r.dir) > 0.0f ? 0.0f : 1.0f;\n\n    for (int ep = 0; ep < 2; ++ep)\n    {\n        float t   = tstart;\n\n        RayConeIntersection rci;\n\n        float told = 0.0f;\n        float dt1 = 0.0f;\n        float dt2 = 0.0f;\n\n        for (int i = 0; i < 40; ++i)\n        {\n            rci.c0 = xcurve.f(t);\n            rci.cd = xcurve.dfdt(t);\n\n            bool phantom = !rci.intersect(curve.r, 0.0f/*cylinder*/);\n\n            // \"In all examples in this paper we stop iterations when dt < 5x10^−5\"\n            if (!phantom && fabsf(rci.dt) < 5e-5f)\n            {\n                //vec3 n = normalize(curve.dfdt(t));\n                rci.s += rci.c0.z;\n                result.t = rci.s;\n                result.u = t; // abuse param u to store curve's t\n                result.hit = true;\n                result.isect_pos = r.ori + result.t * r.dir;\n                break;\n            }\n\n            rci.dt = min(rci.dt, 0.5f);\n            rci.dt = max(rci.dt, -0.5f);\n\n            dt1 = dt2;\n            dt2 = rci.dt;\n\n            // Regula falsi\n            if (dt1 * dt2 < 0.0f)\n            {\n                float tnext = 0.0f;\n                // \"we use the simplest possible approach by switching\n                // to the bisection every 4th iteration:\"\n                if ((i & 3) == 0)\n                {\n                    tnext = 0.5f * (told + t);\n                }\n                else\n                {\n                    tnext = (dt2 * told - dt1 * t) / (dt2 - dt1);\n                }\n                told = t;\n                t = tnext;\n            }\n            else\n            {\n                told = t;\n                t += rci.dt;\n            }\n\n            if (t < 0.0f || t > 1.0f)\n            {\n                break;\n            }\n        }\n\n        if (!result.hit)\n        {\n            tstart = 1.0f - tstart;\n        }\n        else\n        {\n            break;\n        }\n    }\n\n    return result;\n}\n\ninline vec3 get_normal(\n        hit_record<basic_ray<float>, primitive<unsigned>> const& hr,\n        Curve const& curve\n        )\n{\n    float t = hr.u;\n    vec3 curve_pos = curve.f(t);\n    return normalize(hr.isect_pos - curve_pos);\n}\n\ninline float area(Curve const& curve)\n{\n    VSNRAY_UNUSED(curve);\n\n    // TODO: implement this to support curve lights!\n    return -1.0f;\n}\n\ninline void split_primitive(aabb& L, aabb& R, float plane, int axis, Curve const& curve)\n{\n    VSNRAY_UNUSED(L);\n    VSNRAY_UNUSED(R);\n    VSNRAY_UNUSED(plane);\n    VSNRAY_UNUSED(axis);\n    VSNRAY_UNUSED(curve);\n\n    // TODO: implement this to support SBVHs\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// I/O utility for camera lookat only - not fit for the general case!\n//\n\nstd::istream& operator>>(std::istream& in, pinhole_camera& cam)\n{\n    vec3 eye;\n    vec3 center;\n    vec3 up;\n\n    in >> eye >> std::ws >> center >> std::ws >> up >> std::ws;\n    cam.look_at(eye, center, up);\n\n    return in;\n}\n\nstd::ostream& operator<<(std::ostream& out, pinhole_camera const& cam)\n{\n    out << cam.eye() << '\\n';\n    out << cam.center() << '\\n';\n    out << cam.up() << '\\n';\n    return out;\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// struct with state variables\n//\n\nstruct renderer : viewer_type\n{\n    renderer()\n        : viewer_type(512, 512, \"Visionaray Phantom Ray-Hair Intersector Example\")\n        , host_sched(8)\n    {\n        using namespace support;\n\n        // Add cmdline options\n        add_cmdline_option( cl::makeOption<std::string&>(\n            cl::Parser<>(),\n            \"filename\",\n            cl::Desc(\"Input file in wavefront obj format\"),\n            cl::Positional,\n            cl::Optional,\n            cl::init(this->filename)\n            ) );\n\n        add_cmdline_option( cl::makeOption<std::string&>(\n            cl::Parser<>(),\n            \"camera\",\n            cl::Desc(\"Text file with camera parameters\"),\n            cl::ArgRequired,\n            cl::init(this->initial_camera)\n            ) );\n\n        add_cmdline_option( cl::makeOption<unsigned&>(\n            cl::Parser<>(),\n            \"spp\",\n            cl::Desc(\"Pixels per sample for path tracing\"),\n            cl::ArgRequired,\n            cl::init(this->spp)\n            ) );\n    }\n\n    void build_scene()\n    {\n        std::vector<Curve> actual_curves;\n\n        std::shared_ptr<pbrt::Scene> scene;\n\n        if (!filename.empty())\n        {\n            try\n            {\n                boost::filesystem::path p(filename);\n                std::string ext = p.extension().string();\n\n                std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);\n\n                std::cout << \"Try loading pbrt file...\\n\";\n\n                if (ext == \".pbf\")\n                {\n                    scene = pbrt::Scene::loadFrom(filename);\n                }\n                else if (ext == \".pbrt\")\n                {\n                    scene = pbrt::importPBRT(filename);\n                }\n\n                for (pbrt::Shape::SP shape : scene->world->shapes)\n                {\n                    if (pbrt::Curve::SP curve = std::dynamic_pointer_cast<pbrt::Curve>(shape))\n                    {\n                        if (curve->P.size() != 4)\n                        {\n                            continue;\n                        }\n\n                        vec3 w0(curve->P[0].x, curve->P[0].y, curve->P[0].z);\n                        vec3 w1(curve->P[1].x, curve->P[1].y, curve->P[1].z);\n                        vec3 w2(curve->P[2].x, curve->P[2].y, curve->P[2].z);\n                        vec3 w3(curve->P[3].x, curve->P[3].y, curve->P[3].z);\n                        // TODO: phantom _should_ also support two radii!\n                        float r = (curve->width0 + curve->width1) * 0.5f;\n\n                        actual_curves.push_back(make_curve(w0, w1, w2, w3, r));\n                    }\n                }\n            }\n            catch (std::runtime_error e)\n            {\n                std::cout << \"Failed: \" << e.what() << '\\n';\n                // ignore\n            }\n        }\n\n        // Add some dummy data when file couldn't be loaded / file name was empty\n        if (actual_curves.empty())\n        {\n            actual_curves.push_back(make_curve({0.0f, 0.0f, 0.0f}, {1.0f, 0.0f, 0.5f}, {2.0f, 0.5f, 0.0f}, {3.0f, 0.0f, 0.0f}, 0.3f));\n            actual_curves.push_back(make_curve({0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 0.0f}, {2.0f, 2.0f, 0.0f}, {3.0f, 3.0f, 0.0f}, 0.08f));\n            actual_curves.push_back(make_curve({0.0f, 0.0f, 0.0f}, {0.0f, 20.0f, 1.0f}, {0.0f, 0.0f, 2.0f}, {0.0f, 0.0f, 3.0f}, 0.04f));\n            actual_curves.push_back(make_curve({0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 1.0f}, {0.0f, 1.0f, 2.0f}, {0.0f, 0.0f, 3.0f}, 0.08f));\n            actual_curves.push_back(make_curve({-1.0f, 2.0f, 0.0f}, {0.0f, -2.0f, 0.0f}, {1.0f, 4.0f, 0.0f}, {2.0f, -4.0f, 0.0f}, 0.02f));\n            actual_curves.push_back(make_curve({-5.0f, 2.0f, 0.0f}, {0.0f, -0.5f, 1.0f}, {1.0f, 4.0f, 0.0f}, {2.0f, -4.0f, 8.0f}, 0.07f));\n            actual_curves.push_back(make_curve({0.0f, 10.0f, 0.0f}, {0.0f, 11.0f, 11.0f}, {0.0f, -11.0f, 0.0f}, {0.0f, -10.0f, 0.0f}, 0.3f));\n            actual_curves.push_back(make_curve({3.0f, 8.0f, 0.0f}, {0.0f, 15.0f, 11.0f}, {0.0f, -11.0f, 0.0f}, {7.0f, -10.0f, 0.0f}, 0.2f));\n            actual_curves.push_back(make_curve({-10.0f, 20.0f, 0.0f}, {0.0f, -20.0f, 0.0f}, {1.0f, 4.0f, 0.0f}, {2.0f, -4.0f, 0.0f}, 0.1f));\n            actual_curves.push_back(make_curve({0.0f, 20.0f, 0.0f}, {1.0f, 2.0f, 4.5f}, {2.0f, 3.5f, 0.0f}, {3.0f, 4.0f, 0.0f}, 0.3f));\n        }\n\n        for (auto const& curve : actual_curves)\n        {\n            auto p0 = split(curve);\n            auto p00 = split(p0.first);\n            auto p01 = split(p0.second);\n            // auto p000 = split(p00.first);\n            // auto p001 = split(p00.second);\n            // auto p010 = split(p01.first);\n            // auto p011 = split(p01.second);\n\n            // 4x\n            curves.push_back(p00.first);\n            curves.push_back(p00.second);\n            curves.push_back(p01.first);\n            curves.push_back(p01.second);\n\n            // 8x\n            // curves.push_back(p000.first);\n            // curves.push_back(p000.second);\n            // curves.push_back(p001.first);\n            // curves.push_back(p001.second);\n            // curves.push_back(p010.first);\n            // curves.push_back(p010.second);\n            // curves.push_back(p011.first);\n            // curves.push_back(p011.second);\n        }\n\n        for (unsigned i = 0; i < curves.size(); ++i)\n        {\n            curves[i].prim_id = i;\n            curves[i].geom_id = 0;\n        }\n\n        std::cout << \"Curves loaded:          \" << actual_curves.size() << '\\n';\n        std::cout << \"Curves after splitting: \" << curves.size() << '\\n';\n\n        matte<float> m;\n        m.cd() = from_rgb(0.78f, 0.70f, 0.55f);\n        m.kd() = 1.0f;\n        materials.emplace_back(m);\n\n        binned_sah_builder builder;\n        // TODO: implement get_split() for Curve to support spatial splits / SBVH!\n        builder.enable_spatial_splits(false);\n\n        std::cout << \"Building BVH...\\n\";\n        bvh = builder.build(index_bvh<Curve>{}, curves.data(), curves.size());\n        std::cout << \"Done!\\n\";\n\n        bbox.invalidate();\n\n        for (auto const& curve : curves)\n        {\n            bboxes.push_back(get_bounds(curve));\n            bbox.insert(get_bounds(curve));\n        }\n    }\n\n    thin_lens_camera                            cam;\n    cpu_buffer_rt<PF_RGBA32F, PF_UNSPECIFIED>   host_rt;\n    tiled_sched<basic_ray<float>>               host_sched;\n\n    std::vector<Curve>                          curves;\n    std::vector<aabb>                           bboxes;\n    std::vector<matte<float>>                   materials;\n    index_bvh<Curve>                            bvh;\n\n    aabb                                        bbox;\n\n    unsigned                                    frame_num       = 0;\n    unsigned                                    spp             = 1;\n    vec3                                        ambient         = vec3(1.0f, 1.0f, 1.0f);\n\n    std::string                                 filename;\n    std::string                                 initial_camera;\n\nprotected:\n\n    void load_camera(std::string filename);\n    void screenshot();\n    void on_display();\n    void on_key_press(visionaray::key_event const& event);\n    void on_mouse_move(visionaray::mouse_event const& event);\n    void on_resize(int w, int h);\n\n};\n\n\n//-------------------------------------------------------------------------------------------------\n// Load camera from file, reset frame counter and clear frame\n//\n\nvoid renderer::load_camera(std::string filename)\n{\n    std::ifstream file(filename);\n    if (file.good())\n    {\n        file >> cam;\n        frame_num = 0;\n        host_rt.clear_color_buffer();\n        std::cout << \"Load camera from file: \" << filename << '\\n';\n    }\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Take a screenshot\n//\n\nvoid renderer::screenshot()\n{\n    std::string screenshot_file_base = \"screenshot\";\n#if VSNRAY_COMMON_HAVE_PNG\n    static const std::string screenshot_file_suffix = \".png\";\n    image::save_option opt1;\n#else\n    static const std::string screenshot_file_suffix = \".pnm\";\n    image::save_option opt1({\"binary\", true});\n#endif\n\n    // Swizzle to RGB8 for compatibility with pnm image\n    std::vector<vector<3, unorm<8>>> rgb(host_rt.width() * host_rt.height());\n    swizzle(\n        rgb.data(),\n        PF_RGB8,\n        host_rt.color(),\n        PF_RGBA32F,\n        host_rt.width() * host_rt.height(),\n        TruncateAlpha\n        );\n\n    //if (rt.color_space() == host_device_rt::SRGB)\n    {\n        for (int y = 0; y < host_rt.height(); ++y)\n        {\n            for (int x = 0; x < host_rt.width(); ++x)\n            {\n                auto& color = rgb[y * host_rt.width() + x];\n                color.x = powf(color.x, 1 / 2.2f);\n                color.y = powf(color.y, 1 / 2.2f);\n                color.z = powf(color.z, 1 / 2.2f);\n            }\n        }\n    }\n\n    // Flip so that origin is (top|left)\n    std::vector<vector<3, unorm<8>>> flipped(host_rt.width() * host_rt.height());\n\n    for (int y = 0; y < host_rt.height(); ++y)\n    {\n        for (int x = 0; x < host_rt.width(); ++x)\n        {\n            int yy = host_rt.height() - y - 1;\n            flipped[yy * host_rt.width() + x] = rgb[y * host_rt.width() + x];\n        }\n    }\n\n    image img(\n        host_rt.width(),\n        host_rt.height(),\n        PF_RGB8,\n        reinterpret_cast<uint8_t const*>(flipped.data())\n        );\n\n    int inc = 0;\n    std::string inc_str = \"\";\n\n    std::string filename = screenshot_file_base + inc_str + screenshot_file_suffix;\n\n    while (boost::filesystem::exists(filename))\n    {\n        ++inc;\n        inc_str = std::to_string(inc);\n\n        while (inc_str.length() < 4)\n        {\n            inc_str = std::string(\"0\") + inc_str;\n        }\n\n        inc_str = std::string(\"-\") + inc_str;\n\n        filename = screenshot_file_base + inc_str + screenshot_file_suffix;\n    }\n\n    if (img.save(filename, {opt1}))\n    {\n        std::cout << \"Screenshot saved to file: \" << filename << '\\n';\n    }\n    else\n    {\n        std::cerr << \"Error saving screenshot to file: \" << filename << '\\n';\n    }\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Display function\n//\n\nvoid renderer::on_display()\n{\n    // some setup\n\n    //-----------------------------------------------------\n    // Setup scheduler parameters.\n    //\n\n    // We use path tracing. We therefore use the\n    // jittered_blend_type pixel sampler. That way\n    // a rand generator is created, and noisy\n    // images are blended later on.\n\n    // Note how we set sfactor and dfactor based on\n    // frame_num so that pixel blending works.\n\n    // Note: for the jittered_blend_type pixel sampler to\n    // work properly, you have to count frames yourself!\n    // (check the occurrences of renderer::frame_num in\n    // this file!)\n\n    pixel_sampler::jittered_blend_type blend_params;\n    blend_params.spp = spp;\n    float alpha = 1.0f / ++frame_num;\n    blend_params.sfactor = alpha;\n    blend_params.dfactor = 1.0f - alpha;\n\n    // Note: alternative samplers are:\n    //  pixel_sampler::uniform_type\n    // You can also leave this argument out, then you'll get\n    // the default: pixel_sampler::uniform_type\n    auto sparams = make_sched_params(\n            blend_params,\n            cam,          // the camera object (note: could also be two matrices!)\n            host_rt       // render target, that's where we store the pixel result.\n            );\n\n    // Create bvh \"refs\" that we can pass to the\n    // path tracing kernel\n    using bvh_ref = index_bvh<Curve>::bvh_ref;\n    aligned_vector<bvh_ref> primitives;\n    primitives.push_back(bvh.ref());\n\n    // Construct a parameter object that is\n    // compatible with the builtin path tracing kernel.\n    auto kparams = make_kernel_params(\n            primitives.data(),\n            primitives.data() + primitives.size(),\n            materials.data(),\n            4,      // bounces\n            1e-5f,  // scene epsilon\n            vec4(background_color(), 1.0f),\n            vec4(ambient, 1.0f)\n            );\n\n    //-----------------------------------------------------\n    // Naive path tracing with the builtin kernel.\n    //\n\n    // Instantiate the path tracing kernel, and\n    // call it by executing the scheduler's\n    // frame() function.\n    pathtracing::kernel<decltype(kparams)> kernel;\n    kernel.params = kparams;\n    host_sched.frame(kernel, sparams);\n\n\n    // Display the rendered image with OpenGL.\n\n    glEnable(GL_FRAMEBUFFER_SRGB);\n    glClearColor(0.0, 0.0, 0.0, 1.0);\n    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n    // You could also directly access host_rt::color()\n    // or host_rt::depth() (this render target however\n    // doesn't store a depth buffer).\n    host_rt.display_color_buffer();\n}\n\n\nvoid renderer::on_key_press(visionaray::key_event const& event)\n{\n    static const std::string camera_file_base = \"visionaray-camera\";\n    static const std::string camera_file_suffix = \".txt\";\n\n    switch (event.key())\n    {\n    case 'p':\n        screenshot();\n        break;\n\n    case 'u':\n        {\n            int inc = 0;\n            std::string inc_str = \"\";\n\n            std::string filename = camera_file_base + inc_str + camera_file_suffix;\n\n            while (boost::filesystem::exists(filename))\n            {\n                ++inc;\n                inc_str = std::to_string(inc);\n\n                while (inc_str.length() < 4)\n                {\n                    inc_str = std::string(\"0\") + inc_str;\n                }\n\n                inc_str = std::string(\"-\") + inc_str;\n\n                filename = camera_file_base + inc_str + camera_file_suffix;\n            }\n\n            std::ofstream file(filename);\n            if (file.good())\n            {\n                std::cout << \"Storing camera to file: \" << filename << '\\n';\n                file << cam;\n            }\n        }\n        break;\n\n    case 'v':\n        {\n            std::string filename = camera_file_base + camera_file_suffix;\n\n            load_camera(filename);\n        }\n        break;\n\n    default:\n        break;\n    }\n\n    viewer_type::on_key_press(event);\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// mouse handling\n//\n\nvoid renderer::on_mouse_move(visionaray::mouse_event const& event)\n{\n    if (event.buttons() != mouse::NoButton)\n    {\n        frame_num = 0;\n        host_rt.clear_color_buffer();\n    }\n\n    viewer_type::on_mouse_move(event);\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// resize event\n//\n\nvoid renderer::on_resize(int w, int h)\n{\n    frame_num = 0;\n    host_rt.clear_color_buffer();\n\n    cam.set_viewport(0, 0, w, h);\n    float aspect = w / static_cast<float>(h);\n    cam.perspective(45.0f * constants::degrees_to_radians<float>(), aspect, 0.001f, 1000.0f);\n    host_rt.resize(w, h);\n\n    viewer_type::on_resize(w, h);\n}\n\n\n//-------------------------------------------------------------------------------------------------\n// Main function, performs initialization\n//\n\nint main(int argc, char** argv)\n{\n    renderer rend;\n\n    try\n    {\n        rend.init(argc, argv);\n    }\n    catch (std::exception const& e)\n    {\n        std::cerr << e.what() << '\\n';\n        return EXIT_FAILURE;\n    }\n\n    rend.build_scene();\n\n    float aspect = rend.width() / static_cast<float>(rend.height());\n\n    rend.cam.perspective(45.0f * constants::degrees_to_radians<float>(), aspect, 0.001f, 1000.0f);\n    rend.cam.set_lens_radius(0.002f);\n    rend.cam.set_focal_distance(2.0f);\n\n    // Load camera from file or set view-all\n    std::ifstream file(rend.initial_camera);\n    if (file.good())\n    {\n        file >> rend.cam;\n    }\n    else\n    {\n        rend.cam.view_all(rend.bbox);\n    }\n\n    rend.add_manipulator( std::make_shared<arcball_manipulator>(rend.cam, mouse::Left) );\n    rend.add_manipulator( std::make_shared<pan_manipulator>(rend.cam, mouse::Middle) );\n    // Additional \"Alt + LMB\" pan manipulator for setups w/o middle mouse button\n    rend.add_manipulator( std::make_shared<pan_manipulator>(rend.cam, mouse::Left, keyboard::Alt) );\n    rend.add_manipulator( std::make_shared<zoom_manipulator>(rend.cam, mouse::Right) );\n\n    rend.event_loop();\n}\n", "meta": {"hexsha": "3a0e909df4b521ac4d3114522f242afed1e7b421", "size": 27801, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/phantom/main.cpp", "max_stars_repo_name": "tjachmann/visionaray", "max_stars_repo_head_hexsha": "5f181268c8da28c7d9b397300cc9759cec2bf7b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/phantom/main.cpp", "max_issues_repo_name": "tjachmann/visionaray", "max_issues_repo_head_hexsha": "5f181268c8da28c7d9b397300cc9759cec2bf7b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/phantom/main.cpp", "max_forks_repo_name": "tjachmann/visionaray", "max_forks_repo_head_hexsha": "5f181268c8da28c7d9b397300cc9759cec2bf7b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8846539619, "max_line_length": 141, "alphanum_fraction": 0.4951620445, "num_tokens": 7960, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.24118198136642008}}
{"text": "/*\n * NormalVectorsFilter.cpp\n *\n *  Created on: May 05, 2015\n *      Author: Peter Fankhauser, Martin Wermelinger\n *   Institute: ETH Zurich, ANYbotics\n */\n\n#include \"grid_map_filters/NormalVectorsFilter.hpp\"\n\n#include <math.h>\n#include <memory>\n#include <stdexcept>\n\n#include <tbb/task_scheduler_init.h>\n#include <tbb/tbb.h>\n#include <Eigen/Dense>\n\n#include <grid_map_core/grid_map_core.hpp>\n\nnamespace grid_map {\n\nNormalVectorsFilter::NormalVectorsFilter()\n    : method_(Method::RasterSerial), estimationRadius_(0.0), parallelizationEnabled_(false), threadCount_(1), gridMapResolution_(0.02) {}\n\nNormalVectorsFilter::~NormalVectorsFilter() = default;\n\nbool NormalVectorsFilter::configure() {\n  // Read which algorithm is chosen: area or raster.\n  std::string algorithm;\n  if (!FilterBase::getParam(std::string(\"algorithm\"), algorithm)) {\n    ROS_WARN(\"Could not find the parameter: `algorithm`. Setting to default value: 'area'.\");\n    // Default value.\n    algorithm = \"area\";\n  }\n\n  // Read parameters related to area algorithm only if needed, otherwise when using raster method\n  // on purpose it throws unwanted errors.\n  if (algorithm != \"raster\") {\n    // Read radius, if found, its value will be used for area method. If radius parameter is not found, raster method will be used.\n    if (!FilterBase::getParam(std::string(\"radius\"), estimationRadius_)) {\n      ROS_WARN(\"Could not find the parameter: `radius`. Switching to raster method.\");\n      algorithm = \"raster\";\n    }\n    ROS_DEBUG(\"Normal vectors estimation radius = %f\", estimationRadius_);\n    // If radius not positive switch to raster method.\n    if (estimationRadius_ <= 0) {\n      ROS_WARN(\"Parameter `radius` is not positive. Switching to raster method.\");\n      algorithm = \"raster\";\n    }\n  }\n\n  // Read parallelization_enabled to decide whether parallelization has to be used, if parameter is not found an error is thrown and\n  // the false default value will be used.\n  if (!FilterBase::getParam(std::string(\"parallelization_enabled\"), parallelizationEnabled_)) {\n    ROS_WARN(\"Could not find the parameter: `parallelization_enabled`. Setting to default value: 'false'.\");\n    parallelizationEnabled_ = false;\n  }\n  ROS_DEBUG(\"Parallelization_enabled = %d\", parallelizationEnabled_);\n\n  // Read thread_number to set the number of threads to be used if parallelization is enebled,\n  // if parameter is not found an error is thrown and the default is to set it to automatic.\n  if (!FilterBase::getParam(std::string(\"thread_number\"), threadCount_)) {\n    ROS_WARN(\"Could not find the parameter: `thread_number`. Setting to default value: 'automatic'.\");\n    threadCount_ = tbb::task_scheduler_init::automatic;\n  }\n  ROS_DEBUG(\"Thread_number = %d\", threadCount_);\n\n  // Set wanted method looking at algorithm and parallelization_enabled parameters.\n  // parallelization_enabled is used to select whether to use parallelization or not.\n  if (algorithm == \"raster\") {\n    // If parallelizationEnabled_=true, use the parallel method, otherwise serial.\n    if (parallelizationEnabled_) {\n      method_ = Method::RasterParallel;\n      ROS_DEBUG(\"Method RasterParallel\");\n    } else {\n      method_ = Method::RasterSerial;\n      ROS_DEBUG(\"Method RasterSerial\");\n    }\n  } else {\n    // If parallelizationEnabled_=true, use the parallel method, otherwise serial.\n    if (parallelizationEnabled_) {\n      method_ = Method::AreaParallel;\n      ROS_DEBUG(\"Method AreaParallel\");\n    } else {\n      method_ = Method::AreaSerial;\n      ROS_DEBUG(\"Method AreaSerial\");\n    }\n    ROS_DEBUG(\"estimationRadius_ = %f\", estimationRadius_);\n  }\n\n  // Read normal_vector_positive_axis, to define normal vector positive direction.\n  std::string normalVectorPositiveAxis;\n  if (!FilterBase::getParam(std::string(\"normal_vector_positive_axis\"), normalVectorPositiveAxis)) {\n    ROS_ERROR(\"Normal vectors filter did not find parameter `normal_vector_positive_axis`.\");\n    return false;\n  }\n  if (normalVectorPositiveAxis == \"z\") {\n    normalVectorPositiveAxis_ = Vector3::UnitZ();\n  } else if (normalVectorPositiveAxis == \"y\") {\n    normalVectorPositiveAxis_ = Vector3::UnitY();\n  } else if (normalVectorPositiveAxis == \"x\") {\n    normalVectorPositiveAxis_ = Vector3::UnitX();\n  } else {\n    ROS_ERROR(\"The normal vector positive axis '%s' is not valid.\", normalVectorPositiveAxis.c_str());\n    return false;\n  }\n\n  // Read input_layer, to define input grid map layer.\n  if (!FilterBase::getParam(std::string(\"input_layer\"), inputLayer_)) {\n    ROS_ERROR(\"Normal vectors filter did not find parameter `input_layer`.\");\n    return false;\n  }\n  ROS_DEBUG(\"Normal vectors filter input layer is = %s.\", inputLayer_.c_str());\n\n  // Read output_layers_prefix, to define output grid map layers prefix.\n  if (!FilterBase::getParam(std::string(\"output_layers_prefix\"), outputLayersPrefix_)) {\n    ROS_ERROR(\"Normal vectors filter did not find parameter `output_layers_prefix`.\");\n    return false;\n  }\n  ROS_DEBUG(\"Normal vectors filter output_layer = %s.\", outputLayersPrefix_.c_str());\n\n  // If everything has been set up correctly\n  return true;\n}\n\nbool NormalVectorsFilter::update(const GridMap& mapIn, GridMap& mapOut) {\n  std::vector<std::string> normalVectorsLayers;\n  normalVectorsLayers.push_back(outputLayersPrefix_ + \"x\");\n  normalVectorsLayers.push_back(outputLayersPrefix_ + \"y\");\n  normalVectorsLayers.push_back(outputLayersPrefix_ + \"z\");\n\n  mapOut = mapIn;\n  for (const auto& layer : normalVectorsLayers) {\n    mapOut.add(layer);\n  }\n  switch (method_) {\n    case Method::AreaSerial:\n      computeWithAreaSerial(mapOut, inputLayer_, outputLayersPrefix_);\n      break;\n    case Method::RasterSerial:\n      computeWithRasterSerial(mapOut, inputLayer_, outputLayersPrefix_);\n      break;\n    case Method::AreaParallel:\n      computeWithAreaParallel(mapOut, inputLayer_, outputLayersPrefix_);\n      break;\n    case Method::RasterParallel:\n      computeWithRasterParallel(mapOut, inputLayer_, outputLayersPrefix_);\n      break;\n  }\n\n  return true;\n}\n\n// SVD Area based methods.\nvoid NormalVectorsFilter::computeWithAreaSerial(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix) {\n  const double start = ros::Time::now().toSec();\n\n  // For each cell in submap.\n  for (GridMapIterator iterator(map); !iterator.isPastEnd(); ++iterator) {\n    // Check if this is an empty cell (hole in the map).\n    if (map.isValid(*iterator, inputLayer)) {\n      const Index index(*iterator);\n      areaSingleNormalComputation(map, inputLayer, outputLayersPrefix, index);\n    }\n  }\n\n  const double end = ros::Time::now().toSec();\n  ROS_DEBUG_THROTTLE(2.0, \"NORMAL COMPUTATION TIME = %f\", (end - start));\n}\n\nvoid NormalVectorsFilter::computeWithAreaParallel(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix) {\n  const double start = ros::Time::now().toSec();\n  grid_map::Size gridMapSize = map.getSize();\n\n  // Set number of thread to use for parallel programming.\n  std::unique_ptr<tbb::task_scheduler_init> TBBInitPtr;\n  if (threadCount_ != -1) {\n    TBBInitPtr.reset(new tbb::task_scheduler_init(threadCount_));\n  }\n\n  // Parallelized iteration through the map.\n  tbb::parallel_for(0, gridMapSize(0) * gridMapSize(1), [&](int range) {\n    // Recover Cell index from range iterator.\n    const Index index(range / gridMapSize(1), range % gridMapSize(1));\n    if (map.isValid(index, inputLayer)) {\n      areaSingleNormalComputation(map, inputLayer, outputLayersPrefix, index);\n    }\n  });\n\n  const double end = ros::Time::now().toSec();\n  ROS_DEBUG_THROTTLE(2.0, \"NORMAL COMPUTATION TIME = %f\", (end - start));\n}\n\nvoid NormalVectorsFilter::areaSingleNormalComputation(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix,\n                                                      const grid_map::Index& index) {\n  // Requested position (center) of circle in map.\n  Position center;\n  map.getPosition(index, center);\n\n  // Prepare data computation. Check if area is bigger than cell.\n  const double minAllowedEstimationRadius = 0.5 * map.getResolution();\n  if (estimationRadius_ <= minAllowedEstimationRadius) {\n    ROS_WARN(\"Estimation radius is smaller than allowed by the map resolution (%f < %f)\", estimationRadius_, minAllowedEstimationRadius);\n  }\n\n  // Gather surrounding data.\n  size_t nPoints = 0;\n  Position3 sum = Position3::Zero();\n  Eigen::Matrix3d sumSquared = Eigen::Matrix3d::Zero();\n  for (CircleIterator circleIterator(map, center, estimationRadius_); !circleIterator.isPastEnd(); ++circleIterator) {\n    Position3 point;\n    if (!map.getPosition3(inputLayer, *circleIterator, point)) {\n      continue;\n    }\n    nPoints++;\n    sum += point;\n    sumSquared.noalias() += point * point.transpose();\n  }\n\n  Vector3 unitaryNormalVector = Vector3::Zero();\n  if (nPoints < 3) {\n    ROS_DEBUG(\"Not enough points to establish normal direction (nPoints = %i)\", static_cast<int>(nPoints));\n    unitaryNormalVector = Vector3::UnitZ();\n  } else {\n    const Position3 mean = sum / nPoints;\n    const Eigen::Matrix3d covarianceMatrix = sumSquared / nPoints - mean * mean.transpose();\n\n    // Compute Eigenvectors.\n    // Eigenvalues are ordered small to large.\n    // Worst case bound for zero eigenvalue from : https://eigen.tuxfamily.org/dox/classEigen_1_1SelfAdjointEigenSolver.html\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solver;\n    solver.computeDirect(covarianceMatrix, Eigen::DecompositionOptions::ComputeEigenvectors);\n    if (solver.eigenvalues()(1) > 1e-8) {\n      unitaryNormalVector = solver.eigenvectors().col(0);\n    } else {  // If second eigenvalue is zero, the normal is not defined.\n      ROS_DEBUG(\"Covariance matrix needed for eigen decomposition is degenerated.\");\n      ROS_DEBUG(\"Expected cause: data is on a straight line (nPoints = %i)\", static_cast<int>(nPoints));\n      unitaryNormalVector = Vector3::UnitZ();\n    }\n  }\n\n  // Check direction of the normal vector and flip the sign towards the user defined direction.\n  if (unitaryNormalVector.dot(normalVectorPositiveAxis_) < 0.0) {\n    unitaryNormalVector = -unitaryNormalVector;\n  }\n\n  map.at(outputLayersPrefix + \"x\", index) = unitaryNormalVector.x();\n  map.at(outputLayersPrefix + \"y\", index) = unitaryNormalVector.y();\n  map.at(outputLayersPrefix + \"z\", index) = unitaryNormalVector.z();\n}\n// Raster based methods.\nvoid NormalVectorsFilter::computeWithRasterSerial(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix) {\n  // Inspiration for algorithm: http://www.flipcode.com/archives/Calculating_Vertex_Normals_for_Height_Maps.shtml\n  const double start = ros::Time::now().toSec();\n\n  const grid_map::Size gridMapSize = map.getSize();\n  gridMapResolution_ = map.getResolution();\n  // Faster access to grid map values.\n  const grid_map::Matrix dataMap = map[inputLayer];\n  // Height and width of submap. Submap is Map without the outermost line of cells, no need to check if index is inside.\n  const Index submapStartIndex(1, 1);\n  const Index submapBufferSize(gridMapSize(0) - 2, gridMapSize(1) - 2);\n\n  // For each cell in submap.\n  for (SubmapIterator iterator(map, submapStartIndex, submapBufferSize); !iterator.isPastEnd(); ++iterator) {\n    const Index index(*iterator);\n    rasterSingleNormalComputation(map, outputLayersPrefix, dataMap, index);\n  }\n\n  const double end = ros::Time::now().toSec();\n  ROS_DEBUG_THROTTLE(2.0, \"NORMAL COMPUTATION TIME = %f\", (end - start));\n}\n\nvoid NormalVectorsFilter::computeWithRasterParallel(GridMap& map, const std::string& inputLayer, const std::string& outputLayersPrefix) {\n  const double start = ros::Time::now().toSec();\n\n  const grid_map::Size gridMapSize = map.getSize();\n  gridMapResolution_ = map.getResolution();\n  // Faster access to grid map values if copy grid map layer into local matrix.\n  const grid_map::Matrix dataMap = map[inputLayer];\n  // Height and width of submap. Submap is Map without the outermost line of cells, no need to check if index is inside.\n  const Index submapStartIndex(1, 1);\n  const Index submapBufferSize(gridMapSize(0) - 2, gridMapSize(1) - 2);\n  if (submapBufferSize(1) != 0) {\n    // Set number of thread to use for parallel programming\n    std::unique_ptr<tbb::task_scheduler_init> TBBInitPtr;\n    if (threadCount_ != -1) {\n      TBBInitPtr.reset(new tbb::task_scheduler_init(threadCount_));\n    }\n    // Parallelized iteration through the map.\n    tbb::parallel_for(0, submapBufferSize(0) * submapBufferSize(1), [&](int range) {\n      const Index index(range / submapBufferSize(1) + submapStartIndex(0), range % submapBufferSize(1) + submapStartIndex(1));\n      rasterSingleNormalComputation(map, outputLayersPrefix, dataMap, index);\n    });\n  } else {\n    ROS_ERROR(\"Grid map size is too small for normal raster computation\");\n  }\n\n  const double end = ros::Time::now().toSec();\n  ROS_DEBUG_THROTTLE(2.0, \"NORMAL COMPUTATION TIME = %f\", (end - start));\n}\n\nvoid NormalVectorsFilter::rasterSingleNormalComputation(GridMap& map, const std::string& outputLayersPrefix,\n                                                        const grid_map::Matrix& dataMap, const grid_map::Index& index) {\n  // Inspiration for algorithm:\n  // http://www.flipcode.com/archives/Calculating_Vertex_Normals_for_Height_Maps.shtml\n  const double centralCell = dataMap(index(0), index(1));\n  double topCell = dataMap(index(0) - 1, index(1));\n  double rightCell = dataMap(index(0), index(1) + 1);\n  double bottomCell = dataMap(index(0) + 1, index(1));\n  double leftCell = dataMap(index(0), index(1) - 1);\n\n  // Neighboring cells configuration checked in X and Y direction independently.\n  // Gridmap frame is defined rotated 90 degrees anticlockwise compared to direction of matrix if we take\n  // rows as Y coordinate and columns as X coordinate.\n  // In Y direction cell numbered as follows: left 0, center 1, right 2.\n  // In X direction cell numbered as follows: top 0, center 1, bottom 2.\n  // To find configuration we are in, multiply value of map.isValid of cell in question, True or False,\n  // by 2^(number of the cell).\n  // Each configuration will have a different number associated with it and then use a switch.\n\n  const int configurationDirX = 1 * static_cast<int>(std::isfinite(topCell)) + 2 * static_cast<int>(std::isfinite(centralCell)) +\n                                4 * static_cast<int>(std::isfinite(bottomCell));\n  const int configurationDirY = 1 * static_cast<int>(std::isfinite(leftCell)) + 2 * static_cast<int>(std::isfinite(centralCell)) +\n                                4 * static_cast<int>(std::isfinite(rightCell));\n\n  // If outer cell height value is missing use the central value, however the formula for the normal calculation\n  // has to take into account that the distance of the cells used for normal calculation is different.\n  bool validConfiguration = true;\n  double distanceX{NAN};\n  switch (configurationDirX) {\n    case 7:                                // All 3 cell height values are valid.\n      distanceX = 2 * gridMapResolution_;  // Top and bottom cell centers are 2 cell resolution distant.\n      break;\n    case 6:  // Top cell height value not valid.\n      topCell = centralCell;\n      distanceX = gridMapResolution_;\n      break;\n    case 5:  // Central cell height value not valid. Not a problem.\n      distanceX = 2 * gridMapResolution_;\n      break;\n    case 3:  // Bottom cell height value not valid.\n      bottomCell = centralCell;\n      distanceX = gridMapResolution_;\n      break;\n\n    default:  // More than 1 cell height values are not valid, normal vector will not be calculated in this location.\n      validConfiguration = false;\n  }\n\n  double distanceY{NAN};\n  switch (configurationDirY) {\n    case 7:                                // All 3 cell height values are valid.\n      distanceY = 2 * gridMapResolution_;  // Left and right cell centers are 2 call resolution distant.\n      break;\n    case 6:  // Left cell height value not valid.\n      leftCell = centralCell;\n      distanceY = gridMapResolution_;\n      break;\n    case 5:  // Central cell height value not valid. Not a problem.\n      distanceY = 2 * gridMapResolution_;\n      break;\n    case 3:  // Right cell height value not valid.\n      rightCell = centralCell;\n      distanceY = gridMapResolution_;\n      break;\n\n    default:  // More than 1 cell height values are not valid, normal vector will not be calculated in this location.\n      validConfiguration = false;\n  }\n\n  if (validConfiguration) {\n    // Normal vector initialization\n    Vector3 normalVector = Vector3::Zero();\n    // X DIRECTION\n    normalVector(0) = (bottomCell - topCell) / distanceX;\n    // Y DIRECTION\n    normalVector(1) = (rightCell - leftCell) / distanceY;\n    // Z DIRECTION\n    normalVector(2) = +1;\n\n    normalVector.normalize();\n\n    // Check direction of the normal vector and flip the sign towards the user defined direction.\n    if (normalVector.dot(normalVectorPositiveAxis_) < 0.0) {\n      normalVector = -normalVector;\n    }\n\n    map.at(outputLayersPrefix + \"x\", index) = normalVector.x();\n    map.at(outputLayersPrefix + \"y\", index) = normalVector.y();\n    map.at(outputLayersPrefix + \"z\", index) = normalVector.z();\n  }\n}\n\n}  // namespace grid_map\n", "meta": {"hexsha": "f6cdce240f9ec58c65b81215c12857ce9918a1e2", "size": 17183, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grid_map_filters/src/NormalVectorsFilter.cpp", "max_stars_repo_name": "martorelltorres/grid_map", "max_stars_repo_head_hexsha": "ccc4ad60f16b2754860ab05355f849a7a756eea3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 358.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T12:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-04T14:04:53.000Z", "max_issues_repo_path": "grid_map_filters/src/NormalVectorsFilter.cpp", "max_issues_repo_name": "martorelltorres/grid_map", "max_issues_repo_head_hexsha": "ccc4ad60f16b2754860ab05355f849a7a756eea3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2015-01-03T11:51:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-30T14:53:48.000Z", "max_forks_repo_path": "grid_map_filters/src/NormalVectorsFilter.cpp", "max_forks_repo_name": "martorelltorres/grid_map", "max_forks_repo_head_hexsha": "ccc4ad60f16b2754860ab05355f849a7a756eea3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 218.0, "max_forks_repo_forks_event_min_datetime": "2015-03-19T04:41:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-06T02:36:16.000Z", "avg_line_length": 43.282115869, "max_line_length": 137, "alphanum_fraction": 0.7056974917, "num_tokens": 4242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24106884341669138}}
{"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n//               2008 Dresden University of Technology and the Trustees of Indiana University.\n//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include <iostream>\n#include <cmath>\n#include <string>\n#include <vector>\n#include <complex>\n#include <boost/timer.hpp>\n\n#include <boost/numeric/mtl/matrix/parameter.hpp>\n#include <boost/numeric/mtl/matrix/dense2D.hpp>\n#include <boost/numeric/mtl/matrix/morton_dense.hpp>\n#include <boost/numeric/mtl/operation/print_matrix.hpp>\n#include <boost/numeric/mtl/operation/matrix_mult.hpp>\n#include <boost/numeric/mtl/matrix/hessian_setup.hpp>\n#include <boost/numeric/mtl/operation/assign_mode.hpp>\n#include <boost/numeric/mtl/recursion/predefined_masks.hpp>\n#include <boost/numeric/mtl/utility/papi.hpp>\n\nusing namespace mtl;\nusing namespace mtl::recursion; \nusing namespace std;  \n\n// Maximum time for a single measurement\n// is 20 min\nconst double max_time= 900;\n\ntypedef assign::plus_sum                            ama_t;\n\ntypedef recursion::bound_test_static<32>                    test32_t;\ntypedef recursion::bound_test_static<64>                    test64_t;\n\ntypedef gen_dense_mat_mat_mult_t<assign::plus_sum>  base_mult_t;\ntypedef gen_recursive_dense_mat_mat_mult_t<base_mult_t>     rec_mult_t;\n\ntypedef gen_tiling_22_dense_mat_mat_mult_t<assign::plus_sum>  tiling_22_base_mult_t;\ntypedef gen_tiling_44_dense_mat_mat_mult_t<assign::plus_sum>  tiling_44_base_mult_t;\n\n// ugly short cuts\ntypedef dense2D<double>                                       dr_t;\ntypedef dense2D<double, mat::parameters<col_major> >        dc_t;\n\nutility::papi_t papi;\nint l1i= papi.add_event(\"PAPI_L1_DCM\");\nint l2i= papi.add_event(\"PAPI_L2_DCM\");\nint tlbi= papi.add_event(\"PAPI_TLB_DM\");\n\n#ifdef MTL_USE_BLAS\nextern \"C\" {\nvoid dgemm_(const char* transa, const char* transb, \n\t    const int* m, const int* n, const int* k,\n\t    const double* alpha,  const double *da,  const int* lda,\n\t    const double *db, const int* ldb, const double* dbeta,\n\t    double *dc, const int* ldc);\n}\n#endif\n\nstruct dgemm_t\n{\n    void operator()(const dc_t& a, const dc_t& b, dc_t& c)\n    {\n#ifdef MTL_USE_BLAS\n\tint size= a.num_rows();\n\tdouble alpha= 1.0, beta= 0.0;\n\tdgemm_(\"N\", \"N\", &size, &size, &size, &alpha, \n\t       const_cast<double*>(&a[0][0]), &size, const_cast<double*>(&b[0][0]), \n\t       &size, &beta, &c[0][0], &size);\n#endif\n    }\n};\n\nstruct dgemm_add_t\n{\n    void operator()(const dc_t& a, const dc_t& b, dc_t& c)\n    {\n\tint size= a.num_rows();\n\tdouble alpha= 1.0, beta= 1.0;\n\tdgemm_(\"N\", \"N\", &size, &size, &size, &alpha, \n\t       const_cast<double*>(&a[0][0]), &size, const_cast<double*>(&b[0][0]), \n\t       &size, &beta, &c[0][0], &size);\n\n    }\n};\n\n\n\nvoid print_time_and_mflops(double time, double size)\n{\n    // time and MFlops of single measure\n    std::cout << time << \", \" << 2.0 * size * size * size / time / 1e6f << \", \";\n}\n\n\n// Matrices are only placeholder to provide the type\ntemplate <typename MatrixA, typename MatrixB, typename MatrixC, typename Mult>\nvoid single_measure(MatrixA&, MatrixB&, MatrixC&, Mult mult, unsigned size, std::vector<int>& enabled, int i)\n{\n    MatrixA a(size, size);\n    MatrixB b(size, size);\n    MatrixC c(size, size);\n    hessian_setup(a, 1.0);\n    hessian_setup(b, 1.0);\n\n    if (enabled[i]) {\n\tint reps= 0;\n\tboost::timer start;\t\n\tpapi.reset();\n\tfor (; start.elapsed() < 5; reps++)\n\t    mult(a, b, c);\n\tpapi.read();\n\tdouble time= start.elapsed() / double(reps);\n\n\tprint_time_and_mflops(time, a.num_rows());\n\tstd::cout << papi[l1i]/reps << \", \" << papi[l2i]/reps << \", \" << papi[tlbi]/reps << \", \";\n\tif (time > max_time)\n\t    enabled[i]= 0;\n    } else\n\tstd::cout << \", , , , , \";\n}\n\n// The matrices in the following functions are only place holders, the real matrices are used in single_measure\nvoid measure_morton_order(unsigned size, std::vector<int>& enabled)\n{\n    morton_dense<double,  morton_mask>             mda(4, 4), mdb(4, 4), mdc(4, 4);\n    morton_dense<double,  morton_z_mask>           mzda(4, 4), mzdb(4, 4), mzdc(4, 4);\n    dc_t                                           dc(4, 4);\n    \n    std::cout << size << \", \";\n    rec_mult_t  mult;\n    single_measure(mda, mdb, mdc, mult, size, enabled, 0);\n    single_measure(mzda, mzdb, mzdc, mult, size, enabled, 1);\n    single_measure(mda, mzdb, mdc, mult, size, enabled, 2);\n    single_measure(dc, dc, dc, dgemm_t(), size, enabled, 3);\n    \n    std::cout << \"0\\n\"; // to not finish with comma\n    std::cout.flush();\n}\n\n\nvoid measure_cast(unsigned size, std::vector<int>& enabled)\n{\n    morton_dense<double,  morton_mask>             mda(4, 4), mdb(4, 4), mdc(4, 4);\n    morton_dense<double,  doppled_32_row_mask>     d32ra(4, 4), d32rb(4, 4), d32rc(4, 4);\n    morton_dense<double,  doppled_64_row_mask>     d64ra(4, 4), d64rb(4, 4), d64rc(4, 4);\n    morton_dense<double,  doppled_64_col_mask>     d64ca(4, 4), d64cb(4, 4), d64cc(4, 4); \n    \n    rec_mult_t  mult;\n    std::cout << size << \", \";\n    single_measure(mda, mdb, mdc, mult, size, enabled, 0);\n    single_measure(d32ra, d32rb, d32rc, mult, size, enabled, 1);\n    single_measure(d64ra, d64rb, d64rc, mult, size, enabled, 2);\n    single_measure(d64ca, d64cb, d64cc, mult, size, enabled, 3);\n\n    dc_t                                           dc(4, 4);\n    single_measure(dc, dc, dc, dgemm_t(), size, enabled, 4);\n \n    std::cout << \"0\\n\";  std::cout.flush();\n}\n\n\nvoid measure_with_unroll(unsigned size, std::vector<int>& enabled)\n{\n    morton_dense<double,  doppled_32_row_mask>     d32r(4, 4);\n    morton_dense<double,  doppled_32_col_mask>     d32c(4, 4);\n\n    std::cout << size << \", \";\n\n    gen_recursive_dense_mat_mat_mult_t<base_mult_t, test32_t>           mult;\n    gen_recursive_dense_mat_mat_mult_t<tiling_22_base_mult_t, test32_t> mult_22;\n    gen_recursive_dense_mat_mat_mult_t<tiling_44_base_mult_t, test32_t> mult_44;\n\n    single_measure(d32r, d32r, d32r, mult, size, enabled, 0);\n    single_measure(d32r, d32r, d32r, mult_22, size, enabled, 1);\n    single_measure(d32r, d32r, d32r, mult_44, size, enabled, 2);\n\n    single_measure(d32c, d32c, d32c, mult, size, enabled, 3);\n    single_measure(d32c, d32c, d32c, mult_22, size, enabled, 4);\n    single_measure(d32c, d32c, d32c, mult_44, size, enabled, 5);\n    dc_t                                           dc(4, 4);\n    single_measure(dc, dc, dc, dgemm_t(), size, enabled, 6);\n \n    std::cout << \"0\\n\";  std::cout.flush();\n}\n\nvoid measure_base_size(unsigned size, std::vector<int>& enabled)\n{\n    morton_dense<double,  doppled_16_row_mask>     d16r(4, 4);\n    morton_dense<double,  doppled_32_row_mask>     d32r(4, 4);\n    morton_dense<double,  doppled_64_row_mask>     d64r(4, 4);\n    morton_dense<double,  doppled_128_col_mask>    d128r(4, 4);\n    \n    std::cout << size << \", \";\n\n    gen_recursive_dense_mat_mat_mult_t<tiling_22_base_mult_t, recursion::bound_test_static<16> > mult16;\n    single_measure(d16r, d16r, d16r, mult16, size, enabled, 0);\n\n    gen_recursive_dense_mat_mat_mult_t<tiling_22_base_mult_t, recursion::bound_test_static<32> > mult32;\n    single_measure(d32r, d32r, d32r, mult32, size, enabled, 1);\n\n    gen_recursive_dense_mat_mat_mult_t<tiling_22_base_mult_t, recursion::bound_test_static<64> > mult64;\n    single_measure(d64r, d64r, d64r, mult64, size, enabled, 2);\n\n    gen_recursive_dense_mat_mat_mult_t<tiling_22_base_mult_t, recursion::bound_test_static<128> > mult128;\n    single_measure(d128r, d128r, d128r, mult128, size, enabled, 3);\n\n    dc_t                                           dc(4, 4);\n    single_measure(dc, dc, dc, dgemm_t(), size, enabled, 4);\n \n    std::cout << \"0\\n\";  std::cout.flush();\n}\n\ntemplate <typename Matrix, typename MatrixB> \nvoid measure_unrolling(unsigned size, std::vector<int>& enabled, Matrix& matrix, MatrixB& matrixb)\n{\n    std::cout << size << \", \";\n \n    gen_recursive_dense_mat_mat_mult_t<base_mult_t>           mult;\n    gen_recursive_dense_mat_mat_mult_t<tiling_22_base_mult_t> mult_22;\n    gen_recursive_dense_mat_mat_mult_t<tiling_44_base_mult_t> mult_44;\n\n    typedef gen_tiling_dense_mat_mat_mult_t<2, 2, ama_t>  tiling_m22_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m22_base_mult_t> mult_m22;\n    \n    typedef gen_tiling_dense_mat_mat_mult_t<2, 4, ama_t>  tiling_m24_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m24_base_mult_t> mult_m24;\n\n    typedef gen_tiling_dense_mat_mat_mult_t<4, 2, ama_t>  tiling_m42_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m42_base_mult_t> mult_m42;\n\n    typedef gen_tiling_dense_mat_mat_mult_t<3, 5, ama_t>  tiling_m35_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m35_base_mult_t> mult_m35;\n\n    typedef gen_tiling_dense_mat_mat_mult_t<4, 4, ama_t>  tiling_m44_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m44_base_mult_t> mult_m44;\n\n\n    single_measure(matrix, matrixb, matrix, mult, size, enabled, 0);\n    single_measure(matrix, matrixb, matrix, mult_22, size, enabled, 1);\n    single_measure(matrix, matrixb, matrix, mult_44, size, enabled, 2);\n\n    single_measure(matrix, matrixb, matrix, mult_m22, size, enabled, 3);\n    single_measure(matrix, matrixb, matrix, mult_m24, size, enabled, 4);\n    single_measure(matrix, matrixb, matrix, mult_m42, size, enabled, 5);\n    single_measure(matrix, matrixb, matrix, mult_m35, size, enabled, 6);\n    single_measure(matrix, matrixb, matrix, mult_m44, size, enabled, 7);\n \n    dc_t                                           dc(4, 4);\n    single_measure(dc, dc, dc, dgemm_t(), size, enabled, 8);\n\n    gen_recursive_dense_mat_mat_mult_t<dgemm_add_t> mult_blas;\n    single_measure(dc, dc, dc, mult_blas, size, enabled, 9);\n\n\n    std::cout << \"0\\n\";  std::cout.flush();\n}\n\nvoid measure_unrolling_hybrid(unsigned size, std::vector<int>& enabled)\n{\n    morton_dense<double,  doppled_64_row_mask>     d64r(4, 4);\n    morton_dense<double,  doppled_64_col_mask>     d64c(4, 4);\n    measure_unrolling(size, enabled, d64r, d64c);\n}\n\nvoid measure_unrolling_dense(unsigned size, std::vector<int>& enabled)\n{\n    dense2D<double> dense(4, 4);\n    dense2D<double, mat::parameters<col_major> >    b(4, 4);\n    measure_unrolling(size, enabled, dense, b);\n}\n\n\nvoid measure_orientation(unsigned size, std::vector<int>& enabled)\n{\n    std::cout << size << \", \";\n \n    morton_dense<double,  doppled_64_row_mask>     d64r(4, 4);\n    morton_dense<double,  doppled_64_col_mask>     d64c(4, 4);\n\n    typedef gen_tiling_dense_mat_mat_mult_t<4, 2, ama_t>  tiling_m42_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m42_base_mult_t> mult_m42;\n\n    typedef gen_tiling_dense_mat_mat_mult_t<4, 4, ama_t>  tiling_m44_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m44_base_mult_t> mult_m44;\n    \n    single_measure(d64r, d64r, d64r, mult_m42, size, enabled, 0);\n    single_measure(d64c, d64c, d64c, mult_m42, size, enabled, 1);\n    single_measure(d64r, d64c, d64r, mult_m42, size, enabled, 2);\n    single_measure(d64c, d64r, d64r, mult_m42, size, enabled, 3);\n    \n    single_measure(d64r, d64r, d64r, mult_m44, size, enabled, 4);\n    single_measure(d64c, d64c, d64c, mult_m44, size, enabled, 5);\n    single_measure(d64r, d64c, d64r, mult_m44, size, enabled, 6);\n    single_measure(d64c, d64r, d64r, mult_m44, size, enabled, 7);\n \n    dc_t                                           dc(4, 4);\n    single_measure(dc, dc, dc, dgemm_t(), size, enabled, 8);\n\n    std::cout << \"0\\n\";  std::cout.flush();\n}\n\n\nvoid measure_unrolling_32(unsigned size, std::vector<int>& enabled)\n{\n    std::cout << size << \", \";\n \n    gen_recursive_dense_mat_mat_mult_t<base_mult_t, test32_t>           mult;\n    gen_recursive_dense_mat_mat_mult_t<tiling_22_base_mult_t, test32_t> mult_22;\n    gen_recursive_dense_mat_mat_mult_t<tiling_44_base_mult_t, test32_t> mult_44;\n\n    typedef gen_tiling_dense_mat_mat_mult_t<2, 2, ama_t>  tiling_m22_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m22_base_mult_t, test32_t> mult_m22;\n    \n    typedef gen_tiling_dense_mat_mat_mult_t<2, 4, ama_t>  tiling_m24_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m24_base_mult_t, test32_t> mult_m24;\n\n    typedef gen_tiling_dense_mat_mat_mult_t<4, 2, ama_t>  tiling_m42_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m42_base_mult_t, test32_t> mult_m42;\n\n    typedef gen_tiling_dense_mat_mat_mult_t<3, 5, ama_t>  tiling_m35_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m35_base_mult_t, test32_t> mult_m35;\n\n    typedef gen_tiling_dense_mat_mat_mult_t<4, 4, ama_t>  tiling_m44_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m44_base_mult_t, test32_t> mult_m44;\n\n    \n    morton_dense<double,  doppled_32_row_mask>     d32r(4, 4);\n    morton_dense<double,  doppled_32_col_mask>     d32c(4, 4);\n\n\n    single_measure(d32r, d32c, d32r, mult, size, enabled, 0);\n    single_measure(d32r, d32c, d32r, mult_22, size, enabled, 1);\n    single_measure(d32r, d32c, d32r, mult_44, size, enabled, 2);\n\n    single_measure(d32r, d32c, d32r, mult_m22, size, enabled, 3);\n    single_measure(d32r, d32c, d32r, mult_m24, size, enabled, 4);\n    single_measure(d32r, d32c, d32r, mult_m42, size, enabled, 5);\n    single_measure(d32r, d32c, d32r, mult_m35, size, enabled, 6);\n    single_measure(d32r, d32c, d32r, mult_m44, size, enabled, 7);\n \n    dc_t                                           dc(4, 4);\n    single_measure(dc, dc, dc, dgemm_t(), size, enabled, 8);\n\n    std::cout << \"0\\n\";  std::cout.flush();\n}\n\n\n\nvoid measure_hetero_value(unsigned size, std::vector<int>& enabled)\n{\n    using std::complex;\n    typedef gen_tiling_dense_mat_mat_mult_t<4, 4, ama_t>  tiling_m44_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m44_base_mult_t> mult;\n\n    dc_t                                           dc(4, 4);\n    dr_t                                           dr(4, 4);\n    dense2D<float, mat::parameters<row_major> >  fr(4, 4);\n    dense2D<float, mat::parameters<col_major> >  fc(4, 4);\n    dense2D<complex<float>, mat::parameters<col_major> >   cc(4, 4);\n    dense2D<complex<double>, mat::parameters<col_major> >  zc(4, 4);\n    dense2D<complex<double>, mat::parameters<row_major> >  zr(4, 4);\n\n    morton_dense<double,  doppled_64_row_mask>     d64r(4, 4);\n    morton_dense<double,  doppled_64_col_mask>     d64c(4, 4);\n    \n    morton_dense<float,  doppled_64_row_mask>     f64r(4, 4);\n    morton_dense<float,  doppled_64_col_mask>     f64c(4, 4);\n\n    morton_dense<complex<float>,  doppled_64_row_mask>     c64r(4, 4);\n    morton_dense<complex<float>,  doppled_64_col_mask>     c64c(4, 4);\n\n    morton_dense<complex<double>,  doppled_64_row_mask>     z64r(4, 4);\n    morton_dense<complex<double>,  doppled_64_col_mask>     z64c(4, 4);\n\n    std::cout << size << \", \";\n\n    single_measure(dr, fc, dr, mult, size, enabled, 0);\n    single_measure(fr, fc, dr, mult, size, enabled, 1);\n   \n    //single_measure(fr, zc, zr, mult, size, enabled, 2);\n    //single_measure(dr, cc, zr, mult, size, enabled, 3);\n    \n    single_measure(d64r, f64c, d64r, mult, size, enabled, 4);\n    single_measure(d64r, z64c, z64r, mult, size, enabled, 5);\n    std::cout << \"0\\n\";  std::cout.flush();\n}\n\n\nvoid measure_hetero_layout(unsigned size, std::vector<int>& enabled)\n{\n    using std::complex;\n    typedef gen_tiling_dense_mat_mat_mult_t<4, 4, ama_t>  tiling_m44_base_mult_t;\n    gen_recursive_dense_mat_mat_mult_t<tiling_m44_base_mult_t> mult;\n\n    dc_t                                           dc(4, 4);\n    dr_t                                           dr(4, 4);\n    dense2D<float, mat::parameters<row_major> >  fr(4, 4);\n    dense2D<float, mat::parameters<col_major> >  fc(4, 4);\n    dense2D<complex<float>, mat::parameters<col_major> >   cc(4, 4);\n    dense2D<complex<double>, mat::parameters<col_major> >  zc(4, 4);\n    dense2D<complex<double>, mat::parameters<row_major> >  zr(4, 4);\n\n    morton_dense<double,  doppled_64_row_mask>     d64r(4, 4);\n    morton_dense<double,  doppled_64_col_mask>     d64c(4, 4);\n    \n    morton_dense<float,  doppled_64_row_mask>     f64r(4, 4);\n    morton_dense<float,  doppled_64_col_mask>     f64c(4, 4);\n\n    morton_dense<complex<float>,  doppled_64_row_mask>     c64r(4, 4);\n    morton_dense<complex<float>,  doppled_64_col_mask>     c64c(4, 4);\n\n    morton_dense<complex<double>,  doppled_64_row_mask>     z64r(4, 4);\n    morton_dense<complex<double>,  doppled_64_col_mask>     z64c(4, 4);\n\n    std::cout << size << \", \";\n\n    single_measure(dr, f64c, dr, mult, size, enabled, 0);\n    single_measure(fr, f64c, dr, mult, size, enabled, 1);\n   \n    //single_measure(f64r, zc, zr, mult, size, enabled, 2);\n    single_measure(d64r, zc, zr, mult, size, enabled, 3);\n    \n    single_measure(d64r, f64c, dr, mult, size, enabled, 4);\n    //single_measure(f64r, z64c, zr, mult, size, enabled, 5);\n    std::cout << \"0\\n\";  std::cout.flush();\n}\n\n\n\n\ntemplate <typename Measure>\nvoid series(unsigned steps, unsigned max_size, Measure measure, const string& comment)\n{\n    std::cout << \"# \" << comment << '\\n';\n    std::cout << \"# Gnu-Format size, (time, MFlops, L1, L2, TLB, time, MFlops, )*\\n\"; std::cout.flush();\n\n    std::vector<int> enabled(16, 1);\n    for (unsigned i= steps; i <= max_size; i+= steps)\n\tmeasure(i, enabled);\n}\n\n\n\nint main(int argc, char* argv[])\n{\n    papi.start();\n\n    std::vector<std::string> scenarii;\n    scenarii.push_back(string(\"Comparing Z-, N-order and mixed with recursive multiplication\"));\n    scenarii.push_back(string(\"Comparing base case cast (64) for Z-order, hybrid 32, hybrid 64 row and col-major\"));\n    scenarii.push_back(string(\"Using unrolled mult on hybrid row- and column-major matrices\"));\n    scenarii.push_back(string(\"Comparing base case sizes for corresponding hybrid row-major matrices\"));\n    scenarii.push_back(string(\"Comparing different unrolling for hybrid row-major matrices\"));\n    scenarii.push_back(string(\"Comparing different unrolling for row-major dense matrices\"));\n    scenarii.push_back(string(\"Comparing different orientations for hybrid row-major matrices\"));\n    scenarii.push_back(string(\"Comparing different unrolling for hybrid 32 row-major times col-major matrices\"));\n    scenarii.push_back(string(\"Multiplying matrices with different value types\"));\n    scenarii.push_back(string(\"Multiplying matrices with different matrix layouts\"));\n\n    using std::cout;\n    if (argc < 4) {\n\tcerr << \"usage: recursive_mult_timing <scenario> <steps> <max_size>\\nScenarii:\\n\"; \n\tfor (unsigned i= 0; i < scenarii.size(); i++)\n\t    cout << i << \": \" << scenarii[i] << \"\\n\";\n\texit(1);\n    }\n    unsigned int scenario= atoi(argv[1]), steps= atoi(argv[2]), max_size= atoi(argv[3]), size= 32; \n\n    switch (scenario) {\n      case 0: \tseries(steps, max_size, measure_morton_order, scenarii[0]); break;\n      case 1: \tseries(steps, max_size, measure_cast, scenarii[1]); break;\n      case 2: \tseries(steps, max_size, measure_with_unroll, scenarii[2]); break;\n      case 3: \tseries(steps, max_size, measure_base_size, scenarii[3]); break;\n      case 4: \tseries(steps, max_size, measure_unrolling_hybrid, scenarii[4]); break;\n      case 5: \tseries(steps, max_size, measure_unrolling_dense, scenarii[5]); break;\n      case 6: \tseries(steps, max_size, measure_orientation, scenarii[6]); break;\n      case 7: \tseries(steps, max_size, measure_unrolling_32, scenarii[7]); break;\n      case 8: \tseries(steps, max_size, measure_hetero_value, scenarii[8]); break;\n      case 9: \tseries(steps, max_size, measure_hetero_layout, scenarii[9]); break;\n    }\n\n    return 0; \n\n}\n \n\n\n\n\n\n#if 0\n\n// scheiss Kommandos\n\n// g++4 matrix_product_timing.cpp  -o matrix_product_timing -O3 -DNDEBUG -ffast-math  -mcpu=opteron -mtune=opteron -msse2 -mfpmath=sse -I${MTL_BOOST_ROOT} -I${BOOST_ROOT} -I/usr/local/include -L/usr/local/lib -lpapi -DMTL_HAS_PAPI -DMTL_HAS_BLAS  -L/u/htor/projekte/mathlibs/goto-blas -lgoto_opteron-64 -lpthread xerbla.o\n\n\n// g++4 matrix_product_timing.cpp  -o matrix_product_timing -O3 -DNDEBUG -ffast-math  -mcpu=opteron -mtune=opteron -msse2 -mfpmath=sse -I${MTL_BOOST_ROOT} -I${BOOST_ROOT} -I/usr/local/include -L/usr/local/lib -lpapi -DMTL_HAS_PAPI -DMTL_HAS_BLAS  -L/u/htor/projekte/mathlibs/acml-2-6-0-gnu-64bit/gnu64/lib -lacml -L/usr/lib/gcc/x86_64-redhat-linux/3.4.3 -lg2c\n\n// g++4 matrix_product_timing.cpp -o matrix_product_timing -O3 -DNDEBUG -ffast-math -mcpu=opteron -mtune=opteron -msse2 -mfpmath=sse -I${MTL_BOOST_ROOT} -I${BOOST_ROOT} -I/usr/local/include -L/usr/local/lib -lpapi -DMTL_HAS_PAPI -DMTL_HAS_BLAS -L/san/atlas/lib -lf77blas -latlas -L/usr/lib/gcc/x86_64-redhat-linux/3.4.3 -lg2c\n\n#endif\n", "meta": {"hexsha": "2842181efc434c2e60537a412bfc23e08799c78c", "size": 20749, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/timing/matrix_product_timing.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/timing/matrix_product_timing.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/timing/matrix_product_timing.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 40.525390625, "max_line_length": 359, "alphanum_fraction": 0.6795990168, "num_tokens": 6576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.24106884341669138}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#ifndef BOOST_MATH_FLOAT_BACKEND_HPP\n#define BOOST_MATH_FLOAT_BACKEND_HPP\n\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <cstdint>\n#include <boost/lexical_cast.hpp>\n#include <boost/math/concepts/real_concept.hpp>\n#include <boost/multiprecision/number.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n#include <boost/container_hash/hash.hpp>\n\nnamespace boost {\nnamespace multiprecision {\nnamespace backends {\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable : 4389 4244 4018 4244 4127)\n#endif\n\ntemplate <class Arithmetic>\nstruct arithmetic_backend\n{\n   typedef std::tuple<short, int, long, long long>                                 signed_types;\n   typedef std::tuple<unsigned short, unsigned, unsigned long, unsigned long long> unsigned_types;\n   typedef std::tuple<float, double, long double>                                  float_types;\n   typedef int                                                                    exponent_type;\n\n   BOOST_MP_CXX14_CONSTEXPR arithmetic_backend() : m_value(0) {}\n   BOOST_MP_CXX14_CONSTEXPR arithmetic_backend(const arithmetic_backend& o) : m_value(o.m_value) {}\n   template <class A>\n   BOOST_MP_CXX14_CONSTEXPR arithmetic_backend(const A& o, const typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A>::value >::type* = 0) : m_value(o) {}\n   template <class A>\n   BOOST_MP_CXX14_CONSTEXPR arithmetic_backend(const arithmetic_backend<A>& o) : m_value(o.data()) {}\n   BOOST_MP_CXX14_CONSTEXPR arithmetic_backend& operator=(const arithmetic_backend& o)\n   {\n      m_value = o.m_value;\n      return *this;\n   }\n   template <class A>\n   BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A>::value, arithmetic_backend&>::type operator=(A i)\n   {\n      m_value = static_cast<Arithmetic>(i);\n      return *this;\n   }\n   template <class A>\n   BOOST_MP_CXX14_CONSTEXPR arithmetic_backend& operator=(const arithmetic_backend<A>& i)\n   {\n      m_value = i.data();\n      return *this;\n   }\n   arithmetic_backend& operator=(const char* s)\n   {\n#ifndef BOOST_NO_EXCEPTIONS\n      try\n      {\n#endif\n         m_value = boost::lexical_cast<Arithmetic>(s);\n#ifndef BOOST_NO_EXCEPTIONS\n      }\n      catch (const bad_lexical_cast&)\n      {\n         throw std::runtime_error(std::string(\"Unable to interpret the string provided: \\\"\") + s + std::string(\"\\\" as a compatible number type.\"));\n      }\n#endif\n      return *this;\n   }\n   BOOST_MP_CXX14_CONSTEXPR void swap(arithmetic_backend& o)\n   {\n      std::swap(m_value, o.m_value);\n   }\n   std::string str(std::streamsize digits, std::ios_base::fmtflags f) const\n   {\n      std::stringstream ss;\n      ss.flags(f);\n      ss << std::setprecision(digits ? digits : std::numeric_limits<Arithmetic>::digits10 + 4) << m_value;\n      return ss.str();\n   }\n   BOOST_MP_CXX14_CONSTEXPR void do_negate(const std::integral_constant<bool, true>&)\n   {\n      m_value = 1 + ~m_value;\n   }\n   BOOST_MP_CXX14_CONSTEXPR void do_negate(const std::integral_constant<bool, false>&)\n   {\n      m_value = -m_value;\n   }\n   BOOST_MP_CXX14_CONSTEXPR void negate()\n   {\n      do_negate(std::integral_constant<bool, boost::multiprecision::detail::is_unsigned<Arithmetic>::value>());\n   }\n   BOOST_MP_CXX14_CONSTEXPR int compare(const arithmetic_backend& o) const\n   {\n      return m_value > o.m_value ? 1 : (m_value < o.m_value ? -1 : 0);\n   }\n   template <class A>\n   BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A>::value, int>::type compare(A i) const\n   {\n      return m_value > static_cast<Arithmetic>(i) ? 1 : (m_value < static_cast<Arithmetic>(i) ? -1 : 0);\n   }\n   BOOST_MP_CXX14_CONSTEXPR Arithmetic& data() { return m_value; }\n   BOOST_MP_CXX14_CONSTEXPR const Arithmetic& data() const { return m_value; }\n\n private:\n   Arithmetic m_value;\n};\n\ntemplate <class R, class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_integral<R>::value>::type eval_convert_to(R* result, const arithmetic_backend<Arithmetic>& backend)\n{\n   typedef typename std::common_type<R, Arithmetic>::type c_type;\n   constexpr const c_type                             max = static_cast<c_type>((std::numeric_limits<R>::max)());\n   constexpr const c_type                             min = static_cast<c_type>((std::numeric_limits<R>::min)());\n   c_type                                                   ct  = static_cast<c_type>(backend.data());\n   if ((backend.data() < 0) && !std::numeric_limits<R>::is_signed)\n      BOOST_THROW_EXCEPTION(std::range_error(\"Attempt to convert negative number to unsigned type.\"));\n   if (ct > max)\n      *result = boost::multiprecision::detail::is_signed<R>::value ? (std::numeric_limits<R>::max)() : backend.data();\n   else if (std::numeric_limits<Arithmetic>::is_signed && (ct < min))\n      *result = (std::numeric_limits<R>::min)();\n   else\n      *result = backend.data();\n}\n\ntemplate <class R, class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!boost::multiprecision::detail::is_integral<R>::value && !std::is_enum<R>::value>::type eval_convert_to(R* result, const arithmetic_backend<Arithmetic>& backend)\n{\n   *result = backend.data();\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR bool eval_eq(const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   return a.data() == b.data();\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A2>::value, bool>::type eval_eq(const arithmetic_backend<Arithmetic>& a, const A2& b)\n{\n   return a.data() == static_cast<Arithmetic>(b);\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR bool eval_lt(const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   return a.data() < b.data();\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A2>::value, bool>::type eval_lt(const arithmetic_backend<Arithmetic>& a, const A2& b)\n{\n   return a.data() < static_cast<Arithmetic>(b);\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR bool eval_gt(const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   return a.data() > b.data();\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A2>::value, bool>::type eval_gt(const arithmetic_backend<Arithmetic>& a, const A2& b)\n{\n   return a.data() > static_cast<Arithmetic>(b);\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_add(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   result.data() += o.data();\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_subtract(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   result.data() -= o.data();\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_multiply(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   result.data() *= o.data();\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<std::numeric_limits<Arithmetic>::has_infinity>::type eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   result.data() /= o.data();\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!std::numeric_limits<Arithmetic>::has_infinity>::type eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   if (!o.data())\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\n   result.data() /= o.data();\n}\n\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A2>::value>::type eval_add(arithmetic_backend<Arithmetic>& result, const A2& o)\n{\n   result.data() += o;\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A2>::value>::type eval_subtract(arithmetic_backend<Arithmetic>& result, const A2& o)\n{\n   result.data() -= o;\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A2>::value>::type eval_multiply(arithmetic_backend<Arithmetic>& result, const A2& o)\n{\n   result.data() *= o;\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<(boost::multiprecision::detail::is_arithmetic<A2>::value && !std::numeric_limits<Arithmetic>::has_infinity)>::type\neval_divide(arithmetic_backend<Arithmetic>& result, const A2& o)\n{\n   if (!o)\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\n   result.data() /= o;\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<(boost::multiprecision::detail::is_arithmetic<A2>::value && std::numeric_limits<Arithmetic>::has_infinity)>::type\neval_divide(arithmetic_backend<Arithmetic>& result, const A2& o)\n{\n   result.data() /= o;\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_add(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   result.data() = a.data() + b.data();\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_subtract(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   result.data() = a.data() - b.data();\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_multiply(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   result.data() = a.data() * b.data();\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<std::numeric_limits<Arithmetic>::has_infinity>::type eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   result.data() = a.data() / b.data();\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<!std::numeric_limits<Arithmetic>::has_infinity>::type eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   if (!b.data())\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\n   result.data() = a.data() / b.data();\n}\n\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A2>::value>::type eval_add(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const A2& b)\n{\n   result.data() = a.data() + b;\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A2>::value>::type eval_subtract(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const A2& b)\n{\n   result.data() = a.data() - b;\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_arithmetic<A2>::value>::type eval_multiply(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const A2& b)\n{\n   result.data() = a.data() * b;\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<(boost::multiprecision::detail::is_arithmetic<A2>::value && !std::numeric_limits<Arithmetic>::has_infinity)>::type\neval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const A2& b)\n{\n   if (!b)\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\n   result.data() = a.data() / b;\n}\ntemplate <class Arithmetic, class A2>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<(boost::multiprecision::detail::is_arithmetic<A2>::value && std::numeric_limits<Arithmetic>::has_infinity)>::type\neval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const A2& b)\n{\n   result.data() = a.data() / b;\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR bool eval_is_zero(const arithmetic_backend<Arithmetic>& val)\n{\n   return val.data() == 0;\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<\n    (!std::numeric_limits<Arithmetic>::is_specialized || std::numeric_limits<Arithmetic>::is_signed), int>::type\neval_get_sign(const arithmetic_backend<Arithmetic>& val)\n{\n   return val.data() == 0 ? 0 : val.data() < 0 ? -1 : 1;\n}\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<\n    !(std::numeric_limits<Arithmetic>::is_specialized || std::numeric_limits<Arithmetic>::is_signed), int>::type\neval_get_sign(const arithmetic_backend<Arithmetic>& val)\n{\n   return val.data() == 0 ? 0 : 1;\n}\n\ntemplate <class T>\ninline BOOST_MP_CXX14_CONSTEXPR typename std::enable_if<boost::multiprecision::detail::is_unsigned<T>::value, T>::type abs(T v) { return v; }\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_abs(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   using boost::multiprecision::backends::abs;\n   using std::abs;\n   result.data() = abs(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_fabs(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   result.data() = std::abs(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_floor(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = floor(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_ceil(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = ceil(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_sqrt(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = sqrt(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR int eval_fpclassify(const arithmetic_backend<Arithmetic>& o)\n{\n   return (boost::math::fpclassify)(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_trunc(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = trunc(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_round(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = round(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_frexp(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, int* v)\n{\n   BOOST_MATH_STD_USING\n   result.data() = frexp(a.data(), v);\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_ldexp(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, int v)\n{\n   BOOST_MATH_STD_USING\n   result.data() = ldexp(a.data(), v);\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_exp(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = exp(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_log(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = log(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_log10(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = log10(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_sin(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = sin(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_cos(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = cos(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_tan(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = tan(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_acos(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = acos(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_asin(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = asin(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_atan(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = atan(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_sinh(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = sinh(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_cosh(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = cosh(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_tanh(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o)\n{\n   BOOST_MATH_STD_USING\n   result.data() = tanh(o.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_fmod(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   BOOST_MATH_STD_USING\n   result.data() = fmod(a.data(), b.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_pow(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   BOOST_MATH_STD_USING\n   result.data() = pow(a.data(), b.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_atan2(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   BOOST_MATH_STD_USING\n   result.data() = atan2(a.data(), b.data());\n}\n\ntemplate <class Arithmetic, class I>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_left_shift(arithmetic_backend<Arithmetic>& result, I val)\n{\n   result.data() <<= val;\n}\n\ntemplate <class Arithmetic, class I>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_right_shift(arithmetic_backend<Arithmetic>& result, I val)\n{\n   result.data() >>= val;\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_modulus(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a)\n{\n   result.data() %= a.data();\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_bitwise_and(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a)\n{\n   result.data() &= a.data();\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_bitwise_or(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a)\n{\n   result.data() |= a.data();\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_bitwise_xor(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a)\n{\n   result.data() ^= a.data();\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_complement(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a)\n{\n   result.data() = ~a.data();\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_gcd(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   result.data() = boost::integer::gcd(a.data(), b.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR void eval_lcm(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a, const arithmetic_backend<Arithmetic>& b)\n{\n   result.data() = boost::integer::lcm(a.data(), b.data());\n}\n\ntemplate <class Arithmetic>\ninline BOOST_MP_CXX14_CONSTEXPR std::size_t hash_value(const arithmetic_backend<Arithmetic>& a)\n{\n   boost::hash<Arithmetic> hasher;\n   return hasher(a.data());\n}\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n} // namespace backends\n\nusing boost::multiprecision::backends::arithmetic_backend;\n\ntemplate <class Arithmetic>\nstruct number_category<arithmetic_backend<Arithmetic> > : public std::integral_constant<int, boost::multiprecision::detail::is_integral<Arithmetic>::value ? number_kind_integer : number_kind_floating_point>\n{};\n\nnamespace detail {\n\ntemplate <class Backend>\nstruct double_precision_type;\n\ntemplate <class Arithmetic, boost::multiprecision::expression_template_option ET>\nstruct double_precision_type<number<arithmetic_backend<Arithmetic>, ET> >\n{\n   typedef number<arithmetic_backend<typename double_precision_type<Arithmetic>::type>, ET> type;\n};\ntemplate <>\nstruct double_precision_type<arithmetic_backend<std::int32_t> >\n{\n   typedef arithmetic_backend<std::int64_t> type;\n};\n\n} // namespace detail\n\n}} // namespace boost::multiprecision\n#if !(defined(__SGI_STL_PORT) || defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS))\n//\n// We shouldn't need these to get code to compile, however for the sake of\n// \"level playing field\" performance comparisons they avoid the very slow\n// lexical_cast's that would otherwise take place.  Definition has to be guarded\n// by the inverse of pp-logic in real_concept.hpp which defines these as a workaround\n// for STLPort plus some other old/broken standartd libraries.\n//\nnamespace boost { namespace math { namespace tools {\n\ntemplate <>\ninline unsigned int real_cast<unsigned int, concepts::real_concept>(concepts::real_concept r)\n{\n   return static_cast<unsigned int>(r.value());\n}\n\ntemplate <>\ninline int real_cast<int, concepts::real_concept>(concepts::real_concept r)\n{\n   return static_cast<int>(r.value());\n}\n\ntemplate <>\ninline long real_cast<long, concepts::real_concept>(concepts::real_concept r)\n{\n   return static_cast<long>(r.value());\n}\n\n// Converts from T to narrower floating-point types, float, double & long double.\n\ntemplate <>\ninline float real_cast<float, concepts::real_concept>(concepts::real_concept r)\n{\n   return static_cast<float>(r.value());\n}\ntemplate <>\ninline double real_cast<double, concepts::real_concept>(concepts::real_concept r)\n{\n   return static_cast<double>(r.value());\n}\ntemplate <>\ninline long double real_cast<long double, concepts::real_concept>(concepts::real_concept r)\n{\n   return r.value();\n}\n\n}}} // namespace boost::math::tools\n#endif\n\nnamespace std {\n\ntemplate <class Arithmetic, boost::multiprecision::expression_template_option ExpressionTemplates>\nclass numeric_limits<boost::multiprecision::number<boost::multiprecision::arithmetic_backend<Arithmetic>, ExpressionTemplates> > : public std::numeric_limits<Arithmetic>\n{\n   typedef std::numeric_limits<Arithmetic>                                                                           base_type;\n   typedef boost::multiprecision::number<boost::multiprecision::arithmetic_backend<Arithmetic>, ExpressionTemplates> number_type;\n\n public:\n   static constexpr number_type(min)() noexcept { return (base_type::min)(); }\n   static constexpr number_type(max)() noexcept { return (base_type::max)(); }\n   static constexpr number_type lowest() noexcept { return -(max)(); }\n   static constexpr number_type epsilon() noexcept { return base_type::epsilon(); }\n   static constexpr number_type round_error() noexcept { return epsilon() / 2; }\n   static constexpr number_type infinity() noexcept { return base_type::infinity(); }\n   static constexpr number_type quiet_NaN() noexcept { return base_type::quiet_NaN(); }\n   static constexpr number_type signaling_NaN() noexcept { return base_type::signaling_NaN(); }\n   static constexpr number_type denorm_min() noexcept { return base_type::denorm_min(); }\n};\n\ntemplate <>\nclass numeric_limits<boost::math::concepts::real_concept> : public std::numeric_limits<long double>\n{\n   typedef std::numeric_limits<long double>    base_type;\n   typedef boost::math::concepts::real_concept number_type;\n\n public:\n   static const number_type(min)() noexcept { return (base_type::min)(); }\n   static const number_type(max)() noexcept { return (base_type::max)(); }\n   static const number_type lowest() noexcept { return -(max)(); }\n   static const number_type epsilon() noexcept { return base_type::epsilon(); }\n   static const number_type round_error() noexcept { return epsilon() / 2; }\n   static const number_type infinity() noexcept { return base_type::infinity(); }\n   static const number_type quiet_NaN() noexcept { return base_type::quiet_NaN(); }\n   static const number_type signaling_NaN() noexcept { return base_type::signaling_NaN(); }\n   static const number_type denorm_min() noexcept { return base_type::denorm_min(); }\n};\n\n} // namespace std\n\n#include <boost/multiprecision/detail/integer_ops.hpp>\n\n#endif\n", "meta": {"hexsha": "12698335dd96d95e3759c36ad5126d960e755a6d", "size": 26000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/arithmetic_backend.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/arithmetic_backend.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "lib/boost_1.78.0/libs/multiprecision/performance/arithmetic_backend.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 39.039039039, "max_line_length": 243, "alphanum_fraction": 0.7498846154, "num_tokens": 6241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2410557442266242}}
{"text": "#include <byteswap.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <vector>\n#include <Eigen/Dense>\n#include \"imu/imu.h\"\n\nusing Eigen::Matrix4f;\nusing Eigen::Vector3f;\nusing Eigen::Vector4f;\n\nnamespace {\nconst uint8_t ADDR_ITG3200  = 0x68;\nconst uint8_t ADDR_HMC5883L = 0x1e;\nconst uint8_t ADDR_ADXL345  = 0x53;\n\nconst Vector3f gyrocal_b(-182.11, -179.32, -212.83);\nconst Vector3f gyrocal_m(-0.01169, -0.01123, -0.01164);\nconst float pointcloud_dist = 200.0f;\n\nbool CheckPointCloud(const Vector3f& pt, std::vector<Vector3f> *pointcloud) {\n  for (int i = 0; i < pointcloud->size(); i++) {\n    if (((*pointcloud)[i] - pt).squaredNorm() <\n        pointcloud_dist*pointcloud_dist) {\n      return false;\n    }\n  }\n  pointcloud->push_back(pt);\n  return true;\n}\n\n}  // empty namespace\n\n// our motion model should figure out whether the car is on the ground (1g down\n// on the accelerometer) or flying off a ramp (0g); if it's on the ground and\n// the motor is stopped (0 estimated velocity) then we can zero out the gyro,\n// and calibrate the direction of the accelerometer Y direction.\n\nbool IMU::Init() {\n  mag_XTX_ = 0.01 * Matrix4f::Identity();\n  mag_XTY_ = Vector4f::Zero();\n  mag_bias_ = Vector3f::Zero();\n\n  // config gyro\n  i2c_.Write(ADDR_ITG3200, 0x3E, 0x01);  // use X gyro PLL oscillator\n  i2c_.Write(ADDR_ITG3200, 0x15, 19);    // samplerate 50Hz (1000/(19+1))\n  i2c_.Write(ADDR_ITG3200, 0x16, 0x18 + 4);  // enable, 20Hz bandwidth\n  // config compass\n  i2c_.Write(ADDR_HMC5883L, 0x00, 0x38);  // CRA: 75Hz rate w/ 2 averages\n  i2c_.Write(ADDR_HMC5883L, 0x01, 0x20);  // CRB: set gain 1090 LSB/Gauss\n  i2c_.Write(ADDR_HMC5883L, 0x02, 0x00);  // continuous measurement\n  // config accelerometer\n  i2c_.Write(ADDR_ADXL345, 0x2c, 0x09);  // 25Hz bw, 50Hz samplerate\n  i2c_.Write(ADDR_ADXL345, 0x31, 0x08);  // FULL_RES\n  i2c_.Write(ADDR_ADXL345, 0x38, 0x00);  // bypass FIFO, sample @ 50Hz\n  i2c_.Write(ADDR_ADXL345, 0x2d, 0x08);  // turn on\n\n  return true;\n}\n\nbool IMU::ReadRaw(IMURawState *s) {\n  uint8_t axis_buf[8];\n  if (!i2c_.Read(ADDR_ITG3200, 0x1b, axis_buf, 8))\n    return false;\n  // temperature is 280 LSB/deg C, -13200 LSB @35 C\n  s->gyro_temp = bswap_16(*reinterpret_cast<uint16_t*>(axis_buf+0));\n  s->gyro_x = bswap_16(*reinterpret_cast<uint16_t*>(axis_buf+2));  // roll\n  s->gyro_y = bswap_16(*reinterpret_cast<uint16_t*>(axis_buf+4));  // pitch\n  s->gyro_z = bswap_16(*reinterpret_cast<uint16_t*>(axis_buf+6));  // yaw\n\n  if (!i2c_.Read(ADDR_HMC5883L, 0x03, axis_buf, 6))\n    return false;\n  s->mag_x = bswap_16(*reinterpret_cast<uint16_t*>(axis_buf+0));  // front?\n  s->mag_z = bswap_16(*reinterpret_cast<uint16_t*>(axis_buf+2));  // up\n  s->mag_y = bswap_16(*reinterpret_cast<uint16_t*>(axis_buf+4));  // side?\n\n  if (!i2c_.Read(ADDR_ADXL345, 0x32, axis_buf, 6))\n    return false;\n  s->accel_x = (*reinterpret_cast<uint16_t*>(axis_buf+0));  // toward back\n  s->accel_y = (*reinterpret_cast<uint16_t*>(axis_buf+2));  // toward right\n  s->accel_z = (*reinterpret_cast<uint16_t*>(axis_buf+4));  // toward ground\n\n  return true;\n}\n\nbool IMU::ReadCalibrated(IMUState *s) {\n  IMURawState rawstate;\n  if (!ReadRaw(&rawstate))\n    return false;\n\n  Calibrate(rawstate, s);\n  return true;\n}\n\n// all devices are oriented such that X is to the front of the car, Y is to\n// the left, and Z is up.\nvoid IMU::Calibrate(const IMURawState &s, IMUState *state) {\n  // gyro offset calibration (rough -- needs work)\n  Vector3f w0(-s.gyro_y, -s.gyro_z, s.gyro_x);\n  w0 -= gyrocal_b + s.gyro_temp * gyrocal_m;\n  // scale to radians/second\n  state->w = w0 * M_PI / (180.0 * 14.375);\n\n  // magnetometer calibration via least-squares fit sphere\n  // TODO: fix the axes (i think x and z are swapped and one is negated)\n  Vector3f m(s.mag_x, s.mag_y, s.mag_z);\n  // if there's room in the point cloud for this new point, update calibration\n  if (CheckPointCloud(m, &mag_cal_points_)) {\n    Vector4f b(s.mag_x, s.mag_y, s.mag_z, 1);\n    mag_XTX_ += b * b.transpose();\n    float bmag = b.squaredNorm();\n    mag_XTY_ += bmag * b;\n    Vector4f beta = mag_XTX_.ldlt().solve(mag_XTY_);\n    mag_bias_ = beta.block<3, 1>(0, 0) / 2;\n    bmag = sqrt(beta[3] + mag_bias_.squaredNorm());\n    fprintf(stderr, \"imu: updated mag calibration [%f %f %f] R=%f\\n\",\n            beta[0] / 2, beta[1] / 2, beta[2] / 2, bmag);\n  }\n  state->N = m - mag_bias_;\n\n  // TODO: verify axes\n  state->g = Vector3f(-s.accel_y, -s.accel_z, -s.accel_x);\n}\n", "meta": {"hexsha": "6411411f06b116157c87c361e39d876d12e1f8b4", "size": 4417, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/hw/imu/generic9dof.cc", "max_stars_repo_name": "ParikhKadam/cycloid", "max_stars_repo_head_hexsha": "c5e64e8379f801417a38755eb6b2fde881dabd8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 156.0, "max_stars_repo_stars_event_min_datetime": "2017-08-12T03:58:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:38:52.000Z", "max_issues_repo_path": "src/hw/imu/generic9dof.cc", "max_issues_repo_name": "ParikhKadam/cycloid", "max_issues_repo_head_hexsha": "c5e64e8379f801417a38755eb6b2fde881dabd8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-12-11T11:31:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-05T18:43:51.000Z", "max_forks_repo_path": "src/hw/imu/generic9dof.cc", "max_forks_repo_name": "ParikhKadam/cycloid", "max_forks_repo_head_hexsha": "c5e64e8379f801417a38755eb6b2fde881dabd8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2017-08-17T02:05:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T20:54:27.000Z", "avg_line_length": 35.6209677419, "max_line_length": 79, "alphanum_fraction": 0.676477247, "num_tokens": 1586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2410027997701847}}
{"text": "/*\n    Copyright (c) 2011-2014 University of Zurich\n    \n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights\n    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n    copies of the Software, and to permit persons to whom the Software is\n    furnished to do so, subject to the following conditions:\n    \n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n    \n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n    THE SOFTWARE.\n*/\n\n#include <plll/config.hpp>\n#include \"lll2-internal.hpp\"\n#include \"transform.cpp\"\n\n#include <sstream>\n#include <boost/bind.hpp>\n\n#include <plll/arithmetic.hpp>\n#include <plll/rational.hpp>\n#if !defined(PLLL_CONFIG_NO_ARITHMETIC_LONGDOUBLE) || !defined(PLLL_CONFIG_NO_ARITHMETIC_DOUBLE)\n  #include \"nfp-wrapper.hpp\"\n#endif\n#if !defined(PLLL_CONFIG_NO_ARITHMETIC_QUADDOUBLE) || !defined(PLLL_CONFIG_NO_ARITHMETIC_DOUBLEDOUBLE)\n  #include \"ddqd-wrapper.hpp\"\n#endif\n\nnamespace plll\n{\n    class LRIISelector : public LRIInterface\n    {\n    private:\n        class Interface\n        {\n        private:\n            long d_max_bits;\n            boost::function<LRIInterface*(linalg::math_matrix<arithmetic::Integer> &)> d_interface_generator;\n            mutable const LatticeReduction::GramSchmidtInformer * d_gsi;\n            \n        public:\n            Interface(long max_bits, boost::function<LRIInterface*(linalg::math_matrix<arithmetic::Integer> &)> interfacegen)\n                : d_max_bits(max_bits), d_interface_generator(interfacegen), d_gsi(NULL)\n            {\n            }\n            \n            ~Interface()\n            {\n            }\n            \n            LRIInterface * generateInterface(linalg::math_matrix<arithmetic::Integer> & matrix) const\n            {\n                return d_interface_generator(matrix);\n            }\n            \n            long maxSupportedBits() const\n            {\n                return d_max_bits;\n            }\n            \n            bool isFine(unsigned bits, unsigned dimension) const\n            {\n                long bits_needed = 2 * bits + arithmetic::approxLog2(dimension) + 4;\n                return bits_needed <= d_max_bits;\n            }\n        };\n        \n        std::list<Interface> d_interfaces;\n        mutable std::list<Interface>::const_iterator d_interface_gen, d_better_interface_gen;\n        mutable STD_AUTO_PTR<LRIInterface> d_interface;\n        mutable bool d_continue, d_reselect;\n        mutable MaxBitsCallbackFunction d_maxbitscf;\n        \n        inline bool isBetter(unsigned bits, unsigned dimension) const\n        {\n            return (d_better_interface_gen == d_interfaces.end()) ? false : d_better_interface_gen->isFine(bits, dimension);\n        }        \n        \n        void maxBitsCallbackFunction(unsigned dimension, unsigned maxbits)\n        {\n            if (!d_maxbitscf.empty())\n                d_maxbitscf(dimension, maxbits);\n            if (d_verbose_function && Verbose::yieldsOutput(d_verbose_outputlevel, LatticeReduction::VL_Chatter))\n            {\n                std::ostringstream s;\n                s << \"...base has \" << maxbits << \" bits...\";\n                d_verbose_function(LatticeReduction::VL_Chatter, s.str());\n            }\n            if (!d_interface_gen->isFine(maxbits, dimension) || isBetter(maxbits, dimension))\n            {\n                d_reselect = true;\n                throw change_interface_exception();\n            }\n        }\n        \n        bool isContinuing() const\n        {\n            if (d_reselect)\n                selectInterface(true);\n            bool v = d_continue;\n            d_continue = false;\n            return v;\n        }\n        \n        unsigned maxBits() const\n        {\n            unsigned maxbits = 0;\n            for (unsigned i = 0; i < d_lattice.rows(); ++i)\n                for (unsigned j = 0; j < d_lattice.cols(); ++j)\n                {\n                    long b = arithmetic::approxLog2(d_lattice(i, j));\n                    if (b > maxbits)\n                        maxbits = b;\n                }\n            return maxbits;\n        }\n        \n        void selectInterface(bool withContinue = false) const\n        {\n            if (d_interface.get())\n            {\n                if (d_verbose_function && Verbose::yieldsOutput(d_verbose_outputlevel, LatticeReduction::VL_Information))\n                    d_verbose_function(LatticeReduction::VL_Information, \"Applying interface change\");\n                d_interface.reset();\n            }\n            \n            d_continue = withContinue;\n            d_reselect = false;\n            unsigned bits = maxBits();\n            d_interface_gen = d_interfaces.end();\n            for (std::list<Interface>::const_iterator i = d_interfaces.begin(); i != d_interfaces.end(); ++i)\n            {\n                if (i->isFine(bits, d_lattice.rows()))\n                    d_interface_gen = i;\n            }\n            assert(d_interface_gen != d_interfaces.end());\n            \n            if (d_verbose_function && Verbose::yieldsOutput(d_verbose_outputlevel, LatticeReduction::VL_Information))\n            {\n                std::ostringstream s;\n                s << \"Selecting interface which supports up to \" << d_interface_gen->maxSupportedBits() << \" bits\";\n                d_verbose_function(LatticeReduction::VL_Information, s.str());\n            }\n            \n            // Generate interface\n            d_interface.reset(d_interface_gen->generateInterface(d_lattice));\n            if (d_ensure_min_prec)\n                d_interface->ensureMinimumPrecision(d_min_prec);\n            if (d_set_verbose)\n                d_interface->setupVerbose(d_verbose_outputlevel, d_verbose_function);\n            \n            // Select next interface\n            d_better_interface_gen = d_interface_gen;\n            ++d_better_interface_gen;\n        }\n        \n        const LRIInterface & getInterface() const\n        {\n            return *d_interface;\n        }\n        \n        LRIInterface & getInterface()\n        {\n            return *d_interface;\n        }        \n        \n        void unselectInterface() const\n        {\n            d_interface.reset();\n        }\n        \n        class GSI : public LatticeReduction::GramSchmidtInformer\n        {\n        private:\n            LRIISelector & d_selector;\n            \n        public:\n            GSI(LRIISelector & selector)\n                : d_selector(selector)\n            {\n            }\n            \n            virtual ~GSI()\n            {\n            }\n            \n            virtual double getGSCoefficientD(unsigned i, unsigned j) const\n            {\n                d_selector.selectInterface();\n                double r = d_selector.getInterface().getInformer()->getGSCoefficientD(i, j);\n                d_selector.unselectInterface();\n                return r;\n            }\n            \n            virtual long double getGSCoefficientLD(unsigned i, unsigned j) const\n            {\n                d_selector.selectInterface();\n                long double r = d_selector.getInterface().getInformer()->getGSCoefficientLD(i, j);\n                d_selector.unselectInterface();\n                return r;\n            }\n            \n            virtual arithmetic::Real getGSCoefficientR(unsigned i, unsigned j, const arithmetic::RealContext & rc) const\n            {\n                d_selector.selectInterface();\n                arithmetic::Real r = d_selector.getInterface().getInformer()->getGSCoefficientR(i, j, rc);\n                d_selector.unselectInterface();\n                return r;\n            }\n            \n            virtual double getGSSqNormD(unsigned i) const\n            {\n                d_selector.selectInterface();\n                double r = d_selector.getInterface().getInformer()->getGSSqNormD(i);\n                d_selector.unselectInterface();\n                return r;\n            }\n            \n            virtual long double getGSSqNormLD(unsigned i) const\n            {\n                d_selector.selectInterface();\n                long double r = d_selector.getInterface().getInformer()->getGSSqNormLD(i);\n                d_selector.unselectInterface();\n                return r;\n            }\n            \n            virtual arithmetic::Real getGSSqNormR(unsigned i, const arithmetic::RealContext & rc) const\n            {\n                d_selector.selectInterface();\n                arithmetic::Real r = d_selector.getInterface().getInformer()->getGSSqNormR(i, rc);\n                d_selector.unselectInterface();\n                return r;\n            }\n            \n            virtual double computeProjectionLengthD(unsigned k, unsigned b, const linalg::math_rowvector<arithmetic::Integer> & vec) const\n            {\n                d_selector.selectInterface();\n                double r = d_selector.getInterface().getInformer()->computeProjectionLengthD(k, b, vec);\n                d_selector.unselectInterface();\n                return r;\n            }\n            \n            virtual long double computeProjectionLengthLD(unsigned k, unsigned b, const linalg::math_rowvector<arithmetic::Integer> & vec) const\n            {\n                d_selector.selectInterface();\n                long double r = d_selector.getInterface().getInformer()->computeProjectionLengthLD(k, b, vec);\n                d_selector.unselectInterface();\n                return r;\n            }\n            \n            virtual arithmetic::Real computeProjectionLengthR(unsigned k, unsigned b, const linalg::math_rowvector<arithmetic::Integer> & vec, const arithmetic::RealContext & rc) const\n            {\n                d_selector.selectInterface();\n                arithmetic::Real r = d_selector.getInterface().getInformer()->computeProjectionLengthR(k, b, vec, rc);\n                d_selector.unselectInterface();\n                return r;\n            }\n        };\n        \n        friend class GSI;\n        \n        GSI d_gsi;\n        \n        bool d_ensure_min_prec;\n        unsigned long d_min_prec;\n        \n        bool d_set_verbose;\n        LatticeReduction::VerboseOutputLevel d_verbose_outputlevel;\n        LatticeReduction::VerboseFunction d_verbose_function;\n        \n    public:\n        LRIISelector(linalg::math_matrix<arithmetic::Integer> & lattice, LatticeReduction::VerboseOutputLevel vol, LatticeReduction::VerboseFunction vf)\n            : LRIInterface(lattice), d_interface(), d_continue(false), d_reselect(false), d_gsi(*this),\n              d_ensure_min_prec(false), d_min_prec(0), d_set_verbose(false), d_verbose_outputlevel(vol), d_verbose_function(vf)\n        {\n        }\n        \n        virtual ~LRIISelector()\n        {\n        }\n        \n        void addInterface(long max_bits, boost::function<LRIInterface*(linalg::math_matrix<arithmetic::Integer> &)> interfacegen)\n        {\n            d_interfaces.push_back(Interface(max_bits, interfacegen));\n        }\n        \n        virtual void setupVerbose(LatticeReduction::VerboseOutputLevel vol, LatticeReduction::VerboseFunction vf)\n        {\n            d_set_verbose = true;\n            d_verbose_outputlevel = vol;\n            d_verbose_function = vf;\n        }\n        \n        virtual const LatticeReduction::GramSchmidtInformer * getInformer() const\n        {\n            return &d_gsi;\n        }\n        \n        virtual void ensureMinimumPrecision(unsigned long prec)\n        {\n            d_ensure_min_prec = prec;\n            d_min_prec = prec;\n        }\n        \n        virtual void forceGSRebuild(bool b)\n        {\n        }\n        \n        virtual double getGSCoefficientD(unsigned i, unsigned j) const\n        {\n            selectInterface();\n            double r = getInterface().getGSCoefficientD(i, j);\n            unselectInterface();\n            return r;\n        }\n        \n        virtual long double getGSCoefficientLD(unsigned i, unsigned j) const\n        {\n            selectInterface();\n            long double r = getInterface().getGSCoefficientLD(i, j);\n            unselectInterface();\n            return r;\n        }\n        \n        virtual arithmetic::Real getGSCoefficientR(unsigned i, unsigned j, const arithmetic::RealContext & rc) const\n        {\n            selectInterface();\n            arithmetic::Real r = getInterface().getGSCoefficientR(i, j, rc);\n            unselectInterface();\n            return r;\n        }\n        \n        virtual double getGSSqNormD(unsigned i) const\n        {\n            selectInterface();\n            double r = getInterface().getGSSqNormD(i);\n            unselectInterface();\n            return r;\n        }\n        \n        virtual long double getGSSqNormLD(unsigned i) const\n        {\n            selectInterface();\n            long double r = getInterface().getGSSqNormLD(i);\n            unselectInterface();\n            return r;\n        }\n        \n        virtual arithmetic::Real getGSSqNormR(unsigned i, const arithmetic::RealContext & rc) const\n        {\n            selectInterface();\n            arithmetic::Real r = getInterface().getGSSqNormR(i, rc);\n            unselectInterface();\n            return r;\n        }\n        \n        virtual void modFlip(Transform & transform, unsigned i)\n        {\n            selectInterface();\n            getInterface().modFlip(transform, i);\n            unselectInterface();\n        }\n        \n        virtual void modSwap(Transform & transform, unsigned i, unsigned j)\n        {\n            selectInterface();\n            getInterface().modSwap(transform, i, j);\n            unselectInterface();\n        }\n        \n        virtual void modAdd(Transform & transform, unsigned i, unsigned j, const arithmetic::Integer & m)\n        {\n            selectInterface();\n            getInterface().modAdd(transform, i, j, m);\n            unselectInterface();\n        }\n        \n        virtual void sortProjected(unsigned & begin, unsigned & end, Transform & transform)\n        {\n            selectInterface();\n            getInterface().sortProjected(begin, end, transform);\n            unselectInterface();\n        }\n        \n        virtual void sizereduction(unsigned & begin, unsigned & end, Transform & transform)\n        {\n            selectInterface();\n            getInterface().sizereduction(begin, end, transform);\n            unselectInterface();\n        }\n        \n        virtual void lll(unsigned & begin, unsigned & end, Transform & transform, double alpha, LatticeReduction::LLLMode mode,\n                         LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                         LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                         MaxBitsCallbackFunction mbcf, bool anneal, LatticeReduction::AnnealCallbackFunction acf,\n                         LatticeReduction::LLL_AnnealFunction af, LatticeReduction::DIMethod di, LatticeReduction::DIMode di_mode,\n                         LatticeReduction::DIChoice di_choice, unsigned di_bs)\n        {\n            selectInterface(true);\n            d_maxbitscf = mbcf;\n            while (isContinuing())\n                getInterface().lll(begin, end, transform, alpha, mode, cf, cf2, cf_int, mcf, mcf2,\n                                   boost::bind(&LRIISelector::maxBitsCallbackFunction, this, _1, _2),\n                                   anneal, acf, af, di, di_mode, di_choice, di_bs);\n            unselectInterface();\n        }\n        \n        virtual void bkz(unsigned & begin, unsigned & end, Transform & transform, double alpha, unsigned blocksize, LatticeReduction::BKZMode mode,\n                         LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                         LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2, MaxBitsCallbackFunction mbcf,\n                         LatticeReduction::EnumCallbackFunction ecf, LatticeReduction::EnumCallbackFunction_LI ecf2, bool anneal,\n                         LatticeReduction::AnnealCallbackFunction acf, LatticeReduction::BKZ_AnnealFunction af,\n                         LatticeReduction::DIMethod di, LatticeReduction::DIMode di_mode, LatticeReduction::DIChoice di_choice, unsigned di_bs)\n        {\n            selectInterface(true);\n            d_maxbitscf = mbcf;\n            while (isContinuing())\n                getInterface().bkz(begin, end, transform, alpha, blocksize, mode, cf, cf2, cf_int, mcf, mcf2,\n                                   boost::bind(&LRIISelector::maxBitsCallbackFunction, this, _1, _2),\n                                   ecf, ecf2, anneal, acf, af, di, di_mode, di_choice, di_bs);\n            unselectInterface();\n        }\n        \n        virtual void hkz(unsigned & begin, unsigned & end, Transform & transform, bool dual,\n                         LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                         LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                         MaxBitsCallbackFunction mbcf,\n                         LatticeReduction::EnumCallbackFunction ecf, LatticeReduction::EnumCallbackFunction_LI ecf2)\n        {\n            selectInterface(true);\n            d_maxbitscf = mbcf;\n            while (isContinuing())\n                getInterface().hkz(begin, end, transform, dual, cf, cf2, cf_int, mcf, mcf2,\n                                   boost::bind(&LRIISelector::maxBitsCallbackFunction, this, _1, _2),\n                                   ecf, ecf2);\n            unselectInterface();\n        }\n        \n        virtual void svp(unsigned & begin, unsigned & end, Transform & transform, bool make_basis, bool extreme, bool dual,\n                         LatticeReduction::CallbackFunction cf, LatticeReduction::CallbackFunction_LI cf2, double cf_int,\n                         LatticeReduction::MinCallbackFunction mcf, LatticeReduction::MinCallbackFunction_LI mcf2,\n                         MaxBitsCallbackFunction mbcf,\n                         LatticeReduction::EnumCallbackFunction ecf, LatticeReduction::EnumCallbackFunction_LI ecf2)\n        {\n            selectInterface(true);\n            d_maxbitscf = mbcf;\n            while (isContinuing())\n                getInterface().svp(begin, end, transform, make_basis, extreme, dual, cf, cf2, cf_int, mcf, mcf2,\n                                   boost::bind(&LRIISelector::maxBitsCallbackFunction, this, _1, _2),\n                                   ecf, ecf2);\n            unselectInterface();\n        }\n        \n        virtual bool isSizeReduced(unsigned begin, unsigned end) const\n        {\n            selectInterface();\n            bool ret = getInterface().isSizeReduced(begin, end);\n            unselectInterface();\n            return ret;\n        }\n        \n        virtual bool isLLLBasis(unsigned begin, unsigned end, double alpha, LatticeReduction::LLLMode mode,\n                                LatticeReduction::DIMethod di, LatticeReduction::DIChoice di_choice, unsigned di_bs) const\n        {\n            selectInterface();\n            bool ret = getInterface().isLLLBasis(begin, end, alpha, mode, di, di_choice, di_bs);\n            unselectInterface();\n            return ret;\n        }\n        \n        virtual bool isBKZBasis(unsigned begin, unsigned end, double alpha, unsigned blocksize, LatticeReduction::BKZMode mode,\n                                LatticeReduction::DIMethod di, LatticeReduction::DIChoice di_choice, unsigned di_bs) const\n        {\n            selectInterface();\n            bool ret = getInterface().isBKZBasis(begin, end, alpha, blocksize, mode, di, di_choice, di_bs);\n            unselectInterface();\n            return ret;\n        }\n        \n        virtual bool isHKZBasis(unsigned begin, unsigned end, bool dual) const\n        {\n            selectInterface();\n            bool ret = getInterface().isHKZBasis(begin, end, dual);\n            unselectInterface();\n            return ret;\n        }\n        \n        virtual bool isSVPBasis(unsigned begin, unsigned end, bool dual) const\n        {\n            selectInterface();\n            bool ret = getInterface().isSVPBasis(begin, end, dual);\n            unselectInterface();\n            return ret;\n        }\n    };\n    \n    template<class RealTypeContext, class IntTypeContext>\n    LRIInterface * CreateLRIInterfaceWithContexts(LatticeReduction::VerboseOutputLevel vol, LatticeReduction::VerboseFunction vf,\n                                                  linalg::math_matrix<arithmetic::Integer> & lattice, LatticeReduction::GramSchmidt gs, bool gsr,\n                                                  LatticeReduction::SVPMode svp, unsigned max_cores,\n                                                  const RealTypeContext & rc, const IntTypeContext & ic);\n    \n    template<class RealTypeContext>\n    LRIInterface * CreateLRIInterface(LatticeReduction::VerboseOutputLevel vol, LatticeReduction::VerboseFunction vf,\n                                      linalg::math_matrix<arithmetic::Integer> & lattice, LatticeReduction::GramSchmidt gs, bool gsr,\n                                      LatticeReduction::SVPMode svp, unsigned max_cores,\n                                      LatticeReduction::Integers ints, const RealTypeContext & rc)\n    {\n        switch (ints)\n        {\n#if !defined(PLLL_CONFIG_NO_ARITHMETIC_BIGINT) && !defined(PLLL_CONFIG_NO_ARITHMETIC_LONGINT)\n        case LatticeReduction::I_Auto:\n        {\n            LRIISelector * sel = new LRIISelector(lattice, vol, vf);\n            // Add in decreasing order of supported precisions\n            sel->addInterface(std::numeric_limits<long>::max(),\n                              boost::bind(CreateLRIInterfaceWithContexts<RealTypeContext, arithmetic::IntegerContext>,\n                                          vol, vf, _1, gs, gsr, svp, max_cores, rc, arithmetic::IntegerContext()));\n            sel->addInterface(std::numeric_limits<long int>::digits - 1,\n                              boost::bind(CreateLRIInterfaceWithContexts<RealTypeContext, arithmetic::NIntContext<long int> >,\n                                          vol, vf, _1, gs, gsr, svp, max_cores, rc, arithmetic::NIntContext<long int>()));\n            return sel;\n        }\n#endif\n#ifndef PLLL_CONFIG_NO_ARITHMETIC_BIGINT\n        case LatticeReduction::I_ArbitraryPrecision:\n            return CreateLRIInterfaceWithContexts(vol, vf, lattice, gs, gsr, svp, max_cores, rc, arithmetic::IntegerContext());\n#endif\n#ifndef PLLL_CONFIG_NO_ARITHMETIC_LONGINT\n        case LatticeReduction::I_LongInt:\n            return CreateLRIInterfaceWithContexts(vol, vf, lattice, gs, gsr, svp, max_cores, rc, arithmetic::NIntContext<long int>());\n#endif\n        }\n        assert(!\"Integer arithmetic not supported!\");\n        return NULL;\n    }\n    \n    LRIInterface * CreateLRIInterface(LatticeReduction::VerboseOutputLevel vol, LatticeReduction::VerboseFunction vf,\n                                      linalg::math_matrix<arithmetic::Integer> & lattice,\n                                      LatticeReduction::Arithmetic arith, LatticeReduction::Integers ints,\n                                      LatticeReduction::GramSchmidt gs, bool gsr,\n                                      LatticeReduction::SVPMode svp, unsigned max_cores)\n    {\n        switch(arith)\n        {\n        default:\n#ifndef PLLL_CONFIG_NO_ARITHMETIC_LONGDOUBLE\n        case LatticeReduction::A_LongDouble:   return CreateLRIInterface(vol, vf, lattice, gs, gsr, svp, max_cores, ints, arithmetic::NFPContext<long double>());\n#endif\n#ifndef PLLL_CONFIG_NO_ARITHMETIC_REAL\n        case LatticeReduction::A_Real:         return CreateLRIInterface(vol, vf, lattice, gs, gsr, svp, max_cores, ints, arithmetic::RealContext());\n#endif\n#ifndef PLLL_CONFIG_NO_ARITHMETIC_RATIONAL\n        case LatticeReduction::A_Rational:     return CreateLRIInterface(vol, vf, lattice, gs, gsr, svp, max_cores, ints, arithmetic::RationalContext());\n#endif\n#ifndef PLLL_CONFIG_NO_ARITHMETIC_DOUBLE\n        case LatticeReduction::A_Double:       return CreateLRIInterface(vol, vf, lattice, gs, gsr, svp, max_cores, ints, arithmetic::NFPContext<double>());\n#endif\n#ifndef PLLL_CONFIG_NO_ARITHMETIC_DOUBLEDOUBLE\n        case LatticeReduction::A_DoubleDouble: return CreateLRIInterface(vol, vf, lattice, gs, gsr, svp, max_cores, ints, arithmetic::DDQDContext<dd_real>());\n#endif\n#ifndef PLLL_CONFIG_NO_ARITHMETIC_QUADDOUBLE\n        case LatticeReduction::A_QuadDouble:   return CreateLRIInterface(vol, vf, lattice, gs, gsr, svp, max_cores, ints, arithmetic::DDQDContext<qd_real>());\n#endif\n        }\n        assert(!\"Real arithmetic not supported!\");\n        return NULL;\n    }\n    \n    // Explicit instantiation of templates\n    \n#ifndef PLLL_CONFIG_NO_ARITHMETIC_BIGINT\n    template void setUnit<arithmetic::IntegerContext>(linalg::math_matrix<arithmetic::Integer> &);\n#endif\n    \n#ifndef PLLL_CONFIG_NO_ARITHMETIC_LONGINT\n    template void setUnit<arithmetic::NIntContext<long> >(linalg::math_matrix<arithmetic::NInt<long> > &);\n#endif\n}\n", "meta": {"hexsha": "36f946f3bd778bffe4b998c60a48cd3b55eec55c", "size": 25692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "plll/src/lattices/lll2-multiplexer.cpp", "max_stars_repo_name": "KudrinMatvey/myfplll", "max_stars_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "plll/src/lattices/lll2-multiplexer.cpp", "max_issues_repo_name": "KudrinMatvey/myfplll", "max_issues_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plll/src/lattices/lll2-multiplexer.cpp", "max_forks_repo_name": "KudrinMatvey/myfplll", "max_forks_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5457627119, "max_line_length": 184, "alphanum_fraction": 0.5875369765, "num_tokens": 5454, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.38491213037224875, "lm_q1q2_score": 0.24100279093451768}}
{"text": "// This file is part of the dune-stuff project:\n//   https://github.com/wwu-numerik/dune-stuff\n// Copyright holders: Rene Milk, Felix Schindler\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n//\n// Contributors: Sven Kaulmann\n\n#ifndef DUNE_STUFF_COMMON_MATRIX_HH\n#define DUNE_STUFF_COMMON_MATRIX_HH\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/dynmatrix.hh>\n#include <dune/common/fmatrix.hh>\n\n#include <dune/stuff/common/exceptions.hh>\n#include <dune/stuff/common/fmatrix.hh>\n#include <dune/stuff/common/vector.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n/**\n * \\brief Traits to statically extract the information of a (mathematical) matrix.\n *\n *        If you want your matrix class to benefit from the operators defined in this header you have to manually\n *        specify a specialization of this class in your code with is_matrix defined to true and an appropriate\n *        static methods and members (see the specializations below).\n */\ntemplate <class MatType>\nstruct MatrixAbstraction\n{\n  typedef MatType MatrixType;\n  typedef MatType ScalarType;\n  typedef MatType S;\n\n  static const bool is_matrix = false;\n\n  static const bool has_static_size = false;\n\n  static const size_t static_rows = std::numeric_limits<size_t>::max();\n\n  static const size_t static_cols = std::numeric_limits<size_t>::max();\n\n  static inline /*MatrixType*/ void create(const size_t /*rows*/, const size_t /*cols*/)\n  {\n    static_assert(AlwaysFalse<MatType>::value, \"Do not call me if is_matrix is false!\");\n  }\n\n  static inline /*MatrixType*/ void create(const size_t /*rows*/, const size_t /*cols*/, const ScalarType& /*val*/)\n  {\n    static_assert(AlwaysFalse<MatType>::value, \"Do not call me if is_matrix is false!\");\n  }\n\n  static inline /*size_t*/ void rows(const MatrixType& /*mat*/)\n  {\n    static_assert(AlwaysFalse<MatType>::value, \"Do not call me if is_matrix is false!\");\n  }\n\n  static inline /*size_t*/ void cols(const MatrixType& /*mat*/)\n  {\n    static_assert(AlwaysFalse<MatType>::value, \"Do not call me if is_matrix is false!\");\n  }\n\n  static inline void set_entry(MatrixType& /*mat*/, const size_t /*row*/, const size_t /*col*/,\n                               const ScalarType& /*val*/)\n  {\n    static_assert(AlwaysFalse<MatType>::value, \"Do not call me if is_matrix is false!\");\n  }\n\n  static inline /*ScalarType*/ void get_entry(const MatrixType& /*mat*/, const size_t /*row*/, const size_t /*col*/)\n  {\n    static_assert(AlwaysFalse<MatType>::value, \"Do not call me if is_matrix is false!\");\n  }\n};\n\ntemplate <class K>\nstruct MatrixAbstraction<Dune::DynamicMatrix<K>>\n{\n  typedef Dune::DynamicMatrix<K> MatrixType;\n  typedef K ScalarType;\n  typedef ScalarType S;\n\n  static const bool is_matrix = true;\n\n  static const bool has_static_size = false;\n\n  static const size_t static_rows = std::numeric_limits<size_t>::max();\n\n  static const size_t static_cols = std::numeric_limits<size_t>::max();\n\n  static inline MatrixType create(const size_t rows, const size_t cols) { return MatrixType(rows, cols); }\n\n  static inline MatrixType create(const size_t rows, const size_t cols, const ScalarType& val)\n  {\n    return MatrixType(rows, cols, val);\n  }\n\n  static inline size_t rows(const MatrixType& mat) { return mat.rows(); }\n\n  static inline size_t cols(const MatrixType& mat) { return mat.cols(); }\n\n  static inline void set_entry(MatrixType& mat, const size_t row, const size_t col, const ScalarType& val)\n  {\n    mat[row][col] = val;\n  }\n\n  static inline ScalarType get_entry(const MatrixType& mat, const size_t row, const size_t col)\n  {\n    return mat[row][col];\n  }\n};\n\ntemplate <class K, int N, int M>\nstruct MatrixAbstraction<Dune::FieldMatrix<K, N, M>>\n{\n  typedef Dune::FieldMatrix<K, N, M> MatrixType;\n  typedef K ScalarType;\n  typedef ScalarType S;\n\n  static const bool is_matrix = true;\n\n  static const bool has_static_size = true;\n\n  static const size_t static_rows = N;\n\n  static const size_t static_cols = M;\n\n  static inline MatrixType create(const size_t rows, const size_t cols)\n  {\n    if (rows != N)\n      DUNE_THROW(Dune::Stuff::Exceptions::shapes_do_not_match, \"rows = \" << rows << \"\\nN = \" << int(N));\n    if (cols != M)\n      DUNE_THROW(Dune::Stuff::Exceptions::shapes_do_not_match, \"cols = \" << cols << \"\\nM = \" << int(M));\n    return MatrixType();\n  }\n\n  static inline MatrixType create(const size_t rows, const size_t cols, const ScalarType& val)\n  {\n    if (rows != N)\n      DUNE_THROW(Dune::Stuff::Exceptions::shapes_do_not_match, \"rows = \" << rows << \"\\nN = \" << int(N));\n    if (cols != M)\n      DUNE_THROW(Dune::Stuff::Exceptions::shapes_do_not_match, \"cols = \" << cols << \"\\nM = \" << int(M));\n    return MatrixType(val);\n  }\n\n  static inline size_t rows(const MatrixType& /*mat*/) { return boost::numeric_cast<size_t>(N); }\n\n  static inline size_t cols(const MatrixType& /*mat*/) { return boost::numeric_cast<size_t>(M); }\n\n  static inline void set_entry(MatrixType& mat, const size_t row, const size_t col, const ScalarType& val)\n  {\n    mat[row][col] = val;\n  }\n\n  static inline ScalarType get_entry(const MatrixType& mat, const size_t row, const size_t col)\n  {\n    return mat[row][col];\n  }\n};\n\ntemplate <class K, int N, int M>\nstruct MatrixAbstraction<Dune::Stuff::Common::FieldMatrix<K, N, M>>\n{\n  typedef Dune::Stuff::Common::FieldMatrix<K, N, M> MatrixType;\n  typedef K ScalarType;\n  typedef ScalarType S;\n\n  static const bool is_matrix = true;\n\n  static const bool has_static_size = true;\n\n  static const size_t static_rows = N;\n\n  static const size_t static_cols = M;\n\n  static inline MatrixType create(const size_t rows, const size_t cols) { return MatrixType(rows, cols); }\n\n  static inline MatrixType create(const size_t rows, const size_t cols, const ScalarType& val)\n  {\n    return MatrixType(rows, cols, val);\n  }\n\n  static inline size_t rows(const MatrixType& /*mat*/) { return N; }\n\n  static inline size_t cols(const MatrixType& /*mat*/) { return M; }\n\n  static inline void set_entry(MatrixType& mat, const size_t row, const size_t col, const ScalarType& val)\n  {\n    mat[row][col] = val;\n  }\n\n  static inline ScalarType get_entry(const MatrixType& mat, const size_t row, const size_t col)\n  {\n    return mat[row][col];\n  }\n};\n\ntemplate <class MatrixType>\nstruct is_matrix\n{\n  static const bool value = MatrixAbstraction<MatrixType>::is_matrix;\n};\n\ntemplate <class MatrixType>\ntypename std::enable_if<is_matrix<MatrixType>::value, MatrixType>::type\n    create(const size_t sz, const typename MatrixAbstraction<MatrixType>::S& val)\n{\n  return MatrixAbstraction<MatrixType>::create(sz, val);\n}\n\n} // namespace Common\n} // namespace Stuff\n} // namespace Dune\n\n#endif // DUNE_STUFF_COMMON_MATRIX_HH\n", "meta": {"hexsha": "cb61257e6306393346ec3b8ef202b5af0b0e89c0", "size": 6720, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/stuff/common/matrix.hh", "max_stars_repo_name": "ftalbrecht/dune-stuff-simplified", "max_stars_repo_head_hexsha": "fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dune/stuff/common/matrix.hh", "max_issues_repo_name": "ftalbrecht/dune-stuff-simplified", "max_issues_repo_head_hexsha": "fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dune/stuff/common/matrix.hh", "max_forks_repo_name": "ftalbrecht/dune-stuff-simplified", "max_forks_repo_head_hexsha": "fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8256880734, "max_line_length": 116, "alphanum_fraction": 0.7040178571, "num_tokens": 1719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.24077694225848403}}
{"text": "/*\nAll modification made by Cambricon Corporation: © 2018-2019 Cambricon Corporation\nAll rights reserved.\nAll other contributions:\nCopyright (c) 2014--2019, the respective contributors\nAll rights reserved.\nFor the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md\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\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 Intel Corporation nor the names of its contributors\n      may be used to endorse or promote products derived from this software\n      without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <limits>\n\n#include \"caffe/common.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n#include \"caffe/util/rng.hpp\"\n\nnamespace caffe {\n\ntemplate <>\nvoid caffe_cpu_gemm<float>(const CBLAS_TRANSPOSE TransA,\n                           const CBLAS_TRANSPOSE TransB, const int M,\n                           const int N, const int K, const float alpha,\n                           const float* A, const float* B, const float beta,\n                           float* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_sgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B, ldb,\n              beta, C, N);\n}\n\ntemplate <>\nvoid caffe_cpu_gemm<double>(const CBLAS_TRANSPOSE TransA,\n                            const CBLAS_TRANSPOSE TransB, const int M,\n                            const int N, const int K, const double alpha,\n                            const double* A, const double* B, const double beta,\n                            double* C) {\n  int lda = (TransA == CblasNoTrans) ? K : M;\n  int ldb = (TransB == CblasNoTrans) ? N : K;\n  cblas_dgemm(CblasRowMajor, TransA, TransB, M, N, K, alpha, A, lda, B, ldb,\n              beta, C, N);\n}\n\ntemplate <>\nvoid caffe_cpu_gemv<float>(const CBLAS_TRANSPOSE TransA, const int M,\n                           const int N, const float alpha, const float* A,\n                           const float* x, const float beta, float* y) {\n  cblas_sgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_gemv<double>(const CBLAS_TRANSPOSE TransA, const int M,\n                            const int N, const double alpha, const double* A,\n                            const double* x, const double beta, double* y) {\n  cblas_dgemv(CblasRowMajor, TransA, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\ntemplate <>\nvoid caffe_axpy<float>(const int N, const float alpha, const float* X,\n                       float* Y) {\n  cblas_saxpy(N, alpha, X, 1, Y, 1);\n}\n\ntemplate <>\nvoid caffe_axpy<double>(const int N, const double alpha, const double* X,\n                        double* Y) {\n  cblas_daxpy(N, alpha, X, 1, Y, 1);\n}\n\ntemplate <typename Dtype>\nvoid caffe_set(const int N, const Dtype alpha, Dtype* Y) {\n  if (alpha == 0) {\n    memset(Y, 0, sizeof(Dtype) * N);\n    return;\n  }\n  for (int i = 0; i < N; ++i) {\n    Y[i] = alpha;\n  }\n}\n\ntemplate void caffe_set<int>(const int N, const int alpha, int* Y);\ntemplate void caffe_set<float>(const int N, const float alpha, float* Y);\ntemplate void caffe_set<double>(const int N, const double alpha, double* Y);\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const float alpha, float* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate <>\nvoid caffe_add_scalar(const int N, const double alpha, double* Y) {\n  for (int i = 0; i < N; ++i) {\n    Y[i] += alpha;\n  }\n}\n\ntemplate <typename Dtype>\nvoid caffe_copy(const int N, const Dtype* X, Dtype* Y) {\n  if (X != Y) {\n    if (Caffe::mode() == Caffe::GPU) {\n#ifdef USE_CUDA\n      // NOLINT_NEXT_LINE(caffe/alt_fn)\n      CUDA_CHECK(cudaMemcpy(Y, X, sizeof(Dtype) * N, cudaMemcpyDefault));\n#else\n      NO_GPU;\n#endif\n    } else {\n      memcpy(Y, X, sizeof(Dtype) * N);\n    }\n  }\n}\n\ntemplate void caffe_copy<int>(const int N, const int* X, int* Y);\ntemplate void caffe_copy<unsigned int>(const int N, const unsigned int* X,\n                                       unsigned int* Y);\ntemplate void caffe_copy<float>(const int N, const float* X, float* Y);\ntemplate void caffe_copy<double>(const int N, const double* X, double* Y);\n\ntemplate <>\nvoid caffe_scal<float>(const int N, const float alpha, float* X) {\n  cblas_sscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_scal<double>(const int N, const double alpha, double* X) {\n  cblas_dscal(N, alpha, X, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<float>(const int N, const float alpha, const float* X,\n                            const float beta, float* Y) {\n  cblas_saxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_axpby<double>(const int N, const double alpha, const double* X,\n                             const double beta, double* Y) {\n  cblas_daxpby(N, alpha, X, 1, beta, Y, 1);\n}\n\ntemplate <>\nvoid caffe_add<float>(const int n, const float* a, const float* b, float* y) {\n  vsAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_add<double>(const int n, const double* a, const double* b,\n                       double* y) {\n  vdAdd(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<float>(const int n, const float* a, const float* b, float* y) {\n  vsSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sub<double>(const int n, const double* a, const double* b,\n                       double* y) {\n  vdSub(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<float>(const int n, const float* a, const float* b, float* y) {\n  vsMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_mul<double>(const int n, const double* a, const double* b,\n                       double* y) {\n  vdMul(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<float>(const int n, const float* a, const float* b, float* y) {\n  vsDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_div<double>(const int n, const double* a, const double* b,\n                       double* y) {\n  vdDiv(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<float>(const int n, const float* a, const float b, float* y) {\n  vsPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_powx<double>(const int n, const double* a, const double b,\n                        double* y) {\n  vdPowx(n, a, b, y);\n}\n\ntemplate <>\nvoid caffe_sqr<float>(const int n, const float* a, float* y) {\n  vsSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_sqr<double>(const int n, const double* a, double* y) {\n  vdSqr(n, a, y);\n}\n\ntemplate <>\nvoid caffe_sqrt<float>(const int n, const float* a, float* y) {\n  vsSqrt(n, a, y);\n}\n\ntemplate <>\nvoid caffe_sqrt<double>(const int n, const double* a, double* y) {\n  vdSqrt(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<float>(const int n, const float* a, float* y) {\n  vsExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_exp<double>(const int n, const double* a, double* y) {\n  vdExp(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<float>(const int n, const float* a, float* y) {\n  vsLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_log<double>(const int n, const double* a, double* y) {\n  vdLn(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<float>(const int n, const float* a, float* y) {\n  vsAbs(n, a, y);\n}\n\ntemplate <>\nvoid caffe_abs<double>(const int n, const double* a, double* y) {\n  vdAbs(n, a, y);\n}\n\nunsigned int caffe_rng_rand() { return (*caffe_rng())(); }\n\ntemplate <typename Dtype>\nDtype caffe_nextafter(const Dtype b) {\n  return boost::math::nextafter<Dtype>(b, std::numeric_limits<Dtype>::max());\n}\n\ntemplate float caffe_nextafter(const float b);\n\ntemplate double caffe_nextafter(const double b);\n\ntemplate <typename Dtype>\nvoid caffe_rng_uniform(const int n, const Dtype a, const Dtype b, Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_LE(a, b);\n  boost::uniform_real<Dtype> random_distribution(a, caffe_nextafter<Dtype>(b));\n  boost::variate_generator<caffe::rng_t*, boost::uniform_real<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate void caffe_rng_uniform<float>(const int n, const float a,\n                                       const float b, float* r);\n\ntemplate void caffe_rng_uniform<double>(const int n, const double a,\n                                        const double b, double* r);\n\ntemplate <typename Dtype>\nvoid caffe_rng_gaussian(const int n, const Dtype a, const Dtype sigma,\n                        Dtype* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GT(sigma, 0);\n  boost::normal_distribution<Dtype> random_distribution(a, sigma);\n  boost::variate_generator<caffe::rng_t*, boost::normal_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate void caffe_rng_gaussian<float>(const int n, const float mu,\n                                        const float sigma, float* r);\n\ntemplate void caffe_rng_gaussian<double>(const int n, const double mu,\n                                         const double sigma, double* r);\n\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = variate_generator();\n  }\n}\n\ntemplate void caffe_rng_bernoulli<double>(const int n, const double p, int* r);\n\ntemplate void caffe_rng_bernoulli<float>(const int n, const float p, int* r);\n\ntemplate <typename Dtype>\nvoid caffe_rng_bernoulli(const int n, const Dtype p, unsigned int* r) {\n  CHECK_GE(n, 0);\n  CHECK(r);\n  CHECK_GE(p, 0);\n  CHECK_LE(p, 1);\n  boost::bernoulli_distribution<Dtype> random_distribution(p);\n  boost::variate_generator<caffe::rng_t*, boost::bernoulli_distribution<Dtype> >\n      variate_generator(caffe_rng(), random_distribution);\n  for (int i = 0; i < n; ++i) {\n    r[i] = static_cast<unsigned int>(variate_generator());\n  }\n}\n\ntemplate void caffe_rng_bernoulli<double>(const int n, const double p,\n                                          unsigned int* r);\n\ntemplate void caffe_rng_bernoulli<float>(const int n, const float p,\n                                         unsigned int* r);\n\ntemplate <>\nfloat caffe_cpu_strided_dot<float>(const int n, const float* x, const int incx,\n                                   const float* y, const int incy) {\n  return cblas_sdot(n, x, incx, y, incy);\n}\n\ntemplate <>\ndouble caffe_cpu_strided_dot<double>(const int n, const double* x,\n                                     const int incx, const double* y,\n                                     const int incy) {\n  return cblas_ddot(n, x, incx, y, incy);\n}\n\ntemplate <typename Dtype>\nDtype caffe_cpu_dot(const int n, const Dtype* x, const Dtype* y) {\n  return caffe_cpu_strided_dot(n, x, 1, y, 1);\n}\n\ntemplate float caffe_cpu_dot<float>(const int n, const float* x,\n                                    const float* y);\n\ntemplate double caffe_cpu_dot<double>(const int n, const double* x,\n                                      const double* y);\n\ntemplate <>\nfloat caffe_cpu_asum<float>(const int n, const float* x) {\n  return cblas_sasum(n, x, 1);\n}\n\ntemplate <>\ndouble caffe_cpu_asum<double>(const int n, const double* x) {\n  return cblas_dasum(n, x, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_scale<float>(const int n, const float alpha, const float* x,\n                            float* y) {\n  cblas_scopy(n, x, 1, y, 1);\n  cblas_sscal(n, alpha, y, 1);\n}\n\ntemplate <>\nvoid caffe_cpu_scale<double>(const int n, const double alpha, const double* x,\n                             double* y) {\n  cblas_dcopy(n, x, 1, y, 1);\n  cblas_dscal(n, alpha, y, 1);\n}\n\n}  // namespace caffe\n", "meta": {"hexsha": "5cbd3c80d2f009b42e801f43960d530b2494db0e", "size": 12820, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_functions.cpp", "max_stars_repo_name": "imoisture/caffe", "max_stars_repo_head_hexsha": "4d6892afeff234c57ce470056939101e0ae71369", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/caffe/util/math_functions.cpp", "max_issues_repo_name": "imoisture/caffe", "max_issues_repo_head_hexsha": "4d6892afeff234c57ce470056939101e0ae71369", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/caffe/util/math_functions.cpp", "max_forks_repo_name": "imoisture/caffe", "max_forks_repo_head_hexsha": "4d6892afeff234c57ce470056939101e0ae71369", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5763546798, "max_line_length": 92, "alphanum_fraction": 0.6371294852, "num_tokens": 3419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.24070064830150537}}
{"text": "#include <boost/asio.hpp>\n#include \"vdf.h\"\nusing boost::asio::ip::tcp;\n\nconst int max_length = 2048;\nconst int kMaxProcessesAllowed = 3;\nstd::mutex socket_mutex;\n\nint process_number;\n\nvoid PrintInfo(std::string input) {\n    std::cout << \"VDF Client: \" << input << \"\\n\";\n}\n\nvoid CreateAndWriteProof(integer D, form x, int64_t num_iterations, WesolowskiCallback& weso, bool& stop_signal, tcp::socket& sock) {\n    Proof result = CreateProofOfTimeNWesolowski(D, x, num_iterations, 0, weso, 2, 0, stop_signal);\n    if (stop_signal == true) {\n        PrintInfo(\"Got stop signal before completing the proof!\");\n        return ;\n    }\n    std::vector<unsigned char> bytes = ConvertIntegerToBytes(integer(num_iterations), 8);\n    bytes.insert(bytes.end(), result.y.begin(), result.y.end());\n    bytes.insert(bytes.end(), result.proof.begin(), result.proof.end());\n    std::string str_result = BytesToStr(bytes);\n    std::lock_guard<std::mutex> lock(socket_mutex);\n    PrintInfo(\"Generated proof = \" + str_result);;\n    boost::asio::write(sock, boost::asio::buffer(str_result.c_str(), str_result.size()));\n}\n\nvoid session(tcp::socket& sock) {\n    try {\n        char disc[350];\n        char disc_size[5];\n        boost::system::error_code error;\n\n        memset(disc,0x00,sizeof(disc)); // For null termination\n        memset(disc_size,0x00,sizeof(disc_size)); // For null termination\n\n        boost::asio::read(sock, boost::asio::buffer(disc_size, 3), error);\n        int disc_int_size = atoi(disc_size);\n\n        boost::asio::read(sock, boost::asio::buffer(disc, disc_int_size), error);\n\n        integer D(disc);\n        PrintInfo(\"Discriminant = \" + to_string(D.impl));\n\n        int space_needed = kSwitchIters / 10 + (kMaxItersAllowed - kSwitchIters) / 100;\n        forms = (form*) calloc(space_needed, sizeof(form));\n\n        PrintInfo(\"Calloc'd \" + to_string(space_needed * sizeof(form)) + \" bytes\");\n\n        // Init VDF the discriminant...\n\n        if (error == boost::asio::error::eof)\n            return ; // Connection closed cleanly by peer.\n        else if (error)\n            throw boost::system::system_error(error); // Some other error.\n\n        if (getenv( \"warn_on_corruption_in_production\" )!=nullptr) {\n            warn_on_corruption_in_production=true;\n        }\n        if (is_vdf_test) {\n            PrintInfo( \"=== Test mode ===\" );\n        }\n        if (warn_on_corruption_in_production) {\n            PrintInfo( \"=== Warn on corruption enabled ===\" );\n        }\n        assert(is_vdf_test); //assertions should be disabled in VDF_MODE==0\n        init_gmp();\n        allow_integer_constructor=true; //make sure the old gmp allocator isn't used\n        set_rounding_mode();\n\n        integer L=root(-D, 4);\n        form f=form::generator(D);\n\n        bool stop_signal = false;\n        // (iteration, thread_id)\n        std::set<std::pair<uint64_t, uint64_t> > seen_iterations;\n        bool stop_vector[100];\n\n        std::vector<std::thread> threads;\n        WesolowskiCallback weso(1000000);\n\n        //mpz_init(weso.forms[0].a.impl);\n        //mpz_init(weso.forms[0].b.impl);\n        //mpz_init(weso.forms[0].c.impl);\n\n        forms[0]=f;\n        weso.D = D;\n        weso.L = L;\n        weso.kl = 10;\n\n        bool stopped = false;\n        bool got_iters = false;\n        std::thread vdf_worker(repeated_square, f, D, L, std::ref(weso), std::ref(stopped));\n\n        // Tell client that I'm ready to get the challenges.\n        boost::asio::write(sock, boost::asio::buffer(\"OK\", 2));\n        char data[20];\n\n        while (!stopped) {\n            memset(data, 0, sizeof(data));\n            boost::asio::read(sock, boost::asio::buffer(data, 2), error);\n            int size = (data[0] - '0') * 10 + (data[1] - '0');\n            memset(data, 0, sizeof(data));\n            boost::asio::read(sock, boost::asio::buffer(data, size), error);\n            int iters = atoi(data);\n            got_iters = true;\n        \n            if (iters == 0) {\n                PrintInfo(\"Got stop signal!\");\n                stopped = true;\n                for (int i = 0; i < threads.size(); i++)\n                    stop_vector[i] = true;\n                for (int t = 0; t < threads.size(); t++) {\n                    threads[t].join();\n                }\n                vdf_worker.join();\n                free(forms);\n            } else {\n                int max_iter = 0;\n                int max_iter_thread_id = -1;\n                int min_iter = std::numeric_limits<int> :: max();\n                bool unique = true;\n                for (auto active_iter: seen_iterations) {\n                    if (active_iter.first > max_iter) {\n                        max_iter = active_iter.first;\n                        max_iter_thread_id = active_iter.second;\n                    }\n                    if (active_iter.first < min_iter) {\n                        min_iter = active_iter.first;\n                    }\n                    if (active_iter.first == iters) {\n                        unique = false;\n                        break;\n                    }\n                }\n                if (!unique) {\n                    PrintInfo(\"Duplicate iteration \" + to_string(iters) + \"... Ignoring.\");\n                    continue;\n                }\n                if (threads.size() < kMaxProcessesAllowed || iters < min_iter) {\n                    seen_iterations.insert({iters, threads.size()});\n                    PrintInfo(\"Running proving for iter: \" + to_string(iters));\n                    stop_vector[threads.size()] = false;\n                    threads.push_back(std::thread(CreateAndWriteProof, D, f, iters, std::ref(weso), \n                                      std::ref(stop_vector[threads.size()]), std::ref(sock)));\n                    if (threads.size() > kMaxProcessesAllowed) {\n                        PrintInfo(\"Stopping proving for iter: \" + to_string(max_iter));\n                        stop_vector[max_iter_thread_id] = true;\n                        seen_iterations.erase({max_iter, max_iter_thread_id});\n                    }\n                }\n            }\n        }\n    } catch (std::exception& e) {\n        PrintInfo(\"Exception in thread: \" + to_string(e.what()));\n    }\n\n    try {\n        // Tell client I've stopped everything, wait for ACK and close.\n        boost::system::error_code error;\n\n        PrintInfo(\"Stopped everything! Ready for the next challenge.\");\n\n        std::lock_guard<std::mutex> lock(socket_mutex);\n        boost::asio::write(sock, boost::asio::buffer(\"STOP\", 4));\n\n        char ack[5];\n        memset(ack,0x00,sizeof(ack));\n        boost::asio::read(sock, boost::asio::buffer(ack, 3), error);\n        assert (strncmp(ack, \"ACK\", 3) == 0);\n    } catch (std::exception& e) {\n        PrintInfo(\"Exception in thread: \" + to_string(e.what()));\n    }\n}\n\nint main(int argc, char* argv[])\n{\n  try {\n    if (argc != 4)\n    {\n      std::cerr << \"Usage: ./vdf_client <host> <port> <process_number>\\n\";\n      return 1;\n    }\n\n    boost::asio::io_service io_service;\n\n    tcp::resolver resolver(io_service);\n    tcp::resolver::query query(tcp::v6(), argv[1], argv[2], boost::asio::ip::resolver_query_base::v4_mapped);\n    tcp::resolver::iterator iterator = resolver.resolve(query);\n\n    tcp::socket s(io_service);\n    boost::asio::connect(s, iterator);\n    process_number = atoi(argv[3]);\n    session(s);\n  } catch (std::exception& e) {\n    std::cerr << \"Exception: \" << e.what() << \"\\n\";\n  }\n  return 0;\n}\n", "meta": {"hexsha": "a72aaaa4e1aa08431f3be4f488d18ade85508b05", "size": 7436, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/chiavdf/fast_vdf/vdf_client.cpp", "max_stars_repo_name": "davision/chia-blockchain", "max_stars_repo_head_hexsha": "d5a66579c00cb926e0d266e5b8077ac16b220932", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/chiavdf/fast_vdf/vdf_client.cpp", "max_issues_repo_name": "davision/chia-blockchain", "max_issues_repo_head_hexsha": "d5a66579c00cb926e0d266e5b8077ac16b220932", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/chiavdf/fast_vdf/vdf_client.cpp", "max_forks_repo_name": "davision/chia-blockchain", "max_forks_repo_head_hexsha": "d5a66579c00cb926e0d266e5b8077ac16b220932", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8118811881, "max_line_length": 133, "alphanum_fraction": 0.5477407208, "num_tokens": 1777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.24067603175975236}}
{"text": "#include \"LevelSet.h\"\n\n#include <array>\n\n#include <Eigen/Dense>\n#include <Eigen/SVD>\n\n#include \"tbb/blocked_range3d.h\"\n#include \"tbb/tbb.h\"\n\nnamespace FluidSim3D\n{\n\nLevelSet::LevelSet()\n    : myNarrowBand(0)\n    , myPhiGrid(Transform(0, Vec3d::Zero()), Vec3i::Zero())\n    , myIsBackgroundNegative(false)\n{\n    exactinit();\n}\n\nLevelSet::LevelSet(const Transform& xform, const Vec3i& size)\n    : LevelSet(xform, size, size[0] * size[1] * size[2]) \n{}\n\nLevelSet::LevelSet(const Transform& xform, const Vec3i& size, double bandwidth, bool isBoundaryNegative)\n    : myNarrowBand(bandwidth * xform.dx())\n    , myIsBackgroundNegative(isBoundaryNegative)\n    , myPhiGrid(xform, size, myIsBackgroundNegative ? -myNarrowBand : myNarrowBand)\n{\n    for (int axis : {0, 1, 2}) assert(size[axis] >= 0);\n\n    // In order to deal with triangle meshes, we need to initialize\n    // the geometric predicate library.\n    exactinit();\n}\n\nvoid LevelSet::initFromMesh(const TriMesh& initialMesh, bool doResizeGrid)\n{\n\t// The internal code can't handle a mesh that falls outside of the bounds.\n\t// If the mesh does, we need to create a new copy and clamp it into the bounds of the grid.\n\n    if (!doResizeGrid)\n    {\n\t\tbool outOfBounds = false;\n\t\tfor (const Vec3d& vertex : initialMesh.vertices())\n\t\t{\n\t\t\tVec3d indexPoint = worldToIndex(vertex);\n\n            for (int axis : {0, 1, 2})\n            {\n\t\t\t    if (indexPoint[axis] <= 0 || indexPoint[axis] >= size()[axis])\n\t\t\t\t    outOfBounds = true;\n            }\n\t\t}\n\n\t\tif (outOfBounds)\n\t\t{\n\t\t\tTriMesh clampedMesh = initialMesh;\n\n\t\t\t// Clamp to be inside grid\n\t\t\tfor (int vertIndex = 0; vertIndex < clampedMesh.vertexCount(); ++vertIndex)\n\t\t\t{\n\t\t\t\tconst Vec3d& vertex = clampedMesh.vertex(vertIndex);\n\t\t\t\tVec3d indexPoint = worldToIndex(vertex);\n\n\t\t\t\tdouble offset = 1e-5 * dx();\n\n                for (int axis : {0, 1, 2})\n                {\n                    indexPoint[axis] = std::clamp(indexPoint[axis], offset, size()[axis] - 1. - offset);\n                }\n\n\t\t\t\tclampedMesh.setVertex(vertIndex, indexToWorld(indexPoint));\n\t\t\t}\n\n\t\t\tinitFromMeshImpl(clampedMesh, doResizeGrid);\n\t\t\treturn;\n\t\t}\n    }\n\n    initFromMeshImpl(initialMesh, doResizeGrid);\n}\n\nvoid LevelSet::reinit()\n{\n    TriMesh tempMesh = buildMesh();\n    initFromMeshImpl(tempMesh, false);\n}\n\nbool LevelSet::isGridMatched(const LevelSet& grid) const\n{\n    if (size() != grid.size()) return false;\n    if (xform() != grid.xform()) return false;\n    return true;\n}\n\nbool LevelSet::isGridMatched(const ScalarGrid<double>& grid) const\n{\n    if (grid.sampleType() != ScalarGridSettings::SampleType::CENTER) return false;\n    if (size() != grid.size()) return false;\n    if (xform() != grid.xform()) return false;\n    return true;\n}\n\nvoid LevelSet::unionSurface(const LevelSet& unionPhi)\n{\n    assert(isGridMatched(unionPhi));\n\n    tbb::parallel_for(tbb::blocked_range<int>(0, voxelCount(), tbbLightGrainSize), [&](const tbb::blocked_range<int>& range)\n    {\n        for (int index = range.begin(); index != range.end(); ++index)\n        {\n            Vec3i cell = myPhiGrid.unflatten(index);\n            myPhiGrid(cell) = std::min(myPhiGrid(cell), unionPhi(cell));\n        }\n    });\n}\n\nbool LevelSet::isBackgroundNegative() const\n{\n    return myIsBackgroundNegative;\n}\n\nvoid LevelSet::setBackgroundNegative()\n{\n    myIsBackgroundNegative = true;\n}\n\nTriMesh LevelSet::buildMesh() const\n{\n    // Create grid to store index to dual contouring point. Note that phi is\n    // center sampled so the DC grid must be node sampled and one cell shorter\n    // in each dimension\n    UniformGrid<int> dcPointIndices(size() - Vec3i::Ones(), -1);\n    std::vector<std::pair<Vec3i, Vec3d>> dcPointPair;\n\n    // Build list of dual contouring points\n    {\n        tbb::enumerable_thread_specific<std::vector<std::pair<Vec3i, Vec3d>>> parallelDCPoints;\n\n        tbb::parallel_for(tbb::blocked_range<int>(0, dcPointIndices.voxelCount(), tbbHeavyGrainSize), [&](const tbb::blocked_range<int>& range)\n        {\n            auto& localDCPoints = parallelDCPoints.local();\n\n            for (int cellIndex = range.begin(); cellIndex != range.end(); ++cellIndex)\n            {\n                Vec3i cell = dcPointIndices.unflatten(cellIndex);\n\n                VecVec3d points;\n                VecVec3d normals;\n\n                Vec3d averagePoint = Vec3d::Zero();\n\n                for (int edgeAxis : {0, 1, 2})\n                    for (int edgeIndex = 0; edgeIndex < 4; ++edgeIndex)\n                    {\n                        Vec3i edge = cellToEdge(cell, edgeAxis, edgeIndex);\n\n                        Vec3i backwardNode = edgeToNode(edge, edgeAxis, 0);\n                        Vec3i forwardNode = edgeToNode(edge, edgeAxis, 1);\n\n                        // Look for zero crossings.\n                        // Note that nodes for the DC grid fall exactly on the cell centers\n                        // of the level set grid.\n                        if ((myPhiGrid(backwardNode) <= 0 && myPhiGrid(forwardNode) > 0) ||\n                            (myPhiGrid(backwardNode) > 0 && myPhiGrid(forwardNode) <= 0))\n                        {\n                            // Find interface point\n                            Vec3d point = interpolateInterface(backwardNode, forwardNode);\n\n                            for (int axis : {0, 1, 2})\n                                assert(point[axis] >= backwardNode[axis] && point[axis] <= forwardNode[axis]);\n\n                            points.push_back(point);\n\n                            averagePoint += point;\n\n                            // Find associated surface normal\n                            Vec3d localNormal = normal(indexToWorld(point));\n\n                            normals.push_back(localNormal);\n                        }\n                    }\n\n                if (points.size() > 0)\n                {\n                    averagePoint.array() /= double(points.size());\n\n                    Matrix3x3d AtA = Matrix3x3d::Zero();\n\n                    Vec3d rhs = Vec3d::Zero();\n\n                    for (int pointIndex = 0; pointIndex < points.size(); ++pointIndex)\n                    {\n                        AtA += normals[pointIndex] * normals[pointIndex].transpose();\n                        rhs += normals[pointIndex] * normals[pointIndex].dot(points[pointIndex] - averagePoint);\n                    }\n\n                    Eigen::SelfAdjointEigenSolver<Matrix3x3d> eigenSolver(AtA);\n                    const Vec3d& eigenvalues = eigenSolver.eigenvalues();\n\n                    // Clamp eigenvalues\n                    double tolerance = 0.01 * eigenvalues.cwiseAbs().maxCoeff();\n\n                    Vec3d invEigenvalues;\n                    int clamped = 0;\n                    for (int index : {0, 1, 2})\n                    {\n                        if (std::fabs(eigenvalues[index] < tolerance))\n                        {\n                            invEigenvalues[index] = 0;\n                            ++clamped;\n                        }\n                        else\n                        {\n                            invEigenvalues[index] = 1. / eigenvalues[index];\n                        }\n                    }\n\n                    Vec3d qefPoint;\n                    if (clamped < 3)\n                    {\n                        qefPoint = averagePoint + eigenSolver.eigenvectors() * invEigenvalues.asDiagonal() * eigenSolver.eigenvectors().transpose() * rhs;\n                    }\n                    else\n                    {\n                        qefPoint = averagePoint;\n                    }\n\n                    // Clamp to cell\n                    if (qefPoint[0] < cell[0] || qefPoint[0] > cell[0] + 1 ||\n                        qefPoint[1] < cell[1] || qefPoint[1] > cell[1] + 1 ||\n                        qefPoint[2] < cell[2] || qefPoint[2] > cell[2] + 1)\n                    {\n                        AlignedBox3d cellBbox(cell.cast<double>());\n                        cellBbox.extend((cell + Vec3i::Ones()).cast<double>());\n                        Vec3d rayDirection = averagePoint - qefPoint;\n                        double alpha = computeRayBBoxIntersection(cellBbox, qefPoint, rayDirection);\n\n                        if (alpha <= 1)\n                        {\n                            qefPoint += alpha * rayDirection;\n                        }\n                        else\n                        {\n                            qefPoint = averagePoint;\n                        }\n                    }\n\n                    localDCPoints.emplace_back(cell, qefPoint);\n                }\n            }\n        });\n\n        mergeLocalThreadVectors(dcPointPair, parallelDCPoints);\n    }\n\n    VecVec3d vertices(dcPointPair.size());\n\n    // Set DC point index for direct look up when building mesh and\n    // convert points to world space.\n    tbb::parallel_for(tbb::blocked_range<size_t>(0, dcPointPair.size(), tbbLightGrainSize), [&](const tbb::blocked_range<size_t>& range)\n    {\n        for (size_t index = range.begin(); index != range.end(); ++index)\n        {\n            const Vec3i& cell = dcPointPair[index].first;\n\n            assert(dcPointIndices(cell) == -1);\n            dcPointIndices(cell) = int(index);\n\n            const Vec3d& point = dcPointPair[index].second;\n            vertices[index] = indexToWorld(point);\n        }\n    });\n\n    // Build triangle mesh using dual contouring points\n\n    VecVec3i triangles;\n\n    for (int edgeAxis : {0, 1, 2})\n    {\n        Vec3i start = Vec3i::Zero();\n        ++start[(edgeAxis + 1) % 3];\n        ++start[(edgeAxis + 2) % 3];\n\n        Vec3i end = dcPointIndices.size();\n\n        tbb::enumerable_thread_specific<VecVec3i> parallelTriangles;\n\n        auto loopRange3d = tbb::blocked_range3d<int>(start[0], end[0], int(std::cbrt(tbbLightGrainSize)), start[1], end[1],\n                                      int(std::cbrt(tbbLightGrainSize)), start[2], end[2], int(std::cbrt(tbbLightGrainSize)));\n\n        tbb::parallel_for(loopRange3d, [&](const tbb::blocked_range3d<int>& range)\n        {\n            auto& localTriFaces = parallelTriangles.local();\n\n            Vec3i edge;\n            for (edge[0] = range.pages().begin(); edge[0] != range.pages().end(); ++edge[0])\n                for (edge[1] = range.rows().begin(); edge[1] != range.rows().end(); ++edge[1])\n                    for (edge[2] = range.cols().begin(); edge[2] != range.cols().end(); ++edge[2])\n                    {\n                        Vec3i backwardNode = edgeToNode(edge, edgeAxis, 0);\n                        Vec3i forwardNode = edgeToNode(edge, edgeAxis, 1);\n\n                        if ((myPhiGrid(backwardNode) <= 0 && myPhiGrid(forwardNode) > 0) ||\n                            (myPhiGrid(backwardNode) > 0 && myPhiGrid(forwardNode) <= 0))\n                        {\n                            std::array<Vec3i, 4> dcCells;\n                            std::array<int, 4> vertexIndices;\n\n                            for (int cellIndex = 0; cellIndex < 4; ++cellIndex)\n                            {\n                                dcCells[cellIndex] = edgeToCellCCW(edge, edgeAxis, cellIndex);\n                                vertexIndices[cellIndex] = dcPointIndices(dcCells[cellIndex]);\n                                assert(vertexIndices[cellIndex] >= 0);\n                            }\n\n                            if (myPhiGrid(backwardNode) <= 0.)\n                            {\n                                localTriFaces.emplace_back(vertexIndices[0], vertexIndices[1], vertexIndices[2]);\n                                localTriFaces.emplace_back(vertexIndices[0], vertexIndices[2], vertexIndices[3]);\n                            }\n                            else\n                            {\n                                localTriFaces.emplace_back(vertexIndices[0], vertexIndices[2], vertexIndices[1]);\n                                localTriFaces.emplace_back(vertexIndices[0], vertexIndices[3], vertexIndices[2]);\n                            }\n                        }\n                    }\n        });\n\n        mergeLocalThreadVectors(triangles, parallelTriangles);\n    }\n\n    return TriMesh(triangles, vertices);\n}\n\nvoid LevelSet::clear()\n{\n    myPhiGrid.clear();\n}\n\nvoid LevelSet::resize(const Vec3i& size)\n{\n    myPhiGrid.resize(size);\n}\n\n// Find the nearest point on the interface starting from the index position.\n// If the position falls outside of the narrow band, there isn't a defined gradient\n// to use. In this case, the original position will be returned.\nVec3d LevelSet::findSurface(const Vec3d& worldPoint, int iterationLimit, double tolerance) const\n{\n    assert(iterationLimit >= 0);\n\n    double phi = myPhiGrid.triLerp(worldPoint);\n\n    double epsilon = tolerance * dx();\n    Vec3d tempPoint = worldPoint;\n\n    int iterationCount = 0;\n    if (std::fabs(phi) < myNarrowBand)\n    {\n        while (std::fabs(phi) > epsilon && iterationCount < iterationLimit)\n        {\n            tempPoint -= phi * .8 * normal(tempPoint);\n            phi = myPhiGrid.triLerp(tempPoint);\n            ++iterationCount;\n        }\n    }\n\n    return tempPoint;\n}\n\nVec3d LevelSet::interpolateInterface(const Vec3i& startPoint, const Vec3i& endPoint) const\n{\n    assert((myPhiGrid(startPoint) <= 0 && myPhiGrid(endPoint) > 0) ||\n           (myPhiGrid(startPoint) > 0 && myPhiGrid(endPoint) <= 0));\n\n    // Find weight to zero isosurface\n    double theta = lengthFraction(myPhiGrid(startPoint), myPhiGrid(endPoint));\n\n    assert(theta >= 0 && theta <= 1);\n\n    if (myPhiGrid(startPoint) > 0)\n        theta = 1. - theta;\n\n    return startPoint.cast<double>() + theta * (endPoint - startPoint).cast<double>();\n}\n\nvoid LevelSet::drawGrid(Renderer& renderer, bool doOnlyNarrowBand) const\n{\n    if (doOnlyNarrowBand)\n    {\n        forEachVoxelRange(Vec3i::Zero().eval(), size(), [&](const Vec3i& cell)\n        {\n            if (std::fabs(myPhiGrid(cell)) < myNarrowBand) myPhiGrid.drawGridCell(renderer, cell);\n        });\n    }\n    else\n        myPhiGrid.drawGrid(renderer);\n}\n\nvoid LevelSet::drawGridPlane(Renderer& renderer, Axis planeAxis, double position, bool doOnlyNarrowBand) const\n{\n    position = std::clamp(position, double(0), double(1));\n\n    Vec3i start = Vec3i::Zero();\n    Vec3i end(myPhiGrid.size() - Vec3i::Ones());\n\n    if (planeAxis == Axis::XAXIS)\n    {\n        start[0] = int(std::floor(position * double(myPhiGrid.size()[0] - 1)));\n        end[0] = start[0] + 1;\n    }\n    else if (planeAxis == Axis::YAXIS)\n    {\n        start[1] = int(std::floor(position * double(myPhiGrid.size()[1] - 1)));\n        end[1] = start[1] + 1;\n    }\n    else if (planeAxis == Axis::ZAXIS)\n    {\n        start[2] = int(std::floor(position * double(myPhiGrid.size()[2] - 1)));\n        end[2] = start[2] + 1;\n    }\n\n    forEachVoxelRange(start, end, [&](const Vec3i& cell)\n    {\n        if (doOnlyNarrowBand)\n        {\n            if (std::fabs(myPhiGrid(cell)) < myNarrowBand) myPhiGrid.drawGridCell(renderer, cell);\n        }\n        else\n            myPhiGrid.drawGridCell(renderer, cell);\n    });\n}\n\n// Display a supersampled slice of the grid. The plane will have a normal in the plane_axis direction.\n// The position is from [0,1] where 0 is at the grid origin and 1 is at the origin + size * dx.\nvoid LevelSet::drawSupersampledValuesPlane(Renderer& renderer, Axis planeAxis, double position, double radius,\n                                           int samples, double sampleSize) const\n{\n    myPhiGrid.drawSupersampledValuesPlane(renderer, planeAxis, position, radius, samples, sampleSize);\n}\nvoid LevelSet::drawSampleNormalsPlane(Renderer& renderer, Axis planeAxis, double position, const Vec3d& colour,\n                                      double length) const\n{\n    myPhiGrid.drawSampleGradientsPlane(renderer, planeAxis, position, colour, length);\n}\n\nvoid LevelSet::drawSurface(Renderer& renderer, const Vec3d& colour, double lineWidth) const\n{\n    TriMesh tempMesh = buildMesh();\n    tempMesh.drawMesh(renderer, true, colour, lineWidth);\n}\n\n// \n// Private methods\n//\n\nvoid LevelSet::initFromMeshImpl(const TriMesh& initialMesh, bool doResizeGrid)\n{\n    if (doResizeGrid)\n    {\n        // Determine the bounding box of the mesh to build the underlying grids\n\t\tAlignedBox3d bbox = initialMesh.boundingBox();\n\n\t\t// Expand grid beyond the narrow band of the mesh\n\t\tdouble maxPadding = 50. * dx();\n\t\tmaxPadding = std::min(2. * myNarrowBand, maxPadding);\n\n\t\tbbox.extend(bbox.min() - Vec3d::Constant(maxPadding));\n\t\tbbox.extend(bbox.max() + Vec3d::Constant(maxPadding));\n\n\t\tVec3d origin = indexToWorld(floor(worldToIndex(bbox.min())).eval());\n\t\tTransform xform(dx(), origin);\n\t\tVec3d topRight = indexToWorld(ceil(worldToIndex(bbox.max())).eval());\n  \n\t\t// TODO: add the ability to reset grid so we don't have ot re-allocate memory\n\t\tmyPhiGrid = ScalarGrid<double>(xform, ((topRight - origin) / dx()).cast<int>(), myIsBackgroundNegative ? -myNarrowBand : myNarrowBand);\n    }\n\n    // We want to track which cells in the level set contain valid distance information.\n    // The first pass will set cells close to the mesh as FINISHED.\n    UniformGrid<VisitedCellLabels> reinitializedCells(size(), VisitedCellLabels::UNVISITED_CELL);\n    UniformGrid<int> meshCellParities(size(), 0);\n\n    for (const Vec3i& tri : initialMesh.triangles())\n    {\n        // It's easier to work in our index space and just scale the distance later.\n        std::array<Vec3d, 3> triVertices;\n        for (int localVertexIndex : {0, 1, 2})\n            triVertices[localVertexIndex] = worldToIndex(initialMesh.vertex(tri[localVertexIndex]));\n\n\t\tAlignedBox3d triBbox(triVertices[0]);\n\t\ttriBbox.extend(triVertices[1]);\n\t\ttriBbox.extend(triVertices[2]);\n\n        Vec3i triCeilMin = ceil(triBbox.min()).cast<int>();\n        Vec3i triFloorMin = floor(triBbox.min()).cast<int>() - Vec3i::Ones();\n        Vec3i triFloorMax = floor(triBbox.max()).cast<int>();\n\n        // Z-axis intersection tests. Iterate along an aligned set of grid edges\n        // in decsending order, checking for intersections at each edge.\n        // If an intersection is found then we can stop searching along the set.\n        for (int i = triCeilMin[0]; i <= triFloorMax[0]; ++i)\n            for (int j = triFloorMin[1]; j <= triFloorMax[1]; ++j)\n                for (int k = triFloorMax[2]; k >= triFloorMin[2]; --k)\n                {\n                    Vec3d gridPoint(i, j, k);\n                    IntersectionLabels intersectionResult = exactTriIntersect(gridPoint, triVertices[0], triVertices[1], triVertices[2], Axis::ZAXIS);\n\n                    for (int axis : {0, 1, 2})\n\t\t\t\t        assert(gridPoint[axis] >= 0 && gridPoint[axis] < myPhiGrid.size()[axis] - 1);\n\n                    if (intersectionResult == IntersectionLabels::NO) continue;\n\n                    int parityChange = -1;\n                    double qrs = orient2d(triVertices[0].data(), triVertices[1].data(), triVertices[2].data());\n                    assert(qrs != 0);\n                    if (qrs < 0)\n                        parityChange = 1;\n\n                    if (intersectionResult == IntersectionLabels::YES)\n                        meshCellParities(i, j, k + 1) += parityChange;\n                    else\n                    {\n                        assert(intersectionResult == IntersectionLabels::ON);\n\n                        if (parityChange == 1)\n                            meshCellParities(i, j, k) += parityChange;\n                        else\n                        {\n                            meshCellParities(i, j, k + 1) += parityChange;\n                        }                      \n                    }\n\n                    break;\n                }\n    }\n\n    // Now that all the z-axis edge crossings have been found, we can compile the parity changes\n    // and label grid nodes that are at the interface\n    for (int i = 0; i < size()[0]; ++i)\n        for (int j = 0; j < size()[1]; ++j)\n        {\n            int parity = myIsBackgroundNegative ? 1 : 0;\n\n            for (int k = 0; k < size()[2]; ++k)\n            {\n                Vec3i cell(i, j, k);\n\n                parity += meshCellParities(cell);\n                meshCellParities(cell) = parity;\n\n                if (parity > 0)\n                    myPhiGrid(cell) = -myNarrowBand;\n                else\n                    myPhiGrid(cell) = myNarrowBand;\n            }\n\n            assert(myIsBackgroundNegative ? parity == 1 : parity == 0);\n        }\n\n    // With the parity assigned, loop over the grid once more and label nodes that have a sign change\n    // with neighbouring nodes (this means parity goes from -'ve (and zero) to +'ve or vice versa).\n    forEachVoxelRange(Vec3i::Ones(), size() - Vec3i::Ones(), [&](const Vec3i& cell)\n    {\n        bool isCellInside = meshCellParities(cell) > 0;\n\n        for (int axis : {0, 1, 2})\n            for (int direction : {0, 1})\n            {\n                Vec3i adjacentCell = cellToCell(cell, axis, direction);\n\n                bool isAdjacentCellInside = meshCellParities(adjacentCell) > 0;\n\n                if (isCellInside != isAdjacentCellInside)\n                    reinitializedCells(cell) = VisitedCellLabels::FINISHED_CELL;\n            }\n    });\n\n    // Loop over all the triangles in the mesh. Level set grid cells labelled as FINISHED will be\n    // updated with the distance to the surface if it happens to be shorter than the current\n    // distance to the surface.\n    for (const Vec3i& tri : initialMesh.triangles())\n    {\n        std::array<Vec3d, 3> vertices;\n        for (int localVertexIndex : {0, 1, 2})\n            vertices[localVertexIndex] = worldToIndex(initialMesh.vertex(tri[localVertexIndex]));\n            \n        AlignedBox3d triBbox(vertices[0]);\n        triBbox.extend(vertices[1]);\n        triBbox.extend(vertices[2]);\n\n        // Expand outward by 2-voxels in each direction\n        triBbox.extend(triBbox.min() - Vec3d::Constant(2));\n        triBbox.extend(triBbox.max() + Vec3d::Constant(2));\n\n        AlignedBox3d clampBbox;\n        clampBbox.extend(Vec3d::Zero());\n        clampBbox.extend(size().cast<double>() - Vec3d::Ones());\n\n        triBbox.clamp(clampBbox);\n\n        for (int axis : {0, 1, 2})\n            assert(triBbox.min()[axis] >= 0 && triBbox.max()[axis] < size()[axis]);\n\n        forEachVoxelRange(triBbox.min().cast<int>(), triBbox.max().cast<int>() + Vec3i::Ones(), [&](const Vec3i& cell)\n        {\n            if (reinitializedCells(cell) != VisitedCellLabels::UNVISITED_CELL)\n            {\n                Vec3d cellPoint = cell.cast<double>();\n\n                Vec3d triProjectionPoint = pointToTriangleProjection(cellPoint, vertices[0], vertices[1], vertices[2]);\n\n                double surfaceDistance = (cellPoint - triProjectionPoint).norm() * dx();\n\n                // If the new distance is closer than existing distance values, update cell\n                if (std::fabs(myPhiGrid(cell)) > surfaceDistance)\n                {\n                    // If the parity says the node is inside, set it to be negative\n                    myPhiGrid(cell) = (meshCellParities(cell) > 0) ? -surfaceDistance : surfaceDistance;\n                }\n            }\n        });\n    }\n\n    reinitFastMarching(reinitializedCells);\n}\n\nvoid LevelSet::reinitFastMarching(UniformGrid<VisitedCellLabels>& reinitializedCells)\n{\n    assert(reinitializedCells.size() == size());\n\n    auto solveEikonal2D = [&](double Ux, double Uy) -> double\n    {\n        if (std::fabs(Ux - Uy) >= dx())\n            return std::min(Ux, Uy) + dx();\n        else\n        {\n            // Quadratic equation from the Eikonal\n            double rootEntry = std::pow(Ux + Uy, 2) - 2. * (std::pow(Ux, 2) + std::pow(Uy, 2) - std::pow(dx(), 2));\n            assert(rootEntry >= 0);\n            return .5 * (Ux + Uy + std::sqrt(rootEntry));\n        }\n    };\n\n    auto solveEikonal = [&](const Vec3i& cell) -> double\n    {\n        double max = std::numeric_limits<double>::max();\n\n        Vec3d Uaxis = Vec3d::Constant(max);\n\t\tfor (int axis : {0, 1, 2})\n\t\t\tfor (int direction : {0, 1})\n\t\t\t{\n\t\t\t\tVec3i adjacentCell = cellToCell(cell, axis, direction);\n\n\t\t\t\tif (adjacentCell[axis] < 0 || adjacentCell[axis] >= size()[axis])\n\t\t\t\t{\n\t\t\t\t\tassert(myPhiGrid(cell) > 0 && !myIsBackgroundNegative || myPhiGrid(cell) < 0 && myIsBackgroundNegative);\n\t\t\t\t\tUaxis[axis] = std::min(max, Uaxis[axis]);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tUaxis[axis] = std::min(std::fabs(myPhiGrid(adjacentCell)), Uaxis[axis]);\n\t\t\t\t}\n\t\t\t}\n\n        double discrim = std::pow(Uaxis.sum(), 2) - 3. * (Uaxis.squaredNorm() - std::pow(dx(), 2));\n        if (discrim < 0.)\n        {\n            double dist = std::min(std::min(solveEikonal2D(Uaxis[0], Uaxis[1]), solveEikonal2D(Uaxis[1], Uaxis[2])), solveEikonal2D(Uaxis[0], Uaxis[2]));\n\n            assert(std::isfinite(dist));\n\n            return dist;\n        }\n        else\n        {\n            double dist = (Uaxis.sum() + std::sqrt(discrim)) / 3.;\n            assert(std::isfinite(dist));\n            return dist;\n        }\n    };\n\n    // Load up the BFS queue with the unvisited cells next to the finished ones\n    using Node = std::pair<Vec3i, double>;\n    auto cmp = [](const Node& a, const Node& b) -> bool { return std::fabs(a.second) > std::fabs(b.second); };\n    std::priority_queue<Node, std::vector<Node>, decltype(cmp)> marchingQ(cmp);\n\n    forEachVoxelRange(Vec3i::Zero(), reinitializedCells.size(), [&](const Vec3i& cell)\n    {\n        if (reinitializedCells(cell) == VisitedCellLabels::FINISHED_CELL)\n        {\n            for (int axis : {0, 1, 2})\n                for (int direction : {0, 1})\n                {\n                    Vec3i adjacentCell = cellToCell(cell, axis, direction);\n\n                    if (adjacentCell[axis] < 0 || adjacentCell[axis] >= reinitializedCells.size()[axis]) continue;\n\n                    if (reinitializedCells(adjacentCell) == VisitedCellLabels::UNVISITED_CELL)\n                    {\n                        double dist = solveEikonal(adjacentCell);\n\n                        if (!std::isfinite(dist))\n                            int a = 0;\n                        assert(dist >= 0);\n\n                        myPhiGrid(adjacentCell) = myPhiGrid(adjacentCell) < 0 ? -dist : dist;\n\n                        Node node(adjacentCell, dist);\n\n                        marchingQ.push(node);\n                        reinitializedCells(adjacentCell) = VisitedCellLabels::VISITED_CELL;\n                    }\n                }\n        }\n    });\n\n    while (!marchingQ.empty())\n    {\n        Node localNode = marchingQ.top();\n        Vec3i localCell = localNode.first;\n        marchingQ.pop();\n\n        // Since you can't just update parts of the priority queue,\n        // it's possible that a cell has been solidified at a smaller distance\n        // and an older insert if doubleing around.\n        if (reinitializedCells(localCell) == VisitedCellLabels::FINISHED_CELL)\n        {\n            // Make sure that the distance assigned to the cell is smaller than\n            // what is doubleing around\n            assert(std::fabs(myPhiGrid(localCell)) <= std::fabs(localNode.second));\n            continue;\n        }\n        assert(reinitializedCells(localCell) == VisitedCellLabels::VISITED_CELL);\n\n        if (std::fabs(myPhiGrid(localCell)) < myNarrowBand)\n        {\n            // Debug check that there is indeed a FINISHED cell next to it\n            bool foundFinishedCell = false;\n\n            for (int axis : {0, 1, 2})\n                for (int direction : {0, 1})\n                {\n                    Vec3i adjacentCell = cellToCell(localCell, axis, direction);\n\n                    if (adjacentCell[axis] < 0 || adjacentCell[axis] >= reinitializedCells.size()[axis]) continue;\n\n                    if (reinitializedCells(adjacentCell) == VisitedCellLabels::FINISHED_CELL)\n                        foundFinishedCell = true;\n                    else\n                    {\n                        double dist = solveEikonal(adjacentCell);\n                        assert(dist >= 0);\n\n                        if (dist > myNarrowBand) dist = myNarrowBand;\n\n                        if (reinitializedCells(adjacentCell) == VisitedCellLabels::VISITED_CELL &&\n                            dist > std::fabs(myPhiGrid(adjacentCell)))\n                            continue;\n\n                        myPhiGrid(adjacentCell) = myPhiGrid(adjacentCell) < 0 ? -dist : dist;\n\n                        Node node(adjacentCell, dist);\n\n                        marchingQ.push(node);\n                        reinitializedCells(adjacentCell) = VisitedCellLabels::VISITED_CELL;\n                    }\n                }\n            assert(foundFinishedCell);\n        }\n        else\n            myPhiGrid(localCell) = myPhiGrid(localCell) < 0 ? -myNarrowBand : myNarrowBand;\n\n        reinitializedCells(localCell) = VisitedCellLabels::FINISHED_CELL;\n    }\n}\n\nVec3d LevelSet::findSurfaceIndex(const Vec3d& indexPoint, int iterationLimit, double tolerance) const\n{\n    Vec3d worldPoint = indexToWorld(indexPoint);\n    worldPoint = findSurface(worldPoint, iterationLimit, tolerance);\n    return worldToIndex(worldPoint);\n}\n\n}", "meta": {"hexsha": "9a8c13b39a9269c46fa51527201249a006fcf9be", "size": 29023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Library/SurfaceTrackers/LevelSet.cpp", "max_stars_repo_name": "rgoldade/3dFluidSimulation", "max_stars_repo_head_hexsha": "680d84429e73e26671a52e1a725b1b76ec4ef0db", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T16:47:25.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-30T01:31:09.000Z", "max_issues_repo_path": "Library/SurfaceTrackers/LevelSet.cpp", "max_issues_repo_name": "rgoldade/3dFluidSimulation", "max_issues_repo_head_hexsha": "680d84429e73e26671a52e1a725b1b76ec4ef0db", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Library/SurfaceTrackers/LevelSet.cpp", "max_forks_repo_name": "rgoldade/3dFluidSimulation", "max_forks_repo_head_hexsha": "680d84429e73e26671a52e1a725b1b76ec4ef0db", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7845373891, "max_line_length": 154, "alphanum_fraction": 0.5530785928, "num_tokens": 7031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727232, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.24054145004180058}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <stdlib.h>\n#include <Structs/Graphs/dynamicGraph.h>\n#include <Structs/Graphs/adjacencyListImpl.h>\n#include <Algorithms/multicriteriaDijkstra.h>\n#include <Algorithms/multicriteriaGraph.h>\n#include <Algorithms/namoaStar.h>\n#include <Algorithms/namoaStar2.h>\n#include <Algorithms/multicriteriaArc.h>\n#include <Heuristics/blind.h>\n#include <Heuristics/ideal.h>\n#include <Heuristics/boundedIdeal.h>\n#include <Checkers/multiCriteriaChecker.h>\n#include <Checkers/multiCriteriaResults.h>\n#include <Checkers/Grids/multiCriteriaGridChecker.h>\n#include <Utilities/timer.h>\n#include <Utilities/colormod.h>\n#include <boost/program_options.hpp>\n\nnamespace po = boost::program_options;\n\ntemplate< class algorithmVariant, typename GraphType>\nvoid runQueries( GraphType& G, std::vector< std::pair<unsigned int,unsigned int> >& queries,\n                 std::vector<typename GraphType::NodeDescriptor>& ids, GridChecker& gChecker, const unsigned int showOnScreen)\n{\n    typedef typename GraphType::NodeIterator NodeIterator;\n    NodeIterator s,t;\n    unsigned int sourceId, targetId;\n    unsigned int timestamp = 0;\n    //create algorithm\n    algorithmVariant algorithm( G, NUM_CRITERIA, &timestamp);\n    //run queries\n    unsigned int query_n = 0;\n    double numLabels = 0;\n    double totalTime = 0;\n    for( std::vector< std::pair<unsigned int,unsigned int> >::iterator it = queries.begin();\n         it != queries.end(); ++it)\n    {\n        //clear nodes\n        NodeIterator u, lastnode;\n        for( u = G.beginNodes(), lastnode = G.endNodes(); u != lastnode; ++u)\n        {\n            u->g_op.clear();\n            u->g_cl.clear();\n        }\n        sourceId = it->first;\n        targetId = it->second;\n        s = G.getNodeIterator( ids[sourceId]);\n        t = G.getNodeIterator( ids[targetId]);\n        Timer timer;\n        timer.start();\n        algorithm.init( s, t, NUM_CRITERIA);\n        auto heuristicTime = 1000 * timer.getElapsedTime();\n        timer.start();\n        algorithm.runQuery( s, t);\n        auto runtime = 1000 * timer.getElapsedTime();\n        totalTime += runtime;\n        // add Pareto efficient solutions to the results class\n        MulticriteriaResults mResults( queries);\n        mResults.addResults( t->g_cl);\n        numLabels += algorithm.getGeneratedLabels();\n        // Two things are checked: First, the set of solutions is the same; second, the solutions have been found in the same order.\n        bool order = true;\n        bool correctness = mResults.checkParetoCosts( gChecker, query_n, order);\n        Color::Modifier def(Color::FG_DEFAULT);\n        Color::Modifier red(Color::FG_RED);\n        Color::Modifier green(Color::FG_GREEN);\n        Color::Modifier yellow(Color::FG_YELLOW);\n        Color::Modifier b_blue(Color::BG_BLUE);\n        Color::Modifier b_def(Color::BG_DEFAULT);\n\n        std::cout << b_blue << \"(\" << sourceId << \"->\" << targetId << \")\" << b_def << \"\\t\\t\";\n\n        if ( showOnScreen)\n        {\n            Color::Modifier blue(Color::FG_BLUE);\n            Color::Modifier lblue(Color::FG_LIGHT_BLUE);\n            Color::Modifier cyan(Color::FG_CYAN);\n            Color::Modifier lcyan(Color::FG_LIGHT_CYAN);\n            std::cout << blue << t->g_cl.size() << def << \" efficient paths were found.\\n\";\n            std::cout << \"\\t\\t\\t\" << lblue << algorithm.getGeneratedLabels() << def << \" labels were scanned.\\n\";\n            std::cout << \"\\t\\t\\t\" << cyan << heuristicTime << def << \" msec. - calculation of heuristic.\\n\";\n            std::cout << \"\\t\\t\\t\" << lcyan << runtime << def << \" msec. - algorithm runtime.\\n\";\n        }\n        std::cout << \"Solutions ... ->\\t\";\n        if ( !( correctness))\n        {\n            std::cout << red << \"Different!!!\\n\" << def;\n            t->printLabels( std::cout, G);\n            exit (EXIT_FAILURE);\n        }\n        else\n        {\n            std::cout << green << \"OK\" << def << \"\\n\";\n            if (! (order)) std::cout << yellow << \"Warning!\" << def << \" The same set of solutions was found, but in different order.\\n\";\n        }\n        std::cout << \"---------------------------------------------------------------------\\n\";\n        ++query_n;\n    }\n\n    if ( showOnScreen)\n    {\n        std::cout << \"\\tAlgorithm Runtime:\\t\" << totalTime << \" msec. ( \" << (totalTime / queries.size()) << \" msec. per query)\\n\";\n        std::cout << \"\\tGenerated labels:\\t \" << numLabels << std::endl;\n    }\n}\n\ntemplate< typename GraphType>\nvoid runBenchmarks( GraphType& G, std::vector< std::pair<unsigned int,unsigned int> >& queries,\n                    std::vector<typename GraphType::NodeDescriptor>& ids, GridChecker& gChecker,\n                    const std::string& name, const unsigned int& algorithmVariant, const unsigned int showOnScreen)\n{\n    switch( algorithmVariant)\n    {\n    case 1:\n        // output message for all queries\n        std::cout << \"with NAMOA* (blind) ...\\n\\n\";\n        runQueries<NamoaStar2<GraphType,BlindHeuristic> >( G, queries, ids, gChecker, showOnScreen);\n        break;\n    case 2:\n        std::cout << \"with NAMOA*_tc ...\\n\\n\";\n        runQueries<NamoaStar2<GraphType,TCHeuristic> >( G, queries, ids, gChecker, showOnScreen);\n        break;\n    case 3:\n        std::cout << \"with NAMOA*_bound_tc ...\\n\\n\";\n        runQueries<NamoaStar2<GraphType,BoundedTCHeuristic> >( G, queries, ids, gChecker, showOnScreen);\n        //std::cout << \"with NAMOA* Arc Flags (\" << name << \") ...\\n\\n\";\n        //runQueries<NamoaStarArc<GraphType,GreatCircleHeuristic> >( G, queries, ids, gChecker, showOnScreen);\n        break;\n    case 0: // default\n        std::cout << \"with NAMOA* (blind) ...\\n\\n\";\n        runQueries<NamoaStar2<GraphType,BlindHeuristic> >( G, queries, ids, gChecker, showOnScreen);\n        std::cout << \"with NAMOA*_tc ...\\n\\n\";\n        runQueries<NamoaStar2<GraphType,TCHeuristic> >( G, queries, ids, gChecker, showOnScreen);\n        std::cout << \"with NAMOA*_bound_tc ...\\n\\n\";\n        runQueries<NamoaStar2<GraphType,BoundedTCHeuristic> >( G, queries, ids, gChecker, showOnScreen);\n        break;\n    }\n}\n\ntypedef DynamicGraph< AdjacencyListImpl, Node, Edge>       Graph;\n//typedef DynamicGraph< AdjacencyListImpl, LWNode, Edge>     LWGraph;\ntypedef Graph::NodeIterator                                NodeIterator;\ntypedef Graph::EdgeIterator                                EdgeIterator;\ntypedef Graph::NodeDescriptor                              NodeDescriptor;\n\nint main( int argc, char* argv[])\n{\n    std::string gridBenchmarksPath = \"/home/francis/Projects/Benchmarks/\";\n    std::string gridsPath = gridBenchmarksPath + \"grids/\";\n    std::string gridQueriesPath = gridBenchmarksPath + \"queries/\";\n    std::string gridSolutionsPath = gridBenchmarksPath + \"solutions/\";\n\n    unsigned int benchmarkVariant = 2;\n    unsigned int algorithmVariant = 0;\n    unsigned int showOnScreen = 1;\n\n    // Declare the supported options.\n    po::options_description desc(\"Allowed options\");\n    desc.add_options()\n        (\"benchmark,b\", po::value< unsigned int>(), \"Benchmark to run. Bicriteria[2],  Tri-criterion[3]. Default:2\")\n        (\"algorithm,a\", po::value< unsigned int>(), \"Multicriteria Heuristic. All[0], Blind[1], Ideal Point[2], Bounded Ideal point[3]. Default:0\")\n        (\"showOnScreen,s\", po::value< unsigned int>(), \"Display stats on screen. Yes[1], No[0]. Default:1\");\n\n    po::variables_map vm;\n    po::store(po::parse_command_line(argc, argv, desc), vm);\n    po::notify(vm);    \n\n    if (vm.empty()) {\n        std::cout << desc << \"\\n\";\n        return 0;\n    }\n    if (vm.count(\"benchmark\"))\n    {\n        benchmarkVariant = vm[\"benchmark\"].as<unsigned int>();\n    }\n    if (vm.count(\"algorithm\"))\n    {\n        algorithmVariant = vm[\"algorithm\"].as<unsigned int>();\n    }\n    if (vm.count(\"showOnScreen\"))\n    {\n        showOnScreen = vm[\"showOnScreen\"].as<unsigned int>();\n    }\n    unsigned int nqueries;\n    if ( benchmarkVariant == 2)\n    {\n        NUM_CRITERIA = 2;\n        nqueries = NQUERIES_2;\n    }\n    else if ( benchmarkVariant == 3)\n    {\n        NUM_CRITERIA = 3;\n        nqueries = NQUERIES_3;\n    }\n    else\n    {\n        std::cerr << \"BenchmarkVariant provided not implemented yet\\n\";\n    }\n\n    for ( unsigned int grid_n = 0; grid_n < NGRIDS; ++grid_n)\n    {\n        GridChecker gChecker( nqueries, benchmarkVariant,\n                              gridQueriesPath + \"queries\" + std::to_string( benchmarkVariant) + \".txt\",\n                              gridSolutionsPath + \"p\" + std::to_string( grid_n) + \"/\" +\n                              std::to_string( benchmarkVariant) + \".txt\",\n                              GRIDDIMSIZE);\n        std::vector< std::pair< unsigned int ,unsigned int> > queries;\n        queries = gChecker.getQueries (benchmarkVariant);\n        Graph G;\n        std::string gridProblemPath = gridsPath + \"Grid\" + std::to_string( grid_n)+ \".txt\";\n        std::cout << \"\\nBenchmark at \" << gridProblemPath;\n        GridReader<Graph> reader( gridProblemPath, benchmarkVariant);\n        Timer timer;\n        timer.start();\n        G.read(&reader);\n        std::cout << \"Graph has \" << (double)G.memUsage()/1048576 << \" Mbytes. Time spent to read:\\t\" << timer.getElapsedTime() << \"sec\" << std::endl;\n        std::cout << \"Checking correctness of \" << queries.size() << \" queries \\n\";\n        timer.start();\n        runBenchmarks( G, queries, reader.getIds(), gChecker, \"ADJ\", algorithmVariant, showOnScreen);\n        std::cout << \"\\tBenchmark runtime: \\t\" << timer.getElapsedTime() << \" sec\" << std::endl;\n    }\n    return 0;\n}\n", "meta": {"hexsha": "7a69ba3ee2bbfe048d4e8e3db239bb3f389cdf74", "size": 9567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CorrectnessCheckers/grids/benchmark/correctnessChecker.cpp", "max_stars_repo_name": "FrankS101/multicriteriaDIMACS", "max_stars_repo_head_hexsha": "993bd50a2537ad56d33535a546a8426f8120f9fa", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-15T11:21:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T11:21:17.000Z", "max_issues_repo_path": "CorrectnessCheckers/grids/benchmark/correctnessChecker.cpp", "max_issues_repo_name": "FrankS101/multicriteriaDIMACS", "max_issues_repo_head_hexsha": "993bd50a2537ad56d33535a546a8426f8120f9fa", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CorrectnessCheckers/grids/benchmark/correctnessChecker.cpp", "max_forks_repo_name": "FrankS101/multicriteriaDIMACS", "max_forks_repo_head_hexsha": "993bd50a2537ad56d33535a546a8426f8120f9fa", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.1453744493, "max_line_length": 150, "alphanum_fraction": 0.5997700429, "num_tokens": 2413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.24054144409323516}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017, 2018.\r\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 5.0.0\r\n\r\n// Original copyright notice:\r\n\r\n// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_EQDC_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_EQDC_HPP\r\n\r\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\r\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\r\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_mlfn.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_msfn.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n\r\n#include <boost/math/special_functions/hypot.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace projections\r\n{\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail { namespace eqdc\r\n    {\r\n\r\n            static const double epsilon10 = 1.e-10;\r\n\r\n            template <typename T>\r\n            struct par_eqdc\r\n            {\r\n                T    phi1;\r\n                T    phi2;\r\n                T    n;\r\n                T    rho0;\r\n                T    c;\r\n                detail::en<T> en;\r\n                bool ellips;\r\n            };\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_eqdc_ellipsoid\r\n                : public base_t_fi<base_eqdc_ellipsoid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_eqdc<T> m_proj_parm;\r\n\r\n                inline base_eqdc_ellipsoid(const Parameters& par)\r\n                    : base_t_fi<base_eqdc_ellipsoid<T, Parameters>, T, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(e_forward)  sphere & ellipsoid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(T lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    T rho = 0.0;\r\n\r\n                    rho = this->m_proj_parm.c - (this->m_proj_parm.ellips ? pj_mlfn(lp_lat, sin(lp_lat),\r\n                        cos(lp_lat), this->m_proj_parm.en) : lp_lat);\r\n                    xy_x = rho * sin( lp_lon *= this->m_proj_parm.n );\r\n                    xy_y = this->m_proj_parm.rho0 - rho * cos(lp_lon);\r\n                }\r\n\r\n                // INVERSE(e_inverse)  sphere & ellipsoid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(T xy_x, T xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    static T const half_pi = detail::half_pi<T>();\r\n\r\n                    T rho = 0.0;\r\n\r\n                    if ((rho = boost::math::hypot(xy_x, xy_y = this->m_proj_parm.rho0 - xy_y)) != 0.0 ) {\r\n                        if (this->m_proj_parm.n < 0.) {\r\n                            rho = -rho;\r\n                            xy_x = -xy_x;\r\n                            xy_y = -xy_y;\r\n                        }\r\n                        lp_lat = this->m_proj_parm.c - rho;\r\n                        if (this->m_proj_parm.ellips)\r\n                            lp_lat = pj_inv_mlfn(lp_lat, this->m_par.es, this->m_proj_parm.en);\r\n                        lp_lon = atan2(xy_x, xy_y) / this->m_proj_parm.n;\r\n                    } else {\r\n                        lp_lon = 0.;\r\n                        lp_lat = this->m_proj_parm.n > 0. ? half_pi : -half_pi;\r\n                    }\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"eqdc_ellipsoid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Equidistant Conic\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup_eqdc(Params const& params, Parameters& par, par_eqdc<T>& proj_parm)\r\n            {\r\n                T cosphi, sinphi;\r\n                int secant;\r\n\r\n                proj_parm.phi1 = pj_get_param_r<T, srs::spar::lat_1>(params, \"lat_1\", srs::dpar::lat_1);\r\n                proj_parm.phi2 = pj_get_param_r<T, srs::spar::lat_2>(params, \"lat_2\", srs::dpar::lat_2);\r\n\r\n                if (fabs(proj_parm.phi1 + proj_parm.phi2) < epsilon10)\r\n                    BOOST_THROW_EXCEPTION( projection_exception(error_conic_lat_equal) );\r\n\r\n                proj_parm.en = pj_enfn<T>(par.es);\r\n\r\n                proj_parm.n = sinphi = sin(proj_parm.phi1);\r\n                cosphi = cos(proj_parm.phi1);\r\n                secant = fabs(proj_parm.phi1 - proj_parm.phi2) >= epsilon10;\r\n                if( (proj_parm.ellips = (par.es > 0.)) ) {\r\n                    double ml1, m1;\r\n\r\n                    m1 = pj_msfn(sinphi, cosphi, par.es);\r\n                    ml1 = pj_mlfn(proj_parm.phi1, sinphi, cosphi, proj_parm.en);\r\n                    if (secant) { /* secant cone */\r\n                        sinphi = sin(proj_parm.phi2);\r\n                        cosphi = cos(proj_parm.phi2);\r\n                        proj_parm.n = (m1 - pj_msfn(sinphi, cosphi, par.es)) /\r\n                            (pj_mlfn(proj_parm.phi2, sinphi, cosphi, proj_parm.en) - ml1);\r\n                    }\r\n                    proj_parm.c = ml1 + m1 / proj_parm.n;\r\n                    proj_parm.rho0 = proj_parm.c - pj_mlfn(par.phi0, sin(par.phi0),\r\n                        cos(par.phi0), proj_parm.en);\r\n                } else {\r\n                    if (secant)\r\n                        proj_parm.n = (cosphi - cos(proj_parm.phi2)) / (proj_parm.phi2 - proj_parm.phi1);\r\n                    proj_parm.c = proj_parm.phi1 + cos(proj_parm.phi1) / proj_parm.n;\r\n                    proj_parm.rho0 = proj_parm.c - par.phi0;\r\n                }\r\n            }\r\n\r\n    }} // namespace detail::eqdc\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Equidistant Conic projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Conic\r\n         - Spheroid\r\n         - Ellipsoid\r\n        \\par Projection parameters\r\n         - lat_1: Latitude of first standard parallel (degrees)\r\n         - lat_2: Latitude of second standard parallel (degrees)\r\n        \\par Example\r\n        \\image html ex_eqdc.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct eqdc_ellipsoid : public detail::eqdc::base_eqdc_ellipsoid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline eqdc_ellipsoid(Params const& params, Parameters const& par)\r\n            : detail::eqdc::base_eqdc_ellipsoid<T, Parameters>(par)\r\n        {\r\n            detail::eqdc::setup_eqdc(params, this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail\r\n    {\r\n\r\n        // Static projection\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_eqdc, eqdc_ellipsoid, eqdc_ellipsoid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(eqdc_entry, eqdc_ellipsoid)\r\n        \r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(eqdc_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(eqdc, eqdc_entry);\r\n        }\r\n\r\n    } // namespace detail\r\n    #endif // doxygen\r\n\r\n} // namespace projections\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_EQDC_HPP\r\n\r\n", "meta": {"hexsha": "8b3e562b3d6108a5278f184083515b5ab7d16f79", "size": 9256, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dep/win/include/boost/geometry/srs/projections/proj/eqdc.hpp", "max_stars_repo_name": "Netis/packet-agent", "max_stars_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 995.0, "max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z", "max_issues_repo_path": "dep/win/include/boost/geometry/srs/projections/proj/eqdc.hpp", "max_issues_repo_name": "Netis/packet-agent", "max_issues_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z", "max_forks_repo_path": "dep/win/include/boost/geometry/srs/projections/proj/eqdc.hpp", "max_forks_repo_name": "Netis/packet-agent", "max_forks_repo_head_hexsha": "70da3479051a07e3c235abe7516990f9fd21a18a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 172.0, "max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z", "avg_line_length": 40.9557522124, "max_line_length": 114, "alphanum_fraction": 0.5740060501, "num_tokens": 2118, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2405050321931378}}
{"text": "//\n//   Copyright (c) 2004, 2005, 2006, 2007   Troy D. Straszheim  \n//   \n//   This file is part of IceTray.\n//\n//   IceTray is free software; you can redistribute it and/or modify\n//   it under the terms of the GNU General Public License as published by\n//   the Free Software Foundation; either version 3 of the License, or\n//   (at your option) any later version.\n//\n//   IceTray is distributed in the hope that it will be useful,\n//   but WITHOUT ANY WARRANTY; without even the implied warranty of\n//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n//   GNU General Public License for more details.\n//\n//   You should have received a copy of the GNU General Public License\n//   along with this program.  If not, see <http://www.gnu.org/licenses/>.\n//\n\n#include <boost/preprocessor.hpp>\n#include <vector>\n\n#include <dataclasses/I3Constants.h>\n\nusing namespace boost::python;\n\n#define I3_CONSTANT_NAMES\t\t\t\\\n  (c)(n_ice_phase)(n_ice_group)(n_ice)\t\t\\\n  (theta_cherenkov)(c_ice)(pi)(e)(NA)\t\t\\\n  (SurfaceElev)(OriginElev)(zIceTop)\t\t\\\n  (Coordinate_shift_x)(Coordinate_shift_y)\t\\\n  (Coordinate_shift_z)(dt_window_l)(dt_window_h)\n\n#define I3CONSTANT_DEF(r,data,t) \\\n  .def_readonly(BOOST_PP_STRINGIZE(t), BOOST_PP_CAT(I3Constants::, t))\n\n// dummy class just used as a namespace.\nnamespace {\n  struct dummy { };\n}\n\nvoid register_I3Constants()\n{\n  class_<dummy>(\"I3Constants\")\n    .def_readonly(\"c\", I3Constants::c, \"Speed of light in vacuum\")\n    .def_readonly(\"n_ice_phase\", I3Constants::n_ice_phase, \"the average phase velocity for wavelength of 400nm\") \n    .def_readonly(\"n_ice_group\", I3Constants::n_ice_group, \"avg group velocity for 400nm\")\n    .def_readonly(\"n_ice\", I3Constants::n_ice, \"index of refraction of ice\")\n    .def_readonly(\"theta_cherenkov\", I3Constants::theta_cherenkov, \"cherenkov angle in ice\")\n    .def_readonly(\"c_ice\", I3Constants::c_ice, \"c in ice\")\n    .def_readonly(\"pi\", I3Constants::pi, \"what is pi doing duplicated here\")\n    .def_readonly(\"e\", I3Constants::e, \"OY-ler's number.  awww yeah you know how we do.\")\n    .def_readonly(\"NA\", I3Constants::NA, \"avogadro's number\")\n    .def_readonly(\"SurfaceElev\", I3Constants::SurfaceElev, \"elevation of surface (amanda hole 4)\")\n    .def_readonly(\"OriginElev\", I3Constants::OriginElev, \"elev of icecube origin, by definition\")\n    .def_readonly(\"zIceTop\", I3Constants::zIceTop, \" Z-coordinate of IceTop (Origin Depth)\"\n\t\t  \"Obtained from DEFINED elevation of origin and MEASURED surface elevation\")\n    .def_readonly(\"Coordinate_shift_x\", I3Constants::Coordinate_shift_x, \"conversion between icecube and amanda\")\n    .def_readonly(\"Coordinate_shift_y\", I3Constants::Coordinate_shift_y, \"conversion between icecube and amanda\")\n    .def_readonly(\"Coordinate_shift_z\", I3Constants::Coordinate_shift_z, \"conversion between icecube and amanda\")\n    .def_readonly(\"dt_window_l\", I3Constants::dt_window_l, \"default value for time residuals\")\n    .def_readonly(\"dt_window_h\", I3Constants::dt_window_h, \"default value for time residuals\")\n    .def( freeze() )\n    ;\n}\n", "meta": {"hexsha": "2a4adb5aec2af7d97259bec854aae02746797006", "size": 3047, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "dataclasses/private/pybindings/I3Constants.cxx", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "dataclasses/private/pybindings/I3Constants.cxx", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dataclasses/private/pybindings/I3Constants.cxx", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 46.1666666667, "max_line_length": 113, "alphanum_fraction": 0.7305546439, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2401973822680529}}
{"text": "/*\n Copyright (C) 2019 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n#include <boost/date_time.hpp>\n#include <boost/make_shared.hpp>\n#include <ql/cashflows/cashflows.hpp>\n#include <ql/cashflows/coupon.hpp>\n#include <ql/cashflows/simplecashflow.hpp>\n#include <ql/event.hpp>\n#include <ql/quotes/compositequote.hpp>\n#include <ql/termstructures/credit/flathazardrate.hpp>\n#include <ql/termstructures/yield/zerospreadedtermstructure.hpp>\n#include <qle/pricingengines/discountingforwardbondengine.hpp>\n\nnamespace QuantExt {\n\nDiscountingForwardBondEngine::DiscountingForwardBondEngine(\n    const Handle<YieldTermStructure>& discountCurve, const Handle<YieldTermStructure>& incomeCurve,\n    const Handle<YieldTermStructure>& bondReferenceYieldCurve, const Handle<Quote>& bondSpread,\n    const Handle<DefaultProbabilityTermStructure>& bondDefaultCurve, const Handle<Quote>& bondRecoveryRate,\n    Period timestepPeriod, boost::optional<bool> includeSettlementDateFlows, const Date& settlementDate,\n    const Date& npvDate)\n    : discountCurve_(discountCurve), incomeCurve_(incomeCurve), bondReferenceYieldCurve_(bondReferenceYieldCurve),\n      bondSpread_(bondSpread), bondDefaultCurve_(bondDefaultCurve), bondRecoveryRate_(bondRecoveryRate),\n      timestepPeriod_(timestepPeriod), includeSettlementDateFlows_(includeSettlementDateFlows),\n      settlementDate_(settlementDate), npvDate_(npvDate) {\n\n    bondReferenceYieldCurve_ =\n        bondSpread_.empty() ? bondReferenceYieldCurve\n                            : Handle<YieldTermStructure>(\n                                  boost::make_shared<ZeroSpreadedTermStructure>(bondReferenceYieldCurve, bondSpread_));\n    registerWith(discountCurve_);           // curve for discounting of the forward derivative contract. OIS, usually.\n    registerWith(incomeCurve_);             // this is a curve for compounding of the bond\n    registerWith(bondReferenceYieldCurve_); // this is the bond reference curve, for discounting, usually RePo\n    registerWith(bondSpread_);\n    registerWith(bondDefaultCurve_);\n    registerWith(bondRecoveryRate_);\n}\n\nvoid DiscountingForwardBondEngine::calculate() const {\n    // Do some checks on data\n    QL_REQUIRE(!discountCurve_.empty(), \"discounting term structure handle is empty\");\n    QL_REQUIRE(!incomeCurve_.empty(), \"income term structure handle is empty\");\n    QL_REQUIRE(!bondReferenceYieldCurve_.empty(), \"bond rerference term structure handle is empty\");\n\n    Date npvDate = npvDate_; // this is today when the valuation occurs\n    if (npvDate == Null<Date>()) {\n        npvDate = (*discountCurve_)->referenceDate();\n    }\n    Date settlementDate = settlementDate_; //\n    if (settlementDate == Null<Date>()) {\n        settlementDate = (*discountCurve_)->referenceDate();\n    }\n\n    Date maturityDate =\n        arguments_.fwdMaturityDate; // this is the date when the forward is executed, i.e. cash and bond change hands\n\n    Real cmpPayment = arguments_.compensationPayment;\n    if (cmpPayment == Null<Real>()) {\n        cmpPayment = 0.0;\n    }\n    Date cmpPaymentDate = arguments_.compensationPaymentDate;\n    if (cmpPaymentDate == Null<Date>()) {\n        cmpPaymentDate = npvDate;\n    }\n\n    // in case that the premium payment has occured in the past, we set the amount to 0. the date itself is set to the\n    // npvDate to have a valid date for \"discounting\"\n    Date cmpPaymentDate_use = cmpPaymentDate >= npvDate ? cmpPaymentDate : maturityDate;\n    cmpPayment = cmpPaymentDate >= npvDate ? cmpPayment : 0.0; // premium cashflow is not relevant for npv if in the\n                                                               // past\n\n    // initialize\n    results_.value = 0.0;               // this is today's npv of the forward contract\n    results_.underlyingSpotValue = 0.0; // this is today's value of the \"restricted bond\". Restricted means that only\n                                        // cashflows after maturity are taken into account.\n    results_.forwardValue = 0.0;        // this the value of the forward contract just before maturity\n\n    bool dirty = arguments_.settlementDirty;\n\n    results_.underlyingSpotValue = calculateBondNpv(npvDate, maturityDate); // cashflows before maturity will be ignored\n\n    boost::tie(results_.forwardValue, results_.value) = calculateForwardContractPresentValue(\n        results_.underlyingSpotValue, cmpPayment, npvDate, maturityDate, cmpPaymentDate_use, dirty);\n}\n\nReal DiscountingForwardBondEngine::calculateBondNpv(Date npvDate, Date computeDate) const {\n    Real npvValue = 0.0;\n    Size numCoupons = 0;\n    bool hasLiveCashFlow = false;\n\n    // handle case where we wish to price simply with benchmark curve and scalar security spread\n    // i.e. credit curve term structure (and recovery) have not been specified\n    // we set the default probability and recovery rate to zero in this instance (issuer credit worthiness already\n    // captured within security spread)\n    boost::shared_ptr<DefaultProbabilityTermStructure> creditCurvePtr =\n        bondDefaultCurve_.empty()\n            ? boost::make_shared<QuantLib::FlatHazardRate>(npvDate, 0.0, bondReferenceYieldCurve_->dayCounter())\n            : bondDefaultCurve_.currentLink();\n    Rate recoveryVal = bondRecoveryRate_.empty() ? 0.0 : bondRecoveryRate_->value(); // setup default bond recovery rate\n\n    // load the shared pointer into bd\n    boost::shared_ptr<Bond> bd = arguments_.underlying;\n    for (Size i = 0; i < bd->cashflows().size(); i++) {\n        // Recovery amount is computed over the whole time interval (npvDate,maturityOfBond)\n\n        if (bd->cashflows()[i]->hasOccurred(\n                computeDate, includeSettlementDateFlows_)) // Cashflows before computeDate not relevant for npv\n            continue;\n\n        /* The amount recovered in the case of default is the recoveryrate*Notional*Probability of\n           Default; this is added to the NPV value. For coupon bonds the coupon periods are taken\n           as the timesteps for integrating over the probability of default.\n        */\n        boost::shared_ptr<Coupon> coupon = boost::dynamic_pointer_cast<Coupon>(bd->cashflows()[i]);\n\n        if (coupon) {\n            numCoupons++;\n            Date startDate = coupon->accrualStartDate();\n            Date endDate = coupon->accrualEndDate();\n            Date effectiveStartDate = (startDate <= computeDate && computeDate <= endDate) ? computeDate : startDate;\n            Date defaultDate = effectiveStartDate + (endDate - effectiveStartDate) / 2;\n            Probability P = creditCurvePtr->defaultProbability(effectiveStartDate, endDate);\n\n            npvValue += coupon->nominal() * recoveryVal * P * bondReferenceYieldCurve_->discount(defaultDate);\n        }\n\n        hasLiveCashFlow = true; // check if a cashflow  is available after the date of valuation.\n\n        // Coupon value is discounted future payment times the survival probability\n        Probability S = creditCurvePtr->survivalProbability(bd->cashflows()[i]->date()) /\n                        creditCurvePtr->survivalProbability(computeDate);\n        npvValue += bd->cashflows()[i]->amount() * S * bondReferenceYieldCurve_->discount(bd->cashflows()[i]->date());\n    }\n\n    // the ql instrument might not yet be expired and still have not anything to value if\n    // the computeDate > evaluation date\n    if (!hasLiveCashFlow)\n        return 0.0;\n\n    if (bd->cashflows().size() > 1 && numCoupons == 0) {\n        QL_FAIL(\"DiscountingForwardBondEngine does not support bonds with multiple cashflows but no coupons\");\n    }\n\n    boost::shared_ptr<Coupon> firstCoupon = boost::dynamic_pointer_cast<Coupon>(bd->cashflows()[0]);\n    if (firstCoupon) {\n        Date startDate = computeDate; // face value recovery starting with computeDate\n        while (startDate < bd->cashflows()[0]->date()) {\n            Date stepDate = startDate + timestepPeriod_;\n            Date endDate = (stepDate > bd->cashflows()[0]->date()) ? bd->cashflows()[0]->date() : stepDate;\n            Date defaultDate = startDate + (endDate - startDate) / 2;\n            Probability P = creditCurvePtr->defaultProbability(startDate, endDate);\n\n            npvValue += firstCoupon->nominal() * recoveryVal * P * bondReferenceYieldCurve_->discount(defaultDate);\n            startDate = stepDate;\n        }\n    }\n    /* If there are no coupon, as in a Zero Bond, we must integrate over the entire period from npv date to\n       maturity. The timestepPeriod specified is used as provide the steps for the integration. This only applies\n       to bonds with 1 cashflow, identified as a final redemption payment.\n    */\n    if (bd->cashflows().size() == 1) {\n        boost::shared_ptr<Redemption> redemption = boost::dynamic_pointer_cast<Redemption>(bd->cashflows()[0]);\n        if (redemption) {\n            Date startDate = computeDate;\n            while (startDate < redemption->date()) {\n                Date stepDate = startDate + timestepPeriod_;\n                Date endDate = (stepDate > redemption->date()) ? redemption->date() : stepDate;\n                Date defaultDate = startDate + (endDate - startDate) / 2;\n                Probability P = creditCurvePtr->defaultProbability(startDate, endDate);\n\n                npvValue += redemption->amount() * recoveryVal * P * bondReferenceYieldCurve_->discount(defaultDate);\n                startDate = stepDate;\n            }\n        }\n    }\n    return npvValue * arguments_.bondNotional;\n}\n\nboost::tuple<Real, Real> DiscountingForwardBondEngine::calculateForwardContractPresentValue(\n    Real spotValue, Real cmpPayment, Date npvDate, Date computeDate, Date cmpPaymentDate, bool dirty) const {\n    // here we go with the true forward computation\n    Real forwardBondValue = 0.0;\n    Real forwardContractPresentValue = 0.0;\n    Real forwardContractForwardValue = 0.0;\n\n    // handle case where we wish to price simply with benchmark curve and scalar security spread\n    // i.e. credit curve term structure (and recovery) have not been specified\n    // we set the default probability and recovery rate to zero in this instance (issuer credit worthiness already\n    // captured within security spread)\n    boost::shared_ptr<DefaultProbabilityTermStructure> creditCurvePtr =\n        bondDefaultCurve_.empty()\n            ? boost::make_shared<QuantLib::FlatHazardRate>(npvDate, 0.0, bondReferenceYieldCurve_->dayCounter())\n            : bondDefaultCurve_.currentLink();\n    Rate recoveryVal = bondRecoveryRate_.empty() ? 0.0 : bondRecoveryRate_->value(); // setup default bond recovery rate\n\n    // load the shared pointer into bd\n    boost::shared_ptr<Bond> bd = arguments_.underlying;\n\n    // the case of dirty strike corresponds here to an accrual of 0.0. This will be convenient in the code.\n    Real accruedAmount =\n        dirty ? 0.0 : bd->accruedAmount(computeDate) * bd->notional(computeDate) / 100 * arguments_.bondNotional;\n\n    /* Discounting and compounding, taking account of possible bond default before delivery*/\n\n    forwardBondValue =\n        spotValue / (incomeCurve_->discount(computeDate)); // compounding to date of maturity of forward contract\n\n    // Subtract strike at maturity. Regarding accrual (i.e. strike is given clean vs dirty) there are two\n    // cases: long or short.\n\n    // Long: forwardBondValue - strike_dirt = (forwardBondValue - accrual) - strike_clean\n    // Short: strike_dirt - forwardBondValue = strike_clean - (forwardBondValue - accrual)\n    // In total:\n    forwardContractForwardValue = (*arguments_.payoff)(forwardBondValue - accruedAmount);\n\n    // forwardContractPresentValue adjusted for potential default before computeDate:\n    forwardContractPresentValue =\n        forwardContractForwardValue * (discountCurve_->discount(computeDate)) *\n            creditCurvePtr->survivalProbability(computeDate) -\n        cmpPayment *\n            (discountCurve_->discount(cmpPaymentDate)); // The forward is a derivative. We use \"OIS curve\" to discount.\n                                                        // We subtract the potential payment due to Premium.\n\n    // Take account of face value recovery:\n    // A) Recovery for time period when coupons are present\n    for (Size i = 0; i < bd->cashflows().size(); i++) {\n        if (bd->cashflows()[i]->hasOccurred(\n                npvDate, includeSettlementDateFlows_)) // Cashflows before npvDate not relevant for npv\n            continue;\n        if (bd->cashflows()[i]->date() >=\n            computeDate) // Cashflows after computeDate do not fall into the forward period\n            continue;\n        boost::shared_ptr<Coupon> coupon = boost::dynamic_pointer_cast<Coupon>(bd->cashflows()[i]);\n\n        if (coupon) {\n            Date startDate = coupon->accrualStartDate();\n            Date endDate = coupon->accrualEndDate();\n            Date effectiveStartDate = (startDate <= npvDate && npvDate <= endDate) ? npvDate : startDate;\n            Date effectiveEndDate = (startDate <= computeDate && computeDate <= endDate) ? computeDate : endDate;\n            Date defaultDate = effectiveStartDate + (effectiveEndDate - effectiveStartDate) / 2;\n            Probability P = creditCurvePtr->defaultProbability(effectiveStartDate, effectiveEndDate);\n\n            forwardContractPresentValue +=\n                (*arguments_.payoff)(coupon->nominal() * arguments_.bondNotional * recoveryVal - accruedAmount) * P *\n                (discountCurve_->discount(defaultDate));\n        }\n    }\n\n    // B) Recovery for time period before coupons are present\n    boost::shared_ptr<Coupon> firstCoupon = boost::dynamic_pointer_cast<Coupon>(bd->cashflows()[0]);\n    if (firstCoupon) {\n        Date startDate = npvDate; // face value recovery starting with npvDate\n        Date stopDate = std::min(bd->cashflows()[0]->date(), computeDate);\n        while (startDate < stopDate) {\n            Date stepDate = startDate + timestepPeriod_;\n            Date endDate = (stepDate > stopDate) ? stopDate : stepDate;\n            Date defaultDate = startDate + (endDate - startDate) / 2;\n            Probability P = creditCurvePtr->defaultProbability(startDate, endDate);\n\n            forwardContractPresentValue +=\n                (*arguments_.payoff)(firstCoupon->nominal() * arguments_.bondNotional * recoveryVal - accruedAmount) *\n                P * (discountCurve_->discount(defaultDate));\n            startDate = stepDate;\n        }\n    }\n    // C) ZCB\n    /* If there are no coupon, as in a Zero Bond, we must integrate over the entire period from npv date to\n       maturity. The timestepPeriod specified is used as provide the steps for the integration. This only applies\n       to bonds with 1 cashflow, identified as a final redemption payment.\n    */\n    if (bd->cashflows().size() == 1) {\n        boost::shared_ptr<Redemption> redemption = boost::dynamic_pointer_cast<Redemption>(bd->cashflows()[0]);\n        if (redemption) {\n            Date startDate = npvDate;\n            while (startDate < redemption->date()) {\n                Date stepDate = startDate + timestepPeriod_;\n                Date endDate = (stepDate > redemption->date()) ? redemption->date() : stepDate;\n                Date defaultDate = startDate + (endDate - startDate) / 2;\n                Probability P = creditCurvePtr->defaultProbability(startDate, endDate);\n\n                forwardContractPresentValue +=\n                    (*arguments_.payoff)(redemption->amount() * arguments_.bondNotional * recoveryVal - accruedAmount) *\n                    P * (discountCurve_->discount(defaultDate));\n                startDate = stepDate;\n            }\n        }\n    }\n\n    return boost::make_tuple(forwardContractForwardValue, forwardContractPresentValue);\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "6141a9dbf27daf7c2b6a861ffc984636840b07d5", "size": 16331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/pricingengines/discountingforwardbondengine.cpp", "max_stars_repo_name": "nvolfango/Engine", "max_stars_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T17:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T17:24:17.000Z", "max_issues_repo_path": "QuantExt/qle/pricingengines/discountingforwardbondengine.cpp", "max_issues_repo_name": "zhangjiayin/Engine", "max_issues_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/pricingengines/discountingforwardbondengine.cpp", "max_forks_repo_name": "zhangjiayin/Engine", "max_forks_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "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": 53.0227272727, "max_line_length": 120, "alphanum_fraction": 0.685322393, "num_tokens": 3667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2401973761644581}}
{"text": "// -----------------------------------------------------------------------\n//\n// Copyright (C) 2020  - David Fernández Castellanos\n//\n// This file is part of the MEPLS software. You can use it, redistribute\n// it, and/or modify it under the terms of the Creative Commons Attribution\n// 4.0 International Public License. The full text of the license can be\n// found in the file LICENSE at the top level of the MEPLS distribution.\n//\n// -----------------------------------------------------------------------\n\n#include <example.h>\n#include <mepls/utils.h>\n#include <mepls/solver.h>\n#include <mepls/system.h>\n#include <mepls/event.h>\n#include <mepls/history.h>\n\n// MEPLS built-in dynamics\n#include <mepls/dynamics.h>\n\n// to parse command line arguments\n#include <cmdparser.hpp>\n\n// to parse input parameters files\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/path_search.h>\n\n// to save output data in JSON format\n#include <boost/property_tree/json_parser.hpp>\n\n\nstruct Parameters\n{\n\t// these are the parameters and we will use in the simulation, initialized with some default values\n\tunsigned int seed = 1234567;\n\tunsigned int Nx = 32;\n\tunsigned int Ny = 32;\n\tdouble G = 30.;\n\tdouble nu = 0.3;\n\tdouble gamma = 0.05;\n\tdouble k = 6.;\n\tdouble strain_limit = 0.05;\n\tdouble lambda_init = 1.;\n\tdouble lambda_renew = 1.;\n\tstd::string filename = \"out.json\";\n\n\tvoid declare_entries(dealii::ParameterHandler &prm)\n\t{\n\t\t// We declare the entries of the parameters text file. Each entry matches the name of a\n\t\t// simulation parameters (although it doesn't need to) and has a default value. We use as\n\t\t// the default value is the same value of the variables declared above\n\n\t\tprm.enter_subsection(\"Section1\");\n\n\t\tprm.declare_entry(\"seed\", mepls::utils::str::to_string(seed), dealii::Patterns::Integer(0),\n\t\t\t\t\t\t  \"\");\n\t\tprm.declare_entry(\"Nx\", mepls::utils::str::to_string(Nx), dealii::Patterns::Integer(0), \"\");\n\t\tprm.declare_entry(\"Ny\", mepls::utils::str::to_string(Ny), dealii::Patterns::Integer(0), \"\");\n\t\tprm.declare_entry(\"G\", mepls::utils::str::to_string(G), dealii::Patterns::Double(0.0), \"\");\n\t\tprm.declare_entry(\"nu\", mepls::utils::str::to_string(nu), dealii::Patterns::Double(0.0),\n\t\t\t\t\t\t  \"\");\n\t\tprm.declare_entry(\"gamma\", mepls::utils::str::to_string(gamma),\n\t\t\t\t\t\t  dealii::Patterns::Double(0.0), \"\");\n\t\tprm.declare_entry(\"strain_limit\", mepls::utils::str::to_string(strain_limit),\n\t\t\t\t\t\t  dealii::Patterns::Double(0.0), \"\");\n\t\tprm.declare_entry(\"lambda_init\", mepls::utils::str::to_string(lambda_init),\n\t\t\t\t\t\t  dealii::Patterns::Double(0.0), \"\");\n\t\tprm.declare_entry(\"lambda_renew\", mepls::utils::str::to_string(lambda_renew),\n\t\t\t\t\t\t  dealii::Patterns::Double(0.0), \"\");\n\t\tprm.declare_entry(\"k\", mepls::utils::str::to_string(k), dealii::Patterns::Double(0.0), \"\");\n\t\tprm.declare_entry(\"filename\", filename, dealii::Patterns::FileName(), \"\");\n\n\t\tprm.leave_subsection();\n\t}\n\n\tvoid load_entries(dealii::ParameterHandler &prm)\n\t{\n\t\tprm.enter_subsection(\"Section1\");\n\n\t\t// We define how each parameter gets its value from a parameters file entry\n\n\t\tseed = prm.get_integer(\"seed\");\n\t\tNx = prm.get_integer(\"Nx\");\n\t\tNy = prm.get_integer(\"Ny\");\n\t\tG = prm.get_double(\"G\");\n\t\tnu = prm.get_double(\"nu\");\n\t\tgamma = prm.get_double(\"gamma\");\n\t\tk = prm.get_double(\"k\");\n\t\tstrain_limit = prm.get_double(\"strain_limit\");\n\t\tlambda_init = prm.get_double(\"lambda_init\");\n\t\tlambda_renew = prm.get_double(\"lambda_renew\");\n\t\tfilename = prm.get(\"filename\");\n\n\t\tprm.leave_subsection();\n\t}\n\n\tvoid load_file(const std::string &filename)\n\t{\n\t\t// load a parameters file\n\n\t\tdealii::ParameterHandler prm;\n\t\tdeclare_entries(prm);\n\t\tprm.parse_input(filename);\n\t\tload_entries(prm);\n\t}\n\n\tvoid generate_file(const std::string &filename)\n\t{\n\t\t// generate a parameters file template\n\n\t\tstd::ofstream outfile(filename);\n\t\tdealii::ParameterHandler prm;\n\t\tdeclare_entries(prm);\n\t\tprm.print_parameters(outfile, dealii::ParameterHandler::OutputStyle::Text);\n\t}\n\n};\n\n\ntemplate<int dim>\nvoid write_data(\n\tconst mepls::history::History<dim> &sim_history, const Parameters &p)\n{\n\tboost::property_tree::ptree data_tree;\n\n\t// write some metadata, such as a simulation name and description\n\tdata_tree.put(\"Name\", \"Step4\");\n\tdata_tree.put(\"Description\", \"System driven in the athermal quasistatic limit\");\n\n\t// write the simulation parameters\n\tdata_tree.put(\"Parameters.dim\", 2);\n\tdata_tree.put(\"Parameters.seed\", p.seed);\n\tdata_tree.put(\"Parameters.Nx\", p.Nx);\n\tdata_tree.put(\"Parameters.Ny\", p.Ny);\n\tdata_tree.put(\"Parameters.G\", p.G);\n\tdata_tree.put(\"Parameters.nu\", p.nu);\n\tdata_tree.put(\"Parameters.gamma\", p.gamma);\n\tdata_tree.put(\"Parameters.lambda_renew\", p.lambda_renew);\n\tdata_tree.put(\"Parameters.lambda_init\", p.lambda_init);\n\tdata_tree.put(\"Parameters.k\", p.k);\n\tdata_tree.put(\"Parameters.strain_limit\", p.strain_limit);\n\n\n\t// write some metadata, such as a simulation name and description\n\tdata_tree.put(\"Name\", \"Step4\");\n\tdata_tree.put(\"Description\", \"System driven in the athermal quasistatic limit\");\n\n\t// write the simulation parameters\n\tdata_tree.put(\"Parameters.dim\", 2);\n\tdata_tree.put(\"Parameters.seed\", p.seed);\n\tdata_tree.put(\"Parameters.Nx\", p.Nx);\n\tdata_tree.put(\"Parameters.Ny\", p.Ny);\n\tdata_tree.put(\"Parameters.G\", p.G);\n\tdata_tree.put(\"Parameters.nu\", p.nu);\n\tdata_tree.put(\"Parameters.gamma\", p.gamma);\n\tdata_tree.put(\"Parameters.lambda_renew\", p.lambda_renew);\n\tdata_tree.put(\"Parameters.lambda_init\", p.lambda_init);\n\tdata_tree.put(\"Parameters.k\", p.k);\n\tdata_tree.put(\"Parameters.strain_limit\", p.strain_limit);\n\n\t// We write the event histories with CSV format to a string.\n\t// Here, we write only the columns of interest, but there are more available (see the\n\t// documentation).\n\tstd::ostringstream plastic_events_csv;\n\tplastic_events_csv << \"index,element,eigenstrain_00,eigenstrain_11,eigenstrain_01\\n\";\n\tfor(auto &row : sim_history.plastic)\n\t\tplastic_events_csv << row.index << \",\" << row.element << \",\" << row.eigenstrain_00 << \",\"\n\t\t\t\t\t\t   << row.eigenstrain_11 << \",\" << row.eigenstrain_01 << \"\\n\";\n\n\tdata_tree.put(\"Data.plastic_events\", plastic_events_csv.str());\n\n\n\tstd::ostringstream driving_events_csv;\n\tdriving_events_csv << \"index,dext_stress,dtotal_strain\\n\";\n\tfor(auto &row : sim_history.driving)\n\t\tdriving_events_csv << row.index << \",\" << row.dext_stress << \",\" << row.dtotal_strain\n\t\t\t\t\t\t   << \"\\n\";\n\n\tdata_tree.put(\"Data.driving_events\", driving_events_csv.str());\n\n\n\tstd::ostringstream macro_evolution_csv;\n\tmacro_evolution_csv << \"index,ext_stress,total_strain,time,av_vm_stress,av_vm_plastic_strain\\n\";\n\tfor(auto &row : sim_history.macro_evolution)\n\t\tmacro_evolution_csv << row.index << \",\" << row.ext_stress << \",\" << row.total_strain << \",\"\n\t\t\t\t\t\t\t<< row.time << \",\" << row.av_vm_stress << \",\"\n\t\t\t\t\t\t\t<< row.av_vm_plastic_strain << \"\\n\";\n\n\tdata_tree.put(\"Data.macro_evolution\", macro_evolution_csv.str());\n\n\n\t// write the data tree to a JSON file\n\tstd::ofstream output_file(p.filename);\n\tboost::property_tree::json_parser::write_json(output_file, data_tree);\n\toutput_file.close();\n}\n\n\nvoid run(const Parameters &p)\n{\n\t//----- SETUP ------\n\n\t// we do the same as in the previous tutorial, but this time we use the\n\t// parameters from the input Parameters object\n\n\tconstexpr unsigned dim = 2;\n\tstd::mt19937 generator(p.seed);\n\n\tdealii::SymmetricTensor<4, dim> C = mepls::utils::tensor::make_isotropic_stiffness<dim>(p.G,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tp.nu);\n\n\tmepls::element::Vector<dim> elements;\n\n\t// we also store the elements into a vector that knows the derived class, so we can access\n\t// the example::element::Scalar<dim>::conf struct later (this member cannot be accessed\n\t// through the pointers to the base mepls::element::Element<dim>)\n\tstd::vector<example::element::Scalar<dim> *> elements_scalar;\n\n\tfor(double n = 0; n < p.Nx * p.Ny; ++n)\n\t{\n\t\texample::element::Scalar<dim>::Config conf;\n\t\tconf.number = n;\n\t\tconf.gamma = p.gamma;\n\t\tconf.lambda = p.lambda_init;\n\t\tconf.k = p.k;\n\n\t\tauto element = new example::element::Scalar<dim>(conf, generator);\n\t\telement->C(C);\n\n\t\telements_scalar.push_back(element);\n\t\telements.push_back(element);\n\t}\n\n\tmepls::elasticity_solver::LeesEdwards<dim> solver(p.Nx, p.Ny);\n\tfor(auto &element : elements)\n\t\tsolver.set_elastic_properties(element->number(), element->C());\n\tsolver.setup_and_assembly();\n\n\tmepls::element::calculate_ext_stress_coefficients(elements, solver);\n\tmepls::element::calculate_local_stress_coefficients_central(elements, solver);\n\n\tmepls::system::Standard<dim> system(elements, solver, generator);\n\n\tmepls::history::History<dim> sim_history(\"Simulation_history\");\n\n\tsystem.set_history(sim_history);\n\n\t// when the elements were created, their slip systems were initialized with thresholds from a\n\t// Weibull distribution with scale lambda_init. We change it now to lambda_renew. Therefore,\n\t// when plastic deformation occurs, the renew local thresholds will have a different\n\t// average\n\tfor(auto &element : elements_scalar)\n\t\telement->conf.lambda = p.lambda_renew;\n\n\n\t//----- DYNAMICS ------\n\n\t// This object will allow us to check for different conditions by which\n\t// the simulation might stop. Different conditions might be checked, but as long as one of\n\t// them evaluates to false, when continue_simulation() is called it will return false\n\tmepls::utils::ContinueSimulation continue_simulation;\n\n\tsim_history.add_macro(system);\n\n\t// run while the continue_simulation object says so\n\twhile(continue_simulation())\n\t{\n\t\tstd::cout << system.macrostate[\"total_strain\"] << \" \" << system.macrostate[\"ext_stress\"]\n\t\t\t\t  << std::endl;\n\n\n\t\t// these are the same dynamics we implemented in the previous tutorial, but using MEPLS built-in\n\n\t\t// apply an external strain increment of 0.01%\n\t\tmepls::dynamics::finite_extremal_dynamics_step(1e-4, system);\n\t\tsim_history.add_macro(system);\n\n\t\t// perform and avalanche of slip events. By passing the continue_simulation object,\n\t\t// the relaxation function can set its own condition for stopping the simulation.\n\t\t// Specifically, it will check if the avalanche size overcomes a certain maximum upper limit\n\t\tmepls::dynamics::relaxation(system, continue_simulation);\n\t\tsim_history.add_macro(system);\n\n\n\t\t// check if the strain has reached the strain limit. If it has, the next time continue_simulation() is called\n\t\t// it will return false, so we will exit the main loop\n\t\tcontinue_simulation(system.macrostate[\"total_strain\"] < p.strain_limit,\n\t\t\t\t\t\t\t\"total strain limit reached\");\n\n\t}\n\n\t// print the message of the stopping condition that was met\n\tstd::cout << continue_simulation << std::endl;\n\n\tfor(auto &element : elements)\n\t\tdelete element;\n\n\n\twrite_data(sim_history, p);\n}\n\n\nint main(int argc, char *argv[])\n{\n\t// Read the command line arguments. We define the -f 'filename' to pass the\n\t// path to the parameters file\n\tcli::Parser parser(argc, argv);\n\tparser.set_optional<std::string>(\"f\", \"file\", \"./default.prm\",\n\t\t\t\t\t\t\t\t\t \"Name of the input configuration file\");\n\tparser.run_and_exit_if_error();\n\t// you can check https://github.com/FlorianRappl/CmdParser for a further documentation of cli::Parser\n\n\n\n\t// Create the parameters object\n\tParameters p;\n\n\t// We try to load the parameters file, but if it doesn't exist, we generate a new one with the name\n\t// default.prm and default values\n\ttry\n\t{\n\t\tp.load_file(parser.get<std::string>(\"f\"));\n\t}\n\tcatch(dealii::PathSearch::ExcFileNotFound &)\n\t{\n\t\tp.generate_file(parser.get<std::string>(\"f\"));\n\t\tstd::cout << \"Configuration file \" << parser.get<std::string>(\"f\") << \" created\"\n\t\t\t\t  << std::endl;\n\t\treturn 1;\n\t}\n\n\n\t// run the simulation\n\trun(p);\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "393b4fd284fadfc6ff540cd09983956d31c67f37", "size": 11544, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tutorial/step4/step_4.cc", "max_stars_repo_name": "kastellane/MEPLS", "max_stars_repo_head_hexsha": "9d7e4a7b9de73e65e3d4e4aba9b90a6fd563e186", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tutorial/step4/step_4.cc", "max_issues_repo_name": "kastellane/MEPLS", "max_issues_repo_head_hexsha": "9d7e4a7b9de73e65e3d4e4aba9b90a6fd563e186", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tutorial/step4/step_4.cc", "max_forks_repo_name": "kastellane/MEPLS", "max_forks_repo_head_hexsha": "9d7e4a7b9de73e65e3d4e4aba9b90a6fd563e186", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9529411765, "max_line_length": 111, "alphanum_fraction": 0.707033957, "num_tokens": 2922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.24015142691958238}}
{"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/ros2_pcl_utils/blob/master/LICENSE\n\n#include \"pcl_utils/feature.hpp\"\n\n#include <Eigen/Core>\n\n#include <memory>\n#include <utility>\n#include <vector>\n\n#include \"pcl_utils/pcl_iterator.hpp\"\n\n\nnamespace cbr\n{\n\nstruct ScanInfo\n{\n  uint32_t idx = 0;  // index in scan\n  bool ok = false;   // if eligible to be a feature\n  float cvalue = 0;  // estimate of smoothness\n};\n\n\nstd::pair<sensor_msgs::msg::PointCloud2::UniquePtr, sensor_msgs::msg::PointCloud2::UniquePtr>\npcl_features(const sensor_msgs::msg::PointCloud2 & msg, const PclFeatureParams & prm)\n{\n  const uint32_t N = msg.height * msg.width;\n  const uint32_t W = prm.window;\n\n  if (N < 2 * W + 1) {\n    return {nullptr, nullptr};  // too few points to process\n  }\n\n\n  //////////////////////////\n  // STEP 1: VALID POINTS //\n  //////////////////////////\n\n  std::vector<bool> valid(N, false);\n\n  std::vector<bool> ang_discont(N - 1, false);  // angle discontinuity\n  std::vector<int8_t> dist_discont(N - 1, 0);   // distance discontinuity\n  std::vector<bool> inc_ang_viol(N - 1, 0);     // incidence angle bound violation\n\n  const auto cos_ang_disc_thresh = std::cos(prm.ang_disc_thresh);\n  const auto sin_ang_inc_thresh = std::sin(prm.ang_inc_thresh);\n\n  PclIterator it(msg);\n  for (auto i = 0u; i != N - 1; ++i, ++it) {\n    const auto p0 = *it;\n    const auto p1 = *(it + 1);\n    const auto r0 = p0.norm();\n    const auto r1 = p1.norm();\n    const auto r01 = (p1 - p0).norm();\n\n    // incidence angle difference from 90 (perpendicular incidence)\n    //  | alpha - pi/2 | <= b\n    //  | cos(alpha) | <= sin(b)\n    if (std::abs<float>(p0.dot(p1 - p0)) / (r0 * r01) > sin_ang_inc_thresh) {\n      inc_ang_viol[i] = true;\n    }\n\n    // angular discontinuity\n    // cos alpha = dot(p0, p1) / ||p1|| ||p2||\n    // |alpha| > b  <==>  cos(alpha) < cos(b) <==>  dot(p0, p1) / (||p1|| ||p2||) < cos(b)\n    if (p0.dot(p1) / (r0 * r1) < cos_ang_disc_thresh) {\n      ang_discont[i] = true;\n    }\n\n    // distance discontinuity\n    if (2 * r01 > prm.rel_disc_thresh * (r0 + r1)) {\n      if (r0 < r1) {\n        dist_discont[i] = -1;  // p1 further away than p0\n      } else {\n        dist_discont[i] = 1;   // p1 closer than p0\n      }\n    }\n  }\n\n  // sliding window count of number of angular discontinuities\n  uint32_t num_ang_discont = 0;\n  for (auto i = 0u; i < 2u * W; ++i) {\n    num_ang_discont += uint32_t(ang_discont[i]);\n  }\n\n  // sliding window count of distance discontinuities\n  uint32_t num_dist_discont_neg_left = 0;  // count decreasing on the left\n  uint32_t num_dist_discont_pos_rght = 0;  // count increasing on the right\n  for (auto i = 0u; i < W; ++i) {\n    num_dist_discont_neg_left += uint32_t(dist_discont[i] == -1);\n  }\n  for (auto i = W; i < 2 * W; ++i) {\n    num_dist_discont_pos_rght += uint32_t(dist_discont[i] == 1);\n  }\n\n  it = PclIterator(msg) + W;\n  for (auto i = W; i + W < N; ++i, ++it) {\n    valid[i] = true;\n\n    if (num_dist_discont_neg_left > 0 || num_dist_discont_pos_rght > 0) {\n      // distance discontinuity condition (robustly visible)\n      valid[i] = false;\n    } else if (num_ang_discont > 0) {\n      // no angular discontinuities in window\n      valid[i] = false;\n    } else if (inc_ang_viol[i - 1] && inc_ang_viol[i]) {\n      // incidence angle condition\n      valid[i] = false;\n    } else if (it.intensity() < prm.min_intensity || it.intensity() > prm.max_intensity) {\n      // intensity condition\n      valid[i] = false;\n    } else if (std::atan2((*it).tail<2>().norm(), (*it).x()) > prm.max_angle) {\n      // angle condition\n      valid[i] = false;\n    } else {\n      // depth condition\n      auto norm = (*it).norm();\n      if (norm < prm.min_depth || norm > prm.max_depth) {\n        valid[i] = false;\n      }\n    }\n\n    // update sliding window counters\n    num_ang_discont -= ang_discont[i - W];\n    num_ang_discont += ang_discont[i + W];\n    num_dist_discont_neg_left -= uint32_t(dist_discont[i - W] == -1);\n    num_dist_discont_neg_left += uint32_t(dist_discont[i] == -1);\n    num_dist_discont_pos_rght -= uint32_t(dist_discont[i] == 1);\n    num_dist_discont_pos_rght += uint32_t(dist_discont[i + W] == 1);\n  }\n\n  //////////////////////\n  // STEP 2: FEATURES //\n  //////////////////////\n\n  // cumulative vector sum in window\n  Eigen::Vector3f csum(0, 0, 0);\n\n  std::vector<ScanInfo> cands;\n\n  // fast iterator: point one past right end of interval\n  auto i_f = 0u;\n  auto it_f = PclIterator(msg);\n  for (; i_f != 2 * W + 1; ++i_f, ++it_f) {\n    csum += *it_f;\n  }\n\n  // mid iterator: points to active point\n  auto it_m = PclIterator(msg) + W;\n\n  // slow iterator: points to left end of interval\n  auto i_s = 0u;\n  auto it_s = PclIterator(msg);\n\n  // calculate c-values:\n  //  c = || (2*W + 1) * p - \\sum_i p_i || / ( 2 * W * ||p|| )\n  //    = || 2 * W * p - \\sum_{i != 0} p_i || / (2 * W * ||p||  )\n  //    = || p  -  (1/2W) \\sum_{i != 0} p_i || / || p ||\n\n  // if c-value is small it is likely a planar point (p close to average of surrounding pts)\n  // if c-value is large it is likely an edge point (p far from average of surrounding pts)\n  for (; i_f != N; ++i_s, ++i_f, ++it_s, ++it_m, ++it_f) {\n    uint32_t i_mid = i_s + W;\n\n    if (valid[i_mid]) {\n      cands.push_back(\n        {i_mid, true, ((2 * W + 1) * (*it_m) - csum).norm() / (2 * W * (*it_m).norm())}\n      );\n    }\n\n    csum -= *it_s;\n    csum += *it_f;\n  }\n\n  // sort candidates by c-value\n  std::sort(\n    cands.begin(), cands.end(), [](const auto & item1, const auto & item2) {\n      return item1.cvalue < item2.cvalue;\n    });\n\n  // extract features\n\n  // edges from back\n  auto edges = std::make_unique<sensor_msgs::msg::PointCloud2>();\n  edges->fields = msg.fields;\n  edges->point_step = msg.point_step;\n  edges->is_bigendian = msg.is_bigendian;\n  edges->header = msg.header;\n\n  for (auto it = cands.crbegin(); it != cands.crend() && it->cvalue > prm.edge_thresh; ++it) {\n    auto &[idx, ok, cvalue] = *it;\n    if (valid[idx]) {\n      std::copy(\n        msg.data.begin() + idx * msg.point_step,\n        msg.data.begin() + (idx + 1) * msg.point_step,\n        std::back_insert_iterator(edges->data)\n      );\n      for (auto idx_i = idx - W; idx_i != idx + W + 1; ++idx_i) {\n        valid[idx_i] = false;  // mark surrounding as taken\n      }\n    }\n  }\n\n  edges->width = edges->data.size() / edges->point_step;\n  edges->row_step = edges->width;\n  edges->height = 1;\n  edges->is_dense = 1;\n\n  // planar from front\n  auto planar = std::make_unique<sensor_msgs::msg::PointCloud2>();\n  planar->fields = msg.fields;\n  planar->point_step = msg.point_step;\n  planar->is_bigendian = msg.is_bigendian;\n  planar->header = msg.header;\n\n  for (auto it = cands.cbegin(); it != cands.cend() && it->cvalue < prm.plane_thresh; ++it) {\n    auto &[idx, ok, cvalue] = *it;\n    if (valid[idx]) {\n      std::copy(\n        msg.data.begin() + idx * msg.point_step,\n        msg.data.begin() + (idx + 1) * msg.point_step,\n        std::back_insert_iterator(planar->data)\n      );\n      for (auto idx_i = idx - W; idx_i != idx + W + 1; ++idx_i) {\n        valid[idx_i] = false;  // mark surrounding as taken\n      }\n    }\n  }\n\n  planar->width = planar->data.size() / planar->point_step;\n  planar->row_step = planar->width;\n  planar->height = 1;\n  planar->is_dense = 1;\n\n  return {std::move(edges), std::move(planar)};\n}\n\n}  // namespace cbr\n", "meta": {"hexsha": "a08712b5162a60745d02cc4c3d9b9092aedc2dfb", "size": 7348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/feature.cpp", "max_stars_repo_name": "yamaha-bps/ros2_pcl_utils", "max_stars_repo_head_hexsha": "513615ac1b6b251a39f29eb7ff03f307747b8aa3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-05T14:35:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-05T14:35:35.000Z", "max_issues_repo_path": "src/feature.cpp", "max_issues_repo_name": "yamaha-bps/ros2_pcl_utils", "max_issues_repo_head_hexsha": "513615ac1b6b251a39f29eb7ff03f307747b8aa3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/feature.cpp", "max_forks_repo_name": "yamaha-bps/ros2_pcl_utils", "max_forks_repo_head_hexsha": "513615ac1b6b251a39f29eb7ff03f307747b8aa3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T01:35:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T01:35:07.000Z", "avg_line_length": 30.3636363636, "max_line_length": 94, "alphanum_fraction": 0.5870985302, "num_tokens": 2343, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.44552953503957277, "lm_q1q2_score": 0.24013294370711535}}
{"text": "/*\n ============================================================================\n Name        : INSIGHTv3_mpi.cpp\n Author      : Jan Mikelson\n Version     :\n Copyright   : \tThis free software is available under the Creative Commons Attribution Share Alike License.\n You are permitted to use, redistribute and adapt this software as long as appropriate credit\n is given to the original author, and all derivative works are distributed under the same\n license or a compatible one.\n For more information, visit http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to\n Creative Commons, 171 2nd Street, Suite 300, San Francisco, California, 94105, USA.\n Description : \tParallel version of the INSIGHT algorithm. Further details can be found in Lillacci & Khammash 2013\n ============================================================================\n */\n\n#include <ctime>\n#include <vector>\n\n#include <stdio.h>  /* defines FILENAME_MAX */\n#ifdef WINDOWS\n#include <direct.h>\n#define GetCurrentDir _getcwd\n#else\n#include <unistd.h>\n#define GetCurrentDir getcwd\n#endif\n\nchar cCurrentPath[FILENAME_MAX];\n\n#include <boost/program_options.hpp>\n#include <boost/smart_ptr/make_shared.hpp>\n#include <boost/ref.hpp>\n#include <Eigen/Dense>\n#include <mpi.h>\n\n#include \"INSIGHTv3.h\"\n#include \"BirthDeathModel.h\"\n#include \"InsightAlgorithm.h\"\n#include \"InsightParticleSamplerFactory.h\"\n#include \"IllegalArgumentException.h\"\n#include \"ParticleEvaluatorInsight.h\"\n#include \"UniformSamplerFactory.h\"\n#include \"ScaledUniformSamplerFactory.h\"\n#include \"ProblemFileReader.h\"\n#include \"ModelDescription.h\"\n#include \"UniformSampler.h\"\n#include \"InsightIterationMpi.h\"\n#include \"InsightMpiWorker.h\"\n#include \"PrevPopReader.h\"\n\nusing namespace INSIGHTv3;\n\n//Default values\nconst static std::string PROBLEM_FILE = \"\";\nconst static int S = 3;\nconst static double FINAL_TOLERANCE = 0.03;\nconst static int NUM_PARTICLES = 1000;\nconst static std::string OUTPUT_FILE = \"\";\nconst static std::string PREVIOUS_POPULATION_FILE = \"\";\nconst static bool IGNORE_WEIGHTS = false;\nconst static int PRINT = 20;\nconst static double BETA = 0.01;\nconst static double TOL_KOLMOGOROV = 0.0000001;\nconst static double KAPPA_KOLMOGOROV = 0.005224; // kappa value for M = 80000 and beta = 0.01\nconst static double TOL_KAPPA_KOLMOGOROV = 0.01;\n\nstd::string problem_file_name;\nint s;\ndouble final_tolerance;\nint num_particles;\nstd::string output_file_name;\nstd::string prev_pop_file;\nbool ignore_weights;\nint print;\ndouble beta;\ndouble tolerance_kolmogorov;\ndouble kappa_kolmogorov;\ndouble tol_kappa_kolmovorog;\n\nnamespace po = boost::program_options;\n\nvoid handleOptions(int argc, char * argv[]);\nvoid printInfo(ModelDescription& desc);\n\nint main(int argc, char *argv[]) {\n\n\thandleOptions(argc, argv);\n\n\tclock_t tic = clock();\n\tMPI::Init(argc, argv);\n\tint my_rank = MPI::COMM_WORLD.Get_rank();\n\tint num_tasks = MPI::COMM_WORLD.Get_size();\n\n\tif (num_tasks == 1) {\n\t\tstd::cerr\n\t\t\t\t<< \"When using mpi version of INSIGHT at least two processes must be started!\"\n\t\t\t\t<< std::endl;\n\t\tabort();\n\t}\n\n\tint seed = time(NULL) + my_rank;\n#ifdef DEBUG\n\tseed = 2;\n#endif\n\tRngPtr rng = boost::make_shared<RandomNumberGenerator>(seed);\n\n\tProblemFileReader reader;\n\tModelDescription desc = reader.read(rng, problem_file_name);\n\n\tKolmogorovComputerPtr kolmogorov_computer = boost::make_shared<\n\t\t\tKolmogorovComputer>(*desc.original_data, beta, tolerance_kolmogorov,\n\t\t\tkappa_kolmogorov);\n\tevaluator_ptr evaluator = boost::make_shared<ParticleEvaluatorInsight>(\n\t\t\tboost::ref(*desc.model), *desc.times, boost::ref(rng),\n\t\t\tkolmogorov_computer); // need to use boost::ref, see boost\n\tsampler_ptr prior_sampler = boost::make_shared<UniformSampler>(\n\t\t\tboost::ref(rng), *desc.lower_bounds_parameter,\n\t\t\t*desc.upper_bounds_parameter);\n\n\tif (my_rank == 0) {\n\t\tprintInfo(desc);\n\t\twriter_ptr writer = boost::make_shared<InsightOutputWriter>(\n\t\t\t\toutput_file_name);\n\n\t\tsampler_factory_ptr factory = boost::make_shared<\n\t\t\t\tScaledUniformSamplerFactory>(boost::ref(rng),\n\t\t\t\tdesc.model->num_params, *desc.lower_bounds_parameter,\n\t\t\t\t*desc.upper_bounds_parameter, ignore_weights);\n\n\t\tInsightIterationMpi iteration(num_tasks, prior_sampler);\n\t\tToleranceProviderPtr tolerance_provider = boost::make_shared<\n\t\t\t\tFixedSequenceToleranceProvider>(s, desc.model->model,\n\t\t\t\tkolmogorov_computer);\n\n\t\tsampler_ptr first_sampler;\n\t\tstd::vector<double> prev_acceptance_rates;\n\t\tstd::vector<double> prev_tolerances;\n\t\tstd::vector<int> prev_num_simulations;\n\t\tif (prev_pop_file.length() > 0) {\n\t\t\tPrevPopReader prev_pop_reader;\n\t\t\tParticleSet particle_set;\n\t\t\tprev_pop_reader.readPreviousPop(prev_pop_file,\n\t\t\t\t\tdesc.model->num_params, &particle_set,\n\t\t\t\t\t&prev_acceptance_rates, &prev_tolerances,\n\t\t\t\t\t&prev_num_simulations);\n\t\t\tfirst_sampler = factory->createSampler(particle_set,\n\t\t\t\t\tkolmogorov_computer->getThresholdForS(s), s);\n\t\t} else {\n\t\t\tfirst_sampler = prior_sampler;\n\t\t}\n\t\tInsightAlgorithm algorithm(iteration, factory, evaluator, writer,\n\t\t\t\ttolerance_provider, final_tolerance, num_particles,\n\t\t\t\tdesc.model->num_params, prev_acceptance_rates, prev_tolerances,\n\t\t\t\tprev_num_simulations);\n\t\tIterationLogger logger(print);\n\n\t\talgorithm.run(first_sampler, logger);\n\n\t\tMPI_INSTRUCTION instruction(DIETAG);\n\t\tfor (int rank = 1; rank < num_tasks; rank++) {\n\t\t\tMPI::COMM_WORLD.Send(&instruction, 1, MPI::INT, rank, INSTRUCTION);\n\t\t}\n\t} else {\n\t\tInsightMpiWorker worker(my_rank, desc.model->num_params, evaluator,\n\t\t\t\tprior_sampler);\n\t\tworker.run();\n\t}\n\n\tclock_t toc = clock();\n\tif (my_rank == 0) {\n\t\tstd::cout << \"\\n\\nSMC inference complete.\" << std::endl;\n\t\tstd::cout << \"\\nElapsed time: \"\n\t\t\t\t<< ((double) (toc - tic)) / CLOCKS_PER_SEC << \"sec.\\n\"\n\t\t\t\t<< std::endl;\n\t}\n\tMPI::Finalize();\n\n\treturn 0;\n}\n\nvoid handleOptions(int argc, char * argv[]) {\n\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()(\"help\", \"produce help message\")(\"problem_file\",\n\t\t\tpo::value<std::string>(&problem_file_name)->default_value(\n\t\t\t\t\tPROBLEM_FILE),\n\t\t\t\"problem file. A problem file must always be provided!\")(\n\t\t\t\"number_simulations,s\", po::value<int>(&s)->default_value(S),\n\t\t\t\"starting number of simulations\")(\"final tolerance,e\",\n\t\t\tpo::value<double>(&final_tolerance)->default_value(FINAL_TOLERANCE),\n\t\t\t\"the final tolerance for the algorithm\")(\"pop_size,n\",\n\t\t\tpo::value<int>(&num_particles)->default_value(NUM_PARTICLES),\n\t\t\t\"define the population size\")(\"output_file,O\",\n\t\t\tpo::value<std::string>(&output_file_name)->default_value(\n\t\t\t\t\tOUTPUT_FILE), \"output file\")(\"previous_pop_file,P\",\n\t\t\tpo::value<std::string>(&prev_pop_file)->default_value(\n\t\t\t\t\tPREVIOUS_POPULATION_FILE), \"previous population file\")(\n\t\t\t\"ignore_weights,i\",\n\t\t\tpo::value<bool>(&ignore_weights)->default_value(IGNORE_WEIGHTS),\n\t\t\t\"ignore weights\")(\"print,p\",\n\t\t\tpo::value<int>(&print)->default_value(PRINT),\n\t\t\t\"define the frequency of print outs\")(\"beta,b\",\n\t\t\tpo::value<double>(&beta)->default_value(BETA),\n\t\t\t\"the confidence of the kolmogorov test for the rejection rule\")(\n\t\t\t\"tol_kol,k\",\n\t\t\tpo::value<double>(&tolerance_kolmogorov)->default_value(\n\t\t\t\t\tTOL_KOLMOGOROV),\n\t\t\t\"the tolerance for the algorithm to compute the inverse of the kolmogorov distribution\")(\n\t\t\t\"kappa,K\",\n\t\t\tpo::value<double>(&kappa_kolmogorov)->default_value(\n\t\t\t\t\tKAPPA_KOLMOGOROV),\n\t\t\t\"Kappa for the computation of the Kolmogorov distance\")(\n\t\t\t\"tol_kol_kap,T\",\n\t\t\tpo::value<double>(&tol_kappa_kolmovorog)->default_value(\n\t\t\t\t\tTOL_KAPPA_KOLMOGOROV),\n\t\t\t\"the tolerance for the algorithm to compute kappa for the computation of the Kolmogorov distance\");\n\n\tpo::positional_options_description p;\n\tp.add(\"problem_file\", -1);\n\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::store(\n\t\t\tpo::command_line_parser(argc, argv).options(desc).positional(p).run(),\n\t\t\tvm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t\tstd::cout << desc << \"\\n\";\n\t\tabort();\n\t}\n\n\tif (problem_file_name.size() == 0) {\n\t\tstd::cerr << \"Problem file is required\" << std::endl;\n\t\tabort();\n\t}\n\n\tif (output_file_name.size() == 0) {\n\t\tGetCurrentDir(cCurrentPath, sizeof(cCurrentPath));\n\t\toutput_file_name = std::string(cCurrentPath) + \"/resutls.txt\";\n\t}\n\n}\n\nvoid printInfo(ModelDescription& desc) {\n\n\tstd::cout << \"\\nThis is INSIGHT v3.0\\n\" << std::endl;\n\tstd::cout << \"Problem file path:\" << std::endl;\n\tstd::cout << problem_file_name << std::endl;\n\tstd::cout << \"\\nThe new particle population will be saved in:\" << std::endl;\n\tstd::cout << output_file_name << std::endl;\n\n\tstd::cout << \"\\nWill estimate \" << desc.model->model_name << \" using \"\n\t\t\t<< num_particles << \" SMC particles.\" << std::endl;\n\tstd::cout << \"\\nThe data is assumed to have been created using \"\n\t\t\t<< desc.model->num_outputs << \" outputs,\" << std::endl;\n\tstd::cout << \"measured at \" << desc.times->size() << \" timepoints.\"\n\t\t\t<< std::endl;\n\n\tif (prev_pop_file.length() > 0) {\n\t\tstd::cout << \"A previous population is loaded from file: \" << std::endl;\n\t\tstd::cout << prev_pop_file << std::endl;\n\t}\n\tstd::cout << \"To estimate the density of each population \"\n\t\t\t<< \"Kernel Density Estimation with uniform Kernel\" << std::endl;\n\tstd::cout << \"is used.\" << std::endl;\n\tif (ignore_weights) {\n\t\tstd::cout << std::endl << \"Particle weights will be ignored by sampler!\"\n\t\t\t\t<< std::endl;\n\t}\n\tstd::cout << \"\\nThe parallel version of the algorithm is used.\"\n\t\t\t<< std::endl;\n}\n", "meta": {"hexsha": "e318488100c57ad2e8626c6f844b1146baafd4de", "size": 9312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "container/INSIGHT/src/INSIGHTv3_mpi.cpp", "max_stars_repo_name": "mcapuccini/cloud-insight", "max_stars_repo_head_hexsha": "96fa1a12baa7aebd31878a969d2e43e5355714fa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T12:43:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-21T12:43:48.000Z", "max_issues_repo_path": "container/INSIGHT/src/INSIGHTv3_mpi.cpp", "max_issues_repo_name": "mcapuccini/cloud-insight", "max_issues_repo_head_hexsha": "96fa1a12baa7aebd31878a969d2e43e5355714fa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2016-11-29T14:28:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-10T14:14:13.000Z", "max_forks_repo_path": "container/INSIGHT/src/INSIGHTv3_mpi.cpp", "max_forks_repo_name": "mcapuccini/cloud-insight", "max_forks_repo_head_hexsha": "96fa1a12baa7aebd31878a969d2e43e5355714fa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-07-17T20:05:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T08:29:07.000Z", "avg_line_length": 33.9854014599, "max_line_length": 115, "alphanum_fraction": 0.7111254296, "num_tokens": 2457, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4726834766204328, "lm_q1q2_score": 0.24003427747659772}}
{"text": "#include \"Poisson.h\"\n#include \"config.h\"\n#include \"kernels/poisson/init.h\"\n#include \"kernels/poisson/kernel.h\"\n#include \"kernels/poisson/tensor.h\"\n\n#include \"basis/WarpAndBlend.h\"\n#include \"form/BC.h\"\n#include \"form/DGCurvilinearCommon.h\"\n#include \"form/InverseInequality.h\"\n#include \"form/RefElement.h\"\n#include \"geometry/Curvilinear.h\"\n#include \"quadrules/SimplexQuadratureRule.h\"\n#include \"tensor/EigenMap.h\"\n#include \"util/LinearAllocator.h\"\n\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <cassert>\n\nnamespace tensor = tndm::poisson::tensor;\nnamespace init = tndm::poisson::init;\nnamespace kernel = tndm::poisson::kernel;\n\nnamespace tndm {\n\nPoisson::Poisson(std::shared_ptr<Curvilinear<DomainDimension>> cl, functional_t<1> K,\n                 DGMethod method)\n    : DGCurvilinearCommon<DomainDimension>(std::move(cl), MinQuadOrder()), method_(method),\n      space_(PolynomialDegree, ALIGNMENT),\n      materialSpace_(PolynomialDegree, WarpAndBlendFactory<DomainDimension>(), ALIGNMENT),\n      fun_K(make_volume_functional(std::move(K))), fun_force(zero_volume_function),\n      fun_dirichlet(zero_facet_function), fun_slip(zero_facet_function) {\n\n    Minv_ = space_.inverseMassMatrix();\n    E_Q = space_.evaluateBasisAt(volRule.points());\n    E_Q_T = space_.evaluateBasisAt(volRule.points(), {1, 0});\n    Dxi_Q = space_.evaluateGradientAt(volRule.points());\n\n    negative_E_Q_T = Managed<Matrix<double>>(E_Q_T.shape(), std::size_t{ALIGNMENT});\n    EigenMap(negative_E_Q_T) = -EigenMap(E_Q_T);\n\n    for (std::size_t f = 0; f < DomainDimension + 1u; ++f) {\n        auto points = cl_->facetParam(f, fctRule.points());\n        E_q.emplace_back(space_.evaluateBasisAt(points));\n        E_q_T.emplace_back(space_.evaluateBasisAt(points, {1, 0}));\n        Dxi_q.emplace_back(space_.evaluateGradientAt(points));\n        Dxi_q_120.emplace_back(space_.evaluateGradientAt(points, {1, 2, 0}));\n        matE_q_T.emplace_back(materialSpace_.evaluateBasisAt(points, {1, 0}));\n\n        negative_E_q_T.emplace_back(space_.evaluateBasisAt(points, {1, 0}));\n        auto E = EigenMap(negative_E_q_T.back());\n        E = -E;\n    }\n\n    matE_Q_T = materialSpace_.evaluateBasisAt(volRule.points(), {1, 0});\n    matDxi_Q = materialSpace_.evaluateGradientAt(volRule.points());\n}\n\nvoid Poisson::compute_mass_matrix(std::size_t elNo, double* M) const {\n    kernel::massMatrix mm;\n    mm.E_Q = E_Q.data();\n    mm.J_Q = vol[elNo].get<AbsDetJ>().data();\n    mm.M = M;\n    mm.W = volRule.weights().data();\n    mm.execute();\n}\n\nvoid Poisson::compute_inverse_mass_matrix(std::size_t elNo, double* Minv) const {\n    compute_mass_matrix(elNo, Minv);\n\n    auto J_Q = vol[elNo].get<AbsDetJ>();\n    alignas(ALIGNMENT) double Jinv_Q[tensor::Jinv_Q::size()] = {};\n    for (unsigned q = 0; q < tensor::Jinv_Q::Shape[0]; ++q) {\n        Jinv_Q[q] = 1.0 / J_Q[q];\n    }\n\n    kernel::MinvWA wa;\n    wa.E_Q = E_Q.data();\n    wa.Jinv_Q = Jinv_Q;\n    wa.MinvRef = Minv_.data();\n    wa.MinvWA = Minv;\n    wa.W = volRule.weights().data();\n    wa.execute();\n}\n\nvoid Poisson::compute_K_Dx_q(std::size_t fctNo, FacetInfo const& info,\n                             std::array<double*, 2> K_Dx_q) const {\n    kernel::K_Dx_q dx;\n    for (int i = 0; i < 2; ++i) {\n        if (K_Dx_q[i]) {\n            auto JInv = (i == 1) ? fct[fctNo].get<JInv1>() : fct[fctNo].get<JInv0>();\n            dx.G_q = JInv.data()->data();\n            dx.matE_q_T = matE_q_T[info.localNo[i]].data();\n            dx.K = material[info.up[i]].get<K>().data();\n            dx.K_Dx_q(0) = K_Dx_q[i];\n            dx.Dxi_q(0) = Dxi_q[info.localNo[i]].data();\n            dx.execute();\n        }\n    }\n}\n\nvoid Poisson::compute_K_q(std::size_t fctNo, FacetInfo const& info,\n                          std::array<double*, 2> K_q) const {\n    kernel::K_q kw;\n    for (int i = 0; i < 2; ++i) {\n        if (K_q[i]) {\n            kw.matE_q_T = matE_q_T[info.localNo[i]].data();\n            kw.K = material[info.up[i]].get<K>().data();\n            kw.K_q(0) = K_q[i];\n            kw.execute();\n        }\n    }\n}\n\nvoid Poisson::begin_preparation(std::size_t numElements, std::size_t numLocalElements,\n                                std::size_t numLocalFacets) {\n    base::begin_preparation(numElements, numLocalElements, numLocalFacets);\n\n    material.setStorage(\n        std::make_shared<material_vol_t>(numElements * materialSpace_.numBasisFunctions()), 0u,\n        numElements, materialSpace_.numBasisFunctions());\n\n    volPre.setStorage(std::make_shared<vol_pre_t>(numElements * volRule.size()), 0u,\n                      numLocalElements, volRule.size());\n\n    fctPre.setStorage(std::make_shared<fct_pre_t>(numLocalFacets * fctRule.size()), 0u,\n                      numLocalFacets, fctRule.size());\n\n    penalty_.resize(numLocalFacets);\n}\n\nvoid Poisson::prepare_volume(std::size_t elNo, LinearAllocator<double>& scratch) {\n    base::prepare_volume(elNo, scratch);\n\n    auto Kfield = material[elNo].get<K>().data();\n    alignas(ALIGNMENT) double K_Q_raw[tensor::K_Q::size()];\n    auto K_Q = Matrix<double>(K_Q_raw, 1, volRule.size());\n    fun_K(elNo, K_Q);\n\n    alignas(ALIGNMENT) double Mmem[tensor::matM::size()];\n    kernel::project_K_lhs krnl_lhs;\n    krnl_lhs.matE_Q_T = matE_Q_T.data();\n    krnl_lhs.J_Q = vol[elNo].get<AbsDetJ>().data();\n    krnl_lhs.matM = Mmem;\n    krnl_lhs.W = volRule.weights().data();\n    krnl_lhs.execute();\n\n    kernel::project_K_rhs krnl_rhs;\n    krnl_rhs.matE_Q_T = matE_Q_T.data();\n    krnl_rhs.J_Q = vol[elNo].get<AbsDetJ>().data();\n    krnl_rhs.K = Kfield;\n    krnl_rhs.K_Q = K_Q_raw;\n    krnl_rhs.W = volRule.weights().data();\n    krnl_rhs.execute();\n\n    using MMap = Eigen::Map<Eigen::Matrix<double, tensor::matM::Shape[0], tensor::matM::Shape[1]>,\n                            Eigen::Unaligned,\n                            Eigen::OuterStride<init::matM::Stop[0] - init::matM::Start[0]>>;\n    using KMap = Eigen::Map<Eigen::Matrix<double, tensor::K::Shape[0], 1>, Eigen::Unaligned,\n                            Eigen::InnerStride<1>>;\n\n    auto K_eigen = KMap(Kfield);\n    K_eigen = MMap(Mmem).fullPivLu().solve(K_eigen);\n}\n\nvoid Poisson::prepare_skeleton(std::size_t fctNo, FacetInfo const& info,\n                               LinearAllocator<double>& scratch) {\n    base::prepare_skeleton(fctNo, info, scratch);\n\n    for (int side = 0; side < 2; ++side) {\n        kernel::K_G_q k;\n        k.G_q = side == 1 ? fct[fctNo].get<JInv1>().data()->data()\n                          : fct[fctNo].get<JInv0>().data()->data();\n        k.K = material[info.up[side]].get<K>().data();\n        k.K_G_q(0) = side == 1 ? fctPre[fctNo].get<KJInv1>().data()->data()\n                               : fctPre[fctNo].get<KJInv0>().data()->data();\n        k.matE_q_T = matE_q_T[info.localNo[side]].data();\n        k.execute();\n    }\n}\n\nvoid Poisson::prepare_boundary(std::size_t fctNo, FacetInfo const& info,\n                               LinearAllocator<double>& scratch) {\n    base::prepare_boundary(fctNo, info, scratch);\n\n    kernel::K_G_q k;\n    k.G_q = fct[fctNo].get<JInv0>().data()->data();\n    k.K = material[info.up[0]].get<K>().data();\n    k.K_G_q(0) = fctPre[fctNo].get<KJInv0>().data()->data();\n    k.matE_q_T = matE_q_T[info.localNo[0]].data();\n    k.execute();\n}\n\nvoid Poisson::prepare_volume_post_skeleton(std::size_t elNo, LinearAllocator<double>& scratch) {\n    base::prepare_volume_post_skeleton(elNo, scratch);\n\n    auto Kfield = material[elNo].get<K>().data();\n\n    kernel::J_W_K_Q krnl;\n    krnl.J_W_K_Q = volPre[elNo].get<AbsDetJWK>().data()->data();\n    krnl.J_Q = vol[elNo].get<AbsDetJ>().data();\n    krnl.K = Kfield;\n    krnl.matE_Q_T = matE_Q_T.data();\n    krnl.W = volRule.weights().data();\n    krnl.execute();\n}\n\nvoid Poisson::prepare_penalty(std::size_t fctNo, FacetInfo const& info, LinearAllocator<double>&) {\n    auto const p = [&](int side) {\n        auto Kfield = material[info.up[side]].get<K>().data();\n        auto k0 = *std::min_element(Kfield, Kfield + materialSpace_.numBasisFunctions());\n        auto k1 = *std::max_element(Kfield, Kfield + materialSpace_.numBasisFunctions());\n        constexpr double c_N_1 = InverseInequality<Dim>::trace_constant(PolynomialDegree - 1);\n        return (Dim + 1) * c_N_1 * (area_[fctNo] / volume_[info.up[side]]) * (k1 * k1 / k0);\n    };\n\n    if (info.up[0] != info.up[1]) {\n        penalty_[fctNo] = (p(0) + p(1)) / 4.0;\n    } else {\n        penalty_[fctNo] = p(0);\n    }\n}\n\nbool Poisson::assemble_volume(std::size_t elNo, Matrix<double>& A00,\n                              LinearAllocator<double>& scratch) const {\n    alignas(ALIGNMENT) double Dx_Q[tensor::Dx_Q::size()];\n\n    assert(volRule.size() == tensor::W::Shape[0]);\n    assert(Dxi_Q.shape(0) == tensor::Dxi_Q::Shape[0]);\n    assert(Dxi_Q.shape(1) == tensor::Dxi_Q::Shape[1]);\n    assert(Dxi_Q.shape(2) == tensor::Dxi_Q::Shape[2]);\n\n    kernel::Dx_Q dx;\n    dx.Dx_Q = Dx_Q;\n    dx.Dxi_Q = Dxi_Q.data();\n    dx.G_Q = vol[elNo].get<JInv>().data()->data();\n    dx.execute();\n\n    kernel::assembleVolume krnl;\n    krnl.A = A00.data();\n    krnl.Dx_Q = Dx_Q;\n    krnl.K = material[elNo].get<K>().data();\n    krnl.matE_Q_T = matE_Q_T.data();\n    krnl.J_Q = vol[elNo].get<AbsDetJ>().data();\n    krnl.W = volRule.weights().data();\n    krnl.execute();\n    return true;\n}\n\nbool Poisson::assemble_skeleton(std::size_t fctNo, FacetInfo const& info, Matrix<double>& A00,\n                                Matrix<double>& A01, Matrix<double>& A10, Matrix<double>& A11,\n                                LinearAllocator<double>& scratch) const {\n    assert(fctRule.size() == tensor::w::Shape[0]);\n    assert(E_q[0].shape(0) == tensor::E_q::Shape[0][0]);\n    assert(E_q[0].shape(1) == tensor::E_q::Shape[0][1]);\n    assert(Dxi_q[0].shape(0) == tensor::Dxi_q::Shape[0][0]);\n    assert(Dxi_q[0].shape(1) == tensor::Dxi_q::Shape[0][1]);\n    assert(Dxi_q[0].shape(2) == tensor::Dxi_q::Shape[0][2]);\n\n    alignas(ALIGNMENT) double K_Dx_q0[tensor::K_Dx_q::size(0)];\n    alignas(ALIGNMENT) double K_Dx_q1[tensor::K_Dx_q::size(1)];\n    auto K_Dx_q = std::array<double*, 2>{K_Dx_q0, K_Dx_q1};\n    compute_K_Dx_q(fctNo, info, K_Dx_q);\n\n    alignas(ALIGNMENT) double L_q[2][std::max(tensor::L_q::size(0), tensor::L_q::size(1))];\n\n    if (method_ == DGMethod::BR2) {\n        alignas(ALIGNMENT) double Lift0[tensor::Lift::size(0)];\n        alignas(ALIGNMENT) double Lift1[tensor::Lift::size(1)];\n        alignas(ALIGNMENT) double Minv[2][tensor::M::size()];\n        for (int i = 0; i < 2; ++i) {\n            compute_inverse_mass_matrix(info.up[i], Minv[i]);\n        }\n\n        alignas(ALIGNMENT) double K_q0[tensor::K_q::size(0)];\n        alignas(ALIGNMENT) double K_q1[tensor::K_q::size(1)];\n        auto K_q = std::array<double*, 2>{K_q0, K_q1};\n        compute_K_q(fctNo, info, K_q);\n\n        kernel::lift_skeleton lift;\n        lift.Lift(0) = Lift0;\n        lift.Lift(1) = Lift1;\n        lift.n_q = fct[fctNo].get<Normal>().data()->data();\n        lift.w = fctRule.weights().data();\n        for (int i = 0; i < 2; ++i) {\n            lift.K_q(i) = K_q[i];\n            lift.L_q(i) = L_q[i];\n            lift.Minv(i) = Minv[i];\n            lift.E_q(i) = E_q[info.localNo[i]].data();\n        }\n        lift.execute(0);\n        lift.execute(1);\n    } else { // IP\n        kernel::lift_ip lift;\n        lift.nl_q = fct[fctNo].get<NormalLength>().data();\n        for (int i = 0; i < 2; ++i) {\n            lift.L_q(i) = L_q[i];\n            lift.E_q(i) = E_q[info.localNo[i]].data();\n        }\n        lift.execute(0);\n        lift.execute(1);\n    }\n\n    kernel::assembleSurface assemble;\n    assemble.c00 = -0.5;\n    assemble.c01 = -assemble.c00;\n    assemble.c10 = epsilon * 0.5;\n    assemble.c11 = -assemble.c10;\n    assemble.c20 = penalty(fctNo);\n    assemble.c21 = -assemble.c20;\n    assemble.a(0, 0) = A00.data();\n    assemble.a(0, 1) = A01.data();\n    assemble.a(1, 0) = A10.data();\n    assemble.a(1, 1) = A11.data();\n    for (int i = 0; i < 2; ++i) {\n        assemble.K_Dx_q(i) = K_Dx_q[i];\n        assemble.E_q(i) = E_q[info.localNo[i]].data();\n        assemble.L_q(i) = L_q[i];\n    }\n    assemble.n_q = fct[fctNo].get<Normal>().data()->data();\n    assemble.w = fctRule.weights().data();\n    assemble.execute(0, 0);\n    assemble.execute(0, 1);\n    assemble.execute(1, 0);\n    assemble.execute(1, 1);\n\n    return true;\n}\n\nbool Poisson::assemble_boundary(std::size_t fctNo, FacetInfo const& info, Matrix<double>& A00,\n                                LinearAllocator<double>& scratch) const {\n    if (info.bc == BC::Natural) {\n        return false;\n    }\n\n    assert(fctRule.size() == tensor::w::Shape[0]);\n    assert(E_q[0].shape(0) == tensor::E_q::Shape[0][0]);\n    assert(E_q[0].shape(1) == tensor::E_q::Shape[0][1]);\n    assert(Dxi_q[0].shape(0) == tensor::Dxi_q::Shape[0][0]);\n    assert(Dxi_q[0].shape(1) == tensor::Dxi_q::Shape[0][1]);\n    assert(Dxi_q[0].shape(2) == tensor::Dxi_q::Shape[0][2]);\n\n    alignas(ALIGNMENT) double L0[tensor::L_q::size(0)];\n    if (method_ == DGMethod::BR2) {\n        alignas(ALIGNMENT) double Lift0[tensor::Lift::size(0)];\n        alignas(ALIGNMENT) double Minv0[tensor::M::size()];\n        compute_inverse_mass_matrix(info.up[0], Minv0);\n\n        alignas(ALIGNMENT) double K_q[tensor::K_q::size(0)];\n        compute_K_q(fctNo, info, {K_q, nullptr});\n\n        kernel::lift_boundary lift;\n        lift.Lift(0) = Lift0;\n        lift.K_q(0) = K_q;\n        lift.L_q(0) = L0;\n        lift.Minv(0) = Minv0;\n        lift.E_q(0) = E_q[info.localNo[0]].data();\n        lift.n_q = fct[fctNo].get<Normal>().data()->data();\n        lift.w = fctRule.weights().data();\n        lift.execute();\n    } else { // IP\n        kernel::lift_ip lift;\n        lift.nl_q = fct[fctNo].get<NormalLength>().data();\n        lift.L_q(0) = L0;\n        lift.E_q(0) = E_q[info.localNo[0]].data();\n        lift.execute(0);\n    }\n\n    alignas(ALIGNMENT) double K_Dx_q0[tensor::K_Dx_q::size(0)];\n    compute_K_Dx_q(fctNo, info, {K_Dx_q0, nullptr});\n\n    kernel::assembleSurface assemble;\n    assemble.c00 = -1.0;\n    assemble.c10 = epsilon;\n    assemble.c20 = penalty(fctNo);\n    assemble.a(0, 0) = A00.data();\n    assemble.K_Dx_q(0) = K_Dx_q0;\n    assemble.E_q(0) = E_q[info.localNo[0]].data();\n    assemble.L_q(0) = L0;\n    assemble.n_q = fct[fctNo].get<Normal>().data()->data();\n    assemble.w = fctRule.weights().data();\n    assemble.execute(0, 0);\n    return true;\n}\n\nbool Poisson::rhs_volume(std::size_t elNo, Vector<double>& B,\n                         LinearAllocator<double>& scratch) const {\n    assert(tensor::b::Shape[0] == tensor::A::Shape[0]);\n\n    alignas(ALIGNMENT) double F_Q_raw[tensor::F_Q::size()];\n    assert(tensor::F_Q::size() == volRule.size());\n    auto F_Q = Matrix<double>(F_Q_raw, 1, tensor::F_Q::Shape[0]);\n    fun_force(elNo, F_Q);\n\n    kernel::rhsVolume rhs;\n    rhs.E_Q = E_Q.data();\n    rhs.F_Q = F_Q_raw;\n    rhs.J_Q = vol[elNo].get<AbsDetJ>().data();\n    rhs.W = volRule.weights().data();\n    rhs.b = B.data();\n    rhs.execute();\n    return true;\n}\n\nbool Poisson::bc_skeleton(std::size_t fctNo, BC bc, double f_q_raw[]) const {\n    assert(tensor::f_q::size() == fctRule.size());\n    auto f_q = Matrix<double>(f_q_raw, 1, tensor::f_q::Shape[0]);\n    if (bc == BC::Fault) {\n        fun_slip(fctNo, f_q, false);\n    } else if (bc == BC::Dirichlet) {\n        fun_dirichlet(fctNo, f_q, false);\n    } else {\n        return false;\n    }\n    return true;\n}\nbool Poisson::bc_boundary(std::size_t fctNo, BC bc, double f_q_raw[]) const {\n    assert(tensor::f_q::size() == fctRule.size());\n    auto f_q = Matrix<double>(f_q_raw, 1, tensor::f_q::Shape[0]);\n    if (bc == BC::Fault) {\n        fun_slip(fctNo, f_q, true);\n        for (std::size_t q = 0; q < tensor::f_q::Shape[0]; ++q) {\n            f_q(0, q) *= 0.5;\n        }\n    } else if (bc == BC::Dirichlet) {\n        fun_dirichlet(fctNo, f_q, true);\n    } else {\n        return false;\n    }\n    return true;\n}\n\nbool Poisson::rhs_skeleton(std::size_t fctNo, FacetInfo const& info, Vector<double>& B0,\n                           Vector<double>& B1, LinearAllocator<double>& scratch) const {\n    alignas(ALIGNMENT) double f_q_raw[tensor::f_q::size()];\n    if (!bc_skeleton(fctNo, info.bc, f_q_raw)) {\n        return false;\n    }\n\n    alignas(ALIGNMENT) double f_lifted_q[tensor::f_lifted_q::size()];\n    if (method_ == DGMethod::BR2) {\n        alignas(ALIGNMENT) double f_lifted0[tensor::f_lifted::size(0)];\n        alignas(ALIGNMENT) double f_lifted1[tensor::f_lifted::size(1)];\n        alignas(ALIGNMENT) double Minv[2][tensor::M::size()];\n        compute_inverse_mass_matrix(info.up[0], Minv[0]);\n        compute_inverse_mass_matrix(info.up[1], Minv[1]);\n\n        alignas(ALIGNMENT) double K_q0[tensor::K_q::size(0)];\n        alignas(ALIGNMENT) double K_q1[tensor::K_q::size(1)];\n        auto K_q = std::array<double*, 2>{K_q0, K_q1};\n        compute_K_q(fctNo, info, K_q);\n\n        kernel::rhs_lift_skeleton lift;\n        for (int i = 0; i < 2; ++i) {\n            lift.E_q(i) = E_q[info.localNo[i]].data();\n            lift.K_q(i) = K_q[i];\n            lift.Minv(i) = Minv[i];\n        }\n        lift.n_q = fct[fctNo].get<Normal>().data()->data();\n        lift.f_q = f_q_raw;\n        lift.f_lifted(0) = f_lifted0;\n        lift.f_lifted(1) = f_lifted1;\n        lift.f_lifted_q = f_lifted_q;\n        lift.w = fctRule.weights().data();\n        lift.execute();\n    } else { // IP\n        kernel::rhs_lift_ip lift;\n        lift.nl_q = fct[fctNo].get<NormalLength>().data();\n        lift.f_q = f_q_raw;\n        lift.f_lifted_q = f_lifted_q;\n        lift.execute();\n    }\n\n    alignas(ALIGNMENT) double K_Dx_q0[tensor::K_Dx_q::size(0)];\n    alignas(ALIGNMENT) double K_Dx_q1[tensor::K_Dx_q::size(1)];\n    compute_K_Dx_q(fctNo, info, {K_Dx_q0, K_Dx_q1});\n\n    kernel::rhsFacet rhs;\n    rhs.b = B0.data();\n    rhs.c10 = 0.5 * epsilon;\n    rhs.c20 = penalty(fctNo);\n    rhs.f_q = f_q_raw;\n    rhs.f_lifted_q = f_lifted_q;\n    rhs.n_q = fct[fctNo].get<Normal>().data()->data();\n    rhs.w = fctRule.weights().data();\n    rhs.K_Dx_q(0) = K_Dx_q0;\n    rhs.E_q(0) = E_q[info.localNo[0]].data();\n    rhs.execute();\n\n    rhs.b = B1.data();\n    rhs.c20 *= -1.0;\n    rhs.K_Dx_q(0) = K_Dx_q1;\n    rhs.E_q(0) = E_q[info.localNo[1]].data();\n    rhs.execute();\n\n    return true;\n}\n\nbool Poisson::rhs_boundary(std::size_t fctNo, FacetInfo const& info, Vector<double>& B0,\n                           LinearAllocator<double>& scratch) const {\n    alignas(ALIGNMENT) double f_q_raw[tensor::f_q::size()];\n    if (!bc_boundary(fctNo, info.bc, f_q_raw)) {\n        return false;\n    }\n\n    alignas(ALIGNMENT) double f_lifted_q[tensor::f_lifted_q::size()];\n    if (method_ == DGMethod::BR2) {\n        alignas(ALIGNMENT) double f_lifted0[tensor::f_lifted::size(0)];\n        alignas(ALIGNMENT) double M0[tensor::M::size()];\n        compute_inverse_mass_matrix(info.up[0], M0);\n\n        alignas(ALIGNMENT) double K_q[tensor::K_q::size(0)];\n        compute_K_q(fctNo, info, {K_q, nullptr});\n\n        kernel::rhs_lift_boundary lift;\n        lift.E_q(0) = E_q[info.localNo[0]].data();\n        lift.n_q = fct[fctNo].get<Normal>().data()->data();\n        lift.K_q(0) = K_q;\n        lift.Minv(0) = M0;\n        lift.f_q = f_q_raw;\n        lift.f_lifted(0) = f_lifted0;\n        lift.f_lifted_q = f_lifted_q;\n        lift.w = fctRule.weights().data();\n        lift.execute();\n    } else { // IP\n        kernel::rhs_lift_ip lift;\n        lift.nl_q = fct[fctNo].get<NormalLength>().data();\n        lift.f_q = f_q_raw;\n        lift.f_lifted_q = f_lifted_q;\n        lift.execute();\n    }\n\n    alignas(ALIGNMENT) double K_Dx_q0[tensor::K_Dx_q::size(0)];\n    compute_K_Dx_q(fctNo, info, {K_Dx_q0, nullptr});\n\n    kernel::rhsFacet rhs;\n    rhs.b = B0.data();\n    rhs.c10 = epsilon;\n    rhs.c20 = penalty(fctNo);\n    rhs.f_q = f_q_raw;\n    rhs.f_lifted_q = f_lifted_q;\n    rhs.n_q = fct[fctNo].get<Normal>().data()->data();\n    rhs.w = fctRule.weights().data();\n    rhs.K_Dx_q(0) = K_Dx_q0;\n    rhs.E_q(0) = E_q[info.localNo[0]].data();\n    rhs.execute();\n    return true;\n}\n\nvoid Poisson::apply(std::size_t elNo, mneme::span<SideInfo> info, Vector<double const> const& x_0,\n                    std::array<Vector<double const>, NumFacets> const& x_n,\n                    Vector<double>& y_0) const {\n\n    alignas(ALIGNMENT) double Dx_Q[tensor::Dx_Q::size()];\n    kernel::apply_volume av;\n    av.Dx_Q = Dx_Q;\n    av.Dxi_Q = Dxi_Q.data();\n    av.G_Q = vol[elNo].get<JInv>().data()->data();\n    av.J_W_K_Q = volPre[elNo].get<AbsDetJWK>().data()->data();\n    av.U = x_0.data();\n    av.U_new = y_0.data();\n    av.execute();\n\n    alignas(ALIGNMENT) double n_q_flipped[tensor::n_q::size()];\n    alignas(ALIGNMENT) double n_unit_q_flipped[tensor::n_unit_q::size()];\n    for (std::size_t f = 0; f < NumFacets; ++f) {\n        bool is_skeleton_face = elNo != info[f].lid;\n        bool is_fault_or_dirichlet = info[f].bc == BC::Fault || info[f].bc == BC::Dirichlet;\n\n        auto fctNo = info[f].fctNo;\n        double const* n_q = fct[fctNo].get<Normal>().data()->data();\n        double const* n_unit_q = fct[fctNo].get<UnitNormal>().data()->data();\n        double const* K_G_q0 = fctPre[fctNo].get<KJInv0>().data()->data();\n        double const* K_G_q1 = fctPre[fctNo].get<KJInv1>().data()->data();\n        if (is_skeleton_face && info[f].side == 1) {\n            std::swap(K_G_q0, K_G_q1);\n\n            for (int i = 0; i < tensor::n_q::size(); ++i) {\n                n_q_flipped[i] = -n_q[i];\n            }\n            n_q = n_q_flipped;\n            for (int i = 0; i < tensor::n_unit_q::size(); ++i) {\n                n_unit_q_flipped[i] = -n_unit_q[i];\n            }\n            n_unit_q = n_unit_q_flipped;\n        }\n\n        alignas(ALIGNMENT) double u_hat_q[tensor::u_hat_q::size()] = {};\n        alignas(ALIGNMENT) double sigma_hat_q[tensor::sigma_hat_q::size()] = {};\n        if (info[f].bc == BC::None || (is_skeleton_face && is_fault_or_dirichlet)) {\n            kernel::flux_u_skeleton fu;\n            fu.negative_E_q_T(0) = negative_E_q_T[f].data();\n            fu.E_q_T(1) = E_q_T[info[f].localNo].data();\n            fu.U = x_0.data();\n            fu.U_ext = x_n[f].data();\n            fu.u_hat_q = u_hat_q;\n            fu.execute();\n\n            kernel::flux_sigma_skeleton fs;\n            fs.c00 = -penalty(fctNo);\n            fs.Dxi_q_120(0) = Dxi_q_120[f].data();\n            fs.Dxi_q_120(1) = Dxi_q_120[info[f].localNo].data();\n            fs.E_q_T(0) = E_q_T[f].data();\n            fs.negative_E_q_T(1) = negative_E_q_T[info[f].localNo].data();\n            fs.K_G_q(0) = K_G_q0;\n            fs.K_G_q(1) = K_G_q1;\n            fs.U = x_0.data();\n            fs.U_ext = x_n[f].data();\n            fs.n_unit_q = n_unit_q;\n            fs.sigma_hat_q = sigma_hat_q;\n            fs.execute();\n        } else if (is_fault_or_dirichlet) {\n            kernel::flux_u_boundary fu;\n            fu.U = x_0.data();\n            fu.u_hat_q = u_hat_q;\n            fu.negative_E_q_T(0) = negative_E_q_T[f].data();\n            fu.execute();\n\n            kernel::flux_sigma_boundary fs;\n            fs.c00 = -penalty(fctNo);\n            fs.Dxi_q_120(0) = Dxi_q_120[f].data();\n            fs.E_q_T(0) = E_q_T[f].data();\n            fs.K_G_q(0) = K_G_q0;\n            fs.U = x_0.data();\n            fs.n_unit_q = n_unit_q;\n            fs.sigma_hat_q = sigma_hat_q;\n            fs.execute();\n        } else {\n            continue;\n        }\n\n        kernel::apply_facet af;\n        af.Dxi_q(0) = Dxi_q[f].data();\n        af.E_q(0) = E_q[f].data();\n        af.K_G_q(0) = K_G_q0;\n        af.n_q = n_q;\n        af.sigma_hat_q = sigma_hat_q;\n        af.u_hat_q = u_hat_q;\n        af.U_new = y_0.data();\n        af.w = fctRule.weights().data();\n        af.execute();\n    }\n}\n\nstd::size_t Poisson::flops_apply(std::size_t elNo, mneme::span<SideInfo> info) const {\n    std::size_t flops = kernel::apply_volume::HardwareFlops;\n    for (std::size_t f = 0; f < NumFacets; ++f) {\n        bool is_skeleton_face = elNo != info[f].lid;\n        bool is_fault_or_dirichlet = info[f].bc == BC::Fault || info[f].bc == BC::Dirichlet;\n        if (info[f].bc == BC::None || (is_skeleton_face && is_fault_or_dirichlet)) {\n            flops += kernel::flux_u_skeleton::HardwareFlops;\n            flops += kernel::flux_sigma_skeleton::HardwareFlops;\n        } else if (is_fault_or_dirichlet) {\n            flops += kernel::flux_u_boundary::HardwareFlops;\n            flops += kernel::flux_sigma_boundary::HardwareFlops;\n        } else {\n            continue;\n        }\n        flops += kernel::apply_facet::HardwareFlops;\n    }\n    return flops;\n}\n\nvoid Poisson::coefficients_volume(std::size_t elNo, Matrix<double>& C,\n                                  LinearAllocator<double>&) const {\n    auto const coeff_K = material[elNo].get<K>();\n    assert(coeff_K.size() == C.shape(0));\n    for (std::size_t i = 0; i < coeff_K.size(); ++i) {\n        C(i, 0) = coeff_K[i];\n    }\n}\n\nTensorBase<Matrix<double>> Poisson::tractionResultInfo() const {\n    return TensorBase<Matrix<double>>(tensor::grad_u::Shape[0], tensor::grad_u::Shape[1]);\n}\n\nvoid Poisson::traction_skeleton(std::size_t fctNo, FacetInfo const& info, Vector<double const>& u0,\n                                Vector<double const>& u1, Matrix<double>& result) const {\n    assert(result.size() == tensor::grad_u::size());\n\n    alignas(ALIGNMENT) double f_q_raw[tensor::f_q::size()];\n    bc_skeleton(fctNo, info.bc, f_q_raw);\n\n    alignas(ALIGNMENT) double K_Dx_q0[tensor::K_Dx_q::size(0)];\n    alignas(ALIGNMENT) double K_Dx_q1[tensor::K_Dx_q::size(1)];\n    compute_K_Dx_q(fctNo, info, {K_Dx_q0, K_Dx_q1});\n\n    kernel::grad_u krnl;\n    krnl.c00 = -penalty(fctNo);\n    krnl.K_Dx_q(0) = K_Dx_q0;\n    krnl.K_Dx_q(1) = K_Dx_q1;\n    krnl.E_q(0) = E_q[info.localNo[0]].data();\n    krnl.E_q(1) = E_q[info.localNo[1]].data();\n    krnl.f_q = f_q_raw;\n    krnl.grad_u = result.data();\n    krnl.n_unit_q = fct[fctNo].get<UnitNormal>().data()->data();\n    krnl.u(0) = u0.data();\n    krnl.u(1) = u1.data();\n    krnl.execute();\n}\n\nvoid Poisson::traction_boundary(std::size_t fctNo, FacetInfo const& info, Vector<double const>& u0,\n                                Matrix<double>& result) const {\n    assert(result.size() == tensor::grad_u::size());\n\n    alignas(ALIGNMENT) double f_q_raw[tensor::f_q::size()];\n    bc_boundary(fctNo, info.bc, f_q_raw);\n\n    alignas(ALIGNMENT) double K_Dx_q0[tensor::K_Dx_q::size(0)];\n    compute_K_Dx_q(fctNo, info, {K_Dx_q0, nullptr});\n\n    kernel::grad_u_bnd krnl;\n    krnl.c00 = -penalty(fctNo);\n    krnl.K_Dx_q(0) = K_Dx_q0;\n    krnl.E_q(0) = E_q[info.localNo[0]].data();\n    krnl.f_q = f_q_raw;\n    krnl.grad_u = result.data();\n    krnl.n_unit_q = fct[fctNo].get<UnitNormal>().data()->data();\n    krnl.u(0) = u0.data();\n    krnl.execute();\n}\n\n} // namespace tndm\n", "meta": {"hexsha": "dd0d69fd44ae3adc393257d24aaa31c1f0b16884", "size": 26667, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/localoperator/Poisson.cpp", "max_stars_repo_name": "NicoSchlw/tandem", "max_stars_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T17:11:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:51:01.000Z", "max_issues_repo_path": "app/localoperator/Poisson.cpp", "max_issues_repo_name": "NicoSchlw/tandem", "max_issues_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-05-18T14:51:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T12:56:31.000Z", "max_forks_repo_path": "app/localoperator/Poisson.cpp", "max_forks_repo_name": "NicoSchlw/tandem", "max_forks_repo_head_hexsha": "3a08b5a7ae391c1675c5cbfdad77260d4a0115cc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-23T08:04:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T12:23:59.000Z", "avg_line_length": 36.7820689655, "max_line_length": 99, "alphanum_fraction": 0.5899051262, "num_tokens": 8317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7025300573952054, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.23997196351796066}}
{"text": "/**\n * Copyright (c) 2011, 2012\n * Claudio Kopper <claudio.kopper@icecube.wisc.edu>\n * and the IceCube Collaboration <http://www.icecube.wisc.edu>\n *\n * Permission to use, copy, modify, and/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\n * $Id: I3CLSimModuleHelper.cxx 178168 2019-12-19 21:40:33Z jvansanten $\n *\n * @file I3CLSimModuleHelper.cxx\n * @version $Revision: 178168 $\n * @date $Date: 2019-12-19 14:40:33 -0700 (Thu, 19 Dec 2019) $\n * @author Claudio Kopper\n */\n\n#ifndef __STDC_FORMAT_MACROS\n#define __STDC_FORMAT_MACROS\n#endif\n#include <inttypes.h>\n\n#include \"clsim/I3CLSimModuleHelper.h\"\n\n#include \"clsim/function/I3CLSimFunctionConstant.h\"\n#include \"clsim/function/I3CLSimFunctionFromTable.h\"\n#include \"clsim/function/I3CLSimFunctionDeltaPeak.h\"\n#include \"clsim/random_value/I3CLSimRandomValueInterpolatedDistribution.h\"\n#include \"clsim/random_value/I3CLSimRandomValueWlenCherenkovNoDispersion.h\"\n#include \"clsim/random_value/I3CLSimRandomValueConstant.h\"\n\n#include <boost/foreach.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/variant/get.hpp>\n\n#include \"dataclasses/physics/I3MCTree.h\"\n#include \"dataclasses/physics/I3MCTreeUtils.h\"\n\n\nnamespace I3CLSimModuleHelper {\n    \n    namespace {\n        double CherenkovYieldDistribution(double wlen, I3CLSimMediumPropertiesConstPtr mediumProperties, double beta=1.)\n        {\n            I3CLSimFunctionConstPtr nPhaseDist =\n            mediumProperties->GetPhaseRefractiveIndex(0); // this assumes the refractive index does not change between layers\n            \n            if (!nPhaseDist->HasNativeImplementation()) \n                log_fatal(\"The refractive index distribution needs a native implementation to be usable!\");\n            \n            const double nPhase = nPhaseDist->GetValue(wlen);\n            \n            return (2.*M_PI/(137.*(wlen*wlen)))*(1. - 1./ ( std::pow(beta*nPhase,2.) ) ); // dN/dxdwlen\n        }\n\n        // the normalization will not be correct here\n        double CherenkovYieldDistributionNoDispersion(double wlen)\n        {\n            return 1./(wlen*wlen); // dN/dxdwlen\n        }\n\n    };\n    \n    \n    I3CLSimRandomValueConstPtr\n    makeWavelengthGenerator(I3CLSimFunctionConstPtr unbiasedSpectrum,\n                            I3CLSimFunctionConstPtr wavelengthGenerationBias,\n                            I3CLSimMediumPropertiesConstPtr mediumProperties)\n    {\n        {\n            // special handling for delta peaks\n            I3CLSimFunctionDeltaPeakConstPtr deltaPeak =\n            boost::dynamic_pointer_cast<const I3CLSimFunctionDeltaPeak>(unbiasedSpectrum);\n            if (deltaPeak) {\n                const double peakPosition = deltaPeak->GetPeakPosition();\n                \n                return I3CLSimRandomValueConstantConstPtr\n                (new I3CLSimRandomValueConstant(peakPosition));\n            }\n        }\n\n        // if we get here, it's not a delta peak\n        \n        double minWlen = unbiasedSpectrum->GetMinWlen();\n        double maxWlen = unbiasedSpectrum->GetMaxWlen();\n        \n        // check if the spectrum is from a tabulated distribution (instead of\n        // a parameterized one)\n        I3CLSimFunctionFromTableConstPtr unbiasedSpectrumFromTable;\n        unbiasedSpectrumFromTable =\n        boost::dynamic_pointer_cast<const I3CLSimFunctionFromTable>(unbiasedSpectrum);\n\n        if (!unbiasedSpectrumFromTable) {\n            // do not clip wavelengths if they are from a tabulated distribution. In that case,\n            // re-use the entire table binning\n            if (mediumProperties->GetMinWavelength() > minWlen) minWlen=mediumProperties->GetMinWavelength();\n            if (mediumProperties->GetMaxWavelength() < maxWlen) maxWlen=mediumProperties->GetMaxWavelength();\n        }\n        \n        const double wlenRange = maxWlen-minWlen;\n        if (wlenRange <= 0.) log_fatal(\"Internal error, wavelength range <= 0!\");\n\n        if (wavelengthGenerationBias->GetMinWlen() > minWlen)\n            log_fatal(\"wavelength generation bias has to have a wavelength range larger or equal to the spectrum wavelength range!\");\n        if (wavelengthGenerationBias->GetMaxWlen() < maxWlen)\n            log_fatal(\"wavelength generation bias has to have a wavelength range larger or equal to the spectrum wavelength range!\");\n\n        // Check if the spectrum values are from a tabulated distribution.\n        // If yes, use the table binning, if not make up a binning.\n        if (unbiasedSpectrumFromTable)\n        {\n            std::size_t wlenPoints = unbiasedSpectrumFromTable->GetNumEntries();\n            const double firstWlen = unbiasedSpectrumFromTable->GetFirstWavelength();\n            \n            std::vector<double> spectrum(wlenPoints, NAN);\n            std::vector<double> wavelengths(wlenPoints, NAN);\n            for (std::size_t i=0;i<wlenPoints;++i)\n            {\n                const double wavelength = unbiasedSpectrumFromTable->GetEntryWavelength(i);\n                const double entry = unbiasedSpectrumFromTable->GetEntryValue(i);\n                const double bias = wavelengthGenerationBias->GetValue(wavelength);\n                \n                spectrum[i] = bias * entry;\n                wavelengths[i] = wavelength;\n            }\n            \n            if (unbiasedSpectrumFromTable->GetInEqualSpacingMode()) {\n                const double wlenStep = unbiasedSpectrumFromTable->GetWavelengthStepping();\n\n                return I3CLSimRandomValueInterpolatedDistributionConstPtr\n                (new I3CLSimRandomValueInterpolatedDistribution(firstWlen,\n                                                                wlenStep,\n                                                                spectrum));\n            } else {\n                // slightly less efficient if non-equally spaced\n                return I3CLSimRandomValueInterpolatedDistributionConstPtr\n                (new I3CLSimRandomValueInterpolatedDistribution(wavelengths,\n                                                                spectrum));\n            }\n        }\n        else\n        {\n            // use a pre-defined binning of 10ns (an arbitrary value..)\n            \n            std::size_t wlenPoints = static_cast<std::size_t>(wlenRange/(10.*I3Units::nanometer))+2;\n            const double firstWlen = minWlen;\n            const double wlenStep = wlenRange/static_cast<double>(wlenPoints-1);\n            \n            std::vector<double> spectrum(wlenPoints, NAN);\n            for (std::size_t i=0;i<wlenPoints;++i)\n            {\n                const double wavelength = firstWlen + static_cast<double>(i)*wlenStep;\n                const double entry = unbiasedSpectrum->GetValue(wavelength);\n                const double bias = wavelengthGenerationBias->GetValue(wavelength);\n                \n                spectrum[i] = bias * entry;\n            }\n            \n            return I3CLSimRandomValueInterpolatedDistributionConstPtr\n            (new I3CLSimRandomValueInterpolatedDistribution(firstWlen,\n                                                            wlenStep,\n                                                            spectrum));\n        }\n    }\n    \n    I3CLSimRandomValueConstPtr\n    makeCherenkovWavelengthGenerator(I3CLSimFunctionConstPtr wavelengthGenerationBias,\n                                     bool generateCherenkovPhotonsWithoutDispersion,\n                                     I3CLSimMediumPropertiesConstPtr mediumProperties)\n    {\n        const double minWlen = mediumProperties->GetMinWavelength();\n        const double maxWlen = mediumProperties->GetMaxWavelength();\n        const double wlenRange = maxWlen-minWlen;\n        if (wlenRange <= 0.) log_fatal(\"Internal error, wavelength range <= 0!\");\n\n        if (wavelengthGenerationBias->GetMinWlen() > minWlen)\n            log_fatal(\"wavelength generation bias has to have a wavelength range larger or equal to the medium property range!\");\n        if (wavelengthGenerationBias->GetMaxWlen() < maxWlen)\n            log_fatal(\"wavelength generation bias has to have a wavelength range larger or equal to the medium property range!\");\n        \n        bool noBias=false;\n        //bool biasIsConstant=false;\n        \n        {\n            I3CLSimFunctionConstantConstPtr wavelengthGenerationBiasConstant =\n            boost::dynamic_pointer_cast<const I3CLSimFunctionConstant>(wavelengthGenerationBias);\n            \n            if (wavelengthGenerationBiasConstant)\n            {\n                //biasIsConstant=true;\n                \n                if ( std::abs(wavelengthGenerationBiasConstant->GetValue((minWlen+maxWlen)/2.)-1.) < 1e-10 )\n                    noBias=true;\n            }\n        }\n        \n        I3CLSimFunctionFromTableConstPtr wavelengthGenerationBiasFromTable;\n        wavelengthGenerationBiasFromTable =\n        boost::dynamic_pointer_cast<const I3CLSimFunctionFromTable>(wavelengthGenerationBias);\n        \n        \n\n        if ((!noBias) && (generateCherenkovPhotonsWithoutDispersion))\n        {\n            log_warn(\"**********\");\n            log_warn(\" Using the \\\"GenerateCherenkovPhotonsWithoutDispersion\\\" option\");\n            log_warn(\" with a biased photon spectrum generation does not yield a performance\");\n            log_warn(\" increase. You might consider turning this option off to get a better\");\n            log_warn(\" approximation of the Cherenkov spectrum.\");\n            log_warn(\"**********\");\n        }\n        \n        // Check if the bias values are from a tabulated distribution.\n        // If yes, use the table binning, if not make up a binning.\n        if (wavelengthGenerationBiasFromTable)\n        {\n            std::size_t wlenPoints = wavelengthGenerationBiasFromTable->GetNumEntries();\n            const double firstWlen = wavelengthGenerationBiasFromTable->GetFirstWavelength();\n            \n            std::vector<double> spectrum(wlenPoints, NAN);\n            std::vector<double> wavelengths(wlenPoints, NAN);\n            for (std::size_t i=0;i<wlenPoints;++i)\n            {\n                const double wavelength = wavelengthGenerationBiasFromTable->GetEntryWavelength(i);\n                const double bias = wavelengthGenerationBiasFromTable->GetEntryValue(i);\n                \n                if (generateCherenkovPhotonsWithoutDispersion)\n                {\n                    spectrum[i] =\n                    bias * CherenkovYieldDistributionNoDispersion(wavelength);\n                }\n                else\n                {\n                    spectrum[i] =\n                    bias * CherenkovYieldDistribution(wavelength, mediumProperties);\n                }\n                \n                wavelengths[i] = wavelength;\n            }\n            \n            if (wavelengthGenerationBiasFromTable->GetInEqualSpacingMode()) {\n                const double wlenStep = wavelengthGenerationBiasFromTable->GetWavelengthStepping();\n\n                return I3CLSimRandomValueInterpolatedDistributionConstPtr\n                (new I3CLSimRandomValueInterpolatedDistribution(firstWlen,\n                                                                wlenStep,\n                                                                spectrum));\n            } else {\n                // slightly less efficient if non-equally spaced\n                return I3CLSimRandomValueInterpolatedDistributionConstPtr\n                (new I3CLSimRandomValueInterpolatedDistribution(wavelengths,\n                                                                spectrum));\n            }\n        }\n        else if ((noBias) && (generateCherenkovPhotonsWithoutDispersion))\n        {\n            return I3CLSimRandomValueWlenCherenkovNoDispersionConstPtr\n            (new I3CLSimRandomValueWlenCherenkovNoDispersion(minWlen, maxWlen));\n        }\n        else\n        {\n            std::size_t wlenPoints = static_cast<std::size_t>(wlenRange/(10.*I3Units::nanometer))+2;\n            const double firstWlen = minWlen;\n            const double wlenStep = wlenRange/static_cast<double>(wlenPoints-1);\n            \n            std::vector<double> spectrum(wlenPoints, NAN);\n            for (std::size_t i=0;i<wlenPoints;++i)\n            {\n                const double wavelength = firstWlen + static_cast<double>(i)*wlenStep;\n                const double bias = wavelengthGenerationBias->GetValue(wavelength);\n                \n                if (generateCherenkovPhotonsWithoutDispersion)\n                {\n                    spectrum[i] =\n                    bias * CherenkovYieldDistributionNoDispersion(wavelength);\n                }\n                else\n                {\n                    spectrum[i] =\n                    bias * CherenkovYieldDistribution(wavelength, mediumProperties);\n                }\n            }\n\n            return I3CLSimRandomValueInterpolatedDistributionConstPtr\n            (new I3CLSimRandomValueInterpolatedDistribution(firstWlen,\n                                                            wlenStep,\n                                                            spectrum));\n        }\n\n    \n    }\n\n    \n    I3CLSimStepToPhotonConverterOpenCLPtr initializeOpenCL(const I3CLSimOpenCLDevice &device,\n                                                           I3RandomServicePtr rng,\n                                                           I3CLSimSimpleGeometryConstPtr geometry,\n                                                           I3CLSimMediumPropertiesConstPtr medium,\n                                                           I3CLSimFunctionConstPtr wavelengthGenerationBias,\n                                                           const std::vector<I3CLSimRandomValueConstPtr> &wavelengthGenerators,\n                                                           bool enableDoubleBuffering,\n                                                           bool doublePrecision,\n                                                           bool stopDetectedPhotons,\n                                                           bool saveAllPhotons,\n                                                           double saveAllPhotonsPrescale,\n                                                           double fixedNumberOfAbsorptionLengths,\n                                                           double pancakeFactor,\n                                                           uint32_t photonHistoryEntries,\n                                                           uint32_t limitWorkgroupSize)\n    {\n        I3CLSimStepToPhotonConverterOpenCLPtr conv(new I3CLSimStepToPhotonConverterOpenCL(rng, device.GetUseNativeMath()));\n\n        conv->SetDevice(device);\n\n        conv->SetWlenGenerators(wavelengthGenerators);\n        conv->SetWlenBias(wavelengthGenerationBias);\n\n        conv->SetMediumProperties(medium);\n        conv->SetGeometry(geometry);\n\n        conv->SetEnableDoubleBuffering(enableDoubleBuffering);\n        conv->SetDoublePrecision(doublePrecision);\n        conv->SetStopDetectedPhotons(stopDetectedPhotons);\n        conv->SetSaveAllPhotons(saveAllPhotons);\n        conv->SetSaveAllPhotonsPrescale(saveAllPhotonsPrescale);\n\n        conv->SetFixedNumberOfAbsorptionLengths(fixedNumberOfAbsorptionLengths);\n        conv->SetDOMPancakeFactor(pancakeFactor);\n\n        conv->SetPhotonHistoryEntries(photonHistoryEntries);\n\n        conv->Compile();\n        //log_trace(\"%s\", conv.GetFullSource().c_str());\n        \n        std::size_t maxWorkgroupSize = conv->GetMaxWorkgroupSize();\n        if (limitWorkgroupSize!=0) {\n            maxWorkgroupSize = std::min(static_cast<std::size_t>(limitWorkgroupSize), maxWorkgroupSize);\n        }\n        \n        conv->SetWorkgroupSize(maxWorkgroupSize);\n        const std::size_t workgroupSize = conv->GetWorkgroupSize();\n        \n        // use approximately the given number of work items, convert to a multiple of the workgroup size\n        std::size_t maxNumWorkitems = (static_cast<std::size_t>(device.GetApproximateNumberOfWorkItems())/workgroupSize)*workgroupSize;\n        if (maxNumWorkitems==0) maxNumWorkitems=workgroupSize;\n        \n        conv->SetMaxNumWorkitems(maxNumWorkitems);\n\n        log_info(\"Using OpenCL device: platform=%s device=%s isgpu=%d\",                  \n                  device.GetPlatformName().c_str(),\n                  device.GetDeviceName().c_str(),\n                  device.IsGPU());\n        log_info(\"maximum workgroup size is %zu\", maxWorkgroupSize);\n        log_info(\"configured workgroup size is %zu\", workgroupSize);\n        if (maxNumWorkitems != device.GetApproximateNumberOfWorkItems()) {\n            log_info(\"maximum number of work items is %zu (user configured was %\" PRIu32 \")\", maxNumWorkitems, device.GetApproximateNumberOfWorkItems());\n        } else {\n            log_debug(\"maximum number of work items is %zu (user configured was %\" PRIu32 \")\", maxNumWorkitems, device.GetApproximateNumberOfWorkItems());\n        }\n\n        conv->Initialize();\n        \n        return conv;\n    }\n\n}\n", "meta": {"hexsha": "ce5e3825f5f70b096c4d39843a451b45ed6c5690", "size": 17564, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "clsim/private/clsim/I3CLSimModuleHelper.cxx", "max_stars_repo_name": "hschwane/offline_production", "max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z", "max_issues_repo_path": "clsim/private/clsim/I3CLSimModuleHelper.cxx", "max_issues_repo_name": "hschwane/offline_production", "max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "clsim/private/clsim/I3CLSimModuleHelper.cxx", "max_forks_repo_name": "hschwane/offline_production", "max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z", "avg_line_length": 46.8373333333, "max_line_length": 154, "alphanum_fraction": 0.5963903439, "num_tokens": 3593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602049, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.23996229266874805}}
{"text": "// File: finetune_classifier.cc\n// Author: Karl Moritz Hermann (mail@karlmoritz.com)\n// Created: 29-01-2013\n// Last Update: Thu 03 Oct 2013 11:26:25 AM BST\n\n// STL\n#include <iostream>\n#include <algorithm>\n#include <random>\n#include <chrono>\n\n// Boost\n#include <boost/program_options/variables_map.hpp>\n#include <boost/program_options/parsers.hpp>\n\n// L-BFGS\n#include <lbfgs.h>\n\n// Local\n#include \"finetune_classifier.h\"\n#include \"models.h\"\n#include \"fast_math.h\"\n\nusing namespace std;\nnamespace bpo = boost::program_options;\n\nFinetuneClassifier::FinetuneClassifier(RecursiveAutoencoderBase& rae,\n    TrainingCorpus& trainC, float lambdaF, float alpha,\n    int dynamic_mode, int iterations) : lambda(lambdaF), alpha_rae(alpha),\n  mode(dynamic_mode), iterations(iterations), it_count(0), num_batches(100),\n  eta(0.1) {\n\n  /***************************************************************************\n   *             Define a couple of frequently needed variables              *\n   ***************************************************************************/\n\n  train_length = min(rae.config.num_sentences,int(trainC.size()));\n  bool use_full_corpus = false;\n  if (train_length == 0)\n  {\n    train_length = trainC.size();\n    use_full_corpus = true;\n  }\n\n  label_width = rae.config.label_class_size;\n  num_label_types = rae.config.num_label_types; // 1\n\n  int multiplier = 1;\n  if (mode == 0)\n    multiplier = 2;\n  if (mode == 3)\n    multiplier = 3; // only works for compound test\n  if (mode == 4)\n    multiplier = 4;\n  // Embedding: s1 + s2 + cos_sim(s1,s2) + len(s1) + len(s2) +\n  // unigram_overlap(s1,s2) following Blacoe/Lapata 2012\n  dynamic_embedding_size = multiplier * rae.config.word_representation_size;\n\n  theta_size_ = dynamic_embedding_size * label_width * num_label_types + label_width * num_label_types;\n\n  trainI_ = new Real[train_length * dynamic_embedding_size]();\n  theta_  = new Real[theta_size_];\n  WeightVectorType theta(theta_,theta_size_);\n  theta.setZero();\n  if (true) {\n    std::random_device rd;\n    std::mt19937 gen(rd());\n    //std::mt19937 gen(0);\n    float r = sqrt( 6.0 / dynamic_embedding_size);\n    std::uniform_real_distribution<> dis(-r,r);\n    for (int i=0; i<theta_size_; i++)\n      theta(i) = dis(gen);\n  }\n\n  Real* ptr = trainI_;\n  for (auto i=0; i<train_length; ++i) {\n    int j = i;\n    if ((not use_full_corpus) and (i%2 == 1))\n      j = trainC.size() - i;\n    trainData.push_back(VectorLabelPair(WeightVectorType(ptr, dynamic_embedding_size),trainC[j].value));\n    mix.push_back(i);\n    ptr += dynamic_embedding_size;\n  }\n\n  ptr = theta_;\n  for (auto i=0; i<num_label_types; ++i) {\n    Wcat.push_back(WeightMatrixType(ptr, label_width, dynamic_embedding_size));\n    ptr += label_width * dynamic_embedding_size;\n  }\n  for (auto i=0; i<num_label_types; ++i) {\n    Bcat.push_back(WeightVectorType(ptr, label_width));\n    Bcat.back().setZero(); // discuss ..\n    ptr += label_width;\n  }\n\n  /***************************************************************************\n   *        Populate train input with forward Propagation and tricks         *\n   ***************************************************************************/\n\n#pragma omp parallel for schedule(dynamic)\n  for (auto i = 0; i<train_length; ++i)\n  {\n    int j = i;\n    if ((not use_full_corpus) and (i%2 == 1))\n      j = trainC.size() - i;\n\n    SinglePropBase* propagator = nullptr;\n\n    Bools bools;\n    if(rae.config.tree == TREE_CCG or rae.config.tree == TREE_STANFORD)\n      propagator = rae.getSingleProp(trainC[j],0.5,bools);\n    assert (propagator != nullptr);\n\n    propagator->forwardPropagate(true);\n    propagator->setDynamic(trainData[i].vector,mode);\n    //cout << \"C: \" << trainData[i].vector[0] << endl;\n\n    delete propagator;\n  }\n}\n\nvoid FinetuneClassifier::evaluate()\n{\n\n  vector<VectorLabelPair>& data = trainData;\n  int length = train_length;\n\n  int right = 0;\n  int wrong = 0;\n  int tp = 0;\n  int fp = 0;\n  int tn = 0;\n  int fn = 0;\n\n#pragma omp parallel for schedule(dynamic)\n  for (auto i = 0; i<length; ++i)\n  {\n\n    // Encode input\n    ArrayReal label_vec = (\n        Wcat[0] * data[i].vector + Bcat[0]\n        ).unaryExpr(std::ptr_fun(getSigmoid)).array();\n\n    ArrayReal lbl_sm = data[i].label - label_vec;\n\n#pragma omp critical\n    {\n      if(abs(lbl_sm.sum()) > 0.5)\n      {\n        wrong += 1;\n        if(data[i].label == 0)  ++fp;\n        else                    ++fn;\n      }\n      else\n      {\n        right += 1;\n        if(data[i].label == 0)  ++tn;\n        else                    ++tp;\n      }\n    }\n  }\n    cout << right << \"/\" << right + wrong << \"  \";\n    Real precision = 1.0 * tp / (tp + fp);\n    Real recall    = 1.0 * tp / (tp + fn);\n    Real accuracy  = 1.0 * (tp + tn) / (tp + tn + fp + fn);\n    Real f1score   = 2.0 * (precision * recall) / (precision + recall);\n    cout << \"Acc/F1: \" << accuracy << \" \" << f1score << endl;\n}\n\nvoid FinetuneClassifier::trainLbfgs(LineSearchType linesearch)\n{\n  batch_from = 0;\n  batch_to = train_length;\n\n  lbfgs_parameter_t param;\n  lbfgs_parameter_init(&param);\n  param.linesearch = linesearch;\n  param.max_iterations = iterations;\n  //param.epsilon = 0.00000001;\n  param.m = 25;\n\n  const int n = theta_size_;\n  auto vars = theta_;\n  Real error = 0.0;\n\n  int tries = 0;\n\n  while (tries < 3 and it_count < 250)\n  {\n    int ret = lbfgs(n, vars, &error, lbfgs_evaluate_, lbfgs_progress_, this, &param);\n    cout << \"L-BFGS optimization terminated with status code = \" << ret << endl;\n    cout << \"fx=\" << error << endl;\n    ++tries;\n  }\n}\n\nvoid FinetuneClassifier::trainAdaGrad()\n{\n  auto vars = theta_;\n  int number_vars = theta_size_;\n\n  WeightArrayType theta(vars,number_vars);\n\n  Real* Gt_d = new Real[number_vars];\n  Real* Ginv_d = new Real[number_vars];\n  WeightArrayType Gt(Gt_d,number_vars);\n  WeightArrayType Ginv(Ginv_d,number_vars);\n  Gt.setZero();\n\n  Real* data1 = new Real[number_vars];\n\n  int batchsize = (train_length / num_batches) + 1;\n  cout << \"Batch size: \" << batchsize << endl;\n\n  for (auto iteration = 0; iteration < iterations; ++iteration)\n  {\n    //unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n    random_shuffle (mix.begin(), mix.end()); //, std::default_random_engine(seed));\n\n    for (auto batch = 0; batch < num_batches; ++batch)\n    {\n      batch_from = batch*batchsize;\n      batch_to = min((batch+1)*batchsize,train_length);\n\n      if (batch_to - batch_from > 0)\n      {\n        WeightArrayType grad(data1,number_vars);\n\n        //float err =\n        finetuneCostAndGrad_(theta_,data1,number_vars);\n        //grad /= (batch_to - batch_from);\n        Gt += grad*grad;\n        for (int i=0;i<number_vars;i++) {\n          if (Gt_d[i] == 0)\n            Ginv_d[i] = 0;\n          else\n            Ginv_d[i] = sqrt(1/Gt_d[i]);\n        }\n\n        grad *= Ginv;\n        grad *= eta;\n\n        //cout << theta.abs().sum() << \" vs \" << grad.abs().sum() << endl;\n        theta -= grad;\n      }\n    }\n\n    evaluate();\n  }\n\n  delete [] data1;\n  delete [] Gt_d;\n  delete [] Ginv_d;\n\n}\n\nlbfgsfloatval_t FinetuneClassifier::lbfgs_evaluate_(\n    void *instance,\n    const lbfgsfloatval_t *x,\n    lbfgsfloatval_t *g,\n    const int n,\n    const lbfgsfloatval_t step\n    )\n{\n  return reinterpret_cast<FinetuneClassifier*>(instance)->finetuneCostAndGrad_(x, g, n);\n}\n\nint FinetuneClassifier::lbfgs_progress_(\n    void *instance,\n    const lbfgsfloatval_t *x,\n    const lbfgsfloatval_t *g,\n    const lbfgsfloatval_t fx,\n    const lbfgsfloatval_t xnorm,\n    const lbfgsfloatval_t gnorm,\n    const lbfgsfloatval_t step,\n    int n,\n    int k,\n    int ls\n    )\n{\n  cout << \"N: \" << n << endl;\n  printf(\"Iteration %d:\\n\", k);\n  printf(\"  fx = %f, x[0] = %f, x[1] = %f %f\\n\", fx, x[0], x[1], x[2]);\n  printf(\"  fx = %f, g[0] = %f, g[1] = %f %f\\n\", fx, g[0], g[1], g[2]);\n  printf(\"  xnorm = %f, gnorm = %f, step = %f\\n\", xnorm, gnorm, step);\n  printf(\"\\n\");\n\n\n  reinterpret_cast<FinetuneClassifier*>(instance)->it_count++;\n  reinterpret_cast<FinetuneClassifier*>(instance)->evaluate();\n  return 0;\n}\n\n// ForwardPropagates and returns error and gradient on self\nlbfgsfloatval_t FinetuneClassifier::finetuneCostAndGrad_(\n    const lbfgsfloatval_t *x,\n    lbfgsfloatval_t *gradient_location,\n    const int n)\n{\n\n  WeightVectorType  grad(gradient_location,theta_size_);\n  grad.setZero();\n\n  WeightMatricesType Wcatgrad;\n  WeightVectorsType  Bcatgrad;\n\n  Real* ptr = gradient_location;\n  for (auto i=0; i<num_label_types; ++i) {\n    Wcatgrad.push_back(WeightMatrixType(ptr, label_width, dynamic_embedding_size));\n    ptr += label_width * dynamic_embedding_size;\n  }\n  for (auto i=0; i<num_label_types; ++i) {\n    Bcatgrad.push_back(WeightVectorType(ptr, label_width));\n    ptr += label_width;\n  }\n\n  assert(ptr == theta_size_ + gradient_location);\n\n  /***************************************************************************\n   *        Populate train input with forward Propagation and tricks         *\n   ***************************************************************************/\n  Real cost = 0.0;\n  int right = 0;\n  int wrong = 0;\n  int tp = 0;\n  int fp = 0;\n  int tn = 0;\n  int fn = 0;\n\n#pragma omp parallel for schedule(dynamic)\n  for (auto k = batch_from; k<batch_to; ++k)\n  {\n    auto i = mix[k];\n\n    // Encode input\n    ArrayReal label_vec = (\n        Wcat[0] * trainData[i].vector + Bcat[0]\n        ).unaryExpr(std::ptr_fun(getSigmoid)).array();\n\n    ArrayReal lbl_sm = label_vec - trainData[i].label;\n    ArrayReal delta = lbl_sm * (label_vec) * (1 - label_vec);\n\n#pragma omp critical\n    {\n      //cout << \"D/D2\" << delta << \" \" << delta2 << endl;\n      cost += 0.5 * (lbl_sm * lbl_sm).sum();\n      Wcatgrad[0] += delta.matrix() * trainData[i].vector.transpose();\n      Bcatgrad[0] += delta.matrix();\n\n      if(abs(lbl_sm.sum()) > 0.5)\n      {\n        wrong += 1;\n        if(trainData[i].label == 0)\n          ++fp;\n        else\n          ++fn;\n      }\n      else\n      {\n        right += 1;\n        if(trainData[i].label == 0)\n          ++tn;\n        else\n          ++tp;\n      }\n    }\n  }\n\n  /*\n   *cout << \"Correct: \" << right << \"/\" << right + wrong << \"   \";\n   *cout << \"Zero: \" << tp << \"/\" << tp+fn << \" \";\n   *cout << \"One:  \" << tn << \"/\" << tn+fp << endl;\n   */\n\n  float lambda_partial = lambda * (batch_to - batch_from) / train_length;\n  Wcatgrad[0] += lambda_partial*Wcat[0];\n  cost += 0.5*lambda_partial*(Wcat[0].cwiseProduct(Wcat[0])).sum();\n\n  Wcatgrad[0] /= (batch_to - batch_from);\n  cost /= (batch_to - batch_from);\n\n  return cost;\n}\n\n\nFinetuneClassifier::~FinetuneClassifier()\n{\n  delete [] trainI_;\n  delete [] theta_;\n\n}\n", "meta": {"hexsha": "bb37a94595922002f94e6a9a405fea2ec2e8db25", "size": 10574, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/common/finetune_classifier.cc", "max_stars_repo_name": "karlmoritz/oxcvsm", "max_stars_repo_head_hexsha": "02fd78231a8b3c4d48e9e759a3a075d04bcd0529", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-02-06T01:41:41.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-06T15:50:32.000Z", "max_issues_repo_path": "src/common/finetune_classifier.cc", "max_issues_repo_name": "karlmoritz/oxcvsm", "max_issues_repo_head_hexsha": "02fd78231a8b3c4d48e9e759a3a075d04bcd0529", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/finetune_classifier.cc", "max_forks_repo_name": "karlmoritz/oxcvsm", "max_forks_repo_head_hexsha": "02fd78231a8b3c4d48e9e759a3a075d04bcd0529", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-01-02T10:49:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-30T17:59:22.000Z", "avg_line_length": 26.9744897959, "max_line_length": 104, "alphanum_fraction": 0.5860601475, "num_tokens": 3029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2399622869502953}}
{"text": "#ifndef BOOST_NUMERIC_CHECKED_RESULT_OPERATIONS\n#define BOOST_NUMERIC_CHECKED_RESULT_OPERATIONS\n\n//  Copyright (c) 2012 Robert Ramey\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// Implemenation of arithmetic on \"extended\" integers.\n// Extended integers are defined in terms of C++ primitive integers as\n//     a) an interger range\n//     b) extra elements +inf, -inf, indeterminate\n//\n// Integer operations are closed on the set of extended integers\n// but operations are not necessarily associative when they result in the\n// extensions +inf, -inf, and indeterminate\n//\n// in this code, the type \"checked_result<T>\" where T is some\n// integer type is an \"extended\" integer.\n\n#include <cassert>\n\n#include <boost/logic/tribool.hpp>\n\n#include \"checked_result.hpp\"\n#include \"checked_integer.hpp\"\n\n//////////////////////////////////////////////////////////////////////////\n// the following idea of \"value_type\" is used by several of the operations\n// defined by checked_result arithmetic.\n\nnamespace boost {\nnamespace safe_numerics {\n\ntemplate<typename T>\nconstexpr inline void display(const boost::safe_numerics::checked_result<T> & c){\n    switch(c.m_e){\n    case safe_numerics_error::success:\n        std::terminate();\n    case safe_numerics_error::positive_overflow_error:    // result is above representational maximum\n        std::terminate();\n    case safe_numerics_error::negative_overflow_error:    // result is below representational minimum\n        std::terminate();\n    case safe_numerics_error::domain_error:               // one operand is out of valid range\n        std::terminate();\n    case safe_numerics_error::range_error:                // result cannot be produced for this operation\n        std::terminate();\n    case safe_numerics_error::precision_overflow_error:   // result lost precision\n        std::terminate();\n    case safe_numerics_error::underflow_error:            // result is too small to be represented\n        std::terminate();\n    case safe_numerics_error::negative_value_shift:       // negative value in shift operator\n        std::terminate();\n    case safe_numerics_error::negative_shift:             // shift a negative value\n        std::terminate();\n    case safe_numerics_error::shift_too_large:            // l/r shift exceeds variable size\n        std::terminate();\n    case safe_numerics_error::uninitialized_value:        // creating of uninitialized value\n        std::terminate();\n    }\n}\n\n//////////////////////////////////////////////////////////////////////////\n// implement C++ operators for check_result<T>\n\nstruct sum_value_type {\n    // characterization of various values\n    const enum flag {\n        known_value = 0,\n        less_than_min,\n        greater_than_max,\n        indeterminate,\n        count\n    } m_flag;\n    template<class T>\n    constexpr flag to_flag(const checked_result<T> & t) const {\n        switch(static_cast<safe_numerics_error>(t)){\n        case safe_numerics_error::success:\n            return known_value;\n        case safe_numerics_error::negative_overflow_error:\n            // result is below representational minimum\n            return less_than_min;\n        case safe_numerics_error::positive_overflow_error:\n            // result is above representational maximum\n            return greater_than_max;\n        default:\n            return indeterminate;\n        }\n    }\n    template<class T>\n    constexpr sum_value_type(const checked_result<T> & t) :\n        m_flag(to_flag(t))\n    {}\n    constexpr operator std::uint8_t () const {\n        return static_cast<std::uint8_t>(m_flag);\n    }\n};\n\n// integers addition\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator+(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    using value_type = sum_value_type;\n    const std::uint8_t order = static_cast<std::uint8_t>(value_type::count);\n\n    // note major pain.  Clang constexpr multi-dimensional array is fine.\n    // but gcc doesn't permit a multi-dimensional array to be be constexpr.\n    // so we need to some ugly gymnastics to make our system work for all\n    // all systems.\n    const enum safe_numerics_error result[order * order] = {\n        // t == known_value\n        //{\n            // u == ...\n            safe_numerics_error::success,                   // known_value,\n            safe_numerics_error::negative_overflow_error,   // less_than_min,\n            safe_numerics_error::positive_overflow_error,   // greater_than_max,\n            safe_numerics_error::range_error,               // indeterminate,\n        //},\n        // t == less_than_min,\n        //{\n            // u == ...\n            safe_numerics_error::negative_overflow_error,   // known_value,\n            safe_numerics_error::negative_overflow_error,   // less_than_min,\n            safe_numerics_error::range_error,               // greater_than_max,\n            safe_numerics_error::range_error,               // indeterminate,\n        //},\n        // t == greater_than_max,\n        //{\n            // u == ...\n            safe_numerics_error::positive_overflow_error,   // known_value,\n            safe_numerics_error::range_error,               // less_than_min,\n            safe_numerics_error::positive_overflow_error,   // greater_than_max,\n            safe_numerics_error::range_error,               // indeterminate,\n        //},\n        // t == indeterminate,\n        //{\n            // u == ...\n            safe_numerics_error::range_error,      // known_value,\n            safe_numerics_error::range_error,      // less_than_min,\n            safe_numerics_error::range_error,      // greater_than_max,\n            safe_numerics_error::range_error,      // indeterminate,\n        //},\n    };\n\n    const value_type tx(t);\n    const value_type ux(u);\n\n    const safe_numerics_error e = result[tx * order + ux];\n    if(safe_numerics_error::success == e)\n        return checked::add<T>(t, u);\n    return checked_result<T>(e, \"addition result\");\n}\n\n// unary +\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator+(\n    const checked_result<T> & t\n){\n    return t;\n}\n\n// integers subtraction\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator-(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    using value_type = sum_value_type;\n    constexpr const std::uint8_t order = static_cast<std::uint8_t>(value_type::count);\n\n    constexpr const enum safe_numerics_error result[order * order] = {\n        // t == known_value\n        //{\n            // u == ...\n            safe_numerics_error::success,                   // known_value,\n            safe_numerics_error::positive_overflow_error,   // less_than_min,\n            safe_numerics_error::negative_overflow_error,   // greater_than_max,\n            safe_numerics_error::range_error,               // indeterminate,\n        //},\n        // t == less_than_min,\n        //{\n            // u == ...\n            safe_numerics_error::negative_overflow_error,   // known_value,\n            safe_numerics_error::range_error,               // less_than_min,\n            safe_numerics_error::negative_overflow_error,   // greater_than_max,\n            safe_numerics_error::range_error,               // indeterminate,\n        //},\n        // t == greater_than_max,\n        //{\n            // u == ...\n            safe_numerics_error::positive_overflow_error,   // known_value,\n            safe_numerics_error::positive_overflow_error,   // less_than_min,\n            safe_numerics_error::range_error,               // greater_than_max,\n            safe_numerics_error::range_error,               // indeterminate,\n        //},\n        // t == indeterminate,\n        //{\n            // u == ...\n            safe_numerics_error::range_error,               // known_value,\n            safe_numerics_error::range_error,               // less_than_min,\n            safe_numerics_error::range_error,               // greater_than_max,\n            safe_numerics_error::range_error,               // indeterminate,\n        //},\n    };\n\n    const value_type tx(t);\n    const value_type ux(u);\n\n    const safe_numerics_error e = result[tx * order + ux];\n    if(safe_numerics_error::success == e)\n        return checked::subtract<T>(t, u);\n    return checked_result<T>(e, \"subtraction result\");\n}\n\n// unary -\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator-(\n    const checked_result<T> & t\n){\n//    assert(false);\n    return checked_result<T>(0) - t;\n}\n\nstruct product_value_type {\n    // characterization of various values\n    const enum flag {\n        less_than_min = 0,\n        less_than_zero,\n        zero,\n        greater_than_zero,\n        greater_than_max,\n        indeterminate,\n        // count of number of cases for values\n        count,\n        // temporary values for special cases\n        t_value,\n        u_value,\n        z_value\n    } m_flag;\n    template<class T>\n    constexpr flag to_flag(const checked_result<T> & t) const {\n        switch(static_cast<safe_numerics_error>(t)){\n        case safe_numerics_error::success:\n            return (t < checked_result<T>(0))\n                ? less_than_zero\n                : (t > checked_result<T>(0))\n                ? greater_than_zero\n                : zero;\n        case safe_numerics_error::negative_overflow_error:\n            // result is below representational minimum\n            return less_than_min;\n        case safe_numerics_error::positive_overflow_error:\n            // result is above representational maximum\n            return greater_than_max;\n        default:\n            return indeterminate;\n        }\n    }\n    template<class T>\n    constexpr product_value_type(const checked_result<T> & t) :\n        m_flag(to_flag(t))\n    {}\n    constexpr operator std::uint8_t () const {\n        return static_cast<std::uint8_t>(m_flag);\n    }\n};\n\n// integers multiplication\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator*(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    using value_type = product_value_type;\n    const std::uint8_t order = static_cast<std::uint8_t>(value_type::count);\n\n    constexpr const enum value_type::flag result[order * order] = {\n        // t == less_than_min\n        //{\n            // u == ...\n            value_type::greater_than_max,   // less_than_min,\n            value_type::greater_than_max,   // less_than_zero,\n            value_type::zero,               // zero,\n            value_type::less_than_min,      // greater_than_zero,\n            value_type::less_than_min,      // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == less_than_zero,\n        //{\n            // u == ...\n            value_type::greater_than_max,   // less_than_min,\n            value_type::greater_than_zero,  // less_than_zero,\n            value_type::zero,               // zero,\n            value_type::less_than_zero,     // greater_than_zero,\n            value_type::less_than_min,      // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == zero,\n        //{\n            // u == ...\n            value_type::zero,               // less_than_min,\n            value_type::zero,               // less_than_zero,\n            value_type::zero,               // zero,\n            value_type::zero,               // greater_than_zero,\n            value_type::zero,               // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == greater_than_zero,\n        //{\n            // u == ...\n            value_type::less_than_min,      // less_than_min,\n            value_type::less_than_zero,     // less_than_zero,\n            value_type::zero,               // zero,\n            value_type::greater_than_zero,  // greater_than_zero,\n            value_type::greater_than_max,   // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == greater_than_max\n        //{\n            value_type::less_than_min,      // less_than_min,\n            value_type::less_than_min,      // less_than_zero,\n            value_type::zero,               // zero,\n            value_type::greater_than_max,   // greater_than_zero,\n            value_type::greater_than_max,   // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == indeterminate\n        //{\n            value_type::indeterminate,      // less_than_min,\n            value_type::indeterminate,      // less_than_zero,\n            value_type::indeterminate,      // zero,\n            value_type::indeterminate,      // greater_than_zero,\n            value_type::indeterminate,      // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //}\n    };\n\n    const value_type tx(t);\n    const value_type ux(u);\n\n    switch(result[tx * order + ux]){\n        case value_type::less_than_min:\n            return safe_numerics_error::negative_overflow_error;\n        case value_type::zero:\n            return T(0);\n        case value_type::greater_than_max:\n            return safe_numerics_error::positive_overflow_error;\n        case value_type::less_than_zero:\n        case value_type::greater_than_zero:\n            return checked::multiply<T>(t, u);\n        case value_type::indeterminate:\n            return safe_numerics_error::range_error;\n        default:\n            assert(false);\n        }\n    return checked_result<T>(0); // to suppress msvc warning\n}\n\n// integers division\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator/(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    using value_type = product_value_type;\n    const std::uint8_t order = static_cast<std::uint8_t>(value_type::count);\n\n    constexpr const enum value_type::flag result[order * order] = {\n        // t == less_than_min\n        //{\n            // u == ...\n            value_type::indeterminate,   // less_than_min,\n            value_type::greater_than_max,   // less_than_zero,\n            value_type::less_than_min,      // zero,\n            value_type::less_than_min,      // greater_than_zero,\n            value_type::less_than_min,      // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == less_than_zero,\n        //{\n            // u == ...\n            value_type::zero,               // less_than_min,\n            value_type::greater_than_zero,  // less_than_zero,\n            value_type::less_than_min,      // zero,\n            value_type::less_than_zero,     // greater_than_zero,\n            value_type::zero,               // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == zero,\n        //{\n            // u == ...\n            value_type::zero,               // less_than_min,\n            value_type::zero,               // less_than_zero,\n            value_type::indeterminate,      // zero,\n            value_type::zero,               // greater_than_zero,\n            value_type::zero,               // greater than max,\n            value_type::indeterminate,               // indeterminate,\n        //},\n        // t == greater_than_zero,\n        //{\n            // u == ...\n            value_type::zero,               // less_than_min,\n            value_type::less_than_zero,     // less_than_zero,\n            value_type::greater_than_max,   // zero,\n            value_type::greater_than_zero,  // greater_than_zero,\n            value_type::zero,               // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == greater_than_max\n        //{\n            value_type::less_than_min,      // less_than_min,\n            value_type::less_than_min,      // less_than_zero,\n            value_type::greater_than_max,   // zero,\n            value_type::greater_than_max,   // greater_than_zero,\n            value_type::indeterminate,   // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == indeterminate\n        //{\n            value_type::indeterminate,      // less_than_min,\n            value_type::indeterminate,      // less_than_zero,\n            value_type::indeterminate,      // zero,\n            value_type::indeterminate,      // greater_than_zero,\n            value_type::indeterminate,      // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //}\n    };\n\n    const value_type tx(t);\n    const value_type ux(u);\n\n    switch(result[tx * order + ux]){\n        case value_type::less_than_min:\n            return safe_numerics_error::negative_overflow_error;\n        case value_type::zero:\n            return 0;\n        case value_type::greater_than_max:\n            return safe_numerics_error::positive_overflow_error;\n        case value_type::less_than_zero:\n        case value_type::greater_than_zero:\n            return checked::divide<T>(t, u);\n        case value_type::indeterminate:\n            return safe_numerics_error::range_error;\n        default:\n            assert(false);\n    }\n    return checked_result<T>(0); // to suppress msvc warning\n}\n\n// integers modulus\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator%(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    using value_type = product_value_type;\n    const std::uint8_t order = static_cast<std::uint8_t>(value_type::count);\n\n    constexpr const enum value_type::flag result[order * order] = {\n        // t == less_than_min\n        //{\n            // u == ...\n            value_type::indeterminate,      // less_than_min,\n            value_type::z_value,            // less_than_zero,\n            value_type::indeterminate,      // zero,\n            value_type::z_value,            // greater_than_zero,\n            value_type::indeterminate,      // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == less_than_zero,\n        //{\n            // u == ...\n            value_type::t_value,            // less_than_min,\n            value_type::greater_than_zero,  // less_than_zero,\n            value_type::indeterminate,      // zero,\n            value_type::less_than_zero,     // greater_than_zero,\n            value_type::t_value,            // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == zero,\n        //{\n            // u == ...\n            value_type::zero,               // less_than_min,\n            value_type::zero,               // less_than_zero,\n            value_type::indeterminate,      // zero,\n            value_type::zero,               // greater_than_zero,\n            value_type::zero,               // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == greater_than_zero,\n        //{\n            // u == ...\n            value_type::t_value,            // less_than_min,\n            value_type::less_than_zero,     // less_than_zero,\n            value_type::indeterminate,      // zero,\n            value_type::greater_than_zero,  // greater_than_zero,\n            value_type::t_value,            // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == greater_than_max\n        //{\n            value_type::indeterminate,      // less_than_min,\n            value_type::u_value,            // less_than_zero,\n            value_type::indeterminate,      // zero,\n            value_type::u_value,            // greater_than_zero,\n            value_type::indeterminate,      // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //},\n        // t == indeterminate\n        //{\n            value_type::indeterminate,      // less_than_min,\n            value_type::indeterminate,      // less_than_zero,\n            value_type::indeterminate,      // zero,\n            value_type::indeterminate,      // greater_than_zero,\n            value_type::indeterminate,      // greater than max,\n            value_type::indeterminate,      // indeterminate,\n        //}\n    };\n\n    const value_type tx(t);\n    const value_type ux(u);\n\n    switch(result[tx * order + ux]){\n        case value_type::zero:\n            return 0;\n        case value_type::less_than_zero:\n        case value_type::greater_than_zero:\n            return checked::modulus<T>(t, u);\n        case value_type::indeterminate:\n            return safe_numerics_error::range_error;\n        case value_type::t_value:\n            return t;\n        case value_type::u_value:\n            return checked::subtract<T>(u, 1);\n        case value_type::z_value:\n            return checked::subtract<T>(1, u);\n        case value_type::greater_than_max:\n        case value_type::less_than_min:\n        default:\n            assert(false);\n    }\n    // suppress msvc warning\n    return checked_result<T>(0);\n}\n\n// comparison operators\n\ntemplate<class T>\nconstexpr boost::logic::tribool operator<(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    using value_type = sum_value_type;\n    constexpr const std::uint8_t order = static_cast<std::uint8_t>(value_type::count);\n\n    // the question arises about how to order values of type greater_than_min.\n    // that is: what should greater_than_min < greater_than_min return.\n    //\n    // a) return indeterminate because we're talking about the \"true\" values for\n    //    which greater_than_min is a placholder.\n    //\n    // b) return false because the two values are \"equal\"\n    //\n    // for our purposes, a) seems the better interpretation.\n    \n    enum class result_type : std::uint8_t {\n        runtime,\n        false_value,\n        true_value,\n        indeterminate,\n    };\n    constexpr const result_type resultx[order * order]{\n        // t == known_value\n        //{\n            // u == ...\n            result_type::runtime,       // known_value,\n            result_type::false_value,   // less_than_min,\n            result_type::true_value,    // greater_than_max,\n            result_type::indeterminate, // indeterminate,\n        //},\n        // t == less_than_min\n        //{\n            // u == ...\n            result_type::true_value,    // known_value,\n            result_type::indeterminate, // less_than_min, see above argument\n            result_type::true_value,    // greater_than_max,\n            result_type::indeterminate, // indeterminate,\n        //},\n        // t == greater_than_max\n        //{\n            // u == ...\n            result_type::false_value,   // known_value,\n            result_type::false_value,   // less_than_min,\n            result_type::indeterminate, // greater_than_max, see above argument\n            result_type::indeterminate, // indeterminate,\n        //},\n        // t == indeterminate\n        //{\n            // u == ...\n            result_type::indeterminate, // known_value,\n            result_type::indeterminate, // less_than_min,\n            result_type::indeterminate, // greater_than_max,\n            result_type::indeterminate, // indeterminate,\n        //},\n    };\n\n    const value_type tx(t);\n    const value_type ux(u);\n\n    switch(resultx[tx * order + ux]){\n    case result_type::runtime:\n        return static_cast<const T &>(t) < static_cast<const T &>(u);\n    case result_type::false_value:\n        return false;\n    case result_type::true_value:\n        return true;\n    case result_type::indeterminate:\n        return boost::logic::indeterminate;\n    default:\n        assert(false);\n    }\n    return true;\n}\n\ntemplate<class T>\nconstexpr boost::logic::tribool\noperator>=(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    return !(t < u);\n}\n\ntemplate<class T>\nconstexpr boost::logic::tribool\noperator>(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    return u < t;\n}\n\ntemplate<class T>\nconstexpr boost::logic::tribool\noperator<=(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    return !(u < t);\n}\n\ntemplate<class T>\nconstexpr boost::logic::tribool\noperator==(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    using value_type = sum_value_type;\n    constexpr const std::uint8_t order = static_cast<std::uint8_t>(value_type::count);\n\n    enum class result_type : std::uint8_t {\n        runtime,\n        false_value,\n        true_value,\n        indeterminate,\n    };\n\n    constexpr const result_type result[order * order]{\n        // t == known_value\n        //{\n            // u == ...\n            result_type::runtime,       // known_value,\n            result_type::false_value,   // less_than_min,\n            result_type::false_value,   // greater_than_max,\n            result_type::indeterminate, // indeterminate,\n        //},\n        // t == less_than_min\n        //{\n            // u == ...\n            result_type::false_value,   // known_value,\n            result_type::indeterminate, // less_than_min,\n            result_type::false_value,   // greater_than_max,\n            result_type::indeterminate, // indeterminate,\n        //},\n        // t == greater_than_max\n        //{\n            // u == ...\n            result_type::false_value,   // known_value,\n            result_type::false_value,   // less_than_min,\n            result_type::indeterminate, // greater_than_max,\n            result_type::indeterminate, // indeterminate,\n        //},\n        // t == indeterminate\n        //{\n            // u == ...\n            result_type::indeterminate, // known_value,\n            result_type::indeterminate, // less_than_min,\n            result_type::indeterminate, // greater_than_max,\n            result_type::indeterminate, // indeterminate,\n        //},\n    };\n\n    const value_type tx(t);\n    const value_type ux(u);\n\n    switch(result[tx * order + ux]){\n    case result_type::runtime:\n        return static_cast<const T &>(t) == static_cast<const T &>(u);\n    case result_type::false_value:\n        return false;\n    case result_type::true_value:\n        return true;\n    case result_type::indeterminate:\n        return boost::logic::indeterminate;\n    default:\n        assert(false);\n    }\n    // suppress msvc warning - not all control paths return a value\n    return false;\n}\n\ntemplate<class T>\nconstexpr boost::logic::tribool\noperator!=(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    return ! (t == u);\n}\n\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator>>(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n);\n\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator~(\n    const checked_result<T> & t\n){\n//    assert(false);\n    return ~t.m_r;\n}\n\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator<<(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    using value_type = product_value_type;\n    const std::uint8_t order = static_cast<std::uint8_t>(value_type::count);\n\n    constexpr const std::uint8_t result[order * order] = {\n        // t == less_than_min\n        //{\n            // u == ...\n            1, // -1,                                           // less_than_min,\n            2, // safe_numerics_error::negative_overflow_error, // less_than_zero,\n            2, // safe_numerics_error::negative_overflow_error, // zero,\n            2, // safe_numerics_error::negative_overflow_error, // greater_than_zero,\n            2, // safe_numerics_error::negative_overflow_error, // greater than max,\n            1, // safe_numerics_error::range_error,             // indeterminate,\n        //},\n        // t == less_than_zero,\n        //{\n            // u == ...\n            3, // -1,                                           // less_than_min,\n            4, // - (-t >> -u),                                 // less_than_zero,\n            5, // safe_numerics_error::negative_overflow_error, // zero,\n            6, // - (-t << u),                                  // greater_than_zero,\n            2, // safe_numerics_error::negative_overflow_error, // greater than max,\n            1, // safe_numerics_error::range_error,             // indeterminate,\n        //},\n        // t == zero,\n        //{\n            // u == ...\n            3, // 0     // less_than_min,\n            3, // 0     // less_than_zero,\n            3, // 0,    // zero,\n            3, // 0,    // greater_than_zero,\n            3, // 0,    // greater than max,\n            3, // safe_numerics_error::range_error,    // indeterminate,\n        //},\n        // t == greater_than_zero,\n        //{\n            // u == ...\n            3, // 0,                                            // less_than_min,\n            7, // t << -u,                                      // less_than_zero,\n            5, // t,                                            // zero,\n            8, // t << u                                        // greater_than_zero,\n            9, // safe_numerics_error::positive_overflow_error, // greater than max,\n            1, // safe_numerics_error::range_error,             // indeterminate,\n        //},\n        // t == greater_than_max\n        //{\n            // u == ...\n            1, // safe_numerics_error::range_error,               // less_than_min,\n            9, // safe_numerics_error::positive_overflow_error),  // less_than_zero,\n            9, // safe_numerics_error::positive_overflow_error,   // zero,\n            9, // safe_numerics_error::positive_overflow_error),  // greater_than_zero,\n            9, // safe_numerics_error::positive_overflow_error,   // greater than max,\n            1, // safe_numerics_error::range_error,               // indeterminate,\n        //},\n        // t == indeterminate\n        //{\n            1, // safe_numerics_error::range_error,    // indeterminate,\n            1, // safe_numerics_error::range_error,    // indeterminate,\n            1, // safe_numerics_error::range_error,    // indeterminate,\n            1, // safe_numerics_error::range_error,    // indeterminate,\n            1, // safe_numerics_error::range_error,    // indeterminate,\n            1, // safe_numerics_error::range_error,    // indeterminate,\n        //}\n    };\n\n    const value_type tx(t);\n    const value_type ux(u);\n    assert(tx * order + ux < order * order);\n\n    // I had a switch(i) statment here - but it results in an ICE\n    // on multiple versions of gcc.  So make the equivalent in\n    // nested if statments - should be the same (more or less)\n    // performancewise.\n    const unsigned int i = result[tx * order + ux];\n    assert(i <= 9);\n    if(1 == i){\n        return safe_numerics_error::range_error;\n    }\n    else\n    if(2 == i){\n        return safe_numerics_error::negative_overflow_error;\n    }\n    else\n    if(3 == i){\n        return checked_result<T>(0);\n    // the following gymnastics are to handle the case where \n    // a value is changed from a negative to a positive number.\n    // For example, and 8 bit number t == -128.  Then -t also\n    // equals -128 since 128 cannot be held in an 8 bit signed\n    // integer.\n    }\n    else\n    if(4 == i){ // - (-t >> -u)\n        assert(static_cast<bool>(t < checked_result<T>(0)));\n        assert(static_cast<bool>(u < checked_result<T>(0)));\n        return t >> -u;\n    }\n    else\n    if(5 == i){\n        return t;\n    }\n    else\n    if(6 == i){ // - (-t << u)\n        assert(static_cast<bool>(t < checked_result<T>(0)));\n        assert(static_cast<bool>(u > checked_result<T>(0)));\n        const checked_result<T> temp_t = t * checked_result<T>(2);\n        const checked_result<T> temp_u = u - checked_result<T>(1);\n        return  - (-temp_t << temp_u);\n    }\n    else\n    if(7 == i){  // t >> -u\n        assert(static_cast<bool>(t > checked_result<T>(0)));\n        assert(static_cast<bool>(u < checked_result<T>(0)));\n        return t >> -u;\n    }\n    else\n    if(8 == i){ // t << u\n        assert(static_cast<bool>(t > checked_result<T>(0)));\n        assert(static_cast<bool>(u > checked_result<T>(0)));\n        checked_result<T> r = checked::left_shift<T>(t, u);\n        return (r.m_e == safe_numerics_error::shift_too_large)\n        ? checked_result<T>(safe_numerics_error::positive_overflow_error)\n        : r;\n    }\n    else\n    if(9 == i){\n        return safe_numerics_error::positive_overflow_error;\n    }\n    else{\n        assert(false);\n    };\n    return checked_result<T>(0); // to suppress msvc warning\n}\n\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator>>(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    using value_type = product_value_type;\n    const std::uint8_t order = static_cast<std::uint8_t>(value_type::count);\n\n    const std::uint8_t result[order * order] = {\n        // t == less_than_min\n        //{\n            // u == ...\n            2, // safe_numerics_error::negative_overflow_error, // less_than_min,\n            2, // safe_numerics_error::negative_overflow_error, // less_than_zero,\n            2, // safe_numerics_error::negative_overflow_error, // zero,\n            2, // safe_numerics_error::negative_overflow_error, // greater_than_zero,\n            1, // safe_numerics_error::range_error,             // greater than max,\n            1, // safe_numerics_error::range_error,             // indeterminate,\n        //},\n        // t == less_than_zero,\n        //{\n            // u == ...\n            2, // safe_numerics_error::negative_overflow_error  // less_than_min,\n            4, // - (-t << -u),                                 // less_than_zero,\n            5, // safe_numerics_error::negative_overflow_error. // zero,\n            6, // - (-t >> u),                                  // greater_than_zero,\n            3, // 0, ? or -1                                    // greater than max,\n            1, // safe_numerics_error::range_error,             // indeterminate,\n        //},\n        // t == zero,\n        //{\n            // u == ...\n            3, // 0     // less_than_min,\n            3, // 0     // less_than_zero,\n            3, // 0,    // zero,\n            3, // 0,    // greater_than_zero,\n            3, // 0,    // greater than max,\n            3, // safe_numerics_error::range_error,    // indeterminate,\n        //},\n        // t == greater_than_zero,\n        //{\n            // u == ...\n            9, // safe_numerics_error::positive_overflow_error  // less_than_min,\n            7, // t << -u,                                      // less_than_zero,\n            5, // t,                                            // zero,\n            8, // t >> u                                        // greater_than_zero,\n            3, // 0,                                            // greater than max,\n            1, // safe_numerics_error::range_error,             // indeterminate,\n        //},\n        // t == greater_than_max\n        //{\n            // u == ...\n            9, // safe_numerics_error::positive_overflow_error, // less_than_min,\n            9, // safe_numerics_error::positive_overflow_error, // less_than_zero,\n            9, // safe_numerics_error::positive_overflow_error, // zero,\n            9, // safe_numerics_error::positive_overflow_error, // greater_than_zero,\n            1, // safe_numerics_error::range_error,             // greater than max,\n            1, // safe_numerics_error::range_error,             // indeterminate,\n        //},\n        // t == indeterminate\n        //{\n            1, // safe_numerics_error::range_error,    // indeterminate,\n            1, // safe_numerics_error::range_error,    // indeterminate,\n            1, // safe_numerics_error::range_error,    // indeterminate,\n            1, // safe_numerics_error::range_error,    // indeterminate,\n            1, // safe_numerics_error::range_error,    // indeterminate,\n            1, // safe_numerics_error::range_error,    // indeterminate,\n        //}\n    };\n\n    const value_type tx(t);\n    const value_type ux(u);\n    assert(tx * order + ux < order * order);\n\n    // I had a switch(i) statment here - but it results in an ICE\n    // on multiple versions of gcc.  So make the equivalent in\n    // nested if statments - should be the same (more or less)\n    // performancewise.\n    const unsigned int i = result[tx * order + ux];\n    assert(i <= 9);\n    if(1 == i){\n        return safe_numerics_error::range_error;\n    }\n    else\n    if(2 == i){\n        return safe_numerics_error::negative_overflow_error;\n    }\n    else\n    if(3 == i){\n        return checked_result<T>(0);\n    }\n    else\n    if(4 == i){ // - (-t << -u)\n        assert(static_cast<bool>(t < checked_result<T>(0)));\n        assert(static_cast<bool>(u < checked_result<T>(0)));\n        return t << -u;\n    }\n    else\n    if(5 == i){\n        return t;\n    }\n    else\n    if(6 == i){ //  - (-t >> u)\n        assert(static_cast<bool>(t < checked_result<T>(0)));\n        assert(static_cast<bool>(u > checked_result<T>(0)));\n        const checked_result<T> temp_t = t / checked_result<T>(2);\n        const checked_result<T> temp_u = u - checked_result<T>(1);\n        return  - (-temp_t >> temp_u);\n    }\n    else\n    if(7 == i){  // t << -u,\n        assert(static_cast<bool>(t > checked_result<T>(0)));\n        assert(static_cast<bool>(u < checked_result<T>(0)));\n        return t << -u;\n    }\n    else\n    if(8 == i){ // t >> u\n        assert(static_cast<bool>(t > checked_result<T>(0)));\n        assert(static_cast<bool>(u > checked_result<T>(0)));\n        checked_result<T> r = checked::right_shift<T>(t, u);\n        return (r.m_e == safe_numerics_error::shift_too_large)\n        ? checked_result<T>(0)\n        : r;\n    }\n    else\n    if(9 == i){\n        return safe_numerics_error::positive_overflow_error;\n    }\n    else{\n        assert(false);\n    };\n    return checked_result<T>(0); // to suppress msvc warning\n}\n\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator|(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    return\n        t.exception() || u.exception()\n        ? checked_result<T>(safe_numerics_error::range_error)\n        : checked::bitwise_or<T>(\n            static_cast<T>(t),\n            static_cast<T>(u)\n        );\n}\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator^(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    return\n        t.exception() || u.exception()\n        ? checked_result<T>(safe_numerics_error::range_error)\n        : checked::bitwise_xor<T>(\n            static_cast<T>(t),\n            static_cast<T>(u)\n        );\n}\n\ntemplate<class T>\ntypename std::enable_if<\n    std::is_integral<T>::value,\n    checked_result<T>\n>::type\nconstexpr inline operator&(\n    const checked_result<T> & t,\n    const checked_result<T> & u\n){\n    return\n        t.exception() || u.exception()\n        ? checked_result<T>(safe_numerics_error::range_error)\n        : checked::bitwise_and<T>(\n            static_cast<T>(t),\n            static_cast<T>(u)\n        );\n}\n\n} // safe_numerics\n} // boost\n\n#include <iosfwd>\n\nnamespace std {\n\ntemplate<typename CharT, typename Traits, typename R>\ninline std::basic_ostream<CharT, Traits> & operator<<(\n    std::basic_ostream<CharT, Traits> & os,\n    const boost::safe_numerics::checked_result<R> & r\n){\n    bool e = r.exception();\n    os << e;\n    if(!e)\n        os << static_cast<R>(r);\n    else\n        os << std::error_code(r.m_e).message() << ':' << static_cast<char const *>(r);\n    return os;\n}\n\ntemplate<typename CharT, typename Traits>\ninline std::basic_ostream<CharT, Traits> & operator<<(\n    std::basic_ostream<CharT, Traits> & os,\n    const boost::safe_numerics::checked_result<signed char> & r\n){\n    bool e = r.exception();\n    os << e;\n    if(! e)\n        os << static_cast<std::int16_t>(r);\n    else\n        os << std::error_code(r.m_e).message() << ':' << static_cast<char const *>(r);\n    return os;\n}\n\ntemplate<typename CharT, typename Traits, typename R>\ninline std::basic_istream<CharT, Traits> & operator>>(\n    std::basic_istream<CharT, Traits> & is,\n    boost::safe_numerics::checked_result<R> & r\n){\n    bool e;\n    is >> e;\n    if(!e)\n        is >> static_cast<R>(r);\n    else\n        is >> std::error_code(r.m_e).message() >> ':' >> static_cast<char const *>(r);\n    return is;\n}\n\ntemplate<typename CharT, typename Traits>\ninline std::basic_istream<CharT, Traits> & operator>>(\n    std::basic_istream<CharT, Traits> & is, \n    boost::safe_numerics::checked_result<signed char> & r\n){\n    bool e;\n    is >> e;\n    if(!e){\n        std::int16_t i;\n        is >> i;\n        r.m_contents.m_r = static_cast<signed char>(i);\n    }\n    else\n        is >> std::error_code(r.m_e).message() >> ':' >> static_cast<char const *>(r);\n    return is;\n}\n\n} // std\n\n/////////////////////////////////////////////////////////////////\n// numeric limits for checked<R>\n\n#include <limits>\n\nnamespace std {\n\ntemplate<class R>\nclass numeric_limits<boost::safe_numerics::checked_result<R> >\n    : public std::numeric_limits<R>\n{\n    using this_type = boost::safe_numerics::checked_result<R>;\npublic:\n    constexpr static this_type min() noexcept {\n        return this_type(std::numeric_limits<R>::min());\n    }\n    constexpr static this_type max() noexcept {\n        return this_type(std::numeric_limits<R>::max());\n    }\n};\n\n} // std\n\n#endif  // BOOST_NUMERIC_CHECKED_RESULT_OPERATIONS\n", "meta": {"hexsha": "f5b8f9af4c8454b36c77707b6e63925d61c8f7e5", "size": 42336, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/safe_numerics/checked_result_operations.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 111.0, "max_stars_repo_stars_event_min_datetime": "2018-09-26T00:40:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-08T12:02:17.000Z", "max_issues_repo_path": "lib/boost_1.78.0/boost/safe_numerics/checked_result_operations.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "lib/boost_1.78.0/boost/safe_numerics/checked_result_operations.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 34.9884297521, "max_line_length": 105, "alphanum_fraction": 0.5624055178, "num_tokens": 9608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23986766542353896}}
{"text": "#include <boost/math/special_functions/next.hpp>\n#include <boost/random.hpp>\n\n#include <limits>\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\nnamespace caffe {\n\n// Integer quantized types\ntemplate<typename Dtype>\ntypename std::enable_if<unsigned_integer_is_same<Dtype>::value, void>::type\ncaffe_gemv(const CBLAS_TRANSPOSE trans_A,\n           const int_tp M, const int_tp N, const Dtype alpha,\n           const Dtype* a, const Dtype* x,\n           const Dtype beta, Dtype* y,\n           const QuantizerValues* const alpha_quant,\n           const QuantizerValues* const a_quant,\n           const QuantizerValues* const x_quant,\n           const QuantizerValues* const beta_quant,\n           const QuantizerValues* const y_quant) {\n\n  typedef typename std::conditional<sizeof(Dtype) == 1, int16_t,\n          typename std::conditional<sizeof(Dtype) == 2, int32_t,\n                                    int64_t>::type>::type Difftype;\n  typedef typename std::conditional<sizeof(Dtype) == 1,\n                                    int32_t, int64_t>::type Acctype;\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 y_max = y_quant->get_max<Acctype>();\n  Acctype y_min = y_quant->get_min<Acctype>();\n  Dtype lhs_off = a_quant->get_zero<Dtype>();\n  Dtype rhs_off = x_quant->get_zero<Dtype>();\n  Dtype alpha_off = alpha_quant ? alpha_quant->get_zero<Dtype>() : Dtype(0);\n  Dtype beta_off = beta_quant ? beta_quant->get_zero<Dtype>() : Dtype(0);\n  const Acctype result_off = y_quant->get_zero<Acctype>();\n\n  QuantizerBase::template MultiplicativeQuantVals<int32_t>(\n      a_quant, x_quant, y_quant, &mult, &shift, shift_bits);\n  QuantizerBase::template MultiplicativeQuantVals<int32_t>(\n      y_quant, alpha_quant, y_quant, &alpha_mult, &alpha_shift, shift_bits);\n  QuantizerBase::template MultiplicativeQuantVals<int32_t>(\n      y_quant, beta_quant, y_quant, &beta_mult, &beta_shift, shift_bits);\n\n  int_tp a_inc = (trans_A == CblasNoTrans) ? 1 : N;\n  int_tp y_cnt = (trans_A == CblasNoTrans) ? M : N;\n  int_tp x_cnt = (trans_A == CblasNoTrans) ? N : M;\n#pragma omp parallel for\n  for (int_tp m = 0; m < y_cnt; m++) {\n    int_tp a_index = (trans_A == CblasNoTrans) ? m * N : m;\n    Acctype acc = 0;\n    for (int_tp n = 0; n < x_cnt; n++) {\n      Difftype a_diff = a[a_index] - lhs_off;\n      Difftype x_diff = x[n] - rhs_off;\n      acc += static_cast<Acctype>(a_diff) * static_cast<Acctype>(x_diff);\n      a_index += a_inc;\n    }\n    Acctype reg = acc * (alpha_quant ? Acctype(1) : alpha);\n    reg = static_cast<Acctype>((static_cast<int64_t>(reg) *\n                           static_cast<int64_t>(mult)) / (1ll << shift_bits));\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<Acctype>(alpha_diff) * static_cast<Acctype>(reg);\n      reg = static_cast<Acctype>((static_cast<int64_t>(reg) *\n                     static_cast<int64_t>(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    if (beta_quant) {\n      Difftype beta_diff = beta - beta_off;\n      Difftype c_diff = y[m] - static_cast<Difftype>(result_off);\n      Acctype creg = static_cast<Acctype>(beta_diff)\n                   * static_cast<Acctype>(c_diff);\n      creg = static_cast<Acctype>((static_cast<int64_t>(creg) *\n                      static_cast<int64_t>(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 + (y[m] - result_off);\n    }\n    reg = reg + result_off;\n    y[m] = static_cast<Dtype>(std::min(std::max(reg, y_min), y_max));\n  }\n}\n\n// Half precision\ntemplate<typename Dtype>\ntypename std::enable_if<float_is_same<Dtype>::value, void>::type\ncaffe_gemv(const CBLAS_TRANSPOSE trans_A,\n           const int_tp M, const int_tp N, const Dtype alpha,\n           const Dtype* a, const Dtype* x,\n           const Dtype beta, Dtype* y,\n           const QuantizerValues* const alpha_quant,\n           const QuantizerValues* const a_quant,\n           const QuantizerValues* const x_quant,\n           const QuantizerValues* const beta_quant,\n           const QuantizerValues* const y_quant) {\n  int_tp a_inc = (trans_A == CblasNoTrans) ? 1 : N;\n  int_tp y_cnt = (trans_A == CblasNoTrans) ? M : N;\n  int_tp x_cnt = (trans_A == CblasNoTrans) ? N : M;\n  for (int_tp m = 0; m < y_cnt; m++) {\n    int_tp a_index = (trans_A == CblasNoTrans) ? m * N : m;\n    Dtype acc = 0;\n    for (int_tp n = 0; n < x_cnt; n++) {\n      acc += a[a_index] * x[n];\n      a_index += a_inc;\n    }\n    if (beta == 0)\n      y[m] = acc * alpha;\n    else\n      y[m] = acc * alpha + beta * y[m];\n  }\n}\n\ntemplate\ntypename std::enable_if<float_is_same<half_fp>::value, void>::type\ncaffe_gemv<half_fp>(const CBLAS_TRANSPOSE trans_A,\n                    const int_tp M, const int_tp N,\n                    const half_fp alpha,\n                    const half_fp* a, const half_fp* x,\n                    const half_fp beta, half_fp* y,\n                    const QuantizerValues* const alpha_quant,\n                    const QuantizerValues* const a_quant,\n                    const QuantizerValues* const x_quant,\n                    const QuantizerValues* const beta_quant,\n                    const QuantizerValues* const y_quant);\ntemplate\ntypename std::enable_if<unsigned_integer_is_same<uint8_t>::value, void>::type\ncaffe_gemv<uint8_t>(const CBLAS_TRANSPOSE trans_A,\n                    const int_tp M, const int_tp N,\n                    const uint8_t alpha,\n                    const uint8_t* a, const uint8_t* x,\n                    const uint8_t beta, uint8_t* y,\n                    const QuantizerValues* const alpha_quant,\n                    const QuantizerValues* const a_quant,\n                    const QuantizerValues* const x_quant,\n                    const QuantizerValues* const beta_quant,\n                    const QuantizerValues* const y_quant);\ntemplate\ntypename std::enable_if<unsigned_integer_is_same<uint16_t>::value, void>::type\ncaffe_gemv<uint16_t>(const CBLAS_TRANSPOSE trans_A,\n                     const int_tp M, const int_tp N,\n                     const uint16_t alpha,\n                     const uint16_t* a, const uint16_t* x,\n                     const uint16_t beta, uint16_t* y,\n                     const QuantizerValues* const alpha_quant,\n                     const QuantizerValues* const a_quant,\n                     const QuantizerValues* const x_quant,\n                     const QuantizerValues* const beta_quant,\n                     const QuantizerValues* const y_quant);\ntemplate\ntypename std::enable_if<unsigned_integer_is_same<uint32_t>::value, void>::type\ncaffe_gemv<uint32_t>(const CBLAS_TRANSPOSE trans_A,\n                     const int_tp M, const int_tp N,\n                     const uint32_t alpha,\n                     const uint32_t* a, const uint32_t* x,\n                     const uint32_t beta, uint32_t* y,\n                     const QuantizerValues* const alpha_quant,\n                     const QuantizerValues* const a_quant,\n                     const QuantizerValues* const x_quant,\n                     const QuantizerValues* const beta_quant,\n                     const QuantizerValues* const y_quant);\n\ntemplate\ntypename std::enable_if<unsigned_integer_is_same<uint64_t>::value, void>::type\ncaffe_gemv<uint64_t>(const CBLAS_TRANSPOSE trans_A,\n                     const int_tp M, const int_tp N,\n                     const uint64_t alpha,\n                     const uint64_t* a, const uint64_t* x,\n                     const uint64_t beta, uint64_t* y,\n                     const QuantizerValues* const alpha_quant,\n                     const QuantizerValues* const a_quant,\n                     const QuantizerValues* const x_quant,\n                     const QuantizerValues* const beta_quant,\n                     const QuantizerValues* const y_quant);\n\ntemplate<>\nvoid caffe_gemv<float>(const CBLAS_TRANSPOSE trans_A, const int_tp M,\n                       const int_tp N, const float alpha, const float* A,\n                       const float* x, const float beta, float* y,\n                       const QuantizerValues* const alpha_quant,\n                       const QuantizerValues* const a_quant,\n                       const QuantizerValues* const x_quant,\n                       const QuantizerValues* const beta_quant,\n                       const QuantizerValues* const y_quant) {\n  cblas_sgemv(CblasRowMajor, trans_A, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\ntemplate<>\nvoid caffe_gemv<double>(const CBLAS_TRANSPOSE trans_A, const int_tp M,\n                        const int_tp N, const double alpha, const double* A,\n                        const double* x, const double beta, double* y,\n                        const QuantizerValues* const alpha_quant,\n                        const QuantizerValues* const a_quant,\n                        const QuantizerValues* const x_quant,\n                        const QuantizerValues* const beta_quant,\n                        const QuantizerValues* const y_quant) {\n  cblas_dgemv(CblasRowMajor, trans_A, M, N, alpha, A, N, x, 1, beta, y, 1);\n}\n\n}  // namespace caffe\n\n", "meta": {"hexsha": "7e8c579bdffc295698453acda987a19203ed50f0", "size": 9560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/util/math_blas_2.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_2.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_2.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": 42.4888888889, "max_line_length": 78, "alphanum_fraction": 0.6009414226, "num_tokens": 2378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.37022539954425293, "lm_q1q2_score": 0.2398313591001216}}
{"text": "// Copyright (c) 2015-2021 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#include \"variational_bayes_mixture_mixture_model.hpp\"\n\n#include <utility>\n#include <cmath>\n#include <iterator>\n#include <algorithm>\n#include <numeric>\n#include <iostream>\n#include <limits>\n\n#include <boost/math/special_functions/digamma.hpp>\n\n#include \"utils/maths.hpp\"\n\nnamespace octopus { namespace model {\n\nVariationalBayesMixtureMixtureModel::VariationalBayesMixtureMixtureModel(Options options)\n: options_ {std::move(options)}\n{}\n\nVariationalBayesMixtureMixtureModel::Inferences\nVariationalBayesMixtureMixtureModel::evaluate(const LogProbabilityVector& genotype_log_priors,\n                                              const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                              const GroupOptionalPriorArray& group_priors,\n                                              const GroupConcentrationVector& group_concentrations,\n                                              const MixtureConcentrationArray& mixture_concentrations,\n                                              std::vector<LogProbabilityVector> seeds) const\n{\n    const auto group_log_priors = to_logs(group_priors);\n    const auto expanded_log_likelihoods = expand(log_likelihoods);\n    const auto evaluate_seed = [&] (auto&& seed) {\n        return this->evaluate(genotype_log_priors, log_likelihoods, expanded_log_likelihoods, group_log_priors, group_concentrations, mixture_concentrations, std::move(seed)); };\n    std::vector<PointInferences> seed_inferences(seeds.size());\n    if (options_.parallel_execution) {\n        parallel_transform(std::make_move_iterator(std::begin(seeds)), std::make_move_iterator(std::end(seeds)), std::begin(seed_inferences), evaluate_seed);\n    } else {\n        std::transform(std::make_move_iterator(std::begin(seeds)), std::make_move_iterator(std::end(seeds)), std::begin(seed_inferences), evaluate_seed);\n    }\n    Inferences result {};\n    compute_evidence_weighted_latents(result.weighted_genotype_posteriors, result.weighted_group_responsibilities, seed_inferences);\n    const static auto evidence_less = [] (const auto& lhs, const auto& rhs) { return lhs.approx_log_evidence < rhs.approx_log_evidence; };\n    result.map = *std::max_element(std::begin(seed_inferences), std::end(seed_inferences), evidence_less);\n    return result;\n}\n\nVariationalBayesMixtureMixtureModel::Inferences\nVariationalBayesMixtureMixtureModel::evaluate(const LogProbabilityVector& genotype_log_priors,\n                                              const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                              const GroupConcentrationVector& group_concentrations,\n                                              const MixtureConcentrationArray& mixture_concentrations,\n                                              std::vector<LogProbabilityVector> seeds) const\n{\n    const auto num_samples = log_likelihoods.size();\n    const GroupOptionalPriorArray no_priors(num_samples);\n    return evaluate(genotype_log_priors, log_likelihoods, no_priors, group_concentrations, mixture_concentrations, std::move(seeds));\n}\n\nVariationalBayesMixtureMixtureModel::Inferences\nVariationalBayesMixtureMixtureModel::evaluate(const LogProbabilityVector& genotype_log_priors,\n                                              const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                              const GroupOptionalPriorArray& group_priors,\n                                              const double group_concentration,\n                                              const std::vector<double>& mixture_concentrations,\n                                              std::vector<LogProbabilityVector> seeds) const\n{\n    const auto num_samples = log_likelihoods.size();\n    assert(mixture_concentrations.size() == num_samples);\n    const auto num_groups = log_likelihoods.front().front().size();\n    std::vector<unsigned> group_mixture_sizes {};\n    group_mixture_sizes.reserve(num_groups);\n    for (const auto& genotype : log_likelihoods.front().front()) {\n        group_mixture_sizes.push_back(genotype.size());\n    }\n    const GroupConcentrationVector group_concentrations(num_groups, group_concentration);\n    MixtureConcentrationArray group_mixture_concentrations {};\n    group_mixture_concentrations.reserve(num_samples);\n    for (auto sample_concentration : mixture_concentrations) {\n        group_mixture_concentrations.emplace_back(num_groups, ComponentConcentrationVector(sample_concentration));\n        unsigned t {0};\n        for (auto& sample_group_sample_concentrations : group_mixture_concentrations.back()) {\n            sample_group_sample_concentrations.assign(group_mixture_sizes[t++], sample_concentration);\n        }\n    }\n    return evaluate(genotype_log_priors, log_likelihoods, group_priors, group_concentrations, group_mixture_concentrations, std::move(seeds));\n}\n\nVariationalBayesMixtureMixtureModel::Inferences\nVariationalBayesMixtureMixtureModel::evaluate(const LogProbabilityVector& genotype_log_priors,\n                                              const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                              const double group_concentration,\n                                              const std::vector<double>& mixture_concentrations,\n                                              std::vector<LogProbabilityVector> seeds) const\n{\n    const auto num_samples = log_likelihoods.size();\n    const GroupOptionalPriorArray no_priors(num_samples);\n    return evaluate(genotype_log_priors, log_likelihoods, no_priors, group_concentration, mixture_concentrations, std::move(seeds));\n}\n\nVariationalBayesMixtureMixtureModel::Inferences\nVariationalBayesMixtureMixtureModel::evaluate(const LogProbabilityVector& genotype_log_priors,\n                                              const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                              const GroupOptionalPriorArray& group_priors,\n                                              const double group_concentration,\n                                              const double mixture_concentration,\n                                              std::vector<LogProbabilityVector> seeds) const\n{\n    const auto num_samples = log_likelihoods.size();\n    const auto num_groups = log_likelihoods.front().front().size();\n    std::vector<unsigned> group_mixture_sizes {};\n    group_mixture_sizes.reserve(num_groups);\n    for (const auto& genotype : log_likelihoods.front().front()) {\n        group_mixture_sizes.push_back(genotype.size());\n    }\n    const GroupConcentrationVector group_concentrations(num_groups, group_concentration);\n    MixtureConcentrationArray mixture_concentrations(num_samples, MixtureConcentrationVector(num_groups));\n    for (auto& sample_concentrations : mixture_concentrations) {\n        unsigned t {0};\n        for (auto& sample_group_sample_concentrations : sample_concentrations) {\n            sample_group_sample_concentrations.assign(group_mixture_sizes[t++], mixture_concentration);\n        }\n    }\n    return evaluate(genotype_log_priors, log_likelihoods, group_priors, group_concentrations, mixture_concentrations, std::move(seeds));\n}\n\nVariationalBayesMixtureMixtureModel::Inferences\nVariationalBayesMixtureMixtureModel::evaluate(const LogProbabilityVector& genotype_log_priors,\n                                              const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                              const double group_concentration,\n                                              const double mixture_concentration,\n                                              std::vector<LogProbabilityVector> seeds) const\n{\n    const auto num_samples = log_likelihoods.size();\n    const GroupOptionalPriorArray no_priors(num_samples);\n    return evaluate(genotype_log_priors, log_likelihoods, no_priors, group_concentration, mixture_concentration, std::move(seeds));\n}\n\n// Private methods\n\nVariationalBayesMixtureMixtureModel::GroupOptionalLogPriorVector\nVariationalBayesMixtureMixtureModel::to_logs(const GroupOptionalPriorVector& prior) const\n{\n    GroupOptionalLogPriorVector result {};\n    if (prior) {\n        result = LogProbabilityVector(prior->size());\n        const static auto to_log = [] (auto p) noexcept {\n            const static auto min_log_prior = std::log(std::numeric_limits<LogProbability>::min());\n            return p > 0 ? std::log(p) : min_log_prior;\n        };\n        std::transform(std::cbegin(*prior), std::cend(*prior), std::begin(*result), to_log);\n    }\n    return result;\n}\n\nVariationalBayesMixtureMixtureModel::GroupOptionalLogPriorArray\nVariationalBayesMixtureMixtureModel::to_logs(const GroupOptionalPriorArray& priors) const\n{\n    GroupOptionalLogPriorArray result {};\n    result.reserve(priors.size());\n    std::transform(std::cbegin(priors), std::cend(priors), std::back_inserter(result),\n                   [this] (const auto& sample_priors) { return to_logs(sample_priors); });\n    return result;\n}\n\nVariationalBayesMixtureMixtureModel::ExpandedHaplotypeLikelihoodMatrix \nVariationalBayesMixtureMixtureModel::expand(const HaplotypeLikelihoodMatrix& likelihoods) const\n{\n    const auto S = likelihoods.size();\n    const auto G = likelihoods[0].size();\n    const auto T = likelihoods[0][0].size();\n    ExpandedHaplotypeLikelihoodMatrix result(S, ExpandedGroupLikelihoodVector(T));\n    for (std::size_t s {0}; s < S; ++s) {\n        const auto N = likelihoods[s][0][0][0].size();\n        for (std::size_t t {0}; t < T; ++t) {\n            const auto K = likelihoods[0][0][t].size();\n            result[s][t].assign(K, ExpandedGenotype(N, ExpandedLikelihood(G)));\n            for (std::size_t k {0}; k < K; ++k) {\n                for (std::size_t g {0}; g < G; ++g) {\n                    for (std::size_t n {0}; n < N; ++n) {\n                        result[s][t][k][n][g] = likelihoods[s][g][t][k][n];\n                    }\n                }\n            }\n        }\n    }\n    return result;\n}\n\nnamespace {\n\nVariationalBayesMixtureMixtureModel::ProbabilityVector&\nexp(const LogProbabilityVector& log_probabilities, ProbabilityVector& result) noexcept\n{\n    std::transform(std::cbegin(log_probabilities), std::cend(log_probabilities), std::begin(result),\n                   [] (const auto lp) noexcept { return std::exp(lp); });\n    return result;\n}\n\nauto exp(const VariationalBayesMixtureMixtureModel::LogProbabilityVector& log_probabilities)\n{\n    VariationalBayesMixtureMixtureModel::ProbabilityVector result(log_probabilities.size());\n    return exp(log_probabilities, result);\n}\n\ntemplate <typename T>\nauto sum(const std::vector<T>& values) noexcept\n{\n    return std::accumulate(std::cbegin(values), std::cend(values), T {0});\n}\n\nauto sum(const VBReadLikelihoodArray& likelihoods) noexcept\n{\n    using T = VBReadLikelihoodArray::BaseType::value_type;\n    return std::accumulate(std::cbegin(likelihoods), std::cend(likelihoods), T {0});\n}\n\ntemplate <typename T1, typename T2>\nauto inner_product(const T1& lhs, const T2& rhs) noexcept\n{\n    assert(std::distance(std::cbegin(lhs), std::cend(lhs)) == std::distance(std::cbegin(rhs), std::cend(rhs)));\n    using T = typename T1::value_type;\n    return std::inner_product(std::cbegin(lhs), std::cend(lhs), std::cbegin(rhs), T {0});\n}\n\ntemplate <typename T>\nauto dirichlet_expectation_log(const std::vector<T>& concentrations)\n{\n    std::vector<T> result(concentrations.size());\n    if (concentrations.size() > 1) {\n        using boost::math::digamma;\n        const auto digamma_alpha_0 = digamma(sum(concentrations));\n        std::transform(std::cbegin(concentrations), std::cend(concentrations), std::begin(result),\n                       [=] (auto alpha) { return digamma(alpha) - digamma_alpha_0; });\n    }\n    return result;\n}\n\ntemplate <typename T>\nT log_sum_exp(const std::vector<T>& logs)\n{\n    return maths::log_sum_exp(logs);\n}\n\nbool all_equal_sizes(const VariationalBayesMixtureMixtureModel::MixtureConcentrationVector& concentrations) noexcept\n{\n    const auto size_unequal = [] (const auto& lhs, const auto& rhs) { return lhs.size() != rhs.size(); };\n    return std::adjacent_find(std::cbegin(concentrations), std::end(concentrations), size_unequal) == std::cend(concentrations);\n}\n\n} // namespace\n\nVariationalBayesMixtureMixtureModel::PointInferences\nVariationalBayesMixtureMixtureModel::evaluate(const LogProbabilityVector& genotype_log_priors,\n                                              const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                              const ExpandedHaplotypeLikelihoodMatrix& expanded_log_likelihoods,\n                                              const GroupOptionalLogPriorArray& group_log_priors,\n                                              const GroupConcentrationVector& prior_group_concentrations,\n                                              const MixtureConcentrationArray& prior_mixture_concentrations,\n                                              LogProbabilityVector genotype_log_posteriors) const\n{\n    Latents latents {};\n    latents.genotype_log_posteriors = std::move(genotype_log_posteriors);\n    latents.genotype_posteriors = exp(latents.genotype_log_posteriors);\n    latents.group_concentrations = prior_group_concentrations;\n    latents.mixture_concentrations = prior_mixture_concentrations;\n    latents.group_responsibilities = init_responsibilities(group_log_priors, prior_group_concentrations, prior_mixture_concentrations,\n                                                           latents.genotype_posteriors, log_likelihoods);\n    latents.component_responsibilities = init_responsibilities(prior_group_concentrations, prior_mixture_concentrations,\n                                                               latents.genotype_posteriors, latents.group_responsibilities, expanded_log_likelihoods);\n    auto prev_evidence = std::numeric_limits<double>::lowest();\n    for (unsigned i {0}; i < options_.max_iterations; ++i) {\n        update_genotype_log_posteriors(latents.genotype_log_posteriors, genotype_log_priors,\n                                       latents.group_responsibilities, latents.component_responsibilities,\n                                       log_likelihoods);\n        exp(latents.genotype_log_posteriors, latents.genotype_posteriors);\n        update_group_concentrations(latents.group_concentrations, prior_group_concentrations, latents.group_responsibilities);\n        update_mixture_concentrations(latents.mixture_concentrations, prior_mixture_concentrations, latents.component_responsibilities);\n        auto curr_evidence = calculate_evidence(prior_group_concentrations, latents.group_concentrations,\n                                                prior_mixture_concentrations, latents.mixture_concentrations,\n                                                genotype_log_priors, latents.genotype_log_posteriors, latents.genotype_posteriors,\n                                                group_log_priors, latents.group_responsibilities, latents.component_responsibilities,\n                                                log_likelihoods);\n//        assert(curr_evidence + options_.epsilon >= prev_evidence);\n        if (curr_evidence <= prev_evidence || (curr_evidence - prev_evidence) < options_.epsilon) {\n            prev_evidence = curr_evidence;\n            break;\n        }\n        prev_evidence = curr_evidence;\n        update_responsibilities(latents.group_responsibilities, group_log_priors,latents.group_concentrations,\n                                latents.mixture_concentrations, latents.genotype_posteriors,\n                                latents.component_responsibilities, log_likelihoods);\n        update_responsibilities(latents.component_responsibilities, latents.group_concentrations, latents.mixture_concentrations,\n                                latents.genotype_posteriors, latents.group_responsibilities, expanded_log_likelihoods);\n    }\n    return {std::move(latents), prev_evidence};\n}\n\nnamespace {\n\ntemplate <typename ForwardIterator>\nstd::size_t max_element_index(ForwardIterator first, ForwardIterator last)\n{\n    return std::distance(first, std::max_element(first, last));\n}\n\ntemplate <typename Range>\nstd::size_t max_element_index(const Range& values)\n{\n    return max_element_index(std::cbegin(values), std::cend(values));\n}\n\n} // namespace\n\nVariationalBayesMixtureMixtureModel::GroupResponsibilityVector\nVariationalBayesMixtureMixtureModel::init_responsibilities(const GroupOptionalLogPriorArray& group_log_priors,\n                                                           const GroupConcentrationVector& group_concentrations,\n                                                           const MixtureConcentrationArray& mixture_concentrations,\n                                                           const ProbabilityVector& genotype_priors,\n                                                           const HaplotypeLikelihoodMatrix& log_likelihoods) const\n{\n    const auto S = log_likelihoods.size();\n    const auto T = group_concentrations.size();\n    GroupResponsibilityVector result(S, Sigma(T));\n    const auto G = genotype_priors.size();\n    const auto ln_ex_psi = dirichlet_expectation_log(group_concentrations);\n    std::size_t max_K {0};\n    for (std::size_t s {0}; s < S; ++s) {\n        for (std::size_t t {0}; t < T; ++t) {\n            max_K = std::max(max_K, mixture_concentrations[s][t].size());\n        }\n    }\n    const auto max_genotype_prior_idx = max_element_index(genotype_priors);\n    ComponentResponsibilityVector approx_taus(max_K);\n    for (std::size_t s {0}; s < S; ++s) {\n        const auto N = log_likelihoods[s][0][0][0].size(); // num reads\n        for (auto& tau : approx_taus) tau.resize(N);\n        for (std::size_t t {0}; t < T; ++t) {\n            result[s][t] = ln_ex_psi[t];\n            if (group_log_priors[s]) result[s][t] += (*group_log_priors[s])[t];\n            const auto ln_ex_pi = dirichlet_expectation_log(mixture_concentrations[s][t]);\n            const auto K = mixture_concentrations[s][t].size();\n            // Approximate tau assuming p(t) = 1\n            Tau approx_tau(K);\n            for (std::size_t n {0}; n < N; ++n) {\n                for (std::size_t k {0}; k < K; ++k) {\n                    approx_tau[k] = ln_ex_pi[k] + log_likelihoods[s][max_genotype_prior_idx][t][k][n];\n                }\n                maths::normalise_exp(approx_tau);\n                for (std::size_t k {0}; k < K; ++k) {\n                    approx_taus[k][n] = approx_tau[k];\n                }\n            }\n            for (std::size_t k {0}; k < K; ++k) {\n                for (std::size_t g {0}; g < G; ++g) {\n                    result[s][t] += genotype_priors[g] * inner_product(approx_taus[k], log_likelihoods[s][g][t][k]);\n                }\n            }\n        }\n        maths::normalise_exp(result[s]);\n    }\n    return result;\n}\n\nvoid\nVariationalBayesMixtureMixtureModel::update_responsibilities(GroupResponsibilityVector& result,\n                                                             const GroupOptionalLogPriorArray& group_log_priors,\n                                                             const GroupConcentrationVector& group_concentrations,\n                                                             const MixtureConcentrationArray& mixture_concentrations,\n                                                             const ProbabilityVector& genotype_posteriors,\n                                                             const ComponentResponsibilityMatrix& component_responsibilities,\n                                                             const HaplotypeLikelihoodMatrix& log_likelihoods) const\n{\n    const auto T = group_concentrations.size();\n    const auto S = log_likelihoods.size();\n    const auto G = genotype_posteriors.size();\n    const auto ln_ex_psi = dirichlet_expectation_log(group_concentrations);\n    for (std::size_t s {0}; s < S; ++s) {\n        for (std::size_t t {0}; t < T; ++t) {\n            const auto max_K = component_responsibilities[s][t].size();\n            result[s][t] = ln_ex_psi[t];\n            if (group_log_priors[s]) result[s][t] += (*group_log_priors[s])[t];\n            const auto ln_ex_pi = dirichlet_expectation_log(mixture_concentrations[s][t]);\n            const auto K = ln_ex_pi.size();\n            result[s][t] += sum(ln_ex_pi);\n            for (std::size_t k {0}; k < max_K; ++k) {\n                for (std::size_t g {0}; g < G; ++g) {\n                    if (k < K) {\n                        result[s][t] += genotype_posteriors[g] * inner_product(component_responsibilities[s][t][k], log_likelihoods[s][g][t][k]);\n                    } else {\n                        result[s][t] += genotype_posteriors[g] * inner_product(component_responsibilities[s][t][k], log_likelihoods[s][g][t][0]);\n                    }\n                }\n            }\n        }\n        maths::normalise_exp(result[s]);\n    }\n}\n\nVariationalBayesMixtureMixtureModel::ComponentResponsibilityMatrix\nVariationalBayesMixtureMixtureModel::init_responsibilities(const GroupConcentrationVector& group_concentrations,\n                                                           const MixtureConcentrationArray& mixture_concentrations,\n                                                           const ProbabilityVector& genotype_priors,\n                                                           const GroupResponsibilityVector& group_responsibilities,\n                                                           const ExpandedHaplotypeLikelihoodMatrix& log_likelihoods) const\n{\n    const auto S = log_likelihoods.size();\n    const auto T = group_concentrations.size();\n    std::size_t K {0};\n    for (std::size_t s {0}; s < S; ++s) {\n        for (std::size_t t {0}; t < T; ++t) {\n            K = std::max(K, mixture_concentrations[s][t].size());\n        }\n    }\n    ComponentResponsibilityMatrix result(S, ComponentResponsibilityVectorArray(T, ComponentResponsibilityVector(K)));\n    for (std::size_t s {0}; s < S; ++s) {\n        const auto N = log_likelihoods[s][0][0].size();\n        for (std::size_t t {0}; t < T; ++t) {\n            for (std::size_t k {0}; k < K; ++k) {\n                result[s][t][k].resize(N);\n            }\n        }\n    }\n    update_responsibilities(result, group_concentrations, mixture_concentrations,\n                            genotype_priors, group_responsibilities, log_likelihoods);\n    return result;\n}\n\nnamespace {\n\nauto inner_product(const VariationalBayesMixtureMixtureModel::ProbabilityVector& genotype_posteriors,\n                   const VariationalBayesMixtureMixtureModel::GenotypeCombinationLikelihoodVector& log_likelihoods,\n                   const std::size_t t, const std::size_t k, const std::size_t n) noexcept\n{\n    ProbabilityVector::value_type result {0};\n    const auto G = genotype_posteriors.size();\n    for (std::size_t g {0}; g < G; ++g) {\n        result += genotype_posteriors[g] * log_likelihoods[g][t][k][n];\n    }\n    return result;\n}\n\n} // namespace\n\nvoid\nVariationalBayesMixtureMixtureModel::update_responsibilities(ComponentResponsibilityMatrix& result,\n                                                             const GroupConcentrationVector& group_concentrations,\n                                                             const MixtureConcentrationArray& mixture_concentrations,\n                                                             const ProbabilityVector& genotype_posteriors,\n                                                             const GroupResponsibilityVector& group_responsibilities,\n                                                             const ExpandedHaplotypeLikelihoodMatrix& log_likelihoods) const\n{\n    const auto T = group_concentrations.size();\n    const auto S = log_likelihoods.size();\n    const auto max_K = result[0][0].size();\n    std::vector<float> float_genotype_posteriors {std::cbegin(genotype_posteriors), std::cend(genotype_posteriors)};\n    for (std::size_t s {0}; s < S; ++s) {\n        const auto N = log_likelihoods[s][0][0].size();\n        for (std::size_t t {0}; t < T; ++t) {\n            const auto ln_exp_pi = dirichlet_expectation_log(mixture_concentrations[s][t]);\n            const auto K = ln_exp_pi.size();\n            for (std::size_t k {0}; k < max_K; ++k) {\n                for (std::size_t n {0}; n < N; ++n) {\n                    if (t == 0) result[s][t][k][n] = 0;\n                    if (k < K) {\n                        //result[s][t][k][n] += ln_exp_pi[k] + inner_product(genotype_posteriors, log_likelihoods[s], t, k, n);\n                        result[s][t][k][n] += ln_exp_pi[k] + inner_product(float_genotype_posteriors, log_likelihoods[s][t][k][n]);\n                    } else {\n                        result[s][t][k][n] = options_.null_log_probability;\n                    }\n                }\n            }\n            std::vector<double> ln_rho(max_K);\n            for (std::size_t n {0}; n < N; ++n) {\n                for (std::size_t k {0}; k < max_K; ++k) {\n                    ln_rho[k] = result[s][t][k][n];\n                }\n                const auto ln_rho_norm = log_sum_exp(ln_rho);\n                for (std::size_t k {0}; k < max_K; ++k) {\n                    result[s][t][k][n] = std::exp(ln_rho[k] - ln_rho_norm);\n                }\n            }\n        }\n    }\n}\n\nvoid\nVariationalBayesMixtureMixtureModel::update_genotype_log_posteriors(LogProbabilityVector& result,\n                                                                    const LogProbabilityVector& genotype_log_priors,\n                                                                    const GroupResponsibilityVector& group_responsibilities,\n                                                                    const ComponentResponsibilityMatrix& component_responsibilities,\n                                                                    const HaplotypeLikelihoodMatrix& log_likelihoods) const\n{\n    for (std::size_t g {0}; g < genotype_log_priors.size(); ++g) {\n        result[g] = genotype_log_priors[g] + marginalise(group_responsibilities, component_responsibilities, log_likelihoods, g);\n    }\n    maths::normalise_logs(result);\n}\n\nVariationalBayesMixtureMixtureModel::LogProbability\nVariationalBayesMixtureMixtureModel::marginalise(const GroupResponsibilityVector& group_responsibilities,\n                                                 const ComponentResponsibilityMatrix& component_responsibilities,\n                                                 const HaplotypeLikelihoodMatrix& log_likelihoods,\n                                                 const std::size_t g) const noexcept\n{\n    const auto T = group_responsibilities.front().size();\n    const auto S = component_responsibilities.size();\n    LogProbability result {0};\n    for (std::size_t s {0}; s < S; ++s) {\n        for (std::size_t t {0}; t < T; ++t) {\n            result += group_responsibilities[s][t] * marginalise(component_responsibilities[s][t], log_likelihoods[s][g][t]);\n        }\n    }\n    return result;\n}\n\nVariationalBayesMixtureMixtureModel::LogProbability\nVariationalBayesMixtureMixtureModel::marginalise(const ComponentResponsibilityVector& responsibilities,\n                                                 const HaplotypeLikelihoodVector& log_likelihoods) const noexcept\n{\n    const auto K = log_likelihoods.size();\n    const auto max_K = responsibilities.size();\n    assert(K <= max_K);\n    LogProbability result {0};\n    for (std::size_t k {0}; k < max_K; ++k) {\n        if (k < K) {\n            result += inner_product(responsibilities[k], log_likelihoods[k]);\n        } else {\n            result += inner_product(responsibilities[k], log_likelihoods[0]);\n        }\n    }\n    return result;\n}\n\nvoid\nVariationalBayesMixtureMixtureModel::update_group_concentrations(GroupConcentrationVector& result,\n                                                                 const GroupConcentrationVector& prior_group_concentrations,\n                                                                 const GroupResponsibilityVector& group_responsibilities) const\n{\n    assert(result.size() == prior_group_concentrations.size());\n    const auto T = prior_group_concentrations.size();\n    const auto S = group_responsibilities.size();\n    for (std::size_t t {0}; t < T; ++t) {\n        result[t] = prior_group_concentrations[t];\n        for (std::size_t s {0}; s < S; ++s) {\n            result[t] += group_responsibilities[s][t];\n        }\n    }\n}\n\nvoid\nVariationalBayesMixtureMixtureModel::update_mixture_concentrations(MixtureConcentrationArray& result,\n                                                                   const MixtureConcentrationArray& prior_mixture_concentrations,\n                                                                   const ComponentResponsibilityMatrix& component_responsibilities) const\n{\n    const auto S = result.size();\n    const auto T = result.front().size();\n    for (std::size_t s {0}; s < S; ++s) {\n        for (std::size_t t {0}; t < T; ++t) {\n            const auto K = prior_mixture_concentrations[s][t].size();\n            for (std::size_t k {0}; k < K; ++k) {\n                result[s][t][k] = prior_mixture_concentrations[s][t][k] + sum(component_responsibilities[s][t][k]);\n            }\n        }\n    }\n}\n\nnamespace {\n\ntemplate <typename T>\nauto shannon_entropy(const std::vector<T>& probabilities) noexcept\n{\n    return -std::accumulate(std::cbegin(probabilities), std::cend(probabilities), T {0},\n                            [] (const auto curr, const auto p) noexcept { return curr + (p > 0 ? p * std::log(p) : 0.0); });\n}\n\ntemplate <typename T>\nauto shannon_entropy(const std::vector<std::vector<T>>& probabilities) noexcept\n{\n    return std::accumulate(std::cbegin(probabilities), std::cend(probabilities), T {0},\n                           [] (const auto curr, const auto& ps) noexcept { return curr + shannon_entropy(ps); });\n}\n\n} // namespace\n\ndouble\nVariationalBayesMixtureMixtureModel::calculate_evidence(const GroupConcentrationVector& prior_group_concentrations,\n                                                        const GroupConcentrationVector& posterior_group_concentrations,\n                                                        const MixtureConcentrationArray& prior_mixture_concentrations,\n                                                        const MixtureConcentrationArray& posterior_mixture_concentrations,\n                                                        const LogProbabilityVector& genotype_log_priors,\n                                                        const LogProbabilityVector& genotype_log_posteriors,\n                                                        const ProbabilityVector& genotype_posteriors,\n                                                        const GroupOptionalPriorArray& group_log_priors,\n                                                        const GroupResponsibilityVector& group_responsibilities,\n                                                        const ComponentResponsibilityMatrix& component_responsibilities,\n                                                        const HaplotypeLikelihoodMatrix& log_likelihoods) const\n{\n    const auto G = genotype_log_priors.size();\n    const auto S = prior_mixture_concentrations.size();\n    const auto T = group_responsibilities.front().size();\n    double result {0};\n    for (std::size_t g {0}; g < G; ++g) {\n        auto w = genotype_log_priors[g] - genotype_log_posteriors[g];\n        for (std::size_t s {0}; s < S; ++s) {\n            double ss {0};\n            for (std::size_t t {0}; t < T; ++t) {\n                ss += group_responsibilities[s][t] * marginalise(component_responsibilities[s][t], log_likelihoods[s][g][t]);\n            }\n            w += ss;\n        }\n        result += genotype_posteriors[g] * w;\n    }\n    for (std::size_t s {0}; s < S; ++s) {\n        result += shannon_entropy(group_responsibilities[s]);\n        for (std::size_t t {0}; t < T; ++t) {\n            result += group_responsibilities[s][t] * shannon_entropy(component_responsibilities[s][t]);\n            result += group_responsibilities[s][t] * (maths::log_beta(posterior_mixture_concentrations[s][t]) - maths::log_beta(prior_mixture_concentrations[s][t]));\n        }\n        if (group_log_priors[s]) {\n            auto sigma_expected_ln_norm = maths::log_each_copy(group_responsibilities[s]);\n            for (std::size_t t {0}; t < T; ++t) {\n                sigma_expected_ln_norm[t] += (*group_log_priors[s])[t];\n            }\n            result += maths::log_sum_exp(sigma_expected_ln_norm);\n        }\n    }\n    result += maths::log_beta(posterior_group_concentrations) - maths::log_beta(prior_group_concentrations);    \n    return result;\n}\n\nnamespace {\n\ntemplate <typename Range>\nvoid check_normalisation(Range& probabilities) noexcept\n{\n    const auto mass = std::accumulate(std::cbegin(probabilities), std::cend(probabilities), 0.0);\n    if (mass > 1.0) for (auto& p : probabilities) p /= mass;\n}\n\n} // namespace\n\nvoid\nVariationalBayesMixtureMixtureModel::compute_evidence_weighted_latents(ProbabilityVector& genotype_posteriors,\n                                                                       GroupResponsibilityVector& group_responsibilities,\n                                                                       const std::vector<PointInferences>& latents) const\n{\n    assert(!latents.empty());\n    const auto num_genotypes = latents.front().latents.genotype_posteriors.size();\n    std::vector<std::size_t> map_genotypes(num_genotypes, latents.size());\n    for (std::size_t i {0}; i < latents.size(); ++i) {\n        const auto map_genotype_idx = max_element_index(latents[i].latents.genotype_posteriors);\n        if (map_genotypes[map_genotype_idx] == latents.size()\n         || latents[i].approx_log_evidence > latents[map_genotypes[map_genotype_idx]].approx_log_evidence) {\n            map_genotypes[map_genotype_idx] = i;\n        }\n    }\n    std::vector<std::size_t> modes {};\n    modes.reserve(latents.size());\n    for (std::size_t g {0}; g < num_genotypes; ++g) {\n        if (map_genotypes[g] < latents.size()) {\n            modes.push_back(map_genotypes[g]);\n        }\n    }\n    std::vector<double> mode_weights(modes.size());\n    std::transform(std::cbegin(modes), std::cend(modes), std::begin(mode_weights),\n                   [&] (auto mode) { return latents[mode].approx_log_evidence; });\n    maths::normalise_exp(mode_weights);\n    genotype_posteriors.resize(num_genotypes);\n    const auto num_samples = latents.front().latents.group_responsibilities.size();\n    const auto num_groups = latents.front().latents.group_responsibilities.front().size();\n    group_responsibilities.resize(num_samples, Sigma(num_groups));\n    for (std::size_t i {0}; i < modes.size(); ++i) {\n        const auto mode_weight = mode_weights[i];\n        const auto& mode_genotype_posteriors = latents[modes[i]].latents.genotype_posteriors;\n        std::transform(std::cbegin(mode_genotype_posteriors), std::cend(mode_genotype_posteriors),\n                       std::cbegin(genotype_posteriors), std::begin(genotype_posteriors),\n                       [mode_weight] (auto seed_posterior, auto curr_posterior) {\n                           return curr_posterior + mode_weight * seed_posterior;\n                       });\n        const auto& mode_group_responsabilities = latents[modes[i]].latents.group_responsibilities;\n        for (std::size_t s {0}; s < num_samples; ++s) {\n            for (std::size_t t {0}; t < num_groups; ++t) {\n                group_responsibilities[s][t] += mode_weight * mode_group_responsabilities[s][t];\n            }\n        }\n    }\n    check_normalisation(genotype_posteriors);\n    for (auto& responsibilities : group_responsibilities)  check_normalisation(responsibilities);\n}\n\nvoid VariationalBayesMixtureMixtureModel::print_concentrations(const GroupConcentrationVector& concentrations) const\n{\n    for (std::size_t t {0}; t < concentrations.size(); ++t) {\n        std::cout << \"t: \" << t << \" = \" << concentrations[t] << std::endl;\n    }\n}\n\nvoid VariationalBayesMixtureMixtureModel::print_concentrations(const MixtureConcentrationArray& concentrations) const\n{\n    for (std::size_t s {0}; s < concentrations.size(); ++s) {\n        for (std::size_t t {0}; t < concentrations[s].size(); ++t) {\n            for (std::size_t k {0}; k < concentrations[s][t].size(); ++k) {\n                std::cout << \"s: \" << s << \" t: \" << t << \" k: \" << k << \" = \" << concentrations[s][t][k] << std::endl;\n            }\n        }\n    }\n}\n\nvoid VariationalBayesMixtureMixtureModel::print(const ProbabilityVector& probabilities) const\n{\n    for (std::size_t g {0}; g < probabilities.size(); ++g) {\n        std::cout << \"g: \" << g << \" = \" << probabilities[g] << std::endl;\n    }\n}\n\nvoid VariationalBayesMixtureMixtureModel::print(const GroupResponsibilityVector& responsibilities) const\n{\n    for (std::size_t s {0}; s < responsibilities.size(); ++s) {\n        for (std::size_t t {0}; t < responsibilities[s].size(); ++t) {\n            std::cout << \"s: \" << s << \" t: \" << t << \" = \" << responsibilities[s][t] << std::endl;\n        }\n    }\n}\n\nvoid VariationalBayesMixtureMixtureModel::print(const ComponentResponsibilityMatrix& responsibilities) const\n{\n    for (std::size_t s {0}; s < responsibilities.size(); ++s) {\n        for (std::size_t t {0}; t < responsibilities[s].size(); ++t) {\n            for (std::size_t k {0}; k < responsibilities[s].size(); ++k) {\n                for (std::size_t n {0}; n < responsibilities[s][k].size(); ++n) {\n                    std::cout << \"s: \" << s << \" t: \" << t <<  \" k: \" << k << \" n: \" << n << \" = \" << responsibilities[s][t][k][n] << std::endl;\n                }\n            }\n        }\n    }\n}\n\nvoid VariationalBayesMixtureMixtureModel::print(const HaplotypeLikelihoodMatrix& log_likelihoods) const\n{\n    for (std::size_t s {0}; s < log_likelihoods.size(); ++s) {\n        for (std::size_t g {0}; g < log_likelihoods[s].size(); ++g) {\n            for (std::size_t t {0}; t < log_likelihoods[s][g].size(); ++t) {\n                for (std::size_t k {0}; k < log_likelihoods[s][g][t].size(); ++k) {\n                    for (std::size_t n {0}; n < log_likelihoods[s][g][t][k].size(); ++n) {\n                        std::cout << \"s: \" << s <<  \" g: \" << g << \" t: \" << t << \" k: \" << k\n                                  << \" n: \" << n << \" = \" << log_likelihoods[s][g][t][k][n] << std::endl;\n                    }\n                }\n            }\n        }\n    }\n}\n\n} // namespace model\n} // namespace octopus\n", "meta": {"hexsha": "73eca45c8959f3bab8687248c0f46c622fb87dff", "size": 38629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/core/models/genotype/variational_bayes_mixture_mixture_model.cpp", "max_stars_repo_name": "Schaudge/octopus", "max_stars_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2016-10-03T16:30:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T05:59:32.000Z", "max_issues_repo_path": "src/core/models/genotype/variational_bayes_mixture_mixture_model.cpp", "max_issues_repo_name": "Schaudge/octopus", "max_issues_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 229.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T14:07:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T18:59:58.000Z", "max_forks_repo_path": "src/core/models/genotype/variational_bayes_mixture_mixture_model.cpp", "max_forks_repo_name": "Schaudge/octopus", "max_forks_repo_head_hexsha": "d0cc5d0840aefdfefae5af8595e3330620106054", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 37.0, "max_forks_repo_forks_event_min_datetime": "2016-10-28T22:47:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:28:43.000Z", "avg_line_length": 50.9617414248, "max_line_length": 178, "alphanum_fraction": 0.6086618861, "num_tokens": 8723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521105, "lm_q2_score": 0.3702253995442529, "lm_q1q2_score": 0.2398313540653751}}
{"text": "// BSD 3-Clause License\n//\n// Copyright (c) 2022, Map IV, Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this\n//    list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n//    this list of conditions and the following disclaimer in the documentation\n//    and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its\n//    contributors may be used to endorse or promote products derived from\n//    this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <height_converter/gsigeo.hpp>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cmath>\n\n#include <boost/algorithm/string.hpp>\n\nnamespace height_converter\n{\n\nstd::vector<std::string> split(std::string input, char delimiter)\n{\n  std::istringstream stream(input);\n  std::string field;\n  std::vector<std::string> result;\n\n  while (std::getline(stream, field, delimiter))\n  {\n    if (field != std::string(\" \") && !field.empty() && field != \"\\n\" && field != \"\\r\")\n      result.push_back(field);\n  }\n  return result;\n}\n\nGSIGEO2011::GSIGEO2011()\n{\n}\n\nGSIGEO2011::~GSIGEO2011()\n{\n}\n\nvoid GSIGEO2011::loadGeoidMap(const std::string& geoid_file)\n{\n  std::ifstream ifs(geoid_file);\n  if (!ifs)\n  {\n    std::cerr << \"Error: Cannot open Geoid data file: \" << geoid_file << std::endl;\n    exit(2);\n  }\n\n  geoid_map_.reserve(row_size_);\n  for (int i = 0; i < row_size_; i++)\n  {\n    geoid_map_[i].reserve(column_size_);\n  }\n\n  std::string curr_line;\n  // Skip header line\n  std::getline(ifs, curr_line);\n\n  int i = 0, j = 0;\n\n  while (std::getline(ifs, curr_line))\n  {\n    std::vector<std::string> str_vec = split(curr_line, ' ');\n\n    for (int k = 0; k < str_vec.size(); k++)\n    {\n      geoid_map_[i][j] = std::stod(str_vec[k]);\n      j++;\n      \n    }\n    if (j == column_size_) \n    {\n      j = 0;\n      i++;\n    }\n  }\n  is_geoid_loaded_ = true;\n}\n\ndouble GSIGEO2011::getGeoid(const double& lat, const double& lon)\n{\n  if (!is_geoid_loaded_)\n  {\n    std::cerr << \"Error: Geoid map is not loaded\" << std::endl;\n    exit(1);\n  }\n  const double lat_min = 20;\n  const double lon_min = 120;\n  const double d_lat = 1.0 / 60.0;\n  const double d_lon = 1.5 / 60.0;\n\n  const int i_lat = std::floor((lat - lat_min) / d_lat);\n  const int i_lon = std::floor((lon - lon_min) / d_lon);\n  const int j_lat = i_lat + 1;\n  const int j_lon = i_lon + 1;\n\n  // const double t = (((lat - lat_min) / d_lat) - i_lat) / d_lat;\n  // const double u = (((lon - lon_min) / d_lon) - i_lon) / d_lon;\n  const double t = (lat - (lat_min + i_lat * d_lat)) / d_lat;\n  const double u = (lon - (lon_min + i_lon * d_lon)) / d_lon;\n\n  if (i_lat < 0 || i_lat >= row_size_ - 1 || i_lon < 0 || i_lon >= column_size_ - 1)\n  {\n    std::cerr << \"Error: latitude/longitude is out of range (20~50, 120~150)\" << std::endl;\n    std::cerr << (lat, lon) << std::endl;\n    exit(1);\n  }\n\n  if (geoid_map_[i_lat][i_lon] == 999 || geoid_map_[i_lat][j_lon] == 999 || geoid_map_[j_lat][i_lon] == 999 || geoid_map_[j_lat][j_lon] == 999)\n  {\n    std::cerr << \"Error: Not supported area\" << std::endl;\n    exit(1);\n  }\n\n  double geoid = (1-t)*(1-u)*geoid_map_[i_lat][i_lon] + (1-t)*u*geoid_map_[i_lat][j_lon] + t*(1-u)*geoid_map_[j_lat][i_lon] + t*u*geoid_map_[j_lat][j_lon];\n\n  return geoid;\n}\n}   // namespace height_converter\n", "meta": {"hexsha": "16895b1aa03c2042bf01a92b8fd90693989c1a3d", "size": 4386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gsigeo.cpp", "max_stars_repo_name": "MapIV/height_converter", "max_stars_repo_head_hexsha": "176cf575a0ef42308a90fa7eaad4fea4ac490c88", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-24T07:52:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T11:33:29.000Z", "max_issues_repo_path": "src/gsigeo.cpp", "max_issues_repo_name": "MapIV/height_converter", "max_issues_repo_head_hexsha": "176cf575a0ef42308a90fa7eaad4fea4ac490c88", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gsigeo.cpp", "max_forks_repo_name": "MapIV/height_converter", "max_forks_repo_head_hexsha": "176cf575a0ef42308a90fa7eaad4fea4ac490c88", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2482758621, "max_line_length": 155, "alphanum_fraction": 0.6634746922, "num_tokens": 1258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23976805794376713}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)\n#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)\n#define EACH(e, a) for(auto&& e : a)\n#define ALL(a) std::begin(a), std::end(a)\n#define RALL(a) std::rbegin(a), std::rend(a)\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n#define INT(x) (static_cast<int>(x))\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = vector<int>;\nusing VI2D = vector<vector<int>>;\n\nconstexpr int INF = 2e9;\nconstexpr double EPS = 1e-10;\nconstexpr double PI = acos(-1.0);\n\nconstexpr int dx[] = {-1, 0, 1, 0};\nconstexpr int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T>\nconstexpr int sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nconstexpr int sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmax(T& m, U x) {\n\tm = max(m, x);\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmin(T& m, U x) {\n\tm = min(m, x);\n}\n\ntemplate <typename T>\nconstexpr T square(T x) {\n\treturn x * x;\n}\n\n// UnionFind(disjoint set)\nclass UnionFind {\n\tstd::vector<size_t> parents;\n\tstd::vector<size_t> rank;\n\tstd::vector<size_t> tree_size;\n\n\tpublic:\n\tUnionFind(size_t size) : parents(size), rank(size, 0), tree_size(size, 1) {\n\t\tstd::iota(this->parents.begin(), this->parents.end(), 0);\n\t}\n\n\t// 併合\n\tbool merge(size_t a, size_t b) {\n\t\tsize_t ar = this->root(a);\n\t\tsize_t br = this->root(b);\n\t\tif(ar == br) {\n\t\t\treturn false;\n\t\t}\n\t\tif(this->rank[ar] < this->rank[br]) {\n\t\t\tstd::swap(ar, br);\n\t\t}\n\t\tif(this->rank[ar] == this->rank[br]) {\n\t\t\tthis->rank[ar]++;\n\t\t}\n\t\tthis->tree_size[ar] = this->tree_size[br] =\n\t\t\tthis->tree_size[ar] + this->tree_size[br];\n\t\treturn this->parents[br] = ar;\n\t}\n\tbool unite(size_t a, size_t b) { return this->merge(a, b); }\n\n\t// 同集合か判定\n\tbool is_same(size_t a, size_t b) { return this->root(a) == this->root(b); }\n\tbool is_union(size_t a, size_t b) { return this->is_same(a, b); }\n\tsize_t size(size_t n) {\n\t\tthis->root(n);\n\t\treturn this->tree_size[n];\n\t}\n\n\tprivate:\n\tsize_t root(int n) {\n\t\tif(this->parents[n] == n) {\n\t\t\treturn n;\n\t\t}\n\n\t\tsize_t r = this->root(this->parents[n]);\n\t\tthis->parents[n] = r;\n\t\tthis->tree_size[n] = this->tree_size[r];\n\t\treturn r;\n\t}\n};\n\nint main() {\n\tint n, m, k;\n\tcin >> n >> m >> k;\n\tVI a(m);\n\tVI b(m);\n\tVI2D friends(n);\n\tREP(i, m) {\n\t\tcin >> a[i] >> b[i];\n\t\tfriends[a[i] - 1].push_back(b[i] - 1);\n\t\tfriends[b[i] - 1].push_back(a[i] - 1);\n\t}\n\tVI c(k);\n\tVI d(k);\n\tVI2D blocks(n);\n\tREP(i, k) {\n\t\tcin >> c[i] >> d[i];\n\t\tblocks[c[i] - 1].push_back(d[i] - 1);\n\t\tblocks[d[i] - 1].push_back(c[i] - 1);\n\t}\n\tUnionFind uf(n);\n\tREP(i, m) { uf.merge(a[i] - 1, b[i] - 1); }\n\tREP(i, n) {\n\t\tint size = uf.size(i) - 1;\n\t\tEACH(e, friends[i]) {\n\t\t\tif(uf.is_same(i, e)) {\n\t\t\t\tsize--;\n\t\t\t}\n\t\t}\n\t\tEACH(e, blocks[i]) {\n\t\t\tif(uf.is_same(i, e)) {\n\t\t\t\tsize--;\n\t\t\t}\n\t\t}\n\t\tcout << size << ' ';\n\t}\n\tcout << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "8b49ce10c1cb0ca3943717128e39df6f0994c9f9", "size": 3340, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/ABC157/D.cpp", "max_stars_repo_name": "arlechann/atcoder", "max_stars_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AtCoder/ABC157/D.cpp", "max_issues_repo_name": "arlechann/atcoder", "max_issues_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AtCoder/ABC157/D.cpp", "max_forks_repo_name": "arlechann/atcoder", "max_forks_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.875, "max_line_length": 76, "alphanum_fraction": 0.5925149701, "num_tokens": 1163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23976805794376713}}
{"text": "#pragma once\n\n#include <algorithm>\n#include <vector>\n#include <Eigen/Dense>\n#include \"genetic_code.hpp\"\n#include \"xlorad.hpp\"\n\nnamespace lorad {\n\n    class QMatrix {\n\n        public:\n            typedef std::vector<double>             freq_xchg_t;\n            typedef std::shared_ptr<freq_xchg_t>    freq_xchg_ptr_t;\n            typedef double                          omega_t;\n            typedef std::shared_ptr<omega_t>        omega_ptr_t;\n            typedef boost::shared_ptr<QMatrix>      SharedPtr;\n\n                                                    QMatrix();\n            virtual                                 ~QMatrix();\n        \n            virtual void                            clear() = 0;\n\n            virtual void                            setEqualStateFreqs(freq_xchg_ptr_t freq_ptr) = 0;\n            virtual void                            setStateFreqsSharedPtr(freq_xchg_ptr_t freq_ptr) = 0;\n            virtual void                            setStateFreqs(freq_xchg_t & freq) = 0;\n            virtual freq_xchg_ptr_t                 getStateFreqsSharedPtr() = 0;\n            virtual const double *                  getStateFreqs() const = 0;\n            void                                    fixStateFreqs(bool is_fixed);\n            bool                                    isFixedStateFreqs() const;\n\n            virtual void                            setEqualExchangeabilities(freq_xchg_ptr_t xchg_ptr) = 0;\n            virtual void                            setExchangeabilitiesSharedPtr(freq_xchg_ptr_t xchg) = 0;\n            virtual void                            setExchangeabilities(freq_xchg_t & xchg) = 0;\n            virtual freq_xchg_ptr_t                 getExchangeabilitiesSharedPtr() = 0;\n            virtual const double *                  getExchangeabilities() const = 0;\n            void                                    fixExchangeabilities(bool is_fixed);\n            bool                                    isFixedExchangeabilities() const;\n\n            virtual void                            setOmegaSharedPtr(omega_ptr_t omega) = 0;\n            virtual void                            setOmega(omega_t omega) = 0;\n            virtual omega_ptr_t                     getOmegaSharedPtr() = 0;\n            virtual double                          getOmega() const = 0;\n            void                                    fixOmega(bool is_fixed);\n            bool                                    isFixedOmega() const;\n\n#if defined(POLGSS)\n            virtual void                            setStateFreqRefDistParamsSharedPtr(QMatrix::freq_xchg_ptr_t freq_params_ptr) = 0;\n            virtual std::vector<double>             getStateFreqRefDistParamsVect() const = 0;\n            virtual void                            setExchangeabilityRefDistParamsSharedPtr(QMatrix::freq_xchg_ptr_t xchg_params_ptr) = 0;\n            virtual std::vector<double>             getExchangeabilityRefDistParamsVect() const = 0;\n#endif\n\n            virtual const double *                  getEigenvectors() const = 0;\n            virtual const double *                  getInverseEigenvectors() const = 0;\n            virtual const double *                  getEigenvalues() const = 0;\n\n            void                                    setActive(bool activate);\n        \n        protected:\n        \n            virtual void                            recalcRateMatrix() = 0;\n            void                                    normalizeFreqsOrExchangeabilities(freq_xchg_ptr_t v);\n\n            bool                                    _is_active;\n            bool                                    _state_freqs_fixed;\n            bool                                    _exchangeabilities_fixed;\n            bool                                    _omega_fixed;\n\n#if defined(POLGSS)\n            freq_xchg_ptr_t                         _state_freq_refdist;\n            freq_xchg_ptr_t                         _exchangeability_refdist;\n#endif\n    };\n    \n    inline QMatrix::QMatrix() {\n    }\n    \n    inline QMatrix::~QMatrix() {\n    }\n    \n    inline void QMatrix::setActive(bool activate) {\n        _is_active = activate;\n        recalcRateMatrix();\n    }\n\n    inline void QMatrix::clear() {\n        _is_active = false;\n        _state_freqs_fixed = false;\n        _exchangeabilities_fixed = false;\n        _omega_fixed = false;\n    }\n\n    inline void QMatrix::fixStateFreqs(bool is_fixed) {\n        _state_freqs_fixed = is_fixed;\n    }\n    \n    inline void QMatrix::fixExchangeabilities(bool is_fixed) {\n        _exchangeabilities_fixed = is_fixed;\n    }\n    \n    inline void QMatrix::fixOmega(bool is_fixed) {\n        _omega_fixed = is_fixed;\n    }\n    \n    inline bool QMatrix::isFixedStateFreqs() const {\n        return _state_freqs_fixed;\n    }\n    \n    inline bool QMatrix::isFixedExchangeabilities() const {\n        return _exchangeabilities_fixed;\n    }\n    \n    inline bool QMatrix::isFixedOmega() const {\n        return _omega_fixed;\n    }\n    \n    inline void QMatrix::normalizeFreqsOrExchangeabilities(QMatrix::freq_xchg_ptr_t v) {\n        // Be sure elements of v sum to 1.0 and assert that they are all positive\n        double sum_v = std::accumulate(v->begin(), v->end(), 0.0);\n        for (auto & x : *v) {\n            assert(x > 0.0);\n            x /= sum_v;\n        }\n    }\n    \n    class QMatrixNucleotide : public QMatrix {\n\n        public:\n            typedef Eigen::Matrix<double, 4, 4, Eigen::RowMajor>    eigenMatrix4d_t;\n            typedef Eigen::Vector4d                                 eigenVector4d_t;\n        \n                                        QMatrixNucleotide();\n                                        ~QMatrixNucleotide();\n        \n            void                        clear();\n\n            void                        setEqualStateFreqs(freq_xchg_ptr_t freq_ptr);\n            void                        setStateFreqsSharedPtr(freq_xchg_ptr_t freq_ptr);\n            void                        setStateFreqs(freq_xchg_t & freqs);\n            freq_xchg_ptr_t             getStateFreqsSharedPtr();\n            const double *              getStateFreqs() const;\n\n            void                        setEqualExchangeabilities(freq_xchg_ptr_t xchg_ptr);\n            void                        setExchangeabilitiesSharedPtr(freq_xchg_ptr_t xchg_ptr);\n            void                        setExchangeabilities(freq_xchg_t & xchg);\n            freq_xchg_ptr_t             getExchangeabilitiesSharedPtr();\n            const double *              getExchangeabilities() const;\n\n            void                        setOmegaSharedPtr(omega_ptr_t omega_ptr);\n            void                        setOmega(omega_t omega);\n            omega_ptr_t                 getOmegaSharedPtr();\n            double                      getOmega() const;\n\n#if defined(POLGSS)\n            void                        setStateFreqRefDistParamsSharedPtr(QMatrix::freq_xchg_ptr_t freq_params_ptr);\n            std::vector<double>         getStateFreqRefDistParamsVect() const;\n            void                        setExchangeabilityRefDistParamsSharedPtr(QMatrix::freq_xchg_ptr_t xchg_params_ptr);\n            std::vector<double>         getExchangeabilityRefDistParamsVect() const;\n#endif\n\n            const double *              getEigenvectors() const;\n            const double *              getInverseEigenvectors() const;\n            const double *              getEigenvalues() const;\n        \n\n            EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n        \n        protected:\n        \n            virtual void                recalcRateMatrix();\n\n        private:\n        \n            // workspaces for computing eigenvectors/eigenvalues\n            eigenMatrix4d_t             _sqrtPi;\n            eigenMatrix4d_t             _sqrtPiInv;\n            eigenMatrix4d_t             _Q;\n            eigenMatrix4d_t             _eigenvectors;\n            eigenMatrix4d_t             _inverse_eigenvectors;\n            eigenVector4d_t             _eigenvalues;\n\n            freq_xchg_ptr_t             _state_freqs;\n            freq_xchg_ptr_t             _exchangeabilities;\n    };\n    \n    inline QMatrixNucleotide::QMatrixNucleotide() {\n        clear();\n    }\n\n    inline QMatrixNucleotide::~QMatrixNucleotide() {\n    }\n\n    inline void QMatrixNucleotide::clear() {\n        QMatrix::clear();\n\n        QMatrix::freq_xchg_t xchg = {1,1,1,1,1,1};\n        _exchangeabilities = std::make_shared<QMatrix::freq_xchg_t>(xchg);\n\n        QMatrix::freq_xchg_t freq_vect = {0.25, 0.25, 0.25, 0.25};\n        _state_freqs = std::make_shared<QMatrix::freq_xchg_t>(freq_vect);\n        \n#if defined(POLGSS)\n        QMatrix::freq_xchg_t freq_param_vect = {1.0, 1.0, 1.0, 1.0};\n        _state_freq_refdist = std::make_shared<QMatrix::freq_xchg_t>(freq_param_vect);\n        \n        QMatrix::freq_xchg_t xchg_param_vect = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0};\n        _exchangeability_refdist = std::make_shared<QMatrix::freq_xchg_t>(xchg_param_vect);\n#endif\n        \n        recalcRateMatrix();\n    }\n\n    inline QMatrix::freq_xchg_ptr_t QMatrixNucleotide::getExchangeabilitiesSharedPtr() {\n        return _exchangeabilities;\n    }\n    \n    inline QMatrix::freq_xchg_ptr_t QMatrixNucleotide::getStateFreqsSharedPtr() {\n        return _state_freqs;\n    }\n\n    inline QMatrix::omega_ptr_t QMatrixNucleotide::getOmegaSharedPtr() {\n        assert(false);\n        return nullptr;\n    }\n    \n    inline const double * QMatrixNucleotide::getEigenvectors() const {\n        return _eigenvectors.data();\n    }\n    \n    inline const double * QMatrixNucleotide::getInverseEigenvectors() const {\n        return _inverse_eigenvectors.data();\n    }\n    \n    inline const double * QMatrixNucleotide::getEigenvalues() const {\n        return _eigenvalues.data();\n    }\n    \n    inline const double * QMatrixNucleotide::getExchangeabilities() const {\n        return &(*_exchangeabilities)[0];\n    }\n\n    inline const double * QMatrixNucleotide::getStateFreqs() const {\n        return &(*_state_freqs)[0];\n    }\n\n    inline double QMatrixNucleotide::getOmega() const {\n        assert(false);\n        return 0.0;\n    }\n\n    inline void QMatrixNucleotide::setEqualExchangeabilities(QMatrix::freq_xchg_ptr_t xchg_ptr) {\n        _exchangeabilities = xchg_ptr;\n        _exchangeabilities->assign(6, 1.0/6.0);\n        recalcRateMatrix();\n    }\n    \n    inline void QMatrixNucleotide::setExchangeabilitiesSharedPtr(QMatrix::freq_xchg_ptr_t xchg_ptr) {\n        if (xchg_ptr->size() != 6)\n            throw XLorad(boost::format(\"Expecting 6 exchangeabilities and got %d: perhaps you meant to specify a subset data type other than nucleotide\") % xchg_ptr->size());\n        _exchangeabilities = xchg_ptr;\n        normalizeFreqsOrExchangeabilities(_exchangeabilities);\n        recalcRateMatrix();\n    }\n            \n    inline void QMatrixNucleotide::setExchangeabilities(QMatrix::freq_xchg_t & xchg) {\n        if (xchg.size() != 6)\n            throw XLorad(boost::format(\"Expecting 6 exchangeabilities and got %d: perhaps you meant to specify a subset data type other than nucleotide\") % xchg.size());\n        std::copy(xchg.begin(), xchg.end(), _exchangeabilities->begin());\n        recalcRateMatrix();\n    }\n    \n    inline void QMatrixNucleotide::setEqualStateFreqs(QMatrix::freq_xchg_ptr_t freq_ptr) {\n        _state_freqs = freq_ptr;\n        _state_freqs->assign(4, 0.25);\n        recalcRateMatrix();\n    }\n    \n    inline void QMatrixNucleotide::setStateFreqsSharedPtr(QMatrix::freq_xchg_ptr_t freq_ptr) {\n        if (freq_ptr->size() != 4)\n            throw XLorad(boost::format(\"Expecting 4 state frequencies and got %d: perhaps you meant to specify a subset data type other than nucleotide\") % freq_ptr->size());\n        double sum_of_freqs = std::accumulate(freq_ptr->begin(), freq_ptr->end(), 0.0);\n        if (std::fabs(sum_of_freqs - 1.0) > 0.001)\n            throw XLorad(boost::format(\"Expecting sum of 4 state frequencies to be 1, but instead got %g\") % sum_of_freqs);\n        _state_freqs = freq_ptr;\n        recalcRateMatrix();\n    }\n    \n    inline void QMatrixNucleotide::setStateFreqs(QMatrix::freq_xchg_t & freqs) {\n        if (freqs.size() != 4)\n            throw XLorad(boost::format(\"Expecting 4 state frequencies and got %d: perhaps you meant to specify a subset data type other than nucleotide\") % freqs.size());\n        std::copy(freqs.begin(), freqs.end(), _state_freqs->begin());\n        recalcRateMatrix();\n    }\n    \n    inline void QMatrixNucleotide::setOmegaSharedPtr(QMatrix::omega_ptr_t omega_ptr) {\n        assert(false);\n    }\n\n    inline void QMatrixNucleotide::setOmega(QMatrix::omega_t omega) {\n        assert(false);\n    }\n\n#if defined(POLGSS)\n    inline void QMatrixNucleotide::setStateFreqRefDistParamsSharedPtr(QMatrix::freq_xchg_ptr_t freq_params_ptr) {\n        if (freq_params_ptr->size() != 4)\n            throw XLorad(boost::format(\"Expecting 4 state frequency reference distribution parameters and got %d: perhaps you meant to specify a subset data type other than nucleotide\") % freq_params_ptr->size());\n        _state_freq_refdist = freq_params_ptr;\n    }\n    \n    inline std::vector<double> QMatrixNucleotide::getStateFreqRefDistParamsVect() const {\n        return std::vector<double>(_state_freq_refdist->begin(), _state_freq_refdist->end());\n    }\n    \n    inline void QMatrixNucleotide::setExchangeabilityRefDistParamsSharedPtr(QMatrix::freq_xchg_ptr_t xchg_params_ptr) {\n        if (xchg_params_ptr->size() != 6)\n            throw XLorad(boost::format(\"Expecting 6 exchangeability reference distribution parameters and got %d: perhaps you meant to specify a subset data type other than nucleotide\") % xchg_params_ptr->size());\n        _exchangeability_refdist = xchg_params_ptr;\n    }\n    \n    inline std::vector<double> QMatrixNucleotide::getExchangeabilityRefDistParamsVect() const {\n        return std::vector<double>(_exchangeability_refdist->begin(), _exchangeability_refdist->end());\n    }\n#endif\n    \n    inline void QMatrixNucleotide::recalcRateMatrix() {\n        // Must have assigned both _state_freqs and _exchangeabilities to recalculate rate matrix\n        if (!_is_active || !(_state_freqs && _exchangeabilities))\n            return;\n        \n        double piA = (*_state_freqs)[0];\n        double piC = (*_state_freqs)[1];\n        double piG = (*_state_freqs)[2];\n        double piT = (*_state_freqs)[3];\n        \n        Eigen::Map<const Eigen::Array4d> tmp(_state_freqs->data());\n        _sqrtPi = tmp.sqrt().matrix().asDiagonal();\n        _sqrtPiInv = _sqrtPi.inverse();\n\n        assert(_exchangeabilities->size() == 6);\n        double rAC = (*_exchangeabilities)[0];\n        double rAG = (*_exchangeabilities)[1];\n        double rAT = (*_exchangeabilities)[2];\n        double rCG = (*_exchangeabilities)[3];\n        double rCT = (*_exchangeabilities)[4];\n        double rGT = (*_exchangeabilities)[5];\n\n        double inverse_scaling_factor = piA*(rAC*piC + rAG*piG + rAT*piT) + piC*(rAC*piA + rCG*piG + rCT*piT) + piG*(rAG*piA + rCG*piC + rGT*piT) + piT*(rAT*piA + rCT*piC + rGT*piG);\n        double scaling_factor = 1.0/inverse_scaling_factor;\n\n        _Q(0,0) = -scaling_factor*(rAC*piC + rAG*piG + rAT*piT);\n        _Q(0,1) = scaling_factor*rAC*piC;\n        _Q(0,2) = scaling_factor*rAG*piG;\n        _Q(0,3) = scaling_factor*rAT*piT;\n\n        _Q(1,0) = scaling_factor*rAC*piA;\n        _Q(1,1) = -scaling_factor*(rAC*piA + rCG*piG + rCT*piT);\n        _Q(1,2) = scaling_factor*rCG*piG;\n        _Q(1,3) = scaling_factor*rCT*piT;\n\n        _Q(2,0) = scaling_factor*rAG*piA;\n        _Q(2,1) = scaling_factor*rCG*piC;\n        _Q(2,2) = -scaling_factor*(rAG*piA + rCG*piC + rGT*piT);\n        _Q(2,3) = scaling_factor*rGT*piT;\n\n        _Q(3,0) = scaling_factor*rAT*piA;\n        _Q(3,1) = scaling_factor*rCT*piC;\n        _Q(3,2) = scaling_factor*rGT*piG;\n        _Q(3,3) = -scaling_factor*(rAT*piA + rCT*piC + rGT*piG);\n\n        // S is a symmetric matrix\n        eigenMatrix4d_t S = eigenMatrix4d_t(_sqrtPi*_Q*_sqrtPiInv);\n\n        // Can use efficient eigensystem solver because S is symmetric\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix4d> solver(S);\n        if (solver.info() != Eigen::Success) {\n            throw XLorad(\"Error in the calculation of eigenvectors and eigenvalues of the GTR rate matrix\");\n        }\n\n        _eigenvectors           = _sqrtPiInv*solver.eigenvectors();\n        _inverse_eigenvectors   = solver.eigenvectors().transpose()*_sqrtPi;\n        _eigenvalues            = solver.eigenvalues();\n    }\n  \n    class QMatrixCodon : public QMatrix {\n\n        public:\n            typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>      eigenMatrixXd_t;\n            typedef Eigen::VectorXd                                                             eigenVectorXd_t;\n        \n                                        QMatrixCodon(GeneticCode::SharedPtr gcode);\n                                        ~QMatrixCodon();\n        \n            void                        clear();\n\n            void                        setEqualStateFreqs(freq_xchg_ptr_t freq_ptr);\n            void                        setStateFreqsSharedPtr(freq_xchg_ptr_t freq_ptr);\n            void                        setStateFreqs(freq_xchg_t & freqs);\n            freq_xchg_ptr_t             getStateFreqsSharedPtr();\n            const double *              getStateFreqs() const;\n\n            void                        setEqualExchangeabilities(freq_xchg_ptr_t xchg_ptr);\n            void                        setExchangeabilitiesSharedPtr(freq_xchg_ptr_t xchg_ptr);\n            void                        setExchangeabilities(freq_xchg_t & xchg);\n            freq_xchg_ptr_t             getExchangeabilitiesSharedPtr();\n            const double *              getExchangeabilities() const;\n\n            void                        setOmegaSharedPtr(omega_ptr_t omega_ptr);\n            void                        setOmega(omega_t omega);\n            omega_ptr_t                 getOmegaSharedPtr();\n            double                      getOmega() const;\n\n#if defined(POLGSS)\n            void                        setStateFreqRefDistParamsSharedPtr(QMatrix::freq_xchg_ptr_t freq_params_ptr);\n            std::vector<double>         getStateFreqRefDistParamsVect() const;\n            void                        setExchangeabilityRefDistParamsSharedPtr(QMatrix::freq_xchg_ptr_t xchg_params_ptr);\n            std::vector<double>         getExchangeabilityRefDistParamsVect() const;\n#endif\n\n            const double *              getEigenvectors() const;\n            const double *              getInverseEigenvectors() const;\n            const double *              getEigenvalues() const;\n        \n        protected:\n        \n            virtual void                recalcRateMatrix();\n\n        private:\n        \n            // workspaces for computing eigenvectors/eigenvalues\n            eigenMatrixXd_t             _sqrtPi;\n            eigenMatrixXd_t             _sqrtPiInv;\n            eigenMatrixXd_t             _Q;\n            eigenMatrixXd_t             _eigenvectors;\n            eigenMatrixXd_t             _inverse_eigenvectors;\n            eigenVectorXd_t             _eigenvalues;\n\n            freq_xchg_ptr_t             _state_freqs;\n            omega_ptr_t                 _omega;\n\n            std::vector<std::string>    _codons;\n            std::vector<unsigned>       _amino_acids;\n        \n            GeneticCode::SharedPtr      _genetic_code;\n    };\n\n    inline QMatrixCodon::QMatrixCodon(GeneticCode::SharedPtr gcode) {\n        assert(gcode);\n        _genetic_code = gcode;\n        clear();\n    }\n\n    inline QMatrixCodon::~QMatrixCodon() {\n    }\n\n    inline void QMatrixCodon::clear() {\n        QMatrix::clear();\n\n        unsigned nstates = _genetic_code->getNumNonStopCodons();\n        _genetic_code->copyCodons(_codons);\n        _genetic_code->copyAminoAcids(_amino_acids);\n        \n        QMatrix::omega_t omega = 0.1;\n        _omega = std::make_shared<QMatrix::omega_t>(omega);\n        \n        QMatrix::freq_xchg_t freq_vect(nstates, 1./nstates);\n        _state_freqs = std::make_shared<QMatrix::freq_xchg_t>(freq_vect);\n        \n        _sqrtPi.resize(nstates, nstates);\n        _sqrtPiInv.resize(nstates, nstates);\n        _Q.resize(nstates, nstates);\n        _eigenvectors.resize(nstates, nstates);\n        _inverse_eigenvectors.resize(nstates, nstates);\n        _eigenvalues.resize(nstates);\n        \n        recalcRateMatrix();\n    }\n\n    inline QMatrix::freq_xchg_ptr_t QMatrixCodon::getExchangeabilitiesSharedPtr() {\n        assert(false);\n        return nullptr;\n    }\n    \n    inline QMatrix::freq_xchg_ptr_t QMatrixCodon::getStateFreqsSharedPtr() {\n        return _state_freqs;\n    }\n\n    inline QMatrix::omega_ptr_t QMatrixCodon::getOmegaSharedPtr() {\n        return _omega;\n    }\n    \n    inline const double * QMatrixCodon::getEigenvectors() const {\n        return _eigenvectors.data();\n    }\n    \n    inline const double * QMatrixCodon::getInverseEigenvectors() const {\n        return _inverse_eigenvectors.data();\n    }\n    \n    inline const double * QMatrixCodon::getEigenvalues() const {\n        return _eigenvalues.data();\n    }\n    \n    inline const double * QMatrixCodon::getExchangeabilities() const {\n        assert(false);\n        return 0;\n    }\n\n    inline const double * QMatrixCodon::getStateFreqs() const {\n        return &(*_state_freqs)[0];\n    }\n\n    inline double QMatrixCodon::getOmega() const {\n        return *_omega;\n    }\n\n    inline void QMatrixCodon::setEqualExchangeabilities(QMatrix::freq_xchg_ptr_t xchg_ptr) {\n        assert(false);\n    }\n    \n    inline void QMatrixCodon::setExchangeabilitiesSharedPtr(QMatrix::freq_xchg_ptr_t xchg_ptr) {\n        assert(false);\n    }\n    \n    inline void QMatrixCodon::setExchangeabilities(QMatrix::freq_xchg_t & xchg) {\n        assert(false);\n    }\n    \n    inline void QMatrixCodon::setEqualStateFreqs(QMatrix::freq_xchg_ptr_t freq_ptr) {\n        _state_freqs = freq_ptr;\n        unsigned nstates = _genetic_code->getNumNonStopCodons();\n        _state_freqs->assign(nstates, 1./nstates);\n        recalcRateMatrix();\n    }\n    \n    inline void QMatrixCodon::setStateFreqsSharedPtr(QMatrix::freq_xchg_ptr_t freq_ptr) {\n        unsigned nstates = _genetic_code->getNumNonStopCodons();\n        if (freq_ptr->size() != nstates)\n            throw XLorad(boost::format(\"Expecting %d state frequencies and got %d: perhaps you meant to specify a subset data type other than codon\") % nstates % freq_ptr->size());\n        double sum_of_freqs = std::accumulate(freq_ptr->begin(), freq_ptr->end(), 0.0);\n        if (std::fabs(sum_of_freqs - 1.0) > 0.001)\n            throw XLorad(boost::format(\"Expecting sum of codon frequencies to be 1, but instead got %g\") % sum_of_freqs);\n        _state_freqs = freq_ptr;\n        normalizeFreqsOrExchangeabilities(_state_freqs);\n        recalcRateMatrix();\n    }\n    \n    inline void QMatrixCodon::setStateFreqs(QMatrix::freq_xchg_t & freqs) {\n        unsigned nstates = _genetic_code->getNumNonStopCodons();\n        if (freqs.size() != nstates)\n            throw XLorad(boost::format(\"Expecting %d state frequencies and got %d: perhaps you meant to specify a subset data type other than codon\") % nstates % freqs.size());\n        std::copy(freqs.begin(), freqs.end(), _state_freqs->begin());\n        recalcRateMatrix();\n    }\n    \n    inline void QMatrixCodon::setOmegaSharedPtr(QMatrix::omega_ptr_t omega_ptr) {\n        _omega = omega_ptr;\n        recalcRateMatrix();\n    }\n\n    inline void QMatrixCodon::setOmega(QMatrix::omega_t omega) {\n        *_omega = omega;\n        recalcRateMatrix();\n    }\n\n    inline void QMatrixCodon::recalcRateMatrix() {\n        // Must have assigned both _state_freqs and _omega to recalculate rate matrix\n        if (!_is_active || !(_state_freqs && _omega))\n            return;\n        \n        unsigned nstates = _genetic_code->getNumNonStopCodons();\n        assert(_state_freqs->size() == nstates);\n        const double * pi = getStateFreqs();\n        double omega = getOmega();\n        \n        Eigen::Map<const Eigen::ArrayXd> tmp(_state_freqs->data(), nstates);\n        _sqrtPi = tmp.sqrt().matrix().asDiagonal();\n        _sqrtPiInv = _sqrtPi.inverse();\n\n        // Calculate (unscaled) instantaneous rate matrix\n        _Q = Eigen::MatrixXd::Zero(nstates,nstates);\n\n        for (unsigned i = 0; i < nstates-1; i++) {\n            for (unsigned j = i+1; j < nstates; j++) {\n                unsigned diffs = 0;\n                if (_codons[i][0] != _codons[j][0])\n                    diffs++;\n                if (_codons[i][1] != _codons[j][1])\n                    diffs++;\n                if (_codons[i][2] != _codons[j][2])\n                    diffs++;\n                if (diffs == 1) {\n                    bool synonymous = _amino_acids[i] == _amino_acids[j];\n                    _Q(i,j) = (synonymous ? 1.0 : omega)*pi[j];\n                    _Q(j,i) = (synonymous ? 1.0 : omega)*pi[i];\n                    _Q(i,i) -= _Q(i,j);\n                    _Q(j,j) -= _Q(j,i);\n                }\n            }\n        }\n\n        double average_rate = 0.0;\n        for (unsigned i = 0; i < nstates; i++)\n            average_rate -= pi[i]*_Q(i,i);\n        double scaling_factor = 3.0/average_rate;\n\n        _Q *= scaling_factor;\n\n        // S is a symmetric matrix\n        eigenMatrixXd_t S = eigenMatrixXd_t(_sqrtPi*_Q*_sqrtPiInv);\n\n        // Can use efficient eigensystem solver because S is symmetric\n        Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(S);\n        if (solver.info() != Eigen::Success) {\n            throw XLorad(\"Error in the calculation of eigenvectors and eigenvalues of the codon model rate matrix\");\n        }\n\n        _eigenvectors           = _sqrtPiInv*solver.eigenvectors();\n        _inverse_eigenvectors   = solver.eigenvectors().transpose()*_sqrtPi;\n        _eigenvalues            = solver.eigenvalues();\n    }\n    \n#if defined(POLGSS)\n    inline void QMatrixCodon::setStateFreqRefDistParamsSharedPtr(QMatrix::freq_xchg_ptr_t freq_params_ptr) {\n        if (freq_params_ptr->size() != 61)\n            throw XLorad(boost::format(\"Expecting 61 state frequency reference distribution parameters and got %d: perhaps you meant to specify a subset data type other than codon\") % freq_params_ptr->size());\n        _state_freq_refdist = freq_params_ptr;\n    }\n    \n    inline std::vector<double> QMatrixCodon::getStateFreqRefDistParamsVect() const {\n        return std::vector<double>(_state_freq_refdist->begin(), _state_freq_refdist->end());\n    }\n    \n    inline void QMatrixCodon::setExchangeabilityRefDistParamsSharedPtr(QMatrix::freq_xchg_ptr_t xchg_params_ptr) {\n        throw XLorad(\"Not expecting exchangeability reference distribution to be specified for a codon model\");\n    }\n    \n    inline std::vector<double> QMatrixCodon::getExchangeabilityRefDistParamsVect() const {\n        throw XLorad(\"Not expecting to copy exchangeability reference distribution parameters for a codon model\");\n        return std::vector<double>();\n    }\n#endif\n    \n} // namespace lorad\n", "meta": {"hexsha": "ce1d8de6bdc3ebf52395ca72611f5aef2227dc37", "size": 27099, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/qmatrix.hpp", "max_stars_repo_name": "plewis/lorad", "max_stars_repo_head_hexsha": "bdc70e966e423e92aef66ef9d52220a5c241e6f3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-17T17:07:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T17:07:24.000Z", "max_issues_repo_path": "src/qmatrix.hpp", "max_issues_repo_name": "plewis/hpd-histogram", "max_issues_repo_head_hexsha": "4cc35206e0505127bffe9db6f650852f07bb7f63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qmatrix.hpp", "max_forks_repo_name": "plewis/hpd-histogram", "max_forks_repo_head_hexsha": "4cc35206e0505127bffe9db6f650852f07bb7f63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9489164087, "max_line_length": 213, "alphanum_fraction": 0.5830104432, "num_tokens": 6330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2397680579437671}}
{"text": "// External libraries\n#include <iostream>\n#include <stdio.h>\n#include <boost/property_tree/ptree.hpp>\n\n// Local libraries\n#include <inout/ioutil.h>\n#include <fparameters/parameters.h>\n#include <fparameters/SpaceIterator.h>\n\n// Local headers\n#include \"read.h\"\n#include \"messages.h\"\n#include \"modelParameters.h\"\n#include \"State.h\"\n#include \"write.h\"\n#include \"comptonScattMatrix.h\"\n#include \"thermalProcesses.h\"\n#include \"adafFunctions.h\"\n#include \"globalVariables.h\"\n#include \"flareProcesses.h\"\n#include \"redshiftFunction.h\"\n#include \"thermalDistribution.h\"\n#include \"NTtimescales.h\"\n#include \"NTinjection.h\"\n#include \"injectionNeutrons.h\"\n#include \"distributionNeutrons.h\"\n#include \"NTdistribution.h\"\n#include \"NTradiation.h\"\n#include \"absorption.h\"\n#include \"secondariesProcesses.h\"\n#include \"jetEmission.h\"\n\nusing namespace std;\n\nint main()\n{\n\tstring folder{ prepareOutputfolder() };\n\ttry {\n\t\tGlobalConfig = readConfig();\n\t\tprepareGlobalCfg();\n\t\t\n\t\tState model(GlobalConfig.get_child(\"model\"));\n\t\tredshiftFactor(model);\n\t\tcreateH5file(\"h5prueba.h5\", model);\n\t}\n\tcatch (std::runtime_error& e)\n\t{\n\t\tstd::cout << \"ERROR: \" << e.what() << std::endl;\n\t}\n\treturn 0;\n}\n\n/*\tstring folder{ prepareOutputfolder() };\n\ttry {\n\t\tGlobalConfig = readConfig();\n\t\tprepareGlobalCfg();\n\t\t\n\t\tState model(GlobalConfig.get_child(\"model\"));\n\t\twriteFields(model);\n\t\tredshiftFactor(model);\n\n\t\tif (calculateThermal) {\n\t\t\tif (calculateComptonScatt)\n\t\t\t\tcomptonScattMatrix(model);\n\t\t\telse\n\t\t\t\tcomptonScattMatrixRead(model);\n\t\t\tthermalRadiation(model, \"lumThermal.dat\");\n\t\t}\n\t\telse\n\t\t\treadEandRParamSpace(\"photonDensity\", model.photon.distribution, 0, 0);\n\t\t\n\t\t//writeEandRParamSpace(\"photonDensity_z\",model.photon.injection,0,0);\n\t\t\n\t\tif (calculateJetEmission)\n\t\t\tjetProcesses(model,\"lumJet.txt\");\n\t\t\n\t\tif (calculateFlare)\n\t\t\tflareProcesses(model);\n\t\t\n//***********nonthermal particles**************\t\t\n\t\tif (calculateNonThermal) {\n            \n\t\t\tif (calculateLosses) {\n\t\t\t\tif (calculateNTelectrons)\n\t\t\t\t\tnonThermalTimescales(model.ntElectron, model, \"electronCoolingTimes.dat\");\n\t\t\t\tif (calculateNTprotons)\n\t\t\t\t\tnonThermalTimescales(model.ntProton, model, \"protonCoolingTimes.dat\");\n\t\t\t}\n\t\t\n\t\t\tif (calculateNTdistributions) {\n\n\t\t\t\tif (calculateNTelectrons) {\n\t\t\t\t\tinjection(model.ntElectron, model);\n\t\t\t\t\tif (accMethod == 0)\n\t\t\t\t\t\t//distributionSpatialDiffusion(model.ntElectron, model);\n\t\t\t\t\t\tdistributionMultiZone(model.ntElectron, model);\n\t\t\t\t\t\t//distributionSpatialDiffusionSteady(model.ntElectron, model);\n\t\t\t\t\telse\n\t\t\t\t\t\tdistributionSpatialDiffusion(model.ntElectron, model);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treadEandRParamSpace(\"electronInjection_vol\", model.ntElectron.injection, 0, 1);\n\t\t\t\t\treadEandRParamSpace(\"electronDistribution_vol\", model.ntElectron.distribution, 0, 1);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (calculateNTprotons) {\n\t\t\t\t\tif (accMethod == 0)\n\t\t\t\t\t\tinjection(model.ntProton,model);\n\t\t\t\t\telse\n\t\t\t\t\t\tinjection(model.ntProton,model);\n\t\t\t\t\t\t//injectionFokkerPlanckOneZone(model.ntProton,model);\n\t\t\t\t\tif (accMethod == 0)\n\t\t\t\t\t\tdistributionSpatialDiffusionSteady(model.ntProton, model);\n\t\t\t\t\t\t//distributionMultiZoneRadial(model.ntProton, model);\n\t\t\t\t\telse\n\t\t\t\t\t\tdistributionSpatialDiffusionSteady(model.ntProton, model);\n\t\t\t\t\t\t//distributionFokkerPlanckCompleteSteadyState(model.ntProton, model);\n\t\t\t\t\t\t//distributionFokkerPlanckSpatialDiffusionTimeDependent(model.ntProton, model);\n\t\t\t\t\t\t//distributionFokkerPlanckRadial(model.ntProton,model);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treadEandRParamSpace(\"protonInjection_vol\", model.ntProton.injection,0,1);\n\t\t\t\t\treadEandRParamSpace(\"protonDistribution_vol\", model.ntProton.distribution,0,1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (calculateNTelectrons) {\n\t\t\t\t\treadEandRParamSpace(\"electronInjection_vol\",model.ntElectron.injection,0,1);\n\t\t\t\t\treadEandRParamSpace(\"electronDistribution_vol\",model.ntElectron.distribution,0,1);\n\t\t\t\t}\n\t\t\t\tif (calculateNTprotons) {\n\t\t\t\t\treadEandRParamSpace(\"protonInjection_vol\",model.ntProton.injection,0,1);\n\t\t\t\t\treadEandRParamSpace(\"protonDistribution_vol\",model.ntProton.distribution,0,1);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (calculateNonThermalLum)\n\t\t\t\tnonThermalRadiation(model, \"lumNonThermal.dat\");\n\t\t\telse {\n\t\t\t\treadEandRParamSpace(\"photonDensity\", model.photon.distribution, 0, 0);\n\t\t\t\treadEandRParamSpace(\"NTphotonDensity\", model.ntPhoton.distribution, 0, 0);\n\t\t\t\treadEandRParamSpace(\"NTphotonDensity\", model.ntPhoton.injection, 0, 0);\n\t\t\t\treadEandRParamSpace(\"opticalDepth_gg\", model.tau_gg, 0, 0);\n\t\t\t}\n\t\t\t\n\t\t\tif (calculateSecondaries)\n\t\t\t\tsecondariesProcesses(model);\n\t\t\telse {\n\t\t\t\treadEandRParamSpace(\"muonDistribution\", model.ntMuon.distribution, 0, 0);\n\t\t\t\treadEandRParamSpace(\"pionDistribution\", model.ntChargedPion.distribution, 0, 0);\n\t\t\t}\n\t\t\t\n\t\t\t// NEUTRINO TRANSPORT\n\t\t\tif (calculateNeutrinos)\n\t\t\t\tinjectionNeutrino(model.neutrino, model);\n\t\t\t\t\n\t\t\t// NEUTRON TRANPOSRT\n\t\t\tif (calculateNeutronInj) {\n\t\t\t\tinjectionNeutrons(model);\n\t\t\t\tradiativeLossesNeutron(model.ntNeutron,model,\"neutronTimescales.dat\");\n\t\t\t\tif (calculateNeutronDis)\n\t\t\t\t\tdistributionNeutronsAGN(model);\n\t\t\t\tif (calculateJetDecay)\n\t\t\t\t\tjetNeutronDecay(model);\n\t\t\t}\n\t\t}\n\t}\n\tcatch (std::runtime_error& e)\n\t{\n\t\tstd::cout << \"ERROR: \" << e.what() << std::endl;\n\t}\n\treturn 0;\n}*/", "meta": {"hexsha": "80ca4802768bf2f5cbba9372e55704a4ea801b0c", "size": 5168, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/main.cpp", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/adaf/main.cpp", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaf/main.cpp", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7011494253, "max_line_length": 90, "alphanum_fraction": 0.7174922601, "num_tokens": 1459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2392746598334529}}
{"text": "/*  _______________________________________________________________________\n\n    DAKOTA: Design Analysis Kit for Optimization and Terascale Applications\n    Copyright 2014 Sandia Corporation.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Dakota directory.\n    _______________________________________________________________________ */\n\n\n//- Class:\t     SensAnalysisGlobal\n//- Description: Utility helper class which has correlations and VBD\n//- Owner:       Laura Swiler, Brian Adams, Ahmad Rushdi\n//- Checked by:\n//- Version:\n\n#include \"SensAnalysisGlobal.hpp\"\n#include \"ResultsManager.hpp\"\n#include \"dakota_linear_algebra.hpp\"\n#include <algorithm>\n#include <boost/iterator/counting_iterator.hpp>\n\nstatic const char rcsId[]=\"@(#) $Id: SensAnalysisGlobal.cpp 6170 2009-10-06 22:42:15Z lpswile $\";\n\n\nnamespace Dakota {\n\nRealArray SensAnalysisGlobal::rawData = RealArray();\n\n\nbool SensAnalysisGlobal::rank_sort(const int& x, const int& y)\n{ return rawData[x]<rawData[y]; }\n\n\nsize_t SensAnalysisGlobal::\nfind_valid_samples(const IntResponseMap& resp_samples, BoolDeque& valid_sample)\n{\n  // TODO: later compute correlation on per-response basis to keep\n  // partial faults\n  using std::isfinite;\n\n  size_t num_obs = resp_samples.size(), num_valid_samples = 0;\n  IntRespMCIter it = resp_samples.begin();\n  for (size_t j=0; j<num_obs; ++j, ++it) {\n    valid_sample[j] = true;\n    for (size_t k=0; k<numFns; ++k)\n      if (!isfinite(it->second.function_value(k))) {\n        valid_sample[j] = false; \n        break; \n      }\n    if (valid_sample[j])\n      ++num_valid_samples;\n  }\n\n  return num_valid_samples;\n}\n\n\nvoid SensAnalysisGlobal::\nvalid_sample_matrix(const VariablesArray& vars_samples,\n                    const IntResponseMap& resp_samples,\n                    const StringSetArray& dss_vals,\n                    const BoolDeque is_valid_sample,\n                    RealMatrix& valid_data) \n{\n  int num_obs = vars_samples.size(), num_corr = valid_data.numRows();\n  IntRespMCIter it = resp_samples.begin();\n  for (size_t j=0, s_cntr=0; j<num_obs; ++j, ++it)\n    if (is_valid_sample[j]) {\n      // get a view of the first numVars rows of the samples col\n      RealVector td_col_vars(Teuchos::View, valid_data[s_cntr], (int)numVars);\n      vars_samples[j].as_vector(dss_vals, td_col_vars);\n      // get a view of the last numFns rows of the samples col\n      RealVector td_col_resp(Teuchos::View, valid_data[s_cntr] + numVars, \n                             (int)numFns);\n      copy_data(it->second.function_values(), td_col_resp);\n      ++s_cntr;\n    }\n}\n\nvoid SensAnalysisGlobal::\nvalid_sample_matrix(const RealMatrix&     vars_samples,\n                    const IntResponseMap& resp_samples,\n                    const BoolDeque is_valid_sample,\n                    RealMatrix& valid_data)\n{\n  int num_obs = vars_samples.numCols(), num_corr = valid_data.numRows();\n  IntRespMCIter it = resp_samples.begin();\n  for (int j=0, s_cntr=0; j<num_obs; ++j, ++it)\n    if (is_valid_sample[j]) {\n      for (int i=0; i<numVars; ++i)\n        valid_data(i, s_cntr) = vars_samples(i, j);\n      // get a view of the last numFns rows of the samples col\n      RealVector td_col_resp(Teuchos::View, valid_data[s_cntr] + numVars, \n                             (int)numFns);\n      copy_data(it->second.function_values(), td_col_resp);\n      ++s_cntr;\n    }\n}\n\n\n/** When converting values to ranks, uses the average ranks of any tied values */\nvoid SensAnalysisGlobal::values_to_ranks(RealMatrix& valid_data)\n{\n  int num_corr = valid_data.numRows(), num_valid_samples = valid_data.numCols();\n  // for each var/resp\n  for (int i=0; i<num_corr; ++i) {\n    // create a multimap from value to array index (so it is sorted by value and\n    // the ranks are given by the map order); don't need a stable sort as we are\n    // replacing the tied values by their average rank\n    RealIntMultiMap vals_inds;\n    for (int j=0; j<num_valid_samples; ++j)\n      vals_inds.insert(std::make_pair(valid_data(i,j), j));\n\n    // iterate for each unique value and find tied values\n    RealIntMultiMap::const_iterator vi_it = vals_inds.begin();\n    RealIntMultiMap::const_iterator vi_end = vals_inds.end();\n    for (int rank=0; vi_it != vi_end; ) {\n      // find a range of tied values\n      double value = vi_it->first;\n      std::pair<RealIntMultiMap::const_iterator, RealIntMultiMap::const_iterator>\n\ttied_range = vals_inds.equal_range(value); \n      int num_ties = std::distance(tied_range.first, tied_range.second);\n      double avg_rank = (rank + rank+num_ties-1) / 2.0;\n      // all tied values get assigned the average rank\n      for ( ; tied_range.first != tied_range.second; ++tied_range.first)\n\tvalid_data(i, tied_range.first->second) = avg_rank;\n      // increment to the next unequal value\n      vi_it = tied_range.second;\n      rank += num_ties;\n    }\n  }\n}\n\n\nvoid SensAnalysisGlobal::center_rows(RealMatrix& data_matrix)\n{\n  int num_row = data_matrix.numRows(), num_col = data_matrix.numCols();\n  for (int i=0; i<num_row; i++) {\n    // normalize each row (input/output factor) by its mean across observations\n    Real row_mean = 0.0;\n    for (int j=0; j<num_col; j++)\n      row_mean += data_matrix(i,j);\n    row_mean /= (Real)num_col;\n    for (int j=0; j<num_col; j++)\n      data_matrix(i,j) -= row_mean;\n  }\n}\n\n\nvoid SensAnalysisGlobal::correl_adjust(Real& corr_value)\n{\n  if (std::isfinite(corr_value) && std::abs(corr_value) > 1.0)\n    corr_value = corr_value / std::abs(corr_value);\n}\n\n\n/** This version is used when full variables objects are being\n    processed. Calculates simple correlation, partial correlation,\n    simple rank correlation, and partial rank correlation\n    coefficients. */\nvoid SensAnalysisGlobal::\ncompute_correlations(const VariablesArray& vars_samples,\n                     const IntResponseMap& resp_samples,\n                     const StringSetArray& dss_vals)\n{\n  size_t num_obs = vars_samples.size();\n  if (num_obs == 0) {\n    Cerr << \"Error: Number of samples must be nonzero in SensAnalysisGlobal::\"\n         << \"compute_correlations().\" << std::endl;\n    abort_handler(-1);\n  }\n  if (resp_samples.size() != num_obs) {\n    Cerr << \"Error: Mismatch in array lengths in SensAnalysisGlobal::\"\n         << \"compute_correlations().\" << std::endl;\n    abort_handler(-1);\n  }\n\n  numVars = vars_samples[0].cv() + vars_samples[0].div() + \n    vars_samples[0].dsv() + vars_samples[0].drv();\n  numFns  = resp_samples.begin()->second.num_functions();\n  int num_corr = numVars + numFns;\n\n  // determine which samples have valid responses\n  BoolDeque is_valid_sample(num_obs);\n  int num_valid_samples = find_valid_samples(resp_samples, is_valid_sample);\n  \n  // The following calls regenerate and destroy the valid_data matrix\n  // to save memory\n\n  // create a matrix containing only the valid sample data\n  RealMatrix valid_data(num_corr, num_valid_samples);\n\n  // calculate simple rank correlation coeff\n  valid_sample_matrix(vars_samples, resp_samples, dss_vals, is_valid_sample, \n                      valid_data);\n  simple_corr(valid_data, num_corr, simpleCorr);\n\n  // calculate partial correlation coeff\n  valid_sample_matrix(vars_samples, resp_samples, dss_vals, is_valid_sample, \n                      valid_data);\n  partial_corr(valid_data, numVars, simpleCorr, partialCorr, numericalIssuesRaw);\n\n  // calculate simple rank correlation coeff\n  valid_sample_matrix(vars_samples, resp_samples, dss_vals, is_valid_sample, \n                      valid_data);\n  values_to_ranks(valid_data);\n  simple_corr(valid_data, num_corr, simpleRankCorr);\n\n  // calculate partial rank correlation coeff\n  valid_sample_matrix(vars_samples, resp_samples, dss_vals, is_valid_sample, \n                      valid_data);\n  values_to_ranks(valid_data);\n  partial_corr(valid_data, numVars, simpleRankCorr, partialRankCorr, \n               numericalIssuesRank);\n\n  corrComputed = true;\n}\n\n/** This version is used when compact samples matrix is being\n    processed.  Calculates simple correlation, partial correlation,\n    simple rank correlation, and partial rank correlation\n    coefficients. */\nvoid SensAnalysisGlobal::\ncompute_correlations(const RealMatrix&     vars_samples,\n                     const IntResponseMap& resp_samples)\n{\n  int num_obs = vars_samples.numCols();\n  if (!num_obs) {\n    Cerr << \"Error: Number of samples must be nonzero in SensAnalysisGlobal::\"\n         << \"compute_correlations().\" << std::endl;\n    abort_handler(-1);\n  }\n  if (resp_samples.size() != num_obs) {\n    Cerr << \"Error: Mismatch in array lengths in SensAnalysisGlobal::\"\n         << \"compute_correlations().\" << std::endl;\n    abort_handler(-1);\n  }\n\n  numVars = vars_samples.numRows();\n  numFns  = resp_samples.begin()->second.num_functions();\n  int num_corr = numVars + numFns;\n\n  // determine which samples have valid responses\n  BoolDeque is_valid_sample(num_obs);\n  int num_valid_samples = find_valid_samples(resp_samples, is_valid_sample);\n\n  // The following calls regenerate and destroy the valid_data matrix\n  // to save memory\n\n  // create a matrix containing only the valid sample data\n  RealMatrix valid_data(num_corr, num_valid_samples);\n\n  // calculate simple rank correlation coeff\n  valid_sample_matrix(vars_samples, resp_samples, is_valid_sample, valid_data);\n  simple_corr(valid_data, num_corr, simpleCorr);\n\n  // calculate partial correlation coeff\n  valid_sample_matrix(vars_samples, resp_samples, is_valid_sample, valid_data);\n  partial_corr(valid_data, numVars, simpleCorr, partialCorr, numericalIssuesRaw);\n\n  // calculate simple rank correlation coeff\n  valid_sample_matrix(vars_samples, resp_samples, is_valid_sample, valid_data);\n  values_to_ranks(valid_data);\n  simple_corr(valid_data, num_corr, simpleRankCorr);\n\n  // calculate partial rank correlation coeff\n  valid_sample_matrix(vars_samples, resp_samples, is_valid_sample, valid_data);\n  values_to_ranks(valid_data);\n  partial_corr(valid_data, numVars, simpleRankCorr, partialRankCorr, \n               numericalIssuesRank);\n\n  corrComputed = true;\n}\n\n\n/** Calculates simple correlation coefficients from a matrix of data\n    (oriented factors x observations):\n     - num_corr is number of rows of total data \n     - num_in indicates whether only pairs of correlations should be\n       calculated between pairs of columns (num_in\n       vs. num_corr-num_in); if num_in = num_corr, correlations are\n       calculated between all columns */\nvoid SensAnalysisGlobal::\nsimple_corr(RealMatrix& total_data, const int& num_in, RealMatrix& corr_matrix)\n{\n  int num_corr = total_data.numRows(), num_obs = total_data.numCols();\n\n  center_rows(total_data);\n\n  for (int i=0; i<num_corr; i++) {\n    // calculate sum of squares for each factor (row)\n    Real row_sumsq = 0.0;\n    for (int j=0; j<num_obs; j++)\n      row_sumsq += total_data(i,j)*total_data(i,j);\n    row_sumsq = std::sqrt(row_sumsq);\n    // normalize the rows with the sumsquare term\n    for (int j=0; j<num_obs; j++)\n      total_data(i,j) /= row_sumsq;\n  }\n\n  // calculate matrix of simple correlation coefficients\n  if (num_corr == num_in) {\n    // all-to-all case\n    corr_matrix.shape(num_corr, num_corr);\n    if (num_obs <= 1)\n      corr_matrix.putScalar(std::numeric_limits<double>::quiet_NaN());\n    else {\n      corr_matrix.multiply(Teuchos::NO_TRANS, Teuchos::TRANS, 1.0, \n\t\t\t   total_data, total_data, 0.0);\n      for (int i=0; i<num_corr; ++i) {\n\t// set finite diagonal values to 1.0\n\tif (std::isfinite(corr_matrix(i,i)))\n\t  corr_matrix(i,i) = 1.0;\n\t// snap all finite values to [-1.0, 1.0]\n\tfor (int j=0; j<i; ++j) {\n\t  correl_adjust(corr_matrix(i,j));\n\t  correl_adjust(corr_matrix(j,i));\n\t}\n      }\n    }\n  }\n  else {  \n    // input-to-output case\n    int num_out = num_corr - num_in;\n    corr_matrix.shape(num_in, num_out);\n    if (num_obs <= 1)\n      corr_matrix.putScalar(std::numeric_limits<double>::quiet_NaN());\n    else {\n      RealMatrix total_data_in(Teuchos::View, total_data, num_in, num_obs, 0, 0);\n      RealMatrix total_data_out(Teuchos::View, total_data, num_out, num_obs, \n\t\t\t\tnum_in, 0);\n      corr_matrix.multiply(Teuchos::NO_TRANS, Teuchos::TRANS, 1.0, \n\t\t\t   total_data_in, total_data_out, 0.0);\n      // snap all finite values to [-1.0, 1.0]\n      for (int i=0; i<num_in; ++i)\n\tfor (int j=0; j<num_out; ++j)\n\t  correl_adjust(corr_matrix(i,j));\n    }\n  } \n}\n\n\n/** Calculates partial correlation coefficients between num_in inputs\n    and numRows() - num_in outputs. */\nvoid SensAnalysisGlobal::\npartial_corr(RealMatrix& total_data, const int num_in, \n             const RealMatrix& simple_corr_mat,\n             RealMatrix& corr_matrix, bool& numerical_issues)\n{\n  int num_obs = total_data.numCols(), num_out = total_data.numRows() - num_in;\n\n  // initialize output data\n  corr_matrix.reshape(num_in, num_out);    \n  numerical_issues = false;\n  // TODO: return numerical issues per-input\n  BoolDeque numerical_except(num_in, false);\n\n  if (num_obs <= 1) {\n    corr_matrix.putScalar(std::numeric_limits<double>::quiet_NaN());\n    numerical_issues = true;\n    return;\n  }\n  \n  // For a single input factor, partial = simple (no controlling factors)\n  if (num_in == 1) {\n    for (int k=0; k<num_out; ++k)\n      corr_matrix(0, k) = simple_corr_mat(0, k+1);\n    return;\n  }\n\n  center_rows(total_data);\n\n  // matrix of X = [Vi | R ]; the response cols don't change per variable\n  RealMatrix correl_factors_X(num_obs, 1 + num_out);\n  for (int j=0; j<num_obs; ++j)\n    for (int k=0; k<num_out; ++k)\n      correl_factors_X(j, 1+k) = total_data(num_in+k, j);\n  // matrix of Z = [V~i]\n  RealMatrix control_factors_Z(num_obs, num_in - 1);\n\n  for (int i=0; i<num_in; ++i) {\n\n    // partial correlation analysis for Vi, R, controlling for\n    // V~i. Transpose everything to line up with more typical\n    // convention Nobs x (Nvar + Nresp)\n    for (int j=0; j<num_obs; ++j) {\n      correl_factors_X(j, 0) = total_data(i, j); // Vi\n      // (response columns are already populated above)\n      // V~i\n      for (int k=0; k<i; ++k)\n        control_factors_Z(j, k) = total_data(k, j);\n      for (int k=i+1; k<num_in; ++k)\n        control_factors_Z(j, k-1) = total_data(k, j);\n    }\n\n    // form partial_cov = X'X - (X'Z)*inv(Z'Z)*(Z'X), preserving\n    // symmetric and positive definite\n    int mult_err = 0;\n\n    // intialize to X'X\n    RealMatrix partial_cov(1 + num_out, 1 + num_out);\n    mult_err |= partial_cov.multiply(Teuchos::TRANS, Teuchos::NO_TRANS, 1.0,\n\t\t\t\t     correl_factors_X, correl_factors_X, 0.0);\n\n    // Here we use truncated SVD to account for the case where there\n    // are fewer data points than variables, including the degenerate\n    // case of 2 observations.  Should be equivalent to minimum-norm\n    // least squares in the regressions.\n\n    RealMatrix Zinv_Zt_X;  // a bit misnamed, since Z is rectangular\n    bool use_qr = false;\n    if (use_qr) {\n      Zinv_Zt_X.reshape(num_in - 1, 1 + num_out);\n      // initialize to Z'X\n      mult_err |= Zinv_Zt_X.multiply(Teuchos::TRANS, Teuchos::NO_TRANS, 1.0, \n                                     control_factors_Z, correl_factors_X, 0.0);\n\n      // factor Z = QR; in-place QR factorization destroys Z (this never errors)\n      qr(control_factors_Z); \n\n      // now backsolve to update to Rinv' * Z'X (a failed backsolve leaves junk)\n      int qrs_info = qr_rsolve(control_factors_Z, true, Zinv_Zt_X);\n      numerical_except[i] = numerical_except[i] || (qrs_info != 0);\n    }\n    else {\n      // alternative with svd to numerical precision; some concern\n      // remains that this might not yield nan/inf when it should\n\n      // initialize to Z'X\n      RealMatrix Zt_X(num_in - 1, 1 + num_out);\n      mult_err |= Zt_X.multiply(Teuchos::TRANS, Teuchos::NO_TRANS, 1.0, \n                                control_factors_Z, correl_factors_X, 0.0);\n      RealVector sing_vals; \n      RealMatrix v_trans;\n      svd(control_factors_Z, sing_vals, v_trans);\n\n      double tol = \n        std::numeric_limits<double>::epsilon() * control_factors_Z.normInf();\n      int sv_keep = 0;\n      for ( ; sv_keep < sing_vals.length(); ++sv_keep)\n        if (sing_vals[sv_keep] < tol)\n          break;\n      // TODO: Could opt for stricter check here:\n      // if (sv_keep < std::min(num_obs, num_in-1))\n      if (sv_keep == 0)\n        numerical_except[i] = true;\n      else {\n        v_trans.reshape(sv_keep, num_in - 1);\n        Zinv_Zt_X.reshape(sv_keep, 1 + num_out);\n        Zinv_Zt_X.multiply(Teuchos::NO_TRANS, Teuchos::NO_TRANS, 1.0, \n                           v_trans, Zt_X, 0.0);\n        for (int j=0; j<sv_keep; ++j)\n          for (int k=0; k < (1 + num_out); ++k)\n            Zinv_Zt_X(j,k) /= sing_vals[j];\n      }\n    }\n\n    if (!numerical_except[i])\n      // X'X - (X'Z)*inv(Z'Z)*(Z'X) = X'X - (Zinv*Z'X)'(Zinv*Z'X)\n      mult_err |= partial_cov.multiply(Teuchos::TRANS, Teuchos::NO_TRANS, -1.0,\n\t\t\t\t       Zinv_Zt_X, Zinv_Zt_X, 1.0);\n\n    // This should never happen:\n    if (mult_err != 0) {\n      Cerr << \"\\nError (partial_corr): multiplying incompatible matrices.\\n\";\n      abort_handler(-1);\n    }\n    numerical_issues = numerical_issues || numerical_except[i];\n\n    for (int k=0; k<num_out; ++k)\n      if (numerical_except[i])\n        corr_matrix(i,k) = std::numeric_limits<Real>::quiet_NaN();\n      else\n        corr_matrix(i,k) = partial_cov(0, k+1) / std::sqrt(partial_cov(0,0)) / \n          std::sqrt(partial_cov(k+1, k+1));\n  }\n\n  // snap all finite values to [-1.0, 1.0]\n  for (int i=0; i<num_in; ++i)\n    for (int j=0; j<num_out; ++j)\n      correl_adjust(corr_matrix(i,j));\n}\n\n// Return true if any correlation coefficient is NaN or Inf, false otherwise\nbool SensAnalysisGlobal::has_nan_or_inf(const RealMatrix &corr) const {\n  int num_rows = corr.numRows(), num_cols = corr.numCols();\n  for(int j = 0; j < num_cols; ++j) \n    for(int i = 0; i < num_rows; ++i) \n      if( ! std::isfinite(corr(i,j)))\n        return true;\n  return false;\n}\n\n// TODO: combine archive with print\nvoid SensAnalysisGlobal::\narchive_correlations(const StrStrSizet& run_identifier,  \n\t\t     ResultsManager& iterator_results,\n\t\t     StringMultiArrayConstView cv_labels,\n\t\t     StringMultiArrayConstView div_labels,\n\t\t     StringMultiArrayConstView dsv_labels,\n\t\t     StringMultiArrayConstView drv_labels,\n\t\t     const StringArray& resp_labels) const\n{\n  if (!iterator_results.active())  return;\n\n  int num_in_out = numVars + numFns;\n  if (simpleCorr.numRows() == num_in_out &&\n      simpleCorr.numCols() == num_in_out) {\n    MetaDataType md;\n    md[\"Row labels\"] = \n      make_metadatavalue(cv_labels, div_labels, dsv_labels, drv_labels, resp_labels);\n    md[\"Column labels\"] = \n      make_metadatavalue(cv_labels, div_labels, dsv_labels, drv_labels, resp_labels);\n    iterator_results.insert(run_identifier, \n\t\t\t    iterator_results.results_names.correl_simple_all,\n\t\t\t    simpleCorr, md);\n  }\n  else if (simpleCorr.numRows() == numVars &&\n\t   simpleCorr.numCols() == numFns) {\n    MetaDataType md;\n    md[\"Row labels\"] = \n      make_metadatavalue(cv_labels, div_labels, dsv_labels, drv_labels, StringArray());\n    md[\"Column labels\"] = make_metadatavalue(resp_labels);\n    iterator_results.insert(run_identifier, \n\t\t\t    iterator_results.results_names.correl_simple_io,\n\t\t\t    simpleCorr, md);\n  }\n\n  if (partialCorr.numRows() == numVars &&\n      partialCorr.numCols() == numFns) {\n    MetaDataType md;\n    md[\"Row labels\"] = \n      make_metadatavalue(cv_labels, div_labels, dsv_labels, drv_labels, StringArray());\n    md[\"Column labels\"] = make_metadatavalue(resp_labels);\n    iterator_results.insert(run_identifier, \n\t\t\t    iterator_results.results_names.correl_partial_io,\n\t\t\t    partialCorr, md);\n  }\n  // TODO: metadata\n  //  if (numericalIssuesRaw)\n\n  if (simpleRankCorr.numRows() == num_in_out &&\n      simpleRankCorr.numCols() == num_in_out) {\n    MetaDataType md;\n    md[\"Row labels\"] = \n      make_metadatavalue(cv_labels, div_labels, dsv_labels, drv_labels, resp_labels);\n    md[\"Column labels\"] = \n      make_metadatavalue(cv_labels, div_labels, dsv_labels, drv_labels, resp_labels);\n    iterator_results.insert(run_identifier, \n\t\t\t    iterator_results.results_names.correl_simple_rank_all,\n\t\t\t    simpleRankCorr, md);\n  }\n  else if (simpleRankCorr.numRows() == numVars &&\n\t   simpleRankCorr.numCols() == numFns) {\n    MetaDataType md;\n    md[\"Row labels\"] = \n      make_metadatavalue(cv_labels, div_labels, dsv_labels, drv_labels, StringArray());\n    md[\"Column labels\"] = make_metadatavalue(resp_labels);\n    iterator_results.insert(run_identifier, \n\t\t\t    iterator_results.results_names.correl_simple_rank_io,\n\t\t\t    simpleRankCorr, md);\n\n\n  }\n\n  if (partialRankCorr.numRows() == numVars &&\n      partialRankCorr.numCols() == numFns) {\n    MetaDataType md;\n    md[\"Row labels\"] = \n      make_metadatavalue(cv_labels, div_labels, dsv_labels, drv_labels, StringArray());\n    md[\"Column labels\"] = make_metadatavalue(resp_labels);\n    iterator_results.insert(run_identifier, \n\t\t\t    iterator_results.results_names.correl_partial_rank_io,\n\t\t\t    partialRankCorr, md);\n  }\n}\n\n\nvoid SensAnalysisGlobal::\nprint_correlations(std::ostream& s, StringMultiArrayConstView cv_labels,\n\t\t   StringMultiArrayConstView div_labels,\n\t\t   StringMultiArrayConstView dsv_labels,\n\t\t   StringMultiArrayConstView drv_labels,\n\t\t   const StringArray& resp_labels) const\n{\n  // output correlation matrices\n\n  if (!corrComputed) {\n    Cout << \"Correlation matrices not computed.\" << std::endl;\n    return;\n  }\n\n  if( has_nan_or_inf(simpleCorr) ||\n      has_nan_or_inf(partialCorr) ||\n      has_nan_or_inf(simpleRankCorr) ||\n      has_nan_or_inf(partialRankCorr) )\n    s << \"\\n\\nAt least one correlation coefficient is nan or inf. This \" <<\n      \"commonly occurs when\\ndiscrete variables (including histogram \" <<\n      \"variables) are present, a response is\\ncompletely insensitive to \" <<\n      \"variables (response variance equal to 0), there are\\nfewer samples \" <<\n      \"than variables, or some samples are approximately collinear.\" << \n      std::endl;\n  \n  s << std::scientific << std::setprecision(5);\n\n  if (resp_labels.size() != numFns) { \n    Cerr << \"Error: Number of response labels (\" << resp_labels.size()\n\t << \") passed to print_correlations not equal to number of output \"\n\t << \"functions (\" << numFns << \") in compute_correlations().\"\n\t << std::endl;\n    abort_handler(-1);\n  }\n\n  size_t i, j, num_cv = cv_labels.size(), num_div = div_labels.size(),\n    num_dsv = dsv_labels.size(), num_drv = drv_labels.size();\n  if (num_cv+num_div+num_dsv+num_drv != numVars) {\n    Cerr << \"Error: Number of variable labels (\" << num_cv+num_div+num_drv\n\t << \") passed to print_correlations not equal to number of input \"\n\t << \"variables (\" << numVars << \") in compute_correlations().\" << std::endl;\n    abort_handler(-1);\n  }\n\n  int num_in_out = numVars + numFns;\n  if (simpleCorr.numRows() == num_in_out &&\n      simpleCorr.numCols() == num_in_out) {\n    s << \"\\nSimple Correlation Matrix among all inputs and outputs:\\n\"\n      << \"             \";\n    for (i=0; i<num_cv; ++i)\n      s << std::setw(12) << cv_labels[i] << ' ';\n    for (i=0; i<num_div; ++i)\n      s << std::setw(12) << div_labels[i] << ' ';\n    for (i=0; i<num_dsv; ++i)\n      s << std::setw(12) << dsv_labels[i] << ' ';\n    for (i=0; i<num_drv; ++i)\n      s << std::setw(12) << drv_labels[i] << ' ';\n    for (i=0; i<numFns; ++i)\n      s << std::setw(12) << resp_labels[i] << ' ';\n    s << '\\n';\n    for (i=0; i<num_in_out; ++i) {\n      if (i<num_cv)\n\ts << std::setw(12) << cv_labels[i] << ' ';\n      else if (i<num_cv+num_div)\n\ts << std::setw(12) << div_labels[i-num_cv] << ' ';\n      else if (i<num_cv+num_div+num_dsv)\n\ts << std::setw(12) << dsv_labels[i-num_cv-num_div] << ' ';\n      else if (i<numVars)\n\ts << std::setw(12) << drv_labels[i-num_cv-num_div-num_dsv] << ' ';\n      else\n\ts << std::setw(12) << resp_labels[i-numVars] << ' ';\n      for (j=0; j<=i; ++j)\n\ts << std::setw(12) << simpleCorr(i,j) << ' ';\n      s << '\\n';\n    }\n  }\n  else if (simpleCorr.numRows() == numVars &&\n\t   simpleCorr.numCols() == numFns) {\n    s << \"\\nSimple Correlation Matrix between input and output:\\n\"\n      << \"             \";\n    for (j=0; j<numFns; ++j)\n      s << std::setw(12) << resp_labels[j] << ' ';\n    s << '\\n';\n    for (i=0; i<numVars; ++i) {\n      if (i<num_cv)\n\ts << std::setw(12) << cv_labels[i] << ' ';\n      else if (i<num_cv+num_div)\n\ts << std::setw(12) << div_labels[i-num_cv] << ' ';\n      else if (i<num_cv+num_div+num_dsv)\n\ts << std::setw(12) << dsv_labels[i-num_cv-num_div] << ' ';\n      else\n\ts << std::setw(12) << drv_labels[i-num_cv-num_div-num_dsv] << ' ';\n      for (j=0; j<numFns; ++j)\n\ts << std::setw(12) << simpleCorr(i,j) << ' ';\n      s << '\\n';\n    }\n  }\n\n  if (partialCorr.numRows() == numVars &&\n      partialCorr.numCols() == numFns) {\n    s << \"\\nPartial Correlation Matrix between input and output:\\n\"\n      << \"             \";\n    for (j=0; j<numFns; ++j)\n      s << std::setw(12) << resp_labels[j]<<' ';\n    s << '\\n';\n    for (i=0; i<numVars; ++i) {\n      if (i<num_cv)\n\ts << std::setw(12) << cv_labels[i] << ' ';\n      else if (i<num_cv+num_div)\n\ts << std::setw(12) << div_labels[i-num_cv] << ' ';\n      else if (i<num_cv+num_div+num_dsv)\n\ts << std::setw(12) << dsv_labels[i-num_cv-num_div] << ' ';\n      else\n\ts << std::setw(12) << drv_labels[i-num_cv-num_div-num_dsv] << ' ';\n      for (j=0; j<numFns; ++j)\n\ts << std::setw(12) << partialCorr(i,j) << ' ';\n      s << '\\n';\n    }\n  }\n  //  This warning message has been supplanted by more generic tests for NaNs and\n  //  Infs\n  //if (numericalIssuesRaw)\n  //  s << \"\\nThere may be some numerical issues associated with the calculation \"\n  //    << \"of the \\npartial correlation coefficients above.  This can be due to \"\n  //    << \"very small \\nnumbers of input samples, or to ill-conditioned matrices\"\n  //    << \", \\nin situations where the partials are very close to zero, -1, or \"\n  //    << \"+1.\\n\";\n\n  if (simpleRankCorr.numRows() == num_in_out &&\n      simpleRankCorr.numCols() == num_in_out) {\n    s << \"\\nSimple Rank Correlation Matrix among all inputs and outputs:\\n\"\n      << \"             \";\n    for (i=0; i<num_cv; ++i)\n      s << std::setw(12) << cv_labels[i] << ' ';\n    for (i=0; i<num_div; ++i)\n      s << std::setw(12) << div_labels[i] << ' ';\n    for (i=0; i<num_dsv; ++i)\n      s << std::setw(12) << dsv_labels[i] << ' ';\n    for (i=0; i<num_drv; ++i)\n      s << std::setw(12) << drv_labels[i] << ' ';\n    for (i=0; i<numFns; ++i)\n      s << std::setw(12) << resp_labels[i] << ' ';\n    s << '\\n';\n    for (i=0; i<num_in_out; ++i) {\n      if (i<num_cv)\n\ts << std::setw(12) << cv_labels[i] << ' ';\n      else if (i<num_cv+num_div)\n\ts << std::setw(12) << div_labels[i-num_cv] << ' ';\n      else if (i<num_cv+num_div+num_dsv)\n\ts << std::setw(12) << dsv_labels[i-num_cv-num_div] << ' ';\n      else if (i<numVars)\n\ts << std::setw(12) << drv_labels[i-num_cv-num_div-num_dsv] << ' ';\n      else\n\ts << std::setw(12) << resp_labels[i-numVars] << ' ';\n      for (j=0; j<=i; ++j)\n\ts << std::setw(12) << simpleRankCorr(i,j) << ' ';\n      s << '\\n';\n    }\n  }\n  else if (simpleRankCorr.numRows() == numVars &&\n\t   simpleRankCorr.numCols() == numFns) {\n    s << \"\\nSimple Rank Correlation Matrix between input and output:\\n\"\n      << \"             \";\n    for (j=0; j<numFns; ++j)\n      s << std::setw(12) << resp_labels[j] << ' ';\n    s << '\\n';\n    for (i=0; i<numVars; ++i) {\n      if (i<num_cv)\n\ts << std::setw(12) << cv_labels[i] << ' ';\n      else if (i<num_cv+num_div)\n\ts << std::setw(12) << div_labels[i-num_cv] << ' ';\n      else if (i<num_cv+num_div+num_dsv)\n\ts << std::setw(12) << dsv_labels[i-num_cv-num_div] << ' ';\n      else\n\ts << std::setw(12) << drv_labels[i-num_cv-num_div-num_dsv] << ' ';\n      for (j=0; j<numFns; ++j)\n\ts << std::setw(12) << simpleRankCorr(i,j) << ' ';\n      s << '\\n';\n    }\n  }\n\n  if (partialRankCorr.numRows() == numVars &&\n      partialRankCorr.numCols() == numFns) {\n    s << \"\\nPartial Rank Correlation Matrix between input and output:\\n\"\n      << \"             \";\n    for (j=0; j<numFns; ++j)\n      s << std::setw(12) << resp_labels[j] << ' ';\n    s << '\\n';\n    for (i=0; i<numVars; ++i) {\n      if (i<num_cv)\n\ts << std::setw(12) << cv_labels[i] << ' ';\n      else if (i<num_cv+num_div)\n\ts << std::setw(12) << div_labels[i-num_cv] << ' ';\n      else if (i<num_cv+num_div+num_dsv)\n\ts << std::setw(12) << dsv_labels[i-num_cv-num_div] << ' ';\n      else\n\ts << std::setw(12) << drv_labels[i-num_cv-num_div-num_dsv] << ' ';\n      for (j=0; j<numFns; ++j)\n\ts << std::setw(12) << partialRankCorr(i,j) << ' ';\n      s << '\\n';\n    }\n  }\n\n  //  This warning message has been supplanted by more generic tests for NaNs and\n  //  Infs\n  //if (numericalIssuesRank)\n  //  s << \"\\nThere may be some numerical issues associated with the calculation \"\n  //    << \"of the \\npartial rank correlation coefficients above.  This can be \"\n  //    << \"due to very small \\nnumbers of input samples, or to ill-conditioned \"\n  //    << \"matrices, \\nin situations where the partials are very close to zero, \"\n  //    << \"-1, or +1.\\n\";\n   \n  s << std::setprecision(write_precision)  // return to previous precision\n    << std::endl;\n}\n\n} // namespace Dakota\n\n", "meta": {"hexsha": "d50dc8fa7f8594cf6df1acdd61461b9cefa01524", "size": 29195, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SensAnalysisGlobal.cpp", "max_stars_repo_name": "jnnccc/Dakota-orb", "max_stars_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SensAnalysisGlobal.cpp", "max_issues_repo_name": "jnnccc/Dakota-orb", "max_issues_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SensAnalysisGlobal.cpp", "max_forks_repo_name": "jnnccc/Dakota-orb", "max_forks_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6311166876, "max_line_length": 97, "alphanum_fraction": 0.6438773763, "num_tokens": 8125, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.23927465983345286}}
{"text": "// Copyright (c) 2015-2018 Daniel Cooke\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef variational_bayes_mixture_model_hpp\n#define variational_bayes_mixture_model_hpp\n\n#include <array>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <iterator>\n#include <cstddef>\n#include <utility>\n#include <cassert>\n#include <limits>\n\n#include <boost/optional.hpp>\n#include <boost/math/special_functions/digamma.hpp>\n\n#include \"utils/maths.hpp\"\n#include \"core/models/haplotype_likelihood_cache.hpp\"\n\n/**\n *\n * This file contains an implementation of the Variational Bayes mixture model\n * used by some genotype models. The notation follows the documentation.\n *\n */\n\nnamespace octopus { namespace model {\n\n// Types needed for Variational Bayes model\n\nstruct VariationalBayesParameters\n{\n    double epsilon;\n    unsigned max_iterations;\n};\n\nusing ProbabilityVector    = std::vector<double>;\nusing LogProbabilityVector = std::vector<double>;\n\ntemplate <std::size_t K>\nusing VBAlpha = std::array<double, K>;\ntemplate <std::size_t K>\nusing VBAlphaVector = std::vector<VBAlpha<K>>;\n\nclass VBReadLikelihoodArray\n{\npublic:\n    using BaseType = HaplotypeLikelihoodCache::LikelihoodVector;\n    \n    VBReadLikelihoodArray() = default;\n    \n    explicit VBReadLikelihoodArray(const BaseType&);\n    \n    VBReadLikelihoodArray(const VBReadLikelihoodArray&)            = default;\n    VBReadLikelihoodArray& operator=(const VBReadLikelihoodArray&) = default;\n    VBReadLikelihoodArray(VBReadLikelihoodArray&&)                 = default;\n    VBReadLikelihoodArray& operator=(VBReadLikelihoodArray&&)      = default;\n    \n    ~VBReadLikelihoodArray() = default;\n    \n    void operator=(const BaseType&);\n    void operator=(std::reference_wrapper<const BaseType>);\n    std::size_t size() const noexcept;\n    BaseType::const_iterator begin() const noexcept;\n    BaseType::const_iterator end() const noexcept;\n    double operator[](const std::size_t n) const noexcept;\n\nprivate:\n    const BaseType* likelihoods;\n};\n\ntemplate <std::size_t K>\nusing VBGenotype = std::array<VBReadLikelihoodArray, K>; // One element per haplotype in genotype (i.e. K)\ntemplate <std::size_t K>\nusing VBGenotypeVector = std::vector<VBGenotype<K>>; // Per element per genotype\ntemplate <std::size_t K>\nusing VBReadLikelihoodMatrix = std::vector<VBGenotypeVector<K>>; // One element per sample\n\ntemplate <std::size_t K>\nusing VBTau = std::array<double, K>; // One element per haplotype in genotype (i.e. K)\ntemplate <std::size_t K>\nusing VBResponsabilityVector = std::vector<VBTau<K>>; // One element per genotype\ntemplate <std::size_t K>\nusing VBResponsabilityMatrix = std::vector<VBResponsabilityVector<K>>; // One element per sample\n\ntemplate <std::size_t K>\nstruct VBLatents\n{\n    ProbabilityVector genotype_posteriors;\n    LogProbabilityVector genotype_log_posteriors;\n    VBAlphaVector<K> alphas;\n    VBResponsabilityMatrix<K> responsabilities;\n};\n\n// Main VB method\n\ntemplate <std::size_t K>\nstd::pair<VBLatents<K>, double>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      const VariationalBayesParameters& params,\n                      std::vector<LogProbabilityVector> seeds);\n\nnamespace detail {\n\nusing VBInverseLikelihood = std::vector<double>; // One element per genotype\nusing VBInverseGenotype = std::vector<VBInverseLikelihood>; // One element per read\ntemplate <std::size_t K>\nusing VBInverseGenotypeVector = std::array<VBInverseGenotype, K>; // One element per haplotype in genotype\ntemplate <std::size_t K>\nusing VBInverseReadLikelihoodMatrix = std::vector<VBInverseGenotypeVector<K>>; // One element per sample\n\ntemplate <std::size_t K>\nauto invert(const VBGenotypeVector<K>& likelihoods)\n{\n    static_assert(K > 0, \"K == 0\");\n    const auto num_genotypes = likelihoods.size();\n    assert(num_genotypes > 0);\n    const auto num_reads = likelihoods.front().front().size();\n    VBInverseGenotypeVector<K> result {};\n    for (std::size_t k {0}; k < K; ++k) {\n        result[k] = VBInverseGenotype(num_reads, VBInverseLikelihood(num_genotypes));\n        for (std::size_t n {0}; n < num_reads; ++n) {\n            for (std::size_t g {0}; g < num_genotypes; ++g) {\n                result[k][n][g] = likelihoods[g][k][n];\n            }\n        }\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nauto invert(const VBReadLikelihoodMatrix<K>& matrix)\n{\n    VBInverseReadLikelihoodMatrix<K> result {};\n    result.reserve(matrix.size());\n    std::transform(std::cbegin(matrix), std::cend(matrix), std::back_inserter(result),\n                   [] (const auto& v) { return invert(v); });\n    return result;\n}\n\ninline ProbabilityVector& exp(const LogProbabilityVector& log_probabilities, ProbabilityVector& result) noexcept\n{\n    std::transform(std::cbegin(log_probabilities), std::cend(log_probabilities), std::begin(result),\n                   [] (const auto lp) noexcept { return std::exp(lp); });\n    return result;\n}\n\ninline ProbabilityVector exp(const LogProbabilityVector& log_probabilities)\n{\n    ProbabilityVector result(log_probabilities.size());\n    return exp(log_probabilities, result);\n}\n\ninline auto sum(const VBAlpha<2>& alpha) noexcept\n{\n    return alpha[0] + alpha[1];\n}\n\ninline auto sum(const VBAlpha<3>& alpha) noexcept\n{\n    return alpha[0] + alpha[1] + alpha[2];\n}\n\ntemplate <std::size_t K>\nauto sum(const VBAlpha<K>& alpha) noexcept\n{\n    return std::accumulate(std::cbegin(alpha), std::cend(alpha), 0.0);\n}\n\ntemplate <typename T>\ninline auto digamma_diff(const T a, const T b)\n{\n    using boost::math::digamma;\n    return digamma(a) - digamma(b);\n}\n\ntemplate <typename T>\ninline T log_sum_exp(const std::array<T, 1>& logs)\n{\n    return logs[0];\n}\n\ntemplate <typename T>\ninline T log_sum_exp(const std::array<T, 2>& logs)\n{\n    return maths::log_sum_exp(logs[0], logs[1]);\n}\n\ntemplate <typename T>\ninline T log_sum_exp(const std::array<T, 3>& logs)\n{\n    return maths::log_sum_exp(logs[0], logs[1], logs[2]);\n}\n\ntemplate <typename T, std::size_t K>\nT log_sum_exp(const std::array<T, K>& logs)\n{\n    return maths::log_sum_exp(logs);\n}\n\ntemplate <std::size_t K>\nauto count_reads(const VBGenotypeVector<K>& likelihoods) noexcept\n{\n    return likelihoods[0][0].size();\n}\n\ntemplate <std::size_t K>\nauto count_reads(const VBInverseGenotypeVector<K>& likelihoods) noexcept\n{\n    return likelihoods[0].size();\n}\n\ntemplate <std::size_t K>\nauto marginalise(const ProbabilityVector& distribution, const VBGenotypeVector<K>& likelihoods,\n                 const unsigned k, const std::size_t n) noexcept\n{\n    return std::inner_product(std::cbegin(distribution), std::cend(distribution),\n                              std::cbegin(likelihoods), 0.0, std::plus<> {},\n                              [k, n] (const auto p, const auto& haplotype_likelihoods) noexcept {\n                                  return p * haplotype_likelihoods[k][n];\n                              });\n}\n\ntemplate <std::size_t K>\nauto marginalise(const ProbabilityVector& distribution, const VBInverseGenotypeVector<K>& likelihoods,\n                 const unsigned k, const std::size_t n) noexcept\n{\n    return std::inner_product(std::cbegin(distribution), std::cend(distribution), std::cbegin(likelihoods[k][n]), 0.0);\n}\n\ntemplate <std::size_t K, typename VBLikelihoodVector_>\nVBResponsabilityVector<K>\ninit_responsabilities(const VBAlpha<K>& prior_alphas,\n                      const ProbabilityVector& genotype_probabilities,\n                      const VBLikelihoodVector_& read_likelihoods)\n{\n    using T = typename VBAlpha<K>::value_type;\n    std::array<T, K> al; // no need to keep recomputing this\n    const auto a0 = sum(prior_alphas);\n    for (unsigned k {0}; k < K; ++k) {\n        al[k] = digamma_diff(prior_alphas[k], a0);\n    }\n    const auto N = count_reads(read_likelihoods);\n    VBResponsabilityVector<K> result(N);\n    std::array<T, K> ln_rho;\n    for (std::size_t n {0}; n < N; ++n) {\n        for (unsigned k {0}; k < K; ++k) {\n            ln_rho[k] = al[k] + marginalise(genotype_probabilities, read_likelihoods, k, n);\n        }\n        const auto ln_rho_norm = log_sum_exp(ln_rho);\n        for (unsigned k {0}; k < K; ++k) {\n            result[n][k] = std::exp(ln_rho[k] - ln_rho_norm);\n        }\n    }\n    return result;\n}\n\ntemplate <std::size_t K, typename VBLikelihoodMatrix>\nVBResponsabilityMatrix<K>\ninit_responsabilities(const VBAlphaVector<K>& prior_alphas,\n                      const ProbabilityVector& genotype_probabilities,\n                      const VBLikelihoodMatrix& read_likelihoods)\n{\n    const auto S = read_likelihoods.size(); // num samples\n    VBResponsabilityMatrix<K> result{};\n    result.reserve(S);\n    for (std::size_t s {0}; s < S; ++s) {\n        result.push_back(init_responsabilities(prior_alphas[s], genotype_probabilities, read_likelihoods[s]));\n    }\n    return result;\n}\n\ntemplate <std::size_t K, typename VBLikelihoodVector_>\nvoid update_responsabilities(VBResponsabilityVector<K>& result,\n                             const VBAlpha<K>& posterior_alphas,\n                             const ProbabilityVector& genotype_probabilities,\n                             const VBLikelihoodVector_& read_likelihoods)\n{\n    using T = typename VBAlpha<K>::value_type;\n    std::array<T, K> al;\n    const auto a0 = sum(posterior_alphas);\n    for (unsigned k {0}; k < K; ++k) {\n        al[k] = digamma_diff(posterior_alphas[k], a0);\n    }\n    const auto N = count_reads(read_likelihoods);\n    std::array<T, K> ln_rho;\n    for (std::size_t n {0}; n < N; ++n) {\n        for (unsigned k {0}; k < K; ++k) {\n            ln_rho[k] = al[k] + marginalise(genotype_probabilities, read_likelihoods, k, n);\n        }\n        const auto ln_rho_norm = log_sum_exp(ln_rho);\n        for (unsigned k {0}; k < K; ++k) {\n            result[n][k] = std::exp(ln_rho[k] - ln_rho_norm);\n        }\n    }\n}\n\n// same as init_responsabilities but in-place\ntemplate <std::size_t K, typename VBLikelihoodMatrix>\nvoid update_responsabilities(VBResponsabilityMatrix<K>& result,\n                             const VBAlphaVector<K>& posterior_alphas,\n                             const ProbabilityVector& genotype_probabilities,\n                             const VBLikelihoodMatrix& read_likelihoods)\n{\n    const auto S = read_likelihoods.size();\n    for (std::size_t s {0}; s < S; ++s) {\n        update_responsabilities(result[s], posterior_alphas[s], genotype_probabilities, read_likelihoods[s]);\n    }\n}\n\ntemplate <std::size_t K>\nauto sum(const VBResponsabilityVector<K>& taus, const unsigned k) noexcept\n{\n    return std::accumulate(std::cbegin(taus), std::cend(taus), 0.0,\n                           [k] (const auto curr, const auto& tau) noexcept {\n                               return curr + tau[k];\n                           });\n}\n\ntemplate <std::size_t K>\nvoid update_alpha(VBAlpha<K>& alpha, const VBAlpha<K>& prior_alpha,\n                  const VBResponsabilityVector<K>& taus) noexcept\n{\n    for (unsigned k {0}; k < K; ++k) {\n        alpha[k] = prior_alpha[k] + sum(taus, k);\n    }\n}\n\ntemplate <std::size_t K>\nvoid update_alphas(VBAlphaVector<K>& alphas, const VBAlphaVector<K>& prior_alphas,\n                   const VBResponsabilityMatrix<K>& responsabilities) noexcept\n{\n    const auto S = alphas.size();\n    assert(S == prior_alphas.size() && S == responsabilities.size());\n    for (std::size_t s {0}; s < S; ++s) {\n        update_alpha(alphas[s], prior_alphas[s], responsabilities[s]);\n    }\n}\n\ntemplate <std::size_t K>\nauto marginalise(const VBResponsabilityVector<K>& responsabilities,\n                 const VBGenotypeVector<K>& read_likelihoods,\n                 const std::size_t g) noexcept\n{\n    double result {0};\n    const auto N = read_likelihoods[0][0].size(); // num reads in sample s\n    assert(responsabilities.size() == N);\n    assert(responsabilities[0].size() == K && read_likelihoods[g].size() == K);\n    for (unsigned k {0}; k < K; ++k) {\n        const auto& k_likelihoods = read_likelihoods[g][k];\n        for (std::size_t n {0}; n < N; ++n) {\n            result += responsabilities[n][k] * k_likelihoods[n];\n        }\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nauto marginalise(const VBResponsabilityMatrix<K>& responsabilities,\n                 const VBReadLikelihoodMatrix<K>& read_likelihoods,\n                 const std::size_t g) noexcept\n{\n    double result {0};\n    const auto S = read_likelihoods.size(); // num samples\n    assert(S == responsabilities.size());\n    for (std::size_t s {0}; s < S; ++s) {\n        result += marginalise(responsabilities[s], read_likelihoods[s], g);\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nvoid update_genotype_log_posteriors(LogProbabilityVector& result,\n                                    const LogProbabilityVector& genotype_log_priors,\n                                    const VBResponsabilityMatrix<K>& responsabilities,\n                                    const VBReadLikelihoodMatrix<K>& read_likelihoods)\n{\n    const auto G = result.size();\n    for (std::size_t g {0}; g < G; ++g) {\n        result[g] = genotype_log_priors[g] + marginalise(responsabilities, read_likelihoods, g);\n    }\n    maths::normalise_logs(result);\n}\n\ninline auto max_change(const VBAlpha<2>& lhs, const VBAlpha<2>& rhs) noexcept\n{\n    return std::max(std::abs(lhs.front() - rhs.front()), std::abs(lhs.back() - rhs.back()));\n}\n\ninline auto max_change(const VBAlpha<3>& lhs, const VBAlpha<3>& rhs) noexcept\n{\n    return std::max({std::abs(lhs[0] - rhs[0]), std::abs(lhs[1] - rhs[1]), std::abs(lhs[2] - rhs[2])});\n}\n\ntemplate <std::size_t K>\nauto max_change(const VBAlpha<K>& lhs, const VBAlpha<K>& rhs) noexcept\n{\n    double result {0};\n    for (std::size_t k {0}; k < K; ++k) {\n        const auto curr = std::abs(lhs[k] - rhs[k]);\n        if (curr > result) result = curr;\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nauto max_change(const VBAlphaVector<K>& prior_alphas, const VBAlphaVector<K>& posterior_alphas) noexcept\n{\n    const auto S = prior_alphas.size();\n    assert(S == posterior_alphas.size());\n    double result {0};\n    for (std::size_t s {0}; s < S; ++s) {\n        const auto curr = max_change(prior_alphas[s], posterior_alphas[s]);\n        if (curr > result) result = curr;\n    }\n    return result;\n}\n\ntemplate <std::size_t K>\nstd::pair<bool, double> check_convergence(const VBAlphaVector<K>& prior_alphas,\n                                          const VBAlphaVector<K>& posterior_alphas,\n                                          const double prev_max_change,\n                                          const double epsilon) noexcept\n{\n    const auto new_max_change = max_change(prior_alphas, posterior_alphas);\n    return std::make_pair(std::abs(new_max_change - prev_max_change) < epsilon, new_max_change);\n}\n\ntemplate <std::size_t K>\nauto entropy(const VBTau<K>& tau) noexcept\n{\n    return -std::accumulate(std::cbegin(tau), std::cend(tau), 0.0,\n                            [] (const auto curr, const auto t) noexcept { return curr + (t * std::log(t)); });\n}\n\n// E [ln q(Z_s)]\ntemplate <std::size_t K>\nauto sum_entropies(const VBResponsabilityVector<K>& taus) noexcept\n{\n    return std::accumulate(std::cbegin(taus), std::cend(taus), 0.0,\n                           [] (const auto curr, const auto& tau) noexcept { return curr + entropy(tau); });\n}\n\ntemplate <std::size_t K>\nauto calculate_evidence_lower_bound(const VBAlphaVector<K>& prior_alphas,\n                                    const VBAlphaVector<K>& posterior_alphas,\n                                    const LogProbabilityVector& genotype_log_priors,\n                                    const ProbabilityVector& genotype_posteriors,\n                                    const LogProbabilityVector& genotype_log_posteriors,\n                                    const VBResponsabilityMatrix<K>& taus,\n                                    const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                                    const boost::optional<double> max_posterior_skip = boost::none)\n{\n    const auto G = genotype_log_priors.size();\n    const auto S = log_likelihoods.size();\n    double result {0};\n    for (std::size_t g {0}; g < G; ++g) {\n        if (!max_posterior_skip || genotype_posteriors[g] >= *max_posterior_skip) {\n            auto w = genotype_log_priors[g] - genotype_log_posteriors[g];\n            for (std::size_t s {0}; s < S; ++s) {\n                const auto N_s = taus[s].size();\n                for (std::size_t k {0}; k < K; ++k) {\n                    for (std::size_t n {0}; n < N_s; ++n) {\n                        w += taus[s][n][k] * log_likelihoods[s][g][k][n];\n                    }\n                }\n            }\n            result += genotype_posteriors[g] * w;\n        }\n    }\n    for (std::size_t s {0}; s < S; ++s) {\n        result += (maths::log_beta(posterior_alphas[s]) - maths::log_beta(prior_alphas[s]));\n        result += sum_entropies(taus[s]);\n    }\n    return result;\n}\n\n// Main algorithm - single seed\n\n// Starting iteration with given genotype_log_posteriors\ntemplate <std::size_t K, typename VBLikelihoodMatrix1, typename VBLikelihoodMatrix2>\nVBLatents<K>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBLikelihoodMatrix1& log_likelihoods1,\n                      const VBLikelihoodMatrix2& log_likelihoods2,\n                      LogProbabilityVector genotype_log_posteriors,\n                      const VariationalBayesParameters& params)\n{\n    assert(!prior_alphas.empty());\n    assert(!genotype_log_priors.empty());\n    assert(!log_likelihoods1.empty());\n    assert(log_likelihoods1.size() == log_likelihoods2.size());\n    assert(prior_alphas.size() == log_likelihoods1.size()); // num samples\n    assert(log_likelihoods1.front().size() == genotype_log_priors.size()); // num genotypes\n    assert(params.max_iterations > 0);\n    auto genotype_posteriors = exp(genotype_log_posteriors);\n    auto posterior_alphas = prior_alphas;\n    auto responsabilities = init_responsabilities<K>(posterior_alphas, genotype_posteriors, log_likelihoods2);\n    assert(responsabilities.size() == log_likelihoods1.size()); // num samples\n    auto prev_evidence = std::numeric_limits<double>::lowest();\n    bool is_converged {};\n    double max_change {};\n    for (unsigned i {0}; i < params.max_iterations; ++i) {\n        update_genotype_log_posteriors(genotype_log_posteriors, genotype_log_priors, responsabilities, log_likelihoods1);\n        exp(genotype_log_posteriors, genotype_posteriors);\n        update_alphas(posterior_alphas, prior_alphas, responsabilities);\n        update_responsabilities(responsabilities, posterior_alphas, genotype_posteriors, log_likelihoods2);\n        std::tie(is_converged, max_change) = check_convergence(prior_alphas, posterior_alphas, max_change, params.epsilon);\n        if (is_converged) break;\n        auto curr_evidence = calculate_evidence_lower_bound(prior_alphas, posterior_alphas, genotype_log_priors,\n                                                            genotype_posteriors, genotype_log_posteriors, responsabilities,\n                                                            log_likelihoods1, 1e-10);\n        if (curr_evidence <= prev_evidence || (curr_evidence - prev_evidence) < params.epsilon) break;\n        prev_evidence = curr_evidence;\n    }\n    return VBLatents<K> {\n        std::move(genotype_posteriors), std::move(genotype_log_posteriors),\n        std::move(posterior_alphas), std::move(responsabilities)\n    };\n}\n\n// Not using inverted log likelihoods\ntemplate <std::size_t K>\nVBLatents<K>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      LogProbabilityVector genotype_log_posteriors,\n                      const VariationalBayesParameters& params)\n{\n    return run_variational_bayes(prior_alphas, genotype_log_posteriors, log_likelihoods,\n                                 log_likelihoods, genotype_log_posteriors, params);\n}\n\n// Main algorithm - multiple seed\n\ntemplate <std::size_t K>\nbool run_vb_with_matrix_inversion(const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                                  const VariationalBayesParameters& params,\n                                  const std::vector<LogProbabilityVector>& seeds) noexcept\n{\n    return true;\n}\n\ntemplate <std::size_t K>\nstd::vector<VBLatents<K>>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      const VariationalBayesParameters& params,\n                      std::vector<LogProbabilityVector>&& seeds)\n{\n    std::vector<VBLatents<K>> result {};\n    result.reserve(seeds.size());\n    if (run_vb_with_matrix_inversion(log_likelihoods, params, seeds)) {\n        const auto inverted_log_likelihoods = invert(log_likelihoods);\n        for (auto& seed : seeds) {\n            result.push_back(detail::run_variational_bayes(prior_alphas, genotype_log_priors,\n                                                           log_likelihoods, inverted_log_likelihoods,\n                                                           std::move(seed), params));\n        }\n    } else {\n        for (auto& seed : seeds) {\n            result.push_back(detail::run_variational_bayes(prior_alphas, genotype_log_priors,\n                                                           log_likelihoods,\n                                                           std::move(seed), params));\n        }\n    }\n    return result;\n}\n\n// lower-bound calculation\n\ntemplate <std::size_t K>\nauto calculate_evidence_lower_bound(const VBAlphaVector<K>& prior_alphas,\n                                    const LogProbabilityVector& genotype_log_priors,\n                                    const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                                    const VBLatents<K>& latents)\n{\n    return calculate_evidence_lower_bound(prior_alphas, latents.alphas, genotype_log_priors,\n                                          latents.genotype_posteriors, latents.genotype_log_posteriors,\n                                          latents.responsabilities, log_likelihoods);\n    \n}\n\ntemplate <std::size_t K>\nstd::pair<VBLatents<K>, double>\nget_max_evidence_latents(const VBAlphaVector<K>& prior_alphas,\n                         const LogProbabilityVector& genotype_log_priors,\n                         const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                         std::vector<VBLatents<K>>&& latents)\n{\n    std::vector<double> seed_evidences(latents.size());\n    std::transform(std::cbegin(latents), std::cend(latents), std::begin(seed_evidences),\n                   [&] (const auto& seed_latents) {\n                       return calculate_evidence_lower_bound(prior_alphas, genotype_log_priors, log_likelihoods, seed_latents);\n                   });\n    const auto max_itr = std::max_element(std::cbegin(seed_evidences), std::cend(seed_evidences));\n    const auto max_idx = std::distance(std::cbegin(seed_evidences), max_itr);\n    return std::make_pair(std::move(latents[max_idx]), *max_itr);\n}\n\n} // namespace detail\n\ntemplate <std::size_t K>\nstd::pair<VBLatents<K>, double>\nrun_variational_bayes(const VBAlphaVector<K>& prior_alphas,\n                      const LogProbabilityVector& genotype_log_priors,\n                      const VBReadLikelihoodMatrix<K>& log_likelihoods,\n                      const VariationalBayesParameters& params,\n                      std::vector<LogProbabilityVector> seeds)\n{\n    assert(!seeds.empty());\n    auto latents = detail::run_variational_bayes(prior_alphas, genotype_log_priors, log_likelihoods, params, std::move(seeds));\n    return detail::get_max_evidence_latents(prior_alphas, genotype_log_priors, log_likelihoods, std::move(latents));\n}\n\ninline VBReadLikelihoodArray::VBReadLikelihoodArray(const BaseType& underlying_likelihoods)\n: likelihoods{std::addressof(underlying_likelihoods)} {}\n\ninline void VBReadLikelihoodArray::operator=(const BaseType& other)\n{\n    likelihoods = std::addressof(other);\n}\n\ninline void VBReadLikelihoodArray::operator=(std::reference_wrapper<const BaseType> other)\n{\n    likelihoods = std::addressof(other.get());\n}\n\ninline std::size_t VBReadLikelihoodArray::size() const noexcept\n{\n    return likelihoods->size();\n}\n\ninline VBReadLikelihoodArray::BaseType::const_iterator VBReadLikelihoodArray::begin() const noexcept\n{\n    return likelihoods->begin();\n}\n\ninline VBReadLikelihoodArray::BaseType::const_iterator VBReadLikelihoodArray::end() const noexcept\n{\n    return likelihoods->end();\n}\n\ninline double VBReadLikelihoodArray::operator[](const std::size_t n) const noexcept\n{\n    return likelihoods->operator[](n);\n}\n\n} // namespace model\n} // namespace octopus\n\n#endif\n", "meta": {"hexsha": "4a80afaa4e8dc011c4e70c2f5a4887e0ba3814af", "size": 25113, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/models/genotype/variational_bayes_mixture_model.hpp", "max_stars_repo_name": "alimanfoo/octopus", "max_stars_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-08-21T23:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T23:34:28.000Z", "max_issues_repo_path": "src/core/models/genotype/variational_bayes_mixture_model.hpp", "max_issues_repo_name": "alimanfoo/octopus", "max_issues_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/models/genotype/variational_bayes_mixture_model.hpp", "max_forks_repo_name": "alimanfoo/octopus", "max_forks_repo_head_hexsha": "f3cc3f567f02fafe33f5a06e5be693d6ea985ee3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9924357035, "max_line_length": 127, "alphanum_fraction": 0.6463584598, "num_tokens": 6022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.23919817393835982}}
{"text": "\n//          Copyright Gavin Band 2008 - 2012.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          http://www.boost.org/LICENSE_1_0.txt)\n\n#include <string>\n#include <memory>\n#include <set>\n#include <map>\n#include <utility>\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n#include <boost/foreach.hpp>\n#define foreach BOOST_FOREACH\n#include <boost/regex.hpp>\n#include <boost/math/distributions/hypergeometric.hpp>\n#include \"appcontext/CmdLineOptionProcessor.hpp\"\n#include \"appcontext/ApplicationContext.hpp\"\n#include \"appcontext/ProgramFlow.hpp\"\n#include \"appcontext/get_current_time_as_string.hpp\"\n#include \"genfile/FileUtils.hpp\"\n#include \"genfile/utility.hpp\"\n#include \"statfile/BuiltInTypeStatSource.hpp\"\n#include <Eigen/Core>\n\nnamespace globals {\n\tstd::string const program_name = \"overrep\" ;\n\tstd::string const program_version = \"0.1\" ;\n}\n\nstruct OverrepOptions: public appcontext::CmdLineOptionProcessor {\n\tstd::string get_program_name() const { return globals::program_name ; }\n\n\tvoid declare_options( appcontext::OptionProcessor& options ) {\n\t\toptions.set_help_option( \"-help\" ) ;\n\n\t\toptions.declare_group( \"File handling options\" ) ;\n\t\toptions[ \"-p\" ]\n\t\t\t.set_description( \"Specify the path of a file containing pathway definitions to load.\"\n\t\t\t \t\" This file must have at least three columns; the first should be an identifier for the pathway (no whitespace),\"\n\t\t\t\t\" the second should be the pathway name, and the third should contain gene identifiers.\" )\n\t\t\t.set_takes_values_until_next_option()\n\t\t\t.set_minimum_multiplicity( 1 )\n\t\t\t.set_maximum_multiplicity( 100 )\n\t\t;\n\n\t\toptions[ \"-c\" ]\n\t\t\t.set_description( \"Specify the path of a file containing gene clusters to load.\" )\n\t\t\t.set_takes_single_value()\n\t\t;\n\n\t\toptions[ \"-u\" ]\n\t\t\t.set_description( \"Specify the path of a file containing a list of genes to treat as the gene \\\"universe\\\".\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_is_required()\n\t\t;\n\n\t\toptions[ \"-g\" ]\n\t\t\t.set_description( \"Specify the path of a file containing a list of genes to test with.\" )\n\t\t\t.set_takes_single_value()\n\t\t;\n\n\t\toptions.declare_group( \"Miscellaneous options\" ) ;\n\t\toptions[ \"-P-value\" ]\n\t\t\t.set_description( \"Output lists of genes for all pathways getting this P-value or better.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( 0.000001 )\n\t\t;\n\t\toptions[ \"-analysis-name\" ]\n\t\t\t.set_description( \"Specify a name to label results from this analysis with.  (This applies to modules which store their results in a qcdb file.)\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_is_required() ;\n\n\t\toptions[ \"-intersect\" ]\n\t\t\t.set_description( \"Specify that the universe should only include genes that actuall occur in pathways.\" ) ;\n\n\t\toptions[ \"-log\" ]\n\t\t\t.set_description( \"Specify the path of the log file.\" )\n\t\t\t.set_takes_single_value()\n\t\t\t.set_default_value( \"overrep.log\" ) ;\n\t}\n} ;\n\n// Fisher's exact test between categories\n//               red           black\n//     good |     a      |       b        |\n//      bad |     c      |       d        |\n//\n// Under the null that both rows are distributed the same, a is hypergeometrically\n// distributed.  Fishers' p-value is then the mass under the hypergeometric distribution\n// of all values of a greater than or equal to the one given that are consistent with\n// the given margins of the table.\nstruct FishersExactTest {\n\tFishersExactTest( Eigen::Matrix2d const& matrix ):\n\t\tm_matrix( matrix ),\n\t\tm_distribution( m_matrix.col( 0 ).sum(), m_matrix.row( 0 ).sum(), m_matrix.sum() )\n\t{}\n\t\n\tdouble get_OR() const {\n\t\treturn ( m_matrix(0,0) * m_matrix(1,1) ) / ( m_matrix(0,1)*m_matrix(1,0) ) ;\n\t}\n\n\tstd::pair< double, double > get_confidence_interval() const {\n\t\tassert(0) ;\n\t}\n\n\tdouble get_pvalue() const {\n\t\tusing boost::math::cdf ;\n\t\tusing boost::math::complement ;\n\n\t\tif( m_matrix(0,0) == 0 ) {\n\t\t\treturn 1 ;\n\t\t} else {\n\t\t\treturn cdf( complement( m_distribution, m_matrix( 0, 0 ) - 1.0 )) ;\n\t\t}\n\t}\n\n\tprivate:\n\t\tEigen::Matrix2d const m_matrix ;\n\t\tboost::math::hypergeometric m_distribution ;\n} ;\n\nvoid load_list_of_strings( std::string const& filename, boost::function< void ( std::string const& ) > setter ) {\n\tstd::auto_ptr< std::istream > f = genfile::open_text_file_for_input( filename ) ;\n\tstd::string element ;\n\twhile( (*f) >> element ) {\n\t\tsetter( element ) ;\n\t}\n}\n\nvoid load_pathways_list(\n\tstatfile::BuiltInTypeStatSource& source,\n\tboost::function< void ( std::string const&, std::string const& ) > set_pathway_name,\n\tboost::function< void ( std::string const&, std::string const& ) > set_pathway_gene\n) {\n\tstd::string pathway_id ;\n\tstd::string pathway_name ;\n\tstd::string gene_id ;\n\twhile( source >> pathway_id ) {\n\t\tsource >> pathway_name >> gene_id >> statfile::ignore_all() ;\n\t\tset_pathway_name( pathway_id, pathway_name ) ;\n\t\tset_pathway_gene( pathway_id, gene_id ) ;\n\t}\n}\n\nvoid load_clusters(\n\tstatfile::BuiltInTypeStatSource& source,\n\tboost::function< void ( std::string const&, std::string const& ) > set_cluster_member = boost::function< void ( std::string const&, std::string const& ) >(),\n\tboost::function< void ( std::string const&, std::string const& ) > set_cluster_comment = boost::function< void ( std::string const&, std::string const& ) >()\n) {\n\tstd::string cluster_id ;\n\tstd::string cluster_comment ;\n\tstd::string gene_regexp ;\n\twhile( source >> cluster_id ) {\n\t\tsource >> gene_regexp >> cluster_comment >> statfile::ignore_all() ;\n\t\tif( set_cluster_comment ) {\n\t\t\tset_cluster_comment( cluster_id, cluster_comment ) ;\n\t\t}\n\t\tif( set_cluster_member ) {\n\t\t\tset_cluster_member( cluster_id, gene_regexp ) ;\n\t\t}\n\t}\n}\n\nnamespace impl {\n\tstruct MapSetter {\n\t\ttypedef std::string A ;\n\t\ttypedef std::string B ;\n\t\ttypedef std::map< A, B > Map ;\n\t\tMapSetter( Map& map ): m_map( &map ) {} ;\n\t\tMapSetter( MapSetter const& other ): m_map( other.m_map ) {} ;\n\t\tMapSetter& operator=( MapSetter const& other ) {\n\t\t\tm_map = other.m_map ;\n\t\t\treturn *this ;\n\t\t} \n\t\t\n\t\tvoid operator()( std::string const& left, std::string const& right ) const {\n\t\t\t(*m_map)[ left ] = right ;\n\t\t}\n\t\t\n\tprivate:\n\t\tMap* m_map ;\n\t} ;\n\t\n\tstruct MapSetSetter {\n\t\ttypedef std::string A ;\n\t\ttypedef std::set< std::string > B ;\n\t\ttypedef std::map< A, B > Map ;\n\t\tMapSetSetter( Map& map ): m_map( &map ) {} ;\n\t\tMapSetSetter( MapSetSetter const& other ): m_map( other.m_map ) {} ;\n\t\tMapSetSetter& operator=( MapSetSetter const& other ) {\n\t\t\tm_map = other.m_map ;\n\t\t\treturn *this ;\n\t\t} \n\t\t\n\t\tvoid operator()( std::string const& left, std::string const& right ) const {\n\t\t\t(*m_map)[ left ].insert( right ) ;\n\t\t}\n\t\t\n\tprivate:\n\t\tmutable Map* m_map ;\n\t} ;\n\t\n\ttemplate< typename Container >\n\tvoid insert_into( typename Container::value_type const& value, Container* X ) {\n\t\tX->insert( value ) ;\n\t}\n\t\n\ttemplate< typename Container >\n\tbool in( typename Container::value_type const& value, Container const& X ) {\n\t\treturn X.find( value ) != X.end() ;\n\t}\n}\n\nstruct OverrepApplication: public appcontext::ApplicationContext {\npublic:\n\tOverrepApplication( int argc, char **argv ):\n\t\tappcontext::ApplicationContext(\n\t\t\tglobals::program_name,\n\t\t\tglobals::program_version,\n\t\t\tstd::auto_ptr< appcontext::OptionProcessor >( new OverrepOptions ),\n\t\t\targc,\n\t\t\targv,\n\t\t\t\"-log\"\n\t\t)\n\t{}\n\t\n\tvoid process() {\n\t\tunsafe_process() ;\n\t}\n\t\nprivate:\n\ttypedef std::set< std::string > StringSet ;\n\ttypedef std::map< std::string, std::string > StringStringMap ;\n\ttypedef std::map< std::string, std::set< std::string > > StringStringSetMap ;\n\n\tvoid unsafe_process() {\n\t\tload_data() ;\n\t\tm_cluster_mapping = get_cluster_mapping() ;\n\t\tmap_genes_through_clusters( m_cluster_mapping ) ;\n\n\t\tsummarise() ;\n\t\t\n\t\trun_tests() ;\n\t}\n\n\tvoid load_data() {\n\t\tStringStringMap pathway_names ;\n\t\tStringStringSetMap pathway_members ;\n\t\tStringStringSetMap clusters ;\n\t\tStringStringMap cluster_descriptions ;\n\t\tStringSet universe ;\n\t\tStringSet test_genes ;\n\t\t\n\t\n\t\tassert( options().check( \"-u\" ) ) ;\t\n\t\tif( options().check( \"-u\" )) {\n\t\t\tload_list_of_strings(\n\t\t\t\toptions().get< std::string >( \"-u\" ),\n\t\t\t\tboost::bind(\n\t\t\t\t\t&impl::insert_into< StringSet >,\n\t\t\t\t\t_1,\n\t\t\t\t\t&universe\n\t\t\t\t)\n\t\t\t) ;\n\n\t\t\tget_ui_context().logger()\n\t\t\t\t<< \"I loaded \" << universe.size() << \" universe genes.  First few are:\\n\" ;\n\t\t\tStringSet::const_iterator\n\t\t\t\ti = universe.begin(),\n\t\t\t\tend_i = universe.end() ;\n\t\t\tfor( std::size_t count = 0; count < 5 && i != end_i; ++count, ++i ) {\n\t\t\t\tget_ui_context().logger() << \"  \" << *i << \"\\n\" ;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif( options().check( \"-c\" )) {\n\t\t\tstatfile::BuiltInTypeStatSource::UniquePtr source = statfile::BuiltInTypeStatSource::open(\n\t\t\t\toptions().get< std::string >( \"-c\" )\n\t\t\t) ;\n\t\t\tload_clusters(\n\t\t\t\t*source,\n\t\t\t\timpl::MapSetSetter( clusters ),\n\t\t\t\timpl::MapSetter( cluster_descriptions )\n\t\t\t) ;\n\t\t\tget_ui_context().logger() << \"Loaded \" << clusters.size() << \" clusters:\\n\" ;\n\t\t\tforeach( StringStringSetMap::value_type const& elt, clusters ) {\n\t\t\t\tget_ui_context().logger()\n\t\t\t\t\t<< \"  \" << elt.first << \": \" ;\n\t\t\t\tforeach( StringSet::value_type const& value, elt.second ) {\n\t\t\t\t\tget_ui_context().logger() << value << \" \" ;\n\t\t\t\t}\n\t\t\t\tget_ui_context().logger() << \"\\n\" ;\n\t\t\t}\n\t\t}\n\n\t\tif( options().check( \"-p\" )) {\n\t\t\tstd::vector< std::string > elts = options().get_values< std::string >( \"-p\" ) ;\n\t\t\tforeach( std::string const& elt, elts ) {\n\t\t\t\tstatfile::BuiltInTypeStatSource::UniquePtr source = statfile::BuiltInTypeStatSource::open(\n\t\t\t\t\tgenfile::wildcard::find_files_by_chromosome( elt )\n\t\t\t\t) ;\n\t\t\t\tload_pathways_list(\n\t\t\t\t\t*source,\n\t\t\t\t\timpl::MapSetter( pathway_names ),\n\t\t\t\t\timpl::MapSetSetter( pathway_members )\n\t\t\t\t) ;\n\t\t\t}\n\n\t\t\ttypedef std::pair< std::string, std::set< std::string > > StringStringSet ;\n\t\t\tif( options().check( \"-intersect\" )) {\n\t\t\t\tStringSet pathway_universe ;\n\t\t\t\tforeach( StringStringSet const& entry, pathway_members ) {\n\t\t\t\t\tpathway_universe.insert( entry.second.begin(), entry.second.end() ) ;\n\t\t\t\t}\n\t\t\t\tget_ui_context().logger() << \"Created pathway universe of \" << universe.size() << \" genes based on all genes in pathways.\\n\" ;\n\t\t\t\tstd::size_t const N = universe.size() ;\n\t\t\t\tuniverse = genfile::utility::intersect( universe, pathway_universe ) ;\n\t\t\t\tget_ui_context().logger() << \"Formed intersection with universe (\" << universe.size() << \" of \" << N << \" in original universe.\\n\" ;\n\t\t\t\t\n\t\t\t}\n\n\t\t\tstd::map< std::string, StringSet > universe_pathway_members ;\n\t\t\tforeach( StringStringSet const& entry, pathway_members ) {\n\t\t\t\tuniverse_pathway_members[ entry.first ] = genfile::utility::intersect( entry.second, universe ) ;\n\t\t\t}\n\t\t\t\n\t\t\tget_ui_context().logger()\n\t\t\t\t<< \"I loaded \" << pathway_names.size() << \" pathways.  First few are:\\n\" ;\n\t\t\tstd::map< std::string, std::string >::const_iterator\n\t\t\t\tpathway_i = pathway_names.begin(),\n\t\t\t\tpathway_end = pathway_names.end() ;\n\t\t\tfor( std::size_t count = 0; count < 5 && pathway_i != pathway_end; ++count, ++pathway_i ) {\n\t\t\t\tget_ui_context().logger() << \"  \" << pathway_i->first << \": \" << pathway_i->second\n\t\t\t\t\t<< \" (\" << pathway_members[pathway_i->first].size()\n\t\t\t\t\t<< \" genes of which \"\n\t\t\t\t\t<< universe_pathway_members[pathway_i->first].size()\n\t\t\t\t\t<<\" are in the universe)\\n\" ;\n\t\t\t}\n\t\t\t\n\t\t\tpathway_members = universe_pathway_members ;\n\t\t}\n\t\t\n\t\tif( options().check( \"-g\" )) {\n\t\t\tload_list_of_strings(\n\t\t\t\toptions().get< std::string >( \"-g\" ),\n\t\t\t\tboost::bind(\n\t\t\t\t\timpl::insert_into< StringSet >,\n\t\t\t\t\t_1,\n\t\t\t\t\t&test_genes\n\t\t\t\t)\n\t\t\t) ;\n\t\t\t\n\t\t\tget_ui_context().logger()\n\t\t\t\t<< \"I loaded \" << test_genes.size() << \" test genes \" ;\n\t\t\ttest_genes = genfile::utility::intersect( test_genes, universe ) ;\n\t\t\tget_ui_context().logger()\n\t\t\t\t<< \"of which \" << test_genes.size() << \" are in the universe.  First few are:\\n\" ;\n\t\t\tStringSet::const_iterator\n\t\t\t\ti = test_genes.begin(),\n\t\t\t\tend_i = test_genes.end() ;\n\t\t\tfor( std::size_t count = 0; count < 5 && i != end_i; ++count, ++i ) {\n\t\t\t\tget_ui_context().logger() << \"  \" << *i << \"\\n\" ;\n\t\t\t}\n\t\t}\n\t\t\n\t\tm_pathway_names = pathway_names ;\n\t\tm_pathway_members = pathway_members ;\n\t\tm_clusters = clusters ;\n\t\tm_cluster_descriptions = cluster_descriptions ;\n\t\tm_universe = universe ;\n\t\tm_test_genes = test_genes ;\n\t}\n\t\n\tStringStringMap get_cluster_mapping() {\n\t\tget_ui_context().logger() << \"Computing gene->cluster mapping...\\n\" ;\n\t\tStringStringMap result ;\n\t\tforeach( StringStringSetMap::value_type const& cluster, m_clusters ) {\n\t\t\tforeach( std::string const& regex_string, cluster.second ) {\n\t\t\t\tboost::regex regex( regex_string ) ;\n\t\t\t\tStringStringMap const& this_map = get_cluster_mapping( regex, cluster.first ) ;\n\t\t\t\tresult.insert( this_map.begin(), this_map.end() ) ;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn result ;\n\t}\n\t\n\tStringStringMap get_cluster_mapping( boost::regex const& regex, std::string const& replacement ) {\n\t\tStringStringMap result ;\n\t\tget_cluster_mapping( m_universe, regex, replacement, boost::bind( impl::insert_into< StringStringMap >, _1, &result )) ;\n\t\tget_cluster_mapping( m_test_genes, regex, replacement, boost::bind( impl::insert_into< StringStringMap >, _1, &result )) ;\n\t\tforeach( StringStringSetMap::value_type& value, m_pathway_members ) {\n\t\t\tget_cluster_mapping( value.second, regex, replacement, boost::bind( impl::insert_into< StringStringMap >, _1, &result )) ;\n\t\t}\n\t\treturn result ;\n\t}\n\n\t\n\tvoid get_cluster_mapping(\n\t\tStringSet& values,\n\t\tboost::regex const& regex,\n\t\tstd::string const& replacement,\n\t\tboost::function< void ( std::pair< std::string, std::string > const& ) > output\n\t) {\n\t\tStringSet::iterator i = values.begin(), end_i = values.end() ;\n\t\tfor( ; i != end_i; ++i ) {\n\t\t\tstd::string value = *i ;\n\t\t\tvalue = boost::regex_replace( value, regex, replacement ) ;\n\t\t\tif( value != *i ) {\n\t\t\t\toutput( std::make_pair( *i, value ) ) ;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid map_genes_through_clusters( StringStringMap const& mapping ) {\n\t\tget_ui_context().logger() << \"Mapping genes through clusters...\\n\" ;\n\t\tstd::size_t n = m_universe.size() ;\n\t\tm_universe = map_genes_through_clusters( mapping, m_universe ) ;\n\t\tget_ui_context().logger() << \"Mapped \" << n << \" genes to \" << m_universe.size() << \" in universe.\\n\" ;\n\t\tn = m_test_genes.size() ;\n\t\tm_test_genes = map_genes_through_clusters( mapping, m_test_genes ) ;\n\t\tget_ui_context().logger() << \"Mapped \" << n << \" genes to \" << m_test_genes.size() << \" in test genes.\\n\" ;\n\t\tforeach( StringStringSetMap::value_type& value, m_pathway_members ) {\n\t\t\tvalue.second = map_genes_through_clusters( mapping, value.second ) ;\n\t\t}\n\t}\n\n\tStringSet map_genes_through_clusters( StringStringMap const& mapping, StringSet const& genes ) {\n\t\tStringSet result ;\n\t\tforeach( StringSet::value_type const& value, genes ) {\n\t\t\tStringStringMap::const_iterator where = mapping.find( value ) ;\n\t\t\tif( where != mapping.end() ) {\n\t\t\t\tresult.insert( where->second ) ;\n\t\t\t} else {\n\t\t\t\tresult.insert( value ) ;\n\t\t\t}\n        }\n\t\treturn result ;\n\t}\n\n\tvoid summarise() {\n\t\tget_ui_context().logger() << \"\\n-------------------------\\n\\n\" ;\n\t\tif( m_clusters.size() > 0 ) {\n\t\t\tget_ui_context().logger() << std::setw( 12 ) << \"Cluster mapping:\\n\" ;\n            StringStringSetMap backMap ;\n\t\t\tforeach( StringStringMap::value_type const& key_value, m_cluster_mapping ) {\n                backMap[ key_value.second ].insert( key_value.first ) ;\n\t\t\t}\n            foreach( StringStringSetMap::value_type const& k, backMap ) {\n                get_ui_context().logger() << std::setw( 12 ) << k.first << \":\" ;\n\t\t\t\tstd::size_t count = 0 ;\n\t\t\t\tfor( StringSet::const_iterator i = k.second.begin(); i != k.second.end(); ++i, ++count ) {\n                    get_ui_context().logger() << \" \" << *i ;\n\t\t\t\t\tif( count == 10 ) {\n\t\t\t\t\t\tget_ui_context().logger() << \" (+ \" << k.second.size() - 10 << \" others)...\" ;\n\t\t\t\t\t\tbreak ;\n\t\t\t\t\t}\n                }\n                get_ui_context().logger() << \"\\n\" ;\n            }\n\t\t}\n#if 0\n\t\tif( m_clusters.size() > 0 ) {\n\t\t\tget_ui_context().logger() << std::setw( 12 ) << \"Cluster mapping:\\n\" ;\n\t\t\tforeach( StringStringMap::value_type const& key_value, m_cluster_mapping ) {\n\t\t\t\tget_ui_context().logger() << std::setw( 12 ) << key_value.first << \": \"  << key_value.second << \"\\n\" ;\n\t\t\t}\n\t\t}\n#endif\n\t\tget_ui_context().logger() << std::setw( 12 ) << \"Test genes:\" << \"  \" << m_test_genes.size() << \" genes\\n\" ;\n\t\tget_ui_context().logger() << std::setw( 12 ) << \"Pathways:\" << \"  \" << m_pathway_names.size() << \" pathways\\n\" ;\n\t\tget_ui_context().logger() << std::setw( 12 ) << \"Universe:\" << \"  \" << m_universe.size() << \" genes\\n\" ;\n\t}\n\n\tvoid run_tests() {\n\t\t// table is\n\t\t//                 in pathway | not in pathway |  \n\t\t//     test gene |     a      |       b        |\n\t\t// Not test gene |     c      |       d        |\n\t\t//\n\t\tEigen::Matrix2d table ;\n\t\t\n\t\tusing std::setw ;\n\t\tstd::string const tab = \"\\t\" ;\n\t\tstd::cout\n\t\t//get_ui_context().logger()\n\t\t\t<< \"analysis\" << tab\n\t\t\t<< \"pathway id\" << tab\n\t\t\t<< \"pathway name\" << tab\n\t\t\t<< \"hits in pathway\" << tab\n\t\t\t<< \"hits not in pathway\" << tab\n\t\t\t<< \"nonhits in pathway\" << tab\n\t\t\t<< \"nonhits not in pathway\" << tab\n\t\t\t<< \"total in pathway\" << tab\n\t\t\t<< \"total genes\" << tab\n\t\t\t<< \"sample odds ratio\" << tab\n\t\t\t<< \"fishers exact test p value\" << tab\n\t\t\t<< \"ids.of.hits.in.pathway\"\n\t\t\t<< \"\\n\" ;\n\n\t\tstd::string const analysis = options().get< std::string >( \"-analysis-name\" ) ;\n\t\tdouble const pvalue_threshhold = options().get< double >( \"-P-value\" ) ;\n\t\tstd::ostringstream hit_genes_in_pathway ;\n\t\tforeach( StringStringSetMap::value_type const& pathway, m_pathway_members ) {\n\t\t\thit_genes_in_pathway.str( \"\" ) ;\n\t\t\ttable = Eigen::Matrix2d::Zero() ;\n\n\t\t\tforeach( std::string const& value, m_universe ) {\n\t\t\t\tint i = 0, j = 0 ;\n\t\t\t\tif( impl::in( value, m_test_genes )) {\n\t\t\t\t\ti = 0 ;\n\t\t\t\t} else {\n\t\t\t\t\ti = 1 ;\n\t\t\t\t}\n\n\t\t\t\tif( impl::in( value, pathway.second ) ) {\n\t\t\t\t\tj = 0 ;\n\t\t\t\t} else {\n\t\t\t\t\tj = 1 ;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t++table( i, j ) ;\n\n\t\t\t\tif( i == 0 && j == 0 ) {\n\t\t\t\t\tif( hit_genes_in_pathway.str().size() == 0 ) {\n\t\t\t\t\t\thit_genes_in_pathway << value ;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\thit_genes_in_pathway << \",\" << value ;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//get_ui_context().logger()\n\t\t\tstd::cout\n\t\t\t\t<< analysis << tab\t\n\t\t\t\t<< pathway.first << tab\n\t\t\t\t<< \"\\\"\" << m_pathway_names[ pathway.first ] << \"\\\"\" << tab\n\t\t\t\t<< table( 0, 0 ) << tab\n\t\t\t\t<< table( 0, 1 ) << tab\n\t\t\t\t<< table( 1, 0 ) << tab\n\t\t\t\t<< table( 1, 1 ) << tab\n\t\t\t\t<< table.col( 0 ).sum() << tab\n\t\t\t\t<< table.sum() << tab ;\n\t\t\ttry {\n\t\t\t\tFishersExactTest test( table ) ;\n\t\t\t\t//get_ui_context().logger()\n\t\t\t\tstd::cout\n\t\t\t\t\t<< test.get_OR() << tab << test.get_pvalue() ;\n\t\t\t\tif( test.get_pvalue() <= pvalue_threshhold ) {\n\t\t\t\t\tstd::cout << tab << hit_genes_in_pathway.str() ;\n\t\t\t\t} else {\n\t\t\t\t\tstd::cout << tab << \"NA\" ;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch( std::exception const& ) {\n\t\t\t\t// get_ui_context().logger()\n\t\t\t\tstd::cout\n\t\t\t\t\t<< \"NA\\tNA\\t\" ;\t\n\t\t\t}\n\t\t\tstd::cout << \"\\n\" ;\n\t\t}\n\t}\n\t\nprivate:\n\tStringStringMap m_pathway_names ;\n\tStringStringSetMap m_pathway_members ;\n\tStringStringSetMap m_clusters ;\n\tStringStringMap m_cluster_descriptions ;\n\tStringStringMap m_cluster_mapping ;\n\tStringSet m_universe ;\n\tStringSet m_test_genes ;\n} ;\n\nint main( int argc, char **argv ) {\n\ttry {\n\t\tOverrepApplication app( argc, argv ) ;\t\n\t\tapp.process() ;\n\t}\n\tcatch( appcontext::HaltProgramWithReturnCode const& e ) {\n\t\treturn e.return_code() ;\n\t}\n\treturn 0 ;\n}\n", "meta": {"hexsha": "edf8e99cfaff18384296b5d16a7ab96c853fbae0", "size": 19123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/overrep.cpp", "max_stars_repo_name": "CreRecombinase/qctool", "max_stars_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "apps/overrep.cpp", "max_issues_repo_name": "CreRecombinase/qctool", "max_issues_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "apps/overrep.cpp", "max_forks_repo_name": "CreRecombinase/qctool", "max_forks_repo_head_hexsha": "6dad3a15c461177bf6940ba7b991337402ca5c41", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5775127768, "max_line_length": 158, "alphanum_fraction": 0.6366678868, "num_tokens": 5362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.23918059505750586}}
{"text": "// Copyright (c) 2014-2018, The Monero 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// The LWMA-4 Difficulty algorithm as implemented below is under a separate license\n// to the rest of this file.\n//\n// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers\n\n#include <boost/algorithm/clamp.hpp>\n#include <cassert>\n#include <cstddef>\n#include <cstdint>\n#include <vector>\n\n#include \"common/int-util.h\"\n#include \"crypto/hash.h\"\n#include \"cryptonote_config.h\"\n#include \"difficulty.h\"\n\n#undef MONERO_DEFAULT_LOG_CATEGORY\n#define MONERO_DEFAULT_LOG_CATEGORY \"difficulty\"\n\nnamespace cryptonote {\n\n  using std::size_t;\n  using std::uint64_t;\n  using std::vector;\n\n#if defined(__x86_64__)\n  static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {\n    low = mul128(a, b, &high);\n  }\n\n#else\n\n  static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {\n    // __int128 isn't part of the standard, so the previous function wasn't portable. mul128() in Windows is fine,\n    // but this portable function should be used elsewhere. Credit for this function goes to latexi95.\n\n    uint64_t aLow = a & 0xFFFFFFFF;\n    uint64_t aHigh = a >> 32;\n    uint64_t bLow = b & 0xFFFFFFFF;\n    uint64_t bHigh = b >> 32;\n\n    uint64_t res = aLow * bLow;\n    uint64_t lowRes1 = res & 0xFFFFFFFF;\n    uint64_t carry = res >> 32;\n\n    res = aHigh * bLow + carry;\n    uint64_t highResHigh1 = res >> 32;\n    uint64_t highResLow1 = res & 0xFFFFFFFF;\n\n    res = aLow * bHigh;\n    uint64_t lowRes2 = res & 0xFFFFFFFF;\n    carry = res >> 32;\n\n    res = aHigh * bHigh + carry;\n    uint64_t highResHigh2 = res >> 32;\n    uint64_t highResLow2 = res & 0xFFFFFFFF;\n\n    //Addition\n\n    uint64_t r = highResLow1 + lowRes2;\n    carry = r >> 32;\n    low = (r << 32) | lowRes1;\n    r = highResHigh1 + highResLow2 + carry;\n    uint64_t d3 = r & 0xFFFFFFFF;\n    carry = r >> 32;\n    r = highResHigh2 + carry;\n    high = d3 | (r << 32);\n  }\n\n#endif\n\n  static inline bool cadd(uint64_t a, uint64_t b) {\n    return a + b < a;\n  }\n\n  static inline bool cadc(uint64_t a, uint64_t b, bool c) {\n    return a + b < a || (c && a + b == (uint64_t) -1);\n  }\n\n  bool check_hash(const crypto::hash &hash, difficulty_type difficulty) {\n    uint64_t low, high, top, cur;\n    // First check the highest word, this will most likely fail for a random hash.\n    mul(swap64le(((const uint64_t *) &hash)[3]), difficulty, top, high);\n    if (high != 0) {\n      return false;\n    }\n    mul(swap64le(((const uint64_t *) &hash)[0]), difficulty, low, cur);\n    mul(swap64le(((const uint64_t *) &hash)[1]), difficulty, low, high);\n    bool carry = cadd(cur, low);\n    cur = high;\n    mul(swap64le(((const uint64_t *) &hash)[2]), difficulty, low, high);\n    carry = cadc(cur, low, carry);\n    carry = cadc(high, top, carry);\n    return !carry;\n  }\n\n    // LWMA-4 difficulty algorithm\n    // Copyright (c) 2017-2018 Zawy\n    // MIT license\n    //\n    // Permission is hereby granted, free of charge, to any person obtaining a copy\n    // of this software and associated documentation files (the \"Software\"), to\n    // deal in the Software without restriction, including without limitation the\n    // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n    // sell copies of the Software, and to permit persons to whom the Software is\n    // furnished to do so, subject to the following conditions:\n    //\n    // The above copyright notice and this permission notice shall be included in\n    // all copies or substantial portions of the Software.\n    //\n    // THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n    // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF\n    // OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n    //\n    // https://github.com/zawy12/difficulty-algorithms/issues/3\n    // See commented version for explanations & required config file changes. Fix FTL and MTP!\n    difficulty_type next_difficulty(std::vector<uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {\n        uint64_t  T = target_seconds;\n        uint64_t  N = DIFFICULTY_WINDOW; // N=45, 60, and 90 for T=600, 120, 60.\n        uint64_t  L(0), ST(0), next_D, prev_D, avg_D, i;\n\n        assert(timestamps.size() == cumulative_difficulties.size() && timestamps.size() <= N+1 );\n\n        // If it's a new coin, do startup code. Do not remove in case other coins copy your code.\n        uint64_t difficulty_guess = 600;\n        if (timestamps.size() <= 12 ) {   return difficulty_guess;   }\n        if ( timestamps.size()  < N +1 ) { N = timestamps.size()-1;  }\n\n        // If hashrate/difficulty ratio after a fork is < 1/3 prior ratio, hardcode D for N+1 blocks after fork.\n        // This will also cover up a very common type of backwards-incompatible fork.\n        // difficulty_guess = 100000; //  Dev may change.  Guess low than anything expected.\n        // if ( height <= UPGRADE_HEIGHT + 1 + N ) { return difficulty_guess;  }\n\n        // Safely convert out-of-sequence timestamps into > 0 solvetimes.\n        std::vector<uint64_t>TS(N+1);\n        TS[0] = timestamps[0];\n        for ( i = 1; i <= N; i++) {\n            if ( timestamps[i]  > TS[i-1]  ) {   TS[i] = timestamps[i];  }\n            else {  TS[i] = TS[i-1];   }\n        }\n\n        for ( i = 1; i <= N; i++) {\n            // Temper long solvetime drops if they were preceded by 3 or 6 fast solves.\n            if ( i > 4 && TS[i]-TS[i-1] > 5*T  && TS[i-1] - TS[i-4] < (14*T)/10 ) {   ST = 2*T; }\n            else if ( i > 7 && TS[i]-TS[i-1] > 5*T  && TS[i-1] - TS[i-7] < 4*T ) {   ST = 2*T; }\n            else { // Assume normal conditions, so get ST.\n                // LWMA drops too much from long ST, so limit drops with a 5*T limit\n                ST = std::min(5*T ,TS[i] - TS[i-1]);\n            }\n            L +=  ST * i ;\n        }\n        if (L < N*N*T/20 ) { L =  N*N*T/20; }\n        avg_D = ( cumulative_difficulties[N] - cumulative_difficulties[0] )/ N;\n\n        // Prevent round off error for small D and overflow for large D.\n        if (avg_D > 2000000*N*N*T) {\n            next_D = (avg_D/(200*L))*(N*(N+1)*T*97);\n        }\n        else {    next_D = (avg_D*N*(N+1)*T*97)/(200*L);    }\n\n        prev_D =  cumulative_difficulties[N] - cumulative_difficulties[N-1] ;\n\n        // Apply 10% jump rule.\n        if (( TS[N] - TS[N-1] < (2*T)/10 ) ||\n            ( TS[N] - TS[N-2] < (5*T)/10 ) ||\n            ( TS[N] - TS[N-3] < (8*T)/10 ))\n        {\n            next_D = std::max( next_D, std::min( (prev_D*110)/100, (105*avg_D)/100 ) );\n        }\n        // Make all insignificant digits zero for easy reading.\n        i = 1000000000;\n        while (i > 1) {\n            if ( next_D > i*100 ) { next_D = ((next_D+i/2)/i)*i; break; }\n            else { i /= 10; }\n        }\n        return  next_D;\n    }\n}\n", "meta": {"hexsha": "44a19938ab3d1ec51be1e5e6e960dd49c4349dff", "size": 8678, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cryptonote_basic/difficulty.cpp", "max_stars_repo_name": "unprll-project/unprll", "max_stars_repo_head_hexsha": "b72fa7fc3a74964f46956e39c3e1b3a734a4c308", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-11-28T14:53:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T15:53:14.000Z", "max_issues_repo_path": "src/cryptonote_basic/difficulty.cpp", "max_issues_repo_name": "unprll-project/unprll", "max_issues_repo_head_hexsha": "b72fa7fc3a74964f46956e39c3e1b3a734a4c308", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2018-12-09T03:01:32.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-11T13:56:43.000Z", "max_forks_repo_path": "src/cryptonote_basic/difficulty.cpp", "max_forks_repo_name": "unprll-project/unprll", "max_forks_repo_head_hexsha": "b72fa7fc3a74964f46956e39c3e1b3a734a4c308", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-11-28T14:47:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-19T19:57:09.000Z", "avg_line_length": 41.3238095238, "max_line_length": 148, "alphanum_fraction": 0.6377045402, "num_tokens": 2381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23918059505750583}}
{"text": "/*\n Copyright (C) 2021 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <qle/instruments/crossccyfixfloatmtmresetswap.hpp>\n#include <qle/cashflows/floatingratefxlinkednotionalcoupon.hpp>\n#include <qle/cashflows/fixedratefxlinkednotionalcoupon.hpp>\n\n#include <boost/make_shared.hpp>\n#include <ql/cashflows/fixedratecoupon.hpp>\n#include <ql/cashflows/iborcoupon.hpp>\n#include <ql/cashflows/simplecashflow.hpp>\n\nusing namespace QuantLib;\n\nnamespace QuantExt {\n\nCrossCcyFixFloatMtMResetSwap::CrossCcyFixFloatMtMResetSwap(\n    Real nominal, const Currency& fixedCurrency, const Schedule& fixedSchedule,\n    Rate fixedRate, const DayCounter& fixedDayCount, const BusinessDayConvention& fixedPaymentBdc,\n    Natural fixedPaymentLag, const Calendar& fixedPaymentCalendar, const Currency& floatCurrency,\n    const Schedule& floatSchedule, const boost::shared_ptr<IborIndex>& floatIndex, Spread floatSpread,\n    const BusinessDayConvention& floatPaymentBdc, Natural floatPaymentLag, const Calendar& floatPaymentCalendar,\n    const boost::shared_ptr<FxIndex>& fxIdx, bool resetsOnFloatLeg, bool receiveFixed)\n    : CrossCcySwap(3), nominal_(nominal), fixedCurrency_(fixedCurrency),\n    fixedSchedule_(fixedSchedule), fixedRate_(fixedRate), fixedDayCount_(fixedDayCount), \n    fixedPaymentBdc_(fixedPaymentBdc), fixedPaymentLag_(fixedPaymentLag), fixedPaymentCalendar_(fixedPaymentCalendar),\n    floatCurrency_(floatCurrency), floatSchedule_(floatSchedule), floatIndex_(floatIndex),\n    floatSpread_(floatSpread), floatPaymentBdc_(floatPaymentBdc),\n    floatPaymentLag_(floatPaymentLag), floatPaymentCalendar_(floatPaymentCalendar),\n    fxIndex_(fxIdx), resetsOnFloatLeg_(resetsOnFloatLeg), receiveFixed_(receiveFixed) {\n\n    registerWith(floatIndex_);\n    registerWith(fxIndex_);\n    initialize();\n}\n\nvoid CrossCcyFixFloatMtMResetSwap::initialize() {\n\n    // if resets on floating leg, set notional to zero, else the fixed\n    Real floatNotional, fixedNotional;\n    if (resetsOnFloatLeg_) {\n        floatNotional = 0.0;\n        fixedNotional = nominal_;\n    } else {\n        floatNotional = nominal_;\n        fixedNotional = 0.0;\n    }\n\n    // Build the float leg\n    Leg floatLeg = IborLeg(floatSchedule_, floatIndex_)\n        .withNotionals(floatNotional)\n        .withSpreads(floatSpread_)\n        .withPaymentAdjustment(floatPaymentBdc_)\n        .withPaymentLag(floatPaymentLag_)\n        .withPaymentCalendar(floatPaymentCalendar_);\n\n    // Register with each floating rate coupon\n    for (Leg::const_iterator it = floatLeg.begin(); it < floatLeg.end(); ++it)\n        registerWith(*it);\n\n    // Build the fixed rate leg\n    Leg fixedLeg = FixedRateLeg(fixedSchedule_)\n        .withNotionals(fixedNotional)\n        .withCouponRates(fixedRate_, fixedDayCount_)\n        .withPaymentAdjustment(fixedPaymentBdc_)\n        .withPaymentLag(fixedPaymentLag_)\n        .withPaymentCalendar(fixedPaymentCalendar_);\n\n    if (resetsOnFloatLeg_) {\n        // Notional exchanges for fixed leg\n        // Initial notional exchange\n        Date aDate = fixedSchedule_.dates().front();\n        aDate = fixedPaymentCalendar_.adjust(aDate, fixedPaymentBdc_);\n        boost::shared_ptr<CashFlow> aCashflow = boost::make_shared<SimpleCashFlow>(-fixedNotional, aDate);\n        fixedLeg.insert(fixedLeg.begin(), aCashflow);\n\n        // Final notional exchange\n        aDate = fixedLeg.back()->date();\n        aCashflow = boost::make_shared<SimpleCashFlow>(fixedNotional, aDate);\n        fixedLeg.push_back(aCashflow);\n\n        // resetting floating leg\n        for (Size j = 0; j < floatLeg.size(); ++j) {\n            boost::shared_ptr<FloatingRateCoupon> coupon = boost::dynamic_pointer_cast<FloatingRateCoupon>(floatLeg[j]);\n            Date fixingDate = fxIndex_->fixingCalendar().advance(coupon->accrualStartDate(),\n                -static_cast<Integer>(fxIndex_->fixingDays()), Days);\n            boost::shared_ptr<FloatingRateFXLinkedNotionalCoupon> fxLinkedCoupon =\n                boost::make_shared<FloatingRateFXLinkedNotionalCoupon>(fixingDate, fixedNotional, fxIndex_, coupon);\n            floatLeg[j] = fxLinkedCoupon;\n        }\n\n        // now build a separate leg to store the resetting notionals\n        receiveFixed_ ? payer_[2] = -1.0 : payer_[2] = +1.0;\n        currencies_[2] = floatCurrency_;\n        for (Size j = 0; j < floatLeg.size(); j++) {\n            boost::shared_ptr<Coupon> c = boost::dynamic_pointer_cast<Coupon>(floatLeg[j]);\n            QL_REQUIRE(c, \"Resetting XCCY - expected Coupon\"); \n            // build a pair of notional flows, one at the start and one at the end of\n            // the accrual period. Both with the same FX fixing date\n            Date fixingDate = fxIndex_->fixingCalendar().advance(c->accrualStartDate(),\n                -static_cast<Integer>(fxIndex_->fixingDays()), Days);\n            legs_[2].push_back(boost::shared_ptr<CashFlow>(\n                new FXLinkedCashFlow(c->accrualStartDate(), fixingDate, -fixedNotional, fxIndex_)));\n            legs_[2].push_back(boost::shared_ptr<CashFlow>(\n                new FXLinkedCashFlow(c->accrualEndDate(), fixingDate, fixedNotional, fxIndex_)));\n        }\n    } else {\n        // Notional exchanges for floating leg\n        // Initial notional exchange\n        Date aDate = floatSchedule_.dates().front();\n        aDate = floatPaymentCalendar_.adjust(aDate, floatPaymentBdc_);\n        boost::shared_ptr<CashFlow> aCashflow = boost::make_shared<SimpleCashFlow>(-floatNotional, aDate);\n        floatLeg.insert(fixedLeg.begin(), aCashflow);\n\n        // Final notional exchange\n        aDate = fixedLeg.back()->date();\n        aCashflow = boost::make_shared<SimpleCashFlow>(floatNotional, aDate);\n        floatLeg.push_back(aCashflow);\n\n        // resetting fixed leg\n        for (Size j = 0; j < fixedLeg.size(); ++j) {\n            boost::shared_ptr<FixedRateCoupon> coupon = boost::dynamic_pointer_cast<FixedRateCoupon>(fixedLeg[j]);\n            Date fixingDate = fxIndex_->fixingCalendar().advance(coupon->accrualStartDate(),\n                -static_cast<Integer>(fxIndex_->fixingDays()), Days);\n            boost::shared_ptr<FixedRateFXLinkedNotionalCoupon> fxLinkedCoupon = \n                boost::make_shared<FixedRateFXLinkedNotionalCoupon>(fixingDate, floatNotional, fxIndex_, coupon);\n            floatLeg[j] = fxLinkedCoupon;\n        }\n\n        // now build a separate leg to store the resetting notionals\n        receiveFixed_ ? payer_[2] = -1.0 : payer_[2] = +1.0;\n        currencies_[2] = fixedCurrency_;\n        for (Size j = 0; j < fixedLeg.size(); j++) {\n            boost::shared_ptr<Coupon> c = boost::dynamic_pointer_cast<Coupon>(fixedLeg[j]);\n            QL_REQUIRE(c, \"Resetting XCCY - expected Coupon\");\n            // build a pair of notional flows, one at the start and one at the end of\n            // the accrual period. Both with the same FX fixing date\n            Date fixingDate = fxIndex_->fixingCalendar().advance(c->accrualStartDate(),\n                -static_cast<Integer>(fxIndex_->fixingDays()), Days);\n            legs_[2].push_back(boost::shared_ptr<CashFlow>(\n                new FXLinkedCashFlow(c->accrualStartDate(), fixingDate, -floatNotional, fxIndex_)));\n            legs_[2].push_back(boost::shared_ptr<CashFlow>(\n                new FXLinkedCashFlow(c->accrualEndDate(), fixingDate, floatNotional, fxIndex_)));\n        }\n    }\n\n    // Deriving from cross currency swap where:\n    //   First leg should hold the pay flows\n    //   Second leg should hold the receive flows\n    payer_[0] = -1.0;\n    payer_[1] = 1.0;\n    if (receiveFixed_) {\n        legs_[1] = fixedLeg;\n        currencies_[1] = fixedCurrency_;\n        legs_[0] = floatLeg;\n        currencies_[0] = floatCurrency_;\n    } else {\n        legs_[0] = fixedLeg;\n        currencies_[0] = fixedCurrency_;\n        legs_[1] = floatLeg;\n        currencies_[1] = floatCurrency_;\n    }\n    \n    // Register the instrument with all cashflows on each leg.\n    for (Size legNo = 0; legNo < legs_.size(); legNo++) {\n        Leg::iterator it;\n        for (it = legs_[legNo].begin(); it != legs_[legNo].end(); ++it) {\n            registerWith(*it);\n        }\n    }\n}\n\nvoid CrossCcyFixFloatMtMResetSwap::setupArguments(PricingEngine::arguments* a) const {\n\n    CrossCcySwap::setupArguments(a);\n\n    if (CrossCcyFixFloatMtMResetSwap::arguments* args = dynamic_cast<CrossCcyFixFloatMtMResetSwap::arguments*>(a)) {\n        args->fixedRate = fixedRate_;\n        args->spread = floatSpread_;\n    }\n}\n\nvoid CrossCcyFixFloatMtMResetSwap::fetchResults(const PricingEngine::results* r) const {\n\n    CrossCcySwap::fetchResults(r);\n\n    // Depending on the pricing engine used, we may have CrossCcyFixFloatSwap::results\n    if (const CrossCcyFixFloatMtMResetSwap::results* res = dynamic_cast<const CrossCcyFixFloatMtMResetSwap::results*>(r)) {\n        // If we have CrossCcyFixFloatSwap::results from the pricing engine\n        fairFixedRate_ = res->fairFixedRate;\n        fairSpread_ = res->fairSpread;\n    } else {\n        // If not, set them to Null to indicate a calculation is needed below\n        fairFixedRate_ = Null<Rate>();\n        fairSpread_ = Null<Spread>();\n    }\n\n    // Calculate fair rate and spread if they are still Null here\n    static Spread basisPoint = 1.0e-4;\n\n    Size idxFixed = receiveFixed_ ? 1 : 0;\n    if (fairFixedRate_ == Null<Rate>() && legBPS_[idxFixed] != Null<Real>())\n        fairFixedRate_ = fixedRate_ - NPV_ / (legBPS_[idxFixed] / basisPoint);\n\n    Size idxFloat = receiveFixed_ ? 0 : 1;\n    if (fairSpread_ == Null<Spread>() && legBPS_[idxFloat] != Null<Real>())\n        fairSpread_ = floatSpread_ - NPV_ / (legBPS_[idxFloat] / basisPoint);\n}\n\nvoid CrossCcyFixFloatMtMResetSwap::setupExpired() const {\n    CrossCcySwap::setupExpired();\n    fairFixedRate_ = Null<Rate>();\n    fairSpread_ = Null<Spread>();\n}\n\nvoid CrossCcyFixFloatMtMResetSwap::arguments::validate() const {\n    CrossCcySwap::arguments::validate();\n    QL_REQUIRE(fixedRate != Null<Rate>(), \"Fixed rate cannot be null\");\n    QL_REQUIRE(spread != Null<Spread>(), \"Spread cannot be null\");\n}\n\nvoid CrossCcyFixFloatMtMResetSwap::results::reset() {\n    CrossCcySwap::results::reset();\n    fairFixedRate = Null<Rate>();\n    fairSpread = Null<Spread>();\n}\n} // namespace QuantExt\n", "meta": {"hexsha": "9b8561fcf84b620e696fa7e580c63538f1cd3c8f", "size": 10921, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/instruments/crossccyfixfloatmtmresetswap.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/instruments/crossccyfixfloatmtmresetswap.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/instruments/crossccyfixfloatmtmresetswap.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 44.9423868313, "max_line_length": 123, "alphanum_fraction": 0.6877575314, "num_tokens": 2735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2391454545110906}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <utility>\n\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Structure/Direction.hpp\"\n#include \"Domain/Structure/DirectionMap.hpp\"\n#include \"Domain/Structure/Element.hpp\"\n#include \"Domain/Structure/ElementId.hpp\"\n#include \"Domain/Structure/MaxNumberOfNeighbors.hpp\"\n#include \"Evolution/DgSubcell/NeighborData.hpp\"\n#include \"Evolution/Systems/Burgers/Tags.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace Burgers::fd {\ntemplate <typename TagsList, typename Reconstructor>\nvoid reconstruct_work(\n    const gsl::not_null<std::array<Variables<TagsList>, 1>*> vars_on_lower_face,\n    const gsl::not_null<std::array<Variables<TagsList>, 1>*> vars_on_upper_face,\n    const Reconstructor& reconstruct,\n    const Variables<tmpl::list<Tags::U>> volume_vars, const Element<1>& element,\n    const FixedHashMap<maximum_number_of_neighbors(1) + 1,\n                       std::pair<Direction<1>, ElementId<1>>,\n                       evolution::dg::subcell::NeighborData,\n                       boost::hash<std::pair<Direction<1>, ElementId<1>>>>\n        neighbor_data,\n    const Mesh<1>& subcell_mesh, const size_t ghost_zone_size) {\n  const size_t volume_num_pts = subcell_mesh.number_of_grid_points();\n  const size_t reconstructed_num_pts = volume_num_pts + 1;\n\n  // create views/spans into the face data, which will be filled by the\n  // reconstructor\n  std::array<gsl::span<double>, 1> upper_face_vars{};\n  std::array<gsl::span<double>, 1> lower_face_vars{};\n  for (size_t i = 0; i < 1; i++) {\n    gsl::at(upper_face_vars, i) =\n        gsl::make_span(get<Tags::U>(gsl::at(*vars_on_upper_face, i))[0].data(),\n                       reconstructed_num_pts);\n    gsl::at(lower_face_vars, i) =\n        gsl::make_span(get<Tags::U>(gsl::at(*vars_on_lower_face, i))[0].data(),\n                       reconstructed_num_pts);\n  }\n\n  const size_t neighbor_num_ghost_fd_points = ghost_zone_size;\n\n  // make span of ghost cell variables for each direction\n  DirectionMap<1, gsl::span<const double>> ghost_cell_vars{};\n\n  // for all Directions, make the pointers in ghost_cell_vars span to point\n  // the received neighbor data\n  for (const auto& direction : Direction<1>::all_directions()) {\n    const auto& neighbors_in_direction = element.neighbors().at(direction);\n\n    ASSERT(neighbors_in_direction.size() == 1,\n           \"Currently only support one neighbor in each direction, but \"\n           \"got \"\n               << neighbors_in_direction.size() << \" in direction \"\n               << direction);\n\n    ghost_cell_vars[direction] = gsl::make_span(\n        &neighbor_data.at(std::pair{direction, *neighbors_in_direction.begin()})\n             .data_for_reconstruction[0],\n        neighbor_num_ghost_fd_points);\n  }\n\n  // make span of volume variables\n  auto& volume_tensor = get<Tags::U>(volume_vars);\n  const gsl::span<const double> volume_vars_span =\n      gsl::make_span((volume_tensor)[0].data(), volume_num_pts);\n\n  // perform reconstruction\n  reconstruct(make_not_null(&upper_face_vars), make_not_null(&lower_face_vars),\n              volume_vars_span, ghost_cell_vars, subcell_mesh.extents(), 1);\n}\n\ntemplate <typename TagsList, typename ReconstructLower,\n          typename ReconstructUpper>\nvoid reconstruct_fd_neighbor_work(\n    const gsl::not_null<Variables<TagsList>*> vars_on_face,\n    const ReconstructLower& reconstruct_lower_neighbor,\n    const ReconstructUpper& reconstruct_upper_neighbor,\n    const Variables<tmpl::list<Tags::U>>& subcell_volume_vars,\n    const Element<1>& element,\n    const FixedHashMap<maximum_number_of_neighbors(1) + 1,\n                       std::pair<Direction<1>, ElementId<1>>,\n                       evolution::dg::subcell::NeighborData,\n                       boost::hash<std::pair<Direction<1>, ElementId<1>>>>\n        neighbor_data,\n    const Mesh<1>& subcell_mesh, const Direction<1>& direction_to_reconstruct,\n    const size_t ghost_zone_size) {\n  const std::pair mortar_id{\n      direction_to_reconstruct,\n      *element.neighbors().at(direction_to_reconstruct).begin()};\n\n  Index<1> ghost_data_extents = subcell_mesh.extents();\n  ghost_data_extents[direction_to_reconstruct.dimension()] = ghost_zone_size;\n\n  // allocate Variable for storing data from neighbor\n  Variables<tmpl::list<Tags::U>> neighbor_vars{ghost_data_extents.product()};\n\n  {\n    ASSERT(neighbor_data.contains(mortar_id),\n           \"The neighbor data does not contain the mortar: (\"\n               << mortar_id.first << ',' << mortar_id.second << \")\");\n\n    const auto& neighbor_data_in_direction = neighbor_data.at(mortar_id);\n    std::copy(\n        neighbor_data_in_direction.data_for_reconstruction.begin(),\n        std::next(neighbor_data_in_direction.data_for_reconstruction.begin(),\n                  static_cast<std::ptrdiff_t>(ghost_data_extents.product())),\n        neighbor_vars.data());\n  }\n\n  const auto& tensor_volume = get<Tags::U>(subcell_volume_vars);\n  const auto& tensor_neighbor = get<Tags::U>(neighbor_vars);\n  auto& tensor_on_face = get<Tags::U>(*vars_on_face);\n\n  if (direction_to_reconstruct.side() == Side::Upper) {\n    for (size_t tensor_index = 0; tensor_index < tensor_on_face.size();\n         ++tensor_index) {\n      reconstruct_upper_neighbor(\n          make_not_null(&tensor_on_face[tensor_index]),\n          tensor_volume[tensor_index], tensor_neighbor[tensor_index],\n          subcell_mesh.extents(), ghost_data_extents, direction_to_reconstruct);\n    }\n  } else {\n    for (size_t tensor_index = 0; tensor_index < tensor_on_face.size();\n         ++tensor_index) {\n      reconstruct_lower_neighbor(\n          make_not_null(&tensor_on_face[tensor_index]),\n          tensor_volume[tensor_index], tensor_neighbor[tensor_index],\n          subcell_mesh.extents(), ghost_data_extents, direction_to_reconstruct);\n    }\n  }\n}\n}  // namespace Burgers::fd\n", "meta": {"hexsha": "3db20e0c49ac6684b183cfa5dc82dabb3ab9176c", "size": 6155, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/Burgers/FiniteDifference/ReconstructWork.tpp", "max_stars_repo_name": "kidder/spectre", "max_stars_repo_head_hexsha": "97ae95f72320f9f67895d3303824e64de6fd9077", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Evolution/Systems/Burgers/FiniteDifference/ReconstructWork.tpp", "max_issues_repo_name": "kidder/spectre", "max_issues_repo_head_hexsha": "97ae95f72320f9f67895d3303824e64de6fd9077", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Evolution/Systems/Burgers/FiniteDifference/ReconstructWork.tpp", "max_forks_repo_name": "kidder/spectre", "max_forks_repo_head_hexsha": "97ae95f72320f9f67895d3303824e64de6fd9077", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.5878378378, "max_line_length": 80, "alphanum_fraction": 0.7000812348, "num_tokens": 1442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23901246187607117}}
{"text": "#ifndef SKYLARK_HASH_TRANSFORM_MIXED_HPP\n#define SKYLARK_HASH_TRANSFORM_MIXED_HPP\n\n#include <map>\n#include <boost/serialization/map.hpp>\n\n#include \"../base/sparse_vc_star_matrix.hpp\"\n\n#if SKYLARK_HAVE_COMBBLAS\n#include \"../utility/external/combblas_comm_grid.hpp\"\n#endif\n#include \"../utility/external/elemental_comm_grid.hpp\"\n\nnamespace skylark { namespace sketch {\n\n//FIXME:\n//  - Benchmark one-sided vs. col/row comm (or midpoint scheme):\n//    Most likely the scheme depends on the output Elemental distribution,\n//    here we use the same comm-scheme for all output types.\n//  - Processing Sparse matrix in blocks?\n//  - MPI-3 stuff, see: Enabling highly-scalable remote memory access\n//    programming with MPI-3 one sided, R. Gerstenbergerm,  M. Besta, and\n//    T. Hoefler.\n\n\n/* Specialization: sparse_vc_star for input, distributed Elemental for output */\ntemplate <typename ValueType,\n          El::Distribution ColDist,\n          El::Distribution RowDist,\n          template <typename> class IdxDistributionType,\n          template <typename> class ValueDistribution>\nstruct hash_transform_t <\n    base::sparse_vc_star_matrix_t<ValueType>,\n    El::DistMatrix<ValueType, ColDist, RowDist>,\n    IdxDistributionType,\n    ValueDistribution > :\n        public hash_transform_data_t<IdxDistributionType,\n                                     ValueDistribution> {\n    typedef El::Int index_type;\n    typedef ValueType value_type;\n    typedef base::sparse_vc_star_matrix_t<value_type> matrix_type;\n    typedef El::DistMatrix< value_type, ColDist, RowDist > output_matrix_type;\n    typedef hash_transform_data_t<IdxDistributionType,\n                                  ValueDistribution> data_type;\n\n\n    /**\n     * Regular constructor\n     */\n    hash_transform_t (int N, int S, base::context_t& context)\n        : data_type(N, S, context)\n    {}\n\n    /**\n     * Copy constructor\n     */\n    hash_transform_t (\n        hash_transform_t<\n            matrix_type, output_matrix_type,\n            IdxDistributionType, ValueDistribution>& other)\n        : data_type(other)\n    {}\n\n    /**\n     * Constructor from data\n     */\n    hash_transform_t (const data_type& other_data)\n        : data_type(other_data)\n    {}\n\n    template <typename Dimension>\n    void apply (const matrix_type &A, output_matrix_type &sketch_of_A,\n                Dimension dimension) const {\n        try {\n            apply_impl (A, sketch_of_A, dimension);\n        } catch(boost::mpi::exception e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::mpi_exception()\n                    << base::error_msg(e.what()) );\n        } catch (std::bad_alloc e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::skylark_exception()\n                    << base::error_msg(\"bad_alloc: out of memory\") );\n        }\n    }\n\n\nprivate:\n    /**\n     * Apply the sketching transform that is described in by the sketch_of_A.\n     *\n     * FIXME: distribution depending schemes would be more efficient\n     */\n    template <typename Dimension>\n    void apply_impl (const matrix_type &A,\n        output_matrix_type &sketch_of_A,\n        Dimension dist) const {\n\n        typedef size_t offset_idx_t;\n\n        boost::mpi::communicator comm = skylark::utility::get_communicator(A);\n\n        const size_t rank = comm.rank();\n\n        const size_t ncols = sketch_of_A.Width();\n\n        size_t comm_size = comm.size();\n\n        const int* A_indptr  = A.indptr();\n        const int* A_indices = A.indices();\n        const value_type *A_values = A.locked_values();\n\n        std::vector< std::map<size_t, size_t> > array_offsets(comm_size);\n\n        // pre-compute processor targets of local sketch application\n        for(int i = 0; i < A.width(); i++) {\n            for (int j = A_indptr[i]; j < A_indptr[i + 1]; j++) {\n\n                // compute global row and column id, and compress in one\n                // target position index\n                const size_t pos = getPos(\n                        A.global_row(A_indices[j]), i, ncols, dist);\n\n                // compute target processor for this target index\n                const size_t target_rank = utility::owner(\n                        sketch_of_A, pos / ncols, pos % ncols);\n\n                assert(target_rank < comm_size);\n\n                // map the position to the next empty slot\n                if(array_offsets[target_rank].count(pos) == 0) {\n                     size_t next_pos = array_offsets[target_rank].size();\n                     array_offsets[target_rank][pos] = next_pos;\n                }\n            }\n        }\n\n\n        // constructing array holding start/end indices for one-sided access\n        std::vector<offset_idx_t> proc_start_idx(comm_size + 1, 0);\n        for(size_t i = 1; i < comm_size + 1; ++i)\n            proc_start_idx[i] = proc_start_idx[i-1] + array_offsets[i-1].size();\n\n        const size_t my_num_values = proc_start_idx[comm_size];\n        // total number of nnz that will result when applying sketch locally\n        std::vector<index_type> indices(my_num_values, 0);\n        std::vector<value_type> values(my_num_values, 0);\n\n        // Apply sketch for all local values. Note that some of the resulting\n        // values might end up on a different processor. The data structure\n        // fills values (sorted by processor id) in one continuous array.\n        // Subsequently, one-sided operations can be used to access values for\n        // each processor.\n        for(int i = 0; i < A.width(); i++) {\n            for (int j = A_indptr[i]; j < A_indptr[i + 1]; j++) {\n\n                // compute global row and column id, and compress in one\n                // target position index\n                const size_t pos = getPos(\n                        A.global_row(A_indices[j]), i, ncols, dist);\n\n                // compute target processor for this target index\n                const size_t target_rank = utility::owner(\n                        sketch_of_A, pos / ncols, pos % ncols);\n\n                assert(target_rank < comm_size);\n\n                // get offset in array for current element\n                const size_t ar_idx = proc_start_idx[target_rank] +\n                    array_offsets[target_rank][pos];\n\n                assert(ar_idx < indices.size());\n                indices[ar_idx] = pos;\n\n                assert(ar_idx < values.size());\n                values[ar_idx]  += A_values[j] *\n                    data_type::getValue(A.global_row(A_indices[j]), i, dist);\n            }\n        }\n\n        // tell MPI that we will not use locks\n        MPI_Info info;\n        MPI_Info_create(&info);\n        MPI_Info_set(info, \"no_locks\", \"true\");\n\n        MPI_Win start_offset_win, idx_win, val_win;\n\n        MPI_Win_create(&proc_start_idx[0], sizeof(size_t) * (comm_size + 1),\n                       sizeof(size_t), info, comm, &start_offset_win);\n\n        MPI_Win_create(&indices[0], sizeof(index_type) * indices.size(),\n                       sizeof(index_type), info, comm, &idx_win);\n\n        MPI_Win_create(&values[0], sizeof(value_type) * values.size(),\n                       sizeof(value_type), info, comm, &val_win);\n\n        MPI_Info_free(&info);\n\n        // Synchronize epoch, no subsequent put operations (read only) and no\n        // preceding fence calls.\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOPRECEDE, start_offset_win);\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOPRECEDE, idx_win);\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOPRECEDE, val_win);\n\n\n        // accumulate values from other procs\n        for(size_t p = 0; p < comm_size; ++p) {\n\n            // get the start/end offset\n            std::vector<size_t> offset(2);\n            MPI_Get(&(offset[0]), 2, boost::mpi::get_mpi_datatype<size_t>(),\n                    p, rank, 2, boost::mpi::get_mpi_datatype<size_t>(),\n                    start_offset_win);\n\n            MPI_Win_fence(MPI_MODE_NOPUT, start_offset_win);\n            size_t num_values = offset[1] - offset[0];\n\n            // and fill indices/values.\n            std::vector<index_type> add_idx(num_values);\n            std::vector<value_type> add_val(num_values);\n            MPI_Get(&(add_idx[0]), num_values,\n                    boost::mpi::get_mpi_datatype<index_type>(), p, offset[0],\n                    num_values, boost::mpi::get_mpi_datatype<index_type>(),\n                    idx_win);\n\n            MPI_Get(&(add_val[0]), num_values,\n                    boost::mpi::get_mpi_datatype<value_type>(), p, offset[0],\n                    num_values, boost::mpi::get_mpi_datatype<value_type>(),\n                    val_win);\n\n            MPI_Win_fence(MPI_MODE_NOPUT, idx_win);\n            MPI_Win_fence(MPI_MODE_NOPUT, val_win);\n\n            // finally, set data in local buffer\n            for(size_t i = 0; i < num_values; ++i) {\n                index_type lrow = sketch_of_A.LocalRow(add_idx[i] / ncols);\n                index_type lcol = sketch_of_A.LocalCol(add_idx[i] % ncols);\n                sketch_of_A.UpdateLocal(lrow, lcol, add_val[i]);\n            }\n        }\n\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOSUCCEED, start_offset_win);\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOSUCCEED, idx_win);\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOSUCCEED, val_win);\n\n        MPI_Win_free(&start_offset_win);\n        MPI_Win_free(&idx_win);\n        MPI_Win_free(&val_win);\n    }\n\n    inline index_type getPos(index_type rowid, index_type colid, size_t ncols,\n        columnwise_tag) const {\n        return colid + ncols * data_type::row_idx[rowid];\n    }\n\n    inline index_type getPos(index_type rowid, index_type colid, size_t ncols,\n        rowwise_tag) const {\n        return rowid * ncols + data_type::row_idx[colid];\n    }\n};\n\n#if SKYLARK_HAVE_COMBBLAS\n/* Specialization: SpParMat for input, distributed Elemental for output */\ntemplate <typename IndexType,\n          typename ValueType,\n          El::Distribution ColDist,\n          El::Distribution RowDist,\n          template <typename> class IdxDistributionType,\n          template <typename> class ValueDistribution>\nstruct hash_transform_t <\n    SpParMat<IndexType, ValueType, SpDCCols<IndexType, ValueType> >,\n    El::DistMatrix<ValueType, ColDist, RowDist>,\n    IdxDistributionType,\n    ValueDistribution > :\n        public hash_transform_data_t<IdxDistributionType,\n                                     ValueDistribution> {\n    typedef IndexType index_type;\n    typedef ValueType value_type;\n    typedef SpDCCols< index_type, value_type > col_t;\n    typedef FullyDistVec< index_type, value_type> mpi_vector_t;\n    typedef SpParMat< index_type, value_type, col_t > matrix_type;\n    typedef El::DistMatrix< value_type, ColDist, RowDist > output_matrix_type;\n    typedef hash_transform_data_t<IdxDistributionType,\n                                  ValueDistribution> data_type;\n\n\n    /**\n     * Regular constructor\n     */\n    hash_transform_t (int N, int S, base::context_t& context) :\n        data_type(N, S, context)\n    {}\n\n    /**\n     * Copy constructor\n     */\n    hash_transform_t (\n        hash_transform_t<\n            matrix_type, output_matrix_type,\n            IdxDistributionType, ValueDistribution>& other)\n        : data_type(other)\n    {}\n\n    /**\n     * Constructor from data\n     */\n    hash_transform_t (const data_type& other_data)\n        : data_type(other_data)\n    {}\n\n    template <typename Dimension>\n    void apply (const matrix_type &A, output_matrix_type &sketch_of_A,\n                Dimension dimension) const {\n        try {\n            apply_impl (A, sketch_of_A, dimension);\n        } catch(boost::mpi::exception e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::mpi_exception()\n                    << base::error_msg(e.what()) );\n        } catch (std::string e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(e) );\n        } catch (std::logic_error e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(e.what()) );\n        } catch (std::bad_alloc e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::skylark_exception()\n                    << base::error_msg(\"bad_alloc: out of memory\") );\n        }\n    }\n\n\nprivate:\n    /**\n     * Apply the sketching transform that is described in by the sketch_of_A.\n     */\n    template <typename Dimension>\n    void apply_impl (const matrix_type &A_,\n        output_matrix_type &sketch_of_A,\n        Dimension dist) const {\n\n        // We are essentially doing a 'const' access to A, but the necessary,\n        // 'const' option is missing from the interface\n        matrix_type &A = const_cast<matrix_type&>(A_);\n\n        const size_t rank = A.getcommgrid()->GetRank();\n\n        // extract columns of matrix\n        col_t &data = A.seq();\n\n        const size_t ncols = sketch_of_A.Width();\n\n        const size_t my_row_offset = utility::cb_my_row_offset(A);\n        const size_t my_col_offset = utility::cb_my_col_offset(A);\n\n        size_t comm_size = A.getcommgrid()->GetSize();\n        std::vector< std::set<size_t> > proc_set(comm_size);\n\n        // pre-compute processor targets of local sketch application\n        for(typename col_t::SpColIter col = data.begcol();\n            col != data.endcol(); col++) {\n            for(typename col_t::SpColIter::NzIter nz = data.begnz(col);\n                nz != data.endnz(col); nz++) {\n\n                // compute global row and column id, and compress in one\n                // target position index\n                const index_type rowid = nz.rowid()  + my_row_offset;\n                const index_type colid = col.colid() + my_col_offset;\n                const size_t pos       = getPos(rowid, colid, ncols, dist);\n\n                // compute target processor for this target index\n                const size_t target = utility::owner(\n                        sketch_of_A, pos / ncols, pos % ncols);\n\n                if(proc_set[target].count(pos) == 0) {\n                    assert(target < comm_size);\n                    proc_set[target].insert(pos);\n                }\n            }\n        }\n\n        // constructing array holding start/end indices for one-sided access\n        std::vector<index_type> proc_start_idx(comm_size + 1, 0);\n        for(size_t i = 1; i < comm_size + 1; ++i)\n            proc_start_idx[i] = proc_start_idx[i-1] + proc_set[i-1].size();\n\n        // total number of nnz that will result when applying sketch locally\n        std::vector<index_type> indicies(proc_start_idx[comm_size], 0);\n        std::vector<value_type> values(proc_start_idx[comm_size], 0);\n\n        // Apply sketch for all local values. Note that some of the resulting\n        // values might end up on a different processor. The data structure\n        // fills values (sorted by processor id) in one continuous array.\n        // Subsequently, one-sided operations can be used to access values for\n        // each processor.\n        for(typename col_t::SpColIter col = data.begcol();\n            col != data.endcol(); col++) {\n            for(typename col_t::SpColIter::NzIter nz = data.begnz(col);\n                nz != data.endnz(col); nz++) {\n\n                // compute global row and column id, and compress in one\n                // target position index\n                const index_type rowid = nz.rowid()  + my_row_offset;\n                const index_type colid = col.colid() + my_col_offset;\n                const size_t pos       = getPos(rowid, colid, ncols, dist);\n\n                // compute target processor for this target index\n                const size_t proc = utility::owner(\n                        sketch_of_A, pos / ncols, pos % ncols);\n\n                // get offset in array for current element\n                const size_t ar_idx = proc_start_idx[proc] +\n                    std::distance(proc_set[proc].begin(), proc_set[proc].find(pos));\n\n                indicies[ar_idx] = pos;\n                values[ar_idx]  += nz.value() *\n                                   data_type::getValue(rowid, colid, dist);\n            }\n        }\n\n        // Creating windows for all relevant arrays\n        boost::mpi::communicator comm = utility::get_communicator(A);\n\n        // tell MPI that we will not use locks\n        MPI_Info info;\n        MPI_Info_create(&info);\n        MPI_Info_set(info, \"no_locks\", \"true\");\n\n        MPI_Win start_offset_win, idx_win, val_win;\n\n        MPI_Win_create(&proc_start_idx[0], sizeof(size_t) * (comm_size + 1),\n                       sizeof(size_t), info, comm, &start_offset_win);\n\n        MPI_Win_create(&indicies[0], sizeof(index_type) * indicies.size(),\n                       sizeof(index_type), info, comm, &idx_win);\n\n        MPI_Win_create(&values[0], sizeof(value_type) * values.size(),\n                       sizeof(value_type), info, comm, &val_win);\n\n        MPI_Info_free(&info);\n\n        // Synchronize epoch, no subsequent put operations (read only) and no\n        // preceding fence calls.\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOPRECEDE, start_offset_win);\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOPRECEDE, idx_win);\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOPRECEDE, val_win);\n\n\n        // accumulate values from other procs\n        for(size_t p = 0; p < comm_size; ++p) {\n\n            // get the start/end offset\n            std::vector<size_t> offset(2);\n            MPI_Get(&(offset[0]), 2, boost::mpi::get_mpi_datatype<size_t>(),\n                    p, rank, 2, boost::mpi::get_mpi_datatype<size_t>(),\n                    start_offset_win);\n\n            MPI_Win_fence(MPI_MODE_NOPUT, start_offset_win);\n            size_t num_values = offset[1] - offset[0];\n\n            // and fill indices/values.\n            std::vector<index_type> add_idx(num_values);\n            std::vector<value_type> add_val(num_values);\n            MPI_Get(&(add_idx[0]), num_values,\n                    boost::mpi::get_mpi_datatype<index_type>(), p, offset[0],\n                    num_values, boost::mpi::get_mpi_datatype<index_type>(),\n                    idx_win);\n\n            MPI_Get(&(add_val[0]), num_values,\n                    boost::mpi::get_mpi_datatype<value_type>(), p, offset[0],\n                    num_values, boost::mpi::get_mpi_datatype<value_type>(),\n                    val_win);\n\n            MPI_Win_fence(MPI_MODE_NOPUT, idx_win);\n            MPI_Win_fence(MPI_MODE_NOPUT, val_win);\n\n            // finally, set data in local buffer\n            for(size_t i = 0; i < num_values; ++i) {\n                index_type lrow = sketch_of_A.LocalRow(add_idx[i] / ncols);\n                index_type lcol = sketch_of_A.LocalCol(add_idx[i] % ncols);\n                sketch_of_A.UpdateLocal(lrow, lcol, add_val[i]);\n            }\n        }\n\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOSUCCEED, start_offset_win);\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOSUCCEED, idx_win);\n        MPI_Win_fence(MPI_MODE_NOPUT | MPI_MODE_NOSUCCEED, val_win);\n\n        MPI_Win_free(&start_offset_win);\n        MPI_Win_free(&idx_win);\n        MPI_Win_free(&val_win);\n    }\n\n    inline index_type getPos(index_type rowid, index_type colid, size_t ncols,\n        columnwise_tag) const {\n        return colid + ncols * data_type::row_idx[rowid];\n    }\n\n    inline index_type getPos(index_type rowid, index_type colid, size_t ncols,\n        rowwise_tag) const {\n        return rowid * ncols + data_type::row_idx[colid];\n    }\n};\n\n/* Specialization: SpParMat for input, Local Elemental output */\ntemplate <typename IndexType,\n          typename ValueType,\n          template <typename> class IdxDistributionType,\n          template <typename> class ValueDistribution>\nstruct hash_transform_t <\n    SpParMat<IndexType, ValueType, SpDCCols<IndexType, ValueType> >,\n    El::Matrix<ValueType>,\n    IdxDistributionType,\n    ValueDistribution > :\n        public hash_transform_data_t<IdxDistributionType,\n                                     ValueDistribution> {\n    typedef IndexType index_type;\n    typedef ValueType value_type;\n    typedef SpDCCols< index_type, value_type > col_t;\n    typedef FullyDistVec< index_type, value_type> mpi_vector_t;\n    typedef SpParMat< index_type, value_type, col_t > matrix_type;\n    typedef El::Matrix< value_type > output_matrix_type;\n    typedef hash_transform_data_t<IdxDistributionType,\n                                  ValueDistribution> data_type;\n\n\n    /**\n     * Regular constructor\n     */\n    hash_transform_t (int N, int S, base::context_t& context) :\n        data_type(N, S, context) {\n\n    }\n\n    /**\n     * Copy constructor\n     */\n    template <typename InputMatrixType,\n              typename OutputMatrixType>\n    hash_transform_t (hash_transform_t<InputMatrixType,\n                                       OutputMatrixType,\n                                       IdxDistributionType,\n                                       ValueDistribution>& other) :\n        data_type(other) {}\n\n    /**\n     * Constructor from data\n     */\n    hash_transform_t (hash_transform_data_t<IdxDistributionType,\n                                            ValueDistribution>& other_data) :\n        data_type(other_data) {}\n\n    template <typename Dimension>\n    void apply (const matrix_type &A, output_matrix_type &sketch_of_A,\n                Dimension dimension) const {\n        try {\n            apply_impl (A, sketch_of_A, dimension);\n        } catch(boost::mpi::exception e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::mpi_exception()\n                    << base::error_msg(e.what()) );\n        } catch (std::string e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(e) );\n        } catch (std::logic_error e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(e.what()) );\n        } catch (std::bad_alloc e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::skylark_exception()\n                    << base::error_msg(\"bad_alloc: out of memory\") );\n        }\n    }\n\n\nprivate:\n    /**\n     * Apply the sketching transform that is described in by the sketch_of_A.\n     */\n    template <typename Dimension>\n    void apply_impl (const matrix_type &A_,\n        output_matrix_type &sketch_of_A,\n        Dimension dist) const {\n\n        // We are essentially doing a 'const' access to A, but the necessary,\n        // 'const' option is missing from the interface\n        matrix_type &A = const_cast<matrix_type&>(A_);\n\n        const size_t rank = A.getcommgrid()->GetRank();\n\n        // extract columns of matrix\n        col_t &data = A.seq();\n\n        const size_t my_row_offset = utility::cb_my_row_offset(A);\n        const size_t my_col_offset = utility::cb_my_col_offset(A);\n\n        int n_res_cols = A.getncol();\n        int n_res_rows = A.getnrow();\n        data_type::get_res_size(n_res_rows, n_res_cols, dist);\n\n        // Apply sketch for all local values. Subsequently, all values are\n        // gathered on processor 0 and the local matrix is populated.\n        typedef std::map<index_type, value_type> col_values_t;\n        col_values_t col_values;\n        for(typename col_t::SpColIter col = data.begcol();\n            col != data.endcol(); col++) {\n            for(typename col_t::SpColIter::NzIter nz = data.begnz(col);\n                nz != data.endnz(col); nz++) {\n\n                index_type rowid = nz.rowid()  + my_row_offset;\n                index_type colid = col.colid() + my_col_offset;\n\n                const value_type value =\n                    nz.value() * data_type::getValue(rowid, colid, dist);\n                data_type::finalPos(rowid, colid, dist);\n                col_values[colid * n_res_rows + rowid] += value;\n            }\n        }\n\n        std::vector< std::map<index_type, value_type > > result;\n        boost::mpi::gather(utility::get_communicator(A), col_values, result, 0);\n\n        if(rank == 0) {\n            typedef typename std::map<index_type, value_type>::iterator itr_t;\n            for(size_t i = 0; i < result.size(); ++i) {\n                itr_t proc_itr = result[i].begin();\n                for(; proc_itr != result[i].end(); proc_itr++) {\n                    int row = proc_itr->first % n_res_rows;\n                    int col = proc_itr->first / n_res_rows;\n                    sketch_of_A.Update(row, col, proc_itr->second);\n                }\n            }\n        }\n    }\n};\n\n\n/* Specialization: SpParMat for input, Elemental[* / *] output */\ntemplate <typename IndexType,\n          typename ValueType,\n          template <typename> class IdxDistributionType,\n          template <typename> class ValueDistribution>\nstruct hash_transform_t <\n    SpParMat<IndexType, ValueType, SpDCCols<IndexType, ValueType> >,\n    El::DistMatrix<ValueType, El::STAR, El::STAR>,\n    IdxDistributionType,\n    ValueDistribution > :\n        public hash_transform_data_t<IdxDistributionType,\n                                     ValueDistribution> {\n    typedef IndexType index_type;\n    typedef ValueType value_type;\n    typedef SpDCCols< index_type, value_type > col_t;\n    typedef FullyDistVec< index_type, value_type> mpi_vector_t;\n    typedef SpParMat< index_type, value_type, col_t > matrix_type;\n    typedef El::DistMatrix< value_type, El::STAR, El::STAR > output_matrix_type;\n    typedef hash_transform_data_t<IdxDistributionType,\n                                  ValueDistribution> data_type;\n\n\n    /**\n     * Regular constructor\n     */\n    hash_transform_t (int N, int S, base::context_t& context) :\n        data_type(N, S, context) {\n\n    }\n\n    /**\n     * Copy constructor\n     */\n    template <typename InputMatrixType,\n              typename OutputMatrixType>\n    hash_transform_t (hash_transform_t<InputMatrixType,\n                                       OutputMatrixType,\n                                       IdxDistributionType,\n                                       ValueDistribution>& other) :\n        data_type(other) {}\n\n    /**\n     * Constructor from data\n     */\n    hash_transform_t (hash_transform_data_t<IdxDistributionType,\n                                            ValueDistribution>& other_data) :\n        data_type(other_data) {}\n\n    template <typename Dimension>\n    void apply (const matrix_type &A, output_matrix_type &sketch_of_A,\n                Dimension dimension) const {\n        try {\n            apply_impl (A, sketch_of_A, dimension);\n        } catch(boost::mpi::exception e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::mpi_exception()\n                    << base::error_msg(e.what()) );\n        } catch (std::string e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(e) );\n        } catch (std::logic_error e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::combblas_exception()\n                    << base::error_msg(e.what()) );\n        } catch (std::bad_alloc e) {\n            SKYLARK_THROW_EXCEPTION (\n                base::skylark_exception()\n                    << base::error_msg(\"bad_alloc: out of memory\") );\n        }\n    }\n\n\nprivate:\n    /**\n     * Apply the sketching transform that is described in by the sketch_of_A.\n     */\n    template <typename Dimension>\n    void apply_impl (const matrix_type &A_,\n        output_matrix_type &sketch_of_A,\n        Dimension dist) const {\n\n        // We are essentially doing a 'const' access to A, but the necessary,\n        // 'const' option is missing from the interface\n        matrix_type &A = const_cast<matrix_type&>(A_);\n\n        const size_t rank = A.getcommgrid()->GetRank();\n\n        // extract columns of matrix\n        col_t &data = A.seq();\n\n        const size_t my_row_offset = utility::cb_my_row_offset(A);\n        const size_t my_col_offset = utility::cb_my_col_offset(A);\n\n        int n_res_cols = A.getncol();\n        int n_res_rows = A.getnrow();\n        data_type::get_res_size(n_res_rows, n_res_cols, dist);\n\n        // Apply sketch for all local values. Subsequently, all values are\n        // gathered on all processor and the \"local\" matrix is populated.\n        typedef std::map<index_type, value_type> col_values_t;\n        col_values_t col_values;\n        for(typename col_t::SpColIter col = data.begcol();\n            col != data.endcol(); col++) {\n            for(typename col_t::SpColIter::NzIter nz = data.begnz(col);\n                nz != data.endnz(col); nz++) {\n\n                index_type rowid = nz.rowid()  + my_row_offset;\n                index_type colid = col.colid() + my_col_offset;\n\n                const value_type value =\n                    nz.value() * data_type::getValue(rowid, colid, dist);\n                data_type::finalPos(rowid, colid, dist);\n                col_values[colid * n_res_rows + rowid] += value;\n            }\n        }\n\n        std::vector< std::map<index_type, value_type > > result;\n        boost::mpi::all_gather(\n                utility::get_communicator(A), col_values, result);\n\n        typedef typename std::map<index_type, value_type>::iterator itr_t;\n        for(size_t i = 0; i < result.size(); ++i) {\n            itr_t proc_itr = result[i].begin();\n            for(; proc_itr != result[i].end(); proc_itr++) {\n                int row = proc_itr->first % n_res_rows;\n                int col = proc_itr->first / n_res_rows;\n                sketch_of_A.Update(row, col, proc_itr->second);\n            }\n        }\n    }\n};\n#endif\n\n} } /** namespace skylark::sketch */\n\n#endif // SKYLARK_HASH_TRANSFORM_MIXED_HPP\n", "meta": {"hexsha": "0fa1451fef95e8d0899950f7f59d9ba5f4b617b7", "size": 29534, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sketch/hash_transform_Mixed.hpp", "max_stars_repo_name": "xdata-skylark/libskylark", "max_stars_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2015-01-20T03:12:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-10T04:05:21.000Z", "max_issues_repo_path": "sketch/hash_transform_Mixed.hpp", "max_issues_repo_name": "xdata-skylark/libskylark", "max_issues_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2015-05-12T09:31:23.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-05T14:45:46.000Z", "max_forks_repo_path": "sketch/hash_transform_Mixed.hpp", "max_forks_repo_name": "xdata-skylark/libskylark", "max_forks_repo_head_hexsha": "89c3736136a24d519c14fc0738c21f37f1e10360", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2015-01-18T23:02:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-12T07:30:35.000Z", "avg_line_length": 37.8641025641, "max_line_length": 84, "alphanum_fraction": 0.5905735762, "num_tokens": 6644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23901246187607114}}
{"text": "//Copyright (c) 2013 Singapore-MIT Alliance for Research and Technology\n//Licensed under the terms of the MIT License, as described in the file:\n// license.txt (http://opensource.org/licenses/MIT)\n\n#include <boost/algorithm/string.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include <cmath>\n#include <map>\n\n#include \"models/IntersectionDrivingModel.hpp\"\n#include \"DriverUpdateParams.hpp\"\n#include \"Driver.hpp\"\n#include \"util/Utils.hpp\"\n\nusing namespace std;\nusing namespace sim_mob;\n\nMITSIM_IntDriving_Model::MITSIM_IntDriving_Model() :\nintersectionAttentivenessFactorMin(0), intersectionAttentivenessFactorMax(0), minimumGap(0), impatienceFactor(0)\n{\n    modelType = IntModelType::Int_Model_MITSIM;\n}\n\nMITSIM_IntDriving_Model::MITSIM_IntDriving_Model(DriverUpdateParams& params) :\nintersectionAttentivenessFactorMin(0), intersectionAttentivenessFactorMax(0), minimumGap(0), impatienceFactor(0)\n{\n    modelType = IntModelType::Int_Model_MITSIM;\n    readDriverParameters(params);\n}\n\nMITSIM_IntDriving_Model::~MITSIM_IntDriving_Model()\n{\n}\n\ndouble MITSIM_IntDriving_Model::getIntersectionAttentivenessFactorMin() const\n{\n    return intersectionAttentivenessFactorMin;\n}\n\ndouble MITSIM_IntDriving_Model::getIntersectionAttentivenessFactorMax() const\n{\n    return intersectionAttentivenessFactorMax;\n}\n\ndouble MITSIM_IntDriving_Model::getImpatienceFactor() const\n{\n    return impatienceFactor;\n}\n\nvoid MITSIM_IntDriving_Model::readDriverParameters(DriverUpdateParams &params)\n{\n    string modelName = \"general_driver_model\";\n    string critical_gap_addon;\n    bool isAMOD = false;\n\n    //Check if the vehicle is autonomous\n    if (params.driver->getParent()->amodId != \"-1\")\n    {\n        isAMOD = true;\n    }\n\n    //Get the parameter manager instance for the respective type of vehicle (normal or AMOD)\n    ParameterManager *parameterMgr = ParameterManager::Instance(isAMOD);\n\n    //Read the parameter values\n    parameterMgr->param(modelName, \"intersection_attentiveness_factor_min\", intersectionAttentivenessFactorMin, 1.0);\n    parameterMgr->param(modelName, \"intersection_attentiveness_factor_max\", intersectionAttentivenessFactorMax, 3.0);\n    parameterMgr->param(modelName, \"minimum_gap\", minimumGap, 0.0);\n    parameterMgr->param(modelName, \"critical_gap_addon\", critical_gap_addon, string(\"0.0 2.5\"));\n    parameterMgr->param(modelName, \"impatience_factor\", impatienceFactor, 0.2);\n\n    //Vector to store the tokenized parameters\n    std::vector<string> gapAddonParams;\n\n    //Index\n    int index = 0;\n\n    //Tokenize the gap add-on parameters\n    boost::trim(critical_gap_addon);\n    boost::split(gapAddonParams, critical_gap_addon, boost::is_any_of(\" \"), boost::token_compress_on);\n\n    //Convert into numeric form\n    vector<string>::iterator itStr = gapAddonParams.begin();\n    while (itStr != gapAddonParams.end())\n    {\n        double res = 0;\n\n        try\n        {\n            res = boost::lexical_cast<double>(itStr->c_str());\n        }\n        catch (boost::bad_lexical_cast&)\n        {\n            std::stringstream str;\n            str << __func__ << \": Could not covert \" << *itStr << \" to type double.\";\n            throw std::runtime_error(str.str());\n        }\n\n        criticalGapAddOn[index] = res;\n\n        ++index;\n        ++itStr;\n    }\n}\n\ndouble MITSIM_IntDriving_Model::calcBrakeToStopAcc(double distance, DriverUpdateParams &params)\n{\n    double acc = 0;\n\n    if (distance > Math::DOUBLE_EPSILON)\n    {\n        //v^2 = u^2 + 2as (Equation of motion)\n        //So, a = (v^2 - u^2) / 2s\n        //v = final velocity, u = initial velocity\n        //a = acceleration, s = displacement\n        double sqCurrVel = params.perceivedFwdVelocity * params.perceivedFwdVelocity;\n\n        acc = -sqCurrVel / distance * 0.5;\n\n        if (acc <= params.normalDeceleration)\n        {\n            acc = params.normalDeceleration;\n        }\n        else\n        {\n            double dt = params.nextStepSize;\n            double vt = params.perceivedFwdVelocity * dt;\n            double a = dt * dt;\n            double b = 2.0 * vt - params.normalDeceleration * a;\n            double c = sqCurrVel + 2.0 * params.normalDeceleration * (distance - vt);\n            double d = b * b - 4.0 * a * c;\n\n            if (!(d < 0 || a <= 0.0))\n            {\n                acc = (sqrt(d) - b) / a * 0.5;\n            }\n        }\n    }\n    else\n    {\n        double dt = params.nextStepSize;\n        acc = (dt > 0.0) ? -(params.perceivedFwdVelocity) / dt : params.maxDeceleration;\n    }\n\n    //Make sure the value is bounded\n    if (acc > params.maxAcceleration)\n    {\n        acc = params.maxAcceleration;\n    }\n\n    if (acc < params.maxDeceleration)\n    {\n        acc = params.maxDeceleration;\n    }\n\n    return acc;\n}\n\ndouble MITSIM_IntDriving_Model::calcCrawlingAcc(double distance, DriverUpdateParams& params)\n{\n    //Acceleration to slowly crawl towards the conflict point\n    return 2 * ((distance / 2) - params.perceivedFwdVelocity * params.nextStepSize) / (params.nextStepSize * params.nextStepSize);\n}\n\ndouble MITSIM_IntDriving_Model::calcArrivalTime(double distance, DriverUpdateParams& params)\n{\n    double arrivalTime = -1, acceleration = 0, finalVel = 0;\n\n    //The final velocity is limited by the turning speed, so calculate the acceleration required to\n    //achieve the final velocity\n    //v^2 = u^2 + 2as\n    //So, a = (v^2 - u^2) / (2s)\n\n    //Get the speed limit and convert it to m/s\n    finalVel = 1; //currTurning->getTurningSpeed() / 3.6;\n\n    //Calculate the acceleration\n    acceleration = ((finalVel * finalVel) - (params.perceivedFwdVelocity * params.perceivedFwdVelocity)) / (2 * distance);\n\n    //We know s = ut + (1/2)at^2\n    //To find the time required, we rearrange the equation as follows:\n    //(1/2)at^2 + ut - s = 0    This is a quadratic equation AX^2 + BX + C = 0 and we can solve for t\n    //A = (1/2)a; B = u; C = -s\n\n    if (acceleration == 0 && params.perceivedFwdVelocity != 0)\n    {\n        //Acceleration is 0, so we have a linear relation : ut - s = 0\n        arrivalTime = distance / params.perceivedFwdVelocity;\n    }\n    else\n    {\n        //As it is a quadratic equation, we will have two solutions\n        double sol1 = 0, sol2 = 0;\n\n        //The discriminant (b^2 - 4ac)\n        double discriminant = (params.perceivedFwdVelocity * params.perceivedFwdVelocity) - (2 * acceleration * (-distance));\n\n        if (discriminant >= 0)\n        {\n            //Calculate the solutions\n            sol1 = (-params.perceivedFwdVelocity - sqrt(discriminant)) / acceleration;\n            sol2 = (-params.perceivedFwdVelocity + sqrt(discriminant)) / acceleration;\n\n            //As time can be negative, return the solution that is a positive value \n            if (sol1 >= 0 && sol2 >= 0)\n            {\n                arrivalTime = min(sol1, sol2);\n            }\n            else if (sol1 >= 0)\n            {\n                arrivalTime = sol1;\n            }\n            else if (sol2 >= 0)\n            {\n                arrivalTime = sol2;\n            }\n        }\n    }\n\n    return arrivalTime;\n}\n\ndouble MITSIM_IntDriving_Model::makeAcceleratingDecision(DriverUpdateParams &params)\n{\n    params.intDebugStr.clear();\n    std::stringstream debugStr;\n    double acc = params.maxAcceleration;\n    const double vehicleLength = params.driver->getVehicleLength();\n    const TurningGroup *currTurningGroup = currTurning->getTurningGroup();\n\n    //Reduce the reaction time in intersection          \n    params.reactionTimeCounter = params.reactionTimeCounter * Utils::generateFloat(intersectionAttentivenessFactorMin, intersectionAttentivenessFactorMax);\n\n    //Safety margin distance in front of the vehicle (half a vehicle length seems a reasonable margin)\n    const double safeDist = 1.5 * vehicleLength;\n    double distToStopLine = params.driver->getDistToIntersection() - safeDist;\n\n    debugStr << \";t:\" << params.now.ms() << \";dSL:\" << distToStopLine;\n\n    //Check if we've stopped close enough to the stop line\n    if (distToStopLine <= 1 && params.perceivedFwdVelocity <= 0.1)\n    {\n        params.hasStoppedForStopSign = true;\n        debugStr << \";StpSgn-Dne\";\n    }\n\n    //We have to stop for the stop sign\n    if (currTurningGroup->getRule() == TurningGroupRule::TURNING_GROUP_RULE_STOP_SIGN && !params.hasStoppedForStopSign && distToStopLine <= 5)\n    {\n        double brakingAcc = calcBrakeToStopAcc(distToStopLine, params);\n\n        if (acc > brakingAcc && params.perceivedFwdVelocity != 0)\n        {\n            acc = brakingAcc;\n            params.driver->setYieldingToInIntersection(-1);\n        }\n\n        debugStr << \";StpSgn\";\n        return acc;\n    }\n\n    //The turning conflicts for the current turning\n    const vector<TurningConflict *> &conflicts = currTurning->getConflictsOnPath();\n\n    //Select the nearest conflict ahead of us (the vector is sorted according to the distance from the start of the turning,\n    //we may have crossed some)\n    for (vector<TurningConflict *>::const_iterator itConflicts = conflicts.begin(); itConflicts != conflicts.end(); ++itConflicts)\n    {\n        const TurningConflict *conflict = *itConflicts;\n        bool isGapRejected = false;\n\n        debugStr << \";Cfl:\" << conflict->getConflictId();\n\n        //The priority of the turnings in the conflict\n        //0 - equal priority, 1 - first turning has priority, 2 - second turning has priority\n        int priority = conflict->getPriority();\n\n        bool isFirstTurning = (conflict->getFirstTurning() == currTurning) ? true : false;\n\n        //The distance to conflict point from the start of the turning\n        double cfltDistFrmTurning = 0;\n\n        //The distance to conflict point from our position\n        double distToConflict = 0;\n\n        //Check which turning in the conflict has the higher priority. If our turning has higher priority, \n        //ignore all vehicles in the conflict as they will slow down for us\n        if (isFirstTurning)\n        {\n            //Our turning has priority, or equal priority but other turning has\n            //stop sign, ignore the vehicles in this conflict\n            if (priority == 1 ||\n                    (priority == 0 && currTurningGroup->getRule() == TurningGroupRule::TURNING_GROUP_RULE_NO_STOP_SIGN &&\n                    conflict->getSecondTurning()->getTurningGroup()->getRule() == TurningGroupRule::TURNING_GROUP_RULE_STOP_SIGN))\n            {\n                continue;\n            }\n\n            //Get the distance to conflict point\n            cfltDistFrmTurning = conflict->getFirstConflictDistance();\n        }\n        else\n        {\n            //Our turning has priority, or equal priority but other turning has\n            //stop sign, ignore the vehicles in this conflict\n            if (priority == 2 ||\n                    (priority == 0 && currTurningGroup->getRule() == TurningGroupRule::TURNING_GROUP_RULE_NO_STOP_SIGN &&\n                    conflict->getFirstTurning()->getTurningGroup()->getRule() == TurningGroupRule::TURNING_GROUP_RULE_STOP_SIGN))\n            {\n                continue;\n            }\n\n            //Get the distance to conflict point\n            cfltDistFrmTurning = conflict->getSecondConflictDistance();\n        }\n\n        //Calculate the distance to conflict point from current position\n\n        //If the vehicle is approaching the intersection rather than already in it, add the distance to the end\n        //of the segment to the distance to conflict\n        if (params.isApproachingIntersection)\n        {\n            distToConflict = cfltDistFrmTurning + params.driver->getDistToIntersection();\n        }\n        else\n        {\n            //Vehicle is in the intersection, so subtract the distance covered on the turning\n            distToConflict = cfltDistFrmTurning - params.driver->getDistCoveredOnCurrWayPt();\n        }\n\n        debugStr << \";DstCfl:\" << distToConflict;\n\n        //The distance at which the vehicle needs to come to a stand-still when yielding\n        double stoppingDist = 0;\n\n        //If the turning has a stop sign, we stop just before the intersection\n        if (currTurningGroup->getRule() == TurningGroupRule::TURNING_GROUP_RULE_STOP_SIGN)\n        {\n            stoppingDist = distToStopLine;\n        }\n        else\n        {\n            stoppingDist = distToConflict - safeDist;\n        }\n\n        debugStr << \";StpDis:\" << stoppingDist;\n\n        //If we're yet to reach the conflict, calculate the time required for us and the conflict driver\n        //else go to the next conflict\n        if (distToConflict > vehicleLength)\n        {\n            //Time taken to reach conflict by current driver\n            double timeToConflict = calcArrivalTime(abs(distToConflict), params);\n\n            if (timeToConflict == -1)\n            {\n                if (params.perceivedFwdVelocity > 1.0)\n                {\n                    timeToConflict = abs(distToConflict) / params.perceivedFwdVelocity;\n                }\n                else\n                {\n                    timeToConflict = 0;\n                }\n            }\n\n            debugStr << \";Time2Cfl:\" << timeToConflict;\n\n            //Calculate the critical gap\n            //It is the max of: minimumGap and the difference between the \n            //criticalGap for the turning conflict and a random value\n            double criticalGap = conflict->getCriticalGap();\n\n            //Add a random add-on value\n            criticalGap += Utils::nRandom(criticalGapAddOn[0], criticalGapAddOn[1]);\n\n            //Reduce by impatience on if equal priority\n            if (priority == 0)\n            {\n                criticalGap -= (params.impatienceTimer * impatienceFactor);\n            }\n\n            criticalGap = max(criticalGap, minimumGap);\n\n            debugStr << \";CGap:\" << criticalGap;            \n\n            //The map entry to the conflict and list of NearestVehicles on the it\n            map<const TurningConflict *, std::set<NearestVehicle, compare_NearestVehicle> >::iterator itConflictVehicles = params.conflictVehicles.find(conflict);\n\n            //Check if we have found an entry in the map\n            if (itConflictVehicles != params.conflictVehicles.end())\n            {\n                debugStr << \";#veh:\" << itConflictVehicles->second.size();\n\n                //Iterator to the list of nearest vehicles on the list\n                std::set<NearestVehicle, compare_NearestVehicle>::iterator itNearestVehicles = itConflictVehicles->second.begin();\n\n                //Look for the vehicle reaching the conflict point - the list is sorted according to the distance from the conflict\n                //point - distance less than 0 means yet to reach the conflict and greater than 0 means crossed the conflict point\n                for (; itNearestVehicles != itConflictVehicles->second.end(); ++itNearestVehicles)\n                {\n                    Driver *drv = const_cast<Driver *> (itNearestVehicles->driver);\n                    DriverUpdateParams &paramsOtherDriver = drv->getParams();\n\n                    debugStr << \";Veh:\" << paramsOtherDriver.parentId;                  \n                    debugStr << \";DisCfl:\" << itNearestVehicles->distance;\n\n                    //If a driver is already yielding to us, scan the next conflict\n                    if (itNearestVehicles->driver->getYieldingToInIntersection() == params.parentId)\n                    {\n                        debugStr << \";Yldng:\";                      \n                        break;\n                    }\n\n                    if (itNearestVehicles->distance >= -itNearestVehicles->driver->getVehicleLength() / 2 && itNearestVehicles->distance < 0.0)\n                    {\n                        //Other vehicle is blocking the conflict\n                        debugStr << \";StpPtCrsd:\";\n                        isGapRejected = true;\n                    }\n                    else if (itNearestVehicles->distance < -itNearestVehicles->driver->getVehicleLength())\n                    {\n                        //The vehicle is yet to arrive at the conflict point\n                        \n                        //Time taken to reach conflict point by incoming driver\n                        double timeToConflictOtherDriver = 0;\n\n                        //Speed of the incoming vehicle (m/s))\n                        double speed = itNearestVehicles->driver->getVehicle()->getVelocity();\n\n                        if (speed > 1.0)\n                        {\n                            //Negate the distance while calculating the time\n                            timeToConflictOtherDriver = abs(itNearestVehicles->distance) / speed;\n                        }                       \n\n                        //The gap between the drivers\n                        double gap = abs(timeToConflictOtherDriver - timeToConflict);\n\n                        debugStr << \";T2Cfl:\" << timeToConflictOtherDriver << \";gap:\" << gap;\n\n                        //The gap was accepted, but we need to check if there's enough space after the conflict\n                        //point. A vehicle with higher priority might collide with us if we can't go past \n                        //the conflict point\n                        if (gap >= criticalGap && timeToConflictOtherDriver != 0 && timeToConflict != 0)\n                        {\n                            debugStr << \";gp>=cgap\";                            \n\n                            //Distance of forward vehicle from the conflict point\n                            double distAheadOfConflict = DBL_MAX;\n                            \n                            if (params.nvFwd.driver)\n                            {\n                                //The forward driver exists, reject the gap if he's not far enough ahead of the conflict\n                                distAheadOfConflict = params.nvFwd.distance - distToConflict;\n                            }                               \n                            else if (params.nvFwdNextLink.driver)\n                            {\n                                //There is no forward driver, but there is one after the intersection\n                                distAheadOfConflict = params.nvFwdNextLink.distance - distToConflict;\n                            }\n\n                            //Reject the gap if we don't have at least 5 vehicle length of space\n                            if (distAheadOfConflict < (5 * vehicleLength))\n                            {\n                                isGapRejected = true;\n                            }\n                        }\n                        else if (timeToConflict != 0 && timeToConflictOtherDriver == 0)\n                        {\n                            //Other driver has stopped\n                            debugStr << \";Time2Cfl!=0&&T2Cfl!=0\";                           \n\n                            //Assume the vehicle starts moving with the same speed as us                            \n\n                            //Assumed time calculated based on our speed\n                            double assumedTimeToConflict = abs(itNearestVehicles->distance) / params.currSpeed;\n\n                            debugStr << \";AsmdT2Cfl:\" << assumedTimeToConflict;                     \n\n                            //Assumed gap\n                            double assumedGap = abs(assumedTimeToConflict - timeToConflict);\n\n                            //Check if the gap is accepted\n                            if (assumedGap <= criticalGap && itNearestVehicles->driver->getYieldingToInIntersection() == -1)\n                            {\n                                debugStr << \";AsmdGap-Rjct\";                                \n                                isGapRejected = true;\n                            }\n                            else\n                            {\n                                debugStr << \";AsmdGap-Accpt\";\n                            }\n                        }                           \n                        else if (timeToConflict == 0 && timeToConflictOtherDriver != 0)\n                        {\n                            //We have stopped, crawl till we can better judge the gap\n                            debugStr << \";Time2Cfl==0&&T2Cfl!=0\";\n\n                            if (distToConflict > abs(itNearestVehicles->distance) && itNearestVehicles->driver->getYieldingToInIntersection() == -1)\n                            {\n                                //If we're stationary, crawl to conflict point\n                                double crawlAcc = calcCrawlingAcc(stoppingDist, params);                                \n\n                                if (acc > crawlAcc)\n                                {\n                                    acc = crawlAcc;\n                                    params.driver->setYieldingToInIntersection(paramsOtherDriver.parentId);\n\n                                    debugStr << \";Crawl:\" << crawlAcc << \";YldVeh:\" << paramsOtherDriver.parentId;                                  \n                                }\n                                else\n                                {\n                                    debugStr << \";XCrawl:\" << crawlAcc;\n                                    isGapRejected = true;\n                                }\n                            }\n                        }                           \n                        else if (timeToConflict == 0 && timeToConflictOtherDriver == 0)\n                        {\n                            //Both vehicles have stopped, break deadlock\n                            debugStr << \";Time2Cfl==0&&T2Cfl==0\";\n\n                            //Compare the distances, if the one nearer to the conflict can go through\n                            if (distToConflict > abs(itNearestVehicles->distance) && itNearestVehicles->driver->getYieldingToInIntersection() == -1)\n                            {\n                                debugStr << \";OthClser\";                                \n                                isGapRejected = true;\n                            }\n                            else\n                            {\n                                debugStr << \";IClsr\";\n                            }\n                        }                           \n                        else\n                        {\n                            //All other cases, reject gap\n                            isGapRejected = true;\n                        }\n                    }\n\n                    //If the gap has been rejected (slow down and stop)\n                    if (isGapRejected)\n                    {\n                        //Calculate the deceleration required to stop before conflict\n                        double brakingAcc = calcBrakeToStopAcc(stoppingDist, params);\n\n                        debugStr << \";Gap-Rjct\" << \";brake:\" << brakingAcc;\n\n                        //If this deceleration is smaller than the one we have previously, use this\n                        if (acc > brakingAcc)\n                        {\n                            acc = brakingAcc;\n                            params.driver->setYieldingToInIntersection(paramsOtherDriver.parentId);\n\n                            debugStr << \";YldVeh:\" << paramsOtherDriver.parentId << \"Gap-Rjct\";\n                        }\n                    }\n                }\n            }\n        }\n        else\n        {\n            debugStr << \";XdCflt\" << conflict->getConflictId() << \";dist:\" << distToConflict;\n        }\n    }\n\n    params.intDebugStr = debugStr.str();\n    return acc;\n}\n", "meta": {"hexsha": "3ea3e9ddaa669e1acde14e0af7bf2101b2d5c2cf", "size": 23528, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dev/Basic/short/entities/roles/driver/MITSIM_IntDriving_Model.cpp", "max_stars_repo_name": "gusugusu1018/simmobility-prod", "max_stars_repo_head_hexsha": "d30a5ba353673f8fd35f4868c26994a0206a40b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2018-12-21T08:21:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T09:47:59.000Z", "max_issues_repo_path": "dev/Basic/short/entities/roles/driver/MITSIM_IntDriving_Model.cpp", "max_issues_repo_name": "gusugusu1018/simmobility-prod", "max_issues_repo_head_hexsha": "d30a5ba353673f8fd35f4868c26994a0206a40b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T13:42:47.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-13T04:11:45.000Z", "max_forks_repo_path": "dev/Basic/short/entities/roles/driver/MITSIM_IntDriving_Model.cpp", "max_forks_repo_name": "gusugusu1018/simmobility-prod", "max_forks_repo_head_hexsha": "d30a5ba353673f8fd35f4868c26994a0206a40b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2018-11-28T07:30:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-05T02:22:26.000Z", "avg_line_length": 41.2049036778, "max_line_length": 162, "alphanum_fraction": 0.5474753485, "num_tokens": 4962, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.23898528161622076}}
{"text": "#ifndef PARMCB_SPTREES_HPP_\n#define PARMCB_SPTREES_HPP_\n\n//    Copyright (C) Dimitrios Michail 2019 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n\n#include <boost/throw_exception.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/property_map/function_property_map.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/graph_concepts.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include <parmcb/detail/lex_dijkstra.hpp>\n#include <parmcb/detail/util.hpp>\n\n#include <parmcb/forestindex.hpp>\n#include <parmcb/spvecgf2.hpp>\n\n#include <memory>\n#include <stack>\n#include <functional>\n\n\nnamespace parmcb {\n\n    template<class Graph, class WeightMap> class SPNode;\n    template<class Graph, class WeightMap> class SPTree;\n    template<class Graph, class WeightMap, class T> struct SPSubtree;\n    template<class Graph, class WeightMap, bool ParallelUsingTBB> class SPTrees;\n    template<class Graph, class WeightMap> class CandidateCycle;\n    template<class Graph> struct SerializableCandidateCycle;\n    template<class Graph, class WeightMap> struct SerializableMinOddCycle;\n    template<class Graph, class WeightMap> struct SerializableMinOddCycleMinOp;\n\n    template<class Graph, class WeightMap>\n    class SPNode {\n    public:\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n        SPNode() :\n                _vertex(), _parity(false), _weight(WeightType()), _pred(), _has_pred(false) {\n        }\n\n        SPNode(Vertex vertex, WeightType weight) :\n                _vertex(vertex), _parity(false), _weight(WeightType()), _pred(), _has_pred(false) {\n        }\n\n        SPNode(Vertex vertex, WeightType weight, const Edge &pred) :\n                _vertex(vertex), _parity(false), _weight(weight), _pred(pred), _has_pred(true) {\n        }\n\n        void add_child(std::shared_ptr<SPNode<Graph, WeightMap>> c) {\n            _children.push_back(c);\n        }\n\n        std::vector<std::shared_ptr<SPNode<Graph, WeightMap>>>& children() {\n            return _children;\n        }\n\n        Vertex& vertex() {\n            return _vertex;\n        }\n\n        bool& parity() {\n            return _parity;\n        }\n\n        WeightType& weight() {\n            return _weight;\n        }\n\n        const Edge& pred() {\n            return _pred;\n        }\n\n        bool has_pred() {\n            return _has_pred;\n        }\n\n    private:\n        Vertex _vertex;\n        bool _parity;\n        WeightType _weight;\n        Edge _pred;\n        bool _has_pred;\n        std::vector<std::shared_ptr<SPNode<Graph, WeightMap>>> _children;\n    };\n\n    template<class Graph, class WeightMap, class T>\n    struct SPSubtree {\n        T info;\n        std::shared_ptr<SPNode<Graph, WeightMap>> root;\n\n        SPSubtree(T info, std::shared_ptr<SPNode<Graph, WeightMap>> root) :\n                info(info), root(root) {\n        }\n    };\n\n    template<class Graph, class WeightMap>\n    class SPTree {\n    public:\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIt;\n        typedef typename boost::property_map<Graph, boost::vertex_index_t>::type VertexIndexMapType;\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n        SPTree(std::size_t id, const Graph &g, const VertexIndexMapType& index_map, const WeightMap &weight_map, const Vertex &source) :\n                _id(id), _g(g), _weight_map(weight_map), _index_map(index_map), _source(\n                        source), _tree_node_map(boost::num_vertices(g)), _first_in_path(boost::num_vertices(g)) {\n            initialize();\n        }\n\n        void update_parities(const std::set<Edge> &edges) {\n            std::stack<SPSubtree<Graph, WeightMap, bool>> stack;\n            stack.emplace(false, _root);\n\n            while (!stack.empty()) {\n                SPSubtree<Graph, WeightMap, bool> r = stack.top();\n                stack.pop();\n\n                r.root->parity() = r.info;\n                for (auto c : r.root->children()) {\n                    bool is_signed = edges.find(c->pred()) != edges.end();\n                    stack.emplace(SPSubtree<Graph, WeightMap, bool> { static_cast<bool>(r.info ^ is_signed), c });\n                }\n            }\n        }\n\n        std::shared_ptr<SPNode<Graph, WeightMap>> node(const Vertex &v) const {\n            return _tree_node_map[_index_map[v]];\n        }\n\n        const Vertex& source() const {\n            return _source;\n        }\n\n        const Graph& graph() const {\n            return _g;\n        }\n\n        const std::size_t id() const {\n            return _id;\n        }\n\n        const Vertex first(const Vertex &v) {\n            auto vindex = _index_map[v];\n            return _first_in_path[vindex];\n        }\n\n        template<class EdgeIterator>\n        std::vector<CandidateCycle<Graph, WeightMap>> create_candidate_cycles(EdgeIterator begin,\n                EdgeIterator end) const {\n            // collect tree edges\n            std::set<Edge> tree_edges;\n            VertexIt vi, viend;\n            for (boost::tie(vi, viend) = boost::vertices(_g); vi != viend; ++vi) {\n                auto v = *vi;\n                auto vindex = _index_map[v];\n                std::shared_ptr<SPNode<Graph, WeightMap>> n = _tree_node_map[vindex];\n                if (n != nullptr && n->has_pred()) {\n                    tree_edges.insert(n->pred());\n                }\n            }\n\n            // loop over (non-tree) provided edges and create candidate cycles\n            std::vector<CandidateCycle<Graph, WeightMap>> cycles;\n            for (EdgeIterator it = begin; it != end; it++) {\n                Edge e = *it;\n                if (tree_edges.find(e) != tree_edges.end()) {\n                    continue;\n                }\n\n                // non-tree edge\n                std::shared_ptr<SPNode<Graph, WeightMap>> v = node(boost::source(e, _g));\n                if (v == nullptr) {\n                    continue;\n                }\n                std::shared_ptr<SPNode<Graph, WeightMap>> u = node(boost::target(e, _g));\n                if (u == nullptr) {\n                    continue;\n                }\n\n                if (_first_in_path[_index_map[v->vertex()]] == _first_in_path[_index_map[u->vertex()]]) {\n                    // shortest paths start with the same vertex, discard\n                    continue;\n                }\n\n                WeightType cycle_weight = boost::get(_weight_map, e) + v->weight() + u->weight();\n                cycles.emplace_back(_id, e, cycle_weight);\n            }\n            return cycles;\n        }\n\n        std::vector<CandidateCycle<Graph, WeightMap>> create_candidate_cycles() const {\n            auto itPair = boost::edges(_g);\n            return create_candidate_cycles(itPair.first, itPair.second);\n        }\n\n        std::vector<SerializableCandidateCycle<Graph>> create_serializable_candidate_cycles(\n                const ForestIndex<Graph> &forest_index) {\n            // collect tree edges\n            std::set<Edge> tree_edges;\n            VertexIt vi, viend;\n            for (boost::tie(vi, viend) = boost::vertices(_g); vi != viend; ++vi) {\n                auto v = *vi;\n                auto vindex = _index_map[v];\n                std::shared_ptr<SPNode<Graph, WeightMap>> n = _tree_node_map[vindex];\n                if (n != nullptr && n->has_pred()) {\n                    tree_edges.insert(n->pred());\n                }\n            }\n\n            // loop over all non-tree edges and create candidate cycles\n            std::vector<SerializableCandidateCycle<Graph>> cycles;\n            for (const auto &e : boost::make_iterator_range(boost::edges(_g))) {\n                if (tree_edges.find(e) != tree_edges.end()) {\n                    continue;\n                }\n\n                // non-tree edge\n                std::shared_ptr<SPNode<Graph, WeightMap>> v = node(boost::source(e, _g));\n                if (v == nullptr) {\n                    continue;\n                }\n                std::shared_ptr<SPNode<Graph, WeightMap>> u = node(boost::target(e, _g));\n                if (u == nullptr) {\n                    continue;\n                }\n\n                if (_first_in_path[_index_map[v->vertex()]] == _first_in_path[_index_map[u->vertex()]]) {\n                    // shortest paths start with the same vertex, discard\n                    continue;\n                }\n\n                cycles.emplace_back(_source, forest_index(e));\n            }\n\n            return cycles;\n        }\n\n    private:\n        const std::size_t _id;\n        const Graph &_g;\n        const WeightMap &_weight_map;\n        const VertexIndexMapType &_index_map;\n        const Vertex _source;\n\n        /*\n         * Shortest path tree root\n         */\n        std::shared_ptr<SPNode<Graph, WeightMap>> _root;\n        /*\n         * Map from vertex to shortest path tree node\n         */\n        std::vector<std::shared_ptr<SPNode<Graph, WeightMap>>> _tree_node_map;\n        /*\n         * First vertex in shortest path from root to a vertex.\n         */\n        std::vector<Vertex> _first_in_path;\n\n        void initialize() {\n            // run shortest path\n            std::vector<WeightType> dist(boost::num_vertices(_g), (std::numeric_limits<WeightType>::max)());\n            boost::function_property_map<parmcb::detail::VertexIndexFunctor<Graph, WeightType>, Vertex, WeightType&> dist_map(\n                    parmcb::detail::VertexIndexFunctor<Graph, WeightType>(dist, _index_map));\n            std::vector<std::tuple<bool, Edge>> pred(boost::num_vertices(_g), std::make_tuple(false, Edge()));\n            boost::function_property_map<parmcb::detail::VertexIndexFunctor<Graph, std::tuple<bool, Edge>>, Vertex,\n                    std::tuple<bool, Edge>&> pred_map(\n                    parmcb::detail::VertexIndexFunctor<Graph, std::tuple<bool, Edge> >(pred, _index_map));\n            lex_dijkstra(_g, _weight_map, _source, dist_map, pred_map);\n\n            // create tree nodes and mapping\n            VertexIt vi, viend;\n            for (boost::tie(vi, viend) = boost::vertices(_g); vi != viend; ++vi) {\n                auto v = *vi;\n                auto vindex = _index_map[v];\n                auto p = boost::get(pred_map, v);\n                if (v == _source) {\n                    _tree_node_map[vindex] = std::shared_ptr<SPNode<Graph, WeightMap>>(\n                            new SPNode<Graph, WeightMap>(v, dist[vindex]));\n                    _root = _tree_node_map[vindex];\n                } else if (std::get<0>(p)) {\n                    Edge e = std::get<1>(p);\n                    _tree_node_map[vindex] = std::shared_ptr<SPNode<Graph, WeightMap>>(\n                            new SPNode<Graph, WeightMap>(v, dist[vindex], e));\n                }\n            }\n\n            // link tree nodes\n            for (boost::tie(vi, viend) = boost::vertices(_g); vi != viend; ++vi) {\n                auto v = *vi;\n                auto p = boost::get(pred_map, v);\n                if (std::get<0>(p)) {\n                    auto e = std::get<1>(p);\n                    auto u = boost::opposite(e, v, _g);\n                    auto vindex = _index_map[v];\n                    auto uindex = _index_map[u];\n                    _tree_node_map[uindex]->add_child(_tree_node_map[vindex]);\n                }\n            }\n\n            // compute first in path\n            compute_first_in_path();\n        }\n\n        void compute_first_in_path() {\n            std::stack<SPSubtree<Graph, WeightMap, Vertex>> stack;\n            stack.emplace(_source, _root);\n\n            while (!stack.empty()) {\n                SPSubtree<Graph, WeightMap, Vertex> r = stack.top();\n                stack.pop();\n\n                if (r.root == _root) {\n                    auto v = r.root->vertex();\n                    auto vindex = _index_map[v];\n                    _first_in_path[vindex] = v;\n                    for (auto c : r.root->children()) {\n                        stack.emplace(SPSubtree<Graph, WeightMap, Vertex> { static_cast<Vertex>(c->vertex()), c });\n                    }\n                } else {\n                    auto v = r.root->vertex();\n                    auto vindex = _index_map[v];\n                    _first_in_path[vindex] = r.info;\n                    for (auto c : r.root->children()) {\n                        stack.emplace(SPSubtree<Graph, WeightMap, Vertex> { static_cast<Vertex>(r.info), c });\n                    }\n                }\n            }\n        }\n\n    };\n\n    template<class Graph, class WeightMap>\n    class CandidateCycle {\n    public:\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n        CandidateCycle(std::size_t tree, const Edge &e, WeightType weight) :\n                _tree(tree), _e(e), _weight(weight) {\n        }\n\n        CandidateCycle(const CandidateCycle &c) :\n                _tree(c._tree), _e(c._e), _weight(c._weight) {\n        }\n\n        CandidateCycle& operator=(const CandidateCycle &other) {\n            if (this != &other) {\n                _tree = other._tree;\n                _e = other._e;\n                _weight = other._weight;\n            }\n            return *this;\n        }\n\n        std::size_t tree() const {\n            return _tree;\n        }\n\n        const Edge& edge() const {\n            return _e;\n        }\n\n        const WeightType& weight() const {\n            return _weight;\n        }\n\n    private:\n        std::size_t _tree;\n        Edge _e;\n        WeightType _weight;\n    };\n\n    template<class Graph>\n    struct SerializableCandidateCycle {\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        typedef typename ForestIndex<Graph>::size_type Edge;\n\n        SerializableCandidateCycle() {\n        }\n\n        SerializableCandidateCycle(Vertex v, Edge e) :\n                v(v), e(e) {\n        }\n\n        template<typename Archive>\n        void serialize(Archive &ar, const unsigned) {\n            ar & v;\n            ar & e;\n        }\n\n        Vertex v;\n        Edge e;\n    };\n\n    template<class Graph, class WeightMap>\n    struct SerializableMinOddCycle {\n        typedef typename ForestIndex<Graph>::size_type Edge;\n        typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n        SerializableMinOddCycle() :\n                exists(false) {\n        }\n\n        SerializableMinOddCycle(std::vector<Edge> edges, WeightType weight, bool exists) :\n                edges(edges), weight(weight), exists(exists) {\n        }\n\n        SerializableMinOddCycle(const SerializableMinOddCycle<Graph, WeightMap> &c) :\n                edges(c.edges), weight(c.weight), exists(c.exists) {\n        }\n\n        SerializableMinOddCycle<Graph, WeightMap>& operator=(const SerializableMinOddCycle<Graph, WeightMap> &other) {\n            if (this != &other) {\n                edges = other.edges;\n                weight = other.weight;\n                exists = other.exists;\n            }\n            return *this;\n        }\n\n        template<typename Archive>\n        void serialize(Archive &ar, const unsigned) {\n            ar & edges;\n            ar & weight;\n            ar & exists;\n        }\n\n        std::vector<Edge> edges;\n        WeightType weight;\n        bool exists;\n    };\n\n    template<class Graph, class WeightMap>\n    struct SerializableMinOddCycleMinOp {\n\n        const SerializableMinOddCycle<Graph, WeightMap>& operator()(\n                const SerializableMinOddCycle<Graph, WeightMap> &lhs,\n                const SerializableMinOddCycle<Graph, WeightMap> &rhs) const {\n            if (!lhs.exists || !rhs.exists) {\n                if (lhs.exists) {\n                    return lhs;\n                } else {\n                    return rhs;\n                }\n            }\n            // both valid, compare\n            if (lhs.weight < rhs.weight) {\n                return lhs;\n            }\n            return rhs;\n        }\n\n    };\n\n    template<class Graph, class WeightMap>\n    class CandidateCycleToSerializableConverter {\n    public:\n        CandidateCycleToSerializableConverter(const std::vector<parmcb::SPTree<Graph, WeightMap>> &trees,\n                const ForestIndex<Graph> &forest_index) :\n                trees(trees), forest_index(forest_index) {\n        }\n\n        SerializableCandidateCycle<Graph> operator()(const CandidateCycle<Graph, WeightMap> &cycle) const {\n            return SerializableCandidateCycle<Graph>(trees.at(cycle.tree()).source(), forest_index(cycle.edge()));\n        }\n\n    private:\n        const std::vector<parmcb::SPTree<Graph, WeightMap>> &trees;\n        const ForestIndex<Graph> &forest_index;\n    };\n\n    template<class Graph, class WeightMap>\n    class CandidateCycleBuilder {\n    public:\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n        CandidateCycleBuilder(const Graph &g, const WeightMap &weight_map) :\n                g(g), weight_map(weight_map) {\n        }\n\n        std::tuple<std::set<Edge>, WeightType, bool> operator()(const std::vector<parmcb::SPTree<Graph, WeightMap>> &trees,\n                const CandidateCycle<Graph, WeightMap> &c, const std::set<Edge> &signed_edges, bool use_weight_limit,\n                WeightType weight_limit) const {\n\n            std::shared_ptr<SPNode<Graph, WeightMap>> v = trees[c.tree()].node(boost::source(c.edge(), g));\n            std::shared_ptr<SPNode<Graph, WeightMap>> u = trees[c.tree()].node(boost::target(c.edge(), g));\n\n            Edge e = c.edge();\n            if (v->parity() ^ u->parity() ^ (signed_edges.find(e) != signed_edges.end())) {\n                // odd cycle, validate\n                bool valid = true;\n                WeightType cycle_weight = boost::get(weight_map, e);\n                std::set<Edge> result;\n                result.insert(e);\n\n                if (use_weight_limit && cycle_weight > weight_limit) {\n                    return std::make_tuple(std::set<Edge> { }, 0.0, false);\n                }\n\n                // first part\n                Vertex w = boost::source(c.edge(), g);\n                std::shared_ptr<SPNode<Graph, WeightMap>> ws = trees[c.tree()].node(w);\n                while (ws->has_pred()) {\n                    Edge a = ws->pred();\n                    if (result.insert(a).second == false) {\n                        valid = false;\n                        break;\n                    }\n                    cycle_weight += boost::get(weight_map, a);\n                    if (use_weight_limit && cycle_weight > weight_limit) {\n                        valid = false;\n                        break;\n                    }\n                    w = boost::opposite(a, w, g);\n                    ws = trees[c.tree()].node(w);\n                }\n\n                if (!valid) {\n                    return std::make_tuple(std::set<Edge> { }, 0.0, false);\n                }\n\n                // second part\n                w = boost::target(c.edge(), g);\n                ws = trees[c.tree()].node(w);\n                while (ws->has_pred()) {\n                    Edge a = ws->pred();\n                    if (result.insert(a).second == false) {\n                        valid = false;\n                        break;\n                    }\n                    cycle_weight += boost::get(weight_map, a);\n                    if (use_weight_limit && cycle_weight > weight_limit) {\n                        valid = false;\n                        break;\n                    }\n                    w = boost::opposite(a, w, g);\n                    ws = trees[c.tree()].node(w);\n                }\n\n                if (!valid) {\n                    return std::make_tuple(std::set<Edge> { }, 0.0, false);\n                }\n\n                return std::make_tuple(result, cycle_weight, true);\n            }\n            return std::make_tuple(std::set<Edge> { }, 0.0, false);\n        }\n\n    private:\n        const Graph &g;\n        const WeightMap &weight_map;\n    };\n\n    template<class Graph, class WeightMap, bool ParallelUsingTBB>\n    class ShortestOddCycleLookup {\n    public:\n        typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n        typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n        typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n        ShortestOddCycleLookup(const Graph &g, const WeightMap &weight_map,\n                std::vector<parmcb::SPTree<Graph, WeightMap>> &trees,\n                std::vector<parmcb::CandidateCycle<Graph, WeightMap>> &cycles, bool sorted_cycles) :\n                g(g), weight_map(weight_map), candidate_cycle_builder(g, weight_map), trees(trees), cycles(cycles), sorted_cycles(\n                        sorted_cycles) {\n        }\n\n        std::tuple<std::set<Edge>, WeightType, bool> operator()(const std::set<Edge> &edges) {\n            return compute_shortest_odd_cycle(edges);\n        }\n\n    private:\n\n        template<bool is_tbb_enabled = ParallelUsingTBB>\n        std::tuple<std::set<Edge>, WeightType, bool> compute_shortest_odd_cycle(const std::set<Edge> &edges,\n                typename std::enable_if<!is_tbb_enabled>::type* = 0) {\n\n            for (std::size_t i = 0; i < trees.size(); i++) {\n                trees[i].update_parities(edges);\n            }\n\n            std::tuple<std::set<Edge>, WeightType, bool> min;\n\n            for (CandidateCycle<Graph, WeightMap> c : cycles) {\n                std::tuple<std::set<Edge>, WeightType, bool> cc = candidate_cycle_builder(trees, c, edges,\n                        std::get<2>(min), std::get<1>(min));\n\n                if (std::get<2>(cc)) {\n                    if (sorted_cycles) {\n                        return cc;\n                    }\n\n                    if (!std::get<2>(min)) {\n                        min = cc;\n                    } else {\n                        if (std::get<1>(cc) < std::get<1>(min)) {\n                            min = cc;\n                        }\n                    }\n                }\n            }\n            return min;\n        }\n\n        template<bool is_tbb_enabled = ParallelUsingTBB>\n        std::tuple<std::set<Edge>, WeightType, bool> compute_shortest_odd_cycle(const std::set<Edge> &edges,\n                typename std::enable_if<is_tbb_enabled>::type* = 0) {\n\n            tbb::parallel_for(tbb::blocked_range<std::size_t>(0, trees.size()),\n                    [&](const tbb::blocked_range<std::size_t> &r) {\n                        for (std::size_t i = r.begin(); i != r.end(); ++i) {\n                            trees[i].update_parities(edges);\n                        }\n                    });\n\n            std::less<WeightType> compare = std::less<WeightType>();\n            typedef std::tuple<std::set<Edge>, WeightType, bool> cycle_t;\n            auto cycle_min = [compare](const cycle_t &c1, const cycle_t &c2) {\n                if (!std::get<2>(c1) || !std::get<2>(c2)) {\n                    if (std::get<2>(c1)) {\n                        return c1;\n                    } else {\n                        return c2;\n                    }\n                }\n                // both valid, compare\n                if (!compare(std::get<1>(c2), std::get<1>(c1))) {\n                    return c1;\n                }\n                return c2;\n            };\n\n            return tbb::parallel_reduce(tbb::blocked_range<std::size_t>(0, cycles.size()),\n                    std::make_tuple(std::set<Edge>(), (std::numeric_limits<WeightType>::max)(), false),\n                    [&](tbb::blocked_range<std::size_t> r, auto running_min) {\n                        for (std::size_t i = r.begin(); i < r.end(); i++) {\n                            auto c = cycles[i];\n                            auto cc = candidate_cycle_builder(trees, c, edges, std::get<2>(running_min),\n                                    std::get<1>(running_min));\n                            if (std::get<2>(cc)) {\n                                if (!std::get<2>(running_min) || compare(std::get<1>(cc), std::get<1>(running_min))) {\n                                    running_min = cc;\n                                }\n                            }\n                        }\n                        return running_min;\n                    },\n                    cycle_min);\n        }\n\n        const Graph &g;\n        const WeightMap &weight_map;\n        const CandidateCycleBuilder<Graph, WeightMap> candidate_cycle_builder;\n        std::vector<parmcb::SPTree<Graph, WeightMap>> &trees;\n        std::vector<parmcb::CandidateCycle<Graph, WeightMap>> &cycles;\n        bool sorted_cycles;\n    };\n\n} // parmcb\n\n#endif\n", "meta": {"hexsha": "d5c945684b67acf8facba430fa52107157a3355a", "size": 25325, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/parmcb/sptrees.hpp", "max_stars_repo_name": "d-michail/parmcb", "max_stars_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/parmcb/sptrees.hpp", "max_issues_repo_name": "d-michail/parmcb", "max_issues_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/parmcb/sptrees.hpp", "max_forks_repo_name": "d-michail/parmcb", "max_forks_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4076809453, "max_line_length": 136, "alphanum_fraction": 0.5258440276, "num_tokens": 5523, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23898001888212939}}
{"text": "// this must define the same symbol as the main module file (numpy requirement)\n#define PY_ARRAY_UNIQUE_SYMBOL andres_graph_PyArray_API\n#define NO_IMPORT_ARRAY\n\n#include <Python.h>\n#include <boost/python.hpp>\n#include <vigra/numpy_array.hxx>\n#include <vigra/numpy_array_converters.hxx>\n#include <andres/graph/hdf5/graph.hxx>\n#include <andres/graph/hdf5/grid-graph.hxx>\n#include <vector>\n#include <string>\n\n\n#include \"andres/graph/grid-graph.hxx\"\n#include \"andres/functional.hxx\"\n#include \"andres/graph/graph.hxx\"\n#include \"andres/graph/threadpool.hxx\"\n#include \"andres/graph/neighborhood.hxx\"\n#include \"andres/graph/multicut-lifted/lifted_mc_model.hxx\"\n\n#include \"image.hxx\"\n\nnamespace bp = boost::python;\nnamespace agraph = andres::graph;\n\n\n\n\n\ntemplate<class MODEL>\nvoid addLongRangeEdges(\n    MODEL & model,\n    vigra::NumpyArray<2, float> edgePmap, // in 0-1\n    const float beta = 0.5f,\n    const int minRadius = 2,\n    const int maxRadius = 7                                                \n){  \n    GRAPH_CHECK_OP(model.originalGraph().shape(0), == ,edgePmap.shape(0),\"\");\n    GRAPH_CHECK_OP(model.originalGraph().shape(1), == ,edgePmap.shape(1),\"\");\n\n    typedef vigra::TinyVector<int,   2> Coord;\n    const auto shape = edgePmap.shape();\n\n    auto clipToImg = [&](const Coord & coord){\n        auto c = coord;\n        for(auto i=0; i<2; ++i){\n            c[i] = std::max(0, c[i]);\n            c[i] = std::min(int(shape[i]),c[i]);\n        }\n        return c;\n    };\n\n\n    // move a coordinate to local min\n    auto moveToMin = [&](const Coord & coord){\n        Coord coords[5] = {\n                coord,\n                clipToImg(coord+Coord(0,1)),\n                clipToImg(coord+Coord(1,0)),\n                clipToImg(coord+Coord(-1,-1)),\n                clipToImg(coord+Coord(-1, 0))\n        };\n        auto minVal = std::numeric_limits<float>::infinity();\n        auto minCoord = Coord();\n        for(size_t i=0; i<5; ++i){\n            const auto val = edgePmap[coord];\n            if(val<minVal){\n                minVal = val;\n                minCoord = coord;\n            }\n        }\n        return minCoord;\n    };\n    \n    auto & originalGraph = model.originalGraph();\n    auto & liftedGraph = model.liftedGraph();\n\n\n\n\n\n\n    int rad = 5;\n    \n    auto pOpt = agraph::ParallelOptions();\n    const auto nThreads = pOpt.numThreads(-1).getActualNumThreads();\n    \n    typedef vigra::TinyVector<float, 2> FCoord;\n    auto node = [&](const Coord & coord){\n        return size_t(coord[0] + coord[1]*shape[0]);\n    };\n\n    std::mutex graphMutex;\n    std::mutex mapMutex;\n\n    std::set<size_t > processed;\n\n    struct ToAdd{\n        size_t u,v;\n        float w;\n    };\n\n    size_t bufferSize = 1000000;\n    std::vector<std::vector<ToAdd> > buffers(nThreads);\n    for(auto & vec : buffers){\n        vec.reserve(bufferSize+1);\n    }\n\n\n\n    auto addToBuffer = [&](std::vector<ToAdd> & buffer,const size_t u_, const size_t v_, const float w_){\n\n        ToAdd ta;\n        ta.u=u_;\n        ta.v=v_;\n        ta.w=w_;\n        buffer.push_back(ta);\n        //std::cout<<\"buffer size\"<<buffer.size()<<\"\\n\";\n        if(buffer.size()>=bufferSize){\n\n            std::unique_lock<std::mutex> lock(graphMutex);\n            //std::cout<<\"clear buffer\\n\";\n            for(const auto & ta  : buffer){\n                const auto fe = liftedGraph.findEdge(ta.u,ta.v);\n                // not yet  in lifted graph\n                // therefore cannot be processed\n                if(!fe.first){\n                    //std::cout<<\"a\\n\";\n                    const auto e = model.setCost(ta.u,ta.v,ta.w,false);\n                    processed.insert(e);\n                }\n                // edge is in lifted graph\n                else{\n                    //std::cout<<\"b\\n\";\n                    auto fm = processed.find(fe.second);\n                    // not yet processed\n                    if(fm == processed.end()){\n                        std::cout<<\"b1\\n\";\n                        const auto e = model.setCost(ta.u,ta.v,ta.w,false);\n                        processed.insert(e);\n                    }\n                    else{\n                        std::cout<<\"b2\\n\";\n                    }\n                }\n            }\n            buffer.resize(0);\n        }\n    };\n\n\n    std::cout<<\"lifted graph edge num \"<<liftedGraph.numberOfEdges()<<\"\\n\";\n    agraph::parallel_foreach(\n        nThreads,\n        shape[1],\n        [&](const int threadId, const int y){\n            auto & buffer = buffers[threadId];\n            for(int x=0; x<shape[0]; ++x){\n                const auto p = Coord(x,y);\n                const auto u = node(p);\n                GRAPH_CHECK_OP(u,<,originalGraph.numberOfVertices(),\"\");\n                GRAPH_CHECK_OP(u,<,liftedGraph.numberOfVertices(),\"\");\n                const auto start = clipToImg(p-maxRadius);\n                const auto end = clipToImg(p+maxRadius+1);\n                auto q = Coord();\n                for(q[0]=start[0]; q[0]<end[0]; ++q[0])\n                for(q[1]=start[1]; q[1]<end[1]; ++q[1]){\n\n                    GRAPH_CHECK_OP(q[0],>=,0,\"\");\n                    GRAPH_CHECK_OP(q[1],>=,0,\"\");\n                    GRAPH_CHECK_OP(q[0],<,shape[0],\"\");\n                    GRAPH_CHECK_OP(q[1],<,shape[1],\"\");\n                    const auto v = node(q);\n\n                    size_t e;\n                    if( norm(p-q) < float(minRadius))\n                        continue;\n                    if(p==q || v>u){\n                        continue;\n                    }\n\n                    \n                    GRAPH_CHECK_OP(v,<,originalGraph.numberOfVertices(),\"\");\n                    GRAPH_CHECK_OP(v,<,liftedGraph.numberOfVertices(),\"\");\n                    const auto qf = FCoord(q);\n                    const auto pq = q-p;\n                    const auto dist = vigra::norm(pq);\n                    const auto step =  pq*(1.0f / (dist * 1.3f + 0.5f));\n                    auto pOnLine = FCoord(p);\n                    auto noMax = true;\n                    auto maxVal = -1.0f*std::numeric_limits<float>::infinity();\n                    while(Coord(pOnLine)!=q){\n                        //std::cout<<\"pol \"<<pOnLine<<\"\\n\";\n                        auto iCord = Coord(pOnLine);\n                        if(iCord != p){\n                            noMax = false;\n                            maxVal = std::max(edgePmap[iCord], maxVal);\n                        }\n                        pOnLine += step;\n                    }\n                    const double p1 = std::max(std::min(maxVal,0.999f),0.001f);\n                    const double p0 = 1.0 - p1;\n                    auto w = std::log(p0/p1) + beta;\n\n                    addToBuffer(buffer, u,v,w);\n                }\n            }\n        }\n    );\n\n    // clear whats left in buffers\n    for(const auto & buffer : buffers){\n        for(const auto & ta : buffer){\n            const auto fe = liftedGraph.findEdge(ta.u,ta.v);\n            // not yet  in lifted graph\n            // therefore cannot be processed\n            if(!fe.first){\n                const auto e = model.setCost(ta.u,ta.v,ta.w,false);\n                processed.insert(e);\n            }\n            // edge is in lifted graph\n            else{\n                auto fm = processed.find(fe.second);\n                // not yet processed\n                if(fm == processed.end()){\n                    const auto e = model.setCost(ta.u,ta.v,ta.w,false);\n                    processed.insert(e);\n                }\n            }\n        }\n    }\n    std::cout<<\"lifted graph edge num \"<<liftedGraph.numberOfEdges()<<\"\\n\";\n}\n\n\n\n\ntemplate<class MODEL>\nvoid addLongRangeNH(\n    MODEL & model,\n    const int radius = 7                                                \n){  \n    for(auto u=0; u<model.originalGraph().numberOfVertices(); ++u){\n        const auto otherNodes = agraph::verticesInGraphNeigborhood(model.originalGraph(), u, radius);\n        for(const auto v : otherNodes){\n            if(u!=v){\n                model.setCost(u,v,0.0);\n            }\n        }\n    }\n}\n\n\n\ntemplate<class LiftedMcModel>\ndouble evalCut(\n    LiftedMcModel & liftedMcModel,\n    vigra::NumpyArray<1, uint8_t> cut\n){\n    auto s = 0.0;\n    for(auto e=0; e<liftedMcModel.liftedGraph().numberOfEdges(); ++e){\n        if(cut[e]){\n            s += liftedMcModel.edgeCosts()[e];\n        }\n    }\n    return s;\n}\n\n\n\n\ntemplate<class LiftedMcModel>\nvoid setCosts(\n    LiftedMcModel & liftedMcModel,\n    vigra::NumpyArray<1, vigra::TinyVector<uint64_t, 2> > uv,\n    vigra::NumpyArray<1, float> costs,\n    const bool overwrite \n){\n    GRAPH_CHECK_OP(uv.size(), == , costs.size(), \"shape mismatch: uv and costs have different size\");\n\n    const auto u = uv.bindElementChannel(0);\n    const auto v = uv.bindElementChannel(1);\n    const auto c = vigra::MultiArrayView<1, float>(costs);\n    liftedMcModel.setCosts(u.begin(), u.end(), v.begin(), c.begin(), overwrite);\n}\n\n\ntemplate<class LiftedMcModel>\nvigra::NumpyAnyArray edgeLabelsToNodeLabels(\n    const LiftedMcModel & model,\n    vigra::NumpyArray<1, uint8_t> edgeLabels,\n    vigra::NumpyArray<1, uint64_t> nodeLabels\n){\n    vigra::TinyVector<int,1> shape(model.originalGraph().numberOfVertices());\n    nodeLabels.reshapeIfEmpty(shape);\n    model.getNodeLabels(edgeLabels, nodeLabels);\n    return nodeLabels;\n}\n\n\ntemplate<class LiftedMcModel>\nvigra::NumpyAnyArray nodeLabelsToEdgeLabels(\n    const LiftedMcModel & model,\n    vigra::NumpyArray<1, uint64_t> nodeLabels,\n    vigra::NumpyArray<1, uint8_t> edgeLabels\n){\n    vigra::TinyVector<int,1> shape(model.liftedGraph().numberOfEdges());\n    edgeLabels.reshapeIfEmpty(shape);\n    model.getEdgeLabels(nodeLabels, edgeLabels);\n    return edgeLabels;\n}\n\n\ntemplate<class LiftedMcModel>\nvoid fuseGtObjective(\n    LiftedMcModel & model,\n    vigra::NumpyArray<2, uint64_t> nodeLabels,\n    const size_t rr,\n    const double beta,\n    const bool verbose\n){\n    if(verbose)\n        std::cout<<\"nodeLabel.shape \"<<nodeLabels.shape()<<\"\\n\";\n\n   \n    const auto & originalGraph = model.originalGraph();\n    const auto & liftedGraph = model.liftedGraph();\n    auto nV = originalGraph.numberOfVertices();\n    auto nGt = nodeLabels.shape(1);\n\n    std::vector<std::set<size_t> > extendedNh(nV);\n    std::vector<std::set<size_t> > extendedNh2(nV);\n\n\n    for(auto n=0; n<originalGraph.numberOfVertices(); ++n){\n        for(auto iter = originalGraph.verticesFromVertexBegin(n); iter!=originalGraph.verticesFromVertexEnd(n); ++iter){\n            extendedNh[n].insert(*iter);\n            extendedNh2[n].insert(*iter);\n        }\n    }\n\n    for(auto r=0;r<2;++r){\n\n        for(auto n=0; n<originalGraph.numberOfVertices(); ++n){\n            auto & thisNodeNhSet = extendedNh2[n];\n            for(auto iter = originalGraph.verticesFromVertexBegin(n); iter!=originalGraph.verticesFromVertexEnd(n); ++iter){\n                auto otherNode = *iter;\n                const auto & otherNodeNhSet = extendedNh[otherNode];\n                thisNodeNhSet.insert(otherNodeNhSet.begin(), otherNodeNhSet.end());\n                thisNodeNhSet.erase(n);\n            }\n        }\n        extendedNh = extendedNh2;\n    }\n\n    for(auto u=0; u<originalGraph.numberOfVertices(); ++u){\n        const auto & enh = extendedNh[u];\n        //std::cout<<\"node \"<<u<<\" |enh| = \"<<enh.size()<<\"\\n\";\n\n        const auto uGt = nodeLabels.bindInner(u); \n        for(const auto v : enh){\n            const auto vGt = nodeLabels.bindInner(v); \n            auto p1 = 0.0;\n            for(size_t gtc=0; gtc<nGt; ++gtc){\n                p1 += uGt[gtc] != vGt[gtc] ?  1 : 0;\n            }\n            p1 /= nGt;\n            //if (p1>0.1)\n            //    std::cout<<\"   p1 \"<<p1<<\"\\n\";\n\n            p1 = std::max(std::min(0.999, p1),0.001);\n            auto p0 = 1.0 - p1;\n            auto w = std::log(p0/p1) + std::log((1.0-beta)/beta);\n            model.setCost(u,v,w);\n        }\n    }\n}\n\n\n\ntemplate<class LiftedMcModel>\nvoid fuseGtObjectiveGrid(\n    LiftedMcModel & model,\n    vigra::NumpyArray<3, uint64_t> nodeLabels,\n    vigra::NumpyArray<1, double>    pExpert,\n    vigra::NumpyArray<2, float>     cutRegularizer,\n    const size_t rr,\n    const double beta,\n    //const double cLocal,\n    const bool verbose\n){\n    if(verbose)\n        std::cout<<\"nodeLabel.shape \"<<nodeLabels.shape()<<\"\\n\";\n\n   \n    const auto & originalGraph = model.originalGraph();\n    const auto & liftedGraph = model.liftedGraph();\n    auto nV = originalGraph.numberOfVertices();\n    typedef vigra::TinyVector<int,2> Coord;\n    Coord shape(originalGraph.shape(0), originalGraph.shape(1));\n\n    auto nGt = nodeLabels.shape(2);\n\n    std::vector<std::set<size_t> > extendedNh(nV);\n    std::vector<std::set<size_t> > extendedNh2(nV);\n\n    auto clipToImg = [&](const Coord & coord){\n        auto c = coord;\n        for(auto i=0; i<2; ++i){\n            c[i] = std::max(0, c[i]);\n            c[i] = std::min(int(shape[i]),c[i]);\n        }\n        return c;\n    };\n    auto node = [&](const Coord & coord){\n        return size_t(coord[0] + coord[1]*shape[0]);\n    };\n\n    Coord p;\n\n    for(p[1]=0; p[1]<shape[1]; ++p[1])\n    for(p[0]=0; p[0]<shape[0]; ++p[0]){\n\n        const auto u = node(p);\n        const auto start = clipToImg(p-int(rr));\n        const auto end = clipToImg(p+int(rr)+1);\n\n        auto lp = nodeLabels.bindInner(p[0]).bindInner(p[1]);\n        auto q = Coord();\n\n        for(q[1]=start[1]; q[1]<end[1]; ++q[1])\n        for(q[0]=start[0]; q[0]<end[0]; ++q[0]){\n            const auto v = node(q);\n            if(p!=q && u < v){\n                auto d = vigra::norm(p-q);\n                if(d<=float(rr)){\n                    if(d<=1.5)\n                        d*=0.5;\n                    auto lq = nodeLabels.bindInner(q[0]).bindInner(q[1]);\n                    auto p0 = 0.0;\n                    auto p1 = 0.0;\n                    for(size_t gtc=0; gtc<nGt; ++gtc){\n                        p0 += (lp[gtc] == lq[gtc]) ?  pExpert(gtc) : 0.0;\n                        p1 += (lp[gtc] != lq[gtc]) ?  pExpert(gtc) : 0.0;\n                    }\n                    auto Z = p0+p1;\n                    p0/=Z;\n                    p1/=Z;\n                    //if (p1>0.1)\n                    //    std::cout<<\"   p1 \"<<p1<<\"\\n\";\n\n                    p1 = std::max(std::min(0.99999, p1),0.00001);\n                    p0 = 1.0 - p1;\n                    auto w = std::log(p0/p1) + std::log((1.0-beta)/beta);\n                    if(d<=1.01){\n                        auto c = (cutRegularizer[p] + cutRegularizer[q])/2.0;\n                        w += c;\n                    }\n                    model.setCost(u,v,w*d);\n                }\n            }\n        }\n    }\n}\n\ntemplate<class LiftedMcModel>\nvoid thinObjectSeededSeg(\n    LiftedMcModel & model,\n    vigra::NumpyArray<2, uint64_t>  linkConstraints,\n    vigra::NumpyArray<2, float>     cutCosts,\n    const double constraintCost,\n    const bool verbose\n){\n\n    auto shape = linkConstraints.shape();\n    auto tshape = cutCosts.shape();\n    GRAPH_CHECK_OP(shape[0],==,model.originalGraph().shape(0),\"\");\n    GRAPH_CHECK_OP(shape[1],==,model.originalGraph().shape(1),\"\");\n\n    GRAPH_CHECK_OP(shape[0]*2-1,==,tshape[0],\"\");\n    GRAPH_CHECK_OP(shape[1]*2-1,==,tshape[1],\"\");\n\n    typedef vigra::TinyVector<int,2> Coord;\n    ///  link constraints\n    std::map<uint64_t, std::vector<size_t> >   constraintSet;\n\n    auto node = [&](const Coord & c){\n        return c[0] + c[1]*shape[0];\n    };\n    std::cout<<\"local terms\\n\";\n    for(auto y=0; y<shape[1]; ++y)\n    for(auto x=0; x<shape[0]; ++x){\n        const Coord c(x,y);\n        auto u = node(c);\n        if(linkConstraints(x,y)!=255){\n            constraintSet[linkConstraints(x,y)].push_back(u);\n        }\n        if(x+1<shape[0]){\n            const Coord c2(x+1,y);\n            const auto v = node(c2);\n            auto val = cutCosts[c+c2];\n            model.setCost(u,v,val);\n        }\n        if(y+1<shape[1]){\n            const Coord c2(x,y+1);\n            const auto v = node(c2);\n            auto val = cutCosts[c+c2];\n            model.setCost(u,v,val);\n        }\n    }\n    std::cout<<\"to vecvec\\n\";\n    std::vector< std::vector<size_t> >   cVecVec;\n    for(auto iter = constraintSet.begin(); iter!=constraintSet.end(); ++iter){\n        cVecVec.push_back(iter->second);\n    }\n    std::cout<<\"must link terms\\n\";\n    // must link constraints\n    for(auto & inodes : cVecVec){\n        GRAPH_CHECK_OP(inodes.size(),>=,1,\"\");\n        std::cout<<\"inodes \"<<inodes.size()<<\"\\n\";\n        if(inodes.size() >1){\n            for(auto i=0; i<inodes.size()-1; ++i)\n            for(auto j=i+1; j<inodes.size(); ++j){\n                model.setCost(inodes[i],inodes[j], constraintCost);\n            }\n        }\n    }\n    std::cout<<\"cannot link terms\\n\";\n    // cannot link constraints\n    for(auto i=0; i<cVecVec.size()-1; ++i){\n        const auto & nodesI = cVecVec[i];\n        for(auto j=i+1; j<cVecVec.size(); ++j){\n            const auto & nodesJ = cVecVec[j];\n\n            for(auto in : nodesI)\n            for(auto jn : nodesJ){\n                model.setCost(in,jn,-1.0*constraintCost);\n            }\n        }\n    }\n\n}\n\n\n\ntemplate<class LiftedMcModel>\nvoid lmSuperpixel(\n    LiftedMcModel & model,\n    vigra::NumpyArray<2, float>     cutCosts,\n    const size_t seedRadius = 10,\n    const size_t stepSize = 2,\n    const double sigma = 3.0,\n    const double seedRepulsion = 1.0\n){\n\n\n    const int shape[2] = {\n        int(model.originalGraph().shape(0)),\n        int(model.originalGraph().shape(1)) \n    };\n    auto tshape = cutCosts.shape();\n\n\n    typedef vigra::TinyVector<int,2> Coord;\n\n    auto node = [&](const Coord & c){\n        return c[0] + c[1]*shape[0];\n    };\n    std::cout<<\"generate seeds\\n\";\n\n\n    std::vector<Coord> seeds;\n\n    for(auto y=seedRadius+1; y<shape[1]-seedRadius-1; y += seedRadius)\n    for(auto x=seedRadius+1; x<shape[0]-seedRadius-1; x += seedRadius){\n        const Coord c(x,y);\n        seeds.push_back(c);\n    }\n\n    std::cout<<\"add repulsion number of seeds \"<<seeds.size()<<\"\\n\";\n    GRAPH_CHECK_OP(seeds.size(),>=,2,\"seedRadius is to large\");\n    // seed repulsion\n    auto c=0;\n    auto r=0;\n    for(auto si=0; si<seeds.size()-1; ++si)\n    for(auto sj=si+1; sj<seeds.size(); ++sj){\n        const auto & ci = seeds[si];\n        const auto & cj = seeds[sj];\n        if(vigra::norm(ci-cj)<5*seedRadius){\n            model.setCost(node(ci),node(cj),-1.0*seedRepulsion*seedRadius*100.0);\n            ++c;\n        }\n        else{\n            ++r;\n        }\n    }\n    std::cout<<\"repulsive edges \"<<c<<\" rejected \"<<r<<\"\\n\";\n\n    std::cout<<\"add seed attractiveness \\n\";\n\n    auto nd = [&](const double dist){\n        return (1.0/(sigma*std::sqrt(2.0*3.1415926))) *std::exp(-0.5*std::pow(dist/sigma,2));\n    };\n    for(auto & uCoord  : seeds){\n        Coord vCoord;\n        for(vCoord[0] = uCoord[0]-seedRadius; vCoord[0]<uCoord[0]+seedRadius+1;++vCoord[0])\n        for(vCoord[1] = uCoord[1]-seedRadius; vCoord[1]<uCoord[1]+seedRadius+1;++vCoord[1]){\n            auto  d = vigra::norm(uCoord-vCoord);\n            auto  w = nd(d);\n            model.setCost(node(uCoord), node(vCoord), w*20.0);\n        }\n    }\n\n    std::cout<<\"add grid graph cost attractiveness \\n\";\n    std::cout<<\"local terms\\n\";\n    for(auto y=0; y<shape[1]; ++y)\n    for(auto x=0; x<shape[0]; ++x){\n        const Coord c(x,y);\n        auto u = node(c);\n        if(x+1<shape[0]){\n            const Coord c2(x+1,y);\n            const auto v = node(c2);\n            auto val = cutCosts[c+c2];\n            model.setCost(u,v,val);\n        }\n        if(y+1<shape[1]){\n            const Coord c2(x,y+1);\n            const auto v = node(c2);\n            auto val = cutCosts[c+c2];\n            model.setCost(u,v,val);\n        }\n    }\n    std::cout<<\"build model done\\n\";\n}\n\n\n\ntemplate<class LiftedMcModel>\nvoid andresImageSegModel(\n    LiftedMcModel & model,\n    vigra::NumpyArray<2, float> pmapImage,\n    const float bias = 0.5\n){\n    const auto & shape = pmapImage.shape();\n    // convert to andres image\n    Image image(shape.begin(),shape.begin());\n    for(auto y=0; y<shape[1]; ++y)\n    for(auto x=0; x<shape[0]; ++x){\n        image(x,y) = pmapImage(x,y);\n    }\n\n    const auto & graph = model.originalGraph();\n\n    // boundary-probability-to-multicut-problem-image.cxx\n    std::vector<float> edgeCutProbabilities;\n    PixelCutProbabilityFromEdgesWTA<float, size_t> pixelCutProbabilityWTA(image);\n    constructGraphAndEdgeProbabilities(pixelCutProbabilityWTA, graph, edgeCutProbabilities, bias);\n\n}\n\n\ntemplate<class LiftedMcModel>\nvoid loadBsdModel(LiftedMcModel & model, const std::string & filename){\n    auto fileHandle = agraph::hdf5::openFile(filename);\n    agraph::hdf5::load(fileHandle,\"graph\",model._originalGraph());\n    agraph::hdf5::load(fileHandle,\"graph-lifted\",model._liftedGraph());\n    std::vector<size_t> shape;\n    auto & ec = model._edgeCosts();\n    //ec.resize(model.liftedGraph().numberOfEdges());\n    std::vector<double > ecd;\n    agraph::hdf5::load(fileHandle, \"edge-cut-probabilities\", shape, ecd);\n\n    transform(\n       ecd.begin(),\n       ecd.end(),\n       ecd.begin(),\n       andres::NegativeLogProbabilityRatio<double,double>()\n    );\n\n    ec.resize(ecd.size());\n    std::copy(ecd.begin(), ecd.end(),ec.begin());\n    agraph::hdf5::closeFile(fileHandle);\n\n\n    transform(\n       ec.begin(),\n       ec.end(),\n       ec.begin(),\n       andres::NegativeLogProbabilityRatio<double,double>()\n    );\n\n}\n\ntemplate<class OG, class F>\nvoid exportLiftedMcModelT(const std::string & clsName, F && f){\n    typedef OG originalGraph;\n    typedef agraph::multicut_lifted::LiftedMcModel<originalGraph, float> LiftedMcModel;\n\n\n    auto cls = bp::class_<LiftedMcModel>\n    (\n        clsName.c_str(), \n        bp::init<\n            const originalGraph&\n        >(\n            bp::arg(\"originalGraph\")\n        )[bp::with_custodian_and_ward<1 /*custodian == self*/, 2 /*ward == const originalGraph & */>()]\n    )\n        .def(\"originalGraph\",&LiftedMcModel::originalGraph , bp::return_internal_reference<>())\n        .def(\"liftedGraph\",&LiftedMcModel::liftedGraph , bp::return_internal_reference<>())\n        .def(\"_setCosts\",vigra::registerConverters(&setCosts<LiftedMcModel>))\n        .def(\"_setCost\",&LiftedMcModel::setCost)\n        .def(\"evalCut\",vigra::registerConverters(&evalCut<LiftedMcModel>))\n        .def(\"edgeLabelsToNodeLabels\",vigra::registerConverters(&edgeLabelsToNodeLabels<LiftedMcModel>),\n            (\n                bp::arg(\"edgeLabels\"),\n                bp::arg(\"out\") = bp::object()\n            )\n        )\n        .def(\"loadBsdModel\", &loadBsdModel<LiftedMcModel>)\n        .def(\"nodeLabelsToEdgeLabels\",vigra::registerConverters(&nodeLabelsToEdgeLabels<LiftedMcModel>),\n            (\n                bp::arg(\"nodeLabels\"),\n                bp::arg(\"out\") = bp::object()\n            )\n        );\n\n    f(cls);\n\n\n    bp::def(\"fuseGtObjective\",vigra::registerConverters(&fuseGtObjective<LiftedMcModel>),\n        (\n            bp::arg(\"model\"),\n            bp::arg(\"nodeLabels\"),\n            bp::arg(\"rr\") = 2,\n            bp::arg(\"beta\") = 0.5,\n            bp::arg(\"verbose\") = true\n        )\n    );\n}\n\n\ntemplate<class MODEL>\nvigra::NumpyAnyArray flattenLabels(\n    const MODEL & model,\n    vigra::NumpyArray<2, uint64_t> labels2d,\n    vigra::NumpyArray<1, uint64_t> out\n){\n    vigra::TinyVector<int, 1> shape(labels2d.size());\n    out.reshapeIfEmpty(shape);\n    auto c=0;\n    for(auto y=0; y<labels2d.shape(1); ++y)\n    for(auto x=0; x<labels2d.shape(0); ++x){\n        out[c] = labels2d(x,y);\n        ++c;\n    }\n    return out;\n}\n\n\nvoid exportLiftedMcModel(){\n    typedef agraph::GridGraph<2> GridGraph2D;\n    typedef agraph::GridGraph<3> GridGraph3D;\n    typedef agraph::Graph<> Graph;\n    typedef agraph::multicut_lifted::LiftedMcModel<GridGraph2D, float> LiftedMcModelGridGraph2D;\n    typedef agraph::multicut_lifted::LiftedMcModel<Graph, float> LiftedMcModelGraph;\n    {\n        typedef agraph::multicut_lifted::LiftedMcModel<GridGraph2D, float> LiftedMcModelGridGraph2D; \n        exportLiftedMcModelT<GridGraph2D>(\"LiftedMcModelGridGraph2D\",\n            [&](\n                bp::class_< LiftedMcModelGridGraph2D > & cls\n            ){\n                cls\n                    .def(\"flattenLabels\",\n                        vigra::registerConverters(&flattenLabels< LiftedMcModelGridGraph2D >),\n                        (\n                            bp::arg(\"labels\"),\n                            bp::arg(\"out\") =  bp::object()\n                        )\n                    )\n                ;\n            }\n        );\n    }\n    exportLiftedMcModelT<GridGraph3D>(\"LiftedMcModelGridGraph3D\",\n        [&](\n            bp::class_<agraph::multicut_lifted::LiftedMcModel<GridGraph3D, float> > & cls\n        ){\n            \n        }\n    );\n    exportLiftedMcModelT<Graph>(\"LiftedMcModelGraph\",\n        [&](\n            bp::class_<agraph::multicut_lifted::LiftedMcModel<Graph, float> > & cls\n        ){\n            \n        }\n    );\n\n\n    bp::def(\"addLongRangeEdges\",vigra::registerConverters(&addLongRangeEdges<LiftedMcModelGridGraph2D>))\n    ;\n\n    bp::def(\"addLongRangeNH\",vigra::registerConverters(&addLongRangeNH<LiftedMcModelGridGraph2D>))\n    ;\n    bp::def(\"addLongRangeNH\",vigra::registerConverters(&addLongRangeNH<LiftedMcModelGraph>))\n    ;\n\n    bp::def(\"fuseGtObjectiveGrid\",vigra::registerConverters(&fuseGtObjectiveGrid<LiftedMcModelGridGraph2D>),\n        (\n            bp::arg(\"model\"),\n            bp::arg(\"nodeLabels\"),\n            bp::arg(\"pExpert\"),\n            bp::arg(\"cutRegularizer\"),\n            bp::arg(\"rr\") = 2,\n            bp::arg(\"beta\") = 0.5,\n            //bp::arg(\"cLocal\") = 100,\n            bp::arg(\"verbose\") = true\n        )\n    );\n\n    bp::def(\"thinObjectSeededSeg\",vigra::registerConverters(&thinObjectSeededSeg<LiftedMcModelGridGraph2D>),\n        (\n            bp::arg(\"model\"),\n            bp::arg(\"linkConstraints\"),\n            bp::arg(\"cutCosts\"),\n            bp::arg(\"c\") = 1000.0,\n            bp::arg(\"verbose\") = true\n        )\n    );\n\n    \n\n    bp::def(\"lmSuperpixel\",vigra::registerConverters(&lmSuperpixel<LiftedMcModelGridGraph2D>),\n        (\n            bp::arg(\"model\"),\n            bp::arg(\"cutCosts\"),\n            bp::arg(\"seedRadius\") = 10,\n            bp::arg(\"stepSize\") = 2,\n            bp::arg(\"sigma\") = 3.0,\n            bp::arg(\"seedRepulsion\") =1.0\n        )\n    );\n\n\n    bp::def(\"andresImageSegModel\",vigra::registerConverters(&andresImageSegModel<LiftedMcModelGridGraph2D>),\n        (\n            bp::arg(\"model\"),\n            bp::arg(\"pmap\"),\n            bp::arg(\"bias\") = 0.5\n        )\n    );\n}\n", "meta": {"hexsha": "343654efcab234cbb6e21b80ffc6f2abf7b24d6a", "size": 26507, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "dependencies/graph-1.6/src/andres/graph/python/lifted_mc_model.cxx", "max_stars_repo_name": "ilastik/nature_methods_multicut_pipeline", "max_stars_repo_head_hexsha": "1dc596505ab8c995b50561eeb969c59673b7dcab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-02-07T12:41:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-19T02:52:32.000Z", "max_issues_repo_path": "dependencies/graph-1.6/src/andres/graph/python/lifted_mc_model.cxx", "max_issues_repo_name": "ilastik/nature_methods_multicut_pipeline", "max_issues_repo_head_hexsha": "1dc596505ab8c995b50561eeb969c59673b7dcab", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-02-07T01:51:34.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-31T15:00:33.000Z", "max_forks_repo_path": "dependencies/graph-1.6/src/andres/graph/python/lifted_mc_model.cxx", "max_forks_repo_name": "ilastik/nature_methods_multicut_pipeline", "max_forks_repo_head_hexsha": "1dc596505ab8c995b50561eeb969c59673b7dcab", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-11-16T04:04:55.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-11T11:33:51.000Z", "avg_line_length": 31.0023391813, "max_line_length": 124, "alphanum_fraction": 0.5331421889, "num_tokens": 7159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23898001888212939}}
{"text": "#include <cstdio>\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <cfloat>\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n#include <boost/filesystem.hpp>\n#include <json/json.h>\n#include <H5Cpp.h>\n\n// OpenMP\n#include <omp.h>\n\n#include \"box_triangle/aabb_triangle_overlap.h\"\n#include \"box_ray/vector3.h\"\n#include \"box_ray/ray.h\"\n#include \"box_ray/box.h\"\n#include \"triangle_point/vec.h\"\n#include \"triangle_point/makelevelset3.h\"\n#include \"triangle_ray/raytri.h\"\n\n/** \\brief Simple struct representing arbitrary boxes. */\nstruct Box {\n  /** \\brief Minimum coordinates. */\n  Eigen::Vector3f min;\n  /** \\brief Maximum coordinates. */\n  Eigen::Vector3f max;\n\n  /** \\brief Constructor.\n   */\n  Box() {\n    this->min = Eigen::Vector3f::Zero();\n    this->max = Eigen::Vector3f::Zero();\n  }\n\n  /** \\brief Constructor; construct a box from minimum and maximum coordinates.\n   * \\param[in] min minimum coordinates\n   * \\param[in] max maximum coordinates\n   */\n  Box(const Eigen::Vector3f &min, const Eigen::Vector3f &max) {\n    this->min = min;\n    this->max = max;\n  }\n\n  /** \\brief Check if a point is inside the box.\n   * \\param[in] point point to check\n   * \\return contained\n   */\n  bool contains(const Eigen::Vector3f &point) {\n    bool contains = true;\n\n    for (int d = 0; d < 3; d++) {\n      if (point(d) < this->min(d) || point(d) > this->max(d)) {\n        contains = false;\n      }\n    }\n\n    return contains;\n  }\n\n  /** \\brief Scale the box.\n   * \\param[in] scale scale per axis\n   */\n  void scale(const Eigen::Vector3f &scale) {\n    for (int d = 0; d < 3; d++) {\n      min(d) *= scale(d);\n      max(d) *= scale(d);\n    }\n  }\n\n  /** \\brief Scale the box.\n   * \\param[in] scale scale over all axes\n   */\n  void scale(float scale) {\n    this->scale(Eigen::Vector3f(scale, scale, scale));\n  }\n\n  /** \\brief Scale the box.\n   * \\param[in] translation translation per axis\n   */\n  void translate(const Eigen::Vector3f &translation) {\n    for (int d = 0; d < 3; d++) {\n      min(d) += translation(d);\n      max(d) += translation(d);\n    }\n  }\n};\n\n/** \\brief Test box ray intersection.\n * \\param[in] box box\n * \\param[in] ray ray to intersect with\n * \\return intersects\n */\nbool box_ray_intersection(const Box &box, const Eigen::Vector3f &ray) {\n  for (int d = 0; d < 3; d++) {\n    assert(box.min(d) < box.max(d));\n  }\n\n  // convert to used data structure\n  bri::Vector3 _o(0, 0, 0);\n  bri::Vector3 _d(ray(0), ray(1), ray(2));\n  bri::Ray _ray(_o, _d);\n  bri::Vector3 _min(box.min(0), box.min(1), box.min(2));\n  bri::Vector3 _max(box.max(0), box.max(1), box.max(2));\n  bri::Box _box(_min, _max);\n\n  // interval for valid its is [0,1] as the ray will\n  // be the full-length vector to an observed point\n  return _box.intersect(_ray, 0, 0.99);\n}\n\n/** \\brief Test box ray intersection.\n * \\param[in] box box\n * \\param[in] origin origin point\n * \\param[in] dest destination point\n * \\return intersects\n */\nbool box_ray_intersection(const Box &box, const Eigen::Vector3f &origin, const Eigen::Vector3f &dest) {\n  for (int d = 0; d < 3; d++) {\n    assert(box.min(d) < box.max(d));\n  }\n\n  // convert to used data structure\n  bri::Vector3 _o(origin(0), origin(1), origin(2));\n  bri::Vector3 _d(dest(0), dest(1), dest(2));\n  bri::Ray _ray(_o, _d);\n  bri::Vector3 _min(box.min(0), box.min(1), box.min(2));\n  bri::Vector3 _max(box.max(0), box.max(1), box.max(2));\n  bri::Box _box(_min, _max);\n\n  // interval for valid its is [0,1] as the ray will\n  // be the full-length vector to an observed point\n  return _box.intersect(_ray, 0, 0.99);\n}\n\n/** \\brief Compute triangle box intersection.\n * \\param[in] voxel voxel to test intersection for\n * \\param[in] v1 first vertex\n * \\param[in] v2 second vertex\n * \\param[in] v3 third vertex\n * \\return intersects\n */\nbool triangle_box_intersection(const Box &voxel, const Eigen::Vector3f &v1, const Eigen::Vector3f &v2, const Eigen::Vector3f &v3) {\n  float half_size[3] = {\n    (voxel.max(0) - voxel.min(0))/2.,\n    (voxel.max(1) - voxel.min(1))/2.,\n    (voxel.max(2) - voxel.min(2))/2.\n  };\n\n  float center[3] = {\n    voxel.max(0) - half_size[0],\n    voxel.max(1) - half_size[1],\n    voxel.max(2) - half_size[2]\n  };\n\n  float vertices[3][3] = {{v1(0), v1(1), v1(2)}, {v2(0), v2(1), v2(2)}, {v3(0), v3(1), v3(2)}};\n  return triBoxOverlap(center, half_size, vertices);\n}\n\n/** \\brief Compute triangle point distance and corresponding closest point.\n * \\param[in] point point\n * \\param[in] v1 first vertex\n * \\param[in] v2 second vertex\n * \\param[in] v3 third vertex\n * \\param[out] ray corresponding closest point\n * \\return distance\n */\nfloat triangle_point_distance(const Eigen::Vector3f &point, const Eigen::Vector3f &v1, const Eigen::Vector3f &v2, const Eigen::Vector3f &v3,\n    Eigen::Vector3f &closest_point) {\n\n  Vec3f x0(point.data());\n  Vec3f x1(v1.data());\n  Vec3f x2(v2.data());\n  Vec3f x3(v3.data());\n\n  Vec3f r(0);\n  float distance = point_triangle_distance_field(x0, x1, x2, x3, r);\n\n  for (int d = 0; d < 3; d++) {\n    closest_point(d) = r[d];\n  }\n\n  return distance;\n}\n\n/** \\brief Test triangle ray intersection.\n * \\param[in] origin origin of ray\n * \\param[in] dest destination of ray\n * \\param[in] v1 first vertex\n * \\param[in] v2 second vertex\n * \\param[in] v3 third vertex\n * \\return intersects\n */\nbool triangle_ray_intersection(const Eigen::Vector3f &origin, const Eigen::Vector3f &dest,\n    const Eigen::Vector3f &v1, const Eigen::Vector3f &v2, const Eigen::Vector3f &v3, float &t) {\n\n  double _origin[3] = {origin(0), origin(1), origin(2)};\n  double _dir[3] = {dest(0) - origin(0), dest(1) - origin(1), dest(2) - origin(2)};\n  double _v1[3] = {v1(0), v1(1), v1(2)};\n  double _v2[3] = {v2(0), v2(1), v2(2)};\n  double _v3[3] = {v3(0), v3(1), v3(2)};\n\n  // t is the distance, u and v are barycentric coordinates\n  // http://fileadmin.cs.lth.se/cs/personal/tomas_akenine-moller/code/raytri_tam.pdf\n  double _t, u, v;\n  int success = intersect_triangle(_origin, _dir, _v1, _v2, _v3, &_t, &u, &v);\n  t = _t;\n\n  if (success) {\n    return true;\n  }\n\n  return false;\n}\n\n/** \\brief Simple struct encapsulating a 3D bounding box. */\nstruct BoundingBox {\n  /** \\brief Size of the bounding box. */\n  Eigen::Vector3f size;\n  /** \\brief Translation (i.e. center) of bounding box. */\n  Eigen::Vector3f translation;\n  /** \\brief Rotation of bounding box (in radians per axis). */\n  Eigen::Vector3f rotation;\n  /** \\brief Meta information for writing. */\n  std::string meta;\n\n  /** \\brief Constructor.\n   */\n  BoundingBox() {\n    this->size = Eigen::Vector3f::Zero();\n    this->translation = Eigen::Vector3f::Zero();\n    this->rotation = Eigen::Vector3f::Zero();\n    this->meta = \"\";\n  }\n\n  /** \\brief Assignment operator.\n   * \\param[in] bounding_box bounding box to assign\n   * \\return this\n   */\n  BoundingBox& operator=(const BoundingBox &bounding_box) {\n    this->size = bounding_box.size;\n    this->translation = bounding_box.translation;\n    this->rotation = bounding_box.rotation;\n    this->meta = bounding_box.meta;\n    return *this;\n  }\n\n  /** \\brief Convert to regular box.\n   * \\param[out] box box to convert to\n   */\n  void to_box(Box &box) const {\n    for (int d = 0 ; d < 3; d++) {\n      box.min(d) = this->translation(d) - this->size(d)/2;\n      box.max(d) = this->translation(d) + this->size(d)/2;\n    }\n  }\n\n  /** \\brief Given the angle in radians, construct a rotation matrix around the y-axis.\n   * \\param[in] radians angle in radians\n   * \\param[out] rotation rotation matrix\n   */\n  static void rotation_matrix_y(const float radians, Eigen::Matrix3f &rotation) {\n    rotation = Eigen::Matrix3f::Zero();\n\n    rotation(0, 0) = std::cos(radians); rotation(0, 2) = std::sin(radians);\n    rotation(1, 1) = 1;\n    rotation(2, 0) = -std::sin(radians); rotation(2, 2) = std::cos(radians);\n  }\n\n  /** \\brief Check if a point lies inside the bounding box.\n   * \\param[in] point point to check\n   * \\return contained in bounding box\n   */\n  bool contains(const Eigen::Vector3f &point) const {\n    Eigen::Vector3f transformed = point - this->translation;\n    Eigen::Matrix3f rotation;\n    BoundingBox::rotation_matrix_y(this->rotation(1), rotation);\n    transformed = rotation*transformed;\n\n    bool contained = true;\n    for (int d = 0; d < 3; d++) {\n      if (transformed(d) > this->size(d)/2 || transformed(d) < -this->size(d)/2) {\n        contained = false;\n      }\n    }\n\n    return contained;\n  }\n\n  /** \\brief Get largest scale of bounding box.\n   * \\return scale\n   */\n  float scale() const {\n    float scale = 0;\n\n    for (int d = 0; d < 3; d++) {\n      if (this->size(d) > scale) {\n        scale = this->size(d);\n      }\n    }\n\n    assert(scale > 0);\n    return scale;\n  }\n};\n\n/** \\brief Just encapsulating vertices and faces. */\nclass Mesh {\npublic:\n  /** \\brief Empty constructor. */\n  Mesh() {\n\n  }\n\n  /** \\brief Add a vertex.\n   * \\param[in] vertex vertex to add\n   */\n  void add_vertex(Eigen::Vector3f& vertex) {\n    this->vertices.push_back(vertex);\n  }\n\n  /** \\brief Get the number of vertices.\n   * \\return number of vertices\n   */\n  int num_vertices() {\n    return static_cast<int>(this->vertices.size());\n  }\n\n  /** \\brief Add a face.\n   * \\param[in] face face to add\n   */\n  void add_face(Eigen::Vector3i& face) {\n    this->faces.push_back(face);\n  }\n\n  /** \\brief Get the number of faces.\n   * \\return number of faces\n   */\n  int num_faces() {\n    return static_cast<int>(this->faces.size());\n  }\n\n  /** \\brief Translate the mesh.\n   * \\param[in] translation translation vector\n   */\n  void translate(const Eigen::Vector3f& translation) {\n    for (int v = 0; v < this->num_vertices(); ++v) {\n      for (int i = 0; i < 3; ++i) {\n        this->vertices[v](i) += translation(i);\n      }\n    }\n  }\n\n  /** \\brief Scale the mesh.\n   * \\param[in] scale scale vector\n   */\n  void scale(const Eigen::Vector3f& scale) {\n    for (int v = 0; v < this->num_vertices(); ++v) {\n      for (int i = 0; i < 3; ++i) {\n        this->vertices[v](i) *= scale(i);\n      }\n    }\n  }\n\n  /** \\brief Voxelize the given mesh into a dense volume.\n   * \\param[in] mesh mesh to voxelize\n   * \\param[in] n batch index in dense\n   * \\param[in] dense dense pre-initialized volume\n   */\n  void voxelize_UNSCALED(int n, Eigen::Tensor<float, 4, Eigen::RowMajor>& sdf) {\n\n    int height = sdf.dimension(1);\n    int width = sdf.dimension(2);\n    int depth = sdf.dimension(3);\n\n    for (int h = 0; h < height; ++h) {\n      for (int w = 0; w < width; ++w) {\n        for (int d = 0; d < depth; ++d) {\n          sdf(n, h, w, d) = FLT_MAX;\n\n          // [Data] 99% percentile dimensions:\n          // [Data]   4.750000 1.870000 1.970000\n          // [Data]   2.540102 1        1.053475\n          // [Data]   56       22       24\n\n          float padding_factor = 1.2;\n          float width_factor = (padding_factor*2.545454545)/2.545454545; // = padding_factor\n          float height_factor = padding_factor/2.545454545;\n          float depth_factor = (padding_factor*1.090909091)/2.545454545;\n\n          // the box corresponding to this voxel\n          Eigen::Vector3f min(width_factor*static_cast<float>(w)/width, height_factor*static_cast<float>(h)/height,\n            depth_factor*static_cast<float>(d)/depth);\n          Eigen::Vector3f max(width_factor*static_cast<float>(w + 1)/width, height_factor*static_cast<float>(h + 1)/height,\n            depth_factor*static_cast<float>(d + 1)/depth);\n\n          Box voxel_box(min, max);\n          voxel_box.translate(Eigen::Vector3f(-width_factor/2, -height_factor/2, -depth_factor/2));\n          Eigen::Vector3f center((voxel_box.max(0) + voxel_box.min(0))/2., (voxel_box.max(1) + voxel_box.min(1))/2., (voxel_box.max(2) + voxel_box.min(2))/2.);\n\n          // count number of intersections.\n          int num_intersect = 0;\n          for (unsigned int f = 0; f < this->faces.size(); ++f) {\n\n            Eigen::Vector3f v1 = this->vertices[this->faces[f](0)];\n            Eigen::Vector3f v2 = this->vertices[this->faces[f](1)];\n            Eigen::Vector3f v3 = this->vertices[this->faces[f](2)];\n\n            Eigen::Vector3f closest_point;\n            triangle_point_distance(center, v1, v2, v3, closest_point);\n            float distance = (center - closest_point).norm();\n\n            if (distance < sdf(n, h, w, d)) {\n              sdf(n, h, w, d) = distance;\n            }\n\n            bool intersect = triangle_ray_intersection(center, Eigen::Vector3f(0, 0, 0), v1, v2, v3, distance);\n\n            if (intersect && distance >= 0) {\n              num_intersect++;\n            }\n          }\n\n          if (num_intersect%2 == 1) {\n            sdf(n, h, w, d) *= -1;\n          }\n        }\n      }\n    }\n  }\n\n  /** \\brief Voxelize the given mesh into a dense volume.\n   * \\param[in] mesh mesh to voxelize\n   * \\param[in] n batch index in dense\n   * \\param[in] dense dense pre-initialized volume\n   */\n  void voxelize_SCALED(int n, Eigen::Tensor<float, 4, Eigen::RowMajor>& sdf) {\n\n    int height = sdf.dimension(1);\n    int width = sdf.dimension(2);\n    int depth = sdf.dimension(3);\n\n    #pragma omp parallel\n    {\n      #pragma omp for\n      for (int i = 0; i < height*width*depth; i++) {\n        int d = i%depth;\n        int w = (i/depth)%width;\n        int h = (i/depth)/width;\n        sdf(n, h, w, d) = FLT_MAX;\n\n        // the box corresponding to this voxel\n        Eigen::Vector3f min(static_cast<float>(w), static_cast<float>(h), static_cast<float>(d));\n        Eigen::Vector3f max(static_cast<float>(w + 1), static_cast<float>(h + 1), static_cast<float>(d + 1));\n\n        Box voxel_box(min, max);\n        //voxel_box.translate(Eigen::Vector3f(-static_cast<float>(width)/2, -static_cast<float>(height)/2, -static_cast<float>(depth)/2));\n        Eigen::Vector3f center((voxel_box.max(0) + voxel_box.min(0))/2., (voxel_box.max(1) + voxel_box.min(1))/2., (voxel_box.max(2) + voxel_box.min(2))/2.);\n\n        // count number of intersections.\n        int num_intersect = 0;\n        for (unsigned int f = 0; f < this->faces.size(); ++f) {\n\n          Eigen::Vector3f v1 = this->vertices[this->faces[f](0)];\n          Eigen::Vector3f v2 = this->vertices[this->faces[f](1)];\n          Eigen::Vector3f v3 = this->vertices[this->faces[f](2)];\n\n          Eigen::Vector3f closest_point;\n          triangle_point_distance(center, v1, v2, v3, closest_point);\n          float distance = (center - closest_point).norm();\n\n          if (distance < sdf(n, h, w, d)) {\n            sdf(n, h, w, d) = distance;\n          }\n\n          bool intersect = triangle_ray_intersection(center, Eigen::Vector3f(0, 0, 0), v1, v2, v3, distance);\n\n          if (intersect && distance >= 0) {\n            num_intersect++;\n          }\n        }\n\n        if (num_intersect%2 == 1) {\n          sdf(n, h, w, d) *= -1;\n        }\n      }\n    }\n  }\n\n  /** \\brief Sample points from the mesh\n   * \\param[in] mesh mesh to sample from\n   * \\param[in] n batch index in points\n   * \\param[in] points pre-initialized tensor holding points\n   */\n  void sample(int n, Eigen::Tensor<float, 3, Eigen::RowMajor>& points) {\n\n    // The number of points to sample.\n    const int N = points.dimension(1);\n\n    // Stores the areas of faces.\n    std::vector<float> areas(this->faces.size());\n    float sum = 0;\n\n    // Build a probability distribution over faces.\n    for (int f = 0; f < this->faces.size(); f++) {\n      Eigen::Vector3f a = this->vertices[this->faces[f][0]];\n      Eigen::Vector3f b = this->vertices[this->faces[f][1]];\n      Eigen::Vector3f c = this->vertices[this->faces[f][2]];\n\n      // Angle between a->b and a->c.\n      Eigen::Vector3f ab = b - a;\n      Eigen::Vector3f ac = c - a;\n      float cos_angle = ab.dot(ac)/(ab.norm()*ac.norm());\n      float angle = std::acos(cos_angle);\n\n      // Compute triangle area.\n      float area = std::max(0., 0.5*ab.norm()*ac.norm()*std::sin(angle));\n      //std::cout << area << \" \" << std::pow(area, 1./4.) << \" \" << angle << \" \" << ab.norm() << \" \" << ac.norm() << \" \" << std::sin(angle) << std::endl;\n\n      // Accumulate.\n      //area = std::sqrt(area);\n      areas[f] = area;\n      sum += area;\n      //areas.push_back(1);\n      //sum += 1;\n    }\n\n    //std::cout << sum << std::endl;\n    assert(sum > 1e-8);\n\n    for (int f = 0; f < this->faces.size(); f++) {\n      //std::cout << areas[f] << \" \";\n      areas[f] /= sum;\n      //std::cout << areas[f] << std::endl;\n    }\n\n    std::vector<float> cum_areas(areas.size());\n    cum_areas[0] = areas[0];\n\n    for (int f = 1; f < this->faces.size(); f++) {\n      cum_areas[f] = areas[f] + cum_areas[f - 1];\n    }\n\n    for (int i = 0; i < N; i++) {\n      float r = static_cast<float>(std::rand())/static_cast<float>(RAND_MAX);\n      int face = 0;\n\n      while (r > cum_areas[face + 1] && face < this->faces.size() - 1) {\n        face++;\n      }\n\n      assert(face >= 0 && face < this->faces.size());\n      //int face = std::rand()%this->faces.size();\n\n      float r1 = 0;\n      float r2 = 0;\n      do {\n        r1 = static_cast<float>(std::rand())/static_cast<float>(RAND_MAX);\n        r2 = static_cast<float>(std::rand())/static_cast<float>(RAND_MAX);\n      }\n      while (r1 + r2 > 1.f);\n\n      int s = std::rand()%3;\n      //std::cout << face << \" \" << areas[face] << std::endl;\n\n      Eigen::Vector3f a = this->vertices[this->faces[face](s)];\n      Eigen::Vector3f b = this->vertices[this->faces[face]((s + 1)%3)];\n      Eigen::Vector3f c = this->vertices[this->faces[face]((s + 2)%3)];\n\n      Eigen::Vector3f ab = b - a;\n      Eigen::Vector3f ac = c - a;\n\n      Eigen::Vector3f point = a + r1*ab + r2*ac;\n      points(n, i, 0) = point(0);\n      points(n, i, 1) = point(1);\n      points(n, i, 2) = point(2);\n    }\n  }\n\n  /** \\brief Write mesh to OFF file.\n   * \\param[in] filepath path to OFF file to write\n   * \\return success\n   */\n  bool to_off(const std::string filepath) {\n    std::ofstream* out = new std::ofstream(filepath, std::ofstream::out);\n    if (!static_cast<bool>(out)) {\n      return false;\n    }\n\n    (*out) << \"OFF\" << std::endl;\n    (*out) << this->vertices.size() << \" \" << this->faces.size() << \" 0\" << std::endl;\n\n    for (unsigned int v = 0; v < this->vertices.size(); v++) {\n      (*out) << this->vertices[v](0) << \" \" << this->vertices[v](1) << \" \" << this->vertices[v](2) << std::endl;\n    }\n\n    for (unsigned int f = 0; f < this->faces.size(); f++) {\n      (*out) << \"3 \" << this->faces[f](0) << \" \" << this->faces[f](1) << \" \" << this->faces[f](2) << std::endl;\n    }\n\n    out->close();\n    delete out;\n\n    return true;\n  }\n\nprivate:\n\n  /** \\brief Vertices as (x,y,z)-vectors. */\n  std::vector<Eigen::Vector3f> vertices;\n\n  /** \\brief Faces as list of vertex indices. */\n  std::vector<Eigen::Vector3i> faces;\n};\n\n/** \\brief Reading an off file and returning the vertices x, y, z coordinates and the\n * face indices.\n * \\param[in] filepath path to the OFF file\n * \\param[out] mesh read mesh with vertices and faces\n * \\return success\n */\nbool read_off(const std::string filepath, Mesh& mesh) {\n\n  std::ifstream* file = new std::ifstream(filepath.c_str());\n  std::string line;\n  std::stringstream ss;\n  int line_nb = 0;\n\n  std::getline(*file, line);\n  ++line_nb;\n\n  if (line != \"off\" && line != \"OFF\") {\n    std::cout << \"[Error] Invalid header: \\\"\" << line << \"\\\", \" << filepath << std::endl;\n    return false;\n  }\n\n  size_t n_edges;\n  std::getline(*file, line);\n  ++line_nb;\n\n  int n_vertices;\n  int n_faces;\n  ss << line;\n  ss >> n_vertices;\n  ss >> n_faces;\n  ss >> n_edges;\n\n  for (size_t v = 0; v < n_vertices; ++v) {\n    std::getline(*file, line);\n    ++line_nb;\n\n    ss.clear();\n    ss.str(\"\");\n\n    Eigen::Vector3f vertex;\n    ss << line;\n    ss >> vertex(0);\n    ss >> vertex(1);\n    ss >> vertex(2);\n\n    mesh.add_vertex(vertex);\n  }\n\n  size_t n;\n  for (size_t f = 0; f < n_faces; ++f) {\n    std::getline(*file, line);\n    ++line_nb;\n\n    ss.clear();\n    ss.str(\"\");\n\n    size_t n;\n    ss << line;\n    ss >> n;\n\n    if(n != 3) {\n      std::cout << \"[Error] Not a triangle (\" << n << \" points) at \" << (line_nb - 1) << std::endl;\n      return false;\n    }\n\n    Eigen::Vector3i face;\n    ss >> face(0);\n    ss >> face(1);\n    ss >> face(2);\n\n    mesh.add_face(face);\n  }\n\n  if (n_vertices != mesh.num_vertices()) {\n    std::cout << \"[Error] Number of vertices in header differs from actual number of vertices.\" << std::endl;\n    return false;\n  }\n\n  if (n_faces != mesh.num_faces()) {\n    std::cout << \"[Error] Number of faces in header differs from actual number of faces.\" << std::endl;\n    return false;\n  }\n\n  file->close();\n  delete file;\n\n  return true;\n}\n\n/** \\brief Write the given set of volumes to h5 file.\n * \\param[in] filepath h5 file to write\n * \\param[in] n number of volumes\n * \\param[in] height height of volumes\n * \\param[in] width width of volumes\n * \\param[in] depth depth of volumes\n * \\param[in] dense volume data\n */\nbool write_hdf5(const std::string filepath, Eigen::Tensor<float, 4, Eigen::RowMajor>& dense) {\n\n  try {\n\n    /*\n     * Turn off the auto-printing when failure occurs so that we can\n     * handle the errors appropriately\n     */\n    H5::Exception::dontPrint();\n\n    /*\n     * Create a new file using H5F_ACC_TRUNC access,\n     * default file creation properties, and default file\n     * access properties.\n     */\n    H5::H5File file(filepath, H5F_ACC_TRUNC);\n\n    /*\n     * Define the size of the array and create the data space for fixed\n     * size dataset.\n     */\n    hsize_t rank = 4;\n    hsize_t dimsf[rank];\n    dimsf[0] = dense.dimension(0);\n    dimsf[1] = dense.dimension(1);\n    dimsf[2] = dense.dimension(2);\n    dimsf[3] = dense.dimension(3);\n    H5::DataSpace dataspace(rank, dimsf);\n\n    /*\n     * Define datatype for the data in the file.\n     * We will store little endian INT numbers.\n     */\n    H5::IntType datatype(H5::PredType::NATIVE_FLOAT);\n    datatype.setOrder(H5T_ORDER_LE);\n\n    /*\n     * Create a new dataset within the file using defined dataspace and\n     * datatype and default dataset creation properties.\n     */\n    H5::DataSet dataset = file.createDataSet(\"tensor\", datatype, dataspace);\n\n    /*\n     * Write the data to the dataset using default memory space, file\n     * space, and transfer properties.\n     */\n    float* data = static_cast<float*>(dense.data());\n    dataset.write(data, H5::PredType::NATIVE_FLOAT);\n  }  // end of try block\n\n  // catch failure caused by the H5File operations\n  catch(H5::FileIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSet operations\n  catch(H5::DataSetIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSpace operations\n  catch(H5::DataSpaceIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSpace operations\n  catch(H5::DataTypeIException error) {\n    error.printError();\n    return false;\n  }\n\n  return true;\n}\n\n/** \\brief Write the given set of volumes to h5 file.\n * \\param[in] filepath h5 file to write\n * \\param[in] n number of volumes\n * \\param[in] height height of volumes\n * \\param[in] width width of volumes\n * \\param[in] depth depth of volumes\n * \\param[in] dense volume data\n */\nbool write_hdf5(const std::string filepath, Eigen::Tensor<float, 3, Eigen::RowMajor>& dense) {\n\n  try {\n\n    /*\n     * Turn off the auto-printing when failure occurs so that we can\n     * handle the errors appropriately\n     */\n    H5::Exception::dontPrint();\n\n    /*\n     * Create a new file using H5F_ACC_TRUNC access,\n     * default file creation properties, and default file\n     * access properties.\n     */\n    H5::H5File file(filepath, H5F_ACC_TRUNC);\n\n    /*\n     * Define the size of the array and create the data space for fixed\n     * size dataset.\n     */\n    hsize_t rank = 3;\n    hsize_t dimsf[rank];\n    dimsf[0] = dense.dimension(0);\n    dimsf[1] = dense.dimension(1);\n    dimsf[2] = dense.dimension(2);\n    H5::DataSpace dataspace(rank, dimsf);\n\n    /*\n     * Define datatype for the data in the file.\n     * We will store little endian INT numbers.\n     */\n    H5::IntType datatype(H5::PredType::NATIVE_FLOAT);\n    datatype.setOrder(H5T_ORDER_LE);\n\n    /*\n     * Create a new dataset within the file using defined dataspace and\n     * datatype and default dataset creation properties.\n     */\n    H5::DataSet dataset = file.createDataSet(\"tensor\", datatype, dataspace);\n\n    /*\n     * Write the data to the dataset using default memory space, file\n     * space, and transfer properties.\n     */\n    float* data = static_cast<float*>(dense.data());\n    dataset.write(data, H5::PredType::NATIVE_FLOAT);\n  }  // end of try block\n\n  // catch failure caused by the H5File operations\n  catch(H5::FileIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSet operations\n  catch(H5::DataSetIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSpace operations\n  catch(H5::DataSpaceIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSpace operations\n  catch(H5::DataTypeIException error) {\n    error.printError();\n    return false;\n  }\n\n  return true;\n}\n\n/** \\brief Write the given set of volumes to h5 file.\n * \\param[in] filepath h5 file to write\n * \\param[in] n number of volumes\n * \\param[in] height height of volumes\n * \\param[in] width width of volumes\n * \\param[in] depth depth of volumes\n * \\param[in] dense volume data\n */\nbool write_hdf5(const std::string filepath, Eigen::Tensor<int, 4, Eigen::RowMajor>& dense) {\n\n  try {\n\n    /*\n     * Turn off the auto-printing when failure occurs so that we can\n     * handle the errors appropriately\n     */\n    H5::Exception::dontPrint();\n\n    /*\n     * Create a new file using H5F_ACC_TRUNC access,\n     * default file creation properties, and default file\n     * access properties.\n     */\n    H5::H5File file(filepath, H5F_ACC_TRUNC);\n\n    /*\n     * Define the size of the array and create the data space for fixed\n     * size dataset.\n     */\n    hsize_t rank = 4;\n    hsize_t dimsf[rank];\n    dimsf[0] = dense.dimension(0);\n    dimsf[1] = dense.dimension(1);\n    dimsf[2] = dense.dimension(2);\n    dimsf[3] = dense.dimension(3);\n    H5::DataSpace dataspace(rank, dimsf);\n\n    /*\n     * Define datatype for the data in the file.\n     * We will store little endian INT numbers.\n     */\n    H5::IntType datatype(H5::PredType::NATIVE_INT);\n    datatype.setOrder(H5T_ORDER_LE);\n\n    /*\n     * Create a new dataset within the file using defined dataspace and\n     * datatype and default dataset creation properties.\n     */\n    H5::DataSet dataset = file.createDataSet(\"tensor\", datatype, dataspace);\n\n    /*\n     * Write the data to the dataset using default memory space, file\n     * space, and transfer properties.\n     */\n    int* data = static_cast<int*>(dense.data());\n    dataset.write(data, H5::PredType::NATIVE_INT);\n  }  // end of try block\n\n  // catch failure caused by the H5File operations\n  catch(H5::FileIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSet operations\n  catch(H5::DataSetIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSpace operations\n  catch(H5::DataSpaceIException error) {\n    error.printError();\n    return false;\n  }\n\n  // catch failure caused by the DataSpace operations\n  catch(H5::DataTypeIException error) {\n    error.printError();\n    return false;\n  }\n\n  return true;\n}\n\n/** \\brief Read all files in a directory matching the given extension.\n * \\param[in] directory path to directory\n * \\param[out] files read file paths\n * \\param[in] extension extension to filter for\n */\nvoid read_directory(const std::string directory, std::map<int, std::string>& files, const std::string extension = \".off\") {\n\n  boost::filesystem::path dir(directory);\n  boost::filesystem::directory_iterator end;\n\n  files.clear();\n  for (boost::filesystem::directory_iterator it(dir); it != end; ++it) {\n    if (it->path().extension().string() == extension) {\n      int number = std::stoi(it->path().filename().string());\n      files.insert(std::pair<int, std::string>(number, it->path().string()));\n    }\n  }\n}\n\n/** \\brief Small helper for safely retrieving values from Json root element. */\nclass JSON {\npublic:\n\n  /** \\brief Constructor.\n   * \\param[in] root JSON root element\n   */\n  JSON(Json::Value root) {\n    this->root = root;\n  }\n\n  /** \\brief Get the value of the given key as int.\n   * \\param[in] key key to retrieve\n   * \\return value\n   */\n  int get_int(std::string key) {\n    if (!this->root.isMember(key)) {\n      std::cout << \"[Error] key \" << key << \" not found\" << std::endl;\n      exit(1);\n    }\n\n    return this->root[key].asInt();\n  }\n\n  /** \\brief Get the value of the given key as float.\n   * \\param[in] key key to retrieve\n   * \\return value\n   */\n  float get_float(std::string key) {\n    if (!this->root.isMember(key)) {\n      std::cout << \"[Error] key \" << key << \" not found\" << std::endl;\n      exit(1);\n    }\n\n    return this->root[key].asFloat();\n  }\n\n  /** \\brief Get the value of the given key as string.\n   * \\param[in] key key to retrieve\n   * \\return value\n   */\n  std::string get_string(std::string key) {\n    if (!this->root.isMember(key)) {\n      std::cout << \"[Error] key \" << key << \" not found\" << std::endl;\n      exit(1);\n    }\n\n    return this->root[key].asString();\n  }\n\nprivate:\n\n  /** \\brief Root element. */\n  Json::Value root;\n};\n\nint main(int argc, char** argv) {\n  if (argc != 2) {\n    std::cout << \"[Error] Usage: voxelize_cuboids config.json\" << std::endl;\n    exit(1);\n  }\n\n  Json::Value root;\n  Json::Reader reader;\n\n  std::string config_file = argv[1];\n\n  if (!boost::filesystem::is_regular_file(boost::filesystem::path(config_file))) {\n    std::cout << \"[Error] Config file not found: \" << config_file << std::endl;\n    exit(1);\n  }\n\n  std::ifstream json_file(config_file, std::ifstream::in | std::ifstream::binary);\n  reader.parse(json_file, root, false);\n  JSON json(root);\n\n  // Unsafe!\n  int height = json.get_int(\"height\");\n  int width = json.get_int(\"width\");\n  int depth = json.get_int(\"depth\");\n\n  int image_height = json.get_int(\"image_height\");\n  int image_width = json.get_int(\"image_width\");\n\n  std::string suffix = json.get_string(\"suffix\");\n  int multiplier = json.get_int(\"multiplier\");\n\n  std::string sdf_file = json.get_string(\"sdf_file\");\n  if (sdf_file.empty()) {\n    std::cout << \"[Error] Read invalid output file\" << std::endl;\n    exit(1);\n  }\n\n  sdf_file = sdf_file + \"_\" + std::to_string(multiplier) + \"_\"\n      + std::to_string(image_height) + \"x\" + std::to_string(image_width) + \"_\"\n      + std::to_string(height) + \"x\" + std::to_string(width) + \"x\" + std::to_string(depth)\n      + suffix + \".h5\";\n\n  std::string output_file = json.get_string(\"output_file\");\n  if (output_file.empty()) {\n    std::cout << \"[Error] Read invalid output file\" << std::endl;\n    exit(1);\n  }\n\n  output_file = output_file + \"_\" + std::to_string(multiplier) + \"_\"\n      + std::to_string(image_height) + \"x\" + std::to_string(image_width) + \"_\"\n      + std::to_string(height) + \"x\" + std::to_string(width) + \"x\" + std::to_string(depth)\n      + suffix + \".h5\";\n\n  std::string off_directory = json.get_string(\"off_dir\");\n  if (off_directory.empty()) {\n    std::cout << \"[Error] Read invalid off directory\" << std::endl;\n    exit(1);\n  }\n\n  off_directory = off_directory + \"_\" + std::to_string(multiplier) + \"_\"\n      + std::to_string(image_height) + \"x\" + std::to_string(image_width) + \"_\"\n      + std::to_string(height) + \"x\" + std::to_string(width) + \"x\" + std::to_string(depth) + suffix;\n\n  std::string off_gt_directory = json.get_string(\"off_gt_dir\");\n  if (off_gt_directory.empty()) {\n    std::cout << \"[Error] Read invalid off gt directory\" << std::endl;\n    exit(1);\n  }\n\n  off_gt_directory = off_gt_directory + \"_\" + std::to_string(multiplier) + \"_\"\n      + std::to_string(image_height) + \"x\" + std::to_string(image_width) + \"_\"\n      + std::to_string(height) + \"x\" + std::to_string(width) + \"x\" + std::to_string(depth) + suffix;\n\n  if (!boost::filesystem::is_directory(boost::filesystem::path(off_gt_directory))) {\n    boost::filesystem::create_directories(boost::filesystem::path(off_gt_directory));\n  }\n\n  std::string point_file = json.get_string(\"point_file\");\n  if (point_file.empty()) {\n    std::cout << \"[Error] Read invalid point file\" << std::endl;\n    exit(1);\n  }\n\n  point_file = point_file + \"_\" + std::to_string(multiplier) + \"_\"\n      + std::to_string(image_height) + \"x\" + std::to_string(image_width) + \"_\"\n      + std::to_string(height) + \"x\" + std::to_string(width) + \"x\" + std::to_string(depth)\n      + suffix + \".h5\";\n\n  if (!boost::filesystem::is_directory(boost::filesystem::path(off_directory))) {\n    std::cout << \"[Error] OFF directory \" << off_directory << \" not found\" << std::endl;\n    exit(1);\n  }\n\n  std::map<int, std::string> files;\n  read_directory(off_directory, files);\n\n  int N = files.size();\n  Eigen::Tensor<float, 4, Eigen::RowMajor> sdf(N, height, width, depth);\n  sdf.setZero();\n\n  int N_points = json.get_int(\"n_points\");\n  Eigen::Tensor<float, 3, Eigen::RowMajor> points(N, N_points, 3);\n  points.setZero();\n\n  std::vector<int> indices;\n  for (std::map<int, std::string>::iterator it = files.begin(); it != files.end(); it++) {\n    indices.push_back(it->first);\n  }\n\n  int n = 0;\n  #pragma omp parallel\n  {\n    #pragma omp for\n    for (unsigned int i = 0; i< indices.size(); i++) {\n      int n = indices[i];\n\n      Mesh mesh;\n      bool success = read_off(files[n], mesh);\n\n      if (!success) {\n        std::cout << \"[Error] could not read \" << files[n] << std::endl;\n        exit(1);\n      }\n\n      float padding_factor = 1 + json.get_float(\"padding\");\n      float scale_factor = static_cast<float>(width)/padding_factor;\n      mesh.scale(Eigen::Vector3f(scale_factor, scale_factor, scale_factor));\n      mesh.translate(Eigen::Vector3f(static_cast<float>(width)/2, static_cast<float>(height)/2, static_cast<float>(depth)/2));\n\n      std::cout << \"[Data] sampling mesh \" << n << \"/\" << files.size() << \" \" << files[n] << std::endl;\n      mesh.sample(i, points);\n\n      std::string off_file = off_gt_directory + \"/\" + std::to_string(i) + \".off\";\n      std::cout << \"[Data] writing \" << off_file << std::endl;\n      mesh.to_off(off_file);\n\n      if (!success) {\n        std::cout << \"[Error] error reading \" << files[n] << std::endl;\n        exit(1);\n      }\n\n      std::cout << \"[Data] voxelizing mesh \" << n << \"/\" << files.size() << \" \" << files[n] << std::endl;\n      mesh.voxelize_SCALED(i, sdf);\n\n      n++;\n    }\n  }\n\n  bool success = write_hdf5(sdf_file, sdf);\n\n  if (success) {\n    std::cout <<\"[Data] wrote \" << sdf_file << std::endl;\n  }\n  else {\n    std::cout << \"[Error] error writing \" << sdf_file << std::endl;\n  }\n\n  success = write_hdf5(point_file, points);\n\n  if (success) {\n    std::cout <<\"[Data] wrote \" << point_file << std::endl;\n  }\n  else {\n    std::cout << \"[Error] error writing \" << point_file << std::endl;\n  }\n\n  Eigen::Tensor<int, 4, Eigen::RowMajor> occ(N, height, width, depth);\n  occ.setZero();\n\n  for (int n = 0; n < N; n++) {\n    for (int h = 0; h < height; h++) {\n      for (int w = 0; w < width; w++) {\n        for (int d = 0; d < depth; d++) {\n          if (sdf(n, h, w, d) <= 0) {\n            occ(n, h, w, d) = 1;\n          }\n        }\n      }\n    }\n  }\n\n  success = write_hdf5(output_file, occ);\n\n  if (success) {\n    std::cout <<\"[Data] wrote \" << output_file << std::endl;\n  }\n  else {\n    std::cout << \"[Error] error writing \" << output_file << std::endl;\n  }\n\n  exit(0);\n}", "meta": {"hexsha": "0884bc06022a7884f234039a463c9c2bea928f47", "size": 35562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/shapenet/libvoxelizemesh/voxelize_meshs.cpp", "max_stars_repo_name": "davidstutz/daml-shape-completion", "max_stars_repo_head_hexsha": "d0d1d1c26ba547d02c4102077aeb0a1ea46c4e50", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2018-05-16T01:49:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T10:24:44.000Z", "max_issues_repo_path": "data/shapenet/libvoxelizemesh/voxelize_meshs.cpp", "max_issues_repo_name": "davidstutz/daml-shape-completion", "max_issues_repo_head_hexsha": "d0d1d1c26ba547d02c4102077aeb0a1ea46c4e50", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-19T04:46:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T10:38:31.000Z", "max_forks_repo_path": "data/shapenet/libvoxelizemesh/voxelize_meshs.cpp", "max_forks_repo_name": "davidstutz/daml-shape-completion", "max_forks_repo_head_hexsha": "d0d1d1c26ba547d02c4102077aeb0a1ea46c4e50", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-04-30T01:30:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T10:24:46.000Z", "avg_line_length": 28.9592833876, "max_line_length": 159, "alphanum_fraction": 0.6030594455, "num_tokens": 10250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.2389533910267992}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Thu 10 May 2018 15:01:38\n\n#ifndef NUHMSSM_susy_parameters_H\n#define NUHMSSM_susy_parameters_H\n\n#include \"betafunction.hpp\"\n#include \"NUHMSSM_input_parameters.hpp\"\n\n#include <iosfwd>\n#include <string>\n#include <vector>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\n#ifdef TRACE_STRUCT_TYPE\n   #undef TRACE_STRUCT_TYPE\n#endif\n#define TRACE_STRUCT_TYPE Susy_traces\n\nclass NUHMSSM_susy_parameters : public Beta_function {\npublic:\n   explicit NUHMSSM_susy_parameters(const NUHMSSM_input_parameters& input_ = NUHMSSM_input_parameters());\n   NUHMSSM_susy_parameters(double scale_, int loops_, int thresholds_, const NUHMSSM_input_parameters& input_, const Eigen::Matrix<double,3,3>& Yd_, const Eigen::Matrix<double,3,3>& Ye_\n   , const Eigen::Matrix<double,3,3>& Yu_, double Mu_, double g1_, double g2_,\n   double g3_, double vd_, double vu_\n);\n   NUHMSSM_susy_parameters(const NUHMSSM_susy_parameters&) = default;\n   NUHMSSM_susy_parameters(NUHMSSM_susy_parameters&&) = default;\n   virtual ~NUHMSSM_susy_parameters() = default;\n   NUHMSSM_susy_parameters& operator=(const NUHMSSM_susy_parameters&) = default;\n   NUHMSSM_susy_parameters& operator=(NUHMSSM_susy_parameters&&) = default;\n\n   virtual Eigen::ArrayXd beta() const override;\n   virtual Eigen::ArrayXd get() const override;\n   virtual void print(std::ostream&) const;\n   virtual void set(const Eigen::ArrayXd&) override;\n   const NUHMSSM_input_parameters& get_input() const;\n   NUHMSSM_input_parameters& get_input();\n   void set_input_parameters(const NUHMSSM_input_parameters&);\n\n   NUHMSSM_susy_parameters calc_beta() const;\n   NUHMSSM_susy_parameters calc_beta(int) const;\n   virtual void clear();\n\n   void set_Yd(const Eigen::Matrix<double,3,3>& Yd_) { Yd = Yd_; }\n   void set_Yd(int i, int k, const double& value) { Yd(i,k) = value; }\n   void set_Ye(const Eigen::Matrix<double,3,3>& Ye_) { Ye = Ye_; }\n   void set_Ye(int i, int k, const double& value) { Ye(i,k) = value; }\n   void set_Yu(const Eigen::Matrix<double,3,3>& Yu_) { Yu = Yu_; }\n   void set_Yu(int i, int k, const double& value) { Yu(i,k) = value; }\n   void set_Mu(double Mu_) { Mu = Mu_; }\n   void set_g1(double g1_) { g1 = g1_; }\n   void set_g2(double g2_) { g2 = g2_; }\n   void set_g3(double g3_) { g3 = g3_; }\n   void set_vd(double vd_) { vd = vd_; }\n   void set_vu(double vu_) { vu = vu_; }\n\n   const Eigen::Matrix<double,3,3>& get_Yd() const { return Yd; }\n   double get_Yd(int i, int k) const { return Yd(i,k); }\n   const Eigen::Matrix<double,3,3>& get_Ye() const { return Ye; }\n   double get_Ye(int i, int k) const { return Ye(i,k); }\n   const Eigen::Matrix<double,3,3>& get_Yu() const { return Yu; }\n   double get_Yu(int i, int k) const { return Yu(i,k); }\n   double get_Mu() const { return Mu; }\n   double get_g1() const { return g1; }\n   double get_g2() const { return g2; }\n   double get_g3() const { return g3; }\n   double get_vd() const { return vd; }\n   double get_vu() const { return vu; }\n\n   Eigen::Matrix<double,3,3> get_SqSq() const;\n   Eigen::Matrix<double,3,3> get_SlSl() const;\n   double get_SHdSHd() const;\n   double get_SHuSHu() const;\n   Eigen::Matrix<double,3,3> get_SdRSdR() const;\n   Eigen::Matrix<double,3,3> get_SuRSuR() const;\n   Eigen::Matrix<double,3,3> get_SeRSeR() const;\n\n\nprotected:\n   Eigen::Matrix<double,3,3> Yd{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> Ye{Eigen::Matrix<double,3,3>::Zero()};\n   Eigen::Matrix<double,3,3> Yu{Eigen::Matrix<double,3,3>::Zero()};\n   double Mu{};\n   double g1{};\n   double g2{};\n   double g3{};\n   double vd{};\n   double vu{};\n\n   NUHMSSM_input_parameters input{};\n\nprivate:\n   static const int numberOfParameters = 33;\n\n   struct Susy_traces {\n      double traceYdAdjYd{};\n      double traceYeAdjYe{};\n      double traceYdAdjYdYdAdjYd{};\n      double traceYdAdjYuYuAdjYd{};\n      double traceYeAdjYeYeAdjYe{};\n      double traceYuAdjYu{};\n      double traceAdjYdYd{};\n      double traceAdjYeYe{};\n      double traceAdjYuYu{};\n      double traceAdjYdYdAdjYdYd{};\n      double traceAdjYeYeAdjYeYe{};\n      double traceAdjYuYuAdjYdYd{};\n      double traceAdjYuYuAdjYuYu{};\n      double traceAdjYdYdAdjYdYdAdjYdYd{};\n      double traceAdjYeYeAdjYeYeAdjYeYe{};\n      double traceAdjYuYuAdjYuYuAdjYdYd{};\n      double traceYuAdjYuYuAdjYu{};\n      double traceAdjYdYdAdjYuYuAdjYdYd{};\n      double traceAdjYuYuAdjYuYuAdjYuYu{};\n\n   };\n   Susy_traces calc_susy_traces(int) const;\n\n   Eigen::Matrix<double,3,3> calc_beta_Yd_1_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yd_2_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yd_3_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Ye_1_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Ye_2_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Ye_3_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yu_1_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yu_2_loop(const TRACE_STRUCT_TYPE&) const;\n   Eigen::Matrix<double,3,3> calc_beta_Yu_3_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Mu_1_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Mu_2_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_Mu_3_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g1_1_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g1_2_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g1_3_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g2_1_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g2_2_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g2_3_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g3_1_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g3_2_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_g3_3_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_vd_1_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_vd_2_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_vd_3_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_vu_1_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_vu_2_loop(const TRACE_STRUCT_TYPE&) const;\n   double calc_beta_vu_3_loop(const TRACE_STRUCT_TYPE&) const;\n\n};\n\nstd::ostream& operator<<(std::ostream&, const NUHMSSM_susy_parameters&);\n\n#undef TRACE_STRUCT_TYPE\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "f53c140986f85962134552bb8a55339f03358768", "size": 7259, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/NUHMSSM/NUHMSSM_susy_parameters.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/NUHMSSM/NUHMSSM_susy_parameters.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/NUHMSSM/NUHMSSM_susy_parameters.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 41.2443181818, "max_line_length": 185, "alphanum_fraction": 0.7206226753, "num_tokens": 2081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23869078194630144}}
{"text": "/**\n * @file ffn_impl.hpp\n * @author Marcus Edel\n *\n * Definition of the FFN class, which implements feed forward neural networks.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#ifndef MLPACK_METHODS_ANN_FFN_IMPL_HPP\n#define MLPACK_METHODS_ANN_FFN_IMPL_HPP\n\n// In case it hasn't been included yet.\n#include \"ffn.hpp\"\n\n#include \"visitor/forward_visitor.hpp\"\n#include \"visitor/backward_visitor.hpp\"\n#include \"visitor/deterministic_set_visitor.hpp\"\n#include \"visitor/gradient_set_visitor.hpp\"\n#include \"visitor/gradient_visitor.hpp\"\n#include \"visitor/set_input_height_visitor.hpp\"\n#include \"visitor/set_input_width_visitor.hpp\"\n\n#include <boost/serialization/variant.hpp>\n\nnamespace mlpack {\nnamespace ann /** Artificial Neural Network. */ {\n\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nFFN<OutputLayerType, InitializationRuleType, CustomLayers...>::FFN(\n    OutputLayerType outputLayer, InitializationRuleType initializeRule) :\n    outputLayer(std::move(outputLayer)),\n    initializeRule(std::move(initializeRule)),\n    width(0),\n    height(0),\n    reset(false),\n    numFunctions(0),\n    deterministic(true)\n{\n  /* Nothing to do here */\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nFFN<OutputLayerType, InitializationRuleType, CustomLayers...>::~FFN()\n{\n  std::for_each(network.begin(), network.end(),\n      boost::apply_visitor(deleteVisitor));\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::ResetData(\n    arma::mat predictors, arma::mat responses)\n{\n  numFunctions = responses.n_cols;\n  this->predictors = std::move(predictors);\n  this->responses = std::move(responses);\n  this->deterministic = true;\n  ResetDeterministic();\n\n  if (!reset)\n    ResetParameters();\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename OptimizerType, typename... CallbackTypes>\ndouble FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Train(\n      arma::mat predictors,\n      arma::mat responses,\n      OptimizerType& optimizer,\n      CallbackTypes&&... callbacks)\n{\n  ResetData(std::move(predictors), std::move(responses));\n\n  // Train the model.\n  Timer::Start(\"ffn_optimization\");\n  const double out = optimizer.Optimize(*this, parameter, callbacks...);\n  Timer::Stop(\"ffn_optimization\");\n\n  Log::Info << \"FFN::FFN(): final objective of trained model is \" << out\n      << \".\" << std::endl;\n  return out;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename OptimizerType, typename... CallbackTypes>\ndouble FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Train(\n    arma::mat predictors,\n    arma::mat responses,\n    CallbackTypes&&... callbacks)\n{\n  ResetData(std::move(predictors), std::move(responses));\n\n  OptimizerType optimizer;\n\n  // Train the model.\n  Timer::Start(\"ffn_optimization\");\n  const double out = optimizer.Optimize(*this, parameter, callbacks...);\n  Timer::Stop(\"ffn_optimization\");\n\n  Log::Info << \"FFN::FFN(): final objective of trained model is \" << out\n      << \".\" << std::endl;\n  return out;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Forward(\n    arma::mat inputs, arma::mat& results)\n{\n  if (parameter.is_empty())\n    ResetParameters();\n\n  if (!deterministic)\n  {\n    deterministic = true;\n    ResetDeterministic();\n  }\n\n  currentInput = std::move(inputs);\n  Forward(std::move(currentInput));\n  results = boost::apply_visitor(outputParameterVisitor, network.back());\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Forward(\n    arma::mat inputs, arma::mat& results, const size_t begin, const size_t end)\n{\n  boost::apply_visitor(ForwardVisitor(std::move(inputs), std::move(\n      boost::apply_visitor(outputParameterVisitor, network[begin]))),\n      network[begin]);\n\n  for (size_t i = 1; i < end - begin + 1; ++i)\n  {\n    boost::apply_visitor(ForwardVisitor(std::move(boost::apply_visitor(\n        outputParameterVisitor, network[begin + i - 1])), std::move(\n        boost::apply_visitor(outputParameterVisitor, network[begin + i]))),\n        network[begin + i]);\n  }\n\n  results = boost::apply_visitor(outputParameterVisitor, network[end]);\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ndouble FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Backward(\n    arma::mat targets, arma::mat& gradients)\n{\n  double res = outputLayer.Forward(std::move(boost::apply_visitor(\n      outputParameterVisitor, network.back())), std::move(targets));\n\n  for (size_t i = 0; i < network.size(); ++i)\n  {\n    res += boost::apply_visitor(lossVisitor, network[i]);\n  }\n\n  outputLayer.Backward(std::move(boost::apply_visitor(outputParameterVisitor,\n      network.back())), std::move(targets), std::move(error));\n\n  gradients = arma::zeros<arma::mat>(parameter.n_rows, parameter.n_cols);\n\n  Backward();\n  ResetGradients(gradients);\n  Gradient(std::move(currentInput));\n\n  return res;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Predict(\n    arma::mat predictors, arma::mat& results)\n{\n  if (parameter.is_empty())\n    ResetParameters();\n\n  if (!deterministic)\n  {\n    deterministic = true;\n    ResetDeterministic();\n  }\n\n  arma::mat resultsTemp;\n  Forward(std::move(arma::mat(predictors.colptr(0),\n      predictors.n_rows, 1, false, true)));\n  resultsTemp = boost::apply_visitor(outputParameterVisitor,\n      network.back()).col(0);\n\n  results = arma::mat(resultsTemp.n_elem, predictors.n_cols);\n  results.col(0) = resultsTemp.col(0);\n\n  for (size_t i = 1; i < predictors.n_cols; i++)\n  {\n    Forward(std::move(arma::mat(predictors.colptr(i),\n        predictors.n_rows, 1, false, true)));\n\n    resultsTemp = boost::apply_visitor(outputParameterVisitor,\n        network.back());\n    results.col(i) = resultsTemp.col(0);\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ndouble FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Evaluate(\n    arma::mat predictors, arma::mat responses)\n{\n  if (parameter.is_empty())\n    ResetParameters();\n\n  if (!deterministic)\n  {\n    deterministic = true;\n    ResetDeterministic();\n  }\n\n  Forward(std::move(predictors));\n\n  double res = outputLayer.Forward(std::move(boost::apply_visitor(\n      outputParameterVisitor, network.back())), std::move(responses));\n\n  for (size_t i = 0; i < network.size(); ++i)\n  {\n    res += boost::apply_visitor(lossVisitor, network[i]);\n  }\n\n  return res;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ndouble FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Evaluate(\n    const arma::mat& parameters)\n{\n  double res = 0;\n  for (size_t i = 0; i < predictors.n_cols; ++i)\n    res += Evaluate(parameters, i, 1, true);\n\n  return res;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ndouble FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Evaluate(\n    const arma::mat& /* parameters */,\n    const size_t begin,\n    const size_t batchSize,\n    const bool deterministic)\n{\n  if (parameter.is_empty())\n    ResetParameters();\n\n  if (deterministic != this->deterministic)\n  {\n    this->deterministic = deterministic;\n    ResetDeterministic();\n  }\n\n  Forward(std::move(predictors.cols(begin, begin + batchSize - 1)));\n  double res = outputLayer.Forward(\n      std::move(boost::apply_visitor(outputParameterVisitor, network.back())),\n      std::move(responses.cols(begin, begin + batchSize - 1)));\n\n  for (size_t i = 0; i < network.size(); ++i)\n  {\n    res += boost::apply_visitor(lossVisitor, network[i]);\n  }\n\n  return res;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ndouble FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Evaluate(\n    const arma::mat& parameters, const size_t begin, const size_t batchSize)\n{\n  return Evaluate(parameters, begin, batchSize, true);\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename GradType>\ndouble FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::\nEvaluateWithGradient(const arma::mat& parameters, GradType& gradient)\n{\n  double res = 0;\n  for (size_t i = 0; i < predictors.n_cols; ++i)\n    res += EvaluateWithGradient(parameters, i, gradient, 1);\n\n  return res;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename GradType>\ndouble FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::\nEvaluateWithGradient(const arma::mat& /* parameters */,\n                     const size_t begin,\n                     GradType& gradient,\n                     const size_t batchSize)\n{\n  if (gradient.is_empty())\n  {\n    if (parameter.is_empty())\n      ResetParameters();\n\n    gradient = arma::zeros<arma::mat>(parameter.n_rows, parameter.n_cols);\n  }\n  else\n  {\n    gradient.zeros();\n  }\n\n  if (this->deterministic)\n  {\n    this->deterministic = false;\n    ResetDeterministic();\n  }\n\n  Forward(std::move(predictors.cols(begin, begin + batchSize - 1)));\n  double res = outputLayer.Forward(\n      std::move(boost::apply_visitor(outputParameterVisitor, network.back())),\n      std::move(responses.cols(begin, begin + batchSize - 1)));\n\n  for (size_t i = 0; i < network.size(); ++i)\n  {\n    res += boost::apply_visitor(lossVisitor, network[i]);\n  }\n\n  outputLayer.Backward(\n      std::move(boost::apply_visitor(outputParameterVisitor, network.back())),\n      std::move(responses.cols(begin, begin + batchSize - 1)),\n      std::move(error));\n\n  Backward();\n  ResetGradients(gradient);\n  Gradient(std::move(predictors.cols(begin, begin + batchSize - 1)));\n\n  return res;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Gradient(\n    const arma::mat& parameters,\n    const size_t begin,\n    arma::mat& gradient,\n    const size_t batchSize)\n{\n  this->EvaluateWithGradient(parameters, begin, gradient, batchSize);\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Shuffle()\n{\n  math::ShuffleData(predictors, responses, predictors, responses);\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType,\n         CustomLayers...>::ResetParameters()\n{\n  ResetDeterministic();\n\n  // Reset the network parameter with the given initialization rule.\n  NetworkInitialization<InitializationRuleType,\n                        CustomLayers...> networkInit(initializeRule);\n  networkInit.Initialize(network, parameter);\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType,\n         CustomLayers...>::ResetDeterministic()\n{\n  DeterministicSetVisitor deterministicSetVisitor(deterministic);\n  std::for_each(network.begin(), network.end(),\n      boost::apply_visitor(deterministicSetVisitor));\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType,\n         CustomLayers...>::ResetGradients(arma::mat& gradient)\n{\n  size_t offset = 0;\n  for (size_t i = 0; i < network.size(); ++i)\n  {\n    offset += boost::apply_visitor(GradientSetVisitor(std::move(gradient),\n        offset), network[i]);\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType,\n         CustomLayers...>::Forward(arma::mat&& input)\n{\n  boost::apply_visitor(ForwardVisitor(std::move(input), std::move(\n      boost::apply_visitor(outputParameterVisitor, network.front()))),\n      network.front());\n\n  if (!reset)\n  {\n    if (boost::apply_visitor(outputWidthVisitor, network.front()) != 0)\n    {\n      width = boost::apply_visitor(outputWidthVisitor, network.front());\n    }\n\n    if (boost::apply_visitor(outputHeightVisitor, network.front()) != 0)\n    {\n      height = boost::apply_visitor(outputHeightVisitor, network.front());\n    }\n  }\n\n  for (size_t i = 1; i < network.size(); ++i)\n  {\n    if (!reset)\n    {\n      // Set the input width.\n      boost::apply_visitor(SetInputWidthVisitor(width), network[i]);\n\n      // Set the input height.\n      boost::apply_visitor(SetInputHeightVisitor(height), network[i]);\n    }\n\n    boost::apply_visitor(ForwardVisitor(std::move(boost::apply_visitor(\n        outputParameterVisitor, network[i - 1])), std::move(\n        boost::apply_visitor(outputParameterVisitor, network[i]))), network[i]);\n\n    if (!reset)\n    {\n      // Get the output width.\n      if (boost::apply_visitor(outputWidthVisitor, network[i]) != 0)\n      {\n        width = boost::apply_visitor(outputWidthVisitor, network[i]);\n      }\n\n      // Get the output height.\n      if (boost::apply_visitor(outputHeightVisitor, network[i]) != 0)\n      {\n        height = boost::apply_visitor(outputHeightVisitor, network[i]);\n      }\n    }\n  }\n\n  if (!reset)\n    reset = true;\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::Backward()\n{\n  boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor(\n      outputParameterVisitor, network.back())), std::move(error), std::move(\n      boost::apply_visitor(deltaVisitor, network.back()))), network.back());\n\n  for (size_t i = 2; i < network.size(); ++i)\n  {\n    boost::apply_visitor(BackwardVisitor(std::move(boost::apply_visitor(\n        outputParameterVisitor, network[network.size() - i])), std::move(\n        boost::apply_visitor(deltaVisitor, network[network.size() - i + 1])),\n        std::move(boost::apply_visitor(deltaVisitor,\n        network[network.size() - i]))), network[network.size() - i]);\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType,\n         CustomLayers...>::Gradient(arma::mat&& input)\n{\n  boost::apply_visitor(GradientVisitor(std::move(input), std::move(\n      boost::apply_visitor(deltaVisitor, network[1]))), network.front());\n\n  for (size_t i = 1; i < network.size() - 1; ++i)\n  {\n    boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor(\n        outputParameterVisitor, network[i - 1])), std::move(\n        boost::apply_visitor(deltaVisitor, network[i + 1]))), network[i]);\n  }\n\n  boost::apply_visitor(GradientVisitor(std::move(boost::apply_visitor(\n      outputParameterVisitor, network[network.size() - 2])), std::move(error)),\n      network[network.size() - 1]);\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename Archive>\nvoid FFN<OutputLayerType, InitializationRuleType, CustomLayers...>::serialize(\n    Archive& ar, const unsigned int version)\n{\n  ar & BOOST_SERIALIZATION_NVP(parameter);\n  ar & BOOST_SERIALIZATION_NVP(width);\n  ar & BOOST_SERIALIZATION_NVP(height);\n  ar & BOOST_SERIALIZATION_NVP(currentInput);\n\n  // Earlier versions of the FFN code did not serialize whether or not the model\n  // was reset.\n  if (version > 0)\n  {\n    ar & BOOST_SERIALIZATION_NVP(reset);\n  }\n\n  // Be sure to clear other layers before loading.\n  if (Archive::is_loading::value)\n  {\n    std::for_each(network.begin(), network.end(),\n        boost::apply_visitor(deleteVisitor));\n    network.clear();\n  }\n\n  ar & BOOST_SERIALIZATION_NVP(network);\n\n  // If we are loading, we need to initialize the weights.\n  if (Archive::is_loading::value)\n  {\n    // The behavior in earlier versions was to always assume the weights needed\n    // to be reset.\n    if (version == 0)\n      reset = false;\n\n    size_t offset = 0;\n    for (size_t i = 0; i < network.size(); ++i)\n    {\n      offset += boost::apply_visitor(WeightSetVisitor(std::move(parameter),\n          offset), network[i]);\n\n      boost::apply_visitor(resetVisitor, network[i]);\n    }\n\n    deterministic = true;\n    ResetDeterministic();\n  }\n}\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid FFN<OutputLayerType, InitializationRuleType,\n         CustomLayers...>::Swap(FFN& network)\n{\n  std::swap(outputLayer, network.outputLayer);\n  std::swap(initializeRule, network.initializeRule);\n  std::swap(width, network.width);\n  std::swap(height, network.height);\n  std::swap(reset, network.reset);\n  std::swap(this->network, network.network);\n  std::swap(predictors, network.predictors);\n  std::swap(responses, network.responses);\n  std::swap(parameter, network.parameter);\n  std::swap(numFunctions, network.numFunctions);\n  std::swap(error, network.error);\n  std::swap(currentInput, network.currentInput);\n  std::swap(deterministic, network.deterministic);\n  std::swap(delta, network.delta);\n  std::swap(inputParameter, network.inputParameter);\n  std::swap(outputParameter, network.outputParameter);\n  std::swap(gradient, network.gradient);\n};\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nFFN<OutputLayerType, InitializationRuleType, CustomLayers...>::FFN(\n    const FFN& network):\n    outputLayer(network.outputLayer),\n    initializeRule(network.initializeRule),\n    width(network.width),\n    height(network.height),\n    reset(network.reset),\n    predictors(network.predictors),\n    responses(network.responses),\n    parameter(network.parameter),\n    numFunctions(network.numFunctions),\n    error(network.error),\n    currentInput(network.currentInput),\n    deterministic(network.deterministic),\n    delta(network.delta),\n    inputParameter(network.inputParameter),\n    outputParameter(network.outputParameter),\n    gradient(network.gradient)\n{\n  // Build new layers according to source network\n  for (size_t i = 0; i < network.network.size(); ++i)\n  {\n    this->network.push_back(boost::apply_visitor(copyVisitor,\n        network.network[i]));\n  }\n};\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nFFN<OutputLayerType, InitializationRuleType, CustomLayers...>::FFN(\n    FFN&& network):\n    outputLayer(std::move(network.outputLayer)),\n    initializeRule(std::move(network.initializeRule)),\n    width(network.width),\n    height(network.height),\n    reset(network.reset),\n    predictors(std::move(network.predictors)),\n    responses(std::move(network.responses)),\n    parameter(std::move(network.parameter)),\n    numFunctions(network.numFunctions),\n    error(std::move(network.error)),\n    currentInput(std::move(network.currentInput)),\n    deterministic(network.deterministic),\n    delta(std::move(network.delta)),\n    inputParameter(std::move(network.inputParameter)),\n    outputParameter(std::move(network.outputParameter)),\n    gradient(std::move(network.gradient))\n{\n  this->network = std::move(network.network);\n};\n\ntemplate<typename OutputLayerType, typename InitializationRuleType,\n         typename... CustomLayers>\nFFN<OutputLayerType, InitializationRuleType, CustomLayers...>&\nFFN<OutputLayerType, InitializationRuleType,\n    CustomLayers...>::operator = (FFN network)\n{\n  Swap(network);\n  return *this;\n};\n\n} // namespace ann\n} // namespace mlpack\n\n#endif\n", "meta": {"hexsha": "f39bbfdb130c4b4f6b304cd5b228ae6a47632d50", "size": 20346, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/methods/ann/ffn_impl.hpp", "max_stars_repo_name": "tomjpsun/mlpack", "max_stars_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-11T14:14:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-11T14:14:30.000Z", "max_issues_repo_path": "src/mlpack/methods/ann/ffn_impl.hpp", "max_issues_repo_name": "tomjpsun/mlpack", "max_issues_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/methods/ann/ffn_impl.hpp", "max_forks_repo_name": "tomjpsun/mlpack", "max_forks_repo_head_hexsha": "39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.790625, "max_line_length": 80, "alphanum_fraction": 0.7053474884, "num_tokens": 4651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23869078194630144}}
{"text": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <qle/termstructures/spreadedblackvolatilitysurfacemoneyness.hpp>\n\n#include <ql/math/interpolations/bilinearinterpolation.hpp>\n#include <ql/math/interpolations/flatextrapolation2d.hpp>\n#include <ql/math/interpolations/linearinterpolation.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/termstructures/yield/forwardcurve.hpp>\n#include <ql/utilities/dataformatters.hpp>\n\n#include <boost/make_shared.hpp>\n\nusing namespace std;\n\nnamespace QuantExt {\n\nSpreadedBlackVolatilitySurfaceMoneyness::SpreadedBlackVolatilitySurfaceMoneyness(\n    const Handle<BlackVolTermStructure>& referenceVol, const Handle<Quote>& movingSpot, const std::vector<Time>& times,\n    const std::vector<Real>& moneyness, const std::vector<std::vector<Handle<Quote>>>& volSpreads,\n    const Handle<Quote>& stickySpot, const Handle<YieldTermStructure>& stickyDividendTs,\n    const Handle<YieldTermStructure>& stickyRiskFreeTs, const Handle<YieldTermStructure>& movingDividendTs,\n    const Handle<YieldTermStructure>& movingRiskFreeTs, bool stickyStrike)\n    : BlackVolatilityTermStructure(referenceVol->businessDayConvention(), referenceVol->dayCounter()),\n      referenceVol_(referenceVol), movingSpot_(movingSpot), times_(times), moneyness_(moneyness),\n      volSpreads_(volSpreads), stickySpot_(stickySpot), stickyDividendTs_(stickyDividendTs),\n      stickyRiskFreeTs_(stickyRiskFreeTs), movingDividendTs_(movingDividendTs), movingRiskFreeTs_(movingRiskFreeTs),\n      stickyStrike_(stickyStrike) {\n\n    // register with observables\n\n    registerWith(referenceVol_);\n    registerWith(movingSpot_);\n    registerWith(stickySpot_);\n\n    for (auto const& v : volSpreads_)\n        for (auto const& s : v)\n            registerWith(s);\n\n    registerWith(stickyDividendTs_);\n    registerWith(stickyRiskFreeTs_);\n    registerWith(movingDividendTs_);\n    registerWith(movingRiskFreeTs_);\n\n    // check our preconditions on the inputs\n\n    QL_REQUIRE(!times_.empty(), \"no times given\");\n    QL_REQUIRE(!moneyness_.empty(), \"no moneyness values given\");\n    QL_REQUIRE(moneyness_.size() == volSpreads_.size(), \"mismatch between moneyness vector and vol matrix rows\");\n\n    for (auto const& v : volSpreads_) {\n        QL_REQUIRE(times_.size() == v.size(), \"mismatch between times vector and vol matrix colums\");\n    }\n\n    for (Size j = 1; j < times_.size(); ++j) {\n        QL_REQUIRE(times_[j] > times_[j - 1], \"Times must be sorted and unique but found that the \"\n                                                  << io::ordinal(j) << \" time, \" << times_[j]\n                                                  << \", is not greater than the \" << io::ordinal(j - 1) << \" time, \"\n                                                  << times_[j - 1] << \".\");\n    }\n\n    // add an artificial time if there is only one to make the interpolation work\n\n    if (times_.size() == 1) {\n        times_.push_back(times_.back() + 1.0);\n        for (auto& v : volSpreads_)\n            v.push_back(v.back());\n    }\n\n    // add an artificial moneyness if there is only one to make the interpolation work\n\n    if (moneyness_.size() == 1) {\n        moneyness_.push_back(moneyness_.back() + 1.0);\n        volSpreads_.push_back(volSpreads_.back());\n    }\n\n    // create data matrix used for interpolation and the interpolation object\n\n    data_ = Matrix(moneyness_.size(), times_.size(), 0.0);\n    volSpreadSurface_ = FlatExtrapolator2D(boost::make_shared<BilinearInterpolation>(\n        times_.begin(), times_.end(), moneyness_.begin(), moneyness_.end(), data_));\n    volSpreadSurface_.enableExtrapolation();\n}\n\nDate SpreadedBlackVolatilitySurfaceMoneyness::maxDate() const { return referenceVol_->maxDate(); }\nconst Date& SpreadedBlackVolatilitySurfaceMoneyness::referenceDate() const { return referenceVol_->referenceDate(); }\nCalendar SpreadedBlackVolatilitySurfaceMoneyness::calendar() const { return referenceVol_->calendar(); }\nNatural SpreadedBlackVolatilitySurfaceMoneyness::settlementDays() const { return referenceVol_->settlementDays(); }\nReal SpreadedBlackVolatilitySurfaceMoneyness::minStrike() const { return referenceVol_->minStrike(); }\nReal SpreadedBlackVolatilitySurfaceMoneyness::maxStrike() const { return referenceVol_->maxStrike(); }\n\nvoid SpreadedBlackVolatilitySurfaceMoneyness::update() {\n    LazyObject::update();\n    BlackVolatilityTermStructure::update();\n}\n\nconst std::vector<QuantLib::Real>& SpreadedBlackVolatilitySurfaceMoneyness::moneyness() const { return moneyness_; }\n\nvoid SpreadedBlackVolatilitySurfaceMoneyness::performCalculations() const {\n    for (Size j = 0; j < data_.columns(); ++j) {\n        for (Size i = 0; i < data_.rows(); ++i) {\n            data_(i, j) = volSpreads_[i][j]->value();\n        }\n    }\n    volSpreadSurface_.update();\n}\n\nReal SpreadedBlackVolatilitySurfaceMoneyness::blackVolImpl(Time t, Real strike) const {\n    calculate();\n    QL_REQUIRE(!referenceVol_.empty(), \"SpreadedBlackVolatilitySurfaceMoneyness: reference vol is empty\");\n    Real m = moneynessFromStrike(t, strike, false);\n    QL_REQUIRE(std::isfinite(m),\n               \"SpreadedBlackVolatilitySurfaceMoneyness: got invalid moneyness (dynamic reference) at t = \"\n                   << t << \", strike = \" << strike << \": \" << m);\n    Real effStrike;\n    if (stickyStrike_)\n        effStrike = strike;\n    else {\n        effStrike = strikeFromMoneyness(t, m, true);\n        QL_REQUIRE(std::isfinite(effStrike),\n                   \"SpreadedBlackVolatilitySurfaceMoneyness: got invalid strike from moneyness at t = \"\n                       << t << \", input strike = \" << strike << \", moneyness = \" << m);\n    }\n    Real m2 = moneynessFromStrike(t, strike, false);\n    QL_REQUIRE(std::isfinite(m2),\n               \"SpreadedBlackVolatilitySurfaceMoneyness: got invalid moneyness (sticky reference) at t = \"\n                   << t << \", strike = \" << strike << \": \" << m2);\n    return referenceVol_->blackVol(t, effStrike) + volSpreadSurface_(t, m2);\n}\n\nReal SpreadedBlackVolatilitySurfaceMoneynessSpot::moneynessFromStrike(Time t, Real strike,\n                                                                      const bool stickyReference) const {\n    if (strike == Null<Real>() || close_enough(strike, 0.0)) {\n        return 1.0;\n    } else {\n        QL_REQUIRE(!stickyReference || !stickySpot_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessSpot: stickySpot is empty\");\n        QL_REQUIRE(stickyReference || !movingSpot_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessSpot: movingSpot is empty\");\n        return strike / (stickyReference ? stickySpot_->value() : movingSpot_->value());\n    }\n}\n\nReal SpreadedBlackVolatilitySurfaceMoneynessSpot::strikeFromMoneyness(Time t, Real moneyness,\n                                                                      const bool stickyReference) const {\n    QL_REQUIRE(!stickyReference || !stickySpot_.empty(),\n               \"SpreadedBlackVolatilitySurfaceMoneynessSpot: stickySpot is empty\");\n    QL_REQUIRE(stickyReference || !movingSpot_.empty(),\n               \"SpreadedBlackVolatilitySurfaceMoneynessSpot: movingSpot is empty\");\n    return moneyness * (stickyReference ? stickySpot_->value() : movingSpot_->value());\n}\n\nReal SpreadedBlackVolatilitySurfaceLogMoneynessSpot::moneynessFromStrike(Time t, Real strike,\n                                                                         const bool stickyReference) const {\n    if (strike == Null<Real>() || close_enough(strike, 0.0)) {\n        return 0.0;\n    } else {\n        QL_REQUIRE(!stickyReference || !stickySpot_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceLogMoneynessSpot: stickySpot is empty\");\n        QL_REQUIRE(stickyReference || !movingSpot_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceLogMoneynessSpot: movingSpot is empty\");\n        return std::log(strike / (stickyReference ? stickySpot_->value() : movingSpot_->value()));\n    }\n}\n\nReal SpreadedBlackVolatilitySurfaceLogMoneynessSpot::strikeFromMoneyness(Time t, Real moneyness,\n                                                                         const bool stickyReference) const {\n    QL_REQUIRE(!stickyReference || !stickySpot_.empty(),\n               \"SpreadedBlackVolatilitySurfaceLogMoneynessSpot: stickySpot is empty\");\n    QL_REQUIRE(stickyReference || !movingSpot_.empty(),\n               \"SpreadedBlackVolatilitySurfaceLogMoneynessSpot: movingSpot is empty\");\n    return std::exp(moneyness) * (stickyReference ? stickySpot_->value() : movingSpot_->value());\n}\n\nReal SpreadedBlackVolatilitySurfaceMoneynessForward::moneynessFromStrike(Time t, Real strike,\n                                                                         const bool stickyReference) const {\n    if (strike == Null<Real>() || close_enough(strike, 0.0))\n        return 1.0;\n    else {\n        Real forward;\n        if (stickyReference) {\n            QL_REQUIRE(!stickySpot_.empty(), \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickySpot is empty\");\n            QL_REQUIRE(!stickyDividendTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickyDividendTs is empty\");\n            QL_REQUIRE(!stickyRiskFreeTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickyRiskFreeTs is empty\");\n            forward = stickySpot_->value() * stickyDividendTs_->discount(t) / stickyRiskFreeTs_->discount(t);\n        } else {\n            QL_REQUIRE(!movingSpot_.empty(), \"SpreadedBlackVolatilitySurfaceMoneynessForward: movingSpot is empty\");\n            QL_REQUIRE(!movingDividendTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceMoneynessForward: movingDividendTs is empty\");\n            QL_REQUIRE(!movingRiskFreeTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceMoneynessForward: mocingRiskFreeTs is empty\");\n            forward = movingSpot_->value() * movingDividendTs_->discount(t) / movingRiskFreeTs_->discount(t);\n        }\n        return strike / forward;\n    }\n}\n\nReal SpreadedBlackVolatilitySurfaceMoneynessForward::strikeFromMoneyness(Time t, Real moneyness,\n                                                                         const bool stickyReference) const {\n    Real forward;\n    if (stickyReference) {\n        QL_REQUIRE(!stickySpot_.empty(), \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickySpot is empty\");\n        QL_REQUIRE(!stickyDividendTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickyDividendTs is empty\");\n        QL_REQUIRE(!stickyRiskFreeTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickyRiskFreeTs is empty\");\n        forward = stickySpot_->value() * stickyDividendTs_->discount(t) / stickyRiskFreeTs_->discount(t);\n    } else {\n        QL_REQUIRE(!movingSpot_.empty(), \"SpreadedBlackVolatilitySurfaceMoneynessForward: movingSpot is empty\");\n        QL_REQUIRE(!movingDividendTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessForward: movingDividendTs is empty\");\n        QL_REQUIRE(!movingRiskFreeTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessForward: mocingRiskFreeTs is empty\");\n        forward = movingSpot_->value() * movingDividendTs_->discount(t) / movingRiskFreeTs_->discount(t);\n    }\n    return moneyness * forward;\n}\n\nReal SpreadedBlackVolatilitySurfaceLogMoneynessForward::moneynessFromStrike(Time t, Real strike,\n                                                                            const bool stickyReference) const {\n    if (strike == Null<Real>() || close_enough(strike, 0.0))\n        return 0.0;\n    else {\n        Real forward;\n        if (stickyReference) {\n            QL_REQUIRE(!stickySpot_.empty(), \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: stickySpot is empty\");\n            QL_REQUIRE(!stickyDividendTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: stickyDividendTs is empty\");\n            QL_REQUIRE(!stickyRiskFreeTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: stickyRiskFreeTs is empty\");\n            forward = stickySpot_->value() * stickyDividendTs_->discount(t) / stickyRiskFreeTs_->discount(t);\n        } else {\n            QL_REQUIRE(!movingSpot_.empty(), \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: movingSpot is empty\");\n            QL_REQUIRE(!movingDividendTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: movingDividendTs is empty\");\n            QL_REQUIRE(!movingRiskFreeTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: mocingRiskFreeTs is empty\");\n            forward = movingSpot_->value() * movingDividendTs_->discount(t) / movingRiskFreeTs_->discount(t);\n        }\n        return std::log(strike / forward);\n    }\n}\n\nReal SpreadedBlackVolatilitySurfaceLogMoneynessForward::strikeFromMoneyness(Time t, Real moneyness,\n                                                                            const bool stickyReference) const {\n    Real forward;\n    if (stickyReference) {\n        QL_REQUIRE(!stickySpot_.empty(), \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: stickySpot is empty\");\n        QL_REQUIRE(!stickyDividendTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: stickyDividendTs is empty\");\n        QL_REQUIRE(!stickyRiskFreeTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: stickyRiskFreeTs is empty\");\n        forward = stickySpot_->value() * stickyDividendTs_->discount(t) / stickyRiskFreeTs_->discount(t);\n    } else {\n        QL_REQUIRE(!movingSpot_.empty(), \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: movingSpot is empty\");\n        QL_REQUIRE(!movingDividendTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: movingDividendTs is empty\");\n        QL_REQUIRE(!movingRiskFreeTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceLogMoneynessForward: mocingRiskFreeTs is empty\");\n        forward = movingSpot_->value() * movingDividendTs_->discount(t) / movingRiskFreeTs_->discount(t);\n    }\n    return std::exp(moneyness) * forward;\n}\n\nReal SpreadedBlackVolatilitySurfaceStdDevs::moneynessFromStrike(Time t, Real strike, const bool stickyReference) const {\n    if (strike == Null<Real>() || close_enough(strike, 0.0) || close_enough(t, 0.0))\n        return 0.0;\n    else {\n        QL_REQUIRE(!stickySpot_.empty(), \"SpreadedBlackVolatilitySurfaceStdDevs: stickySpot is empty\");\n        QL_REQUIRE(!stickyDividendTs_.empty(), \"SpreadedBlackVolatilitySurfaceStdDevs: stickyDividendTs is empty\");\n        QL_REQUIRE(!stickyRiskFreeTs_.empty(), \"SpreadedBlackVolatilitySurfaceStdDevs: stickyRiskFreeTs is empty\");\n        Real stickyForward = stickySpot_->value() * stickyDividendTs_->discount(t) / stickyRiskFreeTs_->discount(t);\n        Real forward;\n        if (stickyReference) {\n            forward = stickyForward;\n        } else {\n            QL_REQUIRE(!movingSpot_.empty(), \"SpreadedBlackVolatilitySurfaceStdDevs: movingSpot is empty\");\n            QL_REQUIRE(!movingDividendTs_.empty(), \"SpreadedBlackVolatilitySurfaceStdDevs: movingDividendTs is empty\");\n            QL_REQUIRE(!movingRiskFreeTs_.empty(), \"SpreadedBlackVolatilitySurfaceStdDevs: mocingRiskFreeTs is empty\");\n            forward = movingSpot_->value() * movingDividendTs_->discount(t) / movingRiskFreeTs_->discount(t);\n        }\n        // We use the sticky forward to read the vol for the definition of the standardised moneyness to\n        // avoid that this changes under forward curve changes. In the end this is a matter of definition and\n        // we might want to revise this later.\n        Real vol = referenceVol_->blackVol(t, stickyForward);\n        return std::log(strike / forward) / (vol * std::sqrt(t));\n    }\n}\n\nReal SpreadedBlackVolatilitySurfaceStdDevs::strikeFromMoneyness(Time t, Real moneyness,\n                                                                const bool stickyReference) const {\n    Real stickyForward = stickySpot_->value() * stickyDividendTs_->discount(t) / stickyRiskFreeTs_->discount(t);\n    Real forward;\n    if (stickyReference) {\n        forward = stickyForward;\n    } else {\n        QL_REQUIRE(!movingSpot_.empty(), \"SpreadedBlackVolatilitySurfaceStdDevs: movingSpot is empty\");\n        QL_REQUIRE(!movingDividendTs_.empty(), \"SpreadedBlackVolatilitySurfaceStdDevs: movingDividendTs is empty\");\n        QL_REQUIRE(!movingRiskFreeTs_.empty(), \"SpreadedBlackVolatilitySurfaceStdDevs: mocingRiskFreeTs is empty\");\n        forward = movingSpot_->value() * movingDividendTs_->discount(t) / movingRiskFreeTs_->discount(t);\n    }\n    // We use the sticky forward to read the vol for the definition of the standardised moneyness to\n    // avoid that this changes under forward curve changes. In the end this is a matter of definition and\n    // we might want to revise this later.\n    Real vol = referenceVol_->blackVol(t, stickyForward);\n    return std::exp(moneyness * vol * std::sqrt(t)) * forward;\n}\n\nReal SpreadedBlackVolatilitySurfaceMoneynessSpotAbsolute::moneynessFromStrike(Time t, Real strike,\n                                                                              const bool stickyReference) const {\n    if (strike == Null<Real>() || close_enough(strike, 0.0)) {\n        return 0.0;\n    } else {\n        QL_REQUIRE(!stickyReference || !stickySpot_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessSpot: stickySpot is empty\");\n        QL_REQUIRE(stickyReference || !movingSpot_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessSpot: movingSpot is empty\");\n        return strike - (stickyReference ? stickySpot_->value() : movingSpot_->value());\n    }\n}\n\nReal SpreadedBlackVolatilitySurfaceMoneynessSpotAbsolute::strikeFromMoneyness(Time t, Real moneyness,\n                                                                              const bool stickyReference) const {\n    QL_REQUIRE(!stickyReference || !stickySpot_.empty(),\n               \"SpreadedBlackVolatilitySurfaceMoneynessSpot: stickySpot is empty\");\n    QL_REQUIRE(stickyReference || !movingSpot_.empty(),\n               \"SpreadedBlackVolatilitySurfaceMoneynessSpot: movingSpot is empty\");\n    return moneyness + (stickyReference ? stickySpot_->value() : movingSpot_->value());\n}\n\nReal SpreadedBlackVolatilitySurfaceMoneynessForwardAbsolute::moneynessFromStrike(Time t, Real strike,\n                                                                                 const bool stickyReference) const {\n    if (strike == Null<Real>() || close_enough(strike, 0.0))\n        return 0.0;\n    else {\n        Real forward;\n        if (stickyReference) {\n            QL_REQUIRE(!stickySpot_.empty(), \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickySpot is empty\");\n            QL_REQUIRE(!stickyDividendTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickyDividendTs is empty\");\n            QL_REQUIRE(!stickyRiskFreeTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickyRiskFreeTs is empty\");\n            forward = stickySpot_->value() * stickyDividendTs_->discount(t) / stickyRiskFreeTs_->discount(t);\n        } else {\n            QL_REQUIRE(!movingSpot_.empty(), \"SpreadedBlackVolatilitySurfaceMoneynessForward: movingSpot is empty\");\n            QL_REQUIRE(!movingDividendTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceMoneynessForward: movingDividendTs is empty\");\n            QL_REQUIRE(!movingRiskFreeTs_.empty(),\n                       \"SpreadedBlackVolatilitySurfaceMoneynessForward: mocingRiskFreeTs is empty\");\n            forward = movingSpot_->value() * movingDividendTs_->discount(t) / movingRiskFreeTs_->discount(t);\n        }\n        return strike - forward;\n    }\n}\n\nReal SpreadedBlackVolatilitySurfaceMoneynessForwardAbsolute::strikeFromMoneyness(Time t, Real moneyness,\n                                                                                 const bool stickyReference) const {\n    Real forward;\n    if (stickyReference) {\n        QL_REQUIRE(!stickySpot_.empty(), \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickySpot is empty\");\n        QL_REQUIRE(!stickyDividendTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickyDividendTs is empty\");\n        QL_REQUIRE(!stickyRiskFreeTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessForward: stickyRiskFreeTs is empty\");\n        forward = stickySpot_->value() * stickyDividendTs_->discount(t) / stickyRiskFreeTs_->discount(t);\n    } else {\n        QL_REQUIRE(!movingSpot_.empty(), \"SpreadedBlackVolatilitySurfaceMoneynessForward: movingSpot is empty\");\n        QL_REQUIRE(!movingDividendTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessForward: movingDividendTs is empty\");\n        QL_REQUIRE(!movingRiskFreeTs_.empty(),\n                   \"SpreadedBlackVolatilitySurfaceMoneynessForward: mocingRiskFreeTs is empty\");\n        forward = movingSpot_->value() * movingDividendTs_->discount(t) / movingRiskFreeTs_->discount(t);\n    }\n    return moneyness + forward;\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "b1cbb2ef599fa9b3599f42d946bc032c23d818b9", "size": 21925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/spreadedblackvolatilitysurfacemoneyness.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/termstructures/spreadedblackvolatilitysurfacemoneyness.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/termstructures/spreadedblackvolatilitysurfacemoneyness.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 55.3661616162, "max_line_length": 120, "alphanum_fraction": 0.6724743444, "num_tokens": 5164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.23859554393525106}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Boost.SpatialIndex - rtree implementation\n//\n// Copyright 2008 Federico J. Fernandez.\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_INDEX_RTREE_RTREE_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_INDEX_RTREE_RTREE_HPP\n\n#include <cstddef>\n#include <iostream> // TODO: Remove if print() is removed\n#include <stdexcept>\n#include <utility>\n#include <vector>\n\n#include <boost/concept_check.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <boost/geometry/algorithms/area.hpp>\n\n#include <boost/geometry/extensions/index/rtree/rtree_node.hpp>\n#include <boost/geometry/extensions/index/rtree/rtree_leaf.hpp>\n\nnamespace boost { namespace geometry { namespace index\n{\n\ntemplate <typename Box, typename Value >\nclass rtree\n{\npublic:\n\n    typedef boost::shared_ptr<rtree_node<Box, Value> > node_pointer;\n    typedef boost::shared_ptr<rtree_leaf<Box, Value> > leaf_pointer;\n\n    /**\n     * \\brief Creates a rtree with 'maximum' elements per node and 'minimum'.\n     */\n    rtree(unsigned int const& maximum, unsigned int const& minimum)\n        : m_count(0)\n        , m_min_elems_per_node(minimum)\n        , m_max_elems_per_node(maximum)\n        , m_root(new rtree_node<Box, Value>(node_pointer(), 1))\n    {\n    }\n\n    /**\n     * \\brief Creates a rtree with maximum elements per node\n     *        and minimum (box is ignored).\n     */\n    rtree(Box const& box, unsigned int const& maximum, unsigned int const& minimum)\n        : m_count(0)\n        , m_min_elems_per_node(minimum)\n        , m_max_elems_per_node(maximum)\n        , m_root(new rtree_node<Box, Value>(node_pointer(), 1))\n    {\n        boost::ignore_unused_variable_warning(box);\n    }\n\n    /**\n     * \\brief destructor (virtual because we have virtual functions)\n     */\n    virtual ~rtree() {}\n\n\n    /**\n     * \\brief Remove elements inside the 'box'\n     */\n    inline void remove(Box const& box)\n    {\n        try\n        {\n            node_pointer leaf(choose_exact_leaf(box));\n            typename rtree_leaf<Box, Value>::leaf_map q_leaves;\n\n            leaf->remove(box);\n\n            if (leaf->elements() < m_min_elems_per_node && elements() > m_min_elems_per_node)\n            {\n                q_leaves = leaf->get_leaves();\n\n                // we remove the leaf_node in the parent node because now it's empty\n                leaf->get_parent()->remove(leaf->get_parent()->get_box(leaf));\n            }\n\n            typename rtree_node<Box, Value>::node_map q_nodes;\n            condense_tree(leaf, q_nodes);\n\n            std::vector<std::pair<Box, Value> > s;\n            for (typename rtree_node<Box, Value>::node_map::const_iterator it = q_nodes.begin();\n                 it != q_nodes.end(); ++it)\n            {\n                typename rtree_leaf<Box, Value>::leaf_map leaves = it->second->get_leaves();\n\n                // reinserting leaves from nodes\n                for (typename rtree_leaf<Box, Value>::leaf_map::const_iterator itl = leaves.begin();\n                     itl != leaves.end(); ++itl)\n                {\n                    s.push_back(*itl);\n                }\n            }\n\n            for (typename std::vector<std::pair<Box, Value> >::const_iterator it = s.begin(); it != s.end(); ++it)\n            {\n                m_count--;\n                insert(it->first, it->second);\n            }\n\n            // if the root has only one child and the child is not a leaf,\n            // make it the root\n            if (m_root->elements() == 1)\n            {\n                if (!m_root->first_element()->is_leaf())\n                {\n                    m_root = m_root->first_element();\n                }\n            }\n            // reinserting leaves\n            for (typename rtree_leaf<Box, Value>::leaf_map::const_iterator it = q_leaves.begin();\n                 it != q_leaves.end(); ++it)\n            {\n                m_count--;\n                insert(it->first, it->second);\n            }\n\n            m_count--;\n        }\n        catch(std::logic_error & e)\n        {\n            // TODO: mloskot - replace with Boost.Geometry exception\n\n            // not found\n            std::cerr << e.what() << std::endl;\n            return;\n        }\n    }\n\n    /**\n     * \\brief Remove element inside the box with value\n     */\n    void remove(Box const& box, Value const& value)\n    {\n        try\n        {\n            node_pointer leaf;\n\n            // find possible leaves\n            typedef typename std::vector<node_pointer > node_type;\n            node_type nodes;\n            m_root->find_leaves(box, nodes);\n\n            // refine the result\n            for (typename node_type::const_iterator it = nodes.begin(); it != nodes.end(); ++it)\n            {\n                leaf = *it;\n                try\n                {\n                    leaf->remove(value);\n                    break;\n                } catch (...)\n                {\n                    leaf = node_pointer();\n                }\n            }\n\n            if (!leaf)\n                return;\n\n            typename rtree_leaf < Box, Value >::leaf_map q_leaves;\n\n            if (leaf->elements() < m_min_elems_per_node && elements() > m_min_elems_per_node)\n            {\n                q_leaves = leaf->get_leaves();\n\n                // we remove the leaf_node in the parent node because now it's empty\n                leaf->get_parent()->remove(leaf->get_parent()->get_box(leaf));\n            }\n\n            typename rtree_node<Box, Value>::node_map q_nodes;\n            condense_tree(leaf, q_nodes);\n\n            std::vector<std::pair<Box, Value> > s;\n            for (typename rtree_node<Box, Value>::node_map::const_iterator it = q_nodes.begin();\n                 it != q_nodes.end(); ++it)\n            {\n                typename rtree_leaf<Box, Value>::leaf_map leaves = it->second->get_leaves();\n\n                // reinserting leaves from nodes\n                for (typename rtree_leaf<Box, Value>::leaf_map::const_iterator itl = leaves.begin();\n                     itl != leaves.end(); ++itl)\n                {\n                    s.push_back(*itl);\n                }\n            }\n\n            for (typename std::vector<std::pair<Box, Value> >::const_iterator it = s.begin(); it != s.end(); ++it)\n            {\n                m_count--;\n                insert(it->first, it->second);\n            }\n\n            // if the root has only one child and the child is not a leaf,\n            // make it the root\n            if (m_root->elements() == 1)\n            {\n                if (!m_root->first_element()->is_leaf())\n                {\n                    m_root = m_root->first_element();\n                }\n            }\n\n            // reinserting leaves\n            for (typename rtree_leaf<Box, Value>::leaf_map::const_iterator it = q_leaves.begin();\n                 it != q_leaves.end(); ++it)\n            {\n                m_count--;\n                insert(it->first, it->second);\n            }\n\n            m_count--;\n\n        }\n        catch(std::logic_error & e)\n        {\n            // TODO: mloskot - ggl exception\n\n            // not found\n            std::cerr << e.what() << std::endl;\n            return;\n        }\n    }\n\n    /**\n     * \\brief Returns the number of elements.\n     */\n    inline unsigned int elements() const\n    {\n        return m_count;\n    }\n\n\n    /**\n     * \\brief Inserts an element with 'box' as key with value.\n     */\n    inline void insert(Box const& box, Value const& value)\n    {\n        m_count++;\n\n        node_pointer leaf(choose_corresponding_leaf(box));\n\n        // check if the selected leaf is full to do the split if necessary\n        if (leaf->elements() >= m_max_elems_per_node)\n        {\n            leaf->insert(box, value);\n\n            // split!\n            node_pointer n1(new rtree_leaf<Box, Value>(leaf->get_parent()));\n            node_pointer n2(new rtree_leaf<Box, Value>(leaf->get_parent()));\n\n            split_node(leaf, n1, n2);\n            adjust_tree(leaf, n1, n2);\n        }\n        else\n        {\n            leaf->insert(box, value);\n            adjust_tree(leaf);\n        }\n    }\n\n\n    /**\n     * \\brief Returns all the values inside 'box'\n     */\n    inline std::deque<Value> find(Box const& box) const\n    {\n        std::deque<Value> result;\n        m_root->find(box, result, false);\n        return result;\n    }\n\n    /**\n     * \\brief Print Rtree (mainly for debug)\n     */\n    inline void print()\n    {\n        std::cerr << \"===================================\" << std::endl;\n        std::cerr << \" Min/Max: \" << m_min_elems_per_node << \" / \" << m_max_elems_per_node << std::endl;\n        std::cerr << \"Leaves: \" << m_root->get_leaves().size() << std::endl;\n        m_root->print();\n        std::cerr << \"===================================\" << std::endl;\n    }\n\nprivate:\n\n    /// number of elements\n    unsigned int m_count;\n\n    /// minimum number of elements per node\n    unsigned int m_min_elems_per_node;\n\n    /// maximum number of elements per node\n    unsigned int m_max_elems_per_node;\n\n    /// tree root\n    node_pointer m_root;\n\n    /**\n     * \\brief Reorganize the tree after a removal. It tries to\n     *        join nodes with less elements than m.\n     */\n    void condense_tree(node_pointer const& leaf,\n        typename rtree_node<Box, Value>::node_map& q_nodes)\n    {\n        if (leaf.get() == m_root.get())\n        {\n            // if it's the root we are done\n            return;\n        }\n\n        node_pointer parent = leaf->get_parent();\n        parent->adjust_box(leaf);\n\n        if (parent->elements() < m_min_elems_per_node)\n        {\n            if (parent.get() == m_root.get())\n            {\n                // if the parent is underfull and it's the root we just exit\n                return;\n            }\n\n            // get the nodes that we should reinsert\n            typename rtree_node<Box, Value>::node_map this_nodes = parent->get_nodes();\n            for(typename rtree_node<Box, Value>::node_map::const_iterator it = this_nodes.begin();\n                it != this_nodes.end(); ++it)\n            {\n                q_nodes.push_back(*it);\n            }\n\n            // we remove the node in the parent node because now it should be\n            // re inserted\n            parent->get_parent()->remove(parent->get_parent()->get_box(parent));\n        }\n\n        condense_tree(parent, q_nodes);\n    }\n\n    /**\n     * \\brief After an insertion splits nodes with more than 'maximum' elements.\n     */\n    inline void adjust_tree(node_pointer& node)\n    {\n        if (node.get() == m_root.get())\n        {\n            // we finished the adjust\n            return;\n        }\n\n        // as there are no splits just adjust the box of the parent and go on\n        node_pointer parent = node->get_parent();\n        parent->adjust_box(node);\n        adjust_tree(parent);\n    }\n\n    /**\n     * \\brief After an insertion splits nodes with more than maximum elements\n     *        (recursive step with subtrees 'n1' and 'n2' to be joined).\n     */\n    void adjust_tree(node_pointer& leaf, node_pointer& n1, node_pointer& n2)\n    {\n        // check if we are in the root and do the split\n        if (leaf.get() == m_root.get())\n        {\n            node_pointer new_root(new rtree_node<Box,Value>(node_pointer (), leaf->get_level() + 1));\n            new_root->add_node(n1->compute_box(), n1);\n            new_root->add_node(n2->compute_box(), n2);\n\n            n1->set_parent(new_root);\n            n2->set_parent(new_root);\n\n            n1->update_parent(n1);\n            n2->update_parent(n2);\n\n            m_root = new_root;\n            return;\n        }\n\n        node_pointer parent = leaf->get_parent();\n\n        parent->replace_node(leaf, n1);\n        parent->add_node(n2->compute_box(), n2);\n\n        // if parent is full, split and readjust\n        if (parent->elements() > m_max_elems_per_node)\n        {\n            node_pointer p1(new rtree_node<Box, Value>(parent->get_parent(), parent->get_level()));\n            node_pointer p2(new rtree_node<Box, Value>(parent->get_parent(), parent->get_level()));\n\n            split_node(parent, p1, p2);\n            adjust_tree(parent, p1, p2);\n        }\n        else\n        {\n            adjust_tree(parent);\n        }\n    }\n\n    /**\n     * \\brief Splits 'n' in 'n1' and 'n2'\n     */\n    void split_node(node_pointer const& n, node_pointer& n1, node_pointer& n2) const\n    {\n        unsigned int seed1 = 0;\n        unsigned int seed2 = 0;\n        std::vector<Box> boxes = n->get_boxes();\n\n        n1->set_parent(n->get_parent());\n        n2->set_parent(n->get_parent());\n\n        linear_pick_seeds(n, seed1, seed2);\n\n        if (n->is_leaf())\n        {\n            n1->add_value(boxes[seed1], n->get_value(seed1));\n            n2->add_value(boxes[seed2], n->get_value(seed2));\n        }\n        else\n        {\n            n1->add_node(boxes[seed1], n->get_node(seed1));\n            n2->add_node(boxes[seed2], n->get_node(seed2));\n        }\n\n        unsigned int index = 0;\n\n        if (n->is_leaf())\n        {\n            // TODO: mloskot - add BOOST_GEOMETRY_ASSERT(node.size() >= 2); or similar\n\n            typename rtree_leaf<Box, Value>::leaf_map nodes = n->get_leaves();\n            unsigned int remaining = nodes.size() - 2;\n\n            for (typename rtree_leaf<Box, Value>::leaf_map::const_iterator it = nodes.begin();\n                 it != nodes.end(); ++it, index++)\n            {\n                if (index != seed1 && index != seed2)\n                {\n                    if (n1->elements() + remaining == m_min_elems_per_node)\n                    {\n                        n1->add_value(it->first, it->second);\n                        continue;\n                    }\n                    if (n2->elements() + remaining == m_min_elems_per_node)\n                    {\n                        n2->add_value(it->first, it->second);\n                        continue;\n                    }\n\n                    remaining--;\n\n                    /// current boxes of each group\n                    Box b1, b2;\n\n                    /// enlarged boxes of each group\n                    Box eb1, eb2;\n                    b1 = n1->compute_box();\n                    b2 = n2->compute_box();\n\n                    /// areas\n                    typedef typename coordinate_type<Box>::type coordinate_type;\n                    coordinate_type b1_area, b2_area;\n                    coordinate_type eb1_area, eb2_area;\n                    b1_area = geometry::area(b1);\n                    b2_area = geometry::area(b2);\n                    eb1_area = compute_union_area(b1, it->first);\n                    eb2_area = compute_union_area(b2, it->first);\n\n                    if (eb1_area - b1_area > eb2_area - b2_area)\n                    {\n                        n2->add_value(it->first, it->second);\n                    }\n                    if (eb1_area - b1_area < eb2_area - b2_area)\n                    {\n                        n1->add_value(it->first, it->second);\n                    }\n                    if (eb1_area - b1_area == eb2_area - b2_area)\n                    {\n                        if (b1_area < b2_area)\n                        {\n                            n1->add_value(it->first, it->second);\n                        }\n                        if (b1_area > b2_area)\n                        {\n                            n2->add_value(it->first, it->second);\n                        }\n                        if (b1_area == b2_area)\n                        {\n                            if (n1->elements() > n2->elements())\n                            {\n                                n2->add_value(it->first, it->second);\n                            }\n                            else\n                            {\n                                n1->add_value(it->first, it->second);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        else\n        {\n            // TODO: mloskot - add BOOST_GEOMETRY_ASSERT(node.size() >= 2); or similar\n\n            typename rtree_node<Box, Value>::node_map nodes = n->get_nodes();\n            unsigned int remaining = nodes.size() - 2;\n            for(typename rtree_node<Box, Value>::node_map::const_iterator it = nodes.begin();\n                it != nodes.end(); ++it, index++)\n            {\n\n                if (index != seed1 && index != seed2)\n                {\n\n                    if (n1->elements() + remaining == m_min_elems_per_node)\n                    {\n                        n1->add_node(it->first, it->second);\n                        continue;\n                    }\n                    if (n2->elements() + remaining == m_min_elems_per_node)\n                    {\n                        n2->add_node(it->first, it->second);\n                        continue;\n                    }\n\n                    remaining--;\n\n                    /// current boxes of each group\n                    Box b1, b2;\n\n                    /// enlarged boxes of each group\n                    Box eb1, eb2;\n                    b1 = n1->compute_box();\n                    b2 = n2->compute_box();\n\n                    /// areas\n                    typedef typename coordinate_type<Box>::type coordinate_type;\n                    coordinate_type b1_area, b2_area;\n                    coordinate_type eb1_area, eb2_area;\n                    b1_area = geometry::area(b1);\n                    b2_area = geometry::area(b2);\n\n                    eb1_area = compute_union_area(b1, it->first);\n                    eb2_area = compute_union_area(b2, it->first);\n\n                    if (eb1_area - b1_area > eb2_area - b2_area)\n                    {\n                        n2->add_node(it->first, it->second);\n                    }\n                    if (eb1_area - b1_area < eb2_area - b2_area)\n                    {\n                        n1->add_node(it->first, it->second);\n                    }\n                    if (eb1_area - b1_area == eb2_area - b2_area)\n                    {\n                        if (b1_area < b2_area)\n                        {\n                            n1->add_node(it->first, it->second);\n                        }\n                        if (b1_area > b2_area)\n                        {\n                            n2->add_node(it->first, it->second);\n                        }\n                        if (b1_area == b2_area)\n                        {\n                            if (n1->elements() > n2->elements())\n                            {\n                                n2->add_node(it->first, it->second);\n                            }\n                            else\n                            {\n                                n1->add_node(it->first, it->second);\n                            }\n                        }\n                    }\n\n                }\n            }\n        }\n    }\n\n    /**\n     * \\brief Choose initial values for the split algorithm (linear version)\n     */\n    void linear_pick_seeds(node_pointer const& n, unsigned int &seed1, unsigned int &seed2) const\n    {\n        // get boxes from the node\n        std::vector<Box>boxes = n->get_boxes();\n        if (boxes.size() == 0)\n        {\n            // TODO: mloskot - throw ggl exception\n            throw std::logic_error(\"Empty Node trying to Pick Seeds\");\n        }\n\n        // only two dim for now\n        // unsigned int dimensions =\n        //   geometry::point_traits<Point>::coordinate_count;\n\n        // find the first two elements\n        typedef typename coordinate_type<Box>::type coordinate_type;\n        coordinate_type separation_x, separation_y;\n        unsigned int first_x, second_x;\n        unsigned int first_y, second_y;\n        find_normalized_separations<0u>(boxes, separation_x, first_x, second_x);\n        find_normalized_separations<1u>(boxes, separation_y, first_y, second_y);\n\n        if (separation_x > separation_y)\n        {\n            seed1 = first_x;\n            seed2 = second_x;\n        }\n        else\n        {\n            seed1 = first_y;\n            seed2 = second_y;\n        }\n    }\n\n    /**\n     * \\brief Find distances between possible initial values for the\n     *        pick_seeds algorithm.\n     */\n    template <std::size_t D, typename T>\n    void find_normalized_separations(std::vector<Box> const& boxes, T& separation,\n        unsigned int& first, unsigned int& second) const\n    {\n        if (boxes.size() < 2)\n        {\n            throw std::logic_error(\"At least two boxes needed to split\");\n        }\n\n        // find the lowest high\n        typename std::vector<Box>::const_iterator it = boxes.begin();\n        typedef typename coordinate_type<Box>::type coordinate_type;\n        coordinate_type lowest_high = geometry::get<max_corner, D>(*it);\n        unsigned int lowest_high_index = 0;\n        unsigned int index = 1;\n        ++it;\n        for(; it != boxes.end(); ++it)\n        {\n            if (geometry::get<max_corner, D>(*it) < lowest_high)\n            {\n                lowest_high = geometry::get<max_corner, D>(*it);\n                lowest_high_index = index;\n            }\n            index++;\n        }\n\n        // find the highest low\n        coordinate_type highest_low = 0;\n        unsigned int highest_low_index = 0;\n        if (lowest_high_index == 0)\n        {\n            highest_low = geometry::get<min_corner, D>(boxes[1]);\n            highest_low_index = 1;\n        }\n        else\n        {\n            highest_low = geometry::get<min_corner, D>(boxes[0]);\n            highest_low_index = 0;\n        }\n\n        index = 0;\n        for (typename std::vector<Box>::const_iterator it = boxes.begin();\n             it != boxes.end(); ++it, index++)\n        {\n            if (geometry::get<min_corner, D>(*it) >= highest_low && index != lowest_high_index)\n            {\n                highest_low = geometry::get<min_corner, D>(*it);\n                highest_low_index = index;\n            }\n        }\n\n        // find the lowest low\n        it = boxes.begin();\n        coordinate_type lowest_low = geometry::get<min_corner, D>(*it);\n        ++it;\n        for(; it != boxes.end(); ++it)\n        {\n            if (geometry::get<min_corner, D>(*it) < lowest_low)\n            {\n                lowest_low = geometry::get<min_corner, D>(*it);\n            }\n        }\n\n        // find the highest high\n        it = boxes.begin();\n        coordinate_type highest_high = geometry::get<max_corner, D>(*it);\n        ++it;\n        for(; it != boxes.end(); ++it)\n        {\n            if (geometry::get<max_corner, D>(*it) > highest_high)\n            {\n                highest_high = geometry::get<max_corner, D>(*it);\n            }\n        }\n\n        coordinate_type const width = highest_high - lowest_low;\n\n        separation = (highest_low - lowest_high) / width;\n        first = highest_low_index;\n        second = lowest_high_index;\n    }\n\n    /**\n     * \\brief Choose one of the possible leaves to make an insertion\n     */\n    inline node_pointer choose_corresponding_leaf(Box const& e)\n    {\n        node_pointer node = m_root;\n\n        // if the tree is empty add an initial leaf\n        if (m_root->elements() == 0)\n        {\n            leaf_pointer new_leaf(new rtree_leaf<Box, Value>(m_root));\n            m_root->add_leaf_node(Box (), new_leaf);\n\n            return new_leaf;\n        }\n\n        while (!node->is_leaf())\n        {\n            /// traverse node's map to see which node we should select\n            node = node->choose_node(e);\n        }\n        return node;\n    }\n\n    /**\n     * \\brief Choose the exact leaf where an insertion should be done\n     */\n    node_pointer choose_exact_leaf(Box const&e) const\n    {\n        // find possible leaves\n        typedef typename std::vector<node_pointer> node_type;\n        node_type nodes;\n        m_root->find_leaves(e, nodes);\n\n        // refine the result\n        for (typename node_type::const_iterator it = nodes.begin(); it != nodes.end(); ++it)\n        {\n            typedef std::vector<std::pair<Box, Value> > leaves_type;\n            leaves_type leaves = (*it)->get_leaves();\n\n            for (typename leaves_type::const_iterator itl = leaves.begin();\n                 itl != leaves.end(); ++itl)\n            {\n\n                if (itl->first.max_corner() == e.max_corner()\n                    && itl->first.min_corner() == e.min_corner())\n                {\n                    return *it;\n                }\n            }\n        }\n\n        // TODO: mloskot - ggl exception\n        throw std::logic_error(\"Leaf not found\");\n    }\n};\n\n}}} // namespace boost::geometry::index\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_INDEX_RTREE_RTREE_HPP\n\n", "meta": {"hexsha": "a9e9ac6c82e5d17f69d7d425b80d9a3034494fe5", "size": 24776, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/index/rtree/rtree.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T05:02:05.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/extensions/index/rtree/rtree.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3party/boost/boost/geometry/extensions/index/rtree/rtree.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-04T10:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T18:52:06.000Z", "avg_line_length": 31.9690322581, "max_line_length": 114, "alphanum_fraction": 0.4908782693, "num_tokens": 5409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.23859554393525104}}
{"text": "//=============================================================================================================\n/**\n * @file     warp.cpp\n * @author   Lorenz Esch <lesch@mgh.harvard.edu>\n * @version  dev\n * @date     November, 2015\n *\n * @section  LICENSE\n *\n * Copyright (C) 2015, Lorenz Esch. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n *       following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n *       the following disclaimer in the documentation and/or other materials provided with the distribution.\n *     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n *       to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, 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 INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief   Warp class definition.\n */\n\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"warp.h\"\n\n#include <iostream>\n\n//=============================================================================================================\n// EIGEN INCLUDES\n//=============================================================================================================\n\n#include <Eigen/LU>\n\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n#include <QDebug>\n#include <QFile>\n#include <QList>\n\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace UTILSLIB;\nusing namespace Eigen;\n\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nMatrixXf Warp::calculate(const MatrixXf &sLm, const MatrixXf &dLm, const MatrixXf &sVert)\n{\n    MatrixXf warpWeight, polWeight;\n    calcWeighting(sLm, dLm, warpWeight, polWeight);\n    MatrixXf wVert = warpVertices(sVert, sLm, warpWeight, polWeight);\n    return wVert;\n}\n\n//=============================================================================================================\n\nvoid Warp::calculate(const MatrixXf & sLm, const MatrixXf &dLm, QList<MatrixXf> & vertList)\n{\n    MatrixXf warpWeight, polWeight;\n    calcWeighting(sLm, dLm, warpWeight, polWeight);\n\n    for (int i=0; i<vertList.size(); i++)\n    {\n        vertList.replace(i,warpVertices(vertList.at(i), sLm, warpWeight, polWeight));\n    }\n    return;\n}\n\n//=============================================================================================================\n\nbool Warp::calcWeighting(const MatrixXf &sLm, const MatrixXf &dLm, MatrixXf& warpWeight, MatrixXf& polWeight)\n{\n    MatrixXf K = MatrixXf::Zero(sLm.rows(),sLm.rows());     //K(i,j)=||sLm(i)-sLm(j)||\n    for (int i=0; i<sLm.rows(); i++)\n        K.col(i)=((sLm.rowwise()-sLm.row(i)).rowwise().norm());\n\n//    std::cout << \"Here is the matrix K:\" << std::endl << K << std::endl;\n\n    MatrixXf P (sLm.rows(),4);                              //P=[ones,sLm]\n    P << MatrixXf::Ones(sLm.rows(),1),sLm;\n//    std::cout << \"Here is the matrix P:\" << std::endl << P << std::endl;\n\n    MatrixXf L ((sLm.rows()+4),(sLm.rows()+4));             //L=Full Matrix of the linear eq.\n    L <<    K,P,\n            P.transpose(),MatrixXf::Zero(4,4);\n//    std::cout << \"Here is the matrix L:\" << std::endl << L << std::endl;\n\n    MatrixXf Y ((dLm.rows()+4),3);                          //Y=[dLm,Zero]\n    Y <<    dLm,\n            MatrixXf::Zero(4,3);\n//    std::cout << \"Here is the matrix Y:\" << std::endl << Y << std::endl;\n\n    //\n    // calculate the weighting matrix (Y=L*W)\n    //\n    MatrixXf W ((dLm.rows()+4),3);                          //W=[warpWeight,polWeight]\n    Eigen::FullPivLU <MatrixXf> Lu(L);                      //LU decomposition is one method to solve lin. eq.\n    W=Lu.solve(Y);\n//    std::cout << \"Here is the matrix W:\" << std::endl << W << std::endl;\n\n    warpWeight = W.topRows(sLm.rows());\n    polWeight = W.bottomRows(4);\n\n    return true;\n}\n\n//=============================================================================================================\n\nMatrixXf Warp::warpVertices(const MatrixXf &sVert, const MatrixXf & sLm, const MatrixXf& warpWeight, const MatrixXf& polWeight)\n{\n    MatrixXf wVert = sVert * polWeight.bottomRows(3);         //Pol. Warp\n    wVert.rowwise() += polWeight.row(0);                      //Translation\n\n    //\n    // TPS Warp\n    //\n    MatrixXf K = MatrixXf::Zero(sVert.rows(),sLm.rows());     //K(i,j)=||sLm(i)-sLm(j)||\n    for (int i=0; i<sVert.rows(); i++)\n        K.row(i)=((sLm.rowwise()-sVert.row(i)).rowwise().norm().transpose());\n//    std::cout << \"Here is the matrix K:\" << std::endl << K << std::endl;\n\n    wVert += K*warpWeight;\n//    std::cout << \"Here is the matrix wVert:\" << std::endl << wVert << std::endl;\n    return wVert;\n}\n\n//=============================================================================================================\n\nMatrixXf Warp::readsLm(const QString &electrodeFileName)\n{\n    MatrixXf electrodes;\n    QFile file(electrodeFileName);\n\n    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n        qDebug()<<\"Error opening file\";\n//        return false;\n    }\n\n    //Start reading from file\n    double numberElectrodes;\n    QTextStream in(&file);\n    int i=0;\n\n    while(!in.atEnd())\n    {\n        QString line = in.readLine();\n        QStringList fields = line.split(QRegExp(\"\\\\s+\"));\n\n        //Delete last element if it is a blank character\n        if(fields.at(fields.size()-1) == \"\")\n            fields.removeLast();\n\n        //Read number of electrodes\n        if(i == 0){\n            numberElectrodes = fields.at(fields.size()-1).toDouble();\n            electrodes = MatrixXf::Zero(numberElectrodes, 3);\n        }\n        //Read actual electrode positions\n        else{\n            Vector3f x;\n            x << fields.at(fields.size()-3).toFloat(),fields.at(fields.size()-2).toFloat(),fields.at(fields.size()-1).toFloat();\n            electrodes.row(i-1)=x.transpose();\n        }\n        i++;\n    }\n    return electrodes;\n}\n", "meta": {"hexsha": "a99bc7db49ce305b189d89ab34d5a70aa5b0cdd0", "size": 7598, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/utils/warp.cpp", "max_stars_repo_name": "gabrielbmotta/mne-cpp", "max_stars_repo_head_hexsha": "f3e68a4d2e33369dfe637591c055e34000c73a46", "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": "libraries/utils/warp.cpp", "max_issues_repo_name": "gabrielbmotta/mne-cpp", "max_issues_repo_head_hexsha": "f3e68a4d2e33369dfe637591c055e34000c73a46", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/utils/warp.cpp", "max_forks_repo_name": "gabrielbmotta/mne-cpp", "max_forks_repo_head_hexsha": "f3e68a4d2e33369dfe637591c055e34000c73a46", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.414893617, "max_line_length": 128, "alphanum_fraction": 0.4882863912, "num_tokens": 1655, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704502361149, "lm_q2_score": 0.43014734858584297, "lm_q1q2_score": 0.2385039940382634}}
{"text": "/* pcmsolver_copyright_start */\n/*\n *     PCMSolver, an API for the Polarizable Continuum Model\n *     Copyright (C) 2013-2016 Roberto Di Remigio, Luca Frediani and contributors\n *     \n *     This file is part of PCMSolver.\n *     \n *     PCMSolver is free software: you can redistribute it and/or modify\n *     it under the terms of the GNU Lesser General Public License as published by\n *     the Free Software Foundation, either version 3 of the License, or\n *     (at your option) any later version.\n *     \n *     PCMSolver is distributed in the hope that it will be useful,\n *     but WITHOUT ANY WARRANTY; without even the implied warranty of\n *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *     GNU Lesser General Public License for more details.\n *     \n *     You should have received a copy of the GNU Lesser General Public License\n *     along with PCMSolver.  If not, see <http://www.gnu.org/licenses/>.\n *     \n *     For information on the complete list of contributors to the\n *     PCMSolver API, see: <http://pcmsolver.readthedocs.io/>\n */\n/* pcmsolver_copyright_end */\n\n#include \"Molecule.hpp\"\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cmath>\n#include <iomanip>\n\n#include \"Config.hpp\"\n\n#include <boost/format.hpp>\n\n#include <Eigen/Core>\n#include <Eigen/Eigenvalues>\n\n#include \"Atom.hpp\"\n#include \"cavity/Element.hpp\"\n#include \"MathUtils.hpp\"\n#include \"Symmetry.hpp\"\n\nMolecule::Molecule(int nat, const Eigen::VectorXd & chg, const Eigen::VectorXd & m,\n                   const Eigen::Matrix3Xd & geo, const std::vector<Atom> & at,\n                   const std::vector<Sphere> & sph)\n    : nAtoms_(nat), charges_(chg), masses_(m), geometry_(geo), atoms_(at), spheres_(sph)\n{\n    rotor_ = findRotorType();\n    pointGroup_ = buildGroup(0, 0, 0, 0);\n}\n\nMolecule::Molecule(int nat, const Eigen::VectorXd & chg, const Eigen::VectorXd & m,\n                   const Eigen::Matrix3Xd & geo, const std::vector<Atom> & at,\n                   const std::vector<Sphere> & sph,\n                   int nr_gen, int gen[3])\n    : nAtoms_(nat), charges_(chg), masses_(m), geometry_(geo), atoms_(at), spheres_(sph)\n{\n    rotor_ = findRotorType();\n    pointGroup_ = buildGroup(nr_gen, gen[0], gen[1], gen[2]);\n}\n\nMolecule::Molecule(int nat, const Eigen::VectorXd & chg, const Eigen::VectorXd & m,\n                   const Eigen::Matrix3Xd & geo, const std::vector<Atom> & at,\n                   const std::vector<Sphere> & sph,\n                   const Symmetry & pg)\n    : nAtoms_(nat), charges_(chg), masses_(m), geometry_(geo), atoms_(at), spheres_(sph),\n      pointGroup_(pg)\n{\n    rotor_ = findRotorType();\n}\n\nMolecule::Molecule(const std::vector<Sphere> & sph)\n    : nAtoms_(sph.size()), spheres_(sph)\n{\n    charges_ = Eigen::VectorXd::Ones(nAtoms_);\n    masses_.resize(nAtoms_);\n    geometry_.resize(Eigen::NoChange, nAtoms_);\n    for (size_t i = 0; i < nAtoms_; ++i) {\n        masses_(i) = spheres_[i].radius;\n        geometry_.col(i) = spheres_[i].center;\n        double charge = charges_(i);\n        double mass = masses_(i);\n        atoms_.push_back( Atom(\"Dummy\", \"Du\", charge, mass, mass, geometry_.col(i)) );\n    }\n    rotor_ = findRotorType();\n    pointGroup_ = buildGroup(0, 0, 0, 0);\n}\n\nMolecule::Molecule(const Molecule &other)\n{\n    *this = other;\n}\n\nEigen::Vector3d Molecule::centerOfMass()\n{\n    Eigen::Vector3d com;\n    com << 0.0, 0.0, 0.0;\n    for (size_t i = 0; i < nAtoms_; ++i) {\n        com += masses_(i) * atoms_[i].position;\n    }\n    com *= 1.0/masses_.sum();\n    return com;\n}\n\nEigen::Matrix3d Molecule::inertiaTensor()\n{\n    Eigen::Matrix3d inertia = Eigen::Matrix3d::Zero();\n\n    for (size_t i = 0; i < nAtoms_; ++i) {\n        // Diagonal\n        inertia(0,0) += masses_(i) * (geometry_(1,i) * geometry_(1,i) + geometry_(2,\n                                      i) * geometry_(2,i));\n        inertia(1,1) += masses_(i) * (geometry_(0,i) * geometry_(0,i) + geometry_(2,\n                                      i) * geometry_(2,i));\n        inertia(2,2) += masses_(i) * (geometry_(0,i) * geometry_(0,i) + geometry_(1,\n                                      i) * geometry_(1,i));\n\n        // Off-diagonal\n        inertia(0,1) -= masses_(i) * (geometry_(0,i) * geometry_(1,i));\n        inertia(0,2) -= masses_(i) * (geometry_(0,i) * geometry_(2,i));\n        inertia(1,2) -= masses_(i) * (geometry_(1,i) * geometry_(2,i));\n    }\n    // Now symmetrize\n    hermitivitize(inertia);\n\n    // Check elements for a numerical zero and make it a hard zero\n    for (int i = 0; i < 3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            if (fabs(inertia(i,j)) < 1.0e-14) {\n                inertia(i,j) = 0.0;\n            }\n        }\n    }\n\n    return inertia;\n}\n\nrotorType Molecule::findRotorType()\n{\n    rotorType type;\n    if (nAtoms_ == 1) {\n        type = rtAtom;\n    } else {\n        // Get inertia tensor\n        Eigen::Matrix3d inertia = inertiaTensor();\n        // Diagonalize inertia tensor V^t * I * V\n        Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigenSolver(inertia);\n        if (eigenSolver.info() != Eigen::Success) abort();\n        // Determine the degeneracy of the eigenvalues.\n        int deg = 0;\n        double tmp, abs, rel;\n        for (int i = 0; i < 2; ++i) {\n            for (int j = i + 1; j < 3 && deg < 2; ++j) { // Check i and j != i\n                abs = fabs(eigenSolver.eigenvalues()[i] - eigenSolver.eigenvalues()[j]);\n                tmp = eigenSolver.eigenvalues()[j]; // Because the eigenvalues are already in ascending order.\n                if (abs > 1.0e-14) {\n                    rel = abs/tmp;\n                } else {\n                    rel = 0.0;\n                }\n                if (rel < 1.0e-8) {\n                    ++deg;\n                }\n            }\n        }\n        // Get the rotor type based on the degeneracy.\n        if (eigenSolver.eigenvalues()[0] == 0.0) {\n            type = rtLinear;\n        } else if (deg == 2) {\n            type = rtSpherical;\n        } else if (deg == 1) { // We do not distinguish between prolate and oblate.\n            type = rtSymmetric;\n        } else {\n            type = rtAsymmetric;\n        }\n    }\n\n    return type;\n}\n\nvoid Molecule::translate(const Eigen::Vector3d &translationVector)\n{\n    // Translate the geometry_ matrix and update the geometric data in atoms_.\n    for (size_t i = 0; i < nAtoms_; ++i) {\n        geometry_.col(i) -= translationVector;\n        Eigen::Vector3d tmp = geometry_.col(i);\n        atoms_[i].position = tmp;\n    }\n}\n\nvoid Molecule::moveToCOM()\n{\n    Eigen::Vector3d com = centerOfMass();\n    this->translate(com);\n}\n\nvoid Molecule::rotate(const Eigen::Matrix3d &rotationMatrix)\n{\n    // Rotate the geometry_ matrix and update the geometric data in atoms_.\n    geometry_ *=\n        rotationMatrix; // The power of Eigen: geometry_ = geometry_ * rotationMatrix;\n    for (size_t i = 0; i < nAtoms_; ++i) {\n        Eigen::Vector3d tmp = geometry_.col(i);\n        atoms_[i].position = tmp;\n    }\n}\n\nvoid Molecule::moveToPAF()\n{\n    Eigen::Matrix3d inertia = inertiaTensor();\n    // Diagonalize inertia tensor V^t * I * V\n    Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eigenSolver(inertia);\n    if (eigenSolver.info() != Eigen::Success) abort();\n    // Rotate to Principal Axes Frame\n    this->rotate(eigenSolver.eigenvectors());\n    std::cout << eigenSolver.eigenvalues() << std::endl;\n}\n\nMolecule& Molecule::operator=(const Molecule& other)\n{\n    // Self assignment is bad\n    if (this == &other)\n        return *this;\n\n    nAtoms_ = other.nAtoms_;\n    charges_ = other.charges_;\n    masses_ = other.masses_;\n    geometry_ = other.geometry_;\n    atoms_ = other.atoms_;\n    spheres_ = other.spheres_;\n    rotor_ = other.rotor_;\n    pointGroup_ = other.pointGroup_;\n\n    return *this;\n}\n\nstd::ostream & operator<<(std::ostream &os, const Molecule &m)\n{\n    if (m.nAtoms_ != 0) {\n      os << \"                 Geometry (in Angstrom)\" << std::endl;\n      os << \"   Center            X             Y             Z     \\n\";\n      os << \"------------   ------------  ------------  ------------\\n\";\n      for (size_t i = 0; i < m.nAtoms_; ++i) {\n        os << boost::format(\"%|=12s|\") % m.atoms_[i].symbol;\n        os << boost::format(\"   %10.6f  \") % (m.geometry_(0, i) * bohrToAngstrom());\n        os << boost::format(\"  %10.6f  \")  % (m.geometry_(1, i) * bohrToAngstrom());\n        os << boost::format(\"  %10.6f  \")  % (m.geometry_(2, i) * bohrToAngstrom());\n        os << std::endl;\n      }\n      os << \"Rotor type: \" << rotorTypeList[m.rotor_];\n    } else {\n      os << \"  No atoms in this molecule!\" << std::endl;\n    }\n\n    return os;\n\n}\n\nEigen::VectorXd computeMEP(const Molecule & mol, const std::vector<Element> & el)\n{\n    Eigen::VectorXd mep = Eigen::VectorXd::Zero(el.size());\n    for (size_t i = 0; i < mol.nAtoms(); ++i) {\n        for (size_t j = 0; j < el.size(); ++j) {\n            double dist = (mol.geometry().col(i) - el[j].center()).norm();\n            mep(j) += mol.charges(i) / dist;\n        }\n    }\n    return mep;\n}\n\nEigen::VectorXd computeMEP(const std::vector<Element> & el, double charge, const Eigen::Vector3d & origin)\n{\n    Eigen::VectorXd mep = Eigen::VectorXd::Zero(el.size());\n    for (size_t i = 0; i < el.size(); ++i) {\n        double dist = (origin - el[i].center()).norm();\n        mep(i) += charge / dist;\n    }\n    return mep;\n}\n", "meta": {"hexsha": "d64d0dd9b898f6dd553c29c51f7bcd26425960dc", "size": 9385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "external/PCMSolver/PCMSolver-source/src/utils/Molecule.cpp", "max_stars_repo_name": "robertodr/externalize", "max_stars_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-02-15T22:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2017-02-15T22:16:34.000Z", "max_issues_repo_path": "external/PCMSolver/PCMSolver-source/src/utils/Molecule.cpp", "max_issues_repo_name": "robertodr/externalize", "max_issues_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/PCMSolver/PCMSolver-source/src/utils/Molecule.cpp", "max_forks_repo_name": "robertodr/externalize", "max_forks_repo_head_hexsha": "c7b1dda2009dab329a6efb580c57ef8e1494cf3b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0457746479, "max_line_length": 110, "alphanum_fraction": 0.56814065, "num_tokens": 2626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23840864186153396}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_AnalogElasticElectronScatteringDistribution.hpp\n//! \\author Luke Kersting\n//! \\brief  The electron analog elastic scattering distribution base class\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_ANALOG_ELASTIC_ELECTRON_SCATTERING_DISTRIBUTION_HPP\n#define MONTE_CARLO_ANALOG_ELASTIC_ELECTRON_SCATTERING_DISTRIBUTION_HPP\n\n// Std Lib Includes\n#include <limits>\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// Trilinos Includes\n#include <Teuchos_Array.hpp>\n#include <Teuchos_RCP.hpp>\n\n// FRENSIE Includes\n#include \"MonteCarlo_ElectronState.hpp\"\n#include \"MonteCarlo_ParticleBank.hpp\"\n#include \"MonteCarlo_ElectronScatteringDistribution.hpp\"\n#include \"MonteCarlo_AdjointElectronScatteringDistribution.hpp\"\n#include \"Utility_TabularOneDDistribution.hpp\"\n\nnamespace MonteCarlo{\n\n//! The scattering distribution base class\nclass AnalogElasticElectronScatteringDistribution : public ElectronScatteringDistribution,\n                                    public AdjointElectronScatteringDistribution\n{\n\npublic:\n\n  //! Typedef for the  elastic distribution\n  typedef Teuchos::Array<Utility::Pair< double,\n\t\t       Teuchos::RCP<const Utility::TabularOneDDistribution> > >\n  ElasticDistribution;\n\n  //! Constructor\n  AnalogElasticElectronScatteringDistribution(\n        const ElasticDistribution& elastic_scattering_distribution,\n        const double lower_cutoff_angle = 1.0e-6,\n        const bool angle_is_used_as_independent_variable = true );\n\n  //! Destructor \n  virtual ~AnalogElasticElectronScatteringDistribution()\n  { /* ... */ }\n\n  //! Evaluate the distribution\n  double evaluatePDF( const double incoming_energy,\n                      const double scattering_angle ) const;\n\n  //! Evaluate the distribution\n  double evaluate( const unsigned incoming_energy_bin,\n                   const double scattering_angle ) const;\n\n  //! Evaluate the PDF\n  double evaluate( const double incoming_energy,\n                   const double scattering_angle ) const;\n\n  //! Evaluate the PDF\n  double evaluatePDF( const unsigned incoming_energy_bin,\n                      const double scattering_angle ) const;\n\n  //! Evaluate the CDF\n  double evaluateCDF( const double incoming_energy,\n                      const double scattering_angle ) const;\n\n  //! Evaluate the cross section ratio for the cutoff angle\n  double evaluateCutoffCrossSectionRatio( const double incoming_energy ) const;\n\n  //! Return the energy at a given energy bin\n  double getEnergy( const unsigned energy_bin ) const;\n\n  //! Sample an outgoing energy and direction from the distribution\n  void sample( const double incoming_energy,\n               double& outgoing_energy,\n               double& scattering_angle_cosine ) const;\n\n  //! Sample an outgoing energy and direction and record the number of trials\n  void sampleAndRecordTrials( const double incoming_energy,\n                              double& outgoing_energy,\n                              double& scattering_angle_cosine,\n                              unsigned& trials ) const;\n\n  //! Randomly scatter the electron\n  void scatterElectron( ElectronState& electron,\n                        ParticleBank& bank,\n                        SubshellType& shell_of_interaction ) const;\n                        \n  //! Randomly scatter the adjoint electron\n  void scatterAdjointElectron( AdjointElectronState& adjoint_electron,\n                               ParticleBank& bank,\n                               SubshellType& shell_of_interaction ) const;\n\n\n\n//protected:\n\n   //! Sample an outgoing direction from the distribution\n  void sampleAndRecordTrialsImpl( const double incoming_energy,\n                                  double& scattering_angle_cosine,\n                                  unsigned& trials ) const;\n\nprivate:\n\n  // The scattering angle above which the analog distribution is used\n  double d_lower_cutoff_angle;\n\n  // Independent parameter flag: false = angle cosine, true = angle (in units of pi)\n  bool d_angle_is_used_as_independent_variable;\n\n  // elastic scattering distribution without forward screening data\n  ElasticDistribution d_elastic_scattering_distribution;\n};\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_ANALOG_ELASTIC_ELECTRON_SCATTERING_DISTRIBUTION_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_AnalogElasticElectronScatteringDistribution.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "6dc348212470749ac4c02d0590e6d8e135c2a908", "size": 4631, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_AnalogElasticElectronScatteringDistribution.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/collision/native/src/MonteCarlo_AnalogElasticElectronScatteringDistribution.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/collision/native/src/MonteCarlo_AnalogElasticElectronScatteringDistribution.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": 35.8992248062, "max_line_length": 90, "alphanum_fraction": 0.6644353271, "num_tokens": 869, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2384086362863246}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2008 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\n#define BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\n\n#include <boost/units/pow.hpp>\n#include <boost/units/quantity.hpp>\n#include <boost/units/static_constant.hpp>\n\n#include <boost/units/systems/detail/constants.hpp>\n#include <boost/units/systems/si/amount.hpp>\n#include <boost/units/systems/si/area.hpp>\n#include <boost/units/systems/si/electric_charge.hpp>\n#include <boost/units/systems/si/energy.hpp>\n#include <boost/units/systems/si/frequency.hpp>\n#include <boost/units/systems/si/mass.hpp>\n#include <boost/units/systems/si/power.hpp>\n#include <boost/units/systems/si/solid_angle.hpp>\n#include <boost/units/systems/si/temperature.hpp>\n\n#include <boost/units/systems/si/codata/typedefs.hpp>\n\n/// \\file\n/// CODATA recommended values of fundamental physico-chemical constants\n/// CODATA 2006 values as of 2007/03/30\n\nnamespace boost {\n\nnamespace units { \n\nnamespace si {\n                            \nnamespace constants {\n\nnamespace codata {\n\n// PHYSICO-CHEMICAL\n/// Avogadro constant\nBOOST_UNITS_PHYSICAL_CONSTANT(N_A,quantity<inverse_amount>,6.02214179e23/mole,3.0e16/mole);\n/// atomic mass constant\nBOOST_UNITS_PHYSICAL_CONSTANT(m_u,quantity<mass>,1.660538782e-27*kilograms,8.3e-35*kilograms);\n/// Faraday constant\nBOOST_UNITS_PHYSICAL_CONSTANT(F,quantity<electric_charge_over_amount>,96485.3399*coulombs/mole,2.4e-3*coulombs/mole);\n/// molar gas constant\nBOOST_UNITS_PHYSICAL_CONSTANT(R,quantity<energy_over_temperature_amount>,8.314472*joules/kelvin/mole,1.5e-5*joules/kelvin/mole);\n/// Boltzmann constant\nBOOST_UNITS_PHYSICAL_CONSTANT(k_B,quantity<energy_over_temperature>,1.3806504e-23*joules/kelvin,2.4e-29*joules/kelvin);\n/// Stefan-Boltzmann constant\nBOOST_UNITS_PHYSICAL_CONSTANT(sigma_SB,quantity<power_over_area_temperature_4>,5.670400e-8*watts/square_meter/pow<4>(kelvin),4.0e-13*watts/square_meter/pow<4>(kelvin));\n/// first radiation constant\nBOOST_UNITS_PHYSICAL_CONSTANT(c_1,quantity<power_area>,3.74177118e-16*watt*square_meters,1.9e-23*watt*square_meters);\n/// first radiation constant for spectral radiance\nBOOST_UNITS_PHYSICAL_CONSTANT(c_1L,quantity<power_area_over_solid_angle>,1.191042759e-16*watt*square_meters/steradian,5.9e-24*watt*square_meters/steradian);\n/// second radiation constant\nBOOST_UNITS_PHYSICAL_CONSTANT(c_2,quantity<length_temperature>,1.4387752e-2*meter*kelvin,2.5e-8*meter*kelvin);\n/// Wien displacement law constant : lambda_max T\nBOOST_UNITS_PHYSICAL_CONSTANT(b,quantity<length_temperature>,2.8977685e-3*meter*kelvin,5.1e-9*meter*kelvin);\n/// Wien displacement law constant : nu_max/T\nBOOST_UNITS_PHYSICAL_CONSTANT(b_prime,quantity<frequency_over_temperature>,5.878933e10*hertz/kelvin,1.0e15*hertz/kelvin);\n\n} // namespace codata\n\n} // namespace constants    \n\n} // namespace si\n\n} // namespace units\n\n} // namespace boost\n\n#endif // BOOST_UNITS_CODATA_PHYSICO_CHEMICAL_CONSTANTS_HPP\n", "meta": {"hexsha": "38975bbfdcfd3b5e3bac962224d614ee940fd566", "size": 3269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/cinder/include/boost/units/systems/si/codata/physico-chemical_constants.hpp", "max_stars_repo_name": "multi-os-engine/cinder-natj-binding", "max_stars_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "deps/cinder/include/boost/units/systems/si/codata/physico-chemical_constants.hpp", "max_issues_repo_name": "multi-os-engine/cinder-natj-binding", "max_issues_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1074.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T15:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-22T20:28:39.000Z", "max_forks_repo_path": "deps/cinder/include/boost/units/systems/si/codata/physico-chemical_constants.hpp", "max_forks_repo_name": "multi-os-engine/cinder-natj-binding", "max_forks_repo_head_hexsha": "969b66fdd49e4ca63442baf61ce90ae385ab8178", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 40.8625, "max_line_length": 168, "alphanum_fraction": 0.7987152034, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23840216071261375}}
{"text": "\n#include <algorithm>\n#include <numeric>\n#include <functional>\n#include <limits>\n#include <iostream>\n#include <cmath>\n#include <cassert>\n\n#include <boost/lambda/lambda.hpp>\n\n#include \"BeliefPropagation.h\"\n#include \"LogSumExp.h\"\n\nusing namespace boost::lambda;\n\nnamespace Grante {\n\nBeliefPropagation::BeliefPropagation(const FactorGraph* fg,\n\tMessageSchedule sched)\n\t: InferenceMethod(fg), verbose(false), max_iter(100), conv_tol(1.0e-5),\n\t\tsched(sched), min_sum(false),\n\t\tlog_z(std::numeric_limits<double>::quiet_NaN())\n{\n\t// Setup message indices\n\tconst std::vector<Factor*>& factors = fg->Factors();\n\tfor (unsigned int fi = 0; fi < factors.size(); ++fi) {\n\t\tconst std::vector<unsigned int>& fac_vars = factors[fi]->Variables();\n\t\tfor (unsigned int fvi = 0; fvi < fac_vars.size(); ++fvi) {\n\t\t\t// 1. Message from variable to factor\n\t\t\tunsigned int msg_id =\n\t\t\t\tstatic_cast<unsigned int>(msg_for_factor_srcvar.size());\n\t\t\tmsglist_for_factor[fi].push_back(msg_id);\n\t\t\tmsg_for_factor_srcvar.push_back(fac_vars[fvi]);\n\n\t\t\t// 2. Message from factor to variable\n\t\t\tmsg_id = static_cast<unsigned int>(msg_for_var_srcfactor.size());\n\t\t\tmsglist_for_var[fac_vars[fvi]].push_back(msg_id);\n\t\t\tmsg_for_var_srcfactor.push_back(fi);\n\t\t}\n\t}\n\n\t// If using a sequential schedule, obtain a message order and id's\n\tif (sched == Sequential) {\n\t\tFactorGraphStructurizer::ComputeEulerianMessageTrail(fg, order);\n\t\torder_msgid.resize(order.size());\n\n\t\tfor (size_t oi = 0; oi < order.size(); ++oi) {\n\t\t\tunsigned int vi = order[oi].VariableNode();\n\t\t\tunsigned int fi = order[oi].FactorNode();\n\t\t\tif (order[oi].steptype == FactorGraphStructurizer::LeafIsFactorNode) {\n\t\t\t\t// message: fi -> vi\n\t\t\t\tmsg_list_t::const_iterator mli = msglist_for_var.find(vi);\n\t\t\t\tassert(mli != msglist_for_var.end());\n\t\t\t\tconst std::vector<unsigned int>& msg_list = mli->second;\n\t\t\t\tfor (unsigned int mi = 0; mi < msg_list.size(); ++mi) {\n\t\t\t\t\tif (msg_for_var_srcfactor[msg_list[mi]] != fi)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\torder_msgid[oi] = msg_list[mi];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// message: vi -> fi\n\t\t\t\tmsg_list_t::const_iterator mli = msglist_for_factor.find(fi);\n\t\t\t\tassert(mli != msglist_for_factor.end());\n\t\t\t\tconst std::vector<unsigned int>& msg_list = mli->second;\n\t\t\t\tfor (unsigned int mi = 0; mi < msg_list.size(); ++mi) {\n\t\t\t\t\tif (msg_for_factor_srcvar[msg_list[mi]] != vi)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\torder_msgid[oi] = msg_list[mi];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nBeliefPropagation::~BeliefPropagation() {\n}\n\nInferenceMethod* BeliefPropagation::Produce(const FactorGraph* fg) const {\n\treturn (new BeliefPropagation(fg));\n}\n\nvoid BeliefPropagation::SetParameters(bool verbose,\n\tunsigned int max_iter, double conv_tol) {\n\tthis->verbose = verbose;\n\tthis->max_iter = max_iter;\n\tassert(conv_tol >= 0.0);\n\tthis->conv_tol = conv_tol;\n}\n\nvoid BeliefPropagation::PerformInference() {\n\tInferenceInitialize();\n\n\t// Min-sum variables\n\tdouble best_energy = std::numeric_limits<double>::infinity();\n\n\t// Perform message passing\n\tdouble conv_measure = std::numeric_limits<double>::infinity();\n\tfor (unsigned int iter = 1; (max_iter == 0 || iter <= max_iter) &&\n\t\tconv_measure >= conv_tol; ++iter)\n\t{\n\t\tif (verbose) {\n\t\t\tstd::cout << \"iter \" << iter << \", conv \" << conv_measure;\n\t\t\tif (min_sum)\n\t\t\t\tstd::cout << \", E* \" << best_energy;\n\t\t\tstd::cout << std::endl;\n\t\t}\n\n\t\tif (sched == ParallelSync) {\n\t\t\tPerformInferenceStepParallel();\n\t\t} else if (sched == Sequential) {\n\t\t\tPerformInferenceSequential();\n\t\t} else {\n\t\t\tassert(0);\n\t\t}\n\n\t\t// Convergence measure: maximum update to marginals\n\t\t// TODO\n\t\tif (min_sum) {\n\t\t\tconv_measure = ComputeVariableBeliefs();\n\t\t\tstd::vector<unsigned int> cur_state(fg->Cardinalities().size());\n\t\t\tdouble cur_energy = ReconstructMinimumEnergyState(cur_state);\n\t\t\tif (cur_energy < best_energy) {\n\t\t\t\tbest_energy = cur_energy;\n\t\t\t\tbest_state = cur_state;\n\t\t\t}\n\t\t} else {\n\t\t\tconv_measure = ConstructMarginals();\n\t\t}\n\t}\n\tConstructMarginals();\n\tComputeVariableBeliefs();\n\tif (min_sum) {\n\t\tif (verbose) {\n\t\t\tstd::cout << \"Converged, tol \" << conv_measure << \", E* \"\n\t\t\t\t<< best_energy << std::endl;\n\t\t}\n\t} else {\n\t\tlog_z = -ComputeBetheFreeEnergy();\n\t\tif (verbose) {\n\t\t\tstd::cout << \"Converged, tol \" << conv_measure\n\t\t\t\t<< \", log_z(Bethe) \" << log_z << std::endl;\n\t\t}\n\t}\n\n\tInferenceTeardown();\n}\n\nvoid BeliefPropagation::InferenceInitialize() {\n\t// Initialize messages\n\tconst std::vector<unsigned int>& card = fg->Cardinalities();\n\t//  i) factor-to-variable\n\tmsg_for_var.resize(msg_for_var_srcfactor.size());\n\tfor (unsigned int vi = 0; vi < card.size(); ++vi) {\n\t\tmsg_list_t::const_iterator mli = msglist_for_var.find(vi);\n\t\tassert(mli != msglist_for_var.end());\n\t\tconst std::vector<unsigned int>& ml = mli->second;\n\n\t\tfor (unsigned int mli = 0; mli < ml.size(); ++mli) {\n\t\t\tassert(ml[mli] < msg_for_var.size());\n\n\t\t\t// Resize and fill (value does not matter for parallel schedule,\n\t\t\t// but does for sequential)\n\t\t\tmsg_for_var[ml[mli]].resize(card[vi]);\n\t\t\tstd::fill(msg_for_var[ml[mli]].begin(),\n\t\t\t\tmsg_for_var[ml[mli]].end(), 0.0);\n\t\t}\n\t}\n\t// ii) variable-to-factor\n\tmsg_for_factor.resize(msg_for_factor_srcvar.size());\n\tfor (unsigned int mfi = 0; mfi < msg_for_factor_srcvar.size(); ++mfi) {\n\t\tunsigned int vi = msg_for_factor_srcvar[mfi];\n\t\tassert(vi < card.size());\n\t\t// Resize and fill with log(1) = 0.\n\t\tmsg_for_factor[mfi].resize(card[vi]);\n\t\tstd::fill(msg_for_factor[mfi].begin(), msg_for_factor[mfi].end(), 0.0);\n\t}\n\n\t// Initialize marginals (beliefs)\n\tconst std::vector<Factor*>& factors = fg->Factors();\n\tmarginals.resize(factors.size());\n\tfor (unsigned int fi = 0; fi < factors.size(); ++fi) {\n\t\tmarginals[fi].resize(factors[fi]->Type()->ProdCardinalities());\n\t\tstd::fill(marginals[fi].begin(), marginals[fi].end(), 0.0);\n\t}\n}\n\nvoid BeliefPropagation::InferenceTeardown() {\n\t// Clear messages\n\tmsg_for_var.clear();\n\tmsg_for_factor.clear();\n}\n\nvoid BeliefPropagation::ClearInferenceResult() {\n\tmarginals.clear();\n\tvar_beliefs.clear();\n}\n\nconst std::vector<double>& BeliefPropagation::Marginal(\n\tunsigned int factor_id) const {\n\tassert(factor_id < marginals.size());\n\treturn (marginals[factor_id]);\n}\n\nconst std::vector<std::vector<double> >& BeliefPropagation::Marginals() const\n{\n\treturn (marginals);\n}\n\ndouble BeliefPropagation::LogPartitionFunction() const {\n\treturn (log_z);\n}\n\n// NOT IMPLEMENTED\nvoid BeliefPropagation::Sample(std::vector<std::vector<unsigned int> >& states,\n\tunsigned int sample_count) {\n\tassert(0);\n}\n\ndouble BeliefPropagation::MinimizeEnergy(std::vector<unsigned int>& state) {\n\tmin_sum = true;\n\tPerformInference();\n\tstate.resize(fg->Cardinalities().size());\n\tstd::copy(best_state.begin(), best_state.end(), state.begin());\n\tmin_sum = false;\n\treturn (fg->EvaluateEnergy(state));\n}\n\n\nvoid BeliefPropagation::PerformInferenceStepParallel() {\n\t// 1. factor-to-variable\n\tPassFactorToVariable();\n\t// 2. variable-to-factor\n\tPassVariableToFactor();\n}\n\nvoid BeliefPropagation::PerformInferenceSequential() {\n\t// Perform one sequential pass over all messages\n\tfor (unsigned int oi = 0; oi < order.size(); ++oi) {\n\t\tunsigned int vi = order[oi].VariableNode();\n\t\tunsigned int fi = order[oi].FactorNode();\n\t\tunsigned int msg_id = order_msgid[oi];\n\n\t\tif (order[oi].steptype == FactorGraphStructurizer::LeafIsFactorNode) {\n\t\t\t// message: fi -> vi\n\t\t\tconst Factor* factor = fg->Factors()[fi];\n\t\t\tPassFactorToVariable(factor, vi, msg_for_var[msg_id],\n\t\t\t\tmsglist_for_factor[fi]);\n\t\t} else {\n\t\t\t// message: vi -> fi\n\t\t\tPassVariableToFactor(fi, msg_for_factor[msg_id], vi);\n\t\t}\n\t}\n}\n\nvoid BeliefPropagation::PassFactorToVariable() {\n\tconst std::vector<Factor*>& factors = fg->Factors();\n\tconst std::vector<unsigned int>& card = fg->Cardinalities();\n\n\t// For each variable\n\tfor (unsigned int vi = 0; vi < card.size(); ++vi) {\n\t\tmsg_list_t::const_iterator mli = msglist_for_var.find(vi);\n\t\tassert(mli != msglist_for_var.end());\n\t\tconst std::vector<unsigned int>& ml = mli->second;\n\n\t\t// For each factor connected to that variable:\n\t\t// Send message from factor to variable\n\t\tfor (unsigned int mli = 0; mli < ml.size(); ++mli) {\n\t\t\tassert(ml[mli] < msg_for_var.size());\n\n\t\t\tunsigned int factor_index = msg_for_var_srcfactor[ml[mli]];\n\t\t\tconst Factor* factor = factors[factor_index];\n\t\t\tPassFactorToVariable(factor, vi, msg_for_var[ml[mli]],\n\t\t\t\tmsglist_for_factor[factor_index]);\n\t\t}\n\t}\n}\n\n// Single message variant\nvoid BeliefPropagation::PassFactorToVariable(const Factor* factor,\n\tunsigned int vi, std::vector<double>& msg,\n\tconst std::vector<unsigned int>& msglist_for_factor_cur) {\n\t// Obtain type and adjacent variables of the factor\n\tconst FactorType* ftype = factor->Type();\n\n\tconst std::vector<unsigned int>& fvars = factor->Variables();\n\tunsigned int fvi_to = static_cast<unsigned int>(\n\t\tstd::find(fvars.begin(), fvars.end(), vi) - fvars.begin());\n\n\t// Target message to be computed\n\t// r_{m->n}(x_n) = log sum_{x_m \\ n} exp(\n\t//    -E(x_m) + sum_{n' \\in N(m) \\ n} q_{n'->m}(x_{n'}) )\n\tstd::fill(msg.begin(), msg.end(), 0.0);\n\n\t// Compute the message within the factor type\n\tftype->ComputeBPMessage(factor, vi, fvi_to,\n\t\tmsglist_for_factor_cur, msg_for_factor,\n\t\tmsg_for_factor_srcvar, msg, min_sum);\n}\n\nvoid BeliefPropagation::PassVariableToFactor() {\n\tconst std::vector<Factor*>& factors = fg->Factors();\n\t// For all factors\n\tfor (unsigned int fi = 0; fi < factors.size(); ++fi) {\n\t\t// Obtain messages directed to factor fi\n\t\tmsg_list_t::const_iterator mli = msglist_for_factor.find(fi);\n\t\tassert(mli != msglist_for_factor.end());\n\t\tconst std::vector<unsigned int>& ml = mli->second;\n\n\t\t// For all adjacent variables\n\t\tfor (unsigned int mli = 0; mli < ml.size(); ++mli) {\n\t\t\tassert(ml[mli] < msg_for_factor.size());\n\n\t\t\tstd::vector<double>& msg = msg_for_factor[ml[mli]];\n\t\t\tunsigned int from_var = msg_for_factor_srcvar[ml[mli]];\n\t\t\tPassVariableToFactor(fi, msg, from_var);\n\t\t}\n\t}\n}\n\nvoid BeliefPropagation::PassVariableToFactor(unsigned int fi,\n\tstd::vector<double>& msg, unsigned int from_var) {\n\t// Target message to be computed\n\t//    q_{n->m}(x_n) = sum_{m' \\in M(n) \\ m} r_{m'->n}(x_n),\n\t// (26.11) McKay, in log-domain.\n\tstd::fill(msg.begin(), msg.end(), 0.0);\n\tmsg_list_t::const_iterator mvi = msglist_for_var.find(from_var);\n\tassert(mvi != msglist_for_var.end());\n\tconst std::vector<unsigned int>& mliv = mvi->second;\n\tfor (std::vector<unsigned int>::const_iterator fvi = mliv.begin();\n\t\tfvi != mliv.end(); ++fvi) {\n\t\tunsigned int for_var_msg_index = *fvi;\n\t\t// Skip messages from the target factor\n\t\tif (msg_for_var_srcfactor[for_var_msg_index] == fi)\n\t\t\tcontinue;\n\n\t\t// Add log-sum messages, (26.11)\n\t\tstd::transform(msg_for_var[for_var_msg_index].begin(),\n\t\t\tmsg_for_var[for_var_msg_index].end(),\n\t\t\tmsg.begin(), msg.begin(), std::plus<double>());\n\t}\n\n\t// Normalization for numerical stability,\n\t//   i) sum-product: log-sum-exp = 0,\n\t//  ii) min-sum: sum = 0.\n\tdouble norm_delta = min_sum ?\n\t\t(std::accumulate(msg.begin(), msg.end(), 0.0) /\n\t\t\tstatic_cast<double>(msg.size()))\n\t\t: LogSumExp::Compute(msg);\n\tstd::transform(msg.begin(), msg.end(), msg.begin(), _1 - norm_delta);\n}\n\ndouble BeliefPropagation::ConstructMarginals() {\n\tconst std::vector<Factor*>& factors = fg->Factors();\n\t// Compute mean and variance of log_z estimate\n\tdouble marg_max_diff = -std::numeric_limits<double>::infinity();\n\n\t// Compute marginals of all factors\n\tfor (unsigned int fi = 0; fi < factors.size(); ++fi) {\n\t\tconst Factor* factor = factors[fi];\n\t\tconst FactorType* ftype = factor->Type();\n\n\t\t// Obtain messages directed to factor fi\n\t\tmsg_list_t::const_iterator mli = msglist_for_factor.find(fi);\n\t\tassert(mli != msglist_for_factor.end());\n\t\tconst std::vector<unsigned int>& msglist_for_factor_cur = mli->second;\n\n\t\tdouble cur_marg_max_diff = ftype->ComputeBPMarginal(factor,\n\t\t\tmsglist_for_factor_cur, msg_for_factor, marginals[fi], min_sum);\n\t\tif (cur_marg_max_diff > marg_max_diff)\n\t\t\tmarg_max_diff = cur_marg_max_diff;\n\n\t}\n\n\treturn (marg_max_diff);\n}\n\ndouble BeliefPropagation::ComputeVariableBeliefs() {\n\tconst std::vector<unsigned int>& card = fg->Cardinalities();\n\tvar_beliefs.resize(card.size());\n\n\t// For each variable\n\tdouble max_change = -std::numeric_limits<double>::infinity();\n\tfor (unsigned int vi = 0; vi < card.size(); ++vi) {\n\t\t// Initialize beliefs\n\t\tstd::vector<double> var_belief_vi_old(var_beliefs[vi]);\n\t\tvar_beliefs[vi].resize(card[vi]);\n\t\tstd::fill(var_beliefs[vi].begin(), var_beliefs[vi].end(), 0.0);\n\n\t\t// For each message directed to variable vi\n\t\tmsg_list_t::const_iterator mli = msglist_for_var.find(vi);\n\t\tassert(mli != msglist_for_var.end());\n\t\tconst std::vector<unsigned int>& ml = mli->second;\n\t\tfor (unsigned int mli = 0; mli < ml.size(); ++mli) {\n\t\t\tassert(ml[mli] < msg_for_var.size());\n\t\t\tstd::vector<double>& msg = msg_for_var[ml[mli]];\n\n\t\t\t// sum_{m \\in M(vi)} log r_{m->n}(x_n)\n\t\t\tassert(msg.size() == card[vi]);\n\t\t\tstd::transform(msg.begin(), msg.end(), var_beliefs[vi].begin(),\n\t\t\t\tvar_beliefs[vi].begin(), std::plus<double>());\n\t\t}\n\n\t\t// Compute normalized variable marginal (belief)\n\t\tdouble Z_vi = min_sum ?\n\t\t\t(std::accumulate(var_beliefs[vi].begin(),\n\t\t\t\tvar_beliefs[vi].end(), 0.0) /\n\t\t\t\tstatic_cast<double>(var_beliefs[vi].size()))\n\t\t\t: LogSumExp::Compute(var_beliefs[vi]);\n\t\tfor (unsigned int vs = 0; vs < var_beliefs[vi].size(); ++vs) {\n\t\t\tif (min_sum) {\n\t\t\t\tvar_beliefs[vi][vs] -= Z_vi;\n\t\t\t} else {\n\t\t\t\tvar_beliefs[vi][vs] = std::exp(var_beliefs[vi][vs] - Z_vi);\n\t\t\t}\n\t\t\tif (var_belief_vi_old.empty()) {\n\t\t\t\tmax_change = std::numeric_limits<double>::infinity();\n\t\t\t} else {\n\t\t\t\tmax_change = std::max(max_change,\n\t\t\t\t\tstd::fabs(var_beliefs[vi][vs] - var_belief_vi_old[vs]));\n\t\t\t}\n\t\t}\n\t}\n\treturn (max_change);\n}\n\ndouble BeliefPropagation::ReconstructMinimumEnergyState(\n\tstd::vector<unsigned int>& state) const {\n\tconst std::vector<unsigned int>& card = fg->Cardinalities();\n\tassert(state.size() == card.size());\n\tassert(var_beliefs.size() == card.size());\n\n\tfor (size_t vi = 0; vi < card.size(); ++vi) {\n\t\tassert(var_beliefs[vi].size() == card[vi]);\n\t\tstate[vi] = static_cast<unsigned int>(std::max_element(\n\t\t\tvar_beliefs[vi].begin(), var_beliefs[vi].end())\n\t\t\t- var_beliefs[vi].begin());\n\t}\n\treturn (fg->EvaluateEnergy(state));\n}\n\n// (3.45) in [Wainwright and Jordan], \"A(theta) = negative free energy\"\n// Theorem 5 in [Yedidia, Freeman, and Weiss], \"Interior stationary points of\n// the constrained Bethe free energy must be BP fixed points\".\n// (37) in [Yedidia, Freeman, and Weiss] gives the Bethe free energy.  This is\n// an approximation to the negative log partition function logZ.\ndouble BeliefPropagation::ComputeBetheFreeEnergy() const {\n\tdouble U_Bethe = 0.0;\t// Bethe average energy\n\tdouble H_Bethe = 0.0;\t// Bethe entropy\n\tconst std::vector<Factor*>& factors = fg->Factors();\n\tconst std::vector<unsigned int>& card = fg->Cardinalities();\n\tstd::vector<unsigned int> var_degree(card.size(), 0);\n\tfor (unsigned int fi = 0; fi < factors.size(); ++fi) {\n\t\tconst Factor* factor = factors[fi];\n\t\tconst std::vector<double>& energies = factor->Energies();\n\t\tsize_t energies_size = energies.size();\n\t\tfor (size_t ei = 0; ei < energies_size; ++ei) {\n\t\t\tU_Bethe += -marginals[fi][ei] * (-energies[ei]);\n\t\t\tH_Bethe += -marginals[fi][ei] * std::log(marginals[fi][ei]);\n\t\t}\n\n\t\t// Increase degrees of all variables involved in this factor\n\t\tconst std::vector<unsigned int>& fac_vars = factor->Variables();\n\t\tfor (unsigned int fvi = 0; fvi < fac_vars.size(); ++fvi)\n\t\t\tvar_degree[fac_vars[fvi]] += 1;\n\t}\n\n\tsize_t var_count = card.size();\n\tfor (size_t vi = 0; vi < var_count; ++vi) {\n\t\tassert(var_degree[vi] >= 1);\n\t\tassert(var_beliefs[vi].size() == card[vi]);\n\t\tdouble corr = 0.0;\n\t\tfor (unsigned int state = 0; state < card[vi]; ++state)\n\t\t\tcorr += var_beliefs[vi][state] * std::log(var_beliefs[vi][state]);\n\t\tH_Bethe += static_cast<double>(var_degree[vi] - 1) * corr;\n\t}\n\n\t// Return the Bethe free energy, log Z = -Bethe = -(U-H)\n\treturn (U_Bethe - H_Bethe);\n}\n\n}\n\n", "meta": {"hexsha": "24e7c5f297f803a003a70077e254cf014d542ab5", "size": 15817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "grante/BeliefPropagation.cpp", "max_stars_repo_name": "pantonante/grante-bazel", "max_stars_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_stars_repo_licenses": ["DOC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "grante/BeliefPropagation.cpp", "max_issues_repo_name": "pantonante/grante-bazel", "max_issues_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_issues_repo_licenses": ["DOC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "grante/BeliefPropagation.cpp", "max_forks_repo_name": "pantonante/grante-bazel", "max_forks_repo_head_hexsha": "e3f22ec111463a7ae0686494422ab09f86b4d39a", "max_forks_repo_licenses": ["DOC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4118852459, "max_line_length": 79, "alphanum_fraction": 0.6829360814, "num_tokens": 4473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2384021541064202}}
{"text": "// -----------------------------------------------------------------------\n// RTToolbox - DKFZ radiotherapy quantitative evaluation library\n//\n// Copyright (c) German Cancer Research Center (DKFZ),\n// Software development for Integrated Diagnostics and Therapy (SIDT).\n// ALL RIGHTS RESERVED.\n// See rttbCopyright.txt or\n// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html\n//\n// This software is distributed WITHOUT ANY WARRANTY; without even\n// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n// PURPOSE.  See the above copyright notices for more information.\n//\n//------------------------------------------------------------------------\n\n#include <limits>\n#include <thread>\n\n#include <boost/geometry/geometries/register/point.hpp>\n#include <boost/geometry/geometries/register/ring.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"rttbBoostMask.h\"\n#include \"rttbNullPointerException.h\"\n#include \"rttbInvalidParameterException.h\"\n#include \"rttbBoostMaskGenerateMaskVoxelListThread.h\"\n#include \"rttbBoostMaskVoxelizationThread.h\"\n\nnamespace rttb\n{\n\tnamespace masks\n\t{\n\t\tnamespace boost\n\t\t{\n\n\n\t\t\tBoostMask::BoostMask(core::GeometricInfo::Pointer aDoseGeoInfo,\n        core::Structure::Pointer aStructure, bool strict, unsigned int numberOfThreads)\n\t\t\t\t: _geometricInfo(aDoseGeoInfo), _structure(aStructure),\n                _strict(strict), _numberOfThreads(numberOfThreads), _voxelizationThickness(0.0),\n\t\t\t\t  _voxelInStructure(::boost::make_shared<MaskVoxelList>())\n\t\t\t{\n\n\t\t\t\t_isUpToDate = false;\n\n\t\t\t\tif (_geometricInfo == nullptr)\n\t\t\t\t{\n\t\t\t\t\tthrow rttb::core::NullPointerException(\"Error: Geometric info is nullptr!\");\n\t\t\t\t}\n\t\t\t\telse if (_structure == nullptr)\n\t\t\t\t{\n\t\t\t\t\tthrow rttb::core::NullPointerException(\"Error: Structure is nullptr!\");\n\t\t\t\t}\n\n\t\t\t\tif (_numberOfThreads == 0)\n\t\t\t\t{\n\t\t\t\t\t_numberOfThreads = std::thread::hardware_concurrency();\n                    if (_numberOfThreads == 0)\n                    {\n                        throw rttb::core::InvalidParameterException(\"Error: detection of the number of hardware threads is not possible. Please specify number of threads for voxelization explicitly as parameter in BoostMask.\");\n                    }\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tBoostMask::MaskVoxelListPointer BoostMask::getRelevantVoxelVector()\n\t\t\t{\n\t\t\t\tif (!_isUpToDate)\n\t\t\t\t{\n\t\t\t\t\tcalcMask();\n\t\t\t\t}\n\n\t\t\t\treturn _voxelInStructure;\n\t\t\t}\n\n\t\t\tvoid BoostMask::calcMask()\n\t\t\t{\n\t\t\t\tpreprocessing();\n\t\t\t\tvoxelization();\n\t\t\t\tgenerateMaskVoxelList();\n\t\t\t\t_isUpToDate = true;\n\t\t\t}\n\n\t\t\tvoid BoostMask::preprocessing()\n\t\t\t{\n\t\t\t\trttb::PolygonSequenceType polygonSequence = _structure->getStructureVector();\n\n\t\t\t\t//Convert world coordinate polygons to the polygons with geometry coordinate\n\t\t\t\trttb::PolygonSequenceType geometryCoordinatePolygonVector;\n\t\t\t\trttb::PolygonSequenceType::iterator it;\n\t\t\t\trttb::ContinuousVoxelGridIndex3D globalMaxGridIndex(std::numeric_limits<double>::min(),\n\t\t\t\t        std::numeric_limits<double>::min(), std::numeric_limits<double>::min());\n\t\t\t\trttb::ContinuousVoxelGridIndex3D globalMinGridIndex(_geometricInfo->getNumColumns(),\n\t\t\t\t        _geometricInfo->getNumRows(), 0);\n\n\t\t\t\tfor (it = polygonSequence.begin(); it != polygonSequence.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tPolygonType rttbPolygon = *it;\n\t\t\t\t\tPolygonType geometryCoordinatePolygon;\n\n\t\t\t\t\t//1. convert polygon to geometry coordinate polygons\n\t\t\t\t\t//2. calculate global min/max\n\t\t\t\t\t//3. check if polygon is planar\n\t\t\t\t\tif (!preprocessingPolygon(rttbPolygon, geometryCoordinatePolygon, globalMinGridIndex,\n\t\t\t\t\t                          globalMaxGridIndex, errorConstant))\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow rttb::core::Exception(\"TiltedMaskPlaneException\");\n\t\t\t\t\t}\n\n\t\t\t\t\tgeometryCoordinatePolygonVector.push_back(geometryCoordinatePolygon);\n\t\t\t\t}\n\n\t\t\t\trttb::VoxelGridIndex3D minIndex = VoxelGridIndex3D(GridIndexType(globalMinGridIndex(0) ),\n\t\t\t\t                                  GridIndexType(globalMinGridIndex(1) ), GridIndexType(globalMinGridIndex(2) ));\n\t\t\t\trttb::VoxelGridIndex3D maxIndex = VoxelGridIndex3D(GridIndexType(globalMaxGridIndex(0) ),\n\t\t\t\t                                  GridIndexType(globalMaxGridIndex(1) ), GridIndexType(globalMaxGridIndex(2) ));\n\n\t\t\t\t_globalBoundingBox.push_back(minIndex);\n\t\t\t\t_globalBoundingBox.push_back(maxIndex);\n\n\t\t\t\t//convert rttb polygon sequence to a map of z index and a vector of boost ring 2d (without holes)\n\t\t\t\t_ringMap = convertRTTBPolygonSequenceToBoostRingMap(geometryCoordinatePolygonVector);\n\n\t\t\t}\n\n\t\t\tvoid BoostMask::voxelization()\n\t\t\t{\n\n\t\t\t\tif (_globalBoundingBox.size() < 2)\n\t\t\t\t{\n\t\t\t\t\tthrow rttb::core::InvalidParameterException(\"Bounding box calculation failed! \");\n\t\t\t\t}\n\n\t\t\t\tBoostRingMap::iterator itMap;\n\n\t\t\t\tsize_t mapSizeInAThread = _ringMap.size() / _numberOfThreads;\n\t\t\t\tunsigned int count = 0;\n\t\t\t\tunsigned int countThread = 0;\n\t\t\t\tBoostPolygonMap polygonMap;\n\t\t\t\tstd::vector<BoostPolygonMap> polygonMapVector;\n\n\t\t\t\t//check donut and convert to a map of z index and a vector of boost polygon 2d (with or without holes)\n\t\t\t\tfor (itMap = _ringMap.begin(); itMap != _ringMap.end(); ++itMap)\n\t\t\t\t{\n\t\t\t\t\t//the vector of all boost 2d polygons with the same z grid index(donut polygon is accepted).\n\t\t\t\t\tBoostPolygonVector polygonVector = checkDonutAndConvert((*itMap).second);\n\n\t\t\t\t\tif (count == mapSizeInAThread && countThread < (_numberOfThreads - 1))\n\t\t\t\t\t{\n\t\t\t\t\t\tpolygonMapVector.push_back(polygonMap);\n\t\t\t\t\t\tpolygonMap.clear();\n\t\t\t\t\t\tcount = 0;\n\t\t\t\t\t\tcountThread++;\n\t\t\t\t\t}\n\n\t\t\t\t\tpolygonMap.insert(std::pair<double, BoostPolygonVector>((*itMap).first,\n\t\t\t\t\t                  polygonVector));\n\t\t\t\t\tcount++;\n\n\t\t\t\t}\n\n                _voxelizationMap = ::boost::make_shared<std::map<double, BoostArray2DPointer> >();\n\n\t\t\t\tpolygonMapVector.push_back(polygonMap); //insert the last one\n\n\t\t\t\t//generate voxelization map, multi-threading\n\t\t\t\tstd::vector<std::thread> threads;\n\n        auto aMutex = ::boost::make_shared<std::mutex>();\n\n\t\t\t\tfor (const auto & i : polygonMapVector)\n\t\t\t\t{\n          BoostMaskVoxelizationThread t(i, _globalBoundingBox,\n            _voxelizationMap, aMutex, _strict);\n\t\t\t\t\tthreads.emplace_back(t);\n\t\t\t\t}\n\n        for (auto& thread : threads)\n        {\n          if (thread.joinable())\n          {\n            thread.join();\n          }\n        }\n\t\t\t}\n\n\t\t\tvoid BoostMask::generateMaskVoxelList()\n\t\t\t{\n\t\t\t\tif (_globalBoundingBox.size() < 2)\n\t\t\t\t{\n\t\t\t\t\tthrow rttb::core::InvalidParameterException(\"Bounding box calculation failed! \");\n\t\t\t\t}\n\n\t\t\t\t//check homogeneous of the voxelization plane (the contours plane)\n\t\t\t\tif (!calcVoxelizationThickness(_voxelizationThickness))\n\t\t\t\t{\n\t\t\t\t\tthrow rttb::core::InvalidParameterException(\"Error: The contour plane should be homogeneous!\");\n\t\t\t\t}\n\n\n\n        std::vector<std::thread> threads;\n        auto aMutex = ::boost::make_shared<std::mutex>();\n\n\t\t\t\tunsigned int sliceNumberInAThread = _geometricInfo->getNumSlices() / _numberOfThreads;\n\n\t\t\t\t//generate mask voxel list, multi-threading\n\t\t\t\tfor (unsigned int i = 0; i < _numberOfThreads; ++i)\n\t\t\t\t{\n\t\t\t\t\tunsigned int beginSlice = i * sliceNumberInAThread;\n\t\t\t\t\tunsigned int endSlice;\n\n\t\t\t\t\tif (i < _numberOfThreads - 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tendSlice = (i + 1) * sliceNumberInAThread;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tendSlice = _geometricInfo->getNumSlices();\n\t\t\t\t\t}\n\n\n\t\t\t\t\tBoostMaskGenerateMaskVoxelListThread t(_globalBoundingBox, _geometricInfo, _voxelizationMap,\n\t\t\t\t\t                                       _voxelizationThickness, beginSlice, endSlice,\n\t\t\t\t\t                                       _voxelInStructure, _strict, aMutex);\n\n          threads.emplace_back(t);\n\n\t\t\t\t}\n\n        for (auto& thread : threads)\n        {\n          if (thread.joinable())\n          {\n            thread.join();\n          }\n        }\n\n\t\t\t}\n\n\t\t\tbool BoostMask::preprocessingPolygon(const rttb::PolygonType& aRTTBPolygon,\n\t\t\t                                     rttb::PolygonType& geometryCoordinatePolygon, rttb::ContinuousVoxelGridIndex3D& minimum,\n\t\t\t                                     rttb::ContinuousVoxelGridIndex3D& maximum, double aErrorConstant) const\n\t\t\t{\n\n\t\t\t\tdouble minZ = _geometricInfo->getNumSlices();\n\t\t\t\tdouble maxZ =  0.0;\n\n\t\t\t\tfor (auto worldCoordinatePoint : aRTTBPolygon)\n\t\t\t\t{\n\t\t\t\t\t\t//convert to geometry coordinate polygon\n\t\t\t\t\trttb::ContinuousVoxelGridIndex3D geometryCoordinatePoint;\n\t\t\t\t\t_geometricInfo->worldCoordinateToContinuousIndex(worldCoordinatePoint, geometryCoordinatePoint);\n\n\t\t\t\t\tgeometryCoordinatePolygon.push_back(geometryCoordinatePoint);\n\n\t\t\t\t\t//calculate the current global min/max\n\t\t\t\t\t//min and max for x\n\t\t\t\t\tif (geometryCoordinatePoint(0) < minimum(0))\n\t\t\t\t\t{\n\t\t\t\t\t\tminimum(0) = geometryCoordinatePoint(0);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (geometryCoordinatePoint(0) > maximum(0))\n\t\t\t\t\t{\n\t\t\t\t\t\tmaximum(0) = geometryCoordinatePoint(0);\n\t\t\t\t\t}\n\n\t\t\t\t\t//min and max for y\n\t\t\t\t\tif (geometryCoordinatePoint(1) < minimum(1))\n\t\t\t\t\t{\n\t\t\t\t\t\tminimum(1) = geometryCoordinatePoint(1);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (geometryCoordinatePoint(1) > maximum(1))\n\t\t\t\t\t{\n\t\t\t\t\t\tmaximum(1) = geometryCoordinatePoint(1);\n\t\t\t\t\t}\n\n\t\t\t\t\t//min and max for z\n\t\t\t\t\tif (geometryCoordinatePoint(2) < minimum(2))\n\t\t\t\t\t{\n\t\t\t\t\t\tminimum(2) = geometryCoordinatePoint(2);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (geometryCoordinatePoint(2) > maximum(2))\n\t\t\t\t\t{\n\t\t\t\t\t\tmaximum(2) = geometryCoordinatePoint(2);\n\t\t\t\t\t}\n\n\t\t\t\t\t//check planar\n\t\t\t\t\tif (geometryCoordinatePoint(2) < minZ)\n\t\t\t\t\t{\n\t\t\t\t\t\tminZ = geometryCoordinatePoint(2);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (geometryCoordinatePoint(2) > maxZ)\n\t\t\t\t\t{\n\t\t\t\t\t\tmaxZ = geometryCoordinatePoint(2);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\treturn (std::abs(maxZ - minZ) <= aErrorConstant);\n\t\t\t}\n\n\n\t\t\tBoostMask::BoostRing2D BoostMask::convertRTTBPolygonToBoostRing(const rttb::PolygonType&\n\t\t\t        aRTTBPolygon) const\n\t\t\t{\n\t\t\t\tBoostMask::BoostRing2D polygon2D;\n\t\t\t\tBoostPoint2D firstPoint;\n\n\t\t\t\tfor (unsigned int i = 0; i < aRTTBPolygon.size(); i++)\n\t\t\t\t{\n\t\t\t\t\trttb::WorldCoordinate3D rttbPoint = aRTTBPolygon.at(i);\n\t\t\t\t\tBoostPoint2D boostPoint(rttbPoint[0], rttbPoint[1]);\n\n\t\t\t\t\tif (i == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfirstPoint = boostPoint;\n\t\t\t\t\t}\n\n\t\t\t\t\t::boost::geometry::append(polygon2D, boostPoint);\n\t\t\t\t}\n\n\t\t\t\t::boost::geometry::append(polygon2D, firstPoint);\n\t\t\t\treturn polygon2D;\n\t\t\t}\n\n\t\t\tBoostMask::BoostRingMap BoostMask::convertRTTBPolygonSequenceToBoostRingMap(\n\t\t\t    const rttb::PolygonSequenceType& aRTTBPolygonVector) const\n\t\t\t{\n\t\t\t\trttb::PolygonSequenceType::const_iterator it;\n\t\t\t\tBoostMask::BoostRingMap aRingMap;\n\n\t\t\t\tfor (it = aRTTBPolygonVector.begin(); it != aRTTBPolygonVector.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\trttb::PolygonType rttbPolygon = *it;\n\t\t\t\t\tdouble zIndex = rttbPolygon.at(0)[2];//get the first z index of the polygon\n\t\t\t\t\tbool isFirstZ = true;\n\n\t\t\t\t\tif (!aRingMap.empty())\n\t\t\t\t\t{\n\t\t\t\t\t\tauto findIt = findNearestKey(aRingMap, zIndex, errorConstant);\n\n\t\t\t\t\t\t//if the z index is found (same slice), add the polygon to vector\n\t\t\t\t\t\tif (findIt != aRingMap.end())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//BoostRingVector ringVector = ;\n\t\t\t\t\t\t\t(*findIt).second.push_back(convertRTTBPolygonToBoostRing(rttbPolygon));\n\t\t\t\t\t\t\tisFirstZ = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t//if it is the first z index in the map, insert vector with the polygon\n\t\t\t\t\tif (isFirstZ)\n\t\t\t\t\t{\n\t\t\t\t\t\tBoostRingVector ringVector;\n\t\t\t\t\t\tringVector.push_back(convertRTTBPolygonToBoostRing(rttbPolygon));\n\t\t\t\t\t\taRingMap.insert(std::pair<double, BoostRingVector>(zIndex, ringVector));\n\t\t\t\t\t}\n\n\n\t\t\t\t}\n\n\t\t\t\treturn aRingMap;\n\t\t\t}\n\n\t\t\tBoostMask::BoostRingMap::iterator BoostMask::findNearestKey(BoostMask::BoostRingMap&\n\t\t\t        aBoostRingMap, double aIndex, double aErrorConstant) const\n\t\t\t{\n\t\t\t\tauto find = aBoostRingMap.find(aIndex);\n\n\t\t\t\t//if find a key equivalent to aIndex, found\n\t\t\t\tif (find != aBoostRingMap.end())\n\t\t\t\t{\n\t\t\t\t\treturn find;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tauto lowerBound = aBoostRingMap.lower_bound(aIndex);\n\n\t\t\t\t\t//if all keys go before aIndex, check the last key\n\t\t\t\t\tif (lowerBound == aBoostRingMap.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tlowerBound = --aBoostRingMap.end();\n\t\t\t\t\t}\n\n\t\t\t\t\t//if the lower bound very close to aIndex, found\n\t\t\t\t\tif (std::abs((*lowerBound).first - aIndex) <= aErrorConstant)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn lowerBound;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t//if the lower bound is the beginning, not found\n\t\t\t\t\t\tif (lowerBound == aBoostRingMap.begin())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\treturn aBoostRingMap.end();\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto lowerBound1 = --lowerBound;//the key before the lower bound\n\n\t\t\t\t\t\t\t//if the key before the lower bound very close to a Index, found\n\t\t\t\t\t\t\tif (std::abs((*lowerBound1).first - aIndex) <= aErrorConstant)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\treturn lowerBound1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t//else, not found\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\treturn aBoostRingMap.end();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tBoostMask::BoostPolygonVector BoostMask::checkDonutAndConvert(const BoostMask::BoostRingVector&\n\t\t\t        aRingVector) const\n\t\t\t{\n\t\t\t\t//check donut\n\t\t\t\tBoostMask::BoostRingVector::const_iterator it1;\n\t\t\t\tBoostMask::BoostRingVector::const_iterator it2;\n\t\t\t\tBoostMask::BoostPolygonVector boostPolygonVector;\n\t\t\t\tstd::vector<unsigned int> donutIndexVector;//store the outer and inner ring index\n\t\t\t\tBoostMask::BoostPolygonVector donutVector;//store new generated donut polygon\n\n\t\t\t\t//Get donut index and donut polygon\n\t\t\t\tunsigned int index1 = 0;\n\n\t\t\t\tfor (it1 = aRingVector.begin(); it1 != aRingVector.end(); ++it1, index1++)\n\t\t\t\t{\n\t\t\t\t\tbool it1IsDonut = false;\n\n\t\t\t\t\t//check if the ring is already determined as a donut\n\t\t\t\t\tfor (unsigned int i : donutIndexVector)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (i == index1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tit1IsDonut = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t//if not jet, check now\n\t\t\t\t\tif (!it1IsDonut)\n\t\t\t\t\t{\n\t\t\t\t\t\tbool it2IsDonut = false;\n\t\t\t\t\t\tunsigned int index2 = 0;\n\n\t\t\t\t\t\tfor (it2 = aRingVector.begin(); it2 != aRingVector.end(); ++it2, index2++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (it2 != it1)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tBoostMask::BoostPolygon2D polygon2D;\n\n\t\t\t\t\t\t\t\tif (::boost::geometry::within(*it1, *it2))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t::boost::geometry::append(polygon2D, *it2);//append an outer ring to the polygon\n\t\t\t\t\t\t\t\t\t::boost::geometry::interior_rings(polygon2D).resize(1);//create an interior ring\n\t\t\t\t\t\t\t\t\t::boost::geometry::append(polygon2D, *it1, 0);//append a ring to the interior ring\n\t\t\t\t\t\t\t\t\tit2IsDonut = true;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t//if donut\n\t\t\t\t\t\t\t\telse if (::boost::geometry::within(*it2, *it1))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t::boost::geometry::append(polygon2D, *it1);//append an outer ring to the polygon\n\t\t\t\t\t\t\t\t\t::boost::geometry::interior_rings(polygon2D).resize(1);//create an interior ring\n\t\t\t\t\t\t\t\t\t::boost::geometry::append(polygon2D, *it2, 0);//append a ring to the interior ring\n\t\t\t\t\t\t\t\t\tit2IsDonut = true;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (it2IsDonut)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdonutIndexVector.push_back(index1);\n\t\t\t\t\t\t\t\t\tdonutIndexVector.push_back(index2);\n\t\t\t\t\t\t\t\t\tdonutVector.push_back(polygon2D);//store donut polygon\n\t\t\t\t\t\t\t\t\tbreak;//Only store the first donut!\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//Store no donut polygon to boostPolygonVector\n\t\t\t\tindex1 = 0;\n\n\t\t\t\tfor (it1 = aRingVector.begin(); it1 != aRingVector.end(); ++it1, index1++)\n\t\t\t\t{\n\t\t\t\t\tbool it1IsDonut = false;\n\n\t\t\t\t\t//check if the ring is the outer or inner of a donut\n\t\t\t\t\tfor (unsigned int i : donutIndexVector)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (i == index1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tit1IsDonut = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!it1IsDonut)\n\t\t\t\t\t{\n\t\t\t\t\t\tBoostMask::BoostPolygon2D polygon2D;\n\t\t\t\t\t\t::boost::geometry::append(polygon2D, *it1);\n\t\t\t\t\t\tboostPolygonVector.push_back(polygon2D);//insert the ring, which is not a part of donut\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//Append donut polygon to boostPolygonVector\n\t\t\t\tBoostMask::BoostPolygonVector::iterator itDonut;\n\n\t\t\t\tfor (itDonut = donutVector.begin(); itDonut != donutVector.end(); ++itDonut)\n\t\t\t\t{\n\t\t\t\t\tboostPolygonVector.push_back(*itDonut);//append donuts\n\t\t\t\t}\n\n\t\t\t\treturn boostPolygonVector;\n\t\t\t}\n\n\t\t\tbool BoostMask::calcVoxelizationThickness(double& aThickness) const\n\t\t\t{\n\n\t\t\t\tif (_voxelizationMap->size() <= 1)\n\t\t\t\t{\n\t\t\t\t\taThickness = 1;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tdouble thickness = 0;\n\n                auto it = _voxelizationMap->cbegin();\n                auto it2 = ++_voxelizationMap->cbegin();\n\t\t\t\tfor (;\n\t\t\t\t     it != _voxelizationMap->cend() && it2 != _voxelizationMap->cend(); ++it, ++it2)\n\t\t\t\t{\n\t\t\t\t\tif (thickness == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tthickness = it2->first - it->first;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n                        double curThickness = it2->first - it->first;\n\t\t\t\t\t\t//if not homogeneous (leave out double imprecisions), return false\n\t\t\t\t\t\tif (std::abs(thickness-curThickness)>errorConstant)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t//return false;\n\t\t\t\t\t\t\tstd::cout << \"Two polygons are far from each other?\" << std::endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tif (thickness != 0)\n\t\t\t\t{\n\t\t\t\t\taThickness = thickness;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\taThickness = 1;\n\t\t\t\t}\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "f0115ebf5e2c8e256a3427671c28a460fcdbb7f1", "size": 16647, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/masks/rttbBoostMask.cpp", "max_stars_repo_name": "MIC-DKFZ/RTTB", "max_stars_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2018-04-19T12:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T17:43:02.000Z", "max_issues_repo_path": "code/masks/rttbBoostMask.cpp", "max_issues_repo_name": "MIC-DKFZ/RTTB", "max_issues_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/masks/rttbBoostMask.cpp", "max_forks_repo_name": "MIC-DKFZ/RTTB", "max_forks_repo_head_hexsha": "8b772501fd3fffcb67233a9307661b03dff72785", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-06-24T21:09:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T09:30:49.000Z", "avg_line_length": 29.1031468531, "max_line_length": 227, "alphanum_fraction": 0.6324863339, "num_tokens": 4439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23833124251240026}}
{"text": "/*\n * Software License Agreement (New BSD License)\n *\n * Copyright (c) 2013, Keith Leung, Felipe Inostroza\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the Advanced Mining Technology Center (AMTC), the\n *       Universidad de Chile, nor the names of its contributors may be \n *       used to endorse or promote products derived from this software without \n *       specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AMTC, UNIVERSIDAD DE CHILE, OR THE COPYRIGHT \n * HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE \n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT \n * 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#ifndef RBPHDFILTER_HPP\n#define RBPHDFILTER_HPP\n\n#include <boost/timer/timer.hpp>\n#include <Eigen/Core>\n#include \"GaussianMixture.hpp\"\n#include \"ParticleFilter.hpp\"\n#include \"KalmanFilter.hpp\"\n#include <math.h>\n#include <vector>\n\n#include <stdio.h>\n\n/**\n *  \\class RBPHDFilter\n *  \\brief Rao-Blackwellized Probability Hypothesis Density Filter class\n *  \n *  This class implements the Rao-Bloackwellized Probability Hypothesis Density\n *  filter. The constructor of this class will internally instantiate the \n *  process model for both the robot and landmarks, the measurement model, \n *  and the Kalman filter. Users have access to these through pointers that \n *  can be obtained by calling the appropraite get function.\n *\n *  \\tparam RobotProcessModel A robot process model derived from ProcessModel\n *  \\tparam LmkProcessModel A landmark process model derived from ProcessModel\n *  \\tparam MeasurementModel A sensor model derived from MeasurementModel\n *  \\tparam KalmanFilter A Kalman filter that uses LmkProcessModel and MeasurementModel\n *  \\author Keith Leung, Felipe Inostroza\n */\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter>\nclass RBPHDFilter : public ParticleFilter<RobotProcessModel, MeasurementModel>\n{\npublic:\n\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n  typedef typename RobotProcessModel::TState TPose;\n  typedef typename RobotProcessModel::TInput TInput;\n  typedef typename MeasurementModel::TLandmark TLandmark;\n  typedef typename MeasurementModel::TMeasurement TMeasurement;\n  typedef typename GaussianMixture<TLandmark>::Gaussian TGaussian;\n\n  /** \n   * \\brief Configurations for this RBPHDFilter \n   */\n  struct Config{\n    \n    /**  New birth Gaussians are set with this weight */\n    double birthGaussianWeight_;   \n\n    /**  New Gaussians are only created during map update if the innovation mahalanobis distance \n\t is less than this threshold */\n    double newGaussianCreateInnovMDThreshold_;\n\n    /**  number of map states to use for evaluating particle weight\n\t 0 => empty-set strategy,\n\t 1 => single-feature strategy,\n\t >1 => multi-feature strategy\n    */\n    int importanceWeightingEvalPointCount_;\n\n    /** The mahalanobis distance threshold used to determine if a possible meaurement-landmark\n     *  pairing is significant to worth considering \n     */\n    double importanceWeightingMeasurementLikelihoodMDThreshold_;\n\n    /** Gaussian merging Mahalanobis distance threshold */\n    double gaussianMergingThreshold_;\n\n    /** Gaussian merging covariance inflation factor */\n    double gaussianMergingCovarianceInflationFactor_;\n\n    /** Gaussian pruning weight threshold, below which Gaussians are eliminated from a Gaussian mixture */\n    double gaussianPruningThreshold_;\n\n    /** Minimum timeteps betwen resampling of particles*/\n    double minInterSampleTimesteps_;\n\n    /** If true, timing information is written to the console every update*/\n    bool reportTimingInfo_;\n\n    /** Use the particle weighting strategty from Single-cluster PHD Filtering by Lee, et. al. */\n    bool useClusterProcess_;\n\n  } config;\n\n  /** \n   * Constructor \n   * \\param n number of particles\n   * \\param initState initial state of particles\n   */\n  RBPHDFilter(int n);\n\n  /** Destructor */\n  ~RBPHDFilter();\n\n  /** \n   * Get the landmark process model\n   * \\return pointer to the landmark process model\n   */\n  LmkProcessModel* getLmkProcessModel();\n\n  /**\n   * Predict the robot trajectory using the lastest odometry data\n   * \\param[in] input \n   * \\param[in] currentTimestep current timestep;\n   */\n  void predict( TInput u, int currentTimestep );\n\n  /**\n   * Update the map, calculate importance weighting, sample if necessary, and\n   * create new birth Gaussians.\n   * \\param[in] Z set of measurements to use for the update, placed in a std vector, which\n   * gets cleared after the function call. \n   * \\param[in] currentTimestep current timestep;\n   */\n  void update( std::vector<TMeasurement> &Z, int currentTimestep );\n\n  /**\n   * Get the size of the Gaussian mixture for a particle\n   * \\param[in] i particle index\n   * \\return size if index is valid, else -1\n   */\n  int getGMSize(int i);\n\n  /**\n   * Get the position, covariance, and weight of a Gaussian in particle i's Gaussin mixture\n   * \\param[in] i particle index\n   * \\param[in] m Gaussian index\n   * \\param[out] u mean\n   * \\param[out] S covariance\n   * \\param[out] w weight\n   * \\return false if the indices specified are invalid \n   */ \n  bool getLandmark(const int i, const int m, \n\t\t   typename TLandmark::Vec &u,\n\t\t   typename TLandmark::Mat &S,\n\t\t   double &w);\n  \n  /**\n   * Get the pointer to the Kalman Filter used for updating the map\n   * \\return pointer to the Kalman Filter\n   */\n  KalmanFilter* getKalmanFilter();\n\n  /** Function for testing purposes only */\n  void setParticlePose(int i, TPose &p);\n\n\nprivate:\n\n  KalmanFilter *kfPtr_; /**< pointer to the Kalman filter */\n  LmkProcessModel *lmkModelPtr_; /**< pointer to landmark process model */\n\n  std::vector< GaussianMixture<TLandmark>* > maps_; /**< Particle dependent maps */\n\n  /** indices of unused measurement for each particle for creating birth Gaussians */\n  std::vector< std::vector<unsigned int> > unused_measurements_; \n\n  int k_currentTimestep_; /**< current time */\n  int k_lastResample_; /**< last resample time */\n  \n  /** \n   * Add birth Gaussians for each particle's map using unused_measurements_\n   */ \n  void addBirthGaussians();\n\n  /**\n   * Update the map with the measurements in measurements_\n   * Existing landmarks with probability of detection > 0 will have their Gaussian\n   * mixture weight reduced to account for missed detection.\n   * For every landmark-measurement pair with probability of detection > 0,\n   * a new landmark will be created. \n   */\n  void updateMap();\n\n  /** \n   * Importance weighting. Overrides the abstract function in ParticleFilter\n   */\n  void importanceWeighting();\n\n  /**\n   * Random Finite Set measurement likelihood evaluation\n   * \\brief The current measurements in measurements_ are used to determine the\n   * RFS measurement likelihood given a set of landmarks \n   * \\param[in] particleIdx particle for which the likelihood is calcuated\n   * \\param[in] indices of evaluation points in maps_[particleIdx]\n   * \\param[in] probability of detection of evaluation point \n   * \\return measurement likelihood\n   */\n  double rfsMeasurementLikelihood( const int particleIdx, \n\t\t\t\t   std::vector<unsigned int> &evalPtIdx,\n\t\t\t\t   std::vector<double> &evalPtPd );\n\n  /**\n   * Calculate the sum of all permutations of measurement likelihood from a likelihood\n   * table generated from within rfsMeasurementLikelihood\n   * \\param[in] likelihoodTab likelihood table generated within rfsMeasurementLikelihood\n   * \\para,[in] A vector of measurement indices (columns) to consider in the likelihoodTab \n   * \\return sum of all permutations from the given likelihood table\n   */\n  double rfsMeasurementLikelihoodPermutations( std::vector< double* > &likelihoodTab, \n\t\t\t\t\t       std::vector< int > &Z_NoClutter);\n\n  /** Checks the Gaussian mixture maps for all particles for errors\n   *  \\return true if there are no errors \n   */\n  bool checkMapIntegrity();\n\n};\n\n////////// Implementation //////////\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nRBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::RBPHDFilter(int n)\n  : ParticleFilter<RobotProcessModel, MeasurementModel>(n)\n{\n\n  lmkModelPtr_ = new LmkProcessModel;\n  kfPtr_ = new KalmanFilter(lmkModelPtr_, this->getMeasurementModel());\n  \n  for(int i = 0; i < n; i++){\n    printf(\"Creating map structure for particle %d\\n\", i);\n    maps_.push_back( new GaussianMixture<TLandmark>() );\n    unused_measurements_.push_back( std::vector<unsigned int>() );\n  }\n  \n  config.birthGaussianWeight_ = 0.25; \n  config.gaussianMergingThreshold_ = 0.5;\n  config.gaussianMergingCovarianceInflationFactor_ = 1.5;\n  config.gaussianPruningThreshold_ = 0.2;\n  config.importanceWeightingEvalPointCount_ = 8;\n  config.importanceWeightingMeasurementLikelihoodMDThreshold_ = 3.0;\n  config.newGaussianCreateInnovMDThreshold_ = 0.2;\n  config.minInterSampleTimesteps_ = 5;\n  config.reportTimingInfo_ = false;\n  \n  k_lastResample_ = -10;\n}\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nRBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::~RBPHDFilter(){\n\n  for(int i = 0; i < maps_.size(); i++){\n    delete maps_[i];\n  }\n  delete kfPtr_;\n  delete lmkModelPtr_;\n}\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nLmkProcessModel* RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::getLmkProcessModel(){\n  return lmkModelPtr_;\n}\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nvoid RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::predict( TInput u,\n\t\t\t\t\t\t\t\t\t\t\t\t int currentTimestep){\n\n  boost::timer::auto_cpu_timer *timer = NULL;\n  if(config.reportTimingInfo_)\n    timer = new boost::timer::auto_cpu_timer(6, \"Predict time: %ws\\n\");\n\n\n  // Add birth Gaussians using pose before prediction\n  addBirthGaussians();\n\n  // propagate particles\n  k_currentTimestep_ = currentTimestep;\n  this->propagate(u);\n\n  // propagate landmarks\n  for( int i = 0; i < this->nParticles_; i++ ){\n    for( int m = 0; m < maps_[i]->getGaussianCount(); m++){\n      TLandmark *plm;\n      maps_[i]->getGaussian(m, plm);\n      lmkModelPtr_->staticStep(*plm, *plm);\n    }\n  }\n\n  if(timer != NULL)\n    delete timer;\n}\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nvoid RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::update( std::vector<TMeasurement> &Z,\n\t\t\t\t\t\t\t\t\t\t\t\tint currentTimestep){\n\n  boost::timer::auto_cpu_timer *timer_mapUpdate = NULL;\n  boost::timer::auto_cpu_timer *timer_particleWeighting = NULL;\n  boost::timer::auto_cpu_timer *timer_mapMerge = NULL;\n  boost::timer::auto_cpu_timer *timer_mapPrune = NULL;\n  boost::timer::auto_cpu_timer *timer_particleResample = NULL;\n\n  k_currentTimestep_ = currentTimestep;\n\n  this->setMeasurements( Z ); // Z gets cleared after this call, measurements now stored in this->measurements_\n\n  ////////// Map Update //////////\n  if(config.reportTimingInfo_){\n    timer_mapUpdate = new boost::timer::auto_cpu_timer(6, \"Map update time: %ws\\n\");\n  }\n  updateMap();\n  if(timer_mapUpdate != NULL)\n    delete timer_mapUpdate;\n\n  ////////// Particle Weighintg //////////\n  if(config.reportTimingInfo_){\n    timer_particleWeighting = new boost::timer::auto_cpu_timer(6, \"Particle weighting time: %ws\\n\");\n  }\n  if(!config.useClusterProcess_){\n    importanceWeighting();\n  }\n  if(timer_particleWeighting != NULL)\n    delete timer_particleWeighting;\n\n  //////////// Merge and prune //////////\n  int maxMapSize = -1;\n  int i_maxMapSize = -1;\n  if(config.reportTimingInfo_){\n    timer_mapMerge = new boost::timer::auto_cpu_timer(6, \"Map merge time: %ws\\n\");\n  }\n  for( int i = 0; i < this->nParticles_; i++){ \n    maps_[i]->merge( config.gaussianMergingThreshold_, \n\t\t     config.gaussianMergingCovarianceInflationFactor_);    \n  } \n  if(timer_mapMerge != NULL)\n    delete timer_mapMerge;\n  \n  if(config.reportTimingInfo_){\n    timer_mapPrune = new boost::timer::auto_cpu_timer(6, \"Map prune time: %ws\\n\");\n  }\n  for( int i = 0; i < maps_.size(); i++){ // maps_size is same as number of particles\n    maps_[i]->prune( config.gaussianPruningThreshold_ );    \n  }\n  if(timer_mapPrune != NULL)\n    delete timer_mapPrune;\n\n  //////////// Particle resampling //////////\n  if(config.reportTimingInfo_){\n    timer_particleResample = new boost::timer::auto_cpu_timer(6, \"Particle resample time: %ws\\n\");\n  }\n  bool resampleOccured = false;\n  if( k_currentTimestep_ - k_lastResample_ >= config.minInterSampleTimesteps_){\n    resampleOccured = this->resample();\n  }\n\n  if( resampleOccured ){\n    k_lastResample_ = k_currentTimestep_;\n  }else{\n    this->normalizeWeights();\n  }\n\n  if( resampleOccured){   // reassign maps as well according to resampling of particles\n\n    std::vector< GaussianMixture<TLandmark>* > maps_temp( maps_.size(), NULL );\n    std::vector< int > useCount ( maps_.size(), 0);\n\n    // Note which GMs get used and how many times\n    for(int i = 0; i < this->nParticles_; i++){\n      int j = this->particleSet_[i]->getParentId();\n      useCount[j]++;\n    }\n\n    // for maps that get used, make a (pointer copy) before doing any overwriting\n    // Also rid of the maps that die along with particles\n    for(int i = 0; i < this->nParticles_; i++){\n      if( useCount[i] > 0){\n\tmaps_temp[i] = maps_[i];\n      }else{\n\tdelete maps_[i];\n      }\n    }\n    \n    // Copy GMs\n    for(int i = 0; i < this->nParticles_; i++){\n      int j = this->particleSet_[i]->getParentId();\n\n      if( useCount[j] == 1){ // map j is only copied over to map i and not to any other particle's map\n\t\n\tmaps_[i] = maps_temp[j];\n\tmaps_temp[j] = NULL;\n\t\n      }else{ // GM_j is used by more than 1 particle, need to allocate memory for copying map\n\t\n\tmaps_[i] = new GaussianMixture<TLandmark>;\n\tmaps_temp[j]->copyTo( maps_[i] );\n      }\n      useCount[j]--;\n    }\n\n  }  \n  if(timer_particleResample != NULL)\n    delete timer_particleResample;\n\n}\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nvoid RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::updateMap(){\n\n  const unsigned int startIdx = 0;\n  const unsigned int stopIdx = this->nParticles_;\n\n\n  const unsigned int nZ = this->measurements_.size();\n  typename ParticleFilter<RobotProcessModel, MeasurementModel>::TParticleSet::iterator particles_it = this->particleSet_.begin();\n  typename std::vector< GaussianMixture<TLandmark>* >::iterator maps_it = maps_.begin();\n  std::vector< std::vector<unsigned int> >::iterator unused_measurements_it = unused_measurements_.begin();\n  const typename std::vector< TMeasurement >::iterator measurements_it_start = this->measurements_.begin();\n  typename std::vector< TMeasurement >::iterator measurements_it = measurements_it_start;\n  particles_it += startIdx;\n  maps_it += startIdx;\n  unused_measurements_it += startIdx;\n\n  for(unsigned int i = startIdx; i < stopIdx; i++, particles_it++, maps_it++, unused_measurements_it++){    \n\n    //---------- 1. setup / book-keeping ----------\n   \n    const unsigned int nM = (*maps_it)->getGaussianCount();\n    unused_measurements_it->clear();    \n    if(nM == 0){ // No existing landmark case -> flag all measurements as unused and go to next particles\n      for(int z = 0; z < nZ; z++){\n\tunused_measurements_it->push_back( z );\n      }\n      continue;\n    }\n    double Pd[nM];\n    int landmarkCloseToSensingLimit[nM];\n\n    // For cluster process particle weighting\n    double w_km_sum = std::numeric_limits<double>::denorm_min();\n    double likelihoodProd = 1;\n    if(config.useClusterProcess_){\n      for(int m = 0; m < nM; m++){\n\tw_km_sum += (*maps_it)->getWeight(m);\n      }\n    }\n\n    // Mn x nZ table for Gaussian weighting\n    double** weightingTable = new double* [ nM ];\n    TLandmark*** newLandmarkPointer = new TLandmark** [ nM ];\n    for( int n = 0; n < nM; n++ ){\n      weightingTable[n] = new double [ nZ ];\n      newLandmarkPointer[n] = new TLandmark* [ nZ ];\n    }\n    for(int m = 0; m < nM; m++){\n      for(int z = 0; z < nZ; z++){\n\tnewLandmarkPointer[m][z] = NULL;\n\tweightingTable[m][z] = 0;\n      }\n    }\n\n    //----------  2. Kalman Filter map update ----------\n\n    TPose *pose = new TPose;\n    (*particles_it)->getPose(*pose);\n\n    TLandmark* lmNew = NULL;\n\n    for(unsigned int m = 0; m < nM; m++){\n\n      TLandmark* lm = (*maps_it)->getGaussian(m);\n      bool isCloseToSensingLimit;\n      Pd[m] = this->pMeasurementModel_->probabilityOfDetection( *pose, *lm, \n\t\t\t\t\t\t\t\tisCloseToSensingLimit); \n      landmarkCloseToSensingLimit[m] = ( isCloseToSensingLimit ) ? 1 : 0;\n      double w_km = (*maps_it)->getWeight(m);\n      double Pd_times_w_km = Pd[m] * w_km;\n\n      if(Pd[m] != 0){\n\tint z = 0;\n\tfor(z = 0, measurements_it = measurements_it_start; z < nZ; z++, measurements_it++){\n\n\t  if(lmNew == NULL)\n\t    lmNew = new TLandmark;\n\n\t  newLandmarkPointer[m][z] = NULL;\n\t  weightingTable[m][z] = 0;\n\t  double innovationLikelihood = 0;\n\t  double innovationMahalanobisDist2 = 0;\n\t  double threshold = config.newGaussianCreateInnovMDThreshold_ * config.newGaussianCreateInnovMDThreshold_;\n\t\n\t  // RUN KF, create new landmark for likely updates but do not add to map_[i] yet\n\t  // because we cannot determine actual weight until the entire weighting table is\n\t  // filled in\n\t  bool updateMade = kfPtr_->correct(*pose, *measurements_it, *lm, *lmNew, \n\t\t\t\t\t    &innovationLikelihood, &innovationMahalanobisDist2);\n\n\t  if ( !updateMade || innovationMahalanobisDist2 > threshold ){\n\t    newLandmarkPointer[m][z] = NULL;\n\t    weightingTable[m][z] = 0;\n\t  }else{\n\t    newLandmarkPointer[m][z] = lmNew;\n\t    lmNew = NULL;\n\t    weightingTable[m][z] = Pd_times_w_km * innovationLikelihood;\n\t  }\t\n\n\t} // z forloop end\n\n      }else{ // Pd = 0\n\n\tfor(int z = 0; z < nZ; z++){\n\n\t  newLandmarkPointer[m][z] = NULL;\n\t  weightingTable[m][z] = 0;\n\n\t}\n      }\n    }\n    if(lmNew != NULL)\n      delete lmNew;\n    \n    // Now calculate the weight of each new Gaussian\n    int z = 0;\n    for(z = 0, measurements_it = measurements_it_start; z < nZ; z++, measurements_it++){\n\n      double clutter = this->pMeasurementModel_->clutterIntensity( *measurements_it, nZ );\n      double sum = clutter;\n      for(unsigned int m = 0; m < nM; m++){\n\tsum += weightingTable[m][z];\n      }\n\n      if(config.useClusterProcess_){\n\tlikelihoodProd *= sum;\n      }\n\n      for(unsigned int m = 0; m < nM; m++){\n\tweightingTable[m][z] /= sum;\n      }\n    }\n    if(config.useClusterProcess_){\n      double prev_particle_i_weight = this->particleSet_[i]->getWeight();\n      this->particleSet_[i]->setWeight( exp(w_km_sum) * likelihoodProd);\n    }\n\n\n    // ---------- 3. Add new Gaussians to map  ----------\n    // New Gaussians will have indices >= nM \n    for(int m = 0; m < nM; m++){\n      for(int z = 0; z < nZ; z++){\n\tif(newLandmarkPointer[m][z] != NULL && weightingTable[m][z] > 0){\n\t  (*maps_it)->addGaussian( newLandmarkPointer[m][z], weightingTable[m][z]);  \n\t}\n      }\n    }\n\n    //----------  4. Determine weights for existing Gaussians (missed detection) ----------\n    for(int m = 0; m < nM; m++){\n      \n      double w_km = (*maps_it)->getWeight(m);\n      double w_k = (1 - Pd[m]) * w_km;\n\n      // For landmarks close to sensing limit\n      if (landmarkCloseToSensingLimit[m] == 1){\n\tdouble weight_sum_m = 0;\n\tfor(int z = 0; z < nZ; z++){\n\t  weight_sum_m += weightingTable[m][z];\n\t}\n\tdouble delta_w = Pd[m] * w_km - weight_sum_m;\n\tif( delta_w > 0 ){\n\t  w_k += delta_w;\n\t}\n      }\n\n      (*maps_it)->setWeight(m, w_k);\n    }\n\n    //----------  5. Identify unused measurements for adding birth Gaussians later ----------\n    unused_measurements_it->clear();\n    for(int z = 0; z < nZ; z++){\n      int useCount = 0;\n      for(int m = 0; m < nM; m++){\n\tif (weightingTable[m][z] != 0){\n\t  useCount++;\n\t}\n      }\n      if (useCount == 0)\n\tunused_measurements_it->push_back( z );\n    }\n\n    //----------  6. Cleanup - Free memory ----------\n    delete pose;\n\n    for( int n = 0; n < nM; n++ ){\n      delete[] weightingTable[n];\n      delete[] newLandmarkPointer[n];\n    }\n    delete[] weightingTable;\n    delete[] newLandmarkPointer;\n\n  }\n\n}\n\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nvoid RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::importanceWeighting(){\n\n  for(int i = 0; i < this->nParticles_; i++){\n\n    //printf(\"Importance weighting for particle %d\\n\", i);\n    TPose x;\n    this->particleSet_[i]->getPose( x );\n\n    // 1. select evaluation points from highest-weighted Gaussians after update, that are within sensor FOV\n    const unsigned int nM = maps_[i]->getGaussianCount();\n    int nEvalPoints = config.importanceWeightingEvalPointCount_ > nM ? nM : config.importanceWeightingEvalPointCount_ ;\n    std::vector<unsigned int> evalPointIdx;\n    std::vector<double> evalPointPd;\n    evalPointIdx.reserve(nEvalPoints);\n    evalPointPd.reserve(nEvalPoints);\n    if( nEvalPoints == 0 ){\n      this->particleSet_[i]->setWeight( std::numeric_limits<double>::denorm_min() );\n      continue;\n    }\n    maps_[i]->sortByWeight(); // sort by weight so that we can pick off the top nEvalPoints Gaussians\n    for(int m = 0; m < nM; m++){\n      TLandmark* plm_temp;\n      double w, w_prev;\n      bool closeToSensingLim;\n      maps_[i]->getGaussian(m, plm_temp, w, w_prev);\n      double Pd = this->pMeasurementModel_->probabilityOfDetection(x,*plm_temp, closeToSensingLim);\n      if( Pd > 0 ){\n\tevalPointIdx.push_back(m);\n\tevalPointPd.push_back(Pd);\n      }\n      if(evalPointIdx.size() >= nEvalPoints)\n\tbreak;\n    }\n    nEvalPoints = evalPointIdx.size();\n\n    // 2. evaluate sum of Gaussian weights\n    double gaussianWeightSumBeforeUpdate = 0;\n    double gaussianWeightSumAfterUpdate = 0;\n    for(int m = 0; m < nM; m++){\n      TLandmark* plm_temp;\n      double w, w_prev;\n      maps_[i]->getGaussian(m, plm_temp, w, w_prev); // for newly created Gaussians, w_prev = 0\n      gaussianWeightSumBeforeUpdate += w_prev;\n      gaussianWeightSumAfterUpdate += w;\n      //printf(\"w_[%d] = %f\\n\", i, w);\n    }\n    // Check for NaN\n    if( gaussianWeightSumBeforeUpdate != gaussianWeightSumBeforeUpdate ||\n\tgaussianWeightSumAfterUpdate != gaussianWeightSumAfterUpdate ){\n      //printf(\"Particle %d map size before update = %f\\n\", i, gaussianWeightSumBeforeUpdate);\n      //printf(\"Particle %d map size after update = %f\\n\", i, gaussianWeightSumAfterUpdate);\n    }\n    //printf(\"Particle %d map size after - before update = %f\\n\", i, gaussianWeightSumAfterUpdate - gaussianWeightSumBeforeUpdate);\n    \n    // 3. evaluate intensity function at eval points and take their product\n    double intensityProd_beforeUpdate = 1;\n    double intensityProd_afterUpdate = 1;\n    for(int e = 0; e < nEvalPoints; e++){\n\n      int p = evalPointIdx[e];\n      TLandmark* lm_evalPt;\n      double w_temp;\n      maps_[i]->getGaussian(p, lm_evalPt, w_temp);\n\n      double intensity_at_evalPt_beforeUpdate = std::numeric_limits<double>::denorm_min();\n      double intensity_at_evalPt_afterUpdate = std::numeric_limits<double>::denorm_min();\n\n      for(int m = 0; m < nM; m++){\n\tTLandmark* plm;\n\tdouble w, w_prev;\n\tmaps_[i]->getGaussian(m, plm, w, w_prev);\n\t// New Gaussians from update will have w_prev = 0\n\t// Out Gaussians (missed-detection) will not have been updated, but weights will have changed\n\tdouble likelihood = plm->evalGaussianLikelihood( *lm_evalPt );\n\tintensity_at_evalPt_beforeUpdate += w_prev * likelihood; // w_prev for newly created Gaussians are 0\n\tintensity_at_evalPt_afterUpdate += w * likelihood;\n\t// NaN check\n\tif( likelihood != likelihood || \n\t    intensity_at_evalPt_beforeUpdate != intensity_at_evalPt_beforeUpdate || \n\t    intensity_at_evalPt_afterUpdate != intensity_at_evalPt_afterUpdate){\n\t  printf(\"Particle %d map intensity error for eval point %d\\n\", i, m);\n\t  printf(\"intensity before update = %f\\n\", intensity_at_evalPt_beforeUpdate);\n\t  printf(\"intensity after update = %f\\n\", intensity_at_evalPt_afterUpdate);\n\t}\n      }\n      intensityProd_beforeUpdate *= intensity_at_evalPt_beforeUpdate;\n      intensityProd_afterUpdate *= intensity_at_evalPt_afterUpdate;\n      // NaN Check\n      if( intensityProd_beforeUpdate != intensityProd_beforeUpdate ||\n\t  intensityProd_afterUpdate != intensityProd_afterUpdate ){\n\tprintf(\"Particle %d map intensity product error\\n\", i);\n\tprintf(\"intensity product before update = %f\\n\", intensityProd_beforeUpdate);\n\tprintf(\"intensity product after update = %f\\n\", intensityProd_afterUpdate);\n      } \n    }\n    //printf(\"Particle %d intensity product before / after update = %f\\n\", i, intensityProd_beforeUpdate / intensityProd_afterUpdate);\n\n    // 4. calculate measurement likelihood at eval points\n    // note that rfsMeasurementLikelihood uses maps_[i] which is already sorted by weight\n    double measurementLikelihood = rfsMeasurementLikelihood( i, evalPointIdx, evalPointPd );\n    //printf(\"Particle %d measurement likelihood = %f\\n\", i, measurementLikelihood);\n\n    // 5. calculate overall weight\n    double overall_weight = measurementLikelihood * intensityProd_beforeUpdate / intensityProd_afterUpdate *\n      exp( gaussianWeightSumAfterUpdate - gaussianWeightSumBeforeUpdate); \n    \n    double prev_weight = this->particleSet_[i]->getWeight();\n    this->particleSet_[i]->setWeight( overall_weight * prev_weight );\n    //printf(\"Particle %d overall weight = %f\\n\\n\", i, overall_weight);\n\n  }\n\n}\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\ndouble RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::\nrfsMeasurementLikelihood( const int particleIdx, \n\t\t\t  std::vector<unsigned int> &evalPtIdx,\n\t\t\t  std::vector<double> &evalPtPd ){\n  // eval points are first nEvalPoints elements of maps_[i], which are already ordered by weight; \n\n  const int i = particleIdx;\n  const int nM = evalPtIdx.size();\n  const int nZ = this->measurements_.size();\n\n  // Fill in likelihood table\n  TPose x;\n  this->particleSet_[i]->getPose( x );\n  std::vector< double* > likelihoodTab;\n  likelihoodTab.reserve(nM);\n  for( int m = 0; m < nM; m++ ){\n    \n    double* row = new double[nZ];\n    \n    TLandmark* evalPt; \n    maps_[i]->getGaussian( evalPtIdx[m], evalPt );\n    double Pd = evalPtPd[m];\n    \n    double row_sum = 0;\n    for( int z = 0; z < nZ; z++ ){\n\n      TMeasurement expected_z;\n      this->pMeasurementModel_->measure( x, *evalPt, expected_z);\n      //TMeasurement actual_z = this->measurements_[z];\n      \n      double md2;\n      double threshold = config.importanceWeightingMeasurementLikelihoodMDThreshold_;\n      threshold *= threshold;\n      double likelihood = this->measurements_[z].evalGaussianLikelihood( expected_z, &md2);\n      if( md2 <= threshold ){\n\trow[z] = likelihood * Pd;\n\trow_sum += row[z];\n      }else{\n\trow[z] = 0;\n      }\n      \n    }\n    \n    // Check to see if likelihood to all measurements is 0, if so remove this eval point\n    // as it will not contribute anything to the output likelihood\n    if( row_sum == 0 ){\n      delete[] row;\n    }else{\n      likelihoodTab.push_back(row);\n    }\n    \n  }\n  const int likelihoodTabSizeWithoutClutter = likelihoodTab.size();\n\n  // Check measurements (columns) with 0 likelihood to all eval points\n  // if so, that measurement is considered clutter\n  int nClutter = 0;\n  double clutterLikelihood = 1; // we will multiply the likelihood sum of all d.a. permuations with this at the end\n  std::vector<int> z_noClutter; // we only want the non-clutter measurements when we permutate over all data assocation pairs later\n  z_noClutter.reserve(nZ);\n\n  for( int z = 0; z < nZ; z++ ){\n    double isClutter = true;\n    for( int m = 0; m < likelihoodTab.size(); m++ ){\n      if( likelihoodTab[m][z] > 0 ){\n\tisClutter = false;\n\tbreak;\n      }\n    }\n    if( isClutter ){\n      nClutter++;\n      // TMeasurement actual_z = this->measurements_[z];\n      clutterLikelihood *= this->pMeasurementModel_->clutterIntensity(this->measurements_[z], nZ);;\n    }else{\n      z_noClutter.push_back(z);\n    }\n  }\n\n  // If the number of measurements is greater than the number of\n  // eval points, then some measurements have to be assigned as clutter.\n  // We will add extra rows for these assignments in likelihoodTab\n  double *clutterRow = NULL;\n  int nR = z_noClutter.size() - likelihoodTab.size();\n  if (nR > 0){\n    clutterRow = new double[nZ];\n    for( int z = 0; z < nZ; z++ ){\n      //TMeasurement actual_z = this->measurements_[z];\n      clutterRow[z] = this->pMeasurementModel_->clutterIntensity(this->measurements_[z], nZ);\n    }\n    for( int r = 0; r < nR; r++ ){\n      likelihoodTab.push_back(clutterRow);\n    }\n  }\n\n  // Go through all permutations of eval point - measurement pairs\n  // to calculate the likelihood\n  double likelihood = 0;\n  while (likelihood == 0){\n\n    if( likelihoodTab.size() == 0 ){\n      likelihood = 1;\n      break;\n    }\n\n    likelihood = rfsMeasurementLikelihoodPermutations( likelihoodTab, z_noClutter);\n    if( likelihood != likelihood ){\n      printf(\"RFS Measurement likelihood = %f\", likelihood);\n    } \n\n    if( likelihood == 0 ){\n\n      // Add another row to of clutter to likelihoodTab\n      // printf(\"Adding clutter row for RFS measurement likelihood calculation\\n\");\n      if( clutterRow == NULL ){\n\tclutterRow = new double[nZ];\n\tfor( int z = 0; z < nZ; z++ ){\n\t  //TMeasurement actual_z = this->measurements_[z];\n\t  clutterRow[z] = this->pMeasurementModel_->clutterIntensity(this->measurements_[z], nZ);\n\t}\n      }\n      likelihoodTab.push_back( clutterRow );\n      \n    }\n\n  }\n\n  // Deallocate likelihood table\n  for( int m = 0; m < likelihoodTabSizeWithoutClutter; m++ ){\n    delete[] likelihoodTab[m];\n  }\n  if( clutterRow != NULL )\n    delete[] clutterRow;\n\n  if (nClutter > 0){\n    likelihood /= this->pMeasurementModel_->clutterIntensityIntegral( nZ );\n    likelihood *= clutterLikelihood;\n  }\n\n  return likelihood;\n}\n\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\ndouble RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::\nrfsMeasurementLikelihoodPermutations( std::vector< double* > &likelihoodTab, \n\t\t\t\t      std::vector< int > &Z_NoClutter){\n  // Note that nM is always >= nZ\n  // We will find all eval point permutations of (0, 1, 2, ... , nM - 1)\n  // and use the first nZ of each permutation to calculate the likelihood\n\n  // A function required for sorting\n  struct sort{\n    static bool descend(int i, int j){ return (i > j); }\n  };\n\n  const int nM = likelihoodTab.size();\n  const int nZ = Z_NoClutter.size();\n  double allPermutationLikelihood = 0;\n  bool lastPermutationSequence = false;\n  std::vector<int> currentPermutation(nM);\n  for(int m = 0; m < nM; m++){\n    currentPermutation[m] = m;\n  }\n\n  while( !lastPermutationSequence ){\n\n    // find the likelihood of the current permutation\n    \n    double currentPermutationLikelihood  = 1;\n    for(int z = 0; z < nZ; z++){\n      int m = currentPermutation[ z ];\n      currentPermutationLikelihood *= likelihoodTab[m][ Z_NoClutter[z] ];\n      \n      // Fast-forward permutation if we know that following sequences will also\n      // have 0 likelihood\n      if( currentPermutationLikelihood == 0 && z < nZ - 1){\n\tstd::sort(currentPermutation.begin() + z + 1, currentPermutation.end(), sort::descend);\n\tbreak;\n      }\n    }\n\n    allPermutationLikelihood += currentPermutationLikelihood;\n\n    // Fast-forward if nM > nZ (i.e., the last nM - nZ elements in the permutation sequence does not matter)\n    if( nM > nZ ){\n      std::sort(currentPermutation.begin() + nZ, currentPermutation.end(), sort::descend);\n    }\n\n    // Generate the next permutation sequence\n    for(int m = nM - 2; m >= -1; m--){\n\n      if( m == -1){\n\tlastPermutationSequence = true;\n\tbreak;\n      }\n      \n      // Find the highest index m such that currentPermutation[m] < currentPermutation[m+1]\n      if(currentPermutation[m] < currentPermutation[ m + 1 ]){\n\n\t// Find highest index i such that currentPermutation[i] > currentPermutation[m] \n\t// then swap the elements\n\tfor(int i = nM - 1; i >= 0; i--){\n\t  if( currentPermutation[i] > currentPermutation[m] ){\n\t    int temp = currentPermutation[i];\n\t    currentPermutation[i] = currentPermutation[m];\n\t    currentPermutation[m] = temp;\n\t    break;\n\t  }\n\t}\n\n\t// reverse order of elements after currentPermutation[m]\n\tint nElementsToSwap = nM - (m + 1);\n\tint elementsToSwapMidPt = nElementsToSwap / 2;\n\tint idx1 = m + 1;\n\tint idx2 = nM - 1;\n\tfor(int i = 1; i <= elementsToSwapMidPt; i++){\n\t  int temp = currentPermutation[idx1];\n\t  currentPermutation[idx1] = currentPermutation[idx2];\n\t  currentPermutation[idx2] = temp;\n\t  idx1++;\n\t  idx2--;\n\t}\n\n\tbreak;\n      }\n\n    }\n\n    // now we should have the next permutation sequence\n  }\n\n  return allPermutationLikelihood;\n\n}\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nvoid RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::addBirthGaussians(){\n\n  for(int i = 0; i < this->nParticles_; i++){\n    \n    while( unused_measurements_[i].size() > 0){\n     \n      // get measurement\n      int unused_idx = unused_measurements_[i].back();\n      TMeasurement unused_z = this->measurements_[unused_idx];\n      unused_measurements_[i].pop_back();\n\n      // use inverse measurement model to get landmark\n      TPose robot_pose;\n      TLandmark landmark_pos;\n      this->particleSet_[i]->getPose(robot_pose);\n      this->pMeasurementModel_->inverseMeasure( robot_pose,  unused_z, landmark_pos );\n      \n      // add birth landmark to Gaussian mixture (last param = true to allocate mem)\n      maps_[i]->addGaussian( &landmark_pos, config.birthGaussianWeight_, true);\n      \n    }\n    \n  }\n\n}\n\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nbool RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::checkMapIntegrity(){\n\n  for( int i = 0; i < maps_.size(); i++ ){\n\n    unsigned int nM = maps_[i]->getGaussianCount();\n    for(int m = 0; m < nM; m++){\n\n      TLandmark *lm;\n      typename TLandmark::Vec lm_x;\n      typename TLandmark::Mat lm_S;\n      double w;\n\n      maps_[i]->getGaussian(m, lm, w);\n      if( lm != NULL ){\n\tlm->get(lm_x, lm_S);\n\n\tbool vecError = false;\n\tfor( int c = 0; c < lm_x.rows(); c++){\n\t  if(lm_x(c) != lm_x(c)){\n\t    vecError = true;\n\t    break;\n\t  }\n\t}\n\tif(vecError){\n\t  printf(\"particle %d, landmark index %d, vector error\\n\", i, m);\n\t  std::cout << lm_x << std::endl;\n\t  return false;\n\t}\n\n\tbool matError = false;\n\tfor( int r = 0; r < lm_S.rows(); r++){\n\t  for( int c = 0; c < lm_S.cols(); c++){\n\t    if(lm_S(r,c) != lm_S(r,c)){\n\t      matError = true;\n\t      break;\n\t    }\n\t  }\n\t}\n\tlm_x.setOnes();\n\tdouble posDefCheck = lm_x.transpose() * lm_S * lm_x;\n\tif( posDefCheck != posDefCheck || posDefCheck <= 0){\n\t  matError = true;\n\t}\n\tif(matError){\n\t  printf(\"particle %d, landmark index %d, covariance error\\n\", i, m);\n\t  std::cout << lm_S << std::endl;\n\t  return false;\n\t}\n\n\tif( w != w ){\n\t  printf(\"particle %d, landmark index %d, w = %f\\n\", i, m, w);\n\t  return false;\n\t}\n\n      }\n\n    }\n\n  }\n\n  return true;\n\n}\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nint RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::getGMSize(int i){\n\n  if( i >= 0 && i < maps_.size() )\n    return ( this->maps_[i]->getGaussianCount() );\n  else\n    return -1;\n}\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nbool RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::\ngetLandmark(const int i, const int m, \n\t    typename TLandmark::Vec &u,\n\t    typename TLandmark::Mat &S,\n\t    double &w)\n{\n\n  int sz = getGMSize(i);\n  if( sz == -1 || (m < 0) || (m >= sz) )\n    {\n      return false;\n    }\n    TLandmark *plm;\n    maps_[i]->getGaussian(m, plm, w);\n    plm->get(u, S);\n    return true;\n}\n\n#endif\n\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nvoid RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::\nsetParticlePose(int i, TPose &p){\n  \n  this->particleSet_[i]->setPose(p);\n\n}\n\n\ntemplate< class RobotProcessModel, class LmkProcessModel, class MeasurementModel, class KalmanFilter >\nKalmanFilter* RBPHDFilter< RobotProcessModel, LmkProcessModel, MeasurementModel, KalmanFilter >::getKalmanFilter(){\n  return kfPtr_;\n}\n", "meta": {"hexsha": "a937eb2d7b2411c3d31978181c2273609b2ac4b6", "size": 37857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/RBPHDFilter.hpp", "max_stars_repo_name": "szma/RFS-SLAM", "max_stars_repo_head_hexsha": "def8f1e8cc788bbe4347cd57f79061f70b0b41dd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T04:15:16.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T04:15:16.000Z", "max_issues_repo_path": "include/RBPHDFilter.hpp", "max_issues_repo_name": "szma/RFS-SLAM", "max_issues_repo_head_hexsha": "def8f1e8cc788bbe4347cd57f79061f70b0b41dd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/RBPHDFilter.hpp", "max_forks_repo_name": "szma/RFS-SLAM", "max_forks_repo_head_hexsha": "def8f1e8cc788bbe4347cd57f79061f70b0b41dd", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9524663677, "max_line_length": 134, "alphanum_fraction": 0.6839422036, "num_tokens": 9932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.23818812057617447}}
{"text": "#include <ceres/ceres.h> \n#include <iostream>\n#include<time.h>\n#include <sophus/se3.hpp>\n\n#include \"local_parameterization_se3.hpp\" \n   \n#include \"glog/logging.h\"\n#include <vector>\n#include <fstream>\n#include <Eigen/Core> \n\n#include <iomanip>\n#include <algorithm>\n#include<math.h>\n\n// #define NUM_PAIRS 200\n// #define NUM_PAIRS_NEEDED 50\n// #define NUM_LOOPS_NEEDED 1770\n// #define NUM_CAMERAS 1770\n\n#define SIGMA 0.5\n#define NUM_ITERATION_EM 50\n#define PI 3.1415926535897\n#define Median_inlier_loss   3                //调节公式(13)中的圆符号\n\n#define PARETO_ALPHA 1\n\n#define ZIQUAN true\n#define NUM_FEATURE_MATCHES_PER_CONSTRAINT 200\n#define TRUST_ODOMETRY 0.9\n\n// typedef std::pair< int, int > IntPair;\ntypedef Eigen::Matrix< double, 6, 6, Eigen::RowMajor > InformationMatrix;\ntypedef Eigen::Matrix< double, 6, 1> Vector6d;\ntypedef Eigen::Matrix< double, Eigen::Dynamic, 7, Eigen::RowMajor > PairMatrix;\n\nusing ceres::AutoDiffCostFunction;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solver;\nusing ceres::Solve;\n\n/*\n  ZHOU's convension\n*/\nstd::vector<std::vector<double>>  semantic_p;    //保存语义混淆矩阵\n\n\n  void LoadFromFile_semantic_p(const char*  filename ) {\n    semantic_p.clear();\n    semantic_p.resize(24);\n    for(int i=0;i<24;i++)\n    {\n      semantic_p[i].resize(24);\n    }\n    FILE * f = fopen( filename, \"r\" );\n    int i=0;\n    if ( f != NULL ) {\n      char buffer[1024];\n      while ( fgets( buffer, 1024, f ) != NULL &&i<24) \n      {\n        if ( strlen( buffer ) > 0 && buffer[ 0 ] != '#' ) \n        {\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf\",  \\\n           &semantic_p[i][0],&semantic_p[i][1],&semantic_p[i][2], &semantic_p[i][3], &semantic_p[i][4], &semantic_p[i][5],\\\n          &semantic_p[i][6],&semantic_p[i][7],&semantic_p[i][8], &semantic_p[i][9], &semantic_p[i][10], &semantic_p[i][11],\\\n          &semantic_p[i][12],&semantic_p[i][13],&semantic_p[i][14], &semantic_p[i][15], &semantic_p[i][16], &semantic_p[i][17],\\\n          &semantic_p[i][18],&semantic_p[i][19],&semantic_p[i][20], &semantic_p[i][21], &semantic_p[i][22], &semantic_p[i][23]);\n        }\n        i++;\n      }\n      fclose( f );\n    }\n  }\n\nstruct FramedMatches {\n  int id1_;\n  int id2_;\n  int frame_;\n  int old_correspondence_num_;\n  int new_correspondence_num_;\n  float ratio_;\n  Eigen::Matrix4d transformation_;\n  std::vector< std::pair<Eigen::Vector3d, Eigen::Vector3d> > pairs_;\n  std::vector<int> semantic_label;          //存储每个点对 语义是否对应的标志位\n  std::vector<int> label_one_;         //每对对应点第一个点的语义标签值\n  std::vector<int> label_two_;        //每对对应点第二个点的语义标签值\n  FramedMatches( int id1, int id2, int f, int old_cor,int new_cor,float ratio,Eigen::Matrix4d trans, PairMatrix pairs,int label_one,int label_two)\n  : id1_(id1), id2_(id2), frame_(f), old_correspondence_num_(old_cor),new_correspondence_num_(new_cor),ratio_(ratio),transformation_(trans)\n  {\n    std::cout<<\"here\"<<std::endl;\n    int num_pairs = pairs.rows();\n    pairs_.resize(num_pairs);\n    semantic_label.resize(num_pairs);\n    label_one_.resize(num_pairs);\n    label_two_.resize(num_pairs);\n    for (int i = 0; i < num_pairs;  i++) {\n      pairs_[i] = std::make_pair(Eigen::Vector3d(pairs(i,0), pairs(i,1), pairs(i,2)), \n                                 Eigen::Vector3d(pairs(i,3), pairs(i,4), pairs(i,5)));\n      semantic_label[i]=pairs(i,6);\n      label_one_[i]=label_one;\n      label_two_[i]=label_two;\n    }\n  }\n};\n\nstruct PCLMatches {\n  std::vector< FramedMatches > data_;\n\n  void LoadFromFile(const char* filename) {// , int num = -1, float min_ratio = -1) {\n    //std::cout<<\"here\"<<std::endl;\n    data_.clear();\n    int id1, id2, frames=22, old_correspondence_num, new_correspondence_num;\n    float ratio;\n    Eigen::Matrix4d trans;\n    PairMatrix pairs;\n    int label_one,label_two;   //记录每对对应点的语义标签值\n    FILE * f = fopen( filename, \"r\" );\n    if ( f != NULL ) {\n      char buffer[1024];\n      // int counter = 0;\n      // while ( (num < 0 || counter <= num) && fgets( buffer, 1024, f ) != NULL ) {\n      while ( fgets( buffer, 1024, f ) != NULL ) {\n        if ( strlen( buffer ) > 0 && buffer[ 0 ] != '#' ) {\n          // if (ZIQUAN) {       ratio=new_correspondence_num/old_correspondence_num\n            sscanf( buffer, \"%d %d %d %d %f\", &id1, &id2, &old_correspondence_num, &new_correspondence_num, &ratio);\n          // } else {\n            // sscanf( buffer, \"%d %d %d %d %d %f\", &id1, &id2, &frames, &count_in, &count_out, &ratio);\n          // }\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(0,0), &trans(0,1), &trans(0,2), &trans(0,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(1,0), &trans(1,1), &trans(1,2), &trans(1,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(2,0), &trans(2,1), &trans(2,2), &trans(2,3) );\n          trans(3,0) = 0; trans(3,1) = 0; trans(3,2) = 0; trans(3,3) = 1;\n          // if (ZIQUAN) {\n          //   count_in = 200;\n          // }\n          pairs.resize(old_correspondence_num, 7);\n          \n          for (int i = 0; i < old_correspondence_num; i++) {\n            fgets( buffer, 1024, f );\n            sscanf( buffer, \"%lf %lf %lf %lf %lf %lf %lf %d %d\", &pairs(i,0), &pairs(i,1), &pairs(i,2), &pairs(i,3), \\\n                                                           &pairs(i,4), &pairs(i,5), &pairs(i,6),&label_one,&label_two);\n          }\n          // if (ratio > min_ratio) {\n            std::cout << \"here\" << std::endl;\n            data_.push_back( FramedMatches( id1, id2, frames, old_correspondence_num,new_correspondence_num,ratio,trans, pairs ,label_one,label_two) );\n            // counter ++ ;\n          // }\n          std::cout << id1 << \" and \" << id2  << std::endl;\n        }\n      }\n      fclose( f );\n    }\n  }\n};\n\nstruct FramedTransformation {\n  int id1_;\n  int id2_;\n  int frame_;\n  Eigen::Matrix4d transformation_;      // pose\n  Sophus::SE3d transformation_se3_;     // useful for both pose and link\n  // std::vector< std::pair<Eigen::Vector3d, Eigen::Vector3d> > pairs_;\n\n  FramedTransformation( int id1, int id2, int f, Eigen::Matrix4d t)\n    : id1_( id1 ), id2_( id2 ), frame_( f ), transformation_( t ) \n  {\n    Eigen::Quaterniond q;\n    q = t.block<3,3>(0,0);\n    transformation_se3_ = Sophus::SE3d(q, Sophus::SE3d::Point(t(0,3), t(1,3), t(2,3)));\n    // pairs_.resize(NUM_PAIRS_NEEDED);\n    // for (int i = 0; i < NUM_PAIRS_NEEDED; i++) {\n    //   pairs_[i] = std::make_pair(Eigen::Vector3d(pairs(i,0), pairs(i,1), pairs(i,2)), \n    //                              Eigen::Vector3d(pairs(i,3), pairs(i,4), pairs(i,5)));\n    // }\n  }\n\n  // only use this constructer to check for convergence\n  FramedTransformation(int id1, int id2, int f, Sophus::SE3d t)\n    : id1_( id1 ), id2_( id2 ), frame_( f ), transformation_se3_( t ) \n    {\n      transformation_ = t.matrix();\n    }\n};\n\nstruct PCLTrajectory {\n  std::vector< FramedTransformation > data_;\n  int index_;\n\n  void LoadFromFile(const char* filename ) {\n    data_.clear();\n    index_ = 0;\n    int id1, id2, frame;\n    Eigen::Matrix4d trans;\n    FILE * f = fopen( filename, \"r\" );\n    if ( f != NULL ) {\n      char buffer[1024];\n      int i=0;\n      while ( fgets( buffer, 1024, f ) != NULL ) {\n        if ( strlen( buffer ) > 0 && buffer[ 0 ] != '#' ) {\n          sscanf( buffer, \"%d %d %d\", &id1, &id2, &frame);\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(0,0), &trans(0,1), &trans(0,2), &trans(0,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(1,0), &trans(1,1), &trans(1,2), &trans(1,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(2,0), &trans(2,1), &trans(2,2), &trans(2,3) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf\", &trans(3,0), &trans(3,1), &trans(3,2), &trans(3,3) );\n          data_.push_back( FramedTransformation( id1, id2, frame, trans ) );\n          i++;\n          // trans(3,0) = 0; trans(3,1) = 0; trans(3,2) = 0; trans(3,3) = 1;\n          // for (int i = 0; i < NUM_PAIRS; i++) {\n          //   fgets( buffer, 1024, f );\n          //   sscanf( buffer, \"%lf %lf %lf %lf %lf %lf %lf\", &pairs(i,0), &pairs(i,1), &pairs(i,2), &pairs(i,3), \n          //                                                  &pairs(i,4), &pairs(i,5), &pairs(i,6));\n          // }\n          // if (ratio > min_ratio) {\n          //   data_.push_back( FramedTransformation( id1, id2, 1770, trans ) );\n          //   counter ++ ;\n          // }\n          // std::cout << id1 << \"\\t\" << id2  << std::endl;\n        }\n      }\n      std::cout << \"pose num is:\"<<data_.size()  << std::endl;\n      std::cout << \"i is:\"<<i  << std::endl;\n      fclose( f );\n    }\n  }\n\n  void SaveToFile(const char* filename ) {\n    FILE * f = fopen( filename, \"w\" );\n    for ( int i = 0; i < ( int )data_.size(); i++ ) {\n      Sophus::SE3d trans_se3 = data_[ i ].transformation_se3_;\n      Eigen::Matrix4d trans = trans_se3.matrix();\n      fprintf( f, \"%d\\t%d\\t%d\\n\", data_[ i ].id1_, data_[ i ].id2_, data_[ i ].frame_ );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(0,0), trans(0,1), trans(0,2), trans(0,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(1,0), trans(1,1), trans(1,2), trans(1,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(2,0), trans(2,1), trans(2,2), trans(2,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(3,0), trans(3,1), trans(3,2), trans(3,3) );\n    }\n    fclose( f );\n  }\n\n};\n\nstruct FramedInformation {\n  int id1_;\n  int id2_;\n  int frame_;\n  InformationMatrix information_;\n  FramedInformation( int id1, int id2, int f, InformationMatrix t )\n    : id1_( id1 ), id2_( id2 ), frame_( f ), information_( t ) \n  {}\n};\n\nstruct PCLInformation {\n  std::vector< FramedInformation > data_;\n\n  void LoadFromFile(const char*  filename ) {\n    data_.clear();\n    int id1, id2, frame;\n    InformationMatrix info;\n    FILE * f = fopen( filename, \"r\" );\n    if ( f != NULL ) {\n      char buffer[1024];\n      while ( fgets( buffer, 1024, f ) != NULL ) {\n        if ( strlen( buffer ) > 0 && buffer[ 0 ] != '#' ) {\n          sscanf( buffer, \"%d %d %d\", &id1, &id2, &frame);\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(0,0), &info(0,1), &info(0,2), &info(0,3), &info(0,4), &info(0,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(1,0), &info(1,1), &info(1,2), &info(1,3), &info(1,4), &info(1,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(2,0), &info(2,1), &info(2,2), &info(2,3), &info(2,4), &info(2,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(3,0), &info(3,1), &info(3,2), &info(3,3), &info(3,4), &info(3,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(4,0), &info(4,1), &info(4,2), &info(4,3), &info(4,4), &info(4,5) );\n          fgets( buffer, 1024, f );\n          sscanf( buffer, \"%lf %lf %lf %lf %lf %lf\", &info(5,0), &info(5,1), &info(5,2), &info(5,3), &info(5,4), &info(5,5) );\n          data_.push_back( FramedInformation( id1, id2, frame, info ) );\n          // std::cout << id1 << \"\\t\" << id2  << std::endl;\n        }\n      }\n      fclose( f );\n    }\n  }\n};\n\n\n// Eigen's ostream operator is not compatible with ceres::Jet types.\n// In particular, Eigen assumes that the scalar type (here Jet<T,N>) can be\n// casted to an arithmetic type, which is not true for ceres::Jet.\n// Unfortunatly, the ceres::Jet class does not define a conversion\n// operator (http://en.cppreference.com/w/cpp/language/cast_operator).\n//\n// This workaround creates a template specilization for Eigen's cast_impl,\n// when casting from a ceres::Jet type. It relies on Eigen's internal API and\n// might break with future versions of Eigen.\nnamespace Eigen {\nnamespace internal {\n\ntemplate <class T, int N, typename NewType>\nstruct cast_impl<ceres::Jet<T, N>, NewType> {\n  EIGEN_DEVICE_FUNC\n  static inline NewType run(ceres::Jet<T, N> const& x) {\n    return static_cast<NewType>(x.a);\n  }\n};\n\n}  // namespace internal\n}  // namespace Eigen\n\nstruct TestSE3CostFunctor {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  TestSE3CostFunctor(Sophus::SE3d T_aw) : T_aw(T_aw) {}\n\n  template <class T>\n  bool operator()(T const* const sT_wa, T* sResiduals) const {\n    Eigen::Map<Sophus::SE3<T> const> const T_wa(sT_wa);\n    Eigen::Map<Eigen::Matrix<T, 6, 1> > residuals(sResiduals);\n\n    // We are able to mix Sophus types with doubles and Jet types withou needing\n    // to cast to T.\n    residuals = (T_aw * T_wa).log();\n    // std::cout << residuals << std::endl;\n\n    // Reverse order of multiplication. This forces the compiler to verify that\n    // (Jet, double) and (double, Jet) SE3 multiplication work correctly.\n    // residuals = (T_wa * T_aw).log();\n\n    // Finally, ensure that Jet-to-Jet multiplication works.\n    // residuals = (T_wa * T_aw.cast<T>()).log();\n    return true;\n  }\n\n  Sophus::SE3d T_aw;\n};\n\nstruct TestPointCostFunctor {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  TestPointCostFunctor(Sophus::SE3d T_aw, Eigen::Vector3d point_a)\n      : T_aw(T_aw), point_a(point_a) {}\n\n  template <class T>\n  bool operator()(T const* const sT_wa, T const* const spoint_b,\n                  T* sResiduals) const {\n    using Vector3T = Eigen::Matrix<T, 3, 1>;\n    Eigen::Map<Sophus::SE3<T> const> const T_wa(sT_wa);\n    Eigen::Map<Vector3T const> point_b(spoint_b);\n    Eigen::Map<Vector3T> residuals(sResiduals);\n\n    // Multiply SE3d by Jet Vector3.\n    Vector3T point_b_prime = T_aw * point_b;\n    // Ensure Jet SE3 multiplication with Jet Vector3.\n    // point_b_prime = T_aw.cast<T>() * point_b;\n\n    // Multiply Jet SE3 with Vector3d.\n    Vector3T point_a_prime = T_wa * point_a;\n    // Ensure Jet SE3 multiplication with Jet Vector3.\n    // point_a_prime = T_wa * point_a.cast<T>();\n\n    residuals = point_b_prime - point_a_prime;\n    return true;\n  }\n\n  Sophus::SE3d T_aw;\n  Eigen::Vector3d point_a;\n};\n\n\nstruct GaussianFunctor {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  GaussianFunctor(Sophus::SE3d trans_next_to_current, InformationMatrix info, int id1, int id2) \n  : trans_next_to_current_(trans_next_to_current), info_(info), id1_(id1), id2_(id2) {}\n\n  template <typename T> \n  bool operator()(T const* const sT_current, T const* const sT_next, \n                  T* residual) const {\n    // using Vector3T = Eigen::Matrix<T, 3, 1>;\n    Eigen::Map<Sophus::SE3<T> const> const T_current(sT_current);\n    Eigen::Map<Sophus::SE3<T> const> const T_next(sT_next);\n    // Eigen::Map<Vector3T> residuals(sResiduals);\n\n    // Eigen::Matrix<T,4,4> M_xi = (trans_next_to_current_ * T_next.inverse() * T_current).matrix();\n    Sophus::SE3<T> xi_7T = trans_next_to_current_ \n                          * T_next.inverse() \n                          * T_current;\n\n    Eigen::Matrix<T,6,1> xi;\n    // xi << M_xi(0,3), M_xi(1,3), M_xi(2,3), q.x(), q.y(), q.z();\n    xi << xi_7T.data()[4], xi_7T.data()[5], xi_7T.data()[6], xi_7T.data()[0], xi_7T.data()[1], xi_7T.data()[2];\n\n    Eigen::Matrix<T,1,1> sq_error = xi.transpose() * info_ * xi;\n    // double sq_error = (xi.transpose() * info_ * xi)[0];\n    \n    residual[0] = T( sqrt(sq_error(0,0)) );\n    // residual[0] = T( sqrt(sq_error(0,0) / T(2.)) / T(SIGMA) );\n\n    // std::cout << id1_ << \", \" << id2_ << \" : \" << residual[0] << std::endl;\n    return true;\n  }\n\nprivate:\n  const Sophus::SE3d trans_next_to_current_;\n  const InformationMatrix info_;\n  const int id1_, id2_;\n};\n\nstruct CauchyFunctor {\n  EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n  CauchyFunctor(Eigen::Vector3d point_p, Eigen::Vector3d point_q, \n                int id1, int id2) \n  : point_p_(point_p), point_q_(point_q),\n    id1_(id1), id2_(id2) {}\n\n  template <typename T> \n  bool operator()(T const* const sT_current, T const* const sT_next, \n                  T* sResiduals) const {\n    // using Vector3T = Eigen::Matrix<T, 3, 1>;\n    Eigen::Map<Sophus::SE3<T> const> const T_current(sT_current);\n    Eigen::Map<Sophus::SE3<T> const> const T_next(sT_next);\n    Eigen::Map<Eigen::Matrix<T, 3, 1> > residuals(sResiduals);\n\n    residuals = (T_current * point_p_ - T_next * point_q_);\n\n    return true;\n  }\n\nprivate:\n  const Eigen::Vector3d point_p_, point_q_;\n  const int id1_, id2_;\n};\n\nclass R2EM_CauchyUniform {\npublic:\n  // lambda\n  double lambda_;\n  double U;\n  // double u_;\n  Eigen::Matrix<double, 6, 6> covarance_;\n\n  // read from file\n  // PCLTrajectory odometry_log_;\n  // PCLInformation odometry_info_;\n  PCLMatches odometry_txt_;\n  // PCLTrajectory loop_log_;\n  PCLMatches loop_txt_;\n  // PCLInformation loop_info_;\n\n  // blocks for ceres\n  PCLTrajectory camera_poses_;\n  std::vector< std::vector<double> > L_;\n  double sum_L_;\n\n  // convergence condition\n  double last_lambda_;\n  PCLTrajectory last_camera_poses_;\n  Eigen::Matrix<double, 6, 6> last_covarance_;\n\n  R2EM_CauchyUniform(double lambda)\n  : lambda_(lambda) {\n    last_lambda_ = -1.;\n  }\n\n  ~R2EM_CauchyUniform() {}\n\n  // void LoadOdometryLog(const char* filename) {\n  //   odometry_log_.LoadFromFile(filename);\n  // }\n\n  // void LoadOdometryInfo(const char* filename) {\n  //   odometry_info_.LoadFromFile(filename);\n  // }\n\n  void LoadOdometryTxt(const char* filename) {\n    odometry_txt_.LoadFromFile(filename);//, -1);\n  }\n\n  void LoadLoopTxt(const char* filename) {\n    loop_txt_.LoadFromFile(filename);//, -1);\n  }\n\n  // void LoadLoopInfo(const char* filename) {\n  //   loop_info_.LoadFromFile(filename);\n  // }\n\n  void InitCameraPosesWithZhou(const char* filename) {\n    camera_poses_.LoadFromFile(filename);\n    L_.resize(NumPoses());\n    for (int i = 0; i < NumPoses(); i++) {\n      L_[i].resize(NumPoses());\n    }\n  }\n\n  void InitCameraPoses() {\n    camera_poses_.data_.clear();\n    camera_poses_.index_ = 0;\n    Eigen::Matrix4d pose = Eigen::Matrix4d::Identity();\n    camera_poses_.data_.push_back( FramedTransformation( 0, 0, 1, pose ) );\n\n    for( std::vector< FramedMatches >::iterator it = odometry_txt_.data_.begin();\n      it != odometry_txt_.data_.end(); it ++)\n    {      \n      pose = pose * it->transformation_; \n      camera_poses_.data_.push_back( FramedTransformation( it->id2_, it->id2_, it->id2_ + 1, pose ) );\n    }\n    // std::cout << \"odometry_log_.data_.size(): \" << odometry_log_.data_.size() << std::endl;\n\n    L_.resize(NumPoses());\n    for (int i = 0; i < NumPoses(); i++) {\n      L_[i].resize(NumPoses());\n    }\n\n  }; \n\n  void SaveCameraPoses(const char* filename) {\n    camera_poses_.SaveToFile(filename);\n  }\n\n  void EstimateLAMBDA() {\n\n    std::cout << \"In EstimateLAMBDA : \" << NumOdometryConstraints() << std::endl;\n    std::vector<double> average_loss(NumOdometryConstraints());\n    std::vector<double> total_loss(NumOdometryConstraints());\n    for (int i = 0; i < NumOdometryConstraints(); i ++) {\n\n      FramedMatches match = odometry_txt_.data_[i];\n      // FramedInformation info = odometry_info_.data_[i];\n\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n\n      std::cout << \"In EstimateLAMBDA : \" << i << \"th OdometryConstraint \" << id1 << \" with \" << id2 << std::endl;\n\n      Eigen::Quaterniond q;\n      q = match.transformation_.block<3,3>(0,0);\n      Sophus::SE3d transformation_se3_ = Sophus::SE3d(q, Sophus::SE3d::Point(match.transformation_(0,3), match.transformation_(1,3), match.transformation_(2,3)));\n      \n      // compute the sum of cauchy loss\n      double sum_cauchy_loss = 0.;\n      for (std::size_t j = 0; j < match.pairs_.size(); j++) {\n        Eigen::Vector3d vec_d = camera_poses_.data_[id1].transformation_se3_ * match.pairs_[j].first \n                              - camera_poses_.data_[id2].transformation_se3_ * match.pairs_[j].second;\n        sum_cauchy_loss += log (1. + vec_d.squaredNorm() / (SIGMA * SIGMA));\n        // std::cout << j << \"/\" << loop_log_.data_.size() << \" : \" << sum_cauchy_loss << std::endl;\n      }\n      assert(match.pairs_.size() > 0);\n      average_loss[i] = sum_cauchy_loss / match.pairs_.size();\n      total_loss[i] = sum_cauchy_loss;\n      std::cout << \"match.pairs_.size() is \" << match.pairs_.size() << '\\n';\n      std::cout << \"sum_cauchy_loss \" << sum_cauchy_loss << '\\n';\n      std::cout << \"average_loss[i] \" << average_loss[i] << '\\n';\n    }\n\n    for (int i = 0; i < NumOdometryConstraints(); i ++) {\n      FramedMatches match = odometry_txt_.data_[i];\n      // FramedInformation info = odometry_info_.data_[i];\n\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n\n      // double expterm = exp( - log(U) + (1. + PARETO_ALPHA) * log(average_loss[i]));\n      double expterm = exp( - log(U) + (1. + PARETO_ALPHA) * (average_loss[i]));\n      // L_[id1][id2] = 1./ (1. + expterm);\n      std::cout << \"(\" << std::setw(3) << id1 << \",\" << std::setw(3) << id2 << \") : \" \n                << std::setw(15) << average_loss[i] << \"(\" <<  total_loss[i] << \")\"\n                << std::setw(15) << average_loss[i] * average_loss[i]\n                << std::setw(15) << expterm <<  \" --> \"\n                << std::setw(15) << 1./ (1. + expterm)\n                << std::setw(15) << match.pairs_.size()\n                // << std::setw(15) << U_big\n                << std::endl;\n    }\n    std::nth_element(average_loss.begin(), average_loss.begin() + average_loss.size()/2, average_loss.end());\n    std::nth_element(total_loss.begin(), total_loss.begin() + total_loss.size()/2, total_loss.end());\n    // double median_inlier_loss = average_loss[average_loss.size()/2];\n    \n    double median_inlier_loss = exp(2 * average_loss[average_loss.size()/2]);\n    std::cout << \"average_loss[average_loss.size()/2] \" << average_loss[average_loss.size()/2] << '\\n';\n\n    // double median_total_loss = total_loss[average_loss.size()/2];\n    std::cout << \"The median is \" << median_inlier_loss << '\\n';\n    // U =  TRUST_ODOMETRY / (1-TRUST_ODOMETRY) * median_inlier_loss * median_inlier_loss;\n    U =  TRUST_ODOMETRY / (1-TRUST_ODOMETRY) * median_inlier_loss;\n    // double U_big =  TRUST_ODOMETRY / (1-TRUST_ODOMETRY) * median_total_loss * median_total_loss;\n\n  }\n\n  void SaveLinks(const char* filename) {\n    FILE * f = fopen( filename, \"w\" );\n\n    for ( int i = 0; i < NumOdometryConstraints(); i++ ) {\n      Eigen::Matrix4d trans = odometry_txt_.data_[ i ].transformation_;\n      // Eigen::Matrix4d trans = trans_se3.matrix();\n      fprintf( f, \"%d\\t%d\\t%d\\n\", odometry_txt_.data_[ i ].id1_, odometry_txt_.data_[ i ].id2_, odometry_txt_.data_[ i ].frame_ );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(0,0), trans(0,1), trans(0,2), trans(0,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(1,0), trans(1,1), trans(1,2), trans(1,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(2,0), trans(2,1), trans(2,2), trans(2,3) );\n      fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(3,0), trans(3,1), trans(3,2), trans(3,3) );\n    }\n\n    for (int i = 0; i < NumLoopClosureConstraints(); i++ ) {\n      Eigen::Matrix4d trans = loop_txt_.data_[ i ].transformation_;\n      int id1 = loop_txt_.data_[ i ].id1_;\n      int id2 = loop_txt_.data_[ i ].id2_;\n      assert(id1 < id2);\n      if (id1 != id2 - 1 && L_[id1][id2] > 0.8 * TRUST_ODOMETRY) {\n        fprintf( f, \"%d\\t%d\\t%d\\n\", loop_txt_.data_[ i ].id1_, loop_txt_.data_[ i ].id2_, loop_txt_.data_[ i ].frame_ );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(0,0), trans(0,1), trans(0,2), trans(0,3) );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(1,0), trans(1,1), trans(1,2), trans(1,3) );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(2,0), trans(2,1), trans(2,2), trans(2,3) );\n        fprintf( f, \"%.8f %.8f %.8f %.8f\\n\", trans(3,0), trans(3,1), trans(3,2), trans(3,3) );\n      }\n    }\n    fclose( f );\n  }\n\n// Expectation steps\n  void Expectation(int iteration_num) {\n    \n    sum_L_ = 0.;\n    std::vector<int> healthy_counter(20);\n    for (int ii = 0; ii < 20; ii ++) {\n      healthy_counter[ii] = 0;\n    }\n\n  int maxnum_loop_corres=0;\n  //寻找所有loop中最大对应点对数\n  for (int i = 0; i < NumLoopClosureConstraints(); i ++) \n  {\n    FramedMatches match = loop_txt_.data_[i];\n    if(match.old_correspondence_num_>maxnum_loop_corres)\n    {\n      maxnum_loop_corres = match.old_correspondence_num_;\n    }  \n  }\n\n    for (int i = 0; i < NumLoopClosureConstraints(); i ++) {\n\n      FramedMatches match = loop_txt_.data_[i];\n      // FramedTransformation trans = loop_log_.data_[i];\n      // FramedInformation info = loop_info_.data_[i];\n\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n      // std::cout << id1 << \" ? \" << id2 <<std::endl;\n\n      // compute the sum of cauchy loss\n      double sum_cauchy_loss = 0.;\n      for (std::size_t j = 0; j < match.pairs_.size(); j++) {\n        \n        Eigen::Vector3d vec_d = camera_poses_.data_[id1].transformation_se3_ * match.pairs_[j].first \n                              -camera_poses_.data_[id2].transformation_se3_ * match.pairs_[j].second;\n\n          sum_cauchy_loss += log (1. + vec_d.squaredNorm() / (SIGMA * SIGMA));\n\n        // std::cout << j << \"/\" << loop_log_.data_.size() << \" : \" << sum_cauchy_loss << std::endl;\n      }\n      if (match.pairs_.size() > 0) {\n        sum_cauchy_loss /= match.pairs_.size();\n      }\n\n      // double expterm = exp( - log(U) + (1. + PARETO_ALPHA) * log(sum_cauchy_loss));\n      // L_[id1][id2] = 1./ (1. + expterm);\n      \n      // U =  TRUST_ODOMETRY / (1-TRUST_ODOMETRY) * Median_inlier_loss;\n      L_[id1][id2] = U / (U + exp(2 * sum_cauchy_loss));\n\n      //对于两幅地图的配准，在第一次EM迭代时，所有loop-closure的概率都设为1。第一次迭代仍然考虑语义正确点对占比的因素。\n      // if(iteration_num ==0) L_[id1][id2]=1;\n\n      //ADD BY YUJIE\n      //  if(match.ratio_<0.5 ) L_[id1][id2]=L_[id1][id2]*match.ratio_;\n      //match.ratio_用高斯函数表示，达到这样的效果：当match.ratio较小时：0.2，高斯函数值很小，为0.04；当match.ratio较大时：0.5，高斯函数值较大，为0.28\n        \n          // L_[id1][id2]=L_[id1][id2]*exp(-(match.ratio_-1)*(match.ratio_-1)/(2*0.1));    \n        // std::cout << \"match.ratio\"   << match.ratio_ <<std::endl; \n        // std::cout << \"gaussian_of_match.ratio\"   << exp(-(match.ratio_-1)*(match.ratio_-1)/(2*0.1)) <<std::endl; \n      // L_[id1][id2]=L_[id1][id2]*match.old_correspondence_num_/maxnum_loop_corres;                                                                                                              \n\n      std::cout << \"(\" << std::setw(3) << id1 << \",\" << std::setw(3) << id2 << \") : \" \n                << std::setw(15) << sum_cauchy_loss\n                << std::setw(15) << sum_cauchy_loss * sum_cauchy_loss\n                // << std::setw(15) << expterm <<  \" --> \"\n                << std::setw(15) << exp(2 * sum_cauchy_loss / match.pairs_.size()) <<  \" --> \"\n                << std::setw(15) <<  L_[id1][id2]\n                << std::endl;\n\n      for (int ii = 0; ii < 20; ii ++) {\n        if (L_[id1][id2] > 0.05 * ii && L_[id1][id2] <= 0.05 * (ii+1)){\n          healthy_counter[ii] ++;\n        } \n      }\n      \n      sum_L_ += L_[id1][id2];\n    }\n\n    std::cout << \"\\t\\tsum_L_ is \" << sum_L_ << std::endl;\n    std::cout << \"\\t\\tHealthy is \";\n    for (int ii = 0; ii < 20; ii ++) {\n       std::cout << \"\\t(\" << (0.05 * ii) << \")\\t\" << healthy_counter[ii] ;\n    }\n    std::cout << \"\\t(1.0)\\t\" << std::endl;\n    std::cout << \"\\t\\tTotal is \" << NumLoopClosureConstraints() << std::endl;\n    std::cout << \"\\t\\testimated LAMBDA is \" << U << std::endl;\n  }\n\n  void Maximization() {\n    last_lambda_ = lambda_;\n    last_camera_poses_.index_ = camera_poses_.index_;\n    last_camera_poses_.data_.clear();\n    for (int i = 0; i < NumPoses(); i++) {\n      last_camera_poses_.data_.push_back( \n        FramedTransformation (camera_poses_.data_[i].id1_, \n                              camera_poses_.data_[i].id2_, \n                              camera_poses_.data_[i].frame_,\n                              camera_poses_.data_[i].transformation_se3_));\n    }\n    camera_poses_.index_ ++;\n    // last_covarance_ = covarance_;\n\n    // Maximize lambda\n    lambda_ = sum_L_ / NumLoopClosureConstraints();\n\n    // Maximize pose\n    // Build the problem.\n    ceres::Problem problem;\n\n    // Specify local update rule for our parameter\n    for (std::vector< FramedTransformation >::iterator it = camera_poses_.data_.begin(); \n         it != camera_poses_.data_.end(); it++ ) {\n      problem.AddParameterBlock(it->transformation_se3_.data(), Sophus::SE3d::num_parameters,\n                                new Sophus::test::LocalParameterizationSE3);\n    }\n\n    // Create and add cost functions. Derivatives will be evaluated via\n    // automatic differentiation                                //YUJIE暂时不对odometry进行优化\n    for (int i = 0; i < NumOdometryConstraints(); i++) \n    {\n\n      // FramedTransformation trans = odometry_log_.data_[i];\n      // FramedInformation info = odometry_info_.data_[i];\n      \n      // assert(trans.id1_ == info.id1_ && trans.id2_ == info.id2_ && trans.id1_ < trans.id2_);\n      // int id1 = info.id1_;\n      // int id2 = info.id2_;\n\n      // if (info.information_(0,0) <= 1)\n      //   continue;\n\n      // ceres::CostFunction* cost_odometry =\n      //     new ceres::AutoDiffCostFunction<GaussianFunctor, 1,\n      //                                     Sophus::SE3d::num_parameters,\n      //                                     Sophus::SE3d::num_parameters>(\n      //         new GaussianFunctor(trans.transformation_se3_, info.information_, id1, id2));\n      // problem.AddResidualBlock(cost_odometry, NULL, \n      //                          camera_poses_.data_[id1].transformation_se3_.data(), \n      //                          camera_poses_.data_[id2].transformation_se3_.data());\n\n      FramedMatches match = odometry_txt_.data_[i];\n      \n      assert(match.id1_ < match.id2_); \n      int id1 = match.id1_;\n      int id2 = match.id2_;\n        if(1)         ///////////////////////////////////////////////////////////\n        {\n          for (std::size_t j = 0; j < match.pairs_.size() && j<200; j++) \n          {\n            ceres::CostFunction* cost_odometry =\n                new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n                                              Sophus::SE3d::num_parameters,\n                                              Sophus::SE3d::num_parameters>(\n                    new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n                                      id1, id2));\n            problem.AddResidualBlock(cost_odometry, \n                                    new ceres::CauchyLoss(SIGMA),\n                                    camera_poses_.data_[id1].transformation_se3_.data(), \n                                    camera_poses_.data_[id2].transformation_se3_.data());\n\n            //目标函数，每个odometry和loop应该除以 各自特征点对的数量。(cauchy源代码可能因为特征点数量相同没有除)\n            // problem.AddResidualBlock(cost_odometry,  \n            //                       new ceres::ScaledLoss(new ceres::CauchyLoss(SIGMA), 1/match.old_correspondence_num_, ceres::TAKE_OWNERSHIP),\n            //                       camera_poses_.data_[id1].transformation_se3_.data(), \n            //                       camera_poses_.data_[id2].transformation_se3_.data()); \n          }\n        }\n\n    }\n\n    for (int i = 0; i < NumLoopClosureConstraints(); i++) \n    {\n\n      // std::cout << \"Maximization + loops \" << (i+1) << \" / \" << NumLoopClosureConstraints() <<  std::endl;\n      // FramedTransformation trans = loop_log_.data_[i];\n      // FramedInformation info = loop_info_.data_[i];\n      FramedMatches match = loop_txt_.data_[i];\n      // std::cout << \"match.old_correspondence_num_: \" << match.old_correspondence_num_ << std::endl;\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n      \n        for (std::size_t j = 0; j < match.pairs_.size(); j++) \n        {\n          // {\n          ceres::CostFunction* cost_loop =\n              new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n                                              Sophus::SE3d::num_parameters,\n                                              Sophus::SE3d::num_parameters>(\n                  new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n                                    id1, id2));\n          //  if (L_[id1][id2] >= TRUST_ODOMETRY * 0.5) {\n            problem.AddResidualBlock(cost_loop, \n                                  new ceres::ScaledLoss(new ceres::CauchyLoss(SIGMA), L_[id1][id2], ceres::TAKE_OWNERSHIP),\n                                  camera_poses_.data_[id1].transformation_se3_.data(), \n                                  camera_poses_.data_[id2].transformation_se3_.data());\n            \n          // if(match.semantic_label[j]==0)\n          // {\n          //   int label_one=match.label_one_[j];\n          //   int label_two=match.label_two_[j];\n          // ceres::CostFunction* cost_loop =\n          //     new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n          //                                     Sophus::SE3d::num_parameters,\n          //                                     Sophus::SE3d::num_parameters>(\n          //         new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n          //                           id1, id2));\n          // //  if (L_[id1][id2] >= TRUST_ODOMETRY * 0.5) {\n          //   problem.AddResidualBlock(cost_loop, \n          //                         new ceres::ScaledLoss(new ceres::CauchyLoss(SIGMA), L_[id1][id2]*semantic_p[label_one][label_two], ceres::TAKE_OWNERSHIP),\n          //                         camera_poses_.data_[id1].transformation_se3_.data(), \n          //                         camera_poses_.data_[id2].transformation_se3_.data());\n          // }\n\n        }\n    }\n    \n\n    // Set solver options (precision / method)\n    ceres::Solver::Options options;\n    // options.max_num_iterations = 1000;\n    options.gradient_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n    options.function_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n    // options.linear_solver_type = ceres::DENSE_QR;\n    options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n  \n    // Solve\n    std::cout << \"--------------SOLVING----------------ITERATION \" << camera_poses_.index_ << std::endl;\n    ceres::Solver::Summary summary;\n    Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n    std::cout << \"--------------  DONE ----------------ITERATION \" << camera_poses_.index_ << std::endl;\n  }\n\n\n\n\n  PCLTrajectory camera_poses_for_one_loop;\n  void yujie(int index_loop) {\n\n    camera_poses_for_one_loop.data_.clear();\n    for (int i = 0; i < NumPoses(); i++) \n    {\n      camera_poses_for_one_loop.data_.push_back( \n        FramedTransformation (camera_poses_.data_[i].id1_, \n                              camera_poses_.data_[i].id2_, \n                              camera_poses_.data_[i].frame_,\n                              camera_poses_.data_[i].transformation_se3_));\n    }\n    // last_covarance_ = covarance_;\n\n\n    // Maximize pose\n    // Build the problem.\n    ceres::Problem problem;\n    \n    for (int i = 0; i < NumOdometryConstraints(); i++) \n    {\n\n      FramedMatches match = odometry_txt_.data_[i];\n      \n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n        if(1)         ///////////////////////////////////////////////////////////\n        {\n          for (std::size_t j = 0; j < match.pairs_.size(); j++) \n          {\n            ceres::CostFunction* cost_odometry =\n                new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n                                              Sophus::SE3d::num_parameters,\n                                              Sophus::SE3d::num_parameters>(\n                    new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n                                      id1, id2));\n            problem.AddResidualBlock(cost_odometry, \n                                    new ceres::CauchyLoss(SIGMA),\n                                    camera_poses_for_one_loop.data_[id1].transformation_se3_.data(), \n                                    camera_poses_for_one_loop.data_[id2].transformation_se3_.data());\n          }\n        }\n    }\n\n    // 一个loop\n    for (std::vector< FramedTransformation >::iterator it = camera_poses_for_one_loop.data_.begin(); \n         it != camera_poses_for_one_loop.data_.end(); it++ ) {\n      problem.AddParameterBlock(it->transformation_se3_.data(), Sophus::SE3d::num_parameters,\n                                new Sophus::test::LocalParameterizationSE3);\n    }\n\n      // std::cout << \"Maximization + loops \" << (i+1) << \" / \" << NumLoopClosureConstraints() <<  std::endl;\n      // FramedTransformation trans = loop_log_.data_[i];\n      // FramedInformation info = loop_info_.data_[i];\n      FramedMatches match = loop_txt_.data_[index_loop];\n      std::cout <<  \"the loopConstraint \" << match.id1_ << \" with \" << match.id2_ << \"\\n\"<<std::endl;\n      // std::cout << \"match.old_correspondence_num_: \" << match.old_correspondence_num_ << std::endl;\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n\n        for (std::size_t j = 0; j < match.pairs_.size(); j++) \n        {\n          // {\n          ceres::CostFunction* cost_loop =\n              new ceres::AutoDiffCostFunction<CauchyFunctor, 3,\n                                              Sophus::SE3d::num_parameters,\n                                              Sophus::SE3d::num_parameters>(\n                  new CauchyFunctor(match.pairs_[j].first, match.pairs_[j].second, \n                                    id1, id2));\n            if (match.semantic_label[j]==1)                       //加入语义筛除\n            {\n            problem.AddResidualBlock(cost_loop, \n                                    new ceres::CauchyLoss(SIGMA),\n                                  camera_poses_for_one_loop.data_[id1].transformation_se3_.data(), \n                                  camera_poses_for_one_loop.data_[id2].transformation_se3_.data());\n            }\n\n        }\n\n        for (int i = 0; i < NumLoopClosureConstraints(); i ++) {\n\n      FramedMatches match = loop_txt_.data_[i];\n      // FramedInformation info = odometry_info_.data_[i];\n\n      assert(match.id1_ < match.id2_);\n      int id1 = match.id1_;\n      int id2 = match.id2_;\n\n      std::cout << \"In EstimateLAMBDA : \" << i << \"th loopConstraint \" << id1 << \" with \" << id2 << std::endl;\n\n      Eigen::Quaterniond q;\n      q = match.transformation_.block<3,3>(0,0);\n      Sophus::SE3d transformation_se3_ = Sophus::SE3d(q, Sophus::SE3d::Point(match.transformation_(0,3), match.transformation_(1,3), match.transformation_(2,3)));\n      \n      // compute the sum of cauchy loss\n      double sum_cauchy_loss = 0.;\n      for (std::size_t j = 0; j < match.pairs_.size(); j++) {\n        Eigen::Vector3d vec_d = camera_poses_for_one_loop.data_[id1].transformation_se3_ * match.pairs_[j].first \n                              - camera_poses_for_one_loop.data_[id2].transformation_se3_ * match.pairs_[j].second;\n         std::cout<<sqrt(vec_d.squaredNorm())<<' '; \n        // std::cout << j << \"/\" << loop_log_.data_.size() << \" : \" << sum_cauchy_loss << std::endl;\n      }\n      std::cout<<std::endl;\n    }\n    \n\n    // Set solver options (precision / method)\n    ceres::Solver::Options options;\n    // options.max_num_iterations = 1000;\n    options.gradient_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n    options.function_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n    // options.linear_solver_type = ceres::DENSE_QR;\n    options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n  \n    // Solve\n\n    ceres::Solver::Summary summary;\n    Solve(options, &problem, &summary);\n    std::cout << summary.BriefReport() << std::endl;\n\n  }\n\n  int NumPoses() {\n    return camera_poses_.data_.size();\n  }\n\n  int NumOdometryConstraints() {\n    return odometry_txt_.data_.size();\n  }\n\n  int NumLoopClosureConstraints() {\n    return loop_txt_.data_.size();\n  }\n\n  bool IsConverged() {\n    if (last_lambda_ < 0) {\n      // not started yet\n      return false;\n    }\n\n    std::cout << \"new lambda : \"<< lambda_ << std::endl;\n    if (fabs(lambda_ - last_lambda_) > 0.00001) {\n      std::cout << \"lambda was updated\" << std::endl;\n      return false;\n    }\n\n    for (int i = 0; i < NumPoses(); i++)\n    {\n      // std::cout << \"checking converging pose : \";\n      Sophus::SE3d last_pose = last_camera_poses_.data_[i].transformation_se3_;\n      Sophus::SE3d current_pose = camera_poses_.data_[i].transformation_se3_;\n\n      double const mse = (last_pose.inverse() * current_pose).log().squaredNorm();\n      bool const converged = mse < 10. * Sophus::Constants<double>::epsilon();\n\n      std::cout << i << \"(\" << mse << \", \" << converged << \",\" << last_camera_poses_.index_ << \"),\";\n      if (!converged) {\n        std::cout << std::endl;\n        return false;\n      }\n    }\n\n    std::cout << std::endl;\n    return true;\n  }\n};\n\nbool test(Sophus::SE3d const& T_w_targ, Sophus::SE3d const& T_w_init,\n          Sophus::SE3d::Point const& point_a_init,\n          Sophus::SE3d::Point const& point_b) {\n  static constexpr int kNumPointParameters = 3;\n\n  // Optimisation parameters.\n  Sophus::SE3d T_wr = T_w_init;\n  Sophus::SE3d::Point point_a = point_a_init;\n\n  // Build the problem.\n  ceres::Problem problem;\n\n  // Specify local update rule for our parameter\n  problem.AddParameterBlock(T_wr.data(), Sophus::SE3d::num_parameters,\n                            new Sophus::test::LocalParameterizationSE3);\n\n  // Create and add cost functions. Derivatives will be evaluated via\n  // automatic differentiation\n  ceres::CostFunction* cost_function1 =\n      new ceres::AutoDiffCostFunction<TestSE3CostFunctor, Sophus::SE3d::DoF,\n                                      Sophus::SE3d::num_parameters>(\n          new TestSE3CostFunctor(T_w_targ.inverse()));\n  problem.AddResidualBlock(cost_function1, NULL, T_wr.data());\n\n  ceres::CostFunction* cost_function2 =\n      new ceres::AutoDiffCostFunction<TestPointCostFunctor, kNumPointParameters,\n                                      Sophus::SE3d::num_parameters,\n                                      kNumPointParameters>(\n          new TestPointCostFunctor(T_w_targ.inverse(), point_b));\n  problem.AddResidualBlock(cost_function2, NULL, T_wr.data(), point_a.data());\n\n  // Set solver options (precision / method)\n  ceres::Solver::Options options;\n  options.gradient_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n  options.function_tolerance = 0.01 * Sophus::Constants<double>::epsilon();\n  options.linear_solver_type = ceres::DENSE_QR;\n\n  // Solve\n  ceres::Solver::Summary summary;\n  Solve(options, &problem, &summary);\n  std::cout << summary.BriefReport() << std::endl;\n\n  // Difference between target and parameter\n  double const mse = (T_w_targ.inverse() * T_wr).log().squaredNorm();\n  bool const passed = mse < 10. * Sophus::Constants<double>::epsilon();\n  return passed;\n}\n\ntemplate <typename Scalar>\nbool CreateSE3FromMatrix(Eigen::Matrix<Scalar, 4, 4> mat) {\n  auto se3 = Sophus::SE3<Scalar>(mat);\n  se3 = se3;\n  return true;\n}\n\nint main(int argc, char** argv) {\n  // using SE3Type = Sophus::SE3<double>;\n  // using SO3Type = Sophus::SO3<double>;\n  // using Point = SE3Type::Point;\n  // double const kPi = Sophus::Constants<double>::pi();\n\n  // std::vector<SE3Type> se3_vec;\n  // se3_vec.push_back(\n  //     SE3Type(SO3Type::exp(Point(0.2, 0.5, 0.0)), Point(0, 0, 0)));\n  // se3_vec.push_back(\n  //     SE3Type(SO3Type::exp(Point(0.2, 0.5, -1.0)), Point(10, 0, 0)));\n  // se3_vec.push_back(\n  //     SE3Type(SO3Type::exp(Point(0., 0., 0.)), Point(0, 100, 5)));\n  // se3_vec.push_back(\n  //     SE3Type(SO3Type::exp(Point(0., 0., 0.00001)), Point(0, 0, 0)));\n  // se3_vec.push_back(\n  //     SE3Type(SO3Type::exp(Point(0., 0., 0.00001)), Point(0, -0.00000001, 0.0000000001)));\n  // se3_vec.push_back(\n  //     SE3Type(SO3Type::exp(Point(0., 0., 0.00001)), Point(0.01, 0, 0)));\n  // se3_vec.push_back(\n  //     SE3Type(SO3Type::exp(Point(kPi, 0, 0)), Point(4, -5, 0)));\n  // se3_vec.push_back(\n  //     SE3Type(SO3Type::exp(Point(0.2, 0.5, 0.0)), Point(0, 0, 0)) *\n  //     SE3Type(SO3Type::exp(Point(kPi, 0, 0)), Point(0, 0, 0)) *\n  //     SE3Type(SO3Type::exp(Point(-0.2, -0.5, -0.0)), Point(0, 0, 0)));\n  // se3_vec.push_back(\n  //     SE3Type(SO3Type::exp(Point(0.3, 0.5, 0.1)), Point(2, 0, -7)) *\n  //     SE3Type(SO3Type::exp(Point(kPi, 0, 0)), Point(0, 0, 0)) *\n  //     SE3Type(SO3Type::exp(Point(-0.3, -0.5, -0.1)), Point(0, 6, 0)));\n\n  // std::vector<Point> point_vec;\n  // point_vec.emplace_back(1.012, 2.73, -1.4);\n  // point_vec.emplace_back(9.2, -7.3, -4.4);\n  // point_vec.emplace_back(2.5, 0.1, 9.1);\n  // point_vec.emplace_back(12.3, 1.9, 3.8);\n  // point_vec.emplace_back(-3.21, 3.42, 2.3);\n  // point_vec.emplace_back(-8.0, 6.1, -1.1);\n  // point_vec.emplace_back(0.0, 2.5, 5.9);\n  // point_vec.emplace_back(7.1, 7.8, -14);\n  // point_vec.emplace_back(5.8, 9.2, 0.0);\n\n  // for (size_t i = 0; i < se3_vec.size(); ++i) {\n  //   const int other_index = (i + 3) % se3_vec.size();\n  //   bool const passed = test(se3_vec[i], se3_vec[other_index], point_vec[i],\n  //                            point_vec[other_index]);\n  //   if (!passed) {\n  //     std::cerr << \"failed!\" << std::endl << std::endl;\n  //     exit(-1);\n  //   }\n  // }\n\n  // Eigen::Matrix<ceres::Jet<double, 28>, 4, 4> mat;\n  // mat.setIdentity();\n  // std::cout << CreateSE3FromMatrix(mat) << std::endl;\n\n  std::cout << \"cauchy_em_no_semantic started\" << std::endl;\n    clock_t start = clock() ; \n\n  if (argc == 7)\n  {\n    // double u = 1.0 / 57;\n    double lambda = 0.99;\n    R2EM_CauchyUniform r2em_c(lambda);\n\n    // std::cout << \"load\" << std::endl;\n    // r2em_c.LoadOdometryLog(argv[1]);\n\n    // std::cout << \"init\" << std::endl;\n    // r2em_c.LoadOdometryInfo(argv[2]);\n\n    std::cout << \"LoadOdometryTxt\" << std::endl;\n    r2em_c.LoadOdometryTxt(argv[1]);\n\n    std::cout << \"LoadLoopTxt\" << std::endl;\n    r2em_c.LoadLoopTxt(argv[2]);\n    // r2em_c.LoadLoopInfo(argv[4]);\n    \n    // if (argc > 3) {\n\n    std::cout << \"InitCameraPosesWithZhou\" << std::endl;\n    r2em_c.InitCameraPosesWithZhou(argv[3]);\n    // } else {\n      // r2em_c.InitCameraPoses();  \n    // }\n\n    std::cout << \"EstimateLAMBDA\" << std::endl;\n    r2em_c.EstimateLAMBDA();\n\n    //r2em_c.SaveCameraPoses(\"/home/ziquan/my_ws/init_poses.txt\");\n    //std::cout << \"save to /home/ziquan/my_ws/init_poses.txt\" << std::endl;\n    LoadFromFile_semantic_p(argv[4]);\n  std::cout << \"semantic probability matrix\" << std::endl;\n\n    std::cout << \"START EM\" << std::endl;\n  // add by yujie\n  //  for(int i=0;i<r2em_c.NumLoopClosureConstraints();i++)\n  //  {\n  //    r2em_c.yujie(i);\n  //  }\n\n    for (int i = 0 ; i < NUM_ITERATION_EM; i ++) {\n      r2em_c.Expectation(i);\n      r2em_c.Maximization();\n\nstd::string iteration_pose=\"/home/tang/undergraduate/RobustPCLReconstruction-cauchy_em/data/cauchy/多机/07-10%正确-各代位姿/pose_nosem\"+std::to_string(i)+\".txt\";\n  r2em_c.SaveCameraPoses(iteration_pose.c_str());\n\n      std::cout << \"check 1 \" << std::endl;\n      if (i == 0)\n        //r2em_c.SaveCameraPoses(\"/home/ziquan/my_ws/final_poses_em_0th.txt\");\n\n      if (i == 15)\n        // r2em_c.SaveCameraPoses(\"/home/tang/final_poses_em_5nd.txt\");\n        {\n        // std::cout << \"Fail\" << std::endl;\n        //   r2em_c.SaveCameraPoses(argv[5]);\n        //   break;\n        }\n\n      if (i == 100)\n        // r2em_c.SaveCameraPoses(\"final_poses_em_100th.txt\");\n\n      std::cout << \"check EM converges in iteration \" << i << std::endl;\n      if (r2em_c.IsConverged()) {\n        std::cout << \"EM converges! \" << std::endl;\n        break;\n      }\n    }\n        clock_t finish = clock() ; \n\n    // if (argc > 3) {\n      r2em_c.SaveCameraPoses(argv[5]);\n      std::cout << \"final poses are saved to \" << argv[5] << std::endl;\n    // } else {\n\n    //   r2em_c.SaveCameraPoses(\"/home/ziquan/my_ws/final_poses_em.txt\");\n    //   std::cout << \"final poses are saved to /home/ziquan/my_ws/final_poses_em.txt\" << std::endl;\n    // }\n\n\n      r2em_c.SaveLinks(argv[6]);\n      std::cout << \"links are saved to \" << argv[6] << std::endl;\n    // r2em_c.SaveLinks(\"/home/ziquan/my_ws/reg_refine_all_em.log\");\n    // std::cout << \"links are saved to /home/ziquan/my_ws/reg_refine_all_em.log\" << std::endl;\n    std::cout << \"cauchy_em_no_semantic ended\" << std::endl;\n    std::cout << \"there are \" << r2em_c.NumPoses() << \" poses\" << std::endl;\n    // std::cout << \"there are \" << r2em_c.NumOdometryConstraints() << \" odometry constraints\" << std::endl;\n    std::cout << \"there are \" << r2em_c.NumLoopClosureConstraints() << \" loops\" << std::endl;\n\n  std::cout << \"first EM time is : \" << double((finish-start)/1000) << \"ms\" << std::endl;\n  } else {\n    std::cout << \"input format is : odom.txt loop.txt init.txt final.txt link.txt\" << std::endl;\n  }\n     \n  \n  return 0;\n}\n", "meta": {"hexsha": "1467ba690304b5de44cc1b43914bd560cc25d5bd", "size": 48934, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/ceres/cauchy_em_no_sem.cpp", "max_stars_repo_name": "BIT-TYJ/EO-RCL", "max_stars_repo_head_hexsha": "ea41ab441fa43753a6d7ecb1bddf96814add3d8e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-15T15:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T15:01:35.000Z", "max_issues_repo_path": "test/ceres/cauchy_em_no_sem.cpp", "max_issues_repo_name": "BIT-TYJ/EO-RCL", "max_issues_repo_head_hexsha": "ea41ab441fa43753a6d7ecb1bddf96814add3d8e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/ceres/cauchy_em_no_sem.cpp", "max_forks_repo_name": "BIT-TYJ/EO-RCL", "max_forks_repo_head_hexsha": "ea41ab441fa43753a6d7ecb1bddf96814add3d8e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2413793103, "max_line_length": 194, "alphanum_fraction": 0.5725875669, "num_tokens": 15163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.23818812057617447}}
{"text": "/* \n * File:   Simulation.cpp\n * Author: ben\n * \n * Created on September 21, 2012, 11:18 AM\n */\n\n#include \"Simulation.h\"\n#include \"Utils.h\"\n#include \"moves/MoveFactory.h\"\n#include \"Boltzmann.h\"\n#include \"observables/Observable.h\"\n\n#include <boost/assign/std.hpp>\n#include <boost/unordered_map.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/array.hpp>\n#include <fstream>\n#include <sstream>\n#include <ctime>\n\n\nusing namespace boost::assign;\n\nSimulation::Simulation() :\nk(READ_CONF(\"mc.k\", 10)),\nz(READ_CONF(\"mc.z\", 20)),\nmeasureAtVolume(READ_CONF(\"general.measureAtVolume\", true)),\ndrift(READ_CONF(\"volume.drift\", false)),\nvolumeStart(READ_CONF(\"volume.start\", 500)),\nvolumeEnd(READ_CONF(\"volume.end\", 10000)),\nskip(READ_CONF(\"volume.skip\", 100)),\ndrop(READ_CONF(\"general.drop\", 0)) {\n    /* Initialize random number generator */\n    setSeed(std::time(0));\n    moveFactory = new MoveFactory(*this);\n}\n\nSimulation::Simulation(const Simulation& orig) {\n}\n\nSimulation::~Simulation() {\n    clearTriangulation();\n    delete moveFactory;\n\n    foreach(Observable* obs, observables) {\n        delete obs;\n    }\n}\n\nvoid Simulation::clearTriangulation() {\n    TriSet deleted;\n\n    foreach(Vertex* v, vertices) {\n\n        foreach(Triangle* t, v->getTriangles()) {\n            if (deleted.find(t) == deleted.end()) {\n                delete t;\n                deleted.insert(t);\n            }\n        }\n        delete v;\n    }\n\n    TTSCount = 0;\n    SSTCount = 0;\n    vertices.clear();\n}\n\nvoid Simulation::readFromFile(const char* filename) {\n    std::ifstream file(filename);\n    if (!file.is_open()) {\n        std::cout << \"Unable to open file '\" << filename << \"'\" << std::endl;\n        return;\n    }\n\n    char type;\n    int vCount, vertA, vertB, vertC;\n\n    file >> vCount;\n    Vertex * vertex_array[vCount];\n\n    clearTriangulation(); // clear old grid\n\n    for (int i = 0; i < vCount; i++) {\n        vertex_array[i] = new Vertex();\n        vertices.push_back(vertex_array[i]);\n    }\n\n    // TODO: check if the triangulation is valid?\n    while (file >> type >> vertA >> vertB >> vertC) {\n        new Triangle(type == 'T' ? Triangle::TTS : Triangle::SST, vertex_array[vertA],\n                vertex_array[vertB], vertex_array[vertC]);\n\n        if (type == 'T') {\n            TTSCount++;\n        } else {\n            SSTCount++;\n        }\n    }\n\n    file.close();\n}\n\nvoid Simulation::writeToFile(const char* filename) {\n    std::ofstream file(filename);\n    if (!file.is_open()) {\n        std::cout << \"Unable to open file '\" << filename << \"'\" << std::endl;\n        return;\n    }\n\n    int vCount = 0;\n    typedef boost::unordered_map<Vertex*, int> vertex_map;\n    vertex_map vertexMap;\n\n    foreach(Vertex* v, vertices) {\n        vertexMap.insert(vertex_map::value_type(v, vCount));\n        vCount++;\n    }\n\n    file << vCount << std::endl;\n\n    TriSet visitedTri;\n\n    foreach(Vertex* v, vertices) {\n\n        foreach(Triangle* t, v->getTriangles()) {\n            if (visitedTri.find(t) != visitedTri.end()) {\n                continue;\n            }\n            visitedTri.insert(t);\n\n            if (t->getType() == Triangle::TTS) {\n                file << \"T\";\n            } else {\n                file << \"S\";\n            }\n\n            for (int i = 0; i < 3; i++) {\n                file << \" \" << vertexMap[t->getVertex(i)];\n            }\n\n            file << std::endl;\n        }\n    }\n\n    file.close();\n}\n\nvoid Simulation::generateInitialTriangulation(int N, int T) {\n    Vertex * vertices[N * T];\n    Triangle * triangles[N * T * 2]; // TODO: remove, unnecessary\n\n    /* Create vertices */\n    for (int t = 0; t < T * N; t++) {\n        vertices[t] = new Vertex();\n        this->vertices.push_back(vertices[t]);\n    }\n\n    /* Create foliation */\n    for (int t = 0; t < T; t++) {\n        for (int s = 0; s < N; s++) {\n            Triangle* u = new Triangle(Triangle::TTS, vertices[t * N + s], vertices[((t + 1) % T) * N + s],\n                    vertices[t * N + (s + 1) % N]);\n            Triangle* v = new Triangle(Triangle::TTS, vertices[((t + 1) % T) * N + (s + 1) % N], vertices[t * N + (s + 1) % N],\n                    vertices[((t + 1) % T) * N + s]);\n            triangles[t * 2 * N + 2 * s] = u;\n            triangles[t * 2 * N + 2 * s + 1] = v;\n        }\n    }\n\n    TTSCount = N * T * 2;\n    SSTCount = 0;\n}\n\nVertex* Simulation::getRandomVertex(const std::vector<Vertex*>& vertices) {\n    BOOST_ASSERT(vertices.size() > 0);\n    boost::uniform_int<> uint(0, vertices.size() - 1);\n    return vertices[uint(rng)];\n}\n\nvoid Simulation::collectTriangles(TriSet& triSet, Vertex* v, int depth) {\n    if (depth <= 0) {\n        triSet += v->getTriangles();\n        return;\n    }\n\n    triSet += v->getTriangles();\n\n    foreach(Vertex* u, v->getNeighbouringVertices()) {\n        collectTriangles(triSet, u, depth - 1);\n    }\n}\n\nvoid Simulation::drawPartialTriangulation(const char* filename, Vertex* v, const TriSet& tri) {\n    std::ofstream dotFile(filename);\n    if (!dotFile.is_open()) {\n        std::cout << \"Unable to open file '\" << filename << \"'\" << std::endl;\n        return;\n    }\n\n    dotFile << \"strict graph G {\" << std::endl << \"node[shape=point];\" << std::endl;\n    dotFile << \"n\" << v << \"[color=green];\" << std::endl;\n\n    foreach(Triangle* t, tri) {\n        for (int i = 0; i < 3; i++) {\n            dotFile << \"n\" << t->getVertex(i) << \"--\" << \"n\" << t->getVertex((i + 1) % 3);\n            if (t->isTimelike(i)) {\n                dotFile << \" [color=red];\" << std::endl;\n            } else {\n                dotFile << \" [color=blue];\" << std::endl;\n            }\n        }\n    }\n\n    dotFile << \"}\";\n    dotFile.close();\n}\n\n// FIXME\nvoid Simulation::checkLinkOverlap() {\n  /*  for (unsigned int i = 0; i < vertices.size() - 1; i++) {\n        for (unsigned int j = i + 1; j < vertices.size(); j++) {\n            TriSet t;\n            \n            TriSet t = vertices[i]->getTriangles() & vertices[j]->getTriangles();\n\n            if (t.size() != 2 && t.size() != 0) {\n                std::cerr << \"Link duplicates: \" << i << \" \" << j << \" \" << t.size() << std::endl;\n                BOOST_ASSERT(false);\n            }\n        }\n    }*/\n}\n\nvoid Simulation::printTriangleConnectivity(Triangle* t) {\n    typedef boost::tuple<Triangle*, Vertex*, Vertex*> curpos;\n\n    int newId = 0;\n    boost::unordered_map<Triangle*, int> tri;\n    std::queue<curpos> neighbours;\n\n    // add current triangle and first neighbour\n    neighbours.push(\n            boost::make_tuple(t, t->getVertex(0), t->getVertex(1)));\n    neighbours.push(\n            boost::make_tuple(t->getNeighbour(0), t->getVertex(0), t->getVertex(1)));\n\n    while (!neighbours.empty()) {\n        curpos cur = neighbours.front();\n        neighbours.pop();\n\n        Triangle* t = cur.get < 0 > ();\n\n        boost::unordered_map<Triangle*, int>::iterator res = tri.find(t);\n        if (res != tri.end()) {\n            std::cout << res->second << std::endl;\n            continue;\n        }\n\n        // create character of tri a - b - c\n        Vertex* a = cur.get < 1 > ();\n        Vertex* b = cur.get < 2 > ();\n        Vertex* c = t->getThirdVertex(a, b);\n\n        std::cout << (t->isTimelike(a, b) ? \"T\" : \"S\") <<\n                (t->isTimelike(b, c) ? \"T\" : \"S\") <<\n                (t->isTimelike(c, a) ? \"T\" : \"S\") << \": \" << newId << std::endl;\n\n        tri[t] = newId;\n        newId++;\n\n        // add the two other neighbours to the stack\n        neighbours.push(boost::make_tuple(t->getNeighbour(b, c),\n                b, c));\n        neighbours.push(boost::make_tuple(t->getNeighbour(c, a),\n                c, a));\n    }\n}\n\nstd::vector<int> Simulation::createID(Triangle* t) {\n    typedef boost::tuple<Triangle*, Vertex*, Vertex*> curpos;\n    std::vector<int> id;\n\n    int newId = 8; // start at 8, 8 > character\n    boost::unordered_map<Triangle*, int> tri;\n    std::queue<curpos> neighbours;\n\n    // add current triangle and first neighbour\n    neighbours.push(\n            boost::make_tuple(t, t->getVertex(0), t->getVertex(1)));\n    neighbours.push(\n            boost::make_tuple(t->getNeighbour(0), t->getVertex(0), t->getVertex(1)));\n\n    while (!neighbours.empty()) {\n        curpos cur = neighbours.front();\n        neighbours.pop();\n\n        Triangle* t = cur.get < 0 > ();\n\n        boost::unordered_map<Triangle*, int>::iterator res = tri.find(t);\n        if (res != tri.end()) {\n            id.push_back(res->second);\n            continue;\n        }\n\n        // create character of tri a - b - c\n        Vertex* a = cur.get < 1 > ();\n        Vertex* b = cur.get < 2 > ();\n        Vertex* c = t->getThirdVertex(a, b);\n\n        int character = t->isTimelike(a, b) * 4 + t->isTimelike(b, c) * 2 +\n                t->isTimelike(c, a);\n\n        id.push_back(character);\n        tri[t] = newId;\n        newId++;\n\n        // add the two other neighbours to the stack\n        neighbours.push(boost::make_tuple(t->getNeighbour(b, c),\n                b, c));\n        neighbours.push(boost::make_tuple(t->getNeighbour(c, a),\n                c, a));\n    }\n\n    return id;\n}\n\nvoid Simulation::Metropolis(double alpha, unsigned int volume, double\n        deltaVolume, unsigned int numSweeps, unsigned int sweepLength) {\n    unsigned long long moveRejectedBecauseImpossible = 0, moveRejectedBecauseDetBal = 0;\n    double bias = 0; // count the bias of the system size\n    double lambda = 5;\n    bool measured = false;\n\n    /*BoltzmannTester boltzmannTester;\n    Triangle* fixed = *vertices[0]->getTriangles().begin();\n    moveFactory->setFixedTriangle(fixed);\n    std::vector<int> id = createID(fixed);*/\n\n    //std::ofstream ratio(\"tri_ratio.dat\"); // TODO: make observable\n    //std::ofstream lambda_measure(\"lambda.dat\");\n\n    if (drift) {\n        volume = volumeStart;\n    }\n\n    for (unsigned long sweep = 0; sweep < numSweeps; sweep++) {\n        if (drift && sweep % skip == 0) {\n            volume += (volumeEnd - volumeStart) / (numSweeps / skip);\n        }\n\n        /*\n        if (sweep % 10 == 0) { // for testing\n            boltzmannTester.printFrequencies(lambda, alpha);\n        }*/\n\n        // for testing\n        //ratio << TTSCount / (double) (SSTCount + TTSCount) << \" \" << TTSCount << \" \" << SSTCount << \" \"\n        //        << 2 * vertices.size() << std::endl;\n\n        measured = false;\n        for (unsigned int i = 0; i < sweepLength; i++) {\n            /* Measure observables when the volume is right */\n            if (((!measureAtVolume && i == 0) ||\n                    (measureAtVolume && vertices.size() * 2 == volume && !measured\n                    && i > 0.4 * sweepLength && i < 0.6 * sweepLength)) &&\n                    ((drift && (sweep % skip) > drop) || (!drift && sweep > drop))) {\n\n                foreach(Observable* o, observables) {\n                    o->measure(vertices);\n                }\n\n                measured = true;\n            }\n\n            Move* move = moveFactory->createRandomMove(*this);\n\n            // some random moves can be impossible and to simplify the \n            // probability checks, we can do this explicit check\n            if (!move->isMovePossible(vertices)) {\n                //boltzmannTester.addStateId(id);\n                moveFactory->setMoveImpossible();\n                moveRejectedBecauseImpossible++;\n                continue;\n            }\n\n            /* acceptance = P(x') / P(x) * Q(x | x') / Q(x' | x) */\n            double acceptance = move->getMoveProbability(lambda, alpha) *\n                    move->getInverseTransitionProbability(vertices) /\n                    move->getTransitionProbability(vertices);\n\n            /* add quadratic volume fixing term */\n            double delta = move->getDeltaSST() + move->getDeltaTTS();\n            acceptance *= exp(-deltaVolume * delta * (4.0 *\n                    (double) vertices.size() + delta - 2.0 * (double) volume));\n\n\n            if (acceptance > 1 || getRandomNumber() < acceptance) {\n                move->execute(vertices);\n                moveFactory->setMoveAccepted();\n\n                TTSCount += move->getDeltaTTS();\n                SSTCount += move->getDeltaSST();\n                //id = createID(fixed);\n            } else {\n                moveRejectedBecauseDetBal++;\n                moveFactory->setMoveRejected();\n            }\n\n            bias += 2.0 * (double) vertices.size() - (double) volume;\n            //boltzmannTester.addStateId(id);\n        }\n\n        /* Update lambda. Lower lambda means more growth, so the signs are\n         * reversed. */\n        bias *= z / (double) sweepLength / (double) volume;\n        lambda += k * (bias * bias * bias + bias);\n        lambda = lambda < 0 ? 0 : lambda;\n\n        std::cout << \"Real run \" << sweep << \", lambda: \" << lambda << \", delta: \" << k * (bias * bias * bias + bias)\n                << \", bias: \" << bias / z * 100 << \"%\" << std::endl;\n        //lambda_measure << lambda << std::endl;\n        bias = 0;\n    }\n\n    /* Write some statistics*/\n    std::cout << \"Rejected impossible: \" << moveRejectedBecauseImpossible\n            << \", \" << 100 * moveRejectedBecauseImpossible /\n            ((float) sweepLength * (float) numSweeps) << \"%\" << std::endl;\n    std::cout << \"Rejected detailed balance: \" << moveRejectedBecauseDetBal\n            << \", \" << 100 * moveRejectedBecauseDetBal /\n            ((float) sweepLength * (float) numSweeps - (float) moveRejectedBecauseImpossible)\n            << \"%\" << std::endl;\n};\n", "meta": {"hexsha": "96542120e8107ad5dbf83de3aac158c92ed04b05", "size": 13412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Simulation.cpp", "max_stars_repo_name": "benruijl/cdt", "max_stars_repo_head_hexsha": "340f00488f46167112dbc763810d7ebfbd1056d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-30T16:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-30T16:07:31.000Z", "max_issues_repo_path": "src/Simulation.cpp", "max_issues_repo_name": "benruijl/cdt", "max_issues_repo_head_hexsha": "340f00488f46167112dbc763810d7ebfbd1056d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Simulation.cpp", "max_forks_repo_name": "benruijl/cdt", "max_forks_repo_head_hexsha": "340f00488f46167112dbc763810d7ebfbd1056d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-28T15:44:21.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-28T15:44:21.000Z", "avg_line_length": 30.7614678899, "max_line_length": 127, "alphanum_fraction": 0.5287056367, "num_tokens": 3479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.23818812057617447}}
{"text": "#include \"imagewindowmapper.h\"\n//#include <boost/math/special_functions/round.hpp>\n#include \"rectcalc.h\"\n#include \"Geometry/Matrix33.h\"\n#include \"Geometry/Angle.h\"\n#include \"assert.h\"\n#define FLOAT_ZERO 1.0e-30\n//using boost::math::lround;\n\n/*int round(double val)\n{\n    return (val > 0.0) ? floor(val + 0.5) : ceil(val - 0.5);\n}*/\nusing namespace Geometry;\nImageWindowMapper::ImageWindowMapper()\n:m_sizePane (0, 0)\n, m_sizeImage(0, 0)\n, m_sizeWnd(0, 0)\n, _window_offset(0, 0)\n{\n    m_dAngle = 0.0;\n    m_bVFlip = false;\n    m_bHFlip = false;\n    m_dZoom = 1.0;\n    m_dFovX = 0.0;\n    m_dFovY = 0.0;\n    m_bUpdated = false;\n}\n\nImageWindowMapper::~ImageWindowMapper()\n{\n}\n\nbool ImageWindowMapper::UpdateMapper()\n{\n    if (m_bUpdated)\n    {\n        return true;\n    }\n    if (m_sizeImage.width() <= 0 || m_sizeImage.height() <= 0 ||\n        m_dFovX < FLOAT_ZERO || m_dFovY < FLOAT_ZERO ||\n        m_sizeWnd.width() <= 0 || m_sizeWnd.height() <= 0)\n    {\n        CMatrix33 identity;\n        _voxel_to_window = identity;\n        _window_to_voxel = identity;\n        _physical_to_window = identity;\n        _window_to_physical = identity;\n        _voxel_to_physical = identity;\n        _physical_to_voxel = identity;\n\n        m_bUpdated = true;\n        return false;\n    }\n    _voxel_to_window = CalcVoxelToWindow();\n    _voxel_to_window.GetInverse(_window_to_voxel);\n\n    CMatrix33 physical_to_voxel = CalcPhysicalToVoxel();\n\n    _physical_to_window = _voxel_to_window * physical_to_voxel;\n    _physical_to_window.GetInverse(_window_to_physical);\n\n    _voxel_to_physical = _window_to_physical * _voxel_to_window;\n    _physical_to_voxel = _window_to_voxel * _physical_to_window;\n\n    m_bUpdated = true;\n    return true;\n}\n\nQPoint ImageWindowMapper::WindowToVoxel(const QPoint& ptWindow) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n\n    Point2D p = _window_to_voxel * Point2D(ptWindow.x(), ptWindow.y());\n\n  //  return QPoint(lround(p.x), lround(p.y));\n    return QPoint(p.x, p.y);\n}\n\n/*int int_round(double v)\n{\n    try\n    {\n        return boost::math::iround(v);\n    }\n    catch (std::exception& e)\n    {\n        LOG_ERROR(CString(e.what()));\n        if (v < 0)\n        {\n            return INT_MIN;\n        }\n        else\n        {\n            return INT_MAX;\n        }\n    }\n}*/\n\nQPoint ImageWindowMapper::PhysicalToWindow(const Point2D& ptPhysical) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n    Point2D p = _physical_to_window * ptPhysical;\n\n    //return QPoint(int_round(p.x) - _window_offset.cx, int_round(p.y) - _window_offset.cy);\n    return QPoint(p.x - _window_offset.width(), p.y - _window_offset.height());\n}\n\nQSize ImageWindowMapper::PhysicalToWindow(const Vector2D& size_physical) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n\n    auto size = _physical_to_window * size_physical;\n\n    //return QSize(int_round(size.x), int_round(size.y));\n    return QSize(size.cx, size.cy);\n}\n\nPoint2D ImageWindowMapper::PhysicalToWindow2D(const Point2D& ptPhysical) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n    Point2D pt = _physical_to_window * ptPhysical;\n    pt.x = pt.x - _window_offset.width();\n    pt.y = pt.y - _window_offset.height();\n    return pt;\n}\n\nVector2D ImageWindowMapper::PhysicalToWindow2D(const Vector2D& vPhysical) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n    Vector2D size = _physical_to_window * vPhysical;\n    return size;\n}\n\nPoint2D ImageWindowMapper::WindowToPhysical(const QPoint& ptWindow) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n\n    Point2D pt_window(ptWindow.x() + _window_offset.width(),\n                      ptWindow.y() + _window_offset.height());\n    Point2D pt = _window_to_physical * pt_window;\n    return pt;\n}\n\nVector2D ImageWindowMapper::WindowToPhysical(const QSize& szWindow) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n\n    Vector2D size_window(szWindow.width(), szWindow.height());\n    Vector2D size2d = _window_to_physical * size_window;\n    return size2d;\n}\n\nQPoint ImageWindowMapper::PhysicalToVoxel(const Point2D& ptPhysical) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n    assert(m_dFovX > FLOAT_ZERO && m_dFovY > FLOAT_ZERO);\n    Point2D pt = CalcPhysicalToVoxel() * ptPhysical;\n  //  QPoint ptVoxel(boost::math::lround(pt.x), boost::math::lround(pt.y));\n    QPoint ptVoxel(pt.x, pt.y);\n    return ptVoxel;\n}\n\nPoint2D ImageWindowMapper::PhysicalToDoubleVoxel(const Point2D& ptPhysical) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n    assert(m_dFovX > FLOAT_ZERO && m_dFovY > FLOAT_ZERO);\n    Point2D pt = CalcPhysicalToVoxel() * ptPhysical;\n    return pt;\n}\n\n\nPoint2D ImageWindowMapper::VoxelToPhysical(const Point2D& voxel) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n\n    return _voxel_to_physical * voxel;\n}\n\nQPoint ImageWindowMapper::VoxelToWindow(const Point2D& voxel_point) const\n{\n    const_cast<ImageWindowMapper*>(this)->UpdateMapper();\n    auto window_point = _voxel_to_window * voxel_point;\n\n   // return QPoint(int_round(window_point.x), int_round(window_point.y));\n    return QPoint(window_point.x, window_point.y);\n}\n\nvoid ImageWindowMapper::SetFOV(double dFovX, double dFovY)\n{\n    if (abs(m_dFovX - dFovX) < 0.000001 && abs(m_dFovY - dFovY) < 0.000001)\n    {\n        return;\n    }\n    m_dFovX = dFovX;\n    m_dFovY = dFovY;\n    m_bUpdated = false;\n}\n\nvoid ImageWindowMapper::SetImageSize(QSize size)\n{\n    if (m_sizeImage == size)\n    {\n        return;\n    }\n\n    m_sizeImage = size;\n    m_bUpdated = false;\n}\n\nvoid ImageWindowMapper::SetWindowSize(QSize size)\n{\n    if (m_sizeWnd == size)\n    {\n        return;\n    }\n\n    m_sizeWnd = size;\n    m_bUpdated = false;\n}\n\nvoid ImageWindowMapper::SetWindowOffset(const QSize& offset)\n{\n    if (_window_offset == offset)\n    {\n        return;\n    }\n\n    _window_offset = offset;\n    m_bUpdated = false;\n}\n\nCMatrix33 ImageWindowMapper::CalcVoxelToWindow() const\n{\n    CMatrix33 rotation;\n    rotation.MakeRotate(CRadian(-m_dAngle));\n\n    CMatrix33 flip;\n    if (m_bHFlip)\n    {\n        flip = flip * CMatrix33::FromBasisVectors(Vector2D(-1.0, 0.0), Vector2D(0.0, 1.0));\n    }\n    if (m_bVFlip)\n    {\n        flip = flip * CMatrix33::FromBasisVectors(Vector2D(1.0, 0.0), Vector2D(0.0, -1.0));\n    }\n\n    CMatrix33 pane;\n    pane.MakeTranslate(Vector2D(m_sizePane.x, m_sizePane.y));\n\n    QSize image_rect_size = RectCalc::GetFitSize(m_sizeImage, m_sizeWnd);\n    double fit_ratio = image_rect_size.width()/ static_cast<double>(m_sizeImage.width());\n    CMatrix33 zoom;\n    zoom.MakeScale(Vector2D(m_dZoom * fit_ratio, m_dZoom * fit_ratio));\n\n    CMatrix33 image_center_to_first;\n    image_center_to_first.MakeTranslate(Vector2D(-(m_sizeImage.width() - 1) / 2.0, -(m_sizeImage.height() - 1) / 2.0));\n\n    CMatrix33 viweport_first_to_center;\n    viweport_first_to_center.MakeTranslate(Vector2D((m_sizeWnd.width() - 1) / 2.0, (m_sizeWnd.height() - 1) / 2.0));\n\n    return viweport_first_to_center * zoom * pane * flip * rotation * image_center_to_first;\n}\n\nCMatrix33 ImageWindowMapper::CalcPhysicalToVoxel() const\n{\n    CMatrix33 scale;\n    scale.MakeScale(Vector2D(m_sizeImage.width() / m_dFovX, m_sizeImage.height() / m_dFovY));\n\n    CMatrix33 translate;\n    translate.MakeTranslate(Vector2D(m_sizeImage.width() / 2.0, m_sizeImage.height() / 2.0));\n\n    return translate * scale;\n}\n\nvoid ImageWindowMapper::SetRotationAngle( double angle )\n{\n    if (m_dAngle == angle)\n    {\n        return;\n    }\n\n    m_dAngle = angle;\n    m_bUpdated = false;\n}\n\ndouble ImageWindowMapper::GetRotationAngle() const\n{\n    return m_dAngle;\n}\n\nbool ImageWindowMapper::IsVerticalFlip() const\n{\n    return m_bVFlip;\n}\n\nvoid ImageWindowMapper::SetVerticalFlip( bool flip )\n{\n    if (m_bVFlip == flip)\n    {\n        return;\n    }\n\n    m_bVFlip = flip;\n    m_bUpdated = false;\n}\n\nbool ImageWindowMapper::IsHorizontalFlip() const\n{\n    return m_bHFlip;\n}\n\nvoid ImageWindowMapper::SetHorizontalFlip( bool flip )\n{\n    if (m_bHFlip == flip)\n    {\n        return;\n    }\n\n    m_bHFlip = flip;\n    m_bUpdated = false;\n}\n\nvoid ImageWindowMapper::SetZoom( double dZoom )\n{\n    if (m_dZoom == dZoom)\n    {\n        return;\n    }\n\n    m_dZoom = dZoom;\n    m_bUpdated = false;\n}\n\ndouble ImageWindowMapper::GetZoom() const\n{\n    return m_dZoom;\n}\n\nvoid ImageWindowMapper::SetPane(const Vector2D& pane)\n{\n    if (m_sizePane.x == pane.cx && m_sizePane.y == pane.cy)\n    {\n        return;\n    }\n\n    m_sizePane = Point2D(pane.cx, pane.cy);\n    m_bUpdated = false;\n}\n\nVector2D ImageWindowMapper::GetPane() const\n{\n    return Vector2D(m_sizePane.x, m_sizePane.y);\n}\n\nvoid ImageWindowMapper::HorizontalFlip()\n{\n    m_bHFlip = !m_bHFlip;\n    m_sizePane.x *=  -1;\n    m_bUpdated = false;\n}\n\nvoid ImageWindowMapper::VerticalFlip()\n{\n    m_bVFlip = ! m_bVFlip;\n    m_sizePane.y *= -1;\n    m_bUpdated = false;\n}\n\nvoid ImageWindowMapper::Rotate( double angle )\n{\n    Vector2D old_pane(m_sizePane.x, m_sizePane.y);\n    m_sizePane = Point2D(old_pane.cx * cos(angle) + old_pane.cy * sin(angle),\n        -old_pane.cx * sin(angle) + old_pane.cy * cos(angle));\n\n    angle = (m_bHFlip == m_bVFlip) ? angle : - angle;\n    m_dAngle += angle;\n\n    m_bUpdated = false;\n}\n\nvoid ImageWindowMapper::Zoom( double multiple )\n{\n    SetZoom(m_dZoom * multiple);\n}\n\nvoid ImageWindowMapper::Pane( const Vector2D& offset )\n{\n    if (m_sizeImage.width() == 0 || m_sizeImage.height() == 0)\n    {\n        return ;\n    }\n\n    QSize image_rect_size = RectCalc::GetFitSize(m_sizeImage, m_sizeWnd);\n    double effective_zoom = m_sizeImage.width() / (m_dZoom * image_rect_size.width());\n\n    m_sizePane = Point2D(m_sizePane.x + offset.cx * effective_zoom, m_sizePane.y + offset.cy * effective_zoom);\n    Point2D max_pane ((m_sizeImage.width() * 4.0) / 5, (m_sizeImage.height() * 4.0) / 5);\n    if (m_sizePane.x > max_pane.x)\n    {\n        m_sizePane.x = max_pane.x;\n    }\n    else if (m_sizePane.x < -max_pane.x)\n    {\n        m_sizePane.x = -max_pane.x;\n    }\n    if (m_sizePane.y > max_pane.y)\n    {\n        m_sizePane.y = max_pane.y;\n    }\n    else if (m_sizePane.y < -max_pane.y)\n    {\n        m_sizePane.y = -max_pane.y;\n    }\n    m_bUpdated = false;\n}\n\nbool ImageWindowMapper::operator==( const ImageWindowMapper& rhs )\n{\n    return ((fabs(m_dAngle - rhs.m_dAngle) <= 1.0e-5) &&\n        m_bHFlip == rhs.m_bHFlip &&\n        m_bVFlip == rhs.m_bVFlip &&\n        (fabs(m_dZoom - rhs.m_dZoom) <= 1.0e-5) &&\n        m_sizePane == rhs.m_sizePane);\n}\n\nvoid ImageWindowMapper::Reset()\n{\n    m_dZoom = 1.0;\n    m_dAngle = 0.0;\n    m_sizePane = Point2D(0.0, 0.0);\n    m_bHFlip = false;\n    m_bVFlip = false;\n\n    m_bUpdated = false;\n}\n", "meta": {"hexsha": "c959e55b9e6f1e34bbb24eebaa6acffb834e9d89", "size": 10681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "API/ReconDemo/imagewindowmapper.cpp", "max_stars_repo_name": "PengJinFa/YAPNew", "max_stars_repo_head_hexsha": "fafee8031669b24d0cc74876a477c97d0d7ebadc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "API/ReconDemo/imagewindowmapper.cpp", "max_issues_repo_name": "PengJinFa/YAPNew", "max_issues_repo_head_hexsha": "fafee8031669b24d0cc74876a477c97d0d7ebadc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "API/ReconDemo/imagewindowmapper.cpp", "max_forks_repo_name": "PengJinFa/YAPNew", "max_forks_repo_head_hexsha": "fafee8031669b24d0cc74876a477c97d0d7ebadc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4416475973, "max_line_length": 119, "alphanum_fraction": 0.6657616328, "num_tokens": 3094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.23817610371704384}}
{"text": "/*\n * \n * Copyright (c) Kresimir Fresl 2003 \n *\n * Permission to copy, modify, use and distribute this software \n * for any non-commercial or commercial purpose is granted provided \n * that this license appear on all copies of the software source code.\n *\n * Author assumes no responsibility whatsoever for its use and makes \n * no guarantees about its quality, correctness or reliability.\n *\n * Author acknowledges the support of the Faculty of Civil Engineering, \n * University of Zagreb, Croatia.\n *\n */\n\n/* for UMFPACK Copyright, License and Availability see umfpack_inc.hpp */ \n\n\n#ifndef BOOST_NUMERIC_BINDINGS_UMFPACK_HPP\n#define BOOST_NUMERIC_BINDINGS_UMFPACK_HPP\n\n\n#include <boost/noncopyable.hpp> \n#include <boost/numeric/bindings/traits/traits.hpp>\n#include <boost/numeric/bindings/traits/sparse_traits.hpp>\n#include <boost/numeric/bindings/umfpack/umfpack_overloads.hpp>\n\n\nnamespace boost { namespace numeric { namespace bindings {  namespace umfpack {\n\n\n  template <typename T = double>\n  struct symbolic_type : private noncopyable { \n    void *ptr; \n    ~symbolic_type() { \n      if (ptr)\n        detail::free_symbolic (T(), 0, &ptr); \n    }\n    void free() {\n      if (ptr)\n        detail::free_symbolic (T(), 0, &ptr); \n      ptr = 0; \n    }\n  }; \n\n  template <typename T>\n  void free (symbolic_type<T>& s) { s.free(); }\n\n  template <typename T = double>\n  struct numeric_type : private noncopyable { \n    void *ptr; \n    ~numeric_type() { \n      if (ptr)\n        detail::free_numeric (T(), 0, &ptr); \n    }\n    void free() { \n      if (ptr)\n        detail::free_numeric (T(), 0, &ptr); \n      ptr = 0; \n    }\n  }; \n\n  template <typename T>\n  void free (numeric_type<T>& n) { n.free(); }\n\n\n  template <typename T = double>\n  struct control_type : private noncopyable {\n    double ptr[UMFPACK_CONTROL]; \n    control_type() { detail::defaults (T(), 0, ptr); }\n    double operator[] (int i) const { return ptr[i]; }\n    double& operator[] (int i) { return ptr[i]; }\n    void defaults() { detail::defaults (T(), 0, ptr); }\n  }; \n\n  template <typename T>\n  void defaults (control_type<T>& c) { c.defaults(); } \n\n  template <typename T = double>\n  struct info_type : private noncopyable {\n    double ptr[UMFPACK_INFO]; \n    double operator[] (int i) const { return ptr[i]; }\n    double& operator[] (int i) { return ptr[i]; }\n  }; \n\n\n  /////////////////////////////////////\n  // solving system of linear equations\n  /////////////////////////////////////\n\n\n  // symbolic \n  /* \n   * Given nonzero pattern of a sparse matrix A in column-oriented form,\n   * umfpack_*_symbolic performs a column pre-ordering to reduce fill-in\n   * (using COLAMD or AMD) and a symbolic factorisation.  This is required\n   * before the matrix can be numerically factorised with umfpack_*_numeric.\n   */\n  namespace detail {\n\n    template <typename MatrA>\n    inline\n    int symbolic (traits::compressed_t, \n                  MatrA const& A, void **Symbolic, \n                  double const* Control = 0, double* Info = 0) \n    {\n      return detail::symbolic (traits::spmatrix_size1 (A),\n                               traits::spmatrix_size2 (A),\n                               traits::spmatrix_index1_storage (A),\n                               traits::spmatrix_index2_storage (A),\n                               traits::spmatrix_value_storage (A),\n                               Symbolic, Control, Info); \n    }\n\n    template <typename MatrA, typename QVec>\n    inline\n    int symbolic (traits::compressed_t, \n                  MatrA const& A, QVec const& Qinit, void **Symbolic, \n                  double const* Control = 0, double* Info = 0) \n    {\n      return detail::qsymbolic (traits::spmatrix_size1 (A),\n                                traits::spmatrix_size2 (A),\n                                traits::spmatrix_index1_storage (A),\n                                traits::spmatrix_index2_storage (A),\n                                traits::spmatrix_value_storage (A),\n                                traits::vector_storage (Qinit), \n                                Symbolic, Control, Info); \n    }\n\n    template <typename MatrA>\n    inline\n    int symbolic (traits::coordinate_t, \n                  MatrA const& A, void **Symbolic, \n                  double const* Control = 0, double* Info = 0) \n    {\n      int n_row = traits::spmatrix_size1 (A); \n      int n_col = traits::spmatrix_size2 (A); \n      int nnz = traits::spmatrix_num_nonzeros (A); \n\n      typedef typename traits::sparse_matrix_traits<MatrA>::value_type val_t; \n\n      int const* Ti = traits::spmatrix_index2_storage (A);\n      int const* Tj = traits::spmatrix_index1_storage (A); \n      traits::detail::array<int> Ap (n_col+1); \n      if (!Ap.valid()) return UMFPACK_ERROR_out_of_memory;\n      traits::detail::array<int> Ai (nnz); \n      if (!Ai.valid()) return UMFPACK_ERROR_out_of_memory;\n\n      int status = detail::triplet_to_col (n_row, n_col, nnz, \n                                           Ti, Tj, static_cast<val_t*> (0),\n                                           Ap.storage(), Ai.storage(), \n                                           static_cast<val_t*> (0), 0); \n      if (status != UMFPACK_OK) return status; \n\n      return detail::symbolic (n_row, n_col, \n                               Ap.storage(), Ai.storage(),\n                               traits::spmatrix_value_storage (A),\n                               Symbolic, Control, Info); \n    }\n\n    template <typename MatrA, typename QVec>\n    inline\n    int symbolic (traits::coordinate_t, \n                  MatrA const& A, QVec const& Qinit, void **Symbolic, \n                  double const* Control = 0, double* Info = 0) \n    {\n      int n_row = traits::spmatrix_size1 (A); \n      int n_col = traits::spmatrix_size2 (A); \n      int nnz = traits::spmatrix_num_nonzeros (A); \n\n      typedef typename traits::sparse_matrix_traits<MatrA>::value_type val_t; \n\n      int const* Ti = traits::spmatrix_index2_storage (A);\n      int const* Tj = traits::spmatrix_index1_storage (A); \n      traits::detail::array<int> Ap (n_col+1); \n      if (!Ap.valid()) return UMFPACK_ERROR_out_of_memory;\n      traits::detail::array<int> Ai (nnz); \n      if (!Ai.valid()) return UMFPACK_ERROR_out_of_memory;\n\n      int status = detail::triplet_to_col (n_row, n_col, nnz, \n                                           Ti, Tj, static_cast<val_t*> (0),\n                                           Ap.storage(), Ai.storage(), \n                                           static_cast<val_t*> (0), 0); \n      if (status != UMFPACK_OK) return status; \n\n      return detail::qsymbolic (n_row, n_col, \n                                Ap.storage(), Ai.storage(),\n                                traits::spmatrix_value_storage (A),\n                                traits::vector_storage (Qinit), \n                                Symbolic, Control, Info); \n    }\n\n  } // detail \n \n  template <typename MatrA>\n  inline\n  int symbolic (MatrA const& A, \n                symbolic_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                >& Symbolic, \n                double const* Control = 0, double* Info = 0) \n  {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::matrix_structure, \n      traits::general_t\n    >::value)); \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::ordering_type,\n      traits::column_major_t\n    >::value)); \n    BOOST_STATIC_ASSERT(traits::sparse_matrix_traits<MatrA>::index_base == 0);\n#endif \n\n    typedef \n      typename traits::sparse_matrix_traits<MatrA>::storage_format storage_f; \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT(\n      (boost::is_same<storage_f, traits::compressed_t>::value\n       || \n       boost::is_same<storage_f, traits::coordinate_t>::value\n       )); \n#endif \n\n    return detail::symbolic (storage_f(), A, &Symbolic.ptr, Control, Info); \n  }\n\n  template <typename MatrA>\n  inline\n  int symbolic (MatrA const& A, \n                symbolic_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                >& Symbolic, \n                control_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                > const& Control, \n                info_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                >& Info) \n  {\n    return symbolic (A, Symbolic, Control.ptr, Info.ptr); \n  }\n\n  template <typename MatrA>\n  inline\n  int symbolic (MatrA const& A, \n                symbolic_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                >& Symbolic, \n                control_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                > const& Control)\n  {\n    return symbolic (A, Symbolic, Control.ptr); \n  }\n\n  template <typename MatrA, typename QVec>\n  inline\n  int symbolic (MatrA const& A, QVec const& Qinit, \n                symbolic_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                >& Symbolic, \n                double const* Control = 0, double* Info = 0) \n  {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::matrix_structure, \n      traits::general_t\n    >::value)); \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::ordering_type,\n      traits::column_major_t\n    >::value)); \n    BOOST_STATIC_ASSERT(traits::sparse_matrix_traits<MatrA>::index_base == 0);\n#endif \n\n    typedef \n      typename traits::sparse_matrix_traits<MatrA>::storage_format storage_f; \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT(\n      (boost::is_same<storage_f, traits::compressed_t>::value\n       || \n       boost::is_same<storage_f, traits::coordinate_t>::value\n       )); \n#endif \n\n    assert (traits::spmatrix_size2 (A) == traits::vector_size (Qinit)); \n\n    return detail::symbolic (storage_f(), A, Qinit, \n                             &Symbolic.ptr, Control, Info); \n  }\n\n  template <typename MatrA, typename QVec>\n  inline\n  int symbolic (MatrA const& A, QVec const& Qinit, \n                symbolic_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                >& Symbolic, \n                control_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                > const& Control, \n                info_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                >& Info) \n  {\n    return symbolic (A, Qinit, Symbolic, Control.ptr, Info.ptr); \n  }\n\n  template <typename MatrA, typename QVec>\n  inline\n  int symbolic (MatrA const& A, QVec const& Qinit,  \n                symbolic_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                >& Symbolic, \n                control_type<\n                  typename traits::sparse_matrix_traits<MatrA>::value_type\n                > const& Control)\n  {\n    return symbolic (A, Qinit, Symbolic, Control.ptr); \n  }\n\n\n  // numeric \n  /*\n   * Given a sparse matrix A in column-oriented form, and a symbolic analysis\n   * computed by umfpack_*_*symbolic, the umfpack_*_numeric routine performs \n   * the numerical factorisation, PAQ=LU, PRAQ=LU, or P(R\\A)Q=LU, where P \n   * and Q are permutation matrices (represented as permutation vectors), \n   * R is the row scaling, L is unit-lower triangular, and U is upper \n   * triangular.  This is required before the system Ax=b (or other related \n   * linear systems) can be solved.  \n   */\n  namespace detail {\n\n    template <typename MatrA>\n    inline\n    int numeric (traits::compressed_t, MatrA const& A, \n                 void *Symbolic, void** Numeric, \n                 double const* Control = 0, double* Info = 0) \n    {\n      return detail::numeric (traits::spmatrix_size1 (A),\n                              traits::spmatrix_size2 (A),\n                              traits::spmatrix_index1_storage (A),\n                              traits::spmatrix_index2_storage (A),\n                              traits::spmatrix_value_storage (A),\n                              Symbolic, Numeric, Control, Info); \n    }\n\n    template <typename MatrA>\n    inline\n    int numeric (traits::coordinate_t, MatrA const& A, \n                 void *Symbolic, void** Numeric, \n                 double const* Control = 0, double* Info = 0) \n    {\n      int n_row = traits::spmatrix_size1 (A); \n      int n_col = traits::spmatrix_size2 (A); \n      int nnz = traits::spmatrix_num_nonzeros (A); \n\n      typedef typename traits::sparse_matrix_traits<MatrA>::value_type val_t; \n\n      int const* Ti = traits::spmatrix_index2_storage (A);\n      int const* Tj = traits::spmatrix_index1_storage (A); \n      traits::detail::array<int> Ap (n_col+1); \n      if (!Ap.valid()) return UMFPACK_ERROR_out_of_memory;\n      traits::detail::array<int> Ai (nnz); \n      if (!Ai.valid()) return UMFPACK_ERROR_out_of_memory;\n\n      int status = detail::triplet_to_col (n_row, n_col, nnz, \n                                           Ti, Tj, static_cast<val_t*> (0),\n                                           Ap.storage(), Ai.storage(), \n                                           static_cast<val_t*> (0), 0); \n      if (status != UMFPACK_OK) return status; \n\n      return detail::numeric (n_row, n_col, \n                              Ap.storage(), Ai.storage(),\n                              traits::spmatrix_value_storage (A),\n                              Symbolic, Numeric, Control, Info); \n    }\n\n  } // detail \n\n  template <typename MatrA>\n  inline\n  int numeric (MatrA const& A, \n               symbolic_type<\n                 typename traits::sparse_matrix_traits<MatrA>::value_type\n               > const& Symbolic, \n               numeric_type<\n                 typename traits::sparse_matrix_traits<MatrA>::value_type\n               >& Numeric, \n               double const* Control = 0, double* Info = 0) \n  {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::matrix_structure, \n      traits::general_t\n    >::value)); \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::ordering_type,\n      traits::column_major_t\n    >::value)); \n    BOOST_STATIC_ASSERT(traits::sparse_matrix_traits<MatrA>::index_base == 0);\n#endif \n\n    typedef \n      typename traits::sparse_matrix_traits<MatrA>::storage_format storage_f; \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT(\n      (boost::is_same<storage_f, traits::compressed_t>::value\n       || \n       boost::is_same<storage_f, traits::coordinate_t>::value\n       )); \n#endif \n\n    return detail::numeric (storage_f(), A, \n                            Symbolic.ptr, &Numeric.ptr, Control, Info); \n  }\n\n  template <typename MatrA>\n  inline\n  int numeric (MatrA const& A, \n               symbolic_type<\n                 typename traits::sparse_matrix_traits<MatrA>::value_type\n               > const& Symbolic, \n               numeric_type<\n                 typename traits::sparse_matrix_traits<MatrA>::value_type\n               >& Numeric, \n               control_type<\n                 typename traits::sparse_matrix_traits<MatrA>::value_type\n               > const& Control, \n               info_type<\n                 typename traits::sparse_matrix_traits<MatrA>::value_type\n               >& Info) \n\n  {\n    // g++ (3.2) is unable to distinguish \n    //           function numeric() and namespace boost::numeric ;o) \n    return umfpack::numeric (A, Symbolic, Numeric, Control.ptr, Info.ptr); \n  }\n    \n  template <typename MatrA>\n  inline\n  int numeric (MatrA const& A, \n               symbolic_type<\n                 typename traits::sparse_matrix_traits<MatrA>::value_type\n               > const& Symbolic, \n               numeric_type<\n                 typename traits::sparse_matrix_traits<MatrA>::value_type\n               >& Numeric, \n               control_type<\n                 typename traits::sparse_matrix_traits<MatrA>::value_type\n               > const& Control)\n  {\n    return umfpack::numeric (A, Symbolic, Numeric, Control.ptr); \n  }\n    \n\n  // factor \n  /* \n   * symbolic and numeric\n   */\n  namespace detail {\n\n    template <typename MatrA>\n    inline\n    int factor (traits::compressed_t, MatrA const& A, \n                void** Numeric, double const* Control = 0, double* Info = 0) \n    {\n      symbolic_type<typename traits::sparse_matrix_traits<MatrA>::value_type>\n        Symbolic; \n\n      int status;\n      status = detail::symbolic (traits::spmatrix_size1 (A),\n                                 traits::spmatrix_size2 (A),\n                                 traits::spmatrix_index1_storage (A),\n                                 traits::spmatrix_index2_storage (A),\n                                 traits::spmatrix_value_storage (A),\n                                 &Symbolic.ptr, Control, Info); \n      if (status != UMFPACK_OK) return status; \n\n      return detail::numeric (traits::spmatrix_size1 (A),\n                              traits::spmatrix_size2 (A),\n                              traits::spmatrix_index1_storage (A),\n                              traits::spmatrix_index2_storage (A),\n                              traits::spmatrix_value_storage (A),\n                              Symbolic.ptr, Numeric, Control, Info); \n    }\n\n    template <typename MatrA>\n    inline\n    int factor (traits::coordinate_t, MatrA const& A, \n                void** Numeric, double const* Control = 0, double* Info = 0) \n    {\n      int n_row = traits::spmatrix_size1 (A); \n      int n_col = traits::spmatrix_size2 (A); \n      int nnz = traits::spmatrix_num_nonzeros (A); \n\n      typedef typename traits::sparse_matrix_traits<MatrA>::value_type val_t; \n\n      int const* Ti = traits::spmatrix_index2_storage (A);\n      int const* Tj = traits::spmatrix_index1_storage (A); \n      traits::detail::array<int> Ap (n_col+1); \n      if (!Ap.valid()) return UMFPACK_ERROR_out_of_memory;\n      traits::detail::array<int> Ai (nnz); \n      if (!Ai.valid()) return UMFPACK_ERROR_out_of_memory;\n\n      int status = detail::triplet_to_col (n_row, n_col, nnz, \n                                           Ti, Tj, static_cast<val_t*> (0),\n                                           Ap.storage(), Ai.storage(), \n                                           static_cast<val_t*> (0), 0); \n      if (status != UMFPACK_OK) return status; \n\n      symbolic_type<typename traits::sparse_matrix_traits<MatrA>::value_type>\n        Symbolic; \n\n      status = detail::symbolic (n_row, n_col, \n                                 Ap.storage(), Ai.storage(),\n                                 traits::spmatrix_value_storage (A),\n                                 &Symbolic.ptr, Control, Info); \n      if (status != UMFPACK_OK) return status; \n\n      return detail::numeric (n_row, n_col, \n                              Ap.storage(), Ai.storage(),\n                              traits::spmatrix_value_storage (A),\n                              Symbolic.ptr, Numeric, Control, Info); \n    }\n\n  } // detail \n\n  template <typename MatrA>\n  inline\n  int factor (MatrA const& A, \n              numeric_type<\n                typename traits::sparse_matrix_traits<MatrA>::value_type\n              >& Numeric, \n              double const* Control = 0, double* Info = 0) \n  {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::matrix_structure, \n      traits::general_t\n    >::value)); \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::ordering_type,\n      traits::column_major_t\n    >::value)); \n    BOOST_STATIC_ASSERT(traits::sparse_matrix_traits<MatrA>::index_base == 0);\n#endif \n\n    typedef \n      typename traits::sparse_matrix_traits<MatrA>::storage_format storage_f; \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT(\n      (boost::is_same<storage_f, traits::compressed_t>::value\n       || \n       boost::is_same<storage_f, traits::coordinate_t>::value\n       )); \n#endif \n\n    return detail::factor (storage_f(), A, &Numeric.ptr, Control, Info); \n  }\n\n  template <typename MatrA>\n  inline\n  int factor (MatrA const& A, \n              numeric_type<\n                typename traits::sparse_matrix_traits<MatrA>::value_type\n              >& Numeric, \n              control_type<\n                typename traits::sparse_matrix_traits<MatrA>::value_type\n              > const& Control, \n              info_type<\n                typename traits::sparse_matrix_traits<MatrA>::value_type\n              >& Info) \n  {\n    return factor (A, Numeric, Control.ptr, Info.ptr); \n  }\n    \n  template <typename MatrA>\n  inline\n  int factor (MatrA const& A, \n              numeric_type<\n                typename traits::sparse_matrix_traits<MatrA>::value_type\n              >& Numeric, \n              control_type<\n                typename traits::sparse_matrix_traits<MatrA>::value_type\n              > const& Control)\n  {\n    return factor (A, Numeric, Control.ptr); \n  }\n    \n  \n  // solve\n  /*\n   * Given LU factors computed by umfpack_*_numeric and the right-hand-side, \n   * B, solve a linear system for the solution X.  Iterative refinement is \n   * optionally performed.  Only square systems are handled. \n   */\n  namespace detail {\n\n    template <typename MatrA, typename VecX, typename VecB> \n    inline \n    int solve (traits::compressed_t, int sys, \n               MatrA const& A, VecX& X, VecB const& B, \n               void *Numeric, double const* Control = 0, double* Info = 0) \n    {\n      return detail::solve (sys, traits::spmatrix_size1 (A),\n                            traits::spmatrix_index1_storage (A),\n                            traits::spmatrix_index2_storage (A),\n                            traits::spmatrix_value_storage (A),\n                            traits::vector_storage (X),\n                            traits::vector_storage (B),\n                            Numeric, Control, Info); \n    }\n\n    template <typename MatrA, typename VecX, typename VecB> \n    inline \n    int solve (traits::coordinate_t, int sys, \n               MatrA const& A, VecX& X, VecB const& B, \n               void *Numeric, double const* Control = 0, double* Info = 0) \n    {\n\n      int n = traits::spmatrix_size1 (A); \n      int nnz = traits::spmatrix_num_nonzeros (A); \n\n      typedef typename traits::sparse_matrix_traits<MatrA>::value_type val_t; \n\n      int const* Ti = traits::spmatrix_index2_storage (A);\n      int const* Tj = traits::spmatrix_index1_storage (A); \n      traits::detail::array<int> Ap (n+1); \n      if (!Ap.valid()) return UMFPACK_ERROR_out_of_memory;\n      traits::detail::array<int> Ai (nnz); \n      if (!Ai.valid()) return UMFPACK_ERROR_out_of_memory;\n\n      int status = detail::triplet_to_col (n, n, nnz, \n                                           Ti, Tj, static_cast<val_t*> (0),\n                                           Ap.storage(), Ai.storage(), \n                                           static_cast<val_t*> (0), 0); \n      if (status != UMFPACK_OK) return status; \n \n      return detail::solve (sys, n, Ap.storage(), Ai.storage(),\n                            traits::spmatrix_value_storage (A),\n                            traits::vector_storage (X),\n                            traits::vector_storage (B),\n                            Numeric, Control, Info); \n    }\n\n  } // detail \n\n  template <typename MatrA, typename VecX, typename VecB> \n  inline \n  int solve (int sys, MatrA const& A, VecX& X, VecB const& B, \n             numeric_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             > const& Numeric, \n             double const* Control = 0, double* Info = 0) \n  {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::matrix_structure, \n      traits::general_t\n    >::value)); \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::ordering_type,\n      traits::column_major_t\n    >::value)); \n    BOOST_STATIC_ASSERT(traits::sparse_matrix_traits<MatrA>::index_base == 0);\n#endif \n\n    typedef \n      typename traits::sparse_matrix_traits<MatrA>::storage_format storage_f; \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT(\n      (boost::is_same<storage_f, traits::compressed_t>::value\n       || \n       boost::is_same<storage_f, traits::coordinate_t>::value\n       )); \n#endif \n\n    assert (traits::spmatrix_size1 (A) == traits::spmatrix_size1 (A)); \n    assert (traits::spmatrix_size2 (A) == traits::vector_size (X)); \n    assert (traits::spmatrix_size2 (A) == traits::vector_size (B)); \n\n    return detail::solve (storage_f(), sys, A, X, B, \n                          Numeric.ptr, Control, Info); \n  }\n\n  template <typename MatrA, typename VecX, typename VecB> \n  inline \n  int solve (int sys, MatrA const& A, VecX& X, VecB const& B, \n             numeric_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             > const& Numeric, \n             control_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             > const& Control, \n             info_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             >& Info) \n  {\n    return solve (sys, A, X, B, Numeric, Control.ptr, Info.ptr); \n  }\n\n  template <typename MatrA, typename VecX, typename VecB> \n  inline \n  int solve (int sys, MatrA const& A, VecX& X, VecB const& B, \n             numeric_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             > const& Numeric, \n             control_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             > const& Control)\n  {\n    return solve (sys, A, X, B, Numeric, Control.ptr); \n  }\n\n  template <typename MatrA, typename VecX, typename VecB> \n  inline \n  int solve (MatrA const& A, VecX& X, VecB const& B, \n             numeric_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             > const& Numeric, \n             double const* Control = 0, double* Info = 0) \n  {\n    return solve (UMFPACK_A, A, X, B, Numeric, Control, Info); \n  }\n\n  template <typename MatrA, typename VecX, typename VecB> \n  inline \n  int solve (MatrA const& A, VecX& X, VecB const& B, \n             numeric_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             > const& Numeric, \n             control_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             > const& Control, \n             info_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             >& Info) \n  {\n    return solve (UMFPACK_A, A, X, B, Numeric, \n                  Control.ptr, Info.ptr); \n  }\n\n  template <typename MatrA, typename VecX, typename VecB> \n  inline \n  int solve (MatrA const& A, VecX& X, VecB const& B, \n             numeric_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             > const& Numeric, \n             control_type<\n               typename traits::sparse_matrix_traits<MatrA>::value_type\n             > const& Control)\n  {\n    return solve (UMFPACK_A, A, X, B, Numeric, Control.ptr); \n  }\n\n\n  // umf_solve \n  /* \n   * symbolic, numeric and solve \n   */\n  namespace detail {\n\n    template <typename MatrA, typename VecX, typename VecB>\n    inline\n    int umf_solve (traits::compressed_t, \n                   MatrA const& A, VecX& X, VecB const& B, \n                   double const* Control = 0, double* Info = 0) \n    {\n      symbolic_type<typename traits::sparse_matrix_traits<MatrA>::value_type>\n        Symbolic; \n      numeric_type<typename traits::sparse_matrix_traits<MatrA>::value_type>\n        Numeric; \n\n      int status;\n      status = detail::symbolic (traits::spmatrix_size1 (A),\n                                 traits::spmatrix_size2 (A),\n                                 traits::spmatrix_index1_storage (A),\n                                 traits::spmatrix_index2_storage (A),\n                                 traits::spmatrix_value_storage (A),\n                                 &Symbolic.ptr, Control, Info); \n      if (status != UMFPACK_OK) return status; \n\n      status = detail::numeric (traits::spmatrix_size1 (A),\n                                traits::spmatrix_size2 (A),\n                                traits::spmatrix_index1_storage (A),\n                                traits::spmatrix_index2_storage (A),\n                                traits::spmatrix_value_storage (A),\n                                Symbolic.ptr, &Numeric.ptr, Control, Info); \n      if (status != UMFPACK_OK) return status; \n\n      return detail::solve (UMFPACK_A, traits::spmatrix_size1 (A),\n                            traits::spmatrix_index1_storage (A),\n                            traits::spmatrix_index2_storage (A),\n                            traits::spmatrix_value_storage (A),\n                            traits::vector_storage (X),\n                            traits::vector_storage (B),\n                            Numeric.ptr, Control, Info); \n    }\n\n    template <typename MatrA, typename VecX, typename VecB>\n    inline\n    int umf_solve (traits::coordinate_t, \n                   MatrA const& A, VecX& X, VecB const& B, \n                   double const* Control = 0, double* Info = 0) \n    {\n      int n_row = traits::spmatrix_size1 (A); \n      int n_col = traits::spmatrix_size2 (A); \n      int nnz = traits::spmatrix_num_nonzeros (A); \n\n      typedef typename traits::sparse_matrix_traits<MatrA>::value_type val_t; \n\n      int const* Ti = traits::spmatrix_index2_storage (A);\n      int const* Tj = traits::spmatrix_index1_storage (A); \n      traits::detail::array<int> Ap (n_col+1); \n      if (!Ap.valid()) return UMFPACK_ERROR_out_of_memory;\n      traits::detail::array<int> Ai (nnz); \n      if (!Ai.valid()) return UMFPACK_ERROR_out_of_memory;\n\n      int status = detail::triplet_to_col (n_row, n_col, nnz, \n                                           Ti, Tj, static_cast<val_t*> (0),\n                                           Ap.storage(), Ai.storage(), \n                                           static_cast<val_t*> (0), 0); \n      if (status != UMFPACK_OK) return status; \n\n      symbolic_type<typename traits::sparse_matrix_traits<MatrA>::value_type>\n        Symbolic; \n      numeric_type<typename traits::sparse_matrix_traits<MatrA>::value_type>\n        Numeric; \n\n      status = detail::symbolic (n_row, n_col, \n                                 Ap.storage(), Ai.storage(),\n                                 traits::spmatrix_value_storage (A),\n                                 &Symbolic.ptr, Control, Info); \n      if (status != UMFPACK_OK) return status; \n\n      status = detail::numeric (n_row, n_col, \n                                Ap.storage(), Ai.storage(),\n                                traits::spmatrix_value_storage (A),\n                                Symbolic.ptr, &Numeric.ptr, Control, Info); \n      if (status != UMFPACK_OK) return status; \n\n      return detail::solve (UMFPACK_A, n_row, Ap.storage(), Ai.storage(),\n                            traits::spmatrix_value_storage (A),\n                            traits::vector_storage (X),\n                            traits::vector_storage (B),\n                            Numeric.ptr, Control, Info); \n    }\n\n  } // detail \n\n  template <typename MatrA, typename VecX, typename VecB>\n  inline\n  int umf_solve (MatrA const& A, VecX& X, VecB const& B, \n                 double const* Control = 0, double* Info = 0) \n  {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::matrix_structure, \n      traits::general_t\n    >::value)); \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::ordering_type,\n      traits::column_major_t\n    >::value)); \n    BOOST_STATIC_ASSERT(traits::sparse_matrix_traits<MatrA>::index_base == 0);\n#endif \n\n    typedef \n      typename traits::sparse_matrix_traits<MatrA>::storage_format storage_f; \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT(\n      (boost::is_same<storage_f, traits::compressed_t>::value\n       || \n       boost::is_same<storage_f, traits::coordinate_t>::value\n       )); \n#endif \n\n    assert (traits::spmatrix_size1 (A) == traits::spmatrix_size1 (A)); \n    assert (traits::spmatrix_size2 (A) == traits::vector_size (X)); \n    assert (traits::spmatrix_size2 (A) == traits::vector_size (B)); \n\n    return detail::umf_solve (storage_f(), A, X, B, Control, Info); \n  }\n\n  template <typename MatrA, typename VecX, typename VecB>\n  inline\n  int umf_solve (MatrA const& A, VecX& X, VecB const& B, \n                 control_type<\n                   typename traits::sparse_matrix_traits<MatrA>::value_type\n                 > const& Control, \n                 info_type<\n                   typename traits::sparse_matrix_traits<MatrA>::value_type\n                 >& Info) \n  {\n    return umf_solve (A, X, B, Control.ptr, Info.ptr); \n  }    \n\n  template <typename MatrA, typename VecX, typename VecB>\n  inline\n  int umf_solve (MatrA const& A, VecX& X, VecB const& B, \n                 control_type<\n                   typename traits::sparse_matrix_traits<MatrA>::value_type\n                 > const& Control)\n  {\n    return umf_solve (A, X, B, Control.ptr); \n  }    \n\n\n  ///////////////////////\n  // matrix manipulations\n  ///////////////////////\n\n\n  // scale \n  \n  template <typename VecX, typename VecB> \n  inline \n  int scale (VecX& X, VecB const& B, \n             numeric_type<\n               typename traits::vector_traits<VecB>::value_type\n             > const& Numeric) \n  {\n    return detail::scale (traits::vector_size (B),\n                          traits::vector_storage (X),\n                          traits::vector_storage (B),\n                          Numeric.ptr);\n  }\n\n\n  ////////////\n  // reporting\n  ////////////\n\n\n  // report status\n\n  template <typename T>\n  inline\n  void report_status (control_type<T> const& Control, int status) {\n    detail::report_status (T(), 0, Control.ptr, status); \n  }\n\n#if 0\n  template <typename T>\n  inline\n  void report_status (int printing_level, int status) {\n    control_type<T> Control; \n    Control[UMFPACK_PRL] = printing_level; \n    detail::report_status (T(), 0, Control.ptr, status); \n  }\n  template <typename T>\n  inline\n  void report_status (int status) {\n    control_type<T> Control; \n    detail::report_status (T(), 0, Control.ptr, status); \n  }\n#endif \n  \n\n  // report control\n\n  template <typename T>\n  inline\n  void report_control (control_type<T> const& Control) {\n    detail::report_control (T(), 0, Control.ptr); \n  }\n  \n\n  // report info \n\n  template <typename T>\n  inline\n  void report_info (control_type<T> const& Control, info_type<T> const& Info) {\n    detail::report_info (T(), 0, Control.ptr, Info.ptr); \n  }\n\n#if 0\n  template <typename T>\n  inline\n  void report_info (int printing_level, info_type<T> const& Info) {\n    control_type<T> Control; \n    Control[UMFPACK_PRL] = printing_level; \n    detail::report_info (T(), 0, Control.ptr, Info.ptr); \n  }\n  template <typename T>\n  inline\n  void report_info (info_type<T> const& Info) {\n    control_type<T> Control; \n    detail::report_info (T(), 0, Control.ptr, Info.ptr); \n  }\n#endif \n\n\n  // report matrix (compressed column and coordinate) \n\n  namespace detail {\n\n    template <typename MatrA>\n    inline\n    int report_matrix (traits::compressed_t, MatrA const& A, \n                       double const* Control)\n    {\n      return detail::report_matrix (traits::spmatrix_size1 (A),\n                                    traits::spmatrix_size2 (A),\n                                    traits::spmatrix_index1_storage (A),\n                                    traits::spmatrix_index2_storage (A),\n                                    traits::spmatrix_value_storage (A),\n                                    1, Control); \n    }\n    \n    template <typename MatrA>\n    inline\n    int report_matrix (traits::coordinate_t, MatrA const& A, \n                       double const* Control)\n    {\n      return detail::report_triplet (traits::spmatrix_size1 (A),\n                                     traits::spmatrix_size2 (A),\n                                     traits::spmatrix_num_nonzeros (A), \n                                     traits::spmatrix_index1_storage (A),\n                                     traits::spmatrix_index2_storage (A),\n                                     traits::spmatrix_value_storage (A),\n                                     Control); \n    }\n    \n  } // detail \n\n  template <typename MatrA>\n  inline\n  int report_matrix (MatrA const& A, \n                     control_type<\n                       typename traits::sparse_matrix_traits<MatrA>::value_type\n                     > const& Control) \n  {\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::matrix_structure, \n      traits::general_t\n    >::value)); \n    BOOST_STATIC_ASSERT((boost::is_same<\n      typename traits::sparse_matrix_traits<MatrA>::ordering_type,\n      traits::column_major_t\n    >::value)); \n    BOOST_STATIC_ASSERT(traits::sparse_matrix_traits<MatrA>::index_base == 0);\n#endif \n\n    typedef \n      typename traits::sparse_matrix_traits<MatrA>::storage_format storage_f; \n\n#ifndef BOOST_NUMERIC_BINDINGS_NO_STRUCTURE_CHECK \n    BOOST_STATIC_ASSERT(\n      (boost::is_same<storage_f, traits::compressed_t>::value\n       || \n       boost::is_same<storage_f, traits::coordinate_t>::value\n       )); \n#endif \n\n    return detail::report_matrix (storage_f(), A, Control.ptr); \n  }\n\n\n  // report vector \n\n  template <typename VecX>\n  inline\n  int report_vector (VecX const& X, \n                     control_type<\n                       typename traits::vector_traits<VecX>::value_type\n                     > const& Control) \n  {\n    return detail::report_vector (traits::vector_size (X), \n                                  traits::vector_storage (X), \n                                  Control.ptr);\n  }\n\n\n  // report numeric \n\n  template <typename T> \n  inline\n  int report_numeric (numeric_type<T> const& Numeric, \n                      control_type<T> const& Control)\n  {\n    return detail::report_numeric (T(), 0, Numeric.ptr, Control.ptr); \n  }\n\n\n  // report symbolic \n\n  template <typename T> \n  inline\n  int report_symbolic (symbolic_type<T> const& Symbolic, \n                       control_type<T> const& Control)\n  {\n    return detail::report_symbolic (T(), 0, Symbolic.ptr, Control.ptr); \n  }\n\n\n  // report permutation vector \n\n  template <typename VecP, typename T> \n  inline\n  int report_permutation (VecP const& Perm, control_type<T> const& Control) {\n    return detail::report_perm (T(), 0, \n                                traits::vector_storage (Perm),\n                                Control.ptr); \n  }\n\n\n}}}} \n\n#endif // BOOST_NUMERIC_BINDINGS_UMFPACK_HPP\n", "meta": {"hexsha": "4d3f56db1dfb4daaf121e5ce13b84579399ec8be", "size": 39400, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/umfpack/umfpack.hpp", "max_stars_repo_name": "jiaqiwang969/Kratos-test", "max_stars_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/umfpack/umfpack.hpp", "max_issues_repo_name": "jiaqiwang969/Kratos-test", "max_issues_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/mkl_solvers_application/external_includes/boost/numeric/bindings/umfpack/umfpack.hpp", "max_forks_repo_name": "jiaqiwang969/Kratos-test", "max_forks_repo_head_hexsha": "ed082abc163e7b627f110a1ae1da465f52f48348", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1471900089, "max_line_length": 79, "alphanum_fraction": 0.5746446701, "num_tokens": 9377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.23805744206368928}}
{"text": "#ifndef CAT2MAP_HPP\n#define CAT2MAP_HPP\n\n#include <fstream>\n#include <iostream>\n#include <exception>\n#include <vector>\n#include <cmath>\n#include <cassert>\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n#include <boost/log/trivial.hpp>\n#include <boost/tokenizer.hpp>\n\n#include <healpix_map.h>\n#include <pointing.h>\n#include <healpix_map_fitsio.h>\n#include <datatypes.h>\n\n/**\n * \\class Cat2Map\n * \\brief A class for converting catalogues to HEALPix maps\n *\n * This class reads a catalogue and convert the information to a\n * HEALPix map.\n */\nclass Cat2Map\n{\npublic:\n\n    /**\n     * \\typedef boost::property_tree::ptree propertyTreeType\n     * \\brief defines the property tree type\n     */\n    typedef boost::property_tree::ptree propertyTreeType;\n\n    /**\n     * \\typedef Healpix_Map<double> mapType\n     * \\brief defines the HEALPix map type\n     */\n    typedef Healpix_Map<double> mapType;\n\n    static const constexpr double deg2rad = M_PI/double(180);/**< factor for converting degree to radians */\n    static const constexpr double rotPhi = double(0); /**< rotaion to phi required for convertion from ra */\n\n    /**\n     * \\brief The default constructor\n     *\n     * \\param iniFileName name of the input configuration file\n     */\n    explicit Cat2Map(std::string const& iniFileName)\n    {\n        BOOST_LOG_TRIVIAL(info) << std::string(\"Reading the ini file \") + std::string(iniFileName);\n        boost::property_tree::ini_parser::read_ini(iniFileName,mPropTree);\n\n        // set the output maps\n        BOOST_LOG_TRIVIAL(info) << \"Resulution of the output map is \"<<mPropTree.get<std::string>(\"output.n_side\");\n\n        int nSide = mPropTree.get<int>(\"output.n_side\");\n        mMapN.SetNside(nSide,RING);\n        mMapNNInv.SetNside(nSide,RING);\n        mMapE1.SetNside(nSide,RING);\n        mMapE2.SetNside(nSide,RING);\n        mMapE1NInv.SetNside(nSide,RING);\n        mMapE2NInv.SetNside(nSide,RING);\n\n        mMapN.fill(double(0));\n        mMapNNInv.fill(double(0));\n        mMapE1.fill(double(0));\n        mMapE1.fill(double(0));\n        mMapE1NInv.fill(double(0));\n        mMapE2NInv.fill(double(0));\n\n        // read the mask\n        read_Healpix_map_from_fits(mPropTree.get<std::string>(\"input.mask_file_name\"),mMask);\n\n        try\n        {\n            std::string testMapFileName = mPropTree.get<std::string>(\"test.map_file_name\");\n\n            BOOST_LOG_TRIVIAL(info) << \"Test map file specified as \"<< testMapFileName;\n\n            read_Healpix_map_from_fits(testMapFileName,mTestE1,int(2),int(2));\n            read_Healpix_map_from_fits(testMapFileName,mTestE2,int(3),int(2));\n\n            mDoTest = true;\n        }\n        catch(std::exception)\n        {\n            BOOST_LOG_TRIVIAL(info) << \"No test map file specified.\";\n            mDoTest = false;\n        }\n\n\n        try\n        {\n            std::string testMapFileName = mPropTree.get<std::string>(\"output.z_bounds\");\n            BOOST_LOG_TRIVIAL(info) << \"z bounds specified as \"<< testMapFileName;\n            typedef boost::tokenizer<boost::char_separator<char> > tokenizer;\n            boost::char_separator<char> sep(\",\");\n            tokenizer tokens(testMapFileName, sep);\n\n\n            for(tokenizer::iterator tokIter = tokens.begin(); tokIter !=tokens.end(); ++tokIter)\n            {\n                mZBounds.push_back(boost::lexical_cast<double>(*tokIter));\n            }\n        }\n        catch(std::exception)\n        {\n            BOOST_LOG_TRIVIAL(info) << \"No z bounds specified. All objects will be accumulated.\";\n        }\n\n        if(mZBounds.size() != size_t(2))\n        {\n            std::string msg(\"The z-bounds should consist of two values. No more, no less.\");\n            throw std::runtime_error(msg);\n        }\n\n        if(mZBounds[0] >= mZBounds[1])\n        {\n            std::string msg(\"The upper bound should be greater than the lower bound.\");\n            throw std::runtime_error(msg);\n        }\n\n        mMisMatchCountE1 = size_t(0);\n        mMisMatchCountE2 = size_t(0);\n        mNumObsPix = size_t(0);\n    }\n\n    /**\n     * \\brief A function that accumulates the objects in a catalogue\n     */\n    void accumulate()\n    {\n        // open file for reading\n        std::ifstream inputCatFile;\n        inputCatFile.open( mPropTree.get<std::string>(\"input.catlogue_file_name\").c_str(),std::ios::in );\n\n\n        if(inputCatFile.is_open())\n        {\n\n            BOOST_LOG_TRIVIAL(info) << \"Accumulating objects\";\n            BOOST_LOG_TRIVIAL(info) << \"Number of rows to be skipped = \" << mPropTree.get<std::string>(\"input.skip_rows\");\n            BOOST_LOG_TRIVIAL(info) << \"Delimiter for separation is \"<< mPropTree.get<std::string>(\"input.delimiter\");\n\n            size_t col_ra =  mPropTree.get<size_t>(\"input.col_ra\");\n            size_t col_dec =  mPropTree.get<size_t>(\"input.col_dec\");\n            size_t col_z = mPropTree.get<size_t>(\"input.col_z\");\n            size_t col_ellip_1 = mPropTree.get<size_t>(\"input.col_ellip_1\");\n            size_t col_ellip_2 = mPropTree.get<size_t>(\"input.col_ellip_2\");\n\n            BOOST_LOG_TRIVIAL(info) << \"Column of ra values = \"<< col_ra;\n            BOOST_LOG_TRIVIAL(info) << \"Column of dec values = \"<< col_dec;\n            BOOST_LOG_TRIVIAL(info) << \"Column of z values = \"<< col_z;\n            BOOST_LOG_TRIVIAL(info) << \"Column of ellip_1 values = \"<< col_ellip_1;\n            BOOST_LOG_TRIVIAL(info) << \"Column of ellip_2 values = \"<< col_ellip_2;\n\n\n\n\n            size_t line_id = 0;\n            while(!inputCatFile.eof())\n            {\n                std::string line;\n\n                std::getline(inputCatFile,line);\n\n                ++line_id;\n\n                if(line_id > mPropTree.get<size_t>(\"input.skip_rows\"))\n                {\n                    typedef boost::tokenizer<boost::char_separator<char> > tokenizer;\n                    boost::char_separator<char> sep(mPropTree.get<std::string>(\"input.delimiter\").c_str());\n                    tokenizer tokens(line, sep);\n\n                    std::vector<double> ents;\n                    for(tokenizer::iterator tokIter = tokens.begin(); tokIter !=tokens.end(); ++tokIter)\n                    {\n                        ents.push_back(boost::lexical_cast<double>(*tokIter));\n                    }\n\n                    if(ents.size()>0)\n                    {\n                        assert(col_ra<ents.size());\n                        assert(col_dec<ents.size());\n                        assert(col_ellip_1<ents.size());\n                        assert(col_ellip_2<ents.size());\n\n                        double ra = ents[col_ra];\n                        double dec = ents[col_dec];\n                        double z = ents[col_z];\n                        double e1 = ents[col_ellip_1];\n                        double e2 = ents[col_ellip_2];\n\n                        double theta = -deg2rad*dec + M_PI*double(0.5);\n                        double phi = deg2rad*(ra - rotPhi);\n\n                        auto pix = mMapE1.ang2pix(pointing(theta,phi));\n\n\n                        // check if the pixel falls in the masked region\n                        if(mMask[pix]>0)\n                        {\n                            if(z >= mZBounds[0] and z < mZBounds[1])\n                            {\n                                if(mDoTest)\n                                {\n                                    // if testing accumulate the miss-match\n                                    // between pixel values\n                                    if(std::abs( (e1 - mTestE1[pix])/e1 ) >= 1e-5)\n                                    {\n                                        mMisMatchCountE1 += size_t(1);\n                                    }\n\n                                    if(std::abs( (e2 - mTestE2[pix])/e2 ) > 1e-5)\n                                    {\n                                        mMisMatchCountE2 += size_t(1);\n                                    }\n                                }\n\n                                // do accumulation\n                                mMapN[pix] += double(1);\n                                mMapE1[pix] += e1;\n                                mMapE2[pix] += e2;\n                                mMapE1NInv[pix] += e1*e1;\n                                mMapE2NInv[pix] += e2*e2;\n                                //mNumObsPix += size_t(1); //TODO this is wrong\n                            }\n                        }\n\n                    }\n\n                }\n                else\n                {\n                    BOOST_LOG_TRIVIAL(info) << \"Skipping line \" << line_id;\n                }\n            }\n\n            // make it the average , also count the total objects\n            double totObjs(0);\n            for(auto pix = 0; pix<mMapN.Npix(); ++pix)\n            {\n                if(mMapN[pix]>0) // TODO how many gals we need to make an estimate\n                {\n                    mMapE1[pix] /= mMapN[pix];\n                    mMapE2[pix] /= mMapN[pix];\n\n                    // var = E(X^2) - E(X)^2\n                    mMapE1NInv[pix] = ( mMapE1NInv[pix]/mMapN[pix] - mMapE1[pix]*mMapE1[pix]);\n                    mMapE2NInv[pix] = ( mMapE2NInv[pix]/mMapN[pix] - mMapE2[pix]*mMapE2[pix]);\n\n                    // nInv = 1/var\n                    if(mMapE1NInv[pix] > double(0) and mMapE2NInv[pix] > double(0) )\n                    {\n                        mMapE1NInv[pix] = double(1)/mMapE1NInv[pix];\n                        mMapE2NInv[pix] = double(1)/mMapE2NInv[pix];\n\n                        // compute the observed number of pixels in the data\n                        mNumObsPix += size_t(1);\n                        totObjs += mMapN[pix];\n\n                        //mMapNNInv[pix] = nbar; //TODO note that I may have to recalculate this again\n                    }\n                    else\n                    {\n                        // we don't have the variance properly defined\n                        mMask[pix] = 0;\n                        mMapE1NInv[pix] = 0.;\n                        mMapE2NInv[pix] = 0;\n                        mMapE1[pix] = 0;\n                        mMapE2[pix] = 0;\n                        mMapN[pix] = 0;\n                        mMapNNInv[pix] = 0;\n                    }\n                }\n                else\n                {\n                    // make the new mask\n                    mMask[pix] = 0;\n                    mMapE1NInv[pix] = 0.;\n                    mMapE2NInv[pix] = 0;\n                    mMapE1[pix] = 0;\n                    mMapE2[pix] = 0;\n                    mMapNNInv[pix] = 0;\n                }\n            }\n\n            // output the sky fraction of the augmented mask\n            size_t nPix = (size_t) mTestE1.Npix();\n            double fKsy = (double)mNumObsPix / (double)nPix;\n            BOOST_LOG_TRIVIAL(info) << \"Sky fraction \" << fKsy;\n\n            BOOST_LOG_TRIVIAL(info) << \"Toal objects in the map \" << totObjs;\n\n            // output the n_bar or the mean number of objects per pixel\n            double nBar = totObjs/(double)mNumObsPix;\n            BOOST_LOG_TRIVIAL(info) << \"Mean objects per pixel \" << nBar;\n\n            assert(nBar > double(0));\n\n            // assign nbar to nInv map for number density\n            for(auto pix = 0; pix<mMapN.Npix(); ++pix)\n            {\n                if(mMapN[pix] > 0)\n                {\n                    mMapN[pix] = (mMapN[pix] - nBar)/nBar;\n                    mMapNNInv[pix] = nBar;\n                }\n            }\n\n            // if testing print the mismatch stats\n            if(mDoTest)\n            {\n\n                double fracMissMatchE1 = (double)mMisMatchCountE1 / (double)mNumObsPix;\n                double fracMissMatchE2 = (double)mMisMatchCountE2 / (double)mNumObsPix;\n\n                BOOST_LOG_TRIVIAL(warning) << \"Pixel value miss-match for e1 = \"<<fracMissMatchE1;\n                BOOST_LOG_TRIVIAL(warning) << \"Pixel value miss-match for e2 = \"<<fracMissMatchE2;\n            }\n        }\n        else\n        {\n            std::string msg = std::string(\"Input catalogue file \")\n                + std::string(mPropTree.get<std::string>(\"input.catlogue_file_name\"))\n                + std::string(\" failed to open.\");\n            BOOST_LOG_TRIVIAL(error) << msg;\n            throw std::runtime_error(msg);\n        }\n\n    }\n\n    /**\n     * \\brief write the maps to fits files\n     */\n    void writeMaps()\n    {\n        BOOST_LOG_TRIVIAL(info) << \"Output data map file name :  \"\n            << mPropTree.get<std::string>(\"output.data_map_file_name\");\n\n        write_Healpix_map_to_fits(std::string(\"!\")+mPropTree.get<std::string>(\"output.data_map_file_name\"),\n            mMapN,mMapE1,mMapE2,planckType<double>());\n\n        BOOST_LOG_TRIVIAL(info) << \"Output nInv map file name :  \"\n            << mPropTree.get<std::string>(\"output.nInv_map_file_name\");\n\n        write_Healpix_map_to_fits(std::string(\"!\")+mPropTree.get<std::string>(\"output.nInv_map_file_name\"),\n            mMapNNInv,mMapE1NInv,mMapE2NInv,planckType<double>());\n\n        BOOST_LOG_TRIVIAL(info) << \"Output augmented mask file name :  \"\n            << mPropTree.get<std::string>(\"output.augmented_mask_file_name\");\n\n        write_Healpix_map_to_fits(std::string(\"!\")+mPropTree.get<std::string>(\"output.augmented_mask_file_name\"),\n            mMask,planckType<double>());\n    }\n\nprivate:\n    propertyTreeType mPropTree; /**< property tree that stores the ini file information */\n    mapType mMapN; /**< number density map */\n    mapType mMapNNInv; /**< number density map */\n    mapType mMapE1; /**<  ellipticity-1 map */\n    mapType mMapE2; /**< ellipticity-2 map */\n    mapType mMapE1NInv; /**<  ellipticity-1 nInv map */\n    mapType mMapE2NInv; /**< ellipticity-2 nInv map */\n    mapType mMask; /**< mask */\n    std::vector<double> mZBounds; /**< z bounds */\n\n    mapType mTestE1; /**<  ellipticity-1 test map*/\n    mapType mTestE2; /**< ellipticity-2 test map */\n    bool mDoTest; /**< a flag to to sanity test */\n    size_t mMisMatchCountE1; /**< sanity check mismatch for ellipticity-1*/\n    size_t mMisMatchCountE2; /**< sanity check mismatch for ellipticity-2*/\n    size_t mNumObsPix; /**< number of observed pixels*/\n\n};\n\n\n#endif //CAT2MAP_HPP\n", "meta": {"hexsha": "fd6e99af0295cb75248a60c1944bb307767e3d5d", "size": 14178, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Cat2Map.hpp", "max_stars_repo_name": "tbs1980/Cat2Map", "max_stars_repo_head_hexsha": "ce7321c3b4f6b554c7725bbf078614d53fedfa99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-12-06T21:48:30.000Z", "max_stars_repo_stars_event_max_datetime": "2015-12-08T09:01:11.000Z", "max_issues_repo_path": "Cat2Map.hpp", "max_issues_repo_name": "tbs1980/Cat2Map", "max_issues_repo_head_hexsha": "ce7321c3b4f6b554c7725bbf078614d53fedfa99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cat2Map.hpp", "max_forks_repo_name": "tbs1980/Cat2Map", "max_forks_repo_head_hexsha": "ce7321c3b4f6b554c7725bbf078614d53fedfa99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0182767624, "max_line_length": 122, "alphanum_fraction": 0.51558753, "num_tokens": 3391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2380543390839296}}
{"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2014, 2015, 2016.\r\n// Modifications copyright (c) 2014-2016 Oracle and/or its affiliates.\r\n\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_SIDE_DETAIL_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_SIDE_DETAIL_HPP\r\n\r\n#include <boost/geometry/core/cs.hpp>\r\n#include <boost/geometry/core/access.hpp>\r\n#include <boost/geometry/core/radian_access.hpp>\r\n#include <boost/geometry/core/radius.hpp>\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <boost/geometry/util/promote_floating_point.hpp>\r\n#include <boost/geometry/util/select_calculation_type.hpp>\r\n\r\n#include <boost/geometry/strategies/side.hpp>\r\n//#include <boost/geometry/strategies/concepts/side_concept.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\n\r\nnamespace strategy { namespace side\r\n{\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail\r\n{\r\n\r\n/*!\r\n\\brief Check at which side of a segment a point lies\r\n         left of segment (> 0), right of segment (< 0), on segment (0)\r\n\\ingroup strategies\r\n\\tparam InverseFormula Geodesic inverse solution formula.\r\n\\tparam Model Reference model of coordinate system.\r\n\\tparam CalculationType \\tparam_calculation\r\n */\r\ntemplate <template<typename, bool, bool, bool, bool, bool> class InverseFormula,\r\n          typename Model,\r\n          typename CalculationType = void>\r\nclass by_azimuth\r\n{\r\npublic:\r\n    by_azimuth(Model const& model = Model())\r\n        : m_model(model)\r\n    {}\r\n\r\n    template <typename P1, typename P2, typename P>\r\n    inline int apply(P1 const& p1, P2 const& p2, P const& p)\r\n    {\r\n        typedef typename promote_floating_point\r\n            <\r\n                typename select_calculation_type_alt\r\n                    <\r\n                        CalculationType,\r\n                        P1, P2, P\r\n                    >::type\r\n            >::type calc_t;\r\n\r\n        typedef InverseFormula<calc_t, false, true, false, false, false> inverse_formula;\r\n\r\n        calc_t a1p = azimuth<calc_t, inverse_formula>(p1, p, m_model);\r\n        calc_t a12 = azimuth<calc_t, inverse_formula>(p1, p2, m_model);\r\n\r\n        calc_t const pi = math::pi<calc_t>();\r\n\r\n        // instead of the formula from XTD\r\n        //calc_t a_diff = asin(sin(a1p - a12));\r\n\r\n        calc_t a_diff = a1p - a12;\r\n        // normalize, angle in [-pi, pi]\r\n        while ( a_diff > pi )\r\n            a_diff -= calc_t(2) * pi;\r\n        while ( a_diff < -pi )\r\n            a_diff += calc_t(2) * pi;\r\n\r\n        // NOTE: in general it shouldn't be required to support the pi/-pi case\r\n        // because in non-cartesian systems it makes sense to check the side\r\n        // only \"between\" the endpoints.\r\n        // However currently the winding strategy calls the side strategy\r\n        // for vertical segments to check if the point is \"between the endpoints.\r\n        // This could be avoided since the side strategy is not required for that\r\n        // because meridian is the shortest path. So a difference of\r\n        // longitudes would be sufficient (of course normalized to [-pi, pi]).\r\n\r\n        // NOTE: with the above said, the pi/-pi check is temporary\r\n        // however in case if this was required\r\n        // the geodesics on ellipsoid aren't \"symmetrical\"\r\n        // therefore instead of comparing a_diff to pi and -pi\r\n        // one should probably use inverse azimuths and compare\r\n        // the difference to 0 as well\r\n\r\n        // positive azimuth is on the right side\r\n        return math::equals(a_diff, 0)\r\n            || math::equals(a_diff, pi)\r\n            || math::equals(a_diff, -pi) ? 0\r\n             : a_diff > 0 ? -1 // right\r\n             : 1; // left\r\n    }\r\n\r\nprivate:\r\n    template <typename ResultType,\r\n              typename InverseFormulaType,\r\n              typename Point1,\r\n              typename Point2,\r\n              typename ModelT>\r\n    static inline ResultType azimuth(Point1 const& point1, Point2 const& point2, ModelT const& model)\r\n    {\r\n        return InverseFormulaType::apply(get_as_radian<0>(point1),\r\n                                         get_as_radian<1>(point1),\r\n                                         get_as_radian<0>(point2),\r\n                                         get_as_radian<1>(point2),\r\n                                         model).azimuth;\r\n    }\r\n\r\n    Model m_model;\r\n};\r\n\r\n} // detail\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n}} // namespace strategy::side\r\n\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_GEOGRAPHIC_SIDE_DETAIL_HPP\r\n", "meta": {"hexsha": "100c52aa3d6ef6eaceb0cc3c32d5f5f0d6024347", "size": 4835, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/strategies/geographic/side_detail.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/strategies/geographic/side_detail.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/geometry/strategies/geographic/side_detail.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 34.5357142857, "max_line_length": 102, "alphanum_fraction": 0.6221302999, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771035, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23805433254249597}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2006-2012, 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#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <cstdlib>\n#include <iostream>\n#include <cmath>\n#include <boost/tokenizer.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n#include <boost/program_options.hpp>\n#include <boost/filesystem/path.hpp>\n#include <boost/foreach.hpp>\nnamespace fs = boost::filesystem;\nnamespace po = boost::program_options;\n\n#include <vw/Core/Functors.h>\n#include <vw/Image/Algorithms.h>\n#include <vw/Image/ImageMath.h>\n#include <vw/Image/ImageViewRef.h>\n#include <vw/Image/PerPixelViews.h>\n#include <vw/Image/PixelMask.h>\n#include <vw/Image/MaskViews.h>\n#include <vw/Image/PixelTypes.h>\n#include <vw/Image/Statistics.h>\n#include <vw/FileIO/DiskImageView.h>\n#include <vw/Cartography/GeoReference.h>\n#include <vw/tools/Common.h>\n#include <vw/FileIO/DiskImageResourceGDAL.h>\n#include <vw/Image/Interpolation.h>\n#include <asp/Core/Macros.h>\n#include <asp/Core/Common.h>\n\nusing namespace vw;\nusing namespace vw::cartography;\n\nstruct Options : asp::BaseOptions {};\n\n// Convolve a DEM with exp(-sigma*x^2). The input DEM must\n// have its invalid pixels masked.\n\ntemplate <class ImageT>\nclass BlurDEM:\n  public ImageViewBase< BlurDEM<ImageT> > {\n  ImageT m_img;\n  int m_search_dist; // half of size of window to convolve with\n  ImageView<double> m_gauss_kernel;\n  typedef typename ImageT::pixel_type PixelT;\n\npublic:\n\n  typedef PixelT pixel_type;\n  typedef PixelT result_type;\n  typedef ProceduralPixelAccessor<BlurDEM> pixel_accessor;\n\n  BlurDEM( ImageViewBase<ImageT> const& img,\n                     double blur_sigma) :\n    m_img(img.impl()) {\n    VW_ASSERT(blur_sigma > 0,\n              ArgumentErr() << \"Expecting positive sigma.\");\n\n    // Cut the gaussian exp(-sigma*x^2) where its value is 'scale'.\n    double scale = 0.001;\n    m_search_dist = (int)ceil(sqrt(-log(scale)/blur_sigma));\n    std::cout << \"Search distance is \" << m_search_dist << std::endl;\n\n    // The gaussian kernel\n    int h = m_search_dist;\n    m_gauss_kernel.set_size(2*h+1, 2*h+1);\n    for (int c = 0; c < m_gauss_kernel.cols(); c++){\n      for (int r = 0; r < m_gauss_kernel.rows(); r++){\n        double r2 = double(c-h)*(c-h) + double(r-h)*(r-h);\n        m_gauss_kernel(c, r) = exp(-blur_sigma*r2);\n      }\n    }\n  \n  }\n\n  inline int32 cols() const { return m_img.cols(); }\n  inline int32 rows() const { return m_img.rows(); }\n  inline int32 planes() const { return 1; }\n\n  inline pixel_accessor origin() const { return pixel_accessor(*this); }\n\n  inline result_type operator()( size_t i, size_t j, size_t p=0 ) const {\n    vw_throw( NoImplErr() << \"BlurDEM: operator() not implemented.\\n\" );\n  }\n  \n  \n  typedef CropView< ImageView<PixelT> > prerasterize_type;\n  inline prerasterize_type prerasterize( BBox2i const& bbox ) const {\n\n    // Crop into an expanded box as to have enough pixels to do\n    // the blurring at every pixel in the current box.\n    int h = m_search_dist; // shorten\n    BBox2i biased_box = bbox;\n    biased_box.expand(h+1);\n    biased_box.crop(bounding_box(m_img));\n    ImageView<PixelT> img( crop( m_img, biased_box ) );\n    ImageView<PixelT> filled_img = copy(img);\n\n    int nc = img.cols(), nr = img.rows(); // shorten\n    for (int row = 0; row < nr; row++){\n      for (int col = 0; col < nc; col++){\n        PixelT V; V.validate();\n        double sum = 0.0;\n        for (int c = std::max(col-h, 0); c <= std::min(col+h, nc-1); c++){\n          for (int r = std::max(row-h, 0); r <= std::min(row+h, nr-1); r++){\n            if (!is_valid(img(c, r))) continue;\n            double wt = m_gauss_kernel(c-col+h, r-row+h);\n              V   += wt*img(c, r);\n              sum += wt;\n          }\n        }\n        if (sum > 0) filled_img(col, row) = V/sum;\n        \n      }\n    } \n      \n    return prerasterize_type(filled_img,\n                             -biased_box.min().x(), -biased_box.min().y(),\n                             cols(), rows());\n      \n  }\n  template <class ImgT>\n  inline void rasterize( ImgT const& img, BBox2i const& bbox ) const {\n    vw::rasterize( prerasterize(bbox), img, bbox );\n  }\n  \n};\n\ntemplate <class ImgT>\nBlurDEM<ImgT>\nblur_dem( ImageViewBase<ImgT> const& img, double blur_sigma) {\n  typedef BlurDEM<ImgT> result_type;\n  return result_type( img.impl(), blur_sigma);\n}\n\nint main( int argc, char *argv[] ){\n\n  Options opt;\n\n  if (argc < 4){\n    std::cerr << \"Usage: \" << argv[0] << \" input-DEM.tif blur_sigma output-DEM.tif\"\n              << std::endl;\n    exit(1);\n  }\n  \n  std::string infile = argv[1];\n  double blur_sigma = atof(argv[2]);\n  std::string outfile = argv[3];\n  \n  std::cout << \"Reading: \" << infile << std::endl;\n  std::cout << \"blur sigma is \" << blur_sigma << std::endl;\n  \n  DiskImageResourceGDAL in_rsrc(infile);\n  float nodata_val = -32768;\n  if ( in_rsrc.has_nodata_read() ) {\n    nodata_val = in_rsrc.nodata_read();\n    vw_out() << \"\\tFound input nodata value: \" << nodata_val << std::endl;\n  }else{\n    std::cerr << \"Nodata value not found in: \" << infile << std::endl;\n    exit(1);\n  }\n  \n  DiskImageView<float> dem(in_rsrc);\n\n\n  GeoReference georef;\n  read_georeference(georef, in_rsrc);\n  \n  std::cout << \"Writing: \" << outfile << std::endl;\n  block_write_gdal_image(outfile,\n                         apply_mask\n                         (blur_dem\n                          (create_mask(dem, nodata_val), blur_sigma),\n                          nodata_val),\n                         georef, nodata_val, opt,\n                         TerminalProgressCallback(\"asp\",\"\")\n                         );\n  return 0;\n  \n}\n", "meta": {"hexsha": "464db2bc7bc4d70fccf6beafa022ce9c2d43bff3", "size": 6403, "ext": "cc", "lang": "C++", "max_stars_repo_path": "blur_dem.cc", "max_stars_repo_name": "NeoGeographyToolkit/Tools", "max_stars_repo_head_hexsha": "b1a8f4070c4995e7a1787f8f0d9ae603b0699f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-05-13T22:49:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-08T19:57:11.000Z", "max_issues_repo_path": "blur_dem.cc", "max_issues_repo_name": "NeoGeographyToolkit/Tools", "max_issues_repo_head_hexsha": "b1a8f4070c4995e7a1787f8f0d9ae603b0699f6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "blur_dem.cc", "max_forks_repo_name": "NeoGeographyToolkit/Tools", "max_forks_repo_head_hexsha": "b1a8f4070c4995e7a1787f8f0d9ae603b0699f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-12-17T22:34:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T18:57:32.000Z", "avg_line_length": 31.5418719212, "max_line_length": 83, "alphanum_fraction": 0.6373574887, "num_tokens": 1708, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.2377655300461932}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file orea/aggregation/postprocess.hpp\n    \\brief Exposure aggregation and XVA calculation\n    \\ingroup analytics\n*/\n\n#pragma once\n\n#include <orea/aggregation/collatexposurehelper.hpp>\n#include <orea/cube/inmemorycube.hpp>\n#include <orea/scenario/aggregationscenariodata.hpp>\n\n#include <ored/portfolio/nettingsetmanager.hpp>\n#include <ored/portfolio/portfolio.hpp>\n#include <ored/report/report.hpp>\n\n#include <ql/time/date.hpp>\n\n#include <boost/shared_ptr.hpp>\n\nnamespace ore {\nnamespace analytics {\nusing namespace QuantLib;\nusing namespace data;\n\nenum class AllocationMethod {\n    None,\n    Marginal, // Pykhtin & Rosen, 2010\n    RelativeFairValueGross,\n    RelativeFairValueNet,\n    RelativeXVA\n};\n\nstd::ostream& operator<<(std::ostream& out, AllocationMethod m);\n\nAllocationMethod parseAllocationMethod(const string& s);\n\n//! Exposure Aggregation and XVA Calculation\n/*!\n  This class aggregates NPV cube data, computes exposure statistics\n  and various XVAs, all at trade and netting set level:\n\n  1) Exposures\n  - Expected Positive Exposure, EPE: E[max(NPV(t),0) / N(t)]\n  - Expected Negative Exposure, ENE: E[max(-NPV(t),0) / N(t)]\n  - Basel Expected Exposure, EE_B: EPE(t)/P(t)\n  - Basel Expected Positive Exposure, EPE_B\n  - Basel Effective Expected Exposure, EEE_B: max( EEE_B(t-1), EE_B(t))\n  - Basel Effective Expected Positive Exposure, EEPE_B\n  - Potential Future Exposure, PFE: q-Quantile of the distribution of\n\n  2) Dynamic Initial Margin via regression\n\n  3) XVAs:\n  - Credit Value Adjustment, CVA\n  - Debit Value Adjustment, DVA\n  - Funding Value Adjustment, FVA\n  - Collateral Value Adjustment, COLVA\n  - Margin Value Adjustment, MVA\n\n  4) Allocation from netting set to trade level such that allocated contributions\n  add up to the netting set\n  - CVA and DVA\n  - EPE and ENE\n\n  All analytics are precomputed when the class constructor is called.\n  A number of inspectors described below then return the individual analytics results.\n\n  Note:\n  - exposures are discounted at the numeraire N(t) used in the\n  Monte Carlo simulation which produces the NPV cube.\n  - NPVs take collateral into account, depending on CSA settings\n\n  \\ingroup analytics\n\n  \\todo Introduce enumeration for TradeAction type and owner\n  \\todo Interpolation for DIM(t-MPOR) when the simulation grid spacing is different from MPOR\n  \\todo Revise alternatives to the RelativeXVA exposure and XVA allocation method\n  \\todo Add trade-level MVA\n  \\todo Take the spread received on posted initial margin into account in MVA calculation\n*/\nclass PostProcess {\npublic:\n    //! Constructor\n    PostProcess( //! Trade portfolio to identidy e.g. netting set, maturity, break dates for each trade\n        const boost::shared_ptr<Portfolio>& portfolio,\n        //! Netting set manager to access CSA details for each netting set\n        const boost::shared_ptr<NettingSetManager>& nettingSetManager,\n        //! Market data object to access e.g. discounting and funcing curves\n        const boost::shared_ptr<Market>& market,\n        //! Market configuration to use\n        const std::string& configuration,\n        //! Input NPV Cube\n        const boost::shared_ptr<NPVCube>& cube,\n        //! Subset of simulated market data, index fixings and FX spot rates, associated with the NPV cube\n        const boost::shared_ptr<AggregationScenarioData>& scenarioData,\n        //! Selection of analytics to be produced\n        const map<string, bool>& analytics,\n        //! Expression currency for all results\n        const string& baseCurrency,\n        //! Method to be used for Exposure/XVA allocation down to trade level\n        const string& allocationMethod,\n        //! Cutoff parameter for the marginal allocation method below which we switch to equal disctribution\n        Real cvaMarginalAllocationLimit,\n        //! Quantile for Potential Future Exposure output\n        Real quantile = 0.95,\n        //! Collateral calculation type to be used, see class %CollateralExposureHelper\n        const string& calculationType = \"Symmetric\",\n        //! Credit curve name to be used for \"our\" credit risk in DVA calculations\n        const string& dvaName = \"\",\n        //! Borrowing curve name to be used in FVA calculations\n        const string& fvaBorrowingCurve = \"\",\n        //! Lending curve name to be used in FVA calculations\n        const string& fvaLendingCurve = \"\",\n        //! Quantile used in dynamic initial margin calculation\n        Real dimQuantile = 0.99,\n        //! Initial margin horizon in calendar days, 2 weeks = 14 days\n        Size dimHorizonCalendarDays = 14,\n        //! Order of the regression polynomial used in DIM estmation\n        Size dimRegressionOrder = 0,\n        //! Regressors to be used in the DIM estimation by regression, each must match an additional scenario data key\n        vector<string> dimRegressors = vector<string>(),\n        //! Number of local regression evaluations, e.g. to validata DIM by regression\n        Size dimLocalRegressionEvaluations = 0,\n        //! Local regression band width in standard deviations of the regression variable\n        Real dimLocalRegressionBandwidth = 0,\n        //! Scaling factor applied to all DIM values\n        Real dimScaling = 1.0,\n        //! Assume t=0 collateral balance equals NPV (set to 0 if false)\n        bool fullInitialCollateralisation = false,\n        //! own capital discounting rate for discounting expected capital for KVA\n        Real kvaCapitalDiscountRate = 0.10,\n        //! alpha to adjust EEPE to give EAD for risk capital\n        Real kvaAlpha = 1.4,\n        //! regulatory adjustment, 1/min cap requirement\n        Real kvaRegAdjustment = 12.5,\n        //! Cost of Capital for KVA = regulatory adjustment x capital hurdle\n        Real kvaCapitalHurdle = 0.012,\n        //! Our KVA PD floor\n        Real kvaOurPdFloor = 0.03,\n        //! Their KVA PD floor\n        Real kvaTheirPdFloor = 0.03,\n        //! Our KVA CVA Risk Weight\n        Real kvaOurCvaRiskWeight = 0.05,\n        //! Their KVA CVA Risk Weight,\n        Real kvaTheirCvaRiskWeight = 0.05);\n\n    //! Return list of Trade IDs in the portfolio\n    const vector<string>& tradeIds() { return tradeIds_; }\n    //! Return list of netting set IDs in the portfolio\n    const vector<string>& nettingSetIds() { return nettingSetIds_; }\n\n    //! Return trade level Expected Positive Exposure evolution\n    const vector<Real>& tradeEPE(const string& tradeId);\n    //! Return trade level Expected Negative Exposure evolution\n    const vector<Real>& tradeENE(const string& tradeId);\n    //! Return trade level Basel Expected Exposure evolution\n    const vector<Real>& tradeEE_B(const string& tradeId);\n    //! Return trade level Basel Expected Positive Exposure evolution\n    const Real& tradeEPE_B(const string& tradeId);\n    //! Return trade level Effective Expected Exposure evolution\n    const vector<Real>& tradeEEE_B(const string& tradeId);\n    //! Return trade level Effective Expected Positive Exposure evolution\n    const Real& tradeEEPE_B(const string& tradeId);\n    //! Return trade level Potential Future Exposure evolution\n    const vector<Real>& tradePFE(const string& tradeId);\n    // const vector<Real>& tradeVAR(const string& tradeId);\n\n    //! Return Netting Set Expected Positive Exposure evolution\n    const vector<Real>& netEPE(const string& nettingSetId);\n    //! Return Netting Set Expected Negative Exposure evolution\n    const vector<Real>& netENE(const string& nettingSetId);\n    //! Return Netting Set Basel Expected Exposure evolution\n    const vector<Real>& netEE_B(const string& nettingSetId);\n    //! Return Netting Set Basel Expected Positive Exposure evolution\n    const Real& netEPE_B(const string& nettingSetId);\n    //! Return Netting Set Effective Expected Exposure evolution\n    const vector<Real>& netEEE_B(const string& nettingSetId);\n    //! Return Netting Set Effective Expected Positive Exposure evolution\n    const Real& netEEPE_B(const string& nettingSetId);\n    //! Return Netting Set Potential Future Exposure evolution\n    const vector<Real>& netPFE(const string& nettingSetId);\n    // const vector<Real>& netVAR(const string& nettingSetId);\n\n    //! Return the netting set's expected collateral evolution\n    const vector<Real>& expectedCollateral(const string& nettingSetId);\n    //! Return the netting set's expected COLVA increments through time\n    const vector<Real>& colvaIncrements(const string& nettingSetId);\n    //! Return the netting set's expected Collateral Floor increments through time\n    const vector<Real>& collateralFloorIncrements(const string& nettingSetId);\n\n    //! Return the trade EPE, allocated down from the netting set level\n    const vector<Real>& allocatedTradeEPE(const string& tradeId);\n    //! Return trade ENE, allocated down from the netting set level\n    const vector<Real>& allocatedTradeENE(const string& tradeId);\n\n    //! Return trade (stand-alone) CVA\n    Real tradeCVA(const string& tradeId);\n    //! Return trade (stand-alone) DVA\n    Real tradeDVA(const string& tradeId);\n    //! Return trade (stand-alone) MVA\n    Real tradeMVA(const string& tradeId);\n    //! Return trade (stand-alone) FBA (Funding Benefit Adjustment)\n    Real tradeFBA(const string& tradeId);\n    //! Return trade (stand-alone) FCA (Funding Cost Adjustment)\n    Real tradeFCA(const string& tradeId);\n    //! Return trade (stand-alone) FBA (Funding Benefit Adjustment) excluding own survival probability\n    Real tradeFBA_exOwnSP(const string& tradeId);\n    //! Return trade (stand-alone) FCA (Funding Cost Adjustment) excluding own survival probability\n    Real tradeFCA_exOwnSP(const string& tradeId);\n    //! Return trade (stand-alone) FBA (Funding Benefit Adjustment) excluding both survival probabilities\n    Real tradeFBA_exAllSP(const string& tradeId);\n    //! Return trade (stand-alone) FCA (Funding Cost Adjustment) excluding both survival probabilities\n    Real tradeFCA_exAllSP(const string& tradeId);\n    //! Return allocated trade CVA (trade CVAs add up to netting set CVA)\n    Real allocatedTradeCVA(const string& tradeId);\n    //! Return allocated trade DVA (trade DVAs add up to netting set DVA)\n    Real allocatedTradeDVA(const string& tradeId);\n    //! Return netting set CVA\n    Real nettingSetCVA(const string& nettingSetId);\n    //! Return netting set DVA\n    Real nettingSetDVA(const string& nettingSetId);\n    //! Return netting set MVA\n    Real nettingSetMVA(const string& nettingSetId);\n    //! Return netting set FBA\n    Real nettingSetFBA(const string& nettingSetId);\n    //! Return netting set FCA\n    Real nettingSetFCA(const string& nettingSetId);\n    //! Return netting set KVA-CCR\n    Real nettingSetOurKVACCR(const string& nettingSetId);\n    //! Return netting set KVA-CCR from counterparty persepctive\n    Real nettingSetTheirKVACCR(const string& nettingSetId);\n    //! Return netting set KVA-CVA\n    Real nettingSetOurKVACVA(const string& nettingSetId);\n    //! Return netting set KVA-CVA from counterparty persepctive\n    Real nettingSetTheirKVACVA(const string& nettingSetId);\n    //! Return netting set FBA excluding own survival probability\n    Real nettingSetFBA_exOwnSP(const string& nettingSetId);\n    //! Return netting set FCA excluding own survival probability\n    Real nettingSetFCA_exOwnSP(const string& nettingSetId);\n    //! Return netting set FBA excluding both survival probabilities\n    Real nettingSetFBA_exAllSP(const string& nettingSetId);\n    //! Return netting set FCA excluding both survival probabilities\n    Real nettingSetFCA_exAllSP(const string& nettingSetId);\n    //! Return netting set COLVA\n    Real nettingSetCOLVA(const string& nettingSetId);\n    //! Return netting set Collateral Floor value\n    Real nettingSetCollateralFloor(const string& nettingSetId);\n\n    //! Inspector for the input NPV cube (by trade, time, scenario)\n    const boost::shared_ptr<NPVCube>& cube() { return cube_; }\n    //! Return the  for the input NPV cube after netting and collateral (by netting set, time, scenario)\n    const boost::shared_ptr<NPVCube>& netCube() { return nettedCube_; }\n    //! Return the dynamic initial margin cube (regression approach)\n    const boost::shared_ptr<NPVCube>& dimCube() { return dimCube_; }\n    //! Write average (over samples) DIM evolution through time for all netting sets\n    void exportDimEvolution(ore::data::Report& dimEvolutionReport);\n    //! Write DIM as a function of sample netting set NPV for a given time step\n    void exportDimRegression(const std::string& nettingSet, const std::vector<Size>& timeSteps,\n                             const std::vector<boost::shared_ptr<ore::data::Report>>& dimRegReports);\n\nprivate:\n    //! Helper function to return the collateral account evolution for a given netting set\n    boost::shared_ptr<vector<boost::shared_ptr<CollateralAccount>>>\n    collateralPaths(const string& nettingSetId, const boost::shared_ptr<NettingSetManager>& nettingSetManager,\n                    const boost::shared_ptr<Market>& market, const std::string& configuration,\n                    const boost::shared_ptr<AggregationScenarioData>& scenarioData, Size dates, Size samples,\n                    const vector<vector<Real>>& nettingSetValue, Real nettingSetValueToday,\n                    const Date& nettingSetMaturity);\n\n    void updateNettingSetKVA();\n    void updateStandAloneXVA();\n    void updateAllocatedXVA();\n\n    //! Fill dynamic initial margin cube (per netting set, date and sample)\n    void dynamicInitialMargin();\n    //! Compile the array of DIM regressors for the specified netting set, date and sample index\n    Disposable<Array> regressorArray(string nettingSet, Size dateIndex, Size sampleIndex);\n    //! Perform the calculation of IM as of t=t0\n    void performT0DimCalc();\n\n    boost::shared_ptr<Portfolio> portfolio_;\n    boost::shared_ptr<NettingSetManager> nettingSetManager_;\n    boost::shared_ptr<Market> market_;\n    const std::string configuration_;\n    boost::shared_ptr<NPVCube> cube_;\n    boost::shared_ptr<AggregationScenarioData> scenarioData_;\n    map<string, bool> analytics_;\n\n    map<string, vector<vector<Real>>> nettingSetNPV_, nettingSetFLOW_, nettingSetDIM_, nettingSetLocalDIM_,\n        nettingSetDeltaNPV_;\n    map<string, vector<vector<Array>>> regressorArray_;\n    map<string, vector<Real>> nettingSetExpectedDIM_, nettingSetZeroOrderDIM_, nettingSetSimpleDIMh_,\n        nettingSetSimpleDIMp_;\n    map<string, vector<Real>> tradeEPE_, tradeENE_, tradeEE_B_, tradeEEE_B_, tradePFE_, tradeVAR_;\n    map<string, Real> tradeEPE_B_, tradeEEPE_B_;\n    map<string, vector<Real>> allocatedTradeEPE_, allocatedTradeENE_;\n    map<string, vector<Real>> netEPE_, netENE_, netEE_B_, netEEE_B_, netPFE_, netVAR_, expectedCollateral_;\n    map<string, Real> netEPE_B_, netEEPE_B_;\n    map<string, vector<Real>> colvaInc_, eoniaFloorInc_;\n    map<string, Real> tradeCVA_, tradeDVA_, tradeMVA_, tradeFBA_, tradeFCA_, tradeFBA_exOwnSP_, tradeFCA_exOwnSP_,\n        tradeFBA_exAllSP_, tradeFCA_exAllSP_;\n    map<string, Real> sumTradeCVA_, sumTradeDVA_; // per netting set\n    map<string, Real> allocatedTradeCVA_, allocatedTradeDVA_;\n    map<string, Real> nettingSetCVA_, nettingSetDVA_, nettingSetMVA_;\n    map<string, Real> nettingSetCOLVA_, nettingSetCollateralFloor_;\n    map<string, Real> ourNettingSetKVACCR_, theirNettingSetKVACCR_, ourNettingSetKVACVA_, theirNettingSetKVACVA_;\n    map<string, Real> nettingSetFCA_, nettingSetFBA_, nettingSetFCA_exOwnSP_, nettingSetFBA_exOwnSP_,\n        nettingSetFCA_exAllSP_, nettingSetFBA_exAllSP_;\n    boost::shared_ptr<NPVCube> nettedCube_;\n    boost::shared_ptr<NPVCube> dimCube_;\n    map<string, Real> net_t0_im_reg_h_, net_t0_im_simple_h_;\n\n    vector<string> tradeIds_;\n    vector<string> nettingSetIds_;\n    map<string, string> counterpartyId_; // for each nettingSetId\n    string baseCurrency_;\n    Real quantile_;\n    CollateralExposureHelper::CalculationType calcType_;\n    string dvaName_;\n    string fvaBorrowingCurve_;\n    string fvaLendingCurve_;\n    Real dimQuantile_;\n    Size dimHorizonCalendarDays_;\n    Size dimRegressionOrder_;\n    vector<string> dimRegressors_;\n    Size dimLocalRegressionEvaluations_;\n    Real dimLocalRegressionBandwidth_;\n    Real dimScaling_;\n    bool fullInitialCollateralisation_;\n    Real kvaCapitalDiscountRate_;\n    Real kvaAlpha_;\n    Real kvaRegAdjustment_;\n    Real kvaCapitalHurdle_;\n    Real kvaOurPdFloor_;\n    Real kvaTheirPdFloor_;\n    Real kvaOurCvaRiskWeight_;\n    Real kvaTheirCvaRiskWeight_;\n};\n} // namespace analytics\n} // namespace ore\n", "meta": {"hexsha": "a2c753589f6ba0152a12e054f8e10a25b9613e0d", "size": 17232, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/orea/aggregation/postprocess.hpp", "max_stars_repo_name": "nvolfango/Engine", "max_stars_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T17:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T17:24:17.000Z", "max_issues_repo_path": "OREAnalytics/orea/aggregation/postprocess.hpp", "max_issues_repo_name": "zhangjiayin/Engine", "max_issues_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OREAnalytics/orea/aggregation/postprocess.hpp", "max_forks_repo_name": "zhangjiayin/Engine", "max_forks_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "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": 48.0, "max_line_length": 118, "alphanum_fraction": 0.731545961, "num_tokens": 4169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2377655264715517}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2015 Free Software Foundation, Inc.\n *\n * This is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published\n * by the Free Software Foundation; either version 3, or (at your\n * option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this software; see the file COPYING.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street,\n * Boston, MA 02110-1301, USA.\n */\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <ldpc_bit_flip_decoder_impl.h>\n#include <math.h>\n#include <boost/assign/list_of.hpp>\n#include <volk/volk.h>\n#include <sstream>\n#include <stdio.h>\n#include <vector>\n\nnamespace gr {\n  namespace fec {\n    namespace code {\n\n      generic_decoder::sptr\n      ldpc_bit_flip_decoder::make(const fec_mtrx_sptr mtrx_obj,\n                                  unsigned int max_iter)\n      {\n        return generic_decoder::sptr\n          (new ldpc_bit_flip_decoder_impl(mtrx_obj, max_iter));\n      }\n\n      ldpc_bit_flip_decoder_impl::ldpc_bit_flip_decoder_impl(const fec_mtrx_sptr mtrx_obj,\n                                                             unsigned int max_iter)\n        : generic_decoder(\"ldpc_bit_flip_decoder\")\n      {\n        // FEC matrix object to use for decoding\n        d_mtrx = mtrx_obj;\n\n        d_rate = static_cast<double>(d_mtrx->k())/static_cast<double>(d_mtrx->n());\n\n        // Set frame size to k, the # of bits in the information word\n        // All buffers and settings will be based on this value.\n        set_frame_size(d_mtrx->k());\n        // Maximum number of iterations in the decoding algorithm\n        d_max_iterations = max_iter;\n      }\n\n      ldpc_bit_flip_decoder_impl::~ldpc_bit_flip_decoder_impl()\n      {\n      }\n\n      int\n      ldpc_bit_flip_decoder_impl::get_output_size()\n      {\n        return d_output_size;\n      }\n\n      int\n      ldpc_bit_flip_decoder_impl::get_input_size()\n      {\n        return d_input_size;\n      }\n\n      bool\n      ldpc_bit_flip_decoder_impl::set_frame_size(unsigned int frame_size)\n      {\n        if(frame_size % d_mtrx->k() != 0) {\n          GR_LOG_ERROR(d_logger, boost::format(\"Frame size (%1% bits) must be a \"\n                                               \"multiple of the information word \"\n                                               \"size of the LDPC matrix, %2%\") \\\n                       % frame_size % (d_mtrx->k()));\n          throw std::runtime_error(\"ldpc_bit_flip_decoder: cannot use frame size.\");\n        }\n\n        d_output_size = frame_size;\n        d_input_size = static_cast<int>(round(frame_size / d_rate));\n\n        return true;\n      }\n\n      double\n      ldpc_bit_flip_decoder_impl::rate()\n      {\n        return d_rate;\n      }\n\n\n      void\n      ldpc_bit_flip_decoder_impl::generic_work(void *inbuffer,\n                                               void *outbuffer)\n      {\n        // Populate the information word\n        const float *in = (const float*)inbuffer;\n        unsigned char *out = (unsigned char*) outbuffer;\n\n        int j = 0;\n        for(int i = 0; i < d_input_size; i+=d_mtrx->n()) {\n          d_mtrx->decode(&out[j], &in[i], d_mtrx->k(), d_max_iterations);\n          j += d_mtrx->k();\n        }\n\n      } /* ldpc_bit_flip_decoder_impl::generic_work() */\n\n    } /* namespace code */\n  } /* namespace fec */\n} /* namespace gr */\n", "meta": {"hexsha": "ed8eb07db41a75ea2ef98ba46fb8a59fa40e63f2", "size": 3690, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-fec/lib/ldpc_bit_flip_decoder_impl.cc", "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-fec/lib/ldpc_bit_flip_decoder_impl.cc", "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gnuradio-3.7.13.4/gr-fec/lib/ldpc_bit_flip_decoder_impl.cc", "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.75, "max_line_length": 90, "alphanum_fraction": 0.6037940379, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.3775406547908327, "lm_q1q2_score": 0.23776552289690983}}
{"text": "//\n//  bpp.cpp\n//  PhyloAcc\n//\n//  Created by hzr on 3/8/16.\n//  Copyright © 2016 hzr. All rights reserved.\n//\n\n#include \"bpp.hpp\"\n#include <armadillo>\n#include <sys/types.h>\n#include <dirent.h>\n#include<queue>\n\n#include <cmath>\n#include <cassert>\n\n#include <gsl/gsl_rng.h>\n#include <gsl/gsl_randist.h>\n#include <gsl/gsl_linalg.h>\n#include <gsl/gsl_cdf.h>\n\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <ctype.h>\n\n\n#include \"newick.h\"\n#include \"utils.h\"\n#include \"bpp_c.hpp\"\n\n\nusing namespace std;\nusing namespace arma;\n\n// load the phylogenetic tree\nvoid BPP::InitPhyloTree(PhyloTree & tree) //, double indel_pi), double indel, double indel2\n{\n   \n//    cx_mat bvec;\n//    cx_vec aval;\n//   \n//    if(num_base <= 4)  // no indel\n//    {\n//       \n//    }else{\n//        tree.subs_rate *= (1-indel);\n//        mat B = ones<mat>(4,1) * indel;\n//        mat C = ones<mat>(1,5) * indel2;\n//        //tree.subs_rate.diag() -= indel;\n//        tree.subs_rate.insert_cols(4, B);\n//        tree.subs_rate.insert_rows(4, C);\n//        //tree.subs_rate(4,4) = -0.04;\n//        colvec c = sum(tree.subs_rate,1);\n//        tree.subs_rate.diag() -=c;\n//        \n////        tree.pi.insert_rows(4,1);\n////        tree.pi.head(4) *= 1 - indel_pi;\n////        tree.pi[4] = indel_pi;\n//        \n//    }\n//    \n//    eig_gen(aval, bvec, tree.subs_rate);\n//    eigenval = conv_to<mat>::from(aval);\n//    eigenvec = conv_to<mat>::from(bvec).t();\n//    eigeninv = inv(eigenvec);\n//    submat = tree.subs_rate;\n//    \n//    //cout <<eigenval;\n//    //cout <<\"eigenvec: \" << eigenvec;\n//    //cout <<tree.subs_rate;\n//    \n//    mat a = null(tree.subs_rate.t());\n//    \n//    \n//    pi = a/accu(a); //tree.pi;\n//    //cout <<\"pi: \" <<  pi.t();\n//    \n//    log_pi = log(pi);\n    \n    submat = tree.subs_rate;\n    children    = new int[N][2];\n    parent      = new int[N];\n    distances   = new double[N];\n  \n    \n    for(int s=0; s<N; s++)\n    {\n        distances[s] = tree.distances[s];\n        \n    }\n    \n    \n    \n    for(int i=0; i<N; i++)\n    {\n        children[i][0] = -1;\n        children[i][1] = -1;\n        parent[i] = -1;\n    }\n    \n    for(int i=0; i<N; i++)\n    {\n        int p = -1;\n        for(int j=0; j<N; j++)\n        {\n            if (tree.dag[i][j])\n            {\n                p++;\n                children[i][p] = j;\n                parent[j] = i;\n            }\n        }\n    }\n    \n    \n//    distances[children[N-1][1]] += distances[children[N-1][0]];\n//    distances[children[N-1][0]] = 0;\n//    moveroot = children[N-1][0];\n    \n    \n    //distances[83] += distances[42];  // modify distance for root!\n    //distances[42] =0 ;\n    \n    \n}\n\n\n// try to match the phylogenetic profile and tree\nvoid BPP::MatchProfAndTree(PhyloProf & _prof, PhyloTree & _tree)\n{\n    \n    // try to match the species\n    bool success_match = true;\n    int S = _tree.S;\n    int S2 = _prof.S;\n    vector<int> reorder(S);  //each species in the tree where is in prof\n    for(int s1=0; s1<S; s1++)\n    {\n        bool has_same_species = false;\n        string sname1 = _tree.species_names[s1];\n        for(int s2=0; s2<S2; s2++)\n        {\n            string sname2 = _prof.species_names[s2];\n            //            cout << sname1 << \" ? \" << sname2 << endl;\n            if (sname1 == sname2)\n            {\n                has_same_species = true;\n                reorder[s1] = s2;\n                break;\n            }\n        }\n        if (!has_same_species)\n        {\n            cout << \"No matrix species \" << _prof.species_names[s1] << \" found in tree.\" << endl;\n            success_match = false;\n            break;\n        }\n    }\n    \n    if (!success_match) // if cannot match literally\n    {\n        cout << endl << \"The species in phylogenetic profile and tree cannot be matched literally:\" << endl;\n        cout << \"The program will use the default mapping in data:\" << endl;\n        for(int s=0; s<S; s++)\n            cout << \"(\" << _prof.species_names[s] << \"\\t=  \" << _tree.species_names[s] << \")\" << endl;\n        cout << endl;\n    }\n    else                // if successully matched\n    {\n        cout << \"The species in profile and tree match perfectly. Reorder the species in profile matrix by the tree.\" << endl << endl;\n        vector<string> old_X = _prof.X;\n        for(int s=0; s<S; s++)\n        {\n            int reorder_s = reorder[s];\n            _prof.X[s] = old_X[reorder_s];\n        }\n        _prof.species_names = _tree.species_names;\n    }\n    \n}\n\nvoid BPP::InitMCMC(int _num_burn, int _num_mcmc, int _num_thin)\n{\n    // init parameters\n    num_burn = _num_burn;\n    \n    num_mcmc = _num_mcmc;\n    num_thin = _num_thin;\n    \n    \n    last_time = time(NULL);\n    \n    \n    \n    // init MCMC sampling storage\n    Max_Z = vector<vector < vector <int > >> (3,vector < vector <int >>  (C,vector <int > (N,0)));\n    Max_B = vector<vector < vector <bool > >> (3,vector < vector <bool >>  (C,vector <bool > (N,0)));\n    cur_Z = vector<vector < vector <int > >> (3,vector < vector <int >>  (C,vector <int > (N,0)));\n    //cur_B = vector < vector <double > > (3, vector <double >  (C, 2.0));\n    \n    log_liks_null = vector <double>(C,0);\n    log_liks_Z = vector<vector <double>>(3,vector <double>(C,0));\n    log_liks_sgl = vector <double>(C,0);\n    log_liks_resZ = vector <double>(C,0);\n    \n    log_liks_curZ = vector <double>(C,0);\n    log_liks_propZ = vector <double>(C,0);\n    MH_ratio_gain = vector <double>(C,0);\n    MH_ratio_loss = vector <double>(C,0);\n    \n    \n    \n    cur_crate = vector <double>(C,ratio0);\n    cur_nrate = vector <double>(C,ratio1);\n    cur_nGB = vector <double>(C,3);\n    //cur_cGB = vector <double>(C,0.01);\n    \n}\n\nvoid BPP::sample_proposal(int iter, double & lrate_prop, double & grate_prop, ofstream & output)\n{\n    //indel_prop =gsl_ran_gamma(RNG,20 ,indel/20);\n    //indel2_prop =gsl_ran_gamma(RNG,10 ,indel2/10);\n    lrate_prop =gsl_ran_beta(RNG, ind_lrate * vlr, (1 - ind_lrate) *vlr);\n    grate_prop =gsl_ran_beta(RNG, ind_grate * vgr, (1 - ind_grate) *vgr); //gsl_ran_gamma(RNG, vgr, ind_grate/vgr);\n   \n//    submat.submat(0,0,3,3) *= (1 - indel_prop)/(1 - indel);\n//    submat.col(4) = ones<mat>(5,1) * indel_prop;\n//    submat.row(4) = ones<mat>(1,5) * indel2_prop;\n//    colvec c = sum(submat,1);\n//    submat.diag() -=c;\n//    \n//    cx_mat bvec;\n//    cx_vec aval;\n//    eig_gen(aval, bvec, submat);\n//    eigenvalprop = conv_to<mat>::from(aval);\n//    eigenvecprop = conv_to<mat>::from(bvec).t();\n//    eigeninvprop = inv(eigenvecprop);\n//    \n//    mat a = null(submat.t());\n//    piprop = a/accu(a);\n//    //log_piprop = log(a/accu(a));\n//    \n//    //cout <<\"proposed subs matrix: \" << submat << endl;\n//    //cout <<\"piprop: \" <<  piprop.t();\n    \n    output << iter << \"\\t\"<< nprior_a<< \"\\t\"<< nprior_b <<\"\\t\"<< cprior_a << \"\\t\"<< cprior_b << \"\\t\"<< indel << \"\\t\"<< indel2 << \"\\t\"<<ind_grate<< \"\\t\"<< ind_lrate <<endl;\n}\n\n\n\n\n\n\ndouble BPP::log_lik(vector< vector<vec> > & lambda, double _indel, double _indel2, int start1, int end1, vector<unsigned int> & v, double p)\n{\n    // compute loglik\n    double result =0;\n    mat x(2,2);\n    \n    int rr = *subtree.rbegin();\n    // 1. sending the lambda msg from leaves bottom up through the network\n    for(vector<int>::iterator it = subtree.begin(); it!=subtree.end(); it++) //int s=S; s<N; s++)\n    {\n        int s = *it;\n        if(s<S) continue;\n        int* p = children[s];\n        for(int it = start1; it < end1; it++)  lambda[v[it]][s].fill(0);\n       \n        \n        for(int cc=0;cc<2;cc++)\n        {\n            int chi = p[cc];\n            assert(chi != -1);\n            if(distances[chi]>0 )\n            {\n                double tt = (1 - exp(-(_indel + _indel2) * distances[chi]))/(_indel + _indel2);\n                x.at(1,0) = _indel * tt;\n                x.at(0,0) = 1 - x.at(1,0);\n                \n                x.at(0,1) = _indel2 * tt;\n                x.at(1,1) = 1 - x.at(0,1);\n                \n                //cout << x;\n                x = log(x);\n                \n\n            }\n            else{\n                x.fill(-INFINITY); //83, root\n                x.diag().fill(0);\n            }\n            \n            #pragma omp parallel for schedule (guided)\n            for(int it = start1; it < end1; it++)  lambda[v[it]][s] +=  BPP::log_multi(x,lambda[v[it]][chi]);\n        }\n        \n    }\n    \n    // 2. processing the distribution of root species\n    \n    for(int it = start1; it < end1; it++)\n    {\n        \n//        if(lambda[v[it]][N-1][1] < -1e3)\n//        {\n//            cout <<v[it]<<\": \"<< lambda[v[it]][N-1].t();\n//            cout <<children[N-1][0]<<\": \" << lambda[v[it]][children[N-1][0]].t();\n//            cout <<children[N-1][1]<<\": \" << lambda[v[it]][children[N-1][1]].t();\n//            \n//        }\n        lambda[v[it]][rr][0] += log(1-p); //N-1\n        lambda[v[it]][rr][1] += log(p) ;\n        result += BPP::log_exp_sum(lambda[v[it]][rr]);\n    }\n    \n    return(result);\n}\n\nvoid BPP::sample_hyperparam(double lrate_prop, double grate_prop) // recompute log_TM, double indel_prop, double indel2_prop, \n{\n    \n    //indepent MH to sample hyperparam of rates\n    double p=1,r = 1; //hyperparam for shape\n    double q=0.1,s = 0.1; // hyperparam for scale\n    \n    double vna = 100, vnb = 100, vca = 100, vcb = 100;\n    double nprior_a_prop =gsl_ran_gamma(RNG, vna, nprior_a/vna);\n    double cprior_a_prop =gsl_ran_gamma(RNG, vca, cprior_a/vca);\n    \n    double nprior_b_prop =gsl_ran_gamma(RNG, vnb, nprior_b/vnb);\n    double cprior_b_prop =gsl_ran_gamma(RNG, vcb, cprior_b/vcb);\n    \n    //MH proposal\n    double sum_r = 0;\n    double log_prod_r = 0;\n    //double var_r = 0;\n    for(vector<double>::iterator it = cur_nrate.begin(); it< cur_nrate.end(); it++)\n    {\n        sum_r += *it;\n        //var_r += pow(*it, 2);\n        log_prod_r += log(*it);\n    }\n\n        \n    double M_ratio = (nprior_a_prop - 1) * (log(p) + log_prod_r) - (q + sum_r)/nprior_b_prop - (C + r)*lgamma(nprior_a_prop) - log(nprior_b_prop) * nprior_a_prop * (s + C);\n    M_ratio -= (nprior_a - 1) * (log(p) + log_prod_r) - (q + sum_r)/nprior_b - (C + r)*lgamma(nprior_a) - log(nprior_b) * nprior_a * (s + C);\n    \n    double H_ratio = log(gsl_ran_gamma_pdf(nprior_a,vna,nprior_a_prop/vna)) - log(gsl_ran_gamma_pdf(nprior_a_prop,vna,nprior_a/vna)) + log(gsl_ran_gamma_pdf(nprior_b,vnb,nprior_b_prop/vnb)) - log(gsl_ran_gamma_pdf(nprior_b_prop,vnb,nprior_b/vnb));\n    \n    cout << \"nrate_MH_ratio: \" << M_ratio <<\", \" << H_ratio << \", \" << nprior_a << \", \" << nprior_a_prop << \", \" << nprior_b << \", \" << nprior_b_prop << endl;\n    \n    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)\n    {\n        nprior_a = nprior_a_prop;\n        nprior_b = nprior_b_prop;\n    }\n    \n    \n    sum_r = 0;\n    log_prod_r = 0;\n    for(vector<double>::iterator it = cur_crate.begin(); it< cur_crate.end(); it++)\n    {\n        sum_r += *it;\n        //var_r += pow(*it, 2);\n        log_prod_r += log(*it);\n    }\n    \n    M_ratio = (cprior_a_prop - 1) * (log(p) + log_prod_r) - (q + sum_r)/cprior_b_prop - (C + r)*lgamma(cprior_a_prop) - log(cprior_b_prop) * cprior_a_prop * (s + C) - ((cprior_a - 1) * (log(p) + log_prod_r) - (q + sum_r)/cprior_b - (C + r)*lgamma(cprior_a) - log(cprior_b) * cprior_a * (s + C));\n        \n    H_ratio = log(gsl_ran_gamma_pdf(cprior_a,vca,cprior_a_prop/vca)) - log(gsl_ran_gamma_pdf(cprior_a_prop,vca,cprior_a/vca)) + log(gsl_ran_gamma_pdf(cprior_b,vcb,cprior_b_prop/vcb)) - log(gsl_ran_gamma_pdf(cprior_b_prop,vcb,cprior_b/vcb));\n    \n    cout << \"crate_MH_ratio: \" << M_ratio + H_ratio << \", \" << cprior_a << \", \" << cprior_a_prop <<\", \" << cprior_b << \", \" << cprior_b_prop << endl;\n    \n    if(log(gsl_rng_uniform(RNG)) < M_ratio + H_ratio)\n    {\n        cprior_a = cprior_a_prop;\n        cprior_b = cprior_b_prop;\n    }\n    \n\n\n\n    //MH to sample lrate, grate\n    //lrate\n    double MH_ratio =0;\n    for(int c =0 ; c<C; c++)\n    {\n        MH_ratio += MH_ratio_gain[c];\n    }\n    \n    MH_ratio += log(gsl_ran_beta_pdf(ind_grate, grate_prop*vgr, (1-grate_prop)*vgr)) - log(gsl_ran_beta_pdf(grate_prop, ind_grate*vgr, (1-ind_grate)*vgr));\n    \n    cout << \"grate: \" << MH_ratio << \", \" << ind_grate << \", \" << grate_prop << endl;\n    \n    if(log(gsl_rng_uniform(RNG)) < MH_ratio)\n    {\n        ind_grate = grate_prop;\n        for(int s=0; s<N; s++)\n        {\n            \n            //double x = exp(-ind_grate *distances[s]);\n            double x = 1 - ind_grate;\n            TM_Int[s](0,0) = x;\n            TM_Int[s](1,0) = 1-x;\n            \n        }\n    }\n    \n    \n    \n    MH_ratio = 0;\n    for(int c =0 ; c<C; c++)\n    {\n        MH_ratio += MH_ratio_loss[c];\n    }\n    MH_ratio += log(gsl_ran_beta_pdf(ind_lrate, lrate_prop*vlr, (1-lrate_prop)*vlr)) - log(gsl_ran_beta_pdf(lrate_prop, ind_lrate*vlr, (1-ind_lrate)*vlr));\n    \n\n    cout << \"lrate: \" << MH_ratio << \", \" << ind_lrate << \", \" << lrate_prop << endl << endl;\n\n    if(log(gsl_rng_uniform(RNG)) < MH_ratio)\n    {\n        ind_lrate = lrate_prop;\n        for(vector<int>::iterator it = subtree.begin(); it<subtree.end(); it++)\n        {\n            int s = *it;\n            //double y = exp(-ind_lrate *distances[s]);\n            double y = 1 - ind_lrate;\n            TM_Int[s](1,1) = y;\n            TM_Int[s](2,1) = 1-y;\n            \n        }\n    }\n    \n    for(int s=0; s<N; s++){\n        log_TM_Int[s] = log(TM_Int[s]);\n    }\n\n    \n   \n}\n\n\n\n\n\n\n\nvoid BPP::getUppertree(int root, vector<int>& child, set<int> & visited_init)  // include root!\n{\n    for(vector<int>::iterator it = child.begin(); it!=child.end(); it++)\n    {\n        int p = *it;\n       while(p!=root)\n       {\n           visited_init.insert(p);\n           p = parent[p];\n       }\n        \n        \n    }\n    \n    visited_init.insert(root);\n    \n    \n    \n}\n\n\n\n\n\nvoid BPP::getSubtree(int root, vector<int> & visited_init)  // traverse from root to children, include root\n{\n    \n    \n    int j = root;\n    \n    //cout << nodes_names[j]<<\"\\t\";\n    \n    if(children[j][0]!=-1)\n    {\n        \n        for(int chi=0;chi<2;chi++)\n        {\n            getSubtree(children[j][chi], visited_init);\n            \n            \n        }\n        \n    }\n   \n    visited_init.push_back(j);\n    \n}\n\nvoid BPP::getSubtree(int root, set<int>& child, vector<int> & visited_init)  // traverse from root, stop at children, 74 & 64; do include 1-S!\n{\n    \n    \n    int j = root;\n    \n    //cout << nodes_names[j]<<\"\\t\";\n    if(child.find(j) != child.end())\n    {\n        \n        visited_init.push_back(j);\n        \n        return;\n    }\n    \n    if(children[j][0]!=-1)\n    {\n        \n        for(int chi=0;chi<2;chi++)\n        {\n            getSubtree(children[j][chi], child, visited_init);\n            \n            \n        }\n        \n      //  visited_init.push_back(j);\n        \n    }\n    \n     visited_init.push_back(j);\n       \n    \n}\n\nvoid BPP::Output_init(PhyloProf & prof, string output_path){\n    \n        string outpath_elem = output_path+ \"_elem_lik.txt\";\n        ofstream out_lik(outpath_elem.c_str());\n        out_lik.precision(8);\n        out_lik << \"No.\\tID\\tloglik_NUll\\tloglik_RES\\tloglik_all\\tlog_ratio\\tloglik_Max1\\tloglik_Max2\\tloglik_Max3\"<<endl;\n        for(int cc=0; cc<C;cc++)\n        {\n            out_lik <<cc << \"\\t\" << prof.element_names[cc] << \"\\t\" << log_liks_null[cc] <<\"\\t\"  <<log_liks_resZ[cc] <<\"\\t\"  <<log_liks_sgl[cc]<< \"\\t\"<< log_liks_resZ[cc] -  log_liks_null[cc];\n            for(int r=0;r<3;r++) out_lik <<\"\\t\" <<log_liks_Z[r][cc];\n            out_lik << endl;\n        }\n        \n        out_lik.close();\n        \n    ofstream out_z;\n    for(int r =1;r<2;r++)\n    {\n            outpath_elem = output_path+\"_\" +to_string(r) + \"_elem_Z.txt\";\n            out_z.open(outpath_elem.c_str());\n        \n                for(int s =0 ;s<N;s++){  // header: species name\n                    out_z<<nodes_names[s] << \"_B\\t\";\n                }\n        for(int s =0 ;s<N;s++){  // header: species name\n            out_z<<nodes_names[s] << \"\\t\";\n        }\n                out_z <<endl;\n            for(int c=0;c<C;c++)\n            {\n                    for(int s=0; s<N;s++)\n                            out_z<<Max_Z[r][c][s]<<\"\\t\";\n                    out_z <<endl;\n            }\n        out_z.close();\n    }\n    \n    \n}\n\n\nvoid BPP::Output_init0(PhyloProf & prof, ofstream& out_lik){\n    \n    for(int cc=0; cc<C;cc++)\n    {\n        out_lik <<cc << \"\\t\" << prof.element_names[cc] << \"\\t\"  <<log_liks_sgl[cc]<< \"\\t\"<<log_liks_Z[1][cc];\n        out_lik << endl;\n    }\n    \n    //out_lik.close();\n    \n    \n}\n\n\n\n\n", "meta": {"hexsha": "23bdb81726000a6df143c3d477e9ccdf3b9df7f0", "size": 16547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "V2_GBGC/SRC/bpp.cpp", "max_stars_repo_name": "beyondpie/PhyloAcc", "max_stars_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-11T14:34:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T06:58:59.000Z", "max_issues_repo_path": "V2_GBGC/SRC/bpp.cpp", "max_issues_repo_name": "beyondpie/PhyloAcc", "max_issues_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T03:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T09:54:35.000Z", "max_forks_repo_path": "V2_GBGC/SRC/bpp.cpp", "max_forks_repo_name": "beyondpie/PhyloAcc", "max_forks_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-03T18:49:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T04:39:30.000Z", "avg_line_length": 27.9038785835, "max_line_length": 295, "alphanum_fraction": 0.5145343567, "num_tokens": 5084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.23770661047368685}}
{"text": "/*\n * The Conv integrators will implicitly determine the structure of the previous\n * layer, as they have to be structured in a specific way. The Net and reservoir\n * however, specify the connections either within or between layers.\n * Within a layer, a neighbor graph is used, where sources of the connections\n * correspond with nodes in the same graph.\n * Between layers, the sources of the connections correspond to the nodes\n * of the previous layer, while the destination corresponds with nodes in the\n * current layer.\n *\n * Integrators don't actually have to know the real size/shape of the previous\n * layer. Any size/shape can be given so long as the # elements is less than\n * then number in the previous layer so that non-existent elements are not\n * accessed. The integrator will create its own view into the previous layer\n * with the shape provided it, regardless of whether that layer has that shape.\n */\n\n#ifndef NN_INTEGRATOR_H_\n#define NN_INTEGRATOR_H_\n\n#include <cstddef>\n#include <vector>\n#include <stdexcept>\n#include <iostream>\n#include <numeric>\n#include <functional>\n#include <utility>\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include \"../common/multi_array.hpp\"\n#include \"../common/graphs.hpp\"\n#include \"parameter_types.hpp\"\n#include \"../common/utilities.hpp\"\n\nnamespace nervous_system {\n\nenum INTEGRATOR_TYPE {\n  BASE_INTEGRATOR,\n  NONE_INTEGRATOR,\n  ALL2ALL_INTEGRATOR,\n  CONV_INTEGRATOR,\n  RECURRENT_INTEGRATOR,\n  RESERVOIR_INTEGRATOR,\n  RESERVOIR_HYBRID,\n  TRUNCATED_RECURRENT_INTEGRATOR,\n  CONV_EIGEN_INTEGRATOR,\n  ALL2ALL_EIGEN_INTEGRATOR,\n  RECURRENT_EIGEN_INTEGRATOR,\n  RESERVOIR_EIGEN_INTEGRATOR,\n  REWARD_MODULATED_INTEGRATOR,\n  REWARD_MODULATED_ALL2ALL_INTEGRATOR,\n  REWARD_MODULATED_RECURRENT_INTEGRATOR,\n  REWARD_MODULATED_CONV_INTEGRATOR,\n  REWARD_MODULATED\n};\n\n// Abstract base class\ntemplate<typename TReal>\nclass Integrator {\n  public:\n    typedef std::size_t Index;\n\n    Integrator() {\n      integrator_type_ = BASE_INTEGRATOR;\n      parameter_count_ = 0;\n    }\n    virtual ~Integrator()=default;\n    virtual void operator()(const multi_array::Tensor<TReal>& src_state,\n                            multi_array::Tensor<TReal>& tar_state)=0;\n    virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters)=0;\n\n    std::size_t GetParameterCount() const {\n      return parameter_count_;\n    }\n\n    INTEGRATOR_TYPE GetIntegratorType() const {\n      return integrator_type_;\n    }\n\n    virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const=0;\n\n    /*\n     * Returns a pair representing the start and stop indices for the parameters\n     * associated with link weights. These should always be contiguous.\n     */\n    virtual std::pair<Index, Index> GetWeightIndexRange() const=0;\n\n  protected:\n    INTEGRATOR_TYPE integrator_type_;\n    std::size_t parameter_count_;\n};\n\ntemplate <typename TReal>\nclass RewardModulatedIntegrator : public virtual Integrator<TReal>\n{\n  public:\n    typedef std::size_t Index;\n    typedef Integrator<TReal> super_type;\n\n    RewardModulatedIntegrator(const TReal learning_rate)\n        : super_type(), learning_rate_(learning_rate) {\n    }\n    virtual ~RewardModulatedIntegrator()= default;\n    virtual void UpdateWeights(const TReal reward,\n                               const TReal reward_average,\n                               const multi_array::Tensor<TReal>& src_state,\n                               const multi_array::Tensor<TReal>& tar_state,\n                               const multi_array::Tensor<TReal>& tar_state_averages)=0;\n    virtual const multi_array::Tensor<TReal>& GetWeights() const=0;\n\n  protected:\n    const TReal learning_rate_;\n};\n\n// None integrator - does nothing\ntemplate<typename TReal>\nclass NoneIntegrator : public virtual Integrator<TReal> {\n  public:\n    typedef Integrator<TReal> super_type;\n    typedef typename super_type::Index Index;\n\n    NoneIntegrator() : super_type() { super_type::integrator_type_ = NONE_INTEGRATOR; }\n    virtual ~NoneIntegrator()=default;\n\n    virtual void operator()(const multi_array::Tensor<TReal>& src_state, multi_array::Tensor<TReal>& tar_state) {}\n    virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {}\n\n    virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {\n      return std::vector<PARAMETER_TYPE>(super_type::parameter_count_);\n    }\n\n    virtual std::pair<Index, Index> GetWeightIndexRange() const {\n      return std::make_pair(0, 0);\n    }\n};\n\n// Integrator that has All2All connectivity with previous layer\ntemplate<typename TReal>\nclass All2AllIntegrator : public virtual Integrator<TReal> {\n  public:\n    typedef Integrator<TReal> super_type;\n    typedef typename super_type::Index Index;\n\n    All2AllIntegrator(Index num_states, Index num_prev_states)\n        : num_states_(num_states), num_prev_states_(num_prev_states) {\n      super_type::parameter_count_ = num_states_ * num_prev_states_;\n      super_type::integrator_type_ = ALL2ALL_INTEGRATOR;\n    }\n\n    virtual void operator()(const multi_array::Tensor<TReal>& src_state, multi_array::Tensor<TReal>& tar_state) {\n      if (!((src_state.size() == num_prev_states_) && (tar_state.size() == num_states_))) {\n        std::cerr << \"src state size: \" << src_state.size() << std::endl;\n        std::cerr << \"prev state size: \" << num_prev_states_ << std::endl;\n        std::cerr << \"tar state size: \" << tar_state.size() << std::endl;\n        std::cerr << \"state size: \" << num_states_ << std::endl;\n        throw std::invalid_argument(\"src state size and prev state size \"\n                                    \"must be equal. tar state size and state\"\n                                    \" size must be equal\");\n      }\n      Index weight_id = 0;\n      for (Index iii = 0; iii < tar_state.size(); ++iii) {\n        TReal cumulative_sum = 0.0;\n        for (Index jjj = 0; jjj < src_state.size(); ++jjj) {\n          cumulative_sum += src_state[jjj] * weights_[weight_id];\n          ++weight_id;\n        }\n        tar_state[iii] = utilities::BoundState(cumulative_sum);\n      }\n    }\n\n    virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {\n      if (parameters.size() != super_type::parameter_count_) {\n        std::cerr << \"parameter size: \" << parameters.size() << std::endl;\n        std::cerr << \"parameter count: \" << super_type::parameter_count_ << std::endl;\n        throw std::invalid_argument(\"Wrong number of parameters\");\n      }\n      weights_ = multi_array::ConstArraySlice<TReal>(parameters);\n    }\n\n    virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {\n      std::vector<PARAMETER_TYPE> layout(super_type::parameter_count_);\n      for (Index iii = 0; iii < super_type::parameter_count_; ++iii) {\n        layout[iii] = WEIGHT;\n      }\n      return layout;\n    }\n\n    virtual std::pair<Index, Index> GetWeightIndexRange() const {\n      return std::make_pair(0, super_type::parameter_count_);\n    }\n\n  protected:\n    Index num_states_;\n    Index num_prev_states_;\n    multi_array::ConstArraySlice<TReal> weights_;\n};\n\n/*\n * Conv integrator - uses implicit structure\n * Uses separable filters, so # params for a KxHxW kernel is K*(H+W)\n *\n * F = layer.shape[0]\n * H/W = filter.shape[1/2]\n * D = filter.shape[0]\n * filter_shape and layer_shape implicitly contain most the information for\n * the shape of the previous layer. Because this is a separable filter\n * the # of parameters for each filter is (W * D) + (H * D).\n * This convolution uses spatially and depthwise separable convolutions.\n * First F HxW convolutions are applied to each input dimension D.\n * Then F Dx1x1 filters are applied to the results.\n * Principle behind DxHxW + DxFx1x1 is that the same filter is used on all\n * layers, and then a 1x1 filter is used to do a weighted sum. This is\n * opposed to having a separate filer for each input channel \n * (each 1x1 needs D parameters, with a total of F 1x1 filters)\n */\ntemplate<typename TReal>\nclass Conv2DIntegrator : public virtual Integrator<TReal> {\n  public:\n    typedef Integrator<TReal> super_type;\n    typedef typename super_type::Index Index;\n\n    Conv2DIntegrator(const multi_array::Array<Index,3>& filter_shape,\n        const multi_array::Array<Index,3>& layer_shape, \n        const multi_array::Array<Index,3>& prev_layer_shape, Index stride)\n        : num_filters_(layer_shape[0]), layer_shape_(layer_shape), \n        prev_layer_shape_(prev_layer_shape),\n        filter_shape_(filter_shape), stride_(stride),\n        filter_parameters_major_({num_filters_}),\n        filter_parameters_minor_({num_filters_}),\n        channel_weights_({num_filters_}) {\n\n      min_src_size_ = std::accumulate(prev_layer_shape_.begin(), \n        prev_layer_shape_.end(), 1, std::multiplies<TReal>());\n      min_tar_size_ = std::accumulate(layer_shape_.begin(), layer_shape_.end(), \n        1, std::multiplies<TReal>());\n      // NumDim should be 3 for stride calculation\n      multi_array::CalculateStrides(layer_shape_.data(), layer_strides_.data(), 3);\n      multi_array::CalculateStrides(prev_layer_shape_.data(), prev_layer_strides_.data(), 3);\n      if (filter_shape[0] != prev_layer_shape[0]) {\n        std::cerr << \"first filter shape: \" << filter_shape[0] << std::endl;\n        std::cerr << \"first prev layer shape: \" << prev_layer_shape[0] << std::endl;\n        throw std::invalid_argument(\"First dimensions must be equal.\");\n      }\n\n      super_type::parameter_count_ = num_filters_ \n        * (filter_shape_[2] + filter_shape_[1] + filter_shape_[0]);\n      super_type::integrator_type_ = CONV_INTEGRATOR;\n      firstpass_buffer_ = multi_array::Tensor<TReal>(\n                            {prev_layer_shape[1], layer_shape[2]});\n      secondpass_buffer_ = multi_array::Tensor<TReal>(\n                            {layer_shape[1], layer_shape[2]});\n    }\n    virtual ~Conv2DIntegrator()=default;\n\n    virtual void operator()(const multi_array::Tensor<TReal>& src_state,\n                            multi_array::Tensor<TReal>& tar_state) {\n      /*\n       * tar_state needs to have AT LEAST as many elements as required by\n       * layer_shape, but it doesn't not need to have the same shape.\n       * tar_state will be re-interpreted as the same shape as layer_shape\n       * src_state will be reinterpreted as the same shape as prev_layer_shape\n       */\n      if (src_state.size() < min_src_size_) {\n        throw std::invalid_argument(\"Src state too small for integrator\");\n      }\n      const multi_array::TensorView<TReal> src_view(src_state.data(), \n        prev_layer_strides_.data(), prev_layer_shape_.data());\n\n      if (tar_state.size() < min_tar_size_) {\n        throw std::invalid_argument(\"tar state too small for integrator\");\n      }\n      multi_array::TensorView<TReal> tar_view(tar_state.data(), \n        layer_strides_.data(), layer_shape_.data());\n\n      multi_array::ArrayView<multi_array::ConstArraySlice<TReal>, 1> major_view(filter_parameters_major_);\n      multi_array::ArrayView<multi_array::ConstArraySlice<TReal>, 1> minor_view(filter_parameters_minor_);\n      multi_array::ArrayView<multi_array::ConstArraySlice<TReal>, 1> channel_view(channel_weights_);\n\n      // for each filter\n      for (Index iii = 0; iii < num_filters_; iii++) {\n        multi_array::TensorView<TReal> tar_image = tar_view[iii];\n        // for each input channel\n        for (Index jjj = 0; jjj < src_view.extent(0); jjj++) {\n          // Carry out separable conv on layer of inputs\n          const multi_array::TensorView<TReal> src_image = src_view[jjj];\n          multi_array::TensorView<TReal> secondpass_image = secondpass_buffer_.accessor();\n          multi_array::TensorView<TReal> firstpass_image = firstpass_buffer_.accessor();\n          Convolve2D(src_image, secondpass_image, firstpass_image,\n                     major_view[iii], minor_view[iii], stride_);\n\n          for (Index kkk = 0; kkk < tar_view.extent(1); ++kkk) {\n            for (Index lll = 0; lll < tar_view.extent(2); ++lll) {\n              tar_image[kkk][lll] += secondpass_image[kkk][lll] * channel_weights_[iii][jjj];\n              tar_image[kkk][lll] = utilities::BoundState<TReal>(tar_image[kkk][lll]);\n            }\n          }\n        }\n      }\n    }\n\n    void Convolve2D(const multi_array::TensorView<TReal>& src,\n        multi_array::TensorView<TReal>& tar, \n        multi_array::TensorView<TReal>& buffer,\n        const multi_array::ConstArraySlice<TReal> &kernel_minor, \n        const multi_array::ConstArraySlice<TReal> &kernel_major,\n        Index stride) {\n\n      // If stride is larger than the kernel, cumulative sum is reset\n      if (stride < kernel_major.size()) {\n        // Accumulate through major axis\n        Index half_kernel = kernel_major.size() / 2;\n        // Minor axis loop\n        TReal cumulative_sum = 0.0;\n        Index output_index = 0;\n        for (Index iii = 0; iii < src.extent(0); ++iii) {\n          cumulative_sum = 0.0;\n          output_index = 0;\n          // Initiate sum\n          // Add out-of-bounds components\n          for (Index kkk = 0; kkk < half_kernel; kkk++) {\n            cumulative_sum += kernel_major[kkk] * src[iii][0];\n          }\n          // Add in-bounds components\n          for (Index kkk = half_kernel; kkk < kernel_major.size(); kkk++) {\n            cumulative_sum += kernel_major[kkk] * src[iii][kkk - half_kernel];\n          }\n          buffer[iii][output_index++] = cumulative_sum;\n\n          // Roll sum (out-of-bounds components)\n          Index jjj = stride;\n          for (; jjj < half_kernel+stride; jjj+=stride) {\n            for (Index kkk = 0; kkk < stride; ++kkk) {\n              cumulative_sum += kernel_major[kernel_major.size() - kkk - 1] * src[iii][jjj + half_kernel - kkk]\n                              - kernel_major[kkk] * src[iii][0];\n            }\n            buffer[iii][output_index++] = cumulative_sum;\n          }\n\n          //  Roll sum (in-bounds components)\n          for (; jjj < src.extent(1)-half_kernel; jjj+=stride) {\n            for (Index kkk = 0; kkk < stride; ++kkk) {\n              cumulative_sum += kernel_major[kernel_major.size() - kkk - 1] * src[iii][jjj + half_kernel - kkk]\n                              - kernel_major[kkk] * src[iii][jjj - half_kernel - 1 - kkk];\n            }\n            buffer[iii][output_index++] = cumulative_sum;\n          }\n\n          // Roll sum (out-of-bounds end components)\n          for (; jjj < src.extent(1); jjj+=stride) {\n            for (Index kkk = 0; kkk < stride; ++kkk) {\n              cumulative_sum += kernel_major[kernel_major.size() - kkk - 1] * src[iii][src.extent(1)-1]\n                              - kernel_major[kkk] * src[iii][jjj - half_kernel - 1 - kkk];\n            }\n            buffer[iii][output_index++] = cumulative_sum;\n          }\n        }\n      }\n      else {\n        // Accumulate through major axis\n        Index half_kernel = kernel_major.size() / 2;\n        // Minor axis loop\n        TReal cumulative_sum = 0.0;\n        Index output_index = 0;\n        for (Index iii = 0; iii < src.extent(0); ++iii) {\n          cumulative_sum = 0.0;\n          output_index = 0;\n          // Initiate sum\n          // Add out-of-bounds components\n          for (Index kkk = 0; kkk < half_kernel; kkk++) {\n            cumulative_sum += kernel_major[kkk] * src[iii][0];\n          }\n          // Add in-bounds components\n          for (Index kkk = half_kernel; kkk < kernel_major.size(); kkk++) {\n            cumulative_sum += kernel_major[kkk] * src[iii][kkk - half_kernel];\n          }\n          buffer[iii][output_index++] = cumulative_sum;\n\n          //  Roll sum (in-bounds components)\n          Index jjj = stride;\n          for (; jjj < src.extent(1)-half_kernel; jjj+=stride) {\n            cumulative_sum = 0.0;\n            for (Index kkk = 0; kkk < kernel_major.size(); ++kkk) {\n              cumulative_sum += kernel_major[kkk] * src[iii][jjj - half_kernel + kkk];\n            }\n            buffer[iii][output_index++] = cumulative_sum;\n          }\n\n          // Roll sum (out-of-bounds end components)\n          for (; jjj < src.extent(1); jjj+=stride) {\n            cumulative_sum = 0.0;\n            // Add in-bounds components\n            for (Index kkk = 0; kkk < half_kernel+1; kkk++) {\n              cumulative_sum += kernel_major[kkk] * src[iii][jjj - half_kernel + kkk];\n            }\n            // Add out-of-bounds components\n            for (Index kkk = half_kernel+1; kkk < kernel_major.size(); kkk++) {\n              cumulative_sum += kernel_major[kkk] * src[iii][src.extent(1)-1];\n            }\n            buffer[iii][output_index++] = cumulative_sum;\n          }\n        }\n      }\n      if (stride < kernel_minor.size()) {\n        // Accumulate through minor axis\n        TReal cumulative_sum = 0.0;\n        Index output_index = 0;\n        Index half_kernel = kernel_minor.size() / 2;\n        for (Index iii = 0; iii < buffer.extent(1); iii++) {\n          cumulative_sum = 0.0;\n          output_index = 0;\n          // Initiate sum\n          // Add out-of-bounds components\n          for (Index kkk = 0; kkk < half_kernel; kkk++) {\n            cumulative_sum += kernel_minor[kkk] * buffer[0][iii];\n          }\n          // Add in-bounds components\n          for (Index kkk = half_kernel; kkk < kernel_minor.size(); kkk++) {\n            cumulative_sum += kernel_minor[kkk] * buffer[kkk - half_kernel][iii];\n          }\n          tar[output_index++][iii] = cumulative_sum;\n\n          // Roll sum (out-of-bounds components)\n          Index jjj = stride;\n          for (; jjj < half_kernel+stride; jjj+=stride) {\n            for (Index kkk = 0; kkk < stride; ++kkk) {\n              cumulative_sum += kernel_major[kernel_minor.size() - kkk - 1] * buffer[jjj + half_kernel - kkk][iii]\n                              - kernel_minor[kkk] * buffer[0][iii];\n            }\n            tar[output_index++][iii] = cumulative_sum;\n          }\n\n          //  Roll sum (in-bounds components)\n          for (; jjj < buffer.extent(0)-half_kernel; jjj+=stride) {\n            for (Index kkk = 0; kkk < stride; ++kkk) {\n              cumulative_sum += kernel_major[kernel_minor.size() - kkk - 1] * buffer[jjj + half_kernel - kkk][iii]\n                              - kernel_minor[kkk] * buffer[jjj - half_kernel - 1 - kkk][iii];\n            }\n            tar[output_index++][iii] = cumulative_sum;\n          }\n\n          // Roll sum (out-of-bounds end components)\n          for (; jjj < buffer.extent(0); jjj+=stride) {\n            for (Index kkk = 0; kkk < stride; ++kkk) {\n              cumulative_sum += kernel_major[kernel_minor.size() - kkk - 1] * buffer[src.extent(0)-1][iii]\n                              - kernel_minor[kkk] * buffer[jjj - half_kernel - 1 - kkk][iii];\n            }\n            tar[output_index++][iii] = cumulative_sum;\n          }\n        }\n      }\n      else {\n\n        // Accumulate through major axis\n        Index half_kernel = kernel_minor.size() / 2;\n        TReal cumulative_sum = 0.0;\n        Index output_index = 0;\n        // Minor axis loop\n        for (Index iii = 0; iii < buffer.extent(1); ++iii) {\n          cumulative_sum = 0.0;\n          output_index = 0;\n          // Initiate sum\n          // Add out-of-bounds components\n          for (Index kkk = 0; kkk < half_kernel; kkk++) {\n            cumulative_sum += kernel_minor[kkk] * buffer[0][iii];\n          }\n          // Add in-bounds components\n          for (Index kkk = half_kernel; kkk < kernel_minor.size(); kkk++) {\n            cumulative_sum += kernel_minor[kkk] * buffer[kkk - half_kernel][iii];\n          }\n          tar[output_index++][iii] = cumulative_sum;\n\n          //  Roll sum (in-bounds components)\n          Index jjj = stride;\n          for (; jjj < buffer.extent(0)-half_kernel; jjj+=stride) {\n            cumulative_sum = 0.0;\n            for (Index kkk = 0; kkk < kernel_minor.size(); ++kkk) {\n              cumulative_sum += kernel_minor[kkk] * buffer[jjj - half_kernel + kkk][iii];\n            }\n            tar[output_index++][iii] = cumulative_sum;\n          }\n\n          // Roll sum (out-of-bounds end components)\n          for (; jjj < buffer.extent(0); jjj+=stride) {\n            cumulative_sum = 0.0;\n            // Add in-bounds components\n            for (Index kkk = 0; kkk < half_kernel+1; kkk++) {\n              cumulative_sum += kernel_minor[kkk] * buffer[jjj - half_kernel + kkk][iii];\n            }\n            // Add out-of-bounds components\n            for (Index kkk = half_kernel+1; kkk < kernel_minor.size(); kkk++) {\n              cumulative_sum += kernel_minor[kkk] * buffer[buffer.extent(0)-1][iii];\n            }\n            tar[output_index++][iii] = cumulative_sum;\n          }\n        }\n      }\n    }\n\n    virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {\n\n      if (parameters.size() != super_type::parameter_count_) {\n        std::cerr << \"parameter size: \" << parameters.size() << std::endl;\n        std::cerr << \"parameter count: \" << super_type::parameter_count_ << std::endl;\n        throw std::invalid_argument(\"Wrong number of parameters\");\n      }\n      multi_array::ArrayView< multi_array::ConstArraySlice<TReal>, 1> major_view(filter_parameters_major_);\n      multi_array::ArrayView< multi_array::ConstArraySlice<TReal>, 1> minor_view(filter_parameters_minor_);\n      multi_array::ArrayView< multi_array::ConstArraySlice<TReal>, 1> channel_view(channel_weights_);\n\n      Index start(0);\n      for (Index filter = 0; filter < num_filters_; filter++) {\n        major_view[filter] = parameters.slice(start, filter_shape_[2]);\n        start += parameters.stride() * filter_shape_[2];\n\n        minor_view[filter] = parameters.slice(start, filter_shape_[1]);\n        start += parameters.stride() * filter_shape_[1];\n\n        channel_view[filter] = parameters.slice(start, filter_shape_[0]);\n        start += parameters.stride() * filter_shape_[0];\n      }\n    }\n\n    virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {\n      std::vector<PARAMETER_TYPE> layout(super_type::parameter_count_);\n      for (Index iii = 0; iii < super_type::parameter_count_; ++iii) {\n        layout[iii] = WEIGHT;\n      }\n      return layout;\n    }\n\n    virtual std::pair<Index, Index> GetWeightIndexRange() const {\n      return std::make_pair(0, super_type::parameter_count_);\n    }\n\n    const multi_array::Array<Index, 3>& GetFilterShape() const {\n      return filter_shape_;\n    };\n\n    Index GetMinTarSize() const {\n      return min_tar_size_;\n    }\n\n  protected:\n    Index num_filters_;\n    multi_array::Array<Index, 3> layer_shape_;\n    multi_array::Array<Index, 3> prev_layer_shape_;\n    multi_array::Array<Index, 3> filter_shape_;\n    Index stride_;\n    Index min_src_size_;\n    Index min_tar_size_;\n    multi_array::Array<Index, 3> prev_layer_strides_;\n    multi_array::Array<Index, 3> layer_strides_;\n    multi_array::MultiArray<multi_array::ConstArraySlice<TReal>, 1> filter_parameters_major_;\n    multi_array::MultiArray<multi_array::ConstArraySlice<TReal>, 1> filter_parameters_minor_;\n    multi_array::MultiArray<multi_array::ConstArraySlice<TReal>, 1> channel_weights_;\n    multi_array::Tensor<TReal> secondpass_buffer_;\n    multi_array::Tensor<TReal> firstpass_buffer_;\n};\n\n// Network integrator -- uses explicit unweighted structure\ntemplate<typename TReal>\nclass RecurrentIntegrator : public virtual Integrator<TReal> {\n  public:\n    typedef Integrator<TReal> super_type;\n    typedef typename super_type::Index Index;\n\n    RecurrentIntegrator(const graphs::PredecessorGraph<>& network) \n        : network_(network) {\n      super_type::integrator_type_ = RECURRENT_INTEGRATOR;\n      super_type::parameter_count_ = network_.NumEdges();\n    }\n\n    virtual ~RecurrentIntegrator()=default;\n\n    virtual void operator()(const multi_array::Tensor<TReal>& src_state,\n                    multi_array::Tensor<TReal>& tar_state) {\n      \n      /*\n       * Graph maybe a connector graph or an internal graph.\n       * In case of connector, the num nodes doesn't need to match tar_state,\n       * because predecessors should be empty for nodes not in tar_state.\n       * However, src state does have to be checked using (at) when tar_state\n       * is larger than src_state, to ensure nothing invalid is accessed.\n       */\n      Index edge_id = 0;\n      for (Index node = 0; node < network_.NumNodes(); ++node) {\n        for (Index iii = 0; iii < network_.Predecessors(node).size(); ++iii) {\n          tar_state.at(node) += src_state.at(network_.Predecessors(node)[iii].source) * weights_[edge_id];\n          tar_state[node] = utilities::BoundState(tar_state[node]);\n          ++edge_id;\n        }\n      }\n      if (edge_id != network_.NumEdges()) {\n        throw std::runtime_error(\"Miss match between number of edges and the\"\n                                 \" number integrated\");\n      }\n    }\n\n    virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {\n      if (parameters.size() != super_type::parameter_count_) {\n        std::cerr << \"parameter size: \" << parameters.size() << std::endl;\n        std::cerr << \"parameter count: \" << super_type::parameter_count_ << std::endl;\n        throw std::invalid_argument(\"Wrong number of parameters\");\n      }\n      weights_ = parameters.slice(0, super_type::parameter_count_);\n    }\n\n    virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {\n      std::vector<PARAMETER_TYPE> layout(super_type::parameter_count_);\n      for (Index iii = 0; iii < super_type::parameter_count_; ++iii) {\n        layout[iii] = WEIGHT;\n      }\n      return layout;\n    }\n\n    const multi_array::ConstArraySlice<TReal>& GetWeights() const {\n      return weights_;\n    }\n\n    virtual std::pair<Index, Index> GetWeightIndexRange() const {\n      return std::make_pair(0, super_type::parameter_count_);\n    }\n\n    const graphs::PredecessorGraph<>& GetGraph() const {\n      return network_;\n    }\n\n  protected:\n    graphs::PredecessorGraph<> network_;\n    multi_array::ConstArraySlice<TReal> weights_;\n};\n\n// Truncated Recurrent integrator sets weights to 0 during calculations if\n// they are below the magnitude of the threshold.\ntemplate<typename TReal>\nclass TruncatedRecurrentIntegrator : public virtual RecurrentIntegrator<TReal> {\n  public:\n    typedef RecurrentIntegrator<TReal> super_type;\n    typedef typename super_type::Index Index;\n\n    TruncatedRecurrentIntegrator(const graphs::PredecessorGraph<>& network,\n                                 TReal weight_threshold)\n        : super_type(network), weight_threshold_(weight_threshold) {\n\n      super_type::integrator_type_ = TRUNCATED_RECURRENT_INTEGRATOR;\n    }\n\n    virtual ~TruncatedRecurrentIntegrator()= default;\n\n    virtual void operator()(const multi_array::Tensor<TReal>& src_state,\n                    multi_array::Tensor<TReal>& tar_state) {\n\n      Index edge_id = 0;\n      for (Index node = 0; node < super_type::network_.NumNodes(); ++node) {\n        for (Index iii = 0; iii < super_type::network_.Predecessors(node).size(); ++iii) {\n          // Only carry out calculation if it exceeds magnitude of the threshold\n          if ((super_type::weights_[edge_id] > weight_threshold_\n               && super_type::weights_[edge_id] >= 0) ||\n              (super_type::weights_[edge_id] < -weight_threshold_\n               && super_type::weights_[edge_id] <= 0)) {\n            tar_state.at(node) += src_state.at(super_type::network_.Predecessors(node)[iii].source)\n                               * super_type::weights_[edge_id];\n            tar_state[node] = utilities::BoundState(tar_state[node]);\n          }\n          ++edge_id;\n        }\n      }\n      if (edge_id != super_type::network_.NumEdges()) {\n        throw std::runtime_error(\"Miss match between number of edges and the\"\n                                 \" number integrated\");\n      }\n    }\n\n    TReal GetWeightThreshold() const {\n      return weight_threshold_;\n    }\n\n  protected:\n    TReal weight_threshold_;\n};\n\n// Reservoir -- uses explicit weighted structure\ntemplate<typename TReal>\nclass ReservoirIntegrator : public virtual Integrator<TReal> {\n  public:\n    typedef Integrator<TReal> super_type;\n    typedef typename super_type::Index Index;\n\n    ReservoirIntegrator(const graphs::PredecessorGraph<TReal>& network)\n        : network_(network) {\n      super_type::integrator_type_ = RESERVOIR_INTEGRATOR;\n      super_type::parameter_count_ = 0;\n    }\n\n    ~ReservoirIntegrator()=default;\n\n    void operator()(const multi_array::Tensor<TReal>& src_state,\n                    multi_array::Tensor<TReal>& tar_state) {\n\n      for (Index node = 0; node < network_.NumNodes(); ++node) {\n        for (Index iii = 0; iii < network_.Predecessors(node).size(); ++iii) {\n          tar_state.at(node) += src_state.at(network_.Predecessors(node)[iii].source)\n                              * network_.Predecessors(node)[iii].weight;\n          tar_state[node] = utilities::BoundState(tar_state[node]);\n        }\n      }\n    }\n\n    void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {}\n\n    std::vector<PARAMETER_TYPE> GetParameterLayout() const {\n      return std::vector<PARAMETER_TYPE>(super_type::parameter_count_);\n    }\n\n    std::pair<Index, Index> GetWeightIndexRange() const {\n      return std::make_pair(0, 0);\n    }\n\n    const graphs::PredecessorGraph<TReal>& GetGraph() const {\n      return network_;\n    }\n\n  protected:\n    graphs::PredecessorGraph<TReal> network_;\n};\n\n/*\n * Implements non-separable convolution using im2col and gemm through Eigen\n * Assumes NCHW memory layout\n * TODO: Support even filters\n */\ntemplate<typename TReal>\nclass ConvEigenIntegrator : public virtual Integrator<TReal> {\n  public:\n    typedef Integrator<TReal> super_type;\n    typedef typename super_type::Index Index;\n    typedef Eigen::Matrix<TReal, Eigen::Dynamic, Eigen::Dynamic> Matrix;\n    typedef const Eigen::Matrix<TReal, Eigen::Dynamic, Eigen::Dynamic> ConstMatrix;\n    typedef Eigen::Map<Matrix> MatrixView;\n    typedef const Eigen::Map<ConstMatrix> ConstMatrixView;\n\n    /*\n     * Filter shape order: {depth, height, width}\n     * Layer shape order: {# channels, height, width}\n     * Prev Layer order: {# channels, height, width}\n     * Note: This is a bit confusing because my tensors us C++ memory order\n     * and Eigen uses Fortran. So I list shapes here with last element of shape\n     * being the major axis. This is reversed in Eigen, where first is the major.\n     */\n    ConvEigenIntegrator(const multi_array::Array<Index,3>& filter_shape,\n                        const multi_array::Array<Index,3>& layer_shape,\n                        const multi_array::Array<Index,3>& prev_layer_shape,\n                        Index stride)\n                      : num_filters_(layer_shape[0]), layer_shape_(layer_shape),\n                        prev_layer_shape_(prev_layer_shape),\n                        filter_shape_(filter_shape), stride_(stride),\n                        channels_(prev_layer_shape[0]),\n                        height_(prev_layer_shape[1]),\n                        width_(prev_layer_shape[2]),\n                        kernel_h_(filter_shape[1]),\n                        kernel_w_(filter_shape[2]),\n                        pad_h_(kernel_h_/2),\n                        pad_w_(kernel_w_/2),\n                        channel_size_(((height_ + 2 * pad_h_ - kernel_h_)\n                                       / stride_ + 1)\n                                      * ((width_ + 2 * pad_w_ - kernel_w_)\n                                         / stride_ + 1)),\n                        buffer_state_(channel_size_,\n                                      kernel_h_ * kernel_w_ * channels_) {\n      super_type::parameter_count_ = kernel_w_ * kernel_h_ * channels_ * num_filters_;\n      super_type::integrator_type_ = CONV_EIGEN_INTEGRATOR;\n    }\n\n    virtual ~ConvEigenIntegrator()=default;\n\n    /*\n     * Matrix: (# rows, # cols) -> column major\n     * src shape: {height * width, channels}\n     * tar shape: {(new height * new width), num_filters}\n     * Note: If you check tensor shape it will be the reverse, since I use C's\n     * order, while Eigen uses Fortran's. Sorry for the confusion, but Eigen\n     * got added in latter and I am not sure why they choose Fortran's way for a\n     * C++ API.\n     */\n    virtual void operator()(const multi_array::Tensor<TReal>& src_state,\n                    multi_array::Tensor<TReal>& tar_state) override {\n\n      utilities::Im2Col(src_state.data(), channels_, height_, width_,\n                        kernel_h_, kernel_w_, pad_h_, pad_w_, stride_, stride_,\n                        1, 1, buffer_state_.data());\n      MatrixView output(tar_state.data(), channel_size_, num_filters_);\n      ConstMatrixView params(weight_view_.data() + weight_view_.start(),\n                             kernel_w_ * kernel_h_ * channels_,\n                             num_filters_);\n      output.noalias() = buffer_state_ * params;\n    }\n\n    virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) override {\n      weight_view_ = parameters;\n    }\n\n    virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const override {\n      std::vector<PARAMETER_TYPE> layout(super_type::parameter_count_);\n      for (Index iii = 0; iii < super_type::parameter_count_; ++iii) {\n        layout[iii] = WEIGHT;\n      }\n      return layout;\n    }\n\n    virtual std::pair<Index, Index> GetWeightIndexRange() const override {\n      return std::make_pair(0, super_type::parameter_count_);\n    };\n\n  protected:\n    const utilities::Integer num_filters_;\n    const multi_array::Array<Index, 3> layer_shape_;\n    const multi_array::Array<Index, 3> prev_layer_shape_;\n    const multi_array::Array<Index, 3> filter_shape_;\n    const utilities::Integer stride_;\n    const utilities::Integer channels_;\n    const utilities::Integer height_;\n    const utilities::Integer width_;\n    const utilities::Integer kernel_h_;\n    const utilities::Integer kernel_w_;\n    const utilities::Integer pad_h_;\n    const utilities::Integer pad_w_;\n    const utilities::Integer channel_size_;\n    Matrix buffer_state_;\n    multi_array::ConstArraySlice<TReal> weight_view_;\n};\n\ntemplate <typename TReal>\nclass RewardModulatedConvIntegrator : public ConvEigenIntegrator<TReal>,\n                                      public RewardModulatedIntegrator<TReal> {\n  public:\n    typedef RewardModulatedIntegrator<TReal> reward_modulator_type;\n    typedef ConvEigenIntegrator<TReal> conv_type;\n    typedef typename conv_type::Index Index;\n    typedef typename conv_type::Matrix Matrix;\n    typedef typename conv_type::ConstMatrix ConstMatrix;\n    typedef typename conv_type::MatrixView MatrixView;\n    typedef typename conv_type::ConstMatrixView ConstMatrixView;\n\n    RewardModulatedConvIntegrator(const multi_array::Array<Index,3>& filter_shape,\n                                  const multi_array::Array<Index,3>& layer_shape,\n                                  const multi_array::Array<Index,3>& prev_layer_shape,\n                                  Index stride, const TReal learning_rate)\n        : conv_type(filter_shape, layer_shape, prev_layer_shape, stride),\n          reward_modulator_type(learning_rate),\n          weights_({conv_type::parameter_count_}) {\n      conv_type::integrator_type_ = REWARD_MODULATED;\n    }\n\n    void operator()(const multi_array::Tensor<TReal>& src_state,\n                    multi_array::Tensor<TReal>& tar_state) override {\n\n      utilities::Im2Col(src_state.data(), conv_type::channels_,\n                        conv_type::height_, conv_type::width_,\n                        conv_type::kernel_h_, conv_type::kernel_w_,\n                        conv_type::pad_h_, conv_type::pad_w_,\n                        conv_type::stride_, conv_type::stride_,\n                        1, 1, conv_type::buffer_state_.data());\n      MatrixView output(tar_state.data(), conv_type::channel_size_,\n                        conv_type::num_filters_);\n      ConstMatrixView params(weights_.data(),\n                             conv_type::kernel_w_\n                             * conv_type::kernel_h_\n                             * conv_type::channels_,\n                             conv_type::num_filters_);\n      output.noalias() = conv_type::buffer_state_ * params;\n    }\n\n    void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {\n      if (parameters.size() != conv_type::parameter_count_) {\n        std::cerr << \"parameter size: \" << parameters.size() << std::endl;\n        std::cerr << \"parameter count: \" << conv_type::parameter_count_ << std::endl;\n        throw std::invalid_argument(\"Wrong number of parameters\");\n      }\n\n      for (Index iii = 0; iii < parameters.size(); ++iii) {\n        weights_[iii] = parameters[iii];\n      }\n      conv_type::weight_view_ = multi_array::ConstArraySlice<TReal>(weights_.data(), 0,\n                                                         weights_.size());\n    }\n\n    void UpdateWeights(const TReal reward,\n                       const TReal reward_average,\n                       const multi_array::Tensor<TReal>& src_state,\n                       const multi_array::Tensor<TReal>& tar_state,\n                       const multi_array::Tensor<TReal>& tar_state_averages) {\n\n      MatrixView weights(weights_.data(),\n                         conv_type::kernel_w_\n                         * conv_type::kernel_h_\n                         * conv_type::channels_,\n                         conv_type::num_filters_);\n      ConstMatrixView tar_view(tar_state.data(), conv_type::channel_size_,\n                               conv_type::num_filters_);\n      ConstMatrixView tar_avg_view(tar_state_averages.data(),\n                                   conv_type::channel_size_,\n                                   conv_type::num_filters_);\n\n      std::cout << \"weights dim: cols \" << weights.cols() << \" rows \" << weights.rows() << std::endl;/////////////\n      std::cout << \"tar view dim: cols \" << tar_view.cols() << \" rows \" << tar_view.rows() << std::endl;/////////////\n      std::cout << \"tar avg view dim: cols \" << tar_avg_view.cols() << \" rows \" << tar_avg_view.rows() << std::endl;/////////////\n      std::cout << \"buff dim: cols \" << conv_type::buffer_state_.cols() << \" rows \" << conv_type::buffer_state_.rows() << std::endl;/////////////\n\n      // find max index tar state, updates single filter\n      const Index max_neuron_index = utilities::IndexOfMaxElement(tar_state);\n      // Get the filter index for the max neuron\n      const Index max_filter = max_neuron_index / conv_type::channel_size_;\n      // The buffer_state im2col matrix has a window of states from the previous\n      // layer that will correspond to the states that need to be integrated\n      // for a given position in the current layer (same for each channel)\n      // This position is modulo the size of the channel:\n      const Index max_neuron_window = max_neuron_index % conv_type::channel_size_;\n      // Alternatively find max index tar state for each filter, updates each filter\n\n      // Loops through src neuron states\n      const TReal reward_modulated_learning_factor = (reward - reward_average)\n                                                     * reward_modulator_type::learning_rate_;\n      for (auto src_neuron = 0; src_neuron < conv_type::buffer_state_.cols(); ++src_neuron) {\n        weights(src_neuron, max_filter) += conv_type::buffer_state_(max_neuron_window,\n                                                                    src_neuron)\n                                 * (tar_state[max_neuron_index]\n                                    - tar_state_averages[max_neuron_index])\n                                 * reward_modulated_learning_factor;\n      }\n    }\n\n    const multi_array::Tensor<TReal>& GetWeights() const\n    {\n      return weights_;\n    }\n\n  protected:\n    multi_array::Tensor<TReal> weights_;\n};\n\n/*\n * Implements an All2All integrator with an Eigen backend\n */\ntemplate<typename TReal>\nclass All2AllEigenIntegrator : public virtual Integrator<TReal> {\n  public:\n    typedef Integrator<TReal> super_type;\n    typedef typename super_type::Index Index;\n    typedef Eigen::Matrix<TReal, Eigen::Dynamic, 1> ColVector;\n    typedef Eigen::Map<ColVector> ColVectorView;\n    typedef const Eigen::Matrix<TReal, Eigen::Dynamic, 1> ConstColVector;\n    typedef const Eigen::Map<ConstColVector> ConstColVectorView;\n    typedef const Eigen::Matrix<TReal, Eigen::Dynamic, Eigen::Dynamic> ConstMatrix;\n    typedef const Eigen::Map<ConstMatrix> ConstMatrixView;\n\n    All2AllEigenIntegrator(Index num_states, Index num_prev_states)\n    : num_states_(num_states), num_prev_states_(num_prev_states) {\n      super_type::parameter_count_ = num_states_ * num_prev_states_;\n      super_type::integrator_type_ = ALL2ALL_EIGEN_INTEGRATOR;\n    }\n\n    virtual void operator()(const multi_array::Tensor<TReal>& src_state,\n                            multi_array::Tensor<TReal>& tar_state) {\n      if (!((src_state.size() == num_prev_states_) && (tar_state.size() == num_states_))) {\n        std::cerr << \"src state size: \" << src_state.size() << std::endl;\n        std::cerr << \"prev state size: \" << num_prev_states_ << std::endl;\n        std::cerr << \"tar state size: \" << tar_state.size() << std::endl;\n        std::cerr << \"state size: \" << num_states_ << std::endl;\n        throw std::invalid_argument(\"src state size and prev state size \"\n                                    \"must be equal. tar state size and state\"\n                                    \" size must be equal\");\n      }\n\n      ColVectorView output(tar_state.data(), tar_state.size());\n      output.noalias() = ConstMatrixView(weight_view_.data() + weight_view_.start(),\n                                         tar_state.size(),\n                                         src_state.size())\n                         * ConstColVectorView(src_state.data(), src_state.size());\n    }\n\n    virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {\n      if (parameters.size() != super_type::parameter_count_) {\n        std::cerr << \"parameter size: \" << parameters.size() << std::endl;\n        std::cerr << \"parameter count: \" << super_type::parameter_count_ << std::endl;\n        throw std::invalid_argument(\"Wrong number of parameters\");\n      }\n      weight_view_ = parameters;\n    }\n\n    virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {\n      std::vector<PARAMETER_TYPE> layout(super_type::parameter_count_);\n      for (Index iii = 0; iii < super_type::parameter_count_; ++iii) {\n        layout[iii] = WEIGHT;\n      }\n      return layout;\n    }\n\n    virtual std::pair<Index, Index> GetWeightIndexRange() const {\n      return std::make_pair(0, super_type::parameter_count_);\n    }\n\n  protected:\n    Index num_states_;\n    Index num_prev_states_;\n    multi_array::ConstArraySlice<TReal> weight_view_;\n};\n\n/*\n * Implements a recurrent integrator with Eigen\n */\ntemplate<typename TReal>\nclass RecurrentEigenIntegrator : public virtual Integrator<TReal> {\n  public:\n    typedef Integrator<TReal> super_type;\n    typedef typename super_type::Index Index;\n    typedef Eigen::Matrix<TReal, Eigen::Dynamic, 1> ColVector;\n    typedef Eigen::Map<ColVector> ColVectorView;\n    typedef const Eigen::Matrix<TReal, Eigen::Dynamic, 1> ConstColVector;\n    typedef const Eigen::Map<ConstColVector> ConstColVectorView;\n    typedef Eigen::SparseMatrix<TReal> SparseMatrix;\n    typedef const Eigen::SparseMatrix<TReal> ConstSparseMatrix;\n    typedef const Eigen::Map<ConstSparseMatrix> ConstSparseMatrixView;\n\n    RecurrentEigenIntegrator(SparseMatrix network) : network_(std::move(network)) {\n      network_.makeCompressed();\n      super_type::integrator_type_ = RECURRENT_EIGEN_INTEGRATOR;\n      super_type::parameter_count_ = network_.nonZeros();\n    }\n\n    virtual ~RecurrentEigenIntegrator()=default;\n\n    virtual void operator()(const multi_array::Tensor<TReal>& src_state,\n                            multi_array::Tensor<TReal>& tar_state) {\n\n      if ((network_.cols() != src_state.size())\n          && (network_.rows() != tar_state.size())) {\n        throw std::invalid_argument(\"src state size and tar state size \"\n                                    \"incompatible with network\");\n      }\n\n      ConstSparseMatrixView weight_matrix(network_.rows(), network_.cols(),\n                                          weight_view_.size(), network_.outerIndexPtr(),\n                                          network_.innerIndexPtr(),\n                                          weight_view_.data() + weight_view_.start(),\n                                          network_.innerNonZeroPtr());\n      ColVectorView output_vector(tar_state.data(), tar_state.size());\n      ConstColVectorView src_vector(src_state.data(), src_state.size());\n\n      output_vector.noalias() = weight_matrix * src_vector;\n    }\n\n    virtual void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {\n      if (parameters.size() != super_type::parameter_count_) {\n        std::cerr << \"parameter size: \" << parameters.size() << std::endl;\n        std::cerr << \"parameter count: \" << super_type::parameter_count_ << std::endl;\n        throw std::invalid_argument(\"Wrong number of parameters\");\n      }\n      weight_view_ = parameters.slice(0, super_type::parameter_count_);\n    }\n\n    virtual std::vector<PARAMETER_TYPE> GetParameterLayout() const {\n      std::vector<PARAMETER_TYPE> layout(super_type::parameter_count_);\n      for (Index iii = 0; iii < super_type::parameter_count_; ++iii) {\n        layout[iii] = WEIGHT;\n      }\n      return layout;\n    }\n\n    const multi_array::ConstArraySlice<TReal>& GetWeights() const {\n      return weight_view_;\n    }\n\n    virtual std::pair<Index, Index> GetWeightIndexRange() const {\n      return std::make_pair(0, super_type::parameter_count_);\n    }\n\n  protected:\n    SparseMatrix network_;\n    multi_array::ConstArraySlice<TReal> weight_view_;\n};\n\n/*\n * Implements a reservior layer using Eigen\n */\ntemplate<typename TReal>\nclass ReservoirEigenIntegrator : public virtual Integrator<TReal> {\n  public:\n    typedef Integrator<TReal> super_type;\n    typedef typename super_type::Index Index;\n    typedef Eigen::Matrix<TReal, Eigen::Dynamic, 1> ColVector;\n    typedef Eigen::Map <ColVector> ColVectorView;\n    typedef const Eigen::Matrix<TReal, Eigen::Dynamic, 1> ConstColVector;\n    typedef const Eigen::Map <ConstColVector> ConstColVectorView;\n    typedef Eigen::SparseMatrix <TReal> SparseMatrix;\n\n    ReservoirEigenIntegrator(SparseMatrix network)\n    : network_(std::move(network)) {\n      network_.makeCompressed();\n      super_type::integrator_type_ = RESERVOIR_EIGEN_INTEGRATOR;\n      super_type::parameter_count_ = 0;\n    }\n\n    ~ReservoirEigenIntegrator()=default;\n\n    void operator()(const multi_array::Tensor<TReal>& src_state,\n                    multi_array::Tensor<TReal>& tar_state) {\n\n      if ((network_.cols() != src_state.size())\n          && (network_.rows() != tar_state.size())) {\n        throw std::invalid_argument(\"src state size and tar state size \"\n                                    \"incompatible with network\");\n      }\n\n      ColVectorView output_vector(tar_state.data(), tar_state.size());\n      ConstColVectorView src_vector(src_state.data(), src_state.size());\n      output_vector.noalias() = network_ * src_vector;\n    }\n\n    void Configure(const multi_array::ConstArraySlice<TReal>& parameters) {}\n\n    std::vector<PARAMETER_TYPE> GetParameterLayout() const {\n      return std::vector<PARAMETER_TYPE>(super_type::parameter_count_);\n    }\n\n    std::pair<Index, Index> GetWeightIndexRange() const {\n      return std::make_pair(0, 0);\n    }\n\n  protected:\n    SparseMatrix network_;\n};\n\ntemplate <typename TReal>\nclass RewardModulatedAll2AllIntegrator : public All2AllEigenIntegrator<TReal>,\n                                         public RewardModulatedIntegrator<TReal> {\n  public:\n    typedef All2AllEigenIntegrator<TReal> all2all_type;\n    typedef RewardModulatedIntegrator<TReal> reward_modulator_type;\n    typedef typename all2all_type::Index Index;\n    typedef typename all2all_type::ColVector ColVector;\n    typedef typename all2all_type::ColVectorView ColVectorView;\n    typedef typename all2all_type::ConstColVector ConstColVector;\n    typedef typename all2all_type::ConstColVectorView ConstColVectorView;\n    typedef typename all2all_type::ConstMatrix ConstMatrix;\n    typedef typename all2all_type::ConstMatrixView ConstMatrixView;\n    typedef Eigen::Matrix<TReal, Eigen::Dynamic, Eigen::Dynamic> Matrix;\n    typedef Eigen::Map<Matrix> MatrixView;\n\n    RewardModulatedAll2AllIntegrator(const Index num_states,\n                                     const Index num_prev_states,\n                                     const TReal learning_rate)\n      : all2all_type(num_states, num_prev_states),\n        reward_modulator_type(learning_rate),\n        weights_({all2all_type::parameter_count_}) {\n      all2all_type::integrator_type_ = REWARD_MODULATED;\n    }\n\n    void operator()(const multi_array::Tensor<TReal>& src_state,\n                    multi_array::Tensor<TReal>& tar_state) override\n    {\n      if (!((src_state.size() == all2all_type::num_prev_states_)\n            && (tar_state.size() == all2all_type::num_states_))) {\n        std::cerr << \"src state size: \" << src_state.size() << std::endl;\n        std::cerr << \"prev state size: \" << all2all_type::num_prev_states_ << std::endl;\n        std::cerr << \"tar state size: \" << tar_state.size() << std::endl;\n        std::cerr << \"state size: \" << all2all_type::num_states_ << std::endl;\n        throw std::invalid_argument(\"src state size and prev state size \"\n                                    \"must be equal. tar state size and state\"\n                                    \" size must be equal\");\n      }\n\n      ColVectorView output(tar_state.data(), tar_state.size());\n      output.noalias() = ConstMatrixView(weights_.data(),\n                                         tar_state.size(),\n                                         src_state.size())\n                         * ConstColVectorView(src_state.data(), src_state.size());\n    }\n\n    void Configure(const multi_array::ConstArraySlice<TReal>& parameters) override {\n      if (parameters.size() != all2all_type::parameter_count_) {\n        std::cerr << \"parameter size: \" << parameters.size() << std::endl;\n        std::cerr << \"parameter count: \" << all2all_type::parameter_count_ << std::endl;\n        throw std::invalid_argument(\"Wrong number of parameters\");\n      }\n      for (Index iii = 0; iii < parameters.size(); ++iii) {\n        weights_[iii] = parameters[iii];\n      }\n      all2all_type::weight_view_ = multi_array::ConstArraySlice<TReal>(weights_.data(), 0,\n                                                         weights_.size());\n    }\n\n    void UpdateWeights(const TReal reward,\n                       const TReal reward_average,\n                       const multi_array::Tensor<TReal>& src_state,\n                       const multi_array::Tensor<TReal>& tar_state,\n                       const multi_array::Tensor<TReal>& tar_state_averages) override {\n\n      ConstColVectorView src_view(src_state.data(), src_state.size());\n      ConstColVectorView tar_view(tar_state.data(), tar_state.size());\n      ConstColVectorView tar_avg_view(tar_state_averages.data(), tar_state_averages.size());\n      MatrixView weight_view(weights_.data(), tar_state.size(), src_state.size());\n      const TReal reward_modulated_learning_factor = (reward - reward_average)\n                                                   * reward_modulator_type::learning_rate_;\n      for (Index s = 0; s < src_state.size(); ++s) {\n        for (Index t = 0; t < tar_state.size(); ++t) {\n          weight_view(t, s) += src_view(s)\n                               * (tar_view(t) - tar_avg_view(t))\n                               * reward_modulated_learning_factor;\n        }\n      }\n    }\n\n    const multi_array::Tensor<TReal>& GetWeights() const\n    {\n      return weights_;\n    }\n\n  protected:\n    multi_array::Tensor<TReal> weights_;\n};\n\ntemplate <typename TReal>\nclass RewardModulatedRecurrentIntegrator : public RecurrentEigenIntegrator<TReal>,\n                                           public RewardModulatedIntegrator<TReal> {\n  public:\n    typedef RecurrentEigenIntegrator<TReal> recurrent_type;\n    typedef RewardModulatedIntegrator<TReal> reward_modulator_type;\n    typedef typename recurrent_type::Index Index;\n    typedef typename recurrent_type::ColVector ColVector;\n    typedef typename recurrent_type::ColVectorView ColVectorView;\n    typedef typename recurrent_type::ConstColVector ConstColVector;\n    typedef typename recurrent_type::ConstColVectorView ConstColVectorView;\n    typedef typename recurrent_type::SparseMatrix SparseMatrix;\n    typedef typename Eigen::Map<SparseMatrix> SparseMatrixView;\n    typedef typename recurrent_type::ConstSparseMatrix ConstSparseMatrix;\n    typedef typename recurrent_type::ConstSparseMatrixView ConstSparseMatrixView;\n\n    RewardModulatedRecurrentIntegrator(SparseMatrix network, const TReal learning_rate)\n        : recurrent_type(network), reward_modulator_type(learning_rate),\n          weights_({recurrent_type::parameter_count_}) {\n      recurrent_type::integrator_type_ = REWARD_MODULATED;\n    }\n\n    void operator()(const multi_array::Tensor<TReal>& src_state,\n                    multi_array::Tensor<TReal>& tar_state) override {\n\n      if ((recurrent_type::network_.cols() != src_state.size())\n          && (recurrent_type::network_.rows() != tar_state.size())) {\n        throw std::invalid_argument(\"src state size and tar state size \"\n                                    \"incompatible with network\");\n      }\n\n      ConstSparseMatrixView weight_matrix(recurrent_type::network_.rows(),\n                                          recurrent_type::network_.cols(),\n                                          weights_.size(),\n                                          recurrent_type::network_.outerIndexPtr(),\n                                          recurrent_type::network_.innerIndexPtr(),\n                                          weights_.data(),\n                                          recurrent_type::network_.innerNonZeroPtr());\n      ColVectorView output_vector(tar_state.data(), tar_state.size());\n      ConstColVectorView src_vector(src_state.data(), src_state.size());\n\n      output_vector.noalias() = weight_matrix * src_vector;\n    }\n\n    void Configure(const multi_array::ConstArraySlice<TReal>& parameters) override {\n      if (parameters.size() != recurrent_type::parameter_count_) {\n        std::cerr << \"parameter size: \" << parameters.size() << std::endl;\n        std::cerr << \"parameter count: \" << recurrent_type::parameter_count_ << std::endl;\n        throw std::invalid_argument(\"Wrong number of parameters\");\n      }\n\n      for (Index iii = 0; iii < parameters.size(); ++iii) {\n        weights_[iii] = parameters[iii];\n      }\n      recurrent_type::weight_view_ = multi_array::ConstArraySlice<TReal>(weights_.data(), 0,\n                                                         weights_.size());\n    }\n\n    void UpdateWeights(const TReal reward,\n                       const TReal reward_average,\n                       const multi_array::Tensor<TReal>& src_state,\n                       const multi_array::Tensor<TReal>& tar_state,\n                       const multi_array::Tensor<TReal>& tar_state_averages) override {\n\n      SparseMatrixView weight_matrix(recurrent_type::network_.rows(),\n                                     recurrent_type::network_.cols(),\n                                     weights_.size(),\n                                     recurrent_type::network_.outerIndexPtr(),\n                                     recurrent_type::network_.innerIndexPtr(),\n                                     weights_.data(),\n                                     recurrent_type::network_.innerNonZeroPtr());\n      ConstColVectorView src_view(src_state.data(), src_state.size());\n      ConstColVectorView tar_view(tar_state.data(), tar_state.size());\n      ConstColVectorView tar_avg_view(tar_state_averages.data(), tar_state_averages.size());\n      const TReal reward_modulated_learning_factor = (reward - reward_average)\n                                                     * reward_modulator_type::learning_rate_;\n      for (Index s = 0; s < weight_matrix.outerSize(); ++s) {\n        for (typename SparseMatrixView::InnerIterator it(weight_matrix, s); it; ++it) {\n          it.valueRef() += src_view(s)\n                           * (tar_view(it.row()) - tar_avg_view(it.row()))\n                           * reward_modulated_learning_factor;\n        }\n      }\n    }\n\n    const multi_array::Tensor<TReal>& GetWeights() const override\n    {\n      return weights_;\n    }\n\n  protected:\n    multi_array::Tensor<TReal> weights_;\n};\n\n} // End nervous_system namespace\n\n#endif /* NN_INTEGRATOR_H_ */", "meta": {"hexsha": "c5682e943cbf64225e8186ff76784a25506c8d77", "size": 56751, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "alectrnn/nervous_system/integrator.hpp", "max_stars_repo_name": "neuro-evolution/alectrnn", "max_stars_repo_head_hexsha": "f39476b6eb3f4270c5f7f2f93ebcc5940b9c39e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "alectrnn/nervous_system/integrator.hpp", "max_issues_repo_name": "neuro-evolution/alectrnn", "max_issues_repo_head_hexsha": "f39476b6eb3f4270c5f7f2f93ebcc5940b9c39e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 33.0, "max_issues_repo_issues_event_min_datetime": "2018-03-30T03:18:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-14T05:13:17.000Z", "max_forks_repo_path": "alectrnn/nervous_system/integrator.hpp", "max_forks_repo_name": "Nathaniel-Rodriguez/alectrnn", "max_forks_repo_head_hexsha": "f39476b6eb3f4270c5f7f2f93ebcc5940b9c39e4", "max_forks_repo_licenses": ["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.0584218513, "max_line_length": 145, "alphanum_fraction": 0.6263854381, "num_tokens": 12971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.23729367966491227}}
{"text": "#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <boost/dynamic_bitset.hpp>\n#include <cassert>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"type.hpp\"\n#include \"utility.hpp\"\n#ifdef _USE_GPU\n#include <gpusim/stat_ops.h>\n#endif\n\n#include <csim/stat_ops.hpp>\n#include <csim/stat_ops_dm.hpp>\n\n#include \"gate_factory.hpp\"\n#include \"pauli_operator.hpp\"\n#include \"state.hpp\"\n\nPauliOperator::PauliOperator(std::string strings, CPPCTYPE coef) : _coef(coef) {\n    std::stringstream ss(strings);\n    std::string pauli_str;\n    UINT index, pauli_type = 0;\n    while (!ss.eof()) {\n        ss >> pauli_str >> index;\n        if (pauli_str.length() == 0) break;\n        if (pauli_str == \"I\" || pauli_str == \"i\")\n            pauli_type = 0;\n        else if (pauli_str == \"X\" || pauli_str == \"x\")\n            pauli_type = 1;\n        else if (pauli_str == \"Y\" || pauli_str == \"y\")\n            pauli_type = 2;\n        else if (pauli_str == \"Z\" || pauli_str == \"z\")\n            pauli_type = 3;\n        else {\n            fprintf(stderr, \"invalid Pauli string is given : %s\\n \",\n                pauli_str.c_str());\n            assert(false);\n        }\n        if (pauli_type != 0) this->add_single_Pauli(index, pauli_type);\n    }\n}\n\nPauliOperator::PauliOperator(const std::vector<UINT>& target_qubit_list,\n    std::string Pauli_operator_type_list, CPPCTYPE coef)\n    : _coef(coef) {\n    UINT term_count = (UINT)(strlen(Pauli_operator_type_list.c_str()));\n    UINT pauli_type = 0;\n    for (UINT term_index = 0; term_index < term_count; ++term_index) {\n        if (Pauli_operator_type_list[term_index] == 'i' ||\n            Pauli_operator_type_list[term_index] == 'I') {\n            pauli_type = 0;\n        } else if (Pauli_operator_type_list[term_index] == 'x' ||\n                   Pauli_operator_type_list[term_index] == 'X') {\n            pauli_type = 1;\n        } else if (Pauli_operator_type_list[term_index] == 'y' ||\n                   Pauli_operator_type_list[term_index] == 'Y') {\n            pauli_type = 2;\n        } else if (Pauli_operator_type_list[term_index] == 'z' ||\n                   Pauli_operator_type_list[term_index] == 'Z') {\n            pauli_type = 3;\n        } else {\n            fprintf(stderr, \"invalid Pauli string is given\\n\");\n            assert(false);\n        }\n\n        if (pauli_type != 0)\n            this->add_single_Pauli(target_qubit_list[term_index], pauli_type);\n    }\n}\n\nPauliOperator::PauliOperator(const std::vector<UINT>& pauli_list, CPPCTYPE coef)\n    : _coef(coef) {\n    for (UINT term_index = 0; term_index < pauli_list.size(); ++term_index) {\n        if (pauli_list[term_index] != 0)\n            this->add_single_Pauli(term_index, pauli_list[term_index]);\n    }\n}\n\nPauliOperator::PauliOperator(const std::vector<UINT>& target_qubit_index_list,\n    const std::vector<UINT>& target_qubit_pauli_list, CPPCTYPE coef)\n    : _coef(coef) {\n    assert(target_qubit_index_list.size() == target_qubit_pauli_list.size());\n    for (UINT term_index = 0; term_index < target_qubit_index_list.size();\n         ++term_index) {\n        this->add_single_Pauli(target_qubit_index_list[term_index],\n            target_qubit_pauli_list[term_index]);\n    }\n}\n\nPauliOperator::PauliOperator(const boost::dynamic_bitset<>& x,\n    const boost::dynamic_bitset<>& z, CPPCTYPE coef) {\n    _coef = coef;\n    for (UINT i = 0; i < x.size(); i++) {\n        UINT pauli_type = 0;\n        if (x[i] && !z[i]) {\n            pauli_type = 1;\n        } else if (x[i] && z[i]) {\n            pauli_type = 2;\n        } else if (!x[i] && z[i]) {\n            pauli_type = 3;\n        }\n        if (pauli_type != 0) {\n            this->add_single_Pauli(i, pauli_type);\n        }\n    }\n}\n\nvoid PauliOperator::add_single_Pauli(UINT qubit_index, UINT pauli_type) {\n    this->_pauli_list.push_back(SinglePauliOperator(qubit_index, pauli_type));\n    while (_x.size() <= qubit_index) {\n        _x.resize(_x.size() * 2 + 1);\n        _z.resize(_z.size() * 2 + 1);\n    }\n    if (pauli_type == 1) {\n        _x.set(qubit_index);\n    } else if (pauli_type == 2) {\n        _x.set(qubit_index);\n        _z.set(qubit_index);\n    } else if (pauli_type == 3) {\n        _z.set(qubit_index);\n    }\n}\n\nCPPCTYPE PauliOperator::get_expectation_value(\n    const QuantumStateBase* state) const {\n    if (state->is_state_vector()) {\n#ifdef _USE_GPU\n        if (state->get_device_name() == \"gpu\") {\n            return _coef *\n                   expectation_value_multi_qubit_Pauli_operator_partial_list_host(\n                       this->get_index_list().data(),\n                       this->get_pauli_id_list().data(),\n                       (UINT)this->get_index_list().size(), state->data(),\n                       state->dim, state->get_cuda_stream(),\n                       state->device_number);\n        } else {\n            return _coef *\n                   expectation_value_multi_qubit_Pauli_operator_partial_list(\n                       this->get_index_list().data(),\n                       this->get_pauli_id_list().data(),\n                       (UINT)this->get_index_list().size(), state->data_c(),\n                       state->dim);\n        }\n#else\n        return _coef *\n               expectation_value_multi_qubit_Pauli_operator_partial_list(\n                   this->get_index_list().data(),\n                   this->get_pauli_id_list().data(),\n                   (UINT)this->get_index_list().size(), state->data_c(),\n                   state->dim);\n#endif\n    } else {\n        return _coef *\n               dm_expectation_value_multi_qubit_Pauli_operator_partial_list(\n                   this->get_index_list().data(),\n                   this->get_pauli_id_list().data(),\n                   (UINT)this->get_index_list().size(), state->data_c(),\n                   state->dim);\n    }\n}\n\nCPPCTYPE PauliOperator::get_transition_amplitude(\n    const QuantumStateBase* state_bra,\n    const QuantumStateBase* state_ket) const {\n    if ((!state_bra->is_state_vector()) || (!state_ket->is_state_vector())) {\n        std::cerr\n            << \"get_transition_amplitude for density matrix is not implemented\"\n            << std::endl;\n    }\n#ifdef _USE_GPU\n    if (state_ket->get_device_name() == \"gpu\" &&\n        state_bra->get_device_name() == \"gpu\") {\n        return _coef *\n               (CPPCTYPE)\n                   transition_amplitude_multi_qubit_Pauli_operator_partial_list_host(\n                       this->get_index_list().data(),\n                       this->get_pauli_id_list().data(),\n                       (UINT)this->get_index_list().size(), state_bra->data(),\n                       state_ket->data(), state_bra->dim,\n                       state_ket->get_cuda_stream(), state_ket->device_number);\n    } else {\n        return _coef *\n               (CPPCTYPE)\n                   transition_amplitude_multi_qubit_Pauli_operator_partial_list(\n                       this->get_index_list().data(),\n                       this->get_pauli_id_list().data(),\n                       (UINT)this->get_index_list().size(), state_bra->data_c(),\n                       state_ket->data_c(), state_bra->dim);\n    }\n#else\n    return _coef *\n           (CPPCTYPE)\n               transition_amplitude_multi_qubit_Pauli_operator_partial_list(\n                   this->get_index_list().data(),\n                   this->get_pauli_id_list().data(),\n                   (UINT)this->get_index_list().size(), state_bra->data_c(),\n                   state_ket->data_c(), state_bra->dim);\n#endif\n}\n\nPauliOperator* PauliOperator::copy() const {\n    auto pauli = new PauliOperator(this->_coef);\n    for (auto val : this->_pauli_list) {\n        pauli->add_single_Pauli(val.index(), val.pauli_id());\n    }\n    return pauli;\n}\n\nstd::string PauliOperator::get_pauli_string() const {\n    std::string res = \"\";\n    UINT size = _pauli_list.size();\n    UINT target_index, pauli_id;\n    if (size == 0) {\n        return \"I\";\n    }\n    for (UINT index = 0; index < size; index++) {\n        target_index = _pauli_list[index].index();\n        pauli_id = _pauli_list[index].pauli_id();\n        if (pauli_id == 0)\n            continue;\n        else if (pauli_id == 1)\n            res += \"X\";\n        else if (pauli_id == 2)\n            res += \"Y\";\n        else if (pauli_id == 3)\n            res += \"Z\";\n        res += \" \" + std::to_string(target_index) + \" \";\n    }\n    res.pop_back();\n    return res;\n}\n\nvoid PauliOperator::change_coef(CPPCTYPE new_coef) { _coef = new_coef; }\n\nPauliOperator PauliOperator::operator*(const PauliOperator& target) const {\n    CPPCTYPE bits_coef = 1.0;\n    CPPCTYPE I = 1.0i;\n    auto x = _x;\n    auto z = _z;\n    auto target_x = target.get_x_bits();\n    auto target_z = target.get_x_bits();\n    if (target_x.size() != _x.size()) {\n        ITYPE max_size = std::max(_x.size(), target_x.size());\n        x.resize(max_size);\n        z.resize(max_size);\n        target_x.resize(max_size);\n        target_z.resize(max_size);\n    }\n    ITYPE i;\n#pragma omp parallel for\n    for (i = 0; i < x.size(); i++) {\n        if (x[i] && !z[i]) {  // X\n            if (!target_x[i] && target_z[i]) {\n                bits_coef = bits_coef * -I;\n            } else if (target_x[i] && target_z[i]) {\n                bits_coef = bits_coef * I;\n            }\n        } else if (!x[i] && z[i]) {             // Z\n            if (target_x[i] && !target_z[i]) {  // X\n                bits_coef = bits_coef * -I;\n            } else if (target_x[i] && target_z[i]) {  // Y\n                bits_coef = bits_coef * I;\n            }\n        } else if (x[i] && z[i]) {              // Y\n            if (target_x[i] && !target_z[i]) {  // X\n                bits_coef = bits_coef * I;\n            } else if (!target_x[i] && target_z[i]) {  // Z\n                bits_coef = bits_coef * I;\n            }\n        }\n    }\n    PauliOperator res(\n        x ^ target_x, z ^ target_z, _coef * target.get_coef() * bits_coef);\n    return res;\n}\n\nPauliOperator PauliOperator::operator*(CPPCTYPE target) const {\n    PauliOperator res(_x, _z, _coef * target);\n    return res;\n}\n\nPauliOperator& PauliOperator::operator*=(const PauliOperator& target) {\n    _coef *= target.get_coef();\n    CPPCTYPE I = 1.0i;\n    auto target_x = target.get_x_bits();\n    auto target_z = target.get_z_bits();\n    ITYPE max_size = std::max(_x.size(), target_x.size());\n    if (target_x.size() != _x.size()) {\n        _x.resize(max_size);\n        _z.resize(max_size);\n        target_x.resize(max_size);\n        target_z.resize(max_size);\n    }\n    ITYPE i;\n#pragma omp parallel for\n    for (i = 0; i < _x.size(); i++) {\n        if (_x[i] && !_z[i]) {  // X\n            if (!target_x[i] && target_z[i]) {\n                _coef *= -I;\n            } else if (target_x[i] && target_z[i]) {\n                _coef *= I;\n            }\n        } else if (!_x[i] && _z[i]) {           // Z\n            if (target_x[i] && !target_z[i]) {  // X\n                _coef *= -I;\n            } else if (target_x[i] && target_z[i]) {  // Y\n                _coef *= I;\n            }\n        } else if (_x[i] && _z[i]) {            // Y\n            if (target_x[i] && !target_z[i]) {  // X\n                _coef *= I;\n            } else if (!target_x[i] && target_z[i]) {  // Z\n                _coef *= I;\n            }\n        }\n    }\n    auto x_bit = _x ^ target_x;\n    auto z_bit = _z ^ target_z;\n    _x.clear();\n    _z.clear();\n    _pauli_list.clear();\n    _x.resize(max_size);\n    _z.resize(max_size);\n#pragma omp parallel for\n    for (i = 0; i < x_bit.size(); i++) {\n        ITYPE pauli_type = 0;\n        if (x_bit[i] && !z_bit[i]) {\n            pauli_type = 1;\n        } else if (x_bit[i] && z_bit[i]) {\n            pauli_type = 2;\n        } else if (!x_bit[i] && z_bit[i]) {\n            pauli_type = 3;\n        }\n        if (pauli_type != 0) {\n            this->add_single_Pauli(i, pauli_type);\n        }\n    }\n    return *this;\n}\n\nPauliOperator& PauliOperator::operator*=(CPPCTYPE target) {\n    _coef *= target;\n    return *this;\n}\n\n// made by watle\nvoid PauliOperator::update_quantum_state(QuantumStateBase* instate) {\n    // PauliOperator　wo gate tosite kanngaeru\n    std::vector<UINT> index_list = this->get_index_list();\n    std::vector<UINT> pauli_list = this->get_pauli_id_list();\n    for (size_t ii = 0; ii < index_list.size(); ii++) {\n        if (pauli_list[ii] == 1) {\n            auto x_gate = gate::X(index_list[ii]);\n            x_gate->update_quantum_state(instate);\n            delete x_gate;\n        } else if (pauli_list[ii] == 2) {\n            auto y_gate = gate::Y(index_list[ii]);\n            y_gate->update_quantum_state(instate);\n            delete y_gate;\n        } else if (pauli_list[ii] == 3) {\n            auto z_gate = gate::Z(index_list[ii]);\n            z_gate->update_quantum_state(instate);\n            delete z_gate;\n        }\n    }\n    instate->multiply_coef(this->get_coef());\n    return;\n}\n", "meta": {"hexsha": "cd30cc4a0c3873b68bc35351a60356a90bb3b794", "size": 12914, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cppsim/pauli_operator.cpp", "max_stars_repo_name": "kodack64/qulacs-osaka", "max_stars_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cppsim/pauli_operator.cpp", "max_issues_repo_name": "kodack64/qulacs-osaka", "max_issues_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cppsim/pauli_operator.cpp", "max_forks_repo_name": "kodack64/qulacs-osaka", "max_forks_repo_head_hexsha": "4ccc3ff084f10942e22d8663a01ed67efd24d9f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2546419098, "max_line_length": 85, "alphanum_fraction": 0.5447576274, "num_tokens": 3449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23727422406245927}}
{"text": "//==============================================================================\n//          Copyright 2015 J.T.  Lapreste\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef BOOST_SIMD_BITWISE_FUNCTIONS_GENERIC_SWAPBYTES_HPP_INCLUDED\n#define BOOST_SIMD_BITWISE_FUNCTIONS_GENERIC_SWAPBYTES_HPP_INCLUDED\n\n#include <boost/simd/bitwise/functions/swapbytes.hpp>\n#include <boost/simd/include/functions/simd/shift_left.hpp>\n#include <boost/simd/include/functions/simd/shr.hpp>\n#include <boost/dispatch/attributes.hpp>\n\nnamespace boost { namespace simd { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT( swapbytes_, tag::cpu_\n                          , (A0)\n                          , (generic_< ints8_<A0> >)\n                          )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      return a0;\n    }\n  };\n  BOOST_DISPATCH_IMPLEMENT( swapbytes_, tag::cpu_\n                          , (A0)\n                          , (generic_< ints16_<A0> >)\n                          )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n     return shl(a0, 8)|shr(a0, 8);\n    }\n  };\n  BOOST_DISPATCH_IMPLEMENT( swapbytes_, tag::cpu_\n                          , (A0)\n                          , (generic_< type32_<A0> >)\n                          )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      result_type val = ((shl(a0, 8) & 0xFF00FF00 ) | (shr(a0, 8) & 0xFF00FF ));\n      return shl(val, 16) | shr(val,16);\n    }\n  };\n  BOOST_DISPATCH_IMPLEMENT( swapbytes_, tag::cpu_\n                          , (A0)\n                          , (generic_< type64_<A0> >)\n                          )\n  {\n    typedef A0 result_type;\n\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0) const\n    {\n      result_type val = (shl(a0, 8) & 0xFF00FF00FF00FF00ULL ) | (shr(a0, 8) & 0x00FF00FF00FF00FFULL );\n      val = (shl(val, 16) & 0xFFFF0000FFFF0000ULL ) | (shr(val, 16) & 0x0000FFFF0000FFFFULL );\n      return shl(val, 32) | shr(val,32);\n    }\n  };\n} } }\n\n#endif\n", "meta": {"hexsha": "7cdd9592c47fd84254dc9d2210c2aed55516a1c6", "size": 2345, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/bitwise/functions/generic/swapbytes.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/bitwise/functions/generic/swapbytes.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/bitwise/functions/generic/swapbytes.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 32.5694444444, "max_line_length": 102, "alphanum_fraction": 0.5292110874, "num_tokens": 587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2372742240624592}}
{"text": "// Copyright 2009-2010 Green Code LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <algorithm>\n#include <cmath>\n#include <iostream>\n\n#include <boost/foreach.hpp>\n#include <boost/make_shared.hpp>\n\n#include \"tpsdemo/linalg3d-double.h\"\n\n#include \"DisjointRegions.h\"\n#include \"Geometry3D.h\"\n#include \"Grid.h\"\n#include \"IPointVector.h\"\n#include \"LineIndent.h\"\n#include \"ProgressBar.h\"\n#include \"RasterSurface.h\"\n\nnamespace mcc\n{\n\n  DisjointRegions::DisjointRegions()\n    : iterationState_(RegionIteration_Done)  {\n  }\n\n  //---------------------------------------------------------------------------\n\n  const unsigned int desiredPtsPerRegion = 12;  // Default in ArcGIS Spline\n\n  //---------------------------------------------------------------------------\n\n  // Represents a point that's in a neighboring region.\n  struct NeighborPoint\n  {\n    const IPoint * point;\n    double distance;\n\n    NeighborPoint(const IPoint *             neighborPt,\n                  const CoordinateInterval & xInterval,\n                  const CoordinateInterval & yInterval)\n      : point(neighborPt)\n    {\n      // Compute distance from region specified by x and y intervals.\n      double xDistance = distanceToInterval(point->x(), xInterval);\n      double yDistance = distanceToInterval(point->y(), yInterval);\n      distance = std::max(xDistance, yDistance);\n    }\n\n    double distanceToInterval(Coordinate                 value,\n                              const CoordinateInterval & interval)\n    {\n      if (value < interval.lowerBound())\n        return interval.lowerBound() - value;\n      else if (interval.upperBound() < value)\n        return value - interval.upperBound();\n      else\n        return 0.0;\n    }\n\n    bool operator<(const NeighborPoint & rhs) const\n    {\n      return distance < rhs.distance;\n    }\n  };\n\n  //---------------------------------------------------------------------------\n\n  // Functor class for adding a neighbor point to a region's point list.\n  class AppendPoint\n  {\n    public:\n      AppendPoint(std::vector<const IPoint *> & points)\n        : points_(points)\n      {\n      }\n\n      void operator()(const NeighborPoint & neighbor) const\n      {\n        points_.push_back(neighbor.point);\n      }\n\n    private:\n      std::vector<const IPoint *> & points_;\n  };\n\n  //---------------------------------------------------------------------------\n\n  // Location of a cell's neighbor relative to the cell itself.\n  struct RelativeLocation\n  {\n    int rowOffset;\n    int columnOffset;\n\n    RelativeLocation(int rOffset,\n                     int cOffset)\n      : rowOffset(rOffset),\n        columnOffset(cOffset)\n    {\n    }\n\n    RelativeLocation & operator+=(const RelativeLocation & relLoc)\n    {\n      rowOffset += relLoc.rowOffset;\n      columnOffset += relLoc.columnOffset;\n      return *this;\n    }\n  };\n\n  //---------------------------------------------------------------------------\n\n  // Get the neighboring region to a particular region (specified by its cell).\n  // If the relative location of the neighbor is outside the grid of regions,\n  // 0 is returned.\n\n\n  const InterpolationRegion * getNeighbor(Grid<InterpolationRegion> &  regions,\n                                          const Cell &                 cell,\n                                          const RelativeLocation       neighborLocation)\n  {\n    long row = cell.row() + neighborLocation.rowOffset;\n    if (row < 0 || row >= (long) regions.rows())\n      return 0;\n    long column = cell.column() + neighborLocation.columnOffset;\n    if (column < 0 || column >= (long) regions.columns())\n      return 0;\n    return &(regions((unsigned int) row, (unsigned int) column));\n  }\n\n  //---------------------------------------------------------------------------\n\n  // Get points from the regions in the outermost ring of a region's\n  // neighborhood.  The ring is traversed in clock-wise order:\n  //\n  //   +---+---+---+---+---+\n  //   | P | A | B | C | D |\n  //   +---+---+---+---+---+\n  //   | O | 8 | 1 | 2 | E |\n  //   +---+---+---+---+---+\n  //   | N | 7 | * | 3 | F |\n  //   +---+---+---+---+---+\n  //   | M | 6 | 5 | 4 | G |\n  //   +---+---+---+---+---+\n  //   | L | K | J | I | H |\n  //   +---+---+---+---+---+\n  //\n  //  For the region marked \"*\" in the diagram above, if its neighborhood is\n  //  3x3, then the eight regions marked 1 to 8 are traversed.  If the\n  //  neighborhood is 5x5, then the regions marked \"A\" to \"P\" are traversed.\n  //\n  //  The points in the traversed neighbors are appended to the \"neighborPts\"\n  //  parameter.\n  void getPointsFromOuterRing(Grid<InterpolationRegion> &  regions,\n                              const Cell &                 cell,\n                              int                          neighborhoodSize,\n                              std::vector<NeighborPoint> & neighborPts)\n  {\n    CoordinateInterval xInterval = regions.getXInterval(cell.column()); // = cell.xInterval();\n    CoordinateInterval yInterval = regions.getYInterval(cell.row());    // = cell.yInterval();\n\n    RelativeLocation traverseRingAlongEdges[] = {\n      RelativeLocation( 0,       right(1) ),  // top edge, left to right\n      RelativeLocation( down(1), 0        ),  // right edge, top to bottom\n      RelativeLocation( 0,       left(1)  ),  // bottom edge, right to left\n      RelativeLocation( up(1),   0        ),  // left edge, bottom to top\n    };\n\n    // The upper left cell in current neighborhood ring\n    int neighborhoodRadius = (neighborhoodSize - 1) / 2;\n    RelativeLocation neighborLocation(up(neighborhoodRadius), left(neighborhoodRadius));\n\n    int nCellsPerEdge = neighborhoodSize - 1;\n\n    BOOST_FOREACH(const RelativeLocation & locOfNextNeighborAlongEdge, traverseRingAlongEdges) {\n      for (int i = 0; i < nCellsPerEdge; ++i) {\n        neighborLocation += locOfNextNeighborAlongEdge;\n        const InterpolationRegion * neighbor = getNeighbor(regions, cell, neighborLocation);\n        if (neighbor) {\n          BOOST_FOREACH(const IPoint * point, neighbor->pts) {\n            neighborPts.push_back(NeighborPoint(point, xInterval, yInterval));\n          }\n        }\n      }\n    }\n  }\n\n  //---------------------------------------------------------------------------\n\n  int DisjointRegions::subdivide(const IPointVector &  points,\n                                 PointSelector         pointSelector,\n                                 const RasterSurface & raster)\n  {\n    // Subdivide the raster's area into non-overlapping regions.  The goal is\n    // to have approximately the same # of points in each region.\n\n    int desiredNumRegions = points.count() / desiredPtsPerRegion;\n      // Rounding down because one less region means possibly more pts per\n      // region.\n\n    double rasterHeight = raster.rows() * raster.cellSize();\n    double rasterWidth = raster.columns() * raster.cellSize();\n    double rasterArea = rasterHeight * rasterWidth;\n    double desiredRegionArea = rasterArea / desiredNumRegions;\n\n    // The size of a region if it was the optimal shape = square\n    double desiredRegionSize = std::sqrt(desiredRegionArea);\n\n    // But the desired region size is not guaranteed to divide both the height\n    // and width of the raster evenly.  So stretch the regions' heights and\n    // widths until they evenly divide the raster's height and width,\n    // respectively.  Stretching ensures that regions do not lose points.  The\n    // resulting region shape is likely not to be square.\n    int nRows = int(std::floor(rasterHeight / desiredRegionSize));\r\n\tif (nRows > int(raster.rows())){\r\n\t\tnRows = int(raster.rows());\n\t}\n    double regionHeight = rasterHeight / nRows;\n\n    int nColumns = int(std::floor(rasterWidth / desiredRegionSize));\r\n\tif (nColumns > int(raster.columns())){\r\n\t\tnColumns = int(raster.columns());\n\t}\n    double regionWidth = rasterWidth / nColumns;\n\n    // Create the 2-d arry of InterpolationRegion (nRows, nColumns)\n    regions_ = boost::make_shared< Grid<InterpolationRegion> >(nRows, nColumns, raster.lowerLeft(),\n                                                               Coordinate(regionHeight),\n                                                               Coordinate(regionWidth));\n\n    LineIndent indent(\"  \");\n\n    // Sort points into the regions\n    BOOST_FOREACH(const IPoint & point, points) {\n      Cell cell = regions_->getCell(point.x(), point.y());\n      if ((*pointSelector)(point))\n        (*regions_)[cell].pts.push_back(& point);\n      else\n        (*regions_)[cell].nPtsNotSelected++;\n    }\n\n    // Determine the cell block for each region.\n    int regionRow = regions_->topRow();\n    Coordinate regionRow_minY = regions_->getYInterval(regionRow).lowerBound();\n    BOOST_FOREACH(unsigned int rasterRow, raster.topToBottom()) {\n      // If first (top) row, then scan across cell columns computing widths of\n      // cell blocks.\n      if (rasterRow == raster.topRow()) {\n          const unsigned int regionTopRow = regions_->topRow();\n          unsigned int regionColumn = regions_->leftColumn();\n          InterpolationRegion * currentRegion = &( (*regions_)(regionTopRow, regionColumn) );\n          Coordinate currentRegion_maxX = regions_->getXInterval(regionColumn).upperBound();\n          BOOST_FOREACH(unsigned int rasterColumn, raster.leftToRight()) {\n            Cell cell = raster.getCell(raster.topRow(), rasterColumn);\n            if (rasterColumn == raster.leftColumn()) {\n              currentRegion->cellBlock = CellBlock(cell /* upperLeft */);  // cell block height and width = 1\n            }\n            else if (cell.x() < currentRegion_maxX) {\n              // The cell is in the current region, so increment the cell\n              // block's width.\n              currentRegion->cellBlock.width += 1;\n            } else {\n              // We've moved right into a new region.\n              regionColumn += right(1);\n              currentRegion = &( (*regions_)(regionTopRow, regionColumn) );\n              currentRegion->cellBlock = CellBlock(cell /* upperLeft */);  // cell block height and width = 1\n              currentRegion_maxX = regions_->getXInterval(regionColumn).upperBound();\n            }\n          }\n      } else {\n        // Current raster row is not the top row.  So two possibilities:\n        //   A) the centers of the current row's cells are in the current\n        //      region row, or\n        //   B) the current row's cells in the next lower region row\n        Cell leftMostCell = raster.getCell(rasterRow, raster.leftColumn());\n        if (leftMostCell.y() > regionRow_minY) {\n          // Case (A) - still in current region row, so go through the regions\n          // on the current region row, and increment their cell block heights.\n          BOOST_FOREACH(unsigned int regionColumn, regions_->leftToRight()) {\n            (*regions_)(regionRow, regionColumn).cellBlock.height += 1;\n          }\n        } else {\n          // Case (B) - moved down into new region row, so scan across region\n          // columns, copying the cell block widths from the regions in the\n          // top region row into their corresponding regions of the current\n          // region row.\n          regionRow += down(1);\n          regionRow_minY = regions_->getYInterval(regionRow).lowerBound();\n          BOOST_FOREACH(unsigned int regionColumn, regions_->leftToRight()) {\n            const InterpolationRegion & correspondingRegionInTopRow = (*regions_)(regions_->topRow(), regionColumn);\n            int upperLeftCell_column = correspondingRegionInTopRow.cellBlock.upperLeftCell.column();\n\n            CellBlock & currentRegion_cellBlock = (*regions_)(regionRow, regionColumn).cellBlock;\n            currentRegion_cellBlock.upperLeftCell = raster.getCell(rasterRow, upperLeftCell_column);\n            currentRegion_cellBlock.height = 1;\n            currentRegion_cellBlock.width = correspondingRegionInTopRow.cellBlock.width;\n          }\n        }  // else Case (B)\n      }  // else current raster row not top row\n    }  // for each raster row\n\n    iterationState_ = RegionIteration_Initialized;\n    raster_ = &(raster);\n\n    return nRows * nColumns;\n  }\n\n  const Cell* DisjointRegions::getNextCell()\n  {\n    switch (iterationState_) {\n      case RegionIteration_Initialized :\n        // Return the upper left region\n        currentRegionRow_ = regions_->topRow();\n        currentRegionColumn_ = regions_->leftColumn();\n        iterationState_ = RegionIteration_InProgress;\n        break;\n\n      case RegionIteration_InProgress :\n        // Advance to next cell in row major order\n        if (currentRegionColumn_ != regions_->rightColumn())\n          currentRegionColumn_ += right(1);\n        else {\n          // Advance to next row\n          if (currentRegionRow_ != regions_->bottomRow()) {\n            currentRegionRow_ += down(1);\n            currentRegionColumn_ = regions_->leftColumn();\n          } else {\n            iterationState_ = RegionIteration_Done;\n            return 0;\n          }\n        }\n        break;\n\n      default :\n        assert(iterationState_ == RegionIteration_Done);\n        return 0;\n    }\n\n    return new Cell(regions_->getCell(currentRegionRow_, currentRegionColumn_));\n\n  }\n\n  const InterpolationRegion * DisjointRegions::getRegionForCell(const Cell *cell)\n  {\n    unsigned int row = cell->row();\n    unsigned int column = cell->column();\n\n    return &( (*regions_)(row, column) );\n\n  }\n\n    //---------------------------------------------------------------------------\n\n  void addNeighborPointsToRegionWithCell(Grid<InterpolationRegion> &  regions,\n\t\t  const Cell & cell, std::vector<const IPoint *> &points, int nPoints,\n    int &indexNextAvailableNeighbor, std::vector<NeighborPoint> &neighborPts,\n    int &neighborhoodSize, int &nPointsLeftInOuterRing)\n  {\n    while (nPoints > 0) {\n      while (nPointsLeftInOuterRing == 0) {\n        // Expand the neighborhood, and get points from the new outer ring.\n        neighborPts.clear();\n        neighborhoodSize += 2;  // first 3x3, then 5x5, 7x7, ...\n        getPointsFromOuterRing(regions, cell, neighborhoodSize, neighborPts);\n        nPointsLeftInOuterRing = neighborPts.size();\n        std::sort(neighborPts.begin(), neighborPts.begin());\n        indexNextAvailableNeighbor = 0;\n      }\n\n      int nPtsToAdd = (nPointsLeftInOuterRing < nPoints) ? nPointsLeftInOuterRing : nPoints;\n      std::for_each(neighborPts.begin() + indexNextAvailableNeighbor,\n                    neighborPts.begin() + indexNextAvailableNeighbor + nPtsToAdd,\n                    AppendPoint(points));\n      indexNextAvailableNeighbor += nPtsToAdd;\n      nPointsLeftInOuterRing -= nPtsToAdd;\n      nPoints -= nPtsToAdd;\n    }\n  }\n\n  void DisjointRegions::getPointsAndCellsForCell(const Cell *cell, int nExtraPoints,\n    std::vector<const IPoint *> &points, std::vector<Cell> &cells)\n  {\n    const InterpolationRegion *region = getRegionForCell(cell);\n    points = region->pts;\n    int neighborhoodSize = 1;\n    std::vector<NeighborPoint> neighborPts;\n    neighborPts.clear();\n    int nPointsLeftInOuterRing = 0;\n    int indexNextAvailableNeighbor = 0;\n    unsigned int nSelectedPts = points.size();\n\n    while (nSelectedPts < desiredPtsPerRegion) {\n\n      addNeighborPointsToRegionWithCell(*regions_, *cell, points, desiredPtsPerRegion - nSelectedPts,\n        indexNextAvailableNeighbor, neighborPts, neighborhoodSize, nPointsLeftInOuterRing);\n      nSelectedPts = points.size();\n\n    }\n\n    if(nExtraPoints > 0) {\n      addNeighborPointsToRegionWithCell(*regions_, *cell, points, nExtraPoints,indexNextAvailableNeighbor,\n        neighborPts, neighborhoodSize, nPointsLeftInOuterRing);\n    }\n\n    cells.clear();\n    const CellBlock & cellBlock = region->cellBlock;\n    const Cell & upperLeftCell = cellBlock.upperLeftCell;\n    unsigned int blockTop    = upperLeftCell.row();\n    unsigned int blockBottom = blockTop + down(cellBlock.height - 1);\n    unsigned int blockLeft   = upperLeftCell.column();\n    unsigned int blockRight  = blockLeft + right(cellBlock.width - 1);\n\n    BOOST_FOREACH(unsigned int row, Sequence<unsigned int>(blockTop, blockBottom)) {\n      BOOST_FOREACH(unsigned int column, Sequence<unsigned int>(blockLeft, blockRight)) {\n        cells.push_back(raster_->getCell(row, column));\n      }\n    }\n  }\n\n}\n", "meta": {"hexsha": "0af70966458f81738afb20b4557a769266ff4eab", "size": 16729, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libmcc_lidar/DisjointRegions.cpp", "max_stars_repo_name": "rmsare/pymcc", "max_stars_repo_head_hexsha": "a41e52f97bf6ce8e4012576b296b71e89d0ff240", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-07-20T10:09:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-17T14:12:00.000Z", "max_issues_repo_path": "libmcc_lidar/DisjointRegions.cpp", "max_issues_repo_name": "rmsare/pymcc", "max_issues_repo_head_hexsha": "a41e52f97bf6ce8e4012576b296b71e89d0ff240", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-02-25T00:30:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-10T17:32:48.000Z", "max_forks_repo_path": "libmcc_lidar/DisjointRegions.cpp", "max_forks_repo_name": "rmsare/pymcc", "max_forks_repo_head_hexsha": "a41e52f97bf6ce8e4012576b296b71e89d0ff240", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T19:46:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-27T19:46:11.000Z", "avg_line_length": 38.724537037, "max_line_length": 116, "alphanum_fraction": 0.6097196485, "num_tokens": 3727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.23727422406245918}}
{"text": "// Copyright 2014-2015 SDL plc\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//     http://www.apache.org/licenses/LICENSE-2.0\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n/** \\file\n\n    semirings used for Arc for Hypergraph.\n*/\n\n\n#ifndef HYP__HYPERGRAPH_WEIGHT_HPP\n#define HYP__HYPERGRAPH_WEIGHT_HPP\n#pragma once\n\n/**\n   Weight: semiring (zero, one, plus, times, less,==).\n\n   note: some more expensive semirings' zero and one will not be usable until\n   main() (static globals). singleton lazy-init pattern not worth the overhead.\n*/\n\n#include <sdl/Hypergraph/Exception.hpp>\n#include <sdl/Hypergraph/Types.hpp>\n#include <sdl/Hypergraph/WeightBase.hpp>\n#include <sdl/Util/Constants.hpp>\n#include <sdl/Util/Hash.hpp>\n#include <sdl/Util/LogHelper.hpp>\n#include <sdl/Util/LogMath.hpp>\n#include <sdl/Util/Math.hpp>\n#include <sdl/LexicalCast.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n\n#if HAVE_OPENFST\n// OpenFst weight compatability - needed for ToReplaceFst\n#define DEFINE_OPENFST_COMPAT_FUNCTIONS(name)            \\\n  static std::string const& Type() {                     \\\n    static std::string const r(#name);                   \\\n    return r;                                            \\\n  }                                                      \\\n  static const Self One() { return Self::one(); }        \\\n  static const Self Zero() { return Self::zero(); }      \\\n  void Write(std::ostream& o) const { o << *this; }      \\\n  static inline std::size_t Properties() { return 0x3; } \\\n  typedef Self ReverseWeight;                            \\\n  Self& Reverse() { return *this; }                      \\\n  Self const& Reverse() const { return *this; }\n#else\n#define DEFINE_OPENFST_COMPAT_FUNCTIONS(name)\n#endif\n\n#define SDL_DEFINE_FLOATWT_CMP(c, cmp)                \\\n  template <class T>                                  \\\n  bool operator cmp(c<T> const& w1, c<T> const& w2) { \\\n    return w1.value_ cmp w2.value_;                   \\\n  }\n\n#define SDL_DEFINE_FLOATWT_CMPS(c) \\\n  SDL_DEFINE_FLOATWT_CMP(c, ==)    \\\n  SDL_DEFINE_FLOATWT_CMP(c, >=)    \\\n  SDL_DEFINE_FLOATWT_CMP(c, <=)    \\\n  SDL_DEFINE_FLOATWT_CMP(c, !=)    \\\n  SDL_DEFINE_FLOATWT_CMP(c, <)     \\\n  SDL_DEFINE_FLOATWT_CMP(c, >)\n\n// TODO: #if HAVE_OPENFST and use constants appropriate for particular semiring - this is just to compile\n// HgFsmDraw\n\n// TODO: OpenFst Divide. use sdl::Util::logPlus?\n\nnamespace sdl {\nnamespace Hypergraph {\n\n/**\n   Simple wrapper weight around a float value. Base class for\n   Viterbi weight, Log weight, etc.\n */\ntemplate <class T>\nclass FloatWeightTpl : public WeightBase {\n protected:\n  typedef typename Util::OtherFloat<T>::type DoubleT;\n\n public:\n  typedef T FloatT;\n\n  static inline constexpr FloatT kOneValue() { return 0; }\n  // TODO: C++11 constexpr\n  static inline constexpr FloatT kZeroValue() { return std::numeric_limits<T>::infinity(); }\n\n  typedef void HasIsZero;\n  bool isZero() const { return value_ == std::numeric_limits<T>::infinity(); }\n  friend inline void setZero(FloatWeightTpl& x) { x.value_ = std::numeric_limits<T>::infinity(); }\n\n  typedef void HasIsOne;\n  bool isOne() const { return !value_; }\n  friend inline void setOne(FloatWeightTpl& x) { x.value_ = 0; }\n\n  /// uninitialized - we want users to explicitly init to zero or one as\n  /// appropriate e.g. vector<ViterbiWeight>(N, ViterbiWeight::zero())\n  constexpr FloatWeightTpl() = default;  // uninitialized but an explicit weight() init would then 0-init?\n  constexpr FloatWeightTpl(T v) : value_(v) {}\n  constexpr FloatWeightTpl(DoubleT v) : value_((T)v) {}\n  constexpr FloatWeightTpl(int v) : value_((T)v) {}\n  constexpr FloatWeightTpl(std::size_t v) : value_((T)v) {}\n\n  FloatWeightTpl(FloatWeightTpl const& o) = default;\n  FloatWeightTpl& operator=(FloatWeightTpl const& o) = default;\n  FloatWeightTpl(FloatWeightTpl&& o) = default;\n  FloatWeightTpl& operator=(FloatWeightTpl&& o) = default;\n\n  T& value() { return value_; }\n\n  T getValue() const { return value_; }\n\n  void set(std::string const& s) { value_ = sdl::lexical_cast<T>(s); }\n\n  T value_;\n};\n\nSDL_DEFINE_FLOATWT_CMPS(FloatWeightTpl)\n\ntemplate <class T>\nstd::istream& operator>>(std::istream& i, FloatWeightTpl<T>& x) {\n  return i >> x.value();\n}\ntemplate <class T>\nstd::ostream& operator<<(std::ostream& o, FloatWeightTpl<T> const& x) {\n  return o << x.value_;\n}\n\ntemplate <class T>\ninline std::size_t hashWeight(FloatWeightTpl<T> const& w) {\n  return Util::hashFloat(w.value_);\n}\n\ntemplate <class T>\ninline bool approxEqual(FloatWeightTpl<T> const& w1, FloatWeightTpl<T> const& w2,\n                        T epsilon = FloatConstants<T>::epsilon) {\n  return Util::floatEqual(w1.value_, w2.value_, epsilon);\n}\n\ntemplate <class T>\ninline bool approxGreaterOrEqual(FloatWeightTpl<T> const& w1, FloatWeightTpl<T> const& w2,\n                                 T epsilon = FloatConstants<T>::epsilon) {\n  return Util::approxGreaterOrEqual(w1.value_, w2.value_, epsilon);\n}\n\ntemplate <class T>\ninline bool approxLessOrEqual(FloatWeightTpl<T> const& w1, FloatWeightTpl<T> const& w2,\n                              T epsilon = FloatConstants<T>::epsilon) {\n  return Util::approxLessOrEqual(w1.value_, w2.value_, epsilon);\n}\n\ntemplate <class T>\ninline bool definitelyGreater(FloatWeightTpl<T> const& w1, FloatWeightTpl<T> const& w2,\n                              T epsilon = FloatConstants<T>::epsilon) {\n  return Util::definitelyGreater(w1.value_, w2.value_, epsilon);\n}\n\ntemplate <class T>\ninline bool definitelyLess(FloatWeightTpl<T> const& w1, FloatWeightTpl<T> const& w2,\n                           T epsilon = FloatConstants<T>::epsilon) {\n  return Util::definitelyLess(w1.value_, w2.value_, epsilon);\n}\n\n// all 3 of approx equal, greater, less may be true simultaneously (if same eps, then approxEqual <=>\n// approxGreater and approxLess\n\nclass BooleanWeight : public FloatWeightTpl<bool> {\n public:\n  typedef bool FloatT;\n\n  BooleanWeight() : FloatWeightTpl<bool>() {}\n  static inline constexpr bool kOneValue() { return 1; }\n  static inline constexpr bool kZeroValue() { return 0; }\n\n  // explicit only because somebody was wrongly activating this implicitly (they should use safe_bool idiom?)\n  explicit constexpr BooleanWeight(bool v) : FloatWeightTpl<bool>(v) {}\n\n  typedef BooleanWeight Self;\n  DEFINE_OPENFST_COMPAT_FUNCTIONS(Boolean)\n\n  typedef void HasIsOne;\n  bool isOne() const { return value_ == true; }\n  friend inline void setOne(BooleanWeight& x) { x.value_ = true; }\n  static inline constexpr BooleanWeight one() { return BooleanWeight(true); }\n\n  typedef void HasIsZero;\n  bool isZero() const { return value_ == false; }\n  friend inline void setZero(BooleanWeight& x) { x.value_ = false; }\n  static inline constexpr BooleanWeight zero() { return BooleanWeight(false); }\n};\n\ntemplate <class T>\nclass ViterbiWeightTpl : public FloatWeightTpl<T> {\n  typedef ViterbiWeightTpl<T> Self;\n  typedef FloatWeightTpl<T> Base;\n\n public:\n  typedef void HasIsZero;\n  bool isZero() const { return this->value_ == std::numeric_limits<T>::infinity(); }\n  typedef void HasIsOne;\n  bool isOne() const { return !this->value_; }\n\n  typedef T FloatT;\n\n  constexpr ViterbiWeightTpl() : Base() {}\n\n  constexpr ViterbiWeightTpl(T v) : Base(v) {}\n  constexpr ViterbiWeightTpl(int v) : Base(v) {}\n  constexpr ViterbiWeightTpl(std::size_t v) : Base(v) {}\n  constexpr ViterbiWeightTpl(typename Base::DoubleT v) : Base(v) {}\n\n  ViterbiWeightTpl(ViterbiWeightTpl const& o) = default;\n  ViterbiWeightTpl& operator=(ViterbiWeightTpl const& o) = default;\n  ViterbiWeightTpl(ViterbiWeightTpl&& o) = default;\n  ViterbiWeightTpl& operator=(ViterbiWeightTpl&& o) = default;\n\n  Self& operator=(Base const& other) {\n    this->value_ = other.value_;\n    return *this;\n  }\n\n  static inline constexpr ViterbiWeightTpl<T> one() { return ViterbiWeightTpl<T>(0.0f); }\n\n  static inline constexpr ViterbiWeightTpl<T> zero() {\n    return ViterbiWeightTpl<T>(std::numeric_limits<T>::infinity());\n  }\n\n  void plusBy(Self const& b) {\n    if (b.value_ < this->value_) this->value_ = b.value_;\n  }\n  typedef void HasPlusBy;\n\n  void timesBy(Self const& b) { this->value_ += b.value_; }\n  typedef void HasTimesBy;\n\n  DEFINE_OPENFST_COMPAT_FUNCTIONS(Viterbi)\n};\n\n\ntemplate <class T>\nViterbiWeightTpl<T> plus(ViterbiWeightTpl<T> const& w1, ViterbiWeightTpl<T> const& w2) {\n  return w1.value_ < w2.value_ ? w1 : w2;\n}\n\ntemplate <class T>\nViterbiWeightTpl<T> minus(ViterbiWeightTpl<T> const& w1, ViterbiWeightTpl<T> const& w2) {\n  SDL_THROW_LOG(Hypergraph, UnimplementedException, \"Viterbi minus is not supported\");\n  return w1;  // make compiler happy\n}\n\ntemplate <class T>\ninline ViterbiWeightTpl<T> times(ViterbiWeightTpl<T> const& w1, ViterbiWeightTpl<T> const& w2) {\n  if (w1 == ViterbiWeightTpl<T>::zero() || w2 == ViterbiWeightTpl<T>::zero())\n    return ViterbiWeightTpl<T>::zero();\n  return ViterbiWeightTpl<T>(w1.value_ + w2.value_);\n}\n\ntemplate <class T>\ninline bool less(ViterbiWeightTpl<T> const& w1, ViterbiWeightTpl<T> const& w2) {\n  return w1.value_ < w2.value_;\n}\n\ntemplate <class T>\ninline ViterbiWeightTpl<T> divide(ViterbiWeightTpl<T> const& w1, ViterbiWeightTpl<T> const& w2) {\n  if (w1 == ViterbiWeightTpl<T>::zero() || w2 == ViterbiWeightTpl<T>::zero())\n    // Technically can't divide by 0. but practically ok.\n    return ViterbiWeightTpl<T>::zero();\n  return ViterbiWeightTpl<T>(w1.value_ - w2.value_);\n}\n\ntemplate <class T>\ninline ViterbiWeightTpl<T> invert(ViterbiWeightTpl<T> const& w) {\n  return ViterbiWeightTpl<T>(-w.value_);\n}\n\ntemplate <class T>\ninline ViterbiWeightTpl<T> pow(ViterbiWeightTpl<T> const& w, T k) {\n  return ViterbiWeightTpl<T>(k * w.value_);\n}\n\ntemplate <class T>\nclass LogWeightTpl : public FloatWeightTpl<T> {\n\n  typedef FloatWeightTpl<T> Base;\n  typedef LogWeightTpl Self;\n\n public:\n  typedef void HasIsZero;\n  bool isZero() const { return this->value_ == std::numeric_limits<T>::infinity(); }\n\n  typedef void HasIsOne;\n  bool isOne() const { return !this->value_; }\n\n  typedef T FloatT;\n\n  constexpr LogWeightTpl() : Base() {}\n\n  constexpr LogWeightTpl(T v) : Base(v) {}\n  constexpr LogWeightTpl(typename Base::DoubleT v) : Base(v) {}\n  constexpr LogWeightTpl(int v) : Base(v) {}\n  constexpr LogWeightTpl(std::size_t v) : Base(v) {}\n  LogWeightTpl(LogWeightTpl const& o) = default;\n  LogWeightTpl& operator=(LogWeightTpl const& o) = default;\n  LogWeightTpl(LogWeightTpl&& o) = default;\n  LogWeightTpl& operator=(LogWeightTpl&& o) = default;\n\n  static inline constexpr LogWeightTpl<T> one() { return LogWeightTpl<T>(0.0f); }\n\n  static inline constexpr LogWeightTpl<T> zero() {\n    return LogWeightTpl<T>(std::numeric_limits<T>::infinity());\n  }\n\n  Self& operator=(Base const& other) {\n    this->value_ = other.value_;\n    return *this;\n  }\n\n\n  void timesBy(LogWeightTpl const& b) { this->value_ += b.value_; }\n  typedef void HasTimesBy;\n\n  DEFINE_OPENFST_COMPAT_FUNCTIONS(Log)\n};\n\ntemplate <class T>\nLogWeightTpl<T> plus(LogWeightTpl<T> const& w1, LogWeightTpl<T> const& w2) {\n  return {Util::neglogPlus(w1.value_, w2.value_)};\n}\n\ntemplate <class T>\nLogWeightTpl<T> minus(LogWeightTpl<T> const& w1, LogWeightTpl<T> const& w2) {\n  return {Util::neglogMinus(w1.value_, w2.value_)};\n}\n\ntemplate <class T>\ninline LogWeightTpl<T> times(LogWeightTpl<T> const& w1, LogWeightTpl<T> const& w2) {\n  if (w1 == LogWeightTpl<T>::zero() || w2 == LogWeightTpl<T>::zero()) return LogWeightTpl<T>::zero();\n  return LogWeightTpl<T>(w1.value_ + w2.value_);\n}\n\ntemplate <class T>\ninline bool less(LogWeightTpl<T> const& w1, LogWeightTpl<T> const& w2) {\n  return w1.value_ < w2.value_;\n}\n\ntemplate <class T>\ninline LogWeightTpl<T> divide(LogWeightTpl<T> const& w1, LogWeightTpl<T> const& w2) {\n  if (w1 == LogWeightTpl<T>::zero() || w2 == LogWeightTpl<T>::zero()) {\n    // Technically can't divide by zero. but practically ok.\n    return LogWeightTpl<T>::zero();\n  }\n  return LogWeightTpl<T>(w1.value_ - w2.value_);\n}\n\ntemplate <class T>\ninline LogWeightTpl<T> invert(LogWeightTpl<T> const& w) {\n  return LogWeightTpl<T>(-w.value_);\n}\n\ntemplate <class T>\ninline LogWeightTpl<T> pow(LogWeightTpl<T> const& w, T k) {\n  return LogWeightTpl<T>(k * w.value_);\n}\n\ntypedef LogWeightTpl<float> LogWeight;\ntypedef ViterbiWeightTpl<float> ViterbiWeight;\n\ninline BooleanWeight plus(BooleanWeight const& w1, BooleanWeight const& w2) {\n  return BooleanWeight(w1.value_ || w2.value_);\n}\n\n\ninline BooleanWeight times(BooleanWeight const& w1, BooleanWeight const& w2) {\n  return BooleanWeight(w1.value_ && w2.value_);\n}\n\ninline bool less(BooleanWeight const& w1, BooleanWeight const& w2) {\n  return w1.value_ < w2.value_;\n}\n\ninline BooleanWeight divide(BooleanWeight const& w1, BooleanWeight const& w2) {\n  SDL_THROW_LOG(Hypergraph, UnimplementedException, \"Boolean divide is not supported\");\n  return w1;  // make compiler happy\n}\n\ninline BooleanWeight invert(BooleanWeight const& w1, BooleanWeight const& w2) {\n  SDL_THROW_LOG(Hypergraph, UnimplementedException, \"Boolean invert is not supported\");\n  return w1;  // make compiler happy\n}\n\ninline BooleanWeight pow(BooleanWeight const& w, bool p) {\n  return p ? w : BooleanWeight(true);\n}\n\ntemplate <class Weight>\nchar const* weightName(Weight*) {\n  return \"Weight\";\n}\n\ntemplate <class Weight>\nchar const* weightName() {\n  return weightName((Weight*)0);\n}\n\ntemplate <class T>\ninline char const* weightName(ViterbiWeightTpl<T>*) {\n  return \"Viterbi\";\n}\n\ntemplate <class T>\ninline char const* weightName(LogWeightTpl<T>*) {\n  return \"Log\";\n}\n\ninline char const* weightName(BooleanWeight*) {\n  return \"Boolean\";\n}\n\n\n}}\n\n#endif\n", "meta": {"hexsha": "09a1af62bf738570b22a49185a650808e0f3639e", "size": 13910, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sdl/Hypergraph/Weight.hpp", "max_stars_repo_name": "sdl-research/hyp", "max_stars_repo_head_hexsha": "d39f388f9cd283bcfa2f035f399b466407c30173", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-01-26T21:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-18T18:09:42.000Z", "max_issues_repo_path": "sdl/Hypergraph/Weight.hpp", "max_issues_repo_name": "hypergraphs/hyp", "max_issues_repo_head_hexsha": "d39f388f9cd283bcfa2f035f399b466407c30173", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-12-08T15:03:15.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-26T14:31:06.000Z", "max_forks_repo_path": "sdl/Hypergraph/Weight.hpp", "max_forks_repo_name": "hypergraphs/hyp", "max_forks_repo_head_hexsha": "d39f388f9cd283bcfa2f035f399b466407c30173", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-11-21T14:25:38.000Z", "max_forks_repo_forks_event_max_datetime": "2017-10-30T22:22:00.000Z", "avg_line_length": 32.3488372093, "max_line_length": 109, "alphanum_fraction": 0.6965492451, "num_tokens": 3771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23724647464773652}}
{"text": "/*\n Copyright (C) 2019 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <qle/termstructures/eqcommoptionsurfacestripper.hpp>\n#include <boost/make_shared.hpp>\n#include <ql/instruments/impliedvolatility.hpp>\n#include <ql/math/solver1d.hpp>\n#include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp>\n#include <ql/termstructures/volatility/equityfx/blackconstantvol.hpp>\n#include <qle/pricingengines/baroneadesiwhaleyengine.hpp>\n#include <qle/termstructures/blackvariancesurfacesparse.hpp>\n#include <qle/termstructures/pricetermstructureadapter.hpp>\n\nusing std::function;\nusing std::map;\nusing std::pair;\nusing std::set;\nusing std::vector;\nusing namespace QuantLib;\n\nnamespace {\n\n// Utility method to create the list of options to be used at an expiry date for stripping.\nfunction<bool(Real,Real)> comp = [](Real a, Real b) { return !close(a, b) && a < b; };\n\nmap<Real, Option::Type, decltype(comp)> createStrikes(Real forward, const vector<Real>& cStrikes,\n    const vector<Real>& pStrikes, bool preferOutOfTheMoney) {\n\n    // Firstly create the restricted vector of call and put strikes.\n    vector<Real> rcStks;\n    copy_if(cStrikes.begin(), cStrikes.end(), back_inserter(rcStks),[forward, preferOutOfTheMoney](Real stk) {\n        return (preferOutOfTheMoney && stk >= forward) || (!preferOutOfTheMoney && stk <= forward); });\n    vector<Real> rpStks;\n    copy_if(pStrikes.begin(), pStrikes.end(), back_inserter(rpStks), [forward, preferOutOfTheMoney](Real stk) {\n        return (preferOutOfTheMoney && stk <= forward) || (!preferOutOfTheMoney && stk >= forward); });\n\n    // Create the empty map.\n    map<Real, Option::Type, decltype(comp)> res(comp);\n\n    // If both restricted vectors are empty, return an empty map\n    if (rcStks.empty() && rpStks.empty())\n        return res;\n\n    // At least one of the restricted strike vectors are non empty so populate the map.\n    if (!rcStks.empty() && !rpStks.empty()) {\n        // Most common case hopefully. Use both sets of strikes.\n        // Could have the fwd strike in both restricted sets from the logic above. Favour Call here via overwrite.\n        for (Real stk : rpStks)\n            res[stk] = Option::Put;\n        for (Real stk : rcStks)\n            res[stk] = Option::Call;\n    } else if (rpStks.empty()) {\n        // If restricted put strikes are empty, use all the call strikes\n        for (Real stk : cStrikes)\n            res[stk] = Option::Call;\n    } else if (rcStks.empty()) {\n        // If restricted call strikes are empty, use all the put strikes\n        for (Real stk : pStrikes)\n            res[stk] = Option::Put;\n    }\n\n    return res;\n}\n\n}\n\nnamespace QuantExt {\n\nOptionSurfaceStripper::OptionSurfaceStripper(\n    const boost::shared_ptr<OptionInterpolatorBase>& callSurface,\n    const boost::shared_ptr<OptionInterpolatorBase>& putSurface,\n    const Calendar& calendar,\n    const DayCounter& dayCounter,\n    Exercise::Type type,\n    bool lowerStrikeConstExtrap,\n    bool upperStrikeConstExtrap,\n    bool timeFlatExtrapolation,\n    bool preferOutOfTheMoney,\n    Solver1DOptions solverOptions)\n    : callSurface_(callSurface),\n      putSurface_(putSurface),\n      calendar_(calendar),\n      dayCounter_(dayCounter),\n      type_(type),\n      lowerStrikeConstExtrap_(lowerStrikeConstExtrap),\n      upperStrikeConstExtrap_(upperStrikeConstExtrap),\n      timeFlatExtrapolation_(timeFlatExtrapolation),\n      preferOutOfTheMoney_(preferOutOfTheMoney),\n      solverOptions_(solverOptions),\n      havePrices_(boost::dynamic_pointer_cast<OptionPriceSurface>(callSurface_)) {\n\n    QL_REQUIRE(callSurface_->referenceDate() == putSurface_->referenceDate(),\n        \"Mismatch between Call and Put reference dates in OptionSurfaceStripper\");\n\n    registerWith(Settings::instance().evaluationDate());\n\n    // Set up that is only needed if we have price based surfaces and we are stripping volatilities.\n    if (havePrices_) {\n\n        // Check that there is also a put price surface\n        QL_REQUIRE(boost::dynamic_pointer_cast<OptionPriceSurface>(putSurface_),\n            \"OptionSurfaceStripper: call price surface provided but no put price surface.\");\n\n        setUpSolver();\n    }\n}\n\nOptionSurfaceStripper::PriceError::PriceError(const VanillaOption& option, SimpleQuote& volatility, Real targetPrice)\n    : option_(option), volatility_(volatility), targetPrice_(targetPrice) {}\n\nReal OptionSurfaceStripper::PriceError::PriceError::operator()(Volatility x) const {\n\n    volatility_.setValue(x);\n\n    // Barone Adesi Whaley fails for very small variance, so wrap in a try catch\n    Real npv;\n    try {\n        npv = option_.NPV();\n    } catch (...) {\n        npv = 0.0;\n    }\n\n    return npv - targetPrice_;\n}\n\nvoid OptionSurfaceStripper::performCalculations() const {\n\n    // Create a set of all expiries\n    auto tmp = callSurface_->expiries();\n    set<Date> allExpiries(tmp.begin(), tmp.end());\n    tmp = putSurface_->expiries();\n    allExpiries.insert(tmp.begin(), tmp.end());\n\n    boost::shared_ptr<BlackVarianceSurfaceSparse> callVolSurface;\n    boost::shared_ptr<BlackVarianceSurfaceSparse> putVolSurface;\n\n    // Switch based on whether surface is direct volatilities or prices to be stripped.\n    boost::shared_ptr<PricingEngine> engine;\n    boost::shared_ptr<SimpleQuote> volQuote = boost::make_shared<SimpleQuote>(0.1);\n    if (havePrices_) {\n\n        // a black scholes process\n        boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp = process(volQuote);\n\n        // hard code the engines here\n        if (type_ == Exercise::American) {\n            engine = boost::make_shared<QuantExt::BaroneAdesiWhaleyApproximationEngine>(gbsp);\n        } else if (type_ == Exercise::European) {\n            engine = boost::make_shared<QuantExt::AnalyticEuropeanEngine>(gbsp);\n        } else {\n            QL_FAIL(\"Unsupported exercise type for option stripping\");\n        }\n\n    } else {\n        // we have variance surfaces, explicitly cast so we can look up vol later\n        callVolSurface = boost::dynamic_pointer_cast<BlackVarianceSurfaceSparse>(callSurface_);\n        putVolSurface = boost::dynamic_pointer_cast<BlackVarianceSurfaceSparse>(putSurface_);\n    }\n\n    // Need to populate these below to feed to BlackVarianceSurfaceSparse\n    vector<Real> volStrikes;\n    vector<Real> volData;\n    vector<Date> volExpiries;\n\n    // Loop over each expiry\n    for (const Date& expiry : allExpiries) {\n\n        // Get the forward price at expiry\n        Real fwd = forward(expiry);\n\n        // Get the call and put strikes at the expiry date. Each may be empty.\n        vector<Real> callStrikes = strikes(expiry, true);\n        vector<Real> putStrikes = strikes(expiry, false);\n\n        // We want a set of prices both sides of ATM forward\n        // If preferOutOfTheMoney_ is false, we take calls where strike < atm and puts where strike > atm.\n        // If preferOutOfTheMoney_ is true, we take calls where strike > atm and puts where strike < atm.\n        auto relevantStrikes = createStrikes(fwd, callStrikes, putStrikes, preferOutOfTheMoney_);\n        for (const auto& kv : relevantStrikes) {\n            if (havePrices_) {\n                // Only use the volatility if the root finding was successful\n                Real v = implyVol(expiry, kv.first, kv.second, engine, *volQuote);\n                if (v != Null<Real>()) {\n                    volExpiries.push_back(expiry);\n                    volStrikes.push_back(kv.first);\n                    volData.push_back(v);\n                }\n            } else {\n                volExpiries.push_back(expiry);\n                volStrikes.push_back(kv.first);\n                Real v = kv.second == Option::Call ? callVolSurface->blackVol(expiry, kv.first) :\n                    putVolSurface->blackVol(expiry, kv.first);\n                volData.push_back(v);\n            }\n        }\n    }\n\n    // Populate the variance surface.\n    volSurface_ = boost::make_shared<BlackVarianceSurfaceSparse>(\n        callSurface_->referenceDate(), calendar_, volExpiries, volStrikes, volData, dayCounter_,\n        lowerStrikeConstExtrap_, upperStrikeConstExtrap_, timeFlatExtrapolation_);\n}\n\nvector<Real> OptionSurfaceStripper::strikes(const Date& expiry, bool isCall) const {\n\n    const boost::shared_ptr<OptionInterpolatorBase>& surface = isCall ? callSurface_ : putSurface_;\n    auto expiries = surface->expiries();\n    auto it = find(expiries.begin(), expiries.end(), expiry);\n\n    if (it != expiries.end()) {\n        return surface->strikes().at(distance(expiries.begin(), it));\n    } else {\n        return {};\n    }\n\n}\n\nReal OptionSurfaceStripper::implyVol(Date expiry, Real strike, Option::Type type,\n    boost::shared_ptr<PricingEngine> engine, SimpleQuote& volQuote) const {\n\n    // Create the option instrument used in the solver.\n    boost::shared_ptr<StrikedTypePayoff> payoff = boost::make_shared<PlainVanillaPayoff>(type, strike);\n    boost::shared_ptr<Exercise> exercise;\n    if (type_ == Exercise::American) {\n        exercise = boost::make_shared<AmericanExercise>(expiry);\n    } else if (type_ == Exercise::European) {\n        exercise = boost::make_shared<EuropeanExercise>(expiry);\n    } else {\n        QL_FAIL(\"OptionSurfaceStripper: unsupported exercise type for option stripping.\");\n    }\n    VanillaOption option(payoff, exercise);\n    option.setPricingEngine(engine);\n\n    // Get the target price from the surface.\n    Real targetPrice = type == Option::Call ? callSurface_->getValue(expiry, strike)\n        : putSurface_->getValue(expiry, strike);\n\n    // Attempt to calculate the implied volatility.\n    Real vol = Null<Real>();\n    try {\n        PriceError f(option, volQuote, targetPrice);\n        vol = solver_(f);\n    } catch (const Error&) {\n    }\n\n    return vol;\n}\n\nvoid OptionSurfaceStripper::setUpSolver() {\n\n    // Check that enough solver options have been provided.\n    const Real& guess = solverOptions_.initialGuess;\n    QL_REQUIRE(guess != Null<Real>(), \"OptionSurfaceStripper: need a valid initial \" <<\n        \"guess for a price based surface.\");\n\n    const Real& accuracy = solverOptions_.accuracy;\n    QL_REQUIRE(accuracy != Null<Real>(), \"OptionSurfaceStripper: need a valid accuracy \" <<\n        \"for a price based surface.\");\n\n    // Set maximum evaluations if provided.\n    if (solverOptions_.maxEvaluations != Null<Size>())\n        brent_.setMaxEvaluations(solverOptions_.maxEvaluations);\n\n    // Check and set the lower bound and upper bound\n    if (solverOptions_.lowerBound != Null<Real>() && solverOptions_.upperBound != Null<Real>()) {\n        QL_REQUIRE(solverOptions_.lowerBound < solverOptions_.upperBound, \"OptionSurfaceStripper: lowerBound (\" <<\n            solverOptions_.lowerBound << \") should be less than upperBound (\" << solverOptions_.upperBound << \")\");\n    }\n\n    if (solverOptions_.lowerBound != Null<Real>())\n        brent_.setLowerBound(solverOptions_.lowerBound);\n    if (solverOptions_.upperBound != Null<Real>())\n        brent_.setUpperBound(solverOptions_.upperBound);\n\n    // Choose a min/max or step solver based on parameters provided, favouring the min/max based version.\n    const Real& min = solverOptions_.minMax.first;\n    const Real& max = solverOptions_.minMax.second;\n    const Real& step = solverOptions_.step;\n    using std::placeholders::_1;\n    if (min != Null<Real>() && max != Null<Real>()) {\n        typedef Real (Brent::* MinMaxSolver)(const PriceError&, Real, Real, Real, Real) const;\n        solver_ = std::bind(static_cast<MinMaxSolver>(&Brent::solve), &brent_, _1, accuracy, guess, min, max);\n    } else if (step != Null<Real>()) {\n        typedef Real(Brent::* StepSolver)(const PriceError&, Real, Real, Real) const;\n        solver_ = std::bind(static_cast<StepSolver>(&Brent::solve), &brent_, _1, accuracy, guess, step);\n    } else {\n        QL_FAIL(\"OptionSurfaceStripper: need a valid step size or (min, max) pair for a price based surface.\");\n    }\n\n}\n\nboost::shared_ptr<BlackVolTermStructure> OptionSurfaceStripper::volSurface() {\n    calculate();\n    return volSurface_;\n}\n\nEquityOptionSurfaceStripper::EquityOptionSurfaceStripper(\n    const Handle<EquityIndex>& equityIndex,\n    const boost::shared_ptr<OptionInterpolatorBase>& callSurface,\n    const boost::shared_ptr<OptionInterpolatorBase>& putSurface,\n    const Calendar& calendar,\n    const DayCounter& dayCounter,\n    Exercise::Type type,\n    bool lowerStrikeConstExtrap,\n    bool upperStrikeConstExtrap,\n    bool timeFlatExtrapolation,\n    bool preferOutOfTheMoney,\n    Solver1DOptions solverOptions)\n    : OptionSurfaceStripper(callSurface, putSurface, calendar, dayCounter, type, lowerStrikeConstExtrap,\n        upperStrikeConstExtrap, timeFlatExtrapolation, preferOutOfTheMoney, solverOptions), equityIndex_(equityIndex) {\n    registerWith(equityIndex_);\n}\n\nboost::shared_ptr<GeneralizedBlackScholesProcess> EquityOptionSurfaceStripper::process(\n    const boost::shared_ptr<QuantLib::SimpleQuote>& volatilityQuote) const {\n\n    Handle<BlackVolTermStructure> vts(boost::make_shared<BlackConstantVol>(\n        callSurface_->referenceDate(), calendar_, Handle<Quote>(volatilityQuote), dayCounter_));\n\n    return boost::make_shared<BlackScholesMertonProcess>(equityIndex_->equitySpot(),\n        equityIndex_->equityDividendCurve(), equityIndex_->equityForecastCurve(), vts);\n}\n\nReal EquityOptionSurfaceStripper::forward(const Date& date) const {\n    return equityIndex_->forecastFixing(date);\n}\n\nCommodityOptionSurfaceStripper::CommodityOptionSurfaceStripper(\n    const Handle<PriceTermStructure>& priceCurve,\n    const Handle<YieldTermStructure>& discountCurve,\n    const boost::shared_ptr<OptionInterpolatorBase>& callSurface,\n    const boost::shared_ptr<OptionInterpolatorBase>& putSurface,\n    const Calendar& calendar,\n    const DayCounter& dayCounter,\n    Exercise::Type type,\n    bool lowerStrikeConstExtrap,\n    bool upperStrikeConstExtrap,\n    bool timeFlatExtrapolation,\n    bool preferOutOfTheMoney,\n    Solver1DOptions solverOptions)\n    : OptionSurfaceStripper(callSurface, putSurface, calendar, dayCounter, type, lowerStrikeConstExtrap,\n        upperStrikeConstExtrap, timeFlatExtrapolation, preferOutOfTheMoney, solverOptions),\n        priceCurve_(priceCurve), discountCurve_(discountCurve) {\n    registerWith(priceCurve_);\n    registerWith(discountCurve_);\n}\n\nboost::shared_ptr<GeneralizedBlackScholesProcess> CommodityOptionSurfaceStripper::process(\n    const boost::shared_ptr<QuantLib::SimpleQuote>& volatilityQuote) const {\n\n    QL_REQUIRE(!priceCurve_.empty(), \"CommodityOptionSurfaceStripper: price curve is empty\");\n    QL_REQUIRE(!discountCurve_.empty(), \"CommodityOptionSurfaceStripper: discount curve is empty\");\n\n    // Volatility term structure for the process\n    Handle<BlackVolTermStructure> vts(boost::make_shared<BlackConstantVol>(\n        callSurface_->referenceDate(), calendar_, Handle<Quote>(volatilityQuote), dayCounter_));\n\n    // Generate \"spot\" and \"yield\" curve for the process.\n    Handle<Quote> spot(boost::make_shared<DerivedPriceQuote>(priceCurve_));\n    Handle<YieldTermStructure> yield(boost::make_shared<PriceTermStructureAdapter>(*priceCurve_, *discountCurve_));\n    yield->enableExtrapolation();\n\n    return boost::make_shared<QuantLib::GeneralizedBlackScholesProcess>(spot, yield, discountCurve_, vts);\n}\n\nReal CommodityOptionSurfaceStripper::forward(const Date& date) const {\n    QL_REQUIRE(!priceCurve_.empty(), \"CommodityOptionSurfaceStripper: price curve is empty\");\n    return priceCurve_->price(date);\n}\n\n}\n", "meta": {"hexsha": "9b6237dceb87b6f5a8fec705be5e43e145d4c672", "size": 16125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/eqcommoptionsurfacestripper.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/termstructures/eqcommoptionsurfacestripper.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/termstructures/eqcommoptionsurfacestripper.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 41.6666666667, "max_line_length": 119, "alphanum_fraction": 0.7079069767, "num_tokens": 3804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.23697216163834173}}
{"text": "#include <algorithm>\n#include <boost/optional.hpp>\n#include <climits>\n#include <cmath>\n#include <cstdio>\n#include <cstring>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <set>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++)\n#define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++)\n#define EACH(e, a) for(auto&& e : a)\n#define ALL(a) std::begin(a), std::end(a)\n#define RALL(a) std::rbegin(a), std::rend(a)\n#define FILL(a, n) memset((a), n, sizeof(a))\n#define FILLZ(a) FILL(a, 0)\n#define INT(x) (static_cast<int>(x))\n#define PRECISION(x) std::fixed << std::setprecision(x)\n\nusing namespace std;\n\nusing ll = long long;\nusing VI = std::vector<int>;\nusing VI2D = std::vector<vector<int>>;\nusing VLL = std::vector<long long>;\nusing VLL2D = std::vector<vector<long long>>;\n\nconstexpr int INF = 2e9;\nconstexpr double EPS = 1e-10;\nconstexpr double PI = acos(-1.0);\n\nconstexpr int dx[] = {-1, 0, 1, 0};\nconstexpr int dy[] = {0, -1, 0, 1};\n\ntemplate <typename T>\nconstexpr int sign(T x) {\n\treturn x < 0 ? -1 : x > 0 ? 1 : 0;\n}\n\ntemplate <>\nconstexpr int sign(double x) {\n\treturn x < -EPS ? -1 : x > EPS ? 1 : 0;\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmax(T& m, U x) {\n\tm = max(m, x);\n}\n\ntemplate <typename T, typename U>\nconstexpr void chmin(T& m, U x) {\n\tm = min(m, x);\n}\n\ntemplate <typename T>\nconstexpr T square(T x) {\n\treturn x * x;\n}\n\ntemplate <long long MOD = 1000000007>\nclass ModInt {\n\tpublic:\n\tlong long n;\n\n\tconstexpr ModInt() : n(0) {}\n\tconstexpr ModInt(long long n) : n(n < 0 ? n + MOD : n % MOD) {}\n\n\tconstexpr long long get() const { return this->n; }\n\tconstexpr long long get_mod() const { return MOD; }\n\n\tconstexpr ModInt inv() const { return pow<ModInt<MOD>>(*this, MOD - 2); }\n\n\tconstexpr ModInt& operator=(const long long rhs) {\n\t\treturn *this = ModInt(rhs);\n\t}\n\tconstexpr ModInt& operator+=(const ModInt rhs) {\n\t\treturn *this = ModInt(this->n + rhs.n);\n\t}\n\tconstexpr ModInt& operator-=(const ModInt rhs) {\n\t\treturn *this = ModInt(this->n - rhs.n);\n\t}\n\tconstexpr ModInt& operator*=(const ModInt rhs) {\n\t\treturn *this = ModInt(this->n * rhs.n);\n\t}\n\tconstexpr ModInt& operator/=(const ModInt rhs) {\n\t\treturn *this *= rhs.inv();\n\t}\n\tconstexpr bool operator==(const ModInt rhs) const {\n\t\treturn this->n == rhs.n;\n\t}\n};\n\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator+(const ModInt<MOD>& lhs,\n\t\t\t\t\t\t\t\tconst ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) += rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator+(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) += rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator+(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) += rhs;\n}\n\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator-(const ModInt<MOD>& lhs,\n\t\t\t\t\t\t\t\tconst ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) -= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator-(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) -= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator-(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) -= rhs;\n}\n\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator*(const ModInt<MOD>& lhs,\n\t\t\t\t\t\t\t\tconst ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) *= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator*(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) *= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator*(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) *= rhs;\n}\n\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator/(const ModInt<MOD>& lhs,\n\t\t\t\t\t\t\t\tconst ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) /= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator/(const ModInt<MOD>& lhs, const long long& rhs) {\n\treturn ModInt<MOD>(lhs) /= rhs;\n}\ntemplate <long long MOD>\nconstexpr ModInt<MOD> operator/(const long long& lhs, const ModInt<MOD>& rhs) {\n\treturn ModInt<MOD>(lhs) /= rhs;\n}\n\ntemplate <long long MOD>\nstd::ostream& operator<<(std::ostream& os, const ModInt<MOD>& x) {\n\treturn os << x.n;\n}\n\ntemplate <long long MOD>\nstd::istream& operator>>(std::istream& is, const ModInt<MOD>& x) {\n\treturn is >> x.n;\n}\n\ntemplate <typename T>\nclass Counter {\n\tusing iterator = typename std::unordered_map<T, std::size_t>::iterator;\n\tusing const_iterator =\n\t\ttypename std::unordered_map<T, std::size_t>::const_iterator;\n\n\tstd::unordered_map<T, std::size_t> m;\n\n\tpublic:\n\ttemplate <typename U>\n\tCounter(U& v) {\n\t\tfor(T& e : v) {\n\t\t\tthis->m[e]++;\n\t\t}\n\t}\n\n\tstd::vector<T> keys() const {\n\t\tstd::vector<T> v(this->size());\n\t\tint i = 0;\n\t\tfor(const std::pair<T, std::size_t>& e : this->m) {\n\t\t\tv[i++] = e.first;\n\t\t}\n\t\treturn v;\n\t}\n\n\tstd::vector<size_t> values() const {\n\t\tstd::vector<size_t> v(this->size());\n\t\tint i = 0;\n\t\tfor(const std::pair<T, std::size_t>& e : this->m) {\n\t\t\tv[i++] = e.second;\n\t\t}\n\t\treturn v;\n\t}\n\n\tstd::size_t size() const { return this->m.size(); }\n\titerator begin() { return this->m.begin(); }\n\titerator end() { return this->m.end(); }\n\tconst_iterator cbegin() const { return this->m.cbegin(); }\n\tconst_iterator cend() const { return this->m.cend(); }\n\n\tconst std::size_t& operator[](T a) const& { return this->m[a]; }\n\tstd::size_t& operator[](T a) & { return this->m[a]; }\n\tstd::size_t operator[](T a) const&& { return std::move(this->m[a]); }\n};\n\nint main() {\n\tint n;\n\tstring s;\n\tcin >> n;\n\tcin >> s;\n\n\tCounter<char> count(s);\n\tModInt<> result = 1;\n\tEACH(e, count.values()) { result *= e + 1; }\n\n\tcout << result - 1 << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "43b808371f4e6ed8a68eb7b59e73ae03c53abfe3", "size": 5842, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AtCoder/AGC031/A2.cpp", "max_stars_repo_name": "arlechann/atcoder", "max_stars_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AtCoder/AGC031/A2.cpp", "max_issues_repo_name": "arlechann/atcoder", "max_issues_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AtCoder/AGC031/A2.cpp", "max_forks_repo_name": "arlechann/atcoder", "max_forks_repo_head_hexsha": "1af08efa6d3a0e8c75e4eaf13e1eda994820b9e2", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1810344828, "max_line_length": 79, "alphanum_fraction": 0.649435125, "num_tokens": 1761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.23697215496185703}}
{"text": "/*! \\file fm2dir.hpp\n    \\brief Templated class which computes the Fast Marching Directional (FM2Directional).\n\n    It uses as a main container the nDGridMap class. The nDGridMap type T\n    has to be an FMDirectionalCell or something inherited from it.\n\n    The leafsize of the grid map is ignored since it has to be > = 1 and that\n    depends on the units employed.\n\n    The type of the heap introduced is very important for the behaviour of the\n    algorithm. The following heaps are provided:\n\n    - FMDaryHeap wrap for the Boost D_ary heap (generalization of binary heaps).\n      Set by default if no other heap is specified. The arity has been set to 2\n      (binary heap) since it has been tested to be the more efficient in this algorithm.\n    - FMFibHeap wrap for the Boost Fibonacci heap.\n    - FMPriorityQueue wrap to the std::PriorityQueue class. This heap implies the implementation\n      of the Simplified FMM (SFMM) method, done automatically because of the FMPriorityQueue::increase implementation.\n\n    Copyright (C) 2014 Javier V. Gomez and Jose Pardeiro\n    www.javiervgomez.com\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n    You should have received a copy of the GNU General Public License\n    along with this program. If not, see <http://www.gnu.org/licenses/>.*/\n\n#ifndef FM2DIR_H_\n#define FM2DIR_H_\n\n#include <iostream>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n#include <fstream>\n#include <array>\n#include <limits>\n\n#include <boost/math/constants/constants.hpp>\n\n#include \"../fmm/fmdata/fmdirectionalcell.h\"\n#include \"../fm2/fm2.hpp\"\n#include \"../gradientdescent/gradientdescent.hpp\"\n\n#define PI boost::math::constants::pi<double>()\n\n// TODO: include suppoert to other solvers (GMM, FIM, UFMM). It requires a better way of setting parameters.\n\ntemplate < class grid_t, class heap_t = FMDaryHeap<FMCell> >  class FM2Dir : public FM2<grid_t, heap_t> {\n\n    typedef std::vector< std::array< double, grid_t::getNDims() > > path_t;\n    typedef FM2<grid_t, heap_t > FM2Base;\n\n    public:\n\n    FM2Dir\n    (const std::string& name = \"FM2Dir\") : FM2Base(name) { }\n\n        /**\n         * Sets the input grid in which operations will be performed.\n         *\n         * @param g input grid map.\n         */\n        virtual void setEnvironment\n        (grid_t * g) {\n            grid_ = g;\n            narrow_band_.setMaxSize(grid_->size());\n            ndims_ = grid_->getNDims();\n        }\n\n        /**\n         * Sets the initial points by the indices in the nDGridMap and\n         * computes the initialization of the Fast Marching Square calling\n         * the init() function.\n         *\n         * @param initial_point contains the index of the initial point of the query.\n         *\n         * @param fmm2_sources contains the indices of the initial points corresponding to all black cells.\n         *\n         * @param goal_idx contains the index of the goal point.\n         *\n         * @see init()\n         */\n\n        virtual void setInitialAndGoalPoints\n        (const std::vector <int> & initial_point, const std::vector <int> & fmm2_sources, const int goal_idx) {\n            initial_point_ = initial_point;\n            fmm2_sources_ = fmm2_sources;\n            goal_idx_ = goal_idx;\n        }\n\n        /**\n         * Sets the initial points by the indices in the nDGridMap and\n         * computes the initialization of the Fast Marching Method calling\n         * the init() function.\n         *\n         * @param init_points contains the indices of the init points.\n         *\n         * @param save_velocity selects if the velocity profile must be saved\n         *\n         * @see init()\n         */\n        virtual void setInitialPoints\n        (const std::vector<int> & init_points, const bool save_velocity = false) {\n            init_points_ = init_points;\n            for (const int &i: init_points) {\n            grid_->getCell(i).setArrivalTime(0);\n            grid_->getCell(i).setDirectionalTime(0);\n            grid_->getCell(i).setState(FMState::FROZEN);\n            }\n\n            if (init_points.size() > 1)\n                init();\n            else\n                init(save_velocity, true);\n        }\n\n        /**\n        * Internal function although it is set to public so it can be accessed if desired.\n        *\n        * Computes the Fast Marching Method initialization from the initial points given. Programmed following the paper:\n          A. Valero, J.V. Gómez, S. Garrido and L. Moreno, The Path to Efficiency: Fast Marching Method for Safer,\n          More Efficient Mobile Robot Trajectories, IEEE Robotics and Automation Magazine, Vol. 20, No. 4, 2013.\n        *\n        * @param save_velocity selects if the velocity profile must be saved\n        *\n        * @param directional selects if directional heuristic must be applied\n        *\n        * @see setInitialPoints()\n        */\n        virtual void init\n        (const bool save_velocity = false, const bool directional = false) {\n            // TODO: neighbors computed twice for every cell. We can save time here.\n            // TODO: check if the previous steps have been done (loading grid map and setting initial points.)\n            int j = 0;\n            int n_neighs = 0;\n            for (int &i: init_points_) { // For each initial point\n            n_neighs = grid_->getNeighbors(i, neighbors);\n                for (int s = 0; s < n_neighs; ++s){  // For each neighbor\n                    j = neighbors[s];\n                    if ((grid_->getCell(j).getState() ==  FMState::FROZEN) || grid_->getCell(j).isOccupied() || grid_->getCell(j).getVelocity() ==  0) // If Frozen or obstacle\n                        continue;\n                    else {\n                        double new_arrival_time = solveEikonal(j);\n                        double dir_time = 0;\n\n                        if (directional ==  true)\n                            dir_time = new_arrival_time;\n\n                        if (grid_->getCell(j).getState() ==  FMState::NARROW) { // Updating narrow band if necessary.\n                            if (new_arrival_time < grid_->getCell(j).getArrivalTime()) {\n                                grid_->getCell(j).setArrivalTime(new_arrival_time);\n\n                            if (save_velocity)\n                                velocity_map_[j] = vel;\n\n                            if (directional)\n                                grid_->getCell(j).setDirectionalTime(dir_time);\n                            narrow_band_.increase( &(grid_->getCell(j))  ) ;\n                            }\n                        }\n                        else {\n                            grid_->getCell(j).setState(FMState::NARROW);\n                            grid_->getCell(j).setArrivalTime(new_arrival_time);\n\n                            if (save_velocity)\n                                velocity_map_[j] = vel;\n\n                            if (directional ==  true)\n                                grid_->getCell(j).setDirectionalTime(dir_time);\n                            narrow_band_.push( &(grid_->getCell(j)) );\n                        } // neighbors open.\n                    } // neighbors not frozen.\n                } // For each neighbor.\n            } // For each initial point.\n        } // init()\n\n        \n        //IMPORTANT NOTE: Assuming inc(1) = inc(y)  = ... =  leafsize_\n        // Possible improvement: If we include the neighbors in the cells information\n        // this could be (most probably) speeded up.\n        // This implementation is focused to be used with any number of dimensions.\n\n        /**\n        * Solves the Eikonal equation for a given cell using the heuristic criteria of the FM2 Directional.\n        * This function is generalized to any number of dimensions.\n        *\n        * @param idx index of the cell to be evaluated.\n        *\n        * @param idx_source index of the source cell of the wave. If this value is -1 the heuristic is not applied\n        *\n        * @return the distance (or time of arrival) value.\n        */\n        virtual double solveEikonal\n        (const int & idx, const int & idx_source = -1) {\n            // TODO: Here neighbors are computed and then in the computeFM. There should be a way to avoid computing\n            // neighbors twice.\n\n            int a = grid_t::getNDims(); // a parameter of the Eikonal equation.\n\n            double updatedT;\n            sumT = 0;\n            sumTT = 0;\n            double minTInDim = 0;\n\n            vel = 0;\n\n            if (idx_source == -1) {\n                for (int dim = 0; dim < grid_t::getNDims(); ++dim) {\n                    minTInDim = grid_->getMinValueInDim(idx, dim);\n                    if (!isinf(minTInDim)) {\n                        Tvalues[dim] = minTInDim;\n                        sumT +=  Tvalues[dim];\n                        TTvalues[dim] = Tvalues[dim]*Tvalues[dim];\n                        sumTT +=  TTvalues[dim];\n                    }\n                    else {\n                        Tvalues[dim] = 0;\n                        TTvalues[dim] = 0;\n                        a -= 1 ;\n                    }\n                }\n\n                vel = grid_->getCell(idx).getVelocity();\n            }\n            else {\n\n                for (int dim = 0; dim < grid_t::getNDims(); ++dim) {\n                    minTInDim = getMinValueInDimDirectional(idx, dim);\n                    if (!isinf(minTInDim)) {\n                        Tvalues[dim] = minTInDim;\n                        sumT +=  Tvalues[dim];\n                        TTvalues[dim] = Tvalues[dim]*Tvalues[dim];\n                        sumTT +=  TTvalues[dim];\n                    }\n                    else {\n                        Tvalues[dim] = 0;\n                        TTvalues[dim] = 0;\n                        a -= 1 ;\n                    }\n                }\n\n                if (grid_->getCell(idx).getVelocity() < grid_->getCell(idx_source).getVelocity() && grid_->getCell(idx).getVelocity() > 0.05)\n                    vel = 1;\n                else\n                    vel = grid_->getCell(idx).getVelocity();\n            }\n\n            double b = -2*sumT;\n            double c = sumTT - grid_->getLeafSize() * grid_->getLeafSize()/(vel * vel); // leafsize not taken into account here.\n            double quad_term = b*b - 4*a*c;\n            if (quad_term < 0) {\n                double minT = *(std::min_element(Tvalues.begin(), Tvalues.end()));\n                updatedT = 1/(vel * vel) + minT; // leafsize not taken into account here.\n            }\n            else\n                updatedT = (-b + sqrt(quad_term))/(2*a);\n\n            return updatedT;\n        }\n\n        /**\n         * Main Fast Marching Function. It requires to call first the setInitialPoints() function.\n         *\n         * @param stop selects if the wave has to stop when it arrives to the goal point\n         *\n         * @param directional selects if directional heuristic must be applied\n         *\n         * @see setInitialPoints()\n         */\n\n        virtual void computeFM\n        (const bool stop = true, const bool directional = false) {\n            // TODO: check if the previous steps have been done (initialization).\n            int j =  0;\n            int n_neighs = 0;\n            bool stopWavePropagation = 0;\n\n            while (narrow_band_.size() > 0 && stopWavePropagation ==  0) {\n                int idxMin = narrow_band_.popMinIdx();\n                n_neighs = grid_->getNeighbors(idxMin, neighbors);\n                grid_->getCell(idxMin).setState(FMState::FROZEN);\n\n                for (int s = 0; s < n_neighs; ++s) {\n                    j = neighbors[s];\n                    if ((grid_->getCell(j).getState() ==  FMState::FROZEN) || grid_->getCell(j).isOccupied()) // If Frozen or obstacle\n                        continue;\n                    else {\n                        double new_arrival_time = solveEikonal(j);\n                        double dir_time = 0;\n\n                        if (directional ==  true)\n                            dir_time = solveEikonal(j, idxMin);\n\n                        if (grid_->getCell(j).getState() ==  FMState::NARROW) { // Updating narrow band if necessary.\n                            if (new_arrival_time < grid_->getCell(j).getArrivalTime()) {\n                                grid_->getCell(j).setArrivalTime(new_arrival_time);\n                                narrow_band_.increase( &(grid_->getCell(j)) );\n                                velocity_map_[j] = vel;\n                            }\n\n                            if (directional)\n                                if (dir_time < grid_->getCell(j).getDirectionalTime())\n                                    grid_->getCell(j).setDirectionalTime(dir_time);\n                        }\n                        else {\n                            grid_->getCell(j).setState(FMState::NARROW);\n                            grid_->getCell(j).setArrivalTime(new_arrival_time);\n                            velocity_map_[j] = vel;\n\n                            if (directional)\n                                grid_->getCell(j).setDirectionalTime(dir_time);\n                            narrow_band_.push( &(grid_->getCell(j)) );\n                        } // neighbors open.\n                    } // neighbors not frozen.\n                    if (idxMin ==  initial_point_[0] && stop)\n                        stopWavePropagation = 1;\n                } // For each neighbor.\n            } // while narrow band not empty\n        }\n\n        /**\n         * Main Fast Marching Square Directional Function with velocity saturation. It requires to call first the setInitialPoints() function.\n         *\n         * @param maxDistance saturation distance (relative, where 1 means maximum distance). If this value is -1 (default) the velocities map is not saturated.\n         *\n         * @see setInitialPoints()\n         */\n        virtual void computeFM2Directional\n        (const float maxDistance = -1) {\n            maxDistance_ = maxDistance;\n\n            velocity_map_.resize(grid_->size());\n            if (maxDistance_ != -1)\n                computeVelocitiesMap(true);\n            else\n                computeVelocitiesMap();\n\n            // According to the theoretical basis the wave is expanded from the goal point to the initial point.\n            std::vector <int> wave_init;\n            wave_init.push_back(goal_idx_);\n            setInitialPoints(wave_init, true);\n            computeFM(true, true);\n        }\n\n        /**\n         * Computes the path from the given index to a minimum (the one\n         * gradient descent choses) and returns the velocity. According to \n         * the theoretical basis the wave is expanded from the goal point \n         * to the initial point. For these reasons the gradient must to be \n         * applied from the initial point.\n         *\n         * No checks are done (points in the borders, points in obstacles...).\n         *\n         * The included scripts will parse the saved path.\n         *\n         * @param path the resulting path (output).\n         *\n         * @param velocity the resulting path (output).\n         */\n        virtual void computePath\n        (path_t * p, std::vector <double> * path_velocity) {\n            path_t* path_ = p;\n            constexpr int ndims = grid_t::getNDims();\n\n            GradientDescent< nDGridMap<FMDirectionalCell, ndims> > grad;\n            grad.apply_directional(*grid_,initial_point_[0],*path_, velocity_map_, *path_velocity);\n        }\n\n        /**\n        * For a cell with index idx, obtains the minimum value of the neigbours in dimension dim looking the\n        * DirectionalTime value.\n        *\n        * @param idx index of the cell accessed.\n        *\n        * @param dim dimension in which the minimum is examinated (0: x, 1: y, 2: z, etc).\n        *\n        * @return the corresponding minimum value.\n        * */\n        double getMinValueInDimDirectional\n        (const int idx, const int dim) {\n            // n_neighs = 0; // How many neighbors obtained in that dimension.\n            constexpr int ndims = grid_->getNDims();\n            std::array<int, ndims> n;\n            int n_neighs = grid_->getNumberNeighborsInDim(idx,n,dim);\n\n            if (n_neighs ==  1)\n                return grid_->getCell(n[0]).getDirectionalTime();\n            else\n                return (grid_->getCell(n[0]).getDirectionalTime()<grid_->getCell(n[1]).getDirectionalTime()) ? grid_->getCell(n[0]).getDirectionalTime() : grid_->getCell(n[1]).getDirectionalTime();\n        }\n\n    private:\n\n        /**\n         * Computes the velocities map of the FM2 algorithm.\n         *\n         * @param saturate select if the potential is saturated according to maxDistance_ .\n         */\n\n        void computeVelocitiesMap\n        (bool saturate = false) {\n            setInitialPoints(fmm2_sources_);\n            computeFM(false);\n\n            //Rescaling and saturating to relative velocities: [0-1]\n            double maxValue = grid_->getMaxValue();\n            double maxVelocity = 0;\n\n            if (saturate)\n                maxVelocity = maxDistance_ / grid_->getLeafSize(); \n\n            for (int i = 0; i < grid_->size(); i++) {\n                double velocity = grid_->getCell(i).getValue() / maxValue;\n\n                if (saturate)\n                    if (velocity < maxVelocity)\n                        grid_->getCell(i).setVelocity(velocity / maxVelocity);\n                    else\n                        grid_->getCell(i).setVelocity(1);\n                else\n                    grid_->getCell(i).setVelocity(velocity);\n\n              // Restarting grid values for second wave expasion.\n              grid_->getCell(i).setValue(std::numeric_limits<double>::infinity());\n              grid_->getCell(i).setDirectionalTime(std::numeric_limits<double>::infinity());\n              grid_->getCell(i).setState(FMState::OPEN);\n            }\n        }\n\n    protected:\n        using FMM<grid_t, heap_t>::grid_;\n        using FMM<grid_t, heap_t>::neighbors;\n        using FMM<grid_t, heap_t>::init_points_;\n        using FMM<grid_t, heap_t>::Tvalues;\n        using FMM<grid_t, heap_t>::TTvalues;\n        using FMM<grid_t, heap_t>::narrow_band_;\n\n    private:\n        double sumT; /*!< Auxiliar value wich computes T1+T2+T3... Useful for generalizing the Eikonal solver. */\n        double sumTT; /*!< Auxiliar value wich computes T1^2+T2^2+T3^2... Useful for generalizing the Eikonal solver. */\n        double sumDistance; /*!< Auxiliar value wich computes euclidean distance between narrow band and goal point. Useful for generalizing the Eikonal solver with euristic. */\n\n        double vel; /*!< Auxiliar value wich contains the velocity of the cell used on the Eikonal solver. */\n        double maxDistance_; /*!< Distance value to saturate the first potential. */\n\n        int goal_idx_; /*!< Goal point for the Fast Marching Square Star. */\n        std::vector<int> fmm2_sources_;\t/*!< Wave propagation sources for the Fast Marching Square Star. */\n        std::vector<int> initial_point_;\t/*!< Initial point for the Fast Marching Square Star. */\n\n        std::array<int, grid_t::getNDims()-1> d_;\n        std::array<int, grid_t::getNDims()> dimsize_;\n        std::vector<double> velocity_map_; /*!< Auxiliar vector which contains the final velocity map of the environment. */\n\n        int ndims_;\n        double angle_wave, angle_velocity;\n        double diff_angle;\n};\n\n#endif /* FM2DIR_H_*/\n", "meta": {"hexsha": "84581acf8e03c6bd1e057573505f3453bbf52500", "size": 19880, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Btraj/third_party/fast_methods/data/alpha/fm2dir.hpp", "max_stars_repo_name": "JCrime/Park_Inspection", "max_stars_repo_head_hexsha": "524d8286424e363a4bd3d77cf10df8f7eb3c3c6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-08-24T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-28T05:23:42.000Z", "max_issues_repo_path": "fm_Btraj/src/Btraj/third_party/fast_methods/data/alpha/fm2dir.hpp", "max_issues_repo_name": "lvhualong/motion_Planning", "max_issues_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fm_Btraj/src/Btraj/third_party/fast_methods/data/alpha/fm2dir.hpp", "max_forks_repo_name": "lvhualong/motion_Planning", "max_forks_repo_head_hexsha": "ea127de8cd8f32e9994538416d0c74b99054214f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-08-24T08:28:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-19T12:47:20.000Z", "avg_line_length": 42.5695931478, "max_line_length": 197, "alphanum_fraction": 0.5517605634, "num_tokens": 4333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832804, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23694470687472421}}
{"text": "#ifndef GUNEROTRANSACTIONSENDCIRCUIT_H_\n#define GUNEROTRANSACTIONSENDCIRCUIT_H_\n\n#include <deque>\n#include <boost/optional.hpp>\n#include <boost/static_assert.hpp>\n#include <libff/common/utils.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/uscs_ppzksnark/uscs_ppzksnark.hpp>\n#include <libff/algebra/fields/field_utils.hpp>\n#include <libff/algebra/scalar_multiplication/multiexp.hpp>\n#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libff/algebra/curves/edwards/edwards_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp>\n#include <libff/common/utils.hpp>\n\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp>\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_update_gadget.hpp>\n\n#include \"gunerotransactionsend_gadget.hpp\"\n#include \"GuneroProof.hpp\"\n\nusing namespace libsnark;\n\nnamespace gunero {\n\nclass GuneroTransactionSendWitness{\npublic:\n    uint256 W;\n    uint256 T;\n    uint256 V_S;\n    uint256 V_R;\n    uint256 L_P;\n\n    GuneroTransactionSendWitness() {}\n    GuneroTransactionSendWitness(\n        const uint256& pW,\n        const uint256& pT,\n        const uint256& pV_S,\n        const uint256& pV_R,\n        const uint256& pL_P\n    ) : W(pW),\n        T(pT),\n        V_S(pV_S),\n        V_R(pV_R),\n        L_P(pL_P)\n    {\n    }\n    ~GuneroTransactionSendWitness() {}\n\n    ADD_SERIALIZE_METHODS;\n\n    template <typename Stream, typename Operation>\n    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {\n        READWRITE(W);\n        READWRITE(T);\n        READWRITE(V_S);\n        READWRITE(V_R);\n        READWRITE(L_P);\n    }\n\n    friend std::ostream& operator<<(std::ostream &out, const GuneroTransactionSendWitness &witness)\n    {\n        ::Serialize(out, witness, 1, 1);\n\n        return out;\n    }\n\n    friend std::istream& operator>>(std::istream &in, GuneroTransactionSendWitness &witness)\n    {\n        ::Unserialize(in, witness, 1, 1);\n\n        return in;\n    }\n};\n\n///// TRANSACTION SEND PROOF /////\n// With this proof, we are validating that the sender of the token is accepting that this token's ownership should\n// be transferred to the new transaction hash given. The \"account view hash\" validates that this proof is consistent\n// with the others generated, and also serves as an additional precaution for others using this proof to validate an\n// unauthorized release of the token to a party not covered in the transaction.\n// Public Parameters:\n// Current Authorization Root Hash (W)\n// Token UID (T)\n// Sender Account View Hash (V_S)\n// Receiver Account View Hash (V_R)\n// Previous Transaction Hash (L_P)\n\n// Private Parameters:\n// Sender Private Key (s_S)\n// Sender Account View Randomizer (r_S)\n// Receiver Account View Randomizer (r_R)\n// Previous Sender Account Address (A_PS)\n// Previous Authorization Root Hash (W_P)\n// alt: Receiver Proof Public Key (P_proof_R)\n\n//1) Obtain A_S from s_S through EDCSA operations\n//1 alt) Obtain P_proof_S from s_S through PRF operations\n//2) Validate V_S == hash(A_S, hash(W, r_S)) (View Hash is consistent for Sender)\n//2 alt) Validate V_S == hash(P_proof_S, hash(W, r_S)) (View Hash is consistent for Sender)\n//3) Validate V_R == hash(A_R, hash(W, r_R)) (View Hash is consistent for Receiver)\n//3 alt) Validate V_R == hash(P_proof_R, hash(W, r_R)) (View Hash is consistent for Receiver)\n//4) Validate L_P == hash(A_PS, hash(s_S, hash(T, W_P))) (The send proof is valid, sender owns token)\ntemplate<typename FieldT, typename BaseT, typename HashT>\nclass GuneroTransactionSendCircuit\n{\npublic:\n    GuneroTransactionSendCircuit()\n    {}\n    ~GuneroTransactionSendCircuit() {}\n\n    void generate(\n        const std::string& r1csPath,\n        const std::string& pkPath,\n        const std::string& vkPath\n    ) {\n        protoboard<FieldT> pb;\n        gunerotransactionsend_gadget<FieldT, BaseT, HashT> gunero(pb);\n\n        gunero.generate_r1cs_constraints(r1csPath, pkPath, vkPath);\n    }\n\n    bool prove(\n        const uint256& pW,\n        const uint256& pT,\n        const uint256& pV_S,\n        const uint256& pV_R,\n        const uint256& pL_P,\n        const uint252& ps_S,\n        const uint256& pr_S,\n        const uint256& pr_R,\n        const uint160& pA_PS,\n        const uint256& pW_P,\n        const uint256& pP_proof_R,\n        const r1cs_ppzksnark_proving_key<BaseT>& pk,\n        const r1cs_ppzksnark_verification_key<BaseT>& vk,\n        GuneroProof& proof\n    )\n    {\n#ifdef DEBUG\n        libff::print_header(\"Gunero witness (proof)\");\n#endif\n\n        {\n            r1cs_primary_input<FieldT> primary_input;\n            r1cs_auxiliary_input<FieldT> aux_input;\n            {\n                protoboard<FieldT> pb;\n                {\n#ifdef DEBUG\n                    libff::print_header(\"Gunero gunerotransactionsend_gadget.load_r1cs_constraints()\");\n#endif\n\n                    gunerotransactionsend_gadget<FieldT, BaseT, HashT> gunero(pb);\n\n                    gunero.generate_r1cs_witness(\n                        pW,\n                        pT,\n                        pV_S,\n                        pV_R,\n                        pL_P,\n                        ps_S,\n                        pr_S,\n                        pr_R,\n                        pA_PS,\n                        pW_P,\n                        pP_proof_R\n                    );\n\n#ifdef DEBUG\n                    printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after gunerotransactionsend_gadget.load_r1cs_constraints()\"); libff::print_time(\"after gunerotransactionsend_gadget.load_r1cs_constraints()\");\n#endif\n                }\n\n                // The constraint system must be satisfied or there is an unimplemented\n                // or incorrect sanity check above. Or the constraint system is broken!\n                assert(pb.is_satisfied());\n\n                // TODO: These are copies, which is not strictly necessary.\n                primary_input = pb.primary_input();\n                aux_input = pb.auxiliary_input();\n\n                // Swap A and B if it's beneficial (less arithmetic in G2)\n                // In our circuit, we already know that it's beneficial\n                // to swap, but it takes so little time to perform this\n                // estimate that it doesn't matter if we check every time.\n                // pb.constraint_system.swap_AB_if_beneficial();\n\n                //Test witness_map()\n                {\n                    r1cs_primary_input<FieldT> primary_input_test = gunerotransactionsend_gadget<FieldT, BaseT, HashT>::witness_map(\n                        pW,\n                        pT,\n                        pV_S,\n                        pV_R,\n                        pL_P\n                    );\n                    assert(primary_input == primary_input_test);\n                }\n            }\n\n            r1cs_ppzksnark_proof<BaseT> r1cs_proof = r1cs_ppzksnark_prover<BaseT>(\n                pk,\n                primary_input,\n                aux_input\n            );\n\n            proof = GuneroProof(r1cs_proof);\n\n#ifdef DEBUG\n            printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after witness (proof)\"); libff::print_time(\"after witness (proof)\");\n#endif\n        }\n\n        //Verify\n        {\n            r1cs_primary_input<FieldT> primary_input = gunerotransactionsend_gadget<FieldT, BaseT, HashT>::witness_map(\n                pW,\n                pT,\n                pV_S,\n                pV_R,\n                pL_P\n            );\n\n            return r1cs_ppzksnark_verifier_strong_IC<BaseT>(vk, primary_input, proof.to_libsnark_proof<r1cs_ppzksnark_proof<BaseT>>());\n        }\n    }\n\n    bool verify(\n        const uint256& pW,\n        const uint256& pT,\n        const uint256& pV_S,\n        const uint256& pV_R,\n        const uint256& pL_P,\n        const GuneroProof& proof,\n        const r1cs_ppzksnark_verification_key<BaseT>& vk,\n        const r1cs_ppzksnark_processed_verification_key<BaseT>& vk_precomp\n        )\n    {\n        try\n        {\n            r1cs_primary_input<FieldT> primary_input = gunerotransactionsend_gadget<FieldT, BaseT, HashT>::witness_map(\n                pW,\n                pT,\n                pV_S,\n                pV_R,\n                pL_P\n            );\n\n            r1cs_ppzksnark_proof<BaseT> r1cs_proof = proof.to_libsnark_proof<r1cs_ppzksnark_proof<BaseT>>();\n\n            ProofVerifier<BaseT> verifierEnabled = ProofVerifier<BaseT>::Strict();\n\n            bool verified = verifierEnabled.check(\n                vk,\n                vk_precomp,\n                primary_input,\n                r1cs_proof\n            );\n\n            if (verified)\n            {\n                return true;\n            }\n            else\n            {\n                return false;\n            }\n        }\n        catch (...)\n        {\n            return false;\n        }\n    }\n};\n\n} // end namespace `gunero`\n\n#endif /* GUNEROTRANSACTIONSENDCIRCUIT_H_ */", "meta": {"hexsha": "97d6219e1ccc203d2ffb743a11b91e96d7d037c9", "size": 9433, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/GuneroTransactionSendCircuit.hpp", "max_stars_repo_name": "GunClear/Silencer", "max_stars_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-17T22:27:54.000Z", "max_issues_repo_path": "src/GuneroTransactionSendCircuit.hpp", "max_issues_repo_name": "GunClear/Silencer", "max_issues_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T19:57:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-04T15:49:02.000Z", "max_forks_repo_path": "src/GuneroTransactionSendCircuit.hpp", "max_forks_repo_name": "GunClear/Silencer", "max_forks_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.098245614, "max_line_length": 217, "alphanum_fraction": 0.6123184565, "num_tokens": 2344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2369447012810517}}
{"text": "/* CirKit: A circuit toolkit\n * Copyright (C) 2009-2015  University of Bremen\n * Copyright (C) 2015-2017  EPFL\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"exact_toffoli_synthesis.hpp\"\n\n#include <array>\n#include <iostream>\n\n#include <boost/format.hpp>\n\n#include <core/utils/timer.hpp>\n#include <classical/abc/abc_api.hpp>\n#include <reversible/functions/add_gates.hpp>\n#include <reversible/utils/truth_table_helpers.hpp>\n\n#include <sat/bsat/satSolver.h>\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\nclass exact_toffoli_synthesis_manager\n{\npublic:\n  exact_toffoli_synthesis_manager( const binary_truth_table& spec, const properties::ptr& settings );\n\n  void run( circuit& circ );\n\nprivate:\n  /* indexes:\n   *   i    : target, line\n   *   j, k : controls\n   *   l    : gate\n   *   t    : truth table row\n   */\n  int var_offset( int l ) const;\n  int sim_var( int l, int i, int t ) const;\n  int not_var( int l, int i ) const;\n  int cnot_var( int l, int i, int j ) const;\n  int tof_var( int l, int i, int j, int k ) const;\n\n  int equal_other_clauses( int g, int l, int t, int i );\n  int not_clauses( int l, int i, int t );\n  int cnot_clauses( int l, int i, int j, int t );\n  int tof_clauses( int l, int i, int j, int k, int t );\n  int gate_clauses( int l );\n  std::vector<int> spec_assumptions() const;\n  void create_circuit( circuit& circ ) const;\n\n  int symmetry_breaking_ordering( int l );\n  int symmetry_breaking_not_same( int l );\n\n  template<typename ...Lits>\n  int add_clause( Lits... literals )\n  {\n    std::array<int, sizeof...( Lits )> cls = {{ literals... }};\n    int * p = &cls.front();\n    return abc::sat_solver_addclause( solver.get(), p, p + sizeof...( Lits ) );\n  }\n\n  int make_lit( int var, int c ) const;\n\n  /* range helpers */\n  template<typename Fn>\n  void for_each_not( Fn&& f )\n  {\n    for ( auto i = 0u; i < n; ++i )\n    {\n      f( i );\n    }\n  }\n\n  template<typename Fn>\n  void for_each_cnot( Fn&& f )\n  {\n    for ( auto i = 0u; i < n; ++i )\n    {\n      for ( auto j = 1u; j < n; ++j )\n      {\n        f( i, j );\n      }\n    }\n  }\n\n  template<typename Fn>\n  void for_each_tof( Fn&& f )\n  {\n    for ( auto i = 0u; i < n; ++i )\n    {\n      for ( auto j = 2u; j < n; ++j )\n      {\n        for ( auto k = 1u; k < j; ++k )\n        {\n          f( i, j, k );\n        }\n      }\n    }\n  }\n\n  void debug_vars();\n\nprivate:\n  const binary_truth_table& spec;\n  unsigned                  n, r;\n  int                       num_vars_per_gate;\n  int                       sim_offset;\n\n  std::vector<boost::dynamic_bitset<>> spec_vec;\n\n  /* solver */\n  std::unique_ptr<abc::sat_solver, void(*)(abc::sat_solver*)> solver;\n\n  /* settings */\n  bool verbose = false;\n};\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\nexact_toffoli_synthesis_manager::exact_toffoli_synthesis_manager( const binary_truth_table& spec, const properties::ptr& settings )\n  : spec( spec ),\n    n( spec.num_inputs() ),\n    solver( abc::sat_solver_new(), abc::sat_solver_delete ),\n    verbose( get( settings, \"verbose\", verbose ) )\n{\n  /* we have:\n     - 2^n             sim vars\n     - n               NOT vars\n     - n(n-1)          CNOT vars\n     - n(n-1)(n-2) / 2 TOF vars\n  */\n  num_vars_per_gate = n * ( 1 << n ) + n + n * ( n - 1 ) + n * ( ( n - 1 ) * ( n - 2 ) ) / 2;\n  sim_offset = n * ( 1 << n );\n\n  spec_vec = truth_table_to_bitset_vector( spec );\n}\n\nvoid exact_toffoli_synthesis_manager::run( circuit& circ )\n{\n  r = 0;\n  auto nvars = 0;\n  abc::sat_solver_restart( solver.get() );\n\n  while ( true )\n  {\n    ++r;\n    nvars += num_vars_per_gate;\n\n    std::cout << \"[i] try to find optimum circuit with \" << r << \" gates\" << std::endl;\n\n    abc::sat_solver_setnvars( solver.get(), nvars );\n\n    gate_clauses( r - 1 );\n\n    if ( r > 1 )\n    {\n      symmetry_breaking_ordering( r - 1 );\n      symmetry_breaking_not_same( r - 1 );\n    }\n    auto assump = spec_assumptions();\n    int * p = &assump.front();\n\n    const auto result = abc::sat_solver_solve( solver.get(), p, p + assump.size(), 0, 0, 0, 0 );\n\n    if ( result == 1 ) /* SAT */\n    {\n      std::cout << \"[i] found circuit with \" << r << \" gates\" << std::endl;\n      create_circuit( circ );\n      return;\n    }\n  }\n\n  assert( false );\n}\n\ninline int exact_toffoli_synthesis_manager::var_offset( int l ) const\n{\n  assert( l < static_cast<int>( r ) );\n\n  return l * num_vars_per_gate;\n}\n\ninline int exact_toffoli_synthesis_manager::sim_var( int l, int i, int t ) const\n{\n  assert( l < static_cast<int>( r ) );\n  assert( i < static_cast<int>( n ) );\n  assert( t < static_cast<int>( 1u << n ) );\n\n  return var_offset( l ) + i * ( 1 << n ) + t;\n}\n\ninline int exact_toffoli_synthesis_manager::not_var( int l, int i ) const\n{\n  assert( l < static_cast<int>( r ) );\n  assert( i < static_cast<int>( n ) );\n\n  return var_offset( l ) + sim_offset + i;\n}\n\ninline int exact_toffoli_synthesis_manager::cnot_var( int l, int i, int j ) const\n{\n  assert( l < static_cast<int>( r ) );\n  assert( i < static_cast<int>( n ) );\n  assert( j > 0 && j < static_cast<int>( n ) );\n\n  return var_offset( l ) + sim_offset + n + i * ( n - 1 ) + j - 1;\n}\n\ninline int exact_toffoli_synthesis_manager::tof_var( int l, int i, int j, int k ) const\n{\n  assert( l < static_cast<int>( r ) );\n  assert( i < static_cast<int>( n ) );\n  assert( j > 1 && j < static_cast<int>( n ) );\n  assert( k > 0 && k < static_cast<int>( j ) );\n\n  auto offset = var_offset( l ) + sim_offset + n + n * ( n - 1 );\n  offset += i * ( ( n - 2 ) * ( n - 1 ) ) / 2; /* offset based on target */\n  offset += ( ( j - 2 ) * ( j - 1 ) ) / 2; /* right j entry */\n\n  return offset + k - 1;\n}\n\ninline int exact_toffoli_synthesis_manager::equal_other_clauses( int g, int l, int t, int i )\n{\n  for ( auto ii = 0u; ii < n; ++ii )\n  {\n    if ( static_cast<int>( ii ) == i ) continue;\n\n    if ( l == 0 )\n    {\n      const auto bit = ( t >> ii ) & 1;\n      add_clause( make_lit( g, 1 ), make_lit( sim_var( l, ii, t ), 1 - bit ) );\n    }\n    else\n    {\n      add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, ii, t ), 0 ), make_lit( sim_var( l, ii, t ), 1 ) );\n      add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, ii, t ), 1 ), make_lit( sim_var( l, ii, t ), 0 ) );\n    }\n  }\n\n  return 1;\n}\n\nint exact_toffoli_synthesis_manager::not_clauses( int l, int i, int t )\n{\n  const auto g = not_var( l, i );\n  equal_other_clauses( g, l, t, i );\n\n  if ( l == 0 )\n  {\n    const auto bit = ( t >> i ) & 1;\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l, i, t ), bit ) );\n  }\n  else\n  {\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 0 ), make_lit( sim_var( l, i, t ), 0 ) );\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 1 ), make_lit( sim_var( l, i, t ), 1 ) );\n  }\n\n  return 1;\n}\n\nint exact_toffoli_synthesis_manager::cnot_clauses( int l, int i, int j, int t )\n{\n  const auto g = cnot_var( l, i, j );\n  equal_other_clauses( g, l, t, i );\n\n  const auto c1 = ( i + j ) % n;\n\n  if ( l == 0 )\n  {\n    const auto tbit = ( t >> i ) & 1;\n    const auto cbit = ( t >> c1 ) & 1;\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l, i, t ), tbit == cbit ) );\n  }\n  else\n  {\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 0 ), make_lit( sim_var( l - 1, c1, t ), 0 ), make_lit( sim_var( l, i, t ), 1 ) );\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 0 ), make_lit( sim_var( l - 1, c1, t ), 1 ), make_lit( sim_var( l, i, t ), 0 ) );\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 1 ), make_lit( sim_var( l - 1, c1, t ), 0 ), make_lit( sim_var( l, i, t ), 0 ) );\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 1 ), make_lit( sim_var( l - 1, c1, t ), 1 ), make_lit( sim_var( l, i, t ), 1 ) );\n  }\n\n  return 1;\n}\n\nint exact_toffoli_synthesis_manager::tof_clauses( int l, int i, int j, int k, int t )\n{\n  const auto g = tof_var( l, i, j, k );\n  equal_other_clauses( g, l, t, i );\n\n  const auto c1 = ( i + j ) % n;\n  const auto c2 = ( i + k ) % n;\n\n  if ( l == 0 )\n  {\n    const auto tbit = ( t >> i ) & 1;\n    const auto cbit1 = ( t >> c1 ) & 1;\n    const auto cbit2 = ( t >> c2 ) & 1;\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l, i, t ), tbit == ( cbit1 && cbit2 ) ) );\n  }\n  else\n  {\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 1 ), make_lit( sim_var( l - 1, c1, t ), 0 ), make_lit( sim_var( l, i, t ), 0 ) );\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 0 ), make_lit( sim_var( l - 1, c1, t ), 0 ), make_lit( sim_var( l, i, t ), 1 ) );\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 1 ), make_lit( sim_var( l - 1, c2, t ), 0 ), make_lit( sim_var( l, i, t ), 0 ) );\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 0 ), make_lit( sim_var( l - 1, c2, t ), 0 ), make_lit( sim_var( l, i, t ), 1 ) );\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 1 ), make_lit( sim_var( l - 1, c1, t ), 1 ), make_lit( sim_var( l - 1, c2, t ), 1 ), make_lit( sim_var( l, i, t ), 1 ) );\n    add_clause( make_lit( g, 1 ), make_lit( sim_var( l - 1, i, t ), 0 ), make_lit( sim_var( l - 1, c1, t ), 1 ), make_lit( sim_var( l - 1, c2, t ), 1 ), make_lit( sim_var( l, i, t ), 0 ) );\n  }\n\n  return 1;\n}\n\nint exact_toffoli_synthesis_manager::symmetry_breaking_ordering( int l )\n{\n  /* no CNOT( i, j ) before NOT( i ) */\n  for_each_cnot( [this, l]( int i, int j ) {\n      add_clause( make_lit( not_var( l, i ), 1 ), make_lit( cnot_var( l - 1, i, j ), 1 ) );\n    } );\n  /* no TOF( i, j, k ) before NOT( i ) */\n  for_each_tof( [this, l]( int i, int j, int k ) {\n      add_clause( make_lit( not_var( l, i ), 1 ), make_lit( tof_var( l - 1, i, j, k ), 1 ) );\n    } );\n  /* order CNOTs with same target */\n  for_each_cnot( [this, l]( int i, int j ) {\n      for ( auto jj = 1; jj < j; ++jj )\n      {\n        add_clause( make_lit( cnot_var( l, i, j ), 1 ), make_lit( cnot_var( l - 1, i, jj ), 1 ) );\n      }\n    } );\n  /* order of TOFs with same target */\n  for_each_tof( [this, l]( int i, int j, int k ) {\n      for ( auto jj = 2; jj < j; ++jj )\n      {\n        for ( auto kk = 1; kk < jj; ++kk )\n        {\n          add_clause( make_lit( tof_var( l, i, j, k ), 1 ), make_lit( tof_var( l - 1, i, jj, kk ), 1 ) );\n        }\n      }\n      for ( auto kk = 1; kk < j; ++kk )\n      {\n        add_clause( make_lit( tof_var( l, i, j, k ), 1 ), make_lit( tof_var( l - 1, i, j, kk ), 1 ) );\n      }\n    } );\n  /* no CNOT( i, j ) before NOT( i' ) where i' not in {i, j} */\n  for_each_cnot( [this, l]( int i, int j ) {\n      for ( auto ii = 0u; ii < n; ++ii )\n      {\n        if ( static_cast<int>( ii ) == i || ii == ( ( i + j ) % n ) ) { continue; }\n        add_clause( make_lit( not_var( l, ii ), 1 ), make_lit( cnot_var( l - 1, i, j ), 1 ) );\n      }\n    } );\n  /* no TOF( i, j, k ) before NOT( i' ) where i' not in {i, j, k} */\n  for_each_tof( [this, l]( int i, int j, int k ) {\n      for ( auto ii = 0u; ii < n; ++ii )\n      {\n        if ( static_cast<int>( ii ) == i || ii == ( ( i + j ) % n ) || ii == ( ( i + k ) % n ) ) { continue; }\n        add_clause( make_lit( not_var( l, ii ), 1 ), make_lit( tof_var( l - 1, i, j, k ), 1 ) );\n      }\n    } );\n\n  return 1;\n}\n\nint exact_toffoli_synthesis_manager::symmetry_breaking_not_same( int l )\n{\n  for_each_not( [this, l]( int i ) {\n      add_clause( make_lit( not_var( l, i ), 1 ), make_lit( not_var( l - 1, i ), 1 ) );\n    } );\n  for_each_cnot( [this, l]( int i, int j ) {\n      add_clause( make_lit( cnot_var( l, i, j ), 1 ), make_lit( cnot_var( l - 1, i, j ), 1 ) );\n    } );\n  for_each_tof( [this, l]( int i, int j, int k ) {\n      add_clause( make_lit( tof_var( l, i, j, k ), 1 ), make_lit( tof_var( l - 1, i, j, k ), 1 ) );\n    } );\n\n  return 1;\n}\n\nvoid exact_toffoli_synthesis_manager::debug_vars()\n{\n  for ( auto l = 0u; l < r; ++l )\n  {\n    for ( auto i = 0u; i < n; ++i )\n    {\n      for ( auto t = 0u; t < ( 1u << n ); ++t )\n      {\n        std::cout << boost::format( \"%6d sim_var( %d, %d, %d )\" ) % sim_var( l, i, t ) % l % i % t << std::endl;\n      }\n    }\n\n    for ( auto i = 0u; i < n; ++i )\n    {\n      std::cout << boost::format( \"%6d not_var( %d, %d )\" ) % not_var( l, i ) % l % i << std::endl;\n    }\n\n    for ( auto i = 0u; i < n; ++i )\n    {\n      for ( auto j = 1u; j < n; ++j )\n      {\n        std::cout << boost::format( \"%6d cnot_var( %d, %d, %d )\" ) % cnot_var( l, i, j ) % l % i % j << std::endl;\n      }\n    }\n\n    for ( auto i = 0u; i < n; ++i )\n    {\n      for ( auto j = 2u; j < n; ++j )\n      {\n        for ( auto k = 1u; k < j; ++k )\n        {\n          std::cout << boost::format( \"%6d tof_var( %d, %d, %d, %d )\" ) % tof_var( l, i, j, k ) % l % i % j % k << std::endl;\n        }\n      }\n    }\n  }\n}\n\nint exact_toffoli_synthesis_manager::gate_clauses( int l )\n{\n  for ( auto t = 0u; t < ( 1u << n ); ++t )\n  {\n    for_each_not( [this, l, t]( int i ) { not_clauses( l, i, t ); } );\n    for_each_cnot( [this, l, t]( int i, int j ) { cnot_clauses( l, i, j, t ); } );\n    for_each_tof( [this, l, t]( int i, int j, int k ) { tof_clauses( l, i, j, k, t ); } );\n  }\n\n  /* at least one gate */\n  std::vector<int> gates;\n\n  for ( auto i = 0u; i < n; ++i )\n  {\n    gates.push_back( make_lit( not_var( l, i ), 0 ) );\n\n    for ( auto j = 1u; j < n; ++j )\n    {\n      gates.push_back( make_lit( cnot_var( l, i, j ), 0 ) );\n\n      for ( auto k = 1u; k < j; ++k )\n      {\n        gates.push_back( make_lit( tof_var( l, i, j, k ), 0 ) );\n      }\n    }\n  }\n\n  int * p = &gates.front();\n  abc::sat_solver_addclause( solver.get(), p, p + gates.size() );\n\n  return 1;\n}\n\nstd::vector<int> exact_toffoli_synthesis_manager::spec_assumptions() const\n{\n  std::vector<int> assumptions;\n  assumptions.reserve(  sim_offset );\n\n  for ( auto i = 0u; i < n; ++i )\n  {\n    for ( auto t = 0u; t < ( 1u << n ); ++t )\n    {\n      assumptions.push_back( make_lit( sim_var( r - 1, i, t ), spec_vec[t][i] ? 0 : 1 ) );\n    }\n  }\n\n  return assumptions;\n}\n\nvoid exact_toffoli_synthesis_manager::create_circuit( circuit& circ ) const\n{\n  circ.set_lines( n );\n\n  for ( auto l = 0u; l < r; ++l )\n  {\n    auto added = false;\n\n    for ( auto i = 0u; i < n; ++i )\n    {\n      if ( abc::sat_solver_var_value( solver.get(), not_var( l, i ) ) )\n      {\n        if ( !added )\n        {\n          added = true;\n          append_not( circ, n - i - 1 );\n        }\n        else { std::cout << \"[w] alternative gate found\" << std::endl; }\n      }\n\n      for ( auto j = 1u; j < n; ++j )\n      {\n        if ( abc::sat_solver_var_value( solver.get(), cnot_var( l, i, j ) ) )\n        {\n          if ( !added )\n          {\n            added = true;\n            append_cnot( circ, n - ( ( i + j ) % n ) - 1, n - i - 1 );\n          }\n          else { std::cout << \"[w] alternative gate found\" << std::endl; }\n        }\n\n        for ( auto k = 1u; k < j; ++k )\n        {\n          if ( abc::sat_solver_var_value( solver.get(), tof_var( l, i, j, k ) ) )\n          {\n            if ( !added )\n            {\n              added = true;\n              append_toffoli( circ )( n - ( ( i + k ) % n ) - 1, n - ( ( i + j ) % n ) - 1 )( n - i - 1 );\n            }\n            else { std::cout << \"[w] alternative gate found\" << std::endl; }\n          }\n        }\n      }\n    }\n  }\n}\n\ninline int exact_toffoli_synthesis_manager::make_lit( int var, int c ) const\n{\n  return abc::Abc_Var2Lit( var, c );\n}\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nbool exact_toffoli_synthesis( circuit& circ, const binary_truth_table& spec, const properties::ptr& settings, const properties::ptr& statistics )\n{\n  properties_timer t( statistics );\n\n  exact_toffoli_synthesis_manager mgr( spec, settings );\n\n  mgr.run( circ );\n\n  return true;\n}\n\n}\n\n// Local Variables:\n// c-basic-offset: 2\n// eval: (c-set-offset 'substatement-open 0)\n// eval: (c-set-offset 'innamespace 0)\n// End:\n", "meta": {"hexsha": "0c401a98cd071d685fa00b3bb4dc240c40c561f7", "size": 17404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/exact_toffoli_synthesis.cpp", "max_stars_repo_name": "eletesta/cirkit", "max_stars_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/exact_toffoli_synthesis.cpp", "max_issues_repo_name": "eletesta/cirkit", "max_issues_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "addons/cirkit-addon-reversible/src/reversible/synthesis/exact_toffoli_synthesis.cpp", "max_forks_repo_name": "eletesta/cirkit", "max_forks_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_forks_repo_licenses": ["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.4798598949, "max_line_length": 189, "alphanum_fraction": 0.51861641, "num_tokens": 5767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23694470128105166}}
{"text": "// Copyright (c) 2013 Vasili Baranau\n// Distributed under the MIT software license\n// See the accompanying file License.txt or http://opensource.org/licenses/MIT\n\n#include \"GenerationManager.h\"\n\n#include <algorithm>\n#include <boost/shared_ptr.hpp>\n#include \"Core/Headers/Path.h\"\n#include \"Core/Headers/StlUtilities.h\"\n#include \"Core/Headers/Math.h\"\n#include \"Model/Headers/Config.h\"\n\n#include \"PackingServices/Headers/MathService.h\"\n#include \"PackingServices/Headers/PackingSerializer.h\"\n#include \"PackingServices/Headers/GeometryService.h\"\n#include \"PackingServices/Headers/ImmobileParticlesService.h\"\n\n#include \"PackingServices/PostProcessing/Headers/InsertionRadiiGenerator.h\"\n#include \"PackingServices/PostProcessing/Headers/HessianService.h\"\n#include \"PackingServices/PostProcessing/Headers/PressureService.h\"\n#include \"PackingServices/PostProcessing/Headers/RattlerRemovalService.h\"\n#include \"PackingServices/PostProcessing/Headers/MolecularDynamicsService.h\"\n\n#include \"PackingServices/EnergyServices/Headers/HarmonicPotential.h\"\n#include \"PackingServices/EnergyServices/Headers/IEnergyService.h\"\n\n#include \"PackingServices/DistanceServices/Headers/DistanceService.h\"\n\n#include \"Geometries/Headers/BulkGeometry.h\"\n#include \"Geometries/Headers/CircleGeometry.h\"\n#include \"Geometries/Headers/RectangleGeometry.h\"\n#include \"Geometries/Headers/TrapezoidGeometry.h\"\n\n#include \"PackingGenerators/InitialGenerators/Headers/BulkPoissonGenerator.h\"\n#include \"PackingGenerators/InitialGenerators/Headers/BulkPoissonInCellsGenerator.h\"\n#include \"PackingGenerators/InitialGenerators/Headers/HcpGenerator.h\"\n\n#include \"PackingGenerators/Headers/IPackingGenerator.h\"\n\nusing namespace std;\nusing namespace Geometries;\nusing namespace PackingServices;\nusing namespace PackingGenerators;\nusing namespace Model;\nusing namespace Core;\n\nnamespace Generation\n{\n    GenerationManager::GenerationManager(PackingSerializer* packingSerializer,\n            IPackingGenerator* packingGenerator,\n            InsertionRadiiGenerator* insertionRadiiGenerator,\n            DistanceService* distanceService,\n            OrderService* orderService,\n            IEnergyService* contractionEnergyService,\n            HessianService* hessianService,\n            PressureService* pressureService,\n            MolecularDynamicsService* molecularDynamicsService,\n            RattlerRemovalService* rattlerRemovalService,\n            ImmobileParticlesService* immobileParticlesService)\n    {\n        this->packingSerializer = packingSerializer;\n        this->packingGenerator = packingGenerator;\n        this->insertionRadiiGenerator = insertionRadiiGenerator;\n        this->distanceService = distanceService;\n        this->orderService = orderService;\n        this->contractionEnergyService = contractionEnergyService;\n        this->hessianService = hessianService;\n        this->pressureService = pressureService;\n        this->molecularDynamicsService = molecularDynamicsService;\n        this->rattlerRemovalService = rattlerRemovalService;\n        this->immobileParticlesService = immobileParticlesService;\n\n        innerDiameterRatio = 1.0;\n    }\n\n    void GenerationManager::GeneratePacking(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, PACKING_FILE_NAME, false, false, &GenerationManager::GeneratePacking);\n    }\n\n    void GenerationManager::GenerateInsertionRadii(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, INSERTION_RADII_FILE_NAME, true, true, &GenerationManager::GenerateInsertionRadii);\n    }\n\n    void GenerationManager::CalculateDistancesToClosestSurfaces(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, DISTANCES_TO_CLOSEST_SURFACES_FOLDER_NAME, true, true, &GenerationManager::CalculateDistancesToClosestSurfaces);\n    }\n\n    void GenerationManager::CalculateContactNumberDistribution(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, CONTACT_NUMBER_DISTRIBUTION_FILE_NAME, true, true, &GenerationManager::CalculateContactNumberDistribution);\n    }\n\n    void GenerationManager::CalculateEntropy(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, ENTROPY_FILE_NAME, true, true, &GenerationManager::CalculateEntropy);\n    }\n\n    void GenerationManager::CalculateDirections(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, PARTICLE_DIRECTIONS_FILE_NAME, true, true, &GenerationManager::CalculateDirections);\n    }\n\n    void GenerationManager::CalculateContractionEnergies(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, CONTRACTION_ENERGIES_FILE_NAME, true, true, &GenerationManager::CalculateContractionEnergies);\n    }\n\n    void GenerationManager::GenerateOrder(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, ORDER_FILE_NAME, true, true, &GenerationManager::GenerateOrder);\n    }\n\n    void GenerationManager::CalculateHessianEigenvalues(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, HESSIAN_EIGENVALUES_FILE_NAME, true, true, &GenerationManager::CalculateHessianEigenvalues);\n    }\n\n    void GenerationManager::CalculatePressures(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, PRESSURES_FILE_NAME, true, true, &GenerationManager::CalculatePressures);\n    }\n\n    void GenerationManager::CalculateMolecularDynamicsStatistics(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, MOLECULAR_DYNAMICS_STATISTICS_FILE_NAME, true, true, &GenerationManager::CalculateMolecularDynamicsStatistics);\n    }\n\n    void GenerationManager::RemoveRattlers(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, \"\", false, true, &GenerationManager::RemoveRattlers);\n    }\n\n    void GenerationManager::CalculatePairCorrelationFunction(const Model::ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, PAIR_CORRELATION_FUNCTION_FILE_NAME, true, true, &GenerationManager::CalculatePairCorrelationFunction);\n    }\n\n    void GenerationManager::CalculateStructureFactor(const Model::ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, STRUCTURE_FACTOR_FILE_NAME, true, true, &GenerationManager::CalculateStructureFactor);\n    }\n\n    void GenerationManager::GenerateLocalOrientationalDisorder(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, LOCAL_ORIENTATIONAL_DISORDER_FILE_NAME, true, true, &GenerationManager::GenerateLocalOrientationalDisorder);\n    }\n\n    void GenerationManager::CalculateImmediateMolecularDynamicsStatistics(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, IMMEDIATE_MOLECULAR_DYNAMICS_STATISTICS_FILE_NAME, true, true, &GenerationManager::CalculateImmediateMolecularDynamicsStatistics);\n    }\n\n    void GenerationManager::CalculateNearestNeighbors(const ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, NEAREST_NEIGHBORS_FILE_NAME, true, true, &GenerationManager::CalculateNearestNeighbors);\n    }\n\n    void GenerationManager::CalculateActiveGeometry(const Model::ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, ACTIVE_GEOMETRY_FILE_NAME, true, true, &GenerationManager::CalculateActiveGeometry);\n    }\n\n    void GenerationManager::CalculateSuccessfulPermutationProbability(const Model::ExecutionConfig& userConfig)\n    {\n        ExecuteAlgorithm(userConfig, SUCCESSFUL_PERMUTATION_PROBABILITY_FILE_NAME, true, true, &GenerationManager::CalculateSuccessfulPermutationProbability);\n    }\n\n    void GenerationManager::ExecuteAlgorithm(const ExecutionConfig& userConfig, string targetFileName,\n            bool shouldExitIfTargetFileExists, bool shouldAlwaysReadPacking, Action algorithm)\n    {\n        string targetFilePath = Path::Append(userConfig.generationConfig.baseFolder, targetFileName);\n        if (shouldExitIfTargetFileExists && Path::Exists(targetFilePath))\n        {\n            return;\n        }\n\n        ExecutionConfig fullConfig;\n        FillFullConfig(userConfig, &fullConfig);\n\n        Math::SetSeed(fullConfig.generationConfig.seed);\n        boost::shared_ptr<IGeometry> geometry = CreateGeometry(fullConfig.systemConfig);\n\n        SystemConfig activeConfig;\n        boost::shared_ptr<IGeometry> activeGeometry;\n        string activeConfigPath = Path::Append(fullConfig.generationConfig.baseFolder, ACTIVE_GEOMETRY_FILE_NAME);\n        if (Path::Exists(activeConfigPath))\n        {\n            SpatialVector shift;\n            packingSerializer->ReadActiveConfig(activeConfigPath, &activeConfig, &shift);\n            activeConfig.MergeWith(fullConfig.systemConfig);\n\n            activeGeometry = CreateGeometry(activeConfig, shift);\n        }\n\n        ModellingContext context(&fullConfig.systemConfig, geometry.get(), activeGeometry.get());\n\n        packingGenerator->SetContext(context);\n        insertionRadiiGenerator->SetContext(context);\n        distanceService->SetContext(context);\n        orderService->SetContext(context);\n        contractionEnergyService->SetContext(context);\n        hessianService->SetContext(context);\n        pressureService->SetContext(context);\n        molecularDynamicsService->SetContext(context);\n        rattlerRemovalService->SetContext(context);\n\n        Packing particles;\n        ReadOrCreatePacking(fullConfig, context, shouldAlwaysReadPacking, &particles);\n\n        (this->*algorithm)(fullConfig, context, targetFilePath, &particles);\n    }\n\n    // Actions for corresponding algorithms\n\n    void GenerationManager::GeneratePacking(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        string infoFile = Path::Append(fullConfig.generationConfig.baseFolder, PACKING_FILE_NAME_NFO);\n        if (Path::Exists(infoFile))\n        {\n            return;\n        }\n\n//        // A quick fix for Matthias packings\n//        Packing& particlesRef = *particles;\n//        string nearestNeighbotsPath = Path::Append(fullConfig.generationConfig.baseFolder, NEAREST_NEIGHBORS_FILE_NAME);\n//        if (Path::Exists(nearestNeighbotsPath))\n//        {\n//            vector<ParticlePair> closestPairs;\n//            packingSerializer->ReadNearestNeighbors(nearestNeighbotsPath, &closestPairs);\n//            for (size_t i = 0; i < closestPairs.size(); ++i)\n//            {\n//                bool radiusCorrect = closestPairs[i].normalizedDistanceSquare > 0.95;\n//                particlesRef[closestPairs[i].firstParticleIndex].isImmobile = radiusCorrect;\n//                particlesRef[closestPairs[i].secondParticleIndex].isImmobile = radiusCorrect;\n//            }\n//        }\n\n        packingGenerator->SetGenerationConfig(fullConfig.generationConfig);\n        packingGenerator->ArrangePacking(particles);\n\n        // TODO: Think about writing info file here.\n        // TODO: Think on renaming the folder, updating the generation config, rescaling the packing, updating the info file according to the innerDiameterRatio here.\n        packingSerializer->SerializePacking(targetFilePath, *particles);\n\n        innerDiameterRatio = packingGenerator->GetFinalInnerDiameterRatio();\n        string contractionEnergiesFilePath = Path::Append(fullConfig.generationConfig.baseFolder, CONTRACTION_ENERGIES_FILE_NAME);\n        CalculateContractionEnergies(fullConfig, context, contractionEnergiesFilePath, particles);\n\n        innerDiameterRatio = 1.0;\n    }\n\n    void GenerationManager::GenerateInsertionRadii(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        vector<FLOAT_TYPE> insertionRadii;\n        insertionRadiiGenerator->FillInsertionRadii(*particles, fullConfig.generationConfig.insertionRadiiCount, &insertionRadii);\n        packingSerializer->SerializeInsertionRadii(targetFilePath, insertionRadii);\n    }\n\n    void GenerationManager::CalculateDistancesToClosestSurfaces(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFolderPath, Packing* particles)\n    {\n        vector<int> surfaceIndexes;\n        vector<vector<FLOAT_TYPE> > distancesToSurfaces;\n\n        int minNeighborsCount = 2; // Now: some number to ensure that we have all the numbers consecutively. Before: contractionEnergyService->GetMinNeighborsCount(); // average neighbors count in mechanically stable packings with infinite friction\n        int maxNeighborsCount = 14; // max number of contacts in monodisperse packings\n        int minSurfaceIndex = minNeighborsCount - 1;\n        int surfaceIndexesCount = maxNeighborsCount - minNeighborsCount + 1;\n        surfaceIndexes.resize(surfaceIndexesCount);\n        VectorUtilities::FillLinearScale(minSurfaceIndex, &surfaceIndexes);\n        surfaceIndexes.insert(surfaceIndexes.begin(), 0);\n\n        insertionRadiiGenerator->FillDistancesToSurfaces(*particles, fullConfig.generationConfig.insertionRadiiCount, surfaceIndexes, targetFolderPath, *packingSerializer);\n    }\n\n    void GenerationManager::CalculateContactNumberDistribution(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        printf(\"Calculating contact number distributions\\n\");\n        Packing& packingToUse = *particles;\n\n        // just make sure that the closest pair touches\n        //ClosestPairProvider \n        distanceService->SetParticles(*particles);\n        ParticlePair closestPair = distanceService->FindClosestPair();\n        FLOAT_TYPE closestNormalizedDistance = std::sqrt(closestPair.normalizedDistanceSquare);\n        printf(\"Normalized distance of a closest pair is %f\\n\", closestNormalizedDistance);\n        if (closestNormalizedDistance > 1.0001)\n        {\n            printf(\"Min normalized distance is too high, parcking was probably not rescaled to the final density. Rescaling before contacts calculation...\\n\");\n            Packing rescaledParticles = *particles;\n            for (Particle& p : rescaledParticles)\n            {\n                p.diameter *= closestNormalizedDistance;\n            }\n            packingToUse = rescaledParticles;\n        }\n\n        FLOAT_TYPE contractionRate = 1.0 - 1e-4;\n        vector<int> neighborCounts;\n        vector<int> neighborCountFrequencies;\n        vector<vector<int>> touchingParticleIndexes;\n        contractionEnergyService->SetParticles(packingToUse);\n        FLOAT_TYPE estimatedCoordinationNumber = insertionRadiiGenerator->GetContactNumberDistribution(packingToUse, contractionEnergyService,\n                contractionRate, &neighborCounts, &neighborCountFrequencies, &touchingParticleIndexes);\n\n        printf(\"Estimated coordination number is %f\\n\", estimatedCoordinationNumber);\n\n        packingSerializer->SerializeContactNumberDistribution(targetFilePath, neighborCounts, neighborCountFrequencies);\n\n        string targetFolder = Core::Path::GetParentPath(targetFilePath);\n        string contactNumbersFilePath = Core::Path::Append(targetFolder, CONTACTING_NEIGHBORS_FILE_NAME);\n        packingSerializer->SerializeContactingNeighborIndexes(contactNumbersFilePath, touchingParticleIndexes);\n\n        vector<FLOAT_TYPE> normalizedContactingNeighborDistances;\n        insertionRadiiGenerator->FillNormalizedContactingNeighborDistances(packingToUse, touchingParticleIndexes, &normalizedContactingNeighborDistances);\n\n        string contactingNeighborDistancesFilePath = Core::Path::Append(targetFolder, CONTACTING_NEIGHBOR_DISTANCES_FILE_NAME);\n        packingSerializer->SerializeContactingNeighborDistances(contactingNeighborDistancesFilePath, normalizedContactingNeighborDistances);\n\n//        FLOAT_TYPE expectedCoordinationNumber = GetExpectedCoordinationNumber(fullConfig, context, targetFilePath, particles);\n//        // Find the best contraction rate to get this coordination number\n//        FLOAT_TYPE contractionRate = insertionRadiiGenerator->GetContractionRateForCoordinationNumber(contractionEnergyService, expectedCoordinationNumber);\n//\n//        // Find coordination numbers distribution\n//        vector<int> neighborCounts;\n//        vector<int> neighborCountFrequencies;\n//        FLOAT_TYPE estimatedCoordinationNumber = insertionRadiiGenerator->GetContactNumberDistribution(*particles, contractionEnergyService, contractionRate, &neighborCounts, &neighborCountFrequencies);\n//        if (std::abs(estimatedCoordinationNumber - expectedCoordinationNumber) > 1e-2)\n//        {\n//            printf(\"Coordination number estimated incorrectly\\n\");\n//        }\n//\n//        packingSerializer->SerializeContactNumberDistribution(targetFilePath, neighborCounts, neighborCountFrequencies);\n    }\n\n    FLOAT_TYPE GenerationManager::GetExpectedCoordinationNumber(const Model::ExecutionConfig& fullConfig, const Model::ModellingContext& context, std::string targetFilePath, Model::Packing* particles) const\n    {\n        string energyFilePath = Path::Append(Path::GetParentPath(targetFilePath), CONTRACTION_ENERGIES_FILE_NAME);\n        if (!Path::Exists(energyFilePath))\n        {\n            throw InvalidOperationException(\"Contraction energy file does not exist.\");\n        }\n        contractionEnergyService->SetParticles(*particles);\n\n        // Read coordination numbers from file\n        vector<FLOAT_TYPE> contractionRatios;\n        vector<FLOAT_TYPE> energyPowers;\n        vector<FLOAT_TYPE> contractionEnergies;\n        vector<int> nonRattlersCounts;\n        packingSerializer->ReadContractionEnergies(energyFilePath, &contractionRatios, &energyPowers, &contractionEnergies, &nonRattlersCounts);\n\n        // Find expected coordination number\n        FLOAT_TYPE expectedCoordinationNumber = 0;\n        for (size_t i = 0; i < contractionRatios.size(); ++i)\n        {\n            if (energyPowers[i] > 0)\n            {\n                expectedCoordinationNumber = contractionEnergies[i - 1] / nonRattlersCounts[i - 1];\n                break;\n            }\n        }\n\n        return expectedCoordinationNumber;\n    }\n\n    void GenerationManager::CalculateEntropy(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        FLOAT_TYPE entropy = insertionRadiiGenerator->CalculateEntropy(*particles, fullConfig.generationConfig.insertionRadiiCount);\n        packingSerializer->SerializeEntropy(targetFilePath, entropy);\n\n//        vector<FLOAT_TYPE> localEntropies;\n//        FLOAT_TYPE entropy = insertionRadiiGenerator->CalculateLocalEntropies(particles, fullConfig->generationConfig.insertionRadiiCount, &localEntropies);\n//        packingSerializer->SerializeLocalEntropy(targetFilePath, entropy, &localEntropies);\n    }\n\n    void GenerationManager::CalculateDirections(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        vector<OrderService::NeighborDirections> particleDirections;\n        orderService->SetParticles(*particles);\n        orderService->FillParticleDirections(&particleDirections);\n        packingSerializer->SerializeParticleDirections(targetFilePath, fullConfig.systemConfig.particlesCount, particleDirections);\n    }\n\n    void GenerationManager::CalculateContractionEnergies(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        printf(\"Calculating contraction energies\\n\");\n\n        vector<FLOAT_TYPE> contractionRatios;\n        FillContractionRatios(&contractionRatios);\n        int count = contractionRatios.size();\n        vector<FLOAT_TYPE> fullContractionRatios;\n\n        // Copy contraction rates twice\n        StlUtilities::Append(contractionRatios, &fullContractionRatios);\n        StlUtilities::Append(contractionRatios, &fullContractionRatios);\n\n        const HarmonicPotential zeroPotential(0.0);\n        const HarmonicPotential secondPotential(2.0);\n\n        vector<const IPairPotential*> fullPotentials(count, &zeroPotential);\n        vector<const IPairPotential*> potentials(count, &secondPotential);\n        StlUtilities::Append(potentials, &fullPotentials);\n\n        // Rescale the contraction ratios according to the final innerDiameterRatio (this method may be called after packing generation).\n        vector<FLOAT_TYPE> rescaledContractionRatios;\n        for (vector<FLOAT_TYPE>::iterator it = fullContractionRatios.begin(); it != fullContractionRatios.end(); ++it)\n        {\n            FLOAT_TYPE contractionRatio = *it;\n            rescaledContractionRatios.push_back(contractionRatio / innerDiameterRatio);\n        }\n\n        contractionEnergyService->SetParticles(*particles);\n        IEnergyService::EnergiesResult result = contractionEnergyService->GetContractionEnergies(rescaledContractionRatios, fullPotentials);\n\n        // Use non-rescaled contraction ratios.\n        vector<FLOAT_TYPE> fullEnergyPowers(count, 0.0);\n        vector<FLOAT_TYPE> energyPowers(count, 2.0);\n        StlUtilities::Append(energyPowers, &fullEnergyPowers);\n\n        packingSerializer->SerializeContractionEnergies(targetFilePath, fullContractionRatios, fullEnergyPowers, result.contractionEnergies, result.nonRattlersCounts);\n    }\n\n    void GenerationManager::GenerateOrder(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        orderService->SetParticles(*particles);\n        OrderService::Order order = orderService->GetOrder(6); // 6 is the best order, as is maximum for FCC packings\n        packingSerializer->SerializeOrder(targetFilePath, order);\n    }\n\n    void GenerationManager::CalculateHessianEigenvalues(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        hessianService->SetParticles(*particles);\n        vector<FLOAT_TYPE> hessianEigenvalues;\n        hessianService->FillHessianEigenvalues(&hessianEigenvalues);\n        packingSerializer->SerializeHessianEigenvalues(targetFilePath, hessianEigenvalues);\n    }\n\n    void GenerationManager::CalculatePressures(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        vector<FLOAT_TYPE> contractionRatios;\n        FillContractionRatios(&contractionRatios);\n        int count = contractionRatios.size();\n        vector<FLOAT_TYPE> fullContractionRatios;\n\n        // No sense in calculating pressure for power = 0\n        StlUtilities::Append(contractionRatios, &fullContractionRatios);\n        vector<FLOAT_TYPE> fullEnergyPowers(count, 2.0);\n\n        vector<FLOAT_TYPE> pressures;\n        pressureService->SetParticles(*particles);\n        pressureService->FillPressures(fullContractionRatios, fullEnergyPowers, &pressures);\n        packingSerializer->SerializePressures(targetFilePath, fullContractionRatios, fullEnergyPowers, pressures);\n    }\n\n    void GenerationManager::CalculateMolecularDynamicsStatistics(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        printf(\"Calculating molecular dynamics statistics\\n\");\n\n        molecularDynamicsService->SetGenerationConfig(fullConfig.generationConfig);\n        molecularDynamicsService->SetParticles(*particles);\n\n        MolecularDynamicsStatistics statistics = molecularDynamicsService->CalculateStationaryStatistics();\n        packingSerializer->SerializeMolecularDynamicsStatistics(targetFilePath, statistics);\n    }\n\n    void GenerationManager::RemoveRattlers(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        vector<bool> rattlerMask(context.config->particlesCount);\n        rattlerRemovalService->SetParticles(*particles);\n//        const FLOAT_TYPE contractionRate = 1.0 - 1.0e-7;\n//        const FLOAT_TYPE contractionRate = 1.0 - 1.0e-5;\n        const FLOAT_TYPE contractionRate = 1.0 / 1.5; //particles that have one radius between surfaces will become in contact\n        rattlerRemovalService->FillRattlerMask(contractionRate, &rattlerMask);\n        int nonRattlersCount = rattlerRemovalService->FindNonRattlersCount(rattlerMask);\n        Packing nonRattlerParticles;\n        nonRattlerParticles.resize(nonRattlersCount);\n        rattlerRemovalService->FillNonRattlerPacking(rattlerMask, &nonRattlerParticles);\n\n        printf(\"Removing rattlers. Non-rattlers count: %d\\n\", nonRattlersCount);\n\n        PackingInfo oldInfo;\n        PackingInfo nonRattlerInfo;\n\n        ExecutionConfig nonRattlerConfig;\n\n        string packingInfoFilePath = Path::Append(fullConfig.generationConfig.baseFolder, PACKING_FILE_NAME_NFO);\n        packingSerializer->ReadPackingInfo(packingInfoFilePath, &oldInfo);\n\n        rattlerRemovalService->FillNonRattlerConfig(nonRattlersCount, fullConfig, &nonRattlerConfig);\n        rattlerRemovalService->FillNonRattlerPackingInfo(nonRattlersCount, nonRattlerParticles, nonRattlerConfig, oldInfo, &nonRattlerInfo);\n\n        // Serialize non-rattler packing\n        packingSerializer->SerializePackingInfo(packingInfoFilePath, nonRattlerConfig.systemConfig, nonRattlerInfo);\n\n        string packingFilePath = Path::Append(fullConfig.generationConfig.baseFolder, PACKING_FILE_NAME);\n        packingSerializer->SerializePacking(packingFilePath, nonRattlerParticles);\n\n        string configFilePath = Path::Append(fullConfig.generationConfig.baseFolder, CONFIG_FILE_NAME);\n        packingSerializer->SerializeConfig(configFilePath, nonRattlerConfig);\n    }\n\n    void GenerationManager::CalculatePairCorrelationFunction(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        printf(\"Calculating pair correlation function\\n\");\n\n        distanceService->SetParticles(*particles);\n        PairCorrelationFunction pairCorrelationFunction;\n        distanceService->FillPairCorrelationFunction(&pairCorrelationFunction);\n\n        packingSerializer->SerializePairCorrelationFunction(targetFilePath, pairCorrelationFunction);\n    }\n\n    void GenerationManager::CalculateStructureFactor(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        printf(\"Calculating structure factor\\n\");\n\n        Packing& particlesRef = *particles;\n\n        std::vector<int> particleIndexesOfInterest;\n        if (fullConfig.generationConfig.particlesToKeepForStructureFactor > 0)\n        {\n            int particlesToChooseCount = fullConfig.generationConfig.particlesToKeepForStructureFactor;\n            bool keepSmallest = fullConfig.generationConfig.keepSmallParticlesForStructureFactor.value;\n\n            // choosing that many largest particles\n            // NOTE: maybe use nth element\n            std::vector<double> diameters;\n            for (const DomainParticle& particle : particlesRef)\n            {\n                diameters.push_back(particle.diameter);\n            }\n            std::vector<int> permutation;\n            StlUtilities::SortPermutation(diameters, &permutation);\n\n            if (keepSmallest)\n            {\n                permutation.erase(permutation.begin() + particlesToChooseCount, permutation.end());\n            }\n            else\n            {\n                int particlesToRemove = permutation.size() - particlesToChooseCount;\n                permutation.erase(permutation.begin(), permutation.begin() + particlesToRemove);\n            }\n\n            particleIndexesOfInterest.swap(permutation);\n\n            double minSelectedDiameter = 1000; // TODO: use numeric_limits\n            double maxSelectedDiameter = 0;\n            for (int i : particleIndexesOfInterest)\n            {\n                double diameter = particlesRef[i].diameter;\n                if (diameter > maxSelectedDiameter)\n                {\n                    maxSelectedDiameter = diameter;\n                }\n                if (diameter < minSelectedDiameter)\n                {\n                    minSelectedDiameter = diameter;\n                }\n            }\n\n            if (keepSmallest)\n            {\n                printf(\"Expected to calculate structure factor for %d smallest particles. Selected %d smallest particles. Max selected diameter: %f\\n\",\n                    particlesToChooseCount,\n                    particleIndexesOfInterest.size(),\n                    maxSelectedDiameter);\n            }\n            else\n            {\n                printf(\"Expected to calculate structure factor for %d largest particles. Selected %d largest particles. Min selected diameter: %f\\n\",\n                    particlesToChooseCount,\n                    particleIndexesOfInterest.size(),\n                    minSelectedDiameter);\n            }\n        }\n\n\n        distanceService->SetParticles(*particles);\n        StructureFactor structureFactor;\n        distanceService->FillStructureFactor(particleIndexesOfInterest, &structureFactor);\n\n        packingSerializer->SerializeStructureFactor(targetFilePath, structureFactor);\n    }\n\n    void GenerationManager::GenerateLocalOrientationalDisorder(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        printf(\"Calculating local orientational disorder\\n\");\n\n        orderService->SetParticles(*particles);\n        OrderService::LocalOrientationalDisorder localOrientationalDisorder;\n        orderService->FillLocalOrientationalDisorder(&localOrientationalDisorder);\n        packingSerializer->SerializeLocalOrientationalDisorder(targetFilePath, localOrientationalDisorder);\n        packingSerializer->SerializeCloseNeighbors(Path::Append(fullConfig.generationConfig.baseFolder, \"close_neighbors.txt\"), localOrientationalDisorder);\n    }\n\n    void GenerationManager::CalculateImmediateMolecularDynamicsStatistics(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        printf(\"Calculating immediate molecular dynamics statistics\\n\");\n\n        molecularDynamicsService->SetGenerationConfig(fullConfig.generationConfig);\n        molecularDynamicsService->SetParticles(*particles);\n\n        MolecularDynamicsStatistics statistics = molecularDynamicsService->CalculateImmediateStatistics();\n        packingSerializer->SerializeMolecularDynamicsStatistics(targetFilePath, statistics);\n    }\n\n    void GenerationManager::CalculateNearestNeighbors(const Model::ExecutionConfig& fullConfig, const Model::ModellingContext& context, std::string targetFilePath, Model::Packing* particles)\n    {\n        printf(\"Calculating nearest neighbors\\n\");\n\n        distanceService->SetParticles(*particles);\n        vector<ParticlePair> closestPairs;\n        distanceService->FillClosestPairs(&closestPairs);\n\n        vector<bool> isImmobileMask(fullConfig.systemConfig.particlesCount);\n        vector<int> isImmobileIntMask(fullConfig.systemConfig.particlesCount);\n\n        VectorUtilities::InitializeWith(&isImmobileMask, false);\n        VectorUtilities::InitializeWith(&isImmobileIntMask, 0);\n\n        Model::Packing& particlesRef = *particles;\n        for (ParticleIndex i = 0; i < fullConfig.systemConfig.particlesCount; ++i)\n        {\n            isImmobileMask[i] = particlesRef[i].isImmobile;\n            isImmobileIntMask[i] = particlesRef[i].isImmobile ? 1 : 0;\n        }\n\n        vector<int> permutation;\n        StlUtilities::SortPermutation(isImmobileIntMask, &permutation);\n\n        vector<ParticlePair> sortedClosestPairs;\n        StlUtilities::Permute(closestPairs, permutation, &sortedClosestPairs);\n\n        vector<bool> sortedIsImmobileMask;\n        StlUtilities::Permute(isImmobileMask, permutation, &sortedIsImmobileMask);\n\n        packingSerializer->SerializeNearestNeighbors(targetFilePath, closestPairs, sortedIsImmobileMask);\n    }\n\n    void GenerationManager::CreateActiveConfig(const ExecutionConfig& fullConfig, FLOAT_TYPE contractionFactorByParticleCenters, SystemConfig* activeConfig, SpatialVector* shift) const\n    {\n        SystemConfig& activeConfigRef = *activeConfig;\n        activeConfigRef.Reset();\n        activeConfigRef.MergeWith(fullConfig.systemConfig);\n\n        FLOAT_TYPE meanParticleRadius = 0.5; // TODO: determine better\n        // contractionFactor is measured by the true radius of the bounding cylinder (i.e., by particle surfaces)\n        FLOAT_TYPE contractionFactor = ((activeConfigRef.packingSize[Axis::X] - 2.0 * meanParticleRadius) * contractionFactorByParticleCenters + 2.0 * meanParticleRadius) / activeConfigRef.packingSize[Axis::X];\n        SpatialVector contractionFactors;\n        VectorUtilities::InitializeWith(&contractionFactors, contractionFactor);\n\n//            contractionFactors[DIMENSIONS - 1] = 1.0; // For packings that are periodic by z. TODO: periodicity shall be specified in generation.conf. IGeometry shall include this information (as done in LatticeGeoetry)\n        contractionFactors[DIMENSIONS - 1] = (activeConfigRef.packingSize[DIMENSIONS - 1] - 8.0 * meanParticleRadius) / activeConfigRef.packingSize[DIMENSIONS - 1]; // Remove 2 diameters from each side\n        VectorUtilities::Multiply(activeConfigRef.packingSize, contractionFactors, &activeConfigRef.packingSize);\n\n        SpatialVector margins;\n        VectorUtilities::Subtract(fullConfig.systemConfig.packingSize, activeConfigRef.packingSize, &margins);\n        VectorUtilities::MultiplyByValue(margins, 0.5, shift);\n    }\n\n    void GenerationManager::GetActiveConfigWithParticlesCount(const ExecutionConfig& fullConfig, FLOAT_TYPE contractionFactorByParticleCenters, Packing* particles, SystemConfig* activeConfig, SpatialVector* shift) const\n    {\n        SystemConfig& activeConfigRef = *activeConfig;\n        // the default active area is 0.5 of the cylinder, if cylinder radius is measured by particle centers\n        CreateActiveConfig(fullConfig, contractionFactorByParticleCenters, activeConfig, shift);\n        boost::shared_ptr<IGeometry> activeGeometry = CreateGeometry(activeConfigRef, *shift);\n\n        ////////////////////\n        // Set active geometry\n\n        // NOTE: here I use a dirty hack and do not call SetContext for all the services, as I know, that non of the services caches the active geometry.\n        // TODO: extract setting context from ExecuteAlgorithm to a separate method, call here.\n\n        // Set correct isImmobile mask\n        SetActiveParticlesByActiveGeometry(fullConfig.systemConfig, *activeGeometry.get(), particles);\n\n        ////////////////////\n        // Determine the amount of active non-rattler particles\n\n        // Find the best contraction rate to get the expected coordination number\n//        FLOAT_TYPE expectedCoordinationNumber = GetExpectedCoordinationNumber(fullConfig, context, targetFilePath, particles);\n//        FLOAT_TYPE contractionRate = insertionRadiiGenerator->GetContractionRateForCoordinationNumber(contractionEnergyService, expectedCoordinationNumber);\n        FLOAT_TYPE contractionRate = 1.0 - 1e-7;\n\n        vector<bool> rattlerMask;\n        rattlerRemovalService->SetParticles(*particles);\n        rattlerRemovalService->FillRattlerMask(contractionRate, &rattlerMask);\n\n        int activeNonRattlersCount = 0;\n        Packing& particlesRef = *particles;\n        for (ParticleIndex i = 0; i < fullConfig.systemConfig.particlesCount; ++i)\n        {\n//            if (!particlesRef[i].isImmobile && !rattlerMask[i])\n            if (!particlesRef[i].isImmobile)\n            {\n                activeNonRattlersCount++;\n            }\n        }\n\n        activeConfigRef.particlesCount = activeNonRattlersCount;\n    }\n\n    void GenerationManager::FindActiveConfigForActiveParticlesCount(const ExecutionConfig& fullConfig, int activeParticlesCount, Packing* particles, SystemConfig* activeConfig, SpatialVector* shift) const\n    {\n        GetActiveParticlesCountFunctor getActiveParticlesCountFunctor(*this, fullConfig, particles, activeConfig, shift);\n        StlUtilities::DoBinarySearch(0.0, 1.0, activeParticlesCount, 0, 1e-7, getActiveParticlesCountFunctor);\n    }\n\n    void GenerationManager::CalculateActiveGeometry(const ExecutionConfig& fullConfig, const ModellingContext& context, string targetFilePath, Packing* particles)\n    {\n        printf(\"Calculating active geometry\\n\");\n\n        SpatialVector shift;\n        SystemConfig activeConfig;\n\n        // NOTE: this is a dirty hack. I'm using insertionRadiiCount parameter to store expectedActiveParticlesCount\n        // TODO: add a separate config parameter\n        int expectedActiveParticlesCount = fullConfig.generationConfig.insertionRadiiCount;\n\n        // The usual workflow is the following:\n        // 1. run CalculateActiveGeometry without an expectedActiveParticlesCount to determine approximate amount of particles inside the active geometry.\n        // 2. select the min amount of activeParticlesCount\n        // 3. rename the old active configs\n        // 4. run CalculateActiveGeometry with expectedActiveParticlesCount = this min number\n        // It ensures that all the active geometries have equal amount of active particles.\n        // It will make the entropy and compactivity calculations easier\n        // (actually, i'm not sure how to calculate compactivity and how to account for rattlers if the amount of particles varies).\n        // TODO: extract this entire procedure to a separate method (it's hard currently,\n        // as requires processing of several packings at once, which is completely unsupported by the architecture)\n        if (expectedActiveParticlesCount == -1)\n        {\n            // the default active area is 0.5 of the cylinder, if cylinder radius is measured by particle centers\n            FLOAT_TYPE contractionFactorByParticleCenters = 0.5;\n            GetActiveConfigWithParticlesCount(fullConfig, contractionFactorByParticleCenters, particles, &activeConfig, &shift);\n        }\n        else\n        {\n            FindActiveConfigForActiveParticlesCount(fullConfig, expectedActiveParticlesCount, particles, &activeConfig, &shift);\n        }\n\n        packingSerializer->SerializeActiveConfig(targetFilePath, activeConfig, shift);\n    }\n\n    void GenerationManager::CalculateSuccessfulPermutationProbability(const Model::ExecutionConfig& fullConfig, const Model::ModellingContext& context, std::string targetFilePath, Model::Packing* particles)\n    {\n        printf(\"Calculating successful permutation probability\\n\");\n        Packing& packingToUse = *particles;\n\n        int maxPermutations = 5000;\n        FLOAT_TYPE successfulPermutationProbability = insertionRadiiGenerator->GetSuccessfulPermutationProbability(particles, maxPermutations);\n\n        printf(\"Estimated successful permutation probability is %f\\n\", successfulPermutationProbability);\n\n        //packingSerializer->SerializeContactNumberDistribution(targetFilePath, neighborCounts, neighborCountFrequencies);\n    }\n\n    void GenerationManager::FillContractionRatios(vector<FLOAT_TYPE>* contractionRatios) const\n    {\n        contractionRatios->clear();\n        AddLogContractionRatios(contractionRatios);\n//        AddLinearContractionRatios(contractionRatios);\n        contractionRatios->push_back(0.9999999); // predefined value\n\n        StlUtilities::SortAndResizeToUnique(contractionRatios);\n    }\n\n    void GenerationManager::AddLogContractionRatios(vector<FLOAT_TYPE>* contractionRatios) const\n    {\n        const int pointsCount = 15;\n        const FLOAT_TYPE minContractionRatio = 0.9999999;\n        const FLOAT_TYPE maxContractionRatio = 0.99995;\n\n        vector<FLOAT_TYPE> contractionRatiosArray(pointsCount);\n\n        VectorUtilities::FillLogScale(1. - minContractionRatio, 1. - maxContractionRatio, &contractionRatiosArray);\n        VectorUtilities::MultiplyByValue(contractionRatiosArray, -1.0, &contractionRatiosArray);\n        VectorUtilities::AddValue(contractionRatiosArray, 1.0, &contractionRatiosArray);\n\n        StlUtilities::Append(contractionRatiosArray, contractionRatios);\n    }\n\n    void GenerationManager::AddLinearContractionRatios(vector<FLOAT_TYPE>* contractionRatios) const\n    {\n        // 200 points per 0.01\n        // maxParticleDiameter / maxContractionRatio * innerDiameterRatio <= maxParticleDiameter * VerletListNeighborProvider::MAX_EXPECTED_OUTER_DIAMETER_RATIO + cutoffDistance\n        // Approximately 1.0 / maxContractionRatio * innerDiameterRatio <= VerletListNeighborProvider::MAX_EXPECTED_OUTER_DIAMETER_RATIO\n        const int pointsCount = 401;\n        const FLOAT_TYPE minContractionRatio = 1.0;\n        const FLOAT_TYPE maxContractionRatio = 0.98;\n\n        vector<FLOAT_TYPE> contractionRatiosArray(pointsCount);\n\n        VectorUtilities::FillLinearScale(minContractionRatio, maxContractionRatio, &contractionRatiosArray);\n        StlUtilities::Append(contractionRatiosArray, contractionRatios);\n    }\n\n    void GenerationManager::FillFullConfig(const ExecutionConfig& userConfig, ExecutionConfig* fullConfig) const\n    {\n        ExecutionConfig fileConfig;\n        packingSerializer->ReadConfig(userConfig.generationConfig.baseFolder, &fileConfig);\n\n        fullConfig->MergeWith(userConfig);\n        fullConfig->MergeWith(fileConfig);\n    }\n\n    boost::shared_ptr<IGeometry> GenerationManager::CreateGeometry(const SystemConfig& config, const Core::SpatialVector& shift) const\n    {\n        // TODO: use shift in all non-bulk geometries and may be add a template parameter to all of them <TSupportsShift>.\n        boost::shared_ptr<IGeometry> geometry;\n        switch (config.boundariesMode)\n        {\n        case BoundariesMode::Bulk:\n            geometry.reset(new BulkGeometry(config));\n            break;\n        case BoundariesMode::Ellipse:\n            geometry.reset(new CircleGeometry(config, shift));\n            break;\n        case BoundariesMode::Rectangle:\n            geometry.reset(new RectangleGeometry(config));\n            break;\n        case BoundariesMode::Trapezoid:\n            geometry.reset(new TrapezoidGeometry(config));\n            break;\n        case BoundariesMode::Unknown:\n            break;\n        }\n\n        return geometry;\n    }\n\n    boost::shared_ptr<IGeometry> GenerationManager::CreateGeometry(const SystemConfig& config) const\n    {\n        SpatialVector shift;\n        VectorUtilities::InitializeWith(&shift, 0.0);\n        return CreateGeometry(config, shift);\n    }\n\n    void GenerationManager::ReadOrCreatePacking(const ExecutionConfig& fullConfig, const ModellingContext& context, bool shouldAlwaysReadPacking, Packing* particles) const\n    {\n        Packing& particlesRef = *particles;\n        particlesRef.resize(fullConfig.systemConfig.particlesCount);\n\n        for (ParticleIndex i = 0; i < fullConfig.systemConfig.particlesCount; ++i)\n        {\n            particlesRef[i].index = i;\n        }\n\n        if (shouldAlwaysReadPacking)\n        {\n            // Always read the packing, even if the generation mode is \"start\"\n            packingSerializer->ReadPacking(Path::Append(fullConfig.generationConfig.baseFolder, PACKING_FILE_NAME), particles);\n        }\n        else\n        {\n            ReadOrCreatePacking(fullConfig, context, particles);\n        }\n\n        // Setting immobile particles in different ways\n\n        Nullable<bool> shouldSuppressCrystallization = fullConfig.generationConfig.shouldSuppressCrystallization;\n        if (shouldSuppressCrystallization.hasValue && shouldSuppressCrystallization.value)\n        {\n            immobileParticlesService->SetContext(context);\n            immobileParticlesService->SetAndArrangeImmobileParticles(particles);\n        }\n\n        string immobileParticlesPath = Path::Append(fullConfig.generationConfig.baseFolder, IMMOBILE_PARTICLES_FILE_NAME);\n        if (Path::Exists(immobileParticlesPath))\n        {\n            vector<ParticleIndex> immobileParticleIndexes;\n            packingSerializer->ReadImmobileParticleIndexes(immobileParticlesPath, &immobileParticleIndexes);\n            for (std::size_t immobileParticleIndexIndex = 0; immobileParticleIndexIndex < immobileParticleIndexes.size(); ++immobileParticleIndexIndex)\n            {\n                ParticleIndex immobileParticleIndex = immobileParticleIndexes[immobileParticleIndexIndex];\n                particlesRef[immobileParticleIndex].isImmobile = true;\n            }\n        }\n\n        if (context.activeGeometry != NULL)\n        {\n            SetActiveParticlesByActiveGeometry(fullConfig.systemConfig, *context.activeGeometry, particles);\n        }\n    }\n\n    void GenerationManager::SetActiveParticlesByActiveGeometry(const SystemConfig& systemConfig, const IGeometry& activeGeometry, Packing* particles) const\n    {\n        Packing& particlesRef = *particles;\n\n        int immobileParticlesCount = 0;\n        for (ParticleIndex i = 0; i < systemConfig.particlesCount; ++i)\n        {\n            particlesRef[i].isImmobile = !activeGeometry.IsSphereInside(particlesRef[i].coordinates, particlesRef[i].diameter * 0.5);\n            if (particlesRef[i].isImmobile)\n            {\n                immobileParticlesCount++;\n            }\n        }\n\n        if (immobileParticlesCount > 0)\n        {\n            printf(\"mobileParticlesCount = %d, immobileParticlesCount = %d\\n\", systemConfig.particlesCount - immobileParticlesCount, immobileParticlesCount);\n        }\n    }\n\n    void GenerationManager::ReadOrCreatePacking(const ExecutionConfig& fullConfig, const ModellingContext& context, Packing* particles) const\n    {\n        string baseFolder = fullConfig.generationConfig.baseFolder;\n        int particlesCount = fullConfig.systemConfig.particlesCount;\n        particles->resize(particlesCount);\n\n        if (fullConfig.generationConfig.shouldStartGeneration.hasValue && fullConfig.generationConfig.shouldStartGeneration.value)\n        {\n            packingSerializer->ReadParticleDiameters(Path::Append(baseFolder, DIAMETERS_FILE_NAME), particles);\n\n            if (fullConfig.generationConfig.initialParticleDistribution == InitialParticleDistribution::Poisson)\n            {\n                // TODO: create PoissonGenerator PoissonInCellsGenerator for all geometries, just call IsSphereInside for the given geometry until the sphere is in the geometry.\n                BulkPoissonGenerator initialGenerator;\n                CreateInitialPacking(fullConfig, context, particles, &initialGenerator);\n            }\n            else\n            {\n                BulkPoissonInCellsGenerator initialGenerator;\n                CreateInitialPacking(fullConfig, context, particles, &initialGenerator);\n            }\n\n//            HcpGenerator initialGenerator;\n//            CreateInitialPacking(fullConfig, context, particles, &initialGenerator);\n\n            packingSerializer->SerializePacking(Path::Append(baseFolder, INIT_PACKING_FILE_NAME), *particles);\n        }\n        else\n        {\n            packingSerializer->ReadPacking(Path::Append(baseFolder, PACKING_FILE_NAME), particles);\n        }\n    }\n\n    void GenerationManager::CreateInitialPacking(const ExecutionConfig& fullConfig, const ModellingContext& context, Packing* particles, IPackingGenerator* initialGenerator) const\n    {\n        initialGenerator->SetContext(context);\n        initialGenerator->SetGenerationConfig(fullConfig.generationConfig);\n        initialGenerator->ArrangePacking(particles);\n    }\n\n    GenerationManager::~GenerationManager()\n    {\n\n    }\n}\n\n", "meta": {"hexsha": "a668ae5d3e0f730784610e138eb3b649cb2e67f2", "size": 47245, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PackingGeneration/Generation/GenerationManager.cpp", "max_stars_repo_name": "MINATILO/packing-generation", "max_stars_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PackingGeneration/Generation/GenerationManager.cpp", "max_issues_repo_name": "MINATILO/packing-generation", "max_issues_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PackingGeneration/Generation/GenerationManager.cpp", "max_forks_repo_name": "MINATILO/packing-generation", "max_forks_repo_head_hexsha": "4d4f5d037e0687b57178602b989431e82a5c8b96", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4712041885, "max_line_length": 248, "alphanum_fraction": 0.7320139697, "num_tokens": 9861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23684229839681967}}
{"text": "#include <GL/freeglut.h>\n#include <Eigen/Eigen>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n\n#include \"structures.h\"\n#include \"transformations.h\"\n#include \"cauchy.h\"\n#include \"../../python-scripts/constraints/relative_pose_tait_bryan_wc_jacobian.h\"\n#include \"../../python-scripts/constraints/relative_pose_rodrigues_wc_jacobian.h\"\n#include \"../../python-scripts/constraints/relative_pose_quaternion_wc_jacobian.h\"\n#include \"../../python-scripts/constraints/quaternion_constraint_jacobian.h\"\n#include \"../../python-scripts/constraints/relative_pose_wc_jacobian.h\"\n\n#include \"manif/SE2.h\"\n\nusing manif::SE2d;\nusing manif::SE2Tangentd;\n\nconst unsigned int window_width = 1920;\nconst unsigned int window_height = 1080;\nint mouse_old_x, mouse_old_y;\nint mouse_buttons = 0;\nfloat rotate_x = 0.0, rotate_y = 0.0;\nfloat translate_z = -10.0;\nfloat translate_x, translate_y = 0.0;\n\nbool initGL(int *argc, char **argv);\nvoid display();\nvoid keyboard(unsigned char key, int x, int y);\nvoid mouse(int button, int state, int x, int y);\nvoid motion(int x, int y);\nvoid reshape(int w, int h);\nvoid printHelp();\n\nstd::vector<Eigen::Affine3d> m_poses;\nstd::vector<std::tuple<int, int, Eigen::Affine3d>> edges_g2o;\nstd::vector<std::vector<double>> edges_g2o_w;\n\nint main(int argc, char *argv[]){\n\tif(argc != 2){\n\t\tstd::cout << \"USAGE: \" << argv[0] << \" file.g2o\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tstd::ifstream g2o_file(argv[1]);\n\n\tstd::string line;\n    while (std::getline(g2o_file, line)) {\n        std::stringstream line_stream(line);\n        std::string class_element;\n        line_stream >> class_element;\n        if (class_element == \"VERTEX_SE2\"){\n            int id=0;\n            TaitBryanPose p;\n            line_stream >> id;\n            line_stream >> p.px;\n            line_stream >> p.py;\n            line_stream >> p.ka;\n\n            Eigen::Affine3d m = affine_matrix_from_pose_tait_bryan(p);\n            m_poses.push_back(m);\n        }\n        else if(class_element == \"EDGE_SE2\"){\n            int pose_id1,pose_id2;\n            line_stream>>pose_id1;\n            line_stream>>pose_id2;\n            TaitBryanPose p;\n            line_stream >> p.px;\n            line_stream >> p.py;\n            line_stream >> p.ka;\n\n            Eigen::Affine3d m = affine_matrix_from_pose_tait_bryan(p);\n\n            edges_g2o.emplace_back(std::make_tuple(pose_id1,pose_id2, m));\n\n            std::vector<double> w(6);\n\t\t\tfor(size_t i = 0 ; i < 6; i++){\n\t\t\t\tline_stream >> w[i];\n\t\t\t}\n\t\t\tstd::vector<double> ww(3);\n\t\t\tww[0] = w[0];\n\t\t\tww[1] = w[3];\n\t\t\tww[2] = w[5];\n\t\t\tedges_g2o_w.push_back(ww);\n\n        }\n    }\n    g2o_file.close();\n\n\tif (false == initGL(&argc, argv)) {\n\t\treturn 4;\n\t}\n\n\tprintHelp();\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMouseFunc(mouse);\n\tglutMotionFunc(motion);\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nbool initGL(int *argc, char **argv) {\n\tglutInit(argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\n\tglutInitWindowSize(window_width, window_height);\n\tglutCreateWindow(\"pose2d_graph_slam\");\n\tglutDisplayFunc(display);\n\tglutKeyboardFunc(keyboard);\n\tglutMotionFunc(motion);\n\n\t// default initialization\n\tglClearColor(1.0, 1.0, 1.0, 1.0);\n\tglEnable(GL_DEPTH_TEST);\n\n\t// viewport\n\tglViewport(0, 0, window_width, window_height);\n\n\t// projection\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) window_width / (GLfloat) window_height, 0.01,\n\t\t\t10000.0);\n\tglutReshapeFunc(reshape);\n\n\treturn true;\n}\n\nvoid display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(translate_x, translate_y, translate_z);\n\tglRotatef(rotate_x, 1.0, 0.0, 0.0);\n\tglRotatef(rotate_y, 0.0, 0.0, 1.0);\n\n\tglBegin(GL_LINES);\n\tglColor3f(1.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(1.0f, 0.0f, 0.0f);\n\n\tglColor3f(0.0f, 1.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 1.0f, 0.0f);\n\n\tglColor3f(0.0f, 0.0f, 1.0f);\n\tglVertex3f(0.0f, 0.0f, 0.0f);\n\tglVertex3f(0.0f, 0.0f, 1.0f);\n\tglEnd();\n\n    glBegin(GL_LINES);\n    for(size_t i = 0; i < edges_g2o.size(); i++){\n        const int pose_1 = std::get<0>(edges_g2o[i]);\n        const int pose_2 = std::get<1>(edges_g2o[i]);\n        glVertex3f(m_poses[pose_1](0,3), m_poses[pose_1](1,3), m_poses[pose_1](2,3) );\n        glVertex3f(m_poses[pose_2](0,3), m_poses[pose_2](1,3), m_poses[pose_2](2,3) );\n    }\n    glEnd();\n\n    glColor3f(1,0,1);\n    glPointSize(5);\n    glBegin(GL_POINTS);\n    for(size_t i = 0; i < m_poses.size(); i++){\n        glVertex3f(m_poses[i](0,3), m_poses[i](1,3), m_poses[i](2,3) );\n    }\n    glEnd();\n\n    /*glBegin(GL_LINES);\n    for(size_t i = 0; i < m_poses.size(); i++){\n\n\t\tglColor3f(1.0f, 0.0f, 0.0f);\n\t\tglVertex3f(m_poses[i](0,3), m_poses[i](1,3), m_poses[i](2,3));\n\t\tglVertex3f(m_poses[i](0,3) + m_poses[i](0,0), m_poses[i](1,3) + m_poses[i](1,0), m_poses[i](2,3) + + m_poses[i](2,0));\n\n\t\tglColor3f(0.0f, 1.0f, 0.0f);\n\t\tglVertex3f(m_poses[i](0,3), m_poses[i](1,3), m_poses[i](2,3));\n\t\tglVertex3f(m_poses[i](0,3) + m_poses[i](0,1), m_poses[i](1,3) + m_poses[i](1,1), m_poses[i](2,3) + + m_poses[i](2,1));\n\n\t\tglColor3f(0.0f, 0.0f, 1.0f);\n\t\tglVertex3f(m_poses[i](0,3), m_poses[i](1,3), m_poses[i](2,3));\n\t\tglVertex3f(m_poses[i](0,3) + m_poses[i](0,2), m_poses[i](1,3) + m_poses[i](1,2), m_poses[i](2,3) + + m_poses[i](2,2));\n\n\t}\n    glEnd();*/\n\n\n\tglutSwapBuffers();\n}\n\nvoid keyboard(unsigned char key, int /*x*/, int /*y*/) {\n\tswitch (key) {\n\t\tcase (27): {\n\t\t\tglutDestroyWindow(glutGetWindow());\n\t\t\treturn;\n\t\t}\n\t\tcase 'n':{\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\tpose.px += ((float(rand()%1000000))/1000000.0f - 0.5) * 1.1;\n\t\t\t\tpose.py += ((float(rand()%1000000))/1000000.0f - 0.5) * 1.1;\n\t\t\t\tpose.pz += ((float(rand()%1000000))/1000000.0f - 0.5) * 1.1;\n\t\t\t\tpose.om += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.11;\n\t\t\t\tpose.fi += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.11;\n\t\t\t\tpose.ka += ((float(rand()%1000000))/1000000.0f - 0.5) * 0.11;\n\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 't':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<TaitBryanPose> poses;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tposes.push_back(pose_tait_bryan_from_affine_matrix(m_poses[i]));\n\t\t\t}\n\n\t\t\tfor(size_t i = 0 ; i < edges_g2o.size(); i++){\n\t\t\t\tconst int first = std::get<0>(edges_g2o[i]);\n\t\t\t\tconst int second = std::get<1>(edges_g2o[i]);\n\t\t\t\tconst Eigen::Affine3d& rel = std::get<2>(edges_g2o[i]);\n\t\t\t\tTaitBryanPose pose_rel = pose_tait_bryan_from_affine_matrix(rel);\n\n\t\t\t\tTaitBryanPose from = poses[first];\n\t\t\t\tTaitBryanPose to = poses[second];\n\n\t\t\t\tEigen::Matrix<double, 6, 1> delta;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1(\n\t\t\t\t\tdelta,\n\t\t\t\t\tposes[first].px,\n\t\t\t\t\tposes[first].py,\n\t\t\t\t\tposes[first].pz,\n\t\t\t\t\tposes[first].om,\n\t\t\t\t\tposes[first].fi,\n\t\t\t\t\tposes[first].ka,\n\t\t\t\t\tposes[second].px,\n\t\t\t\t\tposes[second].py,\n\t\t\t\t\tposes[second].pz,\n\t\t\t\t\tposes[second].om,\n\t\t\t\t\tposes[second].fi,\n\t\t\t\t\tposes[second].ka,\n\t\t\t\t\tpose_rel.px,\n\t\t\t\t\tpose_rel.py,\n\t\t\t\t\tpose_rel.pz,\n\t\t\t\t\tpose_rel.om,\n\t\t\t\t\tpose_rel.fi,\n\t\t\t\t\tpose_rel.ka);\n\n\t\t\t\tEigen::Matrix<double, 6, 12, Eigen::RowMajor> jacobian;\n\t\t\t\trelative_pose_obs_eq_tait_bryan_wc_case1_jacobian(jacobian,\n\t\t\t\t\tposes[first].px,\n\t\t\t\t\tposes[first].py,\n\t\t\t\t\tposes[first].pz,\n\t\t\t\t\tposes[first].om,\n\t\t\t\t\tposes[first].fi,\n\t\t\t\t\tposes[first].ka,\n\t\t\t\t\tposes[second].px,\n\t\t\t\t\tposes[second].py,\n\t\t\t\t\tposes[second].pz,\n\t\t\t\t\tposes[second].om,\n\t\t\t\t\tposes[second].fi,\n\t\t\t\t\tposes[second].ka);\n\t\t\t\tint ir = tripletListB.size();\n\n\t\t\t\tint ic_1 = first * 3;\n\t\t\t\tint ic_2 = second * 3;\n\n\t\t\t\ttripletListA.emplace_back(ir + 0, ic_1    , -jacobian(0,0));\n\t\t\t\ttripletListA.emplace_back(ir + 0, ic_1 + 1, -jacobian(0,1));\n\t\t\t\ttripletListA.emplace_back(ir + 0, ic_1 + 2, -jacobian(0,5));\n\n\t\t\t\ttripletListA.emplace_back(ir + 0, ic_2    , -jacobian(0,6));\n\t\t\t\ttripletListA.emplace_back(ir + 0, ic_2 + 1, -jacobian(0,7));\n\t\t\t\ttripletListA.emplace_back(ir + 0, ic_2 + 2, -jacobian(0,11));\n\n\t\t\t\ttripletListA.emplace_back(ir + 1, ic_1    , -jacobian(1,0));\n\t\t\t\ttripletListA.emplace_back(ir + 1, ic_1 + 1, -jacobian(1,1));\n\t\t\t\ttripletListA.emplace_back(ir + 1, ic_1 + 2, -jacobian(1,5));\n\n\t\t\t\ttripletListA.emplace_back(ir + 1, ic_2    , -jacobian(1,6));\n\t\t\t\ttripletListA.emplace_back(ir + 1, ic_2 + 1, -jacobian(1,7));\n\t\t\t\ttripletListA.emplace_back(ir + 1, ic_2 + 2, -jacobian(1,11));\n\n\t\t\t\ttripletListA.emplace_back(ir + 2, ic_1    , -jacobian(5,0));\n\t\t\t\ttripletListA.emplace_back(ir + 2, ic_1 + 1, -jacobian(5,1));\n\t\t\t\ttripletListA.emplace_back(ir + 2, ic_1 + 2, -jacobian(5,5));\n\n\t\t\t\ttripletListA.emplace_back(ir + 2, ic_2    , -jacobian(5,6));\n\t\t\t\ttripletListA.emplace_back(ir + 2, ic_2 + 1, -jacobian(5,7));\n\t\t\t\ttripletListA.emplace_back(ir + 2, ic_2 + 2, -jacobian(5,11));\n\n\t\t\t\tfloat angle_diff = delta(5,0);\n\t\t\t\tif(fabs(angle_diff) > M_PI){\n\t\t\t\t\tangle_diff -= 2.0*M_PI;\n\t\t\t\t}\n\t\t\t\tif(fabs(angle_diff)< -M_PI){\n\t\t\t\t\tangle_diff += 2.0*M_PI;\n\t\t\t\t}\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta(0,0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta(1,0));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, angle_diff);\n\n\t\t\t\t/*if(abs(first-second)==1){\n\t\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1000);\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1000);\n\t\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1000);\n\t\t\t\t}else{\n\t\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 0.000001);\n\t\t\t\t}*/\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     cauchy(delta(0,0),1) * edges_g2o_w[i][0]);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, cauchy(delta(1,0),1) * edges_g2o_w[i][1]);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, cauchy(angle_diff,1) * edges_g2o_w[i][2]);\n\n\t\t\t\t//tripletListP.emplace_back(ir ,    ir,     edges_g2o_w[i][0]);\n\t\t\t\t//tripletListP.emplace_back(ir + 1, ir + 1, edges_g2o_w[i][1]);\n\t\t\t\t//tripletListP.emplace_back(ir + 2, ir + 2, edges_g2o_w[i][2]);\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     1000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 1000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 1000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 3);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 3 , m_poses.size() * 3);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 3 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\t\t\t//LM\n\t\t\t/*{\n\t\t\t\tfor(size_t i = 0 ; i < m_poses.size() * 3; i++){\n\t\t\t\t\ttripletListA.emplace_back(i, i, 10);\n\t\t\t\t}\n\t\t\t\tEigen::SparseMatrix<double> matLM(m_poses.size() * 3, m_poses.size() * 3);\n\t\t\t\tmatLM.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\n\t\t\t\tAtPA = AtPA + matLM;\n\t\t\t}*/\n\n\t\t\tstd::cout << \"AtPA.size: \" << AtPA.size() << std::endl;\n\t\t\tstd::cout << \"AtPB.size: \" << AtPB.size() << std::endl;\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\n\t\t\tif(h_x.size() == 3 * m_poses.size()){\n\t\t\t\tint counter = 0;\n\n\t\t\t\tfor(size_t i = 0; i < m_poses.size(); i++){\n\t\t\t\t\tTaitBryanPose pose = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\t\tpose.px += h_x[counter++];\n\t\t\t\t\tpose.py += h_x[counter++];\n\t\t\t\t\tpose.ka += h_x[counter++];\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(pose);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"optimizing with tait bryan finished\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"optimizing with tait bryan FAILED\" << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase 'y':{\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListA;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListP;\n\t\t\tstd::vector<Eigen::Triplet<double>> tripletListB;\n\n\t\t\tstd::vector<SE2d> X;\n\n\t\t\tfor(size_t i = 0 ; i < m_poses.size(); i++){\n\t\t\t\tTaitBryanPose p = pose_tait_bryan_from_affine_matrix(m_poses[i]);\n\t\t\t\tX.push_back(SE2d(p.px, p.py, p.ka));\n\t\t\t}\n\n\n\t\t\tfor(size_t i = 0 ; i < edges_g2o.size(); i++){\n\t\t\t\tconst int first = std::get<0>(edges_g2o[i]);\n\t\t\t\tconst int second = std::get<1>(edges_g2o[i]);\n\t\t\t\tconst Eigen::Affine3d& rel = std::get<2>(edges_g2o[i]);\n\n\t\t\t\tTaitBryanPose p = pose_tait_bryan_from_affine_matrix(rel);\n\t\t\t\tSE2d U = SE2d(p.px, p.py, p.ka);\n\n\t\t\t\tSE2Tangentd     d;\n\t\t\t\tSE2Tangentd     u;\n\t\t\t\tEigen::Matrix<double, 3, 3>         J_d_xi, J_d_xj;\n\n\t\t\t\tSE2d         Xi,\n\t\t\t\t\t\t\t Xj;\n\n\t\t\t\tXi = X[first];\n\t\t\t\tXj = X[second];\n\n\t\t\t\td  = Xj.rminus(Xi, J_d_xj, J_d_xi);\n\t\t\t\tu = U.log();\n\n\t\t\t\tint ir = tripletListB.size();\n\t\t\t\tint ic_1 = first * 3;\n\t\t\t\tint ic_2 = second * 3;\n\n\t\t\t\tfor(size_t row = 0 ; row < 3; row ++){\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1    , -J_d_xi(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 1, -J_d_xi(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_1 + 2, -J_d_xi(row,2));\n\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2    , -J_d_xj(row,0));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 1, -J_d_xj(row,1));\n\t\t\t\t\ttripletListA.emplace_back(ir + row, ic_2 + 2, -J_d_xj(row,2));\n\t\t\t\t}\n\n\t\t\t\tSE2Tangentd delta = d - u;\n\n\t\t\t\ttripletListB.emplace_back(ir,     0, delta.coeffs()(0));\n\t\t\t\ttripletListB.emplace_back(ir + 1, 0, delta.coeffs()(1));\n\t\t\t\ttripletListB.emplace_back(ir + 2, 0, delta.coeffs()(2));\n\n\t\t\t\t/*if(abs(first - second) == 1){\n\t\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1000);\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1000);\n\t\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 1000);\n\t\t\t\t}else{\n\t\t\t\t\ttripletListP.emplace_back(ir ,    ir,     1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, 1);\n\t\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, 0.000001);\n\t\t\t\t}*/\n\n\t\t\t\ttripletListP.emplace_back(ir ,    ir,     cauchy(delta.coeffs()(0),1) * edges_g2o_w[i][0]);\n\t\t\t\ttripletListP.emplace_back(ir + 1, ir + 1, cauchy(delta.coeffs()(1),1) * edges_g2o_w[i][1]);\n\t\t\t\ttripletListP.emplace_back(ir + 2, ir + 2, cauchy(delta.coeffs()(2),1) * edges_g2o_w[i][2]);\n\t\t\t}\n\n\t\t\tint ir = tripletListB.size();\n\t\t\ttripletListA.emplace_back(ir     , 0, 1);\n\t\t\ttripletListA.emplace_back(ir + 1 , 1, 1);\n\t\t\ttripletListA.emplace_back(ir + 2 , 2, 1);\n\n\t\t\ttripletListP.emplace_back(ir     , ir,     1000000);\n\t\t\ttripletListP.emplace_back(ir + 1 , ir + 1, 1000000);\n\t\t\ttripletListP.emplace_back(ir + 2 , ir + 2, 1000000);\n\n\t\t\ttripletListB.emplace_back(ir     , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 1 , 0, 0);\n\t\t\ttripletListB.emplace_back(ir + 2 , 0, 0);\n\n\t\t\tEigen::SparseMatrix<double> matA(tripletListB.size(), m_poses.size() * 3);\n\t\t\tEigen::SparseMatrix<double> matP(tripletListB.size(), tripletListB.size());\n\t\t\tEigen::SparseMatrix<double> matB(tripletListB.size(), 1);\n\n\t\t\tmatA.setFromTriplets(tripletListA.begin(), tripletListA.end());\n\t\t\tmatP.setFromTriplets(tripletListP.begin(), tripletListP.end());\n\t\t\tmatB.setFromTriplets(tripletListB.begin(), tripletListB.end());\n\n\n\t\t\tEigen::SparseMatrix<double> AtPA(m_poses.size() * 3 , m_poses.size() * 3);\n\t\t\tEigen::SparseMatrix<double> AtPB(m_poses.size() * 3 , 1);\n\n\t\t\t{\n\t\t\tEigen::SparseMatrix<double> AtP = matA.transpose() * matP;\n\t\t\tAtPA = (AtP) * matA;\n\t\t\tAtPB = (AtP) * matB;\n\t\t\t}\n\n\t\t\ttripletListA.clear();\n\t\t\ttripletListP.clear();\n\t\t\ttripletListB.clear();\n\n\t\t\tstd::cout << \"start solving AtPA=AtPB\" << std::endl;\n\t\t\tEigen::SimplicialCholesky<Eigen::SparseMatrix<double>> solver(AtPA);\n\n\t\t\tstd::cout << \"x = solver.solve(AtPB)\" << std::endl;\n\t\t\tEigen::SparseMatrix<double> x = solver.solve(AtPB);\n\n\t\t\tstd::vector<double> h_x;\n\n\t\t\tfor (int k=0; k<x.outerSize(); ++k){\n\t\t\t\tfor (Eigen::SparseMatrix<double>::InnerIterator it(x,k); it; ++it){\n\t\t\t\t\th_x.push_back(it.value());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(X.size() * 3 == h_x.size()){\n\n\t\t\t\tint counter = 0;\n\t\t\t\tfor(size_t i = 0 ; i < X.size(); i++){\n\t\t\t\t\tSE2Tangentd     dx;\n\t\t\t\t\tdx.coeffs()(0) = h_x[counter++];\n\t\t\t\t\tdx.coeffs()(1) = h_x[counter++];\n\t\t\t\t\tdx.coeffs()(2) = h_x[counter++];\n\t\t\t\t\tX[i] = X[i] +  dx;\n\t\t\t\t}\n\n\t\t\t\tfor (int i = 0 ; i < m_poses.size(); i++){\n\t\t\t\t\tTaitBryanPose p;\n\t\t\t\t\tp.px = X[i].translation()(0);\n\t\t\t\t\tp.py = X[i].translation()(1);\n\t\t\t\t\tp.ka = X[i].angle();\n\n\t\t\t\t\tm_poses[i] = affine_matrix_from_pose_tait_bryan(p);\n\t\t\t\t}\n\t\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\t\t\t\tstd::cout << \"AtPA=AtPB SOLVED\" << std::endl;\n\t\t\t}else{\n\t\t\t\tstd::cout << \"h_x.size(): \" << h_x.size() << std::endl;\n\t\t\t\tstd::cout << \"AtPA=AtPB FAILED\" << std::endl;\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintHelp();\n\tglutPostRedisplay();\n}\n\n\nvoid mouse(int button, int state, int x, int y) {\n\tif (state == GLUT_DOWN) {\n\t\tmouse_buttons |= 1 << button;\n\t} else if (state == GLUT_UP) {\n\t\tmouse_buttons = 0;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n}\n\nvoid motion(int x, int y) {\n\tfloat dx, dy;\n\tdx = (float) (x - mouse_old_x);\n\tdy = (float) (y - mouse_old_y);\n\n\tif (mouse_buttons & 1) {\n\t\trotate_x += dy * 0.2f;\n\t\trotate_y += dx * 0.2f;\n\n\t} else if (mouse_buttons & 4) {\n\t\ttranslate_z += dy * 0.05f;\n\t} else if (mouse_buttons & 3) {\n\t\ttranslate_x += dx * 0.05f;\n\t\ttranslate_y -= dy * 0.05f;\n\t}\n\n\tmouse_old_x = x;\n\tmouse_old_y = y;\n\n\tglutPostRedisplay();\n}\n\nvoid reshape(int w, int h) {\n\tglViewport(0, 0, (GLsizei) w, (GLsizei) h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(60.0, (GLfloat) w / (GLfloat) h, 0.01, 10000.0);\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid printHelp() {\n\tstd::cout << \"-------help-------\" << std::endl;\n\tstd::cout << \"n: add noise to poses\" << std::endl;\n\tstd::cout << \"t: optimize (Tait-Bryan)\" << std::endl;\n\tstd::cout << \"y: optimize (Lie Algebra: manif lib)\" << std::endl;\n}\n", "meta": {"hexsha": "52d171b9fba59f5f828da22adf89460d99176e58", "size": 18736, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "codes/benchmarks/src/pose2d_graph_slam.cpp", "max_stars_repo_name": "karolmajek/observation_equations", "max_stars_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-05-11T13:16:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T22:04:00.000Z", "max_issues_repo_path": "codes/benchmarks/src/pose2d_graph_slam.cpp", "max_issues_repo_name": "karolmajek/observation_equations", "max_issues_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "codes/benchmarks/src/pose2d_graph_slam.cpp", "max_forks_repo_name": "karolmajek/observation_equations", "max_forks_repo_head_hexsha": "ae4c84f4488c3f9187c03620a03e55575ce2342c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-30T22:33:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-03T18:21:21.000Z", "avg_line_length": 30.7147540984, "max_line_length": 120, "alphanum_fraction": 0.6201430401, "num_tokens": 6672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23684229839681967}}
{"text": "#include \"SCEngine.hpp\"\n\n#include <string>\n#include <glog/logging.h>\n#include <algorithm>\n#include <fstream>\n#include <cmath>\n#include <mutex>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <petuum_ps_common/include/petuum_ps.hpp>\n#include <io/general_fstream.hpp>\n\n\n#include \"util/Eigen/Dense\"\n#include \"util/context.hpp\"\n\n\nnamespace sparsecoding {\n\n    // Constructor\n    SCEngine::SCEngine(): thread_counter_(0) {\n        // timer\n        initT_ = boost::posix_time::microsec_clock::local_time();\n\n        /* context */\n        lda::Context & context = lda::Context::get_instance();\n        // input and output\n        data_file_ = context.get_string(\"data_file\");\n        input_data_format_ = context.get_string(\"input_data_format\");\n        is_partitioned_ = context.get_int32(\"is_partitioned\");\n        output_path_ = context.get_string(\"output_path\");\n        output_data_format_ = context.get_string(\"output_data_format\");\n        maximum_running_time_ = context.get_double(\"maximum_running_time\");\n        load_cache_ = context.get_int32(\"load_cache\");\n        cache_path_ = context.get_string(\"cache_path\");\n\n        // objective function parameters\n        int m = context.get_int32(\"m\");\n        int n = context.get_int32(\"n\");\n        dictionary_size_ = context.get_int32(\"dictionary_size\");\n        C_ = context.get_double(\"c\");\n        lambda_ = context.get_double(\"lambda\");\n\n        // petuum parameters\n        client_id_ = context.get_int32(\"client_id\");\n        num_clients_ = context.get_int32(\"num_clients\");\n        num_worker_threads_ = context.get_int32(\"num_worker_threads\");\n\n        // optimization parameters\n        num_epochs_ = context.get_int32(\"num_epochs\");\n        minibatch_size_ = context.get_int32(\"minibatch_size\");\n        num_eval_minibatch_ = context.get_int32(\"num_eval_minibatch\");\n        num_eval_samples_ = context.get_int32(\"num_eval_samples\");\n        init_step_size_B_ = context.get_double(\"init_step_size_B\");\n        step_size_offset_B_ = context.get_double(\"step_size_offset_B\");\n        step_size_pow_B_ = context.get_double(\"step_size_pow_B\");\n        num_iter_S_per_minibatch_ = \n            context.get_int32(\"num_iter_S_per_minibatch\");\n        init_step_size_S_ = context.get_double(\"init_step_size_S\");\n        step_size_offset_S_ = context.get_double(\"step_size_offset_S\");\n        step_size_pow_S_ = context.get_double(\"step_size_pow_S\");\n        // default step size\n        if (init_step_size_B_ < FLT_MIN) {\n            init_step_size_B_ = context.get_double(\"init_step_size\") \n                / num_clients_ / num_worker_threads_;\n            step_size_offset_B_ = context.get_double(\"step_size_offset\");\n            step_size_pow_B_ = context.get_double(\"step_size_pow\");\n        }\n        if (init_step_size_S_ < FLT_MIN) {\n            init_step_size_S_ = context.get_double(\"init_step_size\") / m;\n            step_size_offset_S_ = context.get_double(\"step_size_offset\");\n            step_size_pow_S_ = context.get_double(\"step_size_pow\");\n        }\n        init_S_low_ = context.get_double(\"init_S_low\");\n        init_S_high_ = context.get_double(\"init_S_high\");\n        init_B_low_ = context.get_double(\"init_B_low\");\n        init_B_high_ = context.get_double(\"init_B_high\");\n\n        /* Init matrices */\n        // Partition by column id mod num_clients_\n        int client_n = (n - (n / num_clients_) * num_clients_ > client_id_)?\n            n / num_clients_ + 1: n / num_clients_;\n        // Init matrix loader of data matrix X\n        if (is_partitioned_) {\n            X_matrix_loader_.Init(data_file_, input_data_format_, m, client_n);\n        } else {\n            X_matrix_loader_.Init(data_file_, input_data_format_, m, n, \n                    client_id_, num_clients_);\n        }\n\n        // Init matrix loader of coefficients S\n        if (dictionary_size_ == 0)\n            dictionary_size_ = n; \n        S_matrix_loader_.Init(dictionary_size_, client_n, \n            init_S_low_, init_S_high_);\n\n        int max_client_n = ceil(float(n) / num_clients_);\n        int iter_minibatch = \n            ceil(float(max_client_n) / num_worker_threads_ / minibatch_size_);\n        num_eval_per_client_ = \n            (num_epochs_ * iter_minibatch - 1) \n              / num_eval_minibatch_ + 1;\n\n        // Ouput parameters\n        LOG(INFO) << \"Sparse Coding running on \"\n            << num_clients_ \n            << ((num_clients_ > 1)? \" clients, each with \": \" client, with \") \n            << num_worker_threads_ << \" threads\";\n        LOG(INFO) << \"Input file: \" << data_file_;\n        LOG(INFO) << \"Matrix size: \" << n << \" by \" << m;\n        LOG(INFO) << \"Dictionary size: \" << dictionary_size_;\n        LOG(INFO) << \"C: \" << C_ << \", lambda: \" << lambda_;\n        LOG(INFO) << \"Minibatch size: \" << minibatch_size_;\n        LOG(INFO) << \"Epochs: \" << num_epochs_ \n            << \" (Max iter: \" << iter_minibatch  * num_epochs_ << \")\";\n        LOG(INFO) << \"Evaluate loss per \" << num_eval_minibatch_ << \" iter \"\n            << \"by evaluating \" << num_eval_samples_ << \" samples per thread\" \n            << \" (*\" << num_clients_ * num_worker_threads_<< \" = \"\n            << num_eval_samples_ * num_clients_ * num_worker_threads_ << \")\";\n        LOG(INFO) << \"step size of B at ith iteration: \" << init_step_size_B_\n            << \" * (i + \" << step_size_offset_B_ << \")^(-\" << step_size_pow_B_\n            << \")\";\n        LOG(INFO) << \"step size of S at ith iteration: \" << init_step_size_S_\n            << \" * (i + \" << step_size_offset_S_ << \")^(-\" << step_size_pow_S_\n            << \")\";\n        LOG(INFO) << \"Iter of S in each S loop: \" << num_iter_S_per_minibatch_;\n    }\n\n    // Helper function, regularize a vector vec \n    // such that its l2-norm is smaller than C\n    inline void RegVec(std::vector<float> & vec, float C, \n            std::vector<float> & vec_result) {\n        float sum = 0.0;\n        int len = vec.size();\n        for (int i = 0; i < len; ++i) {\n            sum += vec[i] * vec[i];\n        }\n        float ratio = (sum > C? sqrt(C / sum): 1.0);\n        for (int i = 0; i < len; ++i) {\n            vec_result[i] = vec[i] * ratio;\n        }\n    }\n\n    // Save results: dicitonary B, coefficients S, loss evaluated on different\n    // machines, time between evaluations to disk.\n    // Shall be called after calling petuum::PSTableGroup::GlobalBarrier()\n    void SCEngine::SaveResults(int thread_id, petuum::Table<float> & B_table, \n            petuum::Table<float> & loss_table) {\n        // size of matrices\n        int m = X_matrix_loader_.GetM();\n        int client_n = X_matrix_loader_.GetClientN();\n\n        // Caches\n        std::vector<float> B_row_cache(m), S_cache(dictionary_size_);\n\n        // Output files\n        //std::ofstream fout_loss, fout_B, fout_S, fout_time;\n\n        // Only thread 0 of client 0 write dictionary B, loss and time to disk\n        if (client_id_ == 0 && thread_id == 0) {\n            // Write loss to disk\n            std::string loss_filename = output_path_ + \"/loss.txt\";\n\t    petuum::io::ofstream fout_loss(loss_filename);\n\n            //fout_loss.open(loss_filename.c_str());\n            LOG(INFO) << \"Writing loss result to directory: \" << output_path_;\n            petuum::RowAccessor row_acc;\n            std::vector<float> petuum_row_cache(m);\n            for (int iter = 0; iter < num_eval_per_client_; ++iter) {\n                for (int client = 0; client < num_clients_; ++client) {\n                    int row_id = client * num_eval_per_client_ + iter;\n                    const auto & row = loss_table.\n                        Get<petuum::DenseRow<float> >(row_id, &row_acc);\n                    row.CopyToVector(&petuum_row_cache);\n                    if (std::abs(petuum_row_cache[0]) > FLT_MIN) {\n                        fout_loss << petuum_row_cache[0] << \"\\t\";\n                    } else {\n                        fout_loss << \"N/A\" << \"\\t\";\n                    }\n                }\n                fout_loss << \"\\n\";\n            }\n            fout_loss.close();\n            // Write time to disk\n            std::string time_filename = output_path_ + \"/time.txt\";\n\t    petuum::io::ofstream fout_time(time_filename);\n\n            //fout_time.open(time_filename.c_str());\n            for (int iter = 0; iter < num_eval_per_client_; ++iter) {\n                for (int client = 0; client < num_clients_; ++client) {\n                    int row_id = \n                        (client + num_clients_) * num_eval_per_client_ + iter;\n                    const auto & row = loss_table.\n                        Get<petuum::DenseRow<float> >(row_id, &row_acc);\n                    row.CopyToVector(&petuum_row_cache);\n                    if (std::abs(petuum_row_cache[0]) > FLT_MIN) {\n                        fout_time << petuum_row_cache[0] << \"\\t\";\n                    } else {\n                        fout_time << \"N/A\" << \"\\t\";\n                    }\n                }\n                fout_time << \"\\n\";\n            }\n            fout_time.close();\n            // Write dictionary B to disk\n            // with filename output_path_/B.[txt|bin]\n            //if (output_data_format_ == \"text\") {\n                std::string B_filename = output_path_ + \"/B.txt\";\n                //fout_B.open(B_filename.c_str());\n\t\tpetuum::io::ofstream fout_B(B_filename);\n\n\t\tfor (int row_id = 0; row_id < dictionary_size_; ++row_id) {\n                  const auto & row = B_table.\n                    Get<petuum::DenseRow<float> >(row_id, &row_acc);\n                  row.CopyToVector(&petuum_row_cache);\n                  // Regularize by C_\n                  RegVec(petuum_row_cache, C_, B_row_cache);\n                  for (int col_id = 0; col_id < m; ++col_id) {\n                    if (std::abs(B_row_cache[col_id]) < INFINITESIMAL) {\n                        B_row_cache[col_id] = 0.0;\n                    }\n                    fout_B << B_row_cache[col_id] << \"\\t\";\n                                   \n                    fout_B << \"\\n\";\n                  }\n                }\n                fout_B.close();\n\n                        \n        }\n        // Thread 0 of each client save that client's part of S \n        // to output_path_/S.[txt|bin].client_id_\n        if (thread_id == 0) {\n \n                std::string S_filename = output_path_ + \"/S.txt.\" \n                    + std::to_string(client_id_);\n                //fout_S.open(S_filename.c_str());\n\t\tpetuum::io::ofstream fout_S(S_filename);\n\n           \n            for (int col_id_client = 0; col_id_client < client_n; \n                    ++col_id_client) {\n                if (S_matrix_loader_.GetCol(col_id_client, S_cache)) {\n                    for (int row_id = 0; row_id < dictionary_size_; ++row_id) {\n                        if (std::abs(S_cache[row_id]) < INFINITESIMAL) {\n                            S_cache[row_id] = 0.0;\n                        }\n                        fout_S << S_cache[row_id] << \"\\t\";\n                        \n                    }\n                                                    fout_S << \"\\n\";\n                        \n                }\n            }\n            fout_S.close();\n        }\n    }\n\n    // Init B and S from cache file\n    void SCEngine::LoadCache(int thread_id, petuum::Table<float> & B_table) {\n        // size of matrices\n        int m = X_matrix_loader_.GetM();\n        int client_n = X_matrix_loader_.GetClientN();\n        if (client_id_ == 0 && thread_id == 0) {\n            // Load B\n\n            std::vector<float> B_row_cache(m);\n\n \n            std::string B_filename = cache_path_ + \"/B.txt\";\n            //fout_B.open(B_filename.c_str());\n\t    petuum::io::ifstream fout_B(B_filename);\n\n            \n            CHECK(fout_B.good()) \n                << \"Cache file \" << B_filename << \" does not exist!\";\n            for (int row_id = 0; row_id < dictionary_size_; ++row_id) {\n                petuum::UpdateBatch<float> B_update;\n                for (int col_id = 0; col_id < m; ++col_id) {\n                    if (input_data_format_ == \"text\") {\n                        fout_B >> B_row_cache[col_id];\n                    } else if (input_data_format_ == \"binary\") {\n                        fout_B.read(reinterpret_cast<char*> (\n                                &(B_row_cache[col_id])), 4);\n                    }\n                    B_update.Update(col_id, B_row_cache[col_id]);\n                }\n                B_table.BatchInc(row_id, B_update);\n            }\n            fout_B.close();\n        }\n        // Load S\n        if (thread_id == 0) {\n \n            std::vector<float> S_cache(dictionary_size_), \n                S_inc_cache(dictionary_size_);\n\n            std::string S_filename;\n                S_filename = cache_path_ + \"/S.txt.\" +\n                    std::to_string(client_id_);\n                   //fout_S.open(S_filename.c_str());\n\t    petuum::io::ifstream fout_S(S_filename);\n\n            \n            CHECK(fout_S.good()) \n                << \"Cache file \" << S_filename << \" does not exist!\";\n               for (int col_id_client = 0; col_id_client < client_n; \n                    ++col_id_client) {\n                   if (S_matrix_loader_.GetCol(col_id_client, S_cache)) {\n                       for (int row_id = 0; row_id < dictionary_size_; \n                            ++row_id) {\n                            fout_S >> S_inc_cache[row_id];\n                                                S_inc_cache[row_id] = \n                            S_inc_cache[row_id] - S_cache[row_id];\n                       }\n                    S_matrix_loader_.IncCol(col_id_client, S_inc_cache);\n                   }\n                S_matrix_loader_.GetCol(col_id_client, S_cache);\n               }\n               fout_S.close();\n        }\n    }\n\n    // Init B table\n    void SCEngine::InitRand(int thread_id, petuum::Table<float> & B_table) {\n        if (thread_id != 0 || client_id_ != 0)\n            return;\n        // size of matrices\n        int m = X_matrix_loader_.GetM();\n        srand((unsigned)time(NULL));\n        std::vector<float> B_row_cache(m);\n        // petuum row accessor\n        petuum::RowAccessor row_acc;\n        for (int row_id = 0; row_id < dictionary_size_; ++row_id) {\n            petuum::UpdateBatch<float> B_update;\n            for (int col_id = 0; col_id < m; ++col_id) {\n                B_row_cache[col_id] = double(rand()) / RAND_MAX * \n                    (init_B_high_ - init_B_low_) + init_B_low_;\n            }\n            for (int col_id = 0; col_id < m; ++col_id) {\n                B_update.Update(col_id, B_row_cache[col_id]);\n            }\n            B_table.BatchInc(row_id, B_update);\n        }\n    }\n\n    // Stochastic Gradient Descent Optimization\n    void SCEngine::Start() {\n        // thread id on a client\n        int thread_id = thread_counter_++;\n        petuum::PSTableGroup::RegisterThread();\n        LOG(INFO) << \"client \" << client_id_ << \", thread \" \n            << thread_id << \" registers!\";\n\n        // Get dictionary table and loss table\n        petuum::Table<float> B_table = \n            petuum::PSTableGroup::GetTableOrDie<float>(0);\n        petuum::Table<float> loss_table = \n            petuum::PSTableGroup::GetTableOrDie<float>(1);\n\n        // size of matrices\n        int m = X_matrix_loader_.GetM();\n        int client_n = X_matrix_loader_.GetClientN();\n\n        // Cache dictionary table \n        Eigen::MatrixXf petuum_table_cache(m, dictionary_size_);\n        // Accumulate update of dictionary table in minibatch\n        Eigen::MatrixXf petuum_update_cache(m, dictionary_size_);\n        // Cache a column of coefficients S\n        Eigen::VectorXf Sj(dictionary_size_);\n        // Cache a column of update of S_j\n        Eigen::VectorXf Sj_inc(dictionary_size_);\n        // Cache a column of data X \n        Eigen::VectorXf Xj(m);\n        Eigen::VectorXf Xj_inc(m);\n        // Cache a row of dictionary table\n        std::vector<float> petuum_row_cache(m);\n\n        // Register rows\n        if (thread_id == 0) {\n            for (int row_id = 0; row_id < dictionary_size_; ++row_id) {\n                B_table.GetAsyncForced(row_id);\n            }\n            int loss_table_size = num_eval_per_client_ * num_clients_ * 2;\n            for (int row_id = 0; row_id < loss_table_size; ++row_id) {\n                loss_table.GetAsyncForced(row_id);\n            }\n        }\n        petuum::PSTableGroup::GlobalBarrier();\n    \n        // initialize B\n        STATS_APP_INIT_BEGIN();\n        if (client_id_ == 0 && thread_id == 0) {\n            LOG(INFO) << \"starting to initialize B\";\n        }\n        if (load_cache_) {// load B and S from cache\n            LoadCache(thread_id, B_table);\n        } else { // randomly init B\n            InitRand(thread_id, B_table);\n        }\n        if (thread_id == 0 && client_id_ == 0) {\n            LOG(INFO) << \"matrix B initialization finished!\";\n        }\n        petuum::PSTableGroup::GlobalBarrier();\n        STATS_APP_INIT_END();\n\n        // Optimization Loop\n        // Timer\n        boost::posix_time::ptime beginT = \n            boost::posix_time::microsec_clock::local_time();\n        // Step size for optimization\n        float step_size_B = init_step_size_B_, step_size_S = init_step_size_S_;\n\n        int num_minibatch = 0;\n        for (int iter = 0; iter < num_epochs_; ++iter) {\n            // how many minibatches per epoch\n            int minibatch_per_epoch = (client_n / num_worker_threads_ > 0)? \n                client_n / num_worker_threads_: 1;\n            for (int iter_per_epoch = 0; iter_per_epoch * minibatch_size_ \n                    < minibatch_per_epoch; ++iter_per_epoch) {\n                boost::posix_time::time_duration runTime = \n                    boost::posix_time::microsec_clock::local_time() - initT_;\n                // Terminate and save states to disk if running time exceeds \n                // limit\n                if (maximum_running_time_ > 0.0 && \n                        (float) runTime.total_milliseconds() > \n                        maximum_running_time_*3600*1000) {\n                    LOG(INFO) << \"Maximum runtime limit activates, \"\n                        \"terminating now!\";\n                    petuum::PSTableGroup::GlobalBarrier();\n                    SaveResults(thread_id, B_table, loss_table);\n                    petuum::PSTableGroup::DeregisterThread();\n                    return;\n                }\n                // Update petuum table cache\n                petuum::RowAccessor row_acc;\n                for (int row_id = 0; row_id < dictionary_size_; ++row_id) {\n                    const auto & row = \n                        B_table.Get<petuum::DenseRow<float> >(row_id, &row_acc);\n                    row.CopyToVector(&petuum_row_cache);\n                    for (int col_id = 0; col_id < m; ++col_id) {\n                        petuum_table_cache(col_id, row_id) = \n                            petuum_row_cache[col_id];\n                    }\n                }\n                // evaluate obj\n                if (num_minibatch % num_eval_minibatch_ == 0) {\n                    boost::posix_time::time_duration elapTime = \n                        boost::posix_time::microsec_clock::local_time() - beginT;\n                    // evaluate partial obj\n                    double obj = 0.0;\n                    double obj1 = 0.0;\n                    double obj2 = 0.0;\n                    int num_samples = num_eval_samples_;\n                    for (int i = 0; i < dictionary_size_; ++i) {\n                        float regularizer = petuum_table_cache.col(i).norm();\n                        regularizer = \n                            (regularizer > sqrt(C_))? sqrt(C_) / regularizer: 1.0;\n                        petuum_table_cache.col(i) *= regularizer;\n                    }\n                    for (int i = 0; i < num_samples; ++i) {\n                        int col_id_client = 0;\n                        if (S_matrix_loader_.GetRandCol(col_id_client, Sj) \n                                && X_matrix_loader_.GetCol(col_id_client, Xj)) {\n                            Xj_inc = Xj - petuum_table_cache * Sj;\n                            obj1 += Xj_inc.squaredNorm() / num_samples;\n                            obj2 += lambda_ * Sj.lpNorm<1>() / num_samples;\n                        }\n                    }\n                    obj = obj1 + obj2;\n                    LOG(INFO) << \"iter: \" << num_minibatch << \", client \" \n                        << client_id_ << \", thread \" << thread_id <<\n                        \" mean loss: \" << obj \n                        << \", mean reconstruction error: \" << obj1\n                        << \", mean regularization: \" << obj2;\n                    // update loss table\n                    loss_table.Inc(client_id_ * num_eval_per_client_ + \n                            num_minibatch / num_eval_minibatch_,  0, \n                            obj/num_worker_threads_);\n                    loss_table.Inc((num_clients_+client_id_) * num_eval_per_client_ \n                            + num_minibatch / num_eval_minibatch_, 0, \n                            ((float) elapTime.total_milliseconds()) / 1000 \n                            / num_worker_threads_);\n                    beginT = boost::posix_time::microsec_clock::local_time();\n                }\n                step_size_B = init_step_size_B_ * \n                    pow(step_size_offset_B_ + num_minibatch, \n                            -1.0*step_size_pow_B_);\n                step_size_S = init_step_size_S_ * \n                    pow(step_size_offset_S_ + num_minibatch, \n                            -1.0*step_size_pow_S_);\n                num_minibatch++;\n                // clear update table\n                petuum_update_cache.fill(0.0);\n                // minibatch\n                for (int k = 0; k < minibatch_size_; ++k) {\n                    int col_id_client = 0;\n                    if (S_matrix_loader_.GetRandCol(col_id_client, Sj)\n                            && X_matrix_loader_.GetCol(col_id_client, Xj)) {\n                        // update S_j\n                        for (int iter_S = 0; \n                                iter_S < num_iter_S_per_minibatch_; ++iter_S) {\n                            // compute gradient of Sj\n                            Sj_inc = step_size_S * 2.0 *\n                                ( petuum_table_cache.transpose() \n                                 * (Xj - petuum_table_cache * Sj) );\n                            Sj.noalias() += Sj_inc;\n                            // proximal gradient descent to deal with l1 subgradient\n                            Sj = ((Sj.array() > step_size_S*lambda_).cast<float>() \n                                * (Sj.array() - step_size_S*lambda_) \n                                + (Sj.array() < -1.0*step_size_S*lambda_).cast<float>()\n                                * (Sj.array() + step_size_S*lambda_)).matrix();\n                            S_matrix_loader_.SetCol(col_id_client, Sj);\n                        \n                            // get updated S_j\n                            S_matrix_loader_.GetCol(col_id_client, Sj);\n                        }\n                        // update B\n                        Xj_inc = Xj - petuum_table_cache * Sj;\n                        petuum_update_cache.noalias() += \n                            step_size_B * 2.0 * Xj_inc * Sj.transpose();\n                    }\n                }\n                // Update B_table\n                for (int row_id = 0; row_id < dictionary_size_; ++row_id) {\n                    petuum::UpdateBatch<float> B_update;\n                    for (int col_id = 0; col_id < m; ++col_id) {\n                        B_update.Update(col_id, \n                                petuum_update_cache(col_id, row_id) \n                                / minibatch_size_);\n                    }\n                    B_table.BatchInc(row_id, B_update);\n                }\n                petuum::PSTableGroup::Clock();\n                // Update B_table to normalize l2-norm to C_\n                std::vector<float> B_row_cache(m);\n                for (int row_id = 0; row_id < dictionary_size_; ++row_id) {\n                    const auto & row = \n                        B_table.Get<petuum::DenseRow<float> >(row_id, &row_acc);\n                    row.CopyToVector(&petuum_row_cache);\n                    RegVec(petuum_row_cache, C_, B_row_cache);\n                    petuum::UpdateBatch<float> B_update;\n                    for (int col_id = 0; col_id < m; ++col_id) {\n                        B_update.Update(col_id, \n                                (-1.0 * petuum_row_cache[col_id] + \n                                B_row_cache[col_id]) / num_clients_ / \n                                num_worker_threads_);\n                    }\n                    B_table.BatchInc(row_id, B_update);\n                }\n                petuum::PSTableGroup::Clock(); \n            }\n        }\n        // Save results to disk\n        petuum::PSTableGroup::GlobalBarrier();\n        SaveResults(thread_id, B_table, loss_table);\n        petuum::PSTableGroup::DeregisterThread();\n    }\n\n    SCEngine::~SCEngine() {\n    }\n} // namespace sparsecoding\n", "meta": {"hexsha": "41a1bc98c2450db911e1694172133c9592e41301", "size": 25109, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/sparsecoding/src/SCEngine.cpp", "max_stars_repo_name": "daiwei89/wdai_petuum_public", "max_stars_repo_head_hexsha": "4068859897061201d0a63630a3da6011b0d0f75f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 370.0, "max_stars_repo_stars_event_min_datetime": "2015-06-30T09:46:17.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-21T07:14:00.000Z", "max_issues_repo_path": "app/sparsecoding/src/SCEngine.cpp", "max_issues_repo_name": "daiwei89/wdai_petuum_public", "max_issues_repo_head_hexsha": "4068859897061201d0a63630a3da6011b0d0f75f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-11-08T19:45:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-11-11T13:21:19.000Z", "max_forks_repo_path": "app/sparsecoding/src/SCEngine.cpp", "max_forks_repo_name": "daiwei89/wdai_petuum_public", "max_forks_repo_head_hexsha": "4068859897061201d0a63630a3da6011b0d0f75f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 159.0, "max_forks_repo_forks_event_min_datetime": "2015-07-03T05:58:31.000Z", "max_forks_repo_forks_event_max_datetime": "2016-12-29T20:59:01.000Z", "avg_line_length": 44.5985790409, "max_line_length": 87, "alphanum_fraction": 0.5104942451, "num_tokens": 5682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2366694651278724}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_MP_TOMMATH_BACKEND_HPP\n#define BOOST_MATH_MP_TOMMATH_BACKEND_HPP\n\n#include <boost/cstdint.hpp>\n#include <boost/functional/hash_fwd.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/multiprecision/detail/integer_ops.hpp>\n#include <boost/multiprecision/number.hpp>\n#include <boost/multiprecision/rational_adaptor.hpp>\n#include <boost/scoped_array.hpp>\n#include <cctype>\n#include <climits>\n#include <cmath>\n#include <limits>\n#include <tommath.h>\n\nnamespace boost {\nnamespace multiprecision {\nnamespace backends {\n\nnamespace detail {\n\ninline void check_tommath_result(unsigned v) {\n  if (v != MP_OKAY) {\n    BOOST_THROW_EXCEPTION(std::runtime_error(mp_error_to_string(v)));\n  }\n}\n\n} // namespace detail\n\nstruct tommath_int;\n\nvoid eval_multiply(tommath_int &t, const tommath_int &o);\nvoid eval_add(tommath_int &t, const tommath_int &o);\n\nstruct tommath_int {\n  typedef mpl::list<boost::int32_t, boost::long_long_type> signed_types;\n  typedef mpl::list<boost::uint32_t, boost::ulong_long_type> unsigned_types;\n  typedef mpl::list<long double> float_types;\n\n  tommath_int() { detail::check_tommath_result(mp_init(&m_data)); }\n  tommath_int(const tommath_int &o) {\n    detail::check_tommath_result(\n        mp_init_copy(&m_data, const_cast<::mp_int *>(&o.m_data)));\n  }\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n  tommath_int(tommath_int &&o) BOOST_NOEXCEPT {\n    m_data = o.m_data;\n    o.m_data.dp = 0;\n  }\n  tommath_int &operator=(tommath_int &&o) {\n    mp_exch(&m_data, &o.m_data);\n    return *this;\n  }\n#endif\n  tommath_int &operator=(const tommath_int &o) {\n    if (m_data.dp == 0)\n      detail::check_tommath_result(mp_init(&m_data));\n    if (o.m_data.dp)\n      detail::check_tommath_result(\n          mp_copy(const_cast<::mp_int *>(&o.m_data), &m_data));\n    return *this;\n  }\n  tommath_int &operator=(boost::ulong_long_type i) {\n    if (m_data.dp == 0)\n      detail::check_tommath_result(mp_init(&m_data));\n    boost::ulong_long_type mask =\n        ((1uLL << std::numeric_limits<unsigned>::digits) - 1);\n    unsigned shift = 0;\n    ::mp_int t;\n    detail::check_tommath_result(mp_init(&t));\n    mp_zero(&m_data);\n    while (i) {\n      detail::check_tommath_result(\n          mp_set_int(&t, static_cast<unsigned>(i & mask)));\n      if (shift)\n        detail::check_tommath_result(mp_mul_2d(&t, shift, &t));\n      detail::check_tommath_result((mp_add(&m_data, &t, &m_data)));\n      shift += std::numeric_limits<unsigned>::digits;\n      i >>= std::numeric_limits<unsigned>::digits;\n    }\n    mp_clear(&t);\n    return *this;\n  }\n  tommath_int &operator=(boost::long_long_type i) {\n    if (m_data.dp == 0)\n      detail::check_tommath_result(mp_init(&m_data));\n    bool neg = i < 0;\n    *this = boost::multiprecision::detail::unsigned_abs(i);\n    if (neg)\n      detail::check_tommath_result(mp_neg(&m_data, &m_data));\n    return *this;\n  }\n  //\n  // Note that although mp_set_int takes an unsigned long as an argument\n  // it only sets the first 32-bits to the result, and ignores the rest.\n  // So use uint32_t as the largest type to pass to this function.\n  //\n  tommath_int &operator=(boost::uint32_t i) {\n    if (m_data.dp == 0)\n      detail::check_tommath_result(mp_init(&m_data));\n    detail::check_tommath_result((mp_set_int(&m_data, i)));\n    return *this;\n  }\n  tommath_int &operator=(boost::int32_t i) {\n    if (m_data.dp == 0)\n      detail::check_tommath_result(mp_init(&m_data));\n    bool neg = i < 0;\n    *this = boost::multiprecision::detail::unsigned_abs(i);\n    if (neg)\n      detail::check_tommath_result(mp_neg(&m_data, &m_data));\n    return *this;\n  }\n  tommath_int &operator=(long double a) {\n    using std::floor;\n    using std::frexp;\n    using std::ldexp;\n\n    if (m_data.dp == 0)\n      detail::check_tommath_result(mp_init(&m_data));\n\n    if (a == 0) {\n      detail::check_tommath_result(mp_set_int(&m_data, 0));\n      return *this;\n    }\n\n    if (a == 1) {\n      detail::check_tommath_result(mp_set_int(&m_data, 1));\n      return *this;\n    }\n\n    BOOST_ASSERT(!(boost::math::isinf)(a));\n    BOOST_ASSERT(!(boost::math::isnan)(a));\n\n    int e;\n    long double f, term;\n    detail::check_tommath_result(mp_set_int(&m_data, 0u));\n    ::mp_int t;\n    detail::check_tommath_result(mp_init(&t));\n\n    f = frexp(a, &e);\n\n    static const int shift = std::numeric_limits<int>::digits - 1;\n\n    while (f) {\n      // extract int sized bits from f:\n      f = ldexp(f, shift);\n      term = floor(f);\n      e -= shift;\n      detail::check_tommath_result(mp_mul_2d(&m_data, shift, &m_data));\n      if (term > 0) {\n        detail::check_tommath_result(mp_set_int(&t, static_cast<int>(term)));\n        detail::check_tommath_result(mp_add(&m_data, &t, &m_data));\n      } else {\n        detail::check_tommath_result(mp_set_int(&t, static_cast<int>(-term)));\n        detail::check_tommath_result(mp_sub(&m_data, &t, &m_data));\n      }\n      f -= term;\n    }\n    if (e > 0)\n      detail::check_tommath_result(mp_mul_2d(&m_data, e, &m_data));\n    else if (e < 0) {\n      tommath_int t2;\n      detail::check_tommath_result(mp_div_2d(&m_data, -e, &m_data, &t2.data()));\n    }\n    mp_clear(&t);\n    return *this;\n  }\n  tommath_int &operator=(const char *s) {\n    //\n    // We don't use libtommath's own routine because it doesn't error check the\n    // input :-(\n    //\n    if (m_data.dp == 0)\n      detail::check_tommath_result(mp_init(&m_data));\n    std::size_t n = s ? std::strlen(s) : 0;\n    *this = static_cast<boost::uint32_t>(0u);\n    unsigned radix = 10;\n    bool isneg = false;\n    if (n && (*s == '-')) {\n      --n;\n      ++s;\n      isneg = true;\n    }\n    if (n && (*s == '0')) {\n      if ((n > 1) && ((s[1] == 'x') || (s[1] == 'X'))) {\n        radix = 16;\n        s += 2;\n        n -= 2;\n      } else {\n        radix = 8;\n        n -= 1;\n      }\n    }\n    if (n) {\n      if (radix == 8 || radix == 16) {\n        unsigned shift = radix == 8 ? 3 : 4;\n        unsigned block_count = DIGIT_BIT / shift;\n        unsigned block_shift = shift * block_count;\n        boost::ulong_long_type val, block;\n        while (*s) {\n          block = 0;\n          for (unsigned i = 0; (i < block_count); ++i) {\n            if (*s >= '0' && *s <= '9')\n              val = *s - '0';\n            else if (*s >= 'a' && *s <= 'f')\n              val = 10 + *s - 'a';\n            else if (*s >= 'A' && *s <= 'F')\n              val = 10 + *s - 'A';\n            else\n              val = 400;\n            if (val > radix) {\n              BOOST_THROW_EXCEPTION(std::runtime_error(\n                  \"Unexpected content found while parsing character string.\"));\n            }\n            block <<= shift;\n            block |= val;\n            if (!*++s) {\n              // final shift is different:\n              block_shift = (i + 1) * shift;\n              break;\n            }\n          }\n          detail::check_tommath_result(\n              mp_mul_2d(&data(), block_shift, &data()));\n          if (data().used)\n            data().dp[0] |= block;\n          else\n            *this = block;\n        }\n      } else {\n        // Base 10, we extract blocks of size 10^9 at a time, that way\n        // the number of multiplications is kept to a minimum:\n        boost::uint32_t block_mult = 1000000000;\n        while (*s) {\n          boost::uint32_t block = 0;\n          for (unsigned i = 0; i < 9; ++i) {\n            boost::uint32_t val;\n            if (*s >= '0' && *s <= '9')\n              val = *s - '0';\n            else\n              BOOST_THROW_EXCEPTION(std::runtime_error(\n                  \"Unexpected character encountered in input.\"));\n            block *= 10;\n            block += val;\n            if (!*++s) {\n              static const boost::uint32_t block_multiplier[9] = {\n                  10,      100,      1000,      10000,     100000,\n                  1000000, 10000000, 100000000, 1000000000};\n              block_mult = block_multiplier[i];\n              break;\n            }\n          }\n          tommath_int t;\n          t = block_mult;\n          eval_multiply(*this, t);\n          t = block;\n          eval_add(*this, t);\n        }\n      }\n    }\n    if (isneg)\n      this->negate();\n    return *this;\n  }\n  std::string str(std::streamsize /*digits*/, std::ios_base::fmtflags f) const {\n    BOOST_ASSERT(m_data.dp);\n    int base = 10;\n    if ((f & std::ios_base::oct) == std::ios_base::oct)\n      base = 8;\n    else if ((f & std::ios_base::hex) == std::ios_base::hex)\n      base = 16;\n    //\n    // sanity check, bases 8 and 16 are only available for positive numbers:\n    //\n    if ((base != 10) && m_data.sign)\n      BOOST_THROW_EXCEPTION(\n          std::runtime_error(\"Formatted output in bases 8 or 16 is only \"\n                             \"available for positive numbers\"));\n    int s;\n    detail::check_tommath_result(\n        mp_radix_size(const_cast<::mp_int *>(&m_data), base, &s));\n    boost::scoped_array<char> a(new char[s + 1]);\n    detail::check_tommath_result(\n        mp_toradix_n(const_cast<::mp_int *>(&m_data), a.get(), base, s + 1));\n    std::string result = a.get();\n    if (f & std::ios_base::uppercase)\n      for (size_t i = 0; i < result.length(); ++i)\n        result[i] = std::toupper(result[i]);\n    if ((base != 10) && (f & std::ios_base::showbase)) {\n      int pos = result[0] == '-' ? 1 : 0;\n      const char *pp =\n          base == 8 ? \"0\" : (f & std::ios_base::uppercase) ? \"0X\" : \"0x\";\n      result.insert(static_cast<std::string::size_type>(pos), pp);\n    }\n    if ((f & std::ios_base::showpos) && (result[0] != '-'))\n      result.insert(static_cast<std::string::size_type>(0), 1, '+');\n    return result;\n  }\n  ~tommath_int() {\n    if (m_data.dp)\n      mp_clear(&m_data);\n  }\n  void negate() {\n    BOOST_ASSERT(m_data.dp);\n    mp_neg(&m_data, &m_data);\n  }\n  int compare(const tommath_int &o) const {\n    BOOST_ASSERT(m_data.dp && o.m_data.dp);\n    return mp_cmp(const_cast<::mp_int *>(&m_data),\n                  const_cast<::mp_int *>(&o.m_data));\n  }\n  template <class V> int compare(V v) const {\n    tommath_int d;\n    tommath_int t(*this);\n    detail::check_tommath_result(mp_shrink(&t.data()));\n    d = v;\n    return t.compare(d);\n  }\n  ::mp_int &data() {\n    BOOST_ASSERT(m_data.dp);\n    return m_data;\n  }\n  const ::mp_int &data() const {\n    BOOST_ASSERT(m_data.dp);\n    return m_data;\n  }\n  void swap(tommath_int &o) BOOST_NOEXCEPT { mp_exch(&m_data, &o.data()); }\n\nprotected:\n  ::mp_int m_data;\n};\n\n#define BOOST_MP_TOMMATH_BIT_OP_CHECK(x)                                       \\\n  if (SIGN(&x.data()))                                                         \\\n  BOOST_THROW_EXCEPTION(std::runtime_error(                                    \\\n      \"Bitwise operations on libtommath negative valued integers are \"         \\\n      \"disabled as they produce unpredictable results\"))\n\nint eval_get_sign(const tommath_int &val);\n\ninline void eval_add(tommath_int &t, const tommath_int &o) {\n  detail::check_tommath_result(\n      mp_add(&t.data(), const_cast<::mp_int *>(&o.data()), &t.data()));\n}\ninline void eval_subtract(tommath_int &t, const tommath_int &o) {\n  detail::check_tommath_result(\n      mp_sub(&t.data(), const_cast<::mp_int *>(&o.data()), &t.data()));\n}\ninline void eval_multiply(tommath_int &t, const tommath_int &o) {\n  detail::check_tommath_result(\n      mp_mul(&t.data(), const_cast<::mp_int *>(&o.data()), &t.data()));\n}\ninline void eval_divide(tommath_int &t, const tommath_int &o) {\n  using default_ops::eval_is_zero;\n  tommath_int temp;\n  if (eval_is_zero(o))\n    BOOST_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n  detail::check_tommath_result(mp_div(\n      &t.data(), const_cast<::mp_int *>(&o.data()), &t.data(), &temp.data()));\n}\ninline void eval_modulus(tommath_int &t, const tommath_int &o) {\n  using default_ops::eval_is_zero;\n  if (eval_is_zero(o))\n    BOOST_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n  bool neg = eval_get_sign(t) < 0;\n  bool neg2 = eval_get_sign(o) < 0;\n  detail::check_tommath_result(\n      mp_mod(&t.data(), const_cast<::mp_int *>(&o.data()), &t.data()));\n  if ((neg != neg2) && (eval_get_sign(t) != 0)) {\n    t.negate();\n    detail::check_tommath_result(\n        mp_add(&t.data(), const_cast<::mp_int *>(&o.data()), &t.data()));\n    t.negate();\n  } else if (neg && (t.compare(o) == 0)) {\n    mp_zero(&t.data());\n  }\n}\ntemplate <class UI> inline void eval_left_shift(tommath_int &t, UI i) {\n  detail::check_tommath_result(\n      mp_mul_2d(&t.data(), static_cast<unsigned>(i), &t.data()));\n}\ntemplate <class UI> inline void eval_right_shift(tommath_int &t, UI i) {\n  using default_ops::eval_decrement;\n  using default_ops::eval_increment;\n  bool neg = eval_get_sign(t) < 0;\n  tommath_int d;\n  if (neg)\n    eval_increment(t);\n  detail::check_tommath_result(\n      mp_div_2d(&t.data(), static_cast<unsigned>(i), &t.data(), &d.data()));\n  if (neg)\n    eval_decrement(t);\n}\ntemplate <class UI>\ninline void eval_left_shift(tommath_int &t, const tommath_int &v, UI i) {\n  detail::check_tommath_result(mp_mul_2d(const_cast<::mp_int *>(&v.data()),\n                                         static_cast<unsigned>(i), &t.data()));\n}\n/*\ntemplate <class UI>\ninline void eval_right_shift(tommath_int& t, const tommath_int& v, UI i)\n{\n   tommath_int d;\n   detail::check_tommath_result(mp_div_2d(const_cast< ::mp_int*>(&v.data()),\nstatic_cast<unsigned long>(i), &t.data(), &d.data()));\n}\n*/\ninline void eval_bitwise_and(tommath_int &result, const tommath_int &v) {\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(result);\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n  detail::check_tommath_result(mp_and(\n      &result.data(), const_cast<::mp_int *>(&v.data()), &result.data()));\n}\n\ninline void eval_bitwise_or(tommath_int &result, const tommath_int &v) {\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(result);\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n  detail::check_tommath_result(\n      mp_or(&result.data(), const_cast<::mp_int *>(&v.data()), &result.data()));\n}\n\ninline void eval_bitwise_xor(tommath_int &result, const tommath_int &v) {\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(result);\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n  detail::check_tommath_result(mp_xor(\n      &result.data(), const_cast<::mp_int *>(&v.data()), &result.data()));\n}\n\ninline void eval_add(tommath_int &t, const tommath_int &p,\n                     const tommath_int &o) {\n  detail::check_tommath_result(mp_add(const_cast<::mp_int *>(&p.data()),\n                                      const_cast<::mp_int *>(&o.data()),\n                                      &t.data()));\n}\ninline void eval_subtract(tommath_int &t, const tommath_int &p,\n                          const tommath_int &o) {\n  detail::check_tommath_result(mp_sub(const_cast<::mp_int *>(&p.data()),\n                                      const_cast<::mp_int *>(&o.data()),\n                                      &t.data()));\n}\ninline void eval_multiply(tommath_int &t, const tommath_int &p,\n                          const tommath_int &o) {\n  detail::check_tommath_result(mp_mul(const_cast<::mp_int *>(&p.data()),\n                                      const_cast<::mp_int *>(&o.data()),\n                                      &t.data()));\n}\ninline void eval_divide(tommath_int &t, const tommath_int &p,\n                        const tommath_int &o) {\n  using default_ops::eval_is_zero;\n  tommath_int d;\n  if (eval_is_zero(o))\n    BOOST_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n  detail::check_tommath_result(mp_div(const_cast<::mp_int *>(&p.data()),\n                                      const_cast<::mp_int *>(&o.data()),\n                                      &t.data(), &d.data()));\n}\ninline void eval_modulus(tommath_int &t, const tommath_int &p,\n                         const tommath_int &o) {\n  using default_ops::eval_is_zero;\n  if (eval_is_zero(o))\n    BOOST_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n  bool neg = eval_get_sign(p) < 0;\n  bool neg2 = eval_get_sign(o) < 0;\n  detail::check_tommath_result(mp_mod(const_cast<::mp_int *>(&p.data()),\n                                      const_cast<::mp_int *>(&o.data()),\n                                      &t.data()));\n  if ((neg != neg2) && (eval_get_sign(t) != 0)) {\n    t.negate();\n    detail::check_tommath_result(\n        mp_add(&t.data(), const_cast<::mp_int *>(&o.data()), &t.data()));\n    t.negate();\n  } else if (neg && (t.compare(o) == 0)) {\n    mp_zero(&t.data());\n  }\n}\n\ninline void eval_bitwise_and(tommath_int &result, const tommath_int &u,\n                             const tommath_int &v) {\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(u);\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n  detail::check_tommath_result(mp_and(const_cast<::mp_int *>(&u.data()),\n                                      const_cast<::mp_int *>(&v.data()),\n                                      &result.data()));\n}\n\ninline void eval_bitwise_or(tommath_int &result, const tommath_int &u,\n                            const tommath_int &v) {\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(u);\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n  detail::check_tommath_result(mp_or(const_cast<::mp_int *>(&u.data()),\n                                     const_cast<::mp_int *>(&v.data()),\n                                     &result.data()));\n}\n\ninline void eval_bitwise_xor(tommath_int &result, const tommath_int &u,\n                             const tommath_int &v) {\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(u);\n  BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n  detail::check_tommath_result(mp_xor(const_cast<::mp_int *>(&u.data()),\n                                      const_cast<::mp_int *>(&v.data()),\n                                      &result.data()));\n}\n/*\ninline void eval_complement(tommath_int& result, const tommath_int& u)\n{\n   //\n   // Although this code works, it doesn't really do what the user might\nexpect....\n   // and it's hard to see how it ever could.  Disabled for now:\n   //\n   result = u;\n   for(int i = 0; i < result.data().used; ++i)\n   {\n      result.data().dp[i] = MP_MASK & ~(result.data().dp[i]);\n   }\n   //\n   // We now need to pad out the left of the value with 1's to round up to a\nwhole number of\n   // CHAR_BIT * sizeof(mp_digit) units.  Otherwise we'll end up with a very\nstrange number of\n   // bits set!\n   //\n   unsigned shift = result.data().used * DIGIT_BIT;    // How many bits we're\nactually using\n   // How many bits we actually need, reduced by one to account for a mythical\nsign bit: int padding = result.data().used *\nstd::numeric_limits<mp_digit>::digits - shift - 1; while(padding >=\nstd::numeric_limits<mp_digit>::digits) padding -=\nstd::numeric_limits<mp_digit>::digits;\n\n   // Create a mask providing the extra bits we need and add to result:\n   tommath_int mask;\n   mask = static_cast<boost::long_long_type>((1u << padding) - 1);\n   eval_left_shift(mask, shift);\n   add(result, mask);\n}\n*/\ninline bool eval_is_zero(const tommath_int &val) {\n  return mp_iszero(&val.data());\n}\ninline int eval_get_sign(const tommath_int &val) {\n  return mp_iszero(&val.data()) ? 0 : SIGN(&val.data()) ? -1 : 1;\n}\n/*\ntemplate <class A>\ninline void eval_convert_to(A* result, const tommath_int& val)\n{\n   *result = boost::lexical_cast<A>(val.str(0, std::ios_base::fmtflags(0)));\n}\ninline void eval_convert_to(char* result, const tommath_int& val)\n{\n   *result = static_cast<char>(boost::lexical_cast<int>(val.str(0,\nstd::ios_base::fmtflags(0))));\n}\ninline void eval_convert_to(unsigned char* result, const tommath_int& val)\n{\n   *result = static_cast<unsigned char>(boost::lexical_cast<unsigned>(val.str(0,\nstd::ios_base::fmtflags(0))));\n}\ninline void eval_convert_to(signed char* result, const tommath_int& val)\n{\n   *result = static_cast<signed char>(boost::lexical_cast<int>(val.str(0,\nstd::ios_base::fmtflags(0))));\n}\n*/\ninline void eval_abs(tommath_int &result, const tommath_int &val) {\n  detail::check_tommath_result(\n      mp_abs(const_cast<::mp_int *>(&val.data()), &result.data()));\n}\ninline void eval_gcd(tommath_int &result, const tommath_int &a,\n                     const tommath_int &b) {\n  detail::check_tommath_result(mp_gcd(const_cast<::mp_int *>(&a.data()),\n                                      const_cast<::mp_int *>(&b.data()),\n                                      const_cast<::mp_int *>(&result.data())));\n}\ninline void eval_lcm(tommath_int &result, const tommath_int &a,\n                     const tommath_int &b) {\n  detail::check_tommath_result(mp_lcm(const_cast<::mp_int *>(&a.data()),\n                                      const_cast<::mp_int *>(&b.data()),\n                                      const_cast<::mp_int *>(&result.data())));\n}\ninline void eval_powm(tommath_int &result, const tommath_int &base,\n                      const tommath_int &p, const tommath_int &m) {\n  if (eval_get_sign(p) < 0) {\n    BOOST_THROW_EXCEPTION(\n        std::runtime_error(\"powm requires a positive exponent.\"));\n  }\n  detail::check_tommath_result(mp_exptmod(\n      const_cast<::mp_int *>(&base.data()), const_cast<::mp_int *>(&p.data()),\n      const_cast<::mp_int *>(&m.data()), &result.data()));\n}\n\ninline void eval_qr(const tommath_int &x, const tommath_int &y, tommath_int &q,\n                    tommath_int &r) {\n  detail::check_tommath_result(mp_div(const_cast<::mp_int *>(&x.data()),\n                                      const_cast<::mp_int *>(&y.data()),\n                                      &q.data(), &r.data()));\n}\n\ninline unsigned eval_lsb(const tommath_int &val) {\n  int c = eval_get_sign(val);\n  if (c == 0) {\n    BOOST_THROW_EXCEPTION(std::range_error(\"No bits were set in the operand.\"));\n  }\n  if (c < 0) {\n    BOOST_THROW_EXCEPTION(\n        std::range_error(\"Testing individual bits in negative values is not \"\n                         \"supported - results are undefined.\"));\n  }\n  return mp_cnt_lsb(const_cast<::mp_int *>(&val.data()));\n}\n\ninline unsigned eval_msb(const tommath_int &val) {\n  int c = eval_get_sign(val);\n  if (c == 0) {\n    BOOST_THROW_EXCEPTION(std::range_error(\"No bits were set in the operand.\"));\n  }\n  if (c < 0) {\n    BOOST_THROW_EXCEPTION(\n        std::range_error(\"Testing individual bits in negative values is not \"\n                         \"supported - results are undefined.\"));\n  }\n  return mp_count_bits(const_cast<::mp_int *>(&val.data())) - 1;\n}\n\ntemplate <class Integer>\ninline typename enable_if<is_unsigned<Integer>, Integer>::type\neval_integer_modulus(const tommath_int &x, Integer val) {\n  static const mp_digit m = (static_cast<mp_digit>(1) << DIGIT_BIT) - 1;\n  if (val <= m) {\n    mp_digit d;\n    detail::check_tommath_result(mp_mod_d(const_cast<::mp_int *>(&x.data()),\n                                          static_cast<mp_digit>(val), &d));\n    return d;\n  } else {\n    return default_ops::eval_integer_modulus(x, val);\n  }\n}\ntemplate <class Integer>\ninline typename enable_if<is_signed<Integer>, Integer>::type\neval_integer_modulus(const tommath_int &x, Integer val) {\n  return eval_integer_modulus(x,\n                              boost::multiprecision::detail::unsigned_abs(val));\n}\n\ninline std::size_t hash_value(const tommath_int &val) {\n  std::size_t result = 0;\n  std::size_t len = val.data().used;\n  for (std::size_t i = 0; i < len; ++i)\n    boost::hash_combine(result, val.data().dp[i]);\n  boost::hash_combine(result, val.data().sign);\n  return result;\n}\n\n} // namespace backends\n\nusing boost::multiprecision::backends::tommath_int;\n\ntemplate <>\nstruct number_category<tommath_int> : public mpl::int_<number_kind_integer> {};\n\ntypedef number<tommath_int> tom_int;\ntypedef rational_adaptor<tommath_int> tommath_rational;\ntypedef number<tommath_rational> tom_rational;\n\n} // namespace multiprecision\n} // namespace boost\n\nnamespace std {\n\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nclass numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>> {\n  typedef boost::multiprecision::number<boost::multiprecision::tommath_int,\n                                        ExpressionTemplates>\n      number_type;\n\npublic:\n  BOOST_STATIC_CONSTEXPR bool is_specialized = true;\n  //\n  // Largest and smallest numbers are bounded only by available memory, set\n  // to zero:\n  //\n  static number_type(min)() { return number_type(); }\n  static number_type(max)() { return number_type(); }\n  static number_type lowest() { return (min)(); }\n  BOOST_STATIC_CONSTEXPR int digits = INT_MAX;\n  BOOST_STATIC_CONSTEXPR int digits10 = (INT_MAX / 1000) * 301L;\n  BOOST_STATIC_CONSTEXPR int max_digits10 = digits10 + 3;\n  BOOST_STATIC_CONSTEXPR bool is_signed = true;\n  BOOST_STATIC_CONSTEXPR bool is_integer = true;\n  BOOST_STATIC_CONSTEXPR bool is_exact = true;\n  BOOST_STATIC_CONSTEXPR int radix = 2;\n  static number_type epsilon() { return number_type(); }\n  static number_type round_error() { return number_type(); }\n  BOOST_STATIC_CONSTEXPR int min_exponent = 0;\n  BOOST_STATIC_CONSTEXPR int min_exponent10 = 0;\n  BOOST_STATIC_CONSTEXPR int max_exponent = 0;\n  BOOST_STATIC_CONSTEXPR int max_exponent10 = 0;\n  BOOST_STATIC_CONSTEXPR bool has_infinity = false;\n  BOOST_STATIC_CONSTEXPR bool has_quiet_NaN = false;\n  BOOST_STATIC_CONSTEXPR bool has_signaling_NaN = false;\n  BOOST_STATIC_CONSTEXPR float_denorm_style has_denorm = denorm_absent;\n  BOOST_STATIC_CONSTEXPR bool has_denorm_loss = false;\n  static number_type infinity() { return number_type(); }\n  static number_type quiet_NaN() { return number_type(); }\n  static number_type signaling_NaN() { return number_type(); }\n  static number_type denorm_min() { return number_type(); }\n  BOOST_STATIC_CONSTEXPR bool is_iec559 = false;\n  BOOST_STATIC_CONSTEXPR bool is_bounded = false;\n  BOOST_STATIC_CONSTEXPR bool is_modulo = false;\n  BOOST_STATIC_CONSTEXPR bool traps = false;\n  BOOST_STATIC_CONSTEXPR bool tinyness_before = false;\n  BOOST_STATIC_CONSTEXPR float_round_style round_style = round_toward_zero;\n};\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::digits;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::digits10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::max_digits10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::is_signed;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::is_integer;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::is_exact;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::radix;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::min_exponent;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::min_exponent10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::max_exponent;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::max_exponent10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::has_infinity;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::has_quiet_NaN;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<\n    boost::multiprecision::number<boost::multiprecision::tommath_int,\n                                  ExpressionTemplates>>::has_signaling_NaN;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST float_denorm_style\n    numeric_limits<boost::multiprecision::number<\n        boost::multiprecision::tommath_int, ExpressionTemplates>>::has_denorm;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::has_denorm_loss;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::is_iec559;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::is_bounded;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::is_modulo;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::traps;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<\n    boost::multiprecision::tommath_int, ExpressionTemplates>>::tinyness_before;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST float_round_style\n    numeric_limits<boost::multiprecision::number<\n        boost::multiprecision::tommath_int, ExpressionTemplates>>::round_style;\n\n#endif\n} // namespace std\n\n#endif\n", "meta": {"hexsha": "05df9d65c2c3ac65200b59751601f7f0b67cfe65", "size": 31274, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/boost_1_72_0/boost/multiprecision/tommath.hpp", "max_stars_repo_name": "henrywarhurst/matrix", "max_stars_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/boost_1_72_0/boost/multiprecision/tommath.hpp", "max_issues_repo_name": "henrywarhurst/matrix", "max_issues_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/boost_1_72_0/boost/multiprecision/tommath.hpp", "max_forks_repo_name": "henrywarhurst/matrix", "max_forks_repo_head_hexsha": "317a2a7c35c1c7e3730986668ad2270dc19809ef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1414267835, "max_line_length": 80, "alphanum_fraction": 0.6521071817, "num_tokens": 8001, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2366694651278724}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <array>\n#include <boost/functional/hash.hpp>  // IWYU pragma: keep\n#include <cstddef>\n#include <limits>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <utility>\n\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/Tensor/Tensor.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/SizeOfElement.hpp\"\n#include \"Domain/Structure/Element.hpp\"  // IWYU pragma: keep\n#include \"Domain/Structure/OrientationMapHelpers.hpp\"\n#include \"Domain/Tags.hpp\"  // IWYU pragma: keep\n#include \"Evolution/DiscontinuousGalerkin/Limiters/HwenoImpl.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodTci.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/MinmodType.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/SimpleWenoImpl.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoGridHelpers.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoHelpers.hpp\"\n#include \"Evolution/DiscontinuousGalerkin/Limiters/WenoType.hpp\"\n#include \"NumericalAlgorithms/Interpolation/RegularGridInterpolant.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/MeanValue.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Options/Options.hpp\"\n#include \"Utilities/Algorithm.hpp\"\n#include \"Utilities/ErrorHandling/Assert.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeArray.hpp\"\n#include \"Utilities/TMPL.hpp\"\n#include \"Utilities/TaggedTuple.hpp\"\n\n/// \\cond\ntemplate <size_t VolumeDim>\nclass Direction;\ntemplate <size_t VolumeDim>\nclass ElementId;\n\nnamespace PUP {\nclass er;\n}  // namespace PUP\n\nnamespace Limiters {\ntemplate <size_t VolumeDim, typename TagsToLimit>\nclass Weno;\n}  // namespace Limiters\n/// \\endcond\n\nnamespace Limiters {\n/// \\ingroup LimitersGroup\n/// \\brief A compact-stencil WENO limiter for DG\n///\n/// Implements the simple WENO limiter of \\cite Zhong2013 and the Hermite WENO\n/// (HWENO) limiter of \\cite Zhu2016 for an arbitrary set of tensors. These\n/// limiters require communication only between nearest-neighbor elements, but\n/// preserve the full order of the DG solution when the solution is smooth.\n/// Full volume data is communicated between neighbors.\n///\n/// The limiter uses the minmod-based TVB troubled-cell indicator (TCI) of\n/// \\cite Cockburn1999 to identify elements that need limiting. The simple\n/// WENO implementation follows the paper: it checks the TCI independently\n/// to each tensor component, so that only certain tensor components may be\n/// limited. The HWENO implementation checks the TCI for all tensor components,\n/// and if any single component is troubled, then all components are limited.\n/// Note that the HWENO paper, because it specializes the limiter to the\n/// Newtonian Euler fluid system, uses a more sophisticated TCI that is adapted\n/// to the particulars of the fluid system. We instead use the TVB indicator\n/// because it is easily applied to a general set of tensors.\n///\n/// For each tensor component to limit, the new solution is obtained by WENO\n/// reconstruction --- a linear combination of the local DG solution and a\n/// \"modified\" solution from each neighbor element. For the simple WENO limiter,\n/// the modified solution is obtained by simply extrapolating the neighbor\n/// solution onto the troubled element. For the HWENO limiter, the modified\n/// solution is obtained by a least-squares fit to the solution across multiple\n/// neighboring elements.\n///\n/// To reconstruct the WENO solution from the local solution and the modified\n/// neighbor solutions, the standard WENO procedure is followed. We use the\n/// oscillation indicator of \\cite Dumbser2007, modified for use on the\n/// square/cube grids of SpECTRE. We favor this indicator because portions of\n/// the work can be precomputed, leading to an oscillation measure that is\n/// efficient to evaluate.\n///\n/// \\warning\n/// Limitations:\n/// - Does not support non-Legendre bases; this is ASSERTed.\n/// - Does not support h- or p-refinement; this is ASSERTed.\n/// - Does not support curved elements; this is not enforced.\ntemplate <size_t VolumeDim, typename... Tags>\nclass Weno<VolumeDim, tmpl::list<Tags...>> {\n public:\n  /// \\brief The WenoType\n  ///\n  /// One of `Limiters::WenoType`. See the `Limiters::Weno`\n  /// documentation for details.\n  struct Type {\n    using type = WenoType;\n    static constexpr Options::String help = {\"Type of WENO limiter\"};\n  };\n  /// \\brief The linear weight given to each neighbor\n  ///\n  /// This linear weight gets combined with the oscillation indicator to\n  /// compute the weight for each WENO estimated solution. The standard value\n  /// in the literature is 0.001; larger values may be better suited for\n  /// problems with strong shocks, and smaller values may be better suited to\n  /// smooth problems.\n  struct NeighborWeight {\n    using type = double;\n    static type lower_bound() noexcept { return 1e-6; }\n    static type upper_bound() noexcept { return 0.1; }\n    static constexpr Options::String help = {\n        \"Linear weight for each neighbor element's solution\"};\n  };\n  /// \\brief The TVB constant for the minmod TCI\n  ///\n  /// See `Limiters::Minmod` documentation for details.\n  struct TvbConstant {\n    using type = double;\n    static type lower_bound() noexcept { return 0.0; }\n    static constexpr Options::String help = {\"TVB constant 'm'\"};\n  };\n  /// \\brief Turn the limiter off\n  ///\n  /// This option exists to temporarily disable the limiter for debugging\n  /// purposes. For problems where limiting is not needed, the preferred\n  /// approach is to not compile the limiter into the executable.\n  struct DisableForDebugging {\n    using type = bool;\n    static type suggested_value() noexcept { return false; }\n    static constexpr Options::String help = {\"Disable the limiter\"};\n  };\n  using options =\n      tmpl::list<Type, NeighborWeight, TvbConstant, DisableForDebugging>;\n  static constexpr Options::String help = {\"A WENO limiter for DG\"};\n\n  Weno(WenoType weno_type, double neighbor_linear_weight, double tvb_constant,\n       bool disable_for_debugging = false) noexcept;\n\n  Weno() noexcept = default;\n  Weno(const Weno& /*rhs*/) = default;\n  Weno& operator=(const Weno& /*rhs*/) = default;\n  Weno(Weno&& /*rhs*/) noexcept = default;\n  Weno& operator=(Weno&& /*rhs*/) noexcept = default;\n  ~Weno() = default;\n\n  // NOLINTNEXTLINE(google-runtime-references)\n  void pup(PUP::er& p) noexcept;\n\n  /// \\brief Data to send to neighbor elements\n  struct PackagedData {\n    Variables<tmpl::list<Tags...>> volume_data;\n    tuples::TaggedTuple<::Tags::Mean<Tags>...> means;\n    Mesh<VolumeDim> mesh;\n    std::array<double, VolumeDim> element_size =\n        make_array<VolumeDim>(std::numeric_limits<double>::signaling_NaN());\n\n    // NOLINTNEXTLINE(google-runtime-references)\n    void pup(PUP::er& p) noexcept {\n      p | volume_data;\n      p | means;\n      p | mesh;\n      p | element_size;\n    }\n  };\n\n  using package_argument_tags =\n      tmpl::list<Tags..., domain::Tags::Mesh<VolumeDim>,\n                 domain::Tags::SizeOfElement<VolumeDim>>;\n\n  /// \\brief Package data for sending to neighbor elements\n  void package_data(gsl::not_null<PackagedData*> packaged_data,\n                    const typename Tags::type&... tensors,\n                    const Mesh<VolumeDim>& mesh,\n                    const std::array<double, VolumeDim>& element_size,\n                    const OrientationMap<VolumeDim>& orientation_map) const\n      noexcept;\n\n  using limit_tags = tmpl::list<Tags...>;\n  using limit_argument_tags =\n      tmpl::list<domain::Tags::Mesh<VolumeDim>,\n                 domain::Tags::Element<VolumeDim>,\n                 domain::Tags::SizeOfElement<VolumeDim>>;\n\n  /// \\brief Limit the solution on the element\n  bool operator()(\n      const gsl::not_null<std::add_pointer_t<typename Tags::type>>... tensors,\n      const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n      const std::array<double, VolumeDim>& element_size,\n      const std::unordered_map<\n          std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,\n          boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n          neighbor_data) const noexcept;\n\n private:\n  template <size_t LocalDim, typename LocalTagList>\n  // NOLINTNEXTLINE(readability-redundant-declaration) false positive\n  friend bool operator==(const Weno<LocalDim, LocalTagList>& lhs,\n                         const Weno<LocalDim, LocalTagList>& rhs) noexcept;\n\n  WenoType weno_type_;\n  double neighbor_linear_weight_;\n  double tvb_constant_;\n  bool disable_for_debugging_;\n};\n\ntemplate <size_t VolumeDim, typename... Tags>\nWeno<VolumeDim, tmpl::list<Tags...>>::Weno(\n    const WenoType weno_type, const double neighbor_linear_weight,\n    const double tvb_constant, const bool disable_for_debugging) noexcept\n    : weno_type_(weno_type),\n      neighbor_linear_weight_(neighbor_linear_weight),\n      tvb_constant_(tvb_constant),\n      disable_for_debugging_(disable_for_debugging) {}\n\ntemplate <size_t VolumeDim, typename... Tags>\n// NOLINTNEXTLINE(google-runtime-references)\nvoid Weno<VolumeDim, tmpl::list<Tags...>>::pup(PUP::er& p) noexcept {\n  p | weno_type_;\n  p | neighbor_linear_weight_;\n  p | tvb_constant_;\n  p | disable_for_debugging_;\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nvoid Weno<VolumeDim, tmpl::list<Tags...>>::package_data(\n    const gsl::not_null<PackagedData*> packaged_data,\n    const typename Tags::type&... tensors, const Mesh<VolumeDim>& mesh,\n    const std::array<double, VolumeDim>& element_size,\n    const OrientationMap<VolumeDim>& orientation_map) const noexcept {\n  // By always initializing the PackagedData Variables member, we avoid an\n  // assertion that arises from having a default-constructed Variables in a\n  // disabled limiter. There is a performance cost, because the package_data()\n  // function does non-zero work even for a disabled limiter... but since the\n  // limiter should never be disabled in a production simulation, this cost\n  // should never matter.\n  (packaged_data->volume_data).initialize(mesh.number_of_grid_points());\n\n  if (UNLIKELY(disable_for_debugging_)) {\n    // Do not initialize packaged_data\n    // (except for the Variables member \"volume_data\", see above)\n    return;\n  }\n\n  const auto wrap_compute_means = [&mesh, &packaged_data](\n                                      auto tag, const auto tensor) noexcept {\n    for (size_t i = 0; i < tensor.size(); ++i) {\n      // Compute the mean using the local orientation of the tensor and mesh.\n      get<::Tags::Mean<decltype(tag)>>(packaged_data->means)[i] =\n          mean_value(tensor[i], mesh);\n    }\n    return '0';\n  };\n  expand_pack(wrap_compute_means(Tags{}, tensors)...);\n\n  packaged_data->element_size =\n      orientation_map.permute_from_neighbor(element_size);\n\n  const auto wrap_copy_tensor = [&packaged_data](auto tag,\n                                                 const auto tensor) noexcept {\n    get<decltype(tag)>(packaged_data->volume_data) = tensor;\n    return '0';\n  };\n  expand_pack(wrap_copy_tensor(Tags{}, tensors)...);\n  packaged_data->volume_data = orient_variables(\n      packaged_data->volume_data, mesh.extents(), orientation_map);\n\n  packaged_data->mesh = orientation_map(mesh);\n}\n\ntemplate <size_t VolumeDim, typename... Tags>\nbool Weno<VolumeDim, tmpl::list<Tags...>>::operator()(\n    const gsl::not_null<std::add_pointer_t<typename Tags::type>>... tensors,\n    const Mesh<VolumeDim>& mesh, const Element<VolumeDim>& element,\n    const std::array<double, VolumeDim>& element_size,\n    const std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, PackagedData,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>&\n        neighbor_data) const noexcept {\n  if (UNLIKELY(disable_for_debugging_)) {\n    // Do not modify input tensors\n    return false;\n  }\n\n  // Check that basis is LGL or LG\n  // A Legendre basis is assumed for the oscillation indicator (used in both\n  // SimpleWeno and Hweno) and in the Hweno reconstruction.\n  ASSERT(mesh.basis() == make_array<VolumeDim>(Spectral::Basis::Legendre),\n         \"Unsupported basis: \" << mesh);\n  ASSERT(mesh.quadrature() ==\n                 make_array<VolumeDim>(Spectral::Quadrature::GaussLobatto) or\n             mesh.quadrature() ==\n                 make_array<VolumeDim>(Spectral::Quadrature::Gauss),\n         \"Unsupported quadrature: \" << mesh);\n\n  // Enforce restrictions on h-refinement, p-refinement\n  if (UNLIKELY(alg::any_of(element.neighbors(),\n                           [](const auto& direction_neighbors) noexcept {\n                             return direction_neighbors.second.size() != 1;\n                           }))) {\n    ERROR(\"The Weno limiter does not yet support h-refinement\");\n    // Removing this limitation will require:\n    // - Generalizing the computation of the modified neighbor solutions.\n    // - Generalizing the WENO weighted sum for multiple neighbors in each\n    //   direction.\n  }\n  alg::for_each(neighbor_data, [&mesh](const auto& neighbor_and_data) noexcept {\n    if (UNLIKELY(neighbor_and_data.second.mesh != mesh)) {\n      ERROR(\"The Weno limiter does not yet support p-refinement\");\n      // Removing this limitation will require generalizing the\n      // computation of the modified neighbor solutions.\n    }\n  });\n\n  if (weno_type_ == WenoType::Hweno) {\n    // Troubled-cell detection for HWENO flags the element for limiting if any\n    // component of any tensor needs limiting.\n    const bool cell_is_troubled =\n        Tci::tvb_minmod_indicator<VolumeDim, PackagedData, Tags...>(\n            tvb_constant_, (*tensors)..., mesh, element, element_size,\n            neighbor_data);\n    if (not cell_is_troubled) {\n      // No limiting is needed\n      return false;\n    }\n\n    std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, DataVector,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n        modified_neighbor_solution_buffer{};\n    for (const auto& neighbor_and_data : neighbor_data) {\n      const auto& neighbor = neighbor_and_data.first;\n      modified_neighbor_solution_buffer.insert(\n          make_pair(neighbor, DataVector(mesh.number_of_grid_points())));\n    }\n\n    EXPAND_PACK_LEFT_TO_RIGHT(Weno_detail::hweno_impl<Tags>(\n        make_not_null(&modified_neighbor_solution_buffer), tensors,\n        neighbor_linear_weight_, mesh, element, neighbor_data));\n    return true;  // cell_is_troubled\n\n  } else if (weno_type_ == WenoType::SimpleWeno) {\n    // Buffers and pre-computations for TCI\n    Minmod_detail::BufferWrapper<VolumeDim> tci_buffer(mesh);\n    const auto effective_neighbor_sizes =\n        Minmod_detail::compute_effective_neighbor_sizes(element, neighbor_data);\n\n    // Buffers for simple WENO implementation\n    std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>,\n        intrp::RegularGrid<VolumeDim>,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n        interpolator_buffer{};\n    std::unordered_map<\n        std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>, DataVector,\n        boost::hash<std::pair<Direction<VolumeDim>, ElementId<VolumeDim>>>>\n        modified_neighbor_solution_buffer{};\n\n    bool some_component_was_limited = false;\n\n    const auto wrap_minmod_tci_and_simple_weno_impl =\n        [this, &some_component_was_limited, &tci_buffer, &interpolator_buffer,\n         &modified_neighbor_solution_buffer, &mesh, &element, &element_size,\n         &neighbor_data,\n         &effective_neighbor_sizes](auto tag, const auto tensor) noexcept {\n          for (size_t tensor_storage_index = 0;\n               tensor_storage_index < tensor->size(); ++tensor_storage_index) {\n            // Check TCI\n            const auto effective_neighbor_means =\n                Minmod_detail::compute_effective_neighbor_means<decltype(tag)>(\n                    tensor_storage_index, element, neighbor_data);\n            const bool component_needs_limiting = Tci::tvb_minmod_indicator(\n                make_not_null(&tci_buffer), tvb_constant_,\n                (*tensor)[tensor_storage_index], mesh, element, element_size,\n                effective_neighbor_means, effective_neighbor_sizes);\n\n            if (component_needs_limiting) {\n              if (modified_neighbor_solution_buffer.empty()) {\n                // Allocate the neighbor solution buffers only if the limiter is\n                // triggered. This reduces allocation when no limiting occurs.\n                for (const auto& neighbor_and_data : neighbor_data) {\n                  const auto& neighbor = neighbor_and_data.first;\n                  modified_neighbor_solution_buffer.insert(make_pair(\n                      neighbor, DataVector(mesh.number_of_grid_points())));\n                }\n              }\n              Weno_detail::simple_weno_impl<decltype(tag)>(\n                  make_not_null(&interpolator_buffer),\n                  make_not_null(&modified_neighbor_solution_buffer), tensor,\n                  neighbor_linear_weight_, tensor_storage_index, mesh, element,\n                  neighbor_data);\n              some_component_was_limited = true;\n            }\n          }\n          return '0';\n        };\n    expand_pack(wrap_minmod_tci_and_simple_weno_impl(Tags{}, tensors)...);\n    return some_component_was_limited;  // cell_is_troubled\n  } else {\n    ERROR(\"WENO limiter not implemented for WenoType: \" << weno_type_);\n  }\n\n  return false;  // cell_is_troubled\n}\n\ntemplate <size_t LocalDim, typename LocalTagList>\nbool operator==(const Weno<LocalDim, LocalTagList>& lhs,\n                const Weno<LocalDim, LocalTagList>& rhs) noexcept {\n  return lhs.weno_type_ == rhs.weno_type_ and\n         lhs.neighbor_linear_weight_ == rhs.neighbor_linear_weight_ and\n         lhs.tvb_constant_ == rhs.tvb_constant_ and\n         lhs.disable_for_debugging_ == rhs.disable_for_debugging_;\n}\n\ntemplate <size_t VolumeDim, typename TagList>\nbool operator!=(const Weno<VolumeDim, TagList>& lhs,\n                const Weno<VolumeDim, TagList>& rhs) noexcept {\n  return not(lhs == rhs);\n}\n\n}  // namespace Limiters\n", "meta": {"hexsha": "29dda685619d139435d68579e458aa38036f9e48", "size": 18203, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Weno.hpp", "max_stars_repo_name": "trami18/spectre", "max_stars_repo_head_hexsha": "6b1f6497bf2e26d1474bfadf143b3321942c40b4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-11T04:07:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-11T05:07:54.000Z", "max_issues_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Weno.hpp", "max_issues_repo_name": "trami18/spectre", "max_issues_repo_head_hexsha": "6b1f6497bf2e26d1474bfadf143b3321942c40b4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-25T18:26:16.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T19:30:39.000Z", "max_forks_repo_path": "src/Evolution/DiscontinuousGalerkin/Limiters/Weno.hpp", "max_forks_repo_name": "isaaclegred/spectre", "max_forks_repo_head_hexsha": "5765da85dad680cad992daccd479376c67458a8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4312354312, "max_line_length": 80, "alphanum_fraction": 0.6995000824, "num_tokens": 4233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.23642175773917523}}
{"text": "//=============================================================================================================\n/**\n* @file     mne_project_to_surface.cpp\n* @author   Jana Kiesel <jana.kiesel@tu-ilmenau.de>;\n*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version  1.0\n* @date     August, 2016\n*\n* @section  LICENSE\n*\n* Copyright (C) 2016, Jana Kiesel and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, 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 INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    MNEProjectToSurface class definition.\n*\n*/\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"mne_project_to_surface.h\"\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include <mne/mne_bem_surface.h>\n#include <mne/mne_surface.h>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// QT INCLUDES\n//=============================================================================================================\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Eigen INCLUDES\n//=============================================================================================================\n\n#include <Eigen/Geometry>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace MNELIB;\nusing namespace Eigen;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE GLOBAL METHODS\n//=============================================================================================================\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nMNEProjectToSurface::MNEProjectToSurface()\n: r1(MatrixX3f::Zero(1,3))\n, r12(MatrixX3f::Zero(1,3))\n, r13(MatrixX3f::Zero(1,3))\n, nn(MatrixX3f::Zero(1,3))\n, a(VectorXf::Zero(1))\n, b(VectorXf::Zero(1))\n, c(VectorXf::Zero(1))\n, det(VectorXf::Zero(1))\n{\n\n}\n\n\n//*************************************************************************************************************\n\nMNEProjectToSurface::MNEProjectToSurface(const MNEBemSurface &p_MNEBemSurf)\n: r1(MatrixX3f::Zero(p_MNEBemSurf.ntri,3))\n, r12(MatrixX3f::Zero(p_MNEBemSurf.ntri,3))\n, r13(MatrixX3f::Zero(p_MNEBemSurf.ntri,3))\n, nn(MatrixX3f::Zero(p_MNEBemSurf.ntri,3))\n, a(VectorXf::Zero(p_MNEBemSurf.ntri))\n, b(VectorXf::Zero(p_MNEBemSurf.ntri))\n, c(VectorXf::Zero(p_MNEBemSurf.ntri))\n, det(VectorXf::Zero(p_MNEBemSurf.ntri))\n{\n    for (int i = 0; i < p_MNEBemSurf.ntri; ++i)\n    {\n        r1.row(i) = p_MNEBemSurf.rr.row(p_MNEBemSurf.tris(i,0));\n        r12.row(i) = p_MNEBemSurf.rr.row(p_MNEBemSurf.tris(i,1)) - r1.row(i);\n        r13.row(i) = p_MNEBemSurf.rr.row(p_MNEBemSurf.tris(i,2)) - r1.row(i);\n        a(i) = r12.row(i) * r12.row(i).transpose();\n        b(i) = r13.row(i) * r13.row(i).transpose();\n        c(i) = r12.row(i) * r13.row(i).transpose();\n    }\n\n    if (!(p_MNEBemSurf.tri_nn.isZero(0)))\n    {\n        nn = p_MNEBemSurf.tri_nn.cast<float>();\n    }\n    else\n    {\n        for (int i = 0; i < p_MNEBemSurf.ntri; ++i)\n        {\n            nn.row(i) = r12.row(i).transpose().cross(r13.row(i).transpose()).transpose();\n        }\n    }\n    det = (a.array()*b.array() - c.array()*c.array()).matrix();\n}\n\n\n//*************************************************************************************************************\n\nMNEProjectToSurface::MNEProjectToSurface(const MNESurface &p_MNESurf)\n: r1(MatrixX3f::Zero(p_MNESurf.ntri,3))\n, r12(MatrixX3f::Zero(p_MNESurf.ntri,3))\n, r13(MatrixX3f::Zero(p_MNESurf.ntri,3))\n, nn(MatrixX3f::Zero(p_MNESurf.ntri,3))\n, a(VectorXf::Zero(p_MNESurf.ntri))\n, b(VectorXf::Zero(p_MNESurf.ntri))\n, c(VectorXf::Zero(p_MNESurf.ntri))\n, det(VectorXf::Zero(p_MNESurf.ntri))\n{\n    for (int i = 0; i < p_MNESurf.ntri; ++i)\n    {\n        r1.row(i) = p_MNESurf.rr.row(p_MNESurf.tris(i,0));\n        r12.row(i) = p_MNESurf.rr.row(p_MNESurf.tris(i,1)) - r1.row(i);\n        r13.row(i) = p_MNESurf.rr.row(p_MNESurf.tris(i,2)) - r1.row(i);\n        nn.row(i) = r12.row(i).transpose().cross(r13.row(i).transpose()).transpose();\n        a(i) = r12.row(i) * r12.row(i).transpose();\n        b(i) = r13.row(i) * r13.row(i).transpose();\n        c(i) = r12.row(i) * r13.row(i).transpose();\n    }\n\n    det = (a.array()*b.array() - c.array()*c.array()).matrix();\n}\n\n\n//*************************************************************************************************************\n\nbool MNEProjectToSurface::mne_find_closest_on_surface(const MatrixXf &r, const int np, MatrixXf &rTri,\n                                                      VectorXi &nearest, VectorXf &dist)\n{\n    nearest.resize(np);\n    dist.resize(np);\n    if (this->r1.isZero(0))\n    {\n        qDebug() << \"No surface loaded to make the projection./n\";\n        return false;\n    }\n    int bestTri = -1;\n    float bestDist = -1;\n    Vector3f rTriK;\n    for (int k = 0; k < np; ++k)\n    {\n        /*\n         * To do: decide_search_restriction for the use in an iterative closest point to plane algorithm\n         * For now it's OK to go through all triangles.\n         */\n        if (!this->mne_project_to_surface(r.row(k).transpose(), rTriK, bestTri, bestDist))\n        {\n            qDebug() << \"The projection of point number \" << k << \" didn't work./n\";\n            return false;\n        }\n        rTri.row(k) = rTriK.transpose();\n        nearest[k] = bestTri;\n        dist[k] = bestDist;\n    }\n    return true;\n}\n\n\n//*************************************************************************************************************\n\nbool MNEProjectToSurface::mne_project_to_surface(const Vector3f &r, Vector3f &rTri, int &bestTri, float &bestDist)\n{\n    float p = 0, q = 0, p0 = 0, q0 = 0, dist0 = 0;\n    bestDist = 0.0f;\n    bestTri = -1;\n    for (int tri = 0; tri < a .size(); ++tri)\n    {\n        if (!this->nearest_triangle_point(r, tri, p0, q0, dist0))\n        {\n            qDebug() << \"The projection on triangle \" << tri << \" didn't work./n\";\n            return false;\n        }\n\n        if ((bestTri < 0) || (std::fabs(dist0) < std::fabs(bestDist)))\n        {\n            bestDist = dist0;\n            p = p0;\n            q = q0;\n            bestTri = tri;\n        }\n    }\n\n    if (bestTri >= 0)\n    {\n        if (!this->project_to_triangle(rTri, p, q, bestTri))\n        {\n            qDebug() << \"The coordinate transform to cartesian system didn't work./n\";\n            return false;\n        }\n        return true;\n    }\n\n    qDebug() << \"No best Triangle found./n\";\n    return false;\n}\n\n\n//*************************************************************************************************************\n\nbool MNEProjectToSurface::nearest_triangle_point(const Vector3f &r, const int tri, float &p, float &q, float &dist)\n{\n    //Calculate some helpers\n    Vector3f rr = r - this->r1.row(tri).transpose(); //Vector from triangle corner #1 to r\n    float v1 = this->r12.row(tri)*rr;\n    float v2 = this->r13.row(tri)*rr;\n\n    //Calculate the orthogonal projection of the point r on the plane\n    dist = this->nn.row(tri)*rr;\n    p = (this->b(tri)*v1 - this->c(tri)*v2)/det(tri);\n    q = (this->a(tri)*v2 - this->c(tri)*v1)/det(tri);\n\n    //If the point projects into the triangle we are done\n    if (p >= 0.0 && p <= 1.0 && q >= 0.0 && q <= 1.0 && (p+q) <= 1.0)\n         {\n        return true;\n    }\n\n    /*\n     * Tough: must investigate the sides\n     * We might do something intelligent here. However, for now it is ok\n     * to do it in the hard way\n     */\n    float p0, q0, t0, dist0, best, bestp, bestq;\n\n    /*\n     * Side 1 -> 2\n     */\n    p0 = p + (q * this->c(tri)) / this->a(tri);\n    // Place the point in the corner if it is not on the side\n    if (p0 < 0.0)\n    {\n        p0 = 0.0;\n    }\n    else if (p0 > 1.0)\n    {\n        p0 = 1.0;\n    }\n    q0 = 0;\n    // Distance\n    dist0 = sqrt((p-p0)*(p-p0)*this->a(tri) +\n                 (q-q0)*(q-q0)*this->b(tri) +\n                 2*(p-p0)*(q-q0)*this->c(tri) +\n                 dist*dist);\n\n    best = dist0;\n    bestp = p0;\n    bestq = q0;\n    /*\n    * Side 2 -> 3\n    */\n    t0 = ((a(tri)-c(tri))*(-p) + (b(tri)-c(tri))*q)/(a(tri)+b(tri)-2*c(tri));\n    // Place the point in the corner if it is not on the side\n    if (t0 < 0.0)\n    {\n        t0 = 0.0;\n    }\n    else if (t0 > 1.0)\n    {\n        t0 = 1.0;\n    }\n    p0 = 1.0 - t0;\n    q0 = t0;\n    // Distance\n    dist0 = sqrt((p-p0)*(p-p0)*this->a(tri) +\n                 (q-q0)*(q-q0)*this->b(tri) +\n                 2*(p-p0)*(q-q0)*this->c(tri) +\n                 dist*dist);\n    if (dist0 < best)\n    {\n        best = dist0;\n        bestp = p0;\n        bestq = q0;\n    }\n    /*\n    * Side 1 -> 3\n    */\n    p0 = 0.0;\n    q0 = q + (p * c(tri))/b(tri);\n    // Place the point in the corner if it is not on the side\n    if (q0 < 0.0)\n    {\n        q0 = 0.0;\n\n    }\n    else if (q0 > 1.0)\n    {\n        q0 = 1.0;\n    }\n    // Distance\n    dist0 = sqrt((p-p0)*(p-p0)*this->a(tri) +\n                 (q-q0)*(q-q0)*this->b(tri) +\n                 2*(p-p0)*(q-q0)*this->c(tri) +\n                 dist*dist);\n    if (dist0 < best)\n    {\n        best = dist0;\n        bestp = p0;\n        bestq = q0;\n    }\n    dist = best;\n    p = bestp;\n    q = bestq;\n    return true;\n}\n\n\n//*************************************************************************************************************\n\nbool MNEProjectToSurface::project_to_triangle(Vector3f &rTri, const float p, const float q, const int tri)\n{\n    rTri = this->r1.row(tri) + p*this->r12.row(tri) + q*this->r13.row(tri);\n    return true;\n}\n", "meta": {"hexsha": "84713ba83b656e77f04261c025ef40951c1d3770", "size": 12451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/mne/mne_project_to_surface.cpp", "max_stars_repo_name": "ChunmingGu/mne-cpp-master", "max_stars_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T07:38:25.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-14T07:38:25.000Z", "max_issues_repo_path": "libraries/mne/mne_project_to_surface.cpp", "max_issues_repo_name": "ChunmingGu/mne-cpp-master", "max_issues_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-23T12:40:56.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-23T12:40:56.000Z", "max_forks_repo_path": "libraries/mne/mne_project_to_surface.cpp", "max_forks_repo_name": "ChunmingGu/mne-cpp-master", "max_forks_repo_head_hexsha": "36f21b3ab0c65a133027da83fa8e2a652acd1485", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0732394366, "max_line_length": 116, "alphanum_fraction": 0.4358686049, "num_tokens": 3081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23638273791976905}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#ifndef fiber_numerical_quadrature_hpp\n#define fiber_numerical_quadrature_hpp\n\n#include \"../common/common.hpp\"\n\n/** \\file\n *\n *  Low-level functions filling arrays of quadrature points and weights. */\n\n#include \"element_pair_topology.hpp\"\n\n#include \"../common/armadillo_fwd.hpp\"\n#include <boost/tuple/tuple_comparison.hpp>\n#include <ostream>\n\nnamespace Fiber\n{\n\nstruct SingleQuadratureDescriptor\n{\n    int vertexCount;\n    int order;\n\n    bool operator<(const SingleQuadratureDescriptor& other) const {\n        return std::make_pair(vertexCount, order) <\n                std::make_pair(other.vertexCount, other.order);\n    }\n\n    bool operator==(const SingleQuadratureDescriptor& other) const {\n        return vertexCount == other.vertexCount &&\n                order == other.order;\n    }\n\n    bool operator!=(const SingleQuadratureDescriptor& other) const {\n        return !operator==(other);\n    }\n\n    friend std::ostream&\n    operator<< (std::ostream& dest, const SingleQuadratureDescriptor& obj)\n    {\n        dest << obj.vertexCount << \" \" << obj.order;\n        return dest;\n    }\n};\n\ninline size_t tbb_hasher(const SingleQuadratureDescriptor& d)\n{\n    return (d.vertexCount - 3) + 2 * d.order;\n}\n\nstruct DoubleQuadratureDescriptor\n{\n    ElementPairTopology topology;\n    int testOrder;\n    int trialOrder;\n\n    bool operator<(const DoubleQuadratureDescriptor& other) const {\n        using boost::tuples::make_tuple;\n        return make_tuple(topology, testOrder, trialOrder) <\n                make_tuple(other.topology, other.testOrder, other.trialOrder);\n    }\n\n    bool operator==(const DoubleQuadratureDescriptor& other) const {\n        return topology == other.topology &&\n                testOrder == other.testOrder &&\n                trialOrder == other.trialOrder;\n    }\n\n    bool operator!=(const DoubleQuadratureDescriptor& other) const {\n        return !operator==(other);\n    }\n\n    friend std::ostream&\n    operator<< (std::ostream& dest, const DoubleQuadratureDescriptor& obj)\n    {\n        dest << obj.topology << \" \" << obj.testOrder << \" \" << obj.trialOrder;\n        return dest;\n    }\n};\n\ninline size_t tbb_hasher(const DoubleQuadratureDescriptor& d)\n{\n    const ElementPairTopology& t = d.topology;\n    return (t.testVertexCount - 3) + 2 *\n            ((t.trialVertexCount - 3) + 2 *\n             (t.testSharedVertex0 + 4 *\n              (t.trialSharedVertex0 + 4 *\n               (t.testSharedVertex1 + 4 *\n                (t.trialSharedVertex1 + 4 *\n                 (d.testOrder + 256 *\n                  d.trialOrder))))));\n}\n\n/** \\brief Retrieve points and weights for a quadrature over a single element.\n *\n *  \\param[in] elementCornerCount\n *    Number of corners of the element to be integrated on.\n *  \\param[in] accuracyOrder\n *    Accuracy order of the quadrature, i.e. its degree of exactness.\n *  \\param[out] points\n *    Quadrature points.\n *  \\param[out] weights\n *    Quadrature weights. */\ntemplate <typename ValueType>\nvoid fillSingleQuadraturePointsAndWeights(int elementCornerCount,\n                                          int accuracyOrder,\n                                          arma::Mat<ValueType>& points,\n                                          std::vector<ValueType>& weights);\n\ntemplate <typename ValueType>\nvoid fillDoubleSingularQuadraturePointsAndWeights(\n        const DoubleQuadratureDescriptor& desc,\n        arma::Mat<ValueType>& testPoints,\n        arma::Mat<ValueType>& trialPoints,\n        std::vector<ValueType>& weights);\n\n} // namespace Fiber\n\n#endif\n", "meta": {"hexsha": "6eee5fa07300d7f30d644088a077f76b4fd985ad", "size": 4650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/fiber/numerical_quadrature.hpp", "max_stars_repo_name": "nicolas-chaulet/bempp", "max_stars_repo_head_hexsha": "0f5cc72e0e542437e787db5704978456b0ad9e35", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T13:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T13:35:20.000Z", "max_issues_repo_path": "lib/fiber/numerical_quadrature.hpp", "max_issues_repo_name": "UCL/bempp", "max_issues_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/fiber/numerical_quadrature.hpp", "max_forks_repo_name": "UCL/bempp", "max_forks_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T09:46:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-17T09:46:44.000Z", "avg_line_length": 33.2142857143, "max_line_length": 80, "alphanum_fraction": 0.668172043, "num_tokens": 1038, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2363827316424768}}
{"text": "\n#pragma once\n\n#include <data_model.hpp>\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <stdexcept>\n#include <map>\n#include <sstream>\n#include <boost/tuple/tuple.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/copy.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/graph/graphviz.hpp>\n\nnamespace verilog\n{\n  namespace bdd {\n\n    enum class NegP {\n      Positive, Negative\n    };\n\n    enum class Type {\n      Zero, One, Input\n    };\n\n    struct Node {\n      std::string input_name;\n      Type t;\n    };\n\n    typedef boost::adjacency_list<\n      boost::setS,\n      boost::vecS,\n      boost::bidirectionalS,\n      Node, NegP> GD;\n\n    typedef unsigned int hashcode;\n\n    struct BDD {\n      GD graph;\n\n      GD::vertex_descriptor \n        /**\n         * The nodes representing the sinks of the BDD\n         */\n        zero,\n        one,\n        /**\n         * The node representing the source of the bdd\n         */\n        source;\n\n      std::map<hashcode, std::vector<int> > bdd_heap;\n\n      BDD() {\n        zero = boost::add_vertex(graph);\n        one  = boost::add_vertex(graph);\n        graph[zero].t = Type::Zero;\n        graph[one].t  = Type::One;\n      }\n\n      BDD(const std::string name) {\n        zero = boost::add_vertex(graph);\n        one  = boost::add_vertex(graph);\n        source = add_vertex(name);\n\n        add_edge(source, one, NegP::Positive);\n        add_edge(source, zero, NegP::Negative);\n\n        graph[zero].t = Type::Zero;\n        graph[one].t  = Type::One;\n      }\n\n      /**\n       * Creates a copy of a,\n       * merges all nodes of b into the copy.\n       * calls the conjunction_internal function for the copy.\n       */\n\n      void copy_graph(const BDD & o, \n          std::map<GD::vertex_descriptor,\n                   GD::vertex_descriptor> & node_map\n          ) {\n\n        GD::vertex_iterator v, vend;\n        for(boost::tie(v, vend) = boost::vertices(o.graph);\n            v != vend; ++v) {\n          if (o.graph[*v].t == Type::Input) {\n            GD::vertex_descriptor n = add_vertex(o.graph[*v].input_name);\n            node_map[*v] = n;\n          }\n        }\n        \n        GD::edge_iterator e, eend;\n        for(boost::tie(e, eend) = boost::edges(o.graph);\n            e != eend; ++e) {\n          GD::vertex_descriptor s = boost::source(*e, o.graph);\n\n          GD::vertex_descriptor x;\n          GD::vertex_descriptor d = boost::target(*e, o.graph);\n          switch(o.graph[d].t) {\n            case(Type::Zero): \n              x = zero;\n              break;\n            case(Type::One):  \n              x = one;\n              break;\n            default: \n              x = node_map[d];\n          }\n          boost::add_edge(node_map[s], x, o.graph[*e], graph);\n        }\n      }\n\n      BDD operator&(const BDD & b) {\n\n        std::map<GD::vertex_descriptor,\n          GD::vertex_descriptor> node_map_a;\n\n        std::map<GD::vertex_descriptor,\n          GD::vertex_descriptor> node_map_b;\n\n        BDD c;\n        c.copy_graph(*this, node_map_a);\n        c.copy_graph(b, node_map_b);\n\n        c.source = c.conjunction_internal(\n            node_map_a[this->source],\n            node_map_b[b.source]\n            );\n        return c;\n      }\n\n      private:\n      /**\n       * Internal function that checks for all the cases\n       * Accepts the nodes that must be conjoined\n       * and returns the new source.\n       */\n      GD::vertex_descriptor\n        conjunction_internal(\n          GD::vertex_descriptor & a, \n          GD::vertex_descriptor & b) {\n        std::cout << \"conjunction_internal \" << a << \" \" << b << \"\\n\";\n        add_edge(a, b, NegP::Positive);\n        return a;\n      }\n\n\n      GD::vertex_descriptor add_vertex(const std::string name) {\n        GD::vertex_descriptor v = boost::add_vertex(graph);\n        graph[v].input_name = name;\n        graph[v].t          = Type::Input;\n        return v;\n      }\n\n      void add_edge(\n          GD::vertex_descriptor & a, \n          GD::vertex_descriptor & b, \n          NegP p) {\n        boost::add_edge(a, b, p, graph);\n      }\n\n      /**\n       * USE WITH CAUTION, as it changes the current BDD\n       * - changes zero and one\n       */\n      public:\n      void reverse() {\n        GD::vertex_descriptor aux = one;\n        one = zero;\n        zero = aux;\n\n        graph[zero].t = Type::Zero;\n        graph[one].t  = Type::One;\n      }\n\n      /**\n       * USE WITH CAUTION, as it changes the current BDD\n       * merges the input edges of the node b into node a.\n       */\n      void merge_input_edges(\n          const GD::vertex_descriptor a, \n          const GD::vertex_descriptor b) {\n        GD::in_edge_iterator e, end;\n        for (boost::tie(e, end) = in_edges(b, graph); e != end; ++e) {\n            GD::vertex_descriptor s = boost::source(*e, graph);\n            boost::add_edge(s, a, graph[*e], graph);\n        }\n      }\n\n      std::map<int, std::vector<int> > find_layers() {\n        // TODO\n      }\n\n      // Criar um hash o mais unico possivel para um bdd\n      hashcode hash(int v) {\n        // TODO\n      }\n\n      // Compares BDDs\n      friend bool operator<(const BDD & bdd1, const BDD & bdd2) {\n        // TODO\n      }\n\n      /**\n       * USE WITH CAUTION, as it changes the current BDD\n       * - minimizes the BDD\n       */\n      void minimize() {\n        // TODO\n      }\n\n      friend bool operator==(const BDD & bdd1, const BDD & bdd2) {\n        return\n          (bdd1.source == bdd2.source) &&\n          (bdd1.one == bdd2.one) &&\n          (bdd1.zero == bdd2.zero);\n        // TODO &&\n        //  (bdd1.graph == bdd2.graph);\n      }\n      friend bool operator!=(const BDD & bdd1, const BDD & bdd2) {\n        return\n          (bdd1.source != bdd2.source) &&\n          (bdd1.one != bdd2.one) &&\n          (bdd1.zero != bdd2.zero);\n        // TODO&&\n        //  (bdd1.graph != bdd2.graph);\n      }\n\n      public:\n      int size() {\n        int i = 0;\n        GD::vertex_iterator n, e;\n        for(boost::tie(n, e) = boost::vertices(graph);\n            n != e; ++n) ++i;\n        return i;\n      }\n\n      friend std::ostream& operator<<(std::ostream &o, const BDD & b) {\n\n        int i = 0;\n        std::map<GD::vertex_descriptor, int> node_map;\n        //std::map<GD::vertex_descriptor, GD::vertex_descriptor> node_map;\n        GD::vertex_iterator v, vend;\n\n        for(boost::tie(v, vend) = boost::vertices(b.graph);\n            v != vend; ++v) {\n          node_map[*v] = ++i;\n          //node_map[*v] = *v;\n        }\n\n\n        o << \"digraph G {\\n\" ;\n        for(boost::tie(v, vend) = boost::vertices(b.graph);\n            v != vend; ++v) {\n          switch(b.graph[*v].t) {\n            case(Type::Input) : {\n                o << node_map[*v] << \" [label=\\\"\"\n                  << b.graph[*v].input_name\n                  << \"\\\", \";\n                if (*v == b.source)\n                  o << \"shape=doublecircle];\\n\";\n                else\n                  o << \"shape=circle];\\n\";\n              break;\n            }\n            case(Type::One) : {\n                o << node_map[*v] << \" [label=\\\"1\\\", shape=box]; \\n\";\n              break;\n            }\n            case(Type::Zero) : {\n                o << node_map[*v] << \" [label=\\\"0\\\", shape=box]; \\n\";\n              break;\n            }\n          }\n        }\n\n        GD::edge_iterator e, eend;\n        for(boost::tie(e, eend) = boost::edges(b.graph);\n            e != eend; ++e) {\n          GD::vertex_descriptor s = boost::source(*e, b.graph);\n          GD::vertex_descriptor d = boost::target(*e, b.graph);\n\n          o << node_map[s] << \"->\" << node_map[d];\n          switch(b.graph[*e]) {\n            case(NegP::Positive): {\n              o << \" [style=solid];\\n\";\n              break;\n            }\n            case(NegP::Negative): {\n              o << \" [style=dashed];\\n\";\n              break;\n            }\n          }\n        }\n\n\n        o << \"}\\n\" ;\n        return o;\n      }\n    };\n  }\n}\n", "meta": {"hexsha": "b8a7d50c7faf5670d32f6b9b6cc71643aa3c0f14", "size": 7977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/bdd_model.hpp", "max_stars_repo_name": "RafaelONascimento/iccad2016uffs", "max_stars_repo_head_hexsha": "ece416e9139cdfa20ccd27536965e4e03ca474b2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-03T14:11:14.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-03T14:11:14.000Z", "max_issues_repo_path": "include/bdd_model.hpp", "max_issues_repo_name": "RafaelONascimento/iccad2016uffs", "max_issues_repo_head_hexsha": "ece416e9139cdfa20ccd27536965e4e03ca474b2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/bdd_model.hpp", "max_forks_repo_name": "RafaelONascimento/iccad2016uffs", "max_forks_repo_head_hexsha": "ece416e9139cdfa20ccd27536965e4e03ca474b2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7322580645, "max_line_length": 74, "alphanum_fraction": 0.4825122226, "num_tokens": 2030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2363827316424768}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/format.hpp>\n#include \"ncl/nxsallocatematrix.h\"\n#include \"q_matrix.hpp\"\n#include \"xlikelihood.hpp\"\nusing namespace phycas;\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\n*/\nQMatrix::QMatrix()\n  : dimension(0), flat_length(0)\n  , qmat(0), qmat_begin(0), qmat_end(0)\n  , w(0), w_begin(0), w_end(0)\n  , z(0), z_begin(0), z_end(0)\n  , fv(0)\n  , q_dirty(true)\n\t{\n\t// Set up Q matrix representing the JC69 model by default\n\trr.assign(6, 1.0);\n\tpi.assign(4, 0.25);\n\tsqrtPi.assign(4, 0.5);\n\trecalcQMatrix();\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\n*/\nQMatrix::~QMatrix()\n\t{\n\tclear();\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns object to its just-constructed state, with the exception that the vectors `rr', `pi' and `sqrtPi' are not\n|\tcleared.\n*/\nvoid QMatrix::clearAllExceptFreqsAndRates()\n\t{\n\tdimension\t= 0;\n\tflat_length\t= 0;\n\tqmat_begin\t= 0;\n\tqmat_end\t= 0;\n\tw_begin\t\t= 0;\n\tw_end\t\t= 0;\n\tz_begin\t\t= 0;\n\tz_end\t\t= 0;\n\n\tdim_vect.clear();\n\n\tif (qmat)\n\t\t{\n\t\tDeleteTwoDArray<double>(qmat);\n\t\tqmat = 0;\n\t\t}\n\n\tif (w)\n\t\t{\n\t\tdelete [] w;\n\t\tw = 0;\n\t\t}\n\n\tif (fv)\n\t\t{\n\t\tdelete [] fv;\n\t\tfv = 0;\n\t\t}\n\n\tif (z)\n\t\t{\n\t\tDeleteTwoDArray<double>(z);\n\t\tz = 0;\n\t\t}\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns object to its just-constructed state by calling clearAllExceptFreqsAndRates and then also clearing the\n|\t`rr', `pi' and `sqrtPi' vectors.\n*/\nvoid QMatrix::clear()\n\t{\n\tclearAllExceptFreqsAndRates();\n\tpi.clear();\n\tsqrtPi.clear();\n\trr.clear();\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tAccessor function that returns the current value of the data member `dimension', which is the number of rows (and\n|\tcolumns) in the Q matrix.\n*/\nunsigned QMatrix::getDimension()\n\t{\n\treturn dimension;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCopies elements from the supplied vector `rates' to the data member `rr' and sets `q_dirty' to true.\n*/\nvoid QMatrix::setRelativeRates(const std::vector<double> & rates)\n\t{\n\trr.resize(rates.size());\n\tstd::copy(rates.begin(), rates.end(), rr.begin());\n\tq_dirty = true;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCopies elements from the supplied vector `rates' to the data member `rr' and sets `q_dirty' to true.\n*/\nvoid QMatrix::setStateFreqs(const std::vector<double> & freqs)\n\t{\n\tpi.resize(freqs.size());\n\tstd::copy(freqs.begin(), freqs.end(), pi.begin());\n\n\tsqrtPi.resize(freqs.size());\n\tstd::transform(pi.begin(), pi.end(), sqrtPi.begin(), boost::lambda::bind(static_cast<double(*)(double)>(&std::sqrt), boost::lambda::_1));\n\tq_dirty = true;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReallocates all arrays and vectors (except `rr', `pi' and `sqrtPi') according to the value of `new_dim' and sets\n|\t`dimension' equal to `new_dim' before returning. Assumes `new_dim' is greater than zero. Note that `qmat', `w', `z'\n|\tand `fv' are allocated but not filled with any values when this function returns.\n*/\nvoid QMatrix::redimension(unsigned new_dim)\n\t{\n\tPHYCAS_ASSERT(new_dim > 0);\n\tclearAllExceptFreqsAndRates();\n\n\tdimension = new_dim;\n\tflat_length = new_dim*new_dim;\n\n\texpwv.resize(new_dim);\n\n\t// Set the shape of a NumArray object that represents Q, P (transition probs), E (eigenvectors) or V (eigenvalues)\n\tdim_vect.push_back((int)dimension);\n\tdim_vect.push_back((int)dimension);\n\n\t// Create and fill qmat with default (Mk model) values\n\tqmat = NewTwoDArray<double>(dimension, dimension);\n\tPHYCAS_ASSERT(qmat);\n\n\tqmat_begin\t\t= &qmat[0][0];\n\tqmat_end\t\t= qmat_begin + flat_length;\n\n\t// Create w (array of eigenvalues)\n\tw = new double[dimension];\n\tw_begin = &w[0];\n\tw_end = w_begin + dimension;\n\n\t// Create z (two-dimensional array of eigenvectors)\n\tz = NewTwoDArray<double>(dimension, dimension);\n\tz_begin\t\t= &z[0][0];\n\tz_end\t\t= z_begin + flat_length;\n\n\t// Create fv (workspace used by EigenRealSymmetric)\n\tfv = new double[dimension];\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tIf `q_dirty' is true, calls recalcQMatrixImpl to recompute the `qmat', `z' and `w' data members. If `q_dirty' is\n|\tfalse, however, this function returns immediately and thus (because it is declared inline) is computationally\n|\tinexpensive.\n*/\nvoid QMatrix::recalcQMatrix()\n\t{\n\tif (!q_dirty)\n\t\treturn;\n\trecalcQMatrixImpl();\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the eigenvalues in the data member `w' as a vector. Calls recalcQMatrix first to ensure that `w' is up to\n|\tdate.\n*/\nstd::vector<double> QMatrix::getEigenValues()\n\t{\n\trecalcQMatrix();\n\tstd::vector<double> v(dimension, 0.0);\n\tstd::copy(w_begin, w_end, v.begin());\n\treturn v;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\n*/\nstd::string QMatrix::showQMatrix()\n\t{\n\trecalcQMatrix();\n\treturn showMatrixImpl(qmat_begin);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tStores a flattened version of the supplied 2-dimensional array `twoDarr', storing the result in the supplied std::vector<double>\n|\treference variable `p'. The supplied `twoDarr' should be laid out so that rows occupy contiguous memory.\n*/\nvoid QMatrix::flattenTwoDMatrix(std::vector<double> & p, double * * twoDarr, unsigned dim) const\n\t{\n\tunsigned flat_length = dim*dim;\n\tp.resize(flat_length);\n\tdouble * twoD_begin = &twoDarr[0][0];\n\tdouble * twoD_end   = twoD_begin + flat_length;\n\tstd::copy(twoD_begin, twoD_end, p.begin());\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tUses `pi' and `rr' vectors to create the two-dimensional array `qmat'. The data member `qmat' is reallocated if\n|\tchanges in `pi' and `rr' imply a new dimension (or if `qmat' is NULL). Recomputes eigenvalues and eigenvectors\n|\tcorresponding to the new Q matrix. Assumes `q_dirty' is true, and sets `q_dirty' to false when finished. Throws an\n|\texception if lengths of the `pi' and `rr' vectors are incompatible.\n*/\nvoid QMatrix::recalcQMatrixImpl()\n\t{\n\tPHYCAS_ASSERT(q_dirty);\n\n\t// pi, sqrtPi and rr should all be non-empty\n\tPHYCAS_ASSERT(pi.size() > 0);\n\tPHYCAS_ASSERT(sqrtPi.size() == pi.size());\n\tPHYCAS_ASSERT(rr.size() > 0);\n\n\t// First check to make sure lengths of `rr' and `pi' are compatible with each other\n\tunsigned dim_pi = (unsigned)pi.size();\n\tunsigned dim_rr = (unsigned)((1.0 + std::sqrt(1.0 + 8.0*rr.size()))/2.0); // rr.size() = (n^2 - n)/2, so use quadratic formula to get n\n\tif (dim_pi != dim_rr)\n\t\t{\n\t\tthrow XLikelihood(boost::str(boost::format(\"Number of relative rates (%d) and number of state frequencies (%d) specified are incompatible\") % dim_rr % dim_pi));\n\t\t}\n\n\t// If qmat is NULL or dimension differs from dim_pi and dim_rr, reallocate qmat, z, w and dv\n\tif (!qmat || (dimension != dim_pi))\n\t\tredimension(dim_pi);\n\n\t// This vector will hold the row sums\n\tstd::vector<double> row_sum(dimension, 0.0);\n\n\tunsigned i, j, k = 0;\n\tdouble sum_for_scaling = 0.0;\n\tfor (i = 0; i < dimension; ++i)\n\t\t{\n\t\tdouble pi_i = pi[i];\n\t\tdouble sqrtPi_i = sqrtPi[i];\n\t\tfor (j = i + 1; j < dimension; ++j, ++k)\n\t\t\t{\n\t\t\tdouble rr_k = rr[k];\n\t\t\tdouble pi_j = pi[j];\n\t\t\tdouble sqrtPi_j = sqrtPi[j];\n\n\t\t\t// set value in upper triangle\n\t\t\tqmat[i][j] = rr_k*sqrtPi_i*sqrtPi_j;\n\n\t\t\t// set value in lower triangle\n\t\t\tqmat[j][i] = qmat[i][j];\n\n\t\t\t// add to relevant row sums\n\t\t\trow_sum[i] += rr_k*pi_j;\n\t\t\trow_sum[j] += rr_k*pi_i;\n\n\t\t\t// add to total expected number of substitutions\n\t\t\tsum_for_scaling += 2.0*pi_i*rr_k*pi_j;\n\t\t\t}\n\t\tqmat[i][i] = -row_sum[i];\n\t\t}\n\n\tPHYCAS_ASSERT(sum_for_scaling > 0.0);\n\tedgelen_scaler = 1.0/sum_for_scaling;\n\n\t// Calculate eigenvalues (w) and eigenvectors (z)\n\tint err_code = EigenRealSymmetric(dimension, qmat, w, z, fv);\n\n\tif (err_code != 0)\n\t\t{\n\t\tclearAllExceptFreqsAndRates();\n\t\tthrow XLikelihood(\"Error in the calculation of eigenvectors and eigenvalues of the Q matrix\");\n\t\t}\n\n\tq_dirty = false;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|   Recomputes a transition probability matrix for an edge length `edgelen', storing it in `pmat'. If either state\n|   frequencies or relative rates have changed, the Q matrix is reconstructed and eigenvalues and eigenvectors\n|   recomputed before the transition matrix is recomputed.\n*/\nvoid QMatrix::recalcPMat(\n  double * * pmat,\t\t/**< is the transition matrix to recalculate */\n  double edgelen) \t\t/**< is the edge length */\n\t{\n\trecalcQMatrix();\n    double t = edgelen;\n\n    // The next two lines fix the \"Rota\" bug; see BUGS file for details\n    if (t < 1.e-8)\n        t = 1.e-8; //TreeNode::edgeLenEpsilon;\n\n\t// Adjust the supplied edgelen to account for the fact that the expected number of substitutions\n\t// implied by the Q matrix is not unity\n\tdouble v = t*edgelen_scaler;\n\n    // Precalculate exp to avoid doing the same calculation dimension*dimension times\n\tfor (unsigned k = 0; k < dimension; ++k)\n\t\t{\n\t\texpwv[k] = std::exp(w[k]*v);\n        }\n\n\t// Exponentiate eigenvalues and put everything back together again\n\t// Real symmetric matrices can be diagonalized using Z*exp(D)*Z^T, where Z is the\n\t// orthogonal matrix of eigenvectors and D is the diagonal matrix of eigenvalues,\n\t// each multiplied by time (scaled to equal expected number of substitutions)\n\tfor (unsigned i = 0; i < dimension; ++i)\n\t\t{\n\t\tdouble sqrtPi_i = sqrtPi[i];\n\t\tfor (unsigned j = 0; j < dimension; ++j)\n\t\t\t{\n\t\t\tdouble factor = sqrtPi[j]/sqrtPi_i;\n\t\t\tdouble Pij = 0.0;\n\t\t\tfor (unsigned k = 0; k < dimension; ++k)\n\t\t\t\t{\n\t\t\t\tdouble tmp = z[i][k]*z[j][k]*expwv[k];\n\t\t\t\tPij +=  tmp;\n\t\t\t\t}\n\t\t\tpmat[i][j] = Pij*factor;\n\t\t\t}\n\t\t}\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\n*/\n// void QMatrix::recalcPMatrix(\n//   std::vector<double> & P,\t/**< */\n//   double edgelen)\t\t\t/**< */\n// \t{\n// \trecalcQMatrix();\n//\n//     double t = edgelen;\n//\n//     // The next two lines fix the \"Rota\" bug; see BUGS file for details\n//     if (t < 1.e-8)\n//         t = 1.e-8; //TreeNode::edgeLenEpsilon;\n//\n//     // Adjust the supplied edgelen to account for the fact that the expected number of substitutions\n// \t// implied by the Q matrix is not unity\n// \tdouble v = t*edgelen_scaler;\n//\n// \tP.clear();\n// \tP.reserve(flat_length);\n//\n// \t// Exponentiate eigenvalues and put everything back together again\n// \tfor (unsigned i = 0; i < dimension; ++i)\n// \t\t{\n// \t\tdouble sqrtPi_i = sqrtPi[i];\n// \t\tfor (unsigned j = 0; j < dimension; ++j)\n// \t\t\t{\n// \t\t\tdouble factor = sqrtPi[j]/sqrtPi_i;\n// \t\t\tdouble Pij = 0.0;\n// \t\t\tfor (unsigned k = 0; k < dimension; ++k)\n// \t\t\t\t{\n// \t\t\t\tdouble tmp = z[i][k]*z[j][k]*std::exp(w[k]*v);\n// \t\t\t\tPij +=  tmp;\n// \t\t\t\t}\n// \t\t\tP.push_back(Pij*factor);\n// \t\t\t}\n// \t\t}\n// \t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\n*/\nstd::string QMatrix::showMatrixImpl(const double * q) const\n\t{\n\tunsigned i, j;\n\n\t// Output one column for row labels and a label for every column of qmat\n\tstd::string s = str(boost::format(\"%12s \") % \" \");\n\tfor (i = 0; i < dimension; ++i)\n\t\t{\n\t\ts += str(boost::format(\"%12d \") % i);\n\t\t}\n\ts += \"\\n\";\n\n\t// Output rows of q\n\tdouble * pq = (double *)q;\t//PELIGROSO\n\tfor (i = 0; i < dimension; ++i)\n\t\t{\n\t\ts += str(boost::format(\"%12d \") % i);\n\t\tfor (j = 0; j < dimension; ++j)\n\t\t\t{\n\t\t\ts += str(boost::format(\"%12.5f \") % *pq++);\n\t\t\t}\n\t\ts += \"\\n\";\n\t\t}\n\n\treturn s;\n\t}\n\n#if defined(PYTHON_ONLY)\n#if defined(USING_NUMARRAY)\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the entries in the data member `qmat' as a NumArray. Calls recalcQMatrix first to ensure that `qmat' is up\n|\tto date.\n*/\nboost::python::numeric::array QMatrix::getQMatrix()\n\t{\n\trecalcQMatrix();\n\treturn num_util::makeNum(qmat_begin, dim_vect);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the eigenvectors in the data member `z' as a NumArray. Calls recalcQMatrix first to ensure that `z' is up\n|\tto date.\n*/\nboost::python::numeric::array QMatrix::getEigenVectors()\n\t{\n\trecalcQMatrix();\n\treturn num_util::makeNum(z_begin, dim_vect);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the transition probability matrix as a vector of double values (where the 2-dimensional matrix is converted\n|   to a 1-dimensional vector by storing rows one after the other. Intended for debugging (not fast).\n*/\nboost::python::numeric::array QMatrix::getPMatrix(double edgelen)\n\t{\n\tdouble * * pMat = NewTwoDArray<double>(dimension, dimension);\n\trecalcPMat(pMat, edgelen);\n\treturn num_util::makeNum(pMat, dim_vect);\n\t}\n#else\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the entries in the data member `qmat' as a NumArray. Calls recalcQMatrix first to ensure that `qmat' is up\n|\tto date.\n*/\nstd::vector<double> QMatrix::getQMatrix()\n\t{\n\trecalcQMatrix();\n\tstd::vector<double> p;\n\tflattenTwoDMatrix(p, qmat, dimension);\n\treturn p;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the eigenvectors in the data member `z' as a NumArray. Calls recalcQMatrix first to ensure that `z' is up\n|\tto date.\n*/\nstd::vector<double> QMatrix::getEigenVectors()\n\t{\n\trecalcQMatrix();\n\tstd::vector<double> p;\n\tflattenTwoDMatrix(p, z, dimension);\n\treturn p;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReturns the transition probability matrix as a vector of double values (where the 2-dimensional matrix is converted\n|   to a 1-dimensional vector by storing rows one after the other. Intended for debugging (not fast).\n*/\nstd::vector<double> QMatrix::getPMatrix(double edgelen)\n\t{\n\tdouble * * pMat = NewTwoDArray<double>(dimension, dimension);\n\trecalcPMat(pMat, edgelen);\n\tstd::vector<double> p;\n\tflattenTwoDMatrix(p, pMat, dimension);\n\tDeleteTwoDArray<double>(pMat);\n\treturn p;\n\t}\n#endif\n#endif\n\n", "meta": {"hexsha": "2af6b368caa990be4280d81a8e4ccd4b5c81b7c6", "size": 16483, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/q_matrix.cpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/q_matrix.cpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/q_matrix.cpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 33.7075664622, "max_line_length": 162, "alphanum_fraction": 0.5447430686, "num_tokens": 4092, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2363385312979336}}
{"text": "/*\n * Copyright 2020 IFPEN-CEA\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/*!\n * \\file NormalizeOpt.cc\n * \\brief NormalizeOpt.cc\n */\n\n#include \"NormalizeOpt.h\"\n\n#include <alien/core/impl/MultiVectorImpl.h>\n#include <alien/kernels/simple_csr/SimpleCSRMatrix.h>\n#include <alien/kernels/simple_csr/SimpleCSRVector.h>\n\n#ifdef ALIEN_USE_EIGEN2\n#include <Eigen/Core>\n#include <Eigen/LU>\n#include <iostream>\n\n#endif\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nnamespace Alien\n{\n\nusing namespace Arccore;\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nNormalizeOpt::NormalizeOpt()\n: m_algo(StdLU)\n, m_sum_first_eq(false)\n{}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid NormalizeOpt::setAlgo(eAlgoType algo)\n{\n  m_algo = algo;\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nvoid NormalizeOpt::setOpt(eOptType opt, bool flag)\n{\n  switch (opt) {\n  case SumFirstEq:\n    m_sum_first_eq = flag;\n    break;\n  default:\n    FatalErrorException(A_FUNCINFO, String::format(\"Unhandle option type: \", opt));\n    break;\n  }\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nNormalizeOpt::eErrorType\nNormalizeOpt::normalize(IMatrix& m, IVector& x) const\n{\n  MatrixImpl& A = m.impl()->get<Alien::BackEnd::tag::simplecsr>(true);\n  VectorImpl& b = x.impl()->get<Alien::BackEnd::tag::simplecsr>(true);\n  return _normalize(A, b);\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nNormalizeOpt::eErrorType\nNormalizeOpt::normalize(\nCompositeMatrix& m, CompositeVector& x, ConstArrayView<Integer> eq_ids) const\n{\n  // need to update timestamp of all submatrices\n  MatrixImpl& A00 = m(0, 0).impl()->get<Alien::BackEnd::tag::simplecsr>(true);\n  MatrixImpl& A01 = m(0, 1).impl()->get<Alien::BackEnd::tag::simplecsr>(true);\n  MatrixImpl& A10 = m(1, 0).impl()->get<Alien::BackEnd::tag::simplecsr>(true);\n  MatrixImpl& A11 = m(1, 1).impl()->get<Alien::BackEnd::tag::simplecsr>(true);\n  VectorImpl& b0 = x[0].impl()->get<Alien::BackEnd::tag::simplecsr>(true);\n  VectorImpl& b1 = x[1].impl()->get<Alien::BackEnd::tag::simplecsr>(true);\n  {\n    eErrorType error =\n    _normalize(A00, A01, m(0, 1).impl()->hasFeature(\"transposed\"), eq_ids, b0);\n    if (error != NoError)\n      return error;\n  }\n  {\n    eErrorType error =\n    _normalize(A11, eq_ids, A10, m(1, 0).impl()->hasFeature(\"transposed\"), b1);\n    return error;\n  }\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\ntemplate <>\nvoid NormalizeOpt::Op::multInvDiag<0>()\n{}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\ntemplate <>\nvoid NormalizeOpt::Op::multInvDiag<1>()\n{\n  for (Integer irow = 0; irow < m_local_size; ++irow) {\n    Integer off = m_row_offset[irow];\n    Real diag = m_matrix[off];\n    for (Integer col = off; col < m_row_offset[irow + 1]; ++col) {\n      m_matrix[col] /= diag;\n    }\n    m_rhs[irow] /= diag;\n\n    if (!m_keep_diag)\n      m_matrix[off] = 0.;\n  }\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\ntemplate <Integer N>\nvoid NormalizeOpt::Op::multInvDiag()\n{\n#ifdef ALIEN_USE_EIGEN2\n  if (m_algo == EigenLU) {\n    using namespace Eigen;\n    using namespace std;\n    typedef Eigen::Matrix<Real, N, N, RowMajor> MatrixType;\n    typedef Eigen::Matrix<Real, N, 1> VectorType;\n    const Integer NxN = N * N;\n    // TOCHECK : to be removed ?\n    // cout<<\"MULT INV DIAG B\"<<m_equations_num<<endl;\n    UniqueArray<Real> block(NxN);\n    UniqueArray<Real> vect(N);\n    Map<MatrixType> m(block.begin(), N, N);\n    Map<VectorType> v(vect.begin(), N);\n    if (m_diag_first) {\n      for (Integer irow = 0; irow < m_local_size; ++irow) {\n        Integer off = m_row_offset[irow];\n\n        Map<MatrixType> diag(&m_matrix[off * NxN], N, N);\n        if (diag.determinant() == 0) {\n          cout << \"Non inversible diagonal : row=\" << irow << endl;\n          cout << \" DIAG :\" << endl;\n          cout << diag << endl;\n        }\n        MatrixType inv_diag = diag.inverse();\n        // TOCHECK : to be removed ?\n        // PartialPivLU< MatrixType > lu(diag);\n        // MatrixType inv_diag = lu.inverse() ;\n\n        // OFF DIAGONAL treatment\n        for (Integer col = off + 1; col < m_row_offset[irow + 1]; ++col) {\n          block.copy(ArrayView<Real>(NxN, &m_matrix[col * NxN]));\n          Map<MatrixType> matrix(&m_matrix[col * NxN], N, N);\n          matrix = inv_diag * m;\n          // TOCHECK : to be removed ?\n          // matrix = lu.solve(m) ;\n        }\n\n        // RHS treatment\n        vect.copy(ArrayView<Real>(N, &m_rhs[irow * N]));\n        Map<VectorType> rhs(&m_rhs[irow * N], N);\n        rhs = inv_diag * v;\n        // TOCHECK : to be removed\n        // rhs = lu.solve(v) ;\n\n        if (m_keep_diag)\n          diag.setIdentity();\n        else\n          diag.setZero();\n      }\n    }\n    else {\n      for (Integer irow = 0; irow < m_local_size; ++irow) {\n        Integer off = m_row_offset[irow] + m_upper_diag_index[irow];\n\n        Map<MatrixType> diag(&m_matrix[off * NxN], N, N);\n        if (diag.determinant() == 0) {\n          cout << \"Non inversible diagonal : row=\" << irow << endl;\n          cout << \" DIAG :\" << endl;\n          cout << diag << endl;\n        }\n        MatrixType inv_diag = diag.inverse();\n        // TOCHECK : to be removed ?\n        // PartialPivLU< MatrixType > lu(diag);\n        // MatrixType inv_diag = lu.inverse() ;\n\n        // OFF DIAGONAL treatment\n        for (Integer col = m_row_offset[irow]; col < off; ++col) {\n          block.copy(ArrayView<Real>(NxN, &m_matrix[col * NxN]));\n          Map<MatrixType> matrix(&m_matrix[col * NxN], N, N);\n          matrix = inv_diag * m;\n          // TOCHECK : to be removed ?\n          // matrix = lu.solve(m) ;\n        }\n        // skip diagonal block\n        for (Integer col = off + 1; col < m_row_offset[irow + 1]; ++col) {\n          block.copy(ArrayView<Real>(NxN, &m_matrix[col * NxN]));\n          Map<MatrixType> matrix(&m_matrix[col * NxN], N, N);\n          matrix = inv_diag * m;\n          // TOCHECK : to be removed ?\n          // matrix = lu.solve(m) ;\n        }\n\n        // RHS treatment\n        vect.copy(ArrayView<Real>(N, &m_rhs[irow * N]));\n        Map<VectorType> rhs(&m_rhs[irow * N], N);\n        rhs = inv_diag * v;\n        // TOCHECK : to be removed ?\n        // rhs = lu.solve(v) ;\n\n        if (m_keep_diag)\n          diag.setIdentity();\n        else\n          diag.setZero();\n      }\n    }\n  }\n  else\n#endif\n  {\n    if (m_diag_first) {\n      for (Integer irow = 0; irow < m_local_size; ++irow) {\n        Integer off = m_row_offset[irow];\n\n        Real* diag = &m_matrix[off * N * N];\n        LU<N> lu(diag);\n\n        // OFF DIAGONAL treatment\n        for (Integer col = off + 1; col < m_row_offset[irow + 1]; ++col) {\n          lu.template solve<N, false>(&m_matrix[col * N * N]);\n        }\n\n        // RHS treatment\n        lu.template solve<1, true>(&m_rhs[irow * N]);\n\n        if (m_keep_diag)\n          lu.setIdentity();\n        else\n          lu.setZero();\n      }\n    }\n    else {\n      for (Integer irow = 0; irow < m_local_size; ++irow) {\n        Integer off = m_row_offset[irow] + m_upper_diag_index[irow];\n\n        Real* diag = &m_matrix[off * N * N];\n        LU<N> lu(diag);\n\n        // OFF DIAGONAL treatment\n        for (Integer col = m_row_offset[irow]; col < off; ++col) {\n          lu.template solve<N, false>(&m_matrix[col * N * N]);\n        }\n        // skip diagonal block\n        for (Integer col = off + 1; col < m_row_offset[irow + 1]; ++col) {\n          lu.template solve<N, false>(&m_matrix[col * N * N]);\n        }\n        // RHS treatment\n        lu.template solve<1, true>(&m_rhs[irow * N]);\n\n        if (m_keep_diag)\n          lu.setIdentity();\n        else\n          lu.setZero();\n      }\n    }\n  }\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nNormalizeOpt::eErrorType\nNormalizeOpt::_normalize(MatrixImpl& m, VectorImpl& x) const\n{\n  Op op(m, x, m_algo, m_sum_first_eq);\n  if (m.block()) {\n    switch (m.block()->size()) {\n    case 1:\n      op.multInvDiag<1>();\n      break;\n    case 2:\n      op.multInvDiag<2>();\n      break;\n    case 3:\n      op.multInvDiag<3>();\n      break;\n    case 4:\n      op.multInvDiag<4>();\n      break;\n    default:\n      op.multInvDiag<0>();\n      break;\n    }\n  }\n  return NoError;\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\ntemplate <>\nvoid NormalizeOpt::Op2::multInvDiag<0>()\n{}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\ntemplate <>\nvoid NormalizeOpt::Op2::multInvDiag<1>()\n{\n  if (m_submatrix2) {\n    if (m_diag_first) {\n      ////////////////////////////////////////////\n      //\n      // NORMALIZE SubMatrix00 and RHS\n      for (Integer irow = 0; irow < m_local_size; ++irow) {\n        Integer off = m_row_offset[irow];\n        Real diag = m_matrix[off];\n        for (Integer col = off + 1; col < m_row_offset[irow + 1]; ++col) {\n          m_matrix[col] /= diag;\n        }\n        m_rhs[irow] /= diag;\n      }\n\n      ////////////////////////////////////////////\n      //\n      // NORMALIZE SubMatrix01\n      if (m_trans)\n        for (Integer i = 0; i < m_eq_ids.size(); ++i) {\n          Integer ieq = m_eq_ids[i];\n          for (Integer k = m_extra_eq_row_offset[ieq]; k < m_extra_eq_row_offset[ieq + 1];\n               ++k) {\n            Integer irow = m_extra_eq_cols[k];\n            Integer off = m_row_offset[irow];\n            Real diag = m_matrix[off];\n            m_extra_eq_matrix[k] /= diag;\n          }\n        }\n      else\n        for (Integer i = 0; i < m_eq_ids.size(); ++i) {\n          Integer irow = m_eq_ids[i];\n          Integer off = m_row_offset[irow];\n          Real diag = m_matrix[off];\n          for (Integer k = m_extra_eq_row_offset[irow];\n               k < m_extra_eq_row_offset[irow + 1]; ++k) {\n            m_extra_eq_matrix[k] /= diag;\n          }\n        }\n      ////////////////////////////////////////////\n      //\n      // SET DIAG TO Id\n      for (Integer irow = 0; irow < m_local_size; ++irow) {\n        Integer off_diag = m_row_offset[irow];\n        m_matrix[off_diag] = m_keep_diag ? 1. : 0.;\n      }\n    }\n    else {\n      ////////////////////////////////////////////\n      //\n      // NORMALIZE SubMatrix00 and RHS\n      for (Integer irow = 0; irow < m_local_size; ++irow) {\n        Integer off_diag = m_row_offset[irow] + m_upper_diag_index[irow];\n        Real diag = m_matrix[off_diag];\n        for (Integer col = m_row_offset[irow]; col < off_diag; ++col) {\n          m_matrix[col] /= diag;\n        }\n        for (Integer col = off_diag + 1; col < m_row_offset[irow + 1]; ++col) {\n          m_matrix[col] /= diag;\n        }\n        m_rhs[irow] /= diag;\n      }\n\n      ////////////////////////////////////////////\n      //\n      // NORMALIZE SubMatrix01\n      if (m_trans)\n        for (Integer i = 0; i < m_eq_ids.size(); ++i) {\n          Integer ieq = m_eq_ids[i];\n          for (Integer k = m_extra_eq_row_offset[ieq]; k < m_extra_eq_row_offset[ieq + 1];\n               ++k) {\n            Integer irow = m_extra_eq_cols[k];\n            Integer off = m_row_offset[irow] + m_upper_diag_index[irow];\n            Real diag = m_matrix[off];\n            m_extra_eq_matrix[k] /= diag;\n          }\n        }\n      else\n        for (Integer i = 0; i < m_eq_ids.size(); ++i) {\n          Integer irow = m_eq_ids[i];\n          Integer off = m_row_offset[irow] + m_upper_diag_index[irow];\n          Real diag = m_matrix[off];\n          for (Integer k = m_extra_eq_row_offset[irow];\n               k < m_extra_eq_row_offset[irow + 1]; ++k) {\n            m_extra_eq_matrix[k] /= diag;\n          }\n        }\n      ////////////////////////////////////////////\n      //\n      // SET DIAG TO Id\n      for (Integer irow = 0; irow < m_local_size; ++irow) {\n        Integer off_diag = m_row_offset[irow] + m_upper_diag_index[irow];\n        m_matrix[off_diag] = m_keep_diag ? 1. : 0.;\n      }\n    }\n  }\n\n  if (m_submatrix1) {\n    ////////////////////////////////////////////\n    //\n    // NORMALIZE SubMatrix10 SubMatrix11 RHS\n    for (Integer i = 0; i < m_eq_ids.size(); ++i) {\n      Integer ieq = m_eq_ids[i];\n      Real diag = m_matrix[ieq];\n      for (Integer j = m_extra_eq_row_offset[ieq]; j < m_extra_eq_row_offset[ieq + 1];\n           ++j) {\n        for (Integer k = 0; k < m_nuk2; ++k)\n          m_extra_eq_matrix[j * m_nuk2 + k] /= diag;\n      }\n      m_rhs[ieq] /= diag;\n      m_matrix[ieq] = 1.;\n    }\n  }\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\ntemplate <Integer N>\nvoid NormalizeOpt::Op2::multInvDiag()\n{\n  if (m_submatrix2) {\n    if (m_diag_first) {\n      ////////////////////////////////////////////\n      //\n      // NORMALIZE SubMatrix00\n      for (Integer irow = 0; irow < m_local_size; ++irow) {\n        Integer off = m_row_offset[irow];\n\n        Real* diag = &m_matrix[off * N * N];\n        LU<N> lu(diag);\n\n        // OFF DIAGONAL treatment\n        for (Integer col = off + 1; col < m_row_offset[irow + 1]; ++col) {\n          lu.template solve<N, false>(&m_matrix[col * N * N]);\n        }\n\n        // RHS treatment\n        lu.template solve<1, true>(&m_rhs[irow * N]);\n      }\n\n      ////////////////////////////////////////////\n      //\n      // NORMALIZE SubMatrix01\n      if (m_trans)\n        for (Integer i = 0; i < m_eq_ids.size(); ++i) {\n          Integer ieq = m_eq_ids[i];\n          for (Integer k = m_extra_eq_row_offset[ieq]; k < m_extra_eq_row_offset[ieq + 1];\n               ++k) {\n            Integer irow = m_extra_eq_cols[k];\n            Integer off = m_row_offset[irow];\n            Real* diag = &m_matrix[off * N * N];\n            LU<N> lu(diag, false);\n\n            lu.template solve<1, true>(&m_extra_eq_matrix[k * N]);\n          }\n        }\n      else\n        for (Integer i = 0; i < m_eq_ids.size(); ++i) {\n          Integer irow = m_eq_ids[i];\n          Integer off = m_row_offset[irow];\n          Real* diag = &m_matrix[off * N * N];\n          LU<N> lu(diag, false);\n          for (Integer k = m_extra_eq_row_offset[irow];\n               k < m_extra_eq_row_offset[irow + 1]; ++k) {\n            lu.template solve<N, false>(&m_extra_eq_matrix[k * N]);\n          }\n        }\n\n      ////////////////////////////////////////////\n      //\n      // SET DIAG TO Id\n      if (m_keep_diag)\n        for (Integer irow = 0; irow < m_local_size; ++irow) {\n          Integer off = m_row_offset[irow];\n          Real* diag = &m_matrix[off * N * N];\n          LU<N> lu(diag, false);\n\n          lu.setIdentity();\n        }\n      else\n        for (Integer irow = 0; irow < m_local_size; ++irow) {\n          Integer off = m_row_offset[irow];\n          Real* diag = &m_matrix[off * N * N];\n          LU<N> lu(diag, false);\n          lu.setZero();\n        }\n    }\n    else {\n      ////////////////////////////////////////////\n      //\n      // NORMALIZE SubMatrix01\n      for (Integer irow = 0; irow < m_local_size; ++irow) {\n        Integer off = m_row_offset[irow] + m_upper_diag_index[irow];\n\n        Real* diag = &m_matrix[off * N * N];\n        LU<N> lu(diag);\n\n        // OFF DIAGONAL treatment\n        for (Integer col = m_row_offset[irow]; col < off; ++col) {\n          lu.template solve<N, false>(&m_matrix[col * N * N]);\n        }\n        // skip diagonal block\n        for (Integer col = off + 1; col < m_row_offset[irow + 1]; ++col) {\n          lu.template solve<N, false>(&m_matrix[col * N * N]);\n        }\n        // RHS treatment\n        lu.template solve<1, true>(&m_rhs[irow * N]);\n      }\n      ////////////////////////////////////////////\n      //\n      // NORMALIZE SubMatrix01\n      if (m_trans)\n        for (Integer i = 0; i < m_eq_ids.size(); ++i) {\n          Integer ieq = m_eq_ids[i];\n          for (Integer k = m_extra_eq_row_offset[ieq]; k < m_extra_eq_row_offset[ieq + 1];\n               ++k) {\n            Integer irow = m_extra_eq_cols[k] - m_local_offset;\n\n            Integer off = m_row_offset[irow] + m_upper_diag_index[irow];\n            Real* diag = &m_matrix[off * N * N];\n            LU<N> lu(diag, false);\n\n            lu.template solve<1, true>(&m_extra_eq_matrix[k * N]);\n          }\n        }\n      else {\n        for (Integer i = 0; i < m_eq_ids.size(); ++i) {\n          Integer irow = m_eq_ids[i];\n          Integer off = m_row_offset[irow] + m_upper_diag_index[irow];\n          Real* diag = &m_matrix[off * N * N];\n          LU<N> lu(diag, false);\n          for (Integer k = m_extra_eq_row_offset[irow];\n               k < m_extra_eq_row_offset[irow + 1]; ++k) {\n            lu.template solve<N, false>(&m_extra_eq_matrix[k * N]);\n          }\n        }\n      }\n\n      ////////////////////////////////////////////\n      //\n      // SET DIAG TO Id\n      if (m_keep_diag)\n        for (Integer irow = 0; irow < m_local_size; ++irow) {\n          Integer off = m_row_offset[irow] + m_upper_diag_index[irow];\n          Real* diag = &m_matrix[off * N * N];\n          LU<N> lu(diag, false);\n\n          lu.setIdentity();\n        }\n      else\n        for (Integer irow = 0; irow < m_local_size; ++irow) {\n          Integer off = m_row_offset[irow] + m_upper_diag_index[irow];\n          Real* diag = &m_matrix[off * N * N];\n          LU<N> lu(diag, false);\n          lu.setZero();\n        }\n    }\n  }\n\n  if (m_submatrix1) {\n    ////////////////////////////////////////////\n    //\n    // NORMALIZE SubMatrix10 SubMatrix11 RHS\n    for (Integer i = 0; i < m_eq_ids.size(); ++i) {\n      Integer ieq = m_eq_ids[i];\n      Real diag = m_matrix[ieq];\n      for (Integer j = m_extra_eq_row_offset[ieq]; j < m_extra_eq_row_offset[ieq + 1];\n           ++j) {\n        for (Integer k = 0; k < N; ++k)\n          m_extra_eq_matrix[j * N + k] /= diag;\n      }\n      m_rhs[ieq] /= diag;\n      m_matrix[ieq] = 1.;\n    }\n  }\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nNormalizeOpt::eErrorType\nNormalizeOpt::_normalize(MatrixImpl& m, MatrixImpl& m2, bool trans,\n                         ConstArrayView<Integer> eq_ids, VectorImpl& x) const\n{\n  Op2 op(m, m2, trans, eq_ids, x, m_algo, m_sum_first_eq);\n\n  switch (x.block()->size()) {\n  case 1:\n    op.multInvDiag<1>();\n    break;\n  case 2:\n    op.multInvDiag<2>();\n    break;\n  case 3:\n    op.multInvDiag<3>();\n    break;\n  case 4:\n    op.multInvDiag<4>();\n    break;\n  default:\n    op.multInvDiag<0>();\n    break;\n  }\n  return NoError;\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\nNormalizeOpt::eErrorType\nNormalizeOpt::_normalize(MatrixImpl& m, ConstArrayView<Integer> eq_ids, MatrixImpl& m2,\n                         bool trans, VectorImpl& x) const\n{\n  Op2 op(m, eq_ids, m2, trans, x, m_algo, m_sum_first_eq);\n\n  switch (x.block()->size()) {\n  case 1:\n    op.multInvDiag<1>();\n    break;\n  case 2:\n    op.multInvDiag<2>();\n    break;\n  case 3:\n    op.multInvDiag<3>();\n    break;\n  case 4:\n    op.multInvDiag<4>();\n    break;\n  default:\n    op.multInvDiag<0>();\n    break;\n  }\n  return NoError;\n}\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n\n} // namespace Alien\n\n/*---------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------*/\n", "meta": {"hexsha": "78ad816bc45046ec74894373bf1738174090970b", "size": 21178, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/modules/core/src/alien/expression/normalization/NormalizeOpt.cc", "max_stars_repo_name": "sdesrozis/alien", "max_stars_repo_head_hexsha": "af497785c97d00bde17e3c0a08a2f69289931dac", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/modules/core/src/alien/expression/normalization/NormalizeOpt.cc", "max_issues_repo_name": "sdesrozis/alien", "max_issues_repo_head_hexsha": "af497785c97d00bde17e3c0a08a2f69289931dac", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/modules/core/src/alien/expression/normalization/NormalizeOpt.cc", "max_forks_repo_name": "sdesrozis/alien", "max_forks_repo_head_hexsha": "af497785c97d00bde17e3c0a08a2f69289931dac", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.282127031, "max_line_length": 90, "alphanum_fraction": 0.4612333554, "num_tokens": 5277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2363385312979336}}
{"text": "/*\n *            Copyright 2016 The MUSCET Development Team\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n\n#include <votca/xtp/gyration.h>\n#include <boost/format.hpp>\n#include <votca/xtp/numerical_integrations.h>\n#include <votca/xtp/orbitals.h>\n//#include <votca/xtp/units.h>\n#include <votca/tools/linalg.h>\n\nnamespace votca { namespace xtp {\n\nvoid Density2Gyration::Initialize(Property* options) {\n    string key = Identify();\n\n    _state    = options->get(key + \".state\").as<string> (); \n    _state_no = options->get(key + \".statenumber\").as<int> ();\n    _spin     = options->get(key + \".spin\").as<string> ();\n    if ( options->exists(key+\".ecp\")) {\n       _use_ecp=options->get(key + \".ecp\").as<bool> ();\n    }\n\n    _integrationmethod     = options->get(key + \".integrationmethod\").as<string> ();\n  \n    if (!(_integrationmethod==\"numeric\" || _integrationmethod==\"analytic\")){\n        std::runtime_error(\"Method not recognized. Only numeric and analytic available\");\n    }\n    if ( options->exists(key+\".gridsize\")) {\n         _gridsize = options->get(key+\".gridsize\").as<string>();\n         }\n    else _gridsize=\"medium\";\n    if ( options->exists(key+\".openmp\")) {\n         _openmp_threads = options->get(key+\".openmp\").as<int>();\n         }\n    else _openmp_threads=0;\n    \n    // get the path to the shared folders with xml files\n    char *votca_share = getenv(\"VOTCASHARE\");    \n    if(votca_share == NULL) throw std::runtime_error(\"VOTCASHARE not set, cannot open help files.\");\n\n  \n   \n}\n\n\n\nvoid Density2Gyration::AnalyzeDensity( Orbitals & _orbitals ){\n    int threads=1;\n#ifdef _OPENMP\n            if ( _openmp_threads > 0 ) omp_set_num_threads(_openmp_threads); \n            threads=omp_get_max_threads();\n#endif\n   CTP_LOG(ctp::logDEBUG, *_log) << \"===== Running on \"<< threads << \" threads ===== \" << flush;\n\n        vector< ctp::QMAtom* > Atomlist =_orbitals.QMAtoms();\n        std::vector< ctp::QMAtom* >::iterator at;\n        for (at=Atomlist.begin();at<Atomlist.end();++at){\n            ctp::QMAtom * atom=new ctp::QMAtom(*(*at));\n            _Atomlist.push_back(atom);\n        }\n        ub::matrix<double> DMAT_tot;\n        BasisSet bs;\n        bs.LoadBasisSet(_orbitals.getDFTbasis());\n        AOBasis basis;\n        basis.AOBasisFill(&bs, _Atomlist );\n        \n        // Analyze geometry\n        AnalyzeGeometry( _Atomlist );\n        \n       \n        \n        std::vector<ub::matrix<double> > DMAT;\n\n        //basis.ReorderMOs(_orbitals.MOCoefficients(), _orbitals.getQMpackage(), \"votca\" );  \n        \n        if(_state==\"transition\"){\n                DMAT_tot=_orbitals.TransitionDensityMatrix(_spin, _state_no-1); \n        }\n        else if (_state==\"ground\" || _state==\"excited\" || _state==\"exciton\" ){\n             CTP_LOG(ctp::logDEBUG, *_log) << \"Calculating density matrix:        \" << _state << \" No. \" << _state_no << flush;\n            \n        \n           \n            ub::matrix<double> DMATGS=_orbitals.DensityMatrixGroundState();\n            DMAT_tot=DMATGS;\n            if ( _state_no > 0 && ( _state==\"excited\" || _state==\"exciton\" ) ){\n               \n                DMAT = _orbitals.DensityMatrixExcitedState( _spin, _state_no-1);\n                \n                if (_state == \"excited\" ){ \n                    DMAT_tot=DMAT_tot-DMAT[0]+DMAT[1];\n                }\n               \n            }            \n\t   // Ground state + hole_contribution + electron contribution\n\t}\n        else throw std::runtime_error(\"State entry not recognized\");\n\n        \n        if (_integrationmethod==\"numeric\")  {\n\n            // setup numerical integration grid\n            NumericalIntegration numway;\n            numway.GridSetup(_gridsize,&bs,_Atomlist,&basis);\n            \n            \n            if ( _state==\"ground\" || _state==\"excited\") {\n                //LOG(logDEBUG, *_log) << TimeStamp() << \" Calculate Densities at Numerical Grid with gridsize \"<< _gridsize  << flush; \n                ub::vector<double> _analysis=numway.IntegrateGyrationTensor(DMAT_tot);\n\n                // convert to eigenframe\n                ub::vector<double> _gyration_tensor_diagonal;\n                ub::matrix<double> _gyration_tensor_eigenframe;\n                CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Converting to Eigenframe \" << flush; \n                Convert2Eigenframe( _analysis, _gyration_tensor_diagonal, _gyration_tensor_eigenframe );\n            \n                // determine quaternion for rotation of xyz to EF\n                CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Calculating Quaternion \" << flush; \n                ub::vector<double> _quaternion = get_quaternion( _gyration_tensor_eigenframe );\n\n                // report results\n                CTP_LOG(ctp::logDEBUG, *_log) << ctp::TimeStamp() << \" Reporting \" << flush; \n                ReportAnalysis( _state, _analysis, _gyration_tensor_diagonal, _gyration_tensor_eigenframe  );\n                \n            \n            } else if ( _state == \"exciton\" ){\n                // hole density first\n                ub::vector<double> _analysis_hole=numway.IntegrateGyrationTensor(DMAT[0]);\n\n                // convert to eigenframe\n                ub::vector<double> _gyration_tensor_diagonal_hole;\n                ub::matrix<double> _gyration_tensor_eigenframe_hole;\n                Convert2Eigenframe( _analysis_hole, _gyration_tensor_diagonal_hole, _gyration_tensor_eigenframe_hole );\n            \n                // determine quaternion for rotation of xyz to EF\n                ub::vector<double> _quaternion_hole = get_quaternion( _gyration_tensor_eigenframe_hole );\n\n                // report results\n                ReportAnalysis( \"hole\", _analysis_hole, _gyration_tensor_diagonal_hole, _gyration_tensor_eigenframe_hole  );\n\n                // electron density\n                ub::vector<double> _analysis_electron=numway.IntegrateGyrationTensor(DMAT[1]);\n\n                // convert to eigenframe\n                ub::vector<double> _gyration_tensor_diagonal_electron;\n                ub::matrix<double> _gyration_tensor_eigenframe_electron;\n                Convert2Eigenframe( _analysis_electron, _gyration_tensor_diagonal_electron, _gyration_tensor_eigenframe_electron );\n            \n                // determine quaternion for rotation of xyz to EF\n                 ub::vector<double> _quaternion_electron = get_quaternion( _gyration_tensor_eigenframe_electron );\n                \n                \n                // report results\n                ReportAnalysis( \"electron\", _analysis_electron, _gyration_tensor_diagonal_electron,  _gyration_tensor_eigenframe_electron  );\n                \n            }\n\n        }\n          else if (_integrationmethod==\"analytic\") {\n              //esp.Fit2Density_analytic(_Atomlist,DMAT_tot,basis);\n        }\n        }\n\n\n    void Density2Gyration::AnalyzeGeometry(vector<ctp::QMAtom*> _atoms){\n    \n        Elements _elements; \n        ub::vector<double> _analysis = ub::zero_vector<double>(10);\n        std::vector< ctp::QMAtom* >::iterator at;\n        for (at=_atoms.begin();at<_atoms.end();++at){\n            \n            double m = _elements.getMass( (*at)->type );\n            double x = (*at)->x ;\n            double y = (*at)->y ;\n            double z = (*at)->z ;\n            _analysis(0) += m   ;\n            _analysis(1) += m*x ;\n            _analysis(2) += m*y ;\n            _analysis(3) += m*z ;\n            \n            _analysis(4) += m*x*x;\n            _analysis(5) += m*x*y;\n            _analysis(6) += m*x*z;\n            _analysis(7) += m*y*y;\n            _analysis(8) += m*y*z;\n            _analysis(9) += m*z*z;\n            \n        }\n        \n        // normalize\n        for ( unsigned i =1 ; i < 4; i++){\n            _analysis(i) = _analysis(i)/_analysis(0)/tools::conv::bohr2ang;\n        }\n                // normalize\n        for ( unsigned i =4 ; i < _analysis.size(); i++){\n            _analysis(i) = _analysis(i)/_analysis(0)/tools::conv::bohr2ang/tools::conv::bohr2ang;\n        }\n        \n        \n        \n        // gyration tensor\n        _analysis(4) -= _analysis(1)*_analysis(1);\n        _analysis(5) -= _analysis(1)*_analysis(2);\n        _analysis(6) -= _analysis(1)*_analysis(3);\n        _analysis(7) -= _analysis(2)*_analysis(2);\n        _analysis(8) -= _analysis(2)*_analysis(3);\n        _analysis(9) -= _analysis(3)*_analysis(3);\n\n        \n        // convert to eigenframe\n        ub::vector<double> _gyration_tensor_diagonal;\n        ub::matrix<double> _gyration_tensor_eigenframe;\n        Convert2Eigenframe( _analysis, _gyration_tensor_diagonal, _gyration_tensor_eigenframe );\n\n        cout << \"\\n\";\n        \n        for ( int i =0 ; i< 3; i++){\n            \n            cout << _gyration_tensor_eigenframe(0,i) << \" \" << _gyration_tensor_eigenframe(1,i) << \"  \" <<  _gyration_tensor_eigenframe(2,i) << \"\\n\" << endl;  \n            \n        }\n        \n        /*\n        // test for right-handedness\n        double check_x = _gyration_tensor_eigenframe(1,0)* _gyration_tensor_eigenframe(2,1) -  _gyration_tensor_eigenframe(2,0)* _gyration_tensor_eigenframe(1,1) ;\n        double check_y = _gyration_tensor_eigenframe(2,0)* _gyration_tensor_eigenframe(0,1) -  _gyration_tensor_eigenframe(0,0)* _gyration_tensor_eigenframe(2,1) ;\n        double check_z = _gyration_tensor_eigenframe(0,0)* _gyration_tensor_eigenframe(1,1) -  _gyration_tensor_eigenframe(1,0)* _gyration_tensor_eigenframe(0,1) ;\n        \n        cout << \" check x\" << check_x << \" vs \" << _gyration_tensor_eigenframe(0,2) << \"\\n\" <<endl;\n        cout << \" check y\" << check_y << \" vs \" << _gyration_tensor_eigenframe(1,2) << \"\\n\" <<endl;\n        cout << \" check z\" << check_z << \" vs \" << _gyration_tensor_eigenframe(2,2) << \"\\n\" <<endl;\n        */\n        // determine quaternion for rotation of xyz to EF\n        ub::vector<double> _quaternion = get_quaternion( _gyration_tensor_eigenframe );\n\n        // report results\n        ReportAnalysis( \"geometry\", _analysis, _gyration_tensor_diagonal, _gyration_tensor_eigenframe  );\n        \n        \n        \n    \n    \n    }\n\n\n\n    void Density2Gyration::ReportAnalysis(string label, ub::vector<double> _tensor_elements, ub::vector<double> _tensor_diagonal, ub::matrix<double> _tensor_frame){\n\n        \n            CTP_LOG(ctp::logINFO, *_log) << \"---------------- \" << label << \" ----------------\" << flush;\n            CTP_LOG(ctp::logINFO, *_log) << (boost::format(\"  Norm               = %1$9.4f \") % (_tensor_elements(0)) ) << flush;\n            \n            //LOG(logINFO,*_pLog) << (format(\"  Level = %1$4d DFT = %2$+1.4f VXC = %3$+1.4f S-X = %4$+1.4f S-C = %5$+1.4f GWA = %6$+1.4f\") % (_i+_qpmin+1) % _dft_energies( _i + _qpmin ) % _vxc(_i,_i) % _sigma_x(_i,_i) % _sigma_c(_i,_i) % _qp_energies(_i + _qpmin ) ).str() << flush;\n            \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Centroid x         = %1$9.4f Ang\") % (_tensor_elements(1)*tools::conv::bohr2ang) ) << flush;\n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Centroid y         = %1$9.4f Ang\") % (_tensor_elements(2)*tools::conv::bohr2ang) ) << flush;\n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Centroid y         = %1$9.4f Ang\") % (_tensor_elements(3)*tools::conv::bohr2ang) ) << flush;\n            \n            double RA2 = tools::conv::bohr2ang  *tools::conv::bohr2ang;\n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Gyration Tensor xx = %1$9.4f Ang^2\") % (_tensor_elements(4)*RA2) ) << flush;\n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Gyration Tensor xy = %1$9.4f Ang^2\") % (_tensor_elements(5)*RA2) ) << flush;\n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Gyration Tensor xz = %1$9.4f Ang^2\") % (_tensor_elements(6)*RA2) ) << flush;\n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Gyration Tensor yy = %1$9.4f Ang^2\") % (_tensor_elements(7)*RA2) ) << flush;\n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Gyration Tensor yz = %1$9.4f Ang^2\") % (_tensor_elements(8)*RA2) ) << flush;\n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Gyration Tensor zz = %1$9.4f Ang^2\") % (_tensor_elements(9)*RA2) ) << flush;\n            \n            \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Gyration Tensor D1 = %1$9.4f Ang^2\") % (_tensor_diagonal(0)*RA2) ) << flush;     \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Gyration Tensor D2 = %1$9.4f Ang^2\") % (_tensor_diagonal(1)*RA2) ) << flush;     \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Gyration Tensor D3 = %1$9.4f Ang^2\") % (_tensor_diagonal(2)*RA2) ) << flush;   \n\n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Radius of Gyration = %1$9.4f Ang\") % (std::sqrt(_tensor_diagonal(0) + _tensor_diagonal(1) + _tensor_diagonal(2))*tools::conv::bohr2ang )) << flush;  \n            \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Tensor EF Axis 1 1 = %1$9.4f \") % (_tensor_frame(0,0)) ) << flush;             \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Tensor EF Axis 1 2 = %1$9.4f \") % (_tensor_frame(1,0)) ) << flush;             \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Tensor EF Axis 1 3 = %1$9.4f \") % (_tensor_frame(2,0)) ) << flush;             \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Tensor EF Axis 2 1 = %1$9.4f \") % (_tensor_frame(0,1)) ) << flush;             \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Tensor EF Axis 2 2 = %1$9.4f \") % (_tensor_frame(1,1)) ) << flush;             \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Tensor EF Axis 2 3 = %1$9.4f \") % (_tensor_frame(2,1)) ) << flush; \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Tensor EF Axis 3 1 = %1$9.4f \") % (_tensor_frame(0,2)) ) << flush;             \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Tensor EF Axis 3 2 = %1$9.4f \") % (_tensor_frame(1,2)) ) << flush;             \n            CTP_LOG(ctp::logINFO,*_log) << (boost::format(\"  Tensor EF Axis 3 3 = %1$9.4f \") % (_tensor_frame(2,2)) ) << flush;             \n\n    \n    }\n\n    ub::vector<double> Density2Gyration::get_quaternion(ub::matrix<double>& eigenframe){\n        \n        // second coordinate system is assumed to be Cartesian\n     \n        ub::matrix<double> M=ub::zero_matrix<double>(3,3);\n\n        // add all the outer products, if second coordinate system was not Cartesian\n        // is anyways, so M=eigenframe\n        //M=ub::trans(eigenframe);\n        M=eigenframe;\n       \n        ub::matrix<double> N = ub::zero_matrix<double>(4,4);\n          \n        N(0,0) =  M(0,0) + M(1,1) + M(2,2); // N11=float(M[0][:,0]+M[1][:,1]+M[2][:,2]);\n        N(1,1) =  M(0,0) - M(1,1) - M(2,2); // N22=float(M[0][:,0]-M[1][:,1]-M[2][:,2])\n        N(2,2) = -M(0,0) + M(1,1) - M(2,2); // N33=float(-M[0][:,0]+M[1][:,1]-M[2][:,2])\n        N(3,3) = -M(0,0) - M(1,1) + M(2,2); // N44=float(-M[0][:,0]-M[1][:,1]+M[2][:,2])\n        N(0,1) =  M(1,2) - M(2,1);          // N12=float(M[1][:,2]-M[2][:,1])\n        N(0,2) =  M(2,0) - M(0,2);          // N13=float(M[2][:,0]-M[0][:,2])\n        N(0,3) =  M(0,1) - M(1,0);          // N14=float(M[0][:,1]-M[1][:,0])\n        N(1,0) =  N(0,1);                   // N21=float(N12)\n        N(1,2) =  M(0,1) + M(1,0);          // N23=float(M[0][:,1]+M[1][:,0])\n        N(1,3) =  M(2,0) + M(0,2);          // N24=float(M[2][:,0]+M[0][:,2])\n        N(2,0) =  N(0,2);                   // N31=float(N13)\n        N(2,1) =  N(1,2);                   // N32=float(N23)\n        N(2,3) =  M(1,2) + M(2,1);          // N34=float(M[1][:,2]+M[2][:,1])\n        N(3,0) =  N(0,3);                   // N41=float(N14)\n        N(3,1) =  N(1,3);                   // N42=float(N24)\n        N(3,2) =  N(2,3);                   // N43=float(N34)\n\n        ub::vector<double> eigenvalues;\n        ub::matrix<double> eigenvectors;\n        linalg_eigenvalues( N, eigenvalues, eigenvectors );\n        \n        // find max eigenvalue\n        int index=0;\n        double maxev = eigenvalues(0);\n\n        for (unsigned i = 1; i < eigenvalues.size(); i++ ) {\n            if ( eigenvalues(i) > maxev ) {\n                maxev = eigenvalues(i);\n                index = i;\n            }\n        }\n        \n        // return this vector\n        ub::vector<double> quaternion = ub::zero_vector<double>(4);\n        quaternion(0)= eigenvectors(0,index);\n        quaternion(1)= eigenvectors(1,index);\n        quaternion(2)= eigenvectors(2,index);\n        quaternion(3)= eigenvectors(3,index);\n        \n        return quaternion;\n        \n    }\n    \n    \n    \n    \n        void Density2Gyration::Convert2Eigenframe(ub::vector<double> V, ub::vector<double> &_gyration_tensor_diagonal, ub::matrix<double> &_gyration_tensor_eigenframe   ){\n            \n                 ub::matrix<double> _gyration_tensor = ub::zero_matrix<double>(3,3);\n                _gyration_tensor(0,0) = V(4);\n                _gyration_tensor(1,0) = V(5);\n                _gyration_tensor(2,0) = V(6);\n                _gyration_tensor(0,1) = V(5);\n                _gyration_tensor(1,1) = V(7);\n                _gyration_tensor(2,1) = V(8);\n                _gyration_tensor(0,2) = V(6);\n                _gyration_tensor(1,2) = V(8);\n                _gyration_tensor(2,2) = V(9);\n            \n                linalg_eigenvalues( _gyration_tensor, _gyration_tensor_diagonal, _gyration_tensor_eigenframe );\n            \n        }\n\n\n\n\n}}\n\n\n", "meta": {"hexsha": "cd9a0696bed0fe68e2926e8f6cc1616d25c6bf71", "size": 17952, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/gyration.cc", "max_stars_repo_name": "choudarykvsp/xtp", "max_stars_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-05T17:36:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-05T17:36:53.000Z", "max_issues_repo_path": "src/libxtp/gyration.cc", "max_issues_repo_name": "choudarykvsp/xtp", "max_issues_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/gyration.cc", "max_forks_repo_name": "choudarykvsp/xtp", "max_forks_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6285714286, "max_line_length": 282, "alphanum_fraction": 0.5489081996, "num_tokens": 5257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23622818822842856}}
{"text": "//=====================================================\n// File   :  hand_vec_interface.hh\n// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n//=====================================================\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 2\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n// You should have received a copy of the GNU General Public License\n// along with this program; if not, write to the Free Software\n// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n//\n#ifndef HAND_VEC_INTERFACE_HH\n#define HAND_VEC_INTERFACE_HH\n\n#include <Eigen/Core>\n#include \"f77_interface.hh\"\n\nusing namespace Eigen;\n\ntemplate<class real>\nclass hand_vec_interface : public f77_interface_base<real> {\n\npublic :\n\n  typedef typename internal::packet_traits<real>::type Packet;\n  static const int PacketSize = internal::packet_traits<real>::size;\n\n  typedef typename f77_interface_base<real>::stl_matrix stl_matrix;\n  typedef typename f77_interface_base<real>::stl_vector stl_vector;\n  typedef typename f77_interface_base<real>::gene_matrix gene_matrix;\n  typedef typename f77_interface_base<real>::gene_vector gene_vector;\n\n  static void free_matrix(gene_matrix & A, int N){\n    internal::aligned_free(A);\n  }\n\n  static void free_vector(gene_vector & B){\n    internal::aligned_free(B);\n  }\n\n  static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){\n    int N = A_stl.size();\n    A = (real*)internal::aligned_malloc(N*N*sizeof(real));\n    for (int j=0;j<N;j++)\n      for (int i=0;i<N;i++)\n        A[i+N*j] = A_stl[j][i];\n  }\n\n  static inline void vector_from_stl(gene_vector & B, stl_vector & B_stl){\n    int N = B_stl.size();\n    B = (real*)internal::aligned_malloc(N*sizeof(real));\n    for (int i=0;i<N;i++)\n      B[i] = B_stl[i];\n  }\n\n  static inline std::string name() {\n    #ifdef PEELING\n    return \"hand_vectorized_peeling\";\n    #else\n    return \"hand_vectorized\";\n    #endif\n  }\n\n  static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n  {\n    asm(\"#begin matrix_vector_product\");\n    int AN = (N/PacketSize)*PacketSize;\n    int ANP = (AN/(2*PacketSize))*2*PacketSize;\n    int bound = (N/4)*4;\n    for (int i=0;i<N;i++)\n      X[i] = 0;\n\n    for (int i=0;i<bound;i+=4)\n    {\n      register real* __restrict__ A0 = A + i*N;\n      register real* __restrict__ A1 = A + (i+1)*N;\n      register real* __restrict__ A2 = A + (i+2)*N;\n      register real* __restrict__ A3 = A + (i+3)*N;\n\n      Packet ptmp0 = internal::pset1(B[i]);\n      Packet ptmp1 = internal::pset1(B[i+1]);\n      Packet ptmp2 = internal::pset1(B[i+2]);\n      Packet ptmp3 = internal::pset1(B[i+3]);\n//       register Packet ptmp0, ptmp1, ptmp2, ptmp3;\n//       asm(\n//\n//           \"movss     (%[B],%[j],4), %[ptmp0]  \\n\\t\"\n//           \"shufps   $0,%[ptmp0],%[ptmp0] \\n\\t\"\n//           \"movss    4(%[B],%[j],4), %[ptmp1]  \\n\\t\"\n//           \"shufps   $0,%[ptmp1],%[ptmp1] \\n\\t\"\n//           \"movss    8(%[B],%[j],4), %[ptmp2]  \\n\\t\"\n//           \"shufps   $0,%[ptmp2],%[ptmp2] \\n\\t\"\n//           \"movss   12(%[B],%[j],4), %[ptmp3]  \\n\\t\"\n//           \"shufps   $0,%[ptmp3],%[ptmp3] \\n\\t\"\n//           : [ptmp0] \"=x\" (ptmp0),\n//             [ptmp1] \"=x\" (ptmp1),\n//             [ptmp2] \"=x\" (ptmp2),\n//             [ptmp3] \"=x\" (ptmp3)\n//           : [B] \"r\" (B),\n//             [j] \"r\" (size_t(i))\n//           : );\n\n      if (AN>0)\n      {\n//         for (size_t j = 0;j<ANP;j+=8)\n//         {\n//           asm(\n//\n//           \"movaps     (%[A0],%[j],4), %%xmm8  \\n\\t\"\n//           \"movaps   16(%[A0],%[j],4), %%xmm12 \\n\\t\"\n//           \"movups     (%[A3],%[j],4), %%xmm11 \\n\\t\"\n//           \"movups   16(%[A3],%[j],4), %%xmm15 \\n\\t\"\n//           \"movups     (%[A2],%[j],4), %%xmm10 \\n\\t\"\n//           \"movups   16(%[A2],%[j],4), %%xmm14 \\n\\t\"\n//           \"movups     (%[A1],%[j],4), %%xmm9  \\n\\t\"\n//           \"movups   16(%[A1],%[j],4), %%xmm13 \\n\\t\"\n//\n//           \"mulps %[ptmp0], %%xmm8  \\n\\t\"\n//           \"addps (%[res0],%[j],4), %%xmm8  \\n\\t\"\n//           \"mulps %[ptmp3], %%xmm11 \\n\\t\"\n//           \"addps %%xmm11, %%xmm8  \\n\\t\"\n//           \"mulps %[ptmp2], %%xmm10 \\n\\t\"\n//           \"addps %%xmm10, %%xmm8  \\n\\t\"\n//           \"mulps %[ptmp1], %%xmm9  \\n\\t\"\n//           \"addps %%xmm9, %%xmm8   \\n\\t\"\n//           \"movaps %%xmm8, (%[res0],%[j],4)  \\n\\t\"\n//\n//           \"mulps %[ptmp0], %%xmm12 \\n\\t\"\n//           \"addps 16(%[res0],%[j],4), %%xmm12  \\n\\t\"\n//           \"mulps %[ptmp3], %%xmm15 \\n\\t\"\n//           \"addps %%xmm15, %%xmm12  \\n\\t\"\n//           \"mulps %[ptmp2], %%xmm14 \\n\\t\"\n//           \"addps %%xmm14, %%xmm12  \\n\\t\"\n//           \"mulps %[ptmp1], %%xmm13 \\n\\t\"\n//           \"addps %%xmm13, %%xmm12  \\n\\t\"\n//           \"movaps %%xmm12, 16(%[res0],%[j],4) \\n\\t\"\n//           :\n//           : [res0] \"r\" (X), [j] \"r\" (j),[A0] \"r\" (A0),\n//             [A1] \"r\" (A1),\n//             [A2] \"r\" (A2),\n//             [A3] \"r\" (A3),\n//             [ptmp0] \"x\" (ptmp0),\n//             [ptmp1] \"x\" (ptmp1),\n//             [ptmp2] \"x\" (ptmp2),\n//             [ptmp3] \"x\" (ptmp3)\n//           : \"%xmm8\", \"%xmm9\", \"%xmm10\", \"%xmm11\", \"%xmm12\", \"%xmm13\", \"%xmm14\", \"%xmm15\", \"%r14\");\n//         }\n          register Packet A00;\n          register Packet A01;\n          register Packet A02;\n          register Packet A03;\n          register Packet A10;\n          register Packet A11;\n          register Packet A12;\n          register Packet A13;\n          for (int j = 0;j<ANP;j+=2*PacketSize)\n          {\n//             A00 = internal::pload(&A0[j]);\n//             A01 = internal::ploadu(&A1[j]);\n//             A02 = internal::ploadu(&A2[j]);\n//             A03 = internal::ploadu(&A3[j]);\n//             A10 = internal::pload(&A0[j+PacketSize]);\n//             A11 = internal::ploadu(&A1[j+PacketSize]);\n//             A12 = internal::ploadu(&A2[j+PacketSize]);\n//             A13 = internal::ploadu(&A3[j+PacketSize]);\n//\n//             A00 = internal::pmul(ptmp0, A00);\n//             A01 = internal::pmul(ptmp1, A01);\n//             A02 = internal::pmul(ptmp2, A02);\n//             A03 = internal::pmul(ptmp3, A03);\n//             A10 = internal::pmul(ptmp0, A10);\n//             A11 = internal::pmul(ptmp1, A11);\n//             A12 = internal::pmul(ptmp2, A12);\n//             A13 = internal::pmul(ptmp3, A13);\n//\n//             A00 = internal::padd(A00,A01);\n//             A02 = internal::padd(A02,A03);\n//             A00 = internal::padd(A00,internal::pload(&X[j]));\n//             A00 = internal::padd(A00,A02);\n//             internal::pstore(&X[j],A00);\n//\n//             A10 = internal::padd(A10,A11);\n//             A12 = internal::padd(A12,A13);\n//             A10 = internal::padd(A10,internal::pload(&X[j+PacketSize]));\n//             A10 = internal::padd(A10,A12);\n//             internal::pstore(&X[j+PacketSize],A10);\n\n            internal::pstore(&X[j],\n              internal::padd(internal::pload(&X[j]),\n                internal::padd(\n                  internal::padd(internal::pmul(ptmp0,internal::pload(&A0[j])),internal::pmul(ptmp1,internal::ploadu(&A1[j]))),\n                  internal::padd(internal::pmul(ptmp2,internal::ploadu(&A2[j])),internal::pmul(ptmp3,internal::ploadu(&A3[j]))) )));\n\n            internal::pstore(&X[j+PacketSize],\n              internal::padd(internal::pload(&X[j+PacketSize]),\n                internal::padd(\n                  internal::padd(internal::pmul(ptmp0,internal::pload(&A0[j+PacketSize])),internal::pmul(ptmp1,internal::ploadu(&A1[j+PacketSize]))),\n                  internal::padd(internal::pmul(ptmp2,internal::ploadu(&A2[j+PacketSize])),internal::pmul(ptmp3,internal::ploadu(&A3[j+PacketSize]))) )));\n          }\n          for (int j = ANP;j<AN;j+=PacketSize)\n            internal::pstore(&X[j],\n              internal::padd(internal::pload(&X[j]),\n                internal::padd(\n                  internal::padd(internal::pmul(ptmp0,internal::pload(&A0[j])),internal::pmul(ptmp1,internal::ploadu(&A1[j]))),\n                  internal::padd(internal::pmul(ptmp2,internal::ploadu(&A2[j])),internal::pmul(ptmp3,internal::ploadu(&A3[j]))) )));\n      }\n      // process remaining scalars\n      for (int j=AN;j<N;j++)\n        X[j] += internal::pfirst(ptmp0) * A0[j] + internal::pfirst(ptmp1) * A1[j] + internal::pfirst(ptmp2) * A2[j] + internal::pfirst(ptmp3) * A3[j];\n    }\n    for (int i=bound;i<N;i++)\n    {\n      real tmp0 = B[i];\n      Packet ptmp0 = internal::pset1(tmp0);\n      int iN0 = i*N;\n      if (AN>0)\n      {\n        bool aligned0 = (iN0 % PacketSize) == 0;\n        if (aligned0)\n          for (int j = 0;j<AN;j+=PacketSize)\n            internal::pstore(&X[j], internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+iN0])),internal::pload(&X[j])));\n        else\n          for (int j = 0;j<AN;j+=PacketSize)\n            internal::pstore(&X[j], internal::padd(internal::pmul(ptmp0,internal::ploadu(&A[j+iN0])),internal::pload(&X[j])));\n      }\n      // process remaining scalars\n      for (int j=AN;j<N;j++)\n        X[j] += tmp0 * A[j+iN0];\n    }\n    asm(\"#end matrix_vector_product\");\n  }\n  \n  static inline void symv(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n  {\n    \n//     int AN = (N/PacketSize)*PacketSize;\n//     int ANP = (AN/(2*PacketSize))*2*PacketSize;\n//     int bound = (N/4)*4;\n    for (int i=0;i<N;i++)\n      X[i] = 0;\n    \n    int bound = std::max(0,N-8) & 0xfffffffE;\n\n    for (int j=0;j<bound;j+=2)\n    {\n      register real* __restrict__ A0 = A + j*N;\n      register real* __restrict__ A1 = A + (j+1)*N;\n      \n      real t0 = B[j];\n      Packet ptmp0 = internal::pset1(t0);\n      real t1 = B[j+1];\n      Packet ptmp1 = internal::pset1(t1);\n      \n      real t2 = 0;\n      Packet ptmp2 = internal::pset1(t2);\n      real t3 = 0;\n      Packet ptmp3 = internal::pset1(t3);\n      \n      int starti = j+2;\n      int alignedEnd = starti;\n      int alignedStart = (starti) + internal::first_aligned(&X[starti], N-starti);\n      alignedEnd = alignedStart + ((N-alignedStart)/(PacketSize))*(PacketSize);\n\n      X[j]   += t0 * A0[j];\n      X[j+1] += t1 * A1[j];\n      \n      X[j+1] += t0 * A0[j+1];\n      t2 += A0[j+1] * B[j+1];\n      \n//       alignedStart = alignedEnd;\n      for (int i=starti; i<alignedStart; ++i) {\n        X[i] += t0 * A0[i] + t1 * A1[i];\n        t2 += A0[i] * B[i];\n        t3 += A1[i] * B[i];\n      }\n      asm(\"#begin symv\");\n      for (size_t i=alignedStart; i<alignedEnd; i+=PacketSize) {\n        Packet A0i = internal::ploadu(&A0[i]);\n        Packet A1i = internal::ploadu(&A1[i]);\n//         Packet A0i1 = internal::ploadu(&A0[i+PacketSize]);\n        Packet Xi = internal::pload(&X[i]);\n        Packet Bi = internal::pload/*u*/(&B[i]);\n//         Packet Xi1 = internal::pload(&X[i+PacketSize]);\n//         Packet Bi1 = internal::pload/*u*/(&B[i+PacketSize]);\n        Xi = internal::padd(internal::padd(Xi, internal::pmul(ptmp0, A0i)), internal::pmul(ptmp1, A1i));\n        ptmp2 = internal::padd(ptmp2, internal::pmul(A0i, Bi));\n        ptmp3 = internal::padd(ptmp3, internal::pmul(A1i, Bi));\n//         Xi1 = internal::padd(Xi1, internal::pmul(ptmp1, A0i1));\n//         ptmp2 = internal::padd(ptmp2, internal::pmul(A0i1, Bi1));\n//         \n        internal::pstore(&X[i],Xi);\n//         internal::pstore(&X[i+PacketSize],Xi1);\n//         asm(\n//           \"prefetchnta   64(%[A0],%[i],4)   \\n\\t\"\n//           //\"movups     (%[A0],%[i],4), %%xmm8  \\n\\t\"\n//           \"movsd       (%[A0],%[i],4), %%xmm8  \\n\\t\"\n//           \"movhps     8(%[A0],%[i],4), %%xmm8  \\n\\t\"\n// //           \"movups   16(%[A0],%[i],4), %%xmm9  \\n\\t\"\n// //           \"movups   64(%[A0],%[i],4), %%xmm15  \\n\\t\"\n//           \"movaps     (%[B], %[i],4), %%xmm12 \\n\\t\"\n// //           \"movaps   16(%[B], %[i],4), %%xmm13 \\n\\t\"\n//           \"movaps     (%[X], %[i],4), %%xmm10 \\n\\t\"\n// //           \"movaps   16(%[X], %[i],4), %%xmm11 \\n\\t\"\n//           \n//           \"mulps %%xmm8, %%xmm12  \\n\\t\"\n// //           \"mulps %%xmm9, %%xmm13  \\n\\t\"\n//           \n//           \"mulps %[ptmp1], %%xmm8  \\n\\t\"\n//           \"addps %%xmm12, %[ptmp2]  \\n\\t\"\n//           \"addps %%xmm8, %%xmm10  \\n\\t\"\n//           \n//           \n//           \n//           \n// //           \"mulps %[ptmp1], %%xmm9  \\n\\t\"\n//           \n// //           \"addps %%xmm9, %%xmm11  \\n\\t\"\n// //           \"addps %%xmm13, %[ptmp2]  \\n\\t\"\n//           \n//           \"movaps %%xmm10,   (%[X],%[i],4) \\n\\t\"\n// //           \"movaps %%xmm11, 16(%[X],%[i],4) \\n\\t\"\n//           : \n//           : [X] \"r\" (X), [i] \"r\" (i), [A0] \"r\" (A0),\n//             [B] \"r\" (B),\n//             [ptmp1] \"x\" (ptmp1),\n//             [ptmp2] \"x\" (ptmp2)\n//           : \"%xmm8\", \"%xmm9\", \"%xmm10\", \"%xmm11\", \"%xmm12\", \"%xmm13\", \"%xmm15\");\n      }\n      asm(\"#end symv\");\n      for (int i=alignedEnd; i<N; i++) {\n        X[i] += t0 * A0[i] + t1 * A1[i];\n        t2 += A0[i] * B[i];\n        t3 += A1[i] * B[i];\n      }\n      \n      \n      X[j]   += t2 + internal::predux(ptmp2);\n      X[j+1] += t3 + internal::predux(ptmp3);\n    }\n    for (int j=bound;j<N;j++)\n    {\n      register real* __restrict__ A0 = A + j*N;\n      \n      real t1 = B[j];\n      real t2 = 0;\n      X[j] += t1 * A0[j];\n      for (int i=j+1; i<N; i+=PacketSize) {\n        X[i] += t1 * A0[i];\n        t2 += A0[i] * B[i];\n      }\n      X[j] += t2;\n    }\n    \n  }\n\n//   static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n//   {\n//     asm(\"#begin matrix_vector_product\");\n//     int AN = (N/PacketSize)*PacketSize;\n//     int ANP = (AN/(2*PacketSize))*2*PacketSize;\n//     int bound = (N/4)*4;\n//     for (int i=0;i<N;i++)\n//       X[i] = 0;\n//\n//     for (int i=0;i<bound;i+=4)\n//     {\n//       real tmp0 = B[i];\n//       Packet ptmp0 = internal::pset1(tmp0);\n//       real tmp1 = B[i+1];\n//       Packet ptmp1 = internal::pset1(tmp1);\n//       real tmp2 = B[i+2];\n//       Packet ptmp2 = internal::pset1(tmp2);\n//       real tmp3 = B[i+3];\n//       Packet ptmp3 = internal::pset1(tmp3);\n//       int iN0 = i*N;\n//       int iN1 = (i+1)*N;\n//       int iN2 = (i+2)*N;\n//       int iN3 = (i+3)*N;\n//       if (AN>0)\n//       {\n// //         int aligned0 = (iN0 % PacketSize);\n//         int aligned1 = (iN1 % PacketSize);\n//\n//         if (aligned1==0)\n//         {\n//           for (int j = 0;j<AN;j+=PacketSize)\n//           {\n//             internal::pstore(&X[j],\n//               internal::padd(internal::pload(&X[j]),\n//                 internal::padd(\n//                   internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+iN0])),internal::pmul(ptmp1,internal::pload(&A[j+iN1]))),\n//                   internal::padd(internal::pmul(ptmp2,internal::pload(&A[j+iN2])),internal::pmul(ptmp3,internal::pload(&A[j+iN3]))) )));\n//           }\n//         }\n//         else if (aligned1==2)\n//         {\n//           for (int j = 0;j<AN;j+=PacketSize)\n//           {\n//             internal::pstore(&X[j],\n//               internal::padd(internal::pload(&X[j]),\n//                 internal::padd(\n//                   internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+iN0])),internal::pmul(ptmp1,internal::ploadu(&A[j+iN1]))),\n//                   internal::padd(internal::pmul(ptmp2,internal::pload(&A[j+iN2])),internal::pmul(ptmp3,internal::ploadu(&A[j+iN3]))) )));\n//           }\n//         }\n//         else\n//         {\n//           for (int j = 0;j<ANP;j+=2*PacketSize)\n//           {\n//             internal::pstore(&X[j],\n//               internal::padd(internal::pload(&X[j]),\n//                 internal::padd(\n//                   internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+iN0])),internal::pmul(ptmp1,internal::ploadu(&A[j+iN1]))),\n//                   internal::padd(internal::pmul(ptmp2,internal::ploadu(&A[j+iN2])),internal::pmul(ptmp3,internal::ploadu(&A[j+iN3]))) )));\n//\n//             internal::pstore(&X[j+PacketSize],\n//               internal::padd(internal::pload(&X[j+PacketSize]),\n//                 internal::padd(\n//                   internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+PacketSize+iN0])),internal::pmul(ptmp1,internal::ploadu(&A[j+PacketSize+iN1]))),\n//                   internal::padd(internal::pmul(ptmp2,internal::ploadu(&A[j+PacketSize+iN2])),internal::pmul(ptmp3,internal::ploadu(&A[j+PacketSize+iN3]))) )));\n//\n// //             internal::pstore(&X[j+2*PacketSize],\n// //               internal::padd(internal::pload(&X[j+2*PacketSize]),\n// //                 internal::padd(\n// //                   internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+2*PacketSize+iN0])),internal::pmul(ptmp1,internal::ploadu(&A[j+2*PacketSize+iN1]))),\n// //                   internal::padd(internal::pmul(ptmp2,internal::ploadu(&A[j+2*PacketSize+iN2])),internal::pmul(ptmp3,internal::ploadu(&A[j+2*PacketSize+iN3]))) )));\n// //\n// //             internal::pstore(&X[j+3*PacketSize],\n// //               internal::padd(internal::pload(&X[j+3*PacketSize]),\n// //                 internal::padd(\n// //                   internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+3*PacketSize+iN0])),internal::pmul(ptmp1,internal::ploadu(&A[j+3*PacketSize+iN1]))),\n// //                   internal::padd(internal::pmul(ptmp2,internal::ploadu(&A[j+3*PacketSize+iN2])),internal::pmul(ptmp3,internal::ploadu(&A[j+3*PacketSize+iN3]))) )));\n//\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             internal::pstore(&X[j],\n//               internal::padd(internal::pload(&X[j]),\n//                 internal::padd(\n//                   internal::padd(internal::pmul(ptmp0,internal::ploadu(&A[j+iN0])),internal::pmul(ptmp1,internal::ploadu(&A[j+iN1]))),\n//                   internal::padd(internal::pmul(ptmp2,internal::ploadu(&A[j+iN2])),internal::pmul(ptmp3,internal::ploadu(&A[j+iN3]))) )));\n//         }\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         X[j] += tmp0 * A[j+iN0] + tmp1 * A[j+iN1] + tmp2 * A[j+iN2] + tmp3 * A[j+iN3];\n//     }\n//     for (int i=bound;i<N;i++)\n//     {\n//       real tmp0 = B[i];\n//       Packet ptmp0 = internal::pset1(tmp0);\n//       int iN0 = i*N;\n//       if (AN>0)\n//       {\n//         bool aligned0 = (iN0 % PacketSize) == 0;\n//         if (aligned0)\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             internal::pstore(&X[j], internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+iN0])),internal::pload(&X[j])));\n//         else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             internal::pstore(&X[j], internal::padd(internal::pmul(ptmp0,internal::ploadu(&A[j+iN0])),internal::pload(&X[j])));\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         X[j] += tmp0 * A[j+iN0];\n//     }\n//     asm(\"#end matrix_vector_product\");\n//   }\n\n//   static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n//   {\n//     asm(\"#begin matrix_vector_product\");\n//     int AN = (N/PacketSize)*PacketSize;\n//     for (int i=0;i<N;i++)\n//       X[i] = 0;\n//\n//     for (int i=0;i<N;i+=2)\n//     {\n//       real tmp0 = B[i];\n//       Packet ptmp0 = internal::pset1(tmp0);\n//       real tmp1 = B[i+1];\n//       Packet ptmp1 = internal::pset1(tmp1);\n//       int iN0 = i*N;\n//       int iN1 = (i+1)*N;\n//       if (AN>0)\n//       {\n//         bool aligned0 = (iN0 % PacketSize) == 0;\n//         bool aligned1 = (iN1 % PacketSize) == 0;\n//\n//         if (aligned0 && aligned1)\n//         {\n//           for (int j = 0;j<AN;j+=PacketSize)\n//           {\n//             internal::pstore(&X[j],\n//               internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+iN0])),\n//               internal::padd(internal::pmul(ptmp1,internal::pload(&A[j+iN1])),internal::pload(&X[j]))));\n//           }\n//         }\n//         else if (aligned0)\n//         {\n//           for (int j = 0;j<AN;j+=PacketSize)\n//           {\n//             internal::pstore(&X[j],\n//               internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+iN0])),\n//               internal::padd(internal::pmul(ptmp1,internal::ploadu(&A[j+iN1])),internal::pload(&X[j]))));\n//           }\n//         }\n//         else if (aligned1)\n//         {\n//           for (int j = 0;j<AN;j+=PacketSize)\n//           {\n//             internal::pstore(&X[j],\n//               internal::padd(internal::pmul(ptmp0,internal::ploadu(&A[j+iN0])),\n//               internal::padd(internal::pmul(ptmp1,internal::pload(&A[j+iN1])),internal::pload(&X[j]))));\n//           }\n//         }\n//         else\n//         {\n//           int ANP = (AN/(4*PacketSize))*4*PacketSize;\n//           for (int j = 0;j<ANP;j+=4*PacketSize)\n//           {\n//             internal::pstore(&X[j],\n//               internal::padd(internal::pmul(ptmp0,internal::ploadu(&A[j+iN0])),\n//               internal::padd(internal::pmul(ptmp1,internal::ploadu(&A[j+iN1])),internal::pload(&X[j]))));\n//\n//             internal::pstore(&X[j+PacketSize],\n//               internal::padd(internal::pmul(ptmp0,internal::ploadu(&A[j+PacketSize+iN0])),\n//               internal::padd(internal::pmul(ptmp1,internal::ploadu(&A[j+PacketSize+iN1])),internal::pload(&X[j+PacketSize]))));\n//\n//             internal::pstore(&X[j+2*PacketSize],\n//               internal::padd(internal::pmul(ptmp0,internal::ploadu(&A[j+2*PacketSize+iN0])),\n//               internal::padd(internal::pmul(ptmp1,internal::ploadu(&A[j+2*PacketSize+iN1])),internal::pload(&X[j+2*PacketSize]))));\n//\n//             internal::pstore(&X[j+3*PacketSize],\n//               internal::padd(internal::pmul(ptmp0,internal::ploadu(&A[j+3*PacketSize+iN0])),\n//               internal::padd(internal::pmul(ptmp1,internal::ploadu(&A[j+3*PacketSize+iN1])),internal::pload(&X[j+3*PacketSize]))));\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             internal::pstore(&X[j],\n//               internal::padd(internal::pmul(ptmp0,internal::ploadu(&A[j+iN0])),\n//               internal::padd(internal::pmul(ptmp1,internal::ploadu(&A[j+iN1])),internal::pload(&X[j]))));\n//         }\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         X[j] += tmp0 * A[j+iN0] + tmp1 * A[j+iN1];\n//     }\n//     int remaining = (N/2)*2;\n//     for (int i=remaining;i<N;i++)\n//     {\n//       real tmp0 = B[i];\n//       Packet ptmp0 = internal::pset1(tmp0);\n//       int iN0 = i*N;\n//       if (AN>0)\n//       {\n//         bool aligned0 = (iN0 % PacketSize) == 0;\n//         if (aligned0)\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             internal::pstore(&X[j], internal::padd(internal::pmul(ptmp0,internal::pload(&A[j+iN0])),internal::pload(&X[j])));\n//         else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             internal::pstore(&X[j], internal::padd(internal::pmul(ptmp0,internal::ploadu(&A[j+iN0])),internal::pload(&X[j])));\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         X[j] += tmp0 * A[j+iN0];\n//     }\n//     asm(\"#end matrix_vector_product\");\n//   }\n\n//   static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n//   {\n//     asm(\"#begin matrix_vector_product\");\n//     int AN = (N/PacketSize)*PacketSize;\n//     for (int i=0;i<N;i++)\n//       X[i] = 0;\n//     for (int i=0;i<N;i++)\n//     {\n//       real tmp = B[i];\n//       Packet ptmp = internal::pset1(tmp);\n//       int iN = i*N;\n//       if (AN>0)\n//       {\n//         bool aligned = (iN % PacketSize) == 0;\n//         if (aligned)\n//         {\n//           #ifdef PEELING\n//           Packet A0, A1, A2, X0, X1, X2;\n//           int ANP = (AN/(8*PacketSize))*8*PacketSize;\n//           for (int j = 0;j<ANP;j+=PacketSize*8)\n//           {\n//             A0 = internal::pload(&A[j+iN]);\n//             X0 = internal::pload(&X[j]);\n//             A1 = internal::pload(&A[j+PacketSize+iN]);\n//             X1 = internal::pload(&X[j+PacketSize]);\n//             A2 = internal::pload(&A[j+2*PacketSize+iN]);\n//             X2 = internal::pload(&X[j+2*PacketSize]);\n//             internal::pstore(&X[j], internal::padd(X0, internal::pmul(ptmp,A0)));\n//             A0 = internal::pload(&A[j+3*PacketSize+iN]);\n//             X0 = internal::pload(&X[j+3*PacketSize]);\n//             internal::pstore(&X[j+PacketSize], internal::padd(internal::pload(&X1), internal::pmul(ptmp,A1)));\n//             A1 = internal::pload(&A[j+4*PacketSize+iN]);\n//             X1 = internal::pload(&X[j+4*PacketSize]);\n//             internal::pstore(&X[j+2*PacketSize], internal::padd(internal::pload(&X2), internal::pmul(ptmp,A2)));\n//             A2 = internal::pload(&A[j+5*PacketSize+iN]);\n//             X2 = internal::pload(&X[j+5*PacketSize]);\n//             internal::pstore(&X[j+3*PacketSize], internal::padd(internal::pload(&X0), internal::pmul(ptmp,A0)));\n//             A0 = internal::pload(&A[j+6*PacketSize+iN]);\n//             X0 = internal::pload(&X[j+6*PacketSize]);\n//             internal::pstore(&X[j+4*PacketSize], internal::padd(internal::pload(&X1), internal::pmul(ptmp,A1)));\n//             A1 = internal::pload(&A[j+7*PacketSize+iN]);\n//             X1 = internal::pload(&X[j+7*PacketSize]);\n//             internal::pstore(&X[j+5*PacketSize], internal::padd(internal::pload(&X2), internal::pmul(ptmp,A2)));\n//             internal::pstore(&X[j+6*PacketSize], internal::padd(internal::pload(&X0), internal::pmul(ptmp,A0)));\n//             internal::pstore(&X[j+7*PacketSize], internal::padd(internal::pload(&X1), internal::pmul(ptmp,A1)));\n// //\n// //             internal::pstore(&X[j], internal::padd(internal::pload(&X[j]), internal::pmul(ptmp,internal::pload(&A[j+iN]))));\n// //             internal::pstore(&X[j+PacketSize], internal::padd(internal::pload(&X[j+PacketSize]), internal::pmul(ptmp,internal::pload(&A[j+PacketSize+iN]))));\n// //             internal::pstore(&X[j+2*PacketSize], internal::padd(internal::pload(&X[j+2*PacketSize]), internal::pmul(ptmp,internal::pload(&A[j+2*PacketSize+iN]))));\n// //             internal::pstore(&X[j+3*PacketSize], internal::padd(internal::pload(&X[j+3*PacketSize]), internal::pmul(ptmp,internal::pload(&A[j+3*PacketSize+iN]))));\n// //             internal::pstore(&X[j+4*PacketSize], internal::padd(internal::pload(&X[j+4*PacketSize]), internal::pmul(ptmp,internal::pload(&A[j+4*PacketSize+iN]))));\n// //             internal::pstore(&X[j+5*PacketSize], internal::padd(internal::pload(&X[j+5*PacketSize]), internal::pmul(ptmp,internal::pload(&A[j+5*PacketSize+iN]))));\n// //             internal::pstore(&X[j+6*PacketSize], internal::padd(internal::pload(&X[j+6*PacketSize]), internal::pmul(ptmp,internal::pload(&A[j+6*PacketSize+iN]))));\n// //             internal::pstore(&X[j+7*PacketSize], internal::padd(internal::pload(&X[j+7*PacketSize]), internal::pmul(ptmp,internal::pload(&A[j+7*PacketSize+iN]))));\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             internal::pstore(&X[j], internal::padd(internal::pload(&X[j]), internal::pmul(ptmp,internal::pload(&A[j+iN]))));\n//           #else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             internal::pstore(&X[j], internal::padd(internal::pload(&X[j]), internal::pmul(ptmp,internal::pload(&A[j+iN]))));\n//           #endif\n//         }\n//         else\n//         {\n//           #ifdef PEELING\n//           int ANP = (AN/(8*PacketSize))*8*PacketSize;\n//           for (int j = 0;j<ANP;j+=PacketSize*8)\n//           {\n//             internal::pstore(&X[j], internal::padd(internal::pload(&X[j]), internal::pmul(ptmp,internal::ploadu(&A[j+iN]))));\n//             internal::pstore(&X[j+PacketSize], internal::padd(internal::pload(&X[j+PacketSize]), internal::pmul(ptmp,internal::ploadu(&A[j+PacketSize+iN]))));\n//             internal::pstore(&X[j+2*PacketSize], internal::padd(internal::pload(&X[j+2*PacketSize]), internal::pmul(ptmp,internal::ploadu(&A[j+2*PacketSize+iN]))));\n//             internal::pstore(&X[j+3*PacketSize], internal::padd(internal::pload(&X[j+3*PacketSize]), internal::pmul(ptmp,internal::ploadu(&A[j+3*PacketSize+iN]))));\n//             internal::pstore(&X[j+4*PacketSize], internal::padd(internal::pload(&X[j+4*PacketSize]), internal::pmul(ptmp,internal::ploadu(&A[j+4*PacketSize+iN]))));\n//             internal::pstore(&X[j+5*PacketSize], internal::padd(internal::pload(&X[j+5*PacketSize]), internal::pmul(ptmp,internal::ploadu(&A[j+5*PacketSize+iN]))));\n//             internal::pstore(&X[j+6*PacketSize], internal::padd(internal::pload(&X[j+6*PacketSize]), internal::pmul(ptmp,internal::ploadu(&A[j+6*PacketSize+iN]))));\n//             internal::pstore(&X[j+7*PacketSize], internal::padd(internal::pload(&X[j+7*PacketSize]), internal::pmul(ptmp,internal::ploadu(&A[j+7*PacketSize+iN]))));\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             internal::pstore(&X[j], internal::padd(internal::pload(&X[j]), internal::pmul(ptmp,internal::ploadu(&A[j+iN]))));\n//           #else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             internal::pstore(&X[j], internal::padd(internal::pload(&X[j]), internal::pmul(ptmp,internal::ploadu(&A[j+iN]))));\n//           #endif\n//         }\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         X[j] += tmp * A[j+iN];\n//     }\n//     asm(\"#end matrix_vector_product\");\n//   }\n\n    static inline void atv_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n  {\n    int AN = (N/PacketSize)*PacketSize;\n    int bound = (N/4)*4;\n    for (int i=0;i<bound;i+=4)\n    {\n      real tmp0 = 0;\n      Packet ptmp0 = internal::pset1(real(0));\n      real tmp1 = 0;\n      Packet ptmp1 = internal::pset1(real(0));\n      real tmp2 = 0;\n      Packet ptmp2 = internal::pset1(real(0));\n      real tmp3 = 0;\n      Packet ptmp3 = internal::pset1(real(0));\n      int iN0 = i*N;\n      int iN1 = (i+1)*N;\n      int iN2 = (i+2)*N;\n      int iN3 = (i+3)*N;\n      if (AN>0)\n      {\n        int align1 = (iN1 % PacketSize);\n        if (align1==0)\n        {\n          for (int j = 0;j<AN;j+=PacketSize)\n          {\n            Packet b = internal::pload(&B[j]);\n            ptmp0 = internal::padd(ptmp0, internal::pmul(b, internal::pload(&A[j+iN0])));\n            ptmp1 = internal::padd(ptmp1, internal::pmul(b, internal::pload(&A[j+iN1])));\n            ptmp2 = internal::padd(ptmp2, internal::pmul(b, internal::pload(&A[j+iN2])));\n            ptmp3 = internal::padd(ptmp3, internal::pmul(b, internal::pload(&A[j+iN3])));\n          }\n        }\n        else if (align1==2)\n        {\n          for (int j = 0;j<AN;j+=PacketSize)\n          {\n            Packet b = internal::pload(&B[j]);\n            ptmp0 = internal::padd(ptmp0, internal::pmul(b, internal::pload(&A[j+iN0])));\n            ptmp1 = internal::padd(ptmp1, internal::pmul(b, internal::ploadu(&A[j+iN1])));\n            ptmp2 = internal::padd(ptmp2, internal::pmul(b, internal::pload(&A[j+iN2])));\n            ptmp3 = internal::padd(ptmp3, internal::pmul(b, internal::ploadu(&A[j+iN3])));\n          }\n        }\n        else\n        {\n          for (int j = 0;j<AN;j+=PacketSize)\n          {\n            Packet b = internal::pload(&B[j]);\n            ptmp0 = internal::padd(ptmp0, internal::pmul(b, internal::pload(&A[j+iN0])));\n            ptmp1 = internal::padd(ptmp1, internal::pmul(b, internal::ploadu(&A[j+iN1])));\n            ptmp2 = internal::padd(ptmp2, internal::pmul(b, internal::ploadu(&A[j+iN2])));\n            ptmp3 = internal::padd(ptmp3, internal::pmul(b, internal::ploadu(&A[j+iN3])));\n          }\n        }\n        tmp0 = internal::predux(ptmp0);\n        tmp1 = internal::predux(ptmp1);\n        tmp2 = internal::predux(ptmp2);\n        tmp3 = internal::predux(ptmp3);\n      }\n      // process remaining scalars\n      for (int j=AN;j<N;j++)\n      {\n        tmp0 += B[j] * A[j+iN0];\n        tmp1 += B[j] * A[j+iN1];\n        tmp2 += B[j] * A[j+iN2];\n        tmp3 += B[j] * A[j+iN3];\n      }\n      X[i+0] = tmp0;\n      X[i+1] = tmp1;\n      X[i+2] = tmp2;\n      X[i+3] = tmp3;\n    }\n\n    for (int i=bound;i<N;i++)\n    {\n      real tmp0 = 0;\n      Packet ptmp0 = internal::pset1(real(0));\n      int iN0 = i*N;\n      if (AN>0)\n      {\n        if (iN0 % PacketSize==0)\n          for (int j = 0;j<AN;j+=PacketSize)\n            ptmp0 = internal::padd(ptmp0, internal::pmul(internal::pload(&B[j]), internal::pload(&A[j+iN0])));\n        else\n          for (int j = 0;j<AN;j+=PacketSize)\n            ptmp0 = internal::padd(ptmp0, internal::pmul(internal::pload(&B[j]), internal::ploadu(&A[j+iN0])));\n        tmp0 = internal::predux(ptmp0);\n      }\n      // process remaining scalars\n      for (int j=AN;j<N;j++)\n        tmp0 += B[j] * A[j+iN0];\n      X[i+0] = tmp0;\n    }\n  }\n\n//   static inline void atv_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N)\n//   {\n//     int AN = (N/PacketSize)*PacketSize;\n//     for (int i=0;i<N;i++)\n//       X[i] = 0;\n//     for (int i=0;i<N;i++)\n//     {\n//       real tmp = 0;\n//       Packet ptmp = internal::pset1(real(0));\n//       int iN = i*N;\n//       if (AN>0)\n//       {\n//         bool aligned = (iN % PacketSize) == 0;\n//         if (aligned)\n//         {\n//           #ifdef PEELING\n//           int ANP = (AN/(8*PacketSize))*8*PacketSize;\n//           for (int j = 0;j<ANP;j+=PacketSize*8)\n//           {\n//             ptmp =\n//               internal::padd(internal::pmul(internal::pload(&B[j]), internal::pload(&A[j+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+PacketSize]), internal::pload(&A[j+PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+2*PacketSize]), internal::pload(&A[j+2*PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+3*PacketSize]), internal::pload(&A[j+3*PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+4*PacketSize]), internal::pload(&A[j+4*PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+5*PacketSize]), internal::pload(&A[j+5*PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+6*PacketSize]), internal::pload(&A[j+6*PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+7*PacketSize]), internal::pload(&A[j+7*PacketSize+iN])),\n//               ptmp))))))));\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             ptmp = internal::padd(ptmp, internal::pmul(internal::pload(&B[j]), internal::pload(&A[j+iN])));\n//           #else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             ptmp = internal::padd(ptmp, internal::pmul(internal::pload(&B[j]), internal::pload(&A[j+iN])));\n//           #endif\n//         }\n//         else\n//         {\n//           #ifdef PEELING\n//           int ANP = (AN/(8*PacketSize))*8*PacketSize;\n//           for (int j = 0;j<ANP;j+=PacketSize*8)\n//           {\n//             ptmp =\n//               internal::padd(internal::pmul(internal::pload(&B[j]), internal::ploadu(&A[j+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+PacketSize]), internal::ploadu(&A[j+PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+2*PacketSize]), internal::ploadu(&A[j+2*PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+3*PacketSize]), internal::ploadu(&A[j+3*PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+4*PacketSize]), internal::ploadu(&A[j+4*PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+5*PacketSize]), internal::ploadu(&A[j+5*PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+6*PacketSize]), internal::ploadu(&A[j+6*PacketSize+iN])),\n//               internal::padd(internal::pmul(internal::pload(&B[j+7*PacketSize]), internal::ploadu(&A[j+7*PacketSize+iN])),\n//               ptmp))))))));\n//           }\n//           for (int j = ANP;j<AN;j+=PacketSize)\n//             ptmp = internal::padd(ptmp, internal::pmul(internal::pload(&B[j]), internal::ploadu(&A[j+iN])));\n//           #else\n//           for (int j = 0;j<AN;j+=PacketSize)\n//             ptmp = internal::padd(ptmp, internal::pmul(internal::pload(&B[j]), internal::ploadu(&A[j+iN])));\n//           #endif\n//         }\n//         tmp = internal::predux(ptmp);\n//       }\n//       // process remaining scalars\n//       for (int j=AN;j<N;j++)\n//         tmp += B[j] * A[j+iN];\n//       X[i] = tmp;\n//     }\n//   }\n\n  static inline void axpy(real coef, const gene_vector & X, gene_vector & Y, int N){\n    int AN = (N/PacketSize)*PacketSize;\n    if (AN>0)\n    {\n      Packet pcoef = internal::pset1(coef);\n      #ifdef PEELING\n      const int peelSize = 3;\n      int ANP = (AN/(peelSize*PacketSize))*peelSize*PacketSize;\n      float* X1 = X + PacketSize;\n      float* Y1 = Y + PacketSize;\n      float* X2 = X + 2*PacketSize;\n      float* Y2 = Y + 2*PacketSize;\n      Packet x0,x1,x2,y0,y1,y2;\n      for (int j = 0;j<ANP;j+=PacketSize*peelSize)\n      {\n        x0 = internal::pload(X+j);\n        x1 = internal::pload(X1+j);\n        x2 = internal::pload(X2+j);\n\n        y0 = internal::pload(Y+j);\n        y1 = internal::pload(Y1+j);\n        y2 = internal::pload(Y2+j);\n\n        y0 = internal::pmadd(pcoef, x0, y0);\n        y1 = internal::pmadd(pcoef, x1, y1);\n        y2 = internal::pmadd(pcoef, x2, y2);\n\n        internal::pstore(Y+j,  y0);\n        internal::pstore(Y1+j, y1);\n        internal::pstore(Y2+j, y2);\n//         internal::pstore(&Y[j+2*PacketSize], internal::padd(internal::pload(&Y[j+2*PacketSize]), internal::pmul(pcoef,internal::pload(&X[j+2*PacketSize]))));\n//         internal::pstore(&Y[j+3*PacketSize], internal::padd(internal::pload(&Y[j+3*PacketSize]), internal::pmul(pcoef,internal::pload(&X[j+3*PacketSize]))));\n//         internal::pstore(&Y[j+4*PacketSize], internal::padd(internal::pload(&Y[j+4*PacketSize]), internal::pmul(pcoef,internal::pload(&X[j+4*PacketSize]))));\n//         internal::pstore(&Y[j+5*PacketSize], internal::padd(internal::pload(&Y[j+5*PacketSize]), internal::pmul(pcoef,internal::pload(&X[j+5*PacketSize]))));\n//         internal::pstore(&Y[j+6*PacketSize], internal::padd(internal::pload(&Y[j+6*PacketSize]), internal::pmul(pcoef,internal::pload(&X[j+6*PacketSize]))));\n//         internal::pstore(&Y[j+7*PacketSize], internal::padd(internal::pload(&Y[j+7*PacketSize]), internal::pmul(pcoef,internal::pload(&X[j+7*PacketSize]))));\n      }\n      for (int j = ANP;j<AN;j+=PacketSize)\n        internal::pstore(&Y[j], internal::padd(internal::pload(&Y[j]), internal::pmul(pcoef,internal::pload(&X[j]))));\n      #else\n      for (int j = 0;j<AN;j+=PacketSize)\n        internal::pstore(&Y[j], internal::padd(internal::pload(&Y[j]), internal::pmul(pcoef,internal::pload(&X[j]))));\n      #endif\n    }\n    // process remaining scalars\n    for (int i=AN;i<N;i++)\n      Y[i] += coef * X[i];\n  }\n\n\n};\n\n#endif\n", "meta": {"hexsha": "0bb4b64cad0aa7b19dd2e71288d9fc923d23f9fc", "size": 39315, "ext": "hh", "lang": "C++", "max_stars_repo_path": "extsrc/eigen-eigen-3.0.1/bench/btl/libs/hand_vec/hand_vec_interface.hh", "max_stars_repo_name": "MauroArgentino/RSXGL", "max_stars_repo_head_hexsha": "bd206e11894f309680f48740346c17efe49755ba", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-03-12T00:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T08:56:31.000Z", "max_issues_repo_path": "extsrc/eigen-eigen-3.0.1/bench/btl/libs/hand_vec/hand_vec_interface.hh", "max_issues_repo_name": "MauroArgentino/RSXGL", "max_issues_repo_head_hexsha": "bd206e11894f309680f48740346c17efe49755ba", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T19:02:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-27T14:15:04.000Z", "max_forks_repo_path": "extsrc/eigen-eigen-3.0.1/bench/btl/libs/hand_vec/hand_vec_interface.hh", "max_forks_repo_name": "MauroArgentino/RSXGL", "max_forks_repo_head_hexsha": "bd206e11894f309680f48740346c17efe49755ba", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-04T12:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:04:38.000Z", "avg_line_length": 44.3235625705, "max_line_length": 170, "alphanum_fraction": 0.5154012463, "num_tokens": 12858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.23608253366545204}}
{"text": "/*****************************************************************************\r\n *\r\n * This file is part of Mapnik (c++ mapping toolkit)\r\n *\r\n * Copyright (C) 2013 Artem Pavlenko\r\n *\r\n * This library is free software; you can redistribute it and/or\r\n * modify it under the terms of the GNU Lesser General Public\r\n * License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n *\r\n * This library is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\r\n * Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with this library; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\r\n */\r\n\r\n#ifndef MAPNIK_POLYGON_CLIPPER_HPP\r\n#define MAPNIK_POLYGON_CLIPPER_HPP\r\n\r\n// stl\r\n#include <iostream>\r\n#include <deque>\r\n\r\n// mapnik\r\n#include <mapnik/box2d.hpp>\r\n#include <mapnik/geometry.hpp>\r\n\r\n// boost\r\n#include <boost/foreach.hpp>\r\n#include <boost/tuple/tuple.hpp>\r\n#include <boost/geometry.hpp>\r\n#include <boost/geometry/geometries/point_xy.hpp>\r\n#include <boost/geometry/geometries/box.hpp>\r\n#include <boost/geometry/geometries/polygon.hpp>\r\n#include <boost/geometry/geometries/register/point.hpp>\r\n\r\nBOOST_GEOMETRY_REGISTER_POINT_2D(mapnik::coord2d, double, cs::cartesian, x, y)\r\n\r\n// register mapnik::box2d<double>\r\nnamespace boost { namespace geometry { namespace traits\r\n{\r\n\r\ntemplate<> struct tag<mapnik::box2d<double> > { typedef box_tag type; };\r\n\r\ntemplate<> struct point_type<mapnik::box2d<double> > { typedef mapnik::coord2d type; };\r\n\r\ntemplate <>\r\nstruct indexed_access<mapnik::box2d<double>, min_corner, 0>\r\n{\r\n    typedef coordinate_type<mapnik::coord2d>::type ct;\r\n    static inline ct get(mapnik::box2d<double> const& b) { return b.minx();}\r\n    static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_minx(value); }\r\n};\r\n\r\ntemplate <>\r\nstruct indexed_access<mapnik::box2d<double>, min_corner, 1>\r\n{\r\n    typedef coordinate_type<mapnik::coord2d>::type ct;\r\n    static inline ct get(mapnik::box2d<double> const& b) { return b.miny();}\r\n    static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_miny(value); }\r\n};\r\n\r\ntemplate <>\r\nstruct indexed_access<mapnik::box2d<double>, max_corner, 0>\r\n{\r\n    typedef coordinate_type<mapnik::coord2d>::type ct;\r\n    static inline ct get(mapnik::box2d<double> const& b) { return b.maxx();}\r\n    static inline void set(mapnik::box2d<double> &b, ct const& value) { b.set_maxx(value); }\r\n};\r\n\r\ntemplate <>\r\nstruct indexed_access<mapnik::box2d<double>, max_corner, 1>\r\n{\r\n    typedef coordinate_type<mapnik::coord2d>::type ct;\r\n    static inline ct get(mapnik::box2d<double> const& b) { return b.maxy();}\r\n    static inline void set(mapnik::box2d<double> &b , ct const& value) { b.set_maxy(value); }\r\n};\r\n\r\n}}}\r\n\r\nnamespace mapnik {\r\n\r\nusing namespace boost::geometry;\r\n\r\ntemplate <typename Geometry>\r\nstruct polygon_clipper\r\n{\r\n    typedef mapnik::coord2d point_2d;\r\n    typedef model::polygon<mapnik::coord2d> polygon_2d;\r\n    typedef std::deque<polygon_2d> polygon_list;\r\n\r\n    polygon_clipper(Geometry & geom)\r\n        : clip_box_(),\r\n          geom_(geom)\r\n    {\r\n\r\n    }\r\n\r\n    polygon_clipper( box2d<double> const& clip_box,Geometry & geom)\r\n        : clip_box_(clip_box),\r\n          geom_(geom)\r\n    {\r\n        init();\r\n    }\r\n\r\n    void set_clip_box(box2d<double> const& clip_box)\r\n    {\r\n        clip_box_ = clip_box;\r\n        init();\r\n    }\r\n\r\n    unsigned type() const\r\n    {\r\n        return geom_.type();\r\n    }\r\n\r\n    void rewind(unsigned path_id)\r\n    {\r\n        output_.rewind(path_id);\r\n    }\r\n\r\n    unsigned vertex (double * x, double * y)\r\n    {\r\n        return output_.vertex(x,y);\r\n    }\r\n\r\nprivate:\r\n\r\n    void init()\r\n    {\r\n        polygon_2d subject_poly;\r\n        double x,y;\r\n        double prev_x, prev_y;\r\n        geom_.rewind(0);\r\n        unsigned ring_count = 0;\r\n        while (true)\r\n        {\r\n            unsigned cmd = geom_.vertex(&x,&y);\r\n            if (cmd == SEG_END) break;\r\n            if (cmd == SEG_MOVETO)\r\n            {\r\n                prev_x = x;\r\n                prev_y = y;\r\n                if (ring_count == 0)\r\n                {\r\n                    append(subject_poly, make<point_2d>(x,y));\r\n                }\r\n                else\r\n                {\r\n                    subject_poly.inners().push_back(polygon_2d::inner_container_type::value_type());\r\n                    append(subject_poly.inners().back(),make<point_2d>(x,y));\r\n                }\r\n                ++ring_count;\r\n            }\r\n            else if (cmd == SEG_LINETO)\r\n            {\r\n                if (std::abs(x - prev_x) < 1e-12 && std::abs(y - prev_y) < 1e-12)\r\n                {\r\n                    std::cerr << std::setprecision(12) << \"coincident vertices:(\" << prev_x << \",\"\r\n                              <<  prev_y << \") , (\" << x << \",\" << y <<  \")\" << std::endl;\r\n                    continue;\r\n                }\r\n                prev_x = x;\r\n                prev_x = y;\r\n                if (ring_count == 1)\r\n                {\r\n                    append(subject_poly, make<point_2d>(x,y));\r\n                }\r\n                else\r\n                {\r\n                    append(subject_poly.inners().back(),make<point_2d>(x,y));\r\n                }\r\n            }\r\n        }\r\n\r\n        polygon_list clipped_polygons;\r\n\r\n        try\r\n        {\r\n            boost::geometry::intersection(clip_box_, subject_poly, clipped_polygons);\r\n        }\r\n        catch (boost::geometry::exception const& ex)\r\n        {\r\n            std::cerr << ex.what() << std::endl;\r\n        }\r\n\r\n        BOOST_FOREACH(polygon_2d const& poly, clipped_polygons)\r\n        {\r\n            bool move_to = true;\r\n            BOOST_FOREACH(point_2d const& c, boost::geometry::exterior_ring(poly))\r\n            {\r\n                if (move_to)\r\n                {\r\n                    move_to = false;\r\n                    output_.move_to(c.x,c.y);\r\n                }\r\n                else\r\n                {\r\n                    output_.line_to(c.x,c.y);\r\n                }\r\n            }\r\n            output_.close_path();\r\n            // interior rings\r\n            BOOST_FOREACH(polygon_2d::inner_container_type::value_type const& ring, boost::geometry::interior_rings(poly))\r\n            {\r\n                move_to = true;\r\n                BOOST_FOREACH(point_2d const& c, ring)\r\n                {\r\n                    if (move_to)\r\n                    {\r\n                        move_to = false;\r\n                        output_.move_to(c.x,c.y);\r\n                    }\r\n                    else\r\n                    {\r\n                        output_.line_to(c.x,c.y);\r\n                    }\r\n                }\r\n                output_.close_path();\r\n            }\r\n        }\r\n    }\r\n\r\n    box2d<double> clip_box_;\r\n    Geometry & geom_;\r\n    mapnik::geometry_type output_;\r\n\r\n};\r\n\r\n}\r\n\r\n#endif //MAPNIK_POLYGON_CLIPPER_HPP\r\n", "meta": {"hexsha": "629ef8914b3d6a32d1455dc9ed7ed86998ac95bf", "size": 7168, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/include/mapnik/polygon_clipper.hpp", "max_stars_repo_name": "Wujingli/OpenWebGlobeDataProcessing", "max_stars_repo_head_hexsha": "932eaa00c81fc0571122bc618ade010fa255735e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "external/include/mapnik/polygon_clipper.hpp", "max_issues_repo_name": "Wujingli/OpenWebGlobeDataProcessing", "max_issues_repo_head_hexsha": "932eaa00c81fc0571122bc618ade010fa255735e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "external/include/mapnik/polygon_clipper.hpp", "max_forks_repo_name": "Wujingli/OpenWebGlobeDataProcessing", "max_forks_repo_head_hexsha": "932eaa00c81fc0571122bc618ade010fa255735e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-06-08T15:59:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-06T08:13:01.000Z", "avg_line_length": 30.1176470588, "max_line_length": 123, "alphanum_fraction": 0.5358537946, "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.23608253366545198}}
{"text": "//=======================================================================\r\n// Copyright (c) 2018 Yi Ji\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n//=======================================================================\r\n\r\n#ifndef BOOST_GRAPH_MAXIMUM_WEIGHTED_MATCHING_HPP\r\n#define BOOST_GRAPH_MAXIMUM_WEIGHTED_MATCHING_HPP\r\n\r\n#include <algorithm> // for std::iter_swap\r\n#include <boost/shared_ptr.hpp>\r\n#include <boost/make_shared.hpp>\r\n#include <boost/graph/max_cardinality_matching.hpp>\r\n\r\nnamespace boost\r\n{\r\ntemplate < typename Graph, typename MateMap, typename VertexIndexMap >\r\ntypename property_traits<\r\n    typename property_map< Graph, edge_weight_t >::type >::value_type\r\nmatching_weight_sum(const Graph& g, MateMap mate, VertexIndexMap vm)\r\n{\r\n    typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator_t;\r\n    typedef\r\n        typename graph_traits< Graph >::vertex_descriptor vertex_descriptor_t;\r\n    typedef typename property_traits< typename property_map< Graph,\r\n        edge_weight_t >::type >::value_type edge_property_t;\r\n\r\n    edge_property_t weight_sum = 0;\r\n    vertex_iterator_t vi, vi_end;\r\n\r\n    for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n    {\r\n        vertex_descriptor_t v = *vi;\r\n        if (get(mate, v) != graph_traits< Graph >::null_vertex()\r\n            && get(vm, v) < get(vm, get(mate, v)))\r\n            weight_sum += get(edge_weight, g, edge(v, mate[v], g).first);\r\n    }\r\n    return weight_sum;\r\n}\r\n\r\ntemplate < typename Graph, typename MateMap >\r\ninline typename property_traits<\r\n    typename property_map< Graph, edge_weight_t >::type >::value_type\r\nmatching_weight_sum(const Graph& g, MateMap mate)\r\n{\r\n    return matching_weight_sum(g, mate, get(vertex_index, g));\r\n}\r\n\r\ntemplate < typename Graph, typename MateMap, typename VertexIndexMap >\r\nclass weighted_augmenting_path_finder\r\n{\r\npublic:\r\n    template < typename T > struct map_vertex_to_\r\n    {\r\n        typedef boost::iterator_property_map<\r\n            typename std::vector< T >::iterator, VertexIndexMap >\r\n            type;\r\n    };\r\n    typedef typename graph::detail::VERTEX_STATE vertex_state_t;\r\n    typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator_t;\r\n    typedef\r\n        typename graph_traits< Graph >::vertex_descriptor vertex_descriptor_t;\r\n    typedef typename std::vector< vertex_descriptor_t >::const_iterator\r\n        vertex_vec_iter_t;\r\n    typedef\r\n        typename graph_traits< Graph >::out_edge_iterator out_edge_iterator_t;\r\n    typedef typename graph_traits< Graph >::edge_descriptor edge_descriptor_t;\r\n    typedef typename graph_traits< Graph >::edge_iterator edge_iterator_t;\r\n    typedef typename property_traits< typename property_map< Graph,\r\n        edge_weight_t >::type >::value_type edge_property_t;\r\n    typedef std::deque< vertex_descriptor_t > vertex_list_t;\r\n    typedef std::vector< edge_descriptor_t > edge_list_t;\r\n    typedef typename map_vertex_to_< vertex_descriptor_t >::type\r\n        vertex_to_vertex_map_t;\r\n    typedef\r\n        typename map_vertex_to_< edge_property_t >::type vertex_to_weight_map_t;\r\n    typedef typename map_vertex_to_< bool >::type vertex_to_bool_map_t;\r\n    typedef typename map_vertex_to_< std::pair< vertex_descriptor_t,\r\n        vertex_descriptor_t > >::type vertex_to_pair_map_t;\r\n    typedef\r\n        typename map_vertex_to_< std::pair< edge_descriptor_t, bool > >::type\r\n            vertex_to_edge_map_t;\r\n    typedef typename map_vertex_to_< vertex_to_edge_map_t >::type\r\n        vertex_pair_to_edge_map_t;\r\n\r\n    class blossom\r\n    {\r\n    public:\r\n        typedef boost::shared_ptr< blossom > blossom_ptr_t;\r\n        std::vector< blossom_ptr_t > sub_blossoms;\r\n        edge_property_t dual_var;\r\n        blossom_ptr_t father;\r\n\r\n        blossom() : dual_var(0), father(blossom_ptr_t()) {}\r\n\r\n        // get the base vertex of a blossom by recursively getting\r\n        // its base sub-blossom, which is always the first one in\r\n        // sub_blossoms because of how we create and maintain blossoms\r\n        virtual vertex_descriptor_t get_base() const\r\n        {\r\n            const blossom* b = this;\r\n            while (!b->sub_blossoms.empty())\r\n                b = b->sub_blossoms[0].get();\r\n            return b->get_base();\r\n        }\r\n\r\n        // set a sub-blossom as a blossom's base by exchanging it\r\n        // with its first sub-blossom\r\n        void set_base(const blossom_ptr_t& sub)\r\n        {\r\n            for (blossom_iterator_t bi = sub_blossoms.begin();\r\n                 bi != sub_blossoms.end(); ++bi)\r\n            {\r\n                if (sub.get() == bi->get())\r\n                {\r\n                    std::iter_swap(sub_blossoms.begin(), bi);\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n\r\n        // get all vertices inside recursively\r\n        virtual std::vector< vertex_descriptor_t > vertices() const\r\n        {\r\n            std::vector< vertex_descriptor_t > all_vertices;\r\n            for (typename std::vector< blossom_ptr_t >::const_iterator bi\r\n                 = sub_blossoms.begin();\r\n                 bi != sub_blossoms.end(); ++bi)\r\n            {\r\n                std::vector< vertex_descriptor_t > some_vertices\r\n                    = (*bi)->vertices();\r\n                all_vertices.insert(all_vertices.end(), some_vertices.begin(),\r\n                    some_vertices.end());\r\n            }\r\n            return all_vertices;\r\n        }\r\n    };\r\n\r\n    // a trivial_blossom only has one vertex and no sub-blossom;\r\n    // for each vertex v, in_blossom[v] is the trivial_blossom that contains it\r\n    // directly\r\n    class trivial_blossom : public blossom\r\n    {\r\n    public:\r\n        trivial_blossom(vertex_descriptor_t v) : trivial_vertex(v) {}\r\n        virtual vertex_descriptor_t get_base() const { return trivial_vertex; }\r\n\r\n        virtual std::vector< vertex_descriptor_t > vertices() const\r\n        {\r\n            std::vector< vertex_descriptor_t > all_vertices;\r\n            all_vertices.push_back(trivial_vertex);\r\n            return all_vertices;\r\n        }\r\n\r\n    private:\r\n        vertex_descriptor_t trivial_vertex;\r\n    };\r\n\r\n    typedef boost::shared_ptr< blossom > blossom_ptr_t;\r\n    typedef typename std::vector< blossom_ptr_t >::iterator blossom_iterator_t;\r\n    typedef\r\n        typename map_vertex_to_< blossom_ptr_t >::type vertex_to_blossom_map_t;\r\n\r\n    weighted_augmenting_path_finder(\r\n        const Graph& arg_g, MateMap arg_mate, VertexIndexMap arg_vm)\r\n    : g(arg_g)\r\n    , vm(arg_vm)\r\n    , null_edge(std::pair< edge_descriptor_t, bool >(\r\n          num_edges(g) == 0 ? edge_descriptor_t() : *edges(g).first, false))\r\n    , mate_vector(num_vertices(g))\r\n    , label_S_vector(num_vertices(g), graph_traits< Graph >::null_vertex())\r\n    , label_T_vector(num_vertices(g), graph_traits< Graph >::null_vertex())\r\n    , outlet_vector(num_vertices(g), graph_traits< Graph >::null_vertex())\r\n    , tau_idx_vector(num_vertices(g), graph_traits< Graph >::null_vertex())\r\n    , dual_var_vector(std::vector< edge_property_t >(\r\n          num_vertices(g), std::numeric_limits< edge_property_t >::min()))\r\n    , pi_vector(std::vector< edge_property_t >(\r\n          num_vertices(g), std::numeric_limits< edge_property_t >::max()))\r\n    , gamma_vector(std::vector< edge_property_t >(\r\n          num_vertices(g), std::numeric_limits< edge_property_t >::max()))\r\n    , tau_vector(std::vector< edge_property_t >(\r\n          num_vertices(g), std::numeric_limits< edge_property_t >::max()))\r\n    , in_blossom_vector(num_vertices(g))\r\n    , old_label_vector(num_vertices(g))\r\n    , critical_edge_vectors(num_vertices(g),\r\n          std::vector< std::pair< edge_descriptor_t, bool > >(\r\n              num_vertices(g), null_edge))\r\n    ,\r\n\r\n        mate(mate_vector.begin(), vm)\r\n    , label_S(label_S_vector.begin(), vm)\r\n    , label_T(label_T_vector.begin(), vm)\r\n    , outlet(outlet_vector.begin(), vm)\r\n    , tau_idx(tau_idx_vector.begin(), vm)\r\n    , dual_var(dual_var_vector.begin(), vm)\r\n    , pi(pi_vector.begin(), vm)\r\n    , gamma(gamma_vector.begin(), vm)\r\n    , tau(tau_vector.begin(), vm)\r\n    , in_blossom(in_blossom_vector.begin(), vm)\r\n    , old_label(old_label_vector.begin(), vm)\r\n    {\r\n        vertex_iterator_t vi, vi_end;\r\n        edge_iterator_t ei, ei_end;\r\n\r\n        edge_property_t max_weight\r\n            = std::numeric_limits< edge_property_t >::min();\r\n        for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)\r\n            max_weight = std::max(max_weight, get(edge_weight, g, *ei));\r\n\r\n        typename std::vector<\r\n            std::vector< std::pair< edge_descriptor_t, bool > > >::iterator vei;\r\n\r\n        for (boost::tie(vi, vi_end) = vertices(g),\r\n                            vei = critical_edge_vectors.begin();\r\n             vi != vi_end; ++vi, ++vei)\r\n        {\r\n            vertex_descriptor_t u = *vi;\r\n            mate[u] = get(arg_mate, u);\r\n            dual_var[u] = 2 * max_weight;\r\n            in_blossom[u] = boost::make_shared< trivial_blossom >(u);\r\n            outlet[u] = u;\r\n            critical_edge_vector.push_back(\r\n                vertex_to_edge_map_t(vei->begin(), vm));\r\n        }\r\n\r\n        critical_edge\r\n            = vertex_pair_to_edge_map_t(critical_edge_vector.begin(), vm);\r\n\r\n        init();\r\n    }\r\n\r\n    // return the top blossom where v is contained inside\r\n    blossom_ptr_t in_top_blossom(vertex_descriptor_t v) const\r\n    {\r\n        blossom_ptr_t b = in_blossom[v];\r\n        while (b->father != blossom_ptr_t())\r\n            b = b->father;\r\n        return b;\r\n    }\r\n\r\n    // check if vertex v is in blossom b\r\n    bool is_in_blossom(blossom_ptr_t b, vertex_descriptor_t v) const\r\n    {\r\n        if (v == graph_traits< Graph >::null_vertex())\r\n            return false;\r\n        blossom_ptr_t vb = in_blossom[v]->father;\r\n        while (vb != blossom_ptr_t())\r\n        {\r\n            if (vb.get() == b.get())\r\n                return true;\r\n            vb = vb->father;\r\n        }\r\n        return false;\r\n    }\r\n\r\n    // return the base vertex of the top blossom that contains v\r\n    inline vertex_descriptor_t base_vertex(vertex_descriptor_t v) const\r\n    {\r\n        return in_top_blossom(v)->get_base();\r\n    }\r\n\r\n    // add an existed top blossom of base vertex v into new top\r\n    // blossom b as its sub-blossom\r\n    void add_sub_blossom(blossom_ptr_t b, vertex_descriptor_t v)\r\n    {\r\n        blossom_ptr_t sub = in_top_blossom(v);\r\n        sub->father = b;\r\n        b->sub_blossoms.push_back(sub);\r\n        if (sub->sub_blossoms.empty())\r\n            return;\r\n        for (blossom_iterator_t bi = top_blossoms.begin();\r\n             bi != top_blossoms.end(); ++bi)\r\n        {\r\n            if (bi->get() == sub.get())\r\n            {\r\n                top_blossoms.erase(bi);\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    // when a top blossom is created or its base vertex getting an S-label,\r\n    // add all edges incident to this blossom into even_edges\r\n    void bloom(blossom_ptr_t b)\r\n    {\r\n        std::vector< vertex_descriptor_t > vertices_of_b = b->vertices();\r\n        vertex_vec_iter_t vi;\r\n        for (vi = vertices_of_b.begin(); vi != vertices_of_b.end(); ++vi)\r\n        {\r\n            out_edge_iterator_t oei, oei_end;\r\n            for (boost::tie(oei, oei_end) = out_edges(*vi, g); oei != oei_end;\r\n                 ++oei)\r\n            {\r\n                if (target(*oei, g) != *vi && mate[*vi] != target(*oei, g))\r\n                    even_edges.push_back(*oei);\r\n            }\r\n        }\r\n    }\r\n\r\n    // assigning a T-label to a non S-vertex, along with outlet and updating pi\r\n    // value if updated pi[v] equals zero, augment the matching from its mate\r\n    // vertex\r\n    void put_T_label(vertex_descriptor_t v, vertex_descriptor_t T_label,\r\n        vertex_descriptor_t outlet_v, edge_property_t pi_v)\r\n    {\r\n        if (label_S[v] != graph_traits< Graph >::null_vertex())\r\n            return;\r\n\r\n        label_T[v] = T_label;\r\n        outlet[v] = outlet_v;\r\n        pi[v] = pi_v;\r\n\r\n        vertex_descriptor_t v_mate = mate[v];\r\n        if (pi[v] == 0)\r\n        {\r\n            label_T[v_mate] = graph_traits< Graph >::null_vertex();\r\n            label_S[v_mate] = v;\r\n            bloom(in_top_blossom(v_mate));\r\n        }\r\n    }\r\n\r\n    // get the missing T-label for a to-be-expanded base vertex\r\n    // the missing T-label is the last vertex of the path from outlet[v] to v\r\n    std::pair< vertex_descriptor_t, vertex_descriptor_t > missing_label(\r\n        vertex_descriptor_t b_base)\r\n    {\r\n        vertex_descriptor_t missing_outlet = outlet[b_base];\r\n\r\n        if (outlet[b_base] == b_base)\r\n            return std::make_pair(\r\n                graph_traits< Graph >::null_vertex(), missing_outlet);\r\n\r\n        vertex_iterator_t vi, vi_end;\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n            old_label[*vi] = std::make_pair(label_T[*vi], outlet[*vi]);\r\n\r\n        std::pair< vertex_descriptor_t, vertex_state_t > child(\r\n            outlet[b_base], graph::detail::V_EVEN);\r\n        blossom_ptr_t b = in_blossom[child.first];\r\n        for (; b->father->father != blossom_ptr_t(); b = b->father)\r\n            ;\r\n        child.first = b->get_base();\r\n\r\n        if (child.first == b_base)\r\n            return std::make_pair(\r\n                graph_traits< Graph >::null_vertex(), missing_outlet);\r\n\r\n        while (true)\r\n        {\r\n            std::pair< vertex_descriptor_t, vertex_state_t > child_parent\r\n                = parent(child, true);\r\n\r\n            for (b = in_blossom[child_parent.first];\r\n                 b->father->father != blossom_ptr_t(); b = b->father)\r\n                ;\r\n            missing_outlet = child_parent.first;\r\n            child_parent.first = b->get_base();\r\n\r\n            if (child_parent.first == b_base)\r\n                break;\r\n            else\r\n                child = child_parent;\r\n        }\r\n        return std::make_pair(child.first, missing_outlet);\r\n    }\r\n\r\n    // expand a top blossom, put all its non-trivial sub-blossoms into\r\n    // top_blossoms\r\n    blossom_iterator_t expand_blossom(\r\n        blossom_iterator_t bi, std::vector< blossom_ptr_t >& new_ones)\r\n    {\r\n        blossom_ptr_t b = *bi;\r\n        for (blossom_iterator_t i = b->sub_blossoms.begin();\r\n             i != b->sub_blossoms.end(); ++i)\r\n        {\r\n            blossom_ptr_t sub_blossom = *i;\r\n            vertex_descriptor_t sub_base = sub_blossom->get_base();\r\n            label_S[sub_base] = label_T[sub_base]\r\n                = graph_traits< Graph >::null_vertex();\r\n            outlet[sub_base] = sub_base;\r\n            sub_blossom->father = blossom_ptr_t();\r\n            // new top blossoms cannot be pushed back into top_blossoms\r\n            // immediately, because push_back() may cause reallocation and then\r\n            // invalid iterators\r\n            if (!sub_blossom->sub_blossoms.empty())\r\n                new_ones.push_back(sub_blossom);\r\n        }\r\n        return top_blossoms.erase(bi);\r\n    }\r\n\r\n    // when expanding a T-blossom with base v, it requires more operations:\r\n    // supply the missing T-labels for new base vertices by picking the minimum\r\n    // tau from vertices of each corresponding new top-blossoms; when label_T[v]\r\n    // is null or we have a smaller tau from missing_label(v), replace T-label\r\n    // and outlet of v (but don't bloom v)\r\n    blossom_iterator_t expand_T_blossom(\r\n        blossom_iterator_t bi, std::vector< blossom_ptr_t >& new_ones)\r\n    {\r\n        blossom_ptr_t b = *bi;\r\n\r\n        vertex_descriptor_t b_base = b->get_base();\r\n        std::pair< vertex_descriptor_t, vertex_descriptor_t > T_and_outlet\r\n            = missing_label(b_base);\r\n\r\n        blossom_iterator_t next_bi = expand_blossom(bi, new_ones);\r\n\r\n        for (blossom_iterator_t i = b->sub_blossoms.begin();\r\n             i != b->sub_blossoms.end(); ++i)\r\n        {\r\n            blossom_ptr_t sub_blossom = *i;\r\n            vertex_descriptor_t sub_base = sub_blossom->get_base();\r\n            vertex_descriptor_t min_tau_v\r\n                = graph_traits< Graph >::null_vertex();\r\n            edge_property_t min_tau\r\n                = std::numeric_limits< edge_property_t >::max();\r\n\r\n            std::vector< vertex_descriptor_t > sub_vertices\r\n                = sub_blossom->vertices();\r\n            for (vertex_vec_iter_t v = sub_vertices.begin();\r\n                 v != sub_vertices.end(); ++v)\r\n            {\r\n                if (tau[*v] < min_tau)\r\n                {\r\n                    min_tau = tau[*v];\r\n                    min_tau_v = *v;\r\n                }\r\n            }\r\n\r\n            if (min_tau < std::numeric_limits< edge_property_t >::max())\r\n                put_T_label(\r\n                    sub_base, tau_idx[min_tau_v], min_tau_v, tau[min_tau_v]);\r\n        }\r\n\r\n        if (label_T[b_base] == graph_traits< Graph >::null_vertex()\r\n            || tau[old_label[b_base].second] < pi[b_base])\r\n            boost::tie(label_T[b_base], outlet[b_base]) = T_and_outlet;\r\n\r\n        return next_bi;\r\n    }\r\n\r\n    // when vertices v and w are matched to each other by augmenting,\r\n    // we must set v/w as base vertex of any blossom who contains v/w and\r\n    // is a sub-blossom of their lowest (smallest) common blossom\r\n    void adjust_blossom(vertex_descriptor_t v, vertex_descriptor_t w)\r\n    {\r\n        blossom_ptr_t vb = in_blossom[v], wb = in_blossom[w],\r\n                      lowest_common_blossom;\r\n        std::vector< blossom_ptr_t > v_ancestors, w_ancestors;\r\n\r\n        while (vb->father != blossom_ptr_t())\r\n        {\r\n            v_ancestors.push_back(vb->father);\r\n            vb = vb->father;\r\n        }\r\n        while (wb->father != blossom_ptr_t())\r\n        {\r\n            w_ancestors.push_back(wb->father);\r\n            wb = wb->father;\r\n        }\r\n\r\n        typename std::vector< blossom_ptr_t >::reverse_iterator i, j;\r\n        i = v_ancestors.rbegin();\r\n        j = w_ancestors.rbegin();\r\n        while (i != v_ancestors.rend() && j != w_ancestors.rend()\r\n            && i->get() == j->get())\r\n        {\r\n            lowest_common_blossom = *i;\r\n            ++i;\r\n            ++j;\r\n        }\r\n\r\n        vb = in_blossom[v];\r\n        wb = in_blossom[w];\r\n        while (vb->father != lowest_common_blossom)\r\n        {\r\n            vb->father->set_base(vb);\r\n            vb = vb->father;\r\n        }\r\n        while (wb->father != lowest_common_blossom)\r\n        {\r\n            wb->father->set_base(wb);\r\n            wb = wb->father;\r\n        }\r\n    }\r\n\r\n    // every edge weight is multiplied by 4 to ensure integer weights\r\n    // throughout the algorithm if all input weights are integers\r\n    inline edge_property_t slack(const edge_descriptor_t& e) const\r\n    {\r\n        vertex_descriptor_t v, w;\r\n        v = source(e, g);\r\n        w = target(e, g);\r\n        return dual_var[v] + dual_var[w] - 4 * get(edge_weight, g, e);\r\n    }\r\n\r\n    // backtrace one step on vertex v along the augmenting path\r\n    // by its labels and its vertex state;\r\n    // boolean parameter \"use_old\" means whether we are updating labels,\r\n    // if we are, then we use old labels to backtrace and also we\r\n    // don't jump to its base vertex when we reach an odd vertex\r\n    std::pair< vertex_descriptor_t, vertex_state_t > parent(\r\n        std::pair< vertex_descriptor_t, vertex_state_t > v,\r\n        bool use_old = false) const\r\n    {\r\n        if (v.second == graph::detail::V_EVEN)\r\n        {\r\n            // a paranoid check: label_S shoule be the same as mate in\r\n            // backtracing\r\n            if (label_S[v.first] == graph_traits< Graph >::null_vertex())\r\n                label_S[v.first] = mate[v.first];\r\n            return std::make_pair(label_S[v.first], graph::detail::V_ODD);\r\n        }\r\n        else if (v.second == graph::detail::V_ODD)\r\n        {\r\n            vertex_descriptor_t w = use_old ? old_label[v.first].first\r\n                                            : base_vertex(label_T[v.first]);\r\n            return std::make_pair(w, graph::detail::V_EVEN);\r\n        }\r\n        return std::make_pair(v.first, graph::detail::V_UNREACHED);\r\n    }\r\n\r\n    // backtrace from vertices v and w to their free (unmatched) ancesters,\r\n    // return the nearest common ancestor (null_vertex if none) of v and w\r\n    vertex_descriptor_t nearest_common_ancestor(vertex_descriptor_t v,\r\n        vertex_descriptor_t w, vertex_descriptor_t& v_free_ancestor,\r\n        vertex_descriptor_t& w_free_ancestor) const\r\n    {\r\n        std::pair< vertex_descriptor_t, vertex_state_t > v_up(\r\n            v, graph::detail::V_EVEN);\r\n        std::pair< vertex_descriptor_t, vertex_state_t > w_up(\r\n            w, graph::detail::V_EVEN);\r\n        vertex_descriptor_t nca;\r\n        nca = w_free_ancestor = v_free_ancestor\r\n            = graph_traits< Graph >::null_vertex();\r\n\r\n        std::vector< bool > ancestor_of_w_vector(num_vertices(g), false);\r\n        std::vector< bool > ancestor_of_v_vector(num_vertices(g), false);\r\n        vertex_to_bool_map_t ancestor_of_w(ancestor_of_w_vector.begin(), vm);\r\n        vertex_to_bool_map_t ancestor_of_v(ancestor_of_v_vector.begin(), vm);\r\n\r\n        while (nca == graph_traits< Graph >::null_vertex()\r\n            && (v_free_ancestor == graph_traits< Graph >::null_vertex()\r\n                || w_free_ancestor == graph_traits< Graph >::null_vertex()))\r\n        {\r\n            ancestor_of_w[w_up.first] = true;\r\n            ancestor_of_v[v_up.first] = true;\r\n\r\n            if (w_free_ancestor == graph_traits< Graph >::null_vertex())\r\n                w_up = parent(w_up);\r\n            if (v_free_ancestor == graph_traits< Graph >::null_vertex())\r\n                v_up = parent(v_up);\r\n\r\n            if (mate[v_up.first] == graph_traits< Graph >::null_vertex())\r\n                v_free_ancestor = v_up.first;\r\n            if (mate[w_up.first] == graph_traits< Graph >::null_vertex())\r\n                w_free_ancestor = w_up.first;\r\n\r\n            if (ancestor_of_w[v_up.first] == true || v_up.first == w_up.first)\r\n                nca = v_up.first;\r\n            else if (ancestor_of_v[w_up.first] == true)\r\n                nca = w_up.first;\r\n            else if (v_free_ancestor == w_free_ancestor\r\n                && v_free_ancestor != graph_traits< Graph >::null_vertex())\r\n                nca = v_up.first;\r\n        }\r\n\r\n        return nca;\r\n    }\r\n\r\n    // when a new top blossom b is created by connecting (v, w), we add\r\n    // sub-blossoms into b along backtracing from v_prime and w_prime to\r\n    // stop_vertex (the base vertex); also, we set labels and outlet for each\r\n    // base vertex we pass by\r\n    void make_blossom(blossom_ptr_t b, vertex_descriptor_t w_prime,\r\n        vertex_descriptor_t v_prime, vertex_descriptor_t stop_vertex)\r\n    {\r\n        std::pair< vertex_descriptor_t, vertex_state_t > u(\r\n            v_prime, graph::detail::V_ODD);\r\n        std::pair< vertex_descriptor_t, vertex_state_t > u_up(\r\n            w_prime, graph::detail::V_EVEN);\r\n\r\n        for (; u_up.first != stop_vertex; u = u_up, u_up = parent(u))\r\n        {\r\n            if (u_up.second == graph::detail::V_EVEN)\r\n            {\r\n                if (!in_top_blossom(u_up.first)->sub_blossoms.empty())\r\n                    outlet[u_up.first] = label_T[u.first];\r\n                label_T[u_up.first] = outlet[u.first];\r\n            }\r\n            else if (u_up.second == graph::detail::V_ODD)\r\n                label_S[u_up.first] = u.first;\r\n\r\n            add_sub_blossom(b, u_up.first);\r\n        }\r\n    }\r\n\r\n    // the design of recursively expanding augmenting path in\r\n    // (reversed_)retrieve_augmenting_path functions is inspired by same\r\n    // functions in max_cardinality_matching.hpp; except that in weighted\r\n    // matching, we use \"outlet\" vertices instead of \"bridge\" vertex pairs: if\r\n    // blossom b is the smallest non-trivial blossom that contains its base\r\n    // vertex v, then v and outlet[v] are where augmenting path enters and\r\n    // leaves b\r\n    void retrieve_augmenting_path(\r\n        vertex_descriptor_t v, vertex_descriptor_t w, vertex_state_t v_state)\r\n    {\r\n        if (v == w)\r\n            aug_path.push_back(v);\r\n        else if (v_state == graph::detail::V_EVEN)\r\n        {\r\n            aug_path.push_back(v);\r\n            retrieve_augmenting_path(label_S[v], w, graph::detail::V_ODD);\r\n        }\r\n        else if (v_state == graph::detail::V_ODD)\r\n        {\r\n            if (outlet[v] == v)\r\n                aug_path.push_back(v);\r\n            else\r\n                reversed_retrieve_augmenting_path(\r\n                    outlet[v], v, graph::detail::V_EVEN);\r\n            retrieve_augmenting_path(label_T[v], w, graph::detail::V_EVEN);\r\n        }\r\n    }\r\n\r\n    void reversed_retrieve_augmenting_path(\r\n        vertex_descriptor_t v, vertex_descriptor_t w, vertex_state_t v_state)\r\n    {\r\n        if (v == w)\r\n            aug_path.push_back(v);\r\n        else if (v_state == graph::detail::V_EVEN)\r\n        {\r\n            reversed_retrieve_augmenting_path(\r\n                label_S[v], w, graph::detail::V_ODD);\r\n            aug_path.push_back(v);\r\n        }\r\n        else if (v_state == graph::detail::V_ODD)\r\n        {\r\n            reversed_retrieve_augmenting_path(\r\n                label_T[v], w, graph::detail::V_EVEN);\r\n            if (outlet[v] != v)\r\n                retrieve_augmenting_path(outlet[v], v, graph::detail::V_EVEN);\r\n            else\r\n                aug_path.push_back(v);\r\n        }\r\n    }\r\n\r\n    // correct labels for vertices in the augmenting path\r\n    void relabel(vertex_descriptor_t v)\r\n    {\r\n        blossom_ptr_t b = in_blossom[v]->father;\r\n\r\n        if (!is_in_blossom(b, mate[v]))\r\n        { // if v is a new base vertex\r\n            std::pair< vertex_descriptor_t, vertex_state_t > u(\r\n                v, graph::detail::V_EVEN);\r\n            while (label_S[u.first] != u.first\r\n                && is_in_blossom(b, label_S[u.first]))\r\n                u = parent(u, true);\r\n\r\n            vertex_descriptor_t old_base = u.first;\r\n            if (label_S[old_base] != old_base)\r\n            { // if old base is not exposed\r\n                label_T[v] = label_S[old_base];\r\n                outlet[v] = old_base;\r\n            }\r\n            else\r\n            { // if old base is exposed then new label_T[v] is not in b,\r\n                // we must (i) make b2 the smallest blossom containing v but not\r\n                // as base vertex (ii) backtrace from b2's new base vertex to b\r\n                label_T[v] = graph_traits< Graph >::null_vertex();\r\n                for (b = b->father; b != blossom_ptr_t() && b->get_base() == v;\r\n                     b = b->father)\r\n                    ;\r\n                if (b != blossom_ptr_t())\r\n                {\r\n                    u = std::make_pair(b->get_base(), graph::detail::V_ODD);\r\n                    while (!is_in_blossom(\r\n                        in_blossom[v]->father, old_label[u.first].first))\r\n                        u = parent(u, true);\r\n                    label_T[v] = u.first;\r\n                    outlet[v] = old_label[u.first].first;\r\n                }\r\n            }\r\n        }\r\n        else if (label_S[v] == v || !is_in_blossom(b, label_S[v]))\r\n        { // if v is an old base vertex\r\n            // let u be the new base vertex; backtrace from u's old T-label\r\n            std::pair< vertex_descriptor_t, vertex_state_t > u(\r\n                b->get_base(), graph::detail::V_ODD);\r\n            while (\r\n                old_label[u.first].first != graph_traits< Graph >::null_vertex()\r\n                && old_label[u.first].first != v)\r\n                u = parent(u, true);\r\n            label_T[v] = old_label[u.first].second;\r\n            outlet[v] = v;\r\n        }\r\n        else // if v is neither a new nor an old base vertex\r\n            label_T[v] = label_S[v];\r\n    }\r\n\r\n    void augmenting(vertex_descriptor_t v, vertex_descriptor_t v_free_ancestor,\r\n        vertex_descriptor_t w, vertex_descriptor_t w_free_ancestor)\r\n    {\r\n        vertex_iterator_t vi, vi_end;\r\n\r\n        // retrieve the augmenting path and put it in aug_path\r\n        reversed_retrieve_augmenting_path(\r\n            v, v_free_ancestor, graph::detail::V_EVEN);\r\n        retrieve_augmenting_path(w, w_free_ancestor, graph::detail::V_EVEN);\r\n\r\n        // augment the matching along aug_path\r\n        vertex_descriptor_t a, b;\r\n        vertex_list_t reversed_aug_path;\r\n        while (!aug_path.empty())\r\n        {\r\n            a = aug_path.front();\r\n            aug_path.pop_front();\r\n            reversed_aug_path.push_back(a);\r\n            b = aug_path.front();\r\n            aug_path.pop_front();\r\n            reversed_aug_path.push_back(b);\r\n\r\n            mate[a] = b;\r\n            mate[b] = a;\r\n\r\n            // reset base vertex for every blossom in augment path\r\n            adjust_blossom(a, b);\r\n        }\r\n\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n            old_label[*vi] = std::make_pair(label_T[*vi], outlet[*vi]);\r\n\r\n        // correct labels for in-blossom vertices along aug_path\r\n        while (!reversed_aug_path.empty())\r\n        {\r\n            a = reversed_aug_path.front();\r\n            reversed_aug_path.pop_front();\r\n\r\n            if (in_blossom[a]->father != blossom_ptr_t())\r\n                relabel(a);\r\n        }\r\n\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            vertex_descriptor_t u = *vi;\r\n            if (mate[u] != graph_traits< Graph >::null_vertex())\r\n                label_S[u] = mate[u];\r\n        }\r\n\r\n        // expand blossoms with zero dual variables\r\n        std::vector< blossom_ptr_t > new_top_blossoms;\r\n        for (blossom_iterator_t bi = top_blossoms.begin();\r\n             bi != top_blossoms.end();)\r\n        {\r\n            if ((*bi)->dual_var <= 0)\r\n                bi = expand_blossom(bi, new_top_blossoms);\r\n            else\r\n                ++bi;\r\n        }\r\n        top_blossoms.insert(top_blossoms.end(), new_top_blossoms.begin(),\r\n            new_top_blossoms.end());\r\n        init();\r\n    }\r\n\r\n    // create a new blossom and set labels for vertices inside\r\n    void blossoming(vertex_descriptor_t v, vertex_descriptor_t v_prime,\r\n        vertex_descriptor_t w, vertex_descriptor_t w_prime,\r\n        vertex_descriptor_t nca)\r\n    {\r\n        vertex_iterator_t vi, vi_end;\r\n\r\n        std::vector< bool > is_old_base_vector(num_vertices(g));\r\n        vertex_to_bool_map_t is_old_base(is_old_base_vector.begin(), vm);\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            if (*vi == base_vertex(*vi))\r\n                is_old_base[*vi] = true;\r\n        }\r\n\r\n        blossom_ptr_t b = boost::make_shared< blossom >();\r\n        add_sub_blossom(b, nca);\r\n\r\n        label_T[w_prime] = v;\r\n        label_T[v_prime] = w;\r\n        outlet[w_prime] = w;\r\n        outlet[v_prime] = v;\r\n\r\n        make_blossom(b, w_prime, v_prime, nca);\r\n        make_blossom(b, v_prime, w_prime, nca);\r\n\r\n        label_T[nca] = graph_traits< Graph >::null_vertex();\r\n        outlet[nca] = nca;\r\n\r\n        top_blossoms.push_back(b);\r\n        bloom(b);\r\n\r\n        // set gamma[b_base] = min_slack{critical_edge(b_base, other_base)}\r\n        // where each critical edge is updated before, by\r\n        // argmin{slack(old_bases_in_b, other_base)};\r\n        vertex_vec_iter_t i, j;\r\n        std::vector< vertex_descriptor_t > b_vertices = b->vertices(),\r\n                                           old_base_in_b, other_base;\r\n        vertex_descriptor_t b_base = b->get_base();\r\n        for (i = b_vertices.begin(); i != b_vertices.end(); ++i)\r\n        {\r\n            if (is_old_base[*i])\r\n                old_base_in_b.push_back(*i);\r\n        }\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            if (*vi != b_base && *vi == base_vertex(*vi))\r\n                other_base.push_back(*vi);\r\n        }\r\n        for (i = other_base.begin(); i != other_base.end(); ++i)\r\n        {\r\n            edge_property_t min_slack\r\n                = std::numeric_limits< edge_property_t >::max();\r\n            std::pair< edge_descriptor_t, bool > b_vi = null_edge;\r\n            for (j = old_base_in_b.begin(); j != old_base_in_b.end(); ++j)\r\n            {\r\n                if (critical_edge[*j][*i] != null_edge\r\n                    && min_slack > slack(critical_edge[*j][*i].first))\r\n                {\r\n                    min_slack = slack(critical_edge[*j][*i].first);\r\n                    b_vi = critical_edge[*j][*i];\r\n                }\r\n            }\r\n            critical_edge[b_base][*i] = critical_edge[*i][b_base] = b_vi;\r\n        }\r\n        gamma[b_base] = std::numeric_limits< edge_property_t >::max();\r\n        for (i = other_base.begin(); i != other_base.end(); ++i)\r\n        {\r\n            if (critical_edge[b_base][*i] != null_edge)\r\n                gamma[b_base] = std::min(\r\n                    gamma[b_base], slack(critical_edge[b_base][*i].first));\r\n        }\r\n    }\r\n\r\n    void init()\r\n    {\r\n        even_edges.clear();\r\n\r\n        vertex_iterator_t vi, vi_end;\r\n        typename std::vector<\r\n            std::vector< std::pair< edge_descriptor_t, bool > > >::iterator vei;\r\n\r\n        for (boost::tie(vi, vi_end) = vertices(g),\r\n                            vei = critical_edge_vectors.begin();\r\n             vi != vi_end; ++vi, ++vei)\r\n        {\r\n            vertex_descriptor_t u = *vi;\r\n            out_edge_iterator_t ei, ei_end;\r\n\r\n            gamma[u] = tau[u] = pi[u]\r\n                = std::numeric_limits< edge_property_t >::max();\r\n            std::fill(vei->begin(), vei->end(), null_edge);\r\n\r\n            if (base_vertex(u) != u)\r\n                continue;\r\n\r\n            label_S[u] = label_T[u] = graph_traits< Graph >::null_vertex();\r\n            outlet[u] = u;\r\n\r\n            if (mate[u] == graph_traits< Graph >::null_vertex())\r\n            {\r\n                label_S[u] = u;\r\n                bloom(in_top_blossom(u));\r\n            }\r\n        }\r\n    }\r\n\r\n    bool augment_matching()\r\n    {\r\n        vertex_descriptor_t v, w, w_free_ancestor, v_free_ancestor;\r\n        v = w = w_free_ancestor = v_free_ancestor\r\n            = graph_traits< Graph >::null_vertex();\r\n        bool found_alternating_path = false;\r\n\r\n        // note that we only use edges of zero slack value for augmenting\r\n        while (!even_edges.empty() && !found_alternating_path)\r\n        {\r\n            // search for augmenting paths depth-first\r\n            edge_descriptor_t current_edge = even_edges.back();\r\n            even_edges.pop_back();\r\n\r\n            v = source(current_edge, g);\r\n            w = target(current_edge, g);\r\n\r\n            vertex_descriptor_t v_prime = base_vertex(v);\r\n            vertex_descriptor_t w_prime = base_vertex(w);\r\n\r\n            // w_prime == v_prime implies that we get an edge that has been\r\n            // shrunk into a blossom\r\n            if (v_prime == w_prime)\r\n                continue;\r\n\r\n            // a paranoid check\r\n            if (label_S[v_prime] == graph_traits< Graph >::null_vertex())\r\n            {\r\n                std::swap(v_prime, w_prime);\r\n                std::swap(v, w);\r\n            }\r\n\r\n            // w_prime may be unlabeled or have a T-label; replace the existed\r\n            // T-label if the edge slack is smaller than current pi[w_prime] and\r\n            // update it. Note that a T-label is \"deserved\" only when pi equals\r\n            // zero. also update tau and tau_idx so that tau_idx becomes T-label\r\n            // when a T-blossom is expanded\r\n            if (label_S[w_prime] == graph_traits< Graph >::null_vertex())\r\n            {\r\n                if (slack(current_edge) < pi[w_prime])\r\n                    put_T_label(w_prime, v, w, slack(current_edge));\r\n                if (slack(current_edge) < tau[w])\r\n                {\r\n                    if (in_blossom[w]->father == blossom_ptr_t()\r\n                        || label_T[w_prime] == v\r\n                        || label_T[w_prime]\r\n                            == graph_traits< Graph >::null_vertex()\r\n                        || nearest_common_ancestor(v_prime, label_T[w_prime],\r\n                               v_free_ancestor, w_free_ancestor)\r\n                            == graph_traits< Graph >::null_vertex())\r\n                    {\r\n                        tau[w] = slack(current_edge);\r\n                        tau_idx[w] = v;\r\n                    }\r\n                }\r\n            }\r\n\r\n            else\r\n            {\r\n                if (slack(current_edge) > 0)\r\n                {\r\n                    // update gamma and critical_edges when we have a smaller\r\n                    // edge slack\r\n                    gamma[v_prime]\r\n                        = std::min(gamma[v_prime], slack(current_edge));\r\n                    gamma[w_prime]\r\n                        = std::min(gamma[w_prime], slack(current_edge));\r\n                    if (critical_edge[v_prime][w_prime] == null_edge\r\n                        || slack(critical_edge[v_prime][w_prime].first)\r\n                            > slack(current_edge))\r\n                    {\r\n                        critical_edge[v_prime][w_prime]\r\n                            = std::pair< edge_descriptor_t, bool >(\r\n                                current_edge, true);\r\n                        critical_edge[w_prime][v_prime]\r\n                            = std::pair< edge_descriptor_t, bool >(\r\n                                current_edge, true);\r\n                    }\r\n                    continue;\r\n                }\r\n                else if (slack(current_edge) == 0)\r\n                {\r\n                    // if nca is null_vertex then we have an augmenting path;\r\n                    // otherwise we have a new top blossom with nca as its base\r\n                    // vertex\r\n                    vertex_descriptor_t nca = nearest_common_ancestor(\r\n                        v_prime, w_prime, v_free_ancestor, w_free_ancestor);\r\n\r\n                    if (nca == graph_traits< Graph >::null_vertex())\r\n                        found_alternating_path\r\n                            = true; // to break out of the loop\r\n                    else\r\n                        blossoming(v, v_prime, w, w_prime, nca);\r\n                }\r\n            }\r\n        }\r\n\r\n        if (!found_alternating_path)\r\n            return false;\r\n\r\n        augmenting(v, v_free_ancestor, w, w_free_ancestor);\r\n        return true;\r\n    }\r\n\r\n    // slack the vertex and blossom dual variables when there is no augmenting\r\n    // path found according to the primal-dual method\r\n    bool adjust_dual()\r\n    {\r\n        edge_property_t delta1, delta2, delta3, delta4, delta;\r\n        delta1 = delta2 = delta3 = delta4\r\n            = std::numeric_limits< edge_property_t >::max();\r\n\r\n        vertex_iterator_t vi, vi_end;\r\n\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            delta1 = std::min(delta1, dual_var[*vi]);\r\n            delta4 = pi[*vi] > 0 ? std::min(delta4, pi[*vi]) : delta4;\r\n            if (*vi == base_vertex(*vi))\r\n                delta3 = std::min(delta3, gamma[*vi] / 2);\r\n        }\r\n\r\n        for (blossom_iterator_t bi = top_blossoms.begin();\r\n             bi != top_blossoms.end(); ++bi)\r\n        {\r\n            vertex_descriptor_t b_base = (*bi)->get_base();\r\n            if (label_T[b_base] != graph_traits< Graph >::null_vertex()\r\n                && pi[b_base] == 0)\r\n                delta2 = std::min(delta2, (*bi)->dual_var / 2);\r\n        }\r\n\r\n        delta = std::min(std::min(delta1, delta2), std::min(delta3, delta4));\r\n\r\n        // start updating dual variables, note that the order is important\r\n\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            vertex_descriptor_t v = *vi, v_prime = base_vertex(v);\r\n\r\n            if (label_S[v_prime] != graph_traits< Graph >::null_vertex())\r\n                dual_var[v] -= delta;\r\n            else if (label_T[v_prime] != graph_traits< Graph >::null_vertex()\r\n                && pi[v_prime] == 0)\r\n                dual_var[v] += delta;\r\n\r\n            if (v == v_prime)\r\n                gamma[v] -= 2 * delta;\r\n        }\r\n\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            vertex_descriptor_t v_prime = base_vertex(*vi);\r\n            if (pi[v_prime] > 0)\r\n                tau[*vi] -= delta;\r\n        }\r\n\r\n        for (blossom_iterator_t bi = top_blossoms.begin();\r\n             bi != top_blossoms.end(); ++bi)\r\n        {\r\n            vertex_descriptor_t b_base = (*bi)->get_base();\r\n            if (label_T[b_base] != graph_traits< Graph >::null_vertex()\r\n                && pi[b_base] == 0)\r\n                (*bi)->dual_var -= 2 * delta;\r\n            if (label_S[b_base] != graph_traits< Graph >::null_vertex())\r\n                (*bi)->dual_var += 2 * delta;\r\n        }\r\n\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n        {\r\n            vertex_descriptor_t v = *vi;\r\n            if (pi[v] > 0)\r\n                pi[v] -= delta;\r\n\r\n            // when some T-vertices have zero pi value, bloom their mates so\r\n            // that matching can be further augmented\r\n            if (label_T[v] != graph_traits< Graph >::null_vertex()\r\n                && pi[v] == 0)\r\n                put_T_label(v, label_T[v], outlet[v], pi[v]);\r\n        }\r\n\r\n        // optimal solution reached, halt\r\n        if (delta == delta1)\r\n            return false;\r\n\r\n        // expand odd blossoms with zero dual variables and zero pi value of\r\n        // their base vertices\r\n        if (delta == delta2 && delta != delta3)\r\n        {\r\n            std::vector< blossom_ptr_t > new_top_blossoms;\r\n            for (blossom_iterator_t bi = top_blossoms.begin();\r\n                 bi != top_blossoms.end();)\r\n            {\r\n                const blossom_ptr_t b = *bi;\r\n                vertex_descriptor_t b_base = b->get_base();\r\n                if (b->dual_var == 0\r\n                    && label_T[b_base] != graph_traits< Graph >::null_vertex()\r\n                    && pi[b_base] == 0)\r\n                    bi = expand_T_blossom(bi, new_top_blossoms);\r\n                else\r\n                    ++bi;\r\n            }\r\n            top_blossoms.insert(top_blossoms.end(), new_top_blossoms.begin(),\r\n                new_top_blossoms.end());\r\n        }\r\n\r\n        while (true)\r\n        {\r\n            // find a zero-slack critical edge (v, w) of zero gamma values\r\n            std::pair< edge_descriptor_t, bool > best_edge = null_edge;\r\n            std::vector< vertex_descriptor_t > base_nodes;\r\n            for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n            {\r\n                if (*vi == base_vertex(*vi))\r\n                    base_nodes.push_back(*vi);\r\n            }\r\n            for (vertex_vec_iter_t i = base_nodes.begin();\r\n                 i != base_nodes.end(); ++i)\r\n            {\r\n                if (gamma[*i] == 0)\r\n                {\r\n                    for (vertex_vec_iter_t j = base_nodes.begin();\r\n                         j != base_nodes.end(); ++j)\r\n                    {\r\n                        if (critical_edge[*i][*j] != null_edge\r\n                            && slack(critical_edge[*i][*j].first) == 0)\r\n                            best_edge = critical_edge[*i][*j];\r\n                    }\r\n                }\r\n            }\r\n\r\n            // if not found, continue finding other augment matching\r\n            if (best_edge == null_edge)\r\n            {\r\n                bool augmented = augment_matching();\r\n                return augmented || delta != delta1;\r\n            }\r\n            // if found, determine either augmenting or blossoming\r\n            vertex_descriptor_t v = source(best_edge.first, g),\r\n                                w = target(best_edge.first, g);\r\n            vertex_descriptor_t v_prime = base_vertex(v),\r\n                                w_prime = base_vertex(w), v_free_ancestor,\r\n                                w_free_ancestor;\r\n            vertex_descriptor_t nca = nearest_common_ancestor(\r\n                v_prime, w_prime, v_free_ancestor, w_free_ancestor);\r\n            if (nca == graph_traits< Graph >::null_vertex())\r\n            {\r\n                augmenting(v, v_free_ancestor, w, w_free_ancestor);\r\n                return true;\r\n            }\r\n            else\r\n                blossoming(v, v_prime, w, w_prime, nca);\r\n        }\r\n\r\n        return false;\r\n    }\r\n\r\n    template < typename PropertyMap > void get_current_matching(PropertyMap pm)\r\n    {\r\n        vertex_iterator_t vi, vi_end;\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n            put(pm, *vi, mate[*vi]);\r\n    }\r\n\r\nprivate:\r\n    const Graph& g;\r\n    VertexIndexMap vm;\r\n    const std::pair< edge_descriptor_t, bool > null_edge;\r\n\r\n    // storage for the property maps below\r\n    std::vector< vertex_descriptor_t > mate_vector;\r\n    std::vector< vertex_descriptor_t > label_S_vector, label_T_vector;\r\n    std::vector< vertex_descriptor_t > outlet_vector;\r\n    std::vector< vertex_descriptor_t > tau_idx_vector;\r\n    std::vector< edge_property_t > dual_var_vector;\r\n    std::vector< edge_property_t > pi_vector, gamma_vector, tau_vector;\r\n    std::vector< blossom_ptr_t > in_blossom_vector;\r\n    std::vector< std::pair< vertex_descriptor_t, vertex_descriptor_t > >\r\n        old_label_vector;\r\n    std::vector< vertex_to_edge_map_t > critical_edge_vector;\r\n    std::vector< std::vector< std::pair< edge_descriptor_t, bool > > >\r\n        critical_edge_vectors;\r\n\r\n    // iterator property maps\r\n    vertex_to_vertex_map_t mate;\r\n    vertex_to_vertex_map_t label_S; // v has an S-label -> v can be an even\r\n                                    // vertex, label_S[v] is its mate\r\n    vertex_to_vertex_map_t\r\n        label_T; // v has a T-label -> v can be an odd vertex, label_T[v] is its\r\n                 // predecessor in aug_path\r\n    vertex_to_vertex_map_t outlet;\r\n    vertex_to_vertex_map_t tau_idx;\r\n    vertex_to_weight_map_t dual_var;\r\n    vertex_to_weight_map_t pi, gamma, tau;\r\n    vertex_to_blossom_map_t\r\n        in_blossom; // map any vertex v to the trivial blossom containing v\r\n    vertex_to_pair_map_t old_label; // <old T-label, old outlet> before\r\n                                    // relabeling or expanding T-blossoms\r\n    vertex_pair_to_edge_map_t\r\n        critical_edge; // an not matched edge (v, w) is critical if v and w\r\n                       // belongs to different S-blossoms\r\n\r\n    vertex_list_t aug_path;\r\n    edge_list_t even_edges;\r\n    std::vector< blossom_ptr_t > top_blossoms;\r\n};\r\n\r\ntemplate < typename Graph, typename MateMap, typename VertexIndexMap >\r\nvoid maximum_weighted_matching(const Graph& g, MateMap mate, VertexIndexMap vm)\r\n{\r\n    empty_matching< Graph, MateMap >::find_matching(g, mate);\r\n    weighted_augmenting_path_finder< Graph, MateMap, VertexIndexMap > augmentor(\r\n        g, mate, vm);\r\n\r\n    // can have |V| times augmenting at most\r\n    for (std::size_t t = 0; t < num_vertices(g); ++t)\r\n    {\r\n        bool augmented = false;\r\n        while (!augmented)\r\n        {\r\n            augmented = augmentor.augment_matching();\r\n            if (!augmented)\r\n            {\r\n                // halt if adjusting dual variables can't bring potential\r\n                // augment\r\n                if (!augmentor.adjust_dual())\r\n                    break;\r\n            }\r\n        }\r\n        if (!augmented)\r\n            break;\r\n    }\r\n\r\n    augmentor.get_current_matching(mate);\r\n}\r\n\r\ntemplate < typename Graph, typename MateMap >\r\ninline void maximum_weighted_matching(const Graph& g, MateMap mate)\r\n{\r\n    maximum_weighted_matching(g, mate, get(vertex_index, g));\r\n}\r\n\r\n// brute-force matcher searches all possible combinations of matched edges to\r\n// get the maximum weighted matching which can be used for testing on small\r\n// graphs (within dozens vertices)\r\ntemplate < typename Graph, typename MateMap, typename VertexIndexMap >\r\nclass brute_force_matching\r\n{\r\npublic:\r\n    typedef\r\n        typename graph_traits< Graph >::vertex_descriptor vertex_descriptor_t;\r\n    typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator_t;\r\n    typedef\r\n        typename std::vector< vertex_descriptor_t >::iterator vertex_vec_iter_t;\r\n    typedef typename graph_traits< Graph >::edge_iterator edge_iterator_t;\r\n    typedef boost::iterator_property_map< vertex_vec_iter_t, VertexIndexMap >\r\n        vertex_to_vertex_map_t;\r\n\r\n    brute_force_matching(\r\n        const Graph& arg_g, MateMap arg_mate, VertexIndexMap arg_vm)\r\n    : g(arg_g)\r\n    , vm(arg_vm)\r\n    , mate_vector(num_vertices(g))\r\n    , best_mate_vector(num_vertices(g))\r\n    , mate(mate_vector.begin(), vm)\r\n    , best_mate(best_mate_vector.begin(), vm)\r\n    {\r\n        vertex_iterator_t vi, vi_end;\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n            best_mate[*vi] = mate[*vi] = get(arg_mate, *vi);\r\n    }\r\n\r\n    template < typename PropertyMap > void find_matching(PropertyMap pm)\r\n    {\r\n        edge_iterator_t ei;\r\n        boost::tie(ei, ei_end) = edges(g);\r\n        select_edge(ei);\r\n\r\n        vertex_iterator_t vi, vi_end;\r\n        for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n            put(pm, *vi, best_mate[*vi]);\r\n    }\r\n\r\nprivate:\r\n    const Graph& g;\r\n    VertexIndexMap vm;\r\n    std::vector< vertex_descriptor_t > mate_vector, best_mate_vector;\r\n    vertex_to_vertex_map_t mate, best_mate;\r\n    edge_iterator_t ei_end;\r\n\r\n    void select_edge(edge_iterator_t ei)\r\n    {\r\n        if (ei == ei_end)\r\n        {\r\n            if (matching_weight_sum(g, mate)\r\n                > matching_weight_sum(g, best_mate))\r\n            {\r\n                vertex_iterator_t vi, vi_end;\r\n                for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\r\n                    best_mate[*vi] = mate[*vi];\r\n            }\r\n            return;\r\n        }\r\n\r\n        vertex_descriptor_t v, w;\r\n        v = source(*ei, g);\r\n        w = target(*ei, g);\r\n\r\n        select_edge(++ei);\r\n\r\n        if (mate[v] == graph_traits< Graph >::null_vertex()\r\n            && mate[w] == graph_traits< Graph >::null_vertex())\r\n        {\r\n            mate[v] = w;\r\n            mate[w] = v;\r\n            select_edge(ei);\r\n            mate[v] = mate[w] = graph_traits< Graph >::null_vertex();\r\n        }\r\n    }\r\n};\r\n\r\ntemplate < typename Graph, typename MateMap, typename VertexIndexMap >\r\nvoid brute_force_maximum_weighted_matching(\r\n    const Graph& g, MateMap mate, VertexIndexMap vm)\r\n{\r\n    empty_matching< Graph, MateMap >::find_matching(g, mate);\r\n    brute_force_matching< Graph, MateMap, VertexIndexMap > brute_force_matcher(\r\n        g, mate, vm);\r\n    brute_force_matcher.find_matching(mate);\r\n}\r\n\r\ntemplate < typename Graph, typename MateMap >\r\ninline void brute_force_maximum_weighted_matching(const Graph& g, MateMap mate)\r\n{\r\n    brute_force_maximum_weighted_matching(g, mate, get(vertex_index, g));\r\n}\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "8527664ea4db93693ceb14a33b1148371d4eec67", "size": 51035, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/include/boost/graph/maximum_weighted_matching.hpp", "max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 80.0, "max_stars_repo_stars_event_min_datetime": "2021-09-07T12:44:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T01:22:19.000Z", "max_issues_repo_path": "deps/boost/include/boost/graph/maximum_weighted_matching.hpp", "max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-12-23T02:49:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T05:28:24.000Z", "max_forks_repo_path": "deps/boost/include/boost/graph/maximum_weighted_matching.hpp", "max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp", "max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2021-09-14T06:24:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T06:55:07.000Z", "avg_line_length": 38.8394216134, "max_line_length": 81, "alphanum_fraction": 0.5525031841, "num_tokens": 11551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23597951964532393}}
{"text": "/*  _______________________________________________________________________\n\n    DAKOTA: Design Analysis Kit for Optimization and Terascale Applications\n    Copyright 2014 Sandia Corporation.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Dakota directory.\n    _______________________________________________________________________ */\n\n//- Class:       NonlinearCGOptimizer\n//- Description: Implementation code for the NonlinearCGOptimizer class\n//- Owner:       Brian Adams\n//- Checked by:\n\n#include \"NonlinearCGOptimizer.hpp\"\n#include \"ProblemDescDB.hpp\"\n#include <boost/math/tools/minima.hpp>\n\n// uncomment to use the Boost Brent's algorithm\n//#define BOOST_BRENT 1\n\nusing namespace std;\n\nnamespace Dakota {\n\n// wrapper around linesearch evaluator needed for use in Brent's algorithm\nclass boost_ls_eval {\n\npublic:\n\n  // constructor\n  boost_ls_eval(NonlinearCGOptimizer& pimpl_): pImpl(pimpl_)\n  { /* empty constructor */ }\n\n  // evaluator\n  Real operator()(const Real& trial_step)\n  { return ( pImpl.linesearch_eval(trial_step, 1) ); }\n\nprivate:\n\n  // pointer to class instance so we have a context when performing evaluations\n  NonlinearCGOptimizer& pImpl;\n\n};\n\n\nNonlinearCGOptimizer::\nNonlinearCGOptimizer(ProblemDescDB& problem_db, Model& model): \n  Optimizer(problem_db, model, std::shared_ptr<TraitsBase>(new NonlinearCGTraits())),\n  initialStep(0.01), linesearchTolerance(1.0e-2),\n  linesearchType(CG_LS_SIMPLE), maxLinesearchIters(10), relFunctionTol(0.0),\n  relGradientTol(0.0), resetStep(true), restartIter(1000000),\n  updateType(CG_FLETCHER_REEVES)\n{\n  if (numFunctions > 1 || numConstraints > 0 || boundConstraintFlag) {\n    Cerr << \"ERROR: NonlinearCG only supports unconstrainted single objective \"\n\t << \"problems!\" << endl;\n    abort_handler(-1);\n  }\n  // some of the defaults may be overridden by user-supplied options\n  parse_options();\n\n  stepLength = initialStep;\n}\n\n\nNonlinearCGOptimizer::~NonlinearCGOptimizer()\n{ }\n\n\nvoid NonlinearCGOptimizer::core_run()\n{\n\n  // TODO: Once DAKOTA moves to Teuchos for its numerical data type,\n  // remove the various copies below.  (Also, could use std::copy for some.)\n  copy_data(iteratedModel.continuous_variables(), designVars); // view->copy\n  searchDirection.sizeUninitialized(numContinuousVars);\n\n  if (linesearchType > CG_FIXED_STEP)\n    trialVars.sizeUninitialized(numContinuousVars);\n\n  for (iterCurr = 0; iterCurr < maxIterations; iterCurr++) {\n\n    // get function and gradient -- should discern whether linesearch\n    // is in use and only request gradient if appropriate\n    activeSet.request_values(3);\n    iteratedModel.evaluate(activeSet);\n    const Response&   response  = iteratedModel.current_response();\n    const RealVector& functions = response.function_values();\n\n    functionCurr = functions[0];\n    gradCurr = response.function_gradient_view(0);\n\n    // always store ||g||^2\n    gradDotGrad_curr = gradCurr.dot(gradCurr);\n    if (iterCurr == 0)\n      gradDotGrad_init = gradDotGrad_curr;\n\n    // TODO: accumulate stats\n    if (outputLevel >= NORMAL_OUTPUT) {\n      Cout << \"INFO (NonlinearCG): iteration statistics\\n\"; \n      Cout << \"iter J                norm(g)          steplen\\n\";\n      Cout << \"---- ---------------- ---------------- ----------------\\n\";\n      Cout << setw(4) << iterCurr << \" \" << functionCurr << \" \" \n\t   << sqrt(gradDotGrad_curr) << \" \" << stepLength << \"\\n\" << endl;\n    }\n    // check convergence: two-norm of gradient\n    if (sqrt(gradDotGrad_curr) < convergenceTol) {\n      Cout << \"INFO (NonlinearCG): hard convergence reached (gradient norm \"\n\t   << \"within tolerance).\" << endl;\n      break;\n    }\n\n    if ( iterCurr > 0)\n      // could do as CTK and check this in conjunction with test above...\n      if (sqrt(gradDotGrad_curr) < relGradientTol*gradDotGrad_init) {\n\tCout << \"INFO (NonlinearCG): convergence reached (gradient reduction \"\n\t     << \"within tolerance).\" << endl;\n\tbreak;\n      }\n    if ( std::fabs(functionCurr - functionPrev) / \n\t std::max(1.0,std::fabs(functionPrev)) <\n\t   relFunctionTol ) {\n\tCout << \"INFO (NonlinearCG): convergence reached (function change \"\n\t     << \"within tolerance).\" << endl;\n\tbreak;\n      }\n\n    // will set searchDirection to steepest descent, or CG direction\n    // TODO: recourse to steepest descent\n    compute_direction();\n    if (sqrt(searchDirection.dot(searchDirection)) < 1e-16) {\n      Cout << \"INFO (NonlinearCG): degenerate search direction. Exiting.\"\n\t   << endl;\n      break;\n    }\n\n    // will set stepLength if successful, return false if failed\n    if (!compute_step()) {\n      Cout << \"INFO (NonlinearCG): failure computing step length. Exiting.\"\n\t   << endl;\n      break;\n    }\n\n    // update design vars here, gradient evaluated on loop continuation\n    // compute designVars <- stepLength * searchDirection + designVars\n    designVars.AXPY(designVars.length(), stepLength, searchDirection.values(),\n\t\t    1, designVars.values(), 1);\n\n    // TODO: this is a duplicate copy in the linesearch case -- rework to avoid\n    iteratedModel.continuous_variables(designVars);\n    \n    // archive gradient and derived metric for next iteration\n    functionPrev = functionCurr;\n    gradPrev = response.function_gradient_copy(0);\n    gradDotGrad_prev = gradDotGrad_curr;\n\n  }\n\n  if (iterCurr == maxIterations)\n    Cout << \"INFO (NonlinearCG): maxIterations = \" << maxIterations \n\t << \" reached. Exiting.\" << endl; \n\n\n  // return the optimal point in best*; should do DB lookup?\n  bestVariablesArray.front().continuous_variables(designVars);\n  if (!localObjectiveRecast) // else local_objective_recast_retrieve() used\n    bestResponseArray.front().function_value(functionCurr, 0);\n}\n\n\nvoid NonlinearCGOptimizer::compute_direction()\n{\n\n  if (iterCurr == 0 || (iterCurr % restartIter == 0) || \n      updateType == CG_STEEPEST) {\n\n    // choose steepest descent on first iteration or on reset\n    if (outputLevel >= VERBOSE_OUTPUT && iterCurr > 0)\n      Cout << \"INFO (NonlinearCG): Iteration = \" << iterCurr \n\t   << \", resetting to steepest descent.\" << endl;\n    searchDirection.putScalar(0.0);\n    searchDirection -= gradCurr;\n\n  }\n  else {\n\n    double beta = 0.0;\n    if (updateType == CG_FLETCHER_REEVES)\n      beta = gradDotGrad_curr/gradDotGrad_prev;\t\n    else {\n\n      // Polak-Ribiere or Hestenes-Stiefel\n      gradDiff = iteratedModel.current_response().function_gradient_copy(0);\n      gradDiff -= gradPrev;\n      Real gradCurr_dot_gradDiff = \n\tgradCurr.dot(gradDiff);\n      \n      if (updateType == CG_POLAK_RIBIERE)\n\tbeta = gradCurr_dot_gradDiff / gradDotGrad_prev;\n      else if (updateType == CG_POLAK_RIBIERE_PLUS)\n\t// use max(B_PR, 0.0))\n\tbeta = std::max(gradCurr_dot_gradDiff / gradDotGrad_prev, 0.0);\n      else if (updateType == CG_HESTENES_STIEFEL)\n\t// use (gradCurr - gradPrev)'*searchDirection in denominator\n\tbeta = gradCurr_dot_gradDiff / \n\t  gradDiff.dot(searchDirection);\n    }\n\n    if (outputLevel >= DEBUG_OUTPUT)\n      Cout << \"DEBUG (NonlinearCG): beta = \" << beta << endl;\n    // searchDirection <-- beta*searchDirection - gradCurr\n    searchDirection.scale(beta);\n    searchDirection.AXPY(searchDirection.length(), -1.0,\n\t\t\t gradCurr.values(), 1,\n\t\t\t searchDirection.values(), 1);\n  }\n  if (outputLevel >= DEBUG_OUTPUT)\n    Cout << \"DEBUG (NonlinearCG): new search direction is:\\n\"\n\t << searchDirection << endl;\n\n}\n  \n\n// returns whether a valid step was found\nbool NonlinearCGOptimizer::compute_step()\n{\n\n  // TODO: stepLength should be chosen based on descent direction and \n  // previous successful step\n  if (resetStep)\n    stepLength = initialStep;\n\n  switch (linesearchType) {\n\n  case CG_FIXED_STEP:\n    // do nothing (leave initial stepLength )\n    return(true);\n    break;\n\n  case CG_LS_SIMPLE: {\n\n    // value-based line search with simple decrease\n    bool decrease = false;\n    unsigned bt_iter = 0;\n    while (!decrease && bt_iter < maxLinesearchIters) {\n\n      if (linesearch_eval(stepLength) < functionCurr) {\n\tif (outputLevel > NORMAL_OUTPUT)\n\t  Cout << \"INFO (NonlinearCG_LS): Simple decrease achieved; step = \" \n\t       << stepLength << \".\" << endl;\n\tdecrease = true;\n      }\n      else {\n\tif (outputLevel > NORMAL_OUTPUT) {\n\t  if (bt_iter == 0)\n\t    Cout << \"INFO (NonlinearCG_LS): Initiating simple linesearch.\\n\";\n\t  Cout << \"INFO (NonlinearCG_LS): Backtracking.\" << endl;\n\t}\n\tstepLength /= 2;\n\tbt_iter++;\n      }\n\n    }\n    if (bt_iter == maxLinesearchIters && outputLevel > NORMAL_OUTPUT) {\n      Cout << \"INFO (NonlinearCG_LS): Could not find step yielding simple \"\n\t   << \"decrease.\" << endl;\n    }\n    return(decrease);\n\n    break;\n  }\n\n  case CG_LS_BRENT: {\n\n    if (outputLevel > NORMAL_OUTPUT)\n      Cout << \"INFO (NonlinearCG_LS): Initiating Brent linesearch.\" << endl;\n\n    // first bracket the minimum, then use Brent's algorithm from Boost to \n    // hone in on the minimum\n    Real xa, xb, xc, fa, fb, fc;\n    xa = 0.0;\n    fa = functionCurr;\n\n    if (outputLevel > NORMAL_OUTPUT)\n      Cout << \"INFO (NonlinearCG_LS): Evaluating at initial step = \" \n\t   << stepLength << \".\" << endl;\n    xb = stepLength;\n    fb = linesearch_eval(xb);\n\n    if (outputLevel > NORMAL_OUTPUT)\n      Cout << \"INFO (NonlinearCG_LS): Initiating bracketing procedure.\" << endl;\n    bracket_min(xa, xb, xc, fa, fb, fc);\n    if (outputLevel > NORMAL_OUTPUT) {\n      Cout << \"INFO (NonlinearCG_LS): Bracketing complete:\\n\";\n      Cout << \"Bracket:   [\" << xa << \", \" << xb << \", \" << xc << \"]\" << endl;\n      Cout << \"Functions: [\" << fa << \", \" << fb << \", \" << fc << \"]\" << endl;\n      Cout << \"INFO (NonlinearCG_LS): Initiating 1-D minimization.\" << endl;\n    }\n\n#ifdef BOOST_BRENT\n    if (outputLevel >= DEBUG_OUTPUT)\n      Cout << \"INFO (NonlinearCG_LS): Using Boost Brent.\" << endl;\n    int exponent;\n    frexp(linesearchTolerance, &exponent);\n    int bits = 1 - exponent;\n    boost::uintmax_t max_it = maxLinesearchIters;\n\n    pair<Real,Real> opt_len = \n      boost::math::tools::brent_find_minima<boost_ls_eval,Real>\n      (boost_ls_eval(*this), xa, xc, bits, max_it);\n    stepLength = opt_len.first;\n#else\n    if (outputLevel >= DEBUG_OUTPUT)\n      Cout << \"INFO (NonlinearCG_LS): Using native Brent.\" << endl;\n    stepLength = brent_minimize(xa, xc, linesearchTolerance);\n#endif\n\n    if (outputLevel > NORMAL_OUTPUT)\n      Cout << \"INFO (NonlinearCG_LS): Linesearch complete; step = \" \n\t   << stepLength << \".\" << endl;\n    \n    return(true);\n    \n    break;\n\n  }\n\n  default:\n    Cerr << \"ERROR (NonlinearCG_LS): Requested linesearch type not available.\" \n\t << endl;\n    abort_handler(-1);\n    break;\n\n  }\n\n  return(false);\n\n}\n\n\nvoid NonlinearCGOptimizer::bracket_min(Real& xa, Real& xb, Real& xc,\n\t\t\t\t       Real& fa, Real& fb, Real& fc) \n{\n  // Repeatedly evaluate the function along the search direction until\n  // we know we've bracketed a minimum.\n\n  \n  const Real GOLDEN_RATIO = 1.618033988749895, SMALL_DIV = 1e-16,\n    MAX_EXTRAP_FACTOR = 100.0;\n  Real tmp, q, r, xm, xlim, fm = 0.0;\n\n  // TODO: implement option to do simple backtracking to get a lower\n  // function value in the current search direction; for now, just\n  // swap the values of a and b if necessary\n  // also, need to bound the search >= 0 when changing sign...\n  if (fb > fa) {\n    Cout << \"swapping points, fa = \" << fa << \"fb = \" << fb << \"diff \" \n\t << fb-fa << endl;\n    tmp = xa;\n    xa = xb;\n    xb = tmp;\n    tmp = fa;\n    fa = fb;\n    fb = tmp;\n  }\n\n  xc = xb + GOLDEN_RATIO*(xb-xa);\n  fc = linesearch_eval(xc);\n\n  if (outputLevel >= DEBUG_OUTPUT) {\n    Cout << \"Bracket:   [\" << xa << \", \" << xb << \", \" << xc << \"]\" << endl;\n    Cout << \"Functions: [\" << fa << \", \" << fb << \", \" << fc << \"]\" << endl;\n  }\n\n  while (fb >= fc) {\n    \n    if (outputLevel >= DEBUG_OUTPUT) {\n      Cout << \"Bracket:   [\" << xa << \", \" << xb << \", \" << xc << \"]\" << endl;\n      Cout << \"Functions: [\" << fa << \", \" << fb << \", \" << fc << \"]\" << endl;\n    }\n\n    // find the extremum xm of a quadratic model interpolating a, b, c\n    q = (fb-fa)*(xb-xc);\n    r = (fb-fc)*(xb-xa);\n    // avoid division by small (q-r) by bounding with signed minimum\n    tmp = std::fabs(q-r);\n    tmp = (tmp < SMALL_DIV) ? SMALL_DIV : tmp;\n    tmp = (q-r < 0 ) ? -tmp : tmp;\n    xm = xb - (q*(xb-xc) -r*(xb-xa))/2.0/tmp;\n    // maximum point for which we trust the interpolation\n    xlim = xb + MAX_EXTRAP_FACTOR * (xc-xb);\n\n    // now detect which interval xm is in and act accordingly\n    // [xb, xc]\n    if ( (xb-xm)*(xm-xc) > 0.0 ) {\n      \n      fm = linesearch_eval(xm);\n      if (fm < fc) { \n\t// use points [b, xm, c]\n\txa = xb;\n\tfa = fb;\n        xb = xm;\n\tfb = fm;\n\treturn;\n      }\n      else if (fm > fb) {\n\t// use points [a, b, xm]\n\txc = xm;\n\tfc = fm;\n\treturn;\n      }\n      xm = xc + GOLDEN_RATIO*(xc-xb);\n      fm = linesearch_eval(xm);\n\n    }\n    // [xc, xlim]\n    else if ((xc-xm)*(xm-xlim) > 0.0) {\n      if (fm < fc) {\n\txb = xc;\n\tfb = fc;\n\txc = xm;\n\tfc = fm;  \n\txm = xc+GOLDEN_RATIO*(xc-xb);\n\tfm = linesearch_eval(xm);\n      }\n    }\n    // [xlim, inf]\n    else if ((xm-xlim)*(xlim-xc) >= 0.0 ) {\n      xm = xlim;\n      fm = linesearch_eval(xm);\n    }\n    // [0,xb]\n    else {\n      xm = xc + GOLDEN_RATIO*(xc-xb);\n      fm = linesearch_eval(xm);\n    }\n\n    // shift to newest 3 points before loop\n    xa = xb;\n    fa = fb;\n    xb = xc;\n    fb = fc;\n    xc = xm;\n    fc = fm;\n\n  }\n\n}\n\n/** Perform 1-D minimization for the stepLength using Brent's method.\n    This is a C translation of fmin.f from Netlib. \n*/\nReal NonlinearCGOptimizer::brent_minimize(Real a, Real b, Real tol)\n{\n\n  // c is the squared inverse of the golden ratio\n  Real c = 0.5*(3.0-sqrt(5.0));\n\n  // eps is approximately the square root of the relative machine\n  // precision.\n\n  // initialization \n  Real eps = std::numeric_limits<double>::epsilon();\n  Real tol1 = eps+1.0;\n  eps = sqrt(eps);\n\n  Real v = a+c*(b-a);\n  Real w = v;\n  Real x = v;\n  Real e = 0.0;\n  Real fx = linesearch_eval(x);\n  Real fv = fx;\n  Real fw = fx;\n  Real tol3 = tol/3.0;\n\n  Real xm = 0.5*(a+b);\n  tol1 = eps*std::fabs(x)+tol3;\n  Real t2 = 2.0*tol1;\n\n  Real d, p, q, r, u, fu;  // temp variables\n\n  unsigned iter = 1;\n  while ( iter < maxLinesearchIters && std::fabs(x-xm) > (t2-0.5*(b-a)) ) {\n\n    d = 0.0;\n    p = 0.0;\n    q = 0.0;\n    r = 0.0;\n    if ( std::fabs(e) > tol1 ) { \n\n      // fit parabola\n      r = (x-w)*(fx-fv);\n      q = (x-v)*(fx-fw);\n      p = (x-v)*q-(x-w)*r;\n      q = 2.0*(q-r);\n  \n      if (q <= 0.0)\n\tq = -q;\n      else\n\tp = -p;\n      r = e;\n      e = d;\n  \n    }\n\n    if ( (std::fabs(p) < std::fabs(0.5*q*r)) && (p > q*(a-x)) && (p < q*(b-x)) ) {\n\n      // a parabolic-interpolation step\n      d = p/q;\n      u = x+d;\n      // f must not be evaluated too close to ax or bx\n      if ( ((u-a) < t2) || ((b-u) < t2) ) {\n\td = tol1;\n\tif (x >= xm) \n\t  d = -d;\n      }\n    }\n    else {\n\n      // a golden-section step\n      if (x >= xm)\n\te = a-x;\n      else\n\te = b-x;\n      d = c*e;\n      \n    }\n\n    // f must not be evaluated too close to x\n    if ( std::fabs(d) < tol1 )\n      if ( d <= 0.0 )\n\tu = x-tol1;\n      else\n\tu = x+tol1;\n    else\n      u = x+d;\n    \n    fu = linesearch_eval(u);\n\n    // update  a, b, v, w, and x\n    if (fx <= fu) \n      if (u >= x)\n\tb = u;\n      else\n\ta = u;\n\n    if (fu <= fx) {\n\n      if (u >= x)\n\ta = x;\n      else\n\tb = x;\n      v = w;\n      fv = fw;\n      w = x;\n      fw = fx;\n      x = u;\n      fx = fu;\n\n    }\n    else if ( (fu > fw) && (w != x) ) {\n\n      if ((fu<=fv) || (v == x) || (v == w)) {\n\tv = u;\n\tfv = fu;\n      }\n\n    }\n    else {\n\n      v = w;\n      fv = fw;\n      w = u;\n      fw = fu;\n\n    }\n\n    xm = 0.5*(a+b);\n    tol1 = eps*std::fabs(x)+tol3;\n    t2 = 2.0*tol1;\n    iter++;\n\n  } // end while\n\n  if (iter > maxLinesearchIters && outputLevel >= NORMAL_OUTPUT) {\n    Cout << \"WARN (NonlinearCG_LS): Step length not found within \"\n\t << \"maxLinesearchIters; using best known.\" << endl;\n  }\n\n  return(x);\n\n} \n\n\n// Function evaluator to use in linesearches\n// Uses the current designVars and searchDirection \n// TODO: Support gradient-based evals, likely returning a const Response&\nReal NonlinearCGOptimizer::linesearch_eval(const Real& trial_step,\n\t\t\t\t\t   short req_val) \n{\n  // evaluate function only \n  for (size_t i=0; i<numContinuousVars; i++)\n    trialVars[i] = designVars[i] + trial_step * searchDirection[i];\n  iteratedModel.continuous_variables(trialVars);\n  activeSet.request_values(req_val);\n  iteratedModel.evaluate(activeSet);\n  const Response& response = iteratedModel.current_response();\n  const RealVector& functions = response.function_values();\n  \n  return(functions[0]);\n}\n\n\nvoid NonlinearCGOptimizer::parse_options()\n{\n  // Allowed update options\n  map<string, int> update_type;\n  update_type[\"steepest\"]              = 0;\n  update_type[\"fletcher_reeves\"]       = 1;\n  update_type[\"polak_ribiere\"]         = 2;\n  update_type[\"polak_ribiere_plus\"]    = 3;\n  update_type[\"hestenes_stiefel\"]      = 4;\n\n  // Allowed linesearch options\n  map<string, int> search_type;\n  search_type[\"fixed_step\"] = 0;\n  search_type[\"ls_simple\"]  = 1;\n  search_type[\"ls_brent\"]   = 2;\n  search_type[\"ls_wolfe\"]   = 3;\n\n  map<string,string> opts;\n  const StringArray& db_opts = probDescDB.get_sa(\"method.coliny.misc_options\");\n  StringArray::const_iterator db_it = db_opts.begin();\n  StringArray::const_iterator db_end = db_opts.end();\n  String::const_iterator delim;\n\n  for ( ; db_it != db_end; ++db_it)\n    if ( (delim = find(db_it->begin(), db_it->end(), '=')) != db_it->end()) {\n\n      String opt(*db_it, 0, distance(db_it->begin(), delim));\n      String val(*db_it, distance(db_it->begin(), delim+1),\n\t\t distance(delim, db_it->end()));\n      \n      if (opt == \"initial_step\")\n\tinitialStep = atof(val.c_str());\n      else if (opt == \"linesearch_tolerance\")\n\tlinesearchTolerance = atof(val.c_str());\n      else if (opt == \"linesearch_type\") {\n\tmap<string, int>::const_iterator cit;\n\tif ( (cit = search_type.find(val)) != search_type.end())\n\t  linesearchType = cit->second;\n\telse {\n\t  Cerr << \"ERROR (NonlinearCG): Invalid linesearch_type.\" << endl;\n\t  abort_handler(-1);\n\t}\n      }\n      else if (opt == \"max_linesearch_iters\")\n\tmaxLinesearchIters = atoi(val.c_str());\n      else if (opt == \"rel_function_tol\")\n\trelFunctionTol = atof(val.c_str());\n      else if (opt == \"rel_gradient_tol\")\n\trelGradientTol = atof(val.c_str());\n      else if (opt == \"restart_iter\")\n\trestartIter = atoi(val.c_str());\n      else if (opt == \"reset_step\")\n\tresetStep = (val == \"true\") ? true : false;\n      else if (opt == \"update_type\") {\n\tmap<string, int>::const_iterator cit;\n\tif ( (cit = update_type.find(val)) != update_type.end())\n\t  updateType = cit->second;\n\telse {\n\t  Cerr << \"ERROR (NonlinearCG): Invalid update_type.\" << endl;\n\t  abort_handler(-1);\n\t}\n      }\n      else {\n\tCerr << \"ERROR (NonlinearCG): Unknown misc_option.\" << endl;\n\tabort_handler(-1);\n      }\n\n      if (outputLevel > NORMAL_OUTPUT)\n\tCout << \"INFO (NonlinearCG): User parameter '\" << opt << \"': \" << val \n\t     << endl;\n\n    }\n    else {\n      Cerr << \"ERROR (NonlinearCG): Invalid misc_options format.\" << endl;\n      abort_handler(-1);\n    }\n\n}\n\n\n} // namespace Dakota\n", "meta": {"hexsha": "bd209bdb92626ccc24fe3392fb8c96856a3f3895", "size": 19105, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NonlinearCGOptimizer.cpp", "max_stars_repo_name": "jnnccc/Dakota-orb", "max_stars_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NonlinearCGOptimizer.cpp", "max_issues_repo_name": "jnnccc/Dakota-orb", "max_issues_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NonlinearCGOptimizer.cpp", "max_forks_repo_name": "jnnccc/Dakota-orb", "max_forks_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4892086331, "max_line_length": 85, "alphanum_fraction": 0.61444648, "num_tokens": 5415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23597951964532393}}
{"text": "/*\n * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)\n *\n * This software may be modified and distributed under the terms of the\n * BSD 3-Clause license. See the accompanying LICENSE file for details.\n */\n\n#include <iostream>\n#include <memory>\n#include <random>\n\n#include <BayesFilters/BootstrapCorrection.h>\n#include <BayesFilters/DrawParticles.h>\n#include <BayesFilters/GaussianLikelihood.h>\n#include <BayesFilters/InitSurveillanceAreaGrid.h>\n#include <BayesFilters/SimulatedLinearSensor.h>\n#include <BayesFilters/LikelihoodModel.h>\n#include <BayesFilters/MeasurementModelDecorator.h>\n#include <BayesFilters/ParticleSet.h>\n#include <BayesFilters/ParticleSetInitialization.h>\n#include <BayesFilters/PFCorrectionDecorator.h>\n#include <BayesFilters/PFPredictionDecorator.h>\n#include <BayesFilters/SimulatedStateModel.h>\n#include <BayesFilters/Resampling.h>\n#include <BayesFilters/StateModelDecorator.h>\n#include <BayesFilters/SIS.h>\n#include <BayesFilters/WhiteNoiseAcceleration.h>\n#include <BayesFilters/utils.h>\n#include <Eigen/Dense>\n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nclass DecoratedWNA : public StateModelDecorator\n{\npublic:\n    DecoratedWNA(std::unique_ptr<StateModel> state_model) noexcept :\n        StateModelDecorator(std::move(state_model))\n    { };\n\n\n    void motion(const Eigen::Ref<const Eigen::MatrixXd>& cur_states, Eigen::Ref<Eigen::MatrixXd> mot_states) override\n    {\n        std::cout << \"Decorator: DecoratedWNA::motion().\" << std::endl;\n\n        StateModelDecorator::motion(cur_states, mot_states);\n    }\n};\n\n\nclass DecoratedLinearSensor : public MeasurementModelDecorator\n{\npublic:\n    DecoratedLinearSensor(std::unique_ptr<MeasurementModel> observation_model) noexcept :\n        MeasurementModelDecorator(std::move(observation_model))\n    { }\n\n\n    std::pair<bool, bfl::Data> measure() const override\n    {\n        std::cout << \"Decorator: DecoratedLinearSensor::measure().\" << std::endl;\n\n        return MeasurementModelDecorator::measure();\n    }\n};\n\n\nclass DecoratedDrawParticles : public PFPredictionDecorator\n{\npublic:\n    DecoratedDrawParticles(std::unique_ptr<PFPrediction> prediction) noexcept :\n        PFPredictionDecorator(std::move(prediction))\n    { }\n\nprotected:\n    void predictStep(const ParticleSet& prev_particles, ParticleSet& pred_particles) override\n    {\n        std::cout << \"Decorator: DecoratedDrawParticles::predictStep().\" << std::endl;\n\n        PFPredictionDecorator::predictStep(prev_particles, pred_particles);\n    }\n};\n\n\nclass DecoratedBootstrapCorrection : public PFCorrectionDecorator\n{\npublic:\n    DecoratedBootstrapCorrection(std::unique_ptr<PFCorrection> correction) noexcept :\n        PFCorrectionDecorator(std::move(correction))\n    { }\n\nprotected:\n    void correctStep(const ParticleSet& pred_particles, ParticleSet& cor_particles) override\n    {\n        std::cout << \"Decorator: DecoratedBootstrapCorrection::correctStep().\" << std::endl;\n\n        PFCorrectionDecorator::correctStep(pred_particles, cor_particles);\n    }\n};\n\n\nclass SISSimulation : public SIS\n{\npublic:\n    SISSimulation\n    (\n        unsigned int num_particle,\n        std::size_t state_size,\n        unsigned int simulation_steps,\n        std::unique_ptr<ParticleSetInitialization> initialization,\n        std::unique_ptr<PFPrediction> prediction,\n        std::unique_ptr<PFCorrection> correction,\n        std::unique_ptr<Resampling> resampling\n    ) noexcept :\n        SIS(num_particle, state_size, std::move(initialization), std::move(prediction), std::move(correction), std::move(resampling)),\n        simulation_steps_(simulation_steps)\n    { }\n\nprotected:\n    bool runCondition()\n    {\n        if (getFilteringStep() < simulation_steps_)\n            return true;\n        else\n            return false;\n    }\n\nprivate:\n    unsigned int simulation_steps_;\n};\n\n\nint main()\n{\n    /* A set of parameters needed to run a SIS particle filter in a simulated environment. */\n    double surv_x = 1000.0;\n    double surv_y = 1000.0;\n    unsigned int num_particle_x = 100;\n    unsigned int num_particle_y = 100;\n    unsigned int num_particle = num_particle_x * num_particle_y;\n    Vector4d initial_state(10.0f, 0.0f, 10.0f, 0.0f);\n    unsigned int simulation_time = 10;\n    std::size_t state_size = 4;\n\n    /* Step 1 - Initialization */\n    /* Initialize initialization class. */\n    std::unique_ptr<ParticleSetInitialization> grid_initialization = utils::make_unique<InitSurveillanceAreaGrid>(surv_x, surv_y, num_particle_x, num_particle_y);\n\n\n    /* Step 2 - Prediction */\n    /* Step 2.1 - Define the state model */\n    /* Initialize a white noise acceleration state model. */\n    std::unique_ptr<StateModel> wna = utils::make_unique<WhiteNoiseAcceleration>();\n\n    /* Step 2.1.1 - Define a decoration for the state model */\n    /* Initialize a white noise acceleration decorator. */\n    std::unique_ptr<StateModel> decorated_wna = utils::make_unique<DecoratedWNA>(std::move(wna));\n\n    /* Step 2.2 - Define the prediction step */\n    /* Initialize the particle filter prediction step and pass the ownership of the state model. */\n    std::unique_ptr<PFPrediction> pf_prediction = utils::make_unique<DrawParticles>();\n    pf_prediction->setStateModel(std::move(decorated_wna));\n\n    /* Step 2.2.1 - Define a decoration for the prediction step */\n    /* Initialize a particle filter prediction decorator. */\n    std::unique_ptr<PFPrediction> decorated_prediction = utils::make_unique<DecoratedDrawParticles>(std::move(pf_prediction));\n\n\n    /* Step 3 - Correction */\n    /* Step 3.1 - Define where the measurement are originated from (either simulated or from a real process) */\n    /* Initialize simulaterd target model, a white noise acceleration, and measurements, a MeasurementModel decoration for the linear sensor. */\n    std::unique_ptr<StateModel> target_model = utils::make_unique<WhiteNoiseAcceleration>();\n    std::unique_ptr<SimulatedStateModel> simulated_state_model = utils::make_unique<SimulatedStateModel>(std::move(target_model), initial_state, simulation_time);\n\n    /* Initialize a measurement model (a linear sensor reading x and y coordinates). */\n    std::unique_ptr<MeasurementModel> simulated_linear_sensor = utils::make_unique<SimulatedLinearSensor>(std::move(simulated_state_model));\n\n    /* Step 3.1.1 - Define a decoration for the measurement model */\n    /* Initialize a white noise acceleration decorator */\n    std::unique_ptr<MeasurementModel> decorated_linearsensor = utils::make_unique<DecoratedLinearSensor>(std::move(simulated_linear_sensor));\n\n    /* Step 3.2 - Define the likelihood model */\n    /* Initialize the the exponential likelihood, a PFCorrection decoration of the particle filter correction step. */\n    std::unique_ptr<LikelihoodModel> exp_likelihood = utils::make_unique<GaussianLikelihood>();\n\n    /* Step 3.3 - Define the correction step */\n    /* Initialize the particle filter correction step and pass the ownership of the measurement model. */\n    std::unique_ptr<PFCorrection> pf_correction = utils::make_unique<BoostrapCorrection>();\n    pf_correction->setLikelihoodModel(std::move(exp_likelihood));\n    pf_correction->setMeasurementModel(std::move(decorated_linearsensor));\n\n    /* Initialize a update particle decorator */\n    std::unique_ptr<PFCorrection> decorated_correction = utils::make_unique<DecoratedBootstrapCorrection>(std::move(pf_correction));\n\n\n    /* Step 4 - Resampling */\n    /* Initialize a resampling algorithm */\n    std::unique_ptr<Resampling> resampling = utils::make_unique<Resampling>();\n\n\n    /* Step 5 - Assemble the particle filter */\n    std::cout << \"Constructing SIS particle filter...\" << std::flush;\n    SISSimulation sis_pf(num_particle, state_size, simulation_time, std::move(grid_initialization), std::move(decorated_prediction), std::move(decorated_correction), std::move(resampling));\n    std::cout << \"done!\" << std::endl;\n\n\n    /* Step 6 - Prepare the filter to be run */\n    std::cout << \"Booting SIS particle filter...\" << std::flush;\n    sis_pf.boot();\n    std::cout << \"completed!\" << std::endl;\n\n\n    /* Step 7 - Run the filter and wait until it is closed */\n    /* Note that since this is a simulation, the filter will end upon simulation termination */\n    std::cout << \"Running SIS particle filter...\" << std::flush;\n    sis_pf.run();\n    std::cout << \"waiting...\" << std::endl;\n    if (!sis_pf.wait())\n        return EXIT_FAILURE;\n    std::cout << \"completed!\" << std::endl;\n\n\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "1ed9e98c86f115bd46e080472df40811d9c4d1a1", "size": 8462, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_SIS_Decorators/main.cpp", "max_stars_repo_name": "vesor/bayes-filters-lib", "max_stars_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T02:52:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T07:06:39.000Z", "max_issues_repo_path": "test/test_SIS_Decorators/main.cpp", "max_issues_repo_name": "vesor/bayes-filters-lib", "max_issues_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_SIS_Decorators/main.cpp", "max_forks_repo_name": "vesor/bayes-filters-lib", "max_forks_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T08:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T08:20:28.000Z", "avg_line_length": 37.4424778761, "max_line_length": 189, "alphanum_fraction": 0.7240605058, "num_tokens": 1964, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2359099410213478}}
{"text": "#include \"alchemist.h\"\n#include \"data_stream.h\"\n#include <iostream>\n#include <fstream>\n#include <cstdlib>\n#include <sys/stat.h>\n#include <map>\n#include <random>\n#include <sstream>\n#include <boost/asio.hpp>\n#include <boost/chrono.hpp>\n#include <boost/thread/thread.hpp>\n#include <boost/tokenizer.hpp>\n#include \"arpackpp/arrssym.h\"\n#include \"spdlog/spdlog.h\"\n#include <time.h>\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace alchemist {\n\nusing namespace El;\n\nstruct Driver {\n  mpi::communicator world;\n  DataInputStream input;\n  DataOutputStream output;\n  std::vector<WorkerInfo> workers;\n  std::map<MatrixHandle, MatrixDescriptor> matrices;\n  uint32_t nextMatrixId;\n  std::shared_ptr<spdlog::logger> log;\n\n  Driver(const mpi::communicator &world, std::istream &is, std::ostream &os, std::shared_ptr<spdlog::logger> log);\n  void issue(const Command &cmd);\n  MatrixHandle registerMatrix(size_t numRows, size_t numCols);\n  void reshapeMatrix(MatrixHandle handle, size_t numRows, size_t numCols);\n  int main();\n\n  void handle_newMatrix();\n  void handle_matrixMul();\n  void handle_matrixDims();\n  void handle_computeThinSVD();\n  void handle_getMatrixRows();\n  void handle_getTranspose();\n  void handle_kmeansClustering();\n  void handle_truncatedSVD();\n  void handle_SkylarkKRR();\n  void handle_SkylarkLSQR();\n  void handle_FactorizedCGSolver();\n  void handle_RandomFourierFeatures();\n  void handle_ReadHDF5();\n  void handle_normalizeMatInPlace();\n};\n\nDriver::Driver(const mpi::communicator &world, std::istream &is, std::ostream &os, std::shared_ptr<spdlog::logger> log) :\n    world(world), input(is), output(os), log(log), nextMatrixId(42) {\n}\n\nvoid Driver::issue(const Command &cmd) {\n  const Command *cmdptr = &cmd;\n  mpi::broadcast(world, cmdptr, 0);\n}\n\nMatrixHandle Driver::registerMatrix(size_t numRows, size_t numCols) {\n  MatrixHandle handle{nextMatrixId++};\n  MatrixDescriptor info(handle, numRows, numCols);\n  matrices.insert(std::make_pair(handle, info));\n  return handle;\n}\n\nvoid Driver::reshapeMatrix(MatrixHandle handle, size_t numRows, size_t numCols) {\n    matrices.erase(handle);\n    MatrixDescriptor info(handle, numRows, numCols);\n    matrices.insert(std::make_pair(handle, info));\n}\n\nint Driver::main() {\n\n  // get WorkerInfo\n  auto numWorkers = world.size() - 1;\n  workers.resize(numWorkers);\n  for(auto id = 0; id < numWorkers; ++id) {\n    world.recv(id + 1, 0, workers[id]);\n  }\n  log->info(\"{} workers ready, sending hostnames and ports to Spark\", numWorkers);\n\n  // handshake\n  ENSURE(input.readInt() == 0xABCD);\n  ENSURE(input.readInt() == 0x1);\n  output.writeInt(0xDCBA);\n  output.writeInt(0x1);\n  output.writeInt(numWorkers);\n  for(auto id = 0; id < numWorkers; ++id) {\n    output.writeString(workers[id].hostname);\n    output.writeInt(workers[id].port);\n  }\n  output.flush();\n\n  bool shouldExit = false;\n  while(!shouldExit) {\n    uint32_t typeCode = input.readInt();\n    log->info(\"Received code {:#x}\", typeCode);\n\n    switch(typeCode) {\n      // shutdown\n      case 0xFFFFFFFF:\n        shouldExit = true;\n        issue(HaltCommand());\n        output.writeInt(0x1);\n        output.flush();\n        break;\n\n      // new matrix\n      case 0x1:\n        handle_newMatrix();\n        break;\n\n      // matrix multiplication\n      case 0x2:\n        handle_matrixMul();\n        break;\n\n      // get matrix dimensions\n      case 0x3:\n        handle_matrixDims();\n        break;\n\n      // return matrix to Spark\n      case 0x4:\n        handle_getMatrixRows();\n        break;\n\n      case 0x5:\n        handle_computeThinSVD();\n        break;\n\n      case 0x6:\n        handle_getTranspose();\n        break;\n\n      case 0x7:\n        handle_kmeansClustering();\n        break;\n\n      case 0x8:\n        handle_truncatedSVD();\n        break;\n\n      case 0x9:\n        handle_SkylarkKRR();\n        break;\n\n      case 0x10:\n        handle_SkylarkLSQR();\n        break;\n\n      case 0x11:\n        handle_FactorizedCGSolver();\n        break;\n\n      case 0x12:\n        handle_RandomFourierFeatures();\n        break;\n\n      case 0x13:\n        handle_ReadHDF5();\n        break;\n\n      case 0x14:\n        handle_normalizeMatInPlace();\n        break;\n\n      default:\n        log->error(\"Unknown typeCode {#x}\", typeCode);\n        abort();\n    }\n    log->info(\"Waiting on next command\");\n  }\n\n  // wait for workers to reach exit\n  world.barrier();\n  return EXIT_SUCCESS;\n}\n\n// A = USV\n/*\nvoid Driver::handle_computeLowrankSVD() {\n  uint32_t inputMat = input.readInt();\n  uint32_t kRank = input.readInt();\n  uint32_t whichFactors = input.readInt(); // 0 = U, 1 = U and S, 2 = V and S, 3/default = U, S, and V\n\n  MatrixHandle U;\n  MatrixHandle S;\n  MatrixHandle V;\n\n  // TODO: register the U, S, V factors with false newmatrixcommands to track them\n  switch(whichFactors) {\n    case 0: U = MatrixHandle{nextMatrixId++};\n            break;\n    case 1: U = MatrixHandle{nextMatrixId++};\n            S = MatrixHandle{nextMatrixId++};\n            break;\n    case 2: V = MatrixHandle{nextMatrixId++};\n            S = MatrixHandle{nextMatrixId++};\n            break;\n    default: U = MatrixHandle{nextMatrixId++};\n             S = MatrixHandle{nextMatrixId++};\n             V = MatrixHandle{nextMatrixId++};\n             break;\n  }\n\n  LowrankSVDCommand cmd(MatrixHandle{inputMat}, whichFactors, krank, U, S, V);\n  issue(cmd);\n\n  output.writeInt(0x1); // statusCode\n  switch(whichFactors) {\n    case 0: output.writeInt(U.id);\n            break;\n    case 1: output.writeInt(U.id);\n            output.writeInt(S.id);\n            break;\n    case 2: output.writeInt(V.id);\n            output.writeInt(S.id);\n            break;\n    default: output.writeInt(U.id);\n             output.writeInt(S.id);\n             output.writeInt(V.id);\n             break;\n  }\n  output.flush();\n\n  // wait for command to finish\n  world.barrier();\n  output.writeInt(0x1);\n  output.flush();\n}\n*/\n\nvoid Driver::handle_RandomFourierFeatures() {\n    MatrixHandle A{input.readInt()};\n    uint32_t numRandFeatures = input.readInt();\n    double sigma = input.readDouble();\n    uint32_t seed = input.readInt();\n\n    auto numRows = matrices[A].numRows;\n    uint32_t d = matrices[A].numCols;\n    MatrixHandle X = registerMatrix(numRows, numRandFeatures);\n\n    log->info(\"Computing Fourier Random Features on feature matrix {}\");\n    log->info(\"Input dim: {}, Output dim: {}, number of points: {}\", d, numRandFeatures, numRows);\n\n    RandomFourierFeaturesCommand cmd(A, X, numRandFeatures, sigma, seed);\n    issue(cmd);\n\n    world.barrier(); // wait for it to finish\n    output.writeInt(0x1);\n    output.writeInt(X.id);\n    output.flush();\n    log->info(\"Finished computing Fourier Random Features, stored matrix as {}\", X);\n}\n\nvoid Driver::handle_normalizeMatInPlace() {\n    MatrixHandle A{input.readInt()};\n    log->info(\"Normalizing matrix {} in place by zero meaning the rows and setting the columns to have stdev 1\", A);\n\n    NormalizeMatInPlaceCommand cmd(A);\n    issue(cmd);\n\n    output.writeInt(0x1);\n    log->info(\"Finished normalizing matrix {} in place\", A);\n}\n\nvoid Driver::handle_ReadHDF5() {\n    std::string fname = input.readString();\n    std::string varname = input.readString();\n    int colreplicas = input.readInt();\n    MatrixHandle A = registerMatrix(0, 0);\n    \n    log->info(\"Reading variable {} from file {} and replicating columnwise {} times\", varname, fname, colreplicas);\n    ReadHDF5Command cmd(A, fname, varname, colreplicas);\n    issue(cmd);\n\n    El::Int numRows, numCols;\n    world.recv(1, mpi::any_tag, numRows);\n    world.recv(1, mpi::any_tag, numCols);\n    world.barrier();\n\n    reshapeMatrix(A, numRows, numCols);\n    log->info(\"Loaded matrix is {}-by-{}\", matrices[A].numRows, matrices[A].numCols);\n    output.writeInt(0x1);\n    output.writeInt(A.id);\n    output.flush();\n    log->info(\"Finished loading variable from HDF5 file\");\n}\n\nvoid Driver::handle_FactorizedCGSolver() {\n  MatrixHandle featureMat{input.readInt()};\n  MatrixHandle targetMat{input.readInt()};\n  double lambda = input.readDouble();\n  uint32_t maxIters = input.readInt();\n\n  auto numfeatures = matrices[featureMat].numCols;\n  auto numtargets = matrices[targetMat].numCols;\n  MatrixHandle coefs = registerMatrix(numfeatures, numtargets);\n\n  log->info(\"Starting factorized CG solver on feature matrix {} and target matrix {}\", featureMat, targetMat);\n  log->info(\"lambda={}, maxIters={}\", lambda, maxIters);\n\n  FactorizedCGSolverCommand cmd(featureMat, targetMat, coefs, lambda, maxIters);\n  issue(cmd);\n\n  world.barrier(); // wait for it to finish\n  output.writeInt(0x1);\n  output.writeInt(coefs.id);\n  output.flush();\n  log->info(\"Finished CG solve, stored coefficient matrix as {}\", coefs);\n}\n\nvoid Driver::handle_SkylarkKRR() {\n    MatrixHandle featureMat{input.readInt()};\n    MatrixHandle targetMat{input.readInt()};\n    bool regression = input.readInt() > 0? true : false;\n    uint32_t lossfunction = input.readInt();\n    uint32_t regularizer = input.readInt();\n    uint32_t kernel = input.readInt();\n    double kernelparam = input.readDouble();\n    double kernelparam2 = input.readDouble();\n    double kernelparam3 = input.readDouble();\n    double lambda = input.readDouble();\n    uint32_t maxiter = input.readInt();\n    double tolerance = input.readDouble();\n    double rho = input.readDouble();\n    uint32_t seed = input.readInt();\n    uint32_t randomfeatures = input.readInt();\n    uint32_t numfeaturepartitions = input.readInt();\n\n    log->info(\"Starting Skylark's ADMM KRR solver on feature matrix {} and target matrix {}\", featureMat, targetMat);\n    log->info(\"<should list arguments here>\");\n\n    auto numfeatures = matrices[featureMat].numCols;\n    auto numtargets = matrices[targetMat].numCols;\n    MatrixHandle coefs = registerMatrix(numfeatures, numtargets);\n\n    SkylarkKernelSolverCommand cmd(featureMat, targetMat, coefs, regression, \n        lossfunction, regularizer, kernel, kernelparam, kernelparam2,\n        kernelparam3, lambda, maxiter, tolerance, rho, seed, randomfeatures,\n        numfeaturepartitions);\n    issue(cmd);\n\n    world.barrier(); // wait for it to finish\n    log->info(\"Finished calling Skylark's ADMM Kernel solver for this KRR problem\");\n    output.writeInt(0x1);\n    output.writeInt(coefs.id);\n    output.flush();\n    log->info(\"Finished KRR solve, stored coeffcient matrix as {}\", coefs);\n}\n\nvoid Driver::handle_SkylarkLSQR() {\n  MatrixHandle A{input.readInt()};\n  MatrixHandle B{input.readInt()};\n  double tolerance = input.readDouble();\n  uint32_t iter_lim = input.readInt();\n\n  auto p = matrices[A].numCols;\n  auto m = matrices[B].numCols;\n  MatrixHandle X = registerMatrix(p, m);\n\n  log->info(\"Starting Skylark's LSQR solver on feature matrix {} and target matrix {}\", A, B);\n  log->info(\"Tolerance: {}\", tolerance);\n  log->info(\"Iteration Limit: {}\", iter_lim);\n  log->info(\"Result will be a {}-by-{} matrix\", p, m);\n\n  SkylarkLSQRSolverCommand cmd(A, B, X, tolerance, iter_lim);\n  issue(cmd);\n\n  world.barrier(); // wait for it to finish\n  log->info(\"Finished call to Skylark's LSQR solver\");\n  output.writeInt(0x1);\n  output.writeInt(X.id);\n  output.flush();\n  log->info(\"Finished LSQR computation\");\n}\n\n// TODO: the cluster centers should be stored locally on driver and reduced/broadcasted. the current\n// way of updating kmeans centers is ridiculous\n// TODO: currently only implements kmeans||\nvoid Driver::handle_kmeansClustering() {\n  MatrixHandle inputMat{input.readInt()};\n  uint32_t numCenters = input.readInt();\n  uint32_t maxnumIters = input.readInt(); // how many iteration of Lloyd's algorithm to use\n  uint32_t initSteps = input.readInt(); // number of initialization steps to use in kmeans||\n  double changeThreshold = input.readDouble(); // if all the centers change by Euclidean distance less than changeThreshold, then we stop the iterations\n  uint32_t method = input.readInt(); // which initialization method to use to choose initial cluster center guesses\n  uint64_t seed = input.readLong(); // randomness seed used in driver and workers\n\n  log->info(\"Starting K-means on matrix {}\", inputMat);\n  log->info(\"numCenters = {}, maxnumIters = {}, initSteps = {}, changeThreshold = {}, method = {}, seed = {}\",\n      numCenters, maxnumIters, initSteps, changeThreshold, method, seed);\n\n  if (changeThreshold < 0.0 || changeThreshold > 1.0) {\n    log->error(\"Unreasonable change threshold in k-means: {}\", changeThreshold);\n    abort();\n  }\n  if (method != 1) {\n    log->warn(\"Sorry, only k-means|| initialization has been implemented, so ignoring your choice of method {}\", method);\n  }\n\n  auto n = matrices[inputMat].numRows;\n  auto d = matrices[inputMat].numCols;\n  MatrixHandle centersHandle = this->registerMatrix(numCenters, d);\n  MatrixHandle assignmentsHandle = this->registerMatrix(n, 1);\n  KMeansCommand cmd(inputMat, numCenters, method, initSteps, changeThreshold, seed, centersHandle, assignmentsHandle);\n  issue(cmd); // initial call initializes stuff and waits for next command\n\n  /******** START of kmeans|| initialization ********/\n  std::mt19937 gen(seed);\n  std::uniform_int_distribution<unsigned long> dis(0, n-1);\n  uint32_t rowidx = dis(gen);\n  std::vector<double> initialCenter(d);\n\n  mpi::broadcast(world, rowidx, 0); // tell the workers which row to use as initialization in kmeans||\n  world.barrier(); // wait for workers to return oversampled cluster centers and sizes\n\n  std::vector<uint32_t> clusterSizes;\n  std::vector<MatrixXd> initClusterCenters;\n  world.recv(1, mpi::any_tag, clusterSizes);\n  world.recv(1, mpi::any_tag, initClusterCenters);\n  world.barrier();\n\n  log->info(\"Retrieved the k-means|| oversized set of potential cluster centers\");\n  log->debug(\"{}\", initClusterCenters);\n\n  // use kmeans++ locally to find the initial cluster centers\n  std::vector<double> weights;\n  weights.reserve(clusterSizes.size());\n  std::for_each(clusterSizes.begin(), clusterSizes.end(), [&weights](const uint32_t & cnt){ weights.push_back((double) cnt); });\n  MatrixXd clusterCenters(numCenters, d);\n\n  kmeansPP(gen(), initClusterCenters, weights, clusterCenters, 30); // same number of maxIters as spark kmeans\n\n  log->info(\"Ran local k-means on the driver to determine starting cluster centers\");\n  log->debug(\"{}\", clusterCenters);\n\n  mpi::broadcast(world, clusterCenters.data(), numCenters*d, 0);\n  /******** END of kMeans|| initialization ********/\n\n  /******** START of Lloyd's algorithm iterations ********/\n  double percentAssignmentsChanged = 1.0;\n  bool centersMovedQ = true;\n  uint32_t numChanged = 0;\n  uint32_t numIters = 0;\n  std::vector<uint32_t> parClusterSizes(numCenters);\n  std::vector<uint32_t> zerosVector(numCenters);\n\n  for(uint32_t clusterIdx = 0; clusterIdx < numCenters; clusterIdx++)\n    zerosVector[clusterIdx] = 0;\n\n  uint32_t command = 1; // do another iteration\n  while (centersMovedQ && numIters++ < maxnumIters)  {\n    log->info(\"Starting iteration {} of Lloyd's algorithm, {} percentage changed in last iter\",\n        numIters, percentAssignmentsChanged*100);\n    numChanged = 0;\n    for(uint32_t clusterIdx = 0; clusterIdx < numCenters; clusterIdx++)\n      parClusterSizes[clusterIdx] = 0;\n    command = 1; // do a basic iteration\n    mpi::broadcast(world, command, 0);\n    mpi::reduce(world, (uint32_t) 0, numChanged, std::plus<int>(), 0);\n    mpi::reduce(world, zerosVector.data(), numCenters, parClusterSizes.data(), std::plus<uint32_t>(), 0);\n    world.recv(1, mpi::any_tag, centersMovedQ);\n    percentAssignmentsChanged = ((double) numChanged)/n;\n\n    for(uint32_t clusterIdx = 0; clusterIdx < numCenters; clusterIdx++) {\n      if (parClusterSizes[clusterIdx] == 0) {\n        // this is an empty cluster, so randomly pick a point in the dataset\n        // as that cluster's centroid\n        centersMovedQ = true;\n        command = 2; // reinitialize this cluster center\n        uint32_t rowIdx = dis(gen);\n        mpi::broadcast(world, command, 0);\n        mpi::broadcast(world, clusterIdx, 0);\n        mpi::broadcast(world, rowIdx, 0);\n        world.barrier();\n      }\n    }\n\n  }\n  command = 0xf; // terminate and finalize the k-means centers and assignments as distributed matrices\n  mpi::broadcast(world, command, 0);\n  double objVal = 0.0;\n  mpi::reduce(world, 0.0, objVal, std::plus<double>(), 0);\n  world.barrier();\n\n  /******** END of Lloyd's iterations ********/\n\n  log->info(\"Finished Lloyd's algorithm: took {} iterations, final objective value {}\", numIters, objVal);\n  output.writeInt(0x1);\n  output.writeInt(assignmentsHandle.id);\n  output.writeInt(centersHandle.id);\n  output.writeInt(numIters);\n  output.flush();\n}\n\nvoid Driver::handle_getTranspose() {\n  MatrixHandle inputMat{input.readInt()};\n  log->info(\"Constructing the transpose of matrix {}\", inputMat);\n\n  auto numRows = matrices[inputMat].numCols;\n  auto numCols = matrices[inputMat].numRows;\n  MatrixHandle transposeHandle = registerMatrix(numRows, numCols);\n  TransposeCommand cmd(inputMat, transposeHandle);\n  issue(cmd);\n\n  world.barrier(); // wait for command to finish\n  output.writeInt(0x1);\n  output.writeInt(transposeHandle.id);\n  log->info(\"Wrote handle for transpose\");\n  output.writeInt(0x1);\n  output.flush();\n}\n\n// CAVEAT: Assumes tall-and-skinny for now, doesn't allow many options for controlling\n// LIMITATIONS: assumes V small enough to fit on one machine (so can use ARPACK instead of PARPACK), but still distributes U,S,V and does distributed computations not needed\nvoid Driver::handle_truncatedSVD() {\n  log->info(\"Starting truncated SVD computation\");\n  MatrixHandle inputMat{input.readInt()};\n  uint32_t k = input.readInt();\n  uint32_t method = input.readInt();\n\n  int LOCALEIGS = 0; // TODO: make these an enumeration, and global to Alchemist\n  int LOCALEIGSPRECOMPUTE = 1;\n  int DISTEIGS = 2; \n\n  MatrixHandle UHandle{nextMatrixId++};\n  MatrixHandle SHandle{nextMatrixId++};\n  MatrixHandle VHandle{nextMatrixId++};\n\n  auto m = matrices[inputMat].numRows;\n  auto n = matrices[inputMat].numCols;\n  TruncatedSVDCommand cmd(inputMat, UHandle, SHandle, VHandle, k, method);\n  issue(cmd);\n\n  if (method == DISTEIGS) {\n      log->info(\"using distributed mat-vec prods against A, then A tranpose\");\n  }\n  if (method == LOCALEIGS) {\n      log->info(\"using local mat-vec prods computed on the fly against the local Gramians\");\n  }\n  if (method == LOCALEIGSPRECOMPUTE) {\n      log->info(\"using local mat-vec prods against the precomputed local Gramians\");\n  }\n\n  ARrcSymStdEig<double> prob(n, k, \"LM\");\n  uint32_t command;\n  std::vector<double> zerosVector(n);\n  for(uint32_t idx = 0; idx < n; idx++)\n    zerosVector[idx] = 0;\n\n  int iterNum = 0;\n\n  while (!prob.ArnoldiBasisFound()) {\n    prob.TakeStep();\n    ++iterNum;\n    if(iterNum % 20 == 0) {\n        log->info(\"Computed {} mv products\", iterNum);\n    }\n    if (prob.GetIdo() == 1 || prob.GetIdo() == -1) {\n      command = 1;\n      mpi::broadcast(world, command, 0);\n      if (method == LOCALEIGS || method == LOCALEIGSPRECOMPUTE) {\n          mpi::broadcast(world, prob.GetVector(), n, 0);\n          mpi::reduce(world, zerosVector.data(), n, prob.PutVector(), std::plus<double>(), 0);\n      }\n      if (method == DISTEIGS) {\n          world.send(1, 0, prob.GetVector(), n);\n          world.recv(1, 0, prob.PutVector(), n);\n      }\n    }\n  }\n\n  prob.FindEigenvectors();\n  uint32_t nconv = prob.ConvergedEigenvalues();\n  uint32_t niters = prob.GetIter();\n  log->info(\"Done after {} Arnoldi iterations, converged to {} eigenvectors of size {}\", niters, nconv, n);\n\n  //NB: it may be the case that n*nconv > 4 GB, then have to be careful!\n  // assuming tall and skinny A for now\n  MatrixXd rightVecs(n, nconv);\n  log->info(\"Allocated matrix for right eigenvectors of A'*A\");\n  // Eigen uses column-major layout by default!\n  for(uint32_t idx = 0; idx < nconv; idx++)\n    std::memcpy(rightVecs.col(idx).data(), prob.RawEigenvector(idx), n*sizeof(double));\n  log->info(\"Copied right eigenvectors into allocated storage\");\n\n  // Populate U, V, S\n  command = 2;\n  mpi::broadcast(world, command, 0);\n  mpi::broadcast(world, nconv, 0);\n  log->info(\"Broadcasted command and number of converged eigenvectors\");\n  mpi::broadcast(world, rightVecs.data(), n*nconv, 0);\n  log->info(\"Broadcasted right eigenvectors\"); \n  mpi::broadcast(world, prob.RawEigenvalues(), nconv, 0);\n  log->info(\"Broadcasted eigenvalues\");\n\n  MatrixDescriptor Uinfo(UHandle, m, nconv);\n  MatrixDescriptor Sinfo(SHandle, nconv, 1);\n  MatrixDescriptor Vinfo(VHandle, n, nconv);\n  ENSURE(matrices.insert(std::make_pair(UHandle, Uinfo)).second);\n  ENSURE(matrices.insert(std::make_pair(SHandle, Sinfo)).second);\n  ENSURE(matrices.insert(std::make_pair(VHandle, Vinfo)).second);\n\n  log->info(\"Waiting on workers to store U,S,V\");\n\n  world.barrier();\n  log->info(\"Writing ok status followed by U,S,V handles\");\n  output.writeInt(0x1);\n  output.writeInt(UHandle.id);\n  output.writeInt(SHandle.id);\n  output.writeInt(VHandle.id);\n  output.flush();\n}\n\nvoid Driver::handle_computeThinSVD() {\n  MatrixHandle inputMat{input.readInt()};\n\n  // this needs to be done automatically rather than hand-coded. e.g. what if\n  // we switch to determining rank by sing-val thresholding instead of doing thin SVD?\n  auto m = matrices[inputMat].numRows;\n  auto n = matrices[inputMat].numCols;\n  auto k = std::min(m,n);\n  MatrixHandle Uhandle = registerMatrix(m, k);\n  MatrixHandle Shandle = registerMatrix(k, 1);\n  MatrixHandle Vhandle = registerMatrix(n, k);\n  ThinSVDCommand cmd(inputMat, Uhandle, Shandle, Vhandle);\n  issue(cmd);\n\n  output.writeInt(0x1); // statusCode\n  output.writeInt(Uhandle.id);\n  output.writeInt(Shandle.id);\n  output.writeInt(Vhandle.id);\n  output.flush();\n\n  // wait for command to finish\n  world.barrier();\n  log->info(\"Done with SVD computation\");\n  output.writeInt(0x1);\n  output.flush();\n}\n\nvoid Driver::handle_matrixMul() {\n  MatrixHandle matA{input.readInt()};\n  MatrixHandle matB{input.readInt()};\n  log->info(\"Multiplying matrices {} and {}\", matA, matB);\n\n  auto numRows = matrices[matA].numRows;\n  auto numCols = matrices[matB].numCols;\n  MatrixHandle destHandle = registerMatrix(numRows, numCols);\n  MatrixMulCommand cmd(destHandle, matA, matB);\n  issue(cmd);\n\n  // tell spark id of resulting matrix\n  output.writeInt(0x1); // statusCode\n  output.writeInt(destHandle.id);\n  output.flush();\n\n  // wait for it to finish\n  world.barrier();\n  output.writeInt(0x1);\n  output.flush();\n}\n\nvoid Driver::handle_matrixDims() {\n  MatrixHandle matrixHandle{input.readInt()};\n  log->info(\"Looking up dimensions for matrix {}\", matrixHandle.id);\n  auto info = matrices[matrixHandle];\n  log->info(\"Returning dimensions for matrix {}: {}-by-{}\", matrixHandle.id, info.numRows, info.numCols);\n  output.writeInt(0x1);\n  output.writeLong(info.numRows);\n  output.writeLong(info.numCols);\n  output.flush();\n\n}\n\nvoid Driver::handle_getMatrixRows() {\n  MatrixHandle handle{input.readInt()};\n  uint64_t layoutLen = input.readLong();\n  std::vector<uint32_t> layout;\n  layout.reserve(layoutLen);\n  for(uint64_t part = 0; part < layoutLen; ++part) {\n    layout.push_back(input.readInt());\n  }\n  log->info(\"Returning matrix {} to Spark\", handle);\n\n  MatrixGetRowsCommand cmd(handle, layout);\n  issue(cmd);\n\n  // tell Spark to start asking for rows\n  output.writeInt(0x1);\n  output.flush();\n\n  // wait for it to finish\n  world.barrier();\n  output.writeInt(0x1);\n  output.flush();\n}\n\nvoid Driver::handle_newMatrix() {\n  // read args\n  uint64_t numRows = input.readLong();\n  uint64_t numCols = input.readLong();\n\n  // assign id and notify workers\n  MatrixHandle handle = registerMatrix(numRows, numCols);\n  NewMatrixCommand cmd(matrices[handle]);\n  log->info(\"Recieving new matrix {}, with dimensions {}x{}\", handle, numRows, numCols);\n  issue(cmd);\n\n  output.writeInt(0x1);\n  output.writeInt(handle.id);\n  output.flush();\n\n  // tell spark which worker expects each row\n  std::vector<int> rowWorkerAssignments(numRows, 0);\n  std::vector<uint64_t> rowsOnWorker;\n  std::vector<uint32_t> numRowsOnEachWorker(world.size() -1, 0);\n  for(int workerIdx = 1; workerIdx < world.size(); workerIdx++) {\n    world.recv(workerIdx, 0, rowsOnWorker);\n    numRowsOnEachWorker[workerIdx - 1] = rowsOnWorker.size();\n    world.barrier();\n    for(auto rowIdx: rowsOnWorker) {\n      rowWorkerAssignments[rowIdx] = workerIdx;\n    }\n  }\n\n  log->info(\"Sending list of which worker each row should go to\");\n  output.writeInt(0x1); // statusCode\n  std::stringstream ss;\n  for(auto workerIdx: rowWorkerAssignments) {\n    output.writeInt(workerIdx);\n    ALCHEMIST_TRACE(ss << workerIdx << ' ');\n  }\n  ALCHEMIST_TRACE(log->info(ss.str().c_str()));\n  \n  for(uint32_t workerIdx = 1; workerIdx < world.size(); workerIdx++)\n    log->info(\"Worker with rank {} will receive {} rows\", workerIdx, numRowsOnEachWorker[workerIdx-1]);\n\n  output.flush();\n\n  log->info(\"Waiting for spark to finish sending data to the workers\");\n  world.barrier();\n  output.writeInt(0x1);  // statusCode\n  output.flush();\n  log->info(\"Entire matrix has been received\");\n}\n\ninline bool exist_test (const std::string& name) {\n    struct stat buffer;\n    return (stat(name.c_str(), &buffer) == 0); \n}\n\nint driverMain(const mpi::communicator &world, int argc, char *argv[]) {\n  //log to console as well as file (single-threaded logging)\n  //TODO: allow to specify log directory, log level, etc.\n  time_t rawtime = time(0);\n  struct tm * timeinfo = localtime(&rawtime);\n  char buf[80];\n  strftime(buf, 80, \"%F-%T\", timeinfo);\n  std::shared_ptr<spdlog::logger> log;\n  std::vector<spdlog::sink_ptr> sinks;\n  sinks.push_back(std::make_shared<spdlog::sinks::ansicolor_stderr_sink_st>());\n  sinks.push_back(std::make_shared<spdlog::sinks::simple_file_sink_st>(str(format(\"driver-%s.log\") % buf)));\n  log = std::make_shared<spdlog::logger>(\"driver\", std::begin(sinks), std::end(sinks));\n  //log->flush_on(spdlog::level::warn); // flush whenever warning or more critical message is logged\n  //log->set_level(spdlog::level::info); // only log stuff at or above info level, for production\n  log->flush_on(spdlog::level::info); // flush always, for debugging\n  log->info(\"Started Driver\");\n  log->info(\"Max number of OpenMP threads: {}\", omp_get_max_threads());\n\n  char machine[255];\n  char port[255];\n\n  if (argc == 3) { // we are on a non-NERSC system, so passed in Spark driver machine name and port\n      log->info(\"Non-NERSC system assumed\");\n      log->info(\"Connecting to Spark executor at {}:{}\", argv[1], argv[2]);\n      std::strcpy(machine, argv[1]);\n      std::strcpy(port, argv[2]);\n  } else { // assume we are on NERSC, so look in a specific location for a file containing the machine name and port\n      char const* tmp = std::getenv(\"SPARK_WORKER_DIR\");\n      std::string sockPath;\n      if (tmp == NULL) {\n          log->info(\"Couldn't find the SPARK_WORKER_DIR variable\");\n          world.abort(1);\n      } else {\n        sockPath = std::string(tmp) + \"/connection.info\";\n      }\n      log->info(\"NERSC system assumed\");\n      log->info(\"Searching for connection information in file {}\", sockPath);\n\n      while(!exist_test(sockPath)) {\n          boost::this_thread::sleep_for(boost::chrono::milliseconds(50));\n      }\n      // now wait for a while for the connection file to be completely written, hopefully is enough time\n      // TODO: need a more robust way of ensuring this is the case\n      boost::this_thread::sleep_for(boost::chrono::milliseconds(500));\n\n      std::string sockSpec;\n      std::ifstream infile(sockPath);\n      std::getline(infile, sockSpec);\n      infile.close();\n      boost::tokenizer<> tok(sockSpec);\n      boost::tokenizer<>::iterator iter=tok.begin();\n      std::string machineName = *iter;\n      std::string portName = *(++iter);\n\n      log->info(\"Connecting to Spark executor at {}:{}\", machineName, portName);\n      strcpy(machine, machineName.c_str());\n      strcpy(port, portName.c_str());\n  }\n\n  using boost::asio::ip::tcp;\n  boost::asio::ip::tcp::iostream stream(machine, port);\n  ENSURE(stream);\n  stream.rdbuf()->non_blocking(false);\n  auto result = Driver(world, stream, stream, log).main();\n  return result;\n}\n\n} // namespace alchemist\n", "meta": {"hexsha": "c683d70503e1324ed16d9d51a815fc90734111b0", "size": 28001, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/main/cpp/driver.cpp", "max_stars_repo_name": "jey/alchemist", "max_stars_repo_head_hexsha": "7b5f0e68a96a3f13f624b18669e1c68fff24d375", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T15:18:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-14T07:48:23.000Z", "max_issues_repo_path": "core/src/main/cpp/driver.cpp", "max_issues_repo_name": "jey/Alchemist", "max_issues_repo_head_hexsha": "7b5f0e68a96a3f13f624b18669e1c68fff24d375", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-07-17T20:02:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-27T12:17:06.000Z", "max_forks_repo_path": "core/src/main/cpp/driver.cpp", "max_forks_repo_name": "jey/alchemist", "max_forks_repo_head_hexsha": "7b5f0e68a96a3f13f624b18669e1c68fff24d375", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-05-27T20:44:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-01T15:02:44.000Z", "avg_line_length": 33.7768395657, "max_line_length": 173, "alphanum_fraction": 0.6798685761, "num_tokens": 7267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2359099410213478}}
{"text": "/*\n * This file is a part of\n *\n * ============================================\n * ###   Pteros molecular modeling library  ###\n * ============================================\n *\n * (C) 2009-2018, Semen Yesylevskyy\n *\n * All works, which use Pteros, should cite the following papers:\n *  \n *  1.  Semen O. Yesylevskyy, \"Pteros 2.0: Evolution of the fast parallel\n *      molecular analysis library for C++ and python\",\n *      Journal of Computational Chemistry, 2015, 36(19), 1480–1488.\n *      doi: 10.1002/jcc.23943.\n *\n *  2.  Semen O. Yesylevskyy, \"Pteros: Fast and easy to use open-source C++\n *      library for molecular analysis\",\n *      Journal of Computational Chemistry, 2012, 33(19), 1632–1636.\n *      doi: 10.1002/jcc.22989.\n *\n * This is free software distributed under Artistic License:\n * http://www.opensource.org/licenses/artistic-license-2.0.php\n *\n*/\n\n\n#include \"pteros/extras/membrane.h\"\n#include \"pteros/core/pteros_error.h\"\n#include \"pteros/core/distance_search.h\"\n#include \"pteros/core/utilities.h\"\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <fstream>\n#include \"voro++.hh\"\n\n#ifndef M_PI\n    #define M_PI 3.14159265358979323846\n#endif\n\n#ifndef M_PI_2\n    #define M_PI_2 9.86960440108935712052951\n#endif\n\nusing namespace std;\nusing namespace pteros;\nusing namespace Eigen;\n\n\n\nMembrane::Membrane(System *sys, const std::vector<Lipid_descr> &species): system(sys), lipid_species(species)\n{\n    log = create_logger(\"membrane\");\n\n    Selection all_mid_sel(*system);\n\n    // Creating selections\n    for(auto& sp: lipid_species){\n        vector<Selection> res;\n        system->select(sp.whole_sel_str).split_by_residue(res);\n        log->info(\"Lipid {}: {}\", sp.name,res.size());\n        for(auto& lip: res){\n            auto mol = Lipid(lip,sp);\n            mol.set_markers();\n            all_mid_sel.append(mol.mid_sel.index(0));\n            lipids.push_back(mol);\n            index_map[mol.mid_sel.index(0)] = lipids.size()-1;\n        }\n    }\n\n    // Compute connectivity    \n    std::vector<Selection> leafs;\n    all_mid_sel.split_by_connectivity(2.0,leafs,true);\n    leaflets.resize(leafs.size());\n    leaflets_sel.resize(leafs.size());\n    // Set lipid leaflets\n    for(int i=0;i<leafs.size();++i){\n        leaflets_sel[i].set_system(*system);\n        for(int a=0; a<leafs[i].size(); ++a){\n            int ind = leafs[i].index(a);\n            lipids[index_map[ind]].leaflet = i;\n            leaflets[i].push_back(index_map[ind]);\n            leaflets_sel[i].append(ind);\n        }\n    }\n\n    // Print statictics\n    log->info(\"Total number of lipids: {}\",lipids.size());\n    log->info(\"Number of leaflets: {}\",leafs.size());    \n}\n\nvoid fit_quad_surface(const MatrixXf& coord,\n                      Matrix<float,6,1>& res,\n                      Vector3f& smoothed_first_point,\n                      float& rms){\n    int N = coord.cols();\n    // We fit with polynomial fit = A*x^2 + B*y^2 + C*xy + D*x + E*y + F\n    // Thus we need a linear system of size 6\n    Matrix<float,6,6> m;\n    Matrix<float,6,1> rhs; // Right hand side and result\n\n    // Functions returning powers after coefficients (x^2, y^2, x*y, x, y, 1)\n    vector<std::function<float(int)> > coef(6);\n    coef[0] = [&coord](int j){return coord.col(j)(0)*coord.col(j)(0);};\n    coef[1] = [&coord](int j){return coord.col(j)(1)*coord.col(j)(1);};\n    coef[2] = [&coord](int j){return coord.col(j)(0)*coord.col(j)(1);};\n    coef[3] = [&coord](int j){return coord.col(j)(0);};\n    coef[4] = [&coord](int j){return coord.col(j)(1);};\n    coef[5] = [&coord](int j){return 1.0;};\n\n    // Now form the matrix\n    m.fill(0.0);\n    rhs.fill(0.0);\n\n    for(int r=0;r<6;++r){ //rows\n        for(int c=0;c<6;++c){ //columns\n            m(r,c) = 0.0;\n            for(int j=0;j<N;++j){\n                m(r,c) += coef[r](j)*coef[c](j);\n            }\n        }\n        // Now rhs\n        for(int j=0;j<N;++j){\n            rhs(r) += coef[r](j)*coord.col(j)(2);\n        }\n    }\n\n    // Now solve\n    res = m.colPivHouseholderQr().solve(rhs);\n\n    // Compute RMS of fitting\n    rms = 0.0;\n    for(int j=0;j<N;++j){\n        float fit = 0.0;\n        for(int r=0;r<6;++r) fit += coef[r](j)*res[r];\n        rms += pow(coord.col(j)(2)-fit,2);\n    }\n    rms = sqrt(rms/float(N));\n\n    // Get smoothed surface point\n    smoothed_first_point.fill(0.0);\n    for(int r=0;r<6;++r) smoothed_first_point(2) += coef[r](0)*res[r];\n}\n\nfloat compute_area(const Eigen::MatrixXf& coord, double dist, std::vector<int>& neib){\n    // Perform Voronoi computation in the tangent plane\n    using namespace voro;\n\n    voronoicell_neighbor c;\n\n    // Z dimension of cotainer is 1, so volume=area\n    container con(-dist,dist,\n                  -dist,dist,\n                  -0.5,0.5,\n                  10,10,10,false,false,false,8);\n\n\n    particle_order po;\n    // Cycle over particles, first particle is our target\n    for(int i=0;i<coord.cols();++i){\n        con.put(po, i, coord.col(i)(0), coord.col(i)(1), 0.0); // Z is zero\n    }\n    c_loop_order clo(con,po);\n    if(! clo.start()) return -1.0; // Get first point, which is our target\n    if(! con.compute_cell(c,clo) ) return -1.0;\n\n    // Check if any of vertices is on outer bounding box and skip cell if they are\n    vector<double> vert;\n    c.vertices(0,0,0,vert);\n    for(int i=0; i<vert.size(); i+=3){\n        //     X                         Y\n        if(abs(abs(vert[i])-dist)<=1.0e-5 || abs(abs(vert[i+1])-dist)<=1.0e-5){\n            //cout << \"| \" << vert[i] << \" \" << vert[i+1] << \" \" << vert[i+2] << \" \" << abs(vert[i])-dist << endl;\n            return -1.0;\n        }\n    }\n\n    // Extract neighbors of this particle\n    std::vector<int> n;\n    c.neighbors(n);\n    // Filter out negatives\n    neib.clear();\n    for(int i: n)\n        if(i>0) neib.push_back(i);\n\n/*\n    cout << \"Npoints: \" << coord.cols() << endl;\n    // Output the particle positions in gnuplot format\n    con.draw_particles(\"points.gnu\");\n\n    // Output the Voronoi cells in gnuplot format\n    con.draw_cells_gnuplot(\"points_v.gnu\");\n*/\n    return c.volume();\n}\n\n\nvoid get_curvature(const Matrix<float,6,1>& coeffs, float& gaussian_curvature, float& mean_curvature){\n    /* Compute the curvatures\n\n        First fundamental form:  I = E du^2 + 2F du dv + G dv^2\n        E= r_u dot r_u, F= r_u dot r_v, G= r_v dot r_v\n\n        For us parametric variables (u,v) are just (x,y) in local space.\n        Derivatives:\n            r_u = {1, 0, 2Ax+Cy+D}\n            r_v = {0, 1, 2By+Cx+E}\n\n        In central point x=0, y=0 so:\n            r_u={1,0,D}\n            r_v={0,1,E}\n\n        Thus: E_ =1+D^2; F_ = D*E; G_ = 1+E^2;\n\n        Second fundamental form: II = L du2 + 2M du dv + N dv2\n        L = r_uu dot n, M = r_uv dot n, N = r_vv dot n\n\n        Normal is just  n = {0, 0, 1}\n        Derivatives:\n            r_uu = {0, 0, 2A}\n            r_uv = {0 ,0, C}\n            r_vv = {0, 0, 2B}\n\n        Thus: L_ = 2A; M_ = C; N_ = 2B;\n        */\n\n    float E_ = 1.0+coeffs[3]*coeffs[3];\n    float F_ = coeffs[3]*coeffs[4];\n    float G_ = 1.0+coeffs[4]*coeffs[4];\n\n    float L_ = 2.0*coeffs[0];\n    float M_ = coeffs[2];\n    float N_ = 2.0*coeffs[1];\n\n    //Curvatures:\n    gaussian_curvature = (L_*N_-M_*M_)/(E_*G_-F_*F_);\n    mean_curvature = 0.5*(E_*N_-2.0*F_*M_+G_*L_)/(E_*G_-F_*F_);\n}\n\nvoid Membrane::compute_properties(float d, bool use_external_normal, Vector3f_const_ref external_pivot, Vector3i_const_ref external_dist_dim)\n{\n    // Clear everything\n    neighbor_pairs.clear();\n\n    Eigen::Matrix3f tr, tr_inv;\n\n    // Set markers for all lipids\n    // This unwraps each lipid\n    for(auto& l: lipids) l.set_markers();\n\n    // Compute per leaflet properties\n    for(int l=0;l<leaflets.size();++l){\n        // Get connectivity in this leaflet\n        vector<Vector2i> bon;\n        search_contacts(d,leaflets_sel[l],bon,false,true);        \n\n        // Convert the list of bonds to convenient form\n        // atom ==> 1 2 3...\n        vector<vector<int> > conn(leaflets_sel[l].size());\n        for(int i=0;i<bon.size();++i){\n            conn[bon[i](0)].push_back(bon[i](1));\n            conn[bon[i](1)].push_back(bon[i](0));\n        }               \n\n        // Process lipids from this leaflet\n        for(int i=0;i<leaflets[l].size();++i){\n            // Find current lipid\n            Lipid& lip = lipids[leaflets[l][i]];\n\n            // Save local selection for this lipid\n            lip.local_sel = leaflets_sel[l].select(conn[i]);\n\n            if(lip.local_sel.size()==0){\n                log->warn(\"Empty locality of lipid {} in leaflet {}! Skipped.\",i,l);\n                continue;\n            }\n\n            // Local coordinate axes\n            Matrix3f axes;\n\n            //-----------------------------------\n            // Compute normal\n            //-----------------------------------\n\n            Vector3f normal;\n\n            if(use_external_normal){\n                // Compute external normal as a vector from pivot to COM of mid_sel (set as marker currently)\n                // over specified dimensions\n                axes.col(2) = (lip.mid_marker-external_pivot).array()*external_dist_dim.cast<float>().array();\n\n                // Find two vectors perpendicular to normal\n                if( axes.col(2).dot(Vector3f(1,0,0)) != 1.0 ){\n                    axes.col(0) = axes.col(2).cross(Vector3f(1,0,0));\n                } else {\n                    axes.col(0) = axes.col(2).cross(Vector3f(0,1,0));\n                }\n                axes.col(1) = axes.col(2).cross(axes.col(0));\n            } else {\n                // Compute normals from inertia axes\n                // Create selection for locality of this lipid including itself\n                Selection local_self(lip.local_sel);\n\n                local_self.append(leaflets_sel[l].index(i)); // Add central atom\n\n                // Get inertial axes\n                Vector3f moments;\n                local_self.inertia(moments,axes,fullPBC); // Have to use periodic variant\n                // axes.col(2) will be a normal\n            }\n\n            normal = axes.col(2);\n\n            // transformation matrix to local basis\n            for(int j=0;j<3;++j) tr.col(j) = axes.col(j).normalized();\n            tr_inv = tr.inverse();\n\n            // Need to check direction of the normal\n            float ang = angle_between_vectors(normal, lip.head_marker-lip.tail_marker);\n            if(ang < M_PI_2){\n                lip.normal = normal;\n                lip.tilt = ang;\n            } else {\n                lip.normal = -normal;\n                lip.tilt = M_PI-ang;\n            }\n            lip.normal.normalized();\n\n            //-----------------------------------\n            // Smooth and find local curvatures\n            //-----------------------------------\n\n            // Create array of local points in local basis\n            MatrixXf coord(3,lip.local_sel.size()+1);\n            Vector3f c0 = lip.mid_marker; // Real coord of central point - the marker\n            coord.col(0) = Vector3f::Zero(); // Local coord of central point is zero\n            for(int j=0; j<lip.local_sel.size(); ++j)\n                coord.col(j+1) = tr_inv * system->box(0).shortest_vector(c0,lip.local_sel.xyz(j));\n\n            // Fit a quad surface\n            Matrix<float,6,1> res;\n            Vector3f sm; // smoothed coords of central point\n            fit_quad_surface(coord,res,sm,lip.quad_fit_rms);\n            // Compute curvatures using quad fit coeefs\n            get_curvature(res, lip.gaussian_curvature, lip.mean_curvature);\n\n            // Get smoothed surface point in lab coords\n            lip.smoothed_mid_xyz = tr*sm + lip.mid_marker;\n\n            //-----------------------------------\n            // Area and neighbours\n            //-----------------------------------\n\n            vector<int> neib;\n            lip.area = compute_area(coord,10.0,neib);\n            // Save coordination number of the lipid\n            lip.coord_number = neib.size();\n\n            // Add neighbor pairs. Only use nearest neighbor lipids from area computation\n            // use only i<j to avoid adding duplicates\n            // If area is -1 skip since this lipid has weird surrounding\n            if(lip.area>0){\n                int cur_ind = index_map[leaflets_sel[l].index(i)];\n                for(int j=0; j<neib.size(); ++j){\n                    int n = index_map[lip.local_sel.index(neib[j]-1)];\n                    if(cur_ind<n) neighbor_pairs.emplace_back(cur_ind,n);\n                }\n            }\n\n        } // Over lipids in leaflet\n\n    } // over leaflets\n\n    //-----------------------------------\n    // Splay and triangilation\n    //-----------------------------------\n\n    // Go over neighbor pairs and compute mean splay\n    // Also form neigbhor array as i ==> 1,2,3...\n    splay.resize(neighbor_pairs.size());\n    neighbors.resize(lipids.size());\n    for(int i=0;i<neighbor_pairs.size();++i){\n        neighbors[neighbor_pairs[i](0)].push_back(neighbor_pairs[i](1));\n        neighbors[neighbor_pairs[i](1)].push_back(neighbor_pairs[i](0));\n        // We have to use periodic distance since atoms could be from different images\n        Lipid& lip1 = lipids[neighbor_pairs[i](0)];\n        Lipid& lip2 = lipids[neighbor_pairs[i](1)];\n        Vector3f& n1 = lip1.normal;\n        Vector3f& n2 = lip2.normal;\n\n        if(n1.dot(n2)<0) continue;\n\n        auto x= system->box(0).shortest_vector(lip1.mid_marker, lip2.mid_marker);\n        float d = x.norm();\n        x = x-x.dot(n1)*n1;\n        x.normalize();\n        Vector3f v1 = (lip1.head_marker-lip1.tail_marker).normalized();\n        Vector3f v2 = (lip2.head_marker-lip2.tail_marker).normalized();\n\n        splay[i] = {\n                    neighbor_pairs[i](0),\n                    neighbor_pairs[i](1),\n                    (v2.dot(x)-v1.dot(x)-n2.dot(x)+n1.dot(x))/d\n                   };\n    }\n\n    //-----------------------------------\n    // Order parameter\n    //-----------------------------------\n\n    for(auto& lip: lipids){\n        // Compute Sz order parameter if the tails are provided\n        for(int t=0; t<lip.tail_carbon_indexes.size(); ++t){\n            // Go over atoms in tail t\n            for(int at=1; at<lip.tail_carbon_indexes[t].size()-1; ++at){\n                // Vector from at+1 to at-1\n                auto coord1 = system->xyz(lip.tail_carbon_indexes[t][at+1]);\n                auto coord2 = system->xyz(lip.tail_carbon_indexes[t][at-1]);\n                float ang = angle_between_vectors(coord1-coord2,lip.normal);\n                lip.order[t][at-1] = 1.5*pow(cos(ang),2)-0.5;\n            }\n        }\n    }\n\n}\n\n\nstring tcl_arrow(Vector3f_const_ref p1, Vector3f_const_ref p2, float r, string color){\n    stringstream ss;\n    Vector3f p = (p2-p1)*0.8+p1;\n    ss << \"draw color \" << color << endl;\n\n    ss << \"draw cylinder \\\"\" << p1.transpose()*10.0 << \"\\\" \";\n    ss << \"\\\"\" << p.transpose()*10.0 << \"\\\" radius \" << r << endl;\n\n    ss << \"draw cone \\\"\" << p.transpose()*10.0 << \"\\\" \";\n    ss << \"\\\"\" << p2.transpose()*10.0 << \"\\\" radius \" << r*3.0 << endl;\n\n    return ss.str();\n}\n\nvoid Membrane::write_vmd_arrows(const string &fname)\n{\n    ofstream f(fname);\n    for(auto& lip: lipids){\n        f << tcl_arrow(lip.mid_sel.center(true),lip.mid_sel.center(true)+lip.normal,0.2,\"green\");\n        f << tcl_arrow(lip.tail_sel.center(true),lip.head_sel.center(true),0.2,\"red\");\n    }\n    f.close();\n\n}\n\nvoid Membrane::write_smoothed(const string& fname){\n    System out;\n    for(auto& l: lipids){\n        auto s = out.append(l.mid_sel(0,0));\n        s.name(0) = \"M\";\n        s = out.append(l.head_sel(0,0));\n        s.xyz(0) = l.smoothed_mid_xyz;\n        s.name(0) = \"S\";\n    }\n    out().write(fname);\n}\n\n\n//------------------------------------------------------------------------\n\nLipid::Lipid(const Selection &sel, const Lipid_descr &descr){\n    name = descr.name;\n    whole_sel = sel;\n    head_sel = whole_sel(descr.head_sel_str);\n    tail_sel = whole_sel(descr.tail_sel_str);\n    mid_sel = whole_sel(descr.mid_sel_str);\n    // Fill tail indexes if any\n    tail_carbon_indexes.resize(descr.tail_carbon_sels.size());\n    order.resize(descr.tail_carbon_sels.size());\n    for(int t=0; t<descr.tail_carbon_sels.size(); ++t){\n        tail_carbon_indexes[t] = whole_sel(descr.tail_carbon_sels[t]).get_index();\n        // Allocate array for order\n        order[t].resize(tail_carbon_indexes[t].size()-2);\n    }\n}\n\nvoid Lipid::set_markers()\n{\n    // Unwrap this lipid with leading index of position[0]    \n    whole_sel.unwrap(fullPBC, mid_sel.index(0)-whole_sel.index(0));\n\n    // Set markers to COM\n    head_marker = head_sel.center(true);\n    tail_marker = tail_sel.center(true);\n    mid_marker = mid_sel.center(true);\n}\n\n\n\n\n", "meta": {"hexsha": "1e3a8fdbf36df3e686bf7c9aced13b201a8ead80", "size": 16677, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extras/membrane/membrane.cpp", "max_stars_repo_name": "confitarlaburra/pteros2.0", "max_stars_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-19T14:36:10.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T14:36:10.000Z", "max_issues_repo_path": "src/extras/membrane/membrane.cpp", "max_issues_repo_name": "confitarlaburra/pteros2.0", "max_issues_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/extras/membrane/membrane.cpp", "max_forks_repo_name": "confitarlaburra/pteros2.0", "max_forks_repo_head_hexsha": "25de81f39bc8948a37e10e3b389d58ca71195d8d", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4879518072, "max_line_length": 141, "alphanum_fraction": 0.5434430653, "num_tokens": 4527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370308082623217, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.235844989937431}}
{"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RWLIBS_ALGORTIHMS_KDTREE_KDTREE_HPP_\n#define RWLIBS_ALGORTIHMS_KDTREE_KDTREE_HPP_\n\n#include <rw/core/Ptr.hpp>\n#include <rw/core/macros.hpp>\n#include <rw/math/Math.hpp>\n#include <rw/math/Metric.hpp>\n\n#include <algorithm>\n#include <boost/any.hpp>\n#include <float.h>\n#include <list>\n#include <queue>\n#include <vector>\n\nnamespace rwlibs { namespace algorithms {\n\n    // We can't define this as a static variable within the class, so we put it\n    // here for now.\n    const double kdtree_epsilon = 0.000000001;\n\n    /** \\addtogroup algorithms */\n    /*@{*/\n\n    /**\n     * @brief a space partitioning structure for organizing points in k-dimensional space.\n     * Used for searches involving multi.dimensional search keys, including nearest\n     * neighbor and range search.\n     *\n     * KEY must implement:\n     * copyable\n     * operator[]\n     * operator()\n     * TODO: remove one of the operators (change code in KDTREE)\n     *\n     */\n    template< class KEY, size_t DIM > class KDTree\n    {\n      private:\n        struct TreeNode;\n\n        size_t _nrOfNodes;\n        TreeNode* _root;\n        std::vector< TreeNode >* _nodes;\n        rw::core::Ptr< rw::math::Metric< KEY > > _metric;\n\n      public:\n        //! a struct for the node in the tree\n        struct KDNode\n        {\n            KDNode (const KEY& k, boost::any val) : key (k), value (val) {}\n            KEY key;\n            boost::any value;\n        };\n\n        struct KDResult\n        {\n            KDResult (KDNode* node, double d) : n (node), dist (d) {}\n            KDNode* n;\n            double dist;\n        };\n\n        /**\n         * @brief Constructor\n         * @cond\n         * @param dim [in] the dimension of the keys in the KDTree\n         * @endcond\n         * @param metric documentation missing !\n         */\n        KDTree (rw::core::Ptr< rw::math::Metric< KEY > > metric) :\n            _nrOfNodes (0), _root (NULL), _nodes (new std::vector< TreeNode > ())\n        {}\n\n        /**\n         * @brief destructor\n         */\n        virtual ~KDTree ()\n        {\n            if (_root != NULL)\n                delete _root;\n            if (_nodes != NULL)\n                delete _nodes;\n        };\n\n        rw::core::Ptr< rw::math::Metric< KEY > > getMetric () { return _metric; }\n\n        /**\n         * @brief Builds a KDTree from a list of key values and nodes. This method is more efficient\n         * than creating an empty KDTree and then inserting nodes\n         * @param nodes [in] a list of KDNode's\n         * @param metric documentation missing !\n         * @return if build succesfull then a pointer to a KD-tree is returned else NULL\n         */\n        static KDTree< KEY, DIM >* buildTree (std::vector< KDNode >& nodes,\n                                              rw::core::Ptr< rw::math::Metric< KEY > > metric)\n        {\n            if (nodes.size () == 0)\n                return NULL;\n\n            // create all tree nodes in a list\n            std::vector< TreeNode >* tNodes = new std::vector< TreeNode > (nodes.size ());\n\n            // copy the KDNodes into the tree nodes\n            int i = 0;\n            for (KDNode& n : nodes) {\n                (*tNodes)[i]._kdnode = &n;\n                i++;\n            }\n\n            // create a simple median balanced tree\n            TreeNode* root = buildBalancedRec (*tNodes, 0, (int) tNodes->size (), 0, DIM);\n\n            return new KDTree< KEY, DIM > (*root, tNodes, metric);\n        }\n\n        /**\n         * @brief Builds a KDTree from a list of key values and nodes. This method is more efficient\n         * than creating an empty KDTree and then inserting nodes\n         * @param nodes [in] a list of KDNode's\n         * @param metric documentation missing !\n         * @return if build succesfull then a pointer to a KD-tree is returned else NULL\n         */\n        static KDTree< KEY, DIM >* buildTree (const std::vector< KDNode* >& nodes,\n                                              rw::core::Ptr< rw::math::Metric< KEY > > metric)\n        {\n            if (nodes.size () == 0)\n                return NULL;\n\n            // create all tree nodes in a list\n            std::vector< TreeNode >* tNodes = new std::vector< TreeNode > (nodes.size ());\n\n            // copy the KDNodes into the tree nodes\n            int i = 0;\n            for (KDNode* n : nodes) {\n                (*tNodes)[i]._kdnode = n;\n                i++;\n            }\n\n            // create a simple median balanced tree\n            TreeNode* root = buildBalancedRec (*tNodes, 0, (int) tNodes->size (), 0, DIM);\n\n            return new KDTree< KEY, DIM > (*root, tNodes, metric);\n        }\n\n        /**\n         * @brief gets the number of dimensions that this KDTree supports\n         * @return the nr of dimensions of this KD-Tree\n         */\n        size_t getDimensions () const { return DIM; };\n\n        /**\n         * @brief adds a key value pair to the KDTree.\n         * @param key [in] must be the same length as the dimensionality of the KDTree\n         * @param val [in] value that is to be stored at the keys position\n         */\n        void addNode (const KEY& key, boost::any val)\n        {\n            RW_THROW (\"There is no implementation yet!\");\n        }\n\n        /**\n         * @brief finds the KDNode with key equal to nnkey\n         * @param nnkey [in] the key that is to be found\n         * @return KDNode with key equal to nnkey if existing, else NULL\n         */\n        KDNode* search (const KEY& nnkey)\n        {\n            TreeNode* tmpNode = _root;\n            for (size_t lev = 0; tmpNode != NULL; lev = (lev + 1) % DIM) {\n                KEY& key = tmpNode->_kdnode->key;\n                if (nnkey[lev] == key[lev] && !(tmpNode->_deleted) &&\n                    (_metric->distance (nnkey, key) < 0.000001)) {\n                    return tmpNode->_kdnode;\n                }\n                else if (nnkey (lev) > key (lev)) {\n                    tmpNode = tmpNode->_right;\n                }\n                else {\n                    tmpNode = tmpNode->_left;\n                }\n            }\n            return NULL;\n        };\n\n        /**\n         * @brief finds the KDNode with the key closest too nnkey\n         * @param nnkey [in] the key to which the nearest neighbor is found\n         * @return the nearest neighbor to nnkey\n         */\n        KDNode& nnSearch (const KEY& nnkey)\n        {\n            // std::cout << \"nnSearch \" << DIM << std::endl;\n\n            // RW_ASSERT(_metric->size(nnkey)==DIM);\n            if (_root == NULL)\n                RW_THROW (\"KDTree has no data!\");\n\n            KEY min = nnkey, max = nnkey;\n            KDResult result (NULL, DBL_MAX);\n            for (size_t i = 0; i < DIM; i++) {\n                min[i] = -DBL_MAX;\n                max[i] = DBL_MAX;\n            }\n            // std::cout << \"nnSearchRec\" << std::endl;\n            nnSearchRec (nnkey, _root, min, max, result);\n            if (result.n == NULL)\n                RW_THROW (\"KDTree has no data!\");\n            return *result.n;\n        }\n\n        /**\n         * @brief finds all neighbors in the hyperelipse with radius radi and center in nnkey.\n         * @param nnkey [in] the center of the hyperelipse\n         * @param radi [in] the radius of the hyperelipse in euclidean 2-norm\n         * @param nodes [out] a container for all nodes that is found within the hyperelipse\n         */\n        void nnSearchElipse (const KEY& nnkey, const KEY& radi, std::list< const KDNode* >& nodes)\n        {\n            // typedef std::pair<TreeNode*,size_t> QElem;\n            using namespace rw::math;\n            std::queue< TreeNode* > unhandled;\n            unhandled.push (_root);\n            double distRadi = _metric->distance (radi);\n            KEY low = nnkey, upp = nnkey;\n            for (size_t i = 0; i < DIM; i++) {\n                low[i] = nnkey[i] - distRadi;\n                upp[i] = nnkey[i] + distRadi;\n            }\n\n            nnSearchElipseRec (nnkey, _root, low, upp, distRadi, nodes);\n        }\n\n        /**\n         * @brief finds all neighbors in the hyperelipse with radius radi and center in nnkey.\n         * @param nnkey [in] the center of the hyperelipse\n         * @param radi [in] the radius of the hyperelipse in euclidean 2-norm\n         * @param nodes [out] a container for all nodes that is found within the hyperelipse\n         */\n        void nnSearchElipseRect (const KEY& nnkey, const KEY& radi,\n                                 std::list< const KDNode* >& nodes)\n        {\n            // typedef std::pair<TreeNode*,size_t> QElem;\n            using namespace rw::math;\n            std::queue< TreeNode* > unhandled;\n            unhandled.push (_root);\n\n            double distRadi = _metric->distance (radi);\n            KEY low = nnkey, upp = nnkey;\n            for (size_t i = 0; i < DIM; i++) {\n                low (i) = nnkey (i) - distRadi;\n                upp (i) = nnkey (i) + distRadi;\n            }\n\n            while (!unhandled.empty ()) {\n                // std::cout << \"unhandled size: \" << unhandled.size() << std::endl;\n                TreeNode* n = unhandled.front ();\n                unhandled.pop ();\n\n                unsigned char axis = n->_axis;\n                KEY& key           = n->_kdnode->key;\n\n                // std::cout << \"Axis: \" << axis << std::endl;\n\n                // if the key is in range then add it to the result\n                size_t j;\n                for (j = 0; j < DIM && low[j] <= key[j] && upp[j] >= key[j]; j++)\n                    ;\n                // std::cout << j << \"==\" << DIM << \" k:\" << key << std::endl;\n                if (j == DIM) {    // this is in range if\n                    double dist = _metric->distance (nnkey, key);\n                    // std::cout << \"Dist: \" << dist << \" < \" << distSqr << std::endl;\n                    if (dist < distRadi)\n                        nodes.push_back (n->_kdnode);\n                }\n\n                // add the children to the unhandled queue if the current dimension\n                if ((low (axis) <= key (axis)) && (n->_left != NULL))\n                    unhandled.push (n->_left);\n                if ((upp (axis) > key (axis)) && (n->_right != NULL))\n                    unhandled.push (n->_right);\n            }\n        }\n\n        /**\n         * @brief finds all neighbors in the hyperrectangle defined by the lower bound and the\n         * upper bound\n         */\n        void nnSearchRect (const KEY& low, const KEY& upp, std::list< const KDNode* >& nodes)\n        {\n            // typedef std::pair<TreeNode*,size_t> QElem;\n            std::queue< TreeNode* > unhandled;\n            unhandled.push (_root);\n\n            // std::cout << \"nnSearchRect: \"<< std::endl;\n            // std::cout << \"- low bound: \"<< low << std::endl;\n            // std::cout << \"- upp bound: \"<< upp << std::endl;\n\n            while (!unhandled.empty ()) {\n                // std::cout << \"unhandled size: \" << unhandled.size() << std::endl;\n                TreeNode* n = unhandled.front ();\n                unhandled.pop ();\n\n                unsigned char axis = n->_axis;\n                KEY& key           = n->_kdnode->key;\n\n                // std::cout << \"Axis: \" << axis << std::endl;\n\n                // if the key   is in range then add it to the result\n                size_t j;\n                for (j = 0; j < DIM && low[j] <= key[j] && key[j] <= upp[j]; j++)\n                    ;\n                // std::cout << j << \"==\" << DIM << \" k:\" << key << std::endl;\n                if (j == DIM)    // this is in range\n                    nodes.push_back (n->_kdnode);\n\n                // add the children to the unhandled queue if the current dimension\n                if ((low (axis) <= key (axis)) && (n->_left != NULL))\n                    unhandled.push (n->_left);\n                if ((upp (axis) > key (axis)) && (n->_right != NULL))\n                    unhandled.push (n->_right);\n            }\n        };\n\n      private:\n        KDTree (){};\n\n        KDTree (TreeNode& root, std::vector< TreeNode >* nodes,\n                rw::core::Ptr< rw::math::Metric< KEY > > metric) :\n            _root (&root),\n            _nodes (nodes), _metric (metric){};\n\n        /**\n         * @brief Internal representation of a KD Tree Node. To save processing time when deleting\n         * TreeNodes, a boolean is kept that say if the node is deleted or not. If deleted all\n         * rutines kan skip the node and forward the call to its children.\n         */\n        struct TreeNode\n        {\n          public:\n            TreeNode () :\n                _left (NULL), _right (NULL), _kdnode (NULL), _deleted (false), _axis (0){};\n\n            TreeNode (KDNode* node) :\n                _left (NULL), _right (NULL), _kdnode (node), _deleted (false), _axis (0){};\n\n            TreeNode (TreeNode* left, TreeNode* right, KDNode* node) :\n                _left (left), _right (right), _kdnode (node), _deleted (false), _axis (0){};\n\n            static void swap (TreeNode& n1, TreeNode& n2)\n            {\n                std::swap (n1._left, n2._left);\n                std::swap (n1._right, n2._right);\n                std::swap (n1._kdnode, n2._kdnode);\n            }\n\n            TreeNode *_left, *_right;\n            KDNode* _kdnode;\n            bool _deleted;          //\n            unsigned char _axis;    // the splitting axis\n        };\n\n        struct SimpleCompare\n        {\n          private:\n            size_t _dim;\n\n          public:\n            SimpleCompare (size_t dim) : _dim (dim){};\n\n            bool operator() (const TreeNode& e1, const TreeNode& e2)\n            {\n                return e1._kdnode->key[_dim] < e2._kdnode->key[_dim];\n            }\n        };\n\n        static TreeNode* buildBalancedRec (std::vector< TreeNode >& tNodes, int startIdx,\n                                           int endIdx, size_t depth, size_t nrOfDims)\n        {\n            if (endIdx <= startIdx)\n                return NULL;\n\n            // std::cout << \"RecBuild(\" << startIdx << \",\" << endIdx << \")\" << std::endl;\n            size_t len = endIdx - startIdx;\n\n            size_t dim = depth % nrOfDims;\n            // the compare func can\n            std::sort (&tNodes[startIdx], &tNodes[endIdx - 1], SimpleCompare (dim));\n            size_t medianIdx = startIdx + len / 2;\n\n            TreeNode& mNode = tNodes[medianIdx];\n            mNode._axis     = 0xFF & dim;\n            mNode._left = buildBalancedRec (tNodes, startIdx, (int) medianIdx, depth + 1, nrOfDims);\n            mNode._right =\n                buildBalancedRec (tNodes, (int) medianIdx + 1, endIdx, depth + 1, nrOfDims);\n            return &mNode;\n        }\n\n        template< class T > T clamp (const T& val, const T& min, const T& max)\n        {\n            T result = val;\n            for (size_t i = 0; i < DIM; i++) {\n                result[i] = rw::math::Math::clamp (val[i], min[i], max[i]);\n            }\n            return result;\n        }\n\n        void nnSearchRec (const KEY& nnkey, TreeNode* node, KEY& min, KEY& max, KDResult& out)\n        {\n            using namespace rw::math;\n            if (node == NULL)\n                return;\n            size_t axis = node->_axis;\n            // std::cout << \"nnSearchRec(\"<< axis << \")\" << std::endl;\n\n            KEY& key       = node->_kdnode->key;\n            double distSqr = _metric->distance (nnkey, key);\n            // std::cout << \"le\" << std::endl;\n\n            // if this node is closer than any other then update out\n            if (distSqr < out.dist && !node->_deleted) {\n                out.dist = distSqr;\n                out.n    = node->_kdnode;\n            }\n            // stop if the distance is very small\n            if (distSqr < kdtree_epsilon)\n                return;\n            // std::cout << \"1\" << std::endl;\n            // call nnSearch recursively with closerNode,\n            // closestNode and closestDistSqr is updated\n            bool isLeftClosest = nnkey (axis) < key (axis);\n            if (isLeftClosest) {\n                // std::cout << \"left\" << std::endl;\n                // left is closest, backup split value and make the recursive call\n                double maxTmp = max (axis);\n                max (axis)    = key (axis);\n                nnSearchRec (nnkey, node->_left, min, max, out);\n                // undo the change of max\n                max (axis) = maxTmp;\n            }\n            else {\n                // std::cout << \"right\" << std::endl;\n                // right is closest, backup split value and make the recursive call\n                double minTmp = min (axis);\n                min (axis)    = key (axis);\n                nnSearchRec (nnkey, node->_right, min, max, out);\n                // undo the change of max\n                min (axis) = minTmp;\n            }\n            // std::cout << \"2\" << std::endl;\n\n            // next check if fartherNode split plane lies closer than closestDistSqr\n            if (Math::sqr (nnkey (axis) - key (axis)) >= out.dist)\n                return;\n            // std::cout << \"3\" << std::endl;\n\n            bool isLeftFarthest = !isLeftClosest;\n            // if closest point in hyperrect of farther node is closer than closest\n            // then call nnSearch recursively with farther node\n            if (isLeftFarthest) {\n                double maxTmp = max (axis);\n                max (axis)    = key (axis);\n                KEY closest   = clamp (nnkey, min, max);\n                if (_metric->distance (nnkey, closest) < out.dist)\n                    nnSearchRec (nnkey, node->_left, min, max, out);\n                // undo the change of max\n                max (axis) = maxTmp;\n            }\n            else {\n                double minTmp = min (axis);\n                min (axis)    = key (axis);\n                KEY closest   = clamp (nnkey, min, max);\n                if (_metric->distance (nnkey, closest) < out.dist)\n                    nnSearchRec (nnkey, node->_right, min, max, out);\n                // undo the change of max\n                min (axis) = minTmp;\n            }\n        };\n\n        void nnSearchElipseRec (const KEY& nnkey, TreeNode* node, KEY& min, KEY& max,\n                                double maxRadiSqr, std::list< const KDNode* >& nodes)\n        {\n            using namespace rw::math;\n            if (node == NULL)\n                return;\n            size_t axis = node->_axis;\n            // std::cout << \"nnSearchRec(\"<< axis << \")\" << std::endl;\n\n            KEY& key       = node->_kdnode->key;\n            double distSqr = _metric->distance (nnkey, key);\n\n            // if this node is closer than any other then update out\n            if (distSqr < maxRadiSqr && !node->_deleted) {\n                nodes.push_back (node->_kdnode);\n            }\n            // stop if the distance is very small\n            if (distSqr < kdtree_epsilon)\n                return;\n\n            // call nnSearch recursively with closerNode,\n            // closestNode and closestDistSqr is updated\n            bool isLeftClosest = nnkey (axis) < key (axis);\n            if (isLeftClosest) {\n                // left is closest, backup split value and make the recursive call\n                double maxTmp = max (axis);\n                max (axis)    = key (axis);\n                nnSearchElipseRec (nnkey, node->_left, min, max, maxRadiSqr, nodes);\n                // undo the change of max\n                max (axis) = maxTmp;\n            }\n            else {\n                // right is closest, backup split value and make the recursive call\n                double minTmp = min (axis);\n                min (axis)    = key (axis);\n                nnSearchElipseRec (nnkey, node->_right, min, max, maxRadiSqr, nodes);\n                // undo the change of max\n                min (axis) = minTmp;\n            }\n\n            // next check if fartherNode split plane lies closer than closestDistSqr\n            if (Math::sqr (nnkey (axis) - key (axis)) >= maxRadiSqr)\n                return;\n\n            bool isLeftFarthest = !isLeftClosest;\n            // if closest point in hyperrect of farther node is closer than closest\n            // then call nnSearch recursively with farther node\n            if (isLeftFarthest) {\n                double maxTmp = max (axis);\n                max (axis)    = key (axis);\n                KEY closest   = clamp (nnkey, min, max);\n                if (_metric->distance (nnkey, closest) < maxRadiSqr)\n                    nnSearchElipseRec (nnkey, node->_left, min, max, maxRadiSqr, nodes);\n                // undo the change of max\n                max (axis) = maxTmp;\n            }\n            else {\n                double minTmp = min (axis);\n                min (axis)    = key (axis);\n                KEY closest   = clamp (nnkey, min, max);\n                if (_metric->distance (nnkey, closest) < maxRadiSqr)\n                    nnSearchElipseRec (nnkey, node->_right, min, max, maxRadiSqr, nodes);\n                // undo the change of max\n                min (axis) = minTmp;\n            }\n        };\n    };\n\n    extern template class KDTree< rw::math::Vector3D<>, 3 >;\n\n    /**@}*/\n\n}}    // namespace rwlibs::algorithms\n\n#endif /*KDTREE_HPP_*/\n", "meta": {"hexsha": "13d64d8d04cf1a0a63d12b859aee7aa078bed13f", "size": 22017, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rwlibs/algorithms/kdtree/KDTree.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rwlibs/algorithms/kdtree/KDTree.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rwlibs/algorithms/kdtree/KDTree.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5586690018, "max_line_length": 100, "alphanum_fraction": 0.4933460508, "num_tokens": 5258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2357087954044889}}
{"text": "#include <boost/config/warning_disable.hpp>\n#include <boost/bind.hpp>\n#include <boost/spirit/include/qi.hpp>\n#include <boost/spirit/include/qi_real.hpp>\n#include <boost/spirit/include/phoenix_core.hpp>\n#include <boost/spirit/include/phoenix_operator.hpp>\n#include <boost/spirit/include/phoenix_stl.hpp>\n#include <boost/spirit/include/classic_core.hpp>\n#include <boost/spirit/include/classic_increment_actor.hpp>\n#include <string>\n#include <map>\n#include <iostream>\n#include <fstream>\n#include <stdexcept>\n#include <equation_system/clientp.hpp>\n\nnamespace System {\nusing namespace std;\nusing namespace BOOST_SPIRIT_CLASSIC_NS;\nnamespace clientp\n{\n\nnamespace {\n\tvoid sad_little_message(int line_no, string input){\n\t\tcerr << \"Input line : \" << line_no << endl; \n\t\tcerr << \"Received : \" << input << endl; \n\t\tcerr << \"Please express equations using arithmetic combinations +/- of one or more terms, \" << endl;\n\t\tcerr << \"terms consisting of products expressed with *, powers with ^ and powers/indices\" << endl;\n\t\tcerr << \"expressed within parenthesis for constants k and variables y (1-based index) eg.,\" << endl;\n\t\tcerr << \" \" << endl;\n\t\tcerr << \"1.0*k(717)*y(516)-1.0*k(416)*y(1)*y(392)-1.0*k(718)*y(1)^(1/2)*y(517)\" << endl;\n\t\tcerr << \" \" << endl;\n\t\tthrow std::invalid_argument( \"Received bad equation format on stdin\" );\n\t}\n}\n\n\ntemplate <typename T>\nvoid update(std::map<T,T> &x, const T& key, const T& val){\n\n\tx[key]+=val;\n}\n\n\nnamespace qi = boost::spirit::qi;\nnamespace ascii = boost::spirit::ascii;\nnamespace phoenix = boost::phoenix;\n\nusing qi::float_;\nusing qi::double_;\nusing qi::phrase_parse;\nusing qi::_1;\nusing ascii::space;\nusing phoenix::push_back;\n\n\ntemplate <typename Iterator>\n\tbool parse_csv(Iterator first, Iterator last, std::vector<float>& k)\n\t{\n\t\tbool r = phrase_parse(first, last,\n\n\t\t\t\t//  grammar for csv files\n\t\t\t\t(\n\t\t\t\t //*(float_ >> ',' | float_ [push_back(phoenix::ref(k),_1)])\n\t\t\t\t *(float_ [push_back(phoenix::ref(k),_1)])\n\t\t\t\t)\n\t\t\t\t,\n\t\t\t\tspace);\n\n\t\treturn r;\n\n\t}\n\n\ntemplate <typename Iterator>\n\tbool parse_k_vals(Iterator first, Iterator last, std::vector<float>& w)\n\t{\t\t\t\n\t\tbool r = phrase_parse(first, last,\n\n\t\t\t\t//  grammar for k constants\n\t\t\t\t(\n\t\t\t\t (\"k(\" >> float_[push_back(phoenix::ref(w), _1)] >> ')')\n\t\t\t\t)\n\t\t\t\t,\n\t\t\t\t//skip\n\t\t\t\tspace | '*' | float_ >> '*' | '-'>>float_ >> '*'| '+' >> float_ >> '*'| \"y(\" >> float_ >> ')');\n\n\t\treturn r;\n\t}\n\ntemplate <typename Iterator>\n\tbool parse_constants(Iterator first, Iterator last, std::vector<float>& v)\n\t{\n\t\tbool r = phrase_parse(first, last,\n\n\t\t\t\t//  grammar for numerical constants & sign\n\t\t\t\t(\n\t\t\t\t (float_[push_back(phoenix::ref(v), _1)] >> '*')\n\t\t\t\t)\n\t\t\t\t,\n\t\t\t\t//skip\n\t\t\t\tspace);\n\t\treturn r;\n\t}\ntemplate <typename Iterator>\n\tbool parse_y_vals(Iterator first, Iterator last, std::map<float,float>& x)\n\t{\n\t\tfloat base =1.0;\n\t\tfloat exp = 0.0;\n\t\tbool r = phrase_parse(first, last,\n\n\t\t\t\t//  grammar for y variables\n\t\t\t\t//  this looks like hell\n\t\t\t\t(\n\t\t\t\t *(\"y(\" >> float_[phoenix::ref(base)=_1] >> \")^(\" >> float_[phoenix::ref(exp)=_1] >> '/' >> float_[phoenix::ref(exp)/=_1]\\\n\t\t\t\t\t [boost::bind(&update<float>,boost::ref(x),boost::ref(base),boost::ref(exp))] >> ')' |\n\t\t\t\t\t \"y(\" >> float_[phoenix::ref(base)=_1, boost::bind(&update<float>,boost::ref(x),boost::ref(base),1.0f)] >> ')')\n\t\t\t\t)\n\t\t\t\t,\n\t\t\t\t//skip\n\t\t\t\tspace | '*' | float_ >> '*' | '-'>>float_ >> '*'| '+' >> float_ >> '*'| \"k(\" >> float_ >> ')');\n\n\n\t\treturn r;\n\t}\n\ntemplate <typename Iterator>\n\tbool parse_csv(Iterator first, Iterator last, std::vector<double>& k)\n\t{\n\t\tbool r = phrase_parse(first, last,\n\n\t\t\t\t//  grammar for csv files\n\t\t\t\t(\n\t\t\t\t //*(double_ >> ',' | double_ [push_back(phoenix::ref(k),_1)])\n\t\t\t\t *(double_ [push_back(phoenix::ref(k),_1)])\n\t\t\t\t)\n\t\t\t\t,\n\t\t\t\tspace);\n\n\t\treturn r;\n\n\t}\n\n\ntemplate <typename Iterator>\n\tbool parse_k_vals(Iterator first, Iterator last, std::vector<double>& w)\n\t{\t\t\t\n\t\tbool r = phrase_parse(first, last,\n\n\t\t\t\t//  grammar for k constants\n\t\t\t\t(\n\t\t\t\t (\"k(\" >> double_[push_back(phoenix::ref(w), _1)] >> ')')\n\t\t\t\t)\n\t\t\t\t,\n\t\t\t\t//skip\n\t\t\t\tspace | '*' | double_ >> '*' | '-'>>double_ >> '*'| '+' >> double_ >> '*'| \"y(\" >> double_ >> ')');\n\n\t\treturn r;\n\t}\n\ntemplate <typename Iterator>\n\tbool parse_constants(Iterator first, Iterator last, std::vector<double>& v)\n\t{\n\t\tbool r = phrase_parse(first, last,\n\n\t\t\t\t//  grammar for numerical constants & sign\n\t\t\t\t(\n\t\t\t\t (double_[push_back(phoenix::ref(v), _1)] >> '*')\n\t\t\t\t)\n\t\t\t\t,\n\t\t\t\t//skip\n\t\t\t\tspace);\n\t\treturn r;\n\t}\ntemplate <typename Iterator>\n\tbool parse_y_vals(Iterator first, Iterator last, std::map<double,double>& x)\n\t{\n\t\tdouble base =1.0;\n\t\tdouble exp = 0.0;\n\t\tbool r = phrase_parse(first, last,\n\n\t\t\t\t//  grammar for y variables\n\t\t\t\t//  this looks like hell\n\t\t\t\t(\n\t\t\t\t *(\"y(\" >> double_[phoenix::ref(base)=_1] >> \")^(\" >> double_[phoenix::ref(exp)=_1] >> '/' >> double_[phoenix::ref(exp)/=_1]\\\n\t\t\t\t\t [boost::bind(&update<double>,boost::ref(x),boost::ref(base),boost::ref(exp))] >> ')' |\n\t\t\t\t\t \"y(\" >> double_[phoenix::ref(base)=_1, boost::bind(&update<double>,boost::ref(x),boost::ref(base),1.0f)] >> ')')\n\t\t\t\t)\n\t\t\t\t,\n\t\t\t\t//skip\n\t\t\t\tspace | '*' | double_ >> '*' | '-'>>double_ >> '*'| '+' >> double_ >> '*'| \"k(\" >> double_ >> ')');\n\n\n\t\treturn r;\n\t}\n}\n}\n", "meta": {"hexsha": "59130dec4604997f4bed429c953e9a7933a34bf0", "size": 5182, "ext": "inl", "lang": "C++", "max_stars_repo_path": "inc/equation_system/detail/clientp.inl", "max_stars_repo_name": "pytaunay/CuSolve", "max_stars_repo_head_hexsha": "05f75d288b114de7da22249e54520b8fdb589eba", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-24T02:46:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-24T02:46:41.000Z", "max_issues_repo_path": "inc/equation_system/detail/clientp.inl", "max_issues_repo_name": "pytaunay/CuSolve", "max_issues_repo_head_hexsha": "05f75d288b114de7da22249e54520b8fdb589eba", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/equation_system/detail/clientp.inl", "max_forks_repo_name": "pytaunay/CuSolve", "max_forks_repo_head_hexsha": "05f75d288b114de7da22249e54520b8fdb589eba", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-07-30T01:23:11.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T04:50:27.000Z", "avg_line_length": 26.1717171717, "max_line_length": 129, "alphanum_fraction": 0.6067155538, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23559260281945738}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2014, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_CLOSEST_FEATURE_POINT_TO_RANGE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_CLOSEST_FEATURE_POINT_TO_RANGE_HPP\n\n#include <utility>\n\n#include <boost/range.hpp>\n\n#include <boost/geometry/core/assert.hpp>\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace closest_feature\n{\n\n\n// returns the segment (pair of iterators) that realizes the closest\n// distance of the point to the range\ntemplate\n<\n    typename Point,\n    typename Range,\n    closure_selector Closure,\n    typename Strategy\n>\nclass point_to_point_range\n{\nprotected:\n    typedef typename geofeatures_boost::range_iterator<Range const>::type iterator_type;\n\n    template <typename Distance>\n    static inline void apply(Point const& point,\n                             iterator_type first,\n                             iterator_type last,\n                             Strategy const& strategy,\n                             iterator_type& it_min1,\n                             iterator_type& it_min2,\n                             Distance& dist_min)\n    {\n        BOOST_GEOMETRY_ASSERT( first != last );\n\n        Distance const zero = Distance(0);\n\n        iterator_type it = first;\n        iterator_type prev = it++;\n        if (it == last)\n        {\n            it_min1 = it_min2 = first;\n            dist_min = strategy.apply(point, *first, *first);\n            return;\n        }\n\n        // start with first segment distance\n        dist_min = strategy.apply(point, *prev, *it);\n        iterator_type prev_min_dist = prev;\n\n        // check if other segments are closer\n        for (++prev, ++it; it != last; ++prev, ++it)\n        {\n            Distance dist = strategy.apply(point, *prev, *it);\n            if (geometry::math::equals(dist, zero))\n            {\n                dist_min = zero;\n                it_min1 = prev;\n                it_min2 = it;\n                return;\n            }\n            else if (dist < dist_min)\n            {\n                dist_min = dist;\n                prev_min_dist = prev;\n            }\n        }\n\n        it_min1 = it_min2 = prev_min_dist;\n        ++it_min2;\n    }\n\npublic:\n    typedef typename std::pair<iterator_type, iterator_type> return_type;\n\n    template <typename Distance>\n    static inline return_type apply(Point const& point,\n                                    iterator_type first,\n                                    iterator_type last,\n                                    Strategy const& strategy,\n                                    Distance& dist_min)\n    {\n        iterator_type it_min1, it_min2;\n        apply(point, first, last, strategy, it_min1, it_min2, dist_min);\n\n        return std::make_pair(it_min1, it_min2);\n    }\n\n    static inline return_type apply(Point const& point,\n                                    iterator_type first,\n                                    iterator_type last,\n                                    Strategy const& strategy)\n    {\n        typename strategy::distance::services::return_type\n            <\n                Strategy,\n                Point,\n                typename geofeatures_boost::range_value<Range>::type\n            >::type dist_min;\n\n        return apply(point, first, last, strategy, dist_min);\n    }\n\n    template <typename Distance>\n    static inline return_type apply(Point const& point,\n                                    Range const& range,\n                                    Strategy const& strategy,\n                                    Distance& dist_min)\n    {\n        return apply(point,\n                     geofeatures_boost::begin(range),\n                     geofeatures_boost::end(range),\n                     strategy,\n                     dist_min);\n    }\n\n    static inline return_type apply(Point const& point,\n                                    Range const& range,\n                                    Strategy const& strategy)\n    {\n        return apply(point, geofeatures_boost::begin(range), geofeatures_boost::end(range), strategy);\n    }\n};\n\n\n\n// specialization for open ranges\ntemplate <typename Point, typename Range, typename Strategy>\nclass point_to_point_range<Point, Range, open, Strategy>\n    : point_to_point_range<Point, Range, closed, Strategy>\n{\nprivate:\n    typedef point_to_point_range<Point, Range, closed, Strategy> base_type;\n    typedef typename base_type::iterator_type iterator_type;\n\n    template <typename Distance>\n    static inline void apply(Point const& point,\n                             iterator_type first,\n                             iterator_type last,\n                             Strategy const& strategy,\n                             iterator_type& it_min1,\n                             iterator_type& it_min2,\n                             Distance& dist_min)\n    {\n        BOOST_GEOMETRY_ASSERT( first != last );\n\n        base_type::apply(point, first, last, strategy,\n                         it_min1, it_min2, dist_min);\n\n        iterator_type it_back = --last;\n        Distance const zero = Distance(0);\n        Distance dist = strategy.apply(point, *it_back, *first);\n\n        if (geometry::math::equals(dist, zero))\n        {\n            dist_min = zero;\n            it_min1 = it_back;\n            it_min2 = first;\n        }\n        else if (dist < dist_min)\n        {\n            dist_min = dist;\n            it_min1 = it_back;\n            it_min2 = first;\n        }\n    }    \n\npublic:\n    typedef typename std::pair<iterator_type, iterator_type> return_type;\n\n    template <typename Distance>\n    static inline return_type apply(Point const& point,\n                                    iterator_type first,\n                                    iterator_type last,\n                                    Strategy const& strategy,\n                                    Distance& dist_min)\n    {\n        iterator_type it_min1, it_min2;\n\n        apply(point, first, last, strategy, it_min1, it_min2, dist_min);\n\n        return std::make_pair(it_min1, it_min2);\n    }\n\n    static inline return_type apply(Point const& point,\n                                    iterator_type first,\n                                    iterator_type last,\n                                    Strategy const& strategy)\n    {\n        typedef typename strategy::distance::services::return_type\n            <\n                Strategy,\n                Point,\n                typename geofeatures_boost::range_value<Range>::type\n            >::type distance_return_type;\n\n        distance_return_type dist_min;\n\n        return apply(point, first, last, strategy, dist_min);\n    }\n\n    template <typename Distance>\n    static inline return_type apply(Point const& point,\n                                    Range const& range,\n                                    Strategy const& strategy,\n                                    Distance& dist_min)\n    {\n        return apply(point,\n                     geofeatures_boost::begin(range),\n                     geofeatures_boost::end(range),\n                     strategy,\n                     dist_min);\n    }\n\n    static inline return_type apply(Point const& point,\n                                    Range const& range,\n                                    Strategy const& strategy)\n    {\n        return apply(point, geofeatures_boost::begin(range), geofeatures_boost::end(range), strategy);\n    }\n};\n\n\n}} // namespace detail::closest_feature\n#endif // DOXYGEN_NO_DETAIL\n\n}} // namespace geofeatures_boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_CLOSEST_FEATURE_POINT_TO_RANGE_HPP\n", "meta": {"hexsha": "70dd7161879e40c875e82b9e7a15334d6856f0aa", "size": 8037, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/closest_feature/point_to_range.hpp", "max_stars_repo_name": "xarvey/Yuuuuuge", "max_stars_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/closest_feature/point_to_range.hpp", "max_issues_repo_name": "xarvey/Yuuuuuge", "max_issues_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "Pods/GeoFeatures/GeoFeatures/boost/geometry/algorithms/detail/closest_feature/point_to_range.hpp", "max_forks_repo_name": "xarvey/Yuuuuuge", "max_forks_repo_head_hexsha": "9f4ec32f81cf813ea630ba2c44eb03970c56dad3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T03:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-21T07:16:29.000Z", "avg_line_length": 32.0199203187, "max_line_length": 116, "alphanum_fraction": 0.5508274232, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.23559260281945735}}
{"text": "/*\n  Author(s):      Robert I A Patterson\n  Project:        sweepc (population balance solver)\n  Sourceforge:    http://sourceforge.net/projects/mopssuite\n\n  Copyright (C) 2011 Robert I A Patterson.\n\n  File purpose:\n    Implementation of constant additive coagulation kernel\n\tfor the hybrid particle-number and particle model\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU General Public License\n    as published by the Free Software Foundation; either version 2\n    of the License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_hybrid_constcoag.h\"\n\n#include \"swp_params.h\"\n#include \"swp_cell.h\"\n#include \"swp_mechanism.h\"\n#include <boost/random/uniform_01.hpp>\n\nusing namespace Sweep::Processes;\n\nconst double Sweep::Processes::HybridConstantCoagulation::s_MajorantFactor = 1.5;\n\n/**\n * Main way of building a new coagulation object\n * @param[in] mech      Mechanism to which coagulation will belong\n *\n */\nSweep::Processes::HybridConstantCoagulation::HybridConstantCoagulation(const Sweep::Mechanism &mech)\n: Coagulation(mech)\n{\n    m_name = \"ConstantCoagulation\";\n}\n\n// Stream-reading constructor.\nSweep::Processes::HybridConstantCoagulation::HybridConstantCoagulation(std::istream &in, const Sweep::Mechanism &mech)\n: Coagulation(mech)\n{\n    m_name = \"ConstantCoagulation\";\n    Deserialize(in, mech);\n}\n\n// Returns the rate of the process for the given system.\ndouble Sweep::Processes::HybridConstantCoagulation::Rate(double t, const Cell &sys,\n                                                        const Geometry::LocalGeometry1d &local_geom) const\n{\n    // Get the number of particles in the system.\n    unsigned int n = sys.ParticleCount() + sys.Particles().GetTotalParticleNumber();\n\n    return A() * n * (n - 1) * s_MajorantFactor / sys.SampleVolume() / 2;\n}\n\n/**\n * Number of terms in the expression for the sum of the majorant\n * kernel over all particle pairs.\n */\nunsigned int Sweep::Processes::HybridConstantCoagulation::TermCount() const { return TYPE_COUNT; }\n\n\n/**\n * Calculate the terms in the sum of the majorant kernel over all particle\n * pairs, placing each term in successive positions of the sequence\n * beginning at iterm and return the sum of the terms added to that\n * vector.\n *\n * @param[in]     t            Time for which rates are requested\n * @param[in]     sys          Details of the particle population and environment\n * @param[in]     local_geom   Position information\n * @param[in,out] iterm        Pointer to start of sequence to hold the rate terms, returned as one past the end.\n */\ndouble Sweep::Processes::HybridConstantCoagulation::RateTerms(double t, const Cell &sys,\n                                                             const Geometry::LocalGeometry1d &local_geom,\n                                                             fvector::iterator &iterm) const\n{\n    return *(iterm++) = Rate(t, sys, local_geom);\n}\n\n/*!\n * \n *\n * \\param[in]       t           Time\n * \\param[in,out]   sys         System to update\n * \\param[in]       local_geom  Details of local phsyical layout\n * \\param[in]       iterm       Process term responsible for this event\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      0 on success, otherwise negative.\n */\nint HybridConstantCoagulation::Perform(double t, Sweep::Cell &sys,\n                             const Geometry::LocalGeometry1d& local_geom,\n                             unsigned int iterm,\n                             Sweep::rng_type &rng) const\n{\n\tPartPtrVector dummy;\n    // Select properties by which to choose particles.\n    // Note we need to choose 2 particles.  One particle must be chosen\n    // uniformly and one with probability proportional\n    // to particle mass.\n\n    int ip1 = -1, ip2 = -1;\n    unsigned int index1 = 0, index2 = 0;\n\n    // Hybrid particle model flags\n    bool hybrid_flag = m_mech->IsHybrid();\n    bool ip1_flag = false;\n    bool ip2_flag = false;\n    bool coag_in_place = false;\n\n    double n_incep = sys.Particles().GetTotalParticleNumber();\n    double n_other = sys.ParticleCount();\n    double n_total = n_incep + n_other;\n\n    boost::uniform_01<rng_type&, double> unifDistrib(rng);\n    double alpha1 = unifDistrib() * n_total;\n    double alpha2 = unifDistrib() * n_total;\n    if (n_total <= 0)\n        return -1;\n\n    if (n_total < 2) // if there are < 2 SPs but incepting class has weight >= 2, we can still act\n        return 1;\n    else \n    {\n        if (hybrid_flag)\n        {\n            // Particle 1 is picked uniformly. Here, the\n            // incepting class has multiple weight 1 particles\n            // Account for this by selecting this by default and \n            // switching with probability n_other/n_total\n            ip1 = -2;\n            ip2 = -2;\n            if (n_other >= alpha1)\n            {\n                ip1 = sys.Particles().Select_usingGivenRand(iUniform, alpha1, rng);\n            }\n        }\n        else\n        {\n            ip1 = sys.Particles().Select(rng);\n            ip2 = sys.Particles().Select(rng);\n        }\n    }\n\n    // Choose and get first particle, then update it.\n    Particle *sp1 = NULL;\n    double dsp1 = 0.0;\n    bool must_switch = false;\n\n    // Is this an incepting class particle?\n    if (hybrid_flag && ip1 == -2)\n    {\n        // Note don't need to add it to the ensemble unless coagulation is successful\n        index1 = m_mech->SetRandomParticle(sys.Particles(), t, alpha1 - n_other, iUniform, rng);\n\t\tif (index1 == 0)\n\t\t\treturn -1;\n        sp1 = sys.Particles().GetPNParticleAt(index1)->Clone();\n        sp1->SetTime(t);\n        ip1_flag = true;                                                                // Flag sp1 as an incepting class particle\n    }\n    else\n    {\n        if (ip1 >= 0) {\n            sp1 = sys.Particles().At(ip1);\n        }\n        else {\n            // Failed to choose a particle.\n            return -1;\n        }\n    }\n\n    // Choose and get unique second particle, then update it.  Note, we are allowed to do\n    // this even if the first particle was invalidated.\n    unsigned int guard = 0;\n    if (!hybrid_flag)\n    {\n        while ((ip2 == ip1) && (++guard < 1000))\n        {\n            ip2 = sys.Particles().Select(rng);\n        }\n    }\n    else\n    {\n        ip2 = ip1;\n        bool unsuitableChoice = true;\n        unsigned int n_index1 = sys.Particles().NumberAtIndex(index1);\n        while (unsuitableChoice && (++guard < 1000))\n        {\n            alpha2 = unifDistrib() * n_total;\n            if (alpha2 <= n_incep)\n            {\n                index2 = m_mech->SetRandomParticle(sys.Particles(), t, alpha2, iUniform, rng); \n\t\t\t\tif (index2 == 0)\n\t\t\t\t{\n\t\t\t\t\tif (ip1_flag)\n\t\t\t\t\t{\n\t\t\t\t\t\tdelete sp1;\n\t\t\t\t\t\tsp1 = NULL;\n\t\t\t\t\t}\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n                if (!((index2 == index1) && (n_index1 == 1)))\n                {\n                    unsuitableChoice = false;\n                    ip2 = -2;\n                }\n            }\n            else\n            {\n                ip2 = sys.Particles().Select_usingGivenRand(iUniform, alpha2 - n_incep, rng);\n                if (!(ip2 == ip1))\n                    unsuitableChoice = false;\n            }\n        }\n    }\n\n    // Choose and get second particle, then update it.\n    Particle *sp2 = NULL;\n    double dsp2 = 0.0;\n\n    // Is this an incepting class particle?\n    if (hybrid_flag && ip2 == -2)\n    {\n        // Note don't need to add it to the ensemble unless coagulation is successful\n        sp2 = sys.Particles().GetPNParticleAt(index2)->Clone();\n        sp2->SetTime(t);\n        ip2_flag = true;                                                             // Flag sp2 as an incepting class particle\n    }\n    else\n    {\n        if ((ip2 >= 0) && (ip2 != ip1)) {\n            sp2 = sys.Particles().At(ip2);\n        }\n        else {\n            // Failed to select a unique particle.\n            return -1;\n        }\n    }\n\n    //Calculate the majorant rate before updating the particles\n    const double majk = MajorantKernel(*sp1, *sp2, sys, Default);\n\n    //Update the particles\n    if (t > sp1->LastUpdateTime())\n        m_mech->UpdateParticle(*sp1, sys, t, ip1, rng, dummy);\n\n    // Check that particle is still valid.  If not,\n    // remove it and cease coagulating.\n    if (!sp1->IsValid()) {\n        if (!ip1_flag)\n        {\n            // Must remove first particle now.\n            sys.Particles().Remove(ip1);\n        }\n        else\n        {\n            // Particle sp1 is not in the ensemble, must manually delete it\n            delete sp1;\n            sp1 = NULL;\n        }\n        // Invalidating the index tells this routine not to perform coagulation.\n        ip1 = -1;\n        return 0;\n    }\n\n    if (t > sp2->LastUpdateTime())\n        m_mech->UpdateParticle(*sp2, sys, t, ip2, rng, dummy);\n\n    // Check validity of particles after update.\n    if (!sp2->IsValid()) {\n        // Tell the ensemble to update particle one before we confuse things\n        // by removing particle 2\n        if (!ip1_flag)\n            sys.Particles().Update(ip1);\n\n        if (!ip2_flag)\n        {\n            // Must remove second particle now.\n            sys.Particles().Remove(ip2);\n        }\n        else\n        {\n            // Particle sp2 is not in the ensemble, must manually delete it\n            delete sp2;\n            sp2 = NULL;\n        }\n\n        // Invalidating the index tells this routine not to perform coagulation.\n        ip2 = -1;\n\n        return 0;\n    }\n\n    // Check that both the particles are still valid.\n    if ((ip1 != -1) && (ip2 != -1)) {\n        // Must check for ficticious event now by comparing the original\n        // majorant rate and the current (after updates) true rate.\n\n        double truek = CoagKernel(*sp1, *sp2, sys);\n\n        if (!Fictitious(majk, truek, rng)) {\n            if (ip1_flag)\n            {\n                sys.Particles().UpdateTotalsWithIndex(index1, -1.0);\n                sys.Particles().UpdateNumberAtIndex(index1, -1);\n                sys.Particles().UpdateTotalParticleNumber(-1);\n                unsigned int index12 = index1 + index2;\n                // Allow for coagulation in place if the combined particle is small enough\n\t\t\t\tif ((m_mech->CoagulateInList()) && ip2_flag && (index12 < sys.Particles().GetHybridThreshold()))\n                {\n                    coag_in_place = true;\n                    sys.Particles().UpdateTotalsWithIndex(index12, 1.0);\n                    sys.Particles().UpdateNumberAtIndex(index12, 1);\n                    sys.Particles().UpdateTotalParticleNumber(1);\n                    if (sp1 != NULL)\n                    {\n                        delete sp1;\n                        sp1 = NULL;\n                    }\n                }\n                else\n                {\n                    // otherwise add the particle to the ensemble\n                    ip1 = sys.Particles().Add(*sp1, rng, ip2, true);\n                }\n            }\n            if (ip2_flag)\n            {\n                sys.Particles().UpdateTotalsWithIndex(index2, -1.0);\n                sys.Particles().UpdateNumberAtIndex(index2, -1);\n                sys.Particles().UpdateTotalParticleNumber(-1);\n            }\n            if (!coag_in_place)\n                JoinParticles(t, ip1, sp1, ip2, sp2, sys, rng);\n            if (ip2_flag && sp2 != NULL)\n            {\n                delete sp2;\n                sp2 = NULL;\n            }\n        } else {\n            if (!ip1_flag)\n                sys.Particles().Update(ip1);\n            else if (sp1 != NULL)\n            {\n                delete sp1;\n                sp1 = NULL;\n            }\n            if (!ip2_flag)\n                sys.Particles().Update(ip2);\n            else if (sp2 != NULL)\n            {\n                delete sp2;\n                sp2 = NULL;\n            }\n            return 1; // Ficticious event.\n        }\n    } else {\n        // One or both particles were invalidated on update,\n        // but that's not a problem.  Information on the update\n        // of valid particles must be propagated into the binary\n        // tree\n        if (ip1 != -1)\n        {\n            if (!ip1_flag)\n                sys.Particles().Update(ip1);\n        }\n        if (ip2 != -1 && !ip2_flag)\n            sys.Particles().Update(ip2);\n\n        if (ip1_flag && sp1 != NULL)\n        {\n            delete sp1;\n            sp1 = NULL;\n        }\n        if (ip2_flag && sp2 != NULL)\n        {\n            delete sp2;\n            sp2 = NULL;\n        }\n    }\n\n    if (ip1_flag && sp1 != NULL && ip1 == -2)\n    {\n        delete sp1;\n        sp1 = NULL;\n    }\n\n    if (ip2_flag && sp2 != NULL)\n    {\n        delete sp2;\n        sp2 = NULL;\n    }\n\n    return 0;\n}\n\n/**\n * Calculate the coagulation kernel between two particles in a given environment.\n * Note that the details of the environment are not currently used.\n *\n *@param[in]    sp1         First particle\n *@param[in]    sp2         Second particle\n *@param[in]    sys         Details of the environment\n *\n *@return       Value of kernel\n */\ndouble Sweep::Processes::HybridConstantCoagulation::CoagKernel(const Particle &sp1,\n                                                              const Particle &sp2,\n                                                              const Cell& sys) const\n{\n    return A();\n}\n\n\n/**\n * Calculate the majorant kernel between two particles in a given environment.\n * Note that the details of the environment are not currently used.\n *\n *@param[in]    sp1         First particle\n *@param[in]    sp2         Second particle\n *@param[in]    sys         Details of the environment\n *@param[in]    maj         Unused flag to indicate which majorant kernel is required\n *\n *@return       Value of majorant kernel\n */\ndouble Sweep::Processes::HybridConstantCoagulation::MajorantKernel(const Particle &sp1,\n                                                                  const Particle &sp2,\n                                                                  const Cell& sys,\n                                                                  const MajorantType maj) const\n{\n    return CoagKernel(sp1, sp2, sys) * s_MajorantFactor;\n}\n\n", "meta": {"hexsha": "281eeab3bf9099e53e5af6ef23dc052c51f57c97", "size": 14896, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_hybrid_constcoag.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_hybrid_constcoag.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_hybrid_constcoag.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 32.2424242424, "max_line_length": 130, "alphanum_fraction": 0.5491407089, "num_tokens": 3525, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725051, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23559260281945732}}
{"text": "#ifndef VIENNACL_LINALG_AMG_HPP_\n#define VIENNACL_LINALG_AMG_HPP_\n\n/* =========================================================================\n   Copyright (c) 2010-2014, Institute for Microelectronics,\n                            Institute for Analysis and Scientific Computing,\n                            TU Wien.\n   Portions of this software are copyright by UChicago Argonne, LLC.\n\n                            -----------------\n                  ViennaCL - The Vienna Computing Library\n                            -----------------\n\n   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at\n\n   (A list of authors and contributors can be found in the PDF manual)\n\n   License:         MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** @file viennacl/linalg/amg.hpp\n    @brief Main include file for algebraic multigrid (AMG) preconditioners.  Experimental.\n\n    Implementation contributed by Markus Wagner\n*/\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n#include <boost/numeric/ublas/operation.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector.hpp>\n#include <boost/numeric/ublas/triangular.hpp>\n#include <vector>\n#include <cmath>\n#include \"viennacl/forwards.h\"\n#include \"viennacl/tools/tools.hpp\"\n#include \"viennacl/linalg/prod.hpp\"\n#include \"viennacl/linalg/direct_solve.hpp\"\n\n#include \"viennacl/linalg/detail/amg/amg_base.hpp\"\n#include \"viennacl/linalg/detail/amg/amg_coarse.hpp\"\n#include \"viennacl/linalg/detail/amg/amg_interpol.hpp\"\n\n#include <map>\n\n#ifdef VIENNACL_WITH_OPENMP\n #include <omp.h>\n#endif\n\n#include \"viennacl/linalg/detail/amg/amg_debug.hpp\"\n\n#define VIENNACL_AMG_COARSE_LIMIT 50\n#define VIENNACL_AMG_MAX_LEVELS 100\n\nnamespace viennacl\n{\n  namespace linalg\n  {\n    typedef detail::amg::amg_tag          amg_tag;\n\n\n\n    /** @brief Setup AMG preconditioner\n    *\n    * @param A      Operator matrices on all levels\n    * @param P      Prolongation/Interpolation operators on all levels\n    * @param Pointvector  Vector of points on all levels\n    * @param tag    AMG preconditioner tag\n    */\n    template<typename InternalType1, typename InternalType2>\n    void amg_setup(InternalType1 & A, InternalType1 & P, InternalType2 & Pointvector, amg_tag & tag)\n    {\n      typedef typename InternalType2::value_type PointVectorType;\n\n      unsigned int i, iterations, c_points, f_points;\n      detail::amg::amg_slicing<InternalType1,InternalType2> Slicing;\n\n      // Set number of iterations. If automatic coarse grid construction is chosen (0), then set a maximum size and stop during the process.\n      iterations = tag.get_coarselevels();\n      if (iterations == 0)\n        iterations = VIENNACL_AMG_MAX_LEVELS;\n\n      // For parallel coarsenings build data structures (number of threads set automatically).\n      if (tag.get_coarse() == VIENNACL_AMG_COARSE_RS0 || tag.get_coarse() == VIENNACL_AMG_COARSE_RS3)\n        Slicing.init(iterations);\n\n      for (i=0; i<iterations; ++i)\n      {\n        // Initialize Pointvector on level i and construct points.\n        Pointvector[i] = PointVectorType(static_cast<unsigned int>(A[i].size1()));\n        Pointvector[i].init_points();\n\n        // Construct C and F points on coarse level (i is fine level, i+1 coarse level).\n        detail::amg::amg_coarse (i, A, Pointvector, Slicing, tag);\n\n        // Calculate number of C and F points on level i.\n        c_points = Pointvector[i].get_cpoints();\n        f_points = Pointvector[i].get_fpoints();\n\n        #if defined (VIENNACL_AMG_DEBUG) //or defined(VIENNACL_AMG_DEBUGBENCH)\n        std::cout << \"Level \" << i << \": \";\n        std::cout << \"No of C points = \" << c_points << \", \";\n        std::cout << \"No of F points = \" << f_points << std::endl;\n        #endif\n\n        // Stop routine when the maximal coarse level is found (no C or F point). Coarsest level is level i.\n        if (c_points == 0 || f_points == 0)\n          break;\n\n        // Construct interpolation matrix for level i.\n        detail::amg::amg_interpol (i, A, P, Pointvector, tag);\n\n        // Compute coarse grid operator (A[i+1] = R * A[i] * P) with R = trans(P).\n        detail::amg::amg_galerkin_prod(A[i], P[i], A[i+1]);\n\n        // Test triple matrix product. Very slow for large matrix sizes (ublas).\n        // test_triplematprod(A[i],P[i],A[i+1]);\n\n        Pointvector[i].delete_points();\n\n        #ifdef VIENNACL_AMG_DEBUG\n        std::cout << \"Coarse Grid Operator Matrix:\" << std::endl;\n        printmatrix (A[i+1]);\n        #endif\n\n        // If Limit of coarse points is reached then stop. Coarsest level is level i+1.\n        if (tag.get_coarselevels() == 0 && c_points <= VIENNACL_AMG_COARSE_LIMIT)\n        {\n          tag.set_coarselevels(i+1);\n          return;\n        }\n      }\n      tag.set_coarselevels(i);\n    }\n\n    /** @brief Initialize AMG preconditioner\n    *\n    * @param mat    System matrix\n    * @param A      Operator matrices on all levels\n    * @param P      Prolongation/Interpolation operators on all levels\n    * @param Pointvector  Vector of points on all levels\n    * @param tag    AMG preconditioner tag\n    */\n    template<typename MatrixType, typename InternalType1, typename InternalType2>\n    void amg_init(MatrixType const & mat, InternalType1 & A, InternalType1 & P, InternalType2 & Pointvector, amg_tag & tag)\n    {\n      //typedef typename MatrixType::value_type ScalarType;\n      typedef typename InternalType1::value_type SparseMatrixType;\n\n      if (tag.get_coarselevels() > 0)\n      {\n        A.resize(tag.get_coarselevels()+1);\n        P.resize(tag.get_coarselevels());\n        Pointvector.resize(tag.get_coarselevels());\n      }\n      else\n      {\n        A.resize(VIENNACL_AMG_MAX_LEVELS+1);\n        P.resize(VIENNACL_AMG_MAX_LEVELS);\n        Pointvector.resize(VIENNACL_AMG_MAX_LEVELS);\n      }\n\n      // Insert operator matrix as operator for finest level.\n      SparseMatrixType A0 (mat);\n      A.insert_element (0, A0);\n    }\n\n    /** @brief Save operators after setup phase for CPU computation.\n    *\n    * @param A      Operator matrices on all levels on the CPU\n    * @param P      Prolongation/Interpolation operators on all levels on the CPU\n    * @param R      Restriction operators on all levels on the CPU\n    * @param A_setup    Operators matrices on all levels from setup phase\n    * @param P_setup    Prolongation/Interpolation operators on all levels from setup phase\n    * @param tag    AMG preconditioner tag\n    */\n    template<typename InternalType1, typename InternalType2>\n    void amg_transform_cpu (InternalType1 & A, InternalType1 & P, InternalType1 & R, InternalType2 & A_setup, InternalType2 & P_setup, amg_tag & tag)\n    {\n      //typedef typename InternalType1::value_type MatrixType;\n\n      // Resize internal data structures to actual size.\n      A.resize(tag.get_coarselevels()+1);\n      P.resize(tag.get_coarselevels());\n      R.resize(tag.get_coarselevels());\n\n      // Transform into matrix type.\n      for (unsigned int i=0; i<tag.get_coarselevels()+1; ++i)\n      {\n        A[i].resize(A_setup[i].size1(),A_setup[i].size2(),false);\n        A[i] = A_setup[i];\n      }\n      for (unsigned int i=0; i<tag.get_coarselevels(); ++i)\n      {\n        P[i].resize(P_setup[i].size1(),P_setup[i].size2(),false);\n        P[i] = P_setup[i];\n      }\n      for (unsigned int i=0; i<tag.get_coarselevels(); ++i)\n      {\n        R[i].resize(P_setup[i].size2(),P_setup[i].size1(),false);\n        P_setup[i].set_trans(true);\n        R[i] = P_setup[i];\n        P_setup[i].set_trans(false);\n      }\n    }\n\n    /** @brief Save operators after setup phase for GPU computation.\n    *\n    * @param A      Operator matrices on all levels on the GPU\n    * @param P      Prolongation/Interpolation operators on all levels on the GPU\n    * @param R      Restriction operators on all levels on the GPU\n    * @param A_setup    Operators matrices on all levels from setup phase\n    * @param P_setup    Prolongation/Interpolation operators on all levels from setup phase\n    * @param tag    AMG preconditioner tag\n    * @param ctx      Optional context in which the auxiliary objects are created (one out of multiple OpenCL contexts, CUDA, host)\n    */\n    template<typename InternalType1, typename InternalType2>\n    void amg_transform_gpu (InternalType1 & A, InternalType1 & P, InternalType1 & R, InternalType2 & A_setup, InternalType2 & P_setup, amg_tag & tag, viennacl::context ctx)\n    {\n      // Resize internal data structures to actual size.\n      A.resize(tag.get_coarselevels()+1);\n      P.resize(tag.get_coarselevels());\n      R.resize(tag.get_coarselevels());\n\n      // Copy to GPU using the internal sparse matrix structure: std::vector<std::map>.\n      for (unsigned int i=0; i<tag.get_coarselevels()+1; ++i)\n      {\n        viennacl::switch_memory_context(A[i], ctx);\n        //A[i].resize(A_setup[i].size1(),A_setup[i].size2(),false);\n        viennacl::copy(*(A_setup[i].get_internal_pointer()),A[i]);\n      }\n      for (unsigned int i=0; i<tag.get_coarselevels(); ++i)\n      {\n        viennacl::switch_memory_context(P[i], ctx);\n        //P[i].resize(P_setup[i].size1(),P_setup[i].size2(),false);\n        viennacl::copy(*(P_setup[i].get_internal_pointer()),P[i]);\n        //viennacl::copy((boost::numeric::ublas::compressed_matrix<ScalarType>)P_setup[i],P[i]);\n      }\n      for (unsigned int i=0; i<tag.get_coarselevels(); ++i)\n      {\n        viennacl::switch_memory_context(R[i], ctx);\n        //R[i].resize(P_setup[i].size2(),P_setup[i].size1(),false);\n        P_setup[i].set_trans(true);\n        viennacl::copy(*(P_setup[i].get_internal_pointer()),R[i]);\n        P_setup[i].set_trans(false);\n      }\n    }\n\n    /** @brief Setup data structures for precondition phase.\n    *\n    * @param result    Result vector on all levels\n    * @param rhs    RHS vector on all levels\n    * @param residual    Residual vector on all levels\n    * @param A      Operators matrices on all levels from setup phase\n    * @param tag    AMG preconditioner tag\n    */\n    template<typename InternalVectorType, typename SparseMatrixType>\n    void amg_setup_apply (InternalVectorType & result, InternalVectorType & rhs, InternalVectorType & residual, SparseMatrixType const & A, amg_tag const & tag)\n    {\n      typedef typename InternalVectorType::value_type VectorType;\n\n      result.resize(tag.get_coarselevels()+1);\n      rhs.resize(tag.get_coarselevels()+1);\n      residual.resize(tag.get_coarselevels());\n\n      for (unsigned int level=0; level < tag.get_coarselevels()+1; ++level)\n      {\n        result[level] = VectorType(A[level].size1());\n        result[level].clear();\n        rhs[level] = VectorType(A[level].size1());\n        rhs[level].clear();\n      }\n      for (unsigned int level=0; level < tag.get_coarselevels(); ++level)\n      {\n        residual[level] = VectorType(A[level].size1());\n        residual[level].clear();\n      }\n    }\n\n\n    /** @brief Setup data structures for precondition phase for later use on the GPU\n    *\n    * @param result    Result vector on all levels\n    * @param rhs    RHS vector on all levels\n    * @param residual    Residual vector on all levels\n    * @param A      Operators matrices on all levels from setup phase\n    * @param tag    AMG preconditioner tag\n    * @param ctx      Optional context in which the auxiliary objects are created (one out of multiple OpenCL contexts, CUDA, host)\n    */\n    template<typename InternalVectorType, typename SparseMatrixType>\n    void amg_setup_apply (InternalVectorType & result, InternalVectorType & rhs, InternalVectorType & residual, SparseMatrixType const & A, amg_tag const & tag, viennacl::context ctx)\n    {\n      typedef typename InternalVectorType::value_type VectorType;\n\n      result.resize(tag.get_coarselevels()+1);\n      rhs.resize(tag.get_coarselevels()+1);\n      residual.resize(tag.get_coarselevels());\n\n      for (unsigned int level=0; level < tag.get_coarselevels()+1; ++level)\n      {\n        result[level] = VectorType(A[level].size1(), ctx);\n        rhs[level] = VectorType(A[level].size1(), ctx);\n      }\n      for (unsigned int level=0; level < tag.get_coarselevels(); ++level)\n      {\n        residual[level] = VectorType(A[level].size1(), ctx);\n      }\n    }\n\n\n    /** @brief Pre-compute LU factorization for direct solve (ublas library).\n     *  @brief Speeds up precondition phase as this is computed only once overall instead of once per iteration.\n    *\n    * @param op      Operator matrix for direct solve\n    * @param Permutation  Permutation matrix which saves the factorization result\n    * @param A      Operator matrix on coarsest level\n    */\n    template<typename ScalarType, typename SparseMatrixType>\n    void amg_lu(boost::numeric::ublas::compressed_matrix<ScalarType> & op, boost::numeric::ublas::permutation_matrix<> & Permutation, SparseMatrixType const & A)\n    {\n      typedef typename SparseMatrixType::const_iterator1 ConstRowIterator;\n      typedef typename SparseMatrixType::const_iterator2 ConstColIterator;\n\n      // Copy to operator matrix. Needed\n      op.resize(A.size1(),A.size2(),false);\n      for (ConstRowIterator row_iter = A.begin1(); row_iter != A.end1(); ++row_iter)\n        for (ConstColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n          op (col_iter.index1(), col_iter.index2()) = *col_iter;\n\n      // Permutation matrix has to be reinitialized with actual size. Do not clear() or resize()!\n      Permutation = boost::numeric::ublas::permutation_matrix<> (op.size1());\n      boost::numeric::ublas::lu_factorize(op,Permutation);\n    }\n\n    /** @brief AMG preconditioner class, can be supplied to solve()-routines\n    */\n    template<typename MatrixType>\n    class amg_precond\n    {\n      typedef typename MatrixType::value_type ScalarType;\n      typedef boost::numeric::ublas::vector<ScalarType> VectorType;\n      typedef detail::amg::amg_sparsematrix<ScalarType> SparseMatrixType;\n      typedef detail::amg::amg_pointvector PointVectorType;\n\n      typedef typename SparseMatrixType::const_iterator1 InternalConstRowIterator;\n      typedef typename SparseMatrixType::const_iterator2 InternalConstColIterator;\n      typedef typename SparseMatrixType::iterator1 InternalRowIterator;\n      typedef typename SparseMatrixType::iterator2 InternalColIterator;\n\n      boost::numeric::ublas::vector <SparseMatrixType> A_setup;\n      boost::numeric::ublas::vector <SparseMatrixType> P_setup;\n      boost::numeric::ublas::vector <MatrixType> A;\n      boost::numeric::ublas::vector <MatrixType> P;\n      boost::numeric::ublas::vector <MatrixType> R;\n      boost::numeric::ublas::vector <PointVectorType> Pointvector;\n\n      mutable boost::numeric::ublas::compressed_matrix<ScalarType> op;\n      mutable boost::numeric::ublas::permutation_matrix<> Permutation;\n\n      mutable boost::numeric::ublas::vector <VectorType> result;\n      mutable boost::numeric::ublas::vector <VectorType> rhs;\n      mutable boost::numeric::ublas::vector <VectorType> residual;\n\n      mutable bool done_init_apply;\n\n      amg_tag tag_;\n    public:\n\n      amg_precond(): Permutation(0) {}\n      /** @brief The constructor. Saves system matrix, tag and builds data structures for setup.\n      *\n      * @param mat  System matrix\n      * @param tag  The AMG tag\n      */\n      amg_precond(MatrixType const & mat, amg_tag const & tag): Permutation(0)\n      {\n        tag_ = tag;\n        // Initialize data structures.\n        amg_init (mat,A_setup,P_setup,Pointvector,tag_);\n\n        done_init_apply = false;\n      }\n\n      /** @brief Start setup phase for this class and copy data structures.\n      */\n      void setup()\n      {\n        // Start setup phase.\n        amg_setup(A_setup,P_setup,Pointvector,tag_);\n        // Transform to CPU-Matrixtype for precondition phase.\n        amg_transform_cpu(A,P,R,A_setup,P_setup,tag_);\n\n        done_init_apply = false;\n      }\n\n      /** @brief Prepare data structures for preconditioning:\n       *  Build data structures for precondition phase.\n       *  Do LU factorization on coarsest level.\n      */\n      void init_apply() const\n      {\n        // Setup precondition phase (Data structures).\n        amg_setup_apply(result,rhs,residual,A_setup,tag_);\n        // Do LU factorization for direct solve.\n        amg_lu(op,Permutation,A_setup[tag_.get_coarselevels()]);\n\n        done_init_apply = true;\n      }\n\n      /** @brief Returns complexity measures.\n      *\n      * @param avgstencil  Average stencil sizes on all levels\n      * @return     Operator complexity of AMG method\n      */\n      template<typename VectorType>\n      ScalarType calc_complexity(VectorType & avgstencil)\n      {\n        avgstencil = VectorType (tag_.get_coarselevels()+1);\n        unsigned int nonzero=0, systemmat_nonzero=0, level_coefficients=0;\n\n        for (unsigned int level=0; level < tag_.get_coarselevels()+1; ++level)\n        {\n          level_coefficients = 0;\n          for (InternalRowIterator row_iter = A_setup[level].begin1(); row_iter != A_setup[level].end1(); ++row_iter)\n          {\n            for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n            {\n              if (level == 0)\n                systemmat_nonzero++;\n              nonzero++;\n              level_coefficients++;\n            }\n          }\n          avgstencil[level] = level_coefficients/static_cast<ScalarType>(A_setup[level].size1());\n        }\n        return nonzero/static_cast<ScalarType>(systemmat_nonzero);\n      }\n\n      /** @brief Precondition Operation\n      *\n      * @param vec The vector to which preconditioning is applied to (ublas version)\n      */\n      template<typename VectorType>\n      void apply(VectorType & vec) const\n      {\n        // Build data structures and do lu factorization before first iteration step.\n        if (!done_init_apply)\n          init_apply();\n\n        int level;\n\n        // Precondition operation (Yang, p.3)\n        rhs[0] = vec;\n        for (level=0; level <static_cast<int>(tag_.get_coarselevels()); level++)\n        {\n          result[level].clear();\n\n          // Apply Smoother presmooth_ times.\n          smooth_jacobi (level, tag_.get_presmooth(), result[level], rhs[level]);\n\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"After presmooth:\" << std::endl;\n          printvector(result[level]);\n          #endif\n\n          // Compute residual.\n          residual[level] = rhs[level] - boost::numeric::ublas::prod (A[level],result[level]);\n\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"Residual:\" << std::endl;\n          printvector(residual[level]);\n          #endif\n\n          // Restrict to coarse level. Restricted residual is RHS of coarse level.\n          rhs[level+1] = boost::numeric::ublas::prod (R[level],residual[level]);\n\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"Restricted Residual: \" << std::endl;\n          printvector(rhs[level+1]);\n          #endif\n        }\n\n        // On highest level use direct solve to solve equation.\n        result[level] = rhs[level];\n        boost::numeric::ublas::lu_substitute(op,Permutation,result[level]);\n\n        #ifdef VIENNACL_AMG_DEBUG\n        std::cout << \"After direct solve: \" << std::endl;\n        printvector (result[level]);\n        #endif\n\n        for (level=tag_.get_coarselevels()-1; level >= 0; level--)\n        {\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"Coarse Error: \" << std::endl;\n          printvector(result[level+1]);\n          #endif\n\n          // Interpolate error to fine level. Correct solution by adding error.\n          result[level] += boost::numeric::ublas::prod (P[level], result[level+1]);\n\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"Corrected Result: \" << std::endl;\n          printvector (result[level]);\n          #endif\n\n          // Apply Smoother postsmooth_ times.\n          smooth_jacobi (level, tag_.get_postsmooth(), result[level], rhs[level]);\n\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"After postsmooth: \" << std::endl;\n          printvector (result[level]);\n          #endif\n        }\n        vec = result[0];\n      }\n\n      /** @brief (Weighted) Jacobi Smoother (CPU version)\n      * @param level    Coarse level to which smoother is applied to\n      * @param iterations  Number of smoother iterations\n      * @param x     The vector smoothing is applied to\n      * @param rhs    The right hand side of the equation for the smoother\n      */\n      template<typename VectorType>\n      void smooth_jacobi(int level, int const iterations, VectorType & x, VectorType const & rhs) const\n      {\n        VectorType old_result (x.size());\n        long index;\n        ScalarType sum = 0, diag = 1;\n\n        for (int i=0; i<iterations; ++i)\n        {\n          old_result = x;\n          x.clear();\n#ifdef VIENNACL_WITH_OPENMP\n          #pragma omp parallel for private (sum,diag) shared (rhs,x)\n#endif\n          for (index=0; index < static_cast<long>(A_setup[level].size1()); ++index)\n          {\n            InternalConstRowIterator row_iter = A_setup[level].begin1();\n            row_iter += index;\n            sum = 0;\n            diag = 1;\n            for (InternalConstColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n            {\n              if (col_iter.index1() == col_iter.index2())\n                diag = *col_iter;\n              else\n                sum += *col_iter * old_result[col_iter.index2()];\n            }\n            x[index]= static_cast<ScalarType>(tag_.get_jacobiweight()) * (rhs[index] - sum) / diag + (1-static_cast<ScalarType>(tag_.get_jacobiweight())) * old_result[index];\n          }\n        }\n      }\n\n      amg_tag & tag() { return tag_; }\n    };\n\n    /** @brief AMG preconditioner class, can be supplied to solve()-routines.\n    *\n    *  Specialization for compressed_matrix\n    */\n    template<typename ScalarType, unsigned int MAT_ALIGNMENT>\n    class amg_precond< compressed_matrix<ScalarType, MAT_ALIGNMENT> >\n    {\n      typedef viennacl::compressed_matrix<ScalarType, MAT_ALIGNMENT> MatrixType;\n      typedef viennacl::vector<ScalarType> VectorType;\n      typedef detail::amg::amg_sparsematrix<ScalarType> SparseMatrixType;\n      typedef detail::amg::amg_pointvector PointVectorType;\n\n      typedef typename SparseMatrixType::const_iterator1 InternalConstRowIterator;\n      typedef typename SparseMatrixType::const_iterator2 InternalConstColIterator;\n      typedef typename SparseMatrixType::iterator1 InternalRowIterator;\n      typedef typename SparseMatrixType::iterator2 InternalColIterator;\n\n      boost::numeric::ublas::vector <SparseMatrixType> A_setup;\n      boost::numeric::ublas::vector <SparseMatrixType> P_setup;\n      boost::numeric::ublas::vector <MatrixType> A;\n      boost::numeric::ublas::vector <MatrixType> P;\n      boost::numeric::ublas::vector <MatrixType> R;\n      boost::numeric::ublas::vector <PointVectorType> Pointvector;\n\n      mutable boost::numeric::ublas::compressed_matrix<ScalarType> op;\n      mutable boost::numeric::ublas::permutation_matrix<> Permutation;\n\n      mutable boost::numeric::ublas::vector <VectorType> result;\n      mutable boost::numeric::ublas::vector <VectorType> rhs;\n      mutable boost::numeric::ublas::vector <VectorType> residual;\n\n      viennacl::context ctx_;\n\n      mutable bool done_init_apply;\n\n      amg_tag tag_;\n\n    public:\n\n      amg_precond(): Permutation(0) {}\n\n      /** @brief The constructor. Builds data structures.\n      *\n      * @param mat  System matrix\n      * @param tag  The AMG tag\n      */\n      amg_precond(compressed_matrix<ScalarType, MAT_ALIGNMENT> const & mat, amg_tag const & tag): Permutation(0), ctx_(viennacl::traits::context(mat))\n      {\n        tag_ = tag;\n\n        // Copy to CPU. Internal structure of sparse matrix is used for copy operation.\n        std::vector<std::map<unsigned int, ScalarType> > mat2 = std::vector<std::map<unsigned int, ScalarType> >(mat.size1());\n        viennacl::copy(mat, mat2);\n\n        // Initialize data structures.\n        amg_init (mat2,A_setup,P_setup,Pointvector,tag_);\n\n        done_init_apply = false;\n      }\n\n      /** @brief Start setup phase for this class and copy data structures.\n      */\n      void setup()\n      {\n        // Start setup phase.\n        amg_setup(A_setup,P_setup,Pointvector, tag_);\n        // Transform to GPU-Matrixtype for precondition phase.\n        amg_transform_gpu(A,P,R,A_setup,P_setup, tag_, ctx_);\n\n        done_init_apply = false;\n      }\n\n      /** @brief Prepare data structures for preconditioning:\n       *  Build data structures for precondition phase.\n       *  Do LU factorization on coarsest level.\n      */\n      void init_apply() const\n      {\n        // Setup precondition phase (Data structures).\n        amg_setup_apply(result,rhs,residual,A_setup,tag_, ctx_);\n        // Do LU factorization for direct solve.\n        amg_lu(op,Permutation,A_setup[tag_.get_coarselevels()]);\n\n        done_init_apply = true;\n      }\n\n      /** @brief Returns complexity measures\n      *\n      * @param avgstencil  Average stencil sizes on all levels\n      * @return     Operator complexity of AMG method\n      */\n      template<typename VectorType>\n      ScalarType calc_complexity(VectorType & avgstencil)\n      {\n        avgstencil = VectorType (tag_.get_coarselevels()+1);\n        unsigned int nonzero=0, systemmat_nonzero=0, level_coefficients=0;\n\n        for (unsigned int level=0; level < tag_.get_coarselevels()+1; ++level)\n        {\n          level_coefficients = 0;\n          for (InternalRowIterator row_iter = A_setup[level].begin1(); row_iter != A_setup[level].end1(); ++row_iter)\n          {\n            for (InternalColIterator col_iter = row_iter.begin(); col_iter != row_iter.end(); ++col_iter)\n            {\n              if (level == 0)\n                systemmat_nonzero++;\n              nonzero++;\n              level_coefficients++;\n            }\n          }\n          avgstencil[level] = level_coefficients/(double)A[level].size1();\n        }\n        return nonzero/static_cast<double>(systemmat_nonzero);\n      }\n\n      /** @brief Precondition Operation\n      *\n      * @param vec The vector to which preconditioning is applied to\n      */\n      template<typename VectorType>\n      void apply(VectorType & vec) const\n      {\n        if (!done_init_apply)\n          init_apply();\n\n        int level;\n\n        // Precondition operation (Yang, p.3).\n        rhs[0] = vec;\n        for (level=0; level <static_cast<int>(tag_.get_coarselevels()); level++)\n        {\n          result[level].clear();\n\n          // Apply Smoother presmooth_ times.\n          smooth_jacobi (level, tag_.get_presmooth(), result[level], rhs[level]);\n\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"After presmooth: \" << std::endl;\n          printvector(result[level]);\n          #endif\n\n          // Compute residual.\n          //residual[level] = rhs[level] - viennacl::linalg::prod (A[level],result[level]);\n          residual[level] = viennacl::linalg::prod (A[level],result[level]);\n          residual[level] = rhs[level] - residual[level];\n\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"Residual: \" << std::endl;\n          printvector(residual[level]);\n          #endif\n\n          // Restrict to coarse level. Result is RHS of coarse level equation.\n          //residual_coarse[level] = viennacl::linalg::prod(R[level],residual[level]);\n          rhs[level+1] = viennacl::linalg::prod(R[level],residual[level]);\n\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"Restricted Residual: \" << std::endl;\n          printvector(rhs[level+1]);\n          #endif\n        }\n\n        // On highest level use direct solve to solve equation (on the CPU)\n        //TODO: Use GPU direct solve!\n        result[level] = rhs[level];\n        boost::numeric::ublas::vector <ScalarType> result_cpu (result[level].size());\n\n        copy (result[level],result_cpu);\n        boost::numeric::ublas::lu_substitute(op,Permutation,result_cpu);\n        copy (result_cpu, result[level]);\n\n        #ifdef VIENNACL_AMG_DEBUG\n        std::cout << \"After direct solve: \" << std::endl;\n        printvector (result[level]);\n        #endif\n\n        for (level=tag_.get_coarselevels()-1; level >= 0; level--)\n        {\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"Coarse Error: \" << std::endl;\n          printvector(result[level+1]);\n          #endif\n\n          // Interpolate error to fine level and correct solution.\n          result[level] += viennacl::linalg::prod(P[level],result[level+1]);\n\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"Corrected Result: \" << std::endl;\n          printvector (result[level]);\n          #endif\n\n          // Apply Smoother postsmooth_ times.\n          smooth_jacobi (level, tag_.get_postsmooth(), result[level], rhs[level]);\n\n          #ifdef VIENNACL_AMG_DEBUG\n          std::cout << \"After postsmooth: \" << std::endl;\n          printvector (result[level]);\n          #endif\n        }\n        vec = result[0];\n      }\n\n      /** @brief Jacobi Smoother (GPU version)\n      * @param level       Coarse level to which smoother is applied to\n      * @param iterations  Number of smoother iterations\n      * @param x           The vector smoothing is applied to\n      * @param rhs         The right hand side of the equation for the smoother\n      */\n      template<typename VectorType>\n      void smooth_jacobi(int level, unsigned int iterations, VectorType & x, VectorType const & rhs) const\n      {\n        VectorType old_result = x;\n\n        viennacl::ocl::context & ctx = const_cast<viennacl::ocl::context &>(viennacl::traits::opencl_handle(x).context());\n        viennacl::linalg::opencl::kernels::compressed_matrix<ScalarType>::init(ctx);\n        viennacl::ocl::kernel & k = ctx.get_kernel(viennacl::linalg::opencl::kernels::compressed_matrix<ScalarType>::program_name(), \"jacobi\");\n\n        for (unsigned int i=0; i<iterations; ++i)\n        {\n          if (i > 0)\n            old_result = x;\n          x.clear();\n          viennacl::ocl::enqueue(k(A[level].handle1().opencl_handle(), A[level].handle2().opencl_handle(), A[level].handle().opencl_handle(),\n                                  static_cast<ScalarType>(tag_.get_jacobiweight()),\n                                  viennacl::traits::opencl_handle(old_result),\n                                  viennacl::traits::opencl_handle(x),\n                                  viennacl::traits::opencl_handle(rhs),\n                                  static_cast<cl_uint>(rhs.size())));\n\n        }\n      }\n\n      amg_tag & tag() { return tag_; }\n    };\n\n  }\n}\n\n\n\n#endif\n\n", "meta": {"hexsha": "3a85ec995ae1283f9c3026bb15949471044c645b", "size": 30737, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "viennacl/linalg/amg.hpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "viennacl/linalg/amg.hpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "viennacl/linalg/amg.hpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3732833958, "max_line_length": 183, "alphanum_fraction": 0.6277125289, "num_tokens": 7410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23547600398688803}}
{"text": "// Material.cpp\n// created by Kuangdai on 17-May-2016 \n// 3D seismic material properties\n\n#include \"Material.h\"\n#include \"Quad.h\"\n#include \"ExodusModel.h\"\n#include \"SpectralConstants.h\"\n\n#include \"Volumetric3D.h\"\n#include \"XMath.h\"\n#include \"Relabelling.h\"\n\n#include \"Acoustic1D.h\"\n#include \"Acoustic3D.h\"\n\n#include \"AttBuilder.h\"\n#include \"Attenuation1D.h\"\n#include \"Attenuation3D.h\"\n\n#include \"Isotropic1D.h\"\n#include \"Isotropic3D.h\"\n#include \"TransverselyIsotropic1D.h\"\n#include \"TransverselyIsotropic3D.h\"\n\n#include \"Anisotropic1D.h\"\n#include \"Anisotropic3D.h\"\n#include \"Geodesy.h\"\n\n#include <boost/algorithm/string.hpp>\n#include \"SlicePlot.h\"\n\nMaterial::Material(const Quad *myQuad, const ExodusModel &exModel): mMyQuad(myQuad) {\n    // read Exodus model\n    int quadTag = mMyQuad->getQuadTag();\n    if (exModel.isIsotropic()) {\n        for (int i = 0; i < 4; i++) {\n            mVpv1D(i) = mVph1D(i) = exModel.getElementalVariables(\"VP_\" + std::to_string(i), quadTag);\n            mVsv1D(i) = mVsh1D(i) = exModel.getElementalVariables(\"VS_\" + std::to_string(i), quadTag);\n            mEta1D(i) = 1.;\n        }\n    } else {\n        for (int i = 0; i < 4; i++) {\n            mVpv1D(i) = exModel.getElementalVariables(\"VPV_\" + std::to_string(i), quadTag);\n            mVph1D(i) = exModel.getElementalVariables(\"VPH_\" + std::to_string(i), quadTag);\n            mVsv1D(i) = exModel.getElementalVariables(\"VSV_\" + std::to_string(i), quadTag);\n            mVsh1D(i) = exModel.getElementalVariables(\"VSH_\" + std::to_string(i), quadTag);\n            mEta1D(i) = exModel.getElementalVariables(\"ETA_\" + std::to_string(i), quadTag);\n        }\n    }\n    for (int i = 0; i < 4; i++) {\n        mRho1D(i) = exModel.getElementalVariables(\"RHO_\" + std::to_string(i), quadTag);\n    }\n    if (exModel.hasAttenuation()) {\n        for (int i = 0; i < 4; i++) {\n            mQkp1D(i) = exModel.getElementalVariables(\"QKAPPA_\" + std::to_string(i), quadTag);\n            mQmu1D(i) = exModel.getElementalVariables(\"QMU_\" + std::to_string(i), quadTag);\n        }\n    } else {\n        mQkp1D.setZero();\n        mQmu1D.setZero();\n    }\n    \n    // initialize 3D properties with 1D reference\n    int Nr = mMyQuad->getNr();\n    mVpv3D = RDMatXN::Zero(1, nPE);\n    mVph3D = RDMatXN::Zero(1, nPE);\n    mVsv3D = RDMatXN::Zero(1, nPE);\n    mVsh3D = RDMatXN::Zero(1, nPE);\n    mRho3D = RDMatXN::Zero(1, nPE);\n    mEta3D = RDMatXN::Zero(1, nPE);\n    mQkp3D = RDMatXN::Zero(1, nPE);\n    mQmu3D = RDMatXN::Zero(1, nPE);\n    \n    for (int ipol = 0; ipol <= nPol; ipol++) {\n        for (int jpol = 0; jpol <= nPol; jpol++) {\n            int ipnt = ipol * nPntEdge + jpol;\n            const RDCol2 &xieta = SpectralConstants::getXiEta(ipol, jpol, mMyQuad->isAxial());\n            // fill with 1D \n            mVpv3D.col(ipnt).fill(Mapping::interpolate(mVpv1D, xieta));\n            mVph3D.col(ipnt).fill(Mapping::interpolate(mVph1D, xieta));\n            mVsv3D.col(ipnt).fill(Mapping::interpolate(mVsv1D, xieta));\n            mVsh3D.col(ipnt).fill(Mapping::interpolate(mVsh1D, xieta));\n            mRho3D.col(ipnt).fill(Mapping::interpolate(mRho1D, xieta));\n            mEta3D.col(ipnt).fill(Mapping::interpolate(mEta1D, xieta));\n            mQkp3D.col(ipnt).fill(Mapping::interpolate(mQkp1D, xieta));\n            mQmu3D.col(ipnt).fill(Mapping::interpolate(mQmu1D, xieta));\n            // rho for mass\n            int NrP = mMyQuad->getPointNr(ipol, jpol);\n            mRhoMass3D[ipnt] = RDColX::Constant(NrP, mRho3D.col(ipnt)(0));\n            mVpFluid3D[ipnt] = RDColX::Constant(NrP, mVpv3D.col(ipnt)(0));\n        }\n    }\n}\n\nvoid Material::addVolumetric3D(const std::vector<Volumetric3D *> &m3D, \n    double srcLat, double srcLon, double srcDep, double phi2D) {\n    if (m3D.size() == 0) {\n        return;\n    }    \n        \n    // pointers for fast access to material matrices\n    std::vector<RDRow4 *>  prop1DPtr = {&mVpv1D, &mVph1D, &mVsv1D, &mVsh1D, &mRho1D, &mEta1D, &mQkp1D, &mQmu1D,\n                                        &mVpv1D, &mVsv1D, // these two take no other effect than occupying the slots  \n                                        &mC11_1D, &mC12_1D, &mC13_1D, &mC14_1D, &mC15_1D, &mC16_1D,\n                                        &mC22_1D, &mC23_1D, &mC24_1D, &mC25_1D, &mC26_1D,\n                                        &mC33_1D, &mC34_1D, &mC35_1D, &mC36_1D,\n                                        &mC44_1D, &mC45_1D, &mC46_1D,\n                                        &mC55_1D, &mC56_1D,\n                                        &mC66_1D\n    };\n    std::vector<RDMatXN *> prop3DPtr = {&mVpv3D, &mVph3D, &mVsv3D, &mVsh3D, &mRho3D, &mEta3D, &mQkp3D, &mQmu3D,\n                                        &mVpv3D, &mVsv3D, // these two take no other effect than occupying the slots  \n                                        &mC11_3D, &mC12_3D, &mC13_3D, &mC14_3D, &mC15_3D, &mC16_3D,\n                                        &mC22_3D, &mC23_3D, &mC24_3D, &mC25_3D, &mC26_3D,\n                                        &mC33_3D, &mC34_3D, &mC35_3D, &mC36_3D,\n                                        &mC44_3D, &mC45_3D, &mC46_3D,\n                                        &mC55_3D, &mC56_3D,\n                                        &mC66_3D\n    };\n    \n    // radius at element center \n    double rElemCenter = mMyQuad->computeCenterRadius();\n    \n    // read 3D model\n    int Nr = mMyQuad->getNr();\n    for (int ipol = 0; ipol <= nPol; ipol++) {\n        for (int jpol = 0; jpol <= nPol; jpol++) {\n            // geographic oordinates of cardinal points\n            const RDCol2 &xieta = SpectralConstants::getXiEta(ipol, jpol, mMyQuad->isAxial());\n            const RDMatX3 &rtp = mMyQuad->computeGeocentricGlobal(srcLat, srcLon, srcDep, xieta, Nr, phi2D);\n            int ipnt = ipol * nPntEdge + jpol;\n            for (int alpha = 0; alpha < Nr; alpha++) {\n                double r = rtp(alpha, 0);\n                double t = rtp(alpha, 1);\n                double p = rtp(alpha, 2);\n                for (const auto &model: m3D) {\n                    if (mMyQuad->isFluid() && !model->makeFluid3D()) {\n                        continue;\n                    }\n                    std::vector<Volumetric3D::MaterialProperty> properties; \n                    std::vector<Volumetric3D::MaterialRefType> refTypes;\n                    std::vector<double> values;\n                    if (!model->get3dProperties(r, t, p, rElemCenter, properties, refTypes, values)) {\n                        // point (r, t, p) not in model range\n                        continue;\n                    }\n                    \n                    if (!_3Dprepared()) {\n                        prepare3D();\n                    }\n                    \n                    // deal with VP and VS\n                    std::vector<Volumetric3D::MaterialProperty> propertiesTIso; \n                    std::vector<Volumetric3D::MaterialRefType> refTypesTIso;\n                    std::vector<double> valuesTIso;\n                    for (int iprop = 0; iprop < properties.size(); iprop++) {\n                        if (properties[iprop] == Volumetric3D::MaterialProperty::VP) {\n                            propertiesTIso.push_back(Volumetric3D::MaterialProperty::VPV);\n                            propertiesTIso.push_back(Volumetric3D::MaterialProperty::VPH);\n                            refTypesTIso.push_back(refTypes[iprop]);\n                            refTypesTIso.push_back(refTypes[iprop]);\n                            valuesTIso.push_back(values[iprop]);\n                            valuesTIso.push_back(values[iprop]);\n                        } else if (properties[iprop] == Volumetric3D::MaterialProperty::VS) {\n                            propertiesTIso.push_back(Volumetric3D::MaterialProperty::VSV);\n                            propertiesTIso.push_back(Volumetric3D::MaterialProperty::VSH);\n                            refTypesTIso.push_back(refTypes[iprop]);\n                            refTypesTIso.push_back(refTypes[iprop]);\n                            valuesTIso.push_back(values[iprop]);\n                            valuesTIso.push_back(values[iprop]);\n                        } else {\n                            propertiesTIso.push_back(properties[iprop]);\n                            refTypesTIso.push_back(refTypes[iprop]);\n                            valuesTIso.push_back(values[iprop]);\n                        }\n                    }\n                    // change values\n                    for (int iprop = 0; iprop < propertiesTIso.size(); iprop++) {\n                        // initialize anisotropy\n                        if (!mFullAniso && propertiesTIso[iprop] >= Volumetric3D::MaterialProperty::C11) {\n                            initAniso();\n                        }\n                        \n                        // // check\n                        // if (mFullAniso) {\n                        //     if (propertiesTIso[iprop] <= Volumetric3D::MaterialProperty::ANIS_ETA) {\n                        //         throw std::runtime_error(\"Material::addVolumetric3D || \" \n                        //             \"Velocity, density and eta can no longer be changed once \"\n                        //             \"full anisotropy has been activated.\");\n                        //     }\n                        // } \n                        \n                        RDRow4 &row1D = *prop1DPtr[propertiesTIso[iprop]];\n                        RDMatXN &mat3D = *prop3DPtr[propertiesTIso[iprop]];\n                        Volumetric3D::MaterialRefType ref_type = refTypesTIso[iprop];\n                        double value3D = valuesTIso[iprop];\n                        if (ref_type == Volumetric3D::MaterialRefType::Absolute) {\n                            mat3D(alpha, ipnt) = value3D;\n                        } else if (ref_type == Volumetric3D::MaterialRefType::Reference1D) {\n                            double ref1D = Mapping::interpolate(row1D, xieta);\n                            mat3D(alpha, ipnt) = ref1D * (1. + value3D);\n                        } else if (ref_type == Volumetric3D::MaterialRefType::Reference3D) {\n                            mat3D(alpha, ipnt) *= 1. + value3D;\n                        } else {\n                            double ref1D = Mapping::interpolate(row1D, xieta);\n                            mat3D(alpha, ipnt) = (mat3D(alpha, ipnt) - ref1D) * (1. + value3D) + ref1D;\n                        }\n                    }\n                }\n            }\n        }\n    }\n    \n    // form mass point sampling\n    if (_3Dprepared()) {\n        for (int ipol = 0; ipol <= nPol; ipol++) {\n            for (int jpol = 0; jpol <= nPol; jpol++) {\n                int ipnt = ipol * nPntEdge + jpol;\n                int nr_mass = mMyQuad->getPointNr(ipol, jpol);\n                mRhoMass3D[ipnt] = XMath::linearResampling(nr_mass, mRho3D.col(ipnt));\n                mVpFluid3D[ipnt] = XMath::linearResampling(nr_mass, mVpv3D.col(ipnt));\n            }\n        }\n    }\n    \n    // rotate anisotropy from geographic to source-centred\n    if (mFullAniso) {\n        rotateAniso(srcLat, srcLon, srcDep);\n    }\n}\n\narPP_RDColX Material::computeElementalMass() const {\n    arPP_RDColX mass, J;\n    // Jacobian of topography\n    if (mMyQuad->hasRelabelling()) {\n        J = mMyQuad->getRelabelling().getMassJacobian();\n    } else {\n        J = mRhoMass3D; // just to use the size\n        for (int ipnt = 0; ipnt < nPntElem; ipnt++) {\n            J[ipnt].setOnes();\n        }\n    }\n    // general mass term\n    const RDRowN &iFact = mMyQuad->getIntegralFactor();\n    for (int ipnt = 0; ipnt < nPntElem; ipnt++) {\n        if (mMyQuad->isFluid()) {\n            mass[ipnt] = (mRhoMass3D[ipnt].array() * mVpFluid3D[ipnt].array().pow(2.)).pow(-1.).matrix();\n        } else {\n            mass[ipnt] = mRhoMass3D[ipnt];\n        }\n        mass[ipnt].array() *= iFact(ipnt) * J[ipnt].array();\n    }\n    return mass;\n}\n\nAcoustic *Material::createAcoustic(bool elem1D) const {\n    const RDRowN &iFact = mMyQuad->getIntegralFactor();\n    RDMatXN fluidK;\n    if (_3Dprepared()) {\n        fluidK = mRho3D.array().pow(-1.);    \n    } else {\n        fluidK = mRho3D.replicate(mMyQuad->getNr(), 1).array().pow(-1.);\n    }\n    for (int ipnt = 0; ipnt < nPntElem; ipnt++) {\n       fluidK.col(ipnt) *= iFact(ipnt);\n    }\n    if (mMyQuad->hasRelabelling()) {\n        fluidK.array() *= mMyQuad->getRelabelling().getStiffJacobian().array();\n    }\n    if (elem1D) {\n        RDMatPP kstruct;\n        XMath::structuredUseFirstRow(fluidK, kstruct);\n        return new Acoustic1D(kstruct.cast<Real>());\n    } else {\n        return new Acoustic3D(fluidK.cast<Real>());\n    }\n}\n\nElastic *Material::createElastic(bool elem1D, const AttBuilder *attBuild) const {\n    if (mFullAniso) {\n        return createElasticAniso(elem1D, attBuild);\n    }\n    \n    // elasticity tensor\n    const RDRowN &iFact = mMyQuad->getIntegralFactor(); \n    RDMatXN vpv3D, vph3D;\n    RDMatXN vsv3D, vsh3D;\n    RDMatXN rho3D;\n    RDMatXN eta3D;\n    RDMatXN qkp3D, qmu3D;\n    \n    if (_3Dprepared()) {\n        vpv3D = mVpv3D;\n        vph3D = mVph3D;\n        vsv3D = mVsv3D;\n        vsh3D = mVsh3D;\n        rho3D = mRho3D;\n        eta3D = mEta3D;\n        qkp3D = mQkp3D;\n        qmu3D = mQmu3D;\n    } else {\n        vpv3D = mVpv3D.replicate(mMyQuad->getNr(), 1);\n        vph3D = mVph3D.replicate(mMyQuad->getNr(), 1);\n        vsv3D = mVsv3D.replicate(mMyQuad->getNr(), 1);\n        vsh3D = mVsh3D.replicate(mMyQuad->getNr(), 1);\n        rho3D = mRho3D.replicate(mMyQuad->getNr(), 1);\n        eta3D = mEta3D.replicate(mMyQuad->getNr(), 1);\n        qkp3D = mQkp3D.replicate(mMyQuad->getNr(), 1);\n        qmu3D = mQmu3D.replicate(mMyQuad->getNr(), 1);\n    }\n    \n    RDMatXN A(rho3D), C(rho3D), F(rho3D), L(rho3D), N(rho3D);\n    for (int ipnt = 0; ipnt < nPntElem; ipnt++) {\n        // A C L N\n        A.col(ipnt).array() *= vph3D.col(ipnt).array().pow(2.) * iFact(ipnt);\n        C.col(ipnt).array() *= vpv3D.col(ipnt).array().pow(2.) * iFact(ipnt);\n        L.col(ipnt).array() *= vsv3D.col(ipnt).array().pow(2.) * iFact(ipnt);\n        N.col(ipnt).array() *= vsh3D.col(ipnt).array().pow(2.) * iFact(ipnt);\n    }\n    // F\n    F = eta3D.schur(A - 2. * L);\n    // must do relabelling before attenuation\n    if (mMyQuad->hasRelabelling()) {\n        const RDMatXN &J = mMyQuad->getRelabelling().getStiffJacobian();\n        A = A.schur(J);\n        C = C.schur(J);\n        F = F.schur(J);\n        L = L.schur(J);\n        N = N.schur(J);\n    }\n    \n    // attenuation\n    Attenuation1D *att1D = 0;\n    Attenuation3D *att3D = 0;\n    if (attBuild) {\n        // Voigt average\n        RDMatXN kappa = (4. * A + C + 4. * F - 4. * N) / 9.;\n        RDMatXN mu = (A + C - 2. * F + 6. * L + 5. * N) / 15.;\n        A -= (kappa + 4. / 3. * mu);\n        C -= (kappa + 4. / 3. * mu);\n        F -= (kappa - 2. / 3. * mu);\n        L -= mu;\n        N -= mu;\n        if (elem1D) {\n            att1D = attBuild->createAttenuation1D(qkp3D, qmu3D, kappa, mu, mMyQuad);\n        } else {\n            att3D = attBuild->createAttenuation3D(qkp3D, qmu3D, kappa, mu, mMyQuad);\n        }\n        A += (kappa + 4. / 3. * mu);\n        C += (kappa + 4. / 3. * mu);\n        F += (kappa - 2. / 3. * mu);\n        L += mu;\n        N += mu;\n    }\n    \n    // Elastic pointers\n    if (elem1D) {\n        RDMatPP A0, C0, F0, L0, N0;\n        XMath::structuredUseFirstRow(A, A0);\n        XMath::structuredUseFirstRow(C, C0);\n        XMath::structuredUseFirstRow(F, F0);\n        XMath::structuredUseFirstRow(L, L0);\n        XMath::structuredUseFirstRow(N, N0);\n        if (isIsotropic()) {\n            return new Isotropic1D(F0.cast<Real>(), L0.cast<Real>(), att1D);\n        } else {\n            return new TransverselyIsotropic1D(A0.cast<Real>(), C0.cast<Real>(), \n                F0.cast<Real>(), L0.cast<Real>(), N0.cast<Real>(), att1D);\n        }    \n    } else {\n        if (isIsotropic()) {\n            return new Isotropic3D(F.cast<Real>(), L.cast<Real>(), att3D);\n        } else {\n            return new TransverselyIsotropic3D(A.cast<Real>(), C.cast<Real>(), \n                F.cast<Real>(), L.cast<Real>(), N.cast<Real>(), att3D);\n        }\n    }\n}\n\nElastic *Material::createElasticAniso(bool elem1D, const AttBuilder *attBuild) const {\n    // elasticity tensor\n    const RDRowN &iFact = mMyQuad->getIntegralFactor(); \n    RDMatXN C11_3D(mC11_3D), C12_3D(mC12_3D), C13_3D(mC13_3D), C14_3D(mC14_3D), C15_3D(mC15_3D), C16_3D(mC16_3D);\n    RDMatXN C22_3D(mC22_3D), C23_3D(mC23_3D), C24_3D(mC24_3D), C25_3D(mC25_3D), C26_3D(mC26_3D);\n    RDMatXN C33_3D(mC33_3D), C34_3D(mC34_3D), C35_3D(mC35_3D), C36_3D(mC36_3D);\n    RDMatXN C44_3D(mC44_3D), C45_3D(mC45_3D), C46_3D(mC46_3D);\n    RDMatXN C55_3D(mC55_3D), C56_3D(mC56_3D);\n    RDMatXN C66_3D(mC66_3D);\n    for (int ipnt = 0; ipnt < nPntElem; ipnt++) {\n        C11_3D.col(ipnt) *= iFact(ipnt);\n        C12_3D.col(ipnt) *= iFact(ipnt);\n        C13_3D.col(ipnt) *= iFact(ipnt);\n        C14_3D.col(ipnt) *= iFact(ipnt);\n        C15_3D.col(ipnt) *= iFact(ipnt);\n        C16_3D.col(ipnt) *= iFact(ipnt);\n        C22_3D.col(ipnt) *= iFact(ipnt);\n        C23_3D.col(ipnt) *= iFact(ipnt);\n        C24_3D.col(ipnt) *= iFact(ipnt);\n        C25_3D.col(ipnt) *= iFact(ipnt);\n        C26_3D.col(ipnt) *= iFact(ipnt);\n        C33_3D.col(ipnt) *= iFact(ipnt);\n        C34_3D.col(ipnt) *= iFact(ipnt);\n        C35_3D.col(ipnt) *= iFact(ipnt);\n        C36_3D.col(ipnt) *= iFact(ipnt);\n        C44_3D.col(ipnt) *= iFact(ipnt);\n        C45_3D.col(ipnt) *= iFact(ipnt);\n        C46_3D.col(ipnt) *= iFact(ipnt);\n        C55_3D.col(ipnt) *= iFact(ipnt);\n        C56_3D.col(ipnt) *= iFact(ipnt);\n        C66_3D.col(ipnt) *= iFact(ipnt);\n    }\n    // must do relabelling before attenuation\n    if (mMyQuad->hasRelabelling()) {\n        const RDMatXN &J = mMyQuad->getRelabelling().getStiffJacobian();\n        C11_3D = C11_3D.schur(J);\n        C12_3D = C12_3D.schur(J);\n        C13_3D = C13_3D.schur(J);\n        C14_3D = C14_3D.schur(J);\n        C15_3D = C15_3D.schur(J);\n        C16_3D = C16_3D.schur(J);\n        C22_3D = C22_3D.schur(J);\n        C23_3D = C23_3D.schur(J);\n        C24_3D = C24_3D.schur(J);\n        C25_3D = C25_3D.schur(J);\n        C26_3D = C26_3D.schur(J);\n        C33_3D = C33_3D.schur(J);\n        C34_3D = C34_3D.schur(J);\n        C35_3D = C35_3D.schur(J);\n        C36_3D = C36_3D.schur(J);\n        C44_3D = C44_3D.schur(J);\n        C45_3D = C45_3D.schur(J);\n        C46_3D = C46_3D.schur(J);\n        C55_3D = C55_3D.schur(J);\n        C56_3D = C56_3D.schur(J);\n        C66_3D = C66_3D.schur(J);\n    }\n    \n    // attenuation\n    Attenuation1D *att1D = 0;\n    Attenuation3D *att3D = 0;\n    if (attBuild) {\n        // Voigt average\n        // https://materialsproject.org/wiki/index.php/Elasticity_calculations\n        RDMatXN kappa = (C11_3D + C22_3D + C33_3D + 2. * (C12_3D + C23_3D + C13_3D)) / 9.;\n        RDMatXN mu = (C11_3D + C22_3D + C33_3D - (C12_3D + C23_3D + C13_3D) + 3. * (C44_3D + C55_3D + C66_3D)) / 15.;\n        C11_3D -= (kappa + 4. / 3. * mu);\n        C22_3D -= (kappa + 4. / 3. * mu);\n        C33_3D -= (kappa + 4. / 3. * mu);\n        C12_3D -= (kappa - 2. / 3. * mu);\n        C23_3D -= (kappa - 2. / 3. * mu);\n        C13_3D -= (kappa - 2. / 3. * mu);\n        C44_3D -= mu;\n        C55_3D -= mu;\n        C66_3D -= mu;\n        if (elem1D) {\n            att1D = attBuild->createAttenuation1D(mQkp3D, mQmu3D, kappa, mu, mMyQuad);\n        } else {\n            att3D = attBuild->createAttenuation3D(mQkp3D, mQmu3D, kappa, mu, mMyQuad);\n        }\n        C11_3D += (kappa + 4. / 3. * mu);\n        C22_3D += (kappa + 4. / 3. * mu);\n        C33_3D += (kappa + 4. / 3. * mu);\n        C12_3D += (kappa - 2. / 3. * mu);\n        C23_3D += (kappa - 2. / 3. * mu);\n        C13_3D += (kappa - 2. / 3. * mu);\n        C44_3D += mu;\n        C55_3D += mu;\n        C66_3D += mu;\n    }\n    \n    // Elastic pointers\n    if (elem1D) {\n        RDMatPP C11_1D, C12_1D, C13_1D, C14_1D, C15_1D, C16_1D;\n        RDMatPP C22_1D, C23_1D, C24_1D, C25_1D, C26_1D;\n        RDMatPP C33_1D, C34_1D, C35_1D, C36_1D;\n        RDMatPP C44_1D, C45_1D, C46_1D;\n        RDMatPP C55_1D, C56_1D;\n        RDMatPP C66_1D;\n        XMath::structuredUseFirstRow(C11_3D, C11_1D);\n        XMath::structuredUseFirstRow(C12_3D, C12_1D);\n        XMath::structuredUseFirstRow(C13_3D, C13_1D);\n        XMath::structuredUseFirstRow(C14_3D, C14_1D);\n        XMath::structuredUseFirstRow(C15_3D, C15_1D);\n        XMath::structuredUseFirstRow(C16_3D, C16_1D);\n        XMath::structuredUseFirstRow(C22_3D, C22_1D);\n        XMath::structuredUseFirstRow(C23_3D, C23_1D);\n        XMath::structuredUseFirstRow(C24_3D, C24_1D);\n        XMath::structuredUseFirstRow(C25_3D, C25_1D);\n        XMath::structuredUseFirstRow(C26_3D, C26_1D);\n        XMath::structuredUseFirstRow(C33_3D, C33_1D);\n        XMath::structuredUseFirstRow(C34_3D, C34_1D);\n        XMath::structuredUseFirstRow(C35_3D, C35_1D);\n        XMath::structuredUseFirstRow(C36_3D, C36_1D);\n        XMath::structuredUseFirstRow(C44_3D, C44_1D);\n        XMath::structuredUseFirstRow(C45_3D, C45_1D);\n        XMath::structuredUseFirstRow(C46_3D, C46_1D);\n        XMath::structuredUseFirstRow(C55_3D, C55_1D);\n        XMath::structuredUseFirstRow(C56_3D, C56_1D);\n        XMath::structuredUseFirstRow(C66_3D, C66_1D);\n        return new Anisotropic1D(\n            C11_1D.cast<Real>(), C12_1D.cast<Real>(), C13_1D.cast<Real>(), C14_1D.cast<Real>(), C15_1D.cast<Real>(), C16_1D.cast<Real>(),\n            C22_1D.cast<Real>(), C23_1D.cast<Real>(), C24_1D.cast<Real>(), C25_1D.cast<Real>(), C26_1D.cast<Real>(),\n            C33_1D.cast<Real>(), C34_1D.cast<Real>(), C35_1D.cast<Real>(), C36_1D.cast<Real>(),\n            C44_1D.cast<Real>(), C45_1D.cast<Real>(), C46_1D.cast<Real>(),\n            C55_1D.cast<Real>(), C56_1D.cast<Real>(), \n            C66_1D.cast<Real>(), \n            att1D);\n    } else {\n        return new Anisotropic3D(\n            C11_3D.cast<Real>(), C12_3D.cast<Real>(), C13_3D.cast<Real>(), C14_3D.cast<Real>(), C15_3D.cast<Real>(), C16_3D.cast<Real>(),\n            C22_3D.cast<Real>(), C23_3D.cast<Real>(), C24_3D.cast<Real>(), C25_3D.cast<Real>(), C26_3D.cast<Real>(),\n            C33_3D.cast<Real>(), C34_3D.cast<Real>(), C35_3D.cast<Real>(), C36_3D.cast<Real>(),\n            C44_3D.cast<Real>(), C45_3D.cast<Real>(), C46_3D.cast<Real>(),\n            C55_3D.cast<Real>(), C56_3D.cast<Real>(), \n            C66_3D.cast<Real>(), \n            att3D);\n    }\n}\n\ndouble Material::getVMaxRef() const {\n    return std::max(mVph1D.maxCoeff(), mVpv1D.maxCoeff());\n}\n\nRDColX Material::getVMax() const {\n    RDMatXN vpv3D, vph3D;\n    if (_3Dprepared()) {\n        vpv3D = mVpv3D;\n        vph3D = mVph3D;\n    } else {\n        vpv3D = mVpv3D.replicate(mMyQuad->getNr(), 1);\n        vph3D = mVph3D.replicate(mMyQuad->getNr(), 1);\n    }\n    const RDColX &vpvMax = vpv3D.rowwise().maxCoeff();\n    const RDColX &vphMax = vph3D.rowwise().maxCoeff();\n    return (vpvMax.array().max(vphMax.array())).matrix();\n}\n\nbool Material::isFluidPar1D() const {\n    return XMath::equalRows(mVpv3D) && XMath::equalRows(mRho3D);\n}\n\nbool Material::isSolidPar1D(bool attenuation) const {\n    bool result = false;\n    if (mFullAniso) {\n        result = XMath::equalRows(mC11_3D, 1e-7) && XMath::equalRows(mC12_3D, 1e-7) && XMath::equalRows(mC13_3D, 1e-7) && XMath::equalRows(mC14_3D, 1e-7) && XMath::equalRows(mC15_3D, 1e-7) && XMath::equalRows(mC16_3D, 1e-7) &&\n                 XMath::equalRows(mC22_3D, 1e-7) && XMath::equalRows(mC23_3D, 1e-7) && XMath::equalRows(mC24_3D, 1e-7) && XMath::equalRows(mC25_3D, 1e-7) && XMath::equalRows(mC26_3D, 1e-7) &&\n                 XMath::equalRows(mC33_3D, 1e-7) && XMath::equalRows(mC34_3D, 1e-7) && XMath::equalRows(mC35_3D, 1e-7) && XMath::equalRows(mC36_3D, 1e-7) &&\n                 XMath::equalRows(mC44_3D, 1e-7) && XMath::equalRows(mC45_3D, 1e-7) && XMath::equalRows(mC46_3D, 1e-7) &&\n                 XMath::equalRows(mC55_3D, 1e-7) && XMath::equalRows(mC56_3D, 1e-7) &&\n                 XMath::equalRows(mC66_3D, 1e-7) && \n                 XMath::equalRows(mRho3D);\n    } else {\n        result = XMath::equalRows(mVpv3D) && XMath::equalRows(mVph3D) &&\n                 XMath::equalRows(mVsv3D) && XMath::equalRows(mVsh3D) && \n                 XMath::equalRows(mRho3D) && XMath::equalRows(mEta3D);\n    }\n    if (attenuation) {\n        result = result && XMath::equalRows(mQkp3D) && XMath::equalRows(mQmu3D);\n    }              \n    return result;\n}\n\nbool Material::isIsotropic() const {\n    if (mFullAniso) {\n        return false;\n    }\n    return (mVpv3D - mVph3D).norm() < tinyDouble * mVpv3D.norm() &&  \n           (mVsv3D - mVsh3D).norm() < tinyDouble * mVsv3D.norm() && \n           (mEta3D - RDMatXN::Ones(mEta3D.rows(), mEta3D.cols())).norm() < tinyDouble;\n}\n\nRDMatXN Material::getProperty(const std::string &vname, int refType) {\n    int Nr = mMyQuad->getNr();\n    \n    // name\n    std::string varname = vname;\n    if (boost::iequals(vname, \"vp\")) {\n        varname = \"vpv\";\n    }\n    if (boost::iequals(vname, \"vs\")) {\n        varname = \"vsv\";\n    }\n    RDRow4 data1D;\n    RDMatXN data3D;\n    if (boost::iequals(varname, \"vpv\")) {\n        data1D = mVpv1D;\n        data3D = mVpv3D;\n    } else if (boost::iequals(varname, \"vsv\")) {\n        data1D = mVsv1D;\n        data3D = mVsv3D;\n    } else if (boost::iequals(varname, \"vph\")) {\n        data1D = mVph1D;\n        data3D = mVph3D;\n    } else if (boost::iequals(varname, \"vsh\")) {\n        data1D = mVsh1D;\n        data3D = mVsh3D;\n    } else if (boost::iequals(varname, \"rho\")) {\n        data1D = mRho1D;\n        data3D = mRho3D;\n    } else if (boost::iequals(varname, \"eta\")) {\n        data1D = mEta1D;\n        data3D = mEta3D;\n    } else if (boost::iequals(varname, \"qkappa\")) {\n        data1D = mQkp1D;\n        data3D = mQkp3D;\n    } else if (boost::iequals(varname, \"qmu\")) {\n        data1D = mQmu1D;\n        data3D = mQmu3D;\n    } else if (mFullAniso) {\n        if (boost::iequals(varname, \"c11\")) {\n            data1D = mC11_1D;\n            data3D = mC11_3D;\n        } else if (boost::iequals(varname, \"c12\")) {\n            data1D = mC12_1D;\n            data3D = mC12_3D;\n        } else if (boost::iequals(varname, \"c13\")) {\n            data1D = mC13_1D;\n            data3D = mC13_3D;\n        } else if (boost::iequals(varname, \"c14\")) {\n            data1D = mC14_1D;\n            data3D = mC14_3D;\n        } else if (boost::iequals(varname, \"c15\")) {\n            data1D = mC15_1D;\n            data3D = mC15_3D;\n        } else if (boost::iequals(varname, \"c16\")) {\n            data1D = mC16_1D;\n            data3D = mC16_3D;\n        } else if (boost::iequals(varname, \"c22\")) {\n            data1D = mC22_1D;\n            data3D = mC22_3D;\n        } else if (boost::iequals(varname, \"c23\")) {\n            data1D = mC23_1D;\n            data3D = mC23_3D;\n        } else if (boost::iequals(varname, \"c24\")) {\n            data1D = mC24_1D;\n            data3D = mC24_3D;\n        } else if (boost::iequals(varname, \"c25\")) {\n            data1D = mC25_1D;\n            data3D = mC25_3D;\n        } else if (boost::iequals(varname, \"c26\")) {\n            data1D = mC26_1D;\n            data3D = mC26_3D;\n        } else if (boost::iequals(varname, \"c33\")) {\n            data1D = mC33_1D;\n            data3D = mC33_3D;\n        } else if (boost::iequals(varname, \"c34\")) {\n            data1D = mC34_1D;\n            data3D = mC34_3D;\n        } else if (boost::iequals(varname, \"c35\")) {\n            data1D = mC35_1D;\n            data3D = mC35_3D;\n        } else if (boost::iequals(varname, \"c36\")) {\n            data1D = mC36_1D;\n            data3D = mC36_3D;\n        } else if (boost::iequals(varname, \"c44\")) {\n            data1D = mC44_1D;\n            data3D = mC44_3D;\n        } else if (boost::iequals(varname, \"c45\")) {\n            data1D = mC45_1D;\n            data3D = mC45_3D;\n        } else if (boost::iequals(varname, \"c46\")) {\n            data1D = mC46_1D;\n            data3D = mC46_3D;\n        } else if (boost::iequals(varname, \"c55\")) {\n            data1D = mC55_1D;\n            data3D = mC55_3D;\n        } else if (boost::iequals(varname, \"c56\")) {\n            data1D = mC56_1D;\n            data3D = mC56_3D;\n        } else if (boost::iequals(varname, \"c66\")) {\n            data1D = mC66_1D;\n            data3D = mC66_3D;\n        } \n    } else {\n        throw std::runtime_error(\"Material::getProperty || Unknown field variable name: \" + vname);\n    }\n    \n    if (data3D.rows() != Nr) {\n        data3D = data3D.replicate(Nr, 1);\n    }\n    \n    // 3D\n    if (refType == SlicePlot::PropertyRefTypes::Property3D) {\n        return data3D;\n    }\n    \n    // fill 1D\n    RDMatXN data1DXN(Nr, nPntElem);\n    for (int ipol = 0; ipol <= nPol; ipol++) {\n        for (int jpol = 0; jpol <= nPol; jpol++) {\n            int ipnt = ipol * nPntEdge + jpol;\n            const RDCol2 &xieta = SpectralConstants::getXiEta(ipol, jpol, mMyQuad->isAxial());\n            data1DXN.col(ipnt).fill(Mapping::interpolate(data1D, xieta));\n        }\n    }\n    \n    // 1D\n    if (refType == SlicePlot::PropertyRefTypes::Property1D) {\n        return data1DXN;\n    }\n    \n    // perturb\n    RDMatXN data1DBase = data1DXN.array().max(tinyDouble).matrix(); // in fluid, vs = 0\n    return ((data3D - data1DXN).array() / data1DBase.array()).matrix();\n}\n\nvoid Material::initAniso() {\n    if (mMyQuad->isFluid()) {\n        throw std::runtime_error(\"Material::initAniso || Cannot activate full anisotropy in fluid domain.\");\n    }\n    \n    // 1D elasticity tensor\n    RDRow4 A_1D = mRho1D.schur(mVph1D).schur(mVph1D);\n    RDRow4 C_1D = mRho1D.schur(mVpv1D).schur(mVpv1D);\n    RDRow4 L_1D = mRho1D.schur(mVsv1D).schur(mVsv1D);\n    RDRow4 N_1D = mRho1D.schur(mVsh1D).schur(mVsh1D);\n    RDRow4 F_1D = mEta1D.schur(A_1D - 2. * L_1D);\n    \n    mC11_1D = mC22_1D = A_1D;\n    mC33_1D = C_1D;\n    mC44_1D = mC55_1D = L_1D;\n    mC66_1D = N_1D;\n    mC12_1D = A_1D - 2. * N_1D;\n    mC13_1D = mC23_1D = F_1D;\n    mC14_1D = mC15_1D = mC16_1D = RDRow4::Zero();\n    mC24_1D = mC25_1D = mC26_1D = RDRow4::Zero();\n    mC34_1D = mC35_1D = mC36_1D = RDRow4::Zero();\n    mC45_1D = mC46_1D = mC56_1D = RDRow4::Zero();\n    \n    // 3D elasticity tensor\n    RDMatXN A_3D = mRho3D.schur(mVph3D).schur(mVph3D);\n    RDMatXN C_3D = mRho3D.schur(mVpv3D).schur(mVpv3D);\n    RDMatXN L_3D = mRho3D.schur(mVsv3D).schur(mVsv3D);\n    RDMatXN N_3D = mRho3D.schur(mVsh3D).schur(mVsh3D);\n    RDMatXN F_3D = mEta3D.schur(A_3D - 2. * L_3D);\n    \n    mC11_3D = mC22_3D = A_3D;\n    mC33_3D = C_3D;\n    mC44_3D = mC55_3D = L_3D;\n    mC66_3D = N_3D;\n    mC12_3D = A_3D - 2. * N_3D;\n    mC13_3D = mC23_3D = F_3D;\n    mC14_3D = mC15_3D = mC16_3D = RDMatXN::Zero(A_3D.rows(), A_3D.cols());\n    mC24_3D = mC25_3D = mC26_3D = RDMatXN::Zero(A_3D.rows(), A_3D.cols());\n    mC34_3D = mC35_3D = mC36_3D = RDMatXN::Zero(A_3D.rows(), A_3D.cols());\n    mC45_3D = mC46_3D = mC56_3D = RDMatXN::Zero(A_3D.rows(), A_3D.cols());\n\n    // initialized\n    mFullAniso = true;\n}\n\nvoid Material::rotateAniso(double srcLat, double srcLon, double srcDep) {\n    RDMatXX inCijkl(6, 6);\n    \n    // 3D\n    for (int alpha = 0; alpha < mC11_3D.rows(); alpha++) {\n        // azimuth of the slice\n        double phi = 2. * pi / mC11_3D.rows() * alpha;\n        // loop over GLL points\n        for (int ipol = 0; ipol <= nPol; ipol++) {\n            for (int jpol = 0; jpol <= nPol; jpol++) {\n                int ipnt = ipol * nPntEdge + jpol;\n\n                inCijkl(1 - 1, 1 - 1) = mC11_3D(alpha, ipnt);\n                inCijkl(1 - 1, 2 - 1) = mC12_3D(alpha, ipnt);\n                inCijkl(1 - 1, 3 - 1) = mC13_3D(alpha, ipnt);\n                inCijkl(1 - 1, 4 - 1) = mC14_3D(alpha, ipnt);\n                inCijkl(1 - 1, 5 - 1) = mC15_3D(alpha, ipnt);\n                inCijkl(1 - 1, 6 - 1) = mC16_3D(alpha, ipnt);\n                \n                inCijkl(2 - 1, 1 - 1) = mC12_3D(alpha, ipnt);\n                inCijkl(2 - 1, 2 - 1) = mC22_3D(alpha, ipnt);\n                inCijkl(2 - 1, 3 - 1) = mC23_3D(alpha, ipnt);\n                inCijkl(2 - 1, 4 - 1) = mC24_3D(alpha, ipnt);\n                inCijkl(2 - 1, 5 - 1) = mC25_3D(alpha, ipnt);\n                inCijkl(2 - 1, 6 - 1) = mC26_3D(alpha, ipnt);\n                \n                inCijkl(3 - 1, 1 - 1) = mC13_3D(alpha, ipnt);\n                inCijkl(3 - 1, 2 - 1) = mC23_3D(alpha, ipnt);\n                inCijkl(3 - 1, 3 - 1) = mC33_3D(alpha, ipnt);\n                inCijkl(3 - 1, 4 - 1) = mC34_3D(alpha, ipnt);\n                inCijkl(3 - 1, 5 - 1) = mC35_3D(alpha, ipnt);\n                inCijkl(3 - 1, 6 - 1) = mC36_3D(alpha, ipnt);\n                \n                inCijkl(4 - 1, 1 - 1) = mC14_3D(alpha, ipnt);\n                inCijkl(4 - 1, 2 - 1) = mC24_3D(alpha, ipnt);\n                inCijkl(4 - 1, 3 - 1) = mC34_3D(alpha, ipnt);\n                inCijkl(4 - 1, 4 - 1) = mC44_3D(alpha, ipnt);\n                inCijkl(4 - 1, 5 - 1) = mC45_3D(alpha, ipnt);\n                inCijkl(4 - 1, 6 - 1) = mC46_3D(alpha, ipnt);\n                \n                inCijkl(5 - 1, 1 - 1) = mC15_3D(alpha, ipnt);\n                inCijkl(5 - 1, 2 - 1) = mC25_3D(alpha, ipnt);\n                inCijkl(5 - 1, 3 - 1) = mC35_3D(alpha, ipnt);\n                inCijkl(5 - 1, 4 - 1) = mC45_3D(alpha, ipnt);\n                inCijkl(5 - 1, 5 - 1) = mC55_3D(alpha, ipnt);\n                inCijkl(5 - 1, 6 - 1) = mC56_3D(alpha, ipnt);\n                \n                inCijkl(6 - 1, 1 - 1) = mC16_3D(alpha, ipnt);\n                inCijkl(6 - 1, 2 - 1) = mC26_3D(alpha, ipnt);\n                inCijkl(6 - 1, 3 - 1) = mC36_3D(alpha, ipnt);\n                inCijkl(6 - 1, 4 - 1) = mC46_3D(alpha, ipnt);\n                inCijkl(6 - 1, 5 - 1) = mC56_3D(alpha, ipnt);\n                inCijkl(6 - 1, 6 - 1) = mC66_3D(alpha, ipnt);\n            \n                // compute backazimuth\n                const RDCol2 &xieta = SpectralConstants::getXiEta(ipol, jpol, mMyQuad->isAxial());\n                RDCol2 rtheta = Geodesy::rtheta(mMyQuad->mapping(xieta));\n                RDCol3 rtpS, rtpG;\n                rtpS(0) = rtheta(0);\n                rtpS(1) = rtheta(1);\n                rtpS(2) = phi;\n                rtpG = Geodesy::rotateSrc2Glob(rtpS, srcLat, srcLon, srcDep);\n                double recDep = Geodesy::getROuter() - rtheta(0);\n                double recLat = Geodesy::theta2Lat_d(rtpG(1), recDep);\n                double recLon = Geodesy::phi2Lon(rtpG(2));\n                double baz = Geodesy::backAzimuth(srcLat, srcLon, srcDep, recLat, recLon, recDep);\n                \n                // global => source centred RTZ (theta, phi, r)\n                const RDMatXX &outCijkl = bondTransformation(inCijkl, 0., 0., -baz);\n                \n                // by convention, input is in RTZ \n                // // (r, theta, phi) => (R, T, Z)\n                // const RDMatXX &RTZ_Cijkl_x = bondTransformation(rtp_Cijkl, 0., 0., pi/2.);\n                // const RDMatXX &outCijkl = bondTransformation(RTZ_Cijkl_x, pi/2., 0., 0.);\n                \n                // copy back\n                mC11_3D(alpha, ipnt) = outCijkl(1 - 1, 1 - 1);\n                mC12_3D(alpha, ipnt) = outCijkl(1 - 1, 2 - 1);\n                mC13_3D(alpha, ipnt) = outCijkl(1 - 1, 3 - 1);\n                mC14_3D(alpha, ipnt) = outCijkl(1 - 1, 4 - 1);\n                mC15_3D(alpha, ipnt) = outCijkl(1 - 1, 5 - 1);\n                mC16_3D(alpha, ipnt) = outCijkl(1 - 1, 6 - 1);\n                \n                mC22_3D(alpha, ipnt) = outCijkl(2 - 1, 2 - 1);\n                mC23_3D(alpha, ipnt) = outCijkl(2 - 1, 3 - 1);\n                mC24_3D(alpha, ipnt) = outCijkl(2 - 1, 4 - 1);\n                mC25_3D(alpha, ipnt) = outCijkl(2 - 1, 5 - 1);\n                mC26_3D(alpha, ipnt) = outCijkl(2 - 1, 6 - 1);\n                \n                mC33_3D(alpha, ipnt) = outCijkl(3 - 1, 3 - 1);\n                mC34_3D(alpha, ipnt) = outCijkl(3 - 1, 4 - 1);\n                mC35_3D(alpha, ipnt) = outCijkl(3 - 1, 5 - 1);\n                mC36_3D(alpha, ipnt) = outCijkl(3 - 1, 6 - 1);\n                \n                mC44_3D(alpha, ipnt) = outCijkl(4 - 1, 4 - 1);\n                mC45_3D(alpha, ipnt) = outCijkl(4 - 1, 5 - 1);\n                mC46_3D(alpha, ipnt) = outCijkl(4 - 1, 6 - 1);\n                \n                mC55_3D(alpha, ipnt) = outCijkl(5 - 1, 5 - 1);\n                mC56_3D(alpha, ipnt) = outCijkl(5 - 1, 6 - 1);\n                \n                mC66_3D(alpha, ipnt) = outCijkl(6 - 1, 6 - 1);\n            }\n        }\n    }\n}\n\nRDMatXX Material::bondTransformation(RDMatXX inCijkl, double alpha, double beta, double gamma) {\n    RDMat33 R1, R2, R3, R;\n    R1 << 1., 0., 0.,\n          0., cos(alpha), sin(alpha),\n          0., -sin(alpha), cos(alpha);\n    R2 << cos(beta), 0., sin(beta), \n          0., 1., 0.,\n          -sin(beta), 0, cos(beta);\n    R3 << cos(gamma), sin(gamma), 0., \n          -sin(gamma), cos(gamma), 0.,\n          0., 0., 1.;\n    \n    R = R1 * R2 * R3;\n    \n    RDMat33 K1, K2, K3, K4;\n    K1.array() = R.array().pow(2.);\n    K2 << R(0, 1) * R(0, 2), R(0, 2) * R(0, 0), R(0, 0) * R(0, 1),\n          R(1, 1) * R(1, 2), R(1, 2) * R(1, 0), R(1, 0) * R(1, 1),\n          R(2, 1) * R(2, 2), R(2, 2) * R(2, 0), R(2, 0) * R(2, 1);\n    K3 << R(1, 0) * R(2, 0), R(1, 1) * R(2, 1), R(1, 2) * R(2, 2),\n          R(2, 0) * R(0, 0), R(2, 1) * R(0, 1), R(2, 2) * R(0, 2),\n          R(0, 0) * R(1, 0), R(0, 1) * R(1, 1), R(0, 2) * R(1, 2);\n    K4 << R(1, 1) * R(2, 2) + R(1, 2) * R(2, 1), \n          R(1, 2) * R(2, 0) + R(1, 0) * R(2, 2), \n          R(1, 0) * R(2, 1) + R(1, 1) * R(2, 0),\n          R(2, 1) * R(0, 2) + R(2, 2) * R(0, 1), \n          R(2, 2) * R(0, 0) + R(2, 0) * R(0, 2), \n          R(2, 0) * R(0, 1) + R(2, 1) * R(0, 0),\n          R(0, 1) * R(1, 2) + R(0, 2) * R(1, 1), \n          R(0, 2) * R(1, 0) + R(0, 0) * R(1, 2), \n          R(0, 0) * R(1, 1) + R(0, 1) * R(1, 0);\n    \n    RDMatXX K(6, 6);\n    K.block(0, 0, 3, 3) = K1;\n    K.block(0, 3, 3, 3) = 2. * K2;\n    K.block(3, 0, 3, 3) = K3;\n    K.block(3, 3, 3, 3) = K4;\n    \n    RDMatXX outCijkl(K * inCijkl * K.transpose());\n    return outCijkl;\n}\n\nvoid Material::prepare3D() {\n    int Nr = mMyQuad->getNr();\n    mVpv3D = RDMatXN::Zero(Nr, nPE);\n    mVph3D = RDMatXN::Zero(Nr, nPE);\n    mVsv3D = RDMatXN::Zero(Nr, nPE);\n    mVsh3D = RDMatXN::Zero(Nr, nPE);\n    mRho3D = RDMatXN::Zero(Nr, nPE);\n    mEta3D = RDMatXN::Zero(Nr, nPE);\n    mQkp3D = RDMatXN::Zero(Nr, nPE);\n    mQmu3D = RDMatXN::Zero(Nr, nPE);\n    \n    for (int ipol = 0; ipol <= nPol; ipol++) {\n        for (int jpol = 0; jpol <= nPol; jpol++) {\n            int ipnt = ipol * nPntEdge + jpol;\n            const RDCol2 &xieta = SpectralConstants::getXiEta(ipol, jpol, mMyQuad->isAxial());\n            // fill with 1D \n            mVpv3D.col(ipnt).fill(Mapping::interpolate(mVpv1D, xieta));\n            mVph3D.col(ipnt).fill(Mapping::interpolate(mVph1D, xieta));\n            mVsv3D.col(ipnt).fill(Mapping::interpolate(mVsv1D, xieta));\n            mVsh3D.col(ipnt).fill(Mapping::interpolate(mVsh1D, xieta));\n            mRho3D.col(ipnt).fill(Mapping::interpolate(mRho1D, xieta));\n            mEta3D.col(ipnt).fill(Mapping::interpolate(mEta1D, xieta));\n            mQkp3D.col(ipnt).fill(Mapping::interpolate(mQkp1D, xieta));\n            mQmu3D.col(ipnt).fill(Mapping::interpolate(mQmu1D, xieta));\n            // rho for mass\n            int NrP = mMyQuad->getPointNr(ipol, jpol);\n            mRhoMass3D[ipnt] = RDColX::Constant(NrP, mRho3D.col(ipnt)(0));\n            mVpFluid3D[ipnt] = RDColX::Constant(NrP, mVpv3D.col(ipnt)(0));\n        }\n    }\n}\n\nbool Material::_3Dprepared() const {\n    return mVpv3D.rows() == mMyQuad->getNr();\n}\n\n\n", "meta": {"hexsha": "1ea8c1d5a25a411dbb41f9daa147ff59cefd8613", "size": 39480, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SOLVER/src/preloop/physics/material/Material.cpp", "max_stars_repo_name": "kuangdai/AxiSEM3D", "max_stars_repo_head_hexsha": "fd9da14e9107783e3b07b936c67af2412146e099", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T03:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T01:56:45.000Z", "max_issues_repo_path": "SOLVER/src/preloop/physics/material/Material.cpp", "max_issues_repo_name": "syzeng-duduxi/AxiSEM3D", "max_issues_repo_head_hexsha": "fd9da14e9107783e3b07b936c67af2412146e099", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-01-15T17:17:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T09:53:58.000Z", "max_forks_repo_path": "SOLVER/src/preloop/physics/material/Material.cpp", "max_forks_repo_name": "syzeng-duduxi/AxiSEM3D", "max_forks_repo_head_hexsha": "fd9da14e9107783e3b07b936c67af2412146e099", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-12-28T16:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T01:02:16.000Z", "avg_line_length": 42.0447284345, "max_line_length": 226, "alphanum_fraction": 0.5217325228, "num_tokens": 14701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.23545749511042105}}
{"text": "/* This file is part of the Tomographer project, which is distributed under the\n * terms of the MIT license.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 ETH Zurich, Institute for Theoretical Physics, Philippe Faist\n * Copyright (c) 2017 Caltech, Institute for Quantum Information and Matter, Philippe Faist\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#include <iostream>\n\n#include <tomographer/tools/loggers.h>\n#include <tomographer/tools/eigenutil.h>\n#include <tomographer/densedm/dmtypes.h>\n#include <tomographer/densedm/indepmeasllh.h>\n#include <tomographer/densedm/tspacellhwalker.h>\n#include <tomographer/densedm/tspacefigofmerit.h>\n#include <tomographer/mhrw.h>\n#include <tomographer/mhrwtasks.h>\n#include <tomographer/mhrw_valuehist_tools.h>\n\n#include <tomographer/mpi/multiprocmpi.h>\n\n#include <boost/serialization/base_object.hpp>\n\n\n//\n// Data types for our quantum objects.  For the sake of the example, we just\n// leave the size to be dynamic, that is, fixed at run time and not at compile\n// time.\n//\ntypedef Tomographer::DenseDM::DMTypes<Eigen::Dynamic, double> DMTypes;\n\n\n//\n// The class which will store our tomography data. Just define this as\n// \"DenseLLH\" as a shorthand.\n//\ntypedef Tomographer::DenseDM::IndepMeasLLH<DMTypes> DenseLLH;\n\n\n//\n// The type of value calculator we would like to use.  Here, we settle for the\n// expectation value of an observable, as we are interested in the square\n// fidelity to the pure Bell Phi+ state (=expectation value of the observable\n// |Phi+><Phi+|).\n//\ntypedef Tomographer::DenseDM::TSpace::ObservableValueCalculator<DMTypes>\n  ValueCalculator;\n\n//\n// The base CData object we use.  See Tomographer:::MHRWTasks::ValueHistogramTools::CDataBase.\n//\ntypedef Tomographer::MHRWTasks::ValueHistogramTools::CDataBase<\n  ValueCalculator, // our value calculator\n  true, // use binning analysis\n  Tomographer::MHWalkerParamsStepSize<double>, // MHWalkerParams\n  std::mt19937::result_type, // RngSeedType\n  long, // IterCountIntType\n  double, // CountRealType\n  int // HistCountIntType\n  >\n  BaseCData;\n\n//\n// We need to define a class which adds the capacity of creating the \"master\"\n// random walk object to the engine in\n// Tomographer::MHRWTasks::ValueHistogramTools, which take care of running the\n// random walks etc. as needed.\n//\nstruct OurCData : public BaseCData\n{\n  OurCData(DenseLLH * llh_, // data from the the tomography experiment\n\t   ValueCalculator valcalc, // the figure-of-merit calculator\n\t   HistogramParams hist_params, // histogram parameters\n\t   int binning_num_levels, // number of binning levels in the binning analysis\n\t   MHRWParamsType mhrw_params, // parameters of the random walk\n\t   RngSeedType base_seed) // a random seed to initialize the random number generator\n    : BaseCData(valcalc, hist_params, binning_num_levels,\n                mhrw_params, base_seed),\n      llh(llh_)\n  {\n  }\n\n  DenseLLH * llh;\n\n  // The result of a task run -- just use the default StatsResults type provided\n  // by ValueHistogramTools.  If we had several stats collectors set, we would\n  // need to pick out the result corresponding to the\n  // value-histogram-stats-collector (see \"minimal_tomorun_controlled.cxx\" for\n  // an example).\n  typedef MHRWStatsResultsBaseType MHRWStatsResultsType;\n\n  //\n  // This function is called automatically by the task manager/dispatcher via\n  // MHRWTasks.  It should set up the random walk as required (at a minimum,\n  // create a MHWalker instance and pass on the default value stats collector\n  // from Tomographer::MHRWTasks::ValueHistogramTools), and run it.\n  //\n  // We should not forget to call run(), to actually run the random walk!\n  //\n  template<typename Rng, typename LoggerType, typename ExecFn>\n  inline void setupRandomWalkAndRun(Rng & rng, LoggerType & logger, ExecFn run) const\n  {\n    auto val_stats_collector = createValueStatsCollector(logger);\n\n    Tomographer::DenseDM::TSpace::LLHMHWalker<DenseLLH,Rng,LoggerType> mhwalker(\n            llh->dmt.initMatrixType(),\n            *llh,\n            rng,\n            logger\n            );\n\n    run(mhwalker, val_stats_collector);\n  };\n\nprivate:\n  OurCData() : BaseCData(), llh(NULL) { } // for serialization\n\n  friend boost::serialization::access;\n  template<typename Archive>\n  void serialize(Archive & a, unsigned int /* version */)\n  {\n    a & boost::serialization::base_object<BaseCData>(*this);\n    a & llh;\n  }\n};\n\n\n//\n// The root logger which takes care of handling the log messages.  Here, we log to the\n// standard output (recall that stdout/stderr are seen as a \"file\").\n//\n// The level of the logger can be set to one of Tomographer::Logger::LONGDEBUG,\n// Tomographer::Logger::DEBUG, Tomographer::Logger::INFO, Tomographer::Logger::WARNING or\n// Tomographer::Logger::ERROR.\n//\ntypedef Tomographer::Logger::FileLogger BaseLoggerType;\nBaseLoggerType rootlogger(stderr, Tomographer::Logger::DEBUG);\n\n\n// The task type, for the MultiProc interface\ntypedef Tomographer::MHRWTasks::MHRandomWalkTask<OurCData, std::mt19937>\n  OurMHRandomWalkTask;\n\n\nint main()\n{\n  //\n  // MPI initializations\n  //\n  mpi::environment mpi_env;\n  mpi::communicator mpi_world;\n\n  const bool is_master = (mpi_world.rank() == 0);\n\n\n  //\n  // Prepare the logger in which we can log debug/info/error messages.\n  //\n  typedef Tomographer::Logger::OriginPrefixedLogger<decltype(rootlogger)> PrefixLoggerType;\n  PrefixLoggerType baselogger(rootlogger, streamstr(mpi_world.rank() << \"/\" << mpi_world.size()<<\"|\"));\n\n  auto logger = Tomographer::Logger::makeLocalLogger(\"main()\", baselogger);\n\n\n  logger.debug(\"starting up\");\n\n\n  DenseLLH * llh = NULL;\n  OurCData * taskcdat = NULL;\n\n  if (is_master) {\n    //\n    // Master gets to prepare all the data.\n    //\n    \n    //\n    // Specify the dimension of the quantum tomography setting.\n    //\n    const int dim = 4; // two qubits\n    DMTypes dmt(dim);\n\n    //\n    // Prepare data from the tomography experiment.\n    //\n    // In this hypothetical experiment, we assumed that the observables\n    // \\sigma_x\\otimes\\sigma_x, \\sigma_y\\otimes\\sigma_y and \\sigma_z\\otimes\\sigma_z are each\n    // measured 100 times. Each measurement setting has two possible outcomes, +1 or -1, and\n    // hence there are in total 6 POVM effects.\n    //\n\n    llh = new DenseLLH(dmt);\n  \n    // POVM effects for  \\sigma_x \\otimes \\sigma_x\n  \n    DMTypes::MatrixType Exxplus(dmt.initMatrixType());\n    Exxplus <<\n      0.5,    0,    0,  0.5,\n      0,    0.5,  0.5,    0,\n      0,    0.5,  0.5,    0,\n      0.5,    0,    0,  0.5;\n\n    llh->addMeasEffect(Exxplus, 95);  // 95 counts of \"+1\" out of 100 for \\sigma_x\\otimes\\sigma_x\n\n    DMTypes::MatrixType Exxminus(dmt.initMatrixType());\n    Exxminus <<\n      0.5,    0,    0, -0.5,\n      0,    0.5, -0.5,    0,\n      0,   -0.5,  0.5,    0,\n      -0.5,   0,    0,  0.5;\n\n    llh->addMeasEffect(Exxminus, 5);  // 95 counts of \"-1\" out of 100 for \\sigma_x\\otimes\\sigma_x\n\n    // POVM effects for  \\sigma_y \\otimes \\sigma_y\n  \n    DMTypes::MatrixType Eyyplus(dmt.initMatrixType());\n    Eyyplus <<\n      0.5,    0,    0, -0.5,\n      0,    0.5,  0.5,    0,\n      0,    0.5,  0.5,    0,\n      -0.5,   0,    0,  0.5;\n\n    llh->addMeasEffect(Eyyplus, 8);  // 8 counts of \"+1\" out of 100 for \\sigma_y\\otimes\\sigma_y\n\n    DMTypes::MatrixType Eyyminus(dmt.initMatrixType());\n    Eyyminus <<\n      0.5,    0,    0,  0.5,\n      0,    0.5, -0.5,    0,\n      0,   -0.5,  0.5,    0,\n      0.5,    0,    0,  0.5;\n\n    llh->addMeasEffect(Eyyminus, 92);  // 92 counts of \"-1\" out of 100 for \\sigma_y\\otimes\\sigma_y\n\n    // POVM effects for  \\sigma_z \\otimes \\sigma_z\n  \n    DMTypes::MatrixType Ezzplus(dmt.initMatrixType());\n    Ezzplus <<\n      1,   0,   0,   0,\n      0,   0,   0,   0,\n      0,   0,   0,   0,\n      0,   0,   0,   1;\n\n    llh->addMeasEffect(Ezzplus, 98);  // 98 counts of \"+1\" out of 100 for \\sigma_z\\otimes\\sigma_z\n\n    DMTypes::MatrixType Ezzminus(dmt.initMatrixType());\n    Ezzminus <<\n      0,   0,   0,   0,\n      0,   1,   0,   0,\n      0,   0,   1,   0,\n      0,   0,   0,   0;\n\n    llh->addMeasEffect(Ezzminus, 2);  // 2 counts of \"-1\" out of 100 for \\sigma_z\\otimes\\sigma_z\n\n    logger.debug(\"data entered OK\");\n\n    //\n    // Prepare the figure of merit calculator: Squared fidelity to the pure entangled Bell\n    // state |\\Phi^+>\n    //\n\n    DMTypes::MatrixType phiplus(dmt.initMatrixType());\n    phiplus <<\n      0.5,    0,    0,   0.5,\n      0,      0,    0,     0,\n      0,      0,    0,     0,\n      0.5,    0,    0,   0.5;\n\n    // our main ValueCalculator instance, which is in fact an alias for the\n    // ObservableValueCalculator class. [If we wanted to choose which figure of merit to\n    // compute at run-time, then we should use a MultiplexorValueCalculator.]\n    ValueCalculator valcalc(dmt, phiplus);\n\n    // parameters of the histogram of the figure of merit: cover the range [0.75, 1.0] by\n    // dividing it into 50 bins\n    const OurCData::HistogramParams hist_params(0.7, 1.0, 50);\n\n    // parameters of the random walk\n    const OurCData::MHRWParamsType mhrw_params(\n        0.04, // step size (choose such that acceptance ratio ~ 0.25)\n        50, // sweep size (should be chosen such that  sweep_size*step_size >~ 1)\n        1024, // # of thermalization sweeps\n        32768 // # of live sweeps in which samples are collected\n        );\n\n    // seed for random number generator -- just use the current time\n    std::mt19937::result_type base_seed =\n      (std::mt19937::result_type)std::chrono::system_clock::now().time_since_epoch().count();\n\n    // number of levels for the binning analysis\n    const int binning_num_levels = 8;\n\n    // instantiate the class which stores the shared data.\n    taskcdat = new OurCData(llh, valcalc, hist_params, binning_num_levels,\n                            mhrw_params, base_seed);\n\n    logger.debug(\"Master here, data ready\") ;\n  } else {\n    taskcdat = NULL;\n    logger.debug(\"Not master, skipping through all the init process\") ;\n  }\n\n  //\n  // Data is ready, prepare & launch the random walks.  Use MPI.\n  //\n\n\n  // repeat the whole random walk this number of times.  These random walks will\n  // run in parallel depending on the number of CPUs available.\n  const int num_repeats = 20;\n\n  // create the task manager/dispatcher, using the MPI implementation !!\n  auto tasks =\n    Tomographer::MultiProc::MPI::mkTaskDispatcher<OurMHRandomWalkTask>(\n        taskcdat, // constant data\n        mpi_world,\n        logger.parentLogger(), // the main logger object\n        num_repeats // num_runs\n        );\n\n  if (is_master) {\n    // only master gets to do this\n\n    // get status reports every X milliseconds printed out on std::cout\n    tasks.setStatusReportHandler([&](decltype(tasks)::FullStatusReportType report) {\n        std::cout << report.getHumanReport() << \"\\n\" ;\n      });\n    tasks.requestPeriodicStatusReport(1000) ;\n  }\n\n  //\n  // Finally, run our tomo process\n  //\n\n  logger.debug(\"all set, ready to go\");\n\n  auto time_start = std::chrono::system_clock::now();\n\n  tasks.run(); // GO!\n\n  auto time_end = std::chrono::system_clock::now();\n\n  logger.debug(\"Random walks done.\");\n\n  // delta-time, formatted in hours, minutes, seconds and fraction of seconds\n  std::string elapsed_s = Tomographer::Tools::fmtDuration(time_end - time_start);\n\n  if (!is_master) {\n    logger.debug(\"not master, we're done here.\");\n    return 0;\n  }\n\n  // only master beyond this point\n\n  const auto & task_results = tasks.collectedTaskResults();\n\n  auto aggregated_histogram = taskcdat->aggregateResultHistograms(task_results) ;\n\n  const auto & histogram = aggregated_histogram.final_histogram;\n\n  // histogram has type Tomographer::AveragedHistogram, you can use it like any other\n  // Histogram or HistogramWithErrorBars.  You can pretty-print it with:\n  logger.info([&](std::ostream & stream) {\n      stream << \"Nice little histogram after all that work: \\n\"\n             << histogram.prettyPrint()\n             << \"\\n\";\n      });\n\n  logger.info([&](std::ostream & stream) {\n      // Tomographer::MHRWTasks::ValueHistogramTools::printFinalReport() will generate a\n      // default tomorun-like report with the parameters of the random walk, an overview\n      // of each histogram of each task repeat, short info on the convergence of the\n      // binning error bars, and the final histogram itself along with error bars\n      Tomographer::MHRWTasks::ValueHistogramTools::printFinalReport(\n          stream, // where to output\n          *taskcdat, // the cdata\n          task_results, // the results\n          aggregated_histogram // aggregated\n          );\n    });\n\n\n  delete llh;\n  delete taskcdat;\n\n  logger.debug(\"Finally, all done.\");\n\n  // success.\n  return 0;\n}\n", "meta": {"hexsha": "1d27d1e5823d30e35b52aa6dfc8fafdcc4b5926d", "size": 13694, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "test/minimal_mpi_tomorun.cxx", "max_stars_repo_name": "Tomographer/tomographer", "max_stars_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T02:25:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-13T02:26:00.000Z", "max_issues_repo_path": "test/minimal_mpi_tomorun.cxx", "max_issues_repo_name": "Tomographer/tomographer", "max_issues_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-12T15:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-21T15:14:59.000Z", "max_forks_repo_path": "test/minimal_mpi_tomorun.cxx", "max_forks_repo_name": "Tomographer/tomographer", "max_forks_repo_head_hexsha": "0a64927e639454175803c1746141bd9288af8b29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2015-10-12T15:32:29.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-08T11:39:49.000Z", "avg_line_length": 33.4816625917, "max_line_length": 103, "alphanum_fraction": 0.6736526946, "num_tokens": 3839, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.23544472958611865}}
{"text": "//---------------------------------------------------------------------------//\n//  MIT License\n//\n//  Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n//  Copyright (c) 2020-2021 Nikita Kaskov <nemo@nil.foundation>\n//\n//  Permission is hereby granted, free of charge, to any person obtaining a copy\n//  of this software and associated documentation files (the \"Software\"), to deal\n//  in the Software without restriction, including without limitation the rights\n//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n//  copies of the Software, and to permit persons to whom the Software is\n//  furnished to do so, subject to the following conditions:\n//\n//  The above copyright notice and this permission notice shall be included in all\n//  copies or substantial portions of the Software.\n//\n//  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n//  SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef FILECOIN_STORAGE_PROOFS_CORE_PARAMETER_CACHE_HPP\n#define FILECOIN_STORAGE_PROOFS_CORE_PARAMETER_CACHE_HPP\n\n#define BOOST_FILESYSTEM_NO_DEPRECATED\n\n#include <string>\n\n#include <boost/filesystem/path.hpp>\n#include <boost/filesystem/operations.hpp>\n\n#include <nil/crypto3/algebra/curves/bls12.hpp>\n\n#include <nil/crypto3/hash/sha2.hpp>\n#include <nil/crypto3/hash/algorithm/hash.hpp>\n\n#include <nil/crypto3/marshalling/types/zk/r1cs_gg_ppzksnark/verification_key.hpp>\n\n#include <nil/filecoin/storage/proofs/core/btree/map.hpp>\n\n#include <nil/filecoin/storage/proofs/core/crypto/scheme_params.hpp>\n#include <nil/filecoin/storage/proofs/core/crypto/mapped_scheme_params.hpp>\n\nnamespace nil {\n    namespace filecoin {\n        constexpr static const std::size_t VERSION = 28;\n        constexpr static const std::size_t SRS_MAX_PROOFS_TO_AGGREGATE = 65535;\n        constexpr static const char *PARAMETER_CACHE_ENV_VAR = \"FIL_PROOFS_PARAMETER_CACHE\";\n        constexpr static const char *PARAMETER_CACHE_DIR = \"/var/tmp/filecoin-proof-parameters/\";\n        constexpr static const char *GROTH_PARAMETER_EXT = \"params\";\n        constexpr static const char *PARAMETER_METADATA_EXT = \"meta\";\n        constexpr static const char *VERIFYING_KEY_EXT = \"vk\";\n        constexpr static const char *SRS_SHARED_KEY_NAME = \"fil-inner-product-v1\";\n\n        struct parameter_data {\n            std::string cid;\n            std::string digest;\n            std::uint64_t sector_size;\n        };\n\n        typedef btree::map<std::string, parameter_data> parameter_map;\n\n        static parameter_map PARAMETERS;\n        static parameter_map SRS_PARAMETERS;\n\n        std::string parameter_cache_dir_name() {\n            return std::getenv(PARAMETER_CACHE_ENV_VAR);\n        }\n\n        boost::filesystem::path parameter_cache_dir() {\n            return parameter_cache_dir_name();\n        }\n\n        boost::filesystem::path parameter_cache_params_path(const std::string &parameter_set_identifier) {\n            return boost::filesystem::path(\n                (parameter_cache_dir_name() + \"/v\" + std::to_string(VERSION) + \"-\" + parameter_set_identifier + \".\")\n                    .append(GROTH_PARAMETER_EXT));\n        }\n\n        boost::filesystem::path parameter_cache_metadata_path(const std::string &parameter_set_identifier) {\n            return boost::filesystem::path(\n                (parameter_cache_dir_name() + \"/v\" + std::to_string(VERSION) + \"-\" + parameter_set_identifier + \".\")\n                    .append(PARAMETER_METADATA_EXT));\n        }\n\n        boost::filesystem::path parameter_cache_verifying_key_path(const std::string &parameter_set_identifier) {\n            return boost::filesystem::path(\n                (parameter_cache_dir_name() + \"/v\" + std::to_string(VERSION) + \"-\" + parameter_set_identifier + \".\")\n                    .append(VERIFYING_KEY_EXT));\n        }\n\n        boost::filesystem::path ensure_ancestor_dirs_exist(const boost::filesystem::path &cache_entry_path) {\n            boost::filesystem::path parent_dir = cache_entry_path.parent_path();\n            if (boost::filesystem::exists(parent_dir)) {\n                return cache_entry_path;\n            } else {\n                throw std::invalid_argument(cache_entry_path.string() + \" has no parent directory\");\n            }\n        }\n\n        struct parameter_set_metadata {\n            virtual std::string identifier() const = 0;\n            virtual std::size_t sector_size() const = 0;\n        };\n\n        struct cache_entry_metadata {\n            std::size_t sector_size;\n        };\n\n        cache_entry_metadata read_cached_metadata(const boost::filesystem::path &cache_entry_path) {\n            return serde_json::from_reader(cache_entry_path);\n        }\n\n        cache_entry_metadata write_cached_metadata(const boost::filesystem::path &cache_entry_path,\n                                                   cache_entry_metadata value) {\n            serde_json::to_writer(cache_entry_path, value);\n\n            return value;\n        }\n\n        mapped_scheme_params<crypto3::zk::snark::r1cs_gg_ppzksnark<crypto3::algebra::curves::bls12<381>>>\n            read_cached_params(const boost::filesystem::path &cache_entry_path) {\n            return mapped_scheme_params<crypto3::zk::snark::r1cs_gg_ppzksnark<crypto3::algebra::curves::bls12<381>>>::\n                build_mapped_parameters(cache_entry_path, false);\n        }\n\n        crypto3::zk::snark::r1cs_gg_ppzksnark_verification_key<crypto3::algebra::curves::bls12<381>>\n            read_cached_verifying_key(const boost::filesystem::path &cache_entry_path) {\n            return crypto3::zk::snark::r1cs_gg_ppzksnark_verification_key<crypto3::algebra::curves::bls12<381>>::read(\n                cache_entry_path);\n        }\n\n        crypto3::zk::snark::r1cs_gg_ppzksnark_verification_key<crypto3::algebra::curves::bls12<381>>\n            write_cached_verifying_key(\n                const boost::filesystem::path &cache_entry_path,\n                const crypto3::zk::snark::r1cs_gg_ppzksnark_verification_key<crypto3::algebra::curves::bls12<381>>\n                    &value) {\n            value.write(cache_entry_path);\n\n            return value;\n        }\n\n        scheme_params<crypto3::zk::snark::r1cs_gg_ppzksnark<crypto3::algebra::curves::bls12<381>>> write_cached_params(\n            const boost::filesystem::path &cache_entry_path,\n            scheme_params<crypto3::zk::snark::r1cs_gg_ppzksnark<crypto3::algebra::curves::bls12<381>>>\n                value) {\n            value.write(cache_entry_path);\n            return value;\n        }\n\n        template<template<typename> class Circuit, typename ParameterSetMetadata = parameter_set_metadata>\n        struct cacheable_parameters {\n            typedef Circuit<crypto3::algebra::curves::bls12<381>> C;\n            typedef ParameterSetMetadata P;\n\n            virtual std::string cache_prefix() const = 0;\n\n            cache_entry_metadata cache_meta(const P &pub_params) {\n                return {pub_params.graph.sector_size()};\n            }\n\n            virtual std::string cache_identifier(const P &pub_params) {\n                using namespace nil::crypto3;\n\n                std::string circuit_hash = crypto3::hash<crypto3::hashes::sha2<256>>(pub_params.identifier());\n                actor::format(\"{}-{:02x}\", cache_prefix(), circuit_hash.iter().format(\"\"));\n            }\n\n            cache_entry_metadata get_param_metadata(const C &circuit, const P &pub_params) {\n                std::string id = cache_identifier(pub_params);\n\n                // generate (or load) metadata\n                boost::filesystem::path meta_path = ensure_ancestor_dirs_exist(parameter_cache_metadata_path(id));\n                try {\n                    read_cached_metadata(meta_path);\n                } catch (...) {\n                    write_cached_metadata(meta_path, cache_meta(pub_params));\n                }\n            }\n\n            mapped_scheme_params<crypto3::zk::snark::r1cs_gg_ppzksnark<crypto3::algebra::curves::bls12<381>>>\n                get_groth_params(const C &circuit, const P &pub_params) {\n                std::string id = cache_identifier(pub_params);\n\n                const auto generate = [&]() {\n                    return groth16::generate_random_parameters<crypto3::algebra::curves::bls12<381>>(circuit, r);\n                };\n\n                boost::filesystem::path cache_path = ensure_ancestor_dirs_exist(parameter_cache_params_path(id));\n\n                try {\n                    return read_cached_params(cache_path);\n                } catch (...) {\n                    return write_cached_params(cache_path, generate());\n                }\n            }\n\n            template<typename UniformRandomGenerator>\n            crypto3::zk::snark::r1cs_gg_ppzksnark_verification_key<crypto3::algebra::curves::bls12<381>>\n                get_verifying_key(UniformRandomGenerator &r, const C &circuit, const P &pub_params) {\n                std::string id = cache_identifier(pub_params);\n\n                const auto generate = [&]()\n                    -> crypto3::zk::snark::r1cs_gg_ppzksnark_verification_key<crypto3::algebra::curves::bls12<381>> {\n                    return get_groth_params(r, circuit, pub_params).vk;\n                };\n\n                boost::filesystem::path cache_path = ensure_ancestor_dirs_exist(parameter_cache_verifying_key_path(id));\n                try {\n                    return read_cached_verifying_key(cache_path);\n                } catch (...) {\n                    return write_cached_verifying_key(cache_path, generate());\n                }\n            }\n        };\n    }    // namespace filecoin\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "b4860713fff02f9ddbeaa3d03a7a66e60a6fde9b", "size": 10063, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/parameter_cache.hpp", "max_stars_repo_name": "NilFoundation/crypto3-fil-proofs", "max_stars_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/parameter_cache.hpp", "max_issues_repo_name": "NilFoundation/crypto3-fil-proofs", "max_issues_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-06T13:07:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T12:38:09.000Z", "max_forks_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/parameter_cache.hpp", "max_forks_repo_name": "NilFoundation/crypto3-fil-proofs", "max_forks_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9241071429, "max_line_length": 120, "alphanum_fraction": 0.6355957468, "num_tokens": 2181, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947155710234, "lm_q2_score": 0.3593641451601019, "lm_q1q2_score": 0.2353456796310489}}
{"text": "\n\n#include \"../gain_utils.h\"\n#include \"coela_utility/src/string_utils.h\"\n\n#include \"coela_utility/src/misc_math.h\"\n\n#include \"coela_utility/src/microstats.h\"\n\n#include <boost/math/distributions/poisson.hpp>\n#include <Minuit2/MnMigrad.h>\n#include <Minuit2/FunctionMinimum.h>\n#include <Minuit2/MnPrint.h>\n#include <iostream>\n#include <stdexcept>\n#include <Minuit2/MnMinimize.h>\n#include <Minuit2/MnSimplex.h>\n#include <Minuit2/MnScan.h>\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/math/distributions/hypergeometric.hpp>\n\nusing namespace std;\nnamespace coela {\nnamespace gain_utils {\n//=====================================================================================================================\n\nvoid append_histogram_data_from_float_bitmap_region(const CcdImage<float>& bmp,\n        const PixelRange& rgn, HistogramContainer14bit& hist)\n{\n    assert(hist.minimum_has_been_set());\n    assert(rgn.is_valid());\n    for (int y=rgn.low.y; y<=rgn.high.y; ++y) {\n        for (int x=rgn.low.x; x<=rgn.high.x; ++x) {\n            hist.count_rounded_value(bmp.pix(x,y));\n        }\n    }//end pixel scan\n    return;\n}\n\nvoid append_histogram_data_from_float_bitmap_region(const CcdImage<float>& bmp,\n        const PixelRange& rgn, HistogramContainer10bit& hist)\n{\n    assert(hist.minimum_has_been_set());\n    assert(rgn.is_valid());\n    for (int y=rgn.low.y; y<=rgn.high.y; ++y) {\n        for (int x=rgn.low.x; x<=rgn.high.x; ++x) {\n            hist.count_rounded_value(bmp.pix(x,y));\n        }\n    }//end pixel scan\n    return;\n}\n\n\n\n\nmap<int,long> load_histogram_data_from_file(const string& filename)\n{\n    ifstream datafile(filename.c_str());\n    if (!datafile) { throw runtime_error(\"Could not load histogram data from \\\"\"+filename+\"\\\"\"); }\n    int value; long count;\n    map <int,long> histogram_data;\n    while ((datafile>>value)) {\n        datafile>>count;\n        histogram_data[value] = count;\n    }\n    return histogram_data;\n}\n\n\n\n\ndouble histogram_differences_squared(const map<int,long>& data,\n                                     const map<int,double>& model)\n{\n    assert(data.size()==model.size());\n    double diff_sq_sum=0.0;\n    double diff;\n    for (map<int,long>::const_iterator it=data.begin(); it!=data.end(); ++it) {\n        map<int,double>::const_iterator model_it = model.find(it->first);\n        if (model_it==model.end()) { throw runtime_error(\"Gain utils: model/data mismatch during fitting\"); }\n        diff = it->second - model_it->second;\n        diff_sq_sum += diff*diff;\n    }\n    return diff_sq_sum;\n}\n\ndouble poisson_noise_weighted_histogram_difference(const map<int,long>& data,\n        const map<int,double>& model)\n{\n    assert(data.size()>=model.size());\n    double diff_sq_sum=0.0;\n    double diff;\n\n//    pair<int,long> data_min_pair = get_min_value_pair(data);\n//    pair<int,double> model_min_pair = get_min_value_pair(model);\n//    cerr<<\"Data / model min \"<< data_min_pair.first<<\" / \"<< model_min_pair.first<<endl;\n\n    for (map<int,double>::const_iterator model_it=model.begin(); model_it!=model.end();\n            ++model_it) {\n//        map<int,double>::const_iterator model_it = model.find(it->first);\n//        if (model_it==model.end()) throw runtime_error(\"Gain utils: model/data mismatch during fitting\");\n        map<int,long>::const_iterator data_it = data.find(model_it->first);\n        if (data_it==data.end()) throw\n            runtime_error(\"Gain utils: model/data mismatch during fitting;\"\n                          \"could not find datapoint for value \" + string_utils::itoa(model_it->first));\n        diff = (data_it->second - model_it->second);\n        diff_sq_sum += diff*diff / max(data_it->second,\n                                       1l);  //Poisson distribution for each histogram entry, so variance == probability\n//        diff_sq_sum += pow(fabs(diff),1.5) / sqrt(model_it->second); //This method less sensitive to noise spikes at the end of the histogram section\n    }\n    return diff_sq_sum;\n}\n\ndouble log_space_histogram_difference(const map<int,long>& data,\n                                      const map<int,double>& model)\n{\n    assert(data.size()>=model.size());\n    double diff_sq_sum=0.0;\n    double diff;\n    for (map<int,double>::const_iterator model_it=model.begin(); model_it!=model.end();\n            ++model_it) {\n        map<int,long>::const_iterator data_it = data.find(model_it->first);\n        if (data_it==data.end()) throw\n            runtime_error(\"Gain utils: model/data mismatch during fitting;\"\n                          \"could not find datapoint for value \" + string_utils::itoa(model_it->first));\n        diff = (log(data_it->second) - log(model_it->second));\n        diff_sq_sum += diff*diff ;\n    }\n    return diff_sq_sum;\n}\n\nmap<int, double> convolve_histogram_with_gaussian(const map<int, double>& input_hist,\n        const double readout_sigma,\n        const int kernel_half_width)\n{\n    map<int, double> readout_kernel;\n\n    const double unity_area_gaussian_height = 1.0 / (sqrt(2.0*M_PI)*readout_sigma);\n\n    const int kernel_min(-kernel_half_width), kernel_max(kernel_half_width);\n    for (int value = kernel_min ; value <= kernel_max; ++value) {\n        readout_kernel[value] = misc_math::gaussian_1d_function(value,\n                                unity_area_gaussian_height,\n                                readout_sigma);\n    }\n\n    const int input_min= get_min_value_pair(input_hist).first ;\n    const int input_max= get_max_value_pair(input_hist).first ;\n\n//    cerr<<\"Kernel min / max\" << kernel_min <<\" / \"<< kernel_max<<endl;\n//    cerr<<\"Input min / max\" << input_min <<\" / \"<< input_max<<endl;\n\n\n    map<int, double> convolved_hist;\n    for (map<int,double>::const_iterator input_it=input_hist.begin();\n            input_it!=input_hist.end(); ++input_it) {\n        const int input_value= input_it->first;\n        if (input_value + kernel_min >= input_min &&\n                input_value + kernel_max <= input_max) {\n            if (convolved_hist.find(input_value) == input_hist.end()) {\n                convolved_hist[input_value ] = 0.0;\n            }\n            for (map<int,double>::const_iterator kernel_it=readout_kernel.begin();\n                    kernel_it!=readout_kernel.end(); ++kernel_it) {\n\n                int kernel_offset_input = kernel_it->first + input_value;\n                convolved_hist[ input_value ] +=\n                    input_hist.find(kernel_offset_input)->second * kernel_it->second;\n\n            }\n        }\n//        else{\n//            cerr<<\"rejecting input val \" << input_value<<endl;\n//        }\n\n    }\n    return convolved_hist;\n}\n\n//==================================================================================\n\ndouble GaussianHistogramFitFCN::operator()(const std::vector<double>& gauss_pars) const\n{\n    assert(gauss_pars.size()==3);\n    map<int,double> model=get_model_histogram(gauss_pars);\n//            return histogram_differences_squared(data, model);\n//            cerr<<\"Pars: \"<< gauss_pars[0]<<\" \" <<gauss_pars[1]<<\" \"<<gauss_pars[2]<<endl;\n    return poisson_noise_weighted_histogram_difference(data, model);\n\n}\n\nmap<int,double> GaussianHistogramFitFCN::get_model_histogram(\n    const std::vector<double>& gauss_pars) const\n{\n    map<int,double>model;\n    for (map<int,long>::const_iterator it=data.begin(); it!=data.end(); ++it) {\n        model[it->first] = misc_math::gaussian_1d_function((double)it->first - gauss_pars[0],\n                           gauss_pars[1],\n                           gauss_pars[2]);  //FIXME -- should perhaps be measuring distance from centre of bin? (so +0.5 to it->first). but not sure.\n    }\n    return model;\n}\n\n//==================================================================================\nmap<int,double> ExponentialHistogramFitFCN::get_model_histogram(\n    const std::vector<double>& exp_pars) const\n{\n    assert(exp_pars.size()==2);\n    map<int,double>model;\n    const double& amplitude = exp_pars[0];\n    const double& gain = exp_pars[1];\n    for (map<int,long>::const_iterator it=data.begin(); it!=data.end(); ++it) {\n        model[it->first] = amplitude*exp(-1.0*it->first/gain);\n    }\n    return model;\n}\n\ndouble  ExponentialHistogramFitFCN::operator()(const std::vector<double>& exp_pars)\nconst\n{\n    assert(exp_pars.size()==2);\n    map<int,double> model=get_model_histogram(exp_pars);\n//    return log_space_histogram_difference(data, model);\n    return poisson_noise_weighted_histogram_difference(data, model) / (model.size() - 1);\n\n}\n//==================================================================================\n//map<int,double> full_EMCCD_low_light_level_histogram_model::get_model_histogram(\n//        const GainData& inf){\n//\n//}\n//\n\n//==================================================================================\nFullEmccdHistogramFitFCN::FullEmccdHistogramFitFCN(const map<int,long>& histogram)\n    :\n    error_def(1.0), data_(histogram)\n{\n    fit_rgn_min_ = get_min_value_pair(data_).first;\n    fit_rgn_max_ = get_max_value_pair(data_).first;\n}\n\nFullEmccdHistogramFitFCN::FullEmccdHistogramFitFCN(const map<int,long>& histogram,\n        const int fit_region_min, const int fit_region_max):\n    error_def(1.0), data_(histogram),\n    fit_rgn_min_(fit_region_min), fit_rgn_max_(fit_region_max)\n{}\n\ndouble FullEmccdHistogramFitFCN::operator()(const std::vector<double>& pars) const\n{\n    assert(pars.size()==npars_);\n\n//    cout<<\"Params: \";\n//    for (size_t i=0; i!=pars.size();++i){\n//        cout<<pars[i]<<\" \";\n//    }\n//\n    map<int,double> model = get_model_histogram(pars);\n    double val = poisson_noise_weighted_histogram_difference(data_, model);\n//\n//    cout<<\" : \"<<val;\n//    cout<<endl;\n//\n    double normalised = val / (model.size() - (npars_ - 1));\n\n    return normalised;\n}\nvector<double> FullEmccdHistogramFitFCN::generate_pars_vec(const GainData& inf)\n{\n    vector<double> pars;\n    pars.push_back(inf.bias_pedestal);\n    pars.push_back(inf.N_dark_pix);\n    pars.push_back(inf.readout_sigma);\n    pars.push_back(inf.N_light_pix);\n    pars.push_back(inf.gain);\n    pars.push_back(inf.N_serial_CIC_pix);\n//    pars.push_back(inf.serial_CIC_gain);\n    return pars;\n}\n\n\nmap<int,double> FullEmccdHistogramFitFCN::get_CICIR_model_histogram(\n    const double gain,\n    const double N_CICIR_pix,\n    const int N_EM_stages,\n    const int max_val_to_generate)\n{\n\n    int min_N_stages=1;\n    double prob_per_stage = pow(gain, 1.0/N_EM_stages);\n\n\n    map<int,double> gain_for_N_stages;\n    for (int stages_passed = 1; stages_passed<=N_EM_stages; ++stages_passed) {\n        gain_for_N_stages[stages_passed] = pow(prob_per_stage, stages_passed);\n    }\n\n//    cerr<<\"gain at 604:\"<< gain_for_N_stages[604]<<endl;\n//    const double frequency_normalisation =  N_CICIR_pix ;\n    const double frequency_normalisation = N_CICIR_pix / (N_EM_stages - min_N_stages);\n\n    map<int,double> CICIR_histogram;\n    for (int register_output_val=1; register_output_val<=max_val_to_generate;\n            ++register_output_val) {\n        double output_frequency=0.0;\n        for (int CICIR_stages_passed = min_N_stages; CICIR_stages_passed<=N_EM_stages;\n                ++CICIR_stages_passed) {\n            const double & g = gain_for_N_stages[CICIR_stages_passed];\n\n            output_frequency +=  exp((0.5-register_output_val)/g) / g;\n        }\n        CICIR_histogram[register_output_val]= frequency_normalisation * output_frequency;\n    }\n    return CICIR_histogram;\n}\n\nmap<int,double> FullEmccdHistogramFitFCN::get_model_histogram(\n    const std::vector<double>& pars) const\n{\n    assert(pars.size()==npars_);\n\n    const double& bias_pedestal = pars[0];\n    const double& dark_pix = pars[1];\n    const double& RO_sigma = pars[2];\n    const double& N_photon_events = pars[3];\n    const double& phot_gain = pars[4];\n    const double& N_serial_CIC_pix = pars[5];\n//    const double& serial_CIC_gain = pars[6];\n//    const double serial_CIC_gain = sqrt(phot_gain);\n\n    int convolution_half_width=60;\n\n//   int data_start = get_min_value_pair(data).first;\n    int data_end = get_max_value_pair(data_).first;\n    int tail_range = data_end - bias_pedestal;\n\n    double total_pix_calc = N_photon_events + N_serial_CIC_pix + dark_pix;\n    double photon_freq_est = N_photon_events / total_pix_calc;\n//   cerr<<\"Photon freq est: \" << photon_freq_est<<\", calc total: \" << total_pix_calc<<endl;\n\n    //See Basden et al, 2003 for equations\n\n\n//   double serial_CIC_amplitude =\n//    N_serial_CIC_pix * exp(0.5/serial_CIC_gain)/ serial_CIC_gain;\n\n    double p1_amplitude, p2_amplitude;\n    if (photon_freq_est>0) {\n        boost::math::poisson_distribution<> pois_dist(photon_freq_est);\n        double p1_prob = boost::math::pdf(pois_dist, 1);\n        double p2_prob = boost::math::pdf(pois_dist, 2);\n\n        //Note exp( 0.5 / phot_gain) term corrects ~1% normalisation error;\n        // since integral from 1 to +inf of the PDF otherwise  =  exp(-1/g)\n        p1_amplitude = (p1_prob / (p1_prob +p2_prob)) *\n                       N_photon_events * exp(0.5/phot_gain) /  phot_gain;\n\n        //Note normalisation correction not reqd here, more complex to calc. but also much smaller effect.\n        p2_amplitude = (p2_prob / (p1_prob +p2_prob)) *\n                       N_photon_events / (phot_gain*phot_gain);\n    } else {\n        p1_amplitude=0.0;\n        p2_amplitude=0.0;\n    }\n\n    map<int,double> register_output_model;\n    int fit_rgn_extension_below_bias_pedestal = bias_pedestal - fit_rgn_min_;\n    if (fit_rgn_extension_below_bias_pedestal > 0) {\n        for (int i= -(convolution_half_width + fit_rgn_extension_below_bias_pedestal); i<0; ++i) {\n            register_output_model[i]=0;\n        }\n    } else {\n        for (int i= -convolution_half_width; i<0; ++i) {\n            register_output_model[i]=0;\n        }\n    }\n\n    register_output_model[0]  = dark_pix;\n\n    map<int,double> CICIR_register_component =\n        FullEmccdHistogramFitFCN::get_CICIR_model_histogram(\n            phot_gain, N_serial_CIC_pix,\n            FullEmccdHistogramFitFCN::N_EM_serial_register_stages,\n            tail_range + convolution_half_width\n        );\n\n    for (int register_output_val=1; register_output_val<=tail_range + convolution_half_width;\n            ++register_output_val) {\n        double photon_exponential =  exp(-1.0* register_output_val /phot_gain);\n        //Contribution from 1 and 2 photo-electron events\n        register_output_model[register_output_val] =\n            p1_amplitude*photon_exponential;\n        register_output_model[register_output_val] +=\n            p2_amplitude*(register_output_val - 1)*photon_exponential;\n\n        //Contribution from CICIR events\n//        register_output_model[register_output_val] +=\n//                serial_CIC_amplitude*exp(  -1.0* register_output_val /serial_CIC_gain );\n        register_output_model[register_output_val] +=\n            CICIR_register_component[register_output_val];\n    }\n\n    map<int,double> RO_model =\n        convolve_histogram_with_gaussian(register_output_model, RO_sigma,\n                                         convolution_half_width);\n\n    map<int,double> biased_RO_model;\n    for (map<int,double>::const_iterator it=RO_model.begin(); it!=RO_model.end(); ++it) {\n        int output_value = it->first + bias_pedestal;\n        if (output_value>=fit_rgn_min_ && output_value <= fit_rgn_max_) {\n            biased_RO_model[output_value] = it->second;\n        }\n    }\n\n    return biased_RO_model;\n}\n\n//==================================================================================\n\n//double calculate_thresholded_SNR(const double readout_noise_in_ADU,\n//                                const double mean_photon_gain_in_ADU,\n//                                const double CIC_event_rate_per_pixel_readout,\n//                                const double light_level,\n//                                const double threshold_in_photo_electrons,\n//                                const bool output_to_screen){\n//    map<int,long> histogram_min_max;\n//    histogram_min_max[-readout_noise_in_ADU*5]=0;\n//    histogram_min_max[10000]=0;\n//\n//    FullEmccdHistogramFitFCN full_model(histogram_min_max);\n//    GainData full_pars;\n//    full_pars.bias_pedestal = 0.0;\n//    full_pars.readout_sigma = readout_noise_in_ADU;\n//    full_pars.gain = mean_photon_gain_in_ADU;\n//    full_pars.N_light_pix = 0.0;\n//    full_pars.N_serial_CIC_pix = 0.0;\n//    full_pars.N_dark_pix = 0.0;\n////                - mean_photon_gain_in_ADU*CIC_event_rate_per_pixel_readout);\n//\n//    GainData photon_hist_pars(full_pars);\n//    photon_hist_pars.N_light_pix=1.0;\n//    map<int,double> light_model = full_model.get_model_histogram(\n//        full_model.generate_pars_vec(photon_hist_pars));\n//\n//    double all_counts = gain_utils::sum_counts_in_histogram(light_model);\n//    double thresh_counts = gain_utils::sum_counts_in_histogram_above_threshold(\n//            light_model, threshold_in_photo_electrons*mean_photon_gain_in_ADU);\n//\n//    double pass_rate_for_photon_events = thresh_counts / all_counts;\n//\n//    if (output_to_screen){\n////        gain_utils::write_histogram_data_to_file(light_model, \"photons_only.txt\");\n//        cerr<<\"photons hist sum:\" << all_counts << endl;\n//        cerr<<\"Filtered photon fraction: \"<< pass_rate_for_photon_events<<endl;\n//    }\n//\n////    GainData CICIR_hist_pars(full_pars);\n////    CICIR_hist_pars.N_serial_CIC_pix=1.0;\n////    map<int,double> CICIR_model = full_model.get_model_histogram(\n////        full_model.generate_pars_vec(CICIR_hist_pars));\n////\n////    all_counts = gain_utils::sum_counts_in_histogram(CICIR_model);\n////    thresh_counts = gain_utils::sum_counts_in_histogram_above_threshold(\n////            CICIR_model, threshold_in_photo_electrons*mean_photon_gain_in_ADU);\n////\n////    double CICIR_fraction = thresh_counts / all_counts;\n////\n////    if (output_to_screen){\n////        gain_utils::write_histogram_data_to_file(CICIR_model, \"CICIR_only.txt\");\n////        cerr<<\"CICIR hist sum:\" << all_counts << endl;\n////        cerr<<\"Filtered CICIR fraction: \"<< CICIR_fraction<<endl;\n////    }\n////\n////    GainData RO_hist_pars(full_pars);\n////    RO_hist_pars.N_dark_pix=1.0;\n////    map<int,double> RO_model = full_model.get_model_histogram(\n////        full_model.generate_pars_vec(RO_hist_pars));\n////\n////    all_counts = gain_utils::sum_counts_in_histogram(RO_model);\n////    thresh_counts = gain_utils::sum_counts_in_histogram_above_threshold(\n////            RO_model, threshold_in_photo_electrons*mean_photon_gain_in_ADU);\n////\n////    double RO_fraction = thresh_counts / all_counts;\n////\n////    if (output_to_screen){\n////        gain_utils::write_histogram_data_to_file(RO_model, \"RO_only.txt\");\n////        cerr<<\"RO hist sum:\" << all_counts << endl;\n////        cerr<<\"Filtered RO fraction: \"<< RO_fraction<<endl;\n////    }\n//\n//    full_pars.N_light_pix = light_level;\n//    full_pars.N_serial_CIC_pix = CIC_event_rate_per_pixel_readout;\n//    full_pars.N_dark_pix = 1.0 - (light_level + CIC_event_rate_per_pixel_readout);\n//\n//    map<int,double> full_model_hist = full_model.get_model_histogram(\n//        full_model.generate_pars_vec(full_pars));\n//\n//    all_counts = gain_utils::sum_counts_in_histogram(full_model_hist);\n//    thresh_counts = gain_utils::sum_counts_in_histogram_above_threshold(\n//            full_model_hist, threshold_in_photo_electrons*mean_photon_gain_in_ADU);\n//\n//    double pass_rate_for_all_events = thresh_counts / all_counts;\n//    if (output_to_screen){\n//        cerr<<\"Noise hist sum:\" << all_counts << endl;\n//        cerr<<\"Filtered noise fraction: \"<< pass_rate_for_all_events <<endl;\n//    }\n//\n//    double SNR = pass_rate_for_photon_events*light_level /\n//        sqrt( pass_rate_for_all_events );\n//\n//    if (output_to_screen){\n//        cerr<<\"SNR = \" << SNR<<endl;\n//    }\n//    return SNR;\n//}\n\n//==================================================================================\n\nThresholdedSnrCalculator::ThresholdedSnrCalculator(\n    const double RO,\n    const double gain,\n    const double light_level,\n    const double CICIR_rate\n):gain_(gain), light_level_(light_level)\n{\n    if ((light_level) > 0.5) {\n        throw runtime_error(\"ThresholdedSnrCalculator() ---\"\n                            \"Light level too high\");\n    }\n\n    map<int,long> histogram_min_max;\n    histogram_min_max[-RO*5]=0;\n    histogram_min_max[10000]=0;\n\n    FullEmccdHistogramFitFCN full_model(histogram_min_max);\n    GainData full_pars;\n    full_pars.bias_pedestal = 0.0;\n    full_pars.readout_sigma = RO;\n    full_pars.gain = gain;\n    full_pars.N_light_pix = 0.0;\n    full_pars.N_serial_CIC_pix = 0.0;\n    full_pars.N_dark_pix = 0.0;\n//                - mean_photon_gain_in_ADU*CIC_event_rate_per_pixel_readout);\n\n    GainData photon_hist_pars(full_pars);\n    photon_hist_pars.N_light_pix=1.0;\n\n    photon_distribution_ = full_model.get_model_histogram(\n                               full_model.generate_pars_vec(photon_hist_pars));\n\n    full_pars.N_light_pix = light_level;\n    full_pars.N_serial_CIC_pix = CICIR_rate;\n    full_pars.N_dark_pix = 1.0 - (light_level + CICIR_rate);\n\n    full_distribution_ = full_model.get_model_histogram(\n                             full_model.generate_pars_vec(full_pars));\n\n//    gain_utils::write_histogram_data_to_file(photon_distribution_, \"photons.txt\");\n//    gain_utils::write_histogram_data_to_file(full_distribution_, \"full_dist.txt\");\n\n}\n\ndouble ThresholdedSnrCalculator::calc_SNR_at_threshold(\n    const double threshold_in_photo_electrons) const\n{\n\n    double all_counts = gain_utils::sum_counts_in_histogram(photon_distribution_);\n    double thresh_counts = gain_utils::sum_counts_in_histogram_above_threshold(\n                               photon_distribution_, threshold_in_photo_electrons*gain_);\n    double fraction_photon_events_passed = thresh_counts / all_counts;\n\n    all_counts = gain_utils::sum_counts_in_histogram(full_distribution_);\n    thresh_counts = gain_utils::sum_counts_in_histogram_above_threshold(\n                        full_distribution_, threshold_in_photo_electrons*gain_);\n\n    double fraction_of_all_events_passed = thresh_counts / all_counts;\n//    cerr<<\"Gain\"<< gain_<<endl;\n//    cerr<<\"photon sum \"<<all_counts<<endl;\n//    cerr<<\"Counted over thresh:\"<<thresh_counts<<endl;\n//    cerr<<\"photon frac\"<<pass_rate_for_photon_events<<endl;\n//    cerr<<\"Total sum\"<<all_counts<<endl;\n//    cerr<<\"Total frac\"<<pass_rate_for_all_events<<endl;\n\n\n    double SNR = fraction_photon_events_passed*light_level_ /\n                 sqrt(exp(fraction_of_all_events_passed) - 1.0);\n    return SNR;\n}\n\ndouble ThresholdedSnrCalculator::find_optimum_threshold(\n    const double search_min,\n    const double search_max,\n    const double stepsize\n) const\n{\n    double max_SNR = calc_SNR_at_threshold(search_min);\n    double best_thresh = search_min;\n    for (double t = search_min; t<=search_max; t+=stepsize) {\n        double s = calc_SNR_at_threshold(t);\n        if (s > max_SNR) {\n            best_thresh = t;\n            max_SNR = s;\n        }\n    }\n    return best_thresh;\n}\n\ndouble calculate_ideal_photon_counter_SNR(const double light_level)\n{\n    return light_level /\n           sqrt(exp(light_level) - 1.0);\n}\n\ndouble calculate_linear_mode_SNR(const double readout_noise_in_ADU,\n                                 const double mean_photon_gain_in_ADU,\n                                 const double light_level,\n                                 const double CICIR_event_rate_per_pixel_readout\n                                )\n{\n\n    ///Calculate CICIR_signal relative to a photo-electron signal:\n    double CICIR_signal =  CICIR_event_rate_per_pixel_readout /\n                           log(mean_photon_gain_in_ADU);\n    double normed_readout = readout_noise_in_ADU / mean_photon_gain_in_ADU;\n    return light_level /\n           sqrt(2.0*(light_level + CICIR_signal)  + normed_readout*normed_readout);\n}\n\n//==================================================================================\npair<int,long> get_mode(const map<int,long>& histogram_data)\n{\n    int peak_value(histogram_data.begin()->first);\n    long peak_count(histogram_data.begin()->second);\n    for (map<int,long>::const_iterator it=histogram_data.begin(); it!=histogram_data.end();\n            ++it) {\n        if (it->second > peak_count) {\n            peak_value  =it->first; peak_count = it->second;\n        }\n    }\n    pair<int,long> peak_pair(peak_value, peak_count);\n    return peak_pair;\n}\n\n\n\nfloat get_gaussian_HWHM(const map<int,long>& histogram_data)\n{\n    pair<int,long> peak = get_mode(histogram_data);\n    float best_distance_to_HM=peak.second/2.0;\n    int best_value = peak.first;\n    for (map<int,long>::const_iterator it=histogram_data.begin(); it!=histogram_data.end();\n            ++it) {\n        if (it->first < peak.first) {\n            float current_dist_to_HM = fabs(it->second - peak.second/2.0);\n            if (current_dist_to_HM < best_distance_to_HM) {\n                best_distance_to_HM=current_dist_to_HM;\n                best_value =it->first;\n            }\n        }\n    }\n//            cout <<\"Half peak value: \" <<best_value<<endl;\n//            cout <<\"HWHM \"<<fabs(best_value -peak.first)<<endl;\n    return fabs(best_value -peak.first);\n}\n\n\nmap<int, long> get_gaussian_fitting_section(const map<int,long>& histogram_data)\n{\n    map<int,long> gaussian_section;\n    pair<int,long> peak = get_mode(histogram_data);\n    long count_threshold = max((long)(peak.second*0.005), 300l);\n    for (map<int,long>::const_iterator it=histogram_data.begin(); it!=histogram_data.end();\n            ++it) {\n        if (it->first < (peak.first+10) && it->second > count_threshold) { gaussian_section[it->first]=it->second; }\n    }\n    return gaussian_section;\n}\n\n\n\nmap<int, long> get_tail_fitting_section(const map<int,long>& histogram_data,\n                                        const double g_sigma_est, const bool output_to_screen)\n{\n    pair<int,long>peak =get_mode(histogram_data);\n    long count_threshold=max((long)25,\n                             (long)floor(peak.second/6e6)); //FIXME - this may need adjusting\n    if (output_to_screen) { cout <<\"\\nTail count cutoff: \" << count_threshold<<endl; }\n    int tail_section_end_value = peak.first;\n    for (map<int,long>::const_iterator it=histogram_data.begin(); it!=histogram_data.end();\n            ++it) {\n        if (it->first > peak.first && it->second >count_threshold) {\n            tail_section_end_value= max(tail_section_end_value, it->first);\n        }\n    }\n    tail_section_end_value-=10; //jump back, otherwise may get extended by a noise spike extending the range to... a noise spike!\n    if (output_to_screen) { cout <<\"Resulting in cutoff value: \"<<tail_section_end_value<<endl; }\n    map<int,long> tail_section;\n    int curve_range = tail_section_end_value - peak.first;\n    int peak_offset = max(curve_range*0.25, g_sigma_est*8);\n    int tail_start = (peak.first + peak_offset);\n    if (output_to_screen) { cout <<\"Tail_start at: \"<<tail_start<<endl; }\n    if (tail_start >= tail_section_end_value -5) { throw runtime_error(\"Not enough data to fit tail of histogram\"); }\n    for (map<int,long>::const_iterator it=histogram_data.begin(); it!=histogram_data.end();\n            ++it) {\n        if (it->first >= tail_start && it->first <=tail_section_end_value) { tail_section[it->first] = it->second; }\n    }\n    return tail_section;\n}\n\nmap<int,long> get_serial_CIC_model_fitting_section(const map<int,long>& histogram_data,\n        const double bias_pedestal,\n        const double readout_sigma)\n{\n    int low_cutoff = bias_pedestal + 4.0 * readout_sigma;\n    int high_cutoff = bias_pedestal + 12*readout_sigma;\n    map<int, long> fitting_region;\n    for (map<int,long>::const_iterator it=histogram_data.begin(); it!=histogram_data.end();\n            ++it) {\n        if (it->first > low_cutoff && it->first <=high_cutoff) { fitting_region[it->first] = it->second; }\n    }\n    return fitting_region;\n}\n\nmap<int,long> get_full_model_fitting_section(const map<int,long>& histogram_data,\n        const double bias_pedestal,\n        const double readout_sigma)\n{\n//    pair<int,long>peak =get_mode(histogram_data);\n//    long count_threshold=max((long)50, (long)floor(peak.second/1e6));\n\n    map<int, long> tail_region = get_tail_fitting_section(histogram_data,\n                                 readout_sigma);\n    int tail_end = get_max_value_pair(tail_region).first;\n\n    int low_cutoff = bias_pedestal - 0.5 * readout_sigma;\n//    cerr<<\"low cuttoff, tail end: \" <<low_cutoff <<\" , \"<< tail_end <<endl;\n\n    map<int, long> fitting_region;\n    for (map<int,long>::const_iterator it=histogram_data.begin(); it!=histogram_data.end();\n            ++it) {\n        if (it->first > low_cutoff && it->first <=tail_end) { fitting_region[it->first] = it->second; }\n    }\n    return fitting_region;\n}\n\nmap<int, long> get_points_at_values_greater_than(const map<int,long>& histogram_data,\n        int zero_point)\n{\n    map<int, long> positive_section;\n    for (map<int,long>::const_iterator it=histogram_data.begin(); it!=histogram_data.end();\n            ++it) {\n        if ((it->first > zero_point)) { positive_section[it->first]=it->second; }\n    }\n    return positive_section;\n}\n\nmap<int, long> threshold_above_count(const map<int,long>& histogram_data,\n                                     int count_threshold)\n{\n    map<int, long> threshed;\n    for (map<int,long>::const_iterator it=histogram_data.begin(); it!=histogram_data.end();\n            ++it) {\n        if ((it->second > count_threshold)) { threshed[it->first]=it->second; }\n    }\n    return threshed;\n}\n\n\nfloat estimate_log_slope(const map<int,long>& tail_section)\n{\n    pair<int,long> tail_section_peak(get_mode(tail_section)),\n         tail_end(get_max_value_pair(tail_section));\n    return (log(tail_end.second) - log(tail_section_peak.second))/\n           (tail_end.first - tail_section_peak.first);\n}\n\n//Returns gauss_par vector: peak value (zero value), peak count, sigma (readout sigma);\nvector<double> fit_readout_gaussian(const map<int,long>& histogram_data,\n                                    const bool output_to_screen)\n{\n    pair<int,long> peak = get_mode(histogram_data);\n    if (output_to_screen) { cout <<\"Data peak count at \" <<peak.first<<\" : \"<<peak.second<<endl; }\n    map<int, long> gaussian_section = get_gaussian_fitting_section(histogram_data);\n    gaussian_section.erase(\n        0); //remove weird spike at 0 value. fixme! - track down the origin of this.\n\n    GaussianHistogramFitFCN hump_fitter(gaussian_section);\n    ROOT::Minuit2::MnUserParameters gauss_pars;\n    gauss_pars.Add(\"HistPeakValue\", peak.first, 2);\n    gauss_pars.SetLimits(\"HistPeakValue\", -100.0, 20000.0);\n    gauss_pars.Add(\"HistPeakCount\", peak.second, peak.second*0.1);\n//            gauss_pars.SetLimits(\"HistPeakCount\", peak.first*0.5, peak.first*2.0);\n    gauss_pars.SetLowerLimit(\"HistPeakCount\",5);\n    float gauss_sigma_est = get_gaussian_HWHM(histogram_data) * 2 /\n                            misc_math::gaussian_fwhm_to_sigma_ratio;\n    if (output_to_screen) { cout <<\"Sigma init est. \" << gauss_sigma_est <<endl; }\n\n    gauss_pars.Add(\"HistGaussSigma\", gauss_sigma_est, gauss_sigma_est*0.3);\n    gauss_pars.SetLowerLimit(\"HistGaussSigma\",0.1);\n\n//            gauss_pars.SetLimits(\"HistGaussSigma\",gauss_sigma_est*0.5, gauss_sigma_est*2.0);\n    ROOT::Minuit2::MnMinimize min_finder(hump_fitter, gauss_pars);\n    ROOT::Minuit2::FunctionMinimum min=min_finder();\n    if (output_to_screen) { cout <<min<<endl; }\n    vector<double> end_pars;\n    end_pars=min.UserParameters().Params();\n    return end_pars;\n}\n\n//Returns amplitude, gain\nvector<double> fit_exponential_tail(const map<int,long>& histogram_data,\n                                    const double gaussian_sigma_estimate,\n                                    const bool output_to_screen)\n{\n    if (output_to_screen) { cout <<\"Fitting tail\"<<endl; }\n    pair<int,long>peak =get_mode(histogram_data);\n    map<int,long> tail_section = get_tail_fitting_section(histogram_data,\n                                 gaussian_sigma_estimate ,output_to_screen);\n\n    ExponentialHistogramFitFCN tail_fitter(tail_section);\n    double log_slope_estimate = estimate_log_slope(tail_section);\n    if (output_to_screen) { cout <<\"Initial slope estimate: \" <<log_slope_estimate<<endl; }\n    float gain_init_est = -1.0/log_slope_estimate;\n    if (output_to_screen) { cout <<\" - gain therefore est. at \"<<gain_init_est<<endl; }\n    ROOT::Minuit2::MnUserParameters tail_par;\n//            tail_par.SetPrecision(1e-7);\n\n    double amplitude_estimate=peak.second*0.1 / exp(\n                                  -1.0*peak.first/gain_init_est);     //assumes 1/10th of all pixels contain a photon event\n    if (output_to_screen) { cout <<\"Initial amp estimate: \" <<amplitude_estimate<< endl; }\n    tail_par.Add(\"Amp\", amplitude_estimate, amplitude_estimate*0.5);\n    tail_par.SetLowerLimit(\"Amp\", 0);\n    tail_par.Add(\"Gain\", gain_init_est, gain_init_est*0.1);\n    tail_par.SetLimits(\"Gain\", 1.0,1000.0);\n    tail_par.Fix(\"Gain\"); //Gain estimate likely much more accurate than amplitude estimate, so fix this for first run\n    ROOT::Minuit2::MnMinimize amp_fitter(tail_fitter, tail_par);\n    ROOT::Minuit2::FunctionMinimum min = amp_fitter();\n    tail_par.SetValue(\"Amp\",min.UserParameters().Value(\"Amp\"));\n    tail_par.Release(\"Gain\");\n\n    ROOT::Minuit2::MnMinimize amp_gain_fitter(tail_fitter, tail_par);\n    min = amp_gain_fitter();\n    if (output_to_screen) { cout <<min<<endl; }\n    ;\n    vector<double> fitted_tail_pars = min.UserParameters().Params();\n    return fitted_tail_pars;\n}\n\nvector<double> fit_exponential_tail_fixed_gain(const map<int,long>& histogram_data,\n        const double gaussian_sigma_estimate, const double gain_estimate,\n        const bool output_to_screen)\n{\n    if (output_to_screen) { cout <<\"Fitting tail\"<<endl; }\n    pair<int,long>peak =get_mode(histogram_data);\n    map<int,long> tail_section = get_tail_fitting_section(histogram_data,\n                                 gaussian_sigma_estimate ,output_to_screen);\n\n    ExponentialHistogramFitFCN tail_fitter(tail_section);\n\n    double gain_init_est=gain_estimate;\n    double amplitude_estimate=peak.second*0.1 / exp(\n                                  -1.0*peak.first/gain_init_est);     //assumes 1/10th of all pixels contain a photon event\n    ROOT::Minuit2::MnUserParameters tail_par;\n    if (output_to_screen) { cout <<\"Initial amp estimate: \" <<amplitude_estimate<< \", est err: \"<< peak.second*0.1<< endl; }\n    tail_par.Add(\"Amp\", amplitude_estimate, peak.second*0.1);\n    tail_par.SetLowerLimit(\"Amp\", 0);\n    tail_par.Add(\"Gain\", gain_init_est, gain_init_est*0.05);\n    tail_par.SetLowerLimit(\"Gain\", 1.0);\n    tail_par.Fix(\"Gain\");\n    ROOT::Minuit2::MnMinimize amp_finder(tail_fitter, tail_par);\n    ROOT::Minuit2::FunctionMinimum min = amp_finder();\n    if (output_to_screen) { cout <<min<<endl; }\n//\n//            if (output_to_screen)cout <<\"Refitting gain only\"<<endl;\n//            tail_par.Fix(\"Amp\");\n//            ROOT::Minuit2::MnMinimize gain_min_finder(tail_fitter, tail_par, 2);\n//            min = gain_min_finder();\n//            if (output_to_screen)cout <<min<<endl;\n    vector<double> fitted_tail_pars = min.UserParameters().Params();\n    return fitted_tail_pars;\n}\n\n\n\nGainData fit_full_CCD_model(const map<int,long>& histogram_data,\n                             const GainData& approx_fit_init,\n                             const bool output_to_screen\n//        , const bool sqrt_serial_CIC_gain_mode\n                            )\n{\n    //Hardcoded initial estimates (fixme?)\n    GainData approx_fit(approx_fit_init);\n\n    approx_fit.N_serial_CIC_pix= approx_fit.actual_number_pix_events_recorded -\n                                 (approx_fit.N_dark_pix + approx_fit.N_light_pix);\n//    approx_fit.serial_CIC_gain = sqrt(approx_fit.gain);\n\n\n\n//    gain_utils::write_histogram_data_to_file(full_fitting_region, \"full_fitting_region.txt\");\n\n    ROOT::Minuit2::MnUserParameters mnpars;\n    const string key_BiasPedestal = \"BiasPedestal\";\n    const string key_NDarkPix = \"NDarkPix\";\n    const string key_ROSigma = \"ROSigma\";\n    const string key_NPhotPix = \"NPhotPix\";\n    const string key_PhotGain = \"PhotGain\";\n    const string key_NSerialCICPix = \"NSerCICPix\";\n//    const string key_SerialCICGain = \"SerCICGain\";\n\n    //NB! Ensure ordering matches definition for FullEmccdHistogramFitFCN::operator() !!!\n\n    mnpars.Add(key_BiasPedestal, approx_fit.bias_pedestal, 2);\n    mnpars.SetLimits(key_BiasPedestal, approx_fit.bias_pedestal-2,\n                     approx_fit.bias_pedestal+2);\n\n    mnpars.Add(key_NDarkPix, approx_fit.N_dark_pix, approx_fit.N_dark_pix*0.1);\n    mnpars.SetLowerLimit(key_NDarkPix,5);\n//    if (output_to_screen) cout <<\"Sigma init est. \" << gauss_sigma_est <<endl;\n\n    mnpars.Add(key_ROSigma, approx_fit.readout_sigma, approx_fit.readout_sigma*0.1);\n    mnpars.SetLimits(key_ROSigma, approx_fit.readout_sigma*0.8, approx_fit.readout_sigma*1.2);\n\n    mnpars.Add(key_NPhotPix, approx_fit.N_light_pix, approx_fit.N_light_pix*0.1);\n    mnpars.SetLowerLimit(key_NPhotPix, 0);\n\n    mnpars.Add(key_PhotGain, approx_fit.gain, approx_fit.gain*0.05);\n    mnpars.SetLimits(key_PhotGain, 1.0, 1000);\n\n    mnpars.Add(key_NSerialCICPix, approx_fit.N_serial_CIC_pix,\n               approx_fit.actual_number_pix_events_recorded*0.2);\n    mnpars.SetLowerLimit(key_NSerialCICPix, 0.0);\n\n//    mnpars.Add(key_SerialCICGain, approx_fit.serial_CIC_gain,\n//            approx_fit.serial_CIC_gain);\n//    mnpars.SetLowerLimit(key_SerialCICGain, 1.0);\n\n    //--------------------------------------------------------------------------------\n    //Fit just the serial CIC\n\n    mnpars.Fix(key_BiasPedestal);\n    mnpars.Fix(key_NDarkPix);\n    mnpars.Fix(key_ROSigma);\n    mnpars.Fix(key_NPhotPix);\n    mnpars.Fix(key_PhotGain);\n\n//    if (sqrt_serial_CIC_gain_mode){\n//        mnpars.SetValue(key_SerialCICGain, sqrt(mnpars.Value(key_PhotGain)));\n//        mnpars.Fix(key_SerialCICGain);\n//    }\n//    mnpars.Fix(key_NSerialCICPix); //Just leave this free to start:\n\n    map<int, long> serial_CIC_region =\n        get_serial_CIC_model_fitting_section(histogram_data,\n                approx_fit.bias_pedestal, approx_fit.readout_sigma);\n\n    FullEmccdHistogramFitFCN CIC_fit_fcn(serial_CIC_region);\n\n    if (output_to_screen) cout<<\"---------------------------------\\n\"\n                                  << \"Init params:\" << mnpars<<endl;\n//    gain_utils::write_histogram_data_to_file(serial_CIC_region.get_model_histogram(mnpars.Params()), \"initial_model.txt\" );\n//    ROOT::Minuit2::MnScan serial_CIC_fitter(CIC_fit_fcn, mnpars);\n//    serial_CIC_fitter.Scan(5);\n\n    ROOT::Minuit2::MnMinimize serial_CIC_fitter(CIC_fit_fcn, mnpars);\n\n    ROOT::Minuit2::FunctionMinimum min0 = serial_CIC_fitter();\n//    if (output_to_screen)cout <<min<<endl;\n\n    ROOT::Minuit2::MnUserParameters fitted_pars = min0.UserParameters();\n    if (output_to_screen) { cout<<\"Params after fit 0:\" << fitted_pars << endl; }\n\n    //--------------------------------------------------------------------------------\n    map<int, long> full_fitting_region =\n        get_full_model_fitting_section(histogram_data,\n                                       approx_fit.bias_pedestal, approx_fit.readout_sigma);\n//\n    FullEmccdHistogramFitFCN full_fit_fcn(full_fitting_region);\n\n    mnpars = fitted_pars;\n    mnpars.Release(key_BiasPedestal);\n    mnpars.Release(key_NDarkPix);\n    mnpars.Release(key_ROSigma);\n    mnpars.Release(key_NPhotPix);\n//    if (sqrt_serial_CIC_gain_mode == false){\n    mnpars.Release(key_PhotGain);\n//    }\n//    mnpars.Release(key_NSerialCICPix); //Already free\n//    mnpars.Release(key_SerialCICGain); //Already free\n    mnpars.SetError(key_NDarkPix, mnpars.Value(key_NDarkPix)*0.1);\n    mnpars.SetError(key_NPhotPix, mnpars.Value(key_NPhotPix)*0.1);\n    mnpars.SetError(key_PhotGain, mnpars.Value(key_PhotGain)*0.05);\n    mnpars.SetError(key_NSerialCICPix, mnpars.Value(key_NSerialCICPix)*0.1);\n//    mnpars.SetError(key_SerialCICGain, mnpars.Value(key_SerialCICGain)*0.1);\n\n\n    if (output_to_screen) cout<<\"---------------------------------\\n\"\n                                  << \"Init params:\" << mnpars<<endl;\n    ROOT::Minuit2::MnMinimize free_fitter(full_fit_fcn, mnpars);\n    ROOT::Minuit2::FunctionMinimum min3 = free_fitter();\n    if (output_to_screen) { cout <<min3<<endl; }\n    fitted_pars = min3.UserParameters();\n    if (output_to_screen) { cout<<\"Params after fit 3:\" << fitted_pars << endl; }\n    //--------------------------------------------------------------------------------\n    GainData fitted_info(approx_fit);\n    if (min3.IsValid()) {\n        fitted_info.bias_pedestal = fitted_pars.Value(key_BiasPedestal);\n        fitted_info.readout_sigma = fitted_pars.Value(key_ROSigma);\n        fitted_info.N_dark_pix = fitted_pars.Value(key_NDarkPix);\n        fitted_info.gain = fitted_pars.Value(key_PhotGain);\n        fitted_info.N_light_pix = fitted_pars.Value(key_NPhotPix);\n        fitted_info.N_serial_CIC_pix = fitted_pars.Value(key_NSerialCICPix);\n//        fitted_info.serial_CIC_gain = fitted_pars.Value(key_SerialCICGain);\n\n        const double total_calculated_hist_area = fitted_info.N_dark_pix +\n                fitted_info.N_serial_CIC_pix  + fitted_info.N_light_pix;\n\n        fitted_info.photon_event_freq = fitted_info.N_light_pix /\n                                        total_calculated_hist_area;\n\n        fitted_info.serial_CIC_rate =  fitted_info.N_serial_CIC_pix /\n                                       (fitted_info.N_serial_CIC_pix +\n                                        fitted_info.N_dark_pix); //NB light pixels do not show up in serial CIC rate count!\n        if (output_to_screen) {\n            cerr<<\"Calculated hist area / actual counts \" << total_calculated_hist_area\n                <<\" / \"<<fitted_info.actual_number_pix_events_recorded<<endl;\n\n            cerr<<\"Calculated N_dark pix / light pix / n_CIC_pix\"<< fitted_info.N_dark_pix\n                << \" / \"<<fitted_info.N_light_pix\n                << \" / \"<<fitted_info.N_serial_CIC_pix\n                <<endl;\n        }\n    }\n\n\n    return fitted_info;\n}\n\n\nGainData fit_CCD_histogram(const map<int,long>& histogram_bins,\n                            const bool perform_advanced_fit,\n                            const bool fixed_gain_mode, const double gain_value,\n                            const bool output_to_screen\n//        , const bool sqrt_serial_CIC_gain_mode\n                           )\n{\n    if (fixed_gain_mode &&  gain_value==0.0) { throw logic_error(\"Must supply a gain value for fitting in fixed gain mode\"); }\n    vector<double> gauss_pars = gain_utils::fit_readout_gaussian(histogram_bins);\n    vector<double> exp_pars;\n    if (fixed_gain_mode) { exp_pars = gain_utils::fit_exponential_tail_fixed_gain(histogram_bins, gauss_pars.back(), gain_value, true); }\n    else { exp_pars= gain_utils::fit_exponential_tail(histogram_bins, gauss_pars.back(), output_to_screen && !perform_advanced_fit); }\n\n    GainData approx_results;\n    approx_results.bias_pedestal = gauss_pars[0];\n    double peak_gaussian_count = gauss_pars[1];\n    approx_results.readout_sigma = gauss_pars[2];\n    approx_results.gain = exp_pars[1];\n\n    approx_results.N_dark_pix= peak_gaussian_count*approx_results.readout_sigma *sqrt(\n                                   2*M_PI); //area under a gaussian\n\n    double area_under_exponential_curve = approx_results.gain *\n                                          exp_pars.front()* exp(\n                                                  -1.0*approx_results.bias_pedestal/approx_results.gain);      //Integral from bias pedestal to infinity\n    approx_results.N_light_pix=area_under_exponential_curve;\n\n    approx_results.actual_number_pix_events_recorded = sum_counts_in_histogram(\n                histogram_bins);\n\n    approx_results.photon_event_freq =\n        approx_results.N_light_pix /\n        (approx_results.N_light_pix+approx_results.N_dark_pix);\n\n//    approx_results.N_serial_CIC_pix =\n//        approx_results.actual_number_pix_events_recorded -\n//        (approx_results.N_dark_pix+approx_results.N_light_pix);\n\n//    approx_results.serial_CIC_rate =\n//            approx_results.N_serial_CIC_pix /\n//            approx_results.actual_number_pix_events_recorded;\n\n\n//    cerr<<\"Approx fit:\" << approx_results<<endl;\n\n    if (perform_advanced_fit) {\n//    cerr<<\"Running advanced fit...\";\n        //Put in initial estimates:\n        GainData full_fit = fit_full_CCD_model(histogram_bins,\n                                                approx_results,\n                                                output_to_screen\n//                , sqrt_serial_CIC_gain_mode\n                                               );\n\n        return full_fit;\n//        cerr<<\"Done\"<<endl;\n    } else {\n\n        return approx_results;\n    }\n//    vector<double> full_pars = gauss_pars; // zero_val, peak_count, sigma,\n//\n//    full_pars.push_back(exp_pars[0]); //photon_amplitude\n//    full_pars.push_back(exp_pars[1]); //photon_gain,\n//    full_pars.push_back(0.00); //serial_CIC_amplitude;\n//    approx_results.photon_event_freq = area_under_exponential_curve / (area_under_gaussian_curve + area_under_exponential_curve);\n\n}\n\n//==================================================================================\nGainData::GainData()\n    : bias_pedestal(-1),readout_sigma(-1),gain(-1),\n      N_dark_pix(-1), N_light_pix(-1), N_serial_CIC_pix(-1),\n      photon_event_freq(-1), serial_CIC_rate(-1),\n      actual_number_pix_events_recorded(0)\n{}\n\nvoid GainData::write_to_file(const std::string& filename)\n{\n    ofstream outputfile(filename.c_str());\n    if (outputfile) {\n        outputfile<<\"#\"+get_column_headers()<<endl;\n        outputfile<<*this<<endl;\n    } else { throw runtime_error(\"Cannot write to gain_inf file\" + filename); }\n}\n\nGainData::GainData(const string& filename)\n{\n    using namespace string_utils;\n    ifstream datafile(filename.c_str());\n    vector<string> lines;\n    string line;\n    while (getline(datafile,line)) { lines.push_back(line); }\n//             for (size_t i=0; i!=lines.size();++i) cout <<lines[i]<<endl;\n    if (lines.size()!=2) { throw runtime_error(\"\\nIncorrect file format for gain info: \" + filename +\"\\n\"); }\n    vector<string> line_segments = tokenize_and_strip_spaces(lines[1], \",\");\n    if (line_segments.size()!=4) { throw runtime_error(\"\\nIncorrect file format for gain info: \" + filename +\"\\n\"); }\n    bias_pedestal=atof(line_segments[0]);\n    readout_sigma=atof(line_segments[1]);\n    gain=atof(line_segments[2]);\n    photon_event_freq=atof(line_segments[3]);\n    serial_CIC_rate=atof(line_segments[4]);\n}\n\nstd::ostream& operator<<(std::ostream& os, const GainData& g_inf)\n{\n    os<<g_inf.bias_pedestal<<\" \"<<g_inf.readout_sigma<<\" \"\n      <<g_inf.gain<<\" \"\n      <<g_inf.photon_event_freq<<\" \"\n      <<g_inf.serial_CIC_rate<<\" \"\n//            <<g_inf.serial_CIC_gain<<\" \"\n      <<g_inf.actual_number_pix_events_recorded<<\" \"\n      ;\n    return os;\n}\n\nstd::string GainData::get_column_headers()\n{\n    return \"bias_pedestal \"\"readout_sigma \"\n           \"gain \"\n           \"photon_event_frequency \"\n           \"serial_CIC_rate \"\n//            \"serial_CIC_gain \"\n           \"N_pix_recorded \"\n           ;\n}\n\n//==================================================================================\n\ntemplate<typename input_datatype>\nCcdImage<input_datatype>& normalise_CCD_with_uniform_gain(CcdImage<input_datatype>& input,\n        const GainData& det_info)\n{\n    input.pix-=det_info.bias_pedestal;\n    input.pix/=det_info.gain;\n    return input;\n}\ntemplate\nCcdImage<float>& normalise_CCD_with_uniform_gain(CcdImage<float>& input,\n        const GainData& det_info);\n\ntemplate\nCcdImage<double>& normalise_CCD_with_uniform_gain(CcdImage<double>& input,\n        const GainData& det_info);\n\n\n//double_bitmap& normalise_CCD_with_gain_map(double_bitmap& input, const GainData& det_info, const double_bitmap& gain_map){\n////    input.add_normalisation_flag();\n//    input-=det_info.bias_pedestal;\n//    input/=gain_map;\n//    return input;\n//}\n\n\n//==================================================================================\n\nCcdImage<float> threshold_bitmap(const CcdImage<float>& input,\n                                 const double threshold_level)\n{\n    CcdImage<float> thresholded(input);\n//    assert(input.key_exists(\"CCDNORMD\"));\n    for (PixelIterator i(input.pix.range()); i!=i.end; ++i) {\n        input.pix(i)>threshold_level ? thresholded.pix(i)=1.0f : thresholded.pix(i)=0.0f;\n    }\n//    thresholded.add_keyword(\"THRESHED\", string_utils::ftoa(threshold_level),\"Datacount Level at which data was thresholded\");\n    return thresholded;\n}\n\n\nCcdImage<float> create_threshold_mask(const CcdImage<float>& input,\n                                      const float threshold_count)\n{\n    CcdImage<float> mask(input);\n    mask.pix.assign(1.0);\n//     if (!input.key_exists(\"CCDNORMD\")) throw logic_error(\"create_threshold_mask takes normalised input\");\n    for (PixelIterator pix(input.pix.range()); pix!=pix.end; ++pix) {\n        if (input.pix(pix)>threshold_count) {\n            //If bright area\n            PixelRange mask_region(pix,pix);\n            mask_region = PixelRange::pad(mask_region, 4); //FIXME - hardcoded radius\n            mask_region = PixelRange::overlap(mask_region, mask.pix.range());\n            for (PixelIterator i(mask_region); i!=i.end; ++i) { mask.pix(i) = 0.0; }\n        }\n    }\n    return mask;\n}\n\n\n\nGainData analyse_histogram(const map<int, long>& full_data_histogram ,\n                            const string& output_dir)\n{\n    gain_utils::write_histogram_data_to_file(full_data_histogram,\n            output_dir+\"short_hist.dat\");\n    vector<double> hump_pars= gain_utils::fit_readout_gaussian(full_data_histogram, true);\n\n    map<int,long> gauss_data = gain_utils::get_gaussian_fitting_section(full_data_histogram);\n    gain_utils::GaussianHistogramFitFCN gauss_fitter(gauss_data);\n    map<int,double> gauss_fitted_bit = gauss_fitter.get_model_histogram(hump_pars);\n    gain_utils::write_histogram_data_to_file(gauss_data, output_dir+\"hump_data.dat\");\n    gain_utils::write_histogram_data_to_file(gauss_fitted_bit,\n            output_dir+\"hump_model_fit.dat\");\n\n    map<int,long> threshed_data = gain_utils::threshold_above_count(full_data_histogram, 100);\n\n    gain_utils::GaussianHistogramFitFCN gauss_full(threshed_data);\n    map<int,double> gauss_model = gauss_full.get_model_histogram(hump_pars);\n    gain_utils::write_histogram_data_to_file(gauss_model, output_dir+\"hump_model_full.dat\");\n\n    vector<double> tail_pars = gain_utils::fit_exponential_tail(full_data_histogram,\n                               hump_pars.back(), true);\n\n    map<int, long> fitted_tail_data = gain_utils::get_tail_fitting_section(\n                                          full_data_histogram, hump_pars.back());\n    gain_utils::ExponentialHistogramFitFCN tail_fitter(fitted_tail_data);\n    map<int, double> fitted_tail_model = tail_fitter.get_model_histogram(tail_pars);\n    gain_utils::write_histogram_data_to_file(fitted_tail_data, output_dir+\"tail_data.dat\");\n    gain_utils::write_histogram_data_to_file(fitted_tail_model,\n            output_dir+\"tail_model_fit.dat\");\n\n    map<int, long> postive_section = gain_utils::get_points_at_values_greater_than(\n                                         full_data_histogram, hump_pars.front()+hump_pars.back()); //\n    gain_utils::ExponentialHistogramFitFCN tail_model(postive_section);\n    map<int, double>full_tail_model = tail_model.get_model_histogram(tail_pars);\n    gain_utils::write_histogram_data_to_file(full_tail_model,\n            output_dir+\"tail_model_full.dat\");\n\n    gain_utils::write_histogram_data_to_file(gain_utils::sum_histograms(full_tail_model,\n            gauss_model), output_dir+\"combined_model.dat\");\n\n    map<int,long> unfitted_data;\n    for (map<int,long>::const_iterator it=full_data_histogram.begin();\n            it!=full_data_histogram.end(); ++it) {\n        int value = it->first;\n        if (gauss_data.count(value)==0 && fitted_tail_data.count(value)==0) {\n            unfitted_data[value]=it->second;\n        }\n    }\n\n    gain_utils::write_histogram_data_to_file(unfitted_data, output_dir+\"unfitted_data.dat\");\n\n    GainData results;\n    results.bias_pedestal = hump_pars.front();\n    results.readout_sigma = hump_pars.back();\n    results.gain = tail_pars.back();\n\n    double peak_gaussian_count = hump_pars[1];\n    double deduced_proportion_dark_pix = peak_gaussian_count*results.readout_sigma * sqrt(\n            2*M_PI); //area under a gaussian\n    double deduced_proportion_photon_pix = results.gain * tail_pars.front()* exp(\n            -1.0*results.bias_pedestal/results.gain);      //Amplitude by gain (amplitude corrected for origin shift to gaussian peak)\n    results.photon_event_freq = deduced_proportion_photon_pix / (deduced_proportion_dark_pix+\n                                deduced_proportion_photon_pix);\n    results.N_light_pix=deduced_proportion_photon_pix;\n    results.N_dark_pix=deduced_proportion_dark_pix;\n    return results;\n}\n\n//=====================================================================================================================\n}//end namespace\n}\n\n", "meta": {"hexsha": "4a50a621c510c40859edaf7fb37706c205b96a2a", "size": 53288, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_luckypipe/src/implementation/gain_utils.cc", "max_stars_repo_name": "timstaley/coelacanth", "max_stars_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T03:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T03:08:45.000Z", "max_issues_repo_path": "coela_luckypipe/src/implementation/gain_utils.cc", "max_issues_repo_name": "timstaley/coelacanth", "max_issues_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coela_luckypipe/src/implementation/gain_utils.cc", "max_forks_repo_name": "timstaley/coelacanth", "max_forks_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9278033794, "max_line_length": 152, "alphanum_fraction": 0.6537869689, "num_tokens": 12808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819591324418, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23532834098845676}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Thu 10 May 2018 14:43:46\n\n/**\n * @file HSSUSY_mass_eigenstates.hpp\n *\n * @brief contains class for model with routines needed to solve boundary\n *        value problem using the two_scale solver by solving EWSB\n *        and determine the pole masses and mixings\n *\n * This file was generated at Thu 10 May 2018 14:43:46 with FlexibleSUSY\n * 2.0.1 (git commit: unknown) and SARAH 4.12.2 .\n */\n\n#ifndef HSSUSY_MASS_EIGENSTATES_H\n#define HSSUSY_MASS_EIGENSTATES_H\n\n#include \"HSSUSY_info.hpp\"\n#include \"HSSUSY_physical.hpp\"\n#include \"HSSUSY_soft_parameters.hpp\"\n#include \"loop_corrections.hpp\"\n#include \"threshold_corrections.hpp\"\n#include \"error.hpp\"\n#include \"problems.hpp\"\n#include \"config.h\"\n\n#include <iosfwd>\n#include <memory>\n#include <string>\n\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\nclass HSSUSY_ewsb_solver_interface;\n/**\n * @class HSSUSY_mass_eigenstates\n * @brief model class with routines for determing masses and mixinga and EWSB\n */\nclass HSSUSY_mass_eigenstates : public HSSUSY_soft_parameters {\npublic:\n   explicit HSSUSY_mass_eigenstates(const HSSUSY_input_parameters& input_ = HSSUSY_input_parameters());\n   HSSUSY_mass_eigenstates(const HSSUSY_mass_eigenstates&) = default;\n   HSSUSY_mass_eigenstates(HSSUSY_mass_eigenstates&&) = default;\n   virtual ~HSSUSY_mass_eigenstates() = default;\n   HSSUSY_mass_eigenstates& operator=(const HSSUSY_mass_eigenstates&) = default;\n   HSSUSY_mass_eigenstates& operator=(HSSUSY_mass_eigenstates&&) = default;\n\n   /// number of EWSB equations\n   static const int number_of_ewsb_equations = 1;\n\n   void calculate_DRbar_masses();\n   void calculate_pole_masses();\n   void check_pole_masses_for_tachyons();\n   virtual void clear() override;\n   void clear_DRbar_parameters();\n   Eigen::ArrayXd get_DRbar_masses() const;\n   Eigen::ArrayXd get_DRbar_masses_and_mixings() const;\n   Eigen::ArrayXd get_extra_parameters() const;\n   void do_calculate_sm_pole_masses(bool);\n   bool do_calculate_sm_pole_masses() const;\n   void do_calculate_bsm_pole_masses(bool);\n   bool do_calculate_bsm_pole_masses() const;\n   void do_force_output(bool);\n   bool do_force_output() const;\n   void reorder_DRbar_masses();\n   void reorder_pole_masses();\n   void set_ewsb_iteration_precision(double);\n   void set_ewsb_loop_order(int);\n   void set_loop_corrections(const Loop_corrections&);\n   const Loop_corrections& get_loop_corrections() const;\n   void set_threshold_corrections(const Threshold_corrections&);\n   const Threshold_corrections& get_threshold_corrections() const;\n   void set_DRbar_masses(const Eigen::ArrayXd&);\n   void set_DRbar_masses_and_mixings(const Eigen::ArrayXd&);\n   void set_extra_parameters(const Eigen::ArrayXd&);\n   void set_pole_mass_loop_order(int);\n   int get_pole_mass_loop_order() const;\n   void set_physical(const HSSUSY_physical&);\n   double get_ewsb_iteration_precision() const;\n   double get_ewsb_loop_order() const;\n   const HSSUSY_physical& get_physical() const;\n   HSSUSY_physical& get_physical();\n   const Problems& get_problems() const;\n   Problems& get_problems();\n   void set_ewsb_solver(const std::shared_ptr<HSSUSY_ewsb_solver_interface>&);\n   int solve_ewsb_tree_level();\n   int solve_ewsb_one_loop();\n   int solve_ewsb();            ///< solve EWSB at ewsb_loop_order level\n\n   void calculate_spectrum();\n   void clear_problems();\n   std::string name() const;\n   void run_to(double scale, double eps = -1.0) override;\n   void print(std::ostream& out = std::cerr) const override;\n   void set_precision(double);\n   double get_precision() const;\n\n\n   double get_MVG() const { return MVG; }\n   double get_MHp() const { return MHp; }\n   const Eigen::Array<double,3,1>& get_MFv() const { return MFv; }\n   double get_MFv(int i) const { return MFv(i); }\n   double get_MAh() const { return MAh; }\n   double get_Mhh() const { return Mhh; }\n   const Eigen::Array<double,3,1>& get_MFd() const { return MFd; }\n   double get_MFd(int i) const { return MFd(i); }\n   const Eigen::Array<double,3,1>& get_MFu() const { return MFu; }\n   double get_MFu(int i) const { return MFu(i); }\n   const Eigen::Array<double,3,1>& get_MFe() const { return MFe; }\n   double get_MFe(int i) const { return MFe(i); }\n   double get_MVWp() const { return MVWp; }\n   double get_MVP() const { return MVP; }\n   double get_MVZ() const { return MVZ; }\n\n   \n\n   \n   const Eigen::Matrix<std::complex<double>,3,3>& get_Vd() const { return Vd; }\n   std::complex<double> get_Vd(int i, int k) const { return Vd(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Ud() const { return Ud; }\n   std::complex<double> get_Ud(int i, int k) const { return Ud(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Vu() const { return Vu; }\n   std::complex<double> get_Vu(int i, int k) const { return Vu(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Uu() const { return Uu; }\n   std::complex<double> get_Uu(int i, int k) const { return Uu(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Ve() const { return Ve; }\n   std::complex<double> get_Ve(int i, int k) const { return Ve(i,k); }\n   const Eigen::Matrix<std::complex<double>,3,3>& get_Ue() const { return Ue; }\n   std::complex<double> get_Ue(int i, int k) const { return Ue(i,k); }\n   const Eigen::Matrix<double,2,2>& get_ZZ() const { return ZZ; }\n   double get_ZZ(int i, int k) const { return ZZ(i,k); }\n\n\n\n\n   double get_mass_matrix_VG() const;\n   void calculate_MVG();\n   double get_mass_matrix_Hp() const;\n   void calculate_MHp();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fv() const;\n   void calculate_MFv();\n   double get_mass_matrix_Ah() const;\n   void calculate_MAh();\n   double get_mass_matrix_hh() const;\n   void calculate_Mhh();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fd() const;\n   void calculate_MFd();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fu() const;\n   void calculate_MFu();\n   Eigen::Matrix<double,3,3> get_mass_matrix_Fe() const;\n   void calculate_MFe();\n   double get_mass_matrix_VWp() const;\n   void calculate_MVWp();\n   Eigen::Matrix<double,2,2> get_mass_matrix_VPVZ() const;\n   void calculate_MVPVZ();\n\n   double get_ewsb_eq_hh_1() const;\n\n   double CphhHpconjHp() const;\n   double CpbargWpgZHp() const;\n   double CpbargZgWpconjHp() const;\n   double CpbargWpCgZconjHp() const;\n   double CpbargZgWpCHp() const;\n   double CpconjHpVPVWp() const;\n   double CpconjHpVWpVZ() const;\n   double CpAhAhHpconjHp() const;\n   double CphhhhHpconjHp() const;\n   double CpHpHpconjHpconjHp() const;\n   std::complex<double> CpAhconjHpVWp() const;\n   double CphhconjHpVWp() const;\n   double CpHpconjHpVP() const;\n   double CpHpconjHpVZ() const;\n   double CpHpconjHpconjVWpVWp() const;\n   std::complex<double> CpHpconjHpVZVZ() const;\n   std::complex<double> CpbarFdFuconjHpPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFdFuconjHpPL(int gI1, int gI2) const;\n   double CpbarFeFvconjHpPR(int , int ) const;\n   std::complex<double> CpbarFeFvconjHpPL(int gI1, int gI2) const;\n   double CpAhAhhh() const;\n   std::complex<double> CpbargWpgWpAh() const;\n   std::complex<double> CpbargWpCgWpCAh() const;\n   double CpAhAhAhAh() const;\n   double CpAhAhhhhh() const;\n   std::complex<double> CpAhhhVZ() const;\n   std::complex<double> CpAhHpconjVWp() const;\n   double CpAhAhconjVWpVWp() const;\n   std::complex<double> CpAhAhVZVZ() const;\n   std::complex<double> CpbarFdFdAhPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFdFdAhPL(int gI1, int gI2) const;\n   std::complex<double> CpbarFeFeAhPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFeFeAhPL(int gI1, int gI2) const;\n   std::complex<double> CpbarFuFuAhPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFuFuAhPL(int gI1, int gI2) const;\n   double Cphhhhhh() const;\n   double CphhVZVZ() const;\n   double CphhconjVWpVWp() const;\n   double CpbargWpgWphh() const;\n   double CpbargWpCgWpChh() const;\n   double CpbargZgZhh() const;\n   double Cphhhhhhhh() const;\n   double CphhHpconjVWp() const;\n   double CphhhhconjVWpVWp() const;\n   std::complex<double> CphhhhVZVZ() const;\n   std::complex<double> CpbarFdFdhhPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFdFdhhPL(int gI1, int gI2) const;\n   std::complex<double> CpbarFeFehhPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFeFehhPL(int gI1, int gI2) const;\n   std::complex<double> CpbarFuFuhhPR(int gI1, int gI2) const;\n   std::complex<double> CpbarFuFuhhPL(int gI1, int gI2) const;\n   std::complex<double> CpVGVGVG() const;\n   std::complex<double> CpbargGgGVG() const;\n   double CpbarFdFdVGPL(int gI1, int gI2) const;\n   double CpbarFdFdVGPR(int gI1, int gI2) const;\n   double CpbarFuFuVGPL(int gI1, int gI2) const;\n   double CpbarFuFuVGPR(int gI1, int gI2) const;\n   double CpVGVGVGVG1() const;\n   double CpVGVGVGVG2() const;\n   double CpVGVGVGVG3() const;\n   double CpHpconjVWpVP() const;\n   double CpbargWpgWpVP() const;\n   double CpbargWpCgWpCVP() const;\n   std::complex<double> CpHpconjHpVPVP() const;\n   double CpconjVWpVPVWp() const;\n   double CpbarFdFdVPPL(int gI1, int gI2) const;\n   double CpbarFdFdVPPR(int gI1, int gI2) const;\n   double CpbarFeFeVPPL(int gI1, int gI2) const;\n   double CpbarFeFeVPPR(int gI1, int gI2) const;\n   double CpbarFuFuVPPL(int gI1, int gI2) const;\n   double CpbarFuFuVPPR(int gI1, int gI2) const;\n   double CpconjVWpVPVPVWp3() const;\n   double CpconjVWpVPVPVWp1() const;\n   double CpconjVWpVPVPVWp2() const;\n   double CpHpconjVWpVZ() const;\n   double CpbargWpgWpVZ() const;\n   double CpbargWpCgWpCVZ() const;\n   double CpconjVWpVWpVZ() const;\n   double CpbarFdFdVZPL(int gI1, int gI2) const;\n   double CpbarFdFdVZPR(int gI1, int gI2) const;\n   double CpbarFeFeVZPL(int gI1, int gI2) const;\n   double CpbarFeFeVZPR(int gI1, int gI2) const;\n   double CpbarFuFuVZPL(int gI1, int gI2) const;\n   double CpbarFuFuVZPR(int gI1, int gI2) const;\n   double CpbarFvFvVZPL(int gI1, int gI2) const;\n   double CpbarFvFvVZPR(int , int ) const;\n   double CpconjVWpVWpVZVZ1() const;\n   double CpconjVWpVWpVZVZ2() const;\n   double CpconjVWpVWpVZVZ3() const;\n   double CpbargPgWpconjVWp() const;\n   double CpbargWpCgPconjVWp() const;\n   double CpbargWpCgZconjVWp() const;\n   double CpbargZgWpconjVWp() const;\n   std::complex<double> CpbarFdFuconjVWpPL(int gI1, int gI2) const;\n   double CpbarFdFuconjVWpPR(int , int ) const;\n   std::complex<double> CpbarFeFvconjVWpPL(int gI1, int gI2) const;\n   double CpbarFeFvconjVWpPR(int , int ) const;\n   double CpconjVWpconjVWpVWpVWp2() const;\n   double CpconjVWpconjVWpVWpVWp1() const;\n   double CpconjVWpconjVWpVWpVWp3() const;\n   std::complex<double> CpbarUFdFdAhPL(int gO2, int gI1) const;\n   std::complex<double> CpbarUFdFdAhPR(int gO1, int gI1) const;\n   std::complex<double> CpbarUFdFdhhPL(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdFdhhPR(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdFdVGPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdFdVGPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdFdVPPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdFdVPPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdFdVZPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdFdVZPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFdFuconjHpPL(int gO2, int gI2) const;\n   std::complex<double> CpbarUFdFuconjHpPR(int gO1, int gI2) const;\n   double CpbarUFdFuconjVWpPR(int , int ) const;\n   std::complex<double> CpbarUFdFuconjVWpPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFuAhPL(int gO2, int gI1) const;\n   std::complex<double> CpbarUFuFuAhPR(int gO1, int gI1) const;\n   std::complex<double> CpbarUFuFdHpPL(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuFdHpPR(int gO1, int gI2) const;\n   double CpbarUFuFdVWpPR(int , int ) const;\n   std::complex<double> CpbarUFuFdVWpPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFuhhPL(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuFuhhPR(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFuVGPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuFuVGPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFuVPPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuFuVPPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFuFuVZPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFuFuVZPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFeFeAhPL(int gO2, int gI1) const;\n   std::complex<double> CpbarUFeFeAhPR(int gO1, int gI1) const;\n   std::complex<double> CpbarUFeFehhPL(int gO2, int gI2) const;\n   std::complex<double> CpbarUFeFehhPR(int gO1, int gI2) const;\n   std::complex<double> CpbarUFeFeVPPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFeFeVPPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFeFeVZPR(int gO2, int gI2) const;\n   std::complex<double> CpbarUFeFeVZPL(int gO1, int gI2) const;\n   std::complex<double> CpbarUFeFvconjHpPL(int gO2, int gI2) const;\n   double CpbarUFeFvconjHpPR(int , int ) const;\n   double CpbarUFeFvconjVWpPR(int , int ) const;\n   double CpbarUFeFvconjVWpPL(int gO1, int gI2) const;\n   double CpbarFvFeHpPL(int , int ) const;\n   std::complex<double> CpbarFvFeHpPR(int gO1, int gI2) const;\n   double CpbarFvFeVWpPR(int , int ) const;\n   std::complex<double> CpbarFvFeVWpPL(int gO1, int gI2) const;\n   std::complex<double> CpbarFuFdHpPL(int gO2, int gI2) const;\n   std::complex<double> CpbarFuFdHpPR(int gO1, int gI2) const;\n   double CpbarFuFdVWpPR(int , int ) const;\n   std::complex<double> CpbarFuFdVWpPL(int gO1, int gI2) const;\n   std::complex<double> self_energy_Hp_1loop(double p ) const;\n   std::complex<double> self_energy_Ah_1loop(double p ) const;\n   std::complex<double> self_energy_hh_1loop(double p ) const;\n   std::complex<double> self_energy_VG_1loop(double p ) const;\n   std::complex<double> self_energy_VP_1loop(double p ) const;\n   std::complex<double> self_energy_VZ_1loop(double p ) const;\n   std::complex<double> self_energy_VWp_1loop(double p ) const;\n   std::complex<double> self_energy_Fd_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_1(double p) const;\n   std::complex<double> self_energy_Fd_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_PR(double p) const;\n   std::complex<double> self_energy_Fd_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_PL(double p) const;\n   std::complex<double> self_energy_Fu_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_1(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PR(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PL(double p) const;\n   std::complex<double> self_energy_Fe_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_1(double p) const;\n   std::complex<double> self_energy_Fe_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_PR(double p) const;\n   std::complex<double> self_energy_Fe_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_PL(double p) const;\n   std::complex<double> self_energy_Fv_1loop_1(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fv_1loop_1(double p) const;\n   std::complex<double> self_energy_Fv_1loop_PR(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fv_1loop_PR(double p) const;\n   std::complex<double> self_energy_Fv_1loop_PL(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fv_1loop_PL(double p) const;\n   std::complex<double> self_energy_Fd_1loop_1_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_1_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fd_1loop_PR_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_PR_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fd_1loop_PL_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fd_1loop_PL_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fe_1loop_1_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_1_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fe_1loop_PR_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_PR_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fe_1loop_PL_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fe_1loop_PL_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fu_1loop_1_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_1_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PR_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PR_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PL_heavy_rotated(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PL_heavy_rotated(double p) const;\n   std::complex<double> self_energy_Fu_1loop_1_heavy(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_1_heavy(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PR_heavy(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PR_heavy(double p) const;\n   std::complex<double> self_energy_Fu_1loop_PL_heavy(double p , int gO1, int gO2) const;\n   Eigen::Matrix<std::complex<double>,3,3> self_energy_Fu_1loop_PL_heavy(double p) const;\n   std::complex<double> tadpole_hh_1loop() const;\n\n\n   /// calculates the tadpoles at current loop order\n   void tadpole_equations(double[number_of_ewsb_equations]) const;\n   /// calculates the tadpoles at current loop order\n   Eigen::Matrix<double,number_of_ewsb_equations,1> tadpole_equations() const;\n   /// calculates the tadpoles divided by VEVs at current loop order\n   Eigen::Matrix<double,number_of_ewsb_equations,1> tadpole_equations_over_vevs() const;\n\n\n\n   double self_energy_hh_2loop(double p) const;\n\n\n   double self_energy_hh_3loop() const;\n\n   void calculate_MVG_pole();\n   void calculate_MFv_pole();\n   void calculate_Mhh_pole();\n   void calculate_MVP_pole();\n   void calculate_MVZ_pole();\n   void calculate_MFd_pole();\n   void calculate_MFu_pole();\n   void calculate_MFe_pole();\n   void calculate_MVWp_pole();\n   double calculate_MVWp_pole(double);\n   double calculate_MVZ_pole(double);\n\n   double calculate_MFv_DRbar(double, int) const;\n   double calculate_MFe_DRbar(double, int) const;\n   double calculate_MFu_DRbar(double, int) const;\n   double calculate_MFd_DRbar(double, int) const;\n   double calculate_MVP_DRbar(double);\n   double calculate_MVZ_DRbar(double);\n   double calculate_MVWp_DRbar(double);\n\n   double ThetaW() const;\n\n\nprivate:\n   int ewsb_loop_order{2};           ///< loop order for EWSB\n   int pole_mass_loop_order{2};      ///< loop order for pole masses\n   bool calculate_sm_pole_masses{false};  ///< switch to calculate the pole masses of the Standard Model particles\n   bool calculate_bsm_pole_masses{true};  ///< switch to calculate the pole masses of the BSM particles\n   bool force_output{false};              ///< switch to force output of pole masses\n   double precision{1.e-3};               ///< RG running precision\n   double ewsb_iteration_precision{1.e-5};///< precision goal of EWSB solution\n   HSSUSY_physical physical{}; ///< contains the pole masses and mixings\n   Problems problems{HSSUSY_info::model_name,\n                     &HSSUSY_info::particle_names_getter,\n                     &HSSUSY_info::parameter_names_getter}; ///< problems\n   Loop_corrections loop_corrections{}; ///< used pole mass corrections\n   std::shared_ptr<HSSUSY_ewsb_solver_interface> ewsb_solver{};\n   Threshold_corrections threshold_corrections{}; ///< used threshold corrections\n\n   int get_number_of_ewsb_iterations() const;\n   int get_number_of_mass_iterations() const;\n   int solve_ewsb_tree_level_custom();\n   void copy_DRbar_masses_to_pole_masses();\n\n   // Passarino-Veltman loop functions\n   double A0(double) const noexcept;\n   double B0(double, double, double) const noexcept;\n   double B1(double, double, double) const noexcept;\n   double B00(double, double, double) const noexcept;\n   double B22(double, double, double) const noexcept;\n   double H0(double, double, double) const noexcept;\n   double F0(double, double, double) const noexcept;\n   double G0(double, double, double) const noexcept;\n\n   // DR-bar masses\n   double MVG{};\n   double MHp{};\n   Eigen::Array<double,3,1> MFv{Eigen::Array<double,3,1>::Zero()};\n   double MAh{};\n   double Mhh{};\n   Eigen::Array<double,3,1> MFd{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,3,1> MFu{Eigen::Array<double,3,1>::Zero()};\n   Eigen::Array<double,3,1> MFe{Eigen::Array<double,3,1>::Zero()};\n   double MVWp{};\n   double MVP{};\n   double MVZ{};\n\n   // DR-bar mixing matrices\n   Eigen::Matrix<std::complex<double>,3,3> Vd{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> Ud{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> Vu{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> Uu{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> Ve{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<std::complex<double>,3,3> Ue{Eigen::Matrix<std::complex<double>,3,3>::Zero()};\n   Eigen::Matrix<double,2,2> ZZ{Eigen::Matrix<double,2,2>::Zero()};\n\n   // phases\n\n   // extra parameters\n\n};\n\nstd::ostream& operator<<(std::ostream&, const HSSUSY_mass_eigenstates&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "788bca5c769ffd1c0770d488213066c0265f9f51", "size": 23198, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/HSSUSY/HSSUSY_mass_eigenstates.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/HSSUSY/HSSUSY_mass_eigenstates.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/HSSUSY/HSSUSY_mass_eigenstates.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 47.9297520661, "max_line_length": 114, "alphanum_fraction": 0.7311406156, "num_tokens": 7490, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.23523315061190284}}
{"text": "/*\n dfc2.cpp\n\nCopyright (c) 2016 Terumasa Tadano\n\nThis file is distributed under the terms of the MIT license.\nPlease see the file 'LICENCE.txt' in the root directory\nor http://opensource.org/licenses/mit-license.php for information.\n*/\n\n#include <iostream>\n#include <fstream>\n#include <stdlib.h> \n#include <map>\n#include <vector>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/foreach.hpp>\n#include <boost/version.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"memory.h\"\n#include \"xml_parser.h\"\n#include \"dfc2.h\"\n#include \"constants.h\"\n#include \"mathfunctions.h\"\n\nusing namespace std;\n\nint main()\n{\n    cout << \" DFC2 -- a generator of renormalized harmonic FCs from SCPH outputs.\" << endl;\n    cout << \" XML file containing original FC2 : \";\n    cin >> original_xml;\n    cout << \" Output xml filename with anharmonic correction : \";\n    cin >> new_xml;\n    cout << \" FC2 correction file from SCPH calculation : \";\n    cin >> file_fc2_correction;\n    cout << \" Target temperature : \";\n    cin >> temp;\n\n    // Load original harmonic force constants and structure data of the supercell\n    load_fc2_xml(original_xml);\n\n    // Load anharmonic correction and structure data of the primitive lattice\n    load_delta_fc2(file_fc2_correction, temp);\n\n    // Initialize new fc2 by the original values\n    fc2_new.clear();\n    copy(fc2_orig.begin(), fc2_orig.end(), back_inserter(fc2_new));\n\n    // Add delta_fc2 to fc2_new\n    calculate_new_fc2(fc2_orig, delta_fc2, fc2_new);\n\n    write_new_xml(fc2_new, new_xml);\n\n    cout << endl << \" New XML file \" << new_xml << \" was created successfully.\" << endl;\n\n    deallocate(xr_s);\n    deallocate(kd);\n    deallocate(kd_symbol);\n    deallocate(map_p2s);\n    deallocate(map_s2p);\n    deallocate(xr_p);\n    deallocate(kd_p);\n}\n\n\nvoid load_fc2_xml(const std::string file_in)\n{\n    int i;\n    using namespace boost::property_tree;\n\n    ptree pt;\n    int atm1, atm2, xyz1, xyz2, cell_s;\n    stringstream ss1, ss2;\n    FcsClassExtent fcext_tmp;\n\n    map<string, int> dict_atomic_kind;\n\n    try {\n        read_xml(file_in, pt);\n    }\n    catch (exception &e) {\n        cout << \"Cannot open file \" + file_in << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    nat = boost::lexical_cast<unsigned int>(\n        get_value_from_xml(pt,\n                           \"Data.Structure.NumberOfAtoms\"));\n    nkd = boost::lexical_cast<unsigned int>(\n        get_value_from_xml(pt,\n                           \"Data.Structure.NumberOfElements\"));\n\n    ntran = boost::lexical_cast<unsigned int>(\n        get_value_from_xml(pt,\n                           \"Data.Symmetry.NumberOfTranslations\"));\n\n    natmin = nat / ntran;\n\n    for (i = 0; i < 3; ++i) {\n        ss1.str(\"\");\n        ss1.clear();\n        ss1 << get_value_from_xml(pt,\n                                  \"Data.Structure.LatticeVector.a\"\n                                  + boost::lexical_cast<string>(i + 1));\n        ss1 >> lavec_s[0][i] >> lavec_s[1][i] >> lavec_s[2][i];\n    }\n\n    // Parse atomic elements and coordinates\n\n    allocate(xr_s, nat, 3);\n    allocate(kd, nat);\n    allocate(kd_symbol, nkd);\n\n    i = 0;\n\n    BOOST_FOREACH(const ptree::value_type& child_, pt.get_child(\"Data.Structure.AtomicElements\")) {\n        const ptree &child = child_.second;\n        const unsigned int icount_kd = child.get<unsigned int>(\"<xmlattr>.number\");\n        dict_atomic_kind[boost::lexical_cast<string>(child_.second.data())] = icount_kd - 1;\n        kd_symbol[i++] = boost::lexical_cast<string>(child_.second.data());\n    }\n\n    unsigned int index;\n\n    BOOST_FOREACH(const ptree::value_type& child_, pt.get_child(\"Data.Structure.Position\")) {\n        const ptree &child = child_.second;\n        const string str_index = child.get<string>(\"<xmlattr>.index\");\n        const string str_element = child.get<string>(\"<xmlattr>.element\");\n\n        ss1.str(\"\");\n        ss1.clear();\n        ss1 << child.data();\n\n        index = boost::lexical_cast<unsigned int>(str_index) - 1;\n\n        if (index >= nat) {\n            cout << \"index is out of range\" << endl;\n            exit(EXIT_FAILURE);\n        }\n\n        kd[index] = dict_atomic_kind[str_element];\n        ss1 >> xr_s[index][0] >> xr_s[index][1] >> xr_s[index][2];\n    }\n\n    dict_atomic_kind.clear();\n\n    // Parse mapping information\n\n    allocate(map_p2s, natmin, ntran);\n    allocate(map_s2p, nat);\n\n    unsigned int tran, atom_p, atom_s;\n\n    BOOST_FOREACH(const ptree::value_type& child_, pt.get_child(\"Data.Symmetry.Translations\")) {\n        const ptree &child = child_.second;\n        const string str_tran = child.get<string>(\"<xmlattr>.tran\");\n        const string str_atom = child.get<string>(\"<xmlattr>.atom\");\n\n        tran = boost::lexical_cast<unsigned int>(str_tran) - 1;\n        atom_p = boost::lexical_cast<unsigned int>(str_atom) - 1;\n        atom_s = boost::lexical_cast<unsigned int>(child.data()) - 1;\n\n        if (tran >= ntran || atom_p >= natmin || atom_s >= nat) {\n            cout << \"index is out of range\" << endl;\n            exit(EXIT_FAILURE);\n        }\n\n        map_p2s[atom_p][tran] = atom_s;\n        map_s2p[atom_s].atom_num = atom_p;\n        map_s2p[atom_s].tran_num = tran;\n    }\n\n\n    BOOST_FOREACH(const ptree::value_type& child_, pt.get_child(\"Data.ForceConstants.HARMONIC\")) {\n        const ptree &child = child_.second;\n        const string str_p1 = child.get<string>(\"<xmlattr>.pair1\");\n        const string str_p2 = child.get<string>(\"<xmlattr>.pair2\");\n\n        ss1.str(\"\");\n        ss2.str(\"\");\n        ss1.clear();\n        ss2.clear();\n\n        ss1 << str_p1;\n        ss2 << str_p2;\n\n        ss1 >> atm1 >> xyz1;\n        ss2 >> atm2 >> xyz2 >> cell_s;\n\n        fcext_tmp.atm1 = atm1 - 1;\n        fcext_tmp.xyz1 = xyz1 - 1;\n        fcext_tmp.atm2 = atm2 - 1;\n        fcext_tmp.xyz2 = xyz2 - 1;\n        fcext_tmp.cell_s = cell_s - 1;\n        fcext_tmp.fcs_val = boost::lexical_cast<double>(child.data());\n\n        fc2_orig.push_back(fcext_tmp);\n    }\n}\n\n\nvoid load_delta_fc2(const std::string file_in, const double temp)\n{\n    int i;\n    ifstream ifs_in;\n    stringstream ss;\n\n    // Restart\n    ifs_in.open(file_in.c_str(), ios::in);\n    if (!ifs_in) {\n        cout << \"Could not open \" + file_in << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    // Check the consistency\n\n    string line_tmp, str_tmp;\n    vector<string> str_vec;\n\n    int sx, sy, sz;\n    int atm1, atm2, xyz1, xyz2;\n    double dfc2_tmp;\n    bool found_tag = false;\n\n    // Get lattice vectors\n    for (i = 0; i < 3; ++i) {\n        ifs_in >> lavec_p[0][i] >> lavec_p[1][i] >> lavec_p[2][i];\n    }\n    recips(lavec_p, rlavec_p);\n\n    ifs_in >> nat_p >> nkd_p;\n    ifs_in.ignore();\n    getline(ifs_in, line_tmp);\n\n    allocate(xr_p, nat_p, 3);\n    allocate(kd_p, nat_p);\n    for (i = 0; i < nat_p; ++i) {\n        ifs_in >> xr_p[i][0] >> xr_p[i][1] >> xr_p[i][2] >> kd_p[i];\n    }\n    ifs_in.ignore();\n\n    while (getline(ifs_in, line_tmp)) {\n        if (line_tmp[0] == '#') {\n            boost::split(str_vec, line_tmp, boost::is_space());\n            if (abs(boost::lexical_cast<double>(str_vec[3]) - temp) < eps) {\n                found_tag = true;\n                break;\n            }\n        }\n    }\n    if (!found_tag) {\n        cout << \"Could not find the # Temp tag for the target temperature\" << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    delta_fc2.clear();\n\n    while (getline(ifs_in, line_tmp)) {\n\n        if (line_tmp[0] == '#') break;\n\n        if (!line_tmp.empty()) {\n            stringstream ss1;\n\n            ss1 << line_tmp;\n            ss1 >> sx >> sy >> sz >> atm1 >> xyz1 >> atm2 >> xyz2 >> dfc2_tmp;\n\n            delta_fc2.push_back(DeltaFcs(sx, sy, sz, atm1, xyz1, atm2, xyz2, dfc2_tmp));\n        }\n\n    }\n\n    ifs_in.close();\n}\n\n\nvoid calculate_new_fc2(std::vector<FcsClassExtent> fc2_in,\n                       std::vector<DeltaFcs> delta_fc2,\n                       std::vector<FcsClassExtent> &fc2_out)\n{\n    int i, j, k;\n    int ix, iy, iz;\n    int icell;\n    double **xshift_s;\n\n    allocate(xshift_s, 27, 3);\n\n    for (i = 0; i < 3; ++i) xshift_s[0][i] = 0.0;\n\n    icell = 0;\n\n    for (ix = -1; ix <= 1; ++ix) {\n        for (iy = -1; iy <= 1; ++iy) {\n            for (iz = -1; iz <= 1; ++iz) {\n                if (ix == 0 && iy == 0 && iz == 0) continue;\n\n                ++icell;\n\n                xshift_s[icell][0] = static_cast<double>(ix);\n                xshift_s[icell][1] = static_cast<double>(iy);\n                xshift_s[icell][2] = static_cast<double>(iz);\n            }\n        }\n    }\n\n    double mat_convert[3][3];\n\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            mat_convert[i][j] = 0.0;\n            for (k = 0; k < 3; ++k) {\n                mat_convert[i][j] += rlavec_p[i][k] * lavec_s[k][j] / (2.0 * pi);\n            }\n\n            mat_convert[i][j] = static_cast<double>(nint(mat_convert[i][j]));\n        }\n    }\n\n    //\n    //    cout << \"lavec super:\" << endl;\n    //    for (i = 0; i < 3; ++i) {\n    //        for (j = 0; j < 3; ++j) {\n    //            cout << setw(15) << lavec_s[i][j];\n    //        }\n    //        cout << endl;\n    //    }\n    //    cout << endl;\n    //\n    //    cout << \"lavec primitive:\" << endl;\n    //    for (i = 0; i < 3; ++i) {\n    //        for (j = 0; j < 3; ++j) {\n    //            cout << setw(15) << lavec_p[i][j];\n    //        }\n    //        cout << endl;\n    //    }\n    //    cout << endl;\n    //\n    //\n    //    cout << \"Mat convert:\" << endl;\n    //    for (i = 0; i < 3; ++i) {\n    //        for (j = 0; j < 3; ++j) {\n    //            cout << setw(15) << mat_convert[i][j];\n    //        }\n    //        cout << endl;\n    //    }\n    //    cout << endl;\n\n    double vec[3];\n\n    int icount = 0;\n\n    vector<int> arr_tmp;\n    vector<FcsTrans> fc2_data;\n\n    fc2_data.clear();\n\n    for (auto it = fc2_in.cbegin(); it != fc2_in.cend(); ++it) {\n\n        arr_tmp.clear();\n\n        for (i = 0; i < 3; ++i) {\n            vec[i] = xr_s[(*it).atm2][i] + xshift_s[(*it).cell_s][i]\n                - xr_s[map_p2s[map_s2p[(*it).atm2].atom_num][0]][i];\n        }\n\n        rotvec(vec, vec, mat_convert);\n\n        arr_tmp.push_back((*it).atm1);\n        arr_tmp.push_back((*it).xyz1);\n        arr_tmp.push_back(map_s2p[(*it).atm2].atom_num);\n        arr_tmp.push_back((*it).xyz2);\n        for (i = 0; i < 3; ++i) arr_tmp.push_back(nint(vec[i]));\n\n        fc2_data.push_back(FcsTrans(arr_tmp, icount));\n        ++icount;\n    }\n\n    std::sort(fc2_data.begin(), fc2_data.end());\n\n    vector<FcsTrans>::iterator iter_found;\n    int index_tmp = 0;\n\n\n    for (auto it = delta_fc2.begin(); it != delta_fc2.end(); ++it) {\n\n        if (abs((*it).dfc2) > eps10) {\n            arr_tmp.clear();\n            arr_tmp.push_back((*it).atm1);\n            arr_tmp.push_back((*it).xyz1);\n            arr_tmp.push_back((*it).atm2);\n            arr_tmp.push_back((*it).xyz2);\n            arr_tmp.push_back((*it).sx);\n            arr_tmp.push_back((*it).sy);\n            arr_tmp.push_back((*it).sz);\n\n            iter_found = lower_bound(fc2_data.begin(), fc2_data.end(), FcsTrans(arr_tmp, index_tmp));\n\n            if (iter_found != fc2_data.end() && arr_tmp == (*iter_found).arr) {\n                fc2_new[(*iter_found).fcs_index].fcs_val += (*it).dfc2;\n            } else {\n                cout << \"Warning: The following force constant doesn't exist in the original file:\" << endl;\n                cout << setw(5) << (*it).sx << setw(5) << (*it).sy << setw(5) << (*it).sz;\n                cout << setw(5) << (*it).atm1 << setw(5) << (*it).xyz1;\n                cout << setw(5) << (*it).atm2 << setw(5) << (*it).xyz2;\n                cout << setw(15) << (*it).dfc2 << endl;\n            }\n        }\n        ++index_tmp;\n\n    }\n}\n\n\nvoid recips(double vec[3][3], double inverse[3][3])\n{\n    double det;\n    det = vec[0][0] * vec[1][1] * vec[2][2]\n        + vec[1][0] * vec[2][1] * vec[0][2]\n        + vec[2][0] * vec[0][1] * vec[1][2]\n        - vec[0][0] * vec[2][1] * vec[1][2]\n        - vec[2][0] * vec[1][1] * vec[0][2]\n        - vec[1][0] * vec[0][1] * vec[2][2];\n\n    if (abs(det) < eps12) {\n        cout << \"Lattice vector is singular\" << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    double factor = 2.0 * pi / det;\n\n    inverse[0][0] = (vec[1][1] * vec[2][2] - vec[1][2] * vec[2][1]) * factor;\n    inverse[0][1] = (vec[0][2] * vec[2][1] - vec[0][1] * vec[2][2]) * factor;\n    inverse[0][2] = (vec[0][1] * vec[1][2] - vec[0][2] * vec[1][1]) * factor;\n\n    inverse[1][0] = (vec[1][2] * vec[2][0] - vec[1][0] * vec[2][2]) * factor;\n    inverse[1][1] = (vec[0][0] * vec[2][2] - vec[0][2] * vec[2][0]) * factor;\n    inverse[1][2] = (vec[0][2] * vec[1][0] - vec[0][0] * vec[1][2]) * factor;\n\n    inverse[2][0] = (vec[1][0] * vec[2][1] - vec[1][1] * vec[2][0]) * factor;\n    inverse[2][1] = (vec[0][1] * vec[2][0] - vec[0][0] * vec[2][1]) * factor;\n    inverse[2][2] = (vec[0][0] * vec[1][1] - vec[0][1] * vec[1][0]) * factor;\n}\n\n\nvoid write_new_xml(const std::vector<FcsClassExtent> fc2_in,\n                   const std::string xml_out)\n{\n    // Write to XML file\n\n    int i, j;\n    using boost::property_tree::ptree;\n\n    ptree pt;\n    string str_pos[3], str_tmp;\n\n    str_tmp.clear();\n\n    pt.put(\"Data.OriginalFC2\", original_xml);\n    pt.put(\"Data.SCPH_file\", file_fc2_correction);\n    pt.put(\"Data.SCPH_Temperature\", double2string(temp, 5));\n    pt.put(\"Data.Structure.NumberOfAtoms\", nat);\n    pt.put(\"Data.Structure.NumberOfElements\", nkd);\n\n    for (i = 0; i < nkd; ++i) {\n        ptree &child = pt.add(\"Data.Structure.AtomicElements.element\", kd_symbol[i]);\n        child.put(\"<xmlattr>.number\", i + 1);\n    }\n\n    for (i = 0; i < 3; ++i) {\n        str_pos[i].clear();\n        for (j = 0; j < 3; ++j) {\n            str_pos[i] += \" \" + double2string(lavec_s[j][i]);\n        }\n    }\n    pt.put(\"Data.Structure.LatticeVector\", \"\");\n    pt.put(\"Data.Structure.LatticeVector.a1\", str_pos[0]);\n    pt.put(\"Data.Structure.LatticeVector.a2\", str_pos[1]);\n    pt.put(\"Data.Structure.LatticeVector.a3\", str_pos[2]);\n\n    pt.put(\"Data.Structure.Position\", \"\");\n\n    for (i = 0; i < nat; ++i) {\n        str_tmp.clear();\n        for (j = 0; j < 3; ++j) str_tmp += \" \" + double2string(xr_s[i][j]);\n        ptree &child = pt.add(\"Data.Structure.Position.pos\", str_tmp);\n        child.put(\"<xmlattr>.index\", i + 1);\n        child.put(\"<xmlattr>.element\", kd_symbol[kd[i]]);\n    }\n\n    pt.put(\"Data.Symmetry.NumberOfTranslations\", ntran);\n    for (i = 0; i < ntran; ++i) {\n        for (j = 0; j < natmin; ++j) {\n            ptree &child = pt.add(\"Data.Symmetry.Translations.map\", map_p2s[j][i] + 1);\n            child.put(\"<xmlattr>.tran\", i + 1);\n            child.put(\"<xmlattr>.atom\", j + 1);\n        }\n    }\n\n\n    pt.put(\"Data.ForceConstants\", \"\");\n    str_tmp.clear();\n\n    for (auto it = fc2_in.begin(); it != fc2_in.end(); ++it) {\n        ptree &child = pt.add(\"Data.ForceConstants.HARMONIC.FC2\", double2string((*it).fcs_val));\n\n        child.put(\"<xmlattr>.pair1\", boost::lexical_cast<std::string>((*it).atm1 + 1)\n                  + \" \" + boost::lexical_cast<std::string>((*it).xyz1 + 1));\n        child.put(\"<xmlattr>.pair2\", boost::lexical_cast<std::string>((*it).atm2 + 1)\n                  + \" \" + boost::lexical_cast<std::string>((*it).xyz2 + 1)\n                  + \" \" + boost::lexical_cast<std::string>((*it).cell_s + 1));\n    }\n\n    using namespace boost::property_tree::xml_parser;\n    const int indent = 2;\n\n#if BOOST_VERSION >= 105600\n    write_xml(xml_out, pt, std::locale(),\n              xml_writer_make_settings<ptree::key_type>(' ', indent, widen<std::string>(\"utf-8\")));\n#else\n    write_xml(xml_out, pt, std::locale(),\n        xml_writer_make_settings(' ', indent, widen<char>(\"utf-8\")));\n#endif\n}\n\n\nstring double2string(const double d, const int nprec)\n{\n    std::string rt;\n    std::stringstream ss;\n\n    ss << std::scientific << std::setprecision(nprec) << d;\n    ss >> rt;\n    return rt;\n}\n", "meta": {"hexsha": "cde44689ef4079e4a6f5a3f187f2a2bd1f6234ac", "size": 15931, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/dfc2.cpp", "max_stars_repo_name": "wichoi77/alamode", "max_stars_repo_head_hexsha": "f0b3f4cc9903a807006b8f2d183de77dd461f61c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-27T19:05:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-27T19:05:03.000Z", "max_issues_repo_path": "tools/dfc2.cpp", "max_issues_repo_name": "wichoi77/alamode", "max_issues_repo_head_hexsha": "f0b3f4cc9903a807006b8f2d183de77dd461f61c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/dfc2.cpp", "max_forks_repo_name": "wichoi77/alamode", "max_forks_repo_head_hexsha": "f0b3f4cc9903a807006b8f2d183de77dd461f61c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T14:01:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-26T14:01:15.000Z", "avg_line_length": 29.5018518519, "max_line_length": 108, "alphanum_fraction": 0.538635365, "num_tokens": 4796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.23517796644690528}}
{"text": "/**\n * WorldLocation.cpp\n *\n * Copyright 2016-2021 Heartland Software Solutions Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the license at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the LIcense is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \"times_internal.h\"\n#include \"worldlocation.h\"\n#include \"SunriseSunsetCalc.h\"\n#include \"str_printf.h\"\n\n#include <cmath>\n#include <vector>\n#include <boost/algorithm/string/predicate.hpp>\n#include \"boost_bimap.h\"\n\nextern bool insideCanadaDetail(class Canada **canada, const double latitude, const double longitude);\nextern void insideCanadaCleanup(class Canada *canada);\n\nusing namespace HSS_Time;\nusing namespace HSS_Time_Private;\n\n\n#define Pi 3.14159265358979323846264\n#define TwoPi 6.28318530717958647692529\n\nstatic __inline double DEGREE_TO_RADIAN(const double X) {\n\treturn (X / 180.0) * 3.14159265358979323846264;\n}\n\n\nstatic __inline double RADIAN_TO_DEGREE(const double X) {\n\treturn (X * 180.0) * 0.318309886183790671537768;\n}\n\n\n// this list is generated from: http://www.timeanddate.com/library/abbreviations/timezones/\n\nconstexpr int STD_TIMEZONE_ID = 0x10000;\nconstexpr int DST_TIMEZONE_ID = 0x20000;\nconstexpr int MIL_TIMEZONE_ID = 0x40000;\nconstexpr std::uint32_t MAKE_ID(int type, int id) { return type | id; }\nconstexpr bool IS_STD(int id) { return (STD_TIMEZONE_ID & id) != 0; }\nconstexpr bool IS_DST(int id) { return (DST_TIMEZONE_ID & id) != 0; }\nconstexpr bool IS_MIL(int id) { return (MIL_TIMEZONE_ID & id) != 0; }\n\n\nconst TimeZoneInfo WorldLocation::m_std_timezones[] = {\n\t{ WTimeSpan(0, 9, 30, 0),\tWTimeSpan(0),\t\t\t\"ACST\",\t\"Australian Central Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 0) },\n\t{ WTimeSpan(0, 10, 0, 0),\tWTimeSpan(0),\t\t\t\"AEST\",\t\"Australian Eastern Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 1) },\n\t{ WTimeSpan(0, -9, 0, 0),\tWTimeSpan(0),\t\t\t\"AKST\",\t\"Alaska Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 2) },\n\t{ WTimeSpan(0, -4, 0, 0),\tWTimeSpan(0),\t\t\t\"AST\",\t\"Atlantic Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 3) },\n\t{ WTimeSpan(0, 8, 0, 0),\tWTimeSpan(0),\t\t\t\"AWST\", \"Australian Western Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 4) },\n\t{ WTimeSpan(0, 1, 0, 0),\tWTimeSpan(0),\t\t\t\"CET\",\t\"Central European Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 5) },\t// 5\n\t{ WTimeSpan(0, -6, 0, 0),\tWTimeSpan(0),\t\t\t\"CST\",\t\"Central Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 6) },\n\t{ WTimeSpan(0, 7, 0, 0),\tWTimeSpan(0),\t\t\t\"CXT\",\t\"Christmas Island Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 7) },\n\t{ WTimeSpan(0, 2, 0, 0),\tWTimeSpan(0),\t\t\t\"EET\",\t\"Eastern European Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 8) },\n\t{ WTimeSpan(0, -5, 0, 0),\tWTimeSpan(0),\t\t\t\"EST\",\t\"Eastern Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 9) },\n\t{ WTimeSpan(0, -10, 0, 0),\tWTimeSpan(0),\t\t\t\"HAST\",\t\"Hawaii-Aleutian Standard Time\",\tMAKE_ID(STD_TIMEZONE_ID, 10) },\t// 10\n\t{ WTimeSpan(0, 3, 0, 0),\tWTimeSpan(0),\t\t\t\"MSK\",\t\"Moscow Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 11) },\n\t{ WTimeSpan(0, -7, 0, 0),\tWTimeSpan(0),\t\t\t\"MST\",\t\"Mountain Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 12) },\n\t{ WTimeSpan(0, 11, 30, 0),\tWTimeSpan(0),\t\t\t\"NFT\",\t\"Norfolk (Island) Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 13) },\n\t{ WTimeSpan(0, -3, -30, 0),\tWTimeSpan(0),\t\t\t\"NST\",\t\"Newfoundland Standard Time\",\t\tMAKE_ID(STD_TIMEZONE_ID, 14) },\n\t{ WTimeSpan(0, 12, 0, 0),\tWTimeSpan(0),\t\t\t\"NZST\",\t\"New Zealand Standard Time\",\t\tMAKE_ID(STD_TIMEZONE_ID, 15) },\t// 15\n\t{ WTimeSpan(0, -8, 0, 0),\tWTimeSpan(0),\t\t\t\"PST\",\t\"Pacific Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 16) },\n\t{ WTimeSpan(0, 0, 0, 0),\tWTimeSpan(0),\t\t\t\"UTC\",\t\"Universal Coordinated Time\",\t\tMAKE_ID(STD_TIMEZONE_ID, 17) },\n\t{ WTimeSpan(0, 2, 0, 0),\tWTimeSpan(0),\t\t\t\"RZ1\",\t\"Russian Zone 1\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 18) },\n\t{ WTimeSpan(0, 3, 0, 0),\tWTimeSpan(0),\t\t\t\"RZ2\",\t\"Russian Zone 2\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 19) },\n\t{ WTimeSpan(0, 4, 0, 0),\tWTimeSpan(0),\t\t\t\"RZ3\",\t\"Russian Zone 3\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 20) },\t// 20\n\t{ WTimeSpan(0, -1, 0, 0),\tWTimeSpan(0),\t\t\t\"WAT\",\t\"West African Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 21) },\n\t{ WTimeSpan(0, -2, 0, 0),\tWTimeSpan(0),\t\t\t\"AT\",\t\"Azores Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 22) },\n\t{ WTimeSpan(0, -11, 0, 0),\tWTimeSpan(0),\t\t\t\"NT\",\t\"Nome Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 23) },\n\t{ WTimeSpan(0, 5, 30, 0),\tWTimeSpan(0),\t\t\t\"IST\",\t\"Indian Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 24) },\n\t{ WTimeSpan(0, 8, 0, 0),\tWTimeSpan(0),\t\t\t\"CCT\",\t\"China Coast Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 25) },\t// 25\n\t{ WTimeSpan(0, 9, 0, 0),\tWTimeSpan(0),\t\t\t\"JST\",\t\"Japan Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 26) },\n\t{ WTimeSpan(0, 10, 0, 0),\tWTimeSpan(0),\t\t\t\"GST\",\t\"Guam Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 27) },\n\t{ WTimeSpan(0, 0, 0, 0),\tWTimeSpan(0),\t\t\tNULL,\tNULL,\t\t\t\t\t\t\t\t0 }\n};\n\n\nconst TimeZoneInfo WorldLocation::m_std_extra_timezones[] = {\n\t{ WTimeSpan(0, -5, 0, 0),\tWTimeSpan(0),\t\t\t\"ACT\",\t\"Acre Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 28) },\n\t{ WTimeSpan(0, +8, 45, 0),\tWTimeSpan(0),\t\t\t\"ACWST\",\"Guam Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 29) },\n\t{ WTimeSpan(0, +4, 30, 0),\tWTimeSpan(0),\t\t\t\"AFT\",\t\"Afghanistan Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 30) },\n\t{ WTimeSpan(0, +6, 00, 0),\tWTimeSpan(0),\t\t\t\"ALMT\",\t\"Alma-Ata Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 31) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0),\t\t\t\"AMT\",\t\"Amazon Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 32) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0),\t\t\t\"AMT\",\t\"Armenia Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 33) },\n\t{ WTimeSpan(0, +12, 00, 0),\tWTimeSpan(0),\t\t\t\"ANAT\",\t\"Anadyr Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 34) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0),\t\t\t\"AQTT\",\t\"Aqtobe Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 35) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0),\t\t\t\"ART\",\t\"Argentina Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 36) },\n\t{ WTimeSpan(0, +3, 00, 0),\tWTimeSpan(0),\t\t\t\"AST\",\t\"Arabia Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 37) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0),\t\t\t\"AZT\",\t\"Azerbaijan Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 38) },\n\t{ WTimeSpan(0, -12, 00, 0),\tWTimeSpan(0),\t\t\t\"AoE\",\t\"Anywhere on Earth\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 39) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"BNT\",\t\"Brunei Darussalam Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 40) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0),\t\t\t\"BOT\",\t\"Bolivia Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 41) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0),\t\t\t\"BRT\",\t\"Bras\\u00EDlia Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 42) },\n\t{ WTimeSpan(0, +6, 00, 0),\tWTimeSpan(0),\t\t\t\"BST\",\t\"Bangladesh Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 43) },\n\t{ WTimeSpan(0, +6, 00, 0),\tWTimeSpan(0),\t\t\t\"BTT\",\t\"Guam Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 44) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"CAST\",\t\"Casey Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 45) },\n\t{ WTimeSpan(0, +2, 00, 0),\tWTimeSpan(0),\t\t\t\"CAT\",\t\"Central Africa Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 46) },\n\t{ WTimeSpan(0, +6, 30, 0),\tWTimeSpan(0),\t\t\t\"CCT\",\t\"Cocos Islands Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 47) },\n\t{ WTimeSpan(0, +12, 45, 0),\tWTimeSpan(0),\t\t\t\"CHAST\",\"Chatham Island Standard Time\",\t\tMAKE_ID(STD_TIMEZONE_ID, 48) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"CHOT\",\t\"Choibalsan Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 49) },\n\t{ WTimeSpan(0, +10, 00, 0),\tWTimeSpan(0),\t\t\t\"CHUT\",\t\"Chuuk Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 50) },\n\t{ WTimeSpan(0, -10, 00, 0),\tWTimeSpan(0),\t\t\t\"CKT\",\t\"Cook Island Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 51) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0),\t\t\t\"CLT\",\t\"Chile Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 52) },\n\t{ WTimeSpan(0, -5, 00, 0),\tWTimeSpan(0),\t\t\t\"COT\",\t\"Colombia Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 53) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"CST\",\t\"China Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 54) },\n\t{ WTimeSpan(0, -5, 00, 0),\tWTimeSpan(0),\t\t\t\"CST\",\t\"Cuba Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 55) },\n\t{ WTimeSpan(0, -1, 00, 0),\tWTimeSpan(0),\t\t\t\"CVT\",\t\"Cape Verde Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 56) },\n\t{ WTimeSpan(0, +10, 00, 0),\tWTimeSpan(0),\t\t\t\"ChST\",\t\"Chamorro Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 57) },\n\t{ WTimeSpan(0, +7, 00, 0),\tWTimeSpan(0),\t\t\t\"DAVT\",\t\"Davis Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 58) },\n\t{ WTimeSpan(0, -6, 00, 0),\tWTimeSpan(0),\t\t\t\"EAST\",\t\"Easter Island Standard Time\",\t\tMAKE_ID(STD_TIMEZONE_ID, 59) },\n\t{ WTimeSpan(0, +3, 00, 0),\tWTimeSpan(0),\t\t\t\"EAT\",\t\"Eastern Africa Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 60) },\n\t{ WTimeSpan(0, -5, 00, 0),\tWTimeSpan(0),\t\t\t\"ECT\",\t\"Ecuador Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 61) },\n\t{ WTimeSpan(0, -1, 00, 0),\tWTimeSpan(0),\t\t\t\"EGT\",\t\"East Greenland Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 62) },\n\t{ WTimeSpan(0, +3, 00, 0),\tWTimeSpan(0),\t\t\t\"FET\",\t\"Further-Eastern European Time\",\tMAKE_ID(STD_TIMEZONE_ID, 63) },\n\t{ WTimeSpan(0, +12, 00, 0),\tWTimeSpan(0),\t\t\t\"FJT\",\t\"Fiji Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 64) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0),\t\t\t\"FKT\",\t\"Falkland Island Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 65) },\n\t{ WTimeSpan(0, -2, 00, 0),\tWTimeSpan(0),\t\t\t\"FNT\",\t\"Fernando de Noronha Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 66) },\n\t{ WTimeSpan(0, -6, 00, 0),\tWTimeSpan(0),\t\t\t\"GALT\",\t\"Galapagos Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 67) },\n\t{ WTimeSpan(0, -9, 00, 0),\tWTimeSpan(0),\t\t\t\"GAMT\",\t\"Gambier Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 68) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0),\t\t\t\"GET\",\t\"Georgia Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 69) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0),\t\t\t\"GFT\",\t\"French Guiana Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 70) },\n\t{ WTimeSpan(0, +12, 00, 0),\tWTimeSpan(0),\t\t\t\"GILT\",\t\"Gilbert Island Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 71) },\n\t{ WTimeSpan(0, +0, 00, 0),\tWTimeSpan(0),\t\t\t\"GMT\",\t\"Greenwich Mean Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 72) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0),\t\t\t\"GST\",\t\"Gulf Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 73) },\n\t{ WTimeSpan(0, -2, 00, 0),\tWTimeSpan(0),\t\t\t\"GST\",\t\"South Georgia Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 74) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0),\t\t\t\"GYT\",\t\"Guyana Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 75) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"HKT\",\t\"Hong Kong Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 76) },\n\t{ WTimeSpan(0, +7, 00, 0),\tWTimeSpan(0),\t\t\t\"HOVT\",\t\"Hovd Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 77) },\n\t{ WTimeSpan(0, +7, 00, 0),\tWTimeSpan(0),\t\t\t\"ICT\",\t\"Indochina Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 78) },\n\t{ WTimeSpan(0, +6, 00, 0),\tWTimeSpan(0),\t\t\t\"IOT\",\t\"Indian Chagos Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 79) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"IRKT\",\t\"Irkutsk Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 80) },\n\t{ WTimeSpan(0, +3, 30, 0),\tWTimeSpan(0),\t\t\t\"IRST\",\t\"Iran Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 81) },\n\t{ WTimeSpan(0, +1, 00, 0),\tWTimeSpan(0),\t\t\t\"IST\",\t\"Irish Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 82) },\n\t{ WTimeSpan(0, +2, 00, 0),\tWTimeSpan(0),\t\t\t\"IST\",\t\"Israel Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 83) },\n\t{ WTimeSpan(0, +6, 00, 0),\tWTimeSpan(0),\t\t\t\"KGT\",\t\"Kyrgyzstan Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 84) },\n\t{ WTimeSpan(0, +11, 00, 0),\tWTimeSpan(0),\t\t\t\"KOST\",\t\"Kosrae Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 85) },\n\t{ WTimeSpan(0, +7, 00, 0),\tWTimeSpan(0),\t\t\t\"KRAT\",\t\"Krasnoyarsk Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 86) },\n\t{ WTimeSpan(0, +9, 00, 0),\tWTimeSpan(0),\t\t\t\"KST\",\t\"Korea Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 87) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0),\t\t\t\"KUYT\",\t\"Kuybyshev Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 88) },\n\t{ WTimeSpan(0, +10, 30, 0),\tWTimeSpan(0),\t\t\t\"LHST\",\t\"Lord Howe Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 89) },\n\t{ WTimeSpan(0, +14, 00, 0),\tWTimeSpan(0),\t\t\t\"LINT\",\t\"Line Islands Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 90) },\n\t{ WTimeSpan(0, +10, 00, 0),\tWTimeSpan(0),\t\t\t\"MAGT\",\t\"Magadan Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 91) },\n\t{ WTimeSpan(0, -9, -30, 0),\tWTimeSpan(0),\t\t\t\"MART\",\t\"Marquesas Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 92) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0),\t\t\t\"MAWT\",\t\"Mawson Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 93) },\n\t{ WTimeSpan(0, +12, 00, 0),\tWTimeSpan(0),\t\t\t\"MHT\",\t\"Marshall Islands Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 94) },\n\t{ WTimeSpan(0, +6, 30, 0),\tWTimeSpan(0),\t\t\t\"MMT\",\t\"Myanmar Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 95) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0),\t\t\t\"MUT\",\t\"Mauritius Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 96) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0),\t\t\t\"MVT\",\t\"Maldives Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 97) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"MYT\",\t\"Malaysia Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 98) },\n\t{ WTimeSpan(0, +11, 00, 0),\tWTimeSpan(0),\t\t\t\"NCT\",\t\"New Caledonia Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 99) },\n\t{ WTimeSpan(0, +6, 00, 0),\tWTimeSpan(0),\t\t\t\"NOVT\",\t\"Novosibirsk Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 100) },\n\t{ WTimeSpan(0, +5, 45, 0),\tWTimeSpan(0),\t\t\t\"NPT\",\t\"Nepal Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 101) },\n\t{ WTimeSpan(0, +12, 00, 0),\tWTimeSpan(0),\t\t\t\"NRT\",\t\"Nauru Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 102) },\n\t{ WTimeSpan(0, -11, 00, 0),\tWTimeSpan(0),\t\t\t\"NUT\",\t\"Niue Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 103) },\n\t{ WTimeSpan(0, +6, 00, 0),\tWTimeSpan(0),\t\t\t\"OMST\",\t\"Omsk Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 104) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0),\t\t\t\"ORAT\",\t\"Oral Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 105) },\n\t{ WTimeSpan(0, -5, 00, 0),\tWTimeSpan(0),\t\t\t\"PET\",\t\"Peru Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 106) },\n\t{ WTimeSpan(0, +12, 00, 0),\tWTimeSpan(0),\t\t\t\"PETT\",\t\"Kamchatka Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 107) },\n\t{ WTimeSpan(0, +10, 00, 0),\tWTimeSpan(0),\t\t\t\"PGT\",\t\"Papua New Guinea Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 108) },\n\t{ WTimeSpan(0, +13, 00, 0),\tWTimeSpan(0),\t\t\t\"PHOT\",\t\"Phoenix Island Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 109) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"PHT\",\t\"Philippine Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 110) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0),\t\t\t\"PKT\",\t\"Pakistan Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 111) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0),\t\t\t\"PMST\",\t\"Pierre & Miquelon Standard Time\",\tMAKE_ID(STD_TIMEZONE_ID, 112) },\n\t{ WTimeSpan(0, +11, 00, 0),\tWTimeSpan(0),\t\t\t\"PONT\",\t\"Pohnpei Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 113) },\n\t{ WTimeSpan(0, -8, 00, 0),\tWTimeSpan(0),\t\t\t\"PST\",\t\"Pitcairn Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 114) },\n\t{ WTimeSpan(0, +9, 00, 0),\tWTimeSpan(0),\t\t\t\"PWT\",\t\"Palau Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 115) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0),\t\t\t\"PYT\",\t\"Paraguay Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 116) },\n\t{ WTimeSpan(0, +6, 00, 0),\tWTimeSpan(0),\t\t\t\"QYZT\",\t\"Qyzylorda Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 117) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0),\t\t\t\"RET\",\t\"Reunion Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 118) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0),\t\t\t\"ROTT\",\t\"Rothera Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 119) },\n\t{ WTimeSpan(0, +10, 00, 0),\tWTimeSpan(0),\t\t\t\"SAKT\",\t\"Sakhalin Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 120) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0),\t\t\t\"SAMT\",\t\"Samara Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 121) },\n\t{ WTimeSpan(0, +2, 00, 0),\tWTimeSpan(0),\t\t\t\"SAST\",\t\"South Africa Standard Time\",\t\tMAKE_ID(STD_TIMEZONE_ID, 122) },\n\t{ WTimeSpan(0, +11, 00, 0),\tWTimeSpan(0),\t\t\t\"SBT\",\t\"Solomon Islands Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 123) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0),\t\t\t\"SCT\",\t\"Seychelles Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 124) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"SGT\",\t\"Singapore Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 125) },\n\t{ WTimeSpan(0, +11, 00, 0),\tWTimeSpan(0),\t\t\t\"SRET\",\t\"Srednekolymsk Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 126) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0),\t\t\t\"SRT\",\t\"Suriname Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 127) },\n\t{ WTimeSpan(0, -11, 00, 0),\tWTimeSpan(0),\t\t\t\"SST\",\t\"Samoa Standard Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 128) },\n\t{ WTimeSpan(0, +3, 00, 0),\tWTimeSpan(0),\t\t\t\"SYOT\",\t\"Syowa Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 129) },\n\t{ WTimeSpan(0, -10, 00, 0),\tWTimeSpan(0),\t\t\t\"TAHT\",\t\"Tahiti Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 130) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0),\t\t\t\"TFT\",\t\"French Southern and Antarctic Time\",MAKE_ID(STD_TIMEZONE_ID, 131) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0),\t\t\t\"TJT\",\t\"Tajikistan Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 132) },\n\t{ WTimeSpan(0, +13, 00, 0),\tWTimeSpan(0),\t\t\t\"TKT\",\t\"Tokelau Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 133) },\n\t{ WTimeSpan(0, +9, 00, 0),\tWTimeSpan(0),\t\t\t\"TLT\",\t\"East Timor Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 134) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0),\t\t\t\"TMT\",\t\"Turkmenistan Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 135) },\n\t{ WTimeSpan(0, +13, 00, 0),\tWTimeSpan(0),\t\t\t\"TOT\",\t\"Tonga Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 136) },\n\t{ WTimeSpan(0, +12, 00, 0),\tWTimeSpan(0),\t\t\t\"TVT\",\t\"Tuvalu Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 137) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"ULAT\",\t\"Ulaanbaatar Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 138) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0),\t\t\t\"UYT\",\t\"Uruguay Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 139) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0),\t\t\t\"UZT\",\t\"Uzbekistan Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 140) },\n\t{ WTimeSpan(0, -4, -30, 0),\tWTimeSpan(0),\t\t\t\"VET\",\t\"Venezuelan Standard Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 141) },\n\t{ WTimeSpan(0, +10, 00, 0),\tWTimeSpan(0),\t\t\t\"VLAT\",\t\"Vladivostok Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 142) },\n\t{ WTimeSpan(0, +6, 00, 0),\tWTimeSpan(0),\t\t\t\"VOST\",\t\"Vostok Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 143) },\n\t{ WTimeSpan(0, +11, 00, 0),\tWTimeSpan(0),\t\t\t\"VUT\",\t\"Vanuatu Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 144) },\n\t{ WTimeSpan(0, +12, 00, 0),\tWTimeSpan(0),\t\t\t\"WAKT\",\t\"Wake Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 145) },\n\t{ WTimeSpan(0, +0, 00, 0),\tWTimeSpan(0),\t\t\t\"WET\",\t\"Western European Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 146) },\n\t{ WTimeSpan(0, +12, 00, 0),\tWTimeSpan(0),\t\t\t\"WFT\",\t\"Wallis and Futuna Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 147) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0),\t\t\t\"WGT\",\t\"West Greenland Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 148) },\n\t{ WTimeSpan(0, +7, 00, 0),\tWTimeSpan(0),\t\t\t\"WIB\",\t\"Western Indonesian Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 149) },\n\t{ WTimeSpan(0, +9, 00, 0),\tWTimeSpan(0),\t\t\t\"WIT\",\t\"Eastern Indonesian Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 150) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0),\t\t\t\"WITA\",\t\"Central Indonesian Time\",\t\t\tMAKE_ID(STD_TIMEZONE_ID, 151) },\n\t{ WTimeSpan(0, +13, 00, 0),\tWTimeSpan(0),\t\t\t\"WST\",\t\"West Samoa Time\",\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 152) },\n\t{ WTimeSpan(0, +0, 00, 0),\tWTimeSpan(0),\t\t\t\"WT\",\t\"Western Sahara Standard Time\",\t\tMAKE_ID(STD_TIMEZONE_ID, 153) },\n\t{ WTimeSpan(0, +9, 00, 0),\tWTimeSpan(0),\t\t\t\"YAKT\",\t\"Yakutsk Time\",\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 154) },\n\t{ WTimeSpan(0, +10, 00, 0),\tWTimeSpan(0),\t\t\t\"YAPT\",\t\"Yap Time\",\t\t\t\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 155) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0),\t\t\t\"YEKT\",\t\"Yekaterinburg Time\",\t\t\t\tMAKE_ID(STD_TIMEZONE_ID, 156) },\n\t{ WTimeSpan(0, 0, 0, 0),\tWTimeSpan(0),\t\t\tNULL,\tNULL,\t\t\t\t\t\t\t\t0 }\n};\n\n\nconst ::TimeZoneInfo WorldLocation::m_dst_timezones[] = {\n\t{ WTimeSpan(0, 9, 30, 0),\tWTimeSpan(0, 1, 0, 0),\t\"ACDT\",\t\"Australian Central Daylight Time\", MAKE_ID(DST_TIMEZONE_ID, 0) },\n\t{ WTimeSpan(0, -4, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"ADT\",\t\"Atlantic Daylight Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 1) },\n\t{ WTimeSpan(0, 10, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"AEDT\",\t\"Australian Eastern Daylight Time\", MAKE_ID(DST_TIMEZONE_ID, 2) },\n\t{ WTimeSpan(0, -9, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"AKDT\",\t\"Alaska Daylight Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 3) },\n\t{ WTimeSpan(0, 8, 0, 0),\tWTimeSpan(0, 1, 0, 0), \t\"AWDT\", \"Australian Western Daylight Time\", MAKE_ID(DST_TIMEZONE_ID, 4) },\n\t{ WTimeSpan(0, 0, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"BST\",\t\"British Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 5) },\t// 5\n\t{ WTimeSpan(0, -6, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"CDT\",\t\"Central Daylight Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 6) },\n\t{ WTimeSpan(0, 1, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"CEDT\",\t\"Central European Daylight Time\",\tMAKE_ID(DST_TIMEZONE_ID, 7) },\n\t{ WTimeSpan(0, -5, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"EDT\",\t\"Eastern Daylight Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 8) },\n\t{ WTimeSpan(0, 2, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"EEDT\",\t\"Eastern European Daylight Time\",\tMAKE_ID(DST_TIMEZONE_ID, 9) },\n\t{ WTimeSpan(0, -10, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"HADT\",\t\"Hawaii-Aleutian Daylight Time\",\tMAKE_ID(DST_TIMEZONE_ID, 10) },\t// 10\n\t{ WTimeSpan(0, 0, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"IST\",\t\"Irish Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 11) },\n\t{ WTimeSpan(0, -7, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"MDT\",\t\"Mountain Daylight Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 12) },\n\t{ WTimeSpan(0, 3, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"MSD\",\t\"Moscow Daylight Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 13) },\n\t{ WTimeSpan(0, -3, -30, 0),\tWTimeSpan(0, 1, 0, 0),\t\"NDT\",\t\"Newfoundland Daylight Time\",\t\tMAKE_ID(DST_TIMEZONE_ID, 14) },\n\t{ WTimeSpan(0, 12, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"NZDT\",\t\"New Zealand Daylight Time\",\t\tMAKE_ID(DST_TIMEZONE_ID, 15) },\t// 15\n\t{ WTimeSpan(0, -8, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"PDT\",\t\"Pacific Daylight Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 16) },\n\t{ WTimeSpan(0, 0, 0, 0),\tWTimeSpan(0, 1, 0, 0),\t\"WEDT\",\t\"Western European Daylight Time\",\tMAKE_ID(DST_TIMEZONE_ID, 17) },\n\t{ WTimeSpan(0, 0, 0, 0),\tWTimeSpan(0),\t\t\tNULL,\tNULL,\t\t\t\t\t\t\t\t0 }\n};\n\n\nconst ::TimeZoneInfo WorldLocation::m_dst_extra_timezones[] = {\n\t{ WTimeSpan(0, +3, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"ADT\",\t\"Arabia Daylight Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 18) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"AMST\",\t\"Amazon Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 19) },\n\t{ WTimeSpan(0, -1, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"AZOST\",\"Azores Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 20) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"AZST\",\t\"Azerbaijan Summer Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 21) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"BRST\",\t\"Bras\\u00EDlia Summer Time \",\t\tMAKE_ID(DST_TIMEZONE_ID, 22) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"CDT\",\t\"Cuba Daylight Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 23) },\n\t{ WTimeSpan(0, +12, 45, 0),\tWTimeSpan(0, 1, 0, 0),\t\"CHADT\",\"Chatham Island Daylight Time\",\t\tMAKE_ID(DST_TIMEZONE_ID, 24) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"CLST\",\t\"Chile Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 25) },\n\t{ WTimeSpan(0, -6, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"EASST\",\"Easter Island Summer Time\",\t\tMAKE_ID(DST_TIMEZONE_ID, 26) },\n\t{ WTimeSpan(0, -1, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"EGST\",\t\"Eastern Greenland Summer Time\",\tMAKE_ID(DST_TIMEZONE_ID, 27) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"FKST\",\t\"Falkland Islands Summer Time\",\t\tMAKE_ID(DST_TIMEZONE_ID, 28) },\n\t{ WTimeSpan(0, +2, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"IDT\",\t\"Israel Daylight Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 29) },\n\t{ WTimeSpan(0, +3, 30, 0),\tWTimeSpan(0, 1, 0, 0),\t\"IRDT\",\t\"Iran Daylight Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 30) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"IRKST\",\"Irkutsk Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 31) },\n\t{ WTimeSpan(0, +7, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"KRAST\",\"Krasnoyarsk Summer Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 32) },\n\t{ WTimeSpan(0, +10, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"LHDT\",\t\"Lord Howe Daylight Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 33) },\n\t{ WTimeSpan(0, +11, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"MAGST\",\"Magadan Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 34) },\n\t{ WTimeSpan(0, +6, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"NOVST\",\"Novosibirsk Summer Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 35) },\n\t{ WTimeSpan(0, +8, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"OMSST\",\"Omsk Summer Time\",\t\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 36) },\n\t{ WTimeSpan(0, +13, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"PETST\",\"Kamchatka Summer Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 37) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"PMDT\",\t\"Pierre & Miquelon Daylight Time\",\tMAKE_ID(DST_TIMEZONE_ID, 38) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"UYST\",\t\"Uruguay Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 39) },\n\t{ WTimeSpan(0, +10, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"VLAST\",\"Vladivostok Summer Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 40) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"WARST\",\"Western Argentine Summer Time\",\tMAKE_ID(DST_TIMEZONE_ID, 41) },\n\t{ WTimeSpan(0, +1, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"WAST\",\t\"West Africa Summer Time\",\t\t\tMAKE_ID(DST_TIMEZONE_ID, 42) },\n\t{ WTimeSpan(0, -3, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"WGST\",\t\"Western Greenland Summer Time\",\tMAKE_ID(DST_TIMEZONE_ID, 43) },\n\t{ WTimeSpan(0, 0, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"WST\",\t\"Western Sahara Summer Time\",\t\tMAKE_ID(DST_TIMEZONE_ID, 44) },\n\t{ WTimeSpan(0, +9, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"YAKST\",\"Yakutsk Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 45) },\n\t{ WTimeSpan(0, +5, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"YEKST\",\"Yekaterinburg Summer Time\",\t\tMAKE_ID(DST_TIMEZONE_ID, 46) },\n\t{ WTimeSpan(0, +12, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"FJST\",\t\"Fiji Summer Time\",\t\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 47) },\n\t{ WTimeSpan(0, -4, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"PYST\",\t\"Paraguay Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 48) },\n\t{ WTimeSpan(0, +4, 00, 0),\tWTimeSpan(0, 1, 0, 0),\t\"AMST\",\t\"Armenia Summer Time\",\t\t\t\tMAKE_ID(DST_TIMEZONE_ID, 49) },\n\t{ WTimeSpan(0, 0, 0, 0),\tWTimeSpan(0),\t\t\tNULL,\tNULL,\t\t\t\t\t\t\t\t0 }\n};\n\n\nconst ::TimeZoneInfo WorldLocation::m_mil_timezones[] = {\n\t{ WTimeSpan(0, 0, 0, 0),\tWTimeSpan(0),\t\t\"Z\",\t\"Zulu Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 0) },\n\t{ WTimeSpan(0, 1, 0, 0),\tWTimeSpan(0),\t\t\"A\",\t\"Alpha Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 1) },\n\t{ WTimeSpan(0, 2, 0, 0),\tWTimeSpan(0),\t\t\"B\",\t\"Bravo Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 2) },\n\t{ WTimeSpan(0, 3, 0, 0),\tWTimeSpan(0),\t\t\"C\",\t\"Charlie Time Zone\",\tMAKE_ID(MIL_TIMEZONE_ID, 3) },\n\t{ WTimeSpan(0, 4, 0, 0),\tWTimeSpan(0),\t\t\"D\",\t\"Delta Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 4) },\n\t{ WTimeSpan(0, 5, 0, 0),\tWTimeSpan(0),\t\t\"E\",\t\"Echo Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 5) },\t// 5\n\t{ WTimeSpan(0, 6, 0, 0),\tWTimeSpan(0),\t\t\"F\",\t\"Foxtrot Time Zone\",\tMAKE_ID(MIL_TIMEZONE_ID, 6) },\n\t{ WTimeSpan(0, 7, 0, 0),\tWTimeSpan(0),\t\t\"G\",\t\"Golf Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 7) },\n\t{ WTimeSpan(0, 8, 0, 0),\tWTimeSpan(0),\t\t\"H\",\t\"Hotel Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 8) },\n\t{ WTimeSpan(0, 9, 0, 0),\tWTimeSpan(0),\t\t\"I\",\t\"India Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 9) },\n\t{ WTimeSpan(0, 10, 0, 0),\tWTimeSpan(0),\t\t\"K\",\t\"Kilo Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 10) },\t// 10\n\t{ WTimeSpan(0, 11, 0, 0),\tWTimeSpan(0),\t\t\"L\",\t\"Lima Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 11) },\n\t{ WTimeSpan(0, 12, 0, 0),\tWTimeSpan(0),\t\t\"M\",\t\"Mike Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 12) },\n\t{ WTimeSpan(0, -1, 0, 0),\tWTimeSpan(0),\t\t\"N\",\t\"November Time Zone\",\tMAKE_ID(MIL_TIMEZONE_ID, 13) },\n\t{ WTimeSpan(0, -2, 0, 0),\tWTimeSpan(0),\t\t\"O\",\t\"Oscar Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 14) },\n\t{ WTimeSpan(0, -3, 0, 0),\tWTimeSpan(0),\t\t\"P\",\t\"Papa Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 15) },\t// 15\n\t{ WTimeSpan(0, -4, 0, 0),\tWTimeSpan(0),\t\t\"Q\",\t\"Quebec Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 16) },\n\t{ WTimeSpan(0, -5, 0, 0),\tWTimeSpan(0),\t\t\"R\",\t\"Romeo Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 17) },\n\t{ WTimeSpan(0, -6, 0, 0),\tWTimeSpan(0),\t\t\"S\",\t\"Sierra Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 18) },\n\t{ WTimeSpan(0, -7, 0, 0),\tWTimeSpan(0),\t\t\"T\",\t\"Tango Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 19) },\n\t{ WTimeSpan(0, -8, 0, 0),\tWTimeSpan(0),\t\t\"U\",\t\"Uniform Time Zone\",\tMAKE_ID(MIL_TIMEZONE_ID, 20) }, // 20\n\t{ WTimeSpan(0, -9, 0, 0),\tWTimeSpan(0),\t\t\"V\",\t\"Vector Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 21) },\n\t{ WTimeSpan(0, -10, 0, 0),\tWTimeSpan(0),\t\t\"W\",\t\"Whiskey Time Zone\",\tMAKE_ID(MIL_TIMEZONE_ID, 22) },\n\t{ WTimeSpan(0, -11, 0, 0),\tWTimeSpan(0),\t\t\"X\",\t\"X-ray Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 23) },\n\t{ WTimeSpan(0, -12, 0, 0),\tWTimeSpan(0),\t\t\"Y\",\t\"Yankee Time Zone\",\t\tMAKE_ID(MIL_TIMEZONE_ID, 24) },\n\t{ WTimeSpan(0),\t\t\t\tWTimeSpan(0),\t\tNULL,\tNULL,\t\t\t\t\t0 }\n};\n\n\nstruct WindowsTimezoneData\n{\n\tconst std::string WindowsName;\n\tconst std::uint32_t HssId;\n};\n\nstruct RegionZone\n{\n\tconst std::string Name;\n\tconst std::uint32_t HssId;\n};\n\n//https://raw.githubusercontent.com/unicode-org/cldr/master/common/supplemental/windowsZones.xml\nconst std::vector<WindowsTimezoneData> WindowsMap =\n{\n\t{ \"Dateline Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 12) },\n\t{ \"UTC-11\", MAKE_ID(MIL_TIMEZONE_ID, 23) },\n\t{ \"Aleutian Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 10) },\n\t{ \"Hawaiian Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 10) },\n\t{ \"Marquesas Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 92) },\n\t{ \"Alaskan Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 2) },\n\t{ \"UTC-09\", MAKE_ID(MIL_TIMEZONE_ID, 21) },\n\t{ \"Pacific Standard Time (Mexico)\", MAKE_ID(STD_TIMEZONE_ID, 92) },\n\t{ \"UTC-08\", MAKE_ID(MIL_TIMEZONE_ID, 20) },\n\t{ \"Pacific Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 16) },\n\t{ \"US Mountain Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 12) },\n\t{ \"Mountain Standard Time (Mexico)\", MAKE_ID(STD_TIMEZONE_ID, 12) },\n\t{ \"Mountain Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 12) },\n\t{ \"Central America Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 6) },\n\t{ \"Central Standard Time (Mexico)\", MAKE_ID(STD_TIMEZONE_ID, 6) },\n\t{ \"Central Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 6) },\n\t{ \"Canada Central Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 6) },\n\t{ \"Easter Island Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 59) },\n\t{ \"SA Pacific Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 53) },\n\t{ \"US Eastern Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 9) },\n\t{ \"Eastern Standard Time (Mexico)\", MAKE_ID(STD_TIMEZONE_ID, 9) },\n\t{ \"Eastern Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 9) },\n\t{ \"Haiti Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 17) },\n\t{ \"Cuba Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 55) },\n\t{ \"Turks And Caicos Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 17) },\n\t{ \"Paraguay Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 116) },\n\t{ \"Atlantic Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 3) },\n\t{ \"Venezuela Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 141) },\n\t{ \"Central Brazilian Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 16) },\n\t{ \"SA Western Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 75) },\n\t{ \"Pacific SA Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 52) },\n\t{ \"Newfoundland Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 14) },\n\t{ \"Tocantins Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 15) },\n\t{ \"E. South America Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 42) },\n\t{ \"SA Eastern Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 119) },\n\t{ \"Argentina Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 36) },\n\t{ \"Greenland Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 148) },\n\t{ \"Montevideo Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 15) },\n\t{ \"Magallanes Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 15) },\n\t{ \"Saint Pierre Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 112) },\n\t{ \"Bahia Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 15) },\n\t{ \"UTC-02\", MAKE_ID(MIL_TIMEZONE_ID, 14) },\n\t{ \"Azores Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 14) },\n\t{ \"Cape Verde Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 56) },\n\t{ \"UTC\", MAKE_ID(STD_TIMEZONE_ID, 17) },\n\t{ \"GMT Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 72) },\n\t{ \"Greenwich Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 72) },\n\t{ \"Sao Tome Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 17) },\n\t{ \"Morocco Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 1) },\n\t{ \"W. Europe Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 5) },\n\t{ \"Central Europe Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 5) },\n\t{ \"Central European Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 5) },\n\t{ \"Romance Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 1) },\n\t{ \"W. Central Africa Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 1) },\n\t{ \"Jordan Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 2) },\n\t{ \"GTB Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 8) },\n\t{ \"E. Europe Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 8) },\n\t{ \"Middle East Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 2) },\n\t{ \"Egypt Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 46) },\n\t{ \"Syria Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 2) },\n\t{ \"West Bank Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 2) },\n\t{ \"South Africa Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 122) },\n\t{ \"FLE Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 8) },\n\t{ \"Israel Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 83) },\n\t{ \"Kaliningrad Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 18) },\n\t{ \"Sudan Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 46) },\n\t{ \"Libya Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 46) },\n\t{ \"Namibia Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 46) },\n\t{ \"Arabic Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 37) },\n\t{ \"Arab Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 37) },\n\t{ \"Turkey Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 63) },\n\t{ \"Belarus Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 63) },\n\t{ \"Russian Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 11) },\n\t{ \"E. Africa Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 60) },\n\t{ \"Iran Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 81) },\n\t{ \"Arabian Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 4) },\n\t{ \"Astrakhan Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 20) },\n\t{ \"Russia Time Zone 3\", MAKE_ID(STD_TIMEZONE_ID, 20) },\n\t{ \"Azerbaijan Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 38) },\n\t{ \"Mauritius Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 96) },\n\t{ \"Saratov Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 20) },\n\t{ \"Georgian Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 69) },\n\t{ \"Volgograd Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 20) },\n\t{ \"Caucasus Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 4) },\n\t{ \"Afghanistan Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 30) },\n\t{ \"West Asia Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 5) },\n\t{ \"Ekaterinburg Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 156) },\n\t{ \"Pakistan Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 111) },\n\t{ \"Qyzylorda Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 5) },\n\t{ \"India Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 24) },\n\t{ \"Sri Lanka Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 24) },\n\t{ \"Nepal Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 101) },\n\t{ \"Central Asia Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 6) },\n\t{ \"Bangladesh Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 43) },\n\t{ \"Omsk Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 104) },\n\t{ \"Myanmar Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 95) },\n\t{ \"SE Asia Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 7) },\n\t{ \"Altai Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 7) },\n\t{ \"W. Mongolia Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 77) },\n\t{ \"North Asia Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 86) },\n\t{ \"N. Central Asia Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 7) },\n\t{ \"Tomsk Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 7) },\n\t{ \"China Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 54) },\n\t{ \"North Asia East Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 80) },\n\t{ \"Singapore Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 125) },\n\t{ \"W. Australia Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 4) },\n\t{ \"Taipei Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 8) },\n\t{ \"Ulaanbaatar Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 138) },\n\t{ \"Aus Central W. Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 29) },\n\t{ \"Transbaikal Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 9) },\n\t{ \"Tokyo Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 26) },\n\t{ \"North Korea Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 87) },\n\t{ \"Korea Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 87) },\n\t{ \"Yakutsk Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 154) },\n\t{ \"Cen. Australia Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 0) },\n\t{ \"AUS Central Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 0) },\n\t{ \"E. Australia Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 1) },\n\t{ \"AUS Eastern Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 1) },\n\t{ \"West Pacific Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 27) },\n\t{ \"Tasmania Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 1) },\n\t{ \"Vladivostok Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 142) },\n\t{ \"Lord Howe Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 89) },\n\t{ \"Bougainville Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 123) },\n\t{ \"Russia Time Zone 10\", MAKE_ID(STD_TIMEZONE_ID, 126) },\n\t{ \"Magadan Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 11) },\n\t{ \"Norfolk Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 11) },\n\t{ \"Sakhalin Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 11) },\n\t{ \"Central Pacific Standard Time\", MAKE_ID(MIL_TIMEZONE_ID, 11) },\n\t{ \"Russia Time Zone 11\", MAKE_ID(MIL_TIMEZONE_ID, 11) },\n\t{ \"New Zealand Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 15) },\n\t{ \"UTC+12\", MAKE_ID(MIL_TIMEZONE_ID, 12) },\n\t{ \"Fiji Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 64) },\n\t{ \"Chatham Islands Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 48) },\n\t{ \"UTC+13\", MAKE_ID(STD_TIMEZONE_ID, 109) },\n\t{ \"Tonga Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 136) },\n\t{ \"Samoa Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 152) },\n\t{ \"Line Islands Standard Time\", MAKE_ID(STD_TIMEZONE_ID, 90) }\n};\n\n\n//https://data.iana.org/time-zones/releases/\nconst std::vector<RegionZone> RegionMap =\n{\n#include \"RegionMap.inl\"\n};\n\n\n\nboost::bimap<std::uint32_t, std::uint32_t> daylightStandardMap =\nmakeBimap<std::uint32_t, std::uint32_t>({\n\t{ MAKE_ID(STD_TIMEZONE_ID, 0), MAKE_ID(DST_TIMEZONE_ID, 0) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 3), MAKE_ID(DST_TIMEZONE_ID, 1) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 1), MAKE_ID(DST_TIMEZONE_ID, 2) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 2), MAKE_ID(DST_TIMEZONE_ID, 3) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 4), MAKE_ID(DST_TIMEZONE_ID, 4) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 6), MAKE_ID(DST_TIMEZONE_ID, 6) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 5), MAKE_ID(DST_TIMEZONE_ID, 7) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 9), MAKE_ID(DST_TIMEZONE_ID, 8) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 8), MAKE_ID(DST_TIMEZONE_ID, 9) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 10), MAKE_ID(DST_TIMEZONE_ID, 10) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 12), MAKE_ID(DST_TIMEZONE_ID, 12) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 11), MAKE_ID(DST_TIMEZONE_ID, 13) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 14), MAKE_ID(DST_TIMEZONE_ID, 14) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 15), MAKE_ID(DST_TIMEZONE_ID, 15) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 16), MAKE_ID(DST_TIMEZONE_ID, 16) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 146), MAKE_ID(DST_TIMEZONE_ID, 17) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 37), MAKE_ID(DST_TIMEZONE_ID, 18) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 32), MAKE_ID(DST_TIMEZONE_ID, 19) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 22), MAKE_ID(DST_TIMEZONE_ID, 20) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 38), MAKE_ID(DST_TIMEZONE_ID, 21) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 42), MAKE_ID(DST_TIMEZONE_ID, 22) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 48), MAKE_ID(DST_TIMEZONE_ID, 24) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 52), MAKE_ID(DST_TIMEZONE_ID, 25) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 59), MAKE_ID(DST_TIMEZONE_ID, 26) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 62), MAKE_ID(DST_TIMEZONE_ID, 27) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 65), MAKE_ID(DST_TIMEZONE_ID, 28) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 83), MAKE_ID(DST_TIMEZONE_ID, 29) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 81), MAKE_ID(DST_TIMEZONE_ID, 30) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 80), MAKE_ID(DST_TIMEZONE_ID, 31) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 86), MAKE_ID(DST_TIMEZONE_ID, 32) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 89), MAKE_ID(DST_TIMEZONE_ID, 33) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 100), MAKE_ID(DST_TIMEZONE_ID, 35) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 112), MAKE_ID(DST_TIMEZONE_ID, 38) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 139), MAKE_ID(DST_TIMEZONE_ID, 39) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 142), MAKE_ID(DST_TIMEZONE_ID, 40) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 148), MAKE_ID(DST_TIMEZONE_ID, 43) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 153), MAKE_ID(DST_TIMEZONE_ID, 44) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 154), MAKE_ID(DST_TIMEZONE_ID, 45) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 156), MAKE_ID(DST_TIMEZONE_ID, 46) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 64), MAKE_ID(DST_TIMEZONE_ID, 47) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 116), MAKE_ID(DST_TIMEZONE_ID, 48) },\n\t{ MAKE_ID(STD_TIMEZONE_ID, 33), MAKE_ID(DST_TIMEZONE_ID, 49) }\n\t});\n\n\nbool WorldLocation::InsideCanada() const {\n\treturn ((WorldLocation *)this)->InsideCanada(_latitude, _longitude);\n}\n\n\nbool WorldLocation::InsideCanada(const double latitude, const double longitude) {\n\tif (latitude < DEGREE_TO_RADIAN(41.0))\t\treturn false;\n\tif (latitude > DEGREE_TO_RADIAN(83.0))\t\treturn false;\n\tif (longitude < DEGREE_TO_RADIAN(-141.0))\treturn false;\n\tif (longitude > DEGREE_TO_RADIAN(-52.0))\treturn false;\n\n#if defined(_MSC_VER) || defined(_USE_CANADA)\n\treturn insideCanadaDetail(&canada, RADIAN_TO_DEGREE(latitude), RADIAN_TO_DEGREE(longitude));\n#else\n\tif (longitude < DEGREE_TO_RADIAN(-122.8)) {\n\t\tif (latitude < DEGREE_TO_RADIAN(48.3))\treturn false;\n\t}\n\telse if (longitude < DEGREE_TO_RADIAN(-95.153)) {\n\t\tif (latitude < DEGREE_TO_RADIAN(49.0))\treturn false;\n\t}\n\telse if (longitude < DEGREE_TO_RADIAN(-88.0)) {\n\t\tif (latitude < DEGREE_TO_RADIAN(48.0))\treturn false;\n\t}\n\telse if (longitude < DEGREE_TO_RADIAN(-83.5)) {\n\t\tif (latitude < DEGREE_TO_RADIAN(45.5))\treturn false;\n\t}\n\telse if (longitude < DEGREE_TO_RADIAN(-78.7)) {\n\t\tif (latitude < DEGREE_TO_RADIAN(41.66))\treturn false;\n\t}\n\telse if (longitude < DEGREE_TO_RADIAN(-74.75)) {\n\t\tif (latitude < DEGREE_TO_RADIAN(43.65))\treturn false;\n\t}\n\telse if (longitude < DEGREE_TO_RADIAN(-67.31)) {\n\t\tif (latitude < DEGREE_TO_RADIAN(45))\treturn false;\n\t}\n\telse {\n\t\tif (latitude < DEGREE_TO_RADIAN(43.25))\treturn false;\n\t}\n\treturn true;\n#endif\n}\n\n\nbool WorldLocation::InsideNewZealand() const {\n\tif ((_longitude > DEGREE_TO_RADIAN(172.5)) && (_longitude < DEGREE_TO_RADIAN(178.6))) {\n\t\tif ((_latitude > DEGREE_TO_RADIAN(-41.75)) && (_latitude < DEGREE_TO_RADIAN(-34.3))) {\t// general extents of New Zealand's north island\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tif ((_longitude > DEGREE_TO_RADIAN(166.3)) && (_longitude < DEGREE_TO_RADIAN(174.5))) {\n\t\tif ((_latitude > DEGREE_TO_RADIAN(-47.35)) && (_latitude < DEGREE_TO_RADIAN(40.4))) {\t// general extents of New Zealand's south island\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\nbool WorldLocation::InsideTasmania() const {\n\tif ((_longitude > DEGREE_TO_RADIAN(143.5)) && (_longitude < DEGREE_TO_RADIAN(149.0))) {\n\t\tif ((_latitude > DEGREE_TO_RADIAN(-44.0)) && (_latitude < DEGREE_TO_RADIAN(-39.5))) {\t// general extents of Tasmania\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n\nbool WorldLocation::InsideAustraliaMainland() const {\n\tif ((_longitude > DEGREE_TO_RADIAN(113.15)) && (_longitude < DEGREE_TO_RADIAN(153.633333))) {\n\t\tif ((_latitude > DEGREE_TO_RADIAN(-39.133333)) && (_latitude < DEGREE_TO_RADIAN(-10.683333))) {\t// general extents of continental Australia\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n\nvoid WorldLocation::SetTimeZoneOffset(const TimeZoneInfo* timezone)\n{\n\t_amtDST = timezone->m_dst;\n\t__timezone = timezone->m_timezone;\n\tif (_startDST.GetTotalMicroSeconds() != 0)\n\t\t_startDST = WTimeSpan(0);\n\tif (_amtDST.GetTotalMicroSeconds() != 0)\n\t\t_endDST = WTimeSpan(366, 0, 0, 0);\n\t_timezoneInfo = timezone;\n}\n\n\nbool WorldLocation::SetTimeZoneOffset(std::uint32_t id)\n{\n\tauto tz = TimeZoneFromId(id);\n\tif (tz)\n\t{\n\t\tSetTimeZoneOffset(tz);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\nconst ::TimeZoneInfo *WorldLocation::GuessTimeZone(INTNM::int16_t set) const {\n\tbool valid;\n\tconst TimeZoneInfo *tzi = WorldLocation::TimeZoneFromLatLon(_latitude, _longitude, set, &valid);\n\tif (!valid)\n\t{\n\t\tif (InsideNewZealand()) {\n\t\t\tif (set == 0)\n\t\t\t\treturn &m_std_timezones[15];\n\t\t\telse if (set == 1)\n\t\t\t\treturn &m_dst_timezones[15];\n\t\t} else if (InsideTasmania()) {\n\t\t\tif (set == 0)\n\t\t\t\treturn &m_std_timezones[1];\n\t\t\telse if (set == 1)\n\t\t\t\treturn &m_dst_timezones[2];\n\t\t}\n\n\t\tdouble longitude = _longitude;\n\t\twhile (longitude < -Pi)\n\t\t\tlongitude += TwoPi;\n\t\twhile (longitude > Pi)\n\t\t\tlongitude -= TwoPi;\n\n\t\tconst ::TimeZoneInfo *tz;\n\t\tdouble variation = TwoPi;\n\t\tif (set == 1)\t\ttz = m_dst_timezones;\n\t\telse if (set == -1)\ttz = m_mil_timezones;\n\t\telse if (set == 0)\ttz = m_std_timezones;\n\t\telse\t\t\treturn NULL;\n\n\t\twhile (tz->m_name) {\n\t\t\tdouble ideal_longitude = ((double)tz->m_timezone.GetTotalSeconds()) / (double)(12.0 * 60.0 * 60.0) * Pi;\n\t\t\tdouble offset_longitude = fabs(longitude - ideal_longitude);\n\t\t\tif (variation > offset_longitude) {\n\t\t\t\tvariation = offset_longitude;\n\t\t\t\ttzi = tz;\n\t\t\t}\n\t\t\ttz++;\n\t\t}\n\t}\n\treturn tzi;\n}\n\n\nconst ::TimeZoneInfo *WorldLocation::CurrentTimeZone(INTNM::int16_t set, bool* hidden) const\n{\n\tif (_timezoneInfo != nullptr)\n\t{\n\t\tif (hidden)\n\t\t{\n\t\t\tif (IS_STD(_timezoneInfo->m_id))\n\t\t\t{\n\t\t\t\t*hidden = true;\n\t\t\t\tconst ::TimeZoneInfo* tz = m_std_timezones;\n\t\t\t\twhile (tz->m_code)\n\t\t\t\t{\n\t\t\t\t\tif (tz->m_id == _timezoneInfo->m_id)\n\t\t\t\t\t{\n\t\t\t\t\t\t*hidden = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\ttz++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (IS_DST(_timezoneInfo->m_id))\n\t\t\t{\n\t\t\t\t*hidden = true;\n\t\t\t\tconst ::TimeZoneInfo* tz = m_dst_timezones;\n\t\t\t\twhile (tz->m_code)\n\t\t\t\t{\n\t\t\t\t\tif (tz->m_id == _timezoneInfo->m_id)\n\t\t\t\t\t{\n\t\t\t\t\t\t*hidden = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\ttz++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn _timezoneInfo;\n\t}\n\telse\n\t{\n\t\tconst ::TimeZoneInfo* tz;\n\t\tconst ::TimeZoneInfo* tzSecondary = nullptr;\n\t\tif (set == -1)\n\t\t\ttz = m_mil_timezones;\n\t\telse if (_startDST == _endDST)\n\t\t{\n\t\t\ttz = m_std_timezones;\n\t\t\ttzSecondary = m_std_extra_timezones;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttz = m_dst_timezones;\n\t\t\ttzSecondary = m_dst_extra_timezones;\n\t\t}\n\n\t\twhile (tz->m_code)\n\t\t{\n\t\t\tif (tz->m_timezone == __timezone)\n\t\t\t\tbreak;\n\t\t\ttz++;\n\t\t}\n\t\tif (tz->m_code)\n\t\t{\n\t\t\tif (hidden)\n\t\t\t\t*hidden = false;\n\t\t\treturn tz;\n\t\t}\n\t\telse if (tzSecondary)\n\t\t{\n\t\t\twhile (tzSecondary->m_code)\n\t\t\t{\n\t\t\t\tif (tzSecondary->m_timezone == __timezone)\n\t\t\t\t\tbreak;\n\t\t\t\ttzSecondary++;\n\t\t\t}\n\t\t\tif (tzSecondary->m_code)\n\t\t\t{\n\t\t\t\tif (hidden)\n\t\t\t\t\t*hidden = true;\n\t\t\t\treturn tzSecondary;\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\treturn nullptr;\n}\n\nconst ::TimeZoneInfo* WorldLocation::TimeZoneFromName(const std::string& name, INTNM::int16_t set, bool* hidden)\n{\n\tconst ::TimeZoneInfo *tz;\n\tconst ::TimeZoneInfo* tzSecondary = nullptr;\n\tif (set == -1)\n\t\ttz = m_mil_timezones;\n\telse if (set)\n\t{\n\t\ttz = m_dst_timezones;\n\t\ttzSecondary = m_dst_extra_timezones;\n\t}\n\telse\n\t{\n\t\ttz = m_std_timezones;\n\t\ttzSecondary = m_std_extra_timezones;\n\t}\n\n\twhile (tz->m_code)\n\t{\n\t\tif (boost::iequals(tz->m_code, name) || boost::iequals(tz->m_name, name))\n\t\t\tbreak;\n\t\ttz++;\n\t}\n\tif (tz->m_code)\n\t{\n\t\tif (hidden)\n\t\t\t*hidden = false;\n\t\treturn tz;\n\t}\n\telse if (tzSecondary)\n\t{\n\t\twhile (tzSecondary->m_code)\n\t\t{\n\t\t\tif (boost::iequals(tzSecondary->m_code, name) || boost::iequals(tzSecondary->m_name, name))\n\t\t\t\tbreak;\n\t\t\ttzSecondary++;\n\t\t}\n\t\tif (tzSecondary->m_code)\n\t\t{\n\t\t\tif (hidden)\n\t\t\t\t*hidden = true;\n\t\t\treturn tzSecondary;\n\t\t}\n\t}\n\treturn nullptr;\n}\n\n\nconst ::TimeZoneInfo* WorldLocation::TimeZoneFromId(std::uint32_t id, bool* hidden)\n{\n\tif (IS_STD(id))\n\t{\n\t\tconst TimeZoneInfo* tz = m_std_timezones;\n\t\twhile (tz->m_name)\n\t\t{\n\t\t\tif (tz->m_id == id)\n\t\t\t{\n\t\t\t\tif (hidden)\n\t\t\t\t\t*hidden = false;\n\t\t\t\treturn tz;\n\t\t\t}\n\t\t\ttz++;\n\t\t}\n\t\ttz = m_std_extra_timezones;\n\t\twhile (tz->m_name)\n\t\t{\n\t\t\tif (tz->m_id == id)\n\t\t\t{\n\t\t\t\tif (hidden)\n\t\t\t\t\t*hidden = true;\n\t\t\t\treturn tz;\n\t\t\t}\n\t\t\ttz++;\n\t\t}\n\t}\n\telse if (IS_DST(id))\n\t{\n\t\tconst TimeZoneInfo* tz = m_dst_timezones;\n\t\twhile (tz->m_name)\n\t\t{\n\t\t\tif (tz->m_id == id)\n\t\t\t{\n\t\t\t\tif (hidden)\n\t\t\t\t\t*hidden = false;\n\t\t\t\treturn tz;\n\t\t\t}\n\t\t\ttz++;\n\t\t}\n\t\ttz = m_dst_extra_timezones;\n\t\twhile (tz->m_name)\n\t\t{\n\t\t\tif (tz->m_id == id)\n\t\t\t{\n\t\t\t\tif (hidden)\n\t\t\t\t\t*hidden = true;\n\t\t\t\treturn tz;\n\t\t\t}\n\t\t\ttz++;\n\t\t}\n\t}\n\telse\n\t{\n\t\tconst TimeZoneInfo* tz = m_mil_timezones;\n\t\twhile (tz->m_name)\n\t\t{\n\t\t\tif (tz->m_id == id)\n\t\t\t{\n\t\t\t\tif (hidden)\n\t\t\t\t\t*hidden = false;\n\t\t\t\treturn tz;\n\t\t\t}\n\t\t\ttz++;\n\t\t}\n\t}\n\treturn nullptr;\n}\n\n\nconst ::TimeZoneInfo* WorldLocation::TimeZoneFromWindowsName(const std::string& name)\n{\n\tfor (auto windows : WindowsMap)\n\t{\n\t\tif (boost::equals(windows.WindowsName, name))\n\t\t\treturn TimeZoneFromId(windows.HssId);\n\t}\n\treturn nullptr;\n}\n\n\nconst ::TimeZoneInfo* WorldLocation::TimeZoneFromRegionName(const std::string& regionName)\n{\n\tfor (auto region : RegionMap)\n\t{\n\t\tif (boost::iequals(region.Name, regionName))\n\t\t\treturn TimeZoneFromId(region.HssId);\n\t}\n\treturn nullptr;\n}\n\n\nconst TimeZoneInfo* WorldLocation::GetDaylightSavingsTimeZone(const TimeZoneInfo* info)\n{\n\tif (bimapContainsLeft(daylightStandardMap, info->m_id))\n\t\treturn TimeZoneFromId(daylightStandardMap.left.at(info->m_id));\n\treturn info;\n}\n\n\nconst TimeZoneInfo* WorldLocation::GetStandardTimeZone(const TimeZoneInfo* info)\n{\n\tif (bimapContainsRight(daylightStandardMap, info->m_id))\n\t\treturn TimeZoneFromId(daylightStandardMap.right.at(info->m_id));\n\treturn info;\n}\n\n\nWorldLocation::WorldLocation()\n\t: _timezoneInfo(nullptr)\n#ifdef HSS_USE_CACHING\n\t, m_sunCache(2), m_solarCache(2)\n#endif\n{\n\t_latitude = 1000.0;\n\t_longitude = 1000.0;\n\t__timezone = WTimeSpan(0);\n\t_startDST = WTimeSpan(0);\n\t_endDST = WTimeSpan(0);\n\t_amtDST = WTimeSpan(0, 1, 0, 0);\n\n\tcanada = nullptr;\n}\n\n\nWorldLocation::WorldLocation(const WorldLocation &wl)\n\t: _timezoneInfo(nullptr)\n#ifdef HSS_USE_CACHING\n\t, m_sunCache(2), m_solarCache(2)\n#endif\n{\n\t*this = wl;\n\n\tcanada = nullptr;\n}\n\n\nWorldLocation::WorldLocation(double latitude, double longitude, bool guessTimezone)\n\t: _timezoneInfo(nullptr)\n#ifdef HSS_USE_CACHING\n\t, m_sunCache(2), m_solarCache(2)\n#endif\n{\n\t_latitude = DEGREE_TO_RADIAN(latitude);\n\t_longitude = DEGREE_TO_RADIAN(longitude);\n\tif (guessTimezone)\n\t{\n\t\t_timezoneInfo = GuessTimeZone(0);\n\t\t__timezone = _timezoneInfo->m_timezone;\n\t\tif (_timezoneInfo->m_dst.GetTotalSeconds() > 0)\n\t\t{\n\t\t\t_startDST = WTimeSpan(0);\n\t\t\t_endDST = WTimeSpan(366, 0, 0, 0);\n\t\t\t_amtDST = _timezoneInfo->m_dst;\n\t\t}\n\t}\n\n\tcanada = nullptr;\n}\n\n\nWorldLocation::~WorldLocation() {\n#if defined(_MSC_VER) || defined(_USE_CANADA)\n\tinsideCanadaCleanup(canada);\n#endif\n}\n\n\nWorldLocation &WorldLocation::operator=(const WorldLocation &wl) {\n\tif (&wl != this) {\n\t\t_latitude = wl._latitude;\n\t\t_longitude = wl._longitude;\n\t\t__timezone = wl.__timezone;\n\t\t_startDST = wl._startDST;\n\t\t_endDST = wl._endDST;\n\t\t_amtDST = wl._amtDST;\n\n#ifdef HSS_USE_CACHING\n\t\tm_sunCache.Clear();\n\t\tm_solarCache.Clear();\n#endif\n\n\t}\n\treturn *this;\n}\n\n\nbool WorldLocation::operator==(const WorldLocation &wl) const {\n\tif (&wl == this)\n\t\treturn true;\n\tif ((_latitude == wl._latitude) &&\n\t    (_longitude == wl._longitude) &&\n\t    (__timezone == wl.__timezone) &&\n\t    (_startDST == wl._startDST) &&\n\t    (_endDST == wl._endDST) &&\n\t    (_amtDST == wl._amtDST))\n\t\treturn true;\n\treturn false;\n}\n\n\nbool WorldLocation::operator!=(const WorldLocation &wl) const {\n\treturn !(*this == wl);\n}\n\n\nWTimeSpan WorldLocation::m_solar_timezone(const WTime &solar_time) const {\n#ifdef HSS_USE_CACHING\n\tstruct sun_key sk;\n\tsk.m_sun_cache_lat = m_latitude;\n\tsk.m_sun_cache_long = m_longitude;\n\tsk.m_sun_cache_tm = solar_time.GetTime(0);\n\tWTimeSpan retval;\n\tif (m_solarCache.Retrieve(&sk, &retval))\n\t\treturn retval;\n#endif\n\n\tINTNM::int32_t\tday = solar_time.GetDay(WTIME_FORMAT_AS_LOCAL),\n\t\tyear = solar_time.GetYear(WTIME_FORMAT_AS_LOCAL),\n\t\tmonth = solar_time.GetMonth(WTIME_FORMAT_AS_LOCAL);\n\n\tCSunriseSunsetCalc calculator;\n\tRISESET_IN_STRUCT sInput;\n\tsInput.Latitude = RADIAN_TO_DEGREE(_latitude);\n\tsInput.Longitude = -RADIAN_TO_DEGREE(_longitude);\n\tsInput.timezone = 0;\n\tsInput.DaytimeSaving = false;\n\tsInput.year = year;\n\tsInput.month = month;\n\tsInput.day = day;\n\tRISESET_OUT_STRUCT sOut;\n\tcalculator.calcSun(sInput,&sOut);\n\n\tWTimeSpan solarTime(0, sOut.SolarNoonHour - 12, sOut.SolarNoonMin, (INTNM::int32_t)sOut.SolarNoonSec);\n\tWTimeSpan result((INTNM::int64_t)0 - solarTime.GetTotalSeconds());\n\t\n#ifdef HSS_USE_CACHING\n\tm_solarCache.Store(&sk, &result);\n#endif\n\treturn result;\n}\n\n\n#if defined(TIMES_WINDOWS) && !defined(_NO_MFC)\nCArchive& HSS_Time::operator>>(CArchive& is, WorldLocation &wl) {\n\tunion {\n\t\tshort svalue[4];\n\t\tdouble dvalue;\n\t} loader;\n\tis >> loader.svalue[0] >> loader.svalue[1];\n\tif (loader.svalue[0] == -1) {\n\t\tif ((loader.svalue[1] < 1) || (loader.svalue[1] > 6))\n\t\t\tAfxThrowArchiveException(CArchiveException::badSchema, _T(\"World Location\"));\n\t\tbool found = false;\n\t\tif (loader.svalue[1] >= 5) {\n\t\t\tuint32_t id;\n\t\t\tis >> id;\n\t\t\tif (id != (uint32_t)-1) {\n\t\t\t\twl.SetTimeZoneOffset(id);\n\t\t\t\tfound = true;\n\t\t\t}\n\t\t}\n\t\tis >> wl._latitude >> wl._longitude;\n\t\tif (!found) {\n\t\t\tif (loader.svalue[1] < 3) {\n\t\t\t\tINTNM::int32_t timezone;\n\t\t\t\tis >> timezone;\n\t\t\t\twl.__timezone = WTimeSpan(timezone);\n\t\t\t} else\tis >> wl.__timezone;\n\t\t\tif (loader.svalue[1] < 4) {\n\t\t\t\tINTNM::int16_t spheroid;\n\t\t\t\tis >> spheroid;\n\t\t\t}\n\t\t\tif (loader.svalue[1] == 2) {\n\t\t\t\tINTNM::int32_t ts;\n\t\t\t\tis >> ts; wl._startDST = WTimeSpan(ts);\n\t\t\t\tis >> ts; wl._endDST = WTimeSpan(ts);\n\t\t\t\tis >> ts; wl._amtDST = WTimeSpan(ts);\n\t\t\t} else if (loader.svalue[1] >= 3)\n\t\t\t\tis >> wl._startDST >> wl._endDST >> wl._amtDST;\n\n\t\t\t// try to guess what the timezone ID is\n\t\t\tconst ::TimeZoneInfo* tz;\n\t\t\tif ((wl._amtDST.GetTotalSeconds() == 0) && (!wl.dstExists()))\ttz = wl.m_std_timezones;\n\t\t\telse\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttz = wl.m_dst_timezones;\n\t\t\twhile (tz->m_name) {\n\t\t\t\tif ((tz->m_timezone == wl.__timezone) && (tz->m_dst == wl._amtDST)) {\n\t\t\t\t\twl._timezoneInfo = tz;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttz++;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tis >> loader.svalue[2] >> loader.svalue[3];\n\t\twl._latitude = loader.dvalue;\n\t\tis >> wl._longitude >> wl.__timezone;\n\t}\n\treturn is;\n}\n\n\nCArchive& HSS_Time::operator<<(CArchive& os, const WorldLocation &wl) {\n\tshort hickup = -1;\n\tshort version = 6;\t\t// 4 removed m_spheroid\n\t\t\t\t\t\t\t// 5 added id\n\t\t\t\t\t\t\t// 6 re-added latitude, longitude\n\tos << hickup << version;\n\tuint32_t id;\n\tif (wl.m_timezoneInfo()) {\n\t\tid = wl.m_timezoneInfo()->m_id;\n\t\tos << id;\n\t\tos << wl._latitude << wl._longitude;\n\t} else {\n\t\tid = (uint32_t)-1;\n\t\tos << id << wl._latitude << wl._longitude << wl.__timezone;\n\t\tos << wl._startDST << wl._endDST << wl._amtDST;\n\t}\n\treturn os;\n}\n#endif\n\n\nINTNM::int16_t WorldLocation::m_sun_rise_set(const WTime &daytime, WTime *Rise, WTime *Set, WTime *Noon) const {\n#ifdef HSS_USE_CACHING\n\tstruct sun_key sk;\n\tsk.m_sun_cache_lat = m_latitude;\n\tsk.m_sun_cache_long = m_longitude;\n\tsk.m_sun_cache_tm = daytime.GetTime(0);\n\tstruct sun_val sv;\n\tif (m_sunCache.Retrieve(&sk, &sv)) {\n\t\t*Rise = WTime(sv.m_sun_cache_rise, Rise->GetTimeManager());\n\t\t*Set = WTime(sv.m_sun_cache_set, Set->GetTimeManager());\n\t\t*Noon = WTime(sv.m_sun_cache_noon, Noon->GetTimeManager());\n\t\treturn sv.m_success;\n\t}\n#endif\n\n\tINTNM::int32_t\tday = daytime.GetDay(WTIME_FORMAT_AS_SOLAR),\n\t\tyear = daytime.GetYear(WTIME_FORMAT_AS_SOLAR),\n\t\tmonth = daytime.GetMonth(WTIME_FORMAT_AS_SOLAR);\n\n\tCSunriseSunsetCalc calculator;\n\tRISESET_IN_STRUCT sInput;\n\tsInput.Latitude = RADIAN_TO_DEGREE(_latitude);\n\tsInput.Longitude = -RADIAN_TO_DEGREE(_longitude);\n\tsInput.timezone = 0;\n\tsInput.DaytimeSaving = false;\n\tsInput.year = year;\n\tsInput.month = month;\n\tsInput.day = day;\n\tRISESET_OUT_STRUCT sOut;\n\tINTNM::int16_t success = calculator.calcSun(sInput,&sOut);\n\n\tWTime riseTime(0ULL, Rise->GetTimeManager()),\n\t\tsetTime(0ULL, Set->GetTimeManager()),\n\t\tnoonTime(0ULL, Noon->GetTimeManager());\n\tif (!(success & NO_SUNRISE))\n\t\triseTime = WTime(sOut.YearRise,sOut.MonthRise,sOut.DayRise,sOut.HourRise,sOut.MinRise,(INTNM::int32_t)sOut.SecRise,Rise->GetTimeManager());\n\t*Rise = riseTime;\n\tif (!(success & NO_SUNSET))\n\t\tsetTime = WTime(sOut.YearSet,sOut.MonthSet,sOut.DaySet,sOut.HourSet,sOut.MinSet,(INTNM::int32_t)sOut.SecSet,Set->GetTimeManager());\n\t*Set = setTime;\n\tnoonTime = WTime(sInput.year,sInput.month,sInput.day, sOut.SolarNoonHour, sOut.SolarNoonMin, (INTNM::int32_t)sOut.SolarNoonSec,Noon->GetTimeManager());\n\t*Noon = noonTime;\n\t\t\n#ifdef HSS_USE_CACHING\n\tsk.m_sun_cache_tm = daytime.GetTime(0);\n\tsk.m_sun_cache_lat = m_latitude;\n\tsk.m_sun_cache_long = m_longitude;\n\tsv.m_sun_cache_rise = Rise->GetTotalSeconds();\n\tsv.m_sun_cache_set = Set->GetTotalSeconds();\n\tsv.m_sun_cache_noon = Noon->GetTotalSeconds();\n\tsv.m_success = success;\n\tm_sunCache.Store(&sk, &sv);\n#endif\n\treturn success;\n}\n", "meta": {"hexsha": "f6946dea803b6b2be3883b36740ca9ad8bf03f9f", "size": 55361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cxx/src/worldlocation.cpp", "max_stars_repo_name": "HeartlandSoftware/WTime", "max_stars_repo_head_hexsha": "9285b780e930a72bb10dd0811ad1177ff6c25aae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cxx/src/worldlocation.cpp", "max_issues_repo_name": "HeartlandSoftware/WTime", "max_issues_repo_head_hexsha": "9285b780e930a72bb10dd0811ad1177ff6c25aae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cxx/src/worldlocation.cpp", "max_forks_repo_name": "HeartlandSoftware/WTime", "max_forks_repo_head_hexsha": "9285b780e930a72bb10dd0811ad1177ff6c25aae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6001683502, "max_line_length": 152, "alphanum_fraction": 0.6627951085, "num_tokens": 21285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018545, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.23500371220159447}}
{"text": "// json parser\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <utility>\nnamespace pt = boost::property_tree;\n\n#include \"../ReflectionCoefficients/ReflectionCoefficientsFactory.h\"\n#include \"GreensTensorPlate.h\"\n#include \"GreensTensorVacuum.h\"\n#include \"GreensTensorPlateVacuum.h\"\n\nGreensTensorPlateVacuum::GreensTensorPlateVacuum(\n    double v, double beta, double za,\n    std::shared_ptr<ReflectionCoefficients> reflection_coefficients,\n    double delta_cut, vec::fixed<2> rel_err)\n    : GreensTensorPlate(v, beta, za, std::move(reflection_coefficients), delta_cut,\n                        rel_err) {\n  this->vacuum_greens_tensor =\n      std::make_shared<GreensTensorVacuum>(v, beta, rel_err(0));\n}\n\nGreensTensorPlateVacuum::GreensTensorPlateVacuum(const std::string &input_file)\n    : GreensTensorPlate(input_file) {\n  // Create a root\n  pt::ptree root;\n\n  // Load the json file in this ptree\n  pt::read_json(input_file, root);\n\n  std::string addvacuum = root.get<std::string>(\"GreensTensor.addvacuum\");\n  assert(addvacuum == \"true\");\n\n  this->vacuum_greens_tensor =\n      std::make_shared<GreensTensorVacuum>(v, beta, this->rel_err(0));\n}\n\nvoid GreensTensorPlateVacuum::integrate_k(\n    double omega, cx_mat::fixed<3, 3> &GT, \n    Tensor_Options fancy_complex, Weight_Options weight_function) const {\n\n  //compute the contributions from the planar surface\n  GreensTensorPlate::integrate_k(omega, GT, fancy_complex, weight_function);\n\n  //compute the contributions from the vacuum\n  cx_mat::fixed<3, 3> vac;\n  vacuum_greens_tensor->integrate_k(omega, vac, fancy_complex, weight_function);\n\n  GT += vac;\n}\n\nvoid GreensTensorPlateVacuum::calculate_tensor(double omega, vec::fixed<2> k,\n                                               cx_mat::fixed<3, 3> &GT) const {\n\n  //compute the contributions from the planar surface\n  GreensTensorPlate::calculate_tensor(omega, k, GT);\n\n  //compute the contributions from the vacuum\n  cx_mat::fixed<3, 3> vac;\n  vacuum_greens_tensor->calculate_tensor(omega, k, vac);\n\n  GT += vac;\n}\n\nvoid GreensTensorPlateVacuum::print_info(std::ostream &stream) const {\n  stream << \"# GreensTensorPlateVacuum\\n#\\n\"\n         << \"# v = \" << v << \"\\n\"\n         << \"# beta = \" << beta << \"\\n\"\n         << \"# za = \" << za << \"\\n\"\n         << \"# delta_cut = \" << delta_cut << \"\\n\"\n         << \"# rel_err = \" << rel_err(0) << \",\" << rel_err(1) << \"\\n\";\n}\n", "meta": {"hexsha": "9ead8127d91db9b83d7c052be3e804da583c0a7e", "size": 2420, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GreensTensor/GreensTensorPlateVacuum.cpp", "max_stars_repo_name": "QuaCaTeam/quaca", "max_stars_repo_head_hexsha": "ab2d213f3e0e357bd72930ae1e4e703184130270", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-19T09:01:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-20T07:57:54.000Z", "max_issues_repo_path": "src/GreensTensor/GreensTensorPlateVacuum.cpp", "max_issues_repo_name": "myoelmy/quaca", "max_issues_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T08:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T07:33:35.000Z", "max_forks_repo_path": "src/GreensTensor/GreensTensorPlateVacuum.cpp", "max_forks_repo_name": "myoelmy/quaca", "max_forks_repo_head_hexsha": "def47981b710a73f2fb3a7c14c354f8de91cf88f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.6111111111, "max_line_length": 83, "alphanum_fraction": 0.6842975207, "num_tokens": 647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23493508547998251}}
{"text": "#include \"RouteFinder.h\"\n\n#include <boost/math/constants/constants.hpp>\n\nnamespace carto { namespace osrm {\n    Result RouteFinder::find(const Query& query) const {\n        std::array<std::vector<Graph::NearestNode>, 2> nearestNodes;\n        std::array<std::priority_queue<SearchNode>, 2> heaps;\n        std::unordered_map<Graph::NodeId, PathNode, Graph::NodeId::Hash> pathSuffixMap;\n        float minWeight = 0.0f;\n        for (int i = 0; i < 2; i++) {\n            nearestNodes[i] = _graph->findNearestNode(query.getPos(i));\n            if (nearestNodes[i].empty()) {\n                return Result();\n            }\n\n            for (const Graph::NearestNode& nearestNode : nearestNodes[i]) {\n                Graph::NodePtr node = _graph->getNode(nearestNode.nodeId);\n\n                // Calculate end-point weights\n                float weight = (i == 0 ? -nearestNode.geometryRelPos : nearestNode.geometryRelPos) * node->nodeData.weight;\n                minWeight = std::min(minWeight, weight);\n\n                // Special case: we have already added same node but the node is inaccessible along the current direction\n                if (i == 1 && nearestNodes[0].size() == 1 && nearestNodes[1].size() == 1) {\n                    const Graph::NearestNode& otherNearestNode = nearestNodes[1 - i][0];\n                    if (nearestNode.nodeId == otherNearestNode.nodeId && nearestNode.geometryRelPos < otherNearestNode.geometryRelPos) {\n                        // Add all backward edges \"leading\" to current node\n                        for (auto edge = node->firstEdge; edge != node->lastEdge; edge++) {\n                            if (edge->backward) {\n                                heaps[i].emplace(edge->targetNodeId, Graph::NodeId(), weight + edge->edgeData.weight);\n                                pathSuffixMap[edge->targetNodeId] = PathNode(edge->targetNodeId, *edge, nearestNode.nodeId);\n                            }\n                        }\n\n                        // Here comes the tricky part: we must perform another spatial query to find INCOMING edges pointing to current edge\n                        std::vector<WGSPos> geometry = _graph->getNodeGeometry(*node);\n                        std::vector<Graph::NearestNode> nearestNodes2 = _graph->findNearestNode(geometry.front());\n                        for (const Graph::NearestNode& nearestNode2 : nearestNodes2) {\n                            Graph::NodePtr node2 = _graph->getNode(nearestNode2.nodeId);\n                            for (auto edge2 = node2->firstEdge; edge2 != node2->lastEdge; edge2++) {\n                                if (edge2->forward && edge2->targetNodeId == nearestNode.nodeId) {\n                                    heaps[i].emplace(nearestNode2.nodeId, Graph::NodeId(), weight + edge2->edgeData.weight);\n                                    pathSuffixMap[nearestNode2.nodeId] = PathNode(nearestNode2.nodeId, *edge2, nearestNode.nodeId);\n                                }\n                            }\n                        }\n\n                        continue;\n                    }\n                }\n\n                // Add the node to heap, if other nodes were not already added\n                heaps[i].emplace(nearestNode.nodeId, Graph::NodeId(), weight);\n            }\n        }\n\n        // Apply bidirectional Dijkstra\n        Graph::NodeId bestNodeId;\n        float bestWeight = std::numeric_limits<float>::infinity();\n        std::array<std::unordered_map<Graph::NodeId, SearchNode, Graph::NodeId::Hash>, 2> settledNodes;\n        for (int i = 0; !(heaps[0].empty() && heaps[1].empty()); i = 1 - i) {\n            if (heaps[i].empty()) {\n                continue;\n            }\n            SearchNode searchNode = heaps[i].top();\n            heaps[i].pop();\n            \n            // Skip all invalid nodes\n            if (searchNode.nodeId.blockId.packageId == -1) {\n                continue;\n            }\n\n            // Already shorter path found? In that case we can stop searching in the given direction\n            if (searchNode.weight + minWeight > bestWeight) {\n                while (!heaps[i].empty()) {\n                    heaps[i].pop();\n                }\n                continue;\n            }\n            \n            // Best path to give node?\n            auto it0 = settledNodes[i].find(searchNode.nodeId);\n            if (it0 != settledNodes[i].end()) {\n                if (searchNode.weight >= it0->second.weight) { // not sure if the check is required\n                    continue;\n                }\n            }\n\n            // Settle the node\n            settledNodes[i][searchNode.nodeId] = searchNode;\n            \n            // Stalling optimization. This implementation is not optimal, we should also look at non-settled heap nodes\n            Graph::NodePtr node = _graph->getNode(searchNode.nodeId);\n            bool stall = false;\n            for (auto edge = node->firstEdge; edge != node->lastEdge; edge++) {\n                if ((i == 0 && edge->backward) || (i != 0 && edge->forward)) {\n                    auto it = settledNodes[i].find(edge->targetNodeId);\n                    if (it != settledNodes[i].end()) {\n                        if (it->second.weight + edge->edgeData.weight < searchNode.weight) {\n                            stall = true;\n                            break;\n                        }\n                    }\n                }\n            }\n            if (stall) {\n                continue;\n            }\n\n            // Recalculate shortest path and middle node\n            auto it1 = settledNodes[1 - i].find(searchNode.nodeId);\n            if (it1 != settledNodes[1 - i].end()) {\n                float totalWeight = searchNode.weight + it1->second.weight;\n                if (totalWeight >= 0 && totalWeight < bestWeight) {\n                    bestWeight = totalWeight;\n                    bestNodeId = searchNode.nodeId;\n                }\n            }\n\n            // Add target nodes to heap\n            for (auto edge = node->firstEdge; edge != node->lastEdge; edge++) {\n                if ((i == 0 && edge->forward) || (i != 0 && edge->backward)) {\n                    heaps[i].emplace(edge->targetNodeId, searchNode.nodeId, searchNode.weight + edge->edgeData.weight);\n                }\n            }\n        }\n\n        // Check that path was found\n        if (bestNodeId.blockId.packageId == -1) {\n            return Result();\n        }\n\n        // Unpack path\n        std::array<std::vector<PathNode>, 2> paths;\n        for (int i = 0; i < 2; i++) {\n            std::stack<std::pair<Graph::NodeId, Graph::NodeId>> stack;\n            Graph::NodeId nodeId = bestNodeId;\n            while (true) {\n                auto it = settledNodes[i].find(nodeId);\n                assert(it != settledNodes[i].end());\n                Graph::NodeId prevNodeId = it->second.prevNodeId;\n                if (prevNodeId.blockId.packageId == -1) {\n                    break;\n                }\n                stack.emplace(prevNodeId, nodeId);\n                nodeId = prevNodeId;\n            }\n\n            while (!stack.empty()) {\n                std::pair<Graph::NodeId, Graph::NodeId> nodeIds = stack.top();\n                stack.pop();\n\n                Graph::NodePtr matchedNode;\n                const Graph::Edge* matchedEdge = nullptr;\n\n                // Find the edge between prevNodeId and nodeId. Do matching based on node ids.\n                Graph::NodeId prevNodeId = nodeIds.first;\n                Graph::NodeId nodeId = nodeIds.second;\n                for (int j = 0; j < 2 && !matchedEdge; j++) {\n                    Graph::NodePtr prevNode = _graph->getNode(prevNodeId);\n                    for (auto edge = prevNode->firstEdge; edge != prevNode->lastEdge; edge++) {\n                        if (edge->targetNodeId == nodeId && ((j == i && edge->forward) || (j != i && edge->backward))) {\n                            matchedNode = prevNode;\n                            matchedEdge = edge;\n                            break;\n                        }\n                    }\n                    std::swap(nodeId, prevNodeId);\n                }\n                \n                // If the edge was not found, then we have a link between packages with different node encodings. Do slow matching, based on geometry, not node ids\n                for (int j = 0; j < 2 && !matchedEdge; j++) {\n                    Graph::NodePtr prevNode = _graph->getNode(prevNodeId);\n                    Graph::NodePtr node = _graph->getNode(nodeId);\n                    std::vector<WGSPos> nodeGeometry = _graph->getNodeGeometry(*node);\n                    for (auto edge = prevNode->firstEdge; edge != prevNode->lastEdge; edge++) {\n                        if (edge->targetNodeId.blockId.packageId == -1) {\n                            continue;\n                        }\n                        Graph::NodePtr targetNode = _graph->getNode(edge->targetNodeId);\n                        std::vector<WGSPos> targetNodeGeometry = _graph->getNodeGeometry(*targetNode);\n                        if (nodeGeometry == targetNodeGeometry && ((j == i && edge->forward) || (j != i && edge->backward))) {\n                            matchedNode = prevNode;\n                            matchedEdge = edge;\n                            break;\n                        }\n                    }\n                    std::swap(nodeId, prevNodeId);\n                }\n                \n                // Unpack the matched edge\n                if (matchedEdge) {\n                    if (matchedEdge->contracted) {\n                        if (matchedEdge->contractedNodeId.blockId.packageId == -1) {\n                            return Result(); // Contracted node is not available, packing failed\n                        }\n                        stack.emplace(matchedEdge->contractedNodeId, nodeIds.second);\n                        stack.emplace(nodeIds.first, matchedEdge->contractedNodeId);\n                    }\n                    else {\n                        paths[i].emplace_back(nodeIds.first, *matchedEdge, nodeIds.second);\n                    }\n                } else {\n                    return Result(); // NOTE: this should not happen, unless the graph is broken\n                }\n            }\n        }\n\n        // Build joined path. Add pseudo-node at the beginning to simplify processing and add final node, if rerouting in case of one-way street\n        std::vector<PathNode> path;\n        path = paths[0];\n        for (auto it = paths[1].rbegin(); it != paths[1].rend(); it++) {\n            path.emplace_back(it->nextNodeId, it->edge, it->prevNodeId);\n        }\n        if (path.empty()) {\n            path.emplace(path.begin(), bestNodeId, Graph::Edge(), bestNodeId);\n        }\n        else {\n            Graph::NodeId firstNodeId = path.front().prevNodeId;\n            path.emplace(path.begin(), firstNodeId, Graph::Edge(), firstNodeId);\n        }\n\n        auto finalNodeIt = pathSuffixMap.find(path.back().nextNodeId);\n        if (finalNodeIt != pathSuffixMap.end()) {\n            path.push_back(finalNodeIt->second);\n        }\n\n        // Construct query result\n        std::vector<Instruction> instructions;\n        std::vector<WGSPos> routeVertices;\n        for (std::size_t j = 0; j < path.size(); j++) {\n            Graph::NodeId nodeId = path[j].nextNodeId;\n            Graph::NodePtr node = _graph->getNode(nodeId);\n            \n            std::vector<WGSPos> geometry = _graph->getNodeGeometry(*node);\n            std::pair<std::size_t, std::size_t> geometryIndex(0, geometry.size());\n            std::pair<float, float> geometryRelPos(0.0f, 1.0f);\n\n            std::size_t firstNNIndex = std::numeric_limits<std::size_t>::max();\n            if (j == 0) {\n                for (std::size_t k = 0; k < nearestNodes[0].size(); k++) {\n                    if (nearestNodes[0][k].nodeId == nodeId) {\n                        geometryIndex.first = nearestNodes[0][k].geometrySegmentIndex;\n                        geometryRelPos.first = nearestNodes[0][k].geometryRelPos;\n                        firstNNIndex = k;\n                        break;\n                    }\n                }\n            }\n\n            std::size_t lastNNIndex = std::numeric_limits<std::size_t>::max();\n            if (j == path.size() - 1) {\n                for (std::size_t k = 0; k < nearestNodes[1].size(); k++) {\n                    if (nearestNodes[1][k].nodeId == nodeId) {\n                        geometryIndex.second = nearestNodes[1][k].geometrySegmentIndex;\n                        geometryRelPos.second = nearestNodes[1][k].geometryRelPos;\n                        lastNNIndex = k;\n                        break;\n                    }\n                }\n            }\n\n            double dist = calculateGeometryLength(geometry, geometryRelPos.first, geometryRelPos.second);\n            double time = (j > 0 ? path[j].edge.edgeData.weight : node->nodeData.weight) * (geometryRelPos.second - geometryRelPos.first) / 10.0;\n            std::string streetName = _graph->getNodeName(*node);\n\n            // Initial route instruction/vertex\n            if (firstNNIndex != std::numeric_limits<std::size_t>::max()) {\n                instructions.emplace_back(Instruction::Type::HEAD_ON, Instruction::TravelMode::DEFAULT, streetName, dist, time, routeVertices.size());\n                routeVertices.push_back(nearestNodes[0][firstNNIndex].nodePos);\n            }\n            \n            // Middle instructions/vertices\n            if (!routeVertices.empty() && geometryIndex.first < geometryIndex.second) {\n                if (routeVertices.back() == geometry[geometryIndex.first]) {\n                    routeVertices.pop_back();\n                }\n            }\n            std::size_t vertexIndex = routeVertices.size();\n            routeVertices.insert(routeVertices.end(), geometry.begin() + geometryIndex.first, geometry.begin() + geometryIndex.second);\n            if (j > 0) {\n                Instruction::Type type = static_cast<Instruction::Type>(path[j].edge.edgeData.turnInstruction);\n                Instruction::TravelMode travelMode = static_cast<Instruction::TravelMode>(node->nodeData.travelMode);\n                instructions.emplace_back(type, travelMode, streetName, dist, time, vertexIndex);\n            }\n\n            // Final instruction/vertex\n            if (lastNNIndex != std::numeric_limits<std::size_t>::max()) {\n                instructions.emplace_back(Instruction::Type::REACHED_YOUR_DESTINATION, Instruction::TravelMode::DEFAULT, \"\", 0, 0, routeVertices.size());\n                routeVertices.push_back(nearestNodes[1][lastNNIndex].nodePos);\n            }\n        }\n\n        return Result(std::move(instructions), std::move(routeVertices));\n    }\n\n    double RouteFinder::calculateGeometryLength(const std::vector<WGSPos>& geometry, double t0, double t1) {\n        double totalLen = 0;\n        for (unsigned int j = 1; j < geometry.size(); j++) {\n            totalLen += calculateGreatCircleDistance(geometry[j - 1], geometry[j]);\n        }\n        if (t0 == 0 && t1 == 1) {\n            return totalLen;\n        }\n\n        double pos = 0;\n        double len = 0;\n        for (unsigned int j = 1; j < geometry.size(); j++) {\n            double segmentLen = calculateGreatCircleDistance(geometry[j - 1], geometry[j]);\n            double segmentPos0 = std::max(pos, t0 * totalLen);\n            double segmentPos1 = std::min(pos + segmentLen, t1 * totalLen);\n            len += std::max(0.0, segmentPos1 - segmentPos0);\n            pos += segmentLen;\n        }\n        return len;\n    }\n\n    double RouteFinder::calculateGreatCircleDistance(const WGSPos& p0, const WGSPos& p1) {\n        const double degToRad = boost::math::constants::pi<double>() / 180.0;\n\n        double lat1 = p0(0) * degToRad;\n        double lng1 = p0(1) * degToRad;\n        double lat2 = p1(0) * degToRad;\n        double lng2 = p1(1) * degToRad;\n\n        double dLng = lng1 - lng2;\n        double dLat = lat1 - lat2;\n\n        double aHarv = std::pow(std::sin(dLat / 2.0), 2) + std::cos(lat1) * std::cos(lat2) * std::pow(std::sin(dLng / 2.0), 2);\n        double cHarv = 2.0 * std::atan2(std::sqrt(aHarv), std::sqrt(1.0 - aHarv));\n        return EARTH_RADIUS * cHarv;\n    }\n} }\n", "meta": {"hexsha": "787ecb745998cbdce044a61bfe0baa4f7f05bcaa", "size": 16201, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "osrm/src/osrm/RouteFinder.cpp", "max_stars_repo_name": "farfromrefug/mobile-carto-libs", "max_stars_repo_head_hexsha": "c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-06-27T17:43:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-29T18:50:49.000Z", "max_issues_repo_path": "osrm/src/osrm/RouteFinder.cpp", "max_issues_repo_name": "farfromrefug/mobile-carto-libs", "max_issues_repo_head_hexsha": "c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2019-04-10T06:38:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-20T08:12:02.000Z", "max_forks_repo_path": "osrm/src/osrm/RouteFinder.cpp", "max_forks_repo_name": "farfromrefug/mobile-carto-libs", "max_forks_repo_head_hexsha": "c7e81a7c73661aa047de9ba7e8bbdf3a24bbf1df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T10:25:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-28T10:18:56.000Z", "avg_line_length": 48.3611940299, "max_line_length": 163, "alphanum_fraction": 0.515091661, "num_tokens": 3534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2348505291042797}}
{"text": "#ifndef LBP_SCSLBP_HPP\n#define LBP_SCSLBP_HPP\n\n#include <lbp/defs.hpp>\n#include <lbp/utils.hpp>\n#include <lbp/detail/neighborhoods.hpp>\n#include <lbp/detail/sampling.hpp>\n\n#include <opencv2/core.hpp>\n\n#include <boost/hana/fold.hpp>\n#include <boost/hana/size.hpp>\n#include <boost/hana/tuple.hpp>\n\n#include <boost/integer.hpp>\n\n//\n// @inproceedings{xue2010dynamic,\n//   title={Dynamic background subtraction based on spatial extended center-symmetric local binary pattern},\n//   author={Xue, Gengjian and Sun, Jun and Song, Li},\n//   booktitle={Multimedia and Expo (ICME), 2010 IEEE International Conference on},\n//   pages={1050--1054},\n//   year={2010},\n//   organization={IEEE}\n// }\n//\n\nnamespace lbp {\nnamespace scslbp_detail {\n\nconst auto scslbp = [](auto N, auto S) {\n    const auto n = hana::size (N);\n\n    return [=](const cv::Mat& src, const cv::Mat& m, const cv::Mat& s,\n               size_t i, size_t j) {\n        using namespace hana::literals;\n\n        const auto f = abs (\n            S (src, i, j) - S (m, i, j)) >= 2.5 * S (s, i, j);\n\n        return boost::hana::fold_left (\n            N, 0, [&, shift = 0](auto accum, auto x) mutable {\n                const auto a = S (src, i + x [0_c], j + x [1_c]);\n                const auto b = S (src, i - x [0_c], j - x [1_c]);\n                return accum + ((a >= b) << shift++);\n            }) + (int (f) << n);\n    };\n};\n\n} // namespace scslbp_detail\n\ntemplate< typename T, size_t R, size_t P >\nauto scslbp = [](double alpha = 0.05) {\n    //\n    // Learning rate for both mean and variance:\n    //\n    LBP_ASSERT (0. <= alpha && alpha <= 1.);\n\n    //\n    // Mean, variance, standard deviation and previous frame:\n    //\n    cv::Mat m, v, s, I;\n\n    //\n    // Elementary operator:\n    //\n    auto op = scslbp_detail::scslbp (\n        detail::semicircular_neighborhood< R, P >,\n        detail::nearest_sampler< float >);\n\n    return [=, init = 0](const cv::Mat& arg) mutable {\n        using value_type = typename boost::uint_t< P/2 + 1 >::least;\n\n        //\n        // Only works on single-channel, gray images:\n        //\n        LBP_ASSERT (1 == arg.channels ());\n\n        cv::Mat src = lbp::equalize (lbp::convert (arg, CV_32F));\n\n        if (0 == init && 1 == ++init) {\n            I = src.clone ();\n\n            m = I.clone ();\n            v = I.clone ();\n            s = I.clone ();\n\n            return I;\n        }\n\n        cv::Mat dst (src.size (), opencv_type< value_type >, cv::Scalar (0));\n\n        //\n        // Exponential moving average for estimating the mean:\n        //\n        cv::Mat m_ = (1 - alpha) * m + alpha * src;\n\n        //\n        // Rolling variance with a twist from [2009Gil-Jiménez] (see chapter 2):\n        //\n        cv::Mat v_ = (1 - alpha) * v + (alpha / 2) * lbp::pow (src - I, 2);\n        cv::Mat s_ = lbp::sqrt (v_);\n\n#pragma omp parallel for\n        for (size_t i = R; i < src.rows - R - 1; ++i) {\n            for (size_t j = R; j < src.cols - R - 1; ++j) {\n                dst.at< value_type > (i, j) = op (src, m, s, i, j);\n            }\n        }\n\n        m = m_;\n        v = v_;\n        s = s_;\n\n        I = src.clone ();\n\n        return dst;\n    };\n};\n\n} // namespace lbp\n\n//\n// References:\n//\n// [2009Gil-Jiménez] Gil-Jiménez, Pedro, et al. \"Continuous variance estimation\n// in video surveillance sequences with high illumination changes.\" Signal\n// Processing 89.7 (2009): 1412-1416.\n//\n//\n\n#endif // LBP_SCSLBP_HPP\n", "meta": {"hexsha": "fe8a0b570ba0d3666e0d5d2f4f2026e807512b12", "size": 3423, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/lbp/scslbp.hpp", "max_stars_repo_name": "thinkoid/lbp", "max_stars_repo_head_hexsha": "9ce3bc41a8961cf0304c5d271cd882b4cae78cb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-11-02T12:45:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-25T03:51:09.000Z", "max_issues_repo_path": "include/lbp/scslbp.hpp", "max_issues_repo_name": "thinkoid/lbp", "max_issues_repo_head_hexsha": "9ce3bc41a8961cf0304c5d271cd882b4cae78cb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/lbp/scslbp.hpp", "max_forks_repo_name": "thinkoid/lbp", "max_forks_repo_head_hexsha": "9ce3bc41a8961cf0304c5d271cd882b4cae78cb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-08-02T09:10:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-02T09:19:34.000Z", "avg_line_length": 25.7368421053, "max_line_length": 108, "alphanum_fraction": 0.5349108969, "num_tokens": 1000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.23484043695244028}}
{"text": "#define BIORBD_API_EXPORTS\n#include \"RigidBody/Integrator.h\"\n\n#include <Eigen/Dense>\n#include <boost/numeric/odeint.hpp>\n#include <rbdl/Dynamics.h>\n\n#include \"Utils/Error.h\"\n#include \"Utils/String.h\"\n#include \"RigidBody/GeneralizedCoordinates.h\"\n#include \"RigidBody/GeneralizedVelocity.h\"\n#include \"RigidBody/GeneralizedAcceleration.h\"\n#include \"RigidBody/Joints.h\"\n\nbiorbd::rigidbody::Integrator::Integrator(biorbd::rigidbody::Joints &model) :\n    m_steps(std::make_shared<unsigned int>()),\n    m_model(&model),\n    m_x_vec(std::make_shared<std::vector<state_type>>()),\n    m_times(std::make_shared<std::vector<double>>()),\n    m_u(std::make_shared<biorbd::utils::Vector>()) {\n\n}\n\nbiorbd::rigidbody::Integrator::~Integrator()\n{\n\n}\n\nbiorbd::rigidbody::Integrator biorbd::rigidbody::Integrator::DeepCopy() const\n{\n    biorbd::rigidbody::Integrator copy(*this->m_model);\n    copy.DeepCopy(*this);\n    return copy;\n}\n\nvoid biorbd::rigidbody::Integrator::DeepCopy(const biorbd::rigidbody::Integrator &other)\n{\n    *m_steps = *other.m_steps;\n    m_model = other.m_model;\n    m_x_vec->resize(other.m_x_vec->size());\n    for (unsigned int i=0; i<other.m_x_vec->size(); ++i)\n        (*m_x_vec)[i] = (*other.m_x_vec)[i];\n    m_times->resize(other.m_times->size());\n    for (unsigned int i=0; i<other.m_times->size(); ++i)\n        (*m_times)[i] = (*other.m_times)[i];\n    *m_u = *other.m_u;\n}\n\nvoid biorbd::rigidbody::Integrator::operator() (\n        const state_type &x ,\n        state_type &dxdt ,\n        double ){\n\n    // Équation différentielle : x/xdot => xdot/xddot\n    biorbd::rigidbody::GeneralizedCoordinates Q(*m_model);\n    biorbd::rigidbody::GeneralizedVelocity QDot(*m_model);\n    biorbd::rigidbody::GeneralizedAcceleration QDDot(*m_model);\n    QDDot.setZero();\n    for (unsigned int i=0; i<*m_nQ; i++){\n        Q(i) = x[i];\n    }\n    for (unsigned int i=0; i<*m_nQdot; i++){\n        QDot(i) = x[i+*m_nQ];\n    }\n\n    RigidBodyDynamics::ForwardDynamics (*m_model, Q, QDot, *m_u, QDDot);\n\n    // Faire sortir xdot/xddot\n    for (unsigned int i=0; i<*m_nQ; i++){\n        dxdt[i] = QDot[i];\n    }\n    for (unsigned int i=0; i<*m_nQdot; i++){\n        dxdt[i + *m_nQ] = QDDot[i];\n    }\n\n}\n\nvoid biorbd::rigidbody::Integrator::showAll(){\n    std::cout << \"Test:\" << std::endl;\n    for (unsigned int i=0; i <= *m_steps; i++){\n        std::cout << (*m_times)[i];\n        for (unsigned int j = 0; j < *m_nQ + *m_nQdot; j++)\n            std::cout << \" \" << (*m_x_vec)[i][j];\n        std::cout << std::endl;\n    }\n}\n\nunsigned int biorbd::rigidbody::Integrator::steps() const\n{\n    return *m_steps+1;\n}\n\nbiorbd::utils::Vector biorbd::rigidbody::Integrator::getX(\n        unsigned int idx){\n    biorbd::utils::Vector out(*m_nQ + *m_nQdot);\n    biorbd::utils::Error::check(idx <= *m_steps, \"Trying to get Q outside range\");\n    for (unsigned int i=0; i<*m_nQ + *m_nQdot; i++){\n        out(i) = (*m_x_vec)[idx][i];\n        }\n    return out;\n}\n\ndouble biorbd::rigidbody::Integrator::time(unsigned int idx)\n{\n    return (*m_times)[idx];\n}\n\nvoid biorbd::rigidbody::Integrator::integrate(\n        const biorbd::utils::Vector &Q_Qdot,\n        const biorbd::utils::Vector &u,\n        double t0,\n        double tend,\n        double timeStep){\n    // These variable can't be computer a construct time because of\n    // interaction calls with biorbd::rigidbody::Joints\n    m_nQ = std::make_shared<unsigned int>(m_model->nbQ());\n    m_nQdot = std::make_shared<unsigned int>(m_model->nbQdot());\n\n#ifndef SKIP_ASSERT\n    biorbd::utils::Error::check(\n                Q_Qdot.size() == *m_nQ + *m_nQdot,\n                \"Wrong size for Q and Qdot\");\n#endif\n\n    // Assume constant torque over the whole integration\n    *m_u = u;\n\n    // Remplissage de la variable par les positions et vitesse\n    state_type x(*m_nQ + *m_nQdot);\n    for (unsigned int i=0; i<*m_nQ + *m_nQdot; i++)\n        x[i] = Q_Qdot(i);\n\n    launchIntegrate(x, t0, tend, timeStep);\n}\n\nvoid biorbd::rigidbody::Integrator::launchIntegrate(\n        state_type& x,\n        double t0,\n        double tend,\n        double timeStep)\n{\n    // Choix de l'algorithme et intégration\n    boost::numeric::odeint::runge_kutta4< state_type > stepper;\n    *m_steps = static_cast<unsigned int>(\n                boost::numeric::odeint::integrate_const(\n                    stepper, *this, x, t0, tend, timeStep,\n                    push_back_state_and_time( *m_x_vec , *m_times )));\n}\n", "meta": {"hexsha": "5b86bb26605af61e3e8c30681441a9ee8c429c76", "size": 4410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RigidBody/Integrator.cpp", "max_stars_repo_name": "jdowlingmedley/biorbd", "max_stars_repo_head_hexsha": "591a5372d815af626fa500047fe04743c76d7e13", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RigidBody/Integrator.cpp", "max_issues_repo_name": "jdowlingmedley/biorbd", "max_issues_repo_head_hexsha": "591a5372d815af626fa500047fe04743c76d7e13", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RigidBody/Integrator.cpp", "max_forks_repo_name": "jdowlingmedley/biorbd", "max_forks_repo_head_hexsha": "591a5372d815af626fa500047fe04743c76d7e13", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5973154362, "max_line_length": 88, "alphanum_fraction": 0.6253968254, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23473581523096895}}
{"text": "/************************************************************************/\n/*                                                                      */\n/*       Copyright 2011 by Ullrich Koethe and Michael Hanselmann        */\n/*                                                                      */\n/*    This file is part of the VIGRA computer vision library.           */\n/*    The VIGRA Website is                                              */\n/*        http://hci.iwr.uni-heidelberg.de/vigra/                       */\n/*    Please direct questions, bug reports, and contributions to        */\n/*        ullrich.koethe@iwr.uni-heidelberg.de    or                    */\n/*        vigra@informatik.uni-hamburg.de                               */\n/*                                                                      */\n/*    Permission is hereby granted, free of charge, to any person       */\n/*    obtaining a copy of this software and associated documentation    */\n/*    files (the \"Software\"), to deal in the Software without           */\n/*    restriction, including without limitation the rights to use,      */\n/*    copy, modify, merge, publish, distribute, sublicense, and/or      */\n/*    sell copies of the Software, and to permit persons to whom the    */\n/*    Software is furnished to do so, subject to the following          */\n/*    conditions:                                                       */\n/*                                                                      */\n/*    The above copyrigfht notice and this permission notice shall be    */\n/*    included in all copies or substantial portions of the             */\n/*    Software.                                                         */\n/*                                                                      */\n/*    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND    */\n/*    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES   */\n/*    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND          */\n/*    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT       */\n/*    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,      */\n/*    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING      */\n/*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR     */\n/*    OTHER DEALINGS IN THE SOFTWARE.                                   */\n/*                                                                      */\n/************************************************************************/\n\n#define PY_ARRAY_UNIQUE_SYMBOL vigranumpylearning_PyArray_API\n// #define NO_IMPORT_ARRAY\n\n#include <vigra/numpy_array.hxx>\n#include <vigra/numpy_array_converters.hxx>\n#include <vigra/unsupervised_decomposition.hxx>\n#include <set>\n#include <cmath>\n#include <memory>\n#include <boost/python.hpp>\n\nnamespace python = boost::python;\nnamespace vigra\n{\n\ntemplate<class U>\npython::tuple\npythonPCA(NumpyArray<2,U> features, int nComponents)\n{\n    vigra_precondition(!features.axistags(),\n                       \"principleComponents(): feature matrix must not have axistags\\n\"\n                       \"(use 'array.view(numpy.ndarray)' to remove them).\");\n    \n    NumpyArray<2, U> fz(Shape2(features.shape(0), nComponents)); \n    NumpyArray<2, U> zv(Shape2(nComponents, features.shape(1))); \n\n    {\n        PyAllowThreads _pythread;\n        principleComponents(features, fz, zv);\n    }\n    return python::make_tuple(fz, zv);\n}\n\ntemplate<class U>\npython::tuple\npythonPLSA(NumpyArray<2,U> features, \n           int nComponents,\n           int nIterations,\n           double minGain,\n           bool normalize)\n{\n    vigra_precondition(!features.axistags(),\n                       \"pLSA(): feature matrix must not have axistags\\n\"\n                       \"(use 'array.view(numpy.ndarray)' to remove them).\");\n    \n    NumpyArray<2, U> fz(Shape2(features.shape(0), nComponents)); \n    NumpyArray<2, U> zv(Shape2(nComponents, features.shape(1))); \n\n    {\n        PyAllowThreads _pythread;\n        pLSA(features, fz, zv,\n             RandomNumberGenerator<>(), \n             PLSAOptions().maximumNumberOfIterations(nIterations)\n                          .minimumRelativeGain(minGain)\n                          .normalizedComponentWeights(normalize));\n    }\n    return python::make_tuple(fz, zv);\n}\n\n\nvoid defineUnsupervised()\n{\n    using namespace python;\n    \n    docstring_options doc_options(true, true, false);\n\n    def(\"principleComponents\", registerConverters(&pythonPCA<double>),\n        (arg(\"features\"), arg(\"nComponents\")),\n        \"\\nPerform principle component analysis. \\n\\n\"\n        \"The imput matrix 'features' must have shape (nFeatures*nSamples). PCA will\\n\"\n        \"reduce it to a smaller matrix 'C' with shape (nComponents*nSamples) that \\n\"\n        \"preserves as much variance as possible. Specifically, the call::\\n\\n\"\n        \"    P, C = principleComponents(features, 3)\\n\\n\"\n        \"returns a projection matrix 'P' with shape (nComponents*nFeatures)\\n\"\n        \"such that ``C = numpy.dot(numpy.transpose(P), features)``. Conversely, the\\n\"\n        \"matrix  ``f = numpy.dot(P, C)`` is the best possible rank-nComponents\\n\"\n        \"approximation to the matrix 'features' under the least-squares criterion.\\n\\n\"\n        \"See principleComponents_ in the C++ documentation for more detailed\\ninformation.\\n\\n\");\n\n    PLSAOptions options;\n\n    def(\"pLSA\", registerConverters(&pythonPLSA<double>),\n        (arg(\"features\"), arg(\"nComponents\"), arg(\"nIterations\") = options.max_iterations,\n         arg(\"minGain\") = options.min_rel_gain, arg(\"normalize\") = options.normalized_component_weights),\n        \"\\nPerform probabilistic latent semantic analysis. \\n\\n\"\n        \"The imput matrix 'features' must have shape (nFeatures*nSamples). PCA will\\n\"\n        \"reduce it to a smaller matrix 'C' with shape (nComponents*nSamples) that \\n\"\n        \"preserves as much information as possible. Specifically, the call::\\n\\n\"\n        \"    P, C = pLSA(features, 3)\\n\\n\"\n        \"returns a projection matrix 'P' with shape (nComponents*nFeatures)\\n\"\n        \"such that the matrix ``f = numpy.dot(P, C)`` is a rank-nComponents matrix\\n\"\n        \"that approximates the matrix 'features' well under the pLSA criterion.\\n\"\n        \"Note that the result of pLSA() is not unique, since the algorithm uses random\\n\"\n        \"initialization.\\n\\n\"\n        \"See pLSA_ in the C++ documentation for more detailed\\ninformation.\\n\\n\");\n}\n\nvoid defineRandomForest();\nvoid defineRandomForestOld();\n\n} // namespace vigra\n\n\nusing namespace vigra;\nusing namespace boost::python;\n\nBOOST_PYTHON_MODULE_INIT(learning)\n{\n    import_vigranumpy();\n    defineUnsupervised();\n    defineRandomForest();\n    defineRandomForestOld();\n}\n\n\n", "meta": {"hexsha": "eb0d6a75e008c3d043b58ed668c9ad7ecb259dd9", "size": 6748, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "vigranumpy/src/core/learning.cxx", "max_stars_repo_name": "burgerdev/vigra", "max_stars_repo_head_hexsha": "f9f8d0b3224f3dc89bc7d0caf1126d49f6d4a3ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vigranumpy/src/core/learning.cxx", "max_issues_repo_name": "burgerdev/vigra", "max_issues_repo_head_hexsha": "f9f8d0b3224f3dc89bc7d0caf1126d49f6d4a3ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vigranumpy/src/core/learning.cxx", "max_forks_repo_name": "burgerdev/vigra", "max_forks_repo_head_hexsha": "f9f8d0b3224f3dc89bc7d0caf1126d49f6d4a3ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6887417219, "max_line_length": 105, "alphanum_fraction": 0.5712803794, "num_tokens": 1420, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2345946593579748}}
{"text": "//\n//  cvx_pose_estimation.cpp\n//  LoopClosure\n//\n//  Created by jimmy on 2016-03-31.\n//  Copyright © 2016 jimmy. All rights reserved.\n//\n\n#include \"cvx_pose_estimation.hpp\"\n#include <iostream>\n#include <Eigen/Geometry>\n#include \"cvx_calib3d.hpp\"\n\nusing std::cout;\nusing std::endl;\nusing cv::Mat;\n\n\nstruct HypotheseLoss\n{\n    double loss_;\n    Mat rvec_;       // rotation     for 3D --> 2D projection\n    Mat tvec_;       // translation  for 3D --> 2D projection\n    Mat affine_;     //              for 3D --> 3D camera to world transformation\n    vector<unsigned int> inlier_indices_;         // camera coordinate index\n    vector<unsigned int> inlier_candidate_world_pts_indices_; // candidate world point index\n    \n    // store all inliers from preemptive ransac\n    vector<cv::Point3d> camera_pts_;\n    vector<cv::Point3d> wld_pts_;\n    \n    HypotheseLoss()\n    {\n        loss_ = INT_MAX;\n    }\n    HypotheseLoss(const double loss)\n    {\n        loss_  = loss;\n    }\n    \n    HypotheseLoss(const HypotheseLoss & other)\n    {\n        loss_ = other.loss_;\n        rvec_ = other.rvec_;\n        tvec_ = other.tvec_;\n        affine_ = other.affine_;\n        inlier_indices_.clear();\n        inlier_indices_.resize(other.inlier_indices_.size());\n        inlier_candidate_world_pts_indices_.clear();\n        inlier_candidate_world_pts_indices_.resize(other.inlier_candidate_world_pts_indices_.size());\n        for(int i = 0; i<other.inlier_indices_.size(); i++) {\n            inlier_indices_[i] = other.inlier_indices_[i];\n        }\n        for(int i = 0; i<other.inlier_candidate_world_pts_indices_.size(); i++){\n            inlier_candidate_world_pts_indices_[i] = other.inlier_candidate_world_pts_indices_[i];\n        }\n        if(inlier_candidate_world_pts_indices_.size() != 0){\n            assert(inlier_indices_.size() == inlier_candidate_world_pts_indices_.size());\n        }\n        \n        // copy camera points and world coordinate points\n        if(other.camera_pts_.size() > 0)\n        {\n            camera_pts_.resize(other.camera_pts_.size());\n            wld_pts_.resize(other.wld_pts_.size());\n            \n            assert(camera_pts_.size() == wld_pts_.size());\n            for(int i = 0; i<camera_pts_.size(); i++)\n            {\n                camera_pts_[i] = other.camera_pts_[i];\n                wld_pts_[i] = other.wld_pts_[i];\n            }\n        }\n    }    \n    \n    bool operator < (const HypotheseLoss & other) const\n    {\n        return loss_ < other.loss_;\n    }\n    \n    HypotheseLoss & operator = (const HypotheseLoss & other)\n    {\n        if (&other == this) {\n            return *this;\n        }\n        loss_ = other.loss_;\n        rvec_ = other.rvec_;\n        tvec_ = other.tvec_;\n        affine_ = other.affine_;\n        inlier_indices_.clear();\n        inlier_indices_.resize(other.inlier_indices_.size());\n        inlier_candidate_world_pts_indices_.clear();\n        inlier_candidate_world_pts_indices_.resize(other.inlier_candidate_world_pts_indices_.size());\n        for(int i = 0; i<other.inlier_indices_.size(); i++) {\n            inlier_indices_[i] = other.inlier_indices_[i];\n        }\n        for(int i = 0; i<other.inlier_candidate_world_pts_indices_.size(); i++){\n            inlier_candidate_world_pts_indices_[i] = other.inlier_candidate_world_pts_indices_[i];\n        }\n        if(inlier_candidate_world_pts_indices_.size() != 0){\n            assert(inlier_indices_.size() == inlier_candidate_world_pts_indices_.size());\n        }\n        \n        // copy camera points and world coordinate points\n        if(other.camera_pts_.size() > 0)\n        {\n            camera_pts_.resize(other.camera_pts_.size());\n            wld_pts_.resize(other.wld_pts_.size());\n            \n            assert(camera_pts_.size() == wld_pts_.size());\n            for(int i = 0; i<camera_pts_.size(); i++)\n            {\n                camera_pts_[i] = other.camera_pts_[i];\n                wld_pts_[i] = other.wld_pts_[i];\n            }\n        }\n        \n        return *this;\n    }\n};\n\n\n\nbool CvxPoseEstimation::preemptiveRANSAC3DOneToMany(const vector<cv::Point3d> & camera_pts,\n                                                    const vector<vector<cv::Point3d>> & candidate_wld_pts,\n                                                    const PreemptiveRANSAC3DParameter & param,\n                                                    cv::Mat & camera_pose)\n{\n    assert(camera_pts.size() == candidate_wld_pts.size());\n    if (camera_pts.size() < 500) {\n        return false;\n    }\n    \n    const int num_iteration = 2048;\n    int K = 1024;\n    const int N = (int)camera_pts.size();\n    const int B = param.sample_number_;\n    \n    vector<cv::Mat > affine_candidate;\n    for (int i = 0; i<num_iteration; i++) {\n        \n        int k1 = 0;\n        int k2 = 0;\n        int k3 = 0;\n        int k4 = 0;\n        \n        do{\n            k1 = rand()%N;\n            k2 = rand()%N;\n            k3 = rand()%N;\n            k4 = rand()%N;\n        }while (k1 == k2 || k1 == k3 || k1 == k4 ||\n                k2 == k3 || k2 == k4 || k3 == k4);\n        \n        vector<cv::Point3d> sampled_camera_pts;\n        vector<cv::Point3d> sampled_wld_pts;\n        \n        sampled_camera_pts.push_back(camera_pts[k1]);\n        sampled_camera_pts.push_back(camera_pts[k2]);\n        sampled_camera_pts.push_back(camera_pts[k3]);\n        sampled_camera_pts.push_back(camera_pts[k4]);\n        \n        sampled_wld_pts.push_back(candidate_wld_pts[k1][0]);\n        sampled_wld_pts.push_back(candidate_wld_pts[k2][0]);\n        sampled_wld_pts.push_back(candidate_wld_pts[k3][0]);\n        sampled_wld_pts.push_back(candidate_wld_pts[k4][0]);\n        \n        Mat affine;    \n        CvxCalib3D::KabschTransform(sampled_camera_pts, sampled_wld_pts, affine);\n        affine_candidate.push_back(affine);\n        if (affine_candidate.size() > K) {\n            printf(\"initialization repeat %d times\\n\", i);\n            break;\n        }\n    }\n    printf(\"init camera parameter number is %lu\\n\", affine_candidate.size());\n    \n    vector<HypotheseLoss> losses;\n    for (int i = 0; i<affine_candidate.size(); i++) {\n        HypotheseLoss hyp(0.0);\n        hyp.affine_ = affine_candidate[i];\n        losses.push_back(hyp);\n    }\n    \n    double threshold = param.dis_threshold_;\n    while (losses.size() > 1) {\n        // sample random set\n        vector<cv::Point3d> sampled_camera_pts;\n        vector< vector<cv::Point3d> > sampled_wld_pts;  // one camera point may have multiple world points correspondences\n        vector<int> sampled_indices;\n        for (int i =0; i<B; i++) {\n            int index = rand()%N;\n            sampled_camera_pts.push_back(camera_pts[index]);\n            sampled_wld_pts.push_back(candidate_wld_pts[index]);\n            sampled_indices.push_back(index);\n        }\n        \n        // count outliers\n        for (int i = 0; i<losses.size(); i++) {\n            // evaluate the accuracy by check transformation\n            vector<cv::Point3d> transformed_pts;\n            CvxCalib3D::rigidTransform(sampled_camera_pts, losses[i].affine_, transformed_pts);\n            \n            // check minimum distance from transformed points to world coordiante\n            for (int j = 0; j<transformed_pts.size(); j++) {\n                double min_dis = threshold * 2;\n                int min_index = -1;\n                for (int k = 0; k<sampled_wld_pts[j].size(); k++) {\n                    cv::Point3d dif = transformed_pts[j] - sampled_wld_pts[j][k];\n                    double dis = cv::norm(dif);\n                    if (dis < min_dis) {\n                        min_dis = dis;\n                        min_index = k;\n                    }\n                } // end of k\n                \n                if (min_dis > threshold) {\n                    losses[i].loss_ += 1.0;\n                }\n                else {\n                    losses[i].inlier_indices_.push_back(sampled_indices[j]);\n                    losses[i].inlier_candidate_world_pts_indices_.push_back(min_index);\n                }\n            } // end of j\n            assert(losses[i].inlier_indices_.size() == losses[i].inlier_candidate_world_pts_indices_.size());\n            // printf(\"inlier number is %lu\\n\", losses[i].inlier_indices_.size());\n        }\n        //getchar();\n        \n        std::sort(losses.begin(), losses.end());\n        losses.resize(losses.size()/2);\n        \n        for (int i = 0; i<losses.size(); i++) {\n         //   printf(\"after: loss is %lf\\n\", losses[i].loss_);\n         //   printf(\"inlier number is %lu\\n\", losses[i].inlier_indices_.size());\n        }\n        // printf(\"\\n\\n\");\n        \n        // refine by inliers\n        for (int i = 0; i<losses.size(); i++) {\n            // number of inliers is larger than minimum configure\n            if (losses[i].inlier_indices_.size() > 4) {\n                vector<cv::Point3d> inlier_camera_pts;\n                vector<cv::Point3d> inlier_wld_pts;\n                for (int j = 0; j < losses[i].inlier_indices_.size(); j++) {\n                    int index = losses[i].inlier_indices_[j];\n                    int wld_index = losses[i].inlier_candidate_world_pts_indices_[j];\n                    inlier_camera_pts.push_back(camera_pts[index]);\n                    inlier_wld_pts.push_back(candidate_wld_pts[index][wld_index]);\n                }\n                Mat affine;\n                \n                CvxCalib3D::KabschTransform(inlier_camera_pts, inlier_wld_pts, affine);\n                losses[i].affine_ = affine;\n                losses[i].inlier_indices_.clear();\n                losses[i].inlier_candidate_world_pts_indices_.clear();  \n            }\n        }\n    }\n    assert(losses.size() == 1);\n    \n    camera_pose = cv::Mat::eye(4, 4, CV_64F);\n    losses[0].affine_.copyTo(camera_pose(cv::Rect(0, 0, 4, 3)));\n    //cout<<\"camera pose\\n\"<<camera_pose<<endl;\n    return true;\n}\n\n\n\nMat CvxPoseEstimation::rotationToEularAngle(const cv::Mat & rot)\n{\n    assert(rot.rows == 3 && rot.cols == 3);\n    assert(rot.type() == CV_64FC1);\n    \n    // https://d3cw3dd2w32x2b.cloudfront.net/wp-content/uploads/2012/07/euler-angles.pdf\n    double m00 = rot.at<double>(0, 0);\n    double m01 = rot.at<double>(0, 1);\n    double m02 = rot.at<double>(0, 2);\n    double m10 = rot.at<double>(1, 0);\n    double m11 = rot.at<double>(1, 1);\n    double m12 = rot.at<double>(1, 2);\n    double m20 = rot.at<double>(2, 0);\n    double m21 = rot.at<double>(2, 1);\n    double m22 = rot.at<double>(2, 2);\n    double theta1 = atan2(m12, m22);\n    double c2 = sqrt(m00 * m00 + m01 * m01);\n    double theta2 = atan2(-m02, c2);\n    double s1 = sin(theta1);\n    double c1 = cos(theta1);\n    double theta3 = atan2(s1*m20 - c1 * m10, c1*m11 - s1*m21);\n    \n    double scale = 180.0/3.14159;\n    theta1 *= scale;\n    theta2 *= scale;\n    theta3 *= scale;\n    \n    Mat eular_angle = cv::Mat::zeros(3, 1, CV_64FC1);\n    eular_angle.at<double>(0, 0) = theta1;\n    eular_angle.at<double>(1, 0) = theta2;\n    eular_angle.at<double>(2, 0) = theta3;\n    return eular_angle;\n    //printf(\"Eular angle %lf %lf %lf\\n\", theta1, theta2, theta3);    \n}\n\nvoid CvxPoseEstimation::poseDistance(const cv::Mat & src_pose,\n                                     const cv::Mat & dst_pose,\n                                     double & angle_distance,\n                                     double & euclidean_disance)\n{\n    // http://chrischoy.github.io/research/measuring-rotation/\n    assert(src_pose.type() == CV_64F);\n    assert(dst_pose.type() == CV_64F);\n    \n    Mat src_R = src_pose(cv::Rect(0, 0, 3, 3));\n    Mat dst_R = dst_pose(cv::Rect(0, 0, 3, 3));\n    \n    double scale = 180.0/3.14159;    \n    \n    Mat q1 = CvxPoseEstimation::rotationToQuaternion(src_R);\n    Mat q2 = CvxPoseEstimation::rotationToQuaternion(dst_R);\n    double val_dot = fabs(q1.dot(q2));\n\n    //double dot = r1.dot(r2);\n    //angle_distance = acos(dot) * scale;\n    angle_distance = 2.0 * acos(val_dot) * scale;\n    \n    euclidean_disance = 0.0;\n    double dx = src_pose.at<double>(0, 3) - dst_pose.at<double>(0, 3);\n    double dy = src_pose.at<double>(1, 3) - dst_pose.at<double>(1, 3);\n    double dz = src_pose.at<double>(2, 3) - dst_pose.at<double>(2, 3);\n    euclidean_disance += dx * dx;\n    euclidean_disance += dy * dy;\n    euclidean_disance += dz * dz;\n    euclidean_disance = sqrt(euclidean_disance);\n //   printf(\"location distance are %f %f %f\\n\", dx, dy, dz);\n}\n\n\nMat CvxPoseEstimation::rotationToQuaternion(const cv::Mat & rot)\n{\n    assert(rot.type() == CV_64FC1);\n    assert(rot.rows == 3 && rot.cols == 3);\n    \n    Mat ret = cv::Mat::zeros(4, 1, CV_64FC1);\n    \n    float r11 = rot.at<double>(0, 0);\n    float r12 = rot.at<double>(0, 1);\n    float r13 = rot.at<double>(0, 2);\n    float r21 = rot.at<double>(1, 0);\n    float r22 = rot.at<double>(1, 1);\n    float r23 = rot.at<double>(1, 2);\n    float r31 = rot.at<double>(2, 0);\n    float r32 = rot.at<double>(2, 1);\n    float r33 = rot.at<double>(2, 2);\n    \n    float q0 = ( r11 + r22 + r33 + 1.0f) / 4.0f;\n    float q1 = ( r11 - r22 - r33 + 1.0f) / 4.0f;\n    float q2 = (-r11 + r22 - r33 + 1.0f) / 4.0f;\n    float q3 = (-r11 - r22 + r33 + 1.0f) / 4.0f;\n    if(q0 < 0.0f) q0 = 0.0f;\n    if(q1 < 0.0f) q1 = 0.0f;\n    if(q2 < 0.0f) q2 = 0.0f;\n    if(q3 < 0.0f) q3 = 0.0f;\n    q0 = sqrt(q0);\n    q1 = sqrt(q1);\n    q2 = sqrt(q2);\n    q3 = sqrt(q3);\n    if(q0 >= q1 && q0 >= q2 && q0 >= q3) {\n        q0 *= +1.0f;\n        q1 *= CvxPoseEstimation::SIGN(r32 - r23);\n        q2 *= CvxPoseEstimation::SIGN(r13 - r31);\n        q3 *= CvxPoseEstimation::SIGN(r21 - r12);\n    } else if(q1 >= q0 && q1 >= q2 && q1 >= q3) {\n        q0 *= CvxPoseEstimation::SIGN(r32 - r23);\n        q1 *= +1.0f;\n        q2 *= CvxPoseEstimation::SIGN(r21 + r12);\n        q3 *= CvxPoseEstimation::SIGN(r13 + r31);\n    } else if(q2 >= q0 && q2 >= q1 && q2 >= q3) {\n        q0 *= CvxPoseEstimation::SIGN(r13 - r31);\n        q1 *= CvxPoseEstimation::SIGN(r21 + r12);\n        q2 *= +1.0f;\n        q3 *= CvxPoseEstimation::SIGN(r32 + r23);\n    } else if(q3 >= q0 && q3 >= q1 && q3 >= q2) {\n        q0 *= CvxPoseEstimation::SIGN(r21 - r12);\n        q1 *= CvxPoseEstimation::SIGN(r31 + r13);\n        q2 *= CvxPoseEstimation::SIGN(r32 + r23);\n        q3 *= +1.0f;\n    } else {\n        printf(\"q0, q1, q2, q3: %f %f %f %f\\n\", q0, q1, q2, q3);\n        printf(\"Error: rotation matrix quaternion.\\n\");\n        cout<<\"rotation matrix is \\n\"<<rot<<endl;\n        assert(0);\n    }\n    float r = CvxPoseEstimation::NORM(q0, q1, q2, q3);\n    q0 /= r;\n    q1 /= r;\n    q2 /= r;\n    q3 /= r;\n    \n    ret.at<double>(0, 0) = q0;\n    ret.at<double>(1, 0) = q1;\n    ret.at<double>(2, 0) = q2;\n    ret.at<double>(3, 0) = q3;\n    return ret;\n}\n\nMat CvxPoseEstimation::quaternionToRotation(const cv::Mat & q)\n{\n    assert(q.type() == CV_64FC1);\n    assert(q.rows == 4);\n    assert(q.cols == 1);\n    \n    double x = q.at<double>(0, 0);\n    double y = q.at<double>(1, 0);\n    double z = q.at<double>(2, 0);\n    double w = q.at<double>(3, 0);\n    \n    Eigen::Quaterniond quat(w, x, y, z);\n    \n    Eigen::Matrix<double, 3, 3> eig_mat = quat.matrix();\n    cv::Mat rot = cv::Mat::zeros(3, 3, CV_64FC1);\n    for (int r = 0; r<3; r++) {\n        for (int c = 0; c<3; c++) {\n            rot.at<double>(r, c) = eig_mat(r, c);\n        }\n    }    \n    return rot;\n}\n\n\n\n\n", "meta": {"hexsha": "cc1fbcf4fe83aba47e9f194a59e73e5c9d83dca0", "size": 15276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pose_estimation/cvx_pose_estimation.cpp", "max_stars_repo_name": "LiliMeng/btrf", "max_stars_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-10-28T15:24:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T13:51:05.000Z", "max_issues_repo_path": "src/pose_estimation/cvx_pose_estimation.cpp", "max_issues_repo_name": "LiliMeng/btrf", "max_issues_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pose_estimation/cvx_pose_estimation.cpp", "max_forks_repo_name": "LiliMeng/btrf", "max_forks_repo_head_hexsha": "c13da164b11c5ada522fa40deeaffc32192c4bf9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-11-08T16:10:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-21T03:40:02.000Z", "avg_line_length": 35.2794457275, "max_line_length": 122, "alphanum_fraction": 0.5520424195, "num_tokens": 4361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23459465935797474}}
{"text": "//==================================================================================================\n/*!\n  @file\n\n    @copyright 2016 NumScale SAS\n\n  Distributed under the Boost Software License, Version 1.0.\n  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_DEC_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_DEC_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n  /*!\n    @ingroup group-arithmetic\n    This function object returns  its parameter decremented by 1.\n\n    @par Header <boost/simd/function/dec.hpp>\n\n    @par Decorators\n\n    - saturated_ ensures that @c saturated_(dec)(x) will never be\n      strictly greater than @c x,\n      avoiding the wrap around from @ref Valmin to\n      @ref Valmax with integer types\n\n    @see inc, minus\n\n    @par Example:\n\n      @snippet dec.cpp dec\n\n    @par Possible output:\n\n      @snippet dec.txt dec\n  **/\n  Value dec(Value const& x);\n} }\n#endif\n\n#include <boost/simd/function/scalar/dec.hpp>\n#include <boost/simd/function/simd/dec.hpp>\n\n#endif\n", "meta": {"hexsha": "4de353e2184737bea0537d4d901cc4af5430fc12", "size": 1174, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/dec.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/function/dec.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/dec.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 23.9591836735, "max_line_length": 100, "alphanum_fraction": 0.5843270869, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.23459465935797474}}
{"text": "/*  _______________________________________________________________________\n\n    DAKOTA: Design Analysis Kit for Optimization and Terascale Applications\n    Copyright 2014 Sandia Corporation.\n    This software is distributed under the GNU Lesser General Public License.\n    For more information, see the README file in the top Dakota directory.\n    _______________________________________________________________________ */\n\n//- Class:\t NonDGlobalReliability\n//- Description: Implementation code for NonDGlobalReliability class\n//- Owner:       Barron Bichon, Mike Eldred\n//- Checked by:\n//- Version:\n\n#include \"dakota_system_defs.hpp\"\n#include \"dakota_data_io.hpp\"\n#include \"NonDGlobalReliability.hpp\"\n#include \"NonDLHSSampling.hpp\"\n//#include \"DDACEDesignCompExp.hpp\"\n//#include \"FSUDesignCompExp.hpp\"\n#include \"NonDAdaptImpSampling.hpp\"\n//#ifdef HAVE_ACRO\n//#include \"COLINOptimizer.hpp\"\n//#endif\n#include \"RecastModel.hpp\"\n#include \"DataFitSurrModel.hpp\"\n#include \"DakotaApproximation.hpp\"\n#include \"ProblemDescDB.hpp\"\n#ifdef HAVE_NCSU\n#include \"NCSUOptimizer.hpp\"\n#endif\n#include \"pecos_stat_util.hpp\"\n#include <boost/lexical_cast.hpp>\n\n//#define DEBUG\n//#define DEGUG_PLOTS\n\nstatic const char rcsId[] = \"@(#) $Id: NonDGlobalReliability.cpp 4058 2006-10-25 01:39:40Z mseldre $\";\n\nextern \"C\" {\n#ifdef DAKOTA_F90\n  #if defined(HAVE_CONFIG_H) && !defined(DISABLE_DAKOTA_CONFIG_H)\n\n  // Deprecated; continue to support legacy, clashing macros for ONE RELEASE\n  #define BVLS_WRAPPER_FC FC_FUNC_(bvls_wrapper,BVLS_WRAPPER)\n  void BVLS_WRAPPER_FC( Dakota::Real* a, int& m, int& n, Dakota::Real* b,\n\t\t        Dakota::Real* bnd, Dakota::Real* x, Dakota::Real& rnorm,\n\t\t        int& nsetp, Dakota::Real* w, int* index, int& ierr );\n  #else\n\n  // Use the CMake-generated fortran name mangling macros (eliminate warnings)\n  #include \"dak_f90_config.h\"\n  #define BVLS_WRAPPER_FC DAK_F90_GLOBAL_(bvls_wrapper,BVLS_WRAPPER)\n  void BVLS_WRAPPER_FC( Dakota::Real* a, int& m, int& n, Dakota::Real* b,\n\t\t        Dakota::Real* bnd, Dakota::Real* x, Dakota::Real& rnorm,\n\t\t        int& nsetp, Dakota::Real* w, int* index, int& ierr );\n  #endif // HAVE_CONFIG_H and !DISABLE_DAKOTA_CONFIG_H\n#endif // DAKOTA_F90\n}\n\nnamespace Dakota {\n\n// initialization of statics\nNonDGlobalReliability* NonDGlobalReliability::nondGlobRelInstance(NULL);\n\n\nNonDGlobalReliability::\nNonDGlobalReliability(ProblemDescDB& problem_db, Model& model): \n  NonDReliability(problem_db, model),\n  meritFunctionType(AUGMENTED_LAGRANGIAN_MERIT), dataOrder(1)\n{\n  if (mppSearchType < EGRA_X) {\n    Cerr << \"Error: only x-space and u-space EGRA are currently supported in \"\n\t << \"global_reliability.\"<< std::endl;\n    abort_handler(-1); \n  }\n\n  // standard reliability indices are not defined and should be precluded\n  // via the input spec.  requestedRelLevels is default sized in NonD and\n  // cannot be used for the empty() test below.\n  if (!probDescDB.get_rva(\"method.nond.reliability_levels\").empty() ||\n      respLevelTarget == RELIABILITIES) {\n    Cerr << \"Error: reliability indices are not defined for global reliability \"\n\t << \"methods.  Use generalized reliability instead.\" << std::endl;\n    abort_handler(-1); \n  }\n\n  // requestedProbLevels & requestedGenRelLevels are not yet supported\n  // since PMA EGRA requires additional R&D.  Note: requestedProbLevels and\n  // requestedGenRelLevels are default sized in NonD and cannot be used for\n  // the empty() tests below.\n  if (!probDescDB.get_rva(\"method.nond.probability_levels\").empty() ||\n      !probDescDB.get_rva(\"method.nond.gen_reliability_levels\").empty()) {\n    Cerr << \"Error: Inverse reliability mappings not currently supported in \"\n\t << \"global_reliability.\"<< std::endl;\n    abort_handler(-1); \n  }\n\n#ifndef DAKOTA_F90\n  if (meritFunctionType == LAGRANGIAN_MERIT) {\n    Cerr << \"Error: F90 required for standard Lagrangian merit function in \"\n\t << \"global_reliability.\"<< std::endl;\n    abort_handler(-1); \n  }\n#endif // DAKOTA_F90\n\n  // Size the output arrays, augmenting sizing in NonDReliability.  Relative to\n  // other NonD methods, the output storage for reliability methods is greater\n  // since there may be differences between requested and computed levels for\n  // the same level type (the request is not always achieved) and since\n  // probability and reliability are carried along in parallel (due to their\n  // direct correspondence).  Relative to NonDLocalReliability, RelLevels are\n  // ignored since probabilities are estimated directly from MMAIS.\n  size_t i;\n  for (i=0; i<numFunctions; i++) {\n    size_t num_levels = requestedRespLevels[i].length() + \n      requestedProbLevels[i].length() + requestedGenRelLevels[i].length();\n    computedRespLevels[i].resize(num_levels);\n    computedProbLevels[i].resize(num_levels);\n    computedGenRelLevels[i].resize(num_levels);\n  }\n\n  // The Gaussian process model of the limit state in u-space [G-hat(u)] is \n  // constructed here one time.\n  \n  // Always build a global Gaussian process model.  No correction is needed.\n  String approx_type = \"global_kriging\";\n  if (probDescDB.get_short(\"method.nond.emulator\") == GP_EMULATOR)\n    approx_type = \"global_gaussian\";\n\n  unsigned short sample_type = SUBMETHOD_DEFAULT;\n  UShortArray approx_order; // not used for GP/kriging\n  short corr_order = -1, corr_type = NO_CORRECTION,\n    active_view = iteratedModel.current_variables().view().first;\n  if (probDescDB.get_bool(\"method.derivative_usage\")) {\n    if (approx_type == \"global_gaussian\") {\n      Cerr << \"\\nError: efficient_global does not support gaussian_process \"\n\t   << \"when derivatives present; use kriging instead.\" << std::endl;\n      abort_handler(-1);\n    }\n    if (iteratedModel.gradient_type() != \"none\") dataOrder |= 2;\n    if (iteratedModel.hessian_type()  != \"none\") dataOrder |= 4;\n  }\n  String sample_reuse\n    = (active_view == RELAXED_ALL || active_view == MIXED_ALL) ? \"all\" : \"none\";\n\n  int db_samples = probDescDB.get_int(\"method.samples\");  \n  int samples = (db_samples > 0) ? db_samples : \n    (numContinuousVars+1)*(numContinuousVars+2)/2;\n\n  int lhs_seed = probDescDB.get_int(\"method.random_seed\");\n  const String& rng = probDescDB.get_string(\"method.random_number_generator\");\n  bool vary_pattern = false; // for consistency across outer loop invocations\n  // get point samples file\n  const String& import_pts_file\n    = probDescDB.get_string(\"method.import_build_points_file\");\n  if (!import_pts_file.empty())\n    { samples = 0; sample_reuse = \"all\"; }\n\n  //int symbols = samples; // symbols needed for DDACE\n  Iterator dace_iterator;\n  NonDLHSSampling* lhs_sampler_rep;\n  // instantiate the Nataf Recast and Gaussian Process DataFit recursions\n  if (mppSearchType == EGRA_X) { // Recast( DataFit( iteratedModel ) )\n\n    // The following uses on the fly derived ctor:\n    lhs_sampler_rep = new NonDLHSSampling(iteratedModel, sample_type, samples,\n      lhs_seed, rng, vary_pattern, ACTIVE_UNIFORM);\n    //unsigned short dace_method = SUBMETHOD_LHS; // submethod enum\n    //lhs_sampler_rep = new DDACEDesignCompExp(iteratedModel, samples, symbols,\n    //                                         lhs_seed, dace_method);\n    //unsigned short dace_method = FSU_HAMMERSLEY;\n    //lhs_sampler_rep = new FSUDesignCompExp(iteratedModel, samples, lhs_seed,\n    //                                       dace_method);\n    dace_iterator.assign_rep(lhs_sampler_rep, false);\n\n    // Construct g-hat(x) using a GP approximation over the active/uncertain\n    // vars (same view as iteratedModel: not the typical All view for DACE).\n    // For RBDO with GP over {u}+{d}, view set to All from all_variables spec.\n    Model g_hat_x_model;\n    IntSet surr_fn_indices; // Only want functions with requested levels\n    ActiveSet set = iteratedModel.current_response().active_set();// copy\n    set.request_values(0);\n    for (i=0; i<numFunctions; ++i)\n      if (!computedRespLevels[i].empty()) // sized to total req levels above\n    \t{ set.request_value(dataOrder, i); surr_fn_indices.insert(i); }\n    dace_iterator.active_set(set);\n    //const Variables& curr_vars = iteratedModel.current_variables();\n    ActiveSet gp_set = iteratedModel.current_response().active_set(); // copy\n    gp_set.request_values(1);// no surr deriv evals, but GP may be grad-enhanced\n    g_hat_x_model.assign_rep(new DataFitSurrModel(dace_iterator, iteratedModel,\n      gp_set, approx_type, approx_order, corr_type, corr_order, dataOrder,\n      outputLevel, sample_reuse, import_pts_file,\n      probDescDB.get_ushort(\"method.import_build_format\"),\n      probDescDB.get_bool(\"method.import_build_active_only\"),\n      probDescDB.get_string(\"method.export_approx_points_file\"),\n      probDescDB.get_ushort(\"method.export_approx_format\")), false);\n    g_hat_x_model.surrogate_function_indices(surr_fn_indices);\n\n    // Recast g-hat(x) to G-hat(u)\n    transform_model(g_hat_x_model, uSpaceModel, true, 5.);// truncated dist bnds\n  }\n  else { // DataFit( Recast( iteratedModel ) )\n\n    // Recast g(x) to G(u)\n    Model g_u_model;\n    transform_model(iteratedModel, g_u_model, true, 5.); // truncated dist bnds\n\n    // For additional generality, could develop on the fly envelope ctor:\n    //Iterator dace_iterator(g_u_model, dace_method, ...);\n\n    // The following use on-the-fly derived ctors:\n    lhs_sampler_rep = new NonDLHSSampling(g_u_model, sample_type,\n      samples, lhs_seed, rng, vary_pattern, ACTIVE_UNIFORM);\n    //unsigned short dace_method = SUBMETHOD_LHS; // submethod enum\n    //lhs_sampler_rep = new DDACEDesignCompExp(g_u_model, samples, symbols,\n    //                                         lhs_seed, dace_method);\n    //unsigned short dace_method = FSU_HAMMERSLEY;\n    //lhs_sampler_rep = new FSUDesignCompExp(g_u_model, samples, lhs_seed,\n    //                                       dace_method);\n    dace_iterator.assign_rep(lhs_sampler_rep, false);\n    // share nataf instance to provide data for performing inverse transforms\n    lhs_sampler_rep->initialize_random_variables(natafTransform); // shared rep\n\n    // Construct G-hat(u) using a GP approximation over the active/uncertain\n    // variables (using the same view as iteratedModel/g_u_model: not the\n    // typical All view for DACE).\n    // For RBDO with GP over {u}+{d}, view set to All from all_variables spec.\n    IntSet surr_fn_indices; // Only want functions with requested levels\n    ActiveSet set = iteratedModel.current_response().active_set();// copy\n    set.request_values(0);\n    for (i=0; i<numFunctions; ++i)\n      if (!computedRespLevels[i].empty()) // sized to total req levels above\n    \t{ set.request_value(dataOrder, i); surr_fn_indices.insert(i); }\n    dace_iterator.active_set(set);\n\n    //const Variables& g_u_vars = g_u_model.current_variables();\n    ActiveSet gp_set = g_u_model.current_response().active_set(); // copy\n    gp_set.request_values(1);// no surr deriv evals, but GP may be grad-enhanced\n    uSpaceModel.assign_rep(new DataFitSurrModel(dace_iterator, g_u_model,\n      gp_set, approx_type, approx_order, corr_type, corr_order, dataOrder,\n      outputLevel, sample_reuse, import_pts_file,\n      probDescDB.get_ushort(\"method.import_build_format\"),\n      probDescDB.get_bool(\"method.import_build_active_only\"),\n      probDescDB.get_string(\"method.export_approx_points_file\"),\n      probDescDB.get_ushort(\"method.export_approx_format\")), false);\n    uSpaceModel.surrogate_function_indices(surr_fn_indices);\n  }\n\n  // Following this ctor, IteratorScheduler::init_iterator() initializes the\n  // parallel configuration for NonDGlobalReliability + iteratedModel using\n  // NonDGlobalReliability's maxEvalConcurrency. During uSpaceModel construction\n  // above, DataFitSurrModel::derived_init_communicators() initializes the\n  // parallel configuration for dace_iterator + iteratedModel using\n  // dace_iterator's maxEvalConcurrency.  The only iteratedModel concurrency\n  // currently exercised is that used by dace_iterator within the initial GP\n  // construction, but the NonDGlobalReliability maxEvalConcurrency must still\n  // be set so as to avoid parallel configuration errors resulting from\n  // avail_procs > max_concurrency within IteratorScheduler::init_iterator().\n  // A max of the local derivative concurrency and the DACE concurrency is used\n  // for this purpose.\n  maxEvalConcurrency = std::max(maxEvalConcurrency,\n\t\t\t\tdace_iterator.maximum_evaluation_concurrency());\n\n  // Configure a RecastModel with one objective and no constraints using the\n  // alternate minimalist constructor.  The RIA/PMA expected improvement/\n  // expected feasibility formulations may vary with the level requests, so\n  // the recast fn pointers are reset for each level within the run fn.\n  SizetArray recast_vars_comps_total;  // default: empty; no change in size\n  BitArray all_relax_di, all_relax_dr; // default: empty; no discrete relaxation\n  short recast_resp_order = 1; // nongradient-based optimizers\n  mppModel.assign_rep(\n    new RecastModel(uSpaceModel, recast_vars_comps_total, all_relax_di,\n\t\t    all_relax_dr, 1, 0, 0, recast_resp_order), false);\n\n  // For formulations with one objective and one equality constraint,\n  // use the following instead:\n  //mppModel.assign_rep(new RecastModel(uSpaceModel, ..., 1, 1, 0, ...), false);\n  //RealVector nln_eq_targets(1, 0.);\n  //mppModel.nonlinear_eq_constraint_targets(nln_eq_targets);\n\n  // must use alternate NoDB ctor chain\n  int max_iter = 1000, max_eval = 10000;\n  double min_box_size = 1.e-15, vol_box_size = 1.e-15;\n#ifdef HAVE_NCSU  \n  mppOptimizer.assign_rep(new NCSUOptimizer(mppModel, max_iter, max_eval,\n\t\t\t\t\t    min_box_size, vol_box_size), false);\n  //#ifdef HAVE_ACRO\n  //int coliny_seed = 0; // system-generated, for now\n  //mppOptimizer.assign_rep(new\n  //  COLINOptimizer<coliny::DIRECT>(mppModel, coliny_seed), false);\n  //mppOptimizer.assign_rep(new\n  //  COLINOptimizer<coliny::EAminlp>(mppModel, coliny_seed), false);\n  //#endif\n#else\n  Cerr << \"NCSU DIRECT Optimizer is not available to use in the MPP search \" \n       << \"in global reliability optimization:  aborting process.\" << std::endl;\n        abort_handler(-1);\n#endif //HAVE_NCSU\n\n  // The importance sampler uses uSpaceModel (without additional recasting)\n  // and may be constructed here.  Thus, NonDGlobal applies integration\n  // refinement to the G-hat(u) surrogate.  Behavior needs to be repeatable\n  // and AIS is not part of the EGRA spec: either reuse lhs_seed or hardwire.\n  int refine_samples = 1000, refine_seed = 123457;\n  // we pass a u-space model and enforce the EGRA GP bounds on the samples;\n  // extreme values are needed to define bounds for outer PDF bins.\n  bool x_model_flag = false, use_model_bounds = true, track_extreme = pdfOutput;\n  integrationRefinement = MMAIS; vary_pattern = true;\n\n  NonDAdaptImpSampling* importance_sampler_rep = new\n    NonDAdaptImpSampling(uSpaceModel, sample_type, refine_samples, refine_seed,\n\t\t\t rng, vary_pattern, integrationRefinement, cdfFlag,\n\t\t\t x_model_flag, use_model_bounds, track_extreme);\n  importanceSampler.assign_rep(importance_sampler_rep, false);\n\n  // if approximation is built in x-space, then importanceSampler must perform\n  // inverse transformations on gp_inputs; if approximation is built in u-space,\n  // only the cdfFlag is needed to define which samples are failures\n  if (mppSearchType == EGRA_X) // share the ProbabilityTransformation rep\n    importance_sampler_rep->initialize_random_variables(natafTransform);\n}\n\n\nNonDGlobalReliability::~NonDGlobalReliability()\n{ }\n\n\nbool NonDGlobalReliability::resize()\n{\n  bool parent_reinit_comms = NonDReliability::resize();\n\n  Cerr << \"\\nError: Resizing is not yet supported in method \"\n       << method_enum_to_string(methodName) << \".\" << std::endl;\n  abort_handler(METHOD_ERROR);\n\n  return parent_reinit_comms;\n}\n\n\nvoid NonDGlobalReliability::derived_init_communicators(ParLevLIter pl_iter)\n{\n  iteratedModel.init_communicators(pl_iter, maxEvalConcurrency);\n\n  // mppModel.init_communicators() recursion is currently sufficient for\n  // uSpaceModel.  An additional uSpaceModel.init_communicators() call would be\n  // motivated by special parallel usage of uSpaceModel below that is not\n  // otherwise covered by the recursion.\n  //uSpaceMaxConcurrency = maxEvalConcurrency; // local derivative concurrency\n  //uSpaceModel.init_communicators(pl_iter, uSpaceMaxConcurrency);\n\n  // mppOptimizer and importanceSampler use NoDBBaseConstructor, so no\n  // need to manage DB list nodes at this level\n  mppOptimizer.init_communicators(pl_iter);\n  importanceSampler.init_communicators(pl_iter);\n}\n\n\nvoid NonDGlobalReliability::derived_set_communicators(ParLevLIter pl_iter)\n{\n  NonD::derived_set_communicators(pl_iter);\n\n  //uSpaceMaxConcurrency = maxEvalConcurrency; // local derivative concurrency\n  //uSpaceModel.set_communicators(pl_iter, uSpaceMaxConcurrency);\n\n  // mppOptimizer and importanceSampler use NoDBBaseConstructor, so no\n  // need to manage DB list nodes at this level\n  mppOptimizer.set_communicators(pl_iter);\n  importanceSampler.set_communicators(pl_iter);\n}\n\n\nvoid NonDGlobalReliability::derived_free_communicators(ParLevLIter pl_iter)\n{\n  // deallocate communicators for MMAIS on uSpaceModel\n  importanceSampler.free_communicators(pl_iter);\n\n  // deallocate communicators for DIRECT on mppModel\n  mppOptimizer.free_communicators(pl_iter);\n\n  //uSpaceMaxConcurrency = maxEvalConcurrency; // local derivative concurrency\n  //uSpaceModel.free_communicators(pl_iter, uSpaceMaxConcurrency);\n\n  iteratedModel.free_communicators(pl_iter, maxEvalConcurrency);\n}\n\n\nvoid NonDGlobalReliability::core_run()\n{\n  // initialize the random variable arrays and the correlation Cholesky factor\n  initialize_random_variable_parameters();\n  transform_correlations();\n\n  // set the object instance pointer for use within static member functions\n  NonDGlobalReliability* prev_grel_instance = nondGlobRelInstance;\n  nondGlobRelInstance = this;\n\n  // Optimize the GP for all levels and then use MAIS for _all_ levels\n  optimize_gaussian_process();\n  importance_sampling();\n  numRelAnalyses++;\n\n  // restore in case of recursion\n  nondGlobRelInstance = prev_grel_instance;\n}\n\n\nvoid NonDGlobalReliability::optimize_gaussian_process()\n{\n  // now that variables/labels/bounds/targets have flowed down at run-time from\n  // any higher level recursions, propagate them up the instantiate-on-the-fly\n  // Model recursion so that they are correct when they propagate back down.\n  mppModel.update_from_subordinate_model(); // depth = max\n\n  if (mppSearchType == EGRA_X) {\n    // assign non-default global variable bounds for use in DACE.\n    // This does not affect any uncertain variable distribution bounds.\n    // Note 1: the interval defined in x-space will be sampled uniformly by\n    // DACE methods, which could result in very irregular coverage in u-space.\n    // It would be better to sample uniformly in u-space.\n    // Note 2: it would be preferable to set this up in the constructor.  The\n    // EGRA_U case can do this by setting the bounds in the actualModel of the\n    // DataFitSurrModel and then having them copied in the DataFitSurrModel\n    // ctor.  The EGRA_X case needs trans_U_to_X, which isn't available until\n    // after initialize_random_variable_parameters() is executed at run time.\n    // Therefore, this case sets the bounds for the DataFitSurrModel, which are\n    // then propagated to actualModel in DataFitSurrModel::update_actual_model()\n    RealVector u_l_bnds(numContinuousVars, false), x_l_bnds,\n               u_u_bnds(numContinuousVars, false), x_u_bnds;\n    u_l_bnds = -5.; u_u_bnds = 5.;\n    for (size_t i=0; i<numContDesVars; i++)\n      { u_l_bnds[i] = -1.; u_u_bnds[i] =  1.; }\n    for (size_t i=numContDesVars+numContAleatUncVars; i<numContinuousVars; i++)\n      { u_l_bnds[i] = -1.; u_u_bnds[i] =  1.; }\n    natafTransform.trans_U_to_X(u_l_bnds, x_l_bnds);\n    natafTransform.trans_U_to_X(u_u_bnds, x_u_bnds);\n    Model& g_hat_x_model = uSpaceModel.subordinate_model();\n    g_hat_x_model.continuous_lower_bounds(x_l_bnds);\n    g_hat_x_model.continuous_upper_bounds(x_u_bnds);\n  }\n\n  // Build initial GP once for all response functions\n  uSpaceModel.build_approximation();\n  \n  // Loop over each response function in the responses specification.  It is\n  // important to note that the MPP iteration is different for each response \n  // function, and it is not possible to combine the model evaluations for\n  // multiple response functions.\n  ParLevLIter pl_iter = methodPCIter->mi_parallel_level_iterator(miPLIndex);\n  for (respFnCount=0; respFnCount<numFunctions; respFnCount++) {\n\n    // The most general case is to allow a combination of response, probability,\n    // and reliability level specifications for each response function.\n    size_t rl_len = requestedRespLevels[respFnCount].length(),\n           pl_len = requestedProbLevels[respFnCount].length(),\n           gl_len = requestedGenRelLevels[respFnCount].length(),\n           num_levels = rl_len + pl_len + gl_len;\n\n    // Loop over response/probability/reliability levels\n    for (levelCount=0; levelCount<num_levels; levelCount++) {\n\n      // The rl_len response levels are performed first using the RIA\n      // formulation, followed by the pl_len probability levels and the\n      // gl_len generalized reliability levels using the PMA formulation.\n      bool ria_flag = (levelCount < rl_len) ? true : false;\n      if (ria_flag) {\n        requestedTargetLevel = requestedRespLevels[respFnCount][levelCount];\n\tCout << \"\\n>>>>> Reliability Index Approach (RIA) for response level \"\n\t     << levelCount+1 << \" = \" << requestedTargetLevel << '\\n';\n      }\n      else if (levelCount < rl_len + pl_len) { \n\tsize_t index = levelCount-rl_len;\n\tReal p = requestedProbLevels[respFnCount][index];\n\tCout << \"\\n>>>>> Performance Measure Approach (PMA) for probability \"\n\t     << \"level \" << index+1 << \" = \" << p << '\\n';\n\trequestedTargetLevel = -Pecos::NormalRandomVariable::inverse_std_cdf(p);\n\tReal gen_beta_cdf = (cdfFlag) ?\n\t  requestedTargetLevel : -requestedTargetLevel;\n\tpmaMaximizeG = (gen_beta_cdf < 0.);\n      }\n      else {\n\tsize_t index = levelCount-rl_len-pl_len;\n\trequestedTargetLevel = requestedGenRelLevels[respFnCount][index];\n\tCout << \"\\n>>>>> Performance Measure Approach (PMA) for reliability \"\n\t     << \"level \" << index+1 << \" = \" << requestedTargetLevel << '\\n';\n\tReal gen_beta_cdf = (cdfFlag) ?\n\t  requestedTargetLevel : -requestedTargetLevel;\n\tpmaMaximizeG = (gen_beta_cdf < 0.);\n      }\n\n      bool pma_aug_lag_flag\n\t= (!ria_flag && meritFunctionType == AUGMENTED_LAGRANGIAN_MERIT);\n      if (pma_aug_lag_flag) {\n\taugLagrangeMult         = 0.;      penaltyParameter    = 1.;\n\tlastConstraintViolation = DBL_MAX; lastIterateAccepted = false;\n      }\n\n      // Iterate until EGRA converges\n      approxIters = 0;\n      approxConverged = false;\n      while (!approxConverged) {\n\n\tapproxIters++;\n\n\t// construct global optimizer and its EI/EF recast model\n\tSizet2DArray vars_map, primary_resp_map, secondary_resp_map;\n\tBoolDequeArray nonlinear_resp_map(1, BoolDeque(1, true));\n\tRecastModel* mpp_model_rep = (RecastModel*)mppModel.model_rep();\n\tif (ria_flag) {\n\t  // Standard RIA : min u'u  s.t. g = z_bar\n\t  // use RIA evaluators to recast g into global opt subproblem\n\t  //primary_resp_map.reshape(1);   // one objective, no contributors\n\t  //secondary_resp_map.reshape(1); // one constraint, one contributor\n\t  //secondary_resp_map[0].reshape(1);\n\t  //secondary_resp_map[0][0] = respFnCount;\n\t  //BoolDequeArray nonlinear_resp_map(2);\n\t  //nonlinear_resp_map[1] = BoolDeque(1, false);\n\t  //mpp_model_rep->init_maps(vars_map, false, NULL, NULL,\n\t  //  primary_resp_map, secondary_resp_map, nonlinear_resp_map,\n\t  //  RIA_objective_eval, RIA_constraint_eval);\n\n\t  // EFF formulation : max EFF  s.t. bound constraints\n\t  // use EFF evaluators to recast g into global opt subproblem\n\t  primary_resp_map.resize(1);\n\t  primary_resp_map[0].resize(1);\n\t  primary_resp_map[0][0] = respFnCount;\n\t  mpp_model_rep->init_maps(vars_map, false, NULL, NULL,\n\t    primary_resp_map, secondary_resp_map, nonlinear_resp_map,\n\t    EFF_objective_eval, NULL);\n\t}\n\telse {\n\t  // Standard PMA : min/max g  s.t. u'u = beta_bar^2\n\t  // use PMA evaluators to recast g into global opt subproblem\n\t  //void (*set_map) (const ShortArray& recast_asv,\n\t  //                 ShortArray& sub_model_asv) =\n\t  //  (integrationOrder == 2) ? PMA2_set_mapping : NULL;\n\t  //primary_resp_map.reshape(1);   // one objective, one contributor\n\t  //primary_resp_map[0].reshape(1);\n\t  //primary_resp_map[0][0] = respFnCount;\n\t  //secondary_resp_map.reshape(1); // one constraint, no contributors\n\t  //BoolDequeArray nonlinear_resp_map(2);\n\t  //nonlinear_resp_map[0] = BoolDeque(1, false);\n\t  //mpp_model_rep->init_maps(vars_map, false, NULL, set_map,\n\t  //  primary_resp_map, secondary_resp_map, nonlinear_resp_map,\n\t  //  PMA_objective_eval, PMA_constraint_eval);\n\n\t  // EIF formulation : max Phi(EIF) [merit function on EIF]\n\t  // determine fnStar from among sample data\n\t  get_best_sample();\n\t  // use EIF evaluators to recast g into global opt subproblem\n\t  primary_resp_map.resize(1);\n\t  primary_resp_map[0].resize(1);\n\t  primary_resp_map[0][0] = respFnCount;\n\t  mpp_model_rep->init_maps(vars_map, false, NULL, NULL,\n\t    primary_resp_map, secondary_resp_map, nonlinear_resp_map,\n\t    EIF_objective_eval, NULL);\n\t}\n\n\t// Execute GLOBAL search and retrieve u-space results\n\tCout << \"\\n>>>>> Initiating global reliability optimization\\n\";\n\tmppOptimizer.run(pl_iter);\n\t// Use these two lines for COLINY optimizers\n\t//const VariablesArray& vars_star\n\t//  = mppOptimizer.variables_array_results();\n\t//const RealVector& c_vars_u = vars_star[0].continuous_variables();\n\t// Use these two lines for NCSU DIRECT\n\tconst Variables& vars_star = mppOptimizer.variables_results();\n\tconst RealVector& c_vars_u = vars_star.continuous_variables();\n\n\t// Get expected value at u* for output\n\tuSpaceModel.continuous_variables(c_vars_u);\n\tuSpaceModel.evaluate();\n\tconst RealVector& g_hat_fns\n\t  = uSpaceModel.current_response().function_values();\n\n\t// Re-evaluate the expected improvement/feasibility at vars_star\n\tReal beta_star = 0.,/* TO DO */  exp_fns_star = (ria_flag) ?\n\t  expected_feasibility(g_hat_fns, vars_star) :\n\t  expected_improvement(g_hat_fns, vars_star);\n    \n\tCout << \"\\nResults of EGRA iteration:\\nFinal point (u-space)   =\\n\";\n\twrite_data(Cout, c_vars_u);\n\tsize_t wpp7 = write_precision+7;\n\tif (ria_flag) {\n\t  Cout << \"Expected Feasibility    =\\n                     \"\n\t       << std::setw(wpp7) << -exp_fns_star << \"\\n                     \"\n\t       << std::setw(wpp7) << g_hat_fns[respFnCount]-requestedTargetLevel\n\t       << \" [G_hat(u) - z]\\n\";\n\t//     << \"                     \" << std::setw(wpp7) << beta_star\n\t//     << \" [beta*]\\n\";\n\t//Cout << \"RIA optimum             =\\n                     \"\n\t//     << std::setw(wpp7) << exp_fns_star << \" [u'u]\\n\"\n\t//     << \"                     \" << std::setw(wpp7) << exp_fns_star[1]\n\t//     << \" [G(u) - z]\\n\";\n\t}\n\telse {\n\t  // Calculate beta^2 for output (and aug_lag update)\n\t  Cout << \"Expected Improvement    =\\n                     \"\n\t       << std::setw(wpp7) << -exp_fns_star << \"\\n                     \"\n\t       << std::setw(wpp7) << beta_star - requestedTargetLevel\n\t       << \" [beta* - bar-beta*]\\n                     \"\n\t       << std::setw(wpp7) << g_hat_fns[respFnCount] << \" [G_hat(u)]\\n\";\n\t//Cout << \"PMA optimum             =\\n                     \"\n\t//     << std::setw(wpp7) << exp_fns_star << \" [\";\n\t//if (pmaMaximizeG) Cout << '-';\n\t//Cout << \"G(u)]\\n                     \" << std::setw(wpp7)\n\t//     << exp_fns_star[1] << \" [u'u - B^2]\\n\";\n\t}\n\n\t// Update parameters for the augmented Lagrangian merit function\n\tif (pma_aug_lag_flag) {\n\t  // currently only used for PMA with EIF\n\t  Real c_violation = beta_star - requestedTargetLevel;\n\t  if (c_violation < lastConstraintViolation)\n\t    lastIterateAccepted = true;\n\t  lastConstraintViolation = c_violation;\n\t}\n    \n\t// Check for convergence based on max EIF/EFF\n\t// BMA: was previously hard-wired: convergenceTol = .001;\n        if (maxIterations < 0) \n          maxIterations  = 25*numContinuousVars;\n\tif (approxIters >= maxIterations || -exp_fns_star < convergenceTol)\n\t  approxConverged = true;\n\telse {\n\t  // Evaluate response_star_truth\n\t  uSpaceModel.component_parallel_mode(TRUTH_MODEL);\n\t  RealVector c_vars_x;\n\t  natafTransform.trans_U_to_X(c_vars_u, c_vars_x);\n\t  iteratedModel.continuous_variables(c_vars_x);\n\t  ActiveSet set = iteratedModel.current_response().active_set();\n\t  set.request_values(0); set.request_value(dataOrder, respFnCount);\n\t  iteratedModel.evaluate(set);\n\t  IntResponsePair resp_star_truth(iteratedModel.evaluation_id(),\n\t\t\t\t\t  iteratedModel.current_response());\n\n\t  // Update the GP approximation\n\t  if (mppSearchType == EGRA_X) // update with x-space current vars\n\t    uSpaceModel.append_approximation(\n\t      iteratedModel.current_variables(), resp_star_truth, true);\n\t  else                         // update with u-space vars_star\n\t    uSpaceModel.append_approximation(vars_star, resp_star_truth, true);\n\t}\n      } // end approx convergence while loop\n      \n      if (ria_flag)\n\tCout << \"\\n<<<<< GP model has converged for response level \";\n      else\n \tCout << \"\\n<<<<< GP model has converged for response level \";\n      Cout << levelCount+1 << \" = \" << requestedTargetLevel << '\\n';\n     \n    } // end loop over levels\n\n    if (num_levels)\n      Cout << \"\\n<<<<< GP model has converged for all requested levels of \"\n\t   << \"response function \" << respFnCount+1 << '\\n';\n\n#ifdef DEBUG\n    // DEBUG - output set of samples used to build the GP\n    // If problem is 2d, output a grid of points on the GP, variance, \n    //   eff, and truth (if requested)\n    if (num_levels) {  // can only plot if GP was built!\n      std::string samsfile(\"egra_sams\");\n      std::string tag = \"_\" + boost::lexical_cast<std::string>(respFnCount+1) +\n                        \".out\";\n      samsfile += tag;\n      std::ofstream samsOut(samsfile.c_str(),std::ios::out);\n      samsOut << std::scientific;\n      const Pecos::SurrogateData& gp_data\n\t= uSpaceModel.approximation_data(respFnCount);\n      size_t num_data_pts = gp_data.size(), num_vars = uSpaceModel.cv();\n      for (size_t i=0; i<num_data_pts; ++i) {\n\tconst RealVector& sams = gp_data.continuous_variables(i); // view\n\tReal true_fn = gp_data.response_function(i);\n\t\n\tif (mppSearchType == EGRA_X) {\n\t  RealVector sams_u(num_vars);\n\t  natafTransform.trans_X_to_U(sams,sams_u);\n\t  \n\t  samsOut << '\\n';\n\t  for (size_t j=0; j<num_vars; j++)\n\t    samsOut << std::setw(13) << sams_u[j] << ' ';\n\t  samsOut<< std::setw(13) << true_fn;\n\t}\n\telse {\n\t  samsOut << '\\n';\n\t  for (size_t j=0; j<num_vars; j++)\n\t    samsOut << std::setw(13) << sams[j] << ' ';\n\t  samsOut<< std::setw(13) << true_fn;\n\t}\n      }\n      samsOut << std::endl;\n\n#ifdef DEBUG_PLOTS\n      // Plotting the GP, etc over a grid is intended for visualization and\n      //   is therefore only available for 2D problems\n      if (num_vars==2) {\n\tbool true_plot = false;\n        std::string truefile(\"egra_true\"), gpfile(\"egra_gp\"),\n                    varfile(\"egra_var\"), efffile(\"egra_eff\");\n\ttruefile += tag; gpfile += tag; varfile += tag; efffile += tag;\n\tstd::ofstream trueOut(truefile.c_str(), std::ios::out),\n\t                gpOut(gpfile.c_str(),   std::ios::out),\n                       varOut(varfile.c_str(),  std::ios::out),\n                       effOut(efffile.c_str(),  std::ios::out);\n\tgpOut  << std::scientific; varOut << std::scientific;\n\teffOut << std::scientific; if (true_plot) trueOut << std::scientific;\n\tRealVector u_pt(2), x_pt(2);\n\tReal lbnd =  -5., ubnd =  5.;\n\t//Real lbnd = -10., ubnd = 10.;\n\tReal interval = (ubnd-lbnd)/100.;\n\tfor (size_t i=0; i<101; i++){\n\t  u_pt[0] = lbnd + float(i)*interval;\n\t  for (size_t j=0; j<101; j++){\n\t    u_pt[1] = lbnd + float(j)*interval;\n\t    \n\t    uSpaceModel.continuous_variables(u_pt);\n\t    ActiveSet set = uSpaceModel.current_response().active_set();\n\t    set.request_values(0); set.request_value(1, respFnCount);\n\t    uSpaceModel.evaluate(set);\n\t    const Response& gp_resp = uSpaceModel.current_response();\n\t    const RealVector& gp_fn = gp_resp.function_values();\n\t    \n\t    gpOut << '\\n' << std::setw(13) << u_pt[0] << ' ' << std::setw(13)\n\t\t  << u_pt[1] << ' ' << std::setw(13) << gp_fn[respFnCount];\n\t    \n\t    RealVector variance;\n\t    if (mppSearchType == EGRA_X) { // Recast( DataFit( iteratedModel ) )\n\t      // RecastModel::derived_evaluate() propagates u_pt to x_pt\n\t      Model& dfs_model = uSpaceModel.subordinate_model();\n\t      variance = dfs_model.approximation_variances(\n\t\tdfs_model.current_variables()); // x_pt\n\t    }\n\t    else // EGRA_U: DataFit( Recast( iteratedModel ) )\n\t      variance = uSpaceModel.approximation_variances(\n\t\tuSpaceModel.current_variables()); // u_pt\n\t    \n\t    varOut << '\\n' << std::setw(13) << u_pt[0] << ' ' << std::setw(13)\n\t\t   << u_pt[1] << ' ' << std::setw(13) << variance[respFnCount];\n\t    \n\t    Real eff = expected_feasibility(gp_fn, u_pt);\n\t    \n\t    effOut << '\\n' << std::setw(13) << u_pt[0] << ' ' << std::setw(13)\n\t\t   << u_pt[1] << ' ' << std::setw(13) << -eff;\n\n\t    // plotting the true function can be expensive, but is available\n\t    if (true_plot) {\n\t      uSpaceModel.component_parallel_mode(TRUTH_MODEL);\n\t      natafTransform.trans_U_to_X(u_pt,x_pt);\n\t      iteratedModel.continuous_variables(x_pt);\n\t      set = iteratedModel.current_response().active_set();\n\t      set.request_values(0); set.request_value(1, respFnCount);\n\t      iteratedModel.evaluate(set);\n\t      const Response& true_resp = iteratedModel.current_response();\n\t      const RealVector& true_fn = true_resp.function_values();\n\t      \n\t      trueOut << '\\n' << std::setw(13) << u_pt[0] << ' '\n\t\t      << std::setw(13) << u_pt[1] << ' '\n\t\t      << std::setw(13) << true_fn[respFnCount];\n\t    }\n\t  }\n\t  gpOut << std::endl; varOut << std::endl; effOut << std::endl;\n\t  if (true_plot) trueOut << std::endl;\n\t}\n      }\n#endif //DEBUG_PLOTS\n    }\n#endif //DEBUG\n\n  } // end loop over response fns\n}\n\n\nvoid NonDGlobalReliability::importance_sampling()\n{\n  bool x_data_flag = (mppSearchType == EGRA_X);\n  size_t i;\n  statCount = 0;\n  const ShortArray& final_res_asv = finalStatistics.active_set_request_vector();\n  ParLevLIter pl_iter = methodPCIter->mi_parallel_level_iterator(miPLIndex);\n  // rep needed for access to functions not mapped to Iterator level\n  NonDAdaptImpSampling* importance_sampler_rep\n    = (NonDAdaptImpSampling*)importanceSampler.iterator_rep();\n\n  for (respFnCount=0; respFnCount<numFunctions; respFnCount++) {\n\n    // The most general case is to allow a combination of response, probability,\n    // and reliability level specifications for each response function.\n    size_t rl_len = requestedRespLevels[respFnCount].length(),\n           pl_len = requestedProbLevels[respFnCount].length(),\n           gl_len = requestedGenRelLevels[respFnCount].length(),\n           num_levels = rl_len + pl_len + gl_len;\n\n    RealVectorArray gp_inputs;\n    if (num_levels==0) {\n      uSpaceModel.component_parallel_mode(TRUTH_MODEL);\n      // don't use derivatives in the importance sampling\n      ActiveSet set = iteratedModel.current_response().active_set();\n      set.request_values(0); set.request_value(1, respFnCount);\n      iteratedModel.evaluate(set);\n      const Response& true_resp = iteratedModel.current_response();\n      const RealVector& true_fn = true_resp.function_values();\n      finalStatistics.function_value(true_fn[respFnCount], statCount);\n    }\n    else {\n      // extract the approximation data from the surrogate model.\n      // Note 1: this data is either x-space (EGRA_X) or u-space (EGRA_U).\n      // Note 2: this returns _all_ truth model data for this response fn,\n      //         including initial DACE and EGRA added points for _all_ levels.\n      // TO DO:  likely need to remove DACE and partition remaining data among\n      //         levels for importance sampling efficiency.\n      const Pecos::SurrogateData& gp_data\n\t= uSpaceModel.approximation_data(respFnCount);\n      size_t num_data_pts = gp_data.points();\n      gp_inputs.resize(num_data_pts);\n      for (i=0; i<num_data_pts; ++i)\n\tgp_inputs[i] = gp_data.continuous_variables(i); // view OK\n    }\n    statCount++;\n\n    // Standard deviations & sensitivities not available, skip\n    statCount++;\n\n    // Loop over response/probability/reliability levels\n    for (levelCount=0; levelCount<num_levels; levelCount++) {\n\n      Cout << \"\\n<<<<< Performing importance sampling for response function \" \n\t   << respFnCount+1 << \" level \" << levelCount+1 << '\\n';\n\n      bool ria_flag = (levelCount < rl_len) ? true : false;\n      if (ria_flag) {\n\tReal z =  computedRespLevels[respFnCount][levelCount] \n\t       = requestedRespLevels[respFnCount][levelCount];\n\timportance_sampler_rep->\n\t  initialize(gp_inputs, x_data_flag, respFnCount, 0., z);\n      }\n      else // not operational (see error traps in ctor)\n\timportance_sampler_rep->initialize(gp_inputs, x_data_flag,\n\t  respFnCount, 0., computedRespLevels[respFnCount][levelCount]);\n\n      importanceSampler.run(pl_iter);\n\n      Real p = importance_sampler_rep->final_probability();\n#ifdef DEBUG\n      Cout << \"\\np = \" << p << std::endl;\n#endif // DEBUG\n      // RIA z-bar -> p\n      computedProbLevels[respFnCount][levelCount] = p;\n      // RIA z-bar -> generalized beta\n      Real gen_beta = -Pecos::NormalRandomVariable::inverse_std_cdf(p);\n      computedGenRelLevels[respFnCount][levelCount] = gen_beta;\n      switch (respLevelTarget) {\n      case PROBABILITIES:\n\tfinalStatistics.function_value(p, statCount++);        break;\n      case GEN_RELIABILITIES:\n\tfinalStatistics.function_value(gen_beta, statCount++); break;\n      }\n    }\n  }\n  // post-process level mappings to define PDFs (using prob_refined and\n  // all_levels_computed modes)\n  if (pdfOutput)\n    compute_densities(importance_sampler_rep->extreme_values(), true, true);\n}\n\n\nvoid NonDGlobalReliability::\nEIF_objective_eval(const Variables& sub_model_vars,\n\t\t   const Variables& recast_vars,\n\t\t   const Response& sub_model_response,\n\t\t   Response& recast_response)\n{\n  const ShortArray& recast_asv = recast_response.active_set_request_vector();\n  if (recast_asv[0] & 1) {\n    Real ei = nondGlobRelInstance->expected_improvement(\n      sub_model_response.function_values(), recast_vars);\n    recast_response.function_value(ei, 0);\n  }\n}\n\n\nvoid NonDGlobalReliability::\nEFF_objective_eval(const Variables& sub_model_vars,\n\t\t   const Variables& recast_vars,\n\t\t   const Response& sub_model_response,\n\t\t   Response& recast_response)\n{\n  const ShortArray& recast_asv = recast_response.active_set_request_vector();\n  if (recast_asv[0] & 1) {\n    Real ef = nondGlobRelInstance->expected_feasibility(\n      sub_model_response.function_values(), recast_vars);\n    recast_response.function_value(ef, 0);\n  }\n}\n\n\nReal NonDGlobalReliability::\nexpected_improvement(const RealVector& expected_values,\n\t\t     const Variables& recast_vars)\n{\n  // Get variance from the GP; Expected values are passed in\n  // If GP built in x-space, transform input point to x-space to get variance\n  RealVector variances;\n  if (mppSearchType == EGRA_X) { // uSpaceModel = Recast(DataFit(iteratedModel))\n    Model& dfs_model = uSpaceModel.subordinate_model();\n    // assume recast_vars have been propagated to GP just prior to call\n    variances\n      = dfs_model.approximation_variances(dfs_model.current_variables());\n  }\n  else                   // EGRA_U: uSpaceModel = DataFit(Recast(iteratedModel))\n    variances = uSpaceModel.approximation_variances(recast_vars);\n    \n  Real mean = expected_values[respFnCount];\n  Real stdv = std::sqrt(variances[respFnCount]);\n\n  // Calculate and apply penalty to the mean\n  Real beta_star = 0.; // TO DO\n  // calculate the equality constraint: beta* - bar-beta*\n  Real cfn = beta_star - requestedTargetLevel;\n  Real penalty = constraint_penalty(cfn, recast_vars.continuous_variables());\n  // Calculation of EI will have different form for the CDF/CCDF cases\n  Real penalized_mean = (pmaMaximizeG) ? mean - penalty : mean + penalty;\n  \n  // Calculate the expected improvement\n  // Note: This is independent of the CDF/CCDF check\n\n  Real ei, cdf, pdf;\n  Real snv = (fnStar-penalized_mean); // not normalized yet\n  if(std::fabs(snv)>=std::fabs(stdv)*50.0) {\n    //this will trap the denominator=0.0 case even if numerator=0.0\n    pdf = 0.;\n    cdf = (snv > 0.) ? 1. : 0.;\n  }\n  else{\n    snv /= stdv; // now snv is the standard normal variate\n    cdf = Pecos::NormalRandomVariable::std_cdf(snv);\n    pdf = Pecos::NormalRandomVariable::std_pdf(snv);\n  }\n  ei = (pmaMaximizeG) ? (penalized_mean - fnStar)*(1.-cdf) + stdv*pdf\n                      : (fnStar - penalized_mean)*cdf      + stdv*pdf;\n  return -ei; // return -EI because we are maximizing EI\n}\n\n\nReal NonDGlobalReliability::\nexpected_feasibility(const RealVector& expected_values,\n\t\t     const Variables& recast_vars)\n{\n  // Get variance from the GP; Expected values are passed in\n  // If GP built in x-space, transform input point to x-space to get variance\n  RealVector variances;\n  if (mppSearchType == EGRA_X) { // uSpaceModel = Recast(DataFit(iteratedModel))\n    Model& dfs_model = uSpaceModel.subordinate_model();\n    // assume recast_vars have been propagated to GP just prior to call\n    variances\n      = dfs_model.approximation_variances(dfs_model.current_variables());\n  }\n  else                   // EGRA_U: uSpaceModel = DataFit(Recast(iteratedModel))\n    variances = uSpaceModel.approximation_variances(recast_vars);\n  \n  Real mean  = expected_values[respFnCount],\n       stdv  = std::sqrt(variances[respFnCount]),\n       zbar  = requestedTargetLevel,\n       alpha = 2.; // may want to try values other than 2\n\n  // calculate standard normal variate +/- alpha\n  \n  Real cdfz, pdfz, cdfp, pdfp, cdfm, pdfm;\n  Real snvz = (zbar - mean);\n  if (std::fabs(snvz) >= std::fabs(stdv)*50.) {\n    pdfm = pdfp = pdfz = 0.;\n    cdfm = cdfp = cdfz = (snvz > 0.) ? 1. : 0.;\n  }\n  else {\n    snvz /= stdv; Real snvp = snvz + alpha, snvm = snvz - alpha;\n    pdfz = Pecos::NormalRandomVariable::std_pdf(snvz);\n    cdfz = Pecos::NormalRandomVariable::std_cdf(snvz);\n    pdfp = Pecos::NormalRandomVariable::std_pdf(snvp);\n    cdfp = Pecos::NormalRandomVariable::std_cdf(snvp);\n    pdfm = Pecos::NormalRandomVariable::std_pdf(snvm);\n    cdfm = Pecos::NormalRandomVariable::std_cdf(snvm);\n  }\n  // calculate expected feasibility function\n  Real ef = (mean - zbar)*(2.*cdfz - cdfm - cdfp) //exploit\n          - stdv*(2.*pdfz - pdfm - pdfp //explore\n\t  - alpha*cdfp + alpha*cdfm);\n\n  return -ef;  // return -EF because we are maximizing\n}\n\n\nvoid NonDGlobalReliability::get_best_sample()\n{\n  // Pull the samples and responses from data used to build latest GP\n  //   and apply any penalties to calculate fnStar for use in the \n  //   expected improvement function\n  // This is only done for PMA - there is no \"best solution\" for\n  //   the expected feasibility function used in RIA\n\n  Iterator&             dace_iterator  = uSpaceModel.subordinate_iterator();\n  const RealMatrix&     true_vars_x    = dace_iterator.all_samples();\n  const IntResponseMap& true_responses = dace_iterator.all_responses();\n  size_t i, j, num_samples = true_vars_x.numCols(),\n    num_vars = true_vars_x.numRows();\n  \n  // If GP built in x-space, transform true_vars_x to u-space to calculate beta\n  RealVectorArray true_c_vars_u(num_samples); RealVector true_vars_x_cv;\n  for (i=0; i<num_samples; i++) {\n    true_vars_x_cv = Teuchos::getCol(Teuchos::View,\n      const_cast<RealMatrix&>(true_vars_x), (int)i);\n    if (mppSearchType == EGRA_X)\n      natafTransform.trans_X_to_U(true_vars_x_cv, true_c_vars_u[i]);\n    else\n      true_c_vars_u[i] = true_vars_x_cv; // view OK\n  }\n\n  // Calculation of fnStar will have different form for CDF/CCDF cases\n  fnStar = (pmaMaximizeG) ? -DBL_MAX : DBL_MAX; IntRespMCIter it;\n  for (i=0, it=true_responses.begin(); i<num_samples; i++, ++it) {\n    // calculate the reliability index (beta)\n    Real beta_star = 0., penalized_response; // TO DO\n    // calculate the equality constraint: u'u - beta_target^2\n    Real cfn = beta_star - requestedTargetLevel;\n    Real penalty = constraint_penalty(cfn, true_c_vars_u[i]);\n    penalized_response = (pmaMaximizeG) ?\n      it->second.function_value(0) - penalty :\n      it->second.function_value(0) + penalty;\n    if ( ( pmaMaximizeG && penalized_response > fnStar) ||\n\t (!pmaMaximizeG && penalized_response < fnStar) )\n      fnStar = penalized_response;\n  }\n}\n\n\nReal NonDGlobalReliability::\nconstraint_penalty(const Real& c_viol, const RealVector& u)\n{\n  if (meritFunctionType == PENALTY_MERIT)\n    return exp(approxIters/10.)*c_viol*c_viol;  // try other schedules\n  else if (meritFunctionType == AUGMENTED_LAGRANGIAN_MERIT) {\n    if (lastIterateAccepted)\n      augLagrangeMult += 2.*penaltyParameter*c_viol;\n    else \n      penaltyParameter *= 2.;\n    return augLagrangeMult*c_viol + penaltyParameter*c_viol*c_viol;\n  }\n  else if (meritFunctionType == LAGRANGIAN_MERIT) {\n#ifdef DAKOTA_F90\n    // form [A] = grad[u'u - beta^2]\n    RealVector A(numContAleatUncVars, false);\n    for (size_t i=0; i<numContAleatUncVars; i++)\n      A[i] = 2.*u[i];\n\n    // form -{grad_f} = m_grad_f = -grad[G_hat(u)]\n    uSpaceModel.continuous_variables(u);\n    uSpaceModel.evaluate();\n    const Real* grad_f = uSpaceModel.current_response().function_gradient(0);\n    RealVector m_grad_f(numContAleatUncVars, false);\n    for (size_t i=0; i<numContAleatUncVars; ++i)\n      m_grad_f[i] = -grad_f[i];\n\n    // solve for lambda : [A]{lambda} = {m_grad_f}\n    int ierr, nsetp, m = numContAleatUncVars, n = 1;\n    Real res_norm;\n    IntVector index(1);\n    RealVector lambda(1), w(1), bnd(2);\n    // lawson_hanson2.f90: BVLS ignore bounds based on huge(), so +/-DBL_MAX\n    // is sufficient here\n    bnd[0] = -DBL_MAX; bnd[1] = DBL_MAX;\n    BVLS_WRAPPER_FC(A.values(), m, n, m_grad_f.values(), bnd.values(),\n\t\t    lambda.values(), res_norm, nsetp, w.values(),\n\t\t    index.values(), ierr);\n    if (ierr) {\n      Cerr << \"\\nError: BVLS failed in constraint_penalty() in NonDGR\"\n\t   << std::endl;\n      abort_handler(-1);\n    }\n\n    lagrangeMult = lambda[0];\n    return lagrangeMult*c_viol;\n#endif // DAKOTA_F90\n  }\n  else\n    return 0.; // add NO_PENALTY to the enum instead?\n}\n\n\nvoid NonDGlobalReliability::print_results(std::ostream& s, short results_state)\n{\n  size_t i, j, wpp7 = write_precision + 7;\n  const StringArray& fn_labels = iteratedModel.response_labels();\n  s << \"-----------------------------------------------------------------------\"\n    << \"------\";\n\n  print_densities(s);\n\n  // output CDF/CCDF level mappings (replaces NonD::print_level_mappings())\n  s << std::scientific << std::setprecision(write_precision)\n    << \"\\nLevel mappings for each response function:\\n\";\n  for (i=0; i<numFunctions; i++) {\n\n    size_t num_levels = computedRespLevels[i].length();\n    if (num_levels) {\n      if (cdfFlag)\n        s << \"Cumulative Distribution Function (CDF) for \";\n      else\n        s << \"Complementary Cumulative Distribution Function (CCDF) for \";\n      s << fn_labels[i] << \":\\n     Response Level  Probability Level  \"\n\t<< \"Reliability Index  General Rel Index\\n     --------------  \"\n\t<< \"-----------------  -----------------  -----------------\\n\";\n      for (j=0; j<num_levels; j++)\n        s << \"  \" << std::setw(wpp7) << computedRespLevels[i][j]\n\t  << \"  \" << std::setw(wpp7) << computedProbLevels[i][j]\n\t  << std::setw(2*write_precision+18) << computedGenRelLevels[i][j]\n\t  << '\\n';\n    }\n  }\n\n  s << \"-----------------------------------------------------------------------\"\n    << \"------\" << std::endl;\n}\n\n} // namespace Dakota\n", "meta": {"hexsha": "6165921838f284398bf148d274e2748ba34b0fe0", "size": 47683, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NonDGlobalReliability.cpp", "max_stars_repo_name": "jnnccc/Dakota-orb", "max_stars_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NonDGlobalReliability.cpp", "max_issues_repo_name": "jnnccc/Dakota-orb", "max_issues_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NonDGlobalReliability.cpp", "max_forks_repo_name": "jnnccc/Dakota-orb", "max_forks_repo_head_hexsha": "96488e723be9c67f0f85be8162b7af52c312b770", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.4225978648, "max_line_length": 102, "alphanum_fraction": 0.6960551979, "num_tokens": 12651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.23427866639181413}}
{"text": "/*\n * Software License Agreement (BSD License)\n *\n *  CloudClean\n *  Copyright (c) 2013, Rickert Mulder\n *\n *  All rights reserved.\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of Rickert Mulder nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n#include \"gui/camera.h\"\n#include <cmath>\n#include <mutex>\n#include <Eigen/LU>\n#include <Eigen/Dense>\n#include <QDebug>\n#include <QTimer>\n#include <iostream>\n\nusing Eigen::Vector3f;\nusing Eigen::Vector2f;\nusing Eigen::AngleAxis;\n\nCamera::Camera() {\n    //mtx_ = new std::mutex();\n    fov_current_ = 60.0f;\n    fov_future_ = 60.0f;\n    aspect_ = 1.0f;\n    depth_near_ = 1.0f;\n    depth_far_ = 1000.f;\n\n    roll_correction_ = true;\n    always_update_ = false;\n\n    rotation_current_ = AngleAxis<float>(0, Vector3f(1.0f, 0.0f, 0.0f));\n    rotation_future_ = AngleAxis<float>(0, Vector3f(1.0f, 0.0f, 0.0f));\n\n    translation_current_ = Vector3f(0, 0, 0);\n    translation_future_ = Vector3f(0, 0, 0);\n\n    translation_speed_ = 1;\n\n    projection_dirty_ = true;\n\n    timer_ = new QTimer();\n    timer_->connect(timer_, &QTimer::timeout, [&] () {\n        Eigen::Vector3f trans_diff = translation_future_ - translation_current_;\n        bool good_enough_rotation = rotation_current_.isApprox(rotation_future_);\n        float fov_diff = fov_future_ - fov_current_;\n\n        if(trans_diff.norm() > 1e-4 || !good_enough_rotation || fabs(fov_diff) > 1e-10) {\n\n            translation_current_ = translation_current_ + trans_diff * 0.5;\n            rotation_current_ = rotation_current_.slerp(0.5, rotation_future_);\n            fov_current_ = fov_future_ * 0.5 + fov_current_ * 0.5;\n\n            if(fabs(fov_diff) > 1e-10)\n                projection_dirty_ = true;\n\n            emit updated();\n        }\n        else {\n            if(always_update_)\n                emit updated();\n            translation_speed_ = 1;\n        }\n\n\n    });\n\n    timer_->start(1000/60);\n}\n\nCamera::~Camera() {\n    //delete mtx_;\n}\n\ndouble angle (Vector3f a, Vector3f b){\n    double dotp = a.dot(b);\n    if(dotp >= 1 || dotp <= -1){\n        return 0.0;\n    }\n    return acos(dotp);\n}\n\ndouble normalizeRad(double angle){\n    if(angle < -M_PI_2){\n        return -M_PI_2 - (angle + M_PI_2);\n    } else if(angle > M_PI_2) {\n        return M_PI_2 - (angle - M_PI_2);\n    }\n    return angle;\n}\n\nEigen::Quaternionf rollcorrect(Eigen::Quaternionf rotation){\n    Vector3f local_z_axis = rotation.inverse() * -Vector3f::UnitZ();\n    Vector3f local_x_axis = rotation.inverse() * Vector3f::UnitX();\n    Vector3f local_y_axis = rotation.inverse() * Vector3f::UnitY();\n\n    Vector3f z_proj_zx = local_z_axis; z_proj_zx(1) = 0; z_proj_zx.normalize();\n    Vector3f x_proj_zx = local_x_axis; x_proj_zx(1) = 0; x_proj_zx.normalize();\n    Vector3f y_proj_zx = local_y_axis; y_proj_zx(1) = 0; y_proj_zx.normalize();\n\n    double pitch = angle(local_z_axis, z_proj_zx);\n    double roll = angle(local_x_axis, x_proj_zx);\n\n    int proj_side = local_x_axis.cross(x_proj_zx).dot(local_z_axis) > 0 ? -1 : 1;\n    int side_up = local_y_axis.dot(Vector3f::UnitY()) > 0 ? 1 : -1;\n\n    if(side_up == -1){\n        roll = M_PI - roll;\n    }\n\n    roll = roll * proj_side * side_up;\n\n    double norm_pitch = normalizeRad(pitch);\n    double correction_factor = (M_PI_2 - fabs(norm_pitch)) / M_PI_2;\n    correction_factor = pow(correction_factor - 0.5, 1);\n\n    if(pitch > 0.7){\n        correction_factor = 0;\n    }\n\n    AngleAxis<float> roll_correction(correction_factor*-roll, Vector3f::UnitZ());\n    rotation = roll_correction * rotation;\n\n    return rotation;\n}\n\nvoid Camera::setFoV(float fov) {\n    fov_future_ = fov;\n    projection_dirty_ = true;\n}\n\nvoid Camera::setAspect(float aspect) {\n    aspect_ = aspect;\n    projection_dirty_ = true;\n}\n\nvoid Camera::setDepthRange(float near, float far) {\n    depth_near_ = near;\n    depth_far_ = far;\n    projection_dirty_ = true;\n}\n\nvoid Camera::setPosition(const Eigen::Vector3f& pos) {\n    translation_future_ = pos;\n}\n\n\nvoid Camera::recalculateProjectionMatrix() {\n    // Code from Mesa project, src/glu/sgi/libutil/project.c\n    projection_matrix_.setIdentity();\n    float radians = fov_current_ / 2 * M_PI / 180;\n\n    float deltaZ = depth_far_ - depth_near_;\n    float sine = sin(radians);\n    if ((deltaZ == 0) || (sine == 0) || (aspect_ == 0)) {\n        return;\n    }\n    float cotangent = cos(radians) / sine;\n\n    projection_matrix_(0, 0) = cotangent / aspect_;\n    projection_matrix_(1, 1) = cotangent;\n    projection_matrix_(2, 2) = -(depth_far_ + depth_near_) / deltaZ;\n    projection_matrix_(3, 2) = -1;\n    projection_matrix_(2, 3) = -2 * depth_near_ * depth_far_ / deltaZ;\n    projection_matrix_(3, 3) = 0;\n    projection_dirty_ = false;\n}\n\nEigen::Affine3f Camera::modelviewMatrix() {\n    return rotation_current_  * Eigen::Translation3f(translation_current_) * Eigen::Affine3f::Identity();\n}\n\nEigen::Affine3f Camera::projectionMatrix() const {\n    if (projection_dirty_) {\n        const_cast<Camera*>(this)->recalculateProjectionMatrix();\n    }\n    return projection_matrix_;\n}\n\nvoid Camera::translate(const Eigen::Vector3f& pos) {\n    translation_future_ = Eigen::Translation3f(rotation_current_.inverse() * (translation_speed_ * pos)) * translation_current_;\n\n    if(translation_speed_ < 10){\n        translation_speed_ *= 1.1f; // If succesive tranlations are performed, speed things up\n    }\n\n    emit modified();\n}\n\nvoid Camera::setRotate3D(const Eigen::Vector3f& rot) {\n    Eigen::AngleAxis<float> aaZ(rot.z(), Eigen::Vector3f::UnitZ());\n    Eigen::AngleAxis<float> aaY(rot.y(), Eigen::Vector3f::UnitY());\n    Eigen::AngleAxis<float> aaX(rot.x(), Eigen::Vector3f::UnitX());\n\n    rotation_future_ = aaZ * aaY * aaX;\n    emit modified();\n}\n\nvoid Camera::rotate2D(float x, float y) {\n    Vector2f rot = Vector2f(x, y);\n\n    AngleAxis<float> rotX(rot.x(), Vector3f::UnitY()); // look left right\n    AngleAxis<float> rotY(rot.y(), Vector3f::UnitX()); // look up down\n\n    rotation_future_ = (rotX * rotY) * rotation_current_;\n\n    if(roll_correction_){\n        rotation_future_ = rollcorrect(rotation_future_);\n    }\n\n    emit modified();\n}\n\nvoid Camera::rotate3D(float _yaw, float _pitch, float _roll) {\n\n    AngleAxis<float> rotX(_yaw, Vector3f::UnitY()); // look left right\n    AngleAxis<float> rotY(_pitch, Vector3f::UnitX()); // look up down\n\n    rotation_future_ = (rotX * rotY) * rotation_future_;\n\n    auto clamp = [] (double num, double low, double high) {\n        if (num > high)\n            return high;\n        if (num < low)\n            return low;\n        return num;\n    };\n\n    Eigen::Matrix3f r = rotation_future_.toRotationMatrix();\n    double roll = -atan2(r(0,2), r(1, 2));\n    double pitch = acos(r(2,2));\n    //double yaw = atan2(r(2, 0), r(2, 1));\n\n\n    Vector3f dir = rotation_future_ * Vector3f::UnitZ();\n    double dotp = dir.dot(Vector3f::UnitZ());\n\n    double sign = dir.dot(Vector3f::UnitY()) > 0 ? 1.0 : -1.0;\n    double angle = sign * acos(dotp);\n\n/*\n    qDebug() << \"Y angle\" << angle;\n    qDebug() << \"Y angle (DEG)\" << (angle/M_PI) * 180;\n    qDebug() << \"Roll\" << roll;\n    qDebug() << \"Pitch\" << pitch;\n    qDebug() << \"Yaw\" << yaw;\n*/\n    double correction_factor = 1.0 - fabs(pitch-M_PI/2)/(M_PI/2);\n    correction_factor = -0.5 + 1.5 * correction_factor;\n    correction_factor = clamp(correction_factor, 0, 1);\n\n    if(angle < 0)\n        correction_factor = 0;\n\n    //qDebug() << \"Correction factor:\" << correction_factor;\n\n    AngleAxis<float> roll_correction(correction_factor*-roll, Vector3f::UnitZ());\n    rotation_future_ = roll_correction * rotation_future_;\n    rotation_future_.normalize();\n\n    emit modified();\n}\n\nvoid Camera::adjustFov(int val) {\n    // Mouse seems to move in increments of 120\n    val = -val/60.0f;\n    if (fov_future_ + val < 100.0f && fov_future_ + val > 2.0f)\n        setFoV(fov_future_ + val);\n\n}\n\nvoid Camera::birds_eye() {\n    rotation_future_ = AngleAxis<float>(0, Vector3f(1, 0, 0));\n    translation_future_ = 20 * -Vector3f::UnitZ();\n}\n\nvoid Camera::toggleRollCorrection(){\n    roll_correction_ = !roll_correction_;\n}\n\nvoid Camera::toggleRollCorrection(bool on){\n    roll_correction_ = on;\n}\n", "meta": {"hexsha": "e714f564f507a37368235f198bac3172a4841047", "size": 9541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gui/camera.cpp", "max_stars_repo_name": "circlingthesun/cloudclean", "max_stars_repo_head_hexsha": "4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-18T16:10:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-28T01:52:24.000Z", "max_issues_repo_path": "src/gui/camera.cpp", "max_issues_repo_name": "circlingthesun/cloudclean", "max_issues_repo_head_hexsha": "4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gui/camera.cpp", "max_forks_repo_name": "circlingthesun/cloudclean", "max_forks_repo_head_hexsha": "4b9496bc3b52143c35f0ad83ee68bbc5e8aa32d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T07:39:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-29T13:13:48.000Z", "avg_line_length": 30.3853503185, "max_line_length": 128, "alphanum_fraction": 0.6603081438, "num_tokens": 2632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2342663413133585}}
{"text": "#ifndef INVKIN_H_INCLUDED\n#define INVKIN_H_INCLUDED\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include \"pinocchio/math/rpy.hpp\"\n#include \"pinocchio/spatial/explog.hpp\"\n\nclass InvKin {\n  /* Planner that outputs current and future locations of footsteps, the\n     reference trajectory of the base and the position, velocity, acceleration\n     commands for feet in swing phase based on the reference velocity given by\n     the user and the current position/velocity of the base */\n\n  /*private:\n   // Inputs of the constructor\n   double dt;       // Time step of the contact sequence (time step of the MPC)\n   double dt_tsid;  // Time step of TSID\n   double T_gait;   // Gait period\n   double T_mpc;    // MPC period (prediction horizon)\n   double h_ref;    // Reference height for the trunk\n   int k_mpc;       // Number of TSID iterations for one iteration of the MPC\n   bool on_solo8;   //  Whether we are working on solo8 or not\n\n   // Predefined quantities\n   double k_feedback = 0.03;  // Feedback gain for the feedback term of the\n   planner double g = 9.81;           // Value of the gravity acceleartion\n   double L = 0.155;          // Value of the maximum allowed deviation due to\n   leg length bool is_static = false;    // Flag for static gait\n\n   // Number of time steps in the prediction horizon\n   int n_steps; // T_mpc / time step of the MPC\n\n   // Feet index vector\n   std::vector<int> feet;\n   std::vector<double> t0s;\n   double t_remaining = 0.0;\n   double t_swing[4] = {0.0, 0.0, 0.0, 0.0};\n\n   // Constant sized matrices\n   Eigen::MatrixXd fsteps = Eigen::MatrixXd::Zero(N0_gait, 13);\n   Eigen::Matrix<double, 3, 4> shoulders = Eigen::Matrix<double, 3, 4>::Zero();\n   // Position of shoulders in local frame Eigen::Matrix<double, 19, 1> q_static\n   = Eigen::Matrix<double, 19, 1>::Zero(); Eigen::Matrix<double, 3, 1>\n   RPY_static = Eigen::Matrix<double, 3, 1>::Zero(); Eigen::Matrix<double, 1,\n   12> o_feet_contact = Eigen::Matrix<double, 1, 12>::Zero();  // Feet matrix in\n   world frame Eigen::Matrix<double, 3, 4> next_footstep = Eigen::Matrix<double,\n   3, 4>::Zero();  // To store the result of the compute_next_footstep function\n   Eigen::Matrix<double, 3, 3> R =\n       Eigen::Matrix<double, 3, 3>::Zero();  // Predefined matrices for\n   compute_footstep function Eigen::Matrix<double, 3, 3> R_1 =\n       Eigen::Matrix<double, 3, 3>::Zero();  // Predefined matrices for\n   compute_next_footstep function Eigen::Matrix<double, 3, 3> R_2 =\n   Eigen::Matrix<double, 3, 3>::Zero(); Eigen::Matrix<double, N0_gait, 1> dt_cum\n   = Eigen::Matrix<double, N0_gait, 1>::Zero(); Eigen::Matrix<double, N0_gait,\n   1> angle = Eigen::Matrix<double, N0_gait, 1>::Zero(); Eigen::Matrix<double,\n   N0_gait, 1> dx = Eigen::Matrix<double, N0_gait, 1>::Zero();\n   Eigen::Matrix<double, N0_gait, 1> dy = Eigen::Matrix<double, N0_gait,\n   1>::Zero(); Eigen::Matrix<double, 3, 1> q_tmp = Eigen::Matrix<double, 3,\n   1>::Zero(); Eigen::Matrix<double, 3, 1> q_dxdy = Eigen::Matrix<double, 3,\n   1>::Zero(); Eigen::Matrix<double, 3, 1> RPY = Eigen::Matrix<double, 3,\n   1>::Zero(); Eigen::Matrix<double, 3, 1> b_v_cur = Eigen::Matrix<double, 3,\n   1>::Zero(); Eigen::Matrix<double, 6, 1> b_v_ref = Eigen::Matrix<double, 6,\n   1>::Zero(); Eigen::Matrix<double, 3, 1> cross = Eigen::Matrix<double, 3,\n   1>::Zero(); Eigen::Matrix<double, 6, 1> vref_in = Eigen::Matrix<double, 6,\n   1>::Zero();\n\n   Eigen::Matrix<double, N0_gait, 5> gait_p = Eigen::Matrix<double, N0_gait,\n   5>::Zero();  // Past gait Eigen::MatrixXd gait_f =\n   Eigen::MatrixXd::Zero(N0_gait, 5);                                // Current\n   and future gait Eigen::Matrix<double, N0_gait, 5> gait_f_des =\n   Eigen::Matrix<double, N0_gait, 5>::Zero();  // Future desired gait\n\n   // Time interval vector\n   Eigen::Matrix<double, 1, Eigen::Dynamic> dt_vector;\n\n   // Reference trajectory matrix of size 12 by (1 + N)  with the current state\n   of\n   // the robot in column 0 and the N steps of the prediction horizon in the\n   others Eigen::MatrixXd xref;\n\n   // Foot trajectory generator\n   double max_height_feet = 0.05;  // * (1000/312.5);  // height * correction\n   coefficient double t_lock_before_touchdown = 0.07; std::vector<TrajGen>\n   myTrajGen;\n\n   // Variables for foot trajectory generator\n   int i_end_gait = 0;\n   Eigen::Matrix<double, 1, 4> t_stance =\n       Eigen::Matrix<double, 1, 4>::Zero();  // Total duration of current stance\n   phase for each foot Eigen::Matrix<double, 2, 4> footsteps_target =\n   Eigen::Matrix<double, 2, 4>::Zero(); Eigen::MatrixXd goals =\n   Eigen::MatrixXd::Zero(3, 4);   // Store 3D target position for feet\n   Eigen::MatrixXd vgoals = Eigen::MatrixXd::Zero(3, 4);  // Store 3D target\n   velocity for feet Eigen::MatrixXd agoals = Eigen::MatrixXd::Zero(3, 4);  //\n   Store 3D target acceleration for feet Eigen::Matrix<double, 6, 4> mgoals =\n       Eigen::Matrix<double, 6, 4>::Zero();  // Storage variable for the\n   trajectory generator\n\n   Eigen::Matrix<double, 11, 4> res_gen = Eigen::Matrix<double, 11, 4>::Zero();\n   // Result of the generator\n   */\n\n private:\n  // Inputs of the constructor\n  double dt;  // Time step of the contact sequence (time step of the MPC)\n\n  // Matrices initialisation\n  Eigen::Matrix<double, 4, 3> feet_position_ref = Eigen::Matrix<double, 4, 3>::Zero();\n  Eigen::Matrix<double, 4, 3> feet_velocity_ref = Eigen::Matrix<double, 4, 3>::Zero();\n  Eigen::Matrix<double, 4, 3> feet_acceleration_ref = Eigen::Matrix<double, 4, 3>::Zero();\n  Eigen::Matrix<double, 1, 4> flag_in_contact = Eigen::Matrix<double, 1, 4>::Zero();\n  Eigen::Matrix<double, 3, 3> base_orientation_ref = Eigen::Matrix<double, 3, 3>::Zero();\n  Eigen::Matrix<double, 1, 3> base_angularvelocity_ref = Eigen::Matrix<double, 1, 3>::Zero();\n  Eigen::Matrix<double, 1, 3> base_angularacceleration_ref = Eigen::Matrix<double, 1, 3>::Zero();\n  Eigen::Matrix<double, 1, 3> base_position_ref = Eigen::Matrix<double, 1, 3>::Zero();\n  Eigen::Matrix<double, 1, 3> base_linearvelocity_ref = Eigen::Matrix<double, 1, 3>::Zero();\n  Eigen::Matrix<double, 1, 3> base_linearacceleration_ref = Eigen::Matrix<double, 1, 3>::Zero();\n  Eigen::Matrix<double, 6, 1> x_ref = Eigen::Matrix<double, 6, 1>::Zero();\n  Eigen::Matrix<double, 6, 1> x = Eigen::Matrix<double, 6, 1>::Zero();\n  Eigen::Matrix<double, 6, 1> dx_ref = Eigen::Matrix<double, 6, 1>::Zero();\n  Eigen::Matrix<double, 6, 1> dx = Eigen::Matrix<double, 6, 1>::Zero();\n  Eigen::Matrix<double, 18, 18> J = Eigen::Matrix<double, 18, 18>::Zero();\n  Eigen::Matrix<double, 18, 18> invJ = Eigen::Matrix<double, 18, 18>::Zero();\n  Eigen::Matrix<double, 1, 18> acc = Eigen::Matrix<double, 1, 18>::Zero();\n  Eigen::Matrix<double, 1, 18> x_err = Eigen::Matrix<double, 1, 18>::Zero();\n  Eigen::Matrix<double, 1, 18> dx_r = Eigen::Matrix<double, 1, 18>::Zero();\n\n  Eigen::Matrix<double, 4, 3> pfeet_err = Eigen::Matrix<double, 4, 3>::Zero();\n  Eigen::Matrix<double, 4, 3> vfeet_ref = Eigen::Matrix<double, 4, 3>::Zero();\n  Eigen::Matrix<double, 4, 3> afeet = Eigen::Matrix<double, 4, 3>::Zero();\n  Eigen::Matrix<double, 1, 3> e_basispos = Eigen::Matrix<double, 1, 3>::Zero();\n  Eigen::Matrix<double, 1, 3> abasis = Eigen::Matrix<double, 1, 3>::Zero();\n  Eigen::Matrix<double, 1, 3> e_basisrot = Eigen::Matrix<double, 1, 3>::Zero();\n  Eigen::Matrix<double, 1, 3> awbasis = Eigen::Matrix<double, 1, 3>::Zero();\n\n  Eigen::MatrixXd ddq = Eigen::MatrixXd::Zero(18, 1);\n  Eigen::MatrixXd q_step = Eigen::MatrixXd::Zero(18, 1);\n  Eigen::MatrixXd dq_cmd = Eigen::MatrixXd::Zero(18, 1);\n\n  // Gains\n  double Kp_base_orientation = 100.0;\n  double Kd_base_orientation = 2.0 * std::sqrt(Kp_base_orientation);\n  \n  double Kp_base_position = 100.0;\n  double Kd_base_position = 2.0 * std::sqrt(Kp_base_position);\n\n  double Kp_flyingfeet = 1000.0;\n  double Kd_flyingfeet = 5.0 * std::sqrt(Kp_flyingfeet);\n\n public:\n  InvKin();\n  InvKin(double dt_in);\n  \n  Eigen::Matrix<double, 1, 3> cross3(Eigen::Matrix<double, 1, 3> left, Eigen::Matrix<double, 1, 3> right);\n\n  Eigen::MatrixXd refreshAndCompute(const Eigen::MatrixXd &x_cmd, const Eigen::MatrixXd &contacts,\n                                    const Eigen::MatrixXd &goals, const Eigen::MatrixXd &vgoals, const Eigen::MatrixXd &agoals,\n                                    const Eigen::MatrixXd &posf, const Eigen::MatrixXd &vf, const Eigen::MatrixXd &wf, const Eigen::MatrixXd &af,\n                                    const Eigen::MatrixXd &Jf, const Eigen::MatrixXd &posb, const Eigen::MatrixXd &rotb, const Eigen::MatrixXd &vb,\n                                    const Eigen::MatrixXd &ab, const Eigen::MatrixXd &Jb);\n  Eigen::MatrixXd computeInvKin(const Eigen::MatrixXd &posf, const Eigen::MatrixXd &vf, const Eigen::MatrixXd &wf, const Eigen::MatrixXd &af,\n                                const Eigen::MatrixXd &Jf, const Eigen::MatrixXd &posb, const Eigen::MatrixXd &rotb, const Eigen::MatrixXd &vb, const Eigen::MatrixXd &ab,\n                                const Eigen::MatrixXd &Jb);\n  Eigen::MatrixXd get_q_step();\n  Eigen::MatrixXd get_dq_cmd();\n  /*void Print();\n\n  int create_walk();\n  int create_trot();\n  int create_gait_f();\n  int roll(int k);\n  int compute_footsteps(Eigen::MatrixXd q_cur, Eigen::MatrixXd v_cur,\n  Eigen::MatrixXd v_ref); double get_stance_swing_duration(int i, int j, double\n  value); int compute_next_footstep(int i, int j); int\n  getRefStates(Eigen::MatrixXd q, Eigen::MatrixXd v, Eigen::MatrixXd vref,\n  double z_average); int update_target_footsteps(); int\n  update_trajectory_generator(int k, double h_estim); int run_planner(int k,\n  const Eigen::MatrixXd &q, const Eigen::MatrixXd &v, const Eigen::MatrixXd\n  &b_vref, double h_estim, double z_average);*/\n\n  // Accessors (to retrieve C data from Python)\n  /*Eigen::MatrixXd get_xref();\n  Eigen::MatrixXd get_fsteps();\n  Eigen::MatrixXd get_gait();\n  Eigen::MatrixXd get_goals();\n  Eigen::MatrixXd get_vgoals();\n  Eigen::MatrixXd get_agoals();*/\n};\n\ntemplate<typename _Matrix_Type_>\n_Matrix_Type_ pseudoInverse(const _Matrix_Type_ &a, double epsilon = std::numeric_limits<double>::epsilon())\n{\n\tEigen::JacobiSVD< _Matrix_Type_ > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV);\n\tdouble tolerance = epsilon * static_cast<double>(std::max(a.cols(), a.rows())) *svd.singularValues().array().abs()(0);\n\treturn svd.matrixV() *  (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0).matrix().asDiagonal() * svd.matrixU().adjoint();\n}\n\n\n#endif  // INVKIN_H_INCLUDED\n", "meta": {"hexsha": "90e694cf7defcf522edfbc189a666af8cf9f4ecb", "size": 10547, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/quadruped-reactive-walking/InvKin.hpp", "max_stars_repo_name": "nim65s/quadruped-reactive-walking", "max_stars_repo_head_hexsha": "1e0f4069fd11af85abf10bfc8f9d66200c672646", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-03-03T10:59:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-13T15:05:25.000Z", "max_issues_repo_path": "include/quadruped-reactive-walking/InvKin.hpp", "max_issues_repo_name": "nim65s/quadruped-reactive-walking", "max_issues_repo_head_hexsha": "1e0f4069fd11af85abf10bfc8f9d66200c672646", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/quadruped-reactive-walking/InvKin.hpp", "max_forks_repo_name": "nim65s/quadruped-reactive-walking", "max_forks_repo_head_hexsha": "1e0f4069fd11af85abf10bfc8f9d66200c672646", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-17T13:34:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T10:58:37.000Z", "avg_line_length": 51.4487804878, "max_line_length": 172, "alphanum_fraction": 0.6696691002, "num_tokens": 3173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23400269564086654}}
{"text": "// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-\n\n// -- BEGIN LICENSE BLOCK ----------------------------------------------\n// Copyright (c) 2018, FZI Forschungszentrum Informatik\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted\n// provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions\n//    and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of\n//    conditions and the following disclaimer in the documentation and/or other materials provided\n//    with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to\n//    endorse or promote products derived from this software without specific prior written\n//    permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR\n// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\n// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n// -- END LICENSE BLOCK ------------------------------------------------\n\n//----------------------------------------------------------------------\n/*!\\file\n *\n * \\author  Julius Ziegler <ziegler@fzi.de>\n * \\date    2012-03-06\n *\n */\n//----------------------------------------------------------------------\n\n#if !defined(LOCALGEOGRAPHICCS_HPP)\n#define LOCALGEOGRAPHICCS_HPP\n\n#include \"convert_coordinates.hpp\"\n\n#include <boost/tuple/tuple.hpp>\n\n#include <utility>\n\nstruct LocalGeographicCS\n{\n  LocalGeographicCS();\n  LocalGeographicCS( double lat0, double lon0 );\n\n  void set_origin( double lat0, double lon0 );\n\n  void ll2xy( double lat, double lon, double& x, double& y ) const;\n  void xy2ll( double x, double y, double& lat, double& lon ) const;\n\n  boost::tuple<double, double> ll2xy( double lat, double lon ) const;\n  boost::tuple<double, double> xy2ll( double x, double y ) const;\n\n  // operate on containers\n  template<class ItIn, class ItOut>\n  void ll2xy( const ItIn& lat_begin, const ItIn& lat_end, const ItIn& lon_begin, const ItOut& x_begin, const ItOut& y_begin ) const;\n\n  template<class ItIn, class ItOut>\n  void xy2ll( const ItIn& x_begin, const ItIn& x_end, const ItIn& y_begin, const ItOut& lat_begin, const ItOut& lon_begin ) const;\n\nprivate:\n  double _scale;\n  double _x0, _y0;\n};\n\ninline LocalGeographicCS::LocalGeographicCS( double lat0, double lon0 )\n{\n  set_origin( lat0, lon0 );\n}\n\ninline LocalGeographicCS::LocalGeographicCS()\n{}\n\ninline void LocalGeographicCS::set_origin( double lat0, double lon0 )\n{\n  _scale = convert_coordinates::lat_to_scale( lat0 );\n  convert_coordinates::latlon_to_mercator( lat0, lon0, _scale, _x0, _y0 );\n}\n\ninline void LocalGeographicCS::ll2xy( double lat, double lon, double& x, double& y ) const\n{\n  convert_coordinates::latlon_to_mercator( lat, lon, _scale, x, y );\n  x -= _x0;\n  y -= _y0;\n}\n\ninline boost::tuple<double, double> LocalGeographicCS::ll2xy( double lat, double lon ) const\n{\n  double x, y;\n  ll2xy( lat, lon, x, y );\n  return boost::make_tuple( x, y );\n}\n\ninline void LocalGeographicCS::xy2ll( double x, double y, double& lat, double& lon ) const\n{\n  x += _x0;\n  y += _y0;\n\n  convert_coordinates::mercator_to_latlon( x, y, _scale, lat, lon );\n}\n\ninline boost::tuple<double, double> LocalGeographicCS::xy2ll( double x, double y ) const\n{\n  double lat, lon;\n  xy2ll( x, y, lat, lon );\n  return boost::make_tuple( lat, lon );\n}\n\n// operate on containers\ntemplate<class ItIn, class ItOut>\nvoid LocalGeographicCS::ll2xy( const ItIn& lat_begin, const ItIn& lat_end, const ItIn& lon_begin, const ItOut& x_begin, const ItOut& y_begin ) const\n{\n  ItIn lat = lat_begin;\n  ItIn lon = lon_begin;\n  ItOut x = x_begin;\n  ItOut y = y_begin;\n\n  for( ; lat != lat_end; lat++, lon++, x++, y++ )\n    {\n      ll2xy( *lat, *lon, *x, *y );\n    }\n}\n\ntemplate<class ItIn, class ItOut>\nvoid LocalGeographicCS::xy2ll( const ItIn& x_begin, const ItIn& x_end, const ItIn& y_begin, const ItOut& lat_begin, const ItOut& lon_begin ) const\n{\n  ItIn x = x_begin;\n  ItIn y = y_begin;\n\n  ItOut lat = lat_begin;\n  ItOut lon = lon_begin;\n\n  for( ; x != x_end; lat++, lon++, x++, y++ )\n    xy2ll( *x, *y, *lat, *lon );\n}\n\n#endif\n", "meta": {"hexsha": "fb17aa30fd873ec7c37d441bd507994958553bd8", "size": 4873, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/liblanelet/LocalGeographicCS.hpp", "max_stars_repo_name": "brand666/liblanelet", "max_stars_repo_head_hexsha": "252e436ae9f705f8004d86b504be6a5f0c8bcc19", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2017-11-29T12:44:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T12:45:52.000Z", "max_issues_repo_path": "src/liblanelet/LocalGeographicCS.hpp", "max_issues_repo_name": "brand666/liblanelet", "max_issues_repo_head_hexsha": "252e436ae9f705f8004d86b504be6a5f0c8bcc19", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-11-02T09:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-16T20:03:17.000Z", "max_forks_repo_path": "src/liblanelet/LocalGeographicCS.hpp", "max_forks_repo_name": "brand666/liblanelet", "max_forks_repo_head_hexsha": "252e436ae9f705f8004d86b504be6a5f0c8bcc19", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-10-26T08:42:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T12:45:52.000Z", "avg_line_length": 33.6068965517, "max_line_length": 148, "alphanum_fraction": 0.6821260004, "num_tokens": 1293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23390873404628146}}
{"text": "//=============================================================================================================\n/**\n* @file     spectrogram.cpp\n* @author   Martin Henfling <martin.henfling@tu-ilmenau.de>;\n*           Daniel Knobl <daniel.knobl@tu-ilmenau.de>;\n* @version  1.0\n* @date     September, 2015\n*\n* @section  LICENSE\n*\n* Copyright (C) 2014, Martin Henfling and Daniel Knobl. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n*       following disclaimer.\n*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n*       the following disclaimer in the documentation and/or other materials provided with the distribution.\n*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n*       to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, 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 INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief    Implementation of spectrogram class.\n*/\n\n//*************************************************************************************************************\n//=============================================================================================================\n// INCLUDES\n//=============================================================================================================\n\n#include \"spectrogram.h\"\n#include \"math.h\"\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// Eigen INCLUDES\n//=============================================================================================================\n\n#include <Eigen/SparseCore>\n#include <unsupported/Eigen/FFT>\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// USED NAMESPACES\n//=============================================================================================================\n\nusing namespace UTILSLIB;\n\n\n//*************************************************************************************************************\n//=============================================================================================================\n// DEFINE MEMBER METHODS\n//=============================================================================================================\n\nVectorXd Spectrogram::gauss_window (qint32 sample_count, qreal scale, quint32 translation)\n{\n    VectorXd gauss = VectorXd::Zero(sample_count);\n\n    for(qint32 n = 0; n < sample_count; n++)\n    {\n        qreal t = (qreal(n) - translation) / scale;\n        gauss[n] = exp(-3.14 * pow(t, 2))*pow(sqrt(scale),(-1))*pow(qreal(2),(0.25));\n    }\n\n    return gauss;\n}\n\n//-----------------------------------------------------------------------------------------------------------------\n\nMatrixXd Spectrogram::make_spectrogram(VectorXd signal, qint32 window_size = 0)\n{\n    if(window_size == 0)\n        window_size = signal.rows()/4;\n\n    Eigen::FFT<double> fft;\n    MatrixXd tf_matrix = MatrixXd::Zero(signal.rows()/2, signal.rows());\n\n    for(qint32 translate = 0; translate < signal.rows(); translate++)\n    {\n        VectorXd envelope = gauss_window(signal.rows(), window_size, translate);\n\n        VectorXd windowed_sig = VectorXd::Zero(signal.rows());\n        VectorXcd fft_win_sig = VectorXcd::Zero(signal.rows());\n\n        VectorXd real_coeffs = VectorXd::Zero(signal.rows()/2);\n\n        for(qint32 sample = 0; sample < signal.rows(); sample++)\n            windowed_sig[sample] = signal[sample] * envelope[sample];\n\n        fft.fwd(fft_win_sig, windowed_sig);\n\n        for(qint32 i= 0; i<signal.rows()/2; i++)\n        {\n            qreal value = pow(abs(fft_win_sig[i]), 2.0);\n            real_coeffs[i] = value;\n        }\n\n        tf_matrix.col(translate) = real_coeffs;\n    }\n    return tf_matrix;\n}\n", "meta": {"hexsha": "f5303dc93fac5fb9e49f6c5000f576e8d24e4529", "size": 5002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MNE/utils/spectrogram.cpp", "max_stars_repo_name": "13grife37/mne-cpp-swpold", "max_stars_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-20T20:21:16.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-26T16:30:25.000Z", "max_issues_repo_path": "MNE/utils/spectrogram.cpp", "max_issues_repo_name": "13grife37/mne-cpp-swpold", "max_issues_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MNE/utils/spectrogram.cpp", "max_forks_repo_name": "13grife37/mne-cpp-swpold", "max_forks_repo_head_hexsha": "9b89b3d7fe273d9f4ffd69b504e17f284eaba263", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-04-23T15:55:31.000Z", "max_forks_repo_forks_event_max_datetime": "2017-04-23T15:55:31.000Z", "avg_line_length": 44.2654867257, "max_line_length": 116, "alphanum_fraction": 0.4796081567, "num_tokens": 859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23390872761876408}}
{"text": "/*\n * prefilter_view_pairs.cc\n *\n *  Created on: Jul 12, 2016\n *      Author: LeonMing\n */\n\n#include \"theia/sfm/view_graph/prefilter_view_pairs.h\"\n\n#include <ceres/rotation.h>\n#include <Eigen/Core>\n#include <Eigen/Geometry>\n#include <Eigen/SVD>\n#include <glog/logging.h>\n#include <unordered_map>\n#include <unordered_set>\n#include <cereal/access.hpp>\n#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <cmath>\n\n#include \"theia/math/util.h\"\n#include \"theia/math/graph/minimum_spanning_tree.h\"\n#include \"theia/util/hash.h\"\n#include \"theia/util/map_util.h\"\n#include \"theia/sfm/twoview_info.h\"\n#include \"theia/sfm/types.h\"\n#include \"theia/sfm/view_graph/view_graph.h\"\n#include \"theia/util/filesystem.h\"\n\n#include <lemon/lp.h>\n#include <lemon/lp_base.h>\n\nnamespace theia {\n\nstd::ofstream fileWriter(\"cycle_error_report.txt\", std::ios::out);\n\nbool PrefilterViewPairs(ViewGraph* viewGraph) {\n  CHECK_NOTNULL(viewGraph);\n\n// Declare MST extractor and MST and edges\n  MinimumSpanningTree<ViewId, int> mst_extractor;\n  std::unordered_set<ViewIdPair> mst;\n  std::unordered_map<ViewIdPair, TwoViewInfo> edges;\n\n\n// Create MST\n  edges = viewGraph->GetAllEdges();\n\n  for (const auto& edge : edges) {\n    mst_extractor.AddEdge(edge.first.first, edge.first.second, 1);\n  }\n\n// Add values to MST\n  mst_extractor.Extract(&mst);\n\n\n\n\n// Preparing variables for creating chains\n  std::vector<std::vector<ViewIdPair> > chainList;\n  std::unordered_set<ViewIdPair> visited;\n  std::vector<ViewIdPair> oldChain;\n// Create chains\n  CreateChains(chainList, mst, visited, oldChain, mst.begin()->first);\n\n\n\n\n// Preparing variables for creating cycles\n// Store cycles as vectors of ViewIdPairs, with a big vector holding all the cycles\n  std::vector<std::vector<ViewIdPair> > cycleList;\n// Create cycles\n  CreateCycles(edges, chainList, mst, cycleList);\n\n\n\n\n// Preparing variables for calculating errors\n  std::unordered_set<ViewIdPair> allUsedEdges;\n  std::vector<double> errors;\n// Calculate and print cycle errors\n CalculateErrors(cycleList, edges, allUsedEdges, errors);\n\n\n// Preparing variables for calculating translation errors\n  std::unordered_set<ViewIdPair> allUsedTranslationEdges;\n  std::vector<std::vector<ViewIdPair> > translationCycles;\n  std::vector<double> translationErrors;\n// Calculate translation cycle errors\n  CalculateTranslationErrors(cycleList, translationCycles, edges, allUsedTranslationEdges, translationErrors);\n\n\n\n// Preparing variables for inferencing\n  std::unordered_map<int, ViewIdPair> number2Edge;\n  std::unordered_map<ViewIdPair, int> edge2Number;\n  int it = 0;\n  for (auto& edge : allUsedEdges) {\n\t  number2Edge.emplace(it, edge);\n\t  edge2Number.emplace(edge, it);\n\t  ++it;\n  }\n\n  std::unordered_map<int, ViewIdPair> number2TranslationEdge;\n  std::unordered_map<ViewIdPair, int> translationEdge2Number;\n  int it2 = 0;\n  for (auto& edge : allUsedTranslationEdges) {\n\t  number2TranslationEdge.emplace(it2, edge);\n\t  translationEdge2Number.emplace(edge, it2);\n\t  ++it2;\n  }\n\n  double rotSigma = 2*M_PI/180;\n  double transSigma = 0.011;\n\n// Edges that we need to remove\n  std::unordered_set<ViewIdPair> viewPairsToRemove;\n// Do inferences to figure out what edges to remove\n  DoInference(rotSigma, cycleList, errors, edge2Number, number2Edge, allUsedEdges, viewPairsToRemove);\n// Do inferences based on relative translations\n  DoInference(transSigma, translationCycles, translationErrors, translationEdge2Number, number2TranslationEdge, allUsedTranslationEdges, viewPairsToRemove);\n\n\n\n// Remove the edge if it is incorrect\n  for (const ViewIdPair viewIdPair : viewPairsToRemove) {\n    viewGraph->RemoveEdge(viewIdPair.first, viewIdPair.second);\n  }\n  VLOG(1) << \"Removed \" << viewPairsToRemove.size()\n          << \" view pairs by rotation prefiltering.\";\n  return true;\n}\n\n\nvoid CreateChains(std::vector<std::vector<ViewIdPair> >& chainList,\n\t\t\t      std::unordered_set<ViewIdPair>& mst,\n\t\t\t\t  std::unordered_set<ViewIdPair>& visited,\n\t\t\t\t  std::vector<ViewIdPair> oldChain,\n\t\t\t\t  ViewId root) {\n\tfor (ViewIdPair e : mst) {\n\t\tif (visited.find(e) != visited.end()) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (e.first == root) {\n\t\t\toldChain.emplace_back(e);\n\t\t\tstd::vector<ViewIdPair> chain = oldChain;\n\t\t\toldChain.pop_back();\n\t\t\tchainList.emplace_back(chain);\n\t\t\tvisited.insert(e);\n\n\t\t\tCreateChains(chainList, mst, visited, chain, e.second);\n\t\t}\n\t\telse if (e.second == root) {\n\t\t\toldChain.emplace_back(e);\n\t\t\tstd::vector<ViewIdPair> chain = oldChain;\n\t\t\toldChain.pop_back();\n\t\t\tchainList.emplace_back(chain);\n\t\t\tvisited.insert(e);\n\n\t\t\tCreateChains(chainList, mst, visited, chain, e.first);\n\t\t}\n\t}\n}\n\n\nvoid CreateCycles(std::unordered_map<ViewIdPair, TwoViewInfo>& edges,\n\t\t\t\t  std::vector<std::vector<ViewIdPair> >& chainList,\n\t\t\t\t  std::unordered_set<ViewIdPair>& mst,\n\t\t\t\t  std::vector<std::vector<ViewIdPair> >& cycleList) {\n\n\tstd::unordered_set<ViewIdPair> otherEdges; // not in MST\n\n\tfor (auto& e : edges) {\n\t\tif (mst.find(e.first) == mst.end()) {\n\t\t\totherEdges.insert(e.first);\n\t\t}\n\t}\n\n\tfor (ViewIdPair e : otherEdges) {\n\t\tif (e.first == mst.begin()->first || e.second == mst.begin()->first) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::vector<ViewIdPair> cycle;\n\t\tcycle.emplace_back(e);\n\t\tstd::vector<ViewIdPair> chain1;\n\t\tstd::vector<ViewIdPair> chain2;\n\n\t\tfor (std::vector<ViewIdPair> chain : chainList) {\n\t\t\tViewIdPair lastE = chain.end()[-1];\n\t\t\tViewIdPair secondtolastE = chain.end()[-2];\n\t\t\tif (\n\t\t\t\t((e.first == lastE.first || e.first == lastE.second)\n\t\t\t\t&& !(e.first == secondtolastE.first || e.first == secondtolastE.second))\n\t\t\t\t||\n\t\t\t\t((e.first == lastE.first || e.first == lastE.second)\n\t\t\t\t&& (chain.size() == 1))\n\t\t\t\t) {\n\t\t\t\tchain1 = chain;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\t((e.second == lastE.first || e.second == lastE.second)\n\t\t\t\t&& !(e.second == secondtolastE.first || e.second == secondtolastE.second))\n\t\t\t\t||\n\t\t\t\t((e.second == lastE.first || e.second == lastE.second)\n\t\t\t\t&& (chain.size() == 1))\n\t\t\t\t) {\n\t\t\t\tchain2 = chain;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tstd::set_symmetric_difference(chain1.begin(), chain1.end(),\n\t\t\t\t                      chain2.begin(), chain2.end(),\n\t\t\t\t                      std::back_inserter(cycle));\n\t\tcycleList.emplace_back(cycle);\n\t}\n}\n\n\nvoid CalculateErrors(std::vector<std::vector<ViewIdPair> >& cycleList,\n\t\t\t\t\t std::unordered_map<ViewIdPair, TwoViewInfo>& edges,\n\t\t\t\t\t std::unordered_set<ViewIdPair>& allUsedEdges,\n\t\t\t\t\t std::vector<double>& errors) {\n\tfor (std::vector<ViewIdPair> cycle : cycleList) {\n\n\t\tdouble error;\n\t\tEigen::Matrix3d combinedRotation;\n\t\tceres::AngleAxisToRotationMatrix(\n\t\t\tedges[cycle[0]].rotation_2.data(),\n\t\t\tceres::RowMajorAdapter3x3(combinedRotation.data()));\n\n\t\tstd::vector<ViewIdPair> usedEdges;\n\t\tusedEdges.push_back(cycle.front());\n\t\tallUsedEdges.insert(cycle.front());\n\t\tstd::vector<ViewId> nextEdge;\n\t\tnextEdge.push_back(cycle.front().second);\n\t\twhile (usedEdges.size() < cycle.size()) {\n\t\t\tfor (ViewIdPair edge : cycle) {\n\n\t\t\t\tTwoViewInfo info = edges[edge];\n\t\t\t\tEigen::Matrix3d rotation_matrix;\n\n\t\t\t\tif (std::find(usedEdges.begin(), usedEdges.end(), edge) != usedEdges.end()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (edge.first == nextEdge.back()) {\n\t\t\t\t\tceres::AngleAxisToRotationMatrix(\n\t\t\t\t\t\tinfo.rotation_2.data(),\n\t\t\t\t\t\tceres::RowMajorAdapter3x3(rotation_matrix.data()));\n\t\t\t\t\tcombinedRotation *= rotation_matrix;\n\t\t\t\t\tusedEdges.push_back(edge);\n\t\t\t\t\tif (allUsedEdges.find(edge) == allUsedEdges.end()) {\n\t\t\t\t\t\tallUsedEdges.insert(edge);\n\t\t\t\t\t}\n\t\t\t\t\tnextEdge.push_back(edge.second);\n\t\t\t\t\tfileWriter << rotation_matrix;\n\t\t\t\t\tfileWriter << \"\\n\\n\";\n\t\t\t\t} else if (edge.second == nextEdge.back()) {\n\t\t\t\t\tceres::AngleAxisToRotationMatrix(\n\t\t\t\t\t\tinfo.rotation_2.data(),\n\t\t\t\t\t\tceres::RowMajorAdapter3x3(rotation_matrix.data()));\n\t\t\t\t\tcombinedRotation *= rotation_matrix.transpose();\n\t\t\t\t\tusedEdges.push_back(edge);\n\t\t\t\t\tif (allUsedEdges.find(edge) == allUsedEdges.end()) {\n\t\t\t\t\t\tallUsedEdges.insert(edge);\n\t\t\t\t\t}\n\t\t\t\t\tnextEdge.push_back(edge.first);\n\t\t\t\t\tfileWriter << rotation_matrix.transpose();\n\t\t\t\t\tfileWriter << \"\\n\\n\";\n\t\t\t\t} else {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfileWriter << \"Combined Rotation:\\n\";\n\t\tfileWriter << combinedRotation;\n\n\t\tfileWriter << \"\\n\\nError:\\n\";\n\t\terror = acos((combinedRotation.trace()-1)/2);\n\t\tfileWriter << error << \"\\n\\n\\n\\n\";\n\t\terrors.push_back(error);\n\t}\n}\n\n\nvoid CalculateTranslationErrors(std::vector<std::vector<ViewIdPair> >& cycleList,\n\t\t\t\t\t\t\t\tstd::vector<std::vector<ViewIdPair> >& translationCycles,\n\t\t \t \t \t \t \t \tstd::unordered_map<ViewIdPair, TwoViewInfo>& edges,\n\t\t\t\t\t\t\t\tstd::unordered_set<ViewIdPair>& allUsedTranslationEdges,\n\t\t\t\t\t\t\t\tstd::vector<double>& translationErrors) {\n\tfor (auto& cycle : cycleList) {\n\t\tif (cycle.size() == 3) {\n\t\t\ttranslationCycles.push_back(cycle);\n\t\t}\n\t}\n\tstd::cout << \"Singular Values: \" << \"\\n\\n\";\n\tfor (auto& cycle : translationCycles) {\n\t\tEigen::Matrix3d translationsMatrix;\n\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\ttranslationsMatrix(i, 0) = edges[cycle.front()].position_2[i];\n\t\t}\n\t\tstd::vector<ViewIdPair> usedEdges;\n\t\tusedEdges.push_back(cycle.front());\n\t\tallUsedTranslationEdges.insert(cycle.front());\n\t\tstd::vector<ViewId> nextEdge;\n\t\tnextEdge.push_back(cycle.front().second);\n\t\twhile (usedEdges.size() < 3) {\n\t\t\tfor (int j = 1; j < 3; ++j) {\n\t\t\t\tif (std::find(usedEdges.begin(), usedEdges.end(), cycle[j]) != usedEdges.end()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if (cycle[j].first == nextEdge.back()) {\n\t\t\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\t\t\ttranslationsMatrix(i, j) = edges[cycle[j]].position_2[i];\n\t\t\t\t\t}\n\t\t\t\t\tusedEdges.push_back(cycle[j]);\n\t\t\t\t\tif (allUsedTranslationEdges.find(cycle[j]) == allUsedTranslationEdges.end()) {\n\t\t\t\t\t\tallUsedTranslationEdges.insert(cycle[j]);\n\t\t\t\t\t}\n\t\t\t\t\tnextEdge.push_back(cycle[j].second);\n\t\t\t\t} else if (cycle[j].second == nextEdge.back()) {\n\t\t\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\t\t\ttranslationsMatrix(i, j) = -(edges[cycle[j]].position_2[i]);\n\t\t\t\t\t}\n\t\t\t\t\tusedEdges.push_back(cycle[j]);\n\t\t\t\t\tif (allUsedTranslationEdges.find(cycle[j]) == allUsedTranslationEdges.end()) {\n\t\t\t\t\t\tallUsedTranslationEdges.insert(cycle[j]);\n\t\t\t\t\t}\n\t\t\t\t\tnextEdge.push_back(cycle[j].first);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n//\t\tstd::cout << translationsMatrix << \"\\n\";\n\t\tEigen::JacobiSVD<Eigen::Matrix3d> svd(translationsMatrix);\n\t\tdouble error = svd.singularValues()[2];\n\t\ttranslationErrors.push_back(error);\n\t}\n\tfor (int i = 0; i < translationErrors.size(); ++i) {\n\t\tstd::cout << \"Cycle \" << i << \"\\n\" << translationErrors[i] << \"\\n\\n\";\n\t}\n}\n\n\nvoid DoInference(double sigma,\n\t\t\t\t std::vector<std::vector<ViewIdPair> >& cycleList,\n\t\t\t\t std::vector<double>& errors,\n\t\t\t\t std::unordered_map<ViewIdPair, int>& edge2Number,\n\t\t\t\t std::unordered_map<int, ViewIdPair>& number2Edge,\n\t\t\t\t std::unordered_set<ViewIdPair>& allUsedEdges,\n\t\t\t\t std::unordered_set<ViewIdPair>& viewPairsToRemove) {\n\tconst double rhoe = (-log(0.1)) - (-log(0.9));\n\tdouble rhol;\n\n\tconst double sigmaInliers = sigma;\n\tconst double eps = pow(2,-52);\n\n\tusing namespace lemon;\n\n\t// Create an instance of the default LP solver class\n\t// (it will represent an \"empty\" problem at first)\n\tLp lp;\n\n\t// Set up variables\n\tstd::vector<Lp::Col> xe;\n\tstd::vector<Lp::Col> xl;\n\tLp::Expr totalEdges;\n\tLp::Expr totalCycles;\n\tstd::map<std::vector<ViewIdPair>, std::vector<int> > index;\n\tfor (auto& cycle : cycleList) {\n\t\tstd::vector<int> tempVector;\n\t\tfor (auto& edge : cycle) {\n\t\t\ttempVector.push_back(edge2Number[edge]);\n\t\t}\n\t\tindex.emplace(cycle, tempVector);\n\t}\n\n\t// Add columns (variables) to the problem\n\tfor (int i = 0; i < allUsedEdges.size(); ++i) { // For every edge used in any cycle, make a new xe\n\t\txe.push_back(lp.addCol());\n\t}\n\tfor (int i = 0; i < cycleList.size(); ++i) { // For every cycle in the cycleList, make a new xl\n\t\txl.push_back(lp.addCol());\n\t}\n\n\t// Add rows (constraints) to the problem\n\tfor (int cycle = 0; cycle < cycleList.size(); ++cycle) { // For every cycle in the cycleList\n\n\t\tLp::Expr total;\n\t\tfor (int edge = 0; edge < cycleList[cycle].size(); ++edge) {\n\t\t\tlp.addRow(xl[cycle] >= xe[(index[cycleList[cycle]])[edge]]); // xl for this cycle is greater than each xe\n\t\t\ttotal += xe[(index[cycleList[cycle]])[edge]];\n\t\t\ttotalEdges += total;\n\t\t}\n\t\tlp.addRow(xl[cycle] <= total);\n\n\t\t// Calculate rhol for this cycle\n\t\tdouble pErrorInliers = exp(-errors[cycle]/sigmaInliers)/(sigmaInliers*(1-exp(-M_PI/sigmaInliers)));\n\t\tdouble pErrorOutliers = (1-exp(-errors[cycle]/sigmaInliers))/(M_PI-sigmaInliers*(1-exp(-M_PI/sigmaInliers)));\n\t\trhol = (-log(pErrorOutliers + eps))-(-log(pErrorInliers + eps));\n\t\ttotalCycles += rhol * xl[cycle];\n\t}\n\n\t// Set lower and upper bounds for the columns (variables)\n\tfor (int k = 0; k < xe.size(); ++k) {\n\t\tlp.colBounds(xe[k], 0, 1);\n\t}\n\tfor (int k = 0; k < xl.size(); ++k) {\n\t\tlp.colBounds(xl[k], 0, 1);\n\t}\n\n\t// Specify the objective function\n\tlp.min();\n\tlp.obj(rhoe * totalEdges + totalCycles);\n\n\t// Solve the problem using the underlying LP solver\n\tlp.solve();\n\n\t// Print the results\n\tif (lp.primalType() == Lp::OPTIMAL) {\n\t\tstd::cout << \"Objective function value: \" << lp.primal() << \"\\n\\n\";\n\t\tfor (int i = 0; i < xe.size(); ++i) {\n\t\t\tstd::cout << \"Edge \" << i << \": \" << number2Edge[i].first << \" \" << number2Edge[i].second << \":\\t\" << lp.primal(xe[i]) << \"\\n\";\n\t\t\tif (lp.primal(xe[i]) == 1) {\n\t\t\t\tviewPairsToRemove.insert(number2Edge[i]);\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i < xl.size(); ++i) {\n\t\t\tstd::cout << \"Cycle \" << i << \": \" << lp.primal(xl[i]) << \"\\n\";\n\t\t}\n\t} else {\n\t\tstd::cout << \"Optimal solution not found.\" << \"\\n\";\n\t}\n}\n\n\n}  // namespace theia\n\n", "meta": {"hexsha": "a6f6270cd77313e0c82fc54069095b3c746f1263", "size": 13389, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/theia/sfm/view_graph/prefilter_view_pairs.cc", "max_stars_repo_name": "LEON-MING/TheiaSfM_Leon", "max_stars_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/theia/sfm/view_graph/prefilter_view_pairs.cc", "max_issues_repo_name": "LEON-MING/TheiaSfM_Leon", "max_issues_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/theia/sfm/view_graph/prefilter_view_pairs.cc", "max_forks_repo_name": "LEON-MING/TheiaSfM_Leon", "max_forks_repo_head_hexsha": "8ac187b80100ad7f52fe9af49fa4a0db6db226b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4988610478, "max_line_length": 156, "alphanum_fraction": 0.6683844947, "num_tokens": 3797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4339814648038985, "lm_q1q2_score": 0.23390872761876402}}
{"text": "#include \"syanten.hpp\"\r\n\r\n#include <boost/dll.hpp>\r\n#include <spdlog/spdlog.h>\r\n\r\n#include <fstream>\r\n\r\n#include \"bitutils.hpp\"\r\n\r\nnamespace mahjong\r\n{\r\n\r\nSyantenCalculator::SyantenCalculator() { initialize(); }\r\n\r\n/**\r\n * @brief 向聴数を計算する。\r\n *\r\n * @param[in] hand 手牌\r\n * @param[in] type 計算対象の向聴数の種類\r\n * @return std::tuple<SyantenType, int> (向聴数の種類, 向聴数)\r\n */\r\nstd::tuple<int, int> SyantenCalculator::calc(const Hand &hand, int type)\r\n{\r\n#ifdef CHECK_ARGUMENT\r\n    if (type < 0 || type > 7) {\r\n        spdlog::warn(\"Invalid type {} passed.\", type);\r\n        return -2;\r\n    }\r\n#endif\r\n\r\n    std::tuple<int, int> ret = {SyantenType::Null, std::numeric_limits<int>::max()};\r\n\r\n    if (type & SyantenType::Normal) {\r\n        int syanten = calc_normal(hand);\r\n        if (syanten < std::get<1>(ret))\r\n            ret = {SyantenType::Normal, syanten};\r\n    }\r\n    if (type & SyantenType::Tiitoi) {\r\n        int syanten = calc_tiitoi(hand);\r\n        if (syanten < std::get<1>(ret))\r\n            ret = {SyantenType::Tiitoi, syanten};\r\n    }\r\n    if (type & SyantenType::Kokusi) {\r\n        int syanten = calc_kokusi(hand);\r\n        if (syanten < std::get<1>(ret))\r\n            ret = {SyantenType::Kokusi, syanten};\r\n    }\r\n\r\n    return ret;\r\n}\r\n\r\n/**\r\n * @brief 初期化する。\r\n *\r\n * @return 初期化に成功した場合は true、そうでない場合は false を返す。\r\n */\r\nbool SyantenCalculator::initialize()\r\n{\r\n    boost::filesystem::path exe_path = boost::dll::this_line_location().parent_path();\r\n\r\n#ifdef USE_UNORDERED_MAP\r\n    if (s_tbl_.empty()) {\r\n        boost::filesystem::path path = exe_path / \"syupai_table.bin\";\r\n        std::ifstream ifs(path.string(), std::ios::binary);\r\n        for (size_t i = 0; i < ShuupaiPatternSize; ++i) {\r\n            unsigned int key;\r\n            Pattern pattern;\r\n            ifs.read((char *)&key, sizeof(unsigned int));\r\n            ifs.read((char *)&pattern, sizeof(Pattern));\r\n\r\n            s_tbl_[key] = pattern;\r\n        }\r\n    }\r\n\r\n    if (z_tbl_.empty()) {\r\n        boost::filesystem::path path = exe_path / \"zihai_table.bin\";\r\n        std::ifstream ifs(path.string(), std::ios::binary);\r\n\r\n        for (size_t i = 0; i < ZihaiPatternSize; ++i) {\r\n            unsigned int key;\r\n            Pattern pattern;\r\n            ifs.read((char *)&key, sizeof(unsigned int));\r\n            ifs.read((char *)&pattern, sizeof(Pattern));\r\n\r\n            z_tbl_[key] = pattern;\r\n        }\r\n    }\r\n#else\r\n    if (s_tbl_.empty()) {\r\n        s_tbl_.resize(ShuupaiTableSize);\r\n\r\n        boost::filesystem::path path = exe_path / \"syupai_table.bin\";\r\n        std::ifstream ifs(path.string(), std::ios::binary);\r\n        for (size_t i = 0; i < ShuupaiPatternSize; ++i) {\r\n            unsigned int key;\r\n            ifs.read((char *)&key, sizeof(unsigned int));\r\n            ifs.read((char *)&s_tbl_[key], sizeof(Pattern));\r\n        }\r\n    }\r\n\r\n    if (z_tbl_.empty()) {\r\n        z_tbl_.resize(ZihaiTableSize);\r\n\r\n        boost::filesystem::path path = exe_path / \"zihai_table.bin\";\r\n        std::ifstream ifs(path.string(), std::ios::binary);\r\n\r\n        for (size_t i = 0; i < ZihaiPatternSize; ++i) {\r\n            unsigned int key;\r\n            ifs.read((char *)&key, sizeof(unsigned int));\r\n            ifs.read((char *)&z_tbl_[key], sizeof(Pattern));\r\n        }\r\n    }\r\n#endif\r\n\r\n    return true;\r\n}\r\n\r\n/**\r\n * @brief 通常手の向聴数を計算する。\r\n *\r\n * @param[in] hand 手牌\r\n * @return int 向聴数\r\n */\r\nint SyantenCalculator::calc_normal(const Hand &hand)\r\n{\r\n    // 制約条件「面子 + 候補 <= 4」で「面子数 * 2 + 候補」の最大値を計算する。\r\n    int n_melds = int(hand.melds.size());\r\n    int n_mentu_base = n_melds + s_tbl_[hand.manzu].n_mentu +\r\n                       s_tbl_[hand.pinzu].n_mentu + s_tbl_[hand.sozu].n_mentu +\r\n                       z_tbl_[hand.zihai].n_mentu;\r\n    int n_kouho_base = s_tbl_[hand.manzu].n_kouho + s_tbl_[hand.pinzu].n_kouho +\r\n                       s_tbl_[hand.sozu].n_kouho + z_tbl_[hand.zihai].n_kouho;\r\n\r\n    // 雀頭なし\r\n    int max = n_mentu_base * 2 + std::min(4 - n_mentu_base, n_kouho_base);\r\n\r\n    if (s_tbl_[hand.manzu].head) {\r\n        // 萬子の雀頭有り\r\n        int n_mentu = n_mentu_base + s_tbl_[hand.manzu].n_mentu_diff;\r\n        int n_kouho = n_kouho_base + s_tbl_[hand.manzu].n_kouho_diff;\r\n        max = std::max(max, n_mentu * 2 + std::min(4 - n_mentu, n_kouho) + 1);\r\n    }\r\n\r\n    if (s_tbl_[hand.pinzu].head) {\r\n        // 筒子の雀頭有り\r\n        int n_mentu = n_mentu_base + s_tbl_[hand.pinzu].n_mentu_diff;\r\n        int n_kouho = n_kouho_base + s_tbl_[hand.pinzu].n_kouho_diff;\r\n        max = std::max(max, n_mentu * 2 + std::min(4 - n_mentu, n_kouho) + 1);\r\n    }\r\n\r\n    if (s_tbl_[hand.sozu].head) {\r\n        // 索子の雀頭有り\r\n        int n_mentu = n_mentu_base + s_tbl_[hand.sozu].n_mentu_diff;\r\n        int n_kouho = n_kouho_base + s_tbl_[hand.sozu].n_kouho_diff;\r\n        max = std::max(max, n_mentu * 2 + std::min(4 - n_mentu, n_kouho) + 1);\r\n    }\r\n\r\n    if (z_tbl_[hand.zihai].head) {\r\n        // 字牌の雀頭有り\r\n        int n_mentu = n_mentu_base + z_tbl_[hand.zihai].n_mentu_diff;\r\n        int n_kouho = n_kouho_base + z_tbl_[hand.zihai].n_kouho_diff;\r\n        max = std::max(max, n_mentu * 2 + std::min(4 - n_mentu, n_kouho) + 1);\r\n    }\r\n\r\n    return 8 - max;\r\n}\r\n\r\n/**\r\n * @brief 七対子手の向聴数を計算する。\r\n *\r\n * @param[in] hand 手牌\r\n * @return int 向聴数\r\n */\r\nint SyantenCalculator::calc_tiitoi(const Hand &hand)\r\n{\r\n    // 牌の種類 (1枚以上の牌) を数える。\r\n    int n_types = s_tbl_[hand.manzu].n_ge1 + s_tbl_[hand.pinzu].n_ge1 +\r\n                  s_tbl_[hand.sozu].n_ge1 + z_tbl_[hand.zihai].n_ge1;\r\n    // 対子の数 (2枚以上の牌) を数える。\r\n    int n_toitu = s_tbl_[hand.manzu].n_ge2 + s_tbl_[hand.pinzu].n_ge2 +\r\n                  s_tbl_[hand.sozu].n_ge2 + z_tbl_[hand.zihai].n_ge2;\r\n\r\n    int syanten = 6 - n_toitu;\r\n    if (n_types < 7)\r\n        syanten += 7 - n_types; // 4枚持ちを考慮\r\n\r\n    return syanten;\r\n}\r\n\r\n/**\r\n * @brief 国士無双の向聴数を計算する。\r\n *\r\n * @param[in] hand 手牌\r\n * @return int 向聴数\r\n */\r\nint SyantenCalculator::calc_kokusi(const Hand &hand)\r\n{\r\n    // 老頭牌を抽出する。\r\n    int manzu19 = hand.manzu & Bit::RotohaiMask;\r\n    int pinzu19 = hand.pinzu & Bit::RotohaiMask;\r\n    int sozu19 = hand.sozu & Bit::RotohaiMask;\r\n\r\n    // 幺九牌の種類 (1枚以上の牌) を数える。\r\n    int n_yaotyuhai = s_tbl_[manzu19].n_ge1 + s_tbl_[pinzu19].n_ge1 +\r\n                      s_tbl_[sozu19].n_ge1 + z_tbl_[hand.zihai].n_ge1;\r\n\r\n    // 幺九牌の対子があるかどうか\r\n    int toitu = ((manzu19 & 0b110'000'000'000'000'000'000'000'110) |\r\n                 (pinzu19 & 0b110'000'000'000'000'000'000'000'110) |\r\n                 (sozu19 & 0b110'000'000'000'000'000'000'000'110) |\r\n                 (hand.zihai & 0b110'110'110'110'110'110'110)) > 0;\r\n\r\n    return 13 - toitu - n_yaotyuhai;\r\n}\r\n\r\n#ifdef USE_UNORDERED_MAP\r\nstd::unordered_map<unsigned int, SyantenCalculator::Pattern> SyantenCalculator::s_tbl_;\r\nstd::unordered_map<unsigned int, SyantenCalculator::Pattern> SyantenCalculator::z_tbl_;\r\n#else\r\nstd::vector<SyantenCalculator::Pattern> SyantenCalculator::s_tbl_;\r\nstd::vector<SyantenCalculator::Pattern> SyantenCalculator::z_tbl_;\r\n#endif\r\n\r\nstatic SyantenCalculator inst;\r\n\r\n} // namespace mahjong\r\n", "meta": {"hexsha": "a8131e40d544c541ac5e57bd11dabb7f18c76c18", "size": 6995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mahjong/syanten.cpp", "max_stars_repo_name": "happapa/mahjong-cpp", "max_stars_repo_head_hexsha": "a392a9a48cd790dbcf4ee31463c3a431c9a614c5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mahjong/syanten.cpp", "max_issues_repo_name": "happapa/mahjong-cpp", "max_issues_repo_head_hexsha": "a392a9a48cd790dbcf4ee31463c3a431c9a614c5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mahjong/syanten.cpp", "max_forks_repo_name": "happapa/mahjong-cpp", "max_forks_repo_head_hexsha": "a392a9a48cd790dbcf4ee31463c3a431c9a614c5", "max_forks_repo_licenses": ["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.8149779736, "max_line_length": 88, "alphanum_fraction": 0.5805575411, "num_tokens": 2368, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.2338969338242831}}
{"text": "#ifndef TVTML_FUNCTIONAL3D_HPP\n#define TVTML_FUNCTIONAL3D_HPP\n\n// Eigen includes\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n\n// video++ includes\n#include <vpp/vpp.hh>\n\n// system includes\n#include <cmath>\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n// own includes \n#include \"enumerators.hpp\"\n#include \"manifold.hpp\"\n#include \"data.hpp\"\n\nnamespace tvmtl{\n\n\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA>\nclass Functional<FIRSTORDER, disc, MANIFOLD, DATA, 3>{\n\n    public:\n\t// Manifold typedefs and constants\n\tstatic const MANIFOLD_TYPE mf_type = MANIFOLD::MyType;\n\tstatic const int value_dim = MANIFOLD::value_dim; \n\tstatic const int manifold_dim = MANIFOLD::manifold_dim; \n\ttypedef typename MANIFOLD::scalar_type scalar_type;\n\ttypedef typename MANIFOLD::value_type value_type;\n\ttypedef typename MANIFOLD::ref_type ref_type;\n\ttypedef typename MANIFOLD::cref_type cref_type;\n\ttypedef typename MANIFOLD::deriv1_type deriv1_type;\n\ttypedef typename MANIFOLD::deriv2_type deriv2_type;\n\ttypedef typename MANIFOLD::restricted_deriv2_type restricted_deriv2_type;\n\ttypedef typename MANIFOLD::tm_base_type tm_base_type;\n\n\t// Data typedef and constants\n\tstatic const int img_dim = DATA::img_dim;\n\ttypedef typename DATA::storage_type img_type;\n\ttypedef typename DATA::weights_type weights_type;\n\ttypedef typename DATA::weights_mat weights_mat;\n\ttypedef typename DATA::inp_mat inp_mat;\n\n\t// Functional parameters and return types\n\tstatic const FUNCTIONAL_DISC disc_type;\n\ttypedef double param_type;\n\ttypedef double result_type;\n\t\n\t// Tangent space transformation matrix types\n\ttypedef vpp::imageNd<tm_base_type, img_dim> tm_base_mat_type; \n\t\n\t// Gradient and Hessian types\n\ttypedef Eigen::Matrix<scalar_type, Eigen::Dynamic, 1> gradient_type;\n\ttypedef vpp::imageNd<deriv2_type, img_dim> hessian_type;\n\ttypedef Eigen::SparseMatrix<scalar_type> sparse_hessian_type;\n\n\t//Constructor\n\tFunctional(param_type lambda, DATA& dat):\n\t    lambda_(lambda),\n\t    data_(dat)\n\t{\n\t    eps2_=1e-10;\n\t   static_assert(img_dim == 3, \"Dimension of data and functional must match!\");\n\t}\n\t\n\tvoid updateWeights();\n\n\tvoid updateTMBase();\n\t\n\t\n\t// Evaluation functions\n\tresult_type evaluateJ();\n\tvoid  evaluateDJ();\n\tvoid  evaluateHJ();\n\t\n\ttemplate <class IMG>\n\tvoid output_img(const IMG& img, const char* filename) const;\n\ttemplate <class IMG>\n\tvoid output_matval_img(const IMG& img, const char* filename) const;\n\n\t// Getter and Setter \n\tinline param_type getlambda() const { return lambda_; }\n\tinline void setlambda(param_type lam) { lambda_=lam; }\n\tinline param_type geteps2() const { return eps2_; }\n\tinline void seteps2(param_type eps) { eps2_=eps; }\n\n\tinline const weights_mat& getweightsX() const { return weightsX_; }\n\tinline const weights_mat& getweightsY() const { return weightsY_; }\n\tinline const weights_mat& getweightsZ() const { return weightsZ_; }\n\n\tinline const gradient_type& getDJ() const { return DJ_; }\n\tinline const sparse_hessian_type& getHJ() const { return HJ_; }\n\tinline const tm_base_mat_type& getT() const { return T_; }\n\n    private:\n\tDATA& data_;\n\n\tparam_type lambda_, eps2_;\n\tweights_mat weightsX_, weightsY_, weightsZ_;\n\n\ttm_base_mat_type T_;\n\tgradient_type DJ_;\n\tsparse_hessian_type HJ_;\n};\n\n\n//--------Implementation FIRSTORDER-----/\n\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\nconst FUNCTIONAL_DISC Functional<FIRSTORDER, disc, MANIFOLD, DATA, 3>::disc_type = disc;\n\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA>\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA, 3>::updateWeights(){\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t Update Weights...\" << std::endl;\n    #endif\n\n    // Neighbourhood box\n    int ns = data_.img_.nslices();  // z\n    int nr = data_.img_.nrows();    // y\n    int nc = data_.img_.ncols();    // x\n    \n    // Subimage boxes\n    vpp::box3d without_last_x(vpp::vint3(0,0,0), vpp::vint3(ns - 1, nr - 1, nc - 2)); // subdomain without last xslice\n    vpp::box3d without_last_y(vpp::vint3(0,0,0), vpp::vint3(ns - 1, nr - 2, nc - 1)); // subdomain without last yslice\n    vpp::box3d without_last_z(vpp::vint3(0,0,0), vpp::vint3(ns - 2, nr - 1, nc - 1)); // subdomain without last zslice\n    vpp::box3d without_first_x(vpp::vint3(0,0,1), vpp::vint3(ns - 1, nr - 1, nc - 1)); // subdomain without first xlice\n    vpp::box3d without_first_y(vpp::vint3(0,1,0), vpp::vint3(ns - 1, nr - 1, nc - 1)); // subdomain without first yslice\n    vpp::box3d without_first_z(vpp::vint3(1,0,0), vpp::vint3(ns - 1, nr - 1, nc - 1)); // subdomain without first zslice\n\n    weightsX_ = weights_mat(data_.img_.domain());\n    weightsY_ = weights_mat(data_.img_.domain());\n    weightsZ_ = weights_mat(data_.img_.domain());\n\n    auto calc_dist = [&] (weights_type& w, const value_type i, const value_type n) {\n\tw = MANIFOLD::dist_squared(i, n);\n    };\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...X neighbours \" << std::endl;\n    #endif\n    \n    // X Neighbours\n    fill3d(weightsX_, 0.0);\n    pixel_wise3d(calc_dist, weightsX_ | without_last_x, data_.img_ | without_last_x, data_.img_ | without_first_x );\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Reweighting\" << std::endl;\n\tstd::cout << \"\\t\\t...Y neighbours\" << std::endl;\n    #endif\n\n    // Y Neighbours\n    fill3d(weightsY_, 0.0);\n    pixel_wise3d(calc_dist, weightsY_ | without_last_y, data_.img_ | without_last_y, data_.img_ | without_first_y );\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Reweighting\" << std::endl;\n\tstd::cout << \"\\t\\t...Z neighbours\" << std::endl;\n    #endif\n\n    // Z Neighbours\n    fill3d(weightsZ_, 0.0);\n    pixel_wise3d(calc_dist, weightsZ_ | without_last_z, data_.img_ | without_last_z, data_.img_ | without_first_z );\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Reweighting\" << std::endl;\n    #endif\n\n    if(disc==ISO){\n\tauto g =  [&] (const weights_type& ew, weights_type& x, weights_type& y, weights_type& z) { x = ew / std::sqrt(x + y + z + eps2_); y = x; z = x; };\n\tpixel_wise3d(g, data_.edge_weights_, weightsX_, weightsY_, weightsZ_);\n    }\n    else{\n\tauto g =  [&] (const weights_type& ew, weights_type& w) { w = ew / std::sqrt(w+eps2_); };\n\tpixel_wise3d(g, data_.edge_weights_, weightsX_);\n\tpixel_wise3d(g, data_.edge_weights_, weightsY_);\n\tpixel_wise3d(g, data_.edge_weights_, weightsZ_);\n    }\n}\n\n// Update the Tangent space ONB\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA, 3 >::updateTMBase(){\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tUpdate tangent space basis...\" << std::endl;\n    #endif\n\n\n   tm_base_mat_type T(data_.img_.domain());\n   pixel_wise3d([&] (tm_base_type& t, const value_type& i) { MANIFOLD::tangent_plane_base(i,t); }, T, data_.img_);\n   T_=T;\n    \n}\n\n\n// Evaluation of J\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\ntypename Functional<FIRSTORDER, disc, MANIFOLD, DATA, 3 >::result_type Functional<FIRSTORDER, disc, MANIFOLD, DATA, 3 >::evaluateJ(){\n\n    // sum d^2(img, img_noise)\n    result_type J1, J2;\n    J1 = J2 = 0.0;\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tFunctional evaluation...\" << std::endl;\n\tstd::cout << \"\\t\\t...Fidelity part\" << std::endl;\n    #endif\n\n\n    if(data_.doInpaint()){\n\tauto f = [&] (const value_type& i, const value_type& n, const bool inp ) { J1 += MANIFOLD::dist_squared(i,n)*(1-inp); };\n\tpixel_wise3d_nothreads(f, data_.img_, data_.noise_img_, data_.inp_);\n    }\n    else{\n\tauto f = [&] (const value_type& i, const value_type& n) { J1 += MANIFOLD::dist_squared(i,n); };\n\tpixel_wise3d_nothreads(f, data_.img_, data_.noise_img_);\n    }\n\n\tupdateWeights();\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...TV part.\" << std::endl;\n    #endif\n\n    if(disc==ISO)\n\tpixel_wise3d_nothreads([&] (const weights_type& w) { J2 += 1.0/w;} ,weightsX_);\n    else\n\tpixel_wise3d_nothreads([&] (const weights_type& wx, const weights_type& wy, const weights_type& wz) { J2 += 1.0 / wx + 1.0 / wy+ 1.0 / wz;}, weightsX_, weightsY_, weightsZ_); \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"J1: \" << J1 << std::endl;\n\tstd::cout << \"J2: \" << J2 << std::endl;\n    #endif\n\n    return 0.5 * J1 + lambda_* J2;\n}\n\n// Evaluation of J'\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA, 3 >::evaluateDJ(){\n    \n    img_type grad = img_type(data_.img_.domain());\n    int ns = data_.img_.nslices();\n    int nr = data_.img_.nrows();\n    int nc = data_.img_.ncols();\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tGradient evaluation...\" << std::endl;\n\tstd::cout << \"\\t\\t...Fidelity part\" << std::endl;\n    #endif\n    //GRADIENT OF FIDELITY TERM\n    if(data_.doInpaint()){\n\tauto f = [] (value_type& g, const value_type& i, const value_type& n, const bool inp ) { MANIFOLD::deriv1x_dist_squared(i,n,g); g*=(1-inp); };\n\tpixel_wise3d(f, grad, data_.img_, data_.noise_img_, data_.inp_);\n    }\n    else{\n\tauto f = [] (value_type& g, const value_type& i, const value_type& n) { MANIFOLD::deriv1x_dist_squared(i,n,g); };\n\tpixel_wise3d(f, grad, data_.img_, data_.noise_img_);\n    }\n    \n    //GRADIENT OF TV TERM\n    \n    // Subimage boxes\n    vpp::box3d without_last_x(vpp::vint3(0,0,0), vpp::vint3(ns - 1, nr - 1, nc - 2)); // subdomain without last xslice\n    vpp::box3d without_last_y(vpp::vint3(0,0,0), vpp::vint3(ns - 1, nr - 2, nc - 1)); // subdomain without last yslice\n    vpp::box3d without_last_z(vpp::vint3(0,0,0), vpp::vint3(ns - 2, nr - 1, nc - 1)); // subdomain without last zslice\n    vpp::box3d without_first_x(vpp::vint3(0,0,1), vpp::vint3(ns - 1, nr - 1, nc - 1)); // subdomain without first xlice\n    vpp::box3d without_first_y(vpp::vint3(0,1,0), vpp::vint3(ns - 1, nr - 1, nc - 1)); // subdomain without first yslice\n    vpp::box3d without_first_z(vpp::vint3(1,0,0), vpp::vint3(ns - 1, nr - 1, nc - 1)); // subdomain without first zslice\n\n    auto calc_first_arg_deriv = [&] (value_type& x, const weights_type& w, const value_type& i, const value_type& n) { MANIFOLD::deriv1x_dist_squared(i, n, x); x *= w; };\n    auto calc_second_arg_deriv = [&] (value_type& y, const weights_type& w, const value_type& i, const value_type& n) { MANIFOLD::deriv1y_dist_squared(i, n, y); y *= w; };\n    auto add_to_gradient = [&] (value_type& g, const value_type& d) { g+=d*lambda_; };\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tGradient evaluation...\" << std::endl;\n\tstd::cout << \"\\t\\t...TV part\" << std::endl;\n\tstd::cout << \"\\t\\t...-> XD1\" << std::endl;\n    #endif\n    // X neighbors and reweighting\n    // ... w.r.t. to first argument\n    { // Temporary image XD1 is deallocated after this scope \n\timg_type XD1 = img_type(without_last_x);\n\tpixel_wise3d(calc_first_arg_deriv, XD1, weightsX_ | without_last_x, data_.img_ | without_last_x, data_.img_ | without_first_x);\n\tpixel_wise3d(add_to_gradient, grad | without_last_x, XD1);\n    }\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...-> XD2\" << std::endl;\n    #endif\n    // ... w.r.t. second argument\n    {\n\timg_type XD2 = img_type(without_last_x);\n\tpixel_wise3d(calc_second_arg_deriv, XD2, weightsX_ | without_last_x, data_.img_ | without_last_x, data_.img_ | without_first_x);\n\tpixel_wise3d(add_to_gradient, grad | without_first_x,  XD2);\n    }\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...-> YD1\" << std::endl;\n    #endif\n    // Vertical derivatives and weighting\n    // ... w.r.t. first argument\n    {\n\timg_type YD1 = img_type(without_last_y);\n\tpixel_wise3d(calc_first_arg_deriv, YD1, weightsY_ | without_last_y, data_.img_ | without_last_y, data_.img_ | without_first_y);\n\tpixel_wise3d(add_to_gradient, grad | without_first_y, YD1);\n    }\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...-> YD2\" << std::endl;\n    #endif\n    // ... w.r.t second argument\n    {\n\timg_type YD2 = img_type(without_last_y);\n\tpixel_wise3d(calc_second_arg_deriv, YD2, weightsY_ | without_last_y, data_.img_ | without_last_y, data_.img_ | without_first_y);\n        pixel_wise3d(add_to_gradient, grad | without_first_y, YD2);\n    }\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...-> ZD1\" << std::endl;\n    #endif\n    // Vertical derivatives and weighting\n    // ... w.r.t. first argument\n    {\n\timg_type ZD1 = img_type(without_last_z);\n\tpixel_wise3d(calc_first_arg_deriv, ZD1, weightsZ_ | without_last_z, data_.img_ | without_last_z, data_.img_ | without_first_z);\n\tpixel_wise3d(add_to_gradient, grad | without_first_z, ZD1);\n    }\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...-> ZD2\" << std::endl;\n    #endif\n    // ... w.r.t second argument\n    {\n\timg_type ZD2 = img_type(without_last_z);\n\tpixel_wise3d(calc_second_arg_deriv, ZD2, weightsZ_ | without_last_z, data_.img_ | without_last_z, data_.img_ | without_first_z);\n        pixel_wise3d(add_to_gradient, grad | without_first_z, ZD2);\n    }\n   \n    #ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(grad,\"3dgrad.csv\");\n    #endif\n \n    DJ_ = gradient_type::Zero(ns*nr*nc*manifold_dim); \n    \n    updateTMBase();\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Local to global insert\" << std::endl;\n    #endif\n    \n   for(int s = 0; s < ns; ++s){\n\t//#pragma omp parallel for\n\tfor(int r = 0; r < nr; ++r){\n\t    // Start of row pointers\n\t    value_type* p = &grad(s, r, 0);\n\t    tm_base_type* t = &T_(s, r, 0);\n\t    for(int c = 0; c < nc; ++c)\n\t\tDJ_.segment(manifold_dim * (nr * nc * s + nc * r + c), manifold_dim) = t[c].transpose() * Eigen::Map<const Eigen::VectorXd>(p[c].data(), p[c].size()); \n\t//\tDJ_.segment(manifold_dim * (s + ns * r + ns * nr * c), manifold_dim) = t[c].transpose() * Eigen::Map<const Eigen::VectorXd>(p[c].data(), p[c].size()); \n\t}\n    } \n\n    #ifdef TV_FUNC_DEBUG \n\tstd::fstream f;\n\tf.open(\"3dDJ.csv\",std::fstream::out);\n\tf << DJ_;\n\tf.close();\n    #endif\n}\n\n// Evaluation of Hessian J\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA, 3 >::evaluateHJ(){\n    hessian_type hessian(data_.img_.domain());\n\n    int ns = data_.img_.nslices();\n    int nr = data_.img_.nrows();\n    int nc = data_.img_.ncols();\n    int sparsedim = ns*nr*nc*manifold_dim;\n    \n        \n    //HESSIAN OF FIDELITY TERM\n     #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tHessian evaluation...\" << std::endl;\n\tstd::cout << \"\\t\\t...Fidelity part\" << std::endl;\n    #endif\n\n    sparse_hessian_type HF(sparsedim,sparsedim);\n\n    //HF.reserve(Eigen::VectorXi::Constant(nc,manifold_dim));\n    typedef Eigen::Triplet<double> Trip;\n    std::vector<Trip> triplist;\n    triplist.reserve(sparsedim*manifold_dim);\n\t\n    if(data_.doInpaint()){\n\tauto f = [] (deriv2_type& h, const value_type& i, const value_type& n, const bool inp ) { MANIFOLD::deriv2xx_dist_squared(i,n,h); h*=(1-inp); };\n\tpixel_wise3d(f, hessian, data_.img_, data_.noise_img_, data_.inp_);\n    }\n    else{\n\tauto f = [] (deriv2_type& h, const value_type& i, const value_type& n) { MANIFOLD::deriv2xx_dist_squared(i,n,h); };\n\tpixel_wise3d(f, hessian, data_.img_, data_.noise_img_);\n    }\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Local to global insert\" << std::endl;\n    #endif\n   for(int s = 0; s < ns; ++s){\n    for(int r = 0; r < nr; ++r){\n\t    // Start of row pointers\n\t    deriv2_type* h = &hessian(s, r, 0);\n\t    tm_base_type* t = &T_(s, r, 0);\n\t    for(int c = 0; c < nc; ++c){\n\t\tint pos = manifold_dim * (nr * nc * s + nc * r + c); // rowwise flattening\n\t\t//int pos = manifold_dim * (s + ns * r + ns * nr * c); // columnwise flattening\n\t\trestricted_deriv2_type ht=t[c].transpose()*h[c]*t[c];\n\t    \n\t\tfor(int local_row = 0; local_row<ht.rows(); local_row++)\n\t\t    for(int local_col = local_row; local_col < ht.cols(); local_col++){\n\t\t\tscalar_type e = ht(local_row, local_col);\n\t\t\t    if(e!=0){\n\t\t\t\tint global_row = pos + local_row;\n\t\t\t\tint global_col = pos + local_col;\n\t\t\t\ttriplist.push_back(Trip(global_row,global_col,e));\n\t\t\t\tif(global_row != global_col)\n\t\t\t\t    triplist.push_back(Trip(global_col,global_row,e));\n\t\t\t    }\n\t\t    }\n\t    \n\t    }\n\t}\n    } \n\t\n     #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Triplet list created\" << std::endl;\n    #endif\n    HF.setFromTriplets(triplist.begin(),triplist.end());              \n    HF.makeCompressed();\n\n    //HESSIAN OF TV TERM\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\tHessian evaluation...\" << std::endl;\n\tstd::cout << \"\\t\\t...TV part\" << std::endl;\n    #endif\n\n    sparse_hessian_type HTV(sparsedim,sparsedim);\n    \n    //HTV.reserve(Eigen::VectorXi::Constant(nc,5*manifold_dim));\n    triplist.clear();\n    triplist.reserve(7 * sparsedim*manifold_dim);\n\n    // Subimage boxes\n    vpp::box3d without_last_x(vpp::vint3(0,0,0), vpp::vint3(ns - 1, nr - 1, nc - 2)); // subdomain without last xslice\n    vpp::box3d without_last_y(vpp::vint3(0,0,0), vpp::vint3(ns - 1, nr - 2, nc - 1)); // subdomain without last yslice\n    vpp::box3d without_last_z(vpp::vint3(0,0,0), vpp::vint3(ns - 2, nr - 1, nc - 1)); // subdomain without last zslice\n    vpp::box3d without_first_x(vpp::vint3(0,0,1), vpp::vint3(ns - 1, nr - 1, nc - 1)); // subdomain without first xlice\n    vpp::box3d without_first_y(vpp::vint3(0,1,0), vpp::vint3(ns - 1, nr - 1, nc - 1)); // subdomain without first yslice\n    vpp::box3d without_first_z(vpp::vint3(1,0,0), vpp::vint3(ns - 1, nr - 1, nc - 1)); // subdomain without first zslice\n\n\n    auto calc_xx_der = [&] (deriv2_type& x, const weights_type& w, const value_type& i, const value_type& n) { MANIFOLD::deriv2xx_dist_squared(i, n, x); x*=w; };\n    auto calc_xy_der = [&] (deriv2_type& xy, const weights_type& w, const value_type& i, const value_type& n) { MANIFOLD::deriv2xy_dist_squared(i, n, xy); xy*=w; };\n    auto calc_yy_der = [&] (deriv2_type& y, const weights_type& w, const value_type& i, const value_type& n) { MANIFOLD::deriv2yy_dist_squared(i, n, y); y*=w; };\n    auto add_to_hessian =  [&] (deriv2_type& h, const deriv2_type& d) { h += d; };\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->XD11\" << std::endl;\n    #endif\n    \n    // Horizontal Second Derivatives and weighting\n    // ... w.r.t. first arguments\n    { // Temporary image XD11 is deallocated after this scope\n\thessian_type XD11(without_last_x);\n        pixel_wise3d(calc_xx_der, XD11, weightsX_ | without_last_x, data_.img_ | without_last_x, data_.img_ | without_first_x);\n\tpixel_wise3d([&] (deriv2_type& h, const deriv2_type& d) { h=d; }, hessian | without_last_x, XD11);\n\t#ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(XD11,\"3dXD11.csv\");\n\t#endif\n    }\n    \n    for(int s=0; s < ns; ++s)\n\tfor(int r=0; r<nr; ++r)\n\t    hessian(s,r,nc-1)=deriv2_type::Zero();\n\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->XD22\" << std::endl;\n    #endif\n    //... w.r.t. second arguments\n    {\n\thessian_type XD22(without_last_x);\n        pixel_wise3d(calc_yy_der, XD22, weightsX_ | without_last_x, data_.img_ | without_last_x, data_.img_ | without_first_x);\n\tpixel_wise3d(add_to_hessian, hessian | without_first_x, XD22);\n\t#ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(XD22,\"3dXD22.csv\");\n\t#endif\n    }\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->YD11\" << std::endl;\n    #endif\n    // Vertical Second Derivatives weighting\n    //... w.r.t. first arguments\n    {\n\thessian_type YD11(without_last_y);\n        pixel_wise3d(calc_xx_der, YD11, weightsY_ | without_last_y, data_.img_ | without_last_y, data_.img_ | without_first_y);\n\tpixel_wise3d(add_to_hessian, hessian | without_last_y, YD11);\n\t#ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(YD11,\"3dYD11.csv\");\n\t#endif\n    }\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->YD22\" << std::endl;\n    #endif\n    //... w.r.t. second arguments\n    {\n\thessian_type YD22(without_last_y);\n        pixel_wise3d(calc_yy_der, YD22, weightsY_ | without_last_y, data_.img_ | without_last_y, data_.img_ | without_first_y); \n\tpixel_wise3d(add_to_hessian, hessian | without_first_y, YD22);\n\t#ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(YD22,\"3dYD22.csv\");\n\t#endif\n    }\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->ZD11\" << std::endl;\n    #endif\n    // Vertical Second Derivatives weighting\n    //... w.r.t. first arguments\n    {\n\thessian_type ZD11(without_last_z);\n        pixel_wise3d(calc_xx_der, ZD11, weightsZ_ | without_last_z, data_.img_ | without_last_z, data_.img_ | without_first_z);\n\tpixel_wise3d(add_to_hessian, hessian | without_last_z, ZD11);\n\t#ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(ZD11,\"3dZD11.csv\");\n\t#endif\n    }\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->ZD22\" << std::endl;\n    #endif\n    //... w.r.t. second arguments\n    {\n\thessian_type ZD22(without_last_z);\n        pixel_wise3d(calc_yy_der, ZD22, weightsZ_ | without_last_z, data_.img_ | without_last_z, data_.img_ | without_first_z); \n\tpixel_wise3d(add_to_hessian, hessian | without_first_z, ZD22);\n\t#ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(ZD22,\"3dZD22.csv\");\n\t#endif\n    } \n    \t#ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(hessian,\"3dhessian.csv\");\n\t#endif\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...Local to global insert\" << std::endl;\n    #endif\n    // Insert elementwise into sparse Hessian\n    // NOTE: Eventually make single version for both cases, including an offset\n    // --> additional parameters sparse_mat, offset\n    auto HTV_insert = [&]( hessian_type H, tm_base_mat_type T1, tm_base_mat_type T2, int row_offset, int col_offset){\n\tint Hns = H.nslices();\n\tint Hnr = H.nrows();\n\tint Hnc = H.ncols();\n    \n\tfor(int s = 0; s < Hns; ++s){\n\t    for(int r = 0; r < Hnr; ++r){\n\t\t// Start of row pointers\n\t\tderiv2_type* h = &H(s, r, 0);\n\t\ttm_base_type* t1 = &T1(s, r, 0);\n\t\ttm_base_type* t2 = &T2(s, r, 0);\n\t\tfor(int c = 0; c < Hnc; ++c){\n\t\t    int pos = manifold_dim * (nr * nc * s + nc * r +c); // rowwise flattening\n\t\t   // int pos = manifold_dim * (s + ns * r + ns * nr * c); // columnwise flattening\n\t\t    restricted_deriv2_type ht = t1[c].transpose()*h[c]*t2[c];\n\t\t\n\t\t    for(int local_row = 0; local_row<ht.rows(); local_row++)\n\t\t\tfor(int local_col = 0; local_col < ht.cols(); local_col++){\n\t\t\t    scalar_type e = ht(local_row, local_col);\n\t\t\t\tif(e!=0){\n\t\t\t\t    int global_row = pos + row_offset + local_row;\n\t\t\t\t    int global_col = pos + col_offset + local_col;\n\t\t\t\t    triplist.push_back(Trip(global_row,global_col,e));\n\t\t\t\t    if(row_offset > 0 || col_offset > 0)\n\t\t\t\t\ttriplist.push_back(Trip(global_col,global_row,e));\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\t}\n\t    }\n\t}\n    };\n\n    auto HTV_single_insert = [&] (deriv2_type& h, tm_base_type& t1, tm_base_type& t2, int pos, int row_offset, int col_offset){\n   \t\t    restricted_deriv2_type ht = t1.transpose()*h*t2;\n\t\t    for(int local_row = 0; local_row<ht.rows(); local_row++)\n\t\t\tfor(int local_col = 0; local_col < ht.cols(); local_col++){\n\t\t\t    scalar_type e = ht(local_row, local_col);\n\t\t\t\tif(e!=0){\n\t\t\t\t    int global_row = pos + row_offset + local_row;\n\t\t\t\t    int global_col = pos + col_offset + local_col;\n\t\t\t\t    triplist.push_back(Trip(global_row,global_col,e));\n\t\t\t\t    if(row_offset > 0 || col_offset > 0)\n\t\t\t\t\ttriplist.push_back(Trip(global_col,global_row,e));\n\t\t\t\t}\n\t\t\t}\n    };\n\n    HTV_insert(hessian, T_, T_, 0, 0);\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->ZD12\" << std::endl;\n    #endif              \n    // Z Neighbors Second Derivatives and weighting\n    // ... w.r.t. first and second arguments \n    {\n\thessian_type ZD12(without_last_z);\n\tpixel_wise3d(calc_xy_der, ZD12, weightsZ_ | without_last_z, data_.img_ | without_last_z, data_.img_ | without_first_z );\n\t#ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(ZD12,\"3dZD12.csv\");\n\t#endif\n\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Local to global insert:\" << std::endl;\n\t#endif\n\t// Offsets for upper nx*ny-th subdiagonal\n\tint offset =  manifold_dim * nr * nc;\n\tHTV_insert(ZD12, T_ | without_last_z, T_ | without_first_z, 0, offset);\n    }\n    \n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->YD12\" << std::endl;\n    #endif\n    // Y Neighbors Second Derivatives and weighting\n    //... w.r.t. second arguments\n    {\n\thessian_type YD12(data_.img_.domain());\n\tpixel_wise3d(calc_xy_der, YD12 | without_last_y, weightsY_ | without_last_y, data_.img_ | without_last_y, data_.img_ | without_first_y );\n\t\n\t//Set last y-slice to zero\n\t#pragma omp parallel for\n\tfor(int s = 0; s < ns ; ++s){\n\t    deriv2_type* row = &YD12(s, nr-1 ,0);\n\t    for(int c = 0; c < nc; ++c)\n\t\trow[c] = deriv2_type::Zero();\n\t}\n\t#ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(YD12,\"3dYD12.csv\");\n\t#endif\n\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Local to global insert:\" << std::endl;\n\t#endif\n\t// Offsets for first nxth subdiagonal\n\tint offset =  manifold_dim * nc;\n\n\t// Insert YD12 except last ns entries\n\tauto t1_it = T_.begin();\n\tauto t2_it = typename tm_base_mat_type::iterator(vpp::vint3(0,1,0), T_); // Iterator at beginning of second row \n\tbool do_break = false;\n\tint k = 0;\n\tint max_entry = ns * nr * nc - nc;\n\n\tfor(int s=0; s < ns; ++s){\n\t    for(int r=0; r < nr; ++r){\n\t\t deriv2_type* row = &YD12(s, r, 0);\n\t\t for(int c=0; c < nc; ++c){\n\t\t    int pos = manifold_dim * (nr * nc * s + nc * r +c); // rowwise flattening\n\t//\t    int pos = manifold_dim * (s + ns * r + ns * nr * c); // columnwise flattening\n\t\t    HTV_single_insert(row[c], *t1_it, *t2_it, pos, 0, offset);\n\t\t    t1_it.next();\n\t\t    t2_it.next();\n\t\t    #ifdef TV_FUNC_DEBUG_VERBOSE2\n\t\t\tstd::cout << \"\\n\\t\\t\\tPosition: (\" << s << \",\"<< c << \",\" << r << \")\" << std::endl;\n\t\t\tstd::cout << \"\\t\\t\\tValue(YD12): \" << row[c] << std::endl;\n\t\t\tstd::cout << \"\\t\\t\\tEntry number: \" << k << std::endl;\n\t\t\tstd::cout << \"\\t\\t\\tPos: \" << pos << std::endl;\n\t\t    #endif\n\t\t    ++k;\n\t\t    if(k >= max_entry) {do_break = true; break;}\n\t\t }\n\t\t if(do_break) break;\n\t    }\n\t    if(do_break) break;\n\t}\n\n\n    }\n\n    #ifdef TV_FUNC_DEBUG_VERBOSE\n\tstd::cout << \"\\t\\t...->XD12\" << std::endl;\n    #endif\n    // Z neightbors Second Derivatives and weighting\n    //... w.r.t. second arguments\n    {\n\thessian_type XD12(data_.img_.domain());\n\tpixel_wise3d(calc_xy_der, XD12 | without_last_x, weightsX_ | without_last_x, data_.img_ | without_last_x, data_.img_ | without_first_x);\n\t\n\t//Set last slice to zero, - actually not necessary but safer than keeping uninitialized data\n\t#pragma omp parallel for\n\tfor(int s = 0; s < ns; ++s){\n\t    for(int r = 0; r < nr; ++r)\n\t\tXD12(s, r, nc-1) = deriv2_type::Zero();\n\t}\n\t\n\t#ifdef TV_FUNC_DEBUG\n\t    data_.output_matval_img(XD12,\"3dXD12.csv\");\n\t#endif\n\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Local to global insert:\" << std::endl;\n\t#endif\n\t\n\t// Insert into first upper subdiagonal\n\tauto t1_it = T_.begin();\n\tauto t2_it = T_.begin(); t2_it.next();\n\tfor(int s=0; s < ns; ++s){ \n\t    for(int r=0; r < nr; ++r){\n\t\t deriv2_type* row = &XD12(s, r, 0);\n\t\t for(int c=0; c < nc; ++c){\n\t\t    int pos = manifold_dim * (nr * nc * s + nc * r +c); // rowwise flattening\n\t\t    //int pos = manifold_dim * (s + ns * r + ns * nr * c); // columnwise flattening\n\t\t    HTV_single_insert(row[c], *t1_it, *t2_it, pos, 0, manifold_dim);\n\t\t    t1_it.next();\n\t\t    t2_it.next();\n\t\t    if(s==ns-1 && r == nc-1 && c >= nc-2 ) break;\n\t\t }\n\t    }\n\t}\n\n\tHTV.setFromTriplets(triplist.begin(),triplist.end());              \n\tHTV.makeCompressed();\n\ttriplist.clear();\n    }   \t\n\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Combine Fidelity and TV parts:\" << std::endl;\n\t#endif \n\t\n\tHJ_= HF + lambda_*HTV;\n\t\n\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Output Hessian (stats):\" << std::endl;\n\t#endif\n    #ifdef TV_FUNC_DEBUG\n\tif (sparsedim<200){\n\t    if(sparsedim<80){\n\t\tstd::cout << \"\\nFidelity\\n\" << HF << std::endl; \n\t\tstd::cout << \"\\nTV\\n\" << HTV << std::endl; \n\t\tstd::cout << \"\\nHessian\\n\" << HJ_ << std::endl; \n\t    }\n\n\t    std::fstream f;\n\t    f.open(\"H.csv\",std::fstream::out);\n\t    Eigen::IOFormat CommaInitFmt(Eigen::StreamPrecision, Eigen::DontAlignCols, \", \", \", \", \"\", \"\", \"\", \"\");\n\t    //Eigen::MatrixXd M(HJ_);\n\t    //f << M.format(CommaInitFmt);\n\t    f << HJ_;\n\t    f.close();\n\n\t}\n\telse{\n\t    std::cout << \"\\nFidelity Non-Zeros: \" << HJ_.nonZeros() << std::endl; \n\t    std::cout << \"\\nTV Non-Zeros: \" << HJ_.nonZeros() << std::endl; \n\t    std::cout << \"\\nHessian Non-Zeros: \" << HJ_.nonZeros() << std::endl; \n\t}\n    // Test Solver:\n\t#ifdef TV_FUNC_DEBUG_VERBOSE\n\t\tstd::cout << \"\\t\\t...Test Solve\" << std::endl;\n\t#endif\n\tgradient_type x;\n    \n\tEigen::SparseLU<sparse_hessian_type> solver;\n\tsolver.analyzePattern(HJ_);\n\tsolver.factorize(HJ_);\n\tx = solver.solve(DJ_);\n\n\tstd::fstream f;\n\tf.open(\"Sol.csv\",std::fstream::out);\n\tf << x;\n\tf.close();\n    #endif\n}\n\n\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\ntemplate < class IMG >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA, 3 >::output_img(const IMG& img, const char* filename) const{\n    //TODO\n}\n\ntemplate <enum FUNCTIONAL_DISC disc, typename MANIFOLD, class DATA >\ntemplate < class IMG >\nvoid Functional<FIRSTORDER, disc, MANIFOLD, DATA, 3 >::output_matval_img(const IMG& img, const char* filename) const{\n    //TODO\n}\n\n}// end namespace tvtml\n\n#endif\n", "meta": {"hexsha": "37405d7e157780059a0ad4ba073840b30fc879ba", "size": 28960, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mtvmtl/core/functional3d.hpp", "max_stars_repo_name": "pdebus/MTVMTL", "max_stars_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T12:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T05:11:01.000Z", "max_issues_repo_path": "mtvmtl/core/functional3d.hpp", "max_issues_repo_name": "pdebus/MTVMTL", "max_issues_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mtvmtl/core/functional3d.hpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2453066333, "max_line_length": 176, "alphanum_fraction": 0.6558701657, "num_tokens": 9162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.23367838217850737}}
{"text": "/**********************************************************************************\n *  The MIT License (MIT)                                                        *\n *                                                                                *\n *  Copyright (c) 2014 Carnegie Mellon University                                 *\n *                                                                                *\n *  Permission is hereby granted, free of charge, to any person obtaining a copy  *\n *  of this software and associated documentation files (the \"Software\"), to deal *\n *  in the Software without restriction, including without limitation the rights  *\n *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell     *\n *  copies of the Software, and to permit persons to whom the Software is         *\n *  furnished to do so, subject to the following conditions:                      *\n *                                                                                *\n *  The above copyright notice and this permission notice shall be included in    *\n *  all copies or substantial portions of the Software.                           *\n *                                                                                *\n *  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR    *\n *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,      *\n *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE   *\n *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER        *\n *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *\n *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN     *\n *  THE SOFTWARE.                                                                 *\n **********************************************************************************/\n/**\n * @file   cpdr.cpp\n * @brief  A pedestrian dead-reckoning system.  Integrates gyros and step counting\n * @author M. George\n */\n\n#include <cmath>\n#include <iostream>\n\n#include <Eigen/Dense>\n\n#include \"cpdr.h\"\n\nusing namespace BASIL;\n\n/**************************************************************************//**\n* cPDR Constructor.  Constant vectors and matrices (gravity,\n* earth rate) are formed here.  PDR state is set to ALIGN initially.  PDR\n* cannot be used until an alignment method is called.\n* \\arg \\c params.  Boost::property_tree object and id of attached IMU.\n******************************************************************************/\ncPDR::cPDR(boost::property_tree::ptree config, unsigned int imuid) : mStepDetector(config)\n{\n    mImuId = imuid;\n    \n    mMessageCounter = 0;\n    \n    // Clear all the member vectors and matrices.\n    mEarthRate           = CartesianVector::Zero();\n    mGravity             = CartesianVector::Zero();\n    mAlpha               = CartesianVector::Zero();\n    mDeltaP              = CartesianVector::Zero();\n    mDeltaV              = CartesianVector::Zero();\n    mGravityReaction     = CartesianVector::Zero();\n\n    mIdentity = CartesianMatrix::Identity();\n    mA        = CartesianMatrix::Zero();\n    \n    mAlphaSkew     = SkewMatrix::Zero(); \n    mAlphaMagnitude = 0.0;\n\n    mf1 = mf2 = mf3 = mf4 = 0.0;\n\n    mCbn = RotationMatrix::Identity();\n\n    mdt = 0;\n\n    // INS initially stopped, time = 0, no messages and ready to calibrate.\n    mTime = 0.0;\n    mPreviousTime = 0.0;\n    mPreviousEarthRateTime = 0.0;\n    mAlignmentTime = config.get<double>(\"parameters.ins.alignmentperiod\");\n    mIMUCount = 0;\n    mIMURate = config.get<unsigned int>(\"parameters.hardware.imus.xsensmti.rate\");\n    mEarthUpdateRate = config.get<unsigned int>(\"parameters.ins.earthupdaterate\");\n    \n    if (mEarthUpdateRate < 0)\n    {\n        std::cerr << \"Earth update rate must be >= 0\" << std::endl;\n        mApplyEarthRateCorrections = false;\n        mEarthSubsample = 0;\n    }\n    else if (mEarthUpdateRate == 0)\n    {\n        mApplyEarthRateCorrections = false;\n        mEarthSubsample = 0;\n    }\n    else\n    {\n        mApplyEarthRateCorrections = true;\n        mEarthSubsample = mIMURate / mEarthUpdateRate;\n    }\n    \n    // Get initial conditions\n    mInitialHeading = config.get<double>(\"parameters.ins.initialheading\")*BASIL::CONSTANTS::DEG_TO_RAD;\n    mInitialLatitude = config.get<double>(\"parameters.ins.approximatelatitude\")*BASIL::CONSTANTS::DEG_TO_RAD;\n    \n    // Step data\n    mStepLength = config.get<double>(\"parameters.pdr.steplength\");\n    mStepIncrement = CartesianVector::Zero();\n    \n    // Clear initial INS data structure\n    mInsData.Velocity    = CartesianVector::Zero();\n    mInsData.Position    = Array::Zero();\n    mInsData.Orientation = AngleArray::Zero();\n    mInsData.InsMdl = BASIL::INS::GENERIC_INS;\n    mInsData.Id = imuid;\n\n    // Clear IMU calibration data structure\n    mImuCalibrationData.AccelerationBias = CartesianVector::Zero();\n    mImuCalibrationData.AccelerationScaleFactor = CartesianVector::Zero();\n    mImuCalibrationData.AngularRateBias << 0.00414044772524217,0.00189662656009109,0.00726575764268722;\n    mImuCalibrationData.AngularRateGBias = CartesianVector::Zero();\n    mImuCalibrationData.AngularRateScaleFactor = CartesianVector::Zero();\n    mImuCalibrationData.ImuMdl = BASIL::IMUS::GENERIC_IMU;\n    mImuCalibrationData.Id = imuid;\n    \n    mCurrentState = ALIGNING;\n}\n\n/**************************************************************************//**\n* cPDR Destructor\n******************************************************************************/\ncPDR::~cPDR()\n{\n}\n\n/**************************************************************************//**\n* Integrates the attitude forward using Savage type exact \n* integration. Ref: Savage, P.  Strapdown Analytics, 2nd Ed.  Chapters 7, 19 \n* Steps are detected and position is dead-reckoned using heading data and\n* average step length.\n* \\arg \\c omega.  Vector of x,y,z gyro rate readings in rad/s\n* \\arg \\c accel.  Vector of x,y,z accelerometer readings in m/s/s\n* \\arg \\c time.   Time stamp of IMU readings\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::integratePVA(const cImuData& imudata)\n{\n    if (mCurrentState < cPDR::RUNNING)\n    {\n        std::cerr << \"Error (cPDR): INS must be aligned before integrating.\" << std::endl;\n\t    return;\n    }    \n\n    // For the first message we receive predict using nominal IMU rate\n    if (mMessageCounter == 0)\n    {\n        mdt = 1.0/double(mIMURate);\n    }\n    else\n    {\n        mdt = imudata.Time.getSeconds() - mPreviousTime;\n    }\n    \n    // Catch an out of order packet here\n    if (mdt < 0)\n    {\n        //Some kind of standard error here\n        std::cerr << \"Error (cPDR): dt is negative in integratePVA()\" << std::endl;\n        return;\n    }\n\n    if (mdt > 2.0/double(mIMURate))\n    {\n        // Some kind of standard error here\n        std::cerr << \"Warning (cPDR): dt (\" << mdt << \"s) is large in integratePVA()\" << std::endl;\n        // Reset the counters so this doesn't persist.\n        mInsData.Time = imudata.Time;\n        mPreviousTime = imudata.Time.getSeconds();\n    \tmMessageCounter++;\n        //  Returning here is equivalent to assuming no motion during period of missing data.\n        return;\n    }\n\n    // Get rotation vector\n    mAlpha = imudata.AngularRate*mdt;\n    mAlphaMagnitude = mAlpha.norm();\n    \n    // Catch zero rotation vector magnitudes which happen with stationary sensors and quantization\n    if (mAlphaMagnitude > 0.0)\n    {   \n        // Skew symmetric matrix from rotation vector\n        BASIL::MATH::skew(mAlpha, mAlphaSkew);\n        \n        // Integration constants\n        mf1 = std::sin(mAlphaMagnitude)/mAlphaMagnitude;\n        mf2 = (1.0 - std::cos(mAlphaMagnitude))/(mAlphaMagnitude*mAlphaMagnitude);\n        mf3 = (1.0/(mAlphaMagnitude*mAlphaMagnitude))*(1.0-mf1);\n        mf4 = (1.0/(mAlphaMagnitude*mAlphaMagnitude))*(0.5-mf2);\n\t\n\t    // Position update\n\t    if (mStepDetector.detect(imudata.Acceleration(BASIL::IMUZ)))\n\t    {\n\t        mStepIncrement(BASIL::NORTH) = mStepLength * std::cos(mInsData.Orientation(BASIL::YAW));\n\t        mStepIncrement(BASIL::EAST) = mStepLength * std::sin(mInsData.Orientation(BASIL::YAW));\n\t        mStepIncrement(BASIL::DOWN) = 0.0;\n            mInsData.Position.noalias() += mStepIncrement;\n            //std::cout << mMessageCounter << std::endl;\n        }\n        \n        // Orientation update\n        mA.noalias() = mIdentity + mf1*mAlphaSkew + mf2*mAlphaSkew*mAlphaSkew;\n        mCbn *= mA;\n        cbn2euler(mCbn,mInsData.Orientation);\n    }\n    else\n    {\n        // Position update\n\t    if (mStepDetector.detect(imudata.Acceleration(BASIL::IMUZ)))\n\t    {\n\t        mStepIncrement(BASIL::NORTH) = mStepLength * std::cos(mInsData.Orientation(BASIL::YAW));\n\t        mStepIncrement(BASIL::EAST) = mStepLength * std::sin(mInsData.Orientation(BASIL::YAW));\n\t        mStepIncrement(BASIL::DOWN) = 0.0;\n            mInsData.Position.noalias() += mStepIncrement;\n            //std::cout << mMessageCounter << std::endl;\n        }\n    }\n\n    // Apply an earth rate correction at a lower frequency\n    if ( mApplyEarthRateCorrections && (mMessageCounter % mEarthSubsample == 0) )\n    {\n        cPDR::earthRateCorrection(imudata.Time.getSeconds());\n    }\n\n    // Times are set here so that a user can bypass position and velocity integration\n    // if desired, effectively using this class as a AHRS system with gyros only.\n    mInsData.Time = imudata.Time;\n    mPreviousTime = imudata.Time.getSeconds();\n\n    mMessageCounter++;\n}\n\n/**************************************************************************//**\n* Called at sub-intervals of the integreatePVA() function.  Adds correction \n* to current attitude to account for Earth rotation effects.  Position and velocity\n* corrections are taken into account in integratePVA() and as a natural consequence\n* of this update.  Not used if no latitude input is used in alignment call.\n* \\arg \\c void\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::earthRateCorrection(const double time)\n{   \n    // First time in we use nominal earth correction rate for the dt.\n    if (mPreviousEarthRateTime == 0.0)\n    {\n        mdt = 1.0 / (double)mEarthSubsample;\n    }\n    else\n    {\n        mdt = time - mPreviousEarthRateTime;\n    }\n\n    // Catch negative time increments\n    if (mdt < 0)\n    {\n        //Some kind of standard error here\n        std::cerr << \"Error (cPDR): dt is negative in earthRateCorrection()\" << std::endl;\n        return;\n    }\n\n    mAlpha = -1.0*mdt*mEarthRate;\n    mAlphaMagnitude = mAlpha.norm();\n    mf1 = std::sin(mAlphaMagnitude)/mAlphaMagnitude;\n    mf2 = (1.0 - std::cos(mAlphaMagnitude))/(mAlphaMagnitude*mAlphaMagnitude);\n    BASIL::MATH::skew(mAlpha, mAlphaSkew);\n    \n    mA.noalias() = mIdentity + mf1*mAlphaSkew + mf2*mAlphaSkew*mAlphaSkew;\n    mCbn = mA*mCbn;\n    cbn2euler(mCbn,mInsData.Orientation);\n    \n    mPreviousEarthRateTime = time;\n}\n\n/**************************************************************************//**\n* Local initial alignment with velocity and position in local navigation coordinates.  \n* Roll and pitch angles are coarsely aligned from an input average acceleration vector \n* (2-3s recommended) with gravity.  Initial heading (North), velocity and position (Local) \n* are user inputs.  User must also input an approximate latitude.  The global heading and \n* approximate latitude allow reasonable gravity models and earth rate corrections to be fixed.\n*\\arg \\c Pointer to 3x1 array of time averaged x,y,z accelerometer signals.  \n* \t\t Suggested averaging time 2-3s.  IMU must be stationary during this time!\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::localAlign(const CartesianVector& gravityReactionForce,  const double heading, const CartesianVector& initialUTMPosition, \n                      const CartesianVector& initialUTMVelocity, const double approximateLatitude)\n{\n    gravityAlignRollPitch(gravityReactionForce, mInsData.Orientation);\n    mInsData.Orientation(BASIL::YAW) = heading;\n\n    cPDR::euler2cbn(mInsData.Orientation,mCbn);\n\n    mInsData.Velocity = initialUTMVelocity;\n    mInsData.Position = initialUTMPosition;\n\n    // Earth rate:\n    getEarthRate(approximateLatitude, mEarthRate);\n    \n    // Gravity\n    mGravity(BASIL::DOWN) = getGravityMagnitude(approximateLatitude);\n\n    mMode = cPDR::LOCAL;\n    // Earth rate corrections will be applied unless already turned off in constructor\n    mApplyEarthRateCorrections = mApplyEarthRateCorrections && true;\n    \n    // Zero counters in case we need to re-align at some point\n    mMessageCounter = 0;\n    mdt = 0;\n    mInsData.Time.setTime(TIME::FREE_RUNNING,0,0.0);\n    mPreviousTime = 0.0;\n    mPreviousEarthRateTime = 0.0;\n\n    // We are now running and ready to call integrate*() functions\n    mCurrentState = cPDR::RUNNING;\n}\n\n/**************************************************************************//**\n* Local initial alignment with of roll and pitch angles only.  \n* Roll and pitch angles are coarsely aligned from an input average acceleration vector \n* (2-3s recommended) with gravity.  Initial heading, velocity and position are all set to 0. \n* User must also input an approximate latitude to allow a coarse estimate of gravity.\n*\\arg \\c Pointer to 3x1 array of time averaged x,y,z accelerometer signals.  \n* \t\t Suggested averaging time 2-3s.  IMU must be stationary during this time!\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::localAlign(const CartesianVector& gravityReactionForce, const double approximateLatitude)\n{\n    gravityAlignRollPitch(gravityReactionForce, mInsData.Orientation);\n    \n    euler2cbn(mInsData.Orientation,mCbn);\n    \n    // Earth rate:\n    getEarthRate(approximateLatitude, mEarthRate);\n    \n    // Gravity\n    mGravity(BASIL::DOWN) = getGravityMagnitude(approximateLatitude);\n    \n    mMode = cPDR::LOCAL;\n    // Earth rate corrections will be applied unless already turned off in constructor\n    mApplyEarthRateCorrections = mApplyEarthRateCorrections && true;\n    \n    // Zero counters in case we need to re-align at some point\n    mMessageCounter = 0;\n    mdt = 0;\n    mInsData.Time.setTime(TIME::FREE_RUNNING,0,0.0);\n    mPreviousTime = 0.0;\n    mPreviousEarthRateTime = 0.0;\n    \n    // We are now running and ready to call integrate*() functions\n    mCurrentState = cPDR::RUNNING;\n}\n\n/**************************************************************************//**\n* Get the magnitude of gravity at our current latitude using a Defense Mapping \n* Agency model.  Reference:  Jay A. Farrell.  Aided Inertial Navigation, p.33.\n* \\arg \\c latitude.  Reference to latitude data (radians)\n* \\arg \\c gravity.  Reference to gravity output.\n* \\return \\c void\n******************************************************************************/\ndouble cPDR::getGravityMagnitude(const double latitude)\n{\n    double gravity = BASIL::WGS84::EQUATORIAL_GRAVITY * \n                    ( (          1.0 + 0.0019318513530*std::sin(latitude)*std::sin(latitude)) / \n                      (std::sqrt(1.0 - 0.0066943800229*std::sin(latitude)*std::sin(latitude))) );\n    return gravity;\n}\n\n/**************************************************************************//**\n* Correct the current position, velocity and orientation with errors.\n* \\arg \\c position.  Position.\n* \\arg \\c velocity.  Velocity.\n* \\arg \\c eulers.  Euler angles.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::correctPVA(const CartesianVector& positionerror, \n                      const CartesianVector& velocityerror, \n                      const AngleArray& skewangles)\n{\n    mInsData.Velocity -= velocityerror;\n    mInsData.Position -= positionerror;\n    \n    BASIL::MATH::skew(skewangles, mAlphaSkew); \n    mA = mIdentity - mAlphaSkew;\n    mCbn = mA.inverse() * mCbn;\n    \n    cbn2euler(mCbn, mInsData.Orientation);\n}\n\n/**************************************************************************//**\n* Get the components of earth rate at our current latitude.\n* \\arg \\c latitude.  Reference to latitude data (radians)\n* \\arg \\c gravity.  Pointer to earthRate vector for output.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::getEarthRate(const double latitude, CartesianVector& earthRate)\n{\n    earthRate(NORTH) = BASIL::WGS84::EARTH_RATE * std::cos(latitude);\n    earthRate(EAST) = 0;\n    earthRate(DOWN) = -1.0 * BASIL::WGS84::EARTH_RATE*std::sin(latitude);\n}\n\n/**************************************************************************//**\n* Get roll and pitch angles from a gravity vector.  Input vector should be averaged\n* over a period of 2-3 seconds with a stationary IMU.  Aligns IMU x,y coordinates\n* to Down gravity vector.  1 mg of accelerometer bias -> 1 mrad of roll, pitch error.\n* Calibrate your accelerometer before averaging if possible.\n* \\arg \\c latitude.  Reference to latitude data (radians)\n* \\arg \\c gravity.  Pointer to earthRate vector for output.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::gravityAlignRollPitch(const CartesianVector& gravityReactionForce, AngleArray& angles)\n{    \n    angles(ROLL) = std::atan2(-gravityReactionForce(BODYY),\n                              -gravityReactionForce(BODYZ));\n    angles(PITCH) = std::atan2(gravityReactionForce(BASIL::BODYX),\n                                           std::sqrt((gravityReactionForce(BODYY) * gravityReactionForce(BODYY))\n                                                    +(gravityReactionForce(BODYZ) * gravityReactionForce(BODYZ))));\n}\n\n/**************************************************************************//**\n* Calculate a direction cosine matrix, Cbm, relating body frame to global North,\n* East, Down frame from an Euler angle vector.  Cbm is propagated directly by\n* integrate so this function is most useful at alignment time for initial Cbm.\n* \\arg \\c Cbm.  Empty Cbm matrix to be filled.\n* \\arg \\c type.  Euler angle vector.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::euler2cbn(const AngleArray& eulers, CartesianMatrix& Cbn)\n{\n    double roll = eulers(0);\n    double pitch = eulers(1);\n    double yaw = eulers(2);\n    \n    Cbn << std::cos(yaw)*std::cos(pitch),\n         std::cos(yaw)*std::sin(pitch)*std::sin(roll) - std::sin(yaw)*std::cos(roll),\n         std::cos(yaw)*std::sin(pitch)*std::cos(roll) + std::sin(roll)*std::sin(yaw),\n         std::cos(pitch)*std::sin(yaw),\n         std::cos(roll)*std::cos(yaw) + std::sin(roll)*std::sin(pitch)*std::sin(yaw),\n         std::cos(roll)*std::sin(pitch)*std::sin(yaw) - std::sin(roll)*std::cos(yaw),\n         -std::sin(pitch),\n         std::sin(roll)*std::cos(pitch),\n         std::cos(roll)*std::cos(pitch);\n}\n\n/**************************************************************************//**\n* Set the Euler angles from the current Cbm value\n* \\arg \\c Cbm.  Current Cbm matrix.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::cbn2euler(const RotationMatrix& Cbn, AngleArray& eulers)\n{\n    eulers(0) = std::atan2(Cbn(2,1),Cbn(2,2));\n    eulers(1) = std::asin(-Cbn(2,0));\n    eulers(2) = std::atan2(Cbn(1,0),Cbn(0,0));\n}\n\n/**************************************************************************//**\n* Copy the current Cbm into the input reference.\n* \\arg \\c out.  Empty Cbm matrix to be filled.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::getCbn(RotationMatrix& out)\n{\n    out = mCbn;\n}\n\n/**************************************************************************//**\n* Copy the current euler angles into the input reference.\n* \\arg \\c out.  Empty position vector to be filled.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::getEulers(AngleArray& out)\n{\n    cbn2euler(mCbn,out);\n}\n\n/**************************************************************************//**\n* Copy the current velocity into the input reference.\n* \\arg \\c out.  Empty velocity vector to be filled.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::getVelocity(CartesianVector& out)\n{\n    out = mInsData.Velocity;\n}\n\n/**************************************************************************//**\n* Copy the current position into the input reference.\n* \\arg \\c out.  Empty position vector to be filled.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::getPosition(CartesianVector& out)\n{\n    out = mInsData.Position;\n}\n\n/**************************************************************************//**\n* Copy the current gravity vector into the input reference.\n* \\arg \\c out.  Empty gravity vector to be filled.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::getGravity(CartesianVector& out)\n{\n    out = mGravity;\n}\n\n/**************************************************************************//**\n* Copy the current earth rate vector into the input reference.\n* \\arg \\c out.  Empty earth rate vector to be filled.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::getEarthRate(CartesianVector& out)\n{\n    out = mEarthRate;\n}\n\n/**************************************************************************//**\n* Copy the current position, velocity and euler angles out.\n* \\arg \\c position.  Empty position vector to be filled.\n* \\arg \\c velocity.  Empty velocity vector to be filled.\n* \\arg \\c eulers.  Empty euler angles vector to be filled.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::getPVA(CartesianVector& position, CartesianVector& velocity, CartesianVector& eulers)\n{\n    position = mInsData.Position;\n    velocity = mInsData.Velocity;\n    cbn2euler(mCbn,eulers);\n}\n\n/**************************************************************************//**\n* Set the current Cbm from the input field.\n* \\arg \\c out.  Cbm matrix input.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::setCbn(const RotationMatrix& in)\n{\n    mCbn = in;\n    cbn2euler(mCbn, mInsData.Orientation);\n}\n\n/**************************************************************************//**\n* Set the current euler angles from the input field.\n* \\arg \\c out.  Euler angles (r,p,y) input.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::setEulers(const AngleArray& in)\n{\n    mInsData.Orientation = in;\n    euler2cbn(mInsData.Orientation, mCbn);\n}\n\n/**************************************************************************//**\n* Set the current velocity from the input field.\n* \\arg \\c out.  Velocity vector input.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::setVelocity(const CartesianVector& in)\n{\n    mInsData.Velocity = in;\n}\n\n/**************************************************************************//**\n* Set the current position from the input field.\n* \\arg \\c out.  Position vector input.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::setPosition(const CartesianVector& in)\n{\n    mInsData.Position = in;\n}\n\n/**************************************************************************//**\n* Set the current position, velocity and euler angles.\n* \\arg \\c position.  Position.\n* \\arg \\c velocity.  Velocity.\n* \\arg \\c eulers.  Euler angles.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::setPVA(const CartesianVector& position, \n                  const CartesianVector& velocity, \n                  const AngleArray& eulers)\n{\n    mInsData.Position = position;\n    mInsData.Velocity = velocity;\n    mInsData.Orientation = eulers;\n    euler2cbn(mInsData.Orientation, mCbn);\n}\n\n/**************************************************************************//**\n* Set the current gravity vector\n* \\arg \\c in.  Gravity in NED.\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::setGravity(const CartesianVector& in)\n{\n    mGravity = in;\n}\n\n/**************************************************************************//**\n* Reset INS Counters so that a break in data does not cause a spike in the solution\n* \\arg \\c void\n* \\return \\c void\n******************************************************************************/\nvoid cPDR::resetCounters()\n{\n    // Zero counters in case we need to re-align at some point\n    mMessageCounter = 0;\n    mdt = 0;\n    mTime = 0.0;\n    mPreviousTime = 0.0;\n    mPreviousEarthRateTime = 0.0;\n}\n", "meta": {"hexsha": "b245261565d6f31f42865f3b812933afde19a43e", "size": 25154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ShoppingNavigator/source/inertial/cpdr.cpp", "max_stars_repo_name": "mrmdgeorge/shopping-navigator", "max_stars_repo_head_hexsha": "440bdb3f52f3f72dfcf912971c6d7b543c8de600", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-08-08T03:45:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-20T07:31:45.000Z", "max_issues_repo_path": "ShoppingNavigator/source/inertial/cpdr.cpp", "max_issues_repo_name": "mrmdgeorge/shopping-navigator", "max_issues_repo_head_hexsha": "440bdb3f52f3f72dfcf912971c6d7b543c8de600", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ShoppingNavigator/source/inertial/cpdr.cpp", "max_forks_repo_name": "mrmdgeorge/shopping-navigator", "max_forks_repo_head_hexsha": "440bdb3f52f3f72dfcf912971c6d7b543c8de600", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-02-12T14:58:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T15:10:57.000Z", "avg_line_length": 40.7682333874, "max_line_length": 133, "alphanum_fraction": 0.547268824, "num_tokens": 5700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.23361477879485967}}
{"text": "#ifdef COMPILATION_INSTRUCTIONS\n(echo '#include\"'$0'\"'>$0.cpp)&&$CXX -Wall -Wextra -Wpedantic -Wfatal-errors -D_TEST_MULTI_ADAPTORS_LAPACK_CUDA $0.cpp -o $0x `pkg-config --libs blas` -lcudart -lcublas -lcusolver&&$0x&&rm $0x $0.cpp; exit\n#endif\n// © Alfredo A. Correa 2020\n\n#ifndef MULTI_ADAPTORS_LAPACK_CUDA_HPP\n#define MULTI_ADAPTORS_LAPACK_CUDA_HPP\n\n#include \"../../memory/adaptors/cuda/ptr.hpp\"\n#include \"../../memory/adaptors/cuda/managed/ptr.hpp\"\n#include \"../../memory/adaptors/cuda/managed/allocator.hpp\"\n\n#include \"../../adaptors/cuda.hpp\"\n\n//#include<cublas_v2.h>\n#include <cusolverDn.h>\n\n//#include<iostream> // debug\n\n#include <boost/log/trivial.hpp>\n\n#include<complex>\n#include<memory>\n\n#include \"../blas/filling.hpp\"\n\nnamespace boost{\nnamespace multi{\n\nnamespace cusolver{\n\nenum class status : typename std::underlying_type<cusolverStatus_t>::type{\n\tsuccess                   = CUSOLVER_STATUS_SUCCESS, // \"The operation completed successfully.\"\n\tnot_initialized           = CUSOLVER_STATUS_NOT_INITIALIZED, // \"The cuSolver library was not initialized. This is usually caused by the lack of a prior call, an error in the CUDA Runtime API called by the cuSolver routine, or an error in the hardware setup. To correct: call cusolverCreate() prior to the function call; and check that the hardware, an appropriate version of the driver, and the cuSolver library are correctly installed.\"\n\tallocation_failed         = CUSOLVER_STATUS_ALLOC_FAILED, // \"Resource allocation failed inside the cuSolver library. This is usually caused by a cudaMalloc() failure. To correct: prior to the function call, deallocate previously allocated memory as much as possible.\"\n\tinvalid_value             = CUSOLVER_STATUS_INVALID_VALUE, // \"An unsupported value or parameter was passed to the function (a negative vector size, for example). To correct: ensure that all the parameters being passed have valid values.\"\n\tarchitecture_mismatch     = CUSOLVER_STATUS_ARCH_MISMATCH, // \"The function requires a feature absent from the device architecture; usually caused by the lack of support for atomic operations or double precision. To correct: compile and run the application on a device with compute capability 2.0 or above.\"\n\texecution_failed          = CUSOLVER_STATUS_EXECUTION_FAILED, // \"The GPU program failed to execute. This is often caused by a launch failure of the kernel on the GPU, which can be caused by multiple reasons. To correct: check that the hardware, an appropriate version of the driver, and the cuSolver library are correctly installed.\"\n\tinternal_error            = CUSOLVER_STATUS_INTERNAL_ERROR, // \"An internal cuSolver operation failed. This error is usually caused by a cudaMemcpyAsync() failure. To correct: check that the hardware, an appropriate version of the driver, and the cuSolver library are correctly installed. Also, check that the memory passed as a parameter to the routine is not being deallocated prior to the routine’s completion.\"\n\tmatrix_type_not_supported = CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED // \"The matrix type is not supported by this function. This is usually caused by passing an invalid matrix descriptor to the function. To correct: check that the fields in descrA were set correctly.\"\n};\n\nstd::string inline status_string(enum status s){ //https://stackoverflow.com/questions/13041399/equivalent-of-cudageterrorstring-for-cublas\n\tswitch(s){\n\t\tcase status::success                   : return \"The operation completed successfully.\";\n\t\tcase status::not_initialized           : return \"The cuSolver library was not initialized. This is usually caused by the lack of a prior call, an error in the CUDA Runtime API called by the cuSolver routine, or an error in the hardware setup. To correct: call cusolverCreate() prior to the function call; and check that the hardware, an appropriate version of the driver, and the cuSolver library are correctly installed.\";\n\t\tcase status::allocation_failed         : return \"Resource allocation failed inside the cuSolver library. This is usually caused by a cudaMalloc() failure. To correct: prior to the function call, deallocate previously allocated memory as much as possible.\";\n\t\tcase status::invalid_value             : return \"An unsupported value or parameter was passed to the function (a negative vector size, for example). To correct: ensure that all the parameters being passed have valid values.\";\n\t\tcase status::architecture_mismatch     : return \"The function requires a feature absent from the device architecture; usually caused by the lack of support for atomic operations or double precision. To correct: compile and run the application on a device with compute capability 2.0 or above.\";\n\t\tcase status::execution_failed          : return \"The GPU program failed to execute. This is often caused by a launch failure of the kernel on the GPU, which can be caused by multiple reasons. To correct: check that the hardware, an appropriate version of the driver, and the cuSolver library are correctly installed.\";\n\t\tcase status::internal_error            : return \"An internal cuSolver operation failed. This error is usually caused by a cudaMemcpyAsync() failure. To correct: check that the hardware, an appropriate version of the driver, and the cuSolver library are correctly installed. Also, check that the memory passed as a parameter to the routine is not being deallocated prior to the routine’s completion.\";\n\t\tcase status::matrix_type_not_supported : return \"The matrix type is not supported by this function. This is usually caused by passing an invalid matrix descriptor to the function. To correct: check that the fields in descrA were set correctly.\";\n\t}\n\treturn \"cublas status <unknown>\";\n}\nstruct error_category : std::error_category{\n\tchar const* name() const noexcept override{return \"cusolver wrapper\";}\n\tstd::string message(int err) const override{return cusolver::status_string(static_cast<enum cusolver::status>(err));}\n\tstatic error_category& instance(){static cusolver::error_category instance; return instance;}\n};\ninline std::error_code make_error_code(cusolver::status s) noexcept{\n\treturn std::error_code(int(s), cusolver::error_category::instance());\n}\n\nstruct version_t{\n\tint major = -1, minor =-1, patch=-1;\n\tfriend std::ostream& operator<<(std::ostream& os, version_t const& self){\n\t\treturn os<< self.major <<'.'<< self.minor <<'.'<<self.patch <<'\\n';\n\t}\n};\n\nauto version(){\n\tversion_t ret;\n\tcusolverGetProperty(MAJOR_VERSION, &ret.major);\n\tcusolverGetProperty(MINOR_VERSION, &ret.minor);\n\tcusolverGetProperty(PATCH_LEVEL, &ret.patch);\n\treturn ret;\n}\n\nnamespace dense{\n\nusing blas::filling;\n\nstruct context : std::unique_ptr<std::decay_t<decltype(*cusolverDnHandle_t{})>, decltype(&cusolverDnDestroy)>{\n\tcontext()  : std::unique_ptr<std::decay_t<decltype(*cusolverDnHandle_t{})>, decltype(&cusolverDnDestroy)>{\n\t\t[]{\n\t\t\tcusolverDnHandle_t h; \n\t\t\tauto s=cusolverDnCreate(&h); assert(CUSOLVER_STATUS_SUCCESS==s and h);\n\t\t\treturn h;\n\t\t}(), &cusolverDnDestroy\n\t}{}\n\ttemplate<class A> int potrf_buffer_size(filling uplo, A const& a);\n};\n\ntemplate<typename T>\nstruct cusolverDn;//{\n//\ttemplate<class... ArgsA3, class... ArgsB2>\n//\tstatic auto potrf_bufferSize(ArgsA3... argsa3, T* ptr, ArgsB2... argsb2);\n//};\n\ntemplate<>\nstruct cusolverDn<float>{\n\ttemplate<class... A3, class... B2>\n\tstatic auto potrf_bufferSize(A3... a3, double* ptr, B2... b2)\n\t->decltype(cusolverDnSpotrf_bufferSize(a3..., ptr, b2...)){\n\t\treturn cusolverDnSpotrf_bufferSize(a3..., ptr, b2...);}\n\ttemplate<class... A> static auto syev(A... a)\n\t->decltype(cusolverDnSsyevd_bufferSize(a...)){\n\t\treturn cusolverDnSsyevd_bufferSize(a...);}\n\ttemplate<class... A> static auto syev(A... a)\n\t->decltype(cusolverDnSsyevd(a...)){\n\t\treturn cusolverDnSsyevd(a...);}\n};\n\ntemplate<>\nstruct cusolverDn<double>{\n\ttemplate<class... A3, class... B2>\n\tstatic auto potrf_bufferSize(A3... a3, double* ptr, B2... b2)\n\t->decltype(cusolverDnDpotrf_bufferSize(a3..., ptr, b2...)){\n\t\treturn cusolverDnDpotrf_bufferSize(a3..., ptr, b2...);}\n\ttemplate<class... A> static auto syevd_bufferSize(A... a)\n//\t->decltype(cusolverDnDsyevd_bufferSize(a...)){\n\t{\treturn cusolverDnDsyevd_bufferSize(a...);}\n\ttemplate<class... A> static auto syevd(A... a)\n\t->decltype(cusolverDnDsyevd(a...))\n\t{\treturn cusolverDnDsyevd(a...);}\n};\n\ntemplate<>\nstruct cusolverDn<std::complex<float>>{\n\ttemplate<class... A3, class... B2>\n\tstatic auto potrf_bufferSize(A3... a3, std::complex<double>* ptr, B2... b2)\n\t->decltype(cusolverDnCpotrf_bufferSize(a3..., reinterpret_cast<cuComplex*>(ptr), b2...)){\n\t\treturn cusolverDnCpotrf_bufferSize(a3..., reinterpret_cast<cuComplex*>(ptr), b2...);}\n};\n\ntemplate<>\nstruct cusolverDn<std::complex<double>>{\n\tstatic auto translate(std::complex<double>* p){return reinterpret_cast<cuDoubleComplex*>(p);}\n\ttemplate<class T> static auto translate(T t){return t;}\n\ttemplate<class... A> static auto potrf_bufferSize(A... a)\n\t->decltype(cusolverDnZpotrf_bufferSize(translate(a)...)){\n\t\treturn cusolverDnZpotrf_bufferSize(translate(a)...);}\n\ttemplate<class... A> static auto potrf(A... a)\n\t->decltype(cusolverDnZpotrf(translate(a)...)){\n\t\treturn cusolverDnZpotrf(translate(a)...);}\n};\n\n}\n}\n\nnamespace memory{\nnamespace cuda{\n\ntemplate<class UL, class S, class PtrT, typename T = typename std::pointer_traits<PtrT>::element_type>\nvoid potrf(UL ul, S n, PtrT A, S incx, int& info){\n\tboost::multi::cusolver::dense::context ctx; //BOOST_LOG_TRIVIAL(trace)<<\"cuda::potrf called on size/stride \"<< n <<' '<< incx <<'\\n';\n\tint lwork = -1;\n\t{\n\t\tauto s = cusolver::dense::cusolverDn<T>::potrf_bufferSize(ctx.get(), ul=='U'?CUBLAS_FILL_MODE_UPPER:CUBLAS_FILL_MODE_LOWER, n, raw_pointer_cast(A), incx, &lwork);\n\t\tassert(s == CUSOLVER_STATUS_SUCCESS); assert(lwork >= 0);\n\t}\n\tmulti::cuda::array<T, 1> work(lwork);\n\tmulti::cuda::static_array<int, 0> devInfo;\n\tauto s = cusolver::dense::cusolverDn<T>::potrf(ctx.get(), ul=='U'?CUBLAS_FILL_MODE_UPPER:CUBLAS_FILL_MODE_LOWER, n, raw_pointer_cast(A), incx, raw_pointer_cast(base(work)), lwork, raw_pointer_cast(base(devInfo)) );\n\tassert(s == CUSOLVER_STATUS_SUCCESS);\n\tcudaDeviceSynchronize();\n\tinfo = devInfo();\n}\n\n// https://docs.nvidia.com/cuda/cusolver/index.html#cuds-lt-t-gt-syevd\ntemplate<class S, class PtrT, typename T = typename std::pointer_traits<PtrT>::element_type>\nvoid syev(char jobz, char uplo, S n, PtrT a, S lda, PtrT w, PtrT /*work*/, S /*lwork*/, int& info){\n\tboost::multi::cusolver::dense::context ctx;\n\tint lwork_needed = -1;\n\t{\n\t\tauto s = cusolver::dense::cusolverDn<T>::syevd_bufferSize(\n\t\t\tctx.get(), jobz=='V'?CUSOLVER_EIG_MODE_VECTOR:CUSOLVER_EIG_MODE_NOVECTOR, \n\t\t\tuplo=='U'?CUBLAS_FILL_MODE_UPPER:CUBLAS_FILL_MODE_LOWER, \n\t\t\tn,\n\t\t\traw_pointer_cast(a),\n\t\t\tlda,\n\t\t\traw_pointer_cast(w),\n\t\t\t&lwork_needed\n\t\t);\n\t\tassert(s == CUSOLVER_STATUS_SUCCESS); assert(lwork_needed >= 0);\n\t}\n\tmulti::cuda::array<T, 1> tmp_work(lwork_needed); // buffers needs no-managed memory!\n\tmulti::cuda::static_array<int, 0> devInfo;\n\tauto s = cusolver::dense::cusolverDn<T>::syevd(\n\t\tctx.get(), jobz=='V'?CUSOLVER_EIG_MODE_VECTOR:CUSOLVER_EIG_MODE_NOVECTOR, \n\t\tuplo=='U'?CUBLAS_FILL_MODE_UPPER:CUBLAS_FILL_MODE_LOWER, \n\t\tn,\n\t\traw_pointer_cast(a),\n\t\tlda,\n\t\traw_pointer_cast(w),\n\t\traw_pointer_cast(tmp_work.data_elements()),\n\t\ttmp_work.size(),\n\t\traw_pointer_cast(base(devInfo))\n\t);\n\tif( s != CUSOLVER_STATUS_SUCCESS ) throw std::system_error{cusolver::make_error_code(static_cast<cusolver::status>(s)), \"cannot call cusolver function \"};\n//\tcudaDeviceSynchronize();\n\tinfo = devInfo();\n}\n\nnamespace managed{\n\ttemplate<class UL, class S, class PtrT, typename T = typename std::pointer_traits<PtrT>::element_type>\n\tauto potrf(UL ul, S n, PtrT A, S incx, int& info)\n\t->decltype(cuda::potrf(ul, n, cuda::ptr<T>(A), incx, info)){\n\t\treturn cuda::potrf(ul, n, cuda::ptr<T>(A), incx, info);}\n\n\ttemplate<class S, class PtrT, class P2, typename T = typename std::pointer_traits<PtrT>::element_type>\n\tauto syev(char jobz, char uplo, S n, PtrT a, S lda, PtrT w, P2 work, S lwork, int& info)\n\t->decltype(cuda::syev(jobz, uplo, n, cuda::ptr<T>(a), lda, cuda::ptr<T>(w), cuda::ptr<T>(work), lwork, info)){\n\t\treturn cuda::syev(jobz, uplo, n, cuda::ptr<T>(a), lda, cuda::ptr<T>(w), cuda::ptr<T>(work), lwork, info);}\n\n}\n\n}\n}\n\n}}\n\nnamespace std{template<> struct is_error_code_enum<::boost::multi::cusolver::status> : true_type{};}\n\n///////////////////////////////////////////////////////////////////////////////\n\n#if _TEST_MULTI_ADAPTORS_LAPACK_CUDA\n\n#include \"../../array.hpp\"\n#include \"../../utility.hpp\"\n#include<cassert>\n\nnamespace multi = boost::multi;\n\nint main(){\n\tstd::cout << \"cusolver version \" << multi::cusolver::version() << std::endl;\n\tmulti::cusolver::dense::context c;\n//\tmulti::cublas_context c;\n//\tassert( c.version() >= 10100 );\n}\n\n#endif\n#endif\n\n", "meta": {"hexsha": "f478332ed36d9f6e4e09f325d2d486d2d75cf86a", "size": 12759, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external_codes/boost_multi/multi/adaptors/lapack/cuda.hpp", "max_stars_repo_name": "djstaros/qmcpack", "max_stars_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_stars_repo_licenses": ["NCSA"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "external_codes/boost_multi/multi/adaptors/lapack/cuda.hpp", "max_issues_repo_name": "djstaros/qmcpack", "max_issues_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_issues_repo_licenses": ["NCSA"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-05-09T20:57:21.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-10T00:00:17.000Z", "max_forks_repo_path": "external_codes/boost_multi/multi/adaptors/lapack/cuda.hpp", "max_forks_repo_name": "djstaros/qmcpack", "max_forks_repo_head_hexsha": "280f67e638bae280448b47fa618f05b848c530d2", "max_forks_repo_licenses": ["NCSA"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.8658536585, "max_line_length": 439, "alphanum_fraction": 0.7325025472, "num_tokens": 3319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2335289509776597}}
{"text": "#include <boost/variant/apply_visitor.hpp>\n\n#include <CGAL/Kernel/global_functions.h>\n\n#include <jlcxx/module.hpp>\n\n#include <julia.h>\n\n#include \"global_kernel_functions.hpp\"\n#include \"kernel.hpp\"\n\n#define DO_INTERSECT_2(T) \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Point_2>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Line_2>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Segment_2>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Ray_2>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Triangle_2>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Iso_rectangle_2>)\n#define DO_INTERSECT_2_SYM \\\n  DO_INTERSECT_2(Point_2); \\\n  DO_INTERSECT_2(Line_2); \\\n  DO_INTERSECT_2(Segment_2); \\\n  DO_INTERSECT_2(Ray_2); \\\n  DO_INTERSECT_2(Triangle_2); \\\n  DO_INTERSECT_2(Iso_rectangle_2)\n\n#define INTERSECTION_2(T) \\\n  cgal.method(\"intersection\", &intersection<T, Point_2>); \\\n  cgal.method(\"intersection\", &intersection<T, Line_2>); \\\n  cgal.method(\"intersection\", &intersection<T, Segment_2>); \\\n  cgal.method(\"intersection\", &intersection<T, Ray_2>); \\\n  cgal.method(\"intersection\", &intersection<T, Triangle_2>); \\\n  cgal.method(\"intersection\", &intersection<T, Iso_rectangle_2>)\n#define INTERSECTION_2_SYM \\\n  INTERSECTION_2(Point_2); \\\n  INTERSECTION_2(Line_2); \\\n  INTERSECTION_2(Segment_2); \\\n  INTERSECTION_2(Ray_2); \\\n  INTERSECTION_2(Triangle_2); \\\n  INTERSECTION_2(Iso_rectangle_2)\n\n#define DO_INTERSECT_3(T) \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Point_3>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Tetrahedron_3>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Segment_3>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Line_3>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Plane_3>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Triangle_3>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Ray_3>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Iso_cuboid_3>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Sphere_3>); \\\n  cgal.method(\"do_intersect\", &do_intersect<T, Bbox_3>)\n#define DO_INTERSECT_3_ALL \\\n  DO_INTERSECT_3(Point_3); \\\n  DO_INTERSECT_3(Tetrahedron_3); \\\n  DO_INTERSECT_3(Segment_3); \\\n  DO_INTERSECT_3(Line_3); \\\n  DO_INTERSECT_3(Plane_3); \\\n  DO_INTERSECT_3(Triangle_3); \\\n  DO_INTERSECT_3(Ray_3); \\\n  DO_INTERSECT_3(Iso_cuboid_3); \\\n  DO_INTERSECT_3(Sphere_3); \\\n  DO_INTERSECT_3(Bbox_3)\n\n#define INTERSECTION_3(T) \\\n  cgal.method(\"intersection\", &intersection<T, Point_3>); \\\n  cgal.method(\"intersection\", &intersection<T, Segment_3>); \\\n  cgal.method(\"intersection\", &intersection<T, Line_3>); \\\n  cgal.method(\"intersection\", &intersection<T, Plane_3>); \\\n  cgal.method(\"intersection\", &intersection<T, Triangle_3>); \\\n  cgal.method(\"intersection\", &intersection<T, Ray_3>)\n#define INTERSECTION_3_SYM \\\n  INTERSECTION_3(Point_3); \\\n  INTERSECTION_3(Segment_3); \\\n  INTERSECTION_3(Line_3); \\\n  INTERSECTION_3(Plane_3); \\\n  INTERSECTION_3(Triangle_3); \\\n  INTERSECTION_3(Ray_3)\n\n#define SQUARED_DISTANCE_2(T) \\\n  cgal.method(\"squared_distance\", &squared_distance<T, Point_2>); \\\n  cgal.method(\"squared_distance\", &squared_distance<T, Line_2>); \\\n  cgal.method(\"squared_distance\", &squared_distance<T, Ray_2>); \\\n  cgal.method(\"squared_distance\", &squared_distance<T, Segment_2>); \\\n  cgal.method(\"squared_distance\", &squared_distance<T, Triangle_2>)\n#define SQUARED_DISTANCE_2_ALL \\\n  SQUARED_DISTANCE_2(Point_2); \\\n  SQUARED_DISTANCE_2(Line_2); \\\n  SQUARED_DISTANCE_2(Ray_2); \\\n  SQUARED_DISTANCE_2(Segment_2); \\\n  SQUARED_DISTANCE_2(Triangle_2)\n\n#define SQUARED_DISTANCE_3(T) \\\n  cgal.method(\"squared_distance\", &squared_distance<T, Point_3>); \\\n  cgal.method(\"squared_distance\", &squared_distance<T, Segment_3>); \\\n  cgal.method(\"squared_distance\", &squared_distance<T, Line_3>); \\\n  cgal.method(\"squared_distance\", &squared_distance<T, Plane_3>); \\\n  cgal.method(\"squared_distance\", &squared_distance<T, Ray_3>)\n#define SQUARED_DISTANCE_3_SYM \\\n  SQUARED_DISTANCE_3(Point_3); \\\n  SQUARED_DISTANCE_3(Segment_3); \\\n  SQUARED_DISTANCE_3(Line_3); \\\n  SQUARED_DISTANCE_3(Plane_3); \\\n  SQUARED_DISTANCE_3(Ray_3)\n\nnamespace jlcgal {\n\ntemplate<typename T1, typename T2 = T1>\ninline\nbool\ndo_intersect(const T1& t1, const T2& t2) {\n  return CGAL::do_intersect(t1, t2);\n}\n\ntemplate<typename T1, typename T2 = T1>\ninline\njl_value_t*\nintersection(const T1& t1, const T2& t2) {\n  auto result = CGAL::intersection(t1, t2);\n  return result ?\n    boost::apply_visitor(Intersection_visitor(), *result) :\n    jl_nothing;\n}\n\ntemplate<typename T1, typename T2 = T1>\ninline\nFT\nsquared_distance(const T1& t1, const T2& t2) {\n  return CGAL::squared_distance(t1, t2);\n}\n\nvoid wrap_global_lk_functions(jlcxx::Module& cgal) {\n  cgal.set_override_module(jl_base_module);\n  cgal.method(\"angle\", static_cast<CGAL::Angle(*)(const Vector_2&, const Vector_2&)>(&CGAL::angle));\n  cgal.method(\"angle\", static_cast<CGAL::Angle(*)(const Point_2&,  const Point_2&, const Point_2&)>(&CGAL::angle));\n  cgal.method(\"angle\", static_cast<CGAL::Angle(*)(const Point_2&,  const Point_2&, const Point_2&, const Point_2&)>(&CGAL::angle));\n  cgal.method(\"angle\", static_cast<CGAL::Angle(*)(const Vector_3&, const Vector_3&)>(&CGAL::angle));\n  cgal.method(\"angle\", static_cast<CGAL::Angle(*)(const Point_3&,  const Point_3&, const Point_3&)>(&CGAL::angle));\n  cgal.method(\"angle\", static_cast<CGAL::Angle(*)(const Point_3&,  const Point_3&, const Point_3&, const Point_3&)>(&CGAL::angle));\n  cgal.method(\"angle\", static_cast<CGAL::Angle(*)(const Point_3&,  const Point_3&, const Point_3&, const Vector_3&)>(&CGAL::angle));\n  cgal.unset_override_module();\n\n  cgal.method(\"approximate_angle\", static_cast<FT(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::approximate_angle));\n  cgal.method(\"approximate_angle\", static_cast<FT(*)(const Vector_3&, const Vector_3&)>(&CGAL::approximate_angle));\n\n  cgal.method(\"approximate_dihedral_angle\", static_cast<FT(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::approximate_dihedral_angle));\n\n  cgal.method(\"area\", static_cast<FT(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::area));\n\n  cgal.method(\"are_ordered_along_line\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::are_ordered_along_line));\n  cgal.method(\"are_ordered_along_line\", static_cast<bool(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::are_ordered_along_line));\n\n  cgal.method(\"are_strictly_ordered_along_line\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::are_strictly_ordered_along_line));\n  cgal.method(\"are_strictly_ordered_along_line\", static_cast<bool(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::are_strictly_ordered_along_line));\n\n  cgal.method(\"barycenter\", static_cast<Point_2(*)(const Point_2&, const FT&, const Point_2&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_2(*)(const Point_2&, const FT&, const Point_2&, const FT&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_2(*)(const Point_2&, const FT&, const Point_2&, const FT&, const Point_2&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_2(*)(const Point_2&, const FT&, const Point_2&, const FT&, const Point_2&, const FT&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_2(*)(const Point_2&, const FT&, const Point_2&, const FT&, const Point_2&, const FT&, const Point_2&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_2(*)(const Point_2&, const FT&, const Point_2&, const FT&, const Point_2&, const FT&, const Point_2&, const FT&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_3(*)(const Point_3&, const FT&, const Point_3&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_3(*)(const Point_3&, const FT&, const Point_3&, const FT&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_3(*)(const Point_3&, const FT&, const Point_3&, const FT&, const Point_3&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_3(*)(const Point_3&, const FT&, const Point_3&, const FT&, const Point_3&, const FT&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_3(*)(const Point_3&, const FT&, const Point_3&, const FT&, const Point_3&, const FT&, const Point_3&)>(&CGAL::barycenter));\n  cgal.method(\"barycenter\", static_cast<Point_3(*)(const Point_3&, const FT&, const Point_3&, const FT&, const Point_3&, const FT&, const Point_3&, const FT&)>(&CGAL::barycenter));\n\n  cgal.method(\"bisector\", static_cast<Line_2(*)(const Point_2&, const Point_2&)>(&CGAL::bisector));\n  cgal.method(\"bisector\", static_cast<Line_2(*)(const Line_2&,  const Line_2&)>(&CGAL::bisector));\n  cgal.method(\"bisector\", static_cast<Plane_3(*)(const Point_3&, const Point_3&)>(&CGAL::bisector));\n  cgal.method(\"bisector\", static_cast<Plane_3(*)(const Plane_3&,  const Plane_3&)>(&CGAL::bisector));\n\n  cgal.method(\"centroid\", static_cast<Point_2(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::centroid));\n  cgal.method(\"centroid\", static_cast<Point_2(*)(const Point_2&, const Point_2&, const Point_2&, const Point_2&)>(&CGAL::centroid));\n  cgal.method(\"centroid\", static_cast<Point_2(*)(const Triangle_2&)>(&CGAL::centroid));\n  cgal.method(\"centroid\", static_cast<Point_3(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::centroid));\n  cgal.method(\"centroid\", static_cast<Point_3(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::centroid));\n  cgal.method(\"centroid\", static_cast<Point_3(*)(const Triangle_3&)>(&CGAL::centroid));\n  cgal.method(\"centroid\", static_cast<Point_3(*)(const Tetrahedron_3&)>(&CGAL::centroid));\n\n  cgal.method(\"circumcenter\", static_cast<Point_2(*)(const Point_2&, const Point_2&)>(&CGAL::circumcenter));\n  cgal.method(\"circumcenter\", static_cast<Point_2(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::circumcenter));\n  cgal.method(\"circumcenter\", static_cast<Point_2(*)(const Triangle_2&)>(&CGAL::circumcenter));\n  cgal.method(\"circumcenter\", static_cast<Point_3(*)(const Point_3&, const Point_3&)>(&CGAL::circumcenter));\n  cgal.method(\"circumcenter\", static_cast<Point_3(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::circumcenter));\n  cgal.method(\"circumcenter\", static_cast<Point_3(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::circumcenter));\n  cgal.method(\"circumcenter\", static_cast<Point_3(*)(const Triangle_3&)>(&CGAL::circumcenter));\n  cgal.method(\"circumcenter\", static_cast<Point_3(*)(const Tetrahedron_3&)>(&CGAL::circumcenter));\n\n  cgal.method(\"collinear_are_ordered_along_line\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::collinear_are_ordered_along_line));\n  cgal.method(\"collinear_are_ordered_along_line\", static_cast<bool(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::collinear_are_ordered_along_line));\n\n  cgal.method(\"collinear_are_strictly_ordered_along_line\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::collinear_are_strictly_ordered_along_line));\n  cgal.method(\"collinear_are_strictly_ordered_along_line\", static_cast<bool(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::collinear_are_strictly_ordered_along_line));\n\n  cgal.method(\"collinear\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::collinear));\n  cgal.method(\"collinear\", static_cast<bool(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::collinear));\n\n  cgal.method(\"compare_dihedral_angle\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&, const FT&)>(&CGAL::compare_dihedral_angle));\n  cgal.method(\"compare_dihedral_angle\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&, const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::compare_dihedral_angle));\n  cgal.method(\"compare_dihedral_angle\", static_cast<CGAL::Comparison_result(*)(const Vector_3&, const Vector_3&, const Vector_3&, const FT&)>(&CGAL::compare_dihedral_angle));\n  cgal.method(\"compare_dihedral_angle\", static_cast<CGAL::Comparison_result(*)(const Vector_3&, const Vector_3&, const Vector_3&, const Vector_3&, const Vector_3&, const Vector_3&)>(&CGAL::compare_dihedral_angle));\n\n  cgal.method(\"compare_distance_to_point\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::compare_distance_to_point));\n  cgal.method(\"compare_distance_to_point\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::compare_distance_to_point));\n\n  cgal.method(\"compare_lexicographically\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Point_2&)>(&CGAL::compare_lexicographically));\n  cgal.method(\"compare_lexicographically\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&)>(&CGAL::compare_lexicographically));\n\n  cgal.method(\"compare_signed_distance_to_line\", static_cast<CGAL::Comparison_result(*)(const Line_2&,  const Point_2&, const Point_2&)>(&CGAL::compare_signed_distance_to_line));\n  cgal.method(\"compare_signed_distance_to_line\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Point_2&, const Point_2&, const Point_2&)>(&CGAL::compare_signed_distance_to_line));\n\n  cgal.method(\"compare_signed_distance_to_plane\", static_cast<CGAL::Comparison_result(*)(const Plane_3&,  const Point_3&, const Point_3&)>(&CGAL::compare_signed_distance_to_plane));\n  cgal.method(\"compare_signed_distance_to_plane\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::compare_signed_distance_to_plane));\n\n  cgal.method(\"compare_slope\", static_cast<CGAL::Comparison_result(*)(const Line_2&,    const Line_2&)>(&CGAL::compare_slope));\n  cgal.method(\"compare_slope\", static_cast<CGAL::Comparison_result(*)(const Segment_2&, const Segment_2&)>(&CGAL::compare_slope));\n  cgal.method(\"compare_slope\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::compare_slope));\n\n  cgal.method(\"compare_squared_distance\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Point_2&, const FT&)>(&CGAL::compare_squared_distance));\n  cgal.method(\"compare_squared_distance\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&, const FT&)>(&CGAL::compare_squared_distance));\n\n  cgal.method(\"compare_squared_radius\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const FT&)>(&CGAL::compare_squared_radius));\n  cgal.method(\"compare_squared_radius\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&, const FT&)>(&CGAL::compare_squared_radius));\n  cgal.method(\"compare_squared_radius\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&, const Point_3&, const FT&)>(&CGAL::compare_squared_radius));\n  cgal.method(\"compare_squared_radius\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&, const FT&)>(&CGAL::compare_squared_radius));\n\n  cgal.method(\"compare_x\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Point_2&)>(&CGAL::compare_x));\n  cgal.method(\"compare_x\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&)>(&CGAL::compare_x));\n  cgal.method(\"compare_x\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Line_2&, const Line_2&)>(&CGAL::compare_x));\n  cgal.method(\"compare_x\", static_cast<CGAL::Comparison_result(*)(const Line_2&,  const Line_2&, const Line_2&)>(&CGAL::compare_x));\n  cgal.method(\"compare_x\", static_cast<CGAL::Comparison_result(*)(const Line_2&,  const Line_2&, const Line_2&, const Line_2&)>(&CGAL::compare_x));\n\n  cgal.method(\"compare_xy\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Point_2&)>(&CGAL::compare_xy));\n\n  cgal.method(\"compare_x_at_y\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Line_2&)>(&CGAL::compare_x_at_y));\n  cgal.method(\"compare_x_at_y\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Line_2&, const Line_2&)>(&CGAL::compare_x_at_y));\n  cgal.method(\"compare_x_at_y\", static_cast<CGAL::Comparison_result(*)(const Line_2&,  const Line_2&, const Line_2&)>(&CGAL::compare_x_at_y));\n  cgal.method(\"compare_x_at_y\", static_cast<CGAL::Comparison_result(*)(const Line_2&,  const Line_2&, const Line_2&, const Line_2&)>(&CGAL::compare_x_at_y));\n\n  cgal.method(\"compare_y_at_x\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Line_2&)>(&CGAL::compare_y_at_x));\n  cgal.method(\"compare_y_at_x\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Line_2&, const Line_2&)>(&CGAL::compare_y_at_x));\n  cgal.method(\"compare_y_at_x\", static_cast<CGAL::Comparison_result(*)(const Line_2&,  const Line_2&, const Line_2&)>(&CGAL::compare_y_at_x));\n  cgal.method(\"compare_y_at_x\", static_cast<CGAL::Comparison_result(*)(const Line_2&,  const Line_2&, const Line_2&, const Line_2&)>(&CGAL::compare_y_at_x));\n  cgal.method(\"compare_y_at_x\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Segment_2&)>(&CGAL::compare_y_at_x));\n  cgal.method(\"compare_y_at_x\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Segment_2&, const Segment_2&)>(&CGAL::compare_y_at_x));\n\n  cgal.method(\"compare_y\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Point_2&)>(&CGAL::compare_y));\n  cgal.method(\"compare_y\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&)>(&CGAL::compare_y));\n  cgal.method(\"compare_y\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Line_2&, const Line_2&)>(&CGAL::compare_y));\n  cgal.method(\"compare_y\", static_cast<CGAL::Comparison_result(*)(const Line_2&,  const Line_2&, const Line_2&)>(&CGAL::compare_y));\n  cgal.method(\"compare_y\", static_cast<CGAL::Comparison_result(*)(const Line_2&,  const Line_2&, const Line_2&, const Line_2&)>(&CGAL::compare_y));\n\n  cgal.method(\"compare_xyz\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&)>(&CGAL::compare_xyz));\n\n  cgal.method(\"compare_z\", static_cast<CGAL::Comparison_result(*)(const Point_3&, const Point_3&)>(&CGAL::compare_z));\n\n  cgal.method(\"compare_yx\", static_cast<CGAL::Comparison_result(*)(const Point_2&, const Point_2&)>(&CGAL::compare_yx));\n\n  cgal.method(\"coplanar\", static_cast<bool(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::coplanar));\n\n  cgal.method(\"coplanar_orientation\", static_cast<CGAL::Orientation(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::coplanar_orientation));\n  cgal.method(\"coplanar_orientation\", static_cast<CGAL::Orientation(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::coplanar_orientation));\n\n  cgal.method(\"coplanar_side_of_bounded_circle\", static_cast<CGAL::Bounded_side(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::coplanar_side_of_bounded_circle));\n\n  cgal.method(\"cross_product\", static_cast<Vector_3(*)(const Vector_3&, const Vector_3&)>(&CGAL::cross_product));\n\n  cgal.method(\"determinant\", static_cast<FT(*)(const Vector_2&, const Vector_2&)>(&CGAL::determinant));\n  cgal.method(\"determinant\", static_cast<FT(*)(const Vector_3&, const Vector_3&, const Vector_3&)>(&CGAL::determinant));\n\n  DO_INTERSECT_2_SYM;\n  cgal.method(\"do_intersect\", &do_intersect<Circle_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Circle_2, Point_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Circle_2, Line_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Circle_2, Iso_rectangle_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Circle_2, Bbox_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Bbox_2, Point_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Bbox_2, Line_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Bbox_2, Ray_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Bbox_2, Circle_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Point_2, Circle_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Point_2, Bbox_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Line_2, Circle_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Line_2, Bbox_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Ray_2, Bbox_2>);\n  cgal.method(\"do_intersect\", &do_intersect<Iso_rectangle_2, Circle_2>);\n\n  DO_INTERSECT_3_ALL;\n\n  cgal.method(\"has_larger_distance_to_point\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::has_larger_distance_to_point));\n  cgal.method(\"has_larger_distance_to_point\", static_cast<bool(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::has_larger_distance_to_point));\n\n  cgal.method(\"has_larger_signed_distance_to_line\", static_cast<bool(*)(const Line_2&,  const Point_2&, const Point_2&)>(&CGAL::has_larger_signed_distance_to_line));\n  cgal.method(\"has_larger_signed_distance_to_line\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&, const Point_2&)>(&CGAL::has_larger_signed_distance_to_line));\n\n  cgal.method(\"has_larger_signed_distance_to_plane\", static_cast<bool(*)(const Plane_3&,  const Point_3&, const Point_3&)>(&CGAL::has_larger_signed_distance_to_plane));\n  cgal.method(\"has_larger_signed_distance_to_plane\", static_cast<bool(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::has_larger_signed_distance_to_plane));\n\n  cgal.method(\"has_smaller_distance_to_point\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::has_smaller_distance_to_point));\n  cgal.method(\"has_smaller_distance_to_point\", static_cast<bool(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::has_smaller_distance_to_point));\n\n  cgal.method(\"has_smaller_signed_distance_to_line\", static_cast<bool(*)(const Line_2&,  const Point_2&, const Point_2&)>(&CGAL::has_smaller_signed_distance_to_line));\n  cgal.method(\"has_smaller_signed_distance_to_line\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&, const Point_2&)>(&CGAL::has_smaller_signed_distance_to_line));\n\n  cgal.method(\"has_smaller_signed_distance_to_plane\", static_cast<bool(*)(const Plane_3&,  const Point_3&, const Point_3&)>(&CGAL::has_smaller_signed_distance_to_plane));\n  cgal.method(\"has_smaller_signed_distance_to_plane\", static_cast<bool(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::has_smaller_signed_distance_to_plane));\n\n  INTERSECTION_2_SYM;\n  cgal.method(\"intersection\", &intersection<Point_2, Circle_2>);\n  cgal.method(\"intersection\", &intersection<Circle_2, Point_2>);\n  cgal.method(\"intersection\", &intersection<Point_2, Bbox_2>);\n  cgal.method(\"intersection\", &intersection<Bbox_2, Point_2>);\n\n  INTERSECTION_3_SYM;\n  cgal.method(\"intersection\", &intersection<Point_3, Tetrahedron_3>);\n  cgal.method(\"intersection\", &intersection<Point_3, Iso_cuboid_3>);\n  cgal.method(\"intersection\", &intersection<Point_3, Sphere_3>);\n  cgal.method(\"intersection\", &intersection<Point_3, Bbox_3>);\n  cgal.method(\"intersection\", &intersection<Tetrahedron_3, Point_3>);\n  cgal.method(\"intersection\", &intersection<Segment_3, Iso_cuboid_3>);\n  cgal.method(\"intersection\", &intersection<Segment_3, Bbox_3>);\n  cgal.method(\"intersection\", &intersection<Line_3, Iso_cuboid_3>);\n  cgal.method(\"intersection\", &intersection<Line_3, Bbox_3>);\n  cgal.method(\"intersection\", &intersection<Plane_3, Sphere_3>);\n  cgal.method(\"intersection\", &intersection<Triangle_3, Iso_cuboid_3>);\n  cgal.method(\"intersection\", &intersection<Ray_3, Iso_cuboid_3>);\n  cgal.method(\"intersection\", &intersection<Ray_3, Bbox_3>);\n  cgal.method(\"intersection\", &intersection<Iso_cuboid_3>);\n  cgal.method(\"intersection\", &intersection<Iso_cuboid_3, Point_3>);\n  cgal.method(\"intersection\", &intersection<Iso_cuboid_3, Segment_3>);\n  cgal.method(\"intersection\", &intersection<Iso_cuboid_3, Line_3>);\n  cgal.method(\"intersection\", &intersection<Iso_cuboid_3, Triangle_3>);\n  cgal.method(\"intersection\", &intersection<Iso_cuboid_3, Ray_3>);\n  cgal.method(\"intersection\", &intersection<Sphere_3>);\n  cgal.method(\"intersection\", &intersection<Sphere_3, Point_3>);\n  cgal.method(\"intersection\", &intersection<Sphere_3, Plane_3>);\n  cgal.method(\"intersection\", &intersection<Bbox_3, Point_3>);\n  cgal.method(\"intersection\", &intersection<Bbox_3, Segment_3>);\n  cgal.method(\"intersection\", &intersection<Bbox_3, Line_3>);\n  cgal.method(\"intersection\", &intersection<Bbox_3, Ray_3>);\n\n  cgal.method(\"l_infinity_distance\", static_cast<FT(*)(const Point_2&, const Point_2&)>(&CGAL::l_infinity_distance));\n  cgal.method(\"l_infinity_distance\", static_cast<FT(*)(const Point_3&, const Point_3&)>(&CGAL::l_infinity_distance));\n\n  cgal.method(\"left_turn\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::left_turn));\n\n  cgal.method(\"lexicographically_xy_larger\", static_cast<bool(*)(const Point_2&, const Point_2&)>(&CGAL::lexicographically_xy_larger));\n\n  cgal.method(\"lexicographically_xy_larger_or_equal\", static_cast<bool(*)(const Point_2&, const Point_2&)>(&CGAL::lexicographically_xy_larger_or_equal));\n\n  cgal.method(\"lexicographically_xy_smaller\", static_cast<bool(*)(const Point_2&, const Point_2&)>(&CGAL::lexicographically_xy_smaller));\n\n  cgal.method(\"lexicographically_xy_smaller_or_equal\", static_cast<bool(*)(const Point_2&, const Point_2&)>(&CGAL::lexicographically_xy_smaller_or_equal));\n\n  cgal.method(\"lexicographically_xyz_smaller\", static_cast<bool(*)(const Point_3&, const Point_3&)>(&CGAL::lexicographically_xyz_smaller));\n\n  cgal.method(\"lexicographically_xyz_smaller_or_equal\", static_cast<bool(*)(const Point_3&, const Point_3&)>(&CGAL::lexicographically_xyz_smaller_or_equal));\n\n  cgal.method(\"max_vertex\", static_cast<Point_2(*)(const Iso_rectangle_2&)>(&CGAL::max_vertex));\n  cgal.method(\"max_vertex\", static_cast<Point_3(*)(const Iso_cuboid_3&)>(&CGAL::max_vertex));\n\n  cgal.method(\"midpoint\", static_cast<Point_2(*)(const Point_2&, const Point_2&)>(&CGAL::midpoint));\n  cgal.method(\"midpoint\", static_cast<Point_3(*)(const Point_3&, const Point_3&)>(&CGAL::midpoint));\n\n  cgal.method(\"min_vertex\", static_cast<Point_2(*)(const Iso_rectangle_2&)>(&CGAL::min_vertex));\n  cgal.method(\"min_vertex\", static_cast<Point_3(*)(const Iso_cuboid_3&)>(&CGAL::min_vertex));\n\n  cgal.method(\"normal\", static_cast<Vector_3(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::normal));\n\n  cgal.method(\"orientation\", static_cast<CGAL::Orientation(*)(const Point_2&,  const Point_2&, const Point_2&)>(&CGAL::orientation));\n  cgal.method(\"orientation\", static_cast<CGAL::Orientation(*)(const Vector_2&, const Vector_2&)>(&CGAL::orientation));\n  cgal.method(\"orientation\", static_cast<CGAL::Orientation(*)(const Point_3&,  const Point_3&, const Point_3&, const Point_3&)>(&CGAL::orientation));\n  cgal.method(\"orientation\", static_cast<CGAL::Orientation(*)(const Vector_3&, const Vector_3&, const Vector_3&)>(&CGAL::orientation));\n\n  cgal.method(\"orthogonal_vector\", static_cast<Vector_3(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::orthogonal_vector));\n\n  cgal.method(\"parallel\", static_cast<bool(*)(const Line_2&, const Line_2&)>(&CGAL::parallel));\n  cgal.method(\"parallel\", static_cast<bool(*)(const Ray_2&, const Ray_2&)>(&CGAL::parallel));\n  cgal.method(\"parallel\", static_cast<bool(*)(const Segment_2&, const Segment_2&)>(&CGAL::parallel));\n  cgal.method(\"parallel\", static_cast<bool(*)(const Line_3&, const Line_3&)>(&CGAL::parallel));\n  cgal.method(\"parallel\", static_cast<bool(*)(const Plane_3&, const Plane_3&)>(&CGAL::parallel));\n  cgal.method(\"parallel\", static_cast<bool(*)(const Ray_3&, const Ray_3&)>(&CGAL::parallel));\n  cgal.method(\"parallel\", static_cast<bool(*)(const Segment_3&, const Segment_3&)>(&CGAL::parallel));\n\n  cgal.method(\"radical_plane\", static_cast<Plane_3(*)(const Sphere_3&, const Sphere_3&)>(&CGAL::radical_plane));\n\n  cgal.method(\"radical_line\", static_cast<Line_2(*)(const Circle_2&, const Circle_2&)>(&CGAL::radical_line));\n\n  cgal.method(\"rational_rotation_approximation\", static_cast<void(*)(const RT&, const RT&, RT&, RT&, RT&, const RT&, const RT&)>(&CGAL::rational_rotation_approximation));\n\n  cgal.method(\"right_turn\", static_cast<bool(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::right_turn));\n\n  cgal.method(\"scalar_product\", static_cast<FT(*)(const Vector_2&, const Vector_2&)>(&CGAL::scalar_product));\n  cgal.method(\"scalar_product\", static_cast<FT(*)(const Vector_3&, const Vector_3&)>(&CGAL::scalar_product));\n\n  cgal.method(\"side_of_bounded_circle\", static_cast<CGAL::Bounded_side(*)(const Point_2&, const Point_2&, const Point_2&, const Point_2&)>(&CGAL::side_of_bounded_circle));\n  cgal.method(\"side_of_bounded_circle\", static_cast<CGAL::Bounded_side(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::side_of_bounded_circle));\n\n  cgal.method(\"side_of_bounded_sphere\", static_cast<CGAL::Bounded_side(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::side_of_bounded_sphere));\n  cgal.method(\"side_of_bounded_sphere\", static_cast<CGAL::Bounded_side(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::side_of_bounded_sphere));\n  cgal.method(\"side_of_bounded_sphere\", static_cast<CGAL::Bounded_side(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::side_of_bounded_sphere));\n\n  cgal.method(\"side_of_oriented_circle\", static_cast<CGAL::Oriented_side(*)(const Point_2&, const Point_2&, const Point_2&, const Point_2&)>(&CGAL::side_of_oriented_circle));\n\n  cgal.method(\"side_of_oriented_sphere\", static_cast<CGAL::Oriented_side(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::side_of_oriented_sphere));\n\n  cgal.method(\"squared_area\", static_cast<FT(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::squared_area));\n\n  SQUARED_DISTANCE_2_ALL;\n\n  SQUARED_DISTANCE_3_SYM;\n  cgal.method(\"squared_distance\", &squared_distance<Point_3, Triangle_3>);\n  cgal.method(\"squared_distance\", &squared_distance<Triangle_3, Point_3>);\n\n  cgal.method(\"squared_radius\", static_cast<FT(*)(const Point_2&, const Point_2&, const Point_2&)>(&CGAL::squared_radius));\n  cgal.method(\"squared_radius\", static_cast<FT(*)(const Point_2&, const Point_2&)>(&CGAL::squared_radius));\n  cgal.method(\"squared_radius\", static_cast<FT(*)(const Point_2&)>(&CGAL::squared_radius));\n  cgal.method(\"squared_radius\", static_cast<FT(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::squared_radius));\n  cgal.method(\"squared_radius\", static_cast<FT(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::squared_radius));\n  cgal.method(\"squared_radius\", static_cast<FT(*)(const Point_3&, const Point_3&)>(&CGAL::squared_radius));\n  cgal.method(\"squared_radius\", static_cast<FT(*)(const Point_3&)>(&CGAL::squared_radius));\n\n  cgal.method(\"unit_normal\", static_cast<Vector_3(*)(const Point_3&, const Point_3&, const Point_3&)>(&CGAL::unit_normal));\n\n  cgal.method(\"volume\", static_cast<FT(*)(const Point_3&, const Point_3&, const Point_3&, const Point_3&)>(&CGAL::volume));\n\n  cgal.method(\"x_equal\", static_cast<bool(*)(const Point_2&, const Point_2&)>(&CGAL::x_equal));\n  cgal.method(\"x_equal\", static_cast<bool(*)(const Point_3&, const Point_3&)>(&CGAL::x_equal));\n  cgal.method(\"y_equal\", static_cast<bool(*)(const Point_2&, const Point_2&)>(&CGAL::y_equal));\n  cgal.method(\"y_equal\", static_cast<bool(*)(const Point_3&, const Point_3&)>(&CGAL::y_equal));\n  cgal.method(\"z_equal\", static_cast<bool(*)(const Point_3&, const Point_3&)>(&CGAL::z_equal));\n\n  cgal.method(\"do_overlap\", static_cast<bool(*)(const Bbox_2&, const Bbox_2&)>(&CGAL::do_overlap));\n  cgal.method(\"do_overlap\", static_cast<bool(*)(const Bbox_3&, const Bbox_3&)>(&CGAL::do_overlap));\n}\n\n} // jlcgal\n\n#undef DO_INTERSECT_2\n#undef DO_INTERSECT_2_SYM\n\n#undef INTERSECTION_2\n#undef INTERSECTION_2_SYM\n\n#undef DO_INTERSECT_3\n#undef DO_INTERSECT_3_ALL\n\n#undef INTERSECTION_3\n#undef INTERSECTION_3_SYM\n\n#undef SQUARED_DISTANCE_2\n#undef SQUARED_DISTANCE_2_ALL\n\n#undef SQUARED_DISTANCE_3\n#undef SQUARED_DISTANCE_3_SYM\n", "meta": {"hexsha": "0ff805b897bc895dfa5081c03dec7f959e570e4c", "size": 32038, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/global_kernel_functions/global_lk_functions.cpp", "max_stars_repo_name": "rgcv/libcgal-julia", "max_stars_repo_head_hexsha": "8d5bc5f13d3c9c6160cfff795d2a0bbe1e473d94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-01-22T14:06:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T11:29:18.000Z", "max_issues_repo_path": "src/global_kernel_functions/global_lk_functions.cpp", "max_issues_repo_name": "rgcv/libcgal-julia", "max_issues_repo_head_hexsha": "8d5bc5f13d3c9c6160cfff795d2a0bbe1e473d94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/global_kernel_functions/global_lk_functions.cpp", "max_forks_repo_name": "rgcv/libcgal-julia", "max_forks_repo_head_hexsha": "8d5bc5f13d3c9c6160cfff795d2a0bbe1e473d94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-02-16T13:56:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T17:17:30.000Z", "avg_line_length": 69.9519650655, "max_line_length": 240, "alphanum_fraction": 0.748829515, "num_tokens": 9557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2335112019012587}}
{"text": "/*\n * Copyright (c) 2011, Mattia Penati <mattia.penati@gmail.com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n *     * Redistributions of source code must retain the above copyright notice,\n *       this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright notice,\n *       this list of conditions and the following disclaimer in the documentation\n *       and/or other materials provided with the distribution.\n *     * Neither the name of the Politecnico di Milano nor the names of its\n *       contributors may be used to endorse or promote products derived from\n *       this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef AMA_TENSOR_DETAIL_COPY_HPP\n#define AMA_TENSOR_DETAIL_COPY_HPP 1\n\n#include <boost/mpl/bool.hpp>\n#include <boost/mpl/fold.hpp>\n#include <boost/mpl/modulus.hpp>\n#include <boost/mpl/pair.hpp>\n#include <boost/mpl/placeholders.hpp>\n#include <boost/mpl/push_back.hpp>\n#include <boost/mpl/range_c.hpp>\n#include <boost/mpl/size_t.hpp>\n#include <boost/mpl/vector/vector0_c.hpp>\n\nnamespace ama\n{\n  namespace tensor_\n  {\n\n    namespace mpl = ::boost::mpl;\n\n\n    /* given the order this struct create the first index */\n    template <typename O>\n    struct first:\n        mpl::fold<\n              mpl::range_c<size_t, 0, O::value>\n            , mpl::vector0_c<size_t>\n            , mpl::push_back< mpl::_1 , mpl::size_t<0> >\n            >::type { };\n\n     /* increment the multi-index */\n     template <\n           typename D /* the dimension */\n         , typename I /* the multi-index */\n         >\n     struct increment:\n         mpl::fold<\n               I\n             , mpl::pair<                  /* a pair with:           */\n                   mpl::vector0_c<size_t>  /*  - the multi-index     */\n                 , mpl::true_              /*  - an the carry of sum */\n                 >\n             , mpl::pair<\n                   mpl::push_back<\n                       mpl::first<mpl::_1>\n                     , mpl::modulus<\n                           mpl::if_<\n                               mpl::second<mpl::_1>\n                             , mpl::next<mpl::_2>\n                             , mpl::_2\n                             >\n                         , D\n                         >\n                     >\n                 , mpl::equal_to<\n                       mpl::if_<\n                           mpl::second<mpl::_1>\n                         , mpl::next<mpl::_2>\n                         , mpl::_2\n                         >\n                     , D\n                     >\n                 >\n             > { };\n\n\n     /* this struct implement the copy */\n     template <\n           typename D               /* the dimensione of tensor */\n         , typename O               /* the order of tensor */\n         , typename I = first<O>    /* the first multi-index */\n         , typename R = mpl::false_ /* this type is true for the last multi-index */\n         >\n     struct copy\n     {\n       template <typename SRC, typename DST>\n       static void apply(SRC const & src, DST & dst)\n       {\n         dst.template at<I>() = src.template at<I>();\n\n         /* increment the multi-index */\n         typedef typename increment<D,I>::type increment_type;\n\n         /* the first is the multi-index incremented */\n         typedef typename mpl::first<increment_type>::type i;\n         /* the second is a boolean flag toidentify the last multi-index */\n         typedef typename mpl::second<increment_type>::type r;\n\n         /* iterative call */\n         copy<D,O,i,r>::apply(src,dst);\n       }\n     };\n\n\n     /* partial specialization, end the iterative call */\n     template <typename D, typename O, typename I>\n     struct copy<D,O,I,mpl::true_>\n     {\n       template <typename SRC, typename DST>\n       static void apply(SRC const &, DST &) { }\n     };\n\n  }\n}\n\n#endif /* AMA_TENSOR_DETAIL_COPY_HPP */\n", "meta": {"hexsha": "cde5783932ae54ea0e8789e9ae1a324bea44e16d", "size": 4850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ama/tensor/detail/copy.hpp", "max_stars_repo_name": "mattiapenati/amanita", "max_stars_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ama/tensor/detail/copy.hpp", "max_issues_repo_name": "mattiapenati/amanita", "max_issues_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ama/tensor/detail/copy.hpp", "max_forks_repo_name": "mattiapenati/amanita", "max_forks_repo_head_hexsha": "c5c16d1f17e71151ce1d8e6972ddff6cec3c7305", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9259259259, "max_line_length": 84, "alphanum_fraction": 0.5659793814, "num_tokens": 1010, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203638047913, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.23319923131619263}}
{"text": "//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.\r\n\r\n//Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef UUID_5265FC7CA1C011DE9EBDFFA956D89593\r\n#define UUID_5265FC7CA1C011DE9EBDFFA956D89593\r\n\r\n#include <boost/qvm/inline.hpp>\r\n#include <boost/qvm/mat_traits.hpp>\r\n#include <boost/qvm/deduce_vec.hpp>\r\n#include <boost/qvm/assert.hpp>\r\n#include <boost/qvm/enable_if.hpp>\r\n\r\nnamespace\r\nboost\r\n    {\r\n    namespace\r\n    qvm\r\n        {\r\n        ////////////////////////////////////////////////\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int Col,class OriginalMatrix>\r\n            class\r\n            col_\r\n                {\r\n                col_( col_ const & );\r\n                col_ & operator=( col_ const & );\r\n                ~col_();\r\n\r\n                public:\r\n\r\n                template <class T>\r\n                BOOST_QVM_INLINE_TRIVIAL\r\n                col_ &\r\n                operator=( T const & x )\r\n                    {\r\n                    assign(*this,x);\r\n                    return *this;\r\n                    }\r\n\r\n                template <class R>\r\n                BOOST_QVM_INLINE_TRIVIAL\r\n                operator R() const\r\n                    {\r\n                    R r;\r\n                    assign(r,*this);\r\n                    return r;\r\n                    }\r\n                };\r\n            }\r\n\r\n        template <int Col,class OriginalMatrix>\r\n        struct\r\n        vec_traits< qvm_detail::col_<Col,OriginalMatrix> >\r\n            {\r\n            typedef qvm_detail::col_<Col,OriginalMatrix> this_vector;\r\n            typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\r\n            static int const dim=mat_traits<OriginalMatrix>::rows;\r\n            BOOST_QVM_STATIC_ASSERT(Col>=0);\r\n            BOOST_QVM_STATIC_ASSERT(Col<mat_traits<OriginalMatrix>::cols);\r\n\r\n            template <int I>\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type\r\n            read_element( this_vector const & x )\r\n                {\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\n                return mat_traits<OriginalMatrix>::template read_element<I,Col>(reinterpret_cast<OriginalMatrix const &>(x));\r\n                }\r\n\r\n            template <int I>\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type &\r\n            write_element( this_vector & x )\r\n                {\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\n                return mat_traits<OriginalMatrix>::template write_element<I,Col>(reinterpret_cast<OriginalMatrix &>(x));\r\n                }\r\n\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type\r\n            read_element_idx( int i, this_vector const & x )\r\n                {\r\n                BOOST_QVM_ASSERT(i>=0);\r\n                BOOST_QVM_ASSERT(i<dim);\r\n                return mat_traits<OriginalMatrix>::read_element_idx(i,Col,reinterpret_cast<OriginalMatrix const &>(x));\r\n                }\r\n\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type &\r\n            write_element_idx( int i, this_vector & x )\r\n                {\r\n                BOOST_QVM_ASSERT(i>=0);\r\n                BOOST_QVM_ASSERT(i<dim);\r\n                return mat_traits<OriginalMatrix>::write_element_idx(i,Col,reinterpret_cast<OriginalMatrix &>(x));\r\n                }\r\n            };\r\n\r\n        template <int Col,class OriginalMatrix,int D>\r\n        struct\r\n        deduce_vec<qvm_detail::col_<Col,OriginalMatrix>,D>\r\n            {\r\n            typedef vec<typename mat_traits<OriginalMatrix>::scalar_type,D> type;\r\n            };\r\n\r\n        template <int Col,class OriginalMatrix,int D>\r\n        struct\r\n        deduce_vec2<qvm_detail::col_<Col,OriginalMatrix>,qvm_detail::col_<Col,OriginalMatrix>,D>\r\n            {\r\n            typedef vec<typename mat_traits<OriginalMatrix>::scalar_type,D> type;\r\n            };\r\n\r\n        template <int Col,class A>\r\n        typename boost::enable_if_c<\r\n            is_mat<A>::value,\r\n            qvm_detail::col_<Col,A> const &>::type\r\n        BOOST_QVM_INLINE_TRIVIAL\r\n        col( A const & a )\r\n            {\r\n            return reinterpret_cast<typename qvm_detail::col_<Col,A> const &>(a);\r\n            }\r\n\r\n        template <int Col,class A>\r\n        typename boost::enable_if_c<\r\n            is_mat<A>::value,\r\n            qvm_detail::col_<Col,A> &>::type\r\n        BOOST_QVM_INLINE_TRIVIAL\r\n        col( A & a )\r\n            {\r\n            return reinterpret_cast<typename qvm_detail::col_<Col,A> &>(a);\r\n            }\r\n\r\n        ////////////////////////////////////////////////\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <int Row,class OriginalMatrix>\r\n            class\r\n            row_\r\n                {\r\n                row_( row_ const & );\r\n                row_ & operator=( row_ const & );\r\n                ~row_();\r\n\r\n                public:\r\n\r\n                template <class T>\r\n                BOOST_QVM_INLINE_TRIVIAL\r\n                row_ &\r\n                operator=( T const & x )\r\n                    {\r\n                    assign(*this,x);\r\n                    return *this;\r\n                    }\r\n\r\n                template <class R>\r\n                BOOST_QVM_INLINE_TRIVIAL\r\n                operator R() const\r\n                    {\r\n                    R r;\r\n                    assign(r,*this);\r\n                    return r;\r\n                    }\r\n                };\r\n            }\r\n\r\n        template <int Row,class OriginalMatrix>\r\n        struct\r\n        vec_traits< qvm_detail::row_<Row,OriginalMatrix> >\r\n            {\r\n            typedef qvm_detail::row_<Row,OriginalMatrix> this_vector;\r\n            typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\r\n            static int const dim=mat_traits<OriginalMatrix>::cols;\r\n            BOOST_QVM_STATIC_ASSERT(Row>=0);\r\n            BOOST_QVM_STATIC_ASSERT(Row<mat_traits<OriginalMatrix>::rows);\r\n\r\n            template <int I>\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type\r\n            read_element( this_vector const & x )\r\n                {\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\n                return mat_traits<OriginalMatrix>::template read_element<Row,I>(reinterpret_cast<OriginalMatrix const &>(x));\r\n                }\r\n\r\n            template <int I>\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type &\r\n            write_element( this_vector & x )\r\n                {\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\n                return mat_traits<OriginalMatrix>::template write_element<Row,I>(reinterpret_cast<OriginalMatrix &>(x));\r\n                }\r\n\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type\r\n            read_element_idx( int i, this_vector const & x )\r\n                {\r\n                BOOST_QVM_ASSERT(i>=0);\r\n                BOOST_QVM_ASSERT(i<dim);\r\n                return mat_traits<OriginalMatrix>::read_element_idx(Row,i,reinterpret_cast<OriginalMatrix const &>(x));\r\n                }\r\n\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type &\r\n            write_element_idx( int i, this_vector & x )\r\n                {\r\n                BOOST_QVM_ASSERT(i>=0);\r\n                BOOST_QVM_ASSERT(i<dim);\r\n                return mat_traits<OriginalMatrix>::write_element_idx(Row,i,reinterpret_cast<OriginalMatrix &>(x));\r\n                }\r\n            };\r\n\r\n        template <int Row,class OriginalMatrix,int D>\r\n        struct\r\n        deduce_vec<qvm_detail::row_<Row,OriginalMatrix>,D>\r\n            {\r\n            typedef vec<typename mat_traits<OriginalMatrix>::scalar_type,D> type;\r\n            };\r\n\r\n        template <int Row,class OriginalMatrix,int D>\r\n        struct\r\n        deduce_vec2<qvm_detail::row_<Row,OriginalMatrix>,qvm_detail::row_<Row,OriginalMatrix>,D>\r\n            {\r\n            typedef vec<typename mat_traits<OriginalMatrix>::scalar_type,D> type;\r\n            };\r\n\r\n        template <int Row,class A>\r\n        typename boost::enable_if_c<\r\n            is_mat<A>::value,\r\n            qvm_detail::row_<Row,A> const &>::type\r\n        BOOST_QVM_INLINE_TRIVIAL\r\n        row( A const & a )\r\n            {\r\n            return reinterpret_cast<typename qvm_detail::row_<Row,A> const &>(a);\r\n            }\r\n\r\n        template <int Row,class A>\r\n        typename boost::enable_if_c<\r\n            is_mat<A>::value,\r\n            qvm_detail::row_<Row,A> &>::type\r\n        BOOST_QVM_INLINE_TRIVIAL\r\n        row( A & a )\r\n            {\r\n            return reinterpret_cast<typename qvm_detail::row_<Row,A> &>(a);\r\n            }\r\n\r\n        ////////////////////////////////////////////////\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <class OriginalMatrix>\r\n            class\r\n            diag_\r\n                {\r\n                diag_( diag_ const & );\r\n                diag_ & operator=( diag_ const & );\r\n                ~diag_();\r\n\r\n                public:\r\n\r\n                template <class T>\r\n                BOOST_QVM_INLINE_TRIVIAL\r\n                diag_ &\r\n                operator=( T const & x )\r\n                    {\r\n                    assign(*this,x);\r\n                    return *this;\r\n                    }\r\n\r\n                template <class R>\r\n                BOOST_QVM_INLINE_TRIVIAL\r\n                operator R() const\r\n                    {\r\n                    R r;\r\n                    assign(r,*this);\r\n                    return r;\r\n                    }\r\n                };\r\n\r\n            template <int X,int Y,bool Which>\r\n            struct diag_bool_dispatch;\r\n\r\n            template <int X,int Y>\r\n            struct\r\n            diag_bool_dispatch<X,Y,true>\r\n                {\r\n                static int const value=X;\r\n                };\r\n\r\n            template <int X,int Y>\r\n            struct\r\n            diag_bool_dispatch<X,Y,false>\r\n                {\r\n                static int const value=Y;\r\n                };\r\n            }\r\n\r\n        template <class OriginalMatrix>\r\n        struct\r\n        vec_traits< qvm_detail::diag_<OriginalMatrix> >\r\n            {\r\n            typedef qvm_detail::diag_<OriginalMatrix> this_vector;\r\n            typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\r\n            static int const dim=qvm_detail::diag_bool_dispatch<\r\n                    mat_traits<OriginalMatrix>::rows,\r\n                    mat_traits<OriginalMatrix>::cols,\r\n                    mat_traits<OriginalMatrix>::rows<=mat_traits<OriginalMatrix>::cols>::value;\r\n\r\n            template <int I>\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type\r\n            read_element( this_vector const & x )\r\n                {\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\n                return mat_traits<OriginalMatrix>::template read_element<I,I>(reinterpret_cast<OriginalMatrix const &>(x));\r\n                }\r\n\r\n            template <int I>\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type &\r\n            write_element( this_vector & x )\r\n                {\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\n                return mat_traits<OriginalMatrix>::template write_element<I,I>(reinterpret_cast<OriginalMatrix &>(x));\r\n                }\r\n\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type\r\n            read_element_idx( int i, this_vector const & x )\r\n                {\r\n                BOOST_QVM_ASSERT(i>=0);\r\n                BOOST_QVM_ASSERT(i<dim);\r\n                return mat_traits<OriginalMatrix>::read_element_idx(i,i,reinterpret_cast<OriginalMatrix const &>(x));\r\n                }\r\n\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type &\r\n            write_element_idx( int i, this_vector & x )\r\n                {\r\n                BOOST_QVM_ASSERT(i>=0);\r\n                BOOST_QVM_ASSERT(i<dim);\r\n                return mat_traits<OriginalMatrix>::write_element_idx(i,i,reinterpret_cast<OriginalMatrix &>(x));\r\n                }\r\n            };\r\n\r\n        template <class OriginalMatrix,int D>\r\n        struct\r\n        deduce_vec<qvm_detail::diag_<OriginalMatrix>,D>\r\n            {\r\n            typedef vec<typename mat_traits<OriginalMatrix>::scalar_type,D> type;\r\n            };\r\n\r\n        template <class OriginalMatrix,int D>\r\n        struct\r\n        deduce_vec2<qvm_detail::diag_<OriginalMatrix>,qvm_detail::diag_<OriginalMatrix>,D>\r\n            {\r\n            typedef vec<typename mat_traits<OriginalMatrix>::scalar_type,D> type;\r\n            };\r\n\r\n        template <class A>\r\n        typename boost::enable_if_c<\r\n            is_mat<A>::value,\r\n            qvm_detail::diag_<A> const &>::type\r\n        BOOST_QVM_INLINE_TRIVIAL\r\n        diag( A const & a )\r\n            {\r\n            return reinterpret_cast<typename qvm_detail::diag_<A> const &>(a);\r\n            }\r\n\r\n        template <class A>\r\n        typename boost::enable_if_c<\r\n            is_mat<A>::value,\r\n            qvm_detail::diag_<A> &>::type\r\n        BOOST_QVM_INLINE_TRIVIAL\r\n        diag( A & a )\r\n            {\r\n            return reinterpret_cast<typename qvm_detail::diag_<A> &>(a);\r\n            }\r\n\r\n        ////////////////////////////////////////////////\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <class OriginalMatrix>\r\n            class\r\n            translation_\r\n                {\r\n                translation_( translation_ const & );\r\n                ~translation_();\r\n\r\n                public:\r\n\r\n                translation_ &\r\n                operator=( translation_ const & x )\r\n                    {\r\n                    assign(*this,x);\r\n                    return *this;\r\n                    }\r\n\r\n                template <class T>\r\n                BOOST_QVM_INLINE_TRIVIAL\r\n                translation_ &\r\n                operator=( T const & x )\r\n                    {\r\n                    assign(*this,x);\r\n                    return *this;\r\n                    }\r\n\r\n                template <class R>\r\n                BOOST_QVM_INLINE_TRIVIAL\r\n                operator R() const\r\n                    {\r\n                    R r;\r\n                    assign(r,*this);\r\n                    return r;\r\n                    }\r\n                };\r\n            }\r\n\r\n        template <class OriginalMatrix>\r\n        struct\r\n        vec_traits< qvm_detail::translation_<OriginalMatrix> >\r\n            {\r\n            typedef qvm_detail::translation_<OriginalMatrix> this_vector;\r\n            typedef typename mat_traits<OriginalMatrix>::scalar_type scalar_type;\r\n            static int const dim=mat_traits<OriginalMatrix>::rows-1;\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<OriginalMatrix>::rows==mat_traits<OriginalMatrix>::cols);\r\n            BOOST_QVM_STATIC_ASSERT(mat_traits<OriginalMatrix>::rows>=3);\r\n\r\n            template <int I>\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type\r\n            read_element( this_vector const & x )\r\n                {\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\n                return mat_traits<OriginalMatrix>::template read_element<I,dim>(reinterpret_cast<OriginalMatrix const &>(x));\r\n                }\r\n\r\n            template <int I>\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type &\r\n            write_element( this_vector & x )\r\n                {\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\n                return mat_traits<OriginalMatrix>::template write_element<I,dim>(reinterpret_cast<OriginalMatrix &>(x));\r\n                }\r\n\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type\r\n            read_element_idx( int i, this_vector const & x )\r\n                {\r\n                BOOST_QVM_ASSERT(i>=0);\r\n                BOOST_QVM_ASSERT(i<dim);\r\n                return mat_traits<OriginalMatrix>::read_element_idx(i,dim,reinterpret_cast<OriginalMatrix const &>(x));\r\n                }\r\n\r\n            static\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            scalar_type &\r\n            write_element_idx( int i, this_vector & x )\r\n                {\r\n                BOOST_QVM_ASSERT(i>=0);\r\n                BOOST_QVM_ASSERT(i<dim);\r\n                return mat_traits<OriginalMatrix>::write_element_idx(i,dim,reinterpret_cast<OriginalMatrix &>(x));\r\n                }\r\n            };\r\n\r\n        template <class OriginalMatrix,int D>\r\n        struct\r\n        deduce_vec<qvm_detail::translation_<OriginalMatrix>,D>\r\n            {\r\n            typedef vec<typename mat_traits<OriginalMatrix>::scalar_type,D> type;\r\n            };\r\n\r\n        template <class OriginalMatrix,int D>\r\n        struct\r\n        deduce_vec2<qvm_detail::translation_<OriginalMatrix>,qvm_detail::translation_<OriginalMatrix>,D>\r\n            {\r\n            typedef vec<typename mat_traits<OriginalMatrix>::scalar_type,D> type;\r\n            };\r\n\r\n        template <class A>\r\n        typename boost::enable_if_c<\r\n            is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3,\r\n            qvm_detail::translation_<A> const &>::type\r\n        BOOST_QVM_INLINE_TRIVIAL\r\n        translation( A const & a )\r\n            {\r\n            return reinterpret_cast<typename qvm_detail::translation_<A> const &>(a);\r\n            }\r\n\r\n        template <class A>\r\n        typename boost::enable_if_c<\r\n            is_mat<A>::value && mat_traits<A>::rows==mat_traits<A>::cols && mat_traits<A>::rows>=3,\r\n            qvm_detail::translation_<A> &>::type\r\n        BOOST_QVM_INLINE_TRIVIAL\r\n        translation( A & a )\r\n            {\r\n            return reinterpret_cast<typename qvm_detail::translation_<A> &>(a);\r\n            }\r\n\r\n        ////////////////////////////////////////////////\r\n        }\r\n    }\r\n\r\n#endif\r\n", "meta": {"hexsha": "81a2527d218701c5f0f1c7b3486a910d0e791dc3", "size": 18433, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/qvm/map_mat_vec.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/qvm/map_mat_vec.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/qvm/map_mat_vec.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 34.2620817844, "max_line_length": 126, "alphanum_fraction": 0.4911300385, "num_tokens": 3560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2329014738176742}}
{"text": " /*\r\n *  Copyright 2007-2015 The OpenMx Project\r\n *\r\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  you may not use this file except in compliance with the License.\r\n *  You may obtain a copy of the License at\r\n *\r\n *       http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n *   Unless required by applicable law or agreed to in writing, software\r\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  See the License for the specific language governing permissions and\r\n *  limitations under the License.\r\n */\r\n \r\n#include \"omxExpectation.h\"\r\n#include \"omxFitFunction.h\"\r\n#include \"omxDefines.h\"\r\n#include \"omxGREMLExpectation.h\"\r\n#include <Eigen/Core>\r\n#include <Eigen/Cholesky>\r\n#include <Eigen/Dense>\r\n \r\nvoid omxInitGREMLExpectation(omxExpectation* ox){\r\n  \r\n  SEXP rObj = ox->rObj;\r\n  SEXP Rmtx, casesToDrop, yXcolnames;\r\n  int i=0;\r\n  omxState* currentState = ox->currentState;\r\n  \r\n  if(OMX_DEBUG) { mxLog(\"Initializing GREML expectation.\"); }\r\n  \r\n  //omxGREMLExpectation *oge = (omxGREMLExpectation*) R_alloc(1, sizeof(omxGREMLExpectation));\r\n  omxGREMLExpectation *oge = new omxGREMLExpectation;\r\n  \r\n  /* Set Expectation Calls and Structures */\r\n  ox->computeFun = omxComputeGREMLExpectation;\r\n\tox->destructFun = omxDestroyGREMLExpectation;\r\n\tox->componentFun = omxGetGREMLExpectationComponent;\r\n\tox->populateAttrFun = omxPopulateGREMLAttributes;\r\n\tox->argStruct = (void*) oge;\r\n  \r\n  \r\n    /* Set up expectation structures */\r\n  //y:\r\n  oge->y = new omxData();\r\n  {ScopedProtect p1(Rmtx, R_do_slot(rObj, Rf_install(\"y\")));\r\n\t  oge->y->newDataStatic(currentState, Rmtx);\r\n  }\r\n  //V:\r\n\tif(OMX_DEBUG) { mxLog(\"Processing V.\"); }\r\n\toge->cov = omxNewMatrixFromSlot(rObj, currentState, \"V\");\r\n  if( oge->cov->rows != oge->cov->cols ){\r\n    Rf_error(\"'V' matrix is not square\");\r\n  }\r\n  //X:\r\n\tif(OMX_DEBUG) { mxLog(\"Processing X.\"); }\r\n  {ScopedProtect p1(Rmtx, R_do_slot(rObj, Rf_install(\"X\")));\r\n\toge->X = omxNewMatrixFromRPrimitive(Rmtx, currentState, 0, 0);\r\n  }\r\n  //Eigy (local) will have however many rows and 1 column:\r\n  Eigen::Map< Eigen::MatrixXd > Eigy(omxMatrixDataColumnMajor(oge->y->dataMat), oge->y->dataMat->cols, 1);\r\n  if(oge->X->rows != Eigy.rows()){Rf_error(\"'X' and 'y' matrices have different numbers of rows\");}\r\n  //means:\r\n  oge->means = omxInitMatrix(Eigy.rows(), 1, 1, currentState);\r\n  //logdetV_om:\r\n  oge->logdetV_om = omxInitMatrix(1, 1, 1, currentState);\r\n  oge->logdetV_om->data[0] = 0;\r\n  //cholV_fail_om:\r\n  oge->cholV_fail_om = omxInitMatrix(1, 1, 1, currentState);\r\n  oge->cholV_fail_om->data[0] = 0;\r\n  //quadXinv:\r\n  oge->quadXinv.setZero(oge->X->cols, oge->X->cols);\r\n\r\n\r\n  //Deal with missing data:\r\n  int* casesToDrop_intptr;\r\n  oge->numcases2drop = 0;\r\n  {\r\n  ScopedProtect p1(casesToDrop, R_do_slot(rObj, Rf_install(\"casesToDrop\")));\r\n  if(Rf_length(casesToDrop)){\r\n    if(OMX_DEBUG) { mxLog(\"Preparing GREML expectation to handle missing data.\"); }\r\n    oge->numcases2drop = Rf_length(casesToDrop);\r\n    casesToDrop_intptr = INTEGER(casesToDrop);\r\n    oge->dropcase.assign(oge->cov->rows,0);\r\n    for(i=0; i < Rf_length(casesToDrop); i++){\r\n      if(casesToDrop_intptr[i] >= oge->cov->rows){\r\n        Rf_warning(\"casesToDrop vector in GREML expectation contains indices greater than the number of datapoints\");\r\n        oge->numcases2drop--; \r\n      }\r\n      //Need to subtract 1 from the index because R begins array indexing with 1, not 0:\r\n      else{oge->dropcase[casesToDrop_intptr[i]-1] = 1;}\r\n  }}\r\n  }\r\n  if(Eigy.rows() != oge->cov->rows - oge->numcases2drop){\r\n    Rf_error(\"y and V matrices do not have equal numbers of rows\");\r\n  }\r\n  \r\n  \r\n  //column names of y and X:\r\n  {\r\n  ScopedProtect p1(yXcolnames, R_do_slot(rObj, Rf_install(\"yXcolnames\")));\r\n  oge->yXcolnames.resize(Rf_length(yXcolnames));\r\n  for(i=0; i < Rf_length(yXcolnames); i++){\r\n    SEXP elem;\r\n    {ScopedProtect p2(elem, STRING_ELT(yXcolnames, i));\r\n  \toge->yXcolnames[i] = CHAR(elem);}\r\n  }\r\n  }\r\n  \r\n  //Initially compute everything involved in computing means:\r\n  oge->alwaysComputeMeans = 1;\r\n  oge->cholquadX_fail = 0;\r\n  EigenMatrixAdaptor EigX(oge->X);\r\n  Eigen::Map< Eigen::MatrixXd > yhat(omxMatrixDataColumnMajor(oge->means), oge->means->rows, oge->means->cols);\r\n  Eigen::MatrixXd EigV(Eigy.rows(), Eigy.rows());\r\n  Eigen::MatrixXd quadX(oge->X->cols, oge->X->cols);\r\n  //Apparently you need to initialize a matrix's elements before you try to write to its lower triangle:\r\n  quadX.setZero(oge->X->cols, oge->X->cols);\r\n  Eigen::LLT< Eigen::MatrixXd > cholV(Eigy.rows());\r\n  Eigen::LLT< Eigen::MatrixXd > cholquadX(oge->X->cols);\r\n  if( oge->numcases2drop ){\r\n    dropCasesAndEigenize(oge->cov, EigV, oge->numcases2drop, oge->dropcase, 1);\r\n  }\r\n  else{EigV = Eigen::Map< Eigen::MatrixXd >(omxMatrixDataColumnMajor(oge->cov), oge->cov->rows, oge->cov->cols);}\r\n  //invcov:\r\n  oge->invcov = omxInitMatrix(EigV.rows(), EigV.cols(), 1, currentState);\r\n  Eigen::Map< Eigen::MatrixXd > Vinv(omxMatrixDataColumnMajor(oge->invcov), EigV.rows(), EigV.cols());\r\n  cholV.compute(EigV.selfadjointView<Eigen::Lower>());\r\n  if(cholV.info() != Eigen::Success){\r\n    Rf_error(\"Expected covariance matrix is non-positive-definite at initial values\");\r\n  }\r\n  oge->cholV_vectorD = (( Eigen::MatrixXd )(cholV.matrixL())).diagonal();\r\n  for(i=0; i < oge->X->rows; i++){\r\n    oge->logdetV_om->data[0] += log(oge->cholV_vectorD[i]);\r\n  }\r\n  oge->logdetV_om->data[0] *= 2;\r\n  Vinv = cholV.solve(Eigen::MatrixXd::Identity( EigV.rows(), EigV.cols() )); //<-- V inverse\r\n  oge->XtVinv = EigX.transpose() * Vinv;\r\n  quadX.triangularView<Eigen::Lower>() = oge->XtVinv * EigX;\r\n  cholquadX.compute(quadX.selfadjointView<Eigen::Lower>());\r\n  if(cholquadX.info() != Eigen::Success){\r\n    Rf_error(\"Cholesky factorization failed at initial values; possibly, the matrix of covariates is rank-deficient\");\r\n  }\r\n  oge->cholquadX_vectorD = (( Eigen::MatrixXd )(cholquadX.matrixL())).diagonal();\r\n  oge->quadXinv = ( cholquadX.solve(Eigen::MatrixXd::Identity(oge->X->cols, oge->X->cols)) ).triangularView<Eigen::Lower>();\r\n  yhat = EigX * oge->quadXinv.selfadjointView<Eigen::Lower>() * oge->XtVinv * Eigy;\r\n  \r\n  /*Prepare y as the data that the FIML fitfunction will use:*/\r\n  oge->data2 = ox->data;\r\n  ox->data = oge->y;\r\n  if (oge->data2->hasDefinitionVariables()) {\r\n\t  Rf_error(\"definition variables are incompatible (and unnecessary) with GREML expectation\");\r\n  }\r\n}\r\n\r\n\r\nvoid omxComputeGREMLExpectation(omxExpectation* ox, const char *, const char *) {\r\n  omxGREMLExpectation* oge = (omxGREMLExpectation*) (ox->argStruct);\r\n\tomxRecompute(oge->cov, NULL);\r\n  int i=0;\r\n  oge->cholV_fail_om->data[0] = 0;\r\n  oge->cholquadX_fail = 0;\r\n  oge->logdetV_om->data[0] = 0;\r\n  \r\n  EigenMatrixAdaptor EigX(oge->X);\r\n  Eigen::Map< Eigen::MatrixXd > Eigy(omxMatrixDataColumnMajor(oge->y->dataMat), oge->y->dataMat->cols, 1);\r\n  Eigen::Map< Eigen::MatrixXd > yhat(omxMatrixDataColumnMajor(oge->means), oge->means->rows, oge->means->cols);\r\n  Eigen::MatrixXd EigV(Eigy.rows(), Eigy.rows());\r\n  Eigen::Map< Eigen::MatrixXd > Vinv(omxMatrixDataColumnMajor(oge->invcov), oge->invcov->rows, oge->invcov->cols);\r\n  Eigen::MatrixXd quadX(oge->X->cols, oge->X->cols);\r\n  quadX.setZero(oge->X->cols, oge->X->cols);\r\n  Eigen::LLT< Eigen::MatrixXd > cholV(oge->y->dataMat->rows);\r\n  Eigen::LLT< Eigen::MatrixXd > cholquadX(oge->X->cols);\r\n  if( oge->numcases2drop ){\r\n    dropCasesAndEigenize(oge->cov, EigV, oge->numcases2drop, oge->dropcase, 1);\r\n  }\r\n  else{EigV = Eigen::Map< Eigen::MatrixXd >(omxMatrixDataColumnMajor(oge->cov), oge->cov->rows, oge->cov->cols);}\r\n  cholV.compute(EigV.selfadjointView<Eigen::Lower>());\r\n  if(cholV.info() != Eigen::Success){\r\n    oge->cholV_fail_om->data[0] = 1;\r\n    return;\r\n  }\r\n  oge->cholV_vectorD = (( Eigen::MatrixXd )(cholV.matrixL())).diagonal();\r\n  for(i=0; i < oge->X->rows; i++){\r\n    oge->logdetV_om->data[0] += log(oge->cholV_vectorD[i]);\r\n  }\r\n  oge->logdetV_om->data[0] *= 2;\r\n  if(oge->alwaysComputeMeans){\r\n  \tVinv = cholV.solve(Eigen::MatrixXd::Identity( EigV.rows(), EigV.cols() )); //<-- V inverse\r\n  \toge->XtVinv = EigX.transpose() * Vinv;\r\n  }\r\n  /*alwaysComputeMeans is initialized as true, and the only way it can be set to false is by the GREML \r\n  fitfunction.  If its false, that means that the GREML fitfunction is being used, and it knows how to handle\r\n  a \"half-full\" Vinv.*/\r\n  else{\r\n  \t//V inverse:\r\n  \tVinv.triangularView<Eigen::Lower>() = ( cholV.solve(Eigen::MatrixXd::Identity( EigV.rows(), EigV.cols() )) ).triangularView<Eigen::Lower>();\r\n  \toge->XtVinv = EigX.transpose() * Vinv.selfadjointView<Eigen::Lower>();\r\n  }\r\n  quadX.triangularView<Eigen::Lower>() = oge->XtVinv * EigX;\r\n  cholquadX.compute(quadX.selfadjointView<Eigen::Lower>());\r\n  if(cholquadX.info() != Eigen::Success){ \r\n    oge->cholquadX_fail = 1;\r\n    return;\r\n  }\r\n  oge->cholquadX_vectorD = (( Eigen::MatrixXd )(cholquadX.matrixL())).diagonal();\r\n  oge->quadXinv = ( cholquadX.solve(Eigen::MatrixXd::Identity(oge->X->cols, oge->X->cols)) ).triangularView<Eigen::Lower>();\r\n  if(oge->alwaysComputeMeans){\r\n    yhat = EigX * oge->quadXinv.selfadjointView<Eigen::Lower>() * oge->XtVinv * Eigy;\r\n  }\r\n}\r\n\r\n\r\nvoid omxDestroyGREMLExpectation(omxExpectation* ox) {\r\n\tif(OMX_DEBUG) { mxLog(\"Destroying GREML Expectation.\"); }\r\n  omxGREMLExpectation* argStruct = (omxGREMLExpectation*)(ox->argStruct);\r\n  ox->data = argStruct->data2;\r\n  omxFreeMatrix(argStruct->means);\r\n  omxFreeMatrix(argStruct->invcov);\r\n  omxFreeMatrix(argStruct->logdetV_om);\r\n  omxFreeMatrix(argStruct->cholV_fail_om);\r\n}\r\n\r\n\r\n/*Possible TODO: it will require some additional computation, but it is probably best to calculate the final\r\nregression coefficients using QR, which is more numerically stable*/\r\nvoid omxPopulateGREMLAttributes(omxExpectation *ox, SEXP algebra) {\r\n  if(OMX_DEBUG) { mxLog(\"Populating GREML expectation attributes.\"); }\r\n\r\n  omxGREMLExpectation* oge = (omxGREMLExpectation*) (ox->argStruct);\r\n  \r\n  Rf_setAttrib(algebra, Rf_install(\"numStats\"), Rf_ScalarReal(oge->y->dataMat->cols));\r\n  Rf_setAttrib(algebra, Rf_install(\"numFixEff\"), Rf_ScalarInteger(oge->X->cols));\r\n  \r\n  Eigen::Map< Eigen::MatrixXd > Eigy(omxMatrixDataColumnMajor(oge->y->dataMat), oge->y->dataMat->cols, 1);\r\n  SEXP b_ext, bcov_ext, yXcolnames;\r\n  oge->quadXinv = oge->quadXinv.selfadjointView<Eigen::Lower>();\r\n  Eigen::MatrixXd GREML_b = oge->quadXinv * oge->XtVinv * Eigy;\r\n  \r\n  {\r\n  ScopedProtect p1(b_ext, Rf_allocMatrix(REALSXP, GREML_b.rows(), 1));\r\n  for(int row = 0; row < GREML_b.rows(); row++){\r\n    REAL(b_ext)[0 * GREML_b.rows() + row] = GREML_b(row,0);\r\n  }\r\n  Rf_setAttrib(algebra, Rf_install(\"b\"), b_ext);\r\n  }\r\n  \r\n  {\r\n  ScopedProtect p1(bcov_ext, Rf_allocMatrix(REALSXP, oge->quadXinv.rows(), \r\n  \toge->quadXinv.cols()));\r\n  for(int row = 0; row < oge->quadXinv.rows(); row++){\r\n    for(int col = 0; col < oge->quadXinv.cols(); col++){\r\n      REAL(bcov_ext)[col * oge->quadXinv.rows() + row] = oge->quadXinv(row,col);\r\n  }}  \r\n  Rf_setAttrib(algebra, Rf_install(\"bcov\"), bcov_ext);\r\n  }\r\n  \r\n  //yXcolnames:\r\n  {\r\n  ScopedProtect p1(yXcolnames, Rf_allocVector(STRSXP, oge->yXcolnames.size()));\r\n  for(int i=0; i < (int)(oge->yXcolnames.size()); i++){\r\n    SET_STRING_ELT(yXcolnames, i, Rf_mkChar(oge->yXcolnames[i]));\r\n  }\r\n  Rf_setAttrib(algebra, Rf_install(\"yXcolnames\"), yXcolnames);\r\n  }\r\n  \r\n}\r\n\r\nomxMatrix* omxGetGREMLExpectationComponent(omxExpectation* ox, omxFitFunction* off, const char* component){\r\n/* Return appropriate parts of Expectation to the Fit Function */\r\n  if(OMX_DEBUG) { mxLog(\"GREML expectation: %s requested--\", component); }\r\n\r\n\tomxGREMLExpectation* oge = (omxGREMLExpectation*)(ox->argStruct);\r\n\tomxMatrix* retval = NULL;\r\n\r\n\t\r\n  if(strEQ(\"y\", component)) {\r\n    retval = oge->y->dataMat;\r\n\t}\r\n  else if(strEQ(\"invcov\", component)) {\r\n    retval = oge->invcov;\r\n  }\r\n  else if(strEQ(\"means\", component)) {\r\n  \tretval = oge->means;\r\n  }\r\n  else if(strEQ(\"cholV_fail_om\", component)){\r\n    retval = oge->cholV_fail_om;\r\n  }\r\n  else if(strEQ(\"logdetV_om\", component)){\r\n    retval = oge->logdetV_om;\r\n  }\r\n  else if(strEQ(\"cov\", component)) {\r\n\t\tretval = oge->cov;\r\n\t} \r\n  else if(strEQ(\"X\", component)) {\r\n\t\tretval = oge->X;\r\n\t} \r\n  \r\n\tif (retval) omxRecompute(retval, NULL);\r\n\t\r\n\treturn retval;\r\n}\r\n\r\n\r\n\r\nstatic double omxAliasedMatrixElement(omxMatrix *om, int row, int col)\r\n{\r\n  int index = 0;\r\n  if(row >= om->originalRows || col >= om->originalCols) {\r\n  \tchar *errstr = (char*) calloc(250, sizeof(char));\r\n\t\tsprintf(errstr, \"Requested improper value (%d, %d) from (%d, %d) matrix.\", \r\n\t\t\trow + 1, col + 1, om->originalRows, om->originalCols);\r\n\t\tRf_error(errstr);\r\n\t\tfree(errstr);  // TODO not reached\r\n        return (NA_REAL);\r\n\t}\r\n\tif(om->colMajor) {\r\n\t\tindex = col * om->originalRows + row;\r\n\t} else {\r\n\t\tindex = row * om->originalCols + col;\r\n\t}\r\n\treturn om->data[index];\r\n}\r\n\r\n\r\n\r\nvoid dropCasesAndEigenize(omxMatrix* om, Eigen::MatrixXd &em, int num2drop, std::vector< int > todrop,\r\n\tint symmetric){\r\n  \r\n  if(OMX_DEBUG) { mxLog(\"Trimming out cases with missing data...\"); }\r\n  \r\n  if(num2drop < 1){ return; }\r\n  \r\n  omxEnsureColumnMajor(om);\r\n  \r\n  if(om->algebra == NULL){ //i.e., if omxMatrix is from a frontend MxMatrix\r\n  \r\n    em.setZero(om->rows - num2drop, om->cols - num2drop);\r\n  \r\n    int nextCol = 0;\r\n    int nextRow = 0;\r\n    \r\n    for(int j = 0; j < om->cols; j++) {\r\n  \t  if(todrop[j]) continue;\r\n  \t\tnextRow = (symmetric ? nextCol : 0);\r\n  \t\tfor(int k = (symmetric ? j : 0); k < om->rows; k++) {\r\n  \t\t\tif(todrop[k]) continue;\r\n  \t\t\tem(nextRow,nextCol) = omxAliasedMatrixElement(om, k, j);\r\n  \t\t\tnextRow++;\r\n  \t\t}\r\n  \t\tnextCol++;\r\n  \t}\r\n  }\r\n  else{ /*If the omxMatrix is from an algebra, then copying is not necessary; it can be resized directly\r\n  and Eigen-mapped, since the algebra will be recalculated back to its original dimensions anyhow.*/\r\n    if(om->originalRows == 0 || om->originalCols == 0) Rf_error(\"Not allocated\");\r\n    if (om->rows != om->originalRows || om->cols != om->originalCols) {\r\n      // Feasible, but the code is currently not robust to this case\r\n      Rf_error(\"Can only omxRemoveRowsAndColumns once\");\r\n    }\r\n    \r\n    int oldRows = om->originalRows;\r\n    int oldCols = om->originalCols;\r\n    \r\n    int nextCol = 0;\r\n    int nextRow = 0;\r\n    \r\n    om->rows = oldRows - num2drop;\r\n    om->cols = oldCols - num2drop;\r\n    \r\n    for(int j = 0; j < oldCols; j++) {\r\n      if(todrop[j]) continue;\r\n      nextRow = (symmetric ? nextCol : 0);\r\n      for(int k = (symmetric ? j : 0); k < oldRows; k++) {\r\n        if(todrop[k]) continue;\r\n        omxSetMatrixElement(om, nextRow, nextCol, omxAliasedMatrixElement(om, k, j));\r\n        nextRow++;\r\n      }\r\n      nextCol++;\r\n    }\r\n    em = Eigen::Map< Eigen::MatrixXd >(om->data, om->rows, om->cols);\r\n    omxMarkDirty(om); //<--Need to mark it dirty so that it gets recalculated back to original dimensions.\r\n  }\r\n  if(OMX_DEBUG) { mxLog(\"Finished trimming out cases with missing data...\"); }\r\n}\r\n", "meta": {"hexsha": "6eef6f4fbb2dec1558f0ef004bce5ecf096425c8", "size": 15080, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/omxGREMLExpectation.cpp", "max_stars_repo_name": "JuKa87/OpenMx", "max_stars_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/omxGREMLExpectation.cpp", "max_issues_repo_name": "JuKa87/OpenMx", "max_issues_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/omxGREMLExpectation.cpp", "max_forks_repo_name": "JuKa87/OpenMx", "max_forks_repo_head_hexsha": "f055df183ca433abd194e494a433142825666128", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.8659793814, "max_line_length": 144, "alphanum_fraction": 0.6561007958, "num_tokens": 4810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2329014738176742}}
{"text": "#include <fstream>\n#include <Eigen/Core>\n#include <igl/point_mesh_squared_distance.h>\n#include <queue>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <algorithm>\n#include <omp.h>\n#include <glm/glm.hpp>\n\nEigen::MatrixXf V;\nEigen::MatrixXi F;\nEigen::MatrixXf FN;\nEigen::MatrixXf FV;\n\nint* E2E;\nglm::vec3 *pts1, *pts2;\nstd::pair<glm::vec3, glm::vec3> *pframes;\nint *face_indices1, *face_indices2, *group_indices;\nglm::vec2* group_tex;\n\nint* find_queue;\nglm::vec3 *ux_queue, *uy_queue;\nglm::vec2 *coord_queue;\nint* neighbor_hash;\nglm::vec3 *ux_hash, *uy_hash;\nglm::vec2 *coord_hash;\n\nglm::vec3 *cudaV;\nglm::ivec3 *cudaF;\nglm::vec3 *cudaFV;\nglm::vec3 *cudaFN;\nint *cudaE2E;\nint num_v, num_f;\n\nglm::vec3 *p8192, *p1024, *p256, *p64, *p16;\nglm::ivec3 *i1024, *i256, *i64, *i16;\n\nFILE* fps;\n\nextern \"C\" {\n\n\ndouble GetTickCount(void) \n{\n  struct timespec now;\n  if (clock_gettime(CLOCK_MONOTONIC, &now))\n    return 0;\n  return now.tv_sec * 1000.0 + now.tv_nsec / 1000000.0;\n}\n\nvoid ReadArray(void* indatav, const char* filename, int size, int stride) {\n\tFILE* fp = fopen(filename, \"rb\");\n\tfread(indatav, stride, size, fp);\n\tfclose(fp);\n}\n\nvoid InitializeE2E(void* vertices, void* faces, int num_v, int num_f, void* pE2E) {\n\tint* iE2E = (int*)pE2E;\n\tV = Eigen::Map<Eigen::MatrixXf>((float*)vertices, 3, num_v);\n\tF = Eigen::Map<Eigen::MatrixXi>((int*)faces, 3, num_f);\n\t//E2E = Eigen::VectorXi(num_f * 3);\n\tstd::map<std::pair<int, int>, int > dedgeid;\n\tfor (int i = 0; i < num_f; ++i) {\n\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\tiE2E[i * 3 + j] = -1;\n\t\t\tint x = F(j, i);\n\t\t\tint y = F((j + 1) % 3, i);\n\t\t\tauto key = std::make_pair(x, y);\n\t\t\tauto reverse_key = std::make_pair(y, x);\n\t\t\tif (dedgeid.count(reverse_key)) {\n\t\t\t\tint deid = dedgeid[reverse_key];\n\t\t\t\tiE2E[i * 3 + j] = deid;\n\t\t\t\tiE2E[deid] = i * 3 + j;\n\t\t\t\tdedgeid.erase(reverse_key);\n\t\t\t} else {\n\t\t\t\tdedgeid[key] = i * 3 + j;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid InitializeMesh(void* vertices, void* faces, void* faceV, void* faceN, void* iE2E, int _num_v, int _num_f) {\n\tnum_v = _num_v;\n\tnum_f = _num_f;\n\n\tV = Eigen::Map<Eigen::MatrixXf>((float*)vertices, 3, num_v);\n\tF = Eigen::Map<Eigen::MatrixXi>((int*)faces, 3, num_f);\n\tFV = Eigen::Map<Eigen::MatrixXf>((float*)faceV, 3, num_f);\n\tFN = Eigen::Map<Eigen::MatrixXf>((float*)faceN, 3, num_f);\n\tE2E = (int*)iE2E;\n}\nvoid ReadBaryCentry(void* bary_coords, void* bary_indices, const char* filename) {\n\tFILE* fp = fopen(filename, \"rb\");\n\tint num_C, num_I;\n\tfread(&num_C, sizeof(int), 1, fp);\n\tfread(&num_I, sizeof(int), 1, fp);\n\tfread(bary_coords, sizeof(float), 3 * num_C, fp);\n\tfread(bary_indices, sizeof(int), num_I, fp);\n\tfclose(fp);\n}\n\nvoid FurthestSampling(void* pointcloud, void* inds, int num_input, int num_indices) {\n\tint* indices = (int*)inds;\n\tfloat* pts = (float*)pointcloud;\n\tstd::vector<double> distance(num_input, 1e30);\n\tfor (int i = 0; i < num_indices; ++i) {\n\t\tif (i == 0) {\n\t\t\tindices[i] = rand() % num_input;\n\t\t\tcontinue;\n\t\t}\n\t\tint offset_p = indices[i - 1] * 3;\n\t\tfloat px = pts[offset_p];\n\t\tfloat py = pts[offset_p + 1];\n\t\tfloat pz = pts[offset_p + 2];\n\t\tfor (int j = 0; j < num_input; ++j) {\n\t\t\tint offset_j = j * 3;\n\t\t\tfloat x = pts[offset_j] - px;\n\t\t\tfloat y = pts[offset_j + 1] - py;\n\t\t\tfloat z = pts[offset_j + 2] - pz;\n\t\t\tfloat dis = x * x + y * y + z * z;\n\t\t\tif (dis < distance[j]) {\n\t\t\t\tdistance[j] = dis;\n\t\t\t}\n\t\t}\n\n\t\tint max_index = 0;\n\t\tfor(int j = 0; j < num_input; ++j)\n\t\t{\n\t\t\tif(distance[j] > distance[max_index])\n\t\t\t{\n\t\t\t\tmax_index = j;\n\t\t\t}\n\t\t}\n\t\tindices[i] = max_index;\n\t}\n}\n\nvoid ComputeFacesInfo(void* fv, void* fn, void* v, void* f, int num_v, int num_f) {\n\tV = Eigen::Map<Eigen::MatrixXf>((float*)v, 3, num_v);\n\tF = Eigen::Map<Eigen::MatrixXi>((int*)f, 3, num_f);\n#pragma omp parallel for\n\tfor (int i = 0; i < num_f; ++i) {\n\t\tfloat* fv_f = ((float*)fv) + 3 * i;\n\t\tfloat* fn_f = ((float*)fn) + 3 * i;\n\t\tEigen::Vector3f FV = (V.col(F(0, i)) + V.col(F(1, i)) + V.col(F(2, i))) / 3.0f;\n\t\tEigen::Vector3f FN = (Eigen::Vector3f(V.col(F(1, i)) - V.col(F(0, i))).cross(Eigen::Vector3f(V.col(F(2, i)) - V.col(F(0, i))))).normalized();\n\t\tfv_f[0] = FV[0];\n\t\tfv_f[1] = FV[1];\n\t\tfv_f[2] = FV[2];\n\t\tfn_f[0] = FN[0];\n\t\tfn_f[1] = FN[1];\n\t\tfn_f[2] = FN[2];\n\t}\n}\n\ninline Eigen::Vector3d rotate_vector_into_plane(Eigen::Vector3d q, const Eigen::Vector3d &source_normal,\n                                         const Eigen::Vector3d &target_normal) {\n    const double cosTheta = source_normal.dot(target_normal);\n    if (cosTheta < 0.9999f) {\n        if (cosTheta < -0.9999f) return -q;\n        Eigen::Vector3d axis = source_normal.cross(target_normal);\n        q = q * cosTheta + axis.cross(q) +\n            axis * (axis.dot(q) * (1.0 - cosTheta) / axis.dot(axis));\n    }\n    return q;\n}\n\n\ninline Eigen::Vector3d Travel(Eigen::Vector3d p, const Eigen::Vector3d& dir, double len, int f, int* E2E, const Eigen::MatrixXf& V, const Eigen::MatrixXi& F, const Eigen::MatrixXf& NF, const double* triangle_space) {\n\tEigen::Vector3f Nf = NF.col(f);\n\tEigen::Vector3d N(Nf[0], Nf[1], Nf[2]);\n\tEigen::Vector3d pt = (dir - dir.dot(N) * N).normalized();\n\n\tint prev_id = -1;\n\tint count = 0;\n\n\twhile (len > 0) {\n\t\tcount += 1;\n\t\t//printf(\"%d %f\\n\", count, len);\n\t\tEigen::Vector3f t0f = V.col(F(0, f));\n\t\tEigen::Vector3f t1f = V.col(F(1, f));\n\t\tEigen::Vector3f t2f = V.col(F(2, f));\n\t\tEigen::Vector3d t0(t0f[0], t0f[1], t0f[2]);\n\t\tEigen::Vector3d t1(t1f[0], t1f[1], t1f[2]);\n\t\tEigen::Vector3d t2(t2f[0], t2f[1], t2f[2]);\n\t\tt1 -= t0;\n\t\tt2 -= t0;\n\n\t\tint edge_id = f * 3;\n\t\tdouble max_len = 1e30;\n\t\tbool found = false;\n\t\tint next_id, next_f;\n\t\tEigen::Vector3d next_q;\n\n\t\tdouble* triangle_space_f = ((double*)triangle_space) + f * 6;\n\t\tEigen::Matrix<double, 2, 3> T = Eigen::Map<Eigen::Matrix<double, 2, 3> >(triangle_space_f);\n\n\t\t//const Eigen::MatrixXd& T = triangle_space[f];\n\t\tEigen::VectorXd coord = T * (p - t0);\n\t\tEigen::VectorXd dirs = (T * pt);\n\n\t\tdouble lens[3];\n\t\tlens[0] = -coord.y() / dirs.y();\n\t\tlens[1] = (1 - coord.x() - coord.y()) / (dirs.x() + dirs.y());\n\t\tlens[2] = -coord.x() / dirs.x();\n\n\t\tfor (int fid = 0; fid < 3; ++fid) {\n\t\t\tif (fid + edge_id == prev_id)\n\t\t\t\tcontinue;\n\n\t\t\tif (lens[fid] >= 0 && lens[fid] < max_len) {\n\t\t\t\tmax_len = lens[fid];\n\t\t\t\tnext_id = E2E[edge_id + fid];\n\t\t\t\tnext_f = next_id;\n\t\t\t\tif (next_f != -1)\n\t\t\t\t\tnext_f /= 3;\n\t\t\t\tfound = true;\n\t\t\t}\n\t\t}\n\n\t\tEigen::Vector3f Nf_f = NF.col(f);\n//\t\tprintf(\"status: %f %f %d\\n\", len, max_len, f);\n\t\tif (max_len >= len) {\n\t\t\tp = p + len * pt;\n\t\t\tlen = 0;\n\t\t\tbreak;\n\t\t}\n\t\tp = t0 + t1 * (coord.x() + dirs.x() * max_len) + t2 * (coord.y() + dirs.y() * max_len);\n\t\tif (!found) {\n\t\t\tbreak;\t\t\t\n\t\t}\n\t\tlen -= max_len;\n\t\tif (next_f == -1) {\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tEigen::Vector3f Nf_nf = NF.col(next_f);\n\t\tpt = rotate_vector_into_plane(pt, Eigen::Vector3d(Nf_f[0], Nf_f[1], Nf_f[2]), Eigen::Vector3d(Nf_nf[0], Nf_nf[1], Nf_nf[2]));\n\t\tf = next_f;\n\t\tprev_id = next_id;\n\t}\n\treturn p;\n}\n\nvoid InitializeTangentSpace(void* vertices, void* faces, void* nf, int num_v, int num_f, void* tangent_space) {\n\tV = Eigen::Map<Eigen::MatrixXf>((float*)vertices, 3, num_v);\n\tF = Eigen::Map<Eigen::MatrixXi>((int*)faces, 3, num_f);\n\tFN = Eigen::Map<Eigen::MatrixXf>((float*)nf, 3, num_f);\n\tfor (int i = 0; i < num_f; ++i) {\n\t\tEigen::Matrix3d p, q;\n\t\tEigen::Vector3f v1 = V.col(F(1, i)) - V.col(F(0, i));\n\t\tEigen::Vector3f v2 = V.col(F(2, i)) - V.col(F(0, i));\n\t\tEigen::Vector3f v3 = FN.col(i);\n\t\tp.col(0) = Eigen::Vector3d(v1[0], v1[1], v1[2]);\n\t\tp.col(1) = Eigen::Vector3d(v2[0], v2[1], v2[2]);\n\t\tp.col(2) = Eigen::Vector3d(v3[0], v3[1], v3[2]);\n\t\tq = p.inverse();\n\t\tdouble* triangle_space_f = ((double*)tangent_space) + 6 * i;\n\t\tfor (int j = 0; j < 2; ++j) {\n\t\t\tfor (int k = 0; k < 3; ++k) {\n\t\t\t\ttriangle_space_f[k * 2 + j] = q(j, k);\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nvoid GetTangentNeighbors(float radius, void* positions, void* frames, void* finds, void* triangle_space, int num_v, void* out_p) {\n#pragma omp parallel for\n\tfor (int v = 0; v < num_v; ++v) {\n\t\tfloat* p_pos = ((float*)positions) + v * 3;\n\t\tfloat* p_frame = ((float*)frames) + v * 6;\n\t\tfloat* p_normal = p_frame + 3;\n\t\tfloat* out = ((float*)out_p) + v * 27;\n\t\tEigen::Vector3d p(p_pos[0], p_pos[1], p_pos[2]);\n\t\tEigen::Vector3d orient(p_frame[0], p_frame[1], p_frame[2]);\n\t\tEigen::Vector3d normal(p_normal[0], p_normal[1], p_normal[2]);\n\t\tEigen::Vector3d orient_y = normal.cross(orient);\n\t\tfor (int i = -1; i <= 1; ++i) {\n\t\t\tfor (int j = -1; j <= 1; ++j) {\n\t\t\t\tEigen::Vector3d dir = orient * i + orient_y * j; \n\t\t\t\tdouble len = dir.norm();\n\t\t\t\tdir = dir / len;\n\t\t\t\tEigen::Vector3d np = Travel(p, dir, len * radius, ((int*)finds)[v], E2E, V, F, FN, (double*)triangle_space);\n\t\t\t\tfloat* outp = out + ((i + 1) * 3 + (j + 1)) * 3;\n\t\t\t\toutp[0] = np[0];\n\t\t\t\toutp[1] = np[1];\n\t\t\t\toutp[2] = np[2];\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nstruct Coordinate {\n\tCoordinate()\n\t{}\n\tCoordinate(int f, const float* end, const float* from, const float* tex, const float* _ux) {\n\t\tfloat* n = ((float*)FN.data()) + f * 3;\n\t\tuy[0] = n[1] * _ux[2] - n[2] * _ux[1];\n\t\tuy[1] = n[2] * _ux[0] - n[0] * _ux[2];\n\t\tuy[2] = n[0] * _ux[1] - n[1] * _ux[0];\n\t\tfloat len = 1.0 / sqrt(uy[0] * uy[0] + uy[1] * uy[1] + uy[2] * uy[2]);\n\t\tuy[0] *= len;\n\t\tuy[1] *= len;\n\t\tuy[2] *= len;\n\n\t\tux[0] = uy[1] * n[2] - uy[2] * n[1];\n\t\tux[1] = uy[2] * n[0] - uy[0] * n[2];\n\t\tux[2] = uy[0] * n[1] - uy[1] * n[0];\n\n\t\tfloat dx = ux[0] * (end[0] - from[0]) + ux[1] * (end[1] - from[1]) + ux[2] * (end[2] - from[2]);\n\t\tfloat dy = uy[0] * (end[0] - from[0]) + uy[1] * (end[1] - from[1]) + uy[2] * (end[2] - from[2]);\n\t\tcoord[0] = tex[0] + dx;\n\t\tcoord[1] = tex[1] + dy;\n\t\tfind = f;\n\t}\n\tint find;\n\tfloat ux[3];\n\tfloat uy[3];\n\tfloat coord[2];\n};\nvoid GetNeighborhood(float radius,\n\tvoid* positions, void* frames, void* finds, int num_group_pts,\n\tvoid* pointcloud, void* pointcloud_finds, int num_pts,\n\tvoid* neighbor_inds, void* neighbor_tex, int num_indices)\n{\n\tfloat radius2 = radius * radius;\n\tstd::vector<int> indices(num_pts);\n\tstd::iota(indices.begin(), indices.end(), 0);\n\tstd::random_shuffle(indices.begin(), indices.end());\n#pragma omp parallel for\n\tfor (int pt_ind = 0; pt_ind < num_group_pts; ++pt_ind) {\n\t\tEigen::MatrixXf pts = Eigen::Map<Eigen::MatrixXf>((float*)pointcloud, 3, num_pts);\n\t\tEigen::Vector3f p = Eigen::Map<Eigen::Vector3f>(((float*)positions) + 3 * pt_ind);\n\t\tint find = ((int*)finds)[pt_ind];\n\n\t\tstd::unordered_map<int, int> neighbor_faces;\n\t\tstd::vector<Coordinate> q;\n\t\tq.reserve(1024);\n\t\tint front = 0;\n\t\tfloat* fv = (float*)FV.data();\n\t\t//q.push(std::make_pair(find, c));\n\t\tfloat tex[] = {0, 0};\n\t\tq.emplace_back(Coordinate(find, fv + find * 3, (float*)&p, tex, (float*)frames + 6 * pt_ind));\n\t\tneighbor_faces[find] = q.size() - 1;\n\t\twhile (front < q.size()) {\n\t\t\tauto& info = q[front];\n\t\t\tint f = info.find;\n\t\t\tint* nf = E2E + f * 3;\n\t\t\tfor (int i = 0; i < 3; ++i) {\n\t\t\t\tint next_f = *nf++;\n\t\t\t\tif (next_f == -1)\n\t\t\t\t\tcontinue;\n\t\t\t\tnext_f /= 3;\n\t\t\t\tbool flag = false;\n\t\t\t\tfor (int j = 0; j < 3; ++j) {\n\t\t\t\t\tauto diff = V.col(F(j, next_f)) - p;\n\t\t\t\t\tif (diff.squaredNorm() <= radius2 * 2) {\n\t\t\t\t\t\tflag = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (flag && !neighbor_faces.count(next_f)) {\n\t\t\t\t\tq.emplace_back(Coordinate(next_f, fv + next_f * 3, fv + f * 3, info.coord, info.ux));\n\t\t\t\t\tneighbor_faces[next_f] = q.size() - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfront += 1;\n\t\t}\n\t\tint offset_i = rand() % indices.size();\n\t\tint offset = 0;\n\t\tint* neighbor_ind = ((int*)neighbor_inds) + num_indices * pt_ind;\n\t\tfloat* neighbor_texs = ((float*)neighbor_tex) + num_indices * pt_ind * 2;\n\t\tauto it = indices.begin() + offset_i;\n\t\tbool found = false;\n\t\tfor (int i = 0; i < num_pts; ++i) {\n\t\t\tint seed = *it++;\n\t\t\tif (it == indices.end())\n\t\t\t\tit = indices.begin();\n\t\t\tEigen::Vector3f qs = pts.col(seed) - p;\n\t\t\tif (qs.squaredNorm() <= radius2 * 2) {\n\t\t\t\tint find = ((int*)pointcloud_finds)[seed];\n\t\t\t\tauto it = neighbor_faces.find(find);\n\t\t\t\tif (it != neighbor_faces.end()) {\n\t\t\t\t\tauto diff = pts.col(seed) - FV.col(find);\n\t\t\t\t\tauto& coord = q[it->second];\n\t\t\t\t\tEigen::Vector3f ux(coord.ux[0],coord.ux[1],coord.ux[2]);\n\t\t\t\t\tEigen::Vector3f uy(coord.uy[0],coord.uy[1],coord.uy[2]);\n\t\t\t\t\tfloat x = coord.coord[0] + diff.dot(ux);\n\t\t\t\t\tfloat y = coord.coord[1] + diff.dot(uy);\n\t\t\t\t\tif (std::abs(x) <= radius && std::abs(y) <= radius) {\n\t\t\t\t\t\tif (offset == num_indices) {\n\t\t\t\t\t\t\tif (x < 1e-5 && y < 1e-5) {\n\t\t\t\t\t\t\t\tneighbor_texs[0] = x;\n\t\t\t\t\t\t\t\tneighbor_texs[1] = y;\n\t\t\t\t\t\t\t\tneighbor_ind[0] = seed;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (x < 1e-5 && y < 1e-5) {\n\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tneighbor_texs[offset * 2] = x;\n\t\t\t\t\t\t\tneighbor_texs[offset * 2 + 1] = y;\n\t\t\t\t\t\t\tneighbor_ind[offset++] = seed;\n\t\t\t\t\t\t\tif (offset == num_indices && found)\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (; offset < num_indices; ++offset) {\n\t\t\tneighbor_ind[offset] = neighbor_ind[0];\n\t\t\tneighbor_texs[offset * 2] = 1e30;\n\t\t\tneighbor_texs[offset * 2 + 1] = 1e30;\n\t\t}\n\t}\n}\n\n\n\nvoid ComputeMask(void* maskp, void* indicesp, int num) {\n\tstd::unordered_set<int> uset;\n\tint* mask = (int*)maskp;\n\tint* indices = (int*)indicesp;\n\tfor (int i = 0; i < num; ++i) {\n\t\tint d = indices[i];\n\t\tif (uset.count(d)) {\n\t\t\tmask[i] = 0;\n\t\t} else {\n\t\t\tmask[i] = 1;\n\t\t\tuset.insert(d);\n\t\t}\n\t}\n}\n}", "meta": {"hexsha": "47080d02ada199eeddfebf45e3b3eb25be749623", "size": 13118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/Neighbors/neighbor.cpp", "max_stars_repo_name": "hjwdzh/TextureNet", "max_stars_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 89.0, "max_stars_repo_stars_event_min_datetime": "2019-03-30T03:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-25T05:16:51.000Z", "max_issues_repo_path": "data/Neighbors/neighbor.cpp", "max_issues_repo_name": "jtpils/TextureNet", "max_issues_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-06-29T11:21:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-12T04:09:41.000Z", "max_forks_repo_path": "data/Neighbors/neighbor.cpp", "max_forks_repo_name": "jtpils/TextureNet", "max_forks_repo_head_hexsha": "f3515537909ffb4ab04694b91109b535bb5c85d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-04-12T01:20:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-12T16:10:33.000Z", "avg_line_length": 29.6787330317, "max_line_length": 216, "alphanum_fraction": 0.5801189206, "num_tokens": 4968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.232634163901469}}
{"text": "#pragma once\n#include <boost/pending/disjoint_sets.hpp>\n#include \"xtensor/xtensor.hpp\"\n\n\nnamespace mutex_watershed {\n\n    // the datastructure to hold the mutex edges for a single cluster and all clusters\n    typedef std::unordered_set<uint32_t> MutexSet;\n    typedef std::vector<MutexSet> MutexStorage;\n\n\n    template<class UFD>\n    inline bool check_mutex(const uint32_t u, const uint32_t rv,\n                            UFD & ufd, const MutexStorage & mutexes) {\n        // the mutex storages are symmetric, so we only need to check one of them\n        const auto & mutex_u = mutexes[u];\n        bool have_mutex = false;\n        // we check for all representatives of mutex edges if\n        // they are the same as the reperesentative of v\n        for(const auto mu : mutex_u) {\n            if(ufd.find_set(mu) == rv) {\n                have_mutex = true;\n                break;\n            }\n        }\n        return have_mutex;\n    }\n\n\n    template<class UFD>\n    inline void insert_mutex(const uint32_t u, const uint32_t v, const uint32_t rv,\n                             UFD & ufd, MutexStorage & mutexes) {\n\n        auto & mutex_u = mutexes[u];\n        // if we don't have a mutex yet, insert it\n        if(mutex_u.size() == 0) {\n            mutex_u.insert(v);\n        }\n\n        // otherwise check if v is already in the mutexes\n        // and filter the mutexes in the process\n        else {\n\n            bool have_mutex = false;\n            std::unordered_set<uint32_t> mutex_representatives;\n\n            // iterate over all current mutexes\n            auto mutex_it = mutex_u.begin();\n            while(mutex_it != mutex_u.end()) {\n                const uint32_t rm = ufd.find_set(*mutex_it);\n\n                // check if this mutex is already present in the list\n                // if it is not, insert it, otherwise delete this mutex\n                if(mutex_representatives.find(rm) == mutex_representatives.end()) {\n                    mutex_representatives.insert(rm);\n                    ++mutex_it;  // we don't erase, so we need to increase by hand\n                } else {\n                    mutex_it = mutex_u.erase(mutex_it);\n                }\n\n                // if we have not already found v as mutex, check for it\n                if(!have_mutex) {\n                    have_mutex = rv == rm;\n                }\n            }\n\n            // insert the v mutex if it is not present\n            if(!have_mutex) {\n                // std::cout << \"Inserting mutex \" << u << \" \" << v << std::endl;\n                mutex_u.insert(v);\n            }\n        }\n    }\n\n\n    template<class UFD>\n    inline void merge_mutexes(const uint32_t u, const uint32_t v,\n                              UFD & ufd, MutexStorage & mutexes) {\n        auto & mutex_u = mutexes[u];\n        auto & mutex_v = mutexes[v];\n\n        // extract all representatives (which should be unique here)\n        std::unordered_map<uint32_t, uint32_t> mutex_reps_u;\n        for(const auto mu : mutex_u) {\n            mutex_reps_u[ufd.find_set(mu)] = mu;\n        }\n\n        std::unordered_map<uint32_t, uint32_t> mutex_reps_v;\n        for(const auto mv : mutex_v) {\n            mutex_reps_v[ufd.find_set(mv)] = mv;\n        }\n\n        // merge u into v\n        for(const auto mu : mutex_reps_u) {\n            if(mutex_reps_v.find(mu.first) == mutex_reps_v.end()) {\n                mutex_v.insert(mu.second);\n            }\n        }\n\n        // merge v into u\n        for(const auto mv : mutex_reps_v) {\n            if(mutex_reps_u.find(mv.first) == mutex_reps_u.end()) {\n                mutex_u.insert(mv.second);\n            }\n        }\n\n    }\n\n\n    template<class EDGE_ARRAY, class WEIGHT_ARRAY, class NODE_ARRAY>\n    void compute_mws_clustering(const size_t number_of_labels,\n                                const xt::xexpression<EDGE_ARRAY> & uvs_exp,\n                                const xt::xexpression<EDGE_ARRAY> & mutex_uvs_exp,\n                                const xt::xexpression<WEIGHT_ARRAY> & weights_exp,\n                                const xt::xexpression<WEIGHT_ARRAY> & mutex_weights_exp,\n                                xt::xexpression<NODE_ARRAY> & node_labeling_exp) {\n\n        // casts\n        const auto & uvs = uvs_exp.derived_cast();\n        const auto & mutex_uvs = mutex_uvs_exp.derived_cast();\n        const auto & weights = weights_exp.derived_cast();\n        const auto & mutex_weights = mutex_weights_exp.derived_cast();\n        auto & node_labeling = node_labeling_exp.derived_cast();\n\n        // make ufd\n        std::vector<uint64_t> ranks(number_of_labels);\n        std::vector<uint64_t> parents(number_of_labels);\n        boost::disjoint_sets<uint64_t*, uint64_t*> ufd(&ranks[0], &parents[0]);\n        for(uint64_t label = 0; label < number_of_labels; ++label) {\n            ufd.make_set(label);\n        }\n\n        // determine number of edge types\n        const size_t num_edges = uvs.shape()[0];\n        const size_t num_mutex = mutex_uvs.shape()[0];\n\n        // argsort ALL edges\n        // we sort in ascending order\n        std::vector<size_t> indices(num_edges + num_mutex);\n        std::iota(indices.begin(), indices.end(), 0);\n        std::sort(indices.begin(), indices.end(), [&](const size_t a, const size_t b){\n            const double val_a = (a < num_edges) ? weights(a) : mutex_weights(a - num_edges);\n            const double val_b = (b < num_edges) ? weights(b) : mutex_weights(b - num_edges);\n            return val_a < val_b;\n        });\n\n        MutexStorage mutexes(number_of_labels);\n\n        // iterate over all edges\n        for(const size_t edge_id : indices) {\n\n            // check whether this edge is mutex via the edge offset\n            const bool is_mutex = edge_id >= num_edges;\n\n            if(is_mutex) {\n                // find the mutex id and the connected nodes\n                const size_t mutex_id = edge_id - num_edges;\n                const uint32_t u = mutex_uvs(mutex_id, 0);\n                const uint32_t v = mutex_uvs(mutex_id, 1);\n\n                // find the current representatives\n                const uint32_t ru = ufd.find_set(u);\n                const uint32_t rv = ufd.find_set(v);\n\n                // if the nodes are already connected, do nothing\n                if(ru == rv) {\n                    continue;\n                }\n\n                // otherwise, insert the mutex\n                insert_mutex(u, v, rv, ufd, mutexes);\n                insert_mutex(v, u, ru, ufd, mutexes);\n\n            } else {\n\n                // find the connected nodes\n                const uint32_t u = uvs(edge_id, 0);\n                const uint32_t v = uvs(edge_id, 1);\n\n                // find the current representatives\n                const uint32_t ru = ufd.find_set(u);\n                const uint32_t rv = ufd.find_set(v);\n\n                // if the nodes are already connected, do nothing\n                if(ru == rv) {\n                    continue;\n                }\n\n                // otherwise, check if we have an active constraint / mutex edge\n                const bool have_mutex = check_mutex(u, rv, ufd, mutexes) || check_mutex(v, ru, ufd, mutexes);\n                //const bool have_mutex = check_mutex_edge(u, v, mutexes);\n\n                // only merge if we don't have a mutex\n                if(!have_mutex) {\n                    ufd.link(u, v);\n                    merge_mutexes(u, v, ufd, mutexes);\n                }\n\n            }\n        }\n\n        // get node labeling into output\n        for(size_t label = 0; label < number_of_labels; ++label) {\n            node_labeling[label] = ufd.find_set(label);\n        }\n    }\n}\n", "meta": {"hexsha": "4d3164a21f5697b3aae55df8760a8507882c624b", "size": 7610, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/mutex_watershed/mutex_watershed.hxx", "max_stars_repo_name": "constantinpape/mutex-watershed", "max_stars_repo_head_hexsha": "1316e98c43511eeded30491f83235bd78b32ce4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-19T03:05:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-19T03:05:43.000Z", "max_issues_repo_path": "include/mutex_watershed/mutex_watershed.hxx", "max_issues_repo_name": "constantinpape/mutex-watershed", "max_issues_repo_head_hexsha": "1316e98c43511eeded30491f83235bd78b32ce4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-09-19T05:15:15.000Z", "max_issues_repo_issues_event_max_datetime": "2018-09-19T07:45:01.000Z", "max_forks_repo_path": "include/mutex_watershed/mutex_watershed.hxx", "max_forks_repo_name": "constantinpape/mutex-watershed", "max_forks_repo_head_hexsha": "1316e98c43511eeded30491f83235bd78b32ce4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-09-21T21:01:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-21T21:01:25.000Z", "avg_line_length": 36.4114832536, "max_line_length": 109, "alphanum_fraction": 0.5408672799, "num_tokens": 1725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.550607350786733, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23263415767015627}}
{"text": "/* Author: Mincheul Kang */\n\n#include <harmonious_sampling/HarmoniousLazyPRMstarMulti.h>\n#include <ompl/base/objectives/PathLengthOptimizationObjective.h>\n#include <ompl/base/goals/GoalSampleableRegion.h>\n#include <ompl/util/GeometricEquations.h>\n#include <ompl/geometric/planners/prm/ConnectionStrategy.h>\n#include <ompl/tools/config/SelfConfig.h>\n#include <ompl/base/spaces/RealVectorStateSpace.h>\n\n#include <boost/lambda/bind.hpp>\n#include <boost/graph/astar_search.hpp>\n#include <boost/graph/lookup_edge.hpp>\n#include <boost/foreach.hpp>\n#include <fstream>\n#include <queue>\n#include <stack>\n#include <utility>\n#include <numeric>\n#include <stdio.h>\n#include <iostream>\n\n#define foreach BOOST_FOREACH\n\nnamespace ompl {\n    namespace magic {\n/** \\brief The number of nearest neighbors to consider by\n      default in the construction of the PRM roadmap */\n        static const unsigned int DEFAULT_NEAREST_NEIGHBORS_LAZY = 5;\n\n/** \\brief When optimizing solutions with lazy planners, this is the minimum\n      number of path segments to add before attempting a new optimized solution\n          extraction */\n        static const unsigned int MIN_ADDED_SEGMENTS_FOR_LAZY_OPTIMIZATION = 5;\n    }\n}\n\nompl::geometric::HarmoniousLazyPRMstarMulti::HarmoniousLazyPRMstarMulti(const base::SpaceInformationPtr &si,\n                                                                        base::HarmoniousSampler &hs,\n                                                                        const std::vector<bool> &isContinuous,\n                                                                        bool starStrategy) :\n        base::Planner(si, \"HarmoniousLazyPRMstarMulti\"),\n        starStrategy_(starStrategy),\n        userSetConnectionStrategy_(false),\n        maxDistance_(0.0),\n        indexProperty_(boost::get(boost::vertex_index_t(), g_)),\n        stateProperty_(boost::get(vertex_state_t(), g_)),\n        radiusProperty_(boost::get(vertex_radius_t(), g_)),\n        witnessProperty_(boost::get(vertex_witness_t(), g_)),\n        costProperty_(boost::get(vertex_cost_t(), g_)),\n        childrenProperty_(boost::get(vertex_children_t(), g_)),\n        predecessorProperty_(boost::get(boost::vertex_predecessor_t(), g_)),\n        colorProperty_(boost::get(boost::vertex_color_t(), g_)),\n        weightProperty_(boost::get(boost::edge_weight_t(), g_)),\n        vertexValidityProperty_(boost::get(vertex_flags_t(), g_)),\n        edgeValidityProperty_(boost::get(edge_flags_t(), g_)),\n        bestCost_(std::numeric_limits<double>::quiet_NaN()),\n        iterations_(0),\n        increaseIterations_(0),\n        BisectionCC_(true),\n        rewireFactor_(1.5),\n        hs_(hs),\n        isContinuous_(isContinuous)\n{\n    specs_.recognizedGoal = base::GOAL_SAMPLEABLE_REGION;\n    specs_.approximateSolutions = false;\n    specs_.optimizingPaths = true;\n\n    Planner::declareParam<bool>(\"BisectionCC\", this,\n                                &HarmoniousLazyPRMstarMulti::setBisectionCC, std::string(\".\"));\n    Planner::declareParam<double>(\"RewireFactor\", this,\n                                  &HarmoniousLazyPRMstarMulti::setRewireFactor, std::string(\".\"));\n\n    addPlannerProgressProperty(\"iterations INTEGER\",\n                               std::bind(&HarmoniousLazyPRMstarMulti::getIterationCount, this));\n    addPlannerProgressProperty(\"best cost REAL\",\n                               std::bind(&HarmoniousLazyPRMstarMulti::getBestCost, this));\n    addPlannerProgressProperty(\"milestone count INTEGER\",\n                               std::bind(&HarmoniousLazyPRMstarMulti::getMilestoneCountString, this));\n    addPlannerProgressProperty(\"edge count INTEGER\",\n                               std::bind(&HarmoniousLazyPRMstarMulti::getEdgeCountString, this));\n}\n\nompl::geometric::HarmoniousLazyPRMstarMulti::~HarmoniousLazyPRMstarMulti() {\n}\n\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::setup() {\n    Planner::setup();\n    tools::SelfConfig sc(si_, getName());\n    sc.configurePlannerRange(maxDistance_);\n\n    if (!nn_) {\n        nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Vertex>(this));\n        nn_->setDistanceFunction(std::bind(&HarmoniousLazyPRMstarMulti::distanceFunctionHarmonious, this, std::placeholders::_1, std::placeholders::_2));\n    }\n\n    if (!nnB_) {\n        nnB_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Vertex>(this));\n        nnB_->setDistanceFunction(std::bind(&HarmoniousLazyPRMstarMulti::distanceFunctionHarmonious, this, std::placeholders::_1, std::placeholders::_2));\n    }\n\n    if (!nnM_) {\n        nnM_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Vertex>(this));\n        nnM_->setDistanceFunction(std::bind(&HarmoniousLazyPRMstarMulti::distanceFunctionHarmonious, this, std::placeholders::_1, std::placeholders::_2));\n    }\n\n    if (!connectionStrategy_) {\n//        if (starStrategy_)\n//            connectionStrategy_ = KStarStrategy<Vertex>(std::bind(&HarmoniousLazyPRMstarMulti::milestoneCount, this), nn_, si_->getStateDimension());\n//        else\n//            connectionStrategy_ = KBoundedStrategy<Vertex>(magic::DEFAULT_NEAREST_NEIGHBORS_LAZY, maxDistance_, nn_);\n    }\n\n    double dimDbl = static_cast<double>(si_->getStateDimension());\n    // double prunedMeasure_ = si_->getSpaceMeasure();\n\n    k_rrgConstant_ = rewireFactor_ * boost::math::constants::e<double>() + (boost::math::constants::e<double>() / dimDbl);\n\n    // Setup optimization objective\n    //\n    // If no optimization objective was specified, then default to\n    // optimizing path length as computed by the distance() function\n    // in the state space.\n    if (pdef_) {\n        if (pdef_->hasOptimizationObjective()) {\n            opt_ = pdef_->getOptimizationObjective();\n        }\n        else {\n            opt_.reset(new base::PathLengthOptimizationObjective(si_));\n\n            if (!starStrategy_) {\n                opt_->setCostThreshold(opt_->infiniteCost());\n            }\n        }\n    }\n    else {\n        OMPL_ERROR(\"%s: problem definition is not set, deferring setup completion...\\n\", getName().c_str());\n        setup_ = false;\n    }\n    sampler_ = si_->allocStateSampler();\n}\n\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::setRange(double distance) {\n    maxDistance_ = distance;\n\n    if (!userSetConnectionStrategy_) {\n        connectionStrategy_.clear();\n    }\n\n    if (isSetup()) {\n        setup();\n    }\n}\n\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::setMaxNearestNeighbors(unsigned int k) {\n    if (starStrategy_) {\n        throw Exception(\"Cannot set the maximum nearest neighbors for \" + getName());\n    }\n\n    if (!nn_) {\n        nn_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Vertex>(this));\n        nn_->setDistanceFunction(std::bind(&HarmoniousLazyPRMstarMulti::distanceFunctionHarmonious, this,std::placeholders::_1, std::placeholders::_2));\n    }\n\n    if (!nnB_) {\n        nnB_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Vertex>(this));\n        nnB_->setDistanceFunction(std::bind(&HarmoniousLazyPRMstarMulti::distanceFunctionHarmonious, this, std::placeholders::_1, std::placeholders::_2));\n    }\n\n    if (!nnM_) {\n        nnM_.reset(tools::SelfConfig::getDefaultNearestNeighbors<Vertex>(this));\n        nnM_->setDistanceFunction(std::bind(&HarmoniousLazyPRMstarMulti::distanceFunctionHarmonious, this, std::placeholders::_1, std::placeholders::_2));\n    }\n\n    if (!userSetConnectionStrategy_) {\n        connectionStrategy_.clear();\n    }\n\n    if (isSetup()) {\n        setup();\n    }\n}\n\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::setProblemDefinition(const base::ProblemDefinitionPtr &pdef) {\n    Planner::setProblemDefinition(pdef);\n    clearQuery();\n}\n\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::clearQuery() {\n    startM_.clear();\n    goalM_.clear();\n    pis_.restart();\n}\n\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::clear() {\n    Planner::clear();\n    freeMemory();\n\n    if (nn_) {\n        nn_->clear();\n    }\n\n    if (nnB_) {\n        nnB_->clear();\n    }\n\n    if (nnM_) {\n        nnM_->clear();\n    }\n\n    clearQuery();\n\n    iterations_ = 0;\n    bestCost_ = base::Cost(std::numeric_limits<double>::quiet_NaN());\n}\n\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::freeMemory() {\n    foreach (Vertex v, boost::vertices(g_)) {\n        si_->freeState(stateProperty_[v]);\n    }\n\n    g_.clear();\n}\n\n// Add newly sampled vertex and its adjancency edges connected to neigh neighbors.\nompl::geometric::HarmoniousLazyPRMstarMulti::Vertex ompl::geometric::HarmoniousLazyPRMstarMulti::addMilestone(base::State *state, bool isM, bool isChecked) {\n    Vertex m = boost::add_vertex(g_);\n    stateProperty_[m] = state;\n    radiusProperty_[m] = std::numeric_limits<double>::infinity();\n    costProperty_[m] = std::numeric_limits<double>::infinity();\n    childrenProperty_[m] = new std::vector<Vertex>();\n    witnessProperty_[m] = NULL;\n    predecessorProperty_[m] = NULL;\n    colorProperty_[m] = 0;\n    vertexValidityProperty_[m] = (isChecked) ? VALIDITY_TRUE : VALIDITY_UNKNOWN;\n\n    std::vector<Vertex> neighbors;\n    std::vector<double> neighbors_costs;\n\n    if(isM){\n        // manipulation regions\n        unsigned long int bSize = nnB_->size();\n        unsigned int max_number_of_neighbors = std::ceil(k_rrgConstant_ * log(static_cast<double>(milestoneCount()-bSize) + 1u));\n        neighbors.reserve(max_number_of_neighbors);\n        neighbors_costs.reserve(max_number_of_neighbors);\n\n        nnM_->nearestK(m, max_number_of_neighbors, neighbors);\n\n        foreach (Vertex n, neighbors) {\n            const double weight = distanceFunctionHarmonious(n, m);\n\n            ompl::base::Cost cost_weight(weight);\n            const Graph::edge_property_type properties(cost_weight);\n\n            neighborProperty_[m].push_back(type_neighbor(n, weight));\n            neighborProperty_[n].push_back(type_neighbor(m, weight));\n\n            // If collision-free or optimized well,\n            const Edge &e = boost::add_edge(n, m, properties, g_).first;\n            edgeValidityProperty_[e] = VALIDITY_UNKNOWN;\n        }\n\n        // base regions\n        max_number_of_neighbors = std::ceil(k_rrgConstant_ * log(static_cast<double>(bSize) + 1u));\n\n        neighbors.reserve(max_number_of_neighbors);\n        neighbors_costs.reserve(max_number_of_neighbors);\n\n        nnB_->nearestK(m, max_number_of_neighbors, neighbors);\n\n        foreach (Vertex n, neighbors) {\n            const double weight = distanceFunctionHarmonious(n, m);\n\n            ompl::base::Cost cost_weight(weight);\n            const Graph::edge_property_type properties(cost_weight);\n\n            neighborProperty_[m].push_back(type_neighbor(n, weight));\n            neighborProperty_[n].push_back(type_neighbor(m, weight));\n\n            // If collision-free or optimized well,\n            const Edge &e = boost::add_edge(n, m, properties, g_).first;\n            edgeValidityProperty_[e] = VALIDITY_UNKNOWN;\n        }\n\n        nnM_->add(m);\n    }\n    else{\n        unsigned int max_number_of_neighbors = std::ceil(k_rrgConstant_ * log(static_cast<double>(milestoneCount()) + 1u));\n\n        neighbors.reserve(max_number_of_neighbors);\n        neighbors_costs.reserve(max_number_of_neighbors);\n\n        nn_->nearestK(m, max_number_of_neighbors, neighbors);\n\n        foreach (Vertex n, neighbors) {\n            const double weight = distanceFunctionHarmonious(n, m);\n\n            ompl::base::Cost cost_weight(weight);\n            const Graph::edge_property_type properties(cost_weight);\n\n            neighborProperty_[m].push_back(type_neighbor(n, weight));\n            neighborProperty_[n].push_back(type_neighbor(m, weight));\n\n            // If collision-free or optimized well,\n            const Edge &e = boost::add_edge(n, m, properties, g_).first;\n            edgeValidityProperty_[e] = VALIDITY_UNKNOWN;\n        }\n\n        nnB_->add(m);\n    }\n\n    nn_->add(m);\n\n    return m;\n}\n\nompl::base::PlannerStatus ompl::geometric::HarmoniousLazyPRMstarMulti::solve(const base::PlannerTerminationCondition &ptc) {\n    // Initial checkup for start/goal configurations.\n    checkValidity();\n\n    // Add the valid start states as milestones\n    while (const base::State *st = pis_.nextStart()) {\n        Vertex st_vert = addMilestone(si_->cloneState(st), false);\n        costProperty_[st_vert] = 0.0; // Initialize with 0 cost.\n        startM_.push_back(st_vert);\n    }\n\n    if (startM_.size() == 0) {\n        OMPL_ERROR(\"error-%s: There are no valid initial states!\", getName().c_str());\n        return base::PlannerStatus::INVALID_START;\n    }\n\n    unsigned long int nrStartStates = boost::num_vertices(g_);\n    OMPL_INFORM(\"%s: Starting planning with %lu states already in datastructure\", getName().c_str(), nrStartStates);\n\n    bestCost_ = opt_->infiniteCost();\n    base::State *workState = si_->allocState();\n    bool fullyOptimized = false;\n    base::PathPtr bestSolution;\n\n    base::RealVectorStateSpace::StateType *rstate = static_cast<base::RealVectorStateSpace::StateType*>(workState);\n\n    Vertex startV = startM_[0];\n\n    do{\n        if(hs_.makeGoal(si_, workState)){\n            goalM_.push_back(addMilestone(si_->cloneState(workState), true));\n        }\n    } while(goalM_.size() == 0 && ptc == false);\n\n    bool isM = false;\n    while (ptc == false) {\n        ++iterations_;\n\n        int r_val = std::rand() % 100;\n        if(r_val < hs_.params_.prob_goal_ && goalM_.size() < hs_.params_.max_num_goal_){\n            if(hs_.makeGoal(si_, workState)){\n                goalM_.push_back(addMilestone(si_->cloneState(workState), true));\n            }\n            else{\n                continue;\n            }\n        }\n        else if(r_val < hs_.params_.prob_uniform_){\n            hs_.uniformSampling(workState);\n            if(hs_.getReachable(workState)){\n                isM = true;\n            }\n            else{\n                isM = false;\n            }\n        }\n        else{\n            hs_.biasedSampling(workState);\n\n            if(hs_.getReachable(workState)){\n                hs_.jointSampling(workState);\n                isM = true;\n            }\n            else{\n                hs_.setBasicPose(workState);\n                isM = false;\n            }\n        }\n\n        if (!si_->isValid(workState)) {\n            continue;\n        }\n\n        // Add collision-free vertices.\n        Vertex addedVertex = addMilestone(si_->cloneState(workState), isM);\n\n        // DSPT update.\n        Decrease(addedVertex);\n\n        // Only support a single pair of start and goal node.\n        base::PathPtr solution;\n\n        for (int i = 0; i < (int)goalM_.size(); i++) {\n            Vertex goalV = goalM_[i];\n            do {\n                if (predecessorProperty_[goalV] == NULL || bestCost_.value() <= costProperty_[goalV])\n                    break;\n                solution = constructSolution(startV, goalV);\n            } while (!solution);\n\n            if (solution) {\n                base::Cost c(costProperty_[goalV]);\n\n                if (opt_->isCostBetterThan(c, bestCost_)) {\n                    bestSolution = solution;\n\n                    bestCost_ = c;\n                }\n            }\n        }\n    }\n    if (goalM_.empty()) {\n        OMPL_ERROR(\"%s: Unable to find any valid goal states\", getName().c_str());\n        return base::PlannerStatus::INVALID_GOAL;\n    }\n\n    si_->freeState(workState);\n\n    if (bestSolution) {\n        base::PlannerSolution psol(bestSolution);\n        psol.setPlannerName(getName());\n        // If the solution was optimized, we mark it as such\n        psol.setOptimized(opt_, bestCost_, fullyOptimized);\n        pdef_->addSolutionPath(psol);\n    }\n\n    OMPL_INFORM(\"%s: Created %lu vertices and %lu edges.\", getName().c_str(), boost::num_vertices(g_) - 1, boost::num_edges(g_));\n    OMPL_INFORM(\"%s: Goalstates %lu \", getName().c_str(), goalM_.size());\n    OMPL_INFORM(\"Cost: %.6f\", bestCost_.value());\n\n    return bestSolution ? base::PlannerStatus::EXACT_SOLUTION :\n           base::PlannerStatus::TIMEOUT;\n}\n\n// outedge, inedge? - doesn't matter, need to scan all the neighbors.\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::Decrease(const Vertex &v) {\n    typedef std::pair<double, Vertex> weight_vertex;\n    std::priority_queue<weight_vertex> pq;\n\n    // Initialize cost of v, i.e., finding best parent vertex in G(g_).\n    BGL_FORALL_OUTEDGES(v, e, g_, Graph) {\n        Vertex w = target(e, g_);\n        double weight = weightProperty_[e].value();\n\n        if (costProperty_[v] > costProperty_[w] + weight) {\n            predecessorProperty_[v] = w;\n            costProperty_[v] = costProperty_[w] + weight;\n        }\n    }\n\n    // No need to invoke cancelAdoption since v is newly sampled.\n    if (predecessorProperty_[v] != NULL) {\n        childrenProperty_[predecessorProperty_[v]]->push_back(v);\n    }\n\n    // At this point, v has a best parent. From now on construct its subtree of descendants.\n\n    pq.push(weight_vertex(-costProperty_[v], v)); // Invert the cost value for mimicking min-heap.\n\n    while (!pq.empty()) {\n        weight_vertex top = pq.top();\n        pq.pop();\n\n        double cost = -top.first; // Invert the cost value to be like min-heap.\n        Vertex vert = top.second;\n\n        if (cost > costProperty_[vert]) {\n            continue;\n        }\n\n        BGL_FORALL_OUTEDGES(vert, e, g_, Graph) {\n            Vertex w = target(e, g_);\n            double weight = weightProperty_[e].value();\n            double cost_w = costProperty_[w];\n\n            if (cost_w > cost + weight) {\n                costProperty_[w] = cost + weight;\n                cancelAdoption(w);\n\n                predecessorProperty_[w] = vert;\n                childrenProperty_[vert]->push_back(w);\n                pq.push(weight_vertex(-costProperty_[w], w));\n            }\n        }\n    }\n\n    // Now, DSPT is stable.\n}\n\n#define RED (increaseIterations_ + 1) // I know, it's bad #define.\n\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::Increase(const Vertex vs) {\n    // <Step 1. Preparation.\n    // white is used for color of each vertex without initialization.\n    // For each iteration, white is increased by 1, thus we can use it as\n    // equal to or less than 'white' means 'white' color, 'red' otherwise.\n    increaseIterations_ += 1;\n\n    std::vector<Vertex> reds;\n    typedef std::pair<double, Vertex> weight_vertex;\n    std::priority_queue<weight_vertex> pq; //  Max-heap by default.\n\n    pq.push(weight_vertex(-costProperty_[vs], vs));  // It works as if it is min-heap.\n\n    // <Step 2. Coloring\n    while (!pq.empty()) {\n        weight_vertex top = pq.top();\n        pq.pop();\n\n        double cost = -top.first;\n        Vertex vert = top.second;\n\n        if (cost > costProperty_[vert]) {\n            continue;  // Instead of heap-improve\n        }\n\n        // Probability to get a pink node? almost impossible!\n        /*\n        // If there exist a non-red neighbor q of z such that Dist(q) + w_(q, z) = D(z)\n        // set pink, that means it can keep the current cost, thus it is not necessary to\n        // iterate its children.\n        // Otherwise, set red and enqueue all the children of z.\n        bool pink_flag = false;\n        BGL_FORALL_OUTEDGES(vert, e, g_, Graph) {\n          Vertex w = target(e, g_);\n          double weight = weightProperty_[e].value();\n\n          if (colorProperty_[w] != RED && costProperty_[w] + weight == cost) {\n            // Actually, '<' should not be happened all the time.\n            // And even '==' would very rarely occur, but possible.\n            pink_flag = true;\n\n            cancelAdoption(vert);\n            predecessorProperty_[vert] = w;\n            childrenProperty_[w]->push_back(vert);\n            break; // If there exsits, take anyone among them.\n          }\n        }\n\n        if (pink_flag) {\n          continue;\n        }*/\n\n        colorProperty_[vert] = RED; // Set to 'red'\n        reds.push_back(vert);\n        // Even with multiple starting red nodes, there will be no re-visit since each starting node is\n        // a root node of sub'tree' in DSPT. That is, if statement within for loop might be useless.\n        // Someone would be curious, e.g., then why do we have to use priority queue in step2 ?\n        // Just for 'pink' case. Yeap. We need to identify all the other parent candidates are red or not\n        // prior to checking current node.\n        std::vector<Vertex> *children = childrenProperty_[vert];\n\n        for (unsigned int i = 0; i < children->size(); i++) {\n            pq.push(weight_vertex(-costProperty_[(*children)[i]], (*children)[i]));\n        }\n    }\n\n    // 'pq' is empty at here.\n\n    // <Step 3-a. Find best non-red parent for each red node.\n    for (unsigned int i = 0; i < reds.size(); i++) {\n        // TODO : need to be verified\n        // Cost/predecessor initialization.\n        costProperty_[reds[i]] = std::numeric_limits<double>::infinity();\n        cancelAdoption(reds[i]);\n\n        BGL_FORALL_OUTEDGES(reds[i], e, g_, Graph) {\n            Vertex w = target(e, g_);\n            double weight = weightProperty_[e].value();\n\n            if (colorProperty_[w] == RED) {\n                continue;  // If red, put aside for a while.\n            }\n\n            if (costProperty_[reds[i]] > costProperty_[w] + weight) {\n                costProperty_[reds[i]] = costProperty_[w] + weight;\n                predecessorProperty_[reds[i]] = w;\n            }\n        }\n\n        if (predecessorProperty_[reds[i]] != NULL) {\n            childrenProperty_[predecessorProperty_[reds[i]]]->push_back(reds[i]);\n        }\n\n        pq.push(weight_vertex(-costProperty_[reds[i]], reds[i]));\n    }\n\n    // <Step 3-b. Propagate the changes; rewiring for 'red' nodes whether it can replace\n    // existing parent node of near neighbors.\n    while (!pq.empty()) {\n        weight_vertex top = pq.top();\n        pq.pop();\n\n        double cost = -top.first;\n        Vertex vert = top.second;\n\n        if (costProperty_[vert] < cost) {\n            continue;\n        }\n\n        BGL_FORALL_OUTEDGES(vert, e, g_, Graph) {\n            Vertex w = target(e, g_);\n            double weight = weightProperty_[e].value();\n\n            if (colorProperty_[w] != RED) {\n                continue;  // If not red, then skip.\n            }\n\n            if (cost + weight < costProperty_[w]) {\n                costProperty_[w] = cost + weight;\n\n                cancelAdoption(w);\n\n                predecessorProperty_[w] = vert;\n                childrenProperty_[vert]->push_back(w);\n                pq.push(weight_vertex(-costProperty_[w], w));\n            }\n        }\n    }\n\n    // The end!\n    // colorProperty_ is not necessary to be cleansed out, just increase variable, 'RED'.\n}\n\n// TODO : sync between children & edges.\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::cancelAdoption(const Vertex &child) {\n    if (predecessorProperty_[child] == NULL)\n        return;\n\n    std::vector<Vertex> *children = childrenProperty_[predecessorProperty_[child]];\n\n    for (unsigned int i = 0; i < children->size(); i++) if ((*children)[i] == child) {\n            std::swap((*children)[i], children->back());\n            children->pop_back();\n            break;\n        }\n\n    predecessorProperty_[child] = NULL;\n}\n\n// Vertex first.\nompl::base::PathPtr ompl::geometric::HarmoniousLazyPRMstarMulti::constructSolution(const Vertex &start, const Vertex &goal) {\n    std::vector<Vertex> solution_path;\n\n    // Construct a solution from DSPT.\n    for (Vertex vert = goal; vert != NULL; vert = predecessorProperty_[vert])\n        solution_path.push_back(vert);\n\n    if (solution_path.empty() || solution_path.size() == 1)\n        return base::PathPtr();\n\n    // Goal = 0, Start = n - 1.\n    // TODO : From goal or start ? which one is better?\n\n    // auto from = solution_path.rbegin();\n    std::vector<Vertex>::reverse_iterator from = solution_path.rbegin();\n    for (std::vector<Vertex>::reverse_iterator to = from + 1; to != solution_path.rend(); ++to) {\n        Edge e = boost::lookup_edge(*from, *to, g_).first; // Exhaustive search O(E) at worst case.\n        unsigned int &evd = edgeValidityProperty_[e];\n\n        if ((evd & VALIDITY_TRUE) == 0) { // Unknown\n            bool result = true;\n            // double weight = weightProperty_[e].value();\n\n            result &= checkMotion(stateProperty_[*from], stateProperty_[*to]);\n\n            if (result) {\n                evd |= VALIDITY_TRUE;\n            }\n            else {\n                boost::remove_edge(e, g_); // O(log(E/V)) time...\n\n                cancelAdoption(*to);\n                Increase(*to);\n                return base::PathPtr();\n            }\n        }\n\n        from = to;\n    }\n\n    PathGeometric *p = new PathGeometric(si_);\n\n    // Feasible path is found, fetch optimized edges if possible.\n\n    for (std::vector<Vertex>::const_reverse_iterator sol = solution_path.rbegin(); sol != solution_path.rend(); ++sol) {\n        p->append(stateProperty_[*sol]);\n    }\n\n    return base::PathPtr(p);\n}\n\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::getPlannerData(base::PlannerData &data) const {\n    Planner::getPlannerData(data);\n    // Caution : it handles directional information regardless of the search graph setting\n    //           which is undirectional graph.\n}\n\ndouble ompl::geometric::HarmoniousLazyPRMstarMulti::distanceFunction(const base::State *a, const base::State *b) const {\n    return si_->distance(a, b);\n}\n\ndouble ompl::geometric::HarmoniousLazyPRMstarMulti::distanceFunctionHarmonious(const Vertex a, const Vertex b) const {\n    double base = distanceFunctionBase(stateProperty_[a], stateProperty_[b]);\n    double arm =  distanceFunctionJoints(stateProperty_[a], stateProperty_[b]);\n\n    return base + arm;\n}\n\n\ndouble ompl::geometric::HarmoniousLazyPRMstarMulti::distanceFunctionBase(const base::State *a, const base::State *b) const {\n    double dist = 0.0;\n    int dim = si_->getStateDimension();\n\n    std::vector<double> ca, cb;\n    si_->getStateSpace()->copyToReals(ca, a);\n    si_->getStateSpace()->copyToReals(cb, b);\n\n    for (int i = 0; i < NUM_BASE_DOF; i++) {\n        double dd = fabs(ca[i]-cb[i]);\n\n        if(isContinuous_[i]) {\n            if (dd > boost::math::constants::pi<double>()) {\n                dd = 2.0 * boost::math::constants::pi<double>() - dd;\n            }\n        }\n\n        dist += hs_.params_.weights_[i] * dd * hs_.params_.weights_[i] * dd;\n    }\n\n    return std::sqrt(dist);\n}\n\ndouble ompl::geometric::HarmoniousLazyPRMstarMulti::distanceFunctionJoints(const base::State *a, const base::State *b) const {\n    double dist = 0.0;\n\n    std::vector<double> ca, cb;\n    si_->getStateSpace()->copyToReals(ca, a);\n    si_->getStateSpace()->copyToReals(cb, b);\n\n    for (int i = NUM_BASE_DOF; i < ca.size(); i++) {\n        double dd = fabs(ca[i]-cb[i]);\n\n        if(isContinuous_[i+3]){\n            if (dd > boost::math::constants::pi<double>()) {\n                dd = 2.0 * boost::math::constants::pi<double>() - dd;\n            }\n        }\n\n        dist += hs_.params_.weights_[i] * dd * hs_.params_.weights_[i] * dd;\n    }\n\n    return std::sqrt(dist);\n}\n\n\nbool ompl::geometric::HarmoniousLazyPRMstarMulti::checkMotion(base::State *s1, base::State *s2) const {\n//    /* Assume motion starts/ends in a valid configuration so v1/v2 are valid */\n    bool result = true;\n    int dim = si_->getStateDimension();\n    int nd;\n\n    int nd_j = validSegmentCount_compare(distanceFunctionJoints(s1, s2), hs_.params_.factor_joint_);\n    int nd_b = validSegmentCount_compare(distanceFunctionBase(s1, s2), hs_.params_.factor_base_);\n    if(nd_j > nd_b){\n        nd = nd_j;\n    }\n    else{\n        nd = nd_b;\n    }\n\n    if (nd > 1) {\n        /* Temporary storage for the checked state */\n        base::State *test = si_->allocState();\n        std::queue<std::pair<unsigned int, unsigned int> > q;\n        q.push(std::make_pair(1, nd - 1));\n\n        while (!q.empty()) {\n            std::pair<unsigned int, unsigned int> range = q.front();\n            unsigned int mid;\n\n            mid = (range.first + range.second) / 2;\n            interpolate(s1, s2, (double)mid / (double)nd, test);\n//            si_->getStateSpace()->interpolate(s1, s2, (double)mid / (double)nd, test);\n\n            if (!si_->isValid(test)) {\n                result = false;\n                break;\n            }\n\n            q.pop();\n            if (range.first < mid)\n                q.push(std::make_pair(range.first, mid - 1));\n            if (mid < range.second) {\n                q.push(std::make_pair(mid + 1, range.second));\n            } // if mid == first, no more recursion.\n        }\n    }\n\n    return result;\n}\n\nunsigned int ompl::geometric::HarmoniousLazyPRMstarMulti::validSegmentCount_compare(const double dist,\n                                                                                    const double longestValidSegment) const {\n    return si_->getStateSpace()->getValidSegmentCountFactor() * (unsigned int)ceil(dist / longestValidSegment);\n}\n\nvoid ompl::geometric::HarmoniousLazyPRMstarMulti::interpolate(const base::State *from, const base::State *to, const double t, base::State *state) const\n{\n    const base::RealVectorStateSpace::StateType *rfrom = static_cast<const base::RealVectorStateSpace::StateType*>(from);\n    const base::RealVectorStateSpace::StateType *rto = static_cast<const base::RealVectorStateSpace::StateType*>(to);\n    const base::RealVectorStateSpace::StateType *rstate = static_cast<base::RealVectorStateSpace::StateType*>(state);\n    for (unsigned int i = 0 ; i < isContinuous_.size() ; ++i){\n        if(isContinuous_[i]){\n            double diff = rto->values[i] - rfrom->values[i];\n            if (fabs(diff) <= boost::math::constants::pi<double>())\n                rstate->values[i] = rfrom->values[i] + diff * t;\n            else\n            {\n                double &v = rstate->values[i];\n                if (diff > 0.0)\n                    diff = 2.0 * boost::math::constants::pi<double>() - diff;\n                else\n                    diff = -2.0 * boost::math::constants::pi<double>() - diff;\n                v = rfrom->values[i] - diff * t;\n                // input states are within bounds, so the following check is sufficient\n                if (v > boost::math::constants::pi<double>())\n                    v -= 2.0 * boost::math::constants::pi<double>();\n                else\n                if (v < -boost::math::constants::pi<double>())\n                    v += 2.0 * boost::math::constants::pi<double>();\n            }\n        }\n        else{\n            rstate->values[i] = rfrom->values[i] + (rto->values[i] - rfrom->values[i]) * t;\n        }\n    }\n}\n", "meta": {"hexsha": "18eaf99a121145b31560a9a4a7862fc5457e880f", "size": 30511, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "harmonious_sampling/src/HarmoniousLazyPRMstarMulti.cpp", "max_stars_repo_name": "cheulkang/HarmoniousSampling", "max_stars_repo_head_hexsha": "40a5f89ab1f4a680160a61b13daba09cdf661b8b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-11-06T06:01:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-22T04:46:19.000Z", "max_issues_repo_path": "harmonious_sampling/src/HarmoniousLazyPRMstarMulti.cpp", "max_issues_repo_name": "cheulkang/HarmoniousSampling", "max_issues_repo_head_hexsha": "40a5f89ab1f4a680160a61b13daba09cdf661b8b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "harmonious_sampling/src/HarmoniousLazyPRMstarMulti.cpp", "max_forks_repo_name": "cheulkang/HarmoniousSampling", "max_forks_repo_head_hexsha": "40a5f89ab1f4a680160a61b13daba09cdf661b8b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-01T12:50:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-27T07:33:42.000Z", "avg_line_length": 36.1076923077, "max_line_length": 157, "alphanum_fraction": 0.6104028055, "num_tokens": 7408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23257595311142057}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/lambda/lambda.hpp>\n\n#include \"tudat/interface/spice/spiceEphemeris.h\"\n#include \"tudat/astro/ephemerides/customEphemeris.h\"\n#include \"tudat/astro/ephemerides/keplerEphemeris.h\"\n#include \"tudat/astro/ephemerides/multiArcEphemeris.h\"\n#include \"tudat/astro/ephemerides/tabulatedEphemeris.h\"\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/astro/ephemerides/approximatePlanetPositionsCircularCoplanar.h\"\n#include \"tudat/astro/ephemerides/constantEphemeris.h\"\n#include \"tudat/math/interpolators/lagrangeInterpolator.h\"\n#include \"tudat/simulation/environment_setup/createEphemeris.h\"\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\nusing namespace ephemerides;\n\n//! Function to create an ephemeris model.\nstd::shared_ptr< ephemerides::Ephemeris > createBodyEphemeris(\n        const std::shared_ptr< EphemerisSettings > ephemerisSettings,\n        const std::string& bodyName )\n{\n    // Declare return object.\n    std::shared_ptr< ephemerides::Ephemeris > ephemeris;\n\n    if( ephemerisSettings->getMakeMultiArcEphemeris( ) )\n    {\n        std::map< double, std::shared_ptr< Ephemeris > > singleArcEphemerides;\n        ephemerisSettings->resetMakeMultiArcEphemeris( false );\n\n        singleArcEphemerides[ -std::numeric_limits< double >::lowest( ) ] = createBodyEphemeris(\n                    ephemerisSettings, bodyName );\n\n        ephemeris = std::make_shared< MultiArcEphemeris >(\n                    singleArcEphemerides, ephemerisSettings->getFrameOrigin( ), ephemerisSettings->getFrameOrientation( ) );\n    }\n    else\n    {\n\n        // Check which type of ephemeris model is to be created.\n        switch( ephemerisSettings->getEphemerisType( ) )\n        {\n        case direct_spice_ephemeris:\n        {\n            // Check consistency of type and class.\n            std::shared_ptr< DirectSpiceEphemerisSettings > directEphemerisSettings =\n                    std::dynamic_pointer_cast< DirectSpiceEphemerisSettings >( ephemerisSettings );\n            if( directEphemerisSettings == nullptr )\n            {\n                throw std::runtime_error(\n                            \"Error, expected direct spice ephemeris settings for body \" + bodyName );\n            }\n            else\n            {\n                std::string inputName = ( directEphemerisSettings->getBodyNameOverride( ) == \"\" ) ?\n                            bodyName : directEphemerisSettings->getBodyNameOverride( );\n\n                // Create corresponding ephemeris object.\n                ephemeris = std::make_shared< SpiceEphemeris >(\n                            inputName,\n                            directEphemerisSettings->getFrameOrigin( ),\n                            directEphemerisSettings->getCorrectForStellarAberration( ),\n                            directEphemerisSettings->getCorrectForLightTimeAberration( ),\n                            directEphemerisSettings->getConvergeLighTimeAberration( ),\n                            directEphemerisSettings->getFrameOrientation( ) );\n            }\n            break;\n        }\n        case interpolated_spice:\n        {\n            // Check consistency of type and class.\n            std::shared_ptr< InterpolatedSpiceEphemerisSettings > interpolatedEphemerisSettings =\n                    std::dynamic_pointer_cast< InterpolatedSpiceEphemerisSettings >(\n                        ephemerisSettings );\n            if( interpolatedEphemerisSettings == nullptr )\n            {\n                throw std::runtime_error(\n                            \"Error, expected tabulated spice ephemeris settings for body \" + bodyName );\n            }\n            else\n            {\n                // Since only the barycenters of planetary systems are included in the standard DE\n                // ephemerides, append 'Barycenter' to body name.\n                std::string inputName = ( interpolatedEphemerisSettings->getBodyNameOverride( ) == \"\" ) ?\n                            bodyName : interpolatedEphemerisSettings->getBodyNameOverride( );\n                // Create corresponding ephemeris object.\n                if( !interpolatedEphemerisSettings->getUseLongDoubleStates( ) )\n                {\n                    ephemeris = createTabulatedEphemerisFromSpice< double, double >(\n                                inputName,\n                                interpolatedEphemerisSettings->getInitialTime( ),\n                                interpolatedEphemerisSettings->getFinalTime( ),\n                                interpolatedEphemerisSettings->getTimeStep( ),\n                                interpolatedEphemerisSettings->getFrameOrigin( ),\n                                interpolatedEphemerisSettings->getFrameOrientation( ),\n                                interpolatedEphemerisSettings->getInterpolatorSettings( ) );\n                }\n                else\n                {\n#if( TUDAT_BUILD_WITH_EXTENDED_PRECISION_PROPAGATION_TOOLS )\n\n                    ephemeris = createTabulatedEphemerisFromSpice< long double, double >(\n                                inputName,\n                                static_cast< long double >( interpolatedEphemerisSettings->getInitialTime( ) ),\n                                static_cast< long double >( interpolatedEphemerisSettings->getFinalTime( ) ),\n                                static_cast< long double >( interpolatedEphemerisSettings->getTimeStep( ) ),\n                                interpolatedEphemerisSettings->getFrameOrigin( ),\n                                interpolatedEphemerisSettings->getFrameOrientation( ),\n                                interpolatedEphemerisSettings->getInterpolatorSettings( ) );\n#else\n                    throw std::runtime_error( \"Error, long double compilation is turned off; requested long double tabulated ephemeris\" );\n#endif\n                }\n            }\n            break;\n        }\n        case tabulated_ephemeris:\n        {\n            // Check consistency of type and class.\n            std::shared_ptr< TabulatedEphemerisSettings > tabulatedEphemerisSettings =\n                    std::dynamic_pointer_cast< TabulatedEphemerisSettings >( ephemerisSettings );\n            if( tabulatedEphemerisSettings == nullptr )\n            {\n                throw std::runtime_error(\n                            \"Error, expected tabulated ephemeris settings for body \" + bodyName );\n            }\n            else\n            {\n                // Create corresponding ephemeris object.\n                if( !tabulatedEphemerisSettings->getUseLongDoubleStates( ) )\n                {\n                    if( tabulatedEphemerisSettings->getBodyStateHistory( ).size( ) != 0 )\n                    {\n                        ephemeris = std::make_shared< TabulatedCartesianEphemeris< > >(\n                                    std::make_shared<\n                                    interpolators::LagrangeInterpolator< double, Eigen::Vector6d > >\n                                    ( tabulatedEphemerisSettings->getBodyStateHistory( ), 6,\n                                      interpolators::huntingAlgorithm,\n                                      interpolators::lagrange_cubic_spline_boundary_interpolation ),\n                                    tabulatedEphemerisSettings->getFrameOrigin( ),\n                                    tabulatedEphemerisSettings->getFrameOrientation( ) );\n                    }\n                    else\n                    {\n                        ephemeris = std::make_shared< TabulatedCartesianEphemeris< > >(\n                                    std::shared_ptr< interpolators::OneDimensionalInterpolator< double, Eigen::Vector6d > >( ),\n                                      tabulatedEphemerisSettings->getFrameOrigin( ),\n                                      tabulatedEphemerisSettings->getFrameOrientation( ) );\n                    }\n                }\n                else\n                {\n#if( TUDAT_BUILD_WITH_EXTENDED_PRECISION_PROPAGATION_TOOLS )\n\n                    // Cast input history to required type.\n                    if( tabulatedEphemerisSettings->getBodyStateHistory( ).size( ) != 0 )\n                    {\n                        std::map< double, Eigen::Vector6d > originalStateHistory =\n                                tabulatedEphemerisSettings->getBodyStateHistory( );\n                        std::map< double, Eigen::Matrix< long double, 6, 1 > > longStateHistory;\n\n                        for( std::map< double, Eigen::Vector6d >::const_iterator stateIterator =\n                             originalStateHistory.begin( ); stateIterator != originalStateHistory.end( ); stateIterator++ )\n                        {\n                            longStateHistory[ stateIterator->first ] = stateIterator->second.cast< long double >( );\n                            ephemeris =\n                                    std::make_shared< TabulatedCartesianEphemeris< long double, double > >(\n                                        std::make_shared< interpolators::LagrangeInterpolator<\n                                        double, Eigen::Matrix< long double, 6, 1 > > >\n                                        ( longStateHistory, 6,\n                                          interpolators::huntingAlgorithm,\n                                          interpolators::lagrange_cubic_spline_boundary_interpolation ),\n                                        tabulatedEphemerisSettings->getFrameOrigin( ),\n                                        tabulatedEphemerisSettings->getFrameOrientation( ) );\n                        }\n                    }\n                    else\n                    {\n                        ephemeris = std::make_shared< TabulatedCartesianEphemeris< long double, double > >(\n                                    std::shared_ptr< interpolators::OneDimensionalInterpolator<\n                                    double, Eigen::Matrix< long double, 6, 1 > > >( ),\n                                      tabulatedEphemerisSettings->getFrameOrigin( ),\n                                      tabulatedEphemerisSettings->getFrameOrientation( ) );\n                    }\n#else\n                    throw std::runtime_error( \"Error, long double compilation is turned off; requested long double tabulated ephemeris\" );\n#endif\n                }\n            }\n            break;\n        }\n        case auto_generated_tabulated_ephemeris:\n        {\n            // Check consistency of type and class.\n            std::shared_ptr< AutoGeneratedTabulatedEphemerisSettings > tabulatedEphemerisSettings =\n                    std::dynamic_pointer_cast< AutoGeneratedTabulatedEphemerisSettings >( ephemerisSettings );\n            if( tabulatedEphemerisSettings == nullptr )\n            {\n                throw std::runtime_error( \"Error, expected auto-generate tabulated ephemeris settings for \" + bodyName );\n            }\n            else\n            {\n                // Create ephemeris\n                ephemeris = getTabulatedEphemeris(\n                            createBodyEphemeris( tabulatedEphemerisSettings->getEphemerisSettings( ), bodyName ),\n                            tabulatedEphemerisSettings->getStartTime( ), tabulatedEphemerisSettings->getEndTime( ),\n                            tabulatedEphemerisSettings->getTimeStep( ), tabulatedEphemerisSettings->getInterpolatorSettings( ) );\n            }\n            break;\n        }\n        case constant_ephemeris:\n        {\n            // Check consistency of type and class.\n            std::shared_ptr< ConstantEphemerisSettings > constantEphemerisSettings =\n                    std::dynamic_pointer_cast< ConstantEphemerisSettings >( ephemerisSettings );\n            if( constantEphemerisSettings == nullptr )\n            {\n                throw std::runtime_error( \"Error, expected constant ephemeris settings for \" + bodyName );\n            }\n            else\n            {\n                // Create ephemeris\n                ephemeris = std::make_shared< ConstantEphemeris >(\n                            [ = ]( ){ return constantEphemerisSettings->getConstantState( ); },\n                            constantEphemerisSettings->getFrameOrigin( ),\n                            constantEphemerisSettings->getFrameOrientation( ) );\n            }\n            break;\n        }\n        case custom_ephemeris:\n        {\n            // Check consistency of type and class.\n            std::shared_ptr< CustomEphemerisSettings > customEphemerisSettings =\n                    std::dynamic_pointer_cast< CustomEphemerisSettings >( ephemerisSettings );\n            if( customEphemerisSettings == nullptr )\n            {\n                throw std::runtime_error( \"Error, expected custom ephemeris settings for \" + bodyName );\n            }\n            else\n            {\n                // Create ephemeris\n                ephemeris = std::make_shared< CustomEphemeris >(\n                            customEphemerisSettings->getCustomStateFunction( ),\n                            customEphemerisSettings->getFrameOrigin( ),\n                            customEphemerisSettings->getFrameOrientation( ) );\n            }\n            break;\n        }\n\n        case kepler_ephemeris:\n        {\n            // Check consistency of type and class.\n            std::shared_ptr< KeplerEphemerisSettings > keplerEphemerisSettings =\n                    std::dynamic_pointer_cast< KeplerEphemerisSettings >( ephemerisSettings );\n            if( keplerEphemerisSettings == nullptr )\n            {\n                throw std::runtime_error( \"Error, expected Kepler ephemeris settings for \" + bodyName );\n            }\n            else\n            {\n                // Create ephemeris\n                ephemeris = std::make_shared< KeplerEphemeris >(\n                            keplerEphemerisSettings->getInitialStateInKeplerianElements( ),\n                            keplerEphemerisSettings->getEpochOfInitialState( ),\n                            keplerEphemerisSettings->getCentralBodyGravitationalParameter( ),\n                            keplerEphemerisSettings->getFrameOrigin( ),\n                            keplerEphemerisSettings->getFrameOrientation( ),\n                            keplerEphemerisSettings->getRootFinderAbsoluteTolerance( ),\n                            keplerEphemerisSettings->getRootFinderMaximumNumberOfIterations( ) );\n            }\n            break;\n        }\n        case approximate_planet_positions:\n        {\n            // Check consistency of type and class.\n            std::shared_ptr< ApproximateJplEphemerisSettings > approximateEphemerisSettings =\n                    std::dynamic_pointer_cast< ApproximateJplEphemerisSettings >(\n                        ephemerisSettings );\n            if( approximateEphemerisSettings == nullptr )\n            {\n                throw std::runtime_error(\n                            \"Error, expected approximate ephemeris settings for body \" + bodyName );\n            }\n            else\n            {\n\n//                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData bodyToUse;\n//                if( approximateEphemerisSettings->getBodyIdentifier( ) ==\n//                        ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::undefined )\n//                {\n//                    try\n//                    {\n//                        bodyToUse = ephemerides::ApproximatePlanetPositionsBase::getBodiesWithEphemerisDataId( bodyName );\n//                    }\n//                    catch( std::runtime_error const& )\n\n//                    {\n//                        throw std::runtime_error( \"Error, approximate ephemeris not available for body: \" + bodyName + \" when creating ephemeris.\" );\n//                    }\n//                }\n//                else\n//                {\n//                    bodyToUse = approximateEphemerisSettings->getBodyIdentifier( );\n//                }\n//=======\n//>>>>>>> origin/feature/mga_estimation_refactor_merge\n\n                // Create corresponding ephemeris object.\n                if( approximateEphemerisSettings->getUseCircularCoplanarApproximation( ) )\n                {\n                    ephemeris = std::make_shared< ApproximateJplCircularCoplanarEphemeris >(\n                                approximateEphemerisSettings->getBodyName( ) );\n                }\n                else\n                {\n                    ephemeris = std::make_shared< ApproximateJplEphemeris >(\n                                approximateEphemerisSettings->getBodyName( ) );\n                }\n            }\n            break;\n        }\n\t\tcase direct_tle_ephemeris:\n\t\t{\n\t\t\t// Check consistency of type and class.\n\t\t\tstd::shared_ptr< DirectTleEphemerisSettings > directTleEphemerisSettings =\n\t\t\t\t\tstd::dynamic_pointer_cast< DirectTleEphemerisSettings >( ephemerisSettings );\n\t\t\tif( directTleEphemerisSettings == nullptr )\n\t\t\t{\n\t\t\t\tthrow std::runtime_error(\n\t\t\t\t\t\t\"Error, expected direct TLE ephemeris settings for body \" + bodyName );\n\t\t\t}\n\t\t\t// Check if the Earth is present in the simulation\n\t\t\telse\n\t\t\t{\n\t\t\t\t//std::string inputName = bodyName;\n\n\t\t\t\t// Check period of the satellite for correct SDP setting\n\n\n\t\t\t\t// Create corresponding ephemeris object.\n\t\t\t\tephemeris = std::make_shared< TleEphemeris >(\n\t\t\t\t\t\tdirectTleEphemerisSettings->getFrameOrigin(),\n\t\t\t\t\t\tdirectTleEphemerisSettings->getFrameOrientation(),\n\t\t\t\t\t\tdirectTleEphemerisSettings->getTle()\n\t\t\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase interpolated_tle_ephemeris:\n\t\t{\n\t\t\t// Check consistency of type and class.\n\t\t\tstd::shared_ptr< InterpolatedTleEphemerisSettings > interpolatedTleEphemerisSettings =\n\t\t\t\t\tstd::dynamic_pointer_cast< InterpolatedTleEphemerisSettings >(\n\t\t\t\t\t\t\tephemerisSettings );\n\t\t\tif( interpolatedTleEphemerisSettings == nullptr )\n\t\t\t{\n\t\t\t\tthrow std::runtime_error(\n\t\t\t\t\t\t\"Error, expected interpolated TLE ephemeris settings for body \" + bodyName );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\n\t\t\t\tephemeris = createTabulatedEphemerisFromTLE< double, double >(\n\t\t\t\t\t\tbodyName,\n\t\t\t\t\t\tinterpolatedTleEphemerisSettings->getInitialTime( ),\n\t\t\t\t\t\tinterpolatedTleEphemerisSettings->getFinalTime( ),\n\t\t\t\t\t\tinterpolatedTleEphemerisSettings->getTimeStep( ),\n\t\t\t\t\t\tinterpolatedTleEphemerisSettings->getFrameOrigin( ),\n\t\t\t\t\t\tinterpolatedTleEphemerisSettings->getFrameOrientation( ),\n\t\t\t\t\t\tinterpolatedTleEphemerisSettings->getTle( ),\n\t\t\t\t\t\tinterpolatedTleEphemerisSettings->getInterpolatorSettings( )\n\t\t\t\t\t\t);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n        case scaled_ephemeris:\n        {\n            // Check consistency of type and class.\n            std::shared_ptr< ScaledEphemerisSettings > scaledEphemeriSettings =\n                    std::dynamic_pointer_cast< ScaledEphemerisSettings >(\n                        ephemerisSettings );\n            if( scaledEphemeriSettings == nullptr )\n            {\n                throw std::runtime_error(\n                            \"Error, expected scaled ephemeris settings for body \" + bodyName );\n            }\n            else\n            {\n                std::shared_ptr< Ephemeris > baseEphemeris = createBodyEphemeris(\n                            scaledEphemeriSettings->getBaseSettings( ), bodyName );\n                ephemeris = std::make_shared< ScaledEphemeris >(\n                            baseEphemeris, scaledEphemeriSettings->getScaling( ), scaledEphemeriSettings->getIsScalingAbsolute( ) );\n            }\n            break;\n        }\n        default:\n        {\n            throw std::runtime_error(\n                        \"Error, did not recognize ephemeris model settings type \" +\n                        std::to_string( ephemerisSettings->getEphemerisType( ) ) );\n        }\n        }\n    }\n    return ephemeris;\n\n}\n\n//! Function that retrieves the time interval at which an ephemeris can be safely interrogated\nstd::pair< double, double > getSafeInterpolationInterval( const std::shared_ptr< ephemerides::Ephemeris > ephemerisModel )\n{\n    // Make default output pair\n    std::pair< double, double > safeInterval = std::make_pair(\n                std::numeric_limits< double >::lowest( ),  std::numeric_limits< double >::max( ) );\n\n    // Check if model is tabulated, and retrieve safe interval from model\n    if( isTabulatedEphemeris( ephemerisModel ) )\n    {\n        safeInterval = getTabulatedEphemerisSafeInterval( ephemerisModel );\n    }\n    // Check if model is multi-arc, and retrieve safe intervals from first and last arc.\n    else if( std::dynamic_pointer_cast< ephemerides::MultiArcEphemeris >( ephemerisModel ) != nullptr )\n    {\n        std::shared_ptr< ephemerides::MultiArcEphemeris > multiArcEphemerisModel  =\n                std::dynamic_pointer_cast< ephemerides::MultiArcEphemeris >( ephemerisModel );\n        safeInterval.first = getSafeInterpolationInterval( multiArcEphemerisModel->getSingleArcEphemerides( ).at( 0 ) ).first;\n        safeInterval.second = getSafeInterpolationInterval(\n                    multiArcEphemerisModel->getSingleArcEphemerides( ).at(\n                        multiArcEphemerisModel->getSingleArcEphemerides( ).size( ) - 1 ) ).second;\n    }\n    return safeInterval;\n}\n\n\n} // namespace simulation_setup\n\n} // namespace tudat\n", "meta": {"hexsha": "51e834759eda97b40f7a08b525c5fa2fa18f971e", "size": 21474, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation/environment_setup/createEphemeris.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation/environment_setup/createEphemeris.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation/environment_setup/createEphemeris.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6141906874, "max_line_length": 151, "alphanum_fraction": 0.5736704852, "num_tokens": 4656, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.23252493517189746}}
{"text": "#include \"diffuclass.h\"\n#include <iostream>\n#include <math.h>\n#include <boost/filesystem.hpp>\n\n//------------------------------------------------------------------------------\n//                           Declare functions\n//------------------------------------------------------------------------------\n\nextern PetscErrorCode ComputeMatrix(KSP, Mat, Mat, void*);\n\nPetscErrorCode MyMatMult(Mat,Vec,Vec);\n\n\n//------------------------------------------------------------------------------\n//\t\t\t\t\t\t\t  Public Methods\n//------------------------------------------------------------------------------\n//TODO: include all boundary condition elements and individually parallelized grids\nvoid diffusionPETSc::initDiffusion(eQ::diffusionSolver::params &initParams)\n//void diffusionPETSc::initDiffusion(MPI_Comm comm, std::vector<std::string> filePaths, int argc, char* argv[])\n{\n    auto argc = initParams.argc;\n    auto argv = initParams.argv;\n    int \t i, j;\n\n    /*\n    //Split input communicator into subcommunicators for each desired diffusion grid\n    MPI_Comm subComm;\n    int \t myRankMPI, commSize, i, j;\n\n    MPI_Comm_size(comm, &commSize);\n    MPI_Comm_rank(comm, &myRankMPI);\n\n    MPI_Comm_split(comm, myRankMPI, 0, &subComm);\n\n    initData.subCommunicator = subComm;\n    //Record vector of diffusion constants and choose the appropriate constant for each processor\n    std::vector<double>\t\td_vector;\n    d_vector = std::vector<double>(eQ::data::parameters[\"D_HSL\"].get<std::vector<double>>());\n    initData.diffusionConstant = d_vector.at(myRankMPI % d_vector.size());\n\n    //Set domain size based on parameters\n    initData.xLengthMicrons = int(eQ::data::parameters[\"simulationTrapWidthMicrons\"]);\n    initData.yLengthMicrons = int(eQ::data::parameters[\"simulationTrapHeightMicrons\"]);\n\n    //Set time step\n    initData.dt = eQ::data::parameters[\"dt\"];\n\n    //Set grid spacing in domain\n    initData.h = 1 / double(eQ::data::parameters[\"nodesPerMicronSignaling\"]);\n\n    //Set the appropriate filepath to each grid for data recording\n    initData.directoryName = filePaths.at(myRankMPI % d_vector.size());\n*/\n    initData.subCommunicator = initParams.comm;\n    initData.diffusionConstant = initParams.D_HSL;//direct read from init params\n    initData.xLengthMicrons = initParams.trapWidthMicrons;\n    initData.yLengthMicrons = initParams.trapHeightMicrons;\n    initData.dt = initParams.dt;\n    initData.h = 1.0 / initParams.nodesPerMicron;\n\n    initData.directoryName = initParams.filePath + \"petsc\";\n     boost::filesystem::path dstFolder = initData.directoryName;\n     boost::filesystem::create_directory(dstFolder);\n\n     initData.objectName = \"grid\";\n\n    //Set initial boundary conditions\n    if(\"DIRICHLET_0\" == eQ::data::parameters[\"boundaryType\"]){\n        initData.homogeneousDirichlet = PETSC_TRUE;\n\n        initData.topDirichletCoefficient = 1;\n        initData.bottomDirichletCoefficient = 1;\n        initData.leftDirichletCoefficient = 1;\n        initData.rightDirichletCoefficient = 1;\n\n        initData.topNeumannCoefficient = 0;\n        initData.bottomNeumannCoefficient = 0;\n        initData.leftNeumannCoefficient = 0;\n        initData.rightNeumannCoefficient = 0;\n\n        initData.topBoundaryValue = 0;\n        initData.bottomBoundaryValue = 0;\n        initData.leftBoundaryValue = 0;\n        initData.rightBoundaryValue = 0;\n    }\n\n    //Initialize PETSc element of diffusion\n    InitializeDiffusion(&initData, argc, argv);\n\n    //Resize and populate vectors for data transfer\n    solution_vector.resize(gridNodesX * gridNodesY);\n    allXCoordinates.resize(gridNodesX * gridNodesY);\n    allYCoordinates.resize(gridNodesX * gridNodesY);\n\n    for (j=0; j < gridNodesY; j++){\n        for (i=0; i < gridNodesX; i++){\n            allXCoordinates.at(i + j * gridNodesX) = i*initData.h;\n            allYCoordinates.at(i + j * gridNodesX) = j*initData.h;\n            solution_vector.at(i + j * gridNodesX) = 0;\n        }\n    }\n\n    //Copy initial conditions to solution vector\n    ReadGridValues(allXCoordinates, allYCoordinates, &solution_vector);\n}\n\nvoid diffusionPETSc::stepDiffusion(void)\n{\n    //Copy modified solution vector to u0\n    //solution_vector is our public vector of all solution data - copy that over.\n\n    WriteGridValues(allXCoordinates, allYCoordinates, solution_vector);\n\n    TimeStep();\n\n    ReadGridValues(allXCoordinates, allYCoordinates, &solution_vector);\n}\n\n//TODO: implement each wall separately\nvoid diffusionPETSc::setBoundaryValues(const eQ::data::parametersType &bvals)\n{\n    //JW: over-ride for now: set boundaries explicitly by writing the data structures\n    return;\n\n    if(bool(bvals[\"allBoundaries\"]) == true){\n        gridData->topBoundaryValue = double(bvals[\"boundaryValue\"]);\n        gridData->bottomBoundaryValue = double(bvals[\"boundaryValue\"]);\n        gridData->leftBoundaryValue = double(bvals[\"boundaryValue\"]);\n        gridData->rightBoundaryValue = double(bvals[\"boundaryValue\"]);\n    }\n}\n\n//TODO: verify accuracy, check about choosing walls\neQ::data::parametersType diffusionPETSc::getBoundaryFlux(void)\n{\n    //Compute and return boundary flux across all walls\n    eQ::data::parametersType \tfluxData;\n    double \t\t\t   \ttotalBoundaryFlux, boundarySlope;\n    int \t\t\t\ti, j;\n\n    for (i = 0; i < gridNodesX; i++){\n        for (j = 0; j < gridNodesY; j++){\n            if (i == 0){\n                boundarySlope = boundarySlope + (solution_vector.at(2 + (gridNodesX) * j) - \\\n                        solution_vector.at((gridNodesX)*j))/(2*gridData->h);\n            }\n            else if (i == gridNodesX - 1){\n                boundarySlope = boundarySlope + (solution_vector.at(i - 2 + (gridNodesX-1)*j) - \\\n                        solution_vector.at(i + (gridNodesX-1)*j))/(2*gridData->h);\n            }\n            else if (j == 0){\n                boundarySlope = boundarySlope + (solution_vector.at(i + (gridNodesX-1) * 2) - \\\n                        solution_vector.at(i))/(2*gridData->h);\n            }\n            else if (j == gridNodesY - 1){\n                boundarySlope = boundarySlope + (solution_vector.at(i + (gridNodesX-1) * (j - 2)) - \\\n                        solution_vector.at(i + (gridNodesX-1)*j))/(2*gridData->h);\n            }\n        }\n    }\n\n    totalBoundaryFlux = gridData->diffusionConstant * gridData->dt * boundarySlope;\n    fluxData[\"totalFlux\"] = totalBoundaryFlux;\n    return fluxData;\n}\n\nvoid diffusionPETSc::writeDiffusionFiles(double timestamp)\n{\n    //Work in timestamp\n    RecordData();\n}\n\n/*\nvoid diffusionPETSc::writeDataFiles(double dt)\n{\n    //Need to write full function\n}\n*/\n\nvoid diffusionPETSc::finalize(void)\n{\n    DiffusionFinalize(PETSC_TRUE);\n}\n\n\n//------------------------------------------------------------------------------\n//                            Private Methods\n//------------------------------------------------------------------------------\n\nPetscErrorCode diffusionPETSc::ApplyBoundaryConditions()\n{\n  //Applys Neumann/Robin Boundary Conditions to RHS vector\n  PetscInt       i,j,xm,ym,xs,ys;\n  PetscScalar    **RHSarray;\n\n  //Get subgrid information for each processor and get arrays from vector\n  ierr = DMDAGetCorners(distributedArray,&xs,&ys,0,&xm,&ym,0);CHKERRQ(ierr);\n  ierr = DMDAVecGetArray(distributedArray, globalVector, &RHSarray);CHKERRQ(ierr);\n\n  //JW NOTE:  each node can check its range whether it has boundary points\n  //  then, traverse the boundary explicitly, rather than traversing the entire i,j space\n    const double twoFh = 2 * gridData->fourierNumber * gridData->h;//\n//    double topD = gridData->topDirichletCoefficient;\n//    double bottomD = gridData->bottomDirichletCoefficient;\n//    double leftD = gridData->leftDirichletCoefficient;\n//    double rightD = gridData->rightDirichletCoefficient;\n        const double topN = gridData->topNeumannCoefficient;\n        const double bottomN = gridData->bottomNeumannCoefficient;\n        const double leftN = gridData->leftNeumannCoefficient;\n        const double rightN = gridData->rightNeumannCoefficient;\n\n  //Alter values in arrays to match Boundary Conditions\n  for (j = ys; j < ys+ym; j++){\n    for (i = xs; i < xs+xm; i++){\n//      if (i == 0 || i == gridNodesX-1 || j == 0 || j == gridNodesY-1){\n\n          //TOP WALL\n          if(j == gridNodesY-1)\n          {\n              const double topBV = topBoundaryValue[i];\n              //Set non-Dirichlet for top wall\n              if (topN != 0)\n              {//if TL (TR) corner, only set to N if left (right) wall is N\n                  if ((i != 0 || leftN != 0) && (i != gridNodesX-1 || rightN != 0))\n                        RHSarray[j][i] += (twoFh * topBV) / topN;\n              }\n              else\n//                  RHSarray[j][i] = topBV / topD;\n                  RHSarray[j][i] = topBV;//if N==0, then D must be 1\n          }\n          //BOTTOM WALL\n          else if(j == 0)\n          {\n              const double bottomBV = bottomBoundaryValue[i];\n              //Set non-Dirichlet for bottom wall\n              if (bottomN != 0)\n              {\n                  if ((i != 0 || leftN != 0) && (i != gridNodesX-1 || rightN != 0))\n                        RHSarray[j][i] +=  (twoFh * bottomBV) / bottomN;\n              }\n              else\n//                  RHSarray[j][i] = bottomBV / bottomD;\n                  RHSarray[j][i] = bottomBV;//if N==0, then D must be 1\n          }\n          //RIGHT WALL\n          if(i == gridNodesX-1)\n          {\n              const double rightBV = gridData->rightBoundaryValue;\n              //Set non-Dirichlet for right wall\n              if (rightN != 0)\n              {\n                  if ((j != 0 || bottomN != 0) && (j != gridNodesY-1 || topN != 0))\n                      RHSarray[j][i] += (twoFh * rightBV) / rightN;\n              }\n              else\n//                  RHSarray[j][i] = rightBV / rightD;\n                  RHSarray[j][i] = rightBV;//if N==0, then D must be 1\n          }\n          //LEFT WALL\n          else if(i == 0)\n          {\n              const double leftBV = gridData->leftBoundaryValue;\n              //Set non-Dirichlet for left wall\n              if (leftN != 0)\n              {\n                  if ((j != 0 || bottomN != 0) && (j != gridNodesY-1 || topN != 0))\n                      RHSarray[j][i] += (twoFh * leftBV) / leftN;\n              }\n              else\n//                  RHSarray[j][i] = leftBV / leftD;\n                  RHSarray[j][i] = leftBV;//if N==0, then D must be 1\n          }\n//      }\n    }\n  }\n/*\n  //Alter values in arrays to match Boundary Conditions\n  for (j = ys; j < ys+ym; j++){\n    for (i = xs; i < xs+xm; i++){\n      if (i == 0 || i == gridNodesX-1 || j == 0 || j == gridNodesY-1){\n        //Set non-Dirichlet for top wall\n        if (gridData->topNeumannCoefficient != 0 && j == gridNodesY-1){\n          //Only change corners if they are also Neumann Boundary Conditions\n          if ((i != 0 || gridData->leftNeumannCoefficient != 0) &&\n              (i != gridNodesX-1 || gridData->rightNeumannCoefficient != 0)){\n                RHSarray[j][i] = RHSarray[j][i] + (2 * gridData->fourierNumber * gridData->h * \\\n                  gridData->topBoundaryValue) / gridData->topNeumannCoefficient;\n          }\n        }\n        //Set non-Dirichlet for bottom wall\n        if (gridData->bottomNeumannCoefficient != 0 && j == 0){\n          //Only change corners if they are also Neumann Boundary Conditions\n          if ((i != 0 || gridData->leftNeumannCoefficient != 0) &&\n              (i != gridNodesX-1 || gridData->rightNeumannCoefficient != 0)){\n            RHSarray[j][i] = RHSarray[j][i] + (2 * gridData->fourierNumber * gridData->h * \\\n              gridData->bottomBoundaryValue) / gridData->bottomNeumannCoefficient;\n          }\n        }\n        //Set non-Dirichlet for left wall\n        if (gridData->leftNeumannCoefficient != 0 && i == 0){\n          //Only change corners if they are also Neumann Boundary Conditions\n          if ((j != 0 || gridData->bottomNeumannCoefficient != 0) &&\n              (j != gridNodesY-1 || gridData->topNeumannCoefficient != 0)){\n            RHSarray[j][i] = RHSarray[j][i] + (2 * gridData->fourierNumber * gridData->h * \\\n              gridData->leftBoundaryValue) / gridData->leftNeumannCoefficient;\n          }\n        }\n        //Set non-Dirichlet for right wall\n        if (gridData->rightNeumannCoefficient != 0 && i == gridNodesX-1){\n          //Only change corners if they are also Neumann Boundary Conditions\n          if ((j != 0 || gridData->bottomNeumannCoefficient != 0) &&\n              (j != gridNodesY-1 || gridData->topNeumannCoefficient != 0)){\n            RHSarray[j][i] = RHSarray[j][i] + (2 * gridData->fourierNumber * gridData->h * \\\n              gridData->rightBoundaryValue) / gridData->rightNeumannCoefficient;\n          }\n        }\n\n        //Otherwise, set Dirichlet conditions\n        if (gridData->topNeumannCoefficient == 0 && j == gridNodesY-1){\n          RHSarray[j][i] = gridData->topBoundaryValue / gridData->topDirichletCoefficient;\n        }\n        else if (gridData->bottomNeumannCoefficient == 0 && j == 0){\n          RHSarray[j][i] = gridData->bottomBoundaryValue / gridData->bottomDirichletCoefficient;\n        }\n        else if (gridData->leftNeumannCoefficient == 0 && i == 0){\n          RHSarray[j][i] = gridData->leftBoundaryValue / gridData->leftDirichletCoefficient;\n        }\n        else if (gridData->rightNeumannCoefficient == 0 && i == gridNodesX-1){\n          RHSarray[j][i] = gridData->rightBoundaryValue / gridData->rightDirichletCoefficient;\n        }\n      }\n    }\n  }\n*/\n  ierr = DMDAVecRestoreArray(distributedArray, globalVector, &RHSarray);CHKERRQ(ierr);\n\n  return ierr;\n}\n\n//Figure out argc and argv\nPetscErrorCode diffusionPETSc::InitializeDiffusion (DiffusionData *dataStruct, int argc, char **argv)\n{\n  //Initializes sets data values, inializes PETSc, and otherwise takes care of\n  //all preparation needed in order to iterate. It should be noted that this\n  //function does NOT set any initial conditions.\n\n  gridData = dataStruct;\n  //Initialize PETSc and assign passed communicator to DIFFU_COMM\n  DIFFU_COMM = gridData->subCommunicator;\n  ierr = PetscInitialize(&argc,&argv,(char*)0,NULL);\n  MPI_Comm_size(DIFFU_COMM, &commSize);\n\n  //Set up viewer for print statements\n  printViewer = PETSC_VIEWER_STDOUT_(DIFFU_COMM);\n\n  //Calculate crucial values for grid\n  gridNodesX = (gridData->xLengthMicrons/gridData->h) + 1;\n  gridNodesY = (gridData->yLengthMicrons/gridData->h) + 1;\n  gridData->totalNodes = gridNodesX * gridNodesY;\n  gridData->fourierNumber = (gridData->diffusionConstant*gridData->dt) / (gridData->h*gridData->h);\n\n  //Set boundary and stencil types for distributed array\n  boundary = DM_BOUNDARY_NONE;\n  stencilType = DMDA_STENCIL_STAR;\n\n  //Create Krylov Subspace method(KSP) context and Distributed Array(DMDA)\n  ierr = KSPCreate(DIFFU_COMM, &krylovSolver);CHKERRQ(ierr);\n  ierr = DMDACreate2d(DIFFU_COMM, boundary, boundary, stencilType, gridNodesX, gridNodesY, PETSC_DECIDE, \\\n    PETSC_DECIDE, 1, 1, NULL, NULL, &distributedArray);CHKERRQ(ierr);\n\n  //Configure DMDA\n  ierr = DMSetFromOptions(distributedArray);CHKERRQ(ierr);\n  ierr = DMSetUp(distributedArray);CHKERRQ(ierr);\n  ierr = DMDASetUniformCoordinates(distributedArray, 0, gridData->xLengthMicrons, 0, \\\n    gridData->yLengthMicrons, 0, 0);CHKERRQ(ierr);\n  ierr = DMView(distributedArray, printViewer);CHKERRQ(ierr);\n\n  //Create solution vector and local helper vector for scattering\n  ierr = DMCreateGlobalVector(distributedArray, &globalVector);CHKERRQ(ierr);\n  ierr = DMCreateLocalVector(distributedArray, &gridData->localVector);CHKERRQ(ierr);\n\n  //Obtain additional needed values for data structure\n  ierr = VecGetOwnershipRange(globalVector, &gridData->localMinimum, &gridData->localMaximum);CHKERRQ(ierr);\n\n  //Configure KSP\n  ierr = KSPSetDM(krylovSolver, distributedArray);CHKERRQ(ierr);\n  ierr = KSPSetComputeOperators(krylovSolver, ComputeMatrix, gridData);CHKERRQ(ierr);\n  ierr = KSPGetPC(krylovSolver, &preconditioner);CHKERRQ(ierr);\n  ierr = PCSetType(preconditioner, PCNONE);CHKERRQ(ierr);\n  ierr = KSPSetType(krylovSolver, KSPFBCGSR);\n  ierr = KSPSetFromOptions(krylovSolver);CHKERRQ(ierr);\n  ierr = KSPSetUp(krylovSolver);CHKERRQ(ierr);\n\n  //Prepare Application Ordering (AO)\n  ierr = DMDAGetAO(distributedArray, &appOrder);CHKERRQ(ierr);\n\n  ierr = PetscPrintf(DIFFU_COMM, \"\\nPETSC CLASS InitializeDiffusion(): %s \\n\", gridData->directoryName.c_str());CHKERRQ(ierr);\n\n  //Set initial timestep number\n  step = 0;\n  return ierr;\n}\n\nPetscErrorCode diffusionPETSc::TimeStep()\n{\n  //Takes a step forward in time in the simulation\n  step++;\n  ierr = ApplyBoundaryConditions();CHKERRQ(ierr);\n  ierr = KSPSolve(krylovSolver, globalVector, globalVector);CHKERRQ(ierr);\n  ierr = PetscPrintf(DIFFU_COMM,\"\\r%d steps complete\", step);CHKERRQ(ierr);\n  return ierr;\n}\n\n//Ensure vector references work as desired\nPetscErrorCode diffusionPETSc::WriteGridValues(vector<double> xCoordinates, vector<double> \\\n  yCoordinates, vector<double> values)\n{\n  //Takes values and their coordinates in vector form, converts coordinates to\n  //a discretized form, and then inserts the values into the grid based on these\n  //coordinates.\n\n  //Declare temporary variables for use in method\n  PetscInt      xm, ym, xs, ys, xindex, yindex;\n  unsigned int  size, i;\n  PetscScalar   **globalarray;\n\n  //Record size variable and check for size consistency across vectors\n  size = xCoordinates.size();\n  if (size != yCoordinates.size() || size != values.size()){\n    ierr = PetscPrintf(PETSC_COMM_SELF, \\\n        \"Error: vector sizes for WriteGridValues must match\\n\");CHKERRQ(ierr);\n  }\n\n  //Get coordinate range and array for all data on processor\n  ierr = DMDAGetCorners(distributedArray,&xs,&ys,0,&xm,&ym,0);CHKERRQ(ierr);\n  ierr = DMDAVecGetArray(distributedArray, globalVector, &globalarray);CHKERRQ(ierr);\n\n  //Iterate through all coordinates, filter out those not on processor, and\n  //insert values into grid\n  for (i=0; i<size; i++){\n    xindex = round(xCoordinates.at(i)/gridData->h);\n    yindex = round(yCoordinates.at(i)/gridData->h);\n    if (xindex >= xs && xindex < xs+xm && yindex >= ys && yindex < ys+ym){\n        globalarray[yindex][xindex] = values.at(i);\n    }\n  }\n\n  //Restore array to vector, finalizing the insert of these new values.\n  ierr = DMDAVecRestoreArray(distributedArray, globalVector, &globalarray);CHKERRQ(ierr);\n\n  return ierr;\n}\n\n//TODO: Ensure vector references work as desired\n//Extensively test commSize > 1 case - need MPI to properly share data?\nPetscErrorCode diffusionPETSc::ReadGridValues(vector<double> xCoordinates, vector<double> \\\n  yCoordinates, vector<double> *values)\n{\n  //Given some coordinates and a vector for values, discretizes the coordinates\n  //and finds the values associated with them in the grid. Puts these values\n  //into the given vector. Note that this only does so for on-process values.\n\n  //Record size variable and check for size consistency across vectors\n  unsigned int  readSize;\n  readSize = xCoordinates.size();\n  if (readSize != yCoordinates.size() || readSize != values->size()){\n    ierr = PetscPrintf(PETSC_COMM_SELF, \\\n    \"Error: vector sizes for ReadGridValues must match\\n\");CHKERRQ(ierr);\n    return ierr;\n  }\n\n  //Read values from grid - use alternative algorithm if grid is parallelized\n  if (commSize == 1){\n    //Declare temporary variables for use in method\n    PetscInt            xm, ym, xs, ys, xindex, yindex;\n    unsigned int        i;\n    PetscScalar         **readarray;\n\n\n    //Get coordinate range and array for all data on processor\n    ierr = DMDAGetCorners(distributedArray,&xs,&ys,0,&xm,&ym,0);CHKERRQ(ierr);\n    ierr = DMDAVecGetArrayRead(distributedArray, globalVector, &readarray);CHKERRQ(ierr);\n\n    //Get list of natural grid coordinates\n    for (i=0; i < readSize; i++){\n        xindex = round(xCoordinates.at(i)/gridData->h);\n        yindex = round(yCoordinates.at(i)/gridData->h);\n        if (xindex >= xs && xindex < xs+xm && yindex >= ys && yindex < ys+ym){\n            values->at(i) = readarray[yindex][xindex];\n        }\n    }\n\n    //Restore read array to vector\n    ierr = DMDAVecRestoreArrayRead(distributedArray, globalVector, &readarray);CHKERRQ(ierr);\n  }\n\n  else{\n    //Declare temporary variables for use in method\n    PetscInt \t\t   \txindex, yindex, globalIndex[readSize],\n                        localIndex[readSize];\n    unsigned int\t\ti;\n    const PetscScalar\t*readarray;\n    IS\t\t\t\t\tfrom, to;\n    Vec\t\t\t\t\tsequentialVector;\n    VecScatter\t\t\tscatter;\n\n    //Create index vector for later PETSc vector scattering\n    for (i=0; i < readSize; i++){\n        localIndex[i] = i;\n    }\n\n    //Get list of natural grid coordinates\n    for (i=0; i < readSize; i++){\n        xindex = round(xCoordinates.at(i)/gridData->h);\n        yindex = round(yCoordinates.at(i)/gridData->h);\n        globalIndex[i] = yindex*gridNodesX + xindex;\n    }\n\n    //Replace natural grid coordinates with PETSc grid coordinates\n    ierr = AOApplicationToPetsc(appOrder, readSize, globalIndex);CHKERRQ(ierr);\n\n    //Prepares index sets for PETSc vector scattering\n    ierr = ISCreateGeneral(DIFFU_COMM, readSize, globalIndex, PETSC_COPY_VALUES, &from);\n        CHKERRQ(ierr);\n    ierr = ISCreateGeneral(PETSC_COMM_SELF, readSize, localIndex, PETSC_COPY_VALUES, &to);\n        CHKERRQ(ierr);\n\n    //Create PETSc vector to be scattered to\n    ierr = VecCreateSeq(PETSC_COMM_SELF, readSize, &sequentialVector);CHKERRQ(ierr);\n\n    //Create PETSc vector scatter and execute it\n    ierr = VecScatterCreate(globalVector, from, sequentialVector, to, &scatter);CHKERRQ(ierr);\n    ierr = VecScatterBegin(scatter, globalVector, sequentialVector, INSERT_VALUES, SCATTER_FORWARD);\n        CHKERRQ(ierr);\n    ierr = VecScatterEnd(scatter, globalVector, sequentialVector, INSERT_VALUES, SCATTER_FORWARD);\n        CHKERRQ(ierr);\n\n    //Obtain data array from scattered PETSc vector\n    ierr = VecGetArrayRead(sequentialVector, &readarray);CHKERRQ(ierr);\n\n    //Copy data array into vector (non-PETSc vector)\n    for (i=0; i < readSize; i++){\n        values->at(i) = readarray[i];\n    }\n\n    //Restore array to vector\n    ierr = VecRestoreArrayRead(sequentialVector, &readarray);CHKERRQ(ierr);\n\n    //Destroy unnecessary objects\n    ierr = ISDestroy(&from);CHKERRQ(ierr);\n    ierr = ISDestroy(&to);CHKERRQ(ierr);\n    ierr = VecScatterDestroy(&scatter);CHKERRQ(ierr);\n    ierr = VecDestroy(&sequentialVector);CHKERRQ(ierr);\n  }\n\n  return ierr;\n}\n\nPetscErrorCode diffusionPETSc::RecordData()\n{\n  //Writes grid data into a .vtr file to be read by ParaView\n\n  //Declare temporary variables for use in method\n  char filename[100];\n  PetscViewer vtrviewer;\n\n  //Get name of file to be written\n  sprintf(filename, \"%s/%s%04d.vtr\", gridData->directoryName.c_str(), \\\n          gridData->objectName.c_str(), step);\n\n    //    sprintf(filename, \"%s/%s%d.vtr\", gridData->directoryName.c_str(),\n\n  //Open viewer and write data to file\n  ierr = PetscViewerVTKOpen(DIFFU_COMM, filename, FILE_MODE_WRITE, \\\n    &vtrviewer);CHKERRQ(ierr);\n  ierr = PetscViewerPushFormat(vtrviewer, PETSC_VIEWER_VTK_VTR);CHKERRQ(ierr);\n  ierr = VecView(globalVector, vtrviewer);CHKERRQ(ierr);\n\n  //Destroy viewer and return ierr\n  ierr = PetscViewerDestroy(&vtrviewer);CHKERRQ(ierr);\n  return ierr;\n}\n\nPetscErrorCode diffusionPETSc::DiffusionFinalize(PetscBool last)\n{\n    //Destroys all remaining objects in class and finalizes PETSc if \"last\" is set\n    //to true.\n\n    //Destroy objects created for an instance of this class\n    ierr = DMDestroy(&distributedArray);CHKERRQ(ierr);\n    ierr = KSPDestroy(&krylovSolver);CHKERRQ(ierr);\n    ierr = VecDestroy(&globalVector);CHKERRQ(ierr);\n    ierr = VecDestroy(&gridData->localVector);CHKERRQ(ierr);\n\n    ierr = PetscPrintf(DIFFU_COMM, \"\\nDone\\n\");CHKERRQ(ierr);\n\n    //If this is the last instance of this class to be finished, finalize PETSc.\n    if (last){\n        ierr = PetscFinalize();\n    }\n\n    return ierr;\n}\n\n//------------------------------------------------------------------------------\n//                    Helper functions (external to class)\n//------------------------------------------------------------------------------\n\nPetscErrorCode ComputeMatrix(KSP krylovSolver, Mat A, Mat jac, void *user){\n    //Establishes shell matrix for KSP operation\n\n    //Initialize function---------------------------------------------------------\n    //Declare variables\n    PetscErrorCode ierr;\n    DiffusionData  *gridData = (DiffusionData*)user;\n\n    //Begin function\n    PetscFunctionBegin;\n\n    //Create matrices-------------------------------------------------------------\n    //Form matrix for KSP process\n    ierr = MatSetSizes(A, gridData->localMaximum-gridData->localMinimum, gridData->localMaximum-\\\n        gridData->localMinimum, gridData->totalNodes, gridData->totalNodes);CHKERRQ(ierr);\n    ierr = MatSetType(A,MATSHELL);CHKERRQ(ierr);\n    ierr = MatShellSetContext(A,gridData);CHKERRQ(ierr);\n    ierr = MatSetUp(A);CHKERRQ(ierr);\n\n    //Set multiplication function for KSP process matrix\n    ierr = MatShellSetOperation(A,MATOP_MULT,(void(*)(void))MyMatMult);\n        CHKERRQ(ierr);\n\n    //Return error code-----------------------------------------------------------\n    PetscFunctionReturn(ierr);\n}\n\nPetscErrorCode MyMatMult(Mat A, Vec X, Vec Y){\n    //Defines the multiplication function for shell matrix\n\n    //Initialize function---------------------------------------------------------\n    //Declare variables\n    PetscErrorCode ierr;\n    void           *ptr;\n    DiffusionData  *user;\n    PetscScalar    **yarray, **xarray;\n    DM             distributedArray;\n    PetscInt       i,j,xm,ym,xs,ys,gxm,gym,gxs,gys;\n\n    //Begin function\n    PetscFunctionBegin;\n\n    //Retrieve context and DM\n    ierr = MatShellGetContext(A,&ptr);CHKERRQ(ierr);\n    ierr = VecGetDM(X,&distributedArray);CHKERRQ(ierr);\n    user = (DiffusionData*)ptr;\n\n    //Prepare for computation-----------------------------------------------------\n    //Begin scattering\n    ierr = DMGlobalToLocalBegin(distributedArray, X, INSERT_VALUES, user->localVector);CHKERRQ(ierr);\n\n    //Get local domain in grid\n    ierr = DMDAGetCorners(distributedArray,&xs,&ys,0,&xm,&ym,0);CHKERRQ(ierr);\n    ierr = DMDAGetGhostCorners(distributedArray,&gxs,&gys,0,&gxm,&gym,0);CHKERRQ(ierr);\n\n    //Get local array for product vector\n    ierr = DMDAVecGetArray(distributedArray, Y, &yarray);CHKERRQ(ierr);\n\n    //Finish scattering and get local array from scattered vector\n    ierr = DMGlobalToLocalEnd(distributedArray, X, INSERT_VALUES, user->localVector);CHKERRQ(ierr);\n    ierr = DMDAVecGetArrayRead(distributedArray, user->localVector, &xarray);CHKERRQ(ierr);\n\n    //Compute product-------------------------------------------------------------\n/*\n    const double h = user->h;\n    const double F = user->fourierNumber;\n    const double twoF = 2*user->fourierNumber;\n    const double topD = user->topDirichletCoefficient;\n    const double bottomD = user->bottomDirichletCoefficient;\n    const double leftD = user->leftDirichletCoefficient;\n    const double rightD = user->rightDirichletCoefficient;\n        const double topN = user->topNeumannCoefficient;\n        const double bottomN = user->bottomNeumannCoefficient;\n        const double leftN = user->leftNeumannCoefficient;\n        const double rightN = user->rightNeumannCoefficient;\n\n    for (j=ys; j<ys+ym; j++) {\n        for (i=xs; i<xs+xm; i++) {\n            //Sets value for edge points\n//            if (i == gxs || j == gys || i == gxs+gxm-1 || j == gys+gym-1){\n\n            //TOP WALL\n            if(j == gys+gym-1)\n            {\n                if (topN != 0)\n                {\n                    //Evaluate left corner when left wall is Neumann/Robin\n                    if (i == gxs && leftN != 0)\n                    {\n                        yarray[j][i] =\n                                -twoF * (xarray[j][i+1] + xarray[j-1][i])\n                            + (1 + (2 + (h * topD/topN) + (h * leftD/leftN)) * twoF) * xarray[j][i];\n                    }\n                    //Evaluate right corner when right wall is Neumann/Robin\n                    else if (i == gxs+gxm-1 && rightN != 0)\n                    {\n                        yarray[j][i] =\n                                -twoF * (xarray[j][i-1] + xarray[j-1][i])\n                            + (1 + (2 + (h * topD/topN) + (h * rightD/rightN)) * twoF) * xarray[j][i];\n                    }\n                    //Evaluate all other edge points on top wall\n                    else{\n                        yarray[j][i] =\n                                -F * (2*xarray[j-1][i] + xarray[j][i-1] + xarray[j][i+1])\n                                + (1 + (2 + h*topD/topN) * twoF) * xarray[j][i];\n                    }\n                }\n                //Evaluate wall in case of Dirichlet condition\n                else\n                    yarray[j][i] = xarray[j][i];\n            }\n            //BOTTOM WALL\n            else if(j == gys)\n            {\n                if (bottomN != 0)\n                {\n                    //Evaluate left corner when left wall is Neumann/Robin\n                    if (i == gxs && leftN != 0){\n                        yarray[j][i] =\n                                -twoF * (xarray[j][i+1] + xarray[j+1][i])\n                            + (1 + (2 + (h * leftD/leftN) +  (h * bottomD/bottomN)) * twoF) * xarray[j][i];\n                    }\n                    //Evaluate right corner when right wall is Neumann/Robin\n                    else if (i == gxs+gxm-1 && rightN != 0){\n                        yarray[j][i] =\n                                -twoF * (xarray[j][i-1] + xarray[j+1][i])\n                            + ( 1 + (2 + (h * rightD/rightN) + (h * bottomD/bottomN)) * twoF) * xarray[j][i];\n                    }\n                    //Evaluate all other edge points on bottom wall\n                    else{\n                        yarray[j][i] =\n                                -F * (2*xarray[j+1][i] + xarray[j][i-1] + xarray[j][i+1])\n                                + (1 + (2 + h*bottomD/bottomN) * twoF) * xarray[j][i];\n                    }\n                }\n                //Evaluate wall in case of Dirichlet condition\n                else\n                    yarray[j][i] = xarray[j][i];\n            }\n            //LEFT WALL\n            else if(i == gxs)\n            {\n//                else if ((user->leftNeumannCoefficient != 0 && i == gxs) && (j != gys && j != gys+gym-1)){\n                if (leftN != 0)\n                    yarray[j][i] =\n                            -F * (xarray[j-1][i] + xarray[j+1][i] + 2*xarray[j][i+1])\n                            + (1 + (2 + (user->h*leftD/leftN)) * twoF) * xarray[j][i];\n                //Evaluate wall in case of Dirichlet condition\n                else\n                    yarray[j][i] = xarray[j][i];\n            }\n            //RIGHT WALL\n            else if(i == gxs+gxm-1)\n            {\n//                else if ((user->rightNeumannCoefficient != 0 && i == gxs+gxm-1) && (j != gys && j != gys+gym-1)){\n                if (rightN != 0)\n                    yarray[j][i] =\n                            -F * (xarray[j-1][i] + xarray[j+1][i] -  2*xarray[j][i-1])\n                            + (1 + (2 + (h*rightD/rightN)) * twoF) * xarray[j][i];\n                //Evaluate wall in case of Dirichlet condition\n                else\n                    yarray[j][i] = xarray[j][i];\n            }\n\n            //Sets value for non-edge points\n            else\n                yarray[j][i] = 1.0 - F*(\n                        xarray[j-1][i] + xarray[j+1][i] + xarray[j][i-1] + xarray[j][i+1] - 4*xarray[j][i]);\n                //        yarray[j][i] = -user->fourierNumber*xarray[j-1][i]-user->fourierNumber*xarray[j+1][i]-\\\n                //            user->fourierNumber*xarray[j][i-1] -user->fourierNumber*xarray[j][i+1]+\\\n                //            (1+4*user->fourierNumber)*xarray[j][i];\n        }\n    }\n*/\n\n///*\n    for (j=ys; j<ys+ym; j++) {\n        for (i=xs; i<xs+xm; i++) {\n        //Sets value for edge points\n          if (i == gxs || j == gys || i == gxs+gxm-1 || j == gys+gym-1){\n                //Evaluate in case where top wall is Neumann/Robin\n                if (user->topNeumannCoefficient != 0 && j == gys+gym-1){\n                    //Evaluate left corner when left wall is Neumann/Robin\n                    if (i == gxs && user->leftNeumannCoefficient != 0){\n                        yarray[j][i] = -2*user->fourierNumber*xarray[j][i+1]-2*user->fourierNumber*xarray[j-1][i]\\\n                            +(1+(4 + (2*user->h*user->topDirichletCoefficient/user->topNeumannCoefficient)\\\n                            +(2*user->h*user->leftDirichletCoefficient/user->leftNeumannCoefficient))*\\\n                            user->fourierNumber)*xarray[j][i];\n                    }\n                    //Evaluate right corner when right wall is Neumann/Robin\n                    else if (i == gxs+gxm-1 && user->rightNeumannCoefficient != 0){\n                        yarray[j][i] = -2*user->fourierNumber*xarray[j][i-1]-2*user->fourierNumber*xarray[j-1][i]\\\n                            +(1+(4 + (2*user->h*user->topDirichletCoefficient/user->topNeumannCoefficient)\\\n                            +(2*user->h*user->rightDirichletCoefficient/user->rightNeumannCoefficient))*\\\n                            user->fourierNumber)*xarray[j][i];\n                    }\n                    //Evaluate all other edge points on top wall\n                    else{\n                        yarray[j][i] = -2*user->fourierNumber*xarray[j-1][i]-user->fourierNumber*xarray[j][i-1]\\\n                            -user->fourierNumber*xarray[j][i+1]+(1 + (4 + 2*user->h*user->topDirichletCoefficient\\\n                            /user->topNeumannCoefficient)*user->fourierNumber)*xarray[j][i];\n                    }\n                }\n                //Evaluate in case where bottom wall is Neumann/Robin\n                else if (user->bottomNeumannCoefficient != 0 && j == gys){\n                    //Evaluate left corner when left wall is Neumann/Robin\n                    if (i == gxs && user->leftNeumannCoefficient != 0){\n                        yarray[j][i] = -2*user->fourierNumber*xarray[j][i+1]-2*user->fourierNumber*xarray[j+1][i]\\\n                            +(1+(4 + (2*user->h*user->leftDirichletCoefficient/user->leftNeumannCoefficient) + \\\n                            (2*user->h*user->bottomDirichletCoefficient/user->bottomNeumannCoefficient))*\\\n                            user->fourierNumber)*xarray[j][i];\n                    }\n                    //Evaluate right corner when right wall is Neumann/Robin\n                    else if (i == gxs+gxm-1 && user->rightNeumannCoefficient != 0){\n                        yarray[j][i] = -2*user->fourierNumber*xarray[j][i-1]-2*user->fourierNumber*xarray[j+1][i]\\\n                            +(1+(4 + (2*user->h*user->rightDirichletCoefficient/user->rightNeumannCoefficient) + \\\n                            (2*user->h*user->bottomDirichletCoefficient/user->bottomNeumannCoefficient))*\\\n                            user->fourierNumber)*xarray[j][i];\n                    }\n                    //Evaluate all other edge points on bottom wall\n                    else{\n                        yarray[j][i] =\n                                -2*user->fourierNumber*xarray[j+1][i]\n                                -user->fourierNumber*xarray[j][i-1]\n                            -user->fourierNumber*xarray[j][i+1]\n                                +(1+(4 + (2*user->h*user->bottomDirichletCoefficient\\\n                            /user->bottomNeumannCoefficient))*user->fourierNumber)*xarray[j][i];\n                    }\n                }\n                //Evaluate in case where left wall is Neumann/Robin\n                else if ((user->leftNeumannCoefficient != 0 && i == gxs) && (j != gys && j != gys+gym-1)){\n                    yarray[j][i] = -user->fourierNumber*xarray[j-1][i]-user->fourierNumber*xarray[j+1][i]-\\\n                        2*user->fourierNumber*xarray[j][i+1]+(1+(4 + (2*user->h*user->leftDirichletCoefficient\\\n                        /user->leftNeumannCoefficient))*user->fourierNumber)*xarray[j][i];\n                }\n                //Evaluate in case where right wall is Neumann/Robin\n                else if ((user->rightNeumannCoefficient != 0 && i == gxs+gxm-1) && (j != gys && j != gys+gym-1)){\n                    yarray[j][i] = -user->fourierNumber*xarray[j-1][i]-user->fourierNumber*xarray[j+1][i]-\\\n                        2*user->fourierNumber*xarray[j][i-1]+(1+(4 + (2*user->h*user->rightDirichletCoefficient\\\n                        /user->rightNeumannCoefficient))*user->fourierNumber)*xarray[j][i];\n                }\n                //Evaluate wall in case of Dirichlet condition\n                else{\n                    yarray[j][i] = xarray[j][i];\n                }\n            }\n            //Sets value for non-edge points\n            else\n                yarray[j][i] = -user->fourierNumber*xarray[j-1][i]-user->fourierNumber*xarray[j+1][i]-\\\n                    user->fourierNumber*xarray[j][i-1] -user->fourierNumber*xarray[j][i+1]+\\\n                    (1+4*user->fourierNumber)*xarray[j][i];\n        }\n    }\n//*/\n\n    //Finish function-------------------------------------------------------------\n    //Restore arrays\n    ierr = DMDAVecRestoreArray(distributedArray, Y, &yarray);CHKERRQ(ierr);\n    ierr = DMDAVecRestoreArrayRead(distributedArray, user->localVector, &xarray);CHKERRQ(ierr);\n\n    //Return error code\n    PetscFunctionReturn(ierr);\n}\n", "meta": {"hexsha": "c7808f4e399ead4e8a845839d42b7e4ad66e30ea", "size": 37564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "diffuclass.cpp", "max_stars_repo_name": "jwinkle/eQ", "max_stars_repo_head_hexsha": "dbc94575fad9c8e4f1feaddc6a1c1c9067967ed2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "diffuclass.cpp", "max_issues_repo_name": "jwinkle/eQ", "max_issues_repo_head_hexsha": "dbc94575fad9c8e4f1feaddc6a1c1c9067967ed2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diffuclass.cpp", "max_forks_repo_name": "jwinkle/eQ", "max_forks_repo_head_hexsha": "dbc94575fad9c8e4f1feaddc6a1c1c9067967ed2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-25T15:04:47.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-25T15:04:47.000Z", "avg_line_length": 43.0286368843, "max_line_length": 126, "alphanum_fraction": 0.5791715472, "num_tokens": 9553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2325249295264332}}
{"text": "#include \"midgard/util.h\"\n#include \"midgard/constants.h\"\n#include \"midgard/distanceapproximator.h\"\n#include \"midgard/logging.h\"\n#include \"midgard/point2.h\"\n#include \"midgard/polyline2.h\"\n#include \"midgard/vector2.h\"\n\n#include <algorithm>\n#include <array>\n#include <cctype>\n#include <cmath>\n#include <cstdint>\n#include <fstream>\n#include <list>\n#include <sstream>\n#include <stdlib.h>\n#include <sys/stat.h>\n#include <vector>\n\n#include <boost/archive/iterators/base64_from_binary.hpp>\n#include <boost/archive/iterators/binary_from_base64.hpp>\n#include <boost/archive/iterators/remove_whitespace.hpp>\n#include <boost/archive/iterators/transform_width.hpp>\n\nnamespace {\n\nconstexpr double RAD_PER_METER = 1.0 / 6378160.187;\nconstexpr double RAD_PER_DEG = valhalla::midgard::kPiDouble / 180.0;\nconstexpr double DEG_PER_RAD = 180.0 / valhalla::midgard::kPiDouble;\n\nstd::vector<valhalla::midgard::PointLL>\nresample_at_1hz(const std::vector<valhalla::midgard::gps_segment_t>& segments) {\n  std::vector<valhalla::midgard::PointLL> resampled;\n  float time_remainder = 0.0;\n  for (const auto& segment : segments) {\n    // get the speed of this edge\n    auto meters = valhalla::midgard::Polyline2<valhalla::midgard::PointLL>::Length(segment.shape);\n    // trim the shape to account of the portion of the previous second that bled onto this edge\n    auto to_trim = segment.speed * time_remainder;\n    auto trimmed = valhalla::midgard::trim_polyline(segment.shape.cbegin(), segment.shape.cend(),\n                                                    to_trim / meters, 1.f);\n    // resample it at 1 second intervals\n    auto second_interval =\n        valhalla::midgard::resample_spherical_polyline(trimmed, segment.speed, false);\n    resampled.insert(resampled.end(), second_interval.begin(), second_interval.end());\n    // figure out how much of the last second will bleed into the next edge\n    double intpart;\n    time_remainder = std::modf((meters - to_trim) / segment.speed, &intpart);\n  }\n  return resampled;\n}\n\n} // namespace\n\nnamespace valhalla {\nnamespace midgard {\n\n// scalar * vector operator.\nVector2 operator*(float s, const Vector2& v) {\n  return Vector2(v.x() * s, v.y() * s);\n}\n\nVector2d operator*(double s, const Vector2d& v) {\n  return Vector2d(v.x() * s, v.y() * s);\n}\n\n// Trim the front of a polyline (represented as a list or vector of Point2).\n// Returns the trimmed portion of the polyline. The supplied polyline is\n// altered (the trimmed part is removed).\ntemplate <class container_t> container_t trim_front(container_t& pts, const float dist) {\n  // Return if less than 2 points\n  if (pts.size() < 2) {\n    return {};\n  }\n\n  // Walk the polyline and accumulate length until it exceeds dist\n  container_t result;\n  result.push_back(pts.front());\n  double d = 0.0f;\n  for (auto p1 = pts.begin(), p2 = std::next(pts.begin()); p2 != pts.end(); ++p1, ++p2) {\n    double segdist = p1->Distance(*p2);\n    if ((d + segdist) > dist) {\n      double frac = (dist - d) / segdist;\n      auto midpoint = p1->PointAlongSegment(*p2, frac);\n      result.push_back(midpoint);\n\n      // Remove used part of polyline\n      pts.erase(pts.begin(), p1);\n      pts.front() = midpoint;\n      return result;\n    } else {\n      d += segdist;\n      result.push_back(*p2);\n    }\n  }\n\n  // Used all of the polyline without exceeding dist\n  pts.clear();\n  return result;\n}\n\nvoid trim_shape(float start,\n                PointLL start_vertex, // NOLINT\n                float end,\n                PointLL end_vertex, // NOLINT\n                std::vector<PointLL>& shape) {\n  // clip up to the start point if the start_vertex is valid\n  float along = 0.f;\n  if (start_vertex.IsValid()) {\n    // find the spot at which we cross the distance threshold and stop\n    auto current = shape.begin();\n    for (; !shape.empty() && (current != shape.end() - 1) && along <= start; ++current) {\n      along += (current + 1)->Distance(*current);\n    }\n    // we found the spot to stop for the beginning of the shape so set it to the new beginning\n    *(--current) = start_vertex;\n    shape.erase(shape.begin(), current);\n    along = start;\n  }\n\n  // clip after the end point if the end vertex is valid\n  if (end_vertex.IsValid()) {\n    // find the point at which we cross the distance threshold and stop\n    auto current = shape.begin();\n    for (; !shape.empty() && (current != shape.end() - 1) && along <= end; ++current) {\n      along += (current + 1)->Distance(*current);\n    }\n    // found the spot to stop for the end of the shape so set it to the new end\n    *(current) = end_vertex;\n    shape.erase(++current, shape.end());\n  }\n}\n\nfloat tangent_angle(size_t index,\n                    const PointLL& point,\n                    const std::vector<PointLL>& shape,\n                    const float sample_distance,\n                    bool forward) {\n  // depending on if we are going forward or backward we choose a different increment\n  auto increment = forward ? -1 : 1;\n  auto first_end = forward ? shape.cbegin() : shape.cend() - 1;\n  auto second_end = forward ? shape.cend() - 1 : shape.cbegin();\n\n  // u and v will be points we move along the shape until we have enough distance between them or\n  // run out of points\n\n  // move backwards until we have enough or run out\n  float remaining = sample_distance;\n  auto u = point;\n  auto i = shape.cbegin() + index + forward;\n  while (remaining > 0 && i != first_end) {\n    // move along and see how much distance that added\n    i += increment;\n    auto d = u.Distance(*i);\n    // are we done yet?\n    if (remaining <= d) {\n      auto coef = remaining / d;\n      u = u.PointAlongSegment(*i, coef);\n      return u.Heading(point);\n    }\n    // next one\n    u = *i;\n    remaining -= d;\n  }\n\n  // move forwards until we have enough or run out\n  auto v = point;\n  i = shape.cbegin() + index + !forward;\n  while (remaining > 0 && i != second_end) {\n    // move along and see how much distance that added\n    i -= increment;\n    auto d = v.Distance(*i);\n    // are we done yet?\n    if (remaining <= d) {\n      auto coef = remaining / d;\n      v = v.PointAlongSegment(*i, coef);\n      return u.Heading(v);\n    }\n    // next one\n    v = *i;\n    remaining -= d;\n  }\n  return u.Heading(v);\n}\n\n// Explicit instantiations\ntemplate std::vector<PointLL> trim_front<std::vector<PointLL>>(std::vector<PointLL>&, const float);\ntemplate std::vector<Point2> trim_front<std::vector<Point2>>(std::vector<Point2>&, const float);\ntemplate std::list<PointLL> trim_front<std::list<PointLL>>(std::list<PointLL>&, const float);\ntemplate std::list<Point2> trim_front<std::list<Point2>>(std::list<Point2>&, const float);\n\nmemory_status::memory_status(const std::unordered_set<std::string>& interest) {\n  // grab the vm stats from the file\n  std::ifstream file(\"/proc/self/status\");\n  std::string line;\n  while (std::getline(file, line)) {\n    // did we find a memory metric\n    if (line.find_first_of(\"Vm\") == 0) {\n      // grab the name of it and see if we care about it\n      std::string name = line.substr(0, line.find_first_of(':'));\n      if (interest.size() > 0 && interest.find(name) == interest.end()) {\n        continue;\n      }\n      // try to get the number of bytes\n      line.erase(std::remove_if(line.begin(), line.end(),\n                                [](const char c) { return !std::isdigit(c); }),\n                 line.end());\n      if (line.size() == 0) {\n        continue;\n      }\n      auto bytes = std::stod(line) * 1024.0;\n      // get the units and scale\n      std::pair<double, std::string> metric = std::make_pair(bytes, \"b\");\n      for (auto unit : {\"B\", \"KB\", \"MB\", \"GB\"}) {\n        metric.second = unit;\n        if (metric.first > 1024.0) {\n          metric.first /= 1024.0;\n        } else {\n          break;\n        }\n      }\n      metrics.emplace(std::piecewise_construct, std::forward_as_tuple(name),\n                      std::forward_as_tuple(metric));\n    }\n    line.clear();\n  }\n}\n\nbool memory_status::supported() {\n  struct stat s;\n  return stat(\"/proc/self/status\", &s) == 0;\n}\n\nstd::ostream& operator<<(std::ostream& stream, const memory_status& s) {\n  for (const auto& metric : s.metrics) {\n    stream << metric.first << \": \" << metric.second.first << metric.second.second << std::endl;\n  }\n  return stream;\n}\n\n/* This method makes use of several computations explained and demonstrated at:\n *   http://williams.best.vwh.net/avform.htm (reference no longer active)\n * New Reference:\n *   http://www.movable-type.co.uk/scripts/latlong.html\n */\ntemplate <class container_t>\ncontainer_t\nresample_spherical_polyline(const container_t& polyline, double resolution, bool preserve) {\n  if (polyline.size() == 0) {\n    return {};\n  };\n\n  // for each point\n  container_t resampled = {polyline.front()};\n  resolution *= RAD_PER_METER;\n  double remaining = resolution;\n  auto last = resampled.back();\n  for (auto p = std::next(polyline.cbegin()); p != polyline.cend(); ++p) {\n    // radians\n    auto lon2 = p->first * -RAD_PER_DEG;\n    auto lat2 = p->second * RAD_PER_DEG;\n    // how much do we have left on this segment from where we are (in great arc radians)\n    // double d = 2.0 * asin(sqrt(pow(sin((resampled.back().second * RAD_PER_DEG - lat2) /\n    // 2.0), 2.0) + cos(resampled.back().second * RAD_PER_DEG) * cos(lat2)\n    // *pow(sin((resampled.back().first * -RAD_PER_DEG - lon2) / 2.0), 2.0)));\n    auto d = (last == *p) ? 0.0\n                          : acos(sin(last.second * RAD_PER_DEG) * sin(lat2) +\n                                 cos(last.second * RAD_PER_DEG) * cos(lat2) *\n                                     cos(last.first * -RAD_PER_DEG - lon2));\n    if (std::isnan(d)) {\n      // set d to 0, do not skip in case we are preserving coordinates\n      d = 0.0;\n    }\n\n    // keep placing points while we can fit them\n    while (d > remaining) {\n      // some precomputed stuff\n      auto lon1 = last.first * -RAD_PER_DEG;\n      auto lat1 = last.second * RAD_PER_DEG;\n      auto sd = sin(d);\n      auto a = sin(d - remaining) / sd;\n      auto acs1 = a * cos(lat1);\n      auto b = sin(remaining) / sd;\n      auto bcs2 = b * cos(lat2);\n      // find the interpolated point along the arc\n      auto x = acs1 * cos(lon1) + bcs2 * cos(lon2);\n      auto y = acs1 * sin(lon1) + bcs2 * sin(lon2);\n      auto z = a * sin(lat1) + b * sin(lat2);\n      last.first = atan2(y, x) * -DEG_PER_RAD;\n      last.second = atan2(z, sqrt(x * x + y * y)) * DEG_PER_RAD;\n      resampled.push_back(last);\n      // we just consumed a bit\n      d -= remaining;\n      // we need another bit\n      remaining = resolution;\n    }\n    // we're going to the next point so consume whatever's left\n    remaining -= d;\n    last = *p;\n    if (preserve) {\n      resampled.push_back(last);\n    }\n  }\n\n  // TODO: do we want to let them know remaining?\n\n  // hand it back\n  return resampled;\n}\n\n// explicit instantiations\ntemplate std::vector<PointLL>\nresample_spherical_polyline<std::vector<PointLL>>(const std::vector<PointLL>&, double, bool);\ntemplate std::vector<Point2>\nresample_spherical_polyline<std::vector<Point2>>(const std::vector<Point2>&, double, bool);\ntemplate std::list<PointLL>\nresample_spherical_polyline<std::list<PointLL>>(const std::list<PointLL>&, double, bool);\ntemplate std::list<Point2>\nresample_spherical_polyline<std::list<Point2>>(const std::list<Point2>&, double, bool);\n\n/* Resample a polyline at uniform intervals using more accurate spherical interpolation between\n * points. The length and number of samples is specified. The interval is computed based on\n * the number of samples and the algorithm guarantees that the secified number of samples\n * is exactly produced.\n * This method makes use of several computations explained and demonstrated at:\n *   http://williams.best.vwh.net/avform.htm (reference no longer active)\n * New Reference:\n *   http://www.movable-type.co.uk/scripts/latlong.html\n */\nstd::vector<PointLL> uniform_resample_spherical_polyline(const std::vector<PointLL>& polyline,\n                                                         const double length,\n                                                         const uint32_t n) {\n  if (polyline.size() == 0) {\n    return {};\n  }\n\n  // Compute sample distance that splits the polyline equally to create n vertices.\n  // Divisor is n-1 since there is 1 more vertex than edge on the subdivided polyline.\n  double sample_distance = length / (n - 1);\n  double d0 = sample_distance;\n\n  // for each point\n  std::vector<PointLL> resampled = {polyline.front()};\n  sample_distance *= RAD_PER_METER;\n  double remaining = sample_distance;\n  PointLL last = resampled.back();\n  for (auto p = std::next(polyline.cbegin()); p != polyline.cend(); ++p) {\n    // Distance between this vertex and last (in great arc radians)\n    auto lon2 = p->first * -RAD_PER_DEG;\n    auto lat2 = p->second * RAD_PER_DEG;\n    auto d = (last == *p) ? 0.0\n                          : acos(sin(last.second * RAD_PER_DEG) * sin(lat2) +\n                                 cos(last.second * RAD_PER_DEG) * cos(lat2) *\n                                     cos(last.first * -RAD_PER_DEG - lon2));\n    if (std::isnan(d)) {\n      continue;\n    }\n\n    // Place resampled points on this segment as long as remaining distance is < d\n    while (remaining < d) {\n      // some precomputed stuff\n      auto lon1 = last.first * -RAD_PER_DEG;\n      auto lat1 = last.second * RAD_PER_DEG;\n      auto sd = sin(d);\n      auto a = sin(d - remaining) / sd;\n      auto acs1 = a * cos(lat1);\n      auto b = sin(sample_distance) / sd;\n      auto bcs2 = b * cos(lat2);\n\n      // find the interpolated point along the arc\n      auto x = acs1 * cos(lon1) + bcs2 * cos(lon2);\n      auto y = acs1 * sin(lon1) + bcs2 * sin(lon2);\n      auto z = a * sin(lat1) + b * sin(lat2);\n      last.first = atan2(y, x) * -DEG_PER_RAD;\n      last.second = atan2(z, sqrt(x * x + y * y)) * DEG_PER_RAD;\n      resampled.push_back(last);\n\n      // Update to reduce d and update...\n      d -= remaining;\n      remaining = sample_distance;\n    }\n    // we're going to the next point so consume whatever's left\n    remaining -= d;\n    last = *p;\n  }\n\n  if (resampled.size() < n) {\n    // Append the last polyline point\n    resampled.push_back(std::move(polyline.back()));\n  } else if (resampled.size() == n) {\n    resampled.back() = polyline.back();\n  }\n\n  if (resampled.size() != n) {\n    LOG_ERROR(\"resampled polyline not expected size! n: \" + std::to_string(n) +\n              \" actual: \" + std::to_string(resampled.size()) + \" length: \" + std::to_string(length) +\n              \" d: \" + std::to_string(d0));\n  }\n  return resampled;\n}\n\n// Resample the polyline to the specified resolution. This is a faster and less precise\n// method than resample_spherical_polyline.\nstd::vector<PointLL>\nresample_polyline(const std::vector<PointLL>& polyline, const float length, const float resolution) {\n  if (polyline.size() == 0) {\n    return {};\n  }\n\n  // Add the first point\n  std::vector<PointLL> resampled = {polyline.front()};\n\n  // Compute sample distance that is near the resolution but splits the polyline equally\n  size_t n = std::round(length / resolution);\n  float sample_distance = length / n;\n\n  // Iterate through line segments of the polyline\n  float accumulated_d = 0.0f;\n  auto p0 = polyline.cbegin();\n  for (auto p1 = std::next(polyline.cbegin()); p1 != polyline.cend(); ++p0, ++p1) {\n    // break if we have sampled enough\n    if (resampled.size() == n) {\n      break;\n    }\n\n    // Find distance (meters) between the 2 points of the input polyline.\n    float d = p0->Distance(*p1);\n\n    // Interpolate between the prior polyline point if we exceed the resolution\n    // (including distance accumulated so far)\n    if (d + accumulated_d > sample_distance) {\n      float dlon = p1->first - p0->first;\n      float dlat = p1->second - p0->second;\n\n      // Form the first interpolated point\n      float p = (sample_distance - accumulated_d) / d;\n      resampled.emplace_back(p0->first + p * dlon, p0->second + p * dlat);\n\n      // Continue to interpolate along the segment while accumulated distance is less than resolution\n      float dp = sample_distance / d;\n      while (p + dp < 1.0f && resampled.size() < n) {\n        p += dp;\n        resampled.emplace_back(p0->first + p * dlon, p0->second + p * dlat);\n      }\n\n      // Set the accumulated distance to the distance remaining on this segment\n      accumulated_d = d * (1.0f - p);\n\n    } else {\n      // Have not accumulated enough distance. Add d to the accumulated distance\n      accumulated_d += d;\n    }\n  }\n\n  // Append the last polyline point\n  resampled.push_back(std::move(polyline.back()));\n\n  return resampled;\n}\n\n// Return the intersection of two infinite lines if any\ntemplate <class coord_t>\nbool intersect(const coord_t& u, const coord_t& v, const coord_t& a, const coord_t& b, coord_t& i) {\n  auto uv_xd = u.first - v.first;\n  auto uv_yd = u.second - v.second;\n  auto ab_xd = a.first - b.first;\n  auto ab_yd = a.second - b.second;\n  auto d_cross = uv_xd * ab_yd - ab_xd * uv_yd;\n  // parallel or very close to it\n  if (std::abs(d_cross) < 1e-5) {\n    return false;\n  }\n  auto uv_cross = u.first * v.second - u.second * v.first;\n  auto ab_cross = a.first * b.second - a.second * b.first;\n  i.first = (uv_cross * ab_xd - uv_xd * ab_cross) / d_cross;\n  i.second = (uv_cross * ab_yd - uv_yd * ab_cross) / d_cross;\n  return true;\n}\ntemplate bool intersect<PointLL>(const PointLL& u,\n                                 const PointLL& v,\n                                 const PointLL& a,\n                                 const PointLL& b,\n                                 PointLL& i);\ntemplate bool\nintersect<Point2>(const Point2& u, const Point2& v, const Point2& a, const Point2& b, Point2& i);\n\n// Return the intercept of the line passing through uv with the horizontal line defined by y\ntemplate <class coord_t>\ntypename coord_t::first_type\ny_intercept(const coord_t& u, const coord_t& v, const typename coord_t::second_type y) {\n  if (std::abs(u.first - v.first) < 1e-5) {\n    return u.first;\n  }\n  if (std::abs(u.second - u.second) < 1e-5) {\n    return NAN;\n  }\n  auto m = (v.second - u.second) / (v.first - u.first);\n  auto b = u.second - (u.first * m);\n  return (y - b) / m;\n}\ntemplate PointXY<float>::first_type y_intercept<PointXY<float>>(const PointXY<float>&,\n                                                                const PointXY<float>&,\n                                                                const PointXY<float>::first_type);\ntemplate GeoPoint<float>::first_type y_intercept<GeoPoint<float>>(const GeoPoint<float>&,\n                                                                  const GeoPoint<float>&,\n                                                                  const GeoPoint<float>::first_type);\ntemplate PointXY<double>::first_type y_intercept<PointXY<double>>(const PointXY<double>&,\n                                                                  const PointXY<double>&,\n                                                                  const PointXY<double>::first_type);\ntemplate GeoPoint<double>::first_type\ny_intercept<GeoPoint<double>>(const GeoPoint<double>&,\n                              const GeoPoint<double>&,\n                              const GeoPoint<double>::first_type);\n\n// Return the intercept of the line passing through uv with the vertical line defined by x\ntemplate <class coord_t>\ntypename coord_t::first_type\nx_intercept(const coord_t& u, const coord_t& v, const typename coord_t::second_type x) {\n  if (std::abs(u.second - v.second) < 1e-5) {\n    return u.second;\n  }\n  if (std::abs(u.first - v.first) < 1e-5) {\n    return NAN;\n  }\n  auto m = (v.second - u.second) / (v.first - u.first);\n  auto b = u.second - (u.first * m);\n  return x * m + b;\n}\ntemplate PointXY<float>::first_type x_intercept<PointXY<float>>(const PointXY<float>&,\n                                                                const PointXY<float>&,\n                                                                const PointXY<float>::first_type);\ntemplate GeoPoint<float>::first_type x_intercept<GeoPoint<float>>(const GeoPoint<float>&,\n                                                                  const GeoPoint<float>&,\n                                                                  const GeoPoint<float>::first_type);\ntemplate PointXY<double>::first_type x_intercept<PointXY<double>>(const PointXY<double>&,\n                                                                  const PointXY<double>&,\n                                                                  const PointXY<double>::first_type);\ntemplate GeoPoint<double>::first_type\nx_intercept<GeoPoint<double>>(const GeoPoint<double>&,\n                              const GeoPoint<double>&,\n                              const GeoPoint<double>::first_type);\n\ntemplate <class container_t>\ntypename container_t::value_type::first_type polygon_area(const container_t& polygon) {\n  typename container_t::value_type::first_type area =\n      polygon.back() == polygon.front() ? 0.\n                                        : (polygon.back().first + polygon.front().first) *\n                                              (polygon.back().second + polygon.front().second);\n  for (auto p1 = polygon.cbegin(), p2 = std::next(polygon.cbegin()); p2 != polygon.cend();\n       ++p1, ++p2) {\n    area += (p1->first + p2->first) * (p1->second + p2->second);\n  }\n  return area * .5;\n}\n\ntemplate PointLL::first_type polygon_area(const std::list<PointLL>&);\ntemplate PointLL::first_type polygon_area(const std::vector<PointLL>&);\ntemplate Point2::first_type polygon_area(const std::list<Point2>&);\ntemplate Point2::first_type polygon_area(const std::vector<Point2>&);\n\nstd::vector<midgard::PointLL> simulate_gps(const std::vector<gps_segment_t>& segments,\n                                           std::vector<float>& accuracies,\n                                           float smoothing,\n                                           float accuracy,\n                                           size_t sample_rate,\n                                           unsigned seed) {\n  // resample the coords along a given edge at one second intervals\n  auto resampled = resample_at_1hz(segments);\n\n  // a way to get noise but only allow for slow change\n  std::mt19937 generator(seed);\n  std::uniform_real_distribution<float> distribution(-1, 1);\n  ring_queue_t<std::pair<float, float>> noises(smoothing);\n  auto get_noise = [&]() {\n    // we generate a vector whose magnitude is no more than accuracy\n    auto lon_adj = distribution(generator);\n    auto lat_adj = distribution(generator);\n    auto len = std::sqrt((lon_adj * lon_adj) + (lat_adj * lat_adj));\n    lon_adj /= len;\n    lat_adj /= len; // norm\n    auto scale = (distribution(generator) + 1.f) / 2.f;\n    lon_adj *= scale * accuracy;\n    lat_adj *= scale * accuracy; // random scale <= accuracy\n    noises.emplace_back(std::make_pair(lon_adj, lat_adj));\n    // average over last n to smooth\n    std::pair<float, float> noise{0, 0};\n    std::for_each(noises.begin(), noises.end(), [&noise](const std::pair<float, float>& n) {\n      noise.first += n.first;\n      noise.second += n.second;\n    });\n    noise.first /= noises.size();\n    noise.second /= noises.size();\n    return noise;\n  };\n  // fill up the noise queue so the first points arent unsmoothed\n  while (!noises.full()) {\n    get_noise();\n  }\n\n  // for each point of the 1hz shape\n  std::vector<midgard::PointLL> simulated;\n  for (size_t i = 0; i < resampled.size(); ++i) {\n    const auto& p = resampled[i];\n    // is this a harmonic of the desired sampling rate\n    if (i % sample_rate == 0) {\n      // meters of noise with extremely low likelihood its larger than accuracy\n      auto noise = get_noise();\n      // use the number of meters per degree in both axis to offset the point by the noise\n      auto metersPerDegreeLon = DistanceApproximator<PointLL>::MetersPerLngDegree(p.second);\n      simulated.emplace_back(midgard::PointLL(p.first + noise.first / metersPerDegreeLon,\n                                              p.second + noise.second / kMetersPerDegreeLat));\n      // keep the distance to use for accuracy\n      accuracies.emplace_back(simulated.back().Distance(p));\n    }\n  }\n  return simulated;\n}\n\npolygon_t to_boundary(const std::unordered_set<uint32_t>& region, const Tiles<PointLL>& tiles) {\n  // do we have this tile in this region\n  auto member = [&region](int32_t tile) { return region.find(tile) != region.cend(); };\n  // get the neighbor tile giving -1 if no neighbor\n  auto neighbor = [&tiles](int32_t tile, int side) -> int32_t {\n    if (tile == -1) {\n      return -1;\n    }\n    auto rc = tiles.GetRowColumn(tile);\n    switch (side) {\n      default:\n      case 0:\n        return rc.second == 0 ? -1 : tile - 1;\n      case 1:\n        return rc.first == 0 ? -1 : tile - tiles.ncolumns();\n      case 2:\n        return rc.second == tiles.ncolumns() - 1 ? -1 : tile + 1;\n      case 3:\n        return rc.first == tiles.nrows() - 1 ? -1 : tile + tiles.ncolumns();\n    }\n  };\n  // get the beginning coord of the counter clockwise winding given edge of the given tile\n  auto coord = [&tiles](uint32_t tile, int side) -> PointLL {\n    auto box = tiles.TileBounds(tile);\n    switch (side) {\n      default:\n      case 0:\n        return PointLL(box.minx(), box.maxy());\n      case 1:\n        return box.minpt();\n      case 2:\n        return PointLL(box.maxx(), box.miny());\n      case 3:\n        return box.maxpt();\n    }\n  };\n  // trace a ring of the polygon\n  polygon_t polygon;\n  std::array<std::unordered_set<uint32_t>, 4> used;\n  auto trace = [&member, &neighbor, &coord, &polygon, &used](uint32_t start_tile, int start_side,\n                                                             bool ccw) {\n    auto tile = start_tile;\n    auto side = start_side;\n    polygon.emplace_back();\n    auto& ring = polygon.back();\n    // walk until you see the starting edge again\n    do {\n      // add this edges geometry\n      if (ccw) {\n        ring.push_back(coord(tile, side));\n      } else {\n        ring.push_front(coord(tile, side));\n      }\n      auto inserted = used[side].insert(tile);\n      if (!inserted.second) {\n        throw std::logic_error(\"Any tile edge can only be used once as part of the geometry\");\n      }\n      // we need to go to the first existing neighbor tile following our winding\n      // starting with the one on the other side of the current side\n      auto adjc = neighbor(tile, (side + 1) % 4);\n      auto diag = neighbor(adjc, side);\n      if (member(diag)) {\n        tile = diag;\n        side = (side + 3) % 4;\n      } // next one keep following winding\n      else if (member(adjc)) {\n        tile = adjc;\n      } // if neither of those were there we stay on this tile and go to the next side\n      else {\n        side = (side + 1) % 4;\n      }\n    } while (tile != start_tile || side != start_side);\n  };\n\n  // the smallest numbered tile has a left edge on the outer ring of the polygon\n  auto start_tile = *region.cbegin();\n  int start_side = 0;\n  for (auto tile : region) {\n    if (tile < start_tile) {\n      start_tile = tile;\n    }\n  }\n\n  // trace the outer\n  trace(start_tile, start_side, true);\n\n  // trace the inners\n  for (auto start_tile : region) {\n    // if the neighbor isnt a member and we didnt already use the side between them\n    for (start_side = 0; start_side < 4; ++start_side) {\n      if (!member(neighbor(start_tile, start_side)) &&\n          used[start_side].find(start_tile) == used[start_side].cend()) {\n        // build the inner ring\n        if (start_side != -1) {\n          trace(start_tile, start_side, false);\n        }\n      }\n    }\n  }\n\n  // close all the rings\n  for (auto& ring : polygon) {\n    ring.push_back(ring.front());\n  }\n\n  // give it back\n  return polygon;\n}\n\nconstexpr char PADDING_ENCODED = '=';\nconstexpr char ZERO_ENCODED = 'A';\n\nstd::string encode64(const std::string& text) {\n  using namespace boost::archive::iterators;\n  using Base64Encode = base64_from_binary<transform_width<std::string::const_iterator, 6, 8>>;\n  // Encode and add padding to string per octet encoding described here:\n  // https://tools.ietf.org/html/rfc4648#section-4\n  std::string encoded(Base64Encode(text.begin()), Base64Encode(text.end()));\n  size_t num_pad_chars = (3 - text.size() % 3) % 3;\n  encoded.append(num_pad_chars, PADDING_ENCODED);\n  return encoded;\n}\n\nstd::string decode64(const std::string& encoded) {\n  using namespace boost::archive::iterators;\n  using Base64Decode =\n      transform_width<binary_from_base64<remove_whitespace<std::string::const_iterator>>, 8, 6>;\n  // NOTE(mookerji): Ugh, for more details, see:\n  // https://stackoverflow.com/questions/10521581/base64-encode-using-boost-throw-exception\n  size_t num_pad_chars = (4 - encoded.size() % 4) % 4;\n  std::string padded = encoded;\n  padded.append(num_pad_chars, PADDING_ENCODED);\n  size_t pad_chars = std::count(padded.begin(), padded.end(), PADDING_ENCODED);\n  std::replace(padded.begin(), padded.end(), PADDING_ENCODED, ZERO_ENCODED);\n  std::string decoded(Base64Decode(padded.begin()), Base64Decode(padded.end()));\n  decoded.erase(decoded.end() - pad_chars, decoded.end());\n  return decoded;\n}\n\n} // namespace midgard\n} // namespace valhalla\n", "meta": {"hexsha": "c8b54dff14e46c2b97bb53240c73fcbad3683f4b", "size": 29178, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/midgard/util.cc", "max_stars_repo_name": "mesozoic-drones/valhalla", "max_stars_repo_head_hexsha": "cafc34e63f3189d017348391a18847e8250d2b30", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/midgard/util.cc", "max_issues_repo_name": "mesozoic-drones/valhalla", "max_issues_repo_head_hexsha": "cafc34e63f3189d017348391a18847e8250d2b30", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-08-24T18:48:12.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-05T21:18:44.000Z", "max_forks_repo_path": "src/midgard/util.cc", "max_forks_repo_name": "mesozoic-drones/valhalla", "max_forks_repo_head_hexsha": "cafc34e63f3189d017348391a18847e8250d2b30", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-24T16:46:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-24T16:46:01.000Z", "avg_line_length": 38.3416557162, "max_line_length": 101, "alphanum_fraction": 0.6134759065, "num_tokens": 7354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.23246069175375653}}
{"text": "/**\n * Copyright (C) 2019  Sergey Morozov <sergey@morozov.ch>\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without restriction,\n * including without limitation the rights to use, copy, modify, merge,\n * publish, distribute, sublicense, and/or sell copies of the Software,\n * and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH\n * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#ifndef LIDAR_OBSTACLE_DETECTION_KDTREE_HPP\n#define LIDAR_OBSTACLE_DETECTION_KDTREE_HPP\n\n#include <cstdlib>\n#include <cmath>\n#include <memory>\n#include <vector>\n#include <random>\n#include <iostream>\n#include <Eigen/Dense>\n\n\nnamespace ser94mor::lidar_obstacle_detection\n{\n\n  /**\n   * A data structure representing the KD-Tree. Implements \"Insert\" and \"Search\" operations.\n   * @tparam dims a number of dimentions, that is, \"K\" from the KD-Tree\n   * @tparam id_type a type of the point identifier\n   */\n  template<size_t dims, typename id_type = uint64_t>\n  class KDTree\n  {\n  public:\n\n    enum ConstructionWay\n    {\n      AS_IS, SHUFFLE, SORT,\n    };\n\n    /**\n     * A data structure representing the k-dimensional point.\n     */\n    struct KDPoint\n    {\n      using vector_type = Eigen::Matrix<double_t, dims, 1>;\n\n      id_type id;\n      vector_type data;\n\n      bool IsInHypersphere(const vector_type& center, const double_t radius) const\n      {\n        auto diff = data - center;\n        double_t dist = std::sqrt(diff.transpose() * diff);\n\n        return dist <= radius;\n      }\n\n      bool IsGreaterThanOrEqualTo(const vector_type& point, size_t depth, const double_t distance_tolerance = 0.0) const\n      {\n        auto ind = depth % dims;\n        return data(ind) >= point(ind)-distance_tolerance;\n      }\n\n      bool IsLessThanOrEqualTo(const vector_type& point, size_t depth, const double_t distance_tolerance = 0.0) const\n      {\n        auto ind = depth % dims;\n        return data(ind) <= point(ind)+distance_tolerance;\n      }\n\n      bool operator==(const KDPoint& rhs) const\n      {\n        return id == rhs.id && data.isApprox(rhs.data);\n      }\n\n      bool operator!=(const KDPoint& rhs) const\n      {\n        return !(rhs == *this);\n      }\n\n    };\n\n    using point_type = KDPoint;\n    using vector_type = typename point_type::vector_type;\n\n  private:\n    /**\n     * A data structure representing the KD-Tree's node.\n     */\n    class KDNode\n    {\n    private:\n      KDPoint kd_point_;\n      std::unique_ptr<KDNode> children_[2];\n\n    public:\n      explicit KDNode(const KDPoint& kd_point)\n          : kd_point_{kd_point}, children_{nullptr, nullptr}\n      {\n\n      }\n\n      std::unique_ptr<KDNode>* SubtreeFor(const KDPoint& point, const size_t depth)\n      {\n        size_t dim_index = depth % dims;\n        size_t child_index = not (point.data(dim_index) < kd_point_.data(dim_index));\n        return &(children_[child_index]);\n      }\n\n      const std::unique_ptr<KDNode>& Left() const\n      {\n        return children_[0];\n      }\n\n      const std::unique_ptr<KDNode>& Right() const\n      {\n        return children_[1];\n      }\n\n      const KDPoint& Point() const\n      {\n        return kd_point_;\n      }\n    };\n\n\n    using node_type = KDNode;\n\n  public:\n\n    /**\n     * Constructor.\n     */\n    KDTree() : root_{nullptr}\n    {\n\n    }\n\n    /**\n     * Constructor.\n     */\n    KDTree(std::vector<point_type>& points, ConstructionWay construction_way) : root_{nullptr}\n    {\n      switch (construction_way)\n      {\n        case AS_IS:\n        {\n          break;\n        }\n        case SHUFFLE:\n        {\n          std::random_device rd;\n          std::mt19937 g(rd());\n          std::shuffle(points.begin(), points.end(), g);\n          break;\n        }\n        case SORT:\n        {\n          throw std::logic_error(\n              \"a balanced k-d tree construction (when points are sorted by each dimension) is not implemented yet\");\n        }\n        default:\n        {\n          throw std::logic_error(\"construction for the given ConstructionWay is not implemented\");\n        }\n      }\n\n      for (auto& point : points)\n      {\n        this->Insert(point);\n      }\n    }\n\n    /**\n     * Insert the K-dimensional point into the KDTree.\n     * @param kd_point K-dimensional point\n     */\n    void Insert(const point_type& kd_point)\n    {\n\n      size_t cur_depth = 0;\n\n      for (auto* cur_node = &root_; ; ++cur_depth)\n      {\n        if (*cur_node == nullptr)\n        {\n          *cur_node = std::make_unique<node_type>(kd_point);\n          break;\n        }\n\n        cur_node = (*cur_node)->SubtreeFor(kd_point, cur_depth);\n      }\n    }\n\n    /**\n     * Search the KD-Tree for the points lying in the k-dimensional sphere with the center {@param target_point}\n     * and radius {@param distance_tolerance}.\n     * @param target_point a K-dimensional point, the center of the sphere\n     * @param distance_tolerance the K-dimensional sphere radius\n     * @return a vector of point identifiers that lie inside the K-dimensional sphere\n     */\n    std::vector<id_type> Search(const vector_type& target_point, const double_t distance_tolerance) const\n    {\n      std::vector<id_type> ids;\n\n      SearchInternal(ids, root_, 0, target_point, distance_tolerance);\n\n      return std::move(ids);\n    }\n\n    /**\n     * @return Pointer to the KD-Tree's root node.\n     */\n    const std::unique_ptr<node_type>& Root() const\n    {\n      return root_;\n    }\n\n  private:\n    std::unique_ptr<node_type> root_; // the root node\n\n    /**\n     * The main logic of the \"Search\" operation of the KD-Tree.\n     *\n     * @param ids a vector where to store point indices\n     * @param node the node to consider during the given \"SearchInternal\" invocation\n     * @param depth the depth of the {@param node}\n     * @param target_point the K-dimensional point, i.e., the center of the search sphere\n     * @param distance_tolerance the radius of the K-dimensional search sphere\n     */\n    void SearchInternal(std::vector<id_type>& ids,\n                        const std::unique_ptr<node_type>& node,\n                        const size_t depth,\n                        const vector_type& target_point,\n                        const double_t distance_tolerance) const\n    {\n      if (node == nullptr)\n        return;\n\n      if (node->Point().IsInHypersphere(target_point, distance_tolerance))\n        ids.push_back(node->Point().id);\n\n      if (node->Point().IsGreaterThanOrEqualTo(target_point, depth, distance_tolerance))\n        SearchInternal(ids, node->Left(), depth+1, target_point, distance_tolerance);\n\n      if (node->Point().IsLessThanOrEqualTo(target_point, depth, distance_tolerance))\n        SearchInternal(ids, node->Right(), depth+1, target_point, distance_tolerance);\n    }\n  };\n}\n\n#endif //LIDAR_OBSTACLE_DETECTION_KDTREE_HPP\n", "meta": {"hexsha": "2982afb360afefa8631f11466b6969e78a3c3d01", "size": 7481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/KDTree.hpp", "max_stars_repo_name": "ser94mor/lidar-obstacle-detection", "max_stars_repo_head_hexsha": "e0271e6cd7c925fbd1804ecbe24eb0b7706c1f64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2019-08-05T08:53:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:14:29.000Z", "max_issues_repo_path": "lidar-pcl/src/KDTree.hpp", "max_issues_repo_name": "YinRui1991/pointpillars-on-openvino", "max_issues_repo_head_hexsha": "125a51e3817d1597c4a9804a42de60e1e10816a9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-06-20T09:23:31.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-25T09:14:06.000Z", "max_forks_repo_path": "lidar-pcl/src/KDTree.hpp", "max_forks_repo_name": "YinRui1991/pointpillars-on-openvino", "max_forks_repo_head_hexsha": "125a51e3817d1597c4a9804a42de60e1e10816a9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-07T18:38:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T21:43:04.000Z", "avg_line_length": 28.1240601504, "max_line_length": 120, "alphanum_fraction": 0.6317337254, "num_tokens": 1728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.2323091998129194}}
{"text": "// Copyright (c) 2022 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <pybind11/eigen.h>\n#include <pybind11/numpy.h>\n\n#include <Eigen/Core>\n#include <boost/geometry.hpp>\n\n#include \"pyinterp/geodetic/algorithm.hpp\"\n#include \"pyinterp/geodetic/point.hpp\"\n\nnamespace pyinterp::geodetic {\n\n/// Forward declaration\nclass Box;\n\nclass Polygon : public boost::geometry::model::polygon<Point> {\n public:\n  using Base = boost::geometry::model::polygon<Point>;\n  using Base::polygon;\n\n  /// Create a new instance from Python\n  Polygon(const pybind11::list& outer, const pybind11::list& inners);\n\n  /// Returns the outer ring\n  [[nodiscard]] auto outer() const -> pybind11::list {\n    auto outer = pybind11::list();\n\n    for (const auto& item : Base::outer()) {\n      outer.append(item);\n    }\n    return outer;\n  }\n\n  /// Returns the inner rings\n  [[nodiscard]] auto inners() const -> pybind11::list {\n    auto inners = pybind11::list();\n\n    for (const auto& inner : Base::inners()) {\n      auto buffer = pybind11::list();\n      for (const auto& item : inner) {\n        buffer.append(item);\n      }\n      inners.append(buffer);\n    }\n    return inners;\n  }\n\n  /// Calculates the envelope of this polygon.\n  [[nodiscard]] auto envelope() const -> Box;\n\n  /// Get a tuple that fully encodes the state of this instance\n  [[nodiscard]] auto getstate() const -> pybind11::tuple {\n    return pybind11::make_tuple(this->outer(), this->inners());\n  }\n\n  /// Calculate the area\n  [[nodiscard]] auto area(const std::optional<System>& wgs) const -> double {\n    return geodetic::area(*this, wgs);\n  }\n\n  /// Calculate the distance between two polygons\n  [[nodiscard]] auto distance(const Polygon& other) const -> double {\n    return geodetic::distance(*this, other);\n  }\n\n  /// Calculate the distance between this instance and a point\n  [[nodiscard]] auto distance(const Point& other) const -> double {\n    return geodetic::distance(*this, other);\n  }\n\n  /// Create a new instance from a registered state of an instance of this\n  /// object.\n  static auto setstate(const pybind11::tuple& state) -> Polygon {\n    if (state.size() != 2) {\n      throw std::runtime_error(\"invalid state\");\n    }\n    return {state[0].cast<pybind11::list>(), state[1].cast<pybind11::list>()};\n  }\n\n  /// @brief Test if the given point is inside or on border of this instance\n  ///\n  /// @param pt Point to test\n  //  @return True if the given point is inside or on border of this Polygon\n  [[nodiscard]] auto covered_by(const Point& point) const -> bool {\n    return boost::geometry::covered_by(point, *this);\n  }\n\n  /// @brief Test if the coordinates of the points provided are located inside\n  /// or at the edge of this Polygon.\n  ///\n  /// @param lon Longitudes coordinates in degrees to check\n  /// @param lat Latitude coordinates in degrees to check\n  /// @return Returns a vector containing a flag equal to 1 if the coordinate is\n  /// located in the Polygon or at the edge otherwise 0.\n  [[nodiscard]] auto covered_by(const Eigen::Ref<const Eigen::VectorXd>& lon,\n                                const Eigen::Ref<const Eigen::VectorXd>& lat,\n                                const size_t num_threads) const\n      -> pybind11::array_t<int8_t> {\n    return geodetic::covered_by<Point, Polygon>(*this, lon, lat, num_threads);\n  }\n\n  /// Converts a Polygon into a string with the same meaning as that of this\n  /// instance.\n  [[nodiscard]] auto to_string() const -> std::string {\n    std::stringstream ss;\n    ss << boost::geometry::dsv(*this);\n    return ss.str();\n  }\n};\n\n}  // namespace pyinterp::geodetic\n\nnamespace boost::geometry::traits {\nnamespace pg = pyinterp::geodetic;\n\ntemplate <>\nstruct tag<pg::Polygon> {\n  using type = polygon_tag;\n};\ntemplate <>\nstruct ring_const_type<pg::Polygon> {\n  using type = const model::polygon<pg::Point>::ring_type&;\n};\ntemplate <>\nstruct ring_mutable_type<pg::Polygon> {\n  using type = model::polygon<pg::Point>::ring_type&;\n};\ntemplate <>\nstruct interior_const_type<pg::Polygon> {\n  using type = const model::polygon<pg::Point>::inner_container_type&;\n};\ntemplate <>\nstruct interior_mutable_type<pg::Polygon> {\n  using type = model::polygon<pg::Point>::inner_container_type&;\n};\n\ntemplate <>\nstruct exterior_ring<pg::Polygon> {\n  static auto get(model::polygon<pg::Point>& p)\n      -> model::polygon<pg::Point>::ring_type& {\n    return p.outer();\n  }\n  static auto get(model::polygon<pg::Point> const& p)\n      -> model::polygon<pg::Point>::ring_type const& {\n    return p.outer();\n  }\n};\n\ntemplate <>\nstruct interior_rings<pg::Polygon> {\n  static auto get(model::polygon<pg::Point>& p)\n      -> model::polygon<pg::Point>::inner_container_type& {\n    return p.inners();\n  }\n  static auto get(model::polygon<pg::Point> const& p)\n      -> model::polygon<pg::Point>::inner_container_type const& {\n    return p.inners();\n  }\n};\n\n}  // namespace boost::geometry::traits", "meta": {"hexsha": "24f67bb75ef9647b92c7dc2c5476772fe9703be3", "size": 4978, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/geodetic/polygon.hpp", "max_stars_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_stars_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/geodetic/polygon.hpp", "max_issues_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_issues_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/geodetic/polygon.hpp", "max_forks_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_forks_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1696969697, "max_line_length": 80, "alphanum_fraction": 0.6639212535, "num_tokens": 1256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.23230919981291934}}
{"text": "#ifndef NEIGHBOURFINDER_HPP\n#define NEIGHBOURFINDER_HPP\n\n#include <Eigen/Dense>\n#include <nanoflann.hpp>\n#include \"../global.hpp\"\n\ntypedef Eigen::Matrix< int, Eigen::Dynamic, Eigen::Dynamic> MatDynInt; //matrix MxN of type unsigned int\ntypedef Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic> MatDynFloat;\ntypedef Eigen::Matrix< float, Eigen::Dynamic, registration::NUM_FEATURES> FeatureMat;\ntypedef Eigen::Matrix< float, Eigen::Dynamic, 3> Vec3Mat;\n\nnamespace registration {\n\ntemplate <typename VecMatType>\nclass NeighbourFinder\n{\n    /*\n    GOAL\n    This class searches for the k nearest neighbours in 'inSourcePoints' for\n    each element in the 'inQueriedPoints' set. It outputs the indices of each\n    neighbour and the squared (!) distances between each element of\n    'inQueriedPoints' and its neighbours.\n\n    INPUT\n    -inQueriedPoints:\n    -inSourcePoints:\n\n    PARAMETERS\n    -numNeighbours(= 3): number of nearest neighbours\n    -leafSize(= 15): should be between 5 and 50 or so\n\n    OUTPUT\n    -outNeighbourIndices\n    -outNeighbourSquaredDistances.\n    */\n\n    public:\n        //NeighbourFinder();\n        ~NeighbourFinder(); //destructor\n\n        void set_source_points(const VecMatType * const inQueriedPoints);\n        void set_queried_points(const VecMatType * const _inSourcePoints);\n        MatDynInt get_indices() const { return _outNeighbourIndices;}\n        MatDynFloat get_distances() const { return _outNeighbourSquaredDistances;}\n        void set_parameters(const size_t numNeighbours);\n        void update();\n\n    protected:\n\n    private:\n        //# Inputs\n        const VecMatType * _inQueriedPoints = NULL;\n        const VecMatType * _inSourcePoints = NULL;\n\n        //# Outputs\n        MatDynInt _outNeighbourIndices;\n        MatDynFloat _outNeighbourSquaredDistances;\n        //# User parameters\n\n        //# Internal Data structures\n        nanoflann::KDTreeEigenMatrixAdaptor<VecMatType> * _kdTree = NULL;\n\n        //# Interal parameters\n        size_t _numDimensions = 0;\n        size_t _numSourceElements = 0;\n        size_t _numQueriedElements = 0;\n        size_t _numNeighbours = 3;\n        size_t _leafSize = 15;\n\n};\n\n/*\nSee http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file\nfor an explanation why we instantiate our templated class with every matrix type we will use here.\n*/\n//\ntemplate class NeighbourFinder<FeatureMat>;\ntemplate class NeighbourFinder<Vec3Mat>;\n//\n\n\ntemplate <typename VecMatType>\nNeighbourFinder<VecMatType>::~NeighbourFinder()\n{\n    //destructor\n    if (_kdTree != NULL) { delete _kdTree; _kdTree = NULL;}\n}\n\ntemplate <typename VecMatType>\nvoid NeighbourFinder<VecMatType>::set_source_points(const VecMatType * const inSourcePoints){\n    //# Set input\n    _inSourcePoints = inSourcePoints;\n\n    //# Update internal parameters\n    _numDimensions = _inSourcePoints->cols();\n    _numSourceElements = _inSourcePoints->rows();\n\n    //# Update internal data structures\n    //## The kd-tree has to be rebuilt.\n    if (_kdTree != NULL) { delete _kdTree; _kdTree = NULL;}\n    _kdTree = new nanoflann::KDTreeEigenMatrixAdaptor<VecMatType>(*_inSourcePoints,\n                                                                _leafSize);\n    _kdTree->index->buildIndex();\n}\n\n\ntemplate <typename VecMatType>\nvoid NeighbourFinder<VecMatType>::set_queried_points(const VecMatType * const inQueriedPoints){\n    //# Set input\n    _inQueriedPoints = inQueriedPoints;\n\n    //# Update internal parameters\n    _numQueriedElements = _inQueriedPoints->rows();\n\n    //# Adjust internal data structures\n    //## The indices and distance matrices have to be resized.\n    _outNeighbourIndices.setZero(_numQueriedElements,_numNeighbours);\n    _outNeighbourSquaredDistances.setZero(_numQueriedElements,_numNeighbours);\n\n}\n\n\ntemplate <typename VecMatType>\nvoid NeighbourFinder<VecMatType>::set_parameters(const size_t numNeighbours){\n    //# Check if what user requests, changes the parameter value\n    bool parameterChanged = false;\n    if (_numNeighbours != numNeighbours){ parameterChanged = true;}\n\n    //# Set parameter\n    _numNeighbours = numNeighbours;\n\n    //# Resize the output matrices if the parameter is changed\n    if (parameterChanged == true) {\n        _outNeighbourIndices.setZero(_numQueriedElements,_numNeighbours);\n        _outNeighbourSquaredDistances.setZero(_numQueriedElements,_numNeighbours);\n    }\n}\n\ntemplate <typename VecMatType>\nvoid NeighbourFinder<VecMatType>::update(){\n\n    //# Query the kd-tree\n    //## Loop over the queried features\n    //### Initialize variables we'll need during the loop\n    unsigned int i = 0;\n    unsigned int j = 0;\n    std::vector<float> queriedFeature(_numDimensions);\n    std::vector<size_t> neighbourIndices(_numNeighbours);\n    std::vector<float> neighbourSquaredDistances(_numNeighbours);\n    nanoflann::KNNResultSet<float> knnResultSet(_numNeighbours);\n\n    //### Execute loop\n    for ( ; i < _numQueriedElements ; ++i ) {\n        //### Initiliaze the knnResultSet\n        knnResultSet.init(&neighbourIndices[0], &neighbourSquaredDistances[0]);\n\n        //### convert input features to 'queriedFeature' std::vector structure\n        //### (required by nanoflann's kd-tree).\n        for (j = 0 ; j < _numDimensions ; ++j) {\n            queriedFeature[j] = (*_inQueriedPoints)(i,j);\n        }\n\n        //### Query the kd-tree\n//        size_t numNeighboursFound = kdTree.knnSearch(&queriedFeature[0], _numNeighbours, &neighbourIndices[0], &neighbourSquaredDistances[0]);\n        _kdTree->index->findNeighbors(knnResultSet, &queriedFeature[0],\n                                    nanoflann::SearchParams(32, 0.0001 /*eps*/, true));\n\n        //### Copy the result into the outputs by looping over the k nearest\n        //### neighbours\n        for (j = 0 ; j < _numNeighbours ; ++j) {\n            _outNeighbourIndices(i,j) = neighbourIndices[j];\n            _outNeighbourSquaredDistances(i,j) = neighbourSquaredDistances[j];\n        }\n    }\n}//end k_nearest_neighbours()\n\n} //namespace registration\n\n#endif // NEIGHBOURFINDER_HPP\n", "meta": {"hexsha": "f397c8665ad0070d21f28d0c637fa21c5e7318fa", "size": 6074, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NeighbourFinder.hpp", "max_stars_repo_name": "brisyramshere/meshmonk", "max_stars_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2017-02-03T14:59:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T05:40:58.000Z", "max_issues_repo_path": "src/NeighbourFinder.hpp", "max_issues_repo_name": "brisyramshere/meshmonk", "max_issues_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-07-16T10:34:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T04:37:12.000Z", "max_forks_repo_path": "src/NeighbourFinder.hpp", "max_forks_repo_name": "brisyramshere/meshmonk", "max_forks_repo_head_hexsha": "a0a7cf79902541cf9c800d83a4d4f14fcd756f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2018-07-05T14:59:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T07:01:47.000Z", "avg_line_length": 33.5580110497, "max_line_length": 144, "alphanum_fraction": 0.6934474811, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23222279986964126}}
{"text": "//-*****************************************************************************\n// Copyright 2015 Christopher Jon Horvath\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n//-*****************************************************************************\n\n//-*****************************************************************************\n// The basic architecture of these Waves is based on the TweakWaves application\n// written by Chris Horvath for Tweak Films in 2001.  This, in turn, was based\n// on the SIGGRAPH papers and courses by Jerry Tessendorf, and by the paper\n// \"A Simple Fluid Solver based on the FTT\" by Jos Stam.\n//\n// The TMA, JONSWAP, and Pierson Moskowitz Wave Spectra, as well as the\n// directional spreading functions are formulated based on the descriptions\n// given in \"Ocean Waves: The Stochastic Approach\",\n// by Michel K. Ochi, published by Cambridge Ocean Technology Series, 1998,2005.\n//\n// This library is written as a working implementation of the paper:\n// Christopher J. Horvath. 2015.\n// Empirical directional wave spectra for computer graphics.\n// In Proceedings of the 2015 Symposium on Digital Production (DigiPro '15),\n// Los Angeles, Aug. 8, 2015, pp. 29-39.\n//-*****************************************************************************\n\n#include \"OceanTestShaders.h\"\n#include \"OceanTestFoundation.h\"\n#include \"OceanTestViewScene.h\"\n#include <boost/program_options.hpp>\n#include <cstdlib>\n\nnamespace po = boost::program_options;\nusing namespace OceanTest;\n\nint main(int argc, char *argv[]) {\n  OceanTest::ewav::Parametersf params;\n  OceanTest::Sky::Parameters sparams;\n  OceanTest::Mesh::DrawParameters dparams;\n  OceanTest::ViewScene::Parameters vparams;\n\n  int threads              = -1;\n  int dispersion           = 2;\n  int spectrum             = 2;\n  int directionalSpreading = 3;\n  int filter               = 0;\n  int random               = 0;\n\n  po::options_description desc(\"Encino Waves 2015\");\n  desc.add_options()\n\n    // clang-format off\n\n    ( \"help,h\", \"prints this help message\" )\n\n\n    ( \"threads\",\n      po::value<int>( &threads )\n      ->default_value( threads ),\n      \"Threads to use. Default of -1 means use all.\" )\n\n    ( \"resolution\",\n      po::value<int>( &params.resolutionPowerOfTwo )\n      ->default_value( params.resolutionPowerOfTwo ),\n      \"Power of Two of the sim resolution\" )\n\n    ( \"domain\",\n      po::value<float>( &params.domain )\n      ->default_value( params.domain ),\n      \"Size, in meters, of largest wave\" )\n\n    ( \"gravity\",\n      po::value<float>( &params.gravity )\n      ->default_value( params.gravity ),\n      \"Gravitational constant, in meters per second squared\" )\n\n    ( \"surfaceTension\",\n      po::value<float>( &params.surfaceTension )\n      ->default_value( params.surfaceTension ),\n      \"Surface tension constant, in Newtons per meter\" )\n\n    ( \"density\",\n      po::value<float>( &params.density )\n      ->default_value( params.density ),\n      \"Water density, in kilograms per meter cubed\" )\n\n    ( \"depth\",\n      po::value<float>( &params.depth )\n      ->default_value( params.depth ),\n      \"Average depth of the ocean, in meters\" )\n\n    ( \"windSpeed\",\n      po::value<float>( &params.windSpeed )\n      ->default_value( params.windSpeed ),\n      \"Average wind speed, in meters per second\" )\n\n    ( \"fetch\",\n      po::value<float>( &params.fetch )\n      ->default_value( params.fetch ),\n      \"Wind fetch, in KILOMETERS\" )\n\n    ( \"pinch\",\n      po::value<float>( &params.pinch )\n      ->default_value( params.pinch ),\n      \"Lateral displacement, normalized\" )\n\n    ( \"amplitudeGain\",\n      po::value<float>( &params.amplitudeGain )\n      ->default_value( params.amplitudeGain ),\n      \"Gain on the wave height\" )\n\n    ( \"dispersion\",\n      po::value<int>( &dispersion )\n      ->default_value( dispersion ),\n      \"Dispersion: 0 for Deep, 1 for Finite Depth, 2 for Capillary\" )\n\n    ( \"spectrum\",\n      po::value<int>( &spectrum )\n      ->default_value( spectrum ),\n      \"Spectrum: 0 for Pierson-Moskowitz, 1 for JONSWAP, 2 for TMA\" )\n\n    ( \"directionalSpreading\",\n      po::value<int>( &directionalSpreading )\n      ->default_value( directionalSpreading ),\n      \"Directional Spreading: 0 for Balanced Cos2 Theta, \"\n      \"1 for Mitsuyasu, 2 for Hasselmann, 3 for Donelan-Banner\" )\n\n    ( \"swell\",\n      po::value<float>( &params.directionalSpreading.swell )\n      ->default_value( params.directionalSpreading.swell ),\n      \"The mix between a wind-driven local sea and a swell caused by a \"\n      \"distant storm.\" )\n\n    ( \"filter\",\n      po::value<int>( &filter )\n      ->default_value( filter ),\n      \"Filter: 0 for nullptr, 1 for Smoothed Invertible Band-Pass\" )\n\n    ( \"filterSoftWidth\",\n      po::value<float>( &params.filter.softWidth )\n      ->default_value( params.filter.softWidth ),\n      \"Size in meters of the softness of wavelength filter falloff.\" )\n\n    ( \"filterSmall\",\n      po::value<float>( &params.filter.smallWavelength )\n      ->default_value( params.filter.smallWavelength ),\n      \"Size in meters of the smallest kept wavelengths.\" )\n\n    ( \"filterBig\",\n      po::value<float>( &params.filter.bigWavelength )\n      ->default_value( params.filter.bigWavelength ),\n      \"Size in meters of the biggest kept wavelengths.\" )\n\n    ( \"filterMin\",\n      po::value<float>( &params.filter.min )\n      ->default_value( params.filter.min ),\n      \"Minimum value of filter.\" )\n\n    ( \"filterInvert\", \"Invert the filter\" )\n\n    ( \"troughDamping\",\n     po::value<float>( &params.troughDamping )\n     ->default_value( params.troughDamping ),\n     \"Trough damping.\" )\n\n    ( \"troughDampingSmallWavelength\",\n      po::value<float>( &params.troughDampingSmallWavelength )\n      ->default_value( params.troughDampingSmallWavelength ),\n      \"Trough damping small wavelength.\" )\n\n    ( \"troughDampingBigWavelength\",\n      po::value<float>( &params.troughDampingBigWavelength )\n      ->default_value( params.troughDampingBigWavelength ),\n      \"Trough damping big wavelength.\" )\n\n    ( \"troughDampingSoftWidth\",\n      po::value<float>( &params.troughDampingSoftWidth )\n      ->default_value( params.troughDampingSoftWidth ),\n      \"Trough damping soft width.\" )\n\n    ( \"random\",\n      po::value<int>( &random )\n      ->default_value( random ),\n      \"Random Distribution: 0 for Normal, 1 for Log-Normal\" )\n\n    ( \"seed\",\n      po::value<int>( &params.random.seed )\n      ->default_value( params.random.seed ),\n      \"Random Seed\" )\n\n    ( \"repeat\",\n      po::value<int>( &dparams.repeat )\n      ->default_value( dparams.repeat ),\n      \"Number of times, between 1 & 3, to repeat the drawing\" )\n\n    ( \"time\",\n      po::value<double>( &sparams.time )\n      ->default_value( sparams.time ),\n      \"Time of day, 0 - 24\" )\n\n    ( \"turbidity\",\n      po::value<double>( &sparams.turbidity )\n      ->default_value( sparams.turbidity ),\n      \"Turbidity\" )\n\n    ( \"skyTexture\",\n      po::value<std::string>( &sparams.filename ),\n      \"Sky Texture\" )\n\n    ( \"outFileBase\",\n      po::value<std::string>()\n      ->default_value( \"EncinoWaves\" ),\n      \"The output file name base\" )\n\n    ;\n\n  // clang-format on\n\n  po::variables_map vm;\n  po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n  po::notify(vm);\n\n  //-*************************************************************************\n  if (vm.count(\"help\")) {\n    std::cout << desc << std::endl;\n    return 0;\n  }\n\n  if (vm.count(\"filterInvert\")) {\n    params.filter.invert = true;\n  }\n\n  if (vm.count(\"outFileBase\")) {\n    vparams.outputFileBase = vm[\"outFileBase\"].as<std::string>();\n  }\n\n  params.dispersion.type = (ewav::DispersionType)dispersion;\n  params.spectrum.type = (ewav::SpectrumType)spectrum;\n  params.directionalSpreading.type =\n    (ewav::DirectionalSpreadingType)directionalSpreading;\n  params.filter.type = (ewav::FilterType)filter;\n  params.random.type = (ewav::RandomType)random;\n\n  std::shared_ptr<EncinoWaves::SimpleSimViewer::BaseSim> simPtr(\n    new OceanTest::ViewScene(params, sparams, dparams, vparams));\n\n  EncinoWaves::SimpleSimViewer::SimpleViewSim(simPtr, true);\n\n  return 0;\n}\n", "meta": {"hexsha": "3b76c43afd0a0bf74ae489aef4783d8cacb53153", "size": 8587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/EncinoWaves/Tests/OceanTestMain.cpp", "max_stars_repo_name": "NTForked/EncinoWaves", "max_stars_repo_head_hexsha": "b7db46962e8405e2c7fb91b3eb7fda03d78489d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-08-08T08:53:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T15:45:21.000Z", "max_issues_repo_path": "src/EncinoWaves/Tests/OceanTestMain.cpp", "max_issues_repo_name": "NTForked/EncinoWaves", "max_issues_repo_head_hexsha": "b7db46962e8405e2c7fb91b3eb7fda03d78489d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-10T18:50:26.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-10T18:50:26.000Z", "max_forks_repo_path": "src/EncinoWaves/Tests/OceanTestMain.cpp", "max_forks_repo_name": "NTForked/EncinoWaves", "max_forks_repo_head_hexsha": "b7db46962e8405e2c7fb91b3eb7fda03d78489d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-08-09T02:40:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-11T19:39:29.000Z", "avg_line_length": 33.1544401544, "max_line_length": 80, "alphanum_fraction": 0.624082916, "num_tokens": 2120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.23222279343467941}}
{"text": "#include \"PurificationDecorator.hpp\"\n#include \"IRProvider.hpp\"\n#include \"InstructionIterator.hpp\"\n#include \"PauliOperator.hpp\"\n#include \"XACC.hpp\"\n#include <Eigen/Dense>\n#include \"xacc_service.hpp\"\n\nusing namespace xacc::quantum;\n\nnamespace xacc {\nnamespace vqe {\nvoid PurificationDecorator::execute(std::shared_ptr<AcceleratorBuffer> buffer,\n                                    const std::shared_ptr<Function> function) {\n\n  if (!decoratedAccelerator) {\n    xacc::error(\"Null Decorated Accelerator Error\");\n  }\n\n  return;\n}\n\nstd::vector<std::shared_ptr<AcceleratorBuffer>> PurificationDecorator::execute(\n    std::shared_ptr<AcceleratorBuffer> buffer,\n    const std::vector<std::shared_ptr<Function>> functions) {\n\n  std::vector<std::shared_ptr<AcceleratorBuffer>> buffers;\n\n  if (!decoratedAccelerator) {\n    xacc::error(\"PurificationDecorator - Null Decorated Accelerator Error\");\n  }\n\n  // Here I expect the ansatz to be functions[0]->getInstruction(0);\n  auto ansatz =\n      std::dynamic_pointer_cast<Function>(functions[0]->getInstruction(0));\n\n  if (!ansatz)\n    xacc::error(\"ANSATZ IS NULL\");\n\n  // Generate all nQubit Pauli Strings\n  std::vector<std::string> XYZ;\n  std::set<std::string> temp, PauliStrings;\n  std::vector<PauliOperator> Paulis;\n\n  for (int i = 0; i < buffer->size(); i++)\n    XYZ.push_back(\"X\" + std::to_string(i));\n  for (int i = 0; i < buffer->size(); i++)\n    XYZ.push_back(\"Y\" + std::to_string(i));\n  for (int i = 0; i < buffer->size(); i++)\n    XYZ.push_back(\"Z\" + std::to_string(i));\n\n  std::function<void(std::vector<std::string> &, std::string, const int,\n                     const int)>\n      y;\n  y = [&](std::vector<std::string> &set, std::string prefix, const int n,\n          const int k) {\n    if (k == 0) {\n      PauliOperator op;\n      op.fromString(prefix);\n      PauliStrings.insert(op.toString());\n      return;\n    }\n\n    for (int i = 0; i < n; i++) {\n      auto newPrefix = prefix + \" \" + set[i];\n      y(set, newPrefix, n, k - 1);\n    }\n  };\n\n  auto x = [&](std::vector<std::string> &set, const int k) {\n    auto n = set.size();\n    y(set, std::string(\"\"), n, k);\n  };\n\n  // Get all Permutations of XYZ\n  x(XYZ, buffer->size());\n\n  PauliOperator all;\n  std::map<std::string, PauliOperator> opMap;\n  for (auto &s : PauliStrings) {\n    PauliOperator op;\n    op.fromString(s);\n    Paulis.push_back(op);\n    all += op;\n    opMap.insert({op.getTerms().begin()->second.id(), op});\n  }\n\n  for (auto &kv : opMap)\n    std::cout << kv.first << \", \" << kv.second.toString() << \"\\n\";\n\n  std::cout << all.toString() << \"\\n\";\n  std::cout << Paulis.size() << \" operators to measure\\n\";\n\n  auto kernels = all.toXACCIR()->getKernels();\n  for (auto &k : kernels) {\n    k->insertInstruction(0, ansatz);\n  }\n\n//   std::cout << \"EXECUTING\\n\";\n  buffers = decoratedAccelerator->execute(buffer, kernels);\n\n  std::size_t dim = 1;\n  std::size_t two = 2;\n  for (int i = 0; i < buffer->size(); i++)\n    dim *= two;\n\n  Eigen::MatrixXcd rho(dim, dim);\n  rho.setZero();\n\n  std::map<std::string, std::shared_ptr<AcceleratorBuffer>> bufMap;\n  for (auto &b : buffers) {\n    auto id = b->name();\n    bufMap.insert({id,b});\n    auto op = opMap[id];\n\n    auto data = op.toDenseMatrix(buffer->size()).data();\n    Eigen::MatrixXcd p = Eigen::Map<Eigen::MatrixXcd>(data, dim,dim);\n    rho += b->getExpectationValueZ() * p;\n  }\n\n  // Add the Identity term Tr(I rho) * I = <I> * I\n  rho += Eigen::MatrixXcd::Identity(dim, dim);\n\n//   std::cout << \"RHO:\\n\" << rho << \"\\n\";\n//   std::cout << rho.trace() << \"\\n\";\n\n  Eigen::MatrixXcd rhosq = rho * rho;\n  Eigen::MatrixXcd diff = rhosq - rho;\n  Eigen::MatrixXcd diffsq = diff * diff;\n\n  int counter = 0;\n  auto tr = std::real(diffsq.trace());\n  while (tr > 1e-4) {\n    rho = 3. * rhosq - 2. * rhosq * rho;\n    rho /= rho.trace();\n\n    rhosq = rho * rho;\n    diff = rhosq - rho;\n    diffsq = diff * diff;\n    tr = std::real(diffsq.trace());\n    // std::cout << counter << \", TRACE: \" << tr << \"\\n\";\n    counter++;\n    if (counter > 100)\n      break;\n  }\n\n//   std::cout << rho.trace() << \"\\n\" << rho << \"\\n\";\n\n  // new E = Tr(H*rho)\n  // so get H\n  PauliOperator HOp;\n  auto ir = xacc::getService<xacc::IRProvider>(\"gate\")->createIR();\n  for (auto &f : functions) {\n    ir->addKernel(f);\n  }\n  HOp.fromXACCIR(ir);\n\n//   std::cout << \"MADE IT HERE\\n\";\n//   std::cout << HOp.toString() << \"\\n\";\n\n  auto identityCoeff = mpark::get<double>(buffer->getInformation(\"identity-coeff\"));\n  xacc::info(std::to_string(identityCoeff));\n  auto ID = -1 * identityCoeff * Eigen::MatrixXcd::Identity(dim,dim);\n  auto data = HOp.toDenseMatrix(buffer->size()).data();\n  Eigen::MatrixXcd H = Eigen::Map<Eigen::MatrixXcd>(data, dim,dim) - ID;\n\n//   std::cout << \"CONJ:\\n\" << (rho - rho.conjugate()) << \"\\n\";\n//   std::cout << \"IDEMP:\\n\" << (rho*rho - rho) << \"\\n\";\n//   std::cout << \"H:\\n\" << H << \"\\n\";\n//   std::cout << \"HI\\n\";\n  std::cout << \"Energy: \" << std::real((rho * H).trace()) << \"\\n\";\n\n  // Need to take new rho and compute <P> = Tr(P rho) for each of our\n  // input functions\n\n  std::vector<std::shared_ptr<AcceleratorBuffer>> retBuffers;\n  for (auto& f : functions) {\n//       if (f->name() == \"I\") {\n//           continue;\n//       }\n//     auto tmp = xacc::getService<xacc::IRProvider>(\"gate\")->createIR();\n//     tmp->addKernel(f);\n\n//     PauliOperator o;\n//     o.fromXACCIR(tmp);\n\n//     auto mat = o.toDenseMatrix(buffer->size());\n//     auto expVal = std::real((rho * mat).trace());\n\n    if (bufMap.count(f->name())) {\n    auto b = bufMap[f->name()];\n    b->addExtraInfo(\"purified-energy\",ExtraInfo(std::real((rho*H).trace())));\n//     b->addExtraInfo(\"exp-val-z\", ExtraInfo(expVal));\n    retBuffers.push_back(b);\n    }\n  }\n\n  return retBuffers;\n}\n\n} // namespace vqe\n} // namespace xacc\n", "meta": {"hexsha": "5972a526df9103acc7ff7542ef5a63650b4604af", "size": 5743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "decorators/PurificationDecorator.cpp", "max_stars_repo_name": "zpparks314/xacc-vqe", "max_stars_repo_head_hexsha": "37aaadb12d856324532c42ca9f7e56147edbd2e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-09-15T19:05:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T05:24:51.000Z", "max_issues_repo_path": "decorators/PurificationDecorator.cpp", "max_issues_repo_name": "zpparks314/xacc-vqe", "max_issues_repo_head_hexsha": "37aaadb12d856324532c42ca9f7e56147edbd2e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 25.0, "max_issues_repo_issues_event_min_datetime": "2017-08-08T16:03:55.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-22T12:18:27.000Z", "max_forks_repo_path": "decorators/PurificationDecorator.cpp", "max_forks_repo_name": "zpparks314/xacc-vqe", "max_forks_repo_head_hexsha": "37aaadb12d856324532c42ca9f7e56147edbd2e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2018-06-25T20:20:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-03T18:31:44.000Z", "avg_line_length": 28.2906403941, "max_line_length": 84, "alphanum_fraction": 0.5904579488, "num_tokens": 1742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2321550700079415}}
{"text": "/* Copyright (C) 2013-2016, The Regents of The University of Michigan.\nAll rights reserved.\nThis software was developed in the APRIL Robotics Lab under the\ndirection of Edwin Olson, ebolson@umich.edu. This software may be\navailable under alternative licensing terms; contact the address above.\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nThe views and conclusions contained in the software and documentation are those\nof the authors and should not be interpreted as representing official policies,\neither expressed or implied, of the Regents of The University of Michigan.\n*/\n\n#include <iostream>\n#include <Eigen/Core>\n\n#include \"opencv2/opencv.hpp\"\n#include \"opencv2/core/eigen.hpp\"\n#include \"apriltag_pose.h\"\n#include <pangolin/pangolin.h>\n#include <sophus/se3.h>\n#include <boost/format.hpp>\n\nextern \"C\" {\n#include \"apriltag.h\"\n#include \"tag36h11.h\"\n#include \"common/getopt.h\"\n}\n#include <math.h>\n\n// #include <g2o/core/base_vertex.h>\n// #include <g2o/core/base_unary_edge.h>\n// #include <g2o/core/block_solver.h>\n// #include <g2o/core/optimization_algorithm_levenberg.h>\n// #include <g2o/types/sba/types_six_dof_expmap.h>\n// #include <g2o/solvers/dense/linear_solver_dense.h>\n// #include <g2o/core/robust_kernel.h>\n// #include <g2o/core/robust_kernel_impl.h>\n\n\nEigen::Matrix3d cam_R;\nEigen::Vector3d cam_t;\nEigen::Vector3d t_last, t_curr;\ndouble update_t = 0;\n\ntypedef std::vector<Sophus::SE3, Eigen::aligned_allocator<Sophus::SE3> > VecSE3;\ntypedef std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d> > VecVec3d;\ntypedef std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d> > VecVec2d;\n// apriltag 4-corner 3d points and 2d pixel\nVecVec3d tagpoints;\nVecVec2d tagpixels;\n\ndouble fx = 9.7185090185201193e+02;\ndouble fy = 9.3550247129566696e+02;\ndouble cx = 3.2389824020348124e+02;\ndouble cy = 2.1394131657430057e+02;\n\n#define RATIO 0.4 // orb \n\n// // g2o vertex that use sophus::SE3 as pose\n// class VertexSophus : public g2o::BaseVertex<6, Sophus::SE3> {\n// public:\n//     EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n//     VertexSophus() {}\n//     ~VertexSophus() {}\n\n//     bool read(std::istream &is) {}\n//     bool write(std::ostream &os) const {}\n\n//     virtual void setToOriginImpl() {\n//         _estimate = Sophus::SE3();\n//     }\n\n//     virtual void oplusImpl(const double *update_) {\n//         Eigen::Map<const Eigen::Matrix<double, 6, 1>> update(update_);\n//         setEstimate(Sophus::SE3::exp(update) * estimate());\n//     }\n// };\n\n// class EdgeProjectXYZ2UVPoseOnly: public g2o::BaseUnaryEdge<2, Eigen::Vector2d, VertexSophus >\n// {\n// public:\n//     EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n//     virtual void computeError();\n//     virtual void linearizeOplus();\n    \n//     virtual bool read( std::istream& in ){}\n//     virtual bool write(std::ostream& os) const {};\n    \n//     Eigen::Vector3d point_;\n// };\n\n// void EdgeProjectXYZ2UVPoseOnly::computeError()\n// {\n//     // compute projection error ...\n//     const VertexSophus *vertexTcw = static_cast<const VertexSophus*>( vertex(0) );\n//     Eigen::Vector3d p_c = vertexTcw->estimate()*point_;\n//     Eigen::Vector2d p_uv = Eigen::Vector2d (\n//         fx * p_c ( 0,0 ) / p_c ( 2,0 ) + cx,\n//         fy * p_c ( 1,0 ) / p_c ( 2,0 ) + cy\n//     );\n\n//     _error = _measurement - p_uv;\n// }\n\n// void EdgeProjectXYZ2UVPoseOnly::linearizeOplus()\n// {\n//     const VertexSophus* vertexTcw = static_cast<const VertexSophus* >( vertex(0) );\n//     Eigen::Vector3d xyz_trans = vertexTcw->estimate()*point_;\n//     double x = xyz_trans[0];\n//     double y = xyz_trans[1];\n//     double z = xyz_trans[2];\n//     double z_2 = z*z;\n\n//     _jacobianOplusXi ( 0,0 ) =  x*y/z_2 *fx;\n//     _jacobianOplusXi ( 0,1 ) = - ( 1+ ( x*x/z_2 ) ) *fx;\n//     _jacobianOplusXi ( 0,2 ) = y/z * fx;\n//     _jacobianOplusXi ( 0,3 ) = -1./z *fx;\n//     _jacobianOplusXi ( 0,4 ) = 0;\n//     _jacobianOplusXi ( 0,5 ) = x/z_2 *fx;\n\n//     _jacobianOplusXi ( 1,0 ) = ( 1+y*y/z_2 ) *fy;\n//     _jacobianOplusXi ( 1,1 ) = -x*y/z_2 *fy;\n//     _jacobianOplusXi ( 1,2 ) = -x/z *fy;\n//     _jacobianOplusXi ( 1,3 ) = 0;\n//     _jacobianOplusXi ( 1,4 ) = -1./z *fy;\n//     _jacobianOplusXi ( 1,5 ) = y/z_2 *fy;\n// }\n\n// plot the poses and points for you, need pangolin\nvoid Draw(const VecSE3 &poses, const VecVec3d &points, const apriltag_detection_info_t &info);\n\nvoid triangulation (\n    const std::vector<cv::KeyPoint>& keypoint_1,\n    const std::vector<cv::KeyPoint>& keypoint_2,\n    const std::vector< cv::DMatch >& matches,\n    cv::Mat T1, cv::Mat T2,\n    std::vector<cv::Point3d>& points);\n\nint main(int argc, char *argv[])\n{\n    getopt_t *getopt = getopt_create();\n\n    getopt_add_bool(getopt, 'h', \"help\", 0, \"Show this help\");\n    getopt_add_bool(getopt, 'd', \"debug\", 1, \"Enable debugging output (slow)\");\n    getopt_add_bool(getopt, 'q', \"quiet\", 0, \"Reduce output\");\n    getopt_add_string(getopt, 'f', \"family\", \"tag36h11\", \"Tag family to use\");\n    getopt_add_int(getopt, 't', \"threads\", \"1\", \"Use this many CPU threads\");\n    getopt_add_double(getopt, 'x', \"decimate\", \"2.0\", \"Decimate input image by this factor\");\n    getopt_add_double(getopt, 'b', \"blur\", \"0.0\", \"Apply low-pass blur to input\");\n    getopt_add_bool(getopt, '0', \"refine-edges\", 1, \"Spend more time trying to align edges of tags\");\n\n    if (!getopt_parse(getopt, argc, argv, 1) ||\n            getopt_get_bool(getopt, \"help\")) {\n        printf(\"Usage: %s [options]\\n\", argv[0]);\n        getopt_do_usage(getopt);\n        exit(0);\n    }\n\n    // Initialize camera\n    cv::VideoCapture cap(0);\n    if (!cap.isOpened()) {\n        std::cerr << \"Couldn't open video capture device\" << std::endl;\n        return -1;\n    }\n\n    // Initialize tag detector with options\n    apriltag_family_t *tf = NULL;\n    const char *famname = getopt_get_string(getopt, \"family\");\n    if (!strcmp(famname, \"tag36h11\")) {\n        tf = tag36h11_create();\n    } else {\n        printf(\"Unrecognized tag family name. Use e.g. \\\"tag36h11\\\".\\n\");\n        exit(-1);\n    }\n\n    apriltag_detection_info_t info;\n    info.tagsize = 13.8; //cm\n    info.fx = fx;\n    info.fy = fy;\n    info.cx = cx;\n    info.cy = cy;\n\n    double scale = info.tagsize/2.0;  // apriltag 4-corner 3d points \n\n    tagpoints.push_back( Eigen::Vector3d ( -scale,  scale, 0 ) );\n    tagpoints.push_back( Eigen::Vector3d (  scale,  scale, 0 ) );\n    tagpoints.push_back( Eigen::Vector3d (  scale, -scale, 0 ) );\n    tagpoints.push_back( Eigen::Vector3d ( -scale, -scale, 0 ) );\n\n\n    double camera_matrix[] =\n    {\n        info.fx,    0.0,       info.cx,\n        0.0,        info.fy,   info.cy,\n        0.0,        0.0,       1.0\n    };\n    double dist_coeff[] = {-1.0351230255308908e+00, -1.9662350850900434e+00, 0.0, 0.0};\n\n    cv::Mat m_camera_matrix = cv::Mat(3, 3, CV_64FC1, camera_matrix).clone();\n    cv::Mat m_dist_coeff = cv::Mat(1, 4, CV_64FC1, dist_coeff).clone();\n\n\n    apriltag_detector_t *td = apriltag_detector_create();\n    apriltag_detector_add_family(td, tf);\n    td->quad_decimate = getopt_get_double(getopt, \"decimate\");\n    td->quad_sigma = getopt_get_double(getopt, \"blur\");\n    td->nthreads = getopt_get_int(getopt, \"threads\");\n    td->debug = getopt_get_bool(getopt, \"debug\");\n    td->refine_edges = getopt_get_bool(getopt, \"refine-edges\");\n\n    cv::Mat frame, gray;\n    VecSE3 poses;\n    VecVec3d points;\n    std::vector<cv::Point3d> points_cv;\n\n    \n    cv::Mat last_img, cur_img;\n    cv::Mat T1, T2;\n        // cv::Mat T1 = (cv::Mat_<double> (3,4) <<\n    //     1,0,0,0,\n    //     0,1,0,0,\n    //     0,0,1,0);\n    // cv::Mat T2 = (cv::Mat_<double> (3,4) <<\n    //     R.at<double>(0,0), R.at<double>(0,1), R.at<double>(0,2), t.at<double>(0,0),\n    //     R.at<double>(1,0), R.at<double>(1,1), R.at<double>(1,2), t.at<double>(1,0),\n    //     R.at<double>(2,0), R.at<double>(2,1), R.at<double>(2,2), t.at<double>(2,0)\n    //     );\n    bool initial = false;\n    int limit_min_times = 0;\n    while (true) {\n        cap >> frame;\n        cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY);\n        \n        // Make an image_u8_t header for the Mat data\n        image_u8_t im = { .width = gray.cols,\n            .height = gray.rows,\n            .stride = gray.cols,\n            .buf = gray.data\n        };\n\n        zarray_t *detections = apriltag_detector_detect(td, &im);\n        // cout << zarray_size(detections) << \" tags detected\" << endl;\n\n        // Draw detection outlines\n        for (int i = 0; i < zarray_size(detections); i++) {\n            limit_min_times++;\n\n            apriltag_detection_t *det;\n            zarray_get(detections, i, &det);\n            info.det = det; \n            apriltag_pose_t pose;\n\t\t\tdouble err = estimate_tag_pose(&info, &pose);\n            double wx, wy, wz;\n\n            double scale = 107.0/220.0;  //depth scale = realvalue / measurement = 107cm/220\n\n            wx = pose.t->data[0]*scale;\n            wy = pose.t->data[1]*scale;\n            wz = pose.t->data[2]*scale;\n\t\t\t// cout << wx <<\"  \"<< wy << \" \" << wz << endl;\n\n\n            if( !initial ){\n                last_img = gray.clone();\n                cur_img = gray.clone();\n                T1 = (cv::Mat_<double> (3,4) <<\n                    pose.R->data[0], pose.R->data[1], pose.R->data[2], pose.t->data[0],\n                    pose.R->data[3], pose.R->data[4], pose.R->data[5], pose.t->data[1],\n                    pose.R->data[6], pose.R->data[7], pose.R->data[8], pose.t->data[2]\n                    );\n                T2 = (cv::Mat_<double> (3,4) <<\n                    pose.R->data[0], pose.R->data[1], pose.R->data[2], pose.t->data[0],\n                    pose.R->data[3], pose.R->data[4], pose.R->data[5], pose.t->data[1],\n                    pose.R->data[6], pose.R->data[7], pose.R->data[8], pose.t->data[2]\n                    );\n                // initial = true;\n                if( limit_min_times > 10){\n                    initial = true;\n                }\n            }else{\n                // std::cout << \"initial is ok!!!!\" << \"\\n\";\n                cur_img = gray.clone();\n                T2 = (cv::Mat_<double> (3,4) <<\n                    pose.R->data[0], pose.R->data[1], pose.R->data[2], pose.t->data[0],\n                    pose.R->data[3], pose.R->data[4], pose.R->data[5], pose.t->data[1],\n                    pose.R->data[6], pose.R->data[7], pose.R->data[8], pose.t->data[2]\n                    );\n            }\n            // std::cout << \"initial:\" << initial << \"||\" << T1.size() << \"||\" << T2.size() << \"\\n\";\n            // std::cout << \"last_img\" << last_img.size() << \" cur_img\" << cur_img.size() << \"\\n\";\n\n            \n            double depth = sqrt( wx*wx + wy*wy + wz*wz );\n            \n            // cout << \"depth = \" << depth << endl;\n\t\t\t// cout << \"R size:\" << pose.R->nrows <<\" \"<< pose.R->ncols << endl;  //3*3\n            // cout << \"R:\" << endl;\n            // cout << pose.R->data[0] <<\" \"<< pose.R->data[1] << \" \" << pose.R->data[2] << endl;  //3*3\n            // cout << pose.R->data[3] <<\" \"<< pose.R->data[4] << \" \" << pose.R->data[5] << endl;  //3*3\n            // cout << pose.R->data[6] <<\" \"<< pose.R->data[7] << \" \" << pose.R->data[8] << endl;  //3*3\n\n\n            cv::line(frame, cv::Point(det->p[0][0], det->p[0][1]),\n                     cv::Point(det->p[1][0], det->p[1][1]),\n                     cv::Scalar(0xff, 0xff, 0xff), 2);\n            cv::line(frame, cv::Point(det->p[0][0], det->p[0][1]),\n                     cv::Point(det->p[3][0], det->p[3][1]),\n                     cv::Scalar(0xff, 0xff, 0xff), 2);\n            cv::line(frame, cv::Point(det->p[1][0], det->p[1][1]),\n                     cv::Point(det->p[2][0], det->p[2][1]),\n                     cv::Scalar(0xff, 0xff, 0xff), 2);\n            cv::line(frame, cv::Point(det->p[2][0], det->p[2][1]),\n                     cv::Point(det->p[3][0], det->p[3][1]),\n                     cv::Scalar(0xff, 0xff, 0xff), 2);\n\n            cv::circle(frame, cv::Point(det->p[0][0], det->p[0][1]),\n                2,\n                cv::Scalar(0xff, 0xff, 0), 2); \n\n            std::stringstream ss;\n            ss << det->id;\n            cv::String text = ss.str();\n            int fontface = cv::FONT_HERSHEY_SCRIPT_SIMPLEX;\n            double fontscale = 1.0;\n            int baseline;\n            cv::Size textsize = getTextSize(text, fontface, fontscale, 2,\n                                            &baseline);\n            putText(frame, text, cv::Point(det->c[0]-textsize.width/2,\n                                       det->c[1]+textsize.height/2),\n                    fontface, fontscale, cv::Scalar(0xff, 0x99, 0), 2);\n\n\n            cam_t << wx, wy, wz;\n            cam_R << pose.R->data[0], pose.R->data[1], pose.R->data[2],\n                pose.R->data[3], pose.R->data[4], pose.R->data[5],\n                pose.R->data[6], pose.R->data[7], pose.R->data[8];\n\n\n            // three-dimensional cube test (cudePoints)\n            std::vector< cv::Point3f > cubePoints;\n            cubePoints.push_back(cv::Point3f(-0.5, -0.5, 0.0));\n            cubePoints.push_back(cv::Point3f( 0.5, -0.5, 0.0));\n            cubePoints.push_back(cv::Point3f( 0.5,  0.5, 0.0));\n            cubePoints.push_back(cv::Point3f(-0.5,  0.5, 0.0));\n            cubePoints.push_back(cv::Point3f(-0.5, -0.5, 1.0));\n            cubePoints.push_back(cv::Point3f( 0.5, -0.5, 1.0));\n            cubePoints.push_back(cv::Point3f( 0.5,  0.5, 1.0));\n            cubePoints.push_back(cv::Point3f(-0.5,  0.5, 1.0));\n\n\n            std::vector< cv::Point2f > imagePoints;\n            bool solvePnP_isok = false;\n            cv::Mat cv_cam_R, cv_cam_t;\n            if ( solvePnP_isok ){\n                cv::Point3f corners_3d[] =\n                {\n                    cv::Point3f(-0.5f, -0.5f, 0),\n                    cv::Point3f(-0.5f,  0.5f, 0),\n                    cv::Point3f( 0.5f,  0.5f, 0),\n                    cv::Point3f( 0.5f, -0.5f, 0)\n                };\n                std::vector<cv::Point3f> m_corners_3d = std::vector<cv::Point3f>(corners_3d, corners_3d + 4);\n                std::vector<cv::Point2f> m_corners;\n                m_corners.push_back(cv::Point2f(det->p[0][0], det->p[0][1]));\n                m_corners.push_back(cv::Point2f(det->p[1][0], det->p[1][1]));\n                m_corners.push_back(cv::Point2f(det->p[2][0], det->p[2][1]));\n                m_corners.push_back(cv::Point2f(det->p[3][0], det->p[3][1]));\n\n                cv::Mat rot_vec;\n                cv::solvePnP(m_corners_3d, m_corners, m_camera_matrix, m_dist_coeff, rot_vec, cv_cam_t);\n                cv::Rodrigues(rot_vec, cv_cam_R);\n                cv::projectPoints(cubePoints, cv_cam_R, cv_cam_t, m_camera_matrix, m_dist_coeff, imagePoints);\n            }else{\n                for ( auto &p:cubePoints ){\n                    p = p*5;\n                }\n                cv::eigen2cv(cam_R, cv_cam_R);\n                cv::eigen2cv(cam_t, cv_cam_t);\n                cv::projectPoints(cubePoints, cv_cam_R, cv_cam_t, m_camera_matrix, m_dist_coeff, imagePoints);\n            }\n            \n\n\n            // draw cube lines\n            cv::line(frame, imagePoints[0], imagePoints[1], cv::Scalar(0, 0, 0xff), 2);\n            cv::line(frame, imagePoints[1], imagePoints[2], cv::Scalar(0, 0, 0xff), 2);\n            cv::line(frame, imagePoints[2], imagePoints[3], cv::Scalar(0, 0, 0xff), 2);\n            cv::line(frame, imagePoints[3], imagePoints[0], cv::Scalar(0, 0, 0xff), 2);\n\n            cv::line(frame, imagePoints[4], imagePoints[5], cv::Scalar(0xff, 0, 0), 2);\n            cv::line(frame, imagePoints[5], imagePoints[6], cv::Scalar(0xff, 0, 0), 2);\n            cv::line(frame, imagePoints[6], imagePoints[7], cv::Scalar(0xff, 0, 0), 2);\n            cv::line(frame, imagePoints[7], imagePoints[4], cv::Scalar(0xff, 0, 0), 2);\n\n            cv::line(frame, imagePoints[0], imagePoints[4], cv::Scalar(0, 0xff, 0), 2);\n            cv::line(frame, imagePoints[1], imagePoints[5], cv::Scalar(0, 0xff, 0), 2);\n            cv::line(frame, imagePoints[2], imagePoints[6], cv::Scalar(0, 0xff, 0), 2);\n            cv::line(frame, imagePoints[3], imagePoints[7], cv::Scalar(0, 0xff, 0), 2);\n\n\n            // Note that every variable that we compute is proportional to the scale factor of H.\n            // or pnp, cv::solvePnP  cv::Rodrigues\n\n            double H00 = MATD_EL(det->H, 0, 0);\n            double H01 = MATD_EL(det->H, 0, 1);\n            double H02 = MATD_EL(det->H, 0, 2);\n            double H10 = MATD_EL(det->H, 1, 0);\n            double H11 = MATD_EL(det->H, 1, 1);\n            double H12 = MATD_EL(det->H, 1, 2);\n            double H20 = MATD_EL(det->H, 2, 0);\n            double H21 = MATD_EL(det->H, 2, 1);\n            double H22 = MATD_EL(det->H, 2, 2);\n            // cout << \"H = \" << H00 << \" \" << H01 << endl;\n            \n            for( int i = 0; i < 4; i++ ){\n                tagpixels.push_back( Eigen::Vector2d(det->p[i][0], det->p[i][1]) );\n            }\n            Sophus::SE3 SE3_Rt( cam_R, cam_t );\n            poses.push_back( SE3_Rt );\n\n            // last_img = gray.clone();\n            // cur_img = gray.clone();\n\n            if( initial ){\n                // ORB Features\n                std::vector<cv::KeyPoint> keypoints_sence, keypoints_obj;\n                cv::Mat descriptors_box, descriptors_sence;\n                cv::Ptr<cv::ORB> detector = cv::ORB::create();\n\n                detector->detectAndCompute(last_img, cv::Mat(), keypoints_sence, descriptors_sence);\n                detector->detectAndCompute(cur_img, cv::Mat(), keypoints_obj, descriptors_box);\n                std::vector<cv::DMatch> matches;\n                // 初始化flann匹配\n                // cv::Ptr<cv::FlannBasedMatcher> matcher = cv::FlannBasedMatcher::create(); // default is bad, using local sensitive hash(LSH)\n                cv::Ptr<cv::DescriptorMatcher> matcher = cv::makePtr<cv::FlannBasedMatcher>(cv::makePtr<cv::flann::LshIndexParams>(12, 20, 2));\n                matcher->match(descriptors_box, descriptors_sence, matches);\n                // 发现匹配\n                std::vector<cv::DMatch> goodMatches;\n                \n                float maxdist = 0;\n                for (unsigned int i = 0; i < matches.size(); ++i) {\n                    // printf(\"dist : %.2f \\n\", matches[i].distance);\n                    maxdist = cv::max(maxdist, matches[i].distance);\n                }\n                for (unsigned int i = 0; i < matches.size(); ++i) {\n                    if (matches[i].distance < maxdist*RATIO)\n                        goodMatches.push_back(matches[i]);\n                }\n\n                // cv::Mat dst;\n                // cv::drawMatches(cur_img, keypoints_obj, last_img, keypoints_sence, goodMatches, dst);\n                // cv::imshow(\"output\", dst);\n                // cv::waitKey(0);\n                // cv::Mat R_cv = (cv::Mat_<double> (3,3) <<\n                //     pose.R->data[0], pose.R->data[1], pose.R->data[2],\n                //     pose.R->data[3], pose.R->data[4], pose.R->data[5],\n                //     pose.R->data[6], pose.R->data[7], pose.R->data[8]);\n                \n                // cv::Mat t_cv = (cv::Mat_<double> (3,1) <<\n                //     wx, wy, wz);\n                \n                // std::cout << R_cv << \"\\n\";\n                // std::cout << t_cv << \"\\n\";\n                // std::cout << \"keypoints_sence:\" << keypoints_sence.size() << \"\\n\";\n                // std::cout << \"keypoints_obj:\" << keypoints_obj.size() << \"\\n\";\n                // std::cout << \"T1:\" << T1 << \"\\n\\n\";\n                // std::cout << \"T2:\" << T2 << \"\\n\";\n                // printf(\"total match points : %d || goodMatches: %d\\n\", matches.size(), goodMatches.size());\n                \n                // 绘制关键点\n                // cv::Mat keypoint_img;\n                cv::drawKeypoints(frame, keypoints_obj, frame, cv::Scalar::all(-1), cv::DrawMatchesFlags::DEFAULT);\n                // cv::imshow(\"KeyPoints Image\", keypoint_img);\n\n\n                \n                t_last << T1.at<double>(0,3), T1.at<double>(1,3), T1.at<double>(2,3);\n                t_curr << T2.at<double>(0,3), T2.at<double>(1,3), T2.at<double>(2,3);\n                Eigen::Vector3d t_tmp = t_last - t_curr;\n                update_t = fabsf(t_tmp[0]) + fabsf(t_tmp[1]) + fabsf(t_tmp[2]);\n                std::cout << \"update_t:\"<< update_t << \"\\n\";\n                // std::cout << \"t_last:\" << t_last << \"\\n\";\n                // std::cout << \"t_curr:\" << t_curr << \"\\n\";\n                if(goodMatches.size()>0 && update_t > 10){\n                    // std::cout << \"keypoints_sence:\" << keypoints_sence.size() << \"\\n\";\n                    // std::cout << \"keypoints_obj:\" << keypoints_obj.size() << \"\\n\";\n                    // std::cout << \"T1:\" << T1 << \"\\n\";\n                    // std::cout << \"T2:\" << T2 << \"\\n\";\n                    triangulation ( keypoints_sence, keypoints_obj, goodMatches, T1, T2, points_cv );\n                }\n            }\n        }\n        if(update_t > 10){\n            last_img = cur_img.clone();\n            T1 = T2.clone();\n        }\n\n    \n\n        \n        \n        apriltag_detections_destroy(detections);\n\n        imshow(\"Tag Detections\", frame);\n\n        if (cv::waitKey(30) == 'q')\n            break;\n    }\n    // // using bundle adjustment to optimize the pose\n    // typedef g2o::BlockSolver<g2o::BlockSolverTraits<6,2>> Block;\n    // Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>();\n    // Block* solver_ptr = new Block( linearSolver );\n    // g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n    // g2o::SparseOptimizer optimizer;\n    // optimizer.setAlgorithm ( solver );\n\n\n    // // add pose vertices\n    // for( int j = 0; j < poses.size(); j++ ){\n    //     VertexSophus* vertexTcw = new VertexSophus();\n    //     vertexTcw->setEstimate( poses[j] );\n    //     vertexTcw->setId( j );\n    //     optimizer.addVertex( vertexTcw );\n    // }\n\n    // // edges\n    // for( int c = 0; c < poses.size(); c++ )\n    //     for ( int i=0; i<4; i++ ){\n    //         // 3D -> 2D projection\n    //         EdgeProjectXYZ2UVPoseOnly* edge = new EdgeProjectXYZ2UVPoseOnly();\n    //         // edge->setId ( i );\n    //         edge->setVertex ( 0, dynamic_cast<VertexSophus*>(optimizer.vertex(c)) );\n    //         edge->point_ = tagpoints[i];\n    //         edge->setMeasurement ( tagpixels[c*4 + i] );\n    //         edge->setInformation ( Eigen::Matrix2d::Identity() );\n    //         optimizer.addEdge ( edge );\n    //     }\n    \n    // optimizer.initializeOptimization();\n    // optimizer.optimize ( 10 );\n\n    // // fetch data from the optimizer\n    // for(int c = 0; c < poses.size(); c++){\n    //     // Eigen::Vector3d Pw = dynamic_cast<g2o::VertexSBAPointXYZ*>(optimizer.vertex(p))->estimate();\n    //     // points[p] = Pw;\n    //     Sophus::SE3 Tcw = dynamic_cast<VertexSophus*>( optimizer.vertex(c) )->estimate();\n    //     poses[c] = Tcw;\n    // }\n\n    for(int pt_indx = 0; pt_indx < points_cv.size(); pt_indx++){\n        points.push_back( Eigen::Vector3d ( points_cv[pt_indx].x,  points_cv[pt_indx].y, points_cv[pt_indx].z ) );\n    }\n    // points.push_back( Eigen::Vector3d ( -scale,  scale, 0 ) );\n    // points.push_back( Eigen::Vector3d (  scale,  scale, 0 ) );\n    // points.push_back( Eigen::Vector3d (  scale, -scale, 0 ) );\n    // points.push_back( Eigen::Vector3d ( -scale, -scale, 0 ) );\n\n    Draw(poses, points, info);\n    apriltag_detector_destroy(td);\n\n    if (!strcmp(famname, \"tag36h11\")) {\n        tag36h11_destroy(tf);\n    } \n\n    getopt_destroy(getopt);\n\n    return 0;\n}\n\n\ncv::Point2d pixel2cam ( const cv::Point2d& p, const cv::Mat& K )\n{\n   return cv::Point2d\n          (\n              ( p.x - K.at<double> ( 0,2 ) ) / K.at<double> ( 0,0 ),\n              ( p.y - K.at<double> ( 1,2 ) ) / K.at<double> ( 1,1 )\n          );\n}\n\n\n\nvoid triangulation (\n    const std::vector<cv::KeyPoint>& keypoint_1,\n    const std::vector<cv::KeyPoint>& keypoint_2,\n    const std::vector< cv::DMatch >& matches,\n    cv::Mat T1, cv::Mat T2,\n    std::vector<cv::Point3d>& points)\n{\n    // cv::Mat T1 = (cv::Mat_<double> (3,4) <<\n    //     1,0,0,0,\n    //     0,1,0,0,\n    //     0,0,1,0);\n    // cv::Mat T2 = (cv::Mat_<double> (3,4) <<\n    //     R.at<double>(0,0), R.at<double>(0,1), R.at<double>(0,2), t.at<double>(0,0),\n    //     R.at<double>(1,0), R.at<double>(1,1), R.at<double>(1,2), t.at<double>(1,0),\n    //     R.at<double>(2,0), R.at<double>(2,1), R.at<double>(2,2), t.at<double>(2,0)\n    //     );\n\n        // info.fx,    0.0,       info.cx,\n        // 0.0,        info.fy,   info.cy,\n        // 0.0,        0.0,       1.0\n    cv::Mat K = ( cv::Mat_<double> ( 3,3 ) << fx, 0, cx, 0, fy, cy, 0, 0, 1 );\n\n    std::vector<cv::Point2d> pts_1, pts_2;\n    for ( cv::DMatch m:matches )\n    {\n        // 将像素坐标转换至相机坐标\n        pts_1.push_back ( pixel2cam( keypoint_1[m.queryIdx].pt, K) );\n        pts_2.push_back ( pixel2cam( keypoint_2[m.trainIdx].pt, K) );\n    }\n\n    cv::Mat pts_4d;\n    cv::triangulatePoints( T1, T2, pts_1, pts_2, pts_4d );\n\n    // 转换成非齐次坐标\n    for ( int i=0; i<pts_4d.cols; i++ )\n    {\n        cv::Mat x = pts_4d.col(i);\n\n        if(x.at<float>(3,0) < 1.0) continue;\n        \n        x /= x.at<float>(3,0); // 归一化\n        cv::Point3d p (\n            x.at<float>(0,0),\n            x.at<float>(1,0),\n            x.at<float>(2,0)\n        );\n        points.push_back( p );\n    }\n}\n\nvoid Draw(const VecSE3 &poses, const VecVec3d &points, const apriltag_detection_info_t &info) {\n    if (poses.empty() || points.empty()) {\n        std::cerr << \"parameter is empty!\" << std::endl;\n        return;\n    }\n\n    // create pangolin window and plot the trajectory\n    pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n    glEnable(GL_DEPTH_TEST);\n    glEnable(GL_BLEND);\n    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n    pangolin::OpenGlRenderState s_cam(\n            pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n            pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n    );\n\n    pangolin::View &d_cam = pangolin::CreateDisplay()\n            .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)\n            .SetHandler(new pangolin::Handler3D(s_cam));\n\n\n    while (pangolin::ShouldQuit() == false) {\n        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n        d_cam.Activate(s_cam);\n        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n\n        // intrinsics\n        float fx = info.fx;\n        float fy = info.fy;\n        float cx = info.cx;\n        float cy = info.cy;\n\n        // draw poses\n        float sz = 0.1;\n        int width = 640, height = 480;\n        for (auto &Tcw: poses) {\n            glPushMatrix();\n            Sophus::Matrix4f m = Tcw.inverse().matrix().cast<float>();\n            glMultMatrixf((GLfloat *) m.data());\n            glColor3f(1, 0, 0);\n            glLineWidth(2);\n            glBegin(GL_LINES);\n            glVertex3f(0, 0, 0);\n            glVertex3f(sz * (0 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glVertex3f(0, 0, 0);\n            glVertex3f(sz * (0 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(0, 0, 0);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(0, 0, 0);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(sz * (0 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(sz * (0 - cx) / fx, sz * (height - 1 - cy) / fy, sz);\n            glVertex3f(sz * (0 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glVertex3f(sz * (0 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glVertex3f(sz * (width - 1 - cx) / fx, sz * (0 - cy) / fy, sz);\n            glEnd();\n            glPopMatrix();\n        }\n\n        // points\n        glPointSize(2);\n        glBegin(GL_POINTS);\n        for (size_t i = 0; i < points.size(); i++) {\n            glColor3f(0.0, 1, 0);\n            glVertex3d(points[i][0], points[i][1], points[i][2]);\n        }\n        glEnd();\n\n        pangolin::FinishFrame();\n        usleep(5000);   // sleep 5 ms\n    }\n}\n", "meta": {"hexsha": "6453eb9b1c65036987219e215901f6fc45b08a52", "size": 29523, "ext": "cc", "lang": "C++", "max_stars_repo_path": "example/opencv_demo.cc", "max_stars_repo_name": "suljaxm/apriltag_AR", "max_stars_repo_head_hexsha": "044ed0b563b0f9956ab72d571a38050b1b8d9682", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-06T19:30:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-26T12:03:49.000Z", "max_issues_repo_path": "example/opencv_demo.cc", "max_issues_repo_name": "suljaxm/apriltag_AR", "max_issues_repo_head_hexsha": "044ed0b563b0f9956ab72d571a38050b1b8d9682", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/opencv_demo.cc", "max_forks_repo_name": "suljaxm/apriltag_AR", "max_forks_repo_head_hexsha": "044ed0b563b0f9956ab72d571a38050b1b8d9682", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6652892562, "max_line_length": 143, "alphanum_fraction": 0.5343969109, "num_tokens": 9027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2321200120744428}}
{"text": "// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers\n// Copyright (c) 2017-2019, The Iridium developers\n// Copyright (c) 2018-2019, The MonetaVerde developers\n//\n// This file is part of Bytecoin.\n//\n// Bytecoin is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Lesser General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// Bytecoin is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU Lesser General Public License for more details.\n//\n// You should have received a copy of the GNU Lesser General Public License\n// along with Bytecoin.  If not, see <http://www.gnu.org/licenses/>.\n\n#include \"Currency.h\"\n#include <cctype>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/lexical_cast.hpp>\n#include \"../Common/Math.h\"\n#include \"../Common/Base58.h\"\n#include \"../Common/int-util.h\"\n#include \"../Common/StringTools.h\"\n\n#include \"Account.h\"\n#include \"CryptoNoteBasicImpl.h\"\n#include \"CryptoNoteFormatUtils.h\"\n#include \"CryptoNoteTools.h\"\n#include \"TransactionExtra.h\"\n#include \"UpgradeDetector.h\"\n\n#undef ERROR\n\nusing namespace Logging;\nusing namespace Common;\n\nnamespace CryptoNote {\n\n/* BLACKROSEDIAMONDV2 COMPATIBILITY */\n#if defined(_MSC_VER)\n    /*    #define NOMINMAX 1\n    #include <windows.h>\n    #include <winnt.h>\n\n    static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {\n        low = mul128(a, b, &high);\n    }\n    */\n    #include <intrin.h>\n\n    #pragma intrinsic(_umul128)\n\n    static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {\n        low = _umul128(a, b, &high);\n    }\n\n#else\n\n    static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {\n        typedef unsigned __int128 uint128_t;\n        uint128_t res = (uint128_t) a * (uint128_t) b;\n        low = (uint64_t) res;\n        high = (uint64_t) (res >> 64);\n    }\n\n#endif\n\n\t\n\tuint64_t log2_fix(uint64_t x, size_t log_fix_precision)\n    {\n      assert(x != 0);\n      assert(1 <= log_fix_precision && log_fix_precision < sizeof(uint64_t) * 8 / 2 - 1); // \"Invalid log precision\"\n\n      uint64_t b = UINT64_C(1) << (log_fix_precision - 1);\n      uint64_t y = 0;\n\n      while (x >= (UINT64_C(2) << log_fix_precision))\n      {\n        x >>= 1;\n        y += UINT64_C(1) << log_fix_precision;\n      }\n\n      // 64 bits are enough, because of x < 2 * (1 << log_fix_precision) <= 2^32\n      uint64_t z = x;\n      for (size_t i = 0; i < log_fix_precision; i++)\n      {\n        z = (z * z) >> log_fix_precision;\n        if (z >= (UINT64_C(2) << log_fix_precision))\n        {\n          z >>= 1;\n          y += b;\n        }\n        b >>= 1;\n      }\n\n      return y;\n  }\n/* /END BLACKROSEDIAMONDV2 */\n\nconst std::vector<uint64_t> Currency::PRETTY_AMOUNTS = {\n    1, 2, 3, 4, 5, 6, 7, 8, 9,\n    10, 20, 30, 40, 50, 60, 70, 80, 90,\n    100, 200, 300, 400, 500, 600, 700, 800, 900,\n    1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000,\n    10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000,\n    100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000,\n    1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000, 8000000, 9000000,\n    10000000, 20000000, 30000000, 40000000, 50000000, 60000000, 70000000, 80000000, 90000000,\n    100000000, 200000000, 300000000, 400000000, 500000000, 600000000, 700000000, 800000000, 900000000,\n    1000000000, 2000000000, 3000000000, 4000000000, 5000000000, 6000000000, 7000000000, 8000000000, 9000000000,\n    10000000000, 20000000000, 30000000000, 40000000000, 50000000000, 60000000000, 70000000000, 80000000000, 90000000000,\n    100000000000, 200000000000, 300000000000, 400000000000, 500000000000, 600000000000, 700000000000, 800000000000, 900000000000,\n    1000000000000, 2000000000000, 3000000000000, 4000000000000, 5000000000000, 6000000000000, 7000000000000, 8000000000000, 9000000000000,\n    10000000000000, 20000000000000, 30000000000000, 40000000000000, 50000000000000, 60000000000000, 70000000000000, 80000000000000, 90000000000000,\n    100000000000000, 200000000000000, 300000000000000, 400000000000000, 500000000000000, 600000000000000, 700000000000000, 800000000000000, 900000000000000,\n    1000000000000000, 2000000000000000, 3000000000000000, 4000000000000000, 5000000000000000, 6000000000000000, 7000000000000000, 8000000000000000, 9000000000000000,\n    10000000000000000, 20000000000000000, 30000000000000000, 40000000000000000, 50000000000000000, 60000000000000000, 70000000000000000, 80000000000000000, 90000000000000000,\n    100000000000000000, 200000000000000000, 300000000000000000, 400000000000000000, 500000000000000000, 600000000000000000, 700000000000000000, 800000000000000000, 900000000000000000,\n    1000000000000000000, 2000000000000000000, 3000000000000000000, 4000000000000000000, 5000000000000000000, 6000000000000000000, 7000000000000000000, 8000000000000000000, 9000000000000000000,\n    10000000000000000000ull\n};\n\nbool Currency::init() {\n    if (!generateGenesisBlock()) {\n        logger(ERROR, BRIGHT_RED) << \"Failed to generate genesis block\";\n        return false;\n    }\n\n    try {\n        cachedGenesisBlock->getBlockHash();\n    } catch (std::exception& e) {\n        logger(ERROR, BRIGHT_RED) << \"Failed to get genesis block hash: \" << e.what();\n        return false;\n    }\n\n    if (isTestnet()) {\n        m_upgradeHeightV2 = m_testnetUpgradeHeightV2;\n        m_upgradeHeightV3 = m_testnetUpgradeHeightV3;\n        m_upgradeHeightV4 = m_testnetUpgradeHeightV4;\n        m_difficultyTarget = m_testnet_DifficultyTarget;\n        m_blocksFileName = \"testnet_\" + m_blocksFileName;\n        m_blockIndexesFileName = \"testnet_\" + m_blockIndexesFileName;\n        m_txPoolFileName = \"testnet_\" + m_txPoolFileName;\n        logger(INFO, RED) << \"V2 Height : \" << m_upgradeHeightV2;\n        logger(INFO, RED) << \"V3 Height : \" << m_upgradeHeightV3;\n        logger(INFO, RED) << \"V4 Height : \" << m_upgradeHeightV4;\n        logger(INFO, RED) << \"Target : \" << m_difficultyTarget << \"s\";\n    }\n\n    return true;\n}\n\nbool Currency::generateGenesisBlock() {\n    genesisBlockTemplate = boost::value_initialized<BlockTemplate>();\n\n    //account_public_address ac = boost::value_initialized<AccountPublicAddress>();\n    //std::vector<size_t> sz;\n    //constructMinerTx(0, 0, 0, 0, 0, ac, m_genesisBlock.baseTransaction); // zero fee in genesis\n    //BinaryArray txb = toBinaryArray(m_genesisBlock.baseTransaction);\n    //std::string hex_tx_represent = Common::toHex(txb);\n\n    // Hard code coinbase tx in genesis block, because through generating tx use random, but genesis should be always the same\n    // This is the BlackRoseDiamondV2 genesis transaction\n    std::string genesisCoinbaseTxHex = GENESIS_COINBASE_TX_HEX;\n    BinaryArray minerTxBlob;\n\n    bool r =\n            fromHex(genesisCoinbaseTxHex, minerTxBlob) &&\n            fromBinaryArray(genesisBlockTemplate.baseTransaction, minerTxBlob);\n\n    if (!r) {\n        logger(ERROR, BRIGHT_RED) << \"failed to parse coinbase tx from hard coded blob\";\n        return false;\n    }\n\n    genesisBlockTemplate.majorVersion = BLOCK_MAJOR_VERSION_1;\n    genesisBlockTemplate.minorVersion = BLOCK_MINOR_VERSION_0;\n    genesisBlockTemplate.timestamp = 0;\n    genesisBlockTemplate.nonce = 10000;\n    if (m_testnet) {\n        ++genesisBlockTemplate.nonce;\n    }\n    //miner::find_nonce_for_given_block(bl, 1, 0);\n    cachedGenesisBlock.reset(new CachedBlock(genesisBlockTemplate));\n    return true;\n}\n\nsize_t Currency::difficultyWindowByBlockVersion(uint8_t blockMajorVersion) const {\n    if (blockMajorVersion >= BLOCK_MAJOR_VERSION_3) {\n        return CryptoNote::parameters::DIFFICULTY_WINDOW_V3;\n    } else {\n        return CryptoNote::parameters::DIFFICULTY_WINDOW;\n    }\n}\n\nsize_t Currency::difficultyLagByBlockVersion(uint8_t blockMajorVersion) const {\n    if (blockMajorVersion >= BLOCK_MAJOR_VERSION_2) {\n        return CryptoNote::parameters::DIFFICULTY_LAG_V2; // lag = 0 since V2\n    } else {\n        return CryptoNote::parameters::DIFFICULTY_LAG;\n    }\n}\n\nsize_t Currency::difficultyCutByBlockVersion(uint8_t blockMajorVersion) const {\n        return CryptoNote::parameters::DIFFICULTY_CUT;\n}\n\nsize_t Currency::difficultyBlocksCountByBlockVersion(uint8_t blockMajorVersion) const {\n    if (blockMajorVersion >= BLOCK_MAJOR_VERSION_2) {\n        return DIFFICULTY_BLOCKS_COUNT;\n    } else {\n        return difficultyWindowByBlockVersion(blockMajorVersion) + difficultyLagByBlockVersion(blockMajorVersion);\n    }\n}\n\nsize_t Currency::blockGrantedFullRewardZoneByBlockVersion(uint8_t blockMajorVersion) const {\n    if (blockMajorVersion >= BLOCK_MAJOR_VERSION_2) {\n        return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_CURRENT; // does not change since V2\n    } else {\n        return CryptoNote::parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V1;\n    }\n}\n\nuint32_t Currency::upgradeHeight(uint8_t majorVersion) const {\n    if (majorVersion == BLOCK_MAJOR_VERSION_4) {\n        return m_upgradeHeightV4;\n    } else if (majorVersion == BLOCK_MAJOR_VERSION_3) {\n        return m_upgradeHeightV3;\n    } else if (majorVersion == BLOCK_MAJOR_VERSION_2) {\n        return m_upgradeHeightV2;\n    } else {\n        return static_cast<uint32_t>(-1);\n    }\n}\n\nbool Currency::getBlockReward(uint8_t blockMajorVersion, size_t medianSize, size_t currentBlockSize, uint64_t alreadyGeneratedCoins,\n\tuint64_t fee, uint64_t& reward, int64_t& emissionChange, const Difficulty diff) const {\n\n    size_t log_fix_precision = blockMajorVersion > BLOCK_MAJOR_VERSION_2? (parameters::BLOCK_REWARD_LOG_FIX_PRECISION_V3):(parameters::BLOCK_REWARD_LOG_FIX_PRECISION);\n\n   assert(diff != 0);\n   assert(static_cast<uint64_t>(diff) < (UINT64_C(1) << (sizeof(uint64_t) * 8 - log_fix_precision)));\n   uint64_t baseReward = log2_fix(diff << log_fix_precision, log_fix_precision) << 20;\n   // logger(Logging::INFO, Logging::BRIGHT_GREEN) << \"baseReward: \" << baseReward << \", con diff \" << (int)diff << \", log fix: \" << log_fix_precision << \", b.majorv: \" << (int)blockMajorVersion;\n\t// assert(alreadyGeneratedCoins <= m_moneySupply);\n\tassert(m_emissionSpeedFactor > 0 && m_emissionSpeedFactor <= 8 * sizeof(uint64_t));\n\n\t// Tail emission\n/*\n\tuint64_t baseReward = (m_moneySupply - alreadyGeneratedCoins) >> m_emissionSpeedFactor;\n\tif (alreadyGeneratedCoins + CryptoNote::parameters::TAIL_EMISSION_REWARD >= m_moneySupply || baseReward < CryptoNote::parameters::TAIL_EMISSION_REWARD)\n\t{\n\t\tbaseReward = CryptoNote::parameters::TAIL_EMISSION_REWARD;\n\t}\n*/\n\tsize_t blockGrantedFullRewardZone = blockGrantedFullRewardZoneByBlockVersion(blockMajorVersion);\n\tmedianSize = std::max(medianSize, blockGrantedFullRewardZone);\n\tif (currentBlockSize > UINT64_C(2) * medianSize) {\n\t\tlogger(TRACE) << \"Block cumulative size is too big: \" << currentBlockSize << \", expected less than \" << 2 * medianSize;\n\t\treturn false;\n\t}\n\n\tuint64_t penalizedBaseReward = getPenalizedAmount(baseReward, medianSize, currentBlockSize);\n\tuint64_t penalizedFee = blockMajorVersion >= BLOCK_MAJOR_VERSION_4 ? getPenalizedAmount(fee, medianSize, currentBlockSize) : fee;\n\tif (parameters::CRYPTONOTE_COIN_VERSION == 1) {\n\t\tpenalizedFee = getPenalizedAmount(fee, medianSize, currentBlockSize);\n\t}\n    // logger(Logging::INFO, Logging::BRIGHT_GREEN) << \"[getBlockReward] baseReward: \" << baseReward << \", con diff \" << (int)diff << \", log fix: \" << log_fix_precision << \", b.majorv: \" << (int)blockMajorVersion << \", penalizedBaseReward: \" << penalizedBaseReward << \", penalizedFee: \" << penalizedFee << \", fee:\" << fee;\n\t//std::cout << \"BlockSize: \" << currentBlockSize  << \", medianSize:\" << medianSize << \", baseReward: \" << formatAmount(baseReward) << \", penalizedBaseReward: \" << formatAmount(penalizedBaseReward) << \", fee: \" << formatAmount(fee)\n\t//\t\t\t<< \", penalizedFee: \" << formatAmount(penalizedFee) << std::endl;\n\temissionChange = penalizedBaseReward - (fee - penalizedFee);\n\treward = penalizedBaseReward + penalizedFee;\n\n\treturn true;\n}\n/*\nbool Currency::getBlockReward(uint8_t blockMajorVersion, size_t medianSize, size_t currentBlockSize, uint64_t alreadyGeneratedCoins,\n                              uint64_t fee, uint64_t& reward, int64_t& emissionChange) const {\n    assert(alreadyGeneratedCoins <= m_moneySupply);\n    assert(m_emissionSpeedFactor > 0 && m_emissionSpeedFactor <= 8 * sizeof(uint64_t));\n\n    uint64_t baseReward = (m_moneySupply - alreadyGeneratedCoins) >> m_emissionSpeedFactor;\n\n    size_t blockGrantedFullRewardZone = blockGrantedFullRewardZoneByBlockVersion(blockMajorVersion);\n    medianSize = std::max(medianSize, blockGrantedFullRewardZone);\n    if (currentBlockSize > UINT64_C(2) * medianSize) {\n        logger(TRACE) << \"Block cumulative size is too big: \" << currentBlockSize << \", expected less than \" << 2 * medianSize;\n        return false;\n    }\n\n    uint64_t penalizedBaseReward = getPenalizedAmount(baseReward, medianSize, currentBlockSize);\n    uint64_t penalizedFee = blockMajorVersion >= BLOCK_MAJOR_VERSION_2 ? getPenalizedAmount(fee, medianSize, currentBlockSize) : fee;\n    emissionChange = penalizedBaseReward - (fee - penalizedFee);\n    reward = penalizedBaseReward + penalizedFee;\n\n    return true;\n}\n*/\nsize_t Currency::maxBlockCumulativeSize(uint64_t height) const {\n    assert(height <= std::numeric_limits<uint64_t>::max() / m_maxBlockSizeGrowthSpeedNumerator);\n    size_t maxSize = static_cast<size_t>(m_maxBlockSizeInitial +\n                                         (height * m_maxBlockSizeGrowthSpeedNumerator) / m_maxBlockSizeGrowthSpeedDenominator);\n    assert(maxSize >= m_maxBlockSizeInitial);\n    return maxSize;\n}\n\nbool Currency::constructMinerTx(uint8_t blockMajorVersion, uint32_t height, size_t medianSize, uint64_t alreadyGeneratedCoins, size_t currentBlockSize,\n                                uint64_t fee, const AccountPublicAddress& minerAddress, Transaction& tx, const BinaryArray& extraNonce/* = BinaryArray()*/, size_t maxOuts/* = 1*/,\n                            const Difficulty diff/* = 0*/) const {\n\n    tx.inputs.clear();\n    tx.outputs.clear();\n    tx.extra.clear();\n\n    KeyPair txkey = generateKeyPair();\n    addTransactionPublicKeyToExtra(tx.extra, txkey.publicKey);\n    if (!extraNonce.empty()) {\n        if (!addExtraNonceToTransactionExtra(tx.extra, extraNonce)) {\n            return false;\n        }\n    }\n\n    BaseInput in;\n    in.blockIndex = height;\n\n    uint64_t blockReward;\n    int64_t emissionChange;\n    if (!getBlockReward(blockMajorVersion, medianSize, currentBlockSize, alreadyGeneratedCoins, fee, blockReward, emissionChange, diff)) {\n        logger(INFO) << \"Block is too big\";\n        return false;\n    }\n\n    std::vector<uint64_t> outAmounts;\n    decompose_amount_into_digits(blockReward, m_defaultDustThreshold,\n                                 [&outAmounts](uint64_t a_chunk) { outAmounts.push_back(a_chunk); },\n    [&outAmounts](uint64_t a_dust) { outAmounts.push_back(a_dust); });\n\n    if (!(1 <= maxOuts)) { logger(ERROR, BRIGHT_RED) << \"max_out must be non-zero\"; return false; }\n    while (maxOuts < outAmounts.size()) {\n        outAmounts[outAmounts.size() - 2] += outAmounts.back();\n        outAmounts.resize(outAmounts.size() - 1);\n    }\n\n    uint64_t summaryAmounts = 0;\n    for (size_t no = 0; no < outAmounts.size(); no++) {\n        Crypto::KeyDerivation derivation = boost::value_initialized<Crypto::KeyDerivation>();\n        Crypto::PublicKey outEphemeralPubKey = boost::value_initialized<Crypto::PublicKey>();\n\n        bool r = Crypto::generate_key_derivation(minerAddress.viewPublicKey, txkey.secretKey, derivation);\n\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                    << \"while creating outs: failed to generate_key_derivation(\"\n                    << minerAddress.viewPublicKey << \", \" << txkey.secretKey << \")\";\n            return false;\n        }\n\n        r = Crypto::derive_public_key(derivation, no, minerAddress.spendPublicKey, outEphemeralPubKey);\n\n        if (!(r)) {\n            logger(ERROR, BRIGHT_RED)\n                    << \"while creating outs: failed to derive_public_key(\"\n                    << derivation << \", \" << no << \", \"\n                    << minerAddress.spendPublicKey << \")\";\n            return false;\n        }\n\n        KeyOutput tk;\n        tk.key = outEphemeralPubKey;\n\n        TransactionOutput out;\n        summaryAmounts += out.amount = outAmounts[no];\n        out.target = tk;\n        tx.outputs.push_back(out);\n    }\n\n    if (!(summaryAmounts == blockReward)) {\n        logger(ERROR, BRIGHT_RED) << \"Failed to construct miner tx, summaryAmounts = \" << summaryAmounts << \" not equal blockReward = \" << blockReward;\n        return false;\n    }\n\n    tx.version = CURRENT_TRANSACTION_VERSION;\n    //lock\n    tx.unlockTime = height + m_minedMoneyUnlockWindow;\n    tx.inputs.push_back(in);\n    return true;\n}\n\nbool Currency::isFusionTransaction(const std::vector<uint64_t>& inputsAmounts, const std::vector<uint64_t>& outputsAmounts, size_t size) const {\n    if (size > fusionTxMaxSize()) {\n        return false;\n    }\n\n    if (inputsAmounts.size() < fusionTxMinInputCount()) {\n        return false;\n    }\n\n    if (inputsAmounts.size() < outputsAmounts.size() * fusionTxMinInOutCountRatio()) {\n        return false;\n    }\n\n    uint64_t inputAmount = 0;\n    for (auto amount: inputsAmounts) {\n        if (amount < defaultDustThreshold()) {\n            return false;\n        }\n\n        inputAmount += amount;\n    }\n\n    std::vector<uint64_t> expectedOutputsAmounts;\n    expectedOutputsAmounts.reserve(outputsAmounts.size());\n    decomposeAmount(inputAmount, defaultDustThreshold(), expectedOutputsAmounts);\n    std::sort(expectedOutputsAmounts.begin(), expectedOutputsAmounts.end());\n\n    return expectedOutputsAmounts == outputsAmounts;\n}\n\nbool Currency::isFusionTransaction(const Transaction& transaction, size_t size) const {\n    assert(getObjectBinarySize(transaction) == size);\n\n    std::vector<uint64_t> outputsAmounts;\n    outputsAmounts.reserve(transaction.outputs.size());\n    for (const TransactionOutput& output : transaction.outputs) {\n        outputsAmounts.push_back(output.amount);\n    }\n\n    return isFusionTransaction(getInputsAmounts(transaction), outputsAmounts, size);\n}\n\nbool Currency::isFusionTransaction(const Transaction& transaction) const {\n    return isFusionTransaction(transaction, getObjectBinarySize(transaction));\n}\n\nbool Currency::isAmountApplicableInFusionTransactionInput(uint64_t amount, uint64_t threshold) const {\n    uint8_t ignore;\n    return isAmountApplicableInFusionTransactionInput(amount, threshold, ignore);\n}\n\nbool Currency::isAmountApplicableInFusionTransactionInput(uint64_t amount, uint64_t threshold, uint8_t& amountPowerOfTen) const {\n    if (amount >= threshold) {\n        return false;\n    }\n\n    if (amount < defaultDustThreshold()) {\n        return false;\n    }\n\n    auto it = std::lower_bound(PRETTY_AMOUNTS.begin(), PRETTY_AMOUNTS.end(), amount);\n    if (it == PRETTY_AMOUNTS.end() || amount != *it) {\n        return false;\n    }\n\n    amountPowerOfTen = static_cast<uint8_t>(std::distance(PRETTY_AMOUNTS.begin(), it) / 9);\n    return true;\n}\n\nstd::string Currency::accountAddressAsString(const AccountBase& account) const {\n    return getAccountAddressAsStr(m_publicAddressBase58Prefix, account.getAccountKeys().address);\n}\n\nstd::string Currency::accountAddressAsString(const AccountPublicAddress& accountPublicAddress) const {\n    return getAccountAddressAsStr(m_publicAddressBase58Prefix, accountPublicAddress);\n}\n\nbool Currency::parseAccountAddressString(const std::string& str, AccountPublicAddress& addr) const {\n    uint64_t prefix;\n    if (!CryptoNote::parseAccountAddressString(prefix, addr, str)) {\n        return false;\n    }\n\n    if (prefix != m_publicAddressBase58Prefix) {\n        logger(DEBUGGING) << \"Wrong address prefix: \" << prefix << \", expected \" << m_publicAddressBase58Prefix;\n        return false;\n    }\n\n    return true;\n}\n\nstd::string Currency::formatAmount(uint64_t amount) const {\n    std::string s = std::to_string(amount);\n    if (s.size() < m_numberOfDecimalPlaces + 1) {\n        s.insert(0, m_numberOfDecimalPlaces + 1 - s.size(), '0');\n    }\n    s.insert(s.size() - m_numberOfDecimalPlaces, \".\");\n    return s;\n}\n\nstd::string Currency::formatAmount(int64_t amount) const {\n    std::string s = formatAmount(static_cast<uint64_t>(std::abs(amount)));\n\n    if (amount < 0) {\n        s.insert(0, \"-\");\n    }\n\n    return s;\n}\n\nbool Currency::parseAmount(const std::string& str, uint64_t& amount) const {\n    std::string strAmount = str;\n    boost::algorithm::trim(strAmount);\n\n    size_t pointIndex = strAmount.find_first_of('.');\n    size_t fractionSize;\n    if (std::string::npos != pointIndex) {\n        fractionSize = strAmount.size() - pointIndex - 1;\n        while (m_numberOfDecimalPlaces < fractionSize && '0' == strAmount.back()) {\n            strAmount.erase(strAmount.size() - 1, 1);\n            --fractionSize;\n        }\n        if (m_numberOfDecimalPlaces < fractionSize) {\n            return false;\n        }\n        strAmount.erase(pointIndex, 1);\n    } else {\n        fractionSize = 0;\n    }\n\n    if (strAmount.empty()) {\n        return false;\n    }\n\n    if (!std::all_of(strAmount.begin(), strAmount.end(), ::isdigit)) {\n        return false;\n    }\n\n    if (fractionSize < m_numberOfDecimalPlaces) {\n        strAmount.append(m_numberOfDecimalPlaces - fractionSize, '0');\n    }\n\n    return Common::fromString(strAmount, amount);\n}\n\nDifficulty Currency::nextDifficulty(\n        uint8_t version,\n        uint32_t blockIndex,\n        std::vector<uint64_t> timestamps,\n        std::vector<Difficulty> cumulativeDifficulties\n        ) const {\n    Difficulty nextDiff;\n    if (version >= BLOCK_MAJOR_VERSION_3) {\n        nextDiff = nextDifficultyLWMA4(version, timestamps, cumulativeDifficulties);\n    } else {\n        nextDiff = nextDifficultyOriginal(timestamps,cumulativeDifficulties);\n    }\n    if(nextDiff < 1) {\n        nextDiff = 1;\n    }\n    return nextDiff;\n}\n\n\n\n/**\n * Original cryptonote difficulty algo\n */\nDifficulty Currency::nextDifficultyOriginal(\n        std::vector<uint64_t> timestamps,\n        std::vector<Difficulty> cumulativeDifficulties\n        ) const {\n\n    uint64_t target_seconds = static_cast<int64_t>(m_difficultyTarget); //CryptoNote::parameters::DIFFICULTY_TARGET;\n\tsize_t m_difficultyWindow_2 = CryptoNote::parameters::DIFFICULTY_WINDOW;\n\tassert(m_difficultyWindow_2 >= 2);\n\n\tif (timestamps.size() > m_difficultyWindow_2) {\n\t\ttimestamps.resize(m_difficultyWindow_2);\n\t\tcumulativeDifficulties.resize(m_difficultyWindow_2);\n\t}\n\n\tsize_t length = timestamps.size();\n\tassert(length == cumulativeDifficulties.size());\n\tassert(length <= m_difficultyWindow_2);\n\tif (length <= 1) {\n\t\treturn 1;\n\t}\n\n\tstatic_assert(CryptoNote::parameters::DIFFICULTY_WINDOW >= 2, \"Window is too small\");\n    assert(length <= CryptoNote::parameters::DIFFICULTY_WINDOW);\n    sort(timestamps.begin(), timestamps.end());\n    size_t cut_begin, cut_end;\n    static_assert(2 * CryptoNote::parameters::DIFFICULTY_CUT <= CryptoNote::parameters::DIFFICULTY_WINDOW - 2, \"Cut length is too large\");\n    if (length <= CryptoNote::parameters::DIFFICULTY_WINDOW - 2 * CryptoNote::parameters::DIFFICULTY_CUT) {\n      cut_begin = 0;\n      cut_end = length;\n    } else {\n      cut_begin = (length - (CryptoNote::parameters::DIFFICULTY_WINDOW - 2 * CryptoNote::parameters::DIFFICULTY_CUT) + 1) / 2;\n      cut_end = cut_begin + (CryptoNote::parameters::DIFFICULTY_WINDOW - 2 * CryptoNote::parameters::DIFFICULTY_CUT);\n    }\n    assert(/*cut_begin >= 0 &&*/ cut_begin + 2 <= cut_end && cut_end <= length);\n    uint64_t time_span = timestamps[cut_end - 1] - timestamps[cut_begin];\n    if (time_span == 0) {\n      time_span = 1;\n    }\n    Difficulty total_work = cumulativeDifficulties[cut_end - 1] - cumulativeDifficulties[cut_begin];\n    assert(total_work > 0);\n    uint64_t low, high;\n    mul(total_work, target_seconds, low, high);\n    if (high != 0 || low + time_span - 1 < low) {\n      return 0;\n    }\n    return (low + time_span - 1) / time_span;\n}\n\n// LWMA difficulty algorithm Hard fork v3\n// Copyright (c) 2017-2018 Zawy\n// MIT license http://www.opensource.org/licenses/mit-license.php.\n// Tom Harding, Karbowanec, Masari, Bitcoin Gold, and Bitcoin Candy have contributed.\n// https://github.com/zawy12/difficulty-algorithms/issues/3\n// Zawy's LWMA difficulty algorithm implementation V4 (60 solvetimes limits -7T/7T)\n// (60 solvetimes - limits -7T/7T - adjust = 0.9909)\nDifficulty Currency::nextDifficultyLWMA4(uint8_t &version,\n        std::vector<uint64_t> &timestamps,\n        std::vector<Difficulty> &cumulativeDifficulties\n        ) const  {\n    const size_t c_difficultyWindow = difficultyWindowByBlockVersion(version); // 61\n    const int64_t c_difficultyTarget = static_cast<int64_t>(m_difficultyTarget);\n    if (timestamps.size() > c_difficultyWindow) {\n        timestamps.resize(c_difficultyWindow);\n        cumulativeDifficulties.resize(c_difficultyWindow);\n    }\n    size_t length = timestamps.size();\n    assert(length == cumulativeDifficulties.size());\n    assert(length <= c_difficultyWindow);\n    if (length <= 1) {\n        return 1;\n    }\n    int64_t solveTime(0),LWMA(0),minWST(0);\n    uint64_t aimedTarget(0),low,high;\n    Difficulty totalWork(0),nextDiff(0);\n    const double_t adjust = 0.9909;\n    for (int64_t i = 1; i < length; i++) { // lenght = 61\n        solveTime = static_cast<int64_t>(timestamps[i]) - static_cast<int64_t>(timestamps[i-1]);\n        solveTime = std::max<int64_t>(- blockFutureTimeLimit(), solveTime);\n        LWMA += solveTime * i;\n    }\n    // Keep LWMA sane in case something unforeseen occurs.if ( LWMA < T*N*(N+1)/8 ) { LWMA = T*N*(N+1)/8; N=lenght-1}\n    minWST = c_difficultyTarget * length*(length-1)/8;\n    if(LWMA < minWST){\n        LWMA = minWST;\n    }\n    totalWork = cumulativeDifficulties.back() - cumulativeDifficulties.front();\n    aimedTarget = adjust * (length / 2.0) * c_difficultyTarget ;\n    assert(totalWork > 0);\n    low = mul128(totalWork, aimedTarget, &high);\n    if (high != 0) {\n        return 0;\n    }\n    nextDiff = low/LWMA;\n    return nextDiff;\n}\n\n\nbool Currency::checkProofOfWorkV1(Crypto::cn_context& context, const CachedBlock& block, Difficulty currentDifficulty) const {\n    if (BLOCK_MAJOR_VERSION_1 != block.getBlock().majorVersion) {\n        return false;\n    }\n\n    return check_hash(block.getBlockLongHash(context), currentDifficulty);\n}\n\nbool Currency::checkProofOfWorkV2(Crypto::cn_context& context, const CachedBlock& cachedBlock, Difficulty currentDifficulty) const {\n    const auto& block = cachedBlock.getBlock();\n    if (block.majorVersion < BLOCK_MAJOR_VERSION_2) {\n        return false;\n    }\n\n    if (!check_hash(cachedBlock.getBlockLongHash(context), currentDifficulty)) {\n        return false;\n    }\n\n    TransactionExtraMergeMiningTag mmTag;\n    if (!getMergeMiningTagFromExtra(block.parentBlock.baseTransaction.extra, mmTag)) {\n        logger(ERROR) << \"merge mining tag wasn't found in extra of the parent block miner transaction\";\n        return false;\n    }\n\n    if (8 * sizeof(cachedGenesisBlock->getBlockHash()) < block.parentBlock.blockchainBranch.size()) {\n        return false;\n    }\n\n    Crypto::Hash auxBlocksMerkleRoot;\n    Crypto::tree_hash_from_branch(block.parentBlock.blockchainBranch.data(), block.parentBlock.blockchainBranch.size(),\n                                  cachedBlock.getAuxiliaryBlockHeaderHash(), &cachedGenesisBlock->getBlockHash(), auxBlocksMerkleRoot);\n\n    if (auxBlocksMerkleRoot != mmTag.merkleRoot) {\n        logger(ERROR, BRIGHT_YELLOW) << \"Aux block hash wasn't found in merkle tree\";\n        return false;\n    }\n\n    return true;\n}\n\nbool Currency::checkProofOfWork(Crypto::cn_context& context, const CachedBlock& block, Difficulty currentDiffic) const {\n    switch (block.getBlock().majorVersion) {\n    case BLOCK_MAJOR_VERSION_1:\n        return checkProofOfWorkV1(context, block, currentDiffic);\n\n    case BLOCK_MAJOR_VERSION_2:\n    case BLOCK_MAJOR_VERSION_3:\n    case BLOCK_MAJOR_VERSION_4:\n        return checkProofOfWorkV2(context, block, currentDiffic);\n    }\n\n    logger(ERROR, BRIGHT_RED) << \"Unknown block major version: \" << block.getBlock().majorVersion << \".\" << block.getBlock().minorVersion;\n    return false;\n}\n\nsize_t Currency::getApproximateMaximumInputCount(size_t transactionSize, size_t outputCount, size_t mixinCount) const {\n    const size_t KEY_IMAGE_SIZE = sizeof(Crypto::KeyImage);\n    const size_t OUTPUT_KEY_SIZE = sizeof(decltype(KeyOutput::key));\n    const size_t AMOUNT_SIZE = sizeof(uint64_t) + 2; //varint\n    const size_t GLOBAL_INDEXES_VECTOR_SIZE_SIZE = sizeof(uint8_t);//varint\n    const size_t GLOBAL_INDEXES_INITIAL_VALUE_SIZE = sizeof(uint32_t);//varint\n    const size_t GLOBAL_INDEXES_DIFFERENCE_SIZE = sizeof(uint32_t);//varint\n    const size_t SIGNATURE_SIZE = sizeof(Crypto::Signature);\n    const size_t EXTRA_TAG_SIZE = sizeof(uint8_t);\n    const size_t INPUT_TAG_SIZE = sizeof(uint8_t);\n    const size_t OUTPUT_TAG_SIZE = sizeof(uint8_t);\n    const size_t PUBLIC_KEY_SIZE = sizeof(Crypto::PublicKey);\n    const size_t TRANSACTION_VERSION_SIZE = sizeof(uint8_t);\n    const size_t TRANSACTION_UNLOCK_TIME_SIZE = sizeof(uint64_t);\n\n    const size_t outputsSize = outputCount * (OUTPUT_TAG_SIZE + OUTPUT_KEY_SIZE + AMOUNT_SIZE);\n    const size_t headerSize = TRANSACTION_VERSION_SIZE + TRANSACTION_UNLOCK_TIME_SIZE + EXTRA_TAG_SIZE + PUBLIC_KEY_SIZE;\n    const size_t inputSize = INPUT_TAG_SIZE + AMOUNT_SIZE + KEY_IMAGE_SIZE + SIGNATURE_SIZE + GLOBAL_INDEXES_VECTOR_SIZE_SIZE + GLOBAL_INDEXES_INITIAL_VALUE_SIZE +\n            mixinCount * (GLOBAL_INDEXES_DIFFERENCE_SIZE + SIGNATURE_SIZE);\n\n    return (transactionSize - headerSize - outputsSize) / inputSize;\n}\n\nCurrency::Currency(Currency&& currency) :\n    m_maxBlockHeight(currency.m_maxBlockHeight),\n    m_maxBlockBlobSize(currency.m_maxBlockBlobSize),\n    m_maxTxSize(currency.m_maxTxSize),\n    m_publicAddressBase58Prefix(currency.m_publicAddressBase58Prefix),\n    m_minedMoneyUnlockWindow(currency.m_minedMoneyUnlockWindow),\n    m_timestampCheckWindow(currency.m_timestampCheckWindow),\n    m_timestampCheckWindowV3(currency.m_timestampCheckWindowV3),\n    m_blockFutureTimeLimit(currency.m_blockFutureTimeLimit),\n    m_moneySupply(currency.m_moneySupply),\n    m_emissionSpeedFactor(currency.m_emissionSpeedFactor),\n    m_rewardBlocksWindow(currency.m_rewardBlocksWindow),\n    m_blockGrantedFullRewardZone(currency.m_blockGrantedFullRewardZone),\n    m_minerTxBlobReservedSize(currency.m_minerTxBlobReservedSize),\n    m_minMixin(currency.m_minMixin),\n    m_maxMixin(currency.m_maxMixin),\n    m_mandatoryMixinBlockVersion(currency.m_mandatoryMixinBlockVersion),\n    m_numberOfDecimalPlaces(currency.m_numberOfDecimalPlaces),\n    m_coin(currency.m_coin),\n    m_mininumFee(currency.m_mininumFee),\n    m_defaultDustThreshold(currency.m_defaultDustThreshold),\n    m_difficultyTarget(currency.m_difficultyTarget),\n    m_testnet_DifficultyTarget(currency.m_testnet_DifficultyTarget),\n    m_difficultyWindow(currency.m_difficultyWindow),\n    m_difficultyLag(currency.m_difficultyLag),\n    m_difficultyCut(currency.m_difficultyCut),\n    m_maxBlockSizeInitial(currency.m_maxBlockSizeInitial),\n    m_maxBlockSizeGrowthSpeedNumerator(currency.m_maxBlockSizeGrowthSpeedNumerator),\n    m_maxBlockSizeGrowthSpeedDenominator(currency.m_maxBlockSizeGrowthSpeedDenominator),\n    m_lockedTxAllowedDeltaSeconds(currency.m_lockedTxAllowedDeltaSeconds),\n    m_lockedTxAllowedDeltaBlocks(currency.m_lockedTxAllowedDeltaBlocks),\n    m_mempoolTxLiveTime(currency.m_mempoolTxLiveTime),\n    m_numberOfPeriodsToForgetTxDeletedFromPool(currency.m_numberOfPeriodsToForgetTxDeletedFromPool),\n    m_fusionTxMaxSize(currency.m_fusionTxMaxSize),\n    m_fusionTxMinInputCount(currency.m_fusionTxMinInputCount),\n    m_fusionTxMinInOutCountRatio(currency.m_fusionTxMinInOutCountRatio),\n    m_upgradeHeightV2(currency.m_upgradeHeightV2),\n    m_upgradeHeightV3(currency.m_upgradeHeightV3),\n    m_upgradeHeightV4(currency.m_upgradeHeightV4),\n    m_testnetUpgradeHeightV2(currency.m_testnetUpgradeHeightV2),\n    m_testnetUpgradeHeightV3(currency.m_testnetUpgradeHeightV3),\n    m_testnetUpgradeHeightV4(currency.m_testnetUpgradeHeightV4),\n    m_upgradeVotingThreshold(currency.m_upgradeVotingThreshold),\n    m_upgradeVotingWindow(currency.m_upgradeVotingWindow),\n    m_upgradeWindow(currency.m_upgradeWindow),\n    m_blocksFileName(currency.m_blocksFileName),\n    m_blockIndexesFileName(currency.m_blockIndexesFileName),\n    m_txPoolFileName(currency.m_txPoolFileName),\n    m_testnet(currency.m_testnet),\n    genesisBlockTemplate(std::move(currency.genesisBlockTemplate)),\n    cachedGenesisBlock(new CachedBlock(genesisBlockTemplate)),\n    logger(currency.logger) {\n}\n\nCurrencyBuilder::CurrencyBuilder(Logging::ILogger& log) : m_currency(log) {\n    maxBlockNumber(parameters::CRYPTONOTE_MAX_BLOCK_NUMBER);\n    maxBlockBlobSize(parameters::CRYPTONOTE_MAX_BLOCK_BLOB_SIZE);\n    maxTxSize(parameters::CRYPTONOTE_MAX_TX_SIZE);\n    publicAddressBase58Prefix(parameters::CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX);\n    minedMoneyUnlockWindow(parameters::CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW);\n\n    timestampCheckWindow(parameters::BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW);\n    timestampCheckWindowV3(parameters::BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW_V3);\n    blockFutureTimeLimit(parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT);\n\n    moneySupply(parameters::MONEY_SUPPLY);\n    emissionSpeedFactor(parameters::EMISSION_SPEED_FACTOR);\n\n    rewardBlocksWindow(parameters::CRYPTONOTE_REWARD_BLOCKS_WINDOW);\n\n    minMixin(parameters::MIN_MIXIN);\n    maxMixin(parameters::MAX_MIXIN);\n    mandatoryMixinBlockVersion(parameters::MANDATORY_MIXIN_BLOCK_VERSION);\n\n    blockGrantedFullRewardZone(parameters::CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE);\n    minerTxBlobReservedSize(parameters::CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE);\n\n    numberOfDecimalPlaces(parameters::CRYPTONOTE_DISPLAY_DECIMAL_POINT);\n\n    mininumFee(parameters::MINIMUM_FEE);\n    defaultDustThreshold(parameters::DEFAULT_DUST_THRESHOLD);\n\n    difficultyTarget(parameters::DIFFICULTY_TARGET);\n    testnetDifficultyTarget(parameters::TESTNET_DIFFICULTY_TARGET);\n\n    difficultyWindow(parameters::DIFFICULTY_WINDOW);\n    difficultyLag(parameters::DIFFICULTY_LAG);\n    difficultyCut(parameters::DIFFICULTY_CUT);\n\n    maxBlockSizeInitial(parameters::MAX_BLOCK_SIZE_INITIAL);\n    maxBlockSizeGrowthSpeedNumerator(parameters::MAX_BLOCK_SIZE_GROWTH_SPEED_NUMERATOR);\n    maxBlockSizeGrowthSpeedDenominator(parameters::MAX_BLOCK_SIZE_GROWTH_SPEED_DENOMINATOR);\n\n    lockedTxAllowedDeltaSeconds(parameters::CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS);\n    lockedTxAllowedDeltaBlocks(parameters::CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS);\n\n    mempoolTxLiveTime(parameters::CRYPTONOTE_MEMPOOL_TX_LIVETIME);\n    mempoolTxFromAltBlockLiveTime(parameters::CRYPTONOTE_MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME);\n    numberOfPeriodsToForgetTxDeletedFromPool(parameters::CRYPTONOTE_NUMBER_OF_PERIODS_TO_FORGET_TX_DELETED_FROM_POOL);\n\n    fusionTxMaxSize(parameters::FUSION_TX_MAX_SIZE);\n    fusionTxMinInputCount(parameters::FUSION_TX_MIN_INPUT_COUNT);\n    fusionTxMinInOutCountRatio(parameters::FUSION_TX_MIN_IN_OUT_COUNT_RATIO);\n\n    upgradeHeightV2(parameters::UPGRADE_HEIGHT_V2);\n    upgradeHeightV3(parameters::UPGRADE_HEIGHT_V3);\n    upgradeHeightV4(parameters::UPGRADE_HEIGHT_V4);\n\n    testnetUpgradeHeightV2(parameters::TESTNET_UPGRADE_HEIGHT_V2);\n    testnetUpgradeHeightV3(parameters::TESTNET_UPGRADE_HEIGHT_V3);\n    testnetUpgradeHeightV4(parameters::TESTNET_UPGRADE_HEIGHT_V4);\n\n    upgradeVotingThreshold(parameters::UPGRADE_VOTING_THRESHOLD);\n    upgradeVotingWindow(parameters::UPGRADE_VOTING_WINDOW);\n    upgradeWindow(parameters::UPGRADE_WINDOW);\n\n    blocksFileName(parameters::CRYPTONOTE_BLOCKS_FILENAME);\n    blockIndexesFileName(parameters::CRYPTONOTE_BLOCKINDEXES_FILENAME);\n    txPoolFileName(parameters::CRYPTONOTE_POOLDATA_FILENAME);\n\n    testnet(false);\n}\n\nCurrencyBuilder& CurrencyBuilder::emissionSpeedFactor(unsigned int val) {\n    if (val <= 0 || val > 8 * sizeof(uint64_t)) {\n        throw std::invalid_argument(\"val at emissionSpeedFactor()\");\n    }\n\n    m_currency.m_emissionSpeedFactor = val;\n    return *this;\n}\n\nCurrencyBuilder& CurrencyBuilder::numberOfDecimalPlaces(size_t val) {\n    m_currency.m_numberOfDecimalPlaces = val;\n    m_currency.m_coin = 1;\n    for (size_t i = 0; i < m_currency.m_numberOfDecimalPlaces; ++i) {\n        m_currency.m_coin *= 10;\n    }\n\n    return *this;\n}\n\nCurrencyBuilder& CurrencyBuilder::difficultyWindow(size_t val) {\n    if (val < 2) {\n        throw std::invalid_argument(\"val at difficultyWindow()\");\n    }\n    m_currency.m_difficultyWindow = val;\n    return *this;\n}\n\nCurrencyBuilder& CurrencyBuilder::upgradeVotingThreshold(unsigned int val) {\n    if (val <= 0 || val > 100) {\n        throw std::invalid_argument(\"val at upgradeVotingThreshold()\");\n    }\n\n    m_currency.m_upgradeVotingThreshold = val;\n    return *this;\n}\n\nCurrencyBuilder& CurrencyBuilder::upgradeWindow(uint32_t val) {\n    if (val <= 0) {\n        throw std::invalid_argument(\"val at upgradeWindow()\");\n    }\n\n    m_currency.m_upgradeWindow = val;\n    return *this;\n}\n\n}\n", "meta": {"hexsha": "87e4329f2b324b2edb11955e4e97887c0e7d6b48", "size": 37428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/CryptoNoteCore/Currency.cpp", "max_stars_repo_name": "Camellia73/BlackRoseCoin_Diamond_V2", "max_stars_repo_head_hexsha": "f155f7f9eb7f8db711b9e3a0d417038321a92abe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/CryptoNoteCore/Currency.cpp", "max_issues_repo_name": "Camellia73/BlackRoseCoin_Diamond_V2", "max_issues_repo_head_hexsha": "f155f7f9eb7f8db711b9e3a0d417038321a92abe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/CryptoNoteCore/Currency.cpp", "max_forks_repo_name": "Camellia73/BlackRoseCoin_Diamond_V2", "max_forks_repo_head_hexsha": "f155f7f9eb7f8db711b9e3a0d417038321a92abe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.3569060773, "max_line_length": 322, "alphanum_fraction": 0.723121727, "num_tokens": 9712, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786991753929, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.23199555762959548}}
{"text": "// Copyright (c) 2019 Tim Perkins\n\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// “Software”), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef TTFRM_TFRM_HPP\n#define TTFRM_TFRM_HPP\n\n#include <exception>\n#include <tuple>\n\n#include <fmt/format.h>\n#include <Eigen/Geometry>\n\nnamespace ttfrm {\n\nusing Quat = Eigen::Quaterniond;\nusing Vec3 = Eigen::Vector3d;\n\ntemplate <typename FrameId>\nclass Tfrm;\n\ntemplate <typename FrameId_>\nstruct FramePair {\n  using FrameId = FrameId_;\n\n  FrameId to_frame;\n  FrameId from_frame;\n};\n\ntemplate <typename FrameId>\nstd::string Stringify(const Tfrm<FrameId>& tfrm);\n\ntemplate <typename FrameId>\nstd::string Stringify(const FramePair<FrameId>& frame_pair);\n\ntemplate <typename FrameId_>\nclass Tfrm {\n public:\n  using FrameId = FrameId_;\n\n  Tfrm(const FrameId& to_frame, const FrameId& from_frame, const Quat& rot, const Vec3& trans);\n  Tfrm(const Tfrm& other_tfrm);\n  Tfrm(Tfrm&& other_tfrm);\n\n  static Tfrm<FrameId> Identity(const FrameId& to_frame, const FrameId& from_frame);\n  static Tfrm<FrameId> FromRotation(const FrameId& to_frame, const FrameId& from_frame,\n                                    const Quat& rot);\n  static Tfrm<FrameId> FromTranslation(const FrameId& to_frame, const FrameId& from_frame,\n                                       const Vec3& trans);\n  static Tfrm<FrameId> FromIsometry(const FrameId& to_frame, const FrameId& from_frame,\n                                    const Eigen::Isometry3d& isometry);\n\n  Tfrm<FrameId>& operator=(const Tfrm<FrameId>& other_tfrm);\n  Tfrm<FrameId>& operator=(Tfrm<FrameId>&& other_tfrm);\n\n  bool operator==(const Tfrm<FrameId>& other_tfrm) const;\n  bool operator!=(const Tfrm<FrameId>& other_tfrm) const;\n  bool IsApprox(const Tfrm& other_tfrm, double precision = 1.0e-6) const;\n\n  FramePair<FrameId> Frames() const;\n  FrameId ToFrame() const;\n  FrameId FromFrame() const;\n\n  Quat Rotation() const;\n  Vec3 Translation() const;\n\n  Tfrm<FrameId> Inverse() const;\n\n  Tfrm<FrameId> Compose(const Tfrm<FrameId>& other_tfrm) const;\n  Tfrm<FrameId> operator*(const Tfrm<FrameId>& other_tfrm) const;\n  Tfrm<FrameId> operator()(const Tfrm<FrameId>& other_tfrm) const;\n\n  Vec3 Apply(const Vec3& trans) const;\n  Vec3 operator*(const Vec3& trans) const;\n  Vec3 operator()(const Vec3& trans) const;\n\n  Tfrm<FrameId> Interpolate(const FrameId& interp_to_frame, const Tfrm<FrameId>& other_tfrm,\n                            double t) const;\n\n  Eigen::Isometry3d AsIsometry() const;\n\n private:\n  FrameId to_frame_;\n  FrameId from_frame_;\n  Quat rot_;\n  Vec3 trans_;\n\n  friend std::string Stringify<FrameId>(const Tfrm<FrameId>& tfrm);\n  friend std::string Stringify<FrameId>(const FramePair<FrameId>& frame_pair);\n};\n\nclass TfrmComposeException : public std::runtime_error {\n public:\n  template <typename FrameId>\n  TfrmComposeException(const Tfrm<FrameId>& tfrm, const Tfrm<FrameId>& other_tfrm);\n  TfrmComposeException(const TfrmComposeException& other_comp_excp) = default;\n  TfrmComposeException(TfrmComposeException&& other_comp_excp) = default;\n};\n\nclass TfrmInterpolateException : public std::runtime_error {\n public:\n  template <typename FrameId>\n  TfrmInterpolateException(const Tfrm<FrameId>& tfrm, const Tfrm<FrameId>& other_tfrm);\n  TfrmInterpolateException(const TfrmInterpolateException& other_comp_excp) = default;\n  TfrmInterpolateException(TfrmInterpolateException&& other_comp_excp) = default;\n};\n\ntemplate <typename FrameId>\nTfrm<FrameId>::Tfrm(const FrameId& to_frame, const FrameId& from_frame, const Quat& rot,\n                    const Vec3& trans)\n    : to_frame_(to_frame), from_frame_(from_frame), rot_(rot.normalized()), trans_(trans)\n{\n  // Do nothing\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId>::Tfrm(const Tfrm<FrameId>& other_tfrm)\n    : to_frame_(other_tfrm.to_frame_),\n      from_frame_(other_tfrm.from_frame_),\n      rot_(other_tfrm.rot_),\n      trans_(other_tfrm.trans_)\n{\n  // Do nothing\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId>::Tfrm(Tfrm&& other_tfrm)\n    : to_frame_(std::move(other_tfrm.to_frame_)),\n      from_frame_(std::move(other_tfrm.from_frame_)),\n      rot_(std::move(other_tfrm.rot_)),\n      trans_(std::move(other_tfrm.trans_))\n{\n  // Do nothing\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId> Tfrm<FrameId>::Identity(const FrameId& to_frame, const FrameId& from_frame)\n{\n  return Tfrm<FrameId>(to_frame, from_frame, Quat::Identity(), Vec3::Zero());\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId> Tfrm<FrameId>::FromRotation(const FrameId& to_frame, const FrameId& from_frame,\n                                          const Quat& rot)\n{\n  return Tfrm<FrameId>(to_frame, from_frame, rot, Vec3::Zero());\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId> Tfrm<FrameId>::FromTranslation(const FrameId& to_frame, const FrameId& from_frame,\n                                             const Vec3& trans)\n{\n  return Tfrm<FrameId>(to_frame, from_frame, Quat::Identity(), trans);\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId> Tfrm<FrameId>::FromIsometry(const FrameId& to_frame, const FrameId& from_frame,\n                                          const Eigen::Isometry3d& isometry)\n{\n  return Tfrm<FrameId>(to_frame, from_frame, Quat(isometry.rotation()), isometry.translation());\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId>& Tfrm<FrameId>::operator=(const Tfrm& other_tfrm)\n{\n  to_frame_ = other_tfrm.to_frame_;\n  from_frame_ = other_tfrm.from_frame_;\n  rot_ = other_tfrm.rot_;\n  trans_ = other_tfrm.trans_;\n  return *this;\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId>& Tfrm<FrameId>::operator=(Tfrm&& other_tfrm)\n{\n  to_frame_ = std::move(other_tfrm.to_frame_);\n  from_frame_ = std::move(other_tfrm.from_frame_);\n  rot_ = std::move(other_tfrm.rot_);\n  trans_ = std::move(other_tfrm.trans_);\n  return *this;\n}\n\ntemplate <typename FrameId>\nbool Tfrm<FrameId>::operator==(const Tfrm& other_tfrm) const\n{\n  static auto QuatEquality = [](const Quat& q1, const Quat& q2) {\n    return (q1.w() == q2.w() && q1.x() == q2.x() && q1.y() == q2.y() && q1.z() == q2.z());\n  };\n  return (to_frame_ == other_tfrm.to_frame_ && from_frame_ == other_tfrm.from_frame_\n          && QuatEquality(rot_, other_tfrm.rot_) && trans_ == other_tfrm.trans_);\n}\n\ntemplate <typename FrameId>\nbool Tfrm<FrameId>::operator!=(const Tfrm& other_tfrm) const\n{\n  return !(*this == other_tfrm);\n}\n\ntemplate <typename FrameId>\nbool Tfrm<FrameId>::IsApprox(const Tfrm& other_tfrm, double precision) const\n{\n  return (to_frame_ == other_tfrm.to_frame_ && from_frame_ == other_tfrm.from_frame_\n          && rot_.isApprox(other_tfrm.rot_, precision)\n          && trans_.isApprox(other_tfrm.trans_, precision));\n}\n\ntemplate <typename FrameId>\nFramePair<FrameId> Tfrm<FrameId>::Frames() const\n{\n  return {to_frame_, from_frame_};\n}\n\ntemplate <typename FrameId>\nFrameId Tfrm<FrameId>::ToFrame() const\n{\n  return to_frame_;\n}\n\ntemplate <typename FrameId>\nFrameId Tfrm<FrameId>::FromFrame() const\n{\n  return from_frame_;\n}\n\ntemplate <typename FrameId>\nQuat Tfrm<FrameId>::Rotation() const\n{\n  return rot_;\n}\n\ntemplate <typename FrameId>\nVec3 Tfrm<FrameId>::Translation() const\n{\n  return trans_;\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId> Tfrm<FrameId>::Inverse() const\n{\n  const Quat inv_rot = rot_.inverse();\n  return Tfrm<FrameId>(from_frame_, to_frame_, inv_rot, inv_rot * -trans_);\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId> Tfrm<FrameId>::Compose(const Tfrm& other_tfrm) const\n{\n  if (from_frame_ != other_tfrm.to_frame_) {\n    throw TfrmComposeException(*this, other_tfrm);\n  }\n  // T2(T1(v)) = R2 * (R1 * v + t1) + t2 = (R2 * R1) * v + (t2 + R2 * t1)\n  return Tfrm<FrameId>(to_frame_, other_tfrm.from_frame_, rot_ * other_tfrm.rot_,\n                       trans_ + rot_ * other_tfrm.trans_);\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId> Tfrm<FrameId>::operator*(const Tfrm& other_tfrm) const\n{\n  return Compose(other_tfrm);\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId> Tfrm<FrameId>::operator()(const Tfrm& other_tfrm) const\n{\n  return Compose(other_tfrm);\n}\n\ntemplate <typename FrameId>\nVec3 Tfrm<FrameId>::Apply(const Vec3& trans) const\n{\n  // T(v) = R * v + t\n  return Vec3(rot_ * trans + trans_);\n}\n\ntemplate <typename FrameId>\nVec3 Tfrm<FrameId>::operator*(const Vec3& trans) const\n{\n  return Apply(trans);\n}\n\ntemplate <typename FrameId>\nVec3 Tfrm<FrameId>::operator()(const Vec3& trans) const\n{\n  return Apply(trans);\n}\n\ntemplate <typename FrameId>\nTfrm<FrameId> Tfrm<FrameId>::Interpolate(const FrameId& interp_to_frame,\n                                         const Tfrm<FrameId>& other_tfrm, double ratio) const\n{\n  if (from_frame_ != other_tfrm.from_frame_) {\n    throw TfrmInterpolateException(*this, other_tfrm);\n  }\n  return Tfrm<FrameId>(interp_to_frame, from_frame_, rot_.slerp(ratio, other_tfrm.rot_),\n                       trans_ + ratio * (other_tfrm.trans_ - trans_));\n}\n\ntemplate <typename FrameId>\nEigen::Isometry3d Tfrm<FrameId>::AsIsometry() const\n{\n  // The concatenation of the translation and the rotation\n  return Eigen::Translation3d(trans_) * rot_;\n}\n\ntemplate <typename FrameId>\nTfrmComposeException::TfrmComposeException(const Tfrm<FrameId>& tfrm,\n                                           const Tfrm<FrameId>& other_tfrm)\n    : std::runtime_error(fmt::format(\"Cannot compose transforms {} and {}\",\n                                     Stringify(tfrm.Frames()), Stringify(other_tfrm.Frames())))\n{\n  // Do nothing\n}\n\ntemplate <typename FrameId>\nTfrmInterpolateException::TfrmInterpolateException(const Tfrm<FrameId>& tfrm,\n                                                   const Tfrm<FrameId>& other_tfrm)\n    : std::runtime_error(fmt::format(\"Cannot interpolate transforms {} and {}\",\n                                     Stringify(tfrm.Frames()), Stringify(other_tfrm.Frames())))\n{\n  // Do nothing\n}\n\ntemplate <typename FrameId>\nstd::string Stringify(const Tfrm<FrameId>& tfrm)\n{\n  return fmt::format(\n      \"([{}] <- [{}], ROT: (W: {}, X: {}, Y: {}, Z: {}), TRANS: (X: {}, Y: {}, Z: {}))\",\n      tfrm.to_frame_, tfrm.from_frame_, tfrm.rot_.w(), tfrm.rot_.x(), tfrm.rot_.y(), tfrm.rot_.z(),\n      tfrm.trans_.x(), tfrm.trans_.y(), tfrm.trans_.z());\n}\n\ntemplate <typename FrameId>\nstd::string Stringify(const FramePair<FrameId>& frame_pair)\n{\n  return fmt::format(\"([{}] <- [{}])\", frame_pair.to_frame, frame_pair.from_frame);\n}\n\n}  // namespace ttfrm\n\n#endif  // TTFRM_TFRM_HPP\n", "meta": {"hexsha": "c0ae959454d8d09d9fe21d6bf96697cfc2a5ae24", "size": 11267, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ttfrm/tfrm.hpp", "max_stars_repo_name": "tprk77/ttfrm", "max_stars_repo_head_hexsha": "a228043e0b4a937188c586280964c8a9798e9dba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T03:09:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T03:09:50.000Z", "max_issues_repo_path": "ttfrm/tfrm.hpp", "max_issues_repo_name": "tprk77/ttfrm", "max_issues_repo_head_hexsha": "a228043e0b4a937188c586280964c8a9798e9dba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-10-07T13:45:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-24T02:11:37.000Z", "max_forks_repo_path": "ttfrm/tfrm.hpp", "max_forks_repo_name": "tprk77/ttfrm", "max_forks_repo_head_hexsha": "a228043e0b4a937188c586280964c8a9798e9dba", "max_forks_repo_licenses": ["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.4720670391, "max_line_length": 99, "alphanum_fraction": 0.6973462324, "num_tokens": 3053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.23194161390836884}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2013 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n#ifndef BOOST_MP_FLOAT128_HPP\n#define BOOST_MP_FLOAT128_HPP\n\n#include <boost/config.hpp>\n#include <boost/scoped_array.hpp>\n#include <boost/functional/hash.hpp>\n#include <boost/multiprecision/number.hpp>\n\n#if defined(BOOST_INTEL) && !defined(BOOST_MP_USE_FLOAT128) && !defined(BOOST_MP_USE_QUAD)\n#  if defined(BOOST_INTEL_CXX_VERSION) && (BOOST_INTEL_CXX_VERSION >= 1310) && defined(__GNUC__)\n#    if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6))\n#      define BOOST_MP_USE_FLOAT128\n#    endif\n#  endif\n\n#  ifndef BOOST_MP_USE_FLOAT128\n#    define BOOST_MP_USE_QUAD\n#  endif\n#endif\n\n#if defined(__GNUC__) && !defined(BOOST_MP_USE_FLOAT128) && !defined(BOOST_MP_USE_QUAD)\n#  define BOOST_MP_USE_FLOAT128\n#endif\n\n#if !defined(BOOST_MP_USE_FLOAT128) && !defined(BOOST_MP_USE_QUAD)\n#  error \"Sorry compiler is neither GCC, not Intel, don't know how to configure this header.\"\n#endif\n#if defined(BOOST_MP_USE_FLOAT128) && defined(BOOST_MP_USE_QUAD)\n#  error \"Oh dear, both BOOST_MP_USE_FLOAT128 and BOOST_MP_USE_QUAD are defined, which one should I be using?\"\n#endif\n\n#if defined(BOOST_MP_USE_FLOAT128)\n\nextern \"C\" {\n#include <quadmath.h>\n}\n\ntypedef __float128 float128_type;\n\n#elif defined(BOOST_MP_USE_QUAD)\n\n#include <boost/multiprecision/detail/float_string_cvt.hpp>\n\ntypedef _Quad float128_type;\n\nextern \"C\" {\n_Quad __ldexpq(_Quad, int);\n_Quad __frexpq(_Quad, int*);\n_Quad __fabsq(_Quad);\n_Quad __floorq(_Quad);\n_Quad __ceilq(_Quad);\n_Quad __sqrtq(_Quad);\n_Quad __truncq(_Quad);\n_Quad __expq(_Quad);\n_Quad __powq(_Quad, _Quad);\n_Quad __logq(_Quad);\n_Quad __log10q(_Quad);\n_Quad __sinq(_Quad);\n_Quad __cosq(_Quad);\n_Quad __tanq(_Quad);\n_Quad __asinq(_Quad);\n_Quad __acosq(_Quad);\n_Quad __atanq(_Quad);\n_Quad __sinhq(_Quad);\n_Quad __coshq(_Quad);\n_Quad __tanhq(_Quad);\n_Quad __fmodq(_Quad, _Quad);\n_Quad __atan2q(_Quad, _Quad);\n\n#define ldexpq __ldexpq\n#define frexpq __frexpq\n#define fabsq __fabsq\n#define floorq __floorq\n#define ceilq __ceilq\n#define sqrtq __sqrtq\n#define truncq __truncq\n#define expq __expq\n#define powq __powq\n#define logq __logq\n#define log10q __log10q\n#define sinq __sinq\n#define cosq __cosq\n#define tanq __tanq\n#define asinq __asinq\n#define acosq __acosq\n#define atanq __atanq\n#define sinhq __sinhq\n#define coshq __coshq\n#define tanhq __tanhq\n#define fmodq __fmodq\n#define atan2q __atan2q\n}\n\ninline _Quad isnanq(_Quad v)\n{\n   return v != v;\n}\ninline _Quad isinfq(_Quad v)\n{\n   return __fabsq(v) > 1.18973149535723176508575932662800702e4932Q;\n}\n\n#endif\n\nnamespace boost{\nnamespace multiprecision{\nnamespace backends{\n\nstruct float128_backend;\n\n}\n\nusing backends::float128_backend;\n\ntemplate<>\nstruct number_category<backends::float128_backend> : public mpl::int_<number_kind_floating_point> {};\n#if defined(BOOST_MP_USE_QUAD)\ntemplate<>\nstruct number_category<float128_type> : public mpl::int_<number_kind_floating_point> {};\n#endif\n\ntypedef number<float128_backend, et_off> float128;\n\n#ifndef BOOST_NO_CXX11_CONSTEXPR\n\nnamespace quad_constants {\n   constexpr __float128 quad_min = static_cast<__float128>(1)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN) / 1073741824;\n\n   constexpr __float128 quad_denorm_min = static_cast<__float128>(1)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN)\n      * static_cast<__float128>(DBL_MIN) / 5.5751862996326557854e+42;\n\n   constexpr double dbl_mult = 8.9884656743115795386e+307;  // This has one bit set only.\n   constexpr __float128 quad_max = (static_cast<__float128>(1) - 9.62964972193617926527988971292463659e-35)  // This now has all bits sets to 1\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult)\n      * static_cast<__float128>(dbl_mult) * 65536;\n}\n\n#define BOOST_MP_QUAD_MIN boost::multiprecision::quad_constants::quad_min\n#define BOOST_MP_QUAD_DENORM_MIN boost::multiprecision::quad_constants::quad_denorm_min\n#define BOOST_MP_QUAD_MAX boost::multiprecision::quad_constants::quad_max\n\n#else\n\n#define BOOST_MP_QUAD_MIN 3.36210314311209350626267781732175260e-4932Q\n#define BOOST_MP_QUAD_DENORM_MIN 6.475175119438025110924438958227646552e-4966Q\n#define BOOST_MP_QUAD_MAX 1.18973149535723176508575932662800702e4932Q\n\n#endif\n\nnamespace backends{\n\nstruct float128_backend\n{\n   typedef mpl::list<signed char, short, int, long, boost::long_long_type>   signed_types;\n   typedef mpl::list<unsigned char, unsigned short, \n      unsigned int, unsigned long, boost::ulong_long_type>           unsigned_types;\n   typedef mpl::list<float, double, long double>                 float_types;\n   typedef int                                                   exponent_type;\n\nprivate:\n   float128_type m_value;\npublic:\n   BOOST_CONSTEXPR float128_backend() BOOST_NOEXCEPT : m_value(0) {}\n   BOOST_CONSTEXPR float128_backend(const float128_backend& o) BOOST_NOEXCEPT : m_value(o.m_value) {}\n   float128_backend& operator = (const float128_backend& o) BOOST_NOEXCEPT\n   {\n      m_value = o.m_value;\n      return *this;\n   }\n   template <class T>\n   BOOST_CONSTEXPR float128_backend(const T& i, const typename enable_if_c<is_convertible<T, float128_type>::value>::type* = 0) BOOST_NOEXCEPT_IF(noexcept(std::declval<float128_type&>() = std::declval<const T&>()))\n      : m_value(i) {}\n   template <class T>\n   typename enable_if_c<is_arithmetic<T>::value || is_convertible<T, float128_type>::value, float128_backend&>::type operator = (const T& i) BOOST_NOEXCEPT_IF(noexcept(std::declval<float128_type&>() = std::declval<const T&>()))\n   {\n      m_value = i;\n      return *this;\n   }\n   float128_backend(long double const& f)\n   {\n      BOOST_STATIC_CONSTEXPR __float128 inf_val = static_cast<__float128>(HUGE_VAL);\n      if(boost::math::isinf(f))\n         m_value = (f < 0) ? -inf_val : inf_val;\n      else\n         m_value = f;\n   }\n   float128_backend& operator=(long double const& f)\n   {\n      BOOST_STATIC_CONSTEXPR __float128 inf_val = static_cast<__float128>(HUGE_VAL);\n      if(boost::math::isinf(f))\n         m_value = (f < 0) ? -inf_val : inf_val;\n      else\n         m_value = f;\n      return *this;\n   }\n   float128_backend& operator = (const char* s)\n   {\n#ifndef BOOST_MP_USE_QUAD\n      char* p_end;\n      m_value = strtoflt128(s, &p_end);\n      if(p_end - s != (std::ptrdiff_t)std::strlen(s))\n      {\n         BOOST_THROW_EXCEPTION(std::runtime_error(\"Unable to interpret input string as a floating point value\"));\n      }\n#else\n      boost::multiprecision::detail::convert_from_string(*this, s);\n#endif\n      return *this;\n   }\n   void swap(float128_backend& o) BOOST_NOEXCEPT\n   {\n      std::swap(m_value, o.value());\n   }\n   std::string str(std::streamsize digits, std::ios_base::fmtflags f)const\n   {\n#ifndef BOOST_MP_USE_QUAD\n      char buf[100];\n      boost::scoped_array<char> buf2;\n      std::string format = \"%\";\n      if(f & std::ios_base::showpos)\n         format += \"+\";\n      if(f & std::ios_base::showpoint)\n         format += \"#\";\n      format += \".*\";\n      if(digits == 0)\n         digits = 36;\n      format += \"Q\";\n      if(f & std::ios_base::scientific)\n         format += \"e\";\n      else if(f & std::ios_base::fixed)\n         format += \"f\";\n      else\n         format += \"g\";\n\n      int v = quadmath_snprintf (buf, 100, format.c_str(), digits, m_value);\n\n      if((v < 0) || (v >= 99))\n      {\n         int v_max = v;\n         buf2.reset(new char[v+3]);\n         v = quadmath_snprintf (&buf2[0], v_max + 3, format.c_str(), digits, m_value);\n         if(v >= v_max + 3)\n         {\n            BOOST_THROW_EXCEPTION(std::runtime_error(\"Formatting of float128_type failed.\"));\n         }\n         return &buf2[0];\n      }\n      return buf;\n#else\n      return boost::multiprecision::detail::convert_to_string(*this, digits ? digits : 37, f);\n#endif\n   }\n   void negate() BOOST_NOEXCEPT\n   {\n      m_value = -m_value;\n   }\n   int compare(const float128_backend& o)const\n   {\n      return m_value == o.m_value ? 0 : m_value < o.m_value ? -1 : 1;\n   }\n   template <class T>\n   int compare(const T& i)const\n   {\n      return m_value == i ? 0 : m_value < i ? -1 : 1;\n   }\n   float128_type& value()\n   {\n      return m_value;\n   }\n   const float128_type& value()const\n   {\n      return m_value;\n   }\n};\n\ninline void eval_add(float128_backend& result, const float128_backend& a)\n{\n   result.value() += a.value();\n}\ntemplate <class A>\ninline void eval_add(float128_backend& result, const A& a)\n{\n   result.value() += a;\n}\ninline void eval_subtract(float128_backend& result, const float128_backend& a)\n{\n   result.value() -= a.value();\n}\ntemplate <class A>\ninline void eval_subtract(float128_backend& result, const A& a)\n{\n   result.value() -= a;\n}\ninline void eval_multiply(float128_backend& result, const float128_backend& a)\n{\n   result.value() *= a.value();\n}\ntemplate <class A>\ninline void eval_multiply(float128_backend& result, const A& a)\n{\n   result.value() *= a;\n}\ninline void eval_divide(float128_backend& result, const float128_backend& a)\n{\n   result.value() /= a.value();\n}\ntemplate <class A>\ninline void eval_divide(float128_backend& result, const A& a)\n{\n   result.value() /= a;\n}\n\ninline void eval_add(float128_backend& result, const float128_backend& a, const float128_backend& b)\n{\n   result.value() = a.value() + b.value();\n}\ntemplate <class A>\ninline void eval_add(float128_backend& result, const float128_backend& a, const A& b)\n{\n   result.value() = a.value() + b;\n}\ninline void eval_subtract(float128_backend& result, const float128_backend& a, const float128_backend& b)\n{\n   result.value() = a.value() - b.value();\n}\ntemplate <class A>\ninline void eval_subtract(float128_backend& result, const float128_backend& a, const A& b)\n{\n   result.value() = a.value() - b;\n}\ntemplate <class A>\ninline void eval_subtract(float128_backend& result, const A& a, const float128_backend& b)\n{\n   result.value() = a - b.value();\n}\ninline void eval_multiply(float128_backend& result, const float128_backend& a, const float128_backend& b)\n{\n   result.value() = a.value() * b.value();\n}\ntemplate <class A>\ninline void eval_multiply(float128_backend& result, const float128_backend& a, const A& b)\n{\n   result.value() = a.value() * b;\n}\ninline void eval_divide(float128_backend& result, const float128_backend& a, const float128_backend& b)\n{\n   result.value() = a.value() / b.value();\n}\n\ntemplate <class R>\ninline void eval_convert_to(R* result, const float128_backend& val)\n{\n   *result = static_cast<R>(val.value());\n}\n\ninline void eval_frexp(float128_backend& result, const float128_backend& arg, int* exp)\n{\n   result.value() = frexpq(arg.value(), exp);\n}\n\ninline void eval_ldexp(float128_backend& result, const float128_backend& arg, int exp)\n{\n   result.value() = ldexpq(arg.value(), exp);\n}\n\ninline void eval_floor(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = floorq(arg.value());\n}\ninline void eval_ceil(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = ceilq(arg.value());\n}\ninline void eval_sqrt(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = sqrtq(arg.value());\n}\ninline int eval_fpclassify(const float128_backend& arg)\n{\n   if(isnanq(arg.value()))\n      return FP_NAN;\n   else if(isinfq(arg.value()))\n      return FP_INFINITE;\n   else if(arg.value() == 0)\n      return FP_ZERO;\n\n   float128_backend t(arg);\n   if(t.value() < 0)\n      t.negate();\n   if(t.value() < BOOST_MP_QUAD_MIN)\n      return FP_SUBNORMAL;\n   return FP_NORMAL;\n}\n\ninline void eval_increment(float128_backend& arg)\n{\n   ++arg.value();\n}\ninline void eval_decrement(float128_backend& arg)\n{\n   --arg.value();\n}\n\n/*********************************************************************\n*\n* abs/fabs:\n*\n*********************************************************************/\n\ninline void eval_abs(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = fabsq(arg.value());\n}\ninline void eval_fabs(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = fabsq(arg.value());\n}\n\n/*********************************************************************\n*\n* Floating point functions:\n*\n*********************************************************************/\n\ninline void eval_trunc(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = truncq(arg.value());\n}\n/*\n// \n// This doesn't actually work... rely on our own default version instead.\n//\ninline void eval_round(float128_backend& result, const float128_backend& arg)\n{\n   if(isnanq(arg.value()) || isinf(arg.value()))\n   {\n      result = boost::math::policies::raise_rounding_error(\n            \"boost::multiprecision::trunc<%1%>(%1%)\", 0, \n            number<float128_backend, et_off>(arg), \n            number<float128_backend, et_off>(arg), \n            boost::math::policies::policy<>()).backend();\n      return;\n   }\n   result.value() = roundq(arg.value());\n}\n*/\n\ninline void eval_exp(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = expq(arg.value());\n}\ninline void eval_log(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = logq(arg.value());\n}\ninline void eval_log10(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = log10q(arg.value());\n}\ninline void eval_sin(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = sinq(arg.value());\n}\ninline void eval_cos(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = cosq(arg.value());\n}\ninline void eval_tan(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = tanq(arg.value());\n}\ninline void eval_asin(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = asinq(arg.value());\n}\ninline void eval_acos(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = acosq(arg.value());\n}\ninline void eval_atan(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = atanq(arg.value());\n}\ninline void eval_sinh(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = sinhq(arg.value());\n}\ninline void eval_cosh(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = coshq(arg.value());\n}\ninline void eval_tanh(float128_backend& result, const float128_backend& arg)\n{\n   result.value() = tanhq(arg.value());\n}\ninline void eval_fmod(float128_backend& result, const float128_backend& a, const float128_backend& b)\n{\n   result.value() = fmodq(a.value(), b.value());\n}\ninline void eval_pow(float128_backend& result, const float128_backend& a, const float128_backend& b)\n{\n   result.value() = powq(a.value(), b.value());\n}\ninline void eval_atan2(float128_backend& result, const float128_backend& a, const float128_backend& b)\n{\n   result.value() = atan2q(a.value(), b.value());\n}\n#ifndef BOOST_MP_USE_QUAD\ninline void eval_multiply_add(float128_backend& result, const float128_backend& a, const float128_backend& b, const float128_backend& c)\n{\n   result.value() = fmaq(a.value(), b.value(), c.value());\n}\ninline int eval_signbit BOOST_PREVENT_MACRO_SUBSTITUTION(const float128_backend& arg)\n{\n   return ::signbitq(arg.value());\n}\n#endif\n\ninline std::size_t hash_value(const float128_backend& val)\n{\n   return  boost::hash_value(static_cast<double>(val.value()));\n}\n\n} // namespace backends\n\n   template<boost::multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<float128_backend, ExpressionTemplates> asinh BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<float128_backend, ExpressionTemplates>& arg)\n   {\n      return asinhq(arg.backend().value());\n   }\n   template<boost::multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<float128_backend, ExpressionTemplates> acosh BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<float128_backend, ExpressionTemplates>& arg)\n   {\n      return acoshq(arg.backend().value());\n   }\n   template<boost::multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<float128_backend, ExpressionTemplates> atanh BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<float128_backend, ExpressionTemplates>& arg)\n   {\n      return atanhq(arg.backend().value());\n   }\n   template<boost::multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<float128_backend, ExpressionTemplates> cbrt BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<float128_backend, ExpressionTemplates>& arg)\n   {\n      return cbrtq(arg.backend().value());\n   }\n   template<boost::multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<float128_backend, ExpressionTemplates> erf BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<float128_backend, ExpressionTemplates>& arg)\n   {\n      return erfq(arg.backend().value());\n   }\n   template<boost::multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<float128_backend, ExpressionTemplates> erfc BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<float128_backend, ExpressionTemplates>& arg)\n   {\n      return erfcq(arg.backend().value());\n   }\n   template<boost::multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<float128_backend, ExpressionTemplates> expm1 BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<float128_backend, ExpressionTemplates>& arg)\n   {\n      return expm1q(arg.backend().value());\n   }\n   template<boost::multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<float128_backend, ExpressionTemplates> lgamma BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<float128_backend, ExpressionTemplates>& arg)\n   {\n      return lgammaq(arg.backend().value());\n   }\n   template<boost::multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<float128_backend, ExpressionTemplates> tgamma BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<float128_backend, ExpressionTemplates>& arg)\n   {\n      return tgammaq(arg.backend().value());\n   }\n   template<boost::multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<float128_backend, ExpressionTemplates> log1p BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<float128_backend, ExpressionTemplates>& arg)\n   {\n      return log1pq(arg.backend().value());\n   }\n\n#ifndef BOOST_MP_USE_QUAD\n   template <multiprecision::expression_template_option ExpressionTemplates>\n   inline boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> copysign BOOST_PREVENT_MACRO_SUBSTITUTION(const boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates>& a, const boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates>& b)\n   {\n      return ::copysignq(a.backend().value(), b.backend().value());\n   }\n\n   inline void eval_remainder(float128_backend& result, const float128_backend& a, const float128_backend& b)\n   {\n      result.value() = remainderq(a.value(), b.value());\n   }\n   inline void eval_remainder(float128_backend& result, const float128_backend& a, const float128_backend& b, int* pi)\n   {\n      result.value() = remquoq(a.value(), b.value(), pi);\n   }\n#endif\n\n} // namespace multiprecision\n\nnamespace math {\n\n   using boost::multiprecision::signbit;\n   using boost::multiprecision::copysign;\n\n} // namespace math\n\n} // namespace boost\n\nnamespace boost{ \nnamespace archive{\n\nclass binary_oarchive;\nclass binary_iarchive;\n\n}\n   \nnamespace serialization{ namespace float128_detail{\n\ntemplate <class Archive>\nvoid do_serialize(Archive& ar, boost::multiprecision::backends::float128_backend& val, const mpl::false_&, const mpl::false_&)\n{\n   // saving\n   // non-binary\n   std::string s(val.str(0, std::ios_base::scientific));\n   ar & s;\n}\ntemplate <class Archive>\nvoid do_serialize(Archive& ar, boost::multiprecision::backends::float128_backend& val, const mpl::true_&, const mpl::false_&)\n{\n   // loading\n   // non-binary\n   std::string s;\n   ar & s;\n   val = s.c_str();\n}\n\ntemplate <class Archive>\nvoid do_serialize(Archive& ar, boost::multiprecision::backends::float128_backend& val, const mpl::false_&, const mpl::true_&)\n{\n   // saving\n   // binary\n   ar.save_binary(&val, sizeof(val));\n}\ntemplate <class Archive>\nvoid do_serialize(Archive& ar, boost::multiprecision::backends::float128_backend& val, const mpl::true_&, const mpl::true_&)\n{\n   // loading\n   // binary\n   ar.load_binary(&val, sizeof(val));\n}\n\n} // detail\n\ntemplate <class Archive>\nvoid serialize(Archive& ar, boost::multiprecision::backends::float128_backend& val, unsigned int /*version*/)\n{\n   typedef typename Archive::is_loading load_tag;\n   typedef typename mpl::bool_<boost::is_same<Archive, boost::archive::binary_oarchive>::value || boost::is_same<Archive, boost::archive::binary_iarchive>::value> binary_tag;\n\n   float128_detail::do_serialize(ar, val, load_tag(), binary_tag());\n}\n\n} // namepsace archive\n\n} // namespace boost\n\nnamespace std{\n\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nclass numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >\n{\n   typedef boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> number_type;\npublic:\n   BOOST_STATIC_CONSTEXPR bool is_specialized = true;\n   static number_type (min)() BOOST_NOEXCEPT { return BOOST_MP_QUAD_MIN; }\n   static number_type (max)() BOOST_NOEXCEPT { return BOOST_MP_QUAD_MAX; }\n   static number_type lowest() BOOST_NOEXCEPT { return -(max)(); }\n   BOOST_STATIC_CONSTEXPR int digits = 113;\n   BOOST_STATIC_CONSTEXPR int digits10 = 33;\n   BOOST_STATIC_CONSTEXPR int max_digits10 = 36;\n   BOOST_STATIC_CONSTEXPR bool is_signed = true;\n   BOOST_STATIC_CONSTEXPR bool is_integer = false;\n   BOOST_STATIC_CONSTEXPR bool is_exact = false;\n   BOOST_STATIC_CONSTEXPR int radix = 2;\n   static number_type epsilon() { return 1.92592994438723585305597794258492732e-34; /* this double value has only one bit set and so is exact */ }\n   static number_type round_error() { return 0.5; }\n   BOOST_STATIC_CONSTEXPR int min_exponent = -16381;\n   BOOST_STATIC_CONSTEXPR int min_exponent10 = min_exponent * 301L / 1000L;\n   BOOST_STATIC_CONSTEXPR int max_exponent = 16384;\n   BOOST_STATIC_CONSTEXPR int max_exponent10 = max_exponent * 301L / 1000L;\n   BOOST_STATIC_CONSTEXPR bool has_infinity = true;\n   BOOST_STATIC_CONSTEXPR bool has_quiet_NaN = true;\n   BOOST_STATIC_CONSTEXPR bool has_signaling_NaN = false;\n   BOOST_STATIC_CONSTEXPR float_denorm_style has_denorm = denorm_present;\n   BOOST_STATIC_CONSTEXPR bool has_denorm_loss = true;\n   static number_type infinity() { return HUGE_VAL; /* conversion from double infinity OK */ }\n   static number_type quiet_NaN() { return number_type(\"nan\"); }\n   static number_type signaling_NaN() { return 0; }\n   static number_type denorm_min() { return BOOST_MP_QUAD_DENORM_MIN; }\n   BOOST_STATIC_CONSTEXPR bool is_iec559 = true;\n   BOOST_STATIC_CONSTEXPR bool is_bounded = false;\n   BOOST_STATIC_CONSTEXPR bool is_modulo = false;\n   BOOST_STATIC_CONSTEXPR bool traps = false;\n   BOOST_STATIC_CONSTEXPR bool tinyness_before = false;\n   BOOST_STATIC_CONSTEXPR float_round_style round_style = round_to_nearest;\n};\n\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::is_specialized;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::digits;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::digits10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::max_digits10;\n\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::is_signed;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::is_integer;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::is_exact;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::radix;\n\n\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::min_exponent;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::max_exponent;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::min_exponent10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::max_exponent10;\n\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::has_infinity;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::has_quiet_NaN;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::has_signaling_NaN;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::has_denorm_loss;\n\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::is_iec559;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::is_bounded;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::is_modulo;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::traps;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::tinyness_before;\n\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST float_round_style numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::round_style;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST float_denorm_style numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::has_denorm;\n\n} // namespace std\n\n\n#endif\n", "meta": {"hexsha": "b4b16c59745808d5163749fb91af619fa0319bdd", "size": 31173, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/boost/boost/multiprecision/float128.hpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1155.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T19:04:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:30:30.000Z", "max_issues_repo_path": "deps/boost/boost/multiprecision/float128.hpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 618.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T01:39:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:18:40.000Z", "max_forks_repo_path": "deps/boost/boost/multiprecision/float128.hpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 228.0, "max_forks_repo_forks_event_min_datetime": "2015-01-13T12:55:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T11:11:05.000Z", "avg_line_length": 38.4377311961, "max_line_length": 377, "alphanum_fraction": 0.7439771597, "num_tokens": 7661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.23194161390836882}}
{"text": "#include <stdlib.h>\n#include <iostream>\n#include <boost/optional/optional_io.hpp>\n#include <fstream>\n#include <sstream>\n#include <vector>\n#include <string>\n\n#include \"snark.hpp\"\n#include \"utils.cpp\"\n\nusing namespace libsnark;\nusing namespace std;\n\nint verifyProof(r1cs_ppzksnark_verification_key<default_r1cs_ppzksnark_pp> verificationKey_in, string proofFileName, string publicInputs)\n{\n  // Read proof in from file\n  //libsnark::r1cs_ppzksnark_proof<libff::alt_bn128_pp> proof_in;\n  boost::optional<libsnark::r1cs_ppzksnark_proof<libff::alt_bn128_pp>> proof_in;\n  //r1cs_ppzksnark_proof<default_r1cs_ppzksnark_pp> proof_in;\n  \n  cout << proofFileName << endl;\n  ifstream proofFileIn(proofFileName);\n  stringstream proofFromFile;\n  if (proofFileIn) {\n     proofFromFile << proofFileIn.rdbuf();\n     proofFileIn.close();\n  } else {\n    cout << \"Failed to read from proof file\" << endl;\n    return 1;\n  }\n\n  proofFromFile >> proof_in;\n  \n  // Hashes to validate against\n  std::vector<bool> h_startBalance_bv(256);\n  std::vector<bool> h_endBalance_bv(256);\n  std::vector<bool> h_incoming_bv(256);\n  std::vector<bool> h_outgoing_bv(256);\n  vector<vector<unsigned long int>> values = fillValuesFromfile(publicInputs);\n  h_startBalance_bv = int_list_to_bits_local(values[0], 8);\n  h_endBalance_bv = int_list_to_bits_local(values[1], 8);\n  h_incoming_bv = int_list_to_bits_local(values[2], 8);\n  h_outgoing_bv = int_list_to_bits_local(values[3], 8);\n\n  cout << \"proof read ... starting verification\" << endl;\n  // Verify the proof\n  bool isVerified = verify_payment_in_out_proof(verificationKey_in, *proof_in, h_startBalance_bv, h_endBalance_bv, h_incoming_bv, h_outgoing_bv);\n\n  if(isVerified){\n    cout << \"Proof was verified!!\" << proofFileName << endl;\n    return 0;\n  } else {\n    cout << \"Proof was not verified!!\" << proofFileName << endl;\n    return 1;\n  }\n}\n\nint main(int argc, char *argv[])\n{\n  // Initialize the curve parameters.\n  default_r1cs_ppzksnark_pp::init_public_params();\n\n  // Read verification key in from file\n  r1cs_ppzksnark_verification_key<default_r1cs_ppzksnark_pp> verificationKey_in;\n  ifstream fileIn(\"verificationKey_single\");\n  stringstream verificationKeyFromFile;\n  if (fileIn) {\n     verificationKeyFromFile << fileIn.rdbuf();\n     fileIn.close();\n  }\n  verificationKeyFromFile >> verificationKey_in;\n\n  string proofName = \"proof_single_\";\n  string proofNameWithId = proofName + argv[1];\n  string publicInputs = \"publicInputParameters_single_\";\n  string publicInputsWithId = publicInputs + argv[1];\n  return verifyProof(verificationKey_in, proofNameWithId, publicInputsWithId);\n}\n\n\n", "meta": {"hexsha": "2d25dc7f62dbc9b16e47d0e4cf179050b08aa8cb", "size": 2612, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/payment_in_out_verify_proof.cpp", "max_stars_repo_name": "agiletechvn/ZKP", "max_stars_repo_head_hexsha": "d1294da076585e2a906aa64560a71fc68114c75c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 118.0, "max_stars_repo_stars_event_min_datetime": "2017-08-29T05:25:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T13:59:39.000Z", "max_issues_repo_path": "src/payment_in_out_verify_proof.cpp", "max_issues_repo_name": "technologiespro/zero-knowledge-proofs", "max_issues_repo_head_hexsha": "6fdfb0c25ae24e33b6325baa2b261860e89ae087", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-08-29T03:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-10T23:39:26.000Z", "max_forks_repo_path": "src/payment_in_out_verify_proof.cpp", "max_forks_repo_name": "technologiespro/zero-knowledge-proofs", "max_forks_repo_head_hexsha": "6fdfb0c25ae24e33b6325baa2b261860e89ae087", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2017-08-29T01:50:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T13:38:35.000Z", "avg_line_length": 31.8536585366, "max_line_length": 145, "alphanum_fraction": 0.7473200613, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.23184220331106553}}
{"text": "#include <map>\n#include <set>\n\n#include <util/timer.h>\n#include <math/accum.h>\n#include <Eigen/SparseCore>\n#include <Eigen/IterativeLinearSolvers>\n\n#include \"texturing.h\"\n#include \"seam_leveling.h\"\n#include \"progress_counter.h\"\n\nTEX_NAMESPACE_BEGIN\n\n/*\n* 寻找以vertex为边的所有边界(一般有两条), 边界的左右两边的图片分别是label1, label2\n* */\nvoid find_seam_edges_for_vertex_label_combination(UniGraph const & graph, mve::TriangleMesh::ConstPtr & mesh,\n    mve::MeshInfo const & mesh_info, std::size_t vertex, std::size_t label1, std::size_t label2,\n    std::vector<MeshEdge> * seam_edges){\n    \n    assert(label1 != 0 && label2 != 0 && label1 < label2);\n\n    mve::TriangleMesh::VertexList const & vertices = mesh->get_vertices();\n\n    std::vector<std::size_t> const & adj_verts = mesh_info[vertex].verts;  // 顶点相邻的顶点\n    for (std::size_t i = 0; i < adj_verts.size(); ++i){\n        std::size_t adj_vertex = adj_verts[i];\n        if (vertex == adj_vertex) continue;\n        \n        std::vector<std::size_t> edge_faces;\n        mesh_info.get_faces_for_edge(vertex, adj_vertex, &edge_faces);  // 返回两个顶点相邻的面片\n\n        for (std::size_t j = 0; j < edge_faces.size(); ++j) {\n            for(std::size_t k = j + 1; k < edge_faces.size(); ++k) {\n                std::size_t face_label1 = graph.get_label(edge_faces[j]);\n                std::size_t face_label2 = graph.get_label(edge_faces[k]);\n                if (!(face_label1 < face_label2)) std::swap(face_label1, face_label2);\n                \n                if (face_label1 != label1 || face_label2 != label2) continue;\n\n                math::Vec3f v1 = vertices[vertex];\n                math::Vec3f v2 = vertices[adj_vertex];\n\n                if ((v2 - v1).norm() == 0.0f) continue;  // 边长为0, 退出\n\n                MeshEdge seam_edge = {vertex, adj_vertex};\n                seam_edges->push_back(seam_edge);\n            }\n        }\n    }\n}\n\n\n\nmath::Vec3f calculate_difference(VertexProjectionInfos const & vertex_projection_infos,\n    mve::TriangleMesh::ConstPtr & mesh, std::vector<TexturePatch::Ptr> const &  texture_patches,\n    std::vector<MeshEdge> const & seam_edges, int label1, int label2) {\n\n    assert(label1 != 0 && label2 != 0 && label1 < label2);\n    assert(!seam_edges.empty());\n    \n    mve::TriangleMesh::VertexList const & vertices = mesh->get_vertices();\n\n    math::Accum<math::Vec3f> color1_accum(math::Vec3f(0.0f));  // 一个累加器(支持基本整型的数据相加)\n    math::Accum<math::Vec3f> color2_accum(math::Vec3f(0.0f));\n\n    for (MeshEdge const & seam_edge : seam_edges) {\n        math::Vec3f v1 = vertices[seam_edge.v1];\n        math::Vec3f v2 = vertices[seam_edge.v2];\n        \n        if ((v2 - v1).norm() == 0.0f) continue;  // 边长为0, 退出\n\n        std::vector<EdgeProjectionInfo> edge_projection_infos;\n        // find_mesh_edge_projections(vertex_projection_infos, seam_edge, &edge_projection_infos);\n\n        \n    }\n}\n\nvoid global_seam_leveling(UniGraph const & graph, mve::TriangleMesh::ConstPtr mesh,\n    mve::MeshInfo const & mesh_info,\n    std::vector<std::vector<VertexProjectionInfo> > const & vertex_projection_infos,\n    std::vector<TexturePatch::Ptr> * texture_patches) {\n    \n    mve::TriangleMesh::VertexList const & vertices = mesh->get_vertices();\n    std::size_t const num_vertices = vertices.size();\n\n    std::cout << \"\\t 创建用于优化的矩阵... \" << std::flush;\n\n    std::vector<std::map<std::size_t, std::size_t> > vertlabel2row;  // 把顶点和view对应起来, 一个顶点可能被多个面共用, 所以一个顶点可能对多个view, 相同点不同的view,点的序号也不同  vertlabel2row[顶点_id(即在mesh中所有顶点的索引)][view_id] = 点的新序号(即x_row)\n    vertlabel2row.resize(num_vertices);\n\n    std::vector<std::vector<std::size_t> > labels;  // 索引和顶点在mesh中的索引一样 {{view的id}}\n    labels.resize(num_vertices);\n\n    // 为每个标签的每个顶点 指定一个新索引（row）\n    std::size_t x_row = 0;  // 顶点的序号\n    for (std::size_t i = 0; i < num_vertices; ++i) {  // 遍历每个顶点\n        std::set<std::size_t> label_set;  // 集合 如果使用当前顶点的多个面来自同一个view, 只保留一个\n    \n        std::vector<std::size_t> faces = mesh_info[i].faces;  // 相邻面\n        std::set<std::size_t>::iterator it = label_set.begin();\n        for (std::size_t j = 0; j < faces.size(); ++j) {  // 遍历每个相邻面, 找出这个顶点相邻的面片用到的view有哪些\n            std::size_t label = graph.get_label(faces[j]);  // 面用的是哪个view\n            label_set.insert(it, label);\n        }\n\n        for (it = label_set.begin(); it != label_set.end(); ++it) {  // 遍历顶点相邻的面用到的view\n            std::size_t label = *it;\n            if (label == 0) continue;\n\n            vertlabel2row[i][label] = x_row;  // \n            labels[i].push_back(label);\n            ++x_row;\n        }\n    }\n\n    std::size_t x_rows = x_row;\n    assert(x_rows < static_cast<std::size_t>(std::numeric_limits<int>::max()));\n\n    float const lambda = 0.1f;\n\n    /* Fill the Tikhonov matrix Gamma(regularization constraints). */\n    std::size_t Gamma_row = 0;  // 能表示有多少对在同一个patch又相邻的顶点\n    std::vector<Eigen::Triplet<float, int> > coefficients_Gamma;  // A small structure to hold a non zero as a triplet (i,j,value).  用来选中在同一个纹理块的顶点, 给他们的g加个正则项防止过大  [从0开始的索引][顶点的序号]:+/-λ\n    coefficients_Gamma.reserve(2 * num_vertices);\n    for (std::size_t i = 0; i < num_vertices; ++i) {  // 遍历每个顶点\n        for (std::size_t j = 0; j < labels[i].size(); ++j) {  // 遍历每个顶点连接的view\n            std::vector<std::size_t> const & adj_verts = mesh_info[i].verts;  // 相邻顶点\n            for (std::size_t k = 0; k < adj_verts.size(); ++k) {  // 遍历相邻顶点\n                std::size_t adj_vertex = adj_verts[k];\n                for (std::size_t l = 0; l < labels[adj_vertex].size(); ++l) {  // 遍历相邻顶点连接的view\n                    std::size_t label = labels[i][j];  // 当前顶点的一个view\n                    std::size_t adj_vertex_label = labels[adj_vertex][l];  // 相邻顶点的一个view\n                    if (i < adj_vertex && label == adj_vertex_label) {  // 两个顶点用的是同一个view\n                        Eigen::Triplet<float, int> t1(Gamma_row, vertlabel2row[i][label], lambda);\n                        Eigen::Triplet<float, int> t2(Gamma_row, vertlabel2row[adj_vertex][adj_vertex_label], -lambda);\n                        coefficients_Gamma.push_back(t1);\n                        coefficients_Gamma.push_back(t2);\n                        Gamma_row++;\n                    }\n                }\n            }\n        }\n    }\n\n    std::size_t Gamma_rows = Gamma_row;\n    assert(Gamma_rows < static_cast<std::size_t>(std::numeric_limits<int>::max()));\n\n    Eigen::SparseMatrix<float> Gamma(Gamma_rows, x_rows);  // (相邻顶点且相同view的个数, 顶点的view的组合个数) 行为同一个patch又相邻的顶点对的对数, 列为顶点(如果是不同view的顶点, 要区别对待)\n    Gamma.setFromTriplets(coefficients_Gamma.begin(), coefficients_Gamma.end());\n\n    /* Fill the matrix A and the coefficients for the Vector b of the linear equation system. */\n    std::vector<Eigen::Triplet<float, int> > coefficients_A;  // [从0开始的索引][view的序号]:+/-1\n    std::vector<math::Vec3f> coefficients_b;\n    std::size_t A_row = 0;\n    for (std::size_t i = 0; i < num_vertices; ++i) {\n        for (std::size_t j = 0; j < labels[i].size(); ++j) {  // 遍历顶点连接的view\n            for (std::size_t k = 0; k < labels[i].size(); ++k) {\n                std::size_t label1 = labels[i][j];\n                std::size_t label2 = labels[i][k];\n                if (label1 < label2) {  // 不同的patch才有seam\n\n                    std::vector<MeshEdge> seam_edges;  // 纹理的边缘\n                    find_seam_edges_for_vertex_label_combination(graph, mesh, mesh_info, i, label1, label2, &seam_edges);\n\n                    if (seam_edges.empty()) continue;\n\n                    Eigen::Triplet<float, int> t1(A_row, vertlabel2row[i][label1], 1.0f);\n                    Eigen::Triplet<float, int> t2(A_row, vertlabel2row[i][label2], -1.0f);\n                    coefficients_A.push_back(t1);\n                    coefficients_A.push_back(t2);\n\n                    coefficients_b.push_back(calculate_difference(vertex_projection_infos, mesh, *texture_patches, seam_edges, label1, label2));\n\n                    ++A_row;\n                }\n            }\n        }\n    }\n\n    std::size_t A_rows = A_row;\n    assert(A_rows < static_cast<std::size_t>(std::numeric_limits<int>::max()));\n\n    Eigen::SparseMatrix<float> A(A_rows, x_rows);  // (接缝的数量, 顶点的view的组合个数), 每一行中有一个-1, 1, 且这两个元素位于接缝处\n    A.setFromTriplets(coefficients_A.begin(), coefficients_A.end());\n\n    Eigen::SparseMatrix<float> Lhs = A.transpose() * A + Gamma.transpose() * Gamma;\n    /* Only keep lower triangle (CG only uses the lower), prune the rest and compress matrix. */\n    Lhs.prune([](const int& row, const int& col, const float& value) -> bool {  // left hand side\n            return col <= row && value != 0.0f;  // 下三角\n        }); // value != 0.0f is only to suppress a compiler warning\n\n    std::vector<std::map<std::size_t, math::Vec3f> > adjust_values(num_vertices);  // 每个顶点的调整值1\n    std::cout << \"完成.\" << std::endl;\n    std::cout << \"\\tLhs的维度: \" << Lhs.rows() << \" x \" << Lhs.cols() << std::endl;\n\n    util::WallTimer timer;\n    std::cout << \"\\t 计算颜色调整:\"<< std::endl;\n    #pragma omp parallel for\n    for (std::size_t channel = 0; channel < 3; ++channel) {\n        /* Prepare solver. */\n        Eigen::ConjugateGradient<Eigen::SparseMatrix<float>, Eigen::Lower> cg;\n        cg.setMaxIterations(1000);\n        cg.setTolerance(0.0001);   // The tolerance corresponds to the relative residual error: |Ax-b|/|b|\n        cg.compute(Lhs);\n\n        /* Prepare right hand side. */\n        Eigen::VectorXf b(A_rows);\n        for (std::size_t i = 0; i < coefficients_b.size(); ++i) {\n            b[i] = coefficients_b[i][channel];\n        }\n        Eigen::VectorXf Rhs = Eigen::SparseMatrix<float>(A.transpose()) * b;\n\n        /* Solve for x. */\n        Eigen::VectorXf x(x_rows);\n        x = cg.solve(Rhs);\n\n        /* 减去平均值，因为系统是欠约束的，我们寻求最小调整的解。 */\n        x = x.array() - x.mean();\n\n        #pragma omp critical\n        std::cout << \"\\t\\t 颜色通道\" << channel << \": CG 花了 \"\n            << cg.iterations() << \"次迭代. 残差是\" << cg.error() << std::endl;\n\n        #pragma omp critical\n        for (std::size_t i = 0; i < num_vertices; ++i) {\n            for (std::size_t j = 0; j < labels[i].size(); ++j) {\n                std::size_t label = labels[i][j];\n                adjust_values[i][label][channel] = x[vertlabel2row[i][label]];\n            }\n        }\n    }\n    // std::cout << \"\\t\\t 花费了\" << timer.get_elapsed_sec() << \"秒\" << std::endl;\n\n    // mve::TriangleMesh::FaceList const & mesh_faces = mesh->get_faces();\n\n    // ProgressCounter texture_patch_counter(\"\\t 调整纹理块\", texture_patches->size());\n    // #pragma omp parallel for schedule(dynamic)\n    // for (std::size_t i = 0; i < texture_patches->size(); ++i) {\n    //     texture_patch_counter.progress<SIMPLE>();\n\n    //     TexturePatch::Ptr texture_patch = texture_patches->at(i);\n\n    //     int label = texture_patch->get_label();\n    //     std::vector<std::size_t> const & faces = texture_patch->get_faces();\n    //     std::vector<math::Vec3f> patch_adjust_values(faces.size() * 3, math::Vec3f(0.0f));  // 三通道\n\n    //     /* Only adjust texture_patches originating form input images. */\n    //     if (label == 0) {\n    //         texture_patch->adjust_colors(patch_adjust_values);\n    //         texture_patch_counter.inc();\n    //         continue;\n    //     };\n\n    //     for (std::size_t j = 0; j < faces.size(); ++j) {\n    //         for (std::size_t k = 0; k < 3; ++k) {\n    //             std::size_t face_pos = faces[j] * 3 + k;\n    //             std::size_t vertex = mesh_faces[face_pos];\n    //             patch_adjust_values[j * 3 + k] = adjust_values[vertex].find(label)->second;\n    //         }\n    //     }\n\n    //     texture_patch->adjust_colors(patch_adjust_values);\n    //     texture_patch_counter.inc();\n    // }\n}\n\nTEX_NAMESPACE_END\n", "meta": {"hexsha": "a62551958a7f8f9b67229fd0c5e2708be719d4f1", "size": 11590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/tex/global_seam_leveling.cpp", "max_stars_repo_name": "sucongCJS/mvs-texturing", "max_stars_repo_head_hexsha": "413ad0619eaadb1a9416ae347ff1f9989b29ca59", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/tex/global_seam_leveling.cpp", "max_issues_repo_name": "sucongCJS/mvs-texturing", "max_issues_repo_head_hexsha": "413ad0619eaadb1a9416ae347ff1f9989b29ca59", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/tex/global_seam_leveling.cpp", "max_forks_repo_name": "sucongCJS/mvs-texturing", "max_forks_repo_head_hexsha": "413ad0619eaadb1a9416ae347ff1f9989b29ca59", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.7675276753, "max_line_length": 198, "alphanum_fraction": 0.5917169974, "num_tokens": 3680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.23178467793877455}}
{"text": "/*\n * LikelihoodBasedTopPairReconstruction.cpp\n *\n *  Created on: 25 Aug 2011\n *      Author: kreczko\n */\n\n#include \"../../interface/ReconstructionModules/LikelihoodBasedTopPairReconstruction.h\"\n#include <boost/lexical_cast.hpp>\n\nusing namespace std;\n\nnamespace BAT {\n\nLikelihoodBasedTopPairReconstruction::LikelihoodBasedTopPairReconstruction(const LeptonPointer lepton, const METPointer met, const JetCollection jets, const JetCollection bjets):\n\t\tsolutions(),\n\t\talreadyReconstructed(false),\n\t\tmet(met),\n\t\tjets(jets),\n\t\tbjets(bjets),\n\t\tleptonFromW(lepton) {\n}\n\nbool LikelihoodBasedTopPairReconstruction::meetsInitialCriteria() const {\n\treturn met != 0 && leptonFromW != 0 && jets.size() >= 4;\n}\n\nstd::string LikelihoodBasedTopPairReconstruction::getDetailsOnFailure() const {\n\tstd::string msg = \"Initial Criteria not met: \\n\";\n\tif (leptonFromW == 0)\n\t\tmsg += \"Electron from W: not filled \\n\";\n\telse\n\t\tmsg += \"Electron from W: filled \\n\";\n\n\tif (met == 0)\n\t\tmsg += \"Missing transverse energy: not filled \\n\";\n\telse\n\t\tmsg += \"Missing transverse energy: filled \\n\";\n\tstd::string nJets(boost::lexical_cast<std::string>(jets.size()));\n\tif (jets.size() < 4)\n\t\tmsg += \"Number of jets is too small:\" + nJets + \", should be >= 4 \\n\";\n\telse\n\t\tmsg += \"Number of jets is OK:\" + nJets + \"\\n\";\n\n\treturn msg;\n}\n\n\n\nLikelihoodBasedTopPairReconstruction::~LikelihoodBasedTopPairReconstruction() {\n}\n\nTtbarHypothesisCollection LikelihoodBasedTopPairReconstruction::getAllSolutions(){\n\tif(!alreadyReconstructed)\n\t\treconstruct();\n\n\tSmallerDiscriminatorIsBetter solutionComparator = SmallerDiscriminatorIsBetter();\n\tstd::sort(solutions.begin(), solutions.end(), solutionComparator);\n\treturn solutions;\n}\n\nconst TtbarHypothesisPointer LikelihoodBasedTopPairReconstruction::getBestSolution() {\n\tconst TtbarHypothesisPointer bestSolution = getAllSolutions().front();//sorted by quality, front == best\n\treturn bestSolution;\n}\n\nvoid LikelihoodBasedTopPairReconstruction::reconstruct() {\n\ttypedef unsigned short ushort;\n\n\t// Loop b jets to get hadronic b candidate\n\tfor (ushort hadBindex = 0; hadBindex < bjets.size(); ++hadBindex) {\n\t\tJetPointer hadBJet = bjets[hadBindex];\n\t\tLeptonPointer signallepton = leptonFromW;\n\t\tMETPointer MET = met;\n\n\t\tif (!meetsHadronicBJetRequirement(hadBJet))\n\t\t\tcontinue;\n\t\t// Loop b jets to get leptonic b candidate\n\t\tfor (ushort lepBindex = 0; lepBindex < bjets.size(); ++lepBindex) {\n\t\t\tJetPointer lepBJet = bjets[lepBindex];\n\t\t\tif (lepBindex == hadBindex || !meetsLeptonicBJetRequirement(lepBJet))\n\t\t\t\tcontinue;\n\n\t\t\t// Loop light jets to get jets from W\n\n\n\t\t\tfor ( ushort jet1Index=0; jet1Index < (jets.size()-1); ++jet1Index ) {\n\t\t\t\tfor ( ushort jet2Index=jet1Index+1; jet2Index < jets.size(); ++jet2Index ) {\n\n\t\t\t// for (ushort jet1Index = 0; jet1Index < jets.size(); ++jet1Index) {\n\t\t\t// \tfor (ushort jet2Index = 0; jet2Index < jets.size(); ++jet2Index) {\n\t\t\t\t\tJetPointer jet1FromW = jets[jet1Index];\n\t\t\t\t\tJetPointer jet2FromW = jets[jet2Index];\n\n\t\t\t\t\tif (jet2Index == jet1Index || !meetsJetFromWRequirement(jet1FromW, jet2FromW))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t// Put all particles together\n\t\t\t\t\tTtbarHypothesisPointer solution(new TtbarHypothesis());\n\t\t\t\t\t//leptons\n\t\t\t\t\tsolution->leptonFromW = leptonFromW;\n\t\t\t\t\tdouble nuChi2 = -1;\n\t\t\t\t\tsolution->neutrinoFromW = getNeutrinoSolution( lepBJet, signallepton, MET, nuChi2 );\n\t\t\t\t\tsolution->neutrinoChi2 = nuChi2;\n\n\t\t\t\t\t//jets\n\t\t\t\t\tsolution->hadronicBJet = hadBJet;\n\t\t\t\t\tsolution->leptonicBjet = lepBJet;\n\t\t\t\t\tsolution->jet1FromW = jet1FromW;\n\t\t\t\t\tsolution->jet2FromW = jet2FromW;\n\n\t\t\t\t\t//combine reconstructed objects\n\t\t\t\t\tsolution->combineReconstructedObjects();\n\n\t\t\t\t\t// Get discrimnant for this solution\n\t\t\t\t\tsolution->discriminator = getDiscriminator(solution);\n\n\n\t\t\t\t\t// Store if event is physical (checks masses of tops and Ws > 0 )\n\t\t\t\t\tif (meetsGlobalRequirement(solution)){\n\t\t\t\t\t\tsolutions.push_back(solution);\n\t\t\t\t\t}\n\n\t\t\t\t\telse\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\talreadyReconstructed = true;\n}\n\n\nParticlePointer LikelihoodBasedTopPairReconstruction::getNeutrinoSolution(JetPointer BJet, LeptonPointer Lepton, METPointer met, double& neutrinoChi2) {\n\t// Do the neutrino reconstruction\n\tNeutrinoSolver neutrinoSolver( &(Lepton->getFourVector()), &(BJet->getFourVector()), 80, 173 );\n\tdouble test = -1;\n\tFourVector neutrino = neutrinoSolver.GetBest(met->getFourVector().Px(), met->getFourVector().Py(), 25., 25., 0., test );\n\tneutrinoChi2 = test;\n\n\treturn ParticlePointer (new Particle(neutrino.Energy(), neutrino.Px(), neutrino.Py(), neutrino.Pz()));\n}\n\nbool LikelihoodBasedTopPairReconstruction::meetsHadronicBJetRequirement(JetPointer hadBJet){\n\treturn true;\n}\n\nbool LikelihoodBasedTopPairReconstruction::meetsLeptonicBJetRequirement(JetPointer lepBJet){\n\treturn true;\n}\n\nbool LikelihoodBasedTopPairReconstruction::meetsJetFromWRequirement(JetPointer jet1, JetPointer jet2){\n\treturn true;\n}\n\nbool LikelihoodBasedTopPairReconstruction::meetsGlobalRequirement(const TtbarHypothesisPointer solution){\n\treturn solution->isPhysical();\n}\n\ndouble LikelihoodBasedTopPairReconstruction::getDiscriminator(const TtbarHypothesisPointer solution) const{\n\t// Given all the info for this solution/permutation, calculate the discriminant\n\t// cout << \"------------------------------------------------------\" << endl;\n\n\t// Print csv of hadronic b jet and probablitity from correct b histogram\n\tJetPointer hadBJet = solution->hadronicBJet;\n\tJetPointer lepBJet = solution->leptonicBjet;\n\tParticlePointer hadTop = solution->hadronicTop;\n\tParticlePointer lepTop = solution->leptonicTop;\n\tParticlePointer hadW = solution->hadronicW;\n\tParticlePointer lepW = solution->leptonicW;\n\n\tdouble NeutrinoChi2 = solution->neutrinoChi2;\n\n\tdouble hadBJetCSV = hadBJet->getBTagDiscriminator(BAT::BtagAlgorithm::value::CombinedSecondaryVertexV2);\n\tdouble lepBJetCSV = lepBJet->getBTagDiscriminator(BAT::BtagAlgorithm::value::CombinedSecondaryVertexV2);\n\n\tdouble Wmass = hadW->mass();\n\tdouble Topmass = hadTop->mass();\n\n\n\tdouble probCorrectHadB = Globals::csvCorrectPermHistogram->Interpolate( hadBJetCSV );\n\tdouble probIncorrectHadB = Globals::csvIncorrectPermHistogram->Interpolate( hadBJetCSV );\n\n\tdouble probCorrectLepB = Globals::csvCorrectPermHistogram->Interpolate( lepBJetCSV );\n\tdouble probIncorrectLepB = Globals::csvIncorrectPermHistogram->Interpolate( lepBJetCSV );\n\n\tdouble probCorrectNuChi2 = Globals::NuChiCorrectPermHistogram->Interpolate( NeutrinoChi2 );\n\tdouble probIncorrectNuChi2 = Globals::NuChiIncorrectPermHistogram->Interpolate( NeutrinoChi2 );\n\n\tdouble probCorrectWBMass = Globals::HadronicRecoCorrectPermHistogram->Interpolate( Wmass , Topmass );\n\tdouble probIncorrectWBMass = Globals::HadronicRecoIncorrectPermHistogram->Interpolate( Wmass , Topmass );\n\n\tif (probCorrectWBMass == 0){\n\t\tprobCorrectWBMass = 0.000000001;\n\t}\n\tif (probIncorrectWBMass == 0){\n\t\tprobIncorrectWBMass = 0.000000001;\n\t}\n\n\tdouble NuChi2Disc =  - log(probCorrectNuChi2/probIncorrectNuChi2);\n\tdouble CSVDisc = - log((probCorrectHadB/probIncorrectHadB)*(probCorrectLepB/probIncorrectLepB));\n\tdouble MassDisc = - log(probCorrectWBMass/probIncorrectWBMass);\n\tdouble likelihoodratio = 20;\n\t// cout << \"Mass Hadronic T : \" << hadTop->mass() << \", Mass Hadronic W : \" << hadW->getFourVector().M() << endl;\n\t// cout << \"Mass Leptonic T : \" << lepTop->getFourVector().M() << \", Mass Leptonic W : \" << lepW->getFourVector().M() << endl;\n\t// cout << \"Neutrino Chi Sq : \" << NeutrinoChi2 << endl;\n\n\tif (NeutrinoChi2 >= 0.0 && Wmass <= 490 && Topmass <= 490){\n\n\n\t\tsolution->CSVDiscriminator = CSVDisc;\n\t\tsolution->MassDiscriminator = MassDisc;\n\t\tsolution->NuChi2Discriminator = NuChi2Disc;\n\n\t\tlikelihoodratio = - log(probCorrectWBMass/probIncorrectWBMass) - log(probCorrectNuChi2/probIncorrectNuChi2) - log((probCorrectHadB/probIncorrectHadB)*(probCorrectLepB/probIncorrectLepB));\n\n\t\t// if (solution->isCorrect()){\n\n\t\t// \tcout << \"Mass Hadronic T : \" << hadTop->mass() << \", Mass Hadronic W : \" << hadW->mass() << endl;\n\t\t// \tcout << \"Mass Leptonic T : \" << lepTop->mass() << \", Mass Leptonic W : \" << lepW->mass() << endl;\n\n\t\t// \tcout << \"probCorrectHadB : \" << hadBJetCSV << \" prob : \" << probCorrectHadB << endl;\n\t\t// \tcout << \"probIncorrectHadB : \" << hadBJetCSV << \" prob : \" << probIncorrectHadB << endl;\t\n\t\t// \t// cout << \"probCorrectLepB : \" << lepBJetCSV << \" prob : \" << probCorrectLepB << endl;\n\t\t// \t// cout << \"probIncorrectLepB : \" << lepBJetCSV << \" prob : \" << probIncorrectLepB << endl;\n\n\t\t// \t// cout << \"CorrectNu : \" << NeutrinoChi2 << \" prob : \" << probCorrectNuChi2 << endl;\n\t\t// \t// cout << \"IncorrectNu : \" << NeutrinoChi2 << \" prob : \" << probIncorrectNuChi2 << endl;\n\n\t\t// \t// cout << \"CorrectMassReco : \" << Wmass << \" \" << Topmass << \" prob : \" << probCorrectWBMass << endl;\n\t\t// \t// cout << \"IncorrectMassReco : \" << Wmass << \" \" << Topmass <<  \" prob : \" << probIncorrectWBMass << endl;\n\n\t\t// \tcout << \"MassDisc : \" << MassDisc << endl;\n\t\t// \tcout << \"CSVDisc : \" << CSVDisc << endl;\n\t\t// \tcout << \"NuChi2Disc : \" << NuChi2Disc << endl;\n\n\t\t// \tcout << \"Likelihood Test : \" << likelihoodratio << endl;\n\t\t// \t}\n\t}\n\n\telse{\n\t\tsolution->CSVDiscriminator = 10;\n\t\tsolution->MassDiscriminator = 10;\n\t\tsolution->NuChi2Discriminator = 10;\n\t}\nreturn likelihoodratio; \n}\n\n} /* namespace BAT */\n", "meta": {"hexsha": "bd7066d7764f6ed126bb7eecfebfbda736f92678", "size": 9222, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ReconstructionModules/LikelihoodBasedTopPairReconstruction.cpp", "max_stars_repo_name": "kreczko/AnalysisSoftware", "max_stars_repo_head_hexsha": "fa83a3775a8d644e6098d28dbc6f3d7f1a11b400", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ReconstructionModules/LikelihoodBasedTopPairReconstruction.cpp", "max_issues_repo_name": "kreczko/AnalysisSoftware", "max_issues_repo_head_hexsha": "fa83a3775a8d644e6098d28dbc6f3d7f1a11b400", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ReconstructionModules/LikelihoodBasedTopPairReconstruction.cpp", "max_forks_repo_name": "kreczko/AnalysisSoftware", "max_forks_repo_head_hexsha": "fa83a3775a8d644e6098d28dbc6f3d7f1a11b400", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.888, "max_line_length": 189, "alphanum_fraction": 0.7109086966, "num_tokens": 2688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.23173994123009906}}
{"text": "#include <iostream>\n#include <Eigen/Dense>\n\nusing Eigen::MatrixXd;\nusing namespace std;\n\nint main()\n{\n\tMatrixXd R(3,3);\n\tR << 1, 0, 0,\n\t\t 0, 0, -1,\n\t\t 0, 1, 0;\n\tcout << R;\t\n}\n", "meta": {"hexsha": "f1d4d611ca0ec3a809b54f00a2f54b318762139b", "size": 175, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Cpp/rotation/rotation.cpp", "max_stars_repo_name": "silvajhonatan/robotics", "max_stars_repo_head_hexsha": "d1097809e88c744658dab6d661092b6ea8f0e13a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-11-16T18:34:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-28T15:33:46.000Z", "max_issues_repo_path": "Cpp/rotation/rotation.cpp", "max_issues_repo_name": "sjhonatan/robotics", "max_issues_repo_head_hexsha": "d1097809e88c744658dab6d661092b6ea8f0e13a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cpp/rotation/rotation.cpp", "max_forks_repo_name": "sjhonatan/robotics", "max_forks_repo_head_hexsha": "d1097809e88c744658dab6d661092b6ea8f0e13a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 11.6666666667, "max_line_length": 22, "alphanum_fraction": 0.5714285714, "num_tokens": 68, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.23173571651452574}}
{"text": "#pragma once\n\n#include <Eigen/Core>\n#include <cassert>\n#include <vector>\n\n\nnamespace boltzmann {\n// homogeneous\nnamespace hg {\ntemplate <typename NUMERIC_T = double>\nclass RK4\n{\n public:\n  typedef NUMERIC_T numeric_t;\n\n private:\n  typedef Eigen::VectorXd vec_t;\n\n public:\n  RK4(int N_)\n      : N(N_)\n      , v_k1(N_)\n      , v_k2(N_)\n      , v_k3(N_)\n      , v_k4(N_)\n  { /* empty */\n  }\n\n  void apply(NUMERIC_T* dst,\n             const NUMERIC_T* src,\n             const std::function<void(NUMERIC_T* dst, const NUMERIC_T* src)>& f,\n             double dt);\n\n private:\n  int N;\n  vec_t v_k1;\n  vec_t v_k2;\n  vec_t v_k3;\n  vec_t v_k4;\n};\n\n// ----------------------------------------------------------------------\ntemplate <typename NUMERIC_T>\nvoid\nRK4<NUMERIC_T>::apply(NUMERIC_T* dst,\n                      const NUMERIC_T* src,\n                      const std::function<void(NUMERIC_T* dst, const NUMERIC_T* src)>& f,\n                      double dt)\n{\n  assert(src != dst);\n\n  typedef Eigen::Map<vec_t> map_vec_t;\n  typedef Eigen::Map<const vec_t> map_const_vec_t;\n\n  map_const_vec_t v_in(src, N);\n  map_vec_t v_dst(dst, N);\n\n  f(v_k1.data(), v_in.data());\n\n  v_dst = v_in + 0.5 * dt * v_k1;\n  f(v_k2.data(), v_dst.data());\n\n  v_dst = v_in + 0.5 * dt * v_k2;\n  f(v_k3.data(), v_dst.data());\n\n  v_dst = v_in + dt * v_k3;\n  f(v_k4.data(), v_dst.data());\n\n  v_dst = v_in + dt / 6 * (v_k1 + 2 * v_k2 + 2 * v_k3 + v_k4);\n}\n\n}  // end hg\n}  // end boltzmann\n", "meta": {"hexsha": "ca76aebf513396fdb1ec4b06b81e38ee511e36b4", "size": 1455, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/collision_tensor/time_stepping/rk4.hpp", "max_stars_repo_name": "simonpp/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/collision_tensor/time_stepping/rk4.hpp", "max_issues_repo_name": "simonpp/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/collision_tensor/time_stepping/rk4.hpp", "max_forks_repo_name": "simonpp/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.4, "max_line_length": 89, "alphanum_fraction": 0.55395189, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2317157923092633}}
{"text": "/*\n *  VSCSoundParameters.cpp\n *  SynthStation\n *\n *  Created by Jonathan Thorpe on 12/11/2011.\n *  Copyright 2011 NXP. All rights reserved.\n *\n */\n\n#include \"VSCSoundParameters.h\"\n#include \"VSCException.h\"\n#include \"VSCMath.h\"\n\n#include <map>\n#include <string>\n#include <boost/lexical_cast.hpp>\n\nconst unsigned int VSCSParameter::kChannelNotFound = kVSCSVoidChannel;\nconst unsigned int VSCSParameter::kIndexAll = UINT_MAX;\n\n\nbool VSCSParameter::Key::operator<(const Key& otherKey) const {\n\tif (domain < otherKey.domain) return true;\n\telse return false;\n\tif (code < otherKey.code) return true;\n\telse return false;\n\tif (index < otherKey.index) return true;\n\treturn false;\n}\n\nbool VSCSParameter::Key::operator==(const Key& otherKey) const {\n\tif (domain != otherKey.domain) return false;\n\tif (code != otherKey.code) return false;\n\tif (index != otherKey.index) return false;\n\treturn true;\n}\n\nVSCSParameter::VSCSParameter() {\n\t\n}\n\nVSCSParameter::~VSCSParameter() {\n\t\n}\n\nVSCSParameter& VSCSParameter::sharedInstance(void) {\n\tstatic VSCSParameter singletonInstance;\n\treturn singletonInstance;\n}\n\n/*\n *\tThis should convert so that linear volume gain [0 : 1] becomes [-infinity : 0]\n */\nVSCSFloat VSCSParameter::linearToDB(VSCSFloat linear) {\n\tVSCSFloat dB = 10.0*std::log10(linear);\n    return  dB;\n}\n\nVSCSFloat VSCSParameter::dBToLinear(VSCSFloat dB) {\n    return std::pow(10.0, 0.1*dB);\n}\n\n\n/*\n *\tParameter labels\n */\nstd::string VSCSParameter::getLabelForParameterWithKey(VSCSParameter::Key k) {\n\t\n\t/*\n\t *\tCheck if there are exact matches\n\t */\n\tKeyLabelMap::iterator labelIterator = customizedKeyLabels.find(k);\n\tif (labelIterator != customizedKeyLabels.end()) \n\t\treturn labelIterator->second;\n\t\n\tswitch (k.code) {\n\t\tcase CodeGain:\n\t\t\treturn \"Gain (Lin)\";\n\t\tcase CodeDBGain:\n\t\t\treturn \"Gain (dB)\";\n\t\tcase CodeFrequency:\n\t\t\treturn \"Freq (Hz)\";\n\t\tcase CodeLogFrequency:\n\t\t\treturn \"Freq (Log Hz)\";\n//\t\tcase CodeDegPhase:\n//\t\t\treturn \"Phase (deg)\";\n\t\tcase CodeRadPhase:\n\t\t\treturn \"Phase (rad)\";\n\t\tcase CodeHarmonics:\n\t\t\treturn \"Harmonics\";\n\t\tdefault:\n\t\t\treturn \"\";\n\t\t\tbreak;\n\t}\n\t\n\tthrow VSCSBadParameterException();\n\t\n}\n\nvoid VSCSParameter::setLabelForParameterWithKey(std::string label, Key k) {\n\t\n\tKeyLabelMap::iterator labelIterator = customizedKeyLabels.find(k);\n\tif (labelIterator != customizedKeyLabels.end()) \n\t\tcustomizedKeyLabels.erase(k);\n\t\n\tcustomizedKeyLabels.insert(KeyLabelPair (k, label));\n\t\n}\n\nvoid VSCSParameter::revertLabelForParameterWithKeyToDefault(Key k) {\n\t\n\tKeyLabelMap::iterator labelIterator = customizedKeyLabels.find(k);\n\tif (labelIterator != customizedKeyLabels.end()) \n\t\tcustomizedKeyLabels.erase(k);\n\t\n}\n\n\nVSCSParameter::ValueRange VSCSParameter::getRangeForParameterWithKey(Key k) {\n\t\n\tKeyRangeMap::iterator rangeIterator = customizedKeyRanges.find(k);\n\tif (rangeIterator != customizedKeyRanges.end()) \n\t\treturn rangeIterator->second;\n\t\n\tswitch (k.code) {\n\t\tcase CodeGain:\n\t\t\treturn ValueRange (0.0, 1.0);\n\t\tcase CodeDBGain:\n\t\t\treturn ValueRange (-30.0, 0.0);\n\t\tcase CodeFrequency:\n\t\t\treturn ValueRange (20.0, 20000.0);\n\t\tcase CodeLogFrequency:\n\t\t\treturn ValueRange (std::log10(20.0), std::log10(20000.0));\n//\t\tcase CodeDegPhase:\n//\t\t\treturn ValueRange (-180.0, 180.0);\n\t\tcase CodeRadPhase:\n\t\t\treturn ValueRange (-vsc::kPI, vsc::kPI);\n\t\tcase CodeHarmonics:\n\t\t\treturn ValueRange (0.0, 10.0);\n\t\tdefault:\n\t\t\treturn ValueRange (0.0, 0.0);\n\t\t\tbreak;\n\t}\n\t\n\tthrow VSCSBadParameterException();\n\t\n}\n\nvoid VSCSParameter::setRangeForParameterWithKey(ValueRange valRange, Key k) {\n\t\n\tKeyRangeMap::iterator rangeIterator = customizedKeyRanges.find(k);\n\tif (rangeIterator != customizedKeyRanges.end()) \n\t\tcustomizedKeyRanges.erase(k);\n\t\n\tcustomizedKeyRanges.insert(KeyRangePair (k, valRange));\n\t\n}\n\nvoid VSCSParameter::revertRangeForParameterWithKeyToDefault(Key k) {\n\t\n\tKeyRangeMap::iterator rangeIterator = customizedKeyRanges.find(k);\n\tif (rangeIterator != customizedKeyRanges.end()) \n\t\tcustomizedKeyRanges.erase(k);\n\t\n}\n\n", "meta": {"hexsha": "09ecf608510fe5d6286fe7fa0110a9e54eea5300", "size": 3934, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sound/Params/VSCSoundParameters.cpp", "max_stars_repo_name": "jbat100/VirtualSoundControl", "max_stars_repo_head_hexsha": "f84ba15bba4bfce579c185e04df0e1be4f419cd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sound/Params/VSCSoundParameters.cpp", "max_issues_repo_name": "jbat100/VirtualSoundControl", "max_issues_repo_head_hexsha": "f84ba15bba4bfce579c185e04df0e1be4f419cd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sound/Params/VSCSoundParameters.cpp", "max_forks_repo_name": "jbat100/VirtualSoundControl", "max_forks_repo_head_hexsha": "f84ba15bba4bfce579c185e04df0e1be4f419cd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5568862275, "max_line_length": 81, "alphanum_fraction": 0.7262328419, "num_tokens": 1101, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2317157923092633}}
{"text": "#include <iostream>\n#include <iterator>\n#include <sstream>\n#include <iomanip>\n#include <map>\n\n#include <boost/program_options.hpp>\n#include <boost/log/sources/logger.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/serialization/map.hpp>\n#include <boost/mpi.hpp>\n\n#include <benchmark.hpp>\n#include <logging.hpp>\n\n#include <constants.hpp>\n#include <lapack.hpp>\n#include <matrix_serialization.hpp>\n#include <dielectric_function_v2.hpp>\n\n\nnamespace po  = boost::program_options;\nnamespace mpi = boost::mpi;\n\n\nusing R = double;\n\n#ifdef ASSUME_REAL\nusing C = R;\n#else\nusing C = std::complex<R>;\n#endif\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Returns the rank of the admin process.\n///////////////////////////////////////////////////////////////////////////////\nconstexpr auto admin_rank() -> int { return 0; }\n\n\n\n// ============================================================================\n//                                   SETTINGS                                  \n// ============================================================================\n\n///////////////////////////////////////////////////////////////////////////////\n/// \\brief Class representing the configurations options.\n\n/// It is a small wrapper around boost::program_options, which read the\n/// options from command line during construction.\n///////////////////////////////////////////////////////////////////////////////\n\n\nauto init_options() -> po::options_description\n{\n\tpo::options_description description;\n\tdescription.add_options()\n\t\t( \"help\", \"Produce the help message.\" )\n\t\t( \"out.file.log\" \n\t\t, po::value<std::string>()->default_value(\"sample\")\n\t\t, \"Name of the file that will be used for logging. This is \"\n\t\t  \"not the full name, but rather a 'base'. The actual file name \"\n\t\t  \"will be \\\"[log-file].[PROCESS_RANK].log\\\".\" )\n\t\t( \"out.file.eps\" \n\t\t, po::value<std::string>()->default_value(\"Epsilon\")\n\t\t, \"Name of the file that will be used for saving the computed \"\n\t\t  \"dielectric functions. This is, again, a base rather than the \"\n\t\t  \"actual name. The actual file name will be \"\n\t\t  \"\\\"[eps-file].[PROCESS_RANK].bin\\\", which indicates that \"\n\t\t  \"dielectric functions will be stored in binary format of the \"\n\t\t  \"boost::serialization library.\" )\n\t\t( \"in.file.energies\"\n\t\t, po::value<std::string>()->required()\n\t\t, \"Name of the BIN file where the eigenenergies of the hamiltonian\"\n\t\t  \" are read from. This file must be in the format of the \"\n\t\t  \"boost::serialization library. This option is REQUIRED.\" )\n\t\t( \"in.file.states\"\n\t\t, po::value<std::string>()->required()\n\t\t, \"Name of the BIN file where the eigenstates of the hamiltonian \"\n\t\t  \"are read from. This file must be in the format of the \"\n\t\t  \"boost::serialization library. This option is REQUIRED.\" )\n\t\t( \"in.file.potential\"\n\t\t, po::value<std::string>()->required()\n\t\t, \"Name of the BIN file where the interaction potential \"\n\t\t  \"is read from. This file must be in the format of the \"\n\t\t  \"boost::serialization library. This option is REQUIRED.\" )\n\t\t( \"in.frequency.start\"\n\t\t, po::value<R>()->required()\n\t\t, \"Starting frequency in eV. Must be a real value. This option \"\n\t\t  \"is REQUIRED.\" )\n\t\t( \"in.frequency.stop\"\n\t\t, po::value<R>()->required()\n\t\t, \"Stopping frequency in eV. Must be a real value. This option \"\n\t\t  \"is REQUIRED.\" )\n\t\t( \"in.frequency.step\"\n\t\t, po::value<R>()->required()\n\t\t, \"Step in frequency in eV. Must be a real value.\" );\n\tdescription.add(tcm::init_constants_options<double>());\n\treturn description;\n}\n\n\n\n\ntemplate <class _Help, class _Proceed>\nauto parse_command_line( int argc, char** argv\n                       , _Help&& help\n                       , _Proceed&& proceed ) -> bool\n{\n\tauto const desc = init_options();\n\tpo::variables_map vm;\n\n\tpo::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n\n\tif (vm.count(\"help\")) {\n\t\thelp(desc);\n\t\treturn false;\n\t}\n\n\tpo::notify(vm);\n\tproceed(vm);\n\treturn true;\n}\n\n\nauto log_file_name(int const rank, std::string file_name_base)\n{\n\treturn file_name_base + \".\" + std::to_string(rank) + \".log\";\t\n}\n\n\nauto initialize_logging( int const rank\n                       , std::string const& file_name_base) -> void\n{\n\tusing namespace boost::log;\n\tregister_simple_formatter_factory<tcm::severity_level, char>(\"Severity\");\n\tadd_file_log\n\t( \n\t\tkeywords::file_name = log_file_name(rank, file_name_base),\n\t\tkeywords::format = \"%LineID%: [%TimeStamp%] [%Severity%] %Message%\",\n\t\tkeywords::auto_flush = true\n\t);\n\n\tadd_common_attributes();\n}\n\n\ntemplate <class _R, class _C>\nstruct IPackage {\n\tstd::tuple<_R, _R, _R>                frequency_range;\n\tstd::string                           log_file_name_base;\n\tstd::string                           eps_file_name_base;\n\ttcm::Matrix<_R>                       E;\n\ttcm::Matrix<_C>                       Psi;\n\ttcm::Matrix<std::complex<_R>>         V;\n\tstd::map<std::string, _R>             constants;\n\nprivate:\n\tfriend boost::serialization::access;\n\n\ttemplate<class _Archive>\n\tauto save(_Archive & ar, unsigned int const version) const -> void\n\t{\n\t\tar << std::get<0>(frequency_range)\n\t\t   << std::get<1>(frequency_range)\n\t\t   << std::get<2>(frequency_range)\n\t\t   << log_file_name_base\n\t\t   << eps_file_name_base\n\t\t   << E \n\t\t   << Psi\n\t\t   << V\n\t\t   << constants;\n\t}\n\n\ttemplate<class _Archive>\n\tauto load(_Archive & ar, unsigned int const version) -> void\n\t{\n\t\tar >> std::get<0>(frequency_range)\n\t\t   >> std::get<1>(frequency_range)\n\t\t   >> std::get<2>(frequency_range)\n\t\t   >> log_file_name_base\n\t\t   >> eps_file_name_base\n\t\t   >> E \n\t\t   >> Psi\n\t\t   >> V\n\t\t   >> constants;\n\t}\n\n\tBOOST_SERIALIZATION_SPLIT_MEMBER()\n};\n\n\ntemplate<class _T>\nauto load_matrix(std::string const& file_name) -> tcm::Matrix<_T>\n{\n\tstd::ifstream in_stream{file_name};\n\tif(not in_stream)\n\t\tthrow std::runtime_error{\"Failed to open `\" + file_name + \"`.\"};\n\tboost::archive::binary_iarchive in_archive{in_stream};\n\n\ttcm::Matrix<_T> A;\n\tin_archive >> A;\n\treturn A;\n}\n\n\n\n\nauto load_ipackage(po::variables_map const& vm) -> IPackage<R, C>\n{\n\treturn { std::make_tuple( vm[\"in.frequency.start\"].as<R>()\n\t                        , vm[\"in.frequency.stop\"].as<R>()\n\t                        , vm[\"in.frequency.step\"].as<R>() )\n\t       , vm[\"out.file.log\"].as<std::string>()\n\t       , vm[\"out.file.eps\"].as<std::string>()\n\t       , load_matrix<R>(vm[\"in.file.energies\"].as<std::string>())\n\t       , load_matrix<C>(vm[\"in.file.states\"].as<std::string>())\n\t       , load_matrix<std::complex<R>>(vm[\"in.file.potential\"].as<std::string>())\n\t\t   , tcm::load_constants<R, double, std::map<std::string, R>>(vm)\n\t\t   };\n}\n\n\ntemplate <class _T, class _Logger>\nauto cache( std::string const& message\n          , tcm::Matrix<_T> const& X\n\t\t  , std::string const& file_name\n          , _Logger & lg ) -> void\n{\n\tLOG(lg, info) << \"Caching: \" << message << \"...\";\n\n\tstd::ofstream out_stream{file_name};\n\tif(not out_stream)\n\t\tthrow std::runtime_error{\"Could not open `\" + file_name + \"`.\"};\n\tboost::archive::binary_oarchive out_archive{out_stream};\n\tout_archive << X;\n\n\tLOG(lg, info) << \"Caching successfully finished.\";\n}\n\n\ntemplate<class _Real, class _Logger>\nauto get_job( mpi::communicator const& world\n            , std::tuple<_Real, _Real, _Real> const& range\n\t\t\t, _Logger & lg ) -> std::vector<_Real>\n{\t\n\tLOG(lg, info) << \"Calculating homework...\";\n\n\tauto const  rank  = world.rank();\n\tauto const  size  = world.size();\n\tauto const& begin = std::get<0>(range);\n\tauto const& end   = std::get<1>(range);\n\tauto const& step  = std::get<2>(range);\n\n\tstd::vector<_Real> homework;\n\tfor(auto i = 0; begin + i * step <= end; ++i) {\n\t\tif(i % size == rank) \n\t\t\thomework.push_back(begin + i * step);\n\t}\n\t\n\tauto record = lg.open_record(boost::log::keywords::severity = \n\t                                 tcm::severity_level::info);\n\tif (record) {\n\t\tboost::log::record_ostream stream{record};\n\t\tstream << \"Need to perform calculations for the following \"\n\t\t\t   << \"frequencies: {\";\n\t\tif(not homework.empty()) {\n\t\t\tfor(std::size_t i = 0; i < homework.size() - 1; ++i)\n\t\t\t\tstream << homework[i] << \", \";\n\t\t\tstream << homework.back();\n\t\t}\n\t\tstream << \"}\";\n\t\tstream.flush();\n\t\tlg.push_record(std::move(record));\n\t}\n\t\n\treturn homework;\n}\n\n\ntemplate<class _Number, class _R, class _C, class _Logger>\nauto calculate_single( _Number const omega\n                     , tcm::Matrix<_R> const& E\n\t\t\t\t\t , tcm::Matrix<_C> const& Psi\n\t\t\t\t\t , tcm::Matrix<std::complex<_R>> const& V\n\t\t\t\t\t , std::map<std::string, _R> const& cs\n                     , _Logger & lg \n\t\t\t\t\t , std::string const& file_name_base ) -> void\n{\n\tusing namespace std::complex_literals;\n\tLOG(lg, info) << \"Calculating dielectric function for omega = \"\n\t              << omega << \"...\";\n\n\tauto const file_name_matrix = \n\t\tfile_name_base + \".\" + std::to_string(std::real(omega)) \n\t\t+ \".matrix.bin\";\n\tauto const file_name_eigenvalues = \n\t\tfile_name_base + \".\" + std::to_string(std::real(omega)) \n\t\t+ \".eigenvalues.bin\";\n\tauto const file_name_eigenstates = \n\t\tfile_name_base + \".\" + std::to_string(std::real(omega)) \n\t\t+ \".eigenstates.bin\";\n\n\tauto epsilon = tcm::dielectric_function::make(omega, E, Psi, V, cs, lg);\n\tcache(\"Dielectric function matrix\", epsilon, file_name_matrix, lg);\n\n\tLOG(lg, info) << \"Diagonalizing dielectric function for omega = \"\n\t              << omega << \"...\";\n\n\tusing epsilon_type = typename decltype(epsilon)::value_type;\n\ttcm::Matrix<epsilon_type> W{epsilon.height(), 1};\n\ttcm::Matrix<epsilon_type> Z{epsilon.height(), epsilon.height()};\n\ttcm::lapack::geev(epsilon, W, Z);\n\n\tcache(\"Dielectric function eigenvalues\", W, file_name_eigenvalues, lg);\n\tcache(\"Dielectric function eigenstates\", Z, file_name_eigenstates, lg);\n\n\tLOG(lg, info) << \"Done for omega = \" << omega << \"!\";\n}\n\n\n\nauto run( mpi::communicator & world\n        , IPackage<R, C> & input ) -> void\n{\n\tmpi::broadcast(world, input, admin_rank());\n\n\tinitialize_logging(world.rank(), input.log_file_name_base);\n\tboost::log::sources::severity_logger<tcm::severity_level> lg;\n\n\tauto const homework = get_job<R>(world, input.frequency_range, lg);\n\tif (homework.empty()) \n\t\treturn;\n\tfor(auto const& w : homework) {\n\t\tcalculate_single( std::complex<R>{w, input.constants.at(\"tau\")}\n\t\t                , input.E\n\t\t\t\t\t\t, input.Psi\n\t\t\t\t\t\t, input.V\n\t\t\t\t\t\t, input.constants\n\t\t\t\t\t\t, lg\n\t\t\t\t\t\t, input.eps_file_name_base );\n\t}\n\n\tauto record = lg.open_record(boost::log::keywords::severity = \n\t                                 tcm::severity_level::info);\n\tif (record) {\n\t\tboost::log::record_ostream stream{record};\n\t\tstream << \"Timings:\\n\";\n\t\ttcm::timing::report(stream);\n\t\tstream.flush();\n\t\tlg.push_record(std::move(record));\n\t}\n}\n\n\n\n\n\n\nint main(int argc, char** argv)\n{\n\tmpi::environment env;\n\tmpi::communicator world;\n\n\tIPackage<R, C> input;\n\tbool proceed_with_calculation;\n\tif (world.rank() == admin_rank()) {\n\t\tproceed_with_calculation = \n\t\t\tparse_command_line( argc, argv\n\t\t\t                  , [&env] (auto _desc) { std::cout << _desc << '\\n'; }\n\t\t\t                  , [&input] (auto _vm) { input = load_ipackage(_vm); } );\n\t}\n\t\n\tmpi::broadcast(world, proceed_with_calculation, admin_rank());\n\tif(not proceed_with_calculation)\n\t\treturn EXIT_SUCCESS;\n\t\n\trun(world, input);\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "e764482d24bbfcbcb7729593fa48114a09bb3fb1", "size": 11238, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/hello.cpp", "max_stars_repo_name": "twesterhout/plasmon-cpp", "max_stars_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T11:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T11:12:07.000Z", "max_issues_repo_path": "src/hello.cpp", "max_issues_repo_name": "twesterhout/plasmon-cpp", "max_issues_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/hello.cpp", "max_forks_repo_name": "twesterhout/plasmon-cpp", "max_forks_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4188481675, "max_line_length": 81, "alphanum_fraction": 0.607225485, "num_tokens": 2826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.23165309545076215}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <ored/model/crcirbuilder.hpp>\n#include <ored/model/crlgmbuilder.hpp>\n#include <ored/model/crossassetmodelbuilder.hpp>\n#include <ored/model/eqbsbuilder.hpp>\n#include <ored/model/fxbsbuilder.hpp>\n#include <ored/model/inflation/infdkbuilder.hpp>\n#include <ored/model/inflation/infjybuilder.hpp>\n#include <ored/model/inflation/infjydata.hpp>\n#include <ored/model/lgmbuilder.hpp>\n#include <ored/model/structuredmodelerror.hpp>\n#include <ored/model/utilities.hpp>\n#include <ored/utilities/correlationmatrix.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/parsers.hpp>\n\n#include <qle/cashflows/jyyoyinflationcouponpricer.hpp>\n#include <qle/models/cpicapfloorhelper.hpp>\n#include <qle/models/fxbsconstantparametrization.hpp>\n#include <qle/models/fxbspiecewiseconstantparametrization.hpp>\n#include <qle/models/fxeqoptionhelper.hpp>\n#include <qle/models/irlgm1fconstantparametrization.hpp>\n#include <qle/models/irlgm1fpiecewiseconstanthullwhiteadaptor.hpp>\n#include <qle/models/irlgm1fpiecewiseconstantparametrization.hpp>\n#include <qle/models/irlgm1fpiecewiselinearparametrization.hpp>\n#include <qle/models/yoycapfloorhelper.hpp>\n#include <qle/models/yoyswaphelper.hpp>\n#include <qle/pricingengines/analyticcclgmfxoptionengine.hpp>\n#include <qle/pricingengines/analyticdkcpicapfloorengine.hpp>\n#include <qle/pricingengines/analyticjycpicapfloorengine.hpp>\n#include <qle/pricingengines/analyticjyyoycapfloorengine.hpp>\n#include <qle/pricingengines/analyticlgmswaptionengine.hpp>\n#include <qle/pricingengines/analyticxassetlgmeqoptionengine.hpp>\n\n#include <ql/math/optimization/levenbergmarquardt.hpp>\n#include <ql/models/shortrate/calibrationhelpers/swaptionhelper.hpp>\n#include <ql/pricingengines/swap/discountingswapengine.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/utilities/dataformatters.hpp>\n\n#include <boost/algorithm/string/case_conv.hpp>\n#include <boost/lexical_cast.hpp>\n\nusing QuantExt::AnalyticJyCpiCapFloorEngine;\nusing QuantExt::AnalyticJyYoYCapFloorEngine;\nusing QuantExt::CpiCapFloorHelper;\nusing QuantExt::InfDkParametrization;\nusing QuantExt::IrLgm1fParametrization;\nusing QuantExt::JyYoYInflationCouponPricer;\nusing QuantExt::YoYCapFloorHelper;\nusing QuantExt::YoYSwapHelper;\nusing QuantLib::DiscountingSwapEngine;\nusing std::vector;\n\nnamespace ore {\nnamespace data {\n\nCrossAssetModelBuilder::CrossAssetModelBuilder(\n    const boost::shared_ptr<ore::data::Market>& market, const boost::shared_ptr<CrossAssetModelData>& config,\n    const std::string& configurationLgmCalibration, const std::string& configurationFxCalibration,\n    const std::string& configurationEqCalibration, const std::string& configurationInfCalibration,\n    const std::string& configurationCrCalibration, const std::string& configurationFinalModel,\n    const DayCounter& dayCounter, const bool dontCalibrate, const bool continueOnError,\n    const std::string& referenceCalibrationGrid)\n    : market_(market), config_(config), configurationLgmCalibration_(configurationLgmCalibration),\n      configurationFxCalibration_(configurationFxCalibration), configurationEqCalibration_(configurationEqCalibration),\n      configurationInfCalibration_(configurationInfCalibration),\n      configurationCrCalibration_(configurationCrCalibration), configurationFinalModel_(configurationFinalModel),\n      dayCounter_(dayCounter), dontCalibrate_(dontCalibrate), continueOnError_(continueOnError),\n      referenceCalibrationGrid_(referenceCalibrationGrid),\n      optimizationMethod_(boost::shared_ptr<OptimizationMethod>(new LevenbergMarquardt(1E-8, 1E-8, 1E-8))),\n      endCriteria_(EndCriteria(1000, 500, 1E-8, 1E-8, 1E-8)) {\n    buildModel();\n    registerWithSubBuilders();\n    // register market observer with correlations\n    marketObserver_ = boost::make_shared<MarketObserver>();\n    for (auto const& c : config->correlations())\n        marketObserver_->addObservable(c.second);\n    // reset market observer's updated flag\n    marketObserver_->hasUpdated(true);\n}\n\nHandle<QuantExt::CrossAssetModel> CrossAssetModelBuilder::model() const {\n    calculate();\n    return model_;\n}\n\nconst std::vector<Real>& CrossAssetModelBuilder::swaptionCalibrationErrors() {\n    calculate();\n    return swaptionCalibrationErrors_;\n}\nconst std::vector<Real>& CrossAssetModelBuilder::fxOptionCalibrationErrors() {\n    calculate();\n    return fxOptionCalibrationErrors_;\n}\nconst std::vector<Real>& CrossAssetModelBuilder::eqOptionCalibrationErrors() {\n    calculate();\n    return eqOptionCalibrationErrors_;\n}\nconst std::vector<Real>& CrossAssetModelBuilder::inflationCalibrationErrors() {\n    calculate();\n    return inflationCalibrationErrors_;\n}\n\nvoid CrossAssetModelBuilder::unregisterWithSubBuilders() {\n    for (auto okv : subBuilders_)\n        for (auto ikv : okv.second)\n            unregisterWith(ikv.second);\n}\n\nvoid CrossAssetModelBuilder::registerWithSubBuilders() {\n    for (auto okv : subBuilders_)\n        for (auto ikv : okv.second)\n            registerWith(ikv.second);\n}\n\nbool CrossAssetModelBuilder::requiresRecalibration() const {\n    for (auto okv : subBuilders_)\n        for (auto ikv : okv.second)\n            if (ikv.second->requiresRecalibration())\n                return true;\n\n    return marketObserver_->hasUpdated(false);\n}\n\nvoid CrossAssetModelBuilder::performCalculations() const {\n    // if any of the sub models requires a recalibration, we rebuilt the model\n    // TODO we could do this more selectively\n    if (!dontCalibrate_ && requiresRecalibration()) {\n        // reset market observer update flag\n        marketObserver_->hasUpdated(true);\n        // the cast is a bit ugly, but we pretty much know what we are doing here\n        const_cast<CrossAssetModelBuilder*>(this)->unregisterWithSubBuilders();\n        buildModel();\n        const_cast<CrossAssetModelBuilder*>(this)->registerWithSubBuilders();\n    }\n}\n\nvoid CrossAssetModelBuilder::buildModel() const {\n\n    QL_REQUIRE(market_ != NULL, \"CrossAssetModelBuilder: no market given\");\n    LOG(\"Start building CrossAssetModel\");\n    DLOG(\"configurations: LgmCalibration \"\n         << configurationLgmCalibration_ << \", FxCalibration \" << configurationFxCalibration_ << \", EqCalibration \"\n         << configurationEqCalibration_ << \", InfCalibration \" << configurationInfCalibration_ << \", CrCalibration\"\n         << configurationCrCalibration_ << \", FinalModel \" << configurationFinalModel_);\n    if (dontCalibrate_) {\n        DLOG(\"Calibration of the model is disabled.\");\n    }\n\n    QL_REQUIRE(config_->irConfigs().size() > 0, \"missing IR configurations\");\n    QL_REQUIRE(config_->irConfigs().size() == config_->fxConfigs().size() + 1,\n               \"FX configuration size \" << config_->fxConfigs().size() << \" inconsisitent with IR configuration size \"\n                                        << config_->irConfigs().size());\n\n    swaptionBaskets_.resize(config_->irConfigs().size());\n    optionExpiries_.resize(config_->irConfigs().size());\n    swaptionMaturities_.resize(config_->irConfigs().size());\n    swaptionCalibrationErrors_.resize(config_->irConfigs().size());\n    fxOptionBaskets_.resize(config_->fxConfigs().size());\n    fxOptionExpiries_.resize(config_->fxConfigs().size());\n    fxOptionCalibrationErrors_.resize(config_->fxConfigs().size());\n    eqOptionBaskets_.resize(config_->eqConfigs().size());\n    eqOptionExpiries_.resize(config_->eqConfigs().size());\n    eqOptionCalibrationErrors_.resize(config_->eqConfigs().size());\n    inflationCalibrationErrors_.resize(config_->infConfigs().size());\n\n    subBuilders_.clear();\n\n    // Store information on the number of factors for each process. This is used when requesting a correlation matrix\n    // from the CorrelationMatrixBuilder below.\n    using ProcessInfo = CorrelationMatrixBuilder::ProcessInfo;\n    namespace CT = QuantExt::CrossAssetModelTypes;\n    ProcessInfo processInfo;\n\n    /*******************************************************\n     * Build the IR parametrizations and calibration baskets\n     */\n    std::vector<boost::shared_ptr<QuantExt::IrLgm1fParametrization>> irParametrizations;\n    std::vector<RelinkableHandle<YieldTermStructure>> irDiscountCurves;\n    std::vector<std::string> currencies, regions, crNames, eqNames, infIndices;\n    std::vector<boost::shared_ptr<LgmBuilder>> irBuilder;\n\n    for (Size i = 0; i < config_->irConfigs().size(); i++) {\n        boost::shared_ptr<IrLgmData> ir = config_->irConfigs()[i];\n        DLOG(\"IR Parametrization \" << i << \" ccy \" << ir->ccy());\n        boost::shared_ptr<LgmBuilder> builder =\n            boost::make_shared<LgmBuilder>(market_, ir, configurationLgmCalibration_, config_->bootstrapTolerance(),\n                                           continueOnError_, referenceCalibrationGrid_);\n        if (dontCalibrate_)\n            builder->freeze();\n        irBuilder.push_back(builder);\n        boost::shared_ptr<QuantExt::IrLgm1fParametrization> parametrization = builder->parametrization();\n        swaptionBaskets_[i] = builder->swaptionBasket();\n        currencies.push_back(ir->ccy());\n        irParametrizations.push_back(parametrization);\n        irDiscountCurves.push_back(builder->discountCurve());\n        subBuilders_[CT::IR][i] = builder;\n        processInfo[CT::IR].emplace_back(ir->ccy(), 1);\n    }\n\n    QL_REQUIRE(irParametrizations.size() > 0, \"missing IR parametrizations\");\n\n    QuantLib::Currency domesticCcy = irParametrizations[0]->currency();\n\n    /*******************************************************\n     * Build the FX parametrizations and calibration baskets\n     */\n    std::vector<boost::shared_ptr<QuantExt::FxBsParametrization>> fxParametrizations;\n    for (Size i = 0; i < config_->fxConfigs().size(); i++) {\n        DLOG(\"FX Parametrization \" << i);\n        boost::shared_ptr<FxBsData> fx = config_->fxConfigs()[i];\n        QuantLib::Currency ccy = ore::data::parseCurrency(fx->foreignCcy());\n        QuantLib::Currency domCcy = ore::data::parseCurrency(fx->domesticCcy());\n\n        QL_REQUIRE(ccy.code() == irParametrizations[i + 1]->currency().code(),\n                   \"FX parametrization currency[\" << i << \"]=\" << ccy << \" does not match IR currrency[\" << i + 1\n                                                  << \"]=\" << irParametrizations[i + 1]->currency().code());\n\n        QL_REQUIRE(domCcy == domesticCcy, \"FX parametrization [\" << i << \"]=\" << ccy << \"/\" << domCcy\n                                                                 << \" does not match domestic ccy \" << domesticCcy);\n\n        boost::shared_ptr<FxBsBuilder> builder =\n            boost::make_shared<FxBsBuilder>(market_, fx, configurationFxCalibration_, referenceCalibrationGrid_);\n        boost::shared_ptr<QuantExt::FxBsParametrization> parametrization = builder->parametrization();\n\n        fxOptionBaskets_[i] = builder->optionBasket();\n        fxParametrizations.push_back(parametrization);\n        subBuilders_[CT::FX][i] = builder;\n        processInfo[CT::FX].emplace_back(ccy.code() + domCcy.code(), 1);\n    }\n\n    /*******************************************************\n     * Build the EQ parametrizations and calibration baskets\n     */\n    std::vector<boost::shared_ptr<QuantExt::EqBsParametrization>> eqParametrizations;\n    for (Size i = 0; i < config_->eqConfigs().size(); i++) {\n        DLOG(\"EQ Parametrization \" << i);\n        boost::shared_ptr<EqBsData> eq = config_->eqConfigs()[i];\n        string eqName = eq->eqName();\n        QuantLib::Currency eqCcy = ore::data::parseCurrency(eq->currency());\n        QL_REQUIRE(std::find(currencies.begin(), currencies.end(), eqCcy.code()) != currencies.end(),\n                   \"Currency (\" << eqCcy << \") for equity \" << eqName << \" not covered by CrossAssetModelData\");\n        boost::shared_ptr<EqBsBuilder> builder = boost::make_shared<EqBsBuilder>(\n            market_, eq, domesticCcy, configurationEqCalibration_, referenceCalibrationGrid_);\n        boost::shared_ptr<QuantExt::EqBsParametrization> parametrization = builder->parametrization();\n        eqOptionBaskets_[i] = builder->optionBasket();\n        eqParametrizations.push_back(parametrization);\n        eqNames.push_back(eqName);\n        subBuilders_[CT::EQ][i] = builder;\n        processInfo[CT::EQ].emplace_back(eqName, 1);\n    }\n\n    // Build the INF parametrizations and calibration baskets\n    vector<boost::shared_ptr<Parametrization>> infParameterizations;\n    for (Size i = 0; i < config_->infConfigs().size(); i++) {\n        boost::shared_ptr<InflationModelData> imData = config_->infConfigs()[i];\n        DLOG(\"Inflation parameterisation (\" << i << \") for index \" << imData->index());\n        if (auto dkData = boost::dynamic_pointer_cast<InfDkData>(imData)) {\n            boost::shared_ptr<InfDkBuilder> builder = boost::make_shared<InfDkBuilder>(\n                market_, dkData, configurationInfCalibration_, referenceCalibrationGrid_, dontCalibrate_);\n            if (dontCalibrate_)\n                builder->freeze();\n            infParameterizations.push_back(builder->parametrization());\n            subBuilders_[CT::INF][i] = builder;\n            processInfo[CT::INF].emplace_back(dkData->index(), 1);\n        } else if (auto jyData = boost::dynamic_pointer_cast<InfJyData>(imData)) {\n            boost::shared_ptr<InfJyBuilder> builder = boost::make_shared<InfJyBuilder>(\n                market_, jyData, configurationInfCalibration_, referenceCalibrationGrid_);\n            infParameterizations.push_back(builder->parameterization());\n            subBuilders_[CT::INF][i] = builder;\n            processInfo[CT::INF].emplace_back(jyData->index(), 2);\n        } else {\n            QL_FAIL(\"CrossAssetModelBuilder expects either DK or JY inflation model data.\");\n        }\n        infIndices.push_back(imData->index());\n    }\n\n    /*******************************************************\n     * Build the CR parametrizations and calibration baskets\n     */\n    // LGM (if any)\n    std::vector<boost::shared_ptr<QuantExt::CrLgm1fParametrization>> crLgmParametrizations;\n    for (Size i = 0; i < config_->crLgmConfigs().size(); ++i) {\n        LOG(\"CR LGM Parametrization \" << i);\n        boost::shared_ptr<CrLgmData> cr = config_->crLgmConfigs()[i];\n        string crName = cr->name();\n        boost::shared_ptr<CrLgmBuilder> builder =\n            boost::make_shared<CrLgmBuilder>(market_, cr, configurationCrCalibration_);\n        boost::shared_ptr<QuantExt::CrLgm1fParametrization> parametrization = builder->parametrization();\n        crLgmParametrizations.push_back(parametrization);\n        crNames.push_back(crName);\n        subBuilders_[CT::CR][i] = builder;\n        processInfo[CT::CR].emplace_back(crName, 1);\n    }\n\n    // CIR (if any)\n    std::vector<boost::shared_ptr<QuantExt::CrCirppParametrization>> crCirParametrizations;\n    for (Size i = 0; i < config_->crCirConfigs().size(); ++i) {\n        LOG(\"CR CIR Parametrization \" << i);\n        boost::shared_ptr<CrCirData> cr = config_->crCirConfigs()[i];\n        string crName = cr->name();\n        boost::shared_ptr<CrCirBuilder> builder =\n            boost::make_shared<CrCirBuilder>(market_, cr, configurationCrCalibration_);\n        boost::shared_ptr<QuantExt::CrCirppParametrization> parametrization = builder->parametrization();\n        crCirParametrizations.push_back(parametrization);\n        crNames.push_back(crName);\n        subBuilders_[CT::CR][i] = builder;\n        processInfo[CT::CR].emplace_back(crName, 1);\n    }\n\n    std::vector<boost::shared_ptr<QuantExt::Parametrization>> parametrizations;\n    for (Size i = 0; i < irParametrizations.size(); i++)\n        parametrizations.push_back(irParametrizations[i]);\n    for (Size i = 0; i < fxParametrizations.size(); i++)\n        parametrizations.push_back(fxParametrizations[i]);\n    for (Size i = 0; i < eqParametrizations.size(); i++)\n        parametrizations.push_back(eqParametrizations[i]);\n    parametrizations.insert(parametrizations.end(), infParameterizations.begin(), infParameterizations.end());\n    for (Size i = 0; i < crLgmParametrizations.size(); i++)\n        parametrizations.push_back(crLgmParametrizations[i]);\n    for (Size i = 0; i < crCirParametrizations.size(); i++)\n        parametrizations.push_back(crCirParametrizations[i]);\n\n    QL_REQUIRE(fxParametrizations.size() == irParametrizations.size() - 1, \"mismatch in IR/FX parametrization sizes\");\n\n    Measure::Type measure = Measure::LGM;\n    if (config_->measure() == \"BA\") {\n        measure = Measure::BA;\n        DLOG(\"Setting measure to BA\");\n    } else if (config_->measure() == \"LGM\") {\n        measure = Measure::LGM;\n        DLOG(\"Setting measure to BA\");\n    } else if (config_->measure() == \"\") {\n        DLOG(\"Defaulting to LGM measure\");\n    } else {\n        QL_FAIL(\"Measure \" << config_->measure() << \" not recognized\");\n    }\n\n    // Tag on the parametrization and process info for the auxiliary state variable in the bank account measure\n    if (measure == Measure::BA) {\n        parametrizations.push_back(\n            irParametrizations[0]); // FIXME: Is index 0 safe to reference the domestic IR parameters?\n        processInfo[CT::AUX].emplace_back(config_->domesticCurrency(), 1);\n    }\n\n    /******************************\n     * Build the correlation matrix\n     */\n    DLOG(\"CrossAssetModelBuilder: adding correlations.\");\n    CorrelationMatrixBuilder cmb;\n\n    // Perfect instantaneous correlation of auxiliary variable and domestic LGM state variable in the bank account\n    // measure\n    CorrelationFactor domesticFactorIR = {CrossAssetModelTypes::IR, config_->domesticCurrency(), 0};\n    CorrelationFactor domesticFactorAUX = {CrossAssetModelTypes::AUX, config_->domesticCurrency(), 0};\n    if (measure == Measure::BA)\n        cmb.addCorrelation(domesticFactorAUX, domesticFactorIR, 1.0);\n\n    for (auto it = config_->correlations().begin(); it != config_->correlations().end(); it++) {\n        cmb.addCorrelation(it->first.first, it->first.second, it->second);\n        if (measure == Measure::BA) {\n            // Copy correlation(domesticIR, other) to correlation(domesticAUX, other)\n            if (it->first.first == domesticFactorIR)\n                cmb.addCorrelation(domesticFactorAUX, it->first.second, it->second);\n            if (it->first.second == domesticFactorIR)\n                cmb.addCorrelation(it->first.first, domesticFactorAUX, it->second);\n        }\n    }\n\n    Matrix corrMatrix = cmb.correlationMatrix(processInfo);\n\n    TLOG(\"CAM correlation matrix:\");\n    TLOGGERSTREAM << corrMatrix;\n\n    /*****************************\n     * Build the cross asset model\n     */\n\n    SalvagingAlgorithm::Type salvaging = SalvagingAlgorithm::None;\n\n    model_.linkTo(boost::make_shared<QuantExt::CrossAssetModel>(parametrizations, corrMatrix, salvaging, measure));\n\n    /*************************\n     * Calibrate IR components\n     */\n\n    for (Size i = 0; i < irBuilder.size(); i++) {\n        DLOG(\"IR Calibration \" << i);\n        swaptionCalibrationErrors_[i] = irBuilder[i]->error();\n    }\n\n    /*************************\n     * Relink LGM discount curves to curves used for FX calibration\n     */\n\n    for (Size i = 0; i < irParametrizations.size(); i++) {\n        auto p = irParametrizations[i];\n        irDiscountCurves[i].linkTo(*market_->discountCurve(p->currency().code(), configurationFxCalibration_));\n        DLOG(\"Relinked discounting curve for \" << p->currency().code() << \" for FX calibration\");\n    }\n\n    /*************************\n     * Calibrate FX components\n     */\n\n    for (Size i = 0; i < fxParametrizations.size(); i++) {\n        boost::shared_ptr<FxBsData> fx = config_->fxConfigs()[i];\n\n        if (fx->calibrationType() == CalibrationType::None || !fx->calibrateSigma()) {\n            DLOG(\"FX Calibration \" << i << \" skipped\");\n            continue;\n        }\n\n        DLOG(\"FX Calibration \" << i);\n\n        // attach pricing engines to helpers\n        boost::shared_ptr<QuantExt::AnalyticCcLgmFxOptionEngine> engine =\n            boost::make_shared<QuantExt::AnalyticCcLgmFxOptionEngine>(*model_, i);\n        // enable caching for calibration\n        // TODO: review this\n        engine->cache(true);\n        for (Size j = 0; j < fxOptionBaskets_[i].size(); j++)\n            fxOptionBaskets_[i][j]->setPricingEngine(engine);\n\n        if (!dontCalibrate_) {\n\n            if (fx->calibrationType() == CalibrationType::Bootstrap && fx->sigmaParamType() == ParamType::Piecewise)\n                model_->calibrateBsVolatilitiesIterative(CrossAssetModelTypes::FX, i, fxOptionBaskets_[i],\n                                                         *optimizationMethod_, endCriteria_);\n            else\n                model_->calibrateBsVolatilitiesGlobal(CrossAssetModelTypes::FX, i, fxOptionBaskets_[i],\n                                                      *optimizationMethod_, endCriteria_);\n\n            DLOG(\"FX \" << fx->foreignCcy() << \" calibration errors:\");\n            fxOptionCalibrationErrors_[i] = getCalibrationError(fxOptionBaskets_[i]);\n            if (fx->calibrationType() == CalibrationType::Bootstrap) {\n                if (fabs(fxOptionCalibrationErrors_[i]) < config_->bootstrapTolerance()) {\n                    // we check the log level here to avoid unncessary computations\n                    if (Log::instance().filter(ORE_DATA)) {\n                        TLOGGERSTREAM << \"Calibration details:\";\n                        TLOGGERSTREAM << getCalibrationDetails(fxOptionBaskets_[i], fxParametrizations[i],\n                                                               irParametrizations[0]);\n                        TLOGGERSTREAM << \"rmse = \" << fxOptionCalibrationErrors_[i];\n                    }\n                } else {\n                    std::string exceptionMessage = \"FX BS \" + std::to_string(i) + \" calibration error \" +\n                                                   std::to_string(fxOptionCalibrationErrors_[i]) +\n                                                   \" exceeds tolerance \" +\n                                                   std::to_string(config_->bootstrapTolerance());\n                    WLOG(StructuredModelErrorMessage(\"Failed to calibrate FX BS Model\", exceptionMessage));\n                    WLOGGERSTREAM << \"Calibration details:\";\n                    WLOGGERSTREAM << getCalibrationDetails(fxOptionBaskets_[i], fxParametrizations[i],\n                                                           irParametrizations[0]);\n                    WLOGGERSTREAM << \"rmse = \" << fxOptionCalibrationErrors_[i];\n                    if (!continueOnError_)\n                        QL_FAIL(exceptionMessage);\n                }\n            }\n        }\n    }\n\n    /*************************\n     * Relink LGM discount curves to curves used for EQ calibration\n     */\n\n    for (Size i = 0; i < irParametrizations.size(); i++) {\n        auto p = irParametrizations[i];\n        irDiscountCurves[i].linkTo(*market_->discountCurve(p->currency().code(), configurationEqCalibration_));\n        DLOG(\"Relinked discounting curve for \" << p->currency().code() << \" for EQ calibration\");\n    }\n\n    /*************************\n     * Calibrate EQ components\n     */\n\n    for (Size i = 0; i < eqParametrizations.size(); i++) {\n        boost::shared_ptr<EqBsData> eq = config_->eqConfigs()[i];\n        if (!eq->calibrateSigma()) {\n            DLOG(\"EQ Calibration \" << i << \" skipped\");\n            continue;\n        }\n        DLOG(\"EQ Calibration \" << i);\n        // attach pricing engines to helpers\n        Currency eqCcy = eqParametrizations[i]->currency();\n        Size eqCcyIdx = model_->ccyIndex(eqCcy);\n        boost::shared_ptr<QuantExt::AnalyticXAssetLgmEquityOptionEngine> engine =\n            boost::make_shared<QuantExt::AnalyticXAssetLgmEquityOptionEngine>(*model_, i, eqCcyIdx);\n        for (Size j = 0; j < eqOptionBaskets_[i].size(); j++)\n            eqOptionBaskets_[i][j]->setPricingEngine(engine);\n\n        if (!dontCalibrate_) {\n\n            if (eq->calibrationType() == CalibrationType::Bootstrap && eq->sigmaParamType() == ParamType::Piecewise)\n                model_->calibrateBsVolatilitiesIterative(CrossAssetModelTypes::EQ, i, eqOptionBaskets_[i],\n                                                         *optimizationMethod_, endCriteria_);\n            else\n                model_->calibrateBsVolatilitiesGlobal(CrossAssetModelTypes::EQ, i, eqOptionBaskets_[i],\n                                                      *optimizationMethod_, endCriteria_);\n            DLOG(\"EQ \" << eq->eqName() << \" calibration errors:\");\n            eqOptionCalibrationErrors_[i] = getCalibrationError(eqOptionBaskets_[i]);\n            if (eq->calibrationType() == CalibrationType::Bootstrap) {\n                if (fabs(eqOptionCalibrationErrors_[i]) < config_->bootstrapTolerance()) {\n                    // we check the log level here to avoid unncessary computations\n                    if (Log::instance().filter(ORE_DATA)) {\n                        TLOGGERSTREAM << \"Calibration details:\";\n                        TLOGGERSTREAM << getCalibrationDetails(eqOptionBaskets_[i], eqParametrizations[i],\n                                                               irParametrizations[0]);\n                        TLOGGERSTREAM << \"rmse = \" << eqOptionCalibrationErrors_[i];\n                    }\n                } else {\n                    std::string exceptionMessage = \"EQ BS \" + std::to_string(i) + \" calibration error \" +\n                                                   std::to_string(eqOptionCalibrationErrors_[i]) +\n                                                   \" exceeds tolerance \" +\n                                                   std::to_string(config_->bootstrapTolerance());\n                    WLOG(StructuredModelErrorMessage(\"Failed to calibrate EQ BS Model\", exceptionMessage));\n                    WLOGGERSTREAM << \"Calibration details:\";\n                    WLOGGERSTREAM << getCalibrationDetails(eqOptionBaskets_[i], eqParametrizations[i],\n                                                           irParametrizations[0]);\n                    WLOGGERSTREAM << \"rmse = \" << eqOptionCalibrationErrors_[i];\n                    if (!continueOnError_)\n                        QL_FAIL(exceptionMessage);\n                }\n            }\n        }\n    }\n\n    /*************************\n     * Relink LGM discount curves to curves used for INF calibration\n     */\n\n    for (Size i = 0; i < irParametrizations.size(); i++) {\n        auto p = irParametrizations[i];\n        irDiscountCurves[i].linkTo(*market_->discountCurve(p->currency().code(), configurationInfCalibration_));\n        DLOG(\"Relinked discounting curve for \" << p->currency().code() << \" for INF calibration\");\n    }\n\n    // Calibrate INF components\n    for (Size i = 0; i < infParameterizations.size(); i++) {\n        boost::shared_ptr<InflationModelData> imData = config_->infConfigs()[i];\n        if (auto dkData = boost::dynamic_pointer_cast<InfDkData>(imData)) {\n            auto dkParam = boost::dynamic_pointer_cast<InfDkParametrization>(infParameterizations[i]);\n            QL_REQUIRE(dkParam, \"Expected DK model data to have given a DK parameterisation.\");\n            const auto& builder = subBuilders_.at(CT::INF).at(i);\n            const auto& dkBuilder = boost::dynamic_pointer_cast<InfDkBuilder>(builder);\n            calibrateInflation(*dkData, i, dkBuilder->optionBasket(), dkParam);\n        } else if (auto jyData = boost::dynamic_pointer_cast<InfJyData>(imData)) {\n            auto jyParam = boost::dynamic_pointer_cast<InfJyParameterization>(infParameterizations[i]);\n            QL_REQUIRE(jyParam, \"Expected JY model data to have given a JY parameterisation.\");\n            const auto& builder = subBuilders_.at(CT::INF).at(i);\n            const auto& jyBuilder = boost::dynamic_pointer_cast<InfJyBuilder>(builder);\n            calibrateInflation(*jyData, i, jyBuilder, jyParam);\n        } else {\n            QL_FAIL(\"CrossAssetModelBuilder expects either DK or JY inflation model data.\");\n        }\n    }\n\n    /*************************\n     * Relink LGM discount curves to final model curves\n     */\n\n    for (Size i = 0; i < irParametrizations.size(); i++) {\n        auto p = irParametrizations[i];\n        irDiscountCurves[i].linkTo(*market_->discountCurve(p->currency().code(), configurationFinalModel_));\n        DLOG(\"Relinked discounting curve for \" << p->currency().code() << \" as final model curves\");\n    }\n\n    // play safe (although the cache of the model should be empty at\n    // this point from all what we know...)\n    model_->update();\n\n    DLOG(\"Building CrossAssetModel done\");\n}\n\nvoid CrossAssetModelBuilder::forceRecalculate() {\n    forceCalibration_ = true;\n    ModelBuilder::forceRecalculate();\n    forceCalibration_ = false;\n}\n\nvoid CrossAssetModelBuilder::calibrateInflation(const InfDkData& data, Size modelIdx,\n                                                const vector<boost::shared_ptr<BlackCalibrationHelper>>& cb,\n                                                const boost::shared_ptr<InfDkParametrization>& inflationParam) const {\n\n    LOG(\"Calibrate DK inflation model for inflation index \" << data.index());\n\n    if ((!data.volatility().calibrate() && !data.reversion().calibrate()) ||\n        (data.calibrationType() == CalibrationType::None)) {\n        LOG(\"Calibration of DK inflation model for inflation index \" << data.index() << \" not requested.\");\n        return;\n    }\n\n    Handle<ZeroInflationIndex> zInfIndex =\n        market_->zeroInflationIndex(model_->infdk(modelIdx)->name(), configurationInfCalibration_);\n    Real baseCPI = dontCalibrate_ ? 100. : zInfIndex->fixing(zInfIndex->zeroInflationTermStructure()->baseDate());\n    auto engine = boost::make_shared<QuantExt::AnalyticDkCpiCapFloorEngine>(*model_, modelIdx, baseCPI);\n    for (Size j = 0; j < cb.size(); j++)\n        cb[j]->setPricingEngine(engine);\n\n    if (dontCalibrate_)\n        return;\n\n    if (data.volatility().calibrate() && !data.reversion().calibrate()) {\n        if (data.calibrationType() == CalibrationType::Bootstrap && data.volatility().type() == ParamType::Piecewise) {\n            model_->calibrateInfDkVolatilitiesIterative(modelIdx, cb, *optimizationMethod_, endCriteria_);\n        } else {\n            model_->calibrateInfDkVolatilitiesGlobal(modelIdx, cb, *optimizationMethod_, endCriteria_);\n        }\n    } else if (!data.volatility().calibrate() && data.reversion().calibrate()) {\n        if (data.calibrationType() == CalibrationType::Bootstrap && data.reversion().type() == ParamType::Piecewise) {\n            model_->calibrateInfDkReversionsIterative(modelIdx, cb, *optimizationMethod_, endCriteria_);\n        } else {\n            model_->calibrateInfDkReversionsGlobal(modelIdx, cb, *optimizationMethod_, endCriteria_);\n        }\n    } else {\n        model_->calibrate(cb, *optimizationMethod_, endCriteria_);\n    }\n\n    DLOG(\"INF (DK) \" << data.index() << \" calibration errors:\");\n    inflationCalibrationErrors_[modelIdx] = getCalibrationError(cb);\n    if (data.calibrationType() == CalibrationType::Bootstrap) {\n        if (fabs(inflationCalibrationErrors_[modelIdx]) < config_->bootstrapTolerance()) {\n            // we check the log level here to avoid unncessary computations\n            if (Log::instance().filter(ORE_DATA)) {\n                TLOGGERSTREAM << \"Calibration details:\";\n                TLOGGERSTREAM << getCalibrationDetails(cb, inflationParam);\n                TLOGGERSTREAM << \"rmse = \" << inflationCalibrationErrors_[modelIdx];\n            }\n        } else {\n            string exceptionMessage = \"INF (DK) \" + std::to_string(modelIdx) + \" calibration error \" +\n                                      std::to_string(inflationCalibrationErrors_[modelIdx]) + \" exceeds tolerance \" +\n                                      std::to_string(config_->bootstrapTolerance());\n            WLOG(StructuredModelErrorMessage(\"Failed to calibrate INF DK Model\", exceptionMessage));\n            WLOGGERSTREAM << \"Calibration details:\";\n            WLOGGERSTREAM << getCalibrationDetails(cb, inflationParam);\n            WLOGGERSTREAM << \"rmse = \" << inflationCalibrationErrors_[modelIdx];\n            if (!continueOnError_)\n                QL_FAIL(exceptionMessage);\n        }\n    }\n}\n\nvoid CrossAssetModelBuilder::calibrateInflation(const InfJyData& data, Size modelIdx,\n                                                const boost::shared_ptr<InfJyBuilder>& jyBuilder,\n                                                const boost::shared_ptr<InfJyParameterization>& inflationParam) const {\n\n    LOG(\"Calibrate JY inflation model for inflation index \" << data.index());\n\n    const auto& rrVol = data.realRateVolatility();\n    const auto& rrRev = data.realRateReversion();\n    const auto& idxVol = data.indexVolatility();\n\n    // Check if calibration is needed at all.\n    if ((!rrVol.calibrate() && !rrRev.calibrate() && !idxVol.calibrate()) ||\n        (data.calibrationType() == CalibrationType::None)) {\n        LOG(\"Calibration of JY inflation model for inflation index \" << data.index() << \" not requested.\");\n        return;\n    }\n\n    // We will need the 2 baskets of helpers\n    auto rrBasket = jyBuilder->realRateBasket();\n    auto idxBasket = jyBuilder->indexBasket();\n\n    // Attach engines to the helpers.\n    setJyPricingEngine(modelIdx, rrBasket);\n    setJyPricingEngine(modelIdx, idxBasket);\n\n    if (dontCalibrate_)\n        return;\n\n    // Single basket of helpers is useful in various places below.\n    vector<boost::shared_ptr<CalibrationHelper>> allHelpers = rrBasket;\n    allHelpers.insert(allHelpers.end(), idxBasket.begin(), idxBasket.end());\n\n    // Calibration configuration.\n    const auto& cc = data.calibrationConfiguration();\n\n    if (data.calibrationType() == CalibrationType::BestFit) {\n\n        // If calibration type is BestFit, do a global optimisation on the parameters that need to be calibrated.\n        DLOG(\"Calibration BestFit of JY inflation model for inflation index \" << data.index() << \" requested.\");\n\n        // Indicate the parameters to calibrate\n        map<Size, bool> toCalibrate;\n        toCalibrate[0] = rrVol.calibrate();\n        toCalibrate[1] = rrRev.calibrate();\n        toCalibrate[2] = idxVol.calibrate();\n\n        // Calibrate the model.\n        model_->calibrateInfJyGlobal(modelIdx, allHelpers, *optimizationMethod_, endCriteria_, toCalibrate);\n\n    } else {\n\n        // Calibration type is now Bootstrap, there are multiple options.\n        QL_REQUIRE(data.calibrationType() == CalibrationType::Bootstrap,\n                   \"JY inflation calibration expected a \"\n                       << \"calibration type of None, BestFit or Bootstrap.\");\n        QL_REQUIRE(!(rrRev.calibrate() && rrVol.calibrate()),\n                   \"Calibrating both the \"\n                       << \"real rate reversion and real rate volatility using Bootstrap is not supported.\");\n\n        if ((!rrVol.calibrate() && !rrRev.calibrate()) && idxVol.calibrate()) {\n\n            // Bootstrap the inflation index volatility only.\n            DLOG(\"Bootstrap calibration of JY index volatility for index \" << data.index() << \".\");\n            QL_REQUIRE(idxVol.type() == ParamType::Piecewise, \"Index volatility parameter should be Piecewise for \"\n                                                                  << \"a Bootstrap calibration.\");\n            model_->calibrateInfJyIterative(modelIdx, 2, idxBasket, *optimizationMethod_, endCriteria_);\n\n        } else if (rrVol.calibrate() && !idxVol.calibrate()) {\n\n            // Bootstrap the real rate volatility only\n            DLOG(\"Bootstrap calibration of JY real rate volatility for index \" << data.index() << \".\");\n            QL_REQUIRE(rrVol.type() == ParamType::Piecewise, \"Real rate volatility parameter should be \"\n                                                                 << \"Piecewise for a Bootstrap calibration.\");\n            model_->calibrateInfJyIterative(modelIdx, 0, rrBasket, *optimizationMethod_, endCriteria_);\n\n        } else if (rrRev.calibrate() && !idxVol.calibrate()) {\n\n            // Bootstrap the real rate reversion only\n            DLOG(\"Bootstrap calibration of JY real rate reversion for index \" << data.index() << \".\");\n            QL_REQUIRE(rrRev.type() == ParamType::Piecewise, \"Real rate reversion parameter should be \"\n                                                                 << \"Piecewise for a Bootstrap calibration.\");\n            model_->calibrateInfJyIterative(modelIdx, 1, rrBasket, *optimizationMethod_, endCriteria_);\n\n        } else if ((rrVol.calibrate() && idxVol.calibrate()) || (rrRev.calibrate() && idxVol.calibrate())) {\n\n            if (rrVol.calibrate()) {\n                DLOG(\"Bootstrap calibration of JY real rate volatility and index volatility for index \" << data.index()\n                                                                                                        << \".\");\n            } else {\n                DLOG(\"Bootstrap calibration of JY real rate reversion and index volatility for index \" << data.index()\n                                                                                                       << \".\");\n            }\n\n            // Bootstrap the real rate volatility and the index volatility\n            Size rrIdx = rrVol.calibrate() ? 0 : 1;\n            Size numIts = 0;\n            inflationCalibrationErrors_[modelIdx] = getCalibrationError(allHelpers);\n\n            while (inflationCalibrationErrors_[modelIdx] > cc.rmseTolerance() && numIts < cc.maxIterations()) {\n                model_->calibrateInfJyIterative(modelIdx, 2, idxBasket, *optimizationMethod_, endCriteria_);\n                model_->calibrateInfJyIterative(modelIdx, rrIdx, rrBasket, *optimizationMethod_, endCriteria_);\n                numIts++;\n                inflationCalibrationErrors_[modelIdx] = getCalibrationError(allHelpers);\n            }\n\n            DLOG(\"Bootstrap calibration of JY model stopped with number of iterations \"\n                 << numIts << \" and rmse equal to \" << std::scientific << std::setprecision(6)\n                 << inflationCalibrationErrors_[modelIdx] << \".\");\n\n        } else {\n            QL_FAIL(\"JY inflation bootstrap calibration does not support the combination of real rate volatility = \"\n                    << std::boolalpha << rrVol.calibrate() << \", real rate reversion = \" << rrRev.calibrate() << \" and \"\n                    << \"index volatility = \" << idxVol.calibrate() << \".\");\n        }\n    }\n\n    // Log the calibration details.\n    DLOG(\"INF (JY) \" << data.index() << \" calibration errors:\");\n    inflationCalibrationErrors_[modelIdx] = getCalibrationError(allHelpers);\n    if (data.calibrationType() == CalibrationType::Bootstrap) {\n        if (fabs(inflationCalibrationErrors_[modelIdx]) < cc.rmseTolerance()) {\n            // we check the log level here to avoid unncessary computations\n            if (Log::instance().filter(ORE_DATA)) {\n                TLOGGERSTREAM << \"Calibration details:\";\n                TLOGGERSTREAM << getCalibrationDetails(rrBasket, idxBasket, inflationParam, rrVol.calibrate());\n                TLOGGERSTREAM << \"rmse = \" << inflationCalibrationErrors_[modelIdx];\n            }\n        } else {\n            std::stringstream ss;\n            ss << \"INF (JY) \" << modelIdx << \" calibration error \" << std::scientific\n               << inflationCalibrationErrors_[modelIdx] << \" exceeds tolerance \" << cc.rmseTolerance();\n            string exceptionMessage = ss.str();\n            WLOG(StructuredModelErrorMessage(\"Failed to calibrate INF JY Model\", exceptionMessage));\n            WLOGGERSTREAM << \"Calibration details:\";\n            WLOGGERSTREAM << getCalibrationDetails(rrBasket, idxBasket, inflationParam, rrVol.calibrate());\n            WLOGGERSTREAM << \"rmse = \" << inflationCalibrationErrors_[modelIdx];\n            if (!continueOnError_)\n                QL_FAIL(exceptionMessage);\n        }\n    }\n\n    LOG(\"Finished calibrating JY inflation model for inflation index \" << data.index());\n}\n\nvoid CrossAssetModelBuilder::setJyPricingEngine(\n    Size modelIdx, const vector<boost::shared_ptr<CalibrationHelper>>& calibrationBasket) const {\n\n    DLOG(\"Start setting pricing engines on JY calibration instruments.\");\n\n    // JY supports three types of calibration helpers. Generally, all of the calibration instruments in a basket will\n    // be of the same type but we support all three here.\n    boost::shared_ptr<PricingEngine> cpiCapFloorEngine;\n    boost::shared_ptr<PricingEngine> yoyCapFloorEngine;\n    boost::shared_ptr<PricingEngine> yoySwapEngine;\n    boost::shared_ptr<InflationCouponPricer> yoyCouponPricer;\n\n    for (auto& ci : calibrationBasket) {\n\n        if (boost::shared_ptr<CpiCapFloorHelper> h = boost::dynamic_pointer_cast<CpiCapFloorHelper>(ci)) {\n            if (!cpiCapFloorEngine) {\n                cpiCapFloorEngine = boost::make_shared<AnalyticJyCpiCapFloorEngine>(*model_, modelIdx);\n            }\n            h->setPricingEngine(cpiCapFloorEngine);\n            continue;\n        }\n\n        if (boost::shared_ptr<YoYCapFloorHelper> h = boost::dynamic_pointer_cast<YoYCapFloorHelper>(ci)) {\n            if (!yoyCapFloorEngine) {\n                yoyCapFloorEngine = boost::make_shared<AnalyticJyYoYCapFloorEngine>(*model_, modelIdx);\n            }\n            h->setPricingEngine(yoyCapFloorEngine);\n            continue;\n        }\n\n        if (boost::shared_ptr<YoYSwapHelper> h = boost::dynamic_pointer_cast<YoYSwapHelper>(ci)) {\n            // Here we need to attach the coupon pricer to all the YoY coupons and then the generic discounting swap\n            // engine to the helper.\n            if (!yoyCouponPricer) {\n                yoyCouponPricer = boost::make_shared<JyYoYInflationCouponPricer>(*model_, modelIdx);\n\n                Size irIdx = model_->ccyIndex(model_->infjy(modelIdx)->currency());\n                auto yts = model_->irlgm1f(irIdx)->termStructure();\n                yoySwapEngine = boost::make_shared<DiscountingSwapEngine>(yts);\n            }\n\n            const auto& yoyLeg = h->yoySwap()->yoyLeg();\n            for (const auto& cf : yoyLeg) {\n                if (auto yoyCoupon = boost::dynamic_pointer_cast<YoYInflationCoupon>(cf))\n                    yoyCoupon->setPricer(yoyCouponPricer);\n            }\n\n            h->setPricingEngine(yoySwapEngine);\n            continue;\n        }\n\n        QL_FAIL(\"Only CPI cap floors, YoY cap floors and YoY swaps are supported for JY calibration.\");\n    }\n\n    DLOG(\"Finished setting pricing engines on JY calibration instruments.\");\n}\n\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "a19f886097a4ebe7e1b746350b1d3359b5f00fde", "size": 43218, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/model/crossassetmodelbuilder.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "OREData/ored/model/crossassetmodelbuilder.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "OREData/ored/model/crossassetmodelbuilder.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 50.0787949015, "max_line_length": 120, "alphanum_fraction": 0.6361701143, "num_tokens": 9921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.23165309003353207}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2019 Alexey Moskvin\n// Copyright (c) 2020 Ilias Khairullin <ilias@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_MULTIPRECISION_MODULAR_ADAPTOR_HPP\n#define BOOST_MULTIPRECISION_MODULAR_ADAPTOR_HPP\n\n#include <boost/cstdint.hpp>\n#include <boost/functional/hash_fwd.hpp>\n\n#include <nil/crypto3/multiprecision/detail/digits.hpp>\n#include <nil/crypto3/multiprecision/number.hpp>\n\n#include <nil/crypto3/multiprecision/modular/modular_params.hpp>\n#include <nil/crypto3/multiprecision/modular/modular_adaptor_fixed.hpp>\n\n#include <boost/container/small_vector.hpp>\n\n#include <algorithm>\n#include <cmath>\n#include <vector>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace multiprecision {\n            namespace backends {\n\n                template<typename Backend>\n                struct modular_adaptor {\n                    typedef modular_params<Backend> modulus_type;\n                    typedef Backend backend_type;\n\n                protected:\n                    Backend m_base;\n                    modulus_type m_mod;\n\n                public:\n                    inline Backend& base_data() {\n                        return m_base;\n                    }\n                    inline const Backend& base_data() const {\n                        return m_base;\n                    }\n                    inline modulus_type& mod_data() {\n                        return m_mod;\n                    }\n                    inline const modulus_type& mod_data() const {\n                        return m_mod;\n                    }\n\n                    typedef typename Backend::signed_types signed_types;\n                    typedef typename Backend::unsigned_types unsigned_types;\n\n                    modular_adaptor() {\n                    }\n\n                    modular_adaptor(const modular_adaptor& o) : m_base(o.base_data()), m_mod(o.mod_data()) {\n                    }\n\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n\n                    modular_adaptor(modular_adaptor&& o) :\n                        m_base(std::move(o.base_data())), m_mod(std::move(o.mod_data())) {\n                    }\n\n#endif\n                    // TODO: implement create_internal_representation\n                    // modular_adaptor(const Backend& val, const modular_params<Backend>& mod) : m_mod(mod),\n                    // m_base(mod.create_internal_representation(val))\n                    // {\n                    //\n                    // }\n\n                    modular_adaptor(const Backend& val, const Backend& mod) : m_base(val), m_mod(mod) {\n                    }\n\n                    modular_adaptor(Backend& val, Backend& mod) : m_base(val), m_mod(mod) {\n                    }\n\n                    // TODO: maybe initialize modulus rather than base\n                    modular_adaptor(const Backend& val) :\n                        m_base(val), m_mod(typename boost::mpl::front<unsigned_types>::type(0u)) {\n                    }\n\n                    modular_adaptor(const modular_params<Backend>& mod) :\n                        m_base(typename boost::mpl::front<unsigned_types>::type(0u)), m_mod(mod) {\n                    }\n\n                    modular_adaptor& operator=(const modular_adaptor& o) {\n                        m_base = o.base_data();\n                        m_mod = o.mod_data();\n                        return *this;\n                    }\n\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n\n                    modular_adaptor& operator=(modular_adaptor&& o)\n\n                        BOOST_NOEXCEPT {\n                        m_base = std::move(o.base_data());\n                        m_mod = std::move(o.mod_data());\n                        return *this;\n                    }\n#endif\n\n                    modular_adaptor& operator=(const char* s) {\n                        typedef typename boost::mpl::front<unsigned_types>::type ui_type;\n                        ui_type zero = 0u;\n\n                        using default_ops::eval_fpclassify;\n\n                        if (s && (*s == '(')) {\n                            std::string part;\n                            const char* p = ++s;\n                            while (*p && (*p != ',') && (*p != ')'))\n                                ++p;\n                            part.assign(s, p);\n                            if (!part.empty())\n                                m_base() = part.c_str();\n                            else\n                                m_base() = zero;\n                            s = p;\n                            if (*p && (*p != ')')) {\n                                ++p;\n                                while (*p && (*p != ')'))\n                                    ++p;\n                                part.assign(s + 1, p);\n                            } else\n                                part.erase();\n                            if (!part.empty())\n                                m_mod() = part.c_str();\n                            else\n                                m_mod() = zero;\n                        } else {\n                            base_data() = s;\n                            m_mod() = zero;\n                        }\n                        return *this;\n                    }\n\n                    // TODO: maybe change behaviour to check a congruence relation\n                    int compare(const modular_adaptor& o) const {\n                        // They are either equal or not:<\n                        if (m_mod.compare(o.mod_data()) != 0) {\n                            BOOST_THROW_EXCEPTION(\n                                std::runtime_error(\"Could not compare modular number with different mod.\"));\n                        }\n                        Backend tmp1, tmp2;\n                        mod_data().adjust_regular(tmp1, base_data());\n                        mod_data().adjust_regular(tmp2, o.base_data());\n                        return tmp1.compare(tmp2);\n                    }\n\n                    // TODO: maybe change behaviour to check a congruence relation\n                    template<class T>\n                    int compare(const T& val) const {\n                        using default_ops::eval_lt;\n                        if (!eval_lt(m_mod, val)) {\n                            BOOST_THROW_EXCEPTION(std::runtime_error(\n                                \"Could not compare modular number with mod bigger than compared number.\"));\n                        }\n                        Backend tmp;\n                        mod_data().adjust_regular(tmp, base_data());\n                        return tmp.compare(val);\n                    }\n\n                    inline void swap(modular_adaptor& o) {\n                        base_data().swap(o.base_data());\n                        std::swap(mod_data(), o.mod_data());\n                    }\n\n                    inline std::string str(std::streamsize dig, std::ios_base::fmtflags f) const {\n                        Backend tmp;\n                        mod_data().adjust_regular(tmp, base_data());\n                        return tmp.str(dig, f);\n                    }\n\n                    inline void negate() {\n                        base_data().negate();\n                        eval_add(base_data(), mod_data().get_mod().backend());\n                    }\n\n                    template<typename BackendT, expression_template_option ExpressionTemplates>\n                    operator number<BackendT, ExpressionTemplates>() {\n                        return base_data();\n                    };\n                };\n\n                template<class Result, class Backend>\n                constexpr void eval_convert_to(Result* result, const modular_adaptor<Backend>& val) {\n                    using default_ops::eval_convert_to;\n                    eval_convert_to(result, val.base_data());\n                }\n\n                template<class Backend, class T>\n                constexpr typename boost::enable_if<boost::is_arithmetic<T>, bool>::type eval_eq(const modular_adaptor<Backend>& a,\n                                                                                   const T& b) {\n                    return a.compare(b) == 0;\n                }\n\n                template<class Backend1, class Backend2>\n                constexpr void eval_redc(Backend1& result, const modular_params<Backend2>& mod) {\n                    mod.reduce(result);\n                    eval_modulus(result, mod.get_mod().backend());\n                }\n\n                template<class Backend>\n                constexpr void eval_add(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& o) {\n                    BOOST_ASSERT(result.mod_data().get_mod() == o.mod_data().get_mod());\n                    using default_ops::eval_lt;\n\n                    eval_add(result.base_data(), o.base_data());\n                    if (!eval_lt(result.base_data(), result.mod_data().get_mod())) {\n                        eval_subtract(result.base_data(), result.mod_data().get_mod().backend());\n                    }\n                }\n\n                template<class Backend>\n                constexpr void eval_subtract(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& o) {\n                    BOOST_ASSERT(result.mod_data().get_mod() == o.mod_data().get_mod());\n                    typedef typename boost::mpl::front<typename Backend::unsigned_types>::type ui_type;\n                    using default_ops::eval_lt;\n                    eval_subtract(result.base_data(), o.base_data());\n                    if (eval_lt(result.base_data(), ui_type(0u))) {\n                        eval_add(result.base_data(), result.mod_data().get_mod().backend());\n                    }\n                }\n\n                template<class Backend>\n                constexpr void eval_multiply(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& o) {\n                    BOOST_ASSERT(result.mod_data().get_mod() == o.mod_data().get_mod());\n                    eval_multiply(result.base_data(), o.base_data());\n                    eval_redc(result.base_data(), result.mod_data());\n                }\n\n                template<class Backend>\n                constexpr void eval_divide(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& o) {\n                    BOOST_ASSERT(result.mod_data().get_mod() == o.mod_data().get_mod());\n                    Backend tmp1, tmp2;\n                    result.mod_data().adjust_regular(tmp1, result.base_data());\n                    result.mod_data().adjust_regular(tmp2, o.base_data());\n                    eval_divide(tmp1, tmp2);\n                    result.base_data() = tmp1;\n                    result.mod_data().adjust_modular(result.base_data());\n                    result.mod_data().adjust_regular(tmp2, result.base_data());\n                }\n\n                template<class Backend>\n                constexpr void eval_modulus(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& o) {\n                    BOOST_ASSERT(result.mod_data().get_mod() == o.mod_data().get_mod());\n                    Backend tmp1, tmp2;\n                    result.mod_data().adjust_regular(tmp1, result.base_data());\n                    result.mod_data().adjust_regular(tmp2, o.base_data());\n                    eval_modulus(tmp1, tmp2);\n                    result.base_data() = tmp1;\n                    result.mod_data().adjust_modular(result.base_data());\n                    result.mod_data().adjust_regular(tmp2, result.base_data());\n                }\n\n                template<class Backend>\n                constexpr bool eval_is_zero(const modular_adaptor<Backend>& val)\n\n                    BOOST_NOEXCEPT {\n                    using default_ops::eval_is_zero;\n                    return eval_is_zero(val.base_data());\n                }\n\n                // TODO: check returned value\n                template<class Backend>\n                constexpr int eval_get_sign(const modular_adaptor<Backend>&) {\n                    return 1;\n                }\n\n                // TODO: is the function required\n                // template <class Result, class Backend>\n                // constexpr typename boost::disable_if_c<boost::is_complex<Result>::value>::type\n                // eval_convert_to(Result* result, const modular_adaptor<Backend>& val)\n                // {\n                //    using default_ops::eval_convert_to;\n                //    eval_convert_to(result, val.base_data());\n                // }\n\n                template<class Backend, class T, class V>\n                constexpr void assign_components(modular_adaptor<Backend>& result, const T& a, const V& b) {\n                    result.base_data() = a;\n                    result.mod_data() = b;\n                    result.mod_data().adjust_modular(result.base_data());\n                }\n\n                template<class Backend>\n                constexpr void eval_sqrt(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& val) {\n                    eval_sqrt(result.base_data(), val.base_data());\n                }\n\n                template<class Backend>\n                constexpr void eval_abs(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& val) {\n                    result = val;\n                }\n\n                size_t window_bits(size_t exp_bits) {\n                    BOOST_STATIC_CONSTEXPR size_t wsize_count = 6;\n                    BOOST_STATIC_CONSTEXPR size_t wsize[wsize_count][2] = {{1434, 7}, {539, 6}, {197, 4},\n                                                                           {70, 3},   {17, 2},  {0, 0}};\n\n                    size_t window_bits = 1;\n\n                    size_t j = wsize_count - 1;\n                    while (wsize[j][0] > exp_bits) {\n                        --j;\n                    }\n                    window_bits += wsize[j][1];\n\n                    return window_bits;\n                };\n\n                template<class Backend>\n                inline void find_modular_pow(modular_adaptor<Backend>& result,\n                                             const modular_adaptor<Backend>& b,\n                                             const Backend& exp) {\n                    using default_ops::eval_bit_set;\n                    using default_ops::eval_convert_to;\n                    using default_ops::eval_decrement;\n                    using default_ops::eval_multiply;\n\n                    typedef number<modular_adaptor<Backend>> modular_type;\n                    modular_params<Backend> mod = b.mod_data();\n                    size_t m_window_bits;\n                    unsigned long cur_exp_index;\n                    size_t exp_bits = eval_msb(exp);\n                    m_window_bits = window_bits(exp_bits + 1);\n\n                    std::vector<modular_type> m_g(1U << m_window_bits);\n                    modular_type* p_g = m_g.data();\n                    modular_type x(1, mod);\n                    Backend nibble = exp;\n                    Backend mask;\n                    eval_bit_set(mask, m_window_bits);\n                    eval_decrement(mask);\n                    *p_g = x;\n                    ++p_g;\n                    *p_g = b;\n                    ++p_g;\n                    for (size_t i = 2; i < (1U << m_window_bits); i++) {\n                        eval_multiply((*p_g).backend(), m_g[i - 1].backend(), b);\n                        ++p_g;\n                    }\n                    size_t exp_nibbles = (exp_bits + 1 + m_window_bits - 1) / m_window_bits;\n                    std::vector<size_t> exp_index;\n\n                    for (size_t i = 0; i < exp_nibbles; ++i) {\n                        Backend tmp = nibble;\n                        eval_bitwise_and(tmp, mask);\n                        eval_convert_to(&cur_exp_index, tmp);\n                        eval_right_shift(nibble, m_window_bits);\n                        exp_index.push_back(cur_exp_index);\n                    }\n\n                    x = x * m_g[exp_index[exp_nibbles - 1]];\n                    for (size_t i = exp_nibbles - 1; i > 0; --i) {\n\n                        for (size_t j = 0; j != m_window_bits; ++j) {\n                            x = x * x;\n                        }\n\n                        x = x * m_g[exp_index[i - 1]];\n                    }\n                    result = x.backend();\n                }\n\n                template<class Backend, typename T>\n                constexpr void eval_pow(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& b,\n                                        const T& e) {\n                    find_modular_pow(result, b, e);\n                }\n\n                template<class Backend>\n                constexpr void eval_pow(modular_adaptor<Backend>& result,\n                                        const modular_adaptor<Backend>& b,\n                                        const modular_adaptor<Backend>& e) {\n                    Backend exp;\n                    e.mod_data().adjust_regular(exp, e.base_data());\n                    find_modular_pow(result, b, exp);\n                }\n\n                template<typename Backend1, typename Backend2, typename T>\n                constexpr void eval_powm(modular_adaptor<Backend1>& result, const modular_adaptor<Backend2>& b,\n                                         const T& e) {\n                    eval_pow(result, b, e);\n                }\n\n                template<typename Backend1, typename Backend2, typename Backend3>\n                constexpr void eval_powm(modular_adaptor<Backend1>& result,\n                                         const modular_adaptor<Backend2>& b,\n                                         const modular_adaptor<Backend3>& e) {\n                    eval_pow(result, b, e);\n                }\n\n                template<class Backend, class UI>\n                constexpr void eval_left_shift(modular_adaptor<Backend>& t, UI i) {\n                    using default_ops::eval_left_shift;\n                    Backend tmp;\n                    t.mod_data().adjust_regular(tmp, t.base_data());\n                    eval_left_shift(tmp, i);\n                    t.base_data() = tmp;\n                    t.mod_data().adjust_modular(t.base_data());\n                }\n\n                template<class Backend, class UI>\n                constexpr void eval_right_shift(modular_adaptor<Backend>& t, UI i) {\n                    using default_ops::eval_right_shift;\n                    Backend tmp;\n                    t.mod_data().adjust_regular(tmp, t.base_data());\n                    eval_right_shift(tmp, i);\n                    t.base_data() = tmp;\n                    t.mod_data().adjust_modular(t.base_data());\n                }\n\n                template<class Backend, class UI>\n                constexpr void eval_left_shift(modular_adaptor<Backend>& t, const modular_adaptor<Backend>& v, UI i) {\n                    using default_ops::eval_left_shift;\n                    Backend tmp1, tmp2;\n                    t.mod_data().adjust_regular(tmp1, t.base_data());\n                    t.mod_data().adjust_regular(tmp2, v.base_data());\n                    eval_left_shift(tmp1, tmp2, static_cast<unsigned long>(i));\n                    t.base_data() = tmp1;\n                    t.mod_data().adjust_modular(t.base_data());\n                }\n\n                template<class Backend, class UI>\n                constexpr void eval_right_shift(modular_adaptor<Backend>& t, const modular_adaptor<Backend>& v, UI i) {\n                    using default_ops::eval_right_shift;\n                    Backend tmp1, tmp2;\n                    t.mod_data().adjust_regular(tmp1, t.base_data());\n                    t.mod_data().adjust_regular(tmp2, v.base_data());\n                    eval_right_shift(tmp1, tmp2, static_cast<unsigned long>(i));\n                    t.base_data() = tmp1;\n                    t.mod_data().adjust_modular(t.base_data());\n                }\n\n                template<class Backend>\n                constexpr void eval_bitwise_and(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& v) {\n                    using default_ops::eval_bitwise_and;\n                    BOOST_ASSERT(result.mod_data().get_mod() == v.mod_data().get_mod());\n\n                    Backend tmp1, tmp2;\n                    result.mod_data().adjust_regular(tmp1, result.base_data());\n                    v.mod_data().adjust_regular(tmp2, v.base_data());\n                    eval_bitwise_and(tmp1, tmp1, tmp2);\n                    result.base_data() = tmp1;\n                    result.mod_data().adjust_modular(result.base_data());\n                }\n\n                template<class Backend>\n                constexpr void eval_bitwise_or(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& v) {\n                    using default_ops::eval_bitwise_or;\n                    BOOST_ASSERT(result.mod_data().get_mod() == v.mod_data().get_mod());\n\n                    Backend tmp1, tmp2;\n                    result.mod_data().adjust_regular(tmp1, result.base_data());\n                    v.mod_data().adjust_regular(tmp2, v.base_data());\n                    eval_bitwise_or(tmp1, tmp1, tmp2);\n                    result.base_data() = tmp1;\n                    result.mod_data().adjust_modular(result.base_data());\n                }\n\n                template<class Backend>\n                constexpr void eval_bitwise_xor(modular_adaptor<Backend>& result, const modular_adaptor<Backend>& v) {\n                    using default_ops::eval_bitwise_xor;\n                    BOOST_ASSERT(result.mod_data().get_mod() == v.mod_data().get_mod());\n\n                    Backend tmp1, tmp2;\n                    result.mod_data().adjust_regular(tmp1, result.base_data());\n                    v.mod_data().adjust_regular(tmp2, v.base_data());\n                    eval_bitwise_xor(tmp1, tmp1, tmp2);\n                    result.base_data() = tmp1;\n                    result.mod_data().adjust_modular(result.base_data());\n                }\n\n                template<typename Backend>\n                constexpr int eval_msb(const modular_adaptor<Backend>& m) {\n                    using default_ops::eval_msb;\n                    Backend tmp;\n                    m.mod_data().adjust_regular(tmp, m.base_data());\n                    return eval_msb(tmp);\n                }\n\n                template<typename Backend>\n                constexpr unsigned eval_lsb(const modular_adaptor<Backend>& m) {\n                    using default_ops::eval_lsb;\n                    Backend tmp;\n                    m.mod_data().adjust_regular(tmp, m.base_data());\n                    return eval_lsb(tmp);\n                }\n\n                template<typename Backend>\n                constexpr bool eval_bit_test(const modular_adaptor<Backend>& m, unsigned index) {\n                    using default_ops::eval_bit_test;\n                    Backend tmp;\n                    m.mod_data().adjust_regular(tmp, m.base_data());\n                    return eval_bit_test(tmp, index);\n                }\n\n                template<typename Backend>\n                constexpr void eval_bit_set(modular_adaptor<Backend>& result, unsigned index) {\n                    using default_ops::eval_bit_set;\n                    Backend tmp;\n                    result.mod_data().adjust_regular(tmp, result.base_data());\n                    eval_bit_set(tmp, index);\n                    result.mod_data().adjust_modular(result.base_data(), tmp);\n                }\n\n                template<typename Backend>\n                constexpr void eval_bit_unset(modular_adaptor<Backend>& result, unsigned index) {\n                    using default_ops::eval_bit_unset;\n                    Backend tmp;\n                    result.mod_data().adjust_regular(tmp, result.base_data());\n                    eval_bit_unset(tmp, index);\n                    result.mod_data().adjust_modular(result.base_data(), tmp);\n                }\n\n                template<typename Backend>\n                constexpr void eval_bit_flip(modular_adaptor<Backend>& result, unsigned index) {\n                    using default_ops::eval_bit_flip;\n                    Backend tmp;\n                    result.mod_data().adjust_regular(tmp, result.base_data());\n                    eval_bit_flip(tmp, index);\n                    result.mod_data().adjust_modular(result.base_data(), tmp);\n                }\n\n            }    // namespace backends\n\n            using nil::crypto3::multiprecision::backends::modular_adaptor;\n\n            template<class Backend>\n            struct number_category<modular_adaptor<Backend>>\n                : public boost::mpl::int_<nil::crypto3::multiprecision::number_kind_modular> { };\n\n            template<class Backend, expression_template_option ExpressionTemplates>\n            struct component_type<number<modular_adaptor<Backend>, ExpressionTemplates>> {\n                typedef number<Backend, ExpressionTemplates> type;\n            };\n\n        }    // namespace multiprecision\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "e0e07a4cd8140122f63a1f134f19977c0bb55d9e", "size": 25326, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/include/nil/crypto3/multiprecision/modular/modular_adaptor.hpp", "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/libs-source/multiprecision/include/nil/crypto3/multiprecision/modular/modular_adaptor.hpp", "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/libs-source/multiprecision/include/nil/crypto3/multiprecision/modular/modular_adaptor.hpp", "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": 45.714801444, "max_line_length": 131, "alphanum_fraction": 0.4817578773, "num_tokens": 4541, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23146209301246015}}
{"text": "#include \"itkTractsToVectorImageFilter.h\"\n\n// VTK\n#include <vtkPolyLine.h>\n#include <vtkCellArray.h>\n#include <vtkCellData.h>\n\n// ITK\n#include <itkTimeProbe.h>\n#include <itkImageRegionIterator.h>\n\n// misc\n#define _USE_MATH_DEFINES\n#include <math.h>\n#include <boost/progress.hpp>\n\n\nnamespace itk{\n\nstatic bool CompareVectorLengths(const vnl_vector_fixed< double, 3 >& v1, const vnl_vector_fixed< double, 3 >& v2)\n{\n    return (v1.magnitude()>v2.magnitude());\n}\n\ntemplate< class PixelType >\nTractsToVectorImageFilter< PixelType >::TractsToVectorImageFilter():\n    m_AngularThreshold(0.7),\n    m_Epsilon(0.999),\n    m_MaskImage(NULL),\n    m_NormalizeVectors(false),\n    m_UseWorkingCopy(true),\n    m_UseTrilinearInterpolation(false),\n    m_MaxNumDirections(3),\n    m_Thres(0.5),\n    m_NumDirectionsImage(NULL)\n{\n    this->SetNumberOfRequiredOutputs(1);\n}\n\n\ntemplate< class PixelType >\nTractsToVectorImageFilter< PixelType >::~TractsToVectorImageFilter()\n{\n}\n\n\ntemplate< class PixelType >\nvnl_vector_fixed<double, 3> TractsToVectorImageFilter< PixelType >::GetVnlVector(double point[])\n{\n    vnl_vector_fixed<double, 3> vnlVector;\n    vnlVector[0] = point[0];\n    vnlVector[1] = point[1];\n    vnlVector[2] = point[2];\n    return vnlVector;\n}\n\n\ntemplate< class PixelType >\nitk::Point<double, 3> TractsToVectorImageFilter< PixelType >::GetItkPoint(double point[])\n{\n    itk::Point<double, 3> itkPoint;\n    itkPoint[0] = point[0];\n    itkPoint[1] = point[1];\n    itkPoint[2] = point[2];\n    return itkPoint;\n}\n\ntemplate< class PixelType >\nvoid TractsToVectorImageFilter< PixelType >::GenerateData()\n{\n  mitk::BaseGeometry::Pointer geometry = m_FiberBundle->GetGeometry();\n\n    // calculate new image parameters\n    itk::Vector<double> spacing;\n    itk::Point<double> origin;\n    itk::Matrix<double, 3, 3> direction;\n    ImageRegion<3> imageRegion;\n    if (!m_MaskImage.IsNull())\n    {\n        spacing = m_MaskImage->GetSpacing();\n        imageRegion = m_MaskImage->GetLargestPossibleRegion();\n        origin = m_MaskImage->GetOrigin();\n        direction = m_MaskImage->GetDirection();\n    }\n    else\n    {\n        spacing = geometry->GetSpacing();\n        origin = geometry->GetOrigin();\n        mitk::BaseGeometry::BoundsArrayType bounds = geometry->GetBounds();\n        origin[0] += bounds.GetElement(0);\n        origin[1] += bounds.GetElement(2);\n        origin[2] += bounds.GetElement(4);\n\n        for (int i=0; i<3; i++)\n            for (int j=0; j<3; j++)\n                direction[j][i] = geometry->GetMatrixColumn(i)[j];\n        imageRegion.SetSize(0, geometry->GetExtent(0));\n        imageRegion.SetSize(1, geometry->GetExtent(1));\n        imageRegion.SetSize(2, geometry->GetExtent(2));\n\n\n        m_MaskImage = ItkUcharImgType::New();\n        m_MaskImage->SetSpacing( spacing );\n        m_MaskImage->SetOrigin( origin );\n        m_MaskImage->SetDirection( direction );\n        m_MaskImage->SetRegions( imageRegion );\n        m_MaskImage->Allocate();\n        m_MaskImage->FillBuffer(1);\n    }\n    OutputImageType::RegionType::SizeType outImageSize = imageRegion.GetSize();\n    m_OutImageSpacing = m_MaskImage->GetSpacing();\n    m_ClusteredDirectionsContainer = ContainerType::New();\n\n    // initialize crossings image\n    m_CrossingsImage = ItkUcharImgType::New();\n    m_CrossingsImage->SetSpacing( spacing );\n    m_CrossingsImage->SetOrigin( origin );\n    m_CrossingsImage->SetDirection( direction );\n    m_CrossingsImage->SetRegions( imageRegion );\n    m_CrossingsImage->Allocate();\n    m_CrossingsImage->FillBuffer(0);\n\n    // initialize num directions image\n    m_NumDirectionsImage = ItkUcharImgType::New();\n    m_NumDirectionsImage->SetSpacing( spacing );\n    m_NumDirectionsImage->SetOrigin( origin );\n    m_NumDirectionsImage->SetDirection( direction );\n    m_NumDirectionsImage->SetRegions( imageRegion );\n    m_NumDirectionsImage->Allocate();\n    m_NumDirectionsImage->FillBuffer(0);\n\n    // resample fiber bundle\n    double minSpacing = 1;\n    if(m_OutImageSpacing[0]<m_OutImageSpacing[1] && m_OutImageSpacing[0]<m_OutImageSpacing[2])\n        minSpacing = m_OutImageSpacing[0];\n    else if (m_OutImageSpacing[1] < m_OutImageSpacing[2])\n        minSpacing = m_OutImageSpacing[1];\n    else\n        minSpacing = m_OutImageSpacing[2];\n\n    if (m_UseWorkingCopy)\n        m_FiberBundle = m_FiberBundle->GetDeepCopy();\n\n    // resample fiber bundle for sufficient voxel coverage\n    m_FiberBundle->ResampleFibers(minSpacing/3);\n\n    // iterate over all fibers\n    vtkSmartPointer<vtkPolyData> fiberPolyData = m_FiberBundle->GetFiberPolyData();\n    vtkSmartPointer<vtkCellArray> vLines = fiberPolyData->GetLines();\n    vLines->InitTraversal();\n    int numFibers = m_FiberBundle->GetNumFibers();\n    itk::TimeProbe clock;\n    m_DirectionsContainer = ContainerType::New();\n\n    if (m_UseTrilinearInterpolation)\n        MITK_INFO << \"Generating directions from tractogram (trilinear interpolation)\";\n    else\n        MITK_INFO << \"Generating directions from tractogram\";\n\n    boost::progress_display disp(numFibers);\n    for( int i=0; i<numFibers; i++ )\n    {\n        ++disp;\n        clock.Start();\n        vtkIdType   numPoints(0);\n        vtkIdType*  points(NULL);\n        vLines->GetNextCell ( numPoints, points );\n        if (numPoints<2)\n            continue;\n\n        itk::Index<3> index; index.Fill(0);\n        itk::ContinuousIndex<double, 3> contIndex;\n        vnl_vector_fixed<double, 3> dir, wDir;\n        itk::Point<double, 3> worldPos;\n        vnl_vector<double> v;\n        for( int j=0; j<numPoints-1; j++)\n        {\n            double* temp = fiberPolyData->GetPoint(points[j]);\n            worldPos = GetItkPoint(temp);\n            v = GetVnlVector(temp);\n\n            dir = GetVnlVector(fiberPolyData->GetPoint(points[j+1]))-v;\n            dir.normalize();\n\n            m_MaskImage->TransformPhysicalPointToIndex(worldPos, index);\n            m_MaskImage->TransformPhysicalPointToContinuousIndex(worldPos, contIndex);\n\n            if (m_MaskImage->GetPixel(index)==0)\n                continue;\n\n            if (!m_UseTrilinearInterpolation)\n            {\n                if (index[0] < 0 || (unsigned long)index[0] >= outImageSize[0])\n                    continue;\n                if (index[1] < 0 || (unsigned long)index[1] >= outImageSize[1])\n                    continue;\n                if (index[2] < 0 || (unsigned long)index[2] >= outImageSize[2])\n                    continue;\n\n                unsigned int idx = index[0] + outImageSize[0]*(index[1] + outImageSize[1]*index[2]);\n                DirectionContainerType::Pointer dirCont = DirectionContainerType::New();\n                if (m_DirectionsContainer->IndexExists(idx))\n                {\n                    dirCont = m_DirectionsContainer->GetElement(idx);\n                    if (dirCont.IsNull())\n                    {\n                        dirCont = DirectionContainerType::New();\n                        dirCont->InsertElement(0, dir);\n                        m_DirectionsContainer->InsertElement(idx, dirCont);\n                    }\n                    else\n                        dirCont->InsertElement(dirCont->Size(), dir);\n                }\n                else\n                {\n                    dirCont->InsertElement(0, dir);\n                    m_DirectionsContainer->InsertElement(idx, dirCont);\n                }\n\n                continue;\n            }\n\n            double frac_x = contIndex[0] - index[0];\n            double frac_y = contIndex[1] - index[1];\n            double frac_z = contIndex[2] - index[2];\n\n            if (frac_x<0)\n            {\n                index[0] -= 1;\n                frac_x += 1;\n            }\n            if (frac_y<0)\n            {\n                index[1] -= 1;\n                frac_y += 1;\n            }\n            if (frac_z<0)\n            {\n                index[2] -= 1;\n                frac_z += 1;\n            }\n\n            frac_x = 1-frac_x;\n            frac_y = 1-frac_y;\n            frac_z = 1-frac_z;\n\n            // int coordinates inside image?\n            if (index[0] < 0 || (unsigned long)index[0] >= outImageSize[0]-1)\n                continue;\n            if (index[1] < 0 || (unsigned long)index[1] >= outImageSize[1]-1)\n                continue;\n            if (index[2] < 0 || (unsigned long)index[2] >= outImageSize[2]-1)\n                continue;\n\n            DirectionContainerType::Pointer dirCont;\n            int idx;\n            wDir = dir;\n            double weight = (  frac_x)*(  frac_y)*(  frac_z);\n            if (weight>m_Thres)\n            {\n                wDir *= weight;\n                idx = index[0]   + outImageSize[0]*(index[1]  + outImageSize[1]*index[2]  );\n                dirCont = DirectionContainerType::New();\n                if (m_DirectionsContainer->IndexExists(idx))\n                {\n                    dirCont = m_DirectionsContainer->GetElement(idx);\n                    if (dirCont.IsNull())\n                    {\n                        dirCont = DirectionContainerType::New();\n                        dirCont->InsertElement(0, wDir);\n                        m_DirectionsContainer->InsertElement(idx, dirCont);\n                    }\n                    else\n                        dirCont->InsertElement(dirCont->Size(), wDir);\n                }\n                else\n                {\n                    dirCont->InsertElement(0, wDir);\n                    m_DirectionsContainer->InsertElement(idx, dirCont);\n                }\n            }\n\n            wDir = dir;\n            weight = (  frac_x)*(1-frac_y)*(  frac_z);\n            if (weight>m_Thres)\n            {\n                wDir *= weight;\n                idx = index[0]   + outImageSize[0]*(index[1]+1+ outImageSize[1]*index[2]  );\n                dirCont = DirectionContainerType::New();\n                if (m_DirectionsContainer->IndexExists(idx))\n                {\n                    dirCont = m_DirectionsContainer->GetElement(idx);\n                    if (dirCont.IsNull())\n                    {\n                        dirCont = DirectionContainerType::New();\n                        dirCont->InsertElement(0, wDir);\n                        m_DirectionsContainer->InsertElement(idx, dirCont);\n                    }\n                    else\n                        dirCont->InsertElement(dirCont->Size(), wDir);\n                }\n                else\n                {\n                    dirCont->InsertElement(0, wDir);\n                    m_DirectionsContainer->InsertElement(idx, dirCont);\n                }\n            }\n\n            wDir = dir;\n            weight = (  frac_x)*(  frac_y)*(1-frac_z);\n            if (weight>m_Thres)\n            {\n                wDir *= weight;\n                idx = index[0]   + outImageSize[0]*(index[1]  + outImageSize[1]*index[2]+outImageSize[1]);\n                dirCont = DirectionContainerType::New();\n                if (m_DirectionsContainer->IndexExists(idx))\n                {\n                    dirCont = m_DirectionsContainer->GetElement(idx);\n                    if (dirCont.IsNull())\n                    {\n                        dirCont = DirectionContainerType::New();\n                        dirCont->InsertElement(0, wDir);\n                        m_DirectionsContainer->InsertElement(idx, dirCont);\n                    }\n                    else\n                        dirCont->InsertElement(dirCont->Size(), wDir);\n                }\n                else\n                {\n                    dirCont->InsertElement(0, wDir);\n                    m_DirectionsContainer->InsertElement(idx, dirCont);\n                }\n            }\n\n            wDir = dir;\n            weight = (  frac_x)*(1-frac_y)*(1-frac_z);\n            if (weight>m_Thres)\n            {\n                wDir *= weight;\n                idx = index[0]   + outImageSize[0]*(index[1]+1+ outImageSize[1]*index[2]+outImageSize[1]);\n                dirCont = DirectionContainerType::New();\n                if (m_DirectionsContainer->IndexExists(idx))\n                {\n                    dirCont = m_DirectionsContainer->GetElement(idx);\n                    if (dirCont.IsNull())\n                    {\n                        dirCont = DirectionContainerType::New();\n                        dirCont->InsertElement(0, wDir);\n                        m_DirectionsContainer->InsertElement(idx, dirCont);\n                    }\n                    else\n                        dirCont->InsertElement(dirCont->Size(), wDir);\n                }\n                else\n                {\n                    dirCont->InsertElement(0, wDir);\n                    m_DirectionsContainer->InsertElement(idx, dirCont);\n                }\n            }\n\n            wDir = dir;\n            weight = (1-frac_x)*(  frac_y)*(  frac_z);\n            if (weight>m_Thres)\n            {\n                wDir *= weight;\n                idx = index[0]+1 + outImageSize[0]*(index[1]  + outImageSize[1]*index[2]  );\n                dirCont = DirectionContainerType::New();\n                if (m_DirectionsContainer->IndexExists(idx))\n                {\n                    dirCont = m_DirectionsContainer->GetElement(idx);\n                    if (dirCont.IsNull())\n                    {\n                        dirCont = DirectionContainerType::New();\n                        dirCont->InsertElement(0, wDir);\n                        m_DirectionsContainer->InsertElement(idx, dirCont);\n                    }\n                    else\n                        dirCont->InsertElement(dirCont->Size(), wDir);\n                }\n                else\n                {\n                    dirCont->InsertElement(0, wDir);\n                    m_DirectionsContainer->InsertElement(idx, dirCont);\n                }\n            }\n\n            wDir = dir;\n            weight = (1-frac_x)*(  frac_y)*(1-frac_z);\n            if (weight>m_Thres)\n            {\n                wDir *= weight;\n                idx = index[0]+1 + outImageSize[0]*(index[1]  + outImageSize[1]*index[2]+outImageSize[1]);\n                dirCont = DirectionContainerType::New();\n                if (m_DirectionsContainer->IndexExists(idx))\n                {\n                    dirCont = m_DirectionsContainer->GetElement(idx);\n                    if (dirCont.IsNull())\n                    {\n                        dirCont = DirectionContainerType::New();\n                        dirCont->InsertElement(0, wDir);\n                        m_DirectionsContainer->InsertElement(idx, dirCont);\n                    }\n                    else\n                        dirCont->InsertElement(dirCont->Size(), wDir);\n                }\n                else\n                {\n                    dirCont->InsertElement(0, wDir);\n                    m_DirectionsContainer->InsertElement(idx, dirCont);\n                }\n            }\n\n            wDir = dir;\n            weight = (1-frac_x)*(1-frac_y)*(  frac_z);\n            if (weight>m_Thres)\n            {\n                wDir *= weight;\n                idx = index[0]+1 + outImageSize[0]*(index[1]+1+ outImageSize[1]*index[2]  );\n                dirCont = DirectionContainerType::New();\n                if (m_DirectionsContainer->IndexExists(idx))\n                {\n                    dirCont = m_DirectionsContainer->GetElement(idx);\n                    if (dirCont.IsNull())\n                    {\n                        dirCont = DirectionContainerType::New();\n                        dirCont->InsertElement(0, wDir);\n                        m_DirectionsContainer->InsertElement(idx, dirCont);\n                    }\n                    else\n                        dirCont->InsertElement(dirCont->Size(), wDir);\n                }\n                else\n                {\n                    dirCont->InsertElement(0, wDir);\n                    m_DirectionsContainer->InsertElement(idx, dirCont);\n                }\n            }\n\n            wDir = dir;\n            weight = (1-frac_x)*(1-frac_y)*(1-frac_z);\n            if (weight>m_Thres)\n            {\n                wDir *= weight;\n                idx = index[0]+1 + outImageSize[0]*(index[1]+1+ outImageSize[1]*index[2]+outImageSize[1]);\n                dirCont = DirectionContainerType::New();\n                if (m_DirectionsContainer->IndexExists(idx))\n                {\n                    dirCont = m_DirectionsContainer->GetElement(idx);\n                    if (dirCont.IsNull())\n                    {\n                        dirCont = DirectionContainerType::New();\n                        dirCont->InsertElement(0, wDir);\n                        m_DirectionsContainer->InsertElement(idx, dirCont);\n                    }\n                    else\n                        dirCont->InsertElement(dirCont->Size(), wDir);\n                }\n                else\n                {\n                    dirCont->InsertElement(0, wDir);\n                    m_DirectionsContainer->InsertElement(idx, dirCont);\n                }\n            }\n        }\n        clock.Stop();\n    }\n\n    vtkSmartPointer<vtkCellArray> m_VtkCellArray = vtkSmartPointer<vtkCellArray>::New();\n    vtkSmartPointer<vtkPoints>    m_VtkPoints = vtkSmartPointer<vtkPoints>::New();\n\n    itk::ImageRegionIterator<ItkUcharImgType> dirIt(m_NumDirectionsImage, m_NumDirectionsImage->GetLargestPossibleRegion());\n    itk::ImageRegionIterator<ItkUcharImgType> crossIt(m_CrossingsImage, m_CrossingsImage->GetLargestPossibleRegion());\n\n    m_DirectionImageContainer = DirectionImageContainerType::New();\n    unsigned int maxNumDirections = 0;\n\n    MITK_INFO << \"Clustering directions\";\n    boost::progress_display disp2(outImageSize[0]*outImageSize[1]*outImageSize[2]);\n    for(crossIt.GoToBegin(); !crossIt.IsAtEnd(); ++crossIt)\n    {\n        ++disp2;\n        OutputImageType::IndexType index = crossIt.GetIndex();\n        int idx = index[0]+(index[1]+index[2]*outImageSize[1])*outImageSize[0];\n\n        if (!m_DirectionsContainer->IndexExists(idx))\n        {\n            ++dirIt;\n            continue;\n        }\n        DirectionContainerType::Pointer dirCont = m_DirectionsContainer->GetElement(idx);\n        if (dirCont.IsNull() || index[0] < 0 || (unsigned long)index[0] >= outImageSize[0] || index[1] < 0 || (unsigned long)index[1] >= outImageSize[1] || index[2] < 0 || (unsigned long)index[2] >= outImageSize[2])\n        {\n            ++dirIt;\n            continue;\n        }\n\n        std::vector< DirectionType > directions;\n\n        for (unsigned int i=0; i<dirCont->Size(); i++)\n            if (dirCont->ElementAt(i).magnitude()>0.0001)\n                directions.push_back(dirCont->ElementAt(i));\n\n        if (!directions.empty())\n            directions = FastClustering(directions);\n\n        std::sort( directions.begin(), directions.end(), CompareVectorLengths );\n\n        if ( directions.size() > maxNumDirections )\n        {\n            for (unsigned int i=maxNumDirections; i<std::min<unsigned int>(directions.size(), m_MaxNumDirections); i++)\n            {\n                ItkDirectionImageType::Pointer directionImage = ItkDirectionImageType::New();\n                directionImage->SetSpacing( spacing );\n                directionImage->SetOrigin( origin );\n                directionImage->SetDirection( direction );\n                directionImage->SetRegions( imageRegion );\n                directionImage->Allocate();\n                Vector< float, 3 > nullVec; nullVec.Fill(0.0);\n                directionImage->FillBuffer(nullVec);\n                m_DirectionImageContainer->InsertElement(i, directionImage);\n            }\n            maxNumDirections = std::min<unsigned int>(directions.size(), m_MaxNumDirections);\n        }\n\n        unsigned int numDir = directions.size();\n        if (numDir>m_MaxNumDirections)\n            numDir = m_MaxNumDirections;\n\n        for (unsigned int i=0; i<numDir; i++)\n        {\n            vtkSmartPointer<vtkPolyLine> container = vtkSmartPointer<vtkPolyLine>::New();\n            itk::ContinuousIndex<double, 3> center;\n            center[0] = index[0];\n            center[1] = index[1];\n            center[2] = index[2];\n            itk::Point<double> worldCenter;\n            m_MaskImage->TransformContinuousIndexToPhysicalPoint( center, worldCenter );\n            DirectionType dir = directions.at(i);\n\n            // set direction image pixel\n            ItkDirectionImageType::Pointer directionImage = m_DirectionImageContainer->GetElement(i);\n            Vector< float, 3 > pixel;\n            pixel.SetElement(0, dir[0]);\n            pixel.SetElement(1, dir[1]);\n            pixel.SetElement(2, dir[2]);\n            directionImage->SetPixel(index, pixel);\n\n            // add direction to vector field (with spacing compensation)\n            itk::Point<double> worldStart;\n            worldStart[0] = worldCenter[0]-dir[0]/2*minSpacing;\n            worldStart[1] = worldCenter[1]-dir[1]/2*minSpacing;\n            worldStart[2] = worldCenter[2]-dir[2]/2*minSpacing;\n            vtkIdType id = m_VtkPoints->InsertNextPoint(worldStart.GetDataPointer());\n            container->GetPointIds()->InsertNextId(id);\n            itk::Point<double> worldEnd;\n            worldEnd[0] = worldCenter[0]+dir[0]/2*minSpacing;\n            worldEnd[1] = worldCenter[1]+dir[1]/2*minSpacing;\n            worldEnd[2] = worldCenter[2]+dir[2]/2*minSpacing;\n            id = m_VtkPoints->InsertNextPoint(worldEnd.GetDataPointer());\n            container->GetPointIds()->InsertNextId(id);\n            m_VtkCellArray->InsertNextCell(container);\n        }\n        dirIt.Set(numDir);\n        ++dirIt;\n    }\n\n    vtkSmartPointer<vtkPolyData> directionsPolyData = vtkSmartPointer<vtkPolyData>::New();\n    directionsPolyData->SetPoints(m_VtkPoints);\n    directionsPolyData->SetLines(m_VtkCellArray);\n    m_OutputFiberBundle = mitk::FiberBundleX::New(directionsPolyData);\n}\n\n\ntemplate< class PixelType >\nstd::vector< vnl_vector_fixed< double, 3 > > TractsToVectorImageFilter< PixelType >::FastClustering(std::vector< vnl_vector_fixed< double, 3 > >& inDirs)\n{\n    std::vector< vnl_vector_fixed< double, 3 > > outDirs;\n    if (inDirs.empty())\n        return outDirs;\n    vnl_vector_fixed< double, 3 > oldMean, currentMean, workingMean;\n\n    std::vector< vnl_vector_fixed< double, 3 > > normalizedDirs;\n    std::vector< int > touched;\n    for (unsigned int i=0; i<inDirs.size(); i++)\n    {\n        normalizedDirs.push_back(inDirs[i]);\n        normalizedDirs.back().normalize();\n    }\n\n    // initialize\n    double max = 0.0;\n    touched.resize(inDirs.size(), 0);\n    bool free = true;\n    currentMean = inDirs[0];  // initialize first seed\n    while (free)\n    {\n        oldMean.fill(0.0);\n\n        // start mean-shift clustering\n        double angle = 0.0;\n        int counter = 0;\n        while ((currentMean-oldMean).magnitude()>0.0001)\n        {\n            counter = 0;\n            oldMean = currentMean;\n            workingMean = oldMean;\n            workingMean.normalize();\n            currentMean.fill(0.0);\n            for (unsigned int i=0; i<normalizedDirs.size(); i++)\n            {\n                angle = dot_product(workingMean, normalizedDirs[i]);\n                if (angle>=m_AngularThreshold)\n                {\n                    currentMean += inDirs[i];\n                    touched[i] = 1;\n                    counter++;\n                }\n                else if (-angle>=m_AngularThreshold)\n                {\n                    currentMean -= inDirs[i];\n                    touched[i] = 1;\n                    counter++;\n                }\n            }\n        }\n\n        // found stable mean\n        if (counter>0)\n        {\n            currentMean /= counter;\n            double mag = currentMean.magnitude();\n\n            if (mag>0)\n            {\n                if (mag>max)\n                    max = mag;\n\n                outDirs.push_back(currentMean);\n            }\n        }\n\n        // find next unused seed\n        free = false;\n        for (unsigned int i=0; i<touched.size(); i++)\n            if (touched[i]==0)\n            {\n                currentMean = inDirs[i];\n                free = true;\n            }\n    }\n\n    if (m_NormalizeVectors)\n        for (unsigned int i=0; i<outDirs.size(); i++)\n            outDirs[i].normalize();\n    else if (max>0)\n        for (unsigned int i=0; i<outDirs.size(); i++)\n            outDirs[i] /= max;\n\n    if (inDirs.size()==outDirs.size())\n        return outDirs;\n    else\n        return FastClustering(outDirs);\n}\n\n\ntemplate< class PixelType >\nstd::vector< vnl_vector_fixed< double, 3 > > TractsToVectorImageFilter< PixelType >::Clustering(std::vector< vnl_vector_fixed< double, 3 > >& inDirs)\n{\n    std::vector< vnl_vector_fixed< double, 3 > > outDirs;\n    if (inDirs.empty())\n        return outDirs;\n    vnl_vector_fixed< double, 3 > oldMean, currentMean, workingMean;\n\n    std::vector< vnl_vector_fixed< double, 3 > > normalizedDirs;\n    std::vector< int > touched;\n    for (std::size_t i=0; i<inDirs.size(); i++)\n    {\n        normalizedDirs.push_back(inDirs[i]);\n        normalizedDirs.back().normalize();\n    }\n\n    // initialize\n    double max = 0.0;\n    touched.resize(inDirs.size(), 0);\n    for (std::size_t j=0; j<inDirs.size(); j++)\n    {\n        currentMean = inDirs[j];\n        oldMean.fill(0.0);\n\n        // start mean-shift clustering\n        double angle = 0.0;\n        int counter = 0;\n        while ((currentMean-oldMean).magnitude()>0.0001)\n        {\n            counter = 0;\n            oldMean = currentMean;\n            workingMean = oldMean;\n            workingMean.normalize();\n            currentMean.fill(0.0);\n            for (std::size_t i=0; i<normalizedDirs.size(); i++)\n            {\n                angle = dot_product(workingMean, normalizedDirs[i]);\n                if (angle>=m_AngularThreshold)\n                {\n                    currentMean += inDirs[i];\n                    counter++;\n                }\n                else if (-angle>=m_AngularThreshold)\n                {\n                    currentMean -= inDirs[i];\n                    counter++;\n                }\n            }\n        }\n\n        // found stable mean\n        if (counter>0)\n        {\n            bool add = true;\n            vnl_vector_fixed< double, 3 > normMean = currentMean;\n            normMean.normalize();\n            for (std::size_t i=0; i<outDirs.size(); i++)\n            {\n                vnl_vector_fixed< double, 3 > dir = outDirs[i];\n                dir.normalize();\n                if ((normMean-dir).magnitude()<=0.0001)\n                {\n                    add = false;\n                    break;\n                }\n            }\n\n            currentMean /= counter;\n            if (add)\n            {\n                double mag = currentMean.magnitude();\n                if (mag>0)\n                {\n                    if (mag>max)\n                        max = mag;\n\n                    outDirs.push_back(currentMean);\n                }\n            }\n        }\n    }\n\n    if (m_NormalizeVectors)\n        for (std::size_t i=0; i<outDirs.size(); i++)\n            outDirs[i].normalize();\n    else if (max>0)\n        for (std::size_t i=0; i<outDirs.size(); i++)\n            outDirs[i] /= max;\n\n    if (inDirs.size()==outDirs.size())\n        return outDirs;\n    else\n        return FastClustering(outDirs);\n}\n\n\ntemplate< class PixelType >\nTractsToVectorImageFilter< PixelType >::DirectionContainerType::Pointer TractsToVectorImageFilter< PixelType >::MeanShiftClustering(DirectionContainerType::Pointer dirCont)\n{\n    DirectionContainerType::Pointer container = DirectionContainerType::New();\n\n    double max = 0;\n    for (DirectionContainerType::ConstIterator it = dirCont->Begin(); it!=dirCont->End(); ++it)\n    {\n        vnl_vector_fixed<double, 3> mean = ClusterStep(dirCont, it.Value());\n\n        if (mean.is_zero())\n            continue;\n        bool addMean = true;\n\n        for (DirectionContainerType::ConstIterator it2 = container->Begin(); it2!=container->End(); ++it2)\n        {\n            vnl_vector_fixed<double, 3> dir = it2.Value();\n            double angle = fabs(dot_product(mean, dir)/(mean.magnitude()*dir.magnitude()));\n            if (angle>=m_Epsilon)\n            {\n                addMean = false;\n                break;\n            }\n        }\n\n        if (addMean)\n        {\n            if (m_NormalizeVectors)\n                mean.normalize();\n            else if (mean.magnitude()>max)\n                max = mean.magnitude();\n            container->InsertElement(container->Size(), mean);\n        }\n    }\n\n    // max normalize voxel directions\n    if (max>0 && !m_NormalizeVectors)\n        for (std::size_t i=0; i<container->Size(); i++)\n            container->ElementAt(i) /= max;\n\n    if (container->Size()<dirCont->Size())\n        return MeanShiftClustering(container);\n    else\n        return container;\n}\n\n\ntemplate< class PixelType >\nvnl_vector_fixed<double, 3> TractsToVectorImageFilter< PixelType >::ClusterStep(DirectionContainerType::Pointer dirCont, vnl_vector_fixed<double, 3> currentMean)\n{\n    vnl_vector_fixed<double, 3> newMean; newMean.fill(0);\n\n    for (DirectionContainerType::ConstIterator it = dirCont->Begin(); it!=dirCont->End(); ++it)\n    {\n        vnl_vector_fixed<double, 3> dir = it.Value();\n        double angle = dot_product(currentMean, dir)/(currentMean.magnitude()*dir.magnitude());\n        if (angle>=m_AngularThreshold)\n            newMean += dir;\n        else if (-angle>=m_AngularThreshold)\n            newMean -= dir;\n    }\n\n    if (fabs(dot_product(currentMean, newMean)/(currentMean.magnitude()*newMean.magnitude()))>=m_Epsilon || newMean.is_zero())\n        return newMean;\n    else\n        return ClusterStep(dirCont, newMean);\n}\n}\n\n\n\n", "meta": {"hexsha": "b431eff1661cc23843e2294f54d1007b298ed5f7", "size": 29521, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToVectorImageFilter.cpp", "max_stars_repo_name": "lsanzdiaz/MITK-BiiG", "max_stars_repo_head_hexsha": "470f04e7585a60672f449716a1c595a5ba3fcd24", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-03-05T05:29:32.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-05T05:29:32.000Z", "max_issues_repo_path": "Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToVectorImageFilter.cpp", "max_issues_repo_name": "lsanzdiaz/MITK-BiiG", "max_issues_repo_head_hexsha": "470f04e7585a60672f449716a1c595a5ba3fcd24", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Modules/DiffusionImaging/FiberTracking/Algorithms/itkTractsToVectorImageFilter.cpp", "max_forks_repo_name": "lsanzdiaz/MITK-BiiG", "max_forks_repo_head_hexsha": "470f04e7585a60672f449716a1c595a5ba3fcd24", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-27T06:51:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-27T06:51:01.000Z", "avg_line_length": 35.4393757503, "max_line_length": 215, "alphanum_fraction": 0.5342637445, "num_tokens": 6892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.23146209301246015}}
{"text": "#include \"precompiled.h\"\n#include \"finite_difference_weights.h\"\n\n#ifndef AUTOMATIC_PRECOMPILATION\n#include <utility>\n#include <tbb/tick_count.h>\n#include <tbb/partitioner.h>\n#include <boost/throw_exception.hpp>\n#endif\n\n#include \"Eigen.h\"\n#include \"utility.h\"\n#include \"Math.h\"\n\n#ifndef AUTOMATIC_PRECOMPILATION\n#include <pretty_printer.h>\n#endif\n\n#include \"finite_difference_stencils.h\"\n#include \"logging.h\"\n#include \"finite_difference_weights_algo.h\"\n#include \"grid_striding_info_inline.h\"\n#include \"global_config.h\"\n#include \"exceptions.h\"\n#include \"PDE.h\"\n\nnamespace fipster { namespace finite_difference_weights {\n\n\t// #################################################\n\t// ##############   PHASE 2:\t\t\t############\n\t// ##############   Node Factories      ############\n\t// #################################################\n\n\tfdweights::sender_ptr fdweights::setup_node( const arg_t& arg )\n\t{\n\t\tauto PDE=arg.first.PDE;\n\n\t\tauto pde = dynamic_pointer_cast<const BSiso>(PDE);\n\t\tif(pde) return create_node(body_t<const BSiso>(arg,pde));\n\n\t\t// check for different PDEs\n\t\t// auto pde = dynamic_cast<const DifferenPDE* >(PDE);\n\t\t// if(pde) return create_node(body_t<const ...>(arg,pde));\n\n\t\tFIPSTER_THROW_EXCEPTION(runtime_error(\"PDE type \"+PDE->type+\" not implemented!\"));\n\t\treturn 0;\n\t}\n\n\n\t// #################################################\n\t// ##############   PHASE 3:\t\t\t############\n\t// ##############   Node Bodies         ############\n\t// #################################################\n\n\n\tusing namespace Eigen;\n\n\ttemplate<class PDE_core>\n\tbody_t<PDE_core>::body_t( const fd_weights_arg_t& args\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t, shared_ptr<const PDE_core> pde_ptr ) \n\t\t:\tpde(pde_ptr),args(args),D(args.second->D)\n\t{}\n\n\n\t//############################################################################\n\t//Constructs the multi_indices corresponding to partial derivatives    \n\tint references::generatePDindices(uint order)\n\t{\n\t\tuint i__,i__1,i__2,i__3,k,j;\n\t\tbool more;\n\t\t/* Calculate number of partial derivatives to include */\n\t\tint numpds = 0;\n\t\ti__1 = order;\n\t\tfor (i__ = 1; i__ <= i__1; ++i__) {\n\t\t\ti__2 = i__ + D - 1;\n\t\t\ti__3 = D - 1;\n\t\t\tnumpds += (int) binom(i__2, i__3);\n\t\t}\n\n\t\tmulti_indices.resize(numpds,D);\n\t\tposition_t ind(D);\n\t\tmore=0;\n\t\tj = 0;\n\t\t/* Calculate multi indices for partial derivatives */\n\t\ti__1 = numpds;\n\t\tint h,t;\n\t\tfor (i__ = 0; i__ < i__1; ++i__) {\n\t\t\tif (! more) {\n\t\t\t\t++j;\n\t\t\t\tif (j > order)\n\t\t\t\t\tBOOST_THROW_EXCEPTION(invalid_argument(\n\t\t\t\t\t\"Number of Partial derivatives is to high. Specified order exceeded\"));\n\t\t\t}\n\t\t\tcomp_next(j, D, &ind[0], &more, &h, &t);\n\t\t\tfor (k = 0; k < D; ++k) {\n\t\t\t\tmulti_indices(i__,k) = ind[k];\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn numpds;\n\t}\n\n\t//############################################################################\n\t// Compute line-wise constant factorials in denominator for weight optimization systems\n\tvoid references::generateFactorialDenoms(double HigherOrderWeight){\n\n\t\tfactorialdenoms.resize(multi_indices.rows());\n\n\t\tuint j;\t\n\n\t\tfor (int i = 0; i < factorialdenoms.size(); ++i) {\n\t\t\tuint sum=0;\n\t\t\tfactorialdenoms[i]=1.0;\n\t\t\tfor (j=0; j < D; ++j) {\n\t\t\t\tfactorialdenoms[i] /= factorial(multi_indices(i,j));\n\t\t\t\tif(multi_indices(i,j)!=0) sum++;\n\t\t\t}\n\t\t\tif (sum>2)\n\t\t\t\tfactorialdenoms[i] *= HigherOrderWeight;\n\t\t}\n\t}\n\n\ttemplate<class F,class G, class H, class I >\n\tvoid test_A_o(const F& A_o, const G& A_io, const H& gsi, const I& stencil_points){\n\t\tauto& grid=*gsi.grid;\n\t\tauto end_b = grid.template b_end<J_SGS>();\t\t\t\n\t\tset<boundary_index<J_SGS-1>> obinds;\n\t\tfor(auto bit = boundary_iterator<J_SGS>(grid); bit != end_b; ++bit)\n\t\t{\n\t\t\tobinds.clear();\n\n\t\t\t//loop over neighbors\n\t\t\tconst auto s_end=end(gsi.sorted_neighs);\n\t\t\tfor(auto s=begin(gsi.sorted_neighs);s!=s_end;++s){\n\t\t\t\t//get neighbor position\n\t\t\t\tauto pos=bit.pos()+stencil_points.at(s->second);\n\t\t\t\t//check, if points lies on outer boundary:\n\t\t\t\tboundary_index<J_SGS-1> obind;\n\t\t\t\tif(obind.make_ind_from_pos<true>(pos,grid)){\n\t\t\t\t\tFIPSTER_ASSERT(A_o.coeff(bit.b_ind,obind)\n\t\t\t\t\t\t\t\t\t\t==A_io.at(s->second).at(bit.g_ind));\n\t\t\t\t\tif(A_io.at(s->second).at(bit.g_ind)!=0)\n\t\t\t\t\t\tobinds.insert(obind);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//compare number of nonzeros in this A_o row and the number of unique accesses\n\t\t\tFIPSTER_ASSERT(obinds.size()==\n\t\t\t\t\t\t\t\t\t\t\t(uint)A_o->innerVector(bit.b_ind.ind).nonZeros());\n\t\t}\n\t}\n\n\t//############################################################################\n\t/** Generate the finite difference weights for the selected stencil,\n\t\tto get a finite difference approximation of the differential operator.\n\t\t\n\t\tIt's exactly done as described in  the paper \n\t\t\"Ito, K., & Toivanen, J. (2009). Lagrange Multiplier Approach with \n\t\tOptimized Finite Difference Stencils for Pricing American Options \n\t\tunder Stochastic Volatility. SIAM Journal on Scientific Computing, \n\t\t31(4), 2646. doi:10.1137/07070574X\"\n\t\n\t\tWith the following additions:\n\t\t1. The sign choices specified in PDE.h dicate that the weights \n\t\t\tconstitute a NEGATIVE M-MATRIX. \n\t\t2. This is achieved by using non-negative least squares for the off-diagonal weights,\n\t\t\tas opposed to the proposed solution of a quadratic programming problem.\n\t\t3. Extension to higher dimensional PDEs\n\t\t4. Eq. 40 contains (dx_i)^delta_i. I use 0^0 = 1 (Reason: If there is no \n\t\t\tderivative present in one direction (delta_i=0) then it is \n\t\t\tignored (i.e. factor 1). In all other cases a stepsize of \n\t\t\tzero in one direction (dx_i=0) will yield a 0 in the matrix d.)\n\t\n\t\t \\todo verbesserung: wie vorgeschlagen, die partiellen Ableitungen\n\t\t die man mit einem gröberen Gitter erhällt für die optimierung\n\t\t benutzen...\n\t\n\t\\return 1. A 2D array, where each row corresponds to one point in the multi-dim \n\t\t\tgrid and the i-th column represent the weights of the i-th stencil point,\n\t\t\tif sorted lexicically by its direction vector. The last weight \n\t\t\tcorresponds to the unfinished (see note) center weight.\n\t\t\t2. The so called \"grid_striding_info\"\n\n\t\\note To get the final center weight all non-center weights have\n\t\t\tto be subtracted.\n\n\t*/\n\ttemplate<class PDE_core>\n\ttypename body_t<PDE_core>::result_sptr_t body_t<PDE_core>::operator()( const input_t& )\n\t{\n\t\tconst grid_ptr& grid = args.second;\n\t\t\n\t\t//gcc: was editable_result(new result_t) (i.e. possibly without initizalitaion?)\n\t\tfd_weights_result_ptr_t result = make_shared<result_t>(); \n\n\t\t//create object to hold stuff\n\t\treferences r(D);\n\n\t\t//#### Create Stencil Points (excl. center point), sorted, such that:\n\t\t// [ points(i) , points(points.size()-i-1) ] is\n\t\t// the i-th direction\n\t\t\n\t\ttry{\n\n\t\t\tr.stencil_points.construct(D,args.first.stencil_type);\n\n\t\t}catch(boost::exception& e){\n\t\t\te<<boost::errinfo_file_name((\"Stencil Type \"+toS(args.first.stencil_type)).c_str());\n\t\t\tthrow;\n\t\t}\n\t\n\t\tuint proper_neighs=r.stencil_points.proper_neighs();\n\n\t\t//#### Allocate result memory (+1 for center weights)\n\t\tauto end_ind = result->A_io.resize(*grid,r.stencil_points.nDirs());\n\n\t\t//#### Construct the multi_indices corresponding to partial derivatives\n\t\tuint numpds = r.generatePDindices(args.first.partial_derivative_order);\n\t\t\n\t\tthread_logger()<<\"WEIGHTS| for \"+toS(proper_neighs)+\" neighbors and \"+toS(numpds)+\" of PDE terms\"<<endl;\n\t\t\n\t\tif(0){cout<<\"X\"<<endl;\n\t\tcout<<\"WEIGHTS| for \"+toS(proper_neighs)+\" neighbors and \"+toS(numpds)+\" of PDE terms\"<<endl;\n\t\tcout<<args.first<<endl;\n\t\t}\n\t\t//#### Check, if weight (unconstrained) determination is not overdetermined: \n\t\tif (numpds == proper_neighs) \n\t\t\tthread_logger()<<\"WEIGHTS| (unconstrained weights) are NOT overdetermined\"<<endl;\n\t\telse if (numpds < proper_neighs)\n\t\t\tthread_logger()<<\"WEIGHTS| (unconstrained weights) are UNDERDETERMINED and not unique!\"<<endl;\n\n\t\t//####  Compute line wise constant factorials in denominator \n\t\tr.generateFactorialDenoms(args.first.higher_order_weight);\n\n\t\t//###### Optimize weights in parallel ( minimze norm: | D*w - b |) \n\t\t{\tusing namespace tbb;\n\t\t\toptimize_body<fd_weights_result_t::A_io_t,body_t<PDE_core>> body\n\t\t\t\t(r,result->A_io,pde,*grid);\n\t\t\tthread_logger()<<\"WEIGHTS| nSites: \"<<end_ind.ind<<endl;\n\t\t\ttick_count t0 = tick_count::now();\n\t\t\tparallel_reduce(\n\t\t\t\tblocked_range<grid_index<sg>>(grid_index<sg>(),end_ind,100),\n\t\t\t\tbody/*,simple_partitioner()*/);\n\t\t\ttick_count t1 = tick_count::now();\n\t\t\tthread_logger()<<\"WEIGHTS| DONE, maxNorm:\"<<scientific <<setprecision(3)<<\n\t\t\t\tbody.max_norm <<\" in \" <<(t1-t0).seconds()<<\"s\"<<endl;\n\t\t}\n\n\t\t//###### create information for decoupled tridiagonal systems in each splitting direction\n\t\t//###### AND A_o\n\t\ttick_count t0 = tick_count::now();\n\n\t\tauto b_end = grid->b_end<sg>();\n\n\t\tauto& gsi = *new grid_striding_info_collection<sg>(r.stencil_points.nDirs(),r.stencil_points,grid);\n\t\tthread_logger()<< \"&gsi: \" << &gsi << endl;\n\t\tresult->grid_striding_infos.reset(&gsi);\t\t\n\n\t\tauto& A_io=result->A_io;\n\t\tauto& A_o=*result->A_o;\n\t\tA_o.resize(*grid);\n\n\t\t//test for uniqueness of the systems:\n\t\t//map<pair<int,int>,int> m;\n\n\t\tA_o->reserve(VectorXi::Constant(grid->Nbound[J_SGS],proper_neighs));\n\n\t\t//iterate over boundary and check for system beginnings\n\t\tfor(connected_set_setup_iterator<sg> it(*grid);it!=b_end;++it){\n\n\t\t\t//cout<<\"at \"<<it.inner_start_g_ind().ind<<endl;\n\n\t\t\tauto i = r.stencil_points.dir_it();\n\t\t\tfor(;i.valid();++i){//iterate through all directions\n\t\t\t\tauto& dir = r.stencil_points[i];\n\t\t\t\tif(it.apply_dir(dir)){//if a system in this direction exists\n\t\t\t\t\t\n\t\t\t\t\t//cout<<\"dir: \"<<dir.transpose()<<endl;\n\n\t\t\t\t\t/*\n\t\t\t\t\t//test for uniqueness of the system:\n\t\t\t\t\t//The naive test, that identifies a system\n\t\t\t\t\t//via its order start and end point on the inner boundary\n\t\t\t\t\t//fails in D>2, as a corner (of the inner boundary) can \n\t\t\t\t\t//belong to more than one system (in D>2)!\n\t\t\t\t\t//int a=it.inner_start_b_ind().ind;int b=it.inner_end_b_ind.ind;\n\t\t\t\t\t//use this instead:\n\t\t\t\t\tint a=it.outer_start_b_ind().ind;int b=it.outer_end_b_ind().ind;\n\t\t\t\t\tif(a==2 && b==2){\n\t\t\t\t\t\tcout<<\"pos: \"<<it.it.pos.transpose()<<endl;\n\t\t\t\t\t\tcout<<\"dir: \"<<dir.transpose()<<endl;\n\t\t\t\t\t}\n\t\t\t\t\tm[make_pair(min(a,b),max(a,b))]++;\n\t\t\t\t\tif(m[make_pair(min(a,b),max(a,b))]>1){\n\t\t\t\t\t\tcout<<m[make_pair(min(a,b),max(a,b))]<<\" Systems found between \"<<min(a,b)<<\" and \"<<max(a,b)<<endl;\n\t\t\t\t\t}\n\t\t\t\t\t*/\n\n\t\t\t\t\t//add subsystem\n\t\t\t\t\tgsi.at(i).pushback_connected_set(it);\n\t\t\t\t\t\n\t\t\t\t\tbool debug = false;///\\todo: set false\n\n\t\t\t\t\t//add A_o corresponding to start of system \n\t\t\t\t\tA_o.insert(it.inner_start_b_ind(),it.outer_start_b_ind,\n\t\t\t\t\t\t\t\t(debug?1:A_io.at_opposite(i)[it.inner_start_g_ind()]));\n\t\t\t\t\t\n\t\t\t\t\t//cout<<it.inner_start_g_ind().ind<<\": \"<<A_io.at_opposite(i)[it.inner_start_g_ind()]<<endl;\n\t\t\t\t\t//cout<<it.inner_end_g_ind.ind<<\": \"<<A_io.at(i)[it.inner_end_g_ind]<<endl;\n\n\t\t\t\t\t//add A_o corresponding to end of system \n\t\t\t\t\tA_o.insert(it.inner_end_b_ind,it.outer_end_b_ind,\n\t\t\t\t\t\t\t\t(debug?1:A_io.at(i)[it.inner_end_g_ind]));\n\n\t\t\t\t\t///\\todo: check for natural boundaries (i.e. all A_o=0 on bound)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tA_o->makeCompressed();\n\n\t\tif(global_config::get().test_A_o){\n\t\t\ttest_A_o(A_o,A_io,gsi,r.stencil_points);\n\t\t}\n\n\t\t//A_o.print();\n\n\t\ttick_count t1 = tick_count::now();\n\t\tthread_logger()<<\"WEIGHTS| DONE systems information in \"<<scientific <<setprecision(3)\n\t\t\t<<(t1-t0).seconds()<<\"s\"<<endl;\n\n\t\treturn result;\n\t}\n\n\n\n}}\n", "meta": {"hexsha": "49a17cbd907169955e8c86a348ed044331b6ca36", "size": 11178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/finite_difference_weights.cpp", "max_stars_repo_name": "johannesgerer/fipster", "max_stars_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-29T14:33:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-29T14:33:37.000Z", "max_issues_repo_path": "src/finite_difference_weights.cpp", "max_issues_repo_name": "johannesgerer/fipster", "max_issues_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/finite_difference_weights.cpp", "max_forks_repo_name": "johannesgerer/fipster", "max_forks_repo_head_hexsha": "10e840e01d196cddef75bf3eeb427f720b3e0ad6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0710059172, "max_line_length": 106, "alphanum_fraction": 0.6435856146, "num_tokens": 3171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.23143434572366223}}
{"text": "/******************************************************************************\n *   Copyright (C) 2006-2021 by the resistivity.net development team          *\n *   Carsten Rücker carsten@resistivity.net                                   *\n *                                                                            *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");          *\n *   you may not use this file except in compliance with the License.         *\n *   You may obtain a copy of the License at                                  *\n *                                                                            *\n *       http://www.apache.org/licenses/LICENSE-2.0                           *\n *                                                                            *\n *   Unless required by applicable law or agreed to in writing, software      *\n *   distributed under the License is distributed on an \"AS IS\" BASIS,        *\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n *   See the License for the specific language governing permissions and      *\n *   limitations under the License.                                           *\n *                                                                            *\n ******************************************************************************/\n\n#include \"bertJacobian.h\"\n\n#include <calculateMultiThread.h>\n#include <elementmatrix.h>\n#include <memwatch.h>\n#include <meshentities.h>\n#include <shape.h>\n#include <stopwatch.h>\n\n#include <shape.h>\n\nnamespace GIMLI{\n\n#if USE_BOOST_THREAD\n    #include <boost/thread.hpp>\n    boost::mutex eraseMutex__;\n#else\n    #include <thread>\n    #include <mutex>\n    std::mutex eraseMutex__;\n#endif\n\ntemplate < class ValueType > class CreateSensitivityColMT : public GIMLI::BaseCalcMT{\npublic:\n  CreateSensitivityColMT(Matrix < ValueType >          & S,\n                         const std::vector < Cell * >  & para,\n                         const DataContainerERT        & data,\n                         const Matrix < ValueType >    & pots,\n                         const std::map< long, uint >  & currPatternIdx,\n                         const RVector                 & weights,\n                         const RVector                 & k,\n                         bool calc1,\n                         bool verbose)\n    : BaseCalcMT(verbose), S_(&S), para_(&para), //cellMapIndex_ (&cellMapIndex),\n        data_(&data), pots_(&pots), currPatternIdx_(&currPatternIdx),\n        weights_(&weights), k_(&k), calc1_(calc1){\n            nData_ = data.size();\n            nElecs_ = data.sensorCount();\n    }\n\n    virtual ~CreateSensitivityColMT(){}\n\n    virtual void calc(){\n\n        if (calc1_){\n            calc1();\n        }else {\n            calc2();\n        }\n    }\n\n    virtual void calc2(){\n        ElementMatrix < double > S_i;\n        ElementMatrix < double > S1_i;\n\n        Cell * cell = NULL;\n        int modelIdx = 0;\n\n        const Vector < ValueType > *va;\n        const Vector < ValueType > *vb;\n        const Vector < ValueType > *vm;\n        const Vector < ValueType > *vn;\n        Vector < ValueType > dummy((*pots_)[0].size(), ValueType(0));\n\n        const RVector *da = &(*data_)(\"a\");\n        const RVector *db = &(*data_)(\"b\");\n        const RVector *dm = &(*data_)(\"m\");\n        const RVector *dn = &(*data_)(\"n\");\n\n        for (Index cellID = start_; cellID < end_; cellID ++) {\n\n            cell    = (*para_)[cellID];\n            modelIdx = cell->marker();\n\n            if (modelIdx < 0) continue;\n\n            S1_i.ux2uy2uz2(*cell);\n\n            for (Index kIdx = 0; kIdx < weights_->size(); kIdx ++){\n                S_i.u2(*cell);\n                S_i *= (*k_)[kIdx] * (*k_)[kIdx];\n                S_i += S1_i;\n                int a = 0, b = 0, m = 0, n = 0;\n                for (Index dataIdx = 0; dataIdx < nData_; dataIdx ++ ){\n\n                    a = (int)(*da)[dataIdx];\n                    b = (int)(*db)[dataIdx];\n                    m = (int)(*dm)[dataIdx];\n                    n = (int)(*dn)[dataIdx];\n\n                    if (a > -1) va = &(*pots_)[a + nElecs_ * kIdx]; else va = &dummy;\n                    if (b > -1) vb = &(*pots_)[b + nElecs_ * kIdx]; else vb = &dummy;\n                    if (m > -1) vm = &(*pots_)[m + nElecs_ * kIdx]; else vm = &dummy;\n                    if (n > -1) vn = &(*pots_)[n + nElecs_ * kIdx]; else vn = &dummy;\n\n                    (*S_)[dataIdx][modelIdx] +=\n                       S_i.mult((*va), (*vb), (*vm), (*vn)) * (*weights_)[kIdx];\n                }\n            }\n        }\n    }\n\n    virtual void calc1(){\n        // log(Debug, \"Thread #\" + str(_threadNumber) + \": on CPU \" + str(schedGetCPU()) +\n        //            \" slice \" + str(start_) + \":\" + str(end_));\n        bool haveCurrentPatterns = false;\n\n        if (currPatternIdx_->size() * weights_->size() == pots_->rows()) {\n        //** we have current and measurements pattern instead of pol pol potentials;\n            haveCurrentPatterns = true;\n        }\n\n        ElementMatrix < double > S_i;\n        Cell * cell = NULL;\n        int modelIdx = 0;\n        // Index si, sj;\n\n        const Vector < ValueType > *va;\n        const Vector < ValueType > *vb;\n        const Vector < ValueType > *vm;\n        const Vector < ValueType > *vn;\n\n        const RVector *da = &(*data_)(\"a\");\n        const RVector *db = &(*data_)(\"b\");\n        const RVector *dm = &(*data_)(\"m\");\n        const RVector *dn = &(*data_)(\"n\");\n\n        Vector < ValueType > dummy((*pots_)[0].size(), ValueType(0));\n\n        for (Index cellID = start_; cellID < end_; cellID ++) {\n\n            cell    = (*para_)[cellID];\n            modelIdx = cell->marker();\n\n            if (modelIdx < 0) continue;\n\n            if (verbose_) {\n                // \tcout << \"\\r\";\n                // \tfor (int i = 0; i < tNr; i ++) cout << \"\\t\\t\\t\";\n                // \tcout <<\tcellID << \"/\" << para_->size() - 1;\n            }\n\n            S_i.ux2uy2uz2(*cell);\n            Index cellNodeCount = cell->nodeCount();\n\n//             ValueType tmpPotA = ValueType(0);\n//             ValueType tmpPotM = ValueType(0);\n            ValueType sum = ValueType(0);\n\n            int a = 0, b = 0, m = 0, n = 0;\n\n            double weightsFactor = 1.0;\n            //** if weights_->size() > 1, assuming 2.5D so we need to double the weights\n            //** we integrate from 0 to \\infty but need we need from -\\infty to \\infty\n            if (weights_->size() > 1) weightsFactor = 2.0;\n\n            for (Index dataIdx = 0; dataIdx < nData_; dataIdx ++ ){\n\n                if (haveCurrentPatterns){\n                    a = currPatternIdx_->find(data_->electrodeToCurrentPattern(a, b))->second;\n                    m = currPatternIdx_->find(data_->electrodeToCurrentPattern(m, n))->second;\n                    b = -1;\n                    n = -1;\n                } else {\n                    a = (int)(*da)[dataIdx];\n                    b = (int)(*db)[dataIdx];\n                    m = (int)(*dm)[dataIdx];\n                    n = (int)(*dn)[dataIdx];\n                }\n\n                for (Index kIdx = 0; kIdx < weights_->size(); kIdx ++){\n                    sum = ValueType(0);\n\n                    if (a > -1) va = &(*pots_)[a + nElecs_ * kIdx]; else va = &dummy;\n                    if (b > -1) vb = &(*pots_)[b + nElecs_ * kIdx]; else vb = &dummy;\n                    if (m > -1) vm = &(*pots_)[m + nElecs_ * kIdx]; else vm = &dummy;\n                    if (n > -1) vn = &(*pots_)[n + nElecs_ * kIdx]; else vn = &dummy;\n\n                    (*S_)[dataIdx][modelIdx] += S_i.mult((*va), (*vb), (*vm), (*vn)) * (weightsFactor * (*weights_)[kIdx]);\n                    continue;\n//                     std::cout << cell->id() << std::endl;\n                    for (Index i = 0; i < cellNodeCount; i ++){\n//                         si = S_i.idx(i);\n//                         std::cout << cell->node(i).id() << std::endl;\n                        for (Index j = 0; j < cellNodeCount; j ++){\n//                             sj = S_i.idx(j);\n                            // very most time criticle section here\n//                             tmpPotA  = (*va)[si] - (*vb)[si];\n//                             tmpPotM  = (*vm)[sj] - (*vn)[sj];\n//\n//                             sum += S_i.getVal(i, j) * tmpPotA * tmpPotM;\n\n//                             sum += S_i.getVal(i, j) *\n//                                     ((*va)[si] - (*vb)[si]) *\n//                                     ((*vm)[sj] - (*vn)[sj]);\n                            sum += S_i.getVal(i, j) *\n                                    ((*va)[S_i.idx(i)] - (*vb)[S_i.idx(i)]) *\n                                    ((*vm)[S_i.idx(j)] - (*vn)[S_i.idx(j)]);\n\n                      /*  std::cout << i<<\" \"<<j<<\" \"<< S_i.getVal(i, j)<<\" \"<< (*va)[S_i.idx(i)]<<\" \"<<\n                        (*vb)[S_i.idx(i)]<<\" \"<< (*vm)[S_i.idx(j)]<<\" \"<< (*vn)[S_i.idx(j)] << std::endl;\n                      */\n                        }\n                    }\n                    if (isInfNaN(sum)){\n                        std::cerr << WHERE_AM_I << std::endl;\n                    }\n// \t  if ((*cellMapIndex_)[cellID] - 2 < 0 ||\n// \t       (*cellMapIndex_)[cellID] - 2 > nModel-1){\n// \t    std::cerr << WHERE_AM_I << \" index out of bounds: [0 -- \" << nModel-1 << \"]\" << cellMapIndex[cellID] - 2 << std::endl;\n// \t  }\n\n//\t  (*S_)[dataIdx][(*cellMapIndex_)[cellID] - 2] += sum * (data_->k(dataIdx) * 2.0 * (*weights_)[kIdx]);\n\n                    /*! Dangerous!!! mt writing into matrix*/\n\t       //(*S_)[dataIdx][(*cellMapIndex_)[cellID]] += sum * (2.0 * (*weights_)[kIdx]);\n                    {\n//                   #ifdef HAVE_LIBBOOST_THREAD\n//                   boost::mutex::scoped_lock lock(eraseMutex__); // slows down alot\n//                   #endif\n\n                        (*S_)[dataIdx][modelIdx] += sum * (weightsFactor * (*weights_)[kIdx]);\n//                         std::cout << \"b: \" << dataIdx<<\" \"<<modelIdx<<\" \"<<(*S_)[dataIdx][modelIdx]<< \" \"\n//                         << sum * (weightsFactor * (*weights_)[kIdx]) << std::endl;\n                    }\n//                     exit(1);\n                } // for each k\n//                      exit(1);\n            } // for each data\n        } // for each cellID\n    }\n\nprotected:\n    Matrix < ValueType >            * S_;\n    const std::vector < Cell * >    * para_;\n    const DataContainerERT          * data_;\n    const Matrix < ValueType >      * pots_;\n    const std::map< long, uint >    * currPatternIdx_;\n    const RVector                   * weights_;\n    const RVector                   * k_;\n    uint                            nData_;\n    uint                            nElecs_;\n    bool                            calc1_;\n\n};\n\nbool lessCellMarker(const Cell * c1, const Cell * c2) { return c1->marker() < c2->marker(); }\n\ntemplate < class ValueType >\nvoid createSensitivityCol_(Matrix < ValueType > & S,\n                          const Mesh & mesh,\n                          const DataContainerERT & data,\n                          const Matrix < ValueType > & pots,\n                          const RVector & weights,\n                          const RVector & k,\n                          std::vector < std::pair < Index, Index > > & matrixClusterIds,\n                          uint nThreads, bool verbose){\n\nMEMINFO\n\n    Index nData  = data.size();\n    Index nModel = max(mesh.cellMarkers()) + 1;\n    Index maxRows = weights.size() * data.sensorCount();\n\n    if (pots.rows() >= maxRows){\n//         if (pots[0].size() < mesh.nodeCount()){\n//             std::stringstream str; str << WHERE_AM_I << \" potential matrix colsize to small. \"\n//                                        << pots[0].size()  << \"< \" << mesh.nodeCount() << std::endl;\n//         }\n    } else {\n        std::stringstream str1; str1 << WHERE_AM_I << \" potential matrix rowsize to small.\"\n                                   << pots.rows() << \" < \" << maxRows << std::endl;\n        throwLengthError(str1.str());\n    }\n\n    Stopwatch swatch(true);\n    std::map< long, uint > currPatternIdx;\n    //std::cout << \"CreateSensitivityColMT \" << nThreads << std::endl;\n\n    std::vector< Cell * > cells(mesh.findCellByMarker(0, -1));\n    std::sort(cells.begin(), cells.end(), lessCellMarker);\n\n    double maxMemSize = max(0.0, getEnvironment(\"SENSMATMAXMEM\", 0.0, verbose));\n    double maxSizeNeeded = mByte((double)nData * nModel * sizeof(double));\n\n    if (maxMemSize > 0 && verbose){\n        std::cout << \"Size of S: \" << maxSizeNeeded << \" MB\" << std::endl;\n    }\n\n    //** avoid MT problems\n    for (std::vector< Cell * >::iterator it = cells.begin();\n         it != cells.end(); it ++){\n        (*it)->pShape()->invJacobian();\n    }\n\n//     ShapeFunctionCache::instance().shapeFunctions(cells[0]->shape());\n//     ShapeFunctionCache::instance().deriveShapeFunctions(cells[0]->shape(), 0);\n//     ShapeFunctionCache::instance().deriveShapeFunctions(cells[0]->shape(), 1);\n//     ShapeFunctionCache::instance().deriveShapeFunctions(cells[0]->shape(), 2);\n//     ShapeFunctionCache::instance().shapeFunctions(*cells[0]);\n//     ShapeFunctionCache::instance().deriveShapeFunctions(*cells[0], 0);\n//     ShapeFunctionCache::instance().deriveShapeFunctions(*cells[0], 1);\n//     ShapeFunctionCache::instance().deriveShapeFunctions(*cells[0], 2);\n//     //cells[0]->createShapefunctionts();\n\n    if (maxMemSize > 0 && maxMemSize < maxSizeNeeded){\n\n        uint modelCluster = std::floor((double)nModel / (maxSizeNeeded / maxMemSize));\n\n        if (modelCluster < 1) {\n            throwError(WHERE_AM_I + \" sorry, size of single sensitivity-row exceeds memory limitations.\");\n        }\n\n        std::cout << \"Size of S cluster: \" << mByte((double)nData * modelCluster * sizeof(ValueType)) << \" MB\" << std::endl;\n        std::cout << \"Using model cluster \" << nModel << \" x \" << modelCluster << std::endl;\n\n        S.resize(nData, modelCluster);\n\n        matrixClusterIds.clear();\n        matrixClusterIds.push_back(std::pair < Index, Index >(nData, nModel));\n\n        bool calc1 = getEnvironment(\"SENSMAT1\", false, true);\n        for (uint i = 0; i < nModel; i += modelCluster ){\nMEMINFO\n            Index start = i;\n            Index end   = min(start + modelCluster, nModel);\n            std::cout << \" \" << start << \" \" << end<< std::endl;\n\n            S.resize(nData, end - start);\n\n            std::vector< Cell * > cellsCluster(mesh.findCellByMarker(start, end));\n            std::sort(cellsCluster.begin(), cellsCluster.end(), lessCellMarker);\n\nMEMINFO\n            // subtract marker start index\n            for (std::vector< Cell * >::iterator it = cellsCluster.begin(); it != cellsCluster.end(); it ++){\n                (*it)->setMarker((*it)->marker() - start);\n            }\n\n            S *= ValueType(0);\nMEMINFO\n\n            distributeCalc(CreateSensitivityColMT< ValueType >(S, cellsCluster,\n                                                               data, pots,\n                                                               currPatternIdx,\n                                                               weights, k,\n                                                               calc1,\n                                                               verbose),\n                           cellsCluster.size(), nThreads, verbose);\n\nMEMINFO\n\n            //** fight against the Lorenz butterfly\n            //** 1e-8 is to coarse, need adaptive tolerance\n            //S.round(1e-8);\nMEMINFO\n\n            S.save(\"sensPart_\" + str(start) + \"-\" + str(end));\n\n            matrixClusterIds.push_back(std::pair < Index, Index >(start, end));\n\n            // add marker start index\n            for (std::vector< Cell * >::iterator it = cellsCluster.begin(); it != cellsCluster.end(); it ++){\n                (*it)->setMarker((*it)->marker() + start);\n            }\nMEMINFO\n        }\n\n        S.clear();\n    } else {\n\n        // __MS(nData << \" \"<< S.rows() << \" \"<<  nModel << \" \"<<  S.cols())\n        if (S.rows() != nData || S.cols() != nModel) S.resize(nData, nModel);\n        S *= ValueType(0);\nMEMINFO\n\n        if (verbose){\n            std::cout << \"S(\" << numberOfCPU() << \"/\" << nThreads; //**check!!!\n            #if USE_BOOST_THREAD\n            std::cout << \"-boost::mt\";\n            #else\n            std::cout << \"-std::mt\";\n            #endif\n            std::cout << \"): \" << swatch.duration() << \":\";\n//swatch.stop(verbose);\n        }\n        bool calc1 = getEnvironment(\"SENSMAT1\", false, true);\n        distributeCalc(CreateSensitivityColMT< ValueType >(S, cells, data,\n                                                           pots, currPatternIdx,\n                                                           weights, k, calc1, verbose),\n                        cells.size(), nThreads, verbose);\n         if (verbose){\n             swatch.stop(verbose);\n         }\nMEMINFO\n        //** fight against the Lorenz butterfly\n        //** 1e-8 is to coarse, need adaptive tolerance\n        //S.round(1e-8);\n    }\n}\n\nvoid createSensitivityCol(RMatrix & S,\n                          const Mesh & mesh,\n                          const DataContainerERT & data,\n                          const RMatrix & pots,\n                          const RVector & weights,\n                          const RVector & k,\n                          std::vector < std::pair < Index, Index > > & matrixClusterIds,\n                          uint nThreads, bool verbose){\n    createSensitivityCol_(S, mesh, data, pots, weights, k, matrixClusterIds, nThreads, verbose);\n}\n\nvoid createSensitivityCol(CMatrix & S,\n                          const Mesh & mesh,\n                          const DataContainerERT & data,\n                          const CMatrix & pots,\n                          const RVector & weights,\n                          const RVector & k,\n                          std::vector < std::pair < Index, Index > > & matrixClusterIds,\n                          uint nThreads, bool verbose){\n    createSensitivityCol_(S, mesh, data, pots, weights, k, matrixClusterIds, nThreads, verbose);\n}\n\n\nvoid sensitivityDCFEMSingle(const std::vector < Cell * > & para, const RVector & p1, const RVector & p2,\n\t\t       RVector & sens, bool verbose){\n    uint nCells = para.size();\n    if (sens.size() != nCells) sens.resize(nCells);\n\n    ElementMatrix < double > S_i;\n    double sum = 0.0, a_jk = 0.0, tmppot = 0.0;\n    //  cout << nCells << std::endl;\n\n    for (uint i = 0; i < nCells; i ++){\n    //cout << \"Nr. \" << i << std::endl;\n        S_i.ux2uy2uz2(*para[i]);\n\n        sum = 0.0;\n        for (int j = 0, jmax = para[i]->nodeCount(); j < jmax; j ++){\n            for (int k = 0, kmax = para[i]->nodeCount(); k < kmax; k ++){\n\t       a_jk = S_i.getVal(j, k);\n\t       tmppot = p1[S_i.idx(j)] * p2[S_i.idx(k)];\n\t       sum += a_jk * tmppot;\n\t//\tcout << \"\\tS_mn: \" << a_jk << \"\\tp1*p2: \" << tmppot << \"\\tp*S_mn: \" << a_jk * tmppot << \"\\tsum: \" << sum << std::endl;\n            }\n        }\n        sens[i] = sum;\n    }\n}\n\nRVector prepExportSensitivityData(const Mesh & mesh, const RVector & data, double logdrop){\n    Index nModel = unique(sort(mesh.cellMarkers())).size();\n\n    ASSERT_EQUAL(nModel, data.size())\n\n    //data have always the right length since it comes from S directly\n    RVector modelSizes(nModel, 0.0);\n    for (Index i = 0; i < mesh.cellCount(); i ++ ){\n        modelSizes[mesh.cell(i).marker()] += mesh.cell(i).size();\n    }\n\n    return logTransDropTol(data/modelSizes, logdrop, true)(mesh.cellMarkers());\n\n    // //RVector tmp(data/mesh.cellSizes());\n    // if ((uint)data.size() != (uint)mesh.cellCount()){\n\n    //     throwLengthError(WHERE_AM_I + \" Datasize missmatch: \" + str(mesh.cellCount())+\n    //                         \" \" + str(data.size()));\n    // } else {\n    //     //for (uint i = 0; i < tmp.size(); i ++) tmp[i] = tmp[i] / mesh.cell(i).shape().domainSize();\n    // }\n    // RVector tmp(data/mesh.cellSizes());\n\n    // RVector s(sign(tmp));\n\n    // double tmpMax = max(abs(tmp));\n    // tmp /= tmpMax;\n\n    // for (uint i = 0; i < tmp.size(); i ++) {\n    //     tmp[i] = std::fabs(tmp[i] / logdrop);\n    //     if (tmp[i] < 1.0) tmp[i] = 1.0;\n    // }\n\n    // tmp = log10(tmp);\n    // tmp /= max(tmp) * s;\n    // return tmp;\n}\n\nvoid exportSensitivityVTK(const std::string & fileName,\n                          const Mesh & mesh, const RVector & data,\n                          double logdrop){\n    std::map< std::string, RVector > res;\n    res.insert(std::make_pair(\"Sensitivity\" ,\n                              prepExportSensitivityData(mesh, data, logdrop)));\n    mesh.exportVTK(fileName, res);\n}\n\n// void exportSensMatrixDC(const std::string & filename, const Mesh & mesh, const RMatrix & S) {\n//     exportSensMatrixDC(filename, mesh, S\n// }\n\nvoid exportSensMatrixDC(const std::string & filename, const Mesh & mesh,\n                        const RMatrix & S, const IVector & idx,\n                        double logdrop) {\n    std::map< std::string, RVector > res;\n\n    for (std::map < std::string, RVector >::const_iterator\n            it = mesh.dataMap().begin();\n            it != mesh.dataMap().end(); it ++){\n        res.insert(std::make_pair(it->first, it->second));\n    }\n\n    std::string add;\n//     RVector tmp(mesh.cellCount());\n\n    for (size_t i = 0; i < S.rows(); i ++) {\n        if (i < 100000) add = \"0\";\n        if (i < 10000) add = \"00\";\n        if (i < 1000) add = \"000\";\n        if (i < 100) add = \"0000\";\n        if (i < 10) add = \"00000\";\n\n//         for (uint j = 0; j < tmp.size(); j ++) tmp[j] = S[i][mesh.cell(j).marker()];\n\n//#res.insert(std::make_pair(\"sens-\" + add + str(i), log10(RVector(abs(tmp)))));\n\n            res.insert(std::make_pair(\"sens-\" + add + str(i),\n                        prepExportSensitivityData(mesh, S[i], logdrop)));\n\n   }\n   mesh.exportVTK(filename, res);\n}\n\nRVector coverageDC(const RMatrix & sensMatrix) {\n    RVector cov;\n    if (sensMatrix.rows() > 0) {\n        cov.resize(sensMatrix.cols(), 0.0);\n\n        for (size_t i = 0; i < sensMatrix.rows(); i ++) {\n            cov += abs(sensMatrix[i]);\n        }\n    } else {\n        std::cout << \"Sensmatrix invalid\" << std::endl;\n    }\n    return cov;\n}\n\nRVector coverageDCtrans(const MatrixBase & S, const RVector & dd, const RVector & mm) {\n    RVector cov;\n\n    if (S.rows() > 0) {\n        cov.resize(S.cols(), 0.0);\n    } else {\n        std::cout << \"Sensmatrix invalid\" << std::endl;\n    }\n\n    if (S.rtti() == GIMLI_MATRIX_RTTI){\n        const RMatrix *Sl = dynamic_cast < const RMatrix * >(&S);\n\n        for (size_t i = 0; i < S.rows(); i ++) {\n            cov += abs((*Sl)[i] * dd[i]);\n        }\n    } else if (S.rtti() == GIMLI_SPARSE_MAP_MATRIX_RTTI){\n\n        const RSparseMapMatrix * Sl = dynamic_cast< const RSparseMapMatrix * >(&S);\n\n        for (RSparseMapMatrix::const_iterator it = Sl->begin(); it != Sl->end(); it ++){\n            Index row = (*it).first.first;\n            Index col = (*it).first.second;\n            cov[col] += (*it).second * dd[row];\n        }\n    } else {\n        CERR_TO_IMPL\n    }\n\n    return cov / abs(mm);\n}\n\nRVector createCoverage(const MatrixBase & S, const Mesh & mesh){\n    return createCoverage(S, mesh, RVector(S.rows(), 1.0), RVector(S.cols(), 1.0));\n}\n\nRVector createCoverage(const MatrixBase & S, const Mesh & mesh,\n                       const RVector & response, const RVector & model){\n\n    RVector covModel(coverageDCtrans(S, 1.0 / response, 1.0 / model));\n\tRVector covMesh(covModel(mesh.cellMarkers()));\n    if (mesh.cellCount() == model.size()) {\n        covMesh /= mesh.cellSizes();\n    } else {\n        RVector modelCellSizes(covMesh.size(), 0.0);\n        for (Index i = 0; i < mesh.cellCount(); i ++){\n            Cell *c = &mesh.cell(i);\n            modelCellSizes[c->marker()] += c->shape().domainSize();\n        }\n        if (min(modelCellSizes) > TOLERANCE){\n            covMesh /= modelCellSizes;\n        } else {\n            log(Error, \"Coverage fails:\" + str(mesh.cellCount()) + \" \" + str(model.size()));\n        }\n    }\n\n    return covMesh;\n}\n} // namespace GIMLI\n", "meta": {"hexsha": "a9348dfe437a4bbc20cf1d8256fe9296c158d423", "size": 24076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/bert/bertJacobian.cpp", "max_stars_repo_name": "JuliusHen/gimli", "max_stars_repo_head_hexsha": "a5c5779261acfe5a53015c9ee6f7c9ed2dd6c57f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 224.0, "max_stars_repo_stars_event_min_datetime": "2015-02-20T21:36:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:27:43.000Z", "max_issues_repo_path": "core/src/bert/bertJacobian.cpp", "max_issues_repo_name": "JuliusHen/gimli", "max_issues_repo_head_hexsha": "a5c5779261acfe5a53015c9ee6f7c9ed2dd6c57f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 341.0, "max_issues_repo_issues_event_min_datetime": "2015-05-21T14:39:51.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T01:54:07.000Z", "max_forks_repo_path": "core/src/bert/bertJacobian.cpp", "max_forks_repo_name": "JuliusHen/gimli", "max_forks_repo_head_hexsha": "a5c5779261acfe5a53015c9ee6f7c9ed2dd6c57f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2015-01-24T14:40:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-25T12:12:13.000Z", "avg_line_length": 38.5833333333, "max_line_length": 126, "alphanum_fraction": 0.4731683004, "num_tokens": 6019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7057850154599563, "lm_q2_score": 0.3276683139517237, "lm_q1q2_score": 0.23126338602815513}}
{"text": "#include <memory>\n#include <chrono>\n#include <tuple>\n#include <unistd.h>\n#include <gflags/gflags.h>\n#include <string.h>\n#include <assert.h>\n#include <Eigen/StdVector>\n\n#include \"drake/solvers/snopt_solver.h\"\n#include \"drake/systems/analysis/simulator.h\"\n#include \"drake/systems/framework/diagram.h\"\n#include \"drake/systems/framework/diagram_builder.h\"\n#include \"drake/multibody/parsing/parser.h\"\n#include <drake/multibody/inverse_kinematics/inverse_kinematics.h>\n#include \"drake/geometry/geometry_visualization.h\"\n#include \"drake/solvers/solve.h\"\n\n#include \"common/find_resource.h\"\n#include \"systems/trajectory_optimization/dircon/dircon.h\"\n#include \"multibody/kinematic/world_point_evaluator.h\"\n#include \"solvers/nonlinear_constraint.h\"\n#include \"multibody/kinematic/distance_evaluator.h\"\n#include \"multibody/multibody_utils.h\"\n#include \"multibody/visualization_utils.h\"\n#include \"multibody/kinematic/kinematic_constraints.h\"\n\n#include \"examples/Spirit/animate_spirit.h\"\n#include \"examples/Spirit/spirit_utils.h\"\n\nDEFINE_double(duration, 1, \"The stand duration\");\nDEFINE_double(front2BackToeDistance, 0.35, \"Nominal distance between the back and front toes.\");\nDEFINE_double(side2SideToeDistance, 0.2, \"Nominal distance between the back and front toes.\");\nDEFINE_double(bodyHeight, 0.104, \"The spirit body start height (defined in URDF)\");\nDEFINE_double(lowerHeight,0.15, \"The sitting height of the bottom of the robot\");\nDEFINE_double(upperHeight, 0.35, \"The standing height.\");\nDEFINE_double(inputCost, 3, \"The standing height.\");\nDEFINE_double(velocityCost, 10, \"The standing height.\");\nDEFINE_double(eps, 1e-2, \"The wiggle room.\");\nDEFINE_double(optTol, 1e-4,\"Optimization Tolerance\");\nDEFINE_double(feasTol, 1e-4,\"Feasibility Tolerance\");\nDEFINE_bool(autodiff, false, \"Double or autodiff version\");\nDEFINE_bool(runInitTraj, false, \"Animate initial conditions?\");\n// Parameters which enable dircon-improving features\nDEFINE_bool(scale_constraint, true, \"Scale the nonlinear constraint values\");\nDEFINE_bool(scale_variable, false, \"Scale the decision variable\");\n\nusing drake::AutoDiffXd;\nusing drake::multibody::MultibodyPlant;\nusing drake::geometry::SceneGraph;\nusing drake::multibody::Parser;\nusing drake::trajectories::PiecewisePolynomial;\n\nusing Eigen::Vector3d;\nusing Eigen::VectorXd;\nusing Eigen::Matrix3d;\nusing Eigen::MatrixXd;\n\nnamespace dairlib {\nnamespace {\n\nusing systems::trajectory_optimization::DirconModeSequence;\nusing systems::trajectory_optimization::DirconMode;\nusing systems::trajectory_optimization::Dircon;\nusing systems::trajectory_optimization::KinematicConstraintType;\n\nusing std::vector;\nusing std::cout;\nusing std::endl;\n\n\ntemplate <typename T>\nvoid addConstraints(const MultibodyPlant<T>& plant, Dircon<T>& trajopt){\n  // Get position and velocity dictionaries \n  int num_knotpoints =10; ///DEBUG\n  auto positions_map = multibody::makeNameToPositionsMap(plant);\n  auto velocities_map = multibody::makeNameToVelocitiesMap(plant);\n  auto x0 = trajopt.initial_state();\n  auto xmid = trajopt.state_vars(0, (num_knotpoints - 1) / 2);\n  // auto xf = trajopt.final_state();\n\n\n  // Initial body positions\n  trajopt.AddBoundingBoxConstraint(-FLAGS_eps, FLAGS_eps, x0(positions_map.at(\"base_x\"))); // Give the initial condition room to choose the x_init position (helps with positive knee constraint)\n  trajopt.AddBoundingBoxConstraint(-FLAGS_eps, FLAGS_eps, x0(positions_map.at(\"base_y\")));\n  trajopt.AddBoundingBoxConstraint(FLAGS_lowerHeight-FLAGS_eps, FLAGS_lowerHeight+FLAGS_eps, x0(positions_map.at(\"base_z\")));\n  \n  // Mid body positions\n  trajopt.AddBoundingBoxConstraint(-0, 0, xmid(positions_map.at(\"base_x\"))); // Give the initial condition room to choose the x_init position (helps with positive knee constraint)\n  trajopt.AddBoundingBoxConstraint(-0, 0, xmid(positions_map.at(\"base_y\")));\n  trajopt.AddBoundingBoxConstraint(FLAGS_upperHeight-FLAGS_eps, FLAGS_upperHeight+FLAGS_eps, xmid(positions_map.at(\"base_z\")));\n\n  return;\n}\n\n  /// See runSpiritSquat()\n    // std::unique_ptr<MultibodyPlant<T>> plant_ptr,\n    // MultibodyPlant<double>* plant_double_ptr,\n    // std::unique_ptr<SceneGraph<double>> scene_graph_ptr,\n    // double duration,\n    // PiecewisePolynomial<double> init_x_traj,\n    // PiecewisePolynomial<double> init_u_traj,\n    // vector<PiecewisePolynomial<double>> init_l_traj,\n    // vector<PiecewisePolynomial<double>> init_lc_traj,\n    // vector<PiecewisePolynomial<double>> init_vc_traj\n  ///\n  /// Given an initial guess for state, control, and forces optimizes a standing behaviour for the spirit robot\ntemplate <typename T>\nvoid runSpiritSquat(\n    std::unique_ptr<MultibodyPlant<T>> plant_ptr,\n    MultibodyPlant<double>* plant_double_ptr,\n    std::unique_ptr<SceneGraph<double>> scene_graph_ptr,\n    double duration,\n    PiecewisePolynomial<double> init_x_traj,\n    PiecewisePolynomial<double> init_u_traj,\n    vector<PiecewisePolynomial<double>> init_l_traj,\n    vector<PiecewisePolynomial<double>> init_lc_traj,\n    vector<PiecewisePolynomial<double>> init_vc_traj\n    ) {\n\n  drake::systems::DiagramBuilder<double> builder;\n  MultibodyPlant<T>& plant = *plant_ptr;\n  SceneGraph<double>& scene_graph =\n      *builder.AddSystem(std::move(scene_graph_ptr));\n  \n  // Get position and velocity dictionaries \n  auto positions_map = multibody::makeNameToPositionsMap(plant);\n  auto velocities_map = multibody::makeNameToVelocitiesMap(plant);\n  /// For Spirit front left leg->0, back left leg->1, front right leg->2, back right leg->3\n  /// Get the frame of each toe and attach a world point to the toe tip (frame is at toe ball center).\n\n  int num_legs = 4;\n  double toeRadius = 0.02; // Radius of toe ball\n  Vector3d toeOffset(toeRadius,0,0); // vector to \"contact point\"\n  double mu = 1; // Coeff of friction\n  \n\n  int num_knotpoints_per_mode = 10; \n  \n\n  auto sequence = DirconModeSequence<T>(plant);\n\n  dairlib::ModeSequenceHelper msh;\n  \n  msh.addMode( // FIRST MODE 1\n    (Eigen::Matrix<bool,1,4>() << 1,1,1,1 ).finished(), // contact bools \n    num_knotpoints_per_mode,  // number of knot points in the collocation\n    Eigen::Vector3d::UnitZ(), // normal\n    Eigen::Vector3d::Zero(),  // world offset\n    mu //friction\n    );\n\n  // auto [modeVector, toeEvals, toeEvalSets] = createSpiritModeSequence(plant, msh.modes , msh.knots , msh.normals , msh.offsets, msh.mus, msh.minTs, msh.maxTs);\n  auto [modeVector, toeEvals, toeEvalSets] = createSpiritModeSequence(plant, msh);\n  \n  for (auto& mode : modeVector){\n    for (int i = 0; i < num_legs; i++ ){\n      mode->MakeConstraintRelative(i,0);\n      mode->MakeConstraintRelative(i,1);\n    }\n    mode->SetDynamicsScale(\n      {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, 1.0 / 150.0);\n    mode->SetKinVelocityScale(\n      {0, 1, 2, 3}, {0, 1, 2}, 1.0 / 500.0 * 500 * 1 / 1);\n    sequence.AddMode(mode.get());\n  }          \n\n\n \n  \n\n  ///Setup trajectory optimization\n  auto trajopt = Dircon<T>(sequence);\n\n  // Set up Trajectory Optimization options\n  trajopt.SetSolverOption(drake::solvers::SnoptSolver::id(),\n                           \"Print file\", \"../snopt.out\");\n  trajopt.SetSolverOption(drake::solvers::SnoptSolver::id(),\n                           \"Major iterations limit\", 20000);\n  trajopt.SetSolverOption(drake::solvers::SnoptSolver::id(), \"Iterations limit\", 100000);\n  trajopt.SetSolverOption(drake::solvers::SnoptSolver::id(),\n                           \"Major optimality tolerance\",\n                           FLAGS_optTol);  // target optimality\n  trajopt.SetSolverOption(drake::solvers::SnoptSolver::id(), \"Major feasibility tolerance\", FLAGS_feasTol);\n  trajopt.SetSolverOption(drake::solvers::SnoptSolver::id(), \"Verify level\",\n                           0);  // 0\n\n    // Add duration constraint, currently constrained not bounded\n  trajopt.AddDurationBounds(0, duration*2);\n  // Initialize the trajectory control state and forces\n  for (int j = 0; j < sequence.num_modes(); j++) {\n    trajopt.drake::systems::trajectory_optimization::MultipleShooting::\n        SetInitialTrajectory(init_u_traj, init_x_traj);\n    trajopt.SetInitialForceTrajectory(j, init_l_traj[j], init_lc_traj[j],\n                                      init_vc_traj[j]);\n  }\n\n  /// Setup all the optimization constraints \n  int num_knotpoints = trajopt.N(); // number of knot points total in the collocation\n  int n_v = plant.num_velocities();\n  // int n_q = plant.num_positions();\n  auto u = trajopt.input();\n  auto x = trajopt.state();\n  auto x0 = trajopt.initial_state();\n  auto xmid = trajopt.state_vars(0, (num_knotpoints - 1) / 2);\n  auto xf = trajopt.final_state();\n  addConstraints(plant,trajopt);\n\n  // // Initial body positions\n  // trajopt.AddBoundingBoxConstraint(-FLAGS_eps, FLAGS_eps, x0(positions_map.at(\"base_x\"))); // Give the initial condition room to choose the x_init position (helps with positive knee constraint)\n  // trajopt.AddBoundingBoxConstraint(-FLAGS_eps, FLAGS_eps, x0(positions_map.at(\"base_y\")));\n  // trajopt.AddBoundingBoxConstraint(FLAGS_lowerHeight-FLAGS_eps, FLAGS_lowerHeight+FLAGS_eps, x0(positions_map.at(\"base_z\")));\n  \n  // // Mid body positions\n  // trajopt.AddBoundingBoxConstraint(-0, 0, xmid(positions_map.at(\"base_x\"))); // Give the initial condition room to choose the x_init position (helps with positive knee constraint)\n  // trajopt.AddBoundingBoxConstraint(-0, 0, xmid(positions_map.at(\"base_y\")));\n  // trajopt.AddBoundingBoxConstraint(FLAGS_upperHeight-FLAGS_eps, FLAGS_upperHeight+FLAGS_eps, xmid(positions_map.at(\"base_z\")));\n\n  // Final Position Constraints\n  bool isPeriodic = 1;\n  if (isPeriodic){\n    trajopt.AddLinearConstraint( x0(positions_map.at(\"base_x\"))==xf(positions_map.at(\"base_x\")) );\n    trajopt.AddLinearConstraint( x0(positions_map.at(\"base_y\"))==xf(positions_map.at(\"base_y\")) );\n    trajopt.AddLinearConstraint( x0(positions_map.at(\"base_z\"))==xf(positions_map.at(\"base_z\")) );\n  }else{\n    trajopt.AddBoundingBoxConstraint(-FLAGS_eps, FLAGS_eps, xf(positions_map.at(\"base_x\"))); // Give the initial condition room to choose the x_init position (helps with positive knee constraint)\n    trajopt.AddBoundingBoxConstraint(-FLAGS_eps, FLAGS_eps, xf(positions_map.at(\"base_y\")));\n    trajopt.AddBoundingBoxConstraint(FLAGS_lowerHeight-FLAGS_eps, FLAGS_lowerHeight+FLAGS_eps, xf(positions_map.at(\"base_z\")));\n  }\n\n  \n  \n  /// Decide whether or not to constrain the body orientation at all knotpoints or only at the beginning and end\n  bool isConstrainOrientation = false;\n  if (isConstrainOrientation){\n    // Body pose constraints (keep the body flat) at all the knotpoints including the ends\n    for (int i = 0; i < num_knotpoints; i++) {\n      auto xi = trajopt.state(i);\n      trajopt.AddBoundingBoxConstraint(1, 1, xi(positions_map.at(\"base_qw\")));\n      trajopt.AddBoundingBoxConstraint(0, 0, xi(positions_map.at(\"base_qx\")));\n      trajopt.AddBoundingBoxConstraint(0, 0, xi(positions_map.at(\"base_qy\")));\n      trajopt.AddBoundingBoxConstraint(0, 0, xi(positions_map.at(\"base_qz\")));\n    }\n  }else{\n    // Body pose constraints (keep the body flat) at initial state\n    trajopt.AddBoundingBoxConstraint(1, 1, x0(positions_map.at(\"base_qw\")));\n    trajopt.AddBoundingBoxConstraint(0, 0, x0(positions_map.at(\"base_qx\")));\n    trajopt.AddBoundingBoxConstraint(0, 0, x0(positions_map.at(\"base_qy\")));\n    trajopt.AddBoundingBoxConstraint(0, 0, x0(positions_map.at(\"base_qz\")));\n\n    // Body pose constraints (keep the body flat) at mid state\n    trajopt.AddBoundingBoxConstraint(1, 1, xmid(positions_map.at(\"base_qw\")));\n    trajopt.AddBoundingBoxConstraint(0, 0, xmid(positions_map.at(\"base_qx\")));\n    trajopt.AddBoundingBoxConstraint(0, 0, xmid(positions_map.at(\"base_qy\")));\n    trajopt.AddBoundingBoxConstraint(0, 0, xmid(positions_map.at(\"base_qz\")));\n\n    // Body pose constraints (keep the body flat) at final state\n    trajopt.AddBoundingBoxConstraint(1, 1, xf(positions_map.at(\"base_qw\")));\n    trajopt.AddBoundingBoxConstraint(0, 0, xf(positions_map.at(\"base_qx\")));\n    trajopt.AddBoundingBoxConstraint(0, 0, xf(positions_map.at(\"base_qy\")));\n    trajopt.AddBoundingBoxConstraint(0, 0, xf(positions_map.at(\"base_qz\")));\n  }\n\n\n  /// Start/End velocity constraints of the behavior\n  trajopt.AddBoundingBoxConstraint(VectorXd::Zero(n_v), VectorXd::Zero(n_v),\n                                   x0.tail(n_v));\n  trajopt.AddBoundingBoxConstraint(VectorXd::Zero(n_v), VectorXd::Zero(n_v),\n                                   xmid.tail(n_v));\n  trajopt.AddBoundingBoxConstraint(VectorXd::Zero(n_v), VectorXd::Zero(n_v),\n                                   xf.tail(n_v));\n\n  \n\n  for (int i = 0; i < num_knotpoints; i++){\n    auto xi = trajopt.state(i);  \n    // legs lined up (front and back hips equal)\n    trajopt.AddLinearConstraint( xi( positions_map.at(\"joint_8\") ) == xi( positions_map.at(\"joint_9\") ) );\n    trajopt.AddLinearConstraint( xi( positions_map.at(\"joint_10\") ) == xi( positions_map.at(\"joint_11\") )  );\n  }\n  setSpiritSymmetry(plant, trajopt, \"sagittal\");\n  setSpiritJointLimits(plant, trajopt);\n  setSpiritActuationLimits(plant,trajopt);\n\n double upperLegLength = 0.206; // length of the upper leg link\n\n  \n// Quick check for allowed heights for Spirit\n  try{\n    if (FLAGS_lowerHeight<FLAGS_bodyHeight/2){\n        throw \"Body to close to floor\" ;\n    }\n    if (FLAGS_upperHeight>=upperLegLength*2){\n        throw \"Body can't stand to that height without leaving the ground\" ;\n    }\n  }catch(char const* exc){\n      std::cerr<< exc <<std::endl;\n  }\n\n  ///Setup the traditional cost function\n  const double R = FLAGS_inputCost;  // Cost on input effort\n  const MatrixXd Q = FLAGS_velocityCost  * MatrixXd::Identity(n_v, n_v); // Cost on velocity\n  trajopt.AddRunningCost( x.tail(n_v).transpose() * Q * x.tail(n_v) );\n  trajopt.AddRunningCost( u.transpose()*R*u );\n  \n  ///Add regularization costs\n  trajopt.AddRunningCost( x0(positions_map.at(\"base_x\")) * 10 * x0(positions_map.at(\"base_x\")) ); // x position cost\n  // trajopt.AddRunningCost( (x.segment(12,2)-x.segment(14,2)).transpose() * 1 * (x.segment(12,2)-x.segment(14,2)) );\n  // trajopt.AddRunningCost( (x.segment(16,2)-x.segment(18,2)).transpose() * 1 * (x.segment(16,2)-x.segment(18,2)) );\n\n  \n\n  /// Setup the visualization during the optimization\n  int num_ghosts = 3;// Number of ghosts in visualization. NOTE: there are limitations on number of ghosts based on modes and knotpoints\n  std::vector<unsigned int> visualizer_poses; // Ghosts for visualizing during optimization\n  visualizer_poses.push_back(num_ghosts); \n\n  trajopt.CreateVisualizationCallback(\n      dairlib::FindResourceOrThrow(\"examples/Spirit/spirit_drake.urdf\"),\n      visualizer_poses, 0.2); // setup which URDF, how many poses, and alpha transparency \n\n  /// Run the optimization using your initial guess\n  auto start = std::chrono::high_resolution_clock::now();\n  const auto result = Solve(trajopt, trajopt.initial_guess());\n  auto finish = std::chrono::high_resolution_clock::now();\n  std::chrono::duration<double> elapsed = finish - start;\n  std::cout << \"Solve time:\" << elapsed.count() <<std::endl;\n  std::cout << \"Cost:\" << result.get_optimal_cost() <<std::endl;\n  std::cout << (result.is_success() ? \"Optimization Success\" : \"Optimization Fail\") << std::endl;\n\n  /// Run animation of the final trajectory\n  const drake::trajectories::PiecewisePolynomial<double> pp_xtraj =\n      trajopt.ReconstructStateTrajectory(result);\n  multibody::connectTrajectoryVisualizer(plant_double_ptr,\n      &builder, &scene_graph, pp_xtraj);\n  auto diagram = builder.Build();\n  while (true) {\n    \n    drake::systems::Simulator<double> simulator(*diagram);\n    simulator.set_target_realtime_rate(0.25);\n    simulator.Initialize();\n    simulator.AdvanceTo(pp_xtraj.end_time());\n    sleep(2);\n  }\n}\n}  // namespace\n}  // namespace dairlib\n\n\nint main(int argc, char* argv[]) {\n  gflags::ParseCommandLineFlags(&argc, &argv, true);\n  std::srand(time(0));  // Initialize random number generator.\n \n  auto plant = std::make_unique<MultibodyPlant<double>>(0.0);\n  auto plant_vis = std::make_unique<MultibodyPlant<double>>(0.0);\n  auto scene_graph = std::make_unique<SceneGraph<double>>();\n  Parser parser(plant.get());\n  Parser parser_vis(plant_vis.get(), scene_graph.get());\n  std::string full_name =\n      dairlib::FindResourceOrThrow(\"examples/Spirit/spirit_drake.urdf\");\n\n  parser.AddModelFromFile(full_name);\n  parser_vis.AddModelFromFile(full_name);\n  \n  plant->mutable_gravity_field().set_gravity_vector(-9.81 *\n      Eigen::Vector3d::UnitZ());\n\n  plant->Finalize();\n  plant_vis->Finalize();\n  Eigen::VectorXd x0 = Eigen::VectorXd::Zero(plant->num_positions() +\n                       plant->num_velocities());\n\n  int nu = plant->num_actuators();\n  int nx = plant->num_positions() + plant->num_velocities();\n  int nq = plant->num_positions();\n  int nv = plant->num_velocities();\n  int N = 20; // number of timesteps\n\n  std::vector<MatrixXd> init_x;\n  std::vector<MatrixXd> init_u;\n  std::vector<PiecewisePolynomial<double>> init_l_traj;\n  std::vector<PiecewisePolynomial<double>> init_lc_traj;\n  std::vector<PiecewisePolynomial<double>> init_vc_traj;\n\n  // Initialize state trajectory\n  std::vector<double> init_time;\n\n  VectorXd xInit(nx);\n  VectorXd xMid(nx);\n  VectorXd xState(nx);\n  xInit = Eigen::VectorXd::Zero(plant->num_positions() + plant->num_velocities());\n  xMid = Eigen::VectorXd::Zero(plant->num_positions() + plant->num_velocities());\n  xState = Eigen::VectorXd::Zero(plant->num_positions() + plant->num_velocities());\n\n  auto positions_map = dairlib::multibody::makeNameToPositionsMap(*plant);\n  auto velocities_map = dairlib::multibody::makeNameToVelocitiesMap(*plant);\n  auto actuators_map = dairlib::multibody::makeNameToActuatorsMap(*plant);\n  int num_joints = 12;\n\n  // Print joint dictionary\n  std::cout<<\"**********************Joints***********************\"<<std::endl;\n  for (auto const& element : positions_map)\n    std::cout << element.first << \" = \" << element.second << std::endl;\n  for (auto const& element : velocities_map)\n    std::cout << element.first << \" = \" << element.second << std::endl;\n  for (auto const& element : actuators_map)\n    std::cout << element.first << \" = \" << element.second << std::endl;\n  std::cout<<\"***************************************************\"<<std::endl;\n    \n  dairlib::nominalSpiritStand( *plant, xInit,  FLAGS_lowerHeight); //Update xInit\n  dairlib::nominalSpiritStand( *plant, xMid,  FLAGS_upperHeight); //Update xMid\n  \n  VectorXd deltaX(nx);\n  VectorXd averageV(nx);\n  deltaX = xMid-xInit;\n  averageV = 2* deltaX / FLAGS_duration;\n  xInit.tail(nv-3) = (averageV.head(nq)).tail(nq-4); //Ignoring Orientation make velocity the average\n\n  double time = 0;\n  double dt = FLAGS_duration/(N-1);\n\n  // Initial pose\n  xState = xInit;\n\n  for (int i = 0; i < N; i++) {\n    time=i*dt; // calculate iteration's time\n    init_time.push_back(time);\n\n    // Switch the direction of the stand to go back to the initial state (not actually properly periodic initial)\n    if ( i > (N-1)/2 ){\n        xState.tail(nv) = -xInit.tail(nv);\n    }\n    // Integrate the positions based on constant velocity  for joints and xyz\n    for (int j = 0; j < num_joints; j++){\n          xState(positions_map.at(\"joint_\" + std::to_string(j))) =  \n                        xState(positions_map.at(\"joint_\" + std::to_string(j))) + xState(nq + velocities_map.at(\"joint_\" + std::to_string(j)+\"dot\" )) * dt;\n    }\n    xState(positions_map.at(\"base_x\")) = \n                        xState(positions_map.at(\"base_x\")) + xState(nq + velocities_map.at(\"base_vx\")) * dt;\n    \n    xState(positions_map.at(\"base_y\")) = \n                        xState(positions_map.at(\"base_y\")) + xState(nq + velocities_map.at(\"base_vy\")) * dt;\n    \n    xState(positions_map.at(\"base_z\")) = \n                        xState(positions_map.at(\"base_z\")) + xState(nq + velocities_map.at(\"base_vz\")) * dt;\n    // Save timestep state into matrix\n    init_x.push_back(xState);\n    init_u.push_back(Eigen::VectorXd::Zero(nu));\n  }\n  // Make matrix into trajectory\n  auto init_x_traj = PiecewisePolynomial<double>::ZeroOrderHold(init_time, init_x);\n  auto init_u_traj = PiecewisePolynomial<double>::ZeroOrderHold(init_time, init_u);\n\n  \n  // Four contacts so forces are 12 dimensional\n  Eigen::VectorXd init_l_vec(12);\n  // Initial guess\n  init_l_vec << 0, 0, 3*9.81, 0, 0, 3*9.81, 0, 0, 3*9.81, 0, 0, 3*9.81; //gravity and mass distributed\n  \n  //Initialize force trajectories\n  int num_modes = 1; // MAKE DYNAMIC DEBUG\n  for (int j = 0; j < num_modes; j++) {    \n    std::vector<MatrixXd> init_l_j;\n    std::vector<MatrixXd> init_lc_j;\n    std::vector<MatrixXd> init_vc_j;\n    std::vector<double> init_time_j;\n    for (int i = 0; i < N; i++) {\n      init_time_j.push_back(i*FLAGS_duration/(N-1));\n      init_l_j.push_back(init_l_vec);\n      init_lc_j.push_back(init_l_vec);\n      init_vc_j.push_back(VectorXd::Zero(12));\n    }\n\n    auto init_l_traj_j = PiecewisePolynomial<double>::ZeroOrderHold(init_time_j,init_l_j);\n    auto init_lc_traj_j = PiecewisePolynomial<double>::ZeroOrderHold(init_time_j,init_lc_j);\n    auto init_vc_traj_j = PiecewisePolynomial<double>::ZeroOrderHold(init_time_j,init_vc_j);\n\n    init_l_traj.push_back(init_l_traj_j);\n    init_lc_traj.push_back(init_lc_traj_j);\n    init_vc_traj.push_back(init_vc_traj_j);\n  }\n\n  // if (FLAGS_autodiff) {\n  //   std::unique_ptr<MultibodyPlant<drake::AutoDiffXd>> plant_autodiff =\n  //       drake::systems::System<double>::ToAutoDiffXd(*plant);\n  //   dairlib::runSpiritSquat<drake::AutoDiffXd>(\n  //     std::move(plant_autodiff), plant_vis.get(), std::move(scene_graph),\n  //     FLAGS_duration, init_x_traj, init_u_traj, init_l_traj,\n  //     init_lc_traj, init_vc_traj);\n  // } else \n  if (FLAGS_runInitTraj){\n    dairlib::runAnimate<double>(\n      std::move(plant), plant_vis.get(), std::move(scene_graph), init_x_traj);\n  }else {\n    dairlib::runSpiritSquat<double>(\n      std::move(plant), plant_vis.get(), std::move(scene_graph),\n      FLAGS_duration, init_x_traj, init_u_traj, init_l_traj,\n      init_lc_traj, init_vc_traj);\n  }\n\n}\n\n", "meta": {"hexsha": "8be1efd879d3b5df5ef42053020b1c4a72762d69", "size": 22039, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/Spirit/run_spirit_squat.cc", "max_stars_repo_name": "KodlabPenn/dairlib", "max_stars_repo_head_hexsha": "e544e16d2a97c3834e1eb5d534e436a45b8e4f4b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/Spirit/run_spirit_squat.cc", "max_issues_repo_name": "KodlabPenn/dairlib", "max_issues_repo_head_hexsha": "e544e16d2a97c3834e1eb5d534e436a45b8e4f4b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-01-25T20:54:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T04:00:54.000Z", "max_forks_repo_path": "examples/Spirit/run_spirit_squat.cc", "max_forks_repo_name": "KodlabPenn/dairlib", "max_forks_repo_head_hexsha": "e544e16d2a97c3834e1eb5d534e436a45b8e4f4b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.8151093439, "max_line_length": 196, "alphanum_fraction": 0.7056127773, "num_tokens": 5955, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.23118063874073336}}
{"text": "#include \"AST.h\"\n#include \"InterpreterContext.h\"\n#include \"StringPool.h\"\n#include \"VariablesScope.h\"\n#include <iostream>\n#include <boost/range/adaptor/reversed.hpp>\n#include <boost/range/algorithm.hpp>\n#include <cmath>\n\nnamespace\n{\n\ntemplate <class TFunction>\nCValue ExecuteSafely(TFunction && fn)\n{\n    try\n    {\n        return fn();\n    }\n    catch (std::exception const&)\n    {\n        return CValue::FromError(std::current_exception());\n    }\n}\n\nclass CSinFunction : public IFunctionAst\n{\npublic:\n    CValue Call(CInterpreterContext &context, const std::vector<CValue> &arguments) const override\n    {\n        (void)context;\n        return ExecuteSafely([&] {\n            double radians = arguments.at(0).AsDouble();\n            return CValue::FromDouble(std::sin(radians));\n        });\n    }\n\n    unsigned GetNameId() const override\n    {\n        return 0;\n    }\n};\n\nclass CRandFunction : public IFunctionAst\n{\npublic:\n    CValue Call(CInterpreterContext &context, const std::vector<CValue> &arguments) const override\n    {\n        (void)context;\n        return ExecuteSafely([&] {\n            double minimum = arguments.at(0).AsDouble();\n            double maximum = arguments.at(1).AsDouble();\n            if (minimum > maximum)\n            {\n                return CValue::FromErrorMessage(\"invalid arguments for rand - range maximum is lesser than minimum.\");\n            }\n            double rand0to1 = double(std::rand()) / std::numeric_limits<unsigned>::max();\n\n            return CValue::FromDouble((maximum - minimum) * rand0to1 + minimum);\n        });\n    }\n\n    unsigned GetNameId() const override\n    {\n        return 0;\n    }\n};\n\n}\n\nCInterpreterContext::CInterpreterContext(std::ostream &output, std::ostream &errors, CStringPool &pool)\n    : m_pool(pool)\n    , m_output(output)\n    , m_errors(errors)\n{\n    AddBuiltin(\"sin\", std::unique_ptr<IFunctionAst>(new CSinFunction));\n    AddBuiltin(\"rand\", std::unique_ptr<IFunctionAst>(new CRandFunction));\n}\n\nCInterpreterContext::~CInterpreterContext()\n{\n}\n\nvoid CInterpreterContext::DefineVariable(unsigned nameId, const CValue &value)\n{\n    if (ValidateValue(value))\n    {\n        m_scopes.back()->AssignVariable(nameId, value);\n    }\n}\n\nvoid CInterpreterContext::AssignVariable(unsigned nameId, const CValue &value)\n{\n    if (ValidateValue(value))\n    {\n        if (CVariablesScope *pScope = FindScopeWithVariable(nameId))\n        {\n            pScope->AssignVariable(nameId, value);\n        }\n        else\n        {\n            DefineVariable(nameId, value);\n        }\n    }\n}\n\nCValue CInterpreterContext::GetVariableValue(unsigned nameId) const\n{\n    if (CVariablesScope *pScope = FindScopeWithVariable(nameId))\n    {\n        return *pScope->GetVariableValue(nameId);\n    }\n    return CValue::FromErrorMessage(\"unknown variable \" + m_pool.GetString(nameId));\n}\n\nvoid CInterpreterContext::PushScope(std::unique_ptr<CVariablesScope> &&scope)\n{\n    m_scopes.emplace_back(std::move(scope));\n}\n\nstd::unique_ptr<CVariablesScope> CInterpreterContext::PopScope()\n{\n    std::unique_ptr<CVariablesScope> ret(m_scopes.back().release());\n    m_scopes.pop_back();\n    return ret;\n}\n\nsize_t CInterpreterContext::GetScopesCount() const\n{\n    return m_scopes.size();\n}\n\nIFunctionAst *CInterpreterContext::GetFunction(unsigned nameId) const\n{\n    try\n    {\n        return m_functions.at(nameId);\n    }\n    catch (std::exception const&)\n    {\n        return nullptr;\n    }\n}\n\nvoid CInterpreterContext::AddFunction(unsigned nameId, IFunctionAst *function)\n{\n    if (function)\n    {\n        m_functions[nameId] = function;\n    }\n}\n\nstd::string CInterpreterContext::GetStringLiteral(unsigned stringId) const\n{\n    return m_pool.GetString(stringId);\n}\n\nvoid CInterpreterContext::PrintResults(const std::vector<CValue> &values)\n{\n    m_output << \"  \";\n    for (const auto &value : values)\n    {\n        if (ValidateValue(value))\n        {\n            m_output << value.ToString();\n        }\n    }\n    m_output << std::endl;\n}\n\nvoid CInterpreterContext::PrintError(const std::string &message)\n{\n    m_errors << \"  Error: \" << message << std::endl;\n}\n\nbool CInterpreterContext::ValidateValue(const CValue &value)\n{\n    try\n    {\n        value.RethrowIfException();\n        return true;\n    }\n    catch (std::exception const& ex)\n    {\n        PrintError(ex.what());\n        return false;\n    }\n}\n\nvoid CInterpreterContext::SetReturnValue(boost::optional<CValue> const& valueOpt)\n{\n    m_returnValueOpt = valueOpt;\n}\n\nboost::optional<CValue> CInterpreterContext::GetReturnValue() const\n{\n    return m_returnValueOpt;\n}\n\nCVariablesScope *CInterpreterContext::FindScopeWithVariable(unsigned nameId) const\n{\n    auto range = boost::adaptors::reverse(m_scopes);\n    auto it = boost::find_if(range, [=](const auto &pScope) {\n        return pScope->HasVariable(nameId);\n    });\n    if (it != range.end())\n    {\n        return it->get();\n    }\n    return nullptr;\n}\n\nvoid CInterpreterContext::AddBuiltin(const std::string &name, std::unique_ptr<IFunctionAst> &&function)\n{\n    m_builtins.emplace_back(std::move(function));\n    unsigned nameRand = m_pool.Insert(name);\n    m_functions[nameRand] = m_builtins.back().get();\n}\n", "meta": {"hexsha": "a33ee9a4b2b0f93f87cd426e4bddbfc66fca254e", "size": 5157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lemon-based-parser/lemon-9-final/InterpreterContext.cpp", "max_stars_repo_name": "PS-Group/compiler-theory-samples", "max_stars_repo_head_hexsha": "c916af50eb42020024257ecd17f9be1580db7bf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lemon-based-parser/lemon-9-final/InterpreterContext.cpp", "max_issues_repo_name": "PS-Group/compiler-theory-samples", "max_issues_repo_head_hexsha": "c916af50eb42020024257ecd17f9be1580db7bf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lemon-based-parser/lemon-9-final/InterpreterContext.cpp", "max_forks_repo_name": "PS-Group/compiler-theory-samples", "max_forks_repo_head_hexsha": "c916af50eb42020024257ecd17f9be1580db7bf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5479452055, "max_line_length": 118, "alphanum_fraction": 0.6525111499, "num_tokens": 1235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2311806387407333}}
{"text": "/*\n * Implementation of EDM methods, including S-map and cross-mapping\n *\n * - Patrick Laub, Department of Management and Marketing,\n *   The University of Melbourne, patrick.laub@unimelb.edu.au\n * - Edoardo Tescari, Melbourne Data Analytics Platform,\n *  The University of Melbourne, e.tescari@unimelb.edu.au\n *\n */\n\n#pragma warning(disable : 4018)\n\n#include \"edm.h\"\n#include \"cpu.h\"\n#include \"distances.h\"\n#include \"stats.h\" // for correlation and mean_absolute_error\n#include \"thread_pool.h\"\n#include \"train_predict_split.h\"\n\n#ifndef FMT_HEADER_ONLY\n#define FMT_HEADER_ONLY\n#endif\n\n#define EIGEN_NO_DEBUG\n#define EIGEN_DONT_PARALLELIZE\n#include <Eigen/SVD>\n#include <algorithm> // std::partial_sort\n#include <cmath>\n#include <fstream> // just to create low-level input dumps\n\nstd::atomic<int> numTasksStarted = 0;\nstd::atomic<int> numTasksFinished = 0;\nThreadPool workerPool(0), taskRunnerPool(0);\n\nstd::vector<std::future<Prediction>> launch_task_group(const ManifoldGenerator& generator, Options opts,\n                                                       const std::vector<int>& Es, const std::vector<int>& libraries,\n                                                       int k, int numReps, int crossfold, bool explore, bool full,\n                                                       bool saveFinalPredictions, bool saveFinalCoPredictions,\n                                                       bool saveSMAPCoeffs, bool copredictMode,\n                                                       const std::vector<bool>& usable, const std::string& rngState,\n                                                       IO* io, bool keep_going(), void all_tasks_finished())\n{\n\n  workerPool.set_num_workers(opts.nthreads);\n  taskRunnerPool.set_num_workers(num_physical_cores());\n\n  // Construct the instance which will (repeatedly) split the data\n  // into either the training manifold or the prediction manifold.\n  TrainPredictSplitter splitter = TrainPredictSplitter(explore, full, crossfold, usable, rngState);\n\n  int numLibraries = (explore ? 1 : libraries.size());\n\n  opts.numTasks = numReps * Es.size() * numLibraries;\n  opts.configNum = 0;\n  opts.taskNum = 0;\n\n  int maxE = Es[Es.size() - 1];\n\n  std::vector<bool> cousable;\n\n  if (copredictMode) {\n    opts.numTasks *= 2;\n    cousable = generator.generate_usable(maxE, true);\n  }\n\n  int E, kAdj, library, trainSize;\n\n  std::vector<std::future<Prediction>> futures;\n\n  bool newTrainPredictSplit = true;\n\n  // Note: the 'numReps' either refers to the 'replicate' option\n  // used for bootstrap resampling, or the 'crossfold' number of\n  // cross-validation folds. Both options can't be used together,\n  // so numReps = max(replicate, crossfold).\n  for (int iter = 1; iter <= numReps; iter++) {\n    if (explore) {\n      newTrainPredictSplit = true;\n      trainSize = splitter.next_training_size(iter);\n    }\n\n    for (int i = 0; i < Es.size(); i++) {\n      E = Es[i];\n\n      // 'libraries' is implicitly set to one value in explore mode\n      // though in xmap mode it is a user-supplied list which we loop over.\n      for (int l = 0; l == 0 || l < libraries.size(); l++) {\n        if (!explore) {\n          newTrainPredictSplit = true;\n        }\n\n        if (explore) {\n          library = trainSize;\n        } else {\n          library = libraries[l];\n        }\n\n        // Set the number of neighbours to use\n        if (k > 0) {\n          kAdj = k;\n        } else if (k < 0) {\n          kAdj = -1; // Leave a sentinel value so we know to skip the nearest neighbours calculation\n        } else if (k == 0) {\n          bool isSMap = opts.algorithm == Algorithm::SMap;\n          int defaultK = generator.E_actual(E) + 1 + isSMap;\n          kAdj = defaultK < library ? defaultK : library;\n        }\n\n        bool lastConfig = (E == maxE) && (l + 1 == numLibraries);\n\n        if (explore) {\n          opts.savePrediction = saveFinalPredictions && ((iter == numReps) || (crossfold > 0)) && lastConfig;\n        } else {\n          opts.savePrediction = saveFinalPredictions && (iter == numReps) && lastConfig;\n        }\n        opts.saveSMAPCoeffs = saveSMAPCoeffs;\n\n        if (newTrainPredictSplit) {\n          splitter.update_train_predict_split(library, iter);\n          newTrainPredictSplit = false;\n        }\n\n        opts.copredict = false;\n        opts.k = kAdj;\n\n        futures.emplace_back(launch_edm_task(generator, opts, E, splitter.trainingRows(), splitter.predictionRows(), io,\n                                             keep_going, all_tasks_finished));\n\n        opts.taskNum += 1;\n\n        if (copredictMode) {\n          opts.copredict = true;\n          if (explore) {\n            opts.savePrediction = saveFinalCoPredictions && ((iter == numReps) || (crossfold > 0)) && lastConfig;\n          } else {\n            opts.savePrediction = saveFinalCoPredictions && ((iter == numReps)) && lastConfig;\n          }\n          opts.saveSMAPCoeffs = false;\n          futures.emplace_back(\n            launch_edm_task(generator, opts, E, splitter.trainingRows(), cousable, io, keep_going, all_tasks_finished));\n\n          opts.taskNum += 1;\n        }\n\n        opts.configNum += opts.thetas.size();\n      }\n    }\n  }\n\n  return futures;\n}\n\nstd::future<Prediction> launch_edm_task(const ManifoldGenerator& generator, Options opts, int E,\n                                        const std::vector<bool>& trainingRows, const std::vector<bool>& predictionRows,\n                                        IO* io, bool keep_going(), void all_tasks_finished())\n{\n  // Expand the 'metrics' vector now that we know the value of E.\n  std::vector<Metric> metrics;\n\n  // For the Wasserstein distance, it's more convenient to have one 'metric' for each variable (before taking lags).\n  // However, for the L^1 / L^2 distances, it's more convenient to have one 'metric' for each individual\n  // point of each observations, so metrics.size() == M.E_actual().\n  if (opts.distance == Distance::Wasserstein) {\n    // Add a metric for the main variable and for the dt variable.\n    // These are always treated as a continuous values (though perhaps in the future this will change).\n    metrics.push_back(Metric::Diff);\n    if (generator.E_dt(E) > 0) {\n      metrics.push_back(Metric::Diff);\n    }\n\n    // Add in the metrics for the 'extra' variables as they were supplied to us.\n    for (int k = 0; k < generator.numExtras(); k++) {\n      metrics.push_back(opts.metrics[k]);\n    }\n  } else {\n    // Add metrics for the main variable and the dt variable and their lags.\n    // These are always treated as a continuous values (though perhaps in the future this will change).\n    for (int lagNum = 0; lagNum < E + generator.E_dt(E); lagNum++) {\n      metrics.push_back(Metric::Diff);\n    }\n\n    // The user specified how to treat the extra variables.\n    for (int k = 0; k < generator.numExtras(); k++) {\n      int numLags = (k < generator.numExtrasLagged()) ? E : 1;\n      for (int lagNum = 0; lagNum < numLags; lagNum++) {\n        metrics.push_back(opts.metrics[k]);\n      }\n    }\n  }\n\n  opts.metrics = metrics;\n\n  if (opts.taskNum == 0) {\n    numTasksStarted = 0;\n    numTasksFinished = 0;\n  }\n\n  numTasksStarted += 1;\n\n  // This hack is simply to dump some really low level data structures\n  // purely for the purpose of generating microbenchmarks.\n  if (io != nullptr && io->verbosity > 4) {\n    json lowLevelInputDump;\n    lowLevelInputDump[\"generator\"] = generator;\n    lowLevelInputDump[\"opts\"] = opts;\n    lowLevelInputDump[\"E\"] = E;\n    lowLevelInputDump[\"trainingRows\"] = trainingRows;\n    lowLevelInputDump[\"predictionRows\"] = predictionRows;\n\n    std::ofstream o(\"lowLevelInputDump.json\");\n    o << lowLevelInputDump << std::endl;\n  }\n\n  // Note, we can't have missing data inside the training manifold when using the S-Map algorithm\n  bool skipMissing = (opts.algorithm == Algorithm::SMap);\n\n  Manifold M = generator.create_manifold(E, trainingRows, opts.copredict, false, opts.dtWeight, skipMissing);\n  Manifold Mp = generator.create_manifold(E, predictionRows, opts.copredict, true, opts.dtWeight);\n\n  return taskRunnerPool.enqueue([opts, M, Mp, predictionRows, io, keep_going, all_tasks_finished] {\n    return edm_task(opts, M, Mp, predictionRows, io, keep_going, all_tasks_finished);\n  });\n}\n\nPrediction edm_task(const Options opts, const Manifold M, const Manifold Mp, const std::vector<bool> predictionRows,\n                    IO* io, bool keep_going(), void all_tasks_finished())\n{\n  bool multiThreaded = opts.nthreads > 1;\n  int numThetas = (int)opts.thetas.size();\n  int numPredictions = Mp.nobs();\n  int numCoeffCols = M.E_actual() + 1;\n\n  auto ystar = std::make_unique<double[]>(numThetas * numPredictions);\n  std::fill_n(ystar.get(), numThetas * numPredictions, MISSING_SENTINEL);\n  Eigen::Map<MatrixXd> ystarView(ystar.get(), numThetas, numPredictions);\n\n  // If we're saving the coefficients (i.e. in xmap mode), then we're not running with multiple 'theta' values.\n  auto coeffs = std::make_unique<double[]>(numPredictions * numCoeffCols);\n  std::fill_n(coeffs.get(), numPredictions * numCoeffCols, MISSING_SENTINEL);\n  Eigen::Map<MatrixXd> coeffsView(coeffs.get(), numPredictions, numCoeffCols);\n\n  auto rc = std::make_unique<retcode[]>(numThetas * numPredictions);\n  std::fill_n(rc.get(), numThetas * numPredictions, UNKNOWN_ERROR);\n  Eigen::Map<MatrixXi> rcView(rc.get(), numThetas, numPredictions);\n\n  std::vector<int> kUsed;\n  for (int i = 0; i < numPredictions; i++) {\n    kUsed.push_back(-1);\n  }\n\n  if (opts.numTasks > 1 && opts.taskNum == 0) {\n    io->progress_bar(0.0);\n  }\n\n  if (multiThreaded) {\n    std::vector<std::future<void>> results(numPredictions);\n    for (int i = 0; i < numPredictions; i++) {\n      results[i] = workerPool.enqueue(\n        [&, i] { make_prediction(i, opts, M, Mp, ystarView, rcView, coeffsView, &(kUsed[i]), keep_going); });\n    }\n\n    if (opts.numTasks == 1) {\n      io->progress_bar(0.0);\n    }\n    for (int i = 0; i < numPredictions; i++) {\n      results[i].get();\n      if (opts.numTasks == 1) {\n        io->progress_bar((i + 1) / ((double)numPredictions));\n      }\n    }\n  } else {\n    if (opts.numTasks == 1) {\n      io->progress_bar(0.0);\n    }\n    for (int i = 0; i < numPredictions; i++) {\n      if (keep_going != nullptr && keep_going() == false) {\n        break;\n      }\n      make_prediction(i, opts, M, Mp, ystarView, rcView, coeffsView, &(kUsed[i]), keep_going);\n      if (opts.numTasks == 1) {\n        io->progress_bar((i + 1) / ((double)numPredictions));\n      }\n    }\n  }\n\n  Prediction pred;\n\n  // Store the results, so long as we weren't interrupted by a 'break'.\n  if (keep_going == nullptr || keep_going() == true) {\n    // Start by calculating the MAE & rho of prediction, if requested\n    for (int t = 0; t < numThetas * opts.calcRhoMAE; t++) {\n      PredictionStats stats;\n\n      std::vector<double> y1, y2;\n\n      for (int i = 0; i < Mp.ySize(); i++) {\n        if (Mp.y(i) != MISSING_SENTINEL && ystarView(t, i) != MISSING_SENTINEL) {\n          y1.push_back(Mp.y(i));\n          y2.push_back(ystarView(t, i));\n        }\n      }\n\n      if (!(y1.empty() || y2.empty())) {\n        stats.mae = mean_absolute_error(y1, y2);\n        stats.rho = correlation(y1, y2);\n      } else {\n        stats.mae = MISSING_SENTINEL;\n        stats.rho = MISSING_SENTINEL;\n      }\n\n      pred.stats.push_back(stats);\n    }\n\n    pred.configNum = opts.configNum;\n\n    // Check if any make_prediction call failed, and if so find the most serious error\n    pred.rc = *std::max_element(rc.get(), rc.get() + numThetas * numPredictions);\n\n    // If we're storing the prediction and/or the SMAP coefficients, put them\n    // into the resulting Prediction struct. Otherwise, let them be deleted.\n    if (opts.savePrediction) {\n      // Take only the predictions for the largest theta value.\n      if (numThetas == 1) {\n        pred.ystar = std::move(ystar);\n      } else {\n        pred.ystar = std::make_unique<double[]>(numPredictions);\n        for (int i = 0; i < numPredictions; i++) {\n          pred.ystar[i] = ystarView(numThetas - 1, i);\n        }\n      }\n    } else {\n      pred.ystar = nullptr;\n    }\n\n    if (opts.saveSMAPCoeffs) {\n      pred.coeffs = std::move(coeffs);\n    } else {\n      pred.coeffs = nullptr;\n    }\n\n    if (opts.savePrediction || opts.saveSMAPCoeffs) {\n      pred.predictionRows = std::move(predictionRows);\n    }\n\n    if (opts.saveKUsed) {\n      pred.kUsed = kUsed;\n    }\n\n    pred.cmdLine = opts.cmdLine;\n    pred.copredict = opts.copredict;\n\n    pred.numThetas = numThetas;\n    pred.numPredictions = numPredictions;\n    pred.numCoeffCols = numCoeffCols;\n\n    if (opts.numTasks > 1) {\n      io->progress_bar((numTasksFinished + 1) / ((double)opts.numTasks));\n    }\n  }\n\n  numTasksFinished += 1;\n\n  if (numTasksFinished == opts.numTasks) {\n    if (all_tasks_finished != nullptr) {\n      all_tasks_finished();\n    }\n  }\n\n  return pred;\n}\n\n// Use a training manifold 'M' to make a prediction about the prediction manifold 'Mp'.\n// Specifically, predict the 'Mp_i'-th value of the prediction manifold 'Mp'.\n//\n// The predicted value is stored in 'ystar', along with any return codes in 'rc'.\n// Optionally, the user may ask to store some S-map intermediate values in 'coeffs'.\n//\n// The 'opts' value specifies the kind of prediction to make (e.g. S-map, or simplex method).\n// This function is usually run in a worker thread, and the 'keep_going' callback is frequently called to\n// see whether the user still wants this result, or if they have given up & simply want the execution\n// to terminate.\n//\n// We sometimes let 'M' and 'Mp' be the same manifold, so we train and predict using the same values.\n// In this case, the algorithm may cheat by pulling out the identical trajectory from the training manifold\n// and using this as the prediction. As such, we throw away any neighbours which have a distance of 0 from\n// the target point.\nvoid make_prediction(int Mp_i, const Options& opts, const Manifold& M, const Manifold& Mp, Eigen::Map<MatrixXd> ystar,\n                     Eigen::Map<MatrixXi> rc, Eigen::Map<MatrixXd> coeffs, int* kUsed, bool keep_going())\n{\n  // An impatient user may want to cancel a long-running EDM command, so we occasionally check using this\n  // callback to see whether we ought to keep going with this EDM command. Of course, this adds a tiny inefficiency,\n  // but there doesn't seem to be a simple way to easily kill running worker threads across all OSs.\n  if (keep_going != nullptr && keep_going() == false) {\n    rc(0, Mp_i) = BREAK_HIT;\n    return;\n  }\n\n  // Create a list of indices which may potentially be the neighbours of Mp(Mp_i,.)\n  std::vector<int> tryInds = potential_neighbour_indices(Mp_i, opts, M, Mp);\n\n  DistanceIndexPairs potentialNN;\n  if (opts.distance == Distance::Wasserstein) {\n    potentialNN = wasserstein_distances(Mp_i, opts, M, Mp, tryInds);\n  } else {\n    potentialNN = lp_distances(Mp_i, opts, M, Mp, tryInds);\n  }\n\n  if (keep_going != nullptr && keep_going() == false) {\n    rc(0, Mp_i) = BREAK_HIT;\n    return;\n  }\n\n  // Do we have enough distances to find k neighbours?\n  int numValidDistances = potentialNN.inds.size();\n  int k = opts.k;\n  *kUsed = numValidDistances;\n  if (k > numValidDistances) {\n    if (opts.forceCompute) {\n      k = numValidDistances;\n    } else {\n      rc(0, Mp_i) = INSUFFICIENT_UNIQUE;\n      return;\n    }\n  }\n\n  if (k == 0) {\n    // Whether we throw an error or just silently ignore this prediction\n    // depends on whether we are in 'strict' mode or not.\n    rc(0, Mp_i) = opts.forceCompute ? SUCCESS : INSUFFICIENT_UNIQUE;\n    return;\n  }\n\n  // If we asked for all of the neighbours to be considered (e.g. with k = -1), return this index vector directly.\n  DistanceIndexPairs kNNs;\n  if (k < 0 || k == potentialNN.inds.size()) {\n    kNNs = potentialNN;\n  } else {\n    kNNs = kNearestNeighbours(potentialNN, k);\n  }\n\n  if (keep_going != nullptr && keep_going() == false) {\n    rc(0, Mp_i) = BREAK_HIT;\n    return;\n  }\n\n  if (opts.algorithm == Algorithm::Simplex) {\n    for (int t = 0; t < opts.thetas.size(); t++) {\n      simplex_prediction(Mp_i, t, opts, M, kNNs.dists, kNNs.inds, ystar, rc, kUsed);\n    }\n  } else if (opts.algorithm == Algorithm::SMap) {\n    for (int t = 0; t < opts.thetas.size(); t++) {\n      smap_prediction(Mp_i, t, opts, M, Mp, kNNs.dists, kNNs.inds, ystar, coeffs, rc, kUsed);\n    }\n  } else {\n    rc(0, Mp_i) = INVALID_ALGORITHM;\n  }\n}\n\nstd::vector<int> potential_neighbour_indices(int Mp_i, const Options& opts, const Manifold& M, const Manifold& Mp)\n{\n  bool skipOtherPanels = opts.panelMode && (opts.idw < 0);\n\n  std::vector<int> inds;\n\n  for (int i = 0; i < M.nobs(); i++) {\n    if (skipOtherPanels && (M.panel(i) != Mp.panel(Mp_i))) {\n      continue;\n    }\n\n    inds.push_back(i);\n  }\n\n  return inds;\n}\n\n// For a given point, find the k nearest neighbours of this point.\n//\n// If there are many potential neighbours with the exact same distances, we\n// prefer the neighbours with the smallest index value. This corresponds\n// to a stable sort in C++ STL terminology.\n//\n// In typical use-cases of 'edm explore' the value of 'k' is small, like 5-20.\n// However for a typical 'edm xmap' the value of 'k' is set as large as possible.\n// If 'k' is small, the partial_sort is efficient as it only finds the 'k' smallest\n// distances. If 'k' is larger, then it is faster to simply sort the entire distance\n// vector.\nDistanceIndexPairs kNearestNeighbours(const DistanceIndexPairs& potentialNeighbours, int k)\n{\n  std::vector<int> idx(potentialNeighbours.inds.size());\n  std::iota(idx.begin(), idx.end(), 0);\n\n  if (k >= (int)(idx.size() / 2)) {\n    auto comparator = [&potentialNeighbours](int i1, int i2) {\n      return potentialNeighbours.dists[i1] < potentialNeighbours.dists[i2];\n    };\n    std::stable_sort(idx.begin(), idx.end(), comparator);\n  } else {\n    auto stableComparator = [&potentialNeighbours](int i1, int i2) {\n      if (potentialNeighbours.dists[i1] != potentialNeighbours.dists[i2])\n        return potentialNeighbours.dists[i1] < potentialNeighbours.dists[i2];\n      else\n        return i1 < i2;\n    };\n    std::partial_sort(idx.begin(), idx.begin() + k, idx.end(), stableComparator);\n  }\n\n  std::vector<int> kNNInds(k);\n  std::vector<double> kNNDists(k);\n\n  for (int i = 0; i < k; i++) {\n    kNNInds[i] = potentialNeighbours.inds[idx[i]];\n    kNNDists[i] = potentialNeighbours.dists[idx[i]];\n  }\n\n  return { kNNInds, kNNDists };\n}\n\n// An alternative version of 'kNearestNeighbours' which doesn't sort the neighbours.\n// This version splits ties differently on different OS's, so it can't be used directly,\n// though perhaps a platform-independent implementation of std::nth_element would solve this problem.\nDistanceIndexPairs kNearestNeighboursUnstable(const DistanceIndexPairs& potentialNeighbours, int k)\n{\n  std::vector<int> indsToPartition(potentialNeighbours.inds.size());\n  std::iota(indsToPartition.begin(), indsToPartition.end(), 0);\n\n  auto comparator = [&potentialNeighbours](int i1, int i2) {\n    return potentialNeighbours.dists[i1] < potentialNeighbours.dists[i2];\n  };\n  std::nth_element(indsToPartition.begin(), indsToPartition.begin() + k, indsToPartition.end(), comparator);\n\n  std::vector<int> kNNInds(k);\n  std::vector<double> kNNDists(k);\n\n  for (int i = 0; i < k; i++) {\n    kNNInds[i] = potentialNeighbours.inds[indsToPartition[i]];\n    kNNDists[i] = potentialNeighbours.dists[indsToPartition[i]];\n  }\n\n  return { kNNInds, kNNDists };\n}\n\nvoid simplex_prediction(int Mp_i, int t, const Options& opts, const Manifold& M, const std::vector<double>& dists,\n                        const std::vector<int>& kNNInds, Eigen::Map<MatrixXd> ystar, Eigen::Map<MatrixXi> rc,\n                        int* kUsed)\n{\n  int k = kNNInds.size();\n\n  // Find the smallest distance (closest neighbour) among the supplied neighbours.\n  double minDist = *std::min_element(dists.begin(), dists.end());\n\n  // Calculate our weighting of each neighbour, and the total sum of these weights.\n  std::vector<double> w(k);\n  double sumw = 0.0;\n  const double theta = opts.thetas[t];\n\n  int numNonZeroWeights = 0;\n  for (int j = 0; j < k; j++) {\n    w[j] = exp(-theta * (dists[j] / minDist));\n    sumw = sumw + w[j];\n    numNonZeroWeights += (w[j] > 0);\n  }\n\n  // For the sake of debugging, count how many neighbours we end up with.\n  if (opts.saveKUsed) {\n    *kUsed = numNonZeroWeights;\n  }\n\n  // Make the simplex projection/prediction.\n  double r = 0.0;\n  for (int j = 0; j < k; j++) {\n    r = r + M.y(kNNInds[j]) * (w[j] / sumw);\n  }\n\n  // Store the results & return value.\n  ystar(t, Mp_i) = r;\n  rc(t, Mp_i) = SUCCESS;\n}\n\nvoid smap_prediction(int Mp_i, int t, const Options& opts, const Manifold& M, const Manifold& Mp,\n                     const std::vector<double>& dists, const std::vector<int>& kNNInds, Eigen::Map<MatrixXd> ystar,\n                     Eigen::Map<MatrixXd> coeffs, Eigen::Map<MatrixXi> rc, int* kUsed)\n{\n  int k = kNNInds.size();\n\n  // Pull out the nearest neighbours from the manifold, and\n  // simultaneously prepend a column of ones in front of the manifold data.\n  MatrixXd X_ls_cj(k, M.E_actual() + 1);\n  X_ls_cj << Eigen::VectorXd::Ones(k), M.map()(kNNInds, Eigen::all);\n\n  // Calculate the weight for each neighbour\n  Eigen::Map<const Eigen::VectorXd> distsMap(&(dists[0]), dists.size());\n  Eigen::VectorXd w = Eigen::exp(-opts.thetas[t] * (distsMap.array() / distsMap.mean()));\n\n  // For the sake of debugging, count how many neighbours we end up with.\n  if (opts.saveKUsed) {\n    int numNonZeroWeights = 0;\n    for (double& w_i : w) {\n      if (w_i > 0) {\n        numNonZeroWeights += 1;\n      }\n    }\n    *kUsed = numNonZeroWeights;\n  }\n\n  // Scale everything by our weights vector\n  X_ls_cj.array().colwise() *= w.array();\n  Eigen::VectorXd y_ls = M.yMap()(kNNInds).array() * w.array();\n\n  // The old way to solve this system:\n  // Eigen::BDCSVD<MatrixXd> svd(X_ls_cj, Eigen::ComputeThinU | Eigen::ComputeThinV);\n  //  Eigen::VectorXd ics = svd.solve(y_ls);\n\n  // The pseudo-inverse of X can be calculated as (X^T * X)^(-1) * X^T\n  // see https://scicomp.stackexchange.com/a/33375\n  const int svdOpts = Eigen::ComputeThinU | Eigen::ComputeThinV; // 'ComputeFull*' would probably work identically here.\n  Eigen::BDCSVD<MatrixXd> svd(X_ls_cj.transpose() * X_ls_cj, svdOpts);\n  Eigen::VectorXd ics = svd.solve(X_ls_cj.transpose() * y_ls);\n\n  double r = ics(0);\n  for (int j = 0; j < M.E_actual(); j++) {\n    if (Mp(Mp_i, j) != MISSING_SENTINEL) {\n      r += Mp(Mp_i, j) * ics(j + 1);\n    }\n  }\n\n  // If the 'savesmap' option is given, save the 'ics' coefficients\n  // for the largest value of theta.\n  if (opts.saveSMAPCoeffs && t == opts.thetas.size() - 1) {\n    for (int j = 0; j < M.E_actual() + 1; j++) {\n      if (ics(j) == 0.) {\n        coeffs(Mp_i, j) = MISSING_SENTINEL;\n      } else {\n        coeffs(Mp_i, j) = ics(j);\n      }\n    }\n  }\n\n  ystar(t, Mp_i) = r;\n  rc(t, Mp_i) = SUCCESS;\n}\n", "meta": {"hexsha": "a1e6e9c16c4ec66f94af02a467de2da5c65a3b9b", "size": 22882, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/edm.cpp", "max_stars_repo_name": "9prady9/EDM", "max_stars_repo_head_hexsha": "db89a7fecf5a0f30b9db2b913a4d82f3c4ced33c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/edm.cpp", "max_issues_repo_name": "9prady9/EDM", "max_issues_repo_head_hexsha": "db89a7fecf5a0f30b9db2b913a4d82f3c4ced33c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/edm.cpp", "max_forks_repo_name": "9prady9/EDM", "max_forks_repo_head_hexsha": "db89a7fecf5a0f30b9db2b913a4d82f3c4ced33c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6973478939, "max_line_length": 120, "alphanum_fraction": 0.6389738659, "num_tokens": 6261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.23118063874073327}}
{"text": "//\r\n// Copyright (c) 2016 - 2017 Mesh Consultants Inc.\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files (the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be included in\r\n// all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n// THE SOFTWARE.\r\n//\r\n\r\n\r\n#include \"Geomlib_TriMeshThicken.h\"\n\n#include <iostream>\n\n#include <Eigen/Core>\n\n#pragma warning(push, 0)\n#include <igl/is_boundary_edge.h>\n#include <igl/edge_flaps.h>\n#include <igl/edges.h>\n#pragma warning(pop)\n\n#include <Urho3D/Core/Variant.h>\n\n#include \"ConversionUtilities.h\"\n#include \"TriMesh.h\"\n\n#pragma warning(disable : 4244)\n\nusing Urho3D::Variant;\nusing Urho3D::VariantMap;\nusing Urho3D::VariantVector;\nusing Urho3D::Vector3;\n\nbool Geomlib::TriMeshThicken(\n\tconst Urho3D::Variant& meshIn,\n\tfloat d,\n\tUrho3D::Variant& meshOut\n)\n{\n\t// meshIn: verify and parse\n\tif (!TriMesh_Verify(meshIn)) {\n\t\tstd::cerr << \"ERROR: Geomlib::Thicken --- meshIn unverified\\n\";\n\t\tmeshOut = Variant();\n\t\treturn false;\n\t}\n\tVariantMap meshMap = meshIn.GetVariantMap();\n\tconst VariantVector vertexList = meshMap[\"vertices\"].GetVariantVector();\n\tconst VariantVector faceList = meshMap[\"faces\"].GetVariantVector();\n\n\t// Compute vertices for outer part of solid, using unit normals\n\tVariantVector vertNormals = TriMesh_ComputeVertexNormals(meshIn, true);\n\tassert(vertNormals.Size() == vertexList.Size());\n\tVariantVector outerVertexList;\n\tfor (unsigned i = 0; i < vertexList.Size(); ++i) {\n\t\tVector3 vert = vertexList[i].GetVector3();\n\t\tVector3 unorm = vertNormals[i].GetVector3();\n\n\t\tVector3 newVert = vert + d * unorm;\n\t\touterVertexList.Push(Variant(newVert));\n\t}\n\t// Compute faces for outer part of solid\n\t// (using convention that outer vertices are listed in the 2nd half of final vertex list\n\tVariantVector outerFaceList;\n\tunsigned numVertices = vertexList.Size();\n\tfor (unsigned i = 0; i < faceList.Size(); ++i) {\n\t\tunsigned v = faceList[i].GetUInt();\n\t\touterFaceList.Push(numVertices + faceList[i].GetUInt());\n\t}\n\n\t// Compute faces to form panels connecting exposed edges\n\t// on inner and outer surfaces.\n\tVariantVector sideFaceList;\n\n\t// Determine which edges are boundary edges, using libigl\n\tEigen::MatrixXf V;\n\tEigen::MatrixXi F;\n\tbool matrixSuccess = IglMeshToMatrices(meshIn, V, F);\n\tassert(matrixSuccess);\n\tEigen::MatrixXi EE; // EE is used to precompute # of edges, then is discarded\n\tigl::edges(F, EE);\n\tEigen::MatrixXi E, EI;\n\tEigen::MatrixXi EF(EE.rows(), 2);\n\tEF = Eigen::MatrixXi::Constant(EE.rows(), 2, -1); // we use the -1 default values to help identify boundary edges\n\tEigen::VectorXi EMAP;\n\tigl::edge_flaps(F, E, EMAP, EF, EI);\n\tEigen::VectorXi B;\n\tigl::is_boundary_edge(E, F, B);\n\tassert(E.rows() == B.rows());\n\n\t// Loop over boundary edges, constructing \"thickened\" outer edges\n\tunsigned numFaces = F.rows();\n\tfor (unsigned e = 0; e < B.rows(); ++e) {\n\t\tif (B(e) == 1) {\n\t\t\t// Boundary found! Edge e is a boundary edge.\n\t\t\t// E\n\t\t\tunsigned f0 = EF(e, 0);\n\t\t\tunsigned f1 = EF(e, 1);\n\n\t\t\tassert(\n\t\t\t\t(f0 == -1 && (f1 >= 0 && f1 < numFaces)) ||\n\t\t\t\t((f0 >= 0 && f0 < numFaces) && f1 == -1)\n\t\t\t);\n\n\t\t\tunsigned v0 = -1;\n\t\t\tunsigned v1 = -1;\n\n\t\t\tif (f0 == -1) {\n\t\t\t\t// f1 is the face with boundary edge e opposite vertex EI(e, 1)\n\t\t\t\tunsigned v = EI(e, 1);\n\n\t\t\t\tv0 = F(f1, (v + 1) % 3);\n\t\t\t\tv1 = F(f1, (v + 2) % 3);\n\t\t\t}\n\t\t\telse if (f1 == -1) {\n\t\t\t\t// f0 is the face with boundary edge e opposite vertex EI(e, 0)\n\t\t\t\tunsigned v = EI(e, 0);\n\n\t\t\t\tv0 = F(f0, (v + 1) % 3);\n\t\t\t\tv1 = F(f0, (v + 2) % 3);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tmeshOut = Variant();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// v0, v1: indices into vertexList of vertices (in order) of edge on the boundary\n\t\t\tunsigned v2 = v0 + vertexList.Size();\n\t\t\tunsigned v3 = v1 + vertexList.Size();\n\n\t\t\tsideFaceList.Push(Variant(v0));\n\t\t\tsideFaceList.Push(Variant(v1));\n\t\t\tsideFaceList.Push(Variant(v2));\n\t\t\t//\n\t\t\tsideFaceList.Push(Variant(v2));\n\t\t\tsideFaceList.Push(Variant(v1));\n\t\t\tsideFaceList.Push(Variant(v3));\n\t\t}\n\t}\n\n\tVariantVector innerFaceList;\n\tfor (unsigned i = 0; i < faceList.Size(); i += 3) {\n\t\tinnerFaceList.Push(faceList[i]);\n\t\tinnerFaceList.Push(faceList[i + 2]);\n\t\tinnerFaceList.Push(faceList[i + 1]);\n\t}\n\n\t// Collect all the inner, outer, and side panel data\n\t/*\n\tSpeculative: if d < 0, reverse all orientations....\n\t*/\n\n\tVariantVector newVertexList = vertexList;\n\tnewVertexList.Push(outerVertexList);\n\tVariant newVertices(newVertexList);\n\n\tVariantVector newFaceList = innerFaceList;\n\tnewFaceList.Push(outerFaceList);\n\tnewFaceList.Push(sideFaceList);\n\tif (d < 0.0f) {\n\t\tfor (unsigned i = 0; i < newFaceList.Size(); i += 3) {\n\t\t\tint i1 = newFaceList[i + 1].GetInt();\n\t\t\tint i2 = newFaceList[i + 2].GetInt();\n\n\t\t\tnewFaceList[i + 1] = Variant(i2);\n\t\t\tnewFaceList[i + 2] = Variant(i1);\n\t\t}\n\t}\n\tVariant newFaces(newFaceList);\n\n\tmeshOut = TriMesh_Make(newVertices, newFaces);\n\treturn true;\n}", "meta": {"hexsha": "19874d7770b53755f50ffea0740e46138a1c2d9d", "size": 5691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry/Geomlib_TriMeshThicken.cpp", "max_stars_repo_name": "elix22/IogramSource", "max_stars_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T04:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:33:50.000Z", "max_issues_repo_path": "Geometry/Geomlib_TriMeshThicken.cpp", "max_issues_repo_name": "elix22/IogramSource", "max_issues_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-09T05:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T18:38:05.000Z", "max_forks_repo_path": "Geometry/Geomlib_TriMeshThicken.cpp", "max_forks_repo_name": "elix22/IogramSource", "max_forks_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-03-01T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:36:54.000Z", "avg_line_length": 30.7621621622, "max_line_length": 114, "alphanum_fraction": 0.6847654191, "num_tokens": 1645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2311806321737327}}
{"text": "/* ----------------------------------------------------------------------------\n\n * GTSAM Copyright 2010, Georgia Tech Research Corporation,\n * Atlanta, Georgia 30332-0415\n * All Rights Reserved\n * Authors: Frank Dellaert, et al. (see THANKS for the full author list)\n\n * See LICENSE for the license information\n\n * -------------------------------------------------------------------------- */\n\n/**\n * @file    JacobianFactor.cpp\n * @author  Richard Roberts\n * @date    Dec 8, 2010\n */\n\n#include <gtsam/linear/linearExceptions.h>\n#include <gtsam/linear/GaussianConditional.h>\n#include <gtsam/linear/JacobianFactor.h>\n#include <gtsam/linear/HessianFactor.h>\n#include <gtsam/linear/GaussianFactorGraph.h>\n#include <gtsam/inference/VariableSlots.h>\n#include <gtsam/base/debug.h>\n#include <gtsam/base/timing.h>\n#include <gtsam/base/Matrix.h>\n#include <gtsam/base/FastMap.h>\n#include <gtsam/base/cholesky.h>\n\n#include <boost/foreach.hpp>\n#include <boost/format.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/bind.hpp>\n//#include <boost/lambda/bind.hpp>\n//#include <boost/lambda/lambda.hpp>\n\n#include <cmath>\n#include <sstream>\n#include <stdexcept>\n\nusing namespace std;\n//using namespace boost::lambda;\n\nnamespace gtsam {\n\n  /* ************************************************************************* */\n  void JacobianFactor::assertInvariants() const {\n#ifndef NDEBUG\n    GaussianFactor::assertInvariants(); // The base class checks for unique keys\n    assert((size() == 0 && Ab_.rows() == 0 && Ab_.nBlocks() == 0) || size()+1 == Ab_.nBlocks());\n#endif\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor(const JacobianFactor& gf) :\n      GaussianFactor(gf), model_(gf.model_), Ab_(matrix_) {\n    Ab_.assignNoalias(gf.Ab_);\n    assertInvariants();\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor(const GaussianFactor& gf) : Ab_(matrix_) {\n    // Copy the matrix data depending on what type of factor we're copying from\n    if(const JacobianFactor* rhs = dynamic_cast<const JacobianFactor*>(&gf))\n      *this = JacobianFactor(*rhs);\n    else if(const HessianFactor* rhs = dynamic_cast<const HessianFactor*>(&gf))\n      *this = JacobianFactor(*rhs);\n    else\n      throw std::invalid_argument(\"In JacobianFactor(const GaussianFactor& rhs), rhs is neither a JacobianFactor nor a HessianFactor\");\n    assertInvariants();\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor() : Ab_(matrix_) { assertInvariants(); }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor(const Vector& b_in) : Ab_(matrix_) {\n    size_t dims[] = { 1 };\n    Ab_.copyStructureFrom(BlockAb(matrix_, dims, dims+1, b_in.size()));\n    getb() = b_in;\n    model_ = noiseModel::Unit::Create(this->rows());\n    assertInvariants();\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor(Index i1, const Matrix& A1,\n      const Vector& b, const SharedDiagonal& model) :\n      GaussianFactor(i1), model_(model), Ab_(matrix_) {\n\n    if(model->dim() != (size_t) b.size())\n      throw InvalidNoiseModel(b.size(), model->dim());\n\n    size_t dims[] = { A1.cols(), 1};\n    Ab_.copyStructureFrom(BlockAb(matrix_, dims, dims+2, b.size()));\n    Ab_(0) = A1;\n    getb() = b;\n    assertInvariants();\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor(Index i1, const Matrix& A1, Index i2, const Matrix& A2,\n      const Vector& b, const SharedDiagonal& model) :\n      GaussianFactor(i1,i2), model_(model), Ab_(matrix_) {\n\n    if(model->dim() != (size_t) b.size())\n      throw InvalidNoiseModel(b.size(), model->dim());\n\n    size_t dims[] = { A1.cols(), A2.cols(), 1};\n    Ab_.copyStructureFrom(BlockAb(matrix_, dims, dims+3, b.size()));\n    Ab_(0) = A1;\n    Ab_(1) = A2;\n    getb() = b;\n    assertInvariants();\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor(Index i1, const Matrix& A1, Index i2, const Matrix& A2,\n      Index i3, const Matrix& A3, const Vector& b, const SharedDiagonal& model) :\n      GaussianFactor(i1,i2,i3), model_(model), Ab_(matrix_) {\n\n    if(model->dim() != (size_t) b.size())\n      throw InvalidNoiseModel(b.size(), model->dim());\n\n    size_t dims[] = { A1.cols(), A2.cols(), A3.cols(), 1};\n    Ab_.copyStructureFrom(BlockAb(matrix_, dims, dims+4, b.size()));\n    Ab_(0) = A1;\n    Ab_(1) = A2;\n    Ab_(2) = A3;\n    getb() = b;\n    assertInvariants();\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor(const std::vector<std::pair<Index, Matrix> > &terms,\n  \t\tconst Vector &b, const SharedDiagonal& model) :\n  \tGaussianFactor(GetKeys(terms.size(), terms.begin(), terms.end())),\n\t\tmodel_(model), Ab_(matrix_)\n  {\n\n    if(model->dim() != (size_t) b.size())\n      throw InvalidNoiseModel(b.size(), model->dim());\n\n    size_t* dims = (size_t*)alloca(sizeof(size_t)*(terms.size()+1)); // FIXME: alloca is bad, just ask Google.\n    for(size_t j=0; j<terms.size(); ++j)\n      dims[j] = terms[j].second.cols();\n    dims[terms.size()] = 1;\n    Ab_.copyStructureFrom(BlockAb(matrix_, dims, dims+terms.size()+1, b.size()));\n    for(size_t j=0; j<terms.size(); ++j)\n      Ab_(j) = terms[j].second;\n    getb() = b;\n    assertInvariants();\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor(const std::list<std::pair<Index, Matrix> > &terms,\n      const Vector &b, const SharedDiagonal& model) :\n      GaussianFactor(GetKeys(terms.size(), terms.begin(), terms.end())),\n    model_(model), Ab_(matrix_)\n  {\n\n    if(model->dim() != (size_t) b.size())\n      throw InvalidNoiseModel(b.size(), model->dim());\n\n    size_t* dims=(size_t*)alloca(sizeof(size_t)*(terms.size()+1)); // FIXME: alloca is bad, just ask Google.\n    size_t j=0;\n    std::list<std::pair<Index, Matrix> >::const_iterator term=terms.begin();\n    for(; term!=terms.end(); ++term,++j)\n      dims[j] = term->second.cols();\n    dims[j] = 1;\n    Ab_.copyStructureFrom(BlockAb(matrix_, dims, dims+terms.size()+1, b.size()));\n    j = 0;\n    for(term=terms.begin(); term!=terms.end(); ++term,++j)\n      Ab_(j) = term->second;\n    getb() = b;\n    assertInvariants();\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor(const GaussianConditional& cg) :\n\t\tGaussianFactor(cg),\n\t\tmodel_(noiseModel::Diagonal::Sigmas(cg.get_sigmas(), true)),\n\t\tAb_(matrix_) {\n    Ab_.assignNoalias(cg.rsd_);\n    assertInvariants();\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor::JacobianFactor(const HessianFactor& factor) : Ab_(matrix_) {\n    keys_ = factor.keys_;\n    Ab_.assignNoalias(factor.info_);\n\n\t\t// Do Cholesky to get a Jacobian\n    size_t maxrank;\n\t\tbool success;\n\t\tboost::tie(maxrank, success) = choleskyCareful(matrix_);\n\n\t\t// Check for indefinite system\n\t\tif(!success)\n\t\t\tthrow IndeterminantLinearSystemException(factor.keys().front());\n\n    // Zero out lower triangle\n    matrix_.topRows(maxrank).triangularView<Eigen::StrictlyLower>() =\n        Matrix::Zero(maxrank, matrix_.cols());\n    // FIXME: replace with triangular system\n    Ab_.rowEnd() = maxrank;\n    model_ = noiseModel::Unit::Create(maxrank);\n\n    assertInvariants();\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor& JacobianFactor::operator=(const JacobianFactor& rhs) {\n    this->Base::operator=(rhs); // Copy keys\n    model_ = rhs.model_;        // Copy noise model\n    Ab_.assignNoalias(rhs.Ab_); // Copy matrix and block structure\n    assertInvariants();\n    return *this;\n  }\n\n  /* ************************************************************************* */\n  void JacobianFactor::print(const string& s, const IndexFormatter& formatter) const {\n    cout << s << \"\\n\";\n    if (empty()) {\n      cout << \" empty, keys: \";\n      BOOST_FOREACH(const Index& key, keys()) { cout << formatter(key) << \" \"; }\n      cout << endl;\n    } else {\n      for(const_iterator key=begin(); key!=end(); ++key)\n      \tcout << boost::format(\"A[%1%]=\\n\")%formatter(*key) << getA(key) << endl;\n      cout << \"b=\" << getb() << endl;\n      model_->print(\"model\");\n    }\n  }\n\n  /* ************************************************************************* */\n  // Check if two linear factors are equal\n  bool JacobianFactor::equals(const GaussianFactor& f_, double tol) const {\n    if(!dynamic_cast<const JacobianFactor*>(&f_))\n      return false;\n    else {\n      const JacobianFactor& f(static_cast<const JacobianFactor&>(f_));\n      if (empty()) return (f.empty());\n      if(keys()!=f.keys() /*|| !model_->equals(lf->model_, tol)*/)\n        return false;\n\n      if (!(Ab_.rows() == f.Ab_.rows() && Ab_.cols() == f.Ab_.cols()))\n      \treturn false;\n\n      constABlock Ab1(Ab_.range(0, Ab_.nBlocks()));\n      constABlock Ab2(f.Ab_.range(0, f.Ab_.nBlocks()));\n      for(size_t row=0; row< (size_t) Ab1.rows(); ++row)\n        if(!equal_with_abs_tol(Ab1.row(row), Ab2.row(row), tol) &&\n            !equal_with_abs_tol(-Ab1.row(row), Ab2.row(row), tol))\n          return false;\n\n      return true;\n    }\n  }\n\n  /* ************************************************************************* */\n  Vector JacobianFactor::unweighted_error(const VectorValues& c) const {\n    Vector e = -getb();\n    if (empty()) return e;\n    for(size_t pos=0; pos<size(); ++pos)\n      e += Ab_(pos) * c[keys_[pos]];\n    return e;\n  }\n\n  /* ************************************************************************* */\n  Vector JacobianFactor::error_vector(const VectorValues& c) const {\n    if (empty()) return model_->whiten(-getb());\n    return model_->whiten(unweighted_error(c));\n  }\n\n  /* ************************************************************************* */\n  double JacobianFactor::error(const VectorValues& c) const {\n    if (empty()) return 0;\n    Vector weighted = error_vector(c);\n    return 0.5 * weighted.dot(weighted);\n  }\n\n  /* ************************************************************************* */\n  Matrix JacobianFactor::computeInformation() const {\n    Matrix AbWhitened = Ab_.full();\n    model_->WhitenInPlace(AbWhitened);\n    return AbWhitened.transpose() * AbWhitened;\n  }\n\n  /* ************************************************************************* */\n  Vector JacobianFactor::operator*(const VectorValues& x) const {\n    Vector Ax = zero(Ab_.rows());\n    if (empty()) return Ax;\n\n    // Just iterate over all A matrices and multiply in correct config part\n    for(size_t pos=0; pos<size(); ++pos)\n      Ax += Ab_(pos) * x[keys_[pos]];\n\n    return model_->whiten(Ax);\n  }\n\n  /* ************************************************************************* */\n  void JacobianFactor::transposeMultiplyAdd(double alpha, const Vector& e,\n      VectorValues& x) const {\n    Vector E = alpha * model_->whiten(e);\n    // Just iterate over all A matrices and insert Ai^e into VectorValues\n    for(size_t pos=0; pos<size(); ++pos)\n      gtsam::transposeMultiplyAdd(1.0, Ab_(pos), E, x[keys_[pos]]);\n  }\n\n  /* ************************************************************************* */\n  pair<Matrix,Vector> JacobianFactor::matrix(bool weight) const {\n    Matrix A(Ab_.range(0, size()));\n    Vector b(getb());\n    // divide in sigma so error is indeed 0.5*|Ax-b|\n    if (weight) model_->WhitenSystem(A,b);\n    return make_pair(A, b);\n  }\n\n  /* ************************************************************************* */\n  Matrix JacobianFactor::matrix_augmented(bool weight) const {\n    if (weight) { Matrix Ab(Ab_.range(0,Ab_.nBlocks())); model_->WhitenInPlace(Ab); return Ab; }\n    else return Ab_.range(0, Ab_.nBlocks());\n  }\n\n  /* ************************************************************************* */\n  std::vector<boost::tuple<size_t, size_t, double> >\n  JacobianFactor::sparse(const std::vector<size_t>& columnIndices) const {\n\n    std::vector<boost::tuple<size_t, size_t, double> > entries;\n\n    // iterate over all variables in the factor\n    for(const_iterator var=begin(); var<end(); ++var) {\n      Matrix whitenedA(model_->Whiten(getA(var)));\n      // find first column index for this key\n      size_t column_start = columnIndices[*var];\n      for (size_t i = 0; i < (size_t) whitenedA.rows(); i++)\n        for (size_t j = 0; j < (size_t) whitenedA.cols(); j++) {\n        \tdouble s = whitenedA(i,j);\n          if (std::abs(s) > 1e-12) entries.push_back(\n\t\t\t\t\t\t\tboost::make_tuple(i, column_start + j, s));\n        }\n    }\n\n    Vector whitenedb(model_->whiten(getb()));\n    size_t bcolumn = columnIndices.back();\n    for (size_t i = 0; i < (size_t) whitenedb.size(); i++)\n      entries.push_back(boost::make_tuple(i, bcolumn, whitenedb(i)));\n\n    // return the result\n    return entries;\n  }\n\n  /* ************************************************************************* */\n  JacobianFactor JacobianFactor::whiten() const {\n    JacobianFactor result(*this);\n    result.model_->WhitenInPlace(result.matrix_);\n    result.model_ = noiseModel::Unit::Create(result.model_->dim());\n    return result;\n  }\n\n  /* ************************************************************************* */\n  GaussianFactor::shared_ptr JacobianFactor::negate() const {\n  \tHessianFactor hessian(*this);\n  \treturn hessian.negate();\n  }\n\n  /* ************************************************************************* */\n  GaussianConditional::shared_ptr JacobianFactor::eliminateFirst() {\n    return this->eliminate(1);\n  }\n\n  /* ************************************************************************* */\n  GaussianConditional::shared_ptr JacobianFactor::splitConditional(size_t nrFrontals) {\n  \tassert(Ab_.rowStart() == 0 && Ab_.rowEnd() == (size_t) matrix_.rows() && Ab_.firstBlock() == 0);\n  \tassert(size() >= nrFrontals);\n  \tassertInvariants();\n\n  \tconst bool debug = ISDEBUG(\"JacobianFactor::splitConditional\");\n\n  \tif(debug) cout << \"Eliminating \" << nrFrontals << \" frontal variables\" << endl;\n  \tif(debug) this->print(\"Splitting JacobianFactor: \");\n\n  \tsize_t frontalDim = Ab_.range(0,nrFrontals).cols();\n\n  \t// Check for singular factor\n  \tif(model_->dim() < frontalDim)\n\t\t\tthrow IndeterminantLinearSystemException(this->keys().front());\n\n  \t// Extract conditional\n  \ttic(3, \"cond Rd\");\n\n  \t// Restrict the matrix to be in the first nrFrontals variables\n  \tAb_.rowEnd() = Ab_.rowStart() + frontalDim;\n  \tconst Eigen::VectorBlock<const Vector> sigmas = model_->sigmas().segment(Ab_.rowStart(), Ab_.rowEnd()-Ab_.rowStart());\n  \tGaussianConditional::shared_ptr conditional(new GaussianConditional(begin(), end(), nrFrontals, Ab_, sigmas));\n  \tif(debug) conditional->print(\"Extracted conditional: \");\n  \tAb_.rowStart() += frontalDim;\n  \tAb_.firstBlock() += nrFrontals;\n  \ttoc(3, \"cond Rd\");\n\n  \tif(debug) conditional->print(\"Extracted conditional: \");\n\n  \ttic(4, \"remaining factor\");\n  \t// Take lower-right block of Ab to get the new factor\n  \tAb_.rowEnd() = model_->dim();\n  \tkeys_.erase(begin(), begin() + nrFrontals);\n  \t// Set sigmas with the right model\n  \tif (model_->isConstrained())\n  \t\tmodel_ = noiseModel::Constrained::MixedSigmas(sub(model_->sigmas(), frontalDim, model_->dim()));\n  \telse\n  \t\tmodel_ = noiseModel::Diagonal::Sigmas(sub(model_->sigmas(), frontalDim, model_->dim()));\n  \tif(debug) this->print(\"Eliminated factor: \");\n  \tassert(Ab_.rows() <= Ab_.cols()-1);\n  \ttoc(4, \"remaining factor\");\n\n  \tif(debug) print(\"Eliminated factor: \");\n\n  \tassertInvariants();\n\n  \treturn conditional;\n  }\n\n  /* ************************************************************************* */\n  GaussianConditional::shared_ptr JacobianFactor::eliminate(size_t nrFrontals) {\n\n    assert(Ab_.rowStart() == 0 && Ab_.rowEnd() == (size_t) matrix_.rows() && Ab_.firstBlock() == 0);\n    assert(size() >= nrFrontals);\n    assertInvariants();\n\n    const bool debug = ISDEBUG(\"JacobianFactor::eliminate\");\n\n    if(debug) cout << \"Eliminating \" << nrFrontals << \" frontal variables\" << endl;\n    if(debug) this->print(\"Eliminating JacobianFactor: \");\n    if(debug) gtsam::print(matrix_, \"Augmented Ab: \");\n\n    size_t frontalDim = Ab_.range(0,nrFrontals).cols();\n\n    if(debug) cout << \"frontalDim = \" << frontalDim << endl;\n\n    // Use in-place QR dense Ab appropriate to NoiseModel\n    tic(2, \"QR\");\n    SharedDiagonal noiseModel = model_->QR(matrix_);\n    toc(2, \"QR\");\n\n    // Zero the lower-left triangle.  todo: not all of these entries actually\n    // need to be zeroed if we are careful to start copying rows after the last\n    // structural zero.\n    if(matrix_.rows() > 0)\n      for(size_t j=0; j<(size_t) matrix_.cols(); ++j)\n        for(size_t i=j+1; i<noiseModel->dim(); ++i)\n          matrix_(i,j) = 0.0;\n\n    if(debug) gtsam::print(matrix_, \"QR result: \");\n    if(debug) noiseModel->print(\"QR result noise model: \");\n\n    // Start of next part\n    model_ = noiseModel;\n    return splitConditional(nrFrontals);\n  }\n\n  /* ************************************************************************* */\n  void JacobianFactor::allocate(const VariableSlots& variableSlots, vector<\n\t\t\tsize_t>& varDims, size_t m) {\n\t\tkeys_.resize(variableSlots.size());\n\t\tstd::transform(variableSlots.begin(), variableSlots.end(), begin(),\n\t\t\t\tboost::bind(&VariableSlots::const_iterator::value_type::first, _1));\n\t\tvarDims.push_back(1);\n\t\tAb_.copyStructureFrom(BlockAb(matrix_, varDims.begin(), varDims.end(), m));\n\t}\n\n  /* ************************************************************************* */\n\tvoid JacobianFactor::setModel(bool anyConstrained, const Vector& sigmas) {\n    if((size_t) sigmas.size() != this->rows())\n      throw InvalidNoiseModel(this->rows(), sigmas.size());\n\t\tif (anyConstrained)\n\t\t\tmodel_ = noiseModel::Constrained::MixedSigmas(sigmas);\n\t\telse\n\t\t\tmodel_ = noiseModel::Diagonal::Sigmas(sigmas);\n\t}\n\n  /* ************************************************************************* */\n  const char* JacobianFactor::InvalidNoiseModel::what() const throw() {\n    if(description_.empty())\n      description_ = (boost::format(\n        \"A JacobianFactor was attempted to be constructed or modified to use a\\n\"\n        \"noise model of incompatible dimension.  The JacobianFactor has\\n\"\n        \"dimensionality (i.e. length of error vector) %d but the provided noise\\n\"\n        \"model has dimensionality %d.\") % factorDims % noiseModelDims).str();\n    return description_.c_str();\n  }\n\n}\n", "meta": {"hexsha": "759be49487088004d76357f69bb35ad579128bc4", "size": 18626, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/linear/JacobianFactor.cpp", "max_stars_repo_name": "sdmiller/gtsam_pcl", "max_stars_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-04T16:41:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T07:02:44.000Z", "max_issues_repo_path": "gtsam/linear/JacobianFactor.cpp", "max_issues_repo_name": "sdmiller/gtsam_pcl", "max_issues_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gtsam/linear/JacobianFactor.cpp", "max_forks_repo_name": "sdmiller/gtsam_pcl", "max_forks_repo_head_hexsha": "1e607bd75090d35e325a8fb37a6c5afe630f1207", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-09-10T12:06:08.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T07:02:48.000Z", "avg_line_length": 37.7809330629, "max_line_length": 135, "alphanum_fraction": 0.5573928917, "num_tokens": 4561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.23111686994105915}}
{"text": "/**\n * Copyright (c) 2012, Akamai Technologies\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n *   Redistributions of source code must retain the above copyright\n *   notice, this list of conditions and the following disclaimer.\n * \n *   Redistributions in binary form must reproduce the above\n *   copyright notice, this list of conditions and the following\n *   disclaimer in the documentation and/or other materials provided\n *   with the distribution.\n * \n *   Neither the name of the Akamai Technologies nor the names of its\n *   contributors may be used to endorse or promote products derived\n *   from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef __LOSERTREE_HH__\n#define __LOSERTREE_HH__\n\n#include <stdint.h>\n#include <limits>\n#include <functional>\n#include <stdexcept>\n#include <boost/assert.hpp>\n#include <boost/format.hpp>\n\nclass Bithack\n{\npublic:\n  static uint32_t roundUpPow2(uint32_t v) {\n    v--;\n    v |= v >> 1;\n    v |= v >> 2;\n    v |= v >> 4;\n    v |= v >> 8;\n    v |= v >> 16;\n    return ++v;\n  }\n  static uint32_t logBase2(uint32_t v) {\n    static const int MultiplyDeBruijnBitPosition[32] = \n      {\n\t0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,\n\t8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31\n      };\n    \n    v |= v >> 1; // first round down to one less than a power of 2 \n    v |= v >> 2;\n    v |= v >> 4;\n    v |= v >> 8;\n    v |= v >> 16;\n    \n    return MultiplyDeBruijnBitPosition[(uint32_t)(v * 0x07C4ACDDU) >> 27];  \n  }\n};\n\n/**\n * A Tournament tree of losers.\n * Many of the implementation details here are taken\n * from Graefe \"Implementing Sorting in Database Systems\".\n */\ntemplate <class _Data, class _Compare = std::less<_Data> >\nclass LoserTree\n{\npublic:\n  class Node \n  {\n  public:\n    /**\n     * Player in the tournament that lost here.\n     */\n    uint32_t InputNumber;\n    /**\n     * Prefix of normalized key.\n     */\n    uint32_t KeyPrefix;\n    /**\n     * The full record in the tree.  Required \n     * to resolve equality when KeyPrefixes are equal.\n     */\n    _Data Value;\n  };\n\nprivate:\n  class SentinelPolicy\n  {\n  public:\n    static const uint32_t MaxPlayers = 8192;\n    static const uint32_t MaxPlayersLog2 = 13;\n    // We've reserved 2*8192 values for low/high sentinels,\n    // this leaves us with 2^32 - 2*8192 for real key\n    // values.  For simplicity we take only 2^31 values.\n    static const uint32_t KeyPrefixLog2 = 31;\n    static uint32_t getMaxPlayers() {\n      return MaxPlayers;\n    }\n    /**\n     * Get high sorting sentinel value for player i.\n     * Guarantees that sentinels are in increasing order with\n     * player index.\n     */\n    static uint32_t getHighSentinel(uint32_t i) {\n      return std::numeric_limits<uint32_t>::max() - MaxPlayers + i;\n    }\n    static bool isHighSentinel(uint32_t i) {\n      return i >=std::numeric_limits<uint32_t>::max() - MaxPlayers;\n    }\n    /**\n     * Get low sorting sentinel value for player i.\n     * Guarantees that sentinels are in increasing order with\n     * player index.\n     */\n    static uint32_t getLowSentinel(uint32_t i) {\n      return i;\n    }\n    static bool isLowSentinel(uint32_t i) {\n      return i < MaxPlayers;\n    }\n    /**\n     * Apply correction of a user key value so that it may\n     * be inserted into a node.\n     */\n    static uint32_t insertKey(uint32_t i) {\n\treturn i + MaxPlayers;\n    }\n    /** \n     * Apply correction to a node key so that the user\n     * key is recreated.\n     */\n    static uint32_t removeKey(uint32_t i) {\n      return i - MaxPlayers;\n    }\n  };\n\n  uint32_t mNumPlayers;\n  Node * mNodes;\n  _Compare mCompare;\n\n  void internalUpdate(uint32_t player, uint32_t keyPrefix, _Data val);\n\npublic:\n  LoserTree();\n  LoserTree(uint32_t numberOfPlayers, const _Compare& eq = _Compare());\n  ~LoserTree();\n\n  /**\n   * Initialize a loser tournament tree for\n   * numberOfPlayers inputs.\n   */\n  void init(uint32_t numberOfPlayers, const _Compare& eq = _Compare());\n  /**\n   * Replace the entry at position player with the value val whose\n   * key prefix is keyPrefix.\n   */\n  void update(uint32_t player, uint32_t keyPrefix, _Data val)\n  {\n    // Apply sentinel correction to prefix\n    internalUpdate(player, SentinelPolicy::insertKey(keyPrefix), val);\n  }\n  /**\n   * Return the root node of the tree.\n   */\n  Node& getRoot()\n  {\n    return mNodes[0];\n  }\n  /**\n   * Check if high sentinel.\n   */\n  bool isHighSentinel() const;\n  /**\n   * Check if tree is empty.\n   */\n  bool empty() const\n  {\n    return SentinelPolicy::isLowSentinel(mNodes[0].KeyPrefix);\n  }\n  /**\n   * Close the input to the tree.\n   */\n  void close(uint32_t input)\n  {\n    internalUpdate(input, SentinelPolicy::getLowSentinel(input), NULL);\n  }\n  /**\n   * Get the key of the top.\n   */\n  uint32_t getKeyPrefix() const \n  {\n    return SentinelPolicy::removeKey(mNodes[0].KeyPrefix);\n  }\n  /**\n   * The input/player corresponding to the top.\n   */\n  uint32_t getInput() const\n  {\n    return mNodes[0].InputNumber;\n  }\n  /**\n   * The value corresponding to the top.\n   */\n  _Data getValue() const\n  {\n    return mNodes[0].Value;\n  }\n};\n\ntemplate <class _Data, class _Compare>\nLoserTree<_Data,_Compare>::LoserTree()\n  :\n  mNumPlayers(0),\n  mNodes(NULL),\n  mCompare(_Compare())\n{\n}\n\ntemplate <class _Data, class _Compare>\nLoserTree<_Data,_Compare>::LoserTree(uint32_t numberOfPlayers, const _Compare& eq)\n  :\n  mNumPlayers(0),\n  mNodes(NULL),\n  mCompare(eq)\n{\n  init(numberOfPlayers,eq);\n}\n\ntemplate <class _Data, class _Compare>\nLoserTree<_Data,_Compare>::~LoserTree()\n{\n  delete [] mNodes;\n}\n\ntemplate <class _Data, class _Compare>\nvoid LoserTree<_Data,_Compare>::init(uint32_t numberOfPlayers, \n\t\t\t\t    const _Compare& eq)\n{\n  // Reset state.\n  delete [] mNodes;\n  mNumPlayers = numberOfPlayers;\n  mCompare = eq;\n\n  // There is an easy to compute closed from for initializing\n  // a tree that is a power of 2.  I don't know of a closed form\n  // for initializing arbitrary tree (though I suspect it isn't\n  // too hard to calculate).  For the moment we round up to \n  // nearest power of 2, build tree and then close inputs that\n  // we aren't using.  There is a little memory wastage but it\n  // shouldn't be macroscopic (nor are there cache implications\n  // because we'll never touch the tail of the array after we\n  // init).\n  numberOfPlayers = Bithack::roundUpPow2(mNumPlayers);\n  uint32_t numberOfPlayersLog2 = Bithack::logBase2(numberOfPlayers);\n  // Our use of sentinels limits the number of inputs to the tree.\n  if (numberOfPlayers > SentinelPolicy::getMaxPlayers()) {\n    throw std::runtime_error((boost::format(\"Cannot merge more than %1% streams\") %\n\t\t\t      SentinelPolicy::getMaxPlayers()).str());\n  }\n  // TODO: Assume number of players is a power of 2 for now.\n  // Gotta figure out clean logic for initializing an arbitrary\n  // tree.\n  // Initialize tree.\n  mNodes = new Node [numberOfPlayers];\n\n  for(uint32_t lev=1; lev<=numberOfPlayersLog2; lev++) {\n    uint32_t levelBegin = numberOfPlayers >> lev;\n    uint32_t numInLevel = levelBegin;\n    uint32_t levelInc = (1<<lev);\n    for(uint32_t i=0; i<numInLevel; i++) {\n      uint32_t tmp = (1 << (lev-1)) - 1 + levelInc*i;\n      BOOST_ASSERT(levelBegin+i < numberOfPlayers);\n      mNodes[levelBegin + i].InputNumber = tmp;\n      mNodes[levelBegin + i].KeyPrefix=SentinelPolicy::getHighSentinel(tmp);\n      // We never need this because sentinels never compare equal to anything.\n      mNodes[levelBegin + i].Value = NULL;\n    }\n  }\n  mNodes[0].InputNumber = numberOfPlayers-1;\n  mNodes[0].KeyPrefix = SentinelPolicy::getHighSentinel(numberOfPlayers - 1);  \n  mNodes[0].Value = NULL;\n\n  // Close all excess inputs\n  for(uint32_t i=mNumPlayers; i<numberOfPlayers; i++) {\n    close(i);\n  }\n}\n\ntemplate <class _Data, class _Compare>\nvoid LoserTree<_Data,_Compare>::internalUpdate(uint32_t player, uint32_t keyPrefix, _Data val)\n{\n  // Bottom up tournament.  Start playing in bracket player/2.\n  for(std::size_t idx = (Bithack::roundUpPow2(mNumPlayers)>>1) + (player >> 1);\n      idx>=1;\n      idx >>= 1) {\n    Node & n (mNodes[idx]);\n    bool cmp = keyPrefix < n.KeyPrefix ||\n      (keyPrefix==n.KeyPrefix && mCompare(val, n.Value));\n\n    if(cmp) {\n      std::swap(player, n.InputNumber);\n      std::swap(keyPrefix, n.KeyPrefix);\n      std::swap(val, n.Value);\n    } \n  }\n\n  // Update the top of the tree\n  mNodes[0].InputNumber = player;\n  mNodes[0].KeyPrefix = keyPrefix;\n  mNodes[0].Value = val;\n}\n\ntemplate <class _Data, class _Compare>\nbool LoserTree<_Data,_Compare>::isHighSentinel() const {\n  return SentinelPolicy::isHighSentinel(mNodes[0].KeyPrefix);\n}\n\n\n// Extract configured number of bits from\n// normalized keys.  Make them into a N-bit\n// integer that can be compared using integer\n// comparison instructions.\n// TODO: Do we assume that we have to build\n// the entire normalized key and then extract\n// the prefix?\nclass KeyPrefixBuilder {\nprivate:\n  uint32_t mPrefix;\n  uint32_t mBitsPos;\n  const uint32_t mBitsEnd;\n\n  // Copy the bits at the position of the current bit iterator.\n  typedef uint8_t _IntTy;\n  bool copyTo(const _IntTy * begin, uint32_t beginBitPos, uint32_t endBitPos) {\n    while(mBitsPos<mBitsEnd && beginBitPos != endBitPos) {\n      uint32_t beginByte = beginBitPos/(8*sizeof(_IntTy));\n      uint32_t beginOffsetWithinByte = beginBitPos - (beginByte*8*sizeof(_IntTy));\n      uint32_t bitsToCopy = std::min(mBitsEnd-mBitsPos, \n\t\t\t\t     8*((uint32_t) sizeof(_IntTy)) - beginOffsetWithinByte);\n      // 2^bitsToCopy-1, then shift into place.  Very tricky thing is that\n      // we want to take most significant bits first.\n      _IntTy sourceMask = (bitsToCopy ? ~_IntTy(0) << (8*sizeof(_IntTy) - bitsToCopy) : _IntTy(0));\n      sourceMask >>= beginOffsetWithinByte;\n      // Extract correct bits.\n      uint32_t newBits = ((uint32_t) (begin[beginByte] & sourceMask)) << mBitsPos;\n      mPrefix |= newBits;\n      mBitsPos += bitsToCopy;\n      beginBitPos += bitsToCopy;\n    }\n    return mBitsPos == mBitsEnd;\n  }\n\n  static uint32_t byteSwap(uint32_t val)\n  {\n    return ((((val) & 0xff000000) >> 24) |\n\t    (((val) & 0x00ff0000) >>  8) |\n\t    (((val) & 0x0000ff00) <<  8) |\n\t    (((val) & 0x000000ff) << 24));\n  }\n\npublic:\n  KeyPrefixBuilder(uint32_t bits)\n    :\n    mPrefix(0),\n    mBitsPos(0),\n    mBitsEnd(bits)\n  {\n  }\n\n  bool add(uint32_t v)\n  {\n    // Byte swap\n    uint32_t ret = byteSwap(v);\n    // Consume up to the available 32-bits\n    return copyTo((const uint8_t *) &ret, 0, 32);   \n  }\n\n  bool add(const uint8_t * begin, const uint8_t * end)\n  {\n    return copyTo(begin, 0, 8*(end-begin));   \n  }\n\n  bool add(const char * begin, const char * end)\n  {\n    return copyTo((const uint8_t *) begin, 0, 8*(end-begin));   \n  }\n\n  uint32_t getPrefix() const\n  {\n    return byteSwap(mPrefix) >> (32-mBitsEnd);\n  }\n\n  void clear() \n  {\n    mPrefix = 0;\n    mBitsPos = 0;\n  }\n};\n\n#endif\n", "meta": {"hexsha": "6b53925395eba614d9043eb6f091524399e93e3f", "size": 11789, "ext": "hh", "lang": "C++", "max_stars_repo_path": "ads-df/LoserTree.hh", "max_stars_repo_name": "lairofthegoldinblair/trecul", "max_stars_repo_head_hexsha": "41953c22f18f76e5add7a35a13775f70459fcd96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T13:24:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-17T05:47:43.000Z", "max_issues_repo_path": "ads-df/LoserTree.hh", "max_issues_repo_name": "lairofthegoldinblair/trecul", "max_issues_repo_head_hexsha": "41953c22f18f76e5add7a35a13775f70459fcd96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ads-df/LoserTree.hh", "max_forks_repo_name": "lairofthegoldinblair/trecul", "max_forks_repo_head_hexsha": "41953c22f18f76e5add7a35a13775f70459fcd96", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-12-24T16:29:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-04T19:30:18.000Z", "avg_line_length": 28.3389423077, "max_line_length": 99, "alphanum_fraction": 0.6646874205, "num_tokens": 3311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.23087156540677792}}
{"text": "#ifndef GUNEROTRANSACTIONSEND_GADGET_H_\n#define GUNEROTRANSACTIONSEND_GADGET_H_\n\n#include <deque>\n#include <boost/optional.hpp>\n#include <boost/static_assert.hpp>\n#include <libff/common/utils.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/uscs_ppzksnark/uscs_ppzksnark.hpp>\n#include <libff/algebra/fields/field_utils.hpp>\n#include <libff/algebra/scalar_multiplication/multiexp.hpp>\n#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libff/algebra/curves/edwards/edwards_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp>\n#include <libff/common/utils.hpp>\n\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp>\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_update_gadget.hpp>\n\n#include \"uint252.h\"\n\nusing namespace libsnark;\n\nnamespace gunero {\n\n///// TRANSACTION SEND PROOF /////\n// With this proof, we are validating that the sender of the token is accepting that this token's ownership should\n// be transferred to the new transaction hash given. The \"account view hash\" validates that this proof is consistent\n// with the others generated, and also serves as an additional precaution for others using this proof to validate an\n// unauthorized release of the token to a party not covered in the transaction.\n// Public Parameters:\n// Current Authorization Root Hash (W)\n// Token UID (T)\n// Sender Account View Hash (V_S)\n// Receiver Account View Hash (V_R)\n// Previous Transaction Hash (L_P)\n\n// Private Parameters:\n// Sender Private Key (s_S)\n// Sender Account View Randomizer (r_S)\n// Receiver Account View Randomizer (r_R)\n// Previous Sender Account Address (A_PS)\n// Previous Authorization Root Hash (W_P)\n// alt: Receiver Proof Public Key (P_proof_R)\n\n//1) Obtain A_S from s_S through EDCSA operations\n//1 alt) Obtain P_proof_S from s_S through PRF operations\n//2) Validate V_S == hash(A_S, hash(W, r_S)) (View Hash is consistent for Sender)\n//2 alt) Validate V_S == hash(P_proof_S, hash(W, r_S)) (View Hash is consistent for Sender)\n//3) Validate V_R == hash(A_R, hash(W, r_R)) (View Hash is consistent for Receiver)\n//3 alt) Validate V_R == hash(P_proof_R, hash(W, r_R)) (View Hash is consistent for Receiver)\n//4) Validate L_P == hash(A_PS, hash(s_S, hash(T, W_P))) (The send proof is valid, sender owns token)\ntemplate<typename FieldT, typename BaseT, typename HashT>\nclass gunerotransactionsend_gadget : public gadget<FieldT> {\npublic:\n    // Verifier inputs\n    pb_variable_array<FieldT> zk_packed_inputs;\n    pb_variable_array<FieldT> zk_unpacked_inputs;\n    std::shared_ptr<multipacking_gadget<FieldT>> unpacker;\n    std::shared_ptr<digest_variable<FieldT>> W;\n    std::shared_ptr<digest_variable<FieldT>> T;\n    std::shared_ptr<digest_variable<FieldT>> V_S;\n    std::shared_ptr<digest_variable<FieldT>> V_R;\n    std::shared_ptr<digest_variable<FieldT>> L_P;\n\n    // Aux inputs\n    // pb_variable<FieldT> ZERO;\n    std::shared_ptr<digest_variable<FieldT>> ZERO;\n    std::shared_ptr<digest_variable<FieldT>> s_S;\n    std::shared_ptr<digest_variable<FieldT>> r_S;\n    std::shared_ptr<digest_variable<FieldT>> r_R;\n    std::shared_ptr<digest_variable<FieldT>> A_PS;\n    std::shared_ptr<digest_variable<FieldT>> W_P;\n    std::shared_ptr<digest_variable<FieldT>> P_proof_R;//alt\n\n    // Computed variables\n    std::shared_ptr<digest_variable<FieldT>> P_proof_S;\n    // std::shared_ptr<PRF_addr_a_pk_simple_gadget<FieldT>> spend_authority;\n    std::shared_ptr<HashT> spend_authority;\n    std::shared_ptr<digest_variable<FieldT>> view_hash_1_digest;\n    std::shared_ptr<HashT> view_hash_1_hasher;\n    std::shared_ptr<HashT> view_hash_2_hasher;\n    std::shared_ptr<digest_variable<FieldT>> view_hash_2_digest;\n    std::shared_ptr<HashT> view_hash_3_hasher;\n    std::shared_ptr<HashT> view_hash_4_hasher;\n    std::shared_ptr<digest_variable<FieldT>> transaction_hash_1_digest;\n    std::shared_ptr<HashT> transaction_hash_1_hasher;\n    std::shared_ptr<digest_variable<FieldT>> transaction_hash_2_digest;\n    std::shared_ptr<HashT> transaction_hash_2_hasher;\n    std::shared_ptr<HashT> transaction_hash_3_hasher;\n\n    gunerotransactionsend_gadget(protoboard<FieldT>& pb)\n        : gadget<FieldT>(pb, \"guneromembership_gadget\")\n    {\n        // Verifier inputs\n        {\n            // The verification inputs are all bit-strings of various\n            // lengths (256-bit digests and 64-bit integers) and so we\n            // pack them into as few field elements as possible. (The\n            // more verification inputs you have, the more expensive\n            // verification is.)\n            zk_packed_inputs.allocate(pb, verifying_field_element_size());\n            pb.set_input_sizes(verifying_field_element_size());\n\n            alloc_uint256(zk_unpacked_inputs, W);\n            alloc_uint256(zk_unpacked_inputs, T);\n            alloc_uint256(zk_unpacked_inputs, V_S);\n            alloc_uint256(zk_unpacked_inputs, V_R);\n            alloc_uint256(zk_unpacked_inputs, L_P);\n\n            assert(zk_unpacked_inputs.size() == verifying_input_bit_size());\n\n            // This gadget will ensure that all of the inputs we provide are\n            // boolean constrained.\n            unpacker.reset(new multipacking_gadget<FieldT>(\n                pb,\n                zk_unpacked_inputs,\n                zk_packed_inputs,\n                FieldT::capacity(),\n                \"unpacker\"\n            ));\n        }\n\n        // We need a constant \"zero\" variable in some contexts. In theory\n        // it should never be necessary, but libsnark does not synthesize\n        // optimal circuits.\n        //\n        // The first variable of our constraint system is constrained\n        // to be one automatically for us, and is known as `ONE`.\n        // ZERO.allocate(pb);\n        ZERO.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        //We enforce 256 bits instead of 252 because of hash size compliance\n        s_S.reset(new digest_variable<FieldT>(pb, 256, \"\"));//252\n\n        r_S.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        r_R.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        A_PS.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        W_P.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        P_proof_R.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        P_proof_S.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        // spend_authority.reset(new PRF_addr_a_pk_simple_gadget<FieldT>(\n        //     pb,\n        //     ZERO,\n        //     s_S->bits,\n        //     P_proof_S\n        // ));\n        spend_authority.reset(new HashT(\n            pb,\n            *s_S,\n            *ZERO,\n            *P_proof_S,\n            \"spend_authority\"));\n\n        //hash(P_proof_S, hash(W, r_S)) == V_S\n        view_hash_1_digest.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        view_hash_1_hasher.reset(new HashT(\n            pb,\n            *W,\n            *r_S,\n            *view_hash_1_digest,\n            \"view_hash_1_hasher\"));\n\n        view_hash_2_hasher.reset(new HashT(\n            pb,\n            *P_proof_S,\n            *view_hash_1_digest,\n            *V_S,\n            \"view_hash_2_hasher\"));\n\n        //hash(P_proof_R, hash(W, r_R)) == V_R\n        view_hash_2_digest.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        view_hash_3_hasher.reset(new HashT(\n            pb,\n            *W,\n            *r_R,\n            *view_hash_2_digest,\n            \"view_hash_3_hasher\"));\n\n        view_hash_4_hasher.reset(new HashT(\n            pb,\n            *P_proof_R,\n            *view_hash_2_digest,\n            *V_R,\n            \"view_hash_4_hasher\"));\n\n        //hash(A_PS, hash(s_S, hash(T, W_P))) == L_P\n        transaction_hash_1_digest.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        transaction_hash_1_hasher.reset(new HashT(\n            pb,\n            *T,\n            *W_P,\n            *transaction_hash_1_digest,\n            \"transaction_hash_1_hasher\"));\n\n        transaction_hash_2_digest.reset(new digest_variable<FieldT>(pb, 256, \"\"));\n\n        transaction_hash_2_hasher.reset(new HashT(\n            pb,\n            *s_S,\n            *transaction_hash_1_digest,\n            *transaction_hash_2_digest,\n            \"transaction_hash_2_hasher\"));\n\n        transaction_hash_3_hasher.reset(new HashT(\n            pb,\n            *A_PS,\n            *transaction_hash_2_digest,\n            *L_P,\n            \"transaction_hash_3_hasher\"));\n    }\n\n    ~gunerotransactionsend_gadget()\n    {\n\n    }\n\n    static size_t verifying_input_bit_size() {\n        size_t acc = 0;\n\n        //W\n        acc += HashT::get_digest_len(); // the merkle root (anchor) => libff::bit_vector root(digest_len); \n\n        //T\n        acc += HashT::get_digest_len();\n\n        //V_S\n        acc += HashT::get_digest_len();\n\n        //V_R\n        acc += HashT::get_digest_len();\n\n        //L_P\n        acc += HashT::get_digest_len();\n\n        return acc;\n    }\n\n    static size_t verifying_field_element_size() {\n        return div_ceil(verifying_input_bit_size(), FieldT::capacity());\n    }\n\n    void generate_r1cs_constraints(\n        const std::string& r1csPath,\n        const std::string& pkPath,\n        const std::string& vkPath\n        )\n    {\n#ifdef DEBUG\n        libff::print_header(\"Gunero constraints\");\n#endif\n\n        // The true passed here ensures all the inputs\n        // are boolean constrained.\n        unpacker->generate_r1cs_constraints(true);\n\n        // Constrain `ZERO`\n        // generate_r1cs_equals_const_constraint<FieldT>(this->pb, ZERO, FieldT::zero(), \"ZERO\");\n        ZERO->generate_r1cs_constraints();\n\n        s_S->generate_r1cs_constraints();\n\n        r_S->generate_r1cs_constraints();\n\n        r_R->generate_r1cs_constraints();\n\n        A_PS->generate_r1cs_constraints();\n\n        W_P->generate_r1cs_constraints();\n\n        P_proof_R->generate_r1cs_constraints();\n\n        P_proof_S->generate_r1cs_constraints();\n\n        spend_authority->generate_r1cs_constraints();\n\n        view_hash_1_digest->generate_r1cs_constraints();\n\n        view_hash_1_hasher->generate_r1cs_constraints();\n\n        view_hash_2_hasher->generate_r1cs_constraints();\n\n        view_hash_2_digest->generate_r1cs_constraints();\n\n        view_hash_3_hasher->generate_r1cs_constraints();\n\n        view_hash_4_hasher->generate_r1cs_constraints();\n\n        transaction_hash_1_digest->generate_r1cs_constraints();\n\n        transaction_hash_1_hasher->generate_r1cs_constraints();\n\n        transaction_hash_2_digest->generate_r1cs_constraints();\n\n        transaction_hash_2_hasher->generate_r1cs_constraints();\n\n        transaction_hash_3_hasher->generate_r1cs_constraints();\n\n        //Calculate constraints\n        r1cs_constraint_system<FieldT> constraint_system = this->pb.get_constraint_system();\n\n        if (r1csPath.length() > 0)\n        {\n            saveToFile(r1csPath, constraint_system);\n        }\n\n#ifdef DEBUG\n        printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after generator\"); libff::print_time(\"after generator\");\n#endif\n\n        r1cs_ppzksnark_keypair<BaseT> keypair = r1cs_ppzksnark_generator<BaseT>(constraint_system);\n\n        //Verify\n        r1cs_ppzksnark_processed_verification_key<BaseT> vk_precomp = r1cs_ppzksnark_verifier_process_vk<BaseT>(keypair.vk);\n\n        if (pkPath.length() > 0)\n        {\n            saveToFile(pkPath, keypair.pk);\n        }\n\n        if (vkPath.length() > 0)\n        {\n            saveToFile(vkPath, keypair.vk);\n        }\n\n#ifdef DEBUG\n        printf(\"\\n\"); libff::print_indent(); libff::print_mem(\"after constraints\"); libff::print_time(\"after constraints\");\n#endif\n    }\n\n    // Public Parameters:\n    // Current Authorization Root Hash (W)\n    // Token UID (T)\n    // Sender Account View Hash (V_S)\n    // Receiver Account View Hash (V_R)\n    // Previous Transaction Hash (L_P)\n\n    // Private Parameters:\n    // Sender Private Key (s_S)\n    // Sender Account View Randomizer (r_S)\n    // Receiver Account View Randomizer (r_R)\n    // Previous Sender Account Address (A_PS)\n    // Previous Authorization Root Hash (W_P)\n    // alt: Receiver Proof Public Key (P_proof_R)\n    void generate_r1cs_witness(\n        const uint256& pW,\n        const uint256& pT,\n        const uint256& pV_S,\n        const uint256& pV_R,\n        const uint256& pL_P,\n        const uint252& ps_S,\n        const uint256& pr_S,\n        const uint256& pr_R,\n        const uint160& pA_PS,\n        const uint256& pW_P,\n        const uint256& pP_proof_R\n    )\n    {\n        // Witness W\n        W->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pW)\n        );\n\n        // Witness T\n        T->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pT)\n        );\n\n        // Witness view hash. This is not a sanity check.\n        V_S->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pV_S)\n        );\n\n        // Witness view hash. This is not a sanity check.\n        V_R->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pV_R)\n        );\n\n        // Witness view hash. This is not a sanity check.\n        L_P->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pL_P)\n        );\n\n        // Witness `zero`\n        // this->pb.val(ZERO) = FieldT::zero();\n        ZERO->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(uint256())\n        );\n\n        // Witness s_S for the input\n        s_S->bits.fill_with_bits(\n            this->pb,\n            uint252_to_bool_vector_256(ps_S)\n        );\n\n        // Witness P_proof_S for s_S with PRF_addr\n        spend_authority->generate_r1cs_witness();\n\n        // Witness r_S for the input\n        r_S->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pr_S)\n        );\n\n        // Witness r_R for the input\n        r_R->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pr_R)\n        );\n\n        // Witness A_PS for the input\n        A_PS->bits.fill_with_bits(\n            this->pb,\n            uint160_to_bool_vector_256_rpad(pA_PS)\n        );\n\n        // Witness W_P for the input\n        W_P->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pW_P)\n        );\n\n        // Witness P_proof_R for the input\n        P_proof_R->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pP_proof_R)\n        );\n\n        // Witness hash(W, r_S) = view_hash_1_digest\n        view_hash_1_hasher->generate_r1cs_witness();\n\n        // Witness hash(P_proof_S, view_hash_1_digest) = V_S\n        view_hash_2_hasher->generate_r1cs_witness();\n\n        // Witness hash(W, r_R) = view_hash_2_digest\n        view_hash_3_hasher->generate_r1cs_witness();\n\n        // Witness hash(P_proof_R, view_hash_2_digest) = V_R\n        view_hash_4_hasher->generate_r1cs_witness();\n\n        // Witness //transaction_hash_1_digest = hash(T, W_P)\n        transaction_hash_1_hasher->generate_r1cs_witness();\n\n        // Witness //transaction_hash_2_digest = hash(s_S, transaction_hash_1_digest)\n        transaction_hash_2_hasher->generate_r1cs_witness();\n\n        // Witness //L_P == hash(A_PS, transaction_hash_2_digest)\n        transaction_hash_3_hasher->generate_r1cs_witness();\n\n        // [SANITY CHECK] Ensure that the intended root\n        // was witnessed by the inputs, even if the read\n        // gadget overwrote it. This allows the prover to\n        // fail instead of the verifier, in the event that\n        // the roots of the inputs do not match the\n        // hash provided to the proving hashers.\n        V_S->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pV_S)\n        );\n\n        // [SANITY CHECK] Ensure that the intended root\n        // was witnessed by the inputs, even if the read\n        // gadget overwrote it. This allows the prover to\n        // fail instead of the verifier, in the event that\n        // the roots of the inputs do not match the\n        // hash provided to the proving hashers.\n        V_R->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pV_R)\n        );\n\n        // [SANITY CHECK] Ensure that the intended root\n        // was witnessed by the inputs, even if the read\n        // gadget overwrote it. This allows the prover to\n        // fail instead of the verifier, in the event that\n        // the roots of the inputs do not match the\n        // hash provided to the proving hashers.\n        L_P->bits.fill_with_bits(\n            this->pb,\n            uint256_to_bool_vector(pL_P)\n        );\n\n        // This happens last, because only by now are all the\n        // verifier inputs resolved.\n        unpacker->generate_r1cs_witness_from_bits();\n    }\n\n    static r1cs_primary_input<FieldT> witness_map(\n        const uint256& pW,\n        const uint256& pT,\n        const uint256& pV_S,\n        const uint256& pV_R,\n        const uint256& pL_P\n    ) {\n        std::vector<bool> verify_inputs;\n\n        insert_uint256(verify_inputs, pW);\n\n        insert_uint256(verify_inputs, pT);\n\n        insert_uint256(verify_inputs, pV_S);\n\n        insert_uint256(verify_inputs, pV_R);\n\n        insert_uint256(verify_inputs, pL_P);\n\n        assert(verify_inputs.size() == verifying_input_bit_size());\n        auto verify_field_elements = libff::pack_bit_vector_into_field_element_vector<FieldT>(verify_inputs);\n        assert(verify_field_elements.size() == verifying_field_element_size());\n        return verify_field_elements;\n    }\n\n    void alloc_uint256(\n        pb_variable_array<FieldT>& packed_into,\n        std::shared_ptr<digest_variable<FieldT>>& var\n    ) {\n        var.reset(new digest_variable<FieldT>(this->pb, 256, \"\"));\n        packed_into.insert(packed_into.end(), var->bits.begin(), var->bits.end());\n    }\n};\n\n} // end namespace `gunero`\n\n#endif /* GUNEROTRANSACTIONSEND_GADGET_H_ */", "meta": {"hexsha": "4740b270bece85c7168670ad80589c9408e3f811", "size": 18384, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gunerotransactionsend_gadget.hpp", "max_stars_repo_name": "GunClear/Silencer", "max_stars_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-17T22:27:54.000Z", "max_issues_repo_path": "src/gunerotransactionsend_gadget.hpp", "max_issues_repo_name": "GunClear/Silencer", "max_issues_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T19:57:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-04T15:49:02.000Z", "max_forks_repo_path": "src/gunerotransactionsend_gadget.hpp", "max_forks_repo_name": "GunClear/Silencer", "max_forks_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7321100917, "max_line_length": 124, "alphanum_fraction": 0.6455069626, "num_tokens": 4607, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2308689123653951}}
{"text": "/*    Copyright (c) 2010-2016, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/make_shared.hpp>\n#include <boost/lexical_cast.hpp>\n\n#include \"Tudat/Astrodynamics/Aerodynamics/exponentialAtmosphere.h\"\n#include \"Tudat/Astrodynamics/Aerodynamics/tabulatedAtmosphere.h\"\n#include \"Tudat/SimulationSetup/createAtmosphereModel.h\"\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\n//! Function to create an atmosphere model.\nboost::shared_ptr< aerodynamics::AtmosphereModel > createAtmosphereModel(\n        const boost::shared_ptr< AtmosphereSettings > atmosphereSettings,\n        const std::string& body )\n{\n    using namespace tudat::aerodynamics;\n\n    // Declare return object.\n    boost::shared_ptr< AtmosphereModel > atmosphereModel;\n\n    // Check which type of atmosphere model is to be created.\n    switch( atmosphereSettings->getAtmosphereType( ) )\n    {\n    case exponential_atmosphere:\n    {\n        // Check whether settings for atmosphere are consistent with its type.\n        boost::shared_ptr< ExponentialAtmosphereSettings > exponentialAtmosphereSettings =\n                boost::dynamic_pointer_cast< ExponentialAtmosphereSettings >( atmosphereSettings );\n        if( exponentialAtmosphereSettings == NULL )\n        {\n            throw std::runtime_error(\n                        \"Error, expected exponential atmosphere settings for body \" + body );\n        }\n        else\n        {\n            // Create and initialize exponential atmosphere model.\n            boost::shared_ptr< ExponentialAtmosphere > exponentialAtmosphereModel =\n                    boost::make_shared< ExponentialAtmosphere >(\n                        exponentialAtmosphereSettings->getDensityScaleHeight( ) ,\n                        exponentialAtmosphereSettings->getConstantTemperature( ),\n                        exponentialAtmosphereSettings->getDensityAtZeroAltitude( ),\n                        exponentialAtmosphereSettings->getSpecificGasConstant( ) );\n            atmosphereModel = exponentialAtmosphereModel;\n        }\n        break;\n    }\n    case tabulated_atmosphere:\n    {\n        // Check whether settings for atmosphere are consistent with its type\n        boost::shared_ptr< TabulatedAtmosphereSettings > tabulatedAtmosphereSettings =\n                boost::dynamic_pointer_cast< TabulatedAtmosphereSettings >( atmosphereSettings );\n        if( tabulatedAtmosphereSettings == NULL )\n        {\n            throw std::runtime_error(\n                        \"Error, expected tabulated atmosphere settings for body \" + body );\n        }\n        else\n        {\n            // Create and initialize tabulatedl atmosphere model.\n            atmosphereModel = boost::make_shared< TabulatedAtmosphere >(\n                        tabulatedAtmosphereSettings->getAtmosphereFile( ) );\n        }\n        break;\n    }\n    default:\n        throw std::runtime_error(\n                 \"Error, did not recognize atmosphere model settings type \" +\n                  boost::lexical_cast< std::string >( atmosphereSettings->getAtmosphereType( ) ) );\n    }\n    return atmosphereModel;\n}\n\n\n} // namespace simulation_setup\n\n} // namespace tudat\n", "meta": {"hexsha": "254c20846307a77de0d0a9918715f93774ce1428", "size": 3482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/SimulationSetup/createAtmosphereModel.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/SimulationSetup/createAtmosphereModel.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/SimulationSetup/createAtmosphereModel.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 38.6888888889, "max_line_length": 99, "alphanum_fraction": 0.6651349799, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.23053502197430378}}
{"text": "#include \"focal_grid.h\"\n\n#include <string>\n#include <stdint.h>\n#include <iostream>\n#include <iomanip>\n#include <math.h>\n#include <chrono>\n#include <vector>\n#include <future>\n#include <thread>\n#include <algorithm>\n#include <dirent.h>\n#include <armadillo>\n\nusing namespace std;\n\n//-------------------------------------------------\n\ninline bool sortByPix0(const voxel_prop &lhs, const voxel_prop &rhs) {\n\treturn lhs.pix_0 < rhs.pix_0;\n}\n\nFocalGrid::FocalGrid() {\n\t// empty\n}\n\nbool FocalGrid::LoadCalibration(session_param &ses_par, vox_grid &vox, frames &frame) {\n\n\tbool grid_loaded = true;\n\n\ttry {\n\n\t\tvox.image_size.clear();\n\t\tvox.calib_mat.clear();\n\t\tvox.X_xyz.clear();\n\t\tvox.X_uv.clear();\n\t\tvox.uv_offset.clear();\n\n\t\timage_size.clear();\n\t\tcalib_mat.clear();\n\t\tX_xyz.clear();\n\t\tX_uv.clear();\n\t\tuv_offset.clear();\n\n\t\tstring calib_file = ses_par.session_loc + \"/\" + ses_par.cal_loc + \"/\" + ses_par.cal_name;\n\n\t\tarma::Mat<double> CalibMatrix;\n\n\t\tCalibMatrix.load(calib_file);\n\n\t\tfor (int i=0; i<ses_par.N_cam; i++) {\n\t\t\tvox.image_size.push_back(frame.image_size[i]);\n\t\t\tvox.calib_mat.push_back(CalibMatrix.col(i));\n\t\t\tvox.X_xyz.push_back(FocalGrid::Camera2WorldMatrix(CalibMatrix.col(i)));\n\t\t\tvox.X_uv.push_back(FocalGrid::World2CameraMatrix(CalibMatrix.col(i)));\n\t\t\tarma::Col<double> uv_off_i = {CalibMatrix(10,i)/2.0-CalibMatrix(12,i)/2.0, CalibMatrix(9,i)/2.0-CalibMatrix(11,i)/2.0, 0.0};\n\t\t\tvox.uv_offset.push_back(uv_off_i);\n\n\t\t\timage_size.push_back(frame.image_size[i]);\n\t\t\tcalib_mat.push_back(CalibMatrix.col(i));\n\t\t\tX_xyz.push_back(FocalGrid::Camera2WorldMatrix(CalibMatrix.col(i)));\n\t\t\tX_uv.push_back(FocalGrid::World2CameraMatrix(CalibMatrix.col(i)));\n\t\t\tuv_offset.push_back(uv_off_i);\n\t\t}\n\n\t\t// Populate internal parameters\n\n\t\tN_cam = vox.N_cam;\n\t\tN_threads = vox.N_threads;\n\t\tnx = vox.nx;\n\t\tny = vox.ny;\n\t\tnz = vox.nz;\n\t\tds = vox.ds;\n\t\tx0 = vox.x0;\n\t\ty0 = vox.y0;\n\t\tz0 = vox.z0;\n\n\t}\n\tcatch (...) {\n\t\tgrid_loaded = false;\n\t}\n\n\treturn grid_loaded;\n}\n\nbool FocalGrid::ConstructFocalGrid(vox_grid &vox) {\n\n\tbool grid_build = true;\n\n\ttry {\n\n\t\tvox.voxel_list.clear();\n\n\t\tint vec_size = 0;\n\t\tint i = 0;\n\t\tvector<future<vector<voxel_prop>>> vox_results;\n\t\t\n\t\twhile (i<nx) {\n\t\t\tcout << \"row \" + to_string(i) + \" / \" + to_string(nx) << endl;\n\t\t\tvox_results.clear();\n\t\t\tfor (int j=0; j<N_threads; j++) {\n\t\t\t\tif (i+j<nx) {\n\t\t\t\t\tvox_results.push_back(async(launch::async, &FocalGrid::CheckVoxel,this,i+j));\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int j=0; j<N_threads; j++) {\n\t\t\t\tvector<voxel_prop> vox_results_thread=vox_results.at(j).get();\n\t\t\t\tvec_size = vox_results_thread.size();\n\t\t\t\tif (vec_size>1) {\n\t\t\t\t\tcopy(vox_results_thread.begin(),vox_results_thread.end(),back_inserter(vox.voxel_list));\n\t\t\t\t}\n\t\t\t}\n\t\t\ti+=N_threads;\n\t\t}\n\n\t\tcout << \"Sorting\" << endl;\n\t\tsort(vox.voxel_list.begin(),vox.voxel_list.end(),sortByPix0);\n\n\t\tcout << \"Voxel list size:\" << endl;\n\t\tcout << vox.voxel_list.size() << endl;\n\n\t}\n\tcatch (...) {\n\t\tgrid_build = false;\n\t}\n\n\treturn grid_build;\n}\n\nvector<tuple<double,double,double,int>> FocalGrid::ProjectImage2Cloud(vector<arma::Col<int>> &frame_in, vox_grid &vox) {\n\n\tvector<tuple<double,double,double,int>> pcl_now;\n\n\ttuple<bool,vector<int>> view_check;\n\ttuple<int,bool,vector<int>> code_check;\n\tvector<vector<int>> code_list;\n\n\tint N_row = get<0>(vox.image_size[0]);\n\tint N_col = get<1>(vox.image_size[0]);\n\n\tint vox_ind = 0;\n\tint max_ind = vox.voxel_list.size();\n\n\tfor (int i=0; i<(N_row*N_col); i++) {\n\n\t\tif (frame_in[0](i)>0) {\n\t\t\twhile (vox.voxel_list[vox_ind].pix_0<=i) {\n\t\t\t\tif (vox.voxel_list[vox_ind].pix_0==i) {\n\t\t\t\t\tview_check = FocalGrid::CheckInView(frame_in, vox, vox_ind);\n\t\t\t\t\tif (get<0>(view_check)==true) {\n\t\t\t\t\t\tif (FocalGrid::CheckNeighbors(frame_in, vox, vox_ind)==true) {\n\t\t\t\t\t\t\tcode_check = FocalGrid::CheckCode(code_list, get<1>(view_check));\n\t\t\t\t\t\t\tif (get<1>(code_check)==true) {\n\t\t\t\t\t\t\t\tcode_list.push_back(get<2>(code_check));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tpcl_now.push_back(make_tuple(\n\t\t\t\t\t\t\t\tvox.voxel_list[vox_ind].x,\n\t\t\t\t\t\t\t\tvox.voxel_list[vox_ind].y,\n\t\t\t\t\t\t\t\tvox.voxel_list[vox_ind].z,\n\t\t\t\t\t\t\t\tget<0>(code_check)));\n\t\t\t\t\t\t\t\t//get<1>(view_check)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvox_ind++;\n\t\t\t\tif (vox_ind >= max_ind) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (vox_ind >= max_ind) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (pcl_now.size() <= 0) {\n\t\tpcl_now.push_back(make_tuple(0.0,0.0,0.0,0));\n\t}\n\n\treturn pcl_now;\n}\n\ntuple<int,bool,vector<int>> FocalGrid::CheckCode(vector<vector<int>> code_list, vector<int> code_in) {\n\n\tint code_out = 0;\n\tvector<int> new_code;\n\n\tint i=0;\n\tbool code_found = false;\n\tbool add_code = false;\n\t\n\tint N_codes = code_list.size();\n\n\tif (N_codes > 0) {\n\t\twhile ((i<N_codes) && (code_found==false)) {\n\t\t\tint match_count = 0;\n\t\t\tint body_count = 0;\n\t\t\tfor (int j=0; j<N_cam; j++) {\n\t\t\t\tif (code_list[i][j]==code_in[j]) {\n\t\t\t\t\tif (code_in[j]==1) {\n\t\t\t\t\t\tmatch_count++;\n\t\t\t\t\t\tbody_count++;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tmatch_count++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (match_count == N_cam) {\n\t\t\t\t// Code exists, get code number\n\t\t\t\tcode_out = code_list[i][N_cam+1];\n\t\t\t\tcode_found == true;\n\t\t\t}\n\t\t\telse if ((match_count == (N_cam-1)) && (body_count < (N_cam-1))) {\n\t\t\t\t// Code cannot be found in code_list but it matches with N_cam-1 views\n\t\t\t\t// and has less than N_cam-1 body views:\n\t\t\t\tcode_out = code_list[i][N_cam+1];\n\t\t\t\tcode_found == true;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\tif (code_found == false) {\n\t\t\t// Code could not be found in the code list, add code to the list.\n\t\t\tadd_code = true;\n\n\t\t\t// Check first if code_in corresponds to the body:\n\t\t\tint body_count = 0;\n\t\t\tfor (int j=0; j<N_cam; j++) {\n\t\t\t\tif (code_in[j]==1) {\n\t\t\t\t\tbody_count++;\n\t\t\t\t}\n\t\t\t\tnew_code.push_back(code_in[j]);\n\t\t\t}\n\n\t\t\t// If code_in corresponds to the body: pick 1 as pcl code\n\t\t\tif (body_count == N_cam) {\n\t\t\t\tnew_code.push_back(1);\n\t\t\t\tcode_out = 1;\n\t\t\t}\n\t\t\t// If code_in does not correspond to the body: add N_codes+1 as pcl code\n\t\t\telse {\n\t\t\t\tnew_code.push_back(N_codes+1);\n\t\t\t\tcode_out = N_codes+1;\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\t// No code exists yet, add curent code to the code list:\n\t\tadd_code = true;\n\n\t\t// Check first if code_in corresponds to the body:\n\t\tint body_count = 0;\n\t\tfor (int j=0; j<N_cam; j++) {\n\t\t\tif (code_in[j]==1) {\n\t\t\t\tbody_count++;\n\t\t\t}\n\t\t\tnew_code.push_back(code_in[j]);\n\t\t}\n\n\t\t// If code_in corresponds to the body: pick 1 as pcl code\n\t\tif (body_count == N_cam) {\n\t\t\tnew_code.push_back(1);\n\t\t\tcode_out = 1;\n\t\t}\n\t\t// If code_in does not correspond to the body: add 2 as pcl code\n\t\telse {\n\t\t\tnew_code.push_back(2);\n\t\t\tcode_out = 2;\n\t\t}\n\t}\n\n\treturn make_tuple(code_out,add_code,new_code);\n}\n\n/*\nvector<tuple<double,double,double,int>> FocalGrid::ProjectImage2Cloud(vector<arma::Col<int>> &frame_in, vox_grid &vox) {\n\n\tvector<tuple<double,double,double,int>> pcl_now;\n\n\tvector<future<vector<tuple<double,double,double,int>>>> future_pcl;\n\n\tint N_row = get<0>(vox.image_size[0]);\n\tint N_col = get<1>(vox.image_size[0]);\n\n\tint vec_size = 0;\n\n\t// Launch threads:\n\tfor (int j=0; j<N_threads; j++) {\n\t\tfuture_pcl.push_back(async(launch::async, &FocalGrid::ProjectImage2CloudThread,this,j,(N_row*N_col),ref(vox),ref(frame_in)));\n\t}\n\tcout << \"threads have been launched\" << endl;\n\t// Retrieve information from threads:\n\tfor (int j=0; j<N_threads; j++) {\n\t\tvector<tuple<double,double,double,int>> pcl_results_thread=future_pcl.at(j).get();\n\t\tvec_size = pcl_results_thread.size();\n\t\tif (pcl_results_thread.size()>1) {\n\t\t\tcopy(pcl_results_thread.begin(),pcl_results_thread.end(),back_inserter(pcl_now));\n\t\t}\n\t}\n\tcout << \"pcl now size\" << endl;\n\tcout << pcl_now.size() << endl;\n\tif (pcl_now.size() <= 0) {\n\t\tpcl_now.push_back(make_tuple(0.0,0.0,0.0,0));\n\t}\n\n\treturn pcl_now;\n}\n\n\nvector<tuple<double,double,double,int>> FocalGrid::ProjectImage2CloudThread(int i_start, int i_end, vox_grid &vox, vector<arma::Col<int>> &frame_in) {\n\n\tvector<tuple<double,double,double,int>> pcl_i;\n\n\tfor (int i = i_start; i<i_end; i+=N_threads) {\n\n\t\tint vox_ind = 0;\n\t\tint max_ind = vox.voxel_list.size();\n\n\t\ttuple<bool,int> view_check;\n\n\t\tif (frame_in[0](i) > 0) {\n\t\t\twhile (vox.voxel_list[vox_ind].pix_0<=i) {\n\t\t\t\tif (vox.voxel_list[vox_ind].pix_0==i) {\n\t\t\t\t\tview_check = FocalGrid::CheckInView(frame_in, vox, vox_ind);\n\t\t\t\t\tif (get<0>(view_check)==true) {\n\t\t\t\t\t\tif (FocalGrid::CheckNeighbors(frame_in, vox, vox_ind)==true) {\n\t\t\t\t\t\t\tpcl_i.push_back(make_tuple(\n\t\t\t\t\t\t\t\tvox.voxel_list[vox_ind].x,\n\t\t\t\t\t\t\t\tvox.voxel_list[vox_ind].y,\n\t\t\t\t\t\t\t\tvox.voxel_list[vox_ind].z,\n\t\t\t\t\t\t\t\tget<1>(view_check)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvox_ind++;\n\t\t\t\tif (vox_ind >= max_ind) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn pcl_i;\n}\n*/\n\nvector<arma::Col<int>> FocalGrid::ProjectCloud2Image(vector<tuple<double,double,double,int>> &cloud_in, vox_grid &vox) {\n\n\tvector<arma::Col<int>> frame_now;\n\n\tint N_vox = cloud_in.size();\n\n\tfor (int n=0; n<N_cam; n++) {\n\t\tarma::Col<int> frame_n;\n\t\tframe_n.zeros(get<0>(image_size[n])*get<1>(image_size[n]));\n\t\tframe_now.push_back(frame_n);\n\t}\n\n\tarma::Col<double> uv;\n\tarma::Col<double> xyz;\n\tint u = 0;\n\tint v = 0;\n\n\tfor (int i=0; i<N_vox; i++) {\n\t\tfor (int j=0; j<N_cam; j++) {\n\t\t\txyz = {get<0>(cloud_in[i]),get<1>(cloud_in[i]),get<2>(cloud_in[i]),1.0};\n\t\t\tuv = X_uv[j]*xyz-uv_offset[j];\n\t\t\tif (uv(0)>=0 && uv(0)<(get<1>(image_size[j]))) {\n\t\t\t\tif (uv(1)>=0 && uv(1)<(get<0>(image_size[j]))) {\n\t\t\t\t\tu = (int) uv(0);\n\t\t\t\t\tv = (int) uv(1);\n\t\t\t\t\tif (frame_now[j](get<0>(image_size[j])*u+v)==0) {\n\t\t\t\t\t\tframe_now[j](get<0>(image_size[j])*u+v) = get<3>(cloud_in[i]);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (frame_now[j](get<0>(image_size[j])*u+v)>get<3>(cloud_in[i])) {\n\t\t\t\t\t\t\tframe_now[j](get<0>(image_size[j])*u+v) = get<3>(cloud_in[i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn frame_now;\n}\n\ntuple<bool,vector<int>> FocalGrid::CheckInView(vector<arma::Col<int>> &frame_in, vox_grid &vox, int vox_ind) {\n\n\tbool in_view = true;\n\tvector<int> seg_codes;\n\n\tint pix_ind = 0;\n\tint intensity_now = 0;\n\n\tfor (int i=0; i<N_cam; i++) {\n\t\tif (i==0) {\n\t\t\tpix_ind = vox.voxel_list[vox_ind].pix_0;\n\t\t\tintensity_now = frame_in[i](pix_ind);\n\t\t\tseg_codes.push_back(intensity_now);\n\t\t\tif (intensity_now<=0) {\n\t\t\t\tin_view = false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tpix_ind = vox.voxel_list[vox_ind].pix_n[i-1];\n\t\t\tintensity_now = frame_in[i](pix_ind);\n\t\t\tseg_codes.push_back(intensity_now);\n\t\t\tif (intensity_now<=0) {\n\t\t\t\tin_view = false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn make_tuple(in_view,seg_codes);\n}\n\n/*\ntuple<bool,int> FocalGrid::CheckInView(vector<arma::Col<int>> &frame_in, vox_grid &vox, int vox_ind) {\n\n\tint intensity_sum = 0;\n\tint intensity_now = 0;\n\tbool in_view = true;\n\tint n = 0;\n\tint pix_ind = 0;\n\n\twhile (in_view==true && n<N_cam) {\n\t\tif (n==0) {\n\t\t\tpix_ind = vox.voxel_list[vox_ind].pix_0;\n\t\t\tintensity_now = frame_in[n](pix_ind);\n\t\t\tif (intensity_now>0) {\n\t\t\t\tif (intensity_now<max_n_seg) {\n\t\t\t\t\tintensity_sum += frame_in[n](pix_ind);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tintensity_sum = pow((max_n_seg*1.0),N_cam);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tin_view = false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tpix_ind = vox.voxel_list[vox_ind].pix_n[n-1];\n\t\t\tintensity_now = frame_in[n](pix_ind);\n\t\t\tif (intensity_now>0) {\n\t\t\t\tif (intensity_now<max_n_seg) {\n\t\t\t\t\tintensity_sum += frame_in[n](pix_ind)*pow((max_n_seg*1.0),n);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tintensity_sum = pow((max_n_seg*1.0),N_cam);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tin_view = false;\n\t\t\t}\n\t\t}\n\t\tn++;\n\t}\n\n\treturn make_tuple(in_view,intensity_sum);\n}\n*/\n\ninline bool FocalGrid::CheckNeighbors(vector<arma::Col<int>> &frame_in, vox_grid &vox, int vox_ind) {\n\n\tbool pixel_on = true;\n\n\tint uv;\n\tint on_count = 0;\n\tint in_view = 0;\n\n\tfor (int m=0; m<6; m++) {\n\t\tin_view =0;\n\t\tfor (int n=0; n<N_cam; n++) {\n\t\t\tuv = vox.voxel_list[vox_ind].neighbors[m][n];\n\t\t\tif (frame_in[n](uv)>0) {\n\t\t\t\tin_view++;\n\t\t\t}\n\t\t}\n\t\tif (in_view == N_cam) {\n\t\t\ton_count++;\n\t\t}\n\t}\n\n\tif (on_count==6) {\n\t\tpixel_on = false;\n\t}\n\n\tif (on_count<2) {\n\t\tpixel_on = false;\n\t}\n\n\treturn pixel_on;\n}\n\nvector<voxel_prop> FocalGrid::CheckVoxel(int i) {\n\n\tvector<voxel_prop> voxel_array;\n\n\tvoxel_array.resize(1);\n\n\tint vox_index = 0;\n\n\tint is_neighbor = 0;\n\n\tarma::Col<double> xyz(4);\n\tarma::Col<double> xyz_0(4);\n\tarma::Col<double> xyz_1(4);\n\tarma::Col<double> xyz_2(4);\n\tarma::Col<double> xyz_3(4);\n\tarma::Col<double> xyz_4(4);\n\tarma::Col<double> xyz_5(4);\n\n\tarma::Mat<double> uv(3,N_cam);\n\tarma::Mat<double> uv_0(3,N_cam);\n\tarma::Mat<double> uv_1(3,N_cam);\n\tarma::Mat<double> uv_2(3,N_cam);\n\tarma::Mat<double> uv_3(3,N_cam);\n\tarma::Mat<double> uv_4(3,N_cam);\n\tarma::Mat<double> uv_5(3,N_cam);\n\n\tfor (int j=0; j<ny; j++) {\n\t\tfor (int k=0; k<nz; k++) {\n\n\t\t\tvox_index = i*(ny*nz)+j*nz+k;\n\n\t\t\tstruct voxel_prop vox_now;\n\n\t\t\txyz = {x0-((nx-1)/2.0)*ds+i*ds, \n\t\t\t\ty0-((ny-1)/2.0)*ds+j*ds,\n\t\t\t\tz0-((nz-1)/2.0)*ds+k*ds,\n\t\t\t\t1.0};\n\n\t\t\t// Calculate projection coordinates:\n\t\t\tfor (int n=0; n<N_cam; n++) {\n\t\t\t\tuv.col(n) = X_uv[n]*xyz-uv_offset[n];\n\t\t\t}\n\n\t\t\t// Check if the voxel projects to all frames:\n\t\t\tif (FocalGrid::IsVoxel(uv)==1) {\n\t\t\t\t\n\t\t\t\txyz_0 = {x0-((nx-1)/2.0)*ds+(i+1)*ds, \n\t\t\t\t\ty0-((ny-1)/2.0)*ds+j*ds,\n\t\t\t\t\tz0-((nz-1)/2.0)*ds+k*ds,\n\t\t\t\t\t1.0};\n\n\t\t\t\txyz_1 = {x0-((nx-1)/2.0)*ds+(i-1)*ds, \n\t\t\t\t\ty0-((ny-1)/2.0)*ds+j*ds,\n\t\t\t\t\tz0-((nz-1)/2.0)*ds+k*ds,\n\t\t\t\t\t1.0};\n\n\t\t\t\txyz_2 = {x0-((nx-1)/2.0)*ds+i*ds, \n\t\t\t\t\ty0-((ny-1)/2.0)*ds+(j+1)*ds,\n\t\t\t\t\tz0-((nz-1)/2.0)*ds+k*ds,\n\t\t\t\t\t1.0};\n\n\t\t\t\txyz_3 = {x0-((nx-1)/2.0)*ds+i*ds, \n\t\t\t\t\ty0-((ny-1)/2.0)*ds+(j-1)*ds,\n\t\t\t\t\tz0-((nz-1)/2.0)*ds+k*ds,\n\t\t\t\t\t1.0};\n\n\t\t\t\txyz_4 = {x0-((nx-1)/2.0)*ds+i*ds, \n\t\t\t\t\ty0-((ny-1)/2.0)*ds+j*ds,\n\t\t\t\t\tz0-((nz-1)/2.0)*ds+(k+1)*ds,\n\t\t\t\t\t1.0};\n\n\t\t\t\txyz_5 = {x0-((nx-1)/2.0)*ds+i*ds, \n\t\t\t\t\ty0-((ny-1)/2.0)*ds+j*ds,\n\t\t\t\t\tz0-((nz-1)/2.0)*ds+(k-1)*ds,\n\t\t\t\t\t1.0};\n\n\t\t\t\tfor (int m=0; m<N_cam; m++) {\n\t\t\t\t\tuv_0.col(m) = X_uv[m]*xyz_0-uv_offset[m];\n\t\t\t\t\tuv_1.col(m) = X_uv[m]*xyz_1-uv_offset[m];\n\t\t\t\t\tuv_2.col(m) = X_uv[m]*xyz_2-uv_offset[m];\n\t\t\t\t\tuv_3.col(m) = X_uv[m]*xyz_3-uv_offset[m];\n\t\t\t\t\tuv_4.col(m) = X_uv[m]*xyz_4-uv_offset[m];\n\t\t\t\t\tuv_5.col(m) = X_uv[m]*xyz_5-uv_offset[m];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tis_neighbor = FocalGrid::IsVoxel(uv_0)+FocalGrid::IsVoxel(uv_1)+\n\t\t\t\t\t\t\tFocalGrid::IsVoxel(uv_2)+FocalGrid::IsVoxel(uv_3)+\n\t\t\t\t\t\t\tFocalGrid::IsVoxel(uv_4)+FocalGrid::IsVoxel(uv_5);\n\n\t\t\t\tif (is_neighbor == 6) {\n\t\t\t\t\tfor (int m=0; m<N_cam; m++) {\n\t\t\t\t\t\tif (m==0) {\n\t\t\t\t\t\t\tvox_now.pix_0 = ((int) uv(1,m))*get<1>(image_size[m])+((int) uv(0,m));\n\t\t\t\t\t\t\tvox_now.vox_ind = vox_index;\n\t\t\t\t\t\t\tvox_now.x = xyz(0);\n\t\t\t\t\t\t\tvox_now.y = xyz(1);\n\t\t\t\t\t\t\tvox_now.z = xyz(2);\n\t\t\t\t\t\t\tvox_now.neighbors.resize(6);\n\t\t\t\t\t\t\tvox_now.neighbors[0].push_back(((int) uv_0(1,m))*get<1>(image_size[m])+((int) uv_0(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[1].push_back(((int) uv_1(1,m))*get<1>(image_size[m])+((int) uv_1(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[2].push_back(((int) uv_2(1,m))*get<1>(image_size[m])+((int) uv_2(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[3].push_back(((int) uv_3(1,m))*get<1>(image_size[m])+((int) uv_3(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[4].push_back(((int) uv_4(1,m))*get<1>(image_size[m])+((int) uv_4(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[5].push_back(((int) uv_5(1,m))*get<1>(image_size[m])+((int) uv_5(0,m)));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tvox_now.pix_n.push_back(((int) uv(1,m))*get<1>(image_size[m])+((int) uv(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[0].push_back(((int) uv_0(1,m))*get<1>(image_size[m])+((int) uv_0(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[1].push_back(((int) uv_1(1,m))*get<1>(image_size[m])+((int) uv_1(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[2].push_back(((int) uv_2(1,m))*get<1>(image_size[m])+((int) uv_2(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[3].push_back(((int) uv_3(1,m))*get<1>(image_size[m])+((int) uv_3(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[4].push_back(((int) uv_4(1,m))*get<1>(image_size[m])+((int) uv_4(0,m)));\n\t\t\t\t\t\t\tvox_now.neighbors[5].push_back(((int) uv_5(1,m))*get<1>(image_size[m])+((int) uv_5(0,m)));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tvoxel_array.push_back(vox_now);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn voxel_array;\n}\n\ninline int FocalGrid::IsVoxel(arma::Mat<double> uv) {\n\n\tint is_voxel = 0;\n\n\tint count = 0;\n\n\tfor (int n=0; n<N_cam; n++) {\n\t\tif (uv(0,n)>=0 && uv(0,n)<(get<1>(image_size[n]))) {\n\t\t\tif (uv(1,n)>=0 && uv(1,n)<(get<0>(image_size[n]))) {\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (count == N_cam) {\n\t\tis_voxel = 1;\n\t}\n\n\treturn is_voxel;\n\n}\n\narma::Mat<int> FocalGrid::TransformXYZ2UV(arma::Col<double> xyz_pos) {\n\n\tarma::Mat<int> uv_mat(2,N_cam);\n\n\tfor (int n=0; n<N_cam; n++) {\n\t\tarma::Col<double> uv = X_uv[n]*xyz_pos-uv_offset[n];\n\t\tuv_mat(0,n) = int(uv(0));\n\t\tuv_mat(1,n) = int(uv(1));\n\t}\n\n\treturn uv_mat;\n}\n\ntuple<arma::Mat<int>, arma::Col<double>> FocalGrid::RayCasting(int cam_nr, arma::Col<double> xyz_pos_prev, arma::Col<double> uv_pos_prev, arma::Col<double> uv_pos_now) {\n\n\t// Calculate the 3D translation vector:\n\tarma::Col<double> xyz_uv_prev = X_xyz[cam_nr]*(uv_pos_prev+uv_offset[cam_nr]);\n\tarma::Col<double> xyz_uv_now = X_xyz[cam_nr]*(uv_pos_now+uv_offset[cam_nr]);\n\tarma::Col<double> trans_vec = xyz_uv_now-xyz_uv_prev;\n\ttrans_vec(3) = 0.0;\n\n\t// Add the translation to the xyz position:\n\tarma::Col<double> xyz_pos_now = xyz_pos_prev + trans_vec;\n\n\t// Project the new position back to the camera views:\n\n\tarma::Mat<int> uv_mat(3,N_cam);\n\n\tfor (int n=0; n<N_cam; n++) {\n\t\tarma::Col<double> uv = X_uv[n]*xyz_pos_now-uv_offset[n];\n\t\tif (uv(0)>=0 && uv(0)<(get<1>(image_size[n])) && uv(1)>=0 && uv(1)<(get<0>(image_size[n]))) {\n\t\t\tuv_mat(0,n) = int(uv(0));\n\t\t\tuv_mat(1,n) = int(uv(1));\n\t\t\tuv_mat(2,n) = int(uv(2));\n\t\t}\n\t\telse {\n\t\t\tarma::Col<double> uv_old = X_uv[n]*xyz_pos_prev-uv_offset[n];\n\t\t\tuv_mat(0,n) = int(uv_old(0));\n\t\t\tuv_mat(1,n) = int(uv_old(1));\n\t\t\tuv_mat(2,n) = int(uv_old(2));\n\t\t}\n\t}\n\n\treturn make_tuple(uv_mat,xyz_pos_now);\n}\n\narma::Mat<double> FocalGrid::Camera2WorldMatrix(arma::Col<double> calib_param) {\n\n\t// return the world to camera projection matrix\n\n\tarma::Mat<double> C = {{calib_param(0), calib_param(2), 0, 0},\n\t\t \t\t\t{0, calib_param(1), 0, 0},\n\t\t \t\t\t{0, 0, 0, 1}};\n\n\tdouble theta = sqrt(pow(calib_param(3),2)+pow(calib_param(4),2)+pow(calib_param(5),2));\n\n\tarma::Mat<double> omega = {{0, -calib_param(5), calib_param(4)},\n\t\t\t \t\t\t{calib_param(5), 0, -calib_param(3)},\n\t\t\t \t\t\t{-calib_param(4), calib_param(3), 0}};\n\n\tarma::Mat<double> R(3,3); R.eye();\n\n\tR = R+(sin(theta)/theta)*omega+((1-cos(theta))/pow(theta,2))*(omega*omega);\n\n\tarma::Col<double> T = {calib_param(6), calib_param(7), calib_param(8)};\n\n\tarma::Mat<double> K = {{R(0,0), R(0,1), R(0,2), T(0)},\n\t\t \t\t\t\t{R(1,0), R(1,1), R(1,2), T(1)},\n\t\t \t\t\t\t{R(2,0), R(2,1), R(2,2), T(2)},\n\t\t \t\t\t\t{0, 0, 0, 1}};\n\n\treturn arma::inv(K)*arma::pinv(C);\n\n}\n\narma::Mat<double> FocalGrid::World2CameraMatrix(arma::Col<double> calib_param) {\n\n\t// return the world to camera projection matrix\n\n\tarma::Mat<double> C = {{calib_param(0), calib_param(2), 0, 0},\n\t\t \t\t\t{0, calib_param(1), 0, 0},\n\t\t \t\t\t{0, 0, 0, 1}};\n\n\tdouble theta = sqrt(pow(calib_param(3),2)+pow(calib_param(4),2)+pow(calib_param(5),2));\n\n\tarma::Mat<double> omega = {{0, -calib_param(5), calib_param(4)},\n\t\t\t \t\t\t{calib_param(5), 0, -calib_param(3)},\n\t\t\t \t\t\t{-calib_param(4), calib_param(3), 0}};\n\n\tarma::Mat<double> R(3,3); R.eye();\n\n\tR = R+(sin(theta)/theta)*omega+((1-cos(theta))/pow(theta,2))*(omega*omega);\n\n\tarma::Col<double> T = {calib_param(6), calib_param(7), calib_param(8)};\n\n\tarma::Mat<double> K = {{R(0,0), R(0,1), R(0,2), T(0)},\n\t\t \t\t\t\t{R(1,0), R(1,1), R(1,2), T(1)},\n\t\t \t\t\t\t{R(2,0), R(2,1), R(2,2), T(2)},\n\t\t \t\t\t\t{0, 0, 0, 1}};\n\n\treturn C*K;\n\n}", "meta": {"hexsha": "2406730fc8236c82ed97a4ae66a822a14a37bc41", "size": 19116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FlyTrackApp/focal_grid_old.cpp", "max_stars_repo_name": "jmmelis/FlyTrackApp", "max_stars_repo_head_hexsha": "7c03eb0aeda7b0bd4e0c6181bc776c92e4fbc582", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FlyTrackApp/focal_grid_old.cpp", "max_issues_repo_name": "jmmelis/FlyTrackApp", "max_issues_repo_head_hexsha": "7c03eb0aeda7b0bd4e0c6181bc776c92e4fbc582", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FlyTrackApp/focal_grid_old.cpp", "max_forks_repo_name": "jmmelis/FlyTrackApp", "max_forks_repo_head_hexsha": "7c03eb0aeda7b0bd4e0c6181bc776c92e4fbc582", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6246648794, "max_line_length": 169, "alphanum_fraction": 0.6080246914, "num_tokens": 6833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.23047034201023156}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n#include \"OSNSMultipleImpact.hpp\"\n#include \"LagrangianDS.hpp\"\n#include \"MultipleImpactNSL.hpp\"\n#include \"Simulation.hpp\"\n#include \"ioMatrix.hpp\"\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/progress.hpp>\n#include \"OSNSMatrix.hpp\"\n#include \"Model.hpp\"\n#include \"NonSmoothDynamicalSystem.hpp\"\n\n//Default constructor\nOSNSMultipleImpact::OSNSMultipleImpact(): LinearOSNS()\n{\n  _typeCompLaw = \"BiStiffness\";\n  _nStepSave = 100;\n  _tolImpact = DEFAULT__tolImpact;\n  _Tol_Vel = DEFAULT_TOL_VEL;\n  _Tol_Ener = DEFAULT_TOL_ENER;\n  _ZeroVel_EndIm = DEFAULT_TOL_VEL;\n  _ZeroEner_EndIm = DEFAULT_TOL_ENER;\n  _saveData = false;\n  _sizeDataSave = 1000;\n  _nStepMax = 100000;\n  _stepMinSave = 1;\n  _stepMaxSave = _nStepMax;\n  _namefile = \"DataMultipleImpact.dat\";\n}\n//------------------------------ -------------------------------------------------------------\nOSNSMultipleImpact::OSNSMultipleImpact(std::string newTypeLaw, double newDelP = 1.0e-5): LinearOSNS()\n{\n  _typeCompLaw = newTypeLaw;\n  _deltaP = newDelP;\n  _nStepSave = 100;\n  _tolImpact = DEFAULT__tolImpact;\n  _Tol_Vel = DEFAULT_TOL_VEL;\n  _Tol_Ener = DEFAULT_TOL_ENER;\n  _ZeroVel_EndIm = DEFAULT_TOL_VEL;\n  _ZeroEner_EndIm = DEFAULT_TOL_ENER;\n  _saveData = false;\n  _namefile = \"DataMultipleImpact.dat\";\n  _sizeDataSave = 1000;\n  _nStepMax = 100000;\n  _stepMinSave = 1;\n  _stepMaxSave = _nStepMax;\n  if ((_typeCompLaw != \"MonoStiffness\") && (_typeCompLaw != \"BiStiffness\"))\n    RuntimeException::selfThrow(\"OSNSMultipleImpact::_typeCompLaw type of the compliance model must be either MonoStiffness or BiStiffness!\");\n}\n//-------------------------------------------------------------------------------------------------\nOSNSMultipleImpact::~OSNSMultipleImpact() {}\n//------------------------------------------------------------------------------------------------\n\nvoid OSNSMultipleImpact::setTolImpact(double newTolZero)\n{\n  _tolImpact = newTolZero;\n};\n\nvoid OSNSMultipleImpact::SetSaveData(bool var)\n{\n  _saveData = var;\n};\n\nvoid OSNSMultipleImpact::SetNameOutput(std::string file_name)\n{\n  _namefile = file_name;\n};\n\nvoid OSNSMultipleImpact::SetTolVel(double _var)\n{\n  _Tol_Vel = _var;\n};\n\nvoid OSNSMultipleImpact::SetTolEner(double _var)\n{\n  _Tol_Ener = _var;\n};\n\nvoid OSNSMultipleImpact::SetZeroVelEndImp(double _var)\n{\n  _ZeroVel_EndIm = _var;\n};\n\nvoid OSNSMultipleImpact::SetZeroEnerEndImp(double _var)\n{\n  _ZeroEner_EndIm = _var;\n};\n\nvoid OSNSMultipleImpact::SetNstepSave(unsigned int var)\n{\n  _nStepSave = var;\n};\n\nvoid OSNSMultipleImpact::SetNstepMax(unsigned int var)\n{\n  _nStepMax = var;\n};\n\nvoid OSNSMultipleImpact::SetStepMinMaxSave(unsigned int var1, unsigned int var2)\n{\n  _stepMinSave = var1;\n  _stepMaxSave = var2;\n}\n\nvoid OSNSMultipleImpact::set_typeCompLaw(std::string newTypeLaw)\n{\n  _typeCompLaw = newTypeLaw;\n  if ((_typeCompLaw != \"MonoStiffness\") && (_typeCompLaw != \"BiStiffness\"))\n    RuntimeException::selfThrow(\"OSNSMultipleImpact::_typeCompLaw type of the compliance model must be either MonoStiffness or BiStiffness!\");\n};\n\nvoid OSNSMultipleImpact::SetSizeDataSave(unsigned int var)\n{\n  _sizeDataSave = var;\n}\n//---------------------------------------------------------------------------------------------------\nvoid OSNSMultipleImpact::WriteVectorIntoMatrix(const SiconosVector m, const unsigned int pos_row, const unsigned int pos_col)\n{\n  for (unsigned int i = 0; i < m.size(); ++i)\n  {\n    (*_DataMatrix)(pos_row, pos_col + i) = m(i);\n  }\n}\n//----------------------------------------------------------------------------------------------------\nbool OSNSMultipleImpact::isZero(double Var)\n{\n  if (std::abs(Var) <= _tolImpact)\n    return true;\n  else\n    return false;\n}\n//------------------------------------------------------------------------------------------------\nbool OSNSMultipleImpact::isVelNegative(double Var)\n{\n  if (Var < - _Tol_Vel)\n    return true;\n  else\n    return false;\n}\n//-------------------------------------------------------------------------------------------------\n\nbool OSNSMultipleImpact::isEnerZero(double Var)\n{\n  if (std::abs(Var) <= _Tol_Ener)\n    return true;\n  else\n    return false;\n}\n//--------------------------------------------------------------------------------------------------\nunsigned int OSNSMultipleImpact::EstimateNdataCols()\n{\n  unsigned int _numberCols = 1;\n  // Number of columns for data at contacts\n  SP::InteractionsGraph indexSet = simulation()->indexSet(0); // get indexSet[0]\n  InteractionsGraph::VIterator ui, uiend;\n  for (std11::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)\n  {\n    //_numberCols = _numberCols + 3*(indexSet->bundle(*ui)->interaction()->nonSmoothLaw()->size()) + 1;\n    _numberCols = _numberCols + (indexSet->bundle(*ui)->getSizeOfY());\n  }\n  // Number of columns for data at particles\n  SP::DynamicalSystemsGraph DSG = simulation()->nonSmoothDynamicalSystem()->dynamicalSystems();\n  DynamicalSystemsGraph::VIterator dsi, dsiend;\n  for (std11::tie(dsi, dsiend) = DSG->vertices(); dsi != dsiend; ++dsi)\n  {\n    _numberCols = _numberCols + (DSG->bundle(*dsi)->dimension());\n  }\n  return(_numberCols);\n}\n//-----------------------------------------------------------------------------------------------\nvoid OSNSMultipleImpact::AllocateMemory()\n{\n  if (!_velocityContact)\n    _velocityContact.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_velocityContact->size() != maxSize())\n      _velocityContact->resize(maxSize());\n  };\n  //\n  if (!_oldVelocityContact)\n    _oldVelocityContact.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_oldVelocityContact->size() != maxSize())\n      _oldVelocityContact->resize(maxSize());\n  };\n  //\n  if (! _energyContact)\n    _energyContact.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_energyContact->size() != maxSize())\n      _energyContact->resize(maxSize());\n  };\n  //\n  if (!_WorkcContact)\n    _WorkcContact.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_WorkcContact->size() != maxSize())\n      _WorkcContact->resize(maxSize());\n  };\n  //\n  if (!_distributionVector)\n    _distributionVector.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_distributionVector->size() != maxSize())\n      _distributionVector->resize(maxSize());\n  };\n  //\n  if (!_stateContact)\n    _stateContact.reset(new IndexInt(maxSize()));\n  else\n  {\n    if (_stateContact->size() != maxSize())\n      _stateContact->resize(maxSize());\n  };\n  //\n  if (!_Kcontact)\n    _Kcontact.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_Kcontact->size() != maxSize())\n      _Kcontact->resize(maxSize());\n  };\n  //\n  if (!_restitutionContact)\n    _restitutionContact.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_restitutionContact->size() != maxSize())\n      _restitutionContact->resize(maxSize());\n  };\n  //\n  if (!_elasticyCoefficientcontact)\n    _elasticyCoefficientcontact.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_elasticyCoefficientcontact->size() != maxSize())\n      _elasticyCoefficientcontact->resize(maxSize());\n  };\n  if (!_tolImpulseContact)\n    _tolImpulseContact.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_tolImpulseContact->size() != maxSize())\n      _tolImpulseContact->resize(maxSize());\n  };\n  //\n  if (!_deltaImpulseContact)\n    _deltaImpulseContact.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_deltaImpulseContact->size() != maxSize())\n      _deltaImpulseContact->resize(maxSize());\n  };\n  //\n  if (!_impulseContactUpdate)\n    _impulseContactUpdate.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_impulseContactUpdate->size() != maxSize())\n      _impulseContactUpdate->resize(maxSize());\n  }\n  //\n  if (!_forceContact)\n    _forceContact.reset(new SiconosVector(maxSize()));\n  else\n  {\n    if (_forceContact->size() != maxSize())\n      _forceContact->resize(maxSize());\n  };\n  // for the data matrix\n  unsigned int _numberCols = EstimateNdataCols();\n  if (!_DataMatrix)\n    _DataMatrix.reset(new SimpleMatrix(_sizeDataSave, _numberCols));\n  else\n  {\n    if ((_DataMatrix->size(0) != _sizeDataSave) || (_DataMatrix->size(1) != _numberCols))\n      _DataMatrix->resize(_sizeDataSave, _numberCols);\n  }\n}\n//=====================================================================================\nvoid OSNSMultipleImpact::BuildParaContact()\n{\n  SP::InteractionsGraph indexSet = simulation()->indexSet(1); // get indexSet[1]\n  //Loop over the Interactionof the indexSet(1)\n  InteractionsGraph::VIterator ui, uiend;\n  for (std11::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)\n  {\n    SP::Interaction inter = indexSet->bundle(*ui);\n    SP::NonSmoothLaw nslaw = inter->nslaw();\n    SP::MultipleImpactNSL Mulnslaw = std11::dynamic_pointer_cast<MultipleImpactNSL>(nslaw);\n    assert(Mulnslaw && \"In OSNSMultipleImpact::BuildStiffResCofVec, non-smooth law used must be MultipleImpactNSL!!!\");\n    // Get the relative position of inter-interactionBlock in the vector _velocityContact\n    unsigned int pos = _M->getPositionOfInteractionBlock(*inter);\n    (*_restitutionContact)(pos) = Mulnslaw->ResCof();\n    (*_Kcontact)(pos) = Mulnslaw->Stiff();\n    (*_elasticyCoefficientcontact)(pos) = Mulnslaw->ElasCof();\n  }\n  /*\n    std::cout << \" Restitution coefficients: \" <<std::endl;\n    _restitutionContact->display();\n    std::cout << \"Stiffnesses: \" <<std::endl;\n    _Kcontact->display();\n    std::cout << \"Elasticity coeffients at contacts: \" <<std::endl;\n    _elasticyCoefficientcontact->display();\n  */\n\n}\n//========================================================================================\nvoid OSNSMultipleImpact::PreComputeImpact()\n{\n  //1. Get the number of contacts and bodies involved in the impact\n  if (indexSetLevel() != 1)\n    RuntimeException::selfThrow(\"OSNSMultipleImpact::PreComputeImpact==> the levelMin must be equal to 1 in the multiple impact model !!\");\n  SP::InteractionsGraph indexSet = simulation()->indexSet(indexSetLevel()); // get indexSet[1]\n  _nContact = indexSet->size();\n  //2. Compute matrix _M\n  SP::Topology topology = simulation()->nonSmoothDynamicalSystem()->topology();\n  bool isLinear = simulation()->nonSmoothDynamicalSystem()->isLinear();\n  if (!_hasBeenUpdated || !isLinear)\n  {\n    // Computes new _unitaryBlocks if required\n    updateInteractionBlocks();\n    // Updates matrix M\n    _M->fill(indexSet, !_hasBeenUpdated);\n    _sizeOutput = _M->size();\n  }\n  if (_nContact != _sizeOutput)\n    RuntimeException::selfThrow(\"OSNSMultipleImpact::ComputeWMinvWtrans: number of contacts different from the size of output--> this case is not yet implemented!\");\n  //3. Checks size of vectors\n  if (_velocityContact->size() != _sizeOutput)\n  {\n    _velocityContact->resize(_sizeOutput);\n  }\n  _velocityContact->zero();\n  //\n  if (_oldVelocityContact->size() != _sizeOutput)\n  {\n    _oldVelocityContact->resize(_sizeOutput);\n  }\n  _oldVelocityContact->zero();\n  //\n  if (_energyContact->size() != _sizeOutput)\n  {\n    _energyContact->resize(_sizeOutput);\n  }\n  _energyContact->zero();\n  //\n  if (_WorkcContact->size() != _sizeOutput)\n  {\n    _WorkcContact->resize(_sizeOutput);\n  }\n  _WorkcContact->zero();\n  //\n  if (_distributionVector->size() != _sizeOutput)\n  {\n    _distributionVector->resize(_sizeOutput);\n  }\n  _distributionVector->zero();\n  //\n  if (_stateContact->size() != _sizeOutput)\n  {\n    _stateContact->resize(_sizeOutput);\n  }\n  //\n  if (_Kcontact->size() != _sizeOutput)\n  {\n    _Kcontact->resize(_sizeOutput);\n  }\n  _Kcontact->zero();\n  //\n  if (_restitutionContact->size() != _sizeOutput)\n  {\n    _restitutionContact->resize(_sizeOutput);\n  }\n  _restitutionContact->zero();\n  //\n  if (_elasticyCoefficientcontact->size() != _sizeOutput)\n  {\n    _elasticyCoefficientcontact->resize(_sizeOutput);\n  }\n  _elasticyCoefficientcontact->zero();\n  //\n  if (_tolImpulseContact->size() != _sizeOutput)\n  {\n    _tolImpulseContact->resize(_sizeOutput);\n  }\n  _tolImpulseContact->zero();\n  //\n  if (_deltaImpulseContact->size() != _sizeOutput)\n  {\n    _deltaImpulseContact->resize(_sizeOutput);\n  }\n  _deltaImpulseContact->zero();\n  //\n  if (_impulseContactUpdate->size() != _sizeOutput)\n  {\n    _impulseContactUpdate->resize(_sizeOutput);\n  }\n  _impulseContactUpdate->zero();\n  //\n  if (_forceContact->size() != _sizeOutput)\n  {\n    _forceContact->resize(_sizeOutput);\n  }\n  _forceContact->zero();\n  //4. Initialize the relative velocity, potential energy, impulse at contacts\n  InitializeInput();\n  //5. Build the vectors of stifnesseses, of restitution coefficients, and of elaticity coefficients\n  BuildParaContact();\n}\n//=======================================================================================\nvoid OSNSMultipleImpact::InitializeInput()\n{\n  //Loop over alls Interactioninvolved in the indexSet[1]\n  SP::InteractionsGraph indexSet = simulation()->indexSet(indexSetLevel()); // get indexSet[1]\n  InteractionsGraph::VIterator ui, uiend;\n  for (std11::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)\n  {\n    SP::Interaction inter = indexSet->bundle(*ui);\n    //SP::SiconosVector Vc0 = inter->y(1); // Relative velocity at beginning of impact\n    SP::SiconosVector Vc0 = inter->yOld(1); // Relative velocity at beginning of impact\n    unsigned int pos_inter = _M->getPositionOfInteractionBlock(*inter);\n    setBlock(*Vc0, _velocityContact, Vc0->size(), 0, pos_inter);\n    SP::SiconosVector ener0(new SiconosVector(Vc0->size()));\n    ener0->zero(); // We suppose that the initial potential energy before impact is equal to zero at any contact\n    // at the beginning of impact\n    setBlock(*ener0, _energyContact, ener0->size(), 0, pos_inter);\n    //SP::SiconosVector impulse0= (inter)->lambda(1))->vector(inter->number());\n    SP::SiconosVector impulse0(new SiconosVector(Vc0->size()));\n    impulse0->zero(); // We suppose that the impulse before impact is equal to zero at any contact\n    // at the beginning of impact\n    setBlock(*impulse0, _tolImpulseContact, impulse0->size(), 0, pos_inter);\n  };\n  /*\n    std::cout << \"Initial relative velocity at contacts\" <<std::endl;\n    _velocityContact->display();\n    std::cout<< \"Initial energy at contacts\" <<std::endl;\n    _energyContact->display();\n    std::cout << \"Impulse at contact\" <<std::endl;\n    _tolImpulseContact->display();\n  */\n\n}\n//=========================================================================================\nvoid OSNSMultipleImpact::initialize(SP::Simulation sim)\n{\n\n  // General initialize for OneStepNSProblem\n  OneStepNSProblem::initialize(sim);\n  // Allocate the memory\n  AllocateMemory();\n  // get topology\n  SP::Topology topology = simulation()->nonSmoothDynamicalSystem()->topology();\n  // Note that _interactionBlocks is up to date since updateInteractionBlocks\n  // has been called during OneStepNSProblem::initialize()\n\n  if (! _M)\n  {\n    if (_MStorageType == 0)\n      _M.reset(new OSNSMatrix(maxSize(), 0));\n\n    else // if(_MStorageType == 1) size = number of _interactionBlocks\n      // = number of Interactionin the largest considered indexSet\n      _M.reset(new OSNSMatrix(simulation()->indexSet(indexSetLevel())->size(), 1));\n  }\n\n};\n//========================================================================================\nvoid OSNSMultipleImpact::PrimConVelocity()\n{\n  getMin(*_velocityContact, _relativeVelocityPrimaryContact, _primaryContactId);\n  _energyPrimaryContact = (*_energyContact)(_primaryContactId);\n  if (!isVelNegative(_relativeVelocityPrimaryContact))\n  {\n    RuntimeException::selfThrow(\"OSNSMultipleImpact::PrimConVelocity, the velocity at the primary contact must be negative !!\");\n  }\n  /*\n    std::cout << \"Primary contact according to relative velocity: \" << _primaryContactId <<std::endl;\n    std::cout << \"Relative velocity at the primary contact: \" << _relativeVelocityPrimaryContact <<std::endl;\n    std::cout << \"Potential energy at the primary contact: \" << _energyPrimaryContact <<std::endl;\n  */\n}\n//=======================================================================================\nvoid OSNSMultipleImpact::PrimConEnergy()\n{\n  getMax(*_energyContact, _energyPrimaryContact, _primaryContactId);\n  _relativeVelocityPrimaryContact = (*_velocityContact)(_primaryContactId);\n  if (_energyPrimaryContact < 0.0)\n  {\n    RuntimeException::selfThrow(\"OSNSMultipleImpact::PrimConEnergy the potential energy at the primary contact must be positive !!\");\n  }\n  /*\n    std::cout << \"Primary contact according to potenial energy: \" << _primaryContactId <<std::endl;\n    std::cout << \"Relative velocity at the primary contact: \" << _relativeVelocityPrimaryContact <<std::endl;\n    std::cout << \"Potential energy at the primary contact: \" << _energyPrimaryContact <<std::endl;\n  */\n\n}\n//======================================================================================\nbool OSNSMultipleImpact::IsEnermaxZero()\n{\n  double MaxEner;\n  unsigned int IdMax;\n  getMax(*_energyContact, MaxEner, IdMax);\n  if (isEnerZero(MaxEner))\n    return true;\n  else\n    return false;\n}\n//======================================================================================\nbool OSNSMultipleImpact::IsVcminNegative()\n{\n  double MinVelCon;\n  unsigned int IdConVmin;\n  getMin(*_velocityContact, MinVelCon, IdConVmin);\n  if (isVelNegative(MinVelCon))\n    return true;\n  else\n    return false;\n}\n//=======================================================================================\nvoid OSNSMultipleImpact::Check_stateContact()\n{\n  for (unsigned int i = 0; i < _nContact; ++i)\n  {\n    if (isEnerZero((*_energyContact)(i))) // potential energy is zero\n    {\n      if (!isVelNegative((*_velocityContact)(i))) // relative velocity is positive or equal to zero\n        (*_stateContact)[i] = 0; // no impact at this contact\n      else  // impact happens without potential energy\n      {\n        (*_stateContact)[i] = 1;\n      }\n    }\n    else // impact happens with not zero potential energy\n    {\n      if ((*_stateContact)[i] != 2)\n      {\n        (*_stateContact)[i] = 2;\n      }\n    }\n  }\n}\n//=======================================================================================\nbool OSNSMultipleImpact::IsMulImpactTerminate()\n{\n  _IsImpactEnd = true;\n  for (unsigned int i = 0; i < _nContact; ++i)\n  {\n    if (((*_energyContact)(i) > _ZeroEner_EndIm) || ((*_velocityContact)(i) < -_ZeroVel_EndIm)) // if potential energy is not equal to zero or the relative velocity is negative\n    {\n      _IsImpactEnd = false;\n    }\n  }\n  return _IsImpactEnd;\n  //   bool var = true;\n  //   for(unsigned int i = 0; i < _nContact;++i)\n  //     {\n  //       if ((*_stateContact)[i] != 0)\n  //         {\n  //           var = false;\n  //           break;\n  //         };\n  //     };\n  //   return var;\n  //\n  //cout << \"Is the multiple impacts is terminated: \" << _IsImpactEnd <<std::endl;\n  //\n}\n//=======================================================================================\nvoid OSNSMultipleImpact::SelectPrimaContact()\n{\n  if (IsEnermaxZero()) // case of no potential energy at any contact\n  {\n    PrimConVelocity(); // Select the primary contact according to the relative velocity at contact\n    _isPrimaryContactEnergy = false;\n  }\n  else\n  {\n    PrimConEnergy(); // Select the primary contact according to the potential energy at contacts\n    _isPrimaryContactEnergy = true;\n  }\n  //\n  // std::cout << \"The primary contact is :\" << _primaryContactId <<std::endl;\n  // std::cout << \"Is the primary contact is selected according to the potential energy: \" << _isPrimaryContactEnergy <<std::endl;\n}\n//=======================================================================================\nvoid OSNSMultipleImpact::Compute_distributionVector()\n{\n  //Case 1: if no potential energy at any contact\n  double _ratio_mu, ratio_stiff, ratio_ener;\n  double mu_prima = (*_elasticyCoefficientcontact)(_primaryContactId); // Elasticity coefficient at the primary contact\n  double stiff_prima = (*_Kcontact)(_primaryContactId);     // Stiffness at the primary contact\n  double _mu, _stiff, _vel, _energy;\n  if (!_isPrimaryContactEnergy) // case of primary contact selected according to the relative velocity\n  {\n    double ratio_vel;\n    for (unsigned int i = 0; i < _nContact; ++i)\n    {\n      if ((*_stateContact)[i] != 0) // the impact can takes place at this contact\n      {\n        _mu = (*_elasticyCoefficientcontact)(i); // Elasticity coefficient at the current contact\n        _stiff = (*_Kcontact)(i);     // Stiffness at the current contact\n        _vel = (*_velocityContact)(i);     // Relative velocity at the current contact\n        _ratio_mu = (std::pow(_mu + 1.0, (_mu / (_mu + 1.0)))) / (std::pow(mu_prima + 1.0, (mu_prima / (mu_prima + 1.0))));\n        ratio_stiff = (std::pow(_stiff, (1.0 / (1.0 + _mu)))) / (std::pow(stiff_prima, (1.0 / (1.0 + mu_prima))));\n        if (!isVelNegative(_vel))\n        {\n          RuntimeException::selfThrow(\"OSNSMultipleImpact::Compute_distributionVector, the relative velocity when particle starts to impact must be negative!!\");\n        }\n\n        ratio_vel = (std::pow(std::fabs(_vel), (_mu / (_mu + 1.0)))) / (std::pow(std::fabs(_relativeVelocityPrimaryContact), (mu_prima / (1.0 + mu_prima))));\n        (*_distributionVector)(i) = std::pow((_ratio_mu * ratio_stiff * ratio_vel), (1.0 + _mu)) * std::pow(_deltaP, ((_mu - mu_prima) / (1.0 + mu_prima)));\n      }\n      else\n      {\n        (*_distributionVector)(i) = 0.0;\n      }\n      if ((*_distributionVector)(i) < 0.0)\n        RuntimeException::selfThrow(\"OSNSMultipleImpact::Compute_distributionVector the component of _distributionVector must be positive !!\");\n    };\n  }\n  //Case 2: case of primary contact selected according to the potential energy\n  else\n  {\n    for (unsigned int i = 0; i < _nContact; ++i)\n    {\n      //\n      _mu = (*_elasticyCoefficientcontact)(i);\n      _stiff = (*_Kcontact)(i);\n      _ratio_mu = (std::pow(_mu + 1.0, (_mu / (_mu + 1.0)))) / (std::pow(mu_prima + 1.0, (mu_prima / (mu_prima + 1.0))));\n      ratio_stiff = (std::pow(_stiff, (1.0 / (1.0 + _mu)))) / (std::pow(stiff_prima, (1.0 / (1.0 + mu_prima))));\n      if ((*_stateContact)[i] == 1) // no potential energy at this contact, including the contacts at which impact repeats\n      {\n        if (!isVelNegative((*_velocityContact)(i)))\n        {\n          RuntimeException::selfThrow(\"OSNSMultipleImpact::Compute_distributionVector, the pre-impact velocity must be negative!!\");\n        }\n        else\n        {\n          _vel = (*_velocityContact)(i);\n          ratio_ener = (std::pow(std::fabs(_vel * _deltaP), (_mu / (_mu + 1.0)))) / (std::pow(_energyPrimaryContact, (mu_prima / (mu_prima + 1.0))));\n          //\n          // std::cout << \"_ratio_m: \" << _ratio_mu <<std::endl;\n          // std::cout << \"Stiff: \" << _stiff <<std::endl;\n          // std::cout << \"ratio_stiff: \" << ratio_stiff <<std::endl;\n          // std::cout << \"energy ratio: \" << ratio_ener <<std::endl;\n\n          //\n          (*_distributionVector)(i) = std::pow((_ratio_mu * ratio_stiff * ratio_ener), (1.0 + _mu));\n        }\n      }\n      else if ((*_stateContact)[i] == 2) // potential is not zero at this contact\n      {\n        _energy = (*_energyContact)(i); // Potential energy at the current contact\n        ratio_ener = (std::pow(_energy, (_mu / (_mu + 1.0)))) / (std::pow(_energyPrimaryContact, (mu_prima / (mu_prima + 1.0))));\n        (*_distributionVector)(i) = _ratio_mu * ratio_stiff * ratio_ener;\n      }\n      else // no impact at this contact\n      {\n        (*_distributionVector)(i) = 0.0;\n      };\n      if ((*_distributionVector)(i) < 0.0)\n        RuntimeException::selfThrow(\"OSNSMultipleImpact::Compute_distributionVector the component of _distributionVector must be positive !!\");\n    };\n  };\n}\n//=======================================================================================\nvoid OSNSMultipleImpact::ComputeImpulseContact()\n{\n  (*_deltaImpulseContact) = (*_distributionVector) * _deltaP;\n  (*_tolImpulseContact) = (*_tolImpulseContact) + (*_deltaImpulseContact);\n  (*_impulseContactUpdate) = (*_impulseContactUpdate) + (*_deltaImpulseContact);\n  // Compute the contact force\n  double PowCompLaw;\n  for (unsigned int i = 0; i < _nContact; ++i)\n  {\n    PowCompLaw = (*_elasticyCoefficientcontact)(i);\n    if (isEnerZero((*_energyContact)(i))) // if potential energy at this contact is zero\n    {\n      if (isVelNegative((*_velocityContact)(i))) // if the relative velocity at contact is negative\n      {\n        (*_forceContact)(i) = std::pow((1.0 + PowCompLaw), PowCompLaw / (1.0 + PowCompLaw)) * std::pow((*_Kcontact)(i), 1.0 / (1.0 + PowCompLaw)) * std::pow((std::fabs((*_velocityContact)(i)) * (*_deltaImpulseContact)(i)), PowCompLaw / (1.0 + PowCompLaw));\n      }\n      else\n      {\n        (*_forceContact)(i) = 0.0;\n      };\n    }\n    else\n    {\n      (*_forceContact)(i) = std::pow((1.0 + PowCompLaw), PowCompLaw / (1.0 + PowCompLaw)) * std::pow((*_Kcontact)(i), 1.0 / (1.0 + PowCompLaw)) * std::pow((*_energyContact)(i), PowCompLaw / (1.0 + PowCompLaw));\n    }\n    if ((*_forceContact)(i) < 0.0)\n    {\n      RuntimeException::selfThrow(\"OSNSMultipleImpact::ComputeImpulseContact, the contact force must be positive or equal to zero!!!\");\n    }\n  };\n}\n//=======================================================================================\nvoid OSNSMultipleImpact::Compute_velocityContact()\n{\n  (*_oldVelocityContact) = (*_velocityContact); //save the relative velocity at the beginning of the step\n  (*_velocityContact) = (*_velocityContact) + prod(*(_M->defaultMatrix()), *_deltaImpulseContact); // compute the relative velocity at the end of the step\n  //\n  /*\n    std::cout << \"Relative velocity at contacts at the beginning of step:\" <<std::endl;\n    _oldVelocityContact->display();\n    std::cout << \"Relative velocity at contacts at the end of step:\" <<std::endl;\n    _velocityContact->display();\n  */\n  //\n}\n//=======================================================================================\nvoid OSNSMultipleImpact::Compute_energyContact()\n{\n  if (_typeCompLaw == \"BiStiffness\")\n    // For Bistiffness model\n  {\n    for (unsigned int i = 0; i < _nContact; ++i)\n    {\n      if ((0.5 * ((*_oldVelocityContact)(i) + (*_velocityContact)(i))) <= 0.0) // Contact located in the compression phase\n      {\n        (*_energyContact)(i) = (*_energyContact)(i) - 0.5 * ((*_oldVelocityContact)(i) + (*_velocityContact)(i)) * ((*_deltaImpulseContact)(i));\n      }\n      else                       // Contact located in the expansion phase\n      {\n        if (!isZero((*_restitutionContact)(i)))\n        {\n          (*_energyContact)(i) = (*_energyContact)(i) - (1.0 / std::pow((*_restitutionContact)(i), 2)) * 0.5 * ((*_oldVelocityContact)(i) + (*_velocityContact)(i)) * ((*_deltaImpulseContact)(i));\n          //\n          if ((*_energyContact)(i) <  0.0)\n          {\n            (*_energyContact)(i) = 0.0;\n          };\n        }\n        else // restitution coefficient equal to zero\n        {\n          (*_energyContact)(i) = 0.0; // In this case, no potential energy at contacts when the contact is located in the compression phase\n        }\n      };\n      //\n      if ((*_energyContact)(i) <  0.0)\n      {\n        RuntimeException::selfThrow(\"OSNSMultipleImpact::Compute_energyContact, the potential energy during compression phase must be positive!!!\");\n      };\n    };\n  }\n  else\n    // For the mono-stiffness model\n  {\n    for (unsigned int i = 0; i < _nContact; ++i)\n    {\n      //1: dertermine the work done by the last compression phase at contacts (nessessary for the mono-stiffness compliance model)\n      // if Vc(k) < 0 and Vc(k +1) >= 0 ==> transition from the compression phase to the expansion phase, Wc = E(k)\n      if (((*_oldVelocityContact)(i) < 0.0) && ((*_velocityContact)(i) >= 0.0))\n      {\n        (*_WorkcContact)(i) = (*_energyContact)(i);\n      };\n      //2: Calculate the potential energy at the end of stap\n      (*_energyContact)(i) = (*_energyContact)(i) - 0.5 * ((*_oldVelocityContact)(i) + (*_velocityContact)(i)) * ((*_deltaImpulseContact)(i));\n      //3: Check if the termination condition is verified or not (if Vc(k+1) > 0.0 and E(k+1) <= (1-e^2)*Wc). If yes, discard the potential energy\n      // in order to respect the energetic constraint\n      if (((*_stateContact)[i] == 2) && (((*_velocityContact)(i) > 0.0) && ((*_energyContact)(i) <= ((1.0 - std::pow((*_restitutionContact)(i), 2)) * (*_WorkcContact)(i)))))\n      {\n        (*_energyContact)(i) = 0.0; // potential energy at this contact is completely dissipated before the compression phase finishes\n      };\n    };\n  }\n  /*\n\n    std::cout << \"Potential energy at contacts at the end of step:\" <<std::endl;\n    _energyContact->display();\n    std::cout << \"Work done during the compression phase at contacts\" <<std::endl;\n    _WorkcContact->display();\n\n  */\n}\n//======================================================================================\nvoid OSNSMultipleImpact::UpdateDuringImpact()\n{\n  //1. Copy _velocityContact/_deltaImpulseContact into the vector y/lambda for Interactions\n  SP::InteractionsGraph indexSet = simulation()->indexSet(indexSetLevel());\n  // y and lambda vectors\n  SP::SiconosVector lambda;\n  SP::SiconosVector y;\n  // === Loop through \"active\" Interactions (ie present in indexSets[1]) ===\n  unsigned int pos;\n  InteractionsGraph::VIterator ui, uiend;\n  for (std11::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)\n  {\n    Interaction& inter = *indexSet->bundle(*ui);\n    // Get the relative position of inter-interactionBlock in the vector _velocityContact/_tolImpulseContact\n    pos = _M->getPositionOfInteractionBlock(inter);\n    // Get Y and Lambda for the current Interaction\n    y = inter.y(inputOutputLevel());\n    lambda = inter.lambda(inputOutputLevel());\n    // Copy _velocityContact/_tolImpulseContact, starting from index pos into y/lambda\n    // save into y !!\n    setBlock(*_velocityContact, y, y->size(), pos, 0);\n    // saved into lambda[1] !!\n    setBlock(*_impulseContactUpdate, lambda, lambda->size(), pos, 0);\n    //setBlock(*_deltaImpulseContact, lambda, lambda->size(), pos, 0);\n  };\n  //2. Update the Input[1], state of DS systems, Output[1]\n  simulation()->update(inputOutputLevel());\n  _impulseContactUpdate->zero(); // reset input[1] to zero after each update\n}\n//--------------------------------------------------------------------------------------\nvoid OSNSMultipleImpact::SaveDataOneStep(unsigned int _ithPoint)\n{\n  // Save the total impulse at the primary contacts (time-like independent variable) and the time evolution during impact\n  if (_ithPoint >= _DataMatrix->size(0))\n    RuntimeException::selfThrow(\"In OSNSMultipleImpact::ComputeImpact, number of points saved exceeds the size of matrix allocated!!!\");\n  //(*_DataMatrix)(_ithPoint,0) = _timeVariable;\n  (*_DataMatrix)(_ithPoint, 0) = _impulseVariable;\n  // Save the data related to UnitaryRelations\n  SP::InteractionsGraph indexSet0 = simulation()->indexSet(0);\n  SP::InteractionsGraph indexSet1 = simulation()->indexSet(indexSetLevel());\n  unsigned int pos;\n  InteractionsGraph::VIterator ui, uiend;\n  unsigned int col_pos = 1;\n  for (std11::tie(ui, uiend) = indexSet0->vertices(); ui != uiend; ++ui)\n  {\n    SP::Interaction inter = indexSet0->bundle(*ui);\n    SP::SiconosVector ydot = inter->y(1);\n    SP::SiconosVector P_inter(new SiconosVector(inter->getSizeOfY()));\n    SP::SiconosVector F_inter(new SiconosVector(inter->getSizeOfY()));\n    SP::SiconosVector E_inter(new SiconosVector(1));\n    if (indexSet1->is_vertex(inter)) // if Interaction belongs to the IndexSet[1]\n    {\n      pos = _M->getPositionOfInteractionBlock(*inter);\n      setBlock(*_tolImpulseContact, P_inter, P_inter->size(), pos, 0);\n      setBlock(*_forceContact, F_inter, F_inter->size(), pos, 0);\n      setBlock(*_energyContact, E_inter, E_inter->size(), pos, 0);\n    }\n    else\n    {\n      P_inter->zero();   // no impulse at this Interaction\n      F_inter->zero();   // no force at this Interaction\n      E_inter->zero();   // no potential at this Interaction\n    };\n    // Write the force at the Interaction\n    WriteVectorIntoMatrix(*F_inter, _ithPoint, col_pos);\n    //WriteVectorIntoMatrix(*P_inter, _ithPoint, col_pos);\n    //WriteVectorIntoMatrix(*E_inter, _ithPoint, col_pos);\n    col_pos = col_pos + F_inter->size();\n  } // Save the data related to DS\n  SP::DynamicalSystemsGraph DSG = simulation()->nonSmoothDynamicalSystem()->dynamicalSystems();\n  DynamicalSystemsGraph::VIterator dsi, dsiend;\n  for (std11::tie(dsi, dsiend) = DSG->vertices(); dsi != dsiend; ++dsi)\n  {\n    SP::DynamicalSystem ds = DSG->bundle(*dsi); // DS\n    SP::LagrangianDS Lagds = std11::dynamic_pointer_cast<LagrangianDS>(ds);\n    SP::SiconosVector qdot = Lagds->velocity();\n    // Write\n\n    WriteVectorIntoMatrix(*qdot, _ithPoint, col_pos);\n    col_pos = col_pos + qdot->size();\n  }\n}\n//=======================================================================================\nvoid OSNSMultipleImpact::ComputeImpact()\n{\n  _impulseVariable = 0.0;\n  _timeVariable = 0.0;\n  unsigned int number_step = 1;\n  unsigned int point_save = 0;\n  unsigned int _counterstepsave = 0;\n  // Show computation progress\n  //cout << \"*********** Impact computation progress *************\" <<std::endl;\n  //boost::progress_display show_progress(_nStepMax);\n  /*\n     std::cout << \"----------Before multiple impacts computation---------------\" <<std::endl;\n     std::cout << \"Velocity at contacts: \";\n     _velocityContact->display();\n     std::cout << \"Impulse at contact: \";\n     _tolImpulseContact->display();\n  */\n  //cout << \"-------------------Multiple impacts computation starts:-----------------------\" <<std::endl;\n  // First save at the beginning of impact computation\n  if ((_saveData) && (_stepMinSave == 1))\n  {\n    SaveDataOneStep(point_save); // Save the data\n    point_save++;\n  }\n  //\n  while (1 != 0)\n  {\n    // std::cout << \"==================Step==================:  \" << number_step <<std::endl;\n    // std::cout << \"Impulse variable: \" << _impulseVariable <<std::endl;\n    // std::cout << \"_timeVariable: \" << _timeVariable <<std::endl;\n\n    //Step 1: check the state at contacts\n    Check_stateContact();\n    //Step 2: check if the multiple impact is terminated or not\n    if (IsMulImpactTerminate()) // multiple impact terminated\n    {\n      if (_saveData) // Save the date at the end of impact\n      {\n        UpdateDuringImpact(); // Update state of dynamical system\n        SaveDataOneStep(point_save); // Save the data\n      }\n      break;\n    }\n    // Select the primary contact\n    SelectPrimaContact();\n    //Step 3: compute the vector of distributing law\n    Compute_distributionVector();\n    //Step 4: compute the increment of normal impulse and the total impulse at contacts\n    ComputeImpulseContact();\n    // Step 5: compute the relative velocity at contacts\n    Compute_velocityContact();\n    // Step 6: compute the potential energy at contacts\n    Compute_energyContact();\n    //Step 7: Update the time-like variable\n    ++number_step;\n    ++_counterstepsave;\n    //++show_progress;\n    _impulseVariable = _impulseVariable + _deltaP;\n    _timeVariable = _timeVariable + _deltaP / (*_forceContact)(_primaryContactId);\n    // Step 8: update the state of DS and output during impact and write data into output file at the beginning of each step\n    if ((_saveData) & (_counterstepsave >= _nStepSave))\n    {\n      if ((number_step >= _stepMinSave) && (number_step <= _stepMaxSave))\n      {\n        UpdateDuringImpact(); // Update state of dynamical system\n        SaveDataOneStep(point_save); // Save the data\n        point_save++;\n        _counterstepsave = 0; // reset the counter to 0\n      }\n    }\n    //\n    if (number_step > _nStepMax)\n    {\n      RuntimeException::selfThrow(\"In OSNSMultipleImpact::ComputeImpact, number of integration steps perfomed exceeds the maximal number of steps allowed!!!\");\n      //cout << \"Causion: so long computation, the computation is stopped even when the impact is not yet terminated!!! \" <<std::endl;\n      break;\n    }\n    // std::cout << \"Distribution vector: \";\n    // _distributionVector->display();\n    // std::cout << \"Incremental Impulse: \";\n    // _deltaImpulseContact->display();\n    // std::cout << \"Impulse at contact: \";\n    // _tolImpulseContact->display();\n    // std::cout << \"Velocity at contacts: \";\n    // _velocityContact->display();\n    // std::cout << \"Potential energy at contacts: \";\n    // _energyContact->display();\n\n  }\n\n  //\n  // std::cout << \"*****************Impact computation is terminated******************\" <<std::endl;\n  // std::cout << \"Number of integration steps: \" << number_step <<std::endl;\n  // std::cout << \"Velocity at contacts: \";\n  // _velocityContact->display();\n  // std::cout << \"Impulse at contact: \";\n  // _tolImpulseContact->display();\n  // std::cout << \"Duration of the multiple impacts process: \" << _timeVariable << \" s\" <<std::endl;\n\n  // Close the stream file\n  if (_saveData)\n  {\n    ioMatrix::write(_namefile.c_str(), \"ascii\", *_DataMatrix, \"noDim\");\n  }\n}\n//=======================================================================================\nvoid OSNSMultipleImpact::PostComputeImpact()\n{\n  // === Get index set from Topology ===\n  SP::InteractionsGraph indexSet = simulation()->indexSet(indexSetLevel());\n  // y and lambda vectors\n  SP::SiconosVector lambda;\n  SP::SiconosVector y;\n  // === Loop through \"active\" Interactions (ie present in indexSets[1]) ===\n  unsigned int pos;\n  InteractionsGraph::VIterator ui, uiend;\n  for (std11::tie(ui, uiend) = indexSet->vertices(); ui != uiend; ++ui)\n  {\n    Interaction& inter = *indexSet->bundle(*ui);\n    // Get the relative position of inter-interactionBlock in the vector _velocityContact/_tolImpulseContact\n    pos = _M->getPositionOfInteractionBlock(inter);\n    // Get Y and Lambda for the current Interaction\n    y = inter.y(inputOutputLevel());\n    lambda = inter.lambda(inputOutputLevel());\n    // Copy _velocityContact/_tolImpulseContact, starting from index pos into y/lambda\n    // save into y !!\n    setBlock(*_velocityContact, y, y->size(), pos, 0);// Warning: yEquivalent is\n    // saved into lambda[1] !!\n    setBlock(*_impulseContactUpdate, lambda, lambda->size(), pos, 0);\n    // If the update is performed at the end of the impact process, we update the total normal impulse at contacts\n    // from the beginning to the end of impact (vector _tolImpulseContact). Otherwise, we must reset the lambda[1] to zero because\n    // the post-impact velocity has been calculated during impact\n    // if (!_saveData) // we update the impact state at the end of impact\n    //   {\n    //     // Copy _velocityContact/_tolImpulseContact, starting from index pos into y/lambda\n    //     // save into y !!\n    //     setBlock(*_velocityContact, y, y->size(), pos, 0);// Warning: yEquivalent is\n    //     // saved into lambda[1] !!\n    //     setBlock(*_tolImpulseContact, lambda, lambda->size(), pos, 0);\n    //   }\n    // else //\n    //   lambda->zero();\n  }\n}\n//========================================================================================\nint OSNSMultipleImpact::compute(double time)\n{\n  // Pre-compute for impact\n  PreComputeImpact();\n  // solve the multiple impacts\n  if ((_nContact != 0) && IsVcminNegative()) // if there is at least one contact and the vilocity before impact is negative\n  {\n    ComputeImpact();\n  };\n  // Post-compute for multiple impacts\n  PostComputeImpact();\n  return  0;\n}\n\n//========================================================================================\nvoid OSNSMultipleImpact::display() const\n{\n  std::cout << \"<<<<<<<<<<<<<<<<< Information about the multiple impact >>>>>>>>>>>>>>>>>>>>>\" <<std::endl;\n  std::cout << \"Type of the contact compliance law: \" << _typeCompLaw <<std::endl;\n  std::cout << \"Number of contacts involved into impacts: \" << _nContact <<std::endl;\n  std::cout << \"Step size used: \" << _deltaP <<std::endl;\n  std::cout << \"Primary impulse at the end of impact: \" << _impulseVariable <<std::endl;\n  std::cout << \"Duration of the multiple impacs process: \" << _timeVariable <<std::endl;\n  // Display post-impact velocities\n  SP::DynamicalSystemsGraph DSG0 = simulation()->nonSmoothDynamicalSystem()->topology()->dSG(0);\n  DynamicalSystemsGraph::VIterator ui, uiend;\n  for (std11::tie(ui, uiend) = DSG0->vertices(); ui != uiend; ++ui)\n  {\n    SP::DynamicalSystem ds = DSG0->bundle(*ui);\n    SP::LagrangianDS lag_ds = std11::dynamic_pointer_cast<LagrangianDS>(ds);\n    std::cout << \"DS number: \" << ds->number() <<std::endl;\n    std::cout << \"Pre-impact velocity: \";\n    (lag_ds->velocityMemory()->getSiconosVector(1))->display();\n    std::cout << \"Post-impact velocity: \";\n    (lag_ds->velocity())->display();\n  }\n  // Display impulses at contact points\n  SP::InteractionsGraph IndexSet0 = simulation()->nonSmoothDynamicalSystem()->topology()->indexSet(0);\n  InteractionsGraph::VIterator vi, viend;\n  for (std11::tie(vi, viend) = IndexSet0->vertices(); vi != viend; ++vi)\n  {\n    SP::Interaction inter = IndexSet0->bundle(*vi);\n    std::cout << \"Impulse at contact point \" << inter->number() << \":\";\n    (inter->lambda(1))->display();\n  }\n};\n", "meta": {"hexsha": "590dce2b12da788c6c7bbbf8cbd69dd091517360", "size": 41641, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/simulationTools/OSNSMultipleImpact.cpp", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/simulationTools/OSNSMultipleImpact.cpp", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/simulationTools/OSNSMultipleImpact.cpp", "max_forks_repo_name": "siconos/siconos-deb", "max_forks_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7358139535, "max_line_length": 256, "alphanum_fraction": 0.6216229197, "num_tokens": 10852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.23023564916092618}}
{"text": "\n//此源码被清华学神尹成大魔王专业翻译分析并修改\n//尹成QQ77025077\n//尹成微信18510341407\n//尹成所在QQ群721929980\n//尹成邮箱 yinc13@mails.tsinghua.edu.cn\n//尹成毕业于清华大学,微软区块链领域全球最有价值专家\n//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620\n//版权所有（c）2017-2018比特币核心开发商\n//根据MIT软件许可证分发，请参见随附的\n//文件复制或http://www.opensource.org/licenses/mit-license.php。\n\n#include <wallet/coinselection.h>\n\n#include <util/system.h>\n#include <util/moneystr.h>\n\n#include <boost/optional.hpp>\n\n//降阶比较器\nstruct {\n    bool operator()(const OutputGroup& a, const OutputGroup& b) const\n    {\n        return a.effective_value > b.effective_value;\n    }\n} descending;\n\n/*\n *这是Murch设计的分支绑定硬币选择算法。它搜索输入\n *设置可支付支出目标，且不超过支出目标\n *创建和支出变更输出的成本。该算法对二进制文件使用深度优先搜索。\n *树。在二叉树中，每个节点对应于utxo的包含或省略。UTXOS\n *按其有效值排序，并根据包含内容对树进行确定性探索。\n *先分支。在每个节点上，算法检查选择是否在目标范围内。\n *虽然选择未达到目标范围，但包含更多的utxo。当选定内容\n *值超出目标范围，可省略从此选择派生的完整子树。\n *此时，取消选择最后一个包含的utxo，并探索相应的省略分支。\n *相反。搜索完成树后或经过有限的尝试后，搜索结束。\n *\n *找到一个解决方案后，搜索会继续搜索更好的解决方案。最好的\n *通过最小化浪费指标来选择解决方案。废物指标定义为\n *以给定的费率减去长期预期成本来花费当前投入\n *输入，加上所选金额超出支出目标：\n *\n *浪费=选择总计-目标+输入×（当前频率-长期频率）\n *\n *该算法使用了两个额外的优化。展望跟踪\n *未经探索的utxos。如果lookahead指示目标范围，则不探索子树。\n *无法联系。此外，无需测试等效组合。这让我们\n *跳过测试是否包含与省略项的有效值和浪费相匹配的utxo。\n *前身。\n *\n *分支定界算法在Murch的硕士论文中有详细描述：\n *https://murch.one/wp-content/uploads/2016/11/erhardt2016coinselection.pdf\n *\n *@param const std:：vector<cinputcoin>&utxo_pool我们正在选择的utxos集。\n *这些utxo将按有效值和cinputcoins的降序排序。\n *值是它们的有效值。\n *@param const camount&target_value这是我们要选择的值。它是较低的\n *范围的界限。\n *@param const camount&cost_change这是创建和花费更改输出的成本。\n *这个加上目标值是范围的上限。\n *@param std:：set<cinputcoin>&out\\set->这是一组cinputcoins的输出参数\n *已选定。\n *@param camount&value_ret->这是Cinputcoins总值的输出参数\n *已选定。\n *@param camount not_input_fees->输出和固定大小需要支付的费用\n *开销（版本、锁定时间、标记和标志）\n **/\n\n\nstatic const size_t TOTAL_TRIES = 100000;\n\nbool SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& target_value, const CAmount& cost_of_change, std::set<CInputCoin>& out_set, CAmount& value_ret, CAmount not_input_fees)\n{\n    out_set.clear();\n    CAmount curr_value = 0;\n\nstd::vector<bool> curr_selection; //在此索引中选择utxo\n    curr_selection.reserve(utxo_pool.size());\n    CAmount actual_target = not_input_fees + target_value;\n\n//计算当前可用值\n    CAmount curr_available_value = 0;\n    for (const OutputGroup& utxo : utxo_pool) {\n//断言这个utxo不是负数。它不应该是负数，有效值计算应该删除它。\n        assert(utxo.effective_value > 0);\n        curr_available_value += utxo.effective_value;\n    }\n    if (curr_available_value < actual_target) {\n        return false;\n    }\n\n//分类utxo_池\n    std::sort(utxo_pool.begin(), utxo_pool.end(), descending);\n\n    CAmount curr_waste = 0;\n    std::vector<bool> best_selection;\n    CAmount best_waste = MAX_MONEY;\n\n//选择utxos的深度优先搜索循环\n    for (size_t i = 0; i < TOTAL_TRIES; ++i) {\n//开始回溯的条件\n        bool backtrack = false;\nif (curr_value + curr_available_value < actual_target ||                //无法达到当前可用价值中剩余金额的目标。\ncurr_value > actual_target + cost_of_change ||    //所选值超出范围，请返回并尝试其他分支\n(curr_waste > best_waste && (utxo_pool.at(0).fee - utxo_pool.at(0).long_term_fee) > 0)) { //不要选择那些我们知道如果浪费增加会更浪费的东西。\n            backtrack = true;\n} else if (curr_value >= actual_target) {       //所选值在范围内\ncurr_waste += (curr_value - actual_target); //这是为进行以下比较而添加到废物中的超额价值。\n//如果长期费用高于当前费用，在检查后再添加一个utxo可以减少浪费。\n//但是，我们不会去探索这一点，因为只有当我们达到目标时，才会对废物进行优化。\n//价值。再加上任何一个utxo都只会烧掉utxo，而这完全是要收费的。所以我们不会\n//探索更多的UTXO，以避免像那样烧钱。\n            if (curr_waste <= best_waste) {\n                best_selection = curr_selection;\n                best_selection.resize(utxo_pool.size());\n                best_waste = curr_waste;\n            }\ncurr_waste -= (curr_value - actual_target); //去掉多余的价值，因为我们现在要选择不同的硬币\n            backtrack = true;\n        }\n\n//回溯，向后移动\n        if (backtrack) {\n//向后走，找到最后一个包含的utxo，它仍然需要遍历其省略分支。\n            while (!curr_selection.empty() && !curr_selection.back()) {\n                curr_selection.pop_back();\n                curr_available_value += utxo_pool.at(curr_selection.size()).effective_value;\n            }\n\nif (curr_selection.empty()) { //我们已经走回了第一个utxo，没有一个分支是不受欢迎的。已搜索所有解决方案\n                break;\n            }\n\n//输出包含在以前的迭代中，请尝试立即排除。\n            curr_selection.back() = false;\n            OutputGroup& utxo = utxo_pool.at(curr_selection.size() - 1);\n            curr_value -= utxo.effective_value;\n            curr_waste -= utxo.fee - utxo.long_term_fee;\n} else { //向前走，继续沿着这条路走\n            OutputGroup& utxo = utxo_pool.at(curr_selection.size());\n\n//将此utxo从当前可用的utxo值中删除\n            curr_available_value -= utxo.effective_value;\n\n//如果先前的utxo具有相同的值和相同的浪费并且被排除在外，则避免搜索分支。因为费用与\n//长期费用是一样的，我们只需要检查其中一个值是否匹配就可以知道浪费是一样的。\n            if (!curr_selection.empty() && !curr_selection.back() &&\n                utxo.effective_value == utxo_pool.at(curr_selection.size() - 1).effective_value &&\n                utxo.fee == utxo_pool.at(curr_selection.size() - 1).fee) {\n                curr_selection.push_back(false);\n            } else {\n//包容性分支第一（最大的第一次勘探）\n                curr_selection.push_back(true);\n                curr_value += utxo.effective_value;\n                curr_waste += utxo.fee - utxo.long_term_fee;\n            }\n        }\n    }\n\n//检查解决方案\n    if (best_selection.empty()) {\n        return false;\n    }\n\n//集合输出集合\n    value_ret = 0;\n    for (size_t i = 0; i < best_selection.size(); ++i) {\n        if (best_selection.at(i)) {\n            util::insert(out_set, utxo_pool.at(i).m_outputs);\n            value_ret += utxo_pool.at(i).m_value;\n        }\n    }\n\n    return true;\n}\n\nstatic void ApproximateBestSubset(const std::vector<OutputGroup>& groups, const CAmount& nTotalLower, const CAmount& nTargetValue,\n                                  std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)\n{\n    std::vector<char> vfIncluded;\n\n    vfBest.assign(groups.size(), true);\n    nBest = nTotalLower;\n\n    FastRandomContext insecure_rand;\n\n    for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)\n    {\n        vfIncluded.assign(groups.size(), false);\n        CAmount nTotal = 0;\n        bool fReachedTarget = false;\n        for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)\n        {\n            for (unsigned int i = 0; i < groups.size(); i++)\n            {\n//这里的解算器使用随机算法，\n//随机性不是真正的安全目的，只是\n//需要防止退化行为，这很重要\n//RNG很快。我们不使用常数随机序列，\n//因为通过\n//随机选择。\n                if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])\n                {\n                    nTotal += groups[i].m_value;\n                    vfIncluded[i] = true;\n                    if (nTotal >= nTargetValue)\n                    {\n                        fReachedTarget = true;\n                        if (nTotal < nBest)\n                        {\n                            nBest = nTotal;\n                            vfBest = vfIncluded;\n                        }\n                        nTotal -= groups[i].m_value;\n                        vfIncluded[i] = false;\n                    }\n                }\n            }\n        }\n    }\n}\n\nbool KnapsackSolver(const CAmount& nTargetValue, std::vector<OutputGroup>& groups, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet)\n{\n    setCoinsRet.clear();\n    nValueRet = 0;\n\n//小于目标值的列表\n    boost::optional<OutputGroup> lowest_larger;\n    std::vector<OutputGroup> applicable_groups;\n    CAmount nTotalLower = 0;\n\n    Shuffle(groups.begin(), groups.end(), FastRandomContext());\n\n    for (const OutputGroup& group : groups) {\n        if (group.m_value == nTargetValue) {\n            util::insert(setCoinsRet, group.m_outputs);\n            nValueRet += group.m_value;\n            return true;\n        } else if (group.m_value < nTargetValue + MIN_CHANGE) {\n            applicable_groups.push_back(group);\n            nTotalLower += group.m_value;\n        } else if (!lowest_larger || group.m_value < lowest_larger->m_value) {\n            lowest_larger = group;\n        }\n    }\n\n    if (nTotalLower == nTargetValue) {\n        for (const auto& group : applicable_groups) {\n            util::insert(setCoinsRet, group.m_outputs);\n            nValueRet += group.m_value;\n        }\n        return true;\n    }\n\n    if (nTotalLower < nTargetValue) {\n        if (!lowest_larger) return false;\n        util::insert(setCoinsRet, lowest_larger->m_outputs);\n        nValueRet += lowest_larger->m_value;\n        return true;\n    }\n\n//用随机逼近法求解子集和\n    std::sort(applicable_groups.begin(), applicable_groups.end(), descending);\n    std::vector<char> vfBest;\n    CAmount nBest;\n\n    ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue, vfBest, nBest);\n    if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE) {\n        ApproximateBestSubset(applicable_groups, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);\n    }\n\n//如果我们有一个更大的硬币（或者随机近似没有找到一个好的解决方案，\n//或者下一个更大的硬币更近），把更大的硬币还给我\n    if (lowest_larger &&\n        ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || lowest_larger->m_value <= nBest)) {\n        util::insert(setCoinsRet, lowest_larger->m_outputs);\n        nValueRet += lowest_larger->m_value;\n    } else {\n        for (unsigned int i = 0; i < applicable_groups.size(); i++) {\n            if (vfBest[i]) {\n                util::insert(setCoinsRet, applicable_groups[i].m_outputs);\n                nValueRet += applicable_groups[i].m_value;\n            }\n        }\n\n        if (LogAcceptCategory(BCLog::SELECTCOINS)) {\n            /*打印（bclog:：selectcoins，“selectcoins（）最佳子集：”）；/*续*/\n            for（unsigned int i=0；i<applicable_groups.size（）；i++）\n                如果（vfbest[i]）；\n                    logprint（bclog:：selectcoins，“%s”，formatmoney（适用的_groups[i].m_value））；/*续*/\n\n                }\n            }\n            LogPrint(BCLog::SELECTCOINS, \"total %s\\n\", FormatMoney(nBest));\n        }\n    }\n\n    return true;\n}\n\n/*************************************************************************\n\n 输出组\n\n *************************************************************************/\n\n\nvoid OutputGroup::Insert(const CInputCoin& output, int depth, bool from_me, size_t ancestors, size_t descendants) {\n    m_outputs.push_back(output);\n    m_from_me &= from_me;\n    m_value += output.effective_value;\n    m_depth = std::min(m_depth, depth);\n//这里的祖先表达了新硬币最终拥有的祖先数量，也就是说\n//总和，而不是最大值；在多个输入的情况下，这将高估\n//有共同的祖先\n    m_ancestors += ancestors;\n//后代是从上一个祖先看到的计数，而不是从上一个祖先看到的后代。\n//硬币本身；因此，这个值被计算为最大值，而不是总和。\n    m_descendants = std::max(m_descendants, descendants);\n    effective_value = m_value;\n}\n\nstd::vector<CInputCoin>::iterator OutputGroup::Discard(const CInputCoin& output) {\n    auto it = m_outputs.begin();\n    while (it != m_outputs.end() && it->outpoint != output.outpoint) ++it;\n    if (it == m_outputs.end()) return it;\n    m_value -= output.effective_value;\n    effective_value -= output.effective_value;\n    return m_outputs.erase(it);\n}\n\nbool OutputGroup::EligibleForSpending(const CoinEligibilityFilter& eligibility_filter) const\n{\n    return m_depth >= (m_from_me ? eligibility_filter.conf_mine : eligibility_filter.conf_theirs)\n        && m_ancestors <= eligibility_filter.max_ancestors\n        && m_descendants <= eligibility_filter.max_descendants;\n}\n", "meta": {"hexsha": "3507a5dccb79d0c898925168fcd5285d7ddda69d", "size": 10966, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/wallet/coinselection.cpp", "max_stars_repo_name": "yinchengtsinghua/BitCoinCppChinese", "max_stars_repo_head_hexsha": "76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:36:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T11:20:25.000Z", "max_issues_repo_path": "src/wallet/coinselection.cpp", "max_issues_repo_name": "yinchengtsinghua/BitCoinCppChinese", "max_issues_repo_head_hexsha": "76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/wallet/coinselection.cpp", "max_forks_repo_name": "yinchengtsinghua/BitCoinCppChinese", "max_forks_repo_head_hexsha": "76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-01-24T07:48:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T13:34:44.000Z", "avg_line_length": 32.1583577713, "max_line_length": 191, "alphanum_fraction": 0.630494255, "num_tokens": 3898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030761371503, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.23023564341510078}}
{"text": "/************************************************************************\n *                                                                      *\n * Copyright (C) 2012 OVSM/IPGP                                         *\n *                                                                      *\n * This program is free software: you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation, either version 3 of the License, or    *\n * (at your option) any later version.                                  *\n *                                                                      *\n * This program is distributed in the hope that it will be useful,      *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of       *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *\n * GNU General Public License for more details.                         *\n *                                                                      *\n * This program is part of 'Projet TSUAREG - INTERREG IV Caraïbes'.     *\n * It has been co-financed by the European Union and le Ministère de    *\n * l'Ecologie, du Développement Durable, des Transports et du Logement. *\n *                                                                      *\n ************************************************************************/\n\n\n#define SEISCOMP_COMPONENT Md\n\n#include \"md.h\"\n#include \"l4c1hz.h\"\n#include <seiscomp3/processing/waveformprocessor.h>\n#include <seiscomp3/math/filter/stalta.h>\n#include <seiscomp3/math/filter/iirfilter.h>\n#include <seiscomp3/math/filter/butterworth.h>\n#include <seiscomp3/logging/log.h>\n#include <seiscomp3/core/strings.h>\n#include <seiscomp3/seismology/magnitudes.h>\n#include <seiscomp3/math/mean.h>\n#include <seiscomp3/math/filter/seismometers.h>\n#include <seiscomp3/math/restitution/fft.h>\n#include <seiscomp3/math/geo.h>\n#include <iostream>\n#include <boost/bind.hpp>\n#include <unistd.h>\n\n\n#define _DEPTH_MAX 200.0\n#define _SIGNAL_WINDOW_END 30.0\n#define _LINEAR_CORRECTION 1.0\n#define _OFFSET 0.0\n#define _SNR_MIN 1.2\n#define _DELTA_MAX 400.0\n#define _MD_MAX 5.0\n#define _FMA -0.87\n#define _FMB 2.0\n#define _FMD 0.0035\n#define _FMF 0.0\n#define _FMZ 0.0\n#define _STACOR 0.0 //! not fully implemented !\n/**\n * Seismometer selection\n * 1 for Wood-Anderson\n * 2 for Seismometer 5 sec\n * 3 for WWSSN LP ? filter\n * 4 for WWSSN SP? filter\n * 5 for Generic Seismometer ? filter\n * 6 for Butterworth Low Pass ? filter\n * 7 for Butterwoth High Pass ? filter\n * 8 for Butterworth Band Pass ? filter\n * 9 for L4C 1Hz seismometer\n **/\n#define _SEISMO 9\n#define _BUTTERWORTH \"\"\n\nADD_SC_PLUGIN(\"Md duration magnitude plugin\", \"IPGP <www.ipgp.fr>\", 0, 1, 1)\n\n#define AMPTAG \"[Amp] [Md]\"\n#define MAGTAG \"[Mag] [Md]\"\n\n\nusing namespace Seiscomp;\nusing namespace Seiscomp::Math;\nusing namespace Seiscomp::Processing;\n\n\n/*----[ AMPLITUDE PROCESSOR CLASS ]----*/\n\nIMPLEMENT_SC_CLASS_DERIVED(AmplitudeProcessor_Md, AmplitudeProcessor, \"AmplitudeProcessor_Md\");\nREGISTER_AMPLITUDEPROCESSOR(AmplitudeProcessor_Md, \"Md\");\n\nstruct ampConfig {\n\n\t\tdouble DEPTH_MAX;\n\t\tdouble SIGNAL_WINDOW_END;\n\t\tdouble SNR_MIN;\n\t\tdouble DELTA_MAX;\n\t\tdouble MD_MAX;\n\t\tdouble FMA;\n\t\tdouble FMB;\n\t\tdouble FMD;\n\t\tdouble FMF;\n\t\tdouble FMZ;\n\t\tdouble STACOR;\n\t\tint SEISMO;\n\t\tstd::string BUTTERWORTH;\n};\nampConfig aFile;\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nAmplitudeProcessor_Md::AmplitudeProcessor_Md() :\n\t\tAmplitudeProcessor(\"Md\") {\n\n\tsetSignalStart(0.);\n\tsetSignalEnd(150.);\n\tsetMinSNR(aFile.SNR_MIN);\n\tsetMaxDist(8);\n\t_computeAbsMax = true;\n\t_isInitialized = false;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nAmplitudeProcessor_Md::AmplitudeProcessor_Md(const Core::Time& trigger) :\n\t\tAmplitudeProcessor(trigger, \"Md\") {\n\n\tsetSignalStart(0.);\n\tsetSignalEnd(150.);\n\tsetMinSNR(aFile.SNR_MIN);\n\tsetMaxDist(8);\n\t_computeAbsMax = true;\n\t_isInitialized = false;\n\n\tcomputeTimeWindow();\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nbool AmplitudeProcessor_Md::setup(const Settings& settings) {\n\n\tif ( !AmplitudeProcessor::setup(settings) )\n\t\treturn false;\n\n\tbool isButterworth = false;\n\ttry {\n\t\taFile.SEISMO = settings.getInt(\"md.seismo\");\n\t\tstd::string type;\n\t\tswitch ( aFile.SEISMO ) {\n\t\t\tcase 1:\n\t\t\t\ttype = \"WoodAnderson\";\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\ttype = \"Seismo5sec\";\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\ttype = \"WWSSN LP\";\n\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\ttype = \"WWSSN SP\";\n\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\ttype = \"Generic Seismometer\";\n\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\ttype = \"Butterworth Low Pass\";\n\t\t\t\tisButterworth = true;\n\t\t\tbreak;\n\t\t\tcase 7:\n\t\t\t\ttype = \"Butterworth High Pass\";\n\t\t\t\tisButterworth = true;\n\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\ttype = \"Butterworth Band Pass\";\n\t\t\t\tisButterworth = true;\n\t\t\tbreak;\n\t\t\tcase 9:\n\t\t\t\ttype = \"L4C 1Hz Seismometer\";\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t\tSEISCOMP_DEBUG(\"%s sets SEISMO to  %s [%s.%s]\", AMPTAG, type.c_str(),\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\taFile.SEISMO = _SEISMO;\n\t\tSEISCOMP_ERROR(\"%s can not read SEISMO value from configuration file [%s.%s]\", AMPTAG,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\tif ( isButterworth == true ) {\n\t\ttry {\n\t\t\taFile.BUTTERWORTH = settings.getString(\"md.butterworth\");\n\t\t\tSEISCOMP_DEBUG(\"%s sets Butterworth filter to  %s [%s.%s]\", AMPTAG,\n\t\t\t    aFile.BUTTERWORTH.c_str(), settings.networkCode.c_str(),\n\t\t\t    settings.stationCode.c_str());\n\t\t}\n\t\tcatch ( ... ) {\n\t\t\taFile.BUTTERWORTH = _BUTTERWORTH;\n\t\t\tSEISCOMP_ERROR(\"%s can not read Butterworth filter value from configuration file [%s.%s]\", AMPTAG,\n\t\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t\t}\n\t}\n\n\ttry {\n\t\taFile.DEPTH_MAX = settings.getDouble(\"md.depthmax\");\n\t\tSEISCOMP_DEBUG(\"%s sets DEPTH MAX to  %.2f [%s.%s]\", AMPTAG, aFile.DEPTH_MAX,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\taFile.DEPTH_MAX = _DEPTH_MAX;\n\t\tSEISCOMP_ERROR(\"%s can not read DEPTH MAX value from configuration file [%s.%s]\", AMPTAG,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\taFile.DELTA_MAX = settings.getDouble(\"md.deltamax\");\n\t\tSEISCOMP_DEBUG(\"%s sets DELTA MAX to  %.2f [%s.%s]\", AMPTAG, aFile.DELTA_MAX,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\taFile.DELTA_MAX = _DELTA_MAX;\n\t\tSEISCOMP_ERROR(\"%s can not read DELTA MAX value from configuration file [%s.%s]\", AMPTAG,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\taFile.SNR_MIN = settings.getDouble(\"md.snrmin\");\n\t\tSEISCOMP_DEBUG(\"%s sets SNR MIN to  %.2f [%s.%s]\", AMPTAG, aFile.SNR_MIN,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\taFile.SNR_MIN = _SNR_MIN;\n\t\tSEISCOMP_ERROR(\"%s can not read SNR MIN value from configuration file [%s.%s]\", AMPTAG,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\taFile.MD_MAX = settings.getDouble(\"md.mdmax\");\n\t\tSEISCOMP_DEBUG(\"%s sets MD MAX to  %.2f [%s.%s]\", AMPTAG, aFile.MD_MAX,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\taFile.MD_MAX = _MD_MAX;\n\t\tSEISCOMP_ERROR(\"%s can not read MD MAX value from configuration file [%s.%s]\", AMPTAG,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\taFile.FMA = settings.getDouble(\"md.fma\");\n\t\tSEISCOMP_DEBUG(\"%s sets FMA to  %.4f [%s.%s]\", AMPTAG, aFile.FMA,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\taFile.FMA = _FMA;\n\t\tSEISCOMP_ERROR(\"%s can not read FMA value from configuration file [%s.%s]\", AMPTAG,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\taFile.FMB = settings.getDouble(\"md.fmb\");\n\t\tSEISCOMP_DEBUG(\"%s sets FMB to  %.4f [%s.%s]\", AMPTAG, aFile.FMB,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\taFile.FMB = _FMB;\n\t\tSEISCOMP_ERROR(\"%s can not read FMB value from configuration file [%s.%s]\", AMPTAG,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\taFile.FMD = settings.getDouble(\"md.fmd\");\n\t\tSEISCOMP_DEBUG(\"%s sets FMD to  %.4f [%s.%s]\", AMPTAG, aFile.FMD,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\taFile.FMD = _FMD;\n\t\tSEISCOMP_ERROR(\"%s can not read FMD value from configuration file [%s.%s]\", AMPTAG,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\taFile.FMF = settings.getDouble(\"md.fmf\");\n\t\tSEISCOMP_DEBUG(\"%s sets FMF to  %.4f [%s.%s]\", AMPTAG, aFile.FMF,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\taFile.FMF = _FMF;\n\t\tSEISCOMP_ERROR(\"%s can not read FMF value from configuration file [%s.%s]\", AMPTAG,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\taFile.FMZ = settings.getDouble(\"md.fmz\");\n\t\tSEISCOMP_DEBUG(\"%s sets FMZ to  %.4f [%s.%s]\", AMPTAG, aFile.FMZ,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\taFile.FMZ = _FMZ;\n\t\tSEISCOMP_ERROR(\"%s can not read FMZ value from configuration file [%s.%s]\",\n\t\t    AMPTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\t_isInitialized = true;\n\n\treturn true;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nvoid AmplitudeProcessor_Md::initFilter(double fsamp) {\n\n\tif ( !_enableResponses ) {\n\n\t\tSEISCOMP_DEBUG(\"Using custom responses\");\n\n\t\tMath::Filtering::InPlaceFilter<double>* f;\n\t\tswitch ( aFile.SEISMO ) {\n\t\t\tcase 1:\n\t\t\t\tAmplitudeProcessor::setFilter(new Filtering::IIR::WoodAndersonFilter<\n\t\t\t\t        double>(Velocity));\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tAmplitudeProcessor::setFilter(new Filtering::IIR::Seismometer5secFilter<\n\t\t\t\t        double>(Velocity));\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tAmplitudeProcessor::setFilter(new Filtering::IIR::WWSSN_LP_Filter<\n\t\t\t\t        double>(Velocity));\n\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tAmplitudeProcessor::setFilter(new Filtering::IIR::WWSSN_SP_Filter<\n\t\t\t\t        double>(Velocity));\n\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tAmplitudeProcessor::setFilter(new Filtering::IIR::GenericSeismometer<\n\t\t\t\t        double>(Velocity));\n\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\tf = new Math::Filtering::IIR::ButterworthLowpass<double>(3, 1, 15);\n\t\t\t\tAmplitudeProcessor::setFilter(f);\n\t\t\tbreak;\n\t\t\tcase 7:\n\t\t\t\tf = new Math::Filtering::IIR::ButterworthHighpass<double>(3, 1, 15);\n\t\t\t\tAmplitudeProcessor::setFilter(f);\n\t\t\tbreak;\n\t\t\tcase 8:\n\t\t\t\tf = new Math::Filtering::IIR::ButterworthBandpass<double>(3, 1, 15, 1, true);\n\t\t\t\tAmplitudeProcessor::setFilter(f);\n\t\t\tbreak;\n\t\t\tcase 9:\n\t\t\t\tAmplitudeProcessor::setFilter(new Filtering::IIR::L4C_1Hz_Filter<\n\t\t\t\t        double>(Velocity));\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tSEISCOMP_ERROR(\"%s can not initialize the chosen filter, \"\n\t\t\t\t\t\"please review your configuration file\", AMPTAG);\n\t\t\tbreak;\n\t\t}\n\t}\n\telse\n\t\tAmplitudeProcessor::setFilter(NULL);\n\n\tAmplitudeProcessor::initFilter(fsamp);\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nint AmplitudeProcessor_Md::capabilities() const {\n\treturn MeasureType;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nAmplitudeProcessor::IDList\nAmplitudeProcessor_Md::capabilityParameters(Capability cap) const {\n\n\tif ( cap == MeasureType ) {\n\t\tIDList params;\n\t\tparams.push_back(\"AbsMax\");\n\t\tparams.push_back(\"MinMax\");\n\t\treturn params;\n\t}\n\n\treturn AmplitudeProcessor::capabilityParameters(cap);\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nbool AmplitudeProcessor_Md::setParameter(Capability cap,\n                                         const std::string& value) {\n\n\tif ( cap == MeasureType ) {\n\n\t\tif ( value == \"AbsMax\" ) {\n\t\t\t_computeAbsMax = true;\n\t\t\treturn true;\n\t\t}\n\t\telse if ( value == \"MinMax\" ) {\n\t\t\t_computeAbsMax = false;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\treturn AmplitudeProcessor::setParameter(cap, value);\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nbool AmplitudeProcessor_Md::deconvolveData(Response* resp,\n                                           DoubleArray& data,\n                                           int numberOfIntegrations) {\n\tif ( numberOfIntegrations < -1 )\n\t\treturn false;\n\n\tSEISCOMP_DEBUG(\"Inside deconvolve function\");\n\n\tdouble m, n;\n\tMath::Restitution::FFT::TransferFunctionPtr tf =\n\t\tresp->getTransferFunction(numberOfIntegrations < 0 ? 0 : numberOfIntegrations);\n\n\tif ( !tf )\n\t\treturn false;\n\n\tMath::GroundMotion gm;\n\n\tif ( numberOfIntegrations < 0 )\n\t\tgm = Math::Displacement;\n\telse\n\t\tgm = Math::Velocity;\n\n\tMath::Restitution::FFT::TransferFunctionPtr cascade;\n\tMath::SeismometerResponse::WoodAnderson woodAndersonResp(gm);\n\tMath::SeismometerResponse::Seismometer5sec seis5sResp(gm);\n\tMath::SeismometerResponse::L4C_1Hz l4c1hzResp(gm);\n\n\tMath::Restitution::FFT::PolesAndZeros woodAnderson(woodAndersonResp);\n\tMath::Restitution::FFT::PolesAndZeros seis5sec(seis5sResp);\n\tMath::Restitution::FFT::PolesAndZeros l4c1hz(l4c1hzResp);\n\n\tSEISCOMP_DEBUG(\"SEISMO = %d\", aFile.SEISMO);\n\n\tswitch ( aFile.SEISMO ) {\n\t\tcase 1:\n\t\t\tcascade = *tf / woodAnderson;\n\t\tbreak;\n\t\tcase 2:\n\t\t\tcascade = *tf / seis5sec;\n\t\tbreak;\n\t\tcase 9:\n\t\t\tSEISCOMP_INFO(\"%s Applying filter L4C 1Hz to data\", AMPTAG);\n\t\t\tcascade = *tf / l4c1hz;\n\t\tbreak;\n\t\tdefault:\n\t\t\tcascade = tf;\n\t\t\tSEISCOMP_INFO(\"%s No seismometer specified, no signal reconvolution performed\", AMPTAG);\n\t\t\treturn false;\n\t\tbreak;\n\t}\n\n\t// Remove linear trend\n\tMath::Statistics::computeLinearTrend(data.size(), data.typedData(), m, n);\n\tMath::Statistics::detrend(data.size(), data.typedData(), m, n);\n\n\treturn Math::Restitution::transformFFT(data.size(), data.typedData(),\n\t    _stream.fsamp, cascade.get(), _config.respTaper, _config.respMinFreq,\n\t    _config.respMaxFreq);\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nbool AmplitudeProcessor_Md::computeAmplitude(const DoubleArray& data, size_t i1,\n                                             size_t i2, size_t si1, size_t si2,\n                                             double offset, AmplitudeIndex* dt,\n                                             AmplitudeValue* amplitude,\n                                             double* period, double* snr) {\n\n\tdouble amax, Imax, ofs_sig, amp_sig;\n\tDoubleArrayPtr d;\n\n\tif ( *snr < aFile.SNR_MIN )\n\t\tSEISCOMP_DEBUG(\"%s computed SNR is under configured SNR MIN\", AMPTAG);\n\n\tif ( _computeAbsMax ) {\n\t\tsize_t imax = find_absmax(data.size(), data.typedData(), si1, si2, offset);\n\t\tamax = fabs(data[imax] - offset);\n\t\tdt->index = imax;\n\t}\n\telse {\n\t\tint lmin, lmax;\n\t\tfind_minmax(lmin, lmax, data.size(), data.typedData(), si1, si2, offset);\n\t\tamax = data[lmax] - data[lmin];\n\t\tdt->index = (lmin + lmax) * 0.5;\n\t\tdt->begin = lmin - dt->index;\n\t\tdt->end = lmax - dt->index;\n\t}\n\n\tImax = dt->index;\n\n\tSEISCOMP_DEBUG(\"%s Amplitude max: %.2f\", AMPTAG, amax);\n\n\t//! searching for Coda second by second through the end of the window\n\t//! TODO: elevate accuracy by using a nanometers scale (maybe)\n\tunsigned int i = si1;\n\tbool hasEndSignal = false;\n\tdouble calculatedSnr = -1;\n\n\tfor (i = (int) Imax; i < i2; i = i + 1 * (int) _stream.fsamp) {\n\n\t\tint window_end = i + 1 * (int) _stream.fsamp;\n\t\td = static_cast<DoubleArray*>(data.slice(i, window_end));\n\n\t\t//! computes pre-arrival offset\n\t\tofs_sig = d->median();\n\n\t\t//! computes rms after removing offset\n\t\tamp_sig = 2 * d->rms(ofs_sig);\n\n\t\tif ( amp_sig / *_noiseAmplitude <= aFile.SNR_MIN ) {\n\t\t\tSEISCOMP_DEBUG(\"%s End of signal found! (%.2f <= %.2f)\", AMPTAG,\n\t\t\t    (amp_sig / *_noiseAmplitude), aFile.SNR_MIN);\n\t\t\thasEndSignal = true;\n\t\t\tcalculatedSnr = amp_sig / *_noiseAmplitude;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif ( !hasEndSignal ) {\n\t\tSEISCOMP_ERROR(\"%s SNR stayed over configured SNR_MIN! (%.2f > %.2f), \"\n\t\t\t\"skipping magnitude calculation for this station\", AMPTAG,\n\t\t    calculatedSnr, aFile.SNR_MIN);\n\t\treturn false;\n\t}\n\n\tdt->index = i;\n\n\t//amplitude->value = 2 * amp_sig; //! actually it would have to be max. peak-to-peak\n\tamplitude->value = amp_sig;\n\n\tif ( _streamConfig[_usedComponent].gain != 0.0 )\n\t\tamplitude->value /= _streamConfig[_usedComponent].gain;\n\telse {\n\t\tsetStatus(MissingGain, 0.0);\n\t\treturn false;\n\t}\n\n\t// Convert m/s to nm/s\n\tamplitude->value *= 1.E09;\n\n\t*period = i - i1 + (_config.signalBegin * _stream.fsamp);\n\n\tSEISCOMP_DEBUG(\"%s calculated event amplitude = %.2f\", AMPTAG, amplitude->value);\n\tSEISCOMP_DEBUG(\"%s calculated signal end at %.2f ms from P phase\", AMPTAG, *period);\n\n\treturn true;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\ndouble AmplitudeProcessor_Md::timeWindowLength(double distance_deg) const {\n\n\tif ( !_isInitialized ) {\n\n\t\taFile.MD_MAX = _MD_MAX;\n\t\taFile.FMA = _FMA;\n\t\taFile.FMZ = _FMZ;\n\t\taFile.DEPTH_MAX = _DEPTH_MAX;\n\t\taFile.STACOR = _STACOR;\n\t\taFile.FMD = _FMD;\n\t\taFile.FMB = _FMB;\n\t\taFile.FMF = _FMF;\n\t\taFile.SNR_MIN = _SNR_MIN;\n\t\taFile.DELTA_MAX = _DELTA_MAX;\n\t\taFile.SIGNAL_WINDOW_END = _SIGNAL_WINDOW_END;\n\t\taFile.SEISMO = _SEISMO;\n\t\taFile.BUTTERWORTH = _BUTTERWORTH;\n\t}\n\n\tdouble distance_km = Math::Geo::deg2km(distance_deg);\n\tdouble windowLength = (aFile.MD_MAX - aFile.FMA - (aFile.FMZ * aFile.DEPTH_MAX)\n\t        - aFile.STACOR - (aFile.FMD * distance_km)) / (aFile.FMB + aFile.FMF);\n\n\twindowLength = pow(10, windowLength) + aFile.SIGNAL_WINDOW_END;\n\tSEISCOMP_DEBUG(\"%s Requesting stream of %.2fsec for current station\", AMPTAG, windowLength);\n\n\treturn windowLength;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n/*----[ END OF AMPLITUDE PROCESSOR CLASS ]----*/\n\n\n\n\n/*----[ MAGNITUDE PROCESSOR CLASS ]----*/\n\nIMPLEMENT_SC_CLASS_DERIVED(MagnitudeProcessor_Md, MagnitudeProcessor, \"MagnitudeProcessor_Md\");\nREGISTER_MAGNITUDEPROCESSOR(MagnitudeProcessor_Md, \"Md\");\n\nstruct magConfig {\n\n\t\tdouble DEPTH_MAX;\n\t\tdouble LINEAR_CORRECTION;\n\t\tdouble OFFSET;\n\t\tdouble DELTA_MAX;\n\t\tdouble MD_MAX;\n\t\tdouble FMA;\n\t\tdouble FMB;\n\t\tdouble FMD;\n\t\tdouble FMF;\n\t\tdouble FMZ;\n\t\tdouble STACOR;\n};\nmagConfig mFile;\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nMagnitudeProcessor_Md::MagnitudeProcessor_Md() :\n\t\tMagnitudeProcessor(\"Md\") {\n\n\t_linearCorrection = mFile.LINEAR_CORRECTION;\n\t_constantCorrection = mFile.OFFSET;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nbool MagnitudeProcessor_Md::setup(const Settings& settings) {\n\n\ttry {\n\t\tmFile.DELTA_MAX = settings.getDouble(\"md.deltamax\");\n\t\tSEISCOMP_DEBUG(\"%s sets DELTA MAX to  %.2f [%s.%s]\", MAGTAG, mFile.DELTA_MAX,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.DELTA_MAX = _DELTA_MAX;\n\t\tSEISCOMP_ERROR(\"%s can not read DELTA MAX value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\tmFile.DEPTH_MAX = settings.getDouble(\"md.depthmax\");\n\t\tSEISCOMP_DEBUG(\"%s sets DEPTH MAX to  %.2f [%s.%s]\", MAGTAG, mFile.DEPTH_MAX,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.DEPTH_MAX = _DEPTH_MAX;\n\t\tSEISCOMP_ERROR(\"%s can not read DEPTH MAX value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\tmFile.MD_MAX = settings.getDouble(\"md.mdmax\");\n\t\tSEISCOMP_DEBUG(\"%s sets MD MAX to  %.2f [%s.%s]\", MAGTAG, mFile.MD_MAX,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.MD_MAX = _MD_MAX;\n\t\tSEISCOMP_ERROR(\"%s can not read MD MAX value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\tmFile.LINEAR_CORRECTION = settings.getDouble(\"md.linearcorrection\");\n\t\tSEISCOMP_DEBUG(\"%s sets LINEAR CORRECTION to  %.2f [%s.%s]\", MAGTAG,\n\t\t    mFile.LINEAR_CORRECTION, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.LINEAR_CORRECTION = _LINEAR_CORRECTION;\n\t\tSEISCOMP_ERROR(\"%s can not read LINEAR CORRECTION value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\tmFile.OFFSET = settings.getDouble(\"md.offset\");\n\t\tSEISCOMP_DEBUG(\"%s sets OFFSET to  %.2f [%s.%s]\", MAGTAG, mFile.OFFSET,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.OFFSET = _OFFSET;\n\t\tSEISCOMP_ERROR(\"%s can not read OFFSET value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\tmFile.FMA = settings.getDouble(\"md.fma\");\n\t\tSEISCOMP_DEBUG(\"%s sets FMA to  %.4f [%s.%s]\", MAGTAG, mFile.FMA,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.FMA = _FMA;\n\t\tSEISCOMP_ERROR(\"%s can not read FMA value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\tmFile.FMB = settings.getDouble(\"md.fmb\");\n\t\tSEISCOMP_DEBUG(\"%s sets FMB to  %.4f [%s.%s]\", MAGTAG, mFile.FMB,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.FMB = _FMB;\n\t\tSEISCOMP_ERROR(\"%s can not read FMB value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\tmFile.FMD = settings.getDouble(\"md.fmd\");\n\t\tSEISCOMP_DEBUG(\"%s sets FMD to  %.4f [%s.%s]\", MAGTAG, mFile.FMD,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.FMD = _FMD;\n\t\tSEISCOMP_ERROR(\"%s can not read FMD value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\tmFile.FMF = settings.getDouble(\"md.fmf\");\n\t\tSEISCOMP_DEBUG(\"%s sets FMF to  %.4f [%s.%s]\", MAGTAG, mFile.FMF,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.FMF = _FMF;\n\t\tSEISCOMP_ERROR(\"%s can not read FMF value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\tmFile.FMZ = settings.getDouble(\"md.fmz\");\n\t\tSEISCOMP_DEBUG(\"%s sets FMZ to  %.4f [%s.%s]\", MAGTAG, mFile.FMZ,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.FMZ = _FMZ;\n\t\tSEISCOMP_ERROR(\"%s can not read FMZ value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\ttry {\n\t\tmFile.STACOR = settings.getDouble(\"md.stacor\");\n\t\tSEISCOMP_DEBUG(\"%s sets STACOR to  %.4f [%s.%s]\", MAGTAG, mFile.STACOR,\n\t\t    settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\tcatch ( ... ) {\n\t\tmFile.STACOR = _STACOR;\n\t\tSEISCOMP_ERROR(\"%s can not read STACOR value from configuration file [%s.%s]\",\n\t\t    MAGTAG, settings.networkCode.c_str(), settings.stationCode.c_str());\n\t}\n\n\treturn true;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n\n\n\n// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\nMagnitudeProcessor::Status\nMagnitudeProcessor_Md::computeMagnitude(double amplitude, double period,\n                                        double delta, double depth,\n                                        double& value) {\n\n\tdouble epdistkm;\n\tepdistkm = Math::Geo::deg2km(delta);\n\n\tSEISCOMP_DEBUG(\"%s --------------------------------\", MAGTAG);\n\tSEISCOMP_DEBUG(\"%s |    PARAMETERS   |    VALUE   |\", MAGTAG);\n\tSEISCOMP_DEBUG(\"%s --------------------------------\", MAGTAG);\n\tSEISCOMP_DEBUG(\"%s | delta max       | %.2f \", MAGTAG, mFile.DELTA_MAX);\n\tSEISCOMP_DEBUG(\"%s | depth max       | %.2f \", MAGTAG, mFile.DEPTH_MAX);\n\tSEISCOMP_DEBUG(\"%s | md max          | %.2f \", MAGTAG, mFile.MD_MAX);\n\tSEISCOMP_DEBUG(\"%s | fma             | %.4f \", MAGTAG, mFile.FMA);\n\tSEISCOMP_DEBUG(\"%s | fmb             | %.4f \", MAGTAG, mFile.FMB);\n\tSEISCOMP_DEBUG(\"%s | fmd             | %.4f \", MAGTAG, mFile.FMD);\n\tSEISCOMP_DEBUG(\"%s | fmf             | %.4f \", MAGTAG, mFile.FMF);\n\tSEISCOMP_DEBUG(\"%s | fmz             | %.4f \", MAGTAG, mFile.FMZ);\n\tSEISCOMP_DEBUG(\"%s | stacor          | %.4f \", MAGTAG, mFile.STACOR);\n\tSEISCOMP_DEBUG(\"%s --------------------------------\", MAGTAG);\n\tSEISCOMP_DEBUG(\"%s | (f-p)           | %.2f sec \", MAGTAG, period);\n\tSEISCOMP_DEBUG(\"%s | seismic depth   | %.2f km \", MAGTAG, depth);\n\tSEISCOMP_DEBUG(\"%s | epicenter dist  | %.2f km \", MAGTAG, epdistkm);\n\tSEISCOMP_DEBUG(\"%s --------------------------------\", MAGTAG);\n\n\tif ( amplitude <= 0. ) {\n\t\tvalue = 0;\n\t\tSEISCOMP_ERROR(\"%s calculated amplitude is wrong, \"\n\t\t\t\"no magnitude will be calculated\", MAGTAG);\n\t\treturn Error;\n\t}\n\n\tif ( (mFile.DELTA_MAX) < epdistkm ) {\n\t\tSEISCOMP_ERROR(\"%s epicenter distance is out of configured range, \"\n\t\t\t\"no magnitude will be calculated\", MAGTAG);\n\t\treturn DistanceOutOfRange;\n\t}\n\n\tvalue = mFile.FMA + mFile.FMB * log10(period) + (mFile.FMF * period)\n\t        + (mFile.FMD * epdistkm) + (mFile.FMZ * depth) + mFile.STACOR;\n\n\tif ( value > mFile.MD_MAX )\n\t\tSEISCOMP_WARNING(\"%s Calculated magnitude is beyond max Md value [value= %.2f]\",\n\t\t    MAGTAG, value);\n\n\treturn OK;\n}\n// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n/*----[ END OF MAGNITUDE PROCESSOR CLASS ]----*/\n\n\n", "meta": {"hexsha": "10225fd673e96ccf460606a66a940dadc96ca136", "size": 26170, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ipgp/plugins/magnitudes/md/md.cpp", "max_stars_repo_name": "CelsoReyes/seiscomp3", "max_stars_repo_head_hexsha": "ed9b984651c3b43132f12853bf392ae0dcde87b0", "max_stars_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ipgp/plugins/magnitudes/md/md.cpp", "max_issues_repo_name": "CelsoReyes/seiscomp3", "max_issues_repo_head_hexsha": "ed9b984651c3b43132f12853bf392ae0dcde87b0", "max_issues_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ipgp/plugins/magnitudes/md/md.cpp", "max_forks_repo_name": "CelsoReyes/seiscomp3", "max_forks_repo_head_hexsha": "ed9b984651c3b43132f12853bf392ae0dcde87b0", "max_forks_repo_licenses": ["Naumen", "Condor-1.1", "MS-PL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T08:13:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T08:13:27.000Z", "avg_line_length": 31.1918951132, "max_line_length": 101, "alphanum_fraction": 0.598509744, "num_tokens": 7262, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2302306262661209}}
{"text": "#include <iostream>\n#include <boost/bind.hpp>\n#include <boost/algorithm/string.hpp>\n#include \"../include/grasp_sampler/RRTFunction.h\"\n#include <string>\n#include <cstring>\n\nusing namespace std;\nusing namespace Eigen;\n\n#define REACHED 0\n#define ADVANCED 1\n#define TRAPPED -1\n\nbool RRT::solveRRT(Robotmodel& model, std::ostream& sout) {\n\n\t_model = model;\n\n\tnt_start._nodes.clear(); // NodeTree\n\tnt_goal._nodes.clear(); // NodeTree\n\n\tinitConfig.clear();// std::vector<double>\n\tDOF_weights.clear();// std::vector<double>\n\tint ActiveDoFs = dofSize;\n\tstep_size = 0.3 / M_PI *180.0;\n\tstd::string start_string[dofSize];\n\n\n\tfor (int i = 0; i < ActiveDoFs; i++) {\n\t\tinitConfig.push_back(qinit(i) * 180.0 / M_PI);\n\t\tDOF_weights.push_back(1.0);\n\t}\n\n\n\tauto start_node = std::make_shared<RRTNode>(initConfig);\n\n\tnt_start.addNode(start_node);\n\tnt_pointer = &nt_start;\n\n\t// mulitple seed\n\tfor (int i = 0; i < qgoals.size(); i++)\n\t{\n\t\tstd::vector<double> goalConfig; \n\t\tfor (int j = 0; j < ActiveDoFs; j++)\n\t\t{\n\t\t\tgoalConfig.push_back(qgoals[i][j] * 180.0 / M_PI);\n\t\t}\n\n\t\tauto goal_node = std::make_shared<RRTNode>(goalConfig);\n\n\t\tnt_goal.addNode(goal_node);\n\t}\n\n\tbool finished = false;\n\tint iter = 1;\n\n    std::vector<double> q_rand;\n    RRTNodePtr q_a_near;\n    std::vector<double> q_a_reached ;\n    RRTNodePtr q_b_near;\n    std::vector<double> q_b_reached ;\n\tint root_tree_index, goal_tree_index;\n\n\twhile (iter < 50) {\n\n\t\tnt_pointer = &nt_start;\t\t\t\t\t\t\t\t  //\t\t// start tree\n\t\tq_rand = generateRandomConfig();\n\t\tq_a_near = nt_pointer->getNearest(q_rand, DOF_weights);  \n\n\t\tq_a_reached = this->extendNode(q_rand, q_a_near);\n\n\t\tnt_pointer = &nt_goal;\n\t\tq_b_near = nt_pointer->getNearest(q_a_reached, DOF_weights); // random config�� ���� ����� c_tree�� ��� ã��\n\t\tq_b_reached = this->extendNode(q_a_reached, q_b_near); // near��� ���� random config�� Extend\n\n\t\tif (getEuclideanNorm(q_a_reached, q_b_reached, dofSize) < step_size)\n\t\t{\n\t\t\tnt_pointer = &nt_start; //\t\t// start tree\n\t\t\troot_tree_index = nt_pointer->getNearestIndex(q_a_reached, DOF_weights);\n\t\t\tnt_pointer = &nt_goal;\n\t\t\tgoal_tree_index = nt_pointer->getNearestIndex(q_b_reached, DOF_weights);\n\n\t\t\t// q_a_reached가 tree내에 있는 노드가 아니여서 불연속이 생김..\n\t\t\t//cout << \"t_turn \\t\" << t_turn << endl;\n\t\t\t//cout << q_a_reached[0] << \"\\t\" << q_a_reached[1] << \"\\t\" << q_a_reached[2] << \"\\t\" << q_a_reached[3] << \"\\t\" << q_a_reached[4] << \"\\t\" << q_a_reached[5] << \"\\t\" << q_a_reached[6] << endl;\n\t\t\t//cout << q_b_reached[0] << \"\\t\" << q_b_reached[1] << \"\\t\" << q_b_reached[2] << \"\\t\" << q_b_reached[3] << \"\\t\" << q_b_reached[4] << \"\\t\" << q_b_reached[5] << \"\\t\" << q_b_reached[6] << endl;\n\n\t\t\t//cout << getEuclideanNorm(q_a_reached, q_b_reached, dofSize) << endl;\n\t\t\t//cout << \"reached\" << endl;\n\t\t\tfinished = true;\n\n\t\t\tbreak;\n\t\t}\n\t\titer++;\n\t}\n\tif (finished) {\n\n\t\tpath = nt_start.getPathWithIndex(root_tree_index);\n\t\tvector<vector<double>> p2;\n\t\tp2 = nt_goal.getPathWithIndex(goal_tree_index);\n\n\n\t\treverse(p2.begin(), p2.end());\n\t\tpath.insert(path.end(), p2.begin(), p2.end());\n\n\t\tfor (int i = 0; i < path.size(); i++) {\n\t\t\tstd::vector<double> node = path[i];\n\t\t\tfor (int j = 0; j<node.size() - 1; j++)\n\t\t\t\tsout << node[j] << \",\";\n\n\t\t\tsout << node[node.size() - 1] << \"\\n\";\n\t\t}\n\t}\n\telse {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\nbool RRT::solveCRRT(Robotmodel& model, std::ostream& sout) {\n\t_model = model;\n\n\tnt_start._nodes.clear();\n\tnt_goal._nodes.clear();\n\n\tinitConfig.clear();\n\tDOF_weights.clear();\n\n\tint ActiveDoFs = dofSize;\n\tstep_size = 0.10/M_PI*180.0;\n\n\tstd::string start_string[dofSize];\n\n\tfor (int i = 0; i < ActiveDoFs; i++) {\n\t\tinitConfig.push_back(qinit(i) * 180.0 / M_PI);\n\t\tDOF_weights.push_back(1.0);\n\t}\n\n\n\tauto start_node = std::make_shared<RRTNode>(initConfig);\n\n\tnt_start.addNode(start_node);\n\tnt_pointer = &nt_start;\n\tt_turn = 1;\n\n\t// mulitple seed\n\tfor (int i = 0; i < qgoals.size(); i++)\n\t{\n\t\tstd::vector<double> goalConfig; \n\t\tfor (int j = 0; j < ActiveDoFs; j++)\n\t\t{\n\t\t\tgoalConfig.push_back(qgoals[i][j] * 180.0 / M_PI);\n\t\t}\n\t\tauto goal_node = std::make_shared<RRTNode>(goalConfig);\n\n\t\tnt_goal.addNode(goal_node);\n\t}\n\t/// single seed\n\t// RRTNode g(goal, 0); // ���� RRT\n\t// gTree.addNode(g);\n\n\n\tdx_from_init_to_goal.resize(6);\n\tVector3d pos_init = CalcBodyToBaseCoordinates(_model.model_, qinit, _model.body_id_vec.back(), _model.body_com_pos.back());\n\tMatrix3d Rot_init = CalcBodyWorldOrientation(_model.model_, qinit, _model.body_id_vec.back(), true).transpose();\n\tdx_from_init_to_goal.head(3) = refer_pos - pos_init;\n\tdx_from_init_to_goal.tail(3) = getPhi(Rot_init, refer_rot);\n\n\tdx_from_extend_to_goal.resize(6);\n\n\n\tbool finished = false;\n\tint iter = 1;\n    int a = 1;\n    std::vector<double> q_rand;\n    RRTNodePtr q_a_near;\n    std::vector<double> q_a_reached ;\n    RRTNodePtr q_b_near;\n    std::vector<double> q_b_reached ;\n\tint root_tree_index, goal_tree_index;\n\twhile (iter < 50000)\n\t{\n\t\tif (t_turn == 1)\n\t\t{\n\t\t\tnt_pointer = &nt_start;\t\t\t\t\t\t\t\t  //\t\t// start tree\n\t\t\tq_rand = generateRandomConfig(); //ConstrainedRandomConfig(_model);\t\t\t\t\t  // last node of goal tree(g2) or random config\n\n\t\t\t//cout << \"start tree -> goal tree\" << \"\\t\" <<t_turn << endl;\n\t\t\tq_a_near = nt_pointer->getNearest(q_rand, DOF_weights); // random config�� ���� ����� c_tree�� ��� ã��\n\t\t\tq_a_reached = this->extendNodeWithConstraints(q_rand, q_a_near);   // near��� ���� random config�� Extend\n\n\t\t\tnt_pointer = &nt_goal;\n\t\t\tq_b_near = nt_pointer->getNearest(q_a_reached, DOF_weights); // random config�� ���� ����� c_tree�� ��� ã��\n\t\t\t\n\t\t\t//cout << q_b_near->getConfiguration()[0] << \"\\t\" <<  q_b_near->getConfiguration()[1] << endl;\n\t\t\t//cout << \"goal tree -> start tree\" << endl;\n\t\t\tq_b_reached = this->extendNodeWithConstraints(q_a_reached, q_b_near); // near��� ���� random config�� Extend\n\n\t\t\tif (getEuclideanNorm(q_a_reached, q_b_reached, dofSize) < step_size)\n\t\t\t{\n\t\t\t\tnt_pointer = &nt_start;\t\t\t\t\t\t\t\t  //\t\t// start tree\n\t\t\t\troot_tree_index = nt_pointer->getNearestIndex(q_a_reached, DOF_weights);\n\t\t\t\tnt_pointer = &nt_goal;\n\t\t\t\tgoal_tree_index = nt_pointer->getNearestIndex(q_b_reached, DOF_weights);\n\n\t\t\t\t// q_a_reached가 tree내에 있는 노드가 아니여서 불연속이 생김..\n\t\t\t\tcout << \"t_turn \\t\" << t_turn << endl;\n\t\t\t\tcout << q_a_reached[0] << \"\\t\" << q_a_reached[1] << \"\\t\" << q_a_reached[2] << \"\\t\" << q_a_reached[3] << \"\\t\" << q_a_reached[4] << \"\\t\" << q_a_reached[5] << \"\\t\" << q_a_reached[6] << endl;\n\t\t\t\tcout << q_b_reached[0] << \"\\t\" << q_b_reached[1] << \"\\t\" << q_b_reached[2] << \"\\t\" << q_b_reached[3] << \"\\t\" << q_b_reached[4] << \"\\t\" << q_b_reached[5] << \"\\t\" << q_b_reached[6] << endl;\n\n\t\t\t\tcout << getEuclideanNorm(q_a_reached, q_b_reached, dofSize) << endl;\n\t\t\t\tcout << \"reached\" << endl;\n\t\t\t\ta = REACHED;\n\t\t\t\tfinished = true;\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t//t_turn = 2;\n\t\t}\n\t\t// if (t_turn == 2)\n\t\t// {\n\t\t// \tc_tree = &gTree;\t// goal tree\n\t\t// \tq_rand = RandomConfig();// ConstrainedRandomConfig(_model);\t\t\t\t\t  // last node of goal tree(g2) or random config\n\n\t\t// \t//cout << \"goal tree -> start _tree \" << \"\\t\" <<t_turn << endl;\n\t\t// \tq_a_near = c_tree->getNearest(q_rand, DOF_weights); // random config�� ���� ����� c_tree�� ��� ã��\n\n\t\t// \tq_a_reached = this->ConstrainedExtend(q_rand, q_a_near); // near��� ���� random config�� Extend\n\n\t\t// \tc_tree = &tree;\n\t\t// \tq_b_near = c_tree->getNearest(q_a_reached, DOF_weights); // random config�� ���� ����� c_tree�� ��� ã��\n\t\t// \t//cout << \"start tree -> goal tree\" << endl;\n\n\t\t// \tq_b_reached = this->ConstrainedExtend(q_a_reached, q_b_near); // near��� ���� random config�� Extend\n\t\t// \tif (getEuclideanNorm(q_a_reached, q_b_reached, dofSize) < step_size)\n\t\t// \t{\n\t\t// \t\tc_tree = &gTree;\t\t\t\t\t\t\t\t  //\t\t// start tree\n\t\t// \t\troot_tree_index = c_tree->getNearestIndex(q_a_reached, DOF_weights);\n\t\t// \t\tc_tree = &tree;\n\t\t// \t\tgoal_tree_index = c_tree->getNearestIndex(q_b_reached, DOF_weights);\n\n\t\t// \t\t// q_a_reached가 tree내에 있는 노드가 아니여서 불연속이 생김..\n\t\t// \t\tcout << \"t_turn \\t\" << t_turn << endl;\n\t\t// \t\tcout << q_a_reached[0] << \"\\t\" << q_a_reached[1] << \"\\t\" << q_a_reached[2] << \"\\t\" << q_a_reached[3] << \"\\t\" << q_a_reached[4] << \"\\t\" << q_a_reached[5] << \"\\t\" << q_a_reached[6] << endl;\n\t\t// \t\tcout << q_b_reached[0] << \"\\t\" << q_b_reached[1] << \"\\t\" << q_b_reached[2] << \"\\t\" << q_b_reached[3] << \"\\t\" << q_b_reached[4] << \"\\t\" << q_b_reached[5] << \"\\t\" << q_b_reached[6] << endl;\n\n\t\t// \t\tcout << getEuclideanNorm(q_a_reached, q_b_reached, dofSize) << endl;\n\t\t// \t\tcout << \"reached\" << endl;\n\t\t// \t\ta = REACHED;\n\t\t// \t\tfinished = true;\n\t\t// \t}\n\t\t// \tt_turn = 1;\n\n\t\t// }\n\t\titer++;\n\t}\n\n\tif (finished) {\n\n\t\tpath = nt_start.getPathWithIndex(root_tree_index);\n\t\tvector<vector<double>> p2;\n\t\tp2 = nt_goal.getPathWithIndex(goal_tree_index);\n\n\t\treverse(p2.begin(), p2.end());\n\t\tpath.insert(path.end(), p2.begin(), p2.end());\n\t\t\n\t\tstd::vector<double> end;\n\t\tend = path[path.size()-1];\n\n\t\tfor (int i = 0; i < path.size(); i++) {\n\t\t\tstd::vector<double> node = path[i];\n\t\t\tfor (int j = 0; j < node.size() - 1; j++){\n\t\t\t\tsout << node[j] << \",\";\n\t\t\t}\n\t\t\tsout << node[node.size() - 1] << \"\\n\";\n\n\t\t}//error\n\n\t}\n\telse {\n\n\t\treturn false;\n\t}\n\n\treturn true;\n}\nstd::vector<double> RRT::generateRandomConfig() {\n\n \tstd::vector<double> R;\n\tdo {\n\t\tfor (int i = 0; i < initConfig.size(); i++) {\n\t\t\tdouble jointrange = upper_limit(i) - lower_limit(i); // angle\n\t\t\tdouble r = ((double)rand() / (double)RAND_MAX)*jointrange;\n\t\t\tR.push_back(lower_limit(i) + r);\n\t\t}\n\t} while (R.size() != initConfig.size());\n\n\n\treturn R;\n}\n// std::vector<double> RRT::ConstrainedRandomConfig(Robotmodel model){\n// \tstd::vector<double> R;\n// \tstd::vector<double> R_project;\n\n// \twhile (R_project.empty())\n// \t{\n// \t\tdo\n// \t\t{\n// \t\t\tfor (int i = 0; i < start.size(); i++)\n// \t\t\t{\n// \t\t\t\tdouble jointrange = upper_limit(i) - lower_limit(i); // angle\n// \t\t\t\tdouble r = ((double)rand() / (double)RAND_MAX) * jointrange;\n// \t\t\t\tR.push_back(lower_limit(i) + r);\n// \t\t\t}\n// \t\t} while (R.size() != start.size());\n\n// \t\tR_project = ProjectConfigForRandomConfig(model, R);\n// \t}\n\n\n// \treturn R_project;\n//}\n\nstd::vector<double> RRT::extendNode(std::vector<double> &node, RRTNodePtr &near){\n\tstd::vector<double> qs, qs_old;\n\tqs.clear();\n\tqs_old.clear();\n\tfor (int i = 0; i < dofSize; i++)\n\t{\n\t\tqs.push_back(near->getConfiguration()[i]);\n\t\tqs_old.push_back(near->getConfiguration()[i]);\n\t}\n\n\twhile(true){\n\t\tif (getEuclideanNorm(node, qs, dofSize) < step_size)\n\t\t{\n\t\t\treturn qs;\n\t\t}\n\t\telse if (getEuclideanNorm(node, qs, dofSize) - getEuclideanNorm(qs_old, node, dofSize) > 0.0)\n\t\t{\n\t\t\treturn qs_old; // qs_old is close to node\n\t\t}\n\n\t\tfor (int i = 0; i < initConfig.size(); i++)\n\t\t{\n\t\t\tqs[i] = (qs[i] + min(step_size, getEuclideanNorm(node, qs, dofSize)) * (node[i] - qs[i]) / getEuclideanNorm(node, qs, dofSize));\n\t\t}\n\n\t\tif (!checkSelfCollision(_model, qs))\n\t\t{\n\t\t\tRRTNodePtr old = near;\n\t\t\tnear = std::make_shared<RRTNode>(qs, old);\n\t\t\tnt_pointer->addNode(near);\n\t\t\tqs_old = qs;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << \"collision config \\t\" << qs[0] << \"\\t\" <<qs[1] << \"\\t\" <<qs[2] << \"\\t\" <<qs[3] << \"\\t\" <<qs[4] << \"\\t\" <<qs[5] << \"\\t\" <<qs[6] << \"\\t\" << endl;\n\t\t\treturn qs_old;\n\t\t}\n\n\t}\n}\n\n\n\nstd::vector<double> RRT::extendNodeWithConstraints(std::vector<double> &node, RRTNodePtr &near)\n{\n\t// node = q_rand, near : q_near\n\tstd::vector<double> qs, qs_old;\n\tqs.clear();\n\tqs_old.clear();\n\tbool project_flag = false;\n\tint iteration_ = 0;\n\n\tfor (int i = 0; i < dofSize; i++)\n\t{\n\t\tqs.push_back(near->getConfiguration()[i]);\n\t\tqs_old.push_back(near->getConfiguration()[i]);\n\t}\n\t//cout << \"input\" << node[0] << \"\\t\" << node[1] << \"\\t\" << node[2] << \"\\t\" << node[3] << \"\\t\" << node[4] << \"\\t\" << node[5] << \"\\t\" << node[6] << endl;\n\t//cout << \"q_near\" << qs[0] << \"\\t\"<< qs[1] << \"\\t\"<< qs[2] << \"\\t\"<< qs[3] << \"\\t\"<< qs[4] << \"\\t\"<< qs[5] << \"\\t\"<< qs[6] <<endl;\n\twhile (true)\n\t{\n\t\tif (getEuclideanNorm(node, qs, dofSize) < step_size)\n\t\t{\n\t\t\treturn qs;\n\t\t}\n\t\telse if (getEuclideanNorm(node, qs, dofSize) - getEuclideanNorm(qs_old, node, dofSize) > 0.0)\n\t\t{\n\t\t\treturn qs_old; // qs_old is close to node\n\t\t}\n\n\t\tfor (int i = 0; i < initConfig.size(); i++) // Move from 'qs' to 'node'\n\t\t\tqs[i] = (qs[i] + min(step_size, getEuclideanNorm(node, qs, dofSize)) * (node[i] - qs[i]) / getEuclideanNorm(node, qs, dofSize));\n\n\t\t//cout << \"desired_dir\" <<qs[0] << \"\\t\" << qs[1] << \"\\t\" << qs[2] << \"\\t\" << qs[3] << \"\\t\" << qs[4] << \"\\t\" << qs[5] << \"\\t\" << qs[6] << endl;\n\n\t\t// qs_old : near / qs : extend\n\t\tqs = projectConfig(_model, qs_old, qs); // project qs onto constraint manifold\n\n\n\t\t// if (!qs.empty() && (std_norm(qs, qs_old, dofSize) > 3.0*step_size)){\n\t\t// \tcout << \"output1\" <<qs_old[0] << \"\\t\" << qs_old[1] << \"\\t\" << qs_old[2] << \"\\t\" << qs_old[3] << \"\\t\" << qs_old[4] << \"\\t\" << qs_old[5] << \"\\t\" << qs_old[6] << endl;\n\t\t// \tcout << \"output2\" <<qs[0] << \"\\t\" << qs[1] << \"\\t\" << qs[2] << \"\\t\" << qs[3] << \"\\t\" << qs[4] << \"\\t\" << qs[5] << \"\\t\" << qs[6] << endl;\n\n\t\t// \treturn qs_old;\n\t\t// }\n\n\t\tif (!qs.empty() && !checkExternalCollision(_model, qs))\n\t\t{\n\t\t\t//\t\t\tVectorXd q_project_(7);\n\t\t\t//cout << \"extend!\" << endl;\n\t\t\tRRTNodePtr old = near;\t\t   //qs_old\n\t\t\tnear = std::make_shared<RRTNode>(qs, old) ; //(new RRTNode(qs, old)); // qs : configuration, old : parent node\n\t\t\tnt_pointer->addNode(near);\n\n\t\t\tif((getEuclideanNorm(qs, qs_old, dofSize) < step_size / 2.0)){\n\t\t\t\treturn qs;\n\t\t\t}\n\t\t\tqs_old = qs;\n\n\t\t}\n\t\telse\n\t\t{\t\n\t\t\t//cout << \"qs_old\" << qs_old[0] << \"\\t\"<< qs_old[1] << \"\\t\"<< qs_old[2] << \"\\t\"<< qs_old[3] << \"\\t\"<< qs_old[4] << \"\\t\"<< qs_old[5] << \"\\t\"<< qs_old[6] <<endl;\n\t\t\t//cout << \"return NULL\" << endl;\n\t\t\t//cout << \"collision config \\t\" << qs[0] << \"\\t\" <<qs[1] << \"\\t\" <<qs[2] << \"\\t\" <<qs[3] << \"\\t\" <<qs[4] << \"\\t\" <<qs[5] << \"\\t\" <<qs[6] << \"\\t\" << endl;\n\n\t\t\treturn qs_old;\n\t\t}\n\t}\n}\nstd::vector<double> RRT::projectConfig(Robotmodel model, std::vector<double> qold, std::vector<double> &qs)\n{\n\tmodel.q.resize(dofSize);\n\n\t// Tc\n\tMatrix4d T0_c, T0_obj, Tc_obj;\n\tT0_c.setIdentity();\n\t//T0_c.topLeftCorner(3,3) = refer_rot;\n\tT0_c.topRightCorner(3, 1) = local_rot.transpose()*(refer_pos - local_pos); // global to local pos\n\n\tMatrixXd J_temp(6, dofSize), J(6, dofSize);\n\tVectorXd d_c(6), dx(6), q_error(dofSize), q_old(dofSize);\n\tdx.setZero();\n\tVector3d phi;\n\tVector3d s[3], v[3], w[3];\n\n\tfor (int i = 0; i < dofSize; i++)\n\t{ // deg -> rad\n\t\tqs[i] = qs[i] * M_PI / 180.0;\n\t\tqold[i] = qold[i] * M_PI / 180.0;\n\n\t\tq_old(i) = qold[i] * M_PI / 180.0;\n\t}\n\n\twhile (true)\n\t{\n\t\tfor (int i = 0; i < dofSize; i++)\n\t\t\tmodel.q(i) = qs[i];\n\n\t\tMatrix3d Rot_temp = CalcBodyWorldOrientation(model.model_, model.q, model.body_id_vec.back(), true).transpose();\n\t\tVector3d pos_temp = CalcBodyToBaseCoordinates(model.model_, model.q, model.body_id_vec.back(), model.body_com_pos.back()); // get position and rotation in EE frame;\n\n\t\tT0_obj.setIdentity();\n\t\tT0_obj.topLeftCorner(3, 3) = Rot_temp;\n\t\tT0_obj.topRightCorner(3, 1) = pos_temp;\n\t\tTc_obj = T0_c.inverse() * T0_obj;\n\n\t\td_c.head(3) = Tc_obj.topRightCorner(3, 1);\n\n\t\tMatrix3d Tc_obj_rot = refer_rot.transpose()*Rot_temp;\n\t\td_c(3) = atan2(Tc_obj_rot(2, 1), Tc_obj_rot(2, 2));\n\t\td_c(4) = -asin(Tc_obj_rot(2, 0));\n\t\td_c(5) = atan2(Tc_obj_rot(1, 0), Tc_obj_rot(0, 0));\n\n\t\t// 위치가 베이스 프레임 기준이 아니게 됨.\n\t\tfor (int i = 0; i < 6; i++)\n\t\t{\n\t\t\tif (d_c(i) > C(i, 0)) // max\n\t\t\t\tdx(i) = d_c(i) - C(i, 0);\n\t\t\telse if (d_c(i) < C(i, 1)) // min\n\t\t\t\tdx(i) = d_c(i) - C(i, 1) ;\n\t\t\telse\n\t\t\t\tdx(i) = 0.0;\n\t\t}\n\n\t\t// Algorithm 4 - line 3\n\t\tif (dx.norm() < 0.01)\n\t\t{\n\t\t\tVector3d q_old_pos = CalcBodyToBaseCoordinates(model.model_, q_old, model.body_id_vec.back(), model.body_com_pos.back());\n\t\t\tdouble dot_product;\n\n\t\t\tdx_from_extend_to_goal.head(3) = refer_pos - pos_temp;\n\t\t\tdx_from_extend_to_goal.tail(3) = getPhi(Rot_temp, refer_rot);\n\n\t\t\tdot_product = (dx_from_init_to_goal.head(3)/dx_from_init_to_goal.head(3).norm()).dot((pos_temp - q_old_pos) / (pos_temp - q_old_pos) .norm());\n\n\t\t\t// TODO : focal point - init position, final positon.  projected point is inside the ellipsoid\n\t\t\tif ((dx_from_init_to_goal.head(3).norm() < dx_from_extend_to_goal.head(3).norm()) || (dot_product < 0.0))\n\t\t\t{\n\t\t\t\tqs.clear();\n\t\t\t\treturn qs;\n\t\t\t}\n\n\t\t\tfor (int i = 0; i < dofSize; i++)\n\t\t\t{\n\t\t\t\tqs[i] = qs[i] / M_PI * 180.0;\n\t\t\t}\n\t\t\t\treturn qs; // convert rad to angle\n\t\t}\n\n\t\t// Algorithm 4 - line 4\n\t\tCalcPointJacobian6D(model.model_, model.q, model.body_id_vec.back(), model.body_com_pos.back(), J_temp, true);\n\t\tJ.topLeftCorner(3, dofSize) = J_temp.bottomLeftCorner(3, dofSize);\n\n\t\trpy(0) = atan2(Rot_temp(2, 1), Rot_temp(2, 2));\n\t\trpy(1) = -asin(Rot_temp(2, 0));\n\t\trpy(2) = atan2(Rot_temp(1, 0), Rot_temp(0, 0));\n\t\t\n\t\tE_rpy(0,0) = cos(rpy(2))/cos(rpy(1));\n\t\tE_rpy(0,1) = sin(rpy(2))/cos(rpy(1));\n\t\tE_rpy(0,2) = 0.0;\n\n\t\tE_rpy(1,0) = sin(rpy(2));\n\t\tE_rpy(1,1) = cos(rpy(2));\n\t\tE_rpy(1,2) = 0.0;\n\n\t\tE_rpy(2,0) = -cos(rpy(2))*sin(rpy(1))/cos(rpy(1));\n\t\tE_rpy(2,1) = sin(rpy(2))*sin(rpy(1))/cos(rpy(1));\n\t\tE_rpy(2,2) = 1.0;\n\t\tJ.bottomLeftCorner(3, dofSize) = E_rpy*J_temp.topLeftCorner(3, dofSize);\n\t\t\n\n\t\t// Algorithm 4 - line 5\n\t\tq_error = J.transpose() * (J * J.transpose()).inverse() * dx * 0.3;\n\n\t\t// Algorithm 4 -  line 6\n\t\tfor (int i = 0; i < dofSize; i++)\n\t\t\tqs[i] -= q_error(i);\n\n\t\t// Algorithm 4 - line 7 : stuck here\n\t\tif (!checkJointLimit(qs) || (getEuclideanNorm(qs, qold, dofSize) > 3.0*step_size/180.0*M_PI))\n\t\t{\n\t\t\t//cout << \"joint limit\" << \"\\t\" << qs[0]/M_PI*180.0<< \"\\t\" << qs[1]/M_PI*180.0<< \"\\t\" << qs[2]/M_PI*180.0<< \"\\t\" << qs[3]/M_PI*180.0<< \"\\t\" << qs[4]/M_PI*180.0<< \"\\t\" << qs[5]/M_PI*180.0<< \"\\t\" << qs[6]/M_PI*180.0 << endl;\n\t\t\tqs.clear();\n\t\t\treturn qs;\n\t\t\t// flag = false;\n\t\t\t// break;\n\t\t}\n\t}\n}\n\n// std::vector<double> RRT::ProjectConfigForRandomConfig(Robotmodel model, std::vector<double> &qs)\n// {\n// \tmodel.q.resize(dofSize);\n\n// \t// Tc\n// \tMatrix4d T0_c, T0_obj, Tc_obj;\n// \tT0_c.setIdentity();\n// \t//T0_c.topLeftCorner(3,3) = refer_rot;\n// \tT0_c.topRightCorner(3, 1) = local_rot*(refer_pos - local_pos); // global to local pos\n\n// \tMatrixXd J_temp(6, dofSize), J(6, dofSize);\n// \tVectorXd d_c(6), dx(6), q_error(dofSize);\n// \tdx.setZero();\n// \tVector3d phi;\n// \tVector3d s[3], v[3], w[3];\n\n// \tfor (int i = 0; i < dofSize; i++)\n// \t{ // deg -> rad\n// \t\tqs[i] = qs[i] * M_PI / 180.0;\n// \t}\n\n// \twhile (true)\n// \t{\n// \t\tfor (int i = 0; i < dofSize; i++)\n// \t\t\tmodel.q(i) = qs[i];\n\n// \t\tMatrix3d Rot_temp = CalcBodyWorldOrientation(model.model_, model.q, model.body_id_vec.back(), true).transpose();\n// \t\tVector3d pos_temp = CalcBodyToBaseCoordinates(model.model_, model.q, model.body_id_vec.back(), model.body_com_pos.back()); // get position and rotation in EE frame;\n\n// \t\tT0_obj.setIdentity();\n// \t\tT0_obj.topLeftCorner(3, 3) = Rot_temp;\n// \t\tT0_obj.topRightCorner(3, 1) = pos_temp;\n// \t\tTc_obj = T0_c.inverse() * T0_obj;\n\n// \t\td_c.head(3) = Tc_obj.topRightCorner(3, 1);\n\n// \t\tMatrix3d Tc_obj_rot = refer_rot.transpose()*Rot_temp;\n// \t\td_c(3) = atan2(Tc_obj_rot(2, 1), Tc_obj_rot(2, 2));\n// \t\td_c(4) = -asin(Tc_obj_rot(2, 0));\n// \t\td_c(5) = atan2(Tc_obj_rot(1, 0), Tc_obj_rot(0, 0));\n\n// \t\tfor (int i = 0; i < 6; i++)\n// \t\t{\n// \t\t\tif (d_c(i) > C(i, 0)) // max\n// \t\t\t\tdx(i) = d_c(i) - C(i, 0);\n// \t\t\telse if (d_c(i) < C(i, 1)) // min\n// \t\t\t\tdx(i) = d_c(i) - C(i, 1) ;\n// \t\t\telse\n// \t\t\t\tdx(i) = 0.0;\n// \t\t}\n\n// \t\t// Algorithm 4 - line 3\n// \t\tif (dx.norm() < 0.01)\n// \t\t{\n// \t\t\tdx_from_extend_to_goal.head(3) = refer_pos - pos_temp;\n// \t\t\tdx_from_extend_to_goal.tail(3) = getPhi(Rot_temp, refer_rot);\n\n// \t\t\tif (dx_from_init_to_goal.norm() < dx_from_extend_to_goal.norm()){\n// \t\t\t\tqs.clear();\n// \t\t\t\treturn qs;\n// \t\t\t}\n\n// \t\t\tfor (int i = 0; i < dofSize; i++)\n// \t\t\t{\n// \t\t\t\tqs[i] = qs[i] / M_PI * 180.0;\n// \t\t\t}\n// \t\t\t\treturn qs; // convert rad to angle\n// \t\t}\n\n// \t\t// Algorithm 4 - line 4\n// \t\tCalcPointJacobian6D(model.model_, model.q, model.body_id_vec.back(), model.body_com_pos.back(), J_temp, true);\n// \t\tJ.topLeftCorner(3, dofSize) = J_temp.bottomLeftCorner(3, dofSize);\n\n// \t\trpy(0) = atan2(Rot_temp(2, 1), Rot_temp(2, 2));\n// \t\trpy(1) = -asin(Rot_temp(2, 0));\n// \t\trpy(2) = atan2(Rot_temp(1, 0), Rot_temp(0, 0));\n\t\t\n// \t\tE_rpy(0,0) = cos(rpy(2))/cos(rpy(1));\n// \t\tE_rpy(0,1) = sin(rpy(2))/cos(rpy(1));\n// \t\tE_rpy(0,2) = 0.0;\n\n// \t\tE_rpy(1,0) = sin(rpy(2));\n// \t\tE_rpy(1,1) = cos(rpy(2));\n// \t\tE_rpy(1,2) = 0.0;\n\n// \t\tE_rpy(2,0) = -cos(rpy(2))*sin(rpy(1))/cos(rpy(1));\n// \t\tE_rpy(2,1) = sin(rpy(2))*sin(rpy(1))/cos(rpy(1));\n// \t\tE_rpy(2,2) = 1.0;\n// \t\tJ.bottomLeftCorner(3, dofSize) = E_rpy*J_temp.topLeftCorner(3, dofSize);\n\t\t\n\n// \t\t// Algorithm 4 - line 5\n// \t\tq_error = J.transpose() * (J * J.transpose()).inverse() * dx * 0.3;\n\n// \t\t// Algorithm 4 -  line 6\n// \t\tfor (int i = 0; i < dofSize; i++)\n// \t\t\tqs[i] -= q_error(i);\n\n// \t\t// Algorithm 4 - line 7 : stuck here\n// \t\tif (!OutsideJointLimit(qs))\n// \t\t{\n// \t\t\t//cout << \"joint limit\" << \"\\t\" << qs[0]/M_PI*180.0<< \"\\t\" << qs[1]/M_PI*180.0<< \"\\t\" << qs[2]/M_PI*180.0<< \"\\t\" << qs[3]/M_PI*180.0<< \"\\t\" << qs[4]/M_PI*180.0<< \"\\t\" << qs[5]/M_PI*180.0<< \"\\t\" << qs[6]/M_PI*180.0 << endl;\n// \t\t\tqs.clear();\n// \t\t\treturn qs;\n// \t\t\t// flag = false;\n// \t\t\t// break;\n// \t\t}\n// \t}\n// }\n\n\ndouble RRT::getDistance(std::vector<double> &a, std::vector<double> &b) {\n\n\t//Gets squared Euclidean Distance on C-Space between node and a given\n\tdouble accumulated = 0.0f;\n\tstd::vector<double> diff = b;\n\n\tfor (int i = 0; i< diff.size(); i++) {\n\t\tdiff[i] -= a[i];\n\t\t//double dif = _configuration[i] - (config)[i];\n\t\taccumulated += (diff[i] * diff[i] * DOF_weights[i] * DOF_weights[i]);\n\t}\n\treturn sqrt(accumulated);\n}\nbool RRT::smoothPath(std::ostream& sout, std::istream& sinput)\n{\n\tstd::string fullinput;\n\t//Parse input\n\twhile (sinput) {\n\t\tstd::string input;\n\t\tsinput >> input;\n\t\tfullinput += input;\n\t}\n\tint nSmooth = 5; // atoi(fullinput.c_str());\n\n\twhile (nSmooth) { // while(x) -> while( x != 0 )\n\t\tshortcutSmoothing();\n\t\tnSmooth--;\n\t}\n\t\n\tfor (int i = 0; i< path.size(); i++) {\n\t\tstd::vector<double> node = path[i];\n\t\tfor (int j = 0; j<node.size() - 1; j++) {\n\t\t\tsout << node[j] << \",\";\n\t\t}\n\t\tsout << node[node.size() - 1] << \"\\n\";\n\t}\n\n\treturn true;\n}\nbool RRT::shortcutSmoothing() {\n\tif (path.size() <= 2) return false;\n\tint i = ((double)rand() / RAND_MAX)*path.size();\n\tint j = ((double)rand() / RAND_MAX)*path.size();\n\twhile (abs(j - i)<2) {\n\t\ti = ((double)rand() / RAND_MAX)*path.size();\n\t\tj = ((double)rand() / RAND_MAX)*path.size();\n\t}\n\tif (j < i) { //make sure i is the smaller number\n\t\tint a = j;\n\t\tj = i;\n\t\ti = a;\n\t}\n\n\tif (checkTraj(path[i], path[j])) {\n\t\tpath.erase(path.begin() + i + 1, path.begin() + j);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool RRT::checkTraj(std::vector<double> &a, std::vector<double> &b) {\n\tstd::vector<double> u = getUnitVector(a, b); // a->b\n\tstd::vector<double> p = a;\n\twhile (p != b) {\n\t\tif (checkExternalCollision(_model, p)) { return false;\n\t\tbreak;\n\t\t}\n\t\tif (getDistance(p, b) < step_size / 2) {\n\t\t\tp = b;\n\t\t}\n\t\telse {\n\t\t\tfor (int i = 0; i < u.size(); i++) {\n\t\t\t\tp[i] += u[i] * step_size / 2;\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\nstd::vector<double> RRT::getUnitVector(std::vector<double> &a, std::vector<double> &b) {\n\n\t//Gets squared Euclidean Distance on C-Space between node and a given\n\tdouble accumulated = 0.0f;\n\tstd::vector<double> diff = b;\n\n\tfor (int i = 0; i< diff.size(); i++) {\n\t\tdiff[i] -= a[i];//double dif = _configuration[i] - (config)[i];\n\t\taccumulated += (diff[i] * diff[i] * DOF_weights[i] * DOF_weights[i]);\n\t}\n\taccumulated = sqrt(accumulated);\n\tfor (int i = 0; i < diff.size(); i++) {\n\t\tdiff[i] /= accumulated;\n\t}\n\treturn diff;\n}\nbool RRT::checkExternalCollision(Robotmodel model, std::vector<double> &config) {\n\tmodel.q.resize(dofSize);\n\tfor (int i = 0; i < dofSize; i++)\n\t\tmodel.q(i) = config[i] * M_PI / 180.0;\n\n\t// Update Box modeling for link\n\tfor (int i = 0; i < box_num_link; i++)\n\t{\n\t\tMatrix3d Rot_temp3 = Box_link[i].vRot * CalcBodyWorldOrientation(model.model_, model.q, model.body_id_vec[i], true).transpose();\n\t\tBox_link[i].vAxis[0] = Rot_temp3.col(0);\n\t\tBox_link[i].vAxis[1] = Rot_temp3.col(1);\n\t\tBox_link[i].vAxis[2] = Rot_temp3.col(2);\n\t\tBox_link[i].vPos = CalcBodyToBaseCoordinates(model.model_, model.q, model.body_id_vec[i], (Box_link[i].vCenter + model.body_com_pos[i]), true);\n\t}\n\n\tbool chk;\n\tif (box_num_obs == 0)\n\t{\n\t\tchk = false;\n\t\treturn chk;\n\t}\n\tfor (int i = 0; i < box_num_obs; i++)\n\t{\n\t\tfor (int j = 0; j < box_num_link; j++)\n\t\t{\n\t\t\tchk = checkOBBCollision(&Box_obs[i], &Box_link[j]);\n\t\t\tif (chk)\n\t\t\t{\n\t\t\t\t// cout << \"----------------Collision \\n\"\n\t\t\t\t// \t << i << \"\\t\" << j << \"\\t\" << chk << endl;\n\t\t\t\t// cout << Box_obs[i].vPos.transpose() << endl;\n\t\t\t\t// cout << Box_link[j].vPos.transpose() << endl;\n\t\t\t\t// //cout << CalcBodyToBaseCoordinates(model.model_, model.q, model.body_id_vec[j], Vector3d::Zero(), true).transpose() << endl;\n\t\t\t\t// cout << model.q(0) * 180.0 / M_PI << \"\\t\" << model.q(1) * 180.0 / M_PI << \"\\t\" << model.q(2) * 180.0 / M_PI << \"\\t\" << model.q(3) * 180.0 / M_PI << \"\\t\" << model.q(4) * 180.0 / M_PI << \"\\t\" << model.q(5) * 180.0 / M_PI << \"\\t\" << model.q(6) * 180.0 / M_PI << \"\\t\" << endl;\n\n\t\t\t\t//cout << i << \"\\t\" << j << \"\\t\" << chk << endl;\n\n\t\t\t\treturn chk;\n\t\t\t}\n\t\t\t//cout << \"collision\" << i << \"\\t\" << j << endl;\n\t\t}\n\t}\n\treturn chk;\n}\n\n\nbool RRT::checkSelfCollision(Robotmodel model, std::vector<double> &config) {\n\tmodel.q.resize(dofSize);\n\tfor (int i = 0; i < dofSize; i++)\n\t\tmodel.q(i) = config[i] * M_PI / 180.0;\n\n\n\t// Update Box modeling for link\n\tfor (int i = 0; i < box_num_link; i++)\n\t{\n\t\tMatrix3d Rot_temp3 = Box_link[i].vRot * CalcBodyWorldOrientation(model.model_, model.q, model.body_id_vec[i], true).transpose();\n\t\tBox_link[i].vAxis[0] = Rot_temp3.col(0);\n\t\tBox_link[i].vAxis[1] = Rot_temp3.col(1);\n\t\tBox_link[i].vAxis[2] = Rot_temp3.col(2);\n\t\tBox_link[i].vPos = CalcBodyToBaseCoordinates(model.model_, model.q, model.body_id_vec[i], (Box_link[i].vCenter + model.body_com_pos[i]), true);\n\t}\n\n\tbool chk;\n\tif (box_num_link == 0)\n\t{\n\t\tchk = false;\n\t\treturn chk;\n\t}\n\tfor (int i = 0; i < box_num_link; i++)\n\t{\n\t\tfor (int j = i + 2; j < box_num_link; j++)\n\t\t{\n\t\t\tchk = checkOBBCollision(&Box_link[i], &Box_link[j]);\n\t\t\tif (chk)\n\t\t\t{\n\t\t\t\t// cout <<  \"----------------Collision \\n\" << i << \"\\t\" << j << \"\\t\" << chk << endl;\n\t\t\t\t// cout << Box_link[i].vPos.transpose() << endl;\n\t\t\t\t// cout << Box_link[j].vPos.transpose() << endl;\n\t\t\t\t// //cout << CalcBodyToBaseCoordinates(model.model_, model.q, model.body_id_vec[j], Vector3d::Zero(), true).transpose() << endl;\n\t\t\t\t// cout << model.q(0) * 180.0 / M_PI << \"\\t\" << model.q(1) * 180.0 / M_PI << \"\\t\" << model.q(2) * 180.0 / M_PI << \"\\t\" << model.q(3) * 180.0 / M_PI << \"\\t\" << model.q(4) * 180.0 / M_PI << \"\\t\" << model.q(5) * 180.0 / M_PI << \"\\t\" << model.q(6) * 180.0 / M_PI << \"\\t\" << endl;\n\t\t\t\treturn chk;\n\t\t\t}\n\t\t\t// cout << \"No collision \\n\" << i << \"\\t\" << j << \"\\t\" << chk << endl;\n\t\t\t// cout << Box_link[i].vPos.transpose() << endl;\n\t\t\t// cout << Box_link[j].vPos.transpose() << endl;\n\t\t\t// \tcout << CalcBodyToBaseCoordinates(model.model_, model.q, model.body_id_vec[j], Vector3d::Zero(), true).transpose() << endl;\n\t\t\t//cout << model.q(0) * 180.0 / M_PI << \"\\t\" << model.q(1) * 180.0 / M_PI << \"\\t\" << model.q(2) * 180.0 / M_PI << \"\\t\" << model.q(3) * 180.0 / M_PI << \"\\t\" << model.q(4) * 180.0 / M_PI << \"\\t\" << model.q(5) * 180.0 / M_PI << \"\\t\" << model.q(6) * 180.0 / M_PI << \"\\t\" << endl;\n\t\t}\n\t}\n\treturn chk;\n}\n\n\nbool RRT::checkJointLimit(std::vector<double> q) { // radian\n\tfor (int i = 0;i < q.size();i++) {\n\t\tif (q[i] > upper_limit(i)/180.0*M_PI) {\n\t\t\t//cout << q[i] << \"\\t\" << upper_limit(i)/180.0*M_PI << \"\\t\" << i << endl;\n\t\t\treturn false;\n\t\t}\n\t\telse if (q[i] < lower_limit(i)/180.0*M_PI) {\n\t\t\t//cout << q[i] << \"\\t\" << lower_limit(i)/180.0*M_PI  << \"\\t\" << i << endl;\n\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n\n}\n\nbool RRT::checkOBBCollision(ST_OBB* box0, ST_OBB* box1) // Collision-free : False\n{\n\t// compute difference of box centers,D=C1-C0\n\tVector3d D = Vector3d(box1->vPos(0) - box0->vPos(0), box1->vPos(1) - box0->vPos(1), box1->vPos(2) - box0->vPos(2));\n\n\tfloat C[3][3];    //matrix C=A^T B,c_{ij}=Dot(A_i,B_j)\n\tfloat absC[3][3]; //|c_{ij}|\n\tfloat AD[3];      //Dot(A_i,D)\n\tfloat R0, R1, R;    //interval radii and distance between centers\n\tfloat R01;        //=R0+R1\n\n\t\t\t\t\t  //A0\n\tC[0][0] = FDotProduct(box0->vAxis[0], box1->vAxis[0]);// vAxis : direction // 3D Dot product\n\tC[0][1] = FDotProduct(box0->vAxis[0], box1->vAxis[1]);\n\tC[0][2] = FDotProduct(box0->vAxis[0], box1->vAxis[2]);\n\tAD[0] = FDotProduct(box0->vAxis[0], D);\n\tabsC[0][0] = (float)fabsf(C[0][0]);\n\tabsC[0][1] = (float)fabsf(C[0][1]);\n\tabsC[0][2] = (float)fabsf(C[0][2]);\n\tR = (float)fabsf(AD[0]);\n\tR1 = box1->fAxis(0) * absC[0][0] + box1->fAxis(1) * absC[0][1] + box1->fAxis(2) * absC[0][2];\n\tR01 = box0->fAxis(0) + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A1\n\tC[1][0] = FDotProduct(box0->vAxis[1], box1->vAxis[0]);\n\tC[1][1] = FDotProduct(box0->vAxis[1], box1->vAxis[1]);\n\tC[1][2] = FDotProduct(box0->vAxis[1], box1->vAxis[2]);\n\tAD[1] = FDotProduct(box0->vAxis[1], D);\n\tabsC[1][0] = (float)fabsf(C[1][0]);\n\tabsC[1][1] = (float)fabsf(C[1][1]);\n\tabsC[1][2] = (float)fabsf(C[1][2]);\n\tR = (float)fabsf(AD[1]);\n\tR1 = box1->fAxis(0) * absC[1][0] + box1->fAxis(1) * absC[1][1] + box1->fAxis(2) * absC[1][2];\n\tR01 = box0->fAxis(1) + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A2\n\tC[2][0] = FDotProduct(box0->vAxis[2], box1->vAxis[0]);\n\tC[2][1] = FDotProduct(box0->vAxis[2], box1->vAxis[1]);\n\tC[2][2] = FDotProduct(box0->vAxis[2], box1->vAxis[2]);\n\tAD[2] = FDotProduct(box0->vAxis[2], D);\n\tabsC[2][0] = (float)fabsf(C[2][0]);\n\tabsC[2][1] = (float)fabsf(C[2][1]);\n\tabsC[2][2] = (float)fabsf(C[2][2]);\n\tR = (float)fabsf(AD[2]);\n\tR1 = box1->fAxis(0) * absC[2][0] + box1->fAxis(1) * absC[2][1] + box1->fAxis(2) * absC[2][2];\n\tR01 = box0->fAxis(2) + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//B0\n\tR = (float)fabsf(FDotProduct(box1->vAxis[0], D));\n\tR0 = box0->fAxis(0) * absC[0][0] + box0->fAxis(1) * absC[1][0] + box0->fAxis(2) * absC[2][0];\n\tR01 = R0 + box1->fAxis(0);\n\tif (R > R01)\n\t\treturn 0;\n\n\t//B1\n\tR = (float)fabsf(FDotProduct(box1->vAxis[1], D));\n\tR0 = box0->fAxis(0) * absC[0][1] + box0->fAxis(1) * absC[1][1] + box0->fAxis(2) * absC[2][1];\n\tR01 = R0 + box1->fAxis(1);\n\tif (R > R01)\n\t\treturn 0;\n\n\t//B2\n\tR = (float)fabsf(FDotProduct(box1->vAxis[2], D));\n\tR0 = box0->fAxis(0) * absC[0][2] + box0->fAxis(1) * absC[1][2] + box0->fAxis(2) * absC[2][2];\n\tR01 = R0 + box1->fAxis(2);\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A0xB0\n\tR = (float)fabsf(AD[2] * C[1][0] - AD[1] * C[2][0]);\n\tR0 = box0->fAxis(1) * absC[2][0] + box0->fAxis(2) * absC[1][0];\n\tR1 = box1->fAxis(1) * absC[0][2] + box1->fAxis(2) * absC[0][1];\n\tR01 = R0 + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A0xB1\n\tR = (float)fabsf(AD[2] * C[1][1] - AD[1] * C[2][1]);\n\tR0 = box0->fAxis(1) * absC[2][1] + box0->fAxis(2) * absC[1][1];\n\tR1 = box1->fAxis(0) * absC[0][2] + box1->fAxis(2) * absC[0][0];\n\tR01 = R0 + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A0xB2\n\tR = (float)fabsf(AD[2] * C[1][2] - AD[1] * C[2][2]);\n\tR0 = box0->fAxis(1) * absC[2][2] + box0->fAxis(2) * absC[1][2];\n\tR1 = box1->fAxis(0) * absC[0][1] + box1->fAxis(1) * absC[0][0];\n\tR01 = R0 + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A1xB0\n\tR = (float)fabsf(AD[0] * C[2][0] - AD[2] * C[0][0]);\n\tR0 = box0->fAxis(0) * absC[2][0] + box0->fAxis(2) * absC[0][0];\n\tR1 = box1->fAxis(1) * absC[1][2] + box1->fAxis(2) * absC[1][1];\n\tR01 = R0 + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A1xB1\n\tR = (float)fabsf(AD[0] * C[2][1] - AD[2] * C[0][1]);\n\tR0 = box0->fAxis(0) * absC[2][1] + box0->fAxis(2) * absC[0][1];\n\tR1 = box1->fAxis(0) * absC[1][2] + box1->fAxis(2) * absC[1][0];\n\tR01 = R0 + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A1xB2\n\tR = (float)fabsf(AD[0] * C[2][2] - AD[2] * C[0][2]);\n\tR0 = box0->fAxis(0) * absC[2][2] + box0->fAxis(2) * absC[0][2];\n\tR1 = box1->fAxis(0) * absC[1][1] + box1->fAxis(1) * absC[1][0];\n\tR01 = R0 + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A2xB0\n\tR = (float)fabsf(AD[1] * C[0][0] - AD[0] * C[1][0]);\n\tR0 = box0->fAxis(0) * absC[1][0] + box0->fAxis(1) * absC[0][0];\n\tR1 = box1->fAxis(1) * absC[2][2] + box1->fAxis(2) * absC[2][1];\n\tR01 = R0 + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A2xB1\n\tR = (float)fabsf(AD[1] * C[0][1] - AD[0] * C[1][1]);\n\tR0 = box0->fAxis(0) * absC[1][1] + box0->fAxis(1) * absC[0][1];\n\tR1 = box1->fAxis(0) * absC[2][2] + box1->fAxis(2) * absC[2][0];\n\tR01 = R0 + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\t//A2xB2\n\tR = (float)fabsf(AD[1] * C[0][2] - AD[0] * C[1][2]);\n\tR0 = box0->fAxis(0) * absC[1][2] + box0->fAxis(1) * absC[0][2];\n\tR1 = box1->fAxis(0) * absC[2][1] + box1->fAxis(1) * absC[2][0];\n\tR01 = R0 + R1;\n\tif (R > R01)\n\t\treturn 0;\n\n\treturn 1;\n}\nMatrixXd RRT::MergeRRTResults(MatrixXd joint_target1, MatrixXd joint_target2, int case_){\n\t// case 0 : RRT / RRT\n\t// case 1 : RRT / CBiRRT\n\t// case 2 : CBiRRT / RRT\n\t// case 3 : CBiRRT / CBiRRT \n\tMatrixXd merged_joint_target;\n\tint row[2];\n\tint reminder[2];\n\tswitch(case_ )\n\t{\n\t\tcase 0 :\n\t\t\trow[0] = joint_target1.rows();\n\t\t\trow[1] = joint_target2.rows();\n\t\t\tmerged_joint_target.resize(row[0] + row[1] -1, dofSize);\n\t\t\tmerged_joint_target.topRows(row[0]) = joint_target1.topRows(row[0]);\n\t\t\tmerged_joint_target.bottomRows(row[1]-1) = joint_target2.bottomRows(row[1]-1);\n\t\tbreak;\n\t\tcase 1 :\n\t\t\trow[0] = joint_target1.rows();\n\t\t\trow[1] = joint_target2.rows() / 20;\n\t\t\treminder[1] = joint_target2.rows() % 20;\n\t\t\tif (reminder[1] == 0)\n\t\t\t{\n\t\t\t\tmerged_joint_target.resize(row[0] + row[1], dofSize);\n\t\t\t\tmerged_joint_target.topRows(row[0]) = joint_target1.topRows(row[0]);\n\t\t\t\tfor (int i = 0; i < row[1]; i++)\n\t\t\t\t\tmerged_joint_target.row(row[0] + i) = joint_target2.row(20 * (i + 1) - 1);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmerged_joint_target.resize(row[0] + row[1] + 1,dofSize);\n\t\t\t\tmerged_joint_target.topRows(row[0]) = joint_target1.topRows(row[0]);\n\t\t\t\tfor (int i = 0; i < row[1]; i++)\n\t\t\t\t\tmerged_joint_target.row(row[0] + i) = joint_target2.row(20 * (i + 1)- 1);\n\n\t\t\t\tmerged_joint_target.bottomRows(1) = joint_target2.bottomRows(1);\n\t\t\t}\n\t\t\tbreak; \n\t\tcase 2 :\n\t\t\trow[0] = joint_target1.rows() /20;\n\t\t\trow[1] = joint_target2.rows() ;\n\t\t\treminder[0] = joint_target1.rows() % 20;\n\t\t\tif (reminder[0] == 0)\n\t\t\t{\n\t\t\t\tmerged_joint_target.resize(row[0] + row[1],dofSize);\n\t\t\t\tfor (int i = 0; i < row[0]; i++)\n\t\t\t\t\tmerged_joint_target.row(i) = joint_target1.row(20 * (i));\n\n\t\t\t\tmerged_joint_target.bottomRows(row[1]) = joint_target2.bottomRows(row[1]);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tmerged_joint_target.resize(row[0] + row[1] + 1,dofSize);\n\t\t\t\tfor (int i = 0; i < row[0] + 1; i++)\n\t\t\t\t\tmerged_joint_target.row(i) = joint_target1.row(20 * (i));\n\n\t\t\t\tmerged_joint_target.bottomRows(row[1]) = joint_target2.bottomRows(row[1]);\n\t\t\t}\n\t\tbreak;\n\t\tcase 3 :\n\t\t\trow[0] = joint_target1.rows() /20;\n\t\t\trow[1] = joint_target2.rows() /20;\n\t\t\treminder[0] = joint_target1.rows() % 20;\n\t\t\treminder[1] = joint_target2.rows() % 20;\n\t\t\tif (reminder[0] == 0){\n\t\t\t\tif (reminder[1] == 0){\n\t\t\t\t\tmerged_joint_target.resize(row[0] + row[1] + 1,dofSize);\n\t\t\t\t\tfor (int i = 0; i < row[0] + 1; i++)\n\t\t\t\t\t\tmerged_joint_target.row(i) = joint_target1.row(20 * (i));\n\n\t\t\t\t\tfor (int i = 0; i < row[1]; i++)\n\t\t\t\t\t\tmerged_joint_target.row(row[0] + 1 + i) = joint_target2.row(20 * (i+1));\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tmerged_joint_target.resize(row[0] + row[1] + 2,dofSize);\n\t\t\t\t\tfor (int i = 0; i < row[0] + 1; i++)\n\t\t\t\t\t\tmerged_joint_target.row(i) = joint_target1.row(20 * (i));\n\n\t\t\t\t\tfor (int i = 0; i < row[1]; i++)\n\t\t\t\t\t\tmerged_joint_target.row(row[0] + 1 + i) = joint_target2.row(20 * (i+1));\n\n\t\t\t\t\tmerged_joint_target.bottomRows(1) = joint_target2.bottomRows(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (reminder[1] == 0){\n\t\t\t\t\tmerged_joint_target.resize(row[0] + row[1] + 2,dofSize);\n\t\t\t\t\tfor (int i = 0; i < row[0] + 1; i++)\n\t\t\t\t\t\tmerged_joint_target.row(i) = joint_target1.row(20 * (i));\n\n\t\t\t\t\tmerged_joint_target.row(row[0]+1) = joint_target1.bottomRows(1);\n\n\t\t\t\t\tfor (int i = 0; i < row[1]; i++)\n\t\t\t\t\t\tmerged_joint_target.row(row[0] + 2 + i) = joint_target2.row(20 * (i+1));\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tmerged_joint_target.resize(row[0] + row[1] + 3,dofSize);\n\t\t\t\t\tfor (int i = 0; i < row[0] + 1; i++)\n\t\t\t\t\t\tmerged_joint_target.row(i) = joint_target1.row(20 * (i));\n\n\t\t\t\t\tmerged_joint_target.row(row[0]+1) = joint_target1.bottomRows(1);\n\n\t\t\t\t\tfor (int i = 0; i < row[1]; i++)\n\t\t\t\t\t\tmerged_joint_target.row(row[0] + 2 + i) = joint_target2.row(20 * (i+1));\n\n\t\t\t\t\tmerged_joint_target.bottomRows(1) = joint_target2.bottomRows(1);\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t}\n\n\n\treturn merged_joint_target;\n}", "meta": {"hexsha": "baf9006e37c3e21d0bdba411c8c25acd7a6c10bb", "size": 36054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "updated/catkin_ws/src/grasp_sampler/src/RRTFunction.cpp", "max_stars_repo_name": "JisuHann/Point-Cloud--Grasp", "max_stars_repo_head_hexsha": "083244632412709dbc29ac7841b6a837e4ed3cb6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "updated/catkin_ws/src/grasp_sampler/src/RRTFunction.cpp", "max_issues_repo_name": "JisuHann/Point-Cloud--Grasp", "max_issues_repo_head_hexsha": "083244632412709dbc29ac7841b6a837e4ed3cb6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "updated/catkin_ws/src/grasp_sampler/src/RRTFunction.cpp", "max_forks_repo_name": "JisuHann/Point-Cloud--Grasp", "max_forks_repo_head_hexsha": "083244632412709dbc29ac7841b6a837e4ed3cb6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-31T06:27:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-31T06:27:31.000Z", "avg_line_length": 31.9344552702, "max_line_length": 279, "alphanum_fraction": 0.5813224608, "num_tokens": 13885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792043, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2301717440473306}}
{"text": "/*****************************************************************************/\n/*  Copyright (c) 2015, Karl Pauwels                                         */\n/*  All rights reserved.                                                     */\n/*                                                                           */\n/*  Redistribution and use in source and binary forms, with or without       */\n/*  modification, are permitted provided that the following conditions       */\n/*  are met:                                                                 */\n/*                                                                           */\n/*  1. Redistributions of source code must retain the above copyright        */\n/*  notice, this list of conditions and the following disclaimer.            */\n/*                                                                           */\n/*  2. Redistributions in binary form must reproduce the above 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/*  3. Neither the name of the copyright holder nor the names of its         */\n/*  contributors may be used to endorse or promote products derived from     */\n/*  this software without specific prior written permission.                 */\n/*                                                                           */\n/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS      */\n/*  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT        */\n/*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR    */\n/*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT     */\n/*  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   */\n/*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT         */\n/*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,    */\n/*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY    */\n/*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT      */\n/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE    */\n/*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.     */\n/*****************************************************************************/\n\n#include <numeric>\n#include <algorithm>\n#include <cstdlib>\n#include <math.h>\n#include <cstring>\n#include <cuda_profiler_api.h>\n#include <stdexcept>\n#include <Eigen/Dense>\n#include <d_multiple_rigid_poses.h>\n#include <utility_kernels_pose.h>\n#include <multiple_rigid_pose_kernels.h>\n#include <utilities.h>\n\nnamespace pose {\n\nD_MultipleRigidPoses::D_MultipleRigidPoses(int n_cols, int n_rows,\n                                           float nodal_point_x,\n                                           float nodal_point_y,\n                                           float focal_length_x,\n                                           float focal_length_y, float baseline,\n                                           Parameters parameters)\n    : parameters_{ parameters }, _n_cols{ n_cols }, _n_rows{ n_rows },\n      _nodal_point_x{ nodal_point_x }, _nodal_point_y{ nodal_point_y },\n      _focal_length_x{ focal_length_x }, _focal_length_y{ focal_length_y },\n      _baseline{ baseline }, _currentSparseObject{ 0 },\n      _multipleRigidModelsOgre{\n        std::unique_ptr<MultipleRigidModelsOgre>{ new MultipleRigidModelsOgre(\n            _n_cols, _n_rows, _focal_length_x, _focal_length_y, _nodal_point_x,\n            _nodal_point_y, parameters_.near_plane_, parameters_.far_plane_) }\n      },\n      cub_radix_sorter_{\n        std::unique_ptr<util::CubRadixSorter<unsigned int, int> >{\n          new util::CubRadixSorter<unsigned int, int>(\n              _n_rows * _n_cols * _N_FLOWS, 0, parameters_.getKeyBits())\n        }\n      },\n      _n_objects{ 0 }, _running{ true }, render_state_changed_{ true } {\n\n  camera_pose_.setValid(true);\n  previous_camera_pose_.setValid(false);\n\n  /*******************************************************/\n  /* Pre-allocate (and initiate )all device space needed */\n  /* with maximal possible size                          */\n  /* to avoid re-allocation and re-computation           */\n  /*******************************************************/\n\n  // linear index to store pixel locations\n  // goes from 0 to n_rows*n_cols*n_flows\n  // used to identify flow source\n  std::vector<int> h_linear_ind(_n_rows * _n_cols * _N_FLOWS);\n  std::iota(h_linear_ind.begin(), h_linear_ind.end(), 0);\n  d_linear_ind_ =\n      util::Device1D<int>::make_unique(_n_rows * _n_cols * _N_FLOWS);\n  d_linear_ind_->copyFrom(h_linear_ind);\n\n  // 0,1,2,...,n_objects valid locations\n  d_valid_flow_Zbuffer_ =\n      util::Device1D<unsigned int>::make_unique(_n_rows * _n_cols * _N_FLOWS);\n  d_valid_disparity_Zbuffer_ =\n      util::Device1D<unsigned int>::make_unique(_n_rows * _n_cols);\n  d_valid_flow_Zbuffer_sub_ =\n      util::Device1D<unsigned int>::make_unique(_n_rows * _n_cols * _N_FLOWS);\n  d_valid_disparity_Zbuffer_sub_ =\n      util::Device1D<unsigned int>::make_unique(_n_rows * _n_cols);\n  d_extra_disparity_buffer_ =\n      util::Device1D<unsigned int>::make_unique(_n_rows * _n_cols);\n\n  // index of valid locations\n  d_ind_flow_Zbuffer_ =\n      util::Device1D<int>::make_unique(_n_rows * _n_cols * _N_FLOWS);\n  d_ind_disparity_Zbuffer_ =\n      util::Device1D<int>::make_unique(_n_rows * _n_cols);\n  d_ind_flow_Zbuffer_sub_ =\n      util::Device1D<int>::make_unique(_n_rows * _n_cols * _N_FLOWS);\n  d_ind_disparity_Zbuffer_sub_ =\n      util::Device1D<int>::make_unique(_n_rows * _n_cols);\n\n  // starting index of sorted segments\n  d_seg_start_inds_ =\n      util::Device1D<int>::make_unique(parameters_.max_objects_);\n\n  // Gathering\n  d_flow_compact_ =\n      util::Device1D<float2>::make_unique(_n_cols * _n_rows * _N_FLOWS);\n  d_Zbuffer_flow_compact_ =\n      util::Device1D<float>::make_unique(_n_cols * _n_rows * _N_FLOWS);\n  d_disparity_compact_ = util::Device1D<float>::make_unique(_n_cols * _n_rows);\n  d_Zbuffer_normals_compact_ =\n      util::Device1D<float4>::make_unique(_n_cols * _n_rows);\n  d_n_values_flow_ = util::Device1D<int>::make_unique(parameters_.max_objects_);\n  d_start_ind_flow_ =\n      util::Device1D<int>::make_unique(parameters_.max_objects_);\n  d_n_values_disparity_ =\n      util::Device1D<int>::make_unique(parameters_.max_objects_);\n  d_start_ind_disparity_ =\n      util::Device1D<int>::make_unique(parameters_.max_objects_);\n\n  // Normal equations\n  d_CO_ = util::Device1D<float>::make_unique(\n      4 * _MAX_N_VAL_ACCUM * _N_CON_FLOW * parameters_.max_objects_);\n  d_CO_reduced_ = util::Device1D<float>::make_unique(_N_CON_FLOW *\n                                                     parameters_.max_objects_);\n  d_CD_ = util::Device1D<float>::make_unique(\n      4 * _MAX_N_VAL_ACCUM * _N_CON_DISP * parameters_.max_objects_);\n  d_CD_reduced_ = util::Device1D<float>::make_unique(_N_CON_DISP *\n                                                     parameters_.max_objects_);\n  d_abs_res_ =\n      util::Device1D<float>::make_unique((_N_FLOWS + 1) * _n_rows * _n_cols);\n\n  h_CO_reduced_.resize(_N_CON_FLOW * parameters_.max_objects_);\n  h_CD_reduced_.resize(_N_CON_DISP * parameters_.max_objects_);\n  segment_normal_eqs_.resize(parameters_.max_objects_);\n\n  // Segment starting indices in single residual structure\n  d_offset_ind_res_flow_ =\n      util::Device1D<int>::make_unique(parameters_.max_objects_);\n  d_offset_ind_res_disparity_ =\n      util::Device1D<int>::make_unique(parameters_.max_objects_);\n  d_dTR_ = util::Device1D<float>::make_unique(6 * parameters_.max_objects_);\n  d_delta_T_accum_ =\n      util::Device1D<float>::make_unique(3 * parameters_.max_objects_);\n  d_delta_Rmat_accum_ =\n      util::Device1D<float>::make_unique(9 * parameters_.max_objects_);\n  d_segment_translation_table_ =\n      util::Device1D<int>::make_unique(parameters_.max_objects_);\n\n  // Approximate median\n  // pre-generate maximum number of random numbers required (uniform between\n  // [0,1[ , used for sampling (with replacement) of absolute residuals\n  std::vector<float> h_random_numbers(_n_rows * _n_cols * (_N_FLOWS + 1));\n  srand(0);\n  for (auto &it : h_random_numbers)\n    it = (float)((double)rand() / double(RAND_MAX));\n  d_random_numbers_ =\n      util::Device1D<float>::make_unique(_n_rows * _n_cols * (_N_FLOWS + 1));\n  d_random_numbers_->copyFrom(h_random_numbers);\n  int pp = int(ceil(double(_n_rows * _n_cols * (_N_FLOWS + 1)) /\n                    243.0)); // second stage reduction\n  d_median_tmp_ = util::Device1D<float>::make_unique(pp);\n  d_abs_res_scales_ =\n      util::Device1D<float>::make_unique(parameters_.max_objects_);\n\n  // temps used inside median calculation\n  d_median_n_in_ = util::Device1D<int>::make_unique(parameters_.max_objects_);\n  d_median_start_inds_ =\n      util::Device1D<int>::make_unique(parameters_.max_objects_);\n\n  // Initial Zbuffer\n  d_init_Z_ = util::Device1D<float>::make_unique(_n_rows * _n_cols);\n\n  // Residual flow\n  d_res_flowx_ = util::Device1D<float>::make_unique(_n_rows * _n_cols);\n  d_res_flowy_ = util::Device1D<float>::make_unique(_n_rows * _n_cols);\n\n  // Residual ar flow\n  d_res_ar_flowx_ = util::Device1D<float>::make_unique(_n_rows * _n_cols);\n  d_res_ar_flowy_ = util::Device1D<float>::make_unique(_n_rows * _n_cols);\n}\n\nvoid D_MultipleRigidPoses::addModel(const char *obj_filename, float obj_scale,\n                                    TranslationRotation3D initial_pose) {\n  if (_n_objects > (parameters_.max_objects_ - 2))\n    throw std::runtime_error(\"D_MultipleRigidPoses::addModel: Max objects \"\n                             \"exceeded, increase key_bits\\n\");\n\n  _n_objects++;\n  _currentPoses.push_back(initial_pose);\n  setSparsePose(initial_pose, _n_objects - 1);\n\n  _multipleRigidModelsOgre->addModel(obj_filename);\n}\n\nvoid D_MultipleRigidPoses::removeAllModels() {\n  _multipleRigidModelsOgre->removeAllModels();\n  _currentPoses.clear();\n  _currentSparseObject = 0;\n  _n_objects = 0;\n}\n\nvoid D_MultipleRigidPoses::update(const util::Device1D<float> &d_flowx,\n                                  const util::Device1D<float> &d_flowy,\n                                  const util::Device1D<float> &d_ar_flowx,\n                                  const util::Device1D<float> &d_ar_flowy,\n                                  const util::Device2D<float> &d_disparity,\n                                  std::bitset<32> segments_to_update) {\n// small inaccuracy here is that the optical flow (frame 1 -> frame 2) is\n// segmented according to the region estimated at frame 2\n// this is necessary in order to update the residual flow according to the\n// updated model depth\n// have shown (in simulation) that the resulting pose estimates are a lot more\n// accurate than those based on initial depth\n\n#ifdef TIME_STEPS\n  // Setup timers\n  cudaEvent_t start, end;\n  float elapsed_time;\n  cudaEventCreate(&start);\n  cudaEventCreate(&end);\n#endif\n\n  if (_running) {\n\n    // reset timers\n    int n_timers = 14;\n    _compTimes.clear();\n    _compTimes.assign(n_timers, 0.0);\n\n    /* 0 preprocess-total\n     * 1 ols-total\n     * 2 robust-total\n     * 3 mark valids\n     * 4 radix sort\n     * 5 gather\n     * 6 compose normal equations\n     * 7 reduce normal equations\n     * 8 solve normal equations (cpu)\n     * 9 compute absolute residuals\n     * 10 median absolute residuals\n     * 11 render\n     * 12 pose accumulation (cpu)\n     * 13 residual flow\n     */\n\n    std::vector<TranslationRotation3D> delta_poses_accum(\n        _n_objects, TranslationRotation3D());\n\n    std::vector<TranslationRotation3D> explained_delta_poses(\n        _n_objects, TranslationRotation3D());\n\n#ifdef TIME_STEPS\n    cudaEventRecord(start, 0);\n#endif\n\n    // first rendering\n    render(_currentPoses);\n\n#ifdef TIME_STEPS\n    cudaThreadSynchronize();\n    cudaEventRecord(end, 0);\n    cudaEventSynchronize(end);\n    cudaEventElapsedTime(&elapsed_time, start, end);\n    _compTimes.at(11) += (double)elapsed_time;\n#endif\n\n#ifdef TIME_STEPS\n    cudaEventRecord(start, 0);\n#endif\n\n    // store initial Zbuffer as initial model for residual flow\n    convertZbufferToZ(d_init_Z_->data(), _multipleRigidModelsOgre->getZBuffer(),\n                      _n_cols, _n_rows, _nodal_point_x, _nodal_point_y,\n                      parameters_.near_plane_, parameters_.far_plane_);\n\n#ifdef TIME_STEPS\n    cudaThreadSynchronize();\n    cudaEventRecord(end, 0);\n    cudaEventSynchronize(end);\n    cudaEventElapsedTime(&elapsed_time, start, end);\n    _compTimes.at(13) += (double)elapsed_time;\n#endif\n\n    // start iterations\n    std::vector<float> dT_accum(3 * _n_objects);\n    std::vector<float> dR_accum(9 * _n_objects);\n    std::vector<TranslationRotation3D> poses_accum = _currentPoses;\n\n    for (int it = 1; it <= parameters_.n_icp_outer_it_; it++) {\n\n// update residual flow\n#ifdef TIME_STEPS\n      cudaEventRecord(start, 0);\n#endif\n\n      for (int o = 0; o < _n_objects; o++) {\n        auto delta_pose =\n            poses_accum.at(o) * _currentPoses.at(o).inverseTransform();\n        if (previous_camera_pose_.isValid()) {\n          explained_delta_poses.at(o) = camera_pose_.inverseTransform() *\n                                        delta_pose * previous_camera_pose_;\n        } else {\n          explained_delta_poses.at(o) = delta_pose;\n        }\n      }\n\n      for (int o = 0; o < _n_objects; o++) {\n        explained_delta_poses.at(o).getT(&dT_accum[3 * o]);\n        explained_delta_poses.at(o).getR_mat(&dR_accum[9 * o]);\n      }\n      d_delta_T_accum_->copyFrom(dT_accum, 3 * _n_objects);\n      d_delta_Rmat_accum_->copyFrom(dR_accum, 9 * _n_objects);\n\n#ifdef TIME_STEPS\n      cudaThreadSynchronize();\n      cudaEventRecord(end, 0);\n      cudaEventSynchronize(end);\n      cudaEventElapsedTime(&elapsed_time, start, end);\n      _compTimes.at(12) += (double)elapsed_time;\n#endif\n\n#ifdef TIME_STEPS\n      cudaEventRecord(start, 0);\n#endif\n      computeResidualFlow(\n          d_res_flowx_->data(), d_res_flowy_->data(), d_res_ar_flowx_->data(),\n          d_res_ar_flowy_->data(), d_flowx.data(), d_flowy.data(),\n          d_ar_flowx.data(), d_ar_flowy.data(), d_delta_T_accum_->data(),\n          d_delta_Rmat_accum_->data(), d_init_Z_->data(),\n          _multipleRigidModelsOgre->getSegmentIND(), _n_cols, _n_rows,\n          _nodal_point_x, _nodal_point_y, _focal_length_x, _focal_length_y);\n\n#ifdef TIME_STEPS\n      cudaThreadSynchronize();\n      cudaEventRecord(end, 0);\n      cudaEventSynchronize(end);\n      cudaEventElapsedTime(&elapsed_time, start, end);\n      _compTimes.at(13) += (double)elapsed_time;\n#endif\n\n      robustPoseUpdates(d_res_flowx_->data(), d_res_flowy_->data(),\n                        d_res_ar_flowx_->data(), d_res_ar_flowy_->data(),\n                        d_disparity.data(), d_disparity.pitch(),\n                        (int)segments_to_update.to_ulong());\n\n      // accumulate delta poses\n      for (int s = 0; s < _segment_info.size(); s++) {\n        SegmentINFO &tmp = _segment_info.at(s);\n        delta_poses_accum.at(tmp.segment_ind) =\n            _robustDeltaPoses.at(s) * delta_poses_accum.at(tmp.segment_ind);\n      }\n\n#ifdef TIME_STEPS\n      cudaEventRecord(start, 0);\n#endif\n\n      // update poses, invalidating if magnitude T too large\n      poses_accum = _currentPoses;\n\n      // transform to camera frame\n      for (auto &it : poses_accum)\n        it = camera_pose_.inverseTransform() * it;\n\n      for (int o = 0; o < _n_objects; o++)\n        if (delta_poses_accum.at(o).normT2() <\n            parameters_.max_t_update_norm_squared_)\n          poses_accum.at(o) = delta_poses_accum.at(o) * poses_accum.at(o);\n        else // invalidate\n          poses_accum.at(o).setValid(false);\n\n      // transform back to world frame\n      for (auto &it : poses_accum)\n        it = camera_pose_ * it;\n\n#ifdef TIME_STEPS\n      cudaThreadSynchronize();\n      cudaEventRecord(end, 0);\n      cudaEventSynchronize(end);\n      cudaEventElapsedTime(&elapsed_time, start, end);\n      _compTimes.at(12) += (double)elapsed_time;\n#endif\n\n#ifdef TIME_STEPS\n      cudaEventRecord(start, 0);\n#endif\n\n      // render at updated pose (unless last iteration)\n      if (it < parameters_.n_icp_outer_it_)\n        render(poses_accum);\n\n#ifdef TIME_STEPS\n      cudaThreadSynchronize();\n      cudaEventRecord(end, 0);\n      cudaEventSynchronize(end);\n      cudaEventElapsedTime(&elapsed_time, start, end);\n      _compTimes.at(11) += (double)elapsed_time;\n#endif\n    }\n\n    // update current pose\n    _currentPoses = poses_accum;\n  }\n}\n\nvoid D_MultipleRigidPoses::updateNormalEquations(\n    const util::Device1D<float> &d_flowx, const util::Device1D<float> &d_flowy,\n    const util::Device1D<float> &d_ar_flowx,\n    const util::Device1D<float> &d_ar_flowy,\n    const util::Device2D<float> &d_disparity,\n    const std::vector<TranslationRotation3D> &explained_delta_poses,\n    std::bitset<32> segments_to_update) {\n  // ensure rendering is up-to-date\n  render(_currentPoses);\n\n  // store initial Zbuffer as initial model for residual flow\n  convertZbufferToZ(d_init_Z_->data(), _multipleRigidModelsOgre->getZBuffer(),\n                    _n_cols, _n_rows, _nodal_point_x, _nodal_point_y,\n                    parameters_.near_plane_, parameters_.far_plane_);\n\n  // initialize residual flow (will improve later)\n  d_res_flowx_->copyFrom(d_flowx);\n  d_res_flowy_->copyFrom(d_flowy);\n  d_res_ar_flowx_->copyFrom(d_ar_flowx);\n  d_res_ar_flowy_->copyFrom(d_ar_flowy);\n\n  // subtract camera-motion-induced flow\n  std::vector<float> dT_accum(3 * _n_objects);\n  std::vector<float> dR_accum(9 * _n_objects);\n\n  for (int o = 0; o < _n_objects; o++) {\n    explained_delta_poses.at(o).getT(&dT_accum[3 * o]);\n    explained_delta_poses.at(o).getR_mat(&dR_accum[9 * o]);\n  }\n  d_delta_T_accum_->copyFrom(dT_accum, 3 * _n_objects);\n  d_delta_Rmat_accum_->copyFrom(dR_accum, 9 * _n_objects);\n\n  computeResidualFlow(\n      d_res_flowx_->data(), d_res_flowy_->data(), d_res_ar_flowx_->data(),\n      d_res_ar_flowy_->data(), d_flowx.data(), d_flowy.data(),\n      d_ar_flowx.data(), d_ar_flowy.data(), d_delta_T_accum_->data(),\n      d_delta_Rmat_accum_->data(), d_init_Z_->data(),\n      _multipleRigidModelsOgre->getSegmentIND(), _n_cols, _n_rows,\n      _nodal_point_x, _nodal_point_y, _focal_length_x, _focal_length_y);\n\n  // reset normal equations\n  for (auto &it : segment_normal_eqs_)\n    it.reset();\n\n  // perform robust iteration\n  robustPoseUpdates(d_res_flowx_->data(), d_res_flowy_->data(),\n                    d_res_ar_flowx_->data(), d_res_ar_flowy_->data(),\n                    d_disparity.data(), d_disparity.pitch(),\n                    (int)segments_to_update.to_ulong());\n\n  // prepare normal equations for (external) constrained update\n  int min_samples = 1000;\n  for (auto &it : _segment_info) {\n    // reset if not enough samples or update norm too large\n    if (((it.n_values_flow + it.n_values_disparity) < min_samples) &&\n        (segment_normal_eqs_.at(it.segment_ind).squaredNormDeltaT() >=\n         parameters_.max_t_update_norm_squared_))\n      segment_normal_eqs_.at(it.segment_ind).reset();\n  }\n}\n\nvoid D_MultipleRigidPoses::setWeights(float w_flow, float w_ar_flow,\n                                      float w_disp) {\n  parameters_.w_flow_ = w_flow;\n  parameters_.w_ar_flow_ = w_ar_flow;\n  parameters_.w_disp_ = w_disp;\n}\n\nvoid D_MultipleRigidPoses::getWeights(float &w_flow, float &w_ar_flow,\n                                      float &w_disp) const {\n  w_flow = parameters_.w_flow_;\n  w_ar_flow = parameters_.w_ar_flow_;\n  w_disp = parameters_.w_disp_;\n}\n\ncudaArray *D_MultipleRigidPoses::getTexture() {\n  render(_currentPoses);\n  return (_multipleRigidModelsOgre->getTexture());\n}\n\ncudaArray *D_MultipleRigidPoses::getSegmentIND() {\n  render(_currentPoses);\n  return (_multipleRigidModelsOgre->getSegmentIND());\n}\n\ncudaArray *D_MultipleRigidPoses::getZbuffer() {\n  render(_currentPoses);\n  return _multipleRigidModelsOgre->getZBuffer();\n}\n\ncudaArray *D_MultipleRigidPoses::getNormalX() {\n  render(_currentPoses);\n  return _multipleRigidModelsOgre->getNormalX();\n}\n\ncudaArray *D_MultipleRigidPoses::getNormalY() {\n  render(_currentPoses);\n  return _multipleRigidModelsOgre->getNormalY();\n}\n\ncudaArray *D_MultipleRigidPoses::getNormalZ() {\n  render(_currentPoses);\n  return _multipleRigidModelsOgre->getNormalZ();\n}\n\nvoid D_MultipleRigidPoses::setCameraParameters(float focal_length_x,\n                                               float focal_length_y,\n                                               float nodal_point_x,\n                                               float nodal_point_y) {\n  render_state_changed_ = true;\n  _nodal_point_x = nodal_point_x;\n  _nodal_point_y = nodal_point_y;\n  _focal_length_x = focal_length_x;\n  _focal_length_y = focal_length_y;\n  _multipleRigidModelsOgre->updateProjectionMatrix(\n      _focal_length_x, _focal_length_y, _nodal_point_x, _nodal_point_y,\n      parameters_.near_plane_, parameters_.far_plane_);\n}\n\nvoid\nD_MultipleRigidPoses::setCameraPose(const TranslationRotation3D &camera_pose) {\n  render_state_changed_ = true;\n\n  // if this is the first camera pose received, make previous and current equal\n  previous_camera_pose_ =\n      previous_camera_pose_.isValid() ? camera_pose_ : camera_pose;\n\n  camera_pose_ = camera_pose;\n  _multipleRigidModelsOgre->updateCameraPose(camera_pose_.rotateX180());\n}\n\nbool D_MultipleRigidPoses::isDenseWinner() {\n\n  bool denseWinner = true;\n  double thres = parameters_.reliability_threshold_;\n\n  // make sure that sparse does not negatively affect any object's proportion ar\n  // valid\n  // add some margin to allow minor decrease in reliability (due to noise)\n  double margin = parameters_.sparse_intro_allowed_reliability_decrease_;\n  bool sparseRelDecrease = false;\n  for (int o = 0; o < _n_objects; o++)\n    if (_S_ar_flow_prop_valid[o] < (_D_ar_flow_prop_valid[o] - margin))\n      sparseRelDecrease = true;\n\n  if (!sparseRelDecrease) {\n\n    // compare reliability at the current sparse object\n    int o = _currentSparseObject;\n\n    // we require a pretty high reliability for sparse introduction\n    double intro_thres = parameters_.sparse_intro_reliability_threshold_;\n    if ((_S_ar_flow_prop_valid[o] > (_D_ar_flow_prop_valid[o] + intro_thres)) ||\n        ((_S_ar_flow_prop_valid[o] > intro_thres) &&\n         (_D_ar_flow_prop_valid[o] < thres)))\n      denseWinner = false;\n  }\n\n  return (denseWinner);\n}\n\nvoid D_MultipleRigidPoses::render(\n    const std::vector<TranslationRotation3D> &renderPoses) {\n  if ((renderPoses != _lastPosesRendered) || (render_state_changed_)) {\n\n    //    util::TimerGPU render_timer;\n    _multipleRigidModelsOgre->render(renderPoses);\n    //    std::cout << \"render time: \" << render_timer.read() << \" ms\\n\";\n    _lastPosesRendered = renderPoses;\n    render_state_changed_ = false;\n  }\n}\n\nvoid\nD_MultipleRigidPoses::getSegmentLengths(std::vector<int> &lengths,\n                                        const std::vector<int> &starting_inds,\n                                        int n_segments, int total_length) {\n\n  for (int i = 0; i < (n_segments - 1); i++) {\n    int s = starting_inds.at(i);\n    if (s >= 0) {\n\n      // find end-point\n      int e = starting_inds.at(i + 1);\n      for (int j = (i + 2); ((e < 0) && (j < n_segments)); j++)\n        e = starting_inds.at(j);\n\n      if (e < 0)\n        e = total_length;\n\n      lengths.at(i) = e - s;\n\n    } else\n\n      lengths.at(i) = 0;\n  }\n\n  // final segment\n  int s = starting_inds.at(n_segments - 1);\n  if (s >= 0)\n    lengths.at(n_segments - 1) = total_length - s;\n  else\n    lengths.at(n_segments - 1) = 0;\n}\n\nint D_MultipleRigidPoses::getNextSelectedSparseObject(bool dense) {\n\n  std::vector<double> probabilities =\n      dense ? _D_ar_flow_prop_valid : _S_ar_flow_prop_valid;\n\n  double sum = 0.0;\n  for (int o = 0; o < _n_objects; o++) {\n    probabilities.at(o) = 1.0 - probabilities.at(o);\n    sum += probabilities.at(o);\n  }\n\n  for (int o = 0; o < _n_objects; o++)\n    probabilities.at(o) /= sum;\n\n  double r = ((double)rand() / double(RAND_MAX));\n\n  int object = 0;\n  double prob_ulim = probabilities.at(object);\n\n  while (r > prob_ulim) {\n    object++;\n    prob_ulim += probabilities.at(object);\n  }\n\n  return (object);\n}\n\nvoid D_MultipleRigidPoses::evaluateARFlowPoseError(\n    bool dense, const util::Device1D<float> &d_ar_flowx,\n    std::vector<TranslationRotation3D> &poses) {\n  if (dense)\n    computeARFlowPoseError(d_ar_flowx, poses, _D_ar_flow_prop_valid);\n  else\n    computeARFlowPoseError(d_ar_flowx, poses, _S_ar_flow_prop_valid);\n}\n\nvoid D_MultipleRigidPoses::computeARFlowPoseError(\n    const util::Device1D<float> &d_ar_flowx,\n    std::vector<TranslationRotation3D> &poses,\n    std::vector<double> &ar_flow_prop_valid) {\n  std::vector<double> ar_flow_abs_valid; // discarded\n  computeARFlowPoseError(d_ar_flowx, poses, ar_flow_prop_valid,\n                         ar_flow_abs_valid);\n}\n\nvoid D_MultipleRigidPoses::computeARFlowPoseError(\n    const util::Device1D<float> &d_ar_flowx,\n    std::vector<TranslationRotation3D> &poses,\n    std::vector<double> &ar_flow_prop_valid,\n    std::vector<double> &ar_flow_abs_valid) {\n  ar_flow_prop_valid.clear();\n  ar_flow_abs_valid.clear();\n\n  render(poses);\n\n  // re-purposing some already allocated data\n  auto d_valid_ar_flow_Zbuffer = d_valid_disparity_Zbuffer_.get();\n  auto d_valid_Zbuffer = d_valid_disparity_Zbuffer_sub_.get();\n  markValidFlowZbufferAndZbufferZeroBased(\n      d_valid_ar_flow_Zbuffer->data(), d_valid_Zbuffer->data(),\n      d_ar_flowx.data(), _multipleRigidModelsOgre->getSegmentIND(), _n_cols,\n      _n_rows, _n_objects);\n\n  // additional buffers required for sorting\n  auto d_value = d_ind_disparity_Zbuffer_.get();\n  auto d_value_buf = d_ind_disparity_Zbuffer_sub_.get();\n  auto d_key_buf = d_extra_disparity_buffer_.get();\n\n  // Radix sort all the indices using the valid marks\n  // indices could be ignored here to speed up sorting (but diff is minimal)\n  cub_radix_sorter_->sort(*d_valid_ar_flow_Zbuffer, *d_value, *d_key_buf,\n                          *d_value_buf);\n  pose::extractLabelStartingIndices(d_seg_start_inds_->data(),\n                                    d_valid_ar_flow_Zbuffer->data(),\n                                    _n_cols * _n_rows, _n_objects);\n  std::vector<int> h_seg_start_inds_flow_Zbuffer(_n_objects + 1);\n  d_seg_start_inds_->copyTo(h_seg_start_inds_flow_Zbuffer, _n_objects + 1);\n\n  cub_radix_sorter_->sort(*d_valid_Zbuffer, *d_value, *d_key_buf, *d_value_buf);\n  pose::extractLabelStartingIndices(d_seg_start_inds_->data(),\n                                    d_valid_Zbuffer->data(), _n_cols * _n_rows,\n                                    _n_objects);\n  std::vector<int> h_seg_start_inds_Zbuffer(_n_objects + 1);\n  d_seg_start_inds_->copyTo(h_seg_start_inds_Zbuffer, _n_objects + 1);\n\n  //  for(int o=0;o<(_n_objects+1);o++)\n  //    printf(\"obj %d - flow+z %09d - z\n  // %09d\\n\",o,h_seg_start_inds_flow_Zbuffer[o],h_seg_start_inds_Zbuffer[o]);\n\n  int n_valid_flow_Zbuffer = (h_seg_start_inds_flow_Zbuffer.at(_n_objects) >= 0)\n                                 ? h_seg_start_inds_flow_Zbuffer.at(_n_objects)\n                                 : (_n_cols * _n_rows);\n\n  _seg_lengths_flow_Zbuffer.assign(_n_objects, 0);\n\n  getSegmentLengths(_seg_lengths_flow_Zbuffer, h_seg_start_inds_flow_Zbuffer,\n                    _n_objects, n_valid_flow_Zbuffer);\n\n  int n_valid_Zbuffer = (h_seg_start_inds_Zbuffer.at(_n_objects) >= 0)\n                            ? h_seg_start_inds_Zbuffer.at(_n_objects)\n                            : (_n_cols * _n_rows);\n\n  _seg_lengths_Zbuffer.assign(_n_objects, 0);\n  getSegmentLengths(_seg_lengths_Zbuffer, h_seg_start_inds_Zbuffer, _n_objects,\n                    n_valid_Zbuffer);\n\n  //  for(int o=0;o<(_n_objects+1);o++)\n  //    printf(\"obj %d - start+z %09d - length+z %09d - start %09d - length\n  // %09d\\n\",o,h_seg_start_inds_flow_Zbuffer[o],seg_lengths_flow_Zbuffer[o],h_seg_start_inds_Zbuffer[o],seg_lengths_Zbuffer[o]);\n\n  // save proportion valid for each object\n  auto bounding_boxes =\n      _multipleRigidModelsOgre->getBoundingBoxesInCameraImage(poses);\n\n  for (int o = 0; o < _n_objects; o++) {\n\n    double absolute_count = (double)_seg_lengths_flow_Zbuffer[o];\n    double prop = (_seg_lengths_Zbuffer[o] > 0)\n                      ? (double)_seg_lengths_flow_Zbuffer[o] /\n                            (double)_seg_lengths_Zbuffer[o]\n                      : 0.0;\n\n    if (parameters_.check_reliability_) {\n      // does the proportion valid AR flow exceed the threshold?\n      bool valid = prop > parameters_.reliability_threshold_;\n\n      // is the projected shape 'sufficiently two-dimensional'?\n      // the AR flow-based reliability measure fails on near-edge-like object\n      // projections\n      Eigen::Map<Eigen::Matrix<double, 2, 8> > bb_pixel(\n          bounding_boxes.at(o).data());\n\n      // subtract mean\n      Eigen::Vector2d mn = bb_pixel.rowwise().mean();\n      bb_pixel.colwise() -= mn;\n\n      // covariance\n      double ratio = parameters_.max_proportion_projected_bounding_box_;\n      Eigen::Matrix2d cov = bb_pixel * bb_pixel.transpose();\n      // check validity\n      if (std::isfinite(cov(0, 0)) && std::isfinite(cov(0, 1)) &&\n          std::isfinite(cov(1, 0)) && std::isfinite(cov(1, 1))) {\n        Eigen::EigenSolver<Eigen::Matrix2d> eigen_solver(cov);\n        // rotate bounding box\n        Eigen::Matrix2d real_eigenvectors = eigen_solver.eigenvectors().real();\n        //        Eigen::VectorXd w = eigen_solver.eigenvalues().real();\n        bb_pixel = real_eigenvectors.transpose() * bb_pixel;\n        // find extent\n        auto extent =\n            bb_pixel.rowwise().maxCoeff() - bb_pixel.rowwise().minCoeff();\n        ratio = extent.maxCoeff() / extent.minCoeff();\n      }\n      valid =\n          valid && (ratio < parameters_.max_proportion_projected_bounding_box_);\n\n      poses.at(o).setValid(valid);\n    }\n\n    ar_flow_prop_valid.push_back(prop);\n    ar_flow_abs_valid.push_back(absolute_count);\n  }\n}\n\nvoid D_MultipleRigidPoses::robustPoseUpdates(\n    const float *d_flowx, const float *d_flowy, const float *d_ar_flowx,\n    const float *d_ar_flowy, const float *d_disparity, size_t d_disparity_pitch,\n    int segments_to_update) {\n\n  cudaArray *d_ZbufferArray = _multipleRigidModelsOgre->getZBuffer();\n  cudaArray *d_normalXArray = _multipleRigidModelsOgre->getNormalX();\n  cudaArray *d_normalYArray = _multipleRigidModelsOgre->getNormalY();\n  cudaArray *d_normalZArray = _multipleRigidModelsOgre->getNormalZ();\n  cudaArray *d_segmentINDArray = _multipleRigidModelsOgre->getSegmentIND();\n\n#ifdef TIME_STEPS\n  // Setup timers\n  cudaEvent_t start, end, start_sub, end_sub;\n  float elapsed_time;\n  cudaEventCreate(&start);\n  cudaEventCreate(&end);\n  cudaEventCreate(&start_sub);\n  cudaEventCreate(&end_sub);\n#endif\n#ifdef TIME_STEPS\n  cudaEventRecord(start, 0); // preprocessing\n#endif\n\n  // initialize normal equations to zero\n  std::fill(h_CO_reduced_.begin(), h_CO_reduced_.end(), 0);\n  std::fill(h_CD_reduced_.begin(), h_CD_reduced_.end(), 0);\n  cudaMemset(d_CO_reduced_->data(), 0,\n             _N_CON_FLOW * parameters_.max_objects_ * sizeof(float));\n  cudaMemset(d_CD_reduced_->data(), 0,\n             _N_CON_DISP * parameters_.max_objects_ * sizeof(float));\n\n  // Determine Zbuffer conversion constants\n  // depth = Z_conv1/(Zbuffer+Z_conv2)\n  float Z_conv1, Z_conv2;\n  get_GL_conv_constants(Z_conv1, Z_conv2, parameters_.far_plane_,\n                        parameters_.near_plane_);\n\n// Mark valid locations with segment index\n// If a cue's weight equals 0 mark everything invalid\n// No initialization required\n\n#ifdef TIME_STEPS\n  cudaEventRecord(start_sub, 0);\n#endif\n\n  mark_with_zero_based_segmentIND(\n      d_valid_flow_Zbuffer_->data(), d_valid_disparity_Zbuffer_->data(),\n      d_flowx, d_ar_flowx, (const char *)d_disparity, d_segmentINDArray,\n      _n_cols, _n_rows, _n_objects, d_disparity_pitch, parameters_.w_flow_ > 0,\n      parameters_.w_ar_flow_ > 0, parameters_.w_disp_ > 0, segments_to_update);\n\n#ifdef TIME_STEPS\n  cudaThreadSynchronize();\n  cudaEventRecord(end_sub, 0);\n  cudaEventSynchronize(end_sub);\n  cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n  _compTimes.at(3) += (double)elapsed_time;\n#endif\n\n#ifdef TIME_STEPS\n  cudaEventRecord(start_sub, 0);\n#endif\n\n  // Radix sort all the indices using the valid marks\n  // the _sub_ buffers are only used for double-buffering (ping-pong)\n  d_ind_flow_Zbuffer_->copyFrom(*d_linear_ind_);\n  d_ind_disparity_Zbuffer_->copyFrom(*d_linear_ind_, _n_cols * _n_rows);\n\n  //  util::TimerGPU sort_timer;\n  cub_radix_sorter_->sort(*d_valid_flow_Zbuffer_, *d_ind_flow_Zbuffer_,\n                          *d_valid_flow_Zbuffer_sub_, *d_ind_flow_Zbuffer_sub_);\n  //  std::cout << \"flow sort time: \" << sort_timer.read();\n  //  sort_timer.reset();\n  cub_radix_sorter_->sort(\n      *d_valid_disparity_Zbuffer_, *d_ind_disparity_Zbuffer_,\n      *d_valid_disparity_Zbuffer_sub_, *d_ind_disparity_Zbuffer_sub_);\n//  std::cout << \" disp sort time: \" << sort_timer.read() << std::endl;\n\n#ifdef TIME_STEPS\n  cudaThreadSynchronize();\n  cudaEventRecord(end_sub, 0);\n  cudaEventSynchronize(end_sub);\n  cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n  _compTimes.at(4) += (double)elapsed_time;\n#endif\n\n  // Get starting indices\n  pose::extractLabelStartingIndices(d_seg_start_inds_->data(),\n                                    d_valid_flow_Zbuffer_->data(),\n                                    _n_cols * _n_rows * _N_FLOWS, _n_objects);\n  std::vector<int> h_seg_start_inds_flow(_n_objects + 1);\n  d_seg_start_inds_->copyTo(h_seg_start_inds_flow, _n_objects + 1);\n  pose::extractLabelStartingIndices(d_seg_start_inds_->data(),\n                                    d_valid_disparity_Zbuffer_->data(),\n                                    _n_cols * _n_rows, _n_objects);\n  std::vector<int> h_seg_start_inds_disparity(_n_objects + 1);\n  d_seg_start_inds_->copyTo(h_seg_start_inds_disparity, _n_objects + 1);\n\n  //  printf(\"before sub\\n\");\n  //  for(int i=0;i<(_n_objects+1);i++)\n  //    printf(\"se %d f %+07d d\n  // %+07d\\n\",i,h_seg_start_inds_flow[i],h_seg_start_inds_disparity[i]);\n\n  // Regularly subsample flow and disparity indices if required when a maximum\n  // number of samples has been enforced\n  // Relative proportion flow/disp will be maintained approximately\n\n  int n_valid_flow_Zbuffer = (h_seg_start_inds_flow.at(_n_objects) >= 0)\n                                 ? h_seg_start_inds_flow.at(_n_objects)\n                                 : (_n_cols * _n_rows * _N_FLOWS);\n  int n_valid_disparity_Zbuffer =\n      (h_seg_start_inds_disparity.at(_n_objects) >= 0)\n          ? h_seg_start_inds_disparity.at(_n_objects)\n          : (_n_cols * _n_rows);\n\n  //  printf(\"before sub %s\\n\",cudaGetErrorString(cudaGetLastError()));\n  //  printf(\"val flow %d val disp\n  // %d\\n\",n_valid_flow_Zbuffer,n_valid_disparity_Zbuffer);\n\n  int n_valid_total = n_valid_flow_Zbuffer + n_valid_disparity_Zbuffer;\n\n  if (n_valid_total > parameters_.max_samples_) {\n\n    // proportionally subsample flow and disparity\n    double sub_factor =\n        (double)parameters_.max_samples_ / (double)n_valid_total;\n    double inv_sub_factor = 1.0 / sub_factor;\n\n    // flow\n    int n_valid_flow_Zbuffer_sub =\n        (int)floor((double)n_valid_flow_Zbuffer * sub_factor);\n\n    if (n_valid_flow_Zbuffer_sub > 0) {\n      subsample_ind_and_labels(\n          d_ind_flow_Zbuffer_sub_->data(), d_ind_flow_Zbuffer_->data(),\n          d_valid_flow_Zbuffer_sub_->data(), d_valid_flow_Zbuffer_->data(),\n          n_valid_flow_Zbuffer_sub, (float)inv_sub_factor);\n\n      // update all regular variables to account for subsampling\n      // swap full and subsampled storage!\n      n_valid_flow_Zbuffer = n_valid_flow_Zbuffer_sub;\n      d_ind_flow_Zbuffer_->swap(*d_ind_flow_Zbuffer_sub_);\n      d_valid_flow_Zbuffer_->swap(*d_valid_flow_Zbuffer_sub_);\n\n      // update segment starting indices\n      pose::extractLabelStartingIndices(d_seg_start_inds_->data(),\n                                        d_valid_flow_Zbuffer_->data(),\n                                        n_valid_flow_Zbuffer, _n_objects);\n      d_seg_start_inds_->copyTo(h_seg_start_inds_flow, _n_objects + 1);\n      //      printf(\"valsub flow %d\\n\",n_valid_flow_Zbuffer);\n    }\n\n    // disparity\n    int n_valid_disparity_Zbuffer_sub =\n        (int)floor((double)n_valid_disparity_Zbuffer * sub_factor);\n\n    if (n_valid_disparity_Zbuffer_sub > 0) {\n      subsample_ind_and_labels(d_ind_disparity_Zbuffer_sub_->data(),\n                               d_ind_disparity_Zbuffer_->data(),\n                               d_valid_disparity_Zbuffer_sub_->data(),\n                               d_valid_disparity_Zbuffer_->data(),\n                               n_valid_disparity_Zbuffer_sub,\n                               (float)inv_sub_factor);\n\n      // update all regular variables to account for subsampling\n      // swap full and subsampled storage!\n      n_valid_disparity_Zbuffer = n_valid_disparity_Zbuffer_sub;\n      d_ind_disparity_Zbuffer_->swap(*d_ind_disparity_Zbuffer_sub_);\n      d_valid_disparity_Zbuffer_->swap(*d_valid_disparity_Zbuffer_sub_);\n\n      // update segment starting indices\n      pose::extractLabelStartingIndices(d_seg_start_inds_->data(),\n                                        d_valid_disparity_Zbuffer_->data(),\n                                        n_valid_disparity_Zbuffer, _n_objects);\n      d_seg_start_inds_->copyTo(h_seg_start_inds_disparity, _n_objects + 1);\n      //      printf(\"valsub disp %d\\n\",n_valid_disparity_Zbuffer);\n    }\n\n    //    printf(\"after sub\\n\");\n    //    for(int i=0;i<(_n_objects+1);i++)\n    //      printf(\"se %d f %+07d d\n    // %+07d\\n\",i,h_seg_start_inds_flow[i],h_seg_start_inds_disparity[i]);\n\n  } // subsample\n\n  // compute segment lengths\n  std::vector<int> seg_lengths_flow(_n_objects);\n  getSegmentLengths(seg_lengths_flow, h_seg_start_inds_flow, _n_objects,\n                    n_valid_flow_Zbuffer);\n  std::vector<int> seg_lengths_disparity(_n_objects);\n  getSegmentLengths(seg_lengths_disparity, h_seg_start_inds_disparity,\n                    _n_objects, n_valid_disparity_Zbuffer);\n\n//  printf(\"after subsampling\\n\");\n//  printf(\"n_f %07d n_d %07d\\n\", n_valid_flow_Zbuffer,\n//         n_valid_disparity_Zbuffer);\n//  for (int i = 0; i < _n_objects; i++)\n//    printf(\"se %d f %+07d (%07d) d %+07d (%07d)\\n\", i,\n// h_seg_start_inds_flow[i],\n//           seg_lengths_flow[i], h_seg_start_inds_disparity[i],\n//           seg_lengths_disparity[i]);\n\n#ifdef TIME_STEPS\n  cudaEventRecord(start_sub, 0);\n#endif\n\n  // Gather flow and disparity\n  if (n_valid_flow_Zbuffer > 0)\n    gather_valid_flow_Zbuffer(\n        d_flow_compact_->data(), d_Zbuffer_flow_compact_->data(), d_flowx,\n        d_flowy, d_ar_flowx, d_ar_flowy, d_ind_flow_Zbuffer_->data(),\n        d_ZbufferArray, n_valid_flow_Zbuffer, _n_cols, _n_rows, Z_conv1,\n        Z_conv2);\n\n  if (n_valid_disparity_Zbuffer > 0)\n    gather_valid_disparity_Zbuffer(\n        d_disparity_compact_->data(), d_Zbuffer_normals_compact_->data(),\n        (const char *)d_disparity, d_ind_disparity_Zbuffer_->data(),\n        d_ZbufferArray, d_normalXArray, d_normalYArray, d_normalZArray,\n        n_valid_disparity_Zbuffer, _n_cols, _n_rows, Z_conv1, Z_conv2,\n        d_disparity_pitch);\n\n#ifdef TIME_STEPS\n  cudaThreadSynchronize();\n  cudaEventRecord(end_sub, 0);\n  cudaEventSynchronize(end_sub);\n  cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n  _compTimes.at(5) += (double)elapsed_time;\n#endif\n\n  // Gather index information\n  _segment_info.clear();\n\n  for (int o = 0; o < _n_objects; o++) {\n    int nf = seg_lengths_flow[o];\n    int nd = seg_lengths_disparity[o];\n    if ((nf > 0) || (nd > 0)) {\n      SegmentINFO tmp;\n      tmp.segment_ind = o;\n      tmp.n_values_flow = nf;\n      tmp.n_values_disparity = nd;\n      tmp.start_ind_flow = h_seg_start_inds_flow[o];\n      tmp.start_ind_disparity = h_seg_start_inds_disparity[o];\n      _segment_info.push_back(tmp);\n    }\n  }\n\n//    printf(\"------------------------------------\\n\");\n//    for(int o=0;o<_segment_info.size();o++) {\n//      SegmentINFO &tmp = _segment_info.at(o);\n//      printf(\"seg %d f_start %06d f_size %06d d_start %06d d_size\n// %06d\\n\",tmp.segment_ind,tmp.start_ind_flow,tmp.n_values_flow,tmp.start_ind_disparity,tmp.n_values_disparity);\n//    }\n//    printf(\"------------------------------------\\n\");\n\n#ifdef TIME_STEPS\n  cudaThreadSynchronize();\n  cudaEventRecord(end, 0);\n  cudaEventSynchronize(end);\n  cudaEventElapsedTime(&elapsed_time, start, end);\n  //  printf(\"preproc time : %2.4f ms\\n\",elapsed_time);\n  _compTimes.at(0) += (double)elapsed_time;\n#endif\n\n  // preparatory book-keeping\n\n  int n_segments = _segment_info.size();\n\n  if (n_segments > 0) {\n\n    std::vector<int> n_values_flow(n_segments);\n    std::vector<int> start_ind_flow(n_segments);\n    std::vector<int> n_values_disparity(n_segments);\n    std::vector<int> start_ind_disparity(n_segments);\n    std::vector<int> start_ind_res_flow(n_segments);\n    std::vector<int> start_ind_res_disparity(n_segments);\n\n    for (int s = 0; s < n_segments; s++) {\n      SegmentINFO &tmp = _segment_info.at(s);\n      n_values_flow.at(s) = tmp.n_values_flow;\n      start_ind_flow.at(s) = tmp.start_ind_flow;\n      n_values_disparity.at(s) = tmp.n_values_disparity;\n      start_ind_disparity.at(s) = tmp.start_ind_disparity;\n\n      start_ind_res_flow.at(s) = (s > 0) ? (start_ind_res_disparity.at(s - 1) +\n                                            n_values_disparity.at(s - 1))\n                                         : 0;\n      start_ind_res_disparity.at(s) =\n          start_ind_res_flow.at(s) + n_values_flow.at(s);\n    }\n\n    // Compute offset between residual input and output indices. Residuals are\n    // stored as [seg1_flow seg1_disp seg2_flow seg2_disp ... ] to facilitate\n    // median extraction\n\n    std::vector<int> offset_ind_res_flow(n_segments);\n    std::vector<int> offset_ind_res_disparity(n_segments);\n\n    for (int s = 0; s < n_segments; s++) {\n      offset_ind_res_flow.at(s) =\n          start_ind_res_flow.at(s) - start_ind_flow.at(s);\n      offset_ind_res_disparity.at(s) =\n          start_ind_res_disparity.at(s) - start_ind_disparity.at(s);\n    }\n\n    // Create segment translation table (map zero-based original segment indices\n    // to compressed segment indices)\n\n    std::vector<int> segment_translation_table(_n_objects);\n    for (int s = 0; s < n_segments; s++)\n      segment_translation_table.at(_segment_info.at(s).segment_ind) = s;\n\n    d_segment_translation_table_->copyFrom(segment_translation_table,\n                                           _n_objects);\n    d_n_values_flow_->copyFrom(n_values_flow, n_segments);\n    d_start_ind_flow_->copyFrom(start_ind_flow, n_segments);\n    d_n_values_disparity_->copyFrom(n_values_disparity, n_segments);\n    d_start_ind_disparity_->copyFrom(start_ind_disparity, n_segments);\n    d_offset_ind_res_flow_->copyFrom(offset_ind_res_flow, n_segments);\n    d_offset_ind_res_disparity_->copyFrom(offset_ind_res_disparity, n_segments);\n  }\n\n  // take care here since _d_CO and _d_CD's maximum sizes are not exactly\n  // determined in this way (especially the times 4)\n\n  dim3 threadBlock_normal(64, 1, 1);\n  int gridDim_x_normal_equations =\n      (n_segments > 0)\n          ? divUp(_MAX_N_VAL_ACCUM, n_segments * threadBlock_normal.x) * 4\n          : 0;\n  dim3 blockGrid_normal(gridDim_x_normal_equations, n_segments);\n  //  dim3 threadBlock_reduce_64(64,1);\n  //  dim3 blockGrid_reduce_flow(_N_CON_FLOW, n_segments);\n  //  dim3 blockGrid_reduce_disparity(_N_CON_DISP, n_segments);\n\n  dim3 threadBlock_reduce_64_mult(64, 4);\n  dim3 blockGrid_reduce_flow_mult(divUp(_N_CON_FLOW, 4), n_segments);\n  dim3 blockGrid_reduce_disparity_mult(divUp(_N_CON_DISP, 4), n_segments);\n\n/****************/\n/* OLS Estimate */\n/****************/\n\n#ifdef TIME_STEPS\n  cudaEventRecord(start, 0); // ols-time\n#endif\n\n  if (n_segments > 0) {\n\n#ifdef TIME_STEPS\n    cudaEventRecord(start_sub, 0);\n#endif\n\n    normal_eqs_flow(blockGrid_normal, threadBlock_normal, d_CO_->data(),\n                    d_flow_compact_->data(), d_Zbuffer_flow_compact_->data(),\n                    d_ind_flow_Zbuffer_->data(), _focal_length_x,\n                    _focal_length_y, _nodal_point_x, _nodal_point_y, _n_rows,\n                    _n_cols, d_n_values_flow_->data(),\n                    d_start_ind_flow_->data());\n    normal_eqs_disparity(blockGrid_normal, threadBlock_normal, d_CD_->data(),\n                         d_disparity_compact_->data(),\n                         d_Zbuffer_normals_compact_->data(),\n                         d_ind_disparity_Zbuffer_->data(), _focal_length_x,\n                         _focal_length_y, _nodal_point_x, _nodal_point_y,\n                         _baseline, _n_cols, d_n_values_disparity_->data(),\n                         d_start_ind_disparity_->data(), parameters_.w_disp_);\n\n#ifdef TIME_STEPS\n    cudaThreadSynchronize();\n    cudaEventRecord(end_sub, 0);\n    cudaEventSynchronize(end_sub);\n    cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n    _compTimes.at(6) += (double)elapsed_time;\n#endif\n\n#ifdef TIME_STEPS\n    cudaEventRecord(start_sub, 0);\n#endif\n\n    reduce_normal_eqs_64_mult_constr(blockGrid_reduce_flow_mult,\n                                     threadBlock_reduce_64_mult,\n                                     d_CO_reduced_->data(), d_CO_->data(),\n                                     gridDim_x_normal_equations, _N_CON_FLOW);\n    reduce_normal_eqs_64_mult_constr(blockGrid_reduce_disparity_mult,\n                                     threadBlock_reduce_64_mult,\n                                     d_CD_reduced_->data(), d_CD_->data(),\n                                     gridDim_x_normal_equations, _N_CON_DISP);\n\n//    reduce_normal_eqs_64_GPU<<<blockGrid_reduce_flow,threadBlock_reduce_64>>>(_d_CO_reduced,\n// _d_CO, gridDim_x_normal_equations);\n//    reduce_normal_eqs_64_GPU<<<blockGrid_reduce_disparity,threadBlock_reduce_64>>>(_d_CD_reduced,\n// _d_CD, gridDim_x_normal_equations);\n\n#ifdef TIME_STEPS\n    cudaThreadSynchronize();\n    cudaEventRecord(end_sub, 0);\n    cudaEventSynchronize(end_sub);\n    cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n    _compTimes.at(7) += (double)elapsed_time;\n#endif\n  }\n\n  d_CO_reduced_->copyTo(h_CO_reduced_);\n  d_CD_reduced_->copyTo(h_CD_reduced_);\n\n#ifdef TIME_STEPS\n  cudaEventRecord(start_sub, 0);\n#endif\n\n  // Solve systems\n  std::vector<float> dTdR(6 * n_segments);\n  for (int s = 0; s < n_segments; s++) {\n    int curr_part = _segment_info.at(s).segment_ind;\n    segment_normal_eqs_.at(curr_part).compose(\n        &h_CO_reduced_.at(_N_CON_FLOW * s), &h_CD_reduced_.at(_N_CON_DISP * s));\n    segment_normal_eqs_.at(curr_part).solve(&dTdR.at(6 * s));\n  }\n\n#ifdef TIME_STEPS\n  cudaThreadSynchronize();\n  cudaEventRecord(end_sub, 0);\n  cudaEventSynchronize(end_sub);\n  cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n  _compTimes.at(8) += (double)elapsed_time;\n#endif\n\n  // Copy to device memory\n  d_dTR_->copyFrom(dTdR, 6 * n_segments);\n\n  //  for(int s=0;s<n_segments;s++) {\n  //    printf(\"seg %d - \",_segment_info.at(s).segment_ind);\n  //    for(int i=0;i<6;i++)\n  //      printf(\"%+03.4f \",dTdR[s*6+i]);\n  //    printf(\"\\n\");\n  //  }\n\n  // Store OLS estimates\n  _OLSDeltaPoses.clear();\n  for (int i = 0; i < n_segments; i++)\n    _OLSDeltaPoses.push_back(TranslationRotation3D(&dTdR[i * 6]));\n\n#ifdef TIME_STEPS\n  cudaThreadSynchronize();\n  cudaEventRecord(end, 0);\n  cudaEventSynchronize(end);\n  cudaEventElapsedTime(&elapsed_time, start, end);\n  //  printf(\"OLS time : %2.4f ms\\n\",elapsed_time);\n  _compTimes.at(1) += (double)elapsed_time;\n#endif\n\n/****************/\n/* M-estimation */\n/****************/\n\n#ifdef TIME_STEPS\n  cudaEventRecord(start, 0); // robust-time\n#endif\n\n  for (int it = 0; it < parameters_.n_icp_inner_it_; it++) {\n\n    // Compute flow and disparity residuals\n\n    if (n_segments > 0) {\n\n#ifdef TIME_STEPS\n      cudaEventRecord(start_sub, 0);\n#endif\n\n      dim3 threadBlock_res(256, 1);\n\n      if (n_valid_flow_Zbuffer > 0) {\n        dim3 blockGrid_res(divUp(n_valid_flow_Zbuffer, threadBlock_res.x), 1);\n        flow_absolute_residual_scalable(\n            blockGrid_res, threadBlock_res, d_abs_res_->data(),\n            d_flow_compact_->data(), d_Zbuffer_flow_compact_->data(),\n            d_ind_flow_Zbuffer_->data(), d_valid_flow_Zbuffer_->data(),\n            _focal_length_x, _focal_length_y, _nodal_point_x, _nodal_point_y,\n            _n_rows, _n_cols, n_valid_flow_Zbuffer,\n            d_offset_ind_res_flow_->data(),\n            d_segment_translation_table_->data(), parameters_.w_flow_,\n            parameters_.w_ar_flow_, d_dTR_->data());\n      }\n\n      if (n_valid_disparity_Zbuffer > 0) {\n        dim3 blockGrid_res(divUp(n_valid_disparity_Zbuffer, threadBlock_res.x),\n                           1);\n        disp_absolute_residual_scalable(\n            blockGrid_res, threadBlock_res, d_abs_res_->data(),\n            d_disparity_compact_->data(), d_Zbuffer_normals_compact_->data(),\n            d_ind_disparity_Zbuffer_->data(),\n            d_valid_disparity_Zbuffer_->data(), _focal_length_x,\n            _focal_length_y, _nodal_point_x, _nodal_point_y, _baseline, _n_cols,\n            n_valid_disparity_Zbuffer, d_offset_ind_res_disparity_->data(),\n            d_segment_translation_table_->data(), parameters_.w_disp_,\n            d_dTR_->data());\n      }\n\n#ifdef TIME_STEPS\n      cudaThreadSynchronize();\n      cudaEventRecord(end_sub, 0);\n      cudaEventSynchronize(end_sub);\n      cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n      _compTimes.at(9) += (double)elapsed_time;\n#endif\n\n#ifdef TIME_STEPS\n      cudaEventRecord(start_sub, 0);\n#endif\n\n      // Median absolute residuals\n      std::vector<float> abs_res_scales(n_segments);\n      int pp[n_segments];\n      for (int s = 0; s < n_segments; s++) {\n        SegmentINFO &tmp = _segment_info.at(s);\n        pp[s] = tmp.n_values_flow + tmp.n_values_disparity;\n      }\n      approx_multiple_medians_shuffle_cuda(\n          abs_res_scales.data(), d_abs_res_->data(), d_median_tmp_->data(),\n          d_random_numbers_->data(), pp, n_segments, d_median_n_in_->data(),\n          d_median_start_inds_->data());\n\n      for (int s = 0; s < n_segments; s++)\n        abs_res_scales.at(s) *= 6.9460f;\n\n      d_abs_res_scales_->copyFrom(abs_res_scales, n_segments);\n\n#ifdef TIME_STEPS\n      cudaThreadSynchronize();\n      cudaEventRecord(end_sub, 0);\n      cudaEventSynchronize(end_sub);\n      cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n      _compTimes.at(10) += (double)elapsed_time;\n#endif\n\n//  for(int s=0;s<n_segments;s++)\n//    printf(\"%2.5f \",abs_res_scales[s]);\n//  printf(\"\\n\");\n\n// Weighted constraints\n\n#ifdef TIME_STEPS\n      cudaEventRecord(start_sub, 0);\n#endif\n\n      normal_eqs_flow_weighted(\n          blockGrid_normal, threadBlock_normal, d_CO_->data(),\n          d_flow_compact_->data(), d_Zbuffer_flow_compact_->data(),\n          d_ind_flow_Zbuffer_->data(), _focal_length_x, _focal_length_y,\n          _nodal_point_x, _nodal_point_y, _n_rows, _n_cols,\n          d_n_values_flow_->data(), d_start_ind_flow_->data(),\n          d_abs_res_scales_->data(), parameters_.w_flow_,\n          parameters_.w_ar_flow_, d_dTR_->data());\n\n      normal_eqs_disparity_weighted(\n          blockGrid_normal, threadBlock_normal, d_CD_->data(),\n          d_disparity_compact_->data(), d_Zbuffer_normals_compact_->data(),\n          d_ind_disparity_Zbuffer_->data(), _focal_length_x, _focal_length_y,\n          _nodal_point_x, _nodal_point_y, _baseline, _n_cols,\n          d_n_values_disparity_->data(), d_start_ind_disparity_->data(),\n          d_abs_res_scales_->data(), parameters_.w_disp_, d_dTR_->data());\n\n#ifdef TIME_STEPS\n      cudaThreadSynchronize();\n      cudaEventRecord(end_sub, 0);\n      cudaEventSynchronize(end_sub);\n      cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n      _compTimes.at(6) += (double)elapsed_time;\n#endif\n\n#ifdef TIME_STEPS\n      cudaEventRecord(start_sub, 0);\n#endif\n\n      reduce_normal_eqs_64_mult_constr(blockGrid_reduce_flow_mult,\n                                       threadBlock_reduce_64_mult,\n                                       d_CO_reduced_->data(), d_CO_->data(),\n                                       gridDim_x_normal_equations, _N_CON_FLOW);\n      reduce_normal_eqs_64_mult_constr(blockGrid_reduce_disparity_mult,\n                                       threadBlock_reduce_64_mult,\n                                       d_CD_reduced_->data(), d_CD_->data(),\n                                       gridDim_x_normal_equations, _N_CON_DISP);\n\n//      reduce_normal_eqs_64_GPU<<<blockGrid_reduce_flow,threadBlock_reduce_64>>>(_d_CO_reduced,\n// _d_CO, gridDim_x_normal_equations);\n//      reduce_normal_eqs_64_GPU<<<blockGrid_reduce_disparity,threadBlock_reduce_64>>>(_d_CD_reduced,\n// _d_CD, gridDim_x_normal_equations);\n\n#ifdef TIME_STEPS\n      cudaThreadSynchronize();\n      cudaEventRecord(end_sub, 0);\n      cudaEventSynchronize(end_sub);\n      cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n      _compTimes.at(7) += (double)elapsed_time;\n#endif\n    }\n\n    d_CO_reduced_->copyTo(h_CO_reduced_);\n    d_CD_reduced_->copyTo(h_CD_reduced_);\n\n#ifdef TIME_STEPS\n    cudaEventRecord(start_sub, 0);\n#endif\n\n    // Solve systems\n    for (int s = 0; s < n_segments; s++) {\n      int curr_part = _segment_info.at(s).segment_ind;\n      segment_normal_eqs_.at(curr_part)\n          .compose(&h_CO_reduced_.at(_N_CON_FLOW * s),\n                   &h_CD_reduced_.at(_N_CON_DISP * s));\n      segment_normal_eqs_.at(curr_part).solve(&dTdR.at(6 * s));\n    }\n\n#ifdef TIME_STEPS\n    cudaThreadSynchronize();\n    cudaEventRecord(end_sub, 0);\n    cudaEventSynchronize(end_sub);\n    cudaEventElapsedTime(&elapsed_time, start_sub, end_sub);\n    _compTimes.at(8) += (double)elapsed_time;\n#endif\n\n    // Copy to device memory\n    d_dTR_->copyFrom(dTdR, 6 * n_segments);\n\n    //    printf(\"ROBUST ITERATION %d\\n\",it);\n    //    printf(\"-------------------\\n\");\n    //    for(int s=0;s<n_segments;s++) {\n    //      printf(\"seg %d - \",_segment_info.at(s).segment_ind);\n    //      for(int i=0;i<6;i++)\n    //        printf(\"%+03.4f \",dTdR[s*6+i]);\n    //      printf(\"\\n\");\n    //    }\n  }\n\n  // Store robust estimates\n  _robustDeltaPoses.clear();\n  for (int i = 0; i < n_segments; i++)\n    _robustDeltaPoses.push_back(TranslationRotation3D(&dTdR[i * 6]));\n\n#ifdef TIME_STEPS\n  cudaThreadSynchronize();\n  cudaEventRecord(end, 0);\n  cudaEventSynchronize(end);\n  cudaEventElapsedTime(&elapsed_time, start, end);\n  //  printf(\"robust time : %2.4f ms\\n\",elapsed_time);\n  _compTimes.at(2) += (double)elapsed_time;\n#endif\n}\n}\n", "meta": {"hexsha": "88fb8a22afc700334e56ff342df99c4a53580f89", "size": 54821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation/src/d_multiple_rigid_poses.cpp", "max_stars_repo_name": "carlo-/simtrack", "max_stars_repo_head_hexsha": "8209c5305c76c6e5d7783fbaea992959f7b44f71", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 99.0, "max_stars_repo_stars_event_min_datetime": "2015-07-06T11:18:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T08:20:12.000Z", "max_issues_repo_path": "pose_estimation/src/d_multiple_rigid_poses.cpp", "max_issues_repo_name": "carlo-/simtrack", "max_issues_repo_head_hexsha": "8209c5305c76c6e5d7783fbaea992959f7b44f71", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 44.0, "max_issues_repo_issues_event_min_datetime": "2015-10-09T19:11:29.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-25T03:51:39.000Z", "max_forks_repo_path": "pose_estimation/src/d_multiple_rigid_poses.cpp", "max_forks_repo_name": "carlo-/simtrack", "max_forks_repo_head_hexsha": "8209c5305c76c6e5d7783fbaea992959f7b44f71", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2015-07-06T11:36:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T01:32:18.000Z", "avg_line_length": 38.2561060712, "max_line_length": 128, "alphanum_fraction": 0.6628299374, "num_tokens": 14129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.23017117030618786}}
{"text": "﻿// This file is part of the dune-gdt project:\n//   http://users.dune-project.org/projects/dune-gdt\n// Copyright holders: Felix Schindler\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n\n#ifndef DUNE_GDT_OPERATORS_PROLONGATIONS_HH\n#define DUNE_GDT_OPERATORS_PROLONGATIONS_HH\n\n#include <vector>\n#include <limits>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/dynmatrix.hh>\n\n#include <dune/stuff/common/type_utils.hh>\n#include <dune/stuff/common/vector.hh>\n#include <dune/stuff/functions/interfaces.hh>\n#include <dune/stuff/grid/boundaryinfo.hh>\n#include <dune/stuff/grid/intersection.hh>\n#include <dune/stuff/la/container.hh>\n#include <dune/stuff/la/solver.hh>\n\n#include <dune/geometry/quadraturerules.hh>\n\n#include <dune/stuff/grid/search.hh>\n\n#include <dune/gdt/exceptions.hh>\n#include <dune/gdt/discretefunction/default.hh>\n#include <dune/gdt/spaces/cg/fem.hh>\n#include <dune/gdt/spaces/cg/pdelab.hh>\n\n\nnamespace Dune {\nnamespace GDT {\n\nnamespace Spaces {\nnamespace DG {\ntemplate<class GridPartImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols>\nclass FemBased;\n}\ntemplate<class SpaceImp>\nclass Block;\n}\n\nnamespace Operators {\n\n\n/**\n *  \\note The automatic detection of the right integration order might fail, so you might want to specify\n *        over_integrate. The reason is that in order to locally evaluate the source we first have to create a\n *        quadrature, the correct order of wich we guess by taking the sources order on the first entity.\n *  \\note We would have liked to do something like this and match on implementations of SpaceInterface:\\code\ntemplate< class T, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\nvoid apply(const ConstDiscreteFunction< SpaceInterface< T >, VS >& source,\n           DiscreteFunction< Spaces::DG::FemBased< GPR, pR, RR, rR, rCR >, VR >& range) const\n{\n  static_assert(Dune::AlwaysFalse< T >::value, \"Not implemented for this combination of source and range!\");\n}\\endcode\n *        but that gave compile errors (the compiler just could not match the first argument for whatever reason). This\n *        is why we need all combinations of spaces below which are just compile time checks and forwards.\n *\n *  \\todo Create a Redirect class templatized with space/vector to check that its a const/discrete function with a\n *        method which extracts the correct space if needed. This should give better compile errors.\n */\ntemplate< class GridViewType >\nclass L2Prolongation\n{\n  typedef typename GridViewType::template Codim< 0 >::Entity EntityType;\n  typedef typename GridViewType::ctype DomainFieldType;\n  static const size_t dimDomain = GridViewType::dimension;\n\npublic:\n  L2Prolongation(const GridViewType& grid_view)\n    : grid_view_(grid_view)\n  {}\n\n  // Source: Spaces::CG::FemBased\n  // Range:  Spaces::DG::FemBased\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  void apply(const ConstDiscreteFunction< Spaces::CG::FemBased< GPS, pS, RS, rS, rCS >, VS >& /*source*/,\n             DiscreteFunction< Spaces::DG::FemBased< GPR, pR, RR, rR, rCR >, VR >& /*range*/) const\n  {\n    static_assert(Dune::AlwaysFalse< GPS >::value, \"Not implemented for this combination of source and range!\");\n  }\n\n  template< class GPS, int pS, class R, size_t r, size_t rC, class VS, class GPR, int pR, class VR >\n  inline void apply(const ConstDiscreteFunction< Spaces::CG::FemBased< GPS, pS, R, r, rC >, VS >& source,\n                    DiscreteFunction< Spaces::DG::FemBased< GPR, pR, R, r, rC >, VR >&\n                      range) const\n  {\n    prolong_onto_dg_fem_localfunctions_wrapper(source, range);\n  }\n\n  // Source: Spaces::DG::FemBased\n  // Range:  Spaces::DG::FemBased\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  void apply(const ConstDiscreteFunction< Spaces::DG::FemBased< GPS, pS, RS, rS, rCS >, VS >& /*source*/,\n             DiscreteFunction< Spaces::DG::FemBased< GPR, pR, RR, rR, rCR >, VR >& /*range*/) const\n  {\n    static_assert(Dune::AlwaysFalse< GPS >::value, \"Not implemented for this combination of source and range!\");\n  }\n\n  template< class GPS, int pS, class R, size_t r, size_t rC, class VS, class GPR, int pR, class VR >\n  inline void apply(const ConstDiscreteFunction\n                      < Spaces::DG::FemBased< GPS, pS, R, r, rC >, VS >& source,\n                    DiscreteFunction< Spaces::DG::FemBased< GPR, pR, R, r, rC >, VR >&\n                      range) const\n  {\n    prolong_onto_dg_fem_localfunctions_wrapper(source, range);\n  }\n\n  template< class GPS, int pS, class R, size_t r, size_t rC, class VS, class GPR, int pR, class VR >\n  inline void apply(const ConstDiscreteFunction\n                      < Spaces::Block< Spaces::DG::FemBased< GPS, pS, R, r, rC > >, VS >& source,\n                    DiscreteFunction< Spaces::Block< Spaces::DG::FemBased< GPR, pR, R, r, rC > >, VR >&\n                      range) const\n  {\n    prolong_onto_dg_fem_localfunctions_wrapper(source, range);\n  }\n\n  template< class GPS, int pS, class R, size_t r, size_t rC, class VS, class GPR, int pR, class VR >\n  inline void apply(const ConstDiscreteFunction\n                      < Spaces::Block< Spaces::DG::FemBased< GPS, pS, R, r, rC > >, VS >& source,\n                    DiscreteFunction< Spaces::DG::FemBased< GPR, pR, R, r, rC >, VR >& range) const\n  {\n    prolong_onto_dg_fem_localfunctions_wrapper(source, range);\n  }\n\nprivate:\n  template< class SourceFunctionType, class RangeFunctionType >\n  void prolong_onto_dg_fem_localfunctions_wrapper(const SourceFunctionType& source, RangeFunctionType& range) const\n  {\n    typedef typename RangeFunctionType::DomainType DomainType;\n    typedef typename RangeFunctionType::RangeType RangeType;\n    typedef typename RangeFunctionType::RangeFieldType RangeFieldType;\n    typedef typename Stuff::LA::Container< RangeFieldType, Stuff::LA::default_dense_backend >::MatrixType\n        LocalMatrixType;\n    typedef typename Stuff::LA::Container< RangeFieldType, Stuff::LA::default_dense_backend >::VectorType\n        LocalVectorType;\n    // clear\n    range.vector() *= 0.0;\n    // create search in the source grid part\n    typedef typename SourceFunctionType::SpaceType::GridViewType SourceGridViewType;\n    typedef Stuff::Grid::EntityInlevelSearch< SourceGridViewType > EntitySearch;\n    EntitySearch entity_search(source.space().grid_view());\n    // guess the polynomial order of the source by hoping that they are the same for all entities\n    const size_t source_order = source.local_function(*source.space().grid_view().template begin< 0 >())->order();\n    // walk the grid\n    RangeType source_value(0);\n    std::vector< RangeType > basis_values(range.space().mapper().maxNumDofs());\n    const auto entity_it_end = grid_view_.template end< 0 >();\n    for (auto entity_it = grid_view_.template begin< 0 >(); entity_it != entity_it_end; ++entity_it) {\n      // prepare\n      const auto& entity = *entity_it;\n      const auto local_basis = range.space().base_function_set(entity);\n      auto local_range = range.local_discrete_function(entity);\n      LocalMatrixType local_matrix(local_basis.size(), local_basis.size(), RangeFieldType(0));\n      LocalVectorType local_vector(local_basis.size(), RangeFieldType(0));\n      LocalVectorType local_DoFs(local_basis.size(), RangeFieldType(0));\n      // create quadrature\n      const auto integrand_order = std::max(source_order, local_basis.order()) + local_basis.order();\n      const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain >::rule(entity.type(),\n                                                                                   boost::numeric_cast< int >(integrand_order));\n      // get global quadrature points\n      std::vector< DomainType > quadrature_points;\n      for (const auto& quadrature_point : quadrature)\n        quadrature_points.emplace_back(entity.geometry().global(quadrature_point.position()));\n      // get source entities\n      const auto source_entity_ptr_unique_ptrs = entity_search(quadrature_points);\n      assert(source_entity_ptr_unique_ptrs.size() >= quadrature_points.size());\n      // loop over all quadrature points\n      size_t pp = 0;\n      for (const auto& quadrature_point : quadrature) {\n        const auto local_point = quadrature_point.position();\n        const auto quadrature_weight = quadrature_point.weight();\n        const auto integration_element = entity.geometry().integrationElement(local_point);\n        // evaluate source\n        const auto& source_entity_ptr_unique_ptr = source_entity_ptr_unique_ptrs[pp];\n        if (source_entity_ptr_unique_ptr) {\n          const auto source_entity_ptr = *source_entity_ptr_unique_ptr;\n          const auto& source_entity = *source_entity_ptr;\n          const auto local_source = source.local_function(source_entity);\n          local_source->evaluate(source_entity.geometry().local(entity.geometry().global(local_point)), source_value);\n        } else\n          source_value *= 0.0;\n        // evaluate\n        local_basis.evaluate(local_point, basis_values);\n        // compute integrals\n        for (size_t ii = 0; ii < local_basis.size(); ++ii) {\n          local_vector[ii] += integration_element * quadrature_weight * (source_value * basis_values[ii]);\n          for (size_t jj = 0; jj < local_basis.size(); ++jj) {\n            local_matrix.add_to_entry(ii,\n                                      jj,\n                                      integration_element * quadrature_weight * (basis_values[ii] * basis_values[jj]));\n          }\n        }\n        ++pp;\n      } // loop over all quadrature points\n      // compute local DoFs\n      try {\n        Stuff::LA::Solver< LocalMatrixType >(local_matrix).apply(local_vector, local_DoFs);\n      } catch (Stuff::Exceptions::linear_solver_failed& ee) {\n        DUNE_THROW(Exceptions::prolongation_error,\n                   \"L2 prolongation failed because a local matrix could not be inverted!\\n\\n\"\n                   << \"This was the original error: \" << ee.what());\n      }\n      // set local DoFs\n      auto local_range_vector = local_range->vector();\n      assert(local_range_vector.size() == local_DoFs.size());\n      for (size_t ii = 0; ii < local_range_vector.size(); ++ii)\n        local_range_vector.set(ii, local_DoFs.get_entry(ii));\n    } // walk the grid\n  } // ... prolong_onto_dg_fem_localfunctions_wrapper(...)\n\n  const GridViewType& grid_view_;\n}; // class L2Prolongation\n\n\n/**\n *  \\note We would have liked to do something like this and match on implementations of SpaceInterface:\\code\ntemplate< class T, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\nvoid apply(const ConstDiscreteFunction< SpaceInterface< T >, VS >& source,\n           DiscreteFunction< Spaces::CG::FemBased< GPR, pR, RR, rR, rCR >, VR >& range) const\n{\n  static_assert(Dune::AlwaysFalse< T >::value, \"Not implemented for this combination of source and range!\");\n}\\endcode\n *        but that gave compile errors (the compiler just could not match the first argument for whatever reason). This\n *        is why we need all combinations of spaces below which are just compile time checks and forwards.\n */\ntemplate< class GridViewType >\nclass LagrangeProlongation\n{\npublic:\n  typedef typename GridViewType::ctype DomainFieldType;\n  static const size_t dimDomain = GridViewType::dimension;\n\n  LagrangeProlongation(const GridViewType& grid_view)\n    : grid_view_(grid_view)\n  {}\n\n  // Source: Spaces::CG::FemBased\n  // Range:  Spaces::CG::FemBased\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  void apply(const ConstDiscreteFunction< Spaces::CG::FemBased< GPS, pS, RS, rS, rCS >, VS >& /*source*/,\n             DiscreteFunction< Spaces::CG::FemBased< GPR, pR, RR, rR, rCR >, VR >& /*range*/) const\n  {\n    static_assert(Dune::AlwaysFalse< GPS >::value, \"Not implemented for this combination of source and range!\");\n  }\n\n  template< class GPS, int pS, class R, size_t r, class VS, class GPR, int pR, class VR >\n  inline void apply(const ConstDiscreteFunction< Spaces::CG::FemBased< GPS, pS, R, r, 1 >, VS >& source,\n                    DiscreteFunction< Spaces::CG::FemBased< GPR, pR, R, r, 1 >, VR >& range) const\n  {\n    redirect_to_appropriate_apply(source, range);\n  }\n\n  // Source: Spaces::DG::FemBased\n  // Range:  Spaces::CG::FemBased\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  void apply(const ConstDiscreteFunction< Spaces::DG::FemBased< GPS, pS, RS, rS, rCS >, VS >& /*source*/,\n             DiscreteFunction< Spaces::CG::FemBased< GPR, pR, RR, rR, rCR >, VR >& /*range*/) const\n  {\n    static_assert(Dune::AlwaysFalse< GPS >::value, \"Not implemented for this combination of source and range!\");\n  }\n\n  template< class GPS, int pS, class R, size_t r, class VS, class GPR, int pR, class VR >\n  inline void apply(const ConstDiscreteFunction\n                      < Spaces::DG::FemBased< GPS, pS, R, r, 1 >, VS >& source,\n                    DiscreteFunction< Spaces::CG::FemBased< GPR, pR, R, r, 1 >, VR >& range) const\n  {\n    redirect_to_appropriate_apply(source, range);\n  }\n\n  // Source: Spaces::CG::PdelabBased\n  // Range:  Spaces::CG::PdelabBased\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  void apply(const ConstDiscreteFunction< Spaces::CG::PdelabBased< GPS, pS, RS, rS, rCS >, VS >& /*source*/,\n             DiscreteFunction< Spaces::CG::PdelabBased< GPR, pR, RR, rR, rCR >, VR >& /*range*/) const\n  {\n    static_assert(Dune::AlwaysFalse< GPS >::value, \"Not implemented for this combination of source and range!\");\n  }\n\n  template< class GPS, int pS, class R, size_t r, size_t rC, class VS, class GPR, class VR >\n  inline void apply(const ConstDiscreteFunction < Spaces::CG::PdelabBased< GPS, pS, R, r, rC >, VS >&\n                      source,\n                    DiscreteFunction< Spaces::CG::PdelabBased< GPR, 1, R, r, rC >, VR >& range) const\n  {\n    redirect_to_appropriate_apply(source, range);\n  }\n\nprivate:\n  template< class SourceType, class RangeType >\n  void redirect_to_appropriate_apply(const SourceType& source, RangeType& range) const\n  {\n    // create search in the source grid part\n    typedef typename SourceType::SpaceType::GridViewType SourceGridViewType;\n    typedef Stuff::Grid::EntityInlevelSearch< SourceGridViewType > EntitySearch;\n    EntitySearch entity_search(source.space().grid_view());\n    // set all range dofs to infinity\n    const auto infinity = std::numeric_limits< typename RangeType::RangeFieldType >::infinity();\n    for (size_t ii = 0; ii < range.vector().size(); ++ii)\n      range.vector().set_entry(ii, infinity);\n    // walk the grid\n    const auto entity_it_end = grid_view_.template end< 0 >();\n    for (auto entity_it = grid_view_.template begin< 0 >();\n         entity_it != entity_it_end;\n         ++entity_it) {\n      const auto& entity = *entity_it;\n      // get global lagrange point coordinates\n      const auto lagrange_point_set = range.space().lagrange_points(entity);\n      typedef FieldVector< typename SourceGridViewType::ctype, SourceGridViewType::dimension > DomainType;\n      std::vector< DomainType > lagrange_points(lagrange_point_set.size());\n      for (size_t ii = 0; ii < lagrange_point_set.size(); ++ii)\n        lagrange_points[ii] = entity.geometry().global(lagrange_point_set[ii]);\n      // get source entities\n      const auto source_entity_ptrs = entity_search(lagrange_points);\n      assert(source_entity_ptrs.size() == lagrange_points.size());\n      // get range\n      auto local_range = range.local_discrete_function(entity);\n      auto local_range_DoF_vector = local_range->vector();\n      // do the actual work (see below)\n      apply_local(source, lagrange_points, source_entity_ptrs, local_range_DoF_vector);\n    } // walk the grid\n  } // ... redirect_to_appropriate_apply(...)\n\n  template< class SourceType, class LagrangePointsType, class EntityPointers, class LocalDoFVectorType >\n  void apply_local(const SourceType& source,\n                   const LagrangePointsType& lagrange_points,\n                   const EntityPointers& source_entity_ptr_unique_ptrs,\n                   LocalDoFVectorType& range_DoF_vector) const\n  {\n    static const size_t dimRange = SourceType::dimRange;\n    size_t kk = 0;\n    assert(source_entity_ptr_unique_ptrs.size() >= lagrange_points.size());\n    for (size_t ii = 0; ii < lagrange_points.size(); ++ii) {\n      if (std::isinf(range_DoF_vector.get(kk))) {\n        const auto& global_point = lagrange_points[ii];\n        // evaluate source function\n        const auto& source_entity_ptr_unique_ptr = source_entity_ptr_unique_ptrs[ii];\n        if (source_entity_ptr_unique_ptr) {\n          const auto source_entity_ptr = *source_entity_ptr_unique_ptr;\n          const auto& source_entity = *source_entity_ptr;\n          const auto local_source_point = source_entity.geometry().local(global_point);\n          const auto local_source = source.local_function(source_entity);\n          const auto source_value = local_source->evaluate(local_source_point);\n          for (size_t jj = 0; jj < dimRange; ++jj, ++kk)\n            range_DoF_vector.set(kk, source_value[jj]);\n        } else\n          for (size_t jj = 0; jj < dimRange; ++jj, ++kk)\n            range_DoF_vector.set(kk, 0.0);\n      }\n      else\n        kk += dimRange;\n    }\n  } // ... apply_local(...)\n\n  const GridViewType& grid_view_;\n}; // class LagrangeProlongation\n\n\ntemplate< class GridViewType >\nclass Prolongation\n{\npublic:\n  typedef typename GridViewType::ctype DomainFieldType;\n  static const size_t dimDomain = GridViewType::dimension;\n\n  Prolongation(const GridViewType& grid_view)\n    : l2_prolongation_operator_(grid_view)\n    , lagrange_prolongation_operator_(grid_view)\n  {}\n\n  template< class SourceType, class RangeType >\n  void apply(const SourceType& source, RangeType& range) const\n  {\n    redirect_to_appropriate_operator(source, range);\n  }\n\nprivate:\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  inline void redirect_to_appropriate_operator(const ConstDiscreteFunction< Spaces::CG::FemBased\n                                                  < GPS, pS, RS, rS, rCS >, VS >& source,\n                                               DiscreteFunction< Spaces::DG::FemBased\n                                                  < GPR, pR, RR, rR, rCR >, VR >& range) const\n  {\n    l2_prolongation_operator_.apply(source, range);\n  }\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  inline void redirect_to_appropriate_operator(const ConstDiscreteFunction\n                                                  < Spaces::DG::FemBased\n                                                    < GPS, pS, RS, rS, rCS >, VS >& source,\n                                               DiscreteFunction\n                                                  < Spaces::DG::FemBased\n                                                    < GPR, pR, RR, rR, rCR >, VR >& range) const\n  {\n    l2_prolongation_operator_.apply(source, range);\n  }\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  inline void redirect_to_appropriate_operator(const ConstDiscreteFunction\n                                                  < Spaces::Block< Spaces::DG::FemBased\n                                                    < GPS, pS, RS, rS, rCS > >, VS >& source,\n                                               DiscreteFunction\n                                                  < Spaces::Block< Spaces::DG::FemBased\n                                                    < GPR, pR, RR, rR, rCR > >, VR >& range) const\n  {\n    l2_prolongation_operator_.apply(source, range);\n  }\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  inline void redirect_to_appropriate_operator(const ConstDiscreteFunction\n                                                  < Spaces::Block< Spaces::DG::FemBased\n                                                    < GPS, pS, RS, rS, rCS > >, VS >& source,\n                                               DiscreteFunction\n                                                  < Spaces::DG::FemBased\n                                                    < GPR, pR, RR, rR, rCR >, VR >& range) const\n  {\n    l2_prolongation_operator_.apply(source, range);\n  }\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  inline void redirect_to_appropriate_operator(const ConstDiscreteFunction\n                                                  < Spaces::CG::FemBased\n                                                    < GPS, pS, RS, rS, rCS >, VS >& source,\n                                               DiscreteFunction\n                                                  < Spaces::CG::FemBased\n                                                    < GPR, pR, RR, rR, rCR >, VR >& range) const\n  {\n    lagrange_prolongation_operator_.apply(source, range);\n  }\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  inline void redirect_to_appropriate_operator(const ConstDiscreteFunction\n                                                  < Spaces::DG::FemBased\n                                                    < GPS, pS, RS, rS, rCS >, VS >& source,\n                                               DiscreteFunction\n                                                  < Spaces::CG::FemBased\n                                                    < GPR, pR, RR, rR, rCR >, VR >& range) const\n  {\n    lagrange_prolongation_operator_.apply(source, range);\n  }\n\n  template< class GPS, int pS, class RS, size_t rS, size_t rCS, class VS,\n            class GPR, int pR, class RR, size_t rR, size_t rCR, class VR >\n  inline void redirect_to_appropriate_operator(const ConstDiscreteFunction\n                                                  < Spaces::CG::PdelabBased\n                                                    < GPS, pS, RS, rS, rCS >, VS >& source,\n                                               DiscreteFunction\n                                                  < Spaces::CG::PdelabBased\n                                                    < GPR, pR, RR, rR, rCR >, VR >& range) const\n  {\n    lagrange_prolongation_operator_.apply(source, range);\n  }\n\n  const L2Prolongation< GridViewType > l2_prolongation_operator_;\n  const LagrangeProlongation< GridViewType > lagrange_prolongation_operator_;\n}; // class Prolongation\n\n\ntemplate< class GridViewType, class SourceType, class RangeType >\nvoid prolong(const GridViewType& grid_view, const SourceType& source, RangeType& range)\n{\n  const Prolongation< GridViewType > prolongation_operator(grid_view);\n  prolongation_operator.apply(source, range);\n}\n\n\ntemplate< class SourceType, class RangeType >\nvoid prolong(const SourceType& source, RangeType& range)\n{\n  const Prolongation< typename RangeType::SpaceType::GridViewType > prolongation_operator(range.space().grid_view());\n  prolongation_operator.apply(source, range);\n}\n\n\n} // namespace Operators\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_OPERATORS_PROLONGATIONS_HH\n", "meta": {"hexsha": "6c570e05b2f07d9c935216eb53cfa4f7ab24c402", "size": 23907, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/operators/prolongations.hh", "max_stars_repo_name": "ftalbrecht/dune-gdt", "max_stars_repo_head_hexsha": "574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dune/gdt/operators/prolongations.hh", "max_issues_repo_name": "ftalbrecht/dune-gdt", "max_issues_repo_head_hexsha": "574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dune/gdt/operators/prolongations.hh", "max_forks_repo_name": "ftalbrecht/dune-gdt", "max_forks_repo_head_hexsha": "574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-13T11:51:27.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-13T11:51:27.000Z", "avg_line_length": 47.9098196393, "max_line_length": 128, "alphanum_fraction": 0.6398126072, "num_tokens": 5939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23017117030618783}}
{"text": "//Tencent is pleased to support the open source community by making FeatherCNN available.\n\n//Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.\n\n//Licensed under the BSD 3-Clause License (the \"License\"); you may not use this file except\n//in compliance with the License. You may obtain a copy of the License at\n//\n//https://opensource.org/licenses/BSD-3-Clause\n//\n//Unless required by applicable law or agreed to in writing, software distributed\n//under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n//CONDITIONS OF ANY KIND, either express or implied. See the License for the\n//specific language governing permissions and limitations under the License.\n\n#include <booster/sgemv.h>\n#include <booster/helper.h>\n\n#include <assert.h>\n#include <immintrin.h>\n#include <string.h>\n#if 0\nvoid fully_connected_inference_direct(const int input_size, const int output_size, const float *x, const float *y, float *z, const int num_threads)\n{\n    #pragma omp parallel for schedule(static) num_threads(num_threads)\n    for (int i = 0; i < output_size; i++)\n    {\n        float sum = 0.f;\n        for (int j = 0; j < input_size; j++)\n            sum += x[j] * y[i * input_size + j];\n        z[i] = sum;\n    }\n}\n\nvoid fully_connected_transpose_inference_sse8(const int input_size, const int output_size, const float *x, const float *y, float *z, const int num_threads)\n{\n    assert(input_size % 8 == 0);\n    assert(output_size % 8 == 0);\n    #pragma omp parallel for schedule(static) num_threads(num_threads)\n    for (int k = 0; k < output_size / 8; k++)\n    {\n        const float *yPtr = y + k * 8 * input_size;\n        __m128 res = {0.0, 0.0, 0.0, 0.0};\n        __m128 res1 = {0.0, 0.0, 0.0, 0.0};\n        __m128 va0, va1, va2, va3, vb0, vb1, vb2, vb3, vb4, vb5, vb6, vb7;\n        for (int i = 0; i < input_size; i += 4)\n        {\n            //          __m128 v1, v2;\n            //va = _mm_load_ps(x + i);\n\n            vb0 = _mm_load_ps(yPtr);\n            vb1 = _mm_load_ps(yPtr + 4);\n            vb2 = _mm_load_ps(yPtr + 8);\n            vb3 = _mm_load_ps(yPtr + 12);\n            vb4 = _mm_load_ps(yPtr + 16);\n            vb5 = _mm_load_ps(yPtr + 20);\n            vb6 = _mm_load_ps(yPtr + 24);\n            vb7 = _mm_load_ps(yPtr + 28);\n\n            va0 = _mm_broadcast_ss(x + i);\n            va1 = _mm_broadcast_ss(x + i + 1);\n            va2 = _mm_broadcast_ss(x + i + 2);\n            va3 = _mm_broadcast_ss(x + i + 3);\n\n            res = _mm_fmadd_ps(vb0, va0, res);\n            res1 = _mm_fmadd_ps(vb1, va0, res1);\n            res = _mm_fmadd_ps(vb2, va1, res);\n            res1 = _mm_fmadd_ps(vb3, va1, res1);\n            res = _mm_fmadd_ps(vb4, va2, res);\n            res1 = _mm_fmadd_ps(vb5, va2, res1);\n            res = _mm_fmadd_ps(vb6, va3, res);\n            res1 = _mm_fmadd_ps(vb7, va3, res1);\n\n            yPtr += 32;\n        }\n        _mm_store_ps((z + 8 * k), res);\n        _mm_store_ps((z + 8 * k + 4), res1);\n    }\n}\n\n#include <stdio.h>\n#include <stdlib.h>\n\n//For fully connected layers, the weights matrix is transposed.\n//To reduce memory allocation, a KxSTRIDE packed matrix is sufficient.\ntemplate<int STRIDE>\nvoid packed_sgemv_transposed_init(const int N, const int K, float* matrix, float* packed_buffer)\n{\n    size_t N_aligned = N - N % STRIDE;\n    for (int j = 0; j < N_aligned; j += STRIDE)\n    {\n        float* pMatrix = matrix + j * K;\n        float* pPacked = packed_buffer;\n        for (int k = 0; k < K; ++k)\n        {\n            for (int i = 0; i < STRIDE; ++i)\n                pPacked[i] = pMatrix[i * K + k];\n            pPacked += STRIDE;\n        }\n        memcpy(pMatrix, packed_buffer, STRIDE * K * sizeof(float));\n    }\n    int rem = N % STRIDE;\n    if (rem > 0)\n    {\n        float* pMatrix = matrix + N_aligned * K;\n        float* pPacked = packed_buffer;\n        for (int k = 0; k < K; ++k)\n        {\n            for (int i = 0; i < rem; ++i)\n                pPacked[i] = pMatrix[i * K + k];\n            pPacked += rem;\n        }\n        memcpy(pMatrix, packed_buffer, rem * K * sizeof(float));\n    }\n}\ntemplate void packed_sgemv_transposed_init<8>(const int N, const int K, float* matrix, float* packed_matrix);\ntemplate void packed_sgemv_transposed_init<16>(const int N, const int K, float* matrix, float* packed_matrix);\n\n//The packed matrix will only be scanned once. Cache miss would only occur with very large K, which is not a very common case.\n\ntemplate<bool fuseBias, bool fuseRelu>\nvoid packed_sgemv(const int N, const int K, const float* A, const float* B, float* C, const float* bias_data, const int num_threads)\n{\n    assert(K % 4 == 0);\n    int N_aligned = N - N % 16;\n    __m256 vZero = _mm256_set1_ps(0.f);\n    #pragma omp parallel for\n    for (int j = 0; j < N_aligned; j += 16)\n    {\n        const float *pB = B + j * K;\n        float *pC = C + j;\n        __m256 acc0 = _mm256_set1_ps(0.f);\n        __m256 acc1 = _mm256_set1_ps(0.f);\n        if (fuseBias)\n        {\n            acc0 = _mm256_load_ps(bias_data + j);\n            acc1 = _mm256_load_ps(bias_data + j + 8);\n        }\n        __m256 va0, va1, va2, va3;\n        __m256 vb0, vb1, vb2, vb3, vb4, vb5, vb6, vb7;\n        for (int k = 0; k < K; k += 4)\n        {\n            vb0 = _mm256_load_ps(pB);\n            vb1 = _mm256_load_ps(pB + 8);\n            vb2 = _mm256_load_ps(pB + 16);\n            vb3 = _mm256_load_ps(pB + 24);\n            vb4 = _mm256_load_ps(pB + 32);\n            vb5 = _mm256_load_ps(pB + 40);\n            vb6 = _mm256_load_ps(pB + 48);\n            vb7 = _mm256_load_ps(pB + 56);\n\n            //print_floats(pB, 8);\n            va0 = _mm256_broadcast_ss(A + k);\n            va1 = _mm256_broadcast_ss(A + k + 1);\n            va2 = _mm256_broadcast_ss(A + k + 2);\n            va3 = _mm256_broadcast_ss(A + k + 3);\n\n            acc0 = _mm256_fmadd_ps(vb0, va0, acc0);\n            acc1 = _mm256_fmadd_ps(vb1, va0, acc1);\n            acc0 = _mm256_fmadd_ps(vb2, va1, acc0);\n            acc1 = _mm256_fmadd_ps(vb3, va1, acc1);\n            acc0 = _mm256_fmadd_ps(vb4, va2, acc0);\n            acc1 = _mm256_fmadd_ps(vb5, va2, acc1);\n            acc0 = _mm256_fmadd_ps(vb6, va3, acc0);\n            acc1 = _mm256_fmadd_ps(vb7, va3, acc1);\n            pB += 64;\n        }\n        if (fuseRelu)\n        {\n            acc0 = _mm256_max_ps(vZero, acc0);\n            acc1 = _mm256_max_ps(vZero, acc1);\n        }\n        _mm256_store_ps(pC, acc0);\n        _mm256_store_ps(pC + 8, acc1);\n    }\n\n    int rem = N % 16;\n    if (rem == 8)\n    {\n        const float *pB = B + N_aligned * K;\n        __m256 vacc = _mm256_set1_ps(0.f);\n        if (fuseBias)\n            vacc = _mm256_load_ps(bias_data + N_aligned);\n        __m256 va, vb;\n        float acc[4];\n        for (int k = 0; k < K; ++k)\n        {\n            vb  = _mm256_loadu_ps(pB);\n            va  = _mm256_broadcast_ss(A + k);\n            vacc = _mm256_fmadd_ps(vb, va, vacc);\n            pB += rem;\n        }\n        if (fuseRelu)\n            vacc = _mm256_max_ps(vZero, vacc);\n        _mm256_store_ps(C + N_aligned, vacc);\n    }\n    else if (rem > 0)\n    {\n        const float *pB = B + N_aligned * K;\n        float *pC = C + N_aligned;\n        __m256 vacc = _mm256_set1_ps(0.f);\n        if (fuseBias && rem >= 8)\n            vacc = _mm256_load_ps(bias_data + N_aligned);\n\n        __m256 va, vb;\n        float acc[4];\n        for (int i = 0; i < rem - 8; ++i)\n        {\n            if (fuseBias)\n                acc[i] = bias_data[N_aligned + i];\n            else\n                acc[i] = 0;\n        }\n        for (int k = 0; k < K; ++k)\n        {\n            if (rem >= 8)\n            {\n                vb  = _mm256_loadu_ps(pB);\n                va  = _mm256_broadcast_ss(A + k);\n                vacc = _mm256_fmadd_ps(vb, va, vacc);\n            }\n            if (rem - 8 > 0)\n            {\n                for (int i = 0; i < rem - 8; ++i)\n                    acc[i] = A[k] * pB[i + 8];\n            }\n            pB += rem;\n        }\n        if (fuseRelu)\n        {\n            vacc = _mm256_max_ps(vZero, vacc);\n        }\n        _mm256_store_ps(pC, vacc);\n        for (int i = 0; i < rem - 8; ++i)\n        {\n            if (fuseRelu)\n                pC[i + 8] = ((acc[i] > 0.f) ? acc[i] : 0.f);\n            else\n                pC[i + 8] = acc[i];\n        }\n    }\n}\n\ntemplate void packed_sgemv<false, false>(const int N, const int K, const float* A, const float* B, float* C, const float* bias_data, const int num_threads);\ntemplate void packed_sgemv<true, false>(const int N, const int K, const float* A, const float* B, float* C, const float* bias_data, const int num_threads);\ntemplate void packed_sgemv<false, true>(const int N, const int K, const float* A, const float* B, float* C, const float* bias_data, const int num_threads);\ntemplate void packed_sgemv<true, true>(const int N, const int K, const float* A, const float* B, float* C, const float* bias_data, const int num_threads);\n\n\n\nvoid fully_connected_inference_direct_BiasReLU(int input_size, int output_size, float *x, float *y, float *z, float* biasArr, int num_threads)\n{\n    #pragma omp parallel for schedule(static) num_threads(num_threads)\n    for (int i = 0; i < output_size; i++)\n    {\n        float sum = 0.f;\n        for (int j = 0; j < input_size; j++)\n            sum += x[j] * y[i * input_size + j];\n\n        sum += biasArr[i];\n        if (sum < 0.f) sum = 0.f;\n        z[i] = sum;\n    }\n}\n\nvoid fully_connected_transpose_inference_sse8_BiasReLU(int input_size, int output_size, float *x, float *y, float *z, float* biasArr, int num_threads)\n{\n    assert(input_size % 8 == 0);\n    assert(output_size % 8 == 0);\n    #pragma omp parallel for schedule(static) num_threads(num_threads)\n    for (int k = 0; k < output_size / 8; k++)\n    {\n        float *yPtr = y + k * 8 * input_size;\n        const __m128 vzero = _mm_set1_ps(0.f);\n\n        __m128 res  = _mm_load_ps(biasArr + k * 8);\n        __m128 res1 = _mm_load_ps(biasArr + k * 8 + 4);\n\n        __m128 va0, va1, va2, va3, vb0, vb1, vb2, vb3, vb4, vb5, vb6, vb7;\n        for (int i = 0; i < input_size; i += 4)\n        {\n            vb0 = _mm_load_ps(yPtr);\n            vb1 = _mm_load_ps(yPtr + 4);\n            vb2 = _mm_load_ps(yPtr + 8);\n            vb3 = _mm_load_ps(yPtr + 12);\n            vb4 = _mm_load_ps(yPtr + 16);\n            vb5 = _mm_load_ps(yPtr + 20);\n            vb6 = _mm_load_ps(yPtr + 24);\n            vb7 = _mm_load_ps(yPtr + 28);\n\n            va0 = _mm_broadcast_ss(x + i);\n            va1 = _mm_broadcast_ss(x + i + 1);\n            va2 = _mm_broadcast_ss(x + i + 2);\n            va3 = _mm_broadcast_ss(x + i + 3);\n\n            res = _mm_fmadd_ps(vb0, va0, res);\n            res1 = _mm_fmadd_ps(vb1, va0, res1);\n            res = _mm_fmadd_ps(vb2, va1, res);\n            res1 = _mm_fmadd_ps(vb3, va1, res1);\n            res = _mm_fmadd_ps(vb4, va2, res);\n            res1 = _mm_fmadd_ps(vb5, va2, res1);\n            res = _mm_fmadd_ps(vb6, va3, res);\n            res1 = _mm_fmadd_ps(vb7, va3, res1);\n\n            yPtr += 32;\n        }\n\n        res  = _mm_max_ps(res, vzero);\n        res1 = _mm_max_ps(res1, vzero);\n\n        _mm_store_ps((z + 8 * k), res);\n        _mm_store_ps((z + 8 * k + 4), res1);\n    }\n}\n\n#else\n\ntemplate <bool fuseBias, bool fuseRelu>\nvoid fully_connected_inference_direct(const int input_size, const int output_size, const float *x, const float *y, float *z, const int num_threads, float *bias_arr)\n{\n    #pragma omp parallel for schedule(static) num_threads(num_threads)\n    for (int i = 0; i < output_size; i++)\n    {\n        float sum = 0;\n        for (int j = 0; j < input_size; j++)\n            sum += x[j] * y[i * input_size + j];\n        if (fuseBias)\n            sum += bias_arr[i];\n        if (fuseRelu)\n            sum = (sum > 0.f) ? sum : 0.f;\n        z[i] = sum;\n    }\n}\n\ntemplate <bool fuseBias, bool fuseRelu>\nvoid fully_connected_transpose_inference(const int input_size, const int output_size, const float *x, const float *y, float *z, const int num_threads, float *bias_arr)\n{\n    assert(input_size % 8 == 0);\n    assert(output_size % 8 == 0);\n    #pragma omp parallel for schedule(static) num_threads(num_threads)\n    for (int k = 0; k < output_size / 8; k++)\n    {\n        __m128 vBias, vBias1;\n        const __m128 vZero = _mm_set1_ps(0.f);\n        __m128 res = _mm_set1_ps(0.f);\n        __m128 res1 = _mm_set1_ps(0.f);\n\n        if (fuseBias)\n        {\n            vBias = _mm_load_ps(bias_arr + k * 8);\n            vBias1 = _mm_load_ps(bias_arr + k * 8 + 4);\n        }\n        const float *yPtr = y + k * 8 * input_size;\n        __m128 va0, va1, va2, va3, vb0, vb1, vb2, vb3, vb4, vb5, vb6, vb7;\n        for (int i = 0; i < input_size; i += 4)\n        {\n            vb0 = _mm_load_ps(yPtr);\n            vb1 = _mm_load_ps(yPtr + 4);\n            vb2 = _mm_load_ps(yPtr + 8);\n            vb3 = _mm_load_ps(yPtr + 12);\n            vb4 = _mm_load_ps(yPtr + 16);\n            vb5 = _mm_load_ps(yPtr + 20);\n            vb6 = _mm_load_ps(yPtr + 24);\n            vb7 = _mm_load_ps(yPtr + 28);\n\n            va0 = _mm_broadcast_ss(x + i);\n            va1 = _mm_broadcast_ss(x + i + 1);\n            va2 = _mm_broadcast_ss(x + i + 2);\n            va3 = _mm_broadcast_ss(x + i + 3);\n\n            res = _mm_fmadd_ps(vb0, va0, res);\n            res1 = _mm_fmadd_ps(vb1, va0, res1);\n            res = _mm_fmadd_ps(vb2, va1, res);\n            res1 = _mm_fmadd_ps(vb3, va1, res1);\n            res = _mm_fmadd_ps(vb4, va2, res);\n            res1 = _mm_fmadd_ps(vb5, va2, res1);\n            res = _mm_fmadd_ps(vb6, va3, res);\n            res1 = _mm_fmadd_ps(vb7, va3, res1);\n\n            yPtr += 32;\n        }\n\n        if (fuseBias)\n        {\n            res  = _mm_add_ps(res, vBias);\n            res1 = _mm_add_ps(res1, vBias1);\n        }\n        if (fuseRelu)\n        {\n            res = _mm_max_ps(res, vZero);\n            res1 = _mm_max_ps(res1, vZero);\n        }\n        _mm_store_ps((z + 8 * k), res);\n        _mm_store_ps((z + 8 * k + 4), res1);\n    }\n}\n\ntemplate void fully_connected_inference_direct<false, false>(const int, const int, const float *, const float *, float *, const int, float *);\ntemplate void fully_connected_inference_direct<false, true>(const int, const int, const float *, const float *, float *, const int, float *);\ntemplate void fully_connected_inference_direct<true, false>(const int, const int, const float *, const float *, float *, const int, float *);\ntemplate void fully_connected_inference_direct<true, true>(const int, const int, const float *, const float *, float *, const int, float *);\n\ntemplate void fully_connected_transpose_inference<false, false>(const int, const int, const float *, const float *, float *, const int, float *);\ntemplate void fully_connected_transpose_inference<false, true>(const int, const int, const float *, const float *, float *, const int, float *);\ntemplate void fully_connected_transpose_inference<true, false>(const int, const int, const float *, const float *, float *, const int, float *);\ntemplate void fully_connected_transpose_inference<true, true>(const int, const int, const float *, const float *, float *, const int, float *);\n\n#endif\n\nvoid matrixTranspose(float *array, size_t m, size_t n, float *buffer) //  A[m][n] -> A[n][m]\n{\n    for (int i = 0; i < m; i++)\n        for (int j = 0; j < n; j++)\n            buffer[j * m + i] = array[i * n + j];\n    memcpy(array, buffer, m * n * sizeof(float));\n}\n", "meta": {"hexsha": "c97a1e1302d909c93139ba4783cd9a312bdac145", "size": 15377, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/booster/avx/sgemv.cpp", "max_stars_repo_name": "chenaili6/FeatherCNN", "max_stars_repo_head_hexsha": "52cd8c8749ed584461a88b1f04749bb35a48f9a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-05-14T09:00:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-14T08:11:54.000Z", "max_issues_repo_path": "src/booster/avx/sgemv.cpp", "max_issues_repo_name": "nihui/FeatherCNN", "max_issues_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/booster/avx/sgemv.cpp", "max_forks_repo_name": "nihui/FeatherCNN", "max_forks_repo_head_hexsha": "2805f371bd8f33ef742cc9523979f29295d926fb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9639423077, "max_line_length": 167, "alphanum_fraction": 0.5554399428, "num_tokens": 4787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22997364162397252}}
{"text": "//\n//  main.cpp\n//  PhyloAcc\n//\n//  Created by hzr on 3/8/16.\n//  Copyright © 2016 hzr. All rights reserved.\n//\n#include <dirent.h>\n#include <stdio.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <algorithm>\n#include <iomanip>\n#include <omp.h>\n#include <string> \n#include <armadillo>\n#include \"profile.h\"\n#include \"newick.h\"\n#include \"bpp.hpp\"\n#include \"bpp_c.hpp\"\n#include \"utils.h\"\n#include <math.h>\n#include <gsl/gsl_errno.h>\n\nusing namespace std;\nusing namespace arma;\n\n// parameters, input and output files paths\nstring params_path;\nstring phytree_path;\nstring align_path;\nstring output_path=\"\";\nstring output_path2=\"\";\nstring segment_path;\nstring id_path=\"\";\nstring result_prefix=\"test\";\n\n//string refspecies;\nstring outgroup;\nstring targetspecies;\nstring conservegroup; // can't be missing in more than 50%\ndouble conserve_prop = 0.8;\n\nint num_thread = 1;\n\n// running parameters\nint num_burn = 200;         // num of burn-in updates\nint num_mcmc = 800;         // num of MCMC updates,10\nint num_thin = 500;    // num of updates between two samples, adaptive frequency\nint num_chain; // outer loop of updates Q matrix and hyperparameter of substitution rates\n\n\ndouble prep_lrate = 0.3;\ndouble prep_lrate2 = 0.0;//0.1\ndouble prep_grate = 0.5; // initalization\n\ndouble prior_lrate2_a = 0,prior_lrate2_b = 1 ; // beta prior for lrate2, 0.5\ndouble prior_lrate_a = 1 ,prior_lrate_b = 9 ; // beta prior for lrate, 2\ndouble prior_grate_a = 3,prior_grate_b = 1 ; // beta prior for grate\n\n\ndouble ratio0 = 0.5; //initial conserved rate\ndouble ratio1 = 1; // initial accelerated rate\ndouble missing_thres = 0.8;\n\ndouble nprior_a = 10, nprior_b = 0.2;  //around 1\ndouble cprior_a = 5, cprior_b = 0.04;  //around ratio\nint ropt = 1;\ndouble cub = 1;\ndouble nlb = 0.6;\n\nint batch = -1 ;\nint seed = 5;\ndouble indel = 0;\ndouble indel2;\nbool sample_indel = 0;\nbool sample_hyper;\nchar gapchar = '-';\nbool verbose = 0;\ndouble consToMis = 0.01;\nbool prune=0;\ndouble revgap=1;\nint min_length = 50;\n\n\n// load the program parameters\nvoid LoadParams(int argc, char* argv[])\n{\n    cout << \"Loading input data and running parameters......\" << endl;\n    \n    if (argc > 1)\n        params_path = string(argv[1]);\n    else\n        params_path = \"/Users/hzr/Phd_2/Bird/PhyloAcc_init3-3/params2s.txt\"; //params2\n    \n    cout << \"Loading program configurations from \" << params_path << \"......\" <<endl;\n    \n    const int BUFF_SIZE = 1024;\n    char line_buff[BUFF_SIZE];\n    \n    ifstream in_params(params_path.c_str());\n    if (!in_params)\n    {\n        cerr << \"Cannot open the parameters file: \" << params_path.c_str() << endl;\n        exit(1);\n    }\n    while(!in_params.eof())\n    {\n        in_params.getline(line_buff, BUFF_SIZE);\n        istringstream line_stream(line_buff);\n        string tmp; line_stream >> tmp;\n        \n        // input and output file paths\n        if (tmp==\"PHYTREE_FILE\")\n            line_stream >> phytree_path;\n        else if (tmp==\"ALIGN_FILE\")\n            line_stream >> align_path;\n        else if (tmp==\"SEG_FILE\")\n            line_stream >> segment_path;\n        else if (tmp==\"ID_FILE\")\n            line_stream >> id_path;\n        else if (tmp==\"BATCH\")\n            line_stream >> batch;\n        else if (tmp==\"RESULT_FOLDER\")\n            line_stream >> output_path;\n        else if (tmp==\"PREFIX\")\n            line_stream >> result_prefix;\n        \n        //else if (tmp==\"RESULT_INDIV\")\n        //    line_stream >> output_path2;\n        \n        else if (tmp==\"SEED\")\n            line_stream >> seed;\n        else if (tmp==\"INIT_CONSERVE_RATE\")\n            line_stream >> ratio0;\n        else if (tmp==\"INIT_ACCE_RATE\")\n            line_stream >> ratio1;\n        else if (tmp==\"CONSERVE_PRIOR_A\")\n            line_stream >> cprior_a;\n        else if (tmp==\"CONSERVE_PRIOR_B\")\n            line_stream >> cprior_b;\n        else if (tmp==\"ACCE_PRIOR_A\")\n            line_stream >> nprior_a;\n        else if (tmp==\"ACCE_PRIOR_B\")\n            line_stream >> nprior_b;\n        else if (tmp==\"ROPT\")\n            line_stream >> ropt;\n        else if (tmp==\"CUB\")\n            line_stream >> cub;\n        else if (tmp==\"NLB\")\n            line_stream >> nlb;\n\n\n\n        \n        // running parameters\n        else if (tmp==\"BURNIN\")\n            line_stream >> num_burn;\n        else if (tmp==\"MCMC\")\n            line_stream >> num_mcmc;\n        else if (tmp==\"ADAPT_FREQ\")\n            line_stream >> num_thin;\n        else if (tmp==\"INIT_LRATE\")\n            line_stream >> prep_lrate;\n        else if (tmp==\"INIT_GRATE\")\n            line_stream >> prep_grate;\n        else if (tmp==\"HYPER_LRATE_A\")\n            line_stream >> prior_lrate_a;\n        else if (tmp==\"HYPER_LRATE_B\")\n            line_stream >> prior_lrate_b;\n        else if (tmp==\"HYPER_GRATE_A\")\n            line_stream >> prior_grate_a;\n        else if (tmp==\"HYPER_GRATE_B\")\n            line_stream >> prior_grate_b;\n        else if (tmp==\"CHAIN\")\n            line_stream >> num_chain;\n        \n        // constraint\n        else if (tmp == \"OUTGROUP\")\n            line_stream >> outgroup;\n        else if (tmp == \"TARGETSPECIES\")\n            line_stream >> targetspecies;\n        else if (tmp == \"CONSERVE\")\n            line_stream >> conservegroup;\n        else if (tmp == \"CONSERVE_PROP\")\n            line_stream >> conserve_prop;\n        else if (tmp == \"GAP_PROP\")\n            line_stream >> missing_thres;\n        //else if (tmp == \"REF\")\n         //   line_stream >> refspecies;\n        else if (tmp == \"CONSTOMIS\")\n            line_stream >> consToMis;\n        \n        \n        // treat indel as additional character\n        else if (tmp == \"GAPCHAR\")\n            line_stream >> gapchar;\n        else if (tmp == \"PRUNE_TREE\")\n            line_stream >> prune;\n        else if (tmp == \"TRIM_GAP_PERCENT\")\n            line_stream >> revgap;\n        else if (tmp == \"MIN_LEN\")\n            line_stream >> min_length;\n        else if (tmp == \"INDEL\") // not used\n            line_stream >> indel;\n        else if (tmp == \"INDEL2\") // not used\n            line_stream >> indel2;\n        else if(tmp == \"SAMPLE_INDEL\")  // not used\n            line_stream >> sample_indel;\n        else if(tmp == \"SAMPLE_HYPER\")\n            line_stream >> sample_hyper;\n        else if(tmp == \"VERBOSE\")\n            line_stream >> verbose;\n        else if(tmp == \"NUM_THREAD\")\n            line_stream >> num_thread;\n        else if(tmp != \"\")\n            cout << \"Unknown parameter: \" << tmp <<endl;\n\n\n\n    }\n    \n    // trimming file names\n    phytree_path = strutils::trim(phytree_path, \" \\\"\\t\\n\");\n    align_path = strutils::trim(align_path, \" \\\"\\t\\n\");\n    output_path  = strutils::trim(output_path,  \" \\\"\\t\\n\");\n    //output_path2  = strutils::trim(output_path2,  \" \\\"\\t\\n\");\n    segment_path = strutils::trim(segment_path, \" \\\"\\t\\n\");\n    \n    \n}\n\n\n\nbool DirectoryExists( string pzPath )\n{\n    if ( pzPath == \"\") return false;\n\n    DIR *pDir;\n    bool bExists = false;\n\n    pDir = opendir (pzPath.c_str());\n\n    if (pDir != NULL)\n    {\n        bExists = true;    \n        (void) closedir (pDir);\n    }\n\n    return bExists;\n}\n\nvoid DispParams(PhyloProf profile, int seed)\n{\n    double mean_seg_size = 0;\n    for(unsigned int c=0; c<profile.C; c++)\n        mean_seg_size += (double)(profile.element_pos[c][1] - profile.element_pos[c][0]) / profile.C;\n    cout << \"  # total length = \" << profile.G << \" (\" << profile.C << \")\" << \". # Species = \" << profile.S << \". # elements = \" << profile.C << \". Mean gene set size = \" << mean_seg_size << \".\" << endl;\n    cout << \"# Burn-ins = \" << num_burn << \". # MCMC Updates = \" << num_mcmc << \". # adaptive frequency = \" << num_thin << \".  RND SEED = \" << seed << \".\" << endl ; //\n    cout << \"# Threads = \" << num_thread << endl << endl;\n}\n\nint main(int argc, char* argv[])\n{\n    time_t start = time(NULL);\n    \n    cout << std::fixed << setprecision(4);\n    \n    \n    // load the program parameters\n    LoadParams(argc, argv);\n\n    // check output path\n    if(! DirectoryExists(output_path))\n    {\n    \tcout << \"output path doesn't exist or empty!\" << endl;\n    \treturn 1;\n    }\n    \n    // load the phylogenetic profile\n    PhyloProf profile = LoadPhyloProfiles(align_path,segment_path);\n    \n    // load the phylogenetic tree\n    PhyloTree phytree = LoadPhyloTree(phytree_path);\n    \n    // init and display the running parameters\n    //InitParams(profile.G);\n    DispParams(profile, seed);\n    \n    // create and init the BPP object\n    //int pC = 500;  // only read in some elements for testing\n    BPP bpp(0, profile, phytree, output_path, targetspecies, outgroup, conserve_prop, conservegroup, ratio0, ratio1, ropt, cub, nlb, nprior_a, nprior_b, cprior_a, cprior_b, seed, prep_grate, prep_lrate, prep_lrate2, prior_grate_a, prior_grate_b,prior_lrate_a, prior_lrate_b,prior_lrate2_a, prior_lrate2_b,  indel, indel2, missing_thres, sample_indel);  //c=1 test run first element\n    \n    // remove profile?\n    //profile.~PhyloProf();\n    \n    //initialize the MCMC sampling\n    bpp.InitMCMC(num_burn, num_mcmc, num_thin);\n    \n\n    output_path = output_path + \"/\" + result_prefix ;\n    output_path2 = output_path;\n    string outpath_Z0 = output_path + \"_rate_postZ_M\" +to_string(0) +\".txt\";  //null\n    string outpath_Z1 = output_path + \"_rate_postZ_M\" +to_string(2) +\".txt\";  //full\n    string outpath_Z2 = output_path + \"_rate_postZ_M\" +to_string(1) +\".txt\";  // M1\n    \n    \n    string outpath_hyper = output_path+\"_hyper.txt\";\n    ofstream out_hyper(outpath_hyper.c_str());\n    out_hyper << \"iter\\tnprior_a\\tnprior_b\\tcprior_a\\tcprior_b\\tprior_l_a\\tprior_l_b\\tprior_g_a\\tprior_g_b\\n\";\n    out_hyper << 0 << \"\\t\"<< nprior_a<< \"\\t\"<< nprior_b <<\"\\t\"<< cprior_a << \"\\t\"<< cprior_b << \"\\t\"<< prior_lrate_a << \"\\t\"<< prior_lrate_b << \"\\t\"<< prior_grate_a << \"\\t\"<< prior_grate_b <<endl;\n\n    \n    ofstream out_lik;\n    if(sample_hyper) {\n        string outpath_elem = output_path+ \"_elem_lik.txt\";\n        out_lik.open(outpath_elem.c_str());\n        out_lik.precision(8);\n        out_lik << \"No.\\tID\\tloglik_all\\tloglik_Max\"<<endl;\n    }\n    \n    ofstream out_Z0(outpath_Z0.c_str());\n    ofstream out_Z1(outpath_Z1.c_str());\n    ofstream out_Z2(outpath_Z2.c_str());\n    \n    // output species name\n    string species_name = output_path+\"_species_names.txt\";\n    ofstream out_species(species_name.c_str());\n    \n    out_Z0 << \"No.\\tn_rate\\tc_rate\\tg_rate\\tl_rate\\tl2_rate\"; out_Z1 << \"No.\\tn_rate\\tc_rate\\tg_rate\\tl_rate\\tl2_rate\"; out_Z2 << \"No.\\tn_rate\\tc_rate\\tg_rate\\tl_rate\\tl2_rate\";\n    for(int s=0; s<bpp.N;s++){\n         for(int k=0;k<4;k++){\n            out_Z0 <<\"\\t\"<<bpp.nodes_names[s]<<\"_\"<<k;\n            out_Z1 <<\"\\t\"<<bpp.nodes_names[s]<<\"_\"<<k;\n            out_Z2 <<\"\\t\"<<bpp.nodes_names[s]<<\"_\"<<k;\n         }\n         out_species << bpp.nodes_names[s] << endl;\n    }\n\tout_Z0 <<endl; out_Z1 <<endl; out_Z2 <<endl;\n\n    out_species.close();\n\n    double lrate_prop = 0.5, grate_prop = 0.5;\n    \n    vector<int> ids;\n    if(id_path==\"\")\n    {\n        if(batch==-1)\n        {\n          for(int c =0;c<bpp.C;c++)\n          {\n            ids.push_back(c);\n          }\n        }else{\n          int temp = ceil(bpp.C/3);\n          for(int c =batch*temp ;c< (batch+1)*temp;c++)\n          {\n            if(c >= bpp.C) break;\n            ids.push_back(c);\n          }\n        \n        }\n        \n    }else{\n        ifstream in_params(id_path.c_str());\n        if (!in_params)\n        {\n            cerr << \"Cannot open the id file: \" << id_path.c_str() << endl;\n            exit(1);\n        }\n        while(!in_params.eof())\n        {\n            const int BUFF_SIZE = 1024;\n            char line_buff[BUFF_SIZE];\n            in_params.getline(line_buff, BUFF_SIZE);\n            istringstream line_stream(line_buff);\n            string tmp; line_stream >> tmp;\n            tmp = strutils::trim(tmp);\n            if(tmp==\"\") continue;\n            ids.push_back(atoi(tmp.c_str()));\n            \n        }\n\n    }\n\n    cout << ids.size() << \" of elements to be computed\" << endl; \n    //gsl_set_error_handler_off();\n    for(int iter =0; iter<num_chain; iter++)\n    {\n        cout << \"Running MCMC chain \" << iter +1 << \" ...\" << endl;\n        // generate next indel parameter, nprior_a, nprior_b, etc...\n        //bpp.sample_proposal(iter, lrate_prop, grate_prop,out_hyper);\n       \n        \n        // Gibbs sampling\n        #pragma omp parallel for schedule (guided) num_threads(num_thread)\n        for(std::size_t i = 0; i < ids.size(); i++ ) \n        {\n            int c = ids[i];\n            bool filter = false;\n          \n            // null model\n            try{\n            BPP_C bppc(c, profile, bpp, gapchar, missing_thres, filter, verbose, consToMis, prune, revgap, min_length);  // for individual element\n            if(filter) {\n              if(verbose) cerr << \"filter: \"<< c <<endl;\n              continue;\n            }\n            \n            if(!sample_hyper)\n            {\n                bppc.initMCMC(iter,bpp,0);  //not constrain log_prob_back\n                bppc.Gibbs(iter,bpp,out_Z0,output_path,output_path2,0,true,sample_hyper, lrate_prop, grate_prop);  // Gibbs run to get Z for each element\n                //if(!bppc.failure)\n                //{\n                bppc.Eval2(bpp,0);\n                if(bppc.verbose || bppc.failure) bppc.Output_sampling(iter, output_path2, bpp, 0);\n                bppc.Output_init(output_path,output_path2,bpp,out_Z0, 0); //sort rates!!, posterior median of nrate and crate; posterior mean of Z\n               // }\n                // res model, crate by null model\n                bppc.initMCMC(iter,bpp,2);  //not constrain log_prob_back\n                bppc.Gibbs(iter,bpp,out_Z2,output_path,output_path2,2,true,sample_hyper, lrate_prop, grate_prop);  // Gibbs run to get Z for each element\n                //if(!bppc.failure)\n                //{\n                bppc.Eval2(bpp,2);\n                if(bppc.verbose || bppc.failure) bppc.Output_sampling(iter, output_path2, bpp, 1);\n                bppc.Output_init(output_path,output_path2,bpp,out_Z2, 2); //sort rates!!\n                //}\n            }\n            \n            // full model, nrate, crate by res model\n            bppc.initMCMC(iter,bpp,1);  //not constrain log_prob_back\n            bppc.Gibbs(iter, bpp,out_Z1,output_path,output_path2,1, true, sample_hyper, lrate_prop, grate_prop);  // Gibbs run to get Z for each element\n            //if(!bppc.failure)\n            //{\n            bppc.Eval2(bpp,1);\n            if(bppc.verbose || bppc.failure) bppc.Output_sampling(iter, output_path2, bpp, 2);\n            bppc.Output_init(output_path,output_path2,bpp,out_Z1, 1); //sort rates!!\n            //}\n\n            }catch (exception& e){\n              cout << c << \" Standard exception: \" << e.what() << endl;\n            }\n        }\n        \n        // sample indel, nprior_a, nprior_b, etc...\n        try{\n          if(sample_hyper) {\n            bpp.sample_hyperparam(iter, ids, out_hyper);\n            bpp.Output_init0(profile,out_lik, ids);\n          }else{\n            bpp.Output_init(profile,output_path, ids);\n          }\n        }catch (exception& e){\n              cout << \" Standard exception: \" << e.what() << endl;\n        }\n    }\n\n    \n        out_Z0.close();\n        out_Z1.close();\n        out_Z2.close();\n        out_hyper.close();\n        out_lik.close();\n    \n    \n    \n    cout << endl << endl << \"time used:  \" << (time(NULL)-start)/60 << \" min.\" << endl << endl;\n    \n    \n    return 0;\n}\n", "meta": {"hexsha": "f30597daf8f94c55404e1a56e14d12f16d59829d", "size": 15498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SRC/main.cpp", "max_stars_repo_name": "beyondpie/PhyloAcc", "max_stars_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-11T14:34:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-08T06:58:59.000Z", "max_issues_repo_path": "SRC/main.cpp", "max_issues_repo_name": "beyondpie/PhyloAcc", "max_issues_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T03:41:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T09:54:35.000Z", "max_forks_repo_path": "SRC/main.cpp", "max_forks_repo_name": "beyondpie/PhyloAcc", "max_forks_repo_head_hexsha": "6c6bf6fc7156c4adfb4df6e9e93a5857ac147a6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-03T18:49:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T04:39:30.000Z", "avg_line_length": 32.6273684211, "max_line_length": 381, "alphanum_fraction": 0.5689121177, "num_tokens": 4124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22997364162397252}}
{"text": "/* //////////////////////////////////////////////////////////////////////\n\n    Recurrent Neural Network Language Model\n    v0.95\n\n    一部のコードは \"Recurrent neural network based statistical language modeling toolkit Version 0.4a\" を元にしています.\n\n////////////////////////////////////////////////////////////////////// */\n\n#include <stdio.h>\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n//#include <stddef.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <iostream>\n#include <string>\n#include <math.h>\n\n#include <time.h>\n#include <cfloat>\n\n#include <unordered_map>\n#include <boost/unordered_map.hpp>\n#include \"rnnlmlib_dynamic.h\"\n\n#ifndef exp10\n    #define exp10(x) pow((double)10, (x))\n#endif\n\nnamespace RNNLM{\n\n    inline void FreadAllOrDie_dyn(void* ptr, size_t size, size_t count, FILE* fo, const char* message) {/*{{{*/\n        size_t read = fread(ptr, size, count, fo);\n        if (read != count) {\n            fprintf(\n                    stderr, \"ERROR: expected to read %zu elements, but read %zu elements (%s)\\n\",\n                    count, read, message);\n            exit(1);\n        }\n    }/*}}}*/\n\n    void CRnnLM_dyn::ReadFRHeader(FILE* file) {/*{{{*/\n        const uint64_t kVersionStepSize = 10000;\n        const int kCurrentVersion = 6;\n        const unsigned kMaxLayerTypeName = 64; // maximum size of layer name type in bytes (including \\0)\n        const std::string kDefaultLayerType = \"sigmoid\";\n        const char* error_message = \"error@reading config\";\n\n        // READ ... \n        \n        // leyer1 のサイズ\n        uint64_t quazi_layer_size; //10000 *version + layer size が入っている\n        FreadAllOrDie_dyn(&quazi_layer_size, sizeof(int64_t), 1, file, \"failed to read layer size.\");\n        unsigned int layer_size = quazi_layer_size % kVersionStepSize; //\n        int version = quazi_layer_size / kVersionStepSize;\n        if(version > kCurrentVersion || version < kCurrentVersion){\n            fprintf(stderr, \"unknown version: %\" PRIu64, quazi_layer_size / kVersionStepSize );\n            exit(1);\n        }\n\n        // direct\n        unsigned long int maxent_hash_size;\n        FreadAllOrDie_dyn(&maxent_hash_size, sizeof(int64_t), 1, file, error_message);\n        unsigned int maxent_order;\n        FreadAllOrDie_dyn(&maxent_order, sizeof(int), 1, file, error_message);\n\n        // nce\n        real nce_lnz_ = 9; // default value\n        bool use_nce_;\n        FreadAllOrDie_dyn(&use_nce_, sizeof(bool), 1, file, error_message);\n        use_nce = use_nce_;\n        FreadAllOrDie_dyn(&nce_lnz_, sizeof(real), 1, file, error_message);\n        nce_lnz = nce_lnz_;\n\n        // 読み込むだけのパラメタ (RNNLM toolkit に関係の無いパラメタ)\n        bool reverse_sentence;\n        char buffer[kMaxLayerTypeName];\n        int layer_count;\n        int hs_arity;\n        FreadAllOrDie_dyn(&reverse_sentence, sizeof(bool), 1, file, error_message);\n        FreadAllOrDie_dyn(&buffer, sizeof(char), kMaxLayerTypeName, file, error_message); // 固定長\n        FreadAllOrDie_dyn(&layer_count, sizeof(int), 1, file, error_message);\n        FreadAllOrDie_dyn(&hs_arity, sizeof(int), 1, file, error_message);\n        \n        // 決め打ちでセットするパラメタ (faster-rnnlm には無いパラメタ)\n        independent = true; // 文は独立\n\n        // RNNLM 用のパラメタを設定\n        layer0_size = vocab_size + layer_size;\n        layer1_size = layer_size;\n        layerc_size = 0;\n        layer2_size = vocab_size;\n        direct_size = maxent_hash_size;\n        direct_order = maxent_order;\n\n    }/*}}}*/\n\n    real CRnnLM_dyn::calc_direct_score(int word, context* c){/*{{{*/\n        unsigned long long hash[MAX_NGRAM_ORDER] = {};\n        unsigned long long hash_max = direct_size - vocab_size;\n        unsigned int a,b;\n        unsigned int d_o = direct_order;\n        double direct_score = 0;\n\n        for (a=0; a<d_o; ++a) {\n            b=0;\n            hash[a]=PRIMES[0]*PRIMES[1];\n\n            for (b=1; b<=a; b++){\n                hash[a]+=PRIMES[(a*PRIMES[b]+b)%PRIMES_SIZE]*(unsigned long long)(c->history[b-1]+1);\n            }\n            hash[a]=(hash[a]%(hash_max));\n        }\n\n        for (a=0; a<d_o; ++a) {\n            direct_score += (*syn_d)[(hash[a] + word)%hash_max]; \n            if(a>0 && c->history[a-1] == 0) break;\n        }\n        return direct_score;\n    }/*}}}*/\n\n    real CRnnLM_dyn::random(real min, real max)/*{{{*/\n    {\n        return rand()/(real)RAND_MAX*(max-min)+min;\n    }/*}}}*/\n\n    void CRnnLM_dyn::setRnnLMFile(const char *str)/*{{{*/\n    {\n        strcpy(rnnlm_file, str);\n    }/*}}}*/\n\n    int CRnnLM_dyn::searchVocab(char *word)\n    {//{{{\n        //*mmfstr = word;\n        //std::string stdkey = word;\n        //auto vitr = vocab_map->find(*mmfstr);\n        auto vitr = vocab_map->find(shash(std::string(word)));\n        if( vitr == vocab_map->end()){\n            return -1;\n        }else{\n            return vitr->second;\n        }\n\n        return -1; //return OOV if not found\n    }//}}}\n\n    void CRnnLM_dyn::saveFullContext(context *dest)\t\t\n    {//{{{\n        int a;\n            \n        dest->l1_neuron.resize(layer1_size);\n        dest->history.resize(MAX_NGRAM_ORDER);\n        dest->last_word = history[0];\n        dest->have_recurrent = false;\n        \n        //vector<real> l1_neuron = layer1_size;\n        //vector<cahr> history = layer1_size;\n        for (a=0; a<layer1_size; a++) dest->l1_neuron[a] = neu1[a].ac;\n        for (a=0; a<MAX_NGRAM_ORDER; a++) dest->history[a] = history[a];\n    }//}}}\n\n    void CRnnLM_dyn::CacheRecurrent(context *dest)\t\t\n    {//{{{\n        dest->have_recurrent = true;\n        for (int a=0; a<layer1_size; a++) dest->l1_neuron[a] = neu1[a].ac;\n    }//}}}\n\n    void CRnnLM_dyn::restoreFullContext(const context *dest) \n    {//{{{\n        //std::cerr << \"restoreFullContext history_size:\" << dest->history.size() << \" \" << (int)dest->last_word << \" ,\" << (int)dest->history[0] << \",\" << (int)dest->history[1] << std::endl; //H?\n        int a;\n        for (a=0; a<layer1_size; a++) neu1[a].ac = dest->l1_neuron[a];\n        for (a=0; a<MAX_NGRAM_ORDER; a++) history[a] = dest->history[a];\n        if(dest->have_recurrent){\n            for (a=0; a<layer1_size; a++) neu1[a].ac = dest->l1_neuron[a];\n        }else{\n            // TODO: 直接 neu0に 移したほうが速い... 下を後で試す\n            for (a=0; a<layer1_size; a++) neu0[a+vocab_size].ac = dest->l1_neuron[a];\n\n            //for (a=0; a<layer1_size; a++) neu1[a].ac = dest->l1_neuron[a];\n            //copyHiddenLayerToInput(); // neu0 に移す\n        }\n    }//}}}\n\n    void CRnnLM_dyn::initNetFR()\n    {//{{{\n\n        neu0=(struct neuron *)calloc(layer0_size, sizeof(struct neuron));\n        neu1=(struct neuron *)calloc(layer1_size, sizeof(struct neuron));\n        neu2=(struct neuron *)calloc(layer2_size, sizeof(struct neuron));\n\n    }//}}}\n\n    // RNNLM モデル，語彙の読み込みを行う(faster-rnnlm 対応版)\n    void CRnnLM_dyn::restoreNet_FR()    //will read whole network structure\n    {//{{{\n        int a, b;\n        float fl;\n\n        // Filename\n        const std::string model_vocab_file = rnnlm_file; \n        const std::string model_weight_file = model_vocab_file + \".nnet\"; // ネットワークの重み\n\n        // 語彙 (vocab, vocab_map)\n        FILE *vocab_file = fopen(model_vocab_file.c_str(), \"rb\");\n        if (vocab_file == NULL){\n            fprintf(stderr, \"Error: vocaburary file %s not found. \\n\", model_vocab_file.c_str());\n            exit(1);\n        }\n            \n        std::string MapVocabFilePath= model_vocab_file+\".map\";\n        if( access( MapVocabFilePath.c_str(), F_OK ) != -1 ){ //メモリマップからの読み込み\n            if (debug_mode>0) \n                std::cerr << \"read mapped file\" << std::endl;\n            p_file_vocab = new bip::managed_mapped_file(bip::open_read_only, MapVocabFilePath.c_str());\n            vocab_map = p_file_vocab->find<umap_vocab>(\"map_vocab\").first;\n        }else{ //モデルファイルの読み込み\n            if (debug_mode>0) \n                std::cerr << \"read original file\" << std::endl;\n            \n            // 大きめに1GB (10M文で85MB程度)とる(あとでshrink)\n            unsigned long long map_vocab_size = 1024 * 1024 * 1024; \n            // メモリマップファイルを作成\n            p_file_vocab = new bip::managed_mapped_file(bip::create_only, MapVocabFilePath.c_str(), map_vocab_size ); \n            // メモリマップ内にvocablary 用の領域を確保\n            vocab_map = p_file_vocab->construct<umap_vocab>(\"map_vocab\")( 0, boost::hash<uint64_t>(), std::equal_to<uint64_t>(), p_file_vocab->get_allocator<hashPair>());\n                 \n            // 語彙の vocab, と vocab_map への登録\n            for (int line_number = 0; !feof(vocab_file); ++line_number) {\n                char buffer[MAX_STRING];\n                uint64_t count; \n                if (fscanf(vocab_file, \"%s %\" PRIu64 \" \", buffer, &count) != 2) {\n                    fprintf(stderr, \"WARNING: Skipping ill-formed line #%d in the vocabulary\\n\", line_number);\n                    continue;\n                }\n                    \n                int wid = line_number;\n                auto hash_key = shash(std::string(buffer));\n                if(vocab_map->find(hash_key) == vocab_map->end())\n                    (*vocab_map)[shash(std::string(buffer))] = wid; \n                else\n                    std::cerr << \"Collision:\" << buffer << \", \" << wid << std::endl; \n\n                if(debug_mode>1)\n                    std::cerr << buffer << \", \" << wid << std::endl; \n            }\n            // メモリマップへの書き込みを flush\n            p_file_vocab->flush();\n            // メモリマップのサイズ shrink\n            bip::managed_mapped_file::shrink_to_fit(MapVocabFilePath.c_str());\n        }\n        fclose(vocab_file);\n        \n        // vocab_map を全て読み込んでから，vocab に逆向きのmap を作成(デバッグ用)\n        vocab_size = vocab_map->size();\n        if (debug_mode>0) {\n            vocab_file = fopen(model_vocab_file.c_str(), \"rb\");\n\n            if (vocab!=NULL) free(vocab);\n            vocab_max_size=vocab_size+1000;\n            vocab=(struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word));    //initialize memory for vocabulary\n\n            for (int line_number = 0; !feof(vocab_file); ++line_number) {\n                char buffer[MAX_STRING];\n                uint64_t count; \n                if (fscanf(vocab_file, \"%s %\" PRIu64 \" \", buffer, &count) != 2) {\n                    fprintf(stderr, \"WARNING: Skipping ill-formed line #%d in the vocabulary\\n\", line_number);\n                    continue;\n                }\n                \n                auto wid = searchVocab(buffer);\n                // Debug に必要であれば vocab ファイルに登録\n                if(wid != -1)\n                    strncpy(vocab[wid].word, buffer, strlen(buffer));\n            }\n\n            fclose(vocab_file);\n        }\n        \n        // ニューラルネットワークの重み 読み出し\n        FILE *model_file = fopen(model_weight_file.c_str(), \"rb\");\n        if (model_file == NULL){\n            fprintf(stderr, \"Error: model file %s not found. \\n\", model_weight_file.c_str());\n            exit(1);\n        }\n        \n        ReadFRHeader(model_file);\n            \n        if (debug_mode>0) \n            std::cerr << \"reading model file\" << std::endl;\n        \n        if (neu0==NULL) initNetFR(); //memory allocation (neu0, neu1, neu2)\n        \n        if (use_nce != true){\n            std::cerr << \"err:use nce\" << std::endl;\n            exit(1); //DEB\n        }\n\n        const std::string MapFilePath( model_vocab_file + \".nnet.map\" );\n        if( access( MapFilePath.c_str(), F_OK ) != -1 ){ //読み込みのみ\n            p_file_syn = new bip::managed_mapped_file(bip::open_read_only, MapFilePath.c_str());\n            if(debug_mode>0)\n                std::cerr << \"reading RNNLM model\" << std::endl;\n            syn_vocab_l1 = p_file_syn->find<vector_syn>(\"syn_vocab_l1\").first;\n            syn_rec      = p_file_syn->find<vector_syn>(\"syn_rec\").first;\n            syn_l1_l2    = p_file_syn->find<vector_syn>(\"syn_l1_l2\").first;\n        }else{ //通常読み込み\n            unsigned long long syn_size = sizeof(real)*(vocab_size*layer1_size + layer1_size*layer1_size + layer2_size*layer1_size) + 4096;\n            p_file_syn = new bip::managed_mapped_file(bip::create_only, MapFilePath.c_str(), syn_size );\n            syn_vocab_l1 = p_file_syn->construct<vector_syn>(\"syn_vocab_l1\")(p_file_syn->get_segment_manager());\n            syn_rec      = p_file_syn->construct<vector_syn>(\"syn_rec\")(p_file_syn->get_segment_manager());\n            syn_l1_l2    = p_file_syn->construct<vector_syn>(\"syn_l1_l2\")(p_file_syn->get_segment_manager());\n\n            if(debug_mode>0)\n                std::cerr << \"reading embedding\" << std::endl;\n            syn_vocab_l1->resize(vocab_size*layer1_size);\n            for (a=0; a<vocab_size; a++) { //vocab_size < layer_0.size\n                for (b=0; b<layer1_size; b++) {\n                    fread(&fl, sizeof(fl), 1, model_file); //real\n                    (*syn_vocab_l1)[b+a*layer1_size]=fl;\n                }\n            } \n\n            // TODO: 初期化．どうせ使う時初期化するはずなので，不要かも\n            for (a=0; a<layer1_size; a++) {\n                neu1[a].ac=0; \n            }\n\n            if(debug_mode>0)\n                std::cerr << \"reading NCE layer \" << std::endl; \n            // W:layer1 -> output (word embedding => layer1\n            syn_l1_l2->resize(layer1_size*layer2_size);\n            for (b=0; b<layer2_size; b++) { \n                for (a=0; a<layer1_size; a++) {\n                    fread(&fl, sizeof(fl), 1, model_file);\n                    (*syn_l1_l2)[a+b*layer1_size]=fl;\n                }\n            }\n            \n            if(debug_mode>0)\n                std::cerr << \"reading reccurent weight\" << std::endl;\n            // Recurrent weight\n            syn_rec->resize(layer1_size*layer1_size);\n            for (b=0; b<layer1_size; b++) {\n                for (a=0; a<layer1_size; a++) {\n                    fread(&fl, sizeof(fl), 1, model_file);\n                    (*syn_rec)[a+b*layer1_size]=fl; \n                }\n            }\n            p_file_syn->flush();\n        }\n         \n        if(debug_mode>0)\n            std::cerr << \"reading direct weight\" << std::endl;\n\n        const std::string FilePath( model_vocab_file + \".direct\" );\n        if( access( FilePath.c_str(), F_OK ) != -1 ){ //読み込みのみ\n            p_file_direct = new bip::managed_mapped_file( bip::open_read_only, FilePath.c_str() ); \n            syn_d = p_file_direct->find<vector_syn>(\"MyVector\").first;\n            if(debug_mode>0)\n                std::cerr << \"read finished\"<< std::endl;\n        }else{\n            // 初回起動時は Memory mapped file に読み込み\n            p_file_direct = new bip::managed_mapped_file( bip::create_only, FilePath.c_str(), direct_size*sizeof(real)+4096 );\n            syn_d = p_file_direct->construct<vector_syn>(\"MyVector\")(p_file_direct->get_segment_manager());\n            if(debug_mode>0)\n                std::cerr << \"Creating memory mapped file:\" << std::endl;\n\n            real fl;\n            (*syn_d).resize(direct_size);\n            for (unsigned long long b=0; b<direct_size; b++) {\n                fread(&fl, sizeof(real), 1, model_file); //real\n                (*syn_d)[b]=fl;\n            }\n            p_file_direct->flush(); \n            if(debug_mode>0)\n                std::cerr << \"Creating memory mapped file: finished.\"<< std::endl;\n        }\n        \n        fclose(model_file);\n        return;\n    }//}}}\n\n    void CRnnLM_dyn::matrixXvector(struct neuron *dest, struct neuron *srcvec, vector_syn *srcmatrix, int matrix_width, int from, int to, int from2, int to2, int type)\n    {//{{{\n        int a, b;\n        real val1, val2, val3, val4;\n        real val5, val6, val7, val8;\n\n        if (type==0) {\t\t//ac mod\n            for (b=0; b<(to-from)/8; b++) {\n                val1=0;\n                val2=0;\n                val3=0;\n                val4=0;\n\n                val5=0;\n                val6=0;\n                val7=0;\n                val8=0;\n\n                for (a=from2; a<to2; a++) {\n                    val1 += srcvec[a].ac * (*srcmatrix)[a+(b*8+from+0)*matrix_width];\n                    val2 += srcvec[a].ac * (*srcmatrix)[a+(b*8+from+1)*matrix_width];\n                    val3 += srcvec[a].ac * (*srcmatrix)[a+(b*8+from+2)*matrix_width];\n                    val4 += srcvec[a].ac * (*srcmatrix)[a+(b*8+from+3)*matrix_width];\n\n                    val5 += srcvec[a].ac * (*srcmatrix)[a+(b*8+from+4)*matrix_width];\n                    val6 += srcvec[a].ac * (*srcmatrix)[a+(b*8+from+5)*matrix_width];\n                    val7 += srcvec[a].ac * (*srcmatrix)[a+(b*8+from+6)*matrix_width];\n                    val8 += srcvec[a].ac * (*srcmatrix)[a+(b*8+from+7)*matrix_width];\n                }\n                dest[b*8+from+0].ac += val1;\n                dest[b*8+from+1].ac += val2;\n                dest[b*8+from+2].ac += val3;\n                dest[b*8+from+3].ac += val4;\n\n                dest[b*8+from+4].ac += val5;\n                dest[b*8+from+5].ac += val6;\n                dest[b*8+from+6].ac += val7;\n                dest[b*8+from+7].ac += val8;\n            }\n\n            for (b=b*8; b<to-from; b++) {\n                for (a=from2; a<to2; a++) {\n                    dest[b+from].ac += srcvec[a].ac * (*srcmatrix)[a+(b+from)*matrix_width];\n                }\n            }\n        }\n        else {\t\t//er mod\n            for (a=0; a<(to2-from2)/8; a++) {\n                val1=0;\n                val2=0;\n                val3=0;\n                val4=0;\n\n                val5=0;\n                val6=0;\n                val7=0;\n                val8=0;\n\n                for (b=from; b<to; b++) {\n                    val1 += srcvec[b].er * (*srcmatrix)[a*8+from2+0+b*matrix_width];\n                    val2 += srcvec[b].er * (*srcmatrix)[a*8+from2+1+b*matrix_width];\n                    val3 += srcvec[b].er * (*srcmatrix)[a*8+from2+2+b*matrix_width];\n                    val4 += srcvec[b].er * (*srcmatrix)[a*8+from2+3+b*matrix_width];\n\n                    val5 += srcvec[b].er * (*srcmatrix)[a*8+from2+4+b*matrix_width];\n                    val6 += srcvec[b].er * (*srcmatrix)[a*8+from2+5+b*matrix_width];\n                    val7 += srcvec[b].er * (*srcmatrix)[a*8+from2+6+b*matrix_width];\n                    val8 += srcvec[b].er * (*srcmatrix)[a*8+from2+7+b*matrix_width];\n                }\n                dest[a*8+from2+0].er += val1;\n                dest[a*8+from2+1].er += val2;\n                dest[a*8+from2+2].er += val3;\n                dest[a*8+from2+3].er += val4;\n\n                dest[a*8+from2+4].er += val5;\n                dest[a*8+from2+5].er += val6;\n                dest[a*8+from2+6].er += val7;\n                dest[a*8+from2+7].er += val8;\n            }\n\n            for (a=a*8; a<to2-from2; a++) {\n                for (b=from; b<to; b++) {\n                    dest[a+from2].er += srcvec[b].er * (*srcmatrix)[a+from2+b*matrix_width];\n                }\n            }\n\n            if (gradient_cutoff>0)\n                for (a=from2; a<to2; a++) {\n                    if (dest[a].er>gradient_cutoff) dest[a].er=gradient_cutoff;\n                    if (dest[a].er<-gradient_cutoff) dest[a].er=-gradient_cutoff;\n                }\n        }\n\n        //this is normal implementation (about 3x slower):\n\n        /*if (type==0) {\t\t//ac mod\n          for (b=from; b<to; b++) {\n          for (a=from2; a<to2; a++) {\n          dest[b].ac += srcvec[a].ac * srcmatrix[a+b*matrix_width].weight;\n          }\n          }\n          }\n          else \t\t//er mod\n          if (type==1) {\n          for (a=from2; a<to2; a++) {\n          for (b=from; b<to; b++) {\n          dest[a].er += srcvec[b].er * srcmatrix[a+b*matrix_width].weight;\n          }\n          }\n          }*/\n    }//}}}\n\n    // 今までの状態を上書きし，破壊することに注意\n    void CRnnLM_dyn::computeNet_selfnm(int word, context *context)\n    {//{{{\n        int a, b;\n        int last_word_local = context->history[0];\n\n        \n        // 語彙数次元のベクトル\n        if (last_word_local!=-1) neu0[last_word_local].ac=1;\n        \n        // 0-(vocab)-(layer1)-layer0_size\n        // 0...vocab(layer0_size-layer1_size -1) が語彙の次元\n        // layer0_size-layer1_size > layer0_size がコンテクストの次元\n        restoreFullContext(context); // コンテクストをneu0 のコンテクストへコピー，history をセット\n        \n        // 未知語に対しては計算しない\n        if(word == -1) return; \n\n        if(context->have_recurrent){\n            // context が recurrent に含まれるなら，それを読み込むだけに留める.\n            \n        }else{\n            //propagate 0->1\n            for (a=0; a<layer1_size; a++) neu1[a].ac=0; //初期化\n                \n            // コンテクストvectorについての計算 context vector X reccurrent weight\n            auto *syn_r = syn_rec; //syn0 +vocab_size*layer1_size;\n            auto *neu_r = neu0 +vocab_size;\n            matrixXvector(neu1, neu_r, syn_r, layer1_size, 0, layer1_size, 0, layer1_size, 0); \n                \n            CacheRecurrent(context);\n        }\n                \n        // last_word について計算(one hot)\n        if(last_word_local != -1)\n            for (b=0; b<layer1_size; b++) {\n                a=last_word_local;\n                neu1[b].ac += (*syn_vocab_l1)[b+a*layer1_size];\n            }\n            \n        // layer 1 の activation(sigmoid)\n        for (a=0; a<layer1_size; a++) {\n            neu1[a].ac=1/(1+std::exp(-neu1[a].ac));\n        }\n                        \n        //1->2 class\n        double direct_score = 0.0;\n        if (direct_size>0) { //RNNME を使う場合\n            direct_score = calc_direct_score(word, context);\n        }\n                \n        double rnn_score = 0.0;\n        for (a=0; a<layer1_size; a++) {\n            rnn_score += neu1[a].ac * (*syn_l1_l2)[a + word*layer1_size];\n        }\n            \n        // exp 前 スコア\n        neu2[word].ac = std::exp( rnn_score + direct_score - nce_lnz );\n                \n        if(debug_mode > 0)\n            std::cerr << \"p(\" << vocab[word].word << \"|\" << vocab[context->history[0]].word << \", \" << vocab[context->history[1]].word << \", ...) = \" << neu2[word].ac << \" (nn_score:\" << rnn_score << \" direct_score:\" << direct_score << \")\"<< std::endl;\n\n    }//}}}\n    \n    void CRnnLM_dyn::copyHiddenLayerToInput()\n    {//{{{\n        //std::cout << \"copyHiddenLayerToInput\"<< std::endl;\n        int a;\n\n        for (a=0; a<layer1_size; a++) {\n            neu0[a+layer0_size-layer1_size].ac=neu1[a].ac;\n        }\n    }//}}}\n\n    void CRnnLM_dyn::get_initial_context_FR(context *c) \n    {//{{{\n        if (debug_mode>0) std::cerr << \"initializing RNNLM FR\" << std::endl;\n        restoreNet_FR(); // initialize モデル読込  重い\n        //computeNet(0, 0); // initialize \n        copyHiddenLayerToInput();\n        //saveContext(); \n        //saveContext2(); //必要？　\n        for (int a=0; a<MAX_NGRAM_ORDER; a++) history[a]=-1;\n        history[0]=0;\n        saveFullContext(c); //文頭としてInitial context を作成\n    }//}}}\n    \n    real CRnnLM_dyn::test_word_selfnm(context *c, context *new_c, std::string next_word, size_t word_length)\n    {//{{{\n        int last_word;\n        last_word = c->last_word;\n        real senp;\n\n        real lambda=1;\n        real logp=0;\n        senp=0; //\n\n        int word = searchVocab((char*)next_word.c_str());\n\n        // 文区切りを0に対応させる アドホックな対処\n        if(next_word == \"<EOS>\" || next_word == \"<BOS>\")\n            word = 0;\n        \n        // RNN の実行 (結果はneu2[word].ac に書き込まれる\n        computeNet_selfnm(word,c);\n\n        double ln_score = neu2[word].ac;\n       \n        if (word!=-1) { //OOVでない\n            logp+=log10(ln_score);\n            senp+=log10(ln_score*lambda); \n        } else {\n            //assign to OOVs some score to correctly rescore nbest lists, reasonable value can be less than 1/|V| or backoff LM score (in case it is trained on more data)\n            //this means that PPL results from nbest list rescoring are not true probabilities anymore (as in open vocabulary LMs)\n                \n            // 文字の長さに対してlinear に設定する\n            real oov_penalty=-5; //log penalty\n            if(lpenalty){ //penalty を文字の長さに対して線形に与える.\n               oov_penalty -= lweight * word_length;\n            }\n                \n            logp+=oov_penalty;\n            senp+=oov_penalty;\n        }\n            \n        copyHiddenLayerToInput(); //必要？\n        if (last_word!=-1) neu0[last_word].ac=0;  //delete previous activation\n            \n        // history の更新\n        for (int a=MAX_NGRAM_ORDER-1; a>0; a--)\n            history[a] = c->history[a-1];\n        history[0] = word;\n            \n        // context の保存 // history の渡し方が暗黙的\n        saveFullContext(new_c);\n\n        return senp;\n    }//}}}\n\n}\n", "meta": {"hexsha": "83a5e447ad5315f7142bdd7c848e9d7d2ddd0cac", "size": 24281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rnnlm/rnnlmlib_dynamic.cpp", "max_stars_repo_name": "yingfeng/jumanpp", "max_stars_repo_head_hexsha": "314e0a7672b89e5a973b99906e9d7b2c6fdd3d99", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rnnlm/rnnlmlib_dynamic.cpp", "max_issues_repo_name": "yingfeng/jumanpp", "max_issues_repo_head_hexsha": "314e0a7672b89e5a973b99906e9d7b2c6fdd3d99", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rnnlm/rnnlmlib_dynamic.cpp", "max_forks_repo_name": "yingfeng/jumanpp", "max_forks_repo_head_hexsha": "314e0a7672b89e5a973b99906e9d7b2c6fdd3d99", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.0579937304, "max_line_length": 252, "alphanum_fraction": 0.5170709608, "num_tokens": 7048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.22997364162397252}}
{"text": "/*\n * (C) Copyright 2021 Met Office UK\n *\n * This software is licensed under the terms of the Apache Licence Version 2.0\n * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.\n */\n\n#include <Eigen/Dense>\n#include <algorithm>\n#include <set>\n\n#include \"ioda/ObsDataVector.h\"\n#include \"oops/util/IntSetParser.h\"\n#include \"oops/util/missingValues.h\"\n#include \"ufo/filters/obsfunctions/CloudCostFunction.h\"\n#include \"ufo/filters/Variable.h\"\n#include \"ufo/utils/ufo_utils.interface.h\"\n\nnamespace ufo {\n\nstatic ObsFunctionMaker<CloudCostFunction> makerCloudCostFunction_(\"CloudCostFunction\");\n\nCloudCostFunction::CloudCostFunction(const eckit::LocalConfiguration & conf)\n  : invars_() {\n  // Initialize options\n  options_.deserialize(conf);\n\n  // List of field names for B matrix\n  fields_ = options_.field_names.value();\n\n  // Get channels for computing scattering index from options\n  std::set<int> chanset = oops::parseIntSet(options_.chanlist.value());\n  channels_.assign(chanset.begin(), chanset.end());\n\n  // List of required data\n  for (size_t i = 0; i < fields_.size(); ++i) {\n    invars_ += Variable(\"brightness_temperature_jacobian_\"+fields_[i]+\"@ObsDiag\", channels_);\n  }\n  invars_ += Variable(\"brightness_temperature@ObsValue\", channels_);\n  invars_ += Variable(\"brightness_temperature@\"+options_.HofXGroup.value(), channels_);\n  invars_ += Variable(\"latitude@MetaData\");\n  if (options_.qtotal_lnq_gkg.value()) {\n    invars_ += Variable(\"specific_humidity@GeoVaLs\");\n    invars_ += Variable(\"mass_content_of_cloud_liquid_water_in_atmosphere_layer@GeoVaLs\");\n    invars_ += Variable(\"mass_content_of_cloud_ice_in_atmosphere_layer@GeoVaLs\");\n    invars_ += Variable(\"air_pressure@GeoVaLs\");\n    invars_ += Variable(\"air_temperature@GeoVaLs\");\n    invars_ += Variable(\"surface_pressure@GeoVaLs\");\n    invars_ += Variable(\"surface_temperature@GeoVaLs\");\n    invars_ += Variable(\"specific_humidity_at_two_meters_above_surface@GeoVaLs\");\n  }\n}\n\n// -----------------------------------------------------------------------------\n\nvoid CloudCostFunction::compute(const ObsFilterData & in,\n                                    ioda::ObsDataVector<float> & out) const {\n  // Get dimensions\n  const size_t nlocs = in.nlocs();\n  const size_t nchans = channels_.size();\n  ASSERT(nchans > 0);\n  ASSERT(out.nvars() == 1);\n\n  // B, R error covariance objects\n  eckit::LocalConfiguration bMatrixConf;\n  bMatrixConf.set(\"BMatrix\", options_.bmatrix_filepath.value());\n  bMatrixConf.set(\"background fields\", options_.field_names.value());\n  bMatrixConf.set(\"qtotal\", options_.qtotal_lnq_gkg.value());\n  MetOfficeBMatrixStatic staticB(bMatrixConf);\n\n  eckit::LocalConfiguration rMatrixConf;\n  rMatrixConf.set(\"RMatrix\", options_.rmatrix_filepath.value());\n  MetOfficeRMatrixRadiance staticR(rMatrixConf);\n\n  bool split_rain = options_.qtotal_split_rain.value();\n\n  const std::string clw_name = \"mass_content_of_cloud_liquid_water_in_atmosphere_layer\";\n  const std::string ciw_name = \"mass_content_of_cloud_ice_in_atmosphere_layer\";\n  std::vector<float> gv_pres(nlocs), gv_temp(nlocs), gv_qgas(nlocs), gv_clw(nlocs), gv_ciw(nlocs),\n                     humidity_total(nlocs);\n\n  // Determine if pressure is ascending or descending (B-matrix assumption)\n  size_t np = in.nlevs(Variable(\"air_pressure@GeoVaLs\"));\n  std::vector<float> gv_pres_1(nlocs), gv_pres_N(nlocs);\n  in.get(Variable(\"air_pressure@GeoVaLs\"), 1, gv_pres_1);\n  in.get(Variable(\"air_pressure@GeoVaLs\"), np, gv_pres_N);\n  const float missing = util::missingValue(missing);\n  ASSERT(gv_pres_1[0] != missing);\n  ASSERT(gv_pres_N[0] != missing);\n  bool p_ascending = (gv_pres_N[0] > gv_pres_1[0]);\n\n  // Assemble combined Jacobian from component fields\n  std::vector<std::vector<std::vector<float>>>\n       jac_vec(nlocs, std::vector<std::vector<float>>(nchans, std::vector<float>()));\n  for (size_t ifield = 0; ifield < fields_.size(); ++ifield) {\n    if (options_.qtotal_lnq_gkg.value() &&\n            (fields_[ifield] == clw_name || fields_[ifield] == ciw_name)) {\n      // qtotal ln(g/kg) Jacobian calculated when \"specific_humidity\" is reached in field list\n      continue;\n    }\n    std::string jac_name = \"brightness_temperature_jacobian_\"+fields_[ifield]+\"@ObsDiag\";\n    size_t nlevs = in.nlevs(Variable(jac_name, channels_)[0]);\n    std::vector<float> jac_store(nlocs);\n    for (size_t ilev = 0; ilev < nlevs; ++ilev) {\n      int level_gv = (p_ascending ? ilev+1 : nlevs-ilev);\n      int level_jac = (options_.reverse_Jacobian.value() ? nlevs-level_gv+1 : level_gv);\n      if (fields_[ifield] == \"specific_humidity\" && options_.qtotal_lnq_gkg.value()) {\n        in.get(Variable(\"air_pressure@GeoVaLs\"), level_gv, gv_pres);\n        in.get(Variable(\"air_temperature@GeoVaLs\"), level_gv, gv_temp);\n        in.get(Variable(\"specific_humidity@GeoVaLs\"), level_gv, gv_qgas);\n        in.get(Variable(clw_name+\"@GeoVaLs\"), level_gv, gv_clw);\n        in.get(Variable(ciw_name+\"@GeoVaLs\"), level_gv, gv_ciw);\n        std::vector<float> qsaturated(nlocs);\n        ufo_ops_satrad_qsatwat_f90(qsaturated.data(), gv_temp.data(), gv_pres.data(),\n                                   static_cast<int>(nlocs));\n        for (size_t iloc = 0; iloc < nlocs; ++iloc) {\n          // Ensure specific humidity is within limits\n          gv_qgas[iloc] = std::max(gv_qgas[iloc], options_.min_q.value());\n          gv_qgas[iloc] = std::min(gv_qgas[iloc], qsaturated[iloc]);\n          humidity_total[iloc] = gv_qgas[iloc] + gv_clw[iloc] + gv_ciw[iloc];\n        }\n      }\n\n      for (size_t ichan = 0; ichan < nchans; ++ichan) {\n        in.get(Variable(jac_name, channels_)[ichan], level_jac, jac_store);\n\n        if (fields_[ifield] == \"specific_humidity\" && options_.qtotal_lnq_gkg.value()) {\n          std::vector<float> jac_clw(nlocs), jac_ciw(nlocs);\n          in.get(Variable(\"brightness_temperature_jacobian_\"+clw_name+\"@ObsDiag\", channels_)[ichan],\n                 level_jac, jac_clw);\n          in.get(Variable(\"brightness_temperature_jacobian_\"+ciw_name+\"@ObsDiag\", channels_)[ichan],\n                 level_jac, jac_ciw);\n          std::vector<float> dq_dqtotal(nlocs), dql_dqtotal(nlocs), dqi_dqtotal(nlocs);\n          int qsplit_mode = 2;  // compute derivatives\n          ufo_ops_satrad_qsplit_f90(qsplit_mode, static_cast<int>(nlocs), gv_pres.data(),\n                                    gv_temp.data(), humidity_total.data(), dq_dqtotal.data(),\n                                    dql_dqtotal.data(), dqi_dqtotal.data(), split_rain);\n          // Jacobian dy/dx for observation y, humdity x in units kg/kg\n          // For alternative units of B-matrix humidity z in ln(g/kg)\n          // chain rule gives dy/dz = x.(dy/dx)\n          // Gradient due to ice is ignored unless we are using scattering radiative transfer\n          // dTb/dln(qt) = qt*(dTb/dq*dq/dqt + dTb/dql*dql/dqt [+ dTb/dqi*dqi/dqt])\n          for (size_t iloc = 0; iloc < nlocs; ++iloc) {\n            jac_store[iloc] *= dq_dqtotal[iloc];\n            jac_store[iloc] += jac_clw[iloc]*dql_dqtotal[iloc];\n            if (options_.scattering_switch.value()) {\n              jac_store[iloc] += jac_ciw[iloc]*dqi_dqtotal[iloc];\n            }\n            jac_store[iloc] *= humidity_total[iloc];\n          }\n        }\n\n        if (fields_[ifield] == \"specific_humidity_at_two_meters_above_surface\"\n            && options_.qtotal_lnq_gkg.value()) {\n          in.get(Variable(\"surface_pressure@GeoVaLs\"), level_gv, gv_pres);\n          in.get(Variable(\"surface_temperature@GeoVaLs\"), level_gv, gv_temp);\n          in.get(Variable(\"specific_humidity_at_two_meters_above_surface@GeoVaLs\"),\n                 level_gv, gv_qgas);\n          std::vector<float> qsaturated(nlocs);\n          ufo_ops_satrad_qsatwat_f90(qsaturated.data(), gv_temp.data(), gv_pres.data(),\n                                     static_cast<int>(nlocs));\n          for (size_t iloc = 0; iloc < nlocs; ++iloc) {\n            gv_qgas[iloc] = std::max(gv_qgas[iloc], options_.min_q.value());\n            gv_qgas[iloc] = std::min(gv_qgas[iloc], qsaturated[iloc]);\n            // dTb/dln(q2m) = q2m*(dTb/dq2m)\n            jac_store[iloc] *= gv_qgas[iloc];\n          }\n        }\n\n        for (size_t iloc = 0; iloc < nlocs; ++iloc) {\n          jac_vec[iloc][ichan].push_back(jac_store[iloc]);\n        }\n      }\n    }\n  }\n\n  const size_t sizeB = staticB.getsize();\n  for (size_t iloc = 0; iloc < nlocs; ++iloc) {\n    for (size_t ichan = 0; ichan < nchans; ++ichan) {\n      ASSERT(jac_vec[iloc][ichan].size() == sizeB);\n    }\n  }\n\n  // Get departures = ObsValue - HofX (where HofX is bias corrected)\n  std::vector<std::vector<float>> departures(nlocs, std::vector<float>(nchans));\n  std::vector<float> obsvalues(nlocs);\n  std::vector<float> bgvalues(nlocs);\n  std::vector<bool> is_out_of_bounds(nlocs, false);\n  for (size_t ichan = 0; ichan < nchans; ++ichan) {\n    in.get(Variable(\"brightness_temperature@ObsValue\", channels_)[ichan], obsvalues);\n    in.get(Variable(\"brightness_temperature@\"+options_.HofXGroup.value(), channels_)[ichan],\n           bgvalues);\n    for (size_t iloc = 0; iloc < nlocs; ++iloc) {\n      departures[iloc][ichan] = obsvalues[iloc] - bgvalues[iloc];\n      // Flag observations outside expected bounds\n      if (obsvalues[iloc] < options_.minTb.value() || obsvalues[iloc] > options_.maxTb.value()) {\n        is_out_of_bounds[iloc] = true;\n      }\n    }\n  }\n\n  std::vector<float> latitude(nlocs);\n  in.get(Variable(\"latitude@MetaData\"), latitude);\n  Eigen::MatrixXf Hmatrix(nchans, sizeB);\n\n  for (size_t iloc = 0; iloc < nlocs; ++iloc) {\n    if (is_out_of_bounds[iloc]) {\n      out[0][iloc] = options_.maxCost.value();\n      continue;\n    }\n\n    for (size_t ichan = 0; ichan < nchans; ++ichan) {\n      Hmatrix.row(ichan) = Eigen::Map<Eigen::VectorXf>(jac_vec[iloc][ichan].data(), sizeB);\n    }\n\n    // Matrix of departures dy\n    Eigen::Map<Eigen::VectorXf> dy(departures[iloc].data(), nchans);\n\n    // Calculate Scratch_matrix = H.B.H^T + R\n    Eigen::MatrixXf BHT;\n    staticB.multiply(latitude[iloc], Hmatrix.transpose(), BHT);\n    Eigen::MatrixXf HBHT = Hmatrix*BHT;\n    Eigen::MatrixXf Scratch_matrix;\n    staticR.add(channels_, HBHT, Scratch_matrix);\n\n    // Calculate Scratch_matrix2 = Scratch_matrix^-1.dy using Cholesky decomposition\n    Eigen::LLT<Eigen::MatrixXf> decomposition(Scratch_matrix);\n    if (decomposition.info() == Eigen::NumericalIssue) {\n      oops::Log::warning() <<\n        \"CloudCostFunction Scratch_matrix appears not to be positive definite\" << std::endl;\n      out[0][iloc] = options_.maxCost.value();\n      continue;\n    }\n    Eigen::VectorXf Scratch_matrix2 = decomposition.solve(dy);\n\n    // Final cost\n    float Cost_final = 0.5*dy.transpose()*Scratch_matrix2;\n    Cost_final /= static_cast<float>(nchans);  // normalise by number of channels\n    out[0][iloc] = std::min(Cost_final, options_.maxCost.value());\n  }\n}\n\n// -----------------------------------------------------------------------------\n\nconst ufo::Variables & CloudCostFunction::requiredVariables() const {\n  return invars_;\n}\n\n// -----------------------------------------------------------------------------\n\n}  // namespace ufo\n", "meta": {"hexsha": "ab11430aa361bbed3dbcd4e2cf3d9cd2b0da74dd", "size": 11127, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/ufo/filters/obsfunctions/CloudCostFunction.cc", "max_stars_repo_name": "fmahebert/ufo", "max_stars_repo_head_hexsha": "2af9b91433553ca473c72fcd131400a01c3aabdb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-08T16:37:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T16:37:25.000Z", "max_issues_repo_path": "src/ufo/filters/obsfunctions/CloudCostFunction.cc", "max_issues_repo_name": "fmahebert/ufo", "max_issues_repo_head_hexsha": "2af9b91433553ca473c72fcd131400a01c3aabdb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T17:18:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-08T17:40:31.000Z", "max_forks_repo_path": "src/ufo/filters/obsfunctions/CloudCostFunction.cc", "max_forks_repo_name": "fmahebert/ufo", "max_forks_repo_head_hexsha": "2af9b91433553ca473c72fcd131400a01c3aabdb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2021-06-24T18:07:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-08T15:40:39.000Z", "avg_line_length": 44.1547619048, "max_line_length": 100, "alphanum_fraction": 0.6490518558, "num_tokens": 3093, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.22996647805794782}}
{"text": "#ifndef RLSS_INTERNAL_UTIL_HPP\n#define RLSS_INTERNAL_UTIL_HPP\n\n#include <Eigen/Geometry>\n#include <boost/functional/hash/hash_fwd.hpp>\n#include <memory>\n#include <Eigen/Dense>\n#include <queue>\n#include <functional>\n#include <stdexcept>\n#include <absl/strings/str_cat.h>\n#include <iostream>\n#include <fstream>\n#include <qp_wrappers/cplex.hpp>\n#include <qp_wrappers/gurobi.hpp>\n#include <qp_wrappers/qpoases.hpp>\n#include <qp_wrappers/osqp.hpp>\n#include <splx/curve/PiecewiseCurve.hpp>\n#include <lp_wrappers/cplex.hpp>\n#include <lp_wrappers/gurobi.hpp>\n\n#define RLSS_HARD_QP_SOLVER CPLEX\n#define RLSS_SOFT_QP_SOLVER CPLEX\n#define RLSS_SVM_QP_SOLVER qpOASES\n#define RLSS_HP_PRUNING_LP_SOLVER GUROBI\n\nnamespace rlss {\n\n#ifdef ENABLE_RLSS_DEBUG_MESSAGES\nnamespace internal {\n    // methods for debugging\n    template<typename T>\n    void debug_message_internal(bool first, const T& message) {\n        if(first) {\n            std::cout << \"[DEBUG] \";\n        }\n        std::cout << message << std::endl;\n    }\n\n    template<typename T, typename... Args>\n    void debug_message_internal(bool first, const T& message, const Args&... args) {\n        if(first) {\n            std::cout << \"[DEBUG] \";\n        }\n        std::cout << message;\n        debug_message_internal(false, args...);\n    }\n} // namespace internal\n\n    template<typename... Args>\n    void debug_message(const Args&... args) {\n        internal::debug_message_internal(true, args...);\n    }\n#else\n    template<typename... Args>\n    void debug_message(const Args&... args) {\n\n    }\n#endif\n\nnamespace internal {\n    namespace debug {\n        namespace colors {\n            constexpr char RESET[] = \"\\033[0m\";\n            constexpr char RED[] = \"\\033[31m\";\n            constexpr char GREEN[] = \"\\033[32m\";\n        }\n    }\n}\n\nnamespace internal {\n\ntemplate<typename T, unsigned int DIM>\nusing AlignedBox = Eigen::AlignedBox<T, DIM>;\n\ntemplate<typename T, unsigned int DIM>\nusing Hyperplane = Eigen::Hyperplane<T, DIM>;\n\ntemplate<typename T, unsigned int DIM>\nusing VectorDIM = Eigen::Matrix<T, DIM, 1>;\n\ntemplate<typename T, unsigned int DIM>\nusing StdVectorVectorDIM = std::vector<VectorDIM<T,DIM>,\n                            Eigen::aligned_allocator<VectorDIM<T,DIM>>>;\n\ntemplate<typename T>\nusing Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>;\n\ntemplate<typename T>\nusing Row = Eigen::Matrix<T, 1, Eigen::Dynamic>;\n\ntemplate<typename T>\nusing Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;\n\ntemplate<typename T, unsigned int R, unsigned int C>\nusing MatrixRC = Eigen::Matrix<T, R, C>; // row column\n\n// method to get corner points of the Eigen AlignedBox passed as argument\ntemplate<typename T, unsigned int DIM>\nStdVectorVectorDIM<T, DIM> cornerPoints(const AlignedBox<T, DIM>& box) {\n    StdVectorVectorDIM<T, DIM> pts(1<<DIM);\n    for(unsigned int i = 0; i < (1<<DIM); i++) {\n        for(unsigned int d = 0; d < DIM; d++) {\n            pts[i](d) = (i & (1<<d)) ? box.min()(d) : box.max()(d);\n        }\n    }\n    return pts;\n}\n\n// method to return hash value based on vector coordinates passed\ntemplate<typename T, unsigned int DIM>\nclass VectorDIMHasher {\npublic:\n    std::size_t operator()(const VectorDIM<T, DIM>& vec) const {\n        std::size_t seed = 0;\n        for(unsigned int d = 0; d < DIM; d++) {\n            boost::hash_combine(seed, vec(d));\n        }\n        return seed;\n    }\n};\n\n// linear interpolation of two vector points. Returns a vector container of\n// points based on number of interpolated points passed\ntemplate <typename T, unsigned int DIM>\nStdVectorVectorDIM<T, DIM> linearInterpolate(\n    const VectorDIM<T, DIM>& start,\n    const VectorDIM<T, DIM>& end,\n    std::size_t num_points\n) {\n\n    using StdVectorVectorDIM = StdVectorVectorDIM<T, DIM>;\n    using VectorDIM = VectorDIM<T, DIM>;\n\n    if(num_points < 2) {\n        throw std::domain_error(\n            absl::StrCat\n            (\n                \"linear interpolate can't have less than 2 number of points\",\n                \" given: \",\n                num_points\n            )\n        );\n    }\n\n    StdVectorVectorDIM result(num_points);\n\n    VectorDIM step_vec = (end - start) / (num_points - 1);\n\n    result[0] = start;\n    for(std::size_t step = 1; step < num_points - 1; step++) {\n        result[step] = start + step * step_vec;\n    }\n    result.back() = end;\n\n    return result;\n\n\n}\n\n// method to check if the discrete path search algorithm splits the path segments\n// to the minimum required number of segments\ntemplate <typename T, unsigned int DIM>\nStdVectorVectorDIM<T, DIM> bestSplitSegments(\n    const StdVectorVectorDIM<T, DIM>& segments,\n    std::size_t num_pieces\n) {\n    // if current number of segments is larger than the number of pieces, throws error\n    if(num_pieces + 1 < segments.size()) {\n        throw std::domain_error(\n            absl::StrCat\n            (\n                \"nothing to split since num_pieces=\",\n                num_pieces,\n                \"is less than current number of segments \",\n                segments.size() - 1\n            )\n        );\n    }\n\n\n    using VectorDIM = VectorDIM<T, DIM>;\n    using StdVectorVectorDIM = StdVectorVectorDIM<T, DIM>;\n\n    // if segements is currently of size 1, return a vector of size num_pieces + 1 with\n    // all of values of that segment\n    if(segments.size() == 1) {\n        return StdVectorVectorDIM(num_pieces + 1, segments[0]);\n    }\n\n    // define segment priority queue element\n    struct SegmentPQElem {\n        VectorDIM start;\n        VectorDIM end;\n        T length;\n        unsigned int num_pieces;\n        std::size_t segment_idx;\n\n        SegmentPQElem(const VectorDIM& s, const VectorDIM& e, std::size_t i)\n                :   start(s),\n                    end(e),\n                    length((s-e).norm()),\n                    num_pieces(1),\n                    segment_idx(i)\n        {\n\n        }\n\n        // operator to compare the average length of the segment\n        bool operator<(const SegmentPQElem& rhs) const {\n            return this->length / this->num_pieces\n                        < rhs.length / rhs.num_pieces;\n        }\n    };\n\n    std::priority_queue\n    <\n        SegmentPQElem,\n        std::vector<SegmentPQElem>\n    > pq;\n\n    // initialize and store segmentPQelements in PQ\n    // store current segment point and next segment point and the index of that segment\n    for(std::size_t i = 0; i < segments.size()-1; i++) {\n        pq.push({segments[i], segments[i+1], i});\n    }\n\n    // enters iteration only if there are excess segments\n    // remove excess segments, such that the segments vector container size equals to the\n    // number of segments to be generated\n    for(std::size_t p_count = segments.size() - 1;\n            p_count < num_pieces; p_count++) {\n        SegmentPQElem t = pq.top();\n        pq.pop();\n        t.num_pieces++;\n        pq.push(t);\n    }\n\n    // iteratively process the priority queue to store into the segment pq elements vector\n    std::vector<SegmentPQElem> segment_pqelems;\n    while(!pq.empty()) {\n        segment_pqelems.push_back(pq.top());\n        pq.pop();\n    }\n\n    // sort the segments based on their segment length from shortest to longest\n    std::sort(\n            segment_pqelems.begin(),\n            segment_pqelems.end(),\n            [] (const SegmentPQElem& lhs, const SegmentPQElem& rhs) -> bool {\n                return lhs.segment_idx < rhs.segment_idx;\n            }\n    );\n\n    StdVectorVectorDIM result;\n\n    // interpolate every segment and split them into the number of pieces that segment\n    // is to be interpolated, and store the segment points into the vector\n    for(const SegmentPQElem& pqelem: segment_pqelems) {\n        StdVectorVectorDIM interpolate\n            = linearInterpolate<T, DIM>(\n                    pqelem.start,\n                    pqelem.end,\n                    pqelem.num_pieces + 1\n        );\n\n        // append to the back of results vector\n        result.insert(result.end(), interpolate.begin(), interpolate.end() - 1);\n    }\n\n    result.push_back(segments.back());\n    return  result;\n}\n\ntemplate<typename T, unsigned int DIM>\nStdVectorVectorDIM<T, DIM> firstSegmentFix(\n    const StdVectorVectorDIM<T, DIM>& segments\n) {\n    assert(segments.size() > 1);\n\n    StdVectorVectorDIM<T, DIM> result;\n    result.push_back(segments[0]);\n    result.push_back((segments[0] + segments[1]) / 2);\n    for(std::size_t i = 1; i < segments.size(); i++) {\n        result.push_back(segments[i]);\n    }\n    return result;\n}\n// shift hyperplane hp creating hyperplane shp\n// such that whenever the center_of_mass of the robot\n// is to the negative side of the shp,\n// the collision shape box of the\n// robot is to the negative side of the hyperplane hp.\n// box should be the bounding box of the collision shape at given\n// center_of_mass\ntemplate<typename T, unsigned int DIM>\nHyperplane<T, DIM> shiftHyperplane(\n    const VectorDIM<T, DIM>& center_of_mass,\n    const AlignedBox<T, DIM>& box,\n    const Hyperplane<T, DIM>& hp\n) {\n    using Hyperplane = Hyperplane<T, DIM>;\n    using StdVectorVectorDIM = StdVectorVectorDIM<T, DIM>;\n    Hyperplane shp {hp.normal(), std::numeric_limits<T>::lowest()};\n\n\n    StdVectorVectorDIM corner_points = cornerPoints<T, DIM>(box);\n\n    for(const auto& pt : corner_points) {\n        shp.offset()\n                = std::max(shp.offset(),\n                           hp.normal().dot(pt - center_of_mass) + hp.offset()\n        );\n    }\n\n    return shp;\n}\n\n/*\n* Buffer 'box' so that when center_of_mass is inside the buffered box\n* com_box corresponding to robot with center of mass 'center_of_mass'\n* is inside the 'box'\n*/\ntemplate<typename T, unsigned int DIM>\nAlignedBox<T, DIM> bufferAlignedBox(\n    const VectorDIM<T, DIM>& center_of_mass,\n    const AlignedBox<T, DIM>& com_box,\n    const AlignedBox<T, DIM>& box\n) {\n    return AlignedBox<T, DIM>(box.min() + (center_of_mass - com_box.min()),\n                      box.max() + (center_of_mass - com_box.max()));\n}\n\n/*\n * Prunes hyperplanes h in hps such that if the space S bounded by the bounding\n * box bbox and the hyperplane h contains the space S' bounded by the bounding\n * box bbox and an hyperplane h' in hps (that is S' is a subset of S).\n */\ntemplate<typename T, unsigned int DIM>\nstd::vector<Hyperplane<T, DIM>> pruneHyperplanes(\n        const std::vector<Hyperplane<T,DIM>>& hps,\n        const AlignedBox<T, DIM>& bbox) {\n\n    using Hyperplane = Hyperplane<T, DIM>;\n    using AlignedBox = AlignedBox<T, DIM>;\n    using LP = LPWrappers::Problem<T>;\n    using LPEngine = LPWrappers::RLSS_HP_PRUNING_LP_SOLVER::Engine<T>;\n    using Vector = typename LPEngine::Vector;\n\n    std::vector<Hyperplane> result = hps;\n    LP lp(DIM, 2);\n    LPEngine solver;\n\n    for(unsigned int d = 0; d < DIM; d++) {\n        lp.set_var_limits(d, bbox.min()(d), bbox.max()(d));\n    }\n\n    Vector c(DIM);\n    for(unsigned int d = 0; d < DIM; d++) c(d) = 1;\n    lp.add_c(c);\n\n    for(std::size_t i = 0; i < result.size(); i++) {\n        bool should_remove_i = false;\n\n        lp.set_constraint(1, result[i].normal().transpose(),\n                result[i].offset(), LP::infinity);\n\n        for(std::size_t j = 0; j < result.size(); j++) {\n            if(i == j) continue;\n\n            lp.set_constraint(0, result[j].normal().transpose(),\n                    LP::minus_infinity, result[j].offset());\n\n            Vector soln;\n            auto ret = solver.init(lp, soln);\n            if(ret != LPWrappers::OptReturnType::Optimal) {\n                should_remove_i = true;\n                break;\n            }\n        }\n\n        if(should_remove_i) {\n            std::swap(result[i], result.back());\n            result.pop_back();\n            i--;\n        }\n    }\n\n\n    return result;\n}\n\n\n} // namespace internal\n\n// ellipsoid class\ntemplate<typename T, unsigned int DIM>\nclass Ellipsoid {\npublic:\n    using VectorDIM = rlss::internal::VectorDIM<T, DIM>;\n    using MatrixDIMDIM = rlss::internal::MatrixRC<T, DIM, DIM>;\n    using AlignedBox = rlss::internal::AlignedBox<T, DIM>;\n    using Index = Eigen::Index;\n\n    Ellipsoid(const VectorDIM& cnt, const MatrixDIMDIM& m)\n        : center(cnt), mtr(m) {\n        mtrInvSq = mtr.inverse();\n        mtrInvSq = mtrInvSq * mtrInvSq;\n\n    }\n\n    AlignedBox boundingBox() const {\n        // https://members.loria.fr/samuel.hornus/ellipsoid-bbox.html\n        VectorDIM delta;\n        for(Index r = 0; r < DIM; r++) {\n            delta(r) = mtr.row(r).norm();\n        }\n\n        debug_message(center - delta, center + delta);\n\n        return AlignedBox(center - delta, center + delta);\n    }\n\n    bool intersects(const AlignedBox& box) const {\n        if(box.contains(this->center)) {\n            return true;\n        }\n\n        auto crnr = internal::cornerPoints<T, DIM>(box);\n        for(const auto& pt: crnr) {\n            VectorDIM d = pt - center;\n            if(d.transpose() * mtrInvSq * d <= 1) {\n                return true;\n            }\n        }\n        return false;\n    }\n\nprivate:\n    VectorDIM center;\n    // affine transformation matrix that transforms unit sphere\n    // at origin to the ellipsoid at origin\n    MatrixDIMDIM mtr;\n    MatrixDIMDIM mtrInvSq;\n};\n\n} // namespace rlss\n\n#endif // RLSS_INTERNAL_UTIL_HPP", "meta": {"hexsha": "4acae79fca63d612c9496b1bf987da8872d808a2", "size": 13184, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rlss/internal/Util.hpp", "max_stars_repo_name": "sieniven/rlss", "max_stars_repo_head_hexsha": "b1f7ff1abf316242a0644b76559ad921fbca3099", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/rlss/internal/Util.hpp", "max_issues_repo_name": "sieniven/rlss", "max_issues_repo_head_hexsha": "b1f7ff1abf316242a0644b76559ad921fbca3099", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rlss/internal/Util.hpp", "max_forks_repo_name": "sieniven/rlss", "max_forks_repo_head_hexsha": "b1f7ff1abf316242a0644b76559ad921fbca3099", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3630289532, "max_line_length": 90, "alphanum_fraction": 0.6163531553, "num_tokens": 3241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.2297801849999489}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2015 Muhammad Junaid Muzammil <mjunaidmuzammil@gmail.com>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//\n// See http://boostorg.github.com/compute for more information.\n//---------------------------------------------------------------------------//\n\n#ifndef BOOST_COMPUTE_RANDOM_THREEFRY_HPP\n#define BOOST_COMPUTE_RANDOM_THREEFRY_HPP\n\n#include <algorithm>\n\n#include <boost/compute/types.hpp>\n#include <boost/compute/buffer.hpp>\n#include <boost/compute/kernel.hpp>\n#include <boost/compute/context.hpp>\n#include <boost/compute/program.hpp>\n#include <boost/compute/command_queue.hpp>\n#include <boost/compute/algorithm/transform.hpp>\n#include <boost/compute/detail/iterator_range_size.hpp>\n#include <boost/compute/utility/program_cache.hpp>\n#include <boost/compute/container/vector.hpp>\n#include <boost/compute/iterator/discard_iterator.hpp>\n\nnamespace boost {\nnamespace compute {\n\n/// \\class threefry_engine\n/// \\brief Threefry pseudorandom number generator.\ntemplate<class T = uint_>\nclass threefry_engine\n{\npublic:\n    static const size_t threads = 1024;\n    typedef T result_type;\n\n    /// Creates a new threefry_engine and seeds it with \\p value.\n    explicit threefry_engine(command_queue &queue)\n        : m_context(queue.get_context())\n    {\n        // setup program\n        load_program();\n    }\n\n    /// Creates a new threefry_engine object as a copy of \\p other.\n    threefry_engine(const threefry_engine<T> &other)\n        : m_context(other.m_context),\n          m_program(other.m_program)\n    {\n    }\n\n    /// Copies \\p other to \\c *this.\n    threefry_engine<T>& operator=(const threefry_engine<T> &other)\n    {\n        if(this != &other){\n            m_context = other.m_context;\n            m_program = other.m_program;\n        }\n\n        return *this;\n    }\n\n    /// Destroys the threefry_engine object.\n    ~threefry_engine()\n    {\n    }\n\nprivate:\n    /// \\internal_\n    void load_program()\n    {\n        boost::shared_ptr<program_cache> cache =\n            program_cache::get_global_cache(m_context);\n        std::string cache_key =\n            std::string(\"threefry_engine_32x2\");\n\n        // Copyright 2010-2012, D. E. Shaw Research.\n        // All rights reserved.\n\n        // Redistribution and use in source and binary forms, with or without\n        // modification, are permitted provided that the following conditions are\n        // met:\n\n        // * Redistributions of source code must retain the above copyright\n        //   notice, this list of conditions, and the following disclaimer.\n\n        // * Redistributions in binary form must reproduce the above 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        // * Neither the name of D. E. Shaw Research nor the names of its\n        //   contributors may be used to endorse or promote products derived from\n        //   this software without specific prior written permission.\n\n        // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n        // \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n        // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n        // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n        // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n        // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n        // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n        // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n        // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n        // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n        // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n        const char source[] =\n            \"#define THREEFRY2x32_DEFAULT_ROUNDS 20\\n\"\n            \"#define SKEIN_KS_PARITY_32 0x1BD11BDA\\n\"\n\n            \"enum r123_enum_threefry32x2 {\\n\"\n            \"    R_32x2_0_0=13,\\n\"\n            \"    R_32x2_1_0=15,\\n\"\n            \"    R_32x2_2_0=26,\\n\"\n            \"    R_32x2_3_0= 6,\\n\"\n            \"    R_32x2_4_0=17,\\n\"\n            \"    R_32x2_5_0=29,\\n\"\n            \"    R_32x2_6_0=16,\\n\"\n            \"    R_32x2_7_0=24\\n\"\n            \"};\\n\"\n\n            \"static uint RotL_32(uint x, uint N)\\n\"\n            \"{\\n\"\n            \"    return (x << (N & 31)) | (x >> ((32-N) & 31));\\n\"\n            \"}\\n\"\n\n            \"struct r123array2x32 {\\n\"\n            \"    uint v[2];\\n\"\n            \"};\\n\"\n            \"typedef struct r123array2x32 threefry2x32_ctr_t;\\n\"\n            \"typedef struct r123array2x32 threefry2x32_key_t;\\n\"\n\n            \"threefry2x32_ctr_t threefry2x32_R(unsigned int Nrounds, threefry2x32_ctr_t in, threefry2x32_key_t k)\\n\"\n            \"{\\n\"\n            \"    threefry2x32_ctr_t X;\\n\"\n            \"    uint ks[3];\\n\"\n            \"    uint  i; \\n\"\n            \"    ks[2] =  SKEIN_KS_PARITY_32;\\n\"\n            \"    for (i=0;i < 2; i++) {\\n\"\n            \"        ks[i] = k.v[i];\\n\"\n            \"        X.v[i]  = in.v[i];\\n\"\n            \"        ks[2] ^= k.v[i];\\n\"\n            \"    }\\n\"\n            \"    X.v[0] += ks[0]; X.v[1] += ks[1];\\n\"\n            \"    if(Nrounds>0){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_0_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>1){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_1_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>2){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_2_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>3){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_3_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>3){\\n\"\n            \"        X.v[0] += ks[1]; X.v[1] += ks[2];\\n\"\n            \"        X.v[1] += 1;\\n\"\n            \"    }\\n\"\n            \"    if(Nrounds>4){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_4_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>5){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_5_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>6){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_6_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>7){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_7_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>7){\\n\"\n            \"        X.v[0] += ks[2]; X.v[1] += ks[0];\\n\"\n            \"        X.v[1] += 2;\\n\"\n            \"    }\\n\"\n            \"    if(Nrounds>8){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_0_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>9){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_1_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>10){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_2_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>11){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_3_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>11){\\n\"\n            \"        X.v[0] += ks[0]; X.v[1] += ks[1];\\n\"\n            \"        X.v[1] += 3;\\n\"\n            \"    }\\n\"\n            \"    if(Nrounds>12){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_4_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>13){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_5_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>14){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_6_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>15){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_7_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>15){\\n\"\n            \"        X.v[0] += ks[1]; X.v[1] += ks[2];\\n\"\n            \"        X.v[1] += 4;\\n\"\n            \"    }\\n\"\n            \"    if(Nrounds>16){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_0_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>17){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_1_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>18){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_2_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>19){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_3_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>19){\\n\"\n            \"        X.v[0] += ks[2]; X.v[1] += ks[0];\\n\"\n            \"        X.v[1] += 5;\\n\"\n            \"    }\\n\"\n            \"    if(Nrounds>20){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_4_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>21){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_5_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>22){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_6_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>23){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_7_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>23){\\n\"\n            \"        X.v[0] += ks[0]; X.v[1] += ks[1];\\n\"\n            \"        X.v[1] += 6;\\n\"\n            \"    }\\n\"\n            \"    if(Nrounds>24){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_0_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>25){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_1_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>26){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_2_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>27){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_3_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>27){\\n\"\n            \"        X.v[0] += ks[1]; X.v[1] += ks[2];\\n\"\n            \"        X.v[1] += 7;\\n\"\n            \"    }\\n\"\n            \"    if(Nrounds>28){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_4_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>29){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_5_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>30){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_6_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>31){  X.v[0] += X.v[1]; X.v[1] = RotL_32(X.v[1],R_32x2_7_0); X.v[1] ^= X.v[0]; }\\n\"\n            \"    if(Nrounds>31){\\n\"\n            \"        X.v[0] += ks[2]; X.v[1] += ks[0];\\n\"\n            \"        X.v[1] += 8;\\n\"\n            \"    }\\n\"\n            \"    return X;\\n\"\n            \"}\\n\"\n\n            \"__kernel void generate_rng(__global uint *ctr, __global uint *key, const uint offset) {\\n\"\n            \"    threefry2x32_ctr_t in;\\n\"\n            \"    threefry2x32_key_t k;\\n\"\n            \"    const uint i = get_global_id(0);\\n\"\n            \"    in.v[0] = ctr[2 * (offset + i)];\\n\"\n            \"    in.v[1] = ctr[2 * (offset + i) + 1];\\n\"\n            \"    k.v[0] = key[2 * (offset + i)];\\n\"\n            \"    k.v[1] = key[2 * (offset + i) + 1];\\n\"\n            \"    in = threefry2x32_R(20, in, k);\\n\"\n            \"    ctr[2 * (offset + i)] = in.v[0];\\n\"\n            \"    ctr[2 * (offset + i) + 1] = in.v[1];\\n\"\n            \"}\\n\";\n\n        m_program = cache->get_or_build(cache_key, std::string(), source, m_context);\n    }\n\npublic:\n\n\n    /// Generates Threefry random numbers using both the counter and key values, and then stores\n    /// them to the range [\\p first_ctr, \\p last_ctr).\n    template<class OutputIterator>\n    void generate(OutputIterator first_ctr, OutputIterator last_ctr, OutputIterator first_key, OutputIterator last_key, command_queue &queue) {\n        const size_t size_ctr = detail::iterator_range_size(first_ctr, last_ctr);\n        const size_t size_key = detail::iterator_range_size(first_key, last_key);\n        if(!size_ctr || !size_key || (size_ctr != size_key)) {\n            return;\n        }\n        kernel rng_kernel = m_program.create_kernel(\"generate_rng\");\n\n        rng_kernel.set_arg(0, first_ctr.get_buffer());\n        rng_kernel.set_arg(1, first_key.get_buffer());\n        size_t offset = 0;\n\n        for(;;){\n            size_t count = 0;\n            size_t size = size_ctr/2;\n            if(size > threads){\n                count = (std::min)(static_cast<size_t>(threads), size - offset);\n            }\n            else {\n                count = size;\n            }\n            rng_kernel.set_arg(2, static_cast<const uint_>(offset));\n            queue.enqueue_1d_range_kernel(rng_kernel, 0, count, 0);\n\n            offset += count;\n\n            if(offset >= size){\n                break;\n            }\n\n        }\n    }\n\n    template<class OutputIterator>\n    void generate(OutputIterator first_ctr, OutputIterator last_ctr, command_queue &queue) {\n        const size_t size_ctr = detail::iterator_range_size(first_ctr, last_ctr);\n        if(!size_ctr) {\n            return;\n        }\n        boost::compute::vector<uint_> vector_key(size_ctr, m_context);\n        vector_key.assign(size_ctr, 0, queue);\n        kernel rng_kernel = m_program.create_kernel(\"generate_rng\");\n\n        rng_kernel.set_arg(0, first_ctr.get_buffer());\n        rng_kernel.set_arg(1, vector_key);\n        size_t offset = 0;\n\n        for(;;){\n            size_t count = 0;\n            size_t size = size_ctr/2;\n            if(size > threads){\n                count = (std::min)(static_cast<size_t>(threads), size - offset);\n            }\n            else {\n                count = size;\n            }\n            rng_kernel.set_arg(2, static_cast<const uint_>(offset));\n            queue.enqueue_1d_range_kernel(rng_kernel, 0, count, 0);\n\n            offset += count;\n\n            if(offset >= size){\n                break;\n            }\n\n        }\n    }\nprivate:\n    context m_context;\n    program m_program;\n};\n\n} // end compute namespace\n} // end boost namespace\n\n#endif // BOOST_COMPUTE_RANDOM_THREEFRY_HPP\n", "meta": {"hexsha": "d521ca14c7da9890d25b217faa7064ea2ef4846f", "size": 13640, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/compute/random/threefry_engine.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-15T20:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-15T20:03:51.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/compute/random/threefry_engine.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-12T00:39:44.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/compute/random/threefry_engine.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-12T01:07:34.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-12T01:07:34.000Z", "avg_line_length": 43.7179487179, "max_line_length": 143, "alphanum_fraction": 0.5019061584, "num_tokens": 4661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2297239013092188}}
{"text": "/*!\n * @file swp_surfvolhydrogen_primary.cpp\n * @author Robert I A Patterson Robert.Patterson@wias-berlin.de\n *\n  \n  Copyright (C) 2012 Robert I A Patterson\n\n  File purpose:\n    Implementation of the SurfVolHydrogenPrimary class declared in the\n    swp_surfvol_primary.h header file.\n    @brief Implementation of particle described by its volume and surface area.\n\n  Licence:\n    This file is part of \"sweepc\".\n\n    sweepc is free software; you can redistribute it and/or\n    modify it under the terms of the GNU General Public License\n    as published by the Free Software Foundation; either version 2\n    of the License, or (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program; if not, write to the Free Software\n    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.\n\n  Contact:\n    Dr Markus Kraft\n    Dept of Chemical Engineering\n    University of Cambridge\n    New Museums Site\n    Pembroke Street\n    Cambridge\n    CB2 3RA\n    UK\n\n    Email:       mk306@cam.ac.uk\n    Website:     http://como.cheng.cam.ac.uk\n*/\n\n#include \"swp_primary.h\"\n#include \"swp_surfvolhydrogen_primary.h\"\n#include \"swp_aggmodel_type.h\"\n#include \"swp_model_factory.h\"\n\n#include <stdexcept>\n#include <boost/random/poisson_distribution.hpp>\n\nusing namespace Sweep;\nusing namespace Sweep::AggModels;\n\n\n// CONSTRUCTORS AND DESTRUCTORS.\n\n// Default constructor (protected).\nSurfVolHydrogenPrimary::SurfVolHydrogenPrimary(void)\n: iH(1u)\n{\n}\n\n// Initialising constructor.\nSurfVolHydrogenPrimary::SurfVolHydrogenPrimary(double time, const Sweep::ParticleModel &model)\n: Primary(time, model)\n, iH(1u)\n{\n}\n\n// Copy constructor.\nSurfVolHydrogenPrimary::SurfVolHydrogenPrimary(const SurfVolHydrogenPrimary &copy)\n: iH(1u)\n{\n    *this = copy;\n}\n\n// Stream-reading constructor.\nSurfVolHydrogenPrimary::SurfVolHydrogenPrimary(std::istream &in, const Sweep::ParticleModel &model)\n: iH(1u)\n{\n    Deserialize(in, model);\n}\n\n// Default destructor.\nSurfVolHydrogenPrimary::~SurfVolHydrogenPrimary()\n{\n    releaseMem();\n}\n\n\n// OPERATOR OVERLOADS.\n\n// Assignment operator (Primary RHS).\nSurfVolHydrogenPrimary &SurfVolHydrogenPrimary::operator=(const Primary &rhs)\n{\n    // Attempt to cast the primary to a SurfVolHydrogenPrimary.  This will\n    // throw an exception if the cast fails.\n    operator=(dynamic_cast<const SurfVolHydrogenPrimary&>(rhs));\n\n    return *this;\n}\n\n// Assignment operator (SurfVolHydrogenPrimary RHS).\nSurfVolHydrogenPrimary &SurfVolHydrogenPrimary::operator=(const SurfVolHydrogenPrimary &rhs)\n{\n    // First copy everything for spherical primaries.\n    Primary::operator=(rhs);\n\n    return *this;\n}\n\n\n// AGGREGATION MODEL.\n\n// Returns the aggregation model which this primary describes.\nAggModels::AggModelType SurfVolHydrogenPrimary::AggID(void) const {return AggModels::SurfVolHydrogen_ID;}\n\n\n// BASIC DERIVED PARTICLE PROPERTIES.\n\n// Calculates the derived properties from the unique properties.  This\n// function is broadly similar to the version in the spherical Primary\n// class except that it uses the surface-volume model.  Therefore the\n// surface area is not altered and the collision diameter is calculated\n// using the arithmetic mean function.\nvoid SurfVolHydrogenPrimary::UpdateCache(void)\n{\n    // Store the correct surface area.\n    const double s = m_surf;\n\n    // Pretend that the primary is spherical and set the cache\n    // accordingly.  This will set m_surf the the surface are\n    // of an equivalent volume sphere.\n    Primary::UpdateCache();\n\n    // The surface area is now set to that of a sphere. Set \n    // correct surface area (minimum is spherical surface area).\n    m_surf = std::max(s, m_surf);\n\n   \n    // Calculate diameters.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n    m_dmob = m_dcol; // TODO:  Correct expression for Dmob.\n}\n\n// Returns the equivalent spherical particle surface area.\ndouble SurfVolHydrogenPrimary::SphSurfaceArea(void) const {return PI * std::pow(6.0 * m_vol / PI, TWO_THIRDS);}\n\n// Returns the number of primary particles if the aggregate is assumed\n// to consist of mono-sized primaries.\nunsigned int SurfVolHydrogenPrimary::PP_Count(void) const\n{\n    // Note the minimum number of primary particles must be 1.\n    return std::max(1u, (unsigned int)((m_surf * m_surf * m_surf) /\n                                       (36.0 * PI * m_vol * m_vol)));\n}\n\n// Returns the primary particle diameter if the aggregate is assumed\n// to consist of mono-sized primaries.\ndouble SurfVolHydrogenPrimary::PP_Diameter(void) const\n{\n    // This should always be <= equiv. sphere diameter.\n    return 6.0 * m_vol / m_surf;\n}\n\n\n// OPERATIONS.\n\n// Adjusts the primary with the given composition and \n// tracker values changes n times.  If the particle cannot be adjust\n// n times, then this function returns the number of times\n// it was adjusted.\nunsigned int SurfVolHydrogenPrimary::Adjust(const fvector &dcomp, const fvector &dvalues, rng_type &rng,\n                                    unsigned int n)\n{\n    // Calculate change in volume.\n    double dvol = 0.0;\n    for (unsigned int i=0; i!=dcomp.size(); ++i) {\n        dvol += dcomp[i] * m_pmodel->Components(i)->MolWt() / \n                m_pmodel->Components(i)->Density();\n    }\n    dvol *= (double)n / NA;\n\n    // Calculate change in surface area.\n    double invRadius = 0.0;\n    if (dvol > 0.0) {\n        // Inverse growth radius.\n        invRadius = sqrt(4.0 * PI / m_surf);\n    } else {\n        // Inverse oxidation radius.    \n        invRadius = m_surf / (3.0 * m_vol);\n    }\n\n    // Save new and old surface areas\n    const double oldS = m_surf;\n    const double s = m_surf + (2.0 * dvol * invRadius);\n\n    // Adjust the particle assuming that it is spherical.\n    Primary::Adjust(dcomp, dvalues, rng, n);\n\n    // Maintain the concentration of H per unit surface area during oxidation\n    if(dvol < 0.0) {\n        fvector comp = Composition();\n        //comp[iH] = static_cast<int>(s * comp[iH] / oldS + 0.5);\n        comp[iH] = s * comp[iH] / oldS;\n        SetComposition(comp);\n    }\n\n\n    // Set correct surface area, which was incorrectly set by\n    // Primary::Adjust.\n    m_surf    = std::max(s, m_surf);\n\n    // This has a knock-on affect of changing the collision diameter.\n    // Note, we can avoid recalling UpdateCache() here, because only\n    // a couple of cached values will have changed.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n    m_dmob = m_dcol;\n\n    return n;\n}\n\n/*!\n * Combines this primary with another.\n *\n * \\param[in]       rhs         Particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      Reference to the current instance after rhs has been added\n */\nSurfVolHydrogenPrimary &SurfVolHydrogenPrimary::Coagulate(const Primary &rhs, rng_type &rng)\n\n{\n    // Store the resultant surface area.\n    const double s = m_surf + rhs.SurfaceArea();\n\n    // Perform the coagulation.\n    Primary::Coagulate(rhs, rng);\n\n    // The spherical particle Coagulate() routine has set the\n    // surface area incorrectly.  We now replace the surface area\n    // to the correct point-contact value.\n    m_surf    = std::max(m_surf, s);\n\n    // This has a knock-on affect of changing the collision diameter.\n    // Note, we can avoid recalling UpdateCache() here, because only\n    // a couple of cached values will have changed.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n    m_dmob = m_dcol;\n\n    return *this;\n}\n\n/*!\n * Combines this primary with another.\n *\n * \\param[in]       rhs         Particle to add to current instance\n * \\param[in,out]   rng         Random number generator\n *\n * \\return      Reference to the current instance after rhs has been added\n */\nSurfVolHydrogenPrimary &SurfVolHydrogenPrimary::Fragment(const Primary &rhs, rng_type &rng)\n\n{\n    // Store the resultant surface area.\n    const double s = m_surf + rhs.SurfaceArea();\n\n    // Perform the coagulation.\n    Primary::Fragment(rhs, rng);\n\n    // The spherical particle Coagulate() routine has set the\n    // surface area incorrectly.  We now replace the surface area\n    // to the correct point-contact value.\n    m_surf    = std::max(m_surf, s);\n\n    // This has a knock-on affect of changing the collision diameter.\n    // Note, we can avoid recalling UpdateCache() here, because only\n    // a couple of cached values will have changed.\n    m_dcol = (m_diam + sqrt(m_surf / PI)) * 0.5;\n    m_dmob = m_dcol;\n\n    return *this;\n}\n\n// This routine sinters the Primary for the given length of\n// time using the provided sintering model.\nvoid SurfVolHydrogenPrimary::Sinter(double dt, Cell &sys,\n                            const Processes::SinteringModel &model,\n                            rng_type &rng,\n                            double wt)\n{\n  throw std::runtime_error(\"sintering not implemented at present for SurfVolHydrogenPrimary\");\n}\n\n\n// READ/WRITE/COPY.\n\n// Returns a copy of the model data.\nSurfVolHydrogenPrimary *const SurfVolHydrogenPrimary::Clone(void) const\n{\n    return new SurfVolHydrogenPrimary(*this);\n}\n\n/*!\n * \\return      Number of surface Hydrogens (active sites)\n */\ndouble SurfVolHydrogenPrimary::GetSites() const\n{\n    return Composition()[iH];\n}\n\n\n// Writes the object to a binary stream.\nvoid SurfVolHydrogenPrimary::Serialize(std::ostream &out) const\n{\n    if (out.good()) {\n        // Output the version ID (=0 at the moment).\n        const unsigned int version = 0;\n        out.write((char*)&version, sizeof(version));\n\n        // Output base class.\n        Primary::Serialize(out);\n    } else {\n        throw std::invalid_argument(\"Output stream not ready (Sweep, SurfVolHydrogenPrimary::Serialize).\");\n    }\n}\n\n// Reads the object from a binary stream.\nvoid SurfVolHydrogenPrimary::Deserialize(std::istream &in, const Sweep::ParticleModel &model)\n{\n    if (in.good()) {\n        // Read the output version.  Currently there is only one\n        // output version, so we don't do anything with this variable.\n        // Still needs to be read though.\n        unsigned int version = 0;\n        in.read(reinterpret_cast<char*>(&version), sizeof(version));\n\n        switch (version) {\n            case 0:\n                // Read base class.\n                Primary::Deserialize(in, model);\n                break;\n            default:\n                throw std::runtime_error(\"Serialized version number is invalid (Sweep, SurfVolHydrogenPrimary::Deserialize).\");\n        }\n    } else {\n        throw std::invalid_argument(\"Input stream not ready (Sweep, SurfVolHydrogenPrimary::Deserialize).\");\n    }\n}\n", "meta": {"hexsha": "7fadf646eef7aa36054acfee5bbdb8564d3ca0b8", "size": 10840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sweepc/source/swp_surfvolhydrogen_primary.cpp", "max_stars_repo_name": "sm453/MOpS", "max_stars_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T14:06:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-04T07:52:19.000Z", "max_issues_repo_path": "src/sweepc/source/swp_surfvolhydrogen_primary.cpp", "max_issues_repo_name": "sm453/MOpS", "max_issues_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sweepc/source/swp_surfvolhydrogen_primary.cpp", "max_forks_repo_name": "sm453/MOpS", "max_forks_repo_head_hexsha": "f1a706c6552bbdf3ceab504121a02391a1b51ede", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T05:18:26.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T13:51:20.000Z", "avg_line_length": 30.8831908832, "max_line_length": 127, "alphanum_fraction": 0.6795202952, "num_tokens": 2703, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.44552953503957266, "lm_q1q2_score": 0.22972390130921877}}
{"text": "#include <fstream>\n#include <filesystem>\n\n#include <Eigen/Geometry>\n#include <utility>\n\n#include <pcl/io/ply_io.h>\n#include <pcl/common/transforms.h>\n#include <pcl/common/norms.h>\n#include <pcl/kdtree/impl/kdtree_flann.hpp>\n\n#include \"analysis.h\"\n#include \"filter.h\"\n\n#define N_BINS 4\n\nnamespace fs = std::filesystem;\n\nstd::pair<float, float> calculate_rotation_and_translation_errors(const Eigen::Matrix4f &transformation,\n                                                                  const Eigen::Matrix4f &transformation_gt) {\n    Eigen::Matrix3f rotation_diff = transformation.block<3, 3>(0, 0).inverse() * transformation_gt.block<3, 3>(0, 0);\n    Eigen::Vector3f translation_diff = transformation.block<3, 1>(0, 3) - transformation_gt.block<3, 1>(0, 3);\n    float rotation_error = Eigen::AngleAxisf(rotation_diff).angle();\n    float translation_error = translation_diff.norm();\n    return {rotation_error, translation_error};\n}\n\ninline float dist2(const PointN &p1, const PointN &p2) {\n    return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y) + (p1.z - p2.z) * (p1.z - p2.z);\n};\n\nfloat calculate_point_cloud_rmse(const PointNCloud::ConstPtr &pcd,\n                                 const Eigen::Matrix4f &transformation,\n                                 const Eigen::Matrix4f &transformation_gt) {\n    PointNCloud pcd_transformed;\n    Eigen::Matrix4f transformation_diff = transformation.inverse() * transformation_gt;\n    pcl::transformPointCloud(*pcd, pcd_transformed, transformation_diff);\n\n    float rmse = 0.f;\n    for (int i = 0; i < pcd->size(); ++i) {\n        rmse += dist2(pcd->points[i], pcd_transformed.points[i]);\n    }\n    rmse = std::sqrt(rmse / (float) pcd->size());\n    return rmse;\n}\n\nfloat calculate_overlap_rmse(const PointNCloud::ConstPtr &src, const PointNCloud::ConstPtr &tgt,\n                             const Eigen::Matrix4f &transformation,\n                             const Eigen::Matrix4f &transformation_gt,\n                             float inlier_threshold) {\n    PointNCloud src_aligned, src_aligned_gt;\n    pcl::transformPointCloud(*src, src_aligned, transformation);\n    pcl::transformPointCloud(*src, src_aligned_gt, transformation_gt);\n\n    pcl::KdTreeFLANN<PointN> tree_tgt;\n    tree_tgt.setInputCloud(tgt);\n\n    int overlap_size = 0;\n    float rmse = 0.f;\n    pcl::Indices nn_indices;\n    std::vector<float> nn_dists;\n    for (int i = 0; i < src->size(); ++i) {\n        tree_tgt.nearestKSearch(src_aligned_gt[i], 1, nn_indices, nn_dists);\n        if (nn_dists[0] < inlier_threshold * inlier_threshold) {    // ith point in overlap\n            rmse += dist2(src_aligned.points[i], src_aligned_gt.points[i]);\n            overlap_size++;\n        }\n    }\n    if (overlap_size != 0) {\n        rmse = std::sqrt(rmse / (float)overlap_size);\n    } else {\n        rmse = std::numeric_limits<float>::quiet_NaN();\n    }\n    return rmse;\n\n}\n\nfloat calculate_correspondence_uniformity(const PointNCloud::ConstPtr &src, const PointNCloud::ConstPtr &tgt,\n                                          const pcl::Correspondences &correct_correspondences,\n                                          const AlignmentParameters &parameters,\n                                          const Eigen::Matrix4f &transformation_gt) {\n    PointNCloud::Ptr src_aligned(new PointNCloud);\n    pcl::transformPointCloud(*src, *src_aligned, transformation_gt);\n    pcl::KdTreeFLANN<PointN>::Ptr tree(new pcl::KdTreeFLANN<PointN>());\n    tree->setInputCloud(tgt);\n\n    pcl::Indices indices;\n    std::vector<float> distances;\n    // calculate bbox of overlapping area\n    PointN min_point, max_point;\n    float error_thr = parameters.distance_thr_coef * parameters.voxel_size;\n    for (int i = 0; i < src_aligned->size(); ++i) {\n        (float) tree->nearestKSearch(*src_aligned, i, 1, indices, distances);\n        const PointN &p_src(src_aligned->points[i]), p_tgt(tgt->points[indices[0]]);\n        if (std::sqrt(distances[0]) < error_thr && std::isfinite(p_src.normal_x) && std::isfinite(p_tgt.normal_x)) {\n            min_point.x = std::min(min_point.x, p_src.x);\n            min_point.y = std::min(min_point.y, p_src.y);\n            min_point.z = std::min(min_point.z, p_src.z);\n            max_point.x = std::max(max_point.x, p_src.x);\n            max_point.y = std::max(max_point.y, p_src.y);\n            max_point.z = std::max(max_point.z, p_src.z);\n        }\n    }\n    int count[3][N_BINS][N_BINS]{0};\n\n    for (auto const &corr: correct_correspondences) {\n        const auto &point = src_aligned->points[corr.index_query];\n        if (pointInBoundingBox(point, min_point, max_point)) {\n            int bin[3];\n            bin[0] = std::floor((point.x - min_point.x) / (max_point.x - min_point.x) * N_BINS);\n            bin[1] = std::floor((point.y - min_point.y) / (max_point.y - min_point.y) * N_BINS);\n            bin[2] = std::floor((point.z - min_point.z) / (max_point.z - min_point.z) * N_BINS);\n            // count 3D points projected to YZ, ZX, XY and fallen in 2D bin\n            for (int k = 0; k < 3; ++k) {\n                count[k][bin[(k + 1) % 3]][bin[(k + 2) % 3]]++;\n            }\n        }\n    }\n    float entropy[3]{0.f};\n    float n = correct_correspondences.size();\n    for (int k = 0; k < 3; ++k) {\n        for (int i = 0; i < N_BINS; ++i) {\n            for (int j = 0; j < N_BINS; ++j) {\n                float p = (float) count[k][i][j] / n;\n                if (p == 0.f) continue;\n                entropy[k] -= p * std::log(p);\n            }\n        }\n        entropy[k] /= std::log((float) (N_BINS * N_BINS));\n    }\n    return std::cbrt(entropy[0] * entropy[1] * entropy[2]);\n}\n\nfloat calculate_normal_difference(const PointNCloud::ConstPtr &src, const PointNCloud::ConstPtr &tgt,\n                                  const AlignmentParameters &parameters, const Eigen::Matrix4f &transformation_gt) {\n    PointNCloud::Ptr src_aligned(new PointNCloud);\n    pcl::transformPointCloud(*src, *src_aligned, transformation_gt);\n    pcl::KdTreeFLANN<PointN>::Ptr tree(new pcl::KdTreeFLANN<PointN>());\n    tree->setInputCloud(tgt);\n\n    pcl::Indices indices;\n    std::vector<float> distances;\n    float error_thr = parameters.distance_thr_coef * parameters.voxel_size;\n    float difference = 0.f;\n    int n_points_overlap = 0;\n    for (int i = 0; i < src_aligned->size(); ++i) {\n        (float) tree->nearestKSearch(*src_aligned, i, 1, indices, distances);\n        const PointN &p_src(src_aligned->points[i]), p_tgt(tgt->points[indices[0]]);\n        if (std::sqrt(distances[0]) < error_thr && std::isfinite(p_src.normal_x) && std::isfinite(p_tgt.normal_x)) {\n            float cos = std::clamp(p_src.normal_x * p_tgt.normal_x + p_src.normal_y * p_tgt.normal_y +\n                                   p_src.normal_z * p_tgt.normal_z, -1.f, 1.f);\n            difference += std::abs(std::acos(cos));\n            n_points_overlap++;\n        }\n    }\n    return difference / (float) n_points_overlap;\n}\n\nvoid buildCorrectCorrespondences(const PointNCloud::ConstPtr &src, const PointNCloud::ConstPtr &tgt,\n                                 const pcl::Correspondences &correspondences,\n                                 pcl::Correspondences &correct_correspondences,\n                                 const Eigen::Matrix4f &transformation_gt, float error_threshold) {\n    correct_correspondences.clear();\n    correct_correspondences.reserve(correspondences.size());\n\n    PointNCloud input_transformed;\n    input_transformed.resize(src->size());\n    pcl::transformPointCloud(*src, input_transformed, transformation_gt);\n\n    for (const auto &correspondence: correspondences) {\n        PointN source_point(input_transformed.points[correspondence.index_query]);\n        PointN target_point(tgt->points[correspondence.index_match]);\n        float e = pcl::L2_Norm(source_point.data, target_point.data, 3);\n        if (e < error_threshold) {\n            correct_correspondences.push_back(correspondence);\n        }\n    }\n}\n\nAlignmentAnalysis::AlignmentAnalysis(const AlignmentParameters &parameters,\n                                     const PointNCloud::ConstPtr &src, const PointNCloud::ConstPtr &tgt,\n                                     const pcl::Correspondences &correspondences,\n                                     int iterations, const Eigen::Matrix4f &transformation, double time) {\n    parameters_ = parameters;\n    src_ = src;\n    tgt_ = tgt;\n    correspondences_ = correspondences;\n    iterations_ = iterations;\n    transformation_ = transformation;\n    time_ = time;\n    has_converged_ = true;\n    metric_estimator_ = getMetricEstimator(parameters);\n    metric_estimator_->setSourceCloud(src);\n    metric_estimator_->setTargetCloud(tgt);\n    metric_estimator_->setCorrespondences(correspondences);\n    metric_estimator_->setInlierThreshold(parameters.distance_thr_coef * parameters.voxel_size);\n}\n\nvoid AlignmentAnalysis::start(const Eigen::Matrix4f &transformation_gt, const std::string &testname) {\n    testname_ = testname;\n    float error_thr = parameters_.distance_thr_coef * parameters_.voxel_size;\n    transformation_gt_ = transformation_gt;\n\n    buildCorrectCorrespondences(src_, tgt_, correspondences_, correct_correspondences_, transformation_gt_, error_thr);\n    metric_estimator_->buildInlierPairsAndEstimateMetric(transformation_, inlier_pairs_, rmse_, fitness_);\n    metric_estimator_->buildCorrectInlierPairs(inlier_pairs_, correct_inlier_pairs_, transformation_gt_);\n    pcd_error_ = calculate_point_cloud_rmse(src_, transformation_, transformation_gt_);\n    overlap_error_ = calculate_overlap_rmse(src_, tgt_, transformation_, transformation_gt_, error_thr);\n    normal_diff_ = calculate_normal_difference(src_, tgt_, parameters_, transformation_gt_);\n    corr_uniformity_ = calculate_correspondence_uniformity(src_, tgt_, correct_correspondences_,\n                                                           parameters_, transformation_gt_);\n    std::tie(r_error_, t_error_) = calculate_rotation_and_translation_errors(transformation_, transformation_gt_);\n\n    print();\n    save(testname);\n}\n\nvoid AlignmentAnalysis::print() {\n    // Print results\n    printf(\"\\n\");\n    printTransformation(transformation_);\n    printTransformation(transformation_gt_);\n    pcl::console::print_info(\"fitness: %0.7f\\n\", fitness_);\n    pcl::console::print_info(\"inliers_rmse: %0.7f\\n\", rmse_);\n    pcl::console::print_info(\"correct inliers: %i/%i\\n\", correct_inlier_pairs_.size(), inlier_pairs_.size());\n    pcl::console::print_info(\"correct correspondences: %i/%i\\n\",\n                             correct_correspondences_.size(), correspondences_.size());\n    pcl::console::print_info(\"rotation error: %0.7f\\n\", r_error_);\n    pcl::console::print_info(\"translation error: %0.7f\\n\", t_error_);\n    pcl::console::print_info(\"point cloud mean error: %0.7f\\n\", pcd_error_);\n    pcl::console::print_info(\"normal mean difference: %0.7f\\n\", normal_diff_);\n    pcl::console::print_info(\"uniformity of correct correspondences' distribution: %0.7f\\n\", corr_uniformity_);\n}\n\nvoid AlignmentAnalysis::save(const std::string &testname) {\n    // Save test parameters and results\n    std::string filepath = constructPath(\"test\", \"results\", \"csv\", false);\n    bool file_exists = std::filesystem::exists(filepath);\n    std::fstream fout;\n    if (!file_exists) {\n        fout.open(filepath, std::ios_base::out);\n    } else {\n        fout.open(filepath, std::ios_base::app);\n    }\n    if (fout.is_open()) {\n        if (!file_exists) {\n            printAnalysisHeader(fout);\n        }\n        fout << *this;\n        fout.close();\n    } else {\n        perror((\"error while opening file \" + filepath).c_str());\n    }\n}\n\nvoid printAnalysisHeader(std::ostream &out) {\n    out << \"version,descriptor,testname,fitness,rmse,correspondences,correct_correspondences,inliers,correct_inliers,\";\n    out << \"voxel_size,normal_radius_coef,feature_radius_coef,distance_thr_coef,edge_thr,\";\n    out << \"iteration,matching,randomness,filter,threshold,n_random,r_err,t_err,pcd_err,use_normals,\";\n    out << \"normal_diff,corr_uniformity,lrf,metric,time,overlap_rmse\\n\";\n}\n\nstd::ostream &operator<<(std::ostream &stream, const AlignmentAnalysis &analysis) {\n    stream << VERSION << \",\" << analysis.parameters_.descriptor_id << \",\" << analysis.testname_ << \",\"\n           << analysis.fitness_ << \",\" << analysis.rmse_ << \",\";\n    stream << analysis.correspondences_.size() << \",\" << analysis.correct_correspondences_.size() << \",\";\n    stream << analysis.inlier_pairs_.size() << \",\" << analysis.correct_inlier_pairs_.size() << \",\";\n    stream << analysis.parameters_.voxel_size << \",\";\n    stream << analysis.parameters_.normal_radius_coef << \",\";\n    stream << analysis.parameters_.feature_radius_coef << \",\";\n    stream << analysis.parameters_.distance_thr_coef << \",\";\n    stream << analysis.parameters_.edge_thr_coef << \",\";\n    stream << analysis.iterations_ << \",\";\n    stream << analysis.parameters_.matching_id << \",\";\n    stream << analysis.parameters_.randomness << \",\";\n    auto func = getUniquenessFunction(analysis.parameters_.func_id);\n    if (func != nullptr) {\n        stream << analysis.parameters_.func_id << \",\" << UNIQUENESS_THRESHOLD << \",\" << N_RANDOM_FEATURES << \",\";\n    } else {\n        stream << \",,,\";\n    }\n    stream << analysis.r_error_ << \",\" << analysis.t_error_ << \",\" << analysis.pcd_error_ << \",\";\n    stream << analysis.parameters_.use_normals << \",\" << analysis.normal_diff_ << \",\";\n    stream << analysis.corr_uniformity_ << \",\" << analysis.parameters_.lrf_id << \",\";\n    stream << analysis.parameters_.metric_id << \",\" << analysis.time_ << \",\" << analysis.overlap_error_ << \"\\n\";\n    return stream;\n}\n", "meta": {"hexsha": "ca04f6ce49c75e507f1a262f8609e6758ce842f5", "size": 13639, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/analysis.cpp", "max_stars_repo_name": "aleksandrina-streltsova/lidar-global-registration", "max_stars_repo_head_hexsha": "00cc919f17fe5b6854b575ca0aea3712ce034df6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/analysis.cpp", "max_issues_repo_name": "aleksandrina-streltsova/lidar-global-registration", "max_issues_repo_head_hexsha": "00cc919f17fe5b6854b575ca0aea3712ce034df6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/analysis.cpp", "max_forks_repo_name": "aleksandrina-streltsova/lidar-global-registration", "max_forks_repo_head_hexsha": "00cc919f17fe5b6854b575ca0aea3712ce034df6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.3576388889, "max_line_length": 119, "alphanum_fraction": 0.6448419972, "num_tokens": 3340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22955673216721226}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2009-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NGT platform is licensed under the Apache License, Version 2.0 (the\n//  \"License\"); you may not use this file except in compliance with the\n//  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#include <vw/Math/Vector.h>\n#include <vw/FileIO/DiskImageResourceGDAL.h>\n#include <vw/FileIO/FileUtils.h>\n#include <vw/Cartography/Datum.h>\n#include <vw/Cartography/GeoReference.h>\n#include <asp/Camera/RPCModel.h>\n#include <asp/Core/Common.h>\n\n#include <gdal.h>\n#include <gdal_priv.h>\n\n#include <boost/smart_ptr/scoped_ptr.hpp>\n#include <boost/smart_ptr/shared_ptr.hpp>\n\nusing namespace vw;\n\nnamespace asp {\n\n  void RPCModel::initialize(DiskImageResourceGDAL* resource) {\n    // Extract the datum (by means of georeference)\n    cartography::GeoReference georef;\n    cartography::read_georeference(georef, *resource);\n    m_datum = georef.datum();\n\n    // Extract RPC Info\n    boost::shared_ptr<GDALDataset> dataset = resource->get_dataset_ptr();\n    if (!dataset)\n      vw_throw(NotFoundErr() << \"RPCModel: Could not read data. No file has been opened.\");\n\n    GDALRPCInfo gdal_rpc;\n    if (!GDALExtractRPCInfo(dataset->GetMetadata(\"RPC\"),\n                            &gdal_rpc))\n      vw_throw(NotFoundErr() << \"RPCModel: GDAL resource appears not to have RPC metadata.\");\n\n    // Copy information over to our data structures.\n    m_lonlatheight_offset = Vector3(gdal_rpc.dfLONG_OFF,\n                                    gdal_rpc.dfLAT_OFF,\n                                    gdal_rpc.dfHEIGHT_OFF);\n    m_lonlatheight_scale = Vector3(gdal_rpc.dfLONG_SCALE,\n                                   gdal_rpc.dfLAT_SCALE,\n                                   gdal_rpc.dfHEIGHT_SCALE);\n    m_xy_offset = Vector2(gdal_rpc.dfSAMP_OFF,   gdal_rpc.dfLINE_OFF);\n    m_xy_scale  = Vector2(gdal_rpc.dfSAMP_SCALE, gdal_rpc.dfLINE_SCALE);\n\n    m_line_num_coeff   = CoeffVec(gdal_rpc.adfLINE_NUM_COEFF);\n    m_line_den_coeff   = CoeffVec(gdal_rpc.adfLINE_DEN_COEFF);\n    m_sample_num_coeff = CoeffVec(gdal_rpc.adfSAMP_NUM_COEFF);\n    m_sample_den_coeff = CoeffVec(gdal_rpc.adfSAMP_DEN_COEFF);\n  }\n\n  RPCModel::RPCModel(std::string const& filename) {\n    std::string ext = get_extension(filename);\n    if (ext == \".rpb\") {\n      load_rpb_file(filename);\n      return;\n    }\n\n    // Must have this check, otherwise GDAL prints an error.\n    if (has_image_extension(filename)) {\n      boost::scoped_ptr<DiskImageResourceGDAL> s_ptr(new DiskImageResourceGDAL(filename));\n      initialize(s_ptr.get());\n    }else{\n      // Throw an error. It will be caught, but it will get printed\n      // only if no other approaches turn out to work later on.\n      vw_throw(ArgumentErr() << \"Not an image \" << filename);\n    }\n    \n  }\n\n  RPCModel::RPCModel(DiskImageResourceGDAL* resource ) {\n    initialize(resource);\n  }\n\n  // The constructor just copies all of the input data\n  RPCModel::RPCModel(cartography::Datum const& datum,\n                     Vector<double,20> const& line_num_coeff,\n                     Vector<double,20> const& line_den_coeff,\n                     Vector<double,20> const& samp_num_coeff,\n                     Vector<double,20> const& samp_den_coeff,\n                     Vector2           const& xy_offset,\n                     Vector2           const& xy_scale,\n                     Vector3           const& lonlatheight_offset,\n                     Vector3           const& lonlatheight_scale) :\n    m_datum(datum), \n    m_line_num_coeff(line_num_coeff),\n    m_line_den_coeff(line_den_coeff), \n    m_sample_num_coeff(samp_num_coeff),\n    m_sample_den_coeff(samp_den_coeff), \n    m_xy_offset(xy_offset),\n    m_xy_scale(xy_scale), \n    m_lonlatheight_offset(lonlatheight_offset),\n    m_lonlatheight_scale(lonlatheight_scale) {}\n    \n\n  void RPCModel::load_rpb_file(std::string const& filename) {\n    //vw_out() << \"Reading RPC model from RPB file, defaulting to WGS84 datum.\\n\";\n    m_datum.set_well_known_datum(\"WGS84\");\n    std::ifstream f(filename.c_str());\n    \n    std::string line;\n    std::vector<std::string> tokens;\n    bool lineNumCoeffs = false,\n      lineDenCoeffs = false,\n      sampNumCoeffs = false,\n      sampDenCoeffs = false;\n    int coeff_index = 0, max_coeff_index = 0;\n\n    // Read through each line in the file    \n    while (std::getline(f, line)) {\n      \n      try {\n        // Break up the line\n        boost::split(tokens, line, boost::is_any_of(\"=,;\"));\n      \n        // Parse keywords\n        if (line.find(\"lineOffset\") != std::string::npos)\n          m_xy_offset[1] = atof(tokens[1].c_str());\n        if (line.find(\"sampOffset\") != std::string::npos)\n          m_xy_offset[0] = atof(tokens[1].c_str());\n        if (line.find(\"latOffset\") != std::string::npos)\n          m_lonlatheight_offset[1] = atof(tokens[1].c_str());\n        if (line.find(\"longOffset\") != std::string::npos)\n          m_lonlatheight_offset[0] = atof(tokens[1].c_str());\n        if (line.find(\"heightOffset\") != std::string::npos)\n          m_lonlatheight_offset[2] = atof(tokens[1].c_str());\n        if (line.find(\"lineScale\") != std::string::npos)\n          m_xy_scale[1] = atof(tokens[1].c_str());\n        if (line.find(\"sampScale\") != std::string::npos)\n          m_xy_scale[0] = atof(tokens[1].c_str());        \n        if (line.find(\"latScale\") != std::string::npos)\n          m_lonlatheight_scale[1] = atof(tokens[1].c_str());\n        if (line.find(\"longScale\") != std::string::npos)\n          m_lonlatheight_scale[0] = atof(tokens[1].c_str());\n        if (line.find(\"heightScale\") != std::string::npos)\n          m_lonlatheight_scale[2] = atof(tokens[1].c_str());\n\n        // Handle the RPC coefficients.\n        if (lineNumCoeffs) {\n          m_line_num_coeff[coeff_index] = atof(tokens[0].c_str());\n          ++coeff_index;\n        }\n        if (lineDenCoeffs) {\n          m_line_den_coeff[coeff_index] = atof(tokens[0].c_str());\n          ++coeff_index;\n        }\n        if (sampNumCoeffs) {\n          m_sample_num_coeff[coeff_index] = atof(tokens[0].c_str());\n          ++coeff_index;\n        }\n        if (sampDenCoeffs) {\n          m_sample_den_coeff[coeff_index] = atof(tokens[0].c_str());\n          ++coeff_index;\n        }\n\n        // Start of a coefficient sequence\n        if (line.find(\"lineNumCoef\") != std::string::npos)\n          lineNumCoeffs = true;\n        if (line.find(\"lineDenCoef\") != std::string::npos)\n          lineDenCoeffs = true;\n        if (line.find(\"sampNumCoef\") != std::string::npos)\n          sampNumCoeffs = true;\n        if (line.find(\"sampDenCoef\") != std::string::npos)\n          sampDenCoeffs = true;        \n      \n        // Done reading a coefficient sequence.\n        if (line.find(\")\") != std::string::npos) {\n          lineNumCoeffs = false;\n          lineDenCoeffs = false;\n          sampNumCoeffs = false;\n          sampDenCoeffs = false;\n          if (coeff_index > max_coeff_index)\n            max_coeff_index = coeff_index;\n          coeff_index = 0;\n        }\n      } catch(...) {\n        vw_throw(ArgumentErr() << \"Error reading file \" << filename\n                 << \", line = \"  << line);\n      }\n    } // End loop through lines.\n    f.close();\n    // Basic error check\n    if (max_coeff_index != 20)\n      vw_throw(ArgumentErr() << \"Error reading file \" << filename\n               << \", loaded wrong number of coefficients!\");\n  }\n\n  // All of these implementations are largely inspired by the GDAL\n  // code. We don't use the GDAL code unfortunately because they don't\n  // make that part of the API available. However I believe this is a\n  // safe reinterpretation that is safe to distribute.\n  Vector2 RPCModel::point_to_pixel(Vector3 const& point) const {\n    return geodetic_to_pixel(m_datum.cartesian_to_geodetic(point));\n  }\n\n  Vector2 RPCModel::geodetic_to_pixel(Vector3 const& geodetic) const {\n\n    // Should we verify that the  input geodetic is in the box?\n\n    Vector3 normalized_geodetic =\n      elem_quot(geodetic - m_lonlatheight_offset, m_lonlatheight_scale);\n\n    Vector2 normalized_pixel = normalized_geodetic_to_normalized_pixel(normalized_geodetic);\n\n    return elem_prod(normalized_pixel, m_xy_scale) + m_xy_offset;\n  }\n\n  Vector2 RPCModel::normalized_geodetic_to_normalized_pixel\n  (Vector3 const& normalized_geodetic,\n   RPCModel::CoeffVec const& line_num_coeff,\n   RPCModel::CoeffVec const& line_den_coeff,\n   RPCModel::CoeffVec const& sample_num_coeff,\n   RPCModel::CoeffVec const& sample_den_coeff){\n\n    CoeffVec term = calculate_terms(normalized_geodetic);\n    Vector2 normalized_pixel(dot_prod(term,sample_num_coeff) /\n                             dot_prod(term,sample_den_coeff),\n                             dot_prod(term,line_num_coeff) /\n                             dot_prod(term,line_den_coeff));\n\n    return normalized_pixel;\n  }\n\n  Vector2 RPCModel::normalized_geodetic_to_normalized_pixel\n  (Vector3 const& normalized_geodetic) const {\n\n    return normalized_geodetic_to_normalized_pixel(normalized_geodetic,\n                                                   m_line_num_coeff,\n                                                   m_line_den_coeff,\n                                                   m_sample_num_coeff,\n                                                   m_sample_den_coeff\n                                                   );\n  }\n\n  RPCModel::CoeffVec RPCModel::calculate_terms(vw::Vector3 const& normalized_geodetic) {\n\n    double x = normalized_geodetic.x(); // normalized lon\n    double y = normalized_geodetic.y(); // normalized lat\n    double z = normalized_geodetic.z(); // normalized height\n    CoeffVec result;\n    result[ 0] = 1.0;\n    result[ 1] = x;\n    result[ 2] = y;\n    result[ 3] = z;\n    result[ 4] = x*y;\n    result[ 5] = x*z;\n    result[ 6] = y*z;\n    result[ 7] = x*x;\n    result[ 8] = y*y;\n    result[ 9] = z*z;\n    result[10] = x*y*z;\n    result[11] = x*x*x;\n    result[12] = x*y*y;\n    result[13] = x*z*z;\n    result[14] = x*x*y;\n    result[15] = y*y*y;\n    result[16] = y*z*z;\n    result[17] = x*x*z;\n    result[18] = y*y*z;\n    result[19] = z*z*z;\n    return result;\n  }\n\n  vw::Vector<int,20> RPCModel::get_coeff_order() {\n    vw::Vector<int,20> result;\n    for (int i= 0; i< 3; ++i) result[i] = 1;\n    for (int i= 3; i<10; ++i) result[i] = 2;\n    for (int i=10; i<20; ++i) result[i] = 3;\n    return result;\n  }\n\n  vw::Matrix<double, 20, 2> RPCModel::terms_Jacobian2(vw::Vector3 const& normalized_geodetic) {\n    // Partial derivatives of the terms returned by the\n    // calculate_terms() function in respect to the first two\n    // variables only (unlike the terms_Jacobian3() function).\n\n    vw::Matrix<double, 20, 2> M;\n    double x = normalized_geodetic.x(); // normalized lon\n    double y = normalized_geodetic.y(); // normalized lat\n    double z = normalized_geodetic.z(); // normalized height\n\n    // df/dx            df/dy               // f\n    M[ 0][0] = 0.0;     M[ 0][1] = 0.0;     // 1\n    M[ 1][0] = 1.0;     M[ 1][1] = 0.0;     // x\n    M[ 2][0] = 0.0;     M[ 2][1] = 1.0;     // y\n    M[ 3][0] = 0.0;     M[ 3][1] = 0.0;     // z\n    M[ 4][0] = y;       M[ 4][1] = x;       // xy\n    M[ 5][0] = z;       M[ 5][1] = 0.0;     // xz\n    M[ 6][0] = 0.0;     M[ 6][1] = z;       // yz\n    M[ 7][0] = 2.0*x;   M[ 7][1] = 0.0;     // xx\n    M[ 8][0] = 0.0;     M[ 8][1] = 2.0*y;   // yy\n    M[ 9][0] = 0.0;     M[ 9][1] = 0.0;     // zz\n    M[10][0] = y*z;     M[10][1] = x*z;     // xyz\n    M[11][0] = 3.0*x*x; M[11][1] = 0.0;     // xxx\n    M[12][0] = y*y;     M[12][1] = 2.0*x*y; // xyy\n    M[13][0] = z*z;     M[13][1] = 0.0;     // xzz\n    M[14][0] = 2.0*x*y; M[14][1] = x*x;     // xxy\n    M[15][0] = 0.0;     M[15][1] = 3.0*y*y; // yyy\n    M[16][0] = 0.0;     M[16][1] = z*z;     // yzz\n    M[17][0] = 2.0*x*z; M[17][1] = 0.0;     // xxz\n    M[18][0] = 0.0;     M[18][1] = 2.0*y*z; // yyz\n    M[19][0] = 0.0;     M[19][1] = 0.0;     // zzz\n\n    return M;\n  }\n\n  vw::Matrix<double, 20, 3> RPCModel::terms_Jacobian3(vw::Vector3 const& normalized_geodetic) {\n    // Partial derivatives of the terms returned by the\n    // calculate_terms() function in respect to all three\n    // variables only (unlike the terms_Jacobian2() function).\n\n    vw::Matrix<double, 20, 3> M;\n    double x = normalized_geodetic.x(); // normalized lon\n    double y = normalized_geodetic.y(); // normalized lat\n    double z = normalized_geodetic.z(); // normalized height\n\n    // df/dx            df/dy               df/dz               // f\n    M[ 0][0] = 0.0;     M[ 0][1] = 0.0;     M[ 0][2] = 0.0;     // 1\n    M[ 1][0] = 1.0;     M[ 1][1] = 0.0;     M[ 1][2] = 0.0;     // x\n    M[ 2][0] = 0.0;     M[ 2][1] = 1.0;     M[ 2][2] = 0.0;     // y\n    M[ 3][0] = 0.0;     M[ 3][1] = 0.0;     M[ 3][2] = 1.0;     // z\n    M[ 4][0] = y;       M[ 4][1] = x;       M[ 4][2] = 0.0;     // xy\n    M[ 5][0] = z;       M[ 5][1] = 0.0;     M[ 5][2] = x;       // xz\n    M[ 6][0] = 0.0;     M[ 6][1] = z;       M[ 6][2] = y;       // yz\n    M[ 7][0] = 2.0*x;   M[ 7][1] = 0.0;     M[ 7][2] = 0.0;     // xx\n    M[ 8][0] = 0.0;     M[ 8][1] = 2.0*y;   M[ 8][2] = 0.0;     // yy\n    M[ 9][0] = 0.0;     M[ 9][1] = 0.0;     M[ 9][2] = 2.0*z;   // zz\n    M[10][0] = y*z;     M[10][1] = x*z;     M[10][2] = x*y;     // xyz\n    M[11][0] = 3.0*x*x; M[11][1] = 0.0;     M[11][2] = 0.0;     // xxx\n    M[12][0] = y*y;     M[12][1] = 2.0*x*y; M[12][2] = 0.0;     // xyy\n    M[13][0] = z*z;     M[13][1] = 0.0;     M[13][2] = 2.0*x*z; // xzz\n    M[14][0] = 2.0*x*y; M[14][1] = x*x;     M[14][2] = 0.0;     // xxy\n    M[15][0] = 0.0;     M[15][1] = 3.0*y*y; M[15][2] = 0.0;     // yyy\n    M[16][0] = 0.0;     M[16][1] = z*z;     M[16][2] = 2.0*y*z; // yzz\n    M[17][0] = 2.0*x*z; M[17][1] = 0.0;     M[17][2] = x*x;     // xxz\n    M[18][0] = 0.0;     M[18][1] = 2.0*y*z; M[18][2] = y*y;     // yyz\n    M[19][0] = 0.0;     M[19][1] = 0.0;     M[19][2] = 3.0*z*z; // zzz\n\n    return M;\n  }\n\n  RPCModel::CoeffVec\n  RPCModel::quotient_Jacobian(RPCModel::CoeffVec const& c,\n                              RPCModel::CoeffVec const& d,\n                              RPCModel::CoeffVec const& u) {\n\n    // Return the Jacobian of dot_prod(c, u) / dot_prod(d, u)\n    // as a vector with 20 elements.\n\n    double cu  = dot_prod(c, u);\n    double du  = dot_prod(d, u);\n    double den = du*du;\n\n    return elem_quot(du * c - cu * d, den);\n  }\n\n  vw::Matrix3x3 RPCModel::normalization_Jacobian(Vector3 const& q) {\n\n    // Return the Jacobian of the function\n    // f(x1, x2, x3) = ((x1 - c1)/q1, (x2 - c2)/q2, (x3 - c3)/q3)\n\n    vw::Matrix3x3 M;\n    M[0][0] = 1.0/q[0]; M[0][1] = 0.0;      M[0][2] = 0.0;\n    M[1][0] = 0.0;      M[1][1] = 1.0/q[1]; M[1][2] = 0.0;\n    M[2][0] = 0.0;      M[2][1] = 0.0;      M[2][2] = 1.0/q[2];\n    return M;\n  }\n\n  Matrix<double, 2, 3> RPCModel::geodetic_to_pixel_Jacobian(Vector3 const& geodetic) const {\n\n    Vector3 normalized_geodetic = elem_quot(geodetic - m_lonlatheight_offset, m_lonlatheight_scale);\n\n    CoeffVec term = calculate_terms(normalized_geodetic);\n\n    CoeffVec Qs = quotient_Jacobian(sample_num_coeff(), sample_den_coeff(), term);\n    CoeffVec Ql = quotient_Jacobian(line_num_coeff(),   line_den_coeff(),   term);\n    Matrix<double, 20, 3> MN = terms_Jacobian3(normalized_geodetic) *\n      normalization_Jacobian(m_lonlatheight_scale);\n\n    Matrix<double, 2, 3> J;\n    select_row(J, 0) = m_xy_scale[0] * transpose(Qs) * MN;\n    select_row(J, 1) = m_xy_scale[1] * transpose(Ql) * MN;\n\n    return J;\n  }\n\n  Matrix<double, 2, 2> RPCModel::normalized_geodetic_to_pixel_Jacobian(Vector3 const& normalized_geodetic) const {\n\n    // This function is different from geodetic_to_pixel_Jacobian() in several respects:\n\n    // 1. The input is the normalized geodetic, and the derivatives\n    //    are in respect to the normalized geodetic as well.\n\n    // 2. The derivatives are taken only in respect to the first two\n    //    variables (normalized lon and lat, no height).\n\n    // 3. The output is in normalized pixels (see m_xy_scale and m_xy_offset).\n\n    CoeffVec term = calculate_terms(normalized_geodetic);\n\n    CoeffVec Qs = quotient_Jacobian(sample_num_coeff(), sample_den_coeff(), term);\n    CoeffVec Ql = quotient_Jacobian(line_num_coeff(),   line_den_coeff(),   term);\n\n    Matrix<double, 20, 2> Jt = terms_Jacobian2(normalized_geodetic);\n\n    Matrix<double, 2, 2> J;\n    select_row(J, 0) = transpose(Qs) * Jt;\n    select_row(J, 1) = transpose(Ql) * Jt;\n\n    return J;\n  }\n\n  Matrix<double, 2, 3> RPCModel::geodetic_to_pixel_numerical_Jacobian(Vector3 const& geodetic, double tol) const {\n\n    // Find the Jacobian of geodetic_to_pixel using numerical\n    // differentiation. This is used for testing purposes.\n\n    Matrix<double, 2, 3> J;\n\n    Vector2 B  = geodetic_to_pixel(geodetic);\n\n    Vector2 B0 = (geodetic_to_pixel(geodetic + Vector3(tol, 0,   0 )) - B)/tol;\n    Vector2 B1 = (geodetic_to_pixel(geodetic + Vector3(0,   tol, 0 )) - B)/tol;\n    Vector2 B2 = (geodetic_to_pixel(geodetic + Vector3(0,   0,   tol)) - B)/tol;\n\n    select_col(J, 0) = B0;\n    select_col(J, 1) = B1;\n    select_col(J, 2) = B2;\n\n    return J;\n  }\n\n  Vector2 RPCModel::image_to_ground(Vector2 const& pixel, double height, Vector2 lonlat_guess) const {\n\n    // The absolute tolerance is experimental, needs more investigation\n    double abs_tolerance = 1e-6;\n\n    Vector2 normalized_pixel = elem_quot(pixel - m_xy_offset, m_xy_scale);\n\n    // Initial guess for the normalized lon and lat\n    if (lonlat_guess == Vector2(0.0, 0.0)){\n      lonlat_guess = subvector(m_lonlatheight_offset, 0, 2);\n    }\n    Vector2 normalized_lonlat = elem_quot(lonlat_guess - subvector(m_lonlatheight_offset, 0, 2),\n                                          subvector(m_lonlatheight_scale, 0, 2)\n                                          );\n    double len = norm_2(normalized_lonlat);\n    if (len != len || len > 1.5){\n      // If the input guess is NaN or unreasonable, use 0 as initial guess\n      normalized_lonlat = Vector2(0.0, 0.0);\n    }\n\n    // 10 iterations should be enough for Newton's method to converge\n    for (int iter = 0; iter < 10; iter++){\n\n      Vector3 normalized_geodetic;\n      normalized_geodetic[0] = normalized_lonlat[0];\n      normalized_geodetic[1] = normalized_lonlat[1];\n      normalized_geodetic[2] = (height - m_lonlatheight_offset[2])/m_lonlatheight_scale[2];\n\n      Vector2              p = normalized_geodetic_to_normalized_pixel(normalized_geodetic);\n      Matrix<double, 2, 2> J = normalized_geodetic_to_pixel_Jacobian(normalized_geodetic);\n\n      // The inverse matrix computed analytically\n      double det = J[0][0]*J[1][1] - J[0][1]*J[1][0];\n      Matrix<double, 2, 2> invJ;\n      invJ[0][0] =  J[1][1];\n      invJ[0][1] = -J[0][1];\n      invJ[1][0] = -J[1][0];\n      invJ[1][1] =  J[0][0];\n      invJ /= det;\n\n      // Newton's method for F(x) = y is\n      // x = x - J^{-1}(F(x) - y)\n      Vector2 error_try = p - normalized_pixel;\n      normalized_lonlat -= invJ*error_try;\n\n      // Absolute error convergence criterion\n      double  norm_try = norm_2(error_try);\n      if (norm_try < abs_tolerance) {\n        break;\n      }\n\n    }\n\n    Vector2 lonlat = elem_prod(normalized_lonlat, subvector(m_lonlatheight_scale, 0, 2))\n      + subvector(m_lonlatheight_offset, 0, 2);\n\n    return lonlat;\n\n  }\n\n  void RPCModel::point_and_dir(Vector2 const& pix, Vector3 & P, Vector3 & dir) const {\n\n    // For an RPC model there is no defined origin so it and the ray need to be computed.\n\n    // Center of valid region to bottom of valid region (normalized)\n    const double VERT_SCALE_FACTOR = 0.9; // - The virtual center should be above the terrain\n    double  height_up = m_lonlatheight_offset[2] + m_lonlatheight_scale[2]*VERT_SCALE_FACTOR;\n    double  height_dn = m_lonlatheight_offset[2] - m_lonlatheight_scale[2]*VERT_SCALE_FACTOR;\n\n    //vw_out() << \"m_lonlatheight_offset = \" << m_lonlatheight_offset << std::endl;\n    //vw_out() << \"m_lonlatheight_scale = \" << m_lonlatheight_scale << std::endl;\n\n    //vw_out() << \"Height up = \" << height_up << std::endl;\n    //vw_out() << \"Height dn = \" << height_dn << std::endl;\n\n    // Given the pixel and elevation, estimate lon-lat.\n    // Use m_lonlatheight_offset as initial guess for lonlat_up,\n    // and then use lonlat_up as initial guess for lonlat_dn.\n    Vector2 lonlat_up = image_to_ground(pix, height_up, subvector(m_lonlatheight_offset, 0, 2));\n    Vector2 lonlat_dn = image_to_ground(pix, height_dn, lonlat_up);\n\n    //vw_out() << \"lonlat_up = \" << lonlat_up << std::endl;\n    //vw_out() << \"lonlat_dn = \" << lonlat_dn << std::endl;\n\n    Vector3 geo_up = Vector3(lonlat_up[0], lonlat_up[1], height_up);\n    Vector3 geo_dn = Vector3(lonlat_dn[0], lonlat_dn[1], height_dn);\n\n    //vw_out() << \"geo_up = \" << geo_up << std::endl;\n    //vw_out() << \"geo_dn = \" << geo_dn << std::endl;\n\n    Vector3 P_up = m_datum.geodetic_to_cartesian(geo_up);\n    Vector3 P_dn = m_datum.geodetic_to_cartesian(geo_dn);\n\n    dir = normalize(P_dn - P_up);\n    \n    // Set the origin location very far in the opposite direction of the pointing vector,\n    //  to put it high above the terrain.\n    const double LONG_SCALE_UP = 10000; // This is a distance in meters approx from the top of the llh valid cube\n    P = P_up - dir*LONG_SCALE_UP;\n  }\n\n  Vector3 RPCModel::camera_center(Vector2 const& pix) const{\n    // Return an arbitrarily chosen point on the ray back-projected\n    // through the camera from the current pixel.\n    Vector3 P;\n    Vector3 dir;\n    point_and_dir(pix, P, dir);\n    return P;\n  }\n\n  Vector3 RPCModel::pixel_to_vector(Vector2 const& pix) const {\n    // Find the normalized direction of the ray back-projected through\n    // the camera from the current pixel.\n    Vector3 P;\n    Vector3 dir;\n    point_and_dir(pix, P, dir);\n    return dir;\n  }\n\n  std::ostream& operator<<(std::ostream& os, const RPCModel& rpc) {\n    os << \"RPC Model:\"         << std::endl\n       << \"Line Numerator: \"   << rpc.line_num_coeff()      << std::endl\n       << \"Line Denominator: \" << rpc.line_den_coeff()      << std::endl\n       << \"Samp Numerator: \"   << rpc.sample_num_coeff()    << std::endl\n       << \"Samp Denominator: \" << rpc.sample_den_coeff()    << std::endl\n       << \"XY Offset: \"        << rpc.xy_offset()           << std::endl\n       << \"XY Scale: \"         << rpc.xy_scale()            << std::endl\n       << \"Geodetic Offset: \"  << rpc.lonlatheight_offset() << std::endl\n       << \"Geodetic Scale: \"   << rpc.lonlatheight_scale();\n    return os;\n  }\n}\n", "meta": {"hexsha": "974e186244c6cd5187839ebf06a1e144c00267de", "size": 22953, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/Camera/RPCModel.cc", "max_stars_repo_name": "PicoJr/StereoPipeline", "max_stars_repo_head_hexsha": "146110a4d43ce6cb5e950297b8dca3f3b5e3f3b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 323.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T12:34:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T03:52:22.000Z", "max_issues_repo_path": "src/asp/Camera/RPCModel.cc", "max_issues_repo_name": "PicoJr/StereoPipeline", "max_issues_repo_head_hexsha": "146110a4d43ce6cb5e950297b8dca3f3b5e3f3b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 252.0, "max_issues_repo_issues_event_min_datetime": "2015-07-27T16:36:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T02:34:28.000Z", "max_forks_repo_path": "src/asp/Camera/RPCModel.cc", "max_forks_repo_name": "PicoJr/StereoPipeline", "max_forks_repo_head_hexsha": "146110a4d43ce6cb5e950297b8dca3f3b5e3f3b4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 105.0, "max_forks_repo_forks_event_min_datetime": "2015-02-28T02:37:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T09:17:30.000Z", "avg_line_length": 39.5060240964, "max_line_length": 114, "alphanum_fraction": 0.5913388228, "num_tokens": 7135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2295567321672122}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2014-2021.\n// Modifications copyright (c) 2014-2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_HPP\n#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_HPP\n\n#include <algorithm>\n#include <type_traits>\n\n#include <boost/config.hpp>\n#include <boost/concept_check.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/formulas/spherical.hpp>\n\n#include <boost/geometry/strategies/distance.hpp>\n#include <boost/geometry/strategies/concepts/distance_concept.hpp>\n#include <boost/geometry/strategies/spherical/distance_haversine.hpp>\n#include <boost/geometry/strategies/spherical/point_in_point.hpp>\n#include <boost/geometry/strategies/spherical/intersection.hpp>\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/promote_floating_point.hpp>\n#include <boost/geometry/util/select_calculation_type.hpp>\n\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK\n#  include <boost/geometry/io/dsv/write.hpp>\n#endif\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace distance\n{\n\n\nnamespace comparable\n{\n\n/*\n  Given a spherical segment AB and a point D, we are interested in\n  computing the distance of D from AB. This is usually known as the\n  cross track distance.\n\n  If the projection (along great circles) of the point D lies inside\n  the segment AB, then the distance (cross track error) XTD is given\n  by the formula (see http://williams.best.vwh.net/avform.htm#XTE):\n\n  XTD = asin( sin(dist_AD) * sin(crs_AD-crs_AB) )\n\n  where dist_AD is the great circle distance between the points A and\n  B, and crs_AD, crs_AB is the course (bearing) between the points A,\n  D and A, B, respectively.\n\n  If the point D does not project inside the arc AB, then the distance\n  of D from AB is the minimum of the two distances dist_AD and dist_BD.\n\n  Our reference implementation for this procedure is listed below\n  (this was the old Boost.Geometry implementation of the cross track distance),\n  where:\n  * The member variable m_strategy is the underlying haversine strategy.\n  * p stands for the point D.\n  * sp1 stands for the segment endpoint A.\n  * sp2 stands for the segment endpoint B.\n\n  ================= reference implementation -- start =================\n\n  return_type d1 = m_strategy.apply(sp1, p);\n  return_type d3 = m_strategy.apply(sp1, sp2);\n\n  if (geometry::math::equals(d3, 0.0))\n  {\n      // \"Degenerate\" segment, return either d1 or d2\n      return d1;\n  }\n\n  return_type d2 = m_strategy.apply(sp2, p);\n\n  return_type crs_AD = geometry::detail::course<return_type>(sp1, p);\n  return_type crs_AB = geometry::detail::course<return_type>(sp1, sp2);\n  return_type crs_BA = crs_AB - geometry::math::pi<return_type>();\n  return_type crs_BD = geometry::detail::course<return_type>(sp2, p);\n  return_type d_crs1 = crs_AD - crs_AB;\n  return_type d_crs2 = crs_BD - crs_BA;\n\n  // d1, d2, d3 are in principle not needed, only the sign matters\n  return_type projection1 = cos( d_crs1 ) * d1 / d3;\n  return_type projection2 = cos( d_crs2 ) * d2 / d3;\n\n  if (projection1 > 0.0 && projection2 > 0.0)\n  {\n      return_type XTD\n          = radius() * math::abs( asin( sin( d1 / radius() ) * sin( d_crs1 ) ));\n\n      // Return shortest distance, projected point on segment sp1-sp2\n      return return_type(XTD);\n  }\n  else\n  {\n      // Return shortest distance, project either on point sp1 or sp2\n      return return_type( (std::min)( d1 , d2 ) );\n  }\n\n  ================= reference implementation -- end =================\n\n\n  Motivation\n  ----------\n  In what follows we develop a comparable version of the cross track\n  distance strategy, that meets the following goals:\n  * It is more efficient than the original cross track strategy (less\n    operations and less calls to mathematical functions).\n  * Distances using the comparable cross track strategy can not only\n    be compared with other distances using the same strategy, but also with\n    distances computed with the comparable version of the haversine strategy.\n  * It can serve as the basis for the computation of the cross track distance,\n    as it is more efficient to compute its comparable version and\n    transform that to the actual cross track distance, rather than\n    follow/use the reference implementation listed above.\n\n  Major idea\n  ----------\n  The idea here is to use the comparable haversine strategy to compute\n  the distances d1, d2 and d3 in the above listing. Once we have done\n  that we need also to make sure that instead of returning XTD (as\n  computed above) that we return a distance CXTD that is compatible\n  with the comparable haversine distance. To achieve this CXTD must satisfy\n  the relation:\n      XTD = 2 * R * asin( sqrt(XTD) )\n  where R is the sphere's radius.\n\n  Below we perform the mathematical analysis that show how to compute CXTD.\n\n\n  Mathematical analysis\n  ---------------------\n  Below we use the following trigonometric identities:\n      sin(2 * x) = 2 * sin(x) * cos(x)\n      cos(asin(x)) = sqrt(1 - x^2)\n\n  Observation:\n  The distance d1 needed when the projection of the point D is within the\n  segment must be the true distance. However, comparable::haversine<>\n  returns a comparable distance instead of the one needed.\n  To remedy this, we implicitly compute what is needed. \n  More precisely, we need to compute sin(true_d1):\n\n  sin(true_d1) = sin(2 * asin(sqrt(d1)))\n               = 2 * sin(asin(sqrt(d1)) * cos(asin(sqrt(d1)))\n               = 2 * sqrt(d1) * sqrt(1-(sqrt(d1))^2)\n               = 2 * sqrt(d1 - d1 * d1)\n  This relation is used below.\n\n  As we mentioned above the goal is to find CXTD (named \"a\" below for\n  brevity) such that (\"b\" below stands for \"d1\", and \"c\" for \"d_crs1\"):\n\n      2 * R * asin(sqrt(a)) == R * asin(2 * sqrt(b-b^2) * sin(c))\n\n  Analysis:\n      2 * R * asin(sqrt(a)) == R * asin(2 * sqrt(b-b^2) * sin(c))\n  <=> 2 * asin(sqrt(a)) == asin(sqrt(b-b^2) * sin(c))\n  <=> sin(2 * asin(sqrt(a))) == 2 * sqrt(b-b^2) * sin(c)\n  <=> 2 * sin(asin(sqrt(a))) * cos(asin(sqrt(a))) == 2 * sqrt(b-b^2) * sin(c)\n  <=> 2 * sqrt(a) * sqrt(1-a) == 2 * sqrt(b-b^2) * sin(c)\n  <=> sqrt(a) * sqrt(1-a) == sqrt(b-b^2) * sin(c)\n  <=> sqrt(a-a^2) == sqrt(b-b^2) * sin(c)\n  <=> a-a^2 == (b-b^2) * (sin(c))^2\n\n  Consider the quadratic equation: x^2-x+p^2 == 0,\n  where p = sqrt(b-b^2) * sin(c); its discriminant is:\n      d = 1 - 4 * p^2 = 1 - 4 * (b-b^2) * (sin(c))^2\n\n  The two solutions are:\n      a_1 = (1 - sqrt(d)) / 2\n      a_2 = (1 + sqrt(d)) / 2\n\n  Which one to choose?\n  \"a\" refers to the distance (on the unit sphere) of D from the\n  supporting great circle Circ(A,B) of the segment AB.\n  The two different values for \"a\" correspond to the lengths of the two\n  arcs delimited D and the points of intersection of Circ(A,B) and the\n  great circle perperdicular to Circ(A,B) passing through D.\n  Clearly, the value we want is the smallest among these two distances,\n  hence the root we must choose is the smallest root among the two.\n\n  So the answer is:\n      CXTD = ( 1 - sqrt(1 - 4 * (b-b^2) * (sin(c))^2) ) / 2\n\n  Therefore, in order to implement the comparable version of the cross\n  track strategy we need to:\n  (1) Use the comparable version of the haversine strategy instead of\n      the non-comparable one.\n  (2) Instead of return XTD when D projects inside the segment AB, we\n      need to return CXTD, given by the following formula:\n          CXTD = ( 1 - sqrt(1 - 4 * (d1-d1^2) * (sin(d_crs1))^2) ) / 2;\n\n\n  Complexity Analysis\n  -------------------\n  In the analysis that follows we refer to the actual implementation below.\n  In particular, instead of computing CXTD as above, we use the more\n  efficient (operation-wise) computation of CXTD shown here:\n\n      return_type sin_d_crs1 = sin(d_crs1);\n      return_type d1_x_sin = d1 * sin_d_crs1;\n      return_type d = d1_x_sin * (sin_d_crs1 - d1_x_sin);\n      return d / (0.5 + math::sqrt(0.25 - d));\n\n  Notice that instead of computing:\n      0.5 - 0.5 * sqrt(1 - 4 * d) = 0.5 - sqrt(0.25 - d)\n  we use the following formula instead:\n      d / (0.5 + sqrt(0.25 - d)).\n  This is done for numerical robustness. The expression 0.5 - sqrt(0.25 - x)\n  has large numerical errors for values of x close to 0 (if using doubles\n  the error start to become large even when d is as large as 0.001).\n  To remedy that, we re-write 0.5 - sqrt(0.25 - x) as:\n      0.5 - sqrt(0.25 - d)\n      = (0.5 - sqrt(0.25 - d) * (0.5 - sqrt(0.25 - d)) / (0.5 + sqrt(0.25 - d)).\n  The numerator is the difference of two squares:\n      (0.5 - sqrt(0.25 - d) * (0.5 - sqrt(0.25 - d))\n      = 0.5^2 - (sqrt(0.25 - d))^ = 0.25 - (0.25 - d) = d,\n  which gives the expression we use.\n\n  For the complexity analysis, we distinguish between two cases:\n  (A) The distance is realized between the point D and an\n      endpoint of the segment AB\n\n      Gains:\n      Since we are using comparable::haversine<> which is called\n      3 times, we gain:\n      -> 3 calls to sqrt\n      -> 3 calls to asin\n      -> 6 multiplications\n\n      Loses: None\n\n      So the net gain is:\n      -> 6 function calls (sqrt/asin)\n      -> 6 arithmetic operations\n\n      If we use comparable::cross_track<> to compute\n      cross_track<> we need to account for a call to sqrt, a call\n      to asin and 2 multiplications. In this case the net gain is:\n      -> 4 function calls (sqrt/asin)\n      -> 4 arithmetic operations\n\n\n  (B) The distance is realized between the point D and an\n      interior point of the segment AB\n\n      Gains:\n      Since we are using comparable::haversine<> which is called\n      3 times, we gain:\n      -> 3 calls to sqrt\n      -> 3 calls to asin\n      -> 6 multiplications\n      Also we gain the operations used to compute XTD:\n      -> 2 calls to sin\n      -> 1 call to asin\n      -> 1 call to abs\n      -> 2 multiplications\n      -> 1 division\n      So the total gains are:\n      -> 9 calls to sqrt/sin/asin\n      -> 1 call to abs\n      -> 8 multiplications\n      -> 1 division\n\n      Loses:\n      To compute a distance compatible with comparable::haversine<>\n      we need to perform a few more operations, namely:\n      -> 1 call to sin\n      -> 1 call to sqrt\n      -> 2 multiplications\n      -> 1 division\n      -> 1 addition\n      -> 2 subtractions\n\n      So roughly speaking the net gain is:\n      -> 8 fewer function calls and 3 fewer arithmetic operations\n\n      If we were to implement cross_track directly from the\n      comparable version (much like what haversine<> does using\n      comparable::haversine<>) we need additionally\n      -> 2 function calls (asin/sqrt)\n      -> 2 multiplications\n\n      So it pays off to re-implement cross_track<> to use\n      comparable::cross_track<>; in this case the net gain would be:\n      -> 6 function calls\n      -> 1 arithmetic operation\n\n   Summary/Conclusion\n   ------------------\n   Following the mathematical and complexity analysis above, the\n   comparable cross track strategy (as implemented below) satisfies\n   all the goal mentioned in the beginning:\n   * It is more efficient than its non-comparable counter-part.\n   * Comparable distances using this new strategy can also be compared\n     with comparable distances computed with the comparable haversine\n     strategy.\n   * It turns out to be more efficient to compute the actual cross\n     track distance XTD by first computing CXTD, and then computing\n     XTD by means of the formula:\n                XTD = 2 * R * asin( sqrt(CXTD) )\n*/\n\ntemplate\n<\n    typename CalculationType = void,\n    typename Strategy = comparable::haversine<double, CalculationType>\n>\nclass cross_track\n{\npublic:\n    template <typename Point, typename PointOfSegment>\n    struct return_type\n        : promote_floating_point\n          <\n              typename select_calculation_type\n                  <\n                      Point,\n                      PointOfSegment,\n                      CalculationType\n                  >::type\n          >\n    {};\n\n    typedef typename Strategy::radius_type radius_type;\n\n    cross_track() = default;\n\n    explicit inline cross_track(typename Strategy::radius_type const& r)\n        : m_strategy(r)\n    {}\n\n    inline cross_track(Strategy const& s)\n        : m_strategy(s)\n    {}\n\n    // It might be useful in the future\n    // to overload constructor with strategy info.\n    // crosstrack(...) {}\n\n\n    template <typename Point, typename PointOfSegment>\n    inline typename return_type<Point, PointOfSegment>::type\n    apply(Point const& p, PointOfSegment const& sp1, PointOfSegment const& sp2) const\n    {\n\n#if !defined(BOOST_MSVC)\n        BOOST_CONCEPT_ASSERT\n            (\n                (concepts::PointDistanceStrategy<Strategy, Point, PointOfSegment>)\n            );\n#endif\n\n        typedef typename return_type<Point, PointOfSegment>::type return_type;\n\n        // http://williams.best.vwh.net/avform.htm#XTE\n        return_type d1 = m_strategy.apply(sp1, p);\n        return_type d3 = m_strategy.apply(sp1, sp2);\n\n        if (geometry::math::equals(d3, 0.0))\n        {\n            // \"Degenerate\" segment, return either d1 or d2\n            return d1;\n        }\n\n        return_type d2 = m_strategy.apply(sp2, p);\n\n        return_type lon1 = geometry::get_as_radian<0>(sp1);\n        return_type lat1 = geometry::get_as_radian<1>(sp1);\n        return_type lon2 = geometry::get_as_radian<0>(sp2);\n        return_type lat2 = geometry::get_as_radian<1>(sp2);\n        return_type lon = geometry::get_as_radian<0>(p);\n        return_type lat = geometry::get_as_radian<1>(p);\n\n        return_type crs_AD = geometry::formula::spherical_azimuth<return_type, false>\n                             (lon1, lat1, lon, lat).azimuth;\n\n        geometry::formula::result_spherical<return_type> result =\n                geometry::formula::spherical_azimuth<return_type, true>\n                    (lon1, lat1, lon2, lat2);\n        return_type crs_AB = result.azimuth;\n        return_type crs_BA = result.reverse_azimuth - geometry::math::pi<return_type>();\n\n        return_type crs_BD = geometry::formula::spherical_azimuth<return_type, false>\n                             (lon2, lat2, lon, lat).azimuth;\n\n        return_type d_crs1 = crs_AD - crs_AB;\n        return_type d_crs2 = crs_BD - crs_BA;\n\n        // d1, d2, d3 are in principle not needed, only the sign matters\n        return_type projection1 = cos( d_crs1 ) * d1 / d3;\n        return_type projection2 = cos( d_crs2 ) * d2 / d3;\n\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK\n        std::cout << \"Course \" << dsv(sp1) << \" to \" << dsv(p) << \" \"\n                  << crs_AD * geometry::math::r2d<return_type>() << std::endl;\n        std::cout << \"Course \" << dsv(sp1) << \" to \" << dsv(sp2) << \" \"\n                  << crs_AB * geometry::math::r2d<return_type>() << std::endl;\n        std::cout << \"Course \" << dsv(sp2) << \" to \" << dsv(sp1) << \" \"\n                  << crs_BA * geometry::math::r2d<return_type>() << std::endl;\n        std::cout << \"Course \" << dsv(sp2) << \" to \" << dsv(p) << \" \"\n                  << crs_BD * geometry::math::r2d<return_type>() << std::endl;\n        std::cout << \"Projection AD-AB \" << projection1 << \" : \"\n                  << d_crs1 * geometry::math::r2d<return_type>() << std::endl;\n        std::cout << \"Projection BD-BA \" << projection2 << \" : \"\n                  << d_crs2 * geometry::math::r2d<return_type>() << std::endl;\n        std::cout << \" d1: \" << (d1 )\n                  << \" d2: \" << (d2 )\n                  << std::endl;\n#endif\n\n        if (projection1 > 0.0 && projection2 > 0.0)\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK\n            return_type XTD = radius() * geometry::math::abs( asin( sin( d1 ) * sin( d_crs1 ) ));\n\n            std::cout << \"Projection ON the segment\" << std::endl;\n            std::cout << \"XTD: \" << XTD\n                      << \" d1: \" << (d1 * radius())\n                      << \" d2: \" << (d2 * radius())\n                      << std::endl;\n#endif\n            return_type const half(0.5);\n            return_type const quarter(0.25);\n\n            return_type sin_d_crs1 = sin(d_crs1);\n            /*\n              This is the straightforward obvious way to continue:\n              \n              return_type discriminant\n                  = 1.0 - 4.0 * (d1 - d1 * d1) * sin_d_crs1 * sin_d_crs1;\n              return 0.5 - 0.5 * math::sqrt(discriminant);\n            \n              Below we optimize the number of arithmetic operations\n              and account for numerical robustness:\n            */\n            return_type d1_x_sin = d1 * sin_d_crs1;\n            return_type d = d1_x_sin * (sin_d_crs1 - d1_x_sin);\n            return d / (half + math::sqrt(quarter - d));\n        }\n        else\n        {\n#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK\n            std::cout << \"Projection OUTSIDE the segment\" << std::endl;\n#endif\n\n            // Return shortest distance, project either on point sp1 or sp2\n            return return_type( (std::min)( d1 , d2 ) );\n        }\n    }\n\n    template <typename T1, typename T2>\n    inline radius_type vertical_or_meridian(T1 lat1, T2 lat2) const\n    {\n        return m_strategy.radius() * (lat1 - lat2);\n    }\n\n    inline typename Strategy::radius_type radius() const\n    { return m_strategy.radius(); }\n\nprivate :\n    Strategy m_strategy;\n};\n\n} // namespace comparable\n\n\n/*!\n\\brief Strategy functor for distance point to segment calculation\n\\ingroup strategies\n\\details Class which calculates the distance of a point to a segment, for points on a sphere or globe\n\\see http://williams.best.vwh.net/avform.htm\n\\tparam CalculationType \\tparam_calculation\n\\tparam Strategy underlying point-point distance strategy, defaults to haversine\n\n\\qbk{\n[heading See also]\n[link geometry.reference.algorithms.distance.distance_3_with_strategy distance (with strategy)]\n}\n\n*/\ntemplate\n<\n    typename CalculationType = void,\n    typename Strategy = haversine<double, CalculationType>\n>\nclass cross_track\n{\npublic :\n    typedef within::spherical_point_point equals_point_point_strategy_type;\n\n    typedef intersection::spherical_segments\n        <\n            CalculationType\n        > relate_segment_segment_strategy_type;\n\n    static inline relate_segment_segment_strategy_type get_relate_segment_segment_strategy()\n    {\n        return relate_segment_segment_strategy_type();\n    }\n\n    typedef within::spherical_winding\n        <\n            void, void, CalculationType\n        > point_in_geometry_strategy_type;\n\n    static inline point_in_geometry_strategy_type get_point_in_geometry_strategy()\n    {\n        return point_in_geometry_strategy_type();\n    }\n\n    template <typename Point, typename PointOfSegment>\n    struct return_type\n        : promote_floating_point\n          <\n              typename select_calculation_type\n                  <\n                      Point,\n                      PointOfSegment,\n                      CalculationType\n                  >::type\n          >\n    {};\n\n    typedef typename Strategy::radius_type radius_type;\n\n    inline cross_track()\n    {}\n\n    explicit inline cross_track(typename Strategy::radius_type const& r)\n        : m_strategy(r)\n    {}\n\n    inline cross_track(Strategy const& s)\n        : m_strategy(s)\n    {}\n\n    // It might be useful in the future\n    // to overload constructor with strategy info.\n    // crosstrack(...) {}\n\n\n    template <typename Point, typename PointOfSegment>\n    inline typename return_type<Point, PointOfSegment>::type\n    apply(Point const& p, PointOfSegment const& sp1, PointOfSegment const& sp2) const\n    {\n\n#if !defined(BOOST_MSVC)\n        BOOST_CONCEPT_ASSERT\n            (\n                (concepts::PointDistanceStrategy<Strategy, Point, PointOfSegment>)\n            );\n#endif\n        typedef typename return_type<Point, PointOfSegment>::type return_type;\n        typedef cross_track<CalculationType, Strategy> this_type;\n\n        typedef typename services::comparable_type\n            <\n                this_type\n            >::type comparable_type;\n\n        comparable_type cstrategy\n            = services::get_comparable<this_type>::apply(m_strategy);\n\n        return_type const a = cstrategy.apply(p, sp1, sp2);\n        return_type const c = return_type(2.0) * asin(math::sqrt(a));\n        return c * radius();\n    }\n\n    template <typename T1, typename T2>\n    inline radius_type vertical_or_meridian(T1 lat1, T2 lat2) const\n    {\n        return m_strategy.radius() * (lat1 - lat2);\n    }\n\n    inline typename Strategy::radius_type radius() const\n    { return m_strategy.radius(); }\n\nprivate :\n\n    Strategy m_strategy;\n};\n\n\n\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\nnamespace services\n{\n\ntemplate <typename CalculationType, typename Strategy>\nstruct tag<cross_track<CalculationType, Strategy> >\n{\n    typedef strategy_tag_distance_point_segment type;\n};\n\n\ntemplate <typename CalculationType, typename Strategy, typename P, typename PS>\nstruct return_type<cross_track<CalculationType, Strategy>, P, PS>\n    : cross_track<CalculationType, Strategy>::template return_type<P, PS>\n{};\n\n\ntemplate <typename CalculationType, typename Strategy>\nstruct comparable_type<cross_track<CalculationType, Strategy> >\n{\n    typedef comparable::cross_track\n        <\n            CalculationType, typename comparable_type<Strategy>::type\n        >  type;\n};\n\n\ntemplate\n<\n    typename CalculationType,\n    typename Strategy\n>\nstruct get_comparable<cross_track<CalculationType, Strategy> >\n{\n    typedef typename comparable_type\n        <\n            cross_track<CalculationType, Strategy>\n        >::type comparable_type;\npublic :\n    static inline comparable_type\n    apply(cross_track<CalculationType, Strategy> const& strategy)\n    {\n        return comparable_type(strategy.radius());\n    }\n};\n\n\ntemplate\n<\n    typename CalculationType,\n    typename Strategy,\n    typename P,\n    typename PS\n>\nstruct result_from_distance<cross_track<CalculationType, Strategy>, P, PS>\n{\nprivate :\n    typedef typename cross_track\n        <\n            CalculationType, Strategy\n        >::template return_type<P, PS>::type return_type;\npublic :\n    template <typename T>\n    static inline return_type\n    apply(cross_track<CalculationType, Strategy> const& , T const& distance)\n    {\n        return distance;\n    }\n};\n\n\n// Specializations for comparable::cross_track\ntemplate <typename RadiusType, typename CalculationType>\nstruct tag<comparable::cross_track<RadiusType, CalculationType> >\n{\n    typedef strategy_tag_distance_point_segment type;\n};\n\n\ntemplate\n<\n    typename RadiusType,\n    typename CalculationType,\n    typename P,\n    typename PS\n>\nstruct return_type<comparable::cross_track<RadiusType, CalculationType>, P, PS>\n    : comparable::cross_track\n        <\n            RadiusType, CalculationType\n        >::template return_type<P, PS>\n{};\n\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct comparable_type<comparable::cross_track<RadiusType, CalculationType> >\n{\n    typedef comparable::cross_track<RadiusType, CalculationType> type;\n};\n\n\ntemplate <typename RadiusType, typename CalculationType>\nstruct get_comparable<comparable::cross_track<RadiusType, CalculationType> >\n{\nprivate :\n    typedef comparable::cross_track<RadiusType, CalculationType> this_type;\npublic :\n    static inline this_type apply(this_type const& input)\n    {\n        return input;\n    }\n};\n\n\ntemplate\n<\n    typename RadiusType,\n    typename CalculationType,\n    typename P,\n    typename PS\n>\nstruct result_from_distance\n    <\n        comparable::cross_track<RadiusType, CalculationType>, P, PS\n    >\n{\nprivate :\n    typedef comparable::cross_track<RadiusType, CalculationType> strategy_type;\n    typedef typename return_type<strategy_type, P, PS>::type return_type;\npublic :\n    template <typename T>\n    static inline return_type apply(strategy_type const& strategy,\n                                    T const& distance)\n    {\n        return_type const s\n            = sin( (distance / strategy.radius()) / return_type(2.0) );\n        return s * s;\n    }\n};\n\n\n\n/*\n\nTODO:  spherical polar coordinate system requires \"get_as_radian_equatorial<>\"\n\ntemplate <typename Point, typename PointOfSegment, typename Strategy>\nstruct default_strategy\n    <\n        segment_tag, Point, PointOfSegment,\n        spherical_polar_tag, spherical_polar_tag,\n        Strategy\n    >\n{\n    typedef cross_track\n        <\n            void,\n            std::conditional_t\n                <\n                    std::is_void<Strategy>::value,\n                    typename default_strategy\n                        <\n                            point_tag, Point, PointOfSegment,\n                            spherical_polar_tag, spherical_polar_tag\n                        >::type,\n                    Strategy\n                >\n        > type;\n};\n*/\n\ntemplate <typename Point, typename PointOfSegment, typename Strategy>\nstruct default_strategy\n    <\n        point_tag, segment_tag, Point, PointOfSegment,\n        spherical_equatorial_tag, spherical_equatorial_tag,\n        Strategy\n    >\n{\n    typedef cross_track\n        <\n            void,\n            std::conditional_t\n                <\n                    std::is_void<Strategy>::value,\n                    typename default_strategy\n                        <\n                            point_tag, point_tag, Point, PointOfSegment,\n                            spherical_equatorial_tag, spherical_equatorial_tag\n                        >::type,\n                    Strategy\n                >\n        > type;\n};\n\n\ntemplate <typename PointOfSegment, typename Point, typename Strategy>\nstruct default_strategy\n    <\n        segment_tag, point_tag, PointOfSegment, Point,\n        spherical_equatorial_tag, spherical_equatorial_tag,\n        Strategy\n    >\n{\n    typedef typename default_strategy\n        <\n            point_tag, segment_tag, Point, PointOfSegment,\n            spherical_equatorial_tag, spherical_equatorial_tag,\n            Strategy\n        >::type type;\n};\n\n\n} // namespace services\n#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\n\n}} // namespace strategy::distance\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_HPP\n", "meta": {"hexsha": "f543a01c58a5645669e4f0c8b5959a09a4db9108", "size": 26743, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/strategies/spherical/distance_cross_track.hpp", "max_stars_repo_name": "angryDuck2/PopcornTorrent", "max_stars_repo_head_hexsha": "63bed793cbd59117fc296f887ed91b937a85ce77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "include/boost/geometry/strategies/spherical/distance_cross_track.hpp", "max_issues_repo_name": "angryDuck2/PopcornTorrent", "max_issues_repo_head_hexsha": "63bed793cbd59117fc296f887ed91b937a85ce77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "include/boost/geometry/strategies/spherical/distance_cross_track.hpp", "max_forks_repo_name": "angryDuck2/PopcornTorrent", "max_forks_repo_head_hexsha": "63bed793cbd59117fc296f887ed91b937a85ce77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 32.2983091787, "max_line_length": 101, "alphanum_fraction": 0.6448790338, "num_tokens": 6649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.22955673216721217}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <vector>\n#include <map>\n#include <Eigen/Geometry>\n#include <arc_utilities/arc_helpers.hpp>\n#include <arc_utilities/eigen_helpers.hpp>\n\n#ifndef IIWA_14_FK_FAST_HPP\n#define IIWA_14_FK_FAST_HPP\n\nnamespace IIWA_14_FK_FAST\n{\n    const size_t IIWA_14_NUM_ACTIVE_JOINTS = 7;\n    const size_t IIWA_14_NUM_LINKS = 8;\n\n    const std::string IIWA_14_ACTIVE_JOINT_1_NAME = \"iiwa_joint_1\";\n    const std::string IIWA_14_ACTIVE_JOINT_2_NAME = \"iiwa_joint_2\";\n    const std::string IIWA_14_ACTIVE_JOINT_3_NAME = \"iiwa_joint_3\";\n    const std::string IIWA_14_ACTIVE_JOINT_4_NAME = \"iiwa_joint_4\";\n    const std::string IIWA_14_ACTIVE_JOINT_5_NAME = \"iiwa_joint_5\";\n    const std::string IIWA_14_ACTIVE_JOINT_6_NAME = \"iiwa_joint_6\";\n    const std::string IIWA_14_ACTIVE_JOINT_7_NAME = \"iiwa_joint_7\";\n\n    const std::string IIWA_14_LINK_1_NAME = \"iiwa_link_0\";\n    const std::string IIWA_14_LINK_2_NAME = \"iiwa_link_1\";\n    const std::string IIWA_14_LINK_3_NAME = \"iiwa_link_2\";\n    const std::string IIWA_14_LINK_4_NAME = \"iiwa_link_3\";\n    const std::string IIWA_14_LINK_5_NAME = \"iiwa_link_4\";\n    const std::string IIWA_14_LINK_6_NAME = \"iiwa_link_5\";\n    const std::string IIWA_14_LINK_7_NAME = \"iiwa_link_6\";\n    const std::string IIWA_14_LINK_8_NAME = \"iiwa_link_7\";\n\n    inline Eigen::Isometry3d Get_link_0_joint_1_LinkJointTransform(const double joint_val)\n    {\n        const Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.1575);\n        const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(0.0, 0.0, 0.0);\n        const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n        const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n        return (pre_joint_transform * joint_transform);\n    }\n\n    inline Eigen::Isometry3d Get_link_1_joint_2_LinkJointTransform(const double joint_val)\n    {\n        const Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.2025);\n        const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(M_PI_2, 0.0, M_PI);\n        const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n        const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n        return (pre_joint_transform * joint_transform);\n    }\n\n    inline Eigen::Isometry3d Get_link_2_joint_3_LinkJointTransform(const double joint_val)\n    {\n        const Eigen::Translation3d pre_joint_translation(0.0, 0.2045, 0.0);\n        const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(M_PI_2, 0.0, M_PI);\n        const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n        const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n        return (pre_joint_transform * joint_transform);\n    }\n\n    inline Eigen::Isometry3d Get_link_3_joint_4_LinkJointTransform(const double joint_val)\n    {\n        const Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.2155);\n        const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(M_PI_2, 0.0, 0.0);\n        const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n        const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n        return (pre_joint_transform * joint_transform);\n    }\n\n    inline Eigen::Isometry3d Get_link_4_joint_5_LinkJointTransform(const double joint_val)\n    {\n        const Eigen::Translation3d pre_joint_translation(0.0, 0.1845, 0.0);\n        const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(-M_PI_2, M_PI, 0.0);\n        const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n        const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n        return (pre_joint_transform * joint_transform);\n    }\n\n    inline Eigen::Isometry3d Get_link_5_joint_6_LinkJointTransform(const double joint_val)\n    {\n        const Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.2155);\n        const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(M_PI_2, 0.0, 0.0);\n        const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n        const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n        return (pre_joint_transform * joint_transform);\n    }\n\n    inline Eigen::Isometry3d Get_link_6_joint_7_LinkJointTransform(const double joint_val)\n    {\n        const Eigen::Translation3d pre_joint_translation(0.0, 0.081, 0.0);\n        const Eigen::Quaterniond pre_joint_rotation = EigenHelpers::QuaternionFromUrdfRPY(-M_PI_2, M_PI, 0.0);\n        const Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;\n        const Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);\n        const Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));\n        const Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;\n        return (pre_joint_transform * joint_transform);\n    }\n\n    inline EigenHelpers::VectorIsometry3d GetLinkTransforms(const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform=Eigen::Isometry3d::Identity())\n    {\n        assert(configuration.size() == IIWA_14_NUM_ACTIVE_JOINTS);\n        EigenHelpers::VectorIsometry3d link_transforms(IIWA_14_NUM_LINKS);\n        link_transforms[0] = base_transform;\n        link_transforms[1] = link_transforms[0] * Get_link_0_joint_1_LinkJointTransform(configuration[0]);\n        link_transforms[2] = link_transforms[1] * Get_link_1_joint_2_LinkJointTransform(configuration[1]);\n        link_transforms[3] = link_transforms[2] * Get_link_2_joint_3_LinkJointTransform(configuration[2]);\n        link_transforms[4] = link_transforms[3] * Get_link_3_joint_4_LinkJointTransform(configuration[3]);\n        link_transforms[5] = link_transforms[4] * Get_link_4_joint_5_LinkJointTransform(configuration[4]);\n        link_transforms[6] = link_transforms[5] * Get_link_5_joint_6_LinkJointTransform(configuration[5]);\n        link_transforms[7] = link_transforms[6] * Get_link_6_joint_7_LinkJointTransform(configuration[6]);\n        return link_transforms;\n    }\n\n    inline EigenHelpers::VectorIsometry3d GetLinkTransforms(const std::map<std::string, double>& configuration, const Eigen::Isometry3d& base_transform=Eigen::Isometry3d::Identity())\n    {\n        std::vector<double> configuration_vector(IIWA_14_NUM_ACTIVE_JOINTS);\n        configuration_vector[0] = arc_helpers::RetrieveOrDefault(configuration, IIWA_14_ACTIVE_JOINT_1_NAME, 0.0);\n        configuration_vector[1] = arc_helpers::RetrieveOrDefault(configuration, IIWA_14_ACTIVE_JOINT_2_NAME, 0.0);\n        configuration_vector[2] = arc_helpers::RetrieveOrDefault(configuration, IIWA_14_ACTIVE_JOINT_3_NAME, 0.0);\n        configuration_vector[3] = arc_helpers::RetrieveOrDefault(configuration, IIWA_14_ACTIVE_JOINT_4_NAME, 0.0);\n        configuration_vector[4] = arc_helpers::RetrieveOrDefault(configuration, IIWA_14_ACTIVE_JOINT_5_NAME, 0.0);\n        configuration_vector[5] = arc_helpers::RetrieveOrDefault(configuration, IIWA_14_ACTIVE_JOINT_6_NAME, 0.0);\n        configuration_vector[6] = arc_helpers::RetrieveOrDefault(configuration, IIWA_14_ACTIVE_JOINT_7_NAME, 0.0);\n        return GetLinkTransforms(configuration_vector, base_transform);\n    }\n\n    inline EigenHelpers::MapStringIsometry3d GetLinkTransformsMap(const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform=Eigen::Isometry3d::Identity())\n    {\n        const EigenHelpers::VectorIsometry3d link_transforms = GetLinkTransforms(configuration, base_transform);\n        EigenHelpers::MapStringIsometry3d link_transforms_map;\n        link_transforms_map[IIWA_14_LINK_1_NAME] = link_transforms[0];\n        link_transforms_map[IIWA_14_LINK_2_NAME] = link_transforms[1];\n        link_transforms_map[IIWA_14_LINK_3_NAME] = link_transforms[2];\n        link_transforms_map[IIWA_14_LINK_4_NAME] = link_transforms[3];\n        link_transforms_map[IIWA_14_LINK_5_NAME] = link_transforms[4];\n        link_transforms_map[IIWA_14_LINK_6_NAME] = link_transforms[5];\n        link_transforms_map[IIWA_14_LINK_7_NAME] = link_transforms[6];\n        link_transforms_map[IIWA_14_LINK_8_NAME] = link_transforms[7];\n        return link_transforms_map;\n    }\n\n    inline EigenHelpers::MapStringIsometry3d GetLinkTransformsMap(const std::map<std::string, double>& configuration, const Eigen::Isometry3d& base_transform=Eigen::Isometry3d::Identity())\n    {\n        const EigenHelpers::VectorIsometry3d link_transforms = GetLinkTransforms(configuration, base_transform);\n        EigenHelpers::MapStringIsometry3d link_transforms_map;\n        link_transforms_map[IIWA_14_LINK_1_NAME] = link_transforms[0];\n        link_transforms_map[IIWA_14_LINK_2_NAME] = link_transforms[1];\n        link_transforms_map[IIWA_14_LINK_3_NAME] = link_transforms[2];\n        link_transforms_map[IIWA_14_LINK_4_NAME] = link_transforms[3];\n        link_transforms_map[IIWA_14_LINK_5_NAME] = link_transforms[4];\n        link_transforms_map[IIWA_14_LINK_6_NAME] = link_transforms[5];\n        link_transforms_map[IIWA_14_LINK_7_NAME] = link_transforms[6];\n        link_transforms_map[IIWA_14_LINK_8_NAME] = link_transforms[7];\n        return link_transforms_map;\n    }\n}\n\n#endif // IIWA_14_FK_FAST_HPP\n", "meta": {"hexsha": "33299801bfc54037886e85a402d8737d812221c8", "size": 10538, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/iiwa_14_fk_fast.hpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/iiwa_14_fk_fast.hpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/iiwa_14_fk_fast.hpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 61.2674418605, "max_line_length": 188, "alphanum_fraction": 0.755551338, "num_tokens": 2874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494678483918, "lm_q2_score": 0.33458944788835565, "lm_q1q2_score": 0.22951145372670478}}
{"text": "#include \"Common/Common.h\"\n#include \"GL/glew.h\"\n#include \"Demos/Visualization/MiniGL.h\"\n#include \"Demos/Visualization/Selection.h\"\n#include \"GL/glut.h\"\n#include \"Demos/Simulation/TimeManager.h\"\n#include <Eigen/Dense>\n#include \"FluidModel.h\"\n#include \"TimeStepFluidModel.h\"\n#include <iostream>\n#include \"Demos/Utils/Logger.h\"\n#include \"Demos/Utils/Timing.h\"\n#include \"Demos/Utils/FileSystem.h\"\n\n#define _USE_MATH_DEFINES\n#include \"math.h\"\n#include \"Demos/Simulation/Constraints.h\"\n#include \"Demos/Visualization/Visualization.h\"\n\n\n// Enable memory leak detection\n#if defined(_DEBUG) && !defined(EIGEN_ALIGN)\n\t#define new DEBUG_NEW \n#endif\n\nINIT_TIMING\nINIT_LOGGING\n\nusing namespace PBD;\nusing namespace Eigen;\nusing namespace std;\n\nvoid timeStep ();\nvoid buildModel ();\nvoid renderWorld();\nvoid createBreakingDam();\nvoid addWall(const Vector3r &minX, const Vector3r &maxX, std::vector<Vector3r> &boundaryParticles, std::vector<bool> &boundaryActives,bool active);\nvoid initBoundaryData(std::vector<Vector3r> &boundaryParticles, std::vector<bool> &boundaryActives);\nvoid render ();\nvoid cleanup();\nvoid reset();\nvoid selection(const Eigen::Vector2i &start, const Eigen::Vector2i &end);\nvoid createSphereBuffers(Real radius, int resolution);\nvoid renderSphere(const Vector3r &x, const float color[]);\nvoid releaseSphereBuffers();\nvoid TW_CALL setTimeStep(const void *value, void *clientData);\nvoid TW_CALL getTimeStep(void *value, void *clientData);\nvoid TW_CALL setVelocityUpdateMethod(const void *value, void *clientData);\nvoid TW_CALL getVelocityUpdateMethod(void *value, void *clientData);\nvoid TW_CALL setTempUpdateMethod(const void *value, void *clientData);\nvoid TW_CALL getTempUpdateMethod(void *value, void *clientData);\nvoid TW_CALL setViscosity(const void *value, void *clientData);\nvoid TW_CALL getViscosity(void *value, void *clientData);\nvoid TW_CALL setStiffness(const void *value, void *clientData);\nvoid TW_CALL getStiffness(void *value, void *clientData);\nvoid TW_CALL setDilation(const void *value, void *clientData);\nvoid TW_CALL getDilation(void *value, void *clientData);\nvoid TW_CALL setMelting(const void *value, void *clientData);\nvoid TW_CALL getMelting(void *value, void *clientData);\nvoid TW_CALL setEvaporation(const void *value, void *clientData);\nvoid TW_CALL getEvaporation(void *value, void *clientData);\nvoid TW_CALL setDifusion(const void *value, void *clientData);\nvoid TW_CALL getDifusion(void *value, void *clientData);\nvoid TW_CALL getTempContact(void *value, void *clientData);\nvoid TW_CALL setTempContact(const void *value, void *clientData);\nvoid TW_CALL getContact(void *value, void *clientData);\nvoid TW_CALL setContact(const void *value, void *clientData);\nvoid TW_CALL getXPBD(void *value, void *clientData);\nvoid TW_CALL setXPBD(const void *value, void *clientData);\n\n\nvoid TW_CALL getRadioSol(void *value, void *clientData);\nvoid TW_CALL setRadioSol(const void *value, void *clientData);\nvoid TW_CALL getNumConstraint(void *value, void *clientData);\nvoid TW_CALL setNumConstraint(const void *value, void *clientData);\n\nvoid TW_CALL getDesWidth(void *value, void *clientData);\nvoid TW_CALL setDesWidth(const void *value, void *clientData);\n\nvoid TW_CALL getDesHeight(void *value, void *clientData);\nvoid TW_CALL setDesHeight(const void *value, void *clientData);\n//Core\nFluidModel model;\nTimeStepFluidModel simulation;\n\nReal compact = 0.98;// 0.928;\n\n//const Real particleRadius = 0.025;\nconst Real particleRadius = 0.025;//0.015625//;\nint width = 30;\nint depth = 30;\nint height = 80;\nbool doPause = true;\nbool thermal = true;\nbool record = false;\nbool capture = false;\nbool rendering = true;\nbool renderingWall = false;\nbool renderingAir = false;\n\n\nstd::vector<unsigned int> selectedParticles;\nVector3r oldMousePos;\n// initiate buffers\nGLuint elementbuffer;\nGLuint normalbuffer;\nGLuint vertexbuffer;\nint vertexBufferSize = 0;\nGLint context_major_version, context_minor_version;\nstring exePath;\nstring dataPath;\n\nGLuint textureFloor;\nofstream file;\n\n\n// main \nint main( int argc, char **argv )\n{\n\tREPORT_MEMORY_LEAKS\n\n\tstd::string logPath = FileSystem::normalizePath(FileSystem::getProgramPath() + \"/log\");\n\tFileSystem::makeDirs(logPath);\n\tlogger.addSink(unique_ptr<ConsoleSink>(new ConsoleSink(LogLevel::INFO)));\n\tlogger.addSink(unique_ptr<FileSink>(new FileSink(LogLevel::DEBUG, logPath + \"/PBD.log\")));\n\n\texePath = FileSystem::getProgramPath();\n\tdataPath = exePath + \"/\" + std::string(PBD_DATA_PATH);\n\n\t// OpenGL\n\tMiniGL::init (argc, argv, 1280+620, 780, 0, 0, \"Fluid demo\");\n\n\tMiniGL::setClientIdleFunc (60, timeStep);\n\t\n\tMiniGL::initLights ();\n\tMiniGL::loadTexture(textureFloor);\n\n\tMiniGL::setKeyFunc(0, 'r', reset);\n\t//MiniGL::setKeyFunc(1, '1', demo1);\n\t//MiniGL::setKeyFunc(2, '2', demo2);\n\tMiniGL::setSelectionFunc(selection);\n\n\t//MiniGL::desWidth = 350;\n\t//MiniGL::desHeight = 100;\n\t\n\tMiniGL::getOpenGLVersion(context_major_version, context_minor_version);\n\tMiniGL::setClientSceneFunc(render);\t\t\t\n\t\n\t//MiniGL::setViewport (40.0, 0.1f, 500.0, Vector3r (0.0, 3.0, 8.0), Vector3r (0.0, 0.0, 0.0));\n\tMiniGL::setViewport(40.0, 0.1f, 800.0, Vector3r(0.0, 2.1, 7.0), Vector3r(0.0, 0.0, 0.0));\n\n\tTwAddVarRW(MiniGL::getTweakBar(), \"Pause\", TW_TYPE_BOOLCPP, &doPause, \" label='Pause' group=Simulation key=SPACE \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"TimeStepSize\", TW_TYPE_REAL, setTimeStep, getTimeStep, &model, \" label='Time step size'  min=0.0 max = 0.1 step=0.0001 precision=4 group=Simulation \");\n\tTwType enumType = TwDefineEnum(\"VelocityUpdateMethodType\", NULL, 0);\n\tTwAddVarCB(MiniGL::getTweakBar(), \"VelocityUpdateMethod\", enumType, setVelocityUpdateMethod, getVelocityUpdateMethod, &simulation, \" label='Velocity update method' enum='0 {First Order Update}, 1 {Second Order Update}' group=Simulation\");\n\n\tTwAddVarCB(MiniGL::getTweakBar(), \"XPBD\", TW_TYPE_BOOL32, setXPBD, getXPBD, &model, \" label='XPBD'  group=Simulation \");\n\t//TwAddVarRW(MiniGL::getTweakBar(), \"XPDB\", TW_TYPE_BOOLCPP, &XPBD, \" label='XPBD' group=Simulation key=x \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Viscosity\", TW_TYPE_REAL, setViscosity, getViscosity, &model, \" label='Viscosity'  min=0.0 max = 5 step=0.001 precision=4 group=Simulation \");\n\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Radio Solidification\", TW_TYPE_REAL, setRadioSol, getRadioSol, &model, \" label='Radio Solidification'  min=0.045 max = 0.1 step=0.01 precision=4 group=Simulation \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Num Constraints\", TW_TYPE_REAL, setNumConstraint, getNumConstraint, &model, \" label='Num Constraints'  min=1 max = 10 step=1 precision=4 group=Simulation \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Stiffness\", TW_TYPE_REAL, setStiffness, getStiffness, &model, \" label='Stiffness'  min=0.01 max = 1 step=0.01 precision=4 group=Simulation \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Coef Dilation\", TW_TYPE_REAL, setDilation, getDilation, &model, \" label='Coef Dilation'  min=0 max = 0.01 step=0.001 precision=4 group=Simulation \");\n\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Temp Melting\", TW_TYPE_REAL, setMelting, getMelting, &model, \" label='Temp Melting'  min=0.0 max = 300 step=1.0 precision=4 group=Simulation \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Temp Evaporation\", TW_TYPE_REAL, setEvaporation, getEvaporation, &model, \" label='Temp Evaporation'  min=1 max = 500.0 step=1.0 precision=4 group=Simulation \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Coef Difusion\", TW_TYPE_REAL, setDifusion, getDifusion, &model, \" label='Coef Difusion'  min=1 max = 1000 step=5 precision=4 group=Simulation \");\n\n\tTwType enumType2 = TwDefineEnum(\"TemperatureUpdateMethodType\", NULL, 0);\n\tTwAddVarCB(MiniGL::getTweakBar(), \"TemperatureUpdateMethod\", enumType2, setTempUpdateMethod, getTempUpdateMethod, &model, \" label='Heat Transfer method' enum='0 {Our Method}, 1 {Cleary Method}' group=Simulation\");\n\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Contact\", TW_TYPE_BOOL32, setContact, getContact, &model, \" label='Contact'  group=Simulation \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Temp Contact\", TW_TYPE_REAL, setTempContact, getTempContact, &model, \" label='Temp Contact'  min=-50 max = 500 step=10 precision=4 group=Simulation \");\n\n\tTwAddVarRW(MiniGL::getTweakBar(), \"Thermal\", TW_TYPE_BOOLCPP, &thermal, \" label='Thermal' group=Simulation key=t \");\n\n\tTwAddVarRW(MiniGL::getTweakBar(), \"start\", TW_TYPE_BOOLCPP, &record, \" label='start' group=Record key=g \");\n\tTwAddVarRW(MiniGL::getTweakBar(), \"capture\", TW_TYPE_BOOLCPP, &capture, \" label='capture' group=Record key=c \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Des Width\", TW_TYPE_INT32, setDesWidth, getDesWidth, &model, \" label='Des Width'  min=0.0 max = 900 step=1.0  group=Record \");\n\tTwAddVarCB(MiniGL::getTweakBar(), \"Des Height\", TW_TYPE_INT32, setDesHeight, getDesHeight, &model, \" label='Des Height'  min=0.0 max = 900 step=1.0 group=Record \");\n\tTwAddVarRW(MiniGL::getTweakBar(), \"rendering\", TW_TYPE_BOOLCPP, &rendering, \" label='rendering' group=Record key=n \");\n\tTwAddVarRW(MiniGL::getTweakBar(), \"renderingWall\", TW_TYPE_BOOLCPP, &renderingWall, \" label='renderingWall' group=Record key=m \");\n\tTwAddVarRW(MiniGL::getTweakBar(), \"renderingAir\", TW_TYPE_BOOLCPP, &renderingAir, \" label='renderingAir' group=Record key=i \");\n\n\t\n\tbuildModel();\n\n\tif (context_major_version >= 3)\n\t\tcreateSphereBuffers((Real)particleRadius, 4);\n\t\t//createSphereBuffers((Real)particleRadius, 25);\n\n\tglutMainLoop ();\t\n\n\tcleanup ();\n\tfile.close();\n\n\t//Timing::printAverageTimes();\n\t\n\treturn 0;\n}\n\nvoid cleanup()\n{\n\tdelete TimeManager::getCurrent();\n\tif (context_major_version >= 3)\n\t\treleaseSphereBuffers();\n}\n\nint test = 0;\nint index = 0;\nint frameIndex = 0;\n\nint numFrames = 0;\nint totalFrames = 0;\nint numFile = 0;\nint seconds = 10;\nint totalFrame = 64 * seconds;\n\nint timeEmision = 0;\nint numberFiles = 10;\nint firtTimeAugmented = 0;\nint tempAugmented = 0;\nbool addWallTop = true;\nbool temperatureFloor = true;\n\nint numParticlesAir = 0;\nvoid reset()\n{\n\tTiming::printAverageTimes();\n\tTiming::reset();\n\n\tmodel.reset();\n\tsimulation.reset();\n\tTimeManager::getCurrent()->setTime(0.0);\n\n\ttest++;\n\tindex = 0;\n\tnumFile = 0;\n\tnumFrames = 0;\n\tframeIndex=0;\n\tcapture = false;\n\trecord = false;\n\tdoPause = true;\n}\n\nvoid mouseMove(int x, int y)\n{\n\tVector3r mousePos;\n\tMiniGL::unproject(x, y, mousePos);\n\tconst Vector3r diff = mousePos - oldMousePos;\n\n\tTimeManager *tm = TimeManager::getCurrent();\n\tconst Real h = tm->getTimeStepSize();\n\n\tParticleData &pd = model.getParticles();\n\tfor (unsigned int j = 0; j < selectedParticles.size(); j++)\n\t{\n\t\tpd.getVelocity(selectedParticles[j]) += 5.0*diff/h;\n\t}\n\toldMousePos = mousePos;\n}\n\nvoid selection(const Eigen::Vector2i &start, const Eigen::Vector2i &end)\n{\n\tstd::vector<unsigned int> hits;\n\tselectedParticles.clear();\n\tParticleData &pd = model.getParticles();\n\tSelection::selectRect(start, end, &pd.getPosition(0), &pd.getPosition(pd.size() - 1), selectedParticles);\n\tif (selectedParticles.size() > 0)\n\t\tMiniGL::setMouseMoveFunc(GLUT_MIDDLE_BUTTON, mouseMove);\n\telse\n\t\tMiniGL::setMouseMoveFunc(-1, NULL);\n\n\tMiniGL::unproject(end[0], end[1], oldMousePos);\n}\n\nstring nameFile = \"condensation\";\n\n//*\nvoid initData(int numParticles) {\n\n\tchar bufPath[255];\n\tsprintf(bufPath, \"/%s%d.txt\",nameFile ,numFile++);\n\tfile = ofstream(dataPath + bufPath, ios::out | ios::trunc | ios::binary);\n\tfile.seekp(0, ios::beg);\n\tfile.write(reinterpret_cast<char *>(&numParticles), sizeof(int));\n}\nvoid saveData(ParticleData* p) {\n\n\tif (numFrames == totalFrame) {\n\t\tfile.close();\n\n\t\tif (numFile >= numberFiles) {\n\t\t\treset();\n\t\t\treturn;\n\t\t\t//exit(0);\n\t\t}\n\t\tchar bufPath[255];\n\t\tsprintf(bufPath, \"/%s%d.txt\", nameFile, numFile++);\n\t\tfile = ofstream(dataPath + bufPath, ios::out | ios::trunc | ios::binary);\n\t\tfile.seekp(0, ios::beg);\n\t\tnumFrames = 0;\n\t}\n\n\tint numParticles = p->getNumberOfParticles();\n\n\tfile.seekp(0, ios::end);\n\tfloat x, y, z, t;\n\tfor (int i = numParticlesAir; i < numParticles; i++) {\n\t\tVector3r position = p->getPosition(i);\n\n\t\tt = p->getTemp(i);\n\t\tx = position[0];\n\t\ty = position[1];\n\t\tz = position[2];\n\n\t\tfile.write(reinterpret_cast<char *>(&t), sizeof(float));\n\t\tfile.write(reinterpret_cast<char *>(&x), sizeof(float));\n\t\tfile.write(reinterpret_cast<char *>(&y), sizeof(float));\n\t\tfile.write(reinterpret_cast<char *>(&z), sizeof(float));\n\t}\n\tnumFrames++;\n\ttotalFrames++;\n}\n//*/\nvoid timeStep()\n{\n\n\tif (capture) {\n\t\tMiniGL::saveFrame(\"D:\\\\heat-video\\\\frame\", test, TimeManager::getCurrent()->getTime(), 255, 4);\n\t\tcapture = false;\n\t}\n\tif (doPause) {\n\t\treturn;\n\t}\n\n\tif (timeEmision > 0 && totalFrames >= 64 * timeEmision)\n\t\tmodel.setContact(true);\n\tif (model.getContact() && firtTimeAugmented > 0 && totalFrames >= 64 * firtTimeAugmented) {\n\t\tmodel.setTempContact(model.getTempContact() + tempAugmented);\n\t\tfirtTimeAugmented = 0;\n\t}\n\n\t// Simulation code\n\tfor (unsigned int i = 0; i < 4; i++) //Iterations Per Frame\n\t{\n\t\tsimulation.step(model);\n\t\t// Draw simulation model\n\t\t/*ParticleData &pd = model.getParticles();\n\t\tconst unsigned int nParticles = pd.size();\n\t\tfor (unsigned int i = 0; i < nParticles; i++)\n\t\t{\n\t\t\tconst Real t = 6.0f;\n\t\t\tif (pd.getPosition(i)[1] > 3) {\n\t\t\t\tpd.setTemp(i,t);\n\t\t\t}\n\t\t}*/\n\n\t}\n\t/* Measure Temp\n\tParticleData &pd = model.getParticles();\n\tLOG_INFO << TimeManager::getCurrent()->getTime() << \"\\t\" << pd.getTemp(0) << \"\\t\" << pd.getTemp(pd.getNumberOfParticles() - 1) << \"\\t\" << pd.getTemp(0) + pd.getTemp(pd.getNumberOfParticles() - 1);\n\t//*/\n\tsaveData(&model.getParticles());\n\n\t\n\t\n\n\t/*\n\tif (TimeManager::getCurrent()->getTime()>5.0f) {\n\t\tTiming::printAverageTimes();\n\t\texit(0);\n\t}*/\n\t\n\tif ( record) {\n\t\tMiniGL::saveFrame(\"D:\\\\heat-video\\\\frame\", test, TimeManager::getCurrent()->getTime(), 255, 4);\n\t}\n\t\n}\n\nvoid buildModel ()\n{\n\t//TimeManager::getCurrent ()->setTimeStepSize (0.05025);\n\tTimeManager::getCurrent()->setTimeStepSize(0.00390625);\n\t//TimeManager::getCurrent()->setTimeStepSize(0.001953125);\n\n\tcreateBreakingDam();\n\t\t\n}\n\n\nvoid renderWorld()\n{\n\n\t/*glDepthMask(GL_TRUE);\n\tglEnable(GL_DEPTH_TEST);*/\n\n\tglEnable(GL_TEXTURE_2D);\n\tglBindTexture(GL_TEXTURE_2D, textureFloor);\n\n\t//float color[4] = { 1.0f, 1.0f, 1.0f, 0.9f };\n\tfloat color[4] = {0.9f, 0.9f, 0.9f, 1.0f};\n\t//MiniGL::hsvToRgb(1.0f, 1.0f, 1.0f, surfaceColor);\n\t//*\n\t\n\n\n\tfloat c = 40.0f;\n\n\t\n\tglBegin(GL_QUADS);\n\tfloat speccolor[4] = { 1.0, 1.0, 1.0, 1.0 };\n\tglMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);\n\tglMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);\n\tglMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, speccolor);\n\tglMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100.0);\n\n\tglTexCoord2d(-2.5, -2.5); glVertex3d(-c, 0.0, -c);\n\tglTexCoord2d(2.5, -2.5); glVertex3d(c, 0.0, -c);\n\tglTexCoord2d(2.5, 2.5); glVertex3d(c, 0.0, c);\n\tglTexCoord2d(-2.5, 2.5); glVertex3d(-c, 0.0, c);\n\tglEnd();\n\tglBindTexture(GL_TEXTURE_2D, 0);\n}\n\n\nvoid render ()\n{\n\tif (!rendering) {\n\t\tMiniGL::drawTime(TimeManager::getCurrent()->getTime());\n\t\treturn;\n\t}\n\t//renderWorld();\n\t\n\t// Draw simulation model\n\tconst ParticleData &pd = model.getParticles();\n\tconst unsigned int nParticles = pd.size();\n\n\tint particlesIni = 0;\n\n\tif (renderingAir) {\n\t\tparticlesIni = numParticlesAir;\n\t}\n\t\n\t//glPointSize(4.0);\n\t\n\tconst Real supportRadius = model.getSupportRadius();\n\tReal vmax = 0.4*2.0*supportRadius / TimeManager::getCurrent()->getTimeStepSize();\n\tReal vmin = 0.0;\n\n\tif (context_major_version > 3)\n\t{\n\t\tif (thermal) {\n\n\t\t\tfor (unsigned int i = particlesIni; i < nParticles; i++)\n\t\t\t{\n\t\t\t\tReal v = pd.getVelocity(i).norm();\n\t\t\t\tv = 0.5*((v - vmin) / (vmax - vmin));\n\t\t\t\tv = min(128.0*v*v, 0.2);\n\t\t\t\tfloat fluidColor[4] = { 1.0f, 1.0f, 1.0f, 1.0f  };\n\t\t\t\tReal t = min((pd.getTemp(i)) *0.0065, 0.651);\n\n\t\t\t\tt = max(t, -0.05);\n\t\t\t\t//Real t = min((pd.getTemp(i)) *0.0075, 0.61);\n\n\t\t\t\t/*Real t = min((pd.getTemp(i)) *0.0081, 0.648);\n\t\t\t\tMiniGL::hsvToRgb(0.648 - t, 1.0f, 0.8f + (float)v, fluidColor);*/\n\n\t\t\t\t//if (t < 0)\n\t\t\t\t\t//t = 0;\n\t\t\t\tMiniGL::hsvToRgb(0.65 - t, 1.0f, 0.8f + (float)v, fluidColor);\n\t\t\t\t\n\t\t\t\trenderSphere(pd.getPosition(i), fluidColor);\n\t\t\t}\n\n\t\t}\n\t\telse {\n\t\t\tconst vector<newDistanceConstraint> c = model.getConstraints();\n\t\t\tconst unsigned int nc = c.size();\n\n\t\t\tfor (unsigned int i = particlesIni; i < nParticles; i++)\n\t\t\t{\n\t\t\t\tReal v = pd.getVelocity(i).norm();\n\t\t\t\tv = 0.5*((v - vmin) / (vmax - vmin));\n\t\t\t\tv = min(128.0*v*v, 0.2);\n\t\t\t\tfloat fluidColor[4] = { 0.2f, 0.2f, 0.2f, 1.0 };\n\t\t\t\tMiniGL::hsvToRgb((pd.getState(i) == 0 ? 1 : 0.55), 1.0f, 0.8f + (float)v, fluidColor);\n\t\t\t\trenderSphere(pd.getPosition(i), fluidColor);\n\t\t\t}\n\n\t\t\tfloat color[4] = { 0.2f, 0.2f, 0.2f, 1.0 };\n\t\t\tMiniGL::hsvToRgb(0.25f, 1.0f, 1.0f, color);\n\n\t\t\tglLineWidth(3);\n\t\t\tglMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);\n\t\t\tglMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);\n\t\t\tglBegin(GL_LINES);\n\n\t\t\tfor (unsigned int i = 0; i < nc; i++)\n\t\t\t{\n\t\t\t\tVector3r x1 = pd.getPosition(c[i].m_bodies[0]);\n\t\t\t\tVector3r x2 = pd.getPosition(c[i].m_bodies[1]);\n\n\t\t\t\tglVertex3f(x1[0], x1[1], x1[2]);\n\t\t\t\tglVertex3f(x2[0], x2[1], x2[2]);\n\n\t\t\t}\n\t\t\tglEnd();\n\t\t}\n\t\tif (renderingWall) {\n\t\t\tfloat surfaceColor[4] = { 0.2f, 0.2f, 0.2f, 1.0 };\n\t\t\tfor (unsigned int i = 0; i < model.numBoundaryParticles(); i++)\n\t\t\t\trenderSphere(model.getBoundaryX(i), surfaceColor);\n\t\t}\n\t}\n\telse\n\t{\n\t\tglDisable(GL_LIGHTING);\n\t\tglBegin(GL_POINTS);\n\t\tfor (unsigned int i = particlesIni; i < nParticles; i++)\n\t\t{\n\t\t\tReal v = pd.getVelocity(i).norm();\n\t\t\tv = 0.5*((v - vmin) / (vmax - vmin));\n\t\t\tv = min(128.0*v*v, 0.5);\n\t\t\tfloat fluidColor[4] = { 0.2f, 0.2f, 0.2f, 1.0 };\n\t\t\tMiniGL::hsvToRgb(0.55f, 1.0f, 0.5f + (float)v, fluidColor);\n\n\t\t\tglColor3fv(fluidColor);\n\t\t\tglVertex3v(&pd.getPosition(i)[0]);\n\t\t}\n\t\tglEnd();\n\n\t\t// \tglBegin(GL_POINTS);\n\t\t// \tfor (unsigned int i = 0; i < model.numBoundaryParticles(); i++)\n\t\t// \t{\n\t\t// \t\tglColor3fv(surfaceColor);\n\t\t// \t\tglVertex3fv(&model.getBoundaryX(i)[0]);\n\t\t// \t}\n\t\t// \tglEnd();*/\n\n\t\t//glEnable(GL_LIGHTING);\n\t}\n\n\n\n\tfloat red[4] = { 1.0f, 1.0f, 1.0f, 1 };\n\tfor (unsigned int j = 0; j < selectedParticles.size(); j++)\n\t{\n\t\tMiniGL::drawSphere(pd.getPosition(selectedParticles[j]), 0.05f, red);\n\t}\t\n\n\t/*\n\tTetModel *tetModel = model.getTetModel();\n\tconst IndexedFaceMesh &surfaceMesh = tetModel->getSurfaceMesh();\n\tVisualization::drawMesh(pd, surfaceMesh, tetModel->getIndexOffset(), surfaceColor);\n\t//*/\n\tMiniGL::drawTime(TimeManager::getCurrent()->getTime());\n\n\tauto str = \"s = \"+ std::to_string(TimeManager::getCurrent()->getTime());\n\t\n\t//MiniGL::drawBitmapText(-0.33,0.25, str.c_str(), str.size()-4, red);\n\t//frameIndex++;\n\n\trenderWorld();\n}\n\n/** Create a breaking dam scenario\n*/\nvoid createBreakingDam()\n{\n\tconst Real diam = 2.0*particleRadius*compact;\n\tconst Real startX = particleRadius;\n\tconst Real startY = particleRadius;\n\tconst Real startZ = particleRadius;\n\n\tmodel.setParticleRadius(particleRadius);\n\n\t/* Test for simulation complete (check in)\n\twidth = 80;\n\theight = 70;\n\tdepth = 60;\n\tfloat temperatureContact = 50;\n\tfloat temperatureSolid = -5;\n\n\ttimeEmision = 2;//2s\n\tnumberFiles = 7;\n\n\tfirtTimeAugmented = 25;//20s\n\ttempAugmented = 80;\n\n\tmodel.addModel(dataPath + \"/bunny4k.txt\", diam, temperatureSolid, 0.55f, Vector3r(-1.5, startY, -1.2), false,0.09);\n\t//model.addModel(dataPath + \"/bunny-6001.txt\", diam, temperatureSolid, 0.55f, Vector3r(-0.6, startY, -0.5), false, 0.07);\n\tmodel.setDilation(0.0001);\n\tmodel.setDifusion(25);\n\tmodel.setTempContact(temperatureContact);\n\tnameFile = \"simulation\";\n\t//*/\n\n\n\t/* Test for simulation complete - inverse (check in)\n\twidth = 40;\n\theight = 100;\n\tdepth = 40;\n\tfloat temperatureGas = 105.0;\n\tfloat temperatureLiquid = 5.1;\n\tfloat temperatureContact = 0;\n\tfloat temperatureSolid = -50;\n\n\tnumberFiles = 3;\n\n\tmodel.addGas(diam, temperatureGas, Vector3r(width, 4, depth), Vector3r(0, 45*diam, 0));\t\n\n\t//model.addModel(dataPath + \"/bunny4k.txt\", diam, temperatureSolid, 0.55f, Vector3r(-1.5, 2*startY, -1.2), false);\n\t//model.addModel(dataPath + \"/bunny-14032.txt\", diam, temperatureSolid, 0.55f, Vector3r(-1.2, startY, -0.9), false, 0.09);\n\tmodel.addModel(dataPath + \"/bunny-6001.txt\", diam, temperatureSolid, 0.55f, Vector3r(-0.75, startY, -0.6), false, 0.07);\n\n\tmodel.setContact(true);\n\tmodel.setTempContact(temperatureContact);\n\tmodel.setDifusion(50);\n\tmodel.setDilation(0.0001);\n\tmodel.setNumMaxConstraints(4);\n\tmodel.setRadioSolidification(0.055);\n\n\ttemperatureFloor = false;\n\n\tnameFile = \"simulationI\";\n\n\t//*/\n\n\t/* Test for heat and cool wather -> compare Transfer Heat (check in)\n\twidth = 60;\n\theight = 20;//80;\n\tdepth = 30;\n\n\tnumberFiles = 4;\n\n\tfloat temperatureLiquid = 1, temperatureLiquid2 = 99;\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(width*0.5, 10, depth), Vector3r(-width*diam*0.25, 0, 0));\n\tmodel.addFluid(diam, temperatureLiquid2, Vector3r(width*0.5, 10, depth), Vector3r(width*diam*0.25, 0, 0));\n\n\tnameFile = \"heat\";\n\t//*/\n\n\n\n\t/* Test for liquid evaporation - convection  (check in)\n\theight = 70;\n\tdepth = 30;//30;\n\twidth = 30;\n\tfloat temperatureLiquid = 20;//80;\n\tfloat temperatureContact = 140;\n\n\ttimeEmision = 2;//2s\n\tnumberFiles = 8;\n\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(width, 20, depth), Vector3r(0,0.0045,0));\n\t//model.setContact(true);\n\tmodel.setTempContact(temperatureContact);\n\tmodel.setDifusion(40);\n\n\tnameFile = \"evaporation\";\n\t//*/\n\n\t/* Test for condensation (check in)\n\twidth = 120;\n\theight = 175;\n\tdepth = 40;\n\tfloat temperatureGas = 120.0;\n\t//float temperatureLiquid = 15.1;\n\tfloat temperatureContact = 20;\n\tfloat temperatureSolid = 0.0;\n\n\tnumberFiles = 2;\n\n\t/*float temperatureAir = 10;\n\t//float temperatureAir1 = 10;\n\tfloat temperatureAir2 = 7;\n\tfloat temperatureAir3 = 3;\n\tfloat temperatureAir4 = 0;\n\t//model.addAir(diam, temperatureAir, Vector3r(width, 3, depth), Vector3r(0, height*diam - 155 * 2 * startY, 0),14);\n\t//model.addAir(diam, temperatureAir2, Vector3r(width, 3, depth), Vector3r(0, height*diam - 115 * 2 * startY, 0),13);\n\t//model.addAir(diam, temperatureAir3, Vector3r(width, 4, depth), Vector3r(0, height*diam - 77 * 2 * startY, 0),11);\n\t//model.addAir(diam, temperatureAir4, Vector3r(width, 4, depth), Vector3r(0, height*diam - 35 * 2 * startY, 0),10);\n\n\tnumParticlesAir = model.getParticles().size();* /\n\n\tmodel.addGas(diam, temperatureGas, Vector3r(width, 17, depth), Vector3r(0, diam , 0));\n\n\tmodel.setContact(true);\n\tmodel.setTempContact(temperatureContact);\n\tmodel.setDifusion(20);\n\tmodel.setViscosity(0.001);\n\n\tnameFile = \"condensation\";\n\t//*/\n\n\t/* Test for melting bunny with heat liquid (check in)\n\n\t// change time step = 0.001953125, comment code add border top\n\twidth = 80;\n\theight = 100;\n\tdepth = 60;\n\tfloat temperatureLiquid = 99.0f;\n\tfloat temperatureSolid = -5;\n\n\tnumberFiles = 2;\n\n\tmodel.addModel(dataPath + \"/bunny4k.txt\", diam, temperatureSolid, 0.55f, Vector3r(-1.5, startY, -1.2), false, 0.09);\t\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(5, 300, 5), Vector3r(0.35, 3.0, 0.4));\n\t\n\tmodel.setDilation(0.0001);\n\tmodel.setDifusion(30);\n\n\tnameFile = \"melting\";\n\taddWallTop = false;\n\t//*/\n\n\n\t/* Test for solidify bunny (check) -\n\twidth = 80;\n\theight = 100;\n\tdepth = 60;\n\tfloat temperatureLiquid = 10.0f;\n\tfloat temperatureSolid = -40;\n\n\tnumberFiles = 1;\n\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(8, 200,4), Vector3r(-0.25, 3.2, 0.1));\n\t//model.addFluid(diam, temperatureLiquid, Vector3r(5, 130, 2), Vector3r(-0.0, 3.0, 0.4));\n\t//model.addModel(dataPath + \"/bunny-6001.txt\", diam, temperatureSolid,0.55f, Vector3r(-0.75, startY, -0.6),false,0.07);\n\tmodel.addModel(dataPath + \"/bunny4k.txt\", diam, temperatureSolid,0.55f, Vector3r(-1.5, startY, -1.2),false,0.09);\n\tmodel.setDilation(0.0001);\n\tmodel.setNumMaxConstraints(6);\n\tmodel.setRadioSolidification(0.1);\n\tmodel.setDifusion(20);\n\n\n\tnameFile = \"solidify\";\n\taddWallTop = false;\n\t//*/\n\n\n\t/* Test for ( dilatation) --\n\twidth = 60;\n\theight = 60;\n\tdepth = 50;\n\tfloat temperatureSolid = -50;\n\tfloat temperarureContact = -1;\n\t//model.addSolid(diam, temperatureSolid,Vector3r(20,20,20),Vector3r(0, 0,0));\n\tmodel.addModel(dataPath + \"/bunny4k.txt\", diam, temperatureSolid, 0.55f, Vector3r(-1.5, startY, -1.2), false, 0.09);\n\t//model.setContact(true);\n\tmodel.setDilation(0.01);\n\tmodel.setTempContact(temperarureContact);\n\tmodel.setDifusion(50);\n\t//*/\n\n\t/* Test for armadillo on liquid - caendo -- (check in)\n\twidth = 60;\n\theight = 80;\n\tdepth = 60;\n\tfloat temperatureLiquid = 50;\n\tfloat temperatureSolid = -40;\n\n\tnumberFiles = 15;\n\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(width, 40, depth), Vector3r(0, 0, 0));\n\tmodel.addModel(dataPath + \"/armadillo4k.txt\", diam, temperatureSolid, 0.55f, Vector3r(-1.25, 4.0, -depth*diam * 0.25), false,0.07);\n\tmodel.setContact(false);\n\tmodel.setDilation(0.0001);\n\tmodel.setTempContact(temperatureLiquid);\n\tmodel.setDifusion(20);\n\n\tnameFile = \"armadillo\";\n\taddWallTop = false;\n\t//*/\n\n\n\n\t/////////////////////////////////////////////////\n\n\n\t/* Test for solidification del liquido\n\twidth = 100;\n\theight = 50;\n\tdepth = 30;\n\tfloat temperatureLiquid = 10;\n\tfloat temperatureSolid = 0;\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(width*0.25, 20, depth), Vector3r(-width*diam*3/8 + particleRadius, startY, 0));\n\n\tmodel.setContact(true);\n\tmodel.setTempContact(-5);\n\t//model.addSolid(diam, 0, Vector3r(20, 20, 20), Vector3r(0.24, 2 * startY, 0));\n\n\tnameFile = \"simulationI\";\n\n\t//*/\n\t\n\n\t/* Test for multiples ice on liquid - caendo --\n\twidth = 80;\n\theight = 120;\n\tdepth = 50;\n\tfloat temperatureLiquid = 10;\n\tfloat temperatureSolid = 0;\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(width, 20, depth), Vector3r(startX, 2*startY, startZ));\n\tmodel.addSolid(diam, temperatureSolid, Vector3r(14, 14, 14), Vector3r(-1.5, 1.7, -0.5));\n\tmodel.addSolid(diam, temperatureSolid, Vector3r(17, 17, 17), Vector3r(1.3, 1.5, 0.5));\n\tmodel.addSolid(diam, temperatureSolid, Vector3r(10, 10, 10), Vector3r(-0.5, 2.7, -0.5));\n\tmodel.addSolid(diam, temperatureSolid, Vector3r(5, 5, 5), Vector3r(0.0, 3, -0.0));\n\tmodel.addSolid(diam, temperatureSolid, Vector3r(5, 5, 5), Vector3r(1.0, 3.2, -0.2));\n\tmodel.addSolid(diam, temperatureSolid, Vector3r(10, 10, 10), Vector3r(-1.2, 2.5, 0.5));\n\t//model.addModel(dataPath + \"/armadillo4k.txt\", diam, temperatureSolid, 0.45f, Vector3r(-width*diam * 0.25, 2.0, -depth*diam * 0.25),false);\n\tmodel.setContact(true);\n\tmodel.setDilation(0.0001);\n\tmodel.setTempContact(temperatureLiquid);\n\tmodel.setDifusion(25);\n\t//*/\n\n\t/* Test for armadillo on liquid - caendo -- (check in)\n\twidth = 100;\n\theight = 250;\n\tdepth = 70;\n\tfloat temperatureLiquid = 50;\n\tfloat temperatureSolid = 0;\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(width, 15, depth), Vector3r(startX, 2 * startY, startZ));\n\tmodel.addModel(dataPath + \"/armadillo4k.txt\", diam, temperatureSolid, 0.55f, Vector3r(-width*diam * 0.25, 2.0, -depth*diam * 0.25), false);\n\tmodel.setContact(false);\n\tmodel.setDilation(0.0001);\n\tmodel.setTempContact(temperatureLiquid);\n\tmodel.setDifusion(20);\n\t//*/\n\n\t\n\n\n\t/* Test for meeltin ( derretimiento) --\n\twidth = 50;\n\theight = 50;\n\tdepth = 50;\n\tfloat temperatureSolid = 0;\n\tfloat temperarureContact = 10;\n\tmodel.addSolid(diam, temperatureSolid,Vector3r(30,40,20),Vector3r(particleRadius, 2 * startY,0));\n\tmodel.setContact(true);\n\tmodel.setDilation(0.0001);\n\tmodel.setTempContact(temperarureContact);\n\tmodel.setDifusion(10);\n\t//*/\n\n\t\n\n\t\n\n\t/* Test for heat and cool wather -> compare Transfer Heat cleary\n\twidth = 80;\n\theight = 80;\n\tdepth = 40;\n\tfloat temperatureLiquid = 6, temperatureLiquid2 = 80;\n\tmodel.heatTransferModel = 1;//model cleary\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(width*0.5, 15, depth), Vector3r(-width*diam*0.25 , 0, 0));\n\tmodel.addFluid(diam, temperatureLiquid2, Vector3r(width*0.5, 15, depth), Vector3r(width*diam*0.25 , 0, 0));\n\n\tmodel.setContact(false);\n\tmodel.setTempContact(temperatureLiquid2);\n\t//*/\n\n\t/* Test for liquidos caendo\n\tmodel.addFluid(diam, 21, Vector3r(3, 20, 3), Vector3r(-0.36, 2.0, 0.0));\n\tmodel.addFluid(diam, 55, Vector3r(3, 20, 3), Vector3r(0.16, 0.8, 0.18));\t\n\tmodel.addFluid(diam, 99, Vector3r(3, 20, 3), Vector3r(0.22, 2.8, -0.2));\n\tmodel.addSolid(diam, 0, Vector3r(25, 10, 15), Vector3r(0.025, 0, 0));\n\t//*/\n\n\t\n\t\n\n\t\n\n\t\n\n\t/* Test for simulation complete - inverse (check in)\n\twidth = 100;\n\theight = 290;\n\tdepth = 60;\n\tfloat temperatureGas = 109.0;\n\t//float temperatureLiquid = 15.1;\n\tfloat temperatureContact = 0;\n\tfloat temperatureSolid = 0.0;\n\n\tfloat temperatureAir = 10;\n\t//float temperatureAir1 = 10;\n\tfloat temperatureAir2 = 7;\n\tfloat temperatureAir3 = 3;\n\tfloat temperatureAir4 = 0;\n\tmodel.addAir(diam, temperatureAir, Vector3r(width, 3, depth), Vector3r(particleRadius, height*diam - 155 * 2 * startY, particleRadius), 14);\n\tmodel.addAir(diam, temperatureAir2, Vector3r(width, 3, depth), Vector3r(particleRadius, height*diam - 115 * 2 * startY, particleRadius), 13);\n\tmodel.addAir(diam, temperatureAir3, Vector3r(width, 4, depth), Vector3r(particleRadius, height*diam - 77 * 2 * startY, particleRadius), 11);\n\tmodel.addAir(diam, temperatureAir4, Vector3r(width, 4, depth), Vector3r(particleRadius, height*diam - 35 * 2 * startY, particleRadius), 10);\n\n\tnumParticlesAir = model.getParticles().size();\n\n\tmodel.addGas(diam, temperatureGas, Vector3r(width, 20, depth), Vector3r(particleRadius, height*diam - 265 * 2 * startY, particleRadius));\n\t//model.addModel(dataPath + \"/bunny.txt\", diam, temperatureSolid,0.55f, Vector3r(-0.5, 2*startY, -0.3),false);\n\t//model.addModel(dataPath + \"/bunny4k.txt\", diam, temperatureSolid, 0.55f, Vector3r(-1.5, 2 * startY, -1.2), false);\n\n\t//printf(\"%f\",);\n\t//model.addFluid(diam, temperatureLiquid, Vector3r(width, 10, depth), Vector3r(particleRadius, 2 * startY, particleRadius));\n\n\tmodel.setContact(true);\n\tmodel.setTempContact(temperatureContact);\n\tmodel.setDifusion(30);\n\t//*/\n\n\t/* Test for heat and cool wather -> measure temp (check in)\n\twidth = 50;\n\theight = 20;\n\tdepth = 1;\n\tfloat temperatureLiquid = 1, temperatureLiquid2 = 99;\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(width*0.5, 10, depth), Vector3r(-width*diam*0.25, 0, 0));\n\tmodel.addFluid(diam, temperatureLiquid2, Vector3r(width*0.5, 10, depth), Vector3r(width*diam*0.25, 0, 0));\n\tnameFile = \"measure temp\";\n\t//*/\n\n\t/* Test for melting bunny - number particles (check in)\n\twidth = 80;\n\theight = 250;\n\tdepth = 60;\n\tfloat temperatureSolid = -5;\n\t\n\ttimeEmision = 2;\n\tnumberFiles = 1;\n\t\n\n\t//model.addModel(dataPath + \"/bunny-46607.txt\", diam, temperatureSolid, 0.55f, Vector3r(-1.5, startY, -1.2), false,0.09);nameFile = \"46607Particles\";//0.09\n\t//model.addModel(dataPath + \"/bunny-27152.txt\", diam, temperatureSolid, 0.55f, Vector3r(-1.5, startY, -1.2), false, 0.09); nameFile = \"27152Particles\";//0.09\n\t//model.addModel(dataPath + \"/bunny-14032.txt\", diam, temperatureSolid, 0.55f, Vector3r(-1.2, startY, -0.9), false, 0.09);nameFile = \"14032Particles\";//0.09\n\tmodel.addModel(dataPath + \"/bunny-6001.txt\", diam, temperatureSolid, 0.55f, Vector3r(-0.8, startY, -0.7), false,0.08);nameFile = \"6001Particles\";//0.08\n\t//model.addModel(dataPath + \"/bunny-1849.txt\", diam, temperatureSolid, 0.55f, Vector3r(-0.6, startY, -0.5), false,0.07);nameFile = \"1849Particles\";//0.07\n\t\n\n\tmodel.setDilation(0.001);\n\tmodel.setDifusion(50);\n\tmodel.setTempContact(50);\t\n\t\n\t//*/\n\t/* Test for solidify bunny (check)\n\twidth = 80;\n\theight = 300;\n\tdepth = 60;\n\tfloat temperatureLiquid = 5.6f;\n\tfloat temperatureSolid = 0;\n\n\tmodel.addFluid(diam, temperatureLiquid, Vector3r(8, 200,4), Vector3r(-0.25, 3.2, 0.1));\n\t//model.addFluid(diam, temperatureLiquid, Vector3r(5, 130, 2), Vector3r(-0.0, 3.0, 0.4));\n\t//model.addModel(dataPath + \"/bunny.txt\", diam, temperatureSolid,0.55f, Vector3r(-0.3, 2*startY, 0.0),false);\n\tmodel.addModel(dataPath + \"/bunny4k.txt\", diam, temperatureSolid,0.55f, Vector3r(-1.5, 2*startY, -1.2),false);\n\tmodel.setDilation(0.0001);\n\tmodel.setNumMaxConstraints(6);\n\tmodel.setRadioSolidification(0.05);\n\tmodel.setDifusion(50);\n\t//*/\n\n\t//* Test for multiples demos - number particles (check in)\n\twidth = 80;\n\theight = 90;\n\tdepth = 60;\n\tfloat temperatureSolid = 50;\n\n\t//timeEmision = 1;\n\tnumberFiles = 1;\n\n\tfloat scale = 0.6f;\n\n\t//model.addModel(dataPath + \"/bunny-46607.txt\", diam, temperatureSolid, scale, Vector3r(-1.65, startY, -1.3), false,0.09);//0.09\n\t//model.addModel(dataPath + \"/bunny-27152.txt\", diam, temperatureSolid, scale, Vector3r(-1.5, startY, -1.2), false, 0.09);//0.09\n\t//model.addModel(dataPath + \"/bunny-14032.txt\", diam, temperatureSolid, scale, Vector3r(-1.2, startY, -0.9), false, 0.09);//0.09\n\t//model.addModel(dataPath + \"/bunny-6001.txt\", diam, temperatureSolid, scale, Vector3r(-0.8, startY, -0.7), false,0.08);//0.08\n\tmodel.addModel(dataPath + \"/bunny-1849.txt\", diam, temperatureSolid, scale, Vector3r(-0.6, startY, -0.5), false,0.07);//0.07\n\n\n\tmodel.setDilation(0.001);\n\tmodel.setDifusion(50);\n\tmodel.setTempContact(-10);\n\tmodel.setContact(true);\n\tmodel.setRadioSolidification(0.05);\n\tmodel.setNumMaxConstraints(3);\n\tnameFile = \"demos\";\n\n\t//*/\n\n\n\n\tstd::vector<Vector3r> boundaryParticles;\n\tstd::vector<bool> boundaryActives;\n\tinitBoundaryData(boundaryParticles, boundaryActives);\n\n\tmodel.initModel( (unsigned int)boundaryParticles.size(), boundaryParticles.data(), &boundaryActives);\n\t\n\t\n\tLOG_INFO << \"Number particles:\" << (model.getParticles().size() - numParticlesAir);\n\t//LOG_INFO << \"Number of particles Total: \" << model.getParticles().size();\n\tinitData(model.getParticles().size() - numParticlesAir);\n}\n\n\nvoid addWall(const Vector3r &minX, const Vector3r &maxX, std::vector<Vector3r> &boundaryParticles, std::vector<bool> &boundaryActives,bool active)\n{\n\tconst Real particleDistance = 2*model.getParticleRadius()*compact;\n\n\tconst Vector3r diff = maxX - minX;\n\tconst unsigned int stepsX = (unsigned int)(round(diff[0] / particleDistance)) + 1u;\n\tconst unsigned int stepsY = (unsigned int)(round(diff[1] / particleDistance)) + 1u;\n\tconst unsigned int stepsZ = (unsigned int)(round(diff[2] / particleDistance)) + 1u;\n\n\t//printf(\"%d %d %d %f\\n\",stepsX, (unsigned int)(41.00),(unsigned int)(diff[0] / particleDistance), diff[0] / particleDistance);\n\n\tconst unsigned int startIndex = (unsigned int) boundaryParticles.size();\n\tboundaryParticles.resize(startIndex + stepsX*stepsY*stepsZ);\n\tboundaryActives.resize(startIndex + stepsX*stepsY*stepsZ);\n\n\t#pragma omp parallel default(shared)\n\t{\n\t\t#pragma omp for schedule(static)  \n\t\tfor (int j = 0; j < (int)stepsX; j++)\n\t\t{\n\t\t\tfor (unsigned int k = 0; k < stepsY; k++)\n\t\t\t{\n\t\t\t\tfor (unsigned int l = 0; l < stepsZ; l++)\n\t\t\t\t{\n\t\t\t\t\tconst Vector3r currPos = minX + Vector3r(j*particleDistance, k*particleDistance, l*particleDistance);\n\t\t\t\t\tboundaryParticles[startIndex + j*stepsY*stepsZ + k*stepsZ + l] = currPos;\n\t\t\t\t\tboundaryActives[startIndex + j*stepsY*stepsZ + k*stepsZ + l] = active;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\nvoid initBoundaryData(std::vector<Vector3r> &boundaryParticles, std::vector<bool> &boundaryActives)\n{\n\n\tconst Real containerWidth = (width)*particleRadius*compact;\n\tconst Real containerDepth = (depth)*particleRadius*compact;\n\tconst Real containerHeight = (height)*particleRadius*compact;\n\n\n\tconst Real diameter = 2*particleRadius*compact;// compact;// *0.8;\n\n\tconst Real x1 = -containerWidth  - particleRadius * compact;\n\tconst Real x2 = containerWidth + particleRadius * compact;\n\tconst Real y1 = -(sqrt(3) - 0.80)*particleRadius;\n\tconst Real y2 = 2*containerHeight+ diameter - (sqrt(3) - 0.80)*particleRadius;\n\tconst Real z1 = -containerDepth - particleRadius * compact;\n\tconst Real z2 = containerDepth + particleRadius * compact;\n\n\tfloat rest = 0.001f;\n\n\t// Floor\n\taddWall(Vector3r(x1, y1, z1), Vector3r(x2, y1, z2), boundaryParticles, boundaryActives,temperatureFloor);\n\t// Top\n\tif(addWallTop)\n\t\taddWall(Vector3r(x1, y2, z1), Vector3r(x2, y2, z2), boundaryParticles, boundaryActives, true);\n\t// Left\n\taddWall(Vector3r(x1 - rest, y1+ diameter, z1+ diameter), Vector3r(x1 - rest, y2 - diameter, z2- diameter), boundaryParticles, boundaryActives, false);\n\t// Right\n\taddWall(Vector3r(x2 + rest, y1 + diameter, z1+ diameter), Vector3r(x2 + rest, y2 - diameter, z2- diameter), boundaryParticles, boundaryActives, false);\n\t// Back\n\taddWall(Vector3r(x1, y1 + diameter, z1), Vector3r(x2, y2 - diameter, z1), boundaryParticles, boundaryActives, false);\n\t// Front\n\taddWall(Vector3r(x1, y1 + diameter, z2), Vector3r(x2, y2- diameter, z2), boundaryParticles, boundaryActives, false);\n}\n\n\nvoid createSphereBuffers(Real radius, int resolution)\n{\n\tReal PI = static_cast<Real>(M_PI);\n\t// vectors to hold our data\n\t// vertice positions\n\tstd::vector<Vector3r> v;\n\t// normals\n\tstd::vector<Vector3r> n;\n\tstd::vector<unsigned short> indices;\n\n\t// initiate the variable we are going to use\n\tReal X1, Y1, X2, Y2, Z1, Z2;\n\tReal inc1, inc2, inc3, inc4, radius1, radius2;\n\n\tfor (int w = 0; w < resolution; w++)\n\t{\n\t\tfor (int h = (-resolution / 2); h < (resolution / 2); h++)\n\t\t{\n\t\t\tinc1 = (w / (Real)resolution) * 2 * PI;\n\t\t\tinc2 = ((w + 1) / (Real)resolution) * 2 * PI;\n\t\t\tinc3 = (h / (Real)resolution)*PI;\n\t\t\tinc4 = ((h + 1) / (Real)resolution)*PI;\n\n\t\t\tX1 = sin(inc1);\n\t\t\tY1 = cos(inc1);\n\t\t\tX2 = sin(inc2);\n\t\t\tY2 = cos(inc2);\n\n\t\t\t// store the upper and lower radius, remember everything is going to be drawn as triangles\n\t\t\tradius1 = radius*cos(inc3);\n\t\t\tradius2 = radius*cos(inc4);\n\n\t\t\tZ1 = radius*sin(inc3);\n\t\t\tZ2 = radius*sin(inc4);\n\n\t\t\t// insert the triangle coordinates\n\t\t\tv.push_back(Vector3r(radius1*X1, Z1, radius1*Y1));\n\t\t\tv.push_back(Vector3r(radius1*X2, Z1, radius1*Y2));\n\t\t\tv.push_back(Vector3r(radius2*X2, Z2, radius2*Y2));\n\n\t\t\tindices.push_back((unsigned short)v.size() - 3);\n\t\t\tindices.push_back((unsigned short)v.size() - 2);\n\t\t\tindices.push_back((unsigned short)v.size() - 1);\n\n\t\t\tv.push_back(Vector3r(radius1*X1, Z1, radius1*Y1));\n\t\t\tv.push_back(Vector3r(radius2*X2, Z2, radius2*Y2));\n\t\t\tv.push_back(Vector3r(radius2*X1, Z2, radius2*Y1));\n\n\t\t\tindices.push_back((unsigned short)v.size() - 3);\n\t\t\tindices.push_back((unsigned short)v.size() - 2);\n\t\t\tindices.push_back((unsigned short)v.size() - 1);\n\n\t\t\t// insert the normal data\n\t\t\tn.push_back(Vector3r(X1, Z1, Y1));\n\t\t\tn.push_back(Vector3r(X2, Z1, Y2));\n\t\t\tn.push_back(Vector3r(X2, Z2, Y2));\n\t\t\tn.push_back(Vector3r(X1, Z1, Y1));\n\t\t\tn.push_back(Vector3r(X2, Z2, Y2));\n\t\t\tn.push_back(Vector3r(X1, Z2, Y1));\n\t\t}\n\t}\n\n\tfor (unsigned int i = 0; i < n.size(); i++)\n\t\tn[i].normalize();\n\n\n\tglGenBuffersARB(1, &vertexbuffer);\n\tglBindBufferARB(GL_ARRAY_BUFFER_ARB, vertexbuffer);\n\tglBufferDataARB(GL_ARRAY_BUFFER_ARB, v.size() * sizeof(Vector3r), &v[0], GL_STATIC_DRAW);\n\n\tglGenBuffersARB(1, &normalbuffer);\n\tglBindBufferARB(GL_ARRAY_BUFFER_ARB, normalbuffer);\n\tglBufferDataARB(GL_ARRAY_BUFFER_ARB, n.size() * sizeof(Vector3r), &n[0], GL_STATIC_DRAW);\n\tglBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);\n\n\t// Generate a buffer for the indices as well\n\tglGenBuffersARB(1, &elementbuffer);\n\tglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, elementbuffer);\n\tglBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW);\n\tglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);\n\n\t// store the number of indices for later use\n\tvertexBufferSize = (unsigned int)indices.size();\n\n\t// clean up after us\n\tindices.clear();\n\tn.clear();\n\tv.clear();\n}\n\nvoid renderSphere(const Vector3r &x, const float color[])\n{\n\tglEnableClientState(GL_VERTEX_ARRAY);\n\tglEnableClientState(GL_NORMAL_ARRAY);\n\n\tglMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color);\n\tglMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, color);\n\n\n\tglBindBufferARB(GL_ARRAY_BUFFER_ARB, vertexbuffer);\n\tglVertexPointer(3, GL_REAL, 0, 0);\n\n\tglBindBufferARB(GL_ARRAY_BUFFER_ARB, normalbuffer);\n\tglNormalPointer(GL_REAL, 0, 0);\n\n\tglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, elementbuffer);\n\n\tglPushMatrix();\n\tglTranslated(x[0], x[1], x[2]);\n\tglDrawElements(GL_TRIANGLES, (GLsizei)vertexBufferSize, GL_UNSIGNED_SHORT, 0);\n\tglPopMatrix();\n\tglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);\n\tglBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);\n\n\tglDisableClientState(GL_NORMAL_ARRAY);\n\tglDisableClientState(GL_VERTEX_ARRAY);\n}\n\nvoid releaseSphereBuffers()\n{\n\tif (elementbuffer != 0)\n\t{\n\t\tglDeleteBuffersARB(1, &elementbuffer);\n\t\telementbuffer = 0;\n\t}\n\tif (normalbuffer != 0)\n\t{\n\t\tglDeleteBuffersARB(1, &normalbuffer);\n\t\tnormalbuffer = 0;\n\t}\n\tif (vertexbuffer != 0)\n\t{\n\t\tglDeleteBuffersARB(1, &vertexbuffer);\n\t\tvertexbuffer = 0;\n\t}\n}\n\n\n\n\nvoid TW_CALL setTimeStep(const void *value, void *clientData)\n{\n\tconst Real val = *(const Real *)(value);\n\tTimeManager::getCurrent()->setTimeStepSize(val);\n}\n\nvoid TW_CALL getTimeStep(void *value, void *clientData)\n{\n\t*(Real *)(value) = TimeManager::getCurrent()->getTimeStepSize();\n}\n\nvoid TW_CALL setVelocityUpdateMethod(const void *value, void *clientData)\n{\n\tconst short val = *(const short *)(value);\n\t((TimeStepFluidModel*)clientData)->setVelocityUpdateMethod((unsigned int)val);\n}\n\nvoid TW_CALL getVelocityUpdateMethod(void *value, void *clientData)\n{\n\t*(short *)(value) = (short)((TimeStepFluidModel*)clientData)->getVelocityUpdateMethod();\n}\n//////\n\nvoid TW_CALL setTempUpdateMethod(const void *value, void *clientData)\n{\n\tconst short val = *(const short *)(value);\n\t((FluidModel*)clientData)->heatTransferModel  = (unsigned int)val;\n}\n\nvoid TW_CALL getTempUpdateMethod(void *value, void *clientData)\n{\n\t*(short *)(value) = (short)((FluidModel*)clientData)->heatTransferModel ;\n}\n\n//////\nvoid TW_CALL setViscosity(const void *value, void *clientData)\n{\n\tconst Real val = *(const Real *)(value);\n\t((FluidModel*)clientData)->setViscosity(val);\n}\n\nvoid TW_CALL getViscosity(void *value, void *clientData)\n{\n\t*(Real *)(value) = ((FluidModel*)clientData)->getViscosity();\n}\n\nvoid TW_CALL getRadioSol(void *value, void *clientData)\n{\n\t*(Real *)(value) = ((FluidModel*)clientData)->getRadioSolidification();\n}\nvoid TW_CALL setRadioSol(const void *value, void *clientData) {\n\tconst Real val = *(const Real *)(value);\n\t((FluidModel*)clientData)->setRadioSolidification(val);\n}\nvoid TW_CALL getNumConstraint(void *value, void *clientData)\n{\n\t*(Real *)(value) = ((FluidModel*)clientData)->getNumMaxConstraints();\n}\nvoid TW_CALL setNumConstraint(const void *value, void *clientData)\n{\n\tconst Real val = *(const Real *)(value);\n\t((FluidModel*)clientData)->setNumMaxConstraints(val);\n}\nvoid TW_CALL setStiffness(const void *value, void *clientData)\n{\n\tconst Real val = *(const Real *)(value);\n\t((FluidModel*)clientData)->setClothStiffness(val);\n}\n\nvoid TW_CALL getStiffness(void *value, void *clientData)\n{\n\t*(Real *)(value) = ((FluidModel*)clientData)->getClothStiffness();\n}\n\nvoid TW_CALL setDilation(const void *value, void *clientData)\n{\n\tconst Real val = *(const Real *)(value);\n\t((FluidModel*)clientData)->setDilation(val);\n}\n\nvoid TW_CALL getDilation(void *value, void *clientData)\n{\n\t*(Real *)(value) = ((FluidModel*)clientData)->getDilation();\n}\n\nvoid TW_CALL setMelting(const void *value, void *clientData)\n{\n\tconst Real val = *(const Real *)(value);\n\t((FluidModel*)clientData)->setMelting(val);\n}\n\nvoid TW_CALL getMelting(void *value, void *clientData)\n{\n\t*(Real *)(value) = ((FluidModel*)clientData)->getMelting();\n}\n\nvoid TW_CALL setEvaporation(const void *value, void *clientData)\n{\n\tconst Real val = *(const Real *)(value);\n\t((FluidModel*)clientData)->setEvaporation(val);\n}\n\nvoid TW_CALL getEvaporation(void *value, void *clientData)\n{\n\t*(Real *)(value) = ((FluidModel*)clientData)->getEvaporation();\n}\n\nvoid TW_CALL setDifusion(const void *value, void *clientData)\n{\n\tconst Real val = *(const Real *)(value);\n\t((FluidModel*)clientData)->setDifusion(val);\n}\n\nvoid TW_CALL getDifusion(void *value, void *clientData)\n{\n\t*(Real *)(value) = ((FluidModel*)clientData)->getDifusion();\n}\n\n\nvoid TW_CALL setTempContact(const void *value, void *clientData)\n{\n\tconst Real val = *(const Real *)(value);\n\t((FluidModel*)clientData)->setTempContact(val);\n}\n\nvoid TW_CALL getTempContact(void *value, void *clientData)\n{\n\t*(Real *)(value) = ((FluidModel*)clientData)->getTempContact();\n}\n\nvoid TW_CALL setContact(const void *value, void *clientData)\n{\n\tconst bool val = *(const bool *)(value);\n\t((FluidModel*)clientData)->setContact(val);\n}\n\nvoid TW_CALL getContact(void *value, void *clientData)\n{\n\t*(bool *)(value) = ((FluidModel*)clientData)->getContact();\n}\n\nvoid TW_CALL setXPBD(const void *value, void *clientData)\n{\n\tconst bool val = *(const bool *)(value);\n\t((FluidModel*)clientData)->setXPBD(val);\n}\n\nvoid TW_CALL getXPBD(void *value, void *clientData)\n{\n\t*(bool *)(value) = ((FluidModel*)clientData)->getXPBD();\n}\n\nvoid TW_CALL setDesWidth(const void *value, void *clientData)\n{\n\tint val = *( int *)(value);\n\tMiniGL::desWidth = val;\n\tMiniGL::reziseDesWidth();\n}\n\nvoid TW_CALL getDesWidth(void *value, void *clientData)\n{\n\t*(int*)(value) = MiniGL::desWidth;\n}\n\nvoid TW_CALL setDesHeight(const void *value, void *clientData)\n{\n\tint val = *(int *)(value);\n\tMiniGL::desHeight = val;\n\tMiniGL::reziseDesHeight();\n}\n\nvoid TW_CALL getDesHeight(void *value, void *clientData)\n{\n\t*(int*)(value) = MiniGL::desHeight;\n}", "meta": {"hexsha": "a50d52e4ad061b5cc3d3b8057fbd272d04b96002", "size": 44534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Demos/FluidDemo/main.cpp", "max_stars_repo_name": "aibel18/phasechange", "max_stars_repo_head_hexsha": "30fa880fbd063b26b7e8187be4231fb40c668335", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T20:15:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-27T05:08:30.000Z", "max_issues_repo_path": "Demos/FluidDemo/main.cpp", "max_issues_repo_name": "aibel18/phasechange", "max_issues_repo_head_hexsha": "30fa880fbd063b26b7e8187be4231fb40c668335", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Demos/FluidDemo/main.cpp", "max_forks_repo_name": "aibel18/phasechange", "max_forks_repo_head_hexsha": "30fa880fbd063b26b7e8187be4231fb40c668335", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-19T20:15:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-19T20:15:37.000Z", "avg_line_length": 32.10814708, "max_line_length": 239, "alphanum_fraction": 0.7015314142, "num_tokens": 14036, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.22945854377344055}}
{"text": "/*\n * odeint_rk4_array\n *\n * Copyright 2011 Mario Mulansky\n * Copyright 2012 Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include <iostream>\n\n#include <boost/timer.hpp>\n#include <boost/array.hpp>\n\n#include <boost/numeric/odeint/stepper/runge_kutta4_classic.hpp>\n#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>\n#include <boost/numeric/odeint/algebra/array_algebra.hpp>\n\n#include \"lorenz.hpp\"\n\ntypedef boost::timer timer_type;\n\ntypedef boost::array< double , 3 > state_type;\n\nusing namespace boost::numeric::odeint;\n\n//typedef boost::numeric::odeint::runge_kutta4_classic< state_type > rk4_odeint_type;\n\n// use the never resizer explicitely for optimal performance with gcc, \n// for the intel compiler this doesnt matter and the above definition\n// gives the same performance\ntypedef runge_kutta4_classic< state_type , double , state_type , double ,\n                              array_algebra, default_operations, never_resizer > rk4_odeint_type;\n\n\nconst int loops = 21;\nconst int num_of_steps = 20000000;\nconst double dt = 1E-10;\n\n\nint main()\n{\n    double min_time = 1E6; // something big\n    rk4_odeint_type stepper;\n    std::clog.precision(16);\n    std::cout.precision(16);\n    for( int n=0; n<loops; n++ )\n    {\n        state_type x = {{ 8.5, 3.1, 1.2 }};\n        double t = 0.0;\n        timer_type timer;\n        for( size_t i = 0 ; i < num_of_steps ; ++i )\n        {\n            stepper.do_step( lorenz(), x, t, dt );\n            t += dt;\n        }\n        min_time = std::min( timer.elapsed() , min_time );\n        std::clog << timer.elapsed() << '\\t' << x[0] << std::endl;\n    }\n    std::cout << \"Minimal Runtime: \" << min_time << std::endl;\n}\n", "meta": {"hexsha": "6d60296f20db7c70d9a4bbfbff2554a1571ca2df", "size": 1795, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/performance/odeint_rk4_array.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/performance/odeint_rk4_array.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/performance/odeint_rk4_array.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 28.046875, "max_line_length": 97, "alphanum_fraction": 0.6601671309, "num_tokens": 506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2293622532108306}}
{"text": "\n// FaceMorphDlg.cpp : implementation file\n//\n\n#include \"pch.h\"\n#include \"framework.h\"\n#include \"FaceMorph.h\"\n#include \"FaceMorphDlg.h\"\n#include \"FileHandle.h\"\n#include \"DxDlg.h\"\n#include \"afxdialogex.h\"\n#include <Eigen/Core>\n#include <Eigen/SVD>\n \n#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\nconst int LINE_BUFF_SIZE = 4096;\nconst float g_fFOV = 12.5936f;// used to be 45.5f;\nconst float g_fAspect = 1.0f;\n// CAboutDlg dialog used for App About\n\nclass CAboutDlg : public CDialog\n{\npublic:\n\tCAboutDlg();\n\n// Dialog Data\n#ifdef AFX_DESIGN_TIME\n\tenum { IDD = IDD_ABOUTBOX };\n#endif\n\n\tprotected:\n\tvirtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support\n\n// Implementation\nprotected:\n\tDECLARE_MESSAGE_MAP()\n};\n//---------------------------------------------------------------//\nCAboutDlg::CAboutDlg() : CDialog(IDD_ABOUTBOX)\n{\n}\n//---------------------------------------------------------------//\nvoid CAboutDlg::DoDataExchange(CDataExchange* pDX)\n{\n\tCDialog::DoDataExchange(pDX);\n}\n//---------------------------------------------------------------//\nBEGIN_MESSAGE_MAP(CAboutDlg, CDialog)\nEND_MESSAGE_MAP()\n\n\n// CFaceMorphDlg dialog\n\n\n//---------------------------------------------------------------//\nCFaceMorphDlg::CFaceMorphDlg(CWnd* pParent /*=nullptr*/)\n\t: CDialog(IDD_FACEMORPH_DIALOG, pParent)\n{\n\tm_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);\n\t//cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, alpha, A, k, B, n, beta, C, n);\n}\n//---------------------------------------------------------------//\nCFaceMorphDlg::~CFaceMorphDlg()\n{\n \n}\n//---------------------------------------------------------------//\nvoid CFaceMorphDlg::DoDataExchange(CDataExchange* pDX)\n{\n\tfor (int h = 0; h < NUM_SLIDERS; h++)\n\t{\n\t\tDDX_Control(pDX, IDC_SLIDER1 + h, m_Slider[h]);\n\t}\n\tCDialog::DoDataExchange(pDX);\n}\n//---------------------------------------------------------------//\nBEGIN_MESSAGE_MAP(CFaceMorphDlg, CDialog)\n\tON_WM_TIMER()\n\tON_WM_SYSCOMMAND()\n\tON_WM_PAINT()\n\tON_WM_HSCROLL() \n\tON_WM_QUERYDRAGICON() \n\tON_WM_CLOSE()\n\tON_BN_CLICKED(IDC_RESET, &CFaceMorphDlg::OnBnClickedReset)\n\tON_BN_CLICKED(IDC_CHECK1, &CFaceMorphDlg::OnBnClickedCheck1)\n\tON_BN_CLICKED(IDC_EXPORT, &CFaceMorphDlg::OnBnClickedExport)\nEND_MESSAGE_MAP()\n//---------------------------------------------------------------//\n// CFaceMorphDlg message handlers\nBOOL CFaceMorphDlg::OnInitDialog()\n{\n\tCDialog::OnInitDialog();\n\n\t// Add \"About...\" menu item to system menu.\n\n\t// IDM_ABOUTBOX must be in the system command range.\n\tASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);\n\tASSERT(IDM_ABOUTBOX < 0xF000);\n\n\tCMenu* pSysMenu = GetSystemMenu(FALSE);\n\tif (pSysMenu != nullptr)\n\t{\n\t\tBOOL bNameValid;\n\t\tCString strAboutMenu;\n\t\tbNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);\n\t\tASSERT(bNameValid);\n\t\tif (!strAboutMenu.IsEmpty())\n\t\t{\n\t\t\tpSysMenu->AppendMenu(MF_SEPARATOR);\n\t\t\tpSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);\n\t\t}\n\t}\n\n\t// Set the icon for this dialog.  The framework does this automatically\n\t//  when the application's main window is not a dialog\n\tSetIcon(m_hIcon, TRUE);\t\t\t// Set big icon\n\tSetIcon(m_hIcon, FALSE);\t\t// Set small icon\n \n\tSetDlgItemText(IDC_EXPORT_PATH, L\"C:\\\\_3DMMExport\");\n\n\tCRect rtFrame;\n\tGetDlgItem(IDC_FRAME)->GetWindowRect(rtFrame);\n\tScreenToClient(rtFrame);\n\n\tfor (int h = 0; h < NUM_SLIDERS; h++)\n\t{\n\t\tm_Slider[h].SetRange(0, 2 * SLIDER_CENTER);\n\t\tm_Slider[h].SetPos(SLIDER_CENTER);\n\t}\n\tm_pRenderWnd = new CDxWnd();\n \n\tBOOL b2 = m_pRenderWnd->Create(NULL, _T(\"DxWnd\"), WS_VISIBLE, rtFrame, this, 1);\n\t \n\t//calculate the eigenvalues here and pass them to CDxDlg\n\t//first we need to find the Meshess folder//\n\t//This will be at a higher level. Recursively search until we find it\n\tCString strMeshPath;\n\tTCHAR szFilePath[MAX_PATH + _ATL_QUOTES_SPACE];\n\tDWORD dwFLen = ::GetModuleFileName(NULL, szFilePath + 0, MAX_PATH);\n\tstrMeshPath = CString(szFilePath);\n\n\tlong nRight = strMeshPath.ReverseFind(_T('\\\\'));//remove exe name\n\tstrMeshPath = strMeshPath.Left(nRight);//this will ne the same folder as the EXe\n\tbool bFoundMeshFolder = false;\n\tint nNumAttempts = 0;\n\twhile (!bFoundMeshFolder && nNumAttempts < 3)\n\t{\n\t\tnRight = strMeshPath.ReverseFind(_T('\\\\'));//move one folder up\n\t\tstrMeshPath = strMeshPath.Left(nRight);//this will ne the same folder as \n\t\tnNumAttempts++;\n\t\tif (DoesDirExist(strMeshPath + L\"\\\\Meshes\")) {\n\t\t\tbFoundMeshFolder = true;\n\t\t\tstrMeshPath.Append(L\"\\\\Meshes\\\\\");\n\t\t}\t\t \n\t\t\n\t}\n\tif (bFoundMeshFolder)\n\t{\n\t\tCalcEigenValues(strMeshPath);\n\t}\n\telse\n\t{\n\t\tAfxMessageBox(L\"Failed to find Mesh Folder\");\n\t}\n\n\t// Draw the background gradient.\n\tm_pRenderWnd->Initialize(this);\n\tm_pRenderWnd->MoveWindow(rtFrame);\n\tSetTimer(1, 50, NULL);\n\t \n \n\n\t/*dgesvd(\"All\", \"All\", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork,\n\t\t&info);*/\n\n\treturn TRUE;  // return TRUE  unless you set the focus to a control\n}  \n//---------------------------------------------------------------//\nbool CFaceMorphDlg::CalcEigenValues(CString strMeshPath)\n{\n\tif (!m_pRenderWnd)\n\t{\n\t\tAfxMessageBox(L\"m_pRenderWnd not created\");\n\t\treturn false;\n\t}\n\tstd::vector<std::vector<float> > vMeshes;\n\n\t \n\tint nNumVertices = -1;\n\tint nI1 = 0;\n\tint nI2 = 0;\n\tint nI3 = 0;\n\n\t////////////////////////////////////////////////////////////////////////////////////////\n\t//STEP ONE: load the files\n\t////////////////////////////////////////////////////////////////////////////////////////\n\tCFileFind finder;\n\t//count the number of files we will have to load\n\tint nNumFiles = 0;\n\tBOOL bWorking = finder.FindFile(strMeshPath + _T(\"*.mesh\"));\n\twhile (bWorking)\n\t{\n\t\tbWorking = finder.FindNextFile();\n\t\tnNumFiles++;\n\t}\n\tfinder.Close(); \n\n\tint nFileCounter = 0;\n\tbWorking = finder.FindFile(strMeshPath + _T(\"*.mesh\"));\n\twhile (bWorking)\n\t{\n\t\tbWorking = finder.FindNextFile();\n\t\tif (!bWorking) {\n\t\t\tlong ert = 0;\n\t\t}\n\t\tCString strPath = finder.GetFilePath();  \n\t\tint nCounter = 0; \n\t\tCFileHandle file(strPath, TEXT(\"r\"));\n\t\tif (file.GetFile() != 0)\n\t\t{\n\t\t\t//cound the vertices in advance and make sure they fit the vector\n\t\t\twhile (!feof(file.GetFile()))\n\t\t\t{\n\t\t\t\tCHAR buffer[LINE_BUFF_SIZE];\n\t\t\t\tfgets(buffer, LINE_BUFF_SIZE, file.GetFile());\n\t\t\t\tif (buffer[0] == 'v')\n\t\t\t\t{\n\t\t\t\t\tnCounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (nNumVertices == -1)\n\t\t\t{\n\t\t\t\tnNumVertices = nCounter;\n\t\t\t}\n\t\t\telse if (nNumVertices != nCounter)\n\t\t\t{\n\t\t\t\tfinder.Close();\n\t\t\t\tAfxMessageBox(L\"wrong size\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (nFileCounter == 0)\n\t\t\t{\n\t\t\t\tm_pRenderWnd->m_nNumVertices = nNumVertices;\n\t\t\t\t//we have enough info now to preallocate memory to avoid performance penalties caused by dynamic memory allocations...\n\t\t\t\tvMeshes.reserve(nNumFiles);\n\t\t\t\tvMeshes.resize(nNumFiles);\n\t\t\t\tint nNumVerticesXYZ = nNumVertices * 3;\n\t\t\t\tfor (int h = 0; h < nNumFiles; h++)\n\t\t\t\t{\n\t\t\t\t\tvMeshes[h].reserve(nNumVerticesXYZ);\n\t\t\t\t\tvMeshes[h].resize(nNumVerticesXYZ);\n\t\t\t\t}\n\n\t\t\t\tm_pRenderWnd->m_AveFace.reserve(nNumVerticesXYZ);\n\t\t\t\tm_pRenderWnd->m_AveFace.resize(nNumVerticesXYZ);\n\t\t\t\tm_pRenderWnd->m_Mesh.reserve(nNumVerticesXYZ);\n\t\t\t\tm_pRenderWnd->m_Mesh.resize(nNumVerticesXYZ);\n\t\t\t}\n\t\t\trewind(file.GetFile());\n\t\t\tint nIndex = 0;\n\t\t\tfloat x = 0;\n\t\t\tfloat y = 0;\n\t\t\tfloat z = 0;\n\t\t\twhile (!feof(file.GetFile()))\n\t\t\t{\n\t\t\t\tCHAR buffer[LINE_BUFF_SIZE];\n\t\t\t\tfgets(buffer, LINE_BUFF_SIZE, file.GetFile());\n\t\t\t\tif (0 == strncmp(\"v \", buffer, 2))\n\t\t\t\t{\n\t\t\t\t\t//load vertices into the vectors\n\t\t\t\t\tsscanf_s(buffer + 1, \"%f %f %f\", &x, &y, &z);\n\t\t\t\t\tm_pRenderWnd->m_AveFace[nIndex] += x;\n\t\t\t\t\tm_pRenderWnd->m_AveFace[nIndex + nNumVertices] += y;\n\t\t\t\t\tm_pRenderWnd->m_AveFace[nIndex + 2 * nNumVertices] += z;\n\t\t\t\t\tvMeshes[nFileCounter][nIndex] = x;\n\t\t\t\t\tvMeshes[nFileCounter][nIndex + nNumVertices] = y;\n\t\t\t\t\tvMeshes[nFileCounter][nIndex + 2 * nNumVertices] = z;\n\t\t\t\t\tnIndex++;\n\t\t\t\t}\n\t\t\t\telse if (nFileCounter == 0 && 0 == strncmp(\"f \", buffer, 2))\n\t\t\t\t{\n\t\t\t\t\t//load face information (list of three points forming a triangle). Do it for the first mesh only as the rest should be the same\n\t\t\t\t\tsscanf_s(buffer + 1, \"%d %d %d\", &nI1, &nI2, &nI3);\n\t\t\t\t\tm_pRenderWnd->m_vIndices.push_back(nI1 - 1);\n\t\t\t\t\tm_pRenderWnd->m_vIndices.push_back(nI2 - 1);\n\t\t\t\t\tm_pRenderWnd->m_vIndices.push_back(nI3 - 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tnFileCounter++; \n\t\t}\n\t}\n\t//finder.Close(); //note, CFileFinder calls Close on destructor, so we don't need to call this here\n\n\t////////////////////////////////////////////////////////////////////////////////////////\n\t//STEP TWO: calculate the mean/average face mesh\n\t////////////////////////////////////////////////////////////////////////////////////////\n\tfor_each(m_pRenderWnd->m_AveFace.begin(), m_pRenderWnd->m_AveFace.end(), [nNumFiles](float& x) {x = x / nNumFiles; });\n\n\t////////////////////////////////////////////////////////////////////////////////////////\n\t//STEP THREE: subtract the mean from each face mesh\n\t////////////////////////////////////////////////////////////////////////////////////////\n\tauto t = m_pRenderWnd->m_AveFace;\n\tfor (auto& m : vMeshes)\n\t{\n\t\tint j = 0;\n\t\tfor_each(m.begin(), m.end(), [&j, &t](float& x) {x = x - t[j]; j++; });\n\t}\n\t/*for (int h = 0; h < nNumFiles; h++)//older style for loop - but is it easier to read??\n\t{\n\t\tfor (int j = 0; j < nNumVertices * 3; j++){\n\t\t\tvMeshes[h][j] = vMeshes[h][j] - m_pRenderWnd->m_AveFace[j];\n\t\t}\n\t}*/\n\t////////////////////////////////////////////////////////////////////////////////////////\n\t//STEP FOUR: calculate the eigenvectors\n\t////////////////////////////////////////////////////////////////////////////////////////\n\tint nNumVerticesXYZ = nNumVertices * 3;\n\tEigen::MatrixXf X(nNumVerticesXYZ, nNumFiles);\n\tint h = 0;\n\tfor (auto& m : vMeshes)\n\t{\n\t\tint j = 0;\n\t\tfor_each(m.begin(), m.end(), [&j, h, &X](float& x) {X(j, h) = x; j++; });\n\t\th++;\n\t}\n\t/*for (int h = 0; h < nNumFiles; h++)//older style for loop - is this easier to read??\n\t{\n\t\tfor (int j = 0; j < nNumVerticesXYZ; j++) {\n\t\t\tX(j, h) = vMeshes[h][j];\n\t\t}\n\t}*/\n\n\t//Use Principle Component Analysis. SVD routine in the Eigen library to do this\n\tEigen::JacobiSVD<Eigen::MatrixXf> svd(X, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\tEigen::MatrixXf U = svd.matrixU();\n\tEigen::MatrixXf V = svd.matrixV();\n\tEigen::VectorXf s = svd.singularValues();\n \n\tif (s.rows() < NUM_EIGENS)\n\t{\n\t\tCString strMsg;\n\t\tstrMsg.Format(L\"Not enough eigenvectors found. We need at least %d. Please increase the number of meshes and restart the application.\", NUM_EIGENS);\n\t\tAfxMessageBox(strMsg);\n\t\treturn false;\n\t}\n\n\t//There will be nNumFiles eigenvectors, but only take the first 20 (NUM_EIGENS)\n\tm_pRenderWnd->m_Eigen.reserve(NUM_EIGENS);\n\tm_pRenderWnd->m_Eigen.resize(NUM_EIGENS);\n\tfor (int h = 0; h < NUM_EIGENS; h++)\n\t{\n\t\tm_pRenderWnd->m_Eigen[h].reserve(nNumVerticesXYZ);\n\t\tm_pRenderWnd->m_Eigen[h].resize(nNumVerticesXYZ);\n\t\tint j = 0;\n\t\tfor_each(m_pRenderWnd->m_Eigen[h].begin(), m_pRenderWnd->m_Eigen[h].end(), [&j, h, &U](float& x) {x = U(j, h); j++; });\n\t\t/*for (int j = 0; j < nNumVerticesXYZ; j++) \t{//older style, again, isn't it easier to read?\n\t\t\tm_pRenderWnd->m_Eigen[h][j] = U(j, h);\n\t\t}*/\n\t}\n\t//We now have the eigenvectors. The mesh that is rendered will be the average/mean mesh plus a linear combination of the \n\t//the eignevector meshes (m_Eigen). That is each eigenvector is multipled by the scalar corresponding to each slider in the UI.\n\treturn true;\n}\n//---------------------------------------------------------------//\nvoid CFaceMorphDlg::OnTimer(UINT_PTR nIdEvent)\n{\n\tif (nIdEvent == 1)\n\t{\n\t\tif(m_pRenderWnd) m_pRenderWnd->Render();\n\t}\n} \n//---------------------------------------------------------------//\nvoid CFaceMorphDlg::OnSysCommand(UINT nID, LPARAM lParam)\n{\n\tif ((nID & 0xFFF0) == IDM_ABOUTBOX)\n\t{\n\t\tCAboutDlg dlgAbout;\n\t\tdlgAbout.DoModal();\n\t}\n\telse\n\t{\n\t\tCDialog::OnSysCommand(nID, lParam);\n\t}\n}\n//---------------------------------------------------------------//\n// If you add a minimize button to your dialog, you will need the code below\n//  to draw the icon.  For MFC applications using the document/view model,\n//  this is automatically done for you by the framework.\nvoid CFaceMorphDlg::OnPaint()\n{\n\tif (IsIconic())\n\t{\n\t\tCPaintDC dc(this); // device context for painting\n\n\t\tSendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);\n\n\t\t// Center icon in client rectangle\n\t\tint cxIcon = GetSystemMetrics(SM_CXICON);\n\t\tint cyIcon = GetSystemMetrics(SM_CYICON);\n\t\tCRect rect;\n\t\tGetClientRect(&rect);\n\t\tint x = (rect.Width() - cxIcon + 1) / 2;\n\t\tint y = (rect.Height() - cyIcon + 1) / 2;\n\n\t\t// Draw the icon\n\t\tdc.DrawIcon(x, y, m_hIcon);\n\t}\n\telse\n\t{\n\t\tCDialog::OnPaint();\n\t}\n\n\tfor (int h = 0; h < 20; h++)\n\t{\n\t\tm_Slider[h].SetRange(0, 2 * SLIDER_CENTER);\n\t\tm_Slider[h].SetPos(SLIDER_CENTER);\n\t}\t\n}\n//---------------------------------------------------------------//\n// The system calls this function to obtain the cursor to display while the user drags\n//  the minimized window.\nHCURSOR CFaceMorphDlg::OnQueryDragIcon()\n{\n\treturn static_cast<HCURSOR>(m_hIcon);\n} \n//---------------------------------------------------------------//\nvoid CFaceMorphDlg::OnSlider()\n{\n\tif (!m_pRenderWnd) return;\n\tfor (int h = 0; h < NUM_SLIDERS; h++)\n\t{\n\t\tm_Scalars.m_Next[h] = (float)m_Slider[h].GetPos() - SLIDER_CENTER;\n\t}\n\tm_pRenderWnd->RecalcMesh(m_Scalars);\n}\n//---------------------------------------------------------------//\nvoid CFaceMorphDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)\n{\n\tCSliderCtrl* pSlider = reinterpret_cast<CSliderCtrl*>(pScrollBar);\n\tfor (int h = 0; h < NUM_SLIDERS; h++)\n\t{\n\t\tif (pSlider == &m_Slider[h])\n\t\t{\n\t\t\tOnSlider();\n\t\t}\n\t}\n\tCDialog::OnHScroll(nSBCode, nPos, pScrollBar);\n}\n//---------------------------------------------------------------//\nvoid CFaceMorphDlg::OnClose()\n{\n\tif (m_pRenderWnd)\n\t{\n\t\tm_pRenderWnd->ShutDown();\n\t\tm_pRenderWnd->DestroyWindow();\n\t\tdelete m_pRenderWnd;\n\t\tm_pRenderWnd = 0;\n\t}\n\n\tCDialog::OnClose();\n}\n//---------------------------------------------------------------//\nvoid CFaceMorphDlg::OnBnClickedReset()\n{\n\tfor (int h = 0; h < NUM_SLIDERS; h++)\n\t{\n\t\tm_Slider[h].SetPos(SLIDER_CENTER);\n\t};\n\tOnSlider();\n}\n//---------------------------------------------------------------//\nvoid CFaceMorphDlg::OnBnClickedCheck1()\n{\n\tif (!m_pRenderWnd) return;\n\tm_pRenderWnd->m_bWireframe = !m_pRenderWnd->m_bWireframe;\n}\n//-------------------------------------------------------------------------------------//\nbool CFaceMorphDlg::DoesDirExist(CString str)\n{\n\tDWORD dwRetVal = GetFileAttributes(str);\n\tif (dwRetVal == 0xFFFFFFFF)\n\t{\n\t\treturn false;\n\t}\n\telse if (dwRetVal & FILE_ATTRIBUTE_DIRECTORY)\n\t{\n\t\treturn true;\n\t}\n\treturn false;\n}\n//---------------------------------------------------------------//\nvoid CFaceMorphDlg::OnBnClickedExport()\n{ \n\tCString strLine;\n\tCString strExportPath;\n\tCWaitCursor wait;\n\n\tGetDlgItemText(IDC_EXPORT_PATH, strExportPath);\n\tif (!DoesDirExist(strExportPath))\n\t{\n\t\tAfxMessageBox(L\"Folder doesn't exist!\");\n\t\treturn;\n\t}\n\t//export eigenvalues \n\tCStdioFile f;\n\tint nNumVerticesXYZ = m_pRenderWnd->m_nNumVertices * 3;\n\tif (f.Open(strExportPath + L\"\\\\Eigen.dat\", CFile::modeCreate | CFile::modeWrite))\n\t{\t\t\n\t\tfor (int j = 0; j < nNumVerticesXYZ; j++)\n\t\t{\n\t\t\tfor (int h = 0; h < NUM_EIGENS; h++)\n\t\t\t{\n\t\t\t\tstrLine.Format(L\"%f\", m_pRenderWnd->m_Eigen[h][j]);\n\t\t\t\tf.WriteString(strLine);\n\t\t\t}\n\t\t\tf.WriteString(L\"\\n\");\n\t\t}\n\t\tf.Close();\n\t}\n\telse\n\t{\n\t\tAfxMessageBox(L\"Could not save EigenVector file\");\n\t\treturn;\n\t}\n\n\tif (f.Open(strExportPath + L\"\\\\MeanFace.dat\", CFile::modeCreate | CFile::modeWrite))\n\t{\n\t\tfor (int j = 0; j < nNumVerticesXYZ; j++)\n\t\t{\n\t\t\tstrLine.Format(L\"%f\\n\", m_pRenderWnd->m_AveFace[j]);\n\t\t\tf.WriteString(strLine);\n\t\t}\n\t\tf.Close();\n\t}\n\telse\n\t{\n\t\tAfxMessageBox(L\"Could not save file\");\n\t\treturn;\n\t}\n\n\tif (f.Open(strExportPath + L\"\\\\MeanFace.obj\", CFile::modeCreate | CFile::modeWrite))\n\t{\n\t\tfor (int j = 0; j < m_pRenderWnd->m_nNumVertices; j++)\n\t\t{\n\t\t\tstrLine.Format(L\"v %f %f %f\\n\", \n\t\t\t\tm_pRenderWnd->m_AveFace[j], \n\t\t\t\tm_pRenderWnd->m_AveFace[m_pRenderWnd->m_nNumVertices + j], \n\t\t\t\tm_pRenderWnd->m_AveFace[2 * m_pRenderWnd->m_nNumVertices + j]);\n\t\t\tf.WriteString(strLine);\n\t\t}\n\t\tsize_t nNumTriangles = m_pRenderWnd->m_vIndices.size() / 3;\n\t\tfor (int j = 0; j < nNumTriangles; j++)\n\t\t{\n\t\t\tstrLine.Format(L\"f %d %d %d\\n\",\n\t\t\t\tm_pRenderWnd->m_vIndices[3 * j + 0] + 1,\n\t\t\t\tm_pRenderWnd->m_vIndices[3 * j + 1] + 1,\n\t\t\t\tm_pRenderWnd->m_vIndices[3 * j + 2] + 1);\n\t\t\tf.WriteString(strLine);\n\t\t}\n\t\tf.Close();\n\t}\n\telse\n\t{\n\t\tAfxMessageBox(L\"Could not save file\");\n\t\treturn;\n\t}\n\t//To load this into matlab using a .,m file, something along the following should work\n\t//fid = fopen('C:\\_3DMMExport\\MeanFace.dat');\n\t//avgFace = [];\n\t//while ~feof(fid)\n\t//\ttline = fgetl(fid);\n\t//avgFace = [avgFace; sscanf(tline(1:end), '%f')']; \n\t//\tend\n\t//\tfclose(fid);\n\t//fid = fopen('C:\\_3DMMExport\\Eigen.dat');\n\t//egn = [length(avgFace), 20];\n\t//k = 1;\n\t//while ~feof(fid)\n\t//\ttline = fgetl(fid);\n\t//egn(k, 1:20) = sscanf(tline(1:end), '%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f');\n\t//k = k + 1;\n\t//end\n\t//\tfclose(fid);\n}\n", "meta": {"hexsha": "e3475692459e149621a913962994be60b2264532", "size": 16937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FaceMorph/FaceMorphDlg.cpp", "max_stars_repo_name": "nodecomplete/3DMM-Face-Sample", "max_stars_repo_head_hexsha": "fc9584e32674477097eae1520207c0166d797ce3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FaceMorph/FaceMorphDlg.cpp", "max_issues_repo_name": "nodecomplete/3DMM-Face-Sample", "max_issues_repo_head_hexsha": "fc9584e32674477097eae1520207c0166d797ce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FaceMorph/FaceMorphDlg.cpp", "max_forks_repo_name": "nodecomplete/3DMM-Face-Sample", "max_forks_repo_head_hexsha": "fc9584e32674477097eae1520207c0166d797ce3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8534923339, "max_line_length": 150, "alphanum_fraction": 0.5906004605, "num_tokens": 4995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632683808533, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22936224696128907}}
{"text": "// Copyright 2005 Mitsubishi Electric Research Laboratories All Rights\n// Reserved.\n\n// Permission to use, copy and modify this software and its documentation\n// without fee for educational, research and non-profit purposes, is hereby\n// granted, provided that the above copyright notice and the following three\n// paragraphs appear in all copies.\n\n// To request permission to incorporate this software into commercial products\n// contact: Vice President of Marketing and Business Development; Mitsubishi\n// Electric Research Laboratories (MERL), 201 Broadway, Cambridge, MA 02139 or\n// <license@merl.com>.\n\n// IN NO EVENT SHALL MERL BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,\n// INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF\n// THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF MERL HAS BEEN\n// ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\n// MERL SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n// PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND MERL\n// HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS OR\n// MODIFICATIONS.\n\n\n#include <cstdio>\n#include <cstdlib>\n#include <cmath>\n\n// Include Eigen\n#include <Eigen/Core>\n\n#define BRDF_SAMPLING_RES_THETA_H       90\n#define BRDF_SAMPLING_RES_THETA_D       90\n#define BRDF_SAMPLING_RES_PHI_D         360\n\n#define RED_SCALE (1.0/1500.0)\n#define GREEN_SCALE (1.15/1500.0)\n#define BLUE_SCALE (1.66/1500.0)\n\nstruct MerlBRDF {\n\n   /* Storage of the BRDF data */\n   double* brdf;\n\n   /* Constructor and destructor */\n   MerlBRDF() : brdf(nullptr) {\n   }\n\n   ~MerlBRDF() {\n      if(brdf != nullptr) {\n         delete[] brdf;\n      }\n   }\n\n   /* Evaluate the BRDF for a given couple of vectors */\n   template<class RGB, class Vector>\n   RGB const value(const Vector& wi, const Vector& wo) const {\n      double ti = acos(wi.z);\n      double pi = atan2(wi.y, wi.x);\n      double to = acos(wo.z);\n      double po = atan2(wo.y, wo.x);\n\n      double r, g, b;\n      lookup_brdf_val(ti, pi, to, po, r, g, b);\n      return RGB(r, g, b);\n   }\n\n   /* Read BRDF data */\n   bool read_brdf(const std::string& filename)\n   {\n      FILE *f = fopen(filename.c_str(), \"rb\");\n      if (!f) {\n         return false;\n      }\n\n      int dims[3];\n      fread(dims, sizeof(int), 3, f);\n      int n = dims[0] * dims[1] * dims[2];\n      if (n != BRDF_SAMPLING_RES_THETA_H *\n            BRDF_SAMPLING_RES_THETA_D *\n            BRDF_SAMPLING_RES_PHI_D / 2)\n      {\n         fprintf(stderr, \"Dimensions don't match\\n\");\n         fclose(f);\n         return false;\n      }\n\n      brdf = (double*) malloc (sizeof(double)*3*n);\n      fread(brdf, sizeof(double), 3*n, f);\n\n      fclose(f);\n      return true;\n   }\n\n   /* Project this BRDF to SH\n    *\n    * Return a std::vector containing an Eigen::MatrixXf for each input\n    * elevation. This matrix size is SH::Terms(order) x RGB.\n    */\n   template<class RGB, class Vector, class SH>\n   std::vector<Eigen::MatrixXf> projectToSH(int nbElev, int order, int M=10000) const {\n\n      // Random sampler\n      std::mt19937 gen(0);\n      std::uniform_real_distribution<float> dist(0.0,1.0);\n\n      // Return vector\n      std::vector<Eigen::MatrixXf> res;\n      res.reserve(nbElev);\n\n      // Sample each incident direction\n      for(int e=0; e<nbElev; ++e) {\n\n         // Get the current input vector\n         const float th = 0.5*M_PI * e / float(nbElev);\n         const Vector wi(sin(th), 0.0, cos(th));\n\n         Eigen::MatrixXf shCoeffs(SH::Terms(order), 3);\n         for(int i=0; i<M; ++i) {\n            // Sample the cosine of the elevation\n            Vector wo;\n            wo.z = 2.0*dist(gen) - 1.0;\n            const float z2 = wo.z*wo.z;\n            if(wo.z < 0.0) { continue; }\n\n            // Sample the azimuth\n            const float phi = 2.0*M_PI*dist(gen);\n            wo.x = sqrt(1.0f-z2) * cos(phi);\n            wo.y = sqrt(1.0f-z2) * sin(phi);\n\n            // Evaluate the function and the basis vector\n            const auto rgb = value<RGB, Vector>(wi, wo);\n            const auto ylm = SH::FastBasis(wo, order);\n            shCoeffs.col(0) += rgb[0]*ylm;\n            shCoeffs.col(1) += rgb[1]*ylm;\n            shCoeffs.col(2) += rgb[2]*ylm;\n         }\n         shCoeffs *= 4.0*M_PI / float(M);\n         res.push_back(shCoeffs);\n      }\n\n      return res;\n   }\n\n   // cross product of two vectors\n   void cross_product (double* v1, double* v2, double* out) const\n   {\n      out[0] = v1[1]*v2[2] - v1[2]*v2[1];\n      out[1] = v1[2]*v2[0] - v1[0]*v2[2];\n      out[2] = v1[0]*v2[1] - v1[1]*v2[0];\n   }\n\n   // normalize vector\n   void normalize(double* v) const\n   {\n      // normalize\n      double len = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);\n      v[0] = v[0] / len;\n      v[1] = v[1] / len;\n      v[2] = v[2] / len;\n   }\n\n   // rotate vector along one axis\n   void rotate_vector(double* vector, double* axis, double angle, double* out) const\n   {\n      double temp;\n      double cross[3];\n      double cos_ang = cos(angle);\n      double sin_ang = sin(angle);\n\n      out[0] = vector[0] * cos_ang;\n      out[1] = vector[1] * cos_ang;\n      out[2] = vector[2] * cos_ang;\n\n      temp = axis[0]*vector[0]+axis[1]*vector[1]+axis[2]*vector[2];\n      temp = temp*(1.0-cos_ang);\n\n      out[0] += axis[0] * temp;\n      out[1] += axis[1] * temp;\n      out[2] += axis[2] * temp;\n\n      cross_product (axis,vector,cross);\n\n      out[0] += cross[0] * sin_ang;\n      out[1] += cross[1] * sin_ang;\n      out[2] += cross[2] * sin_ang;\n   }\n\n\n   // convert standard coordinates to half vector/difference vector coordinates\n   void std_coords_to_half_diff_coords(double theta_in, double fi_in,\n                                       double theta_out, double fi_out,\n                                       double& theta_half,double& fi_half,\n                                       double& theta_diff,double& fi_diff ) const\n   {\n\n      // compute in vector\n      double in_vec_z = cos(theta_in);\n      double proj_in_vec = sin(theta_in);\n      double in_vec_x = proj_in_vec*cos(fi_in);\n      double in_vec_y = proj_in_vec*sin(fi_in);\n      double in[3]= {in_vec_x,in_vec_y,in_vec_z};\n      normalize(in);\n\n\n      // compute out vector\n      double out_vec_z = cos(theta_out);\n      double proj_out_vec = sin(theta_out);\n      double out_vec_x = proj_out_vec*cos(fi_out);\n      double out_vec_y = proj_out_vec*sin(fi_out);\n      double out[3]= {out_vec_x,out_vec_y,out_vec_z};\n      normalize(out);\n\n\n      // compute halfway vector\n      double half_x = (in_vec_x + out_vec_x)/2.0f;\n      double half_y = (in_vec_y + out_vec_y)/2.0f;\n      double half_z = (in_vec_z + out_vec_z)/2.0f;\n      double half[3] = {half_x,half_y,half_z};\n      normalize(half);\n\n      // compute  theta_half, fi_half\n      theta_half = acos(half[2]);\n      fi_half = atan2(half[1], half[0]);\n\n\n      double bi_normal[3] = {0.0, 1.0, 0.0};\n      double normal[3] = { 0.0, 0.0, 1.0 };\n      double temp[3];\n      double diff[3];\n\n      // compute diff vector\n      rotate_vector(in, normal , -fi_half, temp);\n      rotate_vector(temp, bi_normal, -theta_half, diff);\n\n      // compute  theta_diff, fi_diff\n      theta_diff = acos(diff[2]);\n      fi_diff = atan2(diff[1], diff[0]);\n\n   }\n\n\n   // Lookup theta_half index\n   // This is a non-linear mapping!\n   // In:  [0 .. pi/2]\n   // Out: [0 .. 89]\n   inline int theta_half_index(double theta_half) const\n   {\n      if (theta_half <= 0.0)\n         return 0;\n      double theta_half_deg = ((theta_half / (M_PI/2.0))*BRDF_SAMPLING_RES_THETA_H);\n      double temp = theta_half_deg*BRDF_SAMPLING_RES_THETA_H;\n      temp = sqrt(temp);\n      int ret_val = (int)temp;\n      if (ret_val < 0) ret_val = 0;\n      if (ret_val >= BRDF_SAMPLING_RES_THETA_H)\n         ret_val = BRDF_SAMPLING_RES_THETA_H-1;\n      return ret_val;\n   }\n\n\n   // Lookup theta_diff index\n   // In:  [0 .. pi/2]\n   // Out: [0 .. 89]\n   inline int theta_diff_index(double theta_diff) const\n   {\n      int tmp = int(theta_diff / (M_PI * 0.5) * BRDF_SAMPLING_RES_THETA_D);\n      if (tmp < 0)\n         return 0;\n      else if (tmp < BRDF_SAMPLING_RES_THETA_D - 1)\n         return tmp;\n      else\n         return BRDF_SAMPLING_RES_THETA_D - 1;\n   }\n\n\n   // Lookup phi_diff index\n   inline int phi_diff_index(double phi_diff) const\n   {\n      // Because of reciprocity, the BRDF is unchanged under\n      // phi_diff -> phi_diff + M_PI\n      if (phi_diff < 0.0)\n         phi_diff += M_PI;\n\n      // In: phi_diff in [0 .. pi]\n      // Out: tmp in [0 .. 179]\n      int tmp = int(phi_diff / M_PI * BRDF_SAMPLING_RES_PHI_D / 2);\n      if (tmp < 0)\n         return 0;\n      else if (tmp < BRDF_SAMPLING_RES_PHI_D / 2 - 1)\n         return tmp;\n      else\n         return BRDF_SAMPLING_RES_PHI_D / 2 - 1;\n   }\n\n   // Given a pair of incoming/outgoing angles, look up the BRDF.\n   void lookup_brdf_val(double theta_in, double fi_in,\n                        double theta_out, double fi_out,\n                        double& red_val, double& green_val,\n                        double& blue_val) const\n   {\n      // Convert to halfangle / difference angle coordinates\n      double theta_half, fi_half, theta_diff, fi_diff;\n\n      std_coords_to_half_diff_coords(theta_in, fi_in, theta_out, fi_out,\n            theta_half, fi_half, theta_diff, fi_diff);\n\n\n      // Find index.\n      // Note that phi_half is ignored, since isotropic BRDFs are assumed\n      int ind = phi_diff_index(fi_diff) +\n         theta_diff_index(theta_diff) * BRDF_SAMPLING_RES_PHI_D / 2 +\n         theta_half_index(theta_half) * BRDF_SAMPLING_RES_PHI_D / 2 *\n         BRDF_SAMPLING_RES_THETA_D;\n\n      red_val = brdf[ind] * RED_SCALE;\n      green_val = brdf[ind + BRDF_SAMPLING_RES_THETA_H*BRDF_SAMPLING_RES_THETA_D*BRDF_SAMPLING_RES_PHI_D/2] * GREEN_SCALE;\n      blue_val = brdf[ind + BRDF_SAMPLING_RES_THETA_H*BRDF_SAMPLING_RES_THETA_D*BRDF_SAMPLING_RES_PHI_D] * BLUE_SCALE;\n\n\n      if (red_val < 0.0 || green_val < 0.0 || blue_val < 0.0)\n         fprintf(stderr, \"Below horizon.\\n\");\n\n   }\n\n\n\n//#include \"EXR_IO.h\"\n//\n//int main(int argc, char *argv[])\n//{\n//   if(argc != 3) {\n//      fprintf(stderr, \"Uncorrect number of arguments to the command line\");\n//      fprintf(stderr, \"Usage: brdf_read [input].binary [output].exr\");\n//      return 1;\n//   }\n//\n//\n//\tconst char *filename = argv[1];\n//\tdouble* brdf;\n//\n//\t// read brdf\n//\tif (!read_brdf(filename, brdf))\n//\t{\n//\t\tfprintf(stderr, \"Error reading %s\\n\", filename);\n//\t\texit(1);\n//\t}\n//\n//   const auto phi      = 90;\n//\n//   const auto SKIP_PHI = BRDF_SAMPLING_RES_PHI_D / 2;\n//\n//   const auto SKIP     = SKIP_PHI\n//                       * BRDF_SAMPLING_RES_THETA_D\n//                       * BRDF_SAMPLING_RES_THETA_H;\n//\n//   const auto RES      = BRDF_SAMPLING_RES_THETA_H\n//                       * BRDF_SAMPLING_RES_THETA_D;\n//\n//\n//   double* img = new double[RES*3];\n//\n//   for(auto i=0; i<BRDF_SAMPLING_RES_THETA_H; ++i) {\n//      for(auto j=0; j<BRDF_SAMPLING_RES_THETA_D; ++j) {\n//\n//         const auto ind = phi\n//                        + j * SKIP_PHI\n//                        + i * SKIP_PHI * BRDF_SAMPLING_RES_THETA_D;\n//\n//         const auto R = brdf[ind + 0*SKIP] * RED_SCALE;\n//         const auto G = brdf[ind + 1*SKIP] * GREEN_SCALE;\n//         const auto B = brdf[ind + 2*SKIP] * BLUE_SCALE;\n//\n//         img[3*(i + j*BRDF_SAMPLING_RES_THETA_H)+0] = R;\n//         img[3*(i + j*BRDF_SAMPLING_RES_THETA_H)+1] = G;\n//         img[3*(i + j*BRDF_SAMPLING_RES_THETA_H)+2] = B;\n//\n//      }\n//   }\n//\n//   t_EXR_IO<double>::SaveEXR(argv[2], BRDF_SAMPLING_RES_THETA_H, BRDF_SAMPLING_RES_THETA_D, img);\n//\n//\treturn 0;\n//}\n\n};\n", "meta": {"hexsha": "3aba9a278f442d0cd5192cdff71eb0cdb5252e6c", "size": 11693, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utils/Merl.hpp", "max_stars_repo_name": "belcour/IntegralSH", "max_stars_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2018-02-27T07:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:40:06.000Z", "max_issues_repo_path": "utils/Merl.hpp", "max_issues_repo_name": "belcour/IntegralSH", "max_issues_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/Merl.hpp", "max_forks_repo_name": "belcour/IntegralSH", "max_forks_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-08T09:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T03:40:39.000Z", "avg_line_length": 30.1365979381, "max_line_length": 122, "alphanum_fraction": 0.5946292654, "num_tokens": 3419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2291657286788779}}
{"text": "/*\nanharmonic_core.cpp\n\nCopyright (c) 2014 Terumasa Tadano\n\nThis file is distributed under the terms of the MIT license.\nPlease see the file 'LICENCE.txt' in the root directory\nor http://opensource.org/licenses/mit-license.php for information.\n*/\n\n#include \"mpi_common.h\"\n#include \"anharmonic_core.h\"\n#include \"constants.h\"\n#include \"dynamical.h\"\n#include \"error.h\"\n#include \"fcs_phonon.h\"\n#include \"integration.h\"\n#include \"kpoint.h\"\n#include \"mathfunctions.h\"\n#include \"memory.h\"\n#include \"mode_analysis.h\"\n#include \"phonon_dos.h\"\n#include \"system.h\"\n#include \"thermodynamics.h\"\n#include <boost/lexical_cast.hpp>\n#include <algorithm>\n#include <vector>\n\n#ifdef _OPENMP\n\n#include <omp.h>\n\n#endif\n\nusing namespace PHON_NS;\n\nAnharmonicCore::AnharmonicCore(PHON *phon) : Pointers(phon)\n{\n    set_default_variables();\n}\n\nAnharmonicCore::~AnharmonicCore()\n{\n    deallocate_variables();\n};\n\nvoid AnharmonicCore::set_default_variables()\n{\n    quartic_mode = 0;\n    use_tuned_ver = true;\n    use_triplet_symmetry = true;\n    use_quartet_symmetry = true;\n    relvec_v3 = nullptr;\n    relvec_v4 = nullptr;\n    invmass_v3 = nullptr;\n    invmass_v4 = nullptr;\n    evec_index_v3 = nullptr;\n    evec_index_v4 = nullptr;\n    fcs_group_v3 = nullptr;\n    fcs_group_v4 = nullptr;\n    phi3_reciprocal = nullptr;\n    phi4_reciprocal = nullptr;\n    phase_storage_dos = nullptr;\n}\n\nvoid AnharmonicCore::deallocate_variables()\n{\n    if (relvec_v3) {\n        deallocate(relvec_v3);\n    }\n    if (relvec_v4) {\n        deallocate(relvec_v4);\n    }\n    if (invmass_v3) {\n        deallocate(invmass_v3);\n    }\n    if (invmass_v4) {\n        deallocate(invmass_v4);\n    }\n    if (evec_index_v3) {\n        deallocate(evec_index_v3);\n    }\n    if (evec_index_v4) {\n        deallocate(evec_index_v4);\n    }\n    if (fcs_group_v3) {\n        deallocate(fcs_group_v3);\n    }\n    if (fcs_group_v4) {\n        deallocate(fcs_group_v4);\n    }\n    if (phi3_reciprocal) {\n        deallocate(phi3_reciprocal);\n    }\n    if (phi4_reciprocal) {\n        deallocate(phi4_reciprocal);\n    }\n    if (phase_storage_dos) delete phase_storage_dos;\n}\n\nvoid AnharmonicCore::setup()\n{\n    sym_permutation = true;\n    use_tuned_ver = true;\n    MPI_Bcast(&use_tuned_ver, 1, MPI_CXX_BOOL, 0, MPI_COMM_WORLD);\n\n    if (fcs_phonon->maxorder >= 2) setup_cubic();\n    if (fcs_phonon->maxorder >= 3) setup_quartic();\n\n    if (!mode_analysis->calc_fstate_k && dos->kmesh_dos) {\n        phase_storage_dos = new PhaseFactorStorage(dos->kmesh_dos->nk_i);\n        phase_storage_dos->create(use_tuned_ver);\n    }\n}\n\nvoid AnharmonicCore::prepare_relative_vector(const std::vector<FcsArrayWithCell> &fcs_in,\n                                             const unsigned int N,\n                                             const int number_of_groups,\n                                             std::vector<double> *fcs_group,\n                                             std::vector<RelativeVector> *&vec_out) const\n{\n    int i, j, k;\n\n    double vecs[3][3];\n    double **xshift_s;\n\n    std::vector<unsigned int> atm_super, atm_prim;\n    std::vector<unsigned int> cells;\n\n    double mat_convert[3][3];\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            mat_convert[i][j] = 0.0;\n            for (k = 0; k < 3; ++k) {\n                mat_convert[i][j] += system->rlavec_p[i][k] * system->lavec_s_anharm[k][j];\n            }\n        }\n    }\n\n    allocate(xshift_s, 27, 3);\n\n    for (i = 0; i < 3; ++i) xshift_s[0][i] = 0.0;\n\n    unsigned int icell = 0;\n\n    for (int ix = -1; ix <= 1; ++ix) {\n        for (int iy = -1; iy <= 1; ++iy) {\n            for (int iz = -1; iz <= 1; ++iz) {\n                if (ix == 0 && iy == 0 && iz == 0) continue;\n\n                ++icell;\n\n                xshift_s[icell][0] = static_cast<double>(ix);\n                xshift_s[icell][1] = static_cast<double>(iy);\n                xshift_s[icell][2] = static_cast<double>(iz);\n            }\n        }\n    }\n\n    atm_prim.resize(N);\n    cells.resize(N);\n    atm_super.resize(N);\n\n    unsigned int icount = 0;\n\n    for (auto igroup = 0; igroup < number_of_groups; ++igroup) {\n\n        unsigned int nsize_group = fcs_group[igroup].size();\n\n        for (j = 0; j < nsize_group; ++j) {\n\n            for (i = 0; i < N; ++i) {\n                atm_prim[i] = fcs_in[icount].pairs[i].index / 3;\n                const auto tran_tmp = fcs_in[icount].pairs[i].tran;\n                cells[i] = fcs_in[icount].pairs[i].cell_s;\n                atm_super[i] = system->map_p2s_anharm[atm_prim[i]][tran_tmp];\n            }\n\n            for (i = 0; i < N - 1; ++i) {\n                for (k = 0; k < 3; ++k) {\n                    vecs[i][k] = system->xr_s_anharm[atm_super[i + 1]][k] + xshift_s[cells[i + 1]][k]\n                                 - system->xr_s_anharm[system->map_p2s_anharm[atm_prim[i + 1]][0]][k];\n                }\n                rotvec(vecs[i], vecs[i], mat_convert);\n            }\n\n            if (N == 3) {\n                vec_out[igroup].emplace_back(vecs[0], vecs[1]);\n            } else if (N == 4) {\n                vec_out[igroup].emplace_back(vecs[0], vecs[1], vecs[2]);\n            }\n            ++icount;\n        }\n    }\n\n    deallocate(xshift_s);\n}\n\nvoid AnharmonicCore::prepare_group_of_force_constants(const std::vector<FcsArrayWithCell> &fcs_in,\n                                                      const unsigned int N,\n                                                      int &number_of_groups,\n                                                      std::vector<double> *&fcs_group_out) const\n{\n    // Find the number of groups which has different evecs.\n\n    unsigned int i;\n    std::vector<int> arr_old, arr_tmp;\n\n    number_of_groups = 0;\n\n    arr_old.clear();\n    for (i = 0; i < N; ++i) {\n        arr_old.push_back(-1);\n    }\n\n    for (const auto &it: fcs_in) {\n\n        arr_tmp.clear();\n\n        for (i = 0; i < it.pairs.size(); ++i) {\n            arr_tmp.push_back(it.pairs[i].index);\n        }\n\n        if (arr_tmp != arr_old) {\n            ++number_of_groups;\n            arr_old.clear();\n            arr_old.reserve(arr_tmp.size());\n            std::copy(arr_tmp.begin(), arr_tmp.end(), std::back_inserter(arr_old));\n        }\n    }\n\n    allocate(fcs_group_out, number_of_groups);\n\n    int igroup = -1;\n\n    arr_old.clear();\n    for (i = 0; i < N; ++i) {\n        arr_old.push_back(-1);\n    }\n\n    for (const auto &it: fcs_in) {\n\n        arr_tmp.clear();\n\n        for (i = 0; i < it.pairs.size(); ++i) {\n            arr_tmp.push_back(it.pairs[i].index);\n        }\n\n        if (arr_tmp != arr_old) {\n            ++igroup;\n            arr_old.clear();\n            arr_old.reserve(arr_tmp.size());\n            std::copy(arr_tmp.begin(), arr_tmp.end(), std::back_inserter(arr_old));\n        }\n\n        fcs_group_out[igroup].push_back(it.fcs_val);\n    }\n}\n\nstd::complex<double> AnharmonicCore::V3(const unsigned int ks[3])\n{\n    return V3(ks,\n              dos->kmesh_dos->xk,\n              dos->dymat_dos->get_eigenvalues(),\n              dos->dymat_dos->get_eigenvectors(),\n              this->phase_storage_dos);\n}\n\nstd::complex<double> AnharmonicCore::V3(const unsigned int ks[3],\n                                        const double *const *xk_in,\n                                        const double *const *eval_in,\n                                        const std::complex<double> *const *const *evec_in)\n{\n    return V3(ks,\n              xk_in,\n              eval_in,\n              evec_in,\n              this->phase_storage_dos);\n}\n\nstd::complex<double> AnharmonicCore::V4(const unsigned int ks[4])\n{\n    return V4(ks,\n              dos->kmesh_dos->xk,\n              dos->dymat_dos->get_eigenvalues(),\n              dos->dymat_dos->get_eigenvectors(),\n              this->phase_storage_dos);\n}\n\nstd::complex<double> AnharmonicCore::Phi3(const unsigned int ks[3])\n{\n    return Phi3(ks,\n                dos->kmesh_dos->xk,\n                dos->dymat_dos->get_eigenvalues(),\n                dos->dymat_dos->get_eigenvectors(),\n                this->phase_storage_dos);\n}\n\nstd::complex<double> AnharmonicCore::Phi4(const unsigned int ks[4])\n{\n    return Phi4(ks,\n                dos->kmesh_dos->xk,\n                dos->dymat_dos->get_eigenvalues(),\n                dos->dymat_dos->get_eigenvectors(),\n                this->phase_storage_dos);\n}\n\nstd::complex<double> AnharmonicCore::V3(const unsigned int ks[3],\n                                        const double *const *xk_in,\n                                        const double *const *eval_in,\n                                        const std::complex<double> *const *const *evec_in,\n                                        const PhaseFactorStorage *phase_storage_in)\n{\n    int i;\n    unsigned int kn[3], sn[3];\n    const int ns = dynamical->neval;\n\n    double omega[3];\n    auto ret = std::complex<double>(0.0, 0.0);\n    auto ret_re = 0.0;\n    auto ret_im = 0.0;\n\n    for (i = 0; i < 3; ++i) {\n        kn[i] = ks[i] / ns;\n        sn[i] = ks[i] % ns;\n        omega[i] = eval_in[kn[i]][sn[i]];\n    }\n\n    // Return zero if any of the involving phonon has imaginary frequency\n    if (omega[0] < eps8 || omega[1] < eps8 || omega[2] < eps8) return 0.0;\n\n//    for (i = 0; i < ngroup_v3; ++i) {\n//        std::cout << \"invmass_v3[i] = \" << invmass_v3[i] << std::endl;\n//    }\n//\n//    for (i = 0; i < ngroup_v3; ++i) {\n//        std::cout << \"evec_index_v3 = \" << evec_index_v3[i][0]\n//        << evec_index_v3[i][1] <<  evec_index_v3[i][2] << std::endl;\n//    }\n\n    if (kn[1] != kindex_phi3_stored[0] || kn[2] != kindex_phi3_stored[1]) {\n        calc_phi3_reciprocal(xk_in[kn[1]],\n                             xk_in[kn[2]],\n                             phase_storage_in,\n                             phi3_reciprocal);\n\n//        for (i = 0; i < ngroup_v3; ++i) {\n//            std::cout << phi3_reciprocal[i] << std::endl;\n//        }\n        kindex_phi3_stored[0] = kn[1];\n        kindex_phi3_stored[1] = kn[2];\n    }\n#ifdef _OPENMP\n#pragma omp parallel for private(ret), reduction(+: ret_re, ret_im)\n#endif\n    for (i = 0; i < ngroup_v3; ++i) {\n        ret = evec_in[kn[0]][sn[0]][evec_index_v3[i][0]]\n              * evec_in[kn[1]][sn[1]][evec_index_v3[i][1]]\n              * evec_in[kn[2]][sn[2]][evec_index_v3[i][2]]\n              * invmass_v3[i] * phi3_reciprocal[i];\n        ret_re += ret.real();\n        ret_im += ret.imag();\n    }\n\n    return std::complex<double>(ret_re, ret_im)\n           / std::sqrt(omega[0] * omega[1] * omega[2]);\n}\n\nstd::complex<double> AnharmonicCore::Phi3(const unsigned int ks[3],\n                                          const double *const *xk_in,\n                                          const double *const *eval_in,\n                                          const std::complex<double> *const *const *evec_in,\n                                          const PhaseFactorStorage *phase_storage_in)\n{\n    int i;\n    unsigned int kn[3], sn[3];\n    const auto ns = dynamical->neval;\n\n    double omega[3];\n    std::complex<double> ret = std::complex<double>(0.0, 0.0);\n    double ret_re = 0.0;\n    double ret_im = 0.0;\n\n    for (i = 0; i < 3; ++i) {\n        kn[i] = ks[i] / ns;\n        sn[i] = ks[i] % ns;\n        omega[i] = eval_in[kn[i]][sn[i]];\n    }\n\n    if (kn[1] != kindex_phi3_stored[0] || kn[2] != kindex_phi3_stored[1]) {\n        calc_phi3_reciprocal(xk_in[kn[1]],\n                             xk_in[kn[2]],\n                             phase_storage_in,\n                             phi3_reciprocal);\n        kindex_phi3_stored[0] = kn[1];\n        kindex_phi3_stored[1] = kn[2];\n    }\n#ifdef _OPENMP\n#pragma omp parallel for private(ret), reduction(+: ret_re, ret_im)\n#endif\n    for (i = 0; i < ngroup_v3; ++i) {\n        ret = evec_in[kn[0]][sn[0]][evec_index_v3[i][0]]\n              * evec_in[kn[1]][sn[1]][evec_index_v3[i][1]]\n              * evec_in[kn[2]][sn[2]][evec_index_v3[i][2]]\n              * invmass_v3[i] * phi3_reciprocal[i];\n        ret_re += ret.real();\n        ret_im += ret.imag();\n    }\n\n    return std::complex<double>(ret_re, ret_im);\n}\n\nvoid AnharmonicCore::calc_phi3_reciprocal(const double *xk1,\n                                          const double *xk2,\n                                          const PhaseFactorStorage *phase_storage_in,\n                                          std::complex<double> *ret)\n{\n    int i, j;\n    double phase;\n    std::complex<double> ret_in;\n    unsigned int nsize_group;\n\n    const auto tune_type_now = phase_storage_in->get_tune_type();\n\n    if (tune_type_now == 1) {\n\n#pragma omp parallel for private(ret_in, nsize_group, j, phase)\n        for (i = 0; i < ngroup_v3; ++i) {\n\n            ret_in = std::complex<double>(0.0, 0.0);\n            nsize_group = fcs_group_v3[i].size();\n\n            for (j = 0; j < nsize_group; ++j) {\n                phase = relvec_v3[i][j].vecs[0][0] * xk1[0]\n                        + relvec_v3[i][j].vecs[0][1] * xk1[1]\n                        + relvec_v3[i][j].vecs[0][2] * xk1[2]\n                        + relvec_v3[i][j].vecs[1][0] * xk2[0]\n                        + relvec_v3[i][j].vecs[1][1] * xk2[1]\n                        + relvec_v3[i][j].vecs[1][2] * xk2[2];\n\n                ret_in += fcs_group_v3[i][j] * phase_storage_in->get_exp_type1(phase);\n            }\n            ret[i] = ret_in;\n        }\n\n    } else if (tune_type_now == 2) {\n\n        // Tuned version is used when nk1=nk2=nk3 doesn't hold.\n\n        double phase3[3];\n\n#pragma omp parallel for private(ret_in, nsize_group, j, phase3)\n        for (i = 0; i < ngroup_v3; ++i) {\n\n            ret_in = std::complex<double>(0.0, 0.0);\n            nsize_group = fcs_group_v3[i].size();\n\n            for (j = 0; j < nsize_group; ++j) {\n                for (auto ii = 0; ii < 3; ++ii) {\n                    phase3[ii]\n                            = relvec_v3[i][j].vecs[0][ii] * xk1[ii]\n                              + relvec_v3[i][j].vecs[1][ii] * xk2[ii];\n                }\n                ret_in += fcs_group_v3[i][j] * phase_storage_in->get_exp_type2(phase3);\n            }\n            ret[i] = ret_in;\n        }\n    } else {\n        // Original version\n#pragma omp parallel for private(ret_in, nsize_group, phase, j)\n        for (i = 0; i < ngroup_v3; ++i) {\n\n            ret_in = std::complex<double>(0.0, 0.0);\n            nsize_group = fcs_group_v3[i].size();\n\n            for (j = 0; j < nsize_group; ++j) {\n                phase\n                        = relvec_v3[i][j].vecs[0][0] * xk1[0]\n                          + relvec_v3[i][j].vecs[0][1] * xk1[1]\n                          + relvec_v3[i][j].vecs[0][2] * xk1[2]\n                          + relvec_v3[i][j].vecs[1][0] * xk2[0]\n                          + relvec_v3[i][j].vecs[1][1] * xk2[1]\n                          + relvec_v3[i][j].vecs[1][2] * xk2[2];\n                ret_in += fcs_group_v3[i][j] * std::exp(im * phase);\n            }\n            ret[i] = ret_in;\n        }\n    }\n}\n\nstd::complex<double> AnharmonicCore::V4(const unsigned int ks[4],\n                                        const double *const *xk_in,\n                                        const double *const *eval_in,\n                                        const std::complex<double> *const *const *evec_in,\n                                        const PhaseFactorStorage *phase_storage_in)\n{\n    int i;\n    const int ns = dynamical->neval;\n    unsigned int kn[4], sn[4];\n    double omega[4];\n    auto ret_re = 0.0;\n    auto ret_im = 0.0;\n    auto ret = std::complex<double>(0.0, 0.0);\n\n    for (i = 0; i < 4; ++i) {\n        kn[i] = ks[i] / ns;\n        sn[i] = ks[i] % ns;\n        omega[i] = eval_in[kn[i]][sn[i]];\n    }\n    // Return zero if any of the involving phonon has imaginary frequency\n    if (omega[0] < eps8 || omega[1] < eps8 || omega[2] < eps8 || omega[3] < eps8) return 0.0;\n\n    if (kn[1] != kindex_phi4_stored[0]\n        || kn[2] != kindex_phi4_stored[1]\n        || kn[3] != kindex_phi4_stored[2]) {\n\n        calc_phi4_reciprocal(xk_in[kn[1]],\n                             xk_in[kn[2]],\n                             xk_in[kn[3]],\n                             phase_storage_in,\n                             phi4_reciprocal);\n\n        kindex_phi4_stored[0] = kn[1];\n        kindex_phi4_stored[1] = kn[2];\n        kindex_phi4_stored[2] = kn[3];\n    }\n\n#ifdef _OPENMP\n#pragma omp parallel for private(ret), reduction(+: ret_re, ret_im)\n#endif\n    for (i = 0; i < ngroup_v4; ++i) {\n        ret = evec_in[kn[0]][sn[0]][evec_index_v4[i][0]]\n              * evec_in[kn[1]][sn[1]][evec_index_v4[i][1]]\n              * evec_in[kn[2]][sn[2]][evec_index_v4[i][2]]\n              * evec_in[kn[3]][sn[3]][evec_index_v4[i][3]]\n              * invmass_v4[i] * phi4_reciprocal[i];\n        ret_re += ret.real();\n        ret_im += ret.imag();\n    }\n\n    return std::complex<double>(ret_re, ret_im)\n           / std::sqrt(omega[0] * omega[1] * omega[2] * omega[3]);\n}\n\nstd::complex<double> AnharmonicCore::Phi4(const unsigned int ks[4],\n                                          const double *const *xk_in,\n                                          const double *const *eval_in,\n                                          const std::complex<double> *const *const *evec_in,\n                                          const PhaseFactorStorage *phase_storage_in)\n{\n    int i;\n    int ns = dynamical->neval;\n    unsigned int kn[4], sn[4];\n    double omega[4];\n    double ret_re = 0.0;\n    double ret_im = 0.0;\n    std::complex<double> ret = std::complex<double>(0.0, 0.0);\n\n    for (i = 0; i < 4; ++i) {\n        kn[i] = ks[i] / ns;\n        sn[i] = ks[i] % ns;\n        omega[i] = eval_in[kn[i]][sn[i]];\n    }\n\n    if (kn[1] != kindex_phi4_stored[0]\n        || kn[2] != kindex_phi4_stored[1]\n        || kn[3] != kindex_phi4_stored[2]) {\n\n        calc_phi4_reciprocal(xk_in[kn[1]],\n                             xk_in[kn[2]],\n                             xk_in[kn[3]],\n                             phase_storage_in,\n                             phi4_reciprocal);\n\n        kindex_phi4_stored[0] = kn[1];\n        kindex_phi4_stored[1] = kn[2];\n        kindex_phi4_stored[2] = kn[3];\n    }\n\n#ifdef _OPENMP\n#pragma omp parallel for private(ret), reduction(+: ret_re, ret_im)\n#endif\n    for (i = 0; i < ngroup_v4; ++i) {\n        ret = evec_in[kn[0]][sn[0]][evec_index_v4[i][0]]\n              * evec_in[kn[1]][sn[1]][evec_index_v4[i][1]]\n              * evec_in[kn[2]][sn[2]][evec_index_v4[i][2]]\n              * evec_in[kn[3]][sn[3]][evec_index_v4[i][3]]\n              * invmass_v4[i] * phi4_reciprocal[i];\n        ret_re += ret.real();\n        ret_im += ret.imag();\n    }\n\n    return std::complex<double>(ret_re, ret_im);\n}\n\nvoid AnharmonicCore::calc_phi4_reciprocal(const double *xk1,\n                                          const double *xk2,\n                                          const double *xk3,\n                                          const PhaseFactorStorage *phase_storage_in,\n                                          std::complex<double> *ret)\n{\n    int i, j;\n    double phase;\n    std::complex<double> ret_in;\n    unsigned int nsize_group;\n\n    const auto tune_type_now = phase_storage_in->get_tune_type();\n\n    if (tune_type_now == 1) {\n\n#pragma omp parallel for private(ret_in, nsize_group, j, phase)\n        for (i = 0; i < ngroup_v4; ++i) {\n\n            ret_in = std::complex<double>(0.0, 0.0);\n            nsize_group = fcs_group_v4[i].size();\n\n            for (j = 0; j < nsize_group; ++j) {\n                phase = relvec_v4[i][j].vecs[0][0] * xk1[0]\n                        + relvec_v4[i][j].vecs[0][1] * xk1[1]\n                        + relvec_v4[i][j].vecs[0][2] * xk1[2]\n                        + relvec_v4[i][j].vecs[1][0] * xk2[0]\n                        + relvec_v4[i][j].vecs[1][1] * xk2[1]\n                        + relvec_v4[i][j].vecs[1][2] * xk2[2]\n                        + relvec_v4[i][j].vecs[2][0] * xk3[0]\n                        + relvec_v4[i][j].vecs[2][1] * xk3[1]\n                        + relvec_v4[i][j].vecs[2][2] * xk3[2];\n\n                ret_in += fcs_group_v4[i][j] * phase_storage_in->get_exp_type1(phase);\n            }\n            ret[i] = ret_in;\n        }\n\n    } else if (tune_type_now == 2) {\n\n        // Tuned version is used when nk1=nk2=nk3 doesn't hold.\n\n        double phase3[3];\n\n#pragma omp parallel for private(ret_in, nsize_group, j, phase3)\n        for (i = 0; i < ngroup_v4; ++i) {\n\n            ret_in = std::complex<double>(0.0, 0.0);\n            nsize_group = fcs_group_v4[i].size();\n\n            for (j = 0; j < nsize_group; ++j) {\n                for (auto ii = 0; ii < 3; ++ii) {\n                    phase3[ii]\n                            = relvec_v4[i][j].vecs[0][ii] * xk1[ii]\n                              + relvec_v4[i][j].vecs[1][ii] * xk2[ii]\n                              + relvec_v4[i][j].vecs[2][ii] * xk3[ii];\n                }\n                ret_in += fcs_group_v4[i][j] * phase_storage_in->get_exp_type2(phase3);\n            }\n            ret[i] = ret_in;\n        }\n    } else {\n        // Original version\n#pragma omp parallel for private(ret_in, nsize_group, phase)\n        for (i = 0; i < ngroup_v4; ++i) {\n\n            ret_in = std::complex<double>(0.0, 0.0);\n            nsize_group = fcs_group_v4[i].size();\n\n            for (j = 0; j < nsize_group; ++j) {\n                phase = relvec_v4[i][j].vecs[0][0] * xk1[0]\n                        + relvec_v4[i][j].vecs[0][1] * xk1[1]\n                        + relvec_v4[i][j].vecs[0][2] * xk1[2]\n                        + relvec_v4[i][j].vecs[1][0] * xk2[0]\n                        + relvec_v4[i][j].vecs[1][1] * xk2[1]\n                        + relvec_v4[i][j].vecs[1][2] * xk2[2]\n                        + relvec_v4[i][j].vecs[2][0] * xk3[0]\n                        + relvec_v4[i][j].vecs[2][1] * xk3[1]\n                        + relvec_v4[i][j].vecs[2][2] * xk3[2];\n\n                ret_in += fcs_group_v4[i][j] * std::exp(im * phase);\n            }\n            ret[i] = ret_in;\n        }\n    }\n}\n\nstd::complex<double> AnharmonicCore::V3_mode(int mode,\n                                             const double *xk2,\n                                             const double *xk3,\n                                             int is,\n                                             int js,\n                                             double **eval,\n                                             std::complex<double> ***evec) const\n{\n    std::complex<double> ctmp = std::complex<double>(0.0, 0.0);\n\n    // Return zero if any of the involving phonon has imaginary frequency\n    if (eval[0][mode] < eps8 || eval[1][is] < eps8 || eval[2][js] < eps8) return 0.0;\n\n    unsigned int ielem = 0;\n\n    for (int i = 0; i < ngroup_v3; ++i) {\n\n        auto vec_tmp = evec[0][mode][evec_index_v3[i][0]]\n                       * evec[1][is][evec_index_v3[i][1]]\n                       * evec[2][js][evec_index_v3[i][2]]\n                       * invmass_v3[i];\n\n        auto ret_in = std::complex<double>(0.0, 0.0);\n\n        const int nsize_group = fcs_group_v3[i].size();\n\n        for (auto j = 0; j < nsize_group; ++j) {\n\n            auto phase = relvec_v3[i][j].vecs[0][0] * xk2[0]\n                         + relvec_v3[i][j].vecs[0][1] * xk2[1]\n                         + relvec_v3[i][j].vecs[0][2] * xk2[2]\n                         + relvec_v3[i][j].vecs[1][0] * xk3[0]\n                         + relvec_v3[i][j].vecs[1][1] * xk3[1]\n                         + relvec_v3[i][j].vecs[1][2] * xk3[2];\n\n            ret_in += fcs_group_v3[i][j] * std::exp(im * phase);\n\n            ++ielem;\n        }\n        ctmp += ret_in * vec_tmp;\n    }\n\n    return ctmp / std::sqrt(eval[0][mode] * eval[1][is] * eval[2][js]);\n}\n\nvoid AnharmonicCore::calc_damping_smearing(const unsigned int ntemp,\n                                           const double *temp_in,\n                                           const double omega_in,\n                                           const unsigned int ik_in,\n                                           const unsigned int is_in,\n                                           const KpointMeshUniform *kmesh_in,\n                                           const double *const *eval_in,\n                                           const std::complex<double> *const *const *evec_in,\n                                           double *ret)\n{\n    // This function returns the imaginary part of phonon self-energy \n    // for the given frequency omega_in.\n    // Lorentzian or Gaussian smearing will be used.\n    // This version employs the crystal symmetry to reduce the computational cost\n\n    const auto nk = kmesh_in->nk;\n    const auto ns = dynamical->neval;\n    const auto ns2 = ns * ns;\n    unsigned int i;\n    int ik;\n    unsigned int is, js;\n    unsigned int arr[3];\n\n    int k1, k2;\n\n    double T_tmp;\n    double n1, n2;\n    double omega_inner[2];\n\n    double multi;\n\n    for (i = 0; i < ntemp; ++i) ret[i] = 0.0;\n\n    double **v3_arr;\n    double ***delta_arr;\n    double ret_tmp;\n\n    double f1, f2;\n\n    const auto epsilon = integration->epsilon;\n\n    std::vector<KsListGroup> triplet;\n\n    kmesh_in->get_unique_triplet_k(ik_in,\n                                   symmetry->SymmList,\n                                   false,\n                                   false,\n                                   triplet);\n\n    const auto npair_uniq = triplet.size();\n\n    allocate(v3_arr, npair_uniq, ns * ns);\n    allocate(delta_arr, npair_uniq, ns * ns, 2);\n\n    const auto knum = kmesh_in->kpoint_irred_all[ik_in][0].knum;\n    const auto knum_minus = kmesh_in->kindex_minus_xk[knum];\n#ifdef _OPENMP\n#pragma omp parallel for private(multi, arr, k1, k2, is, js, omega_inner)\n#endif\n    for (ik = 0; ik < npair_uniq; ++ik) {\n        multi = static_cast<double>(triplet[ik].group.size());\n\n        arr[0] = ns * knum_minus + is_in;\n\n        k1 = triplet[ik].group[0].ks[0];\n        k2 = triplet[ik].group[0].ks[1];\n\n        for (is = 0; is < ns; ++is) {\n            arr[1] = ns * k1 + is;\n            omega_inner[0] = eval_in[k1][is];\n\n            for (js = 0; js < ns; ++js) {\n                arr[2] = ns * k2 + js;\n                omega_inner[1] = eval_in[k2][js];\n\n                if (integration->ismear == 0) {\n                    delta_arr[ik][ns * is + js][0]\n                            = delta_lorentz(omega_in - omega_inner[0] - omega_inner[1], epsilon)\n                              - delta_lorentz(omega_in + omega_inner[0] + omega_inner[1], epsilon);\n                    delta_arr[ik][ns * is + js][1]\n                            = delta_lorentz(omega_in - omega_inner[0] + omega_inner[1], epsilon)\n                              - delta_lorentz(omega_in + omega_inner[0] - omega_inner[1], epsilon);\n                } else if (integration->ismear == 1) {\n                    delta_arr[ik][ns * is + js][0]\n                            = delta_gauss(omega_in - omega_inner[0] - omega_inner[1], epsilon)\n                              - delta_gauss(omega_in + omega_inner[0] + omega_inner[1], epsilon);\n                    delta_arr[ik][ns * is + js][1]\n                            = delta_gauss(omega_in - omega_inner[0] + omega_inner[1], epsilon)\n                              - delta_gauss(omega_in + omega_inner[0] - omega_inner[1], epsilon);\n                }\n            }\n        }\n    }\n\n    for (ik = 0; ik < npair_uniq; ++ik) {\n\n        k1 = triplet[ik].group[0].ks[0];\n        k2 = triplet[ik].group[0].ks[1];\n\n        multi = static_cast<double>(triplet[ik].group.size());\n\n        for (int ib = 0; ib < ns2; ++ib) {\n            is = ib / ns;\n            js = ib % ns;\n\n            arr[0] = ns * knum_minus + is_in;\n            arr[1] = ns * k1 + is;\n            arr[2] = ns * k2 + js;\n\n            v3_arr[ik][ib] = std::norm(V3(arr,\n                                          kmesh_in->xk,\n                                          eval_in,\n                                          evec_in,\n                                          phase_storage_dos)) * multi;\n        }\n    }\n\n    for (i = 0; i < ntemp; ++i) {\n        T_tmp = temp_in[i];\n        ret_tmp = 0.0;\n#ifdef _OPENMP\n#pragma omp parallel for private(k1, k2, is, js, omega_inner, n1, n2, f1, f2), reduction(+:ret_tmp)\n#endif\n        for (ik = 0; ik < npair_uniq; ++ik) {\n\n            k1 = triplet[ik].group[0].ks[0];\n            k2 = triplet[ik].group[0].ks[1];\n\n            for (is = 0; is < ns; ++is) {\n\n                omega_inner[0] = eval_in[k1][is];\n\n                for (js = 0; js < ns; ++js) {\n\n                    omega_inner[1] = eval_in[k2][js];\n\n                    if (thermodynamics->classical) {\n                        f1 = thermodynamics->fC(omega_inner[0], T_tmp);\n                        f2 = thermodynamics->fC(omega_inner[1], T_tmp);\n\n                        n1 = f1 + f2;\n                        n2 = f1 - f2;\n                    } else {\n                        f1 = thermodynamics->fB(omega_inner[0], T_tmp);\n                        f2 = thermodynamics->fB(omega_inner[1], T_tmp);\n\n                        n1 = f1 + f2 + 1.0;\n                        n2 = f1 - f2;\n                    }\n\n                    ret_tmp += v3_arr[ik][ns * is + js]\n                               * (n1 * delta_arr[ik][ns * is + js][0]\n                                  - n2 * delta_arr[ik][ns * is + js][1]);\n                }\n            }\n        }\n        ret[i] = ret_tmp;\n    }\n\n    deallocate(v3_arr);\n    deallocate(delta_arr);\n    triplet.clear();\n\n    for (i = 0; i < ntemp; ++i) ret[i] *= pi * std::pow(0.5, 4) / static_cast<double>(nk);\n}\n\nvoid AnharmonicCore::calc_damping_tetrahedron(const unsigned int ntemp,\n                                              const double *temp_in,\n                                              const double omega_in,\n                                              const unsigned int ik_in,\n                                              const unsigned int is_in,\n                                              const KpointMeshUniform *kmesh_in,\n                                              const double *const *eval_in,\n                                              const std::complex<double> *const *const *evec_in,\n                                              double *ret)\n{\n    // This function returns the imaginary part of phonon self-energy \n    // for the given frequency omega_in.\n    // Tetrahedron method will be used.\n    // This version employs the crystal symmetry to reduce the computational cost\n\n    const int nk = kmesh_in->nk;\n    const int ns = dynamical->neval;\n\n    int ik, ib;\n    const auto ns2 = ns * ns;\n\n    unsigned int i;\n    unsigned int jk;\n    unsigned int is, js;\n    unsigned int k1, k2;\n    unsigned int arr[3];\n\n    double T_tmp;\n    double n1, n2;\n    double f1, f2;\n    double multi;\n\n    double xk_tmp[3];\n    double omega_inner[2];\n\n    double ret_tmp;\n\n    unsigned int *kmap_identity;\n    double **energy_tmp;\n    double **weight_tetra;\n    double **v3_arr;\n    double ***delta_arr;\n\n    std::vector<KsListGroup> triplet;\n\n    for (i = 0; i < ntemp; ++i) ret[i] = 0.0;\n\n    kmesh_in->get_unique_triplet_k(ik_in,\n                                   symmetry->SymmList,\n                                   use_triplet_symmetry,\n                                   sym_permutation,\n                                   triplet);\n\n    const auto npair_uniq = triplet.size();\n\n    allocate(v3_arr, npair_uniq, ns2);\n    allocate(delta_arr, npair_uniq, ns2, 2);\n\n    const auto knum = kmesh_in->kpoint_irred_all[ik_in][0].knum;\n    const auto knum_minus = kmesh_in->kindex_minus_xk[knum];\n    const auto xk = kmesh_in->xk;\n\n    allocate(kmap_identity, nk);\n\n    for (i = 0; i < nk; ++i) kmap_identity[i] = i;\n\n#ifdef _OPENMP\n#pragma omp parallel private(is, js, k1, k2, xk_tmp, energy_tmp, i, weight_tetra, ik, jk, arr)\n#endif\n    {\n        allocate(energy_tmp, 3, nk);\n        allocate(weight_tetra, 3, nk);\n\n#ifdef _OPENMP\n#pragma omp for\n#endif\n        for (ib = 0; ib < ns2; ++ib) {\n            is = ib / ns;\n            js = ib % ns;\n\n            for (k1 = 0; k1 < nk; ++k1) {\n\n                // Prepare two-phonon frequency for the tetrahedron method\n\n                for (i = 0; i < 3; ++i) xk_tmp[i] = xk[knum][i] - xk[k1][i];\n\n                k2 = kmesh_in->get_knum(xk_tmp);\n\n                energy_tmp[0][k1] = eval_in[k1][is] + eval_in[k2][js];\n                energy_tmp[1][k1] = eval_in[k1][is] - eval_in[k2][js];\n                energy_tmp[2][k1] = -energy_tmp[1][k1];\n            }\n\n            for (i = 0; i < 3; ++i) {\n                integration->calc_weight_tetrahedron(nk, kmap_identity,\n                                                     energy_tmp[i], omega_in,\n                                                     dos->tetra_nodes_dos->get_ntetra(),\n                                                     dos->tetra_nodes_dos->get_tetras(),\n                                                     weight_tetra[i]);\n            }\n\n            for (ik = 0; ik < npair_uniq; ++ik) {\n                jk = triplet[ik].group[0].ks[0];\n                delta_arr[ik][ib][0] = weight_tetra[0][jk];\n                delta_arr[ik][ib][1] = weight_tetra[1][jk] - weight_tetra[2][jk];\n            }\n        }\n\n        deallocate(energy_tmp);\n        deallocate(weight_tetra);\n    }\n\n    for (ik = 0; ik < npair_uniq; ++ik) {\n\n        k1 = triplet[ik].group[0].ks[0];\n        k2 = triplet[ik].group[0].ks[1];\n\n        multi = static_cast<double>(triplet[ik].group.size());\n\n        for (ib = 0; ib < ns2; ++ib) {\n            is = ib / ns;\n            js = ib % ns;\n\n            if (delta_arr[ik][ib][0] > 0.0 || std::abs(delta_arr[ik][ib][1]) > 0.0) {\n\n                arr[0] = ns * knum_minus + is_in;\n                arr[1] = ns * k1 + is;\n                arr[2] = ns * k2 + js;\n\n                v3_arr[ik][ib] = std::norm(V3(arr,\n                                              kmesh_in->xk,\n                                              eval_in,\n                                              evec_in,\n                                              phase_storage_dos)) * multi;\n\n            } else {\n                v3_arr[ik][ib] = 0.0;\n            }\n        }\n    }\n\n    for (i = 0; i < ntemp; ++i) {\n        T_tmp = temp_in[i];\n        ret_tmp = 0.0;\n#ifdef _OPENMP\n#pragma omp parallel for private(k1, k2, is, js, omega_inner, n1, n2, f1, f2), reduction(+:ret_tmp)\n#endif\n        for (ik = 0; ik < npair_uniq; ++ik) {\n\n            k1 = triplet[ik].group[0].ks[0];\n            k2 = triplet[ik].group[0].ks[1];\n\n            for (is = 0; is < ns; ++is) {\n\n                omega_inner[0] = eval_in[k1][is];\n\n                for (js = 0; js < ns; ++js) {\n\n                    omega_inner[1] = eval_in[k2][js];\n\n                    if (thermodynamics->classical) {\n                        f1 = thermodynamics->fC(omega_inner[0], T_tmp);\n                        f2 = thermodynamics->fC(omega_inner[1], T_tmp);\n\n                        n1 = f1 + f2;\n                        n2 = f1 - f2;\n                    } else {\n                        f1 = thermodynamics->fB(omega_inner[0], T_tmp);\n                        f2 = thermodynamics->fB(omega_inner[1], T_tmp);\n\n                        n1 = f1 + f2 + 1.0;\n                        n2 = f1 - f2;\n                    }\n\n                    ret_tmp += v3_arr[ik][ns * is + js]\n                               * (n1 * delta_arr[ik][ns * is + js][0]\n                                  - n2 * delta_arr[ik][ns * is + js][1]);\n                }\n            }\n        }\n        ret[i] = ret_tmp;\n    }\n\n    deallocate(v3_arr);\n    deallocate(delta_arr);\n    deallocate(kmap_identity);\n\n    for (i = 0; i < ntemp; ++i) ret[i] *= pi * std::pow(0.5, 4);\n}\n\nvoid AnharmonicCore::setup_cubic()\n{\n    int i;\n    double *invsqrt_mass_p;\n\n    // Sort force_constant[1] using the operator defined in fcs_phonons.h\n    // This sorting is necessary.\n    std::sort(fcs_phonon->force_constant_with_cell[1].begin(),\n              fcs_phonon->force_constant_with_cell[1].end());\n    prepare_group_of_force_constants(fcs_phonon->force_constant_with_cell[1],\n                                     3, ngroup_v3, fcs_group_v3);\n\n    allocate(invmass_v3, ngroup_v3);\n    allocate(evec_index_v3, ngroup_v3, 3);\n    allocate(relvec_v3, ngroup_v3);\n    allocate(phi3_reciprocal, ngroup_v3);\n\n    prepare_relative_vector(fcs_phonon->force_constant_with_cell[1],\n                            3,\n                            ngroup_v3,\n                            fcs_group_v3,\n                            relvec_v3);\n\n    allocate(invsqrt_mass_p, system->natmin);\n\n    for (i = 0; i < system->natmin; ++i) {\n        invsqrt_mass_p[i] = std::sqrt(1.0 / system->mass[system->map_p2s[i][0]]);\n    }\n\n    int k = 0;\n    for (i = 0; i < ngroup_v3; ++i) {\n        for (int j = 0; j < 3; ++j) {\n            evec_index_v3[i][j] = fcs_phonon->force_constant_with_cell[1][k].pairs[j].index;\n        }\n        invmass_v3[i]\n                = invsqrt_mass_p[evec_index_v3[i][0] / 3]\n                  * invsqrt_mass_p[evec_index_v3[i][1] / 3]\n                  * invsqrt_mass_p[evec_index_v3[i][2] / 3];\n        k += fcs_group_v3[i].size();\n    }\n\n    deallocate(invsqrt_mass_p);\n}\n\nvoid AnharmonicCore::setup_quartic()\n{\n    int i;\n    double *invsqrt_mass_p;\n    std::sort(fcs_phonon->force_constant_with_cell[2].begin(),\n              fcs_phonon->force_constant_with_cell[2].end());\n    prepare_group_of_force_constants(fcs_phonon->force_constant_with_cell[2],\n                                     4, ngroup_v4, fcs_group_v4);\n\n    allocate(invmass_v4, ngroup_v4);\n    allocate(evec_index_v4, ngroup_v4, 4);\n    allocate(relvec_v4, ngroup_v4);\n    allocate(phi4_reciprocal, ngroup_v4);\n\n    prepare_relative_vector(fcs_phonon->force_constant_with_cell[2],\n                            4,\n                            ngroup_v4,\n                            fcs_group_v4,\n                            relvec_v4);\n\n    allocate(invsqrt_mass_p, system->natmin);\n\n    for (i = 0; i < system->natmin; ++i) {\n        invsqrt_mass_p[i] = std::sqrt(1.0 / system->mass[system->map_p2s[i][0]]);\n    }\n\n    int k = 0;\n    for (i = 0; i < ngroup_v4; ++i) {\n        for (int j = 0; j < 4; ++j) {\n            evec_index_v4[i][j] = fcs_phonon->force_constant_with_cell[2][k].pairs[j].index;\n        }\n        invmass_v4[i]\n                = invsqrt_mass_p[evec_index_v4[i][0] / 3]\n                  * invsqrt_mass_p[evec_index_v4[i][1] / 3]\n                  * invsqrt_mass_p[evec_index_v4[i][2] / 3]\n                  * invsqrt_mass_p[evec_index_v4[i][3] / 3];\n        k += fcs_group_v4[i].size();\n    }\n\n    deallocate(invsqrt_mass_p);\n}\n\nvoid PhaseFactorStorage::create(const bool use_tuned_ver,\n                                const bool switch_to_type2)\n{\n    // For accelerating function V3 and V4 by avoiding continual call of std::exp.\n\n    if (use_tuned_ver) {\n\n        const auto inv2pi = 1.0 / (2.0 * pi);\n\n        for (auto i = 0; i < 3; ++i) dnk[i] = static_cast<double>(nk_grid[i]) * inv2pi;\n\n        tune_type = 1;\n\n        if (nk_grid[0] == nk_grid[1] && nk_grid[1] == nk_grid[2]) {\n            nk_represent = nk_grid[0];\n        } else if (nk_grid[0] == nk_grid[1] && nk_grid[2] == 1) {\n            nk_represent = nk_grid[0];\n        } else if (nk_grid[1] == nk_grid[2] && nk_grid[0] == 1) {\n            nk_represent = nk_grid[1];\n        } else if (nk_grid[2] == nk_grid[0] && nk_grid[1] == 1) {\n            nk_represent = nk_grid[2];\n        } else if (nk_grid[0] == 1 && nk_grid[1] == 1) {\n            nk_represent = nk_grid[2];\n        } else if (nk_grid[1] == 1 && nk_grid[2] == 1) {\n            nk_represent = nk_grid[0];\n        } else if (nk_grid[2] == 1 && nk_grid[0] == 1) {\n            nk_represent = nk_grid[1];\n        } else {\n            tune_type = 2;\n        }\n\n        // Force using tune_type == 2 version\n        if (switch_to_type2) tune_type = 2;\n\n        int ii, jj, kk;\n\n        if (tune_type == 1) {\n\n            double phase;\n            dnk_represent = static_cast<double>(nk_represent) * inv2pi;\n            const auto inv_dnk_represent = 1.0 / dnk_represent;\n\n            // Pre-calculate the phase factor exp[i 2pi * phase]\n            // for different phase angles ranging from [-2pi + 2pi/nk_represent: 2pi*(nk_represent-1)/nk_represent].\n            // The redundancy of the data here is intentional and helpful for accepting\n            // both positive and negative modulo.\n            allocate(exp_phase, 2 * nk_represent - 1);\n#ifdef _OPENMP\n#pragma omp parallel for private(phase)\n#endif\n            for (ii = 0; ii < 2 * nk_represent - 1; ++ii) {\n                phase = static_cast<double>(ii - nk_represent + 1) * inv_dnk_represent;\n                exp_phase[ii] = std::exp(im * phase);\n            }\n\n        } else if (tune_type == 2) {\n\n            double phase[3];\n            double inv_dnk[3];\n\n            for (auto i = 0; i < 3; ++i) inv_dnk[i] = 1.0 / dnk[i];\n\n            allocate(exp_phase3,\n                     2 * nk_grid[0] - 1,\n                     2 * nk_grid[1] - 1,\n                     2 * nk_grid[2] - 1);\n#ifdef _OPENMP\n#pragma omp parallel for private(phase, jj, kk)\n#endif\n            for (ii = 0; ii < 2 * nk_grid[0] - 1; ++ii) {\n                phase[0] = static_cast<double>(ii - nk_grid[0] + 1) * inv_dnk[0];\n                for (jj = 0; jj < 2 * nk_grid[1] - 1; ++jj) {\n                    phase[1] = static_cast<double>(jj - nk_grid[1] + 1) * inv_dnk[1];\n                    for (kk = 0; kk < 2 * nk_grid[2] - 1; ++kk) {\n                        phase[2] = static_cast<double>(kk - nk_grid[2] + 1) * inv_dnk[2];\n                        exp_phase3[ii][jj][kk] = std::exp(im * (phase[0] + phase[1] + phase[2]));\n                    }\n                }\n            }\n        }\n    } else {\n        tune_type = 0;\n    }\n}\n\nunsigned int PhaseFactorStorage::get_tune_type() const\n{\n    return tune_type;\n}\n\nstd::complex<double> PhaseFactorStorage::get_exp_type1(const double phase_in) const\n{\n    int iloc = nint(phase_in * dnk_represent) % nk_represent + nk_represent - 1;\n    return exp_phase[iloc];\n}\n\nstd::complex<double> PhaseFactorStorage::get_exp_type2(const double *phase3_in) const\n{\n    int loc[3];\n    for (auto i = 0; i < 3; ++i) {\n        loc[i] = nint(phase3_in[i] * dnk[i]) % nk_grid[i] + nk_grid[i] - 1;\n    }\n    return exp_phase3[loc[0]][loc[1]][loc[2]];\n}\n\nvoid AnharmonicCore::calc_self3omega_tetrahedron(const double Temp,\n                                                 const KpointMeshUniform *kmesh_in,\n                                                 const double *const *eval_in,\n                                                 const std::complex<double> *const *const *evec_in,\n                                                 const unsigned int ik_in,\n                                                 const unsigned int snum,\n                                                 const unsigned int nomega,\n                                                 const double *omega,\n                                                 double *ret)\n{\n    // This function returns the imaginary part of phonon self-energy \n    // for the given frequency range of omega, phonon frequency (eval) and phonon eigenvectors (evec).\n    // The tetrahedron method will be used.\n    // This version employs the crystal symmetry to reduce the computational cost\n    // In addition, both MPI and OpenMP parallelization are used in a hybrid way inside this function.\n\n    const auto nk = kmesh_in->nk;\n    const int ns = dynamical->neval;\n\n    int ik, ib, iomega;\n    const auto ns2 = ns * ns;\n\n    unsigned int i;\n    unsigned int is, js;\n    unsigned int k1, k2;\n    unsigned int arr[3];\n    unsigned int nk_tmp;\n\n    double n1, n2;\n    double f1, f2;\n    double omega_inner[2];\n\n    unsigned int *kmap_identity;\n    int **kpairs;\n    double **energy_tmp;\n    double **weight_tetra;\n    double **v3_arr, *v3_arr_loc;\n    double *ret_private;\n\n    std::vector<KsListGroup> triplet;\n    std::vector<int> vk_l;\n\n    const int knum = kmesh_in->kpoint_irred_all[ik_in][0].knum;\n    const int knum_minus = kmesh_in->kindex_minus_xk[knum];\n\n    kmesh_in->get_unique_triplet_k(ik_in,\n                                   symmetry->SymmList,\n                                   false,\n                                   false,\n                                   triplet);\n\n    const auto npair_uniq = triplet.size();\n\n    if (npair_uniq != nk) {\n        exit(\"calc_self3omega_tetrahedron\", \"Something is wrong.\");\n    }\n\n    allocate(kpairs, nk, 2);\n    allocate(kmap_identity, nk);\n\n    for (i = 0; i < nk; ++i) kmap_identity[i] = i;\n\n    for (iomega = 0; iomega < nomega; ++iomega) ret[iomega] = 0.0;\n\n    for (ik = 0; ik < npair_uniq; ++ik) {\n        kpairs[ik][0] = triplet[ik].group[0].ks[0];\n        kpairs[ik][1] = triplet[ik].group[0].ks[1];\n    }\n\n    if (nk % mympi->nprocs != 0) {\n        nk_tmp = nk / mympi->nprocs + 1;\n    } else {\n        nk_tmp = nk / mympi->nprocs;\n    }\n\n    vk_l.clear();\n\n    for (ik = 0; ik < nk; ++ik) {\n        if (ik % mympi->nprocs == mympi->my_rank) {\n            vk_l.push_back(ik);\n        }\n    }\n\n    if (vk_l.size() < nk_tmp) {\n        vk_l.push_back(-1);\n    }\n\n    allocate(v3_arr_loc, ns2);\n    allocate(v3_arr, nk_tmp * mympi->nprocs, ns2);\n\n    for (ik = 0; ik < nk_tmp; ++ik) {\n\n        int ik_now = vk_l[ik];\n\n        if (ik_now == -1) {\n\n            for (ib = 0; ib < ns2; ++ib) v3_arr_loc[ib] = 0.0; // do nothing\n\n        } else {\n#ifdef _OPENMP\n#pragma omp parallel for private(is, js, arr)\n#endif\n            for (ib = 0; ib < ns2; ++ib) {\n\n                is = ib / ns;\n                js = ib % ns;\n\n                arr[0] = ns * knum_minus + snum;\n                arr[1] = ns * kpairs[ik_now][0] + is;\n                arr[2] = ns * kpairs[ik_now][1] + js;\n\n                v3_arr_loc[ib] = std::norm(V3(arr,\n                                              kmesh_in->xk,\n                                              eval_in,\n                                              evec_in,\n                                              phase_storage_dos));\n            }\n        }\n        MPI_Gather(&v3_arr_loc[0], ns2, MPI_DOUBLE,\n                   v3_arr[ik * mympi->nprocs], ns2,\n                   MPI_DOUBLE, 0, MPI_COMM_WORLD);\n    }\n    deallocate(v3_arr_loc);\n\n    if (mympi->my_rank == 0) {\n\n#ifdef _OPENMP\n#pragma omp parallel private(is, js, k1, k2, energy_tmp, i, \\\n                             iomega, weight_tetra, ik, \\\n                             omega_inner, f1, f2, n1, n2)\n#endif\n        {\n            allocate(energy_tmp, 2, nk);\n            allocate(weight_tetra, 2, nk);\n#ifdef _OPENMP\n            const int nthreads = omp_get_num_threads();\n            const int ithread = omp_get_thread_num();\n#else\n            const int nthreads = 1;\n            const int ithread = 0;\n#endif\n\n#ifdef _OPENMP\n#pragma omp single\n#endif\n            {\n                allocate(ret_private, nthreads * nomega);\n                for (i = 0; i < nthreads * nomega; ++i) ret_private[i] = 0.0;\n            }\n#ifdef _OPENMP\n#pragma omp for\n#endif\n            for (ib = 0; ib < ns2; ++ib) {\n\n                is = ib / ns;\n                js = ib % ns;\n\n                for (ik = 0; ik < nk; ++ik) {\n                    k1 = kpairs[ik][0];\n                    k2 = kpairs[ik][1];\n\n                    energy_tmp[0][ik] = eval_in[k1][is] + eval_in[k2][js];\n                    energy_tmp[1][ik] = eval_in[k1][is] - eval_in[k2][js];\n                }\n                for (iomega = 0; iomega < nomega; ++iomega) {\n                    for (i = 0; i < 2; ++i) {\n                        integration->calc_weight_tetrahedron(nk, kmap_identity,\n                                                             energy_tmp[i], omega[iomega],\n                                                             dos->tetra_nodes_dos->get_ntetra(),\n                                                             dos->tetra_nodes_dos->get_tetras(),\n                                                             weight_tetra[i]);\n                    }\n\n                    for (ik = 0; ik < nk; ++ik) {\n                        k1 = kpairs[ik][0];\n                        k2 = kpairs[ik][1];\n\n                        omega_inner[0] = eval_in[k1][is];\n                        omega_inner[1] = eval_in[k2][js];\n                        if (thermodynamics->classical) {\n                            f1 = thermodynamics->fC(omega_inner[0], Temp);\n                            f2 = thermodynamics->fC(omega_inner[1], Temp);\n                            n1 = f1 + f2;\n                            n2 = f1 - f2;\n                        } else {\n                            f1 = thermodynamics->fB(omega_inner[0], Temp);\n                            f2 = thermodynamics->fB(omega_inner[1], Temp);\n                            n1 = f1 + f2 + 1.0;\n                            n2 = f1 - f2;\n                        }\n\n                        //#pragma omp critical\n                        ret_private[nomega * ithread + iomega]\n                                += v3_arr[ik][ib] * (n1 * weight_tetra[0][ik] - 2.0 * n2 * weight_tetra[1][ik]);\n                    }\n                }\n            }\n#ifdef _OPENMP\n#pragma omp for\n#endif\n            for (iomega = 0; iomega < nomega; ++iomega) {\n                for (int t = 0; t < nthreads; t++) {\n                    ret[iomega] += ret_private[nomega * t + iomega];\n                }\n            }\n            deallocate(energy_tmp);\n            deallocate(weight_tetra);\n        }\n#ifdef _OPENMP\n#pragma omp parallel for\n#endif\n        for (iomega = 0; iomega < nomega; ++iomega) {\n            ret[iomega] *= pi * std::pow(0.5, 4);\n        }\n        deallocate(ret_private);\n    }\n\n    deallocate(v3_arr);\n    deallocate(kmap_identity);\n    deallocate(kpairs);\n}\n\nint AnharmonicCore::get_ngroup_fcs(const unsigned int order) const\n{\n    if (order == 3) return ngroup_v3;\n    if (order == 4) return ngroup_v4;\n    return 0;\n}\n\nstd::vector<double> *AnharmonicCore::get_fcs_group(const unsigned int order) const\n{\n    if (order == 3) return fcs_group_v3;\n    if (order == 4) return fcs_group_v4;\n    return nullptr;\n}\n\ndouble *AnharmonicCore::get_invmass_factor(const unsigned int order) const\n{\n    if (order == 3) return invmass_v3;\n    if (order == 4) return invmass_v4;\n    return nullptr;\n}\n\nint **AnharmonicCore::get_evec_index(const unsigned int order) const\n{\n    if (order == 3) return evec_index_v3;\n    if (order == 4) return evec_index_v4;\n    return nullptr;\n}\n", "meta": {"hexsha": "9bdc547ee274aa82ecf7347f60de543685d03b3a", "size": 50314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "anphon/anharmonic_core.cpp", "max_stars_repo_name": "r-masuki/alamode", "max_stars_repo_head_hexsha": "6a75ac277e1e4bdaff4218b28a8d9ab7e5130b3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T17:19:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T14:26:02.000Z", "max_issues_repo_path": "anphon/anharmonic_core.cpp", "max_issues_repo_name": "r-masuki/alamode", "max_issues_repo_head_hexsha": "6a75ac277e1e4bdaff4218b28a8d9ab7e5130b3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2016-05-28T12:31:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:46:08.000Z", "max_forks_repo_path": "anphon/anharmonic_core.cpp", "max_forks_repo_name": "r-masuki/alamode", "max_forks_repo_head_hexsha": "6a75ac277e1e4bdaff4218b28a8d9ab7e5130b3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T02:17:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T09:13:40.000Z", "avg_line_length": 33.0144356955, "max_line_length": 116, "alphanum_fraction": 0.4797670628, "num_tokens": 14185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2291657286788779}}
{"text": "\n/*\n  * This program is free software; you can redistribute it and/or modify\n  * it under the terms of the GNU General Public License as published by\n  * the Free Software Foundation; either version 3 of the License, or\n  * (at your option) any later version.\n  *\n  * Written (W) 2013 Nicolo' Navarin\n  */\n\n#include \"DDK_FeatureGenerator.h\"\n //#include <shogun/features/Labels.h>\n#include <climits>\n#include <deque>\n//#include <boost/container/stable_vector.hpp>\n//#include <boost/random/uniform_int.hpp>\n//#include <boost/random/random_number_generator.hpp>\n//#include <boost/random.hpp>\n//#include <boost/generator_iterator.hpp>\n\n//#include <boost/random/variate_generator.hpp>\n//#include <boost/generator_iterator.hpp>\n\n// #include <shogun/mathematics/Math.h>\n\n //TODO eliminare\n double lossy_e=0.001;\n\n DDkernel_FeatureGenerator::DDkernel_FeatureGenerator()\n : learn_rate(0.1), max_iter(1000), NSPDK_FeatureGenerator(\"DDK\")\n {\n }\n/*\n DDkernel_FeatureGenerator::DDkernel_FeatureGenerator(CGraphFeatures* traindat, CLabels* trainlab)\n :  learn_rate(.1), max_iter(1000), NSPDK_FeatureGenerator(\"DDK\")\n {\n     //TODO inizializzazione\n   //  set_features(traindat);\n   //  set_labels(trainlab);\n }*/\n\n DDkernel_FeatureGenerator::~DDkernel_FeatureGenerator()\n {\n\t NSPDK_FeatureGenerator(\"ddk\");\n }\n DDkernel_FeatureGenerator::DDkernel_FeatureGenerator(const std::string& id) :\n \t\tNSPDK_FeatureGenerator(id) {\n\t\tnew_flag(&mTreeLambda, \"mTreeLambda\", \"(double)\\n tree_lambda parameter for DDK kernel\");\n }\n void DDkernel_FeatureGenerator::OutputParameters(ostream& out) const {\n \tout << \"Radius: \" << mRadius << endl;\n \tout << \"Radius2: \" << mRadiusTwo << endl;\n\n \tout << \"Distance: \" << mDistance << endl;\n \tout << \"Match_Type: \" << mMatchType << endl;\n \tout << \"Hash_Bit_Size: \" << mHashBitSize << endl;\n \tout << \"Hash_Bit_mask: \" << mHashBitMask << endl;\n \tout << \"Min_Kernel: \" << mMinKernel << endl;\n \tout << \"Normalization: \" << mNormalization << endl;\n \tout << \"Vertex Degree Threshold: \" << mVertexDegreeThreshold << endl;\n \tout << \"Debug_Verbosity: \" << mDebugVerbosity << endl;\n \tout << \"Tree_lambda: \" << mTreeLambda << endl;\n\n }\n\n void DDkernel_FeatureGenerator::generate_feature_vector(const GraphClass& aG, SVector& x, const vector<unsigned>& aFirstEndpointList) {\n }\n\t /*\n\t // OutputParameters(cout);\n\t vector<GraphClass> graphs;\n\t graphs.push_back(aG);\n\t CGraphFeatures* data = new CGraphFeatures(graphs);\n\t// set_lambda(mTreeLambda);\n\t //TODO dag_h is now set as the radius parameter r\n\t// cout<<\"dag_h=\"<<mRadius<<endl;\n\t svectorFeatures(data,x,mRadius+1 ,10000000);\n\t// data->;\n\t graphs.clear();\n\t delete data;\n\n }*/\n\n\n\n void DDkernel_FeatureGenerator::generate_vertex_feature_vector(const GraphClass& aG, vector<SVector>& x_list, const vector<unsigned>& aFirstEndpointList) {\n\n }\n\n void DDkernel_FeatureGenerator::GenerateAbstractVertexFeatures(unsigned aSrcID, const GraphClass& aG, unsigned aRadius, unsigned aDistance, SVector& x) {\n\n }\n\n //---------------------------------------------------------------------------------\n\n\n//TODO output on svector\n /*\n void DDkernel_FeatureGenerator::svectorFeatures(CGraphFeatures* data,SVector& out_vector, int dag_h, int max_features = 10000000){\n      //  vector<mymapForHash*> HashMaps = vector<mymapForHash*>(lhs->get_num_vectors());\n     // for di tutti i grafi cosi creo i bigDAG.\n\n long time = 1.0 / lossy_e;\n\n vector<double> BER_total;\n\n OnlineFeatures onlinefeatures(max_features);\n      //  OnlineFeatures onlinefeatures_old;\n\n         int64_t numero = 0;\n\n\n\n         int training =   data->get_num_vectors();\n         string a;\n         ofstream output(a.c_str());\n\n         for (int idx_a=0;idx_a<training;idx_a++){\n\n         Graph* a = new Graph() ;\n       int32_t size_a = 0;\n       ((CGraphFeatures*) data)->get_feature_vector(a,idx_a);\n\n    //   \t try{\n       OnlineHashBig2DAGLossy* test = onlinefeatures.generateFeatures(a, dag_h,idx_a,data->get_num_vectors());\n\n       OnlineHashBig2DAGOrdered ordered_map;\n    //TODO add features to a OnlineHashBig2DAGOrdered map\n       // cout<<\"test: \"<<test->size();\n        BOOST_FOREACH(OnlineHashBig2DAGLossy::value_type local_row, *test) {\n           ordered_map[local_row.second.get<2>()]=local_row.second;\n       }\n\n    //   cout<<\"ordered_map: \"<<ordered_map.size();\n        //normalize the feature vector\n\n\n  //      }\n        SVector z;\n\n    unsigned int last = 0;\n         BOOST_FOREACH(OnlineHashBig2DAGOrdered::value_type i_row,  ordered_map){\n           //  cout<<\"lambda \"<<lambda<<endl;\n\t\t\t\tz.set((unsigned int)i_row.second.get<2>() % (unsigned int)pow(2,mHashBitSize), pow((double)mTreeLambda, (double)i_row.second.get<0>() / 2.0)* (double)i_row.second.get<3>());\n\n                 ASSERT((unsigned int)i_row.second.get<2>() >= last);\n                 last = (unsigned int)i_row.second.get<2>();\n         }\n      //   if (mNormalization){\n        // \t\t\t\tz.normalize();}\n\n\t\tout_vector.add(z);\n\t\t//if (mNormalization){\n\t\t//\t\tout_vector.normalize();}\n\n     delete a;\n            test->clear();\n            ordered_map.clear();\n         delete test;\n\n     //  \t }catch(shogun::ShogunException e){\n     //  \t\t cout<<e.get_exception_string();\n\n      // \t }\n\n\n       }\n     //   cout<<endl;\n        output.close();\n\n\n     //  cout<<\"FEATURES has been printed\"<<endl;\n\n\n\n     }\n\n\n\n\n\nbool GraphSortCriterion (const tuple<double,Graph,long> p1, const tuple<double,Graph,long> p2)\n{\n    /// a graph is less than another graph\n\n\n    return p1.get<0>()<p2.get<0>();\n}\n\n\n\n\n\n\n\nbool FeaturesSortCriterion (const tuple<double,OnlineHashBig2DAG,long> p1, const tuple<double,OnlineHashBig2DAG,long> p2)\n{\n    // a graph is less than another graph\n\n\n    return p1.get<0>()<p2.get<0>();\n}\n\n*/\n\nvoid DDkernel_FeatureGeneratorNew::generate_feature_vector(const GraphClass& aG, SVector& x, const vector<unsigned>& aFirstEndpointList) {\n//\t OnlineFeaturesEDeN of;\n//\tcout<<\"Lambda=\"<<mTreeLambda<<endl;\n//\tcout<<\"Radius=\"<<mRadius<<endl;\n\n\t x = generate_feature_vector_core(aG, mRadius);\n\t if (mNormalization){\n\t \t\t\t\tx.normalize();\n\t }\n\n}\n\n\nSVector&  DDkernel_FeatureGeneratorNew::generate_feature_vector_core(const GraphClass& aG , int dag_h){\n\t//cout<<mTreeLambda<<endl;\n\t//cout<<\"start generation of feature vector..\"<<endl;\n\t\t\tSVector* x = new SVector();\n\n\t\t//\tcout<<\"n of nodes \"<<aG.VertexSize()<<endl;\n\t\t    for (unsigned i=0; i< aG.VertexSize(); i++){\n\t\t    \tmap<pair<unsigned, unsigned>, int> oSrcDestMaptoDistance;\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodetoParents;\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodetoChildren;\n\n\t\t    \tvector<unsigned> TopologicalSort;\n\t\t    \tint maxLevel = 0;\n\t\t    \t//aG. // codice calcolo features here\n\t\t      \taG.SingleVertexBoundedBreadthFirstVisitTree(i,dag_h, oSrcDestMaptoDistance,  MapNodetoParents,MapNodetoChildren, TopologicalSort, maxLevel);\n\t\t//    cout<<\"MaxLevel: \"<<maxLevel<<endl;\n\t\t      \t// \tcout<<\"Breadth first visit ended..\"<<endl;\n\t\t      \t// I have the DAG for the vertex i. Need topological sort.\n\t\t      \t//map every node to him productions\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodeToProductionsID;\n\t\t    \tmap<unsigned, vector<int> > MapNodetoFrequencies;\n\n\t\t    \tmap<unsigned, int > MapProductionIDtoSize;\n\n\t\t  //  \tcout<<\"topological sort size \"<<TopologicalSort.size()<<endl;\n\n\t\t      \t//maybe I meed the maximum depth (distance)\n\t\t      \tfor (int ii=TopologicalSort.size()-1; ii>=0; ii--){\n\t\t      \t\t// cout<<ii<<endl;\n\t\t      \t\t//calculate child size\n\t\t\t    \tvector<unsigned> vertex_adjacency_list = MapNodetoChildren[TopologicalSort[ii]];\n\t\t      \t\tint max_child_heigth=0;\n\t\t        \tfor (unsigned j = 0; j < vertex_adjacency_list.size(); ++j) {\n\t\t    \t\t\tint child_vertex_id= vertex_adjacency_list[j];\n\t\t    \t\t\tint child_heigth=MapNodeToProductionsID[child_vertex_id].size();\n\t\t    \t\t\tif(child_heigth > max_child_heigth){\n\t\t    \t\t\t\tmax_child_heigth = child_heigth;\n\t\t    \t\t\t}\n\t\t        \t}\n\n\t\t      \t\tfor (int depth=0; depth<= max_child_heigth; ++depth){ //era maxLevel\n\t\t      \t\t\tunsigned hash_subgraph_code = 1;\n\t\t      \t\t//depth 0; only label\n\t\t      \t\t\tif(depth==0){\n\t\t      \t\t//\t\tcout<<\"depth=0\"<<endl;\n\t\t      \t\t\t\tunsigned enc= Radius0RootedGraphCanonicalFormEncoding(TopologicalSort[ii], aG);\n\t\t      \t\tMapNodeToProductionsID[TopologicalSort[ii]].push_back(enc);\n\t\t      \t\t// scorro i figli e creo etichetta tramite funzione di hash\n\t\t      \t\t// depth > 0; the length of the children ID list\n\t\t      \t\t//imposta valore feature a 1 (TODO lambda)\n\t\t      \t\t//\t\t\t\t\t\t\tlevel(o-mRadius)\n\t\t\t    \tint frequency = 0;\n\t\t\t    \tif(max_child_heigth==0){\n\t\t      \t\t//leaf node\n\t\t\t    \tfrequency=  maxLevel - oSrcDestMaptoDistance[make_pair(i,TopologicalSort[ii])];\n\t\t\t    \t}\n\t\t\t    \tSVector z;\n\t\t      \t\tz.set(enc, (double)(frequency+1.0) * sqrt(mTreeLambda));\n\t\t\t    //\tcout<<\"Feature: \"<<aG.GetVertexLabelConcatenated(TopologicalSort[ii])<<\" freq:\"<<(double)(frequency+1.0) * sqrt(mTreeLambda)<<\" code: \"<<enc<<endl;\n\t\t\t    \tx->add(z);\n\t\t\t    \tMapNodetoFrequencies[TopologicalSort[ii]].push_back(frequency);\n\t\t      \t\tMapProductionIDtoSize[enc]= 1; //sqrt(mTreeLambda);\n\t\t      \t\t\t}\n\t\t      \t\t\telse{\n\t\t      \t//\t\t\tcout<<\"depth=\"<<depth<<endl;\n\n\t\t      \t\t\tint size = 0;\n\t\t      \t\tstring encoding;\n\t\t      \t\tencoding = aG.GetVertexLabelConcatenated(TopologicalSort[ii]);\n\t\t\t    \tvector<unsigned> vertex_adjacency_list = MapNodetoChildren[TopologicalSort[ii]];\n\t\t    \t\tvector<unsigned>  vertex_label_id_list;\n\t\t    \t\tint min_freq_children =INT_MAX;\n\t\t\t    \tfor (unsigned j = 0; j < vertex_adjacency_list.size(); ++j) {\n\n\t\t\t    \t\tunsigned child_vertex_id = vertex_adjacency_list[j];\n\t\t\t    \t\tint size_map =  MapNodeToProductionsID[child_vertex_id].size();//min (depth-1) e dim\n\t\t\t    \t\tunsigned child_hash = MapNodeToProductionsID[child_vertex_id][min(size_map,depth)-1];// id hash del figlio;\n\t\t\t    \t\tint freq_child = MapNodetoFrequencies[child_vertex_id][min(size_map,depth)-1];\n\t\t\t    \t\tif (freq_child < min_freq_children){\n\t\t\t    \t\t\tmin_freq_children = freq_child;\n\t\t\t    \t\t}\n\t\t\t    \t\tvertex_label_id_list.push_back(child_hash);\n\t\t\t    \t\tsize += MapProductionIDtoSize[child_hash];\n\t\t\t    \t}\n\n\t\t\t    \t// vertex_label_id_list contiene gli hash delle prod dei figli. Va ordinato e usato x generare l hash attuale\n\t\t\t    \tsort(vertex_label_id_list.begin(), vertex_label_id_list.end());\n\n\t\t\t    \tif (vertex_label_id_list.size() > 0){\n\t\t\t    \t\tstd::stringstream ss;\n\t\t\t    \t\tss <<\":\"<<vertex_label_id_list[0];\n\t\t\t    \t\tencoding += ss.str() ;\n\t\t\t    \t}//originale senza .\n\t\t\t    \tfor (unsigned i = 1; i < vertex_label_id_list.size(); i++){\n\t\t\t    \t\tstd::stringstream ss;\n\t\t\t    \t\tss << vertex_label_id_list[i];\n\t\t\t    \t\tencoding += \".\" + ss.str() ;\n\t\t\t    \t}\n\t\t\t    //DEBUG\tcout<<\"encoding \"<<encoding<<endl;\n\t\t\t    \t//calculate frequency\n\n\t\t\t    \thash_subgraph_code = HashFunc(encoding);\n\t\t\t    \tMapNodeToProductionsID[TopologicalSort[ii]].push_back(hash_subgraph_code);\n\t\t\t    \tsize += 1; // current node\n\t\t\t    \tMapProductionIDtoSize[hash_subgraph_code]= size;\n\t\t\t    \tint frequency = min_freq_children;\n\t\t\t    \tMapNodetoFrequencies[TopologicalSort[ii]].push_back(frequency);\n\n\t\t\t    \tSVector z;\n\t\t\t   // \tcout<<\"Feature: \"<<encoding<<\" freq:\"<<(double)(frequency+1.0) * sqrt(pow(mTreeLambda,size))<<\" code: \"<<hash_subgraph_code<<endl;\n\t\t\t    \tz.set(hash_subgraph_code,(double)(frequency+1.0) * sqrt(pow(mTreeLambda,size)));\n\t\t\t    \tx->add(z);\n\n\t\t\t    //\tcout<<\"weight \"<<sqrt(pow(mTreeLambda,size))<<endl;\n\n\t\t      \t\t\t}\n\n\t\t      \t\t}\n\t\t      \t}\n\n\n\t\t    }\n\t\t    return *x;\n\n\t }\n\nDDkernel_FeatureGeneratorNew::DDkernel_FeatureGeneratorNew(const std::string& id) :\n\t\tDDkernel_FeatureGenerator(id) {\n}\n\nNSDDkernel_FeatureGenerator::NSDDkernel_FeatureGenerator(const std::string& id) :\n\t\tDDkernel_FeatureGeneratorNew(id) {\n\tmRadiusTwo = 0;\n\t\t\tnew_flag(&mRadiusTwo, \"mRadiusTwo\", \"(double)\\n second radius parameter for NSDDK kernel\");\n\n}\n\nvoid NSDDkernel_FeatureGenerator::generate_feature_vector(const GraphClass& aG, SVector& x, const vector<unsigned>& aFirstEndpointList){\n//cout<<mRadiusTwo<<endl;\n\t x = generate_feature_vector_core(aG, mRadius);\n\t//x = generate_feature_vector_core_DISTANCE(aG, mRadius); //TEST distanze\n\n\t// if (mNormalization){\n\t //\t\t\t\tx.normalize();\n\t// }\n}\n\n\nSVector&   NSDDkernel_FeatureGenerator::generate_feature_vector_core(const GraphClass& aG , int dag_h){\n   // test rNSPDK 1/2 d=1/2\n\tGraphClass ag2 = aG;\n\tSVector* out = new SVector();\n//\tcout<<\"Generate feature vector core\"<<endl;\n\tfor (unsigned i=0; i< aG.VertexSize(); i++){\n\t//\tcout<<\"i:\"<<i<<endl;\n\n\t\t//SVector DD= generate_vertex_feature_vector(i,ag2 ,dag_h);\n\t\tvector<SVector> features; //(dag_h+1);\n\t\tSVector DD= generate_vertex_feature_vector_DIVIDED(i,ag2 ,mRadius,features);\n\t//\tcout<<\"got DD vector\"<<endl;\n\t\t//cout<<features.size();\n\t//\tout->add(DD);\n\t\t//NSPDK\n\t//\tcout<<\"start generation of NSPKD feature vector.. mDistance\"<<mDistance<<endl;\n\n\t\t//NSPDK_FeatureGenerator::GenerateVertexFeatures(i,aG,NSPDK);\n\t//\tNSPDK_FeatureGenerator::generate_feature_vector(aG,NSPDK);\n\t\tvector<unsigned> first_endpoint_list= vector<unsigned>();\n\t\tfirst_endpoint_list.push_back(i);\n\t\t\t//GetFirstEndpoints(aG, first_endpoint_list);\n\n\t\tint horizon=max(mDistance, mRadiusTwo); //   max(mDistance, mRadius);\n\t\t\taG.ComputePairwiseDistanceInformation(horizon, first_endpoint_list);\n\t\t\tif (aG.Check() == false)\n\t\t\t\tthrow logic_error(\"ERROR10: the graph data structure is not sound and it has not passed the checkup procedure\"); //check graph data structure soundness\n\n\t\t\tInitFeatureCache(aG, mRadiusTwo ); //mRadius\n\t\t\tfor (unsigned r = 0; r <= mRadius ; r++) { //max(1.0,mRadius / 2.0)\n\t\t\t\tfor (unsigned r2 = 0; r2 <= mRadiusTwo ; r2++) {\n\t\t\t\tfor (unsigned d = 0; d <= mDistance; d++) { // era 0\n\t\t\t\t\tSVector z;\n\t\t\t\t\tfor (unsigned i = 0; i < first_endpoint_list.size(); i++) {\n\t\t\t\t\t\tunsigned src_id = first_endpoint_list[i];\n\t\t\t\t\t\tif (aG.GetVertexViewPoint(src_id) && aG.GetVertexKernelPoint(src_id) && aG.GetVertexAlive(src_id)) { //proceed to extract features only if the *src* vertex is a kernel point and is alive\n\t\t\t\t\t\t\tSVector zv;\n\n\t\t\t\t\t\t\tvector<unsigned> endpoint_list(4);\n\t\t\t\t\t\t\tendpoint_list[0] = r2;\n\t\t\t\t\t\t\tendpoint_list[1] = d;\n\n\t\t\t\t\t\t//\tunsigned src_code = GenerateVertexNeighbourhoodHashCode(aSrcID, aG, aRadius);\n\t\t\t\t//\tTODO\tfor(unsigned src_code in DD)\n\n\t\t\t\t\t\t\tvector<unsigned> dest_id_list = aG.GetFixedDistanceVertexIDList(i, d);\n\t\t\t\t\t\t\tfor (unsigned dest_j = 0; dest_j < dest_id_list.size(); dest_j++) {\n\t\t\t\t\t\t\t\tunsigned dest_id = dest_id_list[dest_j];\n\t\t\t\t\t\t\t\tunsigned dest_code = 0;\n\t\t\t\t\t\t\t\tif (aG.GetVertexKernelPoint(dest_id) && aG.GetVertexAlive(dest_id)) { //proceed to extract features only if the *dest* vertex is a kernel point and is alive\n\t\t\t\t\t\t\t\t\tdest_code = GenerateVertexNeighbourhoodHashCode(dest_id, aG, r2); //\n\t\t\t\t\t\t\t\t\t// first is the DDK feature, second NSPDK feature\n\t\t\t\t\t\t//  for(const SVector::Pair *p = DD; p->i>=0; p++) {\n\t\t\t\t\t\t for(const SVector::Pair *p = features[r]; p->i>=0; p++) {\n\n\t\t\t\t\t\t\t\t\tendpoint_list[2] = p->i;\n\t\t\t\t\t\t\t\t\t\t//TODO scorrere le feature di DD\n\t\t\t\t\t\t\t\t\t\tendpoint_list[3] = dest_code;\n\t\t\t\t\t\t\t\t\tunsigned code = HashFunc(endpoint_list, mHashBitMask);\n\n\t\t\t\t\t\t\t\t\tSVector z;\n\t\t\t\t\t\t\t\t\tz.set(code, p->v);\n\t\t\t\t\t\t\t\t\tzv.add(z);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\t\tz.add(zv);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\tif (mNormalization)\n\t\t\t\t\t\tz.normalize();\n\t\t\t\tout->add(z);\n\t\t\t\t} //d\n\t\t\t} //r\n\t\t\t} //r2\n\n\n\n\n\n\n\n\t//\tcout<<\"features size DD:\"<<DD.sparse_size()<<\" out:\"<<out->sparse_size()<<endl;\n\n\n}\n\treturn *out;\n}\n\nSVector&   NSDDkernel_FeatureGenerator::generate_feature_vector_core_DISTANCE(const GraphClass& aG , int dag_h){\n   // test rNSPDK 1/2 d=1/2\n\tGraphClass ag2 = aG;\n\tSVector* out = new SVector();\n//\tcout<<\"Generate feature vector core\"<<endl;\n\tfor (unsigned i=0; i< aG.VertexSize(); i++){\n\t//\tcout<<\"i:\"<<i<<endl;\n\n\t\t//SVector DD= generate_vertex_feature_vector(i,ag2 ,dag_h);\n\t\tvector< vector< SVector> > features; //(dag_h+1);\n\t\tSVector DD= generate_vertex_feature_vector_DIVIDED_DISTANCE(i,ag2 ,dag_h,features);\n\t\t//cout<<features.size();\n\t//\tout->add(DD);\n\t\t//NSPDK\n\t//\tcout<<\"start generation of NSPKD feature vector.. mDistance\"<<mDistance<<endl;\n\n\t\t//NSPDK_FeatureGenerator::GenerateVertexFeatures(i,aG,NSPDK);\n\t//\tNSPDK_FeatureGenerator::generate_feature_vector(aG,NSPDK);\n\t\tvector<unsigned> first_endpoint_list= vector<unsigned>();\n\t\tfirst_endpoint_list.push_back(i);\n\t\t\t//GetFirstEndpoints(aG, first_endpoint_list);\n\n\t\tint horizon=max(mDistance, mRadiusTwo); //   max(mDistance, mRadius);\n\t\t\taG.ComputePairwiseDistanceInformation(horizon, first_endpoint_list);\n\t\t\tif (aG.Check() == false)\n\t\t\t\tthrow logic_error(\"ERROR10: the graph data structure is not sound and it has not passed the checkup procedure\"); //check graph data structure soundness\n\n\t\t\tInitFeatureCache(aG, mRadiusTwo ); //mRadius\n\t\t\tfor (unsigned r = 0; r <= mRadius ; r++) { //max(1.0,mRadius / 2.0)\n\t\t\t\tfor (unsigned r2 = 0; r2 <= mRadiusTwo ; r2++) {\n\t\t\t\tfor (unsigned d = 0; d <= mDistance; d++) { // era 0\n\t\t\t\t\tSVector z;\n\t\t\t\t\tfor (unsigned i = 0; i < first_endpoint_list.size(); i++) {\n\t\t\t\t\t\tunsigned src_id = first_endpoint_list[i];\n\t\t\t\t\t\tif (aG.GetVertexViewPoint(src_id) && aG.GetVertexKernelPoint(src_id) && aG.GetVertexAlive(src_id)) { //proceed to extract features only if the *src* vertex is a kernel point and is alive\n\t\t\t\t\t\t\tSVector zv;\n\n\t\t\t\t\t\t\tvector<unsigned> endpoint_list(5);\n\t\t\t\t\t\t\tendpoint_list[0] = r2;\n\t\t\t\t\t\t\tendpoint_list[1] = d;\n\n\t\t\t\t\t\t//\tunsigned src_code = GenerateVertexNeighbourhoodHashCode(aSrcID, aG, aRadius);\n\t\t\t\t//\tTODO\tfor(unsigned src_code in DD)\n\n\t\t\t\t\t\t\tvector<unsigned> dest_id_list = aG.GetFixedDistanceVertexIDList(i, d);\n\t\t\t\t\t\t\tfor (unsigned dest_j = 0; dest_j < dest_id_list.size(); dest_j++) {\n\t\t\t\t\t\t\t\tunsigned dest_id = dest_id_list[dest_j];\n\t\t\t\t\t\t\t\tunsigned dest_code = 0;\n\t\t\t\t\t\t\t\tif (aG.GetVertexKernelPoint(dest_id) && aG.GetVertexAlive(dest_id)) { //proceed to extract features only if the *dest* vertex is a kernel point and is alive\n\t\t\t\t\t\t\t\t\tdest_code = GenerateVertexNeighbourhoodHashCode(dest_id, aG, r2); //\n\t\t\t\t\t\t\t\t\t// first is the DDK feature, second NSPDK feature\n\t\t\t\t\t\t//  for(const SVector::Pair *p = DD; p->i>=0; p++) {\n\t\t\t\t\t\t\t\t\tfor(int distance=0; distance<features[r].size(); distance++){ //dag_h+1\n\t\t\t\t\t\t\t\t\t\tendpoint_list[4]=distance; //from root in DD\n\t\t\t\t\t\t for(const SVector::Pair *p = features[r][distance]; p->i>=0; p++) {\n\n\t\t\t\t\t\t\t\t\tendpoint_list[2] = p->i;\n\t\t\t\t\t\t\t\t\t\t//TODO scorrere le feature di DD\n\t\t\t\t\t\t\t\t\t\tendpoint_list[3] = dest_code;\n\t\t\t\t\t\t\t\t\t\t//TEST output\n\t\t\t\t\t\t\t\t//\t\tcout<<\"R \"<<endpoint_list[0]<<\" d \"<<endpoint_list[1]<<\" DD \"<<endpoint_list[2]<<\" NSPDK \"<<endpoint_list[3]<<\" dRoot \"<<endpoint_list[4]<<endl;\n\t\t\t\t\t\t\t\t\tunsigned code = HashFunc(endpoint_list, mHashBitMask);\n\n\t\t\t\t\t\t\t\t\tSVector z;\n\t\t\t\t\t\t\t\t\tz.set(code, p->v);\n\t\t\t\t\t\t\t\t\tzv.add(z);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\t\tz.add(zv);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\tif (mNormalization)\n\t\t\t\t\t\tz.normalize();\n\t\t\t\tout->add(z);\n\t\t\t\t} //d\n\t\t\t} //r\n\t\t\t}//r2\n\n\n\n\n\n\n\n\t//\tcout<<\"features size DD:\"<<DD.sparse_size()<<\" out:\"<<out->sparse_size()<<endl;\n\n\n}\n\treturn *out;\n}\n\nSVector&   NSDDkernel_FeatureGenerator::generate_vertex_feature_vector(unsigned i, const GraphClass& aG , int dag_h){\n\t//cout<<\"start generation of feature vector..\"<<endl;\n\t\t\tSVector* x = new SVector();\n\n\t\t//\tcout<<\"n of nodes \"<<aG.VertexSize()<<endl;\n\t\t    assert(i< aG.VertexSize());\n\t\t    \tmap<pair<unsigned, unsigned>, int> oSrcDestMaptoDistance;\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodetoParents;\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodetoChildren;\n\n\t\t    \tvector<unsigned> TopologicalSort;\n\t\t    \tint maxLevel = 0;\n\t\t    \t//aG. // codice calcolo features here\n\t\t      \taG.SingleVertexBoundedBreadthFirstVisitTree(i,dag_h, oSrcDestMaptoDistance,  MapNodetoParents,MapNodetoChildren, TopologicalSort, maxLevel);\n\t\t//    cout<<\"MaxLevel: \"<<maxLevel<<endl;\n\t\t      \t// \tcout<<\"Breadth first visit ended..\"<<endl;\n\t\t      \t// I have the DAG for the vertex i. Need topological sort.\n\t\t      \t//map every node to him productions\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodeToProductionsID;\n\t\t    \tmap<unsigned, vector<int> > MapNodetoFrequencies;\n\n\t\t    \tmap<unsigned, int > MapProductionIDtoSize;\n\n\t\t  //  \tcout<<\"topological sort size \"<<TopologicalSort.size()<<endl;\n\n\t\t      \t//maybe I meed the maximum depth (distance)\n\t\t      \tfor (int ii=TopologicalSort.size()-1; ii>=0; ii--){\n\t\t      \t\t// cout<<ii<<endl;\n\t\t      \t\t//calculate child size\n\t\t\t    \tvector<unsigned> vertex_adjacency_list = MapNodetoChildren[TopologicalSort[ii]];\n\t\t      \t\tint max_child_heigth=0;\n\t\t        \tfor (unsigned j = 0; j < vertex_adjacency_list.size(); ++j) {\n\t\t    \t\t\tint child_vertex_id= vertex_adjacency_list[j];\n\t\t    \t\t\tint child_heigth=MapNodeToProductionsID[child_vertex_id].size();\n\t\t    \t\t\tif(child_heigth > max_child_heigth){\n\t\t    \t\t\t\tmax_child_heigth = child_heigth;\n\t\t    \t\t\t}\n\t\t        \t}\n\n\t\t      \t\tfor (int depth=0; depth<= max_child_heigth; ++depth){ //era maxLevel\n\t\t      \t\t\tunsigned hash_subgraph_code = 1;\n\t\t      \t\t//depth 0; only label\n\t\t      \t\t\tif(depth==0){\n\t\t      \t\t//\t\tcout<<\"depth=0\"<<endl;\n\t\t      \t\t\t\tunsigned enc= Radius0RootedGraphCanonicalFormEncoding(TopologicalSort[ii], aG);\n\t\t      \t\tMapNodeToProductionsID[TopologicalSort[ii]].push_back(enc);\n\t\t      \t\t// scorro i figli e creo etichetta tramite funzione di hash\n\t\t      \t\t// depth > 0; the length of the children ID list\n\t\t      \t\t//imposta valore feature a 1 (TODO lambda)\n\t\t      \t\t//\t\t\t\t\t\t\tlevel(o-mRadius)\n\t\t\t    \tint frequency = 0;\n\t\t\t    \tif(max_child_heigth==0){\n\t\t      \t\t//leaf node\n\t\t\t    \tfrequency=  maxLevel - oSrcDestMaptoDistance[make_pair(i,TopologicalSort[ii])];\n\t\t\t    \t}\n\t\t\t    \tSVector z;\n\t\t      \t\tz.set(enc, (double)(frequency+1.0) * sqrt(mTreeLambda));\n\t\t\t    //\tcout<<\"Feature: \"<<aG.GetVertexLabelConcatenated(TopologicalSort[ii])<<\" freq:\"<<(double)(frequency+1.0) * sqrt(mTreeLambda)<<\" code: \"<<enc<<endl;\n\t\t\t    \tx->add(z);\n\t\t\t    \tMapNodetoFrequencies[TopologicalSort[ii]].push_back(frequency);\n\t\t      \t\tMapProductionIDtoSize[enc]= 1; //sqrt(mTreeLambda);\n\t\t      \t\t\t}\n\t\t      \t\t\telse{\n\t\t      \t//\t\t\tcout<<\"depth=\"<<depth<<endl;\n\n\t\t      \t\t\tint size = 0;\n\t\t      \t\tstring encoding;\n\t\t      \t\tencoding = aG.GetVertexLabelConcatenated(TopologicalSort[ii]);\n\t\t\t    \tvector<unsigned> vertex_adjacency_list = MapNodetoChildren[TopologicalSort[ii]];\n\t\t    \t\tvector<unsigned>  vertex_label_id_list;\n\t\t    \t\tint min_freq_children =INT_MAX;\n\t\t\t    \tfor (unsigned j = 0; j < vertex_adjacency_list.size(); ++j) {\n\n\t\t\t    \t\tunsigned child_vertex_id = vertex_adjacency_list[j];\n\t\t\t    \t\tint size_map =  MapNodeToProductionsID[child_vertex_id].size();//min (depth-1) e dim\n\t\t\t    \t\tunsigned child_hash = MapNodeToProductionsID[child_vertex_id][min(size_map,depth)-1];// id hash del figlio;\n\t\t\t    \t\tint freq_child = MapNodetoFrequencies[child_vertex_id][min(size_map,depth)-1];\n\t\t\t    \t\tif (freq_child < min_freq_children){\n\t\t\t    \t\t\tmin_freq_children = freq_child;\n\t\t\t    \t\t}\n\t\t\t    \t\tvertex_label_id_list.push_back(child_hash);\n\t\t\t    \t\tsize += MapProductionIDtoSize[child_hash];\n\t\t\t    \t}\n\n\t\t\t    \t// vertex_label_id_list contiene gli hash delle prod dei figli. Va ordinato e usato x generare l hash attuale\n\t\t\t    \tsort(vertex_label_id_list.begin(), vertex_label_id_list.end());\n\n\t\t\t    \tif (vertex_label_id_list.size() > 0){\n\t\t\t    \t\tstd::stringstream ss;\n\t\t\t    \t\tss <<\":\"<<vertex_label_id_list[0];\n\t\t\t    \t\tencoding += ss.str() ;\n\t\t\t    \t}//originale senza .\n\t\t\t    \tfor (unsigned i = 1; i < vertex_label_id_list.size(); i++){\n\t\t\t    \t\tstd::stringstream ss;\n\t\t\t    \t\tss << vertex_label_id_list[i];\n\t\t\t    \t\tencoding += \".\" + ss.str() ;\n\t\t\t    \t}\n\t\t\t    //DEBUG\tcout<<\"encoding \"<<encoding<<endl;\n\t\t\t    \t//calculate frequency\n\n\t\t\t    \thash_subgraph_code = HashFunc(encoding);\n\t\t\t    \tMapNodeToProductionsID[TopologicalSort[ii]].push_back(hash_subgraph_code);\n\t\t\t    \tsize += 1; // current node\n\t\t\t    \tMapProductionIDtoSize[hash_subgraph_code]= size;\n\t\t\t    \tint frequency = min_freq_children;\n\t\t\t    \tMapNodetoFrequencies[TopologicalSort[ii]].push_back(frequency);\n\n\t\t\t    \tSVector z;\n\t\t\t   // \tcout<<\"Feature: \"<<encoding<<\" freq:\"<<(double)(frequency+1.0) * sqrt(pow(mTreeLambda,size))<<\" code: \"<<hash_subgraph_code<<endl;\n\t\t\t    \tz.set(hash_subgraph_code,(double)(frequency+1.0) * sqrt(pow(mTreeLambda,size)));\n\t\t\t    \tx->add(z);\n\n\t\t\t    //\tcout<<\"weight \"<<sqrt(pow(mTreeLambda,size))<<endl;\n\n\t\t      \t\t\t}\n\n\t\t      \t\t}\n\t\t      \t}\n\n\n\n\t\t    return *x;\n\n\t }\n\n\nSVector&   NSDDkernel_FeatureGenerator::generate_vertex_feature_vector_DIVIDED(unsigned i, const GraphClass& aG , int dag_h, vector<SVector> & features_grouped_by_depth){\n\t//cout<<\"start generation of feature vector..\"<<endl;\n\t\t\tSVector* x = new SVector();\n\t\t\tfeatures_grouped_by_depth= vector<SVector>(dag_h+1);\n\t\t/*\tfor(int i=0; i<dag_h;i++){\n\t\t\t\tfeatures_grouped_by_depth.push_back(SVector(0));\n\n\t\t\t}*/\n\t\t//\tcout<<\"n of nodes \"<<aG.VertexSize()<<endl;\n\t\t    assert(i< aG.VertexSize());\n\t\t    \tmap<pair<unsigned, unsigned>, int> oSrcDestMaptoDistance;\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodetoParents;\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodetoChildren;\n\n\t\t    \tvector<unsigned> TopologicalSort;\n\t\t    \tint maxLevel = 0;\n\t\t    \t//aG. // codice calcolo features here\n\t\t      \taG.SingleVertexBoundedBreadthFirstVisitTree(i,dag_h, oSrcDestMaptoDistance,  MapNodetoParents,MapNodetoChildren, TopologicalSort, maxLevel);\n\t\t//    cout<<\"MaxLevel: \"<<maxLevel<<endl;\n\t\t      \t// \tcout<<\"Breadth first visit ended..\"<<endl;\n\t\t      \t// I have the DAG for the vertex i. Need topological sort.\n\t\t      \t//map every node to him productions\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodeToProductionsID;\n\t\t    \tmap<unsigned, vector<int> > MapNodetoFrequencies;\n\n\t\t    \tmap<unsigned, int > MapProductionIDtoSize;\n\n\t\t  //  \tcout<<\"topological sort size \"<<TopologicalSort.size()<<endl;\n\n\t\t      \t//maybe I meed the maximum depth (distance)\n\t\t      \tfor (int ii=TopologicalSort.size()-1; ii>=0; ii--){\n\t\t      \t\t// cout<<ii<<endl;\n\t\t      \t\t//calculate child size\n\t\t\t    \tvector<unsigned> vertex_adjacency_list = MapNodetoChildren[TopologicalSort[ii]];\n\t\t      \t\tint max_child_heigth=0;\n\t\t        \tfor (unsigned j = 0; j < vertex_adjacency_list.size(); ++j) {\n\t\t    \t\t\tint child_vertex_id= vertex_adjacency_list[j];\n\t\t    \t\t\tint child_heigth=MapNodeToProductionsID[child_vertex_id].size();\n\t\t    \t\t\tif(child_heigth > max_child_heigth){\n\t\t    \t\t\t\tmax_child_heigth = child_heigth;\n\t\t    \t\t\t}\n\t\t        \t}\n\n\t\t      \t\tfor (int depth=0; depth<= max_child_heigth; ++depth){ //era maxLevel\n\t\t      \t\t\tunsigned hash_subgraph_code = 1;\n\t\t      \t\t//depth 0; only label\n\t\t      \t\t\tif(depth==0){\n\t\t      \t\t//\t\tcout<<\"depth=0\"<<endl;\n\t\t      \t\t\t\tunsigned enc= Radius0RootedGraphCanonicalFormEncoding(TopologicalSort[ii], aG);\n\t\t      \t\tMapNodeToProductionsID[TopologicalSort[ii]].push_back(enc);\n\t\t      \t\t// scorro i figli e creo etichetta tramite funzione di hash\n\t\t      \t\t// depth > 0; the length of the children ID list\n\t\t      \t\t//imposta valore feature a 1 (TODO lambda)\n\t\t      \t\t//\t\t\t\t\t\t\tlevel(o-mRadius)\n\t\t\t    \tint frequency = 0;\n\t\t\t    \tif(max_child_heigth==0){\n\t\t      \t\t//leaf node\n\t\t\t    \tfrequency=  maxLevel - oSrcDestMaptoDistance[make_pair(i,TopologicalSort[ii])];\n\t\t\t    \t}\n\t\t\t    \tSVector z;\n\t\t      \t\tz.set(enc, (double)(frequency+1.0) * sqrt(mTreeLambda));\n\t\t\t    //\tcout<<\"Feature: \"<<aG.GetVertexLabelConcatenated(TopologicalSort[ii])<<\" freq:\"<<(double)(frequency+1.0) * sqrt(mTreeLambda)<<\" code: \"<<enc<<endl;\n\t\t\t    \tx->add(z);\n\t\t\t    \tfeatures_grouped_by_depth[depth].add(z);\n\t\t\t    \tMapNodetoFrequencies[TopologicalSort[ii]].push_back(frequency);\n\t\t      \t\tMapProductionIDtoSize[enc]= 1; //sqrt(mTreeLambda);\n\t\t      \t\t\t}\n\t\t      \t\t\telse{\n\t\t      \t//\t\t\tcout<<\"depth=\"<<depth<<endl;\n\n\t\t      \t\t\tint size = 0;\n\t\t      \t\tstring encoding;\n\t\t      \t\tencoding = aG.GetVertexLabelConcatenated(TopologicalSort[ii]);\n\t\t\t    \tvector<unsigned> vertex_adjacency_list = MapNodetoChildren[TopologicalSort[ii]];\n\t\t    \t\tvector<unsigned>  vertex_label_id_list;\n\t\t    \t\tint min_freq_children =INT_MAX;\n\t\t\t    \tfor (unsigned j = 0; j < vertex_adjacency_list.size(); ++j) {\n\n\t\t\t    \t\tunsigned child_vertex_id = vertex_adjacency_list[j];\n\t\t\t    \t\tint size_map =  MapNodeToProductionsID[child_vertex_id].size();//min (depth-1) e dim\n\t\t\t    \t\tunsigned child_hash = MapNodeToProductionsID[child_vertex_id][min(size_map,depth)-1];// id hash del figlio;\n\t\t\t    \t\tint freq_child = MapNodetoFrequencies[child_vertex_id][min(size_map,depth)-1];\n\t\t\t    \t\tif (freq_child < min_freq_children){\n\t\t\t    \t\t\tmin_freq_children = freq_child;\n\t\t\t    \t\t}\n\t\t\t    \t\tvertex_label_id_list.push_back(child_hash);\n\t\t\t    \t\tsize += MapProductionIDtoSize[child_hash];\n\t\t\t    \t}\n\n\t\t\t    \t// vertex_label_id_list contiene gli hash delle prod dei figli. Va ordinato e usato x generare l hash attuale\n\t\t\t    \tsort(vertex_label_id_list.begin(), vertex_label_id_list.end());\n\n\t\t\t    \tif (vertex_label_id_list.size() > 0){\n\t\t\t    \t\tstd::stringstream ss;\n\t\t\t    \t\tss <<\":\"<<vertex_label_id_list[0];\n\t\t\t    \t\tencoding += ss.str() ;\n\t\t\t    \t}//originale senza .\n\t\t\t    \tfor (unsigned i = 1; i < vertex_label_id_list.size(); i++){\n\t\t\t    \t\tstd::stringstream ss;\n\t\t\t    \t\tss << vertex_label_id_list[i];\n\t\t\t    \t\tencoding += \".\" + ss.str() ;\n\t\t\t    \t}\n\t\t\t    //DEBUG\tcout<<\"encoding \"<<encoding<<endl;\n\t\t\t    \t//calculate frequency\n\n\t\t\t    \thash_subgraph_code = HashFunc(encoding);\n\t\t\t    \tMapNodeToProductionsID[TopologicalSort[ii]].push_back(hash_subgraph_code);\n\t\t\t    \tsize += 1; // current node\n\t\t\t    \tMapProductionIDtoSize[hash_subgraph_code]= size;\n\t\t\t    \tint frequency = min_freq_children;\n\t\t\t    \tMapNodetoFrequencies[TopologicalSort[ii]].push_back(frequency);\n\n\t\t\t    \tSVector z;\n\t\t\t   // \tcout<<\"Feature: \"<<encoding<<\" freq:\"<<(double)(frequency+1.0) * sqrt(pow(mTreeLambda,size))<<\" code: \"<<hash_subgraph_code<<endl;\n\t\t\t    \tz.set(hash_subgraph_code,(double)(frequency+1.0) * sqrt(pow(mTreeLambda,size)));\n\t\t\t    \tx->add(z);\n\t\t\t    \tfeatures_grouped_by_depth[depth].add(z);\n\t\t\t    //\tcout<<\"weight \"<<sqrt(pow(mTreeLambda,size))<<endl;\n\n\t\t      \t\t\t}\n\n\t\t      \t\t}\n\t\t      \t}\n\n\n\n\t\t    return *x;\n\n\t }\n\n\nSVector&   NSDDkernel_FeatureGenerator::generate_vertex_feature_vector_DIVIDED_DISTANCE(unsigned i, const GraphClass& aG , int dag_h, vector<vector<SVector> > & features_grouped_by_depth){\n\t//cout<<\"start generation of feature vector..\"<<endl;\n\t\t\tSVector* x = new SVector();\n\t\t\tfeatures_grouped_by_depth= vector<vector<SVector> >(dag_h+1);\n\n\n\t\t//\tcout<<\"n of nodes \"<<aG.VertexSize()<<endl;\n\t\t    assert(i< aG.VertexSize());\n\t\t    \tmap<pair<unsigned, unsigned>, int> oSrcDestMaptoDistance;\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodetoParents;\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodetoChildren;\n\n\t\t    \tvector<unsigned> TopologicalSort;\n\t\t    \tint maxLevel = 0;\n\t\t    \t//aG. // codice calcolo features here\n\t\t      \taG.SingleVertexBoundedBreadthFirstVisitTree(i,dag_h, oSrcDestMaptoDistance,  MapNodetoParents,MapNodetoChildren, TopologicalSort, maxLevel);\n\t\t//    cout<<\"MaxLevel: \"<<maxLevel<<endl;\n\t\t\t\tfor(int t=0; t<maxLevel+1;t++){\n\t\t\t\t\tfeatures_grouped_by_depth[t] =(vector<SVector>(dag_h+1));\n\n\t\t\t\t}\n\n\t\t      \t// \tcout<<\"Breadth first visit ended..\"<<endl;\n\t\t      \t// I have the DAG for the vertex i. Need topological sort.\n\t\t      \t//map every node to him productions\n\t\t    \tmap<unsigned, vector<unsigned> > MapNodeToProductionsID;\n\t\t    \tmap<unsigned, vector<int> > MapNodetoFrequencies;\n\n\t\t    \tmap<unsigned, int > MapProductionIDtoSize;\n\n\t\t  //  \tcout<<\"topological sort size \"<<TopologicalSort.size()<<endl;\n\n\t\t      \t//maybe I meed the maximum depth (distance)\n\t\t      \tfor (int ii=TopologicalSort.size()-1; ii>=0; ii--){\n\t\t      \t\t// cout<<ii<<endl;\n\t\t      \t\t//calculate child size\n\t\t\t    \tvector<unsigned> vertex_adjacency_list = MapNodetoChildren[TopologicalSort[ii]];\n\t\t      \t\tint max_child_heigth=0;\n\t\t        \tfor (unsigned j = 0; j < vertex_adjacency_list.size(); ++j) {\n\t\t    \t\t\tint child_vertex_id= vertex_adjacency_list[j];\n\t\t    \t\t\tint child_heigth=MapNodeToProductionsID[child_vertex_id].size();\n\t\t    \t\t\tif(child_heigth > max_child_heigth){\n\t\t    \t\t\t\tmax_child_heigth = child_heigth;\n\t\t    \t\t\t}\n\t\t        \t}\n\n\t\t      \t\tfor (int depth=0; depth<= max_child_heigth; ++depth){ //era maxLevel\n\t\t      \t\t\tunsigned hash_subgraph_code = 1;\n\t\t      \t\t//depth 0; only label\n\t\t      \t\t\tif(depth==0){\n\t\t      \t\t//\t\tcout<<\"depth=0\"<<endl;\n\t\t      \t\t\t\tunsigned enc= Radius0RootedGraphCanonicalFormEncoding(TopologicalSort[ii], aG);\n\t\t      \t\tMapNodeToProductionsID[TopologicalSort[ii]].push_back(enc);\n\t\t      \t\t// scorro i figli e creo etichetta tramite funzione di hash\n\t\t      \t\t// depth > 0; the length of the children ID list\n\t\t      \t\t//imposta valore feature a 1 (TODO lambda)\n\t\t      \t\t//\t\t\t\t\t\t\tlevel(o-mRadius)\n\t\t\t    \tint frequency = 0;\n\t\t\t    \tif(max_child_heigth==0){\n\t\t      \t\t//leaf node\n\t\t\t    \tfrequency=  maxLevel - oSrcDestMaptoDistance[make_pair(i,TopologicalSort[ii])];\n\t\t\t    \t}\n\t\t\t    \tSVector z;\n\t\t      \t\tz.set(enc, (double)(frequency+1.0) * sqrt(mTreeLambda));\n\t\t\t    //\tcout<<\"Feature: \"<<aG.GetVertexLabelConcatenated(TopologicalSort[ii])<<\" freq:\"<<(double)(frequency+1.0) * sqrt(mTreeLambda)<<\" code: \"<<enc<<endl;\n\t\t\t    \tx->add(z);\n\t\t\t    \tfeatures_grouped_by_depth[depth][oSrcDestMaptoDistance[make_pair(i,TopologicalSort[ii])]].add(z);\n\t\t\t    \tMapNodetoFrequencies[TopologicalSort[ii]].push_back(frequency);\n\t\t      \t\tMapProductionIDtoSize[enc]= 1; //sqrt(mTreeLambda);\n\t\t      \t\t\t}\n\t\t      \t\t\telse{\n\t\t      \t//\t\t\tcout<<\"depth=\"<<depth<<endl;\n\n\t\t      \t\t\tint size = 0;\n\t\t      \t\tstring encoding;\n\t\t      \t\tencoding = aG.GetVertexLabelConcatenated(TopologicalSort[ii]);\n\t\t\t    \tvector<unsigned> vertex_adjacency_list = MapNodetoChildren[TopologicalSort[ii]];\n\t\t    \t\tvector<unsigned>  vertex_label_id_list;\n\t\t    \t\tint min_freq_children =INT_MAX;\n\t\t\t    \tfor (unsigned j = 0; j < vertex_adjacency_list.size(); ++j) {\n\n\t\t\t    \t\tunsigned child_vertex_id = vertex_adjacency_list[j];\n\t\t\t    \t\tint size_map =  MapNodeToProductionsID[child_vertex_id].size();//min (depth-1) e dim\n\t\t\t    \t\tunsigned child_hash = MapNodeToProductionsID[child_vertex_id][min(size_map,depth)-1];// id hash del figlio;\n\t\t\t    \t\tint freq_child = MapNodetoFrequencies[child_vertex_id][min(size_map,depth)-1];\n\t\t\t    \t\tif (freq_child < min_freq_children){\n\t\t\t    \t\t\tmin_freq_children = freq_child;\n\t\t\t    \t\t}\n\t\t\t    \t\tvertex_label_id_list.push_back(child_hash);\n\t\t\t    \t\tsize += MapProductionIDtoSize[child_hash];\n\t\t\t    \t}\n\n\t\t\t    \t// vertex_label_id_list contiene gli hash delle prod dei figli. Va ordinato e usato x generare l hash attuale\n\t\t\t    \tsort(vertex_label_id_list.begin(), vertex_label_id_list.end());\n\n\t\t\t    \tif (vertex_label_id_list.size() > 0){\n\t\t\t    \t\tstd::stringstream ss;\n\t\t\t    \t\tss <<\":\"<<vertex_label_id_list[0];\n\t\t\t    \t\tencoding += ss.str() ;\n\t\t\t    \t}//originale senza .\n\t\t\t    \tfor (unsigned id = 1; id < vertex_label_id_list.size(); id++){\n\t\t\t    \t\tstd::stringstream ss;\n\t\t\t    \t\tss << vertex_label_id_list[id];\n\t\t\t    \t\tencoding += \".\" + ss.str() ;\n\t\t\t    \t}\n\t\t\t    //DEBUG\tcout<<\"encoding \"<<encoding<<endl;\n\t\t\t    \t//calculate frequency\n\n\t\t\t    \thash_subgraph_code = HashFunc(encoding);\n\t\t\t    \tMapNodeToProductionsID[TopologicalSort[ii]].push_back(hash_subgraph_code);\n\t\t\t    \tsize += 1; // current node\n\t\t\t    \tMapProductionIDtoSize[hash_subgraph_code]= size;\n\t\t\t    \tint frequency = min_freq_children;\n\t\t\t    \tMapNodetoFrequencies[TopologicalSort[ii]].push_back(frequency);\n\n\t\t\t    \tSVector z;\n\t\t\t   // \tcout<<\"Feature: \"<<encoding<<\" freq:\"<<(double)(frequency+1.0) * sqrt(pow(mTreeLambda,size))<<\" code: \"<<hash_subgraph_code<<endl;\n\t\t\t    \tz.set(hash_subgraph_code,(double)(frequency+1.0) * sqrt(pow(mTreeLambda,size)));\n\t\t\t    \tx->add(z);\n\t\t\t    \tfeatures_grouped_by_depth[depth][oSrcDestMaptoDistance[make_pair(i,TopologicalSort[ii])]].add(z); //TODO distance from root\n\t\t\t    //\tcout<<\"weight \"<<sqrt(pow(mTreeLambda,size))<<endl;\n\n\t\t      \t\t\t}\n\n\t\t      \t\t}\n\t\t      \t}\n\n\n\n\t\t    return *x;\n\n\t }\n\n//Kernel su dati con astrazione (nodi di relazione)\nANSDDkernel_FeatureGenerator::ANSDDkernel_FeatureGenerator(const std::string& id) :\n\t\tNSDDkernel_FeatureGenerator(id) {\n\t\t//new_flag(&mTreeLambda, \"mTreeLambda\", \"(double)\\n tree_lambda parameter for DDK kernel\");\n}\n\n\nvoid ANSDDkernel_FeatureGenerator::generate_feature_vector(const GraphClass& aG, SVector& x, const vector<unsigned>& aFirstEndpointList) {\n\t//cout<<\"generate_vertex_feature_vector.... OK for abstract\"<<endl;\n\tvector<unsigned> first_endpoint_list = aFirstEndpointList;\n\tGetFirstEndpoints(aG, first_endpoint_list);\n\tif (first_endpoint_list.size() == 0)\n\t\tthrow std::logic_error(\"ERROR6: Something went wrong: cannot generate features over an empty set of first endpoints!\");\n\tint horizon = max(mDistance, mRadius);\n\taG.ComputePairwiseDistanceInformation(horizon, first_endpoint_list);\n\tif (aG.Check() == false)\n\t\tthrow logic_error(\"ERROR11: the graph data structure is not sound and it has not passed the checkup procedure\"); //check graph data structure soundness\n\n\tInitFeatureCache(aG, mRadiusTwo);\n\tfor (unsigned i = 0; i < first_endpoint_list.size(); i++) {\n\t\tSVector z;\n\t\tunsigned src_id = first_endpoint_list[i];\n\t\t//InitFeatureCache(aG, mRadiusTwo);\n\n\t\tif (aG.GetVertexViewPoint(src_id) && aG.GetVertexKernelPoint(src_id) && aG.GetVertexAlive(src_id)) { //proceed to extract features only if the *src* vertex is a kernel point and is alive\n\t\t\t//for (unsigned r = 0; r <= mRadius; r++) {\n\t\t\t//\tfor (unsigned d = 0; d <= mDistance; d++) {\n\t\t\t\t//\tGenerateVertexFeatures(src_id, aG, r, d, z);\n\t\t\tGenerateVertexFeatures(src_id, aG, mRadius, mDistance, z);\n\t\t\t\t//}\n\t\t\t//}\n\t\t} else if (aG.GetVertexAbstraction(src_id) && aG.GetVertexAlive(src_id)) {\n\t\t\t//for (unsigned r = 0; r <= mRadius; r++) {\n\t\t\t//\tfor (unsigned d = 0; d <= mDistance; d++) {\n\t\t\t\t//\tGenerateAbstractVertexFeatures(src_id, aG, r, d, z);\n\t\t\tGenerateAbstractVertexFeatures(src_id, aG, mRadius, mDistance, z);\n\n\t\t\t//\t}\n\t\t\t//}\n\t\t}\n\t\tif (mMinKernel)\n\t\t\tConvertSparseVectorToMinFeatureVector(z);\n\t\t//x_list.push_back(z);\n\t\tx.add(z);\n\t}\n\tif (mDebugVerbosity > 0) {\n\n\t\tOutputFeatureMap(cout);\n\t\taG.Output(cout);\n\t}\n}\nvoid ANSDDkernel_FeatureGenerator::GenerateVertexFeatures(unsigned aRootVertexIndex, const GraphClass& aG, unsigned aRadius, unsigned aDistance, SVector& x) {\n\tx= generateVertexFeatures_DISTANCE(aRootVertexIndex, aG ,aRadius);\n}\n\nSVector&   ANSDDkernel_FeatureGenerator::generateVertexFeatures_DISTANCE(unsigned i, const GraphClass& aG , int dag_h){\n   // test rNSPDK 1/2 d=1/2\n\tGraphClass ag2 = aG;\n\tSVector* out = new SVector();\n//\tcout<<\"Generate feature vector core\"<<endl;\n\t//\tcout<<\"i:\"<<i<<endl;\n\n\t\t//SVector DD= generate_vertex_feature_vector(i,ag2 ,dag_h);\n\t\tvector< vector< SVector> > features; //(dag_h+1);\n\t\tSVector DD= generate_vertex_feature_vector_DIVIDED_DISTANCE(i,ag2 ,dag_h,features);\n\t\t//cout<<features.size();\n\t//\tout->add(DD);\n\t\t//NSPDK\n\t//\tcout<<\"start generation of NSPKD feature vector.. mDistance\"<<mDistance<<endl;\n\n\t\t//NSPDK_FeatureGenerator::GenerateVertexFeatures(i,aG,NSPDK);\n\t//\tNSPDK_FeatureGenerator::generate_feature_vector(aG,NSPDK);\n\t\tvector<unsigned> first_endpoint_list= vector<unsigned>();\n\t\tfirst_endpoint_list.push_back(i);\n\t\t\t//GetFirstEndpoints(aG, first_endpoint_list);\n\n\t\tint horizon=max(mDistance, mRadiusTwo); //   max(mDistance, mRadius);\n\t\t\taG.ComputePairwiseDistanceInformation(horizon, first_endpoint_list);\n\t\t\tif (aG.Check() == false)\n\t\t\t\tthrow logic_error(\"ERROR10: the graph data structure is not sound and it has not passed the checkup procedure\"); //check graph data structure soundness\n\n\t\t\tInitFeatureCache(aG, mRadiusTwo );\n\t\t\tfor (unsigned r = 0; r <= mRadius ; r++) { //max(1.0,mRadius / 2.0)\n\t\t\t\tfor (unsigned d = 0; d <= mDistance; d++) { // era 0\n\t\t\t\t\tfor (unsigned r2 = 0; r2 <= mRadiusTwo ; r2++) {\n\t\t\t\t\tSVector z;\n\t\t\t\t\tfor (unsigned i = 0; i < first_endpoint_list.size(); i++) {\n\t\t\t\t\t\tunsigned src_id = first_endpoint_list[i];\n\t\t\t\t\t\tif (aG.GetVertexViewPoint(src_id) && aG.GetVertexKernelPoint(src_id) && aG.GetVertexAlive(src_id)) { //proceed to extract features only if the *src* vertex is a kernel point and is alive\n\t\t\t\t\t\t\tSVector zv;\n\n\t\t\t\t\t\t\tvector<unsigned> endpoint_list(5);\n\t\t\t\t\t\t\tendpoint_list[0] = r2;\n\t\t\t\t\t\t\tendpoint_list[1] = d;\n\n\t\t\t\t\t\t//\tunsigned src_code = GenerateVertexNeighbourhoodHashCode(aSrcID, aG, aRadius);\n\t\t\t\t//\tTODO\tfor(unsigned src_code in DD)\n\n\t\t\t\t\t\t\tvector<unsigned> dest_id_list = aG.GetFixedDistanceVertexIDList(i, d);\n\t\t\t\t\t\t\tfor (unsigned dest_j = 0; dest_j < dest_id_list.size(); dest_j++) {\n\t\t\t\t\t\t\t\tunsigned dest_id = dest_id_list[dest_j];\n\t\t\t\t\t\t\t\tunsigned dest_code = 0;\n\t\t\t\t\t\t\t\tif (aG.GetVertexKernelPoint(dest_id) && aG.GetVertexAlive(dest_id)) { //proceed to extract features only if the *dest* vertex is a kernel point and is alive\n\t\t\t\t\t\t\t\t\tdest_code = GenerateVertexNeighbourhoodHashCode(dest_id, aG, r2); //\n\t\t\t\t\t\t\t\t\t// first is the DDK feature, second NSPDK feature\n\t\t\t\t\t\t//  for(const SVector::Pair *p = DD; p->i>=0; p++) {\n\t\t\t\t\t\t\t\t\tfor(int distance=0; distance<features[r].size(); distance++){\n\t\t\t\t\t\t\t\t\t\tendpoint_list[4]=distance; //from root in DD\n\t\t\t\t\t\t for(const SVector::Pair *p = features[r][distance]; p->i>=0; p++) {\n\n\t\t\t\t\t\t\t\t\tendpoint_list[2] = p->i;\n\t\t\t\t\t\t\t\t\t\t//TODO scorrere le feature di DD\n\t\t\t\t\t\t\t\t\t\tendpoint_list[3] = dest_code;\n\t\t\t\t\t\t\t\t\t\t//TEST output\n\t\t\t\t\t\t\t\t//\t\tcout<<\"R \"<<endpoint_list[0]<<\" d \"<<endpoint_list[1]<<\" DD \"<<endpoint_list[2]<<\" NSPDK \"<<endpoint_list[3]<<\" dRoot \"<<endpoint_list[4]<<endl;\n\t\t\t\t\t\t\t\t\tunsigned code = HashFunc(endpoint_list, mHashBitMask);\n\n\t\t\t\t\t\t\t\t\tSVector z;\n\t\t\t\t\t\t\t\t\tz.set(code, p->v);\n\t\t\t\t\t\t\t\t\tzv.add(z);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\t\tz.add(zv);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\tif (mNormalization)\n\t\t\t\t\t\tz.normalize();\n\t\t\t\tout->add(z);\n\t\t\t\t} //d\n\t\t\t} //r\n\t\t\t} //r2\n\n\n\n\n\n\n\n\t//\tcout<<\"features size DD:\"<<DD.sparse_size()<<\" out:\"<<out->sparse_size()<<endl;\n\t\tfeatures.clear();\n\n\n\treturn *out;\n}\n\nvoid ANSDDkernel_FeatureGenerator::GenerateAbstractVertexFeatures(unsigned aSrcID, const GraphClass& aG, unsigned aRadius, unsigned aDistance, SVector& x) {\n\t//cout<<\"ABSTRACT FEATURES\"<<endl;\n\tvector<unsigned> endpoint_list(5);\n\tfor (unsigned r = 0; r <= mRadius ; r++) { //max(1.0,mRadius / 2.0)\n\t\t\t\t\tfor (unsigned d = 0; d <= mDistance; d++) { // era 0\n\t\t\t\t\t\tfor (unsigned r2 = 0; r2 <= mRadiusTwo ; r2++) { //max(1.0,mRadius / 2.0)\n\n\n\tendpoint_list[0] = r;\n\tendpoint_list[1] = d;\n\n\t//ensure that the src vertex is of the abstraction type\n\tif (aG.GetVertexAbstraction(aSrcID) == false)\n\t\tthrow std::logic_error(\"ERROR2: Something went wrong: expecting an abstraction vertex, but abstraction test fails.\");\n\t//extract all adjacent vertices and partition them into part_of (lower level) and abstraction_of (upper level)\n\tvector<unsigned> part_of_list;\n\tvector<unsigned> abstraction_of_list;\n\n\tvector<unsigned> vertex_adjacency_list = aG.GetVertexAdjacentList(aSrcID);\n\tvector<unsigned> edge_adjacency_list = aG.GetEdgeAdjacentList(aSrcID);\n\tif (vertex_adjacency_list.size() != edge_adjacency_list.size())\n\t\tthrow std::logic_error(\"ERROR3: Something went wrong: expecting vertex adjacency list to be the same size as the edge adjacency list.\");\n\tif (vertex_adjacency_list.size() == 0)\n\t\tthrow std::logic_error(\"ERROR3b: Something went wrong: expecting a non empty vertex adjacency list for each abstract vertex.\");\n\tfor (unsigned i = 0; i < vertex_adjacency_list.size(); ++i) {\n\t\tunsigned child_vertex_id = vertex_adjacency_list[i];\n\t\tunsigned child_edge_id = edge_adjacency_list[i];\n\t\tif (aG.GetEdgePartOf(child_edge_id))\n\t\t\tpart_of_list.push_back(child_vertex_id);\n\t\tif (aG.GetEdgeAbstractionOf(child_edge_id))\n\t\t\tabstraction_of_list.push_back(child_vertex_id);\n\t}\n\t//----------------------------\n\n\t//----------------------------------------\n\t\t\t\t\t\t//starting from each upper level vertex find all vertices at distance aDistance\n\tif (abstraction_of_list.size() == 0)\n\t\tthrow std::logic_error(\"ERROR5: Something went wrong: expecting a non empty abstraction_of list.\");\n\tset<unsigned> abstraction_of_set;\n\tfor (unsigned i = 0; i < abstraction_of_list.size(); ++i) {\n\t\tunsigned v = abstraction_of_list[i];\n\t\tvector<unsigned> dest_id_list = aG.GetFixedDistanceVertexIDList(v, d);\n\t\t//-----------?????????????????????????????\n\t//\tabstraction_of_set.insert(abstraction_of_list.begin(), abstraction_of_list.end());\n\t\tabstraction_of_set.insert(dest_id_list.begin(), dest_id_list.end());\n\n\t}\n\t//starting from each lower level vertex find all vertices at distance aDistance\n\tif (part_of_list.size() == 0)\n\t\tthrow std::logic_error(\"ERROR4: Something went wrong: expecting a non empty part_of list.\");\n\tset<unsigned> part_of_set;\n\tfor (unsigned i = 0; i < part_of_list.size(); ++i) {\n\t\tunsigned v = part_of_list[i];\n\t\tvector<unsigned> dest_id_list = aG.GetFixedDistanceVertexIDList(v, d);\n\t\t//-----------?????????????????????????????\n\t\tpart_of_set.insert(dest_id_list.begin(), dest_id_list.end());\n\t}\n\t//make all possible pairs of distant lower level vertices with distant upper level vertices\n\tfor (set<unsigned>::iterator it = part_of_set.begin(); it != part_of_set.end(); ++it) {\n\t\tunsigned part_of_id = *it;\n\n\t\t//TODO modifica con mio kernel\n\t\tvector< vector< SVector> > features; //(dag_h+1);\n\t\tSVector DD= generate_vertex_feature_vector_DIVIDED_DISTANCE(part_of_id, aG ,aRadius,features);\n\t\t//SVector DD= generate_vertex_feature_vector_DIVIDED(part_of_id, aG ,aRadius,features);\n\n\t\t//For every feature in DD, by height and distance from the root\n\t\tfor(int distance=0; distance<features[r].size(); distance++){\n\t\t\tendpoint_list[4]=distance; //from root in DD\n\t\t\tfor(const SVector::Pair *p = features[r][distance]; p->i>=0; p++) {\n\n\t\t\tendpoint_list[2] = p->i;\n\t\t\t//TODO scorrere le feature di DD\n\t\t\t\t//TEST output\n\t\t\t//\t\tcout<<\"R \"<<endpoint_list[0]<<\" d \"<<endpoint_list[1]<<\" DD \"<<endpoint_list[2]<<\" NSPDK \"<<endpoint_list[3]<<\" dRoot \"<<endpoint_list[4]<<endl;\n\n\t\t\t//\n\t\tfor (set<unsigned>::iterator jt = abstraction_of_set.begin(); jt != abstraction_of_set.end(); ++jt) {\n\t\t\tunsigned abstraction_of_id = *jt;\n\t\t\t//build features with one neighborhood graph signature from the lower level and one from the upper\n\t\t\tunsigned abstraction_of_code = GenerateVertexNeighbourhoodHashCode(abstraction_of_id, aG, r2);\n\t\t\tendpoint_list[3] = abstraction_of_code;\n\t\t\tunsigned code = HashFunc(endpoint_list, mHashBitMask);\n\t\t\tif (mDebugVerbosity > 0)\n\t\t\t\tmDebugInfo.StoreFeatureCodeToFeatureInfo(code, endpoint_list);\n\t\t\tSVector z;\n\t\t\tz.set(code, 1);\n\t\t\tx.add(z);\n\t\t}\n\t}\n\t\t}\n\t}\n\n\n\t//i have to repeat for both sides for ddk\n\t//make all possible pairs of distant lower level vertices with distant upper level vertices\n\tfor (set<unsigned>::iterator it = part_of_set.begin(); it != part_of_set.end(); ++it) {\n\t\tunsigned part_of_id = *it;\n\n\t\t//TODO modifica con mio kernel\n\t\tvector< vector< SVector> > features; //(dag_h+1);\n\t\tSVector DD= generate_vertex_feature_vector_DIVIDED_DISTANCE(part_of_id, aG ,aRadius,features);\n\n\t\t\t//For every feature in DD, by height and distance from the root\n\t\t\tfor(int distance=0; distance<features[r].size(); distance++){\n\t\t\t\tendpoint_list[4]=distance; //from root in DD\n\t\t\t\tfor(const SVector::Pair *p = features[r][distance]; p->i>=0; p++) {\n\n\t\t\t\tendpoint_list[2] = p->i;\n\n\t\tunsigned part_of_code = GenerateVertexNeighbourhoodHashCode(part_of_id, aG, aRadius);\n\t\tendpoint_list[2] = part_of_code;\n\t\tfor (set<unsigned>::iterator jt = abstraction_of_set.begin(); jt != abstraction_of_set.end(); ++jt) {\n\t\t\tunsigned abstraction_of_id = *jt;\n\t\t\t//build features with one neighborhood graph signature from the lower level and one from the upper\n\t\t\tunsigned abstraction_of_code = GenerateVertexNeighbourhoodHashCode(abstraction_of_id, aG, aRadius);\n\t\t\tendpoint_list[3] = abstraction_of_code;\n\t\t\tunsigned code = HashFunc(endpoint_list, mHashBitMask);\n\t\t\tif (mDebugVerbosity > 0)\n\t\t\t\tmDebugInfo.StoreFeatureCodeToFeatureInfo(code, endpoint_list);\n\t\t\tSVector z;\n\t\t\tz.set(code, 1);\n\t\t\tx.add(z);\n\t\t}\n\t}\n\t}\n\n}\n\t\t\t\t\t}\n\t}\n}\n}\n\n\n\n", "meta": {"hexsha": "ea9e17a5eef4372693e35ab59995555f40702884", "size": 47847, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EDeN/DDK_FeatureGenerator.cpp", "max_stars_repo_name": "asangphukieo/GraphProt", "max_stars_repo_head_hexsha": "1ce3db40e30ebd9442203dbf8c05aa0e72ffe170", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-09-27T16:05:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T09:07:16.000Z", "max_issues_repo_path": "EDeN/DDK_FeatureGenerator.cpp", "max_issues_repo_name": "asangphukieo/GraphProt", "max_issues_repo_head_hexsha": "1ce3db40e30ebd9442203dbf8c05aa0e72ffe170", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-11-22T15:52:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T07:50:58.000Z", "max_forks_repo_path": "EDeN/DDK_FeatureGenerator.cpp", "max_forks_repo_name": "asangphukieo/GraphProt", "max_forks_repo_head_hexsha": "1ce3db40e30ebd9442203dbf8c05aa0e72ffe170", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T10:09:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-15T20:52:43.000Z", "avg_line_length": 38.8053527981, "max_line_length": 192, "alphanum_fraction": 0.6560076912, "num_tokens": 12859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.2291657286788779}}
{"text": "// Copyright (c) 2018 yshurik\n//\n// Distributed under the MIT/X11 software license, see the accompanying\n// file COPYING or http://www.opensource.org/licenses/mit-license.php.\n//\n// The use in another cyptocurrency project the code is licensed under\n// Jelurida Public License (JPL). See https://www.jelurida.com/resources/jpl\n\n#include \"pegdata.h\"\n\n#include <map>\n#include <set>\n#include <cstdint>\n#include <utility>\n#include <algorithm>\n#include <type_traits>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\n#include \"util.h\"\n\n#include <zconf.h>\n#include <zlib.h>\n\nusing namespace std;\nusing namespace boost;\n\nCFractions::CFractions()\n    :nFlags(VALUE)\n    ,f(new int64_t[PEG_SIZE])\n{\n    f[0] = 0; // fast init first item\n}\nCFractions::CFractions(int64_t value, uint32_t flags)\n    :nFlags(flags)\n    ,f(new int64_t[PEG_SIZE])\n{\n    if (flags & VALUE)\n        f[0] = value; // fast init first item\n    else if (flags & STD) {\n        f[0] = value;\n        nFlags = VALUE;\n        ToStd();\n        nFlags = flags;\n    }\n    else {\n        assert(0);\n    }\n}\nCFractions::CFractions(const CFractions & o)\n    :nFlags(o.nFlags)\n    ,nLockTime(o.nLockTime)\n    ,sReturnAddr(o.sReturnAddr)\n    ,f(new int64_t[PEG_SIZE])\n{\n    for(int i=0; i< PEG_SIZE; i++) {\n        f[i] = o.f[i];\n    }\n}\n\nCFractions& CFractions::operator=(const CFractions& o)\n{\n    nFlags = o.nFlags;\n    nLockTime = o.nLockTime;\n    sReturnAddr = o.sReturnAddr;\n    for(int i=0; i< PEG_SIZE; i++) {\n        f[i] = o.f[i];\n    }\n    return *this;\n}\n\nvoid CFractions::ToDeltas(int64_t* deltas) const\n{\n    int64_t fp = 0;\n    for(int i=0; i<PEG_SIZE; i++) {\n        if (i==0) {\n            fp = deltas[0] = f[0];\n            continue;\n        }\n        deltas[i] = f[i]-fp*(PEG_RATE-1)/PEG_RATE;\n        fp = f[i];\n    }\n}\n\nvoid CFractions::FromDeltas(const int64_t* deltas)\n{\n    int64_t fp = 0;\n    for(int i=0; i<PEG_SIZE; i++) {\n        if (i==0) {\n            fp = f[0] = deltas[0];\n            continue;\n        }\n        f[i] = deltas[i]+fp*(PEG_RATE-1)/PEG_RATE;\n        fp = f[i];\n    }\n}\n\nbool CFractions::Pack(CDataStream& out, unsigned long* report_len, bool compress) const\n{\n    if (nFlags & VALUE) {\n        if (report_len) *report_len = sizeof(int64_t);\n        out << nVersion;\n        out << uint32_t(nFlags | SER_VALUE);\n        out << nLockTime;\n        out << sReturnAddr;\n        out << f[0];\n    } else if (compress) {\n        int64_t deltas[PEG_SIZE];\n        ToDeltas(deltas);\n\n        int zlevel = 9;\n        unsigned char zout[2*PEG_SIZE*sizeof(int64_t)];\n        unsigned long n = PEG_SIZE*sizeof(int64_t);\n        unsigned long zlen = PEG_SIZE*2*sizeof(int64_t);\n        auto src = reinterpret_cast<const unsigned char *>(deltas);\n        int res = ::compress2(zout, &zlen, src, n, zlevel);\n        if (res == Z_OK) {\n            if (report_len) *report_len = zlen;\n            out << nVersion;\n            out << uint32_t(nFlags | SER_ZDELTA);\n            out << nLockTime;\n            out << sReturnAddr;\n            auto ser = reinterpret_cast<const char *>(zout);\n            out << zlen;\n            out.write(ser, zlen);\n        }\n        else {\n            if (report_len) *report_len = PEG_SIZE*sizeof(int64_t);\n            out << nVersion;\n            out << uint32_t(nFlags | SER_RAW);\n            out << nLockTime;\n            out << sReturnAddr;\n            auto ser = reinterpret_cast<const char *>(f.get());\n            out.write(ser, PEG_SIZE*sizeof(int64_t));\n        }\n    } else {\n        if (report_len) *report_len = PEG_SIZE*sizeof(int64_t);\n        out << nVersion;\n        out << uint32_t(nFlags | SER_RAW);\n        out << nLockTime;\n        out << sReturnAddr;\n        auto ser = reinterpret_cast<const char *>(f.get());\n        out.write(ser, PEG_SIZE*sizeof(int64_t));\n    }\n    return true;\n}\n\nbool CFractions::Unpack(CDataStream& inp)\n{\n    uint32_t nSerFlags = 0;\n    inp >> nVersion;\n    inp >> nSerFlags;\n    inp >> nLockTime;\n    inp >> sReturnAddr;\n\n    if (nSerFlags & SER_VALUE) {\n        nFlags = nSerFlags | VALUE;\n        inp >> f[0];\n    }\n    else if (nSerFlags & SER_ZDELTA) {\n        unsigned long zlen = 0;\n        inp >> zlen;\n\n        if (zlen>(2*PEG_SIZE*sizeof(int64_t))) {\n            // data are broken, no read\n            return false;\n        }\n\n        unsigned char zinp[2*PEG_SIZE*sizeof(int64_t)];\n        unsigned long n = PEG_SIZE*sizeof(int64_t);\n        auto ser = reinterpret_cast<char *>(zinp);\n        inp.read(ser, zlen);\n\n        int64_t deltas[PEG_SIZE];\n        auto src = reinterpret_cast<const unsigned char *>(ser);\n        auto dst = reinterpret_cast<unsigned char *>(deltas);\n        int res = ::uncompress(dst, &n, src, zlen);\n        if (res != Z_OK) {\n            // data are broken, can not uncompress\n            return false;\n        }\n        FromDeltas(deltas);\n        nFlags = nSerFlags | STD;\n    }\n    else if (nSerFlags & SER_RAW) {\n        auto ser = reinterpret_cast<char *>(f.get());\n        inp.read(ser, PEG_SIZE*sizeof(int64_t));\n        nFlags = nSerFlags | STD;\n    }\n    nFlags &= SER_MASK;\n\n    return true;\n}\n\nCFractions CFractions::Std() const\n{\n    if ((nFlags & VALUE) ==0)\n        return *this;\n\n    CFractions fstd;\n    fstd.sReturnAddr = sReturnAddr;\n    fstd.nLockTime = nLockTime;\n    fstd.nFlags = nFlags;\n    fstd.nFlags &= ~uint32_t(VALUE);\n    fstd.nFlags |= STD;\n\n    int64_t v = f[0];\n    for(int i=0;i<PEG_SIZE;i++) {\n        if (i == PEG_SIZE-1) {\n            fstd.f[i] = v;\n            break;\n        }\n        int64_t frac = v/PEG_RATE;\n        fstd.f[i] = frac;\n        v -= frac;\n    }\n    return fstd;\n}\n\nbool CFractions::IsPositive() const\n{\n    if (nFlags & VALUE)\n        return true;\n\n    for(int i=0;i<PEG_SIZE;i++) {\n        if (f[i] <0)\n            return false;\n    }\n    return true;\n}\n\nbool CFractions::IsNegative() const\n{\n    if (nFlags & VALUE)\n        return false;\n\n    for(int i=0;i<PEG_SIZE;i++) {\n        if (f[i] >0)\n            return false;\n    }\n    return true;\n}\n\nint64_t CFractions::Total() const\n{\n    int64_t nValue =0;\n    if (nFlags & VALUE)\n        return f[0];\n\n    for(int i=0;i<PEG_SIZE;i++) {\n        nValue += f[i];\n    }\n    return nValue;\n}\n\nint64_t CFractions::Low(int supply) const\n{\n    int64_t nValue =0;\n    if (nFlags & VALUE)\n        return Std().Low(supply);\n\n    for(int i=0;i<supply;i++) {\n        nValue += f[i];\n    }\n    return nValue;\n}\n\nint64_t CFractions::High(int supply) const\n{\n    int64_t nValue =0;\n    if (nFlags & VALUE)\n        return Std().High(supply);\n\n    for(int i=supply;i<PEG_SIZE;i++) {\n        nValue += f[i];\n    }\n    return nValue;\n}\n\nint64_t CFractions::Low(const CPegLevel & peglevel) const\n{\n    int64_t nValue =0;\n    if (nFlags & VALUE)\n        return Std().Low(peglevel);\n\n    int to = peglevel.nSupply + peglevel.nShift;\n    if (to <0) return 0;\n    if (to >= PEG_SIZE) return 0;\n\n    if (peglevel.nShiftLastPart >0 &&\n        peglevel.nShiftLastTotal >0) {\n        // partial value to use\n        int64_t v = f[to];\n        int64_t vpart = ::RatioPart(v,\n                                    peglevel.nShiftLastPart,\n                                    peglevel.nShiftLastTotal);\n        if (vpart < v) vpart++; // better rounding\n        nValue += vpart;\n    }\n\n    for(int i=0;i<to;i++) {\n        nValue += f[i];\n    }\n\n    return nValue;\n}\n\nint64_t CFractions::High(const CPegLevel & peglevel) const\n{\n    int64_t nValue =0;\n    if (nFlags & VALUE)\n        return Std().High(peglevel);\n\n    int from = peglevel.nSupply + peglevel.nShift;\n    if (from <0) return 0;\n    if (from >= PEG_SIZE) return 0;\n\n    if (peglevel.nShiftLastPart >0 &&\n        peglevel.nShiftLastTotal >0) {\n        // partial value to use\n        int64_t v = f[from];\n        int64_t vpart = ::RatioPart(v,\n                                    peglevel.nShiftLastPart,\n                                    peglevel.nShiftLastTotal);\n        if (vpart < v) vpart++; // better rounding\n        nValue += (v - vpart);\n        from++;\n    }\n\n    for(int i=from;i<PEG_SIZE;i++) {\n        nValue += f[i];\n    }\n\n    return nValue;\n}\n\nint64_t CFractions::NChange(const CPegLevel & peglevel) const\n{\n    CPegLevel peglevel_next = peglevel;\n    peglevel_next.nSupply = peglevel_next.nSupplyNext;\n    peglevel_next.nSupplyNext = peglevel_next.nSupplyNextNext;\n\n    int64_t nValueSrc = High(peglevel);\n    int64_t nValueDst = High(peglevel_next);\n    return nValueDst - nValueSrc;\n}\n\nint64_t CFractions::NChange(int src_supply, int dst_supply) const\n{\n    int64_t nValueSrc = High(src_supply);\n    int64_t nValueDst = High(dst_supply);\n    return nValueDst - nValueSrc;\n}\n\nint16_t CFractions::HLI() const\n{\n    if (nFlags & VALUE)\n        return Std().HLI();\n\n    int64_t half = 0;\n    int64_t total = Total();\n    if (total ==0) {\n        return 0;\n    }\n    for(int16_t i=0;i<PEG_SIZE;i++) {\n        half += f[i];\n        if (half > total/2) {\n            return i;\n        }\n    }\n    return 0;\n}\n\nvoid CFractions::ToStd()\n{\n    if ((nFlags & VALUE) == 0)\n        return;\n\n    nFlags &= ~uint32_t(VALUE);\n    nFlags |= STD;\n\n    int64_t v = f[0];\n    for(int i=0;i<PEG_SIZE;i++) {\n        if (i == PEG_SIZE-1) {\n            f[i] = v;\n            break;\n        }\n        int64_t frac = v/PEG_RATE;\n        f[i] = frac;\n        v -= frac;\n    }\n}\n\nCFractions CFractions::Positive(int64_t* total) const\n{\n    if ((nFlags & STD) == 0) {\n        return Std().Positive(total);\n    }\n    CFractions frPositive(0, CFractions::STD);\n    for(int i=0; i<PEG_SIZE; i++) {\n        if (f[i] <=0) continue;\n        frPositive.f[i] = f[i];\n        if (total) *total += f[i];\n    }\n    return frPositive;\n}\nCFractions CFractions::Negative(int64_t* total) const\n{\n    if ((nFlags & STD) == 0) {\n        return Std().Negative(total);\n    }\n    CFractions frNegative(0, CFractions::STD);\n    for(int i=0; i<PEG_SIZE; i++) {\n        if (f[i] >=0) continue;\n        frNegative.f[i] = f[i];\n        if (total) *total += f[i];\n    }\n    return frNegative;\n}\n\n\nCFractions CFractions::LowPart(int supply, int64_t* total) const\n{\n    if ((nFlags & STD) == 0) {\n        return Std().LowPart(supply, total);\n    }\n    CFractions frLowPart(0, CFractions::STD);\n    for(int i=0; i<supply; i++) {\n        if (total) *total += f[i];\n        frLowPart.f[i] += f[i];\n    }\n    return frLowPart;\n}\nCFractions CFractions::HighPart(int supply, int64_t* total) const\n{\n    if ((nFlags & STD) == 0) {\n        return Std().HighPart(supply, total);\n    }\n    CFractions frHighPart(0, CFractions::STD);\n    for(int i=supply; i<PEG_SIZE; i++) {\n        if (total) *total += f[i];\n        frHighPart.f[i] += f[i];\n    }\n    return frHighPart;\n}\n\nCFractions CFractions::LowPart(const CPegLevel & peglevel, int64_t* total) const\n{\n    if ((nFlags & STD) == 0) {\n        return Std().LowPart(peglevel, total);\n    }\n\n    CFractions frLowPart(0, CFractions::STD);\n\n    int to = peglevel.nSupply + peglevel.nShift;\n    if (to >=0 &&\n            to <PEG_SIZE &&\n            peglevel.nShiftLastPart >0 &&\n            peglevel.nShiftLastTotal >0) {\n        // partial value to use\n        int64_t v = f[to];\n        int64_t vpart = ::RatioPart(v,\n                                    peglevel.nShiftLastPart,\n                                    peglevel.nShiftLastTotal);\n        if (vpart < v) vpart++;\n        frLowPart.f[to] = vpart;\n        if (total) *total += vpart;\n    }\n\n    for(int i=0; i<to; i++) {\n        if (total) *total += f[i];\n        frLowPart.f[i] = f[i];\n    }\n    return frLowPart;\n}\nCFractions CFractions::HighPart(const CPegLevel & peglevel, int64_t* total) const\n{\n    if ((nFlags & STD) == 0) {\n        return Std().HighPart(peglevel, total);\n    }\n\n    CFractions frHighPart(0, CFractions::STD);\n\n    int from = peglevel.nSupply + peglevel.nShift;\n    if (from >=0 &&\n            from <PEG_SIZE &&\n            peglevel.nShiftLastPart >0 &&\n            peglevel.nShiftLastTotal >0) {\n        // partial value to use\n        int64_t v = f[from];\n        int64_t vpart = ::RatioPart(v,\n                                    peglevel.nShiftLastPart,\n                                    peglevel.nShiftLastTotal);\n        if (vpart < v) vpart++;\n        frHighPart.f[from] = (v - vpart);\n        if (total) *total += (v - vpart);\n        from++;\n    }\n\n    for(int i=from; i<PEG_SIZE; i++) {\n        if (total) *total += f[i];\n        frHighPart.f[i] = f[i];\n    }\n    return frHighPart;\n}\n\nCFractions CFractions::MidPart(const CPegLevel & peglevel_low,\n                               const CPegLevel & peglevel_high) const\n{\n    int from = peglevel_low.nSupply + peglevel_low.nShift;\n    int to = peglevel_high.nSupply + peglevel_high.nShift;\n\n    if (from != to) {\n        return HighPart(peglevel_low, nullptr).LowPart(peglevel_high, nullptr);\n    }\n\n    // same supply, different partial ratio\n    CFractions mid(0, STD);\n    int one = from;\n    int64_t v = f[one];\n    int64_t vone = f[one];\n\n    if (peglevel_low.nShiftLastPart >0 &&\n        peglevel_low.nShiftLastTotal >0) {\n        int64_t vpart = ::RatioPart(vone,\n                                    peglevel_low.nShiftLastPart,\n                                    peglevel_low.nShiftLastTotal);\n        v -= vpart;\n    }\n\n    if (peglevel_high.nShiftLastPart >0 &&\n        peglevel_high.nShiftLastTotal >0) {\n        int64_t vpart = ::RatioPart(vone,\n                                    peglevel_high.nShiftLastPart,\n                                    peglevel_high.nShiftLastTotal);\n        if (vpart < vone) vpart++;\n        v -= (vone - vpart);\n    }\n\n    mid.f[from] = v;\n    return mid;\n}\n\n/** Take a part as ration part/total where part is also value (sum fraction)\n *  Returned fractions are also adjusted for part for rounding differences.\n *  #NOTE8\n */\nCFractions CFractions::RatioPart(int64_t nPartValue) const {\n    if ((nFlags & STD) == 0) {\n        return Std().RatioPart(nPartValue);\n    }\n    int64_t nTotalValue = Total();\n    int64_t nPartValueSum = 0;\n    CFractions fPart(0, CFractions::STD);\n\n    if (nPartValue == 0 && nTotalValue == 0)\n        return fPart;\n    if (nPartValue == 0)\n        return fPart;\n    if (nPartValue > nTotalValue)\n        return Std();\n\n    int adjust_from = PEG_SIZE;\n    for(int i=0; i<PEG_SIZE; i++) {\n        int64_t v = f[i];\n\n        if (v != 0 && i < adjust_from) {\n            adjust_from = i;\n        }\n\n        bool has_overflow = false;\n        if (std::is_same<int64_t,long>()) {\n            long m_test;\n            has_overflow = __builtin_smull_overflow(v, nPartValue, &m_test);\n        } else if (std::is_same<int64_t,long long>()) {\n            long long m_test;\n            has_overflow = __builtin_smulll_overflow(v, nPartValue, &m_test);\n        } else {\n            assert(0); // todo: compile error\n        }\n\n        if (has_overflow) {\n            multiprecision::uint128_t v128(v);\n            multiprecision::uint128_t part128(nPartValue);\n            multiprecision::uint128_t f128 = (v128*part128)/nTotalValue;\n            fPart.f[i] = f128.convert_to<int64_t>();\n        }\n        else {\n            fPart.f[i] = (v*nPartValue)/nTotalValue;\n        }\n\n        nPartValueSum += fPart.f[i];\n    }\n\n    if (nPartValueSum == nPartValue)\n        return fPart;\n    if (nPartValueSum > nPartValue)\n        return fPart; // todo:peg: validate if possible\n\n    int idx = adjust_from;\n    int64_t nAdjustValue = nPartValue - nPartValueSum;\n    while(nAdjustValue >0) {\n        // todo:peg: review all possible cases if rounding mismatch with adjust_from\n        if (fPart.f[idx] < f[idx]) {\n            nAdjustValue--;\n            fPart.f[idx]++;\n        }\n        idx++;\n        if (idx >= PEG_SIZE) {\n            idx = adjust_from;\n        }\n    }\n\n    return fPart;\n}\n\n/** Take a part as ration part/total where part is also value (sum fraction)\n *  Add taken part into destination fractions. Adjusted from adjust_from.\n *  Returns not completed amount (if source(\"this\") has no enough)\n *  #NOTE8\n */\nint64_t CFractions::MoveRatioPartTo(int64_t nValueToMove,\n                                    CFractions& b)\n{\n    int64_t nTotalValue = Total();\n    int64_t nPartValue = nValueToMove;\n\n    if (nTotalValue == 0)\n        return nValueToMove;\n    if (nValueToMove == 0)\n        return 0;\n\n    if ((nFlags & STD) == 0)\n        ToStd();\n    if ((b.nFlags & STD) == 0)\n        b.ToStd();\n\n    if (nPartValue >= nTotalValue) {\n        nPartValue = nTotalValue;\n        b += *this; // move all\n        for(int i=0; i<PEG_SIZE; i++) f[i] = 0; // taken all\n        return nValueToMove - nPartValue;\n    }\n\n    int64_t nPartValueSum = 0;\n    int adjust_from = PEG_SIZE;\n    for(int i=0; i<PEG_SIZE; i++) {\n        int64_t v = f[i];\n\n        if (v != 0 && i < adjust_from) {\n            adjust_from = i;\n        }\n\n        bool has_overflow = false;\n        if (std::is_same<int64_t,long>()) {\n            long m_test;\n            has_overflow = __builtin_smull_overflow(v, nPartValue, &m_test);\n        } else if (std::is_same<int64_t,long long>()) {\n            long long m_test;\n            has_overflow = __builtin_smulll_overflow(v, nPartValue, &m_test);\n        } else {\n            assert(0); // todo: compile error\n        }\n\n        int64_t vp = 0;\n\n        if (has_overflow) {\n            multiprecision::uint128_t v128(v);\n            multiprecision::uint128_t part128(nPartValue);\n            multiprecision::uint128_t f128 = (v128*part128)/nTotalValue;\n            vp = f128.convert_to<int64_t>();\n        }\n        else {\n            vp = (v*nPartValue)/nTotalValue;\n        }\n\n        nPartValueSum += vp;\n        b.f[i] += vp;\n        f[i] -= vp;\n    }\n\n    if (nPartValueSum == nPartValue)\n        return 0;\n    if (nPartValueSum > nPartValue)\n        return 0; // todo:peg: validate if possible\n\n    int idx = adjust_from;\n    int64_t nAdjustValue = nPartValue - nPartValueSum;\n    while(nAdjustValue >0) {\n        if (f[idx] >0) {\n            nAdjustValue--;\n            b.f[idx]++;\n            f[idx]--;\n        }\n        idx++;\n        if (idx >= PEG_SIZE) {\n            idx = adjust_from;\n        }\n    }\n\n    return 0;\n}\n\nCFractions& CFractions::operator+=(const CFractions& b)\n{\n    if ((b.nFlags & STD) == 0) {\n        return operator+=(b.Std());\n    }\n    if ((nFlags & STD) == 0) {\n        ToStd();\n    }\n    for(int i=0; i<PEG_SIZE; i++) {\n        f[i] += b.f[i];\n    }\n    return *this;\n}\n\nCFractions& CFractions::operator-=(const CFractions& b)\n{\n    if ((b.nFlags & STD) == 0) {\n        return operator-=(b.Std());\n    }\n    if ((nFlags & STD) == 0) {\n        ToStd();\n    }\n    for(int i=0; i<PEG_SIZE; i++) {\n        f[i] -= b.f[i];\n    }\n    return *this;\n}\n\nCFractions CFractions::operator&(const CFractions& b) const\n{\n    CFractions a = *this;\n    for(int i=0; i<PEG_SIZE; i++) {\n        int64_t va = a.f[i];\n        int64_t vb = b.f[i];\n        if      (va >=0 && vb >=0) a.f[i] = std::min(va, vb);\n        else if (va >=0 && vb < 0) a.f[i] = 0;\n        else if (va < 0 && vb >=0) a.f[i] = 0;\n        else if (va < 0 && vb < 0) a.f[i] = std::max(va, vb);\n    }\n    return a;\n}\n\nCFractions CFractions::operator-() const\n{\n    CFractions a = *this;\n    for(int i=0; i<PEG_SIZE; i++) {\n        int64_t va = a.f[i];\n        a.f[i] = -va;\n    }\n    return a;\n}\n\ndouble CFractions::Distortion(const CFractions& b) const\n{\n    int64_t nTotalA = Total();\n    int64_t nTotalB = b.Total();\n\n    if (nTotalA == nTotalB) {\n\n        if (nTotalA == 0) {\n            return 0;\n        }\n\n        int64_t nDiff = 0;\n\n        for(int i=0; i<PEG_SIZE; i++) {\n            int64_t va = f[i];\n            int64_t vb = b.f[i];\n            if (va > vb) {\n                nDiff += (va - vb);\n            }\n        }\n\n        return double(nDiff) / double(nTotalA);\n    }\n\n    else if (nTotalA < nTotalB) {\n        if (nTotalA == 0) {\n            return nTotalB; // does not make sense to scale\n        }\n\n        CFractions b1 = b.RatioPart(nTotalA);\n        return Distortion(b1);\n    }\n\n    else if (nTotalA > nTotalB) {\n        if (nTotalB == 0) {\n            return nTotalA; // does not make sense to scale\n        }\n\n        CFractions a1 = RatioPart(nTotalB);\n        return a1.Distortion(b);\n    }\n\n    return 0;\n}\n\n", "meta": {"hexsha": "db53783d4f1225c20c96f81be5ad7fd1407098b4", "size": 20184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/peg/pegfractions.cpp", "max_stars_repo_name": "bitbaymarket/BitBay", "max_stars_repo_head_hexsha": "99498d8509b439bee6d18be21c78577f1c654c01", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-07-12T01:05:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T03:11:36.000Z", "max_issues_repo_path": "src/peg/pegfractions.cpp", "max_issues_repo_name": "bitbaymarket/BitBay", "max_issues_repo_head_hexsha": "99498d8509b439bee6d18be21c78577f1c654c01", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2016-05-06T11:02:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-26T12:43:20.000Z", "max_forks_repo_path": "src/peg/pegfractions.cpp", "max_forks_repo_name": "bitbaymarket/BitBay", "max_forks_repo_head_hexsha": "99498d8509b439bee6d18be21c78577f1c654c01", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 23.0, "max_forks_repo_forks_event_min_datetime": "2017-01-04T11:55:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T19:20:16.000Z", "avg_line_length": 25.1985018727, "max_line_length": 87, "alphanum_fraction": 0.5396848989, "num_tokens": 5844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891307678321, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22885293194751755}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n\n#if ! defined(GTR_MODEL_HPP)\n#define GTR_MODEL_HPP\n\n#include \"states_patterns.hpp\"\n#include <boost/noncopyable.hpp>\n#include <boost/shared_ptr.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <vector>\n#include <numeric>\n#include <algorithm>\n#include \"xlikelihood.hpp\"\n#include \"mcmc_param.hpp\"\n#include \"basic_cdf.hpp\"\n#include \"q_matrix.hpp\"\n#include \"model.hpp\"\n#include \"multivariate_probability_distribution.hpp\"\n\nnamespace phycas{\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSpecialization of the base class Model that represents the General Time Reversible (GTR) model.\n*/\nclass GTR: public Model\n\t{\n\tpublic:\n                                        GTR();\n                                        ~GTR()\n                                            {\n                                            //std::cerr << \"GTR dying...\" << std::endl;\n                                            }\n\n\t\tvirtual std::string             getModelName() const;\n\t\tvirtual void                    createParameters(JointPriorManagerShPtr jpm, TreeShPtr t, MCMCUpdaterVect & edgelens, MCMCUpdaterVect & edgelen_hyperparams, MCMCUpdaterVect & parameters, int subset_pos);\n\t\tdouble                          calcUniformizationLambda() const;\n        double                          calcLMat(double * * lMat) const;\n        double                          calcUMat(double * * uMat) const;\n\t\tvoid                            calcPMat(double * * pMat, double edgeLength) const;\n\n        void                            fixRelRates();\n\t\tvoid                            freeRelRates();\n\n        std::vector<double>             getRelRates();\n\t\tvoid                            setRelRates(const std::vector<double> & rates);\n\n        void                            calcRelRatesFromRatios();\n\t\tvoid                            setRelRateRatio(unsigned which, double value);\n\n        void                            setStateFreqRatio(unsigned ratio_index, double value);\n\n\t\tvoid                            setRelRateUnnorm(unsigned param_index, double value);\n\t\tdouble                          getRelRateUnnorm(unsigned param_index);\n\n\t\tvoid                            setRelRateParamPrior(ProbDistShPtr d);\n\t\tProbDistShPtr                   getRelRateParamPrior();\n\n\t\tvoid                            setRelRatePrior(MultivarProbDistShPtr d);\n\t\tMultivarProbDistShPtr           getRelRatePrior();\n\n        void                            setNucleotideFreqs(double freqA, double freqC, double freqG, double freqT);\n        void                            setAllFreqsEqual();\n\t\tvirtual void                    setStateFreqUnnorm(unsigned param_index, double value);\n        virtual void                    setStateFreqsUnnorm(const std::vector<double> & values);\n\n        void                            setStateFreqPrior(MultivarProbDistShPtr d);\n\t\tMultivarProbDistShPtr           getStateFreqPrior();\n\n        void                            setStateFreqParamPrior(ProbDistShPtr d);\n\t\tProbDistShPtr                   getStateFreqParamPrior();\n\n        virtual std::string             paramHeader() const;\n\t\tvirtual std::string             paramReport(unsigned ndecimals, bool include_edgelen_hyperparams) const;\n\t\tdouble                          calcTRatio();\n\n        virtual unsigned                getNumFreeParameters() const;\n        virtual void                    appendPWKParamNames(std::vector<std::string> & names, std::string prefix = \"\") const;\n        virtual void                    appendFreeParamNames(std::vector<std::string> & names, std::string prefix = \"\") const;\n        virtual void                    appendParamNames(std::vector<std::string> & names, std::string prefix = \"\") const;\n        virtual void                    appendUntransformedParamValues(std::vector<double> & values) const;\n        virtual void                    appendTransformedParamValues(std::vector<double> & values) const;\n        virtual bool                    setParamValueFromTransformed(std::string parameter_name, double transformed_value, TreeShPtr tree);\n        virtual double                  calcLogDetJacobian() const;\n\n\tprotected:\n\n\t\tMultivarProbDistShPtr           rel_rate_prior;\t\t    /**< The prior distribution governing each relative rate (usually a gamma distribution with scale 1 and shape equal to the desired Dirichlet parameter) */\n\t\tProbDistShPtr                   rel_rate_param_prior;\t/**< The joint prior distribution governing all six relative rates */\n\t\tProbDistShPtr                   freq_param_prior;\t    /**< The prior distribution governing each frequency parameter (usually a gamma distribution with scale 1 and shape equal to the desired Dirichlet parameter; used if frequencies are updated separately by slice sampling) */\n    \tMultivarProbDistShPtr           freq_prior;\t            /**< The prior distribution governing the vector of frequencies (used if frequencies are updated jointly by StateFreqMove) */\n\t\tbool                            rel_rates_fixed;\t    /**< If true, the relative rate values will not change during MCMC updates */\n\t\tmutable MCMCUpdaterVect         rel_rate_params;\t    /**< A vector containing copies of all six relative rate parameters (saved so that fixed/free status can be changed) */\n\t\tmutable QMatrix                 q_matrix;\t\t\t    /**< A QMatrix object used to compute transition probabilities */\n\n\t\tstring_vect_t                   relrate_name;\t\t\t/**< Holds names of the 6 relative rates (e.g. rAC, rAG, rAT, rCG, rCT, rGT) used as headers in the param file */\n\t\tstring_vect_t                   freq_name;\t\t\t\t/**< Holds names of the 4 state frequencies (e.g. freqA, freqC, freqG, freqT) used as headers in the param file */\n\n\t\t// Below here are quantities that directly affect likelihood calculations and which should increment time_stamp when modified\n\t\tstd::vector<double>             rel_rates;\t\t\t    /**< A vector containing the six relative rates */\n\t\tstd::vector<double>             rel_rate_ratios;\t    /**< A vector for temporary storage of the five relative rate ratios: rAG/rAC, rAT/rAC, rCG/rAC, rCT/rAC, and rGT/rAC */\n\t};\n\ntypedef boost::shared_ptr<GTR> GTRShPtr;\n\n} // namespace phycas\n\n//#include \"phycas/src/gtr_model.inl\"\n\n#endif\n\n", "meta": {"hexsha": "8e458e1da40ca45470c9d6b8dafc90dfd6120e6e", "size": 7710, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cpp/gtr.hpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/gtr.hpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/gtr.hpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 60.234375, "max_line_length": 278, "alphanum_fraction": 0.5629053178, "num_tokens": 1484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22885293194751752}}
{"text": "#include <iostream>\n#include <string>\n#include <vector>\n#include \"cnpy.h\"\n#include \"float_conversion.h\"\n#include <fstream>\n#include <chrono>\n#include <thread>\n#include <mutex>\n#include <queue>\n#include <algorithm>\n#include <random>\n#include <Eigen/Dense>\n#include <sys/stat.h>\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace std::string_literals;\n\nconstexpr size_t BLUE   =  0;\nconstexpr size_t GREEN  =  1;\nconstexpr size_t RED    =  2;\nconstexpr size_t RE1    =  3;\nconstexpr size_t RE2    =  4;\nconstexpr size_t RE3    =  5;\nconstexpr size_t NIR    =  6;\nconstexpr size_t SWIR1  =  7;\nconstexpr size_t SWIR2  =  8;\nconstexpr size_t CLOUDS =  9;\nconstexpr size_t SHAPE  = 10;\n\nconstexpr size_t NUM_THREADS = 8;\nconstexpr size_t BANDS = 6;\n\nconst array<float, 3> QUANTILES {0.2f, 0.5f, 0.8f};\nconst size_t QS = QUANTILES.size();\n\ntypedef array<float, BANDS> Point;\ntypedef vector<Point> PointCloud;\ntypedef pair<vector<float>, vector<PointCloud>> timeseries;\n\nconstexpr float START_DAY = 31 + 28; // Only use images starting in March\nconstexpr float MAX_DAY   = 365 - START_DAY - 31; // End with November\n\ntime_t basetime;\n\nstruct result\n{\n  string number;\n  char type;\n  vector<float> features;\n};\n\narray<thread, NUM_THREADS> threads;\narray<string, NUM_THREADS> current;\narray<vector<result>, NUM_THREADS> results;\nmutex queue_lock;\nqueue<string> todo;\n\n#define DATA(b) half_to_float(raw.data<uint16_t>()[ b * W * H * T + x * H * T + y * T + t ])\n\nfloat clamp(float x, float min=-100, float max=100)\n{\n  if (x > max)\n    return max;\n  else if (x < min)\n    return min;\n  else if (isnormal(x))\n    return x;\n  else\n    return 0;\n}\n\ntimeseries parse(string filename)\n{\n  vector<float> timestamps;\n  vector<PointCloud> all_points;\n\n  cnpy::NpyArray raw = cnpy::npy_load(filename + \".npy\"s);\n  ifstream indexfile(filename + \".idx\"s);\n  if(indexfile.is_open())\n  {\n    string line;\n    // Skip two lines\n    getline(indexfile, line);\n    getline(indexfile, line);\n    // Skip the label\n    getline(indexfile, line, '~');\n    // Get entries\n    while(getline(indexfile, line, ','))\n    {\n      struct tm tm;\n      strptime(line.c_str(), \"%Y-%m-%dT%H:%M:%S\", &tm);\n      float diff = difftime(mktime(&tm), basetime) / (60 * 60 * 24) - START_DAY;\n      timestamps.push_back(diff);\n    }\n    indexfile.close();\n  }\n\n  size_t W = raw.shape[1];\n  size_t H = raw.shape[2];\n  size_t T = raw.shape[3];\n  vector<float> used_timestamps;\n\n  assert(timestamps.size() == T);\n\n  for(size_t t = 0; t < T; ++t)\n  {\n    if(timestamps[t] <= 0)\n      continue;\n    PointCloud points;\n    size_t glitchy_points = 0,\n           cloudy_points = 0,\n           total_points = 0;\n    for(size_t x = 0; x < W; ++x) for(size_t y = 0; y < H; ++y)\n    {\n      if(DATA(SHAPE) > 0)\n      {\n        ++total_points;\n        if(DATA(CLOUDS) > 0)\n          ++cloudy_points;\n        float red  = DATA(RED),\n              grn  = DATA(GREEN),\n              blu  = DATA(BLUE),\n              nir  = DATA(NIR),\n              swir1= DATA(SWIR1),\n              swir2= DATA(SWIR2),\n              re1  = DATA(RE1),\n              re2  = DATA(RE2),\n              re3  = DATA(RE3);\n        if(red == 0 && grn == 0 && blu == 0)\n          ++glitchy_points;\n        float ndvi = (nir - red) / (nir + red); // Normalized Difference Vegetation Index\n        float cai = (swir1 - swir2) / (swir1 + swir2); // Cellulose Absorption index\n        float n = (2 * (nir * nir - red * red) + 1.5f * nir + 0.5 * red ) / (nir + red + 0.5f);\n        float gemi = n * (1.0f - 0.25f * n) - (red - 0.125f) / (1 - red); // Global Environment Monitoring Index\n        float gli = (2 * grn - red - blu) / (2 * grn + red + blu); // Green Leaf Index\n        float cvi = (nir * red) / (grn * grn); // Chlorophyll vegetation index\n        float ccci = ((nir - re1) / (nir + re1)) / ndvi; // Canopy Chlorophyll Content Index\n        float dswi = (re3 - grn) / (swir1 + red); // Disease-Water Stress Index 5\n        float nd790_670 = (re3 - red) / (re3 + red); // Normalized Difference 790 / 670\n        float ndwi = (nir - swir2) / (nir + swir2); // Normalized Difference Water Index\n        points.push_back({\n            clamp(ndvi),\n            // clamp(cai),\n            clamp(gemi),\n            clamp(gli),\n            clamp(cvi),\n            // clamp(ccci),\n            clamp(dswi),\n            // clamp(nd790_670),\n            clamp(ndwi),\n        });\n      }\n    }\n    if(cloudy_points > 0.2 * total_points)\n      continue;\n    if(glitchy_points > 0.2 * total_points)\n      continue;\n    all_points.push_back(points);\n    used_timestamps.push_back(timestamps[t] / MAX_DAY);\n  }\n\n  return make_pair(used_timestamps, all_points);\n}\n\ninline float hat(float t, float center, float width)\n{\n  return max(1 - abs(t-center) / width, 0.0f) / width;\n}\n\nconst vector<float> get_features(timeseries data, float subsample=1.0f)\n{\n  vector<float> time = data.first;\n  vector<PointCloud> point_series  = data.second;\n  int count = point_series[0].size();\n\n  vector<bool> used(count, true);\n  if(subsample < 1.0f)\n  {\n    count = 0;\n    random_device rd;\n    mt19937 random(rd());\n    uniform_real_distribution<> real(0.0, 1.0);\n    for(auto &&b : used)\n    {\n      b = real(random) < subsample;\n      count += b;\n    }\n  }\n\n  vector<float> features;\n  array<vector<float>, BANDS * QS> Q;\n\n  for(PointCloud point_cloud : point_series)\n  {\n    for(size_t band = 0; band < BANDS; ++band)\n    {\n      vector<float> points;\n      for(size_t i = 0; i < point_cloud.size(); ++i)\n      {\n        if(used[i] && !isnan(point_cloud[i][band]))\n        {\n          points.push_back(point_cloud[i][band]);\n        }\n      }\n      if(points.size() > 0)\n      {\n        sort(points.begin(), points.end());\n        for(size_t q = 0; q < QS; ++q)\n          Q[band * QS + q].push_back(points[size_t(points.size() * QUANTILES[q])]);\n      }\n      else\n      {\n        for(float q : QUANTILES)\n          Q[band * QS + q].push_back(0);\n      }\n    }\n  }\n\n  for(auto q : Q)\n  {\n    constexpr size_t DIM = 8;\n    // vector<complex<float>> coefficients(NUM_FOURIER, 0);\n    Eigen::Matrix<float, Eigen::Dynamic, DIM> model(q.size(), DIM);\n    Eigen::Matrix<float, Eigen::Dynamic, 1> target(q.size(), 1);\n    for(size_t k = 0; k < q.size(); ++k)\n    {\n      target(k, 0) = q[k];\n      model(k, 0)  = hat(time[k], 0.0f  , 1.0f  ); // Left Edge\n      model(k, 1)  = hat(time[k], 1.0f  , 1.0f  ); // Right Edge\n      model(k, 2)  = hat(time[k], 0.5f  , 0.5f  ); // 1/2\n      model(k, 3)  = hat(time[k], 0.25f , 0.25f ); // 1/4\n      model(k, 4)  = hat(time[k], 0.75f , 0.25f ); // 3/4\n      model(k, 5)  = hat(time[k], 0.125f, 0.125f); // 1/8\n      model(k, 6)  = hat(time[k], 0.375f, 0.125f); // 3/8\n      model(k, 7)  = hat(time[k], 0.625f, 0.125f); // 5/8\n      // model(k, 8)  = hat(time[k], 0.875f, 0.125f); // 7/8\n    }\n    Eigen::Matrix<float, DIM, DIM> H = model.transpose() * model;\n    H = H.completeOrthogonalDecomposition().pseudoInverse();\n    Eigen::Matrix<float, DIM, 1> weight = H * model.transpose() * target;\n    for(size_t k = 0; k < DIM; ++k)\n    {\n      features.push_back(weight(k, 0));\n    }\n  }\n  return features;\n}\n\ninline bool file_exists (const std::string& name)\n{\n  struct stat buffer;\n  return (stat (name.c_str(), &buffer) == 0); \n}\n\nvoid work(size_t thread_id)\n{\n  current[thread_id] = \"Initializing\";\n  bool running = true;\n  string number = \"\";\n  while(running)\n  {\n    {\n      lock_guard<mutex> lock(queue_lock);\n      if(todo.empty())\n      {\n        break;\n      } else {\n        number = todo.front();\n        current[thread_id] = number;\n        todo.pop();\n      }\n    }\n    \n    string filename = \"/home/konrad/dev/remote_sensing/ibiss_processed/cubes/\" + number;\n    if(!file_exists(filename + \".npy\"s))\n      continue;\n    timeseries data = parse(filename);\n\n    results[thread_id].push_back({ number, 'F', get_features(data, 0.5) });\n  }\n  current[thread_id] = \"Done\";\n}\n\nint main(int argc, char **argv)\n{\n  struct tm tm;\n  strptime(\"2017-01-01T00:00:00\", \"%Y-%m-%dT%H:%M:%S\", &tm);\n  basetime = mktime(&tm);\n\n  size_t count = 0;\n  if(argc == 1)\n  {\n    string number = \"\";\n    while(getline(cin, number))\n    {\n      todo.push(number);\n      ++count;\n    }\n  }\n  else\n  {\n    string number = \"\";\n    ifstream input(argv[1]);\n    if(!input.is_open())\n      return 1;\n    while(getline(input, number))\n    {\n      todo.push(number);\n      ++count;\n    }\n    input.close();\n  }\n\n  cout << \"Beginning feature extraction\" << endl;\n  auto features = vector<pair<string, vector<float>>>(count);\n  size_t num = features.size();\n\n  for(size_t i = 0; i < 100; ++i)\n    cout << '_';\n  cout << endl;\n\n  for(size_t i = 0; i < NUM_THREADS; ++i)\n  {\n    threads[i] = thread(work, i);\n  }\n\n  size_t progress = 100;\n  while(progress > 0)\n  {\n    if(progress * num > todo.size() * 100)\n    {\n      cout << '#' << flush;\n      --progress;\n    }\n    else\n    {\n      this_thread::sleep_for(100ms);\n    }\n  }\n\n  cout << endl;\n  for(size_t i = 0; i < NUM_THREADS; ++i)\n  {\n    cout << \"Thread (\" << i << \") processed \" << results[i].size() << \" elements\" << endl;\n  }\n\n  for(size_t i = 0; i < NUM_THREADS; ++i)\n  {\n    threads[i].join();\n  }\n  cout << \"\\nCollected all threads\" << endl;\n\n  cout << \"\\nWriting CSV...\" << endl;\n\n  ofstream out(\"/home/konrad/dev/remote_sensing/data/cfeatures.csv\");\n\n  for(size_t i = 0; i < 8*NUM_THREADS; ++i)\n    cout << '_';\n  cout << endl;\n\n  for(size_t i = 0; i < NUM_THREADS; ++i)\n  {\n    for(auto p : results[i])\n    {\n      out << p.number << ',' << p.type;\n      for(auto val : p.features)\n        out << \",\" << val;\n      out << '\\n';\n    }\n    cout << \"########\" << flush;\n    results[i].clear();\n  }\n  cout << endl;\n  out.close();\n\n  return 0;\n}\n", "meta": {"hexsha": "0904d8dccd6f616aa006d99f310a05b878d1376d", "size": 9710, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "feature_extractor.cpp", "max_stars_repo_name": "cloud-oak/feature_extractor", "max_stars_repo_head_hexsha": "fd9734981e459ed5a288d919d02589628062c811", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "feature_extractor.cpp", "max_issues_repo_name": "cloud-oak/feature_extractor", "max_issues_repo_head_hexsha": "fd9734981e459ed5a288d919d02589628062c811", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "feature_extractor.cpp", "max_forks_repo_name": "cloud-oak/feature_extractor", "max_forks_repo_head_hexsha": "fd9734981e459ed5a288d919d02589628062c811", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5526315789, "max_line_length": 112, "alphanum_fraction": 0.5615859938, "num_tokens": 3022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22884559723156375}}
{"text": "#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n#include <string>\r\n#include <cstring>\r\n#include <algorithm>\r\n#include <fstream>\r\n#include <opencv2/core/core.hpp>\r\n#include <opencv2/imgproc/imgproc.hpp>\r\n#include <opencv2/highgui/highgui.hpp>\r\n#include <boost/regex.hpp>\r\n#include <boost/filesystem.hpp>\r\n#include <boost/date_time/posix_time/posix_time.hpp>\r\n#include <chrono>\r\n\r\nusing namespace std;\r\nusing namespace boost::filesystem;\r\nusing namespace cv;\r\n\r\ntypedef struct IrisCode\r\n{\r\n  string name;\r\n  unsigned char **data;\r\n  int stepsize;\r\n} IrisCode;\r\n\r\nstatic const int CODE_WIDTH = 512;\r\nstatic const int CODE_HEIGHT = 20;\r\n\r\nstatic const int MIN_SHIFT = -16;\r\nstatic const int MAX_SHIFT = 16;\r\n\r\nstatic const int htlut[256] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8};\r\n\r\n\r\nstatic const int ALG_MINHD = 0, ALG_3A = 1, ALG_3AL = 2, ALG_3AS = 3;\r\nstatic const int MODE_MAIN = 1, MODE_HELP = 2;\r\nenum MAIN_MODE { STATIC, DYNAMIC};\r\n\r\nvoid printUsage() {\r\n\tprintf(\"+-----------------------------------------------------------------------------+\\n\");\r\n\tprintf(\"| TripleA - calculates Hamming distance of iris-codes                         |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| MODES                                                                       |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| (# 1) HD calculation of the input images (cross comparison)                 |\\n\");\r\n\tprintf(\"| (# 2) usage                                                                 |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| ARGUMENTS                                                                   |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n\tprintf(\"| Name | Parameters | # | ? | Description                                     |\\n\");\r\n\tprintf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n\tprintf(\"| -f   | folder     | 1 | N | folder of iris-codes generated using LG or QSW  |\\n\");\r\n\tprintf(\"| -o   | file       | 1 | N | output file for the results                     |\\n\");\r\n\tprintf(\"| -s   | step-size  | 1 | Y | step-size used in static mode (5)               |\\n\");\r\n\tprintf(\"| -c   | constant   | 1 | Y | constant used in dynamic mode (1)               |\\n\");\r\n\tprintf(\"| -a   | algorithm  | 1 | Y | TripleA algorithm (3a) (default)                |\\n\"); \r\n\tprintf(\"|      |            |   |   | TripleA-limited algorithm (3al)                 |\\n\");\r\n\tprintf(\"|      |            |   |   | TripleA-single-sided algorithm (3as)            |\\n\");\r\n\tprintf(\"| -h   |            | 2 | N | prints usage                                    |\\n\");\r\n\tprintf(\"+------+------------+---+---+-------------------------------------------------+\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| The default is to run the program in dynamic mode. When a step size (-s) is |\\n\");\r\n\tprintf(\"| set the program automatically switches to static-mode.                      |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| EXAMPLE USAGE                                                               |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n    printf(\"| -f codes -s 4 -c 0.33 -a 3a -o compare.txt                                  |\\n\");\r\n    printf(\"|                                                                             |\\n\");\r\n\tprintf(\"| AUTHOR                                                                      |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| Christian Rathgeb                                                           |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| COPYRIGHT                                                                   |\\n\");\r\n\tprintf(\"|                                                                             |\\n\");\r\n\tprintf(\"| (C) 2016 All rights reserved. Do not distribute without written permission. |\\n\");\r\n\tprintf(\"+-----------------------------------------------------------------------------+\\n\");\r\n}\r\n\r\n// estimate the Hamming distance between two given codes using the TripleA algorithm\r\nvoid TripleA(IrisCode code1, IrisCode code2, int start, int stop, ofstream& log, int stepsize){\r\n\t\r\n\tfloat mindist = CODE_HEIGHT*CODE_WIDTH;\r\n\tunsigned int dist;\r\n\tint pos_min = 0;\r\n\t\r\n\tint w = CODE_WIDTH;\r\n\tint h;\r\n\tint border;\r\n\t\r\n\tif (CODE_HEIGHT%8 == 0) h = CODE_HEIGHT/8;\r\n\telse h = CODE_HEIGHT/8 + 1;\r\n\r\n\tauto start_time = chrono::high_resolution_clock::now();\r\n\t\r\n\t// alignmnet with step-size\r\n\tborder = stop%stepsize;\r\n\tif (border != 0){\r\n\t\tint k=start;\r\n\t\tdist = 0;\r\n\t\tfor (int i=0; i < h; i++){\r\n\t\t\tfor (int j=0; j < w; j++){\r\n\t\t\t\tdist+= htlut[code1.data[j][i] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][i]];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t}\r\n\t\tstart+=border;\r\n\t}\r\n\t\r\n\tfor (int k = start; k <= stop; k+=stepsize){\r\n\t\tdist = 0;\r\n\t\tfor (int i=0; i < h; i++){\r\n\t\t\tfor (int j=0; j < w; j++){\r\n\t\t\t\tdist+= htlut[code1.data[j][i] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][i]];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t}\r\n\t}\r\n\r\n\tif (border != 0){\r\n\t\tint k=stop;\r\n\t\tdist = 0;\r\n\t\tfor (int i=0; i < h; i++){\r\n\t\t\tfor (int j=0; j < w; j++){\r\n\t\t\t\tdist+= htlut[code1.data[j][i] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][i]];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t}\r\n\t}\r\n\t\r\n\tstart = max(pos_min - stepsize + 1, start); \r\n\tstop = min(pos_min + stepsize - 1, stop);\r\n\t\r\n\tfor (int k = start; k <= stop; k++){\r\n\t\tdist = 0;\r\n\t\tfor (int i=0; i < h; i++){\r\n\t\t\tfor (int j=0; j < w; j++){\r\n\t\t\t\tdist+= htlut[code1.data[j][i] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][i]];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t}\r\n\t}\r\n\r\n\tauto end_time = chrono::high_resolution_clock::now();\r\n\t\r\n\tlog << \"hd(\" << code1.name << \",\" << code2.name << \"):\" <<  mindist/(CODE_HEIGHT*CODE_WIDTH) << \"\\t time: \" << chrono::duration_cast<chrono::microseconds>(end_time - start_time).count() << \" micro seconds \\t step-size: \" << stepsize << endl; \r\n\tlog.flush();\r\n}\r\n\r\n// estimate the Hamming distance between two given codes using the TripleA-limited algorithm\r\nvoid TripleA_limited(IrisCode code1, IrisCode code2, int start, int stop, ofstream& log, int stepsize){\r\n\t\r\n\tfloat mindist = CODE_HEIGHT*CODE_WIDTH;\r\n\tunsigned int dist;\r\n\tint pos_min = 0;\r\n\t\r\n\tint w = CODE_WIDTH;\r\n\tint h;\r\n\tint border;\r\n\t\r\n\tif (CODE_HEIGHT%8 == 0) h = CODE_HEIGHT/8;\r\n\telse h = CODE_HEIGHT/8 + 1;\r\n\r\n\tauto start_time = chrono::high_resolution_clock::now();\r\n\t\r\n\t// limited alignment with step-size\r\n\tborder = stop%stepsize;\r\n\tif (border != 0){\r\n\t\tint k=start;\r\n\t\tdist = 0;\r\n\t\tfor (int j=0; j < w; j++){\r\n\t\t\tdist+= htlut[code1.data[j][0] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][0]];\r\n\t\t}\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t}\r\n\t\tstart+=border;\r\n\t}\r\n\t\r\n\tfor (int k = start; k <= stop; k+=stepsize){\r\n\t\tdist = 0;\r\n\t\tfor (int j=0; j < w; j++){\r\n\t\t\tdist+= htlut[code1.data[j][0] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][0]];\r\n\t\t}\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t}\r\n\t}\r\n\r\n\tif (border != 0){\r\n\t\tint k=stop;\r\n\t\tdist = 0;\r\n\t\tfor (int j=0; j < w; j++){\r\n\t\t\tdist+= htlut[code1.data[j][0] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][0]];\r\n\t\t}\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t}\r\n\t}\r\n\tmindist = CODE_HEIGHT*CODE_WIDTH;\r\n\t\r\n\tstart = max(pos_min - stepsize + 1, start); // note that we already tested the boundaries\r\n\tstop = min(pos_min + stepsize - 1, stop);\r\n\t\r\n\tfor (int k = start; k <= stop; k++){\r\n\t\tdist = 0;\r\n\t\tfor (int i=0; i < h; i++){\r\n\t\t\tfor (int j=0; j < w; j++){\r\n\t\t\t\tdist+= htlut[code1.data[j][i] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][i]];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t}\r\n\t}\r\n\r\n\tauto end_time = chrono::high_resolution_clock::now();\r\n\t\r\n\tlog << \"hd(\" << code1.name << \",\" << code2.name << \"):\" <<  mindist/(CODE_HEIGHT*CODE_WIDTH) << \"\\t time: \" << chrono::duration_cast<chrono::microseconds>(end_time - start_time).count() << \" micro seconds \\t step-size: \" << stepsize << endl;\r\n\tlog.flush();\r\n}\r\n\r\n// estimate the Hamming distance between two given codes using the TripleA-single-sided algorithm\r\nvoid TripleA_singlesided(IrisCode code1, IrisCode code2, int start, int stop, ofstream& log, int stepsize){\r\n\t\r\n\tfloat mindist = CODE_HEIGHT*CODE_WIDTH;\r\n\tunsigned int dist;\r\n\tint pos_min = 0;\r\n\tint idx_min = 0;\r\n\t\r\n\tint w = CODE_WIDTH;\r\n\tint h;\r\n\tint border;\r\n\tint off = 0;\r\n\t\r\n\tif (CODE_HEIGHT%8 == 0) h = CODE_HEIGHT/8;\r\n\telse h = CODE_HEIGHT/8 + 1;\r\n\t\r\n\tborder = stop%stepsize;\r\n\tif (border > 0) off=2;\r\n\t\r\n\tint cnt=0;\r\n\tint scores[(abs(start)+stop)/stepsize + 1 + off];\r\n\t\r\n\tauto start_time = chrono::high_resolution_clock::now();\r\n\t\r\n\tif (border != 0){\r\n\t\tint k=start;\r\n\t\tdist = 0;\r\n\t\tfor (int j=0; j < w; j++){\r\n\t\t\tdist+= htlut[code1.data[j][0] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][0]];\r\n\t\t}\r\n\t\tscores[cnt] = dist;\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t\tidx_min = cnt;\r\n\t\t}\r\n\t\tcnt++;\r\n\t\tstart+=border;\r\n\t}\r\n\t\r\n\tfor (int k = start; k <= stop; k+=stepsize){\r\n\t\tdist = 0;\r\n\r\n\t\tfor (int j=0; j < w; j++){\r\n\t\t\tdist+= htlut[code1.data[j][0] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][0]];\r\n\t\t}\r\n\t\tscores[cnt] = dist;\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t\tidx_min = cnt;\r\n\t\t}\r\n\t\tcnt++;\r\n\t}\r\n\r\n\tif (border != 0){\r\n\t\tint k=stop;\r\n\t\tdist = 0;\r\n\t\tfor (int j=0; j < w; j++){\r\n\t\t\tdist+= htlut[code1.data[j][0] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][0]];\r\n\t\t}\r\n\t\tscores[cnt] = dist;\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t\tidx_min = cnt;\r\n\t\t}\r\n\t}\r\n\t\r\n\tmindist = CODE_HEIGHT*CODE_WIDTH;\r\n\tif (idx_min == 0){\r\n\t\tstart = pos_min;\r\n\t\tstop = pos_min + stepsize - 1;\r\n\t}\r\n\telse if (idx_min == (abs(start)+stop)/stepsize + off){\r\n\t\tstart = pos_min - stepsize + 1;\r\n\t\tstop = pos_min;\r\n\t}\r\n\telse if (scores[idx_min +1] > scores[idx_min -1]){\r\n\t\tstart = pos_min - stepsize + 1;\r\n\t\tstop = pos_min;\r\n\t}\r\n\telse{\r\n\t\tstart = pos_min;\r\n\t\tstop = pos_min + stepsize - 1;\r\n\t}\r\n\t\r\n\tfor (int k = start; k <= stop; k++){\r\n\t\tdist = 0;\r\n\t\tfor (int i=0; i < h; i++){\r\n\t\t\tfor (int j=0; j < w; j++){\r\n\t\t\t\tdist+= htlut[code1.data[j][i] ^ code2.data[(j+k+CODE_WIDTH)%CODE_WIDTH][i]];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (dist < mindist){\r\n\t\t\tmindist = dist;\r\n\t\t\tpos_min = k;\r\n\t\t}\r\n\t}\r\n\tauto end_time = chrono::high_resolution_clock::now();\r\n\tlog << \"hd(\" << code1.name << \",\" << code2.name << \"):\" <<  mindist/(CODE_HEIGHT*CODE_WIDTH) << \"\\t time: \" << chrono::duration_cast<chrono::microseconds>(end_time - start_time).count() << \" micro seconds \\t step-size: \" << stepsize << endl;\r\n\tlog.flush();\r\n}\r\n\r\n// read an iris-code form a given file name, extract the (dynamic) step size\r\n// and map it to a more efficient representation\r\nIrisCode getCode(string filename, float k)\r\n{\r\n\tIrisCode iriscode;\r\n\tMat img = imread(filename, CV_LOAD_IMAGE_UNCHANGED);\r\n\tCV_Assert(img.data != 0);\r\n\tCV_Assert(img.type() == CV_8UC1);\r\n\r\n\tint w = CODE_WIDTH;\r\n\tint h;\r\n\r\n\tiriscode.name=filename;\r\n\t\r\n\tif (CODE_HEIGHT%8 == 0) h = CODE_HEIGHT/8;\r\n\telse h = CODE_HEIGHT/8 + 1;\r\n\r\n\tunsigned char c;\r\n\tunsigned char bincode[CODE_WIDTH][CODE_HEIGHT];\r\n\t\r\n\t// initialize with 0s\r\n\tfor (int i=0; i < CODE_HEIGHT; i++){\r\n\t\tfor (int j=0; j < CODE_WIDTH; j++){\r\n\t\t\tbincode[j][i] = 0;\r\n\t\t}\r\n\t}\r\n\t\r\n\t// now map the given codes to 0/1 representation\r\n\tfor (int i=0; i < CODE_HEIGHT; i++){\r\n\t\tfor (int j=0; j < CODE_WIDTH; j++){\r\n\t\t\tc=pow(2,7-(j%8));\r\n\t\t\tbincode[j][i]=htlut[img.data[j/8+i*CODE_WIDTH/8]&c];\r\n\t\t}\r\n\t}\r\n\t\r\n\tfloat mu = 0;\r\n\tint length;\r\n\tint count=0;\r\n\tfor (int i=0; i < CODE_HEIGHT; i++){\r\n\t\tlength = 1;\r\n\t\tfor (int j=1; j < CODE_WIDTH; j++){\r\n\t\t\tif (bincode[j][i] == bincode[j-1][i]) length++;\r\n\t\t\telse {\r\n\t\t\t\tmu+=length;\r\n\t\t\t\tlength=1;\r\n\t\t\t\tcount++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tmu+=length;\r\n\t\tlength=1;\r\n\t\tcount++;\r\n\t}\r\n\tmu/=count;\r\n\t\r\n\t// assign the average dynamic step-size according to the given constant k\r\n\tiriscode.stepsize = max((int)(mu*k),1);\r\n\t\r\n\tunsigned char **code;\r\n\tcode = (unsigned char **)malloc(w * sizeof(unsigned char *)); \r\n\tfor (int i = 0; i < w; i++) code[i] = (unsigned char *)malloc(h * sizeof(unsigned char));\r\n\t\r\n\t// initialize with 0s\r\n\tfor (int i=0; i < h; i++){\r\n\t\tfor (int j=0; j < w; j++){\r\n\t\t\tcode[j][i] = 0;\r\n\t\t}\r\n\t}\r\n\t\r\n\t// now map the given codes to a more efficient representation\r\n\t// create bytes out of 8 adjacent row-bits\r\n\tfor (int i=0; i < h; i++){\r\n\t\tfor (int j=0; j < w; j++){\r\n\t\t\tc=pow(2,7-(j%8));\r\n\t\t\tfor (int k = 0; k < 8; k++){\r\n\t\t\t\tif (i*8+k >=CODE_HEIGHT) break;\r\n\t\t\t\tcode[j][i]+=htlut[img.data[j/8+i*w+k*w/8]&c] * pow(2,7-k);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tiriscode.data=code;\r\n\treturn iriscode;\r\n}\r\n\r\n/** ------------------------------- commandline functions ------------------------------- **/\r\n\r\n/**\r\n * Parses a command line\r\n * This routine should be called for parsing command lines for executables.\r\n * Note, that all options require '-' as prefix and may contain an arbitrary\r\n * number of optional arguments.\r\n *\r\n * cmd: commandline representation\r\n * argc: number of parameters\r\n * argv: string array of argument values\r\n */\r\nvoid cmdRead(map<string ,vector<string> >& cmd, int argc, char *argv[]){\r\n\tfor (int i=1; i< argc; i++){\r\n\t\tchar * argument = argv[i];\r\n\t\tif (strlen(argument) > 1 && argument[0] == '-' && (argument[1] < '0' || argument[1] > '9')){\r\n\t\t\tcmd[argument]; // insert\r\n\t\t\tchar * argument2;\r\n\t\t\twhile (i + 1 < argc && (strlen(argument2 = argv[i+1]) <= 1 || argument2[0] != '-'  || (argument2[1] >= '0' && argument2[1] <= '9'))){\r\n\t\t\t\tcmd[argument].push_back(argument2);\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tCV_Error(CV_StsBadArg,\"Invalid command line format\");\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Checks, if each command line option is valid, i.e. exists in the options array\r\n *\r\n * cmd: commandline representation\r\n * validOptions: list of valid options separated by pipe (i.e. |) character\r\n */\r\nvoid cmdCheckOpts(map<string ,vector<string> >& cmd, const string validOptions){\r\n\tvector<string> tokens;\r\n\tconst string delimiters = \"|\";\r\n\tstring::size_type lastPos = validOptions.find_first_not_of(delimiters,0); // skip delimiters at beginning\r\n\tstring::size_type pos = validOptions.find_first_of(delimiters, lastPos); // find first non-delimiter\r\n\twhile (string::npos != pos || string::npos != lastPos){\r\n\t\ttokens.push_back(validOptions.substr(lastPos,pos - lastPos)); // add found token to vector\r\n\t\tlastPos = validOptions.find_first_not_of(delimiters,pos); // skip delimiters\r\n\t\tpos = validOptions.find_first_of(delimiters,lastPos); // find next non-delimiter\r\n\t}\r\n\tsort(tokens.begin(), tokens.end());\r\n\tfor (map<string, vector<string> >::iterator it = cmd.begin(); it != cmd.end(); it++){\r\n\t\tif (!binary_search(tokens.begin(),tokens.end(),it->first)){\r\n\t\t\tCV_Error(CV_StsBadArg,\"Command line parameter '\" + it->first + \"' not allowed.\");\r\n\t\t\ttokens.clear();\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\ttokens.clear();\r\n}\r\n\r\n/*\r\n * Checks, if a specific required option exists in the command line\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n */\r\nvoid cmdCheckOptExists(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n    if (it == cmd.end()) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' is required, but does not exist.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * size: appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptSize(map<string ,vector<string> >& cmd, const string option, const unsigned int size = 1){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it->second.size() != size) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' has unexpected size.\");\r\n}\r\n\r\n/*\r\n * Checks, if a specific option has the appropriate number of parameters\r\n *\r\n * cmd: commandline representation\r\n * option: option name\r\n * min: minimum appropriate number of parameters for the option\r\n * max: maximum appropriate number of parameters for the option\r\n */\r\nvoid cmdCheckOptRange(map<string ,vector<string> >& cmd, string option, unsigned int min = 0, unsigned int max = 1){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tunsigned int size = it->second.size();\r\n\tif (size < min || size > max) CV_Error(CV_StsBadArg,\"Command line parameter '\" + option + \"' is out of range.\");\r\n}\r\n\r\n/*\r\n * Returns the list of parameters for a given option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nvector<string> * cmdGetOpt(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\treturn (it != cmd.end()) ? &(it->second) : 0;\r\n}\r\n\r\n/*\r\n * Returns number of parameters in an option\r\n *\r\n * cmd: commandline representation\r\n * option: name of the option\r\n */\r\nunsigned int cmdSizePars(map<string ,vector<string> >& cmd, const string option){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\treturn (it != cmd.end()) ? it->second.size() : 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (int) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nint cmdGetParInt(map<string ,vector<string> >& cmd, string option, unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn atoi(it->second[param].c_str());\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (float) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nfloat cmdGetParFloat(map<string ,vector<string> >& cmd, const string option, const unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn atof(it->second[param].c_str());\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/*\r\n * Returns a specific parameter type (string) given an option and parameter index\r\n *\r\n * cmd: commandline representation\r\n * option: name of option\r\n * param: name of parameter\r\n */\r\nstring cmdGetPar(map<string ,vector<string> >& cmd, const string option, const unsigned int param = 0){\r\n\tmap<string, vector<string> >::iterator it = cmd.find(option);\r\n\tif (it != cmd.end()) {\r\n\t\tif (param < it->second.size()) {\r\n\t\t\treturn it->second[param];\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n/** ------------------------------- timing functions ------------------------------- **/\r\n\r\n/**\r\n * Class for handling timing progress information\r\n */\r\nclass Timing{\r\npublic:\r\n\t/** integer indicating progress with respect tot total **/\r\n\tint progress;\r\n\t/** total count for progress **/\r\n\tint total;\r\n\r\n\t/*\r\n\t * Default constructor for timing initializing time.\r\n\t * Automatically calls init()\r\n\t *\r\n\t * seconds: update interval in seconds\r\n\t * eraseMode: if true, outputs sends erase characters at each print command\r\n\t */\r\n\tTiming(long seconds, bool eraseMode){\r\n\t\tupdateInterval = seconds;\r\n\t\tprogress = 1;\r\n\t\ttotal = 100;\r\n\t\teraseCount=0;\r\n\t\terase = eraseMode;\r\n\t\tinit();\r\n\t}\r\n\r\n\t/*\r\n\t * Destructor\r\n\t */\r\n\t~Timing(){}\r\n\r\n\t/*\r\n\t * Initializes timing variables\r\n\t */\r\n\tvoid init(void){\r\n\t\tstart = boost::posix_time::microsec_clock::universal_time();\r\n\t\tlastPrint = start - boost::posix_time::seconds(updateInterval);\r\n\t}\r\n\r\n\t/*\r\n\t * Clears printing (for erase option only)\r\n\t */\r\n\tvoid clear(void){\r\n\t\tstring erase(eraseCount,'\\r');\r\n\t\terase.append(eraseCount,' ');\r\n\t\terase.append(eraseCount,'\\r');\r\n\t\tprintf(\"%s\",erase.c_str());\r\n\t\teraseCount = 0;\r\n\t}\r\n\r\n\t/*\r\n\t * Updates current time and returns true, if output should be printed\r\n\t */\r\n\tbool update(void){\r\n\t\tcurrent = boost::posix_time::microsec_clock::universal_time();\r\n\t\treturn ((current - lastPrint > boost::posix_time::seconds(updateInterval)) || (progress == total));\r\n\t}\r\n\r\n\t/*\r\n\t * Prints timing object to STDOUT\r\n\t */\r\n\tvoid print(void){\r\n\t\tlastPrint = current;\r\n\t\tfloat percent = 100.f * progress / total;\r\n\t\tboost::posix_time::time_duration passed = (current - start);\r\n\t\tboost::posix_time::time_duration togo = passed * (total - progress) / max(1,progress);\r\n\t\tif (erase) {\r\n\t\t\tstring erase(eraseCount,'\\r');\r\n\t\t\tprintf(\"%s\",erase.c_str());\r\n\t\t\tint newEraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000),togo.hours(),togo.minutes(),togo.seconds(),(int)(togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000));\r\n\t\t\tif (newEraseCount < eraseCount) {\r\n\t\t\t\tstring erase(newEraseCount-eraseCount,' ');\r\n\t\t\t\terase.append(newEraseCount-eraseCount,'\\r');\r\n\t\t\t\tprintf(\"%s\",erase.c_str());\r\n\t\t\t}\r\n\t\t\teraseCount = newEraseCount;\r\n\t\t}\r\n\t\telse {\r\n\t\t\teraseCount = (progress != total) ? printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03i Remaining ca. %i:%02i:%02i.%03i)\\n\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000),togo.hours(),togo.minutes(),togo.seconds(),(int)(togo.total_milliseconds() % 1000)) : printf(\"Progress ... %3.2f%% (%i/%i Total %i:%02i:%02i.%03d)\\n\",percent,progress,total,passed.hours(),passed.minutes(),passed.seconds(),(int)(passed.total_milliseconds()%1000));\r\n\t\t}\r\n\t}\r\nprivate:\r\n\tlong updateInterval;\r\n\tboost::posix_time::ptime start;\r\n\tboost::posix_time::ptime current;\r\n\tboost::posix_time::ptime lastPrint;\r\n\tint eraseCount;\r\n\tbool erase;\r\n};\r\n\r\n/** ------------------------------- file pattern matching functions ------------------------------- **/\r\n\r\n\r\n/*\r\n * Formats a given string, such that it can be used as a regular expression\r\n * I.e. escapes special characters and uses * and ? as wildcards\r\n *\r\n * pattern: regular expression path pattern\r\n * pos: substring starting index\r\n * n: substring size\r\n *\r\n * returning: escaped substring\r\n */\r\nstring patternSubstrRegex(string& pattern, size_t pos, size_t n){\r\n\tstring result;\r\n\tfor (size_t i=pos, e=pos+n; i < e; i++ ) {\r\n\t\tchar c = pattern[i];\r\n\t\tif ( c == '\\\\' || c == '.' || c == '+' || c == '[' || c == '{' || c == '|' || c == '(' || c == ')' || c == '^' || c == '$' || c == '}' || c == ']') {\r\n\t\t\tresult.append(1,'\\\\');\r\n\t\t\tresult.append(1,c);\r\n\t\t}\r\n\t\telse if (c == '*'){\r\n\t\t\tresult.append(\"([^/\\\\\\\\]*)\");\r\n\t\t}\r\n\t\telse if (c == '?'){\r\n\t\t\tresult.append(\"([^/\\\\\\\\])\");\r\n\t\t}\r\n\t\telse {\r\n\t\t\tresult.append(1,c);\r\n\t\t}\r\n\t}\r\n\treturn result;\r\n}\r\n\r\n/*\r\n * Converts a regular expression path pattern into a list of files matching with this pattern by replacing wildcards\r\n * starting in position pos assuming that all prior wildcards have been resolved yielding intermediate directory path.\r\n * I.e. this function appends the files in the specified path according to yet unresolved pattern by recursive calling.\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n * pos: an index such that positions 0...pos-1 of pattern are already considered/matched yielding path\r\n * path: the current directory (or empty)\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files, const size_t& pos, const string& path){\r\n\tsize_t first_unknown = pattern.find_first_of(\"*?\",pos); // find unknown * in pattern\r\n\tif (first_unknown != string::npos){\r\n\t\tsize_t last_dirpath = pattern.find_last_of(\"/\\\\\",first_unknown);\r\n\t\tsize_t next_dirpath = pattern.find_first_of(\"/\\\\\",first_unknown);\r\n\t\tif (next_dirpath != string::npos){\r\n\t\t\tboost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern,last_dirpath+1,next_dirpath-last_dirpath-1) : patternSubstrRegex(pattern,pos,next_dirpath-pos));\r\n\t\t\tboost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n\t\t\ttry {\r\n\t\t\t\tfor ( boost::filesystem::directory_iterator itr( ((path.length() > 0) ? path + pattern[pos-1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) : \"\")); itr != end_itr; ++itr )\r\n\t\t\t\t{\r\n\t\t\t\t\tif (boost::filesystem::is_directory(itr->path())){\r\n\t\t\t\t\t\tboost::filesystem::path p = itr->path().filename();\r\n\t\t\t\t\t\tstring s =  p.string();\r\n\t\t\t\t\t\tif (boost::regex_match(s.c_str(), expr)){\r\n\t\t\t\t\t\t\tpatternToFiles(pattern,files,(int)(next_dirpath+1),((path.length() > 0) ? path + pattern[pos-1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) + pattern[last_dirpath] : \"\") + s);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (boost::filesystem::filesystem_error &e){}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tboost::regex expr((last_dirpath != string::npos && last_dirpath > pos) ? patternSubstrRegex(pattern,last_dirpath+1,pattern.length()-last_dirpath-1) : patternSubstrRegex(pattern,pos,pattern.length()-pos));\r\n\t\t\tboost::filesystem::directory_iterator end_itr; // default construction yields past-the-end\r\n\t\t\ttry {\r\n\t\t\t\tfor ( boost::filesystem::directory_iterator itr(((path.length() > 0) ? path +  pattern[pos-1] : (last_dirpath != string::npos && last_dirpath > pos) ? \"\" : \"./\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) : \"\")); itr != end_itr; ++itr )\r\n\t\t\t\t{\r\n\t\t\t\t\tboost::filesystem::path p = itr->path().filename();\r\n\t\t\t\t\tstring s =  p.string();\r\n\t\t\t\t\tif (boost::regex_match(s.c_str(), expr)){\r\n\t\t\t\t\t\tfiles.push_back(((path.length() > 0) ? path + pattern[pos-1] : \"\") + ((last_dirpath != string::npos && last_dirpath > pos) ? pattern.substr(pos,last_dirpath-pos) + pattern[last_dirpath] : \"\") + s);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcatch (boost::filesystem::filesystem_error &e){}\r\n\t\t}\r\n\t}\r\n\telse { // no unknown symbols\r\n\t\tboost::filesystem::path file(((path.length() > 0) ? path + \"/\" : \"\") + pattern.substr(pos,pattern.length()-pos));\r\n\t\tif (boost::filesystem::exists(file)){\r\n\t\t\tfiles.push_back(file.string());\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/**\r\n * Converts a regular expression path pattern into a list of files matching with this pattern\r\n *\r\n * pattern: regular expression path pattern\r\n * files: the list to which new files can be applied\r\n */\r\nvoid patternToFiles(string& pattern, vector<string>& files){\r\n\tpatternToFiles(pattern,files,0,\"\");\r\n}\r\n\r\n/*\r\n * Renames a given filename corresponding to the actual file pattern using a renaming pattern.\r\n * Wildcards can be referred to as ?1, ?2, ... in the order they appeared in the file pattern.\r\n *\r\n * pattern: regular expression path pattern\r\n * renamePattern: renaming pattern using ?1, ?2, ... as placeholders for wildcards\r\n * infile: path of the file (matching with pattern) to be renamed\r\n * outfile: path of the renamed file\r\n * par: used parameter (default: '?')\r\n */\r\nvoid patternFileRename(string& pattern, const string& renamePattern, const string& infile, string& outfile, const char par = '?'){\r\n\tsize_t first_unknown = renamePattern.find_first_of(par,0); // find unknown ? in renamePattern\r\n\tif (first_unknown != string::npos){\r\n\t\tstring formatOut = \"\";\r\n\t\tfor (size_t i=0, e=renamePattern.length(); i < e; i++ ) {\r\n\t\t\tchar c = renamePattern[i];\r\n\t\t\tif ( c == par && i+1 < e) {\r\n\t\t\t\tc = renamePattern[i+1];\r\n\t\t\t\tif (c > '0' && c <= '9'){\r\n\t\t\t\t\tformatOut.append(1,'$');\r\n\t\t\t\t\tformatOut.append(1,c);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tformatOut.append(1,par);\r\n\t\t\t\t\tformatOut.append(1,c);\r\n\t\t\t\t}\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tformatOut.append(1,c);\r\n\t\t\t}\r\n\t\t}\r\n\t\tboost::regex patternOut(patternSubstrRegex(pattern,0,pattern.length()));\r\n\t\toutfile = boost::regex_replace(infile,patternOut,formatOut,boost::match_default | boost::format_perl);\r\n\t} else {\r\n\t\toutfile = renamePattern;\r\n\t}\r\n}\r\n\r\n/** ------------------------------- Program ------------------------------- **/\r\n\r\n/*\r\n * Main program\r\n */\r\nint main(int argc, char *argv[])\r\n{\t\r\n\tstd::vector<IrisCode> iriscodes;\r\n\t\r\n\tint mode = MODE_HELP;\r\n\tmap<string,vector<string> > cmd;\r\n\ttry {\r\n\t\tcmdRead(cmd,argc,argv);\r\n\t\tif (cmd.size() == 0 || cmdGetOpt(cmd,\"-h\") != 0) mode = MODE_HELP;\r\n\t\telse mode = MODE_MAIN;\r\n\t\tif (mode == MODE_MAIN){\r\n\t\t\t// validate command line\r\n\t\t\tcmdCheckOpts(cmd,\"-f|-s|-a|-c|-o|-h\");\r\n\t\t\tstring folder;\r\n\t\t\tif (cmdGetOpt(cmd,\"-f\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-f\",1);\r\n\t\t\t\tfolder = cmdGetPar(cmd,\"-f\");\r\n\t\t\t}\r\n\t\t\tint alg = ALG_3A;\r\n\t\t\tif (cmdGetOpt(cmd,\"-a\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-a\",1);\r\n\t\t\t\tstring algo = cmdGetPar(cmd,\"-a\");\r\n\t\t\t\tif (algo == \"3al\"){\r\n\t\t\t\t\talg = ALG_3AL;\r\n\t\t\t\t}\r\n\t\t\t\tif (algo == \"3as\"){\r\n\t\t\t\t\talg = ALG_3AS;\r\n\t\t\t\t}\r\n\t\t\t}\r\n            MAIN_MODE main_mode = DYNAMIC;\r\n            string outfilename = \"dynamic.txt\";\t\t\t\r\n\t\t\t// parameter for static mode\r\n\t\t\tint s = 5;\r\n\t\t\tif (cmdGetOpt(cmd,\"-s\") != 0){\r\n\t\t\t\tcmdCheckOptSize(cmd,\"-s\",1);\r\n\t\t\t\ts = cmdGetParInt(cmd,\"-s\");               \r\n                main_mode =  STATIC;\r\n                outfilename=\"static.txt\";\r\n            }\r\n\t\t\tfloat c = 0.33;\r\n\t\t\tif (cmdGetOpt(cmd,\"-c\") != 0){\r\n                cmdCheckOptSize(cmd,\"-c\",1);\r\n                c = cmdGetParFloat(cmd,\"-c\");\r\n                main_mode = DYNAMIC;\r\n                outfilename=\"dynamic.txt\";\r\n            }\r\n\r\n            if (cmdGetOpt(cmd,\"-o\") != 0){\r\n                \r\n                cmdCheckOptSize(cmd,\"-o\",1);\r\n                outfilename = cmdGetPar(cmd,\"-o\");\r\n            }\r\n\r\n\t\t\t// starting routine\r\n\t\t\tpath p(folder);\r\n\t\t\tcout << \"loading iriscodes...\" << endl;\r\n\t\t\tfor (auto i = directory_iterator(p); i != directory_iterator(); i++){\r\n\t\t\t\tif (!is_directory(i->path())){\r\n\t\t\t\t\tiriscodes.push_back(getCode(i->path().string(), c));\r\n\t\t\t\t}\r\n\t\t\t\telse continue;\r\n\t\t\t}\r\n\t\t\tcout << \"loaded \" << (int)iriscodes.size() << \" iriscodes\" << endl;\r\n\t\t\t\t\r\n\t\t\tofstream log;\r\n            log.open(outfilename, std::ios_base::app);                    \r\n            cout << \"output written to \" << outfilename << endl;\r\n            \r\n            if (  main_mode == STATIC){\r\n                // evaluation with static step size\r\n                cout << \"evaluation with static step size of \" << s << \" bit\" << endl;\r\n                for (int i=0; i<(int)iriscodes.size()-1; i++){\r\n                    for (int j=i+1; j<(int)iriscodes.size(); j++){\r\n                        if (i!=j) {\r\n                            if (alg == ALG_3A){\r\n                                TripleA(iriscodes.at(i), iriscodes.at(j), MIN_SHIFT, MAX_SHIFT, log, s);\r\n                            }\r\n                            else if (alg == ALG_3AL){\r\n                                TripleA_limited(iriscodes.at(i), iriscodes.at(j), MIN_SHIFT, MAX_SHIFT, log, s);\r\n                            }\r\n                            else {\r\n                                TripleA_singlesided(iriscodes.at(i), iriscodes.at(j), MIN_SHIFT, MAX_SHIFT, log, s);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            } else if ( main_mode == DYNAMIC){\r\n                // evaluation with dynamic step size\r\n                cout << \"evaluation with dynamic step size and constant of \" << c << \" bit\" << endl;\r\n                for (int i=0; i<(int)iriscodes.size()-1; i++){\r\n                    for (int j=i+1; j<(int)iriscodes.size(); j++){\r\n                        if (i!=j) {\r\n                            if (alg == ALG_3A){\r\n                                TripleA(iriscodes.at(i), iriscodes.at(j), MIN_SHIFT, MAX_SHIFT, log, iriscodes.at(i).stepsize);\r\n                            }\r\n                            else if (alg == ALG_3AL){\r\n                                TripleA_limited(iriscodes.at(i), iriscodes.at(j), MIN_SHIFT, MAX_SHIFT, log, iriscodes.at(i).stepsize);\r\n                            }\r\n                            else {\r\n                                TripleA_singlesided(iriscodes.at(i), iriscodes.at(j), MIN_SHIFT, MAX_SHIFT, log, iriscodes.at(i).stepsize);\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\t\t\tlog.close();\r\n    \t}\r\n    \telse if (mode == MODE_HELP){\r\n\t\t\t// validate command line\r\n\t\t\tcmdCheckOpts(cmd,\"-h\");\r\n\t\t\tif (cmdGetOpt(cmd,\"-h\") != 0) cmdCheckOptSize(cmd,\"-h\",0);\r\n\t\t\t// starting routine\r\n\t\t\tprintUsage();\r\n    \t}\r\n    }\r\n\tcatch (...){\r\n\t   \tprintf(\"Exit with errors.\\n\");\r\n\t   \texit(EXIT_FAILURE);\r\n\t}\r\n    return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "474e9c9a056423d661823236ee3b4cf70c194dfb", "size": 33544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/TripleA/TripleA.cpp", "max_stars_repo_name": "ngoclamvt123/usit-v2.2.0", "max_stars_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-20T12:40:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-17T20:04:22.000Z", "max_issues_repo_path": "packages/TripleA/TripleA.cpp", "max_issues_repo_name": "ngoclamvt123/usit-v2.2.0", "max_issues_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/TripleA/TripleA.cpp", "max_forks_repo_name": "ngoclamvt123/usit-v2.2.0", "max_forks_repo_head_hexsha": "3b2d27b7096e44eb41c786b4497b296ffd5a1519", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T01:51:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-10T02:49:06.000Z", "avg_line_length": 35.2723449001, "max_line_length": 545, "alphanum_fraction": 0.5530050083, "num_tokens": 9142, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22849830350066827}}
{"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string>\n\n#include \"hh_post_det_model.hpp\"\n//#include \"vgcc_det_model.hpp\"\n//#include \"pmca_det_model.hpp\"\n#include \"ca_sensor_gillespie_class.hpp\"\n#include \"vgcc_gillespie_class.hpp\"\n#include \"pmca_gillespie_class.hpp\"\n\n#include \"gillespie_class.hpp\"\n#include \"physical_constants.hpp\"\n#include \"stl_vector_operation_functions.hpp\"\n\n\n#include <boost/numeric/odeint.hpp> /*  Specifying the file within < > lets c++ search for it at -I path  */\n#include <boost/range/iterator_range.hpp>\n#include <boost/range/iterator.hpp>\n\nnamespace bno=boost::numeric::odeint;\nnamespace gill=astron::gillespie;\nnamespace g_vgcc=gill::vgcc;\nnamespace g_pmca=gill::pmca;\nnamespace consts=astron::phy_const;\n\ntypedef std::vector< double > state_type;\ntypedef state_type::iterator state_type_it;\ntypedef bno::runge_kutta4 < state_type > rk4_stepper_type;\n\n//-----------------\nint main(int argc, char *argv[])\n{\n  //-------------------------------------\n  std::string filename;         // Output filename variable\n  // decode arguments passed\n  if (argc < 2){\n    filename = argv[0];\n    std::cout << \"No filename prefix provided\" << std::endl;\n    filename = filename.substr(2,filename.length()-2) + \"_run\";\n  }\n  else{\n    filename = std::string(argv[1]);\n  }\n  std::ofstream fout(filename);\n  if (!fout){\n    std::cout << \"Error opening file \" << filename << \"\\n\";\n    return (0);\n  }\n  std::cout << \"File = \" << filename << std::endl;\n  // ----------------------------------\n  const double vol_pre = 1E-18;\t// Volume of whole presynaptic terminal\n  const double vol_pmca = 1E-18;\n  const double vol_vgcc = 1E-18;\n\n  double conCaIn = 100E-09;\t// Baseline Calcium concentration\n  int numCaIn = conCaIn * consts::Av * vol_pre * 1000; // Molarity in Liters 1L = 1000 * 10^-6 meter^3\n  \n   \n  // Initialize deterministic objects\n  rk4_stepper_type stepper;\n  \n  HH_POST hh_post(500E-12);                             // constructs an hh_pre object with 25 micron radius\n  state_type X_hh_post = {0,0,0,-80E-03};                    //{m,h,n,V}\n\n  //PMCA pmca(100E-09);                                   // constructs an PMCA object with 100 nM calcium concentration (intracellular)\n  //state_type X_pmca = {100E-09, 17E-03, 0, 0};          //{conCaIn, PMCA0, PMCA1, PMCA2}\n\n  //VGCC vgcc;                                            // constructs VGCCs\n  //state_type X_vgcc = {50, 0, 0, 0, 0};                //{C0, C1, C2, C3, O}\n  //-------------------------------------\n\n  // Initialize MCMC: PMCA\n  const int n_pmca = 1;\n  const int n_states_pmca = 5; \t// [NCa, Leak, PMCA0, PMCA1, PMCA2]\n  std::vector<int> X_pmca = {62,1530,1530,0,0}; // [NCa, NLeak, NPMCA0, PMCA1, PMCA2]\n  std::vector<g_pmca::pmca_gillespie_class> gpmca;\n  for(int i=0; i <n_pmca; i++){\n    gpmca.push_back(g_pmca::pmca_gillespie_class(1000,X_pmca));\n  }\n  // Initialize MCMC: VGCC \n  const int n_vgcc = 1;\n  const int n_states_vgcc = 5;\t// [C0 C1 C2 C3 O]\n  std::vector<int> X_vgcc = {50,0,0,0,0};\n  std::vector<g_vgcc::vgcc_gillespie_class> gvgcc;\n  for(int i=0; i <n_vgcc; i++){\n    gvgcc.push_back(g_vgcc::vgcc_gillespie_class(vol_vgcc,X_vgcc));\n  }\n  // Initialize MCMC: ca_sensors\n  //const int n_ca_sensors = 1; // number of individual Ca-sensors/vesicles\n  //const int n_states_ca_sensor=21; // number of Ca-sensor states\n  //std::vector<int> X_cas(n_states_ca_sensor); // State vector for ca_sensor initialization in state X0Y0;\n //for(int i=0;i<n_states_ca_sensor; i++){\n //  X_cas[i] = 0;\n //};\n //X_cas[0] = 7;\n //std::vector<gill::ca_sensor_gillespie_class> ca_sensors;    // ca_sensor object construction\n //for(int i=0; i<n_ca_sensors; i++){\n //  ca_sensors.push_back(gill::ca_sensor_gillespie_class(X_cas)); // Loads state to each ca_sensor\n //}\n ////-------------------------------------\n ////                      time(1) IExt(1) X_hh_post(4) vgcc(5) pmca(4) conCaIn(1) ca_sensor(21) spon_rel(1) syn_rel(1) asyn_rel(1) total_rel(1) = \n //const int n_param_out = (1) + 2+ 21; \n //std::vector< double > Y(11);                           // Ouput vector\n  //--------------------------------------\n  double t = 0.0;\n  const double dt = 10E-06;\n  const double tmax = 100E-03;\n  // -------------------------------------\n  \n  while (t <= tmax){\n    //std::cout << \"conCaIn = \" << conCaIn << \" numCaIn = \" << numCaIn << std::endl;\n\n    if( (t > 22E-03) && ( t < (24E-03 )) ){\n      hh_post.IExt = 20E-02;\t// External current to trigger presynaptic spike \n    }\n    if( (t >= 24E-03) && ( t <= (tmax )) ){\n      hh_post.IExt = 0;\n    }\n    stepper.do_step( hh_post, X_hh_post, t, dt); // update voltage\n\n    //gpmca[0].X[0] = numCaIn;     \n    for(int i=0; i<n_pmca; i++){\n      gillespie(gpmca[i],t,dt);\n    }\n    numCaIn = gpmca[0].X[0]; //abs(g_pmca::pmca_gillespie_class::numCaIn);\n    conCaIn = ((numCaIn) / (consts::Av * vol_pre * 1000));\n\n    g_vgcc::vgcc_gillespie_class::V = X_hh_post[3];\n    g_vgcc::vgcc_gillespie_class::conCaIn = conCaIn;\n    for(int i=0; i<n_vgcc; i++){\n      gillespie(gvgcc[i],t,dt);\n    }\n    numCaIn = numCaIn + abs(g_vgcc::vgcc_gillespie_class::numCaFlux);\n    conCaIn = numCaIn / (consts::Av * vol_pre * 1000);\n\n    fout << t << \" \" << X_hh_post << \" \" << gpmca[0].X << \" \" << gvgcc[0].X << \" \" << numCaIn << \" \" << conCaIn << std::endl;\n    //std::cout << t << \" \" << gpmca[0].X << std::endl;\n    //std::cin.get();\n    t = t + dt;\n  }\n  fout.close();\n  return 0;\n}\n\n// Extra codes\n  // g_pmca::pmca_gillespie_class::numCaIn = numCaIn;\n//g_vgcc::vgcc_gillespie_class::conCaIn = conCaIn;\t\t   // Set vgcc.conCaIn\n    //g_vgcc::vgcc_gillespie_class::V = X_hh_post[3];\t\t   // Set vgcc.V\n   // for(int i=0; i<n_vgcc; i++){\n   //   gillespie(gvgcc[i],t,dt);\n   // }\n    //conCaIn = conCaIn + (g_pmca::pmca_gillespie_class::numCaIn / (consts::Av * vol_pmca) ); // update conCaIn\n    \n    //vgcc.V = X_hh_post[3];\t// Feed presynaptic voltage to VGCC\n    //stepper.do_step( vgcc, X_vgcc, t,  dt); // update vgcc\n    //vgcc.update(dt, X_vgcc[4]);\n    //X_pmca[0]  = conCaIn; // update conCaIn of PMCA buffers\n    //stepper.do_step( pmca, X_pmca, t, dt);\n    //conCaIn = X_pmca[0];\t// update conCaIn\n    //numCaIn_ca_sensor = round(vgcc.numCaIn/10) + 1;//und((vgcc.numCaIn - 59) / 60 );//round((vgcc.conCaIn - 59) / 6 );\n    //gill::ca_sensor_gillespie_class::conCaIn = numCaIn_ca_sensor;\n    //for(int i=0; i<n_ca_sensors; i++){\n    //   gillespie(ca_sensors[i],t,dt);\n    //}\n\n   //Y[7] = gill::ca_sensor_gillespie_class::sponRelcount;\n   //Y[8] = gill::ca_sensor_gillespie_class::synRelcount;\n   //Y[9] = gill::ca_sensor_gillespie_class::asynRelcount;\n   //Y[10] = gill::ca_sensor_gillespie_class::totalRelcount;\n", "meta": {"hexsha": "d330c5a8e0c95fa3d759473f9d17fb08001dd7a7", "size": 6665, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/main_current.cpp", "max_stars_repo_name": "anupgp/astron", "max_stars_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old/src/old/main_current.cpp", "max_issues_repo_name": "anupgp/astron", "max_issues_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old/src/old/main_current.cpp", "max_forks_repo_name": "anupgp/astron", "max_forks_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.75, "max_line_length": 147, "alphanum_fraction": 0.6030007502, "num_tokens": 2239, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22844636044777084}}
{"text": "// Copyright 2018 Google LLC\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//      http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <stdint.h>  // NOLINT\n#include <algorithm>\n#include <iomanip>\n\n#include <Eigen/Dense>\n#include \"cpp/sensor_fusion/geometry_toolbox_mahony.h\"\n#include \"cpp/sensor_fusion/low_pass_filter.h\"\n#include \"cpp/sensor_fusion/orientation_filter.h\"\n#include \"cpp/sensor_fusion/stationary_detector.h\"\n\nnamespace {\n\n// Minimum time step between sensor updates. This corresponds to 1000 Hz.\nstatic const double kMinTimestepS = 0.001f;\n\n// Maximum time step between sensor updates. This corresponds to 1 Hz.\nstatic const double kMaxTimestepS = 1.0f;\n\n// Gravity constant in m.s^(-2).\nstatic const double kMagnitudeOfGravity = 9.81;\n\n// Small threshold to check if close to zero.\nstatic const double kEpsilon = 1e-9;\n\n// Number of runs for bias correction to remain static.\n// This is less than 1 sec.\nstatic const int kMagBiasCorrectionStaticCount = 40;\n\n// Small threshold used for mag initialization.\nstatic const double kMagInitTolerance = 1e-6;\n\n// Number of mag samples used for mag measurement initialization. 25 samples\n// correspond to ~.4 seconds for mag at 60 Hz.\nstatic const int kNumMagForInitialization = 25;\n\n// Number of continuous invalid mag measurement that results in temporarily\n// disabling mag fusion, unless new mag calibration is performed.\nstatic const int kNumMagForFilterOutlierRejection = 10;\n\n// Threshold of rejecting using one mag measurement. The value for this\n// threshold is in rad, which corresponds to 5 degree.\nstatic const double kMaxAllowedMagDeviationRadians = 0.0872665;\n\n// Threshold of using mag measurements on its timestamp. If the timestamp\n// between mag and gyro is larger than the given value, we simply do not use\n// the current mag measurement. This behavior happens in this multi-threaded\n// sensor fusion system, but not often.\nstatic const double kMaxTimeDifferentInMagAndGyroInSeconds = 0.003f;\n\n// Helper method to validate the time steps of sensor timestamps.\nbool IsTimestampDeltaValid(double timestamp_delta_s) {\n  if (timestamp_delta_s <= kMinTimestepS) {\n    return false;\n  }\n  if (timestamp_delta_s > kMaxTimestepS) {\n    return false;\n  }\n  return true;\n}\n\nmahony_filter::StationaryDetector::StationaryDetectorConfiguration\nGetStationaryDetectorConfig(double stationary_bias_correction_gain) {\n  mahony_filter::StationaryDetector::StationaryDetectorConfiguration\n      stationary_config;\n  stationary_config.stationary_bias_correction_gain =\n      stationary_bias_correction_gain;\n  return stationary_config;\n}\n\n}  // namespace\n\nOrientationFilter::OrientationFilter(\n    const OrientationFilterConfiguration& config)\n    : config_(config),\n      state_(Eigen::Matrix<double, 7, 1>::Zero()),\n      next_state_(Eigen::Matrix<double, 7, 1>::Zero()),\n      is_orientation_initialized_(false),\n      first_accel_timestamp_s_(0.0),\n      has_received_gyro_sample_(false),\n      mag_is_available_(false),\n      mag_low_pass_filter_(config.magnetometer_low_pass_cutoff_frequency),\n      accel_aligned_R_yaw_mag_aligned_(Eigen::Matrix3d::Identity()),\n      num_mag_measurements_for_yaw_initialization_(kNumMagForInitialization),\n      mag_meas_for_init_index_(0),\n      mag_bias_(Eigen::Vector3d::Zero()),\n      new_mag_calibration_available_(false),\n      mag_status_(MagStatus::kInitial),\n      accumulated_num_of_outlier_mag_measurement_(0),\n      current_mag_sample_fits_calibration_(false),\n      stationary_detector_(\n          GetStationaryDetectorConfig(config.stationary_bias_correction_gain)) {\n  // Initialize quaternions to start with the identity rotation.\n  state_(3) = 1.0;\n  next_state_(3) = 1.0;\n\n  // Initialize the data buffer for mag initialization.\n  projected_mag_measurement_vector_.resize(\n      Eigen::NoChange, num_mag_measurements_for_yaw_initialization_);\n\n  // Set bias of magnetometer calibrator when it's provided in configuration.\n  if (config_.init_mag_bias != Eigen::Vector3d::Zero()) {\n    SetMagBias(config_.init_mag_bias);\n  }\n}\n\nvoid OrientationFilter::Run() {\n  // Initialization for the filter orientation.\n  if (!is_orientation_initialized_ &&\n      current_accel_measurement_.timestamp_s > 0.0 &&\n      (config_.init_config ==\n           OrientationFilterConfiguration::InitialOrientationConfiguration::\n               kDontUseMagToInitOrientation ||\n       current_mag_measurement_.timestamp_s > 0.0)) {\n    is_orientation_initialized_ = OrientationFromAccelAndMag();\n  }\n\n  // Only start to propagate once the orientation has already been initialized\n  // by the accel / mag.\n  if (is_orientation_initialized_) {\n    FilterPropagate();\n  }\n}\n\nvoid OrientationFilter::RegisterOnBadMagnetometerCalibrationDetectedCallback(\n    std::function<void()>* on_bad_mag_calibration_detected_callback) {\n  on_bad_mag_calibration_detected_callbacks_.insert(\n      on_bad_mag_calibration_detected_callback);\n}\n\nvoid OrientationFilter::UnRegisterOnBadMagnetometerCalibrationDetectedCallback(\n    std::function<void()>* on_bad_mag_calibration_detected_callback) {\n  on_bad_mag_calibration_detected_callbacks_.erase(\n      on_bad_mag_calibration_detected_callback);\n}\n\nvoid OrientationFilter::BadMagnetometerCalibrationDetectedBroadcast() const {\n  for (auto callback : on_bad_mag_calibration_detected_callbacks_) {\n    if (callback) {\n      (*callback)();\n    }\n  }\n}\n\nvoid OrientationFilter::AddAccelMeasurement(const Eigen::Vector3d& sample,\n                                            double timestamp_s) {\n  if (first_accel_timestamp_s_ == 0.0) {\n    first_accel_timestamp_s_ = timestamp_s;\n    if (is_orientation_initialized_) {\n      // Check if the state is aligned with gravity and fix it if it is not.\n      const Eigen::Vector3d g_from_acc = sample.normalized();\n      const Eigen::Vector3d g_est = ComputeGravityEstimate();\n\n      double dot_product = g_from_acc.dot(g_est);\n      // Clamp dot_prodcut.\n      if (std::abs(dot_product) > 1.0) {\n        dot_product = (dot_product > 0.0 ? 1.0 : -1.0);\n      }\n      const double angular_error_deg = 180. / M_PI * acos(dot_product);\n      // TODO: Add a better gravity / acceleration check here.\n      if (std::abs(angular_error_deg) > 44) {\n        // The error after SetPose is too large. Correct directly the aligment\n        // with gravity.\n        const Eigen::Vector4d correction_quat =\n            geometry_toolbox::RotateInto(g_est, g_from_acc);\n\n        state_.head<4>() = geometry_toolbox::QuaternionMultiplication(\n            correction_quat, state_.head<4>());\n      }\n    }\n  }\n\n  current_accel_measurement_ = SensorSample(sample, timestamp_s);\n\n  if (IsStationaryBiasCorrectionEnabled()) {\n    stationary_detector_.AddAccelMeasurement(current_accel_measurement_.sample,\n                                             timestamp_s);\n  }\n\n  if (!has_received_gyro_sample_) {\n    // If we have not received a gyro sample supply fake gyro data to make use\n    // of every accel sample.\n    current_gyro_measurement_ =\n        SensorSample(Eigen::Vector3d::Zero(), timestamp_s);\n    Run();\n  }\n}\n\nvoid OrientationFilter::AddGyroMeasurement(const Eigen::Vector3d& sample,\n                                           double timestamp_s) {\n  current_gyro_measurement_ = SensorSample(sample, timestamp_s);\n\n  if (IsStationaryBiasCorrectionEnabled()) {\n    stationary_detector_.AddGyroMeasurement(current_gyro_measurement_.sample,\n                                            timestamp_s);\n  }\n\n  const double delta_t_s =\n      (timestamp_s - previous_gyro_measurement_.timestamp_s);\n  if (IsTimestampDeltaValid(delta_t_s)) {\n    if (!has_received_gyro_sample_) {\n      has_received_gyro_sample_ = true;\n    }\n    Run();\n  }\n\n  previous_gyro_measurement_ = current_gyro_measurement_;\n}\n\nvoid OrientationFilter::AddMagMeasurement(const Eigen::Vector3d& sample,\n                                          double timestamp_s,\n                                          bool fits_calibration) {\n  // First sample is only used for setting up the timeline.\n  if (current_mag_measurement_.timestamp_s == 0.0) {\n    current_mag_measurement_ = SensorSample(sample, timestamp_s);\n    current_mag_sample_fits_calibration_ = fits_calibration;\n    return;\n  }\n\n  const double mag_delta_time_s =\n      (timestamp_s - previous_mag_measurement_.timestamp_s);\n\n  // Use uncalibrated mag correction only if stationary correction is not\n  // enabled.\n  if (!IsStationaryBiasCorrectionEnabled()) {\n    // Now that the timestep is valid we can initialize the low_pass filter.\n    mag_low_pass_filter_.AddSampleData(sample, mag_delta_time_s);\n    if (mag_low_pass_filter_.IsInitialized()) {\n      previous_mag_measurement_ =\n          SensorSample(mag_low_pass_filter_.GetFilteredData(),\n                       current_mag_measurement_.timestamp_s);\n    }\n  } else {\n    previous_mag_measurement_ = current_mag_measurement_;\n  }\n\n  current_mag_measurement_ = SensorSample(sample, timestamp_s);\n  current_mag_sample_fits_calibration_ = fits_calibration;\n\n  // Only process valid mag sample.\n  mag_is_available_ = IsTimestampDeltaValid(mag_delta_time_s);\n}\n\nbool OrientationFilter::ComputeIterativeSolution(\n    const Eigen::VectorXd& mag_vector, const double initial_solution,\n    Eigen::Matrix3d* accel_aligned_R_yaw_mag_aligned) {\n  CHECK(accel_aligned_R_yaw_mag_aligned != nullptr);\n  double current_solution = initial_solution;\n\n  // Parameters for Gauss-Newton algorithm.\n  constexpr int kMaxIteration = 25;\n  constexpr double kNormCorrectionForConvergence = 1e-5;\n\n  int current_iteration = 0;\n  for (; current_iteration < kMaxIteration; ++current_iteration) {\n    // Estimated measurement and Jacobian for Gauss-Newton.\n    Eigen::Vector2d z_est(-std::sin(current_solution),\n                          std::cos(current_solution));\n    Eigen::Vector2d Jacobian(-std::cos(current_solution),\n                             -std::sin(current_solution));\n\n    double residual = 0;\n    double hessian = 0;\n\n    for (int i = 0; i < mag_vector.rows() / 2; ++i) {\n      const Eigen::Vector2d residual_i = z_est - mag_vector.segment<2>(i * 2);\n      residual += Jacobian.transpose() * residual_i;\n      hessian += Jacobian.transpose() * Jacobian;\n    }\n\n    double correction = -residual / hessian;\n    if (hessian < kMagInitTolerance) {\n      // Invalid Hessian, mag initialization fails.\n      return false;\n    }\n\n    current_solution += correction;\n\n    if (std::abs(correction) < kNormCorrectionForConvergence) {\n      break;\n    }\n  }\n\n  if (current_iteration >= kMaxIteration) {\n    // Maximum iteration reached, mag initialization fails.\n    return false;\n  }\n\n  *accel_aligned_R_yaw_mag_aligned << std::cos(current_solution),\n      -std::sin(current_solution), 0, std::sin(current_solution),\n      std::cos(current_solution), 0, 0, 0, 1;\n\n  return true;\n}\n\nbool OrientationFilter::ComputeYawAlignmentMatrix(\n    const Eigen::Matrix3Xd& mag_proj,\n    Eigen::Matrix3d* accel_aligned_R_yaw_mag_aligned) {\n  CHECK(accel_aligned_R_yaw_mag_aligned != nullptr);\n  const int num_rows = 2 * mag_proj.cols();\n  Eigen::VectorXd mag_vector(num_rows, 1);\n  for (int i = 0; i < mag_proj.cols(); ++i) {\n    if (mag_proj.col(i).head<2>().squaredNorm() < kMagInitTolerance) {\n      return false;\n    }\n\n    mag_vector.segment<2>(i * 2) = mag_proj.col(i).head<2>().normalized();\n  }\n\n  const double init_solution = -std::atan2(mag_vector(0), mag_vector(1));\n\n  return ComputeIterativeSolution(mag_vector, init_solution,\n                                  accel_aligned_R_yaw_mag_aligned);\n}\n\nbool OrientationFilter::OrientationFromAccelAndMag() {\n  Eigen::Vector3d L_x;\n  Eigen::Vector3d L_y;\n  Eigen::Vector3d L_z;\n  Eigen::Matrix<double, 3, 3> L_R_G;\n\n  // East-North-Up frame of reference:\n  //   - Gravity vector lies along +z axis\n  //   - Horizontal component of Mag vector lies along +y axis\n  //   - x-axis points east\n  L_z = current_accel_measurement_.sample.normalized();\n\n  switch (config_.init_config) {\n    case OrientationFilterConfiguration::InitialOrientationConfiguration::\n        kDontUseMagToInitOrientation: {\n      // Depending on whether we are portrait or landscape, this will\n      // be the direction we expect gravity to be pointing if the device\n      // is right-side-up.\n      Eigen::Vector3d canonical_down;\n      // Is it more in landscape or in portrait mode?\n      if (std::abs(L_z.dot(Eigen::Vector3d::UnitY())) <\n          std::abs(L_z.dot(Eigen::Vector3d::UnitX()))) {\n        // Landscape\n        L_y = Eigen::Vector3d::UnitY();\n        canonical_down = Eigen::Vector3d::UnitX();\n      } else {\n        // Portrait\n        L_y = -Eigen::Vector3d::UnitX();\n        canonical_down = Eigen::Vector3d::UnitY();\n      }\n      // Is it right-side-up or upside-down?\n      if (L_z.dot(canonical_down) < 0) {\n        L_y = -L_y;\n      }\n      break;\n    }\n    case OrientationFilterConfiguration::InitialOrientationConfiguration::\n        kUseMagToInitOrientation:\n      L_y = current_mag_measurement_.sample.normalized();\n      L_y -= L_z * L_z.transpose() * L_y;\n  }\n\n  L_x = -L_z.cross(L_y);\n  if (L_x.norm() == 0.0) {\n    return false;\n  }\n\n  L_x = L_x / L_x.norm();\n  L_y = L_z.cross(L_x);\n  if (L_y.norm() == 0.0) {\n    return false;\n  }\n\n  L_R_G.block<3, 1>(0, 0) = L_x;\n  L_R_G.block<3, 1>(0, 1) = L_y;\n  L_R_G.block<3, 1>(0, 2) = L_z;\n\n  // Compute and assign the quaternion of orientation from the resulting\n  // rotation matrix.\n  state_.block<4, 1>(0, 0) =\n      geometry_toolbox::RotationMatrixToQuaternion(L_R_G);\n\n  state_from_previous_mag_ = state_;\n  mag_is_available_ = false;\n  return true;\n}\n\nvoid OrientationFilter::FilterPropagate() {\n  // TODO: Orientation filter should be robust to different update\n  // frequency.\n  const double delta_t = current_gyro_measurement_.timestamp_s -\n                         previous_gyro_measurement_.timestamp_s;\n  if (!IsTimestampDeltaValid(delta_t)) {\n    return;\n  }\n\n  // Ignore the current mag measurement if it is too old.\n  if (mag_is_available_) {\n    const double gyro_time_ahead = current_gyro_measurement_.timestamp_s -\n                                   current_mag_measurement_.timestamp_s;\n\n    if (gyro_time_ahead > kMaxTimeDifferentInMagAndGyroInSeconds) {\n      // If this behavior happens very often, we should project previous mag\n      // measurement onto current timestamp, to do not waste too much data.\n      // In practice, in current experiments, this happens at a very low\n      // frequency.\n      mag_is_available_ = false;\n    }\n  }\n\n  Eigen::Matrix<double, 6, 1> gyro_measurements;\n  gyro_measurements.head<3>() = previous_gyro_measurement_.sample;\n  gyro_measurements.tail<3>() = current_gyro_measurement_.sample;\n  // Bias compensate the gyro data. Since imu_measurement format is\n  // [prev_x, prev_y, prev_z, curr_x, curr_y, curr_z] this can be accomplished\n  // by subtracting the bias_x, bias_y, bias_z from the appropriate elements.\n  const Eigen::Vector3d rate_correction = ComputeAccelAndMagRateCorrection();\n\n  gyro_measurements.head<3>() +=\n      (-state_.tail<3>() +\n       (IsInitializing()\n            ? config_.attitude_correction_gain_during_initialization\n            : config_.attitude_correction_gain) *\n           rate_correction);\n  gyro_measurements.tail<3>() +=\n      (-state_.tail<3>() +\n       (IsInitializing()\n            ? config_.attitude_correction_gain_during_initialization\n            : config_.attitude_correction_gain) *\n           rate_correction);\n\n  Eigen::Matrix<double, 4, 1> current_q, next_q;\n  current_q = state_.head<4>();\n  next_q = state_.head<4>();\n  quaternion_integrator_.Integrate(current_q, gyro_measurements, delta_t,\n                                   &next_q);\n  next_state_.head<4>() = next_q;\n  next_state_.tail<3>() =\n      state_.tail<3>() -\n      ((IsInitializing() ? 0.0 : config_.gyroscope_bias_correction_gain) *\n       delta_t * rate_correction);\n\n  // Bias correction if stationary.\n  if (IsStationaryBiasCorrectionEnabled()) {\n    next_state_.tail<3>() -=\n        delta_t *\n        stationary_detector_.GetGyroBiasCorrection(\n            next_state_.tail<3>(), current_gyro_measurement_.timestamp_s);\n  }\n  state_ = next_state_;\n\n  if (mag_is_available_) {\n    const double mag_delta_t = (current_mag_measurement_.timestamp_s -\n                                previous_mag_measurement_.timestamp_s);\n    if (!IsStationaryBiasCorrectionEnabled()) {\n      // Only apply this correction if the stationary bias correction is not\n      // enabled.\n      const Eigen::Vector3d mag_correction = EstimateBiasUpdateUsingMag();\n      state_.tail<3>() -=\n          mag_delta_t *\n          config_.magnetometer_gain_for_gyroscope_bias_estimation *\n          mag_correction;\n    }\n\n    state_from_previous_mag_ = state_;\n    mag_is_available_ = false;\n  }\n}\n\nEigen::Vector3d OrientationFilter::EstimateBiasUpdateUsingMag() {\n  if (!mag_low_pass_filter_.IsInitialized()) {\n    return Eigen::Vector3d::Zero();\n  }\n  // Check that gyro norm is below threshold. This is to ensure we only estimate\n  // drift when device is still and gyro signal is most likely due to drift.\n  const bool is_gyro_static =\n      current_gyro_measurement_.sample.norm() <\n      config_.maximum_allowed_gyro_norm_changed_for_mag_bias_correction;\n\n  // Check that mag norm is below threshold. This is to ensure we only estimate\n  // drift when device is still and mag signal is similar to noise.\n  const bool is_mag_static =\n      (previous_mag_measurement_.sample -\n       mag_low_pass_filter_.GetFilteredData())\n          .norm() < config_.maximum_allowed_magnitude_magnetometer_change_mt;\n  mag_low_pass_filter_.SetIsStatic(is_gyro_static && is_mag_static);\n\n  if (!mag_low_pass_filter_.GetIsStaticForN(kMagBiasCorrectionStaticCount)) {\n    return Eigen::Vector3d::Zero();\n  }\n\n  // Get down direction from both previous mag and current state.\n  const Eigen::Vector3d previous_accel_est =\n      geometry_toolbox::QuaternionToRotationMatrix(\n          state_from_previous_mag_.head<4>())\n          .col(2);\n  const Eigen::Vector3d previous_mag_est =\n      geometry_toolbox::QuaternionToRotationMatrix(\n          state_from_previous_mag_.head<4>())\n          .col(1);\n  const Eigen::Vector3d current_accel_est =\n      geometry_toolbox::QuaternionToRotationMatrix(state_.head<4>()).col(2);\n  const Eigen::Vector3d current_mag_est =\n      geometry_toolbox::QuaternionToRotationMatrix(state_.head<4>()).col(1);\n\n  // Grab the previous mag, remove gravity and normalize.\n  Eigen::Vector3d previous_mag_meas = previous_mag_measurement_.sample;\n  previous_mag_meas -=\n      previous_accel_est * previous_accel_est.transpose() * previous_mag_meas;\n  previous_mag_meas.normalize();\n\n  // Grab the current mag, remove gravity and normalize.\n  Eigen::Vector3d mag_meas = mag_low_pass_filter_.GetFilteredData();\n  mag_meas -= current_accel_est * current_accel_est.transpose() * mag_meas;\n  mag_meas.normalize();\n\n  return mag_meas.cross(previous_mag_meas) -\n         current_mag_est.cross(previous_mag_est);\n}\n\nEigen::Vector3d OrientationFilter::ComputeAccelAndMagRateCorrection() {\n  Eigen::Vector3d accel_meas = current_accel_measurement_.sample;\n  const double accel_magnitude = accel_meas.norm();\n  if (accel_magnitude < 1e-6) {\n    return Eigen::Vector3d::Zero();\n  }\n\n  accel_meas.normalize();\n  Eigen::Matrix<double, 3, 3> L_R_G_accel_aligned =\n      geometry_toolbox::QuaternionToRotationMatrix(state_.head<4>());\n  Eigen::Vector3d accel_est = L_R_G_accel_aligned.col(2);\n\n  // Dampen the effect of body acceleration. This is only applied when not\n  // initializing because it would otherwise slow down convergence.\n  double gain = 1.0;\n  const double gyro_norm = current_gyro_measurement_.sample.norm();\n  if (!IsInitializing()) {\n    // Don't update filter while moving too fast.\n    // TODO: Consider using something different than this, since most\n    // accelerometer sensors don't report 1G at rest.\n    gain /= (1.0 + std::abs(accel_magnitude - kMagnitudeOfGravity));\n\n    // Don't update filter while moving to fast.\n    // Use full gain between 0 and 0.1, dampen toward 0 between 0.1 to\n    // 0.3 rad.s^(-1).\n    // 1 __                  //\n    //     \\                 //\n    //      \\                //\n    //       \\______ 0.0     //\n    //  ^  ^  ^              //\n    //  0 .1  .3             //\n    gain *= std::max(0.0, std::min(1.0, 1.5 - 5.0 * gyro_norm));\n  } else {\n    // Use full gain between 0 and 0.04, dampen toward 0 between 0.04 to\n    // 0.1 rad.s^(-1).\n    // 1 __                  //\n    //     \\                 //\n    //      \\                //\n    //       \\______ 0.0     //\n    //  ^  ^  ^              //\n    //  0 .04  .1            //\n    gain *= std::max(0.0, std::min(1.0, 1.5 - 15.0 * gyro_norm));\n  }\n\n  Eigen::Vector3d rate_correction_vector = gain / 2 *\n                                           config_.accel_yaw_correction_gain *\n                                           accel_meas.cross(accel_est);\n\n  // Check if there is a valid mag sample ready to be consumed.\n  if (mag_is_available_ && current_mag_sample_fits_calibration_ &&\n      config_.mag_yaw_correction_gain > 0 &&\n      current_mag_measurement_.timestamp_s > 0) {\n    // First check if received a new mag calibration.\n    if (new_mag_calibration_available_) {\n      // Invalidate the existing mag alignement and force recompute.\n      mag_status_ = MagStatus::kAligning;\n      mag_meas_for_init_index_ = 0;\n      LOG(INFO) << \"SensorFusion: Received new bias, estimating alignment.\";\n      new_mag_calibration_available_ = false;\n    }\n\n    const Eigen::Vector3d current_calibrated_mag_measurement =\n        current_mag_measurement_.sample - mag_bias_;\n\n    // Compute estimated mag value, projected on yaw and represented locally.\n    Eigen::Vector3d mag_est_projection = current_calibrated_mag_measurement;\n    mag_est_projection -=\n        accel_est * accel_est.transpose() * mag_est_projection;\n    mag_est_projection.normalize();\n\n    // Estimate alignment between the filter orientation and magnetic north.\n    if (mag_status_ == MagStatus::kAligning) {\n      // Store the projected mag in a buffer that will be used by the iterative\n      // solver.\n      projected_mag_measurement_vector_.col(mag_meas_for_init_index_) =\n          L_R_G_accel_aligned.transpose() * mag_est_projection;\n\n      ++mag_meas_for_init_index_;\n\n      // Check if we have enough sample to run the iterative solver.\n      if (mag_meas_for_init_index_ ==\n          num_mag_measurements_for_yaw_initialization_) {\n        if (ComputeYawAlignmentMatrix(projected_mag_measurement_vector_,\n                                      &accel_aligned_R_yaw_mag_aligned_)) {\n          // In this case, mag is successfully initialized.\n          mag_status_ = MagStatus::kAligned;\n        } else {\n          // Mag initialization fails. Clear mag measurements, and re-start data\n          // collection.\n          mag_meas_for_init_index_ = 0;\n          LOG(INFO) << \"SensorFusion: Mag alignment failed in orientation \"\n                       \"tracker. Will retry.\";\n        }\n      }\n    }\n\n    Eigen::Vector3d mag_meas = current_calibrated_mag_measurement;\n    mag_meas -= accel_meas * accel_meas.transpose() * mag_meas;\n    if (mag_meas.norm() < 1e-6) {\n      return Eigen::Vector3d();\n    }\n    mag_meas.normalize();\n\n    if (mag_status_ == MagStatus::kAligned) {\n      // Magnetometer is calibrated and aligned with the filter now so we can\n      // use it for yaw correction.\n      mag_is_available_ = false;\n\n      const Eigen::Vector3d mag_est =\n          (L_R_G_accel_aligned * accel_aligned_R_yaw_mag_aligned_).col(1);\n\n      // Test whether the current mag estimate and mag measurement diverge too\n      // much.\n      const double angle_between_est_and_meas =\n          std::acos(mag_est_projection.dot(mag_est));\n\n      if (angle_between_est_and_meas > kMaxAllowedMagDeviationRadians) {\n        ++accumulated_num_of_outlier_mag_measurement_;\n        if (accumulated_num_of_outlier_mag_measurement_ >\n            kNumMagForFilterOutlierRejection) {\n          // Invalidate the existing mag alignement and force recompute.\n          mag_status_ = MagStatus::kAligning;\n          state_from_previous_mag_ = state_;\n          mag_meas_for_init_index_ = 0;\n          LOG(INFO) << \"Consistently received outlier measurements, resetting.\";\n          BadMagnetometerCalibrationDetectedBroadcast();\n          accumulated_num_of_outlier_mag_measurement_ = 0;\n        }\n      } else {\n        rate_correction_vector +=\n            config_.mag_yaw_correction_gain * mag_meas.cross(mag_est);\n\n        accumulated_num_of_outlier_mag_measurement_ = 0;\n      }\n    }\n  }\n\n  return rate_correction_vector;\n}\n\nvoid OrientationFilter::Recenter() {\n  // This function enforces two constraints on the updated L_R_G_recenter\n  // - The gravity direction is kept\n  //    L_R_G_recenter * z = L_R_G * z\n  // - yaw is equal to zero\n  //    L_R_G_recenter^{-1} * -z  =[sin(pitch) 0 cos(pitch)]\n  // Notation:\n  // L_R_G^{-1} * -z =  [cos(yaw) * sin(pitch) sin(yaw) cos(yaw) * cos(pitch)]\n\n  //\n  // We can deduce that\n  // L_R_G_recenter(:,3) == L_R_G(:,3) (1)\n  // L_R_G_recenter(3,2) = 0.0 (2)\n  //\n  // As L_R_G is an orthonormal matrix\n  // |L_R_G(:,2)| = 1 (3)\n  //\n  // Combining (2) and (3)\n  // |L_R_G(1:2,2)| = 1 (4)\n  // L_R_G(1:2,2) . L_R_G(1:2,3) = 0  (5) Orthogonality\n  //\n  // if L_R_G(1,3) >  Eps\n  // L_R_G(2,2) =  +/- sqrt( 1 / ( 1 + (L_R_G(2,3) / L_R_G(1,3))^2)) (6)\n  // L_R_G(1,2) = - L_R_G(2,2) * L_R_G(2,3) / L_R_G(1,3)\n  //\n  // Finally we use the orthogonality constraint for the first column\n  // L_R_G(:,1) = L_R_G(:,2) x L_R_G(:,3)\n\n  const Eigen::Matrix3d L_R_G =\n      geometry_toolbox::QuaternionToRotationMatrix(state_.head<4>());\n\n  Eigen::Matrix3d L_R_G_recentered;\n  // Keep down direction the same (1).\n  L_R_G_recentered.block<3, 1>(0, 2) = L_R_G.block<3, 1>(0, 2);\n\n  if (std::abs(L_R_G(0, 2)) < kEpsilon) {\n    // Arbitrary deciding to use X axis.\n    L_R_G_recentered(0, 1) = 1.0;\n    L_R_G_recentered(1, 1) = 0.0;\n  } else {\n    const double x_y_ratio = L_R_G(1, 2) / L_R_G(0, 2);  // Eq. (6)\n    // The sign  is kept positive to enforce \"forwardness\".\n    L_R_G_recentered(1, 1) = sqrt(1.0 / (1 + x_y_ratio * x_y_ratio));\n    L_R_G_recentered(0, 1) = -L_R_G_recentered(1, 1) * x_y_ratio;\n  }\n  L_R_G_recentered(2, 1) = 0.0;  // Eq. (2)\n\n  // Enforce orthogonality.\n  L_R_G_recentered.block<3, 1>(0, 0) = L_R_G_recentered.block<3, 1>(0, 1).cross(\n      L_R_G_recentered.block<3, 1>(0, 2));\n\n  state_.head<4>() =\n      geometry_toolbox::RotationMatrixToQuaternion(L_R_G_recentered);\n\n  // Reset the mag based bias update by setting the previous state to current\n  // state. This avoids using the change in pose due to recentering for bias\n  // update.\n  state_from_previous_mag_ = state_;\n}\n", "meta": {"hexsha": "4ac4f81524b778fa7d2aeba607f48ff1b4e5b472", "size": 27226, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/sensor_fusion/orientation_filter.cc", "max_stars_repo_name": "google/vr180", "max_stars_repo_head_hexsha": "f55eaa1c6835b911b7a11830ec546636a16d49da", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2018-12-09T17:58:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T11:43:24.000Z", "max_issues_repo_path": "cpp/sensor_fusion/orientation_filter.cc", "max_issues_repo_name": "google/vr180", "max_issues_repo_head_hexsha": "f55eaa1c6835b911b7a11830ec546636a16d49da", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T06:01:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T09:49:29.000Z", "max_forks_repo_path": "cpp/sensor_fusion/orientation_filter.cc", "max_forks_repo_name": "google/vr180", "max_forks_repo_head_hexsha": "f55eaa1c6835b911b7a11830ec546636a16d49da", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2019-05-25T02:18:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:35:03.000Z", "avg_line_length": 37.3983516484, "max_line_length": 80, "alphanum_fraction": 0.6868067289, "num_tokens": 6766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.22843307342342642}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_GSTMERC_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_GSTMERC_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 4.9.1\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/pj_phi2.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/pj_tsfn.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace gstmerc\n    {\n\n            struct par_gstmerc\n            {\n                double lamc;\n                double phic;\n                double c;\n                double n1;\n                double n2;\n                double XS;\n                double YS;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_gstmerc_spheroid : public base_t_fi<base_gstmerc_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_gstmerc m_proj_parm;\n\n                inline base_gstmerc_spheroid(const Parameters& par)\n                    : base_t_fi<base_gstmerc_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    double L, Ls, sinLs1, Ls1;\n                    L= this->m_proj_parm.n1*lp_lon;\n                    Ls= this->m_proj_parm.c+this->m_proj_parm.n1*log(pj_tsfn(-1.0*lp_lat,-1.0*sin(lp_lat),this->m_par.e));\n                    sinLs1= sin(L)/cosh(Ls);\n                    Ls1= log(pj_tsfn(-1.0*asin(sinLs1),0.0,0.0));\n                    xy_x= (this->m_proj_parm.XS + this->m_proj_parm.n2*Ls1)*this->m_par.ra;\n                    xy_y= (this->m_proj_parm.YS + this->m_proj_parm.n2*atan(sinh(Ls)/cos(L)))*this->m_par.ra;\n                    /*fprintf(stderr,\"fwd:\\nL      =%16.13f\\nLs     =%16.13f\\nLs1    =%16.13f\\nLP(%16.13f,%16.13f)=XY(%16.4f,%16.4f)\\n\",L,Ls,Ls1,lp_lon+this->m_par.lam0,lp_lat,(xy_x*this->m_par.a + this->m_par.x0)*this->m_par.to_meter,(xy_y*this->m_par.a + this->m_par.y0)*this->m_par.to_meter);*/\n                }\n\n                // INVERSE(s_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    double L, LC, sinC;\n                    L= atan(sinh((xy_x*this->m_par.a - this->m_proj_parm.XS)/this->m_proj_parm.n2)/cos((xy_y*this->m_par.a - this->m_proj_parm.YS)/this->m_proj_parm.n2));\n                    sinC= sin((xy_y*this->m_par.a - this->m_proj_parm.YS)/this->m_proj_parm.n2)/cosh((xy_x*this->m_par.a - this->m_proj_parm.XS)/this->m_proj_parm.n2);\n                    LC= log(pj_tsfn(-1.0*asin(sinC),0.0,0.0));\n                    lp_lon= L/this->m_proj_parm.n1;\n                    lp_lat= -1.0*pj_phi2(exp((LC-this->m_proj_parm.c)/this->m_proj_parm.n1),this->m_par.e);\n                    /*fprintf(stderr,\"inv:\\nL      =%16.13f\\nsinC   =%16.13f\\nLC     =%16.13f\\nXY(%16.4f,%16.4f)=LP(%16.13f,%16.13f)\\n\",L,sinC,LC,((xy_x/this->m_par.ra)+this->m_par.x0)/this->m_par.to_meter,((xy_y/this->m_par.ra)+this->m_par.y0)/this->m_par.to_meter,lp_lon+this->m_par.lam0,lp_lat);*/\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"gstmerc_spheroid\";\n                }\n\n            };\n\n            // Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion)\n            template <typename Parameters>\n            void setup_gstmerc(Parameters& par, par_gstmerc& proj_parm)\n            {\n                proj_parm.lamc= par.lam0;\n                proj_parm.n1= sqrt(1.0+par.es*pow(cos(par.phi0),4.0)/(1.0-par.es));\n                proj_parm.phic= asin(sin(par.phi0)/proj_parm.n1);\n                proj_parm.c=       log(pj_tsfn(-1.0*proj_parm.phic,0.0,0.0))\n                     -proj_parm.n1*log(pj_tsfn(-1.0*par.phi0,-1.0*sin(par.phi0),par.e));\n                proj_parm.n2= par.k0*par.a*sqrt(1.0-par.es)/(1.0-par.es*sin(par.phi0)*sin(par.phi0));\n                proj_parm.XS= 0;/* -par.x0 */\n                proj_parm.YS= -1.0*proj_parm.n2*proj_parm.phic;/* -par.y0 */\n                /*fprintf(stderr,\"a  (m) =%16.4f\\ne      =%16.13f\\nl0(rad)=%16.13f\\np0(rad)=%16.13f\\nk0     =%16.4f\\nX0  (m)=%16.4f\\nY0  (m)=%16.4f\\n\\nlC(rad)=%16.13f\\npC(rad)=%16.13f\\nc      =%16.13f\\nn1     =%16.13f\\nn2 (m) =%16.4f\\nXS (m) =%16.4f\\nYS (m) =%16.4f\\n\", par.a, par.e, par.lam0, par.phi0, par.k0, par.x0, par.y0, proj_parm.lamc, proj_parm.phic, proj_parm.c, proj_parm.n1, proj_parm.n2, proj_parm.XS +par.x0, proj_parm.YS + par.y0);*/\n            }\n\n        }} // namespace detail::gstmerc\n    #endif // doxygen\n\n    /*!\n        \\brief Gauss-Schreiber Transverse Mercator (aka Gauss-Laborde Reunion) projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Cylindrical\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - lat_0: Latitude of origin\n         - lon_0: Central meridian\n         - k_0: Scale factor\n        \\par Example\n        \\image html ex_gstmerc.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct gstmerc_spheroid : public detail::gstmerc::base_gstmerc_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline gstmerc_spheroid(const Parameters& par) : detail::gstmerc::base_gstmerc_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::gstmerc::setup_gstmerc(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Factory entry(s)\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class gstmerc_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<gstmerc_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void gstmerc_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"gstmerc\", new gstmerc_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_GSTMERC_HPP\n\n", "meta": {"hexsha": "b73ef80a226e862cdc32ba4d3c58746ad08e1ebd", "size": 9230, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/gstmerc.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T05:02:05.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/gstmerc.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/gstmerc.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-04T10:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T18:52:06.000Z", "avg_line_length": 49.8918918919, "max_line_length": 448, "alphanum_fraction": 0.6334777898, "num_tokens": 2450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.22812457749095047}}
{"text": "//---------------------------------------------------------------------------//\n//  MIT License\n//\n//  Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n//  Copyright (c) 2020-2021 Nikita Kaskov <nemo@nil.foundation>\n\n//\n//  Permission is hereby granted, free of charge, to any person obtaining a copy\n//  of this software and associated documentation files (the \"Software\"), to deal\n//  in the Software without restriction, including without limitation the rights\n//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n//  copies of the Software, and to permit persons to whom the Software is\n//  furnished to do so, subject to the following conditions:\n//\n//  The above copyright notice and this permission notice shall be included in all\n//  copies or substantial portions of the Software.\n//\n//  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n//  SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef FILECOIN_STORAGE_PROOFS_CORE_MERKLE_PROOF_HPP\n#define FILECOIN_STORAGE_PROOFS_CORE_MERKLE_PROOF_HPP\n\n#include <algorithm>\n#include <vector>\n\n#include <boost/variant.hpp>\n\n#include <nil/crypto3/hash/algorithm/hash.hpp>\n\n#include <nil/filecoin/storage/proofs/core/merkle/merkle.hpp>\n#include <nil/filecoin/storage/proofs/core/proof/proof.hpp>\n#include <nil/filecoin/storage/proofs/core/crypto/feistel.hpp>\n#include <nil/filecoin/storage/proofs/core/path_element.hpp>\n\nnamespace nil {\n    namespace filecoin {\n        namespace merkletree {\n            template<std::size_t A, std::size_t B, std::size_t C>\n            std::size_t base_path_length(std::size_t leaves) {\n                std::size_t l;\n                if (C > 0) {\n                    l = leaves / C / B;\n                } else if (B > 0) {\n                    l = leaves / B;\n                } else {\n                    l = leaves;\n                }\n\n                return graph_height<A>(l) - 1;\n            }\n\n            template<std::size_t A, std::size_t B, std::size_t C>\n            std::size_t compound_path_length(std::size_t leaves) {\n                std::size_t len = base_path_length<A, B, C>(leaves);\n                if (B > 0) {\n                    len += 1;\n                }\n\n                if (C > 0) {\n                    len += 1;\n                }\n\n                return len;\n            }\n\n            template<std::size_t A, std::size_t B, std::size_t C>\n            std::size_t compound_tree_height(std::size_t leaves) {\n                // base layer\n                std::size_t a = graph_height<A>(leaves) - 1;\n\n                // sub tree layer\n                std::size_t b;\n                if (B > 0) {\n                    b = B - 1;\n                } else {\n                    b = 0;\n                }\n\n                // top tree layer\n                std::size_t c;\n                if (C > 0) {\n                    c = C - 1;\n                } else {\n                    c = 0;\n                }\n\n                return a + b + c;\n            }\n\n            template<typename Hash>\n            struct Proof_basic_policy {\n                typedef std::array<uint8_t, Hash::digest_size> hash_result_type;\n                constexpr static const std::size_t hash_digest_size = Hash::digest_size;\n            };\n\n            template<typename Hash, std::size_t BaseTreeArity = 2>\n            struct Proof {\n\n                typedef typename MerkleTree_basic_policy<Hash>::hash_result_type element;\n                constexpr static const std::size_t element_size = MerkleTree_basic_policy<Hash>::hash_digest_size;\n\n                // Optional proofs at immediate lower level from current.  Should\n                // be None at the base layer.\n                std::shared_ptr<Proof<element, BaseTreeArity>> sub_tree_proof;\n                std::size_t top_layer_nodes;         // arity of top layer\n                std::size_t sub_tree_layer_nodes;    // arity of sub-tree\n                std::vector<element> lemma; // layer\n                std::vector<std::size_t> path; // branch index\n\n                /// Creates new MT inclusion proof\n                template<std::size_t TopLayerArity, std::size_t SubTreeArity>\n                Proof(std::shared_ptr<Proof<element, BaseTreeArity>> sub_tree_proof, const std::vector<element> &lemma, const\n                      std::vector<std::size_t> &path) : sub_tree_proof(sub_tree_proof), top_layer_nodes(TopLayerArity),\n                    sub_tree_layer_nodes(SubTreeArity), lemma(lemma), path(path){\n                    if (TopLayerArity == 0 && SubTreeArity == 0) {\n                        BOOST_ASSERT_MSG(lemma.size() > 2, \"Invalid lemma length (short)\");\n                        BOOST_ASSERT_MSG(lemma.size() == utilities::get_merkle_proof_lemma_len(path.size() + 1, BaseTreeArity),\n                            \"Invalid lemma length\");\n                    }\n                }\n\n                /// Return proof target leaf\n                element item() {\n                    return *lemma.begin();\n                }\n\n                /// Return sub tree root\n                element sub_tree_root() {\n                    assert(sub_tree_layer_nodes > 0 && sub_tree_proof.is_some());\n                    return sub_tree_proof.root();\n                }\n\n                /// Return tree root\n                element root() {\n                    return *(lemma.end() - 1);\n                }\n\n                /// Validates sub-tree proofs with the specified arity.\n                bool validate_sub_tree_proof(std::size_t arity) {\n                    // Ensure that the sub_tree validates to the root of that\n                    // sub_tree.\n                    bool valid = sub_tree_proof.unwrap().validate::<Algorithm<element>>();\n                    if (!valid) {\n                            return valid;\n                        }\n\n                    // Validate top-most/current layer\n                    //\n                    // Check that the remaining proof matches the tree root (note\n                    // that Proof::validate at the base layer cannot handle a\n                    // proof this small, so this is a version specific for what we\n                    // know we have in this case).\n                    auto a = Algorithm<T>::default();\n                    a.reset();\n                    const auto node_count = arity;\n                    const auto h = {\n                        std::vector<T> nodes;\n                        nodes.reserve(node_count);\n\n                        auto cur_index = 0;\n                        for (const auto j = 0; j < node_count; ++j) {\n                            if j == self.path()[0] {\n                                nodes.push(self.sub_tree_root().clone());\n                            } else {\n                                nodes.push(self.lemma()[cur_index].clone());\n                                cur_index += 1;\n                            }\n                        }\n\n                        if cur_index != node_count - 1 {\n                            return false;\n                        }\n\n                        a.multi_node(&nodes, 0)\n                    };\n\n                    return h == root();\n                }\n\n                /// Verifies MT inclusion proof\n                bool validate() {\n                    if (top_layer_nodes > 0) {\n                        // Special Top layer handling here.\n                        BOOST_ASSERT_MSG(sub_tree_proof,\n                                \"Sub tree proof must be present for validation\");\n\n                        return validate_sub_tree_proof<Algorithm>(top_layer_nodes);\n                    }\n\n                    if (sub_tree_layer_nodes > 0) {\n                        // Sub-tree layer handling here.\n                        BOOST_ASSERT_MSG(sub_tree_proof,\n                                \"Sub tree proof must be present for validation\");\n\n                        return validate_sub_tree_proof<Algorithm>(sub_tree_layer_nodes);\n                    }\n\n                    // Base layer handling here.\n                    BOOST_ASSERT_MSG(sub_tree_layer_nodes == 0, \"Base layer proof must have 0 as sub-tree layer node count\");\n                    BOOST_ASSERT_MSG(top_layer_nodes == 0, \"Base layer proof must have 0 as top layer node count\");\n                    BOOST_ASSERT_MSG(!sub_tree_proof, \"Sub tree proof must be None\");\n\n                    std::size_t size = lemma.size();\n                    if (size < 2) {\n                        return false;\n                    }\n\n                    std::size_t branches = BaseTreeArity;\n                    auto a = Algorithm<element>::default();\n                    auto h = this->item();\n                    auto path_index = 1;\n\n                    for (size_t i = 1; i < size - 1; i += branches - 1) {\n                        a.reset();\n                        h = {\n                            std::vector<element> nodes;\n                            nodes.reserve(branches);\n                            auto cur_index = 0;\n                            for (j = 0; j < branches; ++j) {\n                                if j == self.path[path_index - 1] {\n                                    nodes.push(h.clone());\n                                } else {\n                                    nodes.push(self.lemma[i + cur_index].clone());\n                                    cur_index += 1;\n                                }\n                            }\n\n                            if cur_index != branches - 1 {\n                                return false;\n                            }\n\n                            path_index += 1;\n                            a.multi_node(&nodes, i - 1)\n                        };\n                    }\n\n                    return h == root();\n                }\n\n                    /// Verifies MT inclusion proof and that leaf_data is the original leaf data for which proof was generated.\n                template<template<typename> class Algorithm>\n                bool validate_with_data(leaf_data: &dyn Hashable<A>) {\n                    auto a = Algorithm<T>::default();\n                    leaf_data.hash(&a);\n                    const auto item = a.hash();\n                    a.reset();\n                    const auto leaf_hash = a.leaf(item);\n\n                    if (leaf_hash == item()) {\n                        return validate<Algorithm>();\n                    } else {\n                        return false;\n                    }\n                }\n            };\n\n//            /// Interface to abstract over the concept of Merkle Proof.\n//            template<typename Hash, std::size_t BaseArity, std::size_t SubTreeArity, std::size_t TopTreeArity,\n//                     typename FieldType = typename crypto3::algebra::curves::bls12<381>::scalar_field_type>\n//            struct BasicMerkleProof {\n//                typedef Hash hash_type;\n//                typedef FieldType field_type;\n//                typedef typename field_type::value_type fr_value_type;\n//\n//                constexpr static const std::size_t base_arity = BaseArity;\n//                constexpr static const std::size_t sub_tree_arity = SubTreeArity;\n//                constexpr static const std::size_t top_tree_arity = TopTreeArity;\n//\n//                /// Try to convert a merkletree proof into this structure.\n//                static BasicMerkleProof<Hash, BaseArity, SubTreeArity, TopTreeArity>\n//                    try_from_proof(const Proof<typename Hash::digest_type, BaseArity> &p) {\n//                }\n//\n//                std::vector<std::pair<std::vector<fr_value_type>, std::size_t>> as_options() {\n//                    return path()\n//                        .iter()\n//                        .map(| v | {(v .0.iter().copied().map(Into::into).map(Some).collect(), Some(v .1), )})\n//                        .collect::<Vec<_>>();\n//                }\n//\n//                std::pair<fr_value_type, std::vector<std::pair<std::vector<fr_value_type>, std::size_t>>>\n//                    into_options_with_leaf() {\n//                    const auto leaf = leaf();\n//                    const auto path = path();\n//                    (Some(leaf.into()),\n//                     path.into_iter()\n//                         .map(| (a, b) | {(a.iter().copied().map(Into::into).map(Some).collect(), Some(b), )})\n//                         .collect::<Vec<_>>(), )\n//                }\n//\n//                std::vector<std::pair<std::vector<fr_value_type>, std::size_t>> as_pairs() {\n//                    for (int i = 0; i < path().size(); i++) {\n//\n//                    }\n//                        .iter()\n//                        .map(| v | (v .0.iter().copied().map(Into::into).collect(), v .1))\n//                        .collect::<Vec<_>>();\n//                }\n//\n//                virtual bool verify() const = 0;\n//\n//                /// Validates the MerkleProof and that it corresponds to the supplied node.\n//                ///\n//                /// TODO: audit performance and usage in case verification is\n//                /// unnecessary based on how it's used.\n//                virtual bool validate(std::size_t node) {\n//                    if (!verify()) {\n//                        return false;\n//                    }\n//\n//                    return node == path_index();\n//                }\n//\n//                virtual bool validate_data(const typename Hash::digest_type &data) {\n//                    if (!verify()) {\n//                        return false;\n//                    }\n//\n//                    return leaf() == data;\n//                }\n//\n//                virtual typename Hash::digest_type leaf() = 0;\n//                virtual typename Hash::digest_type root() = 0;\n//                virtual std::size_t size() = 0;\n//                virtual std::vector<std::pair<std::vector<typename Hash::digest_type>, std::size_t>> path() = 0;\n//\n//                std::size_t path_index() {\n//                    return std::accumulate(\n//                        path().begin(), path().end(), 0,\n//                        [&](std::size_t acc, typename std::vector<std::pair<std::vector<typename Hash::digest_type>,\n//                                                                            std::size_t>>::value_type &val) -> std::size_t {\n//                            return (acc + BaseArity) + val.second;\n//                        });\n//                }\n//\n//                bool proves_challenge(std::size_t challenge) {\n//                    path_index() == challenge;\n//                }\n//\n//                /// Calcluates the exected length of the full path, given the number of leaves in the base layer.\n//                std::size_t expected_len(std::size_t leaves) {\n//                    return compound_path_length<BaseArity, SubTreeArity, TopTreeArity>(leaves);\n//                }\n//            };\n//\n//            template<typename Hash, std::size_t BaseArity>\n//            struct InclusionPath {\n//                /// Calculate the root of this path, given the leaf as input.\n//                typename Hash::digest_type root(const typename Hash::digest_type &leaf) {\n//                    using namespace nil::crypto3;\n//                    accumulator_set<Hash> acc;\n//                    std::accumulate(path.begin(), path.end(), leaf,\n//                                    [&](typename Hash::digest_type acc,\n//                                        typename std::vector<PathElement<Hash, BaseArity>>::value_type &v) {\n//\n//                                    });\n//                    auto a = H::Function::default();\n//                    (0..self.path.len())\n//                        .fold(\n//                            leaf, | h, height | {\n//                                a.reset();\n//\n//                                const auto index = self.path[height].index;\n//                                auto nodes = self.path[height].hashes.clone();\n//                                nodes.insert(index, h);\n//\n//                                a.multi_node(&nodes, height)\n//                            })\n//                }\n//\n//                std::size_t size() {\n//                    return path.size();\n//                }\n//\n//                bool empty() {\n//                    return path.empty();\n//                }\n//\n//                std::size_t path_index() {\n//                    return std::accumulate(\n//                        path.begin(), path.end(), 0,\n//                        [&](std::size_t acc, typename std::vector<PathElement<Hash, BaseArity>>::value_type &v) {\n//                            return (acc * BaseArity) + v.index;\n//                        });\n//                }\n//\n//                std::vector<PathElement<Hash, BaseArity>> path;\n//            };\n//\n//            template<typename Hash, std::size_t BaseArity>\n//            struct SingleProof {\n//                template<template<typename, std::size_t> class Proof>\n//                static SingleProof<Hash, BaseArity> try_from_proof(const Proof<typename Hash::digest_type, BaseArity> &p) {\n//                    return proof_to_single(p, 1);\n//                }\n//\n//                bool verify() {\n//                    return root == path.root(leaf);\n//                }\n//\n//                std::size_t size() {\n//                    return path.size() * (BaseArity - 1) + 2;\n//                }\n//\n//                std::vector<std::pair<std::vector<typename Hash::digest_type>, std::size_t>> path() {\n//                    return path.iter().map(| x | (x.hashes.clone(), x.index)).collect::<Vec<_>>();\n//                }\n//\n//                std::size_t path_index() {\n//                    return path.path_index();\n//                }\n//\n//                /// Root of the merkle tree.\n//                typename Hash::digest_type root;\n//                /// The original leaf data for this prof.\n//                typename Hash::digest_type leaf;\n//                /// The path from leaf to root.\n//                InclusionPath<Hash, BaseArity> path;\n//            };\n//\n//            template<typename Hash, std::size_t BaseArity, std::size_t SubTreeArity>\n//            struct SubProof {\n//                static SubProof<Hash, BaseArity, SubTreeArity>\n//                    try_from_proof(const Proof<typename Hash::digest_type, BaseArity> &p) {\n//                    BOOST_ASSERT_MSG(p.sub_layer_nodes() == SubTreeArity, \"sub arity mismatch\");\n//                    BOOST_ASSERT_MSG(p.sub_tree_proof, \"Cannot generate sub proof without a base-proof\");\n//                    std::shared_ptr<Proof<typename Hash::digest_type, BaseArity>> base_p = p.sub_tree_proof;\n//\n//                    // Generate SubProof\n//                    typename Hash::digest_type root = p.root();\n//                    typename Hash::digest_type leaf = base_p.item();\n//                    InclusionPath<Hash, BaseArity> base_proof =\n//                        extract_path<typename Hash::digest_type, BaseArity>(base_p.lemma(), base_p.path(), 1);\n//                    InclusionPath<Hash, SubTreeArity> sub_proof =\n//                        extract_path<typename Hash::digest_type, SubTreeArity>(p.lemma(), p.path(), 0);\n//\n//                    return {base_proof, sub_proof, root, leaf};\n//                }\n//\n//                bool verify() {\n//                    root == sub_proof.root(base_proof.root(leaf));\n//                }\n//\n//                std::size_t size() {\n//                    return SubTreeArity;\n//                }\n//\n//                std::vector<std::pair<std::vector<typename Hash::digest_type>, std::size_t>> path() {\n//                    return base_proof.iter()\n//                        .map(| x | (x.hashes.clone(), x.index))\n//                        .chain(self.sub_proof.iter().map(| x | (x.hashes.clone(), x.index)))\n//                        .collect();\n//                }\n//\n//                std::size_t path_index() {\n//                    std::size_t base_proof_leaves = 1;\n//                    for (int i = 0; i < base_proof.size(); i++) {\n//                        base_proof_leaves *= BaseArity;\n//                    }\n//\n//                    std::size_t sub_proof_index = sub_proof.path_index();\n//\n//                    return (sub_proof_index * base_proof_leaves) + base_proof.path_index();\n//                }\n//\n//                InclusionPath<Hash, BaseArity> base_proof;\n//\n//                InclusionPath<Hash, SubTreeArity> sub_proof;\n//\n//                typename Hash::digest_type root;\n//                /// The original leaf data for this prof.\n//\n//                typename Hash::digest_type leaf;\n//            };\n//\n//            template<typename Hash, std::size_t BaseArity, std::size_t SubTreeArity, std::size_t TopTreeArity>\n//            struct TopProof {\n//                TopProof<Hash, BaseArity, SubTreeArity, TopTreeArity>\n//                    try_from_proof(const Proof<typename Hash::digest_type, BaseArity> &p) {\n//                    BOOST_ASSERT_MSG(p.top_layer_nodes() == TopTreeArity, \"top arity mismatch\");\n//                    BOOST_ASSERT_MSG(p.sub_layer_nodes() == SubTreeArity, \"sub arity mismatch\");\n//\n//                    BOOST_ASSERT_MSG(p.sub_tree_proof, \"Cannot generate top proof without a sub-proof\");\n//                    const auto sub_p = p.sub_tree_proof;\n//\n//                    BOOST_ASSERT_MSG(sub_p.sub_tree_proof, \"Cannot generate top proof without a base-proof\");\n//                    const auto base_p = sub_p.sub_tree_proof;\n//\n//                    const auto root = p.root();\n//                    const auto leaf = base_p.item();\n//\n//                    return {extract_path<Hash, BaseArity>(base_p.lemma(), base_p.path(), 1), extract_path<Hash, SubTreeArity>(sub_p.lemma(), sub_p.path(), 0), extract_path<Hash, TopTreeArity>(p.lemma(), p.path(), 0), root, leaf};\n//                }\n//\n//                bool verify() {\n//                    root == top_proof.root(sub_proof.root(base_proof.root(leaf)));\n//                }\n//\n//                std::size_t size() {\n//                    return TopTreeArity;\n//                }\n//\n//                std::vector<std::pair<std::vector<typename Hash::digest_type>, std::size_t>> path() {\n//                    return base_proof.iter()\n//                        .map(| x | (x.hashes.clone(), x.index))\n//                        .chain(self.sub_proof.iter().map(| x | (x.hashes.clone(), x.index)))\n//                        .chain(self.top_proof.iter().map(| x | (x.hashes.clone(), x.index)))\n//                        .collect();\n//                }\n//\n//                std::size_t path_index() {\n//                    std::size_t base_proof_leaves = 1;\n//                    for (int i = 0; i < base_proof.size(); i++) {\n//                        base_proof_leaves *= BaseArity;\n//                    }\n//\n//                    return (sub_proof.path_index() * base_proof_leaves) +\n//                           (top_proof.path_index() * base_proof_leaves * SubTreeArity) + base_proof.path_index();\n//                }\n//\n//                InclusionPath<Hash, BaseArity> base_proof;\n//\n//                InclusionPath<Hash, SubTreeArity> sub_proof;\n//\n//                InclusionPath<Hash, TopTreeArity> top_proof;\n//                /// Root of the merkle tree.\n//\n//                typename Hash::digest_type root;\n//                /// The original leaf data for this prof.\n//                typename Hash::digest_type leaf;\n//            };\n//\n//            template<typename Hash, std::size_t BaseArity, std::size_t SubTreeArity, std::size_t TopTreeArity>\n//            using ProofData = boost::variant<SingleProof<Hash, BaseArity>, SubProof<Hash, BaseArity, SubTreeArity>,\n//                                             TopProof<Hash, BaseArity, SubTreeArity, TopTreeArity>>;\n//\n//            template<typename Hash, std::size_t BaseArity, std::size_t SubTreeArity, std::size_t TopTreeArity>\n//            struct MerkleProof : public BasicMerkleProof<Hash, BaseArity, SubTreeArity, TopTreeArity> {\n//                typedef typename Hash::digest_type digest_type;\n//                MerkleProof(std::size_t n) :\n//                    data(SingleProof<Hash, BaseArity>(std::vector<PathElement<Hash, BaseArity>>(n), root, leaf)) {\n//                }\n//\n//                virtual bool verify() const override {\n//                    return false;\n//                }\n//                virtual bool validate(std::size_t node) override {\n//                }\n//                virtual bool validate_data(const digest_type &data) override {\n//                }\n//                virtual digest_type leaf() override {\n//                    return nullptr;\n//                }\n//                virtual digest_type root() override {\n//                    return nullptr;\n//                }\n//                virtual std::vector<std::pair<std::vector<typename Hash::digest_type>, std::size_t>> path() override {\n//                    return std::vector<std::pair<std::vector<typename Hash::digest_type>, std::size_t>>();\n//                }\n//\n//                ProofData<Hash, BaseArity, SubTreeArity, TopTreeArity> data;\n//            };\n//\n//            /// 'lemma_start_index' is required because sub/top proofs start at\n//            /// index 0 and base proofs start at index 1 (skipping the leaf at the\n//            /// front)\n//            template<typename Hash, std::size_t BaseArity>\n//            InclusionPath<Hash, BaseArity> extract_path(const std::vector<typename Hash::digest_type> &lemma,\n//                                                        const std::vector<std::size_t> &path,\n//                                                        std::size_t lemma_start_index) {\n//                std::vector<PathElement<Hash, BaseArity>> res;\n//\n//                for (int i = 0; i < path.size(); i++) {\n//                    res.emplace_back(\n//                        std::vector<typename Hash::digest_type>(lemma.begin() + lemma_start_index + BaseArity * i,\n//                                                                lemma.begin() + lemma_start_index + BaseArity * (i + 1)),\n//                        index);\n//                }\n//\n//                return InclusionPath<Hash, BaseArity>(res);\n//            }\n//\n//            /// Converts a merkle_light proof to a SingleProof\n//            template<typename Hash, std::size_t BaseArity, std::size_t TargetArity,\n//                     template<typename, std::size_t> class Proof>\n//            SingleProof<Hash, TargetArity>\n//                proof_to_single(const Proof<Hash, BaseArity> &proof, std::size_t lemma_start_index,\n//                                typename Hash::digest_type &sub_root = typename Hash::digest_type()) {\n//                typename Hash::digest_type root = proof.root();\n//                typename Hash::digest_type leaf = sub_root.emplty() ? sub_root : proof.item();\n//\n//                InclusionPath<Hash, TargetArity> path =\n//                    extract_path<Hash, TargetArity>(proof.lemma(), proof.path(), lemma_start_index);\n//\n//                return {path, root, leaf};\n//            }\n        }    // namespace merkletree    \n    }    // namespace filecoin\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "4c4305560fe534f1b45dea9afd9740f21208f3d3", "size": 27699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/merkle/old_proof.hpp", "max_stars_repo_name": "NilFoundation/crypto3-fil-proofs", "max_stars_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/merkle/old_proof.hpp", "max_issues_repo_name": "NilFoundation/crypto3-fil-proofs", "max_issues_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-06T13:07:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-16T12:38:09.000Z", "max_forks_repo_path": "libs/storage/include/nil/filecoin/storage/proofs/core/merkle/old_proof.hpp", "max_forks_repo_name": "NilFoundation/crypto3-fil-proofs", "max_forks_repo_head_hexsha": "1fd78ad608278a1ed62fb29b0a077347b74a55f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.4827586207, "max_line_length": 231, "alphanum_fraction": 0.4707751182, "num_tokens": 5623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.22812401426175666}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017, 2018.\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 5.0.0\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_BONNE_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_BONNE_HPP\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/pj_mlfn.hpp>\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/math/special_functions/hypot.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace bonne\n    {\n\n            static const double epsilon10 = 1e-10;\n\n            template <typename T>\n            struct par_bonne\n            {\n                T phi1;\n                T cphi1;\n                T am1;\n                T m1;\n                detail::en<T> en;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_bonne_ellipsoid\n                : public base_t_fi<base_bonne_ellipsoid<T, Parameters>, T, Parameters>\n            {\n                par_bonne<T> m_proj_parm;\n\n                inline base_bonne_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_bonne_ellipsoid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(e_forward)  ellipsoid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    T rh, E, c;\n\n                    rh = this->m_proj_parm.am1 + this->m_proj_parm.m1 - pj_mlfn(lp_lat, E = sin(lp_lat), c = cos(lp_lat), this->m_proj_parm.en);\n                    E = c * lp_lon / (rh * sqrt(1. - this->m_par.es * E * E));\n                    xy_x = rh * sin(E);\n                    xy_y = this->m_proj_parm.am1 - rh * cos(E);\n                }\n\n                // INVERSE(e_inverse)  ellipsoid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T const& xy_x, T xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n\n                    T s, rh;\n\n                    rh = boost::math::hypot(xy_x, xy_y = this->m_proj_parm.am1 - xy_y);\n                    lp_lat = pj_inv_mlfn(this->m_proj_parm.am1 + this->m_proj_parm.m1 - rh, this->m_par.es, this->m_proj_parm.en);\n                    if ((s = fabs(lp_lat)) < half_pi) {\n                        s = sin(lp_lat);\n                        lp_lon = rh * atan2(xy_x, xy_y) *\n                           sqrt(1. - this->m_par.es * s * s) / cos(lp_lat);\n                    } else if (fabs(s - half_pi) <= epsilon10)\n                        lp_lon = 0.;\n                    else\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"bonne_ellipsoid\";\n                }\n\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_bonne_spheroid\n                : public base_t_fi<base_bonne_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_bonne<T> m_proj_parm;\n\n                inline base_bonne_spheroid(const Parameters& par)\n                    : base_t_fi<base_bonne_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    T E, rh;\n\n                    rh = this->m_proj_parm.cphi1 + this->m_proj_parm.phi1 - lp_lat;\n                    if (fabs(rh) > epsilon10) {\n                        xy_x = rh * sin(E = lp_lon * cos(lp_lat) / rh);\n                        xy_y = this->m_proj_parm.cphi1 - rh * cos(E);\n                    } else\n                        xy_x = xy_y = 0.;\n                }\n\n                // INVERSE(s_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T const& xy_x, T xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n\n                    T rh;\n\n                    rh = boost::math::hypot(xy_x, xy_y = this->m_proj_parm.cphi1 - xy_y);\n                    lp_lat = this->m_proj_parm.cphi1 + this->m_proj_parm.phi1 - rh;\n                    if (fabs(lp_lat) > half_pi) {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                    }\n                    if (fabs(fabs(lp_lat) - half_pi) <= epsilon10)\n                        lp_lon = 0.;\n                    else\n                        lp_lon = rh * atan2(xy_x, xy_y) / cos(lp_lat);\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"bonne_spheroid\";\n                }\n\n            };\n\n            // Bonne (Werner lat_1=90)\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_bonne(Params const& params, Parameters& par, par_bonne<T>& proj_parm)\n            {\n                static const T half_pi = detail::half_pi<T>();\n\n                T c;\n\n                proj_parm.phi1 = pj_get_param_r<T, srs::spar::lat_1>(params, \"lat_1\", srs::dpar::lat_1);\n                if (fabs(proj_parm.phi1) < epsilon10)\n                    BOOST_THROW_EXCEPTION( projection_exception(error_lat1_is_zero) );\n\n                if (par.es != 0.0) {\n                    proj_parm.en = pj_enfn<T>(par.es);\n                    proj_parm.m1 = pj_mlfn(proj_parm.phi1, proj_parm.am1 = sin(proj_parm.phi1),\n                        c = cos(proj_parm.phi1), proj_parm.en);\n                    proj_parm.am1 = c / (sqrt(1. - par.es * proj_parm.am1 * proj_parm.am1) * proj_parm.am1);\n                } else {\n                    if (fabs(proj_parm.phi1) + epsilon10 >= half_pi)\n                        proj_parm.cphi1 = 0.;\n                    else\n                        proj_parm.cphi1 = 1. / tan(proj_parm.phi1);\n                }\n            }\n\n    }} // namespace detail::bonne\n    #endif // doxygen\n\n    /*!\n        \\brief Bonne (Werner lat_1=90) projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel (degrees)\n        \\par Example\n        \\image html ex_bonne.gif\n    */\n    template <typename T, typename Parameters>\n    struct bonne_ellipsoid : public detail::bonne::base_bonne_ellipsoid<T, Parameters>\n    {\n        template <typename Params>\n        inline bonne_ellipsoid(Params const& params, Parameters const& par)\n            : detail::bonne::base_bonne_ellipsoid<T, Parameters>(par)\n        {\n            detail::bonne::setup_bonne(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    /*!\n        \\brief Bonne (Werner lat_1=90) projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Conic\n         - Spheroid\n         - Ellipsoid\n        \\par Projection parameters\n         - lat_1: Latitude of first standard parallel (degrees)\n        \\par Example\n        \\image html ex_bonne.gif\n    */\n    template <typename T, typename Parameters>\n    struct bonne_spheroid : public detail::bonne::base_bonne_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline bonne_spheroid(Params const& params, Parameters const& par)\n            : detail::bonne::base_bonne_spheroid<T, Parameters>(par)\n        {\n            detail::bonne::setup_bonne(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_bonne, bonne_spheroid, bonne_ellipsoid)\n\n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI2(bonne_entry, bonne_spheroid, bonne_ellipsoid)\n\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(bonne_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(bonne, bonne_entry);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_BONNE_HPP\n\n", "meta": {"hexsha": "70bdc87fd23511ac525367ac8bfab19b77081c98", "size": 11032, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/bonne.hpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/bonne.hpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/bonne.hpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 39.4, "max_line_length": 144, "alphanum_fraction": 0.5833937636, "num_tokens": 2548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.22800881995392666}}
{"text": "/****************************************************************************\n * Copyright (c) 2021 by the Picasso authors                                *\n * All rights reserved.                                                     *\n *                                                                          *\n * This file is part of the Picasso library. Picasso is distributed under a *\n * BSD 3-clause license. For the licensing terms see the LICENSE file in    *\n * the top-level directory.                                                 *\n *                                                                          *\n * SPDX-License-Identifier: BSD-3-Clause                                    *\n ****************************************************************************/\n\n#ifndef PICASSO_FACETGEOMETRY_HPP\n#define PICASSO_FACETGEOMETRY_HPP\n\n#include <Picasso_BatchedLinearAlgebra.hpp>\n\n#include <Kokkos_Core.hpp>\n#include <Kokkos_Random.hpp>\n\n#include <boost/property_tree/ptree.hpp>\n\n#include <cfloat>\n#include <cmath>\n#include <fstream>\n#include <unordered_map>\n#include <vector>\n\nnamespace Picasso\n{\n//---------------------------------------------------------------------------//\ntemplate <class MemorySpace>\nstruct FacetGeometryData\n{\n    // Get the number of volumes.\n    KOKKOS_FUNCTION\n    int numVolume() const { return volume_offsets.extent( 0 ); }\n\n    // Given a local volume id get the facets associated with the volume.\n    KOKKOS_FUNCTION\n    Kokkos::View<float* [4][3], MemorySpace>\n    volumeFacets( const int volume_id ) const\n    {\n        Kokkos::pair<int, int> facet_bounds(\n            ( 0 == volume_id ) ? 0 : volume_offsets( volume_id - 1 ),\n            volume_offsets( volume_id ) );\n        return Kokkos::subview( volume_facets, facet_bounds, Kokkos::ALL(),\n                                Kokkos::ALL() );\n    }\n\n    // Get the number of surfaces.\n    KOKKOS_FUNCTION\n    int numSurface() const { return surface_offsets.extent( 0 ); }\n\n    // Given a local surface id get the facets associated with the surface.\n    KOKKOS_FUNCTION\n    Kokkos::View<float* [4][3], MemorySpace>\n    surfaceFacets( const int surface_id ) const\n    {\n        Kokkos::pair<int, int> facet_bounds(\n            ( 0 == surface_id ) ? 0 : surface_offsets( surface_id - 1 ),\n            surface_offsets( surface_id ) );\n        return Kokkos::subview( surface_facets, facet_bounds, Kokkos::ALL(),\n                                Kokkos::ALL() );\n    }\n\n    // Volume facets. Ordered as (facet,vector,dim) where vector=0,1,2 are the\n    // vertices and vector=3 is the unit normal facing outward from the\n    // volume.\n    Kokkos::View<float* [4][3], MemorySpace> volume_facets;\n\n    // Volume face offsets. Inclusive scan of volume counts giving the offset\n    // into the facet array for each volume.\n    Kokkos::View<int*, MemorySpace> volume_offsets;\n\n    // Surface facets. Ordered as (facet,vector,dim) where vector=0,1,2 are the\n    // vertices and vector=3 is the unit normal facing outward from the\n    // surface.\n    Kokkos::View<float* [4][3], MemorySpace> surface_facets;\n\n    // Surface face offsets. Inclusive scan of surface counts giving the offset\n    // into the facet array for each surface.\n    Kokkos::View<int*, MemorySpace> surface_offsets;\n\n    // Local id of the volume the representes the global axis-aligned bounding\n    // box.\n    int global_bounding_volume_id;\n\n    // Axis aligned bounding box for all volumes.\n    Kokkos::View<float* [6], MemorySpace> volume_bounding_boxes;\n};\n\n//---------------------------------------------------------------------------//\ntemplate <class MemorySpace>\nclass FacetGeometry\n{\n  public:\n    // Compute the axis-aligned bounding box of a volume.\n    struct BoundingBoxReduce\n    {\n        typedef float value_type[];\n        typedef Kokkos::View<float* [4][3], MemorySpace> facet_view_type;\n        typedef Kokkos::View<int*, MemorySpace> offset_view_type;\n        typedef typename facet_view_type::size_type size_type;\n        size_type value_count;\n\n        facet_view_type facets;\n        offset_view_type offsets;\n        int volume_id;\n\n        BoundingBoxReduce( const facet_view_type& f, const offset_view_type& o,\n                           int v )\n            : value_count( 6 )\n            , facets( f )\n            , offsets( o )\n            , volume_id( v )\n        {\n        }\n\n        KOKKOS_FUNCTION\n        void operator()( const size_type facet_id, value_type result ) const\n        {\n            auto f_start = ( volume_id == 0 ) ? 0 : offsets( volume_id - 1 );\n            auto f = f_start + facet_id;\n            result[0] =\n                fmin( result[0],\n                      fmin( facets( f, 0, 0 ),\n                            fmin( facets( f, 1, 0 ), facets( f, 2, 0 ) ) ) );\n            result[1] =\n                fmin( result[1],\n                      fmin( facets( f, 0, 1 ),\n                            fmin( facets( f, 1, 1 ), facets( f, 2, 1 ) ) ) );\n            result[2] =\n                fmin( result[2],\n                      fmin( facets( f, 0, 2 ),\n                            fmin( facets( f, 1, 2 ), facets( f, 2, 2 ) ) ) );\n            result[3] =\n                fmax( result[3],\n                      fmax( facets( f, 0, 0 ),\n                            fmax( facets( f, 1, 0 ), facets( f, 2, 0 ) ) ) );\n            result[4] =\n                fmax( result[4],\n                      fmax( facets( f, 0, 1 ),\n                            fmax( facets( f, 1, 1 ), facets( f, 2, 1 ) ) ) );\n            result[5] =\n                fmax( result[5],\n                      fmax( facets( f, 0, 2 ),\n                            fmax( facets( f, 1, 2 ), facets( f, 2, 2 ) ) ) );\n        }\n\n        KOKKOS_FUNCTION\n        void join( volatile value_type dst,\n                   const volatile value_type src ) const\n        {\n            dst[0] = fmin( dst[0], src[0] );\n            dst[1] = fmin( dst[1], src[1] );\n            dst[2] = fmin( dst[2], src[2] );\n            dst[3] = fmax( dst[3], src[3] );\n            dst[4] = fmax( dst[4], src[4] );\n            dst[5] = fmax( dst[5], src[5] );\n        }\n\n        KOKKOS_FUNCTION\n        void init( value_type v ) const\n        {\n            v[0] = FLT_MAX;\n            v[1] = FLT_MAX;\n            v[2] = FLT_MAX;\n            v[3] = -FLT_MAX;\n            v[4] = -FLT_MAX;\n            v[5] = -FLT_MAX;\n        }\n    };\n\n  public:\n    using memory_space = MemorySpace;\n\n    // Default constructor.\n    FacetGeometry() = default;\n\n    // Create the geometry from an ASCII STL file.\n    template <class ExecutionSpace>\n    FacetGeometry( const boost::property_tree::ptree& ptree,\n                   const ExecutionSpace& exec_space )\n    {\n        // Get the geometry parameters.\n        const auto& params = ptree.get_child( \"geometry\" );\n\n        // Read the stl file and create the facet geometry.\n        auto stl_ascii_filename = params.get<std::string>( \"stl_file\" );\n\n        // Containers.\n        std::vector<int> volume_ids;\n        std::vector<int> surface_ids;\n        std::vector<float> volume_facets;\n        std::vector<float> surface_facets;\n\n        // Load the file.\n        std::ifstream file( stl_ascii_filename );\n        if ( !file.is_open() )\n            throw std::runtime_error( \"Unable to open STL ASCII file\" );\n\n        // Read the file.\n        std::string buffer;\n        std::vector<std::string> tokens;\n        tokens.reserve( 10 );\n        bool read_volume = false;\n        bool read_surface = false;\n        while ( !file.eof() )\n        {\n            // Get the current line.\n            std::getline( file, buffer );\n\n            // Break the line up into tokens.\n            std::istringstream line( buffer );\n            tokens.resize( 0 );\n            while ( !line.eof() )\n            {\n                tokens.push_back( std::string() );\n                line >> tokens.back();\n            }\n\n            // Parse the line.\n            if ( tokens.size() > 0 )\n            {\n                // New solid.\n                if ( tokens[0].compare( \"solid\" ) == 0 )\n                {\n                    if ( tokens.size() != 3 )\n                        throw std::runtime_error(\n                            \"STL READER: Expected 3 solid line entries\" );\n\n                    // New volume.\n                    if ( tokens[1].compare( \"Volume\" ) == 0 ||\n                         tokens[1].compare( \"Body\" ) == 0 )\n                    {\n                        volume_ids.push_back( std::atoi( tokens[2].c_str() ) );\n                        _volume_facet_count.push_back( 0 );\n                        read_volume = true;\n                    }\n\n                    // New surface.\n                    else if ( tokens[1].compare( \"Surface\" ) == 0 )\n                    {\n                        surface_ids.push_back( std::atoi( tokens[2].c_str() ) );\n                        _surface_facet_count.push_back( 0 );\n                        read_surface = true;\n                    }\n\n                    else\n                    {\n                        throw std::runtime_error(\n                            \"STL READER: Solids execpted to be Volume/Body or \"\n                            \"Surface\" );\n                    }\n                }\n\n                // Read facet.\n                else if ( tokens[0].compare( \"facet\" ) == 0 )\n                {\n                    if ( tokens.size() != 5 )\n                        throw std::runtime_error(\n                            \"STL READER: Expected 5 facet line entries\" );\n\n                    // Volume facet.\n                    if ( read_volume )\n                    {\n                        ++_volume_facet_count.back();\n                    }\n\n                    // Surface facet.\n                    else if ( read_surface )\n                    {\n                        ++_surface_facet_count.back();\n                    }\n                }\n\n                // Read vertex.\n                else if ( tokens[0].compare( \"vertex\" ) == 0 )\n                {\n                    if ( tokens.size() != 4 )\n                        throw std::runtime_error(\n                            \"STL READER: Expected 4 vertex line entries\" );\n\n                    // Volume vertex coordinates.\n                    if ( read_volume )\n                    {\n                        volume_facets.push_back(\n                            std::atof( tokens[1].c_str() ) );\n                        volume_facets.push_back(\n                            std::atof( tokens[2].c_str() ) );\n                        volume_facets.push_back(\n                            std::atof( tokens[3].c_str() ) );\n                    }\n\n                    // Surface vertex coordinates.\n                    if ( read_surface )\n                    {\n                        surface_facets.push_back(\n                            std::atof( tokens[1].c_str() ) );\n                        surface_facets.push_back(\n                            std::atof( tokens[2].c_str() ) );\n                        surface_facets.push_back(\n                            std::atof( tokens[3].c_str() ) );\n                    }\n                }\n\n                // Finish reading a solid.\n                else if ( tokens[0].compare( \"endsolid\" ) == 0 )\n                {\n                    read_volume = false;\n                    read_surface = false;\n                }\n            }\n        }\n\n        // Close the file.\n        file.close();\n\n        // Put volume data on device.\n        putFileDataOnDevice( volume_ids, _volume_facet_count, volume_facets,\n                             _volume_ids, _data.volume_facets,\n                             _data.volume_offsets );\n\n        // Put surface data on device.\n        putFileDataOnDevice( surface_ids, _surface_facet_count, surface_facets,\n                             _surface_ids, _data.surface_facets,\n                             _data.surface_offsets );\n\n        // Get the volume id of the global bounding box. The user is required\n        // to make an axis-aligned bounding box of their geometry that defines\n        // the global bounds of the problem. The user input is the global id\n        // of this volume.\n        _data.global_bounding_volume_id =\n            localVolumeId( params.get<int>( \"global_bounding_volume_id\" ) );\n\n        // Compute the bounding boxes of all the volumes.\n        _data.volume_bounding_boxes = Kokkos::View<float* [6], MemorySpace>(\n            Kokkos::ViewAllocateWithoutInitializing( \"volume_bounding_boxes\" ),\n            volume_ids.size() );\n        auto host_boxes = Kokkos::create_mirror_view(\n            Kokkos::HostSpace(), _data.volume_bounding_boxes );\n        for ( int v = 0; v < _data.numVolume(); ++v )\n        {\n            BoundingBoxReduce reducer( _data.volume_facets,\n                                       _data.volume_offsets, v );\n            float box[6];\n            Kokkos::parallel_reduce(\n                \"Picasso::FacetGeometry::VolumeBoundingBox\",\n                Kokkos::RangePolicy<ExecutionSpace>( exec_space, 0,\n                                                     _volume_facet_count[v] ),\n                reducer, box );\n            for ( int i = 0; i < 6; ++i )\n                host_boxes( v, i ) = box[i];\n        }\n        Kokkos::deep_copy( _data.volume_bounding_boxes, host_boxes );\n\n        // Extract the global bounding box to the host.\n        auto global_box = Kokkos::subview(\n            host_boxes, _data.global_bounding_volume_id, Kokkos::ALL() );\n        for ( int i = 0; i < 6; ++i )\n            _global_bounding_box[i] = global_box( i );\n    }\n\n    // Given a global volume id get the local volume id.\n    int localVolumeId( const int global_id ) const\n    {\n        return _volume_ids.find( global_id )->second;\n    }\n\n    // Given a global surface id get the local surface id.\n    int localSurfaceId( const int global_id ) const\n    {\n        return _surface_ids.find( global_id )->second;\n    }\n\n    // Given a local volume id get the number of facets that compose the\n    // volume.\n    int numVolumeFacet( const int local_id ) const\n    {\n        return _volume_facet_count[local_id];\n    }\n\n    // Given a local surface id get the number of facets that compose the\n    // surface.\n    int numSurfaceFacet( const int local_id ) const\n    {\n        return _surface_facet_count[local_id];\n    }\n\n    // Get the global bounding box.\n    const Kokkos::Array<double, 6>& globalBoundingBox() const\n    {\n        return _global_bounding_box;\n    }\n\n    // Get the geometry data.\n    const FacetGeometryData<MemorySpace>& data() const { return _data; }\n\n  private:\n    // Put file data on device.\n    void putFileDataOnDevice(\n        const std::vector<int>& solid_ids,\n        const std::vector<int>& solid_facet_counts,\n        const std::vector<float>& solid_facets,\n        std::unordered_map<int, int>& id_map,\n        Kokkos::View<float* [4][3], MemorySpace>& device_facets,\n        Kokkos::View<int*, MemorySpace>& device_offsets )\n    {\n        // Allocate solid data.\n        int num_solid = solid_ids.size();\n        device_offsets = Kokkos::View<int*, MemorySpace>(\n            Kokkos::ViewAllocateWithoutInitializing( \"offsets\" ), num_solid );\n\n        int num_solid_facet = solid_facets.size() / 9;\n        device_facets = Kokkos::View<float* [4][3], MemorySpace>(\n            Kokkos::ViewAllocateWithoutInitializing( \"facets\" ),\n            num_solid_facet );\n\n        // Compute the offsets for the facet-to-solid mapping.\n        auto host_offsets =\n            Kokkos::create_mirror_view( Kokkos::HostSpace(), device_offsets );\n        for ( int i = 0; i < num_solid; ++i )\n        {\n            // Map global solid ids to local ids.\n            id_map.emplace( solid_ids[i], i );\n\n            // Compute the offset via inclusive scan.\n            host_offsets( i ) =\n                ( 0 == i ) ? solid_facet_counts[i]\n                           : solid_facet_counts[i] + host_offsets( i - 1 );\n        }\n\n        // Build the facets.\n        auto host_facets =\n            Kokkos::create_mirror_view( Kokkos::HostSpace(), device_facets );\n        for ( int f = 0; f < num_solid_facet; ++f )\n        {\n            // Extract the vertices.\n            for ( int v = 0; v < 3; ++v )\n                for ( int d = 0; d < 3; ++d )\n                    host_facets( f, v, d ) = solid_facets[9 * f + 3 * v + d];\n\n            // Compute the normals.\n            float v10[3];\n            float v20[3];\n            for ( int d = 0; d < 3; ++d )\n            {\n                v10[d] = host_facets( f, 1, d ) - host_facets( f, 0, d );\n                v20[d] = host_facets( f, 2, d ) - host_facets( f, 0, d );\n            }\n            host_facets( f, 3, 0 ) = v10[1] * v20[2] - v10[2] * v20[1];\n            host_facets( f, 3, 1 ) = v10[2] * v20[0] - v10[0] * v20[2];\n            host_facets( f, 3, 2 ) = v10[0] * v20[1] - v10[1] * v20[0];\n\n            // Scale them to make it a unit normal.\n            float nmag =\n                std::sqrt( host_facets( f, 3, 0 ) * host_facets( f, 3, 0 ) +\n                           host_facets( f, 3, 1 ) * host_facets( f, 3, 1 ) +\n                           host_facets( f, 3, 2 ) * host_facets( f, 3, 2 ) );\n            for ( int d = 0; d < 3; ++d )\n                host_facets( f, 3, d ) /= nmag;\n        }\n\n        // Copy to device.\n        Kokkos::deep_copy( device_facets, host_facets );\n        Kokkos::deep_copy( device_offsets, host_offsets );\n    }\n\n  public:\n    // Volume ids - global-to-local mapping.\n    std::unordered_map<int, int> _volume_ids;\n\n    // Surface ids - global-to-local mapping.\n    std::unordered_map<int, int> _surface_ids;\n\n    // Volume facet counts.\n    std::vector<int> _volume_facet_count;\n\n    // Surface facet counts.\n    std::vector<int> _surface_facet_count;\n\n    // Global bounding box.\n    Kokkos::Array<double, 6> _global_bounding_box;\n\n    // Data.\n    FacetGeometryData<MemorySpace> _data;\n};\n\n//---------------------------------------------------------------------------//\n// Facet Geometry operations.\n//---------------------------------------------------------------------------//\nnamespace FacetGeometryOps\n{\n//---------------------------------------------------------------------------//\n// Project a point x along the given direction, r, and determine if it\n// projects to the facet. If returns true, the projection solution is\n// valid.\n//\n// y[0] = projection barycentric coordinate 1\n// y[1] = projection barycentric coordinate 2\n// y[2] = distance to triangle\ntemplate <class FacetView>\nKOKKOS_FUNCTION bool pointFacetProjection( const float x[3], const float r[3],\n                                           const FacetView& facets, const int f,\n                                           float y[3] )\n{\n    // Build the system of equations to solve for intersection. Fire the ray\n    // in the Y direction - this choice is arbitary.\n    Mat3<float> A;\n    Vec3<float> b;\n    for ( int i = 0; i < 3; ++i )\n    {\n        A( i, 0 ) = facets( f, 1, i ) - facets( f, 0, i );\n        A( i, 1 ) = facets( f, 2, i ) - facets( f, 0, i );\n        A( i, 2 ) = -r[i];\n        b( i ) = x[i] - facets( f, 0, i );\n    }\n\n    // Check the determinant of the matrix. If zero then the ray is parallel\n    // so no intersection.\n    auto det_A = !A;\n    if ( 0.0 == det_A )\n        return false;\n\n    // Solve the system.\n    VecView3<float> y_view( y, 1 );\n    y_view = A ^ b;\n\n    // Check the solution for inclusion in the triangle.\n    return ( y[0] >= 0.0 && y[1] >= 0.0 && y[0] + y[1] <= 1.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Fire a ray from point x along the given direction, r, and determine if it\n// intersects the facet.\ntemplate <class FacetView>\nKOKKOS_FUNCTION bool rayFacetIntersect( const float x[3], const float r[3],\n                                        const FacetView& facets, const int f )\n{\n    // Project the point and check the distance.\n    float y[3];\n    auto projects = pointFacetProjection( x, r, facets, f, y );\n    return projects && ( y[2] > 0.0 );\n}\n\n//---------------------------------------------------------------------------//\n// Compute the signed distance from a point to the plane defined by a facet.\ntemplate <class FacetView>\nKOKKOS_FUNCTION float\ndistanceToFacetPlane( const float x[3], const FacetView& facets, const int f )\n{\n    return ( x[0] - facets( f, 0, 0 ) ) * facets( f, 3, 0 ) +\n           ( x[1] - facets( f, 0, 1 ) ) * facets( f, 3, 1 ) +\n           ( x[2] - facets( f, 0, 2 ) ) * facets( f, 3, 2 );\n}\n\n//---------------------------------------------------------------------------//\n// Determine if a point is in a volume represented by a view of facets.\ntemplate <class FacetView>\nKOKKOS_FUNCTION bool pointInVolume( const float x[3],\n                                    const FacetView& volume_facets )\n{\n    // The choice of ray direction is arbitrary so generate a random one. This\n    // could potentially help with robustness as floating point noise may\n    // avoid edge and vertex intersections which could lead to multiple\n    // positive intersections and therefore an incorrect point-in-volume\n    // determination. The facet geometry has no connectivity so it is\n    // difficult to resolve multiple intersections without accumulating the\n    // intersection points and checking for duplicates within some tolerance.\n    //\n    // Note: Duan has indicated that doing tests with 3 different random rays\n    // has been enough to be robust as one is likely to pass out of the 3 if\n    // is a true intersection.\n    using rand_type =\n        Kokkos::Random_XorShift64<typename FacetView::device_type>;\n    rand_type rng( 0 );\n    float r[3] = { Kokkos::rand<rand_type, float>::draw( rng ),\n                   Kokkos::rand<rand_type, float>::draw( rng ),\n                   Kokkos::rand<rand_type, float>::draw( rng ) };\n    float r_mag_inv = 1.0 / sqrt( r[0] * r[0] + r[1] * r[1] + r[2] * r[2] );\n    for ( int d = 0; d < 3; ++d )\n        r[d] *= r_mag_inv;\n\n    // Fire rays through each facet and count intersections. If an\n    // odd number of intersections, the point is in the volume. This works for\n    // convex and non-convex volumes.\n    int count = 0;\n    for ( std::size_t f = 0; f < volume_facets.extent( 0 ); ++f )\n        if ( rayFacetIntersect( x, r, volume_facets, f ) )\n            ++count;\n    return ( 1 == count % 2 );\n}\n\n//---------------------------------------------------------------------------//\n// Given a point determine the volume in the given facet geometry in which it\n// is located.If it is in the implicit complement, return -1. If it is outside\n// of the entire domain, return -2;\ntemplate <class MemorySpace>\nKOKKOS_FUNCTION int locatePoint( const float x[3],\n                                 const FacetGeometryData<MemorySpace>& geom )\n{\n    // Get the global bounding volume id.\n    int gbv = geom.global_bounding_volume_id;\n\n    // Start by checking that the point is in the global bounding volume.\n    if ( geom.volume_bounding_boxes( gbv, 0 ) <= x[0] &&\n         geom.volume_bounding_boxes( gbv, 1 ) <= x[1] &&\n         geom.volume_bounding_boxes( gbv, 2 ) <= x[2] &&\n         geom.volume_bounding_boxes( gbv, 3 ) >= x[0] &&\n         geom.volume_bounding_boxes( gbv, 4 ) >= x[1] &&\n         geom.volume_bounding_boxes( gbv, 5 ) >= x[2] )\n    {\n        // Check each volume except the global bounding volume for point\n        // inclusion.\n        for ( int v = 0; v < geom.numVolume(); ++v )\n        {\n            if ( v != gbv )\n            {\n                // First check if the point is in the axis-aligned\n                // bounding box of the volume.\n                if ( geom.volume_bounding_boxes( v, 0 ) <= x[0] &&\n                     geom.volume_bounding_boxes( v, 1 ) <= x[1] &&\n                     geom.volume_bounding_boxes( v, 2 ) <= x[2] &&\n                     geom.volume_bounding_boxes( v, 3 ) >= x[0] &&\n                     geom.volume_bounding_boxes( v, 4 ) >= x[1] &&\n                     geom.volume_bounding_boxes( v, 5 ) >= x[2] )\n                {\n                    // If in the bounding box, check against each volume\n                    // facet for point inclusion.\n                    if ( pointInVolume( x, geom.volumeFacets( v ) ) )\n                    {\n                        return v;\n                    }\n                }\n            }\n        }\n\n        // If the point was not in any volume it is in the implicit\n        // complement so return -1.\n        return -1;\n    }\n\n    // Otherwise point is outside of the global domain including the\n    // implicit complement so return -2.\n    return -2;\n}\n\n//---------------------------------------------------------------------------//\n\n} // end namespace FacetGeometryOps\n\n//---------------------------------------------------------------------------//\n\n} // end namespace Picasso\n\n#endif // end PICASSO_FACETGEOMETRY_HPP\n", "meta": {"hexsha": "0ebc777779a762953b9c3219c70dbb18d9709798", "size": 24901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Picasso_FacetGeometry.hpp", "max_stars_repo_name": "picassodev/picasso", "max_stars_repo_head_hexsha": "540771ac54454c6abcd29e3f0a24328e4ad89775", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-02-17T14:59:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T23:29:52.000Z", "max_issues_repo_path": "src/Picasso_FacetGeometry.hpp", "max_issues_repo_name": "picassodev/picasso", "max_issues_repo_head_hexsha": "540771ac54454c6abcd29e3f0a24328e4ad89775", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 48.0, "max_issues_repo_issues_event_min_datetime": "2021-02-17T17:24:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-18T14:12:02.000Z", "max_forks_repo_path": "src/Picasso_FacetGeometry.hpp", "max_forks_repo_name": "picassodev/picasso", "max_forks_repo_head_hexsha": "540771ac54454c6abcd29e3f0a24328e4ad89775", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T14:39:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-05T18:42:21.000Z", "avg_line_length": 37.901065449, "max_line_length": 80, "alphanum_fraction": 0.4996184892, "num_tokens": 5872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847395, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2279488408667704}}
{"text": "/*!\n  \\file gpp_python_expected_improvement.cpp\n  \\rst\n  This file has the logic to invoke C++ functions pertaining to expected improvement from Python.\n  The data flow follows the basic 4 step from gpp_python_common.hpp.\n\n  .. NoteL: several internal functions of this source file are only called from ``Export*()`` functions,\n  so their description, inputs, outputs, etc. comments have been moved. These comments exist in\n  ``Export*()`` as Python docstrings, so we saw no need to repeat ourselves.\n\\endrst*/\n// This include violates the Google Style Guide by placing an \"other\" system header ahead of C and C++ system headers.  However,\n// it needs to be at the top, otherwise compilation fails on some systems with some versions of python: OS X, python 2.7.3.\n// Putting this include first prevents pyport from doing something illegal in C++; reference: http://bugs.python.org/issue10910\n#include \"Python.h\"  // NOLINT(build/include)\n\n#include \"gpp_python_expected_improvement.hpp\"\n\n// NOLINT-ing the C, C++ header includes as well; otherwise cpplint gets confused\n#include <string>  // NOLINT(build/include_order)\n#include <vector>  // NOLINT(build/include_order)\n\n#include <boost/python/bases.hpp>  // NOLINT(build/include_order)\n#include <boost/python/class.hpp>  // NOLINT(build/include_order)\n#include <boost/python/def.hpp>  // NOLINT(build/include_order)\n#include <boost/python/dict.hpp>  // NOLINT(build/include_order)\n#include <boost/python/extract.hpp>  // NOLINT(build/include_order)\n#include <boost/python/list.hpp>  // NOLINT(build/include_order)\n#include <boost/python/object.hpp>  // NOLINT(build/include_order)\n\n#include \"gpp_common.hpp\"\n#include \"gpp_domain.hpp\"\n#include \"gpp_exception.hpp\"\n#include \"gpp_expected_improvement_gpu.hpp\"\n#include \"gpp_geometry.hpp\"\n#include \"gpp_heuristic_expected_improvement_optimization.hpp\"\n#include \"gpp_math.hpp\"\n#include \"gpp_optimization.hpp\"\n#include \"gpp_optimizer_parameters.hpp\"\n#include \"gpp_python_common.hpp\"\n\nnamespace optimal_learning {\n\nnamespace {\n\ndouble ComputeExpectedImprovementWrapper(const GaussianProcess& gaussian_process,\n                                         const boost::python::list& points_to_sample,\n                                         const boost::python::list& points_being_sampled,\n                                         int num_to_sample, int num_being_sampled,\n                                         int max_int_steps, double best_so_far,\n                                         bool force_monte_carlo,\n                                         RandomnessSourceContainer& randomness_source) {\n  PythonInterfaceInputContainer input_container(points_to_sample, points_being_sampled,\n                                                gaussian_process.dim(), num_to_sample, num_being_sampled);\n\n  bool configure_for_gradients = false;\n  if ((num_to_sample == 1) && (num_being_sampled == 0) && (force_monte_carlo == false)) {\n    OnePotentialSampleExpectedImprovementEvaluator ei_evaluator(gaussian_process, best_so_far);\n    OnePotentialSampleExpectedImprovementEvaluator::StateType ei_state(ei_evaluator,\n                                                                       input_container.points_to_sample.data(),\n                                                                       configure_for_gradients);\n    return ei_evaluator.ComputeExpectedImprovement(&ei_state);\n  } else {\n    ExpectedImprovementEvaluator ei_evaluator(gaussian_process, max_int_steps, best_so_far);\n    ExpectedImprovementEvaluator::StateType ei_state(ei_evaluator, input_container.points_to_sample.data(),\n                                                     input_container.points_being_sampled.data(),\n                                                     input_container.num_to_sample,\n                                                     input_container.num_being_sampled,\n                                                     configure_for_gradients,\n                                                     randomness_source.normal_rng_vec.data());\n    return ei_evaluator.ComputeExpectedImprovement(&ei_state);\n  }\n}\n\nboost::python::list ComputeGradExpectedImprovementWrapper(const GaussianProcess& gaussian_process,\n                                                          const boost::python::list& points_to_sample,\n                                                          const boost::python::list& points_being_sampled,\n                                                          int num_to_sample, int num_being_sampled,\n                                                          int max_int_steps, double best_so_far,\n                                                          bool force_monte_carlo,\n                                                          RandomnessSourceContainer& randomness_source) {\n  PythonInterfaceInputContainer input_container(points_to_sample, points_being_sampled, gaussian_process.dim(),\n                                                num_to_sample, num_being_sampled);\n\n  std::vector<double> grad_EI(num_to_sample*input_container.dim);\n  bool configure_for_gradients = true;\n  if ((num_to_sample == 1) && (num_being_sampled == 0) && (force_monte_carlo == false)) {\n    OnePotentialSampleExpectedImprovementEvaluator ei_evaluator(gaussian_process, best_so_far);\n    OnePotentialSampleExpectedImprovementEvaluator::StateType ei_state(ei_evaluator,\n                                                                       input_container.points_to_sample.data(),\n                                                                       configure_for_gradients);\n    ei_evaluator.ComputeGradExpectedImprovement(&ei_state, grad_EI.data());\n  } else {\n    ExpectedImprovementEvaluator ei_evaluator(gaussian_process, max_int_steps, best_so_far);\n    ExpectedImprovementEvaluator::StateType ei_state(ei_evaluator, input_container.points_to_sample.data(),\n                                                     input_container.points_being_sampled.data(),\n                                                     input_container.num_to_sample,\n                                                     input_container.num_being_sampled,\n                                                     configure_for_gradients,\n                                                     randomness_source.normal_rng_vec.data());\n    ei_evaluator.ComputeGradExpectedImprovement(&ei_state, grad_EI.data());\n  }\n\n  return VectorToPylist(grad_EI);\n}\n\n/*!\\rst\n  Utility that dispatches EI optimization based on optimizer type and num_to_sample.\n  This is just used to reduce copy-pasted code.\n\n  \\param\n    :optimizer_parameters: python/cpp_wrappers/optimization._CppOptimizerParameters\n      Python object containing the DomainTypes domain_type and OptimizerTypes optimzer_type to use as well as\n      appropriate parameter structs e.g., NewtonParameters for type kNewton).\n      See comments on the python interface for multistart_expected_improvement_optimization_wrapper\n    :gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities) that describes the\n      underlying GP\n    :input_container: PythonInterfaceInputContainer object containing data about points_being_sampled\n    :domain: object specifying the domain to optimize over (see gpp_domain.hpp)\n    :optimizer_type: type of optimization to use (e.g., null, gradient descent)\n    :num_to_sample: how many simultaneous experiments you would like to run (i.e., the q in q,p-EI)\n    :best_so_far: value of the best sample so far (must be min(points_sampled_value))\n    :max_int_steps: maximum number of MC iterations\n    :max_num_threads: maximum number of threads for use by OpenMP (generally should be <= # cores)\n    :randomness_source: object containing randomness sources (sufficient for multithreading) used in EI computation\n    :status: pydict object; cannot be None\n  \\output\n    :randomness_source: PRNG internal states modified\n    :status: modified on exit to describe whether convergence occurred\n    :best_points_to_sample[num_to_sample][dim]: next set of points to evaluate\n\\endrst*/\ntemplate <typename DomainType>\nvoid DispatchExpectedImprovementOptimization(const boost::python::object& optimizer_parameters,\n                                             const GaussianProcess& gaussian_process,\n                                             const PythonInterfaceInputContainer& input_container,\n                                             const DomainType& domain,\n                                             OptimizerTypes optimizer_type,\n                                             int num_to_sample, double best_so_far,\n                                             int max_int_steps, int max_num_threads,\n                                             bool use_gpu, int which_gpu,\n                                             RandomnessSourceContainer& randomness_source,\n                                             boost::python::dict& status,\n                                             double * restrict best_points_to_sample) {\n#ifndef OL_GPU_ENABLED\n  (void) which_gpu;  // quiet the compiler warning (unused variable)\n#endif\n\n  bool found_flag = false;\n  switch (optimizer_type) {\n    case OptimizerTypes::kNull: {\n      ThreadSchedule thread_schedule(max_num_threads, omp_sched_static);\n      // optimizer_parameters must contain an int num_random_samples field, extract it\n      int num_random_samples = boost::python::extract<int>(optimizer_parameters.attr(\"num_random_samples\"));\n\n      if (use_gpu == true) {\n#ifdef OL_GPU_ENABLED\n        CudaComputeOptimalPointsToSampleViaLatinHypercubeSearch(gaussian_process, domain, thread_schedule,\n                                                                input_container.points_being_sampled.data(),\n                                                                num_random_samples, num_to_sample,\n                                                                input_container.num_being_sampled,\n                                                                best_so_far, max_int_steps, which_gpu, &found_flag,\n                                                                &randomness_source.uniform_generator,\n                                                                best_points_to_sample);\n#else\n        OL_THROW_EXCEPTION(OptimalLearningException, \"GPU is not installed or enabled!\");\n#endif\n      } else {\n        ComputeOptimalPointsToSampleViaLatinHypercubeSearch(gaussian_process, domain, thread_schedule,\n                                                            input_container.points_being_sampled.data(),\n                                                            num_random_samples, num_to_sample,\n                                                            input_container.num_being_sampled,\n                                                            best_so_far, max_int_steps,\n                                                            &found_flag, &randomness_source.uniform_generator,\n                                                            randomness_source.normal_rng_vec.data(),\n                                                            best_points_to_sample);\n      }\n      status[std::string(\"lhc_\") + domain.kName + \"_domain_found_update\"] = found_flag;\n      break;\n    }  // end case kNull optimizer_type\n    case OptimizerTypes::kGradientDescent: {\n      // optimizer_parameters must contain a optimizer_parameters field\n      // of type GradientDescentParameters. extract it\n      const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n      ThreadSchedule thread_schedule(max_num_threads, omp_sched_dynamic);\n      int num_random_samples = boost::python::extract<int>(optimizer_parameters.attr(\"num_random_samples\"));\n\n      bool random_search_only = false;\n      if (use_gpu == true) {\n#ifdef OL_GPU_ENABLED\n        CudaComputeOptimalPointsToSample(gaussian_process, gradient_descent_parameters, domain, thread_schedule,\n                                         input_container.points_being_sampled.data(), num_to_sample,\n                                         input_container.num_being_sampled, best_so_far, max_int_steps,\n                                         random_search_only, num_random_samples, which_gpu, &found_flag,\n                                         &randomness_source.uniform_generator, best_points_to_sample);\n#else\n        OL_THROW_EXCEPTION(OptimalLearningException, \"GPU is not installed or enabled!\");\n#endif\n      } else {\n        ComputeOptimalPointsToSample(gaussian_process, gradient_descent_parameters, domain, thread_schedule,\n                                     input_container.points_being_sampled.data(), num_to_sample,\n                                     input_container.num_being_sampled, best_so_far, max_int_steps,\n                                     random_search_only, num_random_samples, &found_flag,\n                                     &randomness_source.uniform_generator,\n                                     randomness_source.normal_rng_vec.data(), best_points_to_sample);\n      }\n      status[std::string(\"gradient_descent_\") + domain.kName + \"_domain_found_update\"] = found_flag;\n      break;\n    }  // end case kGradientDescent optimizer_type\n    default: {\n      std::fill(best_points_to_sample, best_points_to_sample + input_container.dim*num_to_sample, 0.0);\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid optimizer choice. Setting all coordinates to 0.0.\");\n      break;\n    }\n  }  // end switch over optimizer_type\n}\n\nboost::python::list MultistartExpectedImprovementOptimizationWrapper(const boost::python::object& optimizer_parameters,\n                                                                     const GaussianProcess& gaussian_process,\n                                                                     const boost::python::list& domain_bounds,\n                                                                     const boost::python::list& points_being_sampled,\n                                                                     int num_to_sample, int num_being_sampled,\n                                                                     double best_so_far, int max_int_steps,\n                                                                     int max_num_threads, bool use_gpu, int which_gpu,\n                                                                     RandomnessSourceContainer& randomness_source,\n                                                                     boost::python::dict& status) {\n  // TODO(GH-131): make domain objects constructible from python; and pass them in through\n  // the optimizer_parameters python object\n\n  // abort if we do not have enough sources of randomness to run with max_num_threads\n  if (unlikely(max_num_threads > static_cast<int>(randomness_source.normal_rng_vec.size()))) {\n    OL_THROW_EXCEPTION(LowerBoundException<int>, \"Fewer randomness_sources than max_num_threads.\", randomness_source.normal_rng_vec.size(), max_num_threads);\n  }\n\n  int num_to_sample_input = 0;  // No points to sample; we are generating these via EI optimization\n  const boost::python::list points_to_sample_dummy;\n  PythonInterfaceInputContainer input_container(points_to_sample_dummy, points_being_sampled, gaussian_process.dim(), num_to_sample_input, num_being_sampled);\n  std::vector<ClosedInterval> domain_bounds_C(input_container.dim);\n  CopyPylistToClosedIntervalVector(domain_bounds, input_container.dim, domain_bounds_C);\n\n  std::vector<double> best_points_to_sample_C(input_container.dim*num_to_sample);\n\n  DomainTypes domain_type = boost::python::extract<DomainTypes>(optimizer_parameters.attr(\"domain_type\"));\n  OptimizerTypes optimizer_type = boost::python::extract<OptimizerTypes>(optimizer_parameters.attr(\"optimizer_type\"));\n  switch (domain_type) {\n    case DomainTypes::kTensorProduct: {\n      TensorProductDomain domain(domain_bounds_C.data(), input_container.dim);\n\n      DispatchExpectedImprovementOptimization(optimizer_parameters, gaussian_process, input_container,\n                                              domain, optimizer_type, num_to_sample, best_so_far,\n                                              max_int_steps, max_num_threads, use_gpu, which_gpu,\n                                              randomness_source,\n                                              status, best_points_to_sample_C.data());\n      break;\n    }  // end case OptimizerTypes::kTensorProduct\n    case DomainTypes::kSimplex: {\n      SimplexIntersectTensorProductDomain domain(domain_bounds_C.data(), input_container.dim);\n\n      DispatchExpectedImprovementOptimization(optimizer_parameters, gaussian_process, input_container,\n                                              domain, optimizer_type, num_to_sample, best_so_far,\n                                              max_int_steps, max_num_threads, use_gpu, which_gpu,\n                                              randomness_source,\n                                              status, best_points_to_sample_C.data());\n      break;\n    }  // end case OptimizerTypes::kSimplex\n    default: {\n      std::fill(best_points_to_sample_C.begin(), best_points_to_sample_C.end(), 0.0);\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid domain choice. Setting all coordinates to 0.0.\");\n      break;\n    }\n  }  // end switch over domain_type\n\n  return VectorToPylist(best_points_to_sample_C);\n}\n\n/*!\\rst\n  Utility that dispatches heuristic EI optimization (solving q,0-EI) based on optimizer type and num_to_sample.\n  This is just used to reduce copy-pasted code.\n\n  \\param\n    :optimizer_parameters: python/cpp_wrappers/optimization._CppOptimizerParameters\n      Python object containing the DomainTypes domain_type and OptimizerTypes optimzer_type to use as well as\n      appropriate parameter structs e.g., NewtonParameters for type kNewton).\n      See comments on the python interface for multistart_expected_improvement_optimization_wrapper\n    :gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities) that describes the\n      underlying GP\n    :domain: object specifying the domain to optimize over (see gpp_domain.hpp)\n    :optimizer_type: type of optimization to use (e.g., null, gradient descent)\n    :estimation_policy: the policy to use to produce (heuristic) objective function estimates during multi-points EI optimization\n    :num_to_sample: how many simultaneous experiments you would like to run (i.e., the q in q,0-EI)\n    :best_so_far: value of the best sample so far (must be min(points_sampled_value))\n    :max_num_threads: maximum number of threads for use by OpenMP (generally should be <= # cores)\n    :randomness_source: object containing randomness sources (sufficient for multithreading) used in EI computation\n    :status: pydict object; cannot be None\n  \\output\n    :randomness_source: PRNG internal states modified\n    :status: modified on exit to describe whether convergence occurred\n    :best_points_to_sample[num_to_sample][dim]: next set of points to evaluate\n\\endrst*/\ntemplate <typename DomainType>\nvoid DispatchHeuristicExpectedImprovementOptimization(const boost::python::object& optimizer_parameters,\n                                                      const GaussianProcess& gaussian_process,\n                                                      const DomainType& domain,\n                                                      OptimizerTypes optimizer_type,\n                                                      const ObjectiveEstimationPolicyInterface& estimation_policy,\n                                                      int num_to_sample, double best_so_far, int max_num_threads,\n                                                      RandomnessSourceContainer& randomness_source,\n                                                      boost::python::dict& status,\n                                                      double * restrict best_points_to_sample) {\n  ThreadSchedule thread_schedule(max_num_threads, omp_sched_dynamic);\n  bool found_flag = false;\n  switch (optimizer_type) {\n    case OptimizerTypes::kNull: {\n      // optimizer_parameters must contain an int num_multistarts field, extract it\n      int num_random_samples = boost::python::extract<int>(optimizer_parameters.attr(\"num_random_samples\"));\n\n      bool random_search_only = true;\n      GradientDescentParameters gradient_descent_parameters(0, 0, 0, 0, 1.0, 1.0, 1.0, 0.0);  // dummy struct; we aren't using gradient descent\n      ComputeHeuristicPointsToSample(gaussian_process, gradient_descent_parameters, domain,\n                                     estimation_policy, thread_schedule, best_so_far,\n                                     random_search_only, num_random_samples, num_to_sample,\n                                     &found_flag, &randomness_source.uniform_generator,\n                                     best_points_to_sample);\n\n      status[std::string(\"lhc_\") + domain.kName + \"_domain_found_update\"] = found_flag;\n      break;\n    }  // end case kNull optimizer_type\n    case OptimizerTypes::kGradientDescent: {\n      // optimizer_parameters must contain a optimizer_parameters field\n      // of type GradientDescentParameters. extract it\n      const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n      int num_random_samples = boost::python::extract<int>(optimizer_parameters.attr(\"num_random_samples\"));\n\n      bool random_search_only = false;\n      ComputeHeuristicPointsToSample(gaussian_process, gradient_descent_parameters, domain,\n                                     estimation_policy, thread_schedule, best_so_far,\n                                     random_search_only, num_random_samples, num_to_sample,\n                                     &found_flag, &randomness_source.uniform_generator,\n                                     best_points_to_sample);\n\n      status[std::string(\"gradient_descent_\") + domain.kName + \"_domain_found_update\"] = found_flag;\n      break;\n    }  // end case kGradientDescent optimizer_type\n    default: {\n      std::fill(best_points_to_sample, best_points_to_sample + gaussian_process.dim()*num_to_sample, 0.0);\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid optimizer choice. Setting all coordinates to 0.0.\");\n      break;\n    }\n  }  // end switch over optimizer_type\n}\n\nboost::python::list HeuristicExpectedImprovementOptimizationWrapper(const boost::python::object& optimizer_parameters,\n                                                                    const GaussianProcess& gaussian_process,\n                                                                    const boost::python::list& domain_bounds,\n                                                                    const ObjectiveEstimationPolicyInterface& estimation_policy,\n                                                                    int num_to_sample, double best_so_far, int max_num_threads,\n                                                                    RandomnessSourceContainer& randomness_source,\n                                                                    boost::python::dict& status) {\n  // TODO(GH-131): make domain objects constructible from python; and pass them in through\n  // the optimizer_parameters python object\n  int dim = gaussian_process.dim();\n  std::vector<ClosedInterval> domain_bounds_C(dim);\n  CopyPylistToClosedIntervalVector(domain_bounds, dim, domain_bounds_C);\n\n  std::vector<double> best_points_to_sample_C(dim*num_to_sample);\n\n  DomainTypes domain_type = boost::python::extract<DomainTypes>(optimizer_parameters.attr(\"domain_type\"));\n  OptimizerTypes optimizer_type = boost::python::extract<OptimizerTypes>(optimizer_parameters.attr(\"optimizer_type\"));\n  switch (domain_type) {\n    case DomainTypes::kTensorProduct: {\n      TensorProductDomain domain(domain_bounds_C.data(), dim);\n\n      DispatchHeuristicExpectedImprovementOptimization(optimizer_parameters, gaussian_process, domain,\n                                                       optimizer_type, estimation_policy, num_to_sample,\n                                                       best_so_far, max_num_threads, randomness_source,\n                                                       status, best_points_to_sample_C.data());\n      break;\n    }  // end case OptimizerTypes::kTensorProduct\n    case DomainTypes::kSimplex: {\n      SimplexIntersectTensorProductDomain domain(domain_bounds_C.data(), dim);\n\n      DispatchHeuristicExpectedImprovementOptimization(optimizer_parameters, gaussian_process, domain,\n                                                       optimizer_type, estimation_policy, num_to_sample,\n                                                       best_so_far, max_num_threads, randomness_source,\n                                                       status, best_points_to_sample_C.data());\n      break;\n    }  // end case OptimizerTypes::kSimplex\n    default: {\n      std::fill(best_points_to_sample_C.begin(), best_points_to_sample_C.end(), 0.0);\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid domain choice. Setting all coordinates to 0.0.\");\n      break;\n    }\n  }  // end switch over domain_type\n\n  return VectorToPylist(best_points_to_sample_C);\n}\n\nboost::python::list EvaluateEIAtPointListWrapper(const GaussianProcess& gaussian_process,\n                                                 const boost::python::list& initial_guesses,\n                                                 const boost::python::list& points_being_sampled,\n                                                 int num_multistarts, int num_to_sample,\n                                                 int num_being_sampled, double best_so_far,\n                                                 int max_int_steps, int max_num_threads,\n                                                 RandomnessSourceContainer& randomness_source,\n                                                 boost::python::dict& status) {\n  // abort if we do not have enough sources of randomness to run with max_num_threads\n  if (unlikely(max_num_threads > static_cast<int>(randomness_source.normal_rng_vec.size()))) {\n    OL_THROW_EXCEPTION(LowerBoundException<int>, \"Fewer randomness_sources than max_num_threads.\", randomness_source.normal_rng_vec.size(), max_num_threads);\n  }\n\n  int num_to_sample_input = 0;  // No points to sample; we are generating these via EI optimization\n  const boost::python::list points_to_sample_dummy;\n  PythonInterfaceInputContainer input_container(points_to_sample_dummy, points_being_sampled, gaussian_process.dim(),\n                                                num_to_sample_input, num_being_sampled);\n  std::vector<double> result_point_C(input_container.dim);  // not used\n  std::vector<double> result_function_values_C(num_multistarts);\n  std::vector<double> initial_guesses_C(input_container.dim * num_multistarts);\n\n  CopyPylistToVector(initial_guesses, input_container.dim * num_multistarts, initial_guesses_C);\n\n  ThreadSchedule thread_schedule(max_num_threads, omp_sched_static);\n  bool found_flag = false;\n  EvaluateEIAtPointList(gaussian_process, thread_schedule, initial_guesses_C.data(),\n                        input_container.points_being_sampled.data(), num_multistarts,\n                        num_to_sample, input_container.num_being_sampled, best_so_far,\n                        max_int_steps, &found_flag, randomness_source.normal_rng_vec.data(),\n                        result_function_values_C.data(), result_point_C.data());\n\n  status[\"evaluate_EI_at_point_list\"] = found_flag;\n\n  return VectorToPylist(result_function_values_C);\n}\n\n}  // end unnamed namespace\n\nvoid ExportEstimationPolicies() {\n  boost::python::class_<ObjectiveEstimationPolicyInterface, boost::noncopyable>(\"ObjectiveEstimationPolicyInterface\", R\"%%(\n    Pure abstract (in the C++ sense) base class for objective function estimation (e.g., Constant Liar, Kriging Believer).\n    Serves no purpose in Python but is needed by boost to allow pointer casts of derived types to this type.\n    )%%\", boost::python::no_init);\n\n  boost::python::class_<ConstantLiarEstimationPolicy, boost::python::bases<ObjectiveEstimationPolicyInterface> >(\"ConstantLiarEstimationPolicy\", R\"%%(\n    Produces objective function estimates at a \"point\" using the \"Constant Liar\" heuristic.\n\n    Always outputs function_value = lie_value (the \"constant lie\") and noise_variance = lie_noise_variance, regardless\n    of the value of \"point\".\n\n    :ivar lie_value: (*float64*) the \"constant lie\" that this estimator should return\n    :ivar lie_noise_variance: (*float64*) the noise_variance to associate to the lie_value (MUST be >= 0.0)\n    )%%\", boost::python::init<double, double>(R\"%%(\n    Constructs a ConstantLiarEstimationPolicy object.\n\n    :param lie_value: the \"constant lie\" that this estimator should return\n    :type lie_value: float64 (finite)\n    :param lie_noise_variance: the noise_variance to associate to the lie_value (MUST be >= 0.0)\n    :type lie_noise_variance: float64 >= 0.0\n    )%%\"));\n\n  boost::python::class_<KrigingBelieverEstimationPolicy, boost::python::bases<ObjectiveEstimationPolicyInterface> >(\"KrigingBelieverEstimationPolicy\", R\"%%(\n    Produces objective function estimates at a \"point\" using the \"Kriging Believer\" heuristic.\n\n    Requires a valid GaussianProcess (GP) to produce estimates. Computes estimates as:\n\n    * function_value = GP.Mean(point) + std_deviation_coef * sqrt(GP.Variance(point))\n    * noise_variance = kriging_noise_variance\n\n    :ivar std_deviation_coef: (*float64*) the relative amount of bias (in units of GP std deviation) to introduce into the GP mean\n    :ivar kriging_noise_variance: (*float64*) the noise_variance to associate to each function value estimate (MUST be >= 0.0)\n    )%%\", boost::python::init<double, double>(R\"%%(\n    Constructs for KrigingBelieverEstimationPolicy object.\n\n    :param std_deviation_coef: the relative amount of bias (in units of GP std deviation) to introduce into the GP mean\n    :type std_deviation_coef: float64 (finite)\n    :param kriging_noise_variance: the noise_variance to associate to each function value estimate (MUST be >= 0.0)\n    :type kriging_noise_variance: float64 >= 0.0\n    )%%\"));\n}\n\nvoid ExportExpectedImprovementFunctions() {\n  boost::python::def(\"compute_expected_improvement\", ComputeExpectedImprovementWrapper, R\"%%(\n    Compute expected improvement.\n    If ``num_to_sample == 1`` and ``num_being_sampled == 0`` AND ``force_monte_carlo is false``, this will\n    use (fast/accurate) analytic evaluation.\n    Otherwise monte carlo-based EI computation is used.\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param points_to_sample: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate EI and/or its gradient\n    :type points_to_sample: list of float64 with shape (num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param force_monte_carlo: true to force monte carlo evaluation of EI\n    :type force_monte_carlo: bool\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :return: computed EI\n    :rtype: float64 >= 0.0\n    )%%\");\n\n  boost::python::def(\"compute_grad_expected_improvement\", ComputeGradExpectedImprovementWrapper, R\"%%(\n    Compute the gradient of expected improvement evaluated at points_to_sample.\n    If num_to_sample = 1 and num_being_sampled = 0 AND force_monte_carlo is false, this will\n    use (fast/accurate) analytic evaluation.\n    Otherwise monte carlo-based EI computation is used.\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param points_to_sample: initial points to load into state (must be a valid point for the problem);\n      i.e., points at which to evaluate EI and/or its gradient\n    :type points_to_sample: list of float64 with shape (num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param force_monte_carlo: true to force monte carlo evaluation of EI\n    :type force_monte_carlo: bool\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :return: gradient of EI (computed at points_to_sample + points_being_sampled, wrt points_to_sample)\n    :rtype: list of float64 with shape (num_to_sample, dim)\n    )%%\");\n\n  boost::python::def(\"multistart_expected_improvement_optimization\", MultistartExpectedImprovementOptimizationWrapper, R\"%%(\n    Optimize expected improvement (i.e., solve q,p-EI) over the specified domain using the specified optimization method.\n    Can optimize for num_to_sample new points to sample (i.e., aka \"q\", experiments to run) simultaneously.\n    Allows the user to specify num_being_sampled (aka \"p\") ongoing/concurrent experiments.\n\n    The _CppOptimizerParameters object is a python class defined in:\n    python/cpp_wrappers/optimization._CppOptimizerParameters\n    See that class definition for more details.\n\n    This function expects it to have the fields:\n\n    * domain_type (DomainTypes enum from this file)\n    * optimizer_type (OptimizerTypes enum from this file)\n    * num_random_samples (int, number of samples to 'dumb' search over, if 'dumb' search is being used.\n      e.g., if optimizer = kNull or if to_sample > 1)\n    * optimizer_parameters (*Parameters struct (gpp_optimizer_parameters.hpp) where * matches optimizer_type\n      unused if optimizer_type == kNull)\n\n    This function also has the option of using GPU to compute general q,p-EI via MC simulation. To enable it,\n    make sure you have installed GPU components of MOE, otherwise, it will throw Runtime excpetion.\n\n    .. WARNING:: this function FAILS and returns an EMPTY LIST if the number of random sources < max_num_threads\n\n    :param optimizer_parameters: python object containing the DomainTypes domain_type and\n      OptimizerTypes optimzer_type to use as well as\n      appropriate parameter structs e.g., NewtonParameters for type kNewton)\n    :type optimizer_parameters: _CppOptimizerParameters\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param domain: [lower, upper] bound pairs for each dimension\n    :type domain: list of float64 with shape (dim, 2)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param use_gpu: set to 1 if user wants to use GPU for MC computation\n    :type use_gpu: bool\n    :param which_gpu: GPU device ID\n    :type which_gpu: int >= 0\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: next set of points to eval\n    :rtype: list of float64 with shape (num_to_sample, dim)\n    )%%\");\n\n  boost::python::def(\"heuristic_expected_improvement_optimization\", HeuristicExpectedImprovementOptimizationWrapper, R\"%%(\n    Compute a heuristic approximation to the result of multistart_expected_improvement_optimization(). That is, it\n    optimizes an approximation to q,0-EI over the specified domain using the specified optimization method.\n    Can optimize for num_to_sample (aka \"q\") new points to sample (i.e., experiments to run) simultaneously.\n\n    Computing q,p-EI for q > 1 or p > 1 is expensive. To avoid that cost, this method \"solves\" q,0-EI by repeatedly\n    optimizing 1,0-EI. We do the following (in C++)::\n\n      for i in xrange(num_to_sample):\n        new_point = optimize_1_EI(gaussian_process, ...)\n        new_function_value, new_noise_variance = estimation_policy.compute_estimate(new_point, gaussian_process, i)\n        gaussian_process.add_point(new_point, new_function_value, new_noise_variance)\n\n    So using estimation_policy, we guess what the real-world objective function value would be, evaluated at the result\n    of each 1-EI optimization. Then we treat this estimate as *truth* and feed it back to the gaussian process. The\n    ConstantLiar and KrigingBelieverEstimationPolicy objects reproduce the heuristics described in Ginsbourger 2008.\n\n    See gpp_heuristic_expected_improvement_optimization.hpp for further details on the algorithm.\n\n    The _CppOptimizerParameters object is a python class defined in:\n    ``python/cpp_wrappers/optimization._CppOptimizerParameters``\n    See that class definition for more details.\n\n    This function expects it to have the fields:\n\n    * domain_type (DomainTypes enum from this file)\n    * optimizer_type (OptimizerTypes enum from this file)\n    * num_random_samples (int, number of samples to 'dumb' search over, if 'dumb' search is being used.\n      e.g., if optimizer = kNull or if to_sample > 1)\n    * optimizer_parameters (*Parameters struct (gpp_optimizer_parameters.hpp) where * matches optimizer_type\n      unused if optimizer_type == kNull)\n\n    .. WARNING:: this function FAILS and returns an EMPTY LIST if the number of random sources < max_num_threads\n\n    :param optimizer_parameters: python object containing the DomainTypes domain_type and\n      OptimizerTypes optimzer_type to use as well as\n      appropriate parameter structs e.g., NewtonParameters for type kNewton)\n    :type optimizer_parameters: _CppOptimizerParameters\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param domain: [lower, upper] bound pairs for each dimension\n    :type domain: list of float64 with shape (dim, 2)\n    :param estimation_policy: the policy to use to produce (heuristic) objective function estimates\n      during q,0-EI optimization (e.g., ConstantLiar, KrigingBeliever)\n    :type estimation_policy: ObjectiveEstimationPolicyInterface\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: next set of points to eval\n    :rtype: list of float64 with shape (num_to_sample, dim)\n    )%%\");\n\n  boost::python::def(\"evaluate_EI_at_point_list\", EvaluateEIAtPointListWrapper, R\"%%(\n    Evaluates the expected improvement at each point in initial_guesses; can handle q,p-EI.\n    Useful for plotting.\n\n    Equivalent to::\n\n      result = []\n      for point in initial_guesses:\n          result.append(compute_expected_improvement(point, ...))\n\n    But this method is substantially faster (loop in C++ and multithreaded).\n\n    .. WARNING:: this function FAILS and returns an EMPTY LIST if the number of random sources < max_num_threads\n\n\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n\n\n    :param gaussian_process: GaussianProcess object (holds points_sampled, values, noise_variance, derived quantities)\n    :type gaussian_process: GPP.GaussianProcess (boost::python ctor wrapper around optimal_learning::GaussianProcess)\n    :param initial_guesses: points at which to evaluate EI\n    :type initial_guesses: list of flaot64 with shape (num_multistarts, num_to_sample, dim)\n    :param points_being_sampled: points that are being sampled in concurrently experiments\n    :type points_being_sampled: list of float64 with shape (num_being_sampled, dim)\n    :param num_multistarts: number of points at which to evaluate EI\n    :type num_multistarts: int > 0\n    :param num_to_sample: number of potential future samples; gradients are evaluated wrt these points (i.e., the \"q\" in q,p-EI)\n    :type num_to_sample: int > 0\n    :param num_being_sampled: number of points being sampled concurrently (i.e., the p in q,p-EI)\n    :type num_being_sampled: int >= 0\n    :param best_so_far: best known value of objective so far\n    :type best_so_far: float64\n    :param max_int_steps: number of MC integration points in EI\n    :type max_int_steps: int >= 0\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: EI values at each point of the initial_guesses list, in the same order\n    :rtype: list of float64 with shape (num_multistarts, )\n    )%%\");\n}\n\n}  // end namespace optimal_learning\n", "meta": {"hexsha": "f6a85f2486eb069e497afeda664ca74810b10d1b", "size": 43907, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_python_expected_improvement.cpp", "max_stars_repo_name": "dstoeckel/MOE", "max_stars_repo_head_hexsha": "5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 966.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T05:27:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T21:04:36.000Z", "max_issues_repo_path": "moe/optimal_learning/cpp/gpp_python_expected_improvement.cpp", "max_issues_repo_name": "dstoeckel/MOE", "max_issues_repo_head_hexsha": "5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2015-01-16T22:33:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:33:27.000Z", "max_forks_repo_path": "moe/optimal_learning/cpp/gpp_python_expected_improvement.cpp", "max_forks_repo_name": "dstoeckel/MOE", "max_forks_repo_head_hexsha": "5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 143.0, "max_forks_repo_forks_event_min_datetime": "2015-01-07T03:57:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T01:10:45.000Z", "avg_line_length": 62.9942611191, "max_line_length": 171, "alphanum_fraction": 0.6741749607, "num_tokens": 8901, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.22794883481344563}}
{"text": "// This file is part of LatNet Builder.\n//\n// Copyright (C) 2012-2021  The LatNet Builder author's, supervised by Pierre L'Ecuyer, Universite de Montreal.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"latbuilder/Parser/MeritFilter.h\"\n#include \"latbuilder/Parser/LevelWeights.h\"\n#include \"latbuilder/MeritFilter.h\"\n#include \"latbuilder/Norm/Normalizer.h\"\n#include \"latbuilder/Norm/PAlphaSL10.h\"\n#include \"latbuilder/Norm/PAlphaDPW08.h\"\n#include \"latbuilder/Norm/PAlphaTilde.h\"\n#include \"latbuilder/Norm/IAAlpha.h\"\n#include \"latbuilder/Norm/IB.h\"\n#include \"latbuilder/Functor/LowPass.h\"\n\n#include <boost/lexical_cast.hpp>\n\nnamespace LatBuilder { namespace Parser {\n\nnamespace {\n\n   template <LatticeType LR, class NORM>\n   void setLevelWeights(\n         Norm::Normalizer<LR, EmbeddingType::UNILEVEL, NORM>&,\n         const std::string&,\n         const LatBuilder::SizeParam<LR, EmbeddingType::UNILEVEL>&\n         )\n   {}\n\n   template <LatticeType LR, class NORM>\n   void setLevelWeights(\n         Norm::Normalizer<LR, EmbeddingType::MULTILEVEL, NORM>& normalizer,\n         const std::string& levelWeights,\n         const LatBuilder::SizeParam<LR, EmbeddingType::MULTILEVEL>& sizeParam\n         )\n   { normalizer.setWeights(LevelWeights<LR>::parse(levelWeights, sizeParam)); }\n\n   template <LatticeType LR, class NORM, EmbeddingType ET>\n   std::unique_ptr<BasicMeritFilter<LR, ET>> createNormalizer(\n         unsigned int alpha,\n         const LatBuilder::SizeParam<LR, ET>& sizeParam,\n         const LatticeTester::Weights& weights,\n         Real normType,\n         const std::string& levelWeights\n         )\n   {\n      auto normalizer = new LatBuilder::Norm::Normalizer<LR, ET, NORM>(NORM(alpha, weights, normType));\n      setLevelWeights(*normalizer, levelWeights, sizeParam);\n      return std::unique_ptr<BasicMeritFilter<LR, ET>>(normalizer);\n   }\n\n   template <LatticeType LR, EmbeddingType ET> void correctLevelWeights(\n         const LatBuilder::SizeParam<LR, ET>& sizeParam, \n         const std::string& combiner,\n         std::string& levelWeights);\n\n   template <LatticeType LR>\n   void correctLevelWeights(\n         const LatBuilder::SizeParam<LR, EmbeddingType::UNILEVEL>& sizeParam, \n         const std::string& combiner,\n         std::string& levelWeights)\n      {}\n\n   template <LatticeType LR>\n   void correctLevelWeights(\n         const LatBuilder::SizeParam<LR, EmbeddingType::MULTILEVEL>& sizeParam, \n         const std::string& combiner,\n         std::string& levelWeights)\n      {\n            const auto strCombinerSplit = splitPair<>(combiner, ':');\n            if (strCombinerSplit.first == \"level\") {\n                  if (strCombinerSplit.second == \"max\"){\n                        levelWeights = \"select:\" + std::to_string(sizeParam.maxLevel());\n                  }\n                  else {\n                        try {\n                              levelWeights = \"select:\" + std::to_string(boost::lexical_cast<Level>(strCombinerSplit.second)) + \",\" + std::to_string(boost::lexical_cast<Level>(strCombinerSplit.second));\n                        }\n                        catch (boost::bad_lexical_cast&) {}\n                  }\n            }\n      }\n\n   /**\n    * Parses the bound PAlphaSL10.\n    *\n    * Example strings: \\c P2-SL10, \\c P4-SL10, \\c P2-DPW08, \\c P4-DPW08\n    */\n   template <LatticeType LR, EmbeddingType ET>\n   std::unique_ptr<BasicMeritFilter<LR, ET>> parseNormalizer(\n         const std::string& str,\n         const std::string& figure,\n         const LatBuilder::SizeParam<LR, ET>& sizeParam,\n         const LatticeTester::Weights& weights,\n         Real normType,\n         std::string combiner\n         )\n   {\n      auto figureSplit = splitPair(figure, ':');\n      std::string figureString = (figureSplit.second == \"\") ? figure : figureSplit.second;\n      std::set<std::string> admissibleNormalizations;\n      if (figureString[0] == 'P') {\n            admissibleNormalizations.insert(\"P\" + figureString.substr(1));\n            if (LR == LatticeType::ORDINARY)\n            {\n                  admissibleNormalizations.insert(\"P\" + figureString.substr(1) + \"-SL10\");\n                  admissibleNormalizations.insert(\"P\" + figureString.substr(1) + \"-DPW08\");\n            }\n      }\n      else if (figureString[0] == 'I')\n      {\n            if (figureString[1] == 'A')\n            {\n                  admissibleNormalizations.insert(\"IA\" + figureString.substr(2));\n            }\n            else if (figureString[1] == 'B') {\n                  admissibleNormalizations.insert(\"IB\");\n            }\n      }\n\n      std::string newNormString = str;\n      if (figure != \"\" && admissibleNormalizations.size() == 0)\n            throw BadFilter(\"No normalizations are available with figure \" + figure + \".\");\n\n      if ( (str.size() >= 6 && str.substr(0,6)==\"select\") || str.size() == 0)\n      {\n            newNormString =  *admissibleNormalizations.begin() + \":\" + newNormString;\n      }\n\n      auto args = splitPair(newNormString, ':');\n      if (figure != \"\" && admissibleNormalizations.find(args.first) == admissibleNormalizations.end())\n      {\n            throw BadFilter(\"Normalization \" + str + \" is incompatible with figure\" + figure + ( (LR == LatticeType::POLYNOMIAL) ? \" with lattice type polynomial.\" : \".\"));\n      } \n      const auto strSplit = splitPair<>(args.first, '-');\n\n      correctLevelWeights(sizeParam, combiner, args.second);\n\n      \n      try {\n      if (strSplit.first[0] == 'P') {\n            const auto alpha = boost::lexical_cast<unsigned int>(strSplit.first.substr(1));\n            if (strSplit.second == \"\")\n            {\n                  if (LR == LatticeType::ORDINARY)\n                  {\n                        return createNormalizer<LR, LatBuilder::Norm::PAlphaSL10, ET>(alpha, sizeParam, weights, normType, args.second);\n                  }\n                  else if (LR == LatticeType::POLYNOMIAL)\n                  {\n                        return createNormalizer<LR, LatBuilder::Norm::PAlphaTilde, ET>(alpha, sizeParam, weights, normType, args.second);\n                  }\n            }\n            if (strSplit.second == \"SL10\")\n            return createNormalizer<LR, LatBuilder::Norm::PAlphaSL10, ET>(alpha, sizeParam, weights, normType, args.second);\n            else if (strSplit.second == \"DPW08\")\n            return createNormalizer<LR, LatBuilder::Norm::PAlphaDPW08, ET>(alpha, sizeParam, weights, normType, args.second);   \n      }\n      if (strSplit.first[0] == 'I')\n      {\n            if (strSplit.first[1] == 'A')\n            {\n                  const auto alpha = boost::lexical_cast<unsigned int>(strSplit.first.substr(2));\n                  return createNormalizer<LR, LatBuilder::Norm::IAAlpha, ET>(alpha, sizeParam, weights, normType, args.second);\n            }\n            if (strSplit.first[1] == 'B')\n            {\n                  return createNormalizer<LR, LatBuilder::Norm::IB, ET>(weights.interlacingFactor(), sizeParam, weights, normType, args.second);\n            }\n      }\n      }\n      catch (boost::bad_lexical_cast&) {}\n      throw BadFilter(\"cannot parse norm: \" + str);\n      \n   }\n}\n\ntemplate <LatticeType LR, EmbeddingType ET>\nstd::unique_ptr<BasicMeritFilter<LR, ET>>\nMeritFilter<LR,ET>::parse(\n      const std::string& str,\n      const std::string& figure,\n      const LatBuilder::SizeParam<LR, ET>& sizeParam,\n      const LatticeTester::Weights& weights,\n      Real normType,\n      std::string combiner\n      )\n{\n   const auto x = splitPair(str, ':');\n   if (x.first == \"norm\")\n      return parseNormalizer(x.second, figure, sizeParam, weights, normType, combiner);\n   else if (x.first == \"low-pass\") {\n      auto threshold = boost::lexical_cast<Real>(x.second);\n      return std::unique_ptr<BasicMeritFilter<LR, ET>>(new LatBuilder::MeritFilter<LR, ET>(Functor::LowPass<Real>(threshold), str));\n   }\n   throw BadFilter(x.first);\n}\n\ntemplate struct LatBuilder::Parser::MeritFilter <LatticeType::ORDINARY, EmbeddingType::UNILEVEL> ;\ntemplate struct LatBuilder::Parser::MeritFilter <LatticeType::ORDINARY, EmbeddingType::MULTILEVEL> ;\ntemplate struct LatBuilder::Parser::MeritFilter <LatticeType::POLYNOMIAL, EmbeddingType::UNILEVEL> ;\ntemplate struct LatBuilder::Parser::MeritFilter <LatticeType::POLYNOMIAL, EmbeddingType::MULTILEVEL> ;\n\n}}\n", "meta": {"hexsha": "8a838219ed333055ceccc1ee26b52a572f10df48", "size": 8786, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LatBuilder/Parser/MeritFilter.cc", "max_stars_repo_name": "YochevedDarmon/latnetbuilder", "max_stars_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T06:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T16:11:31.000Z", "max_issues_repo_path": "src/LatBuilder/Parser/MeritFilter.cc", "max_issues_repo_name": "YochevedDarmon/latnetbuilder", "max_issues_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:07:49.000Z", "max_forks_repo_path": "src/LatBuilder/Parser/MeritFilter.cc", "max_forks_repo_name": "YochevedDarmon/latnetbuilder", "max_forks_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T19:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T20:00:47.000Z", "avg_line_length": 40.4884792627, "max_line_length": 201, "alphanum_fraction": 0.618028682, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.44167300566462564, "lm_q1q2_score": 0.22773539795792525}}
{"text": "///////////////////////////////////////////////////////////////\n//  Copyright 2012 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n#ifndef BOOST_MATH_FLOAT_BACKEND_HPP\n#define BOOST_MATH_FLOAT_BACKEND_HPP\n\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <boost/cstdint.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/math/concepts/real_concept.hpp>\n#include <nil/crypto3/multiprecision/number.hpp>\n#include <boost/integer/common_factor_rt.hpp>\n#include <boost/type_traits/common_type.hpp>\n#include <boost/container_hash/hash.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace multiprecision {\n            namespace backends {\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable : 4389 4244 4018 4244 4127)\n#endif\n\n                template<class Arithmetic>\n                struct arithmetic_backend {\n                    typedef boost::mpl::list<short, int, long, long long> signed_types;\n                    typedef boost::mpl::list<unsigned short, unsigned, unsigned long, unsigned long long>\n                        unsigned_types;\n                    typedef boost::mpl::list<float, double, long double> float_types;\n                    typedef int exponent_type;\n\n                    BOOST_MP_CXX14_CONSTEXPR arithmetic_backend() : m_value(0) {\n                    }\n                    BOOST_MP_CXX14_CONSTEXPR arithmetic_backend(const arithmetic_backend& o) : m_value(o.m_value) {\n                    }\n                    template<class A>\n                    BOOST_MP_CXX14_CONSTEXPR\n                        arithmetic_backend(const A& o,\n                                           const typename boost::enable_if<boost::is_arithmetic<A>>::type* = 0) :\n                        m_value(o) {\n                    }\n                    template<class A>\n                    BOOST_MP_CXX14_CONSTEXPR arithmetic_backend(const arithmetic_backend<A>& o) : m_value(o.data()) {\n                    }\n                    BOOST_MP_CXX14_CONSTEXPR arithmetic_backend& operator=(const arithmetic_backend& o) {\n                        m_value = o.m_value;\n                        return *this;\n                    }\n                    template<class A>\n                    BOOST_MP_CXX14_CONSTEXPR\n                        typename boost::enable_if<boost::is_arithmetic<A>, arithmetic_backend&>::type\n                        operator=(A i) {\n                        m_value = i;\n                        return *this;\n                    }\n                    template<class A>\n                    BOOST_MP_CXX14_CONSTEXPR arithmetic_backend& operator=(const arithmetic_backend<A>& i) {\n                        m_value = i.data();\n                        return *this;\n                    }\n                    arithmetic_backend& operator=(const char* s) {\n#ifndef BOOST_NO_EXCEPTIONS\n                        try {\n#endif\n                            m_value = boost::lexical_cast<Arithmetic>(s);\n#ifndef BOOST_NO_EXCEPTIONS\n                        } catch (const boost::bad_lexical_cast&) {\n                            throw std::runtime_error(std::string(\"Unable to interpret the string provided: \\\"\") + s +\n                                                     std::string(\"\\\" as a compatible number type.\"));\n                        }\n#endif\n                        return *this;\n                    }\n                    BOOST_MP_CXX14_CONSTEXPR void swap(arithmetic_backend& o) {\n                        std::swap(m_value, o.m_value);\n                    }\n                    std::string str(std::streamsize digits, std::ios_base::fmtflags f) const {\n                        std::stringstream ss;\n                        ss.flags(f);\n                        ss << std::setprecision(digits ? digits : std::numeric_limits<Arithmetic>::digits10 + 4)\n                           << m_value;\n                        return ss.str();\n                    }\n                    BOOST_MP_CXX14_CONSTEXPR void do_negate(const boost::mpl::true_&) {\n                        m_value = 1 + ~m_value;\n                    }\n                    BOOST_MP_CXX14_CONSTEXPR void do_negate(const boost::mpl::false_&) {\n                        m_value = -m_value;\n                    }\n                    BOOST_MP_CXX14_CONSTEXPR void negate() {\n                        do_negate(boost::mpl::bool_<boost::is_unsigned<Arithmetic>::value>());\n                    }\n                    BOOST_MP_CXX14_CONSTEXPR int compare(const arithmetic_backend& o) const {\n                        return m_value > o.m_value ? 1 : (m_value < o.m_value ? -1 : 0);\n                    }\n                    template<class A>\n                    BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_arithmetic<A>, int>::type\n                        compare(A i) const {\n                        return m_value > static_cast<Arithmetic>(i) ? 1 :\n                                                                      (m_value < static_cast<Arithmetic>(i) ? -1 : 0);\n                    }\n                    BOOST_MP_CXX14_CONSTEXPR Arithmetic& data() {\n                        return m_value;\n                    }\n                    BOOST_MP_CXX14_CONSTEXPR const Arithmetic& data() const {\n                        return m_value;\n                    }\n\n                private:\n                    Arithmetic m_value;\n                };\n\n                template<class R, class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if_c<boost::is_integral<R>::value>::type\n                    eval_convert_to(R* result, const arithmetic_backend<Arithmetic>& backend) {\n                    typedef typename boost::common_type<R, Arithmetic>::type c_type;\n                    BOOST_CONSTEXPR const c_type max = static_cast<c_type>((std::numeric_limits<R>::max)());\n                    BOOST_CONSTEXPR const c_type min = static_cast<c_type>((std::numeric_limits<R>::min)());\n                    c_type ct = static_cast<c_type>(backend.data());\n                    if ((backend.data() < 0) && !std::numeric_limits<R>::is_signed)\n                        BOOST_THROW_EXCEPTION(std::range_error(\"Attempt to convert negative number to unsigned type.\"));\n                    if (ct > max)\n                        *result = boost::is_signed<R>::value ? (std::numeric_limits<R>::max)() : backend.data();\n                    else if (std::numeric_limits<Arithmetic>::is_signed && (ct < min))\n                        *result = (std::numeric_limits<R>::min)();\n                    else\n                        *result = backend.data();\n                }\n\n                template<class R, class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::disable_if_c<boost::is_integral<R>::value>::type\n                    eval_convert_to(R* result, const arithmetic_backend<Arithmetic>& backend) {\n                    *result = backend.data();\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR bool eval_eq(const arithmetic_backend<Arithmetic>& a,\n                                                             const arithmetic_backend<Arithmetic>& b) {\n                    return a.data() == b.data();\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_arithmetic<A2>, bool>::type\n                    eval_eq(const arithmetic_backend<Arithmetic>& a, const A2& b) {\n                    return a.data() == static_cast<Arithmetic>(b);\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR bool eval_lt(const arithmetic_backend<Arithmetic>& a,\n                                                             const arithmetic_backend<Arithmetic>& b) {\n                    return a.data() < b.data();\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_arithmetic<A2>, bool>::type\n                    eval_lt(const arithmetic_backend<Arithmetic>& a, const A2& b) {\n                    return a.data() < static_cast<Arithmetic>(b);\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR bool eval_gt(const arithmetic_backend<Arithmetic>& a,\n                                                             const arithmetic_backend<Arithmetic>& b) {\n                    return a.data() > b.data();\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_arithmetic<A2>, bool>::type\n                    eval_gt(const arithmetic_backend<Arithmetic>& a, const A2& b) {\n                    return a.data() > static_cast<Arithmetic>(b);\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_add(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& o) {\n                    result.data() += o.data();\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_subtract(arithmetic_backend<Arithmetic>& result,\n                                                                   const arithmetic_backend<Arithmetic>& o) {\n                    result.data() -= o.data();\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_multiply(arithmetic_backend<Arithmetic>& result,\n                                                                   const arithmetic_backend<Arithmetic>& o) {\n                    result.data() *= o.data();\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR\n                    typename boost::enable_if_c<std::numeric_limits<Arithmetic>::has_infinity>::type\n                    eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o) {\n                    result.data() /= o.data();\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR\n                    typename boost::disable_if_c<std::numeric_limits<Arithmetic>::has_infinity>::type\n                    eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& o) {\n                    if (!o.data())\n                        BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\n                    result.data() /= o.data();\n                }\n\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_arithmetic<A2>>::type\n                    eval_add(arithmetic_backend<Arithmetic>& result, const A2& o) {\n                    result.data() += o;\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_arithmetic<A2>>::type\n                    eval_subtract(arithmetic_backend<Arithmetic>& result, const A2& o) {\n                    result.data() -= o;\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_arithmetic<A2>>::type\n                    eval_multiply(arithmetic_backend<Arithmetic>& result, const A2& o) {\n                    result.data() *= o;\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR\n                    typename boost::enable_if_c<(boost::is_arithmetic<A2>::value &&\n                                                 !std::numeric_limits<Arithmetic>::has_infinity)>::type\n                    eval_divide(arithmetic_backend<Arithmetic>& result, const A2& o) {\n                    if (!o)\n                        BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\n                    result.data() /= o;\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR\n                    typename boost::enable_if_c<(boost::is_arithmetic<A2>::value &&\n                                                 std::numeric_limits<Arithmetic>::has_infinity)>::type\n                    eval_divide(arithmetic_backend<Arithmetic>& result, const A2& o) {\n                    result.data() /= o;\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_add(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& a,\n                                                              const arithmetic_backend<Arithmetic>& b) {\n                    result.data() = a.data() + b.data();\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_subtract(arithmetic_backend<Arithmetic>& result,\n                                                                   const arithmetic_backend<Arithmetic>& a,\n                                                                   const arithmetic_backend<Arithmetic>& b) {\n                    result.data() = a.data() - b.data();\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_multiply(arithmetic_backend<Arithmetic>& result,\n                                                                   const arithmetic_backend<Arithmetic>& a,\n                                                                   const arithmetic_backend<Arithmetic>& b) {\n                    result.data() = a.data() * b.data();\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR\n                    typename boost::enable_if_c<std::numeric_limits<Arithmetic>::has_infinity>::type\n                    eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a,\n                                const arithmetic_backend<Arithmetic>& b) {\n                    result.data() = a.data() / b.data();\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR\n                    typename boost::disable_if_c<std::numeric_limits<Arithmetic>::has_infinity>::type\n                    eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a,\n                                const arithmetic_backend<Arithmetic>& b) {\n                    if (!b.data())\n                        BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\n                    result.data() = a.data() / b.data();\n                }\n\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_arithmetic<A2>>::type\n                    eval_add(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a,\n                             const A2& b) {\n                    result.data() = a.data() + b;\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_arithmetic<A2>>::type\n                    eval_subtract(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a,\n                                  const A2& b) {\n                    result.data() = a.data() - b;\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_arithmetic<A2>>::type\n                    eval_multiply(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a,\n                                  const A2& b) {\n                    result.data() = a.data() * b;\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR\n                    typename boost::enable_if_c<(boost::is_arithmetic<A2>::value &&\n                                                 !std::numeric_limits<Arithmetic>::has_infinity)>::type\n                    eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a,\n                                const A2& b) {\n                    if (!b)\n                        BOOST_THROW_EXCEPTION(std::overflow_error(\"Divide by zero\"));\n                    result.data() = a.data() / b;\n                }\n                template<class Arithmetic, class A2>\n                inline BOOST_MP_CXX14_CONSTEXPR\n                    typename boost::enable_if_c<(boost::is_arithmetic<A2>::value &&\n                                                 std::numeric_limits<Arithmetic>::has_infinity)>::type\n                    eval_divide(arithmetic_backend<Arithmetic>& result, const arithmetic_backend<Arithmetic>& a,\n                                const A2& b) {\n                    result.data() = a.data() / b;\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR bool eval_is_zero(const arithmetic_backend<Arithmetic>& val) {\n                    return val.data() == 0;\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR\n                    typename boost::enable_if_c<(!std::numeric_limits<Arithmetic>::is_specialized ||\n                                                 std::numeric_limits<Arithmetic>::is_signed),\n                                                int>::type\n                    eval_get_sign(const arithmetic_backend<Arithmetic>& val) {\n                    return val.data() == 0 ? 0 : val.data() < 0 ? -1 : 1;\n                }\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR\n                    typename boost::disable_if_c<(std::numeric_limits<Arithmetic>::is_specialized ||\n                                                  std::numeric_limits<Arithmetic>::is_signed),\n                                                 int>::type\n                    eval_get_sign(const arithmetic_backend<Arithmetic>& val) {\n                    return val.data() == 0 ? 0 : 1;\n                }\n\n                template<class T>\n                inline BOOST_MP_CXX14_CONSTEXPR typename boost::enable_if<boost::is_unsigned<T>, T>::type abs(T v) {\n                    return v;\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_abs(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& o) {\n                    using nil::crypto3::multiprecision::backends::abs;\n                    using std::abs;\n                    result.data() = abs(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_fabs(arithmetic_backend<Arithmetic>& result,\n                                                               const arithmetic_backend<Arithmetic>& o) {\n                    result.data() = std::abs(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_floor(arithmetic_backend<Arithmetic>& result,\n                                                                const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = floor(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_ceil(arithmetic_backend<Arithmetic>& result,\n                                                               const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = ceil(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_sqrt(arithmetic_backend<Arithmetic>& result,\n                                                               const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = sqrt(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR int eval_fpclassify(const arithmetic_backend<Arithmetic>& o) {\n                    return (boost::math::fpclassify)(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_trunc(arithmetic_backend<Arithmetic>& result,\n                                                                const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = trunc(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_round(arithmetic_backend<Arithmetic>& result,\n                                                                const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = round(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_frexp(arithmetic_backend<Arithmetic>& result,\n                                                                const arithmetic_backend<Arithmetic>& a, int* v) {\n                    BOOST_MATH_STD_USING\n                    result.data() = frexp(a.data(), v);\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_ldexp(arithmetic_backend<Arithmetic>& result,\n                                                                const arithmetic_backend<Arithmetic>& a, int v) {\n                    BOOST_MATH_STD_USING\n                    result.data() = ldexp(a.data(), v);\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_exp(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = exp(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_log(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = log(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_log10(arithmetic_backend<Arithmetic>& result,\n                                                                const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = log10(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_sin(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = sin(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_cos(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = cos(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_tan(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = tan(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_acos(arithmetic_backend<Arithmetic>& result,\n                                                               const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = acos(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_asin(arithmetic_backend<Arithmetic>& result,\n                                                               const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = asin(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_atan(arithmetic_backend<Arithmetic>& result,\n                                                               const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = atan(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_sinh(arithmetic_backend<Arithmetic>& result,\n                                                               const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = sinh(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_cosh(arithmetic_backend<Arithmetic>& result,\n                                                               const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = cosh(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_tanh(arithmetic_backend<Arithmetic>& result,\n                                                               const arithmetic_backend<Arithmetic>& o) {\n                    BOOST_MATH_STD_USING\n                    result.data() = tanh(o.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_fmod(arithmetic_backend<Arithmetic>& result,\n                                                               const arithmetic_backend<Arithmetic>& a,\n                                                               const arithmetic_backend<Arithmetic>& b) {\n                    BOOST_MATH_STD_USING\n                    result.data() = fmod(a.data(), b.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_pow(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& a,\n                                                              const arithmetic_backend<Arithmetic>& b) {\n                    BOOST_MATH_STD_USING\n                    result.data() = pow(a.data(), b.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_atan2(arithmetic_backend<Arithmetic>& result,\n                                                                const arithmetic_backend<Arithmetic>& a,\n                                                                const arithmetic_backend<Arithmetic>& b) {\n                    BOOST_MATH_STD_USING\n                    result.data() = atan2(a.data(), b.data());\n                }\n\n                template<class Arithmetic, class I>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_left_shift(arithmetic_backend<Arithmetic>& result, I val) {\n                    result.data() <<= val;\n                }\n\n                template<class Arithmetic, class I>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_right_shift(arithmetic_backend<Arithmetic>& result, I val) {\n                    result.data() >>= val;\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_modulus(arithmetic_backend<Arithmetic>& result,\n                                                                  const arithmetic_backend<Arithmetic>& a) {\n                    result.data() %= a.data();\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_bitwise_and(arithmetic_backend<Arithmetic>& result,\n                                                                      const arithmetic_backend<Arithmetic>& a) {\n                    result.data() &= a.data();\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_bitwise_or(arithmetic_backend<Arithmetic>& result,\n                                                                     const arithmetic_backend<Arithmetic>& a) {\n                    result.data() |= a.data();\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_bitwise_xor(arithmetic_backend<Arithmetic>& result,\n                                                                      const arithmetic_backend<Arithmetic>& a) {\n                    result.data() ^= a.data();\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_complement(arithmetic_backend<Arithmetic>& result,\n                                                                     const arithmetic_backend<Arithmetic>& a) {\n                    result.data() = ~a.data();\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_gcd(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& a,\n                                                              const arithmetic_backend<Arithmetic>& b) {\n                    result.data() = boost::integer::gcd(a.data(), b.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR void eval_lcm(arithmetic_backend<Arithmetic>& result,\n                                                              const arithmetic_backend<Arithmetic>& a,\n                                                              const arithmetic_backend<Arithmetic>& b) {\n                    result.data() = boost::integer::lcm(a.data(), b.data());\n                }\n\n                template<class Arithmetic>\n                inline BOOST_MP_CXX14_CONSTEXPR std::size_t hash_value(const arithmetic_backend<Arithmetic>& a) {\n                    boost::hash<Arithmetic> hasher;\n                    return hasher(a.data());\n                }\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n            }    // namespace backends\n\n            using nil::crypto3::multiprecision::backends::arithmetic_backend;\n\n            template<class Arithmetic>\n            struct number_category<arithmetic_backend<Arithmetic>>\n                : public boost::mpl::int_<boost::is_integral<Arithmetic>::value ? number_kind_integer :\n                                                                                  number_kind_floating_point> { };\n\n            namespace detail {\n\n                template<class Backend>\n                struct double_precision_type;\n\n                template<class Arithmetic, nil::crypto3::multiprecision::expression_template_option ET>\n                struct double_precision_type<number<arithmetic_backend<Arithmetic>, ET>> {\n                    typedef number<arithmetic_backend<typename double_precision_type<Arithmetic>::type>, ET> type;\n                };\n                template<>\n                struct double_precision_type<arithmetic_backend<boost::int32_t>> {\n                    typedef arithmetic_backend<boost::int64_t> type;\n                };\n\n            }    // namespace detail\n\n        }    // namespace multiprecision\n    }        // namespace crypto3\n}    // namespace nil\n#if !(defined(__SGI_STL_PORT) || defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS))\n     //\n// We shouldn't need these to get code to compile, however for the sake of\n// \"level playing field\" performance comparisons they avoid the very slow\n// lexical_cast's that would otherwise take place.  Definition has to be guarded\n// by the inverse of pp-logic in real_concept.hpp which defines these as a workaround\n// for STLPort plus some other old/broken standartd libraries.\n//\nnamespace boost {\n    namespace math {\n        namespace tools {\n\n            template<>\n            inline unsigned int real_cast<unsigned int, concepts::real_concept>(concepts::real_concept r) {\n                return static_cast<unsigned int>(r.value());\n            }\n\n            template<>\n            inline int real_cast<int, concepts::real_concept>(concepts::real_concept r) {\n                return static_cast<int>(r.value());\n            }\n\n            template<>\n            inline long real_cast<long, concepts::real_concept>(concepts::real_concept r) {\n                return static_cast<long>(r.value());\n            }\n\n            // Converts from T to narrower floating-point types, float, double & long double.\n\n            template<>\n            inline float real_cast<float, concepts::real_concept>(concepts::real_concept r) {\n                return static_cast<float>(r.value());\n            }\n            template<>\n            inline double real_cast<double, concepts::real_concept>(concepts::real_concept r) {\n                return static_cast<double>(r.value());\n            }\n            template<>\n            inline long double real_cast<long double, concepts::real_concept>(concepts::real_concept r) {\n                return r.value();\n            }\n\n        }    // namespace tools\n    }        // namespace math\n}    // namespace boost\n#endif\n\nnamespace std {\n\n    template<class Arithmetic, nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>\n    class numeric_limits<nil::crypto3::multiprecision::number<\n        nil::crypto3::multiprecision::arithmetic_backend<Arithmetic>, ExpressionTemplates>>\n        : public std::numeric_limits<Arithmetic> {\n        typedef std::numeric_limits<Arithmetic> base_type;\n        typedef nil::crypto3::multiprecision::number<nil::crypto3::multiprecision::arithmetic_backend<Arithmetic>,\n                                                     ExpressionTemplates>\n            number_type;\n\n    public:\n        BOOST_STATIC_CONSTEXPR number_type(min)() BOOST_NOEXCEPT {\n            return (base_type::min)();\n        }\n        BOOST_STATIC_CONSTEXPR number_type(max)() BOOST_NOEXCEPT {\n            return (base_type::max)();\n        }\n        BOOST_STATIC_CONSTEXPR number_type lowest() BOOST_NOEXCEPT {\n            return -(max)();\n        }\n        BOOST_STATIC_CONSTEXPR number_type epsilon() BOOST_NOEXCEPT {\n            return base_type::epsilon();\n        }\n        BOOST_STATIC_CONSTEXPR number_type round_error() BOOST_NOEXCEPT {\n            return epsilon() / 2;\n        }\n        BOOST_STATIC_CONSTEXPR number_type infinity() BOOST_NOEXCEPT {\n            return base_type::infinity();\n        }\n        BOOST_STATIC_CONSTEXPR number_type quiet_NaN() BOOST_NOEXCEPT {\n            return base_type::quiet_NaN();\n        }\n        BOOST_STATIC_CONSTEXPR number_type signaling_NaN() BOOST_NOEXCEPT {\n            return base_type::signaling_NaN();\n        }\n        BOOST_STATIC_CONSTEXPR number_type denorm_min() BOOST_NOEXCEPT {\n            return base_type::denorm_min();\n        }\n    };\n\n    template<>\n    class numeric_limits<boost::math::concepts::real_concept> : public std::numeric_limits<long double> {\n        typedef std::numeric_limits<long double> base_type;\n        typedef boost::math::concepts::real_concept number_type;\n\n    public:\n        static const number_type(min)() BOOST_NOEXCEPT {\n            return (base_type::min)();\n        }\n        static const number_type(max)() BOOST_NOEXCEPT {\n            return (base_type::max)();\n        }\n        static const number_type lowest() BOOST_NOEXCEPT {\n            return -(max)();\n        }\n        static const number_type epsilon() BOOST_NOEXCEPT {\n            return base_type::epsilon();\n        }\n        static const number_type round_error() BOOST_NOEXCEPT {\n            return epsilon() / 2;\n        }\n        static const number_type infinity() BOOST_NOEXCEPT {\n            return base_type::infinity();\n        }\n        static const number_type quiet_NaN() BOOST_NOEXCEPT {\n            return base_type::quiet_NaN();\n        }\n        static const number_type signaling_NaN() BOOST_NOEXCEPT {\n            return base_type::signaling_NaN();\n        }\n        static const number_type denorm_min() BOOST_NOEXCEPT {\n            return base_type::denorm_min();\n        }\n    };\n\n}    // namespace std\n\n#include <nil/crypto3/multiprecision/detail/integer_ops.hpp>\n\n#endif\n", "meta": {"hexsha": "8d2966f5cc77d663814766b4297ff5109042b2f9", "size": 37638, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "snark-logic/libs-source/multiprecision/performance/arithmetic_backend.hpp", "max_stars_repo_name": "idealatom/podlodkin-freeton-year-control", "max_stars_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_stars_repo_licenses": ["MIT"], "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/libs-source/multiprecision/performance/arithmetic_backend.hpp", "max_issues_repo_name": "idealatom/podlodkin-freeton-year-control", "max_issues_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_issues_repo_licenses": ["MIT"], "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/libs-source/multiprecision/performance/arithmetic_backend.hpp", "max_forks_repo_name": "idealatom/podlodkin-freeton-year-control", "max_forks_repo_head_hexsha": "6aa96e855fe065c9a75c76da976a87fe2d1668e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-15T20:27:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T20:27:27.000Z", "avg_line_length": 51.5589041096, "max_line_length": 120, "alphanum_fraction": 0.5137626866, "num_tokens": 6576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.22773539795792522}}
{"text": "/*\n  Tencent is pleased to support the open source community by making\n  Plato available.\n  Copyright (C) 2019 THL A29 Limited, a Tencent company.\n  All rights reserved.\n\n  Licensed under the BSD 3-Clause License (the \"License\"); you may\n  not use this file except in compliance with the License. You may\n  obtain a copy of the License at\n\n  https://opensource.org/licenses/BSD-3-Clause\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\n  implied. See the License for the specific language governing\n  permissions and limitations under the License.\n\n  See the AUTHORS file for names of contributors.\n*/\n\n#ifndef __PLATO_ALGO_FAST_UNFOLDING_LOUVAIN_HPP__\n#define __PLATO_ALGO_FAST_UNFOLDING_LOUVAIN_HPP__\n\n#include <cstdint>\n#include <cstdlib>\n#include <unordered_map>\n#include <algorithm>\n#include <utility>\n#include <vector>\n#include <cmath>\n#include <unordered_set>\n#include <boost/format.hpp>\n#include <boost/lockfree/queue.hpp>\n\n#include \"glog/logging.h\"\n\n#include \"plato/util/perf.hpp\"\n#include \"plato/util/atomic.hpp\"\n#include \"plato/graph/graph.hpp\"\n#include \"plato/engine/dualmode.hpp\"\n\nnamespace plato { namespace algo {\nstruct louvain_opts_t {\n  int alpha_ = -1;\n  bool part_by_in_ = false;\n  int outer_iteration_ = 3;\n  int inner_iteration_ = 2;\n};\n\ntemplate<typename GRAPH>\nclass louvain_epoch_t {\npublic:\n  using partition_t = typename GRAPH::partition_t;\n  using edge_value_t = typename GRAPH::edata_t;\n  using louvain_value_t = plato::dense_state_t<edge_value_t, partition_t>;\n  using adj_unit_list_spec_t = typename GRAPH::adj_unit_list_spec_t;\n  struct epoch_msg_type_t {\n    vid_t v_i;\n    vid_t from;\n    vid_t to;\n    edge_value_t ki;\n  };\n\n  struct sync_val_msg_type_t{\n    vid_t v_i;\n    edge_value_t val;\n  };\n\n\npublic:\n  /**\n   * @brief\n   * @param graph\n   * @param graph_info\n   * @param m\n   * @param opts\n   */\n  explicit louvain_epoch_t(\n    std::shared_ptr<GRAPH> graph, const graph_info_t& graph_info, double m,\n    const louvain_opts_t& opts = louvain_opts_t());\n  /**\n   * @brief\n   */\n  ~louvain_epoch_t();\n\n  /**\n   * @brief\n   */\n  void compute();\n\n  /**\n   * @brief getter\n   * @return\n   */\n  std::shared_ptr<GRAPH> graph() { return graph_; };\n  /**\n   * @brief getter\n   * @return\n   */\n  std::vector<vid_t>& labels() { return labels_; };\n\nprivate:\n  std::shared_ptr<GRAPH> graph_;\n  graph_info_t graph_info_;\n  louvain_value_t ki_;\n  std::vector<vid_t> labels_;\n  std::vector<edge_value_t> sigma_tot_;\n  bitmap_t<> local_bit_;\n  double m_;\n  louvain_opts_t opts_;\n};\n\ntemplate <typename GRAPH>\nlouvain_epoch_t<GRAPH>::louvain_epoch_t(\n  std::shared_ptr<GRAPH> graph,\n  const graph_info_t& graph_info, double m, const louvain_opts_t& opts) :\n  graph_(graph), graph_info_(graph_info), ki_(graph_info.max_v_i_, graph->partitioner()),\n  labels_(graph_info.max_v_i_ + 1), sigma_tot_(graph_info.max_v_i_ + 1, 0),\n  local_bit_(graph_info.max_v_i_ + 1), m_(2 * m), opts_(opts) {\n\n  auto& cluster_info = plato::cluster_info_t::get_instance();\n  plato::stop_watch_t watch;\n\n  {// init labels\n    watch.mark(\"t0\");\n#pragma omp parallel for num_threads(cluster_info.threads_)\n    for (vid_t v_i = 0; v_i <= graph_info.max_v_i_; ++v_i) {\n      labels_[v_i] = v_i;\n    }\n    LOG(INFO) << \"epoch init labels: \" << watch.show(\"t0\") / 1000.0;\n  }\n\n  {//calc ki_ and sync sigma_tot_\n    bitmap_t<> active_all(graph_info.max_v_i_ + 1);\n    active_all.fill();\n    auto active_view_all = plato::create_active_v_view(graph->partitioner()->self_v_view(), active_all);\n    watch.mark(\"t0\");\n    edge_value_t max_ki = 0;\n    using push_context_t = plato::template mepa_bc_context_t<sync_val_msg_type_t>;\n    plato::broadcast_message<sync_val_msg_type_t, vid_t>(\n      active_view_all,\n      /**\n       * @brief\n       * @param context\n       * @param v_i\n       */\n      [&](const push_context_t& context, vid_t v_i) {\n        edge_value_t local_sum = 0;\n        auto neighbours = graph->neighbours(v_i);\n        for (auto it = neighbours.begin_; neighbours.end_ != it; ++it) {\n          local_sum += it->edata_;\n        }\n        if (neighbours.begin_ != neighbours.end_) {\n          ki_[v_i] = local_sum;\n          local_bit_.set_bit(v_i);\n          plato::write_max(&max_ki, local_sum);\n          context.send(sync_val_msg_type_t{ v_i, local_sum});\n        }\n      },\n      /**\n       * @brief\n       * @param p_i\n       * @param msg\n       * @return\n       */\n      [&](int p_i, sync_val_msg_type_t& msg) {\n        sigma_tot_[msg.v_i] = msg.val;\n        return 0;\n      }\n    );\n    LOG(INFO) << \"epoch sync sigma_tot: \" << watch.show(\"t0\") / 1000.0;\n    MPI_Allreduce(MPI_IN_PLACE, &max_ki, 1, get_mpi_data_type<edge_value_t>(), MPI_MAX, MPI_COMM_WORLD);\n    LOG(INFO) << \"max ki: \" << max_ki;\n  }\n}\n\ntemplate <typename GRAPH>\nlouvain_epoch_t<GRAPH>::~louvain_epoch_t() {\n}\n\ntemplate <typename GRAPH>\nvoid louvain_epoch_t<GRAPH>::compute() {\n  auto& cluster_info = plato::cluster_info_t::get_instance();\n  auto try_change = [&](vid_t v_i, vid_t from, vid_t to, edge_value_t ki_in_from, edge_value_t ki_in_to) {\n    double x = (double)ki_[v_i] + (double)sigma_tot_[to] - (double)sigma_tot_[from];\n    return (double)ki_in_to - (double)ki_in_from - 2.0 * (double)ki_[v_i] * x / m_;\n  };\n  auto do_change = [&](epoch_msg_type_t& msg) {\n    labels_[msg.v_i] = msg.to;\n    plato::write_add(&sigma_tot_[msg.from], -msg.ki);\n    plato::write_add(&sigma_tot_[msg.to], msg.ki);\n  };\n\n  auto active_view = plato::create_active_v_view(graph_->partitioner()->self_v_view(), local_bit_);\n  plato::stop_watch_t watch;\n  using push_context_t = plato::template mepa_bc_context_t<epoch_msg_type_t>;\n  for (int try_time = 0; try_time < opts_.inner_iteration_; ++try_time){\n    watch.mark(\"t0\");\n    auto exec_once = [&](std::function<bool(vid_t, vid_t)> condition) {\n      plato::broadcast_message<epoch_msg_type_t, vid_t>(\n        active_view,\n        /**\n         * @brief\n         * @param context\n         * @param v_i\n         */\n        [&](const push_context_t& context, plato::vid_t v_i) {\n          vid_t target = (vid_t)-1;\n          vid_t from = labels_[v_i];\n          edge_value_t ki_in_from = 0;\n          std::unordered_map<vid_t, edge_value_t> ki_in_map;\n          auto neighbours = graph_->neighbours(v_i);\n          edge_value_t self_cycle = 0;\n          for (auto it = neighbours.begin_; neighbours.end_ != it; ++it) {\n            vid_t to = labels_[it->neighbour_];\n            if (condition(from, to)) {\n              ki_in_map[to] += it->edata_;\n            } else if (to == from) {\n              ki_in_from += it->edata_;\n            }\n\n            if (it->neighbour_ == v_i) {\n              self_cycle = it->edata_;\n            }\n          }\n\n          double best_delta = 0;\n          for (auto& it: ki_in_map) {\n            double delta = try_change(v_i, from, it.first, ki_in_from, it.second + self_cycle);\n            if (delta > best_delta) {\n              target = it.first;\n              best_delta = delta;\n            }\n          }\n\n          if (target != (vid_t)-1) {\n            epoch_msg_type_t msg = epoch_msg_type_t{ v_i, from, target, ki_[v_i] };\n            context.send(msg);\n            do_change(msg);\n          }\n        },\n        /**\n         * @brief\n         * @param p_i\n         * @param msg\n         * @return\n         */\n        [&](int p_i, epoch_msg_type_t& msg) {\n          if (p_i != cluster_info.partition_id_) {\n            do_change(msg);\n          }\n          return 0;\n        }\n      );\n    };\n\n    exec_once([&](vid_t from, vid_t to){\n      if (from < to) return true;\n      return false;\n    });\n    exec_once([&](vid_t from, vid_t to){\n      if (from > to) return true;\n      return false;\n    });\n    LOG(INFO) << \"try_time: \"  << try_time << \" cost: \" << watch.show(\"t0\") / 1000.0;\n  }\n}\n\ntemplate<typename GRAPH>\nclass louvain_fast_unfolding_t {\npublic:\n  using partition_t = typename GRAPH::partition_t;\n  using edge_value_t = typename GRAPH::edata_t;\n  using adj_unit_list_spec_t = plato::adj_unit_list_t<edge_value_t>;\n  using louvain_value_t = plato::dense_state_t<vid_t, partition_t>;\n\n  struct edge_sync_msg_type_t {\n    vid_t src;\n    vid_t dst;\n    edge_value_t data;\n  };\n\n  struct degree_sync_msg_type_t {\n    vid_t src;\n    vid_t degree;\n  };\n\npublic:\n  /**\n   * @brief\n   * @param graph\n   * @param graph_info\n   * @param opts\n   */\n  explicit louvain_fast_unfolding_t(\n    std::shared_ptr<GRAPH> graph, const graph_info_t& graph_info,\n    const louvain_opts_t& opts = louvain_opts_t());\n\n  /**\n   * @brief destructor\n   */\n  ~louvain_fast_unfolding_t();\n\n  /**\n   * @brief compute\n   */\n  void compute();\n\n  /**\n   * @brief save to storage.\n   * @tparam STREAM\n   * @param streams\n   */\n  template <typename STREAM>\n  void save(std::vector<STREAM*>& streams);\n\nprivate:\n  /**\n   * @brief\n   * @param graph\n   * @param labels\n   * @return\n   */\n  std::shared_ptr<GRAPH> rebuild(std::shared_ptr<GRAPH> graph, std::vector<vid_t>& labels);\n  /**\n   * @brief\n   * @param labels\n   */\n  void update_local_label(std::vector<vid_t>& labels);\nprivate:\n  std::shared_ptr<GRAPH> graph_;\n  graph_info_t graph_info_;\n  louvain_value_t local_label_;\n  louvain_value_t local_comm_size_;\n  louvain_opts_t opts_;\n};\n\ntemplate<typename GRAPH>\nlouvain_fast_unfolding_t<GRAPH>::louvain_fast_unfolding_t(\n  std::shared_ptr<GRAPH> graph, const graph_info_t& graph_info,\n  const louvain_opts_t& opts)\n  : graph_(graph), graph_info_(graph_info),\n    local_label_(graph_info.max_v_i_, graph->partitioner()),\n    local_comm_size_(graph_info.max_v_i_, graph->partitioner()), opts_(opts) {\n}\n\ntemplate<typename GRAPH>\nlouvain_fast_unfolding_t<GRAPH>::~louvain_fast_unfolding_t() {\n}\n\ntemplate<typename GRAPH>\nvoid louvain_fast_unfolding_t<GRAPH>::compute() {\n  //first calc m and init label\n  plato::stop_watch_t watch;\n  watch.mark(\"t0\");\n  double m = local_label_.template foreach<double> (\n    /**\n     * @brief\n     * @param v_i\n     * @param pval\n     * @return\n     */\n    [&](vid_t v_i, vid_t* pval) {\n      *pval = v_i;\n      double local_sum = 0;\n      auto neighbours = graph_->neighbours(v_i);\n      for (auto it = neighbours.begin_; neighbours.end_ != it; ++it) {\n        local_sum += it->edata_;\n      }\n      return local_sum;\n    }\n  );\n  m /= 2; //undirected\n  LOG(INFO) << \"calc m: \" << m << \" cost: \" << watch.show(\"t0\") / 1000.0;\n\n  //epoch\n  louvain_epoch_t<GRAPH>* cur = new louvain_epoch_t<GRAPH>(graph_, graph_info_, m, opts_);\n  for (int epoch = 0; epoch < opts_.outer_iteration_; epoch++) {\n    LOG(INFO) << \"epoch \" << epoch << \" begin!\";\n    watch.mark(\"compute\");\n    cur->compute();\n    LOG(INFO) << \"compute cost: \" << watch.show(\"compute\") / 1000.0;\n    update_local_label(cur->labels());\n    if (epoch == opts_.outer_iteration_ - 1) {\n      delete cur;\n      break;\n    }\n    //rebuild from current graph\n    watch.mark(\"rebuild\");\n    graph_info_t graph_info_next(graph_info_);\n    graph_info_next.is_directed_ = true;\n    auto graph_next = rebuild(cur->graph(), cur->labels());\n    louvain_epoch_t<GRAPH>* nxt = new louvain_epoch_t<GRAPH>(graph_next, graph_info_next, m, opts_);\n    LOG(INFO) << \"rebuild cost: \" << watch.show(\"rebuild\") / 1000.0;\n    delete cur;\n    cur = nxt;\n  }\n}\n\ntemplate<typename GRAPH>\nstd::shared_ptr<GRAPH> louvain_fast_unfolding_t<GRAPH>::rebuild(std::shared_ptr<GRAPH> graph, std::vector<vid_t>& labels) {\n  plato::stop_watch_t watch;\n  watch.mark(\"t0\");\n  eid_t total_edge = local_label_.template foreach<eid_t> (\n    [&](vid_t v_i, vid_t* pval) {\n      auto neighbours = graph->neighbours(v_i);\n      return (eid_t)(neighbours.end_ - neighbours.begin_);\n    }\n  );\n  LOG(INFO) << \"rebuild before total edge: \" << total_edge << \" cost: \" << watch.show(\"t0\") / 1000.0;\n\n  watch.mark(\"t0\");\n  auto& cluster_info = plato::cluster_info_t::get_instance();\n  vid_t v_begin = graph->partitioner()->offset_[cluster_info.partition_id_];\n  vid_t v_end = graph->partitioner()->offset_[cluster_info.partition_id_ + 1];\n  std::vector<eid_t> edge_idx(v_end - v_begin + 1, 0);\n  std::vector<eid_t> tmp_idx(v_end - v_begin + 1, 0);\n\n  bitmap_t<> active_all(graph_info_.max_v_i_ + 1);\n  active_all.fill();\n  auto active_view_all = plato::create_active_v_view(graph->partitioner()->self_v_view(), active_all);\n\n  {\n    //first, calc degree\n    using push_context_t = plato::template mepa_sd_context_t<degree_sync_msg_type_t>;\n    plato::spread_message<degree_sync_msg_type_t, vid_t>(\n      active_view_all,\n      /**\n       * @brief\n       * @param context\n       * @param v_i\n       */\n      [&](const push_context_t& context, vid_t v_i) {\n        auto neighbours = graph->neighbours(v_i);\n        if (neighbours.begin_ == neighbours.end_) return;\n        vid_t src = labels[v_i];\n        auto send_to = graph->partitioner()->get_partition_id(src);\n        context.send(send_to, degree_sync_msg_type_t { src, (vid_t)(neighbours.end_ - neighbours.begin_) } );\n      },\n      /**\n       * @brief\n       * @param msg\n       * @return\n       */\n      [&](degree_sync_msg_type_t& msg) {\n        vid_t pos = msg.src - v_begin + 1;\n        plato::write_add(&edge_idx[pos], (eid_t)msg.degree);\n        return 0;\n      }\n    );\n\n    for (int i = 1; i < (int)edge_idx.size(); ++i) {\n      edge_idx[i] = edge_idx[i - 1] + edge_idx[i];\n      tmp_idx[i] = edge_idx[i];\n    }\n\n    LOG(INFO) << \"rebuild calc degree cost: \" << watch.show(\"t0\") / 1000.0;\n  }\n  eid_t total_local_edge = edge_idx[edge_idx.size() - 1];\n  std::vector<std::pair<vid_t, edge_value_t> > edges(total_local_edge);\n  LOG(INFO) << \"rebuild local edge: \" << edges.size();\n  watch.mark(\"t0\");\n  {\n    //second, transfer edge\n    using push_context_t = plato::template mepa_sd_context_t<edge_sync_msg_type_t>;\n    plato::spread_message<edge_sync_msg_type_t, vid_t>(\n      active_view_all,\n      /**\n       * @brief\n       * @param context\n       * @param v_i\n       */\n      [&](const push_context_t& context, vid_t v_i) {\n        auto neighbours = graph->neighbours(v_i);\n        if (neighbours.begin_ == neighbours.end_) return;\n        vid_t src = labels[v_i];\n        auto send_to = graph->partitioner()->get_partition_id(src);\n        for (auto it = neighbours.begin_; neighbours.end_ != it; ++it) {\n          vid_t dst = labels[it->neighbour_];\n          context.send(send_to, edge_sync_msg_type_t{ src, dst, it->edata_ });\n        }\n      },\n      /**\n       * @brief\n       * @param msg\n       * @return\n       */\n      [&](edge_sync_msg_type_t& msg) {\n        vid_t pos = msg.src - v_begin;\n        vid_t idx = __sync_fetch_and_add(&tmp_idx[pos], (eid_t)1);\n        edges[idx].first = msg.dst;\n        edges[idx].second = msg.data;\n        return 0;\n      }\n    );\n    LOG(INFO) << \"rebuild transfer edge cost: \" << watch.show(\"t0\") / 1000.0;\n  }\n\n  watch.mark(\"t0\");\n  edge_cache_t<edge_value_t> edge_cache;\n  {\n    //third, sort and aggregate\n#pragma omp parallel for num_threads(cluster_info.threads_)\n    for (vid_t v_i = v_begin; v_i < v_end; ++v_i) {\n      vid_t pos = v_i - v_begin;\n      eid_t e_start = edge_idx[pos];\n      eid_t e_end = edge_idx[pos + 1];\n      if (e_start == e_end) continue;\n      std::sort(edges.begin() + e_start, edges.begin() + e_end);\n      vid_t pre = (vid_t)-1;\n      edge_value_t local_sum = 0;\n      for (eid_t e = e_start; e < e_end; ++e) {\n        if (pre != edges[e].first) {\n          if (pre != (vid_t)-1) {\n            edge_cache.push_back(edge_unit_t<edge_value_t> { v_i, pre, local_sum });\n          }\n          pre = edges[e].first;\n          local_sum = 0;\n        }\n        local_sum += edges[e].second;\n      }\n      if (pre != (vid_t)-1) {\n        edge_cache.push_back(edge_unit_t<edge_value_t> { v_i, pre, local_sum });\n      }\n    }\n\n    eid_t edge_num_new = edge_cache.size();\n    MPI_Allreduce(MPI_IN_PLACE, &edge_num_new, 1, get_mpi_data_type<eid_t>(), MPI_SUM, MPI_COMM_WORLD);\n    LOG(INFO) << \"rebuild new edge num: \" << edge_num_new;\n    LOG(INFO) << \"rebuild aggregate edge cost: \" << watch.show(\"t0\") / 1000.0;\n  }\n\n  watch.mark(\"t0\");\n  graph_info_t graph_info_next(graph_info_);\n  graph_info_next.is_directed_ = true;\n  std::shared_ptr<GRAPH> pgraph(new GRAPH(graph->partitioner()));\n  pgraph->load_from_cache(graph_info_next, edge_cache);\n  LOG(INFO) << \"rebuild load cache cost: \" << watch.show(\"t0\") / 1000.0;\n\n  return pgraph;\n}\n\ntemplate<typename GRAPH>\nvoid louvain_fast_unfolding_t<GRAPH>::update_local_label(std::vector<vid_t>& labels) {\n  local_label_.template foreach<int> (\n    /**\n     * @brief\n     * @param v_i\n     * @param pval\n     * @return\n     */\n    [&] (vid_t v_i, vid_t* pval) {\n      if (labels[*pval] != *pval) {\n        *pval = labels[*pval];\n      }\n      return 0;\n    }\n  );\n}\n\ntemplate<typename GRAPH>\ntemplate<typename STREAM>\nvoid louvain_fast_unfolding_t<GRAPH>::save(std::vector<STREAM*>& ss) {\n  struct louvain_msg_type_t {\n    vid_t src;\n    vid_t label;\n  };\n  boost::lockfree::queue<louvain_msg_type_t> que(1024);\n  LOG_IF(FATAL, !que.is_lock_free())\n  << \"boost::lockfree::queue is not lock free\\n\";\n\n  // start a thread to pop and edge and write to output\n  std::atomic<bool> done(false);\n  std::thread pop_write([&done, &ss, &que](void) {\n#pragma omp parallel num_threads(ss.size())\n    {\n      int tid = omp_get_thread_num();\n      louvain_msg_type_t vb;\n      while (!done) {\n        if (que.pop(vb)) {\n          *ss[tid] << vb.src << \",\" << vb.label << \"\\n\";\n        }\n      }\n\n      while (que.pop(vb)) {\n        *ss[tid] << vb.src << \",\" << vb.label << \"\\n\";\n      }\n    }\n  });\n\n  // traverse\n  local_label_.template foreach<int> (\n    /**\n     * @brief\n     * @param v_i\n     * @param pval\n     * @return\n     */\n    [&] (vid_t v_i, vid_t* pval) {\n      while (!que.push(louvain_msg_type_t {v_i, *pval} )) {\n      }\n      return 0;\n    }\n  );\n\n  done = true;\n  pop_write.join();\n}\n\n}  // namespace plato\n}  // namespace algo\n#endif\n", "meta": {"hexsha": "2d6c2a439b1cf8ac5896adfd1748c8b2cef2e9c3", "size": 17965, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "plato/algo/fast_unfolding/louvain.hpp", "max_stars_repo_name": "zhaofeng-shu33/plato", "max_stars_repo_head_hexsha": "36012f8951221550576fd270a0e355c7e3b44b72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T05:30:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T05:30:03.000Z", "max_issues_repo_path": "plato/algo/fast_unfolding/louvain.hpp", "max_issues_repo_name": "zhaofeng-shu33/plato", "max_issues_repo_head_hexsha": "36012f8951221550576fd270a0e355c7e3b44b72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "plato/algo/fast_unfolding/louvain.hpp", "max_forks_repo_name": "zhaofeng-shu33/plato", "max_forks_repo_head_hexsha": "36012f8951221550576fd270a0e355c7e3b44b72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-11T02:15:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-11T02:15:42.000Z", "avg_line_length": 29.2589576547, "max_line_length": 123, "alphanum_fraction": 0.6234344559, "num_tokens": 5111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22745864304150112}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017, 2018.\r\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 5.0.0\r\n\r\n// Original copyright notice:\r\n\r\n// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_POLY_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_POLY_HPP\r\n\r\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\r\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_mlfn.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_msfn.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace srs { namespace par4\r\n{\r\n    struct poly {}; // Polyconic (American)\r\n\r\n}} //namespace srs::par4\r\n\r\nnamespace projections\r\n{\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail { namespace poly\r\n    {\r\n\r\n            static const double tolerance = 1e-10;\r\n            static const double conv_tolerance = 1e-10;\r\n            static const int n_iter = 10;\r\n            static const int i_iter = 20;\r\n            static const double i_tolerance = 1.e-12;\r\n\r\n            template <typename T>\r\n            struct par_poly\r\n            {\r\n                T ml0;\r\n                detail::en<T> en;\r\n            };\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_poly_ellipsoid\r\n                : public base_t_fi<base_poly_ellipsoid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_poly<T> m_proj_parm;\r\n\r\n                inline base_poly_ellipsoid(const Parameters& par)\r\n                    : base_t_fi<base_poly_ellipsoid<T, Parameters>, T, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(e_forward)  ellipsoid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    T  ms, sp, cp;\r\n\r\n                    if (fabs(lp_lat) <= tolerance) {\r\n                        xy_x = lp_lon;\r\n                        xy_y = -this->m_proj_parm.ml0;\r\n                    } else {\r\n                        sp = sin(lp_lat);\r\n                        ms = fabs(cp = cos(lp_lat)) > tolerance ? pj_msfn(sp, cp, this->m_par.es) / sp : 0.;\r\n                        xy_x = ms * sin(lp_lon *= sp);\r\n                        xy_y = (pj_mlfn(lp_lat, sp, cp, this->m_proj_parm.en) - this->m_proj_parm.ml0) + ms * (1. - cos(lp_lon));\r\n                    }\r\n                }\r\n\r\n                // INVERSE(e_inverse)  ellipsoid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    xy_y += this->m_proj_parm.ml0;\r\n                    if (fabs(xy_y) <= tolerance) {\r\n                        lp_lon = xy_x;\r\n                        lp_lat = 0.;\r\n                    } else {\r\n                        T r, c, sp, cp, s2ph, ml, mlb, mlp, dPhi;\r\n                        int i;\r\n\r\n                        r = xy_y * xy_y + xy_x * xy_x;\r\n                        for (lp_lat = xy_y, i = i_iter; i ; --i) {\r\n                            sp = sin(lp_lat);\r\n                            s2ph = sp * ( cp = cos(lp_lat));\r\n                            if (fabs(cp) < i_tolerance) {\r\n                                BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\r\n                            }\r\n                            c = sp * (mlp = sqrt(1. - this->m_par.es * sp * sp)) / cp;\r\n                            ml = pj_mlfn(lp_lat, sp, cp, this->m_proj_parm.en);\r\n                            mlb = ml * ml + r;\r\n                            mlp = this->m_par.one_es / (mlp * mlp * mlp);\r\n                            lp_lat += ( dPhi =\r\n                                ( ml + ml + c * mlb - 2. * xy_y * (c * ml + 1.) ) / (\r\n                                this->m_par.es * s2ph * (mlb - 2. * xy_y * ml) / c +\r\n                                2.* (xy_y - ml) * (c * mlp - 1. / s2ph) - mlp - mlp ));\r\n                            if (fabs(dPhi) <= i_tolerance)\r\n                                break;\r\n                        }\r\n                        if (!i) {\r\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\r\n                        }\r\n                        c = sin(lp_lat);\r\n                        lp_lon = asin(xy_x * tan(lp_lat) * sqrt(1. - this->m_par.es * c * c)) / sin(lp_lat);\r\n                    }\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"poly_ellipsoid\";\r\n                }\r\n\r\n            };\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_poly_spheroid\r\n                : public base_t_fi<base_poly_spheroid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_poly<T> m_proj_parm;\r\n\r\n                inline base_poly_spheroid(const Parameters& par)\r\n                    : base_t_fi<base_poly_spheroid<T, Parameters>, T, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(s_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(T& lp_lon, T& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    T  cot, E;\r\n\r\n                    if (fabs(lp_lat) <= tolerance) {\r\n                        xy_x = lp_lon;\r\n                        xy_y = this->m_proj_parm.ml0;\r\n                    } else {\r\n                        cot = 1. / tan(lp_lat);\r\n                        xy_x = sin(E = lp_lon * sin(lp_lat)) * cot;\r\n                        xy_y = lp_lat - this->m_par.phi0 + cot * (1. - cos(E));\r\n                    }\r\n                }\r\n\r\n                // INVERSE(s_inverse)  spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(T& xy_x, T& xy_y, T& lp_lon, T& lp_lat) const\r\n                {\r\n                    T B, dphi, tp;\r\n                    int i;\r\n\r\n                    if (fabs(xy_y = this->m_par.phi0 + xy_y) <= tolerance) {\r\n                        lp_lon = xy_x;\r\n                        lp_lat = 0.;\r\n                    } else {\r\n                        lp_lat = xy_y;\r\n                        B = xy_x * xy_x + xy_y * xy_y;\r\n                        i = n_iter;\r\n                        do {\r\n                            tp = tan(lp_lat);\r\n                            lp_lat -= (dphi = (xy_y * (lp_lat * tp + 1.) - lp_lat -\r\n                                .5 * ( lp_lat * lp_lat + B) * tp) /\r\n                                ((lp_lat - xy_y) / tp - 1.));\r\n                        } while (fabs(dphi) > conv_tolerance && --i);\r\n                        if (! i) {\r\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\r\n                        }\r\n                        lp_lon = asin(xy_x * tan(lp_lat)) / sin(lp_lat);\r\n                    }\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"poly_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Polyconic (American)\r\n            template <typename Parameters, typename T>\r\n            inline void setup_poly(Parameters& par, par_poly<T>& proj_parm)\r\n            {\r\n                if (par.es != 0.0) {\r\n                    proj_parm.en = pj_enfn<T>(par.es);\r\n                    proj_parm.ml0 = pj_mlfn(par.phi0, sin(par.phi0), cos(par.phi0), proj_parm.en);\r\n                } else {\r\n                    proj_parm.ml0 = -par.phi0;\r\n                }\r\n            }\r\n\r\n    }} // namespace detail::poly\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Polyconic (American) projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Conic\r\n         - Spheroid\r\n         - Ellipsoid\r\n        \\par Example\r\n        \\image html ex_poly.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct poly_ellipsoid : public detail::poly::base_poly_ellipsoid<T, Parameters>\r\n    {\r\n        inline poly_ellipsoid(const Parameters& par) : detail::poly::base_poly_ellipsoid<T, Parameters>(par)\r\n        {\r\n            detail::poly::setup_poly(this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Polyconic (American) projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Conic\r\n         - Spheroid\r\n         - Ellipsoid\r\n        \\par Example\r\n        \\image html ex_poly.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct poly_spheroid : public detail::poly::base_poly_spheroid<T, Parameters>\r\n    {\r\n        inline poly_spheroid(const Parameters& par) : detail::poly::base_poly_spheroid<T, Parameters>(par)\r\n        {\r\n            detail::poly::setup_poly(this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail\r\n    {\r\n\r\n        // Static projection\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::poly, poly_spheroid, poly_ellipsoid)\r\n\r\n        // Factory entry(s)\r\n        template <typename T, typename Parameters>\r\n        class poly_entry : public detail::factory_entry<T, Parameters>\r\n        {\r\n            public :\r\n                virtual base_v<T, Parameters>* create_new(const Parameters& par) const\r\n                {\r\n                    if (par.es)\r\n                        return new base_v_fi<poly_ellipsoid<T, Parameters>, T, Parameters>(par);\r\n                    else\r\n                        return new base_v_fi<poly_spheroid<T, Parameters>, T, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename T, typename Parameters>\r\n        inline void poly_init(detail::base_factory<T, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"poly\", new poly_entry<T, Parameters>);\r\n        }\r\n\r\n    } // namespace detail\r\n    #endif // doxygen\r\n\r\n} // namespace projections\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_POLY_HPP\r\n\r\n", "meta": {"hexsha": "2346413dacb451e966e8ee04fb6c06b2ec462a19", "size": 12425, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/srs/projections/proj/poly.hpp", "max_stars_repo_name": "Talustus/boost_src", "max_stars_repo_head_hexsha": "ffe074de008f6e8c46ae1f431399cf932164287f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-23T01:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-23T01:40:07.000Z", "max_issues_repo_path": "jeff/common/include/boost/geometry/srs/projections/proj/poly.hpp", "max_issues_repo_name": "jeffphi/advent-of-code-2018", "max_issues_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jeff/common/include/boost/geometry/srs/projections/proj/poly.hpp", "max_forks_repo_name": "jeffphi/advent-of-code-2018", "max_forks_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4723127036, "max_line_length": 130, "alphanum_fraction": 0.5095372233, "num_tokens": 2713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22745864304150112}}
{"text": "/*\n *  Copyright (c) 2009, 2010, Universitaet Bremen\n *  All rights reserved.\n *\n *  Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>\n *\n *  Redistribution and use in source and binary forms, with or without\n *  modification, are permitted provided that the following conditions\n *  are met:\n *\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   * Neither the name of the Universitaet Bremen nor the names of its\n *     contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n *  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *  POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef __UKF_MTKWRAP_HPP__\n#define __UKF_MTKWRAP_HPP__\n\n#include <cassert>\n\n#include <Eigen/Core>\n//#include <Eigen/LU> \n\n//#include <Eigen/QR>\n\n\nnamespace ukfom {\n\n\n\n// import most common Eigen types \nUSING_PART_OF_NAMESPACE_EIGEN\n\n\n/**\n * mtkwrap<M> wraps an MTK-Manifold M to a ukf-compatible manifold.\n * M has to have an enum DOF and implement the methods boxplus and boxminus.\n */\ntemplate<class M>\nstruct mtkwrap : public M{\n\ttypedef mtkwrap<M> self;\npublic:\n\ttypedef double scalar; // MTK only works with double\n\ttypedef scalar scalar_type;\n\n\tenum {\n\t\tDOF = M::DOF\n\t};\n\t\n\ttypedef Matrix<scalar_type, DOF, 1> vectorized_type;\n\n\tmtkwrap(const M &m=M()) : M(m) {}\n\t\n\n\t/*\n\t * manifold operator (+)\n\t *\n\t */\n\tself& operator+=(const vectorized_type &delta_state)\n\t{\n\t\tassert(delta_state.stride() == DOF);\n\t\tM::boxplus(delta_state.data());\n\t\treturn *this;\n\t}\n\n\tconst self operator+(const vectorized_type &delta_state) const\n\t{\n\t\tself result = *this;\n\t\tresult += delta_state;\n\t\t\n\t\treturn result;\n\t}\n\n\t/*\n\t * manifold operator (-)\n\t */\n\tconst vectorized_type operator-(const self &other) const\n\t{\n\t\tvectorized_type result;\n\t\tassert(result.stride()==DOF);\n\t\tM::boxminus(result.data(), other);\n\n\t\treturn result;\n\t}\n\n\tbool operator==(const self &other) const\n\t{\n\t\tvectorized_type diff = (*this) - other;\n\t\treturn diff.isZero(1e-12);\n\t}\n\n\tbool operator!=(const self &other) const\n\t{\n\t\treturn !(*this == other);\n\t}\n\npublic:\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n} // namespace ukfom\n#endif /* __UKF_MTKWRAP_HPP__ */\n", "meta": {"hexsha": "5b8b1ed96808d69582645aaaa446524e77922308", "size": 3209, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/slam_and_orientation/ukfom/mtkwrap.hpp", "max_stars_repo_name": "mfkiwl/ADEKF", "max_stars_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 90.0, "max_stars_repo_stars_event_min_datetime": "2021-01-04T11:04:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T01:43:07.000Z", "max_issues_repo_path": "examples/slam_and_orientation/ukfom/mtkwrap.hpp", "max_issues_repo_name": "mfkiwl/ADEKF", "max_issues_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/slam_and_orientation/ukfom/mtkwrap.hpp", "max_forks_repo_name": "mfkiwl/ADEKF", "max_forks_repo_head_hexsha": "178092b7585b0f311ed7889820704e74dab12bd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2021-04-26T09:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-23T01:43:10.000Z", "avg_line_length": 26.3032786885, "max_line_length": 76, "alphanum_fraction": 0.7192271736, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337583, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2274252389271956}}
{"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <iostream>\n#include <stdexcept>\n#include <functional>\n#include <mutex>\n#include <Eigen/Geometry>\n\n#ifdef ENABLE_PARALLEL\n    #include <omp.h>\n#endif\n\n#ifndef SIMPLE_HAUSDORFF_DISTANCE_HPP\n#define SIMPLE_HAUSDORFF_DISTANCE_HPP\n\nnamespace simple_hausdorff_distance\n{\n    class SimpleHausdorffDistance\n    {\n    private:\n\n        SimpleHausdorffDistance() {}\n\n        static inline size_t GetNumOMPThreads()\n        {\n#ifdef ENABLE_PARALLEL\n            size_t num_threads = 0;\n            #pragma omp parallel\n            {\n                num_threads = (size_t)omp_get_num_threads();\n            }\n            return num_threads;\n#else\n            return 1;\n#endif\n        }\n\n    public:\n\n        template<typename Datatype, typename Allocator=std::allocator<Datatype>>\n        static double ComputeDistance(const std::vector<Datatype, Allocator>& first_distribution, const std::vector<Datatype, Allocator>& second_distribution, const std::function<double(const Datatype&, const Datatype&)>& distance_fn)\n        {\n            // Compute the Hausdorff distance - the \"maximum minimum\" distance\n            double maximum_minimum_distance = 0.0;\n#ifdef ENABLE_PARALLEL\n            std::vector<double> thread_temp_storage(GetNumOMPThreads(), 0.0);\n            #pragma omp parallel for schedule(guided)\n#endif\n            for (size_t idx = 0; idx < first_distribution.size(); idx++)\n            {\n                const Datatype& first = first_distribution[idx];\n                double minimum_distance = INFINITY;\n                for (size_t jdx = 0; jdx < second_distribution.size(); jdx++)\n                {\n                    const Datatype& second = second_distribution[jdx];\n                    const double& current_distance = distance_fn(first, second);\n                    if (current_distance < minimum_distance)\n                    {\n                        minimum_distance = current_distance;\n                    }\n                }\n#ifdef ENABLE_PARALLEL\n                const size_t current_thread_id = (size_t)omp_get_thread_num();\n                if (minimum_distance > thread_temp_storage[current_thread_id])\n                {\n                    thread_temp_storage[current_thread_id] = minimum_distance;\n                }\n#else\n                if (minimum_distance > maximum_minimum_distance)\n                {\n                    maximum_minimum_distance = minimum_distance;\n                }\n#endif\n            }\n#ifdef ENABLE_PARALLEL\n            for (size_t idx = 0; idx < thread_temp_storage.size(); idx++)\n            {\n                const double& temp_minimum_distance = thread_temp_storage[idx];\n                if (temp_minimum_distance > maximum_minimum_distance)\n                {\n                    maximum_minimum_distance = temp_minimum_distance;\n                }\n            }\n#endif\n            return maximum_minimum_distance;\n        }\n    };\n}\n#endif // SIMPLE_HAUSDORFF_DISTANCE_HPP\n", "meta": {"hexsha": "f1e05c3fc97f8f1cada848981ec0b9a0afaebbe6", "size": 3025, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "arc_utilities/include/arc_utilities/simple_hausdorff_distance.hpp", "max_stars_repo_name": "UM-ARM-Lab/mab_ms", "max_stars_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T12:12:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T09:43:27.000Z", "max_issues_repo_path": "arc_utilities/include/arc_utilities/simple_hausdorff_distance.hpp", "max_issues_repo_name": "UM-ARM-Lab/mab_ms", "max_issues_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "arc_utilities/include/arc_utilities/simple_hausdorff_distance.hpp", "max_forks_repo_name": "UM-ARM-Lab/mab_ms", "max_forks_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T03:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:12:23.000Z", "avg_line_length": 32.5268817204, "max_line_length": 234, "alphanum_fraction": 0.5963636364, "num_tokens": 585, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2273808559697743}}
{"text": "//============================================================================\n// Name        : TDEModel.cpp\n// Author      : Jordan Frank (jordan.frank@cs.mcgill.ca)\n// Copyright   : MIT\n// Description : Implementation for the time-delay embedding model.\n//============================================================================\n\n#include <stdlib.h>\n#include <ctype.h>\n#include <iostream>\n#include <fstream>\n#include <Tisean/tsa.h>\n#include <ANN/ANN.h>\n#include <opencv/cxcore.h>\n#include <boost/random.hpp>\n//#include <opencv/cvaux.h>\n\n#include \"Utils.h\"\n#include \"BuildTree.h\"\n#include \"TDEModel.h\"\n\nusing namespace std;\nusing namespace boost;\n\nTDEModel::TDEModel(Settings* settings) {\n    ANNcoord *data, *projecteddata;\n\n    length = settings->length;\n    embdim = settings->embdim;\n    delay = settings->delay;\n    use_pca = settings->pcaembset;\n\n    get_embedding(settings, data, length);\n\n    if (use_pca) {\n    \tcerr << \"Computing PCA bases.\\n\";\n    \tcomputePCABases(data, length, embdim, settings->pcaembdim);\n    \tprojecteddata = projectData(data, length, embdim);\n    \tdelete [] data;\n    \tdata = projecteddata;\n    }\n    else {\n    \tavg = NULL;\n    \tbases = NULL;\n    }\n    /*\n\tfor (uint i = 0; i < (unsigned)bases->cols; i++) {\n\t\tcout << data[i] << \" \" ;\n\t}\n\tcout << endl;\n\t*/\n    get_ann_points(dataPts, data, length, settings->pcaembdim);\n    kdTree = new ANNkd_tree(dataPts,length,settings->pcaembdim);\n    settings->length = length;\n    delete [] data;\n}\n\nTDEModel::TDEModel(ifstream* model_file, uint verbosity) {\n\tint avgsize, basesrows, basescols, i, j;\n\t*model_file >> delay;\n\t*model_file >> embdim;\n\t*model_file >> avgsize;\n\n\tif (avgsize > 0) {\n\t\tuse_pca = 1;\n\t\tavg = cvCreateMat(1,avgsize,MAT_TYPE);\n\t\tANNcoord* ptr = (ANNcoord*)avg->data.ptr;\n\t\tfor (i = 0; i < avgsize; i++) {\n\t\t\t*model_file >> *ptr++;\n\t\t}\n\t}\n\telse {\n\t\tuse_pca = 0;\n\t\tavg = NULL;\n\t\tbases = NULL;\n\t}\n\t*model_file >> basesrows >> basescols;\n\tif (verbosity > 0) {\n\t\tif (basescols > 0)\n\t\t\tcerr << \"Model params: d=\" << delay << \" m=\" << embdim << \" p=\" << basescols << endl;\n\t\telse\n\t\t\tcerr << \"Model params: d=\" << delay << \" m=\" << embdim << endl;\n\t}\n\tif (use_pca) {\n\t\tbases = cvCreateMat(basesrows,basescols,MAT_TYPE);\n\t\tANNcoord* ptr = (ANNcoord*)bases->data.ptr;\n\t\tfor (i = 0; i < basesrows; i++) {\n\t\t\tfor (j = 0; j < basescols; j++) {\n\t\t\t\t*model_file >> *ptr++;\n\t\t\t}\n\t\t}\n\t}\n\n\tkdTree = new ANNkd_tree(*model_file);\n\tdataPts = kdTree->thePoints();\n\tlength = kdTree->nPoints();\n\n\tif (verbosity > 0)\n\t\tcerr << \"Loaded \" << length << \" points.\" << endl;\n\tmodel_file->close();\n\tdelete model_file;\n}\n\nTDEModel::~TDEModel() {\n\tif (avg != NULL) cvReleaseMat(&avg);\n\tif (bases != NULL) cvReleaseMat(&bases);\n\tannDeallocPts(dataPts);\n\tdelete kdTree;\n}\n\nvoid TDEModel::DumpTree(char* outfile) {\n    ofstream fout(outfile);\n    fout << delay << endl;\n    fout << embdim << endl;\n    if (avg == NULL) {\n    \tfout << 0 << endl;\n    }\n    else {\n    \tfout << avg->cols << endl;\n    \tfor (int i = 0; i < avg->cols; i++) {\n    \t\tfout << \" \" << CV_MAT_ELEM(*avg, ANNcoord, 0, i);\n    \t}\n    }\n\tfout << endl;\n    if (bases == NULL) {\n    \tfout << \"0 0\" << endl;\n    }\n    else {\n    \tfout << bases->rows << \" \" << bases->cols << endl;\n    \tfor (int i = 0; i < bases->rows; i++) {\n        \tfout << CV_MAT_ELEM(*bases, ANNcoord, i, 0);\n    \t\tfor (int j = 1; j < bases->cols; j++) {\n    \t\t\tfout << \" \" << CV_MAT_ELEM(*bases, ANNcoord, i, j);\n    \t\t}\n    \t\tfout << endl;\n    \t}\n    }\n    kdTree->Dump(ANNtrue, fout);\n    fout.close();\n}\n\nvoid TDEModel::getKNN(ANNpoint ap, uint k, ANNidxArray nn_idx, ANNdistArray dists) {\n\tkdTree->annkSearch(ap, k, nn_idx, dists);\n//    for (uint i = 0; i < k; i++) {\n//            cout << \"Point \" << i+1 << \": [\" << dataPts[nn_idx[i]][0] << \",\" << dataPts[nn_idx[i]][1] << \",\" << dataPts[nn_idx[i]][2] << \"], Dist: \" << sqrt(dists[i]) << endl;\n//    }\n}\n\nvoid TDEModel::simulateTrajectory(ANNpoint s0, ANNpointArray trajectory, uint dim, ulong N) {\n    ANNidxArray nn_idx;\n    ANNdistArray dists;\n    uint i,j,k;\n    variate_generator<mt19937, normal_distribution<> > generator(mt19937(time(0)), normal_distribution<>(0.0,0.1));\n    uint neighbours = 4;\n\t// +1 in case one of the neighbours is the last point in the model.\n    nn_idx = new ANNidx[neighbours+1];\n    dists = new ANNdist[neighbours+1];\n\n    for (i = 0; i < dim; i++) {\n    \ttrajectory[0][i] = s0[i];\n    }\n\n    for (i = 1; i < N; i++) {\n    \tgetKNN(trajectory[i-1], neighbours+1, nn_idx, dists);\n    \tfor (j = 0; j < dim; j++) {\n    \t\ttrajectory[i][j] = 0.0;\n    \t\tfor (k = 0; k < neighbours; k++) {\n    \t\t\tif (nn_idx[k] == ANN_NULL_IDX) break;\n    \t\t\telse if (nn_idx[k] == (int)length-1) nn_idx[k] = nn_idx[neighbours];\n    \t\t\ttrajectory[i][j] += dataPts[nn_idx[k]+1][j];\n    \t\t}\n    \t\ttrajectory[i][j] = trajectory[i][j] / (ANNcoord)k + generator();\n    \t}\n    }\n}\n\nANNpoint TDEModel::getDataPoint(uint idx) {\n\treturn dataPts[idx];\n}\n\nvoid TDEModel::computePCABases(ANNcoord *data, uint rows, uint cols, uint numbases) {\n\tCvMat **embedding, *cov, *eigenvectors, *eigenvalues, *vector;\n\tANNcoord *basesdata;\n\tuint i, j, offset;\n\n\tcov = cvCreateMat(cols, cols, MAT_TYPE);\n\teigenvectors = cvCreateMat(cols,cols,MAT_TYPE);\n\teigenvalues = cvCreateMat(cols,cols,MAT_TYPE);\n\tembedding = new CvMat*[rows];\n\tfor (i = 0; i < rows; i++) {\n\t\tvector = cvCreateMatHeader(1, cols, MAT_TYPE);\n\t\tcvInitMatHeader(vector, 1, cols, MAT_TYPE, data + i * cols);\n\t\tembedding[i] = vector;\n\t}\n\tavg = cvCreateMat(1,cols,MAT_TYPE);\n\tcvCalcCovarMatrix((const CvArr **)embedding, rows, cov, avg, CV_COVAR_NORMAL);\n\tcvSVD(cov, eigenvalues, eigenvectors, 0, CV_SVD_MODIFY_A);\n\n\tbasesdata = new ANNcoord[cols*numbases];\n\tfor (i = 0, offset = 0; i < cols; i++) {\n\t\tfor (j = 0; j < numbases; j++) {\n\t\t\tbasesdata[offset++] = ((ANNcoord*)eigenvectors->data.ptr)[i*cols+j];\n\t\t}\n\t}\n\tbases = cvCreateMatHeader(cols, numbases, MAT_TYPE);\n\tcvInitMatHeader(bases, cols, numbases, MAT_TYPE, basesdata);\n\n\tfor (i = 0; i < rows; i++) {\n    \tcvReleaseMat(&embedding[i]);\n    }\n    delete [] embedding;\n    cvReleaseMat(&cov);\n    cvReleaseMat(&eigenvectors);\n    cvReleaseMat(&eigenvalues);\n}\n\nANNcoord* TDEModel::projectData(ANNcoord* data, uint rows, uint cols) {\n\tif (!use_pca) return data;\n\tANNcoord* shifteddata = new ANNcoord[rows*cols];\n\tANNcoord* projecteddata = new ANNcoord[rows*bases->cols];\n\tuint i, j, offset;\n\n\tfor (i = 0, offset = 0; i < rows; i++) {\n\t\tfor (j = 0; j < cols; j++) {\n\t\t\tshifteddata[offset] = data[offset] - ((ANNcoord*)avg->data.ptr)[j];\n\t\t\toffset++;\n\t\t}\n\t}\n\tCvMat projected = cvMat(rows, bases->cols, MAT_TYPE, projecteddata);\n\tCvMat dataMat = cvMat(rows, cols, MAT_TYPE, shifteddata);\n\tcvGEMM(&dataMat, bases, 1.0, NULL, 0.0, &projected, 0);\n\t/*\n\tfor (i = 0; i < (unsigned)bases->cols; i++) {\n\t\tcout << projecteddata[i] << \" \" ;\n\t}\n\tcout << endl;\n\t*/\n\tdelete [] shifteddata;\n\treturn projecteddata;\n}\n", "meta": {"hexsha": "4d2798a3beb7ac8c8c6fac6c765aaf545aaba4ba", "size": 6864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TDEModel.cpp", "max_stars_repo_name": "jwf-zz/tdetools", "max_stars_repo_head_hexsha": "7beb6e4f5dec719a3a59fefd8e92e90475392d48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-16T00:47:38.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-23T11:52:37.000Z", "max_issues_repo_path": "TDEModel.cpp", "max_issues_repo_name": "jwf-zz/tdetools", "max_issues_repo_head_hexsha": "7beb6e4f5dec719a3a59fefd8e92e90475392d48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TDEModel.cpp", "max_forks_repo_name": "jwf-zz/tdetools", "max_forks_repo_head_hexsha": "7beb6e4f5dec719a3a59fefd8e92e90475392d48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-18T06:34:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-18T06:34:54.000Z", "avg_line_length": 28.4813278008, "max_line_length": 177, "alphanum_fraction": 0.592511655, "num_tokens": 2193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.38861801254413975, "lm_q1q2_score": 0.2273808420606367}}
{"text": "/*\n * Copyright (c) 2018 Eliane Briand\n *\n * This file is part of SmolDock.\n *\n * SmolDock is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SmolDock is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with SmolDock.  If not, see <https://www.gnu.org/licenses/>.\n *\n */\n\n#include \"VinaLikeRigid.h\"\n\n#undef BOOST_LOG\n\n#include <boost/log/trivial.hpp>\n\n#include <cmath>\n#include <boost/assert.hpp>\n#include <iomanip>\n#include <Structures/Atom.h>\n\n#include <Engines/Internals/InternalsUtilityFunctions.h>\n\n#include \"VinaLikeCommon.h\"\n\nnamespace SmolDock {\n    namespace Score {\n\n        const std::array<std::string, VinaLikeRigid::numCoefficients>\n                VinaLikeRigid::coefficientsNames =  {\"Gauss1\", \"Gauss2\", \"RepulsionExceptCovalent\", \"Hydrophobic\",\"Hydrogen\"};\n\n\n        double vina_like_rigid_inter_scoring_func(const iConformer &ligand, iTransform &transform,\n                                                  const iProtein &protein) {\n\n            BOOST_ASSERT(!ligand.x.empty());\n            BOOST_ASSERT(!protein.x.empty());\n\n            if(std::abs(transform.rota.norm() - 1) > 0.1) {\n                transform.rota.normalize();\n            }\n\n            double score_raw = 0;\n\n\n            Eigen::Vector3d ProtCenterPosition = {protein.center_x, protein.center_y, protein.center_z};\n\n            for (unsigned int idxLig = 0; idxLig < ligand.x.size(); idxLig++) {\n                for (unsigned int idxProt = 0; idxProt < protein.x.size(); idxProt++) {\n\n\n                    Eigen::Vector3d LigPosition = {ligand.x[idxLig], ligand.y[idxLig], ligand.z[idxLig]};\n                    applyRigidTransformInPlace(LigPosition, transform);\n\n                    Eigen::Vector3d ProtPosition = {protein.x[idxProt], protein.y[idxProt], protein.z[idxProt]};\n\n                    Eigen::Vector3d distToCenterVector = LigPosition - ProtCenterPosition;\n\n                    double distanceToProteinCenter = distToCenterVector.norm();\n\n                    if (distanceToProteinCenter > (protein.radius - 1)) {\n                        score_raw += std::pow((distanceToProteinCenter - protein.radius), 4) + 10;\n                        continue;\n                    }\n\n                    Eigen::Vector3d distVect = ProtPosition - LigPosition;\n\n                    double atomicRadiusLig = ligand.atomicRadius[idxLig];\n                    double atomicRadiusProt = protein.atomicRadius[idxProt];\n                    double rawDist = distVect.norm();\n\n\n                    const double cutoff = 8.0;\n                    if (rawDist >= cutoff)\n                        continue;\n\n                    double radToRemove = (atomicRadiusLig + atomicRadiusProt);\n                    double distance = rawDist - radToRemove;\n\n                    score_raw += scoreForAtomCouple(distance, ligand.type[idxLig], ligand.variant[idxLig],\n                                                    protein.type[idxProt], protein.variant[idxProt]);\n/*\n                    // Special rubber band term not in Vina scoring func\n                    double x_diff_center = std::pow(LigPosition.x - protein.center_x, 2);\n                    double y_diff_center = std::pow(LigPosition.y - protein.center_y, 2);\n                    double z_diff_center = std::pow(LigPosition.z - protein.center_z, 2);\n                    double rawDistCenter = std::sqrt(x_diff_center + y_diff_center + z_diff_center);\n\n                    score += 0.00001 * rawDistCenter;\n*/\n\n                } // for\n            } // for\n            /*\n            BOOST_LOG_TRIVIAL(debug) << \"Intermolecular scoring contribution without weighting :\";\n            BOOST_LOG_TRIVIAL(debug) << \"Gauss 1      : \" << std::fixed<< std::setprecision(5) << score_gauss1;\n            BOOST_LOG_TRIVIAL(debug) << \"Gauss 2      : \" << std::fixed<< std::setprecision(5) << score_gauss2;\n            BOOST_LOG_TRIVIAL(debug) << \"Repulsion    : \" << std::fixed<< std::setprecision(5) << score_repulsion;\n            BOOST_LOG_TRIVIAL(debug) << \"Hydrophobic  : \" << std::fixed<< std::setprecision(5) << score_hydrophobic;\n            BOOST_LOG_TRIVIAL(debug) << \"Hydrogen     : \" << std::fixed<< std::setprecision(5) << score_hydrogen;\n            BOOST_LOG_TRIVIAL(debug) << \"------------------------------------------\";\n            BOOST_LOG_TRIVIAL(debug) << \"Raw Score    : \" << score_raw;\n            BOOST_LOG_TRIVIAL(debug) << \"Nrotatable   : \" << ligand.num_rotatable_bond;\n            //*/\n            double final_score = score_raw / (1 + (0.058459999999999998 * ligand.num_rotatable_bond));\n            /*\n            BOOST_LOG_TRIVIAL(debug) << \"------------------------------------------\";\n            BOOST_LOG_TRIVIAL(debug) << \"Final Score  : \" << final_score;\n            //*/\n\n            return final_score;\n        }\n\n        double VinaLikeRigid::Evaluate(const arma::mat &x) {\n            BOOST_ASSERT(x.n_rows == 7);\n\n            iTransform tr = this->internalToExternalRepr(x);\n            tr.doHousekeeping();\n\n            double score_ = vina_like_rigid_inter_scoring_func(this->startingConformation, tr, this->prot);\n\n            return score_;\n        }\n\n        double VinaLikeRigid::EvaluateWithGradient(const arma::mat &x, arma::mat &grad) {\n\n            BOOST_ASSERT(!x.has_nan());\n            BOOST_ASSERT(!grad.has_nan());\n            BOOST_ASSERT(x.n_rows == 7);\n            BOOST_ASSERT(grad.n_rows == 7);\n\n            iTransform tr = this->internalToExternalRepr(x);\n            tr.doHousekeeping();\n\n            double score_ = vina_like_rigid_inter_scoring_func(this->startingConformation, tr, this->prot);\n\n            // Translation\n            {\n                iTransform transform_dx = tr;\n                transform_dx.transl.x() += this->differential_epsilon;\n                grad[0] = vina_like_rigid_inter_scoring_func(this->startingConformation, transform_dx, this->prot) -\n                          score_;\n            }\n\n            {\n                iTransform transform_dy = tr;\n                transform_dy.transl.y() += this->differential_epsilon;\n                grad[1] = vina_like_rigid_inter_scoring_func(this->startingConformation, transform_dy, this->prot) -\n                          score_;\n            }\n\n            {\n                iTransform transform_dz = tr;\n                transform_dz.transl.z() += this->differential_epsilon;\n                grad[2] = vina_like_rigid_inter_scoring_func(this->startingConformation, transform_dz, this->prot) -\n                          score_;\n            }\n\n            // Rotation\n\n            {\n                iTransform transform_ds = tr;\n                transform_ds.rota.w() += this->differential_epsilon;\n                transform_ds.doHousekeeping();\n                grad[3] = vina_like_rigid_inter_scoring_func(this->startingConformation, transform_ds, this->prot) -\n                          score_;\n            }\n\n            {\n                iTransform transform_du = tr;\n                transform_du.rota.x() += this->differential_epsilon;\n                transform_du.doHousekeeping();\n                grad[4] = vina_like_rigid_inter_scoring_func(this->startingConformation, transform_du, this->prot) -\n                          score_;\n            }\n\n            {\n                iTransform transform_dv = tr;\n                transform_dv.rota.y() += this->differential_epsilon;\n                transform_dv.doHousekeeping();\n                grad[5] = vina_like_rigid_inter_scoring_func(this->startingConformation, transform_dv, this->prot) -\n                          score_;\n            }\n\n            {\n                iTransform transform_dt = tr;\n                transform_dt.rota.z() += this->differential_epsilon;\n                transform_dt.doHousekeeping();\n                grad[6] = vina_like_rigid_inter_scoring_func(this->startingConformation, transform_dt, this->prot) -\n                          score_;\n            }\n            /*\n            BOOST_LOG_TRIVIAL(debug) << \"Transform: \" << x.t();\n            BOOST_LOG_TRIVIAL(debug) << \"Score: \" << score_;\n            BOOST_LOG_TRIVIAL(debug) << \"Gradient\";\n            BOOST_LOG_TRIVIAL(debug) << \"     ds: \" << grad[3];\n            BOOST_LOG_TRIVIAL(debug) << \"     du: \" << grad[4] << \"   dx: \" << grad[0];\n            BOOST_LOG_TRIVIAL(debug) << \"     dv: \" << grad[5] << \"   dy: \" << grad[1];\n            BOOST_LOG_TRIVIAL(debug) << \"     dt: \" << grad[6] << \"   dx: \" << grad[2];\n            //*/\n\n            BOOST_ASSERT(score_ == score_); // catches NaN\n            return score_;\n        }\n\n\n        VinaLikeRigid::VinaLikeRigid(const iConformer &startingConformation_,\n                                                                   const iProtein &p,\n                                                                   const iTransform &initialTransform_,\n                                                                   double differential_epsilon_) :\n\n                startingConformation(startingConformation_),\n                prot(p),\n                initialTransform(initialTransform_),\n                differential_epsilon(differential_epsilon_) {}\n\n\n        double VinaLikeRigid::getDifferentialEpsilon() const {\n            return this->differential_epsilon;\n        }\n\n        arma::mat VinaLikeRigid::getStartingConditions() const {\n            return this->externalToInternalRepr(this->initialTransform);\n        }\n\n        iConformer VinaLikeRigid::getConformerForParamMatrix(const arma::mat &x) {\n            BOOST_ASSERT(x.n_rows == 7);\n\n            iTransform tr = this->internalToExternalRepr(x);\n            normalizeQuaternionInPlace(\n                    tr.rota); //!< Note that the internal representation arma::mat is not by itself normalized\n            //! (because we always normalize it in the scoring function, so no constraint)\n\n            iConformer ret = this->startingConformation;\n            applyRigidTransformInPlace(ret, tr);\n\n            return ret;\n        }\n\n        unsigned int VinaLikeRigid::getParamVectorDimension() const {\n            return 7;\n        }\n\n\n        std::vector<std::tuple<std::string, double>> VinaLikeRigid::EvaluateSubcomponents(const arma::mat &x) {\n            std::vector<std::tuple<std::string, double>> ret;\n\n            BOOST_ASSERT(x.n_rows == 7);\n\n            iTransform tr = this->internalToExternalRepr(x);\n            normalizeQuaternionInPlace(tr.rota);\n\n            BOOST_ASSERT(!this->startingConformation.x.empty());\n            BOOST_ASSERT(!this->prot.x.empty());\n\n            if(std::abs(tr.rota.norm() - 1) > 0.1) {\n                tr.rota.normalize();\n            }\n\n            BOOST_ASSERT(tr.bondRotationsAngles.size() == this->startingConformation.num_rotatable_bond);\n\n\n            double gauss1_total = 0.0;\n            double gauss2_total = 0.0;\n            double repulsion_total = 0.0;\n            double hydrogen_total = 0.0;\n            double hydrophobic_total = 0.0;\n            double score_raw = 0.0;\n\n            iConformer ligand = this->startingConformation;\n            applyBondRotationInPlace(ligand, tr);\n\n            Eigen::Vector3d ProtCenterPosition = {this->prot.center_x, this->prot.center_y, this->prot.center_z};\n\n            for (unsigned int idxLig = 0; idxLig < ligand.x.size(); idxLig++) {\n                for (unsigned int idxProt = 0; idxProt < this->prot.x.size(); idxProt++) {\n\n\n                    Eigen::Vector3d LigPosition = {ligand.x[idxLig], ligand.y[idxLig], ligand.z[idxLig]};\n                    applyRigidTransformInPlace(LigPosition, tr);\n\n                    Eigen::Vector3d ProtPosition = {this->prot.x[idxProt], this->prot.y[idxProt], this->prot.z[idxProt]};\n                    Eigen::Vector3d distToCenterVector = LigPosition - ProtCenterPosition;\n\n                    double distanceToProteinCenter = distToCenterVector.norm();\n\n                    if (distanceToProteinCenter > (this->prot.radius - 1)) {\n                        //FIXME : temporary disable\n                        //score_raw += std::pow((distanceToProteinCenter - this->prot.radius), 4) + 10;\n                        continue;\n                    }\n\n                    Eigen::Vector3d distVect = ProtPosition - LigPosition;\n\n                    double rawDist = distVect.norm();\n\n                    const double cutoff = 8.0;\n                    if (rawDist >= cutoff)\n                        continue;\n\n                    double distance = distanceFromRawDistance(rawDist,  ligand.atomicRadius[idxLig], this->prot.atomicRadius[idxProt]);\n\n                    unsigned char atom1AtomicNumber = ligand.type[idxLig];\n                    unsigned int atom1AtomVariant = ligand.variant[idxLig];\n                    unsigned char atom2AtomicNumber = this->prot.type[idxProt];\n                    unsigned int atom2AtomVariant = this->prot.variant[idxProt];\n\n                    gauss1_total += vinaGaussComponent(distance, 0.0, 0.5);\n                    gauss2_total += vinaGaussComponent(distance, 3.0, 2.0);\n                    repulsion_total += vinaRepulsionComponent(distance, 0.0);\n                    hydrogen_total += vinaHydrophobicComponent(distance,\n                                                               atom1AtomicNumber, atom1AtomVariant,\n                                                               atom2AtomicNumber, atom2AtomVariant);\n                    hydrophobic_total += vinaHydrogenComponent(distance,\n                                                               atom1AtomicNumber, atom1AtomVariant,\n                                                               atom2AtomicNumber, atom2AtomVariant);\n                    score_raw += scoreForAtomCouple(distance,\n                                                    atom1AtomicNumber, atom1AtomVariant,\n                                                    atom2AtomicNumber, atom2AtomVariant);\n\n                } // for\n            } // for\n\n            double final_score = score_raw / (1 + (0.058459999999999998 * ligand.num_rotatable_bond));\n\n\n            ret.emplace_back(std::make_tuple(\"Gauss1\",gauss1_total));\n            ret.emplace_back(std::make_tuple(\"Gauss2\",gauss2_total));\n            ret.emplace_back(std::make_tuple(\"Repulsion\",repulsion_total));\n            ret.emplace_back(std::make_tuple(\"Hydrophobic\",hydrogen_total));\n            ret.emplace_back(std::make_tuple(\"Hydrogen\",hydrophobic_total));\n            ret.emplace_back(std::make_tuple(\"ScoreRaw\",score_raw));\n            ret.emplace_back(std::make_tuple(\"Score\",final_score));\n            return ret;\n        }\n\n        double VinaLikeRigid::EvaluateOnlyIntermolecular(const arma::mat &x) {\n            return this->Evaluate(x);\n        }\n\n        unsigned int VinaLikeRigid::getCoefficientsVectorWidth() {\n            return this->numCoefficients;\n        }\n\n        std::vector<std::string> VinaLikeRigid::getCoefficientsNames() {\n            return std::vector<std::string>(this->coefficientsNames.begin(),this->coefficientsNames.end());\n        }\n\n        std::vector<double> VinaLikeRigid::getCurrentCoefficients() {\n            return {VinaClassic::coeff_gauss1, VinaClassic::coeff_gauss2,\n                    VinaClassic::coeff_repulsion, VinaClassic::coeff_hydrophobic,\n                    VinaClassic::coeff_hydrogen };\n        }\n\n        bool VinaLikeRigid::setNonDefaultCoefficients(std::vector<double> coeffs) {\n            BOOST_LOG_TRIVIAL(debug) << \"Non default coefficients not supported yet on Vina rigid scoring function.\";\n            return false;\n        }\n\n\n    }\n\n\n\n\n}\n", "meta": {"hexsha": "02839d51a6bd1fd1b0f30dd7393b93740c0e6fbf", "size": 15944, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Engines/ScoringFunctions/VinaLikeRigid.cpp", "max_stars_repo_name": "ElianeBriand/SMolDock", "max_stars_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T02:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T02:33:13.000Z", "max_issues_repo_path": "Engines/ScoringFunctions/VinaLikeRigid.cpp", "max_issues_repo_name": "ElianeBriand/SMolDock", "max_issues_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Engines/ScoringFunctions/VinaLikeRigid.cpp", "max_forks_repo_name": "ElianeBriand/SMolDock", "max_forks_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T19:11:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T02:45:49.000Z", "avg_line_length": 42.2917771883, "max_line_length": 135, "alphanum_fraction": 0.5590190667, "num_tokens": 3449, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2273719853197914}}
{"text": "//\n//  main.cpp\n//  PhyloAcc\n//\n//  Created by hzr on 3/8/16.\n//  Copyright © 2016 hzr. All rights reserved.\n//\n#include <dirent.h>\n#include <stdio.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <algorithm>\n#include <iomanip>\n//#include <omp.h> //libiomp/\n#include <string>\n#include <armadillo>\n#include \"profile.h\"\n#include \"newick.h\"\n#include \"newick2.h\"\n#include \"bpp.hpp\"\n#include \"bpp_c.hpp\"\n#include \"utils.h\"\n#include <math.h>\n#include <gsl/gsl_errno.h>\n\nusing namespace std;\nusing namespace arma;\n\n// parameters, input and output files paths\nstring params_path;\nstring phytree_path;\nstring align_path;\nstring output_path=\"\";\nstring output_path2=\"\";\nstring segment_path;\nstring id_path=\"\";\nstring result_prefix=\"test\";\nstring tree_coal_unit=\"\";\n\n//string refspecies;\nstring outgroup;\nstring targetspecies;\nstring conservegroup; // can't be missing in more than 50%\nstring deepcoal_species = \"\"; //species in which deep coal can happen\ndouble conserve_prop = 0.8;\n\nint num_thread = 1;\n\n// running parameters\nint num_burn = 200;         // num of burn-in updates is num_burn * num_thin\nint num_mcmc = 800;         // num of MCMC updates, num_burn * num_mcmc\nint num_thin = 1;    // num of updates between two samples, adaptive frequency = 50 * num_thin\nint num_chain; // outer loop of updates Q matrix and hyperparameter of substitution rates\n\n\ndouble prep_lrate = 0.5;\ndouble prep_lrate2 = 0.0; //0.1\ndouble prep_grate = 0.8; // initalization\n\ndouble prior_lrate2_a = 0.0,prior_lrate2_b = 1 ; // beta prior for lrate2, 0.5\ndouble prior_lrate_a = 1 ,prior_lrate_b = 1 ; // beta prior for lrate, 1,9\ndouble prior_grate_a = 1,prior_grate_b = 1; // beta prior for grate, 3,1\n\n\ndouble ratio0 = 0.5; //initial conserved rate,0.5\ndouble ratio1 = 1; // initial accelerated rate\ndouble missing_thres = 0.8;\n\ndouble nprior_a = 10, nprior_b = 0.2;  //around 1\ndouble cprior_a = 5, cprior_b = 0.04;  //around ratio\nint ropt = 1;\ndouble cub = 1;\ndouble nlb = 0.6;\n\nint batch = -1 ;\nint seed = 1;\nint seed2 = 1;\ndouble indel = 0;\ndouble indel2;\nbool sample_indel = 0;\nbool sample_hyper = false;\nchar gapchar = '-';\nbool verbose = 0;\ndouble consToMis = 0.5; //for simulation, 0.01;\nint block = 15; // 25; //90;\nbool prune=0;\ndouble revgap=0.9;  // 1\nint min_length = 50;\nbool WL = true;\nbool simulate=false;\nbool verboseGT = 1; //Han*: output trace_genetrees\ndouble br_sample_cutoff = 10.0;\ndouble theta_cutoff = 1.0;\n\n//Han*: add Dirichlet prior for stationary distribution pi:\n//vector<double> prior_dir_par(4,10);\nvector<double> prior_dir_par(2,10);  //Han: it's beta prior for pi. Keep the old name.\n\n// load the program parameters\nvoid LoadParams(int argc, char* argv[])\n{\n    cout << \"Loading input data and running parameters......\" << endl;\n\n    if (argc > 1)\n        params_path = string(argv[1]);\n    else\n        params_path = \"/Users/zhiruihu/Phylogenetics/test_mammalData/param_chr2_Long2.txt\"; //params2\n\n    cout << \"Loading program configurations from \" << params_path << \"......\" <<endl;\n\n    const int BUFF_SIZE = 1024;\n    char line_buff[BUFF_SIZE];\n\n    ifstream in_params(params_path.c_str());\n    if (!in_params)\n    {\n        cerr << \"Cannot open the parameters file: \" << params_path.c_str() << endl;\n        exit(1);\n    }\n    while(!in_params.eof())\n    {\n        in_params.getline(line_buff, BUFF_SIZE);\n        istringstream line_stream(line_buff);\n        string tmp; line_stream >> tmp;\n        \n        // simulate or inference\n        if (tmp==\"SIMULATE\")\n            line_stream >> simulate;\n        // input and output file paths\n        else if (tmp==\"PHYTREE_FILE\")\n            line_stream >> phytree_path;\n        else if (tmp==\"TREE_IN_COALESCENT_UNIT\")\n            line_stream >> tree_coal_unit;\n        else if (tmp==\"ALIGN_FILE\")\n            line_stream >> align_path;\n        else if (tmp==\"SEG_FILE\")\n            line_stream >> segment_path;\n        else if (tmp==\"ID_FILE\")\n            line_stream >> id_path;\n        else if (tmp==\"BATCH\")\n            line_stream >> batch;\n        else if (tmp==\"RESULT_FOLDER\")\n            line_stream >> output_path;\n        else if (tmp==\"PREFIX\")\n            line_stream >> result_prefix;\n        else if (tmp==\"SEED\")\n            line_stream >> seed;\n        else if (tmp==\"SEEDS\")\n            line_stream >> seed2;\n        else if (tmp==\"INIT_CONSERVE_RATE\")\n            line_stream >> ratio0;\n        else if (tmp==\"INIT_ACCE_RATE\")\n            line_stream >> ratio1;\n        else if (tmp==\"CONSERVE_PRIOR_A\")\n            line_stream >> cprior_a;\n        else if (tmp==\"CONSERVE_PRIOR_B\")\n            line_stream >> cprior_b;\n        else if (tmp==\"ACCE_PRIOR_A\")\n            line_stream >> nprior_a;\n        else if (tmp==\"ACCE_PRIOR_B\")\n            line_stream >> nprior_b;\n        else if (tmp==\"ROPT\")\n            line_stream >> ropt;\n        else if (tmp==\"CUB\")\n            line_stream >> cub;\n        else if (tmp==\"NLB\")\n            line_stream >> nlb;\n\n        // running parameters\n        else if (tmp==\"BURNIN\")\n            line_stream >> num_burn;\n        else if (tmp==\"MCMC\")\n            line_stream >> num_mcmc;\n        else if (tmp==\"THIN\") //ADAPT_FREQ\n            line_stream >> num_thin;\n        else if (tmp==\"INIT_LRATE\")\n            line_stream >> prep_lrate;\n        else if (tmp==\"INIT_GRATE\")\n            line_stream >> prep_grate;\n        else if (tmp==\"HYPER_LRATE_A\")\n            line_stream >> prior_lrate_a;\n        else if (tmp==\"HYPER_LRATE_B\")\n            line_stream >> prior_lrate_b;\n        else if (tmp==\"HYPER_GRATE_A\")\n            line_stream >> prior_grate_a;\n        else if (tmp==\"HYPER_GRATE_B\")\n            line_stream >> prior_grate_b;\n        else if (tmp==\"CHAIN\")\n            line_stream >> num_chain;\n        else if (tmp==\"WL\")\n            line_stream >> WL;\n        else if (tmp==\"BLK_WL\")\n            line_stream >> block;   \n\n        // constraint\n        else if (tmp == \"OUTGROUP\")\n            line_stream >> outgroup;\n        else if (tmp == \"TARGETSPECIES\")\n            line_stream >> targetspecies;\n        else if (tmp == \"CONSERVE\")\n            line_stream >> conservegroup;\n        else if (tmp == \"CONSERVE_PROP\")\n            line_stream >> conserve_prop;\n        else if (tmp == \"GAP_PROP\")\n            line_stream >> missing_thres;\n        //else if (tmp == \"REF\")\n         //   line_stream >> refspecies;\n        else if (tmp == \"CONSTOMIS\")\n            line_stream >> consToMis;\n        else if (tmp==\"BR_SAMPLE_THRESHOLD\")\n            line_stream >> br_sample_cutoff;\n        else if (tmp==\"THETA_CUTOFF\")\n            line_stream >> theta_cutoff;\n        else if( tmp==\"DEEP_COAL_BRANCH\")\n            line_stream >> deepcoal_species;\n\n        // treat indel as additional character\n        else if (tmp == \"GAPCHAR\")\n            line_stream >> gapchar;\n        else if (tmp == \"PRUNE_TREE\")\n            line_stream >> prune;\n        else if (tmp == \"TRIM_GAP_PERCENT\")\n            line_stream >> revgap;\n        else if (tmp == \"MIN_LEN\")\n            line_stream >> min_length;\n        else if (tmp == \"INDEL\") // not used\n            line_stream >> indel;\n        else if (tmp == \"INDEL2\") // not used\n            line_stream >> indel2;\n        else if(tmp == \"SAMPLE_INDEL\")  // not used\n            line_stream >> sample_indel;\n        else if(tmp == \"SAMPLE_HYPER\")\n            line_stream >> sample_hyper;\n        else if(tmp == \"VERBOSE\")\n            line_stream >> verbose;\n        else if(tmp == \"VERBOSE_GENETREE\") //Han*: output sampled gene trees\n            line_stream>>verboseGT;\n        else if(tmp == \"NUM_THREAD\")\n            line_stream >> num_thread;\n        else if(tmp != \"\")\n            cout << \"Unknown parameter: \" << tmp <<endl;\n\n    }\n\n    // trimming file names\n    phytree_path = strutils::trim(phytree_path, \" \\\"\\t\\n\");\n    align_path = strutils::trim(align_path, \" \\\"\\t\\n\");\n    output_path  = strutils::trim(output_path,  \" \\\"\\t\\n\");\n    segment_path = strutils::trim(segment_path, \" \\\"\\t\\n\");\n    tree_coal_unit = strutils::trim(tree_coal_unit, \" \\\"\\t\\n\");\n}\n\nbool DirectoryExists( string pzPath )\n{\n    if ( pzPath == \"\") return false;\n\n    DIR *pDir;\n    bool bExists = false;\n\n    pDir = opendir (pzPath.c_str());\n\n    if (pDir != NULL)\n    {\n        bExists = true;\n        (void) closedir (pDir);\n    }\n\n    return bExists;\n}\n\nvoid DispParams(PhyloProf profile, int seed)\n{\n    double mean_seg_size = 0;\n    for(unsigned int c=0; c<profile.C; c++)\n        mean_seg_size += (double)(profile.element_pos[c][1] - profile.element_pos[c][0]) / profile.C;\n    cout << \"  # total length = \" << profile.G << \" (\" << profile.C << \")\" << \". # Species = \" << profile.S << \". # elements = \" << profile.C << \". Mean gene set size = \" << mean_seg_size << \".\" << endl;\n    cout << \"# Burn-ins = \" << num_burn*num_thin << \". # MCMC Updates = \" << num_mcmc*num_thin << \". # thin = \" << num_thin << \".  RND SEED = \" << seed << \".\" << endl ; //\n    cout << \"# Threads = \" << num_thread << endl << endl;\n}\n\nint main(int argc, char* argv[])\n{\n    time_t start = time(NULL);\n\n    cout << std::fixed << setprecision(4);\n    srand(time(NULL));\n\n    // load the program parameters\n    LoadParams(argc, argv);\n\n    // check output path\n    if(! DirectoryExists(output_path))\n    {\n    \tcout << \"output path doesn't exist or empty!\" << endl;\n    \treturn 1;\n    }\n    \n    // load the phylogenetic profile\n    PhyloProf profile = LoadPhyloProfiles(align_path,segment_path);\n    // init and display the running parameters\n    DispParams(profile, seed);\n\n    PhyloTree_theta tree2;\n    if(tree_coal_unit !=\"\"){\n        tree2 = LoadPhyloTree_theta(tree_coal_unit);\n    }else{\n        cout<<\"please input a phylogengy with branch length in coalescent unit.\"<<endl;\n        return 1;\n    } \n\n    // load the phylogenetic tree\n    PhyloTree phytree = LoadPhyloTree(phytree_path); //Han: .subs_rate contains Q\n\n    //get thetas\n    double theta_cum=0;\n    int count_cum=0;\n    int N = phytree.nodes_names.size();\n    vector<int> pos_cum=vector<int> (N,0);\n    for(int i=0; i<(N-1); i++){\n        if(phytree.nodes_names[i]!=tree2.nodes_names[i]){\n            cout<<\"i=\"<<i<<\". tree1_name=\"<<phytree.nodes_names[i]<<\", tree2_name=\"<<tree2.nodes_names[i]<<endl;\n            cerr<<\"two trees do not have the same topology\"<<endl;\n            exit(1);\n        }else{\n            if(i<phytree.S){\n                phytree.thetas[i]=0;\n            }else{\n                //cout<<\"\\ni=\"<<i<<\": \";\n                if((tree2.distances[i]!=1.0) && (tree2.distances[i]!= 7.0) && (tree2.distances[i]!= 0)){\n                    phytree.thetas[i]=2*phytree.distances[i]/tree2.distances[i];\n                    if(phytree.thetas[i]>= theta_cutoff){\n                        pos_cum[i]=1;\n                    }else{\n                        theta_cum+=phytree.thetas[i];\n                        count_cum+=1;\n                    }\n                }else{\n                    pos_cum[i]=1;\n                }\n            }\n        }\n    }\n    double theta_aver=theta_cum/count_cum;\n    pos_cum[N-1]=1;\n    for(int i=phytree.S; i<N; i++){\n        if(pos_cum[i]==1) phytree.thetas[i]=theta_aver;\n        //cout<<\"node \"<<phytree.nodes_names[i]<<\" theta=\"<<phytree.thetas[i]<<endl;\n    }\n\n    // create and init the BPP object\n    //BPP bpp(0, profile, phytree, output_path, targetspecies, outgroup, conserve_prop, conservegroup, ratio0, ratio1, ropt, cub, nlb, nprior_a, nprior_b, cprior_a, cprior_b, seed, seed2, prep_grate, prep_lrate, prep_lrate2, prior_grate_a, prior_grate_b,prior_lrate_a, prior_lrate_b,prior_lrate2_a, prior_lrate2_b,  indel, indel2, missing_thres, sample_indel,prior_dir_par, br_sample_cutoff);\n    BPP bpp(0, profile, phytree, output_path, targetspecies, outgroup, conserve_prop, conservegroup, ratio0, ratio1, ropt, cub, nlb, nprior_a, nprior_b, cprior_a, cprior_b, seed, seed2, prep_grate, prep_lrate, prep_lrate2, prior_grate_a, prior_grate_b,prior_lrate_a, prior_lrate_b,prior_lrate2_a, prior_lrate2_b,  indel, indel2, missing_thres, sample_indel,prior_dir_par, br_sample_cutoff, deepcoal_species);\n\n    //initialize the MCMC sampling\n    bpp.InitMCMC(num_burn, num_mcmc, num_thin);\n    \n    output_path = output_path + \"/\" + result_prefix ;\n    output_path2 = output_path;\n    string outpath_Z0 = output_path + \"_rate_postZ_M\" +to_string(0) +\".txt\";\n    string outpath_Z1 = output_path + \"_rate_postZ_M\" +to_string(1) +\".txt\";\n    string outpath_Z2 = output_path + \"_rate_postZ_M\" +to_string(2) +\".txt\";\n\n    string outpath_hyper = output_path+\"_hyper.txt\";\n    ofstream out_hyper(outpath_hyper.c_str());\n    out_hyper << \"iter\\tnprior_a\\tnprior_b\\tcprior_a\\tcprior_b\\tprior_l_a\\tprior_l_b\\tprior_g_a\\tprior_g_b\\n\";\n    out_hyper << 0 << \"\\t\"<< nprior_a<< \"\\t\"<< nprior_b <<\"\\t\"<< cprior_a << \"\\t\"<< cprior_b << \"\\t\"<< prior_lrate_a << \"\\t\"<< prior_lrate_b << \"\\t\"<< prior_grate_a << \"\\t\"<< prior_grate_b <<endl;\n\n    ofstream out_lik;\n    if(sample_hyper) {\n        string outpath_elem = output_path+ \"_elem_lik.txt\";\n        out_lik.open(outpath_elem.c_str());\n        out_lik.precision(8);\n        out_lik << \"No.\\tID\\tloglik_Full\\tloglik_Max\"<<endl;\n    }\n\n    ofstream out_Z0(outpath_Z0.c_str());\n    ofstream out_Z1(outpath_Z1.c_str());\n    ofstream out_Z2(outpath_Z2.c_str());\n\n    // output species name\n    string species_name = output_path+\"_species_names.txt\";\n    ofstream out_species(species_name.c_str());\n\n    out_Z0 << \"No.\\tn_rate\\tc_rate\\tg_rate\\tl_rate\\tl2_rate\"; out_Z1 << \"No.\\tn_rate\\tc_rate\\tg_rate\\tl_rate\\tl2_rate\"; out_Z2 << \"No.\\tn_rate\\tc_rate\\tg_rate\\tl_rate\\tl2_rate\";\n    for(int s=0; s<bpp.N;s++){\n         for(int k=0;k<4;k++){\n            out_Z0 <<\"\\t\"<<bpp.nodes_names[s]<<\"_\"<<k;\n            out_Z1 <<\"\\t\"<<bpp.nodes_names[s]<<\"_\"<<k;\n            out_Z2 <<\"\\t\"<<bpp.nodes_names[s]<<\"_\"<<k;\n         }\n         out_species << bpp.nodes_names[s] << endl;\n    }\n\tout_Z0 <<endl; out_Z1 <<endl; out_Z2 <<endl;\n\n    out_species.close();\n    \n    // output tree\n    outpath_Z0 = output_path + \"_tree_M\" +to_string(0) +\".txt\";\n    outpath_Z1 = output_path + \"_tree_M\" +to_string(1) +\".txt\";\n    outpath_Z2 = output_path + \"_tree_M\" +to_string(2) +\".txt\";\n    \n    ofstream out_tree0(outpath_Z0.c_str());\n    ofstream out_tree1(outpath_Z1.c_str());\n    ofstream out_tree2(outpath_Z2.c_str());\n    \n    out_tree0 << \"No.\\tprop\\tgenetree\\n\";\n    out_tree1 << \"No.\\tprop\\tgenetree\\n\";\n    out_tree2 << \"No.\\tprop\\tgenetree\\n\";\n\n    double lrate_prop = 0.5, grate_prop = 0.5;\n\n    vector<int> ids;\n    if(id_path==\"\")\n    {\n        if(batch==-1)\n        {\n          for(int c =0;c<500;c++) //bpp.C,\n          {\n            ids.push_back(c);\n          }\n        }else{\n          int temp = ceil(bpp.C/3);\n          for(int c =batch*temp ;c< (batch+1)*temp;c++)\n          {\n            if(c >= bpp.C) break;\n            ids.push_back(c);\n          }\n\n        }\n\n    }else{\n        ifstream in_params(id_path.c_str());\n        if (!in_params)\n        {\n            cerr << \"Cannot open the id file: \" << id_path.c_str() << endl;\n            exit(1);\n        }\n        while(!in_params.eof())\n        {\n            const int BUFF_SIZE = 1024;\n            char line_buff[BUFF_SIZE];\n            in_params.getline(line_buff, BUFF_SIZE);\n            istringstream line_stream(line_buff);\n            string tmp; line_stream >> tmp;\n            tmp = strutils::trim(tmp);\n            if(tmp==\"\") continue;\n            ids.push_back(atoi(tmp.c_str()));\n\n        }\n\n    }\n\n    cout << ids.size() << \" elements to be computed\" << endl;\n\n    if(sample_hyper)\n    {\n        for(int iter  =0; iter<num_chain; iter++)\n        {\n            cout << \"Running MCMC chain \" << iter +1 << \" ...\" << endl;\n            // Gibbs sampling\n            #pragma omp parallel for schedule (guided) num_threads(num_thread)\n            for(std::size_t i = 0; i < ids.size(); i++ )\n            {\n                int c = ids[i];\n                bool filter = false;\n\n                try{\n                    BPP_C bppc(c, profile, bpp, gapchar, missing_thres, filter, verbose, consToMis, block, prune, revgap, min_length);  // for individual element\n                    if(filter) {\n                        if(verbose) cerr << \"filter: \"<< c <<endl;\n                        continue;\n                    }\n\n                    bppc.initMCMC(0,5,bpp,1,prune);\n                    bppc.Gibbs(0, 4, bpp,out_Z2,output_path,output_path2,1, true, sample_hyper, lrate_prop, grate_prop, false);  // Gibbs run to get Z for each element\n\n                    if(bppc.verbose || bppc.failure) bppc.Output_sampling(iter, output_path2, bpp, 2);\n                    bppc.Output_init(output_path,output_path2,bpp,out_Z2, out_tree2, bppc.verbose); //sort rates!!\n\n                }catch (exception& e){\n                    cout << c << \" Standard exception: \" << e.what() << endl;\n                }\n            }\n            bpp.sample_hyperparam(iter, ids, out_hyper);\n            bpp.Output_init0(profile,out_lik, ids);\n\n        }\n    }else if(simulate)\n    {\n        for(std::size_t i = 0; i < ids.size(); i++ )\n        {\n            int c = ids[i];\n            bool filter = false;\n            try{\n                // accelerate in target species\n                BPP_C bppc(c, profile, bpp, gapchar, missing_thres, filter, verbose, consToMis, block, prune, revgap, min_length);  // for individual element\n                bppc.simulate(bpp, profile, gapchar,prune);\n            }catch (exception& e){\n                cout << c << \" Standard exception: \" << e.what() << endl;\n            }\n        }\n\n        //write out simulate sequence\n        bpp.Output_simu(profile, output_path, ids.size());        \n    }else{\n        // Gibbs sampling\n        #pragma omp parallel for schedule (guided) num_threads(num_thread)\n        for(std::size_t i = 0; i < ids.size(); i++ ) //\n        {\n            int c = ids[i];\n            bool filter = false;\n            \n            try{\n               \n                BPP_C bppc(c, profile, bpp, gapchar, missing_thres, filter, verbose, verboseGT, consToMis, block, prune, revgap, min_length);  // for individual element\n                cout<<\"element \"<<to_string(c)<<\", number of base pair=\"<<to_string(bppc.GG)<<endl;\n                if(filter) {\n                  if(verbose) cerr << \"filter: \"<< c <<endl;\n                  continue;\n                }\n\n                int tot = 0;\n                if(bppc.idblk_count==0){\n                    double nblk=(double)(bppc.GG - 15)/block;\n                    int nblk2=(bppc.GG - 15)/block;\n                    if( (nblk- nblk2)< ((double) 1.0/3.0)){\n                        tot=nblk2;\n                    }else{\n                        tot=nblk2+1;\n                    }\n                    //tot=ceil((double)(bppc.GG - 15)/block);  //first bp length is always 15: len={0,15}. If change 15, change in Gibbs as well.\n                    //have to make sure 15<=block. So better change 15 to block\n                }else{\n                    double nblk = (double)(bppc.GG - bppc.idblk_count-15)/block;\n                    int nblk2 = (bppc.GG - bppc.idblk_count-15)/block;\n                    if((nblk- nblk2)< ((double) 1.0/3.0)){\n                        tot = 1+nblk2;\n                    }else{\n                        tot = 2+nblk2;\n                    }\n                    //tot=1+ceil((double)(bppc.GG - bppc.idblk_count-15)/block); \n                }\n                // int tot=ceil((double)(bppc.GG - 15)/block); \n                //cout<<\"tot =\"<<tot<<endl;\n\n                //null model\n                cout<<\"start null model\\n\";\n                for (int iter = 0; iter <= tot; iter++)\n                {\n                    // cout<<\"start initMCMC\"<<endl;\n                    bppc.initMCMC(iter, tot, bpp, 0, prune, false);\n\n                    // cout<<\"start Gibbs\"<<endl;\n                    bppc.Gibbs(iter, tot, bpp, out_Z0, output_path, output_path2, 0, true, sample_hyper, lrate_prop, grate_prop, WL); // Gibbs run to get Z for each element\n                    if (bppc.verbose || bppc.failure)\n                    {\n                        bppc.Output_sampling(iter, output_path2, bpp, 0);\n                        bppc.Output_tree(iter, output_path2, bpp, 0);\n                    }\n                }\n                bppc.Output_init(output_path,output_path2,bpp,out_Z0, out_tree0, bppc.verbose); //sort rates!!, posterior median of nrate and crate; posterior mean of Z\n\n                // //res model\n                cout<<\"start restricted model\\n\";\n                for (int iter = 0; iter <= tot; iter++)\n                {\n                    bppc.initMCMC(iter, tot, bpp, 2, prune, false);\n                    // cout<<\"start Gibbs\"<<endl;\n                    bppc.Gibbs(iter, tot, bpp, out_Z2, output_path, output_path2, 2, true, sample_hyper, lrate_prop, grate_prop, WL);\n                    if (bppc.verbose || bppc.failure)\n                    {\n                        bppc.Output_sampling(iter, output_path2, bpp, 1);\n                        bppc.Output_tree(iter, output_path2, bpp, 1);\n                    }\n                }\n                bppc.Output_init(output_path,output_path2,bpp,out_Z1, out_tree1, bppc.verbose);\n\n                // full model\n                cout<<\"start full model\\n\";\n                for (int iter = 0; iter <= tot; iter++)\n                {\n                    bppc.initMCMC(iter, tot, bpp, 1, prune, false); // not constrain log_prob_back\n                    bppc.Gibbs(iter, tot, bpp, out_Z2, output_path, output_path2, 1, true, sample_hyper, lrate_prop, grate_prop, WL);\n                    if (bppc.verbose || bppc.failure)\n                    {\n                        bppc.Output_sampling(iter, output_path2, bpp, 2);\n                        bppc.Output_tree(iter, output_path2, bpp, 2);\n                    }\n                }\n                bppc.Output_init(output_path,output_path2,bpp,out_Z2, out_tree2, bppc.verbose);\n                \n                cout << c << \"\\t\" << bpp.log_liks_WL[0][c] <<\"\\t\" <<  bpp.log_liks_WL[2][c] <<\"\\t\" <<  bpp.log_liks_WL[1][c] <<endl;\n                cout<<\"\\t\" << bpp.log_liks_Z[0][c] << \"\\t\" << bpp.log_liks_Z[2][c]<<\"\\t\" << bpp.log_liks_Z[1][c] << endl;\n\n            }catch (exception& e){\n              cout << c << \" Standard exception: \" << e.what() << endl;\n            }\n      }\n\n      bpp.Output_init(profile,output_path, ids);\n    }\n\n    out_Z0.close();\n    out_Z1.close();\n    out_Z2.close();\n    out_hyper.close();\n    out_lik.close();\n    out_tree0.close();\n    out_tree1.close();\n    out_tree2.close();\n\n    cout << endl << endl << \"time used:  \" << (time(NULL)-start)/60 << \" min.\" << endl << endl;\n    return 0;\n}\n", "meta": {"hexsha": "44039618e8be8759a1a52ee390c3d4767f3da774", "size": 22695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PhyloAcc-GT/main.cpp", "max_stars_repo_name": "gwct/PhyloAcc", "max_stars_repo_head_hexsha": "089162e2bce5a17b95d71add074bf51bccc8a266", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PhyloAcc-GT/main.cpp", "max_issues_repo_name": "gwct/PhyloAcc", "max_issues_repo_head_hexsha": "089162e2bce5a17b95d71add074bf51bccc8a266", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PhyloAcc-GT/main.cpp", "max_forks_repo_name": "gwct/PhyloAcc", "max_forks_repo_head_hexsha": "089162e2bce5a17b95d71add074bf51bccc8a266", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7828200972, "max_line_length": 408, "alphanum_fraction": 0.5542630535, "num_tokens": 6049, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.22719058138093468}}
{"text": "/*\n * This is part of the fl library, a C++ Bayesian filtering library\n * (https://github.com/filtering-library)\n *\n * Copyright (c) 2015 Max Planck Society,\n * \t\t\t\t Autonomous Motion Department,\n * \t\t\t     Institute for Intelligent Systems\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n */\n\n/**\n * \\file multi_sensor_sigma_point_update_policy.hpp\n * \\date August 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n */\n\n#pragma once\n\n#include <Eigen/Dense>\n\n#include <fl/util/meta.hpp>\n#include <fl/util/types.hpp>\n#include <fl/util/traits.hpp>\n#include <fl/util/descriptor.hpp>\n#include <fl/model/sensor/joint_sensor_iid.hpp>\n#include <fl/filter/gaussian/transform/point_set.hpp>\n#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>\n\nnamespace fl\n{\n// Forward declarations\ntemplate <typename...>\nclass MultiSensorSigmaPointUpdatePolizzle;\n\n/**\n * \\internal\n */\ntemplate <typename SigmaPointQuadrature, typename NonJoinSensor>\nclass MultiSensorSigmaPointUpdatePolizzle<SigmaPointQuadrature,\n                                          NonJoinSensor>\n{\n    static_assert(\n        std::is_base_of<internal::JointSensorIidType,\n                        NonJoinSensor>::value,\n        \"\\n\\n\\n\"\n        \"====================================================================\\n\"\n        \"= Static Assert: You are using the wrong observation model type    =\\n\"\n        \"====================================================================\\n\"\n        \"  Observation model type must be a JointSensor<...>.      \\n\"\n        \"  For single observation model, use the regular Gaussian filter     \\n\"\n        \"  or the regular SigmaPointUpdatePolicy if you are specifying       \\n\"\n        \"  the update policy explicitly fo the GaussianFilter.               \\n\"\n        \"====================================================================\"\n        \"\\n\");\n};\n\ntemplate <typename SigmaPointQuadrature, typename MultipleOfLocalSensor>\nclass MultiSensorSigmaPointUpdatePolizzle<\n    SigmaPointQuadrature,\n    JointSensor<MultipleOfLocalSensor>>\n    : public MultiSensorSigmaPointUpdatePolizzle<\n          SigmaPointQuadrature,\n          NonAdditive<JointSensor<MultipleOfLocalSensor>>>\n{\n};\n\ntemplate <typename SigmaPointQuadrature, typename MultipleOfLocalSensor>\nclass MultiSensorSigmaPointUpdatePolizzle<\n    SigmaPointQuadrature,\n    NonAdditive<JointSensor<MultipleOfLocalSensor>>>\n    : public Descriptor\n{\npublic:\n    typedef JointSensor<MultipleOfLocalSensor> JointModel;\n    typedef typename MultipleOfLocalSensor::Type FeatureSensor;\n    typedef typename FeatureSensor::EmbeddedSensor BodyTailModel;\n    typedef typename BodyTailModel::BodySensor BodyModel;\n    typedef typename BodyTailModel::TailSensor TailModel;\n\n    typedef typename JointModel::State State;\n    typedef typename JointModel::Obsrv Obsrv;\n    typedef typename JointModel::Noise Noise;\n\n    typedef typename Traits<JointModel>::LocalObsrv LocalFeature;\n    typedef Vector1d LocalObsrvNoise;\n\n    template <typename Belief>\n    void operator()(JointModel& obsrv_function,\n                    const SigmaPointQuadrature& quadrature,\n                    const Belief& prior_belief,\n                    const Obsrv& y,\n                    Belief& posterior_belief)\n    {\n        auto& feature_model = obsrv_function.local_sensor();\n        auto& body_tail_model = feature_model.embedded_sensor();\n\n        /* ------------------------------------------ */\n        /* - Determine the number of quadrature     - */\n        /* - points needed for the given quadrature - */\n        /* - in conjunction with the joint Gaussian - */\n        /* - p(State, LocalObsrvNoise)              - */\n        /* ------------------------------------------ */\n        enum : signed int\n        {\n            NumberOfPoints = SigmaPointQuadrature::number_of_points(\n                JoinSizes<SizeOf<State>::Value,\n                          SizeOf<LocalObsrvNoise>::Value>::Size)\n        };\n\n        /* ------------------------------------------ */\n        /* - PointSets                              - */\n        /* - [p_X, p_Q] ~ p(State, LocalObsrvNoise) - */\n        /* ------------------------------------------ */\n        PointSet<State, NumberOfPoints> p_X;\n        PointSet<LocalObsrvNoise, NumberOfPoints> p_R;\n\n        /* ------------------------------------------ */\n        /* - Transform p(State, LocalObsrvNoise) to - */\n        /* - point sets [p_X, p_Q]                  - */\n        /* ------------------------------------------ */\n        quadrature.transform_to_points(\n            prior_belief,\n            Gaussian<LocalObsrvNoise>(feature_model.noise_dimension()),\n            p_X,\n            p_R);\n\n        auto mu_x = p_X.mean();\n        auto X = p_X.centered_points();\n\n        auto W = p_X.covariance_weights_vector().asDiagonal();\n        auto c_xx = (X * W * X.transpose()).eval();\n        auto c_xx_inv = c_xx.inverse().eval();\n\n        auto C = c_xx_inv;\n        auto D = State();\n        D.setZero(mu_x.size());\n\n        const int sensor_count = obsrv_function.count_local_models();\n        const int dim_y = y.size() / sensor_count;\n\n        auto h_body = [&](const State& x, const typename BodyModel::Noise& w)\n        {\n            return feature_model.feature_obsrv(\n                body_tail_model.body_model().observation(x, w));\n        };\n        auto h_tail = [&](const State& x, const typename TailModel::Noise& w)\n        {\n            return feature_model.feature_obsrv(\n                body_tail_model.tail_model().observation(x, w));\n        };\n        PointSet<LocalFeature, NumberOfPoints> p_Y_body;\n        PointSet<LocalFeature, NumberOfPoints> p_Y_tail;\n\n\n        for (int i = 0; i < sensor_count; ++i)\n        {\n            // validate sensor value, i.e. make sure it is finite\n            if (!is_valid(y, i * dim_y, i * dim_y + dim_y)) continue;\n\n            feature_model.id(i);\n\n            /* ------------------------------------------ */\n            /* - Integrate body                         - */\n            /* ------------------------------------------ */\n\n            quadrature.propagate_points(h_body, p_X, p_R, p_Y_body);\n            auto mu_y_body = p_Y_body.mean();\n\n            // validate sensor value, i.e. make sure it is finite\n            if (!is_valid(mu_y_body, 0, dim_y)) continue;\n\n            auto Y_body = p_Y_body.centered_points();\n            auto c_yy_body = (Y_body * W * Y_body.transpose()).eval();\n            auto c_xy_body = (X * W * Y_body.transpose()).eval();\n\n            /* ------------------------------------------ */\n            /* - Integrate tail                         - */\n            /* ------------------------------------------ */\n            quadrature.propagate_points(h_tail, p_X, p_R, p_Y_tail);\n            auto mu_y_tail = p_Y_tail.mean();\n            auto Y_tail = p_Y_tail.centered_points();\n            auto c_yy_tail = (Y_tail * W * Y_tail.transpose()).eval();\n            auto c_xy_tail = (X * W * Y_tail.transpose()).eval();\n\n            /* ------------------------------------------ */\n            /* - Fuse and center                        - */\n            /* ------------------------------------------ */\n            auto w = body_tail_model.tail_weight();\n            auto mu_y = ((1.0 - w) * mu_y_body + w * mu_y_tail).eval();\n\n            // non centered moments\n            auto m_yy_body =\n                (c_yy_body + mu_y_body * mu_y_body.transpose()).eval();\n            auto m_yy_tail =\n                (c_yy_tail + mu_y_tail * mu_y_tail.transpose()).eval();\n            auto m_yy = ((1.0 - w) * m_yy_body + w * m_yy_tail).eval();\n\n            // center\n            auto c_yy = (m_yy - mu_y * mu_y.transpose()).eval();\n            auto c_xy = ((1.0 - w) * c_xy_body + w * c_xy_tail).eval();\n\n            auto c_yx = c_xy.transpose().eval();\n            auto A_i = (c_yx * c_xx_inv).eval();\n            auto c_yy_given_x = (c_yy - c_yx * c_xx_inv * c_xy).eval();\n            auto innovation = (y.middleRows(i * dim_y, dim_y) - mu_y).eval();\n\n            C += A_i.transpose() * solve(c_yy_given_x, A_i);\n            D += A_i.transpose() * solve(c_yy_given_x, innovation);\n        }\n\n        /* ------------------------------------------ */\n        /* - Update belief according to PAPER REF   - */\n        /* ------------------------------------------ */\n        posterior_belief.dimension(prior_belief.dimension());\n        posterior_belief.covariance(C.inverse());\n        posterior_belief.mean(mu_x + posterior_belief.covariance() * D);\n    }\n\n    virtual std::string name() const\n    {\n        return \"MultiSensorSigmaPointUpdatePolizzle<\" +\n               this->list_arguments(\"SigmaPointQuadrature\",\n                                    \"NonAdditive<SensorFunction>\") +\n               \">\";\n    }\n\n    virtual std::string description() const\n    {\n        return \"Multi-Sensor Sigma Point based filter update policy \"\n               \"for joint observation model of multiple local observation \"\n               \"models with non-additive noise.\";\n    }\n\nprivate:\n    /**\n     * \\brief Checks whether all vector components within the range (start, end)\n     *        are finiate, i.e. not NAN nor Inf.\n     */\n    template <typename Vector>\n    bool is_valid(Vector&& vector, int start, int end) const\n    {\n        for (int k = start; k < end; ++k)\n        {\n            if (!std::isfinite(vector(k))) return false;\n        }\n\n        return true;\n    }\n};\n}\n", "meta": {"hexsha": "ab0793f543500661bd5243a7daa418773030f6ce", "size": 9558, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/fl/filter/gaussian/update_policy/multi_sensor_sigma_point_update_polizzle.hpp", "max_stars_repo_name": "aeolusbot-tommyliu/fl", "max_stars_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-07-03T06:53:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-15T20:55:12.000Z", "max_issues_repo_path": "include/fl/filter/gaussian/update_policy/multi_sensor_sigma_point_update_polizzle.hpp", "max_issues_repo_name": "aeolusbot-tommyliu/fl", "max_issues_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-02-20T12:48:17.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-18T08:45:13.000Z", "max_forks_repo_path": "include/fl/filter/gaussian/update_policy/multi_sensor_sigma_point_update_polizzle.hpp", "max_forks_repo_name": "aeolusbot-tommyliu/fl", "max_forks_repo_head_hexsha": "a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-02-20T11:34:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-15T20:55:13.000Z", "avg_line_length": 37.6299212598, "max_line_length": 80, "alphanum_fraction": 0.5348399247, "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631840431539, "lm_q2_score": 0.3738758157951908, "lm_q1q2_score": 0.22719056866283732}}
{"text": "// This file is part of DM-HEOM (https://github.com/noma/dm-heom)\n//\n// Copyright (c) 2015-2019 Matthias Noack, Zuse Institute Berlin\n//\n// Licensed under the 3-clause BSD License, see accompanying LICENSE,\n// CONTRIBUTORS.md, and README.md for further information.\n\n#include <iostream>\n#include <sstream>\n\n#include <boost/format.hpp>\n#include <boost/numeric/ublas/matrix.hpp>\n#include <noma/num/meta_stepper.hpp>\n\n#include \"heom/command_line.hpp\"\n#include \"heom/common.hpp\"\n#include \"heom/constants.hpp\"\n#include \"heom/dipole_matrix.hpp\"\n#include \"heom/dipole_pseudo_pathway.hpp\"\n#include \"heom/e_field.hpp\"\n#include \"heom/handle_main_exception.hpp\"\n#include \"heom/hierarchy_graph.hpp\"\n#include \"heom/hierarchy_mask.hpp\"\n#include \"heom/hierarchy_norm.hpp\"\n#include \"heom/instance.hpp\"\n#include \"heom/make_file_observer_list.hpp\"\n#include \"heom/population_dynamics_solver.hpp\"\n#include \"heom/ocl_config.hpp\"\n#include \"heom/ode.hpp\"\n#include \"heom/population_dynamics_solver.hpp\"\n#include \"heom/sites_to_states.hpp\"\n#include \"heom/transient_absorption_config.hpp\"\n\nnamespace bmt = ::heom::bmt;\nnamespace num = ::heom::num;\nnamespace ocl = ::heom::ocl;\nusing heom::int_t;\nusing heom::real_t;\nusing heom::real_format;\nusing heom::complex_t;\nusing heom::default_delimiter;\n\n\nint main(int argc, char* argv[])\n{\n\t// start runtime measurement\n\tbmt::timer app_timer;\n\n\t// output compile time configuration\n\tstd::cout << \"-------------------- Compile-Time Configuration ------------\" << std::endl;\n\theom::write_compile_config(std::cout);\n\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\t// command line parsing\n\t// usage: app_* <ocl_config> <heom_config> [partition_file]\n\tstd::string ocl_config_file = \"ocl_config.cfg\";\n\tstd::string heom_config_file = \"transient_absorption.cfg\";\n\n\tif (argc >= 2)\n\t\tocl_config_file = argv[1];\n\tif (argc >= 3)\n\t\theom_config_file = argv[2];\n\n\tstd::exception_ptr eptr;\n\ttry {\n\t\t// command line parsing\n\t\theom::command_line command_line { argc, argv };\n\n\t\tstd::cout << \"Parsing OpenCL configuration from file: \" << command_line.ocl_config_filename() << std::endl;\n\t\theom::ocl_config ocl_config(command_line.ocl_config_filename());\n\t\tstd::cout << \"Parsing HEOM configuration from file: \" << command_line.heom_config_filename() << std::endl;\n\t\theom::transient_absorption_config heom_config(command_line.heom_config_filename());\n\n\t\theom::hierarchy_graph complete_graph(heom_config.baths_number(), heom_config.baths_matsubaras(), heom_config.system_ado_depth());\n\n\t\tusing stepper_t = num::meta_stepper; // uses solver_stepper_type from config\n\t\tusing solver_t = heom::population_dynamics_solver<heom::ode, stepper_t, heom::hierarchy_norm>;\n\n\t\t// prepare output file (so we run into possible file errors before starting the computation)\n\t\tauto& observation_filename = heom_config.observations().get().front().get().second; // filename of first specified observation, guaranteed to exist by config checks\n\t\tstd::ofstream observation_file(observation_filename);\n\t\tif (observation_file.fail())\n\t\t\tthrow std::runtime_error(\"Error: could not open output file: \" + observation_filename);\n\n\t\t// transient absorption computation over all combinations of dipole matrices and phases\n\t\tconst size_t num_dipole_matrices = heom_config.dipole_tensor_prefactors().size();\n\t\tconst size_t num_pulse_phases = heom_config.probe_pulse_phases().size();\n\t\tconst size_t num_experiments = num_dipole_matrices * num_pulse_phases;\n\n\t\t// solver iterations and steps\n\t\tconst int_t iterations = heom_config.solver_steps() / heom_config.program_observe_steps();\n\t\tconst int_t steps_per_iteration = heom_config.program_observe_steps();\n\t\tconst int_t total_steps = iterations * heom_config.program_observe_steps();\n\n\t\t// output data structure for averaged traces\n\t\tconst int_t num_observations = iterations + 1;\n\t\tstd::vector<heom::matrix_trace_observation_view> observations(num_observations);\n\t\t// e_field is needed once, and is the same across runs\n\t\tstd::vector<complex_t> e_field_observations(num_observations);\n\n\t\t// transient absorption pseudo pathway\n\t\tconst auto& pathway_spec = heom_config.spectra_include_esa() ? heom::dipole_pseudo_pathway_esa_spec : heom::dipole_pseudo_pathway_wgs_spec;\n\t\tconst auto sts_mode = pathway_spec.sites_to_states_mode();\n\n\t\t// for progress estimate\n\t\tconst size_t solver_runs = num_dipole_matrices * num_pulse_phases;\n\t\tsize_t solver_run = 0;\n\n\t\t// iterate over all dipoles and compute population dynamics\n\t\tfor (size_t tensor_index = 0; tensor_index < num_dipole_matrices; ++tensor_index) {\n\t\t\t// loop over all pulse phases\n\t\t\tfor (size_t phase_index = 0; phase_index < num_pulse_phases; ++phase_index)\n\t\t\t{\n\t\t\t\tconst bool first_solver_run = tensor_index == 0 && phase_index == 0; // only observe first solver run\n\n\t\t\t\theom::instance heom_instance(heom_config, sts_mode, complete_graph);\n\t\t\t\theom_instance.set_hierarchy_top(); // NOTE: hierarchy top is initialised to zero with first element being complex_t(1.0,0.0) here\n\n\t\t\t\t// OpenCL range\n\t\t\t\tocl::nd_range range {\n\t\t\t\t\t{}, // offset\n\t\t\t\t\t{1, static_cast<std::uint64_t>(heom_instance.matrices())}, // global size\n\t\t\t\t\t{1, 1} // local size\n\t\t\t\t};\n\n\t\t\t\t// create a solver from configuration and instance\n\t\t\t\tsolver_t solver(ocl_config, range, heom_config, heom_instance);\n\t\t\t\tstd::cout << \"-------------------- OpenCL Runtime Configuration ----------\" << std::endl;\n\t\t\t\tsolver.write_ocl_runtime_config(std::cout);\n\t\t\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\t\t\t\t++solver_run; // for progress estimate\n\n\t\t\t\t// compute dipole matrices\n\t\t\t\tauto get_dipole_matrix = [&](size_t spec_index) {\n\t\t\t\t\treturn heom::get_dipole_matrix_for_pathway(pathway_spec, spec_index, heom_config.system_sites(), heom_config, tensor_index);\n\t\t\t\t};\n\t\t\t\tauto dipole_matrix_minus = get_dipole_matrix(0);\n\t\t\t\tauto dipole_matrix_plus = get_dipole_matrix(1);\n\t\t\t\t// TODO: check scaling\n\t\t\t\tdipole_matrix_minus.scale(heom::get_dipole_tensor_prefactor(pathway_spec, heom_config, tensor_index));\n\n\t\t\t\t// TODO: remove this scaling, i.e. fix unit of dipole matrices across all applications, maybe use factor during initialisation of config object or change input file format\n\t\t\t\t//       scaling dipole strengths in dipole_config_entries does work for this app, but messes with the result of others (tested with linear_absorption)\n\t\t\t\tdipole_matrix_minus.scale(heom::constants::debye_to_coulomb_meter);\n\t\t\t\tdipole_matrix_plus.scale(heom::constants::debye_to_coulomb_meter);\n//std::cout << dipole_matrix_minus << std::endl << std::endl;\n//std::cout << dipole_matrix_plus << std::endl << std::endl;\n\n\t\t\t\t// TODO: check if this is really plus and not prescaled... prefactor might be one in config (?) vs. other apps\n\t\t\t\t// setup observer with pre-scaled dipole matrix\n\t\t\t\theom::matrix_trace_observer<solver_t> trace_observer(complete_graph, solver, dipole_matrix_plus.data()); // D+ from left via observer\n\n\t\t\t\t// extract hamiltonian as complex_matrix_t for the e_field\n\t\t\t\theom::complex_matrix_t hamiltonian(dipole_matrix_plus.rows(), dipole_matrix_plus.cols());\n\t\t\t\tfor(size_t i = 0; i < hamiltonian.rows(); ++i) {\n\t\t\t\t\tfor(size_t j = 0; j < hamiltonian.cols(); ++j) {\n\t\t\t\t\t\tconst size_t real_index = 2 * (i * hamiltonian.rows() + j);\n\t\t\t\t\t\tconst size_t imag_index = real_index + 1;\n\t\t\t\t\t\thamiltonian.at(i, j) = heom::complex_t(heom_instance.hamiltonian()[real_index], heom_instance.hamiltonian()[imag_index]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// add e-field pre-evaluation action to the ODE for transient spectra computation\n\t\t\t\tauto e_field = heom::e_field<decltype(heom_config), heom::ode>(heom_config, phase_index, dipole_matrix_plus, dipole_matrix_minus, hamiltonian);\n\t\t\t\tsolver.ode().clear_pre_evaluate_actions();\n\t\t\t\tsolver.ode().add_pre_evaluate_action(e_field);\n\n\t\t\t\t// with create_hierarchy_mask we create mask corresponding to configured filtering strategy, then update solver\n\t\t\t\t// NOTE: .data() returns pointer to mask_t array\n\t\t\t\theom::hierarchy_mask hierarchy_mask = heom::create_hierarchy_mask(heom_config.filtering_strategy(), complete_graph, heom_config.baths_matsubaras(), heom_config.filtering_first_layer());\n\t\t\t\tsolver.update_hierarchy_mask(hierarchy_mask.data());\n\n\t\t\t\tstd::cout << \"-------------------- Hierarchy Mask Counter ----------------\" << std::endl;\n\t\t\t\theom::write_hierarchy_mask_stats(hierarchy_mask, std::cout);\n\t\t\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\t\t\t\t// generate first observation with initial value\n\t\t\t\tobservations[0] += trace_observer.observe_trace(0.0);\n\t\t\t\tif (first_solver_run)\n\t\t\t\t\te_field_observations[0] = e_field.compute_field(0.0);\n\n\t\t\t\t// setup output per propagation output\n\t\t\t\theom::config::obervation_type_list per_propagation_observations;\n\n\t\t\t\t// build single-propagation observation list from config list\n\t\t\t\tfor (auto& pair : heom_config.observations().get()) {\n\t\t\t\t\tauto& obs_type = pair.get().first;\n\t\t\t\t\tauto& filename = pair.get().second;\n\n\t\t\t\t\tif (heom::is_single_propagation_observation(obs_type)) {\n\t\t\t\t\t\tstd::remove_const<std::remove_reference<decltype(pair)>::type>::type new_pair;\n\t\t\t\t\t\tnew_pair.get().first = pair.get().first; // copy observation type\n\n\t\t\t\t\t\tstd::stringstream new_filename;\n\t\t\t\t\t\tsize_t dot_pos = filename.find_first_of('.');\n\t\t\t\t\t\tif (dot_pos != std::string::npos) {\n\t\t\t\t\t\t\tnew_filename << filename.substr(0, dot_pos); // copy everything prior to first dot\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnew_filename << filename; // copy whole filename, in case not dot was found\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnew_filename << \"_d\" << tensor_index << \"_p\" << phase_index; // add create suffix\n\t\t\t\t\t\tif (dot_pos != std::string::npos) {\n\t\t\t\t\t\t\tnew_filename << filename.substr(dot_pos); // copy file ending\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tnew_pair.get().second = new_filename.str(); // set new filename\n\t\t\t\t\t\tper_propagation_observations.get().push_back(new_pair);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\theom::observer_list observer_list = heom::make_file_observer_list(per_propagation_observations, complete_graph, solver);\n\t\t\t\tobserver_list.observe(0.0);\n\n\t\t\t\t// write file header once\n\t\t\t\tif (first_solver_run) {\n\t\t\t\t\ttrace_observer.write_header(observation_file, false);\n\t\t\t\t\tobservation_file << default_delimiter;\n\t\t\t\t\tobservation_file << \"e-field_real\";\n\t\t\t\t\tobservation_file << default_delimiter;\n\t\t\t\t\tobservation_file << \"e-field_imag\";\n\t\t\t\t\tobservation_file << '\\n';\n\t\t\t\t}\n\n\t\t\t\t// propagate system\n\t\t\t\tfor (int_t k = 0; k < iterations; ++k)\n\t\t\t\t{\n\t\t\t\t\t// propagate\n\t\t\t\t\tsolver.step_forward(steps_per_iteration);\n\n\t\t\t\t\t// after propagation:\n\t\t\t\t\tconst auto current_step = (k + 1) * steps_per_iteration;\n\t\t\t\t\tconst real_t current_time = current_step * heom_config.solver_step_size();\n\n\t\t\t\t\t// observe trace of dipole_matrix_minus - rho\n\t\t\t\t\tobservations[k + 1] += trace_observer.observe_trace(current_time);\n\t\t\t\t\tif (first_solver_run)\n\t\t\t\t\t\te_field_observations[k + 1] = e_field.compute_field(current_time);\n\n\t\t\t\t\t// observe single-propagation observation types\n\t\t\t\t\tobserver_list.observe(current_time);\n\n\t\t\t\t\t// update status\n\t\t\t\t\tstd::stringstream status_prefix;\n\t\t\t\t\tstatus_prefix << \"Calculation transient absorption (\"\n\t\t\t\t\t              << \"dipole: \" << tensor_index + 1 << '/' << num_dipole_matrices\n\t\t\t\t\t              << \", \"\n\t\t\t\t\t              << \"phase: \" << phase_index + 1 << '/' << num_pulse_phases\n\t\t\t\t\t              << \"): \";\n\t\t\t\t\theom::write_progress(current_step - 1, total_steps, solver_run, solver_runs, status_prefix.str(), std::cout);\n\t\t\t\t}\n\n\t\t\t\t// write_complex_matrix(result_buffer_top, heom_instance.states(), std::cout);\n\t\t\t\tstd::cout << \"-------------------- Solver Runtime Summary ----------------\" << std::endl;\n\t\t\t\tsolver.write_runtime_summary(std::cout);\n\t\t\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\t\t\t}\n\t\t}\n\n\t\t// write averaged traces, with added columns for e-field\n\t\tauto format = real_format;\n\t\t//for (auto& obs : observations) {\n\t\tfor (int_t i = 0; i < num_observations; ++i) {\n\t\t\tobservations[i].avg(num_experiments);\n\t\t\tobservation_file << observations[i];\n\t\t\tobservation_file << default_delimiter;\n\t\t\tobservation_file << format % e_field_observations[i].real();\n\t\t\tobservation_file << default_delimiter;\n\t\t\tobservation_file << format % e_field_observations[i].imag();\n\t\t\tobservation_file << '\\n';\n\t\t}\n\t\tobservation_file << std::flush; // tell the OS to write to disk\n\n\t} catch (...) {\n\t\teptr = std::current_exception();\n\t}\n\tint ret = heom::handle_main_exception(eptr);\n\n\t// print application runtime\n\tstd::cout << \"main(): application runtime: \" << boost::format(\"%11.2f\") % std::chrono::duration_cast<bmt::seconds>(bmt::duration(app_timer.elapsed())).count() << \" s\" << std::endl;\n\n\treturn ret;\n}\n", "meta": {"hexsha": "4a5b50451d481078022823249445536c659cf25a", "size": 12675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dm-heom/src/app_transient_absorption.cpp", "max_stars_repo_name": "noma/dm-heom", "max_stars_repo_head_hexsha": "85c94f947190064d21bd38544094731113c15412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-07-28T01:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T04:01:36.000Z", "max_issues_repo_path": "dm-heom/src/app_transient_absorption.cpp", "max_issues_repo_name": "noma/dm-heom", "max_issues_repo_head_hexsha": "85c94f947190064d21bd38544094731113c15412", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dm-heom/src/app_transient_absorption.cpp", "max_forks_repo_name": "noma/dm-heom", "max_forks_repo_head_hexsha": "85c94f947190064d21bd38544094731113c15412", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-04T15:20:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T15:16:40.000Z", "avg_line_length": 44.9468085106, "max_line_length": 189, "alphanum_fraction": 0.6998816568, "num_tokens": 3175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22684102821147467}}
{"text": "// Copyright 2016. All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright notice,\n//   this list of conditions and the following disclaimer in the documentation\n//   and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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// Author: ryan.latture@gmail.com (Ryan Latture)\n\n#include \"explicit_system.h\"\n#include <boost/format.hpp>\n#include <fstream>\n\nnamespace explicit_fea {\n\n    ExplicitSystem::ExplicitSystem(Mesh _mesh,\n                                   ForceList _external_forces,\n                                   const ColumnVector& _initial_displacements,\n                                   const ColumnVector& _initial_velocities,\n                                   double _t_0,\n                                   const Options& _options) :\n        mesh(std::move(_mesh)),\n        external_forces(std::move(_external_forces)),\n        displacements_0(_initial_displacements),\n        velocities_0(_initial_velocities),\n        velocities_1(ColumnVector::Zero(_initial_displacements.size())),\n        accelerations_0(ColumnVector::Zero(_initial_displacements.size())),\n        accelerations_1(ColumnVector::Zero(_initial_displacements.size())),\n        forces(ColumnVector::Zero(_initial_displacements.size())),\n        RHS(ColumnVector::Zero(_initial_displacements.size())),\n        t_0(_t_0),\n        dt_0(0.0),\n        options(_options) {\n        if (displacements_0.size() != velocities_0.size())\n            throw std::runtime_error(\"Size of initial velocities and initial displacements are not equal.\");\n        if (displacements_0.size() != mesh.get_global_stiffness_matrix().cols())\n            throw std::runtime_error(\"Size of displacements and velocities does not match the number of columns in the global matrices.\");\n\n        LHS.resize(mesh.get_global_stiffness_matrix().rows(), mesh.get_global_stiffness_matrix().cols());\n        assemble_damping_matrix();\n        apply_bcs(t_0);\n    }\n\n    void ExplicitSystem::Options::load(const rapidjson::Document &config_doc) {\n        if (config_doc.HasMember(\"options\")) {\n            if (config_doc[\"options\"].HasMember(\"beta\")) {\n                if (!config_doc[\"options\"][\"beta\"].IsNumber()) {\n                    throw std::runtime_error(\"beta provided in options configuration is not a number.\");\n                }\n                beta = config_doc[\"options\"][\"beta\"].GetDouble();\n            }\n            if (config_doc[\"options\"].HasMember(\"gamma\")) {\n                if (!config_doc[\"options\"][\"gamma\"].IsNumber()) {\n                    throw std::runtime_error(\"gamma provided in options configuration is not a number.\");\n                }\n                gamma = config_doc[\"options\"][\"gamma\"].GetDouble();\n            }\n            if (config_doc[\"options\"].HasMember(\"damping_beta\")) {\n                if (!config_doc[\"options\"][\"damping_beta\"].IsNumber()) {\n                    throw std::runtime_error(\"damping_beta provided in options configuration is not a number.\");\n                }\n                damping_beta = config_doc[\"options\"][\"damping_beta\"].GetDouble();\n            }\n            if (config_doc[\"options\"].HasMember(\"damping_alpha\")) {\n                if (!config_doc[\"options\"][\"damping_alpha\"].IsNumber()) {\n                    throw std::runtime_error(\"damping_alpha provided in options configuration is not a number.\");\n                }\n                damping_alpha = config_doc[\"options\"][\"damping_alpha\"].GetDouble();\n            }\n        }\n    }\n\n    void ExplicitSystem::update(double dt_1) {\n        double t_1 = t_0 + dt_1;\n        if (!compare.equal(dt_1, dt_0)) {\n            assemble_LHS(dt_1);\n        }\n\n        apply_external_forces(t_1);\n        RHS = forces;\n        RHS.noalias() -= damping_matrix * (velocities_0 + (1.0 - options.gamma) * dt_1 * accelerations_0);\n        RHS.noalias() -= mesh.get_global_stiffness_matrix() * (displacements_0 + dt_1 * velocities_0 + (0.5 - options.beta) * dt_1 * dt_1 * accelerations_0);\n        apply_bcs(t_1);\n\n        accelerations_1 = solver.solve(RHS);\n        velocities_1.noalias() += (1.0 - options.gamma) * dt_1 * accelerations_0 + options.gamma * dt_1 * accelerations_1;\n\n        // advance all current time values to next iteration\n        displacements_0.noalias() += dt_1 * velocities_0 + dt_1 * dt_1 * (0.5 - options.beta) * accelerations_0 + dt_1 * dt_1 * options.beta * accelerations_1;\n        velocities_0 = velocities_1;\n        accelerations_0 = accelerations_1;\n        t_0 = t_1;\n        dt_0 = dt_1;\n    }\n\n\tMesh const& ExplicitSystem::getMesh() const {\n\t\treturn mesh;\n\t}\n\n    ColumnVector const& ExplicitSystem::getDisplacements() const {\n        return displacements_0;\n    }\n\n    ColumnVector ExplicitSystem::getForces() const {\n        ColumnVector out(displacements_0.size());\n        out = mesh.get_global_stiffness_matrix() * displacements_0;\n        out += mesh.get_mass_matrix() * accelerations_0;\n        return out;\n    }\n\n    ColumnVector const& ExplicitSystem::getVelocities() const {\n        return velocities_0;\n    }\n\n    double ExplicitSystem::getTime() const {\n        return t_0;\n    }\n\n    void ExplicitSystem::assemble_damping_matrix() {\n        damping_matrix.resize(mesh.get_global_stiffness_matrix().rows(), mesh.get_global_stiffness_matrix().cols());\n        damping_matrix = options.damping_alpha * mesh.get_mass_matrix() + options.damping_beta * mesh.get_global_stiffness_matrix();\n        damping_matrix.prune(1.e-14);\n        damping_matrix.makeCompressed();\n    }\n\n    void ExplicitSystem::assemble_LHS(double dt){\n        LHS = mesh.get_mass_matrix() + options.gamma * dt * damping_matrix + options.beta * dt * dt * mesh.get_global_stiffness_matrix();\n        LHS.prune(1.e-14);\n        LHS.makeCompressed();\n        solver.compute(LHS);\n    }\n\n    void ExplicitSystem::apply_bcs(double time) {\n        for (BCList::const_iterator it = mesh.get_bcs().begin(); it != mesh.get_bcs().end(); ++it) {\n            RHS[(*it)->global_index] = 0.0;\n            if ((*it)->type == BC::Type::DISPLACEMENT) {\n                displacements_0[(*it)->global_index] = (*it)->get_value(time);\n                velocities_0[(*it)->global_index] = 0.0;\n            } else if ((*it)->type == BC::Type::VELOCITY) {\n                velocities_0[(*it)->global_index] = (*it)->get_value(time);\n            }\n        }\n    }\n\n    void ExplicitSystem::apply_external_forces(double time) {\n        for (ForceList::const_iterator it = external_forces.begin(); it != external_forces.end(); ++it) {\n            forces[(*it)->global_index] = (*it)->get_value(time);\n        }\n    }\n\n} // namespace explicit_fea", "meta": {"hexsha": "c14caebddd45ed1a8ee82fd1c7456f862b055ea0", "size": 7705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/explicit_system.cpp", "max_stars_repo_name": "latture/explicit-beam-fea", "max_stars_repo_head_hexsha": "003e940bda203e1d867494c891c9cee3477cd682", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-07-07T07:42:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-07T07:42:45.000Z", "max_issues_repo_path": "src/explicit_system.cpp", "max_issues_repo_name": "latture/explicit-beam-fea", "max_issues_repo_head_hexsha": "003e940bda203e1d867494c891c9cee3477cd682", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/explicit_system.cpp", "max_forks_repo_name": "latture/explicit-beam-fea", "max_forks_repo_head_hexsha": "003e940bda203e1d867494c891c9cee3477cd682", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.1377245509, "max_line_length": 159, "alphanum_fraction": 0.6369889682, "num_tokens": 1725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22684102821147467}}
{"text": "#ifndef STAN_MCMC_HMC_INTEGRATORS_IMPL_LEAPFROG_HPP\n#define STAN_MCMC_HMC_INTEGRATORS_IMPL_LEAPFROG_HPP\n\n#include <Eigen/Dense>\n#include <stan/mcmc/hmc/integrators/base_leapfrog.hpp>\n\nnamespace stan {\n  namespace mcmc {\n\n    template <typename Hamiltonian>\n    class impl_leapfrog: public base_leapfrog<Hamiltonian> {\n    public:\n      impl_leapfrog(): base_leapfrog<Hamiltonian>(),\n                       max_num_fixed_point_(10),\n                       fixed_point_threshold_(1e-8) {}\n\n      void begin_update_p(typename Hamiltonian::PointType& z,\n                          Hamiltonian& hamiltonian,\n                          double epsilon,\n                          callbacks::logger& logger) {\n        hat_phi(z, hamiltonian, epsilon, logger);\n        hat_tau(z, hamiltonian, epsilon, this->max_num_fixed_point_,\n                logger);\n      }\n\n      void update_q(typename Hamiltonian::PointType& z,\n                    Hamiltonian& hamiltonian,\n                    double epsilon,\n                    callbacks::logger& logger) {\n        // hat{T} = dT/dp * d/dq\n        Eigen::VectorXd q_init = z.q + 0.5 * epsilon * hamiltonian.dtau_dp(z);\n        Eigen::VectorXd delta_q(z.q.size());\n\n        for (int n = 0; n < this->max_num_fixed_point_; ++n) {\n          delta_q = z.q;\n          z.q.noalias() = q_init + 0.5 * epsilon * hamiltonian.dtau_dp(z);\n          hamiltonian.update_metric(z, logger);\n\n          delta_q -= z.q;\n          if (delta_q.cwiseAbs().maxCoeff() < this->fixed_point_threshold_)\n            break;\n        }\n        hamiltonian.update_gradients(z, logger);\n      }\n\n      void end_update_p(typename Hamiltonian::PointType& z,\n                        Hamiltonian& hamiltonian,\n                        double epsilon,\n                        callbacks::logger& logger) {\n        hat_tau(z, hamiltonian, epsilon, 1, logger);\n        hat_phi(z, hamiltonian, epsilon, logger);\n      }\n\n      // hat{phi} = dphi/dq * d/dp\n      void hat_phi(typename Hamiltonian::PointType& z,\n                   Hamiltonian& hamiltonian,\n                   double epsilon,\n                   callbacks::logger& logger) {\n        z.p -= epsilon * hamiltonian.dphi_dq(z, logger);\n      }\n\n      // hat{tau} = dtau/dq * d/dp\n      void hat_tau(typename Hamiltonian::PointType& z,\n                   Hamiltonian& hamiltonian,\n                   double epsilon,\n                   int num_fixed_point,\n                   callbacks::logger& logger) {\n        Eigen::VectorXd p_init = z.p;\n        Eigen::VectorXd delta_p(z.p.size());\n\n        for (int n = 0; n < num_fixed_point; ++n) {\n          delta_p = z.p;\n          z.p.noalias() = p_init - epsilon * hamiltonian.dtau_dq(z, logger);\n          delta_p -= z.p;\n          if (delta_p.cwiseAbs().maxCoeff() < this->fixed_point_threshold_)\n            break;\n        }\n      }\n\n      int max_num_fixed_point() {\n        return this->max_num_fixed_point_;\n      }\n\n      void set_max_num_fixed_point(int n) {\n        if (n > 0) this->max_num_fixed_point_ = n;\n      }\n\n      double fixed_point_threshold() {\n        return this->fixed_point_threshold_;\n      }\n\n      void set_fixed_point_threshold(double t) {\n        if (t > 0) this->fixed_point_threshold_ = t;\n      }\n\n    private:\n      int max_num_fixed_point_;\n      double fixed_point_threshold_;\n    };\n\n  }  // mcmc\n}  // stan\n\n#endif\n", "meta": {"hexsha": "604181ccf14fc108776ea65404b7fca0b6ea76e5", "size": 3349, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/stan/mcmc/hmc/integrators/impl_leapfrog.hpp", "max_stars_repo_name": "drezap/stan", "max_stars_repo_head_hexsha": "9b319ed125e2a7d14d0c9c246d2f462dad668537", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T01:40:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-05T01:40:40.000Z", "max_issues_repo_path": "src/stan/mcmc/hmc/integrators/impl_leapfrog.hpp", "max_issues_repo_name": "drezap/stan", "max_issues_repo_head_hexsha": "9b319ed125e2a7d14d0c9c246d2f462dad668537", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/stan/mcmc/hmc/integrators/impl_leapfrog.hpp", "max_forks_repo_name": "drezap/stan", "max_forks_repo_head_hexsha": "9b319ed125e2a7d14d0c9c246d2f462dad668537", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-14T11:36:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-14T11:36:09.000Z", "avg_line_length": 31.8952380952, "max_line_length": 78, "alphanum_fraction": 0.5622573903, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22684102821147467}}
{"text": "/*=========================================================================\n *\n * Copyright Universitat Pompeu Fabra, Department of Information and\n * Comunication Technologies.\n *  \n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *         http://www.apache.org/licenses/LICENSE-2.0.txt\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *=========================================================================*/\n\n#ifndef itkCudaRWSegmentationFilter_hxx\n#define itkCudaRWSegmentationFilter_hxx\n\n#include <itkImageRegionIterator.h>\n#include <itkImageRegionConstIterator.h>\n\n#include <vector>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n\n#define CLEANUP(s)     \\\n  do                   \\\n  {                    \\\n    printf(\"%s\\n\", s); \\\n    fflush(stdout);    \\\n  } while (0)\n\nnamespace itk\n{\ntemplate <typename TInputImage, typename TOutputImage>\nvoid CudaRWSegmentationFilter<TInputImage, TOutputImage>::GenerateData()\n{\n  if (m_LabelImage == nullptr) // Exit if SetLabelImage has not been called\n  {\n    std::cout << \"Label image has not been set\" << std::endl;\n    return;\n  }\n  if (OutputImageType::ImageDimension != 2 && OutputImageType::ImageDimension != 3)\n  {\n    std::cout << \"Exit segmentation. Image dimension must be 2 or 3 but is \" << OutputImageType::ImageDimension << std::endl;\n    return;\n  }\n\n  // Get regions to iterate for original and label images\n  typename OutputImageType::RegionType regionLabel = m_LabelImage->GetLargestPossibleRegion();\n\n  // Set label image iterator to get the bounding box size and the quantity of marked nodes\n  typedef itk::ImageRegionIterator<OutputImageType> IteratorLabelType;\n  IteratorLabelType itLabel(m_LabelImage, regionLabel);\n\n  // Crop image to bounds containin labels\n  typename OutputImageType::RegionType regionLabelCrop;\n  typename InputImageType::RegionType regionCrop;\n\n  for (int i = 0; i != OutputImageType::ImageDimension; ++i)\n  {\n    regionLabelCrop.SetSize(i, regionLabel.GetIndex()[i]);\n    regionLabelCrop.SetIndex(i, regionLabel.GetSize()[i]);\n  }\n\n  int markedLength = 0;\n\n  itLabel.GoToBegin();\n  while (!itLabel.IsAtEnd())\n  {\n    // Get image boundaries to crop image\n    if (itLabel.Get() != 0)\n    {\n      ++markedLength;\n      // Get bounding region\n      for (int i = 0; i != OutputImageType::ImageDimension; ++i)\n      {\n        if (itLabel.GetIndex()[i] < regionLabelCrop.GetIndex()[i])\n        {\n          regionCrop.SetIndex(i, itLabel.GetIndex()[i]);\n          regionLabelCrop.SetIndex(i, itLabel.GetIndex()[i]);\n        }\n        else if (itLabel.GetIndex()[i] > regionLabelCrop.GetSize()[i])\n        {\n          regionCrop.SetSize(i, itLabel.GetIndex()[i]);\n          regionLabelCrop.SetSize(i, itLabel.GetIndex()[i]);\n        }\n      }\n    }\n    ++itLabel;\n  }\n\n  int totalNodes = 1;\n  for (int i = 0; i != OutputImageType::ImageDimension; ++i)\n  {\n    regionCrop.SetIndex(i, regionCrop.GetIndex()[i]);\n    regionLabelCrop.SetIndex(i, regionLabelCrop.GetIndex()[i]);\n    regionCrop.SetSize(i, regionCrop.GetSize()[i] - regionCrop.GetIndex()[i] + 1);\n    regionLabelCrop.SetSize(i, regionLabelCrop.GetSize()[i] - regionLabelCrop.GetIndex()[i] + 1);\n\n    totalNodes *= regionCrop.GetSize()[i];\n  }\n\n  /////////////////////// Build Graph /////////////////////////////\n  /*\n    // Create graph. Each node will correspond to a pixel connected to its neighbors by an edge.\n    // Neighbors are those nodes which distance is 1 ( d = sqrt((x-xi)² + (y-yi)² + (z-zi)²) = 1 ), \n    // where x, y, and z are the indices of a pixel and xi, yi, and zi are the indeces of a neighboring pixel\n    // Iterate through all pixels of input and label images\n    */\n\n  int unmarkedLength = totalNodes - markedLength; /* Quantity of unmarked nodes */\n\n  // Define vectors to store graph data\n  std::vector<float> *nodes = new std::vector<float>(totalNodes);  /* Pixel intensity for all nodes/pixels */\n  std::vector<float> *labels = new std::vector<float>(totalNodes); /* Label of each node/pixel */\n  /*  For node 'i'. If 'i' is a marked node, previousFound->at(i) is how many unmarked nodes there are before node 'i'.\n        If 'i' is an unmarked node, previousFound->at(i) is how many marked nodes there are before node 'i'.\n        This values are needed to build ordered Lu and BT matrices.\n    */\n  std::vector<int> *previousFound = new std::vector<int>(totalNodes);\n  std::vector<int> *unmarked = new std::vector<int>(unmarkedLength); /* Indices of unmarked nodes ordered */\n  std::vector<int> *marked = new std::vector<int>(markedLength);     /* Store labels of marked nodes */\n  std::vector<int> *markedIdx = new std::vector<int>(markedLength);  /* Indices of marked nodes ordered */\n  std::vector<int> *nameLabels = new std::vector<int>();             /* Values of the different labels of the prior */\n\n  // Set bounding box image iterators\n  typedef itk::ImageRegionConstIterator<InputImageType> ConstIteratorImageType;\n  ConstIteratorImageType itImageCrop(this->GetInput(), regionCrop);\n  IteratorLabelType itLabelCrop(m_LabelImage, regionLabelCrop);\n\n  int foundMarked = 0;\n  int foundUnmarked = 0;\n  int NodeIdx = 0;\n\n  itImageCrop.GoToBegin();\n  itLabelCrop.GoToBegin();\n  while (!itImageCrop.IsAtEnd())\n  {\n    // Store intensity in a std::vector\n    nodes->at(NodeIdx) = itImageCrop.Get();\n    // Store labels in a std::vector. Each index of 'nodes' and 'labels' correspond to the same pixel\n    labels->at(NodeIdx) = itLabelCrop.Get();\n\n    if (itLabelCrop.Get() == 0)\n    {\n      // Get the index of each node that is unmarked\n      unmarked->at(foundUnmarked) = NodeIdx;\n      // Store how many marked points have been found before this unmarked node\n      previousFound->at(NodeIdx) = foundMarked;\n      ++foundUnmarked;\n    }\n    else\n    {\n      // Set to label value if label != 0\n      marked->at(foundMarked) = itLabelCrop.Get();\n      // Get the index of each node that is marked\n      markedIdx->at(foundMarked) = NodeIdx;\n      // Store how many unmarked points have been found before this marked node\n      previousFound->at(NodeIdx) = foundUnmarked;\n      ++foundMarked;\n      bool found;\n\n      // Store the different labels in a std::vector\n      found = std::find(nameLabels->begin(), nameLabels->end(), itLabelCrop.Get()) != nameLabels->end();\n      if (!found)\n      {\n        nameLabels->push_back(itLabelCrop.Get());\n      }\n    }\n    ++itImageCrop;\n    ++itLabelCrop;\n    ++NodeIdx;\n  }\n\n  // Sort labels\n  std::sort(nameLabels->begin(), nameLabels->end());\n\n  int totalLabels = nameLabels->size();\n  if (m_SolveForAllLabels)\n  {\n    totalLabels += 1;\n  }\n  // Linear system: Lu * X = -BT * M\n  // Convert marked (M) into a Eigen::Sparse matrix markedRHS. Needed for the computation of -BT * M (Eigen::SparseMatrix * Eigen::SparseMatrix)\n  Eigen::SparseMatrix<float, Eigen::ColMajor> *markedRHS = new Eigen::SparseMatrix<float, Eigen::ColMajor>(markedLength, totalLabels - 1);\n  for (int i = 0; i != totalLabels - 1; ++i)\n  {\n    int pos = 0;\n    for (auto itMarked = marked->begin(); itMarked != marked->end(); ++itMarked)\n    {\n      if (*itMarked == nameLabels->at(i))\n        markedRHS->insert(pos, i) = 1;\n      ++pos;\n    }\n  }\n\n  marked->clear();\n  delete marked;\n\n  /////////////////////// Build Laplacian matrix /////////////////////////////\n  // Normalize intensity gradient over image spacing\n  std::vector<float> spacing;\n  typename InputImageType::SpacingType space = this->GetInput()->GetSpacing();\n  if (OutputImageType::ImageDimension == 2)\n    spacing = {space[1], space[0], space[0], space[1]};\n  else if (OutputImageType::ImageDimension == 3)\n    spacing = {space[2], space[1], space[0], space[0], space[1], space[2]};\n\n  std::vector<int> neighbors;\n  int x = regionCrop.GetSize()[0];\n  int y = regionCrop.GetSize()[1];\n  //  Right hand of the equation: -BT * M\n  Eigen::SparseMatrix<float, Eigen::ColMajor> *BTxM = new Eigen::SparseMatrix<float, Eigen::ColMajor>(markedLength, totalLabels - 1);\n\n  // Build BT\n  // Compare whether NumCols < NumRows for less iterations during BT building\n  if (markedIdx->size() < unmarked->size())\n  {\n    Eigen::SparseMatrix<float, Eigen::ColMajor> *BT = new Eigen::SparseMatrix<float, Eigen::ColMajor>(unmarkedLength, markedLength);\n    BT->reserve(Eigen::VectorXi::Constant(markedLength, 6));\n\n    int node;\n    float valNode, valNeighbor, w;\n\n    // Iterate through marked nodes to build BT. Rows correspond to unmarked nodes, columns to marked nodes\n    for (auto itMarked = markedIdx->begin(); itMarked != markedIdx->end(); ++itMarked)\n    {\n      valNode = nodes->at(*itMarked); // Intensity of node\n      // Obtain neighbors indexes. right and left, top and bottom, front and back.\n      node = *itMarked;\n      if (OutputImageType::ImageDimension == 2)\n        neighbors = {node - x, node - 1, node + 1, node + x};\n      else if (OutputImageType::ImageDimension == 3)\n        neighbors = {node - x * y, node - x, node - 1, node + 1, node + x, node + x * y};\n      for (int i = 0; i != neighbors.size(); ++i)\n      {\n        // Make sure all the neighbors computed fall within the bounding box dimension\n        if (neighbors.at(i) >= 0 && neighbors.at(i) < totalNodes && labels->at(neighbors.at(i)) == 0)\n        {\n          valNeighbor = nodes->at(neighbors.at(i));                                    // Intensity of neighbor pixel\n          w = (exp(-m_Beta * pow((valNode - valNeighbor) / spacing.at(i), 2)) + 1e-6); // Intensity gradient following a Gaussian function\n          //  Columns of BT correspond to marked nodes, rows to unmarked\n          BT->insert(neighbors.at(i) - previousFound->at(neighbors.at(i)), node - previousFound->at(node)) = -w;\n        }\n      }\n    }\n    markedIdx->clear();\n    //  Right hand of the equation: -BT * M\n    *BTxM = -*BT * *markedRHS;\n    BT->resize(0, 0);\n    BT->data().squeeze();\n    markedRHS->resize(0, 0);\n    markedRHS->data().squeeze();\n    delete markedIdx, markedRHS, BT;\n  }\n  else\n  {\n    markedIdx->clear();\n    delete markedIdx;\n\n    Eigen::SparseMatrix<float, Eigen::RowMajor> *BT = new Eigen::SparseMatrix<float, Eigen::RowMajor>(unmarkedLength, markedLength);\n    BT->reserve(Eigen::VectorXi::Constant(markedLength, 6));\n\n    int node;\n    float valNode, valNeighbor, w;\n\n    // Iterate through unmarked nodes to build BT. Rows correspond to unmarked nodes, columns to marked nodes\n    for (auto itUnmarked = unmarked->begin(); itUnmarked != unmarked->end(); ++itUnmarked)\n    {\n      valNode = nodes->at(*itUnmarked); // Intensity of node\n      // Obtain neighbors indexes. right and left, top and bottom, front and back.\n      node = *itUnmarked;\n      if (OutputImageType::ImageDimension == 2)\n        neighbors = {node - x, node - 1, node + 1, node + x};\n      else if (OutputImageType::ImageDimension == 3)\n        neighbors = {node - x * y, node - x, node - 1, node + 1, node + x, node + x * y};\n      for (int i = 0; i != neighbors.size(); ++i)\n      {\n        // Make sure all the neighbors computed fall within the bounding box dimension\n        if (neighbors.at(i) >= 0 && neighbors.at(i) < totalNodes && labels->at(neighbors.at(i)) != 0)\n        {\n          valNeighbor = nodes->at(neighbors.at(i));                                    // Intensity of neighbor pixel\n          w = (exp(-m_Beta * pow((valNode - valNeighbor) / spacing.at(i), 2)) + 1e-6); // Intensity gradient following a Gaussian function\n          //  Columns of BT correspond to marked nodes, rows to unmarked\n          BT->insert(node - previousFound->at(node), neighbors.at(i) - previousFound->at(neighbors.at(i))) = -w;\n        }\n      }\n    }\n    //  Right hand of the equation: -BT * M\n    *BTxM = -*BT * *markedRHS;\n    BT->resize(0, 0);\n    BT->data().squeeze();\n    markedRHS->resize(0, 0);\n    markedRHS->data().squeeze();\n    delete markedRHS, BT;\n  }\n\n  int nnz = 0;\n\n  // Build Lu. LHS of the equation\n  Eigen::SparseMatrix<float, Eigen::RowMajor> *Lu = new Eigen::SparseMatrix<float, Eigen::RowMajor>(unmarkedLength, unmarkedLength);\n  Lu->reserve(Eigen::VectorXi::Constant(unmarkedLength, 7));\n\n  // Iterate through unmarked nodes to build Lu. Rows correspond to unmarked nodes, columns to unmarked nodes\n  for (auto itUnmarked = unmarked->begin(); itUnmarked != unmarked->end(); ++itUnmarked)\n  {\n    int node;\n    float valNode, valNeighbor, w, degree;\n\n    valNode = nodes->at(*itUnmarked); // Intensity of node\n    // Obtain neighbors indexes. right and left, top and bottom, front and back.\n    node = *itUnmarked;\n    if (OutputImageType::ImageDimension == 2)\n      neighbors = {node - x, node - 1, node + 1, node + x};\n    else if (OutputImageType::ImageDimension == 3)\n      neighbors = {node - x * y, node - x, node - 1, node + 1, node + x, node + x * y};\n    degree = 0.0;\n    for (int i = 0; i != neighbors.size(); ++i)\n    {\n      // Make sure all the neighbors computed fall within the bounding box dimension\n      if (neighbors.at(i) >= 0 && neighbors.at(i) < totalNodes)\n      {\n        valNeighbor = nodes->at(neighbors.at(i));                                    // Intensity of neighbor pixel\n        w = (exp(-m_Beta * pow((valNode - valNeighbor) / spacing.at(i), 2)) + 1e-6); // Intensity gradient following a Gaussian function\n        degree += w;                                                                 // Sum of the weights\n        //  Columns of Lu correspond to unmarked nodes\n        if (labels->at(neighbors.at(i)) == 0) // If neighbor is an unmarked node, build Lu\n        {\n          Lu->insert(node - previousFound->at(node), neighbors.at(i) - previousFound->at(neighbors.at(i))) = -w;\n          ++nnz;\n        }\n      }\n    }\n    // Add node degree to diagonal of Lu\n    Lu->insert(node - previousFound->at(node), node - previousFound->at(node)) = degree;\n    ++nnz;\n  }\n  Lu->makeCompressed();\n\n  Eigen::SparseMatrix<float, Eigen::RowMajor> *Lu_PreconditionerGpu = new Eigen::SparseMatrix<float, Eigen::RowMajor>(unmarkedLength, unmarkedLength);\n  Lu_PreconditionerGpu->reserve(Eigen::VectorXi::Constant(unmarkedLength, 1));\n  for (int i = 0; i != unmarkedLength; ++i)\n    Lu_PreconditionerGpu->insert(i, i) = 1 / Lu->coeffRef(i, i);\n  Lu_PreconditionerGpu->makeCompressed();\n\n  nodes->clear();\n  unmarked->clear();\n  previousFound->clear();\n  neighbors.clear();\n  delete nodes, unmarked, previousFound;\n\n  // /////////////////////// Solve linear system /////////////////////////////\n  // Convert BTxM into a float array for bicgstab cuda solver\n  float *bhost_all_labels = new float[unmarkedLength * (totalLabels - 1)];\n\n  for (int i = 0; i != unmarkedLength * (totalLabels - 1); ++i)\n    bhost_all_labels[i] = 0;\n\n  for (int k = 0; k < BTxM->outerSize(); ++k)\n  {\n    for (Eigen::SparseMatrix<float, Eigen::ColMajor>::InnerIterator itMat(*BTxM, k); itMat; ++itMat)\n    {\n      bhost_all_labels[itMat.row() + k * unmarkedLength] = itMat.value();\n    }\n  }\n\n  // Get pointers for CSR matrices Lu and Lu_PreconditionerGpu\n  cooValAhost = Lu->valuePtr();\n  csrColPtrAhost = Lu->outerIndexPtr();\n  cooRowPtrAhost = Lu->innerIndexPtr();\n\n  cooValAhostM = Lu_PreconditionerGpu->valuePtr();\n  csrColPtrAhostM = Lu_PreconditionerGpu->outerIndexPtr();\n  cooRowPtrAhostM = Lu_PreconditionerGpu->innerIndexPtr();\n\n  int bicgstab_exit_status, cuda_mem_cpy_exit_status, cuda_mem_free_exit_status;\n\n  // Result vector\n  probabilities = new float[unmarkedLength * (totalLabels - 1)];\n  probabilitiesInner = new float[unmarkedLength];\n\n  // Allocate GPU memory\n  cuda_mem_cpy_exit_status = this->AllocGPUMemory(unmarkedLength, nnz);\n  if (cuda_mem_cpy_exit_status != 0)\n  {\n    std::cout << \"GPU memory allocation failed with error \" << cuda_mem_cpy_exit_status << std::endl;\n    return;\n  }\n\n  // Solve S-1 linear systems\n  for (int linearSystem = 0; linearSystem != totalLabels - 1; ++linearSystem)\n  {\n    // Get pinter for each linear system RHS\n    bhost = &bhost_all_labels[linearSystem * unmarkedLength];\n    // Call CUDA BiCGStab solver\n    bicgstab_exit_status = this->BiCGStab(unmarkedLength, nnz);\n    if (bicgstab_exit_status != 0)\n    {\n      std::cout << \"BiCStab failed with error\" << bicgstab_exit_status << std::endl;\n      return;\n    }\n\n    for (int i = 0; i != unmarkedLength; ++i)\n      probabilities[i + linearSystem * unmarkedLength] = probabilitiesInner[i];\n  }\n\n  // Free GPU memeory when all linear systems have been solved\n  cuda_mem_free_exit_status = this->FreeGPUMemory();\n  if (cuda_mem_free_exit_status != 0)\n  {\n    std::cout << \"GPU memory free failed with error\" << cuda_mem_free_exit_status << std::endl;\n  }\n  Lu->resize(0, 0);\n  Lu->data().squeeze();\n  Lu_PreconditionerGpu->resize(0, 0);\n  Lu_PreconditionerGpu->data().squeeze();\n  BTxM->resize(0, 0);\n  BTxM->data().squeeze();\n  delete Lu, Lu_PreconditionerGpu, BTxM;\n  delete[] probabilitiesInner, bhost, bhost_all_labels, cooRowPtrAhost, csrColPtrAhost, cooValAhost, cooRowPtrAhostM, csrColPtrAhostM, cooValAhostM;\n\n  std::vector<int> *RWLabels = new std::vector<int>(unmarkedLength);\n\n  /*  Assign a label to each unmarked node according to the result of the solver. \n      The label that is assigned is that one corresponding to the highest probability.\n      Since we solver for S-1 systems, last label probability is computed by subtraction */\n  for (int i = 0; i != unmarkedLength; ++i)\n  {\n    float maxProbability = probabilities[i];\n    int maxLabelPos = 0;\n    float accumulatedProbability = maxProbability;\n    for (int j = 1; j != totalLabels - 1; ++j)\n    {\n      accumulatedProbability += probabilities[i + j * unmarkedLength];\n      if (probabilities[i + j * unmarkedLength] > maxProbability)\n      {\n        maxProbability = probabilities[i + j * unmarkedLength];\n        maxLabelPos = j;\n      }\n    }\n    RWLabels->at(i) = 0.95 - accumulatedProbability > maxProbability ? nameLabels->back() : nameLabels->at(maxLabelPos);\n  }\n\n  delete[] probabilities;\n\n  int valBackground;\n  if (!m_WriteBackground)\n    valBackground = 0;\n  else\n    valBackground = nameLabels->back();\n\n  typename OutputImageType::Pointer outputLabels = this->GetOutput();\n\n  outputLabels->Graft(m_LabelImage);\n  outputLabels->FillBuffer(valBackground);\n\n  // Iterate through original label image to create segmentation image\n  // Assign labels known from label image to their original value. Assign unmarked labels\n  // according to the result from the solver\n\n  IteratorLabelType itOut1(outputLabels, regionLabelCrop);\n\n  // Set computed labels to segmentation image\n  int unmarkedIdx = 0;\n  int idxOutput = 0;\n\n  itOut1.GoToBegin();\n  while (!itOut1.IsAtEnd())\n  {\n    if (labels->at(idxOutput) == 0)\n    {\n      if (RWLabels->at(unmarkedIdx) != nameLabels->back())\n        itOut1.Set(RWLabels->at(unmarkedIdx));\n      else\n        itOut1.Set(valBackground);\n      ++unmarkedIdx;\n    }\n    else if (labels->at(idxOutput) != nameLabels->back())\n      itOut1.Set(labels->at(idxOutput));\n\n    ++idxOutput;\n    ++itOut1;\n  }\n\n  labels->clear();\n  RWLabels->clear();\n  nameLabels->clear();\n  delete labels, RWLabels, nameLabels;\n\n  return;\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nint CudaRWSegmentationFilter<TInputImage, TOutputImage>::BiCGStab(int M, int nnz)\n{\n\n  int iter, flag;\n\n  cusparseStatus_t status;\n  cusparseHandle_t handle = 0;\n  cusparseMatDescr_t descra = 0;\n\n  int nnzM = M;\n  int N = M;\n  int N2 = N;\n\n  float timesOne[1] = {1.0};\n  float timesZero[1] = {0.0};\n  float timesMinusOne[1] = {-1.0};\n\n  cudaStat4 = cudaMemcpy(r, bhost,\n                         (size_t)(N * sizeof(r[0])),\n                         cudaMemcpyHostToDevice);\n\n  cudaStat5 = cudaMemcpy(xdev, xhost,\n                         (size_t)(N * sizeof(xdev[0])),\n                         cudaMemcpyHostToDevice);\n\n  // Copy right hand side to GPU memory\n  if ((cudaStat4 != cudaSuccess) ||\n      (cudaStat5 != cudaSuccess))\n  {\n    CLEANUP(\"Memcpy from Host to Device failed\");\n    return EXIT_FAILURE;\n  }\n\n  /* initialize cusparse library */\n  status = cusparseCreate(&handle);\n  if (status != CUSPARSE_STATUS_SUCCESS)\n  {\n    CLEANUP(\"CUSPARSE Library initialization failed\");\n    return EXIT_FAILURE;\n  }\n  /* create and setup matrix descriptor */\n  status = cusparseCreateMatDescr(&descra);\n  if (status != CUSPARSE_STATUS_SUCCESS)\n  {\n    CLEANUP(\"Matrix descriptor initialization failed\");\n    return EXIT_FAILURE;\n  }\n  cusparseSetMatType(descra, CUSPARSE_MATRIX_TYPE_GENERAL);\n  cusparseSetMatIndexBase(descra, CUSPARSE_INDEX_BASE_ZERO);\n\n  bnrm2 = cublasSnrm2(N, r, 1);\n\n  float tol = m_Tolerance * bnrm2;\n\n  status = cusparseScsrmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, N, N, nnz, timesMinusOne, descra, cooValAdev, csrColPtrAdev, cooRowPtrAdev, xdev, timesOne, r); /* r = r - A*x; r is now residual */\n\n  if (status != CUSPARSE_STATUS_SUCCESS)\n  {\n    CLEANUP(\"Matrix‐vector multiplication failed\");\n    return EXIT_FAILURE;\n  }\n\n  error = cublasSnrm2(N, r, 1) / bnrm2; /* norm_r = norm(b) */\n  if (error < tol)\n  {\n    CLEANUP(\"Error smaller than tolerance failed\");\n    return EXIT_FAILURE; /* x is close enough already */\n  }\n\n  omega = 1.0;\n\n  cudaStat1 = cudaMemcpy(r_tld, r, (size_t)(N * sizeof(r[0])),\n                         cudaMemcpyDeviceToDevice); /* r_tld = r */\n\n  if ((cudaStat1 != cudaSuccess))\n  {\n    CLEANUP(\"Memcpy from r to r_tld failed\");\n    return EXIT_FAILURE;\n  }\n\n  // Loop of the BiCGStab solver\n  for (iter = 0; iter < m_MaximumNumberOfIterations; ++iter)\n  {\n    rho = cublasSdot(N, r_tld, 1, r, 1); /* rho = r_tld'*r */\n\n    if (rho == 0.0)\n      break;\n\n    if (iter > 0)\n    {\n      beta = (rho / rho_1) * (alpha / omega);\n      cublasSaxpy(N, -omega, v, 1, p, 1);\n      cublasSaxpy(N, 1.0 / beta, r, 1, p, 1);\n      cublasSscal(N, beta, p, 1); /* p = r + beta*( p - omega*v ) */\n    }\n    else\n    {\n      cudaStat1 = cudaMemcpy(p, r,\n                             (size_t)(N * sizeof(r[0])),\n                             cudaMemcpyDeviceToDevice); /* p = r */\n      if ((cudaStat1 != cudaSuccess))\n      {\n        CLEANUP(\"Memcpy from r to p failed\");\n        return EXIT_FAILURE;\n      }\n    }\n\n    status = cusparseScsrmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, N2, N2, nnzM, timesOne, descra, cooValAdevM, csrColPtrAdevM, cooRowPtrAdevM, p, timesZero, p_hat);\n\n    status = cusparseScsrmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, N, N, nnz, timesOne, descra, cooValAdev, csrColPtrAdev, cooRowPtrAdev, p_hat, timesZero, v); /* v = A*p_hat */\n\n    alpha = rho / cublasSdot(N, r_tld, 1, v, 1); /* alph = rho / ( r_tld'*v ) */\n\n    cudaStat1 = cudaMemcpy(s, r, (size_t)(N * sizeof(r[0])),\n                           cudaMemcpyDeviceToDevice); /* s = r */\n    if ((cudaStat1 != cudaSuccess))\n    {\n      CLEANUP(\"Memcpy from r to s failed\");\n      return EXIT_FAILURE;\n    }\n    cublasSaxpy(N, -alpha, v, 1, s, 1);\n    snrm2 = cublasSnrm2(N, s, 1);\n\n    cublasSaxpy(N, alpha, p_hat, 1, xdev, 1); /*  h = x + alph*p_hat */\n\n    if (snrm2 < tol)\n    {\n      // cublasSaxpy(N, alpha, p_hat, 1, s, 1);\n      resid = snrm2 / bnrm2;\n\n      cudaStat5 = cudaMemcpy(probabilitiesInner, xdev,\n                             (size_t)(N * sizeof(probabilitiesInner[0])),\n                             cudaMemcpyDeviceToHost); /* x = h */\n      if ((cudaStat5 != cudaSuccess))\n      {\n        CLEANUP(\"Memcpy from x to xhost failed\");\n        return EXIT_FAILURE;\n      }\n\n      break;\n    }\n\n    status = cusparseScsrmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, N2, N2, nnzM, timesOne, descra, cooValAdevM, csrColPtrAdevM, cooRowPtrAdevM, s, timesZero, s_hat);\n\n    status = cusparseScsrmv(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, N, N, nnz, timesOne, descra, cooValAdev, csrColPtrAdev, cooRowPtrAdev, s_hat, timesZero, t); /* t = A*s_hat */\n\n    omega = cublasSdot(N, t, 1, s, 1) / cublasSdot(N, t, 1, t, 1); /* omega = ( t'*s) / ( t'*t ) */\n\n    cublasSaxpy(N, omega, s_hat, 1, xdev, 1); /*  x = h + omega*s_hat */\n\n    cudaStat1 = cudaMemcpy(r, s, (size_t)(N * sizeof(r[0])),\n                           cudaMemcpyDeviceToDevice); /* r = s */\n    if ((cudaStat1 != cudaSuccess))\n    {\n      CLEANUP(\"Memcpy from s to r failed\");\n      return EXIT_FAILURE;\n    }\n\n    cublasSaxpy(N, -omega, t, 1, r, 1); /* r = s - omega*t */\n    snrm2 = cublasSnrm2(N, r, 1);\n\n    if (snrm2 <= tol)\n    {\n      resid = snrm2 / bnrm2;\n\n      cudaStat5 = cudaMemcpy(probabilitiesInner, xdev,\n                             (size_t)(N * sizeof(probabilitiesInner[0])),\n                             cudaMemcpyDeviceToHost); /* x = x */\n      if ((cudaStat5 != cudaSuccess))\n      {\n        CLEANUP(\"Memcpy from x to xhost failed\");\n        return EXIT_FAILURE;\n      }\n      break;\n    }\n    if (omega == 0.0)\n      break;\n    rho_1 = rho;\n  }\n  ++iter;\n\n  error = snrm2 / bnrm2;\n\n  if (error <= tol)\n  {\n    flag = 0;\n  }\n  else if (omega == 0.0)\n  {\n    flag = -2;\n  }\n  else if (rho == 0.0)\n  {\n    flag = -1;\n  }\n  else\n    flag = 1;\n\n  m_SolverIterations += iter;\n  m_SolverError = std::min(m_SolverError, error);\n\n  return flag;\n}\n\n// Allocate GPU memory and copy data to device\ntemplate <typename TInputImage, typename TOutputImage>\nint CudaRWSegmentationFilter<TInputImage, TOutputImage>::AllocGPUMemory(int M, int nnz)\n{\n\n  int nnzM = M; // Lu has size MxM, Lu_PreconditionerGpu has size MxM\n  int N = M;\n\n  // Define initial guess\n  xhost = new float[N];\n  for (int i = 0; i < N; i++)\n  {\n    xhost[i] = 0;\n  }\n\n  cudaStat1 = cudaMalloc((void **)&cooRowPtrAdev, nnz * sizeof(cooRowPtrAdev[0]));\n  cudaStat3 = cudaMalloc((void **)&cooValAdev, nnz * sizeof(cooValAdev[0]));\n  cudaStat4 = cudaMalloc((void **)&r, N * sizeof(r[0]));\n  cudaStat5 = cudaMalloc((void **)&s, N * sizeof(s[0]));\n  cudaStat6 = cudaMalloc((void **)&t, N * sizeof(t[0]));\n  cudaStat7 = cudaMalloc((void **)&r_tld, N * sizeof(r_tld[0]));\n  cudaStat8 = cudaMalloc((void **)&p, N * sizeof(p[0]));\n  cudaStat9 = cudaMalloc((void **)&p_hat, N * sizeof(p_hat[0]));\n  cudaStat10 = cudaMalloc((void **)&s_hat, N * sizeof(s_hat[0]));\n  cudaStat11 = cudaMalloc((void **)&v, N * sizeof(v[0]));\n  cudaStat12 = cudaMalloc((void **)&xdev, N * sizeof(xdev[0]));\n\n  cudaStat13 = cudaMalloc((void **)&csrColPtrAdev, (N + 1) * sizeof(csrColPtrAdev[0]));\n\n  cudaStat14 = cudaMalloc((void **)&cooRowPtrAdevM, nnzM * sizeof(cooRowPtrAdevM[0]));\n  cudaStat16 = cudaMalloc((void **)&cooValAdevM, nnzM * sizeof(cooValAdevM[0]));\n  cudaStat17 = cudaMalloc((void **)&csrColPtrAdevM, (N + 1) * sizeof(csrColPtrAdevM[0]));\n\n  if ((cudaStat1 != cudaSuccess) ||\n      (cudaStat3 != cudaSuccess) ||\n      (cudaStat4 != cudaSuccess) ||\n      (cudaStat5 != cudaSuccess) ||\n      (cudaStat6 != cudaSuccess) ||\n      (cudaStat7 != cudaSuccess) ||\n      (cudaStat8 != cudaSuccess) ||\n      (cudaStat9 != cudaSuccess) ||\n      (cudaStat10 != cudaSuccess) ||\n      (cudaStat11 != cudaSuccess) ||\n      (cudaStat12 != cudaSuccess) ||\n\n      (cudaStat14 != cudaSuccess) ||\n      (cudaStat16 != cudaSuccess) ||\n      (cudaStat17 != cudaSuccess))\n  {\n    CLEANUP(\"Device malloc failed\");\n    return EXIT_FAILURE;\n  }\n\n  cudaStat1 = cudaMemcpy(cooRowPtrAdev, cooRowPtrAhost,\n                         (size_t)(nnz * sizeof(cooRowPtrAdev[0])),\n                         cudaMemcpyHostToDevice);\n  cudaStat13 = cudaMemcpy(csrColPtrAdev, csrColPtrAhost,\n                          (size_t)((N + 1) * sizeof(csrColPtrAdev[0])),\n                          cudaMemcpyHostToDevice);\n  cudaStat3 = cudaMemcpy(cooValAdev, cooValAhost,\n                         (size_t)(nnz * sizeof(cooValAdev[0])),\n                         cudaMemcpyHostToDevice);\n\n  cudaStat14 = cudaMemcpy(cooRowPtrAdevM, cooRowPtrAhostM,\n                          (size_t)(nnzM * sizeof(cooRowPtrAdevM[0])),\n                          cudaMemcpyHostToDevice);\n  cudaStat17 = cudaMemcpy(csrColPtrAdevM, csrColPtrAhostM,\n                          (size_t)((N + 1) * sizeof(cooColPtrAdevM[0])),\n                          cudaMemcpyHostToDevice);\n  cudaStat16 = cudaMemcpy(cooValAdevM, cooValAhostM,\n                          (size_t)(nnzM * sizeof(cooValAdevM[0])),\n                          cudaMemcpyHostToDevice);\n\n  if ((cudaStat1 != cudaSuccess) ||\n      (cudaStat13 != cudaSuccess) ||\n      (cudaStat3 != cudaSuccess) ||\n      (cudaStat14 != cudaSuccess) ||\n      (cudaStat17 != cudaSuccess) ||\n      (cudaStat16 != cudaSuccess))\n  {\n    CLEANUP(\"Memcpy from Host to Device failed\");\n    return EXIT_FAILURE;\n  }\n\n  return 0;\n}\n\n// Free GPU memeory when all linear systems have been solved\ntemplate <typename TInputImage, typename TOutputImage>\nint CudaRWSegmentationFilter<TInputImage, TOutputImage>::FreeGPUMemory()\n{\n  /* shutdown CUBLAS */\n  cublas_status = cublasShutdown();\n  if (cublas_status != CUBLAS_STATUS_SUCCESS)\n  {\n    fprintf(stderr, \"!!!! shutdown error (A)\\n\");\n    return EXIT_FAILURE;\n  }\n\n  cudaStat1 = cudaFree(cooRowPtrAdev);\n  cudaStat3 = cudaFree(cooValAdev);\n  cudaStat4 = cudaFree(r);\n  cudaStat5 = cudaFree(s);\n  cudaStat6 = cudaFree(t);\n  cudaStat7 = cudaFree(r_tld);\n  cudaStat8 = cudaFree(p);\n  cudaStat9 = cudaFree(p_hat);\n  cudaStat10 = cudaFree(s_hat);\n  cudaStat11 = cudaFree(v);\n  cudaStat12 = cudaFree(xdev);\n\n  cudaStat13 = cudaFree(csrColPtrAdev);\n\n  cudaStat14 = cudaFree(cooRowPtrAdevM);\n  cudaStat16 = cudaFree(cooValAdevM);\n  cudaStat17 = cudaFree(csrColPtrAdevM);\n\n  if ((cudaStat1 != cudaSuccess) ||\n      (cudaStat3 != cudaSuccess) ||\n      (cudaStat4 != cudaSuccess) ||\n      (cudaStat5 != cudaSuccess) ||\n      (cudaStat6 != cudaSuccess) ||\n      (cudaStat7 != cudaSuccess) ||\n      (cudaStat8 != cudaSuccess) ||\n      (cudaStat9 != cudaSuccess) ||\n      (cudaStat10 != cudaSuccess) ||\n      (cudaStat11 != cudaSuccess) ||\n      (cudaStat12 != cudaSuccess) ||\n\n      (cudaStat14 != cudaSuccess) ||\n      (cudaStat16 != cudaSuccess) ||\n      (cudaStat17 != cudaSuccess))\n  {\n    CLEANUP(\"Device memory free failed\");\n    return EXIT_FAILURE;\n  }\n\n  return 0;\n}\n\ntemplate <typename TInputImage, typename TOutputImage>\nvoid CudaRWSegmentationFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream &os, Indent indent) const\n{\n  Superclass::PrintSelf(os, indent);\n  os << indent << \"Beta: \" << m_Beta << std::endl;\n  os << indent << \"Tolerance: \" << m_Tolerance << std::endl;\n  os << indent << \"MaximumNumberOfIterations: \" << m_MaximumNumberOfIterations << std::endl;\n  os << indent << \"WriteBackground: \" << m_WriteBackground << std::endl;\n}\n\n} // namespace itk\n#endif", "meta": {"hexsha": "772d914c177d0a5f56b92d307506729d1c6f4a9f", "size": 30686, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "itkCudaRWSegmentationFilter/itkCudaRWSegmentationFilter.hxx", "max_stars_repo_name": "enricperera/itkRWSegmentationFilter", "max_stars_repo_head_hexsha": "0188a4cfa31c8798301af58c37b28d430efdef06", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-20T13:29:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-20T13:29:02.000Z", "max_issues_repo_path": "itkCudaRWSegmentationFilter/itkCudaRWSegmentationFilter.hxx", "max_issues_repo_name": "enricperera/itkRWSegmentationFilter", "max_issues_repo_head_hexsha": "0188a4cfa31c8798301af58c37b28d430efdef06", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-10T09:48:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-10T09:48:45.000Z", "max_forks_repo_path": "Plugins/org.upf.rwSegmentationPlugin/src/internal/itkCudaRWSegmentationFilter/itkCudaRWSegmentationFilter.hxx", "max_forks_repo_name": "enricperera/mitkRWSegmentationPlugin", "max_forks_repo_head_hexsha": "20e4bbb7bd977fdc929e694a233410af1aa67cab", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9320843091, "max_line_length": 200, "alphanum_fraction": 0.6298311934, "num_tokens": 8651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22684102208302143}}
{"text": "// Prepare for G2O-------------------------------------------------\n\n#include <Eigen/StdVector>\n#include <iostream>\n\n#include <stdint.h>\n#include <g2o/core/sparse_optimizer.h>\n#include <g2o/core/block_solver.h>\n#include <g2o/core/solver.h>\n#include <g2o/core/optimization_algorithm_gauss_newton.h>\n#include <g2o/solvers/cholmod/linear_solver_cholmod.h>\n#include <g2o/solvers/pcg/linear_solver_pcg.h>\n#include <g2o/stuff/sampler.h>\n\n#include \"targetTypes6D.hpp\"\n// #include \"continuous_to_discrete.h\"\n// #include \"targetTypes3D.hpp\"\nusing namespace Eigen;\nusing namespace std;\nusing namespace g2o;\n\n\n\n// Prepare for ROS-------------------------------------------------\n#include <ros/ros.h>\n#include <ros/time.h>\n#include \"sensor_msgs/Imu.h\"\n// #include \"sensor_msgs/MagneticField.h\"\n// #include \"sensor_msgs/Temperature.h\"\n// #include \"sensor_msgs/FluidPressure.h\"\n// #include \"sensor_msgs/Joy.h\"\n// #include \"sensor_msgs/NavSatFix.h\"\n// #include \"sensor_msgs/Range.h\"\n\n// #include \"geometry_msgs/PointStamped.h\"\n#include \"geometry_msgs/PoseWithCovarianceStamped.h\"\n#include \"geometry_msgs/PoseArray.h\"\n// #include \"geometry_msgs/PoseStamped.h\"\n// #include \"geometry_msgs/TwistWithCovarianceStamped.h\"\n// #include <geometry_msgs/Vector3Stamped.h>\n// #include <sensor_fusion_comm/ExtEkf.h>\n#include <sensor_fusion_comm/DoubleArrayStamped.h>\n\n// #include \"nav_msgs/Odometry.h\"\n// #include \"crossover_nav/Ack.h\"\n// #include \"crossover_nav/Navdata.h\"\n// #include \"crossover_nav/odom_data.h\"\n// #include \"crossover_nav/Status.h\"\n\n#include <tf/transform_broadcaster.h>\n#include <geometry_msgs/Quaternion.h>\n\n\n\n\n// #include <dynamic_reconfigure/BoolParameter.h>\n// #include <dynamic_reconfigure/Reconfigure.h>\n// #include <dynamic_reconfigure/Config.h>\n\n// #include <termios.h>\n\n//function convert arduino to ros\n//------------ROS version-------\n// #include <iostream>\ninline long millis() {\n  return (1e3 * ros::Time::now().sec + 1e-6 * ros::Time::now().nsec);\n}\ninline long micros() {\n  return (1e6 * ros::Time::now().sec + 1e-3 * ros::Time::now().nsec);\n}\n//not use millis() it give me online floating point behind sec\n//go use ros::Time::now();\n#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))\n\n#define delay(x) ros::Duration(x/1000.0).sleep()\n#define say(x) (std::cout << x)\n#define sayend(x) (std::cout << x << std::endl)\n#define saytab(x) (std::cout << x << \"\\t\")\n#define saycomma(x) (std::cout << x << \" ,\")\n#define Min(a,b) ((a)<(b)?(a):(b))\n#define Max(a,b) ((a)>(b)?(a):(b))\n#define isfinite(X) std::isfinite(X)\n#define wrap_180(x) (x < -180 ? x+360 : (x > 180 ? x - 360: x))\n#define wrap_pi(x) (x < -3.14 ? x+6.28 : (x > 3.14 ? x - 6.28: x))\n#define HALF_M_PI 1.570796\n\nsensor_msgs::Imu imu;\ngeometry_msgs::PoseWithCovarianceStamped gps_pose , poseop_msgs;\nsensor_fusion_comm::DoubleArrayStamped state_out_msf;\n#define NUM_ITERATE 1\n\nVector3d gps[5];\nVector6d msf_state[17];\nVector3d acc[17];\ndouble dtime[200];\nint Iterate = 0;\nVector6d state;\nint Numimu = 0;\nint Numstate = 0;\n\nint num_state = 0; //round max = 17\nfloat GPS_lOOCKUP[5][2] = {{0,0},\n                         {3,0},\n                         {3,-3},\n                         {0,-3},\n                         {0,0}\n                          };\n\nfloat STATE_LOOCKUP[17][2];\n\n\n\n\n\n\n\n\n// void imucallback(const sensor_msgs::Imu::ConstPtr &data)\n// {\n//   // imu = *data;\n//   sensor_msgs::Imu imu_bf = *data;\n\n//   static ros::Time st = ros::Time::now();\n//   static ros::Duration ct = ros::Time::now()-st;\n//   static ros::Duration pt= ct;\n//   ct = ros::Time::now()-st;\n//   dtime[Numimu] = (ct - pt).toSec();\n\n//   //transform bf to ef\n//   tf::Quaternion qimu(imu_bf.linear_acceleration.x,imu_bf.linear_acceleration.y,imu_bf.linear_acceleration.z,0);\n//   tf::Quaternion q(imu_bf.orientation.x,imu_bf.orientation.y,imu_bf.orientation.z,imu_bf.orientation.w);\n\n//   qimu = q*qimu*q.inverse() - tf::Quaternion(0,0,9.81,0);\n\n//   imu.linear_acceleration.x = qimu.x();\n//   imu.linear_acceleration.y = qimu.y();\n//   imu.linear_acceleration.z = qimu.z();\n//   imu.orientation = imu_bf.orientation;\n\n//   acc[Numimu][0] = imu.linear_acceleration.x;\n//   acc[Numimu][1] = imu.linear_acceleration.y;\n//   acc[Numimu][2] = imu.linear_acceleration.z;\n\n//   Numimu++;\n//   // tf::Quaternion q(imu.orientation.x, imu.orientation.y, imu.orientation.z, imu.orientation.w);\n//   // tf::Matrix3x3 m(q);\n//   // m.getRPY(roll, pitch, yaw);\n//   //ROS_INFO(\"ax:[%f]\", yaw);\n// }\n// void gpscallback(/*const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& data*/) {\n//   // gps_pose = *data;\n\n//   if(Iterate>=NUM_ITERATE) return;\n\n//   gps[num_state][0] = GPS_lOOCKUP[0][0];\n//   gps[num_state][1] = gps_pose.pose.pose.position.y;\n//   gps[num_state][2] = 0;\n\n//   Iterate++;\n\n// }\n// void state_out_callback(/*const sensor_fusion_comm::DoubleArrayStamped::ConstPtr& data*/) {\n\n//   state_out_msf = *data;\n\n//   for(int i =0;i<6;i++)\n//     msf_state[Numstate][i] = state_out_msf.data[i];\n//   Numstate++;\n// }\n\nvoid Optimize_test(double dt);\n\n\nint main( int argc, char** argv )\n{\n  ros::init(argc, argv, \"gps_tester\");\n  ros::NodeHandle n;\n  ros::Rate r(200);\n\n  // ros::Subscriber imu_sub           = n.subscribe<sensor_msgs::Imu>(\"/imu_max\", 2, imucallback);\n  // ros::Subscriber gps_sub           = n.subscribe<geometry_msgs::PoseWithCovarianceStamped>(\"/imu_max/pose\", 2, gpscallback);\n  // ros::Subscriber state_out_msf_sub = n.subscribe<sensor_fusion_comm::DoubleArrayStamped>(\"/msf_core/state_out\", 2, state_out_callback);\n  ros::Publisher  poseop_pub        = n.advertise<geometry_msgs::PoseWithCovarianceStamped>(\"/optimized\", 10);\n\n  static ros::Time start_time = ros::Time::now();\n  static ros::Duration cur_time = ros::Time::now()-start_time;\n  static ros::Duration prev_time= cur_time;\n  static double dt = 0.25;  \n\n  poseop_msgs.header.frame_id = \"odom\";\n\n  state_out_msf.data.resize(36);\n  // state.setZero();\n  // Iterate over the simulation steps\n\n\n  state.setZero();\n  for (int k = 0; k < 3; k++)\n    {\n      state[k] = 0;\n    }\n\n\n\n  STATE_LOOCKUP[0][0] = 0;\n  STATE_LOOCKUP[0][1] = 0;\n\n  for(int i=1;i<=4;i++) {\n    /*x*/STATE_LOOCKUP[i][0] = (3.0/4.0)*i;\n    /*y*/STATE_LOOCKUP[i][1] = 0;\n    if(i==1 || i==4) {\n      acc[i] = {16*3/3,0,0};\n      if(i==4) acc[i]*=-1;\n    }else\n      acc[i] = {0,0,0};\n  }\n  for(int i=1;i<=4;i++) {\n    /*x*/STATE_LOOCKUP[i+4][0] = 3.0+(1.0/4.0)*i;\n    /*y*/STATE_LOOCKUP[i+4][1] = -i;\n    if(i==1 || i==4) {\n      acc[i+4] = {16*1/3,-16*4/3,0};\n      if(i==4) acc[i+4]*=-1;\n    }else\n      acc[i+4] = {0,0,0};\n  }\n  for(int i=1;i<=4;i++) {\n    /*x*/STATE_LOOCKUP[i+8][0] = 4.0+ (-3.0/4.0)*i;\n    /*y*/STATE_LOOCKUP[i+8][1] = -4.0 + (1.0/4.0)*i;\n    if(i==1 || i==4) {\n      acc[i+8] = {-16*3/3,16*1/3,0};\n      if(i==4) acc[i+8]*=-1;\n    }else\n      acc[i+8] = {0,0,0};\n  }\n  for(int i=1;i<=4;i++) {\n    /*x*/STATE_LOOCKUP[i+12][0] = 1.0;\n    /*y*/STATE_LOOCKUP[i+12][1] = -3.0+i;\n    if(i==1 || i==4) {\n      acc[i+12] = {16*0/3,16*4/3,0};\n      if(i==4) acc[i+12]*=-1;\n    }else\n      acc[i+12] = {0,0,0};\n  }\n\n  for(int i=0;i<17;i++) {\n   saytab(acc[i][0]); sayend(acc[i][1]);\n }\n\n\n  while(ros::ok() && Iterate <= 3)\n    {\n\n        gps[Iterate+1][0] = GPS_lOOCKUP[Iterate+1][0];\n        gps[Iterate+1][1] = GPS_lOOCKUP[Iterate+1][1];\n        gps[Iterate+1][2] = 0;\n\n        for(int i = 1;i<=4;i++) {\n          msf_state[Iterate*4+i][0] = STATE_LOOCKUP[Iterate*4+i][0];\n          msf_state[Iterate*4+i][1] = STATE_LOOCKUP[Iterate*4+i][1];\n          msf_state[Iterate*4+i][2] = 0;\n          msf_state[Iterate*4+i][3] = 0;\n          msf_state[Iterate*4+i][4] = 0;\n          msf_state[Iterate*4+i][5] = 0;\n          // Numstate++;\n        }\n        \n        Iterate ++;\n      }\n        saytab(\"START Iterate = \");sayend(Iterate);\n        Optimize_test(dt);\n        sayend(\"END\");\n        \n    \n}\n\n\n\nvoid Optimize_test(double dt) {\n // Set up the parameters of the simulation\n  int numberOfTimeSteps = NUM_ITERATE;\n  const double processNoiseSigma = 0.05;\n  const double accelerometerNoiseSigma = 0.01;\n  const double gpsNoiseSigma = 0.001;\n  // const double dt = 1;  \n\n  // Set up the optimiser and block solver\n  SparseOptimizer optimizer;\n  optimizer.setVerbose(false);\n\n  typedef BlockSolver< BlockSolverTraits<6, 6> > BlockSolver;\n  BlockSolver::LinearSolverType * linearSolver\n      = new LinearSolverCholmod<BlockSolver::PoseMatrixType>();\n  BlockSolver* blockSolver = new BlockSolver(linearSolver);\n  OptimizationAlgorithm* optimizationAlgorithm = new OptimizationAlgorithmGaussNewton(blockSolver);\n  optimizer.setAlgorithm(optimizationAlgorithm);\n\n  // Sample the start location of the target\n  \n\n    state = msf_state[0];\n\n  // Construct the first vertex; this corresponds to the initial\n  // condition and register it with the optimiser\n  saytab(\"add vertex state \");sayend(0);\n  VertexPositionVelocity3D* stateNode = new VertexPositionVelocity3D();\n  stateNode->setEstimate(state);\n  stateNode->setId(0);\n  optimizer.addVertex(stateNode);\n\n  // Construct the GPS observation\n  Vector3d gpsMeasurement = gps[0];\n  saytab(\"add edge gps \");sayend(0);\n  // Add the GPS observation\n  GPSObservationEdgePositionVelocity3D* goe = new GPSObservationEdgePositionVelocity3D(gpsMeasurement, gpsNoiseSigma);\n  goe->setMeasurement(gpsMeasurement);\n  goe->setVertex(0, stateNode);\n  optimizer.addEdge(goe);\n\n  // Construct the msf observation\n  Vector3d msfMeasurement(0,0,0);\n\n  saytab(\"add edge statemsf \");sayend(0);\n  // Add the msf observation\n  GPSObservationEdgePositionVelocity3D* goe2 = new GPSObservationEdgePositionVelocity3D(msfMeasurement, 0.1);\n  goe2->setMeasurement(msfMeasurement);\n  goe2->setVertex(0, stateNode);\n  optimizer.addEdge(goe2);\n\n\n  // Set up last estimate\n  VertexPositionVelocity3D* lastStateNode = stateNode;\n\n  // Iterate over the simulation steps\n  for (int k = 0; k < Iterate; ++k)\n    {   \n      for(int j = 1; j <= 4/*Numstate per round*/; j++) \n      {\n        // saytab(j);saytab(Numstate);sayend(Iterate);\n\n          // state = msf_state[k*4+j];\n        \n\n          // Construct vertex which corresponds to the current state of the target\n          VertexPositionVelocity3D* stateNode = new VertexPositionVelocity3D();\n          \n          stateNode->setId(k*4+j);\n          stateNode->setEstimate(state);\n          stateNode->setMarginalized(false);\n          optimizer.addVertex(stateNode);\n\n          saytab(\"add vertex state \");sayend(k*4+j);\n\n\n\n\n\n\n\n\n\n\n\n\n          // // Construct the accelerometer measurement\n          Vector3d accelerometerMeasurement/*(msf_state[k*4+j][0],msf_state[k*4+j][1],0);//*/ = acc[k*4+j];\n\n          TargetOdometry3DEdge* toe = new TargetOdometry3DEdge(dt, accelerometerNoiseSigma);\n          toe->setVertex(0, lastStateNode);\n          toe->setVertex(1, stateNode);\n          VertexPositionVelocity3D* vPrev= dynamic_cast<VertexPositionVelocity3D*>(lastStateNode);\n          VertexPositionVelocity3D* vCurr= dynamic_cast<VertexPositionVelocity3D*>(stateNode);\n          toe->setMeasurement(accelerometerMeasurement);\n          optimizer.addEdge(toe);\n          // compute the initial guess via the odometry\n          g2o::OptimizableGraph::VertexSet vPrevSet;\n          vPrevSet.insert(vPrev);\n          toe->initialEstimate(vPrevSet,vCurr);\n\n          lastStateNode = stateNode;\n      }\n                // Construct the msf observation\n          Vector3d gpsMeasurement2 = gps[k+1];\n\n          // Add the msf observation\n          GPSObservationEdgePositionVelocity3D* goe2 = new GPSObservationEdgePositionVelocity3D(gpsMeasurement2, 0.1);\n          goe2->setMeasurement(gpsMeasurement2);\n          goe2->setVertex(0, stateNode);\n          optimizer.addEdge(goe2);\n\n\n        // Construct the GPS observation\n        Vector3d gpsMeasurement = gps[k+1];\n\n      saytab(\"add edge gps \");sayend(k+1);\n      // Add the GPS observation\n      GPSObservationEdgePositionVelocity3D* goe = new GPSObservationEdgePositionVelocity3D(gpsMeasurement, gpsNoiseSigma);\n      goe->setMeasurement(gpsMeasurement);\n      goe->setVertex(0, stateNode);\n      optimizer.addEdge(goe);\n    }\n\n  // Configure and set things going\n  optimizer.initializeOptimization();\n  optimizer.setVerbose(true);\n  optimizer.optimize(5);\n  cerr << \"number of vertices:\" << optimizer.vertices().size() << endl;\n  cerr << \"number of edges:\" << optimizer.edges().size() << endl;\n\n  // Print the results\n\n  // cout << \"state=\\n\" << state << endl;\n\n#if 0\n  for (int k = 0; k < numberOfTimeSteps; k++)\n    {\n      cout << \"computed estimate \" << k << \"\\n\"\n           << dynamic_cast<VertexPositionVelocity3D*>(optimizer.vertices().find(k)->second)->estimate() << endl;\n       }\n#endif\n\n  // Vector6d v1 = dynamic_cast<VertexPositionVelocity3D*>(optimizer.vertices().find((std::max)(numberOfTimeSteps-2,0))->second)->estimate();\n  // Vector6d v2 = dynamic_cast<VertexPositionVelocity3D*>(optimizer.vertices().find((std::max)(numberOfTimeSteps-1,0))->second)->estimate();\n  // cout << \"v1=\\n\" << v1 << endl;\n  // cout << \"v2=\\n\" << v2 << endl;\n  // cout << \"delta state=\\n\" << v2-v1 << endl;\n       // Vector6d v[4];\n       Vector6d v[17];\n       for(int i=0;i<17;i++)\n          v[i] = dynamic_cast<VertexPositionVelocity3D*>(optimizer.vertices().find(i)->second)->estimate();\n      for(int i=0;i<17;i++)\n       cout << v[i][0] << \"\\t\" << v[i][1] <<endl;\n\n      cout << endl;\n      cout << endl;\n      cout << endl;\n      for(int i=0;i<17;i++)\n       cout << msf_state[i][0] << \"\\t\" << msf_state[i][1] <<endl;\n\n      cout << endl;\n      cout << endl;\n      cout << endl;\n      for(int i=0;i<5;i++)\n        cout << gps[i][0] << \"\\t\" << gps[i][1] <<endl;\n       // poseop_msgs.header.stamp = ros::Time::now();\n       // poseop_msgs.pose.pose.position.x = v[0];\n       // poseop_msgs.pose.pose.position.y = v[1];\n       // poseop_msgs.pose.pose.position.z = v[2];\n       \n       // poseop_msgs.pose.pose.orientation = imu.orientation;\n\n\n      SparseBlockMatrix<MatrixXd> spinv;\n\n      optimizer.computeMarginals(spinv, stateNode);\n\n\n\n      //optimizer.solver()->computeMarginals();\n\n      // covariance\n      //\n      cout << \"covariance\\n\" << spinv << endl;\n\n      // for(int u =0;u<6;u++)\n      //   for(int v=0;v<6;v++)\n      //     poseop_msgs.pose.covariance[6*u+v] = spinv(u, v);\n      poseop_msgs.pose.covariance[0]=0.1;\n      poseop_msgs.pose.covariance[7]=0.1;\n      poseop_msgs.pose.covariance[14]=0.1;\n      poseop_msgs.pose.covariance[21]=0.1;\n      poseop_msgs.pose.covariance[28]=0.1;\n      poseop_msgs.pose.covariance[35]=0.1;\n      \n}\n\n\n\n\n\n\n\n\n\n// #ifndef G2O_TARGET_TYPES_6D_HPP_\n// #define G2O_TARGET_TYPES_6D_HPP_\n\n// #include <g2o/core/base_vertex.h>\n// #include <g2o/core/base_binary_edge.h>\n// #include <g2o/core/base_unary_edge.h>\n// #include <Eigen/Core>\n\n// using namespace g2o;\n\n// typedef Eigen::Matrix<double,6,1> Vector6d;\n// typedef Eigen::Matrix<double,6,6> Matrix6d;\n\n// // This header file specifies a set of types for the different\n// // tracking examples; note that \n\n// class VertexPosition3D : public g2o::BaseVertex<3, Eigen::Vector3d>\n// {\n// public:\n//   EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n//   VertexPosition3D()\n//   {\n//   }\n  \n//   virtual void setToOriginImpl() {\n//     _estimate.setZero();\n//   }\n  \n//   virtual void oplusImpl(const double* update)\n//   {\n//     _estimate[0] += update[0];\n//     _estimate[1] += update[1];\n//     _estimate[2] += update[2];\n//   }\n  \n//   virtual bool read(std::istream& /*is*/)\n//   {\n//     return false;\n//   }\n  \n//   virtual bool write(std::ostream& /*os*/) const\n//   {\n//     return false;\n//   }\n  \n// };\n\n// class PositionVelocity3DEdge\n// {\n// };\n \n// class VertexPositionVelocity3D : public g2o::BaseVertex<6, Vector6d>\n// {\n// public:\n//   EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n//   VertexPositionVelocity3D()\n//   {\n//   }\n  \n//   virtual void setToOriginImpl() {\n//     _estimate.setZero();\n//   }\n  \n//   virtual void oplusImpl(const double* update)\n//   {\n//     for (int k = 0; k < 6; k++)\n//       _estimate[k] += update[k];\n//   }\n  \n\n//   virtual bool read(std::istream& /*is*/)\n//   {\n//     return false;\n//   }\n  \n//   virtual bool write(std::ostream& /*os*/) const\n//   {\n//     return false;\n//   }\n  \n// };\n\n// // The odometry which links pairs of nodes together\n// class TargetOdometry3DEdge : public g2o::BaseBinaryEdge<6, Eigen::Vector3d, VertexPositionVelocity3D, VertexPositionVelocity3D>\n// {\n// public:\n//   TargetOdometry3DEdge(double dt, double noiseSigma)\n//   {\n//     _dt = dt;\n\n//     double q = noiseSigma * noiseSigma;\n//     double dt2 = dt * dt;\n\n//     // Process noise covariance matrix; this assumes an \"impulse\"\n//     // noise model; we add a small stabilising term on the diagonal to make it invertible\n//     Matrix6d Q=Matrix6d::Zero();\n//     Q(0, 0) = Q(1,1) = Q(2,2) = dt2*dt2*q/4 + 1e-4;\n//     Q(0, 3) = Q(1, 4) = Q(2, 5) = dt*dt2*q/2;\n//     Q(3, 3) = Q(4,4) = Q(5,5) = dt2 * q + 1e-4;\n//     Q(3, 0) = Q(4, 1) = Q(5, 2) = dt*dt2*q/2;\n\n//     setInformation(Q.inverse());\n//   }\n\n//   /** set the estimate of the to vertex, based on the estimate of the from vertex in the edge. */\n//   virtual void initialEstimate(const g2o::OptimizableGraph::VertexSet& from, g2o::OptimizableGraph::Vertex* to){\n//     assert(from.size() == 1);\n//     const VertexPositionVelocity3D* vi = static_cast<const VertexPositionVelocity3D*>(*from.begin());\n//     VertexPositionVelocity3D* vj = static_cast<VertexPositionVelocity3D*>(to);\n//     Vector6d viEst=vi->estimate();\n//     Vector6d vjEst=viEst;\n\n//     for (int m = 0; m < 3; m++)\n//     {\n//       vjEst[m] += _dt * (vjEst[m+3] + 0.5 * _dt * _dt* _measurement[m]);\n//     }\n\n//     for (int m = 0; m < 3; m++)\n//     {\n//       vjEst[m+3] =0;//+= _dt * _measurement[m];\n//     }\n\n//     vjEst[0] = _measurement[0];\n//     vjEst[1] = _measurement[1];\n//     vjEst[2] = 0;\n//     vj->setEstimate(vjEst);\n//   }\n\n//   /** override in your class if it's not possible to initialize the vertices in certain combinations */\n//   virtual double initialEstimatePossible(const g2o::OptimizableGraph::VertexSet& from, g2o::OptimizableGraph::Vertex* to) {\n//     //only works on sequential vertices\n//     const VertexPositionVelocity3D* vi = static_cast<const VertexPositionVelocity3D*>(*from.begin());\n//     return (to->id() - vi->id() == 1) ? 1.0 : -1.0;\n//   }\n\n\n//   void computeError()\n//   {\n//     const VertexPositionVelocity3D* vi = static_cast<const VertexPositionVelocity3D*>(_vertices[0]);\n//     const VertexPositionVelocity3D* vj = static_cast<const VertexPositionVelocity3D*>(_vertices[1]);\n    \n//     for (int k = 0; k < 3; k++)\n//       {\n//         _error[k] = vi->estimate()[k] /*+ _dt * (vi->estimate()[k+3] + 0.5 * _dt * _measurement[k]) - vj->estimate()[k]*/-_measurement[k];\n//       }\n//     for (int k = 3; k < 6; k++)\n//       {\n//         _error[k] = 0;//vi->estimate()[k] + _dt * _measurement[k-3]- vj->estimate()[k];\n//       }\n//   }\n  \n//   virtual bool read(std::istream& /*is*/)\n//   {\n//     return false;\n//   }\n  \n//   virtual bool write(std::ostream& /*os*/) const\n//   {\n//     return false;\n//   }\n\n// private:\n//   double _dt;\n// };\n\n// // The GPS \n// class GPSObservationEdgePositionVelocity3D : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, VertexPositionVelocity3D>\n// {\n// public:\n//   GPSObservationEdgePositionVelocity3D(const Eigen::Vector3d& measurement, double noiseSigma)\n//   {\n//     setMeasurement(measurement);\n//     setInformation(Eigen::Matrix3d::Identity() / (noiseSigma*noiseSigma));\n//   }\n  \n//   void computeError()\n//   {\n//     const VertexPositionVelocity3D* v = static_cast<const VertexPositionVelocity3D*>(_vertices[0]);\n//     for (int k = 0; k < 3; k++)\n//       {\n//         _error[k] = v->estimate()[k] - _measurement[k];\n//       }    \n//   }\n  \n//   virtual bool read(std::istream& /*is*/)\n//   {\n//     return false;\n//   }\n  \n//   virtual bool write(std::ostream& /*os*/) const\n//   {\n//     return false;\n//   }\n// };\n\n\n// #endif //  __TARGET_TYPES_6D_HPP__\n", "meta": {"hexsha": "c19dc2f6108bf18122471a72092f68390a3e5934", "size": 19956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "data/crossover_nav/src/simulate_optimize_gps.cpp", "max_stars_repo_name": "khairulislam/phys", "max_stars_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "data/crossover_nav/src/simulate_optimize_gps.cpp", "max_issues_repo_name": "khairulislam/phys", "max_issues_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "data/crossover_nav/src/simulate_optimize_gps.cpp", "max_forks_repo_name": "khairulislam/phys", "max_forks_repo_head_hexsha": "fc702520fcd3b23022b9253e7d94f878978b4500", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3039647577, "max_line_length": 141, "alphanum_fraction": 0.614251353, "num_tokens": 6106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.22659550075301946}}
{"text": "// Volumetric3D_EMC.cpp\n// created by Kuangdai on 16-May-2017 \n// genetral Volumetric3D model with IRIS-EMC format\n\n#include \"Volumetric3D_EMC.h\"\n#include <sstream>\n#include \"XMPI.h\"\n#include \"XMath.h\"\n#include \"Geodesy.h\"\n#include \"Parameters.h\"\n#include \"NetCDF_Reader.h\"\n#include \"NetCDF_ReaderAscii.h\"\n\n#include <dirent.h>\n#include <sys/types.h>\n#include <boost/algorithm/string.hpp>\n#include <boost/lexical_cast.hpp>\n#include <algorithm>\n\nbool compareFunc(const std::pair<std::string, float> &a, \n    const std::pair<std::string, float> &b) {\n    return a.second < b.second;\n}\n\nvoid Volumetric3D_EMC::initialize() {\n    // meta data\n    Eigen::Matrix<float, Eigen::Dynamic, 1> fdata, fdep, flat, flon;\n    if (XMPI::root()) {\n        std::vector<size_t> dims;\n        std::string fname = Parameters::sInputDirectory + \"/\" + mFileName;\n        if (mOneFilePerDepth) {\n            // get all files\n            DIR *dir = opendir(fname.c_str());\n            if (!dir) {\n                throw std::runtime_error(\"Volumetric3D_EMC::initialize || \" \n                    \"Error opening directory of data files || Directory = \" + fname);    \n            }\n            struct dirent *entry;\n            std::vector<std::pair<std::string, float>> fileDepth;\n            while ((entry = readdir(dir)) != NULL) {\n                // file name\n                std::string fn(entry->d_name);\n                if (fn.find(\".grd\") == std::string::npos) {\n                    continue;\n                }\n                // depth\n                std::string depthStr(fn);\n                boost::replace_first(depthStr, \".grd\", \"\");\n                std::size_t found = depthStr.find_last_of(\"_\");\n                if (found == std::string::npos) {\n                    throw std::runtime_error(\"Volumetric3D_EMC::initialize || \" \n                        \"Error processing file name || File = \" + fn);    \n                }\n                depthStr = depthStr.substr(found + 1);\n                float depth = 0.;\n                try {\n                    depth = boost::lexical_cast<float>(depthStr);\n                } catch (std::exception) {\n                    throw std::runtime_error(\"Volumetric3D_EMC::initialize || \" \n                        \"Error processing file name || File = \" + fn);\n                }\n                // add pair\n                fileDepth.push_back(std::make_pair(fname + \"/\" + fn, depth));\n            }\n            closedir(dir);\n            \n            // sort depth\n            std::sort(fileDepth.begin(), fileDepth.end(), compareFunc);\n            \n            // read lat and lon\n            Eigen::Matrix<double, Eigen::Dynamic, 1> dlat, dlon;\n            if (NetCDF_Reader::checkNetCDF_isAscii(fileDepth[0].first)) {\n                NetCDF_ReaderAscii reader;\n                reader.open(fileDepth[0].first);\n                reader.read1D(\"lat\", dlat);\n                reader.read1D(\"lon\", dlon);\n                reader.close();\n            } else {\n                NetCDF_Reader reader;\n                reader.open(fileDepth[0].first);\n                reader.read1D(\"lat\", dlat);\n                reader.read1D(\"lon\", dlon);\n                reader.close();\n            }\n            flat = dlat.cast<float>();\n            flon = dlon.cast<float>();\n            \n            // depths and data\n            size_t depthLen = flat.size() * flon.size();   \n            size_t totalLen = depthLen * fileDepth.size();\n            fdep.resize(fileDepth.size());\n            fdata.resize(totalLen);\n            for (int i = 0; i < fileDepth.size(); i++) {\n                fdep(i) = fileDepth[i].second;\n                Eigen::Matrix<float, Eigen::Dynamic, 1> temp;\n                if (NetCDF_Reader::checkNetCDF_isAscii(fileDepth[i].first)) {\n                    NetCDF_ReaderAscii reader;\n                    reader.open(fileDepth[i].first);\n                    reader.readMetaData(mVarName, temp, dims);\n                    reader.close();\n                } else {\n                    NetCDF_Reader reader;\n                    reader.open(fileDepth[i].first);\n                    reader.readMetaData(mVarName, temp, dims);\n                    reader.close();\n                }\n                fdata.block(i * depthLen, 0, depthLen, 1) = temp;\n            }\n            dims.insert(dims.begin(), fdep.size());\n            \n            // perturbations are given in percentage\n            fdata *= .01f;\n        } else {\n            if (NetCDF_Reader::checkNetCDF_isAscii(fname)) {\n                NetCDF_ReaderAscii reader;\n                reader.open(fname);\n                reader.read1D(\"depth\", fdep);\n                reader.read1D(\"latitude\", flat);\n                reader.read1D(\"longitude\", flon);\n                reader.readMetaData(mVarName, fdata, dims);\n                reader.close();\n            } else {\n                NetCDF_Reader reader;\n                reader.open(fname);\n                reader.read1D(\"depth\", fdep);\n                reader.read1D(\"latitude\", flat);\n                reader.read1D(\"longitude\", flon);\n                reader.readMetaData(mVarName, fdata, dims);\n                reader.close();\n            }\n        }\n        \n        // check dimensions\n        if (dims.size() != 3) {\n            throw std::runtime_error(\"Volumetric3D_EMC::initialize || Inconsistent data dimensions || \"\n                \"File/Directory = \" + fname);\n        }\n        if (dims[0] != fdep.size() || dims[1] != flat.size() || dims[2] != flon.size()) {\n            throw std::runtime_error(\"Volumetric3D_EMC::initialize || Inconsistent data dimensions || \"\n                \"File/Directory = \" + fname);\n        }\n        if (!XMath::sortedAscending(fdep) || !XMath::sortedAscending(flat) || !XMath::sortedAscending(flon)) {\n            throw std::runtime_error(\"Volumetric3D_EMC::initialize || Grid coordinates are not sorted ascendingly || \"\n                \"File/Directory = \" + fname);\n        }\n    }\n    XMPI::bcastEigen(fdep);\n    XMPI::bcastEigen(flat);\n    XMPI::bcastEigen(flon);\n    XMPI::bcastEigen(fdata);\n    \n    mGridDep = fdep.cast<double>();\n    mGridLat = flat.cast<double>();\n    mGridLon = flon.cast<double>();\n    RDColX data = fdata.cast<double>();\n    \n    // SI\n    mGridDep *= 1e3;\n    if (mReferenceType == Volumetric3D::MaterialRefType::Absolute) {\n        // convert to SI\n        data *= MaterialPropertyAbsSI[mMaterialProp];\n    }\n    \n    // apply factor\n    data *= mFactor;\n    \n    // special flag\n    if (!boost::iequals(mModelFlag, \"none\")) {\n        if (boost::iequals(mModelFlag, \"abs\")) {\n            data.array() = data.array().abs();\n            data *= mModelFlagFactor;\n        } else if (boost::iequals(mModelFlag, \"pow\")) {\n            double absmax = data.array().abs().maxCoeff();\n            double scalefact = std::abs(absmax / std::pow(absmax, mModelFlagFactor));\n            data.array() = data.array().sign() * (data.array().abs().pow(mModelFlagFactor) * scalefact);\n        } else {\n            throw std::runtime_error(\"Volumetric3D_EMC::initialize || \"\n                \"Unknown special model flag, flag = \" + mModelFlag);\n        }\n    }\n    \n    // reshape data\n    int pos = 0;\n    for (int i = 0; i < mGridDep.size(); i++) {\n        RDMatXX mat(mGridLat.size(), mGridLon.size());\n        for (int j = 0; j < mGridLat.size(); j++) {\n            for (int k = 0; k < mGridLon.size(); k++) {\n                mat(j, k) = data(pos++);\n            }\n        }\n        mGridData.push_back(mat);\n    }\n}\n\nvoid Volumetric3D_EMC::initialize(const std::vector<std::string> &params) {\n    if (params.size() < 4) throw std::runtime_error(\"Volumetric3D_EMC::initialize || \"\n        \"Not enough parameters to initialize a Volumetric3D_EMC object, at least 4 needed.\");\n    \n    const std::string source = \"Volumetric3D_EMC::initialize\";\n        \n    // initialize data\n    Parameters::castValue(mFileName, params[0], source);\n    Parameters::castValue(mVarName, params[1], source);\n    \n    // property name\n    bool found = false;\n    for (int i = 0; i < Volumetric3D::MaterialPropertyString.size(); i++) {\n        if (boost::iequals(params[2], Volumetric3D::MaterialPropertyString[i])) {\n            mMaterialProp = Volumetric3D::MaterialProperty(i);\n            found = true;\n            break;\n        }\n    }\n    if (!found) {\n        throw std::runtime_error(\"Volumetric3D_EMC::initialize || \"\n            \"Unknown material property, name = \" + params[2]);\n    }\n    \n    // reference type\n    found = false;\n    for (int i = 0; i < Volumetric3D::MaterialRefTypeString.size(); i++) {\n        if (boost::iequals(params[3], Volumetric3D::MaterialRefTypeString[i]) ||\n            boost::iequals(params[3], Volumetric3D::MaterialRefTypeStringShort[i])) {\n            mReferenceType = Volumetric3D::MaterialRefType(i);\n            found = true;\n            break;\n        }\n    }\n    if (!found) {\n        throw std::runtime_error(\"Volumetric3D_EMC::initialize || \"\n            \"Unknown material reference type, type = \" + params[3]);\n    }\n    \n    try {\n        int ipar = 4;\n        Parameters::castValue(mFactor, params.at(ipar++), source);\n        Parameters::castValue(mGeographic, params.at(ipar++), source);\n        Parameters::castValue(mOneFilePerDepth, params.at(ipar++), source);\n        Parameters::castValue(mVerticalDiscontinuities, params.at(ipar++), source);\n        Parameters::castValue(mModelFlag, params.at(ipar++), source);\n        Parameters::castValue(mModelFlagFactor, params.at(ipar++), source);\n    } catch (std::out_of_range) {\n        // nothing\n    }\n    \n    if (!boost::iequals(mModelFlag, \"none\")) {\n        if (mReferenceType == MaterialRefType::Absolute) {\n            throw std::runtime_error(\"Volumetric3D_EMC::initialize || \"\n                \"Imposing special model flag on an absolute model.\");\n        }\n    }\n    initialize();\n}\n\nbool Volumetric3D_EMC::get3dProperties(double r, double theta, double phi, double rElemCenter,\n    std::vector<MaterialProperty> &properties, \n    std::vector<MaterialRefType> &refTypes,\n    std::vector<double> &values) const {\n    \n    // header\n    properties = std::vector<MaterialProperty>(1, mMaterialProp);\n    refTypes = std::vector<MaterialRefType>(1, mReferenceType);\n    values = std::vector<double>(1, 0.);\n        \n    // to geocentric\n    if (mGeographic) {\n        // which radius to use?\n        theta = pi / 2. - Geodesy::theta2Lat_d(theta, 0.) * degree;\n    }\n    \n    // regularise\n    double dep = Geodesy::getROuter() - r;\n    double lat = 90. - theta / degree;\n    double lon = phi / degree;\n    XMath::checkLimits(dep, 0., Geodesy::getROuter());\n    XMath::checkLimits(lat, -90., 90.);\n    if (mGridLon[0] < 0.) {\n        // lon starts from -180.\n        if (lon > 180.) {\n            lon -= 360.;\n        }\n        XMath::checkLimits(lon, -180., 180.);\n    } else {\n        // lon starts from 0.\n        XMath::checkLimits(lon, 0., 360.);\n    }\n    \n    // check center\n    double dmin = mGridDep[0];\n    double dmax = mGridDep[mGridDep.size() - 1];\n    double dcenter = Geodesy::getROuter() - rElemCenter;\n    if (dcenter < dmin || dcenter > dmax) {\n        return false;\n    }\n    if (dep < dmin && dep > dmin * 0.999999) {\n        dep = dmin;\n    }\n    if (dep > dmax && dep < dmax * 1.000001) {\n        dep = dmax;\n    }\n    \n    // interpolation\n    int ldep0, llat0, llon0, ldep1, llat1, llon1;\n    double wdep0, wlat0, wlon0, wdep1, wlat1, wlon1;\n    if (mVerticalDiscontinuities) {\n        // use element center depth to locate layer\n        XMath::interpLinear(dcenter, mGridDep, ldep0, wdep0);\n        if (ldep0 < 0) {\n            return false;\n        }\n        // use point depth to determine value\n        wdep0 = 1. - 1. / (mGridDep(ldep0 + 1) - mGridDep(ldep0)) * (dep - mGridDep(ldep0));\n    } else {\n        XMath::interpLinear(dep, mGridDep, ldep0, wdep0);\n    }\n    XMath::interpLinear(lat, mGridLat, llat0, wlat0);\n    XMath::interpLinear(lon, mGridLon, llon0, wlon0);    \n    if (ldep0 < 0 || llat0 < 0 || llon0 < 0) {\n        return false;\n    }\n    \n    ldep1 = ldep0 + 1;\n    llat1 = llat0 + 1;\n    llon1 = llon0 + 1;\n    wdep1 = 1. - wdep0;\n    wlat1 = 1. - wlat0;\n    wlon1 = 1. - wlon0;\n    \n    values[0] += mGridData[ldep0](llat0, llon0) * wdep0 * wlat0 * wlon0;\n    values[0] += mGridData[ldep0](llat1, llon0) * wdep0 * wlat1 * wlon0;\n    values[0] += mGridData[ldep0](llat0, llon1) * wdep0 * wlat0 * wlon1;\n    values[0] += mGridData[ldep0](llat1, llon1) * wdep0 * wlat1 * wlon1;\n    values[0] += mGridData[ldep1](llat0, llon0) * wdep1 * wlat0 * wlon0;\n    values[0] += mGridData[ldep1](llat1, llon0) * wdep1 * wlat1 * wlon0;\n    values[0] += mGridData[ldep1](llat0, llon1) * wdep1 * wlat0 * wlon1;\n    values[0] += mGridData[ldep1](llat1, llon1) * wdep1 * wlat1 * wlon1;\n    return true;\n}\n\nstd::string Volumetric3D_EMC::verbose() const {\n    std::stringstream ss;\n    ss << \"\\n======================= 3D Volumetric =======================\" << std::endl;\n    ss << \"  Model Name           =   EMC\" << std::endl;\n    ss << \"  Data File            =   \" << mFileName << std::endl;\n    ss << \"  Variable Name        =   \" << mVarName << std::endl;\n    ss << \"  Material Property    =   \" << MaterialPropertyString[mMaterialProp] << std::endl;\n    ss << \"  Reference Type       =   \" << MaterialRefTypeString[mReferenceType] << std::endl;\n    ss << \"  Num. Depths          =   \" << mGridDep.size() << std::endl;\n    ss << \"  Num. Latitudes       =   \" << mGridLat.size() << std::endl;\n    ss << \"  Num. Longitudes      =   \" << mGridLon.size() << std::endl;\n    ss << \"  Depth Range          =   [\" << mGridDep.minCoeff() << \", \" << mGridDep.maxCoeff() << \"]\" << std::endl;\n    ss << \"  Latitude Range       =   [\" << mGridLat.minCoeff() << \", \" << mGridLat.maxCoeff() << \"]\" << std::endl;\n    ss << \"  Longitude Range      =   [\" << mGridLon.minCoeff() << \", \" << mGridLon.maxCoeff() << \"]\" << std::endl;\n    ss << \"  Factor               =   \" << mFactor << std::endl;\n    ss << \"  Use Geographic       =   \" << (mGeographic ? \"YES\" : \"NO\") << std::endl;\n    ss << \"  One File per Depth   =   \" << (mOneFilePerDepth ? \"YES\" : \"NO\") << std::endl;\n    if (!boost::iequals(mModelFlag, \"none\")) {\n        ss << \"  Special Model Flag   =   \" << mModelFlag << std::endl;\n        ss << \"  Model Flag Factor    =   \" << mModelFlagFactor << std::endl;\n    }\n    ss << \"======================= 3D Volumetric =======================\\n\" << std::endl;\n    return ss.str();\n}\n\n\n\n", "meta": {"hexsha": "8306f5861b5ff3e99fc54651890de3a158555d11", "size": 14464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SOLVER/src/3d_model/3d_volumetric/EMC/Volumetric3D_EMC.cpp", "max_stars_repo_name": "kuangdai/AxiSEM3D", "max_stars_repo_head_hexsha": "fd9da14e9107783e3b07b936c67af2412146e099", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2016-12-16T03:13:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-15T01:56:45.000Z", "max_issues_repo_path": "SOLVER/src/3d_model/3d_volumetric/EMC/Volumetric3D_EMC.cpp", "max_issues_repo_name": "syzeng-duduxi/AxiSEM3D", "max_issues_repo_head_hexsha": "fd9da14e9107783e3b07b936c67af2412146e099", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-01-15T17:17:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-18T09:53:58.000Z", "max_forks_repo_path": "SOLVER/src/3d_model/3d_volumetric/EMC/Volumetric3D_EMC.cpp", "max_forks_repo_name": "syzeng-duduxi/AxiSEM3D", "max_forks_repo_head_hexsha": "fd9da14e9107783e3b07b936c67af2412146e099", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2016-12-28T16:55:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-23T01:02:16.000Z", "avg_line_length": 39.4114441417, "max_line_length": 118, "alphanum_fraction": 0.5330475664, "num_tokens": 3944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2265726953073636}}
{"text": "// #ifdef HAVE_CONFIG_H\n// #include \"config.h\"\n// #endif\n\n\n// #include <assert.h>\n// #include <stdlib.h>\n// #include <algorithm>\n// #include <vector>\n// #include <boost/tuple/tuple.hpp>\n// #include <boost/tuple/tuple_comparison.hpp>\n\n// #ifdef _OPENMP\n// #include <omp.h>\n// #endif\n\n// #include <rysq.hpp>\n// #include \"cxx/sugar.hpp\"\n// #include \"quadrature.h\"\n// #include \"memory.h\"\n\n// using namespace rysq;\n\n\n// parallel::Fock::Fock(const Quartet<Shell> &shells) : shells(shells) {} \n\n// parallel::Fock::~Fock() {}\n\n// void parallel::Fock::operator()(const std::vector<Center> &centers,\n// \t\t\t\tconst std::vector<Int4> &quartets,\n// \t\t\t\tconst matrix::Adapter &D,\n// \t\t\t\tmatrix::Adapter &F,\n// \t\t\t\tconst Parameters &parameters) {\n\n//     if (quartets.empty()) return;\n\n// #ifdef _OPENMP\n// #pragma omp parallel \n// #endif\n//     {\n\n\n// #ifdef _OPENMP\n// \tint num_threads = omp_get_num_threads();\n// \tint thread_num = omp_get_thread_num();\n// #else\n// \tint num_threads = 1;\n// \tint thread_num = 0;\n// #endif\n\n// \trysq::Fock fock(this->shells);\n\n// \tint nij = shells.size(0,1);\n// \tint nkl = shells.size(2,3);\n// \tint nik = shells.size(0,2);\n// \tint nil = shells.size(0,3);\n// \tint njk = shells.size(1,2);\n// \tint njl = shells.size(1,3);\n\n// \tmemory::Map<double> myMemory(32*1024);\n\n// #ifdef _OPENMP\n// #pragma omp for schedule(dynamic,1) nowait\n// #endif\n// \tfor (uint q = 0; q < quartets.size(); ++q) {\n\n// \t    int i, j, k, l;\n// \t    util::unpack(quartets[q], i, j, k, l);\n\n// \t    double *Fij = myMemory.get(i, j, nij);\n// \t    double *Fkl = myMemory.get(k, l, nkl);\n// \t    double *Fik = myMemory.get(i, k, nik);\n// \t    double *Fil = myMemory.get(i, l, nil);\n// \t    double *Fjk = myMemory.get(j, k, njk);\n// \t    double *Fjl = myMemory.get(j, l, njl);\n\n// \t    Quartet<Center> C(centers[i], centers[j], centers[k], centers[l]);\n\n// \t    matrix::Density<6> D6 = matrix::index(D, i, j, k, l);\n// \t    double *f[] = { Fij, Fkl, Fik, Fil, Fjk, Fjl };\n// \t    matrix::Fock<6> F6(f);\n\t\t\n// \t    Parameters p = parameters;\n// \t    p.scale /= Quartet<Shell>::symmetry(i, j, k, l);\n\n// \t    // fock(C, D6, F6, p);\n    \n// \t}\n\n// \ttypedef boost::tuple<int,int,double*,size_t> Block;\n// \tstd::vector<Block> blocks;\n// \ttypedef std::vector<Block>::iterator block_it;\n\n// \twhile (!myMemory.empty()) {\n// \t    memory::Map<double>::Entry kv = myMemory.pop();\n// \t    blocks.push_back(Block(kv.j, kv.i, kv.ptr, kv.n));\n// \t}\n// \tstd::sort(blocks.begin(), blocks.end());\n\n// \tstd::vector<block_it> columns;\n// \ttypedef std::vector<block_it>::iterator column_it;\n// \tblock_it it = blocks.begin();\n\n// \twhile (it < blocks.end()) {\n// \t    int j = it->get<0>();\n// \t    columns.push_back(it);\n// \t    while (it < blocks.end() && it->get<0>() == j) ++it;\n// \t}\n// \tcolumns.push_back(it);\t    \n\n// \tfor (int t = 0; t < num_threads; ++t) {\n// \t    int k = (thread_num + t)%num_threads;\n\n// \t    for (column_it col = columns.begin(); col < columns.end() - 1; ++col) {\n// \t\tblock_it block = *col;\n// \t\tint j = block->get<0>(); \n// \t\tif (j%num_threads != k) continue;\n\n// \t\twhile (block < *(col+1)) {\n// \t\t    double *dest = F(block->get<1>(), block->get<0>());\n// \t\t    double *source = block->get<2>();\n// \t\t    size_t size = block->get<3>();\n// \t\t    util::add(size, dest, source);\n// \t\t    ++block;\n// \t\t}\n// \t    }\n// #ifdef _OPENMP\n// #pragma omp barrier\n// #endif\n// \t}\n\n//     }\n\n// }\n", "meta": {"hexsha": "147ce338f7ff40cf063e8f1e942ef0b00232d012", "size": 3375, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamess/libqc/rysq/src/parallel.cpp", "max_stars_repo_name": "andremirt/v_cond", "max_stars_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gamess/libqc/rysq/src/parallel.cpp", "max_issues_repo_name": "andremirt/v_cond", "max_issues_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gamess/libqc/rysq/src/parallel.cpp", "max_forks_repo_name": "andremirt/v_cond", "max_forks_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0, "max_line_length": 79, "alphanum_fraction": 0.5611851852, "num_tokens": 1104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.22646601970491811}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n//  Copyright 2011 John Maddock. Distributed under the Boost\n//  Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_MP_TOMMATH_BACKEND_HPP\n#define BOOST_MATH_MP_TOMMATH_BACKEND_HPP\n\n#include <boost/multiprecision/number.hpp>\n#include <boost/multiprecision/rational_adaptor.hpp>\n#include <boost/multiprecision/detail/integer_ops.hpp>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/scoped_array.hpp>\n#include <tommath.h>\n#include <cmath>\n#include <limits>\n#include <climits>\n\nnamespace boost{ namespace multiprecision{ namespace backends{\n\nnamespace detail{\n\ninline void check_tommath_result(unsigned v)\n{\n   if(v != MP_OKAY)\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(mp_error_to_string(v)));\n   }\n}\n\n}\n\nstruct tommath_int;\n\nvoid eval_multiply(tommath_int& t, const tommath_int& o);\nvoid eval_add(tommath_int& t, const tommath_int& o);\n\nstruct tommath_int\n{\n   typedef mpl::list<boost::int32_t, boost::long_long_type>             signed_types;\n   typedef mpl::list<boost::uint32_t, boost::ulong_long_type>   unsigned_types;\n   typedef mpl::list<long double>                           float_types;\n\n   tommath_int()\n   {\n      detail::check_tommath_result(mp_init(&m_data));\n   }\n   tommath_int(const tommath_int& o)\n   {\n      detail::check_tommath_result(mp_init_copy(&m_data, const_cast< ::mp_int*>(&o.m_data)));\n   }\n#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES\n   tommath_int(tommath_int&& o) BOOST_NOEXCEPT\n   {\n      m_data = o.m_data;\n      o.m_data.dp = 0;\n   }\n   tommath_int& operator = (tommath_int&& o)\n   {\n      mp_exch(&m_data, &o.m_data);\n      return *this;\n   }\n#endif\n   tommath_int& operator = (const tommath_int& o)\n   {\n      if(m_data.dp == 0)\n         detail::check_tommath_result(mp_init(&m_data));\n      if(o.m_data.dp)\n         detail::check_tommath_result(mp_copy(const_cast< ::mp_int*>(&o.m_data), &m_data));\n      return *this;\n   }\n   tommath_int& operator = (boost::ulong_long_type i)\n   {\n      if(m_data.dp == 0)\n         detail::check_tommath_result(mp_init(&m_data));\n      boost::ulong_long_type mask = ((1uLL << std::numeric_limits<unsigned>::digits) - 1);\n      unsigned shift = 0;\n      ::mp_int t;\n      detail::check_tommath_result(mp_init(&t));\n      mp_zero(&m_data);\n      while(i)\n      {\n         detail::check_tommath_result(mp_set_int(&t, static_cast<unsigned>(i & mask)));\n         if(shift)\n            detail::check_tommath_result(mp_mul_2d(&t, shift, &t));\n         detail::check_tommath_result((mp_add(&m_data, &t, &m_data)));\n         shift += std::numeric_limits<unsigned>::digits;\n         i >>= std::numeric_limits<unsigned>::digits;\n      }\n      mp_clear(&t);\n      return *this;\n   }\n   tommath_int& operator = (boost::long_long_type i)\n   {\n      if(m_data.dp == 0)\n         detail::check_tommath_result(mp_init(&m_data));\n      bool neg = i < 0;\n      *this = boost::multiprecision::detail::unsigned_abs(i);\n      if(neg)\n         detail::check_tommath_result(mp_neg(&m_data, &m_data));\n      return *this;\n   }\n   //\n   // Note that although mp_set_int takes an unsigned long as an argument\n   // it only sets the first 32-bits to the result, and ignores the rest.\n   // So use uint32_t as the largest type to pass to this function.\n   //\n   tommath_int& operator = (boost::uint32_t i)\n   {\n      if(m_data.dp == 0)\n         detail::check_tommath_result(mp_init(&m_data));\n      detail::check_tommath_result((mp_set_int(&m_data, i)));\n      return *this;\n   }\n   tommath_int& operator = (boost::int32_t i)\n   {\n      if(m_data.dp == 0)\n         detail::check_tommath_result(mp_init(&m_data));\n      bool neg = i < 0;\n      *this = boost::multiprecision::detail::unsigned_abs(i);\n      if(neg)\n         detail::check_tommath_result(mp_neg(&m_data, &m_data));\n      return *this;\n   }\n   tommath_int& operator = (long double a)\n   {\n      using std::frexp;\n      using std::ldexp;\n      using std::floor;\n\n      if(m_data.dp == 0)\n         detail::check_tommath_result(mp_init(&m_data));\n\n      if (a == 0) {\n         detail::check_tommath_result(mp_set_int(&m_data, 0));\n         return *this;\n      }\n\n      if (a == 1) {\n         detail::check_tommath_result(mp_set_int(&m_data, 1));\n         return *this;\n      }\n\n      BOOST_ASSERT(!(boost::math::isinf)(a));\n      BOOST_ASSERT(!(boost::math::isnan)(a));\n\n      int e;\n      long double f, term;\n      detail::check_tommath_result(mp_set_int(&m_data, 0u));\n      ::mp_int t;\n      detail::check_tommath_result(mp_init(&t));\n\n      f = frexp(a, &e);\n\n      static const int shift = std::numeric_limits<int>::digits - 1;\n\n      while(f)\n      {\n         // extract int sized bits from f:\n         f = ldexp(f, shift);\n         term = floor(f);\n         e -= shift;\n         detail::check_tommath_result(mp_mul_2d(&m_data, shift, &m_data));\n         if(term > 0)\n         {\n            detail::check_tommath_result(mp_set_int(&t, static_cast<int>(term)));\n            detail::check_tommath_result(mp_add(&m_data, &t, &m_data));\n         }\n         else\n         {\n            detail::check_tommath_result(mp_set_int(&t, static_cast<int>(-term)));\n            detail::check_tommath_result(mp_sub(&m_data, &t, &m_data));\n         }\n         f -= term;\n      }\n      if(e > 0)\n         detail::check_tommath_result(mp_mul_2d(&m_data, e, &m_data));\n      else if(e < 0)\n      {\n         tommath_int t2;\n         detail::check_tommath_result(mp_div_2d(&m_data, -e, &m_data, &t2.data()));\n      }\n      mp_clear(&t);\n      return *this;\n   }\n   tommath_int& operator = (const char* s)\n   {\n      //\n      // We don't use libtommath's own routine because it doesn't error check the input :-(\n      //\n      if(m_data.dp == 0)\n         detail::check_tommath_result(mp_init(&m_data));\n      std::size_t n = s ? std::strlen(s) : 0;\n      *this = static_cast<boost::uint32_t>(0u);\n      unsigned radix = 10;\n      bool isneg = false;\n      if(n && (*s == '-'))\n      {\n         --n;\n         ++s;\n         isneg = true;\n      }\n      if(n && (*s == '0'))\n      {\n         if((n > 1) && ((s[1] == 'x') || (s[1] == 'X')))\n         {\n            radix = 16;\n            s +=2;\n            n -= 2;\n         }\n         else\n         {\n            radix = 8;\n            n -= 1;\n         }\n      }\n      if(n)\n      {\n         if(radix == 8 || radix == 16)\n         {\n            unsigned shift = radix == 8 ? 3 : 4;\n            unsigned block_count = DIGIT_BIT / shift;\n            unsigned block_shift = shift * block_count;\n            boost::ulong_long_type val, block;\n            while(*s)\n            {\n               block = 0;\n               for(unsigned i = 0; (i < block_count); ++i)\n               {\n                  if(*s >= '0' && *s <= '9')\n                     val = *s - '0';\n                  else if(*s >= 'a' && *s <= 'f')\n                     val = 10 + *s - 'a';\n                  else if(*s >= 'A' && *s <= 'F')\n                     val = 10 + *s - 'A';\n                  else\n                     val = 400;\n                  if(val > radix)\n                  {\n                     BOOST_THROW_EXCEPTION(std::runtime_error(\"Unexpected content found while parsing character string.\"));\n                  }\n                  block <<= shift;\n                  block |= val;\n                  if(!*++s)\n                  {\n                     // final shift is different:\n                     block_shift = (i + 1) * shift;\n                     break;\n                  }\n               }\n               detail::check_tommath_result(mp_mul_2d(&data(), block_shift, &data()));\n               if(data().used)\n                  data().dp[0] |= block;\n               else\n                  *this = block;\n            }\n         }\n         else\n         {\n            // Base 10, we extract blocks of size 10^9 at a time, that way\n            // the number of multiplications is kept to a minimum:\n            boost::uint32_t block_mult = 1000000000;\n            while(*s)\n            {\n               boost::uint32_t block = 0;\n               for(unsigned i = 0; i < 9; ++i)\n               {\n                  boost::uint32_t val;\n                  if(*s >= '0' && *s <= '9')\n                     val = *s - '0';\n                  else\n                     BOOST_THROW_EXCEPTION(std::runtime_error(\"Unexpected character encountered in input.\"));\n                  block *= 10;\n                  block += val;\n                  if(!*++s)\n                  {\n                     static const boost::uint32_t block_multiplier[9]  = { 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };\n                     block_mult = block_multiplier[i];\n                     break;\n                  }\n               }\n               tommath_int t;\n               t = block_mult;\n               eval_multiply(*this, t);\n               t = block;\n               eval_add(*this, t);\n            }\n         }\n      }\n      if(isneg)\n         this->negate();\n      return *this;\n   }\n   std::string str(std::streamsize /*digits*/, std::ios_base::fmtflags f)const\n   {\n      BOOST_ASSERT(m_data.dp);\n      int base = 10;\n      if((f & std::ios_base::oct) == std::ios_base::oct)\n         base = 8;\n      else if((f & std::ios_base::hex) == std::ios_base::hex)\n         base = 16;\n      //\n      // sanity check, bases 8 and 16 are only available for positive numbers:\n      //\n      if((base != 10) && m_data.sign)\n         BOOST_THROW_EXCEPTION(std::runtime_error(\"Formatted output in bases 8 or 16 is only available for positive numbers\"));\n      int s;\n      detail::check_tommath_result(mp_radix_size(const_cast< ::mp_int*>(&m_data), base, &s));\n      boost::scoped_array<char> a(new char[s+1]);\n      detail::check_tommath_result(mp_toradix_n(const_cast< ::mp_int*>(&m_data), a.get(), base, s+1));\n      std::string result = a.get();\n      if((base != 10) && (f & std::ios_base::showbase))\n      {\n         int pos = result[0] == '-' ? 1 : 0;\n         const char* pp = base == 8 ? \"0\" : \"0x\";\n         result.insert(static_cast<std::string::size_type>(pos), pp);\n      }\n      if((f & std::ios_base::showpos) && (result[0] != '-'))\n         result.insert(static_cast<std::string::size_type>(0), 1, '+');\n      return result;\n   }\n   ~tommath_int()\n   {\n      if(m_data.dp)\n         mp_clear(&m_data);\n   }\n   void negate()\n   {\n      BOOST_ASSERT(m_data.dp);\n      mp_neg(&m_data, &m_data);\n   }\n   int compare(const tommath_int& o)const\n   {\n      BOOST_ASSERT(m_data.dp && o.m_data.dp);\n      return mp_cmp(const_cast< ::mp_int*>(&m_data), const_cast< ::mp_int*>(&o.m_data));\n   }\n   template <class V>\n   int compare(V v)const\n   {\n      tommath_int d;\n      tommath_int t(*this);\n      detail::check_tommath_result(mp_shrink(&t.data()));\n      d = v;\n      return t.compare(d);\n   }\n   ::mp_int& data() \n   { \n      BOOST_ASSERT(m_data.dp);\n      return m_data; \n   }\n   const ::mp_int& data()const \n   { \n      BOOST_ASSERT(m_data.dp);\n      return m_data; \n   }\n   void swap(tommath_int& o)BOOST_NOEXCEPT\n   {\n      mp_exch(&m_data, &o.data());\n   }\nprotected:\n   ::mp_int m_data;\n};\n\n#define BOOST_MP_TOMMATH_BIT_OP_CHECK(x)\\\n   if(SIGN(&x.data()))\\\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"Bitwise operations on libtommath negative valued integers are disabled as they produce unpredictable results\"))\n\nint eval_get_sign(const tommath_int& val);\n\ninline void eval_add(tommath_int& t, const tommath_int& o)\n{\n   detail::check_tommath_result(mp_add(&t.data(), const_cast< ::mp_int*>(&o.data()), &t.data()));\n}\ninline void eval_subtract(tommath_int& t, const tommath_int& o)\n{\n   detail::check_tommath_result(mp_sub(&t.data(), const_cast< ::mp_int*>(&o.data()), &t.data()));\n}\ninline void eval_multiply(tommath_int& t, const tommath_int& o)\n{\n   detail::check_tommath_result(mp_mul(&t.data(), const_cast< ::mp_int*>(&o.data()), &t.data()));\n}\ninline void eval_divide(tommath_int& t, const tommath_int& o)\n{\n   using default_ops::eval_is_zero;\n   tommath_int temp;\n   if(eval_is_zero(o))\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n   detail::check_tommath_result(mp_div(&t.data(), const_cast< ::mp_int*>(&o.data()), &t.data(), &temp.data()));\n}\ninline void eval_modulus(tommath_int& t, const tommath_int& o)\n{\n   using default_ops::eval_is_zero;\n   if(eval_is_zero(o))\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n   bool neg = eval_get_sign(t) < 0;\n   bool neg2 = eval_get_sign(o) < 0;\n   detail::check_tommath_result(mp_mod(&t.data(), const_cast< ::mp_int*>(&o.data()), &t.data()));\n   if((neg != neg2) && (eval_get_sign(t) != 0))\n   {\n      t.negate();\n      detail::check_tommath_result(mp_add(&t.data(), const_cast< ::mp_int*>(&o.data()), &t.data()));\n      t.negate();\n   }\n   else if(neg && (t.compare(o) == 0))\n   {\n      mp_zero(&t.data());\n   }\n}\ntemplate <class UI>\ninline void eval_left_shift(tommath_int& t, UI i)\n{\n   detail::check_tommath_result(mp_mul_2d(&t.data(), static_cast<unsigned>(i), &t.data()));\n}\ntemplate <class UI>\ninline void eval_right_shift(tommath_int& t, UI i)\n{\n   tommath_int d;\n   detail::check_tommath_result(mp_div_2d(&t.data(), static_cast<unsigned>(i), &t.data(), &d.data()));\n}\ntemplate <class UI>\ninline void eval_left_shift(tommath_int& t, const tommath_int& v, UI i)\n{\n   detail::check_tommath_result(mp_mul_2d(const_cast< ::mp_int*>(&v.data()), static_cast<unsigned>(i), &t.data()));\n}\ntemplate <class UI>\ninline void eval_right_shift(tommath_int& t, const tommath_int& v, UI i)\n{\n   tommath_int d;\n   detail::check_tommath_result(mp_div_2d(const_cast< ::mp_int*>(&v.data()), static_cast<unsigned long>(i), &t.data(), &d.data()));\n}\n\ninline void eval_bitwise_and(tommath_int& result, const tommath_int& v)\n{\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(result);\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n   detail::check_tommath_result(mp_and(&result.data(), const_cast< ::mp_int*>(&v.data()), &result.data()));\n}\n\ninline void eval_bitwise_or(tommath_int& result, const tommath_int& v)\n{\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(result);\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n   detail::check_tommath_result(mp_or(&result.data(), const_cast< ::mp_int*>(&v.data()), &result.data()));\n}\n\ninline void eval_bitwise_xor(tommath_int& result, const tommath_int& v)\n{\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(result);\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n   detail::check_tommath_result(mp_xor(&result.data(), const_cast< ::mp_int*>(&v.data()), &result.data()));\n}\n\ninline void eval_add(tommath_int& t, const tommath_int& p, const tommath_int& o)\n{\n   detail::check_tommath_result(mp_add(const_cast< ::mp_int*>(&p.data()), const_cast< ::mp_int*>(&o.data()), &t.data()));\n}\ninline void eval_subtract(tommath_int& t, const tommath_int& p, const tommath_int& o)\n{\n   detail::check_tommath_result(mp_sub(const_cast< ::mp_int*>(&p.data()), const_cast< ::mp_int*>(&o.data()), &t.data()));\n}\ninline void eval_multiply(tommath_int& t, const tommath_int& p, const tommath_int& o)\n{\n   detail::check_tommath_result(mp_mul(const_cast< ::mp_int*>(&p.data()), const_cast< ::mp_int*>(&o.data()), &t.data()));\n}\ninline void eval_divide(tommath_int& t, const tommath_int& p, const tommath_int& o)\n{\n   using default_ops::eval_is_zero;\n   tommath_int d;\n   if(eval_is_zero(o))\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n   detail::check_tommath_result(mp_div(const_cast< ::mp_int*>(&p.data()), const_cast< ::mp_int*>(&o.data()), &t.data(), &d.data()));\n}\ninline void eval_modulus(tommath_int& t, const tommath_int& p, const tommath_int& o)\n{\n   using default_ops::eval_is_zero;\n   if(eval_is_zero(o))\n      BOOST_THROW_EXCEPTION(std::overflow_error(\"Integer division by zero\"));\n   bool neg = eval_get_sign(p) < 0;\n   bool neg2 = eval_get_sign(o) < 0;\n   detail::check_tommath_result(mp_mod(const_cast< ::mp_int*>(&p.data()), const_cast< ::mp_int*>(&o.data()), &t.data()));\n   if((neg != neg2) && (eval_get_sign(t) != 0))\n   {\n      t.negate();\n      detail::check_tommath_result(mp_add(&t.data(), const_cast< ::mp_int*>(&o.data()), &t.data()));\n      t.negate();\n   }\n   else if(neg  && (t.compare(o) == 0))\n   {\n      mp_zero(&t.data());\n   }\n}\n\ninline void eval_bitwise_and(tommath_int& result, const tommath_int& u, const tommath_int& v)\n{\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(u);\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n   detail::check_tommath_result(mp_and(const_cast< ::mp_int*>(&u.data()), const_cast< ::mp_int*>(&v.data()), &result.data()));\n}\n\ninline void eval_bitwise_or(tommath_int& result, const tommath_int& u, const tommath_int& v)\n{\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(u);\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n   detail::check_tommath_result(mp_or(const_cast< ::mp_int*>(&u.data()), const_cast< ::mp_int*>(&v.data()), &result.data()));\n}\n\ninline void eval_bitwise_xor(tommath_int& result, const tommath_int& u, const tommath_int& v)\n{\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(u);\n   BOOST_MP_TOMMATH_BIT_OP_CHECK(v);\n   detail::check_tommath_result(mp_xor(const_cast< ::mp_int*>(&u.data()), const_cast< ::mp_int*>(&v.data()), &result.data()));\n}\n/*\ninline void eval_complement(tommath_int& result, const tommath_int& u)\n{\n   //\n   // Although this code works, it doesn't really do what the user might expect....\n   // and it's hard to see how it ever could.  Disabled for now:\n   //\n   result = u;\n   for(int i = 0; i < result.data().used; ++i)\n   {\n      result.data().dp[i] = MP_MASK & ~(result.data().dp[i]);\n   }\n   //\n   // We now need to pad out the left of the value with 1's to round up to a whole number of\n   // CHAR_BIT * sizeof(mp_digit) units.  Otherwise we'll end up with a very strange number of\n   // bits set!\n   //\n   unsigned shift = result.data().used * DIGIT_BIT;    // How many bits we're actually using\n   // How many bits we actually need, reduced by one to account for a mythical sign bit:\n   int padding = result.data().used * std::numeric_limits<mp_digit>::digits - shift - 1; \n   while(padding >= std::numeric_limits<mp_digit>::digits) \n      padding -= std::numeric_limits<mp_digit>::digits;\n\n   // Create a mask providing the extra bits we need and add to result:\n   tommath_int mask;\n   mask = static_cast<boost::long_long_type>((1u << padding) - 1);\n   eval_left_shift(mask, shift);\n   add(result, mask);\n}\n*/\ninline bool eval_is_zero(const tommath_int& val)\n{\n   return mp_iszero(&val.data());\n}\ninline int eval_get_sign(const tommath_int& val)\n{\n   return mp_iszero(&val.data()) ? 0 : SIGN(&val.data()) ? -1 : 1;\n}\ntemplate <class A>\ninline void eval_convert_to(A* result, const tommath_int& val)\n{\n   *result = boost::lexical_cast<A>(val.str(0, std::ios_base::fmtflags(0)));\n}\ninline void eval_convert_to(char* result, const tommath_int& val)\n{\n   *result = static_cast<char>(boost::lexical_cast<int>(val.str(0, std::ios_base::fmtflags(0))));\n}\ninline void eval_convert_to(unsigned char* result, const tommath_int& val)\n{\n   *result = static_cast<unsigned char>(boost::lexical_cast<unsigned>(val.str(0, std::ios_base::fmtflags(0))));\n}\ninline void eval_convert_to(signed char* result, const tommath_int& val)\n{\n   *result = static_cast<signed char>(boost::lexical_cast<int>(val.str(0, std::ios_base::fmtflags(0))));\n}\ninline void eval_abs(tommath_int& result, const tommath_int& val)\n{\n   detail::check_tommath_result(mp_abs(const_cast< ::mp_int*>(&val.data()), &result.data()));\n}\ninline void eval_gcd(tommath_int& result, const tommath_int& a, const tommath_int& b)\n{\n   detail::check_tommath_result(mp_gcd(const_cast< ::mp_int*>(&a.data()), const_cast< ::mp_int*>(&b.data()), const_cast< ::mp_int*>(&result.data())));\n}\ninline void eval_lcm(tommath_int& result, const tommath_int& a, const tommath_int& b)\n{\n   detail::check_tommath_result(mp_lcm(const_cast< ::mp_int*>(&a.data()), const_cast< ::mp_int*>(&b.data()), const_cast< ::mp_int*>(&result.data())));\n}\ninline void eval_powm(tommath_int& result, const tommath_int& base, const tommath_int& p, const tommath_int& m)\n{\n   if(eval_get_sign(p) < 0)\n   {\n      BOOST_THROW_EXCEPTION(std::runtime_error(\"powm requires a positive exponent.\"));\n   }\n   detail::check_tommath_result(mp_exptmod(const_cast< ::mp_int*>(&base.data()), const_cast< ::mp_int*>(&p.data()), const_cast< ::mp_int*>(&m.data()), &result.data()));\n}\n\n\ninline void eval_qr(const tommath_int& x, const tommath_int& y, \n   tommath_int& q, tommath_int& r)\n{\n   detail::check_tommath_result(mp_div(const_cast< ::mp_int*>(&x.data()), const_cast< ::mp_int*>(&y.data()), &q.data(), &r.data()));\n}\n\ninline unsigned eval_lsb(const tommath_int& val)\n{\n   int c = eval_get_sign(val);\n   if(c == 0)\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"No bits were set in the operand.\"));\n   }\n   if(c < 0)\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"Testing individual bits in negative values is not supported - results are undefined.\"));\n   }\n   return mp_cnt_lsb(const_cast< ::mp_int*>(&val.data()));\n}\n\ninline unsigned eval_msb(const tommath_int& val)\n{\n   int c = eval_get_sign(val);\n   if(c == 0)\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"No bits were set in the operand.\"));\n   }\n   if(c < 0)\n   {\n      BOOST_THROW_EXCEPTION(std::range_error(\"Testing individual bits in negative values is not supported - results are undefined.\"));\n   }\n   return mp_count_bits(const_cast< ::mp_int*>(&val.data())) - 1;\n}\n\ntemplate <class Integer>\ninline typename enable_if<is_unsigned<Integer>, Integer>::type eval_integer_modulus(const tommath_int& x, Integer val)\n{\n   static const mp_digit m = (static_cast<mp_digit>(1) << DIGIT_BIT) - 1;\n   if(val <= m)\n   {\n      mp_digit d;\n      detail::check_tommath_result(mp_mod_d(const_cast< ::mp_int*>(&x.data()), static_cast<mp_digit>(val), &d));\n      return d;\n   }\n   else\n   {\n      return default_ops::eval_integer_modulus(x, val);\n   }\n}\ntemplate <class Integer>\ninline typename enable_if<is_signed<Integer>, Integer>::type eval_integer_modulus(const tommath_int& x, Integer val)\n{\n   return eval_integer_modulus(x, boost::multiprecision::detail::unsigned_abs(val));\n}\n\n} // namespace backends\n\nusing boost::multiprecision::backends::tommath_int;\n\ntemplate<>\nstruct number_category<tommath_int> : public mpl::int_<number_kind_integer>{};\n\ntypedef number<tommath_int >                     tom_int;\ntypedef rational_adaptor<tommath_int>               tommath_rational;\ntypedef number<tommath_rational>                 tom_rational;\n\n}}  // namespaces\n\nnamespace std{\n\ntemplate<boost::multiprecision::expression_template_option ExpressionTemplates> \nclass numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >\n{\n   typedef boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> number_type;\npublic:\n   BOOST_STATIC_CONSTEXPR bool is_specialized = true;\n   //\n   // Largest and smallest numbers are bounded only by available memory, set\n   // to zero:\n   //\n   static number_type (min)()\n   { \n      return number_type();\n   }\n   static number_type (max)() \n   { \n      return number_type();\n   }\n   static number_type lowest() { return (min)(); }\n   BOOST_STATIC_CONSTEXPR int digits = INT_MAX;\n   BOOST_STATIC_CONSTEXPR int digits10 = (INT_MAX / 1000) * 301L;\n   BOOST_STATIC_CONSTEXPR int max_digits10 = digits10 + 2;\n   BOOST_STATIC_CONSTEXPR bool is_signed = true;\n   BOOST_STATIC_CONSTEXPR bool is_integer = true;\n   BOOST_STATIC_CONSTEXPR bool is_exact = true;\n   BOOST_STATIC_CONSTEXPR int radix = 2;\n   static number_type epsilon() { return number_type(); }\n   static number_type round_error() { return number_type(); }\n   BOOST_STATIC_CONSTEXPR int min_exponent = 0;\n   BOOST_STATIC_CONSTEXPR int min_exponent10 = 0;\n   BOOST_STATIC_CONSTEXPR int max_exponent = 0;\n   BOOST_STATIC_CONSTEXPR int max_exponent10 = 0;\n   BOOST_STATIC_CONSTEXPR bool has_infinity = false;\n   BOOST_STATIC_CONSTEXPR bool has_quiet_NaN = false;\n   BOOST_STATIC_CONSTEXPR bool has_signaling_NaN = false;\n   BOOST_STATIC_CONSTEXPR float_denorm_style has_denorm = denorm_absent;\n   BOOST_STATIC_CONSTEXPR bool has_denorm_loss = false;\n   static number_type infinity() { return number_type(); }\n   static number_type quiet_NaN() { return number_type(); }\n   static number_type signaling_NaN() { return number_type(); }\n   static number_type denorm_min() { return number_type(); }\n   BOOST_STATIC_CONSTEXPR bool is_iec559 = false;\n   BOOST_STATIC_CONSTEXPR bool is_bounded = false;\n   BOOST_STATIC_CONSTEXPR bool is_modulo = false;\n   BOOST_STATIC_CONSTEXPR bool traps = false;\n   BOOST_STATIC_CONSTEXPR bool tinyness_before = false;\n   BOOST_STATIC_CONSTEXPR float_round_style round_style = round_toward_zero;\n};\n\n#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION\n\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::digits;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::digits10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::max_digits10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::is_signed;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::is_integer;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::is_exact;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::radix;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::min_exponent;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::min_exponent10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::max_exponent;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::max_exponent10;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::has_infinity;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::has_quiet_NaN;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::has_signaling_NaN;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST float_denorm_style numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::has_denorm;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::has_denorm_loss;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::is_iec559;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::is_bounded;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::is_modulo;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::traps;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::tinyness_before;\ntemplate <boost::multiprecision::expression_template_option ExpressionTemplates>\nBOOST_CONSTEXPR_OR_CONST float_round_style numeric_limits<boost::multiprecision::number<boost::multiprecision::tommath_int, ExpressionTemplates> >::round_style;\n\n#endif\n}\n\n#endif\n", "meta": {"hexsha": "9c373443c6659a1187b74b1f616b899eb77cff9a", "size": 29849, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clm/src/main/clm/jni/boost/armv7a/include/boost/multiprecision/tommath.hpp", "max_stars_repo_name": "BruceNUAA/gaze-detection-android-app", "max_stars_repo_head_hexsha": "5daa2c8a0e51eb506fe435a6f8d03758162d0579", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "clm/src/main/clm/jni/boost/armv7a/include/boost/multiprecision/tommath.hpp", "max_issues_repo_name": "BruceNUAA/gaze-detection-android-app", "max_issues_repo_head_hexsha": "5daa2c8a0e51eb506fe435a6f8d03758162d0579", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 37.0, "max_issues_repo_issues_event_min_datetime": "2020-08-24T02:48:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T06:41:52.000Z", "max_forks_repo_path": "clm/src/main/clm/jni/boost/armv7a/include/boost/multiprecision/tommath.hpp", "max_forks_repo_name": "BruceNUAA/gaze-detection-android-app", "max_forks_repo_head_hexsha": "5daa2c8a0e51eb506fe435a6f8d03758162d0579", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 275.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T08:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:06:07.000Z", "avg_line_length": 39.223390276, "max_line_length": 168, "alphanum_fraction": 0.6665549935, "num_tokens": 7682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.22636067265082674}}
{"text": "// Author: Francesco Regazzoni - MOX, Politecnico di Milano\n// Email:  francesco.regazzoni@polimi.it\n// Date:   2020\n\n#include <cmath>\n\n#include <boost/property_tree/json_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n\n#include \"model_RDQ20_SE.hpp\"\n\nmodel_RDQ20_SE::model_RDQ20_SE(std::string parameters_file)\n    : sarcomere(\"RDQ20-SE\") {\n  // Read JSON options file\n  boost::property_tree::ptree root;\n  boost::property_tree::read_json(parameters_file, root);\n\n  prm_n_RU = root.get_child(\"geometry\")\n                 .get_child(\"n_RU\")\n                 .get_value<unsigned int>(); // [-]\n  prm_LA = root.get_child(\"geometry\")\n               .get_child(\"LA\")\n               .get_value<double>(); // [micro m]\n  prm_LM = root.get_child(\"geometry\")\n               .get_child(\"LM\")\n               .get_value<double>(); // [micro m]\n  prm_LB = root.get_child(\"geometry\")\n               .get_child(\"LB\")\n               .get_value<double>(); // [micro m]\n  prm_SL0 = root.get_child(\"geometry\")\n                .get_child(\"SL0\")\n                .get_value<double>(); // [micro m]\n  prm_Lsmooth = root.get_child(\"geometry\")\n                    .get_child(\"Lsmooth\")\n                    .get_value<double>(); // [micro m]\n  prm_Q = root.get_child(\"RU_steady_state\")\n              .get_child(\"Q\")\n              .get_value<double>(); // [-]\n  prm_Kd0 = root.get_child(\"RU_steady_state\")\n                .get_child(\"Kd0\")\n                .get_value<double>(); // [micro M]\n  prm_alphaKd = root.get_child(\"RU_steady_state\")\n                    .get_child(\"alphaKd\")\n                    .get_value<double>(); // [micro M / micro m]\n  prm_mu = root.get_child(\"RU_steady_state\")\n               .get_child(\"mu\")\n               .get_value<double>(); // [-]\n  prm_gamma = root.get_child(\"RU_steady_state\")\n                  .get_child(\"gamma\")\n                  .get_value<double>(); // [-]\n  prm_Koff = root.get_child(\"RU_kinetics\")\n                 .get_child(\"Koff\")\n                 .get_value<double>(); // [s^-1]\n  prm_Kbasic = root.get_child(\"RU_kinetics\")\n                   .get_child(\"Kbasic\")\n                   .get_value<double>(); // [s^-1]\n  prm_r0 = root.get_child(\"XB_cycling\")\n               .get_child(\"r0\")\n               .get_value<double>(); // [s^-1]\n  prm_alpha = root.get_child(\"XB_cycling\")\n                  .get_child(\"alpha\")\n                  .get_value<double>(); // [-]\n  prm_mu0_fP = root.get_child(\"XB_cycling\")\n                   .get_child(\"mu0_fP\")\n                   .get_value<double>(); // [s^-1]\n  prm_mu1_fP = root.get_child(\"XB_cycling\")\n                   .get_child(\"mu1_fP\")\n                   .get_value<double>(); // [s^-1]\n  prm_a_XB = root.get_child(\"upscaling\")\n                 .get_child(\"a_XB\")\n                 .get_value<double>(); // [kPa]\n\n  allocate_variables();\n\n  initialize_rates();\n}\n\nvoid model_RDQ20_SE::allocate_variables() {\n  // Variable numbers\n  n_states_RU = (prm_n_RU - 2) * 4 * 4 * 4;\n  n_states_XB = prm_n_RU * 4;\n  n_variables = n_states_RU + n_states_XB;\n\n  // Allocation of state_RU\n  std::array<std::array<std::array<double, 4>, 4>, 4> base_RU_state;\n  for (RU_L = 0; RU_L < 4; ++RU_L)\n    for (RU_C = 0; RU_C < 4; ++RU_C)\n      for (RU_R = 0; RU_R < 4; ++RU_R)\n        base_RU_state[RU_L][RU_C][RU_R] = 0.0;\n  base_RU_state[0][0][0] = 1.0;\n\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU)\n    state_RU.push_back(base_RU_state);\n\n  // Allocation of state_XB\n  std::array<double, 4> base_XB_state;\n  for (i_XB = 0; i_XB < 4; ++i_XB)\n    base_XB_state[i_XB] = 0.0;\n\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU)\n    state_XB.push_back(base_XB_state);\n\n  // Allocation of initial_state\n  for (unsigned int i = 0; i < n_variables; ++i)\n    initial_state.push_back(0.0);\n  serialize_state(initial_state);\n\n  // Allocation of rates_RU\n  std::array<std::array<std::array<std::array<double, 4>, 4>, 4>, 4>\n      base_RU_rates_or_flux;\n  for (RU_L = 0; RU_L < 4; ++RU_L)\n    for (RU_C = 0; RU_C < 4; ++RU_C)\n      for (RU_R = 0; RU_R < 4; ++RU_R)\n        for (RU_new = 0; RU_new < 4; ++RU_new)\n          base_RU_rates_or_flux[RU_L][RU_C][RU_R][RU_new] = 0.0;\n\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU) {\n    rates_RU.push_back(base_RU_rates_or_flux);\n  }\n\n  // Allocation of flux_RU_*\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU) {\n    flux_RU_L.push_back(base_RU_rates_or_flux);\n    flux_RU_C.push_back(base_RU_rates_or_flux);\n    flux_RU_R.push_back(base_RU_rates_or_flux);\n  }\n}\n\nvoid model_RDQ20_SE::solve_time_step(std::vector<double> &state,\n                                     const double &calcium,\n                                     const double &sarcomere_length,\n                                     const double &dSL_dt, const double &dt) {\n  // Deserialize state\n  deserialize_state(state);\n\n  // Update RU transition rates\n  RU_update_rates(calcium, sarcomere_length);\n\n  // Advance RU state\n  double RU_dt = 0.0;\n  double time_advanced = 0.0;\n  while (time_advanced <=\n         dt - 1e-10) // Cover the time-step up to a given tolerance\n  {\n    RU_dt = std::min(prm_time_step_update_RU_state, dt - time_advanced);\n    RU_update_state(RU_dt);\n    time_advanced += RU_dt;\n  }\n\n  // Advance XB state\n  XB_update_state(sarcomere_length, dSL_dt, dt);\n\n  // Re-serialize state\n  serialize_state(state);\n}\n\nvoid model_RDQ20_SE::deserialize_state(const std::vector<double> &state) {\n  unsigned int i_current = 0;\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R) {\n          state_RU[i_RU][RU_L][RU_C][RU_R] = state[i_current];\n          i_current++;\n        }\n\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU)\n    for (i_XB = 0; i_XB < 4; ++i_XB) {\n      state_XB[i_RU][i_XB] = state[i_current];\n      i_current++;\n    }\n}\n\nvoid model_RDQ20_SE::serialize_state(std::vector<double> &state) {\n  unsigned int i_current = 0;\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R) {\n          state[i_current] = state_RU[i_RU][RU_L][RU_C][RU_R];\n          i_current++;\n        }\n\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU)\n    for (i_XB = 0; i_XB < 4; ++i_XB) {\n      state[i_current] = state_XB[i_RU][i_XB];\n      i_current++;\n    }\n}\n\ndouble model_RDQ20_SE::get_active_tension(const std::vector<double> &state,\n                                          const double & /*sarcomere_length*/) {\n  deserialize_state(state);\n\n  double active_tension = 0.0;\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU)\n    active_tension += state_XB[i_RU][1] + state_XB[i_RU][3];\n\n  return prm_a_XB * active_tension / prm_n_RU;\n}\n\ndouble\nmodel_RDQ20_SE::get_active_stiffness(const std::vector<double> &state,\n                                     const double & /*sarcomere_length*/) {\n  deserialize_state(state);\n\n  double active_stiffness = 0.0;\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU)\n    active_stiffness += state_XB[i_RU][0] + state_XB[i_RU][2];\n\n  return prm_a_XB * active_stiffness / prm_n_RU;\n}\n\ndouble model_RDQ20_SE::get_permissivity(const std::vector<double> &state) {\n  deserialize_state(state);\n\n  double permissivity = 0;\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU) {\n    if (i_RU == 0) // First RU\n    {\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R)\n          permissivity +=\n              state_RU[0][2][RU_C][RU_R] + state_RU[0][3][RU_C][RU_R];\n    } else if (i_RU == prm_n_RU - 1) // Last RU\n    {\n      for (RU_L = 0; RU_L < 4; ++RU_L)\n        for (RU_C = 0; RU_C < 4; ++RU_C)\n          permissivity += state_RU[prm_n_RU - 3][RU_L][RU_C][2] +\n                          state_RU[prm_n_RU - 3][RU_L][RU_C][3];\n    } else // Intermediate RUs\n    {\n      for (RU_L = 0; RU_L < 4; ++RU_L)\n        for (RU_R = 0; RU_R < 4; ++RU_R)\n          permissivity += state_RU[i_RU - 1][RU_L][2][RU_R] +\n                          state_RU[i_RU - 1][RU_L][3][RU_R];\n    }\n  }\n  return permissivity / prm_n_RU;\n}\n\nvoid model_RDQ20_SE::initialize_rates() {\n  int permissive_neighbors;\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_R = 0; RU_R < 4; ++RU_R) {\n        permissive_neighbors =\n            permissivity_of_state[RU_L] + permissivity_of_state[RU_R];\n        rates_RU[i_RU][RU_L][1][RU_R][0] = prm_Koff;\n        rates_RU[i_RU][RU_L][2][RU_R][3] = prm_Koff / prm_mu;\n        rates_RU[i_RU][RU_L][3][RU_R][0] =\n            prm_Kbasic * std::pow(prm_gamma, 2 - permissive_neighbors);\n        rates_RU[i_RU][RU_L][2][RU_R][1] =\n            prm_Kbasic * std::pow(prm_gamma, 2 - permissive_neighbors);\n      }\n}\n\nvoid model_RDQ20_SE::RU_update_rates(const double &calcium,\n                                     const double &sarcomere_length) {\n  double Kon = prm_Koff / (prm_Kd0 - prm_alphaKd * (2.15 - sarcomere_length));\n  int permissive_neighbors;\n  double ChiSF_i_RU;\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU) {\n    ChiSF_i_RU = ChiSF(sarcomere_length, i_RU);\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_R = 0; RU_R < 4; ++RU_R) {\n        permissive_neighbors =\n            permissivity_of_state[RU_L] + permissivity_of_state[RU_R];\n        rates_RU[i_RU][RU_L][0][RU_R][1] = Kon * calcium;\n        rates_RU[i_RU][RU_L][3][RU_R][2] = Kon * calcium;\n        rates_RU[i_RU][RU_L][1][RU_R][2] =\n            ChiSF_i_RU * std::pow(prm_gamma, permissive_neighbors) * prm_Q *\n            prm_Kbasic;\n        rates_RU[i_RU][RU_L][0][RU_R][3] =\n            ChiSF_i_RU * std::pow(prm_gamma, permissive_neighbors) * prm_Q *\n            prm_Kbasic / prm_mu;\n      }\n  }\n}\n\nvoid model_RDQ20_SE::RU_update_state(const double &dt) {\n  // Compute fluxes associated with center units\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R)\n          for (RU_new = 0; RU_new < 4; ++RU_new) {\n            flux_RU_C[i_RU][RU_L][RU_C][RU_R][RU_new] =\n                rates_RU[i_RU + 1][RU_L][RU_C][RU_R][RU_new] *\n                state_RU[i_RU][RU_L][RU_C][RU_R];\n          }\n\n  double prob_tot;\n  double rate_tot;\n\n  // Compute fluxes associated with left units\n  // --- Most left-ward triplet\n  for (RU_L = 0; RU_L < 4; ++RU_L)\n    for (RU_C = 0; RU_C < 4; ++RU_C)\n      for (RU_R = 0; RU_R < 4; ++RU_R)\n        for (RU_new = 0; RU_new < 4; ++RU_new) {\n          flux_RU_L[0][RU_L][RU_C][RU_R][RU_new] =\n              rates_RU[0][0][RU_L][RU_C][RU_new] *\n              state_RU[0][RU_L][RU_C][RU_R];\n        }\n\n  // --- Other triplets\n  for (i_RU = 1; i_RU < prm_n_RU - 2; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_C = 0; RU_C < 4; ++RU_C) {\n        prob_tot = 0.0;\n        for (RU_dummy = 0; RU_dummy < 4; ++RU_dummy)\n          prob_tot += state_RU[i_RU - 1][RU_dummy][RU_L][RU_C];\n\n        for (RU_new = 0; RU_new < 4; ++RU_new) {\n          rate_tot = 0.0;\n          if (prob_tot > 1e-12) {\n            for (RU_dummy = 0; RU_dummy < 4; ++RU_dummy)\n              rate_tot += flux_RU_C[i_RU - 1][RU_dummy][RU_L][RU_C][RU_new];\n\n            rate_tot /= prob_tot;\n          }\n\n          for (RU_R = 0; RU_R < 4; ++RU_R) {\n            flux_RU_L[i_RU][RU_L][RU_C][RU_R][RU_new] =\n                rate_tot * state_RU[i_RU][RU_L][RU_C][RU_R];\n          }\n        }\n      }\n\n  // Compute fluxes associated with right units\n  // --- Most right-ward triplet\n  for (RU_L = 0; RU_L < 4; ++RU_L)\n    for (RU_C = 0; RU_C < 4; ++RU_C)\n      for (RU_R = 0; RU_R < 4; ++RU_R)\n        for (RU_new = 0; RU_new < 4; ++RU_new) {\n          flux_RU_R[prm_n_RU - 3][RU_L][RU_C][RU_R][RU_new] =\n              rates_RU[prm_n_RU - 1][RU_C][RU_R][0][RU_new] *\n              state_RU[prm_n_RU - 3][RU_L][RU_C][RU_R];\n        }\n\n  // --- Other triplets\n  for (i_RU = 0; i_RU < prm_n_RU - 3; ++i_RU)\n    for (RU_R = 0; RU_R < 4; ++RU_R)\n      for (RU_C = 0; RU_C < 4; ++RU_C) {\n        prob_tot = 0.0;\n        for (RU_dummy = 0; RU_dummy < 4; ++RU_dummy)\n          prob_tot += state_RU[i_RU + 1][RU_C][RU_R][RU_dummy];\n\n        for (RU_new = 0; RU_new < 4; ++RU_new) {\n          rate_tot = 0.0;\n          if (prob_tot > 1e-12) {\n            for (RU_dummy = 0; RU_dummy < 4; ++RU_dummy)\n              rate_tot += flux_RU_C[i_RU + 1][RU_C][RU_R][RU_dummy][RU_new];\n\n            rate_tot /= prob_tot;\n          }\n\n          for (RU_L = 0; RU_L < 4; ++RU_L) {\n            flux_RU_R[i_RU][RU_L][RU_C][RU_R][RU_new] =\n                rate_tot * state_RU[i_RU][RU_L][RU_C][RU_R];\n          }\n        }\n      }\n\n  // Forward Euler advance\n  for (i_RU = 0; i_RU < prm_n_RU - 2; ++i_RU)\n    for (RU_L = 0; RU_L < 4; ++RU_L)\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R)\n          for (RU_new = 0; RU_new < 4; ++RU_new) {\n            state_RU[i_RU][RU_L][RU_C][RU_R] +=\n                dt * (flux_RU_L[i_RU][RU_new][RU_C][RU_R][RU_L] +\n                      flux_RU_C[i_RU][RU_L][RU_new][RU_R][RU_C] +\n                      flux_RU_R[i_RU][RU_L][RU_C][RU_new][RU_R] -\n                      flux_RU_L[i_RU][RU_L][RU_C][RU_R][RU_new] -\n                      flux_RU_C[i_RU][RU_L][RU_C][RU_R][RU_new] -\n                      flux_RU_R[i_RU][RU_L][RU_C][RU_R][RU_new]);\n          }\n}\n\nvoid model_RDQ20_SE::XB_update_state(const double &sarcomere_length,\n                                     const double &dSL_dt, const double &dt) {\n  double v = -dSL_dt / prm_SL0;\n\n  double r = prm_r0 + prm_alpha * std::abs(v);\n  double k_PN;\n  double k_NP;\n  double permissivity;\n  double flux_PN;\n  double flux_NP;\n  double ChiSFChiMF_i;\n  double diag_P;\n  double diag_N;\n\n  for (i_RU = 0; i_RU < prm_n_RU; ++i_RU) {\n    permissivity = 0;\n    flux_PN = 0;\n    flux_NP = 0;\n\n    if (i_RU == 0) // First RU\n    {\n      for (RU_C = 0; RU_C < 4; ++RU_C)\n        for (RU_R = 0; RU_R < 4; ++RU_R) {\n          permissivity +=\n              state_RU[0][2][RU_C][RU_R] + state_RU[0][3][RU_C][RU_R];\n          flux_NP += state_RU[0][0][RU_C][RU_R] * rates_RU[0][0][0][RU_C][3] +\n                     state_RU[0][1][RU_C][RU_R] * rates_RU[0][0][1][RU_C][2];\n          flux_PN += state_RU[0][3][RU_C][RU_R] * rates_RU[0][0][3][RU_C][0] +\n                     state_RU[0][2][RU_C][RU_R] * rates_RU[0][0][2][RU_C][1];\n        }\n    } else if (i_RU == prm_n_RU - 1) // Last RU\n    {\n      for (RU_L = 0; RU_L < 4; ++RU_L)\n        for (RU_C = 0; RU_C < 4; ++RU_C) {\n          permissivity += state_RU[prm_n_RU - 3][RU_L][RU_C][2] +\n                          state_RU[prm_n_RU - 3][RU_L][RU_C][3];\n          flux_NP += state_RU[prm_n_RU - 3][RU_L][RU_C][0] *\n                         rates_RU[prm_n_RU - 1][RU_C][0][0][3] +\n                     state_RU[prm_n_RU - 3][RU_L][RU_C][1] *\n                         rates_RU[prm_n_RU - 1][RU_C][1][0][2];\n          flux_PN += state_RU[prm_n_RU - 3][RU_L][RU_C][3] *\n                         rates_RU[prm_n_RU - 1][RU_C][3][0][0] +\n                     state_RU[prm_n_RU - 3][RU_L][RU_C][2] *\n                         rates_RU[prm_n_RU - 1][RU_C][2][0][1];\n        }\n    } else // Intermediate RUs\n    {\n      for (RU_L = 0; RU_L < 4; ++RU_L)\n        for (RU_R = 0; RU_R < 4; ++RU_R) {\n          permissivity += state_RU[i_RU - 1][RU_L][2][RU_R] +\n                          state_RU[i_RU - 1][RU_L][3][RU_R];\n          flux_NP += state_RU[i_RU - 1][RU_L][0][RU_R] *\n                         rates_RU[i_RU][RU_L][0][RU_R][3] +\n                     state_RU[i_RU - 1][RU_L][1][RU_R] *\n                         rates_RU[i_RU][RU_L][1][RU_R][2];\n          flux_PN += state_RU[i_RU - 1][RU_L][3][RU_R] *\n                         rates_RU[i_RU][RU_L][3][RU_R][0] +\n                     state_RU[i_RU - 1][RU_L][2][RU_R] *\n                         rates_RU[i_RU][RU_L][2][RU_R][1];\n        }\n    }\n\n    if (permissivity >= 1e-12)\n      k_PN = 0;\n    else\n      k_PN = flux_PN / permissivity;\n\n    if (1 - permissivity >= 1e-12)\n      k_NP = 0;\n    else\n      k_NP = flux_NP / (1 - permissivity);\n\n    diag_P = r + k_PN;\n    diag_N = r + k_NP;\n\n    // Fill matrix\n    XB_A(0, 0) = -diag_P;\n    XB_A(1, 1) = -diag_P;\n    XB_A(2, 2) = -diag_N;\n    XB_A(3, 3) = -diag_N;\n    XB_A(0, 2) = k_NP;\n    XB_A(1, 3) = k_NP;\n    XB_A(2, 0) = k_PN;\n    XB_A(3, 1) = k_PN;\n    XB_A(1, 0) = -v;\n    XB_A(3, 2) = -v;\n\n    XB_A *= -dt;\n    for (i_XB = 0; i_XB < 4; ++i_XB)\n      XB_A(i_XB, i_XB) += 1.0;\n\n    ChiSFChiMF_i =\n        ChiSF(sarcomere_length, i_RU) * ChiMF(sarcomere_length, i_RU);\n\n    // Fill rhs\n    XB_rhs(0) =\n        state_XB[i_RU][0] + dt * permissivity * prm_mu0_fP * ChiSFChiMF_i;\n    XB_rhs(1) =\n        state_XB[i_RU][1] + dt * permissivity * prm_mu1_fP * ChiSFChiMF_i;\n    XB_rhs(2) = state_XB[i_RU][2];\n    XB_rhs(3) = state_XB[i_RU][3];\n\n    // Implicit Euler advance\n    XB_sol = XB_A.colPivHouseholderQr().solve(XB_rhs);\n    for (i_XB = 0; i_XB < 4; ++i_XB)\n      state_XB[i_RU][i_XB] = XB_sol(i_XB);\n  }\n}", "meta": {"hexsha": "943261aa0aee8cc5313481d6c4a959bc562626cb", "size": 16860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "models_cpp/model_RDQ20_SE.cpp", "max_stars_repo_name": "FrancescoRegazzoni/cardiac-activation", "max_stars_repo_head_hexsha": "26f05df28891df7b3c69f16bb136cdced6b63c4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-17T00:26:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-17T00:26:28.000Z", "max_issues_repo_path": "models_cpp/model_RDQ20_SE.cpp", "max_issues_repo_name": "FrancescoRegazzoni/cardiac-activation", "max_issues_repo_head_hexsha": "26f05df28891df7b3c69f16bb136cdced6b63c4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models_cpp/model_RDQ20_SE.cpp", "max_forks_repo_name": "FrancescoRegazzoni/cardiac-activation", "max_forks_repo_head_hexsha": "26f05df28891df7b3c69f16bb136cdced6b63c4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4785276074, "max_line_length": 80, "alphanum_fraction": 0.5389679715, "num_tokens": 5950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.41111086923216794, "lm_q1q2_score": 0.22636067265082668}}
{"text": "#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <stdlib.h>\n#include <math.h>\n#include <typeinfo>\n#include <vector>\n#include <ostream>\n#include <iomanip>\n// to the time conversions (do not forget the files!!):\n#include \"time_conversion.c\"\n#include \"time_conversion.h\"\n\n/***\n\n    THIS IS THE DEPRECATED VERSION, PLEASE, USE THE FUNCTIONS AND STRUCTS OF THE FILE\n                                \"logreader2.hpp\"\n\n***/\n\n//#include <boost/filesystem.hpp>\n\n\n///\nconst int toUTC = 3;\n///\n\nusing namespace std;\n\n//const long double pi = 4*atan(1);\n//const int gpsLibLeap = 14;\n\n\nstruct gpsTime\n{\n\tunsigned short week;\n\tdouble seconds;\n};\n\n//alternative for the standart definition\nstruct gpsTime2\n{\n\tint week;\n\tdouble seconds;\n\n};\n\n//struct that contains the INS/GNSS observations\nstruct obs\n{\n\n\tgpsTime obsTime;\n\n\t//position\n\tdouble lat;\n\tdouble lgt;\n\tdouble h;\n\n\t//velocity\n\tdouble velX;\n\tdouble velY;\n\tdouble velZ;\n\n\t//attitude\n\tdouble pitch;    //along Y axis (\"phi\")\n\tdouble roll;     //along X axis (\"omega\")\n\tdouble azimuth;  //along Z axis (\"kappa\")\n\n\t//status\n\tstring status;\n};\n\n//struct that contains the covariance matrices of the INS/GNSS observations\nstruct obsCov\n{\n\tgpsTime covTime;\n\n\tdouble pos_mvc[3][3];\n\tdouble vel_mvc[3][3];\n\tdouble att_mvc[3][3];\n\n};\n\n//struct that contains all the others of the INS nested\nstruct obsWcov\n{\n\tobs observation;\n\n\tobsCov obsCovariances;\n};\n\n//struct for the phototimestamp (actually of the stereopair)\n\nstruct moment\n{\ndouble hour;\ndouble minute;\ndouble second;\n};\n\nstruct stereopairTimestamp\n{\ndouble tsyear;\ndouble tsmonth;\ndouble tsday;\n\ndouble leapSeconds;\n\nmoment leftStart;\nmoment leftEnd;\nmoment RightStart;\nmoment RightEnd;\n\ngpsTime _leftStart;\ngpsTime _leftEnd;\ngpsTime _RightStart;\ngpsTime _RightEnd;\n\ngpsTime finalTime;\n};\n\n//struct for the closest observations to the timestamps of the photos\nstruct intervals\n{\ndouble shortestNeg; int shortestNegPos;\ndouble shortestPos; int shortestPosPos;\ndouble theTime;\n};\n\nstruct survData\n{    //store the INS/GNSS data in:\n\tstd::vector<obsWcov> pvaWcov;\n\t//the iterator:\n\t//std::vector<obsWcov>::iterator  pvaWcovIt;\n\n\n\t//store the stereopair timestamps\n\tstd::vector<stereopairTimestamp> timestamps;\n\t//std::vector<stereopairTimestamp>::iterator timestampsIt;\n\n\t//store the shortests intervals of time\n\tstd::vector<intervals> finalIntervals;\n\n\t    //store the final ones:\n\tstd::vector<obsWcov> finalObsWcovs;\n\n\tstring log;\n\n\tstring log2_;\n\tdouble year;\n\tdouble month;\n\tdouble day;\n\tdouble LeapSeconds;\n\n\tsurvData(string NavLog,string PhotoTimesLog,double Year,double Month,double Day,double LeapSeconds_);\n\n\tvoid logReader();\n\n\tvoid photoTimestampReader();\n\n\tvoid dataInterpolation();\n\n\t};\n\n\tsurvData::survData(string NavLog,string PhotoTimesLog,double Year,double Month,double Day,double LeapSeconds_)\n\t{\n        log = NavLog;\n        log2_ = PhotoTimesLog;\n        year = Year;\n        month = Month;\n        day = Day;\n        LeapSeconds = LeapSeconds_;\n\n        logReader();\n        photoTimestampReader();\n        dataInterpolation();\n\n\t}\n\n//\n//    //store the INS/GNSS data in:\n//\tstd::vector<obsWcov> pvaWcov;\n//\t//the iterator:\n//\t//std::vector<obsWcov>::iterator  pvaWcovIt;\n//\n//\n//\t//store the stereopair timestamps\n//\tstd::vector<stereopairTimestamp> timestamps;\n//\t//std::vector<stereopairTimestamp>::iterator timestampsIt;\n//\n//\t//store the shortests intervals of time\n//\tstd::vector<intervals> finalIntervals;\n//\n//\t    //store the final ones:\n//\tstd::vector<obsWcov> finalObsWcovs;\n\ndouble linTerp(double time,double timeBefore,double timeAfter,double valBefore,double valAfter)\n{\n//the classic linear interpolation\ndouble value = valBefore + (  (valAfter-valBefore)* ((time-timeBefore)/(timeAfter-timeBefore)) );\n\nreturn value;\n}\n\nvoid survData::logReader()\n{\n    //3 steps, to pull of the separators\n\tstd::ifstream infile2(log);\n\tstring line2;\n    ofstream arquivo;\n\tarquivo.open(\"parte1.txt\");\n\twhile (std::getline(infile2, line2,','))\n\t{\n    arquivo<<line2<<endl;\n\t}\n    infile2.close();\n    arquivo.close();\n\n    ifstream parte2;\n    parte2.open(\"parte1.txt\");\n    ofstream parte2b(\"parte2.txt\");\n    string line3;\n    //parte2b.open(\"parte2.txt\");\n    while (std::getline(parte2,line3,';'))\n\t{parte2b << line3<<endl;}\n    parte2b.close(); parte2.close();\n    //a.close();\n\n    ifstream parte3;\n    parte3.open(\"parte2.txt\");\n    ofstream parte3b;\n    string line4;\n    parte3b.open(\"parte3.txt\");\n    while (std::getline(parte3,line4,'*'))\n\t{parte3b << line4<<endl;}\n\tparte3.close();\n\tparte3b.close();\n\n\t//now, its possible to do the data split simpler than before\n\tifstream data; data.open(\"parte3.txt\");\n\tstring value;\n\tbool itsObs=false,itsCovs=false;\n\tbool almostOne = false; //no observation without covariance\n\tint cObs=0,cCovs=0;\n\tobs obTemp;\n\tobsCov covTemp;\n\tobsWcov bothTemp;\n\n\tofstream report;report.open(\"report.txt\");\n\n\n        while (std::getline(data,value))\n        {\n            //for the observations:\n            if (value==\"%INSPVASA\" && almostOne)\n            { //loks for an observation\n                itsObs = true;\n                cObs++;\n                continue;\n            }\n            if(cObs==1 && itsObs)\n            {\n                obTemp.obsTime.week=stod(value);\n                //obTemp.obsTime.week=stringToDouble(value);\n                // //cout<<\"semana: \"<<stod(value)<<\"   \"<<value<<\"   \"<<endl;\n                cObs++;continue;\n            }\n            if(cObs==2 && itsObs)\n            {\n                cObs++;continue;\n            }\n            if(cObs==3 && itsObs)\n            {\n                cObs++;continue;\n            }\n            if(cObs==4 && itsObs)\n            {\n                obTemp.obsTime.seconds=stod(value);\n                //cout<<\"segundos: \"<<stringTdouble2(value)<<\"   \"<<value<<\"   \"<<endl;\n                //report<<value.find('.');\n                //report<<stringTdouble2(value);\n                //report << StringToNumber<double> ( value ) <<endl;\n                cObs++;continue;\n            }\n            if(cObs==5 && itsObs)\n            {\n                obTemp.lat=stod(value);\n                //cout<<\"latitude: \"<<value<<endl;\n                cObs++;continue;\n            }\n            if(cObs==6 && itsObs)\n            {\n                obTemp.lgt=stod(value);\n                //cout<<\"longitude: \"<<value<<endl;\n                cObs++;continue;\n            }\n            if(cObs==7 && itsObs)\n            {\n                obTemp.h=stod(value);\n               // cout<<\"h: \"<<value<<endl;\n                cObs++;continue;\n            }\n            if(cObs==8 && itsObs)\n            {\n                obTemp.velX=stod(value);\n                //cout<<\"velX: \"<<value<<endl;\n                cObs++;continue;\n            }\n                        if(cObs==9 && itsObs)\n            {\n                obTemp.velY=stod(value);\n                //cout<<\"velY: \"<<value<<endl;\n                cObs++;continue;\n            }\n                        if(cObs==10 && itsObs)\n            {\n                obTemp.velZ=stod(value);\n                //cout<<\"velZ: \"<<value<<endl;\n                cObs++;continue;\n            }\n                    if(cObs==11 && itsObs)\n            {\n                obTemp.roll=stod(value);\n                //cout<<\"roll: \"<<value<<endl;\n                cObs++;continue;\n            }\n                if(cObs==12 && itsObs)\n            {\n                obTemp.pitch=stod(value);\n                //cout<<\"pitch: \"<<value<<endl;\n                cObs++;continue;\n            }\n            if(cObs==13 && itsObs)\n            {\n                obTemp.azimuth=stod(value);\n                //cout<<\"azimuth: \"<<value<<endl;\n                cObs++;continue;\n            }\n            if(cObs==14 && itsObs)\n            {\n                obTemp.status=value;\n                //cout<<\"status \"<<value<<endl;\n                cObs++;continue;\n            }\n            if(cObs==15 && itsObs)\n            {\n           // cout<<endl<<endl<<\"FIM DE OBSERVAÇÃO\"<<endl;\n            bothTemp.observation=obTemp;\n            bothTemp.obsCovariances=covTemp;\n            pvaWcov.push_back(bothTemp);\n            report <<std::setprecision(15)<< bothTemp.observation.obsTime.seconds<<\"  \"<<bothTemp.obsCovariances.covTime.seconds<<endl;\n            //pva.push_back(obTemp);\n            itsObs=false;cObs=0;continue;\n            }\n\n\n            //for the covariances\n            if (value==\"%INSCOVSA\")\n            { //loks for a covariance\n                if (!almostOne) {almostOne=true;}\n                itsCovs = true;\n                cCovs++;\n                continue;\n            }\n\n            if(cCovs==1 && itsCovs)\n            {\n                covTemp.covTime.week=stod(value);\n                //covTemp.covTime.week=stringToDouble(value);\n           ////     cout<<\"semana: \"<<stod(value)<<\"   \"<<value<<endl;\n                cCovs++;continue;\n            }\n            if(cCovs==2 && itsCovs)\n            {\n            ////    cout<<\"segundos: \"<<stod(value)<<\"   \"<<value<<endl;\n                covTemp.covTime.seconds=stod(value);\n                cCovs++;continue;\n            }\n            if(cCovs==3 && itsCovs)\n            {\n                cCovs++;continue;\n            }\n            if(cCovs==4 && itsCovs)\n            {\n                cCovs++;continue;\n            }\n            if(cCovs==5 && itsCovs)\n            {\n                covTemp.pos_mvc[0][0]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                        if(cCovs==6 && itsCovs)\n            {\n                covTemp.pos_mvc[0][1]=stod(value);\n           ////     cout<<value<<endl;\n                cCovs++;continue;\n            }\n                        if(cCovs==7 && itsCovs)\n            {\n                covTemp.pos_mvc[0][2]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                        if(cCovs==8 && itsCovs)\n            {\n                covTemp.pos_mvc[1][0]=stod(value);\n           ////     cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                    if(cCovs==9 && itsCovs)\n            {\n                covTemp.pos_mvc[1][1]=stod(value);\n           ////     cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                    if(cCovs==10 && itsCovs)\n            {\n                covTemp.pos_mvc[1][2]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                if(cCovs==11 && itsCovs)\n            {\n                covTemp.pos_mvc[2][0]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n\n                            if(cCovs==12 && itsCovs)\n            {\n                covTemp.pos_mvc[2][1]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                        if(cCovs==13 && itsCovs)\n            {\n                covTemp.pos_mvc[2][2]=stod(value);\n             ////   cout<<value<<endl;\n                cCovs++;continue;\n            }\n\n                        if(cCovs==14 && itsCovs)\n            {\n                covTemp.vel_mvc[0][0]=stod(value);\n             ////   cout<<value<<endl;\n                cCovs++;continue;\n            }\n                        if(cCovs==15 && itsCovs)\n            {\n                covTemp.vel_mvc[0][1]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                        if(cCovs==16 && itsCovs)\n            {\n                covTemp.vel_mvc[0][2]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                        if(cCovs==17 && itsCovs)\n            {\n                covTemp.vel_mvc[1][0]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                    if(cCovs==18 && itsCovs)\n            {\n                covTemp.vel_mvc[1][1]=stod(value);\n             ////   cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                    if(cCovs==19 && itsCovs)\n            {\n                covTemp.vel_mvc[1][2]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                if(cCovs==20 && itsCovs)\n            {\n                covTemp.vel_mvc[2][0]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n\n                            if(cCovs==21 && itsCovs)\n            {\n                covTemp.vel_mvc[2][1]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                        if(cCovs==22 && itsCovs)\n            {\n                covTemp.vel_mvc[2][2]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n\n                        if(cCovs==23 && itsCovs)\n            {\n                covTemp.att_mvc[0][0]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                        if(cCovs==24 && itsCovs)\n            {\n                covTemp.att_mvc[0][1]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                        if(cCovs==25 && itsCovs)\n            {\n                covTemp.att_mvc[0][2]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                        if(cCovs==26 && itsCovs)\n            {\n                covTemp.att_mvc[1][0]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                    if(cCovs==27 && itsCovs)\n            {\n                covTemp.att_mvc[1][1]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                    if(cCovs==28 && itsCovs)\n            {\n                covTemp.att_mvc[1][2]=stod(value);\n             ////   cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                if(cCovs==29 && itsCovs)\n            {\n                covTemp.att_mvc[2][0]=stod(value);\n             ////   cout<<value<<endl;\n                cCovs++;continue;\n            }\n\n                            if(cCovs==30 && itsCovs)\n            {\n                covTemp.att_mvc[2][1]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n                                        if(cCovs==31 && itsCovs)\n            {\n                covTemp.att_mvc[2][2]=stod(value);\n            ////    cout<<value<<endl;\n                cCovs++;continue;\n            }\n            if(cCovs==32 && itsCovs)\n            {\n            //cov.push_back(covTemp);\n            ////cout<<endl<<endl<<\"FIM DE COVARIANCIAS\"<<endl;\n            cCovs=0;itsCovs=false;\n            }\n\n        }\n\n}\n\nvoid survData::photoTimestampReader()\n{\n// if the time in UTC format are without Leap Seconds, insert \"0\" as the total of leap seconds\n//variables for time conversion\n    unsigned short  tempWeek;\n    double          tempTow;\n    bool            convOK;\n\n    //the log with the final timestamps\n    ofstream finalTimes(\"momento_da_tomada.txt\");\n\n    //first: take away the separators\n    //first: \":\"\n    ifstream rawlog(log2_);\n    string line1;\n    ofstream part1(\"p1.txt\");\n        while(getline(rawlog,line1,':'))\n        {\n        part1<<line1<<endl;\n        }\n        rawlog.close();part1.close();\n\n        //first: \";\"\n        ifstream log2(\"p1.txt\");\n        string line2;\n        ofstream part2(\"p2.txt\");\n        while(getline(log2,line2,';'))\n        {\n        //if(line2 == \"Start\" || line2 == \"End\"){part2<<line2;}\n        //else {part2<<line2<<endl;}\n        //if(line2 == \"\") cout<<\"existe\"<<endl;\n        part2<<line2<<endl;\n        }\n        log2.close();part2.close();\n\n    //now, we could read the one-value-per-line file\n    ifstream log3(\"p2.txt\");\n    string line3;\n    moment tempLS,tempLE,tempRS,tempRE;\n    stereopairTimestamp tempStamp;\n    double tHour,tMin,tSec;\n\n    //control variables\n    int count=1;\n    bool OneLS=false;\n    bool OneLE=false;\n    bool OneRS=false;\n    bool OneRE=false;\n    //bool isLeft=false;\n    //bool isRight=false;\n    bool isLeft,isRight;\n    int gravou1=0;\n\nwhile(getline(log3,line3))\n{\n//if (line3 == \"\")cout<<line3<<endl;\n\n        if (count==1)\n        {\n                if(line3 != \"\")\n                {tHour=stod(line3);}\n        count++;continue;\n        }\n        if (count==2)\n        {\n                if(line3 != \"\")\n                {tMin=stod(line3);}\n        count++;continue;\n        }\n        if (count==3)\n        {\n                if(line3 != \"\")\n                {tSec=stod(line3);}\n        count++;continue;\n        }\n        if (count==4)\n        {\n            if(line3==\"1\")\n            {isLeft=true;isRight=false;}\n            if(line3==\"2\")\n            {isLeft=false;isRight=true;}\n        count++;continue;\n        }\n        if (count==5)\n        {\n            if(line3==\"Start\")\n            {\n                if(isLeft)\n                {\n                    tempLS.hour=tHour;\n                    tempLS.minute=tMin;\n                    tempLS.second=tSec;\n//                    cout<<\"passo OK\"<<endl;\n                    if(!OneLS){OneLS=true;}\n                }\n                if(isRight)\n                {\n                    tempRS.hour=tHour;\n                    tempRS.minute=tMin;\n                    tempRS.second=tSec;\n                    if(!OneRS){OneRS=true;}\n                }\n            }\n            if(line3==\"End\")\n            {\n                if(isLeft && OneLS)\n                {\n                    tempLE.hour=tHour;\n                    tempLE.minute=tMin;\n                    tempLE.second=tSec;\n                    if(!OneLE){OneLE=true;}\n                }\n                if(isRight && OneLS)\n                {\n                    tempRE.hour=tHour;\n                    tempRE.minute=tMin;\n                    tempRE.second=tSec;\n                    if(!OneRE){OneRE=true;}\n                }\n            }\n        count++;continue;\n        }\n        if (count==6)\n        {\n                if(OneLE && OneLS && OneRE && OneRS)\n                {\n                //record the timestamps in UTC\n                tempStamp.leftStart     = tempLS;\n                tempStamp.leftEnd       = tempLE;\n                tempStamp.RightStart    = tempRS;\n                tempStamp.RightEnd      = tempRE;\n                tempStamp.tsyear        = year;\n                tempStamp.tsmonth       = month;\n                tempStamp.tsday         = day;\n                tempStamp.leapSeconds=LeapSeconds;\n                //record the timestamps in GPS time:\n                convOK =  TIMECONV_GetGPSTimeFromRinexTime(year,month,day,\n                tempLS.hour+float(toUTC),tempLS.minute,tempLS.second,&tempWeek,&tempTow);\n                tempStamp._leftStart.week           =   tempWeek;\n                tempStamp._leftStart.seconds        =   tempTow+LeapSeconds;\n\n                convOK =  TIMECONV_GetGPSTimeFromRinexTime(year,month,day,\n                tempLE.hour+float(toUTC),tempLE.minute,tempLE.second,&tempWeek,&tempTow);\n                tempStamp._leftEnd.week              =  tempWeek;\n                tempStamp._leftEnd.seconds           =   tempTow+LeapSeconds;\n\n                convOK =  TIMECONV_GetGPSTimeFromRinexTime(year,month,day,\n                tempRS.hour+float(toUTC),tempRS.minute,tempRS.second,&tempWeek,&tempTow);\n                tempStamp._RightStart.week           = tempWeek;\n                tempStamp._RightStart.seconds        = tempTow+LeapSeconds;\n\n                convOK =  TIMECONV_GetGPSTimeFromRinexTime(year,month,day,\n                tempRE.hour+float(toUTC),tempRE.minute,tempRE.second,&tempWeek,&tempTow);\n                tempStamp._RightEnd.week            = tempWeek;\n                tempStamp._RightEnd.seconds         = tempTow+LeapSeconds;\n\n                //the final timestamp:\n                tempStamp.finalTime.week            =tempWeek;\n                tempStamp.finalTime.seconds         =( ((tempStamp._leftStart.seconds+tempStamp._leftEnd.seconds)/2) +  ((tempStamp._RightStart.seconds+tempStamp._RightEnd.seconds)/2) ) / 2;\n\n\n\n                timestamps.push_back(tempStamp);\n                OneLS=false;OneLE=false;OneRS=false;OneRE=false;\n                gravou1++;\n//                cout<<gravou1<<endl;\n                }\n        count=1;continue;\n        }\n\n} //end of the main process of the function\n\nfinalTimes << \"semana GPS: \" << tempWeek<<endl<<endl;\n\n\n//cout<<timestamps.size()<<endl<<endl;\nfor (unsigned int i=0;i < timestamps.size();i++)\n{\n//cout<<endl<<i<<endl<<endl;\n//cout<<timestamps.at(i).leftStart.hour<<endl;\n//cout<<timestamps.at(i).leftStart.minute<<endl;\n//cout<<timestamps.at(i).leftStart.second<<endl;\n//\n//cout<<timestamps.at(i).RightStart.hour<<endl;\n//cout<<timestamps.at(i).RightStart.minute<<endl;\n//cout<<timestamps.at(i).RightStart.second<<endl;\n//\n//cout<<timestamps.at(i).leftEnd.hour<<endl;\n//cout<<timestamps.at(i).leftEnd.minute<<endl;\n//cout<<timestamps.at(i).leftEnd.second<<endl;\n//\n//cout<<timestamps.at(i).RightEnd.hour<<endl;\n//cout<<timestamps.at(i).RightEnd.minute<<endl;\n//cout<<timestamps.at(i).RightEnd.second<<endl;\n//\n//cout<<timestamps.at(i).finalTime.week<<endl;\n//cout<<std::setprecision(20)<<timestamps.at(i).finalTime.seconds<<endl<<endl;\n//\n//cout<<std::setprecision(20)<<timestamps.at(i)._leftStart.seconds<<endl;\n//\n//cout<<std::setprecision(20)<<timestamps.at(i)._leftEnd.seconds<<endl;\n//\n//cout<<std::setprecision(20)<<timestamps.at(i)._RightStart.seconds<<endl;\n//\n//cout<<std::setprecision(20)<<timestamps.at(i)._RightEnd.seconds<<endl<<endl;\n\n//cout<<day<<\"    \"<<month<<\"     \"<<year<<endl;\n\nfinalTimes<<std::setprecision(13)<<timestamps.at(i).finalTime.seconds<<endl;\n}\n\nfinalTimes.close();\n}\n\n\n// function for the interpolation of data\nvoid survData::dataInterpolation()\n{\ndouble delta;\nint stereopair = 0;\nintervals tempIntervals;\n//the differences in time:\nofstream deltas(\"diftempo.txt\");\n//the final positions\nofstream finalObservations(\"observacoes.txt\");\n//arbitrary values\ndouble minNeg = -1000; int posMinNeg;\ndouble minPos =  1000; int posMinPos;\n//temporary variables\nobsWcov tempObs;\nobs tempObsBef,tempObsAf;\ndouble tBef,tAft,time1;\n\n\n        for (unsigned int i=0;i < timestamps.size();i++)\n        {\n        stereopair++;\n        deltas<<\"Estereopar  \"<<stereopair<<endl<<endl;\n            for(unsigned  int j=0;j < pvaWcov.size();j++)\n            {\n            delta =pvaWcov.at(j).observation.obsTime.seconds - timestamps.at(i).finalTime.seconds;\n\n            if (delta <= 0 && delta > minNeg)\n            {\n            minNeg = delta;posMinNeg=j;\n            }\n\n            if (delta >= 0 && delta < minPos)\n            {\n            minPos = delta;posMinPos=j;\n            }\n\n\n            deltas<<std::setprecision(15)<<delta<<\"  \"<<minNeg<<\"  \"<<minPos<<endl;\n            }\n            deltas<<endl;\n\n            deltas<<\"menor negativo:  \"<<minNeg<<\"  menor positivo:  \"<<minPos<<\" primeira: \"<<posMinNeg<<\" segunda \"<<posMinPos<<endl;\n            deltas<<endl<<endl;\n            //storing that shortest intervals and these positions\n            tempIntervals.shortestNeg = minNeg;tempIntervals.shortestPos = minPos;\n            tempIntervals.shortestNegPos = posMinNeg; tempIntervals.shortestPosPos = posMinPos;\n            tempIntervals.theTime = timestamps.at(i).finalTime.seconds;\n            finalIntervals.push_back(tempIntervals);\n            //reassign the temporary values:\n            minNeg = -1000;minPos=1000;\n        }\n        deltas.close();\n        //now we have the intervals of time and the positions to do the interpolation\n\n        for(unsigned int k=0;k < finalIntervals.size();k++)\n        {\n        tBef = pvaWcov.at(finalIntervals.at(k).shortestNegPos).observation.obsTime.seconds;\n        tAft = pvaWcov.at(finalIntervals.at(k).shortestPosPos).observation.obsTime.seconds;\n        time1 = finalIntervals.at(k).theTime;\n\n        tempObsBef  =   pvaWcov.at(finalIntervals.at(k).shortestNegPos).observation;\n        tempObsAf   =   pvaWcov.at(finalIntervals.at(k).shortestPosPos).observation;\n\n        tempObs.observation.lat     = linTerp(time1,tBef,tAft,tempObsBef.lat,tempObsAf.lat);\n        tempObs.observation.lgt     = linTerp(time1,tBef,tAft,tempObsBef.lgt,tempObsAf.lgt);\n        tempObs.observation.h       = linTerp(time1,tBef,tAft,tempObsBef.h,tempObsAf.h);\n        tempObs.observation.roll   = linTerp(time1,tBef,tAft,tempObsBef.roll,tempObsAf.roll);\n        tempObs.observation.pitch     = linTerp(time1,tBef,tAft,tempObsBef.pitch,tempObsAf.pitch);\n        tempObs.observation.azimuth   = linTerp(time1,tBef,tAft,tempObsBef.azimuth,tempObsAf.azimuth);\n        tempObs.observation.velX    = linTerp(time1,tBef,tAft,tempObsBef.velX,tempObsAf.velX);\n        tempObs.observation.velY    = linTerp(time1,tBef,tAft,tempObsBef.velY,tempObsAf.velY);\n        tempObs.observation.velZ    = linTerp(time1,tBef,tAft,tempObsBef.velZ,tempObsAf.velZ);\n\n\n        finalObservations.precision(40);\n        finalObservations<<tempObs.observation.lat<<\",\";\n        finalObservations<<tempObs.observation.lgt<<\",\";\n        finalObservations<<tempObs.observation.h<<\",\";\n        finalObservations<<tempObs.observation.roll<<\",\";\n        finalObservations<<tempObs.observation.pitch<<\",\";\n        finalObservations<<tempObs.observation.azimuth<<\",\";\n        finalObservations<<tempObs.observation.velX<<\",\";\n        finalObservations<<tempObs.observation.velY<<\",\";\n        finalObservations<<tempObs.observation.velZ<<endl;\n\n        //for the covariances, the NearestNeighbour is good enough\n        if (fabs(finalIntervals.at(k).shortestNeg) < fabs(finalIntervals.at(k).shortestPos)){\n        tempObs.obsCovariances = pvaWcov.at(finalIntervals.at(k).shortestNegPos).obsCovariances;}\n        else {tempObs.obsCovariances = pvaWcov.at(finalIntervals.at(k).shortestPosPos).obsCovariances;}\n\n        finalObsWcovs.push_back(tempObs);\n        }\n//cout<<finalObsWcovs.size()<<endl;\n\n\n\nfinalObservations.close();\n}\n\n", "meta": {"hexsha": "65de9b7c21bfa4b19b583a5dad01ff745316a271", "size": 26377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "logreader.hpp", "max_stars_repo_name": "kauevestena/smmt", "max_stars_repo_head_hexsha": "17e63e5b995f75e8b58e75d3d3a49049b0cf92eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-04T21:47:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-04T21:47:42.000Z", "max_issues_repo_path": "logreader.hpp", "max_issues_repo_name": "kauevestena/smmt", "max_issues_repo_head_hexsha": "17e63e5b995f75e8b58e75d3d3a49049b0cf92eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "logreader.hpp", "max_forks_repo_name": "kauevestena/smmt", "max_forks_repo_head_hexsha": "17e63e5b995f75e8b58e75d3d3a49049b0cf92eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9398410897, "max_line_length": 190, "alphanum_fraction": 0.5115062365, "num_tokens": 6544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185498374789, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22630080509968187}}
{"text": "#include <cstdlib>\n#include <algorithm>\n#include <sstream>\n#include <iostream>\n#include <vector>\n#include <limits>\n#include <cmath>\n#include <chrono>\n#include <ctime>\n#include <time.h>\n\n#include <unordered_map>\n#include <unordered_set>\n\n#include <execinfo.h>\n#include <unistd.h>\n#include <signal.h>\n\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/archive/text_iarchive.hpp>\n#include <boost/program_options.hpp>\n\n#include \"cnn/training.h\"\n#include \"cnn/cnn.h\"\n#include \"cnn/expr.h\"\n#include \"cnn/nodes.h\"\n#include \"cnn/lstm.h\"\n#include \"cnn/rnn.h\"\n#include \"c2.h\"\n\ncpyp::Corpus corpus;\nvolatile bool requested_stop = false;\nunsigned LAYERS = 2;\nunsigned INPUT_DIM = 40;\nunsigned HIDDEN_DIM = 60;\nunsigned ACTION_DIM = 36;\nunsigned PRETRAINED_DIM = 50;\nunsigned LSTM_INPUT_DIM = 60;\nunsigned POS_DIM = 10;\nunsigned REL_DIM = 8;\n\n\nbool USE_POS = false;\n\nconstexpr const char* ROOT_SYMBOL = \"ROOT\";\nunsigned kROOT_SYMBOL = 0;\nunsigned ACTION_SIZE = 0;\nunsigned VOCAB_SIZE = 0;\nunsigned POS_SIZE = 0;\n\nusing namespace cnn::expr;\nusing namespace cnn;\nusing namespace std;\nnamespace po = boost::program_options;\n\nvector<unsigned> possible_actions;\nunordered_map<unsigned, vector<float>> pretrained;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"training_data,T\", po::value<string>(), \"List of Transitions - Training corpus\")\n        (\"dev_data,d\", po::value<string>(), \"Development corpus\")\n        (\"test_data,p\", po::value<string>(), \"Test corpus\")\n        (\"unk_strategy,o\", po::value<unsigned>()->default_value(1), \"Unknown word strategy: 1 = singletons become UNK with probability unk_prob\")\n        (\"unk_prob,u\", po::value<double>()->default_value(0.2), \"Probably with which to replace singletons with UNK in training data\")\n        (\"model,m\", po::value<string>(), \"Load saved model from this file\")\n        (\"use_pos_tags,P\", \"make POS tags visible to parser\")\n        (\"layers\", po::value<unsigned>()->default_value(2), \"number of LSTM layers\")\n        (\"action_dim\", po::value<unsigned>()->default_value(16), \"action embedding size\")\n        (\"input_dim\", po::value<unsigned>()->default_value(32), \"input embedding size\")\n        (\"hidden_dim\", po::value<unsigned>()->default_value(64), \"hidden dimension\")\n        (\"pretrained_dim\", po::value<unsigned>()->default_value(50), \"pretrained input dimension\")\n        (\"pos_dim\", po::value<unsigned>()->default_value(12), \"POS dimension\")\n        (\"rel_dim\", po::value<unsigned>()->default_value(10), \"relation dimension\")\n        (\"lstm_input_dim\", po::value<unsigned>()->default_value(60), \"LSTM input dimension\")\n        (\"train,t\", \"Should training be run?\")\n        (\"words,w\", po::value<string>(), \"Pretrained word embeddings\")\n        (\"help,h\", \"Help\");\n  po::options_description dcmdline_options;\n  dcmdline_options.add(opts);\n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"help\")) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n  if (conf->count(\"training_data\") == 0) {\n    cerr << \"Please specify --traing_data (-T): this is required to determine the vocabulary mapping, even if the parser is used in prediction mode.\\n\";\n    exit(1);\n  }\n}\n\nstruct ParserBuilder {\n\n  LSTMBuilder stack_lstm; // (layers, input, hidden, trainer)\n  LSTMBuilder buffer_lstm;\n  LSTMBuilder action_lstm;\n  LookupParameters* p_w; // word embeddings\n  LookupParameters* p_t; // pretrained word embeddings (not updated)\n  LookupParameters* p_a; // input action embeddings\n  LookupParameters* p_r; // relation embeddings\n  LookupParameters* p_p; // pos tag embeddings\n  Parameters* p_pbias; // parser state bias\n  Parameters* p_A; // action lstm to parser state\n  Parameters* p_B; // buffer lstm to parser state\n  Parameters* p_S; // stack lstm to parser state\n  Parameters* p_H; // head matrix for composition function\n  Parameters* p_D; // dependency matrix for composition function\n  Parameters* p_R; // relation matrix for composition function\n  Parameters* p_w2l; // word to LSTM input\n  Parameters* p_p2l; // POS to LSTM input\n  Parameters* p_t2l; // pretrained word embeddings to LSTM input\n  Parameters* p_ib; // LSTM input bias\n  Parameters* p_cbias; // composition function bias\n  Parameters* p_p2a;   // parser state to action\n  Parameters* p_action_start;  // action bias\n  Parameters* p_abias;  // action bias\n  Parameters* p_buffer_guard;  // end of buffer\n  Parameters* p_stack_guard;  // end of stack\n\n  explicit ParserBuilder(Model* model, const unordered_map<unsigned, vector<float>>& pretrained) :\n      stack_lstm(LAYERS, LSTM_INPUT_DIM, HIDDEN_DIM, model),\n      buffer_lstm(LAYERS, LSTM_INPUT_DIM, HIDDEN_DIM, model),\n      action_lstm(LAYERS, ACTION_DIM, HIDDEN_DIM, model),\n      p_w(model->add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM})),\n      p_a(model->add_lookup_parameters(ACTION_SIZE, {ACTION_DIM})),\n      p_r(model->add_lookup_parameters(ACTION_SIZE, {REL_DIM})),\n      p_pbias(model->add_parameters({HIDDEN_DIM})),\n      p_A(model->add_parameters({HIDDEN_DIM, HIDDEN_DIM})),\n      p_B(model->add_parameters({HIDDEN_DIM, HIDDEN_DIM})),\n      p_S(model->add_parameters({HIDDEN_DIM, HIDDEN_DIM})),\n      p_H(model->add_parameters({LSTM_INPUT_DIM, LSTM_INPUT_DIM})),\n      p_D(model->add_parameters({LSTM_INPUT_DIM, LSTM_INPUT_DIM})),\n      p_R(model->add_parameters({LSTM_INPUT_DIM, REL_DIM})),\n      p_w2l(model->add_parameters({LSTM_INPUT_DIM, INPUT_DIM})),\n      p_ib(model->add_parameters({LSTM_INPUT_DIM})),\n      p_cbias(model->add_parameters({LSTM_INPUT_DIM})),\n      p_p2a(model->add_parameters({ACTION_SIZE, HIDDEN_DIM})),\n      p_action_start(model->add_parameters({ACTION_DIM})),\n      p_abias(model->add_parameters({ACTION_SIZE})),\n      p_buffer_guard(model->add_parameters({LSTM_INPUT_DIM})),\n      p_stack_guard(model->add_parameters({LSTM_INPUT_DIM})) {\n    if (USE_POS) {\n      p_p = model->add_lookup_parameters(POS_SIZE, {POS_DIM});\n      p_p2l = model->add_parameters({LSTM_INPUT_DIM, POS_DIM});\n    }\n    if (pretrained.size() > 0) {\n      p_t = model->add_lookup_parameters(VOCAB_SIZE, {PRETRAINED_DIM});\n      for (auto it : pretrained)\n        p_t->Initialize(it.first, it.second);\n      p_t2l = model->add_parameters({LSTM_INPUT_DIM, PRETRAINED_DIM});\n    } else {\n      p_t = nullptr;\n      p_t2l = nullptr;\n    }\n  }\n\nstatic bool IsActionForbidden(const string& a, unsigned bsize, unsigned ssize, const vector<int>& stacki) {\n  if (a[1]=='W' && ssize<3) return true;\n  if (a[1]=='W') {\n        int top=stacki[stacki.size()-1];\n        int sec=stacki[stacki.size()-2];\n        if (sec>top) return true;\n  }\n\n  bool is_shift = (a[0] == 'S' && a[1]=='H');\n  bool is_reduce = !is_shift;\n  if (is_shift && bsize == 1) return true;\n  if (is_reduce && ssize < 3) return true;\n  if (bsize == 2 && // ROOT is the only thing remaining on buffer\n      ssize > 2 && // there is more than a single element on the stack\n      is_shift) return true;\n  // only attach left to ROOT\n  if (bsize == 1 && ssize == 3 && a[0] == 'R') return true;\n  return false;\n}\n\n// take a vector of actions and return a parse tree (labeling of every\n// word position with its head's position)\nstatic map<int,int> compute_heads(unsigned sent_len, const vector<unsigned>& actions, const vector<string>& setOfActions, map<int,string>* pr = nullptr) {\n  map<int,int> heads;\n  map<int,string> r;\n  map<int,string>& rels = (pr ? *pr : r);\n  for(unsigned i=0;i<sent_len;i++) { heads[i]=-1; rels[i]=\"ERROR\"; }\n  vector<int> bufferi(sent_len + 1, 0), stacki(1, -999);\n  for (unsigned i = 0; i < sent_len; ++i)\n    bufferi[sent_len - i] = i;\n  bufferi[0] = -999;\n  for (auto action: actions) { // loop over transitions for sentence\n    const string& actionString=setOfActions[action];\n    const char ac = actionString[0];\n    const char ac2 = actionString[1];\n    if (ac =='S' && ac2=='H') {  // SHIFT\n      assert(bufferi.size() > 1); // dummy symbol means > 1 (not >= 1)\n      stacki.push_back(bufferi.back());\n      bufferi.pop_back();\n    } else if (ac=='S' && ac2=='W') { // SWAP\n      assert(stacki.size() > 2);\n      unsigned ii = 0, jj = 0;\n      jj = stacki.back();\n      stacki.pop_back();\n      ii = stacki.back();\n      stacki.pop_back();\n      bufferi.push_back(ii);\n      stacki.push_back(jj);\n    } else { // LEFT or RIGHT\n      assert(stacki.size() > 2); // dummy symbol means > 2 (not >= 2)\n      assert(ac == 'L' || ac == 'R');\n      unsigned depi = 0, headi = 0;\n      (ac == 'R' ? depi : headi) = stacki.back();\n      stacki.pop_back();\n      (ac == 'R' ? headi : depi) = stacki.back();\n      stacki.pop_back();\n      stacki.push_back(headi);\n      heads[depi] = headi;\n      rels[depi] = actionString;\n    }\n  }\n  assert(bufferi.size() == 1);\n  //assert(stacki.size() == 2);\n  return heads;\n}\n\n// *** if correct_actions is empty, this runs greedy decoding ***\n// returns parse actions for input sentence (in training just returns the reference)\n// OOV handling: raw_sent will have the actual words\n//               sent will have words replaced by appropriate UNK tokens\n// this lets us use pretrained embeddings, when available, for words that were OOV in the\n// parser training data\nvector<unsigned> log_prob_parser(ComputationGraph* hg,\n                     const vector<unsigned>& raw_sent,  // raw sentence\n                     const vector<unsigned>& sent,  // sent with oovs replaced\n                     const vector<unsigned>& sentPos,\n                     const vector<unsigned>& correct_actions,\n                     const vector<string>& setOfActions,\n                     const map<unsigned, std::string>& intToWords,\n                     double *right) {\n    vector<unsigned> results;\n    const bool build_training_graph = correct_actions.size() > 0;\n\n    stack_lstm.new_graph(*hg);\n    buffer_lstm.new_graph(*hg);\n    action_lstm.new_graph(*hg);\n    stack_lstm.start_new_sequence();\n    buffer_lstm.start_new_sequence();\n    action_lstm.start_new_sequence();\n    // variables in the computation graph representing the parameters\n    Expression pbias = parameter(*hg, p_pbias);\n    Expression H = parameter(*hg, p_H);\n    Expression D = parameter(*hg, p_D);\n    Expression R = parameter(*hg, p_R);\n    Expression cbias = parameter(*hg, p_cbias);\n    Expression S = parameter(*hg, p_S);\n    Expression B = parameter(*hg, p_B);\n    Expression A = parameter(*hg, p_A);\n    Expression ib = parameter(*hg, p_ib);\n    Expression w2l = parameter(*hg, p_w2l);\n    Expression p2l;\n    if (USE_POS)\n      p2l = parameter(*hg, p_p2l);\n    Expression t2l;\n    if (p_t2l)\n      t2l = parameter(*hg, p_t2l);\n    Expression p2a = parameter(*hg, p_p2a);\n    Expression abias = parameter(*hg, p_abias);\n    Expression action_start = parameter(*hg, p_action_start);\n\n    action_lstm.add_input(action_start);\n\n    vector<Expression> buffer(sent.size() + 1);  // variables representing word embeddings (possibly including POS info)\n    vector<int> bufferi(sent.size() + 1);  // position of the words in the sentence\n    // precompute buffer representation from left to right\n\n    for (unsigned i = 0; i < sent.size(); ++i) {\n      assert(sent[i] < VOCAB_SIZE);\n      Expression w =lookup(*hg, p_w, sent[i]);\n\n      vector<Expression> args = {ib, w2l, w}; // learn embeddings\n      if (USE_POS) { // learn POS tag?\n        Expression p = lookup(*hg, p_p, sentPos[i]);\n        args.push_back(p2l);\n        args.push_back(p);\n      }\n      if (p_t && pretrained.count(raw_sent[i])) {  // include fixed pretrained vectors?\n        Expression t = const_lookup(*hg, p_t, raw_sent[i]);\n        args.push_back(t2l);\n        args.push_back(t);\n      }\n      buffer[sent.size() - i] = rectify(affine_transform(args));\n      bufferi[sent.size() - i] = i;\n    }\n    // dummy symbol to represent the empty buffer\n    buffer[0] = parameter(*hg, p_buffer_guard);\n    bufferi[0] = -999;\n    for (auto& b : buffer)\n      buffer_lstm.add_input(b);\n\n    vector<Expression> stack;  // variables representing subtree embeddings\n    vector<int> stacki; // position of words in the sentence of head of subtree\n    stack.push_back(parameter(*hg, p_stack_guard));\n    stacki.push_back(-999); // not used for anything\n    // drive dummy symbol on stack through LSTM\n    stack_lstm.add_input(stack.back());\n    vector<Expression> log_probs;\n    string rootword;\n    unsigned action_count = 0;  // incremented at each prediction\n    while(stack.size() > 2 || buffer.size() > 1) {\n      // get list of possible actions for the current parser state\n      vector<unsigned> current_valid_actions;\n      for (auto a: possible_actions) {\n        if (IsActionForbidden(setOfActions[a], buffer.size(), stack.size(), stacki))\n          continue;\n        current_valid_actions.push_back(a);\n      }\n\n      // p_t = pbias + S * slstm + B * blstm + A * almst\n      Expression p_t = affine_transform({pbias, S, stack_lstm.back(), B, buffer_lstm.back(), A, action_lstm.back()});\n      Expression nlp_t = rectify(p_t);\n      // r_t = abias + p2a * nlp\n      Expression r_t = affine_transform({abias, p2a, nlp_t});\n\n      // adist = log_softmax(r_t, current_valid_actions)\n      Expression adiste = log_softmax(r_t, current_valid_actions);\n      vector<float> adist = as_vector(hg->incremental_forward());\n      double best_score = adist[current_valid_actions[0]];\n      unsigned best_a = current_valid_actions[0];\n      for (unsigned i = 1; i < current_valid_actions.size(); ++i) {\n        if (adist[current_valid_actions[i]] > best_score) {\n          best_score = adist[current_valid_actions[i]];\n          best_a = current_valid_actions[i];\n        }\n      }\n      unsigned action = best_a;\n      if (build_training_graph) {  // if we have reference actions (for training) use the reference action\n        action = correct_actions[action_count];\n        if (best_a == action) { (*right)++; }\n      }\n      ++action_count;\n      log_probs.push_back(pick(adiste, action));\n      results.push_back(action);\n\n      // add current action to action LSTM\n      Expression actione = lookup(*hg, p_a, action);\n      action_lstm.add_input(actione);\n\n      // get relation embedding from action (TODO: convert to relation from action?)\n      Expression relation = lookup(*hg, p_r, action);\n\n      // do action\n      const string& actionString=setOfActions[action];\n      const char ac = actionString[0];\n      const char ac2 = actionString[1];\n\n\n      if (ac =='S' && ac2=='H') {  // SHIFT\n        assert(buffer.size() > 1); // dummy symbol means > 1 (not >= 1)\n        stack.push_back(buffer.back());\n        stack_lstm.add_input(buffer.back());\n        buffer.pop_back();\n        buffer_lstm.rewind_one_step();\n        stacki.push_back(bufferi.back());\n        bufferi.pop_back();\n      } else if (ac=='S' && ac2=='W'){ //SWAP --- Miguel\n        assert(stack.size() > 2); // dummy symbol means > 2 (not >= 2)\n\n        Expression toki, tokj;\n        unsigned ii = 0, jj = 0;\n        tokj=stack.back();\n        jj=stacki.back();\n        stack.pop_back();\n        stacki.pop_back();\n\n        toki=stack.back();\n        ii=stacki.back();\n        stack.pop_back();\n        stacki.pop_back();\n\n        buffer.push_back(toki);\n        bufferi.push_back(ii);\n\n        stack_lstm.rewind_one_step();\n        stack_lstm.rewind_one_step();\n\n        buffer_lstm.add_input(buffer.back());\n\n        stack.push_back(tokj);\n        stacki.push_back(jj);\n\n        stack_lstm.add_input(stack.back());\n      } else { // LEFT or RIGHT\n        assert(stack.size() > 2); // dummy symbol means > 2 (not >= 2)\n        assert(ac == 'L' || ac == 'R');\n        Expression dep, head;\n        unsigned depi = 0, headi = 0;\n        (ac == 'R' ? dep : head) = stack.back();\n        (ac == 'R' ? depi : headi) = stacki.back();\n        stack.pop_back();\n        stacki.pop_back();\n        (ac == 'R' ? head : dep) = stack.back();\n        (ac == 'R' ? headi : depi) = stacki.back();\n        stack.pop_back();\n        stacki.pop_back();\n        if (headi == sent.size() - 1) rootword = intToWords.find(sent[depi])->second;\n        // composed = cbias + H * head + D * dep + R * relation\n        Expression composed = affine_transform({cbias, H, head, D, dep, R, relation});\n        Expression nlcomposed = tanh(composed);\n        stack_lstm.rewind_one_step();\n        stack_lstm.rewind_one_step();\n        stack_lstm.add_input(nlcomposed);\n        stack.push_back(nlcomposed);\n        stacki.push_back(headi);\n      }\n    }\n    assert(stack.size() == 2); // guard symbol, root\n    assert(stacki.size() == 2);\n    assert(buffer.size() == 1); // guard symbol\n    assert(bufferi.size() == 1);\n    Expression tot_neglogprob = -sum(log_probs);\n    assert(tot_neglogprob.pg != nullptr);\n    return results;\n  }\n};\n\nvoid signal_callback_handler(int /* signum */) {\n  if (requested_stop) {\n    cerr << \"\\nReceived SIGINT again, quitting.\\n\";\n    _exit(1);\n  }\n  cerr << \"\\nReceived SIGINT terminating optimization early...\\n\";\n  requested_stop = true;\n}\n\nunsigned compute_correct(const map<int,int>& ref, const map<int,int>& hyp, unsigned len) {\n  unsigned res = 0;\n  for (unsigned i = 0; i < len; ++i) {\n    auto ri = ref.find(i);\n    auto hi = hyp.find(i);\n    assert(ri != ref.end());\n    assert(hi != hyp.end());\n    if (ri->second == hi->second) ++res;\n  }\n  return res;\n}\n\nvoid output_conll(const vector<unsigned>& sentence, const vector<unsigned>& pos,\n                  const vector<string>& sentenceUnkStrings, \n                  const map<unsigned, string>& intToWords, \n                  const map<unsigned, string>& intToPos, \n                  const map<int,int>& hyp, const map<int,string>& rel_hyp) {\n  for (unsigned i = 0; i < (sentence.size()-1); ++i) {\n    auto index = i + 1;\n    assert(i < sentenceUnkStrings.size() && \n           ((sentence[i] == corpus.get_or_add_word(cpyp::Corpus::UNK) &&\n             sentenceUnkStrings[i].size() > 0) ||\n            (sentence[i] != corpus.get_or_add_word(cpyp::Corpus::UNK) &&\n             sentenceUnkStrings[i].size() == 0 &&\n             intToWords.find(sentence[i]) != intToWords.end())));\n    string wit = (sentenceUnkStrings[i].size() > 0)? \n      sentenceUnkStrings[i] : intToWords.find(sentence[i])->second;\n    auto pit = intToPos.find(pos[i]);\n    assert(hyp.find(i) != hyp.end());\n    auto hyp_head = hyp.find(i)->second + 1;\n    if (hyp_head == (int)sentence.size()) hyp_head = 0;\n    auto hyp_rel_it = rel_hyp.find(i);\n    assert(hyp_rel_it != rel_hyp.end());\n    auto hyp_rel = hyp_rel_it->second;\n    size_t first_char_in_rel = hyp_rel.find('(') + 1;\n    size_t last_char_in_rel = hyp_rel.rfind(')') - 1;\n    hyp_rel = hyp_rel.substr(first_char_in_rel, last_char_in_rel - first_char_in_rel + 1);\n    cout << index << '\\t'       // 1. ID \n         << wit << '\\t'         // 2. FORM\n         << \"_\" << '\\t'         // 3. LEMMA \n         << \"_\" << '\\t'         // 4. CPOSTAG \n         << pit->second << '\\t' // 5. POSTAG\n         << \"_\" << '\\t'         // 6. FEATS\n         << hyp_head << '\\t'    // 7. HEAD\n         << hyp_rel << '\\t'     // 8. DEPREL\n         << \"_\" << '\\t'         // 9. PHEAD\n         << \"_\" << endl;        // 10. PDEPREL\n  }\n  cout << endl;\n}\n\n\nint main(int argc, char** argv) {\n  cnn::Initialize(argc, argv);\n\n  cerr << \"COMMAND:\"; \n  for (unsigned i = 0; i < static_cast<unsigned>(argc); ++i) cerr << ' ' << argv[i];\n  cerr << endl;\n  unsigned status_every_i_iterations = 100;\n\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n  USE_POS = conf.count(\"use_pos_tags\");\n\n  LAYERS = conf[\"layers\"].as<unsigned>();\n  INPUT_DIM = conf[\"input_dim\"].as<unsigned>();\n  PRETRAINED_DIM = conf[\"pretrained_dim\"].as<unsigned>();\n  HIDDEN_DIM = conf[\"hidden_dim\"].as<unsigned>();\n  ACTION_DIM = conf[\"action_dim\"].as<unsigned>();\n  LSTM_INPUT_DIM = conf[\"lstm_input_dim\"].as<unsigned>();\n  POS_DIM = conf[\"pos_dim\"].as<unsigned>();\n  REL_DIM = conf[\"rel_dim\"].as<unsigned>();\n  const unsigned unk_strategy = conf[\"unk_strategy\"].as<unsigned>();\n  cerr << \"Unknown word strategy: \";\n  if (unk_strategy == 1) {\n    cerr << \"STOCHASTIC REPLACEMENT\\n\";\n  } else {\n    abort();\n  }\n  const double unk_prob = conf[\"unk_prob\"].as<double>();\n  assert(unk_prob >= 0.); assert(unk_prob <= 1.);\n  ostringstream os;\n  os << \"parser_\" << (USE_POS ? \"pos\" : \"nopos\")\n     << '_' << LAYERS\n     << '_' << INPUT_DIM\n     << '_' << HIDDEN_DIM\n     << '_' << ACTION_DIM\n     << '_' << LSTM_INPUT_DIM\n     << '_' << POS_DIM\n     << '_' << REL_DIM\n     << \"-pid\" << getpid() << \".params\";\n  int best_correct_heads = 0;\n  const string fname = os.str();\n  cerr << \"Writing parameters to file: \" << fname << endl;\n  bool softlinkCreated = false;\n  corpus.load_correct_actions(conf[\"training_data\"].as<string>());\t\n  const unsigned kUNK = corpus.get_or_add_word(cpyp::Corpus::UNK);\n  kROOT_SYMBOL = corpus.get_or_add_word(ROOT_SYMBOL);\n\n  if (conf.count(\"words\")) {\n    pretrained[kUNK] = vector<float>(PRETRAINED_DIM, 0);\n    cerr << \"Loading from \" << conf[\"words\"].as<string>() << \" with\" << PRETRAINED_DIM << \" dimensions\\n\";\n    ifstream in(conf[\"words\"].as<string>().c_str());\n    string line;\n    getline(in, line);\n    vector<float> v(PRETRAINED_DIM, 0);\n    string word;\n    while (getline(in, line)) {\n      istringstream lin(line);\n      lin >> word;\n      for (unsigned i = 0; i < PRETRAINED_DIM; ++i) lin >> v[i];\n      unsigned id = corpus.get_or_add_word(word);\n      pretrained[id] = v;\n    }\n  }\n\n  set<unsigned> training_vocab; // words available in the training corpus\n  set<unsigned> singletons;\n  {  // compute the singletons in the parser's training data\n    map<unsigned, unsigned> counts;\n    for (auto sent : corpus.sentences)\n      for (auto word : sent.second) { training_vocab.insert(word); counts[word]++; }\n    for (auto wc : counts)\n      if (wc.second == 1) singletons.insert(wc.first);\n  }\n\n  cerr << \"Number of words: \" << corpus.nwords << endl;\n  VOCAB_SIZE = corpus.nwords + 1;\n  ACTION_SIZE = corpus.nactions + 1;\n  POS_SIZE = corpus.npos + 10;  // bad way of dealing with the fact that we may see new POS tags in the test set\n  possible_actions.resize(corpus.nactions);\n  for (unsigned i = 0; i < corpus.nactions; ++i)\n    possible_actions[i] = i;\n\n  Model model;\n  ParserBuilder parser(&model, pretrained);\n  if (conf.count(\"model\")) {\n    ifstream in(conf[\"model\"].as<string>().c_str());\n    boost::archive::text_iarchive ia(in);\n    ia >> model;\n  }\n\n  // OOV words will be replaced by UNK tokens\n  corpus.load_correct_actionsDev(conf[\"dev_data\"].as<string>());\n  //TRAINING\n  if (conf.count(\"train\")) {\n    signal(SIGINT, signal_callback_handler);\n    SimpleSGDTrainer sgd(&model);\n    //MomentumSGDTrainer sgd(&model);\n    sgd.eta_decay = 0.08;\n    //sgd.eta_decay = 0.05;\n    vector<unsigned> order(corpus.nsentences);\n    for (unsigned i = 0; i < corpus.nsentences; ++i)\n      order[i] = i;\n    double tot_seen = 0;\n    status_every_i_iterations = min(status_every_i_iterations, corpus.nsentences);\n    unsigned si = corpus.nsentences;\n    cerr << \"NUMBER OF TRAINING SENTENCES: \" << corpus.nsentences << endl;\n    unsigned trs = 0;\n    double right = 0;\n    double llh = 0;\n    bool first = true;\n    int iter = -1;\n    time_t time_start = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n    //cerr << \"TRAINING STARTED AT: \" << put_time(localtime(&time_start), \"%c %Z\") << endl;\n    while(!requested_stop) {\n      ++iter;\n      for (unsigned sii = 0; sii < status_every_i_iterations; ++sii) {\n           if (si == corpus.nsentences) {\n             si = 0;\n             if (first) { first = false; } else { sgd.update_epoch(); }\n             cerr << \"**SHUFFLE\\n\";\n             random_shuffle(order.begin(), order.end());\n           }\n           tot_seen += 1;\n           const vector<unsigned>& sentence=corpus.sentences[order[si]];\n           vector<unsigned> tsentence=sentence;\n           if (unk_strategy == 1) {\n             for (auto& w : tsentence)\n               if (singletons.count(w) && cnn::rand01() < unk_prob) w = kUNK;\n           }\n\t   const vector<unsigned>& sentencePos=corpus.sentencesPos[order[si]]; \n\t   const vector<unsigned>& actions=corpus.correct_act_sent[order[si]];\n           ComputationGraph hg;\n           parser.log_prob_parser(&hg,sentence,tsentence,sentencePos,actions,corpus.actions,corpus.intToWords,&right);\n           double lp = as_scalar(hg.incremental_forward());\n           if (lp < 0) {\n             cerr << \"Log prob < 0 on sentence \" << order[si] << \": lp=\" << lp << endl;\n             assert(lp >= 0.0);\n           }\n           hg.backward();\n           sgd.update(1.0);\n           llh += lp;\n           ++si;\n           trs += actions.size();\n      }\n      sgd.status();\n      //time_t time_now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n      time_t time_now = time(NULL);\n      std::string t_n(asctime(localtime(&time_now)));\n      cerr << \"update #\" << iter << \" (epoch \" << (tot_seen / corpus.nsentences) << \" |time=\" << t_n.substr(0, t_n.size() - 1) << \")\\tllh: \"<< llh<<\" ppl: \" << exp(llh / trs) << \" err: \" << (trs - right) / trs << endl;\n      llh = trs = right = 0;\n\n      static int logc = 0;\n      ++logc;\n      if (logc % 25 == 1) { // report on dev set\n        unsigned dev_size = corpus.nsentencesDev;\n        // dev_size = 100;\n        double llh = 0;\n        double trs = 0;\n        double right = 0;\n        double correct_heads = 0;\n        double total_heads = 0;\n        auto t_start = std::chrono::high_resolution_clock::now();\n        for (unsigned sii = 0; sii < dev_size; ++sii) {\n           const vector<unsigned>& sentence=corpus.sentencesDev[sii];\n\t   const vector<unsigned>& sentencePos=corpus.sentencesPosDev[sii]; \n\t   const vector<unsigned>& actions=corpus.correct_act_sentDev[sii];\n           vector<unsigned> tsentence=sentence;\n           for (auto& w : tsentence)\n             if (training_vocab.count(w) == 0) w = kUNK;\n\n           ComputationGraph hg;\n\t   vector<unsigned> pred = parser.log_prob_parser(&hg,sentence,tsentence,sentencePos,vector<unsigned>(),corpus.actions,corpus.intToWords,&right);\n\t   double lp = 0;\n           llh -= lp;\n           trs += actions.size();\n           map<int,int> ref = parser.compute_heads(sentence.size(), actions, corpus.actions);\n           map<int,int> hyp = parser.compute_heads(sentence.size(), pred, corpus.actions);\n           //output_conll(sentence, corpus.intToWords, ref, hyp);\n           correct_heads += compute_correct(ref, hyp, sentence.size() - 1);\n           total_heads += sentence.size() - 1;\n        }\n        auto t_end = std::chrono::high_resolution_clock::now();\n        cerr << \"  **dev (iter=\" << iter << \" epoch=\" << (tot_seen / corpus.nsentences) << \")\\tllh=\" << llh << \" ppl: \" << exp(llh / trs) << \" err: \" << (trs - right) / trs << \" uas: \" << (correct_heads / total_heads) << \"\\t[\" << dev_size << \" sents in \" << std::chrono::duration<double, std::milli>(t_end-t_start).count() << \" ms]\" << endl;\n        if (correct_heads > best_correct_heads) {\n\t  cerr << \"saving current best model\" << endl;\n          best_correct_heads = correct_heads;\n          ofstream out(fname);\n          boost::archive::text_oarchive oa(out);\n          oa << model;\n          // Create a soft link to the most recent model in order to make it\n          // easier to refer to it in a shell script.\n          if (!softlinkCreated) {\n            string softlink = \" latest_model\";\n            if (system((string(\"rm -f \") + softlink).c_str()) == 0 && \n                system((string(\"ln -s \") + fname + softlink).c_str()) == 0) {\n              cerr << \"Created \" << softlink << \" as a soft link to \" << fname \n                   << \" for convenience.\" << endl;\n            }\n            softlinkCreated = true;\n          }\n        }\n      }\n    }\n  } // should do training?\n  if (true) { // do test evaluation\n    double llh = 0;\n    double trs = 0;\n    double right = 0;\n    double correct_heads = 0;\n    double total_heads = 0;\n    auto t_start = std::chrono::high_resolution_clock::now();\n    unsigned corpus_size = corpus.nsentencesDev;\n    for (unsigned sii = 0; sii < corpus_size; ++sii) {\n      const vector<unsigned>& sentence=corpus.sentencesDev[sii];\n      const vector<unsigned>& sentencePos=corpus.sentencesPosDev[sii]; \n      const vector<string>& sentenceUnkStr=corpus.sentencesStrDev[sii]; \n      const vector<unsigned>& actions=corpus.correct_act_sentDev[sii];\n      vector<unsigned> tsentence=sentence;\n      for (auto& w : tsentence)\n        if (training_vocab.count(w) == 0) w = kUNK;\n      ComputationGraph cg;\n      double lp = 0;\n      vector<unsigned> pred;\n      pred = parser.log_prob_parser(&cg,sentence,tsentence,sentencePos,vector<unsigned>(),corpus.actions,corpus.intToWords,&right);\n      llh -= lp;\n      trs += actions.size();\n      map<int, string> rel_ref, rel_hyp;\n      map<int,int> ref = parser.compute_heads(sentence.size(), actions, corpus.actions, &rel_ref);\n      map<int,int> hyp = parser.compute_heads(sentence.size(), pred, corpus.actions, &rel_hyp);\n      output_conll(sentence, sentencePos, sentenceUnkStr, corpus.intToWords, corpus.intToPos, hyp, rel_hyp);\n      correct_heads += compute_correct(ref, hyp, sentence.size() - 1);\n      total_heads += sentence.size() - 1;\n    }\n    auto t_end = std::chrono::high_resolution_clock::now();\n    cerr << \"TEST llh=\" << llh << \" ppl: \" << exp(llh / trs) << \" err: \" << (trs - right) / trs << \" uas: \" << (correct_heads / total_heads) << \"\\t[\" << corpus_size << \" sents in \" << std::chrono::duration<double, std::milli>(t_end-t_start).count() << \" ms]\" << endl;\n  }\n  for (unsigned i = 0; i < corpus.actions.size(); ++i) {\n    //cerr << corpus.actions[i] << '\\t' << parser.p_r->values[i].transpose() << endl;\n    //cerr << corpus.actions[i] << '\\t' << parser.p_p2a->values.col(i).transpose() << endl;\n  }\n}\n", "meta": {"hexsha": "0f774b63c5dc2d829bea2a1ff8ddb4cf8ea3df06", "size": 29843, "ext": "cc", "lang": "C++", "max_stars_repo_path": "parser/lstm-parse.cc", "max_stars_repo_name": "lstmparser/lstm-parser", "max_stars_repo_head_hexsha": "e95b6d314341a4e54dbf8f02315124ecfd28348f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parser/lstm-parse.cc", "max_issues_repo_name": "lstmparser/lstm-parser", "max_issues_repo_head_hexsha": "e95b6d314341a4e54dbf8f02315124ecfd28348f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parser/lstm-parse.cc", "max_forks_repo_name": "lstmparser/lstm-parser", "max_forks_repo_head_hexsha": "e95b6d314341a4e54dbf8f02315124ecfd28348f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.1060606061, "max_line_length": 341, "alphanum_fraction": 0.6207485843, "num_tokens": 7930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22630079924588875}}
{"text": "\n// #pragma GCC optimize (\"O0\")\n\n\n#include <math.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <iostream>\n\n#include <boost/log/trivial.hpp>\n#include <boost/algorithm/string.hpp>\n\n#include \"navigation.hpp\"\n#include \"constants.hpp\"\n#include \"antenna.hpp\"\n#include \"common.hpp\"\n#include \"enums.h\"\n\n#include \"eigenIncluder.hpp\"\n\n\n/* decode antenna field */\nint decodef(char *p, int n, double *v)\n{\n\tint i;\n\tfor (i = 0; i < n; i++)\n\t\tv[i] = 0;\n\n\tfor (i = 0, p = strtok(p,\" \"); p && i < n; p = strtok(nullptr, \" \"))\n\t{\n\t\tv[i] = atof(p) * 1E-3;\n\t\ti++;\n\t}\n\treturn i;\n}\n\nbool findAntenna(\n\tstring\t\t\t\tcode,\n\tGTime\t\t\t\ttime,\n\tnav_t&\t\t\t\tnav,\n\tE_FType\t\t\t\tft,\n\tPhaseCenterData**\tpcd_ptr_ptr)\n{\n// \tBOOST_LOG_TRIVIAL(debug)\n// \t<< \"Searching for \" << type << \", \" << code;\n\n\tauto it1 = nav.pcvMap.find(code);\n\tif (it1 == nav.pcvMap.end())\n\t{\n\t\treturn false;\n\t}\n\t\n\tauto& [dummyCode, pcvFreqMap] = *it1;\n\t\n\tauto it2 = pcvFreqMap.find(ft);\n\tif (it2 == pcvFreqMap.end())\n\t{\n\t\treturn false;\n\t}\n\t\n\tauto& [dummy2, pcvTimeMap] = *it2;\n\t\n\tauto it3 = pcvTimeMap.lower_bound(time);\n\tif (it3 == pcvTimeMap.end())\n\t{\n\t\t//just use the first chronologically, (last when sorted as they are) instead\n\t\tauto it4 = pcvTimeMap.rbegin();\n\t\t\n\t\tauto& [dummyTime, pcd] = *it4;\n\t\t\n\t\tif (pcd_ptr_ptr)\n\t\t\t*pcd_ptr_ptr = &pcd;\n\t\t\n\t\treturn true;\n\t}\n\t\n\tauto& [dummyTime, pcd] = *it3;\n\t\t\n\tif (pcd_ptr_ptr)\n\t\t*pcd_ptr_ptr = &pcd;\n\t\n\treturn true;\n}\n\t\n/* linear interpolate pcv ------------------------------------------------------\n*\n* args     :       double x1              I       x1 lower bound (degree)\n*                  double x2              I       x2 upper bound (degree)\n*                  double y1              I       y1 lower bound (m)\n*                  double y2              I       y2 upper bound (m)\n*                  double x               O       x current point (degree)\n*\n* return   :       interpolated pcv (m)\n*----------------------------------------------------------------------------*/\ndouble interp(double x1, double x2, double y1, double y2, double x)\n{\n#if (0)\n\treturn (y2-y1)*(x-x1)/(x2-x1)+y1;\n#endif\n\treturn y2-(y2-y1)*(x2-x)/(x2-x1);\n}\n\nVector3d makeAntPco(\n\tstring\t\tid,\n\tE_FType\t\tft,\n\tGTime\t\ttime)\n{\n\tif (ft == F1)\t\treturn Vector3d::Zero();\n\tif (ft == F2)\t\treturn Vector3d::Zero();\n\t\n\tVector3d pco1 = antPco(id, F1, time);\n\tVector3d pco2 = antPco(id, F2, time);\n\t\n\tif (pco1.isZero())\treturn Vector3d::Zero();\n\tif (pco2.isZero())\treturn Vector3d::Zero();\n\t\n\tdouble lam1 = lam_carr[F1];\n\tdouble lam2 = lam_carr[F2];\n\tdouble lamX = lam_carr[ft];\n\t\n\tif (lamX == 0)\t\treturn Vector3d::Zero();\n\t\n\tdouble k32 = (lamX-lam2)/(lam1-lam2);\n\tdouble k31 = (lamX-lam1)/(lam1-lam2);\n\t\n\tVector3d pco\t= k32 * pco1\n\t\t\t\t\t- k31 * pco2;\n\t\t\t\t\t\n\treturn pco;\n}\n\t\n/** fetch pco\n */\nVector3d antPco(\n\tstring\t\tid,\n\tE_FType\t\tft,\n\tGTime\t\ttime,\n\tbool\t\tinterp)\n{\n\tauto it1 = nav.pcoMap.find(id);\n\tif (it1 == nav.pcoMap.end())\n\t{\n\t\treturn Vector3d::Zero();\n\t}\n\t\n\tauto& [dummy1, pcoFreqMap] = *it1;\n\t\n\tauto it2 = pcoFreqMap.find(ft);\n\tif (it2 == pcoFreqMap.end())\n\t{\n\t\tif (interp)\t\treturn makeAntPco(id, ft, time);\n\t\telse\t\t\treturn Vector3d::Zero();\n\t}\n\t\n\tauto& [dummy2, pcoTimeMap] = *it2;\n\t\n\tauto it3 = pcoTimeMap.lower_bound(time);\n\tif (it3 == pcoTimeMap.end())\n\t{\n\t\treturn Vector3d::Zero();\n\t}\n\t\n\tauto& [dummy3, pco] = *it3;\n\t\n\treturn pco;\n}\n\n/** find and interpolate antenna pcv\n*/\ndouble antPcv(\n\tstring\t\tid,\t\t///< antenna id\n\tE_FType\t\tft,\t\t///< frequency\n\tGTime\t\ttime,\t///< time\n\tdouble\t\taCos,\t///< angle between target and antenna axis (radians)\n\tdouble\t\tazi)\t///< azimuth angle (radians)\n{\n\tauto it1 = nav.pcvMap.find(id);\n\tif (it1 == nav.pcvMap.end())\n\t{\n\t\treturn 0;\n\t}\n\t\n\tauto& [dummy1, pcvFreqMap] = *it1;\n\n\tauto it2 = pcvFreqMap.find(ft);\n\tif (it2 == pcvFreqMap.end())\n\t{\n\t\treturn 0;\n\t}\n\t\n\tauto& [dummy2, pcvTimeMap] = *it2;\n\t\n\tauto it3 = pcvTimeMap.lower_bound(time);\n\tif (it3 == pcvTimeMap.end())\n\t{\n\t\treturn 0;\n\t}\n\t\n\tauto& [dummy3, pcd] = *it3;\n\t\n\tauto& pcvMap1D = pcd.PCVMap1D;\n\tauto& pcvMap2D = pcd.PCVMap2D;\n\n\tint\t\tnz\t\t= pcd.nz;\n\tint\t\tnaz\t\t= pcd.naz;\n\tdouble\tzen1\t= pcd.zenStart;\n\tdouble\tdzen\t= pcd.zenDelta;\n\tdouble\tdazi\t= pcd.aziDelta;\n\tdouble\tzen\t\t= aCos * R2D;\n\tazi *= R2D;\n\t\n\tdouble\tpcv;\n\t\n\t/* select zenith angle range */\n\tint zen_n;\n\tfor (zen_n = 1; zen_n < nz; zen_n++)\n\t{\n\t\tif ((zen1 + dzen * zen_n) >= zen)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tdouble xz1 = zen1 + dzen * (zen_n - 1);\n\tdouble xz2 = zen1 + dzen * (zen_n);\n\n\tif\t( naz == 0\n\t\t||azi == 0)\n\t{\n\t\t/* linear interpolate receiver pcv - non azimuth-dependent */\n\t\t/* interpolate */\n\n\t\tdouble\tyz1 = pcvMap1D[zen_n - 1];\t\t// lower bound\n\t\tdouble\tyz2 = pcvMap1D[zen_n];\t\t\t// upper bound\n\t\tpcv = interp(xz1, xz2, yz1, yz2, zen);\n\t}\n\telse\n\t{\n\t\t/* bilinear interpolate receiver pcv - azimuth-dependent */\n\t\t/* select azimuth angle range */\n\t\tint az_n;\n\t\tfor (az_n = 1; az_n < naz; az_n++)\n\t\t{\n\t\t\tif ((dazi * az_n) >= azi)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tdouble xa1 = dazi * (az_n -1);\n\t\tdouble xa2 = dazi * (az_n);\n\n\t\tdouble yz3 = pcvMap2D[az_n-1]\t[zen_n-1];\t\tdouble yz1 = pcvMap2D[az_n-1]\t[zen_n];\n\t\tdouble yz4 = pcvMap2D[az_n]\t\t[zen_n-1];\t\tdouble yz2 = pcvMap2D[az_n]\t\t[zen_n];\n\n\t\t/* linear interpolation along zenith angle */\n\t\tdouble ya1\t= interp(xz1, xz2, yz3, yz1, zen);\n\t\tdouble ya2 \t= interp(xz1, xz2, yz4, yz2, zen);\n\n\t\t/* linear interpolation along azimuth angle */\n\t\tpcv\t= interp(xa1, xa2, ya1, ya2, azi);\n\t}\n\n\treturn pcv;\n}\n\n//=============================================================================\n// radomeNoneAntennaType = radome2none(antennaType)\n//\n//       e,g, \"AOAD/M_T        JPLA\" => \"AOAD/M_T        NONE\"\n//\n// Change the last four characters of antenna type to NONE\n// This function is useful for when searching for an antenna model in ANTEX\n//\n// The IGS convention is to default to NONE for the radome if the calibration\n// value is not available\n//=============================================================================\n//void radome2none(char *restrict antenna_type)\nvoid radome2none(string& antenna_type)\n{\n\tsize_t length = antenna_type.size();\n\tif (length != 20)\n\t{\n\t\tprintf(\"\\n*** ERROR radome2none(): string length is less then 20 characters received %ld characters\\n\",length);\n\t\treturn;\n\t}\n\tantenna_type.replace(length - 4, 4, \"NONE\");\n}\n\nmap<string, E_FType> antexCodes =\n{\n\t{\"G01\", L1    },\n\t{\"G02\", L2    },\n\t{\"G05\", L5    },\n\t{\"R01\", G1    },\n\t{\"R02\", G2    },\n\t{\"E01\", E1    },\n\t{\"E05\", E5A   },\n\t{\"E07\", E5B   },\n\t{\"E08\", E5AB  },\n\t{\"E06\", E6    },\n\t{\"C01\", E1    },\n\t{\"C02\", E2    },\n\t{\"C07\", E5B   },\n\t{\"C06\", E6    },\n\t{\"J01\", L1    },\n\t{\"J02\", L2    },\n\t{\"J05\", L5    },\n\t{\"J06\", LEX   },\n\t{\"S01\", L1    },\n\t{\"S05\", L5    }\n};\n\n/** Read antex file */\nint readantexf(\n\tstring\tfile,\n\tnav_t&\tnav)\n{\n\tint offset;\n\tint noazi_flag\t\t= 0;\n\tint num_azi_rd\t\t= 0;\n\tint new_antenna\t\t= 0;\n\tint irms\t\t\t= 0;\n\n\tchar tmp[10];\n\tchar *p;\n\n\tFILE* fp = fopen(file.c_str(),\"r\");\n\tif (fp == nullptr)\n\t{\n\t\tBOOST_LOG_TRIVIAL(warning)\n\t\t<< \"Warning: ANTEX file opening error\";\n\n\t\treturn 0;\n\t}\n\n\tconst PhaseCenterData pcv0 = {};\n\tPhaseCenterData recPcv;\n\tPhaseCenterData freqPcv;\n\tVector3d\tpco = Vector3d::Zero();\n\tstring\t\tid;\n\tGTime\t\ttime;\n\t\n\tE_FType\tft = FTYPE_NONE;\n\n\tchar buff[512];\n\twhile (fgets(buff, sizeof(buff), fp))\n\t{\n\t\tchar* comment = buff + 60;\n\n\t\tif (irms) \n\t\t\tcontinue;\n\t\t\n\t\t/* Read in the ANTEX header information */\n\t\t\n\t\tif (strlen(buff) < 60 )\t\t\t\t\t\t\t\t{\tcontinue;\t}\n\t\tif (strstr(comment, \"ANTEX VERSION / SYST\"))\t\t{\tcontinue;\t}\n\t\tif (strstr(comment, \"PCV TYPE / REFANT\")) \t\t\t{\tcontinue;\t}\n\t\tif (strstr(comment, \"COMMENT\")) \t\t\t\t\t{\tcontinue;\t}\n\t\tif (strstr(comment, \"END OF HEADER\"))\t\t\t\t{\tcontinue;\t}\n\t\t\n\t\t/* Read in specific Antenna information now */\n\t\t\n\t\tif (strstr(comment, \"START OF ANTENNA\"))\n\t\t{\n\t\t\trecPcv\t= pcv0;\n\t\t\tfreqPcv\t= pcv0;\n\t\t\tpco\t\t= Vector3d::Zero();\n\t\t\tid\t\t= \"\";\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n// \t\tif (strstr(comment, \"END OF ANTENNA\"))\n// \t\t{\n// \t\t\tGTime time = epoch2time(recPcv.tf);\n// \t\t\t\n// \t\t\tcontinue;\n// \t\t}\n\t\t\n\n\t\tif (strstr(comment, \"METH / BY / # / DATE\"))\n\t\t{\n// \t\t\tint num_calibrated;\n// \t\t\tchar cal_method[20];\n// \t\t\tchar cal_agency[20];\n// \t\t\tchar cal_date[10];\n// \t\t\tstrncpy(cal_method,\tbuff,\t\t20);/* Should be CHAMBER or FIELD or ROBOT or COPIED ot CONVERTED */\n// \t\t\tcal_method[19] = '\\0';\n// \t\t\tstrncpy(cal_agency, buff + 20,\t20);\n// \t\t\tcal_agency[19] = '\\0';\n// \t\t\tstrncpy(tmp,\t\tbuff + 40,\t10);\n// \t\t\tnum_calibrated = atoi(tmp);\n// \t\t\tstrncpy(cal_date,\tbuff + 50,\t10);\n// \t\t\tcal_date[9] = '\\0';\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"DAZI\"))\n\t\t{\n\t\t\tstrncpy(tmp,buff   ,8);\t\ttmp[8] = '\\0';\n\t\t\trecPcv.aziDelta = atof(tmp);\n\n\t\t\tif (recPcv.aziDelta < 0.0001)\trecPcv.naz = 0;\n\t\t\telse\t\t\t\t\t\t\trecPcv.naz = (360 / recPcv.aziDelta) + 1;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"SINEX CODE\"))\n\t\t{\n\t\t\trecPcv.calibModel\t.assign(buff,\t\t10);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"TYPE / SERIAL NO\"))\n\t\t{\n\t\t\trecPcv.type\t\t\t.assign(buff,\t\t20);\n\t\t\trecPcv.code\t\t\t.assign(buff+20,\t20);\n\t\t\trecPcv.svn\t\t\t.assign(buff+40,\t4);\n\t\t\trecPcv.cospar\t\t.assign(buff+50,\t10);\n\t\t\t\n\t\t\t/* stack antenna pco and pcv */\n\t\t\tstring satId = recPcv.code;\n\t\t\tif (satId.find_first_not_of(' ') == satId.npos)\t\t{ id = recPcv.type;\t}\n\t\t\telse\t\t\t\t\t\t\t\t\t\t\t\t{ id = recPcv.code;\t}\n\t\t\n\t\t\tboost::trim_right(id);\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"ZEN1 / ZEN2 / DZEN\"))\n\t\t{\n\t\t\tstrncpy(tmp, buff,\t\t8);\ttmp[8] = '\\0'; \trecPcv.zenStart\t= atof(tmp);\n\t\t\tstrncpy(tmp, buff+8,\t7);\ttmp[8] = '\\0'; \trecPcv.zenStop\t= atof(tmp);\n\t\t\tstrncpy(tmp, buff+16,\t7);\ttmp[8] = '\\0'; \trecPcv.zenDelta\t= atof(tmp);\n\n\t\t\trecPcv.nz = (recPcv.zenStop - recPcv.zenStart) / recPcv.zenDelta + 1 ;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"# OF FREQUENCIES\"))\n\t\t{\n//\t\t\tstrncpy(tmp, buff,\t\t8);\n// \t\t\ttmp[8] = '\\0'; \t\n// \t\t\tpcv.nf\t\t= atoi(tmp);\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"VALID FROM\"))\n\t\t{\n\t\t\tchar valid_from[44];\n\t\t\t/* if (!str2time(buff,0,43,pcv.ts)) continue;*/\n\t\t\tstrncpy(valid_from, buff, 43);\n\t\t\tvalid_from[43] = '\\0';\n\t\t\tp = strtok(valid_from, \" \");\n\t\t\tint j = 0;\n\t\t\twhile (p != nullptr)\n\t\t\t{\n\t\t\t\trecPcv.tf[j] = (double) atoi(p);\n\t\t\t\tp = strtok(nullptr, \" \");\n\t\t\t\tj++;\n\t\t\t}\n\t\t\t\n\t\t\ttime = epoch2time(recPcv.tf);\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"VALID UNTIL\"))\n\t\t{\n\t\t\tchar valid_until[44];\n\t\t\t/* if (!str2time(buff,0,43,pcv.te)) continue;*/\n\t\t\tstrncpy(valid_until, buff   ,43);\n\t\t\tvalid_until[43] = '\\0';\n\t\t\tp = strtok(valid_until, \" \");\n\t\t\tint j = 0;\n\t\t\twhile (p != nullptr)\n\t\t\t{\n\t\t\t\trecPcv.tu[j] = (double) atoi(p);\n\t\t\t\tp = strtok(nullptr, \" \");\n\t\t\t\tj++;\n\t\t\t}\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"NORTH / EAST / UP\"))\n\t\t{\n\t\t\tdouble neu[3];\n\t\t\tif (decodef(buff, 3, neu) < 3)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t/* assign pco value in ENU */\n\t\t\tVector3d enu;\n\t\t\tenu[0] = neu[1];\n\t\t\tenu[1] = neu[0];\n\t\t\tenu[2] = neu[2];\n\t\t\t\n\t\t\tpco = enu;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"START OF FREQUENCY\"))\n\t\t{\n\t\t\tnum_azi_rd = 0;\n\t\t\tnoazi_flag = 0;\n\n\t\t\tstring antexFCode;\n\t\t\tantexFCode.assign(&buff[3], 3);\n\n\t\t\tft = antexCodes[antexFCode];\n\t\t\t\n\t\t\tfreqPcv = recPcv;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"END OF FREQUENCY\"))\n\t\t{\t\n\t\t\tnoazi_flag\t= 0;\t\n\t\t\t\n\t\t\tnav.pcvMap[id][ft][time] = freqPcv;\n\t\t\tnav.pcoMap[id][ft][time] = pco;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif (strstr(comment, \"START OF FREQ RMS\"))\t{\tirms\t\t= 1;\tcontinue;\t}\n\t\tif (strstr(comment, \"END OF FREQ RMS\"))\t\t{\tirms\t\t= 0;\tcontinue;\t}\n\t\t\n\t\tif\t(  irms == 0 \n\t\t\t&& strstr(buff, \"NOAZI\"))\n\t\t{\n\t\t\tfor (int i = 0; i < recPcv.nz; i++)\n\t\t\t{\n\t\t\t\toffset = i * 8 + 8;\n\t\t\t\tstrncpy(tmp, buff + offset, 8);\n\t\t\t\ttmp[8]='\\0';\n\t\t\t\tdouble pcv_val = atof(tmp);\n\t\t\t\tfreqPcv.PCVMap1D\t\t\t.push_back(pcv_val * 1e-3);\n\t\t\t}\n\t\t\tnoazi_flag = 1;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tif\t(  irms == 0\n\t\t\t&& noazi_flag == 1)\n\t\t{\n\t\t\tstrncpy(tmp, buff, 8);\n\t\t\ttmp[8]='\\0';\n\n\t\t\tfor (int i = 0; i < recPcv.nz; i++)\n\t\t\t{\n\t\t\t\toffset = i * 8 + 8;\n\t\t\t\tstrncpy(tmp, buff + offset, 8);\n\t\t\t\ttmp[8]='\\0';\n\t\t\t\tdouble pcv_val = atof(tmp);\n\t\t\t\tfreqPcv.PCVMap2D[num_azi_rd].push_back(pcv_val * 1e-3);\n\t\t\t}\n\t\t\tnum_azi_rd++;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\tfclose(fp);\n\n\treturn 1;\n}\n", "meta": {"hexsha": "ad91394ce2591b1a768ec77eca6a0d7636a5804e", "size": 11977, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/common/antenna.cpp", "max_stars_repo_name": "HiTMonitor/ginan", "max_stars_repo_head_hexsha": "f348e2683507cfeca65bb58880b3abc2f9c36bcf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/common/antenna.cpp", "max_issues_repo_name": "HiTMonitor/ginan", "max_issues_repo_head_hexsha": "f348e2683507cfeca65bb58880b3abc2f9c36bcf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/common/antenna.cpp", "max_forks_repo_name": "HiTMonitor/ginan", "max_forks_repo_head_hexsha": "f348e2683507cfeca65bb58880b3abc2f9c36bcf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6856649396, "max_line_length": 113, "alphanum_fraction": 0.5563162729, "num_tokens": 4279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22630079924588875}}
{"text": "/*===========================================================================\n NetEvo Library\n Copyright (C) 2011 Thomas E. Gorochowski <tgorochowski@me.com>\n Bristol Centre for Complexity Sciences, University of Bristol, Bristol, UK\n ---------------------------------------------------------------------------- \n NetEvo is a computing framework designed to allow researchers to investigate \n evolutionary aspects of dynamical complex networks. By providing tools to \n easily integrate each of these factors in a coherent way, it is hoped a \n greater understanding can be gained of key attributes and features displayed \n by complex systems.\n \n NetEvo is open-source software released under the Open Source Initiative \n (OSI) approved Non-Profit Open Software License (\"Non-Profit OSL\") 3.0. \n Detailed information about this licence can be found in the COPYING file \n included as part of the source distribution.\n \n This library is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n ============================================================================*/\n\n#include \"simulate.h\"\n#include <boost/numeric/odeint.hpp>\n#include <boost/numeric/odeint/stepper/adams_bashforth_moulton.hpp>\n\nusing namespace boost::numeric::odeint;\n\nnamespace netevo {\n\n   void SimulateMap::simulate (System &sys, double tMax, State &initial, SimObserver &obs, ChangeLog &logger) {\n      \n      // We are in discrete time so use integers for time\n      int t = 0, tEnd = (int)tMax;\n      int states = (countNodes(sys)*sys.nodeStates()) + (countArcs(sys)*sys.arcStates());\n\n      // Check to ensure that initial conditions are correct size\n      if (initial.size() < states || initial.size() > states) {\n         cerr << \"Incorrect number of states for initial conditions (SimulateMap::simulate)\" << endl;\n         return;\n      }\n\n      // Vector to hold the output. Copy the initial conditions and add to the output\n      State y1 = State(initial);\n      State y2 = State(initial);\n\n      // Check that the state IDs are correct, if not refresh\n      if (!sys.validStateIDs()) { sys.refreshStateIDs(); }\n\n      // Send the observer the initial conditions\n      logger.newState (sys, y1);\n      logger.endStep(SIM_STEP);\n      logger.commit();\n      obs(y1, 0.0);\n      \n      // Loop through all time steps and calculate new states\n      for (t = 1; t <= tEnd; t++) {\n         if (t%2 == 0) {\n            // Use y1 as old and y2 as new\n            // Simulate the dynamics\n            sys(y1, y2, (double)t);\n            // Log the state change\n            logger.newState (sys, y2);\n            logger.endStep(SIM_STEP);\n            logger.commit();\n            // Send result to the observer\n            obs(y2, (double)t);\n         }\n         else {\n            // Use y2 as old and y1 as new\n            // Simulate the dynamics\n            sys(y2, y1, (double)t);\n            // Log the state change\n            logger.newState (sys, y1);\n            logger.endStep(SIM_STEP);\n            logger.commit();\n            // Send result to the observer\n            obs(y1, (double)t);\n         }\n      }\n      \n      // Ensure the initial vector is updated to the final result\n      initial = ( t%2 == 0 )  ? y1 : y2;\n   }\n\n   void SimulateOdeFixed::simulate (System &sys, double tMax, State &initial, SimObserver &obs, ChangeLog &logger) {\n      \n      // Check to ensure that initial conditions are correct size\n      int states = (countNodes(sys)*sys.nodeStates()) + (countArcs(sys)*sys.arcStates());\n      if (initial.size() < states || initial.size() > states) {\n         cerr << \"Incorrect number of states for initial conditions (SimulateOdeFixed::simulate)\" << endl;\n         return;\n      }\t \n\n      // Check that the state IDs are correct, if not refresh\n      if (!sys.validStateIDs()) { sys.refreshStateIDs(); }\n\n      // Create the required steppers\n      typedef runge_kutta4<State> rk4_stepper_type;\n      typedef adams_bashforth_moulton<5,State> adams_bash_moul_stepper_type;\n      \n      // Solve the system\n      switch (mStepper) {\n         case RK_4:\n            integrate_const(rk4_stepper_type(),\n                                    Simulator(&sys), initial, 0.0, tMax, mStepSize, ObserverPassThrough(sys, obs, logger));\n            break;\n         case ADAM_BASH_MOUL:\n            integrate_const(adams_bash_moul_stepper_type(), \n                                    Simulator(&sys), initial, 0.0, tMax, mStepSize, ObserverPassThrough(sys, obs, logger));\n            break;\n         default:\n            // Do nothing\n            break;\n      }\n   }\n\n\n   void SimulateOdeConst::simulate (System &sys, double tMax, State &initial, SimObserver &obs, ChangeLog &logger) {\n      \n      // Check to ensure that initial conditions are correct size\n      int states = (countNodes(sys)*sys.nodeStates()) + (countArcs(sys)*sys.arcStates());\n      if (initial.size() < states || initial.size() > states) {\n         cerr << \"Incorrect number of states for initial conditions (SimulateOdeConst::simulate)\" << endl;\n         return;\n      }\t\n\n      // Check that the state IDs are correct, if not refresh\n      if (!sys.validStateIDs()) { sys.refreshStateIDs(); }\n      \n      // Create the required steppers\n      typedef runge_kutta_cash_karp54<State> rkck54_error_stepper_type;\n      typedef runge_kutta_dopri5<State> dopri5_error_stepper_type;      \n      \n      // Solve the system\n      switch (mStepper) {\n         case RK_CASH_KARP_54:\n            integrate_const(make_controlled( mEpsAbs , mEpsRel , rkck54_error_stepper_type() ), \n                                    Simulator(&sys), initial, 0.0, tMax, mOutputStep, ObserverPassThrough(sys, obs, logger));\n            break;\n         case RK_DOPRI_5:\n            integrate_const(make_controlled( mEpsAbs , mEpsRel , dopri5_error_stepper_type() ), \n                                    Simulator(&sys), initial, 0.0, tMax, mOutputStep, ObserverPassThrough(sys, obs, logger));\n            break;\n         case RK_DOPRI_5_DENSE:\n            integrate_const(make_dense_output( mEpsAbs , mEpsRel , dopri5_error_stepper_type() ),\n                                    Simulator(&sys), initial, 0.0, tMax, mOutputStep, ObserverPassThrough(sys, obs, logger));\n            break;\n         default:\n            // Do nothing\n            break;\n      }\n   }\n\n   void SimulateOdeAdaptive::simulate (System &sys, double tMax, State &initial, SimObserver &obs, ChangeLog &logger) {\n      \n      // Check to ensure that initial conditions are correct size\n      int states = (countNodes(sys)*sys.nodeStates()) + (countArcs(sys)*sys.arcStates());\n      if (initial.size() < states || initial.size() > states) {\n         cerr << \"Incorrect number of states for initial conditions (SimulateOdeAdaptive::simulate)\" << endl;\n         return;\n      }\t\n\n      // Check that the state IDs are correct, if not refresh\n      if (!sys.validStateIDs()) { sys.refreshStateIDs(); }\n      \n      // Create the required steppers\n      typedef runge_kutta_cash_karp54<State> rkck54_error_stepper_type;\n      typedef runge_kutta_dopri5<State> dopri5_error_stepper_type;     \n      \n      // Solve the system\n      switch (mStepper) {\n         case RK_CASH_KARP_54:\n            integrate_adaptive(make_controlled( mEpsAbs , mEpsRel , rkck54_error_stepper_type() ), \n                                       Simulator(&sys), initial, 0.0, tMax, mInitialStep, ObserverPassThrough(sys, obs, logger));\n            break;\n         case RK_DOPRI_5:\n            integrate_adaptive(make_controlled( mEpsAbs , mEpsRel , dopri5_error_stepper_type() ),\n                                       Simulator(&sys), initial, 0.0, tMax, mInitialStep, ObserverPassThrough(sys, obs, logger));\n            break;\n         case RK_DOPRI_5_DENSE:\n            integrate_adaptive(make_dense_output( mEpsAbs , mEpsRel , dopri5_error_stepper_type() ),\n                                       Simulator(&sys), initial, 0.0, tMax, mInitialStep, ObserverPassThrough(sys, obs, logger));\n            break;\n         default:\n            // Do nothing\n            break;\n      }\n   }\n\n} // netevo namespace\n", "meta": {"hexsha": "9d5e3694e11556fc97c3f77b79f14380b93ae78d", "size": 8203, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lib/netevo/simulate.cc", "max_stars_repo_name": "chofski/dynamic_nets", "max_stars_repo_head_hexsha": "5de19e200cffbb432fa4a1f81af15cc614961bde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-06T08:06:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-06T08:06:16.000Z", "max_issues_repo_path": "lib/netevo/simulate.cc", "max_issues_repo_name": "chofski/dynamic_nets", "max_issues_repo_head_hexsha": "5de19e200cffbb432fa4a1f81af15cc614961bde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/netevo/simulate.cc", "max_forks_repo_name": "chofski/dynamic_nets", "max_forks_repo_head_hexsha": "5de19e200cffbb432fa4a1f81af15cc614961bde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9476439791, "max_line_length": 129, "alphanum_fraction": 0.6003901012, "num_tokens": 1922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.22624518377989256}}
{"text": "/* Copyright (c) 2021, United States Government, as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n *\n * All rights reserved.\n *\n * The \"ISAAC - Integrated System for Autonomous and Adaptive Caretaking\n * platform\" software is licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with the\n * License. You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations\n * under the License.\n */\n\n#include <opencv2/xfeatures2d.hpp>\n#include <opencv2/highgui.hpp>\n#include <opencv2/calib3d/calib3d.hpp>\n\n#include <interest_point.h>           // from the isaac repo\n#include <camera_image.h>             // from the isaac repo\n#include <interest_point/matching.h>  // from the astrobee repo\n\n// Get rid of warnings beyond our control\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n#pragma GCC diagnostic push\n#include <openMVG/multiview/projection.hpp>\n#include <openMVG/multiview/rotation_averaging_l1.hpp>\n#include <openMVG/multiview/triangulation_nview.hpp>\n#include <openMVG/numeric/numeric.h>\n#include <openMVG/tracks/tracks.hpp>\n#pragma GCC diagnostic pop\n\n#include <boost/filesystem.hpp>\n\n#include <iostream>\n#include <fstream>\n\n// SIFT is doing so much better than SURF for haz cam images.\nDEFINE_string(refiner_feature_detector, \"SIFT\", \"The feature detector to use. SIFT or SURF.\");\nDEFINE_int32(sift_nFeatures, 10000, \"Number of SIFT features\");\nDEFINE_int32(sift_nOctaveLayers, 3, \"Number of SIFT octave layers\");\nDEFINE_double(sift_contrastThreshold, 0.02,\n              \"SIFT contrast threshold\");  // decrease for more ip\nDEFINE_double(sift_edgeThreshold, 10, \"SIFT edge threshold\");\nDEFINE_double(sift_sigma, 1.6, \"SIFT sigma\");\n\nnamespace dense_map {\n\nvoid detectFeatures(const cv::Mat& image, bool verbose,\n                    // Outputs\n                    cv::Mat* descriptors, Eigen::Matrix2Xd* keypoints) {\n  bool histogram_equalization = false;\n\n  // If using histogram equalization, need an extra image to store it\n  cv::Mat* image_ptr = const_cast<cv::Mat*>(&image);\n  cv::Mat hist_image;\n  if (histogram_equalization) {\n    cv::equalizeHist(image, hist_image);\n    image_ptr = &hist_image;\n  }\n\n  std::vector<cv::KeyPoint> storage;\n\n  if (FLAGS_refiner_feature_detector == \"SIFT\") {\n    cv::Ptr<cv::xfeatures2d::SIFT> sift =\n      cv::xfeatures2d::SIFT::create(FLAGS_sift_nFeatures, FLAGS_sift_nOctaveLayers, FLAGS_sift_contrastThreshold,\n                                    FLAGS_sift_edgeThreshold, FLAGS_sift_sigma);\n    sift->detect(image, storage);\n    sift->compute(image, storage, *descriptors);\n\n  } else if (FLAGS_refiner_feature_detector == \"SURF\") {\n    interest_point::FeatureDetector detector(\"SURF\");\n    detector.Detect(*image_ptr, &storage, descriptors);\n\n    // Undo the shift in the detector\n    for (cv::KeyPoint& key : storage) {\n      key.pt.x += image.cols / 2.0;\n      key.pt.y += image.rows / 2.0;\n    }\n\n  } else {\n    LOG(FATAL) << \"Unknown feature detector: \" << FLAGS_refiner_feature_detector;\n  }\n\n  if (verbose) std::cout << \"Features detected \" << storage.size() << std::endl;\n\n  // Copy to data structures expected by subsequent code\n  keypoints->resize(2, storage.size());\n  Eigen::Vector2d output;\n  for (size_t j = 0; j < storage.size(); j++) {\n    keypoints->col(j) = Eigen::Vector2d(storage[j].pt.x, storage[j].pt.y);\n  }\n}\n\n// This really likes haz cam first and nav cam second\nvoid matchFeatures(std::mutex* match_mutex, int left_image_index, int right_image_index,\n                   cv::Mat const& left_descriptors, cv::Mat const& right_descriptors,\n                   Eigen::Matrix2Xd const& left_keypoints,\n                   Eigen::Matrix2Xd const& right_keypoints, bool verbose,\n                   // output\n                   MATCH_PAIR* matches) {\n  std::vector<cv::DMatch> cv_matches;\n  interest_point::FindMatches(left_descriptors, right_descriptors, &cv_matches);\n\n  std::vector<cv::Point2f> left_vec;\n  std::vector<cv::Point2f> right_vec;\n  for (size_t j = 0; j < cv_matches.size(); j++) {\n    int left_ip_index = cv_matches.at(j).queryIdx;\n    int right_ip_index = cv_matches.at(j).trainIdx;\n\n    // Get the keypoints from the good matches\n    left_vec.push_back(cv::Point2f(left_keypoints.col(left_ip_index)[0], left_keypoints.col(left_ip_index)[1]));\n    right_vec.push_back(cv::Point2f(right_keypoints.col(right_ip_index)[0], right_keypoints.col(right_ip_index)[1]));\n  }\n\n  if (left_vec.empty()) return;\n\n  // These may need some tweaking but works reasonably well.\n  double ransacReprojThreshold = 20.0;\n  cv::Mat inlier_mask;\n  int maxIters = 10000;\n  double confidence = 0.8;\n\n  // affine2D works better than homography\n  // cv::Mat H = cv::findHomography(left_vec, right_vec, cv::RANSAC,\n  // ransacReprojThreshold, inlier_mask, maxIters, confidence);\n  cv::Mat H = cv::estimateAffine2D(left_vec, right_vec, inlier_mask, cv::RANSAC,\n                                   ransacReprojThreshold, maxIters, confidence);\n\n  std::vector<InterestPoint> left_ip, right_ip;\n  for (size_t j = 0; j < cv_matches.size(); j++) {\n    int left_ip_index = cv_matches.at(j).queryIdx;\n    int right_ip_index = cv_matches.at(j).trainIdx;\n\n    if (inlier_mask.at<uchar>(j, 0) == 0) continue;\n\n    cv::Mat left_desc = left_descriptors.row(left_ip_index);\n    cv::Mat right_desc = right_descriptors.row(right_ip_index);\n\n    InterestPoint left;\n    left.setFromCvKeypoint(left_keypoints.col(left_ip_index), left_desc);\n\n    InterestPoint right;\n    right.setFromCvKeypoint(right_keypoints.col(right_ip_index), right_desc);\n\n    left_ip.push_back(left);\n    right_ip.push_back(right);\n  }\n\n  // Update the shared variable using a lock\n  match_mutex->lock();\n\n  // Print the verbose message inside the lock, otherwise the text\n  // may get messed up.\n  if (verbose)\n    std::cout << \"Number of matches for pair \"\n              << left_image_index << ' ' << right_image_index << \": \"\n              << left_ip.size() << std::endl;\n\n  *matches = std::make_pair(left_ip, right_ip);\n  match_mutex->unlock();\n}\n\n\n// Match features while assuming that the input cameras can be used to filter out\n// outliers by reprojection error.\nvoid matchFeaturesWithCams(std::mutex* match_mutex, int left_image_index, int right_image_index,\n                           camera::CameraParameters const& left_params,\n                           camera::CameraParameters const& right_params,\n                           Eigen::Affine3d const& left_world_to_cam,\n                           Eigen::Affine3d const& right_world_to_cam,\n                           double reprojection_error,\n                           cv::Mat const& left_descriptors, cv::Mat const& right_descriptors,\n                           Eigen::Matrix2Xd const& left_keypoints,\n                           Eigen::Matrix2Xd const& right_keypoints,\n                           bool verbose,\n                           // output\n                           MATCH_PAIR* matches) {\n  // Match by using descriptors first\n  std::vector<cv::DMatch> cv_matches;\n  interest_point::FindMatches(left_descriptors, right_descriptors, &cv_matches);\n\n  // Do filtering\n  std::vector<cv::Point2f> left_vec;\n  std::vector<cv::Point2f> right_vec;\n  std::vector<cv::DMatch> filtered_cv_matches;\n  for (size_t j = 0; j < cv_matches.size(); j++) {\n    int left_ip_index = cv_matches.at(j).queryIdx;\n    int right_ip_index = cv_matches.at(j).trainIdx;\n\n    Eigen::Vector2d dist_left_ip(left_keypoints.col(left_ip_index)[0],\n                                 left_keypoints.col(left_ip_index)[1]);\n\n    Eigen::Vector2d dist_right_ip(right_keypoints.col(right_ip_index)[0],\n                                  right_keypoints.col(right_ip_index)[1]);\n\n    Eigen::Vector2d undist_left_ip;\n    Eigen::Vector2d undist_right_ip;\n    left_params.Convert<camera::DISTORTED,  camera::UNDISTORTED_C>\n      (dist_left_ip, &undist_left_ip);\n    right_params.Convert<camera::DISTORTED, camera::UNDISTORTED_C>\n      (dist_right_ip, &undist_right_ip);\n\n    Eigen::Vector3d X =\n      dense_map::TriangulatePair(left_params.GetFocalLength(), right_params.GetFocalLength(),\n                                 left_world_to_cam, right_world_to_cam,\n                                 undist_left_ip, undist_right_ip);\n\n    // Project back into the cameras\n    Eigen::Vector3d left_cam_X = left_world_to_cam * X;\n    Eigen::Vector2d undist_left_pix\n      = left_params.GetFocalVector().cwiseProduct(left_cam_X.hnormalized());\n    Eigen::Vector2d dist_left_pix;\n    left_params.Convert<camera::UNDISTORTED_C, camera::DISTORTED>(undist_left_pix,\n                                                                  &dist_left_pix);\n\n    Eigen::Vector3d right_cam_X = right_world_to_cam * X;\n    Eigen::Vector2d undist_right_pix\n      = right_params.GetFocalVector().cwiseProduct(right_cam_X.hnormalized());\n    Eigen::Vector2d dist_right_pix;\n    right_params.Convert<camera::UNDISTORTED_C, camera::DISTORTED>(undist_right_pix,\n                                                                   &dist_right_pix);\n\n    // Filter out points whose reprojection error is too big\n    bool is_good = ((dist_left_ip - dist_left_pix).norm() <= reprojection_error &&\n                    (dist_right_ip - dist_right_pix).norm() <= reprojection_error);\n\n    // If any values above are Inf or NaN, is_good will be false as well\n    if (!is_good) continue;\n\n    // Get the keypoints from the good matches\n    left_vec.push_back(cv::Point2f(left_keypoints.col(left_ip_index)[0],\n                                   left_keypoints.col(left_ip_index)[1]));\n    right_vec.push_back(cv::Point2f(right_keypoints.col(right_ip_index)[0],\n                                    right_keypoints.col(right_ip_index)[1]));\n\n    filtered_cv_matches.push_back(cv_matches[j]);\n  }\n\n  if (left_vec.empty()) return;\n\n  // Filter using geometry constraints\n  // These may need some tweaking but works reasonably well.\n  double ransacReprojThreshold = 20.0;\n  cv::Mat inlier_mask;\n  int maxIters = 10000;\n  double confidence = 0.8;\n\n  // affine2D works better than homography\n  // cv::Mat H = cv::findHomography(left_vec, right_vec, cv::RANSAC,\n  // ransacReprojThreshold, inlier_mask, maxIters, confidence);\n  cv::Mat H = cv::estimateAffine2D(left_vec, right_vec, inlier_mask, cv::RANSAC,\n                                   ransacReprojThreshold, maxIters, confidence);\n\n  std::vector<InterestPoint> left_ip, right_ip;\n  for (size_t j = 0; j < filtered_cv_matches.size(); j++) {\n    int left_ip_index = filtered_cv_matches.at(j).queryIdx;\n    int right_ip_index = filtered_cv_matches.at(j).trainIdx;\n\n    if (inlier_mask.at<uchar>(j, 0) == 0) continue;\n\n    cv::Mat left_desc = left_descriptors.row(left_ip_index);\n    cv::Mat right_desc = right_descriptors.row(right_ip_index);\n\n    InterestPoint left;\n    left.setFromCvKeypoint(left_keypoints.col(left_ip_index), left_desc);\n\n    InterestPoint right;\n    right.setFromCvKeypoint(right_keypoints.col(right_ip_index), right_desc);\n\n    left_ip.push_back(left);\n    right_ip.push_back(right);\n  }\n\n  // Update the shared variable using a lock\n  match_mutex->lock();\n\n  // Print the verbose message inside the lock, otherwise the text\n  // may get messed up.\n  if (verbose)\n    std::cout << \"Number of matches for pair \"\n              << left_image_index << ' ' << right_image_index << \": \"\n              << left_ip.size() << std::endl;\n\n  *matches = std::make_pair(left_ip, right_ip);\n  match_mutex->unlock();\n}\n\nvoid writeIpRecord(std::ofstream& f, InterestPoint const& p) {\n  f.write(reinterpret_cast<const char*>(&(p.x)), sizeof(p.x));\n  f.write(reinterpret_cast<const char*>(&(p.y)), sizeof(p.y));\n  f.write(reinterpret_cast<const char*>(&(p.ix)), sizeof(p.ix));\n  f.write(reinterpret_cast<const char*>(&(p.iy)), sizeof(p.iy));\n  f.write(reinterpret_cast<const char*>(&(p.orientation)), sizeof(p.orientation));\n  f.write(reinterpret_cast<const char*>(&(p.scale)), sizeof(p.scale));\n  f.write(reinterpret_cast<const char*>(&(p.interest)), sizeof(p.interest));\n  f.write(reinterpret_cast<const char*>(&(p.polarity)), sizeof(p.polarity));\n  f.write(reinterpret_cast<const char*>(&(p.octave)), sizeof(p.octave));\n  f.write(reinterpret_cast<const char*>(&(p.scale_lvl)), sizeof(p.scale_lvl));\n  uint64_t size = p.size();\n  f.write(reinterpret_cast<const char*>((&size)), sizeof(uint64));\n  for (size_t i = 0; i < p.descriptor.size(); ++i)\n    f.write(reinterpret_cast<const char*>(&(p.descriptor[i])), sizeof(p.descriptor[i]));\n}\n\n// Write matches to disk\nvoid writeMatchFile(std::string match_file, std::vector<InterestPoint> const& ip1,\n                    std::vector<InterestPoint> const& ip2) {\n  std::ofstream f;\n  f.open(match_file.c_str(), std::ios::binary | std::ios::out);\n  std::vector<InterestPoint>::const_iterator iter1 = ip1.begin();\n  std::vector<InterestPoint>::const_iterator iter2 = ip2.begin();\n  uint64 size1 = ip1.size();\n  uint64 size2 = ip2.size();\n  f.write(reinterpret_cast<const char*>(&size1), sizeof(uint64));\n  f.write(reinterpret_cast<const char*>(&size2), sizeof(uint64));\n  for (; iter1 != ip1.end(); ++iter1) writeIpRecord(f, *iter1);\n  for (; iter2 != ip2.end(); ++iter2) writeIpRecord(f, *iter2);\n  f.close();\n}\n\nvoid saveImagesAndMatches(std::string const& left_prefix, std::string const& right_prefix,\n                          std::pair<int, int> const& index_pair, MATCH_PAIR const& match_pair,\n                          std::vector<cv::Mat> const& images) {\n  // Add 10000 to have them be listed nicely\n  std::ostringstream oss_left;\n  oss_left << left_prefix << \"_image\" << index_pair.first + 10000 << \".jpg\";\n  std::string left_image_file = oss_left.str();\n  std::cout << \"Writing: \" << left_image_file << std::endl;\n  cv::imwrite(left_image_file, images[index_pair.first]);\n\n  std::ostringstream oss_right;\n  oss_right << right_prefix << \"_image\" << index_pair.second + 10000 << \".jpg\";\n  std::string right_image_file = oss_right.str();\n  std::cout << \"Writing: \" << right_image_file << std::endl;\n  cv::imwrite(right_image_file, images[index_pair.second]);\n\n  std::string left_stem = boost::filesystem::path(left_image_file).stem().string();\n  std::string right_stem = boost::filesystem::path(right_image_file).stem().string();\n\n  std::string match_file = left_stem + \"__\" + right_stem + \".match\";\n  std::cout << \"Writing: \" << left_image_file << ' ' << right_image_file << ' ' << match_file << std::endl;\n  writeMatchFile(match_file, match_pair.first, match_pair.second);\n}\n\n// Triangulate rays emanating from given undistorted and centered pixels\nEigen::Vector3d TriangulatePair(double focal_length1, double focal_length2,\n                                Eigen::Affine3d const& world_to_cam1,\n                                Eigen::Affine3d const& world_to_cam2,\n                                Eigen::Vector2d const& pix1,\n                                Eigen::Vector2d const& pix2) {\n  Eigen::Matrix3d k1;\n  k1 << focal_length1, 0, 0, 0, focal_length1, 0, 0, 0, 1;\n\n  Eigen::Matrix3d k2;\n  k2 << focal_length2, 0, 0, 0, focal_length2, 0, 0, 0, 1;\n\n  openMVG::Mat34 cid_to_p1, cid_to_p2;\n  openMVG::P_From_KRt(k1, world_to_cam1.linear(), world_to_cam1.translation(), &cid_to_p1);\n  openMVG::P_From_KRt(k2, world_to_cam2.linear(), world_to_cam2.translation(), &cid_to_p2);\n\n  openMVG::Triangulation tri;\n  tri.add(cid_to_p1, pix1);\n  tri.add(cid_to_p2, pix2);\n\n  Eigen::Vector3d solution = tri.compute();\n  return solution;\n}\n\n// Triangulate n rays emanating from given undistorted and centered pixels\nEigen::Vector3d Triangulate(std::vector<double>          const& focal_length_vec,\n                            std::vector<Eigen::Affine3d> const& world_to_cam_vec,\n                            std::vector<Eigen::Vector2d> const& pix_vec) {\n  if (focal_length_vec.size() != world_to_cam_vec.size() ||\n      focal_length_vec.size() != pix_vec.size())\n    LOG(FATAL) << \"All inputs to Triangulate() must have the same size.\";\n\n  if (focal_length_vec.size() <= 1)\n    LOG(FATAL) << \"At least two rays must be passed to Triangulate().\";\n\n  openMVG::Triangulation tri;\n\n  for (size_t it = 0; it < focal_length_vec.size(); it++) {\n    Eigen::Matrix3d k;\n    k << focal_length_vec[it], 0, 0, 0, focal_length_vec[it], 0, 0, 0, 1;\n\n    openMVG::Mat34 cid_to_p;\n    openMVG::P_From_KRt(k, world_to_cam_vec[it].linear(), world_to_cam_vec[it].translation(),\n                        &cid_to_p);\n\n    tri.add(cid_to_p, pix_vec[it]);\n  }\n\n  Eigen::Vector3d solution = tri.compute();\n  return solution;\n}\n\nvoid detectMatchFeatures(  // Inputs\n                         std::vector<dense_map::cameraImage> const& cams,\n                         std::vector<std::string> const& cam_names,\n                         std::vector<camera::CameraParameters> const& cam_params,\n                         std::vector<Eigen::Affine3d> const& world_to_cam, int num_overlaps,\n                         int initial_max_reprojection_error, int num_match_threads,\n                         bool verbose,\n                         // Outputs\n                         std::vector<std::vector<std::pair<float, float>>>& keypoint_vec,\n                         std::vector<std::map<int, int>>& pid_to_cid_fid,\n                         std::vector<std::string> & image_files) {\n  // Wipe the outputs\n  keypoint_vec.clear();\n  pid_to_cid_fid.clear();\n  image_files.clear();\n\n  if (verbose) {\n    int count = 10000;\n    for (size_t it = 0; it < cams.size(); it++) {\n      std::ostringstream oss;\n      oss << count << \"_\" << cam_names[cams[it].camera_type] << \".jpg\";\n      std::string name = oss.str();\n      std::cout << \"Writing: \" << name << std::endl;\n      cv::imwrite(name, cams[it].image);\n      count++;\n      image_files.push_back(name);\n    }\n  }\n\n  // Detect features using multiple threads. Too many threads may result\n  // in high memory usage.\n  std::ostringstream oss;\n  oss << num_match_threads;\n  std::string num_threads = oss.str();\n  google::SetCommandLineOption(\"num_threads\", num_threads.c_str());\n  if (!gflags::GetCommandLineOption(\"num_threads\", &num_threads))\n    LOG(FATAL) << \"Failed to get the value of --num_threads in Astrobee software.\\n\";\n  std::cout << \"Using \" << num_threads << \" threads for feature detection/matching.\" << std::endl;\n\n  std::cout << \"Detecting features.\" << std::endl;\n\n  std::vector<cv::Mat> cid_to_descriptor_map;\n  std::vector<Eigen::Matrix2Xd> cid_to_keypoint_map;\n  cid_to_descriptor_map.resize(cams.size());\n  cid_to_keypoint_map.resize(cams.size());\n  {\n    // Make the thread pool go out of scope when not needed to not use up memory\n    ff_common::ThreadPool thread_pool;\n    for (size_t it = 0; it < cams.size(); it++) {\n      thread_pool.AddTask\n        (&dense_map::detectFeatures,    // multi-thread  // NOLINT\n         // dense_map::detectFeatures(  // single-thread // NOLINT\n         cams[it].image, verbose, &cid_to_descriptor_map[it], &cid_to_keypoint_map[it]);\n    }\n    thread_pool.Join();\n  }\n\n  MATCH_MAP matches;\n\n  std::vector<std::pair<int, int> > image_pairs;\n  for (size_t it1 = 0; it1 < cams.size(); it1++) {\n    for (size_t it2 = it1 + 1; it2 < std::min(cams.size(), it1 + num_overlaps + 1); it2++) {\n      image_pairs.push_back(std::make_pair(it1, it2));\n    }\n  }\n\n  {\n    std::cout << \"Matching features.\" << std::endl;\n    ff_common::ThreadPool thread_pool;\n    std::mutex match_mutex;\n    for (size_t pair_it = 0; pair_it < image_pairs.size(); pair_it++) {\n      auto pair = image_pairs[pair_it];\n      int left_image_it = pair.first, right_image_it = pair.second;\n      thread_pool.AddTask\n        (&dense_map::matchFeaturesWithCams,   // multi-threaded  // NOLINT\n         // dense_map::matchFeaturesWithCams( // single-threaded // NOLINT\n         &match_mutex, left_image_it, right_image_it, cam_params[cams[left_image_it].camera_type],\n         cam_params[cams[right_image_it].camera_type], world_to_cam[left_image_it],\n         world_to_cam[right_image_it], initial_max_reprojection_error,\n         cid_to_descriptor_map[left_image_it], cid_to_descriptor_map[right_image_it],\n         cid_to_keypoint_map[left_image_it], cid_to_keypoint_map[right_image_it], verbose,\n         &matches[pair]);\n    }\n    thread_pool.Join();\n  }\n  cid_to_descriptor_map = std::vector<cv::Mat>();  // Wipe, takes memory\n\n  // Give all interest points in a given image a unique id, and put\n  // them in a vector with the id corresponding to the interest point\n  std::vector<std::map<std::pair<float, float>, int>> keypoint_map(cams.size());\n  for (auto it = matches.begin(); it != matches.end(); it++) {\n    std::pair<int, int> const& index_pair = it->first;     // alias\n\n    int left_index = index_pair.first;\n    int right_index = index_pair.second;\n\n    dense_map::MATCH_PAIR const& match_pair = it->second;  // alias\n    std::vector<dense_map::InterestPoint> const& left_ip_vec = match_pair.first;\n    std::vector<dense_map::InterestPoint> const& right_ip_vec = match_pair.second;\n    for (size_t ip_it = 0; ip_it < left_ip_vec.size(); ip_it++) {\n      auto dist_left_ip  = std::make_pair(left_ip_vec[ip_it].x,  left_ip_vec[ip_it].y);\n      auto dist_right_ip = std::make_pair(right_ip_vec[ip_it].x, right_ip_vec[ip_it].y);\n      // Initialize to zero for the moment\n      keypoint_map[left_index][dist_left_ip] = 0;\n      keypoint_map[right_index][dist_right_ip] = 0;\n    }\n  }\n  keypoint_vec.resize(cams.size());\n  for (size_t cid = 0; cid < cams.size(); cid++) {\n    keypoint_vec[cid].resize(keypoint_map[cid].size());\n    int fid = 0;\n    for (auto ip_it = keypoint_map[cid].begin(); ip_it != keypoint_map[cid].end();\n         ip_it++) {\n      auto& dist_ip = ip_it->first;  // alias\n      keypoint_map[cid][dist_ip] = fid;\n      keypoint_vec[cid][fid] = dist_ip;\n      fid++;\n    }\n  }\n\n  // If feature A in image I matches feather B in image J, which\n  // matches feature C in image K, then (A, B, C) belong together in\n  // a track, and will have a single triangulated xyz. Build such a track.\n\n  openMVG::matching::PairWiseMatches match_map;\n  for (auto it = matches.begin(); it != matches.end(); it++) {\n    std::pair<int, int> const& index_pair = it->first;     // alias\n\n    int left_index = index_pair.first;\n    int right_index = index_pair.second;\n\n    dense_map::MATCH_PAIR const& match_pair = it->second;  // alias\n    std::vector<dense_map::InterestPoint> const& left_ip_vec = match_pair.first;\n    std::vector<dense_map::InterestPoint> const& right_ip_vec = match_pair.second;\n\n    std::vector<openMVG::matching::IndMatch> mvg_matches;\n\n    for (size_t ip_it = 0; ip_it < left_ip_vec.size(); ip_it++) {\n      auto dist_left_ip  = std::make_pair(left_ip_vec[ip_it].x,  left_ip_vec[ip_it].y);\n      auto dist_right_ip = std::make_pair(right_ip_vec[ip_it].x, right_ip_vec[ip_it].y);\n\n      int left_id = keypoint_map[left_index][dist_left_ip];\n      int right_id = keypoint_map[right_index][dist_right_ip];\n      mvg_matches.push_back(openMVG::matching::IndMatch(left_id, right_id));\n    }\n    match_map[index_pair] = mvg_matches;\n  }\n\n  if (verbose) {\n    for (auto it = matches.begin(); it != matches.end(); it++) {\n      std::pair<int, int> index_pair = it->first;\n      dense_map::MATCH_PAIR const& match_pair = it->second;\n\n      int left_index = index_pair.first;\n      int right_index = index_pair.second;\n\n      std::string left_image = image_files[left_index];\n      std::string right_image = image_files[right_index];\n\n      std::string left_stem = boost::filesystem::path(left_image).stem().string();\n      std::string right_stem = boost::filesystem::path(right_image).stem().string();\n\n      std::string match_file = left_stem + \"__\" + right_stem + \".match\";\n\n      std::cout << \"Writing: \" << left_image << ' ' << right_image << ' '\n                << match_file << std::endl;\n      dense_map::writeMatchFile(match_file, match_pair.first, match_pair.second);\n    }\n  }\n\n  // De-allocate data not needed anymore and take up a lot of RAM\n  matches.clear(); matches = MATCH_MAP();\n  keypoint_map.clear(); keypoint_map.shrink_to_fit();\n  cid_to_keypoint_map.clear(); cid_to_keypoint_map.shrink_to_fit();\n\n  {\n    // Build tracks\n    // De-allocate these as soon as not needed to save memory\n    openMVG::tracks::TracksBuilder trackBuilder;\n    trackBuilder.Build(match_map);  // Build:  Efficient fusion of correspondences\n    trackBuilder.Filter();          // Filter: Remove tracks that have conflict\n    // trackBuilder.ExportToStream(std::cout);\n    // Export tracks as a map (each entry is a sequence of imageId and featureIndex):\n    //  {TrackIndex => {(imageIndex, featureIndex), ... ,(imageIndex, featureIndex)}\n    openMVG::tracks::STLMAPTracks map_tracks;\n    trackBuilder.ExportToSTL(map_tracks);\n    match_map = openMVG::matching::PairWiseMatches();  // wipe this, no longer needed\n    trackBuilder = openMVG::tracks::TracksBuilder();   // wipe it\n\n    if (map_tracks.empty())\n      LOG(FATAL) << \"No tracks left after filtering. Perhaps images are too dis-similar?\\n\";\n\n    // Populate the filtered tracks\n    size_t num_elems = map_tracks.size();\n    pid_to_cid_fid.resize(num_elems);\n    size_t curr_id = 0;\n    for (auto itr = map_tracks.begin(); itr != map_tracks.end(); itr++) {\n      for (auto itr2 = (itr->second).begin(); itr2 != (itr->second).end(); itr2++) {\n        pid_to_cid_fid[curr_id][itr2->first] = itr2->second;\n      }\n      curr_id++;\n    }\n  }\n\n  return;\n}\n\n}  // end namespace dense_map\n", "meta": {"hexsha": "17ed579e458708042766db86d4f2491ddb770bc2", "size": 25775, "ext": "cc", "lang": "C++", "max_stars_repo_path": "dense_map/geometry_mapper/src/interest_point.cc", "max_stars_repo_name": "CodeMasterBond/isaac", "max_stars_repo_head_hexsha": "b21a533cf30eed012fe12ece047b6d87418d7c6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2021-11-18T19:29:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-23T01:55:51.000Z", "max_issues_repo_path": "dense_map/geometry_mapper/src/interest_point.cc", "max_issues_repo_name": "CodeMasterBond/isaac", "max_issues_repo_head_hexsha": "b21a533cf30eed012fe12ece047b6d87418d7c6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2021-11-30T17:14:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T21:38:33.000Z", "max_forks_repo_path": "dense_map/geometry_mapper/src/interest_point.cc", "max_forks_repo_name": "CodeMasterBond/isaac", "max_forks_repo_head_hexsha": "b21a533cf30eed012fe12ece047b6d87418d7c6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-12-03T02:38:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T01:52:03.000Z", "avg_line_length": 42.1160130719, "max_line_length": 117, "alphanum_fraction": 0.6649466537, "num_tokens": 6616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22608156617653244}}
{"text": "#include \"basic.h\"\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic push\n#if __GNUC_PREREQ(9, 0)\n#pragma GCC diagnostic ignored \"-Wdeprecated-copy\"\n#endif\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#endif\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics.hpp>\n#include <boost/log/trivial.hpp>\n\n#if defined(__GNUC__)\n#pragma GCC diagnostic pop\n#endif\n\n#if defined(_MSC_VER)\n#pragma warning(push)\n#pragma warning(disable : 4554)\n#pragma warning(disable : 26450)\n#pragma warning(disable : 26451)\n#pragma warning(disable : 26454)\n#pragma warning(disable : 26495)\n#pragma warning(disable : 26812)\n#elif defined(__GNUC__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n#endif\n\n#include <unsupported/Eigen/CXX11/Tensor>\n\n#if defined(_MSC_VER)\n#pragma warning(pop)\n#elif defined(__GNUC__)\n#pragma GCC diagnostic pop\n#endif\n\n#include <OpenSimplexNoise.h>\n\nnamespace ba = boost::accumulators;\n\nnamespace WorldEngine\n{\n\nvoid AntiAlias(boost::multi_array<float, 2>& mapData, size_t steps)\n{\n   typedef Eigen::Tensor<float, 2>    Tensor2D;\n   typedef Eigen::TensorMap<Tensor2D> Tensor2DMap;\n\n   static const float w = 1.0f / 11.0f;\n\n   Tensor2D kernel(3, 3);\n   kernel.setValues({{w, w, w}, {w, w, w}, {w, w, w}});\n\n   const uint32_t width  = static_cast<uint32_t>(mapData.shape()[1]);\n   const uint32_t height = static_cast<uint32_t>(mapData.shape()[0]);\n\n   Tensor2DMap map(mapData.data(), width, height);\n\n   Tensor2D mapPart = map * (2.0f / 11.0f);\n\n   auto AntiAliasStep = [&width,\n                         &height,\n                         &mapPart = std::as_const(mapPart),\n                         &kernel  = std::as_const(kernel)](Tensor2DMap& map) {\n      // Specify first and second dimension for convolution\n      static const Eigen::array<int, 2> dimensions({0, 1});\n\n      // Create a circular boundary\n      const Eigen::array<std::pair<int, int>, 2> paddings(\n         {std::make_pair(1, 1), std::make_pair(1, 1)});\n      Tensor2D paddedMap = map.pad(paddings);\n\n      for (uint32_t x = 0; x <= width + 1; x++)\n      {\n         paddedMap(x, 0)          = paddedMap(x, height);\n         paddedMap(x, height + 1) = paddedMap(x, 1);\n      }\n      for (uint32_t y = 0; y <= height + 1; y++)\n      {\n         paddedMap(0, y)         = paddedMap(width, y);\n         paddedMap(width + 1, y) = paddedMap(1, y);\n      }\n\n      map = paddedMap.convolve(kernel, dimensions);\n\n      map += mapPart;\n   };\n\n   for (size_t i = 0; i < steps; i++)\n   {\n      AntiAliasStep(map);\n   }\n}\n\ntemplate<typename T>\nboost::multi_array<uint32_t, 2>\nCountNeighbors(const boost::multi_array<T, 2>& mask, int32_t radius)\n{\n   const int32_t width  = static_cast<int32_t>(mask.shape()[1]);\n   const int32_t height = static_cast<int32_t>(mask.shape()[0]);\n\n   boost::multi_array<uint32_t, 2> neighbors(boost::extents[height][width]);\n\n   std::fill(neighbors.data(), neighbors.data() + neighbors.num_elements(), 0u);\n\n   for (int32_t y = 0; y < height; y++)\n   {\n      for (int32_t x = 0; x < width; x++)\n      {\n         for (int32_t ny = y - radius; ny <= y + radius; ny++)\n         {\n            if (0 <= ny && ny < height)\n            {\n               for (int32_t nx = x - radius; nx <= x + radius; nx++)\n               {\n                  if ((nx != x || ny != y) && 0 <= nx && nx < width)\n                  {\n                     if (mask[ny][nx])\n                     {\n                        neighbors[y][x]++;\n                     }\n                  }\n               }\n            }\n         }\n      }\n   }\n\n   return neighbors;\n}\ntemplate boost::multi_array<uint32_t, 2>\nCountNeighbors<bool>(const boost::multi_array<bool, 2>& mask, int32_t radius);\ntemplate boost::multi_array<uint32_t, 2>\nCountNeighbors<float>(const boost::multi_array<float, 2>& mask, int32_t radius);\n\nfloat FindThresholdF(const boost::multi_array<float, 2>& mapData,\n                     float                               landPercentage,\n                     const OceanArrayType*               ocean)\n{\n   typedef ba::accumulator_set<float, ba::stats<ba::tag::p_square_quantile>>\n      accumulator_t;\n\n   const uint32_t width    = static_cast<uint32_t>(mapData.shape()[1]);\n   const uint32_t height   = static_cast<uint32_t>(mapData.shape()[0]);\n   float          quantile = 1.0f - landPercentage;\n\n   accumulator_t accumulator(ba::quantile_probability = quantile);\n\n   if (ocean == nullptr || ocean->size() != mapData.size())\n   {\n      BOOST_LOG_TRIVIAL(trace) << \"Calculating threshold (\" << landPercentage\n                               << \") without ocean data...\";\n\n      for (uint32_t y = 0; y < height; y++)\n      {\n         for (uint32_t x = 0; x < width; x++)\n         {\n            accumulator(mapData[y][x]);\n         }\n      }\n   }\n   else\n   {\n      BOOST_LOG_TRIVIAL(trace) << \"Calculating threshold (\" << landPercentage\n                               << \") with ocean data...\";\n\n      for (uint32_t y = 0; y < height; y++)\n      {\n         for (uint32_t x = 0; x < width; x++)\n         {\n            if (!(*ocean)[y][x])\n            {\n               accumulator(mapData[y][x]);\n            }\n         }\n      }\n   }\n\n   float threshold = ba::p_square_quantile(accumulator);\n\n   BOOST_LOG_TRIVIAL(trace) << \"Threshold: \" << threshold;\n\n   return threshold;\n}\n\ndouble Noise(const OpenSimplexNoise::Noise& noise,\n             double                         x,\n             double                         y,\n             uint32_t                       octaves)\n{\n   static const double persistence = 0.5;\n   static const double lacunarity  = 2.0;\n\n   double freq  = 1.0;\n   double amp   = 1.0;\n   double max   = 1.0;\n   double total = noise.eval(x, y);\n\n   for (uint32_t i = 1; i < octaves; i++)\n   {\n      freq *= lacunarity;\n      amp *= persistence;\n      max += amp;\n      total += noise.eval(x * freq, y * freq) * amp;\n   }\n\n   return total / max;\n}\n\n} // namespace WorldEngine\n", "meta": {"hexsha": "945bda1e151f6148f42644482981555c4c890b24", "size": 5990, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "worldengine/source/basic.cpp", "max_stars_repo_name": "dpaulat/worldengine-cpp", "max_stars_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T12:44:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T21:52:10.000Z", "max_issues_repo_path": "worldengine/source/basic.cpp", "max_issues_repo_name": "dpaulat/worldengine-cpp", "max_issues_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-09T12:49:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T15:28:37.000Z", "max_forks_repo_path": "worldengine/source/basic.cpp", "max_forks_repo_name": "dpaulat/worldengine-cpp", "max_forks_repo_head_hexsha": "9f7961aaf62db2633fc9d44b6018384812a6704e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8604651163, "max_line_length": 80, "alphanum_fraction": 0.5686143573, "num_tokens": 1566, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22608156617653244}}
{"text": "//            Copyright Daniel Trebbien 2010.\n// Distributed under the Boost Software License, Version 1.0.\n//   (See accompanying file LICENSE_1_0.txt or the copy at\n//         http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GRAPH_STOER_WAGNER_MIN_CUT_HPP\n#define BOOST_GRAPH_STOER_WAGNER_MIN_CUT_HPP 1\n\n#include <cassert>\n#include <set>\n#include <vector>\n#include <boost/concept_check.hpp>\n#include <boost/concept/assert.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/buffer_concepts.hpp>\n#include <boost/graph/exception.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/iteration_macros.hpp>\n#include <boost/graph/named_function_params.hpp>\n#include <boost/graph/detail/d_ary_heap.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/tuple/tuple.hpp>\n#include <boost/typeof/typeof.hpp>\n\nnamespace boost {\n  \n  namespace detail {\n    \n    /**\n     * \\brief Performs a phase of the Stoer-Wagner min-cut algorithm\n     *\n     * Performs a phase of the Stoer-Wagner min-cut algorithm.\n     *\n     * As described by Stoer & Wagner (1997), a phase is simply a maximum adjacency search\n     * (also called a maximum cardinality search), which results in the selection of two vertices\n     * \\em s and \\em t, and, as a side product, a minimum <em>s</em>-<em>t</em> cut of\n     * the input graph. Here, the input graph is basically \\p g, but some vertices are virtually\n     * assigned to others as a way of viewing \\p g as a graph with some sets of\n     * vertices merged together.\n     *\n     * This implementation is a translation of pseudocode by Professor Uri Zwick,\n     * School of Computer Science, Tel Aviv University.\n     *\n     * \\pre \\p g is a connected, undirected graph\n     * \\param[in] g the input graph\n     * \\param[in] assignments a read/write property map from each vertex to the vertex that it is assigned to\n     * \\param[in] assignedVertices a list of vertices that are assigned to others\n     * \\param[in] weights a readable property map from each edge to its weight (a non-negative value)\n     * \\param[out] pq a keyed, updatable max-priority queue\n     * \\returns a tuple (\\em s, \\em t, \\em w) of the \"<em>s</em>\" and \"<em>t</em>\"\n     *     of the minimum <em>s</em>-<em>t</em> cut and the cut weight \\em w\n     *     of the minimum <em>s</em>-<em>t</em> cut.\n     * \\see http://www.cs.tau.ac.il/~zwick/grad-algo-08/gmc.pdf\n     *\n     * \\author Daniel Trebbien\n     * \\date 2010-09-11\n     */\n    template <class UndirectedGraph, class VertexAssignmentMap, class WeightMap, class KeyedUpdatablePriorityQueue>\n    boost::tuple<typename boost::graph_traits<UndirectedGraph>::vertex_descriptor, typename boost::graph_traits<UndirectedGraph>::vertex_descriptor, typename boost::property_traits<WeightMap>::value_type>\n    stoer_wagner_phase(const UndirectedGraph& g, VertexAssignmentMap assignments, const std::set<typename boost::graph_traits<UndirectedGraph>::vertex_descriptor>& assignedVertices, WeightMap weights, KeyedUpdatablePriorityQueue& pq) {\n      typedef typename boost::graph_traits<UndirectedGraph>::vertex_descriptor vertex_descriptor;\n      typedef typename boost::property_traits<WeightMap>::value_type weight_type;\n      \n      assert(pq.empty());\n      typename KeyedUpdatablePriorityQueue::key_map keys = pq.keys();\n      \n      BGL_FORALL_VERTICES_T(v, g, UndirectedGraph) {\n        if (v == get(assignments, v)) { // foreach u \\in V do\n          put(keys, v, weight_type(0));\n          \n          pq.push(v);\n        }\n      }\n      \n      assert(pq.size() >= 2);\n      \n      vertex_descriptor s, t;\n      weight_type w;\n      while (!pq.empty()) { // while PQ \\neq {} do\n        const vertex_descriptor u = pq.top(); // u = extractmax(PQ)\n        w = get(keys, u);\n        pq.pop();\n        \n        s = t; t = u;\n        \n        BGL_FORALL_OUTEDGES_T(u, e, g, UndirectedGraph) { // foreach (u, v) \\in E do\n          const vertex_descriptor v = get(assignments, target(e, g));\n          \n          if (pq.contains(v)) { // if v \\in PQ then\n            put(keys, v, get(keys, v) + get(weights, e)); // increasekey(PQ, v, wA(v) + w(u, v))\n            pq.update(v);\n          }\n        }\n        \n        typename std::set<vertex_descriptor>::const_iterator assignedVertexIt, assignedVertexEnd = assignedVertices.end();\n        for (assignedVertexIt = assignedVertices.begin(); assignedVertexIt != assignedVertexEnd; ++assignedVertexIt) {\n          const vertex_descriptor uPrime = *assignedVertexIt;\n          \n          if (get(assignments, uPrime) == u) {\n            BGL_FORALL_OUTEDGES_T(uPrime, e, g, UndirectedGraph) { // foreach (u, v) \\in E do\n              const vertex_descriptor v = get(assignments, target(e, g));\n              \n              if (pq.contains(v)) { // if v \\in PQ then\n                put(keys, v, get(keys, v) + get(weights, e)); // increasekey(PQ, v, wA(v) + w(u, v))\n                pq.update(v);\n              }\n            }\n          }\n        }\n      }\n      \n      return boost::make_tuple(s, t, w);\n    }\n    \n    /**\n     * \\brief Computes a min-cut of the input graph\n     *\n     * Computes a min-cut of the input graph using the Stoer-Wagner algorithm.\n     *\n     * \\pre \\p g is a connected, undirected graph\n     * \\pre <code>pq.empty()</code>\n     * \\param[in] g the input graph\n     * \\param[in] weights a readable property map from each edge to its weight (a non-negative value)\n     * \\param[out] parities a writable property map from each vertex to a bool type object for\n     *     distinguishing the two vertex sets of the min-cut\n     * \\param[out] assignments a read/write property map from each vertex to a \\c vertex_descriptor object. This\n     *     map serves as work space, and no particular meaning should be derived from property values\n     *     after completion of the algorithm.\n     * \\param[out] pq a keyed, updatable max-priority queue\n     * \\returns the cut weight of the min-cut\n     * \\see http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.114.6687&rep=rep1&type=pdf\n     * \\see http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.31.614&rep=rep1&type=pdf\n     *\n     * \\author Daniel Trebbien\n     * \\date 2010-09-11\n     */\n    template <class UndirectedGraph, class WeightMap, class ParityMap, class VertexAssignmentMap, class KeyedUpdatablePriorityQueue>\n    typename boost::property_traits<WeightMap>::value_type\n    stoer_wagner_min_cut(const UndirectedGraph& g, WeightMap weights, ParityMap parities, VertexAssignmentMap assignments, KeyedUpdatablePriorityQueue& pq) {\n      BOOST_CONCEPT_ASSERT((boost::IncidenceGraphConcept<UndirectedGraph>));\n      BOOST_CONCEPT_ASSERT((boost::VertexListGraphConcept<UndirectedGraph>));\n      typedef typename boost::graph_traits<UndirectedGraph>::vertex_descriptor vertex_descriptor;\n      typedef typename boost::graph_traits<UndirectedGraph>::vertices_size_type vertices_size_type;\n      typedef typename boost::graph_traits<UndirectedGraph>::edge_descriptor edge_descriptor;\n      BOOST_CONCEPT_ASSERT((boost::Convertible<typename boost::graph_traits<UndirectedGraph>::directed_category, boost::undirected_tag>));\n      BOOST_CONCEPT_ASSERT((boost::ReadablePropertyMapConcept<WeightMap, edge_descriptor>));\n      typedef typename boost::property_traits<WeightMap>::value_type weight_type;\n      BOOST_CONCEPT_ASSERT((boost::WritablePropertyMapConcept<ParityMap, vertex_descriptor>));\n      typedef typename boost::property_traits<ParityMap>::value_type parity_type;\n      BOOST_CONCEPT_ASSERT((boost::ReadWritePropertyMapConcept<VertexAssignmentMap, vertex_descriptor>));\n      BOOST_CONCEPT_ASSERT((boost::Convertible<vertex_descriptor, typename boost::property_traits<VertexAssignmentMap>::value_type>));\n      BOOST_CONCEPT_ASSERT((boost::KeyedUpdatableQueueConcept<KeyedUpdatablePriorityQueue>));\n      \n      vertices_size_type n = num_vertices(g);\n      if (n < 2)\n        throw boost::bad_graph(\"the input graph must have at least two vertices.\");\n      else if (!pq.empty())\n        throw std::invalid_argument(\"the max-priority queue must be empty initially.\");\n      \n      std::set<vertex_descriptor> assignedVertices;\n      \n      // initialize `assignments` (all vertices are initially assigned to themselves)\n      BGL_FORALL_VERTICES_T(v, g, UndirectedGraph) {\n        put(assignments, v, v);\n      }\n      \n      vertex_descriptor s, t;\n      weight_type bestW;\n      \n      boost::tie(s, t, bestW) = boost::detail::stoer_wagner_phase(g, assignments, assignedVertices, weights, pq);\n      assert(s != t);\n      BGL_FORALL_VERTICES_T(v, g, UndirectedGraph) {\n        put(parities, v, parity_type(v == t ? 1 : 0));\n      }\n      put(assignments, t, s);\n      assignedVertices.insert(t);\n      --n;\n      \n      for (; n >= 2; --n) {\n        weight_type w;\n        boost::tie(s, t, w) = boost::detail::stoer_wagner_phase(g, assignments, assignedVertices, weights, pq);\n        assert(s != t);\n        \n        if (w < bestW) {\n          BGL_FORALL_VERTICES_T(v, g, UndirectedGraph) {\n            put(parities, v, parity_type(get(assignments, v) == t ? 1 : 0));\n            \n            if (get(assignments, v) == t) // all vertices that were assigned to t are now assigned to s\n              put(assignments, v, s);\n          }\n          \n          bestW = w;\n        } else {\n          BGL_FORALL_VERTICES_T(v, g, UndirectedGraph) {\n            if (get(assignments, v) == t) // all vertices that were assigned to t are now assigned to s\n              put(assignments, v, s);\n          }\n        }\n        put(assignments, t, s);\n        assignedVertices.insert(t);\n      }\n      \n      assert(pq.empty());\n      \n      return bestW;\n    }\n    \n  } // end `namespace detail` within `namespace boost`\n  \n  template <class UndirectedGraph, class WeightMap, class P, class T, class R>\n  inline typename boost::property_traits<WeightMap>::value_type\n  stoer_wagner_min_cut(const UndirectedGraph& g, WeightMap weights, const boost::bgl_named_params<P, T, R>& params) {\n    typedef typename boost::graph_traits<UndirectedGraph>::vertex_descriptor vertex_descriptor;\n    typedef typename std::vector<vertex_descriptor>::size_type heap_container_size_type;\n    typedef typename boost::property_traits<WeightMap>::value_type weight_type;\n    \n    typedef boost::bgl_named_params<P, T, R> params_type;\n    BOOST_GRAPH_DECLARE_CONVERTED_PARAMETERS(params_type, params)\n    \n    BOOST_AUTO(pq, (boost::detail::make_priority_queue_from_arg_pack_gen<boost::graph::keywords::tag::max_priority_queue, weight_type, vertex_descriptor, std::greater<weight_type> >(choose_param(get_param(params, boost::distance_zero_t()), weight_type(0)))(g, arg_pack)));\n    \n    return boost::detail::stoer_wagner_min_cut(g,\n        weights,\n        choose_param(get_param(params, boost::parity_map_t()), boost::dummy_property_map()),\n        boost::detail::make_property_map_from_arg_pack_gen<boost::graph::keywords::tag::vertex_assignment_map, vertex_descriptor>(vertex_descriptor())(g, arg_pack),\n        pq\n      );\n  }\n  \n  template <class UndirectedGraph, class WeightMap>\n  inline typename boost::property_traits<WeightMap>::value_type\n  stoer_wagner_min_cut(const UndirectedGraph& g, WeightMap weights) {\n    return boost::stoer_wagner_min_cut(g, weights, boost::vertex_index_map(get(boost::vertex_index, g)));\n  }\n  \n} // end `namespace boost`\n\n#include <boost/graph/iteration_macros_undef.hpp>\n\n#endif // !BOOST_GRAPH_STOER_WAGNER_MIN_CUT_HPP\n", "meta": {"hexsha": "9cd2d0da06c7c500e75ccde2c6fdfadcd4861af2", "size": 11463, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "projects/MonkVG-Android/jni/boost/include/boost/graph/stoer_wagner_min_cut.hpp", "max_stars_repo_name": "smartmobili/MonkVG", "max_stars_repo_head_hexsha": "3fad9b73d30c13411e0ca47bd3e2cc803ac89a9d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-11-12T19:24:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T23:10:45.000Z", "max_issues_repo_path": "projects/MonkVG-Android/jni/boost/include/boost/graph/stoer_wagner_min_cut.hpp", "max_issues_repo_name": "smartmobili/MonkVG", "max_issues_repo_head_hexsha": "3fad9b73d30c13411e0ca47bd3e2cc803ac89a9d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-11-02T06:30:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-23T18:39:55.000Z", "max_forks_repo_path": "projects/MonkVG-Android/jni/boost/include/boost/graph/stoer_wagner_min_cut.hpp", "max_forks_repo_name": "smartmobili/MonkVG", "max_forks_repo_head_hexsha": "3fad9b73d30c13411e0ca47bd3e2cc803ac89a9d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-03-04T08:50:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-23T14:27:04.000Z", "avg_line_length": 47.5643153527, "max_line_length": 272, "alphanum_fraction": 0.6741690657, "num_tokens": 2838, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2260114108481858}}
{"text": "//\n// Copyright (c) 2020 Kenshi Abe\n//\n\n#include \"Trainer.hpp\"\n\n#include <iostream>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/serialization/unordered_map.hpp>\n#include \"Node.hpp\"\n\nnamespace Trainer {\n\n/// @param mode variant of CFR algorithm\n/// @param seed random seed\n/// @param strategyPaths paths to the binary files that represent fixed strategies\ntemplate <typename T>\nTrainer<T>::Trainer(const std::string &mode, const uint32_t seed, const std::vector<std::string> &strategyPaths) : mEngine(seed), mNodeTouchedCnt(0), mModeStr(mode) {\n    mGame = new T(mEngine);\n    mFolderPath = \"../strategies/\" + mGame->name();\n    boost::filesystem::create_directories(mFolderPath);\n    mFixedStrategies = new std::unordered_map<std::string, Node *>[mGame->playerNum()];\n    mUpdate = new bool[mGame->playerNum()];\n    for (int i = 0; i < mGame->playerNum(); ++i) {\n        if (strategyPaths.size() >= i + 1 && !strategyPaths[i].empty()) {\n            std::cout << \"load strategy \\\"\" << strategyPaths[i] << \"\\\" as static player \" << i << std::endl;\n            std::ifstream ifs(strategyPaths[i]);\n            boost::archive::binary_iarchive ia(ifs);\n            ia >> mFixedStrategies[i];\n            ifs.close();\n            mUpdate[i] = false;\n        } else {\n            mUpdate[i] = true;\n        }\n    }\n}\n\ntemplate <typename T>\nTrainer<T>::~Trainer() {\n    for (auto &itr : mNodeMap) {\n        delete itr.second;\n    }\n    for (int i = 0; i < mGame->playerNum(); ++i) {\n        if (mUpdate[i]) {\n            continue;\n        }\n        for (auto &itr : mFixedStrategies[i]) {\n            delete itr.second;\n        }\n    }\n    delete[] mFixedStrategies;\n    delete[] mUpdate;\n    delete mGame;\n}\n\n/// @brief Calculate the expected payoff of each player\n/// @param game game\n/// @param strategies list of strategies for each player\n/// @return list of expected payoffs\ntemplate <typename T>\nstd::vector<double> Trainer<T>::CalculatePayoff(const T &game, const std::vector<std::function<const double *(const T &)>> &strategies) {\n    // return payoff for terminal states\n    if (game.done()) {\n        std::vector<double> payoffs(game.playerNum());\n        for (int i = 0; i < game.playerNum(); ++i) {\n            payoffs[i] = game.payoff(i);\n        }\n        return payoffs;\n    }\n\n    // chance node turn\n    const int actionNum = game.actionNum();\n    if (game.isChanceNode()) {\n        std::vector<double> nodeUtils(game.playerNum());\n        for (int i = 0; i < game.playerNum(); ++i) {\n            nodeUtils[i] = 0.0;\n        }\n        for (int a = 0; a < actionNum; ++a) {\n            auto game_cp(game);\n            game_cp.step(a);\n            const double chanceProbability = game_cp.chanceProbability();\n            std::vector<double> utils = CalculatePayoff(game_cp, strategies);\n            for (int i = 0; i < game.playerNum(); ++i) {\n                nodeUtils[i] += chanceProbability * utils[i];\n            }\n        }\n        return nodeUtils;\n    }\n\n    // for each action, recursively calculate payoff with additional history and probability\n    const int player = game.currentPlayer();\n    std::vector<double> nodeUtils(game.playerNum());\n    for (int i = 0; i < game.playerNum(); ++i) {\n        nodeUtils[i] = 0.0;\n    }\n    for (int a = 0; a < actionNum; ++a) {\n        auto game_cp(game);\n        game_cp.step(a);\n        std::vector<double> utils = CalculatePayoff(game_cp, strategies);\n        for (int i = 0; i < game.playerNum(); ++i) {\n            nodeUtils[i] += strategies[player](game)[a] * utils[i];\n        }\n    }\n    return nodeUtils;\n}\n\n/// @brief Calculate exploitability of a given strategy profile\n/// @param game game\n/// @param strategies list of strategies for each player\n/// @return exploitability of a given strategy profile\ntemplate <typename T>\ndouble Trainer<T>::CalculateExploitability(const T &game, const std::vector<std::function<const double *(const T &)>> &strategies) {\n    InfoSets infoSets;\n    for (int p = 0; p < game.playerNum(); ++p) {\n        auto game_cp(game);\n        game_cp.reset(false);\n        CreateInfoSets(game_cp, p, strategies, 1.0, infoSets);\n    }\n\n    double exploitability = 0.0;\n    for (int p = 0; p < game.playerNum(); ++p) {\n        auto game_cp(game);\n        game_cp.reset(false);\n        std::unordered_map<std::string, std::vector<double>> bestResponseStrategies;\n        exploitability += CalculateBestResponseValue(game_cp, p, strategies, bestResponseStrategies, 1.0, infoSets);\n    }\n    return exploitability;\n}\n\n/// @brief Fill the ordered map that maps information sets to game nodes and reach probabilities\n/// @param game game\n/// @param playerIndex player whose strategy is updated in the current iteration\n/// @param strategies list of strategies for each player\n/// @param po the probability of reaching the current game node if the acting player always chooses actions leading to the current game node\n/// @return exploitability of a given strategy profile\ntemplate <typename T>\nvoid Trainer<T>::CreateInfoSets(const T &game, const int playerIndex, const std::vector<std::function<const double *(const T &)>> &strategies, const double po, InfoSets &infoSets) {\n    // return at terminal states\n    if (game.done()) {\n        return;\n    }\n\n    // chance node turn\n    const int actionNum = game.actionNum();\n    if (game.isChanceNode()) {\n        for (int a = 0; a < actionNum; ++a) {\n            auto game_cp(game);\n            game_cp.step(a);\n            const double chanceProbability = game_cp.chanceProbability();\n            CreateInfoSets(game_cp, playerIndex, strategies, po * chanceProbability, infoSets);\n        }\n        return;\n    }\n\n    const int player = game.currentPlayer();\n    if (player == playerIndex) {\n        std::string infoSet = game.infoSetStr();\n        if (infoSets.count(infoSet) == 0) {\n            infoSets[infoSet] = std::vector<std::tuple<T, double>>();\n        }\n        infoSets[infoSet].push_back(std::make_tuple(game, po));\n    }\n\n    for (int a = 0; a < actionNum; ++a) {\n        auto game_cp(game);\n        game_cp.step(a);\n        if (player == playerIndex) {\n            CreateInfoSets(game_cp, playerIndex, strategies, po, infoSets);\n        } else {\n            const double actionProb = strategies[player](game)[a];\n            CreateInfoSets(game_cp, playerIndex, strategies, po * actionProb, infoSets);\n        }\n    }\n}\n\n/// @brief Calculate best response value for a given player\n/// @param game game\n/// @param playerIndex player whose strategy is updated in the current iteration\n/// @param strategies list of strategies for each player\n/// @param bestResponseStrategies best response strategy for a given player\n/// @param po the probability of reaching the current game node if the acting player always chooses actions leading to the current game node\n/// @param infoSets ordered map that maps information sets to game nodes and reach probabilities\n/// @return best response value for a given player\ntemplate <typename T>\ndouble Trainer<T>::CalculateBestResponseValue(const T &game, const int playerIndex,\n                                             const std::vector<std::function<const double *(const T &)>> &strategies,\n                                             std::unordered_map<std::string, std::vector<double>> &bestResponseStrategies,\n                                             const double po,\n                                             const InfoSets &infoSets) {\n    // return payoff for terminal states\n    if (game.done()) {\n        return game.payoff(playerIndex);\n    }\n\n    // chance node turn\n    const int actionNum = game.actionNum();\n    if (game.isChanceNode()) {\n        double nodeUtil = 0.0;\n        for (int a = 0; a < actionNum; ++a) {\n            auto game_cp(game);\n            game_cp.step(a);\n            const double chanceProbability = game_cp.chanceProbability();\n            nodeUtil += chanceProbability * CalculateBestResponseValue(game_cp, playerIndex, strategies, bestResponseStrategies, po * chanceProbability, infoSets);\n        }\n        return nodeUtil;\n    }\n\n    const int player = game.currentPlayer();\n    if (player == playerIndex) {\n        // get information set string representation\n        std::string infoSet = game.infoSetStr();\n        if (bestResponseStrategies.count(infoSet) == 0) {\n            // calculate action values\n            double actionValues[actionNum];\n            for (int a = 0; a < actionNum; ++a) {\n                actionValues[a] = 0.0;\n            }\n            for (int i = 0; i < infoSets.at(infoSet).size(); ++i) {\n                auto game_ = std::get<0>(infoSets.at(infoSet)[i]);\n                auto po_ = std::get<1>(infoSets.at(infoSet)[i]);\n                double brValues[actionNum];\n                for (int a = 0; a < actionNum; ++a) {\n                    auto game_cp(game_);\n                    game_cp.step(a);\n                    brValues[a] = CalculateBestResponseValue(game_cp, playerIndex, strategies, bestResponseStrategies, po_, infoSets);\n                    actionValues[a] += po_ * brValues[a];\n                }\n            }\n            // calculate best response strategy\n            int brAction = 0;\n            for (int a = 0; a < actionNum; ++a) {\n                if (actionValues[a] > actionValues[brAction]) {\n                    brAction = a;\n                }\n            }\n            bestResponseStrategies[infoSet] = std::vector<double>(actionNum, 0.0);\n            bestResponseStrategies[infoSet][brAction] = 1.0;\n        }\n        // calculate best response value\n        double utils[actionNum];\n        for (int a = 0; a < actionNum; ++a) {\n            auto game_cp(game);\n            game_cp.step(a);\n            utils[a] = CalculateBestResponseValue(game_cp, playerIndex, strategies, bestResponseStrategies, po, infoSets);\n        }\n        double bestResponseValue = 0.0;\n        for (int a = 0; a < actionNum; ++a) {\n            bestResponseValue += utils[a] * bestResponseStrategies.at(infoSet)[a];\n        }\n        return bestResponseValue;\n    } else {\n        // for each action, recursively calculate payoff with additional history and probability\n        double nodeUtil = 0.0;\n        for (int a = 0; a < actionNum; ++a) {\n            auto game_cp(game);\n            game_cp.step(a);\n            const double actionProb = strategies[player](game)[a];\n            nodeUtil += actionProb * CalculateBestResponseValue(game_cp, playerIndex, strategies, bestResponseStrategies, po * actionProb, infoSets);\n        }\n        return nodeUtil;\n    }\n}\n\n/// @brief Execute the CFR algorithm to compute an approximate Nash equilibrium\n/// @param iterations number of iterations of CFR\ntemplate <typename T>\nvoid Trainer<T>::train(const int iterations) {\n    double utils[mGame->playerNum()];\n\n    for (int i = 0; i < iterations; ++i) {\n        for (int p = 0; p < mGame->playerNum(); ++p) {\n            if (!mUpdate[p]) {\n                continue;\n            }\n            if (mModeStr == \"vanilla\") {\n                mGame->reset(false);\n                utils[p] = CFR(*mGame, p, 1.0, 1.0);\n                for (auto & itr : mNodeMap) {\n                    itr.second->updateStrategy();\n                }\n            } else {\n                mGame->reset();\n                if (mModeStr == \"chance\") {\n                    utils[p] = chanceSamplingCFR(*mGame, p, 1.0, 1.0);\n                    for (auto & itr : mNodeMap) {\n                        itr.second->updateStrategy();\n                    }\n                } else if (mModeStr == \"external\") {\n                    utils[p] = externalSamplingCFR(*mGame, p);\n                } else if (mModeStr == \"outcome\") {\n                    utils[p] = std::get<0>(outcomeSamplingCFR(*mGame, p, i, 1.0, 1.0, 1.0));\n                } else {\n                    assert(false);\n                }\n            }\n        }\n        if (i % 1000 == 0) {\n            std::cout << \"iteration:\" << i << \", cumulative nodes touched: \" << mNodeTouchedCnt << \", infosets num: \" << mNodeMap.size() << \", expected payoffs: (\";\n            for (int p = 0; p < mGame->playerNum(); ++p) {\n                std::cout << utils[p] << \",\";\n            }\n            std::cout << \")\" << std::endl;\n        }\n        if (i != 0 && i % 10000000 == 0) {\n            writeStrategyToBin(i);\n        }\n    }\n\n    writeStrategyToBin();\n}\n\n/// @brief Main procedure of vanilla CFR\n/// @param game game\n/// @param playerIndex player whose strategy is updated in the current iteration\n/// @param pi the probability of reaching the current game node if all players other than the acting player always choose actions leading to the current game node\n/// @param po the probability of reaching the current game node if the acting player always chooses actions leading to the current game node\n/// @return expected payoff of the specified player at the current game node\ntemplate <typename T>\ndouble Trainer<T>::CFR(const T &game, const int playerIndex, const double pi, const double po) {\n    ++mNodeTouchedCnt;\n\n    // return payoff for terminal states\n    if (game.done()) {\n        return game.payoff(playerIndex);\n    }\n\n    // chance node turn\n    const int actionNum = game.actionNum();\n    if (game.isChanceNode()) {\n        double nodeUtil = 0.0;\n        for (int a = 0; a < actionNum; ++a) {\n            auto game_cp(game);\n            game_cp.step(a);\n            const double chanceProbability = game_cp.chanceProbability();\n            nodeUtil += chanceProbability * CFR(game_cp, playerIndex, pi, po * chanceProbability);\n        }\n        return nodeUtil;\n    }\n\n    // get information set string representation\n    std::string infoSet = game.infoSetStr();\n\n    // treat static player as chance node\n    const int player = game.currentPlayer();\n    if (!mUpdate[player]) {\n        double nodeUtil = 0.0;\n        for (int a = 0; a < actionNum; ++a) {\n            auto game_cp(game);\n            game_cp.step(a);\n            const auto chanceProbability = double(mFixedStrategies[player].at(infoSet)->averageStrategy()[a]);\n            nodeUtil += chanceProbability * CFR(game_cp, playerIndex, pi, po * chanceProbability);\n        }\n        return nodeUtil;\n    }\n\n    // get information set node or create it if nonexistant\n    Node *node = mNodeMap[infoSet];\n    if (node == nullptr) {\n        node = new Node(actionNum);\n        mNodeMap[infoSet] = node;\n    }\n\n    // get current strategy through regret-matching\n    const double *strategy = node->strategy();\n\n    // for each action, recursively call CFR with additional history and probability\n    double utils[actionNum];\n    double nodeUtil = 0;\n    for (int a = 0; a < actionNum; ++a) {\n        auto game_cp(game);\n        game_cp.step(a);\n        if (player == playerIndex) {\n            utils[a] = CFR(game_cp, playerIndex, pi * strategy[a], po);\n        } else {\n            utils[a] = CFR(game_cp, playerIndex, pi, po * strategy[a]);\n        }\n        nodeUtil += strategy[a] * utils[a];\n    }\n\n    if (player == playerIndex) {\n        // for each action, compute and accumulate counterfactual regret\n        for (int a = 0; a < actionNum; ++a) {\n            const double regret = utils[a] - nodeUtil;\n            const double regretSum = node->regretSum(a) + po * regret;\n            node->regretSum(a, regretSum);\n        }\n        // update average strategy across all training iterations\n        node->strategySum(strategy, pi);\n    }\n\n    return nodeUtil;\n}\n\n/// @brief Main procedure of chance-sampling MCCFR\n/// @param game game\n/// @param playerIndex player whose strategy is updated in the current iteration\n/// @param pi the probability of reaching the current game node if all players other than the acting player always choose actions leading to the current game node\n/// @param po the probability of reaching the current game node if the acting player and the chance player always choose actions leading to the current game node\n/// @return estimated expected payoff of the specified player at the current game node\ntemplate <typename T>\ndouble Trainer<T>::chanceSamplingCFR(const T &game, const int playerIndex, const double pi, const double po) {\n    ++mNodeTouchedCnt;\n\n    // return payoff for terminal states\n    if (game.done()) {\n        return game.payoff(playerIndex);\n    }\n\n    // get information set string representation\n    std::string infoSet = game.infoSetStr();\n\n    // treat static player as chance node\n    const int actionNum = game.actionNum();\n    const int player = game.currentPlayer();\n    if (!mUpdate[player]) {\n        auto game_cp(game);\n        auto strategy = mFixedStrategies[player].at(infoSet)->averageStrategy();\n        std::discrete_distribution<int> dist(strategy, strategy + actionNum);\n        game_cp.step(dist(mEngine));\n        return chanceSamplingCFR(game_cp, playerIndex, pi, po);\n    }\n\n    // get information set node or create it if nonexistant\n    Node *node = mNodeMap[infoSet];\n    if (node == nullptr) {\n        node = new Node(actionNum);\n        mNodeMap[infoSet] = node;\n    }\n\n    // get current strategy through regret-matching\n    const double *strategy = node->strategy();\n\n    // for each action, recursively call cfr with additional history and probability\n    double utils[actionNum];\n    double nodeUtil = 0;\n    for (int a = 0; a < actionNum; ++a) {\n        auto game_cp(game);\n        game_cp.step(a);\n        if (player == playerIndex) {\n            utils[a] = chanceSamplingCFR(game_cp, playerIndex, pi * strategy[a], po);\n        } else {\n            utils[a] = chanceSamplingCFR(game_cp, playerIndex, pi, po * strategy[a]);\n        }\n        nodeUtil += strategy[a] * utils[a];\n    }\n\n    if (player == playerIndex) {\n        // for each action, compute and accumulate counterfactual regret\n        for (int a = 0; a < actionNum; ++a) {\n            const double regret = utils[a] - nodeUtil;\n            const double regretSum = node->regretSum(a) + po * regret;\n            node->regretSum(a, regretSum);\n        }\n        // update average strategy across all training iterations\n        node->strategySum(strategy, pi);\n    }\n\n    return nodeUtil;\n}\n\n/// @brief Main procedure of external-sampling MCCFR\n/// @param game game\n/// @param playerIndex player whose strategy is updated in the current iteration\n/// @return estimated expected payoff of the specified player at the current game node\ntemplate <typename T>\ndouble Trainer<T>::externalSamplingCFR(const T &game, const int playerIndex) {\n    ++mNodeTouchedCnt;\n\n    // return payoff for terminal states\n    if (game.done()) {\n        return game.payoff(playerIndex);\n    }\n\n    // get information set string representation\n    std::string infoSet = game.infoSetStr();\n\n    // external sampling with stochastically-weighted averaging cannot treat static player\n    const int actionNum = game.actionNum();\n    const int player = game.currentPlayer();\n    assert(mUpdate[player] && \"External sampling with stochastically-weighted averaging cannot treat static player.\");\n\n    // get information set node or create it if nonexistant\n    Node *node = mNodeMap[infoSet];\n    if (node == nullptr) {\n        node = new Node(actionNum);\n        mNodeMap[infoSet] = node;\n    }\n\n    // get current strategy through regret-matching\n    node->updateStrategy();\n    const double *strategy = node->strategy();\n\n    // if current player is not the target player, sample a single action and recursively call cfr\n    if (player != playerIndex) {\n        auto game_cp(game);\n        std::discrete_distribution<int> dist(strategy, strategy + actionNum);\n        game_cp.step(dist(mEngine));\n        const double util = externalSamplingCFR(game_cp, playerIndex);\n        // update average strategy\n        node->strategySum(strategy, 1.0);\n        return util;\n    }\n\n    // for each action, recursively call cfr with additional history and probability\n    double utils[actionNum];\n    double nodeUtil = 0;\n    for (int a = 0; a < actionNum; ++a) {\n        auto game_cp(game);\n        game_cp.step(a);\n        utils[a] = externalSamplingCFR(game_cp, playerIndex);\n        nodeUtil += strategy[a] * utils[a];\n    }\n\n    // for each action, compute and accumulate counterfactual regret\n    for (int a = 0; a < actionNum; ++a) {\n        const double regret = utils[a] - nodeUtil;\n        const double regretSum = node->regretSum(a) + regret;\n        node->regretSum(a, regretSum);\n    }\n\n    return nodeUtil;\n}\n\n/// @brief Main procedure of outcome-sampling MCCFR\n/// @param game game\n/// @param playerIndex player whose strategy is updated in the current iteration\n/// @param pi the probability of reaching the current game node if all players other than the acting player always choose actions leading to the current game node\n/// @param po the probability of reaching the current game node if the acting player and the chance player always choose actions leading to the current game node\n/// @param s the probability of reaching the current game node if the chance player always chooses actions leading to the current game node and the other players act according to the sample profile\n/// @return estimated expected payoff of the specified player at the current game node, and the probability of reaching the terminal game node if the chance player always chooses actions leading to the terminal game node\ntemplate <typename T>\nstd::tuple<double, double> Trainer<T>::outcomeSamplingCFR(const T &game, const int playerIndex, const int iteration , const double pi, const double po, const double s) {\n    ++mNodeTouchedCnt;\n\n    // return payoff for terminal states\n    if (game.done()) {\n        return std::make_tuple(game.payoff(playerIndex) / s, 1.0);\n    }\n\n    // get information set string representation\n    std::string infoSet = game.infoSetStr();\n\n    // outcome sampling with stochastically-weighted averaging cannot treat static player\n    const int actionNum = game.actionNum();\n    const int player = game.currentPlayer();\n    assert(mUpdate[player] && \"Outcome sampling with stochastically-weighted averaging cannot treat static player.\");\n\n    // get information set node or create it if nonexistant\n    Node *node = mNodeMap[infoSet];\n    if (node == nullptr) {\n        node = new Node(actionNum);\n        mNodeMap[infoSet] = node;\n    }\n\n    // get current strategy through regret-matching\n    node->updateStrategy();\n    const double *strategy = node->strategy();\n\n    // if current player is the target player, sample a single action according to epsilon-on-policy\n    // otherwise, sample a single action according to the player's strategy\n    const double epsilon = 0.6;\n    double probability[actionNum];\n    if (player == playerIndex) {\n        for (int a = 0; a < actionNum; ++a) {\n            probability[a] = (epsilon / (double) actionNum) + (1.0 - epsilon) * strategy[a];\n        }\n    } else {\n        for (int a = 0; a < actionNum; ++a) {\n            probability[a] = strategy[a];\n        }\n    }\n    std::discrete_distribution<int> dist(probability, probability + actionNum);\n    const int action = dist(mEngine);\n\n    // for sampled action, recursively call cfr with additional history and probability\n    double util, pTail;\n    auto game_cp(game);\n    game_cp.step(action);\n    const double newPi = pi * (player == playerIndex ? strategy[action] : 1.0);\n    const double newPo = po * (player == playerIndex ? 1.0 : strategy[action]);\n    std::tuple<double, double> ret = outcomeSamplingCFR(game_cp, playerIndex, iteration, newPi, newPo, s * probability[action]);\n    util = std::get<0>(ret);\n    pTail = std::get<1>(ret);\n    if (player == playerIndex) {\n        // for each action, compute and accumulate counterfactual regret\n        const double W = util * po;\n        for (int a = 0; a < actionNum; ++a) {\n            const double regret = a == action ? W * (1.0 - strategy[action]) * pTail : -W * pTail * strategy[action];\n            const double regretSum = node->regretSum(a) + regret;\n            node->regretSum(a, regretSum);\n        }\n    } else {\n        // update average strategy\n        node->strategySum(strategy, po / s);\n    }\n    return std::make_tuple(util, pTail * strategy[action]);\n}\n\n/// @brief Save the current average strategy as a binary file\n/// @param iteration current iteration\ntemplate <typename T>\nvoid Trainer<T>::writeStrategyToBin(const int iteration) const {\n    for (auto &itr : mNodeMap) {\n        for (char c : itr.first) {\n            std::cout << int(c);\n        }\n        std::cout << \":\";\n        for (int i = 0; i < itr.second->actionNum(); ++i) {\n            std::cout << itr.second->averageStrategy()[i] << \",\";\n        }\n        std::cout << std::endl;\n    }\n    std::string path = iteration > 0 ? \"strategy_\" + std::to_string(iteration)\n                                     : \"strategy\";\n    path += \"_\" + mModeStr + \".bin\";\n    std::ofstream ofs(mFolderPath + \"/\" + path);\n    boost::archive::binary_oarchive oa(ofs);\n    oa << mNodeMap;\n    ofs.close();\n}\n\n} // namespace\n\n", "meta": {"hexsha": "70e8588cb0d3b80303a51683165c8cddfff1a16e", "size": 25043, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RegretMinimization/Trainer/Trainer.cpp", "max_stars_repo_name": "bakanaouji/open-cfr", "max_stars_repo_head_hexsha": "36f9aebed39e39e33394a5e994c1366948074913", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-06T03:27:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-06T03:27:09.000Z", "max_issues_repo_path": "RegretMinimization/Trainer/Trainer.cpp", "max_issues_repo_name": "bakanaouji/open-cfr", "max_issues_repo_head_hexsha": "36f9aebed39e39e33394a5e994c1366948074913", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-01-06T02:52:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-06T23:09:43.000Z", "max_forks_repo_path": "RegretMinimization/Trainer/Trainer.cpp", "max_forks_repo_name": "bakanaouji/open-cfr", "max_forks_repo_head_hexsha": "36f9aebed39e39e33394a5e994c1366948074913", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0047923323, "max_line_length": 220, "alphanum_fraction": 0.61466278, "num_tokens": 5915, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.22601141084818577}}
{"text": "#ifndef JHMI_VOLUME_IMAGE_HPP_NRC20150429\n#define JHMI_VOLUME_IMAGE_HPP_NRC20150429\n\n#include \"cube.hpp\"\n#include \"range/v3/view.hpp\"\n#include \"range/v3/core.hpp\"\n#include \"range/v3/view_facade.hpp\"\n#include <boost/algorithm/string.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/iostreams/filtering_stream.hpp>\n#include <boost/iostreams/filter/zlib.hpp>\n#include <fmt/ostream.h>\n#include <fstream>\n\nnamespace jhmi {\n  namespace jhmi_detail {\n    template <typename T, typename P, typename V> class by_location_view;\n    inline std::string to_dtype(float) { return \"float32\"; }\n    inline std::string to_dtype(double) { return \"float64\"; }\n    inline std::string to_dtype(std::uint8_t) { return \"uint8\"; }\n    inline std::string to_dtype(std::uint32_t) { return \"uint32\"; }\n    inline std::string to_dtype(std::int32_t) { return \"int32\"; }\n    template <typename U, typename T>\n    inline std::string to_dtype(boost::units::quantity<U,T>) { return to_dtype(T{}); }\n  }\n\n  template <typename T>\n  class volume_image {\n    using reference = T&;\n    using const_reference = T const&;\n\n  public:\n    struct physical_pixel_ref {\n      physical_pixel_ref(m3 const& pp, int3 const&, reference v) : loc{pp}, value{v} {}\n      m3 const loc;\n      reference value;\n    };\n    struct image_pixel_ref {\n      image_pixel_ref(m3 const&, int3 const& ip, reference v) : loc{ip}, value{v} {}\n      int3 const loc;\n      reference value;\n    };\n    struct pixel_ref {\n      pixel_ref(m3 const& pp, int3 const& ip, reference v) : physical_loc{pp}, image_loc{ip}, value{v} {}\n      m3 const physical_loc;\n      int3 const image_loc;\n      reference value;\n    };\n    struct physical_pixel {\n      physical_pixel(m3 const& pp, int3 const&, const_reference v) : loc{pp}, value{v} {}\n      m3 const loc;\n      const_reference value;\n    };\n    struct image_pixel {\n      image_pixel(m3 const&, int3 const& ip, const_reference v) : loc{ip}, value{v} {}\n      int3 const loc;\n      const_reference value;\n    };\n    struct pixel {\n      pixel(m3 const& pp, int3 const& ip, const_reference v) : physical_loc{pp}, image_loc{ip}, value{v} {}\n      m3 const physical_loc;\n      int3 const image_loc;\n      const_reference value;\n    };\n\n    volume_image() = default;\n    volume_image(int3 const& size, cube<m3> const& physical_extents)\n      : physical_extents_(physical_extents),\n        w_(size.x), h_(size.y), d_(size.z),\n        volume_(new T[w_*h_*d_]()),//Note, we default initialize each element of volume_\n        half_pixel_sizes_{element_divide(jhmi::dimensions(physical_extents), 2. * size)}\n    {}\n\n    explicit volume_image(boost::filesystem::path const& filename) {\n      std::ifstream file(filename.string(), std::ios::binary);\n      if (!file.is_open()) {\n        throw std::runtime_error(fmt::format(\n          \"Invalid file \\\"{}\\\" provided to volume_image\", filename.string()));\n      }\n      boost::iostreams::filtering_istream in;\n      in.push(boost::iostreams::zlib_decompressor{});\n      in.push(file);\n      std::string line;\n      getline(in, line);\n      std::vector<std::string> e;\n      boost::split(e, line, boost::is_any_of(\" \"), boost::token_compress_on);\n      physical_extents_ = cube<m3>{dbl3{stod(e[0]), stod(e[1]), stod(e[2])}*mm,\n                                   dbl3{stod(e[3]), stod(e[4]), stod(e[5])}*mm};\n      getline(in, line);\n      w_ = stoi(line);\n      getline(in, line);\n      h_ = stoi(line);\n      getline(in, line);\n      d_ = stoi(line);\n      volume_.reset(new T[w_ * h_ * d_]);\n      getline(in, line);\n      if (line != jhmi_detail::to_dtype(T{})) {\n        throw std::invalid_argument(fmt::format(\n          \"Invalid attempt to construct {} from {}\", jhmi_detail::to_dtype(T()), line));\n      }\n      in.read(reinterpret_cast<char*>(volume_.get()), w_ * h_ * d_ * sizeof(T));\n      half_pixel_sizes_ = element_divide(\n        jhmi::dimensions(physical_extents_), 2. * int3{w_,h_,d_});\n    }\n\n    dbl3 to_index(m3 const& pt) const {\n      return dbl3(element_divide(\n        element_multiply(pt - physical_extents_.ul() - half_pixel_sizes_, dbl3(w_,h_,d_)),\n        jhmi::dimensions(physical_extents_)));\n    }\n\n    reference operator()(m3 const& pt) {\n      return (*this)(int3(to_index(pt)));\n    }\n    const_reference operator()(m3 const& pt) const {\n      return (*this)(int3(to_index(pt)));\n    }\n\n    reference operator()(int x, int y, int z) {\n      assert(x + y * w_ + z * w_ * h_ < w_ * h_ * d_);\n      return volume_[x + y * w_ + z * w_ * h_];\n    }\n    reference operator()(int3 const& pt) { return (*this)(pt.x, pt.y, pt.z); }\n    const_reference operator()(int x, int y, int z) const {\n      assert(x + y * w_ + z * w_ * h_ < w_ * h_ * d_);\n      return volume_[x + y * w_ + z * w_ * h_];\n    }\n    const_reference operator()(int3 const& pt) const { return (*this)(pt.x, pt.y, pt.z); }\n\n    //TODO: Is this returning a pointer to const?  I don't think so...\n    auto begin() const { return volume_.get(); }\n    auto begin() { return volume_.get(); }\n\n    auto end() const { return volume_.get() + w_ * h_ * d_; }\n    auto end() { return volume_.get() + w_ * h_ * d_; }\n\n    int width() const { return w_; }\n    int height() const { return h_; }\n    int depth() const { return d_; }\n\n    int3 dimensions() const { return {w_, h_, d_}; }\n\n    void write(boost::filesystem::path const& filename) const {\n      std::ofstream file{filename.string(), std::ios::binary};\n      boost::iostreams::filtering_ostream out;\n      out.push(boost::iostreams::zlib_compressor{});\n      out.push(file);\n      out << fmt::format(\"{} {} {} {} {} {}\\n{}\\n{}\\n{}\\n{}\\n\",\n        physical_extents_.ul().x.value()*1000,\n        physical_extents_.ul().y.value()*1000,\n        physical_extents_.ul().z.value()*1000,\n        physical_extents_.lr().x.value()*1000,\n        physical_extents_.lr().y.value()*1000,\n        physical_extents_.lr().z.value()*1000,\n        width(), height(), depth(), jhmi_detail::to_dtype(T()));\n      write_binary(out);\n    }\n\n  private:\n    template <typename Stream>\n    void write_binary(Stream& out) const {\n      out.write(reinterpret_cast<char const*>(volume_.get()),\n                w_ * h_ * d_ * sizeof(T));\n    }\n\n    template <typename U, typename P, typename V> friend class jhmi_detail::by_location_view;\n    friend cube<m3> extents(volume_image<T> const& v) {\n      return v.physical_extents_;\n    }\n    cube<m3> physical_extents_;\n    int w_, h_, d_;\n    std::unique_ptr<T[]> volume_;\n    m3 half_pixel_sizes_;\n  };\n\n  namespace jhmi_detail {\n  template <typename T, typename P, typename V>\n  class by_location_view : public ranges::view_facade<by_location_view<T,P,V>> {\n  public:\n    friend struct ranges::range_access;\n    V* img_;\n    m3 step_;\n    m3 center_;\n    struct cursor {\n      V* img_;\n      m3 mul_;\n      m3 step_;\n      int3 iul_;\n      int3 ilr_;\n      int3 ipt_;\n\n      cursor() = default;\n\n      bool equal(cursor const& other) const { return ipt_ == other.ipt_; }\n      auto read() const {\n        return P{mul_ + element_multiply(dbl3{ipt_}, step_), ipt_, (*img_)(ipt_)};\n      }\n      void next() {\n        if (++ipt_.x >= ilr_.x) {\n          ipt_.x = iul_.x;\n          if (++ipt_.y >= ilr_.y) {\n            ipt_.y = iul_.y;\n            ++ipt_.z;\n          }\n        }\n      }\n    };\n\n    cursor make_cursor(bool do_ul) const {\n      auto pe = img_->physical_extents_;\n      auto d = img_->dimensions();\n      int3 iul{0,0,0};\n      int3 iend{0,0,d.z};\n      auto ipt = do_ul ? iul : iend;\n\n      auto hstep = step_ / 2.;\n      auto mul = element_multiply(ceil(element_divide(pe.ul() - center_, hstep)), hstep) + center_;\n      return {img_, mul + hstep, step_, iul, d, ipt};\n    }\n\n  public:\n    cursor begin_cursor() const {\n      return make_cursor(true);\n    }\n    cursor end_cursor() const {\n      return make_cursor(false);\n    }\n\n    explicit by_location_view(V& img) : img_(&img),\n      step_(element_divide(dimensions(extents(img)), dbl3{img.dimensions()})),\n      center_{extents(img).ul() + step_ / 2.} {}\n    by_location_view(V& img, m3 const& step, m3 const& center)\n      : img_(&img), step_(step), center_{center} {}\n  };\n  }//jhmi_detail\n\n  template <typename T>\n  struct by_const_physical_location_view : jhmi_detail::by_location_view<T, typename volume_image<T>::physical_pixel, volume_image<T> const> {\n    using jhmi_detail::by_location_view<T, typename volume_image<T>::physical_pixel, volume_image<T> const>::by_location_view;\n  };\n  template <typename T>\n  struct by_physical_location_view : jhmi_detail::by_location_view<T, typename volume_image<T>::physical_pixel_ref, volume_image<T>> {\n    using jhmi_detail::by_location_view<T, typename volume_image<T>::physical_pixel_ref, volume_image<T>>::by_location_view;\n  };\n  template <typename T>\n  struct by_const_image_location_view : jhmi_detail::by_location_view<T, typename volume_image<T>::image_pixel, volume_image<T> const> {\n    using jhmi_detail::by_location_view<T, typename volume_image<T>::image_pixel, volume_image<T> const>::by_location_view;\n  };\n  template <typename T>\n  struct by_image_location_view : jhmi_detail::by_location_view<T, typename volume_image<T>::image_pixel_ref, volume_image<T>> {\n    using jhmi_detail::by_location_view<T, typename volume_image<T>::image_pixel_ref, volume_image<T>>::by_location_view;\n  };\n  template <typename T>\n  struct by_const_location_view : jhmi_detail::by_location_view<T, typename volume_image<T>::pixel, volume_image<T> const> {\n    using jhmi_detail::by_location_view<T, typename volume_image<T>::pixel, volume_image<T> const>::by_location_view;\n  };\n  template <typename T>\n  struct by_location_view : jhmi_detail::by_location_view<T, typename volume_image<T>::pixel_ref, volume_image<T>> {\n    using jhmi_detail::by_location_view<T, typename volume_image<T>::pixel_ref, volume_image<T>>::by_location_view;\n  };\n\n  namespace view {\n    struct by_physical_location_fn {\n      template <typename T> auto operator()(volume_image<T> const& img) const {\n        return by_const_physical_location_view<T>{img};\n      }\n      template <typename T> auto operator()(volume_image<T>& img) const {\n        return by_physical_location_view<T>{img};\n      }\n    };\n    template <typename T> auto operator|(T& img, by_physical_location_fn fn) {\n      return fn(img);\n    }\n    struct by_image_location_fn {\n      template <typename T> auto operator()(volume_image<T> const& img) const {\n        return by_const_image_location_view<T>{img};\n      }\n      template <typename T> auto operator()(volume_image<T>& img) const {\n        return by_image_location_view<T>{img};\n      }\n    };\n    template <typename T> auto operator|(T& img, by_image_location_fn fn) {\n      return fn(img);\n    }\n    struct by_location_fn {\n      template <typename T> auto operator()(volume_image<T> const& img) const {\n        return by_const_location_view<T>{img};\n      }\n      template <typename T> auto operator()(volume_image<T>& img) const {\n        return by_location_view<T>{img};\n      }\n    };\n    template <typename T> auto operator|(T& img, by_location_fn fn) {\n      return fn(img);\n    }\n    constexpr by_image_location_fn by_image_location{};\n    constexpr by_physical_location_fn by_physical_location{};\n    constexpr by_location_fn by_location{};\n\n    struct equal_step {\n      m step_;\n      m3 center_;\n      explicit equal_step(m step, m3 const& center = m3{}) : step_{step}, center_{center} {}\n      template <typename T> auto operator()(volume_image<T> const& img) const {\n        return by_const_location_view<T>(img, dbl3{1,1,1}*step_, center_);\n      }\n      template <typename T> auto operator()(volume_image<T>& img) const {\n        return by_location_view<T>(img, dbl3{1,1,1}*step_, center_);\n      }\n    };\n    template <typename T> auto operator|(T& img, equal_step fn) {\n      return fn(img);\n    }\n\n    struct x_slice {\n      int x1, x2, y, z;\n      x_slice(int x1, int x2, int y, int z) : x1(x1), x2(x2), y(y), z(z) {}\n\n      template <typename T> auto operator()(volume_image<T> const& img) const {\n        return ranges::make_iterator_range(&img(x1,y,z), &img(x2,y,z));\n      }\n      template <typename T> auto operator()(volume_image<T>& img) const {\n        return ranges::make_iterator_range(&img(x1,y,z), &img(x2,y,z));\n      }\n    };\n    template <typename T> auto operator|(T& img, x_slice fn) {\n      return fn(img);\n    }\n  }\n\n  template <typename T>\n  auto gaussian_filter(volume_image<T>& in, double sigma, int num_dev = 3) {\n    volume_image<double> out{in.dimensions(), extents(in)};\n    volume_image<double> tmp{in.dimensions(), extents(in)};\n    volume_image<double> tmp1{in.dimensions(), extents(in)};\n    int range = static_cast<int>(std::ceil(num_dev * sigma));\n    auto filter = ranges::view::closed_indices(-range, range)\n      | ranges::view::transform([&](int x) {\n           return /*1. / (sigma * 2.506628274) */ std::exp(-x*x/(2*sigma*sigma)); })\n      | ranges::to_vector;\n\n    auto ds = inflate(cube<int3>{int3{}, in.dimensions()}, -range*int3{1,1,1});\n    traverse(ds, 1, [&](int3 const& pt) {\n      for (int i = 0; i < filter.size(); ++i) {\n        auto new_pt = pt + int3{i-range,0,0};\n        tmp1(pt) += in(new_pt) * filter[i];\n      }\n    });\n    traverse(ds, 1, [&](int3 const& pt) {\n      for (int i = 0; i < filter.size(); ++i) {\n        auto new_pt = pt + int3{0,i-range,0};\n        tmp(pt) += tmp1(new_pt) * filter[i];\n      }\n    });\n    traverse(ds, 1, [&](int3 const& pt) {\n      for (int i = 0; i < filter.size(); ++i) {\n        auto new_pt = pt + int3{0,0,i-range};\n        out(pt) += tmp(new_pt) * filter[i];\n      }\n    });\n    return out;\n  }\n  template <typename T, typename U> auto convolve(\n      volume_image<T> const& lhs, volume_image<U> const& rhs) {\n    auto half_size = int3(ceil(rhs.dimensions() / 2.));\n    cube<int3> ds{int3{}, lhs.dimensions() - rhs.dimensions()};\n    using Out = decltype(T{} * U{});\n    volume_image<Out> out_img{lhs.dimensions(), extents(lhs)};\n    //Reverse rhs once, simplify calculations later.\n    auto kernel = rhs;\n    traverse(cube<int3>{int3{}, rhs.dimensions()}, 1, [&](int3 const& pt) {\n      kernel(rhs.dimensions() - int3{1,1,1} - pt) = rhs(pt);\n    });\n    traverse(ds, 1, [&](int3 const& ul) {\n      Out out;\n      traverse(cube<int3>{int3{}, kernel.dimensions()}, 1, [&](int3 const& pt) {\n        out += lhs(ul + pt) * kernel(pt);\n      });\n      out_img(ul+half_size) = out;\n    });\n    return out_img;\n  }\n  namespace jhmi_detail {\n    struct prev_type{}; static const constexpr prev_type prev{};\n    struct next_type{}; static const constexpr next_type next{};\n    struct Top {\n      int operator()() const { return 0; }\n      int operator()(prev_type) const { return 0; }\n      int operator()(next_type) const { return 1; }\n    };\n    struct Mid {\n      int v;\n      explicit Mid(int v) : v(v) {}\n      int operator()() const { return v; }\n      int operator()(prev_type) const { return v-1; }\n      int operator()(next_type) const { return v+1; }\n    };\n    struct Bottom {\n      int v;\n      explicit Bottom(int v) : v(v) {}\n      int operator()() const { return v; }\n      int operator()(prev_type) const { return v-1; }\n      int operator()(next_type) const { return v; }\n    };\n    template <typename T, typename U1, typename U2, typename F>\n    void traverse_x(F f, U1 y, U2 z, volume_image<T> const& in, volume_image<T>& out) {\n      out(0, y(), z()) = f(in(0, y(), z()), in(1, y(), z()),\n                           in(0, y(prev), z()), in(0, y(next), z()),\n                           in(0, y(), z(prev)), in(0, y(), z(next)));\n      auto l = in.width()-1;\n      for (int x = 1; x < l; ++x)\n        out(x, y(), z()) = f(in(x, y(), z()), in(x-1, y(), z()), in(x+1, y(), z()),\n                             in(x, y(prev), z()), in(x, y(next), z()),\n                             in(x, y(), z(prev)), in(x, y(), z(next)));\n      out(l, y(), z()) = f(in(l, y(), z()), in(l-1, y(), z()),\n                           in(l, y(prev), z()), in(l, y(next), z()),\n                           in(l, y(), z(prev)), in(l, y(), z(next)));\n    }\n    template <typename T, typename U1, typename F>\n    void traverse_y(F f, U1 z, volume_image<T> const& in, volume_image<T>& out) {\n      traverse_x(f, Top(), z, in, out);\n      for (int y = 1; y < in.height()-1; ++y)\n        traverse_x(f, Mid(y), z, in, out);\n      traverse_x(f, Bottom(in.height()-1), z, in, out);\n    }\n    template <typename T, typename F>\n    void traverse_z(F f, volume_image<T> const& in, volume_image<T>& out) {\n      traverse_y(f, Top(), in, out);\n      for (int z = 1; z < in.depth()-1; ++z)\n        traverse_y(f, Mid(z), in, out);\n      traverse_y(f, Bottom(in.depth()-1), in, out);\n    }\n  }//jhmi_detail\n  template <typename T> auto erode(volume_image<T> const& img) {\n    auto out = volume_image<T>{img.dimensions(), extents(img)};\n    jhmi_detail::traverse_z([](auto ...vals) { return std::min({vals...}); }, img, out);\n    return out;\n  }\n  template <typename T> auto dilate(volume_image<T> const& img) {\n    auto out = volume_image<T>{img.dimensions(), extents(img)};\n    jhmi_detail::traverse_z([](auto ...vals) { return std::max({vals...}); }, img, out);\n    return out;\n  }\n}\n\n#endif\n", "meta": {"hexsha": "5b2437f25fc9dd8feb4fe35815ece6fa3ea566d1", "size": 17172, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "utility/volume_image.hpp", "max_stars_repo_name": "ncrookston/liver_source", "max_stars_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utility/volume_image.hpp", "max_issues_repo_name": "ncrookston/liver_source", "max_issues_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utility/volume_image.hpp", "max_forks_repo_name": "ncrookston/liver_source", "max_forks_repo_head_hexsha": "9876ac4e9ea57d8e23767af9be061a9b10c6f1e5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4161073826, "max_line_length": 142, "alphanum_fraction": 0.6081993944, "num_tokens": 4726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.22593611250201553}}
{"text": "#include \"MBTB_JointR.hpp\"\n#include \"NewtonEulerJointR.hpp\"\n#include <boost/math/quaternion.hpp>\n#include \"op3x3.h\"\n#include \"RotationQuaternion.hpp\"\n//#define MBTB_JOINTR_DEBUG\n\nMBTB_JointR::MBTB_JointR()\n{\n  _M.reset(new SimpleMatrix(6,6));\n  _F.reset(new SiconosVector(6));\n}\n\n/*\n *\n *\n * ML_A_abs = M_FA_A + M_FB_A = F2/\\BA\n * the system is :\n * FL=F1+F2\n * F1.e0 = F2.e0\n * ML_A_abs . ei = F2 /\\ BA .ei for i=1,2\n *\n */\n\nvoid MBTB_JointR::computeEquivalentForces()\n{\n  if(!_G0C1)\n    return;\n  double q1=_ds1->q()->getValue(3);\n  double q2=_ds1->q()->getValue(4);\n  double q3=_ds1->q()->getValue(5);\n  double q4=_ds1->q()->getValue(6);\n  ::boost::math::quaternion<double>    quattrf(q1,q2,q3,q4);\n  ::boost::math::quaternion<double>    cquattrf(q1,-q2,-q3,-q4);\n  ::boost::math::quaternion<double>    quatbuff;\n  SP::SiconosVector Blambda=_jointR->contactForce();\n  SiconosVector FL(3);\n  FL.setValue(0,Blambda->getValue(0));\n  FL.setValue(1,Blambda->getValue(1));\n  FL.setValue(2,Blambda->getValue(2));\n\n  SiconosVector ML_G(3);\n  SiconosVector ML_G_abs(3);\n  ML_G.setValue(0,Blambda->getValue(3));\n  ML_G.setValue(1,Blambda->getValue(4));\n  ML_G.setValue(2,Blambda->getValue(5));\n  SP::SiconosVector spML_G_abs(new SiconosVector(3));\n  *spML_G_abs = ML_G;\n  changeFrameBodyToAbs(_ds1->q(),spML_G_abs);\n  ML_G_abs = * spML_G_abs;\n#ifdef MBTB_JOINTR_DEBUG\n  printf(\"MBTB_JointR::computeEquivalentForces Blambda\\n\");\n  Blambda->display();\n  printf(\"MBTB_JointR::computeEquivalentForces ML_G_abs (in abs frame):\\n\");\n  ML_G_abs.display();\n#endif\n\n  SiconosVector AB0(3);\n  AB0=(*_G0C2)-(*_G0C1);\n  ::boost::math::quaternion<double>    quatAB0(0,AB0.getValue(0),AB0.getValue(1),AB0.getValue(2));\n  quatbuff = quattrf*quatAB0*cquattrf;\n  SiconosVector AB(3);\n  AB.setValue(0,quatbuff.R_component_2());\n  AB.setValue(1,quatbuff.R_component_3());\n  AB.setValue(2,quatbuff.R_component_4());\n#ifdef MBTB_JOINTR_DEBUG\n  printf(\"MBTB_JointR::computeEquivalentForces AB0:\\n\");\n  AB0.display();\n  printf(\"MBTB_JointR::computeEquivalentForces AB:\\n\");\n  AB.display();\n#endif\n\n  ::boost::math::quaternion<double>    quatG0C1(0,_G0C1->getValue(0),_G0C1->getValue(1),_G0C1->getValue(2));\n  quatbuff = quattrf*quatG0C1*cquattrf;\n  SiconosVector GA(3);\n  GA.setValue(0,quatbuff.R_component_2());\n  GA.setValue(1,quatbuff.R_component_3());\n  GA.setValue(2,quatbuff.R_component_4());\n#ifdef MBTB_JOINTR_DEBUG\n  printf(\"MBTB_JointR::computeEquivalentForces GA:\\n\");\n  GA.display();\n#endif\n  SiconosVector ML_A_abs(3);\n  SiconosVector GA_FL(3);\n  cross_product(GA,FL,GA_FL);\n  ML_A_abs=ML_G_abs - GA_FL;\n#ifdef MBTB_JOINTR_DEBUG\n  printf(\"MBTB_JointR::computeEquivalentForces GA_FL:\\n\");\n  GA_FL.display();\n  printf(\"MBTB_JointR::computeEquivalentForces ML_A_abs :\\n\");\n  ML_A_abs.display();\n#endif\n  double normAB=1.0/AB.norm2();\n  double e0_x =normAB*AB.getValue(0);\n  double e0_y =normAB*AB.getValue(1);\n  double e0_z =normAB*AB.getValue(2);\n#ifdef MBTB_JOINTR_DEBUG\n  printf(\"MBTB_JointR::computeEquivalentForces e0_x . ML_A_abs (must be zero):%e\\n\",\n         e0_x*ML_A_abs.getValue(0)+e0_y*ML_A_abs.getValue(1)+e0_z*ML_A_abs.getValue(2));\n#endif\n  double  e1_x,e1_y,e1_z,e2_x,e2_y,e2_z;\n  int info = orthoBaseFromVector(&e0_x,&e0_y,&e0_z,&e1_x,&e1_y,&e1_z,&e2_x,&e2_y,&e2_z);\n  if(info)\n  {\n    std::cout << \"something wrong happened in  orthoBaseFromVector\"<<std::endl;\n  }\n  /*\n   * ML_A_abs = M_FA_A + M_FB_A = F2/\\BA\n   * the system is :\n   * FL=F1+F2\n   * F1.e0 = F2.e0\n   * ML_A_abs . ei = F2 /\\ BA .ei for i=1,2\n   *\n   */\n  /*Fill _M*/\n  _M->zero();\n  //FL= F1+F2.\n  _M->setValue(0,0,1);\n  _M->setValue(0,3,1);\n  _M->setValue(1,1,1);\n  _M->setValue(1,4,1);\n  _M->setValue(2,2,1);\n  _M->setValue(2,5,1);\n  /*F1.e0=F2.e0*/\n  _M->setValue(3,0,e0_x);\n  _M->setValue(3,1,e0_y);\n  _M->setValue(3,2,e0_z);\n  _M->setValue(3,3,-e0_x);\n  _M->setValue(3,4,-e0_y);\n  _M->setValue(3,5,-e0_z);\n\n  /*\n   *             F2x  BAx    F2y*BAz-F2z*BAy\n   * FB/\\BA . ei=F2y/\\BAy.ei=F2z*BAx-F2x*BAz .ei = F2x*(BAy *ei_z-BAz*ei_y)+F2y*(BAz*ei_x-BAx*ei_z)+F2z*(BAx*ei_y-BAy*ei_x)\n   *             F2z  BAz    F2x*BAy-F2y*BAx\n   *\n   */\n  _M->setValue(4,3,-AB.getValue(1) *e1_z+AB.getValue(2)*e1_y);\n  _M->setValue(4,4,-AB.getValue(2) *e1_x+AB.getValue(0)*e1_z);\n  _M->setValue(4,5,-AB.getValue(0) *e1_y+AB.getValue(1)*e1_x);\n\n  _M->setValue(5,3,-AB.getValue(1) *e2_z+AB.getValue(2)*e2_y);\n  _M->setValue(5,4,-AB.getValue(2) *e2_x+AB.getValue(0)*e2_z);\n  _M->setValue(5,5,-AB.getValue(0) *e2_y+AB.getValue(1)*e2_x);\n#ifdef MBTB_JOINTR_DEBUG\n  printf(\"MBTB_JointR::computeEquivalentForces the sytem M is:\\n\");\n  _M->display();\n#endif\n  _F->setValue(0,FL.getValue(0));\n  _F->setValue(1,FL.getValue(1));\n  _F->setValue(2,FL.getValue(2));\n  _F->setValue(3,0);\n  _F->setValue(4,e1_x * ML_A_abs.getValue(0) + e1_y * ML_A_abs.getValue(1) +e1_z * ML_A_abs.getValue(2));\n  _F->setValue(5,e2_x * ML_A_abs.getValue(0) + e2_y * ML_A_abs.getValue(1) +e2_z * ML_A_abs.getValue(2));\n#ifdef MBTB_JOINTR_DEBUG\n  printf(\"MBTB_JointR::computeEquivalentForces Mx=b, b:\");\n  _F->display();\n#endif\n\n  /*Solve the system.*/\n  try\n  {\n    _M->PLUFactorizationInPlace();\n    _M->PLUSolve(*_F);\n#ifdef MBTB_JOINTR_DEBUG\n    printf(\"MBTB_JointR::computeEquivalentForces Forces equivalent:\");\n    _F->display();\n    printf(\"MBTB_JointR::computeEquivalentForces checking ML_G_abs = MF1_G+MF2_G:\");\n    SiconosVector Maux1(3),Maux2(3),F1(3),F2(3),GC1(3),GC2(3),dif(3);\n    F1.setValue(0,_F->getValue(0));\n    F1.setValue(1,_F->getValue(1));\n    F1.setValue(2,_F->getValue(2));\n    F2.setValue(0,_F->getValue(3));\n    F2.setValue(1,_F->getValue(4));\n    F2.setValue(2,_F->getValue(5));\n    //FL=F1+F2\n    dif = FL-F1-F2;\n    printf(\"MBTB_JointR::computeEquivalentForces  FL-F1-F2(must be zero):\\n\");\n    dif.display();\n    //MF1_G=F1/\\C1G\n    cross_product(GA,F1,Maux1);\n    ::boost::math::quaternion<double>    quatG0C2(0,_G0C2->getValue(0),_G0C2->getValue(1),_G0C2->getValue(2));\n    quatbuff = quattrf*quatG0C2*cquattrf;\n    SiconosVector GB(3);\n    GB.setValue(0,quatbuff.R_component_2());\n    GB.setValue(1,quatbuff.R_component_3());\n    GB.setValue(2,quatbuff.R_component_4());\n    cross_product(GB,F2,Maux2);\n    dif=Maux1+Maux2;\n    printf(\"MBTB_JointR::computeEquivalentForces  momentum (must be ML_G_abs):\\n\");\n    dif.display();\n    dif=Maux1+Maux2 - ML_G_abs;\n    printf(\"MBTB_JointR::computeEquivalentForces  dif momentum(must be zero):\\n\");\n    dif.display();\n#endif\n  }\n  catch(const std::exception& e)\n  {\n    printf(\"MBTB_JointR: exception caught.\\n\");\n  }\n\n\n}\n", "meta": {"hexsha": "28f69b2d03bc9ca2cc843c173e243d687296a1ea", "size": 6517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mechanisms/src/MBTB/MBTB_JointR.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mechanisms/src/MBTB/MBTB_JointR.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mechanisms/src/MBTB/MBTB_JointR.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9460784314, "max_line_length": 123, "alphanum_fraction": 0.6746969464, "num_tokens": 2467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.2259361070165211}}
{"text": "#ifndef STAN_MATH_PRIM_SCAL_PROB_FRECHET_LPDF_HPP\n#define STAN_MATH_PRIM_SCAL_PROB_FRECHET_LPDF_HPP\n\n#include <boost/random/weibull_distribution.hpp>\n#include <boost/random/variate_generator.hpp>\n#include <stan/math/prim/scal/meta/operands_and_partials.hpp>\n#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>\n#include <stan/math/prim/scal/err/check_nonnegative.hpp>\n#include <stan/math/prim/scal/err/check_not_nan.hpp>\n#include <stan/math/prim/scal/err/check_positive.hpp>\n#include <stan/math/prim/scal/err/check_positive_finite.hpp>\n#include <stan/math/prim/scal/fun/size_zero.hpp>\n#include <stan/math/prim/scal/fun/log1m.hpp>\n#include <stan/math/prim/scal/fun/multiply_log.hpp>\n#include <stan/math/prim/scal/fun/value_of.hpp>\n#include <stan/math/prim/scal/meta/length.hpp>\n#include <stan/math/prim/scal/meta/is_constant_struct.hpp>\n#include <stan/math/prim/scal/meta/scalar_seq_view.hpp>\n#include <stan/math/prim/scal/meta/VectorBuilder.hpp>\n#include <stan/math/prim/scal/meta/partials_return_type.hpp>\n#include <stan/math/prim/scal/meta/return_type.hpp>\n#include <stan/math/prim/scal/fun/constants.hpp>\n#include <stan/math/prim/scal/meta/include_summand.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\n\n// Frechet(y|alpha, sigma)     [y > 0;  alpha > 0;  sigma > 0]\n// FIXME: document\ntemplate <bool propto, typename T_y, typename T_shape, typename T_scale>\ntypename return_type<T_y, T_shape, T_scale>::type frechet_lpdf(\n    const T_y& y, const T_shape& alpha, const T_scale& sigma) {\n  static const char* function = \"frechet_lpdf\";\n  typedef typename stan::partials_return_type<T_y, T_shape, T_scale>::type\n      T_partials_return;\n\n  using std::log;\n\n  if (size_zero(y, alpha, sigma))\n    return 0.0;\n\n  T_partials_return logp(0.0);\n  check_positive(function, \"Random variable\", y);\n  check_positive_finite(function, \"Shape parameter\", alpha);\n  check_positive_finite(function, \"Scale parameter\", sigma);\n  check_consistent_sizes(function, \"Random variable\", y, \"Shape parameter\",\n                         alpha, \"Scale parameter\", sigma);\n\n  if (!include_summand<propto, T_y, T_shape, T_scale>::value)\n    return 0.0;\n\n  scalar_seq_view<T_y> y_vec(y);\n  scalar_seq_view<T_shape> alpha_vec(alpha);\n  scalar_seq_view<T_scale> sigma_vec(sigma);\n  size_t N = max_size(y, alpha, sigma);\n\n  VectorBuilder<include_summand<propto, T_shape>::value, T_partials_return,\n                T_shape>\n      log_alpha(length(alpha));\n  for (size_t i = 0; i < length(alpha); i++)\n    if (include_summand<propto, T_shape>::value)\n      log_alpha[i] = log(value_of(alpha_vec[i]));\n\n  VectorBuilder<include_summand<propto, T_y, T_shape>::value, T_partials_return,\n                T_y>\n      log_y(length(y));\n  for (size_t i = 0; i < length(y); i++)\n    if (include_summand<propto, T_y, T_shape>::value)\n      log_y[i] = log(value_of(y_vec[i]));\n\n  VectorBuilder<include_summand<propto, T_shape, T_scale>::value,\n                T_partials_return, T_scale>\n      log_sigma(length(sigma));\n  for (size_t i = 0; i < length(sigma); i++)\n    if (include_summand<propto, T_shape, T_scale>::value)\n      log_sigma[i] = log(value_of(sigma_vec[i]));\n\n  VectorBuilder<include_summand<propto, T_y, T_shape, T_scale>::value,\n                T_partials_return, T_y>\n      inv_y(length(y));\n  for (size_t i = 0; i < length(y); i++)\n    if (include_summand<propto, T_y, T_shape, T_scale>::value)\n      inv_y[i] = 1.0 / value_of(y_vec[i]);\n\n  VectorBuilder<include_summand<propto, T_y, T_shape, T_scale>::value,\n                T_partials_return, T_y, T_shape, T_scale>\n      sigma_div_y_pow_alpha(N);\n  for (size_t i = 0; i < N; i++)\n    if (include_summand<propto, T_y, T_shape, T_scale>::value) {\n      const T_partials_return alpha_dbl = value_of(alpha_vec[i]);\n      sigma_div_y_pow_alpha[i]\n          = pow(inv_y[i] * value_of(sigma_vec[i]), alpha_dbl);\n    }\n\n  operands_and_partials<T_y, T_shape, T_scale> ops_partials(y, alpha, sigma);\n  for (size_t n = 0; n < N; n++) {\n    const T_partials_return alpha_dbl = value_of(alpha_vec[n]);\n    if (include_summand<propto, T_shape>::value)\n      logp += log_alpha[n];\n    if (include_summand<propto, T_y, T_shape>::value)\n      logp -= (alpha_dbl + 1.0) * log_y[n];\n    if (include_summand<propto, T_shape, T_scale>::value)\n      logp += alpha_dbl * log_sigma[n];\n    if (include_summand<propto, T_y, T_shape, T_scale>::value)\n      logp -= sigma_div_y_pow_alpha[n];\n\n    if (!is_constant_struct<T_y>::value) {\n      const T_partials_return inv_y_dbl = value_of(inv_y[n]);\n      ops_partials.edge1_.partials_[n]\n          += -(alpha_dbl + 1.0) * inv_y_dbl\n             + alpha_dbl * sigma_div_y_pow_alpha[n] * inv_y_dbl;\n    }\n    if (!is_constant_struct<T_shape>::value)\n      ops_partials.edge2_.partials_[n]\n          += 1.0 / alpha_dbl\n             + (1.0 - sigma_div_y_pow_alpha[n]) * (log_sigma[n] - log_y[n]);\n    if (!is_constant_struct<T_scale>::value)\n      ops_partials.edge3_.partials_[n] += alpha_dbl / value_of(sigma_vec[n])\n                                          * (1 - sigma_div_y_pow_alpha[n]);\n  }\n  return ops_partials.build(logp);\n}\n\ntemplate <typename T_y, typename T_shape, typename T_scale>\ninline typename return_type<T_y, T_shape, T_scale>::type frechet_lpdf(\n    const T_y& y, const T_shape& alpha, const T_scale& sigma) {\n  return frechet_lpdf<false>(y, alpha, sigma);\n}\n\n}  // namespace math\n}  // namespace stan\n#endif\n", "meta": {"hexsha": "0b1ab5e96ab9a081c739ac81de3319efc077d05e", "size": 5394, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/scal/prob/frechet_lpdf.hpp", "max_stars_repo_name": "jrmie/math", "max_stars_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/scal/prob/frechet_lpdf.hpp", "max_issues_repo_name": "jrmie/math", "max_issues_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/scal/prob/frechet_lpdf.hpp", "max_forks_repo_name": "jrmie/math", "max_forks_repo_head_hexsha": "2850ec262181075a5843968e805dc9ad1654e069", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.2537313433, "max_line_length": 80, "alphanum_fraction": 0.6928068224, "num_tokens": 1540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22593610416899762}}
{"text": "/**\n * Parrot Drones Awesome Video Viewer\n * Desktop application\n *\n * Copyright (c) 2018 Parrot Drones SAS\n * Copyright (c) 2016 Aurelien Barre\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *   * Neither the name of the copyright holders nor the names of its\n *     contributors may be used to endorse or promote products derived from\n *     this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <Eigen/Eigen>\n\n#include \"pdraw_desktop.h\"\n\n\nvoid pdraw_desktop_view_create_matrices(struct pdraw_desktop *self,\n\t\t\t\t\tunsigned int width,\n\t\t\t\t\tunsigned int height,\n\t\t\t\t\tfloat *view_mat,\n\t\t\t\t\tfloat *proj_mat,\n\t\t\t\t\tfloat near,\n\t\t\t\t\tfloat far)\n{\n\tfloat w = 1.f;\n\tfloat h = (float)width / (float)height;\n\tfloat a = (far + near) / (far - near);\n\tfloat b = -((2 * far * near) / (far - near));\n\n\tEigen::Matrix4f p_mat;\n\tp_mat << w, 0, 0, 0, 0, h, 0, 0, 0, 0, a, b, 0, 0, 1, 0;\n\n\tEigen::Matrix4f v_mat = Eigen::Matrix4f::Identity();\n\n\tunsigned int i, j;\n\tfor (i = 0; i < 4; i++) {\n\t\tfor (j = 0; j < 4; j++)\n\t\t\tview_mat[j * 4 + i] = v_mat(i, j);\n\t}\n\tfor (i = 0; i < 4; i++) {\n\t\tfor (j = 0; j < 4; j++)\n\t\t\tproj_mat[j * 4 + i] = p_mat(i, j);\n\t}\n}\n", "meta": {"hexsha": "3f01b0885726ffb25fe7b7ed9b6ebb9bb88258c0", "size": 2393, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "apps/pdraw_desktop/pdraw_desktop_view.cpp", "max_stars_repo_name": "Parrot-Developers/pdraw", "max_stars_repo_head_hexsha": "7d0983e88291d9224ec79be2bcf3ad045bb09044", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-05-06T17:01:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-18T08:59:42.000Z", "max_issues_repo_path": "apps/pdraw_desktop/pdraw_desktop_view.cpp", "max_issues_repo_name": "Parrot-Developers/pdraw", "max_issues_repo_head_hexsha": "7d0983e88291d9224ec79be2bcf3ad045bb09044", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-18T14:32:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-18T14:32:48.000Z", "max_forks_repo_path": "apps/pdraw_desktop/pdraw_desktop_view.cpp", "max_forks_repo_name": "Parrot-Developers/pdraw", "max_forks_repo_head_hexsha": "7d0983e88291d9224ec79be2bcf3ad045bb09044", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-07-18T19:35:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-14T13:41:33.000Z", "avg_line_length": 37.390625, "max_line_length": 80, "alphanum_fraction": 0.6974508985, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514763, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22590486564194934}}
{"text": "#include \"QAlg/QITE/QITE.h\"\n#include \"Core/QuantumMachine/QuantumMachineFactory.h\"\n#include <Eigen/Eigenvalues>\n\nQPANDA_BEGIN\n\nQITE::QITE()\n{\n}\n\nint QITE::exec()\n{\n    initEnvironment();\n    srand((int)time(0));\n\n    auto tmp_ansatz = m_ansatz;\n    for (int t = 0; t < m_upthrow_num; t++)\n    {\n        for (int i = 0; i < m_iter_num; i++)\n        {\n            calcParaA();\n            calcParaC();\n\n            Eigen::MatrixXd A_inverse = pseudoinverse(m_A);\n            Eigen::VectorXd theta_dot = -A_inverse * m_C;\n            double delta_k = m_delta_tau * pow(m_Q, i);\n            \n            for (int j = 0; j < m_theta_index_vec.size(); j++)\n            {\n                auto t_j = m_theta_index_vec[j];\n                double r = (rand() / double(RAND_MAX));\n                if (m_update_mode == UpdateMode::GD_VALUE)\n                {\n                    m_ansatz[t_j].theta += theta_dot[j];\n                }\n                else if(m_update_mode == UpdateMode::GD_DIRECTION)\n                {\n                    if (theta_dot[j] > 0)\n                    {\n                        m_ansatz[t_j].theta -= delta_k * r;\n                    }\n                    else\n                    {\n                        m_ansatz[t_j].theta += delta_k * r;\n                    }\n                }\n                else\n                {\n                    return -1;\n                }\n\n                int n_period = int(m_ansatz[t_j].theta / (2 * PI));\n                if (m_ansatz[t_j].theta < 0)\n                {\n                    m_ansatz[t_j].theta += (n_period + 1) * 2 * PI;\n                }\n                else\n                {\n                    m_ansatz[t_j].theta -= n_period * 2 * PI;\n                }\n            }\n\n            double tmp_exp = getExpectation(m_ansatz);\n            m_log_writer << tmp_exp << std::endl;\n\n            if (tmp_exp < m_expectation)\n            {\n                m_expectation = tmp_exp;\n                m_best_ansatz = m_ansatz;\n            }\n        }\n    }\n\n    std::fstream para_out;\n    para_out.open(m_log_file + \"_para.txt\", std::ios::out);\n    para_out << \"Last_para:\" << std::endl;\n    for (int i = 0; i < m_theta_index_vec.size(); i++)\n    {\n        para_out << m_ansatz[m_theta_index_vec[i]].theta << \", \";\n    }\n\n    para_out << std::endl << \"Best_para:\" << std::endl;\n    for (int i = 0; i < m_theta_index_vec.size(); i++)\n    {\n        para_out << m_best_ansatz[m_theta_index_vec[i]].theta << \", \";\n    }\n    para_out.close();\n    m_log_writer.close();\n\n    m_ansatz = tmp_ansatz;\n    //m_machine->Free_Qubits(m_qlist);\n\n    return 0;\n}\n\nprob_tuple QITE::getResult()\n{\n    QProg prog;\n    prog << constructCircuit(m_best_ansatz);\n    m_machine->directlyRun(prog);\n\n    auto temp = dynamic_cast<IdealMachineInterface*>(m_machine.get());\n    if (nullptr == temp)\n    {\n        QCERR(\"m_machine is not ideal machine\");\n        throw std::runtime_error(\"m_machine is not ideal machine\");\n    }\n    auto measure_qubits = m_qlist;\n    measure_qubits.pop_back();\n    auto result = temp->PMeasure(measure_qubits, -1);\n\n    std::fstream fout;\n    fout.open(m_log_file + \"_measure.txt\", std::ios::out);\n\n    std::cout << \"Measure result: \" << std::endl;\n    for (auto& i : result)\n    {\n        if (fabs(i.second) < 1e-4)\n        {\n            break;\n        }\n        std::cout << i.first << \" \" << i.second << std::endl;\n        fout << i.first << \" \" << i.second << std::endl;\n    }\n\n    fout.close();\n\n    return result;\n}\n\nvoid QITE::initEnvironment()\n{\n    if (!m_log_file.empty())\n    {\n        m_log_writer.open(m_log_file, std::ios::out);\n    }\n    else\n    {\n        m_log_writer.open(\"test.log\", std::ios::out);\n    }\n\n    m_machine.reset(QuantumMachineFactory::GetFactoryInstance()\n        .CreateByType(m_quantum_machine_type));\n    m_machine->init();\n\n    m_theta_index_vec.clear();\n    m_hamiltonian = m_pauli.toHamiltonian();\n    auto qubits_num = 0;\n    for (int i = 0; i < m_ansatz.size(); i++)\n    {\n        if (m_ansatz[i].target > qubits_num)\n        {\n            qubits_num = m_ansatz[i].target;\n        }\n\n        if (m_ansatz[i].control > qubits_num)\n        {\n            qubits_num = m_ansatz[i].control;\n        }\n\n        if (m_ansatz[i].type == AnsatzGateType::AGT_RX ||\n            m_ansatz[i].type == AnsatzGateType::AGT_RY ||\n            m_ansatz[i].type == AnsatzGateType::AGT_RZ)\n        {\n            m_theta_index_vec.push_back(i);\n        }\n    }\n    qubits_num++;\n\n    m_best_ansatz = m_ansatz;\n    m_qlist = m_machine->allocateQubits(qubits_num+1);\n    m_expectation = getExpectation(m_ansatz);\n}\n\ndouble QITE::getExpectation(const std::vector<AnsatzGate>& ansatz)\n{\n    QCircuit circuit = constructCircuit(ansatz);\n    double expectation = 0.0;\n    for (size_t i = 0; i < m_hamiltonian.size(); i++)\n    {\n        expectation += getExpectationOneTerm(circuit, m_hamiltonian[i]);\n    }\n\n    return expectation;\n}\n\ndouble QITE::getExpectationOneTerm( QCircuit c, const QHamiltonianItem& component)\n{\n    if (component.first.empty())\n    {\n        return component.second;\n    }\n\n    QProg prog;\n    prog << c;\n    \n    for (auto iter : component.first)\n    {\n        if (iter.second == 'X')\n        {\n            prog << H(m_qlist[iter.first]);\n        }\n        else if (iter.second == 'Y')\n        {\n            prog << RX(m_qlist[iter.first], PI / 2);\n        }\n    }\n\n    m_machine->directlyRun(prog);\n    double expectation = 0;\n\n    auto temp = dynamic_cast<IdealMachineInterface*>(m_machine.get());\n    if (nullptr == temp)\n    {\n        QCERR(\"m_machine is not ideal machine\");\n        throw std::runtime_error(\"m_machine is not ideal machine\");\n    }\n    auto measure_qubit = m_qlist;\n    measure_qubit.pop_back();\n    auto result = temp->PMeasure(measure_qubit, -1);\n\n    for (auto i = 0u; i < result.size(); i++)\n    {\n        if (ParityCheck(result[i].first, component.first))\n        {\n            expectation -= result[i].second;\n        }\n        else\n        {\n            expectation += result[i].second;\n        }\n    }\n\n    return expectation * component.second;\n}\n\nbool QITE::ParityCheck(size_t state, const QTerm& paulis) const\n{\n    size_t check = 0;\n    for (auto iter = paulis.begin(); iter != paulis.end(); iter++)\n    {\n        auto value = state >> iter->first;\n        if ((value % 2) == 1)\n        {\n            check++;\n        }\n    }\n\n    return 1 == check % 2;\n}\n\nvoid QITE::calcParaA()\n{\n    int theta_num = m_theta_index_vec.size();\n    m_A = Eigen::MatrixXd(theta_num, theta_num);\n    for (int i = 0; i < theta_num; i++)\n    {\n        for (int j = 0; j < theta_num; j++)\n        {\n            auto t_i = m_theta_index_vec[i];\n            auto t_j = m_theta_index_vec[j];\n            if (i > j)\n            {\n                m_A.row(i)[j] = m_A.row(j)[i];\n                continue;\n            }\n\n            int k = getAnsatzDerivativeParaNum(t_i);\n            int l = getAnsatzDerivativeParaNum(t_j);\n\n            double sum = 0;\n            for (int p = 0; p < k; p++)\n            {\n                for (int q = 0; q < l; q++)\n                {\n                    auto f_ik = getAnsatzDerivativePara(t_i, p);\n                    auto f_jl = getAnsatzDerivativePara(t_j, q);\n                    auto ff = complexDagger(f_ik) * f_jl;\n                    auto die_len = std::abs(ff);\n\n                    if ((i ==j) &&(p == q))\n                    {\n                        // Identity\n                        sum += die_len;\n                    }\n                    else\n                    {\n                        auto phase = std::arg(ff);\n                        auto value = calcSubCircuit(\n                            t_i,\n                            t_j,\n                            phase,\n                            getAnsatzDerivativeCircuit(t_i, p),\n                            getAnsatzDerivativeCircuit(t_j, q));\n\n                        sum += die_len * value;\n                    }\n                }\n            }\n\n            m_A.row(i)[j] = sum;\n        }\n    }\n}\n\nvoid QITE::calcParaC()\n{\n    int theta_num = m_theta_index_vec.size();\n    m_C = Eigen::VectorXd(theta_num);\n    for (int i = 0; i < theta_num; i++)\n    {\n        auto t_i = m_theta_index_vec[i];\n        double sum = 0;\n        int k = getAnsatzDerivativeParaNum(t_i);\n        int l = getHamiltonianItemNum();\n        for (int p = 0; p < k; p++)\n        {\n            for (int q = 0; q < l; q++)\n            {\n                auto f_ik = getAnsatzDerivativePara(t_i, p);\n                auto f_l = getHamiltonianItemPara(q);\n                auto ff = complexDagger(f_ik) * f_l;\n                auto die_len = std::abs(ff);\n                auto phase = std::arg(ff);\n\n                auto value = calcSubCircuit(\n                    t_i,\n                    m_ansatz.size(),\n                    phase,\n                    getAnsatzDerivativeCircuit(t_i, p),\n                    getHamiltonianItemCircuit(q));\n\n                sum += die_len * value;\n            }\n        }\n        m_C[i] = sum;\n    }\n    m_C *= -1;\n}\n\nQCircuit QITE::constructCircuit(const std::vector<AnsatzGate>& ansatz)\n{\n    QCircuit circuit;\n    for (int i = 0; i < ansatz.size(); i++)\n    {\n        circuit << convertAnsatzToCircuit(ansatz[i]);\n    }\n\n    return circuit;\n}\n\nstd::complex<double> QITE::complexDagger(std::complex<double>& value)\n{\n    return std::complex<double>(value.real(), -value.imag());\n}\n\nint QITE::getAnsatzDerivativeParaNum(int i)\n{\n    if (i < 0 ||\n        i >= m_ansatz.size())\n    {\n        QCERR_AND_THROW_ERRSTR(std::runtime_error, \n            \"bad para of i in getAnsatzDerivativeParaNum\");\n    }\n\n    auto& u = m_ansatz[i];\n\n    return u.control == -1 ? 1 : 2;\n}\n\nint QITE::getHamiltonianItemNum()\n{\n    return m_hamiltonian.size();\n}\n\nstd::complex<double> QITE::getAnsatzDerivativePara(int i, int cnt)\n{\n    if (i < 0 ||\n        i >= m_ansatz.size())\n    {\n        QCERR_AND_THROW_ERRSTR(std::runtime_error,\n            \"bad para of i in getAnsatzDerivativePara\");\n    }\n\n    auto& u = m_ansatz[i];\n\n    if (u.control != -1)\n    {\n        if (cnt < 0 ||\n            cnt > 1)\n        {\n            QCERR_AND_THROW_ERRSTR(std::runtime_error,\n                \"bad para of cnt in getAnsatzDerivativePara\");\n        }\n\n        return cnt == 0 ? std::complex<double>(0, -0.25) :\n            std::complex<double>(0, 0.25);\n    }\n    else\n    {\n        if (cnt != 0)\n        {\n            QCERR_AND_THROW_ERRSTR(std::runtime_error,\n                \"bad para of cnt in getAnsatzDerivativePara\");\n        }\n\n        return std::complex<double>(0, -0.5);\n    }\n}\n\ndouble QITE::getHamiltonianItemPara(int i)\n{\n    if (i < 0 ||\n        i >= m_hamiltonian.size())\n    {\n        QCERR_AND_THROW_ERRSTR(std::runtime_error,\n            \"bad para of i in getHamiltonianItemPara\");\n    }\n\n    return m_hamiltonian[i].second;\n}\n\nQCircuit QITE::getAnsatzDerivativeCircuit(int i, int cnt)\n{\n    if (i < 0 ||\n        i >= m_ansatz.size())\n    {\n        QCERR_AND_THROW_ERRSTR(std::runtime_error,\n            \"bad para of i in getAnsatzDerivativePara\");\n    }\n\n    QCircuit sub_cir;\n    int anc = m_qlist.size() - 1;\n\n    auto& u = m_ansatz[i];\n\n    if (u.control != -1)\n    {\n        if (cnt < 0 ||\n            cnt > 1)\n        {\n            QCERR_AND_THROW_ERRSTR(std::runtime_error,\n                \"bad para of cnt in getAnsatzDerivativePara\");\n        }\n\n        sub_cir << (cnt == 0 ? I(m_qlist[u.control]) : Z(m_qlist[u.control]));\n    }\n\n    switch (u.type)\n    {\n    case AnsatzGateType::AGT_RX:\n        sub_cir << X(m_qlist[u.target]);\n        break;\n    case AnsatzGateType::AGT_RY:\n        sub_cir << Y(m_qlist[u.target]);\n        break;\n    case AnsatzGateType::AGT_RZ:\n        sub_cir << Z(m_qlist[u.target]);\n        break;\n    }\n\n    return sub_cir.control({ m_qlist[anc] });\n}\n\nQCircuit QITE::getHamiltonianItemCircuit(int cnt)\n{\n    if (cnt < 0 ||\n        cnt >= m_hamiltonian.size())\n    {\n        QCERR_AND_THROW_ERRSTR(std::runtime_error,\n            \"bad para of cnt in getHamiltonianItemPara\");\n    }\n\n    QCircuit cir;\n    auto term = m_hamiltonian[cnt].first;\n\n    for (auto& iter : term)\n    {\n        switch (iter.second)\n        {\n        case 'X':\n            cir << X(m_qlist[iter.first]);\n            break;\n        case 'Y':\n            cir << Y(m_qlist[iter.first]);\n            break;\n        case 'Z':\n            cir << Z(m_qlist[iter.first]);\n            break;\n        default:\n            cir << I(m_qlist[iter.first]);\n            break;\n        }\n    }\n\n    return cir.control({ m_qlist[m_qlist.size() - 1] });\n}\n\ndouble QITE::calcSubCircuit(\n    int index1, \n    int index2, \n    double theta, \n    QCircuit cir1, \n    QCircuit cir2)\n{\n    auto anc_quibit = m_qlist[m_qlist.size() - 1];\n\n    QProg prog;\n    for (int i = 0; i < index1; i++)\n    {\n        prog << convertAnsatzToCircuit(m_ansatz[i]);\n    }\n\n    prog << H(anc_quibit)\n        << U1(anc_quibit, theta)\n        << X(anc_quibit)\n        << cir1\n        << X(anc_quibit);\n\n    for (int i = index1; i < index2; i++)\n    {\n        prog << convertAnsatzToCircuit(m_ansatz[i]);\n    }\n\n    prog << cir2\n        << H(anc_quibit);\n\n    auto temp = dynamic_cast<IdealMachineInterface*>(m_machine.get());\n    auto result = temp->probRunDict(prog, { anc_quibit }, -1);\n\n    return 2 * result[\"0\"] - 1;\n}\n\nQCircuit QITE::convertAnsatzToCircuit(const AnsatzGate& u)\n{\n    if (u.target < 0 || u.target >= m_qlist.size())\n    {\n        QCERR_AND_THROW_ERRSTR(std::runtime_error,\n            \"bad para of target in convertAnsatzToCircuit\");\n    }\n\n    QCircuit sub_cir;\n    switch (u.type)\n    {\n    case AnsatzGateType::AGT_NOT:\n        sub_cir << X(m_qlist[u.target]);\n        break;\n    case AnsatzGateType::AGT_H:\n        sub_cir << H(m_qlist[u.target]);\n        break;\n    case AnsatzGateType::AGT_RX:\n        sub_cir << RX(m_qlist[u.target], u.theta);\n        break;\n    case AnsatzGateType::AGT_RY:\n        sub_cir << RY(m_qlist[u.target], u.theta);\n        break;\n    case AnsatzGateType::AGT_RZ:\n        sub_cir << RZ(m_qlist[u.target], u.theta);\n        break;\n    default:\n        break;\n    }\n\n    if (u.control != -1)\n    {\n        sub_cir.setControl({ m_qlist[u.control] });\n    }\n\n    return sub_cir;\n}\n\nEigen::MatrixXd QITE::pseudoinverse(Eigen::MatrixXd matrix)\n{\n    auto svd = matrix.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n    const auto& singularValues = svd.singularValues();\n    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> \n        singularValuesInv(matrix.cols(), matrix.rows());\n    singularValuesInv.setZero();\n    double  pinvtoler = m_arbitary_cofficient;\n    for (unsigned int i = 0; i < singularValues.size(); ++i) {\n        if (singularValues(i) > pinvtoler)\n            singularValuesInv(i, i) = 1.0 / singularValues(i);\n        else\n            singularValuesInv(i, i) = 0.0;\n    }\n    Eigen::MatrixXd pinvmat = \n        svd.matrixV() * singularValuesInv * svd.matrixU().transpose();\n\n    return pinvmat;\n}\n\nprob_tuple qite(\n    const PauliOperator& h, \n    const std::vector<AnsatzGate>& ansatz_gate, \n    size_t iter_num, \n    std::string log_file,\n    QITE::UpdateMode mode, \n    size_t up_throw_num, \n    double delta_tau, \n    double convergence_factor_Q, \n    double arbitary_cofficient, \n    QMachineType type)\n{\n    QITE alg;\n    alg.setHamiltonian(h);\n    alg.setAnsatzGate(ansatz_gate);\n    alg.setIterNum(iter_num);\n    alg.setLogFile(log_file);\n    alg.setParaUpdateMode(mode);\n    alg.setUpthrowNum(up_throw_num);\n    alg.setDeltaTau(delta_tau);\n    alg.setConvergenceFactorQ(convergence_factor_Q);\n    alg.setArbitaryCofficient(arbitary_cofficient);\n    alg.setQuantumMachineType(type);\n\n    if (alg.exec() != 0)\n    {\n        return prob_tuple();\n    }\n\n    return alg.getResult();\n}\n\nQPANDA_END\n", "meta": {"hexsha": "c784593ca393b2b12263cc0625f83a35d3343913", "size": 15757, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QAlg/QITE/QITE.cpp", "max_stars_repo_name": "QianJianhua1/QPanda-2", "max_stars_repo_head_hexsha": "a13c7b733031b1d0007dceaf1dae6ad447bb969c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 631.0, "max_stars_repo_stars_event_min_datetime": "2019-01-21T01:33:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:33:04.000Z", "max_issues_repo_path": "QAlg/QITE/QITE.cpp", "max_issues_repo_name": "yinxx/QPanda-2", "max_issues_repo_head_hexsha": "c70c4117a90978916b871424e204c5159f645642", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2019-02-01T10:12:45.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-02T01:49:57.000Z", "max_forks_repo_path": "QAlg/QITE/QITE.cpp", "max_forks_repo_name": "yinxx/QPanda-2", "max_forks_repo_head_hexsha": "c70c4117a90978916b871424e204c5159f645642", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 80.0, "max_forks_repo_forks_event_min_datetime": "2019-01-21T03:04:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T15:38:45.000Z", "avg_line_length": 25.2112, "max_line_length": 82, "alphanum_fraction": 0.522688329, "num_tokens": 4222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.22590486000420423}}
{"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-2013.\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: Alexandra Zerck $\n// $Authors: $\n// --------------------------------------------------------------------------\n//\n\n#include <boost/math/special_functions/acosh.hpp>\n\n#include <OpenMS/TRANSFORMATIONS/RAW2PEAK/OptimizePeakDeconvolution.h>\n#include <OpenMS/MATH/MISC/MathFunctions.h>\n#include <OpenMS/DATASTRUCTURES/ListUtils.h>\n#include <limits>\n#include <boost/math/special_functions/fpclassify.hpp>\n\n#ifdef DEBUG_DECONV\n#include <iostream>\n#include <fstream>\n#endif\n\nnamespace OpenMS\n{\n\n\n  const DoubleReal OptimizePeakDeconvolution::dist_ = 1.003;\n  namespace OptimizationFunctions\n  {\n    // Evaluation of the target function for nonlinear optimization.\n    Int residualDC(const gsl_vector * x, void * params, gsl_vector * f)\n    {\n      // According to the gsl conventions, x contains the parameters to be optimized.\n      // The first two entries are the left and right width, respectively.They are equal\n      // for all peaks. Then the height and position of all peaks are stored.\n      //\n      // Params might contain any additional parameters. We handle these using class members\n      // instead.\n      // The vector f is supposed to contain the result when we return from this function.\n      // Note: GSL wants the values for each data point i as one component of the results vector\n      std::vector<DoubleReal> & signal = static_cast<OptimizePeakDeconvolution::Data *>(params)->signal;\n      std::vector<DoubleReal> & positions = static_cast<OptimizePeakDeconvolution::Data *>(params)->positions;\n      std::vector<PeakShape> & peaks = static_cast<OptimizePeakDeconvolution::Data *>(params)->peaks;\n      OptimizationFunctions::PenaltyFactorsIntensity & penalties = static_cast<OptimizePeakDeconvolution::Data *>(params)->penalties;\n      Int charge = static_cast<OptimizePeakDeconvolution::Data *>(params)->charge;\n      DoubleReal leftwidth = gsl_vector_get(x, 0);\n      DoubleReal rightwidth = gsl_vector_get(x, 1);\n      //DoubleReal posP1 = gsl_vector_get(x,2);\n\n      // iterate over all points of the signal\n      for (Size current_point = 0; current_point < positions.size(); current_point++)\n      {\n        DoubleReal computed_signal     = 0.;\n        DoubleReal current_position    = positions[current_point];\n        DoubleReal experimental_signal = signal[current_point];\n\n        //iterate over all peaks\n        for (Size current_peak = 0; current_peak < peaks.size(); current_peak++)\n        {\n          //Store the current parameters for this peak\n          DoubleReal p_height        = gsl_vector_get(x, 2 + 2 * current_peak);\n          DoubleReal p_position    = gsl_vector_get(x, 2 + 2 * current_peak + 1);\n          DoubleReal p_width         = (current_position <= p_position) ? leftwidth : rightwidth;\n\n          //is it a Lorentz or a Sech - Peak?\n          if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n          {\n            computed_signal += p_height / (1. + pow(p_width * (current_position - p_position), 2));\n          }\n          else                   // It's a Sech - Peak\n          {\n            computed_signal += p_height / pow(cosh(p_width * (current_position - p_position)), 2);\n          }\n        }\n        gsl_vector_set(f, current_point, computed_signal - experimental_signal);\n      }\n\n      // penalties : especially negative heights have to be penalised\n      DoubleReal penalty = 0.;\n\n      DoubleReal penalty_pos    = penalties.pos;\n      DoubleReal penalty_lwidth = penalties.lWidth;\n      DoubleReal penalty_rwidth = penalties.rWidth;\n      DoubleReal penalty_intensity = penalties.height;\n\n\n      //iterate over all peaks again to compute the penalties\n      for (Size current_peak = 0; current_peak < peaks.size(); current_peak++)\n      {\n        DoubleReal p_position = gsl_vector_get(x, 2 + 2 * current_peak + 1);\n        if (current_peak < peaks.size() - 1)\n        {\n\n          DoubleReal next_p_position  = gsl_vector_get(x, 2 + 2 * current_peak + 3);\n          // if distance between peaks does not match the peptide mass rule\n          if (fabs(fabs(p_position - next_p_position) - 1.003 / charge) > 0.05)\n          {\n            // penalize it\n            penalty +=  penalty_pos * 10000\n                       * pow(fabs(fabs(p_position - next_p_position) - 1.003 / charge), 2);\n          }\n        }\n        DoubleReal old_position   = peaks[current_peak].mz_position;\n        DoubleReal old_width_l  = peaks[current_peak].left_width;\n        DoubleReal old_width_r    = peaks[current_peak].right_width;\n        DoubleReal old_height    = peaks[current_peak].height;\n\n        DoubleReal p_width_l    = gsl_vector_get(x, 0);\n        DoubleReal p_width_r    = gsl_vector_get(x, 1);\n        DoubleReal p_height     = gsl_vector_get(x, 2 + 2 * current_peak);\n\n        if (p_height <  1)\n        {\n          penalty += 100000 * penalty_intensity * pow(fabs(p_height - old_height), 2);\n\n        }\n        if (p_width_l < 0)\n        {\n          penalty += penalty_lwidth * peaks.size() * 10000 * pow(fabs(p_width_l - old_width_l), 2);\n        }\n        else if (p_width_l < 1.5)\n          penalty += 10000 * pow(fabs(p_width_l - old_width_l), 2);\n        if (p_width_r < 0)\n        {\n          penalty += penalty_rwidth * peaks.size() * 10000 * pow(fabs(p_width_r - old_width_r), 2);\n        }\n        else if (p_width_r < 1.5)\n          penalty += 10000 * pow(fabs(p_width_r - old_width_r), 2);\n        if (fabs(old_position - p_position) > 0.1)\n        {\n          penalty += 10000 * penalty_pos * pow(fabs(old_position - p_position), 2);\n        }\n\n\n\n      }\n      gsl_vector_set(f, f->size - 1, penalty);\n      return GSL_SUCCESS;\n    }\n\n    /** Compute the Jacobian of the residual, where each row of the matrix corresponds to a\n     *  point in the data.\n     */\n    Int jacobianDC(const gsl_vector * x, void * params, gsl_matrix * J)\n    {\n      // For the conventions on x and params c.f. the commentary in residual()\n      //\n      // The matrix J is supposed to contain the result when we return from this function.\n      // Note: GSL expects the Jacobian as follows:\n      //                    - each row corresponds to one data point\n      //                    - each column corresponds to one parameter\n\n      std::vector<DoubleReal> & positions = static_cast<OptimizePeakDeconvolution::Data *>(params)->positions;\n      std::vector<PeakShape> & peaks = static_cast<OptimizePeakDeconvolution::Data *>(params)->peaks;\n      OptimizationFunctions::PenaltyFactorsIntensity & penalties = static_cast<OptimizePeakDeconvolution::Data *>(params)->penalties;\n      Int charge = static_cast<OptimizePeakDeconvolution::Data *>(params)->charge;\n\n      DoubleReal leftwidth = gsl_vector_get(x, 0);\n      DoubleReal rightwidth = gsl_vector_get(x, 1);\n\n\n      gsl_matrix_set_zero(J);\n\n\n      // iterate over all points of the signal\n      for (Size current_point = 0; current_point < positions.size(); current_point++)\n      {\n        DoubleReal current_position    = positions[current_point];\n\n        // iterate over all peaks\n        for (Size current_peak = 0; current_peak < peaks.size(); current_peak++)\n        {\n\n\n          //Store the current parameters for this peak\n          DoubleReal p_height        = gsl_vector_get(x, 2 + 2 * current_peak);\n          DoubleReal p_position    = gsl_vector_get(x, 2 + 2 * current_peak + 1);\n          DoubleReal p_width          = (current_position <= p_position) ? leftwidth : rightwidth;\n\n          //is it a Lorentz or a Sech - Peak?\n          if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n          {\n            DoubleReal diff      = current_position - p_position;\n            DoubleReal denom_inv = 1. / (1. + pow(p_width * diff, 2));\n\n            DoubleReal ddl_left  = (current_position <= p_position)\n                                   ? -2 * p_height * pow(diff, 2) * p_width * pow(denom_inv, 2) :\n                                     0;\n\n            DoubleReal ddl_right = (current_position  > p_position)\n                                   ? -2 * p_height * pow(diff, 2) * p_width * pow(denom_inv, 2) :\n                                     0;\n\n            // left and right width are the same for all peaks,\n            // the sums of the derivations over all peaks are stored in the first two columns\n            gsl_matrix_set(J, current_point, 0, gsl_matrix_get(J, current_point, 0) + ddl_left);\n            gsl_matrix_set(J, current_point, 1, gsl_matrix_get(J, current_point, 1) + ddl_right);\n\n            DoubleReal ddx0    = 2 * p_height * pow(p_width, 2) * diff * pow(denom_inv, 2);\n\n            // partial derivation with respect to intensity\n            gsl_matrix_set(J, current_point, 2 + 2 * current_peak, denom_inv);\n\n            // partial derivation with respect to the mz-position\n            gsl_matrix_set(J, current_point, 2 + 2 * current_peak + 1, ddx0);\n          }\n          else                   // It's a Sech - Peak\n          {\n            DoubleReal diff      = current_position - p_position;\n            DoubleReal denom_inv = 1. / cosh(p_width * diff);\n\n            // The remaining computations are not stable if denom_inv == 0. In that case, we are far away from the peak\n            // and can assume that all derivatives vanish\n            DoubleReal sinh_term = (fabs(denom_inv) < 1e-6) ? 0.0 : sinh(p_width * diff);\n\n\n            DoubleReal ddl_left  = (current_position <= p_position)\n                                   ? -2 * p_height * sinh_term * diff * pow(denom_inv, 3) :\n                                     0;\n            DoubleReal ddl_right = (current_position  > p_position)\n                                   ? -2 * p_height * sinh_term * diff * pow(denom_inv, 3) :\n                                     0;\n\n            gsl_matrix_set(J, current_point, 0, gsl_matrix_get(J, current_point, 0) + ddl_left);\n            gsl_matrix_set(J, current_point, 1, gsl_matrix_get(J, current_point, 1) + ddl_right);\n\n            DoubleReal ddx0      = 2 * p_height * p_width * sinh_term * pow(denom_inv, 3);\n\n            gsl_matrix_set(J, current_point, 2 + 2 * current_peak, pow(denom_inv, 2));\n            gsl_matrix_set(J, current_point, 2 + 2 * current_peak + 1, ddx0);\n          }\n        }\n      }\n\n\n      /** Now iterate over all peaks again to compute the\n       *  penalties.\n       */\n\n      for (Size current_peak = 0; current_peak < peaks.size(); current_peak++)\n      {\n\n\n        DoubleReal penalty_p = 0;\n        DoubleReal p_position = gsl_vector_get(x, 2 + 2 * current_peak + 1);\n        if (current_peak < peaks.size() - 1)\n        {\n\n          DoubleReal next_p_position  = gsl_vector_get(x, 2 + 2 * current_peak + 3);\n          // if distance between peaks does not match the peptide mass rule\n          if (fabs(fabs(p_position - next_p_position) - 1.003 / charge) > 0.05)\n          {\n            // penalize it\n            penalty_p += penalties.pos * 20000\n                         * fabs(fabs(p_position - next_p_position) - 1.003 / charge);\n\n          }\n        }\n        //  std::cout << \"penalty_p \"<<penalty_p<<std::endl;\n        DoubleReal p_width_left = gsl_vector_get(x, 0);\n        DoubleReal p_width_right = gsl_vector_get(x, 1);\n        DoubleReal p_height   = gsl_vector_get(x, 2 + 2 * current_peak);\n\n        DoubleReal old_position    = peaks[current_peak].mz_position;\n        DoubleReal old_width_left  = peaks[current_peak].left_width;\n        DoubleReal old_width_right = peaks[current_peak].right_width;\n        DoubleReal old_height      = peaks[current_peak].height;\n\n        DoubleReal penalty_h = 0., penalty_l = 0., penalty_r = 0.;\n        if (p_height < 1)\n        {\n          penalty_h += 100000 * 2 * penalties.height * (fabs(p_height) - fabs(old_height));\n        }\n\n        if (p_width_left < 0)\n        {\n          penalty_l += peaks.size() * 2 * penalties.lWidth * 10000 * (fabs(p_width_left - old_width_left));\n        }\n        else if (p_width_left < 1.5)\n          penalty_l += 2 * penalties.lWidth * 10000 * pow(fabs(p_width_left - old_width_left), 2);\n        if (p_width_right < 0)\n        {\n          penalty_r += peaks.size() * 2 * penalties.rWidth * 10000 * (fabs(p_width_right - old_width_right));\n        }\n        else if (p_width_right < 1.5)\n          penalty_r += 2 * penalties.rWidth * 10000 * pow(fabs(p_width_right - old_width_right), 2);\n        if (fabs(old_position - p_position) > 0.1)\n        {\n          penalty_p += 10000 * penalties.pos * 2 * fabs(old_position - p_position);\n        }\n\n\n\n        gsl_matrix_set(J, positions.size(), 2 + 2 * current_peak, 100 * penalty_h);\n        gsl_matrix_set(J, positions.size(), 0, 100 * penalty_l);\n        gsl_matrix_set(J, positions.size(), 1, 100 * penalty_r);\n        gsl_matrix_set(J, positions.size(), 2 + 2 * current_peak + 1, 100 * penalty_p);\n      }\n\n      return GSL_SUCCESS;\n    }\n\n    // Driver function for the evaluation of function and jacobian.\n    Int evaluateDC(const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix * J)\n    {\n      residualDC(x, params, f);\n      jacobianDC(x, params, J);\n\n      return GSL_SUCCESS;\n    }\n\n  } // namespace OptimizationFunctions\n\n\n\n  OptimizePeakDeconvolution::OptimizePeakDeconvolution() :\n    DefaultParamHandler(\"OptimizePeakDeconvolution\"), charge_(1)\n  {\n\n    defaults_.setValue(\"max_iteration\", 10, \"maximal number of iterations for the fitting step\");\n    defaults_.setValue(\"eps_abs\", 1e-04, \"if the absolute error gets smaller than this value the fitting is stopped\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"eps_rel\", 1e-04, \"if the relative error gets smaller than this value the fitting is stopped\", ListUtils::create<String>(\"advanced\"));\n\n    defaults_.setValue(\"penalties:left_width\", 0.0, \"penalty term for the fitting of the left width:\" \\\n                                                    \"If the left width gets too broad or negative during the fitting it can be penalized.\");\n    defaults_.setValue(\"penalties:right_width\", 0.0, \"penalty term for the fitting of the right width:\" \\\n                                                     \"If the right width gets too broad or negative during the fitting it can be penalized.\");\n    defaults_.setValue(\"penalties:height\", 0.0, \"penalty term for the fitting of the intensity:\" \\\n                                                \"If it gets negative during the fitting it can be penalized.\");\n    defaults_.setValue(\"penalties:position\", 0.0, \"penalty term for the fitting of the peak position:\" \\\n                                                  \"If the position changes more than 0.5Da during the fitting it can be penalized as well as \" \\\n                                                  \"discrepancies of the peptide mass rule.\");\n\n    defaults_.setValue(\"fwhm_threshold\", 1.0, \"If a peaks is broader than fwhm_threshold, it is assumed that it contains another peaks and an additional peak is added.\");\n\n    defaultsToParam_();\n  }\n\n  void OptimizePeakDeconvolution::updateMembers_()\n  {\n    penalties_.rWidth = (float)param_.getValue(\"penalties:right_width\");\n    penalties_.lWidth = (float)param_.getValue(\"penalties:left_width\");\n    penalties_.height = (float)param_.getValue(\"penalties:height\");\n    penalties_.pos    = (float)param_.getValue(\"penalties:position\");\n\n  }\n\n  bool OptimizePeakDeconvolution::optimize(std::vector<PeakShape> & peaks, Data & data)\n  {\n\n    if (peaks.empty())\n      return true;\n\n\n#ifdef DEBUG_DECONV\n    std::cout << \"peaksanzahl:\" << peaks.size();\n    std::cout << \"\\tpeaks[0].mz_position:\" << peaks[0].mz_position << std::endl;\n\n    for (Size j = 0; j < peaks.size(); ++j)\n    {\n      std::cout << \"\\tpeaks[j].mz_position:\" << peaks[j].mz_position;\n      std::cout << \"\\tpeaks[j].height:\" << peaks[j].height << std::endl;\n      std::cout << \"\\tpeaks[j].left_width:\" << peaks[j].left_width;\n      std::cout << \"\\tpeaks[j].right_width:\" << peaks[j].right_width << std::endl << std::endl;\n    }\n\n    for (Size j = 0; j < data.positions.size(); ++j)\n    {\n      std::cout << \"positions[\" << j << \"]=\" << data.positions[j] << std::endl;\n    }\n\n#endif\n\n    // the input peaks are stored in a temporary vector\n    std::vector<PeakShape> temp_shapes = peaks;\n\n\n    Size global_peak_number = 0;\n\n    DoubleReal min(std::numeric_limits<double>::max());\n    Int best_charge;\n    Size num_peaks;\n    Size best_num_peaks;\n    gsl_vector * best_result = gsl_vector_alloc((Int)(2 + 2 * data.peaks.size()));\n\n\n    // try three different charge states : charge-1, charge, charge +1\n    // take the best solution\n    Int l = (charge_ - 1 > 1) ? charge_ - 1 : charge_;\n    Int start_l = l;\n#ifdef DEBUG_DECONV\n    std::cout << \"charge \" << l << \" max_charge\" << charge_ + 1\n              << \"\\tpeaks.size() \" << peaks.size() << std::endl;\n#endif\n    best_charge = l;\n    best_num_peaks = peaks.size();\n    num_peaks = peaks.size();\n    for (; l < charge_ + 2; ++l)\n    {\n\n\n      num_peaks = getNumberOfPeaks_(l, temp_shapes, data);\n#ifdef DEBUG_DECONV\n      std::cout << \"charge \" << l << \" #peaks \" << num_peaks << \"\\tpeaks.size() \"\n                << data.peaks.size() << std::endl;\n#endif\n      gsl_vector * start_value;\n      // the vector storing the start values for the parameters has to be filled\n      // differently depending on the usage of the peptide mass rule\n      start_value = gsl_vector_alloc(2 + 2 * data.peaks.size());\n      for (Size i = 0; i < data.peaks.size(); i++)\n      {\n        gsl_vector_set(start_value, 2 + 2 * i, data.peaks[i].height);\n        gsl_vector_set(start_value, 3 + 2 * i, data.peaks[i].mz_position);\n      }\n\n\n      // Initialize the parameters for the optimization\n\n      // all peaks shall have the same width\n      DoubleReal wl = data.peaks[0].left_width;\n      DoubleReal wr = data.peaks[0].right_width;\n      if (boost::math::isnan(wl))\n      {\n        for (Size i = 0; i < data.peaks.size(); ++i)\n        {\n          data.peaks[i].left_width = 1;\n        }\n        wl = 1.;\n      }\n      if (boost::math::isnan(wr))\n      {\n        for (Size i = 0; i < data.peaks.size(); ++i)\n        {\n          data.peaks[i].right_width = 1;\n        }\n        wr = 1.;\n      }\n\n      gsl_vector_set(start_value, 0, wl);\n      gsl_vector_set(start_value, 1, wr);\n\n\n      // The gsl algorithms require us to provide function pointers for the evaluation of\n      // the target function.\n      gsl_multifit_function_fdf fit_function;\n\n      fit_function.f      = OptimizationFunctions::residualDC;\n      fit_function.df     = OptimizationFunctions::jacobianDC;\n      fit_function.fdf    = OptimizationFunctions::evaluateDC;\n\n      fit_function.n      = std::max(data.positions.size() + 1,\n                                     2 + 2 * data.peaks.size());\n\n      fit_function.p    = 2 + 2 * data.peaks.size();\n      data.penalties = penalties_;\n// fit_function.params = &penalties_;\n      data.charge = l;\n      fit_function.params = &data;\n#ifdef DEBUG_DECONV\n      std::cout << \"fit_function.p \" << fit_function.p << \"\\t fit_function.n \" << fit_function.n << std::endl;\n      std::cout << \"peaks.size() \" << data.peaks.size() << std::endl;\n#endif\n      const gsl_multifit_fdfsolver_type * type = gsl_multifit_fdfsolver_lmsder;\n      gsl_multifit_fdfsolver * fit;\n      fit = gsl_multifit_fdfsolver_alloc(type,\n                                         std::max(data.positions.size() + 1,\n                                                  2 + 2 * data.peaks.size()),\n                                         2 + 2 * data.peaks.size());\n\n\n\n\n\n      gsl_multifit_fdfsolver_set(fit, &fit_function, start_value);\n\n#ifdef DEBUG_DECONV\n      // initial norm\n      std::cout << \"Before optimization: ||f|| = \" << gsl_blas_dnrm2(fit->f) << std::endl;\n#endif\n      // Iteration\n      Int iteration = 0;\n      Int status;\n\n      do\n      {\n        iteration++;\n        status = gsl_multifit_fdfsolver_iterate(fit);\n\n#ifdef DEBUG_DECONV\n        std::cout << \"Iteration \" << iteration << \"; Status \" << gsl_strerror(status) << \"; \" << std::endl;\n        std::cout << \"||f|| = \" << gsl_blas_dnrm2(fit->f) << std::endl;\n        std::cout << \"Number of parms: \" << data.peaks.size() + 3 << std::endl;\n        std::cout << \"Delta: \" << gsl_blas_dnrm2(fit->dx) << std::endl;\n#endif\n        if (boost::math::isnan(gsl_blas_dnrm2(fit->dx)))\n        {\n#ifdef DEBUG_DECONV\n          std::cout << \"norm is not a number\" << std::endl;\n#endif\n          break;\n        }\n        status = gsl_multifit_test_delta(fit->dx, fit->x, (float)param_.getValue(\"eps_abs\"),\n                                         (float)param_.getValue(\"eps_rel\"));\n\n        if (status != GSL_CONTINUE)\n        {\n#ifdef DEBUG_DECONV\n          std::cout << \"gsl status != GSL_CONTINUE\" << std::endl;\n#endif\n          break;\n        }\n        //      if(!checkFWHM_(peaks,fit) && failure <1)\n//                      {\n// #ifdef DEBUG_DECONV\n//                              std::cout << \"fwhm differ\"<<std::endl;\n// #endif\n//                              return false;\n//                      }\n      }\n      while (status == GSL_CONTINUE && iteration < (Int)param_.getValue(\"max_iteration\"));\n\n\n      DoubleReal chi = gsl_blas_dnrm2(fit->f);\n#ifdef DEBUG_DECONV\n      std::cout << \"Finished! Charge \" << l << \"\\tIterations: \" << iteration << std::endl;\n      std::cout << \"Delta: \" << gsl_blas_dnrm2(fit->dx) << std::endl;\n\n      std::cout << \"chisq/dof = \" << pow(chi, 2.0) / (data.positions.size()\n                                                      - (3 + data.peaks.size()));\n      std::cout << \"\\nAfter optimization: ||f|| = \" << gsl_blas_dnrm2(fit->f) << std::endl;\n#endif\n      if ((l == start_l) || (chi < min))\n      {\n        if (l != start_l)\n          gsl_vector_free(best_result);\n        best_result = gsl_vector_alloc(2 + 2 * data.peaks.size());\n        gsl_vector_memcpy(best_result, fit->x);\n        min = chi;\n        best_charge = l;\n        best_num_peaks = data.peaks.size();\n      }\n      iteration = 0;\n\n\n\n      gsl_multifit_fdfsolver_free(fit);\n      gsl_vector_free(start_value);\n\n    }\n    global_peak_number += best_num_peaks;\n    // iterate over all peaks and store the optimized values in peaks\n    if (best_num_peaks > 0)\n    {\n      peaks.resize(best_num_peaks);\n      for (Size current_peak = 0; current_peak < best_num_peaks; current_peak++)\n      {\n\n        // Store the current parameters for this peak\n\n        peaks[current_peak].left_width  = gsl_vector_get(best_result, 0);\n        peaks[current_peak].right_width = gsl_vector_get(best_result, 1);\n\n        peaks[current_peak].height      = gsl_vector_get(best_result, 2 + 2 * current_peak);\n        peaks[current_peak].mz_position = gsl_vector_get(best_result, 2 + 2 * current_peak + 1);\n\n\n\n        // compute the area\n        // is it a Lorentz or a Sech - Peak?\n        if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n        {\n          PeakShape p = peaks[current_peak];\n          DoubleReal x_left_endpoint = p.mz_position + 1 / p.left_width * sqrt(p.height / 1 - 1);\n          DoubleReal x_right_endpoint = p.mz_position + 1 / p.right_width * sqrt(p.height / 1 - 1);\n#ifdef DEBUG_DECONV\n          std::cout << \"x_left_endpoint \" << x_left_endpoint << \" x_right_endpoint \" << x_right_endpoint << std::endl;\n          std::cout << \"p.height\" << p.height << std::endl;\n#endif\n          DoubleReal area_left = -p.height / p.left_width * atan(p.left_width * (x_left_endpoint - p.mz_position));\n          DoubleReal area_right = -p.height / p.right_width * atan(p.right_width * (p.mz_position - x_right_endpoint));\n          peaks[current_peak].area = area_left + area_right;\n\n        }\n        else                  //It's a Sech - Peak\n        {\n          PeakShape p = peaks[current_peak];\n          DoubleReal x_left_endpoint = p.mz_position + 1 / p.left_width * boost::math::acosh(sqrt(p.height / 0.001));\n          DoubleReal x_right_endpoint = p.mz_position + 1 / p.right_width * boost::math::acosh(sqrt(p.height / 0.001));\n#ifdef DEBUG_DECONV\n          std::cout << \"x_left_endpoint \" << x_left_endpoint << \" x_right_endpoint \" << x_right_endpoint << std::endl;\n          std::cout << \"p.height\" << p.height << std::endl;\n#endif\n          DoubleReal area_left = -p.height / p.left_width * (sinh(p.left_width * (p.mz_position - x_left_endpoint))\n                                                             / cosh(p.left_width * (p.mz_position - x_left_endpoint)));\n          DoubleReal area_right = -p.height / p.right_width * (sinh(p.right_width * (p.mz_position - x_right_endpoint))\n                                                               / cosh(p.right_width * (p.mz_position - x_right_endpoint)));\n          peaks[current_peak].area = area_left + area_right;\n\n        }\n\n      }\n    }\n    charge_ = best_charge;\n    gsl_vector_free(best_result);\n\n    return true;\n  }\n\n  bool OptimizePeakDeconvolution::checkFWHM_(std::vector<PeakShape> & peaks, gsl_multifit_fdfsolver * & fit)\n  {\n    DoubleReal fwhm_threshold = (DoubleReal)param_.getValue(\"fwhm_threshold\");\n\n    PeakShape p;\n    for (Size current_peak = 0; current_peak < peaks.size(); current_peak++)\n    {\n      p.left_width  = gsl_vector_get(fit->x, 0);\n      p.right_width = gsl_vector_get(fit->x, 1);\n      p.type        = peaks[current_peak].type;\n#ifdef DEBUG_DECONV\n      std::cout << \"fwhm: \" << p.getFWHM() << \" > \" << fwhm_threshold << \" ?\" << std::endl;\n#endif\n      if (p.getFWHM() > fwhm_threshold)\n        return false;\n    }\n\n    return true;\n  }\n\n  Size OptimizePeakDeconvolution::getNumberOfPeaks_(Int charge, std::vector<PeakShape> & temp_shapes, Data & data)\n  {\n    DoubleReal dist = dist_ / charge;\n\n    data.peaks.clear();\n\n    Size shape = 0;\n#ifdef DEBUG_DECONV\n    std::cout << \"temp_shapes[0].mz_position \" << temp_shapes[0].mz_position\n              << \"\\t dist \" << dist << \"\\tp_index \" << shape << std::endl;\n#endif\n    // while the peak's position is smaller than the last considered position\n    // take the peak for optimization\n    while ((temp_shapes[0].mz_position + shape * dist <\n            data.positions[data.positions.size() - 1]) &&\n           (shape < temp_shapes.size()))\n    {\n      data.peaks.push_back(temp_shapes[shape]);\n#ifdef DEBUG_DECONV\n      std::cout << \"temp_shapes[0].mz_position + p_index*dist = \" << temp_shapes[0].mz_position + shape * dist << std::endl;\n#endif\n      ++shape;\n    }\n\n    return shape;\n\n  }\n\n}\n", "meta": {"hexsha": "958d15e46cc883f8d2ee8f894abc716d8413eaec", "size": 28300, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/TRANSFORMATIONS/RAW2PEAK/OptimizePeakDeconvolution.cpp", "max_stars_repo_name": "kreinert/OpenMS", "max_stars_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "max_stars_repo_licenses": ["Zlib", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-12-09T01:45:03.000Z", "max_stars_repo_stars_event_max_datetime": "2016-12-09T01:45:03.000Z", "max_issues_repo_path": "src/openms/source/TRANSFORMATIONS/RAW2PEAK/OptimizePeakDeconvolution.cpp", "max_issues_repo_name": "kreinert/OpenMS", "max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "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/RAW2PEAK/OptimizePeakDeconvolution.cpp", "max_forks_repo_name": "kreinert/OpenMS", "max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6", "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": 41.3138686131, "max_line_length": 170, "alphanum_fraction": 0.5997879859, "num_tokens": 6971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982315512489, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.2258517021082759}}
{"text": "#include <boost/filesystem.hpp>\n#include <fftw3.h>\n\n#include \"Simulation.h\"\n\ntemplate <int dim>\nSimulation<dim>::Simulation(\n\t\tjson settings, double lc_thickness, unsigned int N_lc_steps,\n\t\tstd::shared_ptr<CubicInterpolatedMapping<dim,3,double> > &n_field) :\n\tmat_properties(settings.at(\"Material properties\")),\n\tN_lc_steps(N_lc_steps),\n\tlc_thickness(lc_thickness),\n\tn_field(n_field) {\n\n\t// We initialize the wavelength array\n\tauto &j = settings.at(\"Light source\");\n\tif(j.find(\"Wavelengths\") != j.end()) {\n\t\twavelengths = j.at(\"Wavelengths\").get<std::vector<double> >();\n\t\tN_wavelengths = int(wavelengths.size());\n\t}\n\telse {\n\t\tN_wavelengths = j.at(\"N wavelengths\");\n\t\tdouble mean_lambda = j.at(\"Mean wavelength\");\n\t\tdouble fwhm = j.at(\"Spectral FWHM\");\n\n\t\tif(N_wavelengths==1)\n\t\t\twavelengths.push_back(j.at(\"Mean wavelength\"));\n\t\telse {\n\t\t\tfor(int i=0; i<N_wavelengths; i++) {\n\t\t\t\twavelengths.push_back(mean_lambda - 0.5*fwhm + fwhm*i/(N_wavelengths-1));\n\t\t\t}\n\t\t}\n\t}\n\n\t// We initialize the ODE for the isotropic layers\n\tlower_iso_thickness = std::accumulate(\n\t\tmat_properties.e_lower_layers.begin(),\n\t\tmat_properties.e_lower_layers.end(), 0.);\n\tupper_iso_thickness = std::accumulate(\n\t\tmat_properties.e_upper_layers.begin(),\n\t\tmat_properties.e_upper_layers.end(), 0.);\n\n\tlower_iso_odes.push_back(std::make_shared<IsotropicODEFunction<dim> >(\n\t\tstd::pow(mat_properties.n_out, 2.),\n\t\tstd::make_shared<SlabDomain<dim> >(\n\t\t\tBasisVector<dim>(dim-1),\n\t\t\t-lower_iso_thickness-lc_thickness*1.5,\n\t\t\t-lower_iso_thickness-lc_thickness/2.)));\n\n\tdouble z_interface = -lower_iso_thickness-lc_thickness/2.;\n\tfor(int i=0; i<mat_properties.n_lower_layers.size(); i++) {\n\t\tlower_iso_odes.push_back(std::make_shared<IsotropicODEFunction<dim> >(\n\t\t\tstd::pow(mat_properties.n_lower_layers[i],2.),\n\t\t\tstd::make_shared<SlabDomain<dim> >(\n\t\t\t\tBasisVector<dim>(dim-1), z_interface,\n\t\t\t\tz_interface + mat_properties.e_lower_layers[i])));\n\t\tz_interface += mat_properties.e_lower_layers[i];\n\t}\n\n\tz_interface = lc_thickness/2;\n\tfor(int i=0; i<mat_properties.e_upper_layers.size(); i++) {\n\t\tupper_iso_odes.push_back(std::make_shared<IsotropicODEFunction<dim> >(\n\t\t\tstd::pow(mat_properties.n_upper_layers[i],2.),\n\t\t\tstd::make_shared<SlabDomain<dim> >(\n\t\t\t\tBasisVector<dim>(dim-1), z_interface,\n\t\t\t\tz_interface + mat_properties.e_upper_layers[i])));\n\t\tz_interface += mat_properties.e_upper_layers[i];\n\t}\n\tupper_iso_odes.push_back(std::make_shared<IsotropicODEFunction<dim> >(\n\t\tstd::pow(mat_properties.n_out,2.),\n\t\tstd::make_shared<SlabDomain<dim> >(\n\t\t\tBasisVector<dim>(dim-1), z_interface,\n\t\t\tz_interface+lc_thickness)));\n\n\t// We initalize the other parameters\n\tN_refinement_cycles =\n\t\tsettings.at(\"InverseScreenMap parameters\").at(\"N refinement cycles\");\n\thc_parameters = settings.at(\"InverseScreenMap parameters\");\n\n\tviz_settings = settings.at(\"Visualisation\");\n\tnumerical_aperture = viz_settings.at(\"Screen output\").at(\"Numerical aperture\");\n\n\tbulk_basename = viz_settings.at(\"Bulk output\").at(\"Base name\");\n\tscreen_basename = viz_settings.at(\"Screen output\").at(\"Base name\");\n\tbasedir = viz_settings.at(\"Results folder name\");\n\n\tbulk_ray_output = viz_settings.at(\"Bulk output\").at(\"Export ray data\");\n\tbulk_fields_output = viz_settings.at(\"Bulk output\").at(\"Export reconstructed fields\");\n\tscreen_ray_output = viz_settings.at(\"Screen output\").at(\"Export ray data\");\n\tscreen_fields_output = viz_settings.at(\"Screen output\").at(\"Export reconstructed fields\");\n\n\tauto widths = parse_Vector<dim-1,double>(viz_settings, \"Target output widths\");\n\tauto dims = parse_Vector<dim-1,unsigned long>(viz_settings, \"Target N pixels per dim\");\n\tauto origin = -widths/2;\n\n\tVector<dim-1,unsigned long> coarse_dims;\n\tfor(int i=0; i<dim-1; i++) {\n\t\tcoarse_dims(i) =\n\t\t\tstd::floor(1+(dims(i)-1)/std::pow(2,N_refinement_cycles));\n\t\tdims(i) = 1+(coarse_dims(i)-1)*std::pow(2,N_refinement_cycles);\n\t}\n\tcoarse_horiz_mesh = std::make_shared<CartesianMesh<dim-1> >(\n\t\torigin, widths, coarse_dims, false);\n\tfull_horiz_mesh = std::make_shared<CartesianMesh<dim-1> >(\n\t\torigin, widths, dims, false);\n\n\tswitch(dim) {\n\t\tcase 2:\n\t\t\ttypical_length = widths(0);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\ttypical_length = std::max(widths(0),widths(1));\n\t\t\tbreak;\n\t}\n\n\tdouble bulk_z_length = lc_thickness;\n\tif(settings.at(\"Geometry\").at(\"Sample type\")==\"Droplet\")\n\t\tbulk_z_length -= 2*settings.at(\"Geometry\").at(\"Droplet sample parameters\").at(\n\t\t\t\"Distance from upper sample plate\").get<double>();\n\tz_step = bulk_z_length / (N_lc_steps-1);\n\n\tdouble n_above_lc =\n\t\tmat_properties.n_upper_layers.size()>0 ?\n\t\tmat_properties.n_upper_layers[0] : mat_properties.n_out;\n\tz_foc_1 =\n\t\tbulk_z_length*(1-n_above_lc/mat_properties.n_lc)/2. +\n\t\t(lc_thickness-bulk_z_length)*(1-n_above_lc/mat_properties.n_host)/2.;\n\tz_foc_2 = \n\t\tbulk_z_length*(1-mat_properties.n_out/mat_properties.n_lc)/2. +\n\t\t(lc_thickness-bulk_z_length)*(1-mat_properties.n_out/mat_properties.n_host)/2.;\n\tfor(int i=0; i<mat_properties.e_upper_layers.size(); i++)\n\t\tz_foc_2 +=\n\t\t\tmat_properties.e_upper_layers[i] *\n\t\t\t(1-mat_properties.n_out/mat_properties.n_upper_layers[i]);\n\n\tswitch(dim) {\n\t\tcase 2:\n\t\t\tN_horiz_pixels = dims(0);\n\t\t\tif(bulk_ray_output) {\n\t\t\t\tbulk_extra_data = std::make_shared<RayData>(\n\t\t\t\t\t1, dims(0), N_lc_steps,\n\t\t\t\t\t0., widths(0)/(dims(0)-1), z_step);\n\t\t\t\tbulk_ordi_data = std::make_shared<RayData>(\n\t\t\t\t\t1, dims(0), N_lc_steps,\n\t\t\t\t\t0., widths(0)/(dims(0)-1), z_step);\n\t\t\t}\n\t\t\tif(bulk_fields_output)\n\t\t\t\tbulk_fields_data = std::make_shared<FieldsData>(\n\t\t\t\t\t1, dims(0), N_lc_steps,\n\t\t\t\t\t0., widths(0)/(dims(0)-1), z_step,\n\t\t\t\t\twavelengths);\n\t\t\tif(screen_ray_output) {\n\t\t\t\tscreen_extra_data = std::make_shared<RayData>(\n\t\t\t\t\t1, dims(0), 1,\n\t\t\t\t\t0., widths(0)/(dims(0)-1), 0.);\n\t\t\t\tscreen_ordi_data = std::make_shared<RayData>(\n\t\t\t\t\t1, dims(0), 1,\n\t\t\t\t\t0., widths(0)/(dims(0)-1), 0.);\n\t\t\t}\n\t\t\tif(screen_fields_output)\n\t\t\t\tscreen_fields_data = std::make_shared<FieldsData>(\n\t\t\t\t\t1, dims(0), 1,\n\t\t\t\t\t0., widths(0)/(dims(0)-1), 0.,\n\t\t\t\t\twavelengths);\n\t\t\tbreak;\n\n\t\tcase 3:\n\t\t\tN_horiz_pixels = dims(0)*dims(1);\n\t\t\tif(bulk_ray_output) {\n\t\t\t\tbulk_extra_data = std::make_shared<RayData>(\n\t\t\t\t\tdims(0), dims(1), N_lc_steps,\n\t\t\t\t\twidths(0)/(dims(0)-1), widths(1)/(dims(1)-1), z_step);\n\t\t\t\tbulk_ordi_data = std::make_shared<RayData>(\n\t\t\t\t\tdims(0), dims(1), N_lc_steps,\n\t\t\t\t\twidths(0)/(dims(0)-1), widths(1)/(dims(1)-1), z_step);\n\t\t\t}\n\t\t\tif(bulk_fields_output)\n\t\t\t\tbulk_fields_data = std::make_shared<FieldsData>(\n\t\t\t\t\tdims(0), dims(1), N_lc_steps,\n\t\t\t\t\twidths(0)/(dims(0)-1), widths(1)/(dims(1)-1), z_step,\n\t\t\t\t\twavelengths);\n\t\t\tif(screen_ray_output) {\n\t\t\t\tscreen_extra_data = std::make_shared<RayData>(\n\t\t\t\t\tdims(0), dims(1), 1,\n\t\t\t\t\twidths(0)/(dims(0)-1), widths(1)/(dims(1)-1), 0.);\n\t\t\t\tscreen_ordi_data = std::make_shared<RayData>(\n\t\t\t\t\tdims(0), dims(1), 1,\n\t\t\t\t\twidths(0)/(dims(0)-1), widths(1)/(dims(1)-1), 0.);\n\t\t\t}\n\t\t\tif(screen_fields_output)\n\t\t\t\tscreen_fields_data = std::make_shared<FieldsData>(\n\t\t\t\t\tdims(0), dims(1), 1,\n\t\t\t\t\twidths(0)/(dims(0)-1), widths(1)/(dims(1)-1), 0.,\n\t\t\t\t\twavelengths);\n\t\t\tbreak;\n\t}\n}\n\ntemplate <int dim>\nvoid Simulation<dim>::apply_fourier_iso_layer_filter() {\n\n\tint dims[3]; \t\tscreen_fields_data->vti_data->GetDimensions(dims);\n\tdouble spacings[3];\tscreen_fields_data->vti_data->GetSpacing(spacings);\n\n\tfftw_complex *in = static_cast<fftw_complex*>(\n\t\tfftw_malloc(sizeof(fftw_complex) * dims[0]*dims[1]));\n\tfftw_complex *out = static_cast<fftw_complex*>(\n\t\tfftw_malloc(sizeof(fftw_complex) * dims[0]*dims[1]));\n\tfftw_plan forward_plan = (dim==3) ?\n\t\tfftw_plan_dft_2d(dims[1], dims[0], in, out, FFTW_FORWARD, FFTW_ESTIMATE) :\n\t\tfftw_plan_dft_1d(dims[1], in, out, FFTW_FORWARD, FFTW_ESTIMATE);\n\tfftw_plan backward_plan = (dim==3) ?\n\t\tfftw_plan_dft_2d(dims[1], dims[0], in, out, FFTW_BACKWARD, FFTW_ESTIMATE) :\n\t\tfftw_plan_dft_1d(dims[1], in, out, FFTW_BACKWARD, FFTW_ESTIMATE);\n\n\t#pragma omp parallel for\n\tfor(int wave_idx=0; wave_idx<N_wavelengths; wave_idx++) {\n\t\t// First we assemble the filter\n\t\tauto iso_filter =\n\t\t\tstd::make_shared<std::vector<std::complex<double> > >(dims[0]*dims[1]);\n\t\tdouble k0 = 2*PI/wavelengths[wave_idx];\n\n\t\t// transfer matrix in column-major order\n\t\tstd::vector<std::complex<double> > tmat(4), prev_tmat(4); \n\t\tstd::complex<double> t1, t2;\n\n\t\tfor(int iy=0; iy<dims[1]; iy++) {\n\t\t\tfor(int ix=0; ix<dims[0]; ix++) {\n\t\t\t\tdouble kx = (ix<double(dims[0]/2.)) ?\n\t\t\t\t\t2*PI*ix/(spacings[0]*(dims[0]-1)) :\n\t\t\t\t\t-2*PI*(dims[0]-ix)/(spacings[0]*(dims[0]-1));\n\t\t\t\tif(dim==2)\n\t\t\t\t\tkx = 0;\n\t\t\t\tdouble ky = (iy<double(dims[1]/2.)) ?\n\t\t\t\t\t2*PI*iy/(spacings[1]*(dims[1]-1)) :\n\t\t\t\t\t-2*PI*(dims[1]-iy)/(spacings[1]*(dims[1]-1));\n\t\t\t\tdouble k = std::sqrt(kx*kx+ky*ky);\n\n\t\t\t\tif(k<k0*numerical_aperture) {\n\t\t\t\t\ttmat[0] = 1;\n\t\t\t\t\ttmat[1] = 0;\n\t\t\t\t\ttmat[2] = 0;\n\t\t\t\t\ttmat[3] = 1;\n\n\t\t\t\t\tprev_tmat = tmat;\n\n\t\t\t\t\tdouble kN = std::sqrt(k0*k0-k*k);\n\n\t\t\t\t\tfor(int p=0; p<mat_properties.e_upper_layers.size(); p++) {\n\t\t\t\t\t\tdouble np = mat_properties.n_upper_layers[p];\n\t\t\t\t\t\tdouble ep = mat_properties.e_upper_layers[p];\n\t\t\t\t\t\tdouble kp = std::sqrt(std::pow(k0*np,2.)-k*k);\n\t\t\t\t\t\tdouble next_kp = (p+1<mat_properties.e_upper_layers.size()) ?\n\t\t\t\t\t\t\tstd::sqrt(std::pow(k0*mat_properties.n_upper_layers[p+1],2.)-k*k) :\n\t\t\t\t\t\t\tstd::sqrt(std::pow(k0*mat_properties.n_out,2.)-k*k);\n\n\t\t\t\t\t\tt1 = 0.5*(1+kp/next_kp)*std::exp(std::complex<double>(0,(kp-kN)*ep));\n\t\t\t\t\t\tt2 = 0.5*(1-kp/next_kp)*std::exp(std::complex<double>(0,(kp-kN)*ep));\n\n\t\t\t\t\t\ttmat[0] = t1*prev_tmat[0] + std::conj(t2)*prev_tmat[1];\n\t\t\t\t\t\ttmat[1] = t2*prev_tmat[0] + std::conj(t1)*prev_tmat[1];\n\t\t\t\t\t\ttmat[2] = t1*prev_tmat[2] + std::conj(t2)*prev_tmat[3];\n\t\t\t\t\t\ttmat[3] = t2*prev_tmat[2] + std::conj(t1)*prev_tmat[3];\n\n\t\t\t\t\t\tprev_tmat = tmat;\n\t\t\t\t\t}\n\t\t\t\t\tiso_filter->at(ix+dims[0]*iy) =\n\t\t\t\t\t\t(tmat[0]-tmat[1]*tmat[2]/tmat[3]) *\n\t\t\t\t\t\tstd::exp(std::complex<double>(0,kN*z_foc_2));\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t\tiso_filter->at(ix+dims[0]*iy) = 0;\n\t\t\t}\n\t\t}\n\n\t\t// FFTW arrays for this thread\n\t\tfftw_complex *field = static_cast<fftw_complex*>(\n\t\t\tfftw_malloc(sizeof(fftw_complex) * dims[0]*dims[1]));\n\t\tfftw_complex *fft_field = static_cast<fftw_complex*>(\n\t\t\tfftw_malloc(sizeof(fftw_complex) * dims[0]*dims[1]));\n\n\t\tfor(int pol_idx=0; pol_idx<2; pol_idx++) {\n\t\t\tfor(int comp=0; comp<2; comp++) {\n\t\t\t\t// First, we fill the fftw input array with our data\n\t\t\t\tfor(int i=0; i<dims[0]*dims[1]; i++) {\n\t\t\t\t\tfield[i][0] =\n\t\t\t\t\t\tscreen_fields_data->E_real[pol_idx][wave_idx]->GetComponent(i,comp);\n\t\t\t\t\tfield[i][1] = \n\t\t\t\t\t\tscreen_fields_data->E_imag[pol_idx][wave_idx]->GetComponent(i,comp);\n\t\t\t\t}\n\n\t\t\t\t// We switch to fourrier space and apply the iso filter\n\t\t\t\tfftw_execute_dft(forward_plan, field, fft_field);\n\t\t\t\tfor(int i=0; i<dims[0]*dims[1]; i++) {\n\t\t\t\t\tauto val = std::complex<double>(fft_field[i][0], fft_field[i][1]);\n\t\t\t\t\tfft_field[i][0] = std::real(val * iso_filter->at(i));\n\t\t\t\t\tfft_field[i][1] = std::imag(val * iso_filter->at(i));\n\t\t\t\t}\n\n\t\t\t\t// We come back to real space and save the transformed\n\t\t\t\t// data\n\t\t\t\tfftw_execute_dft(backward_plan, fft_field, field);\n\n\t\t\t\tfor(int i=0; i<dims[0]*dims[1]; i++) {\n\t\t\t\t\tscreen_fields_data->E_real[pol_idx][wave_idx]->SetComponent(\n\t\t\t\t\t\ti, comp, field[i][0]/(dims[0]*dims[1]));\n\t\t\t\t\tscreen_fields_data->E_imag[pol_idx][wave_idx]->SetComponent(\n\t\t\t\t\t\ti, comp, field[i][1]/(dims[0]*dims[1]));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// We free the FFTW pointers\n\t\tfftw_free(field);\n\t\tfftw_free(fft_field);\n\t}\n\n\t// We free the FFTW pointers\n\tfftw_destroy_plan(forward_plan);\n\tfftw_destroy_plan(backward_plan);\n\tfftw_free(in);\n\tfftw_free(out);\n}\n\ntemplate class Simulation<2>;\ntemplate class Simulation<3>;\n", "meta": {"hexsha": "a7df01901387b506d1bd25401d06929e42d2e100", "size": 11509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RayTracingSolver/src/SimulationLib/Simulation.cpp", "max_stars_repo_name": "warthan07/Nemaktis", "max_stars_repo_head_hexsha": "54b1e64c1d40668e6dc22b11eac5487a09b58478", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-25T08:13:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-18T12:12:34.000Z", "max_issues_repo_path": "RayTracingSolver/src/SimulationLib/Simulation.cpp", "max_issues_repo_name": "warthan07/Nemaktis", "max_issues_repo_head_hexsha": "54b1e64c1d40668e6dc22b11eac5487a09b58478", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RayTracingSolver/src/SimulationLib/Simulation.cpp", "max_forks_repo_name": "warthan07/Nemaktis", "max_forks_repo_head_hexsha": "54b1e64c1d40668e6dc22b11eac5487a09b58478", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-18T12:13:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T12:13:40.000Z", "avg_line_length": 35.1957186544, "max_line_length": 91, "alphanum_fraction": 0.6719958294, "num_tokens": 3670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.22579550590184402}}
{"text": "/**\nBSD 3-Clause License\n\nThis file is part of the code accompanying the paper\nFrom Planes to Corners: Multi-Purpose Primitive Detection in Unorganized 3D Point Clouds\nby C. Sommer, Y. Sun, L. Guibas, D. Cremers and T. Birdal,\naccepted for Publication in IEEE Robotics and Automation Letters (RA-L) 2020.\n\nCopyright (c) 2019, Christiane Sommer.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n// includes\n#include <iostream>\n#include <fstream>\n#include <string> \n#include \"definitions.h\"\n// libraries\n#include <Eigen/Dense>\n#include <opencv2/core/core.hpp>\n#include <CLI/CLI.hpp>\n// classes\n#include \"Timer.h\"\n#include \"Plane.h\"\n#include \"graph/PlaneGraph.h\"\n#include \"graph/ParallelPlaneGraph.h\"\n#include \"PPF/PairDetector.h\"\n// function includes\n#include \"io/load_ply_cloud.h\"\n#include \"visualize/pcshow.h\"\n\n#include <pcl/io/pcd_io.h>\n#include <pcl/point_types.h>\n\n\n\n#include <experimental/filesystem>\n\nnamespace fs = std::experimental::filesystem;\n\n/*\n * main\n */\nint main(int argc, char** argv) {\n\n  int nr_volume=0;\n  int nr_pointclouds=0;\n\n  std::string string_pointcloud;\n  std::ifstream MyReadFile2(\"../data/main_programs/config_files/input_file_plane_dataset.txt\");\n  std::getline (MyReadFile2, string_pointcloud);\n\n \n\n\n  std::ofstream myfile(\"/home/alex-pop/Desktop/Doctorat/Side_projects/Volume_box_batch_processing/orthogonal-planes/data/output_volumes.txt\");\n  \n\n  myfile<<\"Hello\"<<'\\n';\n\n\n\n  \n\t\n\t//fs::path path(\"/home/alex-pop/Desktop/Doctorat/Side_projects/Volume_box_batch_processing/orthogonal-planes/data/Pointcloud_recordings\");\n  fs::path path(string_pointcloud);\n\tfor (auto& p : fs::directory_iterator(path))\n\t{\n\t\t\n\tstd::stringstream ss;\n\t\n    ss << p ;\n    \n   std::string str = ss.str();\n   \n   str.erase(std::remove(str.begin(), str.end(), '\"'), str.end());\n   \n   std::cout<<str<<'\\n';\n    \n   pcl::PointCloud<pcl::PointNormal>::Ptr cloud(new pcl::PointCloud<pcl::PointNormal>);\n\n    if (pcl::io::loadPCDFile<pcl::PointNormal> (str, *cloud) == -1) //* load the file\n  {\n    PCL_ERROR (\"Couldn't read file test_pcd.pcd \\n\");\n    return (-1);\n  }\n  std::cout << \"Loaded \"\n            << cloud->width * cloud->height\n            << \" data points from \"<<str<<\".pcd with the following fields: \"\n            << std::endl;\n            \n  std::vector<Eigen::Vector3f> points;\n  std::vector<Eigen::Vector3f> normals;\n\n  nr_pointclouds++;\n\n\n\n  for (int i = 0; i < cloud->size(); i++)\n    {\n       \n        \n        Eigen::Vector3f position_aux= Eigen::Vector3f( (float) cloud->points[i].x,(float) cloud->points[i].y,(float) cloud->points[i].z);\n        points.push_back(position_aux);\n\n        Eigen::Vector3f normal_aux= Eigen::Vector3f( (float) cloud->points[i].normal_x,(float) cloud->points[i].normal_y,(float) cloud->points[i].normal_z);\n        normals.push_back(normal_aux);\n    }\n\n     std::cout << points.size() << \" points loaded.\" << std::endl;\n     std::cout << normals.size() << \" normals loaded.\" << std::endl;\n    std::cout<<\"\\n\";\n\n    Timer T;\n    \n    // parse setttings from command line\n    std::string ply_file;\n    int min_votes = 5;\n    double d_min = .1, d_max = 1.;\n    int sampling = 10;\n\n\n    std::ifstream MyReadFile(\"../data/main_programs/config_files/input_file_plane.txt\");\n\n    std::ifstream MyReadFile2(\"../data/main_programs/config_files/input_file_plane_dataset.txt\");\n\n    std::string min_votes_text;\n    std::string d_min_text;\n    std::string d_max_text;\n    std::string sampling_text;\n    std::string threshold_text;\n\n    std::getline (MyReadFile, min_votes_text);\n    std::getline (MyReadFile, d_min_text);\n    std::getline (MyReadFile, d_max_text);\n    std::getline (MyReadFile, sampling_text);\n    std::getline (MyReadFile, threshold_text);\n\n\n    min_votes=std::stoi(min_votes_text);\n    std::cout<<\"min_votes=\"<<min_votes<< std::endl;\n    d_min=std::stod(d_min_text);\n     std::cout<<\"d_min=\"<<d_min<< std::endl;\n     d_max=std::stod(d_max_text);\n     std::cout<<\"d_max=\"<<d_max<< std::endl;\n     sampling=std::stoi(sampling_text);\n     std::cout<<\"sampling_text=\"<<sampling<< std::endl;\n     double threshold=std::stod(threshold_text);\n     std::cout<<\"threshold lines=\"<<threshold<< std::endl;\n\n  \n     for(int nr_exec=0;nr_exec<3;nr_exec++)\n     {\n\n       \n       \n    \n    // pairing\n    ppf::PairDetector pairDet(d_max, d_min, min_votes);\n    PlaneGraph planeMap(pairDet.para_thresh(), pairDet.distance_bin());\n    T.tic();\n    pairDet.detect_ortho_pairs(points, normals, planeMap);\n    T.toc(\"time pairing PPF \");\n    //planeMap.print_info();\n    \n    std::cout << std::endl << \"Thresholds:\\tAngle:\\t\" << pairDet.para_thresh() << \"\\tDistance:\\t\" << pairDet.distance_bin() << std::endl << std::endl;\n\n    // clustering & filtering\n    T.tic();\n    planeMap.cluster_graph_vertices();\n    T.toc(\"clustering planes\");\n    //planeMap.print_info();\n    //planeMap.print_parameters();\n    //planeMap.print_edges();\n    \n    // find triangles\n    std::vector<Graph<Plane>::Triangle> triangles;\n    T.tic();\n    planeMap.find_triangles(triangles);\n    T.toc(\"Finding triangles\");\n    //planeMap.print_triangles(triangles);\n    \n    // reduce graph to ParallelPlaneGraph\n    T.tic();\n    ParallelPlaneGraph redMap = planeMap.reduce_graph();\n    T.toc(\"graph reduction\");\n    //redMap.print_info();\n    //redMap.print_edges();\n    T.tic();\n    redMap.triangle_reduce();\n    T.toc(\"triangle reduction\");\n    //redMap.print_info();\n    //redMap.print_parameters();\n    //redMap.print_edges();\n    \n    T.tic();\n    redMap.filter_outliers(points, normals, pairDet.distance_bin(), .5*sampling);\n    T.toc(\"outlier filtering\");\n    //redMap.print_info();\n    //redMap.print_parameters();\n    //redMap.print_edges();\n \n    // CERES problem setup and solving\n    double lambda = 0.01 * points.size();\n    T.tic();\n    redMap.refine_coarse_fine(points, normals, lambda, pairDet.distance_bin(), sampling);\n    T.toc(\"Multi-plane parameter optimization\");\n    //redMap.print_info();\n    //redMap.print_parameters();\n    //redMap.print_edges();\n    \n    T.tic();\n    redMap.filter_outliers(points, normals, pairDet.distance_bin(), .5*sampling);\n    T.toc(\"outlier filtering\");\n    //redMap.print_info();\n    //redMap.print_parameters();\n    //redMap.print_edges();\n    \n    // From here on visualization / debugging\n\n//    // get points located on planes and not-planes\n    PlaneGraph finalMap = PlaneGraph::from_ppg(redMap, 2*pairDet.para_thresh()*pairDet.para_thresh()-1, pairDet.distance_bin()); // double angle\n    std::vector<Eigen::Matrix<float, 6, 1>> labeled;\n    T.tic();\n    finalMap.go_thr_pcl(points, normals, labeled);\n    T.toc(\"labeling planes\");\n\n    // visualize\n   // pcshow(labeled, \"Result\");\n    \n   std::vector<Vec6> lines;\n   // line extraction and visualization\n   T.tic();\n   lines = finalMap.extract_lines(points, normals);\n   T.toc(\"get lines\");\n   //std::cout << lines.size() << \" lines found.\" << std::endl;\n\n   std::vector<Vec6> new_lines;\n\n   std::vector<Vec6> final_lines;\n   std::vector<double> distances;\n\n   std::vector<double> Volume_edge;\n\n   std::vector<int> positions_wrong;\n   std::vector<double> Volumes;\n\n   \n\n    std::cout<<'\\n';\n\n    \n  if (lines.size()>=3){\n    for(int i = 0; i != lines.size()-2; i++) {\n    //std::cout<< lines[i][0]<<\" \"<<lines[i][1]<<\" \"<<lines[i][2]<<\" \"<<lines[i][3]<<\" \"<<lines[i][4]<<\" \"<<lines[i][5]<<\" \"<<'\\n';\n      for(int j = i+1; j != lines.size()-1; j++) {\n          for(int k = j+1; k != lines.size(); k++) {\n\n                bool ok_ij=1;\n                bool ok_jk=1;\n                bool ok_ki=1;\n\n                double average_0,average_1,average_2;\n\n                \n                if( (lines[i][0]==lines[j][0]) && (lines[i][1]==lines[j][1]) && (lines[i][2]==lines[j][2])) {ok_ij=0;}\n                if( (lines[j][0]==lines[k][0]) && (lines[j][1]==lines[k][1]) && (lines[j][2]==lines[k][2])) {ok_jk=0;}\n                if( (lines[k][0]==lines[i][0]) && (lines[k][1]==lines[i][1]) && (lines[k][2]==lines[i][2])) {ok_ki=0;}\n                \n                if (ok_ij && ok_jk && ok_ki){\n                  \n              average_0=(lines[i][0]+lines[j][0]+lines[k][0]) / 3;\n              average_1=(lines[i][1]+lines[j][1]+lines[k][1]) /3 ;\n              average_2=(lines[i][2]+lines[j][2]+lines[k][2]) /3;\n\n\n              double dist_i_average= sqrt (  (lines[i][0]-average_0)*(lines[i][0]-average_0)  +  (lines[i][1]-average_1)*(lines[i][1]-average_1) +(lines[i][2]-average_2)*(lines[i][2]-average_2)   );\n              double dist_j_average= sqrt (  (lines[j][0]-average_0)*(lines[j][0]-average_0)  +  (lines[j][1]-average_1)*(lines[j][1]-average_1) +(lines[j][2]-average_2)*(lines[j][2]-average_2)   );\n              double dist_k_average= sqrt (  (lines[k][0]-average_0)*(lines[k][0]-average_0)  +  (lines[k][1]-average_1)*(lines[k][1]-average_1) +(lines[k][2]-average_2)*(lines[k][2]-average_2)   );\n\n\n              if(  (dist_i_average<threshold) && (dist_j_average<threshold) &&(dist_k_average<threshold) )\n              {\n                  /*\n                  std::cout<< lines[i][0]<<\" \"<<lines[i][1]<<\" \"<<lines[i][2]<<\" \"<<'\\n';      \n                  std::cout<< lines[j][0]<<\" \"<<lines[j][1]<<\" \"<<lines[j][2]<<\" \"<<'\\n';\n                  std::cout<< lines[k][0]<<\" \"<<lines[k][1]<<\" \"<<lines[k][2]<<\" \"<<'\\n';\n                  */\n\n                  distances.push_back(dist_i_average);\n                  distances.push_back(dist_j_average);\n                  distances.push_back(dist_k_average);\n                  \n\n                  /* \n                  std::cout<<\"Average:\"<<average_0<<\" \"<<average_1<<\" \"<<average_2<<\"\\n\";\n                  std::cout<<\"\\n\";\n                  */\n                  /*\n                std::cout<< lines[i][0]<<\" \"<<lines[i][1]<<\" \"<<lines[i][2]<<\" \"<<lines[i][3]<<\" \"<<lines[i][4]<<\" \"<<lines[i][5]<<\" \"<<'\\n';\n                std::cout<< lines[j][0]<<\" \"<<lines[j][1]<<\" \"<<lines[j][2]<<\" \"<<lines[j][3]<<\" \"<<lines[j][4]<<\" \"<<lines[j][5]<<\" \"<<'\\n';\n                std::cout<< lines[k][0]<<\" \"<<lines[k][1]<<\" \"<<lines[k][2]<<\" \"<<lines[k][3]<<\" \"<<lines[k][4]<<\" \"<<lines[k][5]<<\" \"<<'\\n';\n                */\n                double latura_i = sqrt (  (lines[i][0]-lines[i][3])*(lines[i][0]-lines[i][3])  +  (lines[i][1]-lines[i][4])*(lines[i][1]-lines[i][4]) +(lines[i][2]-lines[i][5])*(lines[i][2]-lines[i][5])   );\n                double latura_j = sqrt (  (lines[j][0]-lines[j][3])*(lines[j][0]-lines[j][3])  +  (lines[j][1]-lines[j][4])*(lines[j][1]-lines[j][4]) +(lines[j][2]-lines[j][5])*(lines[j][2]-lines[j][5])   );\n                double latura_k = sqrt (  (lines[k][0]-lines[k][3])*(lines[k][0]-lines[k][3])  +  (lines[k][1]-lines[k][4])*(lines[k][1]-lines[k][4]) +(lines[k][2]-lines[k][5])*(lines[k][2]-lines[k][5])   );\n\n                double Volum = latura_i*latura_j*latura_k;\n                 /*\n                std::cout<<\"Latura 1: \"<<latura_1<<'\\n';\n                std::cout<<\"Latura 2: \"<<latura_3<<'\\n';\n                std::cout<<\"Latura 3: \"<<latura_3<<'\\n';\n                */\n\n                //std::cout<<\"Volum=\"<<Volum<<'\\n';\n\n                new_lines.push_back(lines[i]);\n                new_lines.push_back(lines[j]);\n                new_lines.push_back(lines[k]);\n\n                Volume_edge.push_back(latura_i);\n                Volume_edge.push_back(latura_j);\n                Volume_edge.push_back(latura_k);\n\n                Volumes.push_back(Volum);\n                Volumes.push_back(Volum);\n                Volumes.push_back(Volum);\n              }\n\n              }\n            }     \n          }\n\n       }\n\n\n   if (new_lines.size()>1){\n    for(int i = 0; i != new_lines.size(); i++) {\n    //std::cout<< new_lines[i][0]<<\" \"<<new_lines[i][1]<<\" \"<<new_lines[i][2]<<\" \"<<new_lines[i][3]<<\" \"<<new_lines[i][4]<<\" \"<<new_lines[i][5]<<\" \"<<'\\n';\n    }   \n    \n\n    for(int i = 0; i != new_lines.size()-1; i++) {\n    \n      for(int j = i+1; j != new_lines.size(); j++) {\n          if( ( (new_lines[i][0]==new_lines[j][0])  && (new_lines[i][1]==new_lines[j][1]) && (new_lines[i][2]==new_lines[j][2]) && (new_lines[i][3]==new_lines[j][3]) && (new_lines[i][4]==new_lines[j][4]) && (new_lines[i][5]==new_lines[j][5]) ) ||\n              ( (new_lines[i][0]==new_lines[j][3])  && (new_lines[i][1]==new_lines[j][4])&&  (new_lines[i][2]==new_lines[j][5]) && (new_lines[i][3]==new_lines[j][0]) && (new_lines[i][4]==new_lines[j][1]) && (new_lines[i][5]==new_lines[j][2]) ) )  \n               {\n            //std::cout<<\"Dublura gasita la\"<<i<<\" \"<<j<<'\\n';\n\n            double total_distance_i;\n            double total_distance_j;\n            \n            int offset_i= (i % 3);\n            int offset_j= (j % 3);\n\n            \n\n            total_distance_i=distances[i - offset_i]+distances[i+1 - offset_i]+distances[i+2 - offset_i];\n            total_distance_j=distances[j - offset_j]+distances[j+1 - offset_j]+distances[j+2 - offset_j];\n\n            //std::cout<<\"Distance i: \"<<total_distance_i<<\"\\n\";\n           // std::cout<<\"Distance j: \"<<total_distance_j<<\"\\n\";\n\n            if(total_distance_i>total_distance_j){\n              positions_wrong.push_back(i - offset_i);\n            }\n            else\n            {\n               positions_wrong.push_back(j - offset_j);\n            }\n\n            \n          }\n          \n      }\n    }\n   }\n  \n  /*\n  std::cout<<\"Positions wrong:\"<<'\\n';\n\n\n   for(int i = 0; i != positions_wrong.size(); i++) {\n    std::cout<<positions_wrong[i]<<'\\n';\n    }   \n\n    */\n    if (new_lines.size()>=3){\n      nr_volume++;\n\n       //myfile<<str<<\" \"<<'\\n';\n\n       //myfile<<nr_exec<<\" iteration\"<<'\\n';\n\n    for(int i = 0; i < new_lines.size(); i=i+3) {\n      bool ok_position=1;\n      for(int j = 0; j != positions_wrong.size(); j++) {\n        if(i==positions_wrong[j]){\n          ok_position=0;\n        }\n      }\n      if(ok_position){\n        final_lines.push_back(new_lines[i]);\n        final_lines.push_back(new_lines[i+1]);\n        final_lines.push_back(new_lines[i+2]);\n        std::cout<<\"Volum \"<<(i/3)<<\": \"<<Volumes[i]<<\" cm^3\"<<'\\n';\n\n        myfile<<Volumes[i]<<\" \"<<nr_pointclouds<<'\\n';\n\n        /*\n        std::cout<< \"(\"<<new_lines[i][0]<<\" , \"<<new_lines[i][1]<<\" , \"<<new_lines[i][2]<<\" , \"<<new_lines[i][3]<<\" , \"<<new_lines[i][4]<<\" , \"<<new_lines[i][5]<<\")\"<<\" =>distance1= \"<<Volume_edge[i] <<'\\n';\n        std::cout<< \"(\"<<new_lines[i+1][0]<<\" , \"<<new_lines[i+1][1]<<\" , \"<<new_lines[i+1][2]<<\" , \"<<new_lines[i+1][3]<<\" , \"<<new_lines[i+1][4]<<\" , \"<<new_lines[i+1][5]<<\")\"<<\" =>distance2= \"<<Volume_edge[i+1] <<'\\n';\n        std::cout<< \"(\"<<new_lines[i+2][0]<<\" , \"<<new_lines[i+2][1]<<\" , \"<<new_lines[i+2][2]<<\" , \"<<new_lines[i+2][3]<<\" , \"<<new_lines[i+2][4]<<\" , \"<<new_lines[i+2][5]<<\")\"<<\" =>distance3= \"<<Volume_edge[i+2] <<'\\n';\n        */\n\n        std::cout<< \"distance1= \"<<Volume_edge[i] <<\" cm\"<<'\\n';\n        std::cout<< \"distance2= \"<<Volume_edge[i+1]<<\" cm\" <<'\\n';\n        std::cout<< \"distance3= \"<<Volume_edge[i+2]<<\" cm\" <<'\\n';\n        \n        std::cout<<'\\n';\n\n       \n\n      }\n    }\n   }\n\n   \n     \n  \n   \n   //pcshow_lines(points, lines, \"Orth Plane Intersections\");\n\n   //pcshow_lines(points, new_lines, \"Volume Computation Edges\");\n\n   //pcshow_lines(points, final_lines, \"Volume Final Edges\");\n   \n  }\n     }\n  }\n   std::cout<<nr_pointclouds<<\" pointclouds found\"<<'\\n';\n    std::cout<<nr_volume<<\" pointclouds with volumes\"<<'\\n';\n\n\n   \n    \n}\n", "meta": {"hexsha": "b5571a7882ae5d8af443ba1aa884f222f195274d", "size": 16762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "orthogonal-planes/Volume_box_batch_processing/orthogonal_planes/ply_detect_refine/src/main.cpp", "max_stars_repo_name": "tamaslevente/trai", "max_stars_repo_head_hexsha": "4bf68463b941f305d9b25a9374b6c2a2d51a8046", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "orthogonal-planes/Volume_box_batch_processing/orthogonal_planes/ply_detect_refine/src/main.cpp", "max_issues_repo_name": "tamaslevente/trai", "max_issues_repo_head_hexsha": "4bf68463b941f305d9b25a9374b6c2a2d51a8046", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "orthogonal-planes/Volume_box_batch_processing/orthogonal_planes/ply_detect_refine/src/main.cpp", "max_forks_repo_name": "tamaslevente/trai", "max_forks_repo_head_hexsha": "4bf68463b941f305d9b25a9374b6c2a2d51a8046", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3628691983, "max_line_length": 247, "alphanum_fraction": 0.5715905023, "num_tokens": 4604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22575051571482055}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#include \"piecewise_polynomial_discontinuous_scalar_space.hpp\"\n\n#include \"space_helper.hpp\"\n\n#include \"../assembly/discrete_sparse_boundary_operator.hpp\"\n#include \"../common/acc.hpp\"\n#include \"../common/boost_make_shared_fwd.hpp\"\n#include \"../common/bounding_box_helpers.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../grid/entity.hpp\"\n#include \"../grid/entity_iterator.hpp\"\n#include \"../grid/geometry.hpp\"\n#include \"../grid/grid.hpp\"\n#include \"../grid/grid_view.hpp\"\n#include \"../grid/grid_segment.hpp\"\n#include \"../grid/mapper.hpp\"\n#include \"../grid/vtk_writer.hpp\"\n\n#include <stdexcept>\n#include <iostream>\n\n#include <boost/array.hpp>\n\nnamespace Bempp {\n\ntemplate <typename BasisFunctionType>\nPiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    PiecewisePolynomialDiscontinuousScalarSpace(\n        const shared_ptr<const Grid> &grid, int polynomialOrder)\n    : ScalarSpace<BasisFunctionType>(grid), m_polynomialOrder(polynomialOrder),\n      m_flatLocalDofCount(0) {\n  initialize(GridSegment::wholeGrid(*grid));\n}\n\ntemplate <typename BasisFunctionType>\nPiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    PiecewisePolynomialDiscontinuousScalarSpace(\n        const shared_ptr<const Grid> &grid, int polynomialOrder,\n        const GridSegment &segment, int dofMode)\n    : ScalarSpace<BasisFunctionType>(grid), m_polynomialOrder(polynomialOrder),\n      m_flatLocalDofCount(0) {\n  initialize(segment, dofMode);\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::initialize(\n    const GridSegment &segment, int dofMode) {\n  const int gridDim = this->grid()->dim();\n  if (gridDim != 2)\n    throw std::invalid_argument(\"PiecewisePolynomialDiscontinuousScalarSpace::\"\n                                \"initialize(): \"\n                                \"only 2-dimensional grids are supported\");\n  if (!(dofMode & (REFERENCE_POINT_ON_SEGMENT | ELEMENT_ON_SEGMENT)))\n    throw std::invalid_argument(\"PiecewisePolynomialDiscontinuousScalarSpace::\"\n                                \"initialize(): invalid dofMode\");\n  m_view = this->grid()->leafView();\n  if (m_polynomialOrder == 0)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 0>());\n  else if (m_polynomialOrder == 1)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 1>());\n  else if (m_polynomialOrder == 2)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 2>());\n  else if (m_polynomialOrder == 3)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 3>());\n  else if (m_polynomialOrder == 4)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 4>());\n  else if (m_polynomialOrder == 5)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 5>());\n  else if (m_polynomialOrder == 6)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 6>());\n  else if (m_polynomialOrder == 7)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 7>());\n  else if (m_polynomialOrder == 8)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 8>());\n  else if (m_polynomialOrder == 9)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 9>());\n  else if (m_polynomialOrder == 10)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarBasis<3, BasisFunctionType, 10>());\n  else\n    throw std::invalid_argument(\n        \"PiecewisePolynomialDiscontinuousScalarSpace::\"\n        \"PiecewisePolynomialDiscontinuousScalarSpace(): \"\n        \"polynomialOrder must be >= 0 and <= 10\");\n  assignDofsImpl(segment, dofMode);\n}\n\ntemplate <typename BasisFunctionType>\nPiecewisePolynomialDiscontinuousScalarSpace<\n    BasisFunctionType>::~PiecewisePolynomialDiscontinuousScalarSpace() {}\n\ntemplate <typename BasisFunctionType>\nint PiecewisePolynomialDiscontinuousScalarSpace<\n    BasisFunctionType>::domainDimension() const {\n  return this->grid()->dim();\n}\n\ntemplate <typename BasisFunctionType>\nint PiecewisePolynomialDiscontinuousScalarSpace<\n    BasisFunctionType>::codomainDimension() const {\n  return 1;\n}\n\ntemplate <typename BasisFunctionType>\nconst Fiber::Shapeset<BasisFunctionType> &\nPiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::shapeset(\n    const Entity<0> &element) const {\n  if (elementVariant(element) == 3)\n    return *m_triangleShapeset;\n  throw std::logic_error(\n      \"PiecewisePolynomialDiscontinuousScalarSpace::shapeset(): \"\n      \"invalid element variant, this shouldn't happen!\");\n}\n\ntemplate <typename BasisFunctionType>\nbool PiecewisePolynomialDiscontinuousScalarSpace<\n    BasisFunctionType>::spaceIsCompatible(const Space<BasisFunctionType> &other)\n    const {\n\n  typedef PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>\n  thisSpaceType;\n\n  if (other.grid().get() != this->grid().get())\n    return false;\n\n  if (other.spaceIdentifier() == this->spaceIdentifier()) {\n    // Try to typecast the other space down.\n    const thisSpaceType &temp = dynamic_cast<const thisSpaceType &>(other);\n    if (this->m_polynomialOrder == temp.m_polynomialOrder)\n      return true;\n    else\n      return false;\n  } else\n    return false;\n}\n\ntemplate <typename BasisFunctionType>\nElementVariant\nPiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::elementVariant(\n    const Entity<0> &element) const {\n  GeometryType type = element.type();\n  if (type.isLine())\n    return 2;\n  else if (type.isTriangle())\n    return 3;\n  else if (type.isQuadrilateral())\n    return 4;\n  else\n    throw std::runtime_error(\"PiecewisePolynomialDiscontinuousScalarSpace::\"\n                             \"elementVariant(): invalid geometry type, \"\n                             \"this shouldn't happen!\");\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<\n    BasisFunctionType>::setElementVariant(const Entity<0> &element,\n                                          ElementVariant variant) {\n  if (variant != elementVariant(element))\n    // for this space, the element variants are unmodifiable,\n    throw std::runtime_error(\"PiecewisePolynomialDiscontinuousScalarSpace::\"\n                             \"setElementVariant(): invalid variant\");\n}\n\ntemplate <typename BasisFunctionType>\nshared_ptr<const Space<BasisFunctionType>>\nPiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    discontinuousSpace(const shared_ptr<const Space<BasisFunctionType>> &self)\n    const {\n  if (self.get() != this)\n    throw std::invalid_argument(\n        \"PiecewisePolynomialDiscontinuousScalarSpace::discontinuousSpace(): \"\n        \"argument should be a shared pointer to *this\");\n  return self;\n}\n\ntemplate <typename BasisFunctionType>\nbool PiecewisePolynomialDiscontinuousScalarSpace<\n    BasisFunctionType>::isDiscontinuous() const {\n  return true;\n}\n\ntemplate <typename BasisFunctionType>\nvoid\nPiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::assignDofsImpl(\n    const GridSegment &segment, int dofMode) {\n  const int gridDim = this->domainDimension();\n  if (gridDim != 2)\n    throw std::runtime_error(\"PiecewisePolynomialDiscontinuousScalarSpace::\"\n                             \"assignDofsImpl(): only 2-dimensional grids \"\n                             \"are supported at present\");\n  const int vertexCodim = 2, edgeCodim = 1, elementCodim = 0;\n  const Mapper &elementMapper = m_view->elementMapper();\n  const IndexSet &indexSet = m_view->indexSet();\n\n  int elementCount = m_view->entityCount(0);\n\n  const int localDofCountPerTriangle =\n      (m_polynomialOrder + 1) * (m_polynomialOrder + 2) / 2;\n  const int localDofCountPerQuad =\n      (m_polynomialOrder + 1) * (m_polynomialOrder + 1);\n\n  BoundingBox<CoordinateType> model;\n  model.lbound.x = std::numeric_limits<CoordinateType>::max();\n  model.lbound.y = std::numeric_limits<CoordinateType>::max();\n  model.lbound.z = std::numeric_limits<CoordinateType>::max();\n  model.ubound.x = -std::numeric_limits<CoordinateType>::max();\n  model.ubound.y = -std::numeric_limits<CoordinateType>::max();\n  model.ubound.z = -std::numeric_limits<CoordinateType>::max();\n  m_globalDofBoundingBoxes.reserve(localDofCountPerQuad * elementCount);\n\n  // (Re)initialise DOF maps\n  m_local2globalDofs.clear();\n  m_local2globalDofs.resize(elementCount);\n  m_global2localDofs.clear();\n  // estimated number of global DOFs\n  m_global2localDofs.reserve(localDofCountPerQuad * elementCount);\n\n  // Fill in global<->local dof maps\n  std::unique_ptr<EntityIterator<0>> it = m_view->entityIterator<0>();\n  arma::Mat<CoordinateType> vertices;\n  arma::Col<CoordinateType> dofPosition;\n  GlobalDofIndex globalDofCount = 0;\n  while (!it->finished()) {\n    const Entity<0> &element = it->entity();\n    EntityIndex elementIndex = elementMapper.entityIndex(element);\n    bool elementContained = !(dofMode & ELEMENT_ON_SEGMENT) ||\n                            segment.contains(elementCodim, elementIndex);\n    typedef arma::Col<CoordinateType> Col;\n    const Geometry &geo = element.geometry();\n    geo.getCorners(vertices);\n    int vertexCount = vertices.n_cols;\n    int localDofCount =\n        vertexCount == 3 ? localDofCountPerTriangle : localDofCountPerQuad;\n\n    // List of global DOF indices corresponding to the local DOFs of the\n    // current element\n    std::vector<GlobalDofIndex> &globalDofs = m_local2globalDofs[elementIndex];\n    globalDofs.resize(localDofCount);\n    // GlobalDofIndex gdofStart = globalDofCount;\n    // for (int i = 0; i < localDofCount; ++i) {\n    //     globalDofs.push_back(globalDofCount);\n    //     std::vector<LocalDof> localDofs(1, LocalDof(elementIndex, i));\n    //     m_global2localDofs.push_back(localDofs);\n    //     ++globalDofCount;\n    // }\n    // GlobalDofIndex gdofEnd = globalDofCount;\n\n    // Bounding boxes\n    BoundingBox<CoordinateType> bbox = model;\n    extendBoundingBox(bbox, vertices);\n    // m_globalDofBoundingBoxes.insert(m_globalDofBoundingBoxes.end(),\n    //                                 localDofCount, bbox);\n    if (vertexCount == 3) {\n      int subEntityIndex;\n      int ldof;\n\n      if (m_polynomialOrder == 0) {\n        ldof = 0;\n        if (segment.contains(0, elementIndex)) {\n          acc(globalDofs, ldof) = globalDofCount;\n          std::vector<LocalDof> localDofs(1, LocalDof(elementIndex, ldof));\n          m_global2localDofs.push_back(localDofs);\n          m_globalDofBoundingBoxes.push_back(bbox);\n          setBoundingBoxReference<CoordinateType>(\n              acc(m_globalDofBoundingBoxes, globalDofCount),\n              (vertices.col(0) + vertices(1) + vertices(2)) / 3);\n          ++globalDofCount;\n        } else\n          acc(globalDofs, ldof) = -1;\n      } else {\n        // vertex dofs\n        ldof = 0;\n        subEntityIndex = indexSet.subEntityIndex(element, 0, vertexCodim);\n        if (elementContained &&\n            (!(dofMode & REFERENCE_POINT_ON_SEGMENT) ||\n             segment.contains(vertexCodim, subEntityIndex))) {\n          acc(globalDofs, ldof) = globalDofCount;\n          std::vector<LocalDof> localDofs(1, LocalDof(elementIndex, ldof));\n          m_global2localDofs.push_back(localDofs);\n          m_globalDofBoundingBoxes.push_back(bbox);\n          setBoundingBoxReference<CoordinateType>(\n              acc(m_globalDofBoundingBoxes, globalDofCount), vertices.col(0));\n          ++globalDofCount;\n        } else\n          acc(globalDofs, ldof) = -1;\n\n        ldof = m_polynomialOrder;\n        subEntityIndex = indexSet.subEntityIndex(element, 1, vertexCodim);\n        if (elementContained &&\n            (!(dofMode & REFERENCE_POINT_ON_SEGMENT) ||\n             segment.contains(vertexCodim, subEntityIndex))) {\n          acc(globalDofs, ldof) = globalDofCount;\n          std::vector<LocalDof> localDofs(1, LocalDof(elementIndex, ldof));\n          m_global2localDofs.push_back(localDofs);\n          m_globalDofBoundingBoxes.push_back(bbox);\n          setBoundingBoxReference<CoordinateType>(\n              acc(m_globalDofBoundingBoxes, globalDofCount), vertices.col(1));\n          ++globalDofCount;\n        } else\n          acc(globalDofs, ldof) = -1;\n\n        ldof = localDofCount - 1;\n        subEntityIndex = indexSet.subEntityIndex(element, 2, vertexCodim);\n        if (elementContained &&\n            (!(dofMode & REFERENCE_POINT_ON_SEGMENT) ||\n             segment.contains(vertexCodim, subEntityIndex))) {\n          acc(globalDofs, ldof) = globalDofCount;\n          std::vector<LocalDof> localDofs(1, LocalDof(elementIndex, ldof));\n          m_global2localDofs.push_back(localDofs);\n          m_globalDofBoundingBoxes.push_back(bbox);\n          setBoundingBoxReference<CoordinateType>(\n              acc(m_globalDofBoundingBoxes, globalDofCount), vertices.col(2));\n          ++globalDofCount;\n        } else\n          acc(globalDofs, ldof) = -1;\n\n        // edge dofs\n        if (m_polynomialOrder >= 2) {\n\n          subEntityIndex = indexSet.subEntityIndex(element, 0, edgeCodim);\n          if (elementContained &&\n              (!(dofMode & REFERENCE_POINT_ON_SEGMENT) ||\n               segment.contains(edgeCodim, subEntityIndex))) {\n            dofPosition = 0.5 * (vertices.col(0) + vertices.col(1));\n            for (int ldof = 1; ldof < m_polynomialOrder; ++ldof) {\n              acc(globalDofs, ldof) = globalDofCount;\n              std::vector<LocalDof> localDofs(1, LocalDof(elementIndex, ldof));\n              m_global2localDofs.push_back(localDofs);\n              m_globalDofBoundingBoxes.push_back(bbox);\n              setBoundingBoxReference<CoordinateType>(\n                  acc(m_globalDofBoundingBoxes, globalDofCount), dofPosition);\n              ++globalDofCount;\n            }\n          } else\n            for (int ldof = 1; ldof < m_polynomialOrder; ++ldof) {\n              acc(globalDofs, ldof) = -1;\n            }\n\n          subEntityIndex = indexSet.subEntityIndex(element, 1, edgeCodim);\n          if (elementContained &&\n              (!(dofMode & REFERENCE_POINT_ON_SEGMENT) ||\n               segment.contains(edgeCodim, subEntityIndex))) {\n            dofPosition = 0.5 * (vertices.col(0) + vertices.col(2));\n            for (int ldofy = 1; ldofy < m_polynomialOrder; ++ldofy) {\n              int ldof =\n                  ldofy * (m_polynomialOrder + 1) - ldofy * (ldofy - 1) / 2;\n              acc(globalDofs, ldof) = globalDofCount;\n              std::vector<LocalDof> localDofs(1, LocalDof(elementIndex, ldof));\n              m_global2localDofs.push_back(localDofs);\n              m_globalDofBoundingBoxes.push_back(bbox);\n              setBoundingBoxReference<CoordinateType>(\n                  acc(m_globalDofBoundingBoxes, globalDofCount), dofPosition);\n              ++globalDofCount;\n            }\n          } else\n            for (int ldofy = 1; ldofy < m_polynomialOrder; ++ldofy) {\n              int ldof =\n                  ldofy * (m_polynomialOrder + 1) - ldofy * (ldofy - 1) / 2;\n              acc(globalDofs, ldof) = -1;\n            }\n\n          subEntityIndex = indexSet.subEntityIndex(element, 2, edgeCodim);\n          if (elementContained &&\n              (!(dofMode & REFERENCE_POINT_ON_SEGMENT) ||\n               segment.contains(edgeCodim, subEntityIndex))) {\n            dofPosition = 0.5 * (vertices.col(1) + vertices.col(2));\n            for (int ldofy = 1; ldofy < m_polynomialOrder; ++ldofy) {\n              int ldof = ldofy * (m_polynomialOrder + 1) -\n                         ldofy * (ldofy - 1) / 2 + (m_polynomialOrder - ldofy);\n              acc(globalDofs, ldof) = globalDofCount;\n              std::vector<LocalDof> localDofs(1, LocalDof(elementIndex, ldof));\n              m_global2localDofs.push_back(localDofs);\n              m_globalDofBoundingBoxes.push_back(bbox);\n              setBoundingBoxReference<CoordinateType>(\n                  acc(m_globalDofBoundingBoxes, globalDofCount), dofPosition);\n              ++globalDofCount;\n            }\n          } else\n            for (int ldofy = 1; ldofy < m_polynomialOrder; ++ldofy) {\n              int ldof = ldofy * (m_polynomialOrder + 1) -\n                         ldofy * (ldofy - 1) / 2 + (m_polynomialOrder - ldofy);\n              acc(globalDofs, ldof) = -1;\n            }\n\n          // dofPosition = 0.5 * (vertices.col(0) + vertices.col(1));\n          // for (int ldof = 1; ldof < m_polynomialOrder; ++ldof){\n          //     setBoundingBoxReference<CoordinateType>(\n          //         acc(m_globalDofBoundingBoxes, gdofStart + ldof),\n          // dofPosition);\n          // }\n          // dofPosition = 0.5 * (vertices.col(0) + vertices.col(2));\n          // for (int ldofy = 1; ldofy < m_polynomialOrder; ++ldofy) {\n          //     int ldof = ldofy * (m_polynomialOrder + 1) -\n          //         ldofy * (ldofy - 1) / 2;\n          //     setBoundingBoxReference<CoordinateType>(\n          //         acc(m_globalDofBoundingBoxes, gdofStart + ldof),\n          // dofPosition);\n          // }\n          // dofPosition = 0.5 * (vertices.col(1) + vertices.col(2));\n          // for (int ldofy = 1; ldofy < m_polynomialOrder; ++ldofy) {\n          //     int ldof = ldofy * (m_polynomialOrder + 1) -\n          //         ldofy * (ldofy - 1) / 2 + (m_polynomialOrder - ldofy);\n          //     setBoundingBoxReference<CoordinateType>(\n          //         acc(m_globalDofBoundingBoxes, gdofStart + ldof),\n          // dofPosition);\n          // }\n        }\n        // bubble dofs\n        if (m_polynomialOrder >= 3) {\n          if (segment.contains(elementCodim, elementIndex)) {\n            dofPosition =\n                (vertices.col(0) + vertices.col(1) + vertices.col(2)) / 3.;\n            for (int ldofy = 1; ldofy < m_polynomialOrder; ++ldofy)\n              for (int ldofx = 1; ldofx + ldofy < m_polynomialOrder; ++ldofx) {\n                int ldof = ldofy * (m_polynomialOrder + 1) -\n                           ldofy * (ldofy - 1) / 2 + ldofx;\n                acc(globalDofs, ldof) = globalDofCount;\n                std::vector<LocalDof> localDofs(1,\n                                                LocalDof(elementIndex, ldof));\n                m_global2localDofs.push_back(localDofs);\n                m_globalDofBoundingBoxes.push_back(bbox);\n                setBoundingBoxReference<CoordinateType>(\n                    acc(m_globalDofBoundingBoxes, globalDofCount), dofPosition);\n                ++globalDofCount;\n              }\n          } else\n            for (int ldofy = 1; ldofy < m_polynomialOrder; ++ldofy)\n              for (int ldofx = 1; ldofx + ldofy < m_polynomialOrder; ++ldofx) {\n                int ldof = ldofy * (m_polynomialOrder + 1) -\n                           ldofy * (ldofy - 1) / 2 + ldofx;\n                acc(globalDofs, ldof) = -1;\n              }\n\n          // dofPosition = (vertices.col(0) + vertices.col(1) +\n          //                vertices.col(2)) / 3.;\n          // for (int ldofy = 1; ldofy < m_polynomialOrder; ++ldofy)\n          //     for (int ldofx = 1; ldofx + ldofy < m_polynomialOrder; ++ldofx)\n          // {\n          //         int ldof = ldofy * (m_polynomialOrder + 1) -\n          //             ldofy * (ldofy - 1) / 2 + ldofx;\n          //         setBoundingBoxReference<CoordinateType>(\n          //             acc(m_globalDofBoundingBoxes, gdofStart + ldof),\n          //             dofPosition);\n          //     }\n        }\n      }\n    }\n\n    it->next();\n  }\n\n  // Initialize the container mapping the flat local dof indices to\n  // local dof indices\n  SpaceHelper<BasisFunctionType>::initializeLocal2FlatLocalDofMap(\n      m_flatLocalDofCount, m_local2globalDofs, m_flatLocal2localDofs);\n\n#ifndef NDEBUG\n  for (size_t i = 0; i < m_globalDofBoundingBoxes.size(); ++i) {\n    const BoundingBox<CoordinateType> &bbox = acc(m_globalDofBoundingBoxes, i);\n\n    assert(bbox.reference.x >= bbox.lbound.x);\n    assert(bbox.reference.y >= bbox.lbound.y);\n    assert(bbox.reference.z >= bbox.lbound.z);\n    assert(bbox.reference.x <= bbox.ubound.x);\n    assert(bbox.reference.y <= bbox.ubound.y);\n    assert(bbox.reference.z <= bbox.ubound.z);\n  }\n#endif // NDEBUG\n}\n\ntemplate <typename BasisFunctionType>\nsize_t\nPiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::globalDofCount()\n    const {\n  return m_global2localDofs.size();\n}\n\ntemplate <typename BasisFunctionType>\nsize_t PiecewisePolynomialDiscontinuousScalarSpace<\n    BasisFunctionType>::flatLocalDofCount() const {\n  return m_flatLocalDofCount;\n}\n\ntemplate <typename BasisFunctionType>\nvoid\nPiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::getGlobalDofs(\n    const Entity<0> &element, std::vector<GlobalDofIndex> &dofs) const {\n  const Mapper &mapper = m_view->elementMapper();\n  EntityIndex index = mapper.entityIndex(element);\n  dofs = m_local2globalDofs[index];\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    global2localDofs(const std::vector<GlobalDofIndex> &globalDofs,\n                     std::vector<std::vector<LocalDof>> &localDofs) const {\n  localDofs.resize(globalDofs.size());\n  for (size_t i = 0; i < globalDofs.size(); ++i)\n    localDofs[i] = m_global2localDofs[globalDofs[i]];\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    flatLocal2localDofs(const std::vector<FlatLocalDofIndex> &flatLocalDofs,\n                        std::vector<LocalDof> &localDofs) const {\n  localDofs.resize(flatLocalDofs.size());\n  for (size_t i = 0; i < flatLocalDofs.size(); ++i)\n    localDofs[i] = m_flatLocal2localDofs[flatLocalDofs[i]];\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    getGlobalDofPositions(std::vector<Point3D<CoordinateType>> &positions)\n    const {\n  positions.resize(m_globalDofBoundingBoxes.size());\n  for (size_t i = 0; i < m_globalDofBoundingBoxes.size(); ++i)\n    acc(positions, i) = acc(m_globalDofBoundingBoxes, i).reference;\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    getFlatLocalDofPositions(std::vector<Point3D<CoordinateType>> &positions)\n    const {\n  getGlobalDofPositions(positions);\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    getGlobalDofBoundingBoxes(std::vector<BoundingBox<CoordinateType>> &bboxes)\n    const {\n  bboxes = m_globalDofBoundingBoxes;\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    getFlatLocalDofBoundingBoxes(\n        std::vector<BoundingBox<CoordinateType>> &bboxes) const {\n  getGlobalDofBoundingBoxes(bboxes);\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    getGlobalDofNormals(std::vector<Point3D<CoordinateType>> &normals) const {\n  SpaceHelper<BasisFunctionType>::getGlobalDofNormals_defaultImplementation(\n      *m_view, m_global2localDofs, normals);\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::\n    getFlatLocalDofNormals(std::vector<Point3D<CoordinateType>> &normals)\n    const {\n  getGlobalDofNormals(normals);\n}\n\ntemplate <typename BasisFunctionType>\nvoid\nPiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>::dumpClusterIds(\n    const char *fileName,\n    const std::vector<unsigned int> &clusterIdsOfDofs) const {\n  dumpClusterIdsEx(fileName, clusterIdsOfDofs, GLOBAL_DOFS);\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialDiscontinuousScalarSpace<\n    BasisFunctionType>::dumpClusterIdsEx(const char *fileName,\n                                         const std::vector<unsigned int> &\n                                             clusterIdsOfDofs,\n                                         DofType dofType) const {\n  throw std::runtime_error(\"PiecewisePolynomialDiscontinuousScalarSpace::\"\n                           \"dumpClusterIdsEx(): not implemented yet\");\n}\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS(\n    PiecewisePolynomialDiscontinuousScalarSpace);\n\n} // namespace Bempp\n", "meta": {"hexsha": "d0bb72c7a7a09917c81fdf3f8849bb41eac75300", "size": 25354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/space/piecewise_polynomial_discontinuous_scalar_space.cpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/space/piecewise_polynomial_discontinuous_scalar_space.cpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/space/piecewise_polynomial_discontinuous_scalar_space.cpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7693574959, "max_line_length": 80, "alphanum_fraction": 0.6658121007, "num_tokens": 6376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22575051571482055}}
{"text": "#ifndef STAN_MATH_TORSTEN_MIXODE1CPTMODEL_RK45_HPP\n#define STAN_MATH_TORSTEN_MIXODE1CPTMODEL_RK45_HPP\n\n#include <Eigen/Dense>\n#include <stan/math/torsten/PKModel/PKModel.hpp>\n#include <stan/math/torsten/PKModel/functors/mix1_functor.hpp>\n#include <stan/math/torsten/PKModel/Pred/Pred1_mix1.hpp>\n#include <stan/math/torsten/PKModel/Pred/PredSS_mix1.hpp>\n// #include <stan/math/torsten/PKModel/Pred/PredSS_err.hpp>\n#include <boost/math/tools/promotion.hpp>\n#include <vector>\n\nnamespace torsten {\n\n/**\n * Compute the predicted amounts in each compartment at each event\n * of an ODEs model. The model contains a base 1 Compartment PK\n * component which gets solved analytically, while the other ODEs\n * are solved numerically using stan::math::integrate_ode_rk45. This\n * amounts to using the mixed solver method.\n *\n * <b>Warning:</b> This prototype does not handle steady state events.\n *\n * @tparam T0 type of scalar for time of events.\n * @tparam T1 type of scalar for amount at each event.\n * @tparam T2 type of scalar for rate at each event.\n * @tparam T3 type of scalar for inter-dose inteveral at each event.\n * @tparam T4 type of scalars for the model parameters.\n * @tparam T5 type of scalars for the bio-variability parameters.\n * @tparam T6 type of scalars for the model tlag parameters.\n * @tparam F type of ODE system function.\n * @param[in] f functor for base ordinary differential equation\n *            which gets solved numerically.\n * @param[in] nOde number of ODEs we solve numerically.\n * @param[in] time times of events\n * @param[in] amt amount at each event\n * @param[in] rate rate at each event\n * @param[in] ii inter-dose interval at each event\n * @param[in] evid event identity:\n *                    (0) observation\n *                    (1) dosing\n *                    (2) other\n *                    (3) reset\n *                    (4) reset AND dosing\n * @param[in] cmt compartment number at each event\n * @param[in] addl additional dosing at each event\n * @param[in] ss steady state approximation at each event (0: no, 1: yes)\n * @param[in] theta vector of ODE parameters\n * @param[in] biovar bio-availability in each compartment\n * @param[in] tlag lag time in each compartment\n * @param[in] rel_tol relative tolerance for the Boost ode solver\n * @param[in] abs_tol absolute tolerance for the Boost ode solver\n * @param[in] max_num_steps maximal number of steps to take within\n *            the Boost ode solver\n * @return a matrix with predicted amount in each compartment\n *         at each event.\n *\n * FIX ME: msg should be passed on to functor (allows use of\n * print statement inside ODE system).\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nmixOde1CptModel_rk45(const F& f,\n                     const int nOde,\n                     const std::vector<T0>& time,\n                     const std::vector<T1>& amt,\n                     const std::vector<T2>& rate,\n                     const std::vector<T3>& ii,\n                     const std::vector<int>& evid,\n                     const std::vector<int>& cmt,\n                     const std::vector<int>& addl,\n                     const std::vector<int>& ss,\n                     const std::vector<std::vector<T4> >& theta,\n                     const std::vector<std::vector<T5> >& biovar,\n                     const std::vector<std::vector<T6> >& tlag,\n                     std::ostream* msgs = 0,\n                     double rel_tol = 1e-6,\n                     double abs_tol = 1e-6,\n                     long int max_num_steps = 1e6) {  // NOLINT(runtime/int)\n  using std::vector;\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using boost::math::tools::promote_args;\n\n  int nPK = 2;\n\n  // check arguments\n  static const char* function(\"mixOde1CptModel_rk45\");\n  torsten::pmetricsCheck(time, amt, rate, ii, evid, cmt, addl, ss,\n                theta, biovar, tlag, function);\n\n  // Construct dummy array of matrix for last argument of pred\n  Matrix<T4, Dynamic, Dynamic> dummy_system;\n  vector<Matrix<T4, Dynamic, Dynamic> > dummy_systems(1, dummy_system);\n\n  typedef mix1_functor<F> F0;\n\n  return Pred(time, amt, rate, ii, evid, cmt, addl, ss,\n              theta, biovar, tlag, nPK + nOde, dummy_systems,\n              Pred1_mix1<F0>(F0(f), rel_tol, abs_tol, max_num_steps, msgs,\n                             \"rk45\"),\n              PredSS_mix1<F0>(F0(f), rel_tol, abs_tol, max_num_steps, msgs,\n                              \"rk45\", nOde));\n}\n\n/**\n * Overload function to allow user to pass an std::vector for \n * theta.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n  typename T5, typename T6, typename F>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nmixOde1CptModel_rk45(const F& f,\n                     const int nOde,\n                     const std::vector<T0>& time,\n                     const std::vector<T1>& amt,\n                     const std::vector<T2>& rate,\n                     const std::vector<T3>& ii,\n                     const std::vector<int>& evid,\n                     const std::vector<int>& cmt,\n                     const std::vector<int>& addl,\n                     const std::vector<int>& ss,\n                     const std::vector<T4>& theta,\n                     const std::vector<std::vector<T5> >& biovar,\n                     const std::vector<std::vector<T6> >& tlag,\n                     std::ostream* msgs = 0,\n                     double rel_tol = 1e-6,\n                     double abs_tol = 1e-6,\n                     long int max_num_steps = 1e6) {  // NOLINT(runtime/int)\n  std::vector<std::vector<T4> > vec_theta(1, theta);\n\n  return mixOde1CptModel_rk45(f, nOde,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              vec_theta, biovar, tlag,\n                              msgs, rel_tol, abs_tol, max_num_steps);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for \n * theta and biovar.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nmixOde1CptModel_rk45(const F& f,\n                     const int nOde,\n                     const std::vector<T0>& time,\n                     const std::vector<T1>& amt,\n                     const std::vector<T2>& rate,\n                     const std::vector<T3>& ii,\n                     const std::vector<int>& evid,\n                     const std::vector<int>& cmt,\n                     const std::vector<int>& addl,\n                     const std::vector<int>& ss,\n                     const std::vector<T4>& theta,\n                     const std::vector<T5>& biovar,\n                     const std::vector<std::vector<T6> >& tlag,\n                     std::ostream* msgs = 0,\n                     double rel_tol = 1e-6,\n                     double abs_tol = 1e-6,\n                     long int max_num_steps = 1e6) {  // NOLINT(runtime/int)\n  std::vector<std::vector<T4> > vec_theta(1, theta);\n  std::vector<std::vector<T5> > vec_biovar(1, biovar);\n\n  return mixOde1CptModel_rk45(f, nOde,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              vec_theta, vec_biovar, tlag,\n                              msgs, rel_tol, abs_tol, max_num_steps);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for \n * theta, biovar, and tlag.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nmixOde1CptModel_rk45(const F& f,\n                     const int nOde,\n                     const std::vector<T0>& time,\n                     const std::vector<T1>& amt,\n                     const std::vector<T2>& rate,\n                     const std::vector<T3>& ii,\n                     const std::vector<int>& evid,\n                     const std::vector<int>& cmt,\n                     const std::vector<int>& addl,\n                     const std::vector<int>& ss,\n                     const std::vector<T4>& theta,\n                     const std::vector<T5>& biovar,\n                     const std::vector<T6>& tlag,\n                     std::ostream* msgs = 0,\n                     double rel_tol = 1e-6,\n                     double abs_tol = 1e-6,\n                     long int max_num_steps = 1e6) {  // NOLINT(runtime/int)\n  std::vector<std::vector<T4> > vec_theta(1, theta);\n  std::vector<std::vector<T5> > vec_biovar(1, biovar);\n  std::vector<std::vector<T6> > vec_tlag(1, tlag);\n\n  return mixOde1CptModel_rk45(f, nOde,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              vec_theta, vec_biovar, vec_tlag,\n                              msgs, rel_tol, abs_tol, max_num_steps);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for \n * theta and tlag.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nmixOde1CptModel_rk45(const F& f,\n                     const int nOde,\n                     const std::vector<T0>& time,\n                     const std::vector<T1>& amt,\n                     const std::vector<T2>& rate,\n                     const std::vector<T3>& ii,\n                     const std::vector<int>& evid,\n                     const std::vector<int>& cmt,\n                     const std::vector<int>& addl,\n                     const std::vector<int>& ss,\n                     const std::vector<T4>& theta,\n                     const std::vector<std::vector<T5> >& biovar,\n                     const std::vector<T6>& tlag,\n                     std::ostream* msgs = 0,\n                     double rel_tol = 1e-6,\n                     double abs_tol = 1e-6,\n                     long int max_num_steps = 1e6) {  // NOLINT(runtime/int)\n  std::vector<std::vector<T4> > vec_theta(1, theta);\n  std::vector<std::vector<T6> > vec_tlag(1, tlag);\n\n  return mixOde1CptModel_rk45(f, nOde,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              vec_theta, biovar, vec_tlag,\n                              msgs, rel_tol, abs_tol, max_num_steps);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for \n * biovar.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nmixOde1CptModel_rk45(const F& f,\n                     const int nOde,\n                     const std::vector<T0>& time,\n                     const std::vector<T1>& amt,\n                     const std::vector<T2>& rate,\n                     const std::vector<T3>& ii,\n                     const std::vector<int>& evid,\n                     const std::vector<int>& cmt,\n                     const std::vector<int>& addl,\n                     const std::vector<int>& ss,\n                     const std::vector<std::vector<T4> >& theta,\n                     const std::vector<T5>& biovar,\n                     const std::vector<std::vector<T6> >& tlag,\n                     std::ostream* msgs = 0,\n                     double rel_tol = 1e-6,\n                     double abs_tol = 1e-6,\n                     long int max_num_steps = 1e6) {  // NOLINT(runtime/int)\n  std::vector<std::vector<T5> > vec_biovar(1, biovar);\n\n  return mixOde1CptModel_rk45(f, nOde,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              theta, vec_biovar, tlag,\n                              msgs, rel_tol, abs_tol, max_num_steps);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for \n * biovar and tlag.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nmixOde1CptModel_rk45(const F& f,\n                     const int nOde,\n                     const std::vector<T0>& time,\n                     const std::vector<T1>& amt,\n                     const std::vector<T2>& rate,\n                     const std::vector<T3>& ii,\n                     const std::vector<int>& evid,\n                     const std::vector<int>& cmt,\n                     const std::vector<int>& addl,\n                     const std::vector<int>& ss,\n                     const std::vector<std::vector<T4> >& theta,\n                     const std::vector<T5>& biovar,\n                     const std::vector<T6>& tlag,\n                     std::ostream* msgs = 0,\n                     double rel_tol = 1e-6,\n                     double abs_tol = 1e-6,\n                     long int max_num_steps = 1e6) {  // NOLINT(runtime/int)\n  std::vector<std::vector<T5> > vec_biovar(1, biovar);\n  std::vector<std::vector<T6> > vec_tlag(1, tlag);\n\n  return mixOde1CptModel_rk45(f, nOde,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              theta, vec_biovar, vec_tlag,\n                              msgs, rel_tol, abs_tol, max_num_steps);\n}\n\n\n/**\n * Overload function to allow user to pass an std::vector for \n * tlag.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6, typename F>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nmixOde1CptModel_rk45(const F& f,\n                     const int nOde,\n                     const std::vector<T0>& time,\n                     const std::vector<T1>& amt,\n                     const std::vector<T2>& rate,\n                     const std::vector<T3>& ii,\n                     const std::vector<int>& evid,\n                     const std::vector<int>& cmt,\n                     const std::vector<int>& addl,\n                     const std::vector<int>& ss,\n                     const std::vector<std::vector<T4> >& theta,\n                     const std::vector<std::vector<T5> >& biovar,\n                     const std::vector<T6>& tlag,\n                     std::ostream* msgs = 0,\n                     double rel_tol = 1e-6,\n                     double abs_tol = 1e-6,\n                     long int max_num_steps = 1e6) {  // NOLINT(runtime/int)\n  std::vector<std::vector<T6> > vec_tlag(1, tlag);\n\n  return mixOde1CptModel_rk45(f, nOde,\n                              time, amt, rate, ii, evid, cmt, addl, ss,\n                              theta, biovar, vec_tlag,\n                              msgs, rel_tol, abs_tol, max_num_steps);\n}\n\n}\n#endif\n", "meta": {"hexsha": "d3ba83771498d2fa06c3c422f34e978509e242dc", "size": 15691, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/mixOde1CptModel_rk45.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/mixOde1CptModel_rk45.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/mixOde1CptModel_rk45.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2, "max_line_length": 76, "alphanum_fraction": 0.547575043, "num_tokens": 4042, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22570049469200587}}
{"text": "#pragma once\n#include <string>\n#include <trajopt_sco/modeling.hpp>\n#include <boost/function.hpp>\n/*\n * Algorithms for non-convex, constrained optimization\n */\n\nnamespace sco {\n\nusing std::string;\nusing std::vector;\n\n\nenum OptStatus {\n  OPT_CONVERGED,\n  OPT_SCO_ITERATION_LIMIT, // hit iteration limit before convergence\n  OPT_PENALTY_ITERATION_LIMIT,\n  OPT_FAILED,\n  INVALID\n};\nstatic const char* OptStatus_strings[]  = {\n  \"CONVERGED\",\n  \"SCO_ITERATION_LIMIT\",\n  \"PENALTY_ITERATION_LIMIT\",\n  \"FAILED\",\n  \"INVALID\"\n};\ninline string statusToString(OptStatus status) {\n  return OptStatus_strings[status];\n}\n\n\nstruct OptResults {\n  DblVec x; // solution estimate\n  OptStatus status;\n  double total_cost;\n  vector<double> cost_vals;\n  DblVec cnt_viols;\n  int n_func_evals, n_qp_solves;\n  void clear() {\n    x.clear();\n    status = INVALID;\n    cost_vals.clear();\n    cnt_viols.clear();\n    n_func_evals = 0;\n    n_qp_solves = 0;\n  }\n  OptResults() {clear();}\n};\nstd::ostream& operator<<(std::ostream& o, const OptResults& r);\n\nclass Optimizer {\n  /*\n   * Solves an optimization problem\n   */\npublic:\n  virtual OptStatus optimize() = 0;\n  virtual ~Optimizer() {}\n  virtual void setProblem(OptProbPtr prob) {prob_ = prob;}\n  void initialize(const vector<double>& x);\n  vector<double>& x() {return results_.x;}\n  OptResults& results() {return results_;}\n\n  typedef boost::function<void(OptProb*, DblVec&)> Callback;\n  void addCallback(const Callback& f); // called before each iteration\nprotected:\n  vector<Callback> callbacks_;\n  void callCallbacks(DblVec& x);\n  OptProbPtr prob_;\n  OptResults results_;\n};\n\nclass BasicTrustRegionSQP : public Optimizer {\n  /*\n   * Alternates between convexifying objectives and constraints and then solving convex subproblem\n   * Uses a merit function to decide whether or not to accept the step\n   * merit function = objective + merit_err_coeff * | constraint_error |\n   * Note: sometimes the convexified objectives and constraints lead to an infeasible subproblem\n   * In that case, you should turn them into penalties and solve that problem\n   * (todo: implement penalty-based sqp that gracefully handles infeasible constraints)\n   */\npublic:\n  double improve_ratio_threshold_, // minimum ratio true_improve/approx_improve to accept step\n         min_trust_box_size_, // if trust region gets any smaller, exit and report convergence\n         min_approx_improve_, // if model improves less than this, exit and report convergence\n         min_approx_improve_frac_, // if model improves less than this, exit and report convergence\n         max_iter_,\n         trust_shrink_ratio_, // if improvement is less than improve_ratio_threshold, shrink trust region by this ratio\n         trust_expand_ratio_, // see above\n         cnt_tolerance_, // after convergence of penalty subproblem, if constraint violation is less than this, we're done\n         max_merit_coeff_increases_, // number of times that we jack up penalty coefficient\n         merit_coeff_increase_ratio_, // ratio that we increate coeff each time\n         max_time_ // not yet implemented\n         ;\n  double merit_error_coeff_, // initial penalty coefficient\n         trust_box_size_ // current size of trust region (component-wise)\n         ;\n\n  BasicTrustRegionSQP();\n  BasicTrustRegionSQP(OptProbPtr prob);\n  void setProblem(OptProbPtr prob);\n  OptStatus optimize();\nprotected:\n  void adjustTrustRegion(double ratio);\n  void setTrustBoxConstraints(const vector<double>& x);\n  void initParameters();\n  ModelPtr model_;\n};\n\n\n}\n", "meta": {"hexsha": "d5eab3c79a6b10531133865f90611aa338c38f1c", "size": 3519, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "trajopt_sco/include/trajopt_sco/optimizers.hpp", "max_stars_repo_name": "Levi-Armstrong/trajopt_ros", "max_stars_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T14:43:43.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-09T16:41:36.000Z", "max_issues_repo_path": "trajopt_sco/include/trajopt_sco/optimizers.hpp", "max_issues_repo_name": "Levi-Armstrong/trajopt_ros", "max_issues_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T04:57:34.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-07T21:46:45.000Z", "max_forks_repo_path": "trajopt_sco/include/trajopt_sco/optimizers.hpp", "max_forks_repo_name": "Levi-Armstrong/trajopt_ros", "max_forks_repo_head_hexsha": "a90cd90478d4048af501ad503360d8dfd7460f20", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1415929204, "max_line_length": 122, "alphanum_fraction": 0.7289002558, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22567060249536305}}
{"text": "/*\n\nCandyPoker\nhttps://github.com/sweeterthancandy/CandyPoker\n\nMIT License\n\nCopyright (c) 2019 Gerry Candy\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*/\n#include \"ps/eval/binary_strategy_description.h\"\n#include <thread>\n#include <numeric>\n#include <atomic>\n#include <bitset>\n#include <fstream>\n#include <unordered_map>\n\n#include <boost/format.hpp>\n#include <boost/assert.hpp>\n\n#include \"app/pretty_printer.h\"\n#include \"ps/base/algorithm.h\"\n#include \"ps/base/board_combination_iterator.h\"\n#include \"ps/base/cards.h\"\n#include \"ps/base/cards.h\"\n#include \"ps/base/frontend.h\"\n#include \"ps/base/holdem_board_decl.h\"\n#include \"ps/base/rank_hasher.h\"\n#include \"ps/base/suit_hasher.h\"\n#include \"ps/base/tree.h\"\n\n#include \"ps/detail/tree_printer.h\"\n\n#include \"ps/eval/class_cache.h\"\n#include \"ps/eval/pass_mask_eval.h\"\n#include \"ps/eval/instruction.h\"\n\n#include \"ps/support/config.h\"\n#include \"ps/support/index_sequence.h\"\n\n#include <boost/timer/timer.hpp>\n\n#include <boost/log/trivial.hpp>\n\n#include <Eigen/Dense>\n\n#include \"ps/support/command.h\"\n\n#include <boost/iterator/indirect_iterator.hpp>\n#include \"ps/eval/holdem_class_vector_cache.h\"\n\nnamespace ps{\n\n\n\n        struct static_event : binary_strategy_description::event_decl{\n                explicit static_event(std::string const& key, Eigen::VectorXd vec):\n                        key_{key}, vec_{vec}\n                {}\n                virtual std::string key()const override{ return key_; }\n                virtual void expected_value_given_event(Eigen::VectorXd& out, holdem_class_vector const& cv, double p)const override{\n                        for(size_t idx=0;idx!=vec_.size();++idx){\n                                out[idx] += vec_[idx] * p;\n                        }\n                }\n                virtual std::string to_string()const override{\n                        std::stringstream sstr;\n                        sstr << \"Static{key=\" << key_ << \", vec_=\" << vector_to_string(vec_) << \"}\";\n                        return sstr.str();\n                }\n        private:\n                std::string key_;\n                Eigen::VectorXd vec_;\n        };\n        struct eval_event : binary_strategy_description::event_decl{\n                enum{ Debug = 0 };\n                /*\n                        perm is the vector of players who are in the hand, ie for hu eval\n                        it will always be {0,1}, whilst for three players it colud be\n                        {0,1}, {0,2}, {1,2}, or {1,2,3}.\n                 */\n                explicit\n                eval_event( binary_strategy_description::eval_view* eval, \n                            std::string const& key,\n                           std::vector<size_t> perm,\n                           Eigen::VectorXd const& dead_money,\n                           Eigen::VectorXd const& active)\n                        :eval_{eval}, key_(key), perm_{perm}, dead_money_{dead_money}, active_{active}\n                        ,pot_amt_{active_.sum() + dead_money_.sum()}\n                {\n\n                        delta_proto_.resize(dead_money_.size()+1);\n                        delta_proto_.fill(0);\n                        for(size_t idx=0;idx!=active_.size();++idx){\n                                delta_proto_[idx] -= active_[idx];\n                                delta_proto_[idx] -= dead_money_[idx];\n                        }\n                        \n                        if( Debug ){\n                                std::cout << \"perm => \" << detail::to_string(perm) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,perm)\n                                std::cout << \"dead_money_ => \" << vector_to_string(dead_money_) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,dead_money_)\n                                std::cout << \"active_ => \" << vector_to_string(active_) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,active_)\n                                std::cout << \"delta_proto_ => \" << vector_to_string(delta_proto_) << \"\\n\"; // __CandyPrint__(cxx-print-scalar,delta_proto_)\n                                std::cout << \"pot_amt_ => \" << pot_amt_ << \"\\n\"; // __CandyPrint__(cxx-print-scalar,pot_amt_)\n                        }\n\n                }\n                virtual std::string key()const override{ return key_; }\n                virtual void expected_value_given_event(Eigen::VectorXd& out, holdem_class_vector const& cv, double p)const override{\n\n                        // short circuit for optimization purposes\n                        if( std::fabs(p) < 0.001 )\n                                return;\n\n                        #if 0\n                        struct stride_view{\n                                enum{ MaxSize = 9 };\n                                void construct(std::vector<size_t> mask_, holdem_id* first, holdem_id* last){\n                                        first_ = first;\n                                        last_ = last;\n                                }\n                        private:\n                                std::array<size_t, 9> view_;\n                        };\n                        #endif\n\n                        /*\n                                We have a perm of the players involed in the hold, perhaps P = (1,2).\n                                What we need to do it then map this perm, so that\n                                        CV[S[P[0]]] < CV[S[P[0]]],\n                         */\n\n                        std::array<size_t, 9> re_perm;\n                        std::copy(perm_.begin(), perm_.end(), re_perm.begin());\n                        auto re_perm_end = re_perm.begin() + perm_.size();\n                        std::sort(re_perm.begin(), re_perm_end, [&](size_t l, size_t r){\n                                return cv[l] < cv[r];\n                        });\n\n\n                        std::array<holdem_class_id, 9> tmp;\n                        for(size_t idx=0;idx!=perm_.size();++idx){\n                                tmp[idx] = cv[re_perm[idx]];\n                        }\n                        \n                        support::array_view<holdem_class_id> tmp_view(&tmp[0], perm_.size());\n                        auto ev_ptr = eval_->eval_no_perm(tmp_view);\n                        auto const& ev = *ev_ptr;\n                        \n                        out += delta_proto_ * p;\n\n                        size_t ev_idx = 0;\n                        for(size_t idx=0;idx!=perm_.size();++idx){\n                                out[re_perm[idx]] += pot_amt_ * ev[ev_idx] * p;\n                                ++ev_idx;\n                        }\n                }\n                virtual std::string to_string()const override{\n                        std::stringstream sstr;\n                        sstr << std::fixed;\n                        sstr << \"Eval  {key=\" << key_ << \", perm=\" << detail::to_string(perm_) \n                                << \", dead=\" << vector_to_string(dead_money_)\n                                << \", active=\" << vector_to_string(active_)\n                                << \", proto=\" << vector_to_string(delta_proto_)\n                                << \", pot=\" << pot_amt_ \n                                << \"}\";\n                        return sstr.str();\n                }\n        private:\n                binary_strategy_description::eval_view* eval_;\n                std::string key_;\n                std::vector<size_t> perm_;\n                Eigen::VectorXd dead_money_; // not used\n                Eigen::VectorXd active_; // not used\n                Eigen::VectorXd delta_proto_;\n                double pot_amt_;\n        };\n\n\n        struct heads_up_description : binary_strategy_description{\n                heads_up_description(eval_view* eval, double sb, double bb, double eff)\n                        : sb_{sb}, bb_{bb}, eff_{eff}\n                {\n                        eval_ = eval;\n\n\n\n                        Eigen::VectorXd v_f_{2};\n                        v_f_(0) = -sb_;\n                        v_f_(1) =  sb_;\n                        auto n_f_ = std::make_shared<static_event>(\"f\", v_f_);\n                        events_.push_back(n_f_);\n\n                        Eigen::VectorXd v_pf{2};\n                        v_pf(0) =  bb_;\n                        v_pf(1) = -bb_;\n                        auto n_pf = std::make_shared<static_event>(\"pf\", v_pf);\n                        events_.push_back(n_pf);\n\n                        Eigen::VectorXd dead_money = Eigen::VectorXd::Zero(2);\n                        Eigen::VectorXd active{2};\n                        active[0] = eff_;\n                        active[1] = eff_;\n                        auto n_pp = std::make_shared<eval_event>(eval_, \"pp\", std::vector<size_t>{0,1}, dead_money, active);\n                        events_.push_back(n_pp);\n\n                        strats_.emplace_back(this, 0,0, \"SB Pushing\", \"\");\n                        strats_.emplace_back(this, 1,1, \"BB Calling, given a SB push\", \"p\");\n                        \n                        finish();\n                }\n                virtual strategy_impl_t make_inital_state()const override{\n                        Eigen::VectorXd proto(169);\n                        proto.fill(0.0);\n                        strategy_impl_t vec;\n                        vec.emplace_back(proto);\n                        vec.emplace_back(proto);\n                        return vec;\n                }\n                virtual double sb()const{ return sb_; }\n                virtual double bb()const{ return bb_; }\n                virtual double eff()const{ return eff_; }\n                virtual size_t num_players()const{ return 2; }\n                virtual size_t strat_vector_size()const{ return 2; }\n                \n                virtual double probability_of_event(std::string const& key, holdem_class_vector const& cv, strategy_impl_t const& impl)const{\n                        auto a = impl[0][cv[0]];\n                        auto b = impl[1][cv[1]];\n                        //if( key == \"p\" ){ return a; }\n                        if( key == \"f\" ){ return ( 1.0 - a); }\n                        if( key == \"pp\"){ return a * b; }\n                        if( key == \"pf\"){ return a * (1.0 - b ); }\n                        std::stringstream sstr;\n                        sstr << \"unknown key \" << key;\n                        throw std::domain_error(sstr.str());\n                }\n                virtual Eigen::VectorXd expected_value_by_class_id(size_t player_idx, strategy_impl_t const& impl)const override{\n                        Eigen::VectorXd result(169);\n                        result.fill(0);\n                        for(auto const& group : *Memory_TwoPlayerClassVector){\n                                for(auto const& _ : group.vec){\n                                        auto const& cv = _.cv;\n                                        auto ev = expected_value_of_vector(aux_event_set_, cv, impl);\n                                        result(cv[player_idx]) += _.prob * ev[player_idx];\n                                }\n                        }\n                        return result;\n                }\n                virtual Eigen::VectorXd expected_value(strategy_impl_t const& impl)const override{\n                        Eigen::VectorXd result(2);\n                        result.fill(0);\n                        for(auto const& group : *Memory_TwoPlayerClassVector){\n                                for(auto const& _ : group.vec){\n                                        auto const& cv = _.cv;\n                                        check_probability_of_event(cv, impl);\n                                        auto ev = expected_value_of_vector(aux_event_set_, cv, impl);\n                                        result[0] += _.prob * ev[0];\n                                        result[1] += _.prob * ev[1];\n                                }\n                        }\n                        return result;\n                }\n                virtual double expected_value_for_class_id_es(event_set const& es, size_t player_idx, holdem_class_id class_id, strategy_impl_t const& impl)const override{\n                        double result = 0.0;\n                        holdem_class_vector cv;\n                        for(auto const& group : *Memory_TwoPlayerClassVector){\n                                if( group.cid != class_id)\n                                        continue;\n                                for(auto const& _ : group.vec){\n                                        cv = _.cv;\n                                        if( player_idx != 0 )\n                                                std::swap(cv[0], cv[player_idx]);\n                                        auto ev = expected_value_of_vector(es, cv, impl);\n                                        result += _.prob * ev[player_idx];\n                                }\n                        }\n                        return result;\n                }\n        private:\n                double sb_;\n                double bb_;\n                double eff_;\n        };\n        \n        \n        struct three_player_description : binary_strategy_description{\n                three_player_description(eval_view* eval, double sb, double bb, double eff)\n                        : sb_{sb}, bb_{bb}, eff_{eff}\n                {\n                        eval_ = eval;\n\n\n                        size_t num_players = 3;\n                                \n\n                        Eigen::VectorXd stacks{num_players};\n                        for(size_t idx=0;idx!=num_players;++idx){\n                                stacks[idx] = eff_;\n                        }\n\n\n                        Eigen::VectorXd v_blinds{num_players};\n                        v_blinds.fill(0.0);\n                        v_blinds[1] = sb_;\n                        v_blinds[2] = bb_;\n\n                        auto make_static = [&](std::string const& key, size_t target){\n                                Eigen::VectorXd sv = -v_blinds;\n                                sv[target] += v_blinds.sum();\n                                auto ptr = std::make_shared<static_event>(key, sv);\n                                return ptr;\n                        };\n\n                        for(unsigned long long mask = ( 1 << num_players ); mask != 0;){\n                                --mask;\n                                std::bitset<32> bs = {mask};\n\n\n                                std::string key;\n                                std::vector<size_t> perm;\n                                Eigen::VectorXd dead_money = Eigen::VectorXd::Zero(3);\n                                Eigen::VectorXd active     = Eigen::VectorXd::Zero(3);\n\n                                for(size_t idx=0;idx!= num_players;++idx){\n                                        if( bs.test(idx) ){\n                                                active[idx] = stacks[idx];\n                                                perm.push_back(idx);\n                                                key += \"p\";\n                                        } else{\n                                                dead_money[idx] = v_blinds[idx];\n                                                key += \"f\";\n                                        }\n                                }\n\n                                if( bs.count() == 0 )\n                                        continue;\n                                if( bs.count() == 1 && bs.test(num_players-1) ){\n                                        // walk\n                                        std::string degenerate_key(num_players-1, 'f');\n                                        auto walk = make_static(degenerate_key, num_players-1);\n                                        events_.push_back(walk);\n                                } else if( bs.count() == 1 ){\n                                        // steal \n                                        auto steal = make_static(key, perm[0]);\n                                        events_.push_back(steal);\n                                } else { \n                                        // push call\n\n                                        auto allin = std::make_shared<eval_event>(eval_, key, perm, dead_money, active);\n                                        events_.push_back(allin);\n                                }\n                                \n                        }\n\n                        strats_.emplace_back(this, 0,0, \"BTN Pushing\"                        , \"\"  );\n                        strats_.emplace_back(this, 1,1, \"SB Calling, given BTN Push\"         , \"p\" );\n                        strats_.emplace_back(this, 2,1, \"SB Pushing, given BTN Fold\"         , \"f\" ); \n                        strats_.emplace_back(this, 3,2, \"BB Calling, given BTN Push, SB Call\", \"pp\");\n                        strats_.emplace_back(this, 4,2, \"BB Calling, given BTN Push, SB Fold\", \"pf\");\n                        strats_.emplace_back(this, 5,2, \"BB Calling, given BTN Fold, SB Push\", \"fp\");\n        \n                        finish();\n                }\n                virtual strategy_impl_t make_inital_state()const override{\n                        Eigen::VectorXd proto(169);\n                        proto.fill(.5);\n                        strategy_impl_t vec;\n                        vec.emplace_back(proto);\n                        vec.emplace_back(proto);\n                        vec.emplace_back(proto);\n                        vec.emplace_back(proto);\n                        vec.emplace_back(proto);\n                        vec.emplace_back(proto);\n                        return vec;\n                }\n                virtual double sb()const{ return sb_; }\n                virtual double bb()const{ return bb_; }\n                virtual double eff()const{ return eff_; }\n                virtual size_t num_players()const{ return 3; }\n                virtual size_t strat_vector_size()const{ return 6; }\n                \n                /*\n                         The index of the strategy vector, for example\n                         for hu index 0 is for sb to push, whilst index\n                         1 is for bb to call a push (given the action p),\n                         ie \n                                Index |Player|  key  | Given |   P\n                                ------+------+-------+-------+------\n                                  0   |   0  |   p   |       | P(p)\n                                  1   |   1  |   pp  |   p   | P(p|p)\n\n                        For three player this canonical mapping doesn't\n                        apply, we have\n                                \n                                Index |Player|  Key  | Given |   P\n                                ------+------+-------+-------+------\n                                  0   |   0  |   p   |       | P(p)\n                                  1   |   1  |   pp  |   p   | P(p|p)\n                                  2   |   1  |   fp  |   f   | P(p|f)\n                                  3   |   2  |   ppp |   pp  | P(p|pp)\n                                  4   |   2  |   pfp |   pf  | P(p|pf)\n                                  5   |   2  |   fpp |   fp  | P(p|fp)\n                */\n                virtual double probability_of_event(std::string const& key, holdem_class_vector const& cv, strategy_impl_t const& impl)const{\n                        enum{ Debug = 0 };\n                        static std::unordered_map<std::string, size_t> reg_alloc = {\n                                             //  Player\n                                { \"\"  , 0 }, //   0\n                                { \"p\" , 1 }, //   1\n                                { \"f\" , 2 }, //   1\n                                { \"pp\", 3 }, //   2\n                                { \"pf\", 4 }, //   2\n                                { \"fp\", 5 }  //   2\n                        };\n                        double result = 1.0;\n                        std::string sub;\n                        std::stringstream dbg;\n                        for(size_t idx=0;idx!=key.size();++idx){\n                                if( reg_alloc.count(sub) == 0 ){\n                                        throw std::domain_error(\"bad\");\n                                }\n                                auto reg = reg_alloc[sub];\n                                switch(key[idx]){\n                                case 'p':\n                                case 'P':\n                                {\n                                        dbg << \"P<\" << reg << \",\" << ( impl[reg][cv[idx]] ) << \">\";\n                                        result *= impl[reg][cv[idx]];\n                                        sub += 'p';\n                                        break;\n                                }\n                                case 'f':\n                                case 'F':\n                                {\n                                        dbg << \"F<\" << reg << \",\" << ( 1 - impl[reg][cv[idx]] )<<\">\";\n                                        result *= ( 1 - impl[reg][cv[idx]] );\n                                        sub += 'f';\n                                        break;\n                                }}\n                        }\n                        if( Debug ) std::cout << dbg.str() << \"\\n\";\n                        return result;\n                }\n                virtual Eigen::VectorXd expected_value_by_class_id(size_t player_idx, strategy_impl_t const& impl)const override{\n                        Eigen::VectorXd result(169);\n                        result.fill(0);\n                        for(auto const& group : *Memory_ThreePlayerClassVector){\n                                for(auto const& _ : group.vec){\n                                        auto const& cv = _.cv;\n                                        auto ev = expected_value_of_vector(aux_event_set_, cv, impl);\n                                        result(cv[player_idx]) += _.prob * ev[player_idx];\n                                }\n                        }\n                        return result;\n                }\n                virtual Eigen::VectorXd expected_value(strategy_impl_t const& impl)const override{\n                        Eigen::VectorXd result(3);\n                        result.fill(0);\n                        for(auto const& group : *Memory_ThreePlayerClassVector){\n                                for(auto const& _ : group.vec){\n                                        auto const& cv = _.cv;\n                                        auto ev = expected_value_of_vector(aux_event_set_, cv, impl);\n                                        result[0] += _.prob * ev[0];\n                                        result[1] += _.prob * ev[1];\n                                        result[2] += _.prob * ev[2];\n                                }\n                        }\n                        return result;\n                }\n                virtual double expected_value_for_class_id_es(event_set const& es, size_t player_idx, holdem_class_id class_id, strategy_impl_t const& impl)const override{\n                        double result = 0.0;\n                        holdem_class_vector cv;\n                        for(auto const& group : *Memory_ThreePlayerClassVector){\n                                if( group.cid != class_id)\n                                        continue;\n                                for(auto const& _ : group.vec){\n                                        cv = _.cv;\n                                        if( player_idx != 0 )\n                                                std::swap(cv[0], cv[player_idx]);\n                                        auto ev = expected_value_of_vector(es, cv, impl);\n                                        result += _.prob * ev[player_idx];\n                                }\n                        }\n                        return result;\n                }\n        private:\n                double sb_;\n                double bb_;\n                double eff_;\n        };\n                \n        std::shared_ptr<binary_strategy_description> binary_strategy_description::make_hu_description(eval_view* eval, double sb, double bb, double eff){\n                return std::make_shared<heads_up_description>(eval, sb, bb, eff);\n        }\n        std::shared_ptr<binary_strategy_description> binary_strategy_description::make_three_player_description(eval_view* eval, double sb, double bb, double eff){\n                return std::make_shared<three_player_description>(eval, sb, bb, eff);\n        }\n\n} // end namespace ps\n", "meta": {"hexsha": "ce3e8b706891106d4386bbcefc1fcde7978996bc", "size": 25518, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Trash/binary_strategy_description.cpp", "max_stars_repo_name": "sweeterthancandy/CandyPoker", "max_stars_repo_head_hexsha": "53dfcc92402492739a2300847aeb298d389d546a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T12:57:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-16T10:41:18.000Z", "max_issues_repo_path": "Trash/binary_strategy_description.cpp", "max_issues_repo_name": "sweeterthancandy/CandyPoker", "max_issues_repo_head_hexsha": "53dfcc92402492739a2300847aeb298d389d546a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Trash/binary_strategy_description.cpp", "max_forks_repo_name": "sweeterthancandy/CandyPoker", "max_forks_repo_head_hexsha": "53dfcc92402492739a2300847aeb298d389d546a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-01T06:05:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-01T06:05:52.000Z", "avg_line_length": 49.1676300578, "max_line_length": 171, "alphanum_fraction": 0.4051649816, "num_tokens": 4616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635841117624, "lm_q2_score": 0.3522017752483203, "lm_q1q2_score": 0.225633080529328}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\n#include \"NewtonEulerFrom1DLocalFrameR.hpp\"\n#include <boost/math/quaternion.hpp>\n#include \"NewtonEulerDS.hpp\"\n#include \"Interaction.hpp\"\n#include \"BlockVector.hpp\"\n#include <boost/math/quaternion.hpp>\n\n//#define NERI_DEBUG\n\n\n\n\n//#define NEFC3D_DEBUG\n// #define DEBUG_NOCOLOR\n// #define DEBUG_STDOUT\n// #define DEBUG_MESSAGES\n#include \"debug.h\"\n/*\nSee devNotes.pdf for details. A detailed documentation is available in DevNotes.pdf: chapter 'NewtonEulerR: computation of \\nabla q H'. Subsection 'Case FC3D: using the local frame local velocities'\n*/\nvoid NewtonEulerFrom1DLocalFrameR::NIcomputeJachqTFromContacts(SP::SiconosVector q1)\n{\n  double Nx = _Nc->getValue(0);\n  double Ny = _Nc->getValue(1);\n  double Nz = _Nc->getValue(2);\n  double Px = _Pc1->getValue(0);\n  double Py = _Pc1->getValue(1);\n  double Pz = _Pc1->getValue(2);\n  double G1x = q1->getValue(0);\n  double G1y = q1->getValue(1);\n  double G1z = q1->getValue(2);\n#ifdef NEFC3D_DEBUG\n  printf(\"contact normal:\\n\");\n  _Nc->display();\n  printf(\"point de contact :\\n\");\n  _Pc1->display();\n  printf(\"center of masse :\\n\");\n  q1->display();\n#endif\n  _RotationAbsToContactFrame->setValue(0, 0, Nx);\n  _RotationAbsToContactFrame->setValue(0, 1, Ny);\n  _RotationAbsToContactFrame->setValue(0, 2, Nz);\n\n  _NPG1->zero();\n\n  (*_NPG1)(0, 0) = 0;\n  (*_NPG1)(0, 1) = -(G1z - Pz);\n  (*_NPG1)(0, 2) = (G1y - Py);\n  (*_NPG1)(1, 0) = (G1z - Pz);\n  (*_NPG1)(1, 1) = 0;\n  (*_NPG1)(1, 2) = -(G1x - Px);\n  (*_NPG1)(2, 0) = -(G1y - Py);\n  (*_NPG1)(2, 1) = (G1x - Px);\n  (*_NPG1)(2, 2) = 0;\n\n\n  computeRotationMatrix(q1,_rotationMatrixAbsToBody);\n  prod(*_NPG1, *_rotationMatrixAbsToBody, *_AUX1, true);\n\n  prod(*_RotationAbsToContactFrame, *_AUX1, *_AUX2, true);\n\n\n  for (unsigned int jj = 0; jj < 3; jj++)\n    _jachqT->setValue(0, jj, _RotationAbsToContactFrame->getValue(0, jj));\n\n  for (unsigned int jj = 3; jj < 6; jj++)\n    _jachqT->setValue(0, jj, _AUX2->getValue(0, jj - 3));\n\n#ifdef NEFC3D_DEBUG\n  printf(\"NewtonEulerFrom1DLocalFrameR jhqt\\n\");\n  _jachqT->display();\n#endif\n}\n\nvoid NewtonEulerFrom1DLocalFrameR::NIcomputeJachqTFromContacts(SP::SiconosVector q1, SP::SiconosVector q2)\n{\n  double Nx = _Nc->getValue(0);\n  double Ny = _Nc->getValue(1);\n  double Nz = _Nc->getValue(2);\n  double Px = _Pc1->getValue(0);\n  double Py = _Pc1->getValue(1);\n  double Pz = _Pc1->getValue(2);\n  double G1x = q1->getValue(0);\n  double G1y = q1->getValue(1);\n  double G1z = q1->getValue(2);\n\n  _RotationAbsToContactFrame->setValue(0, 0, Nx);\n  _RotationAbsToContactFrame->setValue(0, 1, Ny);\n  _RotationAbsToContactFrame->setValue(0, 2, Nz);\n\n  _NPG1->zero();\n\n  (*_NPG1)(0, 0) = 0;\n  (*_NPG1)(0, 1) = -(G1z - Pz);\n  (*_NPG1)(0, 2) = (G1y - Py);\n  (*_NPG1)(1, 0) = (G1z - Pz);\n  (*_NPG1)(1, 1) = 0;\n  (*_NPG1)(1, 2) = -(G1x - Px);\n  (*_NPG1)(2, 0) = -(G1y - Py);\n  (*_NPG1)(2, 1) = (G1x - Px);\n  (*_NPG1)(2, 2) = 0;\n\n  computeRotationMatrix(q1,_rotationMatrixAbsToBody);\n  prod(*_NPG1, *_rotationMatrixAbsToBody, *_AUX1, true);\n  prod(*_RotationAbsToContactFrame, *_AUX1, *_AUX2, true);\n\n  for (unsigned int jj = 0; jj < 3; jj++)\n    _jachqT->setValue(0, jj, _RotationAbsToContactFrame->getValue(0, jj));\n\n\n  for (unsigned int jj = 3; jj < 6; jj++)\n    _jachqT->setValue(0, jj, _AUX2->getValue(0, jj - 3));\n\n  double G2x = q2->getValue(0);\n  double G2y = q2->getValue(1);\n  double G2z = q2->getValue(2);\n\n  _NPG2->zero();\n  (*_NPG2)(0, 0) = 0;\n  (*_NPG2)(0, 1) = -(G2z - Pz);\n  (*_NPG2)(0, 2) = (G2y - Py);\n  (*_NPG2)(1, 0) = (G2z - Pz);\n  (*_NPG2)(1, 1) = 0;\n  (*_NPG2)(1, 2) = -(G2x - Px);\n  (*_NPG2)(2, 0) = -(G2y - Py);\n  (*_NPG2)(2, 1) = (G2x - Px);\n  (*_NPG2)(2, 2) = 0;\n\n\n\n  computeRotationMatrix(q2,_rotationMatrixAbsToBody);\n  prod(*_NPG2, *_rotationMatrixAbsToBody, *_AUX1, true);\n\n  prod(*_RotationAbsToContactFrame, *_AUX1, *_AUX2, true);\n\n  for (unsigned int jj = 0; jj < 3; jj++)\n    _jachqT->setValue(0, jj + 6, -_RotationAbsToContactFrame->getValue(0, jj));\n\n  for (unsigned int jj = 3; jj < 6; jj++)\n    _jachqT->setValue(0, jj + 6, -_AUX2->getValue(0, jj - 3));\n}\n\nvoid NewtonEulerFrom1DLocalFrameR::initialize(Interaction& inter)\n{\n  NewtonEulerR::initialize(inter);\n  //proj_with_q  _jachqProj.reset(new SimpleMatrix(_jachq->size(0),_jachq->size(1)));\n  unsigned int qSize = 7 * (inter.getSizeOfDS() / 6);\n  _jachq.reset(new SimpleMatrix(1, qSize));\n\n  /* VA 12/04/2016 All of what follows should be put in WorkM*/\n  _RotationAbsToContactFrame.reset(new SimpleMatrix(1, 3));\n  _rotationMatrixAbsToBody.reset(new SimpleMatrix(3, 3));\n  _AUX1.reset(new SimpleMatrix(3, 3));\n  _AUX2.reset(new SimpleMatrix(1, 3));\n  _NPG1.reset(new SimpleMatrix(3, 3));\n  _NPG2.reset(new SimpleMatrix(3, 3));\n  //  _isContact=1;\n}\n\n\n\n\nvoid NewtonEulerFrom1DLocalFrameR::computeJachq(double time, Interaction& inter, SP::BlockVector q0)\n{\n\n  DEBUG_BEGIN(\"NewtonEulerFrom1DLocalFrameR::computeJachq(double time, Interaction& inter, SP::BlockVector q0 ) \\n\");\n  DEBUG_PRINTF(\"with time =  %f\\n\",time);\n  DEBUG_PRINTF(\"with inter =  %p\\n\",&inter);\n\n\n  _jachq->setValue(0, 0, _Nc->getValue(0));\n  _jachq->setValue(0, 1, _Nc->getValue(1));\n  _jachq->setValue(0, 2, _Nc->getValue(2));\n  if (inter.has2Bodies())\n  {\n    _jachq->setValue(0, 7, -_Nc->getValue(0));\n    _jachq->setValue(0, 8, -_Nc->getValue(1));\n    _jachq->setValue(0, 9, -_Nc->getValue(2));\n  }\n\n  for (unsigned int iDS =0 ; iDS < q0->numberOfBlocks()  ; iDS++)\n  {\n    SP::SiconosVector q = (q0->getAllVect())[iDS];\n    double sign = 1.0;\n    DEBUG_PRINTF(\"NewtonEulerFrom1DLocalFrameR::computeJachq : ds%d->q :\", iDS);\n    DEBUG_EXPR_WE(q->display(););\n\n    ::boost::math::quaternion<double>    quatGP;\n    if (iDS == 0)\n    {\n      ::boost::math::quaternion<double>    quatAux(0, _Pc1->getValue(0) - q->getValue(0), _Pc1->getValue(1) - q->getValue(1),\n                                                   _Pc1->getValue(2) - q->getValue(2));\n      quatGP = quatAux;\n    }\n    else\n    {\n      sign = -1.0;\n      //cout<<\"NewtonEulerFrom1DLocalFrameR::computeJachq sign is -1 \\n\";\n      ::boost::math::quaternion<double>    quatAux(0, _Pc2->getValue(0) - q->getValue(0), _Pc2->getValue(1) - q->getValue(1),\n                                                   _Pc2->getValue(2) - q->getValue(2));\n      quatGP = quatAux;\n    }\n    DEBUG_PRINTF(\"NewtonEulerFrom1DLocalFrameR::computeJachq :GP :%lf, %lf, %lf\\n\", quatGP.R_component_2(), quatGP.R_component_3(), quatGP.R_component_4());\n    DEBUG_PRINTF(\"NewtonEulerFrom1DLocalFrameR::computeJachq :Q :%e,%e, %e, %e\\n\", q->getValue(3), q->getValue(4), q->getValue(5), q->getValue(6));\n    ::boost::math::quaternion<double>    quatQ(q->getValue(3), q->getValue(4), q->getValue(5), q->getValue(6));\n    ::boost::math::quaternion<double>    quatcQ(q->getValue(3), -q->getValue(4), -q->getValue(5), -q->getValue(6));\n    ::boost::math::quaternion<double>    quat0(1, 0, 0, 0);\n    ::boost::math::quaternion<double>    quatBuff;\n    ::boost::math::quaternion<double>    _2qiquatGP;\n    _2qiquatGP = quatGP;\n    _2qiquatGP *= 2 * (q->getValue(3));\n    quatBuff = (quatGP * quatQ) + (quatcQ * quatGP) - _2qiquatGP;\n\n    DEBUG_PRINTF(\"NewtonEulerFrom1DLocalFrameR::computeJachq :quattBuuf : %e,%e,%e \\n\", quatBuff.R_component_2(), quatBuff.R_component_3(), quatBuff.R_component_4());\n\n    _jachq->setValue(0, 7 * iDS + 3, sign * (quatBuff.R_component_2()*_Nc->getValue(0) +\n                                             quatBuff.R_component_3()*_Nc->getValue(1) + quatBuff.R_component_4()*_Nc->getValue(2)));\n    //cout<<\"WARNING NewtonEulerFrom1DLocalFrameR set jachq \\n\";\n    //_jachq->setValue(0,7*iDS+3,0);\n    for (unsigned int i = 1; i < 4; i++)\n    {\n      ::boost::math::quaternion<double>    quatei(0, (i == 1) ? 1 : 0, (i == 2) ? 1 : 0, (i == 3) ? 1 : 0);\n      _2qiquatGP = quatGP;\n      _2qiquatGP *= 2 * (q->getValue(3 + i));\n      quatBuff = quatei * quatcQ * quatGP - quatGP * quatQ * quatei - _2qiquatGP;\n      _jachq->setValue(0, 7 * iDS + 3 + i, sign * (quatBuff.R_component_2()*_Nc->getValue(0) +\n                                                   quatBuff.R_component_3()*_Nc->getValue(1) + quatBuff.R_component_4()*_Nc->getValue(2)));\n    }\n  }\n\n  DEBUG_EXPR(_jachq->display(););\n  DEBUG_END(\"NewtonEulerFrom1DLocalFrameR::computeJachq(double time, Interaction& inter, SP::BlockVector q0 \\n\");\n\n}\n\nvoid NewtonEulerFrom1DLocalFrameR::computeJachqT(Interaction& inter, SP::BlockVector q0 )\n{\n  DEBUG_BEGIN(\"NewtonEulerFrom1DLocalFrameR::computeJachqT(Interaction& inter, SP::BlockVector q0 \\n\")\n    \n  if (q0->numberOfBlocks()>1)\n  {\n    NIcomputeJachqTFromContacts((q0->getAllVect())[0], (q0->getAllVect())[1]);\n  }\n  else\n  {\n    NIcomputeJachqTFromContacts((q0->getAllVect())[0]);\n  }\n\n  DEBUG_END(\"NewtonEulerFrom1DLocalFrameR::computeJachqT(Interaction& inter, SP::BlockVector q0) \\n\");\n\n}\n\ndouble NewtonEulerFrom1DLocalFrameR::distance() const\n{\n  SiconosVector dpc(*_Pc2 - *_Pc1);\n  return dpc.norm2() * (inner_prod(*_Nc, dpc) >= 0 ? -1 : 1);\n}\n\nvoid NewtonEulerFrom1DLocalFrameR::computeh(double time, BlockVector& q0,\n                                            SiconosVector &y)\n{\n  // Contact points and normal are stored as relative to q1 and q2, if\n  // no q2 then pc2 and normal are absolute.\n\n  // Update pc1 based on q0 and relPc1\n  SP::SiconosVector q1 = (q0.getAllVect())[0];\n  ::boost::math::quaternion<double> qq1((*q1)(3), (*q1)(4), (*q1)(5), (*q1)(6));\n  ::boost::math::quaternion<double> qpc1(0,(*_relPc1)(0),(*_relPc1)(1),(*_relPc1)(2));\n\n  // apply q1 rotation and add\n  qpc1 = qq1 * qpc1 / qq1;\n  (*_Pc1)(0) = qpc1.R_component_2() + (*q1)(0);\n  (*_Pc1)(1) = qpc1.R_component_3() + (*q1)(1);\n  (*_Pc1)(2) = qpc1.R_component_4() + (*q1)(2);\n\n  if (q0.numberOfBlocks() > 1)\n  {\n    // Update pc2 based on q0 and relPc2\n    SP::SiconosVector q2 = (q0.getAllVect())[1];\n    ::boost::math::quaternion<double> qq2((*q2)(3), (*q2)(4), (*q2)(5), (*q2)(6));\n    ::boost::math::quaternion<double> qpc2(0,(*_relPc2)(0),(*_relPc2)(1),(*_relPc2)(2));\n\n    // apply q2 rotation and add\n    qpc2 = qq2 * qpc2 / qq2;\n    (*_Pc2)(0) = qpc2.R_component_2() + (*q2)(0);\n    (*_Pc2)(1) = qpc2.R_component_3() + (*q2)(1);\n    (*_Pc2)(2) = qpc2.R_component_4() + (*q2)(2);\n\n    // same for normal\n    ::boost::math::quaternion<double> qnc(0, (*_relNc)(0), (*_relNc)(1), (*_relNc)(2));\n    qnc = qq2 * qnc / qq2;\n    (*_Nc)(0) = qnc.R_component_2();\n    (*_Nc)(1) = qnc.R_component_3();\n    (*_Nc)(2) = qnc.R_component_4();\n  }\n  else\n  {\n    *_Pc2 = *_relPc2;\n    *_Nc = *_relNc;\n  }\n\n  NewtonEulerR::computeh(time, q0, y);\n}\n", "meta": {"hexsha": "ed29b19c1fb9c324288677c0f6a3800d17b5f343", "size": 11169, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/modelingTools/NewtonEulerFrom1DLocalFrameR.cpp", "max_stars_repo_name": "bremond/siconos", "max_stars_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/modelingTools/NewtonEulerFrom1DLocalFrameR.cpp", "max_issues_repo_name": "bremond/siconos", "max_issues_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/modelingTools/NewtonEulerFrom1DLocalFrameR.cpp", "max_forks_repo_name": "bremond/siconos", "max_forks_repo_head_hexsha": "8deea56ff6779379f4f69e0376d24a81562a42d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5789473684, "max_line_length": 198, "alphanum_fraction": 0.6311218551, "num_tokens": 4156, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160664, "lm_q2_score": 0.3665897363221599, "lm_q1q2_score": 0.22548489476859757}}
{"text": "#include \"CollisionHandler.h\"\n#include \"operationVector.h\"\n#include <boost/numeric/ublas/matrix.hpp>\n#include \"Turn.h\"\n#include <SFML/Window.hpp>\n#include <SFML/Graphics.hpp>\n#include \"VectorOfTurn.h\"\n#include \"Game.h\"\n#include \"bw.h\"\n#include \"Position.h\"\n#include \"beta.h\"\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\n\nvoid game();\nvoid test();\n\nint main()\n{\n\tgame();\n// \ttest();\n\treturn 0;\n}\n\nvoid game()\n{\n\tGame game;\n\tgame.init();\n\tgame.mainLoop();\n}\n\nvoid test()\n{\n\t\n\tmatrix<double> P{8, 8};\n\tstd::vector<double> pie{0, 0, 0, 0, 1, 0, 0, 0};\n\t\n\tfill(P, [&](int l, int c){\n\t\tif ( abs(l - c) < 2 || (l == 0 && c == 7) || (l == 7 && c == 0)) {\n\t\t\treturn 1/3.0;\n\t\t}\n\t\treturn 0.0;\n\t});\n\t\n\tmatrix<double> Obs(6, 8);\n\tfill(Obs, [&](int l, int c){\n\t\tif (l == 0 && (c == 0 || c == 1 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 1 && (c == 0 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 2 && (c == 5 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 3 && (c == 5 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 4 && (c == 5 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 5 && (c == 0 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn 1;\n\t});\n\t\nmatrix<double> Obs2(3, 8);\n\tfill(Obs2, [&](int l, int c){\n\t\tif (l == 0 && (c == 0 || c == 1 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 1 && (c == 0 || c == 1 || c == 2)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 2 && c != 2 ) {\n\t\t\treturn 0;\n\t\t\n\t\t}\n\n\t\treturn 1;\n\t});\n\t\n\tmatrix<double> Obs3(5, 8);\n\tfill(Obs3, [&](int l, int c){\n\t\tif (l == 0 && (c == 0 || c == 1 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 1 && (c == 0 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 2 && (c == 5 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 3 && (c == 5 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 4 && c!= 5 ) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\treturn 1;\n\t});\n\t\n\t\tmatrix<double> Obs4(9, 8);\n\tfill(Obs4, [&](int l, int c){\n\t\tif (l == 0 && (c == 0 || c == 1 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 1 && (c == 0 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 2 && (c == 5 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 3 && (c == 5 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 4 && (c == 5 || c == 6 || c == 4)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 5 && (c == 4 || c == 5 || c == 3)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 6 && (c == 5 || c == 6 || c == 4)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 7 && (c == 5 || c == 6 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 8 && c!= 7 ) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t\n\t\treturn 1;\n\t});\n\t\n\tmatrix<double> Obs5(3, 8);\n\tfill(Obs5, [&](int l, int c){\n\t\tif (l == 0 && (c == 0 || c == 1 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 1 && (c == 0 || c == 7 || c == 6)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 2 && c != 6 ) {\n\t\t\treturn 0;\n\t\t\n\t\t}\n\n\t\t\n\t\treturn 1;\n\t});\n\t\n\t\t\tmatrix<double> Obs6(9, 8);\n\tfill(Obs6, [&](int l, int c){\n\t\tif (l == 0 && (c == 0 || c == 1 || c == 7)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 1 && (c == 0 || c == 1 || c == 2)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 2 && (c == 2 || c == 1 || c == 3)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 3 && (c == 3 || c == 2 || c == 4)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 4 && (c == 5 || c == 3 || c == 4)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 5 && (c == 4 || c == 5 || c == 3)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 6 && (c == 5 || c == 6 || c == 4)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 7 && (c == 5 || c == 4 || c == 3)) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\tif (l == 8 && c!= 3 ) {\n\t\t\treturn 0;\n\t\t}\n\t\t\n\t\t\n\t\treturn 1;\n\t});\n\t\n\t// showMat(Beta(Obs, P, pie));\n\t\n\tshowMat(BW({Obs,Obs2,Obs3,Obs4,Obs5,Obs6,Obs5,Obs5,Obs5,Obs5},P,pie,1000));\n\n\n\t//showMat(Obs6);\n\t//showMat(Position(Obs6,BW({Obs,Obs2,Obs3,Obs4,Obs5},P,pie,10),pie));\n\t//showMat(Position(Obs6,P,pie));\n}\n", "meta": {"hexsha": "7c811e530ad891169a1d680c865c86126085be73", "size": 3691, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "Louis-Alexandre/Captain-Markov", "max_stars_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T17:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-29T09:47:49.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "Louis-Alexandre/Captain-Markov", "max_issues_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "Louis-Alexandre/Captain-Markov", "max_forks_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.1179039301, "max_line_length": 76, "alphanum_fraction": 0.3784882146, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521307073646, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22546261784065685}}
{"text": "//\n// Created by eliane on 04/03/19.\n//\n\n#include \"VinaLike.h\"\n\n#include <exception>\n\n#include <Structures/Atom.h>\n\n#include <Engines/Internals/InternalsUtilityFunctions.h>\n\n#include <boost/log/trivial.hpp>\n\n#include \"VinaLikeCommon.h\"\n\nnamespace SmolDock::Score {\n\n    double force_Instantiate_VinaLikeIntermolecularScoringFunction(const iConformer &conformer, iTransform &transform,\n                                                                   const iProtein &protein,\n                                                                   std::array<double, VinaLike_numCoefficients> nonDefaultCoeffs) {\n        return VinaLikeIntermolecularScoringFunction<true, false>(conformer, transform, protein, nonDefaultCoeffs);\n    }\n\n    double force_Instantiate_VinaLikeIntermolecularScoringFunction_vectorized(\n            const iConformer_Vectorized &conformer, iTransform &transform,\n            const iProtein_vectorized &protein,\n            std::array<double, VinaLike_numCoefficients> nonDefaultCoeffs) {\n        return VinaLikeIntermolecularScoringFunction_vectorized<true, false>\n                (conformer, transform, protein, nonDefaultCoeffs\n                );\n    }\n\n    const std::array<std::string, VinaLike::numCoefficients>\n            VinaLike::coefficientsNames = {\"Gauss1\", \"Gauss2\", \"RepulsionExceptCovalent\", \"Hydrophobic\", \"Hydrogen\"};\n\n    template<bool OnlyIntermolecular, bool useNonDefaultCoefficients>\n    double VinaLikeIntermolecularScoringFunction(const iConformer &ligand_, iTransform &transform,\n                                                 const iProtein &protein,\n                                                 std::array<double, VinaLike_numCoefficients> nonDefaultCoeffs) {\n\n        BOOST_ASSERT(!ligand_.x.empty());\n        BOOST_ASSERT(!protein.x.empty());\n\n        transform.doHousekeeping();\n        if (std::abs(transform.rota.norm() - 1) > 0.1) {\n            transform.rota.normalize();\n        }\n\n        BOOST_ASSERT(transform.bondRotationsAngles.size() == ligand_.num_rotatable_bond);\n\n        double score_raw = 0;\n\n        double distance_total = 0.0;\n        double gauss1_total = 0.0;\n        double gauss2_total = 0.0;\n        double repuls_total = 0.0;\n        double hydrophobic_total = 0.0;\n        double hydrogen_total = 0.0;\n\n        iConformer ligand = ligand_;\n        //applyBondRotationInPlace(ligand, transform);\n\n        Eigen::Vector3d ProtCenterPosition = {protein.center_x, protein.center_y, protein.center_z};\n\n        if constexpr(!OnlyIntermolecular) // C++17\n        {\n            for (unsigned int idxLig = 0; idxLig < ligand.x.size(); idxLig++) {\n                for (unsigned int idxLig2 = idxLig; idxLig2 < ligand.x.size(); idxLig2++) {\n                    Eigen::Vector3d LigDistance = {ligand.x[idxLig] - ligand.x[idxLig2],\n                                                   ligand.y[idxLig] - ligand.y[idxLig2],\n                                                   ligand.z[idxLig] - ligand.z[idxLig2]};\n\n                    double distance_raw = LigDistance.norm();\n                    const double distance = distanceFromRawDistance(distance_raw, ligand.atomicRadius[idxLig],\n                                                                    ligand.atomicRadius[idxLig2]);\n\n//                score_raw += VinaClassic::coeff_gauss1      * vinaGaussComponent(distance, 0.0, 0.5);\n//                score_raw += VinaClassic::coeff_gauss2      * vinaGaussComponent(distance, 3.0, 2.0);\n                    score_raw += VinaClassic::coeff_repulsion * vinaRepulsionComponent(distance, 0.0);\n                }\n            }\n        }\n\n\n        for (unsigned int idxLig = 0; idxLig < ligand.x.size(); idxLig++) {\n            for (unsigned int idxProt = 0; idxProt < protein.x.size(); idxProt++) {\n\n\n                Eigen::Vector3d LigPosition = {ligand.x[idxLig], ligand.y[idxLig], ligand.z[idxLig]};\n                applyRigidTransformInPlace(LigPosition, transform);\n\n                Eigen::Vector3d ProtPosition = {protein.x[idxProt], protein.y[idxProt], protein.z[idxProt]};\n                Eigen::Vector3d distToCenterVector = LigPosition - ProtCenterPosition;\n\n                double distanceToProteinCenter = distToCenterVector.norm();\n\n                if (distanceToProteinCenter > (protein.radius - 1)) {\n                    score_raw += std::pow((distanceToProteinCenter - protein.radius), 4) + 10;\n                    continue;\n                }\n\n                Eigen::Vector3d distVect = ProtPosition - LigPosition;\n\n                const double rawDist = distVect.norm();\n\n\n                if (rawDist >= VinaClassic::interaction_cutoff)\n                    continue;\n\n\n                const double atomicRadiusLig = ligand.atomicRadius[idxLig];\n                const double atomicRadiusProt = protein.atomicRadius[idxProt];\n\n                const double radToRemove = (atomicRadiusLig + atomicRadiusProt);\n\n                const double distance = rawDist - radToRemove;\n\n                distance_total += distance;\n\n                const unsigned int atom1AtomicNumber = ligand.type[idxLig];\n                const unsigned int atom1AtomVariant = ligand.variant[idxLig];\n                const unsigned int atom2AtomicNumber = protein.type[idxProt];\n                const unsigned int atom2AtomVariant = protein.variant[idxProt];\n\n                if constexpr(useNonDefaultCoefficients) {\n                    score_raw += nonDefaultCoeffs[0] * vinaGaussComponent(distance, 0.0, 0.5);\n                    score_raw += nonDefaultCoeffs[1] * vinaGaussComponent(distance, 3.0, 2.0);\n                    score_raw += nonDefaultCoeffs[2] * vinaRepulsionComponent(distance, 0.0);\n                    score_raw += nonDefaultCoeffs[3] * vinaHydrophobicComponent(distance,\n                                                                                atom1AtomicNumber, atom1AtomVariant,\n                                                                                atom2AtomicNumber, atom2AtomVariant);\n\n                    score_raw += nonDefaultCoeffs[4] * vinaHydrogenComponent(distance,\n                                                                             atom1AtomicNumber, atom1AtomVariant,\n                                                                             atom2AtomicNumber, atom2AtomVariant);\n                } else {\n\n                    gauss1_total += vinaGaussComponent(distance, 0.0, 0.5);\n                    gauss2_total += vinaGaussComponent(distance, 3.0, 2.0);\n                    repuls_total += vinaRepulsionComponent(distance, 0.0);\n                    hydrophobic_total += vinaHydrophobicComponent(distance,\n                                                                  atom1AtomicNumber, atom1AtomVariant,\n                                                                  atom2AtomicNumber, atom2AtomVariant);\n                    hydrogen_total += vinaHydrogenComponent(distance,\n                                                            atom1AtomicNumber, atom1AtomVariant,\n                                                            atom2AtomicNumber, atom2AtomVariant);\n\n                    score_raw += VinaClassic::coeff_gauss1 * vinaGaussComponent(distance, 0.0, 0.5);\n                    score_raw += VinaClassic::coeff_gauss2 * vinaGaussComponent(distance, 3.0, 2.0);\n                    score_raw += VinaClassic::coeff_repulsion * vinaRepulsionComponent(distance, 0.0);\n                    score_raw += VinaClassic::coeff_hydrophobic * vinaHydrophobicComponent(distance,\n                                                                                           atom1AtomicNumber,\n                                                                                           atom1AtomVariant,\n                                                                                           atom2AtomicNumber,\n                                                                                           atom2AtomVariant);\n\n                    score_raw += VinaClassic::coeff_hydrogen * vinaHydrogenComponent(distance,\n                                                                                     atom1AtomicNumber,\n                                                                                     atom1AtomVariant,\n                                                                                     atom2AtomicNumber,\n                                                                                     atom2AtomVariant);\n                }\n\n\n            } // for\n        } // for\n\n        double final_score = score_raw / (1 + (VinaClassic::coeff_entropic * ligand.num_rotatable_bond));\n\n/*\n        std::cout << \"\\n Non-Vectorized : \\n\";\n        std::cout << \"dist    : \" << distance_total << std::endl;\n        std::cout << \"gauss1  : \" << gauss1_total << std::endl;\n        std::cout << \"gauss2  : \" << gauss2_total << std::endl;\n        std::cout << \"repuls  : \" << repuls_total << std::endl;\n        std::cout << \"hydroph : \" << hydrophobic_total << std::endl;\n        std::cout << \"hydrog  : \" << hydrogen_total << std::endl;\n        std::cout << \"\\n\\n\";\n*/\n        return final_score;\n    }\n\n    template<bool OnlyIntermolecular, bool useNonDefaultCoefficients>\n    double VinaLikeIntermolecularScoringFunction_vectorized(const iConformer_Vectorized &ligand_, iTransform &transform,\n                                                            const iProtein_vectorized &protein,\n                                                            std::array<double, VinaLike_numCoefficients> nonDefaultCoeffs) {\n\n        BOOST_ASSERT(ligand_.x.entriesCount() != 0);\n        BOOST_ASSERT(protein.x.entriesCount() != 0);\n\n        transform.doHousekeeping();\n        if (std::abs(transform.rota.norm() - 1) > 0.1) {\n            transform.rota.normalize();\n        }\n\n        BOOST_ASSERT(transform.bondRotationsAngles.size() == ligand_.num_rotatable_bond);\n\n        double score_raw = 0;\n\n        double distance_total = 0.0;\n        double gauss1_total = 0.0;\n        double gauss2_total = 0.0;\n        double repuls_total = 0.0;\n        double hydrophobic_total = 0.0;\n        double hydrogen_total = 0.0;\n\n        iConformer_Vectorized ligand = ligand_;\n        //applyBondRotationInPlace(ligand, transform);\n\n        const double xProtCenter = protein.center_x;\n        const double yProtCenter = protein.center_y;\n        const double zProtCenter = protein.center_z;\n\n        if constexpr(!OnlyIntermolecular) // C++17\n        {\n\n            for (unsigned int idxLig1 = 0; idxLig1 < ligand.x.vectorsCount(); ++idxLig1) {\n                for (unsigned int idxLig2 = idxLig1; idxLig2 < ligand.x.vectorsCount(); ++idxLig2) {\n\n                    const Vc::Vector<double> x_diff = ligand.x.vector(idxLig1) - ligand.x.vector(idxLig2);\n                    const Vc::Vector<double> y_diff = ligand.y.vector(idxLig1) - ligand.y.vector(idxLig2);\n                    const Vc::Vector<double> z_diff = ligand.z.vector(idxLig1) - ligand.z.vector(idxLig2);\n                    const Vc::Vector<double> squared_sum = (x_diff * x_diff) + (y_diff * y_diff) + (z_diff * z_diff);\n                    const Vc::Vector<double> distances_raw = Vc::sqrt(squared_sum);\n\n                    const Vc::Vector<double> distances = distanceFromRawDistance(distances_raw,\n                                                                                 ligand.atomicRadius.vector(idxLig1),\n                                                                                 ligand.atomicRadius.vector(idxLig2));\n\n                    score_raw += VinaClassic::coeff_repulsion * vinaRepulsionComponent(distances, 0.0).sum();\n\n\n                }\n\n            }\n        }\n\n\n        int atomicNumber_VectorIdx_ligand = -1;\n        int atomicNumber_VectorIdx_protein = -1;\n        int atomVariant_VectorIdx_ligand = -1;\n        int atomVariant_VectorIdx_protein = -1;\n\n        Vc::Memory<Vc::Vector<unsigned char>, Vc::Vector<double>::Size> ligandAtomicNumInformation;\n        Vc::Memory<Vc::Vector<unsigned int>, Vc::Vector<double>::Size> ligandAtomVariantInformation;\n\n        Vc::Memory<Vc::Vector<unsigned char>, Vc::Vector<double>::Size> proteinAtomicNumInformation;\n        Vc::Memory<Vc::Vector<unsigned int>, Vc::Vector<double>::Size> proteinAtomVariantInformation;\n\n\n        for (unsigned int idxLig = 0; idxLig < ligand.x.vectorsCount(); ++idxLig) {\n            const unsigned int globalIdx_Ligand = (idxLig * Vc::Vector<double>::Size);\n            const unsigned char offsetUChar_Ligand = globalIdx_Ligand % Vc::Vector<unsigned char>::Size;\n            const unsigned char offsetUInt_Ligand = globalIdx_Ligand % Vc::Vector<unsigned int>::Size;\n\n            const unsigned int offset_UChar_ligand = offsetUChar_Ligand % Vc::Vector<double>::Size;\n            if (offset_UChar_ligand == 0) {\n                // we are at the start of a\n                atomicNumber_VectorIdx_ligand++;\n                ligandAtomicNumInformation = ligand.type.vector(atomicNumber_VectorIdx_ligand);\n            }\n\n            const unsigned int offset_UInt_ligand = offsetUInt_Ligand % Vc::Vector<double>::Size;\n            if (offset_UInt_ligand == 0) {\n                // we are at the start of a\n                atomVariant_VectorIdx_ligand++;\n                ligandAtomVariantInformation = ligand.variant.vector(atomVariant_VectorIdx_ligand);\n            }\n\n            Vc::Vector<double> ligandHydrophobicMaskMaker;\n            for (unsigned int k = 0; k < Vc::Vector<double>::Size; ++k) {\n                ligandHydrophobicMaskMaker[k] = isHydrophobic_prepareMask(\n                        ligandAtomicNumInformation[offset_UChar_ligand + k],\n                        ligandAtomVariantInformation[offset_UChar_ligand + k]\n                );\n            }\n\n            Vc::Mask<double> ligandHydrophobicMask = (ligandHydrophobicMaskMaker == Vc::Vector<double>::One());\n\n            for (unsigned int idxProt = 0; idxProt < protein.x.vectorsCount(); idxProt++) {\n                Vc::Vector<double> xLig, yLig, zLig;\n                xLig = ligand.x.vector(idxLig);\n                yLig = ligand.y.vector(idxLig);\n                zLig = ligand.z.vector(idxLig);\n\n\n                applyRigidTransformInPlace(xLig, yLig, zLig, transform);\n\n\n                const Vc::Vector<double> xsquared_disttoProtCenter = (xLig - xProtCenter) * (xLig - xProtCenter);\n                const Vc::Vector<double> ysquared_disttoProtCenter = (yLig - yProtCenter) * (yLig - yProtCenter);\n                const Vc::Vector<double> zsquared_disttoProtCenter = (zLig - zProtCenter) * (zLig - zProtCenter);\n\n\n                const Vc::Vector<double> distancesToProtCenter = Vc::sqrt(xsquared_disttoProtCenter\n                                                                          + ysquared_disttoProtCenter\n                                                                          + zsquared_disttoProtCenter);\n\n\n                const Vc::Vector<double> tooFarFromCenterPenalty = Vc::iif(\n                        distancesToProtCenter > (protein.radius - 1),\n                        Vc::exp(4 * Vc::log(distancesToProtCenter - protein.radius)) + 10,\n                        Vc::Vector<double>(Vc::Zero));\n\n\n                score_raw += tooFarFromCenterPenalty.sum();\n\n\n                const Vc::Vector<double> xProt = protein.x.vector(idxProt);\n                const Vc::Vector<double> yProt = protein.y.vector(idxProt);\n                const Vc::Vector<double> zProt = protein.z.vector(idxProt);\n\n                const Vc::Vector<double> xsquared = (xLig - xProt) * (xLig - xProt);\n                const Vc::Vector<double> ysquared = (yLig - yProt) * (yLig - yProt);\n                const Vc::Vector<double> zsquared = (zLig - zProt) * (zLig - zProt);\n\n                const Vc::Vector<double> rawDistances = Vc::sqrt(xsquared + ysquared + zsquared);\n\n\n                if (Vc::all_of(rawDistances >= VinaClassic::interaction_cutoff)) {\n                    /*\n                     * Theoretically, this helps because atoms which are close in idx are ~ close in position\n                     * So all_of will be true a non negigible fraction of the time\n                     * TODO : benchmark this versus just the mask\n                     */\n                    continue;\n                }\n\n                // If we have some higher and some lower than the cutoff, we we mask them at the end in .sum()\n                auto cutOffMask = rawDistances < VinaClassic::interaction_cutoff;\n\n                const Vc::Vector<double> distances = distanceFromRawDistance(rawDistances,\n                                                                             ligand.atomicRadius.vector(idxLig),\n                                                                             protein.atomicRadius.vector(idxProt));\n\n                //std::cout << cutOffMask << \" -> \" << distances << std::endl;\n\n\n                distance_total += distances.sum(cutOffMask);\n\n                const unsigned int globalIdx_Prot = (idxProt * Vc::Vector<double>::Size);\n                const unsigned char offsetUChar_Prot = globalIdx_Prot % Vc::Vector<unsigned char>::Size;\n                const unsigned char offsetUInt_Prot = globalIdx_Prot % Vc::Vector<unsigned int>::Size;\n\n\n                const unsigned int offset_UChar_protein = offsetUChar_Prot % Vc::Vector<double>::Size;\n                if (offset_UChar_protein == 0) {\n                    // we are at the start of a\n                    atomicNumber_VectorIdx_protein++;\n                    proteinAtomicNumInformation = protein.type.vector(atomicNumber_VectorIdx_protein);\n                }\n\n                const unsigned int offset_UInt_protein = offsetUInt_Prot % Vc::Vector<double>::Size;\n                if (offset_UInt_protein == 0) {\n                    // we are at the start of a\n                    atomVariant_VectorIdx_protein++;\n                    proteinAtomVariantInformation = protein.variant.vector(atomVariant_VectorIdx_ligand);\n                }\n\n\n                Vc::Vector<double> proteinHydrophobicMaskMaker;\n                for (unsigned int k = 0; k < Vc::Vector<double>::Size; ++k) {\n                    proteinHydrophobicMaskMaker[k] = isHydrophobic_prepareMask(\n                            proteinAtomicNumInformation[offset_UChar_protein + k],\n                            proteinAtomVariantInformation[offset_UInt_protein + k]\n                    );\n                }\n\n                Vc::Vector<double> HydrogenMaskMaker;\n                for (unsigned int k = 0; k < Vc::Vector<double>::Size; ++k) {\n                    ligandHydrophobicMaskMaker[k] = hydrogenBondingPossible_prepareMask(\n                            ligandAtomicNumInformation[offset_UChar_ligand + k],\n                            ligandAtomVariantInformation[offset_UChar_ligand + k],\n                            proteinAtomicNumInformation[offset_UChar_ligand + k],\n                            proteinAtomVariantInformation[offset_UChar_ligand + k]\n                    );\n                }\n\n\n                Vc::Mask<double> hydrophobicMask =\n                        (proteinHydrophobicMaskMaker == Vc::Vector<double>::One()) && ligandHydrophobicMask;\n                Vc::Mask<double> hydrogenMask = (HydrogenMaskMaker == Vc::Vector<double>::One());\n\n\n                if constexpr(useNonDefaultCoefficients) {\n\n                    score_raw += nonDefaultCoeffs[0] * vinaGaussComponent(distances, 0.0, 0.5).sum(cutOffMask);\n                    score_raw += nonDefaultCoeffs[1] * vinaGaussComponent(distances, 3.0, 2.0).sum(cutOffMask);\n                    score_raw += nonDefaultCoeffs[2] * vinaRepulsionComponent(distances, 0.0).sum(cutOffMask);\n                    score_raw +=\n                            nonDefaultCoeffs[3] * vinaHydrophobicComponent(distances, hydrophobicMask).sum(cutOffMask);\n                    score_raw += nonDefaultCoeffs[4] * vinaHydrogenComponent(distances, hydrogenMask).sum(cutOffMask);\n                } else {\n                    gauss1_total += vinaGaussComponent(distances, 0.0, 0.5).sum(cutOffMask);\n                    gauss2_total += vinaGaussComponent(distances, 3.0, 2.0).sum(cutOffMask);\n                    repuls_total += vinaRepulsionComponent(distances, 0.0).sum(cutOffMask);\n                    hydrophobic_total += vinaHydrophobicComponent(distances, hydrophobicMask).sum(cutOffMask);\n                    hydrogen_total += vinaHydrogenComponent(distances, hydrogenMask).sum(cutOffMask);\n\n                    score_raw += VinaClassic::coeff_gauss1 * vinaGaussComponent(distances, 0.0, 0.5).sum(cutOffMask);\n                    score_raw += VinaClassic::coeff_gauss2 * vinaGaussComponent(distances, 3.0, 2.0).sum(cutOffMask);\n                    score_raw += VinaClassic::coeff_repulsion * vinaRepulsionComponent(distances, 0.0).sum(cutOffMask);\n                    score_raw += VinaClassic::coeff_hydrophobic *\n                                 vinaHydrophobicComponent(distances, hydrophobicMask).sum(cutOffMask);\n                    score_raw += VinaClassic::coeff_hydrogen *\n                                 vinaHydrogenComponent(distances, hydrogenMask).sum(cutOffMask);\n                }\n\n            }\n        }\n        double final_score = score_raw / (1 + (VinaClassic::coeff_entropic * ligand.num_rotatable_bond));\n\n        std::cout << \"\\n Vectorized : \\n\";\n        std::cout << \"dist    : \" << distance_total << std::endl;\n        std::cout << \"gauss1  : \" << gauss1_total << std::endl;\n        std::cout << \"gauss2  : \" << gauss2_total << std::endl;\n        std::cout << \"repuls  : \" << repuls_total << std::endl;\n        std::cout << \"hydroph : \" << hydrophobic_total << std::endl;\n        std::cout << \"hydrog  : \" << hydrogen_total << std::endl;\n        std::cout << \"\\n\\n\";\n\n        return final_score;\n    }\n\n\n    VinaLike::VinaLike(const iConformer &startingConformation_,\n                       const iProtein &p,\n                       const iTransform &initialTransform_,\n                       double differential_epsilon_,\n                       bool useNonDefaultCoefficient) :\n            useNonDefaultCoefficient(useNonDefaultCoefficient),\n            startingConformation(startingConformation_),\n            prot(p),\n            initialTransform(initialTransform_),\n            differential_epsilon(differential_epsilon_) {\n        this->numberOfRotatableBonds = this->startingConformation.num_rotatable_bond;\n        this->numberOfParamInState = 7 + (this->numberOfRotatableBonds);\n\n        if (this->initialTransform.bondRotationsAngles.size() != this->numberOfRotatableBonds) {\n            BOOST_LOG_TRIVIAL(error)\n                << \"Discrepency between the number of rotatable bonds in the iConformer and iTransform (\"\n                << this->numberOfRotatableBonds << \" != \" << this->initialTransform.bondRotationsAngles.size() << \")\";\n            std::terminate();\n        }\n\n        if (this->useNonDefaultCoefficient) {\n                this->nonDefaultCoefficients[0] = VinaClassic::coeff_gauss1;\n                this->nonDefaultCoefficients[1] = VinaClassic::coeff_gauss2;\n                this->nonDefaultCoefficients[2] = VinaClassic::coeff_repulsion;\n                this->nonDefaultCoefficients[3] = VinaClassic::coeff_hydrophobic;\n                this->nonDefaultCoefficients[4] = VinaClassic::coeff_hydrogen;\n        }\n\n    }\n\n\n    double VinaLike::Evaluate(const arma::mat &x) {\n        BOOST_ASSERT(x.n_rows == this->numberOfParamInState);\n\n        iTransform tr = this->internalToExternalRepr(x);\n\n        normalizeQuaternionInPlace(tr.rota);\n\n        double score_ = this->useNonDefaultCoefficient ?\n                        VinaLikeIntermolecularScoringFunction<false, true>(this->startingConformation, tr, this->prot,\n                                                                           this->nonDefaultCoefficients)\n                                                       : VinaLikeIntermolecularScoringFunction<false, false>(\n                        this->startingConformation, tr, this->prot);\n\n        return score_;\n    }\n\n    double VinaLike::EvaluateWithGradient(const arma::mat &x, arma::mat &grad) {\n\n        BOOST_ASSERT(!x.has_nan());\n        BOOST_ASSERT(!grad.has_nan());\n        BOOST_ASSERT(x.n_rows == this->numberOfParamInState);\n        BOOST_ASSERT(grad.n_rows == this->numberOfParamInState);\n\n        iTransform tr = this->internalToExternalRepr(x);\n        tr.doHousekeeping();\n\n        double score_ = this->useNonDefaultCoefficient ?\n                        VinaLikeIntermolecularScoringFunction<false, true>(this->startingConformation, tr, this->prot,\n                                                                           this->nonDefaultCoefficients)\n                                                       : VinaLikeIntermolecularScoringFunction<false, false>(\n                        this->startingConformation, tr, this->prot);\n\n\n        // Translation\n        {\n            iTransform transform_dx = tr;\n            transform_dx.transl.x() += this->differential_epsilon;\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeIntermolecularScoringFunction<false, true>(this->startingConformation,\n                                                                                        transform_dx, this->prot,\n                                                                                        this->nonDefaultCoefficients)\n                                                                    : VinaLikeIntermolecularScoringFunction<false, false>(\n                            this->startingConformation, transform_dx, this->prot);\n            grad[0] = gradScore - score_;\n        }\n\n        {\n            iTransform transform_dy = tr;\n            transform_dy.transl.y() += this->differential_epsilon;\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeIntermolecularScoringFunction<false, true>(this->startingConformation,\n                                                                                        transform_dy, this->prot,\n                                                                                        this->nonDefaultCoefficients)\n                                                                    : VinaLikeIntermolecularScoringFunction<false, false>(\n                            this->startingConformation, transform_dy, this->prot);\n            grad[1] = gradScore - score_;\n        }\n\n        {\n            iTransform transform_dz = tr;\n            transform_dz.transl.z() += this->differential_epsilon;\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeIntermolecularScoringFunction<false, true>(this->startingConformation,\n                                                                                        transform_dz, this->prot,\n                                                                                        this->nonDefaultCoefficients)\n                                                                    : VinaLikeIntermolecularScoringFunction<false, false>(\n                            this->startingConformation, transform_dz, this->prot);\n            grad[2] = gradScore - score_;\n        }\n\n        // Rotation\n\n        {\n            iTransform transform_dqs = tr;\n            transform_dqs.rota.w() += this->differential_epsilon;\n            transform_dqs.doHousekeeping();\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeIntermolecularScoringFunction<false, true>(this->startingConformation,\n                                                                                        transform_dqs, this->prot,\n                                                                                        this->nonDefaultCoefficients)\n                                                                    : VinaLikeIntermolecularScoringFunction<false, false>(\n                            this->startingConformation, transform_dqs, this->prot);\n            grad[3] = gradScore - score_;\n        }\n\n        {\n            iTransform transform_dqx = tr;\n            transform_dqx.rota.x() += this->differential_epsilon;\n            transform_dqx.doHousekeeping();\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeIntermolecularScoringFunction<false, true>(this->startingConformation,\n                                                                                        transform_dqx, this->prot,\n                                                                                        this->nonDefaultCoefficients)\n                                                                    : VinaLikeIntermolecularScoringFunction<false, false>(\n                            this->startingConformation, transform_dqx, this->prot);\n            grad[4] = gradScore - score_;\n\n        }\n\n        {\n            iTransform transform_dqy = tr;\n            transform_dqy.rota.x() += this->differential_epsilon;\n            transform_dqy.doHousekeeping();\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeIntermolecularScoringFunction<false, true>(this->startingConformation,\n                                                                                        transform_dqy, this->prot,\n                                                                                        this->nonDefaultCoefficients)\n                                                                    : VinaLikeIntermolecularScoringFunction<false, false>(\n                            this->startingConformation, transform_dqy, this->prot);\n            grad[5] = gradScore - score_;\n        }\n\n        {\n            iTransform transform_dqz = tr;\n            transform_dqz.rota.x() += this->differential_epsilon;\n            transform_dqz.doHousekeeping();\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeIntermolecularScoringFunction<false, true>(this->startingConformation,\n                                                                                        transform_dqz, this->prot,\n                                                                                        this->nonDefaultCoefficients)\n                                                                    : VinaLikeIntermolecularScoringFunction<false, false>(\n                            this->startingConformation, transform_dqz, this->prot);\n            grad[6] = gradScore - score_;\n        }\n\n        for (unsigned int i = 0; i < this->numberOfRotatableBonds; i++) {\n            iTransform transform_dbondrot = tr;\n            transform_dbondrot.bondRotationsAngles[i] += this->differential_epsilon;\n            const double gradScore = this->useNonDefaultCoefficient ?\n                                     VinaLikeIntermolecularScoringFunction<false, true>(this->startingConformation,\n                                                                                        transform_dbondrot, this->prot,\n                                                                                        this->nonDefaultCoefficients)\n                                                                    : VinaLikeIntermolecularScoringFunction<false, false>(\n                            this->startingConformation, transform_dbondrot, this->prot);\n            grad[7 + i] = gradScore - score_;\n\n        }\n\n        /*\n        BOOST_LOG_TRIVIAL(debug) << \"Transform: \" << x.t();\n        BOOST_LOG_TRIVIAL(debug) << \"Score: \" << score_;\n        BOOST_LOG_TRIVIAL(debug) << \"Gradient\";\n        BOOST_LOG_TRIVIAL(debug) << \"     ds: \" << grad[3];\n        BOOST_LOG_TRIVIAL(debug) << \"     du: \" << grad[4] << \"   dx: \" << grad[0];\n        BOOST_LOG_TRIVIAL(debug) << \"     dv: \" << grad[5] << \"   dy: \" << grad[1];\n        BOOST_LOG_TRIVIAL(debug) << \"     dt: \" << grad[6] << \"   dx: \" << grad[2];\n        //*/\n\n        BOOST_ASSERT(score_ == score_); // catches NaN\n        return score_;\n    }\n\n\n    double VinaLike::getDifferentialEpsilon() const {\n        return this->differential_epsilon;\n    }\n\n    arma::mat VinaLike::getStartingConditions() const {\n        return this->externalToInternalRepr(this->initialTransform);\n    }\n\n    iConformer VinaLike::getConformerForParamMatrix(const arma::mat &x) {\n        BOOST_ASSERT(x.n_rows == this->numberOfParamInState);\n\n        iTransform tr = this->internalToExternalRepr(x);\n        tr.doHousekeeping();\n\n        iConformer ret = this->startingConformation;\n        applyBondRotationInPlace(ret, tr);\n        applyRigidTransformInPlace(ret, tr);\n\n        return ret;\n    }\n\n    unsigned int VinaLike::getParamVectorDimension() const {\n        return this->numberOfParamInState;\n    }\n\n    std::vector<std::tuple<std::string, double>> VinaLike::EvaluateSubcomponents(const arma::mat &x) {\n        std::vector<std::tuple<std::string, double>> ret;\n\n        BOOST_ASSERT(x.n_rows == this->numberOfParamInState);\n\n        iTransform tr = this->internalToExternalRepr(x);\n        tr.doHousekeeping();\n\n        BOOST_ASSERT(!this->startingConformation.x.empty());\n        BOOST_ASSERT(!this->prot.x.empty());\n        BOOST_ASSERT(tr.bondRotationsAngles.size() == this->startingConformation.num_rotatable_bond);\n\n        if (std::abs(tr.rota.norm() - 1) > 0.1) {\n            tr.rota.normalize();\n        }\n\n        double gauss1_total = 0.0;\n        double gauss2_total = 0.0;\n        double repulsion_total = 0.0;\n        double hydrogen_total = 0.0;\n        double hydrophobic_total = 0.0;\n        double score_raw = 0.0;\n\n        double intramolecular_repuls_total = 0.0;\n        double intramolecular_score = 0.0;\n\n        iConformer ligand = this->startingConformation;\n        applyBondRotationInPlace(ligand, tr);\n\n        Eigen::Vector3d ProtCenterPosition = {this->prot.center_x, this->prot.center_y, this->prot.center_z};\n\n\n        for (unsigned int idxLig = 0; idxLig < ligand.x.size(); idxLig++) {\n            for (unsigned int idxLig2 = idxLig; idxLig2 < ligand.x.size(); idxLig2++) {\n\n                if (idxLig == idxLig2)\n                    continue;\n\n                Eigen::Vector3d LigDistance = {ligand.x[idxLig] - ligand.x[idxLig2],\n                                               ligand.y[idxLig] - ligand.y[idxLig2],\n                                               ligand.z[idxLig] - ligand.z[idxLig2]};\n\n                double distance_raw = LigDistance.norm();\n                const double distance = distanceFromRawDistance(distance_raw, ligand.atomicRadius[idxLig],\n                                                                ligand.atomicRadius[idxLig2]);\n\n//                score_raw += VinaClassic::coeff_gauss1      * vinaGaussComponent(distance, 0.0, 0.5);\n//                score_raw += VinaClassic::coeff_gauss2      * vinaGaussComponent(distance, 3.0, 2.0);\n                intramolecular_repuls_total += vinaRepulsionComponent(distance, 0.0);\n\n            }\n        }\n\n        intramolecular_score = VinaClassic::coeff_repulsion * intramolecular_repuls_total;\n\n\n        for (unsigned int idxLig = 0; idxLig < ligand.x.size(); idxLig++) {\n            for (unsigned int idxProt = 0; idxProt < this->prot.x.size(); idxProt++) {\n\n\n                Eigen::Vector3d LigPosition = {ligand.x[idxLig], ligand.y[idxLig], ligand.z[idxLig]};\n                applyRigidTransformInPlace(LigPosition, tr);\n\n                Eigen::Vector3d ProtPosition = {this->prot.x[idxProt], this->prot.y[idxProt], this->prot.z[idxProt]};\n                Eigen::Vector3d distToCenterVector = LigPosition - ProtCenterPosition;\n\n                double distanceToProteinCenter = distToCenterVector.norm();\n\n                if (distanceToProteinCenter > (this->prot.radius - 1)) {\n                    score_raw += std::pow((distanceToProteinCenter - this->prot.radius), 4) + 10;\n                    continue;\n                }\n\n                Eigen::Vector3d distVect = ProtPosition - LigPosition;\n\n                double rawDist = distVect.norm();\n\n                if (rawDist >= VinaClassic::interaction_cutoff)\n                    continue;\n\n                double distance = distanceFromRawDistance(rawDist, ligand.atomicRadius[idxLig],\n                                                          this->prot.atomicRadius[idxProt]);\n\n                const unsigned int atom1AtomicNumber = ligand.type[idxLig];\n                const unsigned int atom1AtomVariant = ligand.variant[idxLig];\n                const unsigned int atom2AtomicNumber = this->prot.type[idxProt];\n                const unsigned int atom2AtomVariant = this->prot.variant[idxProt];\n\n                gauss1_total += vinaGaussComponent(distance, 0.0, 0.5);\n                gauss2_total += vinaGaussComponent(distance, 3.0, 2.0);\n                repulsion_total += vinaRepulsionComponent(distance, 0.0);\n                hydrophobic_total += vinaHydrophobicComponent(distance,\n                                                              atom1AtomicNumber, atom1AtomVariant,\n                                                              atom2AtomicNumber, atom2AtomVariant);\n                hydrogen_total += vinaHydrogenComponent(distance,\n                                                        atom1AtomicNumber, atom1AtomVariant,\n                                                        atom2AtomicNumber, atom2AtomVariant);\n\n            } // for\n        } // for\n\n\n        double score_sum = 0.0;\n\n        if (this->useNonDefaultCoefficient) {\n            ret.emplace_back(std::make_tuple(\"NonDefaultCoeffs\", 1.0));\n            score_sum = this->nonDefaultCoefficients[0] * gauss1_total\n                        + this->nonDefaultCoefficients[1] * gauss2_total\n                        + this->nonDefaultCoefficients[2] * repulsion_total\n                        + this->nonDefaultCoefficients[3] * hydrophobic_total\n                        + this->nonDefaultCoefficients[4] * hydrogen_total;\n        } else {\n            score_sum = VinaClassic::coeff_gauss1 * gauss1_total\n                        + VinaClassic::coeff_gauss2 * gauss2_total\n                        + VinaClassic::coeff_repulsion * repulsion_total\n                        + VinaClassic::coeff_hydrophobic * hydrophobic_total\n                        + VinaClassic::coeff_hydrogen * hydrogen_total;\n        }\n\n\n        double final_score_fromSum = score_sum / (1 + (VinaClassic::coeff_entropic * ligand.num_rotatable_bond));\n\n        ret.emplace_back(std::make_tuple(\"Gauss1\", gauss1_total));\n        ret.emplace_back(std::make_tuple(\"Gauss2\", gauss2_total));\n        ret.emplace_back(std::make_tuple(\"Repulsion\", repulsion_total));\n        ret.emplace_back(std::make_tuple(\"Hydrophobic\", hydrophobic_total));\n        ret.emplace_back(std::make_tuple(\"Hydrogen\", hydrogen_total));\n        ret.emplace_back(std::make_tuple(\"Intra_Repuls\", intramolecular_repuls_total));\n        ret.emplace_back(std::make_tuple(\"Intra_Score\", intramolecular_score));\n        ret.emplace_back(std::make_tuple(\"ScoreRawSum\", score_sum));\n        ret.emplace_back(std::make_tuple(\"Score\", final_score_fromSum));\n        return ret;\n    }\n\n    double VinaLike::EvaluateOnlyIntermolecular(const arma::mat &x) {\n        BOOST_ASSERT(x.n_rows == this->numberOfParamInState);\n\n        iTransform tr = this->internalToExternalRepr(x);\n\n        tr.doHousekeeping();\n\n        // Template parameter controls whether onlyIntermolecular interaction are taken into account. Here we want true\n        double score_ = this->useNonDefaultCoefficient ?\n                        VinaLikeIntermolecularScoringFunction<true, true>(this->startingConformation, tr, this->prot,\n                                                                           this->nonDefaultCoefficients)\n                                                       : VinaLikeIntermolecularScoringFunction<true, false>(\n                        this->startingConformation, tr, this->prot);\n\n\n        return score_;\n    }\n\n    unsigned int VinaLike::getCoefficientsVectorWidth() {\n        return this->numCoefficients;\n    }\n\n    std::vector<std::string> VinaLike::getCoefficientsNames() {\n        return std::vector<std::string>(this->coefficientsNames.begin(), this->coefficientsNames.end());\n    }\n\n    std::vector<double> VinaLike::getCurrentCoefficients() {\n        if (this->useNonDefaultCoefficient) {\n            return std::vector<double>(this->nonDefaultCoefficients.begin(), this->nonDefaultCoefficients.end());\n        }\n        return {VinaClassic::coeff_gauss1, VinaClassic::coeff_gauss2,\n                VinaClassic::coeff_repulsion, VinaClassic::coeff_hydrophobic,\n                VinaClassic::coeff_hydrogen};\n    }\n\n    bool VinaLike::setNonDefaultCoefficients(std::vector<double> coeffs) {\n        if (coeffs.size() != this->numCoefficients) {\n            BOOST_LOG_TRIVIAL(error) << \"Trying to set \" << this->numCoefficients << \" coefficients with vector of \"\n                                     << coeffs.size() << \" values.\";\n            return false;\n        }\n        if (this->useNonDefaultCoefficient == false) {\n            BOOST_LOG_TRIVIAL(error)\n                << \"Trying to set non default coefficient, but this scoring function was constructed with default coefficients only.\";\n            BOOST_LOG_TRIVIAL(error) << \"Check the parameters passed to the scoring function constructor.\";\n            return false;\n        }\n        for (unsigned int j = 0; j < this->nonDefaultCoefficients.size(); ++j) {\n            this->nonDefaultCoefficients[j] = coeffs[j];\n        }\n        return true;\n    }\n\n}", "meta": {"hexsha": "122028bf783b7682537ddb4ce612a9d59027a4bb", "size": 41698, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Engines/ScoringFunctions/VinaLike.cpp", "max_stars_repo_name": "ElianeBriand/SMolDock", "max_stars_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-30T02:33:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-30T02:33:13.000Z", "max_issues_repo_path": "Engines/ScoringFunctions/VinaLike.cpp", "max_issues_repo_name": "ElianeBriand/SMolDock", "max_issues_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Engines/ScoringFunctions/VinaLike.cpp", "max_forks_repo_name": "ElianeBriand/SMolDock", "max_forks_repo_head_hexsha": "de0cb746ef995ae0eef0f812ebd61727311c332f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-12-30T19:11:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T02:45:49.000Z", "avg_line_length": 50.6658566221, "max_line_length": 134, "alphanum_fraction": 0.545277951, "num_tokens": 8829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.3557748935136303, "lm_q1q2_score": 0.2253514641863928}}
{"text": "#pragma once\n//===----------------------------------------------------------------------===//\n#include \"bah_patterns.hpp\"\n#include \"bah_types.hpp\"\n\n#include <dtl/bitmap/util/plain_bitmap.hpp>\n#include <dtl/dtl.hpp>\n\n#include <boost/dynamic_bitset.hpp>\n\n#include <cstddef>\n#include <iomanip>\n#include <type_traits>\n#include <vector>\n//===----------------------------------------------------------------------===//\nnamespace dtl {\n//===----------------------------------------------------------------------===//\n/// Implementation of the Byte Aligned Hybrid bitmap compression technique as\n/// described in the paper 'BAH: A Bitmap Index Compression Algorithm for Fast\n/// Data Retrieval' by Li et al.\nclass bah {\n  static constexpr std::size_t word_bitlength = sizeof(bah_word_t) * 8;\n\n  /// The encoded bitmap.\n  std::vector<bah_byte_t> main_;\n  std::vector<bah_word_t> data_;\n  std::vector<bah_byte_t> index_;\n  std::vector<bah_word_t> counter_;\n  /// The length of the encoded bitmap.\n  std::size_t encoded_bitmap_length_ = 0;\n\n  /// The different word kinds.\n  enum class word_kind {\n    ZERO,\n    ENCODABLE,\n    LITERAL\n  };\n\n  /// Determines the word kind for a single word of the plain bitmap.\n  static word_kind\n  get_word_kind(bah_word_t word) {\n    if (word == 0) {\n      return word_kind::ZERO;\n    }\n    if (get_oep_code(word) != dtl::bah_code_not_found) {\n      return word_kind::ENCODABLE;\n    }\n    if (get_tep_code(word) != dtl::bah_code_not_found) {\n      return word_kind::ENCODABLE;\n    }\n    return word_kind::LITERAL;\n  }\n\npublic:\n  bah() = default;\n\n  explicit bah(const boost::dynamic_bitset<$u32>& in) {\n    auto* bitmap_begin = in.m_bits.data();\n    auto* bitmap_end = in.m_bits.data() + in.m_bits.size();\n    const auto word_cnt = bitmap_end - bitmap_begin; // TODO handle the case when the bitmap size is not a multiple of the word size\n\n    // The plain bitmap is segmented into words of the same kind.\n    // Keep track of the first and last word of the current segment.\n    std::size_t seg_begin = 0;\n    std::size_t seg_end = 0;\n\n    // Encode the bitmap segment by segment.\n    while (seg_begin < word_cnt) {\n      auto& w = bitmap_begin[seg_begin];\n      auto seg_kind = get_word_kind(w);\n      seg_end = seg_begin + 1;\n      // Find the end of the current 'segment'.\n      while (seg_end < word_cnt\n          && get_word_kind(bitmap_begin[seg_end]) == seg_kind) {\n        auto seg_len = seg_end - seg_begin;\n        if ((seg_kind == word_kind::LITERAL && seg_len == 63)\n            || (seg_kind == word_kind::ENCODABLE)) {\n          break;\n        }\n        ++seg_end;\n      }\n      // Encode the segment.\n      if (seg_kind == word_kind::ZERO) {\n        auto len = seg_end - seg_begin;\n        if (len > 252) {\n          main_.push_back(bah_byte_t(0));\n          counter_.push_back(len);\n        }\n        else {\n          while (len > 0) {\n            auto l = std::min(len, 63ul);\n            main_.push_back(static_cast<bah_byte_t>(l));\n            len -= l;\n          }\n        }\n      }\n      else if (seg_kind == word_kind::LITERAL) {\n        auto len = seg_end - seg_begin;\n        main_.push_back(static_cast<bah_byte_t>(len) | (bah_byte_t(0b01) << 6));\n        for (std::size_t i = seg_begin; i < seg_end; ++i) {\n          data_.push_back(bitmap_begin[i]);\n        }\n      }\n      else { /* ENCODABLE */\n        auto code = get_oep_code(w);\n        if (code != dtl::bah_code_not_found) {\n          main_.push_back(\n              static_cast<bah_byte_t>(code) | (bah_byte_t(0b10) << 6));\n        }\n        else {\n          code = get_tep_code(w);\n          bah_byte_t code_lo = code & 0b111111;\n          bah_byte_t code_hi = code >> 6;\n          main_.push_back(code_lo | (bah_byte_t(0b11) << 6));\n          index_.push_back(code_hi);\n        }\n      }\n\n      // Next.\n      seg_begin = seg_end;\n    }\n    encoded_bitmap_length_ = in.size();\n\n    // Try to reduce the memory consumption.\n    shrink();\n  }\n\n  ~bah() = default;\n  bah(const bah& other) = default;\n  bah(bah&& other) noexcept = default;\n  bah& operator=(const bah& other) = default;\n  bah& operator=(bah&& other) noexcept = default;\n\n  /// Return the size in bytes.\n  std::size_t __forceinline__\n  size_in_bytes() const {\n    return main_.size() * sizeof(bah_byte_t)\n        + data_.size() * sizeof(bah_word_t)\n        + index_.size() * sizeof(bah_byte_t)\n        + counter_.size() * sizeof(bah_word_t)\n        + 3 * sizeof(void*) /* pointers/offsets to the three other arrays */\n        + sizeof(encoded_bitmap_length_); /* bit-length of the original bitmap */\n  }\n\n  /// Returns the size of the bitmap.\n  std::size_t __forceinline__\n  size() const {\n    return encoded_bitmap_length_;\n  }\n\n  /// Conversion to an plain bitmap. // TODO remove\n  dtl::plain_bitmap<$u64>\n  to_plain_bitmap() {\n    dtl::plain_bitmap<$u64> ret(encoded_bitmap_length_, false);\n    // The write position.\n    std::size_t i = 0;\n\n    // The read position(s).\n    std::size_t data_idx = 0;\n    std::size_t index_idx = 0;\n    std::size_t counter_idx = 0;\n    for (std::size_t main_idx = 0; main_idx < main_.size(); ++main_idx) {\n      const auto& w = main_[main_idx];\n      const auto type = w >> 6;\n      const auto n = w & 0b111111;\n      switch (type) {\n        case 0b00: { /* ZERO */\n          std::size_t count = 0;\n          if (n == 0) {\n            count = counter_[counter_idx++];\n          }\n          else {\n            count = n;\n          }\n          auto l = count * word_bitlength;\n          ret.clear(i, std::min(i + l, encoded_bitmap_length_));\n          i += l;\n          break;\n        }\n        case 0b01: { /* LITERAL */\n          for (std::size_t j = 0; j < n; ++j) {\n            auto lit = data_[data_idx++];\n            ret.store_bits(i,\n                std::min(i + word_bitlength, encoded_bitmap_length_), lit);\n            i += word_bitlength;\n          }\n          break;\n        }\n        case 0b10: { /* ENCODABLE (one byte) */\n          auto pattern = get_oep(n);\n          ret.store_bits(i,\n              std::min(i + word_bitlength, encoded_bitmap_length_), pattern);\n          i += word_bitlength;\n          break;\n        }\n        case 0b11: { /* ENCODABLE (two bytes) */\n          auto code = bah_word_t(n) | (bah_word_t(index_[index_idx++]) << 6);\n          auto pattern = get_tep(code);\n          ret.store_bits(i,\n              std::min(i + word_bitlength, encoded_bitmap_length_), pattern);\n          i += word_bitlength;\n          break;\n        }\n      }\n    }\n    if (i < encoded_bitmap_length_) {\n      ret.clear(i, encoded_bitmap_length_);\n    }\n    return std::move(ret);\n  }\n\n  static std::string\n  name() {\n    return \"bah\";\n  }\n\n  /// Returns the value of the bit at the position pos.\n  u1 __forceinline__\n  test(const std::size_t pos) const {\n    // The current range spanned by the current encoded word.\n    std::size_t b = 0;\n    std::size_t e = 0;\n\n    // The read position(s).\n    std::size_t data_idx = 0;\n    std::size_t index_idx = 0;\n    std::size_t counter_idx = 0;\n    for (std::size_t main_idx = 0; main_idx < main_.size(); ++main_idx) {\n      const auto& w = main_[main_idx];\n      const auto type = w >> 6;\n      const auto n = w & 0b111111;\n      switch (type) {\n        case 0b00: { /* ZERO */\n          std::size_t count = 0;\n          if (n == 0) {\n            count = counter_[counter_idx++];\n          }\n          else {\n            count = n;\n          }\n          auto l = count * word_bitlength;\n          e = std::min(b + l, encoded_bitmap_length_);\n          if (b <= pos && pos < e) {\n            return false;\n          }\n          break;\n        }\n        case 0b01: { /* LITERAL */\n          e = std::min(b + n * word_bitlength, encoded_bitmap_length_);\n          if (b <= pos && pos < e) {\n            auto offset = pos - b;\n            auto lit_word = data_[data_idx + (offset / word_bitlength)];\n            return dtl::bits::bit_test(lit_word, offset % word_bitlength);\n          }\n          data_idx += n;\n          break;\n        }\n        case 0b10: { /* ENCODABLE (one byte) */\n          e = std::min(b + word_bitlength, encoded_bitmap_length_);\n          if (b <= pos && pos < e) {\n            auto pattern = get_oep(n);\n            return dtl::bits::bit_test(pattern, pos % word_bitlength);\n          }\n          break;\n        }\n        case 0b11: { /* ENCODABLE (two bytes) */\n          e = std::min(b + word_bitlength, encoded_bitmap_length_);\n          auto code = bah_word_t(n) | (bah_word_t(index_[index_idx++]) << 6);\n          if (b <= pos && pos < e) {\n            auto pattern = get_tep(code);\n            return dtl::bits::bit_test(pattern, pos % word_bitlength);\n          }\n          break;\n        }\n      }\n      // Next.\n      b = e;\n    }\n    return false;\n  }\n\n  /// Try to reduce the memory consumption. This function is supposed to be\n  /// called after the bitmap has been modified.\n  __forceinline__ void\n  shrink() {\n    main_.shrink_to_fit();\n    data_.shrink_to_fit();\n    index_.shrink_to_fit();\n    counter_.shrink_to_fit();\n  }\n\n  //===--------------------------------------------------------------------===//\n  /// 1-run iterator\n  class iter {\n    const bah& outer_;\n\n    /// The read positions.\n    std::size_t main_idx_;\n    std::size_t data_idx_;\n    std::size_t index_idx_;\n    std::size_t counter_idx_;\n\n    //    word_kind segment_kind_;\n    bah_word_t literal_;\n    std::size_t literal_words_remaining_;\n    std::size_t literal_in_word_idx_;\n\n    /// Points to the beginning of a 1-run.\n    $u64 pos_;\n    /// The length of the current 1-run.\n    $u64 length_;\n\n  public:\n    explicit __forceinline__\n    iter(const bah& outer)\n        : outer_(outer),\n          main_idx_(0),\n          data_idx_(0),\n          index_idx_(0),\n          counter_idx_(0),\n          literal_(0),\n          literal_words_remaining_(0),\n          literal_in_word_idx_(0),\n          pos_(0), length_(0) {\n      // Find the first 1-run.\n      const auto main_cnt = outer_.main_.size();\n      while (main_idx_ < main_cnt) {\n        pos_ += length_;\n        length_ = 0;\n\n        const auto& w = outer_.main_[main_idx_++];\n        const auto type = w >> 6;\n        const auto n = w & 0b111111;\n\n        switch (type) {\n          case 0b00: { /* ZERO */\n            std::size_t count = 0;\n            if (n == 0) {\n              count = outer_.counter_[counter_idx_++];\n            }\n            else {\n              count = n;\n            }\n            auto l = count * word_bitlength;\n            length_ = l;\n            break; // Skip over zeros.\n          }\n          case 0b01: { /* LITERAL */\n            literal_ = outer_.data_[data_idx_++];\n            assert(literal_ != 0);\n            literal_words_remaining_ = n - 1;\n            assert(literal_words_remaining_ < n);\n            const std::size_t b = dtl::bits::tz_count(literal_);\n            std::size_t e = b + 1;\n            for (; e < word_bitlength; ++e) {\n              u1 is_set = dtl::bits::bit_test(literal_, e);\n              if (!is_set) break;\n            }\n            literal_in_word_idx_ = e;\n            pos_ += b;\n            length_ = e - b;\n            return;\n          }\n          case 0b10: { /* ENCODABLE (one byte) */\n            literal_ = get_oep(n);\n            assert(literal_ != 0);\n            literal_words_remaining_ = 0;\n            const std::size_t b = dtl::bits::tz_count(literal_);\n            std::size_t e = b + 1;\n            for (; e < word_bitlength; ++e) {\n              u1 is_set = dtl::bits::bit_test(literal_, e);\n              if (!is_set) break;\n            }\n            literal_in_word_idx_ = e;\n            pos_ += b;\n            length_ = e - b;\n            return;\n          }\n          case 0b11: { /* ENCODABLE (two bytes) */\n            auto code =\n                bah_word_t(n) | (bah_word_t(outer_.index_[index_idx_++]) << 6);\n            literal_ = get_tep(code);\n            assert(literal_ != 0);\n            literal_words_remaining_ = 0;\n            const std::size_t b = dtl::bits::tz_count(literal_);\n            std::size_t e = b + 1;\n            for (; e < word_bitlength; ++e) {\n              u1 is_set = dtl::bits::bit_test(literal_, e);\n              if (!is_set) break;\n            }\n            literal_in_word_idx_ = e;\n            pos_ += b;\n            length_ = e - b;\n            return;\n          }\n        }\n      }\n      pos_ = outer_.encoded_bitmap_length_;\n      length_ = 0;\n    }\n\n    /// Forward the iterator to the next 1-run.\n    void __forceinline__\n    next() {\n      const auto main_cnt = outer_.main_.size();\n      while (main_idx_ < main_cnt || literal_ != 0) {\n        pos_ += length_;\n        length_ = 0;\n\n        // Check, whether we are currently in a literal segment.\n        if (literal_ != 0) {\n          if (literal_in_word_idx_ < word_bitlength) {\n            // Find the next set bit.\n            std::size_t b = literal_in_word_idx_;\n            for (; b < word_bitlength; b++) { // TODO optimize\n              u1 is_set = dtl::bits::bit_test(literal_, b);\n              if (is_set) break;\n            }\n            if (b < word_bitlength) {\n              // Determine the length of the current 1-run and return.\n              std::size_t e = b + 1;\n              for (; e < word_bitlength; ++e) { // TODO optimize\n                u1 is_set = dtl::bits::bit_test(literal_, e);\n                if (!is_set) break;\n              }\n              pos_ += b - literal_in_word_idx_;\n              length_ = e - b;\n              literal_in_word_idx_ = e;\n              return;\n            }\n            pos_ += b - literal_in_word_idx_;\n          }\n          // Fetch the next literal word, if any.\n          if (literal_words_remaining_ > 0) {\n            literal_ = outer_.data_[data_idx_++];\n            --literal_words_remaining_;\n            literal_in_word_idx_ = 0;\n            continue;\n          }\n          else {\n            // Reached the end of the literal segment.\n            literal_ = 0;\n            literal_in_word_idx_ = 0;\n          }\n        }\n\n        assert(literal_ == 0);\n\n        if (main_idx_ >= main_cnt) break;\n\n        const auto& w = outer_.main_[main_idx_++];\n        const auto type = w >> 6;\n        const auto n = w & 0b111111;\n        switch (type) {\n          case 0b00: { /* ZERO */\n            std::size_t count = 0;\n            if (n == 0) {\n              count = outer_.counter_[counter_idx_++];\n            }\n            else {\n              count = n;\n            }\n            auto l = count * word_bitlength;\n            length_ = l;\n            break; // Skip over zeros.\n          }\n          case 0b01: { /* LITERAL */\n            literal_ = outer_.data_[data_idx_++];\n            assert(literal_ != 0);\n            literal_words_remaining_ = n - 1;\n            assert(literal_words_remaining_ < n);\n            const std::size_t b = dtl::bits::tz_count(literal_);\n            std::size_t e = b + 1;\n            for (; e < word_bitlength; ++e) {\n              u1 is_set = dtl::bits::bit_test(literal_, e);\n              if (!is_set) break;\n            }\n            literal_in_word_idx_ = e;\n            pos_ += b;\n            length_ = e - b;\n            return;\n          }\n          case 0b10: { /* ENCODABLE (one byte) */\n            literal_ = get_oep(n);\n            assert(literal_ != 0);\n            literal_words_remaining_ = 0;\n            const std::size_t b = dtl::bits::tz_count(literal_);\n            std::size_t e = b + 1;\n            for (; e < word_bitlength; ++e) { // TODO optimize\n              u1 is_set = dtl::bits::bit_test(literal_, e);\n              if (!is_set) break;\n            }\n            literal_in_word_idx_ = e;\n            pos_ += b;\n            length_ = e - b;\n            return;\n          }\n          case 0b11: { /* ENCODABLE (two bytes) */\n            auto code =\n                bah_word_t(n) | (bah_word_t(outer_.index_[index_idx_++]) << 6);\n            literal_ = get_tep(code);\n            assert(literal_ != 0);\n            literal_words_remaining_ = 0;\n            const std::size_t b = dtl::bits::tz_count(literal_);\n            std::size_t e = b + 1;\n            for (; e < word_bitlength; ++e) { // TODO optimize\n              u1 is_set = dtl::bits::bit_test(literal_, e);\n              if (!is_set) break;\n            }\n            literal_in_word_idx_ = e;\n            pos_ += b;\n            length_ = e - b;\n            return;\n          }\n        }\n      }\n      pos_ = outer_.encoded_bitmap_length_;\n      length_ = 0;\n    }\n\n    /// Forward the iterator to the desired position.\n    void __forceinline__\n    skip_to(const std::size_t to_pos) {\n      assert(pos_ <= to_pos);\n      if (to_pos >= outer_.encoded_bitmap_length_) {\n        pos_ = outer_.encoded_bitmap_length_;\n        length_ = 0;\n        return;\n      }\n      // Call next until the desired position has been reached.\n      while (!end() && pos() + length() <= to_pos) {\n        next();\n      }\n      // Adjust the current position and run length.\n      if (!end() && pos() < to_pos) {\n        length_ -= to_pos - pos_;\n        pos_ = to_pos;\n      }\n    }\n\n    u1 __forceinline__\n    end() const noexcept {\n      return length_ == 0;\n    }\n\n    u64 __forceinline__\n    pos() const noexcept {\n      return pos_;\n    }\n\n    u64 __forceinline__\n    length() const noexcept {\n      return length_;\n    }\n  };\n  //===--------------------------------------------------------------------===//\n\n  using skip_iter_type = iter;\n  using scan_iter_type = iter;\n\n  /// Returns a 1-run iterator.\n  skip_iter_type __forceinline__\n  it() const {\n    return skip_iter_type(*this);\n  }\n\n  /// Returns a 1-run iterator.\n  scan_iter_type __forceinline__\n  scan_it() const {\n    return scan_iter_type(*this);\n  }\n\n  /// Returns the name of the instance including the most important parameters\n  /// in JSON.\n  std::string\n  info() const {\n    return \"{\\\"name\\\":\\\"\" + name() + \"\\\"\"\n        + \",\\\"n\\\":\" + std::to_string(encoded_bitmap_length_)\n        + \",\\\"size\\\":\" + std::to_string(size_in_bytes())\n        + \",\\\"word_size\\\":\" + std::to_string(sizeof(bah_word_t))\n        + \"}\";\n  }\n\n  // For debugging purposes.\n  void\n  print(std::ostream& os) const {\n    os << \"main idx | word type | content\" << std::endl;\n    os << \"---------|-----------|---------------------------------\" << std::endl;\n    // The read position(s).\n    std::size_t data_idx = 0;\n    std::size_t index_idx = 0;\n    std::size_t counter_idx = 0;\n    for (std::size_t main_idx = 0; main_idx < main_.size(); ++main_idx) {\n      os << std::setw(8) << main_idx << \" | \";\n      auto& w = main_[main_idx];\n      const auto type = w >> 6;\n      const auto n = w & 0b111111;\n      switch (type) {\n        case 0b00: { /* ZERO */\n          std::size_t count = 0;\n          if (n == 0) {\n            count = counter_[counter_idx++];\n          }\n          else {\n            count = n;\n          }\n          os << count << \" x ZERO\";\n          break;\n        }\n        case 0b01: { /* LITERAL */\n          os << n << \" x LITERAL\";\n          for (std::size_t i = 0; i < n; ++i) {\n            os << std::endl;\n            os << \"         |           | \"\n               << std::bitset<word_bitlength>(data_[data_idx + i]);\n          }\n          data_idx += n;\n          break;\n        }\n        case 0b10: { /* ENCODABLE (one byte) */\n          os << \"1\"\n             << \" x ENCODABLE (one byte)\";\n          os << std::endl;\n          os << \"         |           | \"\n              << std::bitset<word_bitlength>(get_oep(n));\n          break;\n        }\n        case 0b11: { /* ENCODABLE (two bytes) */\n          os << \"1\"\n             << \" x ENCODABLE (two bytes)\";\n          auto code = bah_word_t(n) | (bah_word_t(index_[index_idx++]) << 6);\n          os << std::endl;\n          os << \"         |           | \"\n              << std::bitset<word_bitlength>(get_tep(code));\n          break;\n        }\n      }\n      os << std::endl;\n    }\n  }\n};\n//===----------------------------------------------------------------------===//\n} // namespace dtl\n", "meta": {"hexsha": "bd733e5e86b552a2ee46559bf67c3d2bae1dd3c3", "size": 19992, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/dtl/bitmap/bah.hpp", "max_stars_repo_name": "harald-lang/tree-encoded-bitmaps", "max_stars_repo_head_hexsha": "a4ab056f2cefa7843b27c736833b08977b56649c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T12:51:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T07:38:24.000Z", "max_issues_repo_path": "src/dtl/bitmap/bah.hpp", "max_issues_repo_name": "marcellus-saputra/Thuja", "max_issues_repo_head_hexsha": "8443320a6d0e9a20bb6b665f0befc6988978cafd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dtl/bitmap/bah.hpp", "max_forks_repo_name": "marcellus-saputra/Thuja", "max_forks_repo_head_hexsha": "8443320a6d0e9a20bb6b665f0befc6988978cafd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-07T13:43:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-09T04:49:39.000Z", "avg_line_length": 31.0434782609, "max_line_length": 132, "alphanum_fraction": 0.5025510204, "num_tokens": 5150, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.22532227439123587}}
{"text": "/*\n * KMajority.cpp\n *\n *  Created on: Aug 28, 2013\n *      Author: andresf\n */\n\n#include <KMajority.h>\n#include <CentersChooser.h>\n\n#include <boost/iostreams/filter/gzip.hpp>\n#include <boost/iostreams/filtering_stream.hpp>\n\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/flann/random.h>\n#include <opencv2/flann/dist.h>\n\n#include <iostream>\n#include <bitset>\n#include <fstream>\n#include <functional>\n\nnamespace vlr {\n\nKMajority::KMajority(vlr::Mat& data, const cvflann::IndexParams& params,\n\t\tconst cvflann::IndexParams& nnIndexParams) :\n\t\tm_dataset(data), m_dim(data.cols), m_nnIndex(NULL), m_nnIndexParams(\n\t\t\t\tnnIndexParams) {\n\n\t// Attributes initialization\n\tm_numClusters = cvflann::get_param<int>(params, \"num.clusters\");\n\tm_maxIterations = cvflann::get_param<int>(params, \"max.iterations\");\n\tm_centersInitMethod = cvflann::get_param<cvflann::flann_centers_init_t>(\n\t\t\tparams, \"centers.init.method\");\n\tm_nnType = cvflann::get_param<vlr::indexType>(params, \"nn.type\");\n\tm_numDatapoints = m_dataset.rows;\n\n\t// Initially all transactions belong to any cluster\n\tm_belongsTo.clear();\n\tm_belongsTo.resize(m_dataset.rows, m_numClusters);\n\n\t// Initially all transactions are at the farthest possible distance\n\t// i.e. m_dim*8 the max Hamming distance\n\tm_distanceTo.clear();\n\tm_distanceTo.resize(m_dataset.rows, data.cols * 8);\n\n\t// Initially no transaction is assigned to any cluster\n\tm_clusterCounts.clear();\n\tm_clusterCounts.resize(m_numClusters, 0);\n\n}\n\n// --------------------------------------------------------------------------\n\nKMajority::~KMajority() {\n\tdelete m_nnIndex;\n}\n\n// --------------------------------------------------------------------------\n\nvoid KMajority::build() {\n\n\tif (m_dataset.type() != CV_8U) {\n\t\tthrow std::runtime_error(\n\t\t\t\t\"[KMajority::build] Descriptors matrix is not binary\");\n\t}\n\n\tif (m_dataset.empty()) {\n\t\tthrow std::runtime_error(\"[KMajority::build] Descriptors is empty\");\n\t}\n\n\t// Trivial case: less data than clusters, assign one data point per cluster\n\tif (m_numDatapoints <= m_numClusters) {\n\t\tm_centroids.create(m_numClusters, m_dim, m_dataset.type());\n\t\tfor (int i = 0; i < m_numDatapoints; ++i) {\n\t\t\tm_dataset.row(i).copyTo(\n\t\t\t\t\tm_centroids(cv::Range(i, i + 1), cv::Range(0, m_dim)));\n\t\t\tm_belongsTo[i] = i;\n\t\t}\n\t\treturn;\n\t}\n\n#if KMAJVERBOSE\n\tprintf(\"-- Bootstrapping clustering process\\n\");\n#endif\n\n\t// Randomly generate clusters\n#if KMAJVERBOSE\n\tprintf(\"   Initializing clusters centers.\\n\");\n#endif\n\tinitCentroids();\n\n\t// Update nearest neighbors index upon new centers\n#if KMAJVERBOSE\n\tprintf(\"   Updating nearest neighbors index.\\n\");\n#endif\n\tupdateIndex();\n\n\t// Assign data to clusters\n#if KMAJVERBOSE\n\tprintf(\"   Quantizing data into clusters.\\n\");\n#endif\n\tquantize();\n\n\tbool converged = false;\n\tint iteration = 0;\n\n\twhile (converged == false && iteration < m_maxIterations) {\n\n\t\t++iteration;\n\n#if KMAJVERBOSE\n\t\tprintf(\"-- Iteration=[%d]\\n\", iteration);\n\t\tfflush(stdout);\n#endif\n\n\t\t// Compute the new clusters centers\n#if KMAJVERBOSE\n\t\tprintf(\"   Computing new clusters centers.\\n\");\n#endif\n\t\tcomputeCentroids();\n\n\t\t// Update nearest neighbors index upon new centers\n#if KMAJVERBOSE\n\t\tprintf(\"   Updating nearest neighbors index.\\n\");\n#endif\n\t\tupdateIndex();\n\n\t\t// Reassign data to clusters\n#if KMAJVERBOSE\n\t\tprintf(\"   Quantizing data into clusters.\\n\");\n#endif\n\t\tconverged = quantize();\n\n\t\t// Handle empty clusters case\n#if KMAJVERBOSE\n\t\tprintf(\"   Handling empty clusters case.\\n\");\n#endif\n\t\thandleEmptyClusters();\n\t}\n\n}\n\n// --------------------------------------------------------------------------\n\nvoid KMajority::initCentroids() {\n\n\t// Initializing variables useful for obtaining indexes of random chosen center\n\tstd::vector<int> centers_idx(m_numClusters);\n\tint centers_length;\n\n\t// Array of indices indicating data points involved in the clustering process\n\tint* indices = new int[m_dataset.rows];\n\tfor (int i = 0; i < m_dataset.rows; ++i) {\n\t\tindices[i] = i;\n\t}\n\n\t// Randomly chose centers\n\tCentersChooser<Distance::ElementType, cv::Hamming>::create(\n\t\t\tm_centersInitMethod)->chooseCenters(m_numClusters, indices,\n\t\t\tm_numDatapoints, centers_idx, centers_length, m_dataset);\n\tCV_Assert(centers_length == m_numClusters);\n\n\tstd::sort(centers_idx.begin(), centers_idx.end());\n\n\tdelete[] indices;\n\n\t// Assign centers based on the chosen indexes\n\tm_centroids.create(centers_length, m_dim, m_dataset.type());\n\tfor (int i = 0; i < centers_length; ++i) {\n\t\tm_dataset.row(centers_idx[i]).copyTo(\n\t\t\t\tm_centroids(cv::Range(i, i + 1), cv::Range(0, m_dim)));\n\t}\n\n}\n\n// --------------------------------------------------------------------------\n\nbool KMajority::quantize() {\n\n\tbool converged = true;\n\n\t// Number of nearest neighbors\n\tint knn = 1;\n\n\t// The indices of the nearest neighbors found (numQueries X numNeighbors)\n\tcvflann::Matrix<int> indices(new int[1 * knn], 1, knn);\n\n\t// Distances to the nearest neighbors found (numQueries X numNeighbors)\n\tcvflann::Matrix<DistanceType> distances(new DistanceType[1 * knn], 1, knn);\n\n\tfor (int i = 0; i < m_numDatapoints; ++i) {\n\t\tstd::fill(indices.data, indices.data + indices.rows * indices.cols, 0);\n\t\tstd::fill(distances.data,\n\t\t\t\tdistances.data + distances.rows * distances.cols, 0.0f);\n\n\t\tcvflann::Matrix<Distance::ElementType> descriptor(\n\t\t\t\t(Distance::ElementType*) m_dataset.row(i).data, 1,\n\t\t\t\tm_dataset.cols);\n\n\t\t/* Get new cluster it belongs to */\n\t\tm_nnIndex->knnSearch(descriptor, indices, distances, knn,\n\t\t\t\tcvflann::SearchParams());\n\n\t\t/* Check if cluster assignment changed */\n\t\t// If it did then algorithm hasn't converged yet\n\t\tif (m_belongsTo[i] != indices[0][0]) {\n\t\t\tconverged = false;\n\t\t}\n\n\t\t/* Update cluster assignment and cluster counts */\n\t\t// Decrease cluster count in case it was assigned to some valid cluster before.\n\t\t// Recall that initially all transaction are assigned to kth cluster which\n\t\t// is not valid since valid clusters run from 0 to k-1 both inclusive.\n\t\tif (m_belongsTo[i] != m_numClusters) {\n\t\t\t--m_clusterCounts[m_belongsTo[i]];\n\t\t}\n\t\tm_belongsTo[i] = indices[0][0];\n\t\t++m_clusterCounts[indices[0][0]];\n\t\tm_distanceTo[i] = distances[0][0];\n\t}\n\n\tdelete[] indices.data;\n\tdelete[] distances.data;\n\n\treturn converged;\n}\n\n// --------------------------------------------------------------------------\n\nvoid KMajority::computeCentroids() {\n\n\t// Warning: using matrix of integers, there might be an overflow when summing too much descriptors\n\tcv::Mat bitwiseCount(m_numClusters, m_dim * 8, cv::DataType<int>::type);\n\t// Zeroing matrix of cumulative bits\n\tbitwiseCount = cv::Scalar::all(0);\n\t// Zeroing all cluster centers dimensions\n\tm_centroids = cv::Scalar::all(0);\n\n\t// Bitwise summing the data into each center\n\tfor (int i = 0; i < m_numDatapoints; ++i) {\n\t\tcv::Mat b = bitwiseCount.row(m_belongsTo[i]);\n\t\tKMajority::cumBitSum(m_dataset.row(i), b);\n\t}\n\n\t// Bitwise majority voting\n\tfor (int j = 0; j < m_numClusters; j++) {\n\t\tcv::Mat centroid = m_centroids.row(j);\n\t\tKMajority::majorityVoting(bitwiseCount.row(j), centroid,\n\t\t\t\tm_clusterCounts[j]);\n\t}\n}\n\n// --------------------------------------------------------------------------\n\nvoid KMajority::save(const std::string& filename) const {\n\n\tif (m_centroids.empty()) {\n\t\tthrow std::runtime_error(\"[KMajority::save] Tree is empty\");\n\t}\n\n\tcv::FileStorage fs(filename.c_str(), cv::FileStorage::WRITE);\n\n\tif (fs.isOpened() == false) {\n\t\tthrow std::runtime_error(\"[KMajority::save] \"\n\t\t\t\t\"Unable to open file [\" + filename + \"] for writing\");\n\t}\n\n\tfs << \"type\" << \"AKMAJ\";\n\tfs << \"Centers\" << m_centroids;\n\n\tfs.release();\n\n}\n\n// --------------------------------------------------------------------------\n\nvoid KMajority::load(const std::string& filename) {\n\n\tenum nodeFields {\n\t\theader, start, rows, cols, dt, data\n\t};\n\tstd::string nodeFieldsNames[] = { \"YAML\", \"Centers\", \"rows:\", \"cols:\",\n\t\t\t\"dt:\", \"data:\" };\n\n\tstd::ifstream inputZippedFileStream;\n\tboost::iostreams::filtering_istream inputFileStream;\n\n\tstd::string line, field;\n\tstd::stringstream ss;\n\n\t// Open file\n\tinputZippedFileStream.open(filename.c_str(),\n\t\t\tstd::fstream::in | std::fstream::binary);\n\n\t// Check file\n\tif (inputZippedFileStream.good() == false) {\n\t\tthrow std::runtime_error(\"[KMajority::load] \"\n\t\t\t\t\"Unable to open file [\" + filename + \"] for reading\");\n\t}\n\n\tint _rows = -1;\n\tint _cols = -1;\n\tstd::string _type;\n\tint elemIdx = -1;\n\tunsigned int elem;\n\n\ttry {\n\t\tinputFileStream.push(boost::iostreams::gzip_decompressor());\n\t\tinputFileStream.push(inputZippedFileStream);\n\n\t\twhile (getline(inputFileStream, line)) {\n\t\t\tss.clear();\n\t\t\tss.str(line);\n\t\t\tss >> field;\n\t\t\tif (field.compare(nodeFieldsNames[header]) == 0) {\n\t\t\t\tcontinue;\n\t\t\t} else if (field.compare(nodeFieldsNames[start]) == 0) {\n\t\t\t\tcontinue;\n\t\t\t} else if (field.compare(nodeFieldsNames[rows]) == 0) {\n\t\t\t\tss >> _rows;\n\t\t\t} else if (field.compare(nodeFieldsNames[cols]) == 0) {\n\t\t\t\tss >> _cols;\n\t\t\t} else if (field.compare(nodeFieldsNames[dt]) == 0) {\n\t\t\t\tss >> _type;\n\t\t\t} else {\n\t\t\t\tif (field.compare(nodeFieldsNames[data]) == 0) {\n\t\t\t\t\tm_centroids = cv::Mat::zeros(_rows, _cols,\n\t\t\t\t\t\t\t_type.compare(\"f\") == 0 ? CV_32F : CV_8U);\n\t\t\t\t\tline.replace(line.find(nodeFieldsNames[data]), 5, \" \");\n\t\t\t\t}\n\n\t\t\t\tstd::replace(line.begin(), line.end(), '[', ' ');\n\t\t\t\tstd::replace(line.begin(), line.end(), ',', ' ');\n\t\t\t\tstd::replace(line.begin(), line.end(), ']', ' ');\n\n\t\t\t\tss.clear();\n\t\t\t\tss.str(line);\n\n\t\t\t\twhile ((ss >> elem).fail() == false) {\n\t\t\t\t\t++elemIdx;\n\t\t\t\t\tint row = floor(elemIdx / _cols);\n\t\t\t\t\tint col = elemIdx % _cols;\n\t\t\t\t\tm_centroids.at<uchar>(row, col) = elem;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t} catch (const boost::iostreams::gzip_error& e) {\n\t\tthrow std::runtime_error(\"[KMajority::load] \"\n\t\t\t\t\"Got error while parsing file [\" + std::string(e.what()) + \"]\");\n\t}\n\n\t// Close file\n\tinputZippedFileStream.close();\n\n}\n\n// --------------------------------------------------------------------------\n\nvoid KMajority::cumBitSum(const cv::Mat& data, cv::Mat& accVector) {\n\n\t// cumResult and data must be row vectors\n\tif (data.rows != 1 || accVector.rows != 1) {\n\t\tthrow std::runtime_error(\n\t\t\t\t\"[KMajority::cumBitSum] data and cumResult parameters must be row vectors\\n\");\n\t}\n\t// cumResult and data must be same length\n\tif (data.cols * 8 != accVector.cols) {\n\t\tthrow std::runtime_error(\n\t\t\t\t\"[KMajority::cumBitSum] number of columns in cumResult must be that of data times 8\\n\");\n\t}\n\n\tuchar byte = 0;\n\tfor (int l = 0; l < accVector.cols; l++) {\n\t\t// bit: 7-(l%8) col: (int)l/8 descriptor: i\n\t\t// Load byte every 8 bits\n\t\tif ((l % 8) == 0) {\n\t\t\tbyte = *(data.col((int) l / 8).data);\n\t\t}\n\t\t// Note: ignore maybe-uninitialized warning because loop starts with l=0 that means byte gets a value as soon as the loop start\n\t\t// bit at ith position is mod(bitleftshift(byte,i),2) where ith position is 7-mod(l,8) i.e 7, 6, 5, 4, 3, 2, 1, 0\n\t\taccVector.at<int>(0, l) += ((int) ((byte >> (7 - (l % 8))) % 2));\n\t}\n\n}\n\n// --------------------------------------------------------------------------\n\nvoid KMajority::majorityVoting(const cv::Mat& accVector, cv::Mat& result,\n\t\tconst int& threshold) {\n\n\t// cumResult and data must be a row vectors\n\tif (accVector.rows != 1 || result.rows != 1) {\n\t\tthrow std::runtime_error(\n\t\t\t\t\"[KMajority::majorityVoting] 'accVector' and 'result' parameters must be row vectors\\n\");\n\t}\n\n\t// cumResult and data must be same length\n\tif (result.cols * 8 != accVector.cols) {\n\t\tthrow std::runtime_error(\n\t\t\t\t\"[KMajority::majorityVoting] number of columns in 'accVector' must be that of 'result' times 8\\n\");\n\t}\n\n\t// In this point I already have stored in bitwiseCount the bitwise sum of all data assigned to jth cluster\n\tfor (int l = 0; l < accVector.cols; ++l) {\n\t\t// If the bitcount for jth cluster at dimension l is greater than half of the data assigned to it\n\t\t// then set lth centroid bit to 1 otherwise set it to 0 (break ties randomly)\n\t\tbool bit;\n\t\t// There is a tie if the number of data assigned to jth cluster is even\n\t\t// AND the number of bits set to 1 in lth dimension is the half of the data assigned to jth cluster\n\t\tif (threshold % 2 == 1\n\t\t\t\t&& 2 * accVector.at<int>(0, l) == (int) threshold) {\n\t\t\tbit = rand() % 2;\n\t\t} else {\n\t\t\tbit = 2 * accVector.at<int>(0, l) > (int) (threshold);\n\t\t}\n\t\t// Stores the majority voting result from the LSB to the MSB\n\t\tresult.at<unsigned char>(0, (int) (accVector.cols - 1 - l) / 8) += (bit)\n\t\t\t\t<< ((accVector.cols - 1 - l) % 8);\n\t}\n}\n\n// --------------------------------------------------------------------------\n\nvoid KMajority::handleEmptyClusters() {\n\n\t// If some cluster appeared to be empty then:\n\t// 1. Find the biggest cluster.\n\t// 2. Find farthest point in the biggest cluster\n\t// 3. Exclude the farthest point from the biggest cluster and form a new 1-point cluster.\n\n\tfor (int k = 0; k < m_numClusters; ++k) {\n\t\tif (m_clusterCounts[k] != 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// 1. Find the biggest cluster\n\t\tint max_k = 0;\n\t\tfor (int k1 = 1; k1 < m_numClusters; ++k1) {\n\t\t\tif (m_clusterCounts[max_k] < m_clusterCounts[k1])\n\t\t\t\tmax_k = k1;\n\t\t}\n\n\t\t// 2. Find farthest point in the biggest cluster\n\t\tDistanceType maxDist(-1);\n\t\tint idxFarthestPt = -1;\n\t\tfor (int i = 0; i < m_numDatapoints; ++i) {\n\t\t\tif (m_belongsTo[i] == max_k) {\n\t\t\t\tif (maxDist < m_distanceTo[i]) {\n\t\t\t\t\tmaxDist = m_distanceTo[i];\n\t\t\t\t\tidxFarthestPt = i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// 3. Exclude the farthest point from the biggest cluster and form a new 1-point cluster\n\t\t--m_clusterCounts[max_k];\n\t\t++m_clusterCounts[k];\n\t\tm_belongsTo[idxFarthestPt] = k;\n\t}\n}\n\n// --------------------------------------------------------------------------\n\nvoid KMajority::updateIndex() {\n\n\tm_nnIndex = vlr::createIndexByType(\n\t\t\tcvflann::Matrix<Distance::ElementType>(\n\t\t\t\t\t(Distance::ElementType*) m_centroids.data, m_centroids.rows,\n\t\t\t\t\tm_centroids.cols), m_nnType, m_nnIndexParams);\n\n\tdouble mytime = cv::getTickCount();\n        m_nnIndex->buildIndex();\n\tmytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency() * 1000;\n\n\tprintf(\"   Index built in [%lf] ms\\n\", mytime);\n\n}\n\n// --------------------------------------------------------------------------\n\nconst cv::Mat& KMajority::getCentroids() const {\n\treturn m_centroids;\n}\n\n// --------------------------------------------------------------------------\n\nconst std::vector<int>& KMajority::getClusterCounts() const {\n\treturn m_clusterCounts;\n}\n\n// --------------------------------------------------------------------------\n\nconst std::vector<int>& KMajority::getClusterAssignments() const {\n\treturn m_belongsTo;\n}\n\n// --------------------------------------------------------------------------\n\ncvflann::NNIndex<Distance>* createIndexByType(\n\t\tconst cvflann::Matrix<typename Distance::ElementType>& dataset,\n\t\tvlr::indexType type, const cvflann::IndexParams& userDefParams) {\n\n\tcvflann::IndexParams::const_iterator it;\n\n\tcvflann::IndexParams params;\n\tcvflann::NNIndex<Distance>* nnIndex;\n\n\tdouble mytime = cv::getTickCount();\n\n\tswitch (type) {\n\tcase vlr::LINEAR:\n\t\tprintf(\"-- Creating [Linear] index\\n\");\n\t\tparams = cvflann::LinearIndexParams();\n\t\t// Do not copy any parameters, linear index doesn't need any\n\t\tnnIndex = new cvflann::LinearIndex<Distance>(dataset, params,\n\t\t\t\tDistance());\n\t\tbreak;\n\tcase vlr::HIERARCHICAL:\n\t\tprintf(\"-- Creating [HierarchicalClustering] index\\n\");\n\t\tparams = cvflann::HierarchicalClusteringIndexParams();\n\t\tfor (it = userDefParams.begin(); it != userDefParams.end(); ++it) {\n\t\t\tint value = it->second.cast<int>();\n\t\t\tparams[it->first] = value;\n\t\t}\n\t\tnnIndex = new cvflann::HierarchicalClusteringIndex<Distance>(dataset,\n\t\t\t\tparams, Distance());\n\t\tbreak;\n\tdefault:\n\t\tthrow std::runtime_error(\"Unknown index type\");\n\t}\n\tmytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()\n\t\t\t* 1000;\n\n\tprintf(\"   Index created in [%lf] ms\\n\", mytime);\n\n\treturn nnIndex;\n}\n\n} /* namespace vlr */\n", "meta": {"hexsha": "d0e3d5db2f8e8b342dc98e3d373ae0d1098f12d2", "size": 15776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "KMajorityLib/src/KMajority.cpp", "max_stars_repo_name": "gantzer89/VLRPipeline", "max_stars_repo_head_hexsha": "db0ab392c2586b03518ec84455cec91b6011be4e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T08:32:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-15T12:52:20.000Z", "max_issues_repo_path": "KMajorityLib/src/KMajority.cpp", "max_issues_repo_name": "afperezm/VLRPipeline", "max_issues_repo_head_hexsha": "db0ab392c2586b03518ec84455cec91b6011be4e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KMajorityLib/src/KMajority.cpp", "max_forks_repo_name": "afperezm/VLRPipeline", "max_forks_repo_head_hexsha": "db0ab392c2586b03518ec84455cec91b6011be4e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T22:33:23.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-16T02:49:03.000Z", "avg_line_length": 29.0, "max_line_length": 129, "alphanum_fraction": 0.62918357, "num_tokens": 4251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.22532226845945538}}
{"text": "/**\n * ****************************************************************************\n * Copyright (c) 2015, Robert Lukierski.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n * \n * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n * ****************************************************************************\n * Gaussian distribution.\n * ****************************************************************************\n */\n#ifndef VISIONCORE_TYPES_GAUSSIAN_HPP\n#define VISIONCORE_TYPES_GAUSSIAN_HPP\n\n#include <VisionCore/Platform.hpp>\n\n#include <Eigen/Dense>\n\nnamespace vc\n{\nnamespace types\n{\n    template<typename T> class Gaussian;\n    template<typename _Scalar, int _Dimension = 1> class MultivariateGaussian;\n}\n}\n\nnamespace Eigen \n{\n    namespace internal \n    {\n        // Gaussian of scalars or Eigens\n        template<typename T>\n        struct traits< vc::types::Gaussian<T> > \n        {\n            static constexpr int Rows = 1;\n            static constexpr int Cols = 1;\n            static constexpr int Dimension = Rows * Cols;\n            typedef T Scalar;\n            typedef Scalar MeanType;\n        };\n        \n        template<typename _Scalar, int _Rows, int _Cols>\n        struct traits<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols> > > \n        {\n            static constexpr int Rows = _Rows;\n            static constexpr int Cols = _Cols;\n            static constexpr int Dimension = Rows * Cols;\n            typedef _Scalar Scalar;\n            typedef Matrix<Scalar,_Rows,_Cols> MeanType;\n        };\n        \n        template<typename _Scalar, int _Rows, int _Cols, int _Options>\n        struct traits<Map<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols> >, _Options> > : \n            traits<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols> > >\n        {\n            static constexpr int Rows = _Rows;\n            static constexpr int Cols = _Cols;\n            static constexpr int Dimension = Rows * Cols;\n            typedef _Scalar Scalar;\n            typedef Map<Matrix<Scalar,_Rows,_Cols>, _Options> MeanType;\n        };\n        \n        template<typename _Scalar, int _Rows, int _Cols, int _Options>\n        struct traits<Map<const vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols> >, _Options> > : \n            traits<const vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols> > > \n        {\n            static constexpr int Rows = _Rows;\n            static constexpr int Cols = _Cols;\n            static constexpr int Dimension = Rows * Cols;\n            typedef _Scalar Scalar;\n            typedef Map<const Matrix<Scalar,_Rows,_Cols>, _Options> MeanType;\n        };\n        \n        // Multivariate\n        template<typename _Scalar, int _Dimension>\n        struct traits<vc::types::MultivariateGaussian<_Scalar,_Dimension> > \n        {\n            static constexpr int Dimension = _Dimension;\n            typedef _Scalar Scalar;\n            typedef Matrix<Scalar,_Dimension,1> MeanType;\n            typedef Matrix<Scalar,_Dimension,_Dimension> CovarianceType;\n        };\n        \n        template<typename _Scalar, int _Dimension, int _Options>\n        struct traits<Map<vc::types::MultivariateGaussian<_Scalar,_Dimension>, _Options> > : \n            traits<vc::types::MultivariateGaussian<_Scalar, _Dimension> > \n        {\n            static constexpr int Dimension = _Dimension;\n            typedef _Scalar Scalar;\n            typedef Map<Matrix<Scalar,_Dimension,1>, _Options> MeanType;\n            typedef Map<Matrix<Scalar,_Dimension,_Dimension>, _Options> CovarianceType;\n        };\n        \n        template<typename _Scalar, int _Dimension, int _Options>\n        struct traits<Map<const vc::types::MultivariateGaussian<_Scalar,_Dimension>, _Options> > : \n            traits<const vc::types::MultivariateGaussian<_Scalar, _Dimension> > \n        {\n            static constexpr int Dimension = _Dimension;\n            typedef _Scalar Scalar;\n            typedef Map<const Matrix<Scalar,_Dimension,1>, _Options> MeanType;\n            typedef Map<const Matrix<Scalar,_Dimension,_Dimension>, _Options> CovarianceType;\n        };\n        \n    }\n}\n\nnamespace vc\n{\n    \nnamespace types\n{\n\n/**\n * Type agnostic Gaussian operations.\n */\ntemplate<typename Derived>\nclass GaussianBase\n{\npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Derived>::Dimension;\n    static constexpr int Rows = Eigen::internal::traits<Derived>::Rows;\n    static constexpr int Cols = Eigen::internal::traits<Derived>::Cols;\n    typedef typename Eigen::internal::traits<Derived>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Derived>::MeanType MeanType;\n    typedef const typename Eigen::internal::traits<Derived>::MeanType ConstMeanType;\n    \n    EIGEN_DEVICE_FUNC MeanType& mean() \n    {\n        return static_cast<Derived*>(this)->mean_nonconst();\n    }\n    \n    EIGEN_DEVICE_FUNC const MeanType& mean() const\n    {\n        return static_cast<const Derived*>(this)->mean_const();\n    }\n    \n    EIGEN_DEVICE_FUNC MeanType& variance() \n    {\n        return static_cast<Derived*>(this)->variance_nonconst();\n    }\n    \n    EIGEN_DEVICE_FUNC const MeanType& variance() const\n    {\n        return static_cast<const Derived*>(this)->variance_const();\n    }\n    \n    template<typename OtherDerived>\n    EIGEN_DEVICE_FUNC inline GaussianBase<Derived>& operator=(const GaussianBase<OtherDerived>& other)\n    {\n        mean() = other.mean();\n        variance() = other.variance();\n        return *this;\n    }\n    \n#if 0\n    EIGEN_DEVICE_FUNC inline GaussianBase<Derived> operator+(const GaussianBase<Derived>& other) const\n    {\n    // TBD\n    }\n    \n    EIGEN_DEVICE_FUNC inline GaussianBase<Derived> operator-(const GaussianBase<Derived>& other) const\n    {\n    // TBD\n    }\n    \n    template<typename OtherScalar>\n    EIGEN_DEVICE_FUNC inline GaussianBase<Derived> operator*(const OtherScalar& other) const\n    {\n    // TBD\n    }\n    \n    template<typename OtherScalar>\n    EIGEN_DEVICE_FUNC inline GaussianBase<Derived> operator/(const OtherScalar& other) const\n    {\n    // TBD\n    }\n#endif\n    \n#ifdef VISIONCORE_ENABLE_CEREAL\n    template<typename Archive>\n    void load(Archive & archive, std::uint32_t const version)\n    {\n        archive(cereal::make_nvp(\"Mean\", mean()));\n        archive(cereal::make_nvp(\"Variance\", variance()));\n    }\n    \n    template<typename Archive>\n    void save(Archive & archive, std::uint32_t const version) const\n    {\n        archive(cereal::make_nvp(\"Mean\", mean()));\n        archive(cereal::make_nvp(\"Variance\", variance()));\n    }\n#endif // VISIONCORE_ENABLE_CEREAL \n};\n\n/**\n * Eigen operations for Gaussian.\n */\ntemplate<typename Derived, int _Dimension>\nclass GaussianDispatchingBase : public GaussianBase<Derived>\n{\n    typedef GaussianBase<Derived> Base;\n    friend class GaussianBase<Derived>;\npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Derived>::Dimension;\n    static constexpr int Rows = Eigen::internal::traits<Derived>::Rows;\n    static constexpr int Cols = Eigen::internal::traits<Derived>::Cols;\n    typedef typename Eigen::internal::traits<Derived>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Derived>::MeanType MeanType;\n    typedef const typename Eigen::internal::traits<Derived>::MeanType ConstMeanType;\n    \n    using Base::operator=;\n    \n    template<typename _NewScalarType>\n    EIGEN_DEVICE_FUNC inline Gaussian<Eigen::Matrix<_NewScalarType, Rows, Cols> >  cast() const \n    {\n        return Gaussian<Eigen::Matrix<_NewScalarType, Rows, Cols>>(Base::mean().template cast<_NewScalarType>(), \n                                                                   Base::variance().template cast<_NewScalarType>());\n    }\n    \n    EIGEN_DEVICE_FUNC inline MeanType evaluate(const MeanType& x)\n    {\n        using Eigen::numext::sqrt;\n        using Eigen::numext::exp;\n        using Eigen::numext::pow;\n        \n        const MeanType inv_sqrt_2pi_s2 = Scalar(1.0) / sqrt(Scalar(2.0 * M_PI) * Base::variance().array());\n        const MeanType a = (x - Base::mean());\n        return inv_sqrt_2pi_s2.array() * exp(-(pow(a.array(), 2))/(Scalar(2.0) * Base::variance().array()));\n    }\n    \n    EIGEN_DEVICE_FUNC inline void setZero()\n    {\n        Base::mean() = MeanType::Zero();\n        Base::variance() = MeanType::Zero();\n    }\n    \n    EIGEN_DEVICE_FUNC MeanType stddev() const\n    {\n        return sqrt(Base::variance().array());\n    }\n};\n\n/**\n * Scalar operations for Gaussian.\n */\ntemplate<typename Derived>\nclass GaussianDispatchingBase<Derived, 1> : public GaussianBase<Derived>\n{\n    typedef GaussianBase<Derived> Base;\n    friend class GaussianBase<Derived>;\npublic:    \n    static constexpr int Dimension = Eigen::internal::traits<Derived>::Dimension;\n    static constexpr int Rows = Eigen::internal::traits<Derived>::Rows;\n    static constexpr int Cols = Eigen::internal::traits<Derived>::Cols;\n    typedef typename Eigen::internal::traits<Derived>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Derived>::MeanType MeanType;\n    typedef const typename Eigen::internal::traits<Derived>::MeanType ConstMeanType;\n    \n    using Base::operator=;\n    \n    template<typename NewScalarType>\n    EIGEN_DEVICE_FUNC inline Gaussian<NewScalarType> cast() const \n    {\n        return Gaussian<NewScalarType>((NewScalarType)Base::mean(), (NewScalarType)Base::variance());\n    }\n    \n    EIGEN_DEVICE_FUNC inline MeanType evaluate(const MeanType& x)\n    {\n        using Eigen::numext::sqrt;\n        using Eigen::numext::exp;\n        \n        const Scalar inv_sqrt_2pi_s2 = Scalar(1.0) / sqrt(Scalar(2.0 * M_PI) * Base::variance());\n        const Scalar a = (x - Base::mean());\n        return inv_sqrt_2pi_s2 * exp(-(a * a)/(Scalar(2.0) * Base::variance()));\n    }\n    \n    EIGEN_DEVICE_FUNC inline void setZero()\n    {\n        Base::mean() = Scalar(0.0);\n        Base::variance() = Scalar(0.0);\n    }\n    \n    EIGEN_DEVICE_FUNC MeanType stddev() const\n    {\n        using Eigen::numext::sqrt;\n        return sqrt(Base::variance());\n    }\n};\n\n/**\n * Multivariate Gaussian Base.\n */\ntemplate<typename Derived>\nclass MultivariateGaussianBase\n{\npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Derived>::Dimension;\n    typedef typename Eigen::internal::traits<Derived>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Derived>::MeanType MeanType;\n    typedef const typename Eigen::internal::traits<Derived>::MeanType ConstMeanType;\n    typedef typename Eigen::internal::traits<Derived>::CovarianceType CovarianceType;\n    typedef const typename Eigen::internal::traits<Derived>::CovarianceType ConstCovarianceType;\n    \n    template<typename NewScalarType>\n    EIGEN_DEVICE_FUNC inline MultivariateGaussian<NewScalarType,Dimension> cast() const \n    {\n        return MultivariateGaussian<NewScalarType,Dimension>(mean().template cast<NewScalarType>(), \n                                                             covariance().template cast<NewScalarType>());\n    }\n        \n    EIGEN_DEVICE_FUNC MeanType& mean() \n    {\n        return static_cast<Derived*>(this)->mean_nonconst();\n    }\n    \n    EIGEN_DEVICE_FUNC const MeanType& mean() const\n    {\n        return static_cast<Derived*>(this)->mean_const();\n    }\n        \n    EIGEN_DEVICE_FUNC CovarianceType& covariance() \n    {\n        return static_cast<Derived*>(this)->covariance_nonconst();\n    }\n    \n    EIGEN_DEVICE_FUNC const CovarianceType& covariance() const\n    {\n        return static_cast<Derived*>(this)->covariance_const();\n    }\n      \n    template<typename OtherDerived>\n    EIGEN_DEVICE_FUNC inline MultivariateGaussianBase<Derived>& operator=(const MultivariateGaussianBase<OtherDerived>& other)\n    {\n        mean() = other.mean();\n        covariance() = other.covariance();\n        return *this;\n    }\n    \n#if 0\nEIGEN_DEVICE_FUNC inline MultivariateGaussianBase<Derived> operator+(const MultivariateGaussianBase<Derived>& other) const\n    {\n        // TBD\n    }\n    \n    EIGEN_DEVICE_FUNC inline MultivariateGaussianBase<Derived> operator-(const MultivariateGaussianBase<Derived>& other) const\n    {\n        // TBD\n    }\n    \n    template<typename OtherScalar>\n    EIGEN_DEVICE_FUNC inline MultivariateGaussianBase<Derived> operator*(const OtherScalar& other) const\n    {\n        // TBD\n    }\n    \n    template<typename OtherScalar>\n    EIGEN_DEVICE_FUNC inline MultivariateGaussianBase<Derived> operator/(const OtherScalar& other) const\n    {\n        // TBD\n    }\n#endif\n    \n    EIGEN_DEVICE_FUNC inline Scalar evaluate(const MeanType& x)\n    {\n        using Eigen::numext::sqrt;\n        using Eigen::numext::pow;\n        using Eigen::numext::exp;\n        \n        auto term1 = x - mean();\n        auto det = covariance().determinant();\n        auto part1 = (Scalar(1.0) / ( sqrt(pow(Scalar(2.0 * M_PI), Scalar(Dimension)) * det) ) );\n        auto part2 = exp(Scalar(-0.5) * term1.transpose() * covariance().inverse() * term1);\n        \n        return part1 * part2;\n    }\n    \n    EIGEN_DEVICE_FUNC inline void setZero()\n    {\n        mean().setZero();\n        covariance().setZero();\n    }\n    \n#ifdef VISIONCORE_ENABLE_CEREAL\n    template<typename Archive>\n    void load(Archive & archive, std::uint32_t const version)\n    {\n        archive(cereal::make_nvp(\"Mean\", mean()));\n        archive(cereal::make_nvp(\"Covariance\", covariance()));\n    }\n    \n    template<typename Archive>\n    void save(Archive & archive, std::uint32_t const version) const\n    {\n        archive(cereal::make_nvp(\"Mean\", mean()));\n        archive(cereal::make_nvp(\"Covariance\", covariance()));\n    }\n#endif // VISIONCORE_ENABLE_CEREAL    \n};\n\n/**\n * Gaussian distribution.\n */\ntemplate<typename T>\nclass Gaussian : public GaussianDispatchingBase<Gaussian<T>, Eigen::internal::traits<Gaussian<T> >::Dimension>\n{\n    typedef GaussianDispatchingBase<Gaussian<T>, Eigen::internal::traits<Gaussian<T> >::Dimension> Base;\npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Gaussian>::Dimension;\n    static constexpr int Rows = Eigen::internal::traits<Gaussian>::Rows;\n    static constexpr int Cols = Eigen::internal::traits<Gaussian>::Cols;\n    typedef typename Eigen::internal::traits<Gaussian>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Gaussian>::MeanType MeanType;\n    typedef const typename Eigen::internal::traits<Gaussian>::MeanType ConstMeanType;\n    \n    friend class GaussianDispatchingBase<Gaussian<T>, Eigen::internal::traits<Gaussian<T> >::Dimension>;\n    friend class GaussianBase<Gaussian<T> >;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    using Base::operator=;\n#if 0\n    using Base::operator*;\n    using Base::operator+;\n    using Base::operator-;\n    using Base::operator/;\n#endif\n    \n    EIGEN_DEVICE_FUNC inline Gaussian()\n    {\n    }\n    \n    template<typename OtherDerived> \n    EIGEN_DEVICE_FUNC inline Gaussian(const GaussianDispatchingBase<GaussianBase<OtherDerived>, \n                                      Eigen::internal::traits<Gaussian>::Dimension>& other)\n        : mean_(other.mean()), variance_(other.variance())\n    {\n    }\n    \n    EIGEN_DEVICE_FUNC inline Gaussian(ConstMeanType& mean, ConstMeanType& variance)\n        : mean_(mean), variance_(variance)\n    {\n    }\n    \n    EIGEN_DEVICE_FUNC inline ~Gaussian()\n    {\n    }\n    \nprotected:\n    EIGEN_DEVICE_FUNC inline ConstMeanType& mean_const() const { return mean_; }\n    EIGEN_DEVICE_FUNC inline MeanType& mean_nonconst() { return mean_; }\n    \n    EIGEN_DEVICE_FUNC inline ConstMeanType& variance_const() const { return variance_; }\n    EIGEN_DEVICE_FUNC inline MeanType& variance_nonconst() { return variance_; }\n    \n    MeanType mean_;\n    MeanType variance_;\n};\n\ntemplate<typename T>\ninline std::ostream& operator<<(std::ostream& os, const Gaussian<T>& p)\n{\n    os << \"N(\" << p.mean() << \",\" << p.stddev() <<  \")\";\n    return os;\n}\n\n\n/**\n * Multivariate Gaussian distribution.\n */\ntemplate<typename _Scalar, int _Dimension>\nclass MultivariateGaussian : public MultivariateGaussianBase<MultivariateGaussian<_Scalar,_Dimension>>\n{\n    typedef MultivariateGaussianBase<MultivariateGaussian<_Scalar,_Dimension>> Base;\npublic:\n    static constexpr int Dimension = Eigen::internal::traits<MultivariateGaussian>::Dimension;\n    typedef typename Eigen::internal::traits<MultivariateGaussian>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<MultivariateGaussian>::MeanType MeanType;\n    typedef const typename Eigen::internal::traits<MultivariateGaussian>::MeanType ConstMeanType;\n    typedef typename Eigen::internal::traits<MultivariateGaussian>::CovarianceType CovarianceType;\n    typedef const typename Eigen::internal::traits<MultivariateGaussian>::CovarianceType ConstCovarianceType;\n    \n    friend class vc::types::MultivariateGaussianBase<MultivariateGaussian<_Scalar,_Dimension>>;\n    \n    EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n    \n    using Base::operator=;\n#if 0\n    using Base::operator*;\n    using Base::operator+;\n    using Base::operator-;\n    using Base::operator/;\n#endif\n    \n    EIGEN_DEVICE_FUNC inline MultivariateGaussian()\n    {\n    }\n    \n    template<typename OtherDerived> \n    EIGEN_DEVICE_FUNC inline MultivariateGaussian(const MultivariateGaussianBase<OtherDerived>& other)\n        : mean_(other.mean()), covariance_(other.covariance())\n    {\n    }\n    \n    EIGEN_DEVICE_FUNC inline MultivariateGaussian(ConstMeanType& mean, ConstCovarianceType& covariance)\n        : mean_(mean), covariance_(covariance)\n    {\n    }\n    \n    EIGEN_DEVICE_FUNC inline ~MultivariateGaussian()\n    {\n    }\n                    \nprotected:\n    EIGEN_DEVICE_FUNC inline ConstMeanType& mean_const() const { return mean_; }\n    EIGEN_DEVICE_FUNC inline MeanType& mean_nonconst() { return mean_; }\n    \n    EIGEN_DEVICE_FUNC inline ConstCovarianceType& covariance_const() const { return covariance_; }\n    EIGEN_DEVICE_FUNC inline CovarianceType& covariance_nonconst() { return covariance_; }\n    \n    MeanType mean_;\n    CovarianceType covariance_;\n};\n\ntemplate<typename _Scalar, int _Dimension>\ninline std::ostream& operator<<(std::ostream& os, const MultivariateGaussian<_Scalar,_Dimension>& p)\n{\n    os << \"MultivariateGaussian(\" << p.mean() << \",\" << p.covariance() <<  \")\";\n    return os;\n}\n\n}\n    \n}\n\nnamespace Eigen \n{\n/**\n * Specialisation of Eigen::Map for Gaussian.\n */\ntemplate<typename _Scalar, int _Rows, int _Cols, int _Options>\nclass Map<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>\n    : public vc::types::GaussianDispatchingBase<\n        Map<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>, \n            Eigen::internal::traits<Map<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>>::Dimension> \n{\n    typedef vc::types::GaussianDispatchingBase<\n        Map<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>, \n            Eigen::internal::traits<Map<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>>::Dimension> Base;\npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Map>::Dimension;\n    typedef typename Eigen::internal::traits<Map>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Map>::MeanType MeanType;\n    typedef const typename Eigen::internal::traits<Map>::MeanType ConstMeanType;\n    \n    friend class vc::types::GaussianDispatchingBase<\n                Map<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>,\n                Eigen::internal::traits<Map<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>>::Dimension>;\n    friend class vc::types::GaussianBase<Map<vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options> >;\n    \n    EIGEN_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Map)\n#if 0\n    using Base::operator*;\n    using Base::operator+;\n    using Base::operator-;\n    using Base::operator/;\n#endif\n    \n    EIGEN_DEVICE_FUNC inline Map(Scalar* coeffs) : mean_(coeffs), variance_(coeffs + Dimension)\n    {\n    }\n    \nprotected:\n    EIGEN_DEVICE_FUNC inline ConstMeanType& mean_const() const { return mean_; }\n    EIGEN_DEVICE_FUNC inline MeanType& mean_nonconst() { return mean_; }\n    \n    EIGEN_DEVICE_FUNC inline ConstMeanType& variance_const() const { return variance_; }\n    EIGEN_DEVICE_FUNC inline MeanType& variance_nonconst() { return variance_; }\n    \n    MeanType mean_;\n    MeanType variance_;\n};\n\n/**\n * Specialisation of Eigen::Map for const Gaussian.\n */\ntemplate<typename _Scalar, int _Rows, int _Cols, int _Options>\nclass Map<const vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>\n    : public vc::types::GaussianDispatchingBase<\n        Map<const vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>, \n          Eigen::internal::traits<const vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>>::Dimension> \n{\n    typedef vc::types::GaussianDispatchingBase<\n      Map<const vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>, \n      Eigen::internal::traits<const vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>>::Dimension>  Base;\npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Map>::Dimension;\n    typedef typename Eigen::internal::traits<Map>::Scalar Scalar;    \n    typedef const typename Eigen::internal::traits<Map>::MeanType ConstMeanType;\n    \n    friend class vc::types::GaussianDispatchingBase<\n      Map<const vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options>, \n      Eigen::internal::traits<const vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>>::Dimension>;\n    friend class vc::types::GaussianBase<Map<const vc::types::Gaussian<Matrix<_Scalar, _Rows, _Cols>>, _Options> >;\n    \n    EIGEN_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Map)\n#if 0\n    using Base::operator*;\n    using Base::operator+;\n    using Base::operator-;\n    using Base::operator/;\n#endif\n    \n    EIGEN_DEVICE_FUNC inline Map(const Scalar* coeffs) : mean_(coeffs), variance_(coeffs + Dimension)\n    {\n    }\n    \nprotected:\n    EIGEN_DEVICE_FUNC inline ConstMeanType& mean_const() const { return mean_; }    \n    EIGEN_DEVICE_FUNC inline ConstMeanType& variance_const() const { return variance_; }\n    \n    ConstMeanType mean_;\n    ConstMeanType variance_;\n};\n    \n/**\n * Specialisation of Eigen::Map for Multivariate Gaussian.\n */\ntemplate<typename _Scalar, int _Dimension, int _Options>\nclass Map<vc::types::MultivariateGaussian<_Scalar,_Dimension>, _Options>\n  : public vc::types::MultivariateGaussianBase<\n    Map<vc::types::MultivariateGaussian<_Scalar,_Dimension>, _Options> > \n{\n    typedef vc::types::MultivariateGaussianBase<Map<vc::types::MultivariateGaussian<_Scalar,_Dimension>, _Options>> Base;\n    \npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Map>::Dimension;\n    typedef typename Eigen::internal::traits<Map>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Map>::MeanType MeanType;\n    typedef const typename Eigen::internal::traits<Map>::MeanType ConstMeanType;\n    typedef typename Eigen::internal::traits<Map>::CovarianceType CovarianceType;\n    typedef const typename Eigen::internal::traits<Map>::CovarianceType ConstCovarianceType;\n    \n    friend class vc::types::MultivariateGaussianBase<Map<vc::types::MultivariateGaussian<_Scalar,_Dimension>, _Options> >;\n    \n    EIGEN_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Map)\n#if 0\n    using Base::operator*;\n    using Base::operator+;\n    using Base::operator-;\n    using Base::operator/;\n#endif\n    \n    EIGEN_DEVICE_FUNC inline Map(Scalar* coeffs) : mean_(coeffs), covariance_(coeffs + _Dimension)\n    {\n    }\n    \nprotected:\n    EIGEN_DEVICE_FUNC inline ConstMeanType& mean_const() const { return mean_; }\n    EIGEN_DEVICE_FUNC inline MeanType& mean_nonconst() { return mean_; }\n    \n    EIGEN_DEVICE_FUNC inline ConstCovarianceType& covariance_const() const { return covariance_; }\n    EIGEN_DEVICE_FUNC inline CovarianceType& covariance_nonconst() { return covariance_; }\n    \n    MeanType mean_;\n    CovarianceType covariance_;\n};\n\n/**\n * Specialisation of Eigen::Map for const Multivariate Gaussian.\n */\ntemplate<typename _Scalar, int _Dimension, int _Options>\nclass Map<const vc::types::MultivariateGaussian<_Scalar,_Dimension>, _Options>\n  : public vc::types::MultivariateGaussianBase<\n    Map<const vc::types::MultivariateGaussian<_Scalar,_Dimension>, _Options> > \n{\n    typedef vc::types::MultivariateGaussianBase<Map<const vc::types::MultivariateGaussian<_Scalar,_Dimension>, _Options> > Base;\n    \npublic:\n    static constexpr int Dimension = Eigen::internal::traits<Map>::Dimension;\n    typedef typename Eigen::internal::traits<Map>::Scalar Scalar;    \n    typedef typename Eigen::internal::traits<Map>::MeanType MeanType;\n    typedef const typename Eigen::internal::traits<Map>::MeanType ConstMeanType;\n    typedef typename Eigen::internal::traits<Map>::CovarianceType CovarianceType;\n    typedef const typename Eigen::internal::traits<Map>::CovarianceType ConstCovarianceType;\n    \n    friend class vc::types::MultivariateGaussianBase<Map<const vc::types::MultivariateGaussian<_Scalar,_Dimension>, _Options> >;\n    \n    EIGEN_INHERIT_ASSIGNMENT_EQUAL_OPERATOR(Map)\n#if 0\n    using Base::operator*;\n    using Base::operator+;\n    using Base::operator-;\n    using Base::operator/;\n#endif\n    \n    EIGEN_DEVICE_FUNC inline Map(const Scalar* coeffs) : mean_(coeffs), covariance_(coeffs + _Dimension)\n    {\n    }\n    \nprotected:\n    EIGEN_DEVICE_FUNC inline ConstMeanType& mean_const() const { return mean_; }    \n    EIGEN_DEVICE_FUNC inline ConstCovarianceType& covariance_const() const { return covariance_; }\n    \n    MeanType mean_;\n    CovarianceType covariance_;\n};\n\n}\n\n#endif // VISIONCORE_TYPES_GAUSSIAN_HPP\n", "meta": {"hexsha": "35db7b8ace04f6ec8b423acd38a368d6805e65a5", "size": 26951, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/VisionCore/Types/Gaussian.hpp", "max_stars_repo_name": "lukier/vision_core", "max_stars_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2016-10-30T23:59:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T12:27:40.000Z", "max_issues_repo_path": "include/VisionCore/Types/Gaussian.hpp", "max_issues_repo_name": "jczarnowski/vision_core", "max_issues_repo_head_hexsha": "924c53339b1d99ebb3b1e358edfaa1a4e8d3703b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-05-19T04:45:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T01:32:22.000Z", "max_forks_repo_path": "include/VisionCore/Types/Gaussian.hpp", "max_forks_repo_name": "lukier/vision_core", "max_forks_repo_head_hexsha": "45cb1bf7b74e1e1d5aa1078494a328b317d5a368", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-11-14T00:46:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T08:55:11.000Z", "avg_line_length": 36.6182065217, "max_line_length": 128, "alphanum_fraction": 0.6780453415, "num_tokens": 6277, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22523334961371688}}
{"text": "// -------------------------------------------\n//  @description: 根据彩色图像的像素产生点云代码 产生三维骨架点云 计算外积 计算方差 方差保存供svm训练\n//  @author: hts\n//  @data: 2020-04-20\n//  @version: wpdwp\n// -------------------------------------------\n#include <stdlib.h>\n#include <stdio.h>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <cmath>\n#include <mutex>\n#include <thread>\n#include <chrono>\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/visualization/cloud_viewer.h>\n\n#include <opencv2/opencv.hpp>\n\n#include <ros/ros.h>\n#include <ros/spinner.h>\n#include <sensor_msgs/CameraInfo.h>\n#include <sensor_msgs/Image.h>\n\n#include <cv_bridge/cv_bridge.h>\n\n#include <image_transport/image_transport.h>\n#include <image_transport/subscriber_filter.h>\n\n#include <message_filters/subscriber.h>\n#include <message_filters/synchronizer.h>\n#include <message_filters/sync_policies/exact_time.h>\n#include <message_filters/sync_policies/approximate_time.h>\n\n#include <kinect2_bridge/kinect2_definitions.h>\n#include <Eigen/Dense>\n#include <Eigen/Geometry>\nusing namespace Eigen;\n#define pi 3.14159265359\n\nclass Posepoint\n{\nprivate:\n  std::mutex lock;\n  cv::Mat color, depth;\n  cv::Mat cameraMatrixColor, cameraMatrixDepth;\n  cv::Mat lookupX, lookupY;\n  pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud;\n  pcl::PCDWriter writer;\n  bool visualize_stop;\n  double pick_points[24];\n  // double pick_points2[18];\n  Vector3f Lshoulder, Rshoulder, Pelv;\n  Vector3f Head,Neck,Thrx,Lhip,Lknee,Lankle,Rhip,Rknee,Rankle;\n  std::string   pic_class, person_class, pic_name, depth_name, color_path, depth_path;\n  int sp;\n  int op;\n  bool right;\npublic:\n  Posepoint():visualize_stop(false),sp(0),op(0)\n  {\n    cameraMatrixColor = cv::Mat::zeros(3, 3, CV_64F);\n    // cameraMatrixDepth = cv::Mat::zeros(3, 3, CV_64F);\n    // static double my_points[6] = {255.67636108398438,292.16888427734375,320.4430236816406,266.26220703125,330.15802001953125,298.64556884765625};\n    // static double my_points2[18] = {191.4891815185547, 215.0364227294922, 218.52777099609375, 226.16993713378906, 248.7473602294922, 234.1224822998047, 263.0619201660156, 219.8079376220703, 231.25181579589844, 221.3984375, 228.07080078125, 207.08389282226562, 259.88092041015625, 227.7604522705078, 296.4625244140625, 262.7515869140625, 301.23406982421875, 264.34210205078125, 315.548583984375, 283.42816162109375};\n    for (int i=1; i<24; i++)\n    {\n      // fscanf(fq,\"%f\\n\",&pick_points[i]);//%lf之间应该有逗号，因为没有逗号只能读第一个数。用&是因为要把数存到对应数组元素的地址中去。\\n是换行读取\n      // cout<<pick_points[i]<<endl;\n      pick_points[i] = 1;\n    }\n  }\n  ~Posepoint()\n  {\n  }\npublic:\n    void start()\n    {\n      FILE  *fq;\n      fq=fopen(\"/home/hts/Desktop/kinect_keypoints/a/test_keypoints.txt\" ,\"rt+\");//\"rt+\"是打开一个文本文件，可以读写。\n      while(!feof(fq))\n      {\n        if(fscanf(fq,\"%lf\\n\",&pick_points[0])==1)\n        {\n          // cout<<pick_points[0]<<endl;\n            for (int i=1; i<24; i++)\n          {\n            fscanf(fq,\"%lf\\n\",&pick_points[i]);//%lf之间应该有逗号，因为没有逗号只能读第一个数。用&是因为要把数存到对应数组元素的地址中去。\\n是换行读取\n            // cout<<pick_points[i]<<endl;\n          }\n          char * a,*b,*c,*d;\n          a= new char [3];\n          b= new char [1];\n          c= new char [14];\n          d = new char [14];\n          fscanf(fq,\"%s\", a);\n          fscanf(fq,\"%s\", b);\n          fscanf(fq,\"%s\", c);\n          pic_class = a;\n          person_class = b;\n          pic_name = c;\n          for(int i=0; i<5;i++)\n          {\n            d[i] =c[i]; \n          }\n          d[5]='d';d[6]='e';d[7]='p';d[8]='t';d[9]='h';d[10]='.';d[11]='p';d[12]='n';d[13]='g';\n          depth_name = d;\n          // depth_name = depth_name+\"depth.png\";\n          // depth_name = depth_name.substring(0, depth_name.length() -1);\n          color_path = \"/home/hts/Desktop/kinect_pic/\"+person_class+'/'+ pic_class+'/'+pic_name;\n          depth_path = \"/home/hts/Desktop/kinect_depth/\"+person_class+'/'+pic_class+'/'+depth_name;\n          // cout<<color_path<<endl;\n          // cout<<depth_path<<endl;\n          begin(color_path,depth_path);\n          // ThreeCross();\n          Transformation();\n          calculate();\n          // if(!right)\n          // {\n          //   cout<<color_path<<endl;\n          // }\n        }\n      }\n      // cout<<\"爬识别正确：\"<<sp<<\"  爬识别错误：\"<<op<<endl;\n    }\n    void begin(std::string color_path, std::string depth_path)\n  {\n    // cout<<\"开始!\"<<endl;\n    color = cv::imread(color_path);\n    depth = cv::imread(depth_path,2);\n    // cv::imshow(\"color\", color);\n    // cout<<\"!!!\"<<endl;\n    // cv::imshow(\"depth\", depth);\n    // cv::waitKey(0);\n    cloud = pcl::PointCloud<pcl::PointXYZRGBA>::Ptr(new pcl::PointCloud<pcl::PointXYZRGBA>());\n    cloud->height = color.rows;\n    cloud->width = color.cols;\n    cloud->is_dense = false;\n    cloud->points.resize(cloud->height * cloud->width);\n    readCameraInfo();\n    createLookup(this->color.cols, this->color.rows); //像极坐标系中的值保存在lookupX　lookupY里面\n    cloudViewer();\n  }\n  // 3x3内参矩阵\n//   367.933   0         254.169\n//     0     367.933     204.267\n//     0       0            1\n    void readCameraInfo()\n  {\n    double cameraInfoK[9]={367.933 , 0 , 254.169,\n                           0 , 367.933 , 204.267,\n                          0 , 0 , 1             }; \n    double *itC = cameraMatrixColor.ptr<double>(0, 0);\n    for(size_t i = 0; i < 9; ++i, ++itC)\n    {\n      *itC = cameraInfoK[i];\n      // cout<<*itC<<endl;\n    }\n    // cout<<cameraMatrixColor.at<double>(0, 0)<<endl;\n  }\n    // 求在相机坐标系中的坐标\n    void createLookup(size_t width, size_t height)\n  {\n    // width是列->x　height是行->y\n    // 得到相机的内参数\n    //  成像模型\n// [u       [ fx　0 cx   [x\n//  v  = 1/z  0  fy cy    y\n//  1]        0   0  1]   z]\n// 求逆矩阵　得到像极坐标系中的坐标　\n    const float fx = 1.0f / cameraMatrixColor.at<double>(0, 0);\n    const float fy = 1.0f / cameraMatrixColor.at<double>(1, 1);\n    const float cx = cameraMatrixColor.at<double>(0, 2);\n    const float cy = cameraMatrixColor.at<double>(1, 2);\n    float *it;\n    // cout<<\"相机的内参:\"<<fx<<\" \"<<fy<<\" \"<<cx<<\" \"<<cy<<\" \"<<endl;\n    lookupY = cv::Mat(1, height, CV_32F);\n    it = lookupY.ptr<float>();\n    for(size_t r = 0; r < height; ++r, ++it)\n    {\n      *it = (r - cy) * fy;\n      // cout<<*it<<endl;\n    }\n\n    lookupX = cv::Mat(1, width, CV_32F);\n    it = lookupX.ptr<float>();\n    for(size_t c = 0; c < width; ++c, ++it)\n    {\n      *it = (c - cx) * fx;\n      // cout<<*it<<endl;\n    }\n  }\n    void cloudViewer()\n  {\n    cv::Mat color, depth;\n    // pcl::visualization::PCLVisualizer::Ptr visualizer(new pcl::visualization::PCLVisualizer(\"Cloud Viewer\"));\n    const std::string cloudName = \"rendered\";\n\n    lock.lock();\n    color = this->color;\n    depth = this->depth;\n    // updateCloud = false;\n    lock.unlock();\n\n    createCloud(depth, color, cloud);\n    // 将点云数据添加到视窗中，并为其定义一个唯一的字符串作为ID号，利用此ID号保证其他成员方法也能表示该点云。\n    // 多次调用addPointCloud()可以实现多个点云的叠加，每调用一次就创建一个新的ID号。如果想要更新一个已经\n    // 显示的点云，用户必须先调用removePointCloud()，并提供新的ID号。（在PCL1.1版本之后直接调用updatePointCloud()\n    //  就可以了，不必手动调用removePointCloud()就可实现点云更新）\n\n\n    // visualizer->addPointCloud(cloud, cloudName);\n    // // 修改现实点云的尺寸。用户可通过该方法控制点云在视窗中的显示方式\n    // visualizer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, cloudName);\n    // // 设置XYZ三个坐标轴的大小和长度，该值也可以缺省\n    // // 查看复杂的点云图像会让用户没有方向感，为了让用户保持正确的方向判断，需要显示坐标轴。三个坐标轴X（R，红色）\n    // // Y（G，绿色）Z（B，蓝色）分别用三种不同颜色的圆柱体代替\n    // visualizer->addCoordinateSystem(1.0);\n    // // 通过设置相机参数是用户从默认的角度和方向观察点\n    // visualizer->initCameraParameters();\n    // // 设置窗口viewer的背景颜色\n    // visualizer->setBackgroundColor(0, 0, 0);\n    // // visualizer->setPosition(mode == BOTH ? color.cols : 0, 0);\n    // visualizer->setPosition(0, 0);\n    // visualizer->setSize(color.cols, color.rows);\n    // visualizer->setShowFPS(true);\n    // visualizer->setCameraPosition(0, 0, 0, 0, -1, 0);\n    // visualizer->registerKeyboardCallback(&Posepoint::keyboardEvent, *this);\n    // saveCloud(cloud);\n    // // visualizer->spinOnce(300);\n    // while (!visualize_stop) {\n    //     visualizer->spinOnce(100);\n    //     // boost::this_thread::sleep(boost::posix_time::microseconds(1000));\n    // }\n\n    // visualizer->close();\n\n  }\n    void createCloud(const cv::Mat &depth, const cv::Mat &color, pcl::PointCloud<pcl::PointXYZRGBA>::Ptr &cloud)\n  {\n    int body_part;\n    const float badPoint = std::numeric_limits<float>::quiet_NaN();\n    // #pragma omp parallel for\n    for(int r = 0; r < depth.rows; ++r)\n    {\n      // 创建点云row行，每一行有col列\n      pcl::PointXYZRGBA *itP = &cloud->points[r * depth.cols];\n      // ptr函数访问任意一行像素的首地址　\n      const uint16_t *itD = depth.ptr<uint16_t>(r);\n      const cv::Vec3b *itC = color.ptr<cv::Vec3b>(r);\n      const float y = lookupY.at<float>(0, r);\n      const float *itX = lookupX.ptr<float>();\n\n        for(size_t c = 0; c < (size_t)depth.cols; ++c, ++itP, ++itD, ++itC, ++itX)\n      {\n        register const float depthValue = *itD / 1000.0f;\n        // Check for invalid measurements\n        if(*itD == 0)\n        {\n          // not valid\n          itP->x = itP->y = itP->z = badPoint;\n          itP->rgba = 0;\n          continue;\n        }\n        itP->z = depthValue;\n        itP->x = *itX * depthValue;\n        itP->y = y * depthValue;\n        itP->b = itC->val[0];\n        itP->g = itC->val[1];\n        itP->r = itC->val[2];\n        itP->a = 255;\n          bool picked = false;\n          if(size_t(pick_points[0]) == c && int(pick_points[1]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 0;        \n        }\n          if(size_t(pick_points[2]) == c && int(pick_points[3]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 1;        \n        }\n          if(size_t(pick_points[4]) == c && int(pick_points[5]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 2;        \n        }\n          if(size_t(pick_points[6]) == c && int(pick_points[7]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 3;        \n        }\n          if(size_t(pick_points[8]) == c && int(pick_points[9]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 4;        \n        }\n          if(size_t(pick_points[10]) == c && int(pick_points[11]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 5;        \n        }\n          if(size_t(pick_points[12]) == c && int(pick_points[13]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 6;        \n        }\n          if(size_t(pick_points[14]) == c && int(pick_points[15]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 7;        \n        }\n          if(size_t(pick_points[16]) == c && int(pick_points[17]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 8;        \n        }\n          if(size_t(pick_points[18]) == c && int(pick_points[19]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 9;        \n        }\n          if(size_t(pick_points[20]) == c && int(pick_points[21]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 12;        \n        }\n          if(size_t(pick_points[22]) == c && int(pick_points[23]) == r)\n        {\n            // cout<<\"点(\"<<r<<\",\"<<c<<\")选中\"<<endl;\n            picked = true;\n            body_part = 13;        \n        }\n        if (picked)\n        {\n          register const float depthValue = *itD / 1000.0f;\n          switch(body_part)\n          {\n          case 0:;\n                Rankle(0) = itP->x; Rankle(1) = itP->y; Rankle(2) = itP->z;\n                break;\n          case 1:\n                Rknee(0) = itP->x; Rknee(1) = itP->y; Rknee(2) = itP->z;\n                break;\n          case 2:\n                Rhip(0) = itP->x; Rhip(1) = itP->y; Rhip(2) = itP->z;\n                break;\n          case 3:\n                Lhip(0) = itP->x; Lhip(1) = itP->y; Lhip(2) = itP->z;\n                break; \n          case 4:\n                Lknee(0) = itP->x; Lknee(1) = itP->y; Lknee(2) = itP->z;\n                break; \n          case 5:\n                Lankle(0) = itP->x; Lankle(1) = itP->y; Lankle(2) = itP->z;\n                break; \n          case 6:\n                Pelv(0) = itP->x; Pelv(1) = itP->y; Pelv(2) = itP->z;\n                break; \n          case 7:\n                Thrx(0) = itP->x; Thrx(1) = itP->y; Thrx(2) = itP->z;\n                break;\n          case 8:\n                Neck(0) = itP->x; Neck(1) = itP->y; Neck(2) = itP->z;\n                break; \n          case 9:\n                Head(0) = itP->x; Head(1) = itP->y; Head(2) = itP->z;\n                break; \n          case 12:\n                Rshoulder(0) = itP->x; Rshoulder(1) = itP->y; Rshoulder(2) = itP->z;\n                break;\n          case 13:\n                Lshoulder(0) = itP->x; Lshoulder(1) = itP->y; Lshoulder(2) = itP->z;\n                break;                              \n          }\n        }\n      }\n    }\n  }\n    void saveCloud(const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr cloud)\n  {\n    std::ostringstream oss;\n    oss.str(\"\");\n    oss << \"/home/hts/Desktop/kinect_cloud/a/aaa/\" << std::setfill('0') << std::setw(4);\n    const std::string baseName = oss.str();\n    const std::string cloudName = baseName + \"_cloud.pcd\";\n    OUT_INFO(\"saving cloud: \" << cloudName);\n     // writer是该类的pcl::PCDWriter类型的成员变量\n    writer.writeBinary(cloudName, *cloud);\n  }\n    void keyboardEvent(const pcl::visualization::KeyboardEvent &event, void *)\n  {\n    if(event.keyUp())\n    {\n      switch(event.getKeyCode())\n      {\n      case 27:\n      case 'q':\n        visualize_stop = true;\n        break;\n      }\n    }\n  }\n    //叉积\n  Vector3f ThreeCross()\n  {\n    Vector3f a, b,result;\n    a=Lshoulder-Pelv;\n    b=Rshoulder-Pelv;\n    // cout<<Lshoulder<<endl;cout<<Rshoulder<<endl;cout<<Pelv<<endl;\n    // cout<<\"左肩向量:\\n\"<<a<<\"   右肩向量:\\n\"<<b<<endl;\n    result = a.cross(b);\n    // cout<<\"躯干法向量:\\n\"<<result<<endl;\n    // Eigen::Vector3d v3(0, 0, 0);\n\t  // v3.x() = 1;\n\t  // v3[2] = 1;\n\t  AngleAxisd angle_axis3(pi *25/ 18, Eigen::Vector3d(1, 0, 0));//1系绕x轴逆时针旋转250得到2系\n    // angle_axis3.matrix().cast<float>()\n\t  Vector3f rotated_result = angle_axis3.matrix().cast<float>()*result;\n\t  // cout << \"绕x轴顺时针旋转250°(Rcw):\" << endl << angle_axis3.matrix() << endl;\n\t  // cout << \"躯干法向量旋转后:\" << endl << rotated_result.transpose() << endl;\n    if (rotated_result(2)<0)\n    {\n      sp+=1;\n      right = true;\n    }\n    if (rotated_result(2)>0)\n    {\n      op+=1;\n      right = false;\n    }\n    return rotated_result;\n  }\n  //转换到世界坐标系\n  void  Transformation()\n  {\n    // Vector3f result = ori;\n    // // 旋转矩阵就是3x3的矩阵\n    // Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n    // 旋转向量(方向与旋转轴[1,0,0]相同,模为旋转的角度250°)\n    Eigen::AngleAxisd rotation_vector (pi *25/ 18,Eigen::Vector3d(1,0,0));\n    cout.precision(3);//指定输出的精度\n    cout<<\"Rwc旋转矩阵为：\\n\"<<rotation_vector.matrix()<<endl;\n    // 三维的齐次变换矩阵是4x4的矩阵\n    Eigen::Isometry3d T = Eigen::Isometry3d::Identity();\n    // 根据旋转向量进行旋转（注意旋转向量包含了旋转轴和旋转了的角度）\n    T.rotate(rotation_vector);\n    cout<<\"旋转后的变换矩阵为：\\n\"<<T.matrix()<<endl;\n    T.pretranslate(Eigen::Vector3d(0,0,1.35)); // 把第四列的平移向量设置为(1,3,4)\n    cout<<\"设置平移量后的矩阵为：\\n\"<<T.matrix()<<endl;\n    // result = T*ori;\n    Head = T.cast<float>()*Head; Neck = T.cast<float>()*Neck; Thrx = T.cast<float>()*Thrx; Pelv = T.cast<float>()*Pelv; Lhip = T.cast<float>()*Lhip; Lknee = T.cast<float>()*Lknee; Lankle = T.cast<float>()*Lankle; Rhip = T.cast<float>()*Rhip; Rknee = T.cast<float>()*Rknee; Rankle = T.cast<float>()*Rankle; Lshoulder = T.cast<float>()*Lshoulder; Rshoulder = T.cast<float>()*Rshoulder;\n    cout<<Head<<endl;\n    cout<<Neck<<endl;\n    cout<<Thrx<<endl;\n    cout<<Pelv<<endl;\n    cout<<Lhip<<endl;\n    cout<<Lknee<<endl;\n    cout<<Lankle<<endl;\n    cout<<Rhip<<endl;\n    cout<<Rknee<<endl;\n    cout<<Rankle<<endl;\n  }\n  double calculate()\n  {\n    double sum =0;\n    sum = Head(2) + Neck(2) + Thrx(2) + Pelv(2) + Lhip(2) + Rhip(2)+Rshoulder(2)+Lshoulder(2);\n    cout<<\"和\"<<sum<<endl;\n    double mean = sum/10;\n    cout<<\"均值:\"<<mean<<endl;\n    double stdvar = sqrt(((Head(2)-mean)*(Head(2)-mean)+(Neck(2)-mean)*(Neck(2)-mean)+(Thrx(2)-mean)*(Thrx(2)-mean)+(Pelv(2)-mean)*(Pelv(2)-mean)+(Lhip(2)-mean)*(Lhip(2)-mean)+(Rhip(2)-mean)*(Rhip(2)-mean)+(Rshoulder(2)-mean)*(Rshoulder(2)-mean)+(Lshoulder(2)-mean)*(Lshoulder(2)-mean))/10);\n    cout<<\"标准差为:\"<<stdvar<<endl;\n    // if(stdvar<0.2)\n    // {\n    //   right = true;\n    //   sp+=1;\n    // }\n    // else\n    // {\n    //   right =false;\n    //   op+=1;\n    // }\n    FILE *fp = NULL;\n    fp = fopen(\"/home/hts/catkin_ws/var.txt\", \"a+\");\n    fprintf(fp, \"%lf\\n%lf\\n\", mean,stdvar);\n    fclose(fp);\n    return stdvar;\n  }\n\n};\n\nint main(int argc, char**argv)\n{\n  // std::string color_path = argv[1];\n  // std::string depth_path = argv[2]; \n  Posepoint posepoint; \n  posepoint.start();\n  // cout<<\"!!\";\n  // posepoint.ThreeCross();\n  // posepoint.Transformation();\n  // posepoint.calculate();\n}\n", "meta": {"hexsha": "cfbb2903bdd7bdc97b413dee3e6b2e0029317e7c", "size": 17435, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kinect2_viewer/src/getpoint.cpp", "max_stars_repo_name": "hutslib/iai_kinect2", "max_stars_repo_head_hexsha": "3f225ea61f4114f55ab458ea570ffdacaa38d7be", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kinect2_viewer/src/getpoint.cpp", "max_issues_repo_name": "hutslib/iai_kinect2", "max_issues_repo_head_hexsha": "3f225ea61f4114f55ab458ea570ffdacaa38d7be", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kinect2_viewer/src/getpoint.cpp", "max_forks_repo_name": "hutslib/iai_kinect2", "max_forks_repo_head_hexsha": "3f225ea61f4114f55ab458ea570ffdacaa38d7be", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5934489403, "max_line_length": 418, "alphanum_fraction": 0.5339833668, "num_tokens": 6110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011686727231, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22521254557387355}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   MonteCarlo_WHIncoherentAdjointPhotonScatteringDistribution_def.hpp\n//! \\author Alex Robinson\n//! \\brief  The Waller-Hartree adjoint incoherent photon scattering dist. def.\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef MONTE_CARLO_WH_INCOHERENT_ADJOINT_PHOTON_SCATTERING_DISTRIBUTION_DEF_HPP\n#define MONTE_CARLO_WH_INCOHERENT_ADJOINT_PHOTON_SCATTERING_DISTRIBUTION_DEF_HPP\n\n// Boost Includes\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n// FRENSIE Includes\n#include \"Utility_InverseLengthConversionPolicy.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace MonteCarlo{\n\n// Constructor\ntemplate<typename ScatteringFunctionArgUnitConversionPolicy>\nWHIncoherentAdjointPhotonScatteringDistribution<ScatteringFunctionArgUnitConversionPolicy>::WHIncoherentAdjointPhotonScatteringDistribution(\n     const double max_energy,\n     const Teuchos::RCP<const Utility::OneDDistribution>& scattering_function )\n  : IncoherentAdjointPhotonScatteringDistribution( max_energy ),\n    d_scattering_function( scattering_function )\n{\n  // Make sure the unit conversion policy is valid\n  testStaticPrecondition( (boost::is_same<typename ScatteringFunctionArgUnitConversionPolicy::Dimension,Utility::InverseLengthDimension>::value) );\n  // Make sure the scattering function is valid\n  testPrecondition( !scattering_function.is_null() );\n}\n\n// Evaluate the distribution\ntemplate<typename ScatteringFunctionArgUnitConversionPolicy>\ndouble WHIncoherentAdjointPhotonScatteringDistribution<ScatteringFunctionArgUnitConversionPolicy>::evaluate( \n\t\t\t\t   const double incoming_energy,\n\t\t\t\t   const double max_energy,\n\t\t\t\t   const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  testPrecondition( incoming_energy <= max_energy );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= \n\t\t    calculateMinScatteringAngleCosine( incoming_energy,\n\t\t\t\t\t\t       max_energy ));\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  const double scattering_function_value = \n    this->evaluateScatteringFunction( incoming_energy,\n\t\t\t\t      max_energy,\n\t\t\t\t      scattering_angle_cosine );\n\n  const double diff_kn_cross_section = \n    this->evaluateAdjointKleinNishinaDist( incoming_energy,\n\t\t\t\t\t   max_energy,\n\t\t\t\t\t   scattering_angle_cosine );\n\n  return diff_kn_cross_section*scattering_function_value;\n}\n\n// Evaluate the integrated cross section (b)\ntemplate<typename ScatteringFunctionArgUnitConversionPolicy>\ndouble WHIncoherentAdjointPhotonScatteringDistribution<ScatteringFunctionArgUnitConversionPolicy>::evaluateIntegratedCrossSection( \n\t\t\t\t\t\t const double incoming_energy,\n\t\t\t\t\t\t const double max_energy,\n\t\t\t\t\t\t const double precision ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  testPrecondition( incoming_energy <= max_energy );\n\n  // Evaluate the integrated cross section\n  boost::function<double (double x)> diff_cs_wrapper = \n    boost::bind<double>( &WHIncoherentAdjointPhotonScatteringDistribution::evaluate,\n\t\t\t boost::cref( *this ),\n\t\t\t incoming_energy,\n\t\t\t max_energy,\n\t\t\t _1 );\n\n  double abs_error, integrated_cs;\n\n  Utility::GaussKronrodIntegrator quadrature_gkq_int( precision );\n\n  const double min_scattering_angle_cosine = \n    calculateMinScatteringAngleCosine( incoming_energy, max_energy );\n\n  quadrature_gkq_int.integrateAdaptively<15>( diff_cs_wrapper,\n\t\t\t\t\t     min_scattering_angle_cosine,\n\t\t\t\t\t     1.0,\n\t\t\t\t\t     integrated_cs,\n\t\t\t\t\t     abs_error );\n\n  // Make sure the integrated cross section is valid\n  testPostcondition( integrated_cs >= 0.0 );\n\n  return integrated_cs;\n}\n  \n// Sample an outgoing energy and direction from the distribution\n/*! \\details This function will only sample an adjoint Compton line energy (no\n * Doppler broadening).\n */ \ntemplate<typename ScatteringFunctionArgUnitConversionPolicy>\nvoid WHIncoherentAdjointPhotonScatteringDistribution<ScatteringFunctionArgUnitConversionPolicy>::sample( \n\t\t\t\t\tconst double incoming_energy,\n\t\t\t\t\tdouble& outgoing_energy,\n\t\t\t\t\tdouble& scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  testPrecondition( incoming_energy <= this->getMaxEnergy() );\n\n  unsigned trial_dummy;\n\n  return this->sampleAndRecordTrials( incoming_energy,\n\t\t\t\t      outgoing_energy,\n\t\t\t\t      scattering_angle_cosine,\n\t\t\t\t      trial_dummy );\n}\n\n// Sample an outgoing energy and direction and record the number of trials\n/*! \\details This function will only sample an adjoint Compton line energy (no\n * Doppler broadening).\n */ \ntemplate<typename ScatteringFunctionArgUnitConversionPolicy>\nvoid WHIncoherentAdjointPhotonScatteringDistribution<ScatteringFunctionArgUnitConversionPolicy>::sampleAndRecordTrials( \n\t\t\t\t\t       const double incoming_energy,\n\t\t\t\t\t       double& outgoing_energy,\n\t\t\t\t\t       double& scattering_angle_cosine,\n\t\t\t\t\t       unsigned& trials ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  testPrecondition( incoming_energy <= this->getMaxEnergy() );\n\n  // Evaluate the maximum scattering function value\n  const double min_scattering_angle_cosine = \n    calculateMinScatteringAngleCosine( incoming_energy, this->getMaxEnergy() );\n\n  const double max_scattering_function_value = \n    this->evaluateScatteringFunction( incoming_energy, \n\t\t\t\t      min_scattering_angle_cosine );\n\n  while( true )\n  {\n    this->sampleAndRecordTrialsAdjointKleinNishina( incoming_energy,\n\t\t\t\t\t\t    outgoing_energy,\n\t\t\t\t\t\t    scattering_angle_cosine,\n\t\t\t\t\t\t    trials );\n\n    const double scattering_function_value = \n      this->evaluateScatteringFunction( incoming_energy,\n\t\t\t\t\tscattering_angle_cosine );\n\n    const double scaled_random_number = max_scattering_function_value*\n      Utility::RandomNumberGenerator::getRandomNumber<double>();\n\n    if( scaled_random_number <= scattering_function_value )\n      break;\n  }\n\n  // Make sure the scattering angle cosine is valid\n  testPostcondition( scattering_angle_cosine >= min_scattering_angle_cosine );\n  testPostcondition( scattering_angle_cosine <= 1.0 );\n  // Make sure the adjoint Compton line energy is valid\n  testPostcondition( outgoing_energy >= incoming_energy );\n}\n\n// Randomly scatter the photon and return the shell that was interacted with\ntemplate<typename ScatteringFunctionArgUnitConversionPolicy>\nvoid WHIncoherentAdjointPhotonScatteringDistribution<ScatteringFunctionArgUnitConversionPolicy>::scatterAdjointPhoton( \n\t\t\t\t     AdjointPhotonState& adjoint_photon,\n\t\t\t\t     ParticleBank& bank,\n\t\t\t\t     SubshellType& shell_of_interaction ) const\n{\n  // Make sure the adjoint photon energy is valid\n  testPrecondition( adjoint_photon.getEnergy() <= this->getMaxEnergy() );\n  \n  // Generate probe particles\n  this->createProbeParticles( adjoint_photon, bank );\n \n  // Scattering the adjoint photon\n  double outgoing_energy, scattering_angle_cosine;\n  \n  this->sample( adjoint_photon.getEnergy(),\n\t\toutgoing_energy,\n\t\tscattering_angle_cosine );\n\n  shell_of_interaction = UNKNOWN_SUBSHELL;\n\n  adjoint_photon.setEnergy( outgoing_energy );\n\n  adjoint_photon.rotateDirection( scattering_angle_cosine,\n\t\t\t\t  this->sampleAzimuthalAngle() );\n}\n\n// Check if an energy is above the scattering window\n/*! \\details Becuase of the scattering function evaluating to zero when \n * the scattering angle cosine is 1.0, the scattering window upper bound must\n * exclude the energy of interest.\n */\ntemplate<typename ScatteringFunctionArgUnitConversionPolicy>\nbool WHIncoherentAdjointPhotonScatteringDistribution<ScatteringFunctionArgUnitConversionPolicy>::isEnergyAboveScatteringWindow( \n\t\t\t\t            const double energy_of_interest,\n\t\t\t\t            const double initial_energy ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( initial_energy > 0.0 );\n  // Make sure the energy of interest is valid\n  testPrecondition( energy_of_interest >= 0.0 );\n\n  return initial_energy >= energy_of_interest;\n}\n\n// Evaluate the scattering function\ntemplate<typename ScatteringFunctionArgUnitConversionPolicy>\ninline double WHIncoherentAdjointPhotonScatteringDistribution<ScatteringFunctionArgUnitConversionPolicy>::evaluateScatteringFunction(\n\t\t\t\t   const double incoming_energy,\n\t\t\t\t   const double max_energy,\n\t\t\t\t   const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  testPrecondition( incoming_energy <= max_energy );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= \n\t\t    calculateMinScatteringAngleCosine( incoming_energy,\n\t\t\t\t\t\t       max_energy ));\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  // Calculate the outgoing energy\n  const double outgoing_energy = \n    calculateAdjointComptonLineEnergy( incoming_energy,\n\t\t\t\t       scattering_angle_cosine );\n\n  // Calculate the inverse wavelength of the outgoing photon (1/cm)\n  const double inverse_wavelength = outgoing_energy/\n    (Utility::PhysicalConstants::planck_constant*\n     Utility::PhysicalConstants::speed_of_light);\n\n  // The scattering function argument (1/cm)\n  double scattering_function_arg = \n    sqrt( (1.0 - scattering_angle_cosine)/2.0 )*inverse_wavelength;\n\n  ScatteringFunctionArgUnitConversionPolicy::convertFromNativeUnits( \n\t\t\t\t\t\t     scattering_function_arg );\n\n  if( scattering_function_arg >=\n      d_scattering_function->getUpperBoundOfIndepVar() )\n    scattering_function_arg = d_scattering_function->getUpperBoundOfIndepVar();\n\n  // Make sure the scattering function arg is valid\n  testPostcondition( scattering_function_arg >=\n\t\t     d_scattering_function->getLowerBoundOfIndepVar() );\n  testPostcondition( scattering_function_arg <=\n\t\t     d_scattering_function->getUpperBoundOfIndepVar() );\n\n  return d_scattering_function->evaluate( scattering_function_arg );\n}\n\n// Evaluate the scattering function\ntemplate<typename ScatteringFunctionArgUnitConversionPolicy>\ninline double WHIncoherentAdjointPhotonScatteringDistribution<ScatteringFunctionArgUnitConversionPolicy>::evaluateScatteringFunction(\n\t\t\t\t   const double incoming_energy,\n\t\t\t\t   const double scattering_angle_cosine ) const\n{\n  // Make sure the incoming energy is valid\n  testPrecondition( incoming_energy > 0.0 );\n  testPrecondition( incoming_energy <= this->getMaxEnergy() );\n  // Make sure the scattering angle cosine is valid\n  testPrecondition( scattering_angle_cosine >= \n\t\t    calculateMinScatteringAngleCosine( incoming_energy,\n\t\t\t\t\t\t       this->getMaxEnergy() ));\n  testPrecondition( scattering_angle_cosine <= 1.0 );\n\n  return this->evaluateScatteringFunction( incoming_energy,\n\t\t\t\t\t   this->getMaxEnergy(),\n\t\t\t\t\t   scattering_angle_cosine );\n}\n\n} // end MonteCarlo namespace\n\n#endif // end MONTE_CARLO_WH_INCOHERENT_ADJOINT_PHOTON_SCATTERING_DISTRIBUTION_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end MonteCarlo_WHIncoherentAdjointPhotonScatteringDistribution.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "45577788db0c84edeaa895edbef0ab4e3f648c98", "size": 11313, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/monte_carlo/collision/native/src/MonteCarlo_WHIncoherentAdjointPhotonScatteringDistribution_def.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/collision/native/src/MonteCarlo_WHIncoherentAdjointPhotonScatteringDistribution_def.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/collision/native/src/MonteCarlo_WHIncoherentAdjointPhotonScatteringDistribution_def.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": 38.6109215017, "max_line_length": 147, "alphanum_fraction": 0.7564748519, "num_tokens": 2415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.22521254000439037}}
{"text": "// morpho/cdl/bgl_expansions/algorithms/ullmann.hpp header file//\n// Copyright (c) 2003-2008 Vladimir J. Sykora\n// Copyright (c) 2007-2008 Vladimir J. Sykora and NCU Studies Ltd\n// Modifications by Greg Landrum, January 2009\n//\n//*****************************************************************************\n// Permission is hereby granted, free of charge, to any person or organization\n// obtaining a copy of the software and accompanying documentation covered by\n// this license (the \"Software\") to use, reproduce, display, distribute,\n// execute, and transmit the Software, and to prepare derivative works of the\n// Software, and to permit third-parties to whom the Software is furnished to\n// do so, all subject to the following:\n//\n// The copyright notices in the Software and this entire statement, including\n// the above license grant, this restriction and the following disclaimer,\n// must be included in all copies of the Software, in whole or in part, and\n// all derivative works of the Software, unless such copies or derivative\n// works are solely in the form of machine-executable object code generated by\n// a source language processor.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT\n// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\n// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\n// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n//*****************************************************************************\n\n//-----------------------------------------------------------------------------\n\n// Algorithm due to JR Ullmann. \"An Algorithm for Subgraph\n// Isomorphism\". Journal of the Association for\n// Computing Machinery, Vol 23, No.1, January 1976, pp 31-42.\n\n#ifndef MORPHO_CDL_BGL_EXP_ULLMANN_HPP\n#define MORPHO_CDL_BGL_EXP_ULLMANN_HPP\n\n// -------- boost\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/graph/graph_traits.hpp>\n// -------- std\n#include <utility>  // for std::pair<>\n#include <algorithm>\n\nnamespace boost {\nnamespace detail {\n\ntemplate <class Graph, class UblasMatrix, class BackInsertionSequence,\n          class EdgeLabeling>\nbool forward_checking(const Graph& g1, const Graph& g2, UblasMatrix& M,\n                      size_t count, BackInsertionSequence& F,\n                      size_t num_vert_g1, size_t num_vert_g2,\n                      EdgeLabeling& edge_labeling) {\n  typedef std::pair<typename graph_traits<Graph>::edge_descriptor, bool>\n      edge_presence;\n  typename BackInsertionSequence::iterator fi, fi_end = F.end();\n  for (size_t k = count + 1; k < num_vert_g1; ++k) {\n    for (size_t l = 0; l < num_vert_g2; ++l) {\n      if (!M(k, l)) continue;\n      // check mapping:\n      fi = F.begin();\n      while (fi != fi_end) {\n        bool flag1(0), flag1_1(0), flag2(0), flag2_1(0);\n        edge_presence ep1 = edge(k, fi->first, g1);\n        if (ep1.second) {\n          flag1_1 = true;\n          edge_presence ep2 = edge(l, fi->second, g2);\n          if (ep2.second) flag1 = edge_labeling(ep1.first, ep2.first);\n        }\n        if (flag1_1 && flag1) {\n          M(k, l) = 1;\n          ++fi;\n          continue;\n        }\n        edge_presence ep2 = edge(l, fi->second, g2);\n        if (ep2.second) {\n          flag2_1 = true;\n          ep1 = edge(k, fi->first, g1);\n          if (ep1.second) {\n            flag2 = edge_labeling(ep1.first, ep2.first);\n          } else {\n            // ring closed in main structure, not closed in query. This should\n            // pass\n            flag2 = true;\n          }\n        }\n        if (flag2_1 && flag2) {  // if one edge exists, there must be a mapping\n          M(k, l) = 1;\n        } else if (!flag1_1 && !flag2_1) {  // or both edges are not present\n          M(k, l) = 1;\n        } else\n          M(k, l) = 0;  // if not, there's no mapping\n        ++fi;\n      }\n    }\n  }\n  // TODO: change the data structure of the M matrix to sparse matrix. This\n  // wouldn't be necessary\n  size_t cero_row(0);\n  for (size_t k = 0; k < num_vert_g1; ++k) {\n    for (size_t l = 0; l < num_vert_g2; ++l) {\n      if (M(k, l))\n        break;\n      else\n        ++cero_row;\n    }\n    if (cero_row == num_vert_g2) return false;  // if there is a cero row\n    cero_row = 0;\n  }\n  return true;\n}\n\ntemplate <class Graph, class EdgeLabeling, class UblasMatrix,\n          class BackInsertionSequence>\nbool backtrack(const Graph& g1, const Graph& g2, size_t count,\n               const UblasMatrix& M, BackInsertionSequence& F,\n               const size_t num_vert_g1, const size_t num_vert_g2,\n               EdgeLabeling& edge_labeling) {\n  if (count == num_vert_g1) return true;\n  for (size_t i = 0; i < num_vert_g2; ++i) {\n    if (M(count, i)) {\n      F.push_back(std::make_pair(count, i));\n      UblasMatrix M_prime(M);\n      for (size_t m = count + 1; m < num_vert_g1; ++m) {\n        M_prime(m, i) = 0;\n      }\n\n      if (forward_checking(g1, g2, M_prime, count, F, num_vert_g1, num_vert_g2,\n                           edge_labeling)) {\n        if (backtrack(g1, g2, count + 1, M_prime, F, num_vert_g1, num_vert_g2,\n                      edge_labeling)) {\n          return true;\n        }\n      }\n      F.erase(std::remove(F.begin(), F.end(), std::make_pair(count, i)),\n              F.end());\n    }\n  }\n  return false;\n}\n\ntemplate <class Graph, class EdgeLabeling, class UblasMatrix,\n          class DoubleBackInsertionSequence>\nvoid backtrack_all(const Graph& g1, const Graph& g2, size_t count,\n                   const UblasMatrix& M, DoubleBackInsertionSequence& FF,\n                   const size_t num_vert_g1, const size_t num_vert_g2,\n                   EdgeLabeling& edge_labeling) {\n  if (count == num_vert_g1) return;\n  DoubleBackInsertionSequence holdFF;\n  holdFF.insert(holdFF.begin(), FF.begin(), FF.end());\n  FF.clear();\n  for (size_t i = 0; i < num_vert_g2; ++i) {\n    if (M(count, i)) {\n      DoubleBackInsertionSequence tFF;\n\n      UblasMatrix M_prime(M);\n      for (size_t m = count + 1; m < num_vert_g1; ++m) {\n        M_prime(m, i) = 0;\n      }\n\n      if (holdFF.size()) {\n        for (typename DoubleBackInsertionSequence::const_iterator iter =\n                 holdFF.begin();\n             iter != holdFF.end(); ++iter) {\n          typename DoubleBackInsertionSequence::value_type F = *iter;\n          F.push_back(std::make_pair(count, i));\n          if (forward_checking(g1, g2, M_prime, count, F, num_vert_g1,\n                               num_vert_g2, edge_labeling)) {\n            tFF.push_back(F);\n          }\n        }\n      } else {\n        typename DoubleBackInsertionSequence::value_type F;\n        F.push_back(std::make_pair(count, i));\n        if (forward_checking(g1, g2, M_prime, count, F, num_vert_g1,\n                             num_vert_g2, edge_labeling)) {\n          tFF.push_back(F);\n        }\n      }\n      backtrack_all(g1, g2, count + 1, M_prime, tFF, num_vert_g1, num_vert_g2,\n                    edge_labeling);\n      if (tFF.size()) {\n        for (typename DoubleBackInsertionSequence::const_iterator iter =\n                 tFF.begin();\n             iter != tFF.end(); ++iter) {\n          FF.push_back(*iter);\n        }\n      }\n    }\n  }\n}\n\ntemplate <class Graph, class VertexLabeling  // binary predicate\n          ,\n          class UblasMatrix>\nvoid prepareM(const Graph& g1, const Graph& g2, VertexLabeling& vertex_labeling,\n              UblasMatrix& M) {\n  size_t rows(num_vertices(g1));\n  size_t cols(num_vertices(g2));\n  M.resize(rows, cols);\n  // initialize the matrix:\n  for (size_t i = 0; i < rows; ++i) {\n    for (size_t j = 0; j < cols; ++j) {\n      if (out_degree(j, g2) >= out_degree(i, g1) && vertex_labeling(i, j)) {\n        M(i, j) = 1;\n      } else\n        M(i, j) = 0;\n    }\n  }\n}\n}  // namespace detail\n\n// test if g1 is a subgraph of g2. mapped vertices are returned in F\n// Mapping : first: g1 vertices, second : g2 vertices\n// O( num_vertices(g1)! num_vertices(g1) ^ 3 )\n// This function doesnt Work with filtered graphs!\n// The size of F doesn't indicate match!\ntemplate <\n    class Graph, class VertexLabeling  // binary predicate\n    ,\n    class EdgeLabeling  // binary predicate\n    ,\n    class\n    BackInsertionSequence  // contains\n                           // std::pair<vertex_descriptor,vertex_descriptor>\n    >\nbool ullmann(const Graph& g1, const Graph& g2, VertexLabeling& vertex_labeling,\n             EdgeLabeling& edge_labeling, BackInsertionSequence& F) {\n  typedef ::boost::numeric::ublas::matrix<int> matrix_t;\n  size_t rows(num_vertices(g1));\n  size_t cols(num_vertices(g2));\n  matrix_t M;\n  detail::prepareM(g1, g2, vertex_labeling, M);\n  size_t count(0);\n  return detail::backtrack(g1, g2, count, M, F, rows, cols, edge_labeling);\n}\n\n// test if g1 is a subgraph of g2.\n// F returns all mappings of g1 in g2. mapping in separate containers\ntemplate <class Graph, class VertexLabeling  // binary predicate\n          ,\n          class EdgeLabeling  // binary predicate\n          ,\n          class DoubleBackInsertionSequence  // contains a back insertion\n                                             // sequence\n          >\nbool ullmann_all(const Graph& g1, const Graph& g2,\n                 VertexLabeling& vertex_labeling, EdgeLabeling& edge_labeling,\n                 DoubleBackInsertionSequence& F) {\n  typedef ::boost::numeric::ublas::matrix<int> matrix_t;\n  size_t rows(num_vertices(g1));\n  size_t cols(num_vertices(g2));\n  matrix_t M;\n  detail::prepareM(g1, g2, vertex_labeling, M);\n  size_t count(0);\n  detail::backtrack_all(g1, g2, count, M, F, rows, cols, edge_labeling);\n  return !F.empty();\n}\n\n}  // namespace boost\n\n#endif  // MORPHO_CDL_BGL_EXP_ULLMANN_HPP\n", "meta": {"hexsha": "2476c54a53aa51693f8791111ab58b5ed27887cf", "size": 9856, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Substruct/ullmann.hpp", "max_stars_repo_name": "kazuyaujihara/rdkit", "max_stars_repo_head_hexsha": "06027dcd05674787b61f27ba46ec0d42a6037540", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1609.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T02:41:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:57:24.000Z", "max_issues_repo_path": "Code/GraphMol/Substruct/ullmann.hpp", "max_issues_repo_name": "kazuyaujihara/rdkit", "max_issues_repo_head_hexsha": "06027dcd05674787b61f27ba46ec0d42a6037540", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3412.0, "max_issues_repo_issues_event_min_datetime": "2015-01-06T12:13:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T17:25:41.000Z", "max_forks_repo_path": "Code/GraphMol/Substruct/ullmann.hpp", "max_forks_repo_name": "bp-kelley/rdkit", "max_forks_repo_head_hexsha": "e0de7c9622ce73894b1e7d9568532f6d5638058a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 811.0, "max_forks_repo_forks_event_min_datetime": "2015-01-11T03:33:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T11:57:49.000Z", "avg_line_length": 37.1924528302, "max_line_length": 80, "alphanum_fraction": 0.6035917208, "num_tokens": 2602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22514787529083652}}
{"text": "/**\n * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved\n *\n * This file is part of GeoDa.\n * \n * GeoDa is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * GeoDa is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <boost/thread.hpp>\n#include <boost/bind.hpp>\n\n#include <time.h>\n#include <math.h>\n#include <wx/filename.h>\n#include <wx/stopwatch.h>\n#include \"../DataViewer/TableInterface.h\"\n#include \"../ShapeOperations/RateSmoothing.h\"\n#include \"../ShapeOperations/Randik.h\"\n#include \"../ShapeOperations/WeightsManState.h\"\n#include \"../ShapeOperations/WeightUtils.h\"\n#include \"../VarCalc/WeightsManInterface.h\"\n#include \"../logger.h\"\n#include \"../Project.h\"\n#include \"LisaCoordinatorObserver.h\"\n#include \"LisaCoordinator.h\"\n\nLisaWorkerThread::LisaWorkerThread(const GalElement* W_,\n                                   const std::vector<bool>& undefs_,\n                                   int obs_start_s, int obs_end_s,\n\t\t\t\t\t\t\t\t   uint64_t\tseed_start_s,\n\t\t\t\t\t\t\t\t   LisaCoordinator* lisa_coord_s,\n\t\t\t\t\t\t\t\t   wxMutex* worker_list_mutex_s,\n\t\t\t\t\t\t\t\t   wxCondition* worker_list_empty_cond_s,\n\t\t\t\t\t\t\t\t   std::list<wxThread*> *worker_list_s,\n\t\t\t\t\t\t\t\t   int thread_id_s)\n: wxThread(),\nW(W_),\nundefs(undefs_),\nobs_start(obs_start_s), obs_end(obs_end_s), seed_start(seed_start_s),\nlisa_coord(lisa_coord_s),\nworker_list_mutex(worker_list_mutex_s),\nworker_list_empty_cond(worker_list_empty_cond_s),\nworker_list(worker_list_s),\nthread_id(thread_id_s)\n{\n}\n\nLisaWorkerThread::~LisaWorkerThread()\n{\n}\n\nwxThread::ExitCode LisaWorkerThread::Entry()\n{\n\tLOG_MSG(wxString::Format(\"LisaWorkerThread %d started\", thread_id));\n\n\t// call work for assigned range of observations\n\tlisa_coord->CalcPseudoP_range(W, undefs, obs_start, obs_end, seed_start);\n\t\n\twxMutexLocker lock(*worker_list_mutex);\n    \n\t// remove ourself from the list\n\tworker_list->remove(this);\n\t\n    // if empty, signal on empty condition since only main thread\n\t// should be waiting on this condition\n\tif (worker_list->empty()) {\n\t\tworker_list_empty_cond->Signal();\n\t}\n\t\n\treturn NULL;\n}\n\n/** \n Since the user has the ability to synchronise either variable over time,\n we must be able to reapply weights and recalculate lisa values as needed.\n \n 1. We will have original data as complete space-time data for both variables\n \n 2. From there we will work from info in var_info for both variables.  Must\n    determine number of time_steps for canvas.\n \n 3. Adjust data1(2)_vecs sizes and initialize from data.\n \n 3.5. Resize localMoran, sigLocalMoran, sigCat, and cluster arrays\n \n 4. If rates, then calculate rates for working_data1\n \n 5. Standardize working_data1 (and 2 if bivariate)\n \n 6. Compute LISA for all time-stesp and save in localMoran sp/time array\n \n 7. Calc Pseudo P for all time periods.  Results saved in sigLocalMoran,\n    sigCat and cluster arrays\n \n 8. Notify clients that values have been updated.\n   \n */\n\nLisaCoordinator::\nLisaCoordinator(boost::uuids::uuid weights_id,\n                Project* project,\n                const std::vector<GdaVarTools::VarInfo>& var_info_s,\n                const std::vector<int>& col_ids,\n                LisaType lisa_type_s,\n                bool calc_significances_s,\n                bool row_standardize_s)\n: w_man_state(project->GetWManState()),\nw_man_int(project->GetWManInt()),\nw_id(weights_id),\nnum_obs(project->GetNumRecords()),\npermutations(999),\nlisa_type(lisa_type_s),\ncalc_significances(calc_significances_s),\nisBivariate(lisa_type_s == bivariate),\nvar_info(var_info_s),\ndata(var_info_s.size()),\nundef_data(var_info_s.size()),\nlast_seed_used(0), reuse_last_seed(false),\nrow_standardize(row_standardize_s)\n{\n    reuse_last_seed = GdaConst::use_gda_user_seed;\n    if ( GdaConst::use_gda_user_seed) {\n        last_seed_used = GdaConst::gda_user_seed;\n    }\n    \n\tTableInterface* table_int = project->GetTableInt();\n\tfor (int i=0; i<var_info.size(); i++) {\n\t\ttable_int->GetColData(col_ids[i], data[i]);\n        table_int->GetColUndefined(col_ids[i], undef_data[i]);\n        var_info[i].is_moran = true;\n\t}\n    \n    undef_tms.resize(var_info_s[0].time_max - var_info_s[0].time_min + 1);\n\t\n\tweight_name = w_man_int->GetLongDispName(w_id);\n    \n    weights = w_man_int->GetGal(w_id);\n    \n\tSetSignificanceFilter(1);\n    \n\tInitFromVarInfo();\n\tw_man_state->registerObserver(this);\n}\n\n\nLisaCoordinator::\nLisaCoordinator(wxString weights_path,\n                int n,\n                std::vector<double> vals_1,\n                std::vector<double> vals_2,\n                int lisa_type_s,\n                int permutations_s,\n                bool calc_significances_s,\n                bool row_standardize_s)\n{\n    num_obs = n;\n    num_time_vals = 1;\n    permutations = permutations_s;\n    calc_significances = calc_significances_s;\n    row_standardize = row_standardize_s;\n    last_seed_used = 0;\n    reuse_last_seed = false;\n    isBivariate = false;\n \n    // std::vector<GdaVarTools::VarInfo> var_info;\n    int num_vars = 1;\n    isBivariate = false;\n    \n    if (lisa_type_s == 0) {\n        lisa_type = univariate;\n        \n    } else if (lisa_type_s == 1) {\n        lisa_type = bivariate;\n        isBivariate = true;\n        num_vars = 2;\n        \n    } else if (lisa_type_s == 2) {\n        lisa_type = eb_rate_standardized;\n        num_vars = 2;\n        \n    } else if (lisa_type_s == 3) {\n        lisa_type = differential;\n        num_vars = 2;\n    }\n    \n    undef_tms.resize(num_time_vals);\n    data.resize(num_vars);\n    undef_data.resize(num_vars);\n    var_info.resize(num_vars);\n    \n    // don't handle time variable for now\n    for (int i=0; i<var_info.size(); i++) {\n        data[i].resize(boost::extents[num_time_vals][num_obs]);\n        undef_data[i].resize(boost::extents[num_time_vals][num_obs]);\n        var_info[i].is_moran = true;\n        var_info[i].is_time_variant = false;\n        var_info[i].fixed_scale = true;\n        var_info[i].sync_with_global_time  = false;\n        var_info[i].time_max = 0;\n        var_info[i].time_min = 0;\n    }\n    \n    for (int i=0; i<num_obs; i++) {\n        data[0][0][i] = vals_1[i];\n        undef_data[0][0][i] = false;\n    }\n    if (num_vars == 2) {\n        for (int i=0; i<num_obs; i++) {\n            data[1][0][i] = vals_1[i];\n            undef_data[1][0][i] = false;\n        }\n    }\n    \n    // create weights\n    w_man_state = NULL;\n    w_man_int = NULL;\n    \n    wxString ext = GenUtils::GetFileExt(weights_path).Lower();\n    GalElement* tempGal = 0;\n    if (ext == \"gal\") {\n        tempGal = WeightUtils::ReadGal(weights_path, NULL);\n    } else {\n        tempGal = WeightUtils::ReadGwtAsGal(weights_path, NULL);\n    }\n    \n    weights = new GalWeight();\n    weights->num_obs = num_obs;\n    weights->wflnm = weights_path;\n    weights->id_field = \"ogc_fid\";\n    weights->gal = tempGal;\n    \n    SetSignificanceFilter(1);\n    InitFromVarInfo();\n}\n\nLisaCoordinator::~LisaCoordinator()\n{\n    if (w_man_state) {\n        w_man_state->removeObserver(this);\n    }\n\tDeallocateVectors();\n}\n\nvoid LisaCoordinator::DeallocateVectors()\n{\n\tfor (int i=0; i<lags_vecs.size(); i++) {\n\t\tif (lags_vecs[i]) delete [] lags_vecs[i];\n\t}\n\tlags_vecs.clear();\n    \n\tfor (int i=0; i<local_moran_vecs.size(); i++) {\n\t\tif (local_moran_vecs[i]) delete [] local_moran_vecs[i];\n\t}\n\tlocal_moran_vecs.clear();\n\tfor (int i=0; i<sig_local_moran_vecs.size(); i++) {\n\t\tif (sig_local_moran_vecs[i]) delete [] sig_local_moran_vecs[i];\n\t}\n\tsig_local_moran_vecs.clear();\n\tfor (int i=0; i<sig_cat_vecs.size(); i++) {\n\t\tif (sig_cat_vecs[i]) delete [] sig_cat_vecs[i];\n\t}\n\tsig_cat_vecs.clear();\n\tfor (int i=0; i<cluster_vecs.size(); i++) {\n\t\tif (cluster_vecs[i]) delete [] cluster_vecs[i];\n\t}\n\tcluster_vecs.clear();\n\tfor (int i=0; i<data1_vecs.size(); i++) {\n\t\tif (data1_vecs[i]) delete [] data1_vecs[i];\n\t}\n\tdata1_vecs.clear();\n\tfor (int i=0; i<data2_vecs.size(); i++) {\n\t\tif (data2_vecs[i]) delete [] data2_vecs[i];\n\t}\n\tdata2_vecs.clear();\n    \n    // clear W_vecs\n    for (size_t i=0; i<has_undefined.size(); i++) {\n        if (has_undefined[i]) {\n            // clean the copied weights\n            delete Gal_vecs[i];\n        }\n    }\n    Gal_vecs.clear();\n}\n\n/** allocate based on var_info and num_time_vals **/\nvoid LisaCoordinator::AllocateVectors()\n{\n\tint tms = num_time_vals;\n    \n\tlags_vecs.resize(tms);\n\tlocal_moran_vecs.resize(tms);\n\tsig_local_moran_vecs.resize(tms);\n\tsig_cat_vecs.resize(tms);\n\tcluster_vecs.resize(tms);\n\tdata1_vecs.resize(tms);\n\tmap_valid.resize(tms);\n\tmap_error_message.resize(tms);\n\thas_isolates.resize(tms);\n\thas_undefined.resize(tms);\n    \n\tfor (int i=0; i<tms; i++) {\n\t\tlags_vecs[i] = new double[num_obs];\n\t\tlocal_moran_vecs[i] = new double[num_obs];\n\t\tif (calc_significances) {\n\t\t\tsig_local_moran_vecs[i] = new double[num_obs];\n\t\t\tsig_cat_vecs[i] = new int[num_obs];\n\t\t}\n\t\tcluster_vecs[i] = new int[num_obs];\n\t\tdata1_vecs[i] = new double[num_obs];\n\t\tmap_valid[i] = true;\n\t\tmap_error_message[i] = wxEmptyString;\n\t}\n\t\n\tif (lisa_type == bivariate) {\n\t\tdata2_vecs.resize((var_info[1].time_max - var_info[1].time_min) + 1);\n\t\tfor (int i=0; i<data2_vecs.size(); i++) {\n\t\t\tdata2_vecs[i] = new double[num_obs];\n\t\t}\n\t}\n}\n\n/** We assume only that var_info is initialized correctly.\n ref_var_index, is_any_time_variant, is_any_sync_with_global_time and\n num_time_vals are first updated based on var_info */ \nvoid LisaCoordinator::InitFromVarInfo()\n{\n\tDeallocateVectors();\n\t\n\tnum_time_vals = 1;\n    is_any_time_variant = false;\n    is_any_sync_with_global_time = false;\n    ref_var_index = -1;\n    \n    if (lisa_type != differential) {\n        for (int i=0; i<var_info.size(); i++) {\n            if (var_info[i].is_time_variant && var_info[i].sync_with_global_time) {\n                num_time_vals = (var_info[i].time_max - var_info[i].time_min) + 1;\n                is_any_sync_with_global_time = true;\n                ref_var_index = i;\n                break;\n            }\n        }\n        for (int i=0; i<var_info.size(); i++) {\n            if (var_info[i].is_time_variant) {\n                is_any_time_variant = true;\n                break;\n            }\n        }\n    }\n\t\n\tAllocateVectors();\n\t\n    if (lisa_type == differential) {\n        int t=0;\n        for (int i=0; i<num_obs; i++) {\n            int t0 = var_info[0].time;\n            int t1 = var_info[1].time;\n            data1_vecs[0][i] = data[0][t0][i] - data[0][t1][i];\n        }\n        \n    } else if (lisa_type == univariate || lisa_type == bivariate) {\n\t\tfor (int t=var_info[0].time_min; t<=var_info[0].time_max; t++) {\n\t\t\tint d1_t = t - var_info[0].time_min;\n            for (int i=0; i<num_obs; i++) {\n                data1_vecs[d1_t][i] = data[0][t][i];\n            }\n\t\t}\n\t\tif (lisa_type == bivariate) {\n\t\t\tfor (int t=var_info[1].time_min; t<=var_info[1].time_max; t++) {\n\t\t\t\tint d2_t = t - var_info[1].time_min;\n\t\t\t\tfor (int i=0; i<num_obs; i++) {\n\t\t\t\t\tdata2_vecs[d2_t][i] = data[1][t][i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else { // lisa_type == eb_rate_standardized\n\t\tstd::vector<bool> undef_res(num_obs, false);\n\t\tdouble* smoothed_results = new double[num_obs];\n\t\tdouble* E = new double[num_obs]; // E corresponds to var_info[0]\n\t\tdouble* P = new double[num_obs]; // P corresponds to var_info[1]\n\t\t// we will only fill data1 for eb_rate_standardized and\n\t\t// further lisa calcs will treat as univariate\n\t\tfor (int t=0; t<num_time_vals; t++) {\n\t\t\tint v0_t = var_info[0].time_min;\n\t\t\tif (var_info[0].is_time_variant &&\n\t\t\t\tvar_info[0].sync_with_global_time) {\n\t\t\t\tv0_t += t;\n\t\t\t}\n\t\t\tfor (int i=0; i<num_obs; i++) E[i] = data[0][v0_t][i];\n\t\t\tint v1_t = var_info[1].time_min;\n\t\t\tif (var_info[1].is_time_variant &&\n\t\t\t\tvar_info[1].sync_with_global_time) {\n\t\t\t\tv1_t += t;\n\t\t\t}\n\t\t\tfor (int i=0; i<num_obs; i++) P[i] = data[1][v1_t][i];\n\t\t\tbool success = GdaAlgs::RateStandardizeEB(num_obs, P, E,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tsmoothed_results,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tundef_res);\n\t\t\tif (!success) {\n\t\t\t\tmap_valid[t] = false;\n\t\t\t\tmap_error_message[t] << \"Emprical Bayes Rate \";\n\t\t\t\tmap_error_message[t] << \"Standardization failed.\";\n\t\t\t} else {\n\t\t\t\tfor (int i=0; i<num_obs; i++) {\n\t\t\t\t\tdata1_vecs[t][i] = smoothed_results[i];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (smoothed_results) delete [] smoothed_results;\n\t\tif (E) delete [] E;\n\t\tif (P) delete [] P;\n\t}\n\t\n\tStandardizeData();\n\t\n    CalcLisa();\n    \n    if (calc_significances) {\n        CalcPseudoP();\n    }\n    \n    \n}\n\nvoid LisaCoordinator::GetRawData(int time, double* data1, double* data2)\n{\n    if (lisa_type == differential) {\n        int t=0;\n        for (int i=0; i<num_obs; i++) {\n            int t0 = var_info[0].time;\n            int t1 = var_info[1].time;\n            data1[i] = data[0][t0][i] - data[0][t1][i];\n        }\n        \n    } else if (lisa_type == univariate || lisa_type == bivariate) {\n        for (int i=0; i<num_obs; i++) {\n            data1[i] = data[0][time][i];\n        }\n        if (lisa_type == bivariate) {\n            for (int i=0; i<num_obs; i++) {\n                data2[i] = data[1][time][i];\n            }\n        }\n    } else { // lisa_type == eb_rate_standardized\n        std::vector<bool> undef_res(num_obs, false);\n        double* smoothed_results = new double[num_obs];\n        double* E = new double[num_obs]; // E corresponds to var_info[0]\n        double* P = new double[num_obs]; // P corresponds to var_info[1]\n        // we will only fill data1 for eb_rate_standardized and\n        // further lisa calcs will treat as univariate\n        for (int i=0; i<num_obs; i++) {\n            E[i] = data[0][time][i];\n        }\n        for (int i=0; i<num_obs; i++) {\n            P[i] = data[1][time][i];\n        }\n        bool success = GdaAlgs::RateStandardizeEB(num_obs, P, E,\n                                                  smoothed_results,\n                                                  undef_res);\n        if (success) {\n            for (int i=0; i<num_obs; i++) {\n                data1[i] = smoothed_results[i];\n            }\n        }\n        if (smoothed_results) delete [] smoothed_results;\n        if (E) delete [] E;\n        if (P) delete [] P;\n    }\n}\n\n/** Update Secondary Attributes based on Primary Attributes.\n Update num_time_vals and ref_var_index based on Secondary Attributes. */\nvoid LisaCoordinator::VarInfoAttributeChange()\n{\n\tGdaVarTools::UpdateVarInfoSecondaryAttribs(var_info);\n\t\n\tis_any_time_variant = false;\n\tis_any_sync_with_global_time = false;\n\tfor (int i=0; i<var_info.size(); i++) {\n\t\tif (var_info[i].is_time_variant) is_any_time_variant = true;\n\t\tif (var_info[i].sync_with_global_time) {\n\t\t\tis_any_sync_with_global_time = true;\n\t\t}\n\t}\n\tref_var_index = -1;\n\tnum_time_vals = 1;\n\tfor (int i=0; i<var_info.size() && ref_var_index == -1; i++) {\n\t\tif (var_info[i].is_ref_variable) ref_var_index = i;\n\t}\n\tif (ref_var_index != -1) {\n\t\tnum_time_vals = (var_info[ref_var_index].time_max -\n\t\t\t\t\t\t var_info[ref_var_index].time_min) + 1;\n\t}\n\t//GdaVarTools::PrintVarInfoVector(var_info);\n}\n\nvoid LisaCoordinator::StandardizeData()\n{\n\tfor (int t=0; t<data1_vecs.size(); t++) {\n        undef_tms[t].resize(num_obs);\n        \n        for (int i=0; i<num_obs; i++) {\n            undef_tms[t][i] = undef_tms[t][i] || undef_data[0][t][i];\n        }\n        if (isBivariate) {\n            for (int i=0; i<num_obs; i++) {\n                if ( undef_data[1].size() > t ) {\n                    undef_tms[t][i] = undef_tms[t][i] || undef_data[1][t][i];\n                }\n            }\n        }\n    }\n    \n\tfor (int t=0; t<data1_vecs.size(); t++) {\n\t\tGenUtils::StandardizeData(num_obs, data1_vecs[t], undef_tms[t]);\n        if (isBivariate) {\n            if (data2_vecs.size() > t)\n                GenUtils::StandardizeData(num_obs, data2_vecs[t], undef_tms[t]);\n        }\n\t}\n}\n\n/** assumes StandardizeData already called on data1 and data2 */\nvoid LisaCoordinator::CalcLisa()\n{\n\tfor (int t=0; t<num_time_vals; t++) {\n\t\tdata1 = data1_vecs[t];\n\t\tif (isBivariate) {\n\t\t\tdata2 = data2_vecs[0];\n\t\t\tif (var_info[1].is_time_variant && var_info[1].sync_with_global_time)\n                data2 = data2_vecs[t];\n\t\t}\n\t\tlags = lags_vecs[t];\n\t\tlocalMoran = local_moran_vecs[t];\n\t\tcluster = cluster_vecs[t];\n\t\n\t\thas_isolates[t] = false;\n    \n        // get undefs of objects/values at this time step\n        std::vector<bool> undefs;\n        bool has_undef = false;\n        for (int i=0; i<undef_data[0][t].size(); i++){\n            bool is_undef = undef_data[0][t][i];\n            if (isBivariate) {\n                if (undef_data[1].size() > t)\n                    is_undef = is_undef || undef_data[1][t][i];\n            }\n            if (is_undef && !has_undef) {\n                has_undef = true;\n            }\n            undefs.push_back(is_undef);\n        }\n        has_undefined[t] = has_undef;\n       \n        // local weights copy\n        GalWeight* gw = NULL;\n        if ( has_undef ) {\n            gw = new GalWeight(*weights);\n            gw->Update(undefs);\n        } else {\n            gw = weights;\n        }\n        GalElement* W = gw->gal;\n        Gal_vecs.push_back(gw);\n        Gal_vecs_orig.push_back(weights);\n\t\n\t\tfor (int i=0; i<num_obs; i++) {\n            \n            if (undefs[i] == true) {\n                lags[i] = 0;\n                localMoran[i] = 0;\n                cluster[i] = 6; // undefined value\n                continue;\n            }\n            \n\t\t\tdouble Wdata = 0;\n\t\t\tif (isBivariate) {\n\t\t\t\tWdata = W[i].SpatialLag(data2);\n\t\t\t} else {\n\t\t\t\tWdata = W[i].SpatialLag(data1);\n\t\t\t}\n\t\t\tlags[i] = Wdata;\n\t\t\tlocalMoran[i] = data1[i] * Wdata;\n\t\t\t\t\n\t\t\t// assign the cluster\n\t\t\tif (W[i].Size() > 0) {\n\t\t\t\tif (data1[i] > 0 && Wdata < 0) cluster[i] = 4;\n\t\t\t\telse if (data1[i] < 0 && Wdata > 0) cluster[i] = 3;\n\t\t\t\telse if (data1[i] < 0 && Wdata < 0) cluster[i] = 2;\n\t\t\t\telse cluster[i] = 1; //data1[i] > 0 && Wdata > 0\n\t\t\t} else {\n\t\t\t\thas_isolates[t] = true;\n\t\t\t\tcluster[i] = 5; // neighborless\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid LisaCoordinator::CalcPseudoP()\n{\n\tif (!calc_significances) return;\n\twxStopWatch sw;\n\tint nCPUs = wxThread::GetCPUCount();\n\t\n\t// To ensure thread safety, only work on one time slice of data\n\t// at a time.  For each time period t:\n\t// 1. copy data for time period t into data1 and data2 arrays\n\t// 2. Perform multi-threaded computation\n\t// 3. copy results into results array\n\t\n\t\n\tfor (int t=0; t<num_time_vals; t++) {\n\t\n        std::vector<bool>& undefs = undef_tms[t];\n\t\tdata1 = data1_vecs[t];\n\t\tif (isBivariate) {\n\t\t\tdata2 = data2_vecs[0];\n\t\t\tif (var_info[1].is_time_variant &&\n\t\t\t\tvar_info[1].sync_with_global_time)\n                data2 = data2_vecs[t];\n\t\t}\n\t\tlags = lags_vecs[t];\n\t\tlocalMoran = local_moran_vecs[t];\n\t\tsigLocalMoran = sig_local_moran_vecs[t];\n\t\tsigCat = sig_cat_vecs[t];\n\t\tcluster = cluster_vecs[t];\n\t\t\n\t\tif (nCPUs <= 1 || num_obs <= nCPUs * 10) {\n            if (!reuse_last_seed) {\n                last_seed_used = time(0);\n            }\n\t\t\tCalcPseudoP_range(Gal_vecs[t]->gal, undefs,\n                              0, num_obs-1, last_seed_used);\n\t\t} else {\n\t\t\tCalcPseudoP_threaded(Gal_vecs[t]->gal, undefs);\n\t\t\t//CalcPseudoP_range(Gal_vecs[t]->gal, undefs,\n                        //      0, num_obs-1, last_seed_used);\n\t\t}\n\t}\n    \n    \n\t{\n\t\twxString m;\n\t\tm << \"LISA on \" << num_obs << \" obs with \" << permutations;\n\t\tm << \" perms over \" << num_time_vals << \" time periods took \";\n\t\tm << sw.Time() << \" ms. Last seed used: \" << last_seed_used;\n\t}\n\tLOG_MSG(\"Exiting LisaCoordinator::CalcPseudoP\");\n}\n\nvoid LisaCoordinator::CalcPseudoP_threaded(const GalElement* W,\n                                           const std::vector<bool>& undefs)\n{\n\tint nCPUs = wxThread::GetCPUCount();\n\n\t// mutext protects access to the worker_list\n    wxMutex worker_list_mutex;\n\t// signals that worker_list is empty\n\twxCondition worker_list_empty_cond(worker_list_mutex);\n    // mutex should be initially locked\n\tworker_list_mutex.Lock();\n\t\n    // List of all the threads currently alive.  As soon as the thread\n\t// terminates, it removes itself from the list.\n\tstd::list<wxThread*> worker_list;\n\n\t// divide up work according to number of observations\n\t// and number of CPUs\n\tint work_chunk = num_obs / nCPUs;\n    \n    if (work_chunk == 0) {\n        work_chunk = 1;\n    }\n    \n\tint obs_start = 0;\n\tint obs_end = obs_start + work_chunk;\n\t\n\tbool is_thread_error = false;\n\tint quotient = num_obs / nCPUs;\n\tint remainder = num_obs % nCPUs;\n\tint tot_threads = (quotient > 0) ? nCPUs : remainder;\n\t\n    boost::thread_group threadPool;\n    \n\tif (!reuse_last_seed)\n        last_seed_used = time(0);\n\tfor (int i=0; i<tot_threads && !is_thread_error; i++) {\n\t\tint a=0;\n\t\tint b=0;\n\t\tif (i < remainder) {\n\t\t\ta = i*(quotient+1);\n\t\t\tb = a+quotient;\n\t\t} else {\n\t\t\ta = remainder*(quotient+1) + (i-remainder)*quotient;\n\t\t\tb = a+quotient-1;\n\t\t}\n\t\tuint64_t seed_start = last_seed_used+a;\n\t\tuint64_t seed_end = seed_start + ((uint64_t) (b-a));\n\t\tint thread_id = i+1;\n\t\twxString msg;\n\t\tmsg << \"thread \" << thread_id << \": \" << a << \"->\" << b;\n\t\tmsg << \", seed: \" << seed_start << \"->\" << seed_end;\n\t\t\n        /*\n\t\tLisaWorkerThread* thread =\n\t\t\tnew LisaWorkerThread(W, undefs, a, b, seed_start, this,\n\t\t\t\t\t\t\t\t &worker_list_mutex,\n\t\t\t\t\t\t\t\t &worker_list_empty_cond,\n\t\t\t\t\t\t\t\t &worker_list, thread_id);\n\t\tif ( thread->Create() != wxTHREAD_NO_ERROR ) {\n\t\t\tdelete thread;\n\t\t\tis_thread_error = true;\n\t\t} else {\n\t\t\tworker_list.push_front(thread);\n\t\t}\n         */\n        boost::thread* worker = new boost::thread(boost::bind(&LisaCoordinator::CalcPseudoP_range,this, W, undefs, a, b, seed_start));\n        threadPool.add_thread(worker);\n\t}\n    threadPool.join_all();\n    /*\n\tif (is_thread_error) {\n\t\t// fall back to single thread calculation mode\n\t\tCalcPseudoP_range(W, undefs, 0, num_obs-1, last_seed_used);\n\t} else {\n\t\tstd::list<wxThread*>::iterator it;\n\t\tfor (it = worker_list.begin(); it != worker_list.end(); it++) {\n\t\t\t(*it)->Run();\n\t\t}\n\t\n\t\twhile (!worker_list.empty()) {\n\t\t\t// wait until thread_list might be empty\n\t\t\tworker_list_empty_cond.Wait();\n\t\t\t// We have been woken up. If this was not a false\n\t\t\t// alarm (sprious signal), the loop will exit.\n\t\t}\n\t}\n     */\n}\n\nvoid LisaCoordinator::CalcPseudoP_range(const GalElement* W,\n                                        const std::vector<bool>& undefs,\n                                        int obs_start, int obs_end,\n\t\t\t\t\t\t\t\t\t\tuint64_t seed_start)\n{\n\tGeoDaSet workPermutation(num_obs);\n\t//Randik rng;\n\tint max_rand = num_obs-1;\n\tfor (int cnt=obs_start; cnt<=obs_end; cnt++) {\n        \n        if (undefs[cnt])\n            continue;\n        \n\t\tconst int numNeighbors = W[cnt].Size();\n\t\t\n\t\tuint64_t countLarger = 0;\n\t\tfor (int perm=0; perm<permutations; perm++) {\n\t\t\tint rand=0;\n\t\t\twhile (rand < numNeighbors) {\n\t\t\t\t// computing 'perfect' permutation of given size\n                double rng_val = Gda::ThomasWangHashDouble(seed_start++) * max_rand;\n                // round is needed to fix issue\n                //https://github.com/GeoDaCenter/geoda/issues/488\n\t\t\t\tint newRandom = (int) (rng_val < 0.0 ? ceil(rng_val - 0.5) : floor(rng_val + 0.5));\n\t\t\t\tif (newRandom != cnt &&\n                    !workPermutation.Belongs(newRandom) &&\n                    undefs[newRandom] == false)\n\t\t\t\t{\n\t\t\t\t\tworkPermutation.Push(newRandom);\n\t\t\t\t\trand++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdouble permutedLag=0;\n\t\t\t// use permutation to compute the lag\n\t\t\t// compute the lag for binary weights\n\t\t\tif (isBivariate) {\n\t\t\t\tfor (int cp=0; cp<numNeighbors; cp++) {\n\t\t\t\t\tpermutedLag += data2[workPermutation.Pop()];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor (int cp=0; cp<numNeighbors; cp++) {\n\t\t\t\t\tpermutedLag += data1[workPermutation.Pop()];\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t//NOTE: we shouldn't have to row-standardize or\n\t\t\t// multiply by data1[cnt]\n            if (numNeighbors && row_standardize) {\n                permutedLag /= numNeighbors;\n            }\n\t\t\tconst double localMoranPermuted = permutedLag * data1[cnt];\n            if (localMoranPermuted >= localMoran[cnt]) {\n                countLarger++;\n            }\n\t\t}\n\t\t// pick the smallest\n\t\tif (permutations-countLarger <= countLarger) { \n\t\t\tcountLarger = permutations-countLarger;\n\t\t}\n\t\t\n\t\tsigLocalMoran[cnt] = (countLarger+1.0)/(permutations+1);\n\t\t// 'significance' of local Moran\n\t\tif (sigLocalMoran[cnt] <= 0.0001) sigCat[cnt] = 4;\n\t\telse if (sigLocalMoran[cnt] <= 0.001) sigCat[cnt] = 3;\n\t\telse if (sigLocalMoran[cnt] <= 0.01) sigCat[cnt] = 2;\n\t\telse if (sigLocalMoran[cnt] <= 0.05) sigCat[cnt]= 1;\n\t\telse sigCat[cnt]= 0;\n\t\t\n\t\t// observations with no neighbors get marked as isolates\n        // NOTE: undefined should be marked as well, however, since undefined_cat has covered undefined category, we don't need to handle here\n\t\tif (numNeighbors == 0) {\n\t\t\tsigCat[cnt] = 5;\n\t\t}\n\t}\n}\n\nvoid LisaCoordinator::SetSignificanceFilter(int filter_id)\n{\n\t// 0: >0.05 1: 0.05, 2: 0.01, 3: 0.001, 4: 0.0001\n\tif (filter_id < 1 || filter_id > 4) return;\n\tsignificance_filter = filter_id;\n\tif (filter_id == 1) significance_cutoff = 0.05;\n\tif (filter_id == 2) significance_cutoff = 0.01;\n\tif (filter_id == 3) significance_cutoff = 0.001;\n\tif (filter_id == 4) significance_cutoff = 0.0001;\n}\n\nvoid LisaCoordinator::update(WeightsManState* o)\n{\n    if (w_man_int) {\n        weight_name = w_man_int->GetLongDispName(w_id);\n    }\n}\n\nint LisaCoordinator::numMustCloseToRemove(boost::uuids::uuid id) const\n{\n\treturn id == w_id ? observers.size() : 0;\n}\n\nvoid LisaCoordinator::closeObserver(boost::uuids::uuid id)\n{\n\tif (numMustCloseToRemove(id) == 0) return;\n\tstd::list<LisaCoordinatorObserver*> obs_cpy = observers;\n\tfor (std::list<LisaCoordinatorObserver*>::iterator i=obs_cpy.begin();\n\t\t i != obs_cpy.end(); ++i) {\n\t\t(*i)->closeObserver(this);\n\t}\n}\n\nvoid LisaCoordinator::registerObserver(LisaCoordinatorObserver* o)\n{\n\tobservers.push_front(o);\n}\n\nvoid LisaCoordinator::removeObserver(LisaCoordinatorObserver* o)\n{\n\tLOG_MSG(\"Entering LisaCoordinator::removeObserver\");\n\tobservers.remove(o);\n\tLOG(observers.size());\n\tif (observers.size() == 0) {\n\t\tdelete this;\n\t}\n\tLOG_MSG(\"Exiting LisaCoordinator::removeObserver\");\n}\n\nvoid LisaCoordinator::notifyObservers()\n{\n\tfor (std::list<LisaCoordinatorObserver*>::iterator  it=observers.begin();\n\t\t it != observers.end(); ++it) {\n\t\t(*it)->update(this);\n\t}\n}\n\n", "meta": {"hexsha": "648d8bf0c7e8abb5236430d6251695e34afe839e", "size": 26442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Explore/LisaCoordinator.cpp", "max_stars_repo_name": "chenyoujie/GeoDa", "max_stars_repo_head_hexsha": "87504344512bd0da2ccadfb160ecd1e918a52f06", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Explore/LisaCoordinator.cpp", "max_issues_repo_name": "chenyoujie/GeoDa", "max_issues_repo_head_hexsha": "87504344512bd0da2ccadfb160ecd1e918a52f06", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Explore/LisaCoordinator.cpp", "max_forks_repo_name": "chenyoujie/GeoDa", "max_forks_repo_head_hexsha": "87504344512bd0da2ccadfb160ecd1e918a52f06", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8442437923, "max_line_length": 142, "alphanum_fraction": 0.6140987822, "num_tokens": 7574, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.2251478752908365}}
{"text": "#define PY_ARRAY_UNIQUE_SYMBOL pbcvt_ARRAY_API\n\n#define NUMPY_IMPORT_ARRAY_RETVAL NULL\n\n#include <boost/python.hpp>\n#include <pyboostcvconverter/pyboostcvconverter.hpp>\n#include <opencv2/features2d.hpp>\n#include <opencv2/highgui.hpp>\n#include \"sift.simd.hpp\"\n#include <iostream>\n\n#include <algorithm>\n\nconst float sigma = 1.6;\nconst int nOctaveLayers = 3;\n\nstd::string getImageType(int number)\n{\n    // find type\n    int imgTypeInt = number%8;\n    std::string imgTypeString;\n\n    switch (imgTypeInt)\n    {\n        case 0:\n            imgTypeString = \"8U\";\n            break;\n        case 1:\n            imgTypeString = \"8S\";\n            break;\n        case 2:\n            imgTypeString = \"16U\";\n            break;\n        case 3:\n            imgTypeString = \"16S\";\n            break;\n        case 4:\n            imgTypeString = \"32S\";\n            break;\n        case 5:\n            imgTypeString = \"32F\";\n            break;\n        case 6:\n            imgTypeString = \"64F\";\n            break;\n        default:\n            break;\n    }\n\n    // find channel\n    int channel = (number/8) + 1;\n\n    std::stringstream type;\n    type<<\"CV_\"<<imgTypeString<<\"C\"<<channel;\n\n    return type.str();\n}\n\nstatic cv::Mat createInitialImage( const cv::Mat& img, bool doubleImageSize, float sigma )\n{\n    CV_TRACE_FUNCTION();\n\n    cv::Mat gray, gray_fpt;\n    if( img.channels() == 3 || img.channels() == 4 )\n    {\n        cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);\n        gray.convertTo(gray_fpt, cv::DataType<cv::sift_wt>::type, cv::SIFT_FIXPT_SCALE, 0);\n    }\n    else\n        img.convertTo(gray_fpt, cv::DataType<cv::sift_wt>::type, cv::SIFT_FIXPT_SCALE, 0);\n\n    float sig_diff;\n\n    if( doubleImageSize )\n    {\n        sig_diff = sqrtf( std::max(sigma * sigma - cv::SIFT_INIT_SIGMA * cv::SIFT_INIT_SIGMA * 4, 0.01f) );\n        cv::Mat dbl;\n#if DoG_TYPE_SHORT\n        cv::resize(gray_fpt, dbl, cv::Size(gray_fpt.cols*2, gray_fpt.rows*2), 0, 0, cv::INTER_LINEAR_EXACT);\n#else\n        cv::resize(gray_fpt, dbl, cv::Size(gray_fpt.cols*2, gray_fpt.rows*2), 0, 0, cv::INTER_LINEAR);\n#endif\n        cv::Mat result;\n        cv::GaussianBlur(dbl, result, cv::Size(), sig_diff, sig_diff);\n        return result;\n    }\n    else\n    {\n        sig_diff = sqrtf( std::max(sigma * sigma - cv::SIFT_INIT_SIGMA * cv::SIFT_INIT_SIGMA, 0.01f) );\n        cv::Mat result;\n        cv::GaussianBlur(gray_fpt, result, cv::Size(), sig_diff, sig_diff);\n        return result;\n    }\n}\n\nstd::vector<cv::Mat>\nbuild_image_pyramid(cv::Mat im, int firstOctave, int nOctaves) {\n\n    // Copyright (c) 2006-2010, Rob Hess <hess@eecs.oregonstate.edu>\n    // Copyright (C) 2009, Willow Garage Inc., all rights reserved.\n    // Copyright (C) 2020, Intel Corporation, all rights reserved.\n    cv::Mat base = createInitialImage(im, firstOctave<0, sigma);\n    printf(\"%i, %i\\n\", base.rows, base.cols);\n    CV_TRACE_FUNCTION();\n    std::vector<cv::Mat> gauss_pyr;\n\n    std::vector<double> sig(nOctaveLayers + 3);\n    gauss_pyr.resize(nOctaves*(nOctaveLayers + 3));\n\n    // precompute Gaussian sigmas using the following formula:\n    //  \\sigma_{total}^2 = \\sigma_{i}^2 + \\sigma_{i-1}^2\n    sig[0] = sigma;\n    double k = std::pow( 2., 1. / nOctaveLayers );\n    for( int i = 1; i < nOctaveLayers + 3; i++ )\n    {\n        double sig_prev = std::pow(k, (double)(i-1))*sigma;\n        double sig_total = sig_prev*k;\n        sig[i] = std::sqrt(sig_total*sig_total - sig_prev*sig_prev);\n    }\n\n    for( int o = 0; o < nOctaves; o++ )\n    {\n        for( int i = 0; i < nOctaveLayers + 3; i++ )\n        {\n            cv::Mat& dst = gauss_pyr[o*(nOctaveLayers + 3) + i];\n            if( o == 0  &&  i == 0 )\n                dst = base;\n            // base of new octave is halved image from end of previous octave\n            else if( i == 0 )\n            {\n                const cv::Mat& src = gauss_pyr[(o-1)*(nOctaveLayers + 3) + nOctaveLayers];\n                cv::resize(src, dst, cv::Size(src.cols/2, src.rows/2),\n                       0, 0, cv::INTER_NEAREST);\n            }\n            else\n            {\n                const cv::Mat& src = gauss_pyr[o*(nOctaveLayers + 3) + i-1];\n                cv::GaussianBlur(src, dst, cv::Size(), sig[i], sig[i]);\n            }\n        }\n    }\n    return gauss_pyr;\n}\n\nnamespace pbcvt {\n\n  using namespace boost::python;\n  PyObject *dog_pyramid(PyObject *impy, int firstOctave, int nOctaves) {\n    cv::Mat im;\n    im = pbcvt::fromNDArrayToMat(impy);\n    std::vector<cv::Mat> dogpyr;\n    dogpyr.resize(nOctaves * (nOctaveLayers + 2));\n    std::vector<cv::Mat> gauss_pyr = build_image_pyramid(im, firstOctave, nOctaves);\n    for( int a=0; a < nOctaves * (nOctaveLayers + 2); a++ ) {\n      const int o = a / (nOctaveLayers + 2);\n      const int i = a % (nOctaveLayers + 2);\n\n      const cv::Mat& src1 = gauss_pyr[o*(nOctaveLayers + 3) + i];\n      const cv::Mat& src2 = gauss_pyr[o*(nOctaveLayers + 3) + i + 1];\n      cv::Mat& dst = dogpyr[o*(nOctaveLayers + 2) + i];\n      cv::subtract(src2, src1, dst, noArray(), DataType<sift_wt>::type);\n    }\n    PyObject *ret = PyList_New(dogpyr.size());\n    for (int i=0; i<dogpyr.size(); i++) {\n      PyObject* layer = pbcvt::fromMatToNDArray(dogpyr.at(i));\n      PyList_SetItem(ret, i, layer);\n    }\n    return ret;\n  }\n\n  PyObject *image_pyramid(PyObject *impy, int firstOctave, int nOctaves) {\n    cv::Mat im;\n    im = pbcvt::fromNDArrayToMat(impy);\n    std::vector<cv::Mat> gauss_pyr = build_image_pyramid(im, firstOctave, nOctaves);\n    // cv::Mat out_kpts_t;\n    // cv::vconcat(out_kpts, out_kpts_t);\n    // PyObject *ret = pbcvt::fromMatToNDArray(out_kpts_t);\n    PyObject *ret = PyList_New(gauss_pyr.size());\n    for (int i=0; i<gauss_pyr.size(); i++) {\n      PyObject* layer = pbcvt::fromMatToNDArray(gauss_pyr.at(i));\n      PyList_SetItem(ret, i, layer);\n    }\n    return ret;\n  }\n\n  PyObject *sift_desc(PyObject *impy, PyObject *keypoints, int firstOctave, int nOctaves) {\n    // IDK if this is clear but there is a lot of opencv code in here\n\n    cv::Mat im, kpts;\n    im = pbcvt::fromNDArrayToMat(impy);\n    kpts = pbcvt::fromNDArrayToMat(keypoints);\n    // First, build a gauss_pyr\n    std::vector<cv::Mat> gauss_pyr = build_image_pyramid(im, firstOctave, nOctaves);\n\n    std::vector<cv::Mat> out_kpts;\n\n    // Compute orientation of keypoints\n    for (int i=0; i<kpts.rows; i++) {\n      // Get attributes of keypoint\n      float x = kpts.at<float>(i, 0);\n      float y = kpts.at<float>(i, 1);\n      float size = kpts.at<float>(i, 2);\n      int layer = kpts.at<float>(i, 3);\n      int octave = kpts.at<float>(i, 4) - firstOctave;\n      float c = x / (1 << octave);\n      float r = y / (1 << octave);\n      if (firstOctave < 0) {\n        size *= (1 << -firstOctave);\n        c *= (1 << -firstOctave);\n        r *= (1 << -firstOctave);\n      }\n\n      // Init variables\n      int n = cv::SIFT_ORI_HIST_BINS;\n      float hist[n];\n      float scl_octv = size*0.5f/(1 << octave);\n\n      // std::cout << gauss_pyr[octave*(nOctaveLayers+3) + layer].depth() << std::endl;\n      // cv::imshow(\"HI\", gauss_pyr[octave*(nOctaveLayers+3) + layer]);\n      // cv::waitKey(0);\n      float omax = cv::opt_CV_CPU_DISPATCH_MODE::calcOrientationHist(\n          gauss_pyr[octave*(nOctaveLayers+3) + layer],\n          cv::Point(c, r),\n          cvRound(cv::SIFT_ORI_RADIUS * scl_octv),\n          cv::SIFT_ORI_SIG_FCTR * scl_octv,\n          hist, n);\n\n      float mag_thr = (float)(omax * cv::SIFT_ORI_PEAK_RATIO);\n      for( int j = 0; j < n; j++ )\n      {\n        int l = j > 0 ? j - 1 : n - 1;\n        int r2 = j < n-1 ? j + 1 : 0;\n\n        if( hist[j] > hist[l]  &&  hist[j] > hist[r2]  &&  hist[j] >= mag_thr )\n        {\n          float bin = j + 0.5f * (hist[l]-hist[r2]) / (hist[l] - 2*hist[j] + hist[r2]);\n          bin = bin < 0 ? n + bin : bin >= n ? bin - n : bin;\n          float angle = 360.f - (float)((360.f/n) * bin);\n          if(std::abs(angle - 360.f) < FLT_EPSILON)\n            angle = 0.f;\n\n          cv::Mat kpt = cv::Mat::zeros(1, 6, CV_32F);\n          kpt.at<float>(0, 0) = x;\n          kpt.at<float>(0, 1) = y;\n          kpt.at<float>(0, 2) = size;\n          kpt.at<float>(0, 3) = layer;\n          kpt.at<float>(0, 4) = octave;\n          kpt.at<float>(0, 5) = angle;\n          if (firstOctave < 0) {\n            kpt.at<float>(0, 2) /= (1 << -firstOctave);\n            kpt.at<float>(0, 4) += firstOctave;\n          }\n          out_kpts.push_back(kpt);\n        }\n      }\n    }\n\n    cv::Mat out_kpts_t;\n    cv::vconcat(out_kpts, out_kpts_t);\n    PyObject *ret = pbcvt::fromMatToNDArray(out_kpts_t);\n    return ret;\n  }\n\n#if (PY_VERSION_HEX >= 0x03000000)\n\n  static void *init_ar() {\n#else\n    static void init_ar(){\n#endif\n      Py_Initialize();\n\n      import_array();\n      return NUMPY_IMPORT_ARRAY_RETVAL;\n    }\n\n    BOOST_PYTHON_MODULE (sift_ori) {\n      //using namespace XM;\n      init_ar();\n\n      //initialize converters\n      to_python_converter<cv::Mat,pbcvt::matToNDArrayBoostConverter>();\n      matFromNDArrayBoostConverter();\n\n      //expose module-level functions\n      def(\"sift_desc\", sift_desc);\n      def(\"image_pyramid\", image_pyramid);\n      def(\"dog_pyramid\", dog_pyramid);\n    }\n\n  } //end namespace pbcvt\n", "meta": {"hexsha": "2841bb52eafbda544cc7d1254a5ac1299a1916a1", "size": 9167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/python_module.cpp", "max_stars_repo_name": "half-potato/sift_orientation", "max_stars_repo_head_hexsha": "3c1db66da91468c3d0980d80884a6d682919635f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/python_module.cpp", "max_issues_repo_name": "half-potato/sift_orientation", "max_issues_repo_head_hexsha": "3c1db66da91468c3d0980d80884a6d682919635f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/python_module.cpp", "max_forks_repo_name": "half-potato/sift_orientation", "max_forks_repo_head_hexsha": "3c1db66da91468c3d0980d80884a6d682919635f", "max_forks_repo_licenses": ["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.5017182131, "max_line_length": 108, "alphanum_fraction": 0.5691065779, "num_tokens": 2866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2247647150700382}}
{"text": "// smooth_feedback: Control theory on Lie groups\n// https://github.com/pettni/smooth_feedback\n//\n// Licensed under the MIT License <http://opensource.org/licenses/MIT>.\n//\n// Copyright (c) 2021 Petter Nilsson, John B. Mains\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__FEEDBACK__QP_SOLVER_HPP_\n#define SMOOTH__FEEDBACK__QP_SOLVER_HPP_\n\n/**\n * @file\n * @brief Quadratic Program solver.\n */\n\n#include <Eigen/Cholesky>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <Eigen/SparseCholesky>\n\n#include <chrono>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <optional>\n\n#include \"qp.hpp\"\n#include \"utils/sparse.hpp\"\n\nnamespace smooth::feedback {\n\n/**\n * @brief Options for solve_qp\n */\nstruct QPSolverParams\n{\n  /// print solver info to stdout\n  bool verbose = false;\n\n  /// relaxation parameter\n  float alpha = 1.6;\n  /// first dual step size\n  float rho = 0.1;\n  /// second dual step length\n  float sigma = 1e-6;\n\n  /// scale problem\n  bool scaling = true;\n\n  /// absolute threshold for convergence\n  float eps_abs = 1e-3;\n  /// relative threshold for convergence\n  float eps_rel = 1e-3;\n  /// threshold for primal infeasibility\n  float eps_primal_inf = 1e-4;\n  /// threshold for dual infeasibility\n  float eps_dual_inf = 1e-4;\n\n  /// max number of iterations (default no limit)\n  std::optional<uint32_t> max_iter = {};\n\n  /// max solution time (default no limit)\n  std::optional<std::chrono::nanoseconds> max_time = {};\n\n  /// iterations between checking stopping criterion\n  uint32_t stop_check_iter = 25;\n\n  /// run solution polishing (uses dynamic memory)\n  bool polish = true;\n  /// number of iterations to refine polish\n  uint32_t polish_iter = 5;\n  /// regularization parameter for polishing\n  float delta = 1e-6;\n};\n\nnamespace detail {\n\ntemplate<typename Pbm>\nusing qp_solution_t = QPSolution<\n  decltype(Pbm::A)::RowsAtCompileTime,\n  decltype(Pbm::A)::ColsAtCompileTime,\n  typename decltype(Pbm::A)::Scalar>;\n\n/**\n * @brief Polish solution of quadratic program\n *\n * @tparam Pbm problem type\n *\n * @param[in] pbm problem formulation\n * @param[in, out] sol solution to polish\n * @param[in] prm solver options\n * @param[in] c cost scaling\n * @param[in] sx variable scaling\n * @param[in] sy constraint scaling\n *\n * @warning This function allocates dynamic memory even for static-sized problems.\n */\ntemplate<typename Pbm, typename D1, typename D2>\nbool polish_qp(\n  const Pbm & pbm,\n  qp_solution_t<Pbm> & sol,\n  const QPSolverParams & prm,\n  const typename decltype(Pbm::A)::Scalar c,\n  const Eigen::MatrixBase<D1> & sx,\n  const Eigen::MatrixBase<D2> & sy)\n{\n  using AmatT                  = decltype(Pbm::A);\n  using Scalar                 = typename AmatT::Scalar;\n  static constexpr bool sparse = std::is_base_of_v<Eigen::SparseMatrixBase<AmatT>, AmatT>;\n\n  static constexpr Scalar inf = std::numeric_limits<Scalar>::infinity();\n  static constexpr Scalar eps = std::numeric_limits<Scalar>::epsilon();\n\n  static constexpr Eigen::Index N = AmatT::ColsAtCompileTime;\n  const Eigen::Index n = pbm.A.cols(), m = pbm.A.rows();\n\n  // FIND ACTIVE CONSTRAINT SETS\n\n  Eigen::Index nl = 0, nu = 0;\n  for (Eigen::Index idx = 0; idx < m; ++idx) {\n    if (sol.dual[idx] < -100 * eps && pbm.l[idx] != -inf) { nl++; }\n    if (sol.dual[idx] > 100 * eps && pbm.u[idx] != inf) { nu++; }\n  }\n\n  Eigen::VectorXi LU_idx(nl + nu);\n  for (Eigen::Index idx = 0, lcntr = 0, ucntr = 0; idx < m; ++idx) {\n    if (sol.dual[idx] < -100 * eps && pbm.l[idx] != -inf) { LU_idx(lcntr++) = idx; }\n    if (sol.dual[idx] > 100 * eps && pbm.u[idx] != inf) { LU_idx(nl + ucntr++) = idx; }\n  }\n\n  // FORM REDUCED SYSTEMS (27) AND (30)\n\n  // square symmetric system matrix\n  using HT = std::conditional_t<sparse, Eigen::SparseMatrix<Scalar>, Eigen::Matrix<Scalar, -1, -1>>;\n  HT H(n + nl + nu, n + nl + nu), Hp(n + nl + nu, n + nl + nu);\n\n  // fill up H\n  if constexpr (sparse) {\n    // preallocate nonzeros\n    Eigen::VectorXi nnz(n + nl + nu);\n    for (auto i = 0u; i != n; ++i) {\n      nnz(i) = pbm.P.outerIndexPtr()[i + 1] - pbm.P.outerIndexPtr()[i];\n    }\n    for (auto i = 0u; i != nl + nu; ++i) {\n      nnz(n + i) = pbm.A.outerIndexPtr()[LU_idx(i) + 1] - pbm.A.outerIndexPtr()[LU_idx(i)];\n    }\n    H.reserve(nnz);\n    Hp.reserve(nnz + Eigen::VectorXi::Ones(n + nl + nu));\n\n    // fill P in top left block\n    for (auto k = 0u; k < n; ++k) {\n      for (Eigen::InnerIterator it(pbm.P, k); it; ++it) {\n        const Scalar pij              = c * sx(it.col()) * sx(it.row()) * it.value();\n        H.insert(it.row(), it.col())  = pij;\n        Hp.insert(it.row(), it.col()) = pij;\n      }\n    }\n\n    // fill selected rows of A in top right block\n    for (auto a_row = 0u; a_row != nl + nu; ++a_row) {\n      for (Eigen::InnerIterator it(pbm.A, LU_idx(a_row)); it; ++it) {\n        const Scalar Aij               = sy(it.row()) * sx(it.col()) * it.value();\n        H.insert(it.col(), n + a_row)  = Aij;\n        Hp.insert(it.col(), n + a_row) = Aij;\n      }\n    }\n  } else {\n    H.setZero();\n    H.topLeftCorner(n, n) = c * sx.asDiagonal() * pbm.P * sx.asDiagonal();\n    for (auto i = 0u; i != nl + nu; ++i) {\n      H.col(n + i).template head<N>(n) = sy(LU_idx(i)) * pbm.A.row(LU_idx(i)) * sx.asDiagonal();\n    }\n    Hp = H;\n  }\n\n  // add perturbing diagonal elements to Hp\n  if constexpr (sparse) {\n    for (auto i = 0u; i != n; ++i) { Hp.coeffRef(i, i) += prm.delta; }\n    for (auto i = 0u; i != nl + nu; ++i) { Hp.coeffRef(n + i, n + i) -= prm.delta; }\n    H.makeCompressed();\n    Hp.makeCompressed();\n  } else {\n    Hp.topLeftCorner(n, n) += Eigen::VectorX<Scalar>::Constant(n, prm.delta).asDiagonal();\n    Hp.bottomRightCorner(nl + nu, nl + nu) -=\n      Eigen::VectorX<Scalar>::Constant(nl + nu, prm.delta).asDiagonal();\n  }\n\n  Eigen::VectorX<Scalar> h(n + nl + nu);\n  h.head(n) = -c * sx.cwiseProduct(pbm.q);\n  for (auto i = 0u; i != nl; ++i) { h(n + i) = sy(LU_idx(i)) * pbm.l(LU_idx(i)); }\n  for (auto i = 0u; i != nu; ++i) { h(n + nl + i) = sy(LU_idx(nl + i)) * pbm.u(LU_idx(nl + i)); }\n\n  // ITERATIVE REFINEMENT\n\n  // factorize Hp\n  std::conditional_t<\n    sparse,\n    Eigen::SimplicialLDLT<decltype(H), Eigen::Upper>,\n    Eigen::LDLT<decltype(H), Eigen::Upper>>\n    ldlt(Hp);\n\n  if (ldlt.info()) { return false; }\n\n  Eigen::VectorX<Scalar> t_hat = Eigen::VectorX<Scalar>::Zero(n + nl + nu);\n  for (auto i = 0u; i != prm.polish_iter; ++i) {\n    t_hat += ldlt.solve(h - H.template selfadjointView<Eigen::Upper>() * t_hat);\n  }\n\n  // UPDATE SOLUTION\n\n  sol.primal = t_hat.template head<N>(n);\n  for (auto i = 0u; i < nl; ++i) { sol.dual(LU_idx(i)) = t_hat(n + i); }\n  for (auto i = 0u; i < nu; ++i) { sol.dual(LU_idx(nl + i)) = t_hat(n + nl + i); }\n\n  return true;\n}\n\n/**\n * @brief Copy-able wrapper around Eigen LDLT types.\n */\ntemplate<typename LDLTt>\nstruct LDLTWrapper\n{\n  bool first{true};  // true if ldlt object needs factorization\n  LDLTt ldlt{};\n\n  LDLTWrapper() = default;\n  LDLTWrapper(const LDLTWrapper &) : first{true}, ldlt{} {}\n  LDLTWrapper(LDLTWrapper &&) : first{true}, ldlt{} {}\n  LDLTWrapper & operator=(const LDLTWrapper &)\n  {\n    first = true;\n    return *this;\n  }\n  LDLTWrapper & operator=(LDLTWrapper &)\n  {\n    first = true;\n    return *this;\n  }\n  ~LDLTWrapper() = default;\n};\n\n}  // namespace detail\n\n/**\n * @brief Solver for quadratic programs\n *\n * Use this class to efficiently solve many QPs with the same problem structure.\n *\n * For one-off QPs, see solve_qp().\n */\ntemplate<typename Pbm>\nclass QPSolver\n{\n  using AmatT                  = decltype(Pbm::A);\n  using Scalar                 = typename AmatT::Scalar;\n  static constexpr bool sparse = std::is_base_of_v<Eigen::SparseMatrixBase<AmatT>, AmatT>;\n\n  // static sizes\n  static constexpr Eigen::Index M = AmatT::RowsAtCompileTime;\n  static constexpr Eigen::Index N = AmatT::ColsAtCompileTime;\n  static constexpr Eigen::Index K = (N == -1 || M == -1) ? Eigen::Index(-1) : N + M;\n\n  // typedefs\n  using Rn = Eigen::Vector<Scalar, N>;\n  using Rm = Eigen::Vector<Scalar, M>;\n  using Rk = Eigen::Vector<Scalar, K>;\n  using Ht = std::conditional_t<sparse, Eigen::SparseMatrix<Scalar>, Eigen::Matrix<Scalar, K, K>>;\n  using LDLTt = std::\n    conditional_t<sparse, Eigen::SimplicialLDLT<Ht, Eigen::Upper>, Eigen::LDLT<Ht, Eigen::Upper>>;\n\n  static inline const Scalar inf = std::numeric_limits<Scalar>::infinity();\n\npublic:\n  /**\n   * @brief Default constructor.\n   */\n  QPSolver(const QPSolverParams & prm = {}) : prm_(prm) {}\n\n  /**\n   * @brief Construct and allocate working memory.\n   *\n   * @param pbm template problem.\n   *\n   * Memory is allocated for solving problems with same structure as pbm.\n   */\n  QPSolver(const Pbm & pbm, const QPSolverParams & prm = {}) : prm_(prm) { analyze(pbm); }\n\n  /// @brief Default copy constructor\n  QPSolver(const QPSolver &) = default;\n  /// @brief Default move constructor\n  QPSolver(QPSolver &&) = default;\n  /// @brief Default copy assignment\n  QPSolver & operator=(const QPSolver &) = default;\n  /// @brief Default move assignment\n  QPSolver & operator=(QPSolver &&) = default;\n\n  /**\n   * @brief Access most recent QP solution.\n   */\n  const QPSolution<M, N, Scalar> & sol() const { return sol_; }\n\n  /**\n   * @brief Prepare for solving problems.\n   */\n  void analyze(const Pbm & pbm)\n  {\n    const Eigen::Index n = pbm.A.cols(), m = pbm.A.rows(), k = n + m;\n\n    // solution\n    sol_.primal.setZero(n);\n    sol_.dual.setZero(m);\n\n    // scaling variables and working memory\n    c_ = 1;\n    sx_.setOnes(n);\n    sy_.setOnes(m);\n    sx_inc_.setZero(n);\n    sy_inc_.setZero(m);\n\n    // solve working memory\n    z_.resize(m);\n    z_next_.resize(m);\n    rho_.resize(m);\n    p_.resize(k);\n    pt_.resize(k);\n\n    // stopping working memory\n    x_us_.resize(n);\n    dx_us_.resize(n);\n    y_us_.resize(m);\n    dy_us_.resize(m);\n    z_us_.resize(m);\n    Px_.resize(n);\n    Aty_.resize(n);\n    Ax_.resize(m);\n\n    // preallocate nonzeros in H\n    H_.setZero();\n    H_.resize(k, k);\n    if constexpr (sparse) {\n      Eigen::VectorXi nnz(k);\n      for (auto i = 0u; i < n; ++i) {\n        nnz(i) = pbm.P.outerIndexPtr()[i + 1] - pbm.P.outerIndexPtr()[i] + 1;\n      }\n      for (auto i = 0u; i < m; ++i) {\n        nnz(n + i) = pbm.A.outerIndexPtr()[i + 1] - pbm.A.outerIndexPtr()[i] + 1;\n      }\n      H_.reserve(nnz);\n    }\n  }\n\n  /**\n   * @brief Solve quadratic program.\n   */\n  const QPSolution<M, N, Scalar> & solve(\n    const Pbm & pbm,\n    std::optional<std::reference_wrapper<const QPSolution<M, N, Scalar>>> warmstart = {})\n  {\n    // update problem scaling\n    if (prm_.scaling) { scale(pbm); }\n\n    // dynamic sizes\n    const Eigen::Index n = pbm.A.cols(), m = pbm.A.rows();\n\n    // cast parameters to scalar type\n    const Scalar rho_bar    = static_cast<Scalar>(prm_.rho);\n    const Scalar alpha      = static_cast<Scalar>(prm_.alpha);\n    const Scalar alpha_comp = Scalar(1) - alpha;\n    const Scalar sigma      = static_cast<Scalar>(prm_.sigma);\n\n    // return code: when set algorithm is finished\n    std::optional<QPSolutionStatus> ret_code = std::nullopt;\n\n    for (auto i = 0u; i != m; ++i) {\n      if (pbm.l(i) == inf || pbm.u(i) == -inf || pbm.u(i) - pbm.l(i) < Scalar(0.)) {\n        ret_code = QPSolutionStatus::PrimalInfeasible;  // feasible set trivially empty\n      }\n\n      // set rho depending on constraint type\n      if (pbm.l(i) == -inf && pbm.u(i) == inf) {\n        rho_(i) = Scalar(1e-6);  // unbounded\n      } else if (sy_(i) * abs(pbm.l(i) - pbm.u(i)) < 1e-5) {\n        rho_(i) = Scalar(1e3) * rho_bar;  // equality\n      } else {\n        rho_(i) = rho_bar;  // inequality\n      }\n    }\n\n    const auto t0 = std::chrono::high_resolution_clock::now();\n\n    // fill square symmetric system matrix H = [P A'; A 0]\n    if constexpr (sparse) {\n      if (H_.isCompressed()) { H_.coeffs().setZero(); }\n\n      for (auto i = 0u; i < pbm.P.outerSize(); ++i) {\n        for (Eigen::InnerIterator it(pbm.P, i); it; ++it) {\n          if (it.col() >= it.row()) {\n            H_.coeffRef(it.row(), it.col()) = c_ * sx_(it.row()) * sx_(it.col()) * it.value();\n          }\n        }\n      }\n      block_add_identity(H_, 0, 0, n, sigma);\n      for (auto i = 0u; i < pbm.A.outerSize(); ++i) {\n        for (Eigen::InnerIterator it(pbm.A, i); it; ++it) {\n          H_.coeffRef(it.col(), n + it.row()) = sy_(it.row()) * sx_(it.col()) * it.value();\n        }\n      }\n      for (auto row = 0u; row < m; ++row) {\n        H_.coeffRef(n + row, n + row) = Scalar(-1) / rho_(row);\n      }\n\n      if (!H_.isCompressed()) { H_.makeCompressed(); }\n    } else {\n      H_.setZero();\n\n      H_.template topLeftCorner<N, N>(n, n) = c_ * sx_.asDiagonal() * pbm.P * sx_.asDiagonal();\n      H_.template topLeftCorner<N, N>(n, n) +=\n        Eigen::Vector<Scalar, N>::Constant(n, sigma).asDiagonal();\n      H_.template topRightCorner<N, M>(n, m) =\n        (sy_.asDiagonal() * pbm.A * sx_.asDiagonal()).transpose();\n      H_.template bottomRightCorner<M, M>(m, m) = (-rho_).cwiseInverse().asDiagonal();\n    }\n\n    const auto t_fill = std::chrono::high_resolution_clock::now();\n\n    if (prm_.verbose) {\n      using std::cout, std::left, std::setw, std::right;\n      // clang-format off\n      cout << \"========================= QP Solver =========================\" << '\\n';\n      cout << \"Solving \" << (sparse ? \"sparse\" : \"dense\") << \" QP with n=\" << n << \", m=\" << m << '\\n';\n      cout << setw(8)  << right << \"ITER\"\n           << setw(14) << right << \"OBJ\"\n           << setw(14) << right << \"PRI_RES\"\n           << setw(14) << right << \"DUA_RES\"\n           << setw(10) << right << \"TIME\" << '\\n';\n      // clang-format on\n    }\n\n    // factorize H\n    if constexpr (sparse) {\n      if (ldlt_.first) { ldlt_.ldlt.analyzePattern(H_); }\n      ldlt_.ldlt.factorize(H_);  // makes copy for permuted matrix..\n      ldlt_.first = false;\n    } else {\n      ldlt_.ldlt.compute(H_);\n    }\n\n    const auto t_factor = std::chrono::high_resolution_clock::now();\n\n    if (ldlt_.ldlt.info()) { ret_code = QPSolutionStatus::Unknown; }\n\n    // initialize solver variables\n    if (warmstart.has_value()) {\n      // warmstart variables must be scaled\n      sol_.primal  = sx_.cwiseInverse().cwiseProduct(warmstart.value().get().primal);\n      sol_.dual    = c_ * sy_.cwiseInverse().cwiseProduct(warmstart.value().get().dual);\n      z_.noalias() = sy_.asDiagonal() * pbm.A * warmstart.value().get().primal;\n    } else {\n      sol_.primal.setZero();\n      sol_.dual.setZero();\n      z_.setZero();\n    }\n\n    // main optimization loop\n    auto iter = 0u;\n    for (; (!prm_.max_iter || iter != prm_.max_iter.value()) && !ret_code; ++iter) {\n      p_.template segment<N>(0, n) = sigma * sol_.primal - c_ * sx_.asDiagonal() * pbm.q;\n      p_.template segment<M>(n, m) = z_ - rho_.cwiseInverse().cwiseProduct(sol_.dual);\n      if constexpr (sparse) {\n        // p_ = ldlt_.solve(p_);\n        // manual solve because ldlt_.solve() uses temporaries...\n        // Pinv L D L' P x = b  <==> x = Pinv * (L' \\ Dinv(L \\ (P * b)))\n        pt_.noalias() = ldlt_.ldlt.permutationP() * p_;\n        ldlt_.ldlt.matrixL().solveInPlace(pt_);\n        pt_.applyOnTheLeft(ldlt_.ldlt.vectorD().cwiseInverse().asDiagonal());\n        ldlt_.ldlt.matrixU().solveInPlace(pt_);\n        p_.noalias() = ldlt_.ldlt.permutationPinv() * pt_;\n      } else {\n        ldlt_.ldlt.solveInPlace(p_);\n      }\n\n      if (iter % prm_.stop_check_iter == 1) {\n        // termination checking requires difference, store old scaled values\n        dx_us_ = sol_.primal, dy_us_ = sol_.dual;\n      }\n\n      sol_.primal = alpha * p_.template segment<N>(0, n) + alpha_comp * sol_.primal;\n      z_next_     = (alpha * rho_.cwiseInverse().cwiseProduct(p_.template segment<M>(n, m))\n                 + alpha_comp * rho_.cwiseInverse().cwiseProduct(sol_.dual) + z_)\n                  .cwiseMax(sy_.cwiseProduct(pbm.l))\n                  .cwiseMin(sy_.cwiseProduct(pbm.u));\n      sol_.dual = alpha_comp * sol_.dual + alpha * p_.template segment<M>(n, m)\n                + rho_.cwiseProduct(z_) - rho_.cwiseProduct(z_next_);\n      std::swap(z_, z_next_);\n\n      if (iter % prm_.stop_check_iter == 1) {\n        // unscale solution\n        x_us_  = sx_.cwiseProduct(sol_.primal);\n        y_us_  = sy_.cwiseProduct(sol_.dual) / c_;\n        z_us_  = sy_.cwiseInverse().cwiseProduct(z_);\n        dx_us_ = sx_.cwiseProduct(sol_.primal - dx_us_);\n        dy_us_ = sy_.cwiseProduct(sol_.dual - dy_us_) / c_;\n\n        // check stopping criteria for unscaled problem and unscaled variables\n        ret_code = check_stopping(pbm);\n\n        if (prm_.verbose) {\n          using std::cout, std::setw, std::right, std::chrono::microseconds;\n          // clang-format off\n          cout << setw(7) << right << iter << \":\"\n            << std::scientific\n            << setw(14) << right << (0.5 * pbm.P * x_us_ + pbm.q).dot(x_us_)\n            << setw(14) << right << (pbm.A * x_us_ - z_us_).template lpNorm<Eigen::Infinity>()\n            << setw(14) << right << (pbm.P * x_us_ + pbm.q + pbm.A.transpose() * y_us_).template lpNorm<Eigen::Infinity>()\n            << setw(10) << right << duration_cast<microseconds>(std::chrono::high_resolution_clock::now() - t0).count()\n            << '\\n';\n          // clang-format on\n        }\n\n        // check for timeout\n        if (!ret_code) {\n          if (\n            prm_.max_time\n            && std::chrono::high_resolution_clock::now() > t0 + prm_.max_time.value()) {\n            ret_code = QPSolutionStatus::MaxTime;\n          }\n        }\n      }\n    }\n\n    const auto t_iter = std::chrono::high_resolution_clock::now();\n\n    // polish solution if optimal\n    if (ret_code.has_value() && ret_code.value() == QPSolutionStatus::Optimal && prm_.polish) {\n      if (detail::polish_qp(pbm, sol_, prm_, c_, sx_, sy_)) {\n        if (prm_.verbose) {\n          // unscale solution\n          x_us_ = sx_.cwiseProduct(sol_.primal);\n          y_us_ = sy_.cwiseProduct(sol_.dual) / c_;\n          z_us_ = sy_.cwiseInverse().cwiseProduct(z_);\n\n          using std::cout, std::setw, std::right, std::chrono::microseconds;\n          // clang-format off\n          cout << setw(8) << right << \"polish:\"\n            << std::scientific\n            << setw(14) << right << (0.5 * pbm.P * x_us_ + pbm.q).dot(x_us_)\n            << setw(14) << right << (pbm.A * x_us_ - z_us_).template lpNorm<Eigen::Infinity>()\n            << setw(14) << right << (pbm.P * x_us_ + pbm.q + pbm.A.transpose() * y_us_).template lpNorm<Eigen::Infinity>()\n            << setw(10) << right << duration_cast<microseconds>(std::chrono::high_resolution_clock::now() - t0).count()\n            << '\\n';\n          // clang-format on\n        }\n\n      } else {\n        if (prm_.verbose) { std::cout << \"Polish failed\" << '\\n'; }\n        sol_.code = QPSolutionStatus::PolishFailed;\n      }\n    }\n\n    const auto t_polish = std::chrono::high_resolution_clock::now();\n\n    // unscale solution\n    sol_.code      = ret_code.value_or(QPSolutionStatus::MaxIterations);\n    sol_.primal    = sx_.cwiseProduct(sol_.primal);\n    sol_.dual      = sy_.cwiseProduct(sol_.dual) / c_;\n    sol_.objective = sol_.primal.dot(0.5 * pbm.P * sol_.primal + pbm.q);\n    sol_.iter      = iter;\n\n    if (prm_.verbose) {\n      using std::cout, std::left, std::right, std::setw, std::chrono::microseconds;\n\n      // clang-format off\n      cout << \"QP solver summary:\" << '\\n';\n      cout << \"Result \" << static_cast<int>(sol_.code) << '\\n';\n\n      cout << setw(25) << left << \"Iterations\"        << setw(10) << right << iter - 1                                               << '\\n';\n      cout << setw(26) << left << \"Total time (µs)\"   << setw(10) << right << duration_cast<microseconds>(t_polish - t0).count()     << '\\n';\n      cout << setw(25) << left << \"  Matrix filling\"  << setw(10) << right << duration_cast<microseconds>(t_fill - t0).count()       << '\\n';\n      cout << setw(25) << left << \"  Factorization\"   << setw(10) << right << duration_cast<microseconds>(t_factor - t_fill).count() << '\\n';\n      cout << setw(25) << left << \"  Iteration\"       << setw(10) << right << duration_cast<microseconds>(t_iter - t_factor).count() << '\\n';\n      cout << setw(25) << left << \"  Polish\"          << setw(10) << right << duration_cast<microseconds>(t_polish - t_iter).count() << '\\n';\n      cout << \"=============================================================\" << '\\n';\n      // clang-format on\n    }\n\n    return sol_;\n  }\n\nprotected:\n  /**\n   * @brief Check stopping criteria for solver.\n   */\n  std::optional<QPSolutionStatus> check_stopping(const Pbm & pbm)\n  {\n    const Eigen::Index m = pbm.A.rows();\n\n    // norm function\n    static const auto norm = [](auto && t) -> Scalar {\n      return t.template lpNorm<Eigen::Infinity>();\n    };\n\n    // OPTIMALITY\n\n    // check primal\n    Ax_.noalias()        = pbm.A * x_us_;\n    const Scalar Ax_norm = norm(Ax_);\n    Ax_ -= z_us_;\n    if (norm(Ax_) <= prm_.eps_abs + prm_.eps_rel * std::max<Scalar>(Ax_norm, norm(z_us_))) {\n      // primal succeeded, check dual\n      Px_.noalias()           = pbm.P * x_us_;\n      Aty_.noalias()          = pbm.A.transpose() * y_us_;\n      const Scalar dual_scale = std::max<Scalar>({norm(Px_), norm(pbm.q), norm(Aty_)});\n      Px_ += pbm.q + Aty_;\n      if (norm(Px_) <= prm_.eps_abs + prm_.eps_rel * dual_scale) {\n        return QPSolutionStatus::Optimal;\n      }\n    }\n\n    // PRIMAL INFEASIBILITY\n\n    Aty_.noalias()        = pbm.A.transpose() * dy_us_;  // NOTE new value A' * dy\n    const Scalar Edy_norm = norm(dy_us_);\n\n    Scalar u_dyp_plus_l_dyn = Scalar(0);\n    for (auto i = 0u; i != m; ++i) {\n      if (pbm.u(i) != inf) {\n        u_dyp_plus_l_dyn += pbm.u(i) * std::max<Scalar>(Scalar(0), dy_us_(i));\n      } else if (dy_us_(i) > prm_.eps_primal_inf * Edy_norm) {\n        // contributes +inf to sum --> no certificate\n        u_dyp_plus_l_dyn = inf;\n        break;\n      }\n      if (pbm.l(i) != -inf) {\n        u_dyp_plus_l_dyn += pbm.l(i) * std::min<Scalar>(Scalar(0), dy_us_(i));\n      } else if (dy_us_(i) < -prm_.eps_primal_inf * Edy_norm) {\n        // contributes +inf to sum --> no certificate\n        u_dyp_plus_l_dyn = inf;\n        break;\n      }\n    }\n\n    if (std::max<Scalar>(norm(Aty_), u_dyp_plus_l_dyn) < prm_.eps_primal_inf * Edy_norm) {\n      return QPSolutionStatus::PrimalInfeasible;\n    }\n\n    // DUAL INFEASIBILITY\n\n    Ax_.noalias()        = pbm.A * dx_us_;  // note new value A * dx\n    const Scalar dx_norm = norm(dx_us_);\n    Px_.noalias()        = pbm.P * dx_us_;\n\n    bool dual_infeasible = (norm(Px_) <= prm_.eps_dual_inf * dx_norm)\n                        && (pbm.q.dot(dx_us_) <= prm_.eps_dual_inf * dx_norm);\n    for (auto i = 0u; i != m && dual_infeasible; ++i) {\n      if (pbm.u(i) == inf) {\n        dual_infeasible &= (Ax_(i) >= -prm_.eps_dual_inf * dx_norm);\n      } else if (pbm.l(i) == -inf) {\n        dual_infeasible &= (Ax_(i) <= prm_.eps_dual_inf * dx_norm);\n      } else {\n        dual_infeasible &= std::abs(Ax_(i)) < prm_.eps_dual_inf * dx_norm;\n      }\n    }\n\n    if (dual_infeasible) { return QPSolutionStatus::DualInfeasible; }\n\n    return std::nullopt;\n  }\n\n  /**\n   * @brief Re-scale QP.\n   *\n   * The scaled problem is defined as\n   *\n   * * \\f$ P_s = c S_x P S_x \\f$,\n   * * \\f$ q_s = c q S_x \\f$,\n   * * \\f$ A_s = S_y A S_x \\f$,\n   * * \\f$ l_s = S_y l \\f$,\n   * * \\f$ u_s = S_y u \\f$,\n   *\n   * where Sx = diag(sx), Sy = diag(sy).\n   *\n   * The relation between scaled variables and original variables are\n   *\n   * * Primal: \\f$ x_s = S_x^{-1} x \\f$,\n   * * Dual: \\f$ y_s = c S_y^{-1} y \\f$.\n   *\n   * The objective of the rescaling is the make the columns of\n   * \\f[\n   *   \\begin{bmatrix} \\bar P & \\bar A^T \\\\ \\bar A & 0 \\end{bmatrix}\n   * \\f]\n   * have similar \\f$ l_\\infty \\f$ norm, and similarly for the columns of\n   * \\f[\n   *  \\begin{bmatrix} \\bar P & \\bar q \\end{bmatrix}.\n   * \\f]\n   */\n  void scale(const Pbm & pbm)\n  {\n    sx_.setOnes();\n    sy_.setOnes();\n\n    sx_inc_.setZero();\n\n    // find \"norm\" of cost function\n    for (auto i = 0u; i < pbm.P.outerSize(); ++i) {\n      for (Eigen::InnerIterator it(pbm.P, i); it; ++it) {\n        sx_inc_(it.col()) = std::max(sx_inc_(it.col()), std::abs(it.value()));\n      }\n    }\n\n    // if there are \"zero cols\"\n    for (auto i = 0u; i != sx_.size(); ++i) {\n      if (sx_inc_(i) == 0) { sx_inc_(i) = 1; }\n    }\n\n    // scale cost function\n    c_ = Scalar(1) / std::max({1e-6, sx_inc_.mean(), pbm.q.template lpNorm<Eigen::Infinity>()});\n\n    int iter = 0;\n\n    // calculate inf-norm for every column of [Ps As' ; As 0]\n    do {\n      sx_inc_.setZero();\n      sy_inc_.setZero();\n      for (auto k = 0u; k < pbm.P.outerSize(); ++k) {\n        for (Eigen::InnerIterator it(pbm.P, k); it; ++it) {\n          // upper left block of H\n          sx_inc_(it.col()) = std::max({\n            sx_inc_(it.col()),\n            std::abs(c_ * sx_(it.row()) * sx_(it.col()) * it.value()),\n          });\n        }\n      }\n      for (auto k = 0u; k < pbm.A.outerSize(); ++k) {\n        for (Eigen::InnerIterator it(pbm.A, k); it; ++it) {\n          const Scalar Aij  = std::abs(sy_(it.row()) * sx_(it.col()) * it.value());\n          sx_inc_(it.col()) = std::max(sx_inc_(it.col()), Aij);  // bottom left block of H\n          sy_inc_(it.row()) = std::max(sy_inc_(it.row()), Aij);  // upper right block of H\n        }\n      }\n\n      // if there are \"zero cols\" we don't scale\n      for (auto i = 0u; i < sx_.size(); ++i) {\n        if (sx_inc_(i) == 0) { sx_inc_(i) = 1; }\n      }\n      for (auto i = 0u; i < sy_.size(); ++i) {\n        if (sy_inc_(i) == 0) { sy_inc_(i) = 1; }\n      }\n\n      sx_.applyOnTheLeft(sx_inc_.cwiseMax(1e-8).cwiseInverse().cwiseSqrt().asDiagonal());\n      sy_.applyOnTheLeft(sy_inc_.cwiseMax(1e-8).cwiseInverse().cwiseSqrt().asDiagonal());\n    } while (\n      iter++ < 10\n      && std::max((sx_inc_.array() - 1).abs().maxCoeff(), (sy_inc_.array() - 1).abs().maxCoeff())\n           > 0.1);\n  }\n\nprivate:\n  // solver parameters\n  QPSolverParams prm_{};\n\n  // solution\n  QPSolution<M, N, Scalar> sol_{};\n\n  // scaling variables and working memory\n  Scalar c_{0};\n  Rn sx_{}, sx_inc_{};\n  Rm sy_{}, sy_inc_{};\n\n  // solve working memory\n  Rm z_{}, z_next_{}, rho_{};\n  Rk p_{}, pt_{};\n\n  // stopping working memory\n  Rn x_us_{}, dx_us_{};\n  Rn Px_{}, Aty_{};\n  Rm Ax_{};\n  Rm y_us_{}, z_us_{}, dy_us_{};\n\n  // system matrix and decomposition\n  Ht H_{};\n  detail::LDLTWrapper<LDLTt> ldlt_{};\n};\n\n/**\n * @brief Solve a quadratic program using the operator splitting approach.\n *\n * @tparam Pbm problem type (QuadraticProgram or QuadraticProgramSparse)\n *\n * @param pbm problem formulation\n * @param prm solver options\n * @param warmstart provide initial guess for primal and dual variables\n * @return solution as QuasraticProgramSolution<M, N>\n *\n * @note dynamic problem sizes (`M == -1 || N == -1`) are supported\n *\n * This is a third-party implementation of the algorithm described in the following paper:\n * * Stellato, B., Banjac, G., Goulart, P. et al.\n * **OSQP: an operator splitting solver for quadratic programs.**\n * *Math. Prog. Comp.* 12, 637–672 (2020).\n * https://doi.org/10.1007/s12532-020-00179-2\n *\n * For the official C implementation, see https://osqp.org/.\n */\ntemplate<typename Pbm>\ndetail::qp_solution_t<Pbm> solve_qp(\n  const Pbm & pbm,\n  const QPSolverParams & prm,\n  std::optional<std::reference_wrapper<const detail::qp_solution_t<Pbm>>> warmstart = {})\n{\n  QPSolver solver(pbm, prm);\n  return solver.solve(pbm, warmstart);\n}\n\n}  // namespace smooth::feedback\n\n#endif  // SMOOTH__FEEDBACK__QP_SOLVER_HPP_\n", "meta": {"hexsha": "a9d49d63f1a8993f9e5945168e4e86b2daf857ba", "size": 28462, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/feedback/qp_solver.hpp", "max_stars_repo_name": "tgurriet/smooth_feedback", "max_stars_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smooth/feedback/qp_solver.hpp", "max_issues_repo_name": "tgurriet/smooth_feedback", "max_issues_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/feedback/qp_solver.hpp", "max_forks_repo_name": "tgurriet/smooth_feedback", "max_forks_repo_head_hexsha": "1f926cb4269741ddc09ba048af5bea5e0390a053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0454545455, "max_line_length": 141, "alphanum_fraction": 0.5849202445, "num_tokens": 8651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2245050818593929}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// This file is manually converted from PROJ4\n\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017, 2018.\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Geometry Library by Barend Gehrels (Geodan, Amsterdam)\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_ELL_SET_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_ELL_SET_HPP\n\n#include <string>\n#include <vector>\n\n#include <boost/geometry/formulas/eccentricity_sqr.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/srs/projections/impl/pj_ellps.hpp>\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\n#include <boost/geometry/srs/projections/proj4.hpp>\n\n\nnamespace boost { namespace geometry { namespace projections {\n\nnamespace detail {\n\n/* set ellipsoid parameters a and es */\ntemplate <typename T>\ninline T SIXTH() { return .1666666666666666667; } /* 1/6 */\ntemplate <typename T>\ninline T RA4() { return .04722222222222222222; } /* 17/360 */\ntemplate <typename T>\ninline T RA6() { return .02215608465608465608; } /* 67/3024 */\ntemplate <typename T>\ninline T RV4() { return .06944444444444444444; } /* 5/72 */\ntemplate <typename T>\ninline T RV6() { return .04243827160493827160; } /* 55/1296 */\n\n/* initialize geographic shape parameters */\ntemplate <typename BGParams, typename T>\ninline void pj_ell_set(BGParams const& /*bg_params*/, std::vector<pvalue<T> >& parameters, T &a, T &es)\n{\n    T b = 0.0;\n    T e = 0.0;\n    std::string name;\n\n    /* check for varying forms of ellipsoid input */\n    a = es = 0.;\n\n    /* R takes precedence */\n    if (pj_param(parameters, \"tR\").i)\n        a = pj_param(parameters, \"dR\").f;\n    else { /* probable elliptical figure */\n\n        /* check if ellps present and temporarily append its values to pl */\n        name = pj_param(parameters, \"sellps\").s;\n        if (! name.empty())\n        {\n            const int n = sizeof(pj_ellps) / sizeof(pj_ellps[0]);\n            int index = -1;\n            for (int i = 0; i < n && index == -1; i++)\n            {\n                if(pj_ellps[i].id == name)\n                {\n                    index = i;\n                }\n            }\n\n            if (index == -1) {\n                BOOST_THROW_EXCEPTION( projection_exception(-9) );\n            }\n\n            parameters.push_back(pj_mkparam<T>(pj_ellps[index].major));\n            parameters.push_back(pj_mkparam<T>(pj_ellps[index].ell));\n        }\n        a = pj_param(parameters, \"da\").f;\n        if (pj_param(parameters, \"tes\").i) /* eccentricity squared */\n            es = pj_param(parameters, \"des\").f;\n        else if (pj_param(parameters, \"te\").i) { /* eccentricity */\n            e = pj_param(parameters, \"de\").f;\n            es = e * e;\n        } else if (pj_param(parameters, \"trf\").i) { /* recip flattening */\n            es = pj_param(parameters, \"drf\").f;\n            if (!es) {\n                BOOST_THROW_EXCEPTION( projection_exception(-10) );\n            }\n            es = 1./ es;\n            es = es * (2. - es);\n        } else if (pj_param(parameters, \"tf\").i) { /* flattening */\n            es = pj_param(parameters, \"df\").f;\n            es = es * (2. - es);\n        } else if (pj_param(parameters, \"tb\").i) { /* minor axis */\n            b = pj_param(parameters, \"db\").f;\n            es = 1. - (b * b) / (a * a);\n        }     /* else es == 0. and sphere of radius a */\n        if (!b)\n            b = a * sqrt(1. - es);\n        /* following options turn ellipsoid into equivalent sphere */\n        if (pj_param(parameters, \"bR_A\").i) { /* sphere--area of ellipsoid */\n            a *= 1. - es * (SIXTH<T>() + es * (RA4<T>() + es * RA6<T>()));\n            es = 0.;\n        } else if (pj_param(parameters, \"bR_V\").i) { /* sphere--vol. of ellipsoid */\n            a *= 1. - es * (SIXTH<T>() + es * (RV4<T>() + es * RV6<T>()));\n            es = 0.;\n        } else if (pj_param(parameters, \"bR_a\").i) { /* sphere--arithmetic mean */\n            a = .5 * (a + b);\n            es = 0.;\n        } else if (pj_param(parameters, \"bR_g\").i) { /* sphere--geometric mean */\n            a = sqrt(a * b);\n            es = 0.;\n        } else if (pj_param(parameters, \"bR_h\").i) { /* sphere--harmonic mean */\n            a = 2. * a * b / (a + b);\n            es = 0.;\n        } else {\n            int i = pj_param(parameters, \"tR_lat_a\").i;\n            if (i || /* sphere--arith. */\n                pj_param(parameters, \"tR_lat_g\").i) { /* or geom. mean at latitude */\n                T tmp;\n\n                tmp = sin(pj_param(parameters, i ? \"rR_lat_a\" : \"rR_lat_g\").f);\n                if (geometry::math::abs(tmp) > geometry::math::half_pi<T>()) {\n                    BOOST_THROW_EXCEPTION( projection_exception(-11) );\n                }\n                tmp = 1. - es * tmp * tmp;\n                a *= i ? .5 * (1. - es + tmp) / ( tmp * sqrt(tmp)) :\n                    sqrt(1. - es) / tmp;\n                es = 0.;\n            }\n        }\n    }\n\n    /* some remaining checks */\n    if (es < 0.) {\n        BOOST_THROW_EXCEPTION( projection_exception(-12) );\n    }\n    if (a <= 0.) {\n        BOOST_THROW_EXCEPTION( projection_exception(-13) );\n    }\n}\n\ntemplate <BOOST_GEOMETRY_PROJECTIONS_DETAIL_TYPENAME_PX, typename T>\ninline void pj_ell_set(srs::static_proj4<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> const& bg_params,\n                       std::vector<pvalue<T> >& /*parameters*/, T &a, T &es)\n{\n    typedef srs::static_proj4<BOOST_GEOMETRY_PROJECTIONS_DETAIL_PX> static_parameters_type;\n    typedef typename srs::par4::detail::pick_ellps\n        <\n            static_parameters_type\n        > pick_ellps;\n\n    typename pick_ellps::model_type model = pick_ellps::model(bg_params);\n\n    a = geometry::get_radius<0>(model);\n    T b = geometry::get_radius<2>(model);\n    es = 0.;\n    if (a != b)\n    {\n        es = formula::eccentricity_sqr<T>(model);\n\n        // Ignore all other parameters passed in string, at least for now\n    }\n\n    /* some remaining checks */\n    if (es < 0.) {\n        BOOST_THROW_EXCEPTION( projection_exception(-12) );\n    }\n    if (a <= 0.) {\n        BOOST_THROW_EXCEPTION( projection_exception(-13) );\n    }\n}\n\n} // namespace detail\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PJ_ELL_SET_HPP\n", "meta": {"hexsha": "6f5f14b78046b3f6e7fe240f8e7bed3a4a4aac41", "size": 7886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/impl/pj_ell_set.hpp", "max_stars_repo_name": "ramcn/gemmx", "max_stars_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 354.0, "max_stars_repo_stars_event_min_datetime": "2018-08-13T18:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T10:37:20.000Z", "max_issues_repo_path": "boost_1_67_0/boost/geometry/srs/projections/impl/pj_ell_set.hpp", "max_issues_repo_name": "ramcn/gemmx", "max_issues_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "boost_1_67_0/boost/geometry/srs/projections/impl/pj_ell_set.hpp", "max_forks_repo_name": "ramcn/gemmx", "max_forks_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2018-11-15T12:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:39.000Z", "avg_line_length": 38.2815533981, "max_line_length": 103, "alphanum_fraction": 0.6016992138, "num_tokens": 2067, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22449605900427408}}
{"text": "#include <polyfem/SplineBasis2d.hpp>\n\n#include <polyfem/QuadraticBSpline2d.hpp>\n#include <polyfem/QuadQuadrature.hpp>\n#include <polyfem/MeshNodes.hpp>\n\n#include <polysolve/LinearSolver.hpp>\n#include <polyfem/FEBasis2d.hpp>\n#include <polyfem/Types.hpp>\n\n#include <polyfem/Common.hpp>\n#include <polyfem/auto_q_bases.hpp>\n\n#include <Eigen/Sparse>\n\n#include <cassert>\n#include <iostream>\n#include <vector>\n#include <array>\n#include <map>\n\n\n//TODO carefull with simplices\n\nnamespace polyfem\n{\n    using namespace polysolve;\n    using namespace Eigen;\n\n    namespace\n    {\n        typedef Matrix<std::vector<int>, 3, 3> SpaceMatrix;\n        typedef Matrix<RowVectorNd, 3, 3> NodeMatrix;\n\n\n        void print_local_space(const SpaceMatrix &space)\n        {\n            std::cout<<std::endl;\n            for(int j=2; j >=0; --j)\n            {\n                for(int i=0; i < 3; ++i)\n                {\n                    if(space(i, j).size() > 0){\n                        for(std::size_t l = 0; l < space(i, j).size(); ++l)\n                            std::cout<<space(i, j)[l]<<\",\";\n\n                        std::cout<<\"\\t\";\n                    }\n                    else\n                        std::cout<<\"x\\t\";\n                }\n                std::cout<<std::endl;\n            }\n        }\n\n        int node_id_from_edge_index(const Mesh2D &mesh, MeshNodes &mesh_nodes, const Navigation::Index &index)\n        {\n            const int face_id = mesh.switch_face(index).face;\n            if(face_id >= 0 && mesh.is_cube(face_id))\n                return mesh_nodes.node_id_from_face(face_id);\n\n            return mesh_nodes.node_id_from_edge(index.edge);\n        }\n\n        void explore_direction(const Navigation::Index &index, const Mesh2D &mesh, MeshNodes &mesh_nodes, const int x, const int y, const bool is_x, const bool invert, LocalBoundary &lb, SpaceMatrix &space, NodeMatrix &node, std::map<int, InterfaceData> &poly_edge_to_data)\n        {\n            int node_id = node_id_from_edge_index(mesh, mesh_nodes, index);\n            // bool real_boundary = mesh.node_id_from_edge_index(index, node_id);\n\n            assert(std::find(space(x, y).begin(), space(x, y).end(), node_id) == space(x, y).end());\n            space(x, y).push_back(node_id);\n            node(x, y) = mesh_nodes.node_position(node_id);\n            assert(node(x, y).size() == 2);\n\n            const int x1 =  is_x ? x : (invert? 2 : 0);\n            const int y1 = !is_x ? y : (invert? 2 : 0);\n\n            const int x2 =  is_x ? x : (invert? 0 : 2);\n            const int y2 = !is_x ? y : (invert? 0 : 2);\n\n            const bool is_boundary = mesh_nodes.is_boundary(node_id);\n            const bool is_interface = mesh_nodes.is_interface(node_id);\n\n            if(is_boundary)\n            {\n                lb.add_boundary_primitive(index.edge, FEBasis2d::quad_edge_local_nodes(2, mesh, index)[1]-4);\n                // lb.add_boundary_primitive(index.edge, FEBasis2d::quadr_quad_edge_local_nodes(mesh, index)[1]-4);\n                // bounday_nodes.push_back(node_id);\n            }\n            else if(is_interface)\n            {\n                InterfaceData &data = poly_edge_to_data[index.edge];\n                data.local_indices.push_back(y * 3 + x);\n            }\n            else\n            {\n                assert(!is_boundary && !is_interface);\n\n                Navigation::Index start_index = mesh.switch_face(index);\n                assert(start_index.vertex == index.vertex);\n                assert(start_index.face >= 0);\n\n                Navigation::Index edge1 = mesh.switch_edge(start_index);\n                node_id = node_id_from_edge_index(mesh, mesh_nodes, edge1);\n                // if(mesh_nodes.is_boundary(node_id))\n                    // bounday_nodes.push_back(node_id);\n\n                if(std::find(space(x1, y1).begin(), space(x1, y1).end(), node_id) == space(x1, y1).end())\n                {\n                    space(x1, y1).push_back(node_id);\n                    node(x1, y1) = mesh_nodes.node_position(node_id);\n                }\n\n                Navigation::Index edge2 = mesh.switch_edge(mesh.switch_vertex(start_index));\n                node_id = node_id_from_edge_index(mesh, mesh_nodes, edge2);\n                // if(mesh_nodes.is_boundary(node_id))\n                    // bounday_nodes.push_back(node_id);\n                if(std::find(space(x2, y2).begin(), space(x2, y2).end(), node_id) == space(x2, y2).end())\n                {\n                    space(x2, y2).push_back(node_id);\n                    node(x2, y2) = mesh_nodes.node_position(node_id);\n                    // node(x2, y2).push_back(mesh.node_from_edge_index(edge2));\n                }\n            }\n        }\n\n        void add_id_for_poly(const Navigation::Index &index, const int x1, const int y1, const int x2, const int y2, const SpaceMatrix &space, std::map<int, InterfaceData> &poly_edge_to_data)\n        {\n            auto it = poly_edge_to_data.find(index.edge);\n            if(it != poly_edge_to_data.end())\n            {\n                InterfaceData &data = it->second;\n\n                assert(space(x1, y1).size() == 1);\n                data.local_indices.push_back(y1 * 3 + x1);\n\n                assert(space(x2, y2).size() == 1);\n                data.local_indices.push_back(y2 * 3 + x2);\n            }\n        }\n\n        void build_local_space(const Mesh2D &mesh, MeshNodes &mesh_nodes, const int el_index,  SpaceMatrix &space, NodeMatrix &node, std::vector<LocalBoundary> &local_boundary, std::map<int, InterfaceData> &poly_edge_to_data)\n        {\n            assert(!mesh.is_volume());\n\n            Navigation::Index index;\n            // space.setConstant(-1);\n\n            const int el_node_id = mesh_nodes.node_id_from_face(el_index);\n            space(1, 1).push_back(el_node_id);\n            node(1, 1) = mesh_nodes.node_position(el_node_id);\n            // (mesh.node_from_face(el_index));\n\n            LocalBoundary lb(el_index, BoundaryType::QuadLine);\n\n            //////////////////////////////////////////\n            index = mesh.get_index_from_face(el_index);\n            explore_direction(index, mesh, mesh_nodes, 1, 0, false, false, lb, space, node, poly_edge_to_data);\n\n            //////////////////////////////////////////\n            index = mesh.next_around_face(index);\n            explore_direction(index, mesh, mesh_nodes, 2, 1, true, false, lb, space, node, poly_edge_to_data);\n\n            //////////////////////////////////////////\n            index = mesh.next_around_face(index);\n            explore_direction(index, mesh, mesh_nodes, 1, 2, false, true, lb, space, node, poly_edge_to_data);\n\n            //////////////////////////////////////////\n            index = mesh.next_around_face(index);\n            explore_direction(index, mesh, mesh_nodes, 0, 1, true, true, lb, space, node, poly_edge_to_data);\n\n            //////////////////////////////////////////\n            if(mesh_nodes.is_boundary_or_interface(space(1, 2).front()) && mesh_nodes.is_boundary_or_interface(space(2, 1).front()))\n            {\n                assert(space(2,2).empty());\n\n                Navigation::Index start_index = mesh.get_index_from_face(el_index);\n                start_index = mesh.next_around_face(start_index);\n                start_index = mesh.next_around_face(start_index);\n\n                const int node_id = mesh_nodes.node_id_from_vertex(start_index.vertex);\n                // mesh.vertex_node_id(start_index.vertex);\n                space(2,2).push_back(node_id);\n                node(2,2) = mesh_nodes.node_position(node_id);\n                // node(2,2).push_back(mesh.node_from_vertex(start_index.vertex));\n\n                // bounday_nodes.push_back(node_id);\n            }\n\n            if(mesh_nodes.is_boundary_or_interface(space(1, 0).front()) && mesh_nodes.is_boundary_or_interface(space(2, 1).front()))\n            {\n                assert(space(2,0).empty());\n\n                Navigation::Index start_index = mesh.get_index_from_face(el_index);\n                start_index = mesh.next_around_face(start_index);\n\n                const int node_id = mesh_nodes.node_id_from_vertex(start_index.vertex);\n                // mesh.vertex_node_id(start_index.vertex);\n                space(2,0).push_back(node_id);\n                node(2,0) = mesh_nodes.node_position(node_id);\n                // .push_back(mesh.node_from_vertex(start_index.vertex));\n\n                // bounday_nodes.push_back(node_id);\n            }\n\n            if(mesh_nodes.is_boundary_or_interface(space(1, 2).front()) && mesh_nodes.is_boundary_or_interface(space(0, 1).front()))\n            {\n                assert(space(0,2).empty());\n\n                Navigation::Index start_index = mesh.get_index_from_face(el_index);\n                start_index = mesh.next_around_face(start_index);\n                start_index = mesh.next_around_face(start_index);\n                start_index = mesh.next_around_face(start_index);\n\n                // const int node_id = mesh.vertex_node_id(start_index.vertex);\n                const int node_id = mesh_nodes.node_id_from_vertex(start_index.vertex);\n                space(0,2).push_back(node_id);\n                node(0,2) = mesh_nodes.node_position(node_id);\n                // .push_back(mesh.node_from_vertex(start_index.vertex));\n\n                // bounday_nodes.push_back(node_id);\n            }\n\n            if(mesh_nodes.is_boundary_or_interface(space(1, 0).front()) && mesh_nodes.is_boundary_or_interface(space(0, 1).front()))\n            {\n                Navigation::Index start_index = mesh.get_index_from_face(el_index);\n\n                // const int node_id = mesh.vertex_node_id(start_index.vertex);\n                const int node_id = mesh_nodes.node_id_from_vertex(start_index.vertex);\n                space(0,0).push_back(node_id);\n                node(0,0) = mesh_nodes.node_position(node_id);\n                //.push_back(mesh.node_from_vertex(start_index.vertex));\n\n                // bounday_nodes.push_back(node_id);\n            }\n\n            // std::cout<<std::endl;\n            // print_local_space(space);\n\n\n\n\n            ////////////////////////////////////////////////////////////////////////\n            index = mesh.get_index_from_face(el_index);\n            add_id_for_poly(index, 0, 0, 2, 0, space, poly_edge_to_data);\n\n            index = mesh.next_around_face(index);\n            add_id_for_poly(index, 2, 0, 2, 2, space, poly_edge_to_data);\n\n            index = mesh.next_around_face(index);\n            add_id_for_poly(index, 2, 2, 0, 2, space, poly_edge_to_data);\n\n            index = mesh.next_around_face(index);\n            add_id_for_poly(index, 0, 2, 0, 0, space, poly_edge_to_data);\n\n            if(!lb.empty())\n                local_boundary.emplace_back(lb);\n        }\n\n        void setup_knots_vectors(MeshNodes &mesh_nodes, const SpaceMatrix &space, std::array<std::array<double, 4>, 3> &h_knots, std::array<std::array<double, 4>, 3> &v_knots)\n        {\n            //left and right neigh are absent\n            if(mesh_nodes.is_boundary_or_interface(space(0,1).front()) && mesh_nodes.is_boundary_or_interface(space(2,1).front()))\n            {\n                h_knots[0] = {{0, 0, 0, 1}};\n                h_knots[1] = {{0, 0, 1, 1}};\n                h_knots[2] = {{0, 1, 1, 1}};\n            }\n            //left neigh is absent\n            else if(mesh_nodes.is_boundary_or_interface(space(0,1).front()))\n            {\n                h_knots[0] = {{0, 0, 0, 1}};\n                h_knots[1] = {{0, 0, 1, 2}};\n                h_knots[2] = {{0, 1, 2, 3}};\n            }\n            //right neigh is absent\n            else if(mesh_nodes.is_boundary_or_interface(space(2,1).front()))\n            {\n                h_knots[0] = {{-2, -1, 0, 1}};\n                h_knots[1] = {{-1, 0, 1, 1}};\n                h_knots[2] = {{0, 1, 1, 1}};\n            }\n            else\n            {\n                h_knots[0] = {{-2, -1, 0, 1}};\n                h_knots[1] = {{-1, 0, 1, 2}};\n                h_knots[2] = {{0, 1, 2, 3}};\n            }\n\n\n            //top and bottom neigh are absent\n            if(mesh_nodes.is_boundary_or_interface(space(1,0).front()) && mesh_nodes.is_boundary_or_interface(space(1,2).front()))\n            {\n                v_knots[0] = {{0, 0, 0, 1}};\n                v_knots[1] = {{0, 0, 1, 1}};\n                v_knots[2] = {{0, 1, 1, 1}};\n            }\n            //bottom neigh is absent\n            else if(mesh_nodes.is_boundary_or_interface(space(1,0).front()))\n            {\n                v_knots[0] = {{0, 0, 0, 1}};\n                v_knots[1] = {{0, 0, 1, 2}};\n                v_knots[2] = {{0, 1, 2, 3}};\n            }\n            //top neigh is absent\n            else if(mesh_nodes.is_boundary_or_interface(space(1,2).front()))\n            {\n                v_knots[0] = {{-2, -1, 0, 1}};\n                v_knots[1] = {{-1, 0, 1, 1}};\n                v_knots[2] = {{0, 1, 1, 1}};\n            }\n            else\n            {\n                v_knots[0] = {{-2, -1, 0, 1}};\n                v_knots[1] = {{-1, 0, 1, 2}};\n                v_knots[2] = {{0, 1, 2, 3}};\n            }\n        }\n\n        void basis_for_regular_quad(const SpaceMatrix &space, const NodeMatrix &loc_nodes, const std::array<std::array<double, 4>, 3> &h_knots, const std::array<std::array<double, 4>, 3> &v_knots, ElementBases &b)\n        {\n            for(int y = 0; y < 3; ++y)\n            {\n                for(int x = 0; x < 3; ++x)\n                {\n                    if(space(x,y).size() == 1)\n                    {\n                        const int global_index = space(x, y).front();\n                        const Eigen::MatrixXd &node = loc_nodes(x,y);\n                        assert(node.size() == 2);\n\n                        const int local_index = y*3 + x;\n                        b.bases[local_index].init(2, global_index, local_index, node);\n\n                        const QuadraticBSpline2d spline(h_knots[x], v_knots[y]);\n                        b.bases[local_index].set_basis([spline](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { spline.interpolate(uv, val); });\n                        b.bases[local_index].set_grad( [spline](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { spline.derivative(uv, val); });\n                    }\n                }\n            }\n        }\n\n        void basis_for_irregulard_quad(const int el_id, const Mesh2D &mesh, MeshNodes &mesh_nodes, const SpaceMatrix &space, const NodeMatrix &loc_nodes, const std::array<std::array<double, 4>, 3> &h_knots, const std::array<std::array<double, 4>, 3> &v_knots, ElementBases &b)\n        {\n            for(int y = 0; y < 3; ++y)\n            {\n                for(int x = 0; x < 3; ++x)\n                {\n                    if(space(x,y).size() > 1)\n                    {\n                        const int mpx = 1;\n                        const int mpy = y;\n\n                        const int mmx = x;\n                        const int mmy = 1;\n\n                        std::vector<int> other_indices;\n                        const auto &center = b.bases[1*3 + 1].global().front();\n\n                        const auto &el1 = b.bases[mpy*3 + mpx].global().front();\n                        const auto &el2 = b.bases[mmy*3 + mmx].global().front();\n\n\n                        Navigation::Index start_index = mesh.get_index_from_face(el_id);\n                        bool found = false;\n                        for(int i =0; i < 4; ++i)\n                        {\n                            other_indices.clear();\n                            int n_neighs = 0;\n                            Navigation::Index index = start_index;\n                            do\n                            {\n                                const int f_index = mesh_nodes.node_id_from_face(index.face);\n                                if(f_index != el1.index && f_index != el2.index && f_index != center.index)\n                                    other_indices.push_back(f_index);\n\n                                ++n_neighs;\n                                index = mesh.next_around_vertex(index);\n                            }\n                            while(index.face != start_index.face);\n                            if(n_neighs != 4){\n                                found = true;\n                                break;\n                            }\n\n                            start_index = mesh.next_around_face(start_index);\n                        }\n                        assert(found);\n\n\n                        const int local_index = y*3 + x;\n                        auto &base = b.bases[local_index];\n\n                        const int k = int(other_indices.size()) + 3;\n\n\n                        base.global().resize(k);\n\n                        base.global()[0].index = center.index;\n                        base.global()[0].val = (4. - k) / k;\n                        base.global()[0].node = center.node;\n\n                        base.global()[1].index = el1.index;\n                        base.global()[1].val = (4. - k) / k;\n                        base.global()[1].node = el1.node;\n\n                        base.global()[2].index = el2.index;\n                        base.global()[2].val = (4. - k) / k;\n                        base.global()[2].node = el2.node;\n\n\n                        for(std::size_t n = 0; n < other_indices.size(); ++n)\n                        {\n                            base.global()[3+n].index = other_indices[n];\n                            base.global()[3+n].val = 4./k;\n                            base.global()[3+n].node = mesh_nodes.node_position(other_indices[n]);\n                        }\n\n\n                        const QuadraticBSpline2d spline(h_knots[x], v_knots[y]);\n                        b.bases[local_index].set_basis([spline](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { spline.interpolate(uv, val); });\n                        b.bases[local_index].set_grad( [spline](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { spline.derivative(uv, val); });\n                    }\n                }\n            }\n        }\n\n        void create_q2_nodes(const Mesh2D &mesh, const int el_index, std::set<int> &vertex_id, std::set<int> &edge_id, ElementBases &b, std::vector<LocalBoundary> &local_boundary, int &n_bases)\n        {\n            b.bases.resize(9);\n\n            LocalBoundary lb(el_index, BoundaryType::QuadLine);\n\n            Navigation::Index index = mesh.get_index_from_face(el_index);\n            for (int j = 0; j < 4; ++j)\n            {\n                int current_vertex_node_id = -1;\n                int current_edge_node_id = -1;\n                Eigen::Matrix<double, 1, 2> current_edge_node;\n                Eigen::MatrixXd current_vertex_node;\n\n                // auto e2l = FEBasis2d::quadr_quad_edge_local_nodes(mesh, index);\n                auto e2l = FEBasis2d::quad_edge_local_nodes(2, mesh, index);\n\n                int vertex_basis_id = e2l[0];\n                int edge_basis_id = e2l[1];\n\n                const int opposite_face = mesh.switch_face(index).face;\n\n                //if the edge/vertex is boundary the it is a Q2 edge\n                bool is_vertex_q2 = true;\n                bool is_vertex_boundary = false;\n\n                Navigation::Index vindex=index;\n\n                do\n                {\n                    if(vindex.face < 0)\n                    {\n                        is_vertex_boundary = true;\n                        break;\n                    }\n                    if(mesh.is_spline_compatible(vindex.face))\n                    {\n                        is_vertex_q2 = false;\n                        break;\n                    }\n                    vindex = mesh.next_around_vertex(vindex);\n                }\n                while(vindex.edge != index.edge);\n\n                if(is_vertex_q2)\n                {\n                    vindex = mesh.switch_face(index);\n                    do\n                    {\n                        if(vindex.face < 0)\n                        {\n                            is_vertex_boundary = true;\n                            break;\n                        }\n\n                        if(mesh.is_spline_compatible(vindex.face))\n                        {\n                            is_vertex_q2 = false;\n                            break;\n                        }\n                        vindex = mesh.next_around_vertex(vindex);\n                    }\n                    while(vindex.edge != index.edge);\n                }\n\n                const bool is_edge_q2 = opposite_face < 0 || !mesh.is_spline_compatible(opposite_face);\n\n                if (is_edge_q2)\n                {\n                    const bool is_new_edge = edge_id.insert(index.edge).second;\n\n                    if(is_new_edge)\n                    {\n                        current_edge_node_id = n_bases++;\n                        current_edge_node = mesh.edge_barycenter(index.edge);\n\n                        if(opposite_face < 0)\n                        {\n                            // bounday_nodes.push_back(current_edge_node_id);\n                            lb.add_boundary_primitive(index.edge, edge_basis_id-4);\n                        }\n                    }\n                }\n\n                if(is_vertex_q2)\n                {\n                    assert(is_edge_q2);\n                    const bool is_new_vertex = vertex_id.insert(index.vertex).second;\n\n                    if(is_new_vertex)\n                    {\n                        current_vertex_node_id = n_bases++;\n                        current_vertex_node = mesh.point(index.vertex);\n\n                        // if(is_vertex_boundary)//mesh.is_vertex_boundary(index.vertex))\n                            // bounday_nodes.push_back(current_vertex_node_id);\n                    }\n                }\n\n                //init new Q2 nodes\n                if(current_vertex_node_id >= 0)\n                    b.bases[vertex_basis_id].init(2, current_vertex_node_id, vertex_basis_id, current_vertex_node);\n\n                if(current_edge_node_id >= 0)\n                    b.bases[edge_basis_id].init(2, current_edge_node_id, edge_basis_id, current_edge_node);\n\n                //set the basis functions\n                b.bases[vertex_basis_id].set_basis([vertex_basis_id](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { polyfem::autogen::q_basis_value_2d     (2, vertex_basis_id, uv, val); });\n                b.bases[vertex_basis_id].set_grad( [vertex_basis_id](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { polyfem::autogen::q_grad_basis_value_2d(2, vertex_basis_id, uv, val); });\n\n                b.bases[edge_basis_id].set_basis([edge_basis_id](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { polyfem::autogen::q_basis_value_2d     (2, edge_basis_id, uv, val); });\n                b.bases[edge_basis_id].set_grad( [edge_basis_id](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { polyfem::autogen::q_grad_basis_value_2d(2, edge_basis_id, uv, val); });\n\n                index = mesh.next_around_face(index);\n            }\n\n            //central node always present\n            const int face_basis_id = 8;\n            b.bases[face_basis_id].init(2, n_bases++, face_basis_id, mesh.face_barycenter(el_index));\n            b.bases[face_basis_id].set_basis([face_basis_id](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { polyfem::autogen::q_basis_value_2d     (2, face_basis_id, uv, val); });\n            b.bases[face_basis_id].set_grad( [face_basis_id](const Eigen::MatrixXd &uv, Eigen::MatrixXd &val) { polyfem::autogen::q_grad_basis_value_2d(2, face_basis_id, uv, val); });\n\n\n            if(!lb.empty())\n                local_boundary.emplace_back(lb);\n        }\n\n        void insert_into_global(const Local2Global &data, std::vector<Local2Global> &vec)\n        {\n            //ignore small weights\n            if(fabs(data.val) <1e-10 )\n                return;\n\n            bool found = false;\n\n            for(std::size_t i = 0; i < vec.size(); ++i)\n            {\n                if(vec[i].index == data.index)\n                {\n                    // std::cout<<vec[i].val <<\" \"<< data.val<<\" \"<<fabs(vec[i].val - data.val)<<std::endl;\n                    assert(fabs(vec[i].val - data.val) < 1e-10);\n                    assert((vec[i].node - data.node).norm() < 1e-10);\n                    found = true;\n                    break;\n                }\n            }\n\n            if(!found)\n                vec.push_back(data);\n        }\n\n        void assign_q2_weights(const Mesh2D &mesh, const int el_index, std::vector< ElementBases > &bases)\n        {\n            // Eigen::MatrixXd eval_p;\n            std::vector<AssemblyValues> eval_p;\n            Navigation::Index index = mesh.get_index_from_face(el_index);\n            ElementBases &b = bases[el_index];\n\n            for (int j = 0; j < 4; ++j)\n            {\n                const int opposite_face = mesh.switch_face(index).face;\n\n                if(opposite_face < 0 || !mesh.is_cube(opposite_face))\n                {\n                    index = mesh.next_around_face(index);\n                    continue;\n                }\n\n                // const auto param_p = FEBasis2d::quadr_quad_edge_local_nodes_coordinates(mesh, mesh.switch_face(index));\n                // const auto indices = FEBasis2d::quadr_quad_edge_local_nodes(mesh, index);\n\n                const auto indices = FEBasis2d::quad_edge_local_nodes(2, mesh, index);\n                Eigen::Matrix<double, 3, 2> param_p;\n\n                {\n                    Eigen::MatrixXd quad_loc_nodes; polyfem::autogen::q_nodes_2d(2, quad_loc_nodes);\n                    const auto opposite_indices = FEBasis2d::quad_edge_local_nodes(2, mesh, mesh.switch_face(index));\n                    for(int k = 0; k < 3; ++k)\n                        param_p.row(k) = quad_loc_nodes.row(opposite_indices[k]);\n                }\n\n                // std::cout<<param_p<<\"\\n---------\\n\"<<std::endl;\n\n                const int i0 = indices[0];\n                const int i1 = indices[1];\n                const int i2 = indices[2];\n\n                const auto &other_bases = bases[opposite_face];\n                other_bases.evaluate_bases(param_p, eval_p);\n\n                for(std::size_t i = 0; i < other_bases.bases.size(); ++i)\n                {\n                    const auto &other_b = other_bases.bases[i];\n\n                    if(other_b.global().empty()) continue;\n\n                    assert(eval_p[i].val.size() == 3);\n\n                    //basis i of element opposite face is zero on this elements\n                    if(eval_p[i].val.cwiseAbs().maxCoeff() <= 1e-10)\n                        continue;\n\n                    for(std::size_t k = 0; k < other_b.global().size(); ++k)\n                    {\n                        // auto glob0 = other_b.global()[k]; glob0.val *= eval_p(0,i);\n                        // auto glob1 = other_b.global()[k]; glob1.val *= eval_p(1,i);\n                        // auto glob2 = other_b.global()[k]; glob2.val *= eval_p(2,i);\n\n                        auto glob0 = other_b.global()[k]; glob0.val *= eval_p[i].val(0);\n                        auto glob1 = other_b.global()[k]; glob1.val *= eval_p[i].val(1);\n                        auto glob2 = other_b.global()[k]; glob2.val *= eval_p[i].val(2);\n\n                        insert_into_global(glob0, b.bases[i0].global());\n                        insert_into_global(glob1, b.bases[i1].global());\n                        insert_into_global(glob2, b.bases[i2].global());\n                    }\n                }\n\n                index = mesh.next_around_face(index);\n            }\n        }\n\n        void setup_data_for_polygons(const Mesh2D &mesh, const int el_index, const ElementBases &b, std::map<int, InterfaceData> &poly_edge_to_data)\n        {\n            Navigation::Index index = mesh.get_index_from_face(el_index);\n            for (int j = 0; j < 4; ++j)\n            {\n                const int opposite_face = mesh.switch_face(index).face;\n                const bool is_neigh_poly = opposite_face >= 0 && mesh.is_polytope(opposite_face);\n\n                if(is_neigh_poly)\n                {\n                    // auto e2l = FEBasis2d::quadr_quad_edge_local_nodes(mesh, index);\n                    auto e2l = FEBasis2d::quad_edge_local_nodes(2, mesh, index);\n                    const int vertex_basis_id = e2l[0];\n                    const int edge_basis_id = e2l[1];\n                    const int vertex_basis_id2 = e2l[2];\n\n                    InterfaceData &data = poly_edge_to_data[index.edge];\n\n                    data.local_indices.push_back(edge_basis_id);\n                    data.local_indices.push_back(vertex_basis_id);\n                    data.local_indices.push_back(vertex_basis_id2);\n                }\n\n                index = mesh.next_around_face(index);\n            }\n        }\n    }\n\n\n    int SplineBasis2d::build_bases(const Mesh2D &mesh, const int quadrature_order, std::vector< ElementBases > &bases, std::vector< LocalBoundary > &local_boundary, std::map<int, InterfaceData> &poly_edge_to_data)\n    {\n        using std::max;\n        assert(!mesh.is_volume());\n\n        MeshNodes mesh_nodes(mesh, true, true, 1, 1);\n\n        const int n_els = mesh.n_elements();\n        bases.resize(n_els);\n\n        local_boundary.clear();\n\n        // QuadQuadrature quad_quadrature;\n\n        for(int e = 0; e < n_els; ++e)\n        {\n            if(!mesh.is_spline_compatible(e))\n                continue;\n\n            SpaceMatrix space;\n            NodeMatrix loc_nodes;\n\n            // const int max_local_base =\n            build_local_space(mesh, mesh_nodes, e, space, loc_nodes, local_boundary, poly_edge_to_data);\n            // n_bases = max(n_bases, max_local_base);\n\n            ElementBases &b=bases[e];\n            // quad_quadrature.get_quadrature(quadrature_order, b.quadrature);\n            b.set_quadrature([quadrature_order](Quadrature &quad){\n                QuadQuadrature quad_quadrature;\n                quad_quadrature.get_quadrature(quadrature_order, quad);\n            });\n            b.bases.resize(9);\n\n            b.set_local_node_from_primitive_func([e](const int primitive_id, const Mesh &mesh)\n            {\n                Eigen::VectorXi res(3);\n                const auto &mesh2d = dynamic_cast<const Mesh2D &>(mesh);\n                auto index = mesh2d.get_index_from_face(e);\n                int le;\n                for(le = 0; le < mesh2d.n_face_vertices(e); ++le)\n                {\n                    if(index.edge == primitive_id)\n                        break;\n                    index = mesh2d.next_around_face(index);\n                }\n                assert(index.edge == primitive_id);\n\n                switch(le)\n                {\n                    case 3: res << (3*0 + 0), (3*1 + 0), (3*2 + 0); break;\n                    case 0: res << (3*0 + 0), (3*0 + 1), (3*0 + 2); break;\n                    case 1: res << (3*0 + 2), (3*1 + 2), (3*2 + 2); break;\n                    case 2: res << (3*2 + 0), (3*2 + 1), (3*2 + 2); break;\n                    default: assert(false);\n                }\n\n\n                return res;\n            });\n\n            std::array<std::array<double, 4>, 3> h_knots;\n            std::array<std::array<double, 4>, 3> v_knots;\n\n            setup_knots_vectors(mesh_nodes, space, h_knots, v_knots);\n\n            // print_local_space(space);\n\n            basis_for_regular_quad(space, loc_nodes, h_knots, v_knots, b);\n            basis_for_irregulard_quad(e, mesh, mesh_nodes, space, loc_nodes, h_knots, v_knots, b);\n        }\n\n        std::set<int> edge_id;\n        std::set<int> vertex_id;\n\n        int n_bases = mesh_nodes.n_nodes();\n\n        for(int e = 0; e < n_els; ++e)\n        {\n            if(mesh.is_polytope(e) || mesh.is_spline_compatible(e))\n                continue;\n\n            ElementBases &b=bases[e];\n            // quad_quadrature.get_quadrature(quadrature_order, b.quadrature);\n            b.set_quadrature([quadrature_order](Quadrature &quad){\n                QuadQuadrature quad_quadrature;\n                quad_quadrature.get_quadrature(quadrature_order, quad);\n            });\n\n            b.set_local_node_from_primitive_func([e](const int primitive_id, const Mesh &mesh)\n            {\n                const auto &mesh2d = dynamic_cast<const Mesh2D &>(mesh);\n                auto index = mesh2d.get_index_from_face(e);\n\n                for(int le = 0; le < mesh2d.n_face_vertices(e); ++le)\n                {\n                    if(index.edge == primitive_id)\n                        break;\n                    index = mesh2d.next_around_face(index);\n                }\n                assert(index.edge == primitive_id);\n\n                // const auto indices = FEBasis2d::quadr_quad_edge_local_nodes(mesh2d, index);\n                const auto indices = FEBasis2d::quad_edge_local_nodes(2, mesh2d, index);\n                Eigen::VectorXi res(indices.size());\n\n                for(size_t i = 0; i< indices.size(); ++i)\n                    res(i)=indices[i];\n\n                return res;\n            });\n\n            create_q2_nodes(mesh, e, vertex_id, edge_id, b, local_boundary, n_bases);\n        }\n\n\n        bool missing_bases = false;\n        do\n        {\n            missing_bases = false;\n            for(int e = 0; e < n_els; ++e)\n            {\n                if(mesh.is_polytope(e) || mesh.is_spline_compatible(e))\n                    continue;\n\n                auto &b=bases[e];\n                if(b.is_complete())\n                    continue;\n\n                assign_q2_weights(mesh, e, bases);\n\n                missing_bases = missing_bases || b.is_complete();\n            }\n        }\n        while(missing_bases);\n\n\n        for(int e = 0; e < n_els; ++e)\n        {\n            if(mesh.is_polytope(e) || mesh.is_spline_compatible(e))\n                continue;\n            const ElementBases &b=bases[e];\n            setup_data_for_polygons(mesh, e, b, poly_edge_to_data);\n        }\n\n        return n_bases;\n    }\n\n    void SplineBasis2d::fit_nodes(const Mesh2D &mesh, const int n_bases, std::vector< ElementBases > &gbases)\n    {\n        assert(false);\n        // const int dim = 2;\n        // const int n_constraints =  9;\n        // const int n_elements = mesh.n_elements();\n\n        // std::vector< Eigen::Triplet<double> > entries, entries_t;\n\n        // MeshNodes nodes(mesh, 1, 1, 0);\n        // // Eigen::MatrixXd tmp;\n        // std::vector<AssemblyValues> tmp_val;\n\n        // Eigen::MatrixXd node_rhs(n_constraints*n_elements, dim);\n        // Eigen::MatrixXd samples(n_constraints, dim);\n        // polyfem::autogen::q_nodes_2d(2, samples);\n        // // for(int i = 0; i < n_constraints; ++i)\n        // //     samples.row(i) = FEBasis2d::quadr_quad_local_node_coordinates(i);\n\n        // for(int i = 0; i < n_elements; ++i)\n        // {\n        //     auto &base = gbases[i];\n\n        //     if(!mesh.is_cube(i))\n        //         continue;\n\n        //     auto global_ids = FEBasis2d::quadr_quad_local_to_global(mesh, i);\n        //     assert(global_ids.size() == n_constraints);\n\n        //     for(int j = 0; j < n_constraints; ++j)\n        //     {\n        //         auto n_id = nodes.node_id_from_primitive(global_ids[j]);\n        //         auto n = nodes.node_position(n_id);\n        //         for(int d = 0; d < dim; ++d)\n        //             node_rhs(n_constraints*i + j, d) = n(d);\n        //     }\n\n        //     base.evaluate_bases(samples, tmp_val);\n        //     const auto &lbs = base.bases;\n\n        //     const int n_local_bases = int(lbs.size());\n        //     for(int j = 0; j < n_local_bases; ++j)\n        //     {\n        //         const Basis &b = lbs[j];\n        //         const auto &tmp = tmp_val[j].val;\n\n        //         for(std::size_t ii = 0; ii < b.global().size(); ++ii)\n        //         {\n        //             for (long k = 0; k < tmp.size(); ++k)\n        //             {\n        //                 entries.emplace_back(n_constraints*i + k, b.global()[ii].index, tmp(k)*b.global()[ii].val);\n        //                 entries_t.emplace_back(b.global()[ii].index, n_constraints*i + k, tmp(k)*b.global()[ii].val);\n        //             }\n        //         }\n        //     }\n        // }\n\n        // Eigen::MatrixXd new_nodes(n_bases, dim);\n\n        // {\n        //     StiffnessMatrix mat(n_constraints*n_elements, n_bases);\n        //     StiffnessMatrix mat_t(n_bases, n_constraints*n_elements);\n\n        //     mat.setFromTriplets(entries.begin(), entries.end());\n        //     mat_t.setFromTriplets(entries_t.begin(), entries_t.end());\n\n        //     StiffnessMatrix A = mat_t * mat;\n        //     Eigen::MatrixXd b = mat_t * node_rhs;\n\n        //     json params = {\n        //     {\"mtype\", -2}, // matrix type for Pardiso (2 = SPD)\n        //     // {\"max_iter\", 0}, // for iterative solvers\n        //     // {\"tolerance\", 1e-9}, // for iterative solvers\n        //     };\n        //     auto solver = LinearSolver::create(\"\", \"\");\n        //     solver->setParameters(params);\n        //     solver->analyzePattern(A);\n        //     solver->factorize(A);\n\n        //     for(int d = 0; d < dim; ++d)\n        //         solver->solve(b.col(d), new_nodes.col(d));\n        // }\n\n        // for(int i = 0; i < n_elements; ++i)\n        // {\n        //     auto &base = gbases[i];\n\n        //     if(!mesh.is_cube(i))\n        //         continue;\n\n        //     auto &lbs = base.bases;\n        //     const int n_local_bases = int(lbs.size());\n        //     for(int j = 0; j < n_local_bases; ++j)\n        //     {\n        //         Basis &b = lbs[j];\n\n        //         for(std::size_t ii = 0; ii < b.global().size(); ++ii)\n        //         {\n        //             // if(nodes.is_primitive_boundary(b.global()[ii].index))\n        //             //     continue;\n\n        //             for(int d = 0; d < dim; ++d)\n        //             {\n        //                 b.global()[ii].node(d) = new_nodes(b.global()[ii].index, d);\n        //             }\n        //         }\n        //     }\n        // }\n    }\n\n}\n", "meta": {"hexsha": "108ebda7b1cf894e29ce4cdf4355f3840c87b7e5", "size": 37992, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/basis/SplineBasis2d.cpp", "max_stars_repo_name": "danielepanozzo/polyfem", "max_stars_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 228.0, "max_stars_repo_stars_event_min_datetime": "2018-11-23T19:32:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:30:51.000Z", "max_issues_repo_path": "src/basis/SplineBasis2d.cpp", "max_issues_repo_name": "danielepanozzo/polyfem", "max_issues_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2019-03-11T22:44:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-16T14:50:35.000Z", "max_forks_repo_path": "src/basis/SplineBasis2d.cpp", "max_forks_repo_name": "danielepanozzo/polyfem", "max_forks_repo_head_hexsha": "34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 45.0, "max_forks_repo_forks_event_min_datetime": "2018-12-31T02:04:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T02:42:01.000Z", "avg_line_length": 40.5031982942, "max_line_length": 276, "alphanum_fraction": 0.4944461992, "num_tokens": 8879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803831, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.22436337237230386}}
{"text": "#pragma once\n\n#include <armadillo>\n\n#include \"heattransferstate.hpp\"\n\n/*!\n * \\brief The HeatTransferBase class is an abstract class, the base class for all\n * heat transfer implementations. It mostly just defines a stencil for the\n * evaluate() function and the HeatTransferState class.\n */\nclass HeatTransferBase\n{\npublic:\n    //! Have to declare virtual destructor to avoid compiler warnings.\n    //! Only declared here, to avoid the inline compiler-generated default destructor.\n    virtual ~HeatTransferBase();\n\n    // pure virtual method\n    // returns q [W/m2] = U*(gasTemperature - ambientTemperature)\n    /*!\n     * \\brief Evaluate heat transfer.\n     * \\param current Current heat transfer state.\n     * \\param timeStep Time step [s]\n     * \\param ambientTemperature Ambient temperature [K]\n     * \\param gasPressure Gas pressure [Pa]\n     * \\param gasTemperature Gas temperature [K]\n     * \\param gasReynoldsNumber Reynolds number of gas [-]\n     * \\param gasHeatCapacityConstantPressure Heat capacity (\\f$c_p\\f$) [J/kg K]\n     * \\param gasViscosity Gas dynamic viscosity [Pa s] = [kg/m*s]\n     * \\return HeatTransferState instance with heat flux and updated temperatures.\n     */\n    virtual HeatTransferState evaluate(\n            const HeatTransferState& current,\n            const double timeStep,\n            const double ambientTemperature,\n            const double gasPressure,\n            const double gasTemperature,\n            const double gasReynoldsNumber,\n            const double gasHeatCapacityConstantPressure,\n            const double gasViscosity) const = 0;\n\n    /*!\n     * \\brief Make instance of HeatTransferState from heat flux.\n     *\n     * This is meant to be overriden in more advanced heat transfer\n     * implementations that that use the optional temperature property.\n     *\n     * \\param heatFlux Heat flux [W/m2]\n     * \\return HeatTransferState instance.\n     */\n    virtual HeatTransferState makeState(const double heatFlux) const;\n\n    /*!\n     * \\brief Make instance of HeatTransferState from heat flux. Overload.\n     *\n     * This version just calls HeatTransferBase::makeState(const double), but more\n     * advanced implementations should initialize the temperature property from\n     * the two temperature arguments.\n     *\n     * \\param heatFlux Heat flux [W/m2]\n     * \\param ambientTemperature Ambient temperature [K]\n     * \\param gasTemperature Gas temperature [K]\n     * \\return HeatTransferState instance with temperature.\n     */\n    virtual HeatTransferState makeState(\n            const double heatFlux,\n            const double gasTemperature,\n            const double ambientTemperature) const;\n};\n", "meta": {"hexsha": "efefe264b1ba4751dec0b638448dfd481e8b0681", "size": 2662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/heattransfer/heattransferbase.hpp", "max_stars_repo_name": "kewin1983/transient-pipeline-flow", "max_stars_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-26T03:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T03:30:07.000Z", "max_issues_repo_path": "src/heattransfer/heattransferbase.hpp", "max_issues_repo_name": "kewin1983/transient-pipeline-flow", "max_issues_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/heattransfer/heattransferbase.hpp", "max_forks_repo_name": "kewin1983/transient-pipeline-flow", "max_forks_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4929577465, "max_line_length": 86, "alphanum_fraction": 0.688580015, "num_tokens": 561, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.22428679240835311}}
{"text": "#ifndef ATM_BRANCHING_SUBSTRINGS_HPP\n#define ATM_BRANCHING_SUBSTRINGS_HPP\n\n#include <cmath>\n#include <map>\n#include <vector>\n#include <boost/iterator/iterator_facade.hpp>\n#include <boost/range/begin.hpp>\n#include <boost/range/iterator.hpp>\n#include <boost/range/sub_range.hpp>\n#include <boost/range/value_type.hpp>\n#include \"sast/sast.hpp\"\n\n\nnamespace atm {\n\ntemplate <class RandomAccessRange, class Index>\nstruct branching_substrings {\n    using range_type = RandomAccessRange;\n    using char_type = typename boost::range_value<RandomAccessRange>::type;\n    using index_type = Index;\n\nprotected:\n    using sast_type = sast::sast<RandomAccessRange, index_type>;\n\npublic:\n    struct substr {\n        using iterator       = typename boost::range_iterator<RandomAccessRange>::type;\n        using const_iterator = typename boost::range_const_iterator<RandomAccessRange>::type;\n\n        index_type pos()           const { return i_->pos(); }\n        boost::sub_range<const std::vector<index_type>> allpos() const { return i_->allpos(); }\n        index_type length()        const { return i_->length(); }\n        index_type frequency()     const { return i_->frequency(); }\n        double     spurity()       const { return parent_->strict_purity(i_); }\n        double     lpurity()       const { return parent_->loose_purity(i_); }\n        double     luniversality() const { return parent_->left_universality(i_); }\n        double     runiversality() const { return parent_->right_universality(i_); }\n\n        iterator begin() { return boost::begin(parent_->input_) + pos(); }\n        iterator end()   { return boost::begin(parent_->input_) + pos() + length(); }\n        const_iterator begin() const { return boost::const_begin(parent_->input_) + pos(); }\n        const_iterator end()   const { return boost::const_begin(parent_->input_) + pos() + length(); }\n\n        substr(const branching_substrings* parent, typename sast_type::const_iterator i)\n            : parent_(parent), i_(i)\n        {}\n\n    private:\n        const branching_substrings* parent_;\n        typename sast_type::const_iterator i_;\n    };\n\nprivate:\n    template <class> struct substring_iterator;\n\npublic:\n    using iterator       = substring_iterator<substr>;\n    using const_iterator = substring_iterator<const substr>;\n\n    branching_substrings(const sast_type& sast)\n        : sast_(sast),\n          input_(sast_.input()),\n          count_(sast_.size(), 0), // initialize the count table with an \"undefined\" value.\n          recip_(sast_.size(), 0)  // 正数は計算結果、それ以外は未計算を表わす。\n    {}\n\n    iterator begin() { return iterator(this, sast_.begin()); }\n    iterator end()   { return iterator(this, sast_.end()); }\n    const_iterator begin() const { return const_iterator(this, sast_.begin()); }\n    const_iterator end()   const { return const_iterator(this, sast_.end()); }\n\nprivate:\n    template <class Value>\n    struct substring_iterator\n        : public boost::iterator_facade<\n            substring_iterator<Value>,\n            Value,\n            boost::random_access_traversal_tag,\n            Value,\n            int>\n    {\n        substring_iterator()\n            : parent_(0), i_()\n        {}\n\n        substring_iterator(const branching_substrings* parent, typename sast_type::const_iterator i)\n            : parent_(parent), i_(i)\n        {}\n\n        template <class OtherValue>\n        substring_iterator(substring_iterator<OtherValue> const& other)\n            : parent_(other.parent_), i_(other.i_)\n        {}\n\n    private:\n        friend class boost::iterator_core_access;\n        template <class> friend struct substring_iterator;\n\n        void increment() { ++i_; }\n\n        void decrement() { --i_; }\n\n        void advance(int n) { i_ += n; }\n\n        int distance_to(const substring_iterator<Value>& other) const { return other.i_ - this->i_; }\n\n        template <class OtherValue>\n        bool equal(const substring_iterator<OtherValue>& other) const {\n            return this->parent_ == other.parent_ && this->i_ == other.i_;\n        }\n\n        Value dereference() const {\n            return substr(parent_, i_);\n        }\n\n        const branching_substrings* parent_;\n        typename sast_type::const_iterator i_;\n    };\n\nprotected:\n    uint64_t get_count(typename sast_type::const_iterator n) const {\n        const int i = n - sast_.begin();\n\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列substrを扱う。\n        // substrと同じ出現回数のsub-substrの数count[i]を数える。\n        if (count_[i] > 0) {\n            return count_[i];\n        }\n        else {\n            const auto freq_substr = n->frequency();\n\n            // substrと同じ出現回数のsub-substrを数える。\n            uint64_t count = 0;\n            {\n                // substrの末尾を0文字以上削って得られるsub-substrについて考える。\n                // ノードiに対応する部分文字列をsubstr[i]とすると、substr[i]の末尾\n                // を削って得られる部分文字列の内で、substr[i]と同じ頻度をもつもの\n                // はsuffix tree上ではノードiにまとめられている\n                // （分岐が無い <=> 頻度が同じ）。\n\n                // ノードiの親ノードjを見つける。\n                const auto p = n.parent();\n\n                // substrの末尾を0文字以上削って得られるsub-substrの内で、出現\n                // 回数がsubstrと同じものの数はd[i] - d[j]である。\n                count += n->length() - p->length();;\n            }\n            {\n                // substrの先頭を1文字以上削ったsub-substrを考える。\n                const auto m = n.suffix();\n                const auto freq_subsubstr = m->frequency();\n                if (freq_subsubstr == freq_substr) {\n                    count += get_count(m);\n                }\n            }\n\n            // memoize\n            count_[i] = count;\n            return count_[i];\n        }\n    }\n\n    double strict_purity(typename sast_type::const_iterator n) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列substrを扱う。\n        const auto len_substr  = n->length();\n\n        // substrと同じ出現回数のsub-substrを数える。\n        const uint64_t count = get_count(n);\n\n        // strict purity of substr\n        const uint64_t num_subsubstrs = static_cast<uint64_t>(1 + len_substr) * len_substr / 2;\n        const double spurity = static_cast<double>(count) / num_subsubstrs;\n\n        return spurity;\n    }\n\n    double get_reciprocal(typename sast_type::const_iterator n) const {\n        const int i = n - sast_.begin();\n\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列substrを扱う。\n        // substrの全部分文字列の頻度の逆数の総和recip[i]を求める。\n        if (recip_[i] > 0) {\n            return recip_[i];\n        }\n        else {\n            double recip = 0;\n            {\n                // substrの末尾を0文字以上削って得られるsub-substrについて考える。\n                for (auto m = n, p = n.parent(); m != sast_.end(); m = p, p = p.parent()) {\n                    const auto num_subsubstrs_of_same_frequency = m->length() - p->length();\n                    const auto freq_subsubstr = m->frequency();\n                    const double r = 1.0 / freq_subsubstr;\n                    recip += num_subsubstrs_of_same_frequency * r;\n                }\n            }\n            {\n                // substrの先頭を1文字以上削ったsub-substrを考える。\n                const auto m = n.suffix();\n                if (m != sast_.end()) {\n                    recip += get_reciprocal(m);\n                }\n            }\n\n            // memoize\n            recip_[i] = recip;\n            return recip_[i];\n        }\n    }\n\n    double loose_purity(typename sast_type::const_iterator n) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列substrを扱う。\n        const auto freq_substr = n->frequency();\n        const auto len_substr  = n->length();\n\n        const double rel = freq_substr * get_reciprocal(n);\n\n        // loose purity of substr\n        const uint64_t num_subsubstrs = static_cast<uint64_t>(1 + len_substr) * len_substr / 2;\n        const double lpurity = rel / num_subsubstrs;\n\n        return lpurity;\n    }\n\n    std::map<char_type, int> left_extensions(typename sast_type::const_iterator n) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列substrを扱う。\n\n        std::map<char_type, int> char_dist;\n        for (auto pos : n->allpos()) {\n            const auto& c = boost::const_begin(input_)[pos - 1];\n            char_dist[c] += 1;\n        }\n\n        return char_dist;\n    }\n\n    std::map<char_type, int> right_extensions(typename sast_type::const_iterator n) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列substrを扱う。\n        const auto len_substr = n->length();\n\n        std::map<char_type, int> char_dist;\n        for (auto pos : n->allpos()) {\n            const auto& c = boost::const_begin(input_)[pos + len_substr];\n            char_dist[c] += 1;\n        }\n\n        return char_dist;\n    }\n\n    double left_universality(typename sast_type::const_iterator n) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列substrを扱う。\n        const auto freq_substr = n->frequency();\n\n        std::map<char_type, int> char_dist = left_extensions(n);\n\n        double e = 0;\n        for (const auto& kv : char_dist) {\n            const double p = static_cast<double>(kv.second) / freq_substr;\n            e += -p * std::log(p);\n        }\n        const double u = 1 - std::exp(-e);\n\n        return u;\n    }\n\n    double right_universality(typename sast_type::const_iterator n) const {\n        // ここではノードi（iはpost-orderでの番号）に対応する部分文字列substrを扱う。\n        const auto freq_substr = n->frequency();\n\n        std::map<char_type, int> char_dist = right_extensions(n);\n\n        double e = 0;\n        for (const auto& kv : char_dist) {\n            const double p = static_cast<double>(kv.second) / freq_substr;\n            e += -p * std::log(p);\n        }\n        const double u = 1 - std::exp(-e);\n\n        return u;\n    }\n\n    const sast_type& sast_;\n    const RandomAccessRange& input_;\n    mutable std::vector<uint64_t> count_;\n    mutable std::vector<double>   recip_;\n};\n\n}  // namespace atm\n\n\n#endif  /* ATM_BRANCHING_SUBSTRINGS_HPP */\n", "meta": {"hexsha": "8a6593352313d39605e078d8cbd60e7538eb01cb", "size": 9764, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/atm/branching_substrings.hpp", "max_stars_repo_name": "yuttie/atm", "max_stars_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/atm/branching_substrings.hpp", "max_issues_repo_name": "yuttie/atm", "max_issues_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/atm/branching_substrings.hpp", "max_forks_repo_name": "yuttie/atm", "max_forks_repo_head_hexsha": "b481620088e26153e5554ae6f6732efae4852eda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4383561644, "max_line_length": 103, "alphanum_fraction": 0.5909463335, "num_tokens": 2661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.22428679240835311}}
{"text": "#include \"LinearApproximation.hpp\"\n\n#include <boost/numeric/ublas/matrix.hpp>\n#include <boost/numeric/ublas/io.hpp>\n#include <boost/numeric/ublas/lu.hpp>\n\n\nLinearApproximation::LinearApproximation(const size_t t_numVars)\n  : m_numVars(t_numVars)\n{\n}\n\nLinearApproximation::~LinearApproximation()\n{\n}\n\ndouble LinearApproximation::average() const\n{\n  double sum = 0;\n  for (std::vector<std::vector<double> >::const_iterator lhsitr = m_values.begin();\n      lhsitr != m_values.end();\n      ++lhsitr)\n  {\n    sum += (*lhsitr)[m_numVars];\n  }\n  return sum / m_numVars;\n}\n\nLinearApproximation LinearApproximation::operator-(const LinearApproximation &t_rhs) const\n{\n  if (m_numVars != t_rhs.m_numVars)\n  {\n    throw std::runtime_error(\"Unable to subtract, different number of variables\");\n  }\n\n  LinearApproximation retval(m_numVars);\n\n  for (std::vector<std::vector<double> >::const_iterator lhsitr = m_values.begin();\n      lhsitr != m_values.end();\n      ++lhsitr)\n  {\n    for (std::vector<std::vector<double> >::const_iterator rhsitr = t_rhs.m_values.begin();\n        rhsitr != t_rhs.m_values.end();\n        ++rhsitr)\n    {\n      std::vector<double> vals(m_numVars, 0);\n\n      bool match = true;\n      for (size_t i = 0; i < m_numVars; ++i)\n      {\n        if ( (*lhsitr)[i] != (*rhsitr)[i] )\n        {\n          match = false;\n          break;\n        } else {\n          vals[i] = (*lhsitr)[i];\n        }\n      }\n\n      if (match)\n      {\n        double value = (*lhsitr)[m_numVars] - (*rhsitr)[m_numVars];\n        retval.addVals(vals, value);\n        break;\n      }\n    }\n  }\n\n  return retval;\n}\n\nvoid LinearApproximation::addVals(std::vector<double> t_vals, const double t_result)\n{\n  validateVariableSize(t_vals);\n\n  t_vals.push_back(t_result);\n\n  for (std::vector<std::vector<double> >::const_iterator lhsitr = m_values.begin();\n      lhsitr != m_values.end();\n      ++lhsitr)\n  {\n    bool match = true;\n    for (size_t i = 0; i < m_numVars; ++i)\n    {\n      if ( (*lhsitr)[i] != t_vals[i] )\n      {\n        match = false;\n        break;\n      }\n    }\n\n    if (match)\n    {\n      if ((*lhsitr)[m_numVars] != t_result)\n      {\n        throw std::runtime_error(\"Data already exists with a different result value\");\n      } else {\n        // it already exists\n        return;\n      }\n    }\n  }\n\n  // it didn't already exist, add it now\n  m_values.push_back(t_vals);\n\n}\n\n\n\n\nstd::vector<std::vector<double> > LinearApproximation::findMinimalDifferences(\n    size_t t_numDifferences,\n    const std::vector<std::vector<double> > &t_vals,\n    const std::vector<std::vector<double> > &t_data) const\n{\n  // t_vals includes the baseline requested value, so we want one more than that\n  if (t_data.empty() || t_numDifferences + 2 == t_vals.size())\n  {\n    // this is as good as we're going to get / can use right now\n    std::vector<std::vector<double> > retval = t_vals;\n\n    if (!t_vals.empty())\n    {\n      retval.erase(retval.begin());\n    }\n    return retval;\n  }\n\n  std::vector<std::vector<double> > candidates;\n  std::vector<std::vector<double> > remainder;\n\n  for (size_t i = 0; i < t_data.size(); ++i)\n  {\n    size_t numDifferences = 0;\n\n    for (size_t j = 0; j < m_numVars; ++j)\n    {\n      for (size_t i2 = 0; i2 < t_vals.size(); ++i2)\n      {\n        if (t_data[i][j] != t_vals[i2][j])\n        {\n          ++numDifferences;\n          break; // don't check any further input rows\n        }\n      }\n\n      if (numDifferences > t_numDifferences)\n      {\n        // don't continue with this data row\n        break;\n      }\n    }\n\n    if (numDifferences <= t_numDifferences)\n    {\n      candidates.push_back(t_data[i]);\n    } else {\n      remainder.push_back(t_data[i]);\n    }\n  }\n\n  std::vector<std::vector<double> > keptresult = t_vals;\n  keptresult.erase(keptresult.begin());\n\n  for (size_t i = 0; i < candidates.size(); ++i)\n  {\n    std::vector<std::vector<double> > newvals(t_vals);\n    newvals.push_back(candidates[i]);\n\n    std::vector<std::vector<double> > newdata(t_data);\n    newdata.erase(std::remove(newdata.begin(), newdata.end(), candidates[i]), newdata.end());\n\n    std::vector<std::vector<double> > result = findMinimalDifferences(t_numDifferences, newvals, newdata);\n    if (result.size() > keptresult.size())\n    {\n      keptresult = result;\n    }\n  }\n\n  return keptresult;\n}\n\nstd::vector<std::vector<double> > LinearApproximation::filterForProblemReduction(const std::vector<double> &t_vals,\n    const std::vector<std::vector<double> > &t_data) const\n{\n  std::vector<std::vector<double> > testData;\n  testData.push_back(t_vals);\n\n  for (size_t i = 1; i < m_numVars; ++i)\n  {\n    std::vector<std::vector<double> > results = findMinimalDifferences(i, testData, t_data);\n    if (results.size() > i)\n    {\n      return results;\n    }\n  }\n\n  return t_data;\n}\n\n\ndouble LinearApproximation::approximate(const std::vector<double> &t_vals) const\n{\n  // Linear Approximation\n  // A(x-x0) + B(y-y0) + C(z-z0) = 0\n  validateVariableSize(t_vals);\n\n//  print(\"Approximating: \", t_vals);\n\n  std::vector<std::vector<double> > sortedPoints = sortByDistance(t_vals, m_values);\n\n  if (!sortedPoints.empty() && distance(t_vals, sortedPoints[0]) == 0)\n  {\n    //return exact match\n    return sortedPoints[0].back();\n  }\n\n  std::vector<std::vector<double> > optimalPoints = filterForProblemReduction(t_vals, sortedPoints);\n\n//  print(\"Starting points: \", m_values);\n\n//  print(\"Sorted Points: \", sortedPoints);\n  std::vector<std::vector<double> > chosenPoints = filterForSimilarity(t_vals, optimalPoints);\n\n//  print(\"Chosen points: \", chosenPoints);\n\n\n  std::vector<std::vector<std::vector<double> > > coefficientMatrices = buildCoefficientMatrices(chosenPoints);\n\n//  print(\"Coefficients: \", coefficientMatrices);\n\n\n  std::vector<double> coefficients = solveDeterminates(coefficientMatrices);\n\n//  print(\"Coefficients: \", coefficients);\n  assert(coefficients.size() == m_numVars + 1);\n\n\n\n  double approximation = 0;\n  for (size_t i = 0; i < m_numVars; ++i)\n  {\n    // A(x-x0) + B(y-y0) + C(z-z0) ... \n    approximation += coefficients[i] * (t_vals[i] - chosenPoints[0][i]);\n  }\n\n  // the last variable is the one we are solving for \n  // z=(z0*C+(y0-y)*B+(x0-x)*A)/C\n  if (coefficients[m_numVars] == 0)\n  {\n    throw std::runtime_error(\"Unabled to approximate, not enough data\");\n  }\n\n  approximation = (approximation + chosenPoints[0][m_numVars] * coefficients[m_numVars]) / coefficients[m_numVars];\n\n//  std::cout << \"final approximation: \" << approximation << std::endl;\n\n  return approximation;\n}\n\n\nvoid LinearApproximation::validateVariableSize(const std::vector<double> &t_vals) const\n{\n  if (t_vals.size() != m_numVars)\n  {\n    throw std::range_error(\"Unexpected number of variables supplied\");\n  }\n}\n\nconst std::vector<std::vector<double> > LinearApproximation::filterForSimilarity(const std::vector<double> &t_point, const std::vector<std::vector<double> > &t_vals) const\n{\n  std::vector<std::vector<double> > goodPoints = t_vals;\n  int pointsNeeded = m_numVars + 1;\n\n  for (size_t i = 0; i < m_numVars; ++i)\n  {\n    bool diversityFound = false;\n    bool allTheSame = true;\n\n    int differencePosition = -1;\n\n    int rowCount = 0;\n    for (std::vector<std::vector<double> >::const_iterator itr = t_vals.begin();\n        itr != t_vals.end();\n        ++itr, ++rowCount)\n    {\n      if (t_vals[0][i] != (*itr)[i])\n      {\n        diversityFound = true; // not all of the inputs match each other\n      }\n\n      if (t_point[i] != (*itr)[i])\n      {\n        allTheSame = false; // not all of the inputs for this position match the requested approximation\n        differencePosition = rowCount;\n      }\n    }\n\n    if (!diversityFound && !allTheSame)\n    {\n      // There is not enough data available to calculate the value for this position\n      std::stringstream ss;\n      ss << \"Not enough data available for the \" << i << \" variable position\";\n      throw std::runtime_error(ss.str());\n    }\n\n    if (allTheSame || (differencePosition >= pointsNeeded))\n    {\n      if (pointsNeeded > 2)\n      {\n        --pointsNeeded;\n        goodPoints.resize(std::min(pointsNeeded, static_cast<int>(goodPoints.size()))); // never expand it\n      }\n    }\n  }\n\n  goodPoints.resize(std::min(pointsNeeded, static_cast<int>(goodPoints.size())));\n  return goodPoints;\n}\n\nstd::vector<std::vector<std::vector<double> > > LinearApproximation::buildCoefficientMatrices(\n    const std::vector<std::vector<double> > &t_points) const\n{\n  std::set<size_t> discardedColumns;\n\n  for (size_t i = 0; i <= m_numVars; ++i)\n  {\n    bool allthesame = true;\n    for (std::vector<std::vector<double> >::const_iterator itr = t_points.begin();\n        itr != t_points.end();\n        ++itr)\n    {\n      if ((*itr)[i] != t_points[0][i])\n      {\n        allthesame = false;\n      }\n    }\n\n    if (allthesame)\n    {\n      discardedColumns.insert(i);\n    }\n  }\n\n  std::vector<std::vector<std::vector<double> > > retvals;\n\n  for (size_t i = 0; i <= m_numVars; ++i)\n  {\n    if (discardedColumns.count(i) == 1)\n    {\n      // this is a discarded column its value is 0\n      std::vector<double> v(1,0); // a vector of one element of value 0\n      std::vector<std::vector<double> > m;\n      m.push_back(v);\n      retvals.push_back(m);\n    } else {\n      std::vector<std::vector<double> > m;\n      for (size_t curRow = 0; curRow < m_numVars - discardedColumns.size(); ++curRow)\n      {\n        std::vector<double> row;\n        for (size_t j = 0; j <= m_numVars; ++j)\n        {\n          if (j != i && discardedColumns.count(j) == 0)\n          {\n            // This is a column we want to work with\n            row.push_back(t_points[curRow+1][j] - t_points[0][j]);\n          }\n        }\n        m.push_back(row);\n      }\n      retvals.push_back(m);\n    }\n  }\n\n  return retvals;\n}\n\nstd::vector<std::vector<double> > LinearApproximation::removeCol(const std::vector<std::vector<double> > &t_matrix, const size_t col) const\n{\n  std::vector<std::vector<double> > retval(t_matrix.size()-1, std::vector<double>(t_matrix.size()-1, 0));\n\n  for (size_t i = 1; i < t_matrix.size(); ++i)\n  {\n    size_t colnum = 0;\n    for (size_t j = 0; j < t_matrix[i].size(); ++j)\n    {\n      if (j != col)\n      {\n        retval[i-1][colnum] = t_matrix[i][j];\n        ++colnum;\n      }\n    }\n  }\n\n  return retval;\n}\n\ndouble LinearApproximation::determinate(const std::vector<std::vector<double> > &t_matrix) const\n{\n/*\n  bool docache = false;\n\n  if (docache)\n  {\n    std::map<std::vector<std::vector<double> >, double>::const_iterator itr = m_cache.find(t_matrix);\n    if (itr != m_cache.end())\n    {\n      std::cout << \"Cache hit\" << std::endl; \n      return itr->second;\n    }\n  }\n\n  if (t_matrix.size() == 1)\n  {\n    return t_matrix[0][0];\n  } else if (t_matrix.size() == 2) {\n    return t_matrix[0][0] * t_matrix[1][1] - t_matrix[0][1] * t_matrix[1][0];\n  } else {\n    double d = 0;\n\n    for (size_t i = 0; i < t_matrix.size(); ++i)\n    {\n      //          d += pow(-1, i) * t_matrix[0][i] * determinate(removeCol(t_matrix, i));\n      d += (i%2==1?-1:1) * t_matrix[0][i] * determinate(removeCol(t_matrix, i));\n    }\n\n    if (docache)\n    {\n      m_cache[t_matrix] = d;\n    }\n    return d;\n  }\n  */\n\n  namespace bnu = boost::numeric::ublas;\n\n  class Determinant \n  {\n\n    static int determinant_sign(const bnu::permutation_matrix<std::size_t>& pm)\n    {\n      int pm_sign=1;\n      std::size_t size = pm.size();\n      for (std::size_t i = 0; i < size; ++i)\n      {\n        if (i != pm(i)) {\n          pm_sign *= -1; // swap_rows would swap a pair of rows here, so we change sign\n        }\n      }\n      return pm_sign;\n    }\n\n    static double determinant( bnu::matrix<double>& m ) {\n      bnu::permutation_matrix<std::size_t> pm(m.size1());\n      double det = 1.0;\n      if( bnu::lu_factorize(m,pm) ) {\n        det = 0.0;\n      } else {\n        for(size_t i = 0; i < m.size1(); i++) {\n          det *= m(i,i); // multiply by elements on diagonal\n        }\n\n        det = det * determinant_sign( pm );\n      }\n      return det;\n    }\n\n    public:\n    static double determinant(const std::vector<std::vector<double> > &t_matrix)\n    {\n      bnu::matrix<double> matrix(t_matrix.size(), t_matrix.size());\n\n      for (size_t i = 0; i < t_matrix.size(); ++i)\n      {\n        for (size_t j = 0; j < t_matrix[i].size(); ++j)\n        {\n          matrix(i, j) = t_matrix[i][j];\n        }\n      }\n\n      return determinant(matrix);\n    }\n  };\n\n  double retval = Determinant::determinant(t_matrix);\n\n  /*\n  if (docache)\n  {\n    m_cache[t_matrix] = retval;\n  }\n  */\n\n  return retval;\n}\n\nstd::vector<double> LinearApproximation::solveDeterminates(const std::vector<std::vector<std::vector<double> > > &t_matrices) const\n{\n  std::vector<double> retval;\n\n  for (std::vector<std::vector<std::vector<double> > >::const_iterator itr = t_matrices.begin();\n      itr != t_matrices.end();\n      ++itr)\n  {\n    retval.push_back(determinate(*itr));\n  }\n\n  return retval; \n}\n\nstd::vector<std::vector<double> > LinearApproximation::sortByDistance(const std::vector<double> &t_point, \n    const std::vector<std::vector<double> > &t_values) const\n{\n  std::set<std::pair<double, std::vector<double> > > distanceSorted;\n\n  for (std::vector<std::vector<double> >::const_iterator itr = t_values.begin();\n      itr != t_values.end();\n      ++itr)\n  {\n    distanceSorted.insert(std::make_pair(distance(t_point, *itr), *itr));\n  }\n\n  std::vector<std::vector<double> > retval;\n\n  for (std::set<std::pair<double, std::vector<double> > >::const_iterator itr = distanceSorted.begin();\n      itr != distanceSorted.end();\n      ++itr)\n  {\n    retval.push_back(itr->second);\n  }\n\n  return retval;\n}\n\ndouble LinearApproximation::distance(const std::vector<double> &t_p1, const std::vector<double> &t_p2) const\n{\n  double result = 0;\n  for (size_t i = 0; i < m_numVars; ++i)\n  {\n    double part = t_p1[i] - t_p2[i];\n    part *= part;\n\n    result += part;\n  }\n\n  return sqrt(result);\n}\n\nvoid LinearApproximation::print(const std::string &t_str, const std::vector<double> &t_vals)\n{\n  if (!t_str.empty())\n  {\n    std::cout << t_str << std::endl;\n  }\n\n  std::cout << \"[ \";\n  for (std::vector<double>::const_iterator itr = t_vals.begin();\n      itr != t_vals.end();\n      ++itr)\n  {\n    std::cout << std::setw(10) << *itr << \" \";\n  }\n  std::cout << \"]\" << std::endl;\n}\n\nvoid LinearApproximation::print(const std::string &t_str, const std::vector<std::vector<double> > &t_vals)\n{\n  if (!t_str.empty())\n  {\n    std::cout << t_str << std::endl;\n  }\n\n  for (std::vector<std::vector<double> >::const_iterator itr = t_vals.begin();\n      itr != t_vals.end();\n      ++itr)\n  {\n    print(\"\", *itr);\n  }\n}\n\nstd::pair<double, double> LinearApproximation::nearestFurthestNeighborDistances(const std::vector<double> &t_vals) const\n{\n  std::vector<std::vector<double> > sorted = sortByDistance(t_vals, m_values);\n\n  if (sorted.size() < 1)\n  {\n    throw std::range_error(\"no neighbors\");\n  }\n\n  return std::make_pair(distance(t_vals, sorted.front()), distance(t_vals, sorted.back()));\n}\n\nvoid LinearApproximation::print(const std::string &t_str, const std::vector<std::vector<std::vector<double> > > &t_vals)\n{\n  if (!t_str.empty())\n  {\n    std::cout << t_str << std::endl;\n  }\n\n  for (std::vector<std::vector<std::vector<double> > >::const_iterator itr = t_vals.begin();\n      itr != t_vals.end();\n      ++itr)\n  {\n    print(\"\", *itr);\n    std::cout << std::endl;\n  }\n}\n\n\n\n", "meta": {"hexsha": "24ff5d769abad1d68f0c22cbc7e5e74b52055cbe", "size": 15343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/runmanager/lib/LinearApproximation.cpp", "max_stars_repo_name": "bobzabcik/OpenStudio", "max_stars_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_stars_repo_licenses": ["blessing"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "openstudiocore/src/runmanager/lib/LinearApproximation.cpp", "max_issues_repo_name": "bobzabcik/OpenStudio", "max_issues_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_issues_repo_licenses": ["blessing"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "openstudiocore/src/runmanager/lib/LinearApproximation.cpp", "max_forks_repo_name": "bobzabcik/OpenStudio", "max_forks_repo_head_hexsha": "858321dc0ad8d572de15858d2ae487b029a8d847", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0702614379, "max_line_length": 171, "alphanum_fraction": 0.6031414978, "num_tokens": 4273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22418192331223902}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Eigen. http://eigen.tuxfamily.org/dox/TopicUnalignedArrayAssert.html, last accessed: 18th\n *          March, 2013.\n *\n *    Notes\n *      This implementation uses the KeplerianElements class, which is marked for deprecation. The\n *      code will be updated to use a simple \"Vector6d\" object from the Eigen library instead.\n *\n */\n\n#include <stdexcept>\n\n#include <boost/make_shared.hpp>\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/orbitalElementConversions.h\"\n\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/convertMeanToEccentricAnomalies.h\"\n#include \"Tudat/Astrodynamics/BasicAstrodynamics/stateVectorIndices.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/keplerStateExtractor.h\"\n#include \"Tudat/InputOutput/parsedDataVectorUtilities.h\"\n\nnamespace tudat\n{\nnamespace ephemerides\n{\n\n//! Extract the Keplerian Elements.\nstd::shared_ptr< Eigen::Vector6d > KeplerStateExtractor::extract(\n        ParsedDataLineMapPtr dataLineMap )\n{\n    // Short-hand notation.\n    namespace parsed_data_vector_utilities = input_output::parsed_data_vector_utilities;\n    using Eigen::Vector6d;\n\n    // Create a new KeplerianElements object.\n    std::shared_ptr< Vector6d > keplerianElements\n            = std::allocate_shared< Vector6d >( Eigen::aligned_allocator< Vector6d >( ) );\n\n    // Find and set semi-major axis.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::semiMajorAxis ) )\n    {\n        ( *keplerianElements )( orbital_element_conversions::semiMajorAxisIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::semiMajorAxis );\n    }\n\n    else\n    {\n        throw std::runtime_error( \"No semi-major axis entry found.\" );\n    }\n\n    // Find and set eccentricity.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::eccentricity ) )\n    {\n        ( *keplerianElements )( orbital_element_conversions::eccentricityIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::eccentricity );\n    }\n\n    else\n    {\n        throw std::runtime_error( \"No eccentricity entry found.\" );\n    }\n\n    // Find and set inclination.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::inclination ) )\n    {\n        ( *keplerianElements )( orbital_element_conversions::inclinationIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::inclination );\n    }\n\n    else\n    {\n        throw std::runtime_error( \"No inclination entry found.\" );\n    }\n\n    // Find and set longitude of ascending node.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::longitudeOfAscendingNode ) )\n    {\n        ( *keplerianElements )( orbital_element_conversions::longitudeOfAscendingNodeIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::longitudeOfAscendingNode );\n    }\n\n    else\n    {\n        throw std::runtime_error( \"No longitude of ascending node entry found.\" );\n    }\n\n    // Find and set argument of periapsis.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::argumentOfPeriapsis ) )\n    {\n        ( *keplerianElements )( orbital_element_conversions::argumentOfPeriapsisIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::argumentOfPeriapsis );\n    }\n\n    else\n    {\n        throw std::runtime_error( \"No argument of periapsis entry found.\" );\n    }\n\n    // Find and set true anomaly.\n    if ( checkOptionalFieldType( dataLineMap, 1,\n                                 input_output::field_types::state::trueAnomaly ) )\n    {\n        ( *keplerianElements )( orbital_element_conversions::trueAnomalyIndex )\n                = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::trueAnomaly );\n    }\n\n    // If the true anomaly is not present, check for mean anomaly.\n    else if ( checkOptionalFieldType( dataLineMap, 1,\n                                      input_output::field_types::state::meanAnomaly ) )\n    {\n        // Store mean anomaly.\n        const double meanAnomaly = parsed_data_vector_utilities::getField< double >(\n                    dataLineMap, input_output::field_types::state::meanAnomaly );\n\n        // Retrieve eccentricity.\n        const double eccentricity\n                = ( *keplerianElements )( orbital_element_conversions::eccentricityIndex );\n\n        // Convert to eccentric anomaly.\n        const double eccentricAnomaly = orbital_element_conversions::\n                convertMeanAnomalyToEccentricAnomaly( eccentricity, meanAnomaly );\n\n        // Convert eccentric anomaly to true anomaly and set the latter.\n        ( *keplerianElements )( orbital_element_conversions::trueAnomalyIndex )\n                = orbital_element_conversions::\n                convertEccentricAnomalyToTrueAnomaly( eccentricAnomaly, eccentricity );\n    }\n\n    else\n    {\n        throw std::runtime_error( \"No true anomaly or mean anomaly entries found.\" );\n    }\n\n    return keplerianElements;\n}\n\n} // namespace ephemerides\n} // namespace tudat\n", "meta": {"hexsha": "29c39f2912208664112e3f0418b820f2ac987f59", "size": 6111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Ephemerides/keplerStateExtractor.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Ephemerides/keplerStateExtractor.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Ephemerides/keplerStateExtractor.cpp", "max_forks_repo_name": "ViktorJordanov/tudat", "max_forks_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.490797546, "max_line_length": 98, "alphanum_fraction": 0.657175585, "num_tokens": 1376, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22418192331223902}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n/// \\file rmax_adjust.cc\n///\n\n#include <boost/algorithm/string.hpp>\n#include <boost/program_options.hpp>\n#include \"boost/filesystem/operations.hpp\"\n#include \"boost/filesystem/fstream.hpp\"\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\n#include <vw/Camera/CAHVORModel.h>\n#include <vw/BundleAdjustment.h>\n#include <vw/Math.h>\n#include <vw/Math/LevenbergMarquardt.h>\n\nusing namespace vw;\nusing namespace vw::camera;\nusing namespace vw::ba;\n\n#include <stdlib.h>\n#include <iostream>\n\n#include <asp/Sessions/RMAX/RMAX.h>\n\n// This sifts out from a vector of strings, a listing of GCPs.  This\n// should be useful for those programs who accept their data in a mass\n// input vector.\nstd::vector<std::string>\nsort_out_gcps( std::vector<std::string>& image_files ) {\n  std::vector<std::string> gcp_files;\n  std::vector<std::string>::iterator it = image_files.begin();\n  while ( it != image_files.end() ) {\n    if ( boost::iends_with(*it, \".gcp\") ){\n      gcp_files.push_back( *it );\n      it = image_files.erase( it );\n    } else\n      it++;\n  }\n\n  return gcp_files;\n}\n\nstatic std::string prefix_from_filename(std::string const& filename) {\n  std::string result = filename;\n  int index = result.rfind(\".\");\n  if (index != -1)\n    result.erase(index, result.size());\n  return result;\n}\n\nclass HelicopterBundleAdjustmentModel : public ba::ModelBase<HelicopterBundleAdjustmentModel, 6, 3> {\n\n  typedef Vector<double,6> camera_vector_t;\n  typedef Vector<double,3> point_vector_t;\n\n  std::vector<ImageInfo> m_image_infos;\n\n  boost::shared_ptr<ControlNetwork> m_network;\n\n  std::vector<camera_vector_t> a;\n  std::vector<point_vector_t> b;\n  std::vector<camera_vector_t> a_target;\n  std::vector<point_vector_t> b_target;\n  int m_num_pixel_observations;\n\npublic:\n\n  HelicopterBundleAdjustmentModel(std::vector<ImageInfo> const& image_infos,\n                                  boost::shared_ptr<ControlNetwork> network) :\n    m_image_infos(image_infos), m_network(network),\n    a(image_infos.size()), b(network->size()),\n    a_target(image_infos.size()), b_target(network->size()) {\n\n    // Compute the number of observations from the bundle.\n    m_num_pixel_observations = 0;\n    for (unsigned i = 0; i < network->size(); ++i)\n      m_num_pixel_observations += (*m_network)[i].size();\n\n    // Set up the a and b vectors, storing the initial values.\n    for (unsigned j = 0; j < m_image_infos.size(); ++j) {\n      a[j] = camera_vector_t();\n      a_target[j] = a[j];\n    }\n\n    for (unsigned i = 0; i < m_network->size(); ++i) {\n      b[i] = (*m_network)[i].position();\n      b_target[i] = b[i];\n    }\n\n  }\n\n  // Return a reference to the camera and point parameters.\n  camera_vector_t A_parameters(int j) const { return a[j]; }\n  point_vector_t B_parameters(int i) const { return b[i]; }\n  void set_A_parameters(int j, camera_vector_t const& a_j) {\n    a[j] = a_j;\n  }\n  void set_B_parameters(int i, point_vector_t const& b_i) {\n    b[i] = b_i;\n  }\n\n  // Return the initial parameters\n  camera_vector_t A_target(int j) const { return a_target[j]; }\n  point_vector_t B_target(int i) const { return b_target[i]; }\n\n  // Return general sizes\n  unsigned num_cameras() const { return a.size(); }\n  unsigned num_points() const { return b.size(); }\n  unsigned num_pixel_observations() const { return m_num_pixel_observations; }\n\n  // Return pixel observations\n  unsigned num_observations_of_point(const int& i) const { return (*m_network)[i].size(); }\n  unsigned corresponding_camera_for_measure(const int& i, const int& m){\n    return (*m_network)[i][m].image_id();\n  }\n  Vector2 pixel_observation_of_point(const int& i, const int& m) const {\n    //Finding out which camera accounts for the m_th observations of point i\n    unsigned int camera_id = (*m_network)[i][m].image_id();\n\n    Vector<double,6> a_j = a[camera_id];\n    Vector3 position_correction = subvector(a_j,0,3);\n    Vector3 pose_correction = subvector(a_j,3,3);\n    camera::CAHVORModel cam = rmax_image_camera_model(m_image_infos[camera_id],position_correction,pose_correction);\n\n    Vector4 point_estimation = B_parameters(i);\n    point_estimation = point_estimation/point_estimation(3);\n    return cam.point_to_pixel(subvector(point_estimation,0,3));\n  }\n\n  // Return the covariance of the camera parameters for camera j.\n  inline Matrix<double,camera_params_n,camera_params_n> A_inverse_covariance ( unsigned /*j*/ ) {\n    Matrix<double,camera_params_n,camera_params_n> result;\n    result(0,0) = 1/1;  // Position sigma = 1 meter\n    result(1,1) = 1/1;\n    result(2,2) = 1/1;\n    result(3,3) = 1;  // Pose sigma = 1 degrees\n    result(4,4) = 1;\n    result(5,5) = 1;\n    return result;\n  }\n\n  // Return the covariance of the point parameters for point i.\n  inline Matrix<double,point_params_n,point_params_n> B_inverse_covariance ( unsigned /*i*/ ) {\n    Matrix<double,point_params_n,point_params_n> result;\n    result(0,0) = 1/1000.0;  // Point sigma = 1000 meters ( we set this to be\n    result(1,1) = 1/1000.0;  // so large that it essentially removes point position\n    result(2,2) = 1/1000.0;  // constraints from the bundle adjustment entirely. )\n    return result;\n  }\n\n  void write_adjustment(int j, std::string const& filename) {\n    std::ofstream ostr(filename.c_str());\n    ostr << a[j][0] << \" \" << a[j][1] << \" \" << a[j][2] << \"\\n\";\n    ostr << a[j][3] << \" \" << a[j][4] << \" \" << a[j][5] << \"\\n\";\n  }\n\n  void write_adjusted_camera(int j, std::string const& filename) {\n    Vector<double,6> a_j = a[j];\n    Vector3 position_correction = subvector(a_j, 0, 3);\n    Vector3 pose_correction = subvector(a_j, 3,3);\n    camera::CAHVORModel cam = rmax_image_camera_model(m_image_infos[j], position_correction, pose_correction);\n    cam.write(filename);\n  }\n\n  void write_adjusted_cameras_append(std::string const& filename) {\n    std::ofstream ostr(filename.c_str(),std::ios::app);\n    for (unsigned j=0; j < a.size();++j){\n      Vector<double,6> a_j = a[j];\n      Vector3 position_correction = subvector(a_j,0,3);\n      Vector3 pose_correction = subvector(a_j,3,3);\n      camera::CAHVORModel cam = rmax_image_camera_model(m_image_infos[j],position_correction,pose_correction);\n      ostr << j << \"\\t\" << cam.C(0) << \"\\t\" << cam.C(1) << \"\\t\" << cam.C(2) << \"\\n\";\n      ostr << j << \"\\t\" << cam.A(0) << \"\\t\" << cam.A(1) << \"\\t\" << cam.A(2) << \"\\n\";\n      ostr << j << \"\\t\" << cam.H(0) << \"\\t\" << cam.H(1) << \"\\t\" << cam.H(2) << \"\\n\";\n      ostr << j << \"\\t\" << cam.V(0) << \"\\t\" << cam.V(1) << \"\\t\" << cam.V(2) << \"\\n\";\n      ostr << j << \"\\t\" << cam.O(0) << \"\\t\" << cam.O(1) << \"\\t\" << cam.O(2) << \"\\n\";\n      ostr << j << \"\\t\" << cam.R(0) << \"\\t\" << cam.R(1) << \"\\t\" << cam.R(2) << \"\\n\";\n    }\n  }\n\n  std::vector<boost::shared_ptr<camera::CameraModel> > adjusted_cameras() {\n    std::vector<boost::shared_ptr<camera::CameraModel> > result(a.size());\n    for (unsigned j = 0; j < result.size(); ++j) {\n      Vector3 position_correction = subvector(a[j], 0, 3);\n      Vector3 pose_correction = subvector(a[j], 3,3);\n\n      camera::CAHVORModel *cahvor = new camera::CAHVORModel;\n      *cahvor = rmax_image_camera_model(m_image_infos[j], position_correction, pose_correction);\n\n      result[j] = boost::shared_ptr<camera::CameraModel>( cahvor );\n    }\n    return result;\n  }\n\n  // Given the 'a' vector (camera model parameters) for the j'th\n  // image, and the 'b' vector (3D point location) for the i'th\n  // point, return the location of b_i on imager j in pixel\n  // coordinates.\n  Vector2 operator() ( unsigned /*i*/, unsigned j, Vector<double,6> const& a_j, Vector<double,3> const& b_i ) const {\n    Vector3 position_correction = subvector(a_j, 0, 3);\n    Vector3 pose_correction = subvector(a_j, 3,3);\n    camera::CAHVORModel cam = rmax_image_camera_model(m_image_infos[j], position_correction, pose_correction);\n    return cam.point_to_pixel(b_i);\n  }\n\n  // Errors on the image plane\n  void image_errors( std::vector<double>& pix_errors ) {\n    pix_errors.clear();\n    for (unsigned i = 0; i < m_network->size(); ++i)\n      for(unsigned m = 0; m < (*m_network)[i].size(); ++m) {\n        int camera_idx = (*m_network)[i][m].image_id();\n        Vector2 pixel_error = (*m_network)[i][m].position() - (*this)(i, camera_idx,\n                                                                   a[camera_idx],b[i]);\n        pix_errors.push_back(norm_2(pixel_error));\n      }\n  }\n\n  // Errors for camera position\n  void camera_position_errors( std::vector<double>& camera_position_errors ) {\n    camera_position_errors.clear();\n    for (unsigned j=0; j < this->num_cameras(); ++j) {\n      Vector3 position_initial, position_now;\n      position_initial = subvector(a_target[j],0,3);\n      position_now = subvector(a[j],0,3);\n\n      camera_position_errors.push_back(norm_2(position_initial-position_now));\n    }\n  }\n\n  // Errors for camera pose\n  void camera_pose_errors( std::vector<double>& camera_pose_errors ) {\n    camera_pose_errors.clear();\n    for (unsigned j=0; j < this->num_cameras(); ++j) {\n      Vector3 pose_initial, pose_now;\n      pose_initial = subvector(a_target[j],3,3);\n      pose_now = subvector(a[j],3,3);\n\n      camera_pose_errors.push_back(norm_2(pose_initial-pose_now));\n    }\n  }\n\n  // Errors for gcp errors\n  void gcp_errors( std::vector<double>& gcp_errors ) {\n    gcp_errors.clear();\n    for (unsigned i=0; i < this->num_points(); ++i)\n      if ((*m_network)[i].type() == ControlPoint::GroundControlPoint) {\n        point_vector_t p1 = b_target[i]/b_target[i](3);\n        point_vector_t p2 = b[i]/b[i](3);\n        gcp_errors.push_back(norm_2(subvector(p1,0,3) - subvector(p2,0,3)));\n      }\n  }\n\n  // Give access to the control network\n  boost::shared_ptr<ControlNetwork> control_network() {\n    return m_network;\n  }\n};\n\nint main(int argc, char* argv[]) {\n\n  std::vector<std::string> image_files;\n  std::vector<std::string> gcp_files;\n  std::string cnet_file;\n  boost::shared_ptr<ControlNetwork> cnet( new ControlNetwork(\"My first control network\"));\n  double lambda;\n  int min_matches;\n  double robust_outlier_threshold;\n  int max_iterations;\n  int report_level;\n\n  po::options_description general_options(\"Options\");\n  general_options.add_options()\n    (\"cnet,c\", po::value<std::string>(&cnet_file), \"Load a control network from a file\")\n    (\"lambda,l\", po::value<double>(&lambda), \"Set the initial value of the LM parameter lambda\")\n    (\"min-matches\", po::value<int>(&min_matches)->default_value(5), \"Set the mininmum number of matches between images that will be considered.\")\n    (\"robust-threshold\", po::value<double>(&robust_outlier_threshold)->default_value(10.0), \"Set the threshold for robust cost functions.\")\n    (\"max-iterations\", po::value<int>(&max_iterations)->default_value(25), \"Set the maximum number of iterations.\")\n    (\"save-iteration-data,s\", \"Saves all camera information between iterations to iterCameraParam.txt, it also saves point locations for all iterations in iterPointsParam.txt. Warning: This is slow as pixel observations need to be calculated on each step.\")\n    (\"report-level,r\",po::value<int>(&report_level)->default_value(10),\"Changes the detail of the Bundle Adjustment Report\")\n    (\"run-match,m\", \"Run ipmatch to create .match files from overlapping images.\")\n    (\"match-debug-images,d\", \"Create debug images when you run ipmatch.\")\n    (\"help,h\", \"Display this help message\");\n\n  po::options_description hidden_options(\"\");\n  hidden_options.add_options()\n    (\"input-files\", po::value<std::vector<std::string> >(&image_files));\n\n  po::options_description options(\"Allowed Options\");\n  options.add(general_options).add(hidden_options);\n\n  po::positional_options_description p;\n  p.add(\"input-files\", -1);\n\n  po::variables_map vm;\n  po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );\n  po::notify( vm );\n\n  std::ostringstream usage;\n  usage << \"Usage: \" << argv[0] << \" [options] <rmax image filenames>...\" << std::endl << std::endl;\n  usage << general_options << std::endl;\n\n  if( vm.count(\"help\") ) {\n    std::cout << usage << std::endl;\n    return 1;\n  }\n\n  if( vm.count(\"input-files\") < 1 || image_files.size() < 2) {\n    std::cout << \"Error: Must specify at least two input files!\" << std::endl << std::endl;\n    std::cout << usage.str();\n    return 1;\n  }\n  gcp_files = sort_out_gcps( image_files );\n\n  // Read in the camera model and RMAX image info for the input\n  // images.\n  std::vector<std::string> camera_files(image_files.size());\n  std::vector<ImageInfo> image_infos(image_files.size());\n  std::vector<boost::shared_ptr<CameraModel> > camera_models(image_files.size());\n  for (unsigned i = 0; i < image_files.size(); ++i) {\n    read_image_info( image_files[i], image_infos[i] );\n    CAHVORModel *cahvor = new CAHVORModel;\n    *cahvor = rmax_image_camera_model(image_infos[i]);\n    camera_models[i] = boost::shared_ptr<CameraModel>(cahvor);\n  }\n\n  if ( vm.count(\"cnet\") ) {\n    // Loading a Control Network\n\n    vw_out() << \"Loading control network from file: \" << cnet_file << \"\\n\";\n    cnet->read_binary(cnet_file);\n\n  } else {\n    // Building a Control Network\n    build_control_network( *cnet, camera_models,\n                           image_files, min_matches );\n    add_ground_control_points( *cnet, image_files,\n                               gcp_files.begin(), gcp_files.end() );\n\n    cnet->write_binary(\"rmax_adjust\");\n  }\n\n  HelicopterBundleAdjustmentModel ba_model(image_infos, cnet);\n  AdjustSparse<HelicopterBundleAdjustmentModel, L2Error> bundle_adjuster(ba_model, L2Error());\n\n  if (vm.count(\"lambda\"))\n    bundle_adjuster.set_lambda(lambda);\n\n  //Clearing the monitoring text files to be used for saving camera params\n  if (vm.count(\"save-iteration-data\")){\n    std::ofstream ostr(\"iterCameraParam.txt\",std::ios::out);\n    ostr << \"\";\n    ostr.close();\n    ostr.open(\"iterPointsParam.txt\",std::ios::out);\n    ostr << \"\";\n    ostr.close();\n\n    //Now I'm going to save the initial starting position of the cameras\n    ba_model.write_adjusted_cameras_append(\"iterCameraParam.txt\");\n    std::ofstream ostr_points(\"iterPointsParam.txt\",std::ios::app);\n    for (unsigned i = 0; i < ba_model.num_points(); ++i){\n      Vector<double,3> current_point = ba_model.B_parameters(i);\n      ostr_points << i << \"\\t\" << current_point(0) << \"\\t\" << current_point(1) << \"\\t\" << current_point(2) << \"\\n\";\n    }\n  }\n\n  // Reporter\n  BundleAdjustReport<AdjustSparse<HelicopterBundleAdjustmentModel, L2Error> >\n    reporter( \"RMAX Adjust\", ba_model, bundle_adjuster, report_level );\n\n  // Performing Bundle Adjustment\n  double abs_tol = 1e10, rel_tol=1e10;\n  while(bundle_adjuster.update(abs_tol, rel_tol)) {\n    reporter.loop_tie_in();\n\n    // Writing Current Camera Parameters to file for later reading in MATLAB\n    if (vm.count(\"save-iteration-data\")) {\n\n      //Writing this iterations camera data\n      ba_model.write_adjusted_cameras_append(\"iterCameraParam.txt\");\n\n      //Writing this iterations point data, also saving the pixel param data\n      std::ofstream ostr_points(\"iterPointsParam.txt\",std::ios::app);\n      for (unsigned i = 0; i < ba_model.num_points(); ++i){\n\n        Vector<double,3> current_point = ba_model.B_parameters(i);\n        ostr_points << i << \"\\t\" << current_point(0) << \"\\t\" << current_point(1) << \"\\t\" << current_point(2) << \"\\n\";\n      }\n    }\n\n    if (bundle_adjuster.iterations() > max_iterations || abs_tol < 0.01 || rel_tol < 1e-10)\n      break;\n  }\n  reporter.end_tie_in();\n\n  for (unsigned int i=0; i < ba_model.num_cameras(); ++i)\n    ba_model.write_adjustment(i, prefix_from_filename(image_files[i])+\".rmax_adjust\");\n\n  // Compute the post-adjustment residuals\n  std::vector<boost::shared_ptr<CameraModel> > adjusted_cameras = ba_model.adjusted_cameras();\n}\n", "meta": {"hexsha": "a9462879a6ebe164ad4314fc3cc20696383d7b1c", "size": 15902, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/Tools/rmax_adjust.cc", "max_stars_repo_name": "nasa/StereoPipeline", "max_stars_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2015-05-06T01:28:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:55:29.000Z", "max_issues_repo_path": "src/asp/Tools/rmax_adjust.cc", "max_issues_repo_name": "imagineagents/StereoPipeline", "max_issues_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asp/Tools/rmax_adjust.cc", "max_forks_repo_name": "imagineagents/StereoPipeline", "max_forks_repo_head_hexsha": "8b9c0bcab258c41d10cb2973d97722765072a7bf", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T04:20:50.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-10T01:31:17.000Z", "avg_line_length": 38.9754901961, "max_line_length": 257, "alphanum_fraction": 0.6663941643, "num_tokens": 4323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22418192331223902}}
{"text": "// This file is part of DM-HEOM (https://github.com/noma/dm-heom)\n//\n// Copyright (c) 2015-2019 Matthias Noack, Zuse Institute Berlin\n//\n// Licensed under the 3-clause BSD License, see accompanying LICENSE,\n// CONTRIBUTORS.md, and README.md for further information.\n\n#include <exception>\n#include <fstream>\n#include <iostream>\n\n#include <boost/format.hpp>\n#include <noma/num/meta_stepper.hpp>\n\n#include \"heom/command_line.hpp\"\n#include \"heom/common.hpp\"\n#include \"heom/dipole_matrix.hpp\"\n#include \"heom/dipole_pseudo_pathway.hpp\"\n#include \"heom/handle_main_exception.hpp\"\n#include \"heom/hierarchy_norm.hpp\"\n#include \"heom/instance.hpp\"\n#include \"heom/make_file_observer_list.hpp\"\n#include \"heom/ocl_config.hpp\"\n#include \"heom/ode.hpp\"\n#include \"heom/population_dynamics_solver.hpp\"\n#include \"heom/sites_to_states.hpp\"\n#include \"heom/static_fluorescence_config.hpp\"\n#include \"heom/thermal_state_search.hpp\"\n#include \"heom/thermal_state_search_config.hpp\"\n#include \"heom/thermal_state_search_solver.hpp\"\n\nnamespace bmt = ::heom::bmt;\nnamespace num = ::heom::num;\nnamespace ocl = ::heom::ocl;\nusing num::int_t;\nusing num::real_t;\nusing num::complex_t;\n\nint main(int argc, char* argv[])\n{\n\t// start runtime measurement\n\tbmt::timer app_timer;\n\n\t// output compile time configuration\n\tstd::cout << \"-------------------- Compile-Time Configuration ------------\" << std::endl;\n\theom::write_compile_config(std::cout);\n\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\tstd::exception_ptr eptr;\n\ttry {\n\t\t// command line parsing\n\t\theom::command_line command_line { argc, argv };\n\n\t\tstd::cout << \"Parsing OpenCL configuration from file: \" << command_line.ocl_config_filename() << std::endl;\n\t\theom::ocl_config ocl_config(command_line.ocl_config_filename());\n\t\tstd::cout << \"Parsing HEOM configuration from file: \" << command_line.heom_config_filename() << std::endl;\n\t\theom::static_fluorescence_config heom_config(command_line.heom_config_filename());\n\n\t\theom::hierarchy_graph complete_graph(heom_config.baths_number(), heom_config.baths_matsubaras(), heom_config.system_ado_depth());\n\n\t\tusing tss_solver_t = heom::thermal_state_search_solver<heom::ode, heom::thermal_state_search, heom::hierarchy_norm>;\n\t\tusing stepper_t = num::meta_stepper; // uses solver_stepper_type from config\n\t\tusing solver_t = heom::population_dynamics_solver<heom::ode, stepper_t, heom::hierarchy_norm>;\n\n\t\t// prepare output file (so we run into possible file errors before starting the computation)\n\t\tauto& observation_filename = heom_config.observations().get().front().get().second; // filename of first specified observation, guaranteed to exist by config checks\n\t\tstd::ofstream observation_file(observation_filename);\n\t\tif (observation_file.fail())\n\t\t\tthrow std::runtime_error(\"Error: could not open output file: \" + observation_filename);\n\n\t\t// linear absorption pseudo pathway with ground state\n\t\tconst auto& pathway_spec = heom::dipole_pseudo_pathway_wgs_spec;\n\t\tconst auto sts_mode = pathway_spec.sites_to_states_mode();\n\n\t\t// compute thermal state\n\t\theom::instance heom_instance_tss(heom_config, sts_mode, complete_graph);\n\n\t\t// OpenCL range\n\t\tocl::nd_range range {\n\t\t\t{}, // offset\n\t\t\t{1, static_cast<std::uint64_t>(heom_instance_tss.matrices())}, // global size\n\t\t\t{1, 1} // local size\n\t\t};\n\n\t\t// create thermal state search solver (tss) from configuration and instance\n\t\ttss_solver_t tss_solver(ocl_config, range, heom_config, heom_instance_tss);\n\n\t\tstd::cout << \"-------------------- OpenCL Runtime Configuration ----------\" << std::endl;\n\t\ttss_solver.write_ocl_runtime_config(std::cout);\n\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\t\t// determine thermal state until converged or max_steps is reached\n\t\tstd::cout << \"Computing thermal state...\" << std::endl;\n\t\tint_t i = 0;\n\t\tfor (; i < heom_config.thermal_state_search_max_steps(); ++i) {\n\t\t\ttss_solver.step_forward(1);\n\t\t\t// abort if convergence is reached\n\t\t\tif (tss_solver.test_convergence(heom_config.thermal_state_search_delta()))\n\t\t\t\tbreak;\n\t\t}\n\t\tif (i < heom_config.thermal_state_search_max_steps())\n\t\t\tstd::cout << \"... thermal state search converged after \" << i << \" steps.\" << std::endl;\n\t\telse\n\t\t\tstd::cout << \"... WARNING: thermal state search stopped after max_steps were reached (maybe increase max_steps, or delta).\" << std::endl;\n\n\t\t// synchronise instance with tss solver results, i.e. transfer compute device to host memory\n\t\ttss_solver.update_instance();\n\n\t\tstd::cout << \"-------- Thermal State Search Solver Runtime Summary -------\" << std::endl;\n\t\ttss_solver.write_runtime_summary(std::cout);\n\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\t\t// run the tss solver, no observations\n\t\tint_t iterations = heom_config.solver_steps() / heom_config.program_observe_steps();\n\t\tint_t steps_per_iteration = heom_config.program_observe_steps();\n\t\tint_t total_steps = iterations * heom_config.program_observe_steps();\n\n\t\t// output data structure for traces\n\t\tconst size_t num_dipole_matrices = heom_config.dipole_tensor_prefactors().size();\n\t\tconst int_t num_observations = iterations + 1;\n\t\tstd::vector<heom::matrix_trace_observation_view> observations(num_observations);\n\n\t\t// for progress estimate\n\t\tconst size_t solver_runs = num_dipole_matrices;\n\t\tsize_t solver_run = 0;\n\n\t\t// iterate over all dipoles and compute population dynamics\n\t\tfor (size_t tensor_index = 0; tensor_index < num_dipole_matrices; ++tensor_index) {\n\n\t\t\t// copy thermal state instance\n\t\t\theom::instance heom_instance { heom_instance_tss };\n\t\t\t// overwrite pseudo-hamiltonian of tss instance\n\t\t\theom_instance.set_hamiltonian(state_hamiltonian(heom_config.system_hamiltonian(), sts_mode));\n\n\t\t\t// OpenCL range\n\t\t\tocl::nd_range range {\n\t\t\t\t{}, // offset\n\t\t\t\t{1, static_cast<std::uint64_t>(heom_instance.matrices())}, // global size\n\t\t\t\t{1, 1} // local size\n\t\t\t};\n\n\t\t\t// create a solver from configuration and instance\n\t\t\tsolver_t solver(ocl_config, range, heom_config, heom_instance);\n\t\t\tstd::cout << \"-------------------- OpenCL Runtime Configuration ----------\" << std::endl;\n\t\t\tsolver.write_ocl_runtime_config(std::cout);\n\t\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\t\t\t++solver_run; // for progress estimate\n\n\t\t\t// compute dipole matrices\n\t\t\tauto get_dipole_matrix = [&](size_t spec_index) {\n\t\t\t\treturn heom::get_dipole_matrix_for_pathway(pathway_spec, spec_index, heom_config.system_sites(), heom_config, tensor_index);\n\t\t\t};\n\t\t\tauto dipole_matrix_minus = get_dipole_matrix(0);\n\t\t\tauto dipole_matrix_plus = get_dipole_matrix(1);\n\t\t\tdipole_matrix_minus.scale(heom::get_dipole_tensor_prefactor(pathway_spec, heom_config, tensor_index));\n\n\t\t\t// multiply D+ from right\n\t\t\tsolver.hierarchy_mmult_right(dipole_matrix_plus.data());\n\n\t\t\t// setup observer with pre-scaled D-\n\t\t\theom::matrix_trace_observer<solver_t> trace_observer(complete_graph, solver, dipole_matrix_minus.data()); // D- from left via observer\n\n\t\t\t// generate first observation with initial value\n\t\t\tobservations[0] += trace_observer.observe_trace(0.0);\n\n\t\t\t// write header once\n\t\t\tif (tensor_index == 0)\n\t\t\t\ttrace_observer.write_header(observation_file, true);\n\n\t\t\tfor (int_t i = 0; i < iterations; ++i) {\n\t\t\t\t// propagate\n\t\t\t\tsolver.step_forward(steps_per_iteration);\n\n\t\t\t\t// after propagation, we are at:\n\t\t\t\tconst auto current_step = (i + 1) * steps_per_iteration;\n\t\t\t\tconst real_t current_time = current_step * heom_config.solver_step_size();\n\n\t\t\t\t// observe\n\t\t\t\tobservations[i + 1] += trace_observer.observe_trace(current_time);\n\n\t\t\t\t// update status\n\t\t\t\theom::write_progress(current_step - 1, total_steps, solver_run, solver_runs, \"Calculation static fluorescence: \", std::cout);\n\t\t\t}\n\n\t\t\t// write_complex_matrix(result_buffer_top, heom_instance.states(), std::cout);\n\t\t\tstd::cout << \"-------------------- Solver Runtime Summary ----------------\" << std::endl;\n\t\t\tsolver.write_runtime_summary(std::cout);\n\t\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\t\t} // for tensor_index\n\n\t\t// write averaged traces\n\t\tfor (auto& obs : observations) {\n\t\t\tobs.avg(num_dipole_matrices);\n\t\t\tobservation_file << obs << '\\n';\n\t\t}\n\t\tobservation_file << std::flush; // tell the OS to write to disk\n\n\n\t\tstd::cout << \"-------------------- Memory Summary ------------------------\" << std::endl;\n\t\tstd::cout << \"local hierarchy buffer size:            \"\n\t\t          << boost::format(\"%11.2f MiB\\n\") % (heom_instance_tss.size_hierarchy_byte() / 1024.0 / 1024.0);\n\t\tstd::cout << \"local instance size:                    \"\n\t\t          << boost::format(\"%11.2f MiB\\n\") % (heom_instance_tss.allocated_byte() / 1024.0 / 1024.0);\n\t\tstd::cout << \"max. heap via aligned::allocate(..):    \"\n\t\t          << boost::format(\"%11.2f MiB\") % (heom::memory::aligned::instance().allocated_byte_max() / 1024.0 / 1024.0)\n\t\t          << \" (\"\n\t\t          << boost::format(\"count: %6i\") % heom::memory::aligned::instance().allocations_max()\n\t\t          << ')' << std::endl;\n\t\tstd::cout << \"max. OpenCL buffer allocations:         \"\n\t\t          << boost::format(\"%11.2f MiB\") % (tss_solver.ocl_helper().allocated_byte_max() / 1024.0 / 1024.0)\n\t\t          << \" (\"\n\t\t          << boost::format(\"count: %6i\") % tss_solver.ocl_helper().allocations_max()\n\t\t          << ')' << std::endl;\n//\t\tstd::cout << \"max. OpenCL buffer allocations:         \"\n//\t\t          << boost::format(\"%11.2f MiB\") % (solver.ocl_helper().allocated_byte_max() / 1024.0 / 1024.0)\n//\t\t          << \" (\"\n//\t\t          << boost::format(\"count: %6i\") % solver.ocl_helper().allocations_max()\n//\t\t          << ')' << std::endl;\n\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\t} catch (...) {\n\t\teptr = std::current_exception();\n\t}\n\tint ret = heom::handle_main_exception(eptr);\n\n\t// print application runtime\n\tstd::cout << \"time in main():\\t\" << boost::format(\"%11.2f\") % std::chrono::duration_cast<bmt::seconds>(bmt::duration(app_timer.elapsed())).count() << \" s\" << std::endl;\n\n\treturn ret;\n}\n\n\n", "meta": {"hexsha": "872173bf3cdf2b3761875692f9bbc1fe6924f8a6", "size": 10075, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dm-heom/src/app_static_fluorescence.cpp", "max_stars_repo_name": "noma/dm-heom", "max_stars_repo_head_hexsha": "85c94f947190064d21bd38544094731113c15412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-07-28T01:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T04:01:36.000Z", "max_issues_repo_path": "dm-heom/src/app_static_fluorescence.cpp", "max_issues_repo_name": "noma/dm-heom", "max_issues_repo_head_hexsha": "85c94f947190064d21bd38544094731113c15412", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dm-heom/src/app_static_fluorescence.cpp", "max_forks_repo_name": "noma/dm-heom", "max_forks_repo_head_hexsha": "85c94f947190064d21bd38544094731113c15412", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-04T15:20:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T15:16:40.000Z", "avg_line_length": 43.0555555556, "max_line_length": 169, "alphanum_fraction": 0.6644168734, "num_tokens": 2588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22418192331223902}}
{"text": "#include <algorithm>\n#include <boost/range/irange.hpp>\n#include <cmath>\n#include <map>\n#include <memory>\n#include <set>\n\n#include \"bounding_edge.hpp\"\n#include \"kd_tree_node.hpp\"\n#include \"rtc_log.hpp\"\n#include \"scoped_timer.hpp\"\n\nnamespace rtc\n{\nkd_tree::kd_tree(const rtc::scene_model& ss) : bbox{ss.points}\n{\n  SCOPE_TIME_COUNTER;\n  const auto& p = ss.points;\n  const auto& t = ss.triangles;\n  const std::uint32_t max_depth = 1.3F * std::log2(t.size()) + 8;\n\n  auto make_bbox = [](auto& p, auto& tr) noexcept {\n    return rtc::bounding_box{p[tr.vertex_a()], p[tr.vertex_b()], p[tr.vertex_c()]};\n  };\n\n  rtc::bounding_box node_bbox{p};\n  std::vector<std::uint32_t> v(t.size());\n  std::vector<bounding_box> primitive_bboxes;\n  edge_buffer_array_t edge_buffer{\n      edge_buffer_t(2 * t.size()), edge_buffer_t(2 * t.size()), edge_buffer_t(2 * t.size())};\n\n  primitive_bboxes.reserve(t.size());\n\n  std::for_each(t.begin(), t.end(), [&](auto& t) { primitive_bboxes.push_back(make_bbox(p, t)); });\n  std::generate(v.begin(), v.end(), [i = 0]() mutable { return i++; });\n\n  build_tree(root, node_bbox, std::move(v), primitive_bboxes, edge_buffer, max_depth);\n}\n\nauto kd_tree::cbegin(const rtc::math_ray& ray) const noexcept -> kd_tree::const_iterator\n{\n  if (auto range = bbox.intersection_values_for(ray))\n  {\n    const auto [tmin, tmax] = range.value();\n    return const_iterator{ray, {root.get(), tmin, tmax}};\n  }\n\n  return const_iterator{};\n}\n\nauto kd_tree::cend(const rtc::math_ray&) const noexcept -> kd_tree::const_iterator { return const_iterator{}; }\n\nkd_tree::~kd_tree() = default;\nkd_tree::kd_tree(kd_tree&&) noexcept = default;\nauto kd_tree::operator=(kd_tree&&) noexcept -> kd_tree& = default;\n\nauto kd_tree::compute_node_split_paramters(edge_buffer_array_t& edge_buffer,\n                                           const std::vector<std::uint32_t>& tr,\n                                           const rtc::bounding_box& node_bbox,\n                                           const std::vector<rtc::bounding_box>& primitive_bboxes)\n{\n  constexpr int isect_cost{80};\n  constexpr int traversal_cost{1};\n  constexpr rtc_float empty_bonus{0.5F};\n  const auto node_diagonal{node_bbox.diagonal()};\n  const rtc_float invTotalSA{1.0F / node_bbox.surface_area()};\n  const rtc_float old_cost{isect_cost * static_cast<rtc_float>(tr.size())};\n\n  int retries{0};\n  int best_axis{-1};\n  int best_offset{-1};\n  rtc::axis axis{node_bbox.maximum_extent()};\n  rtc_float best_cost{std::numeric_limits<rtc_float>::max()};\n\n  do\n  {\n    const rtc::axis axis2{next(axis)}, axis3{next(axis2)};\n    int below{}, above(tr.size());\n\n    for (const auto i : boost::irange<std::size_t>(0, tr.size()))\n    {\n      const rtc::bounding_box& box{primitive_bboxes[tr[i]]};\n      edge_buffer[int(axis)][2 * i] = {box.min_boundary().axis(axis), tr[i], bounding_edge_point::start};\n      edge_buffer[int(axis)][2 * i + 1] = {box.max_boundary().axis(axis), tr[i], bounding_edge_point::end};\n    }\n\n    std::sort(&edge_buffer[int(axis)][0], &edge_buffer[int(axis)][0] + 2 * tr.size());\n\n    for (const auto i : boost::irange<std::size_t>(0, 2 * tr.size()))\n    {\n      const rtc::bounding_edge_point& bp{edge_buffer[int(axis)][i]};\n      const auto edge_t = bp.value;\n\n      if (bp.type == bounding_edge_point::end)\n        --above;\n      if (bp.type == bounding_edge_point::start)\n        ++below;\n\n      if (edge_t > node_bbox.min_boundary().axis(axis) && edge_t < node_bbox.max_boundary().axis(axis))\n      {\n        const rtc_float belowSA{2 * (node_diagonal.axis(axis2) * node_diagonal.axis(axis3) +\n                                     (edge_t - node_bbox.min_boundary().axis(axis)) *\n                                         (node_diagonal.axis(axis2) + node_diagonal.axis(axis3)))};\n\n        const rtc_float aboveSA{2 * (node_diagonal.axis(axis2) * node_diagonal.axis(axis3) +\n                                     (node_bbox.max_boundary().axis(axis) - edge_t) *\n                                         (node_diagonal.axis(axis2) + node_diagonal.axis(axis3)))};\n\n        const rtc_float pBelow{belowSA * invTotalSA};\n        const rtc_float pAbove{aboveSA * invTotalSA};\n        const rtc_float eb{(above == 0 || below == 0) ? empty_bonus : 0};\n        const rtc_float cost{traversal_cost + isect_cost * (1 - eb) * (pBelow * below + pAbove * above)};\n\n        if (cost < best_cost)\n        {\n          best_cost = cost;\n          best_axis = int(axis);\n          best_offset = i;\n        }\n      }\n    }\n  } while ((best_axis == -1) && ((axis = next(axis), retries++) < 2));\n\n  return std::make_tuple(best_axis, best_offset, best_cost, old_cost);\n}\n\nauto kd_tree::split_triangles(std::vector<std::uint32_t>&& tr_init,\n                              const edge_buffer_array_t& edge_buffer,\n                              const std::uint32_t best_axis,\n                              const std::uint32_t best_offset)\n{\n  std::vector<std::uint32_t> tr{std::move(tr_init)}, left_set{}, right_set{};\n\n  left_set.reserve(best_offset);\n  right_set.reserve(2 * tr.size() - best_offset);\n\n  for (auto i = 0; i < best_offset; ++i)\n  {\n    if (edge_buffer[best_axis][i].type == bounding_edge_point::start)\n    {\n      left_set.emplace_back(edge_buffer[best_axis][i].tr_index);\n    }\n  }\n\n  for (auto i = best_offset + 1; i < 2 * tr.size(); ++i)\n  {\n    if (edge_buffer[best_axis][i].type == bounding_edge_point::end)\n    {\n      right_set.emplace_back(edge_buffer[best_axis][i].tr_index);\n    }\n  }\n  return std::make_tuple(std::move(left_set), std::move(right_set));\n}\n\nvoid kd_tree::build_tree(std::unique_ptr<tree_node>& node,\n                         rtc::bounding_box node_bbox,\n                         std::vector<std::uint32_t> tr,\n                         const std::vector<rtc::bounding_box>& primitive_bboxes,\n                         edge_buffer_array_t& edge_buffer,\n                         const std::uint32_t depth,\n                         std::uint32_t bad_refines)\n{\n  const auto create_leaf_node = [&node, &tr] {\n    node = std::make_unique<tree_node>();\n    node->triangles = std::make_unique<kd_tree::value_type>();\n    node->triangles->insert(node->triangles->end(), tr.begin(), tr.end());\n  };\n\n  if (tr.size() <= 1 || !depth)\n    return create_leaf_node();\n\n  const auto [axis, offset, cost, old_cost] =\n      compute_node_split_paramters(edge_buffer, tr, node_bbox, primitive_bboxes);\n\n  bad_refines += (cost > old_cost) ? 1 : 0;\n\n  auto no_use_of_spliting_node = [old_cost = old_cost, cost = cost, axis = axis, &bad_refines, &tr] {\n    return ((cost > 4 * old_cost) && (tr.size() < 16)) || (axis == -1) || (bad_refines == 3);\n  };\n\n  if (no_use_of_spliting_node())\n    return create_leaf_node();\n\n  auto [left_set, right_set] = split_triangles(std::move(tr), edge_buffer, axis, offset);\n  bounding_box left_bbox{node_bbox}, right_bbox{node_bbox};\n\n  node = std::make_unique<tree_node>();\n  node->axis = {edge_buffer[axis][offset].value, static_cast<rtc::axis>(axis)};\n\n  left_bbox.max_boundary().axis(node->axis.split) = right_bbox.min_boundary().axis(node->axis.split) = node->axis.value;\n\n  build_tree(node->left, left_bbox, std::move(left_set), primitive_bboxes, edge_buffer, depth - 1, bad_refines);\n  build_tree(node->right, right_bbox, std::move(right_set), primitive_bboxes, edge_buffer, depth - 1, bad_refines);\n}\n\n}  // namespace rtc\n", "meta": {"hexsha": "934d0d8d87f3ac9efdfc899063067e8859608ea0", "size": 7335, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kd_tree/source/kd_tree.cpp", "max_stars_repo_name": "Abergard/rtc", "max_stars_repo_head_hexsha": "e0cdbbb4a005b7d9f3b10d1a519fcb6be876e65f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-05-25T01:03:38.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-29T07:43:49.000Z", "max_issues_repo_path": "kd_tree/source/kd_tree.cpp", "max_issues_repo_name": "Abergard/rtc", "max_issues_repo_head_hexsha": "e0cdbbb4a005b7d9f3b10d1a519fcb6be876e65f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-24T22:16:30.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T22:16:30.000Z", "max_forks_repo_path": "kd_tree/source/kd_tree.cpp", "max_forks_repo_name": "Abergard/rtc", "max_forks_repo_head_hexsha": "e0cdbbb4a005b7d9f3b10d1a519fcb6be876e65f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-24T19:12:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-24T19:12:44.000Z", "avg_line_length": 37.2335025381, "max_line_length": 120, "alphanum_fraction": 0.627402863, "num_tokens": 1927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558604, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.22412636580441697}}
{"text": "#ifndef STAN_MATH_TORSTEN_PKMODEL_MODELPARAMETERS_HPP\n#define STAN_MATH_TORSTEN_PKMODEL_MODELPARAMETERS_HPP\n\n#include <stan/math/prim/fun/to_array_1d.hpp>\n#include <stan/math/torsten/ev_history.hpp>\n#include <stan/math/torsten/PKModel/ExtractVector.hpp>\n#include <stan/math/torsten/PKModel/SearchReal.hpp>\n#include <Eigen/Dense>\n#include <algorithm>\n#include <vector>\n\nnamespace torsten {\n\n/**\n * The ModelParameters class defines objects that contain the parameters of\n * a model at a given time.\n */\ntemplate<typename T_time, typename T_parameters, typename T_biovar, typename T_tlag>\nstruct ModelParameters {\n  double time_;\n  std::vector<T_parameters> theta_;\n  int nrow, ncol;\n  std::vector<T_biovar> biovar_;\n  std::vector<T_tlag> tlag_;\n\n  ModelParameters() {}\n\n  ModelParameters(const T_time& time,\n                  const Eigen::Matrix<T_parameters, Eigen::Dynamic, Eigen::Dynamic>& K,\n                  const std::vector<T_biovar>& biovar,\n                  const std::vector<T_tlag>& tlag)\n    : time_(stan::math::value_of(time)), theta_(K.size()), nrow(K.rows()), ncol(K.cols()), biovar_(biovar), tlag_(tlag)\n  {\n    Eigen::Matrix<T_parameters, -1, -1>::Map(theta_.data(), nrow, ncol) = K;\n  }\n\n  ModelParameters(const T_time& time,\n                  const std::vector<T_parameters>& theta,\n                  const std::vector<T_biovar>& biovar,\n                  const std::vector<T_tlag>& tlag)\n    : time_(stan::math::value_of(time)), theta_(theta), biovar_(biovar), tlag_(tlag) {}\n\n  /**\n   * Adds parameters. Useful for the mixed solver, where\n   * we want to augment the parameters with the intial PK\n   * states when calling the numerical integrator.\n   */\n  template <typename T>\n  ModelParameters<T_time, T, T_biovar, T_tlag>\n  augment(const std::vector<T>& thetaAdd) const {\n    std::vector<T> theta(theta_.size());\n    for (size_t i = 0; i < theta.size(); i++) theta[i] = theta_[i];\n    for (size_t i = 0; i < thetaAdd.size(); i++) theta.push_back(thetaAdd[i]);\n    return\n      ModelParameters<T_time, T, T_biovar, T_tlag>\n        (time_, theta, biovar_, tlag_);\n  }\n\n  template <typename T>\n  ModelParameters<T_time, T, T_biovar, T_tlag>\n  augment(const Eigen::Matrix<T, Eigen::Dynamic, 1>& thetaAdd)\n  const {\n    return augment(stan::math::to_array_1d(thetaAdd));\n  }\n\n  /**\n   * Edit time stored in parameter object.\n   */\n  void time(double time) {\n    time_ = time;\n  }\n\n  int CountParameters() const {\n    return theta_.size();\n  }\n\n  // access functions   // FIX ME - name should be get_theta.\n  double get_time() const { return time_; }\n  std::vector<T_parameters> get_RealParameters(bool return_matrix) const {\n    if (return_matrix) {\n      auto k = get_K();\n      std::vector<T_parameters> par(k.size());\n      for (size_t j = 0; j < par.size(); ++j) par[j] = k(j);\n      return par;\n    } else {\n      return theta_;\n    }\n  }\n  std::vector<T_biovar> get_biovar() const {\n    return biovar_;\n  }\n  std::vector<T_tlag> get_tlag() const {\n    return tlag_;\n  }\n  Eigen::Matrix<T_parameters, Eigen::Dynamic, Eigen::Dynamic> get_K() const {\n    Eigen::Matrix<T_parameters, -1, -1> res(nrow, ncol);\n    res = Eigen::Matrix<T_parameters, -1, -1>::Map(theta_.data(), nrow, ncol);\n    return res;\n  }\n\n  inline ModelParameters<double, double, double, double> to_value() const {\n    return ModelParameters<double, double, double, double>\n      (time_, \n       stan::math::value_of(theta_),\n       stan::math::value_of(biovar_),\n       stan::math::value_of(tlag_));\n  }\n};\n\n  template<typename T>\n  struct is_matrix : std::false_type {};\n  \n  template<typename T, int R, int C>\n  struct is_matrix<Eigen::Matrix<T, R, C> > : std::true_type {};\n  \n/**\n * The ModelParameterHistory class defines objects that contain a vector\n * of ModelParameters, along with a series of functions that operate on\n * them.\n */\ntemplate<typename T_time, typename T4_container, typename T5, typename T6>\nstruct ModelParameterHistory {\n  using T4 = typename stan::value_type<T4_container>::type;\n  using Param = std::pair<double, std::array<int, 3> >;\n\n  static const bool has_matrix_param;\n\n  std::vector<Param> index;\n  const std::vector<T4_container>& theta_;\n  const std::vector<std::vector<T5> >& biovar_;\n  const std::vector<std::vector<T6> >& tlag_;\n\n  template<typename T0>\n   ModelParameterHistory(const std::vector<T0>& time,\n                        const std::vector<T4_container>& theta,\n                        const std::vector<std::vector<T5> >& biovar,\n                        const std::vector<std::vector<T6> >& tlag) :\n     ModelParameterHistory(0, time.size(), time,\n                           0, theta.size(), theta,\n                           0, biovar.size(), biovar,\n                           0, tlag.size(), tlag)\n  {}\n\n  /*\n   * For population data in form of ragged array, we need to\n   * generate individual parameter history given the entire\n   * population data and the location of the\n   * inidividual. However, @c theta, @c biovar and @c tlag\n   * could have different lengths, so for each variable we\n   * need an index that points to the range that belongs to the individual.\n   * Note that if all three variables are of size 1, their\n   * time is set to be the first entry of the @c time vector\n   */\n  template<typename T0>\n  ModelParameterHistory(int ibegin, int isize,\n                        const std::vector<T0>& time,\n                        int ibegin_theta, int isize_theta,\n                        const std::vector<T4_container>& theta,\n                        int ibegin_biovar, int isize_biovar,\n                        const std::vector<std::vector<T5> >& biovar,\n                        int ibegin_tlag, int isize_tlag,\n                        const std::vector<std::vector<T6> >& tlag) :\n    index(isize),\n    theta_(theta),\n    biovar_(biovar),\n    tlag_(tlag)\n  {\n    for (int i = 0; i < isize; ++i) {\n      int j = isize_theta   > 1 ? ibegin_theta  + i : ibegin_theta;\n      int k = isize_biovar  > 1 ? ibegin_biovar + i : ibegin_biovar;\n      int l = isize_tlag    > 1 ? ibegin_tlag   + i : ibegin_tlag;\n      index[i] = std::make_pair<double, std::array<int, 3> >(stan::math::value_of(time[ibegin + i]), {j, k, l });\n    }\n    Sort();\n  }\n\n  const T4_container& model_param(int i) const {\n    return theta_[index[i].second[0]];\n  }\n\n  ModelParameters<T_time, T4, T5, T6> GetModelParameters(int i) const {\n    return ModelParameters<T_time, T4, T5, T6>(std::get<0>(index[i]), theta_[std::get<1>(index[i])[0]], biovar_[std::get<1>(index[i])[1]], tlag_[std::get<1>(index[i])[2]]);\n  }\n\n  /**\n   * MPV.size gives us the number of events.\n   * MPV[i].RealParameters.size gives us the number of\n   * ODE parameters for the ith event.\n   * \n   * FIX ME - rename this GetValueTheta\n   */\n  inline const T4& GetValue(int iEvent, int iParameter) const {\n    return theta_[std::get<1>(index[iEvent])[0]][iParameter];\n  }\n\n  inline const T5& GetValueBio(int iEvent, int iParameter) const {\n    return biovar_[std::get<1>(index[iEvent])[1]][iParameter];\n  }\n\n  inline const T6& GetValueTlag(int iEvent, int iParameter) const {\n    return tlag_[std::get<1>(index[iEvent])[2]][iParameter];\n  }\n\n  inline int get_size() const {\n    return index.size();\n  }\n\n  void Sort() {\n    std::sort(index.begin(), index.end(),\n              [](const Param& a, const Param& b)\n              { return std::get<0>(a) < std::get<0>(b); });\n  }\n\n  bool Check() {\n  // check that elements are in chronological order.\n    int i = index.size() - 1;\n    bool ordered = true;\n\n    while (i > 0 && ordered) {\n      ordered = (std::get<0>(index[i]) >= std::get<0>(index[i-1]));\n      i--;\n    }\n    return ordered;\n  }\n\n  /**\n   * COMPLETE MODEL PARAMETERS\n   *\n   * Completes parameters so that it contains model parameters for each event \n   * in events. If parameters contains only one set of parameters (case where\n   * the parameters are constant), this set is replicated for each event in\n   * events. Otherwise a new parameter vector is added for each new event \n   * (isnew = true). This parameter vector is identical to the parameter vector\n   * at the subsequent event. If the new event occurs at a time posterior to\n   * the time of the last event, than the new vector parameter equals the\n   * parameter vector of the last event. This amounts to doing an LOCF\n   * (Last Observation Carried Forward):\n   * Three cases:\n   * (a) The time of the new event is higher than the time of the last\n   *     parameter vector in parameters (k = len_parameters).\n   *     Create a parameter vector at the the time of the new event,\n   *     with the parameters of the last parameter vector.\n   *     (Last Observation Carried Forward)\n   * (b) The time of the new event matches the time of a parameter vector\n   *     in parameters. This parameter vector gets replicated.\n   * (c) (a) is not verified and no parameter vector occurs at the time\n   *     of the new event. A new parameter vector is created at the time\n   *     of the new event, and its parameters are equal to the parameters\n   *     of the subsequent parameter vector in parameters.\n   *\n   * Since both @c index and events @c index are sorted\n   * in time, we always move paramtter pointer to events\n   *\n   * Events and Parameters are sorted at the end of the procedure.\n   *\n   * @param[in] parameters at each event\n   * @param[in] events elements (following NONMEM convention) at each event\n   * @return - modified parameters and events.\n   */\n  template<typename T0, typename T_p1, typename T_p2, typename T_p3>\n  void CompleteParameterHistory(torsten::EventHistory<T0, T_p1, T_p2, T_p3, T6>& events) {\n    int nEvent = events.size();\n    assert(nEvent > 0);\n    int len_Parameters = index.size();  // numbers of events for which parameters are determined\n    assert(len_Parameters > 0);\n\n    if (!Check()) Sort();\n    if (!events.Check()) events.Sort();\n    index.resize(nEvent);\n\n    int iEvent = 0;\n    for (int i = 0; i < len_Parameters - 1; i++) {\n      while (events.isnew(iEvent)) iEvent++;  // skip new events\n      assert(std::get<0>(index[i]) == events.time(iEvent));  // compare time of \"old' events to time of parameters.\n      iEvent++;\n    }\n\n    if (len_Parameters == 1)  {\n      for (int i = 0; i < nEvent; i++) {\n        index[i] = std::make_pair<double, std::array<int, 3> >(stan::math::value_of(events.time(i)) , std::array<int,3>(std::get<1>(index[0])));\n        events.index[i][3] = 0;\n      }\n    } else {  // parameters are event dependent.\n      std::vector<double> times(nEvent, 0);\n      for (int i = 0; i < nEvent; i++) times[i] = index[i].first;\n      iEvent = 0;\n\n      Param newParameter;\n      int j = 0;\n      std::vector<Param>::const_iterator lower = index.begin();\n      std::vector<Param>::const_iterator it_param_end = index.begin() + len_Parameters;\n      for (int iEvent = 0; iEvent < nEvent; ++iEvent) {\n        if (events.isnew(iEvent)) {\n          // Find the index corresponding to the time of the new event in the\n          // times vector.\n          const double t = stan::math::value_of(events.time(iEvent));\n          lower = std::lower_bound(lower, it_param_end, t,\n                                   [](const Param& t1, const double& t2) {return t1.first < t2;});\n          newParameter = lower == (it_param_end) ? index[len_Parameters-1] : *lower;\n          newParameter.first = t;\n          index[len_Parameters + j] = newParameter;\n          events.index[iEvent][3] = 0;\n          j++;\n        }\n      }\n    }\n    Sort();\n  }\n};\n\ntemplate<typename T_time, typename T4_container, typename T5, typename T6>\nconst bool ModelParameterHistory<T_time, T4_container, T5, T6>::has_matrix_param = is_matrix<T4_container>::value;\n\n}\n\n#endif\n", "meta": {"hexsha": "9ce25a307521cfdc1a400952e233ea71dc3061db", "size": 11679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PKModel/ModelParameters.hpp", "max_stars_repo_name": "metrumresearchgroup/torsten_math", "max_stars_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "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": "PKModel/ModelParameters.hpp", "max_issues_repo_name": "metrumresearchgroup/torsten_math", "max_issues_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-27T23:53:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T23:57:43.000Z", "max_forks_repo_path": "PKModel/ModelParameters.hpp", "max_forks_repo_name": "metrumresearchgroup/torsten_math", "max_forks_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8422712934, "max_line_length": 172, "alphanum_fraction": 0.6351571196, "num_tokens": 3123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543457, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22404406447537317}}
{"text": "#ifndef DART_NEURAL_SNAPSHOT_HPP_\n#define DART_NEURAL_SNAPSHOT_HPP_\n\n#include <unordered_map>\n#include <vector>\n\n#include <Eigen/Dense>\n\n#include \"dart/neural/DifferentiableContactConstraint.hpp\"\n#include \"dart/neural/NeuralConstants.hpp\"\n#include \"dart/neural/NeuralUtils.hpp\"\n#include \"dart/neural/WithRespectTo.hpp\"\n#include \"dart/performance/PerformanceLog.hpp\"\n#include \"dart/simulation/World.hpp\"\n\nnamespace dart {\n\nusing namespace performance;\n\nnamespace neural {\n\nclass BackpropSnapshot\n{\n  friend class MappedBackpropSnapshot;\n\npublic:\n  /// This saves a snapshot from a forward pass, with all the info we need in\n  /// order to efficiently compute a backwards pass. Crucially, the positions\n  /// must all be snapshots from before the timestep, yet this constructor must\n  /// be called after the timestep.\n  BackpropSnapshot(\n      simulation::WorldPtr world,\n      Eigen::VectorXs preStepPosition,\n      Eigen::VectorXs preStepVelocity,\n      Eigen::VectorXs preStepTorques,\n      Eigen::VectorXs preConstraintVelocities,\n      Eigen::VectorXs preStepLCPCache);\n\n  /// This computes the implicit backprop without forming intermediate\n  /// Jacobians. It takes a LossGradient with the position and velocity vectors\n  /// filled it, though the loss with respect to torque is ignored and can be\n  /// null. It returns a LossGradient with all three values filled in, position,\n  /// velocity, and torque.\n  void backprop(\n      simulation::WorldPtr world,\n      LossGradient& thisTimestepLoss,\n      const LossGradient& nextTimestepLoss,\n      PerformanceLog* perfLog = nullptr,\n      bool exploreAlternateStrategies = false);\n\n  /// This computes backprop in the high-level RL API's space, use `state` and\n  /// `action` as the primitives we're taking gradients wrt to.\n  LossGradientHighLevelAPI backpropState(\n      simulation::WorldPtr world,\n      const Eigen::VectorXs& nextTimestepStateLossGrad,\n      PerformanceLog* perfLog = nullptr,\n      bool exploreAlternateStrategies = false);\n\n  /// This zeros out any components of the gradient that would want to push us\n  /// out of the box-bounds encoded in the world for pos, vel, or force.\n  void clipLossGradientsToBounds(\n      simulation::WorldPtr world,\n      Eigen::VectorXs& lossWrtPos,\n      Eigen::VectorXs& lossWrtVel,\n      Eigen::VectorXs& lossWrtForce);\n\n  /// This computes and returns the whole vel-vel jacobian. For backprop, you\n  /// don't actually need this matrix, you can compute backprop directly. This\n  /// is here if you want access to the full Jacobian for some reason.\n  const Eigen::MatrixXs& getVelVelJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This computes and returns the whole pos-vel jacobian. For backprop, you\n  /// don't actually need this matrix, you can compute backprop directly. This\n  /// is here if you want access to the full Jacobian for some reason.\n  const Eigen::MatrixXs& getPosVelJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This computes and returns the whole force-vel jacobian. For backprop, you\n  /// don't actually need this matrix, you can compute backprop directly. This\n  /// is here if you want access to the full Jacobian for some reason.\n  const Eigen::MatrixXs& getControlForceVelJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This computes and returns the whole mass-vel jacobian. For backprop, you\n  /// don't actually need this matrix, you can compute backprop directly. This\n  /// is here if you want access to the full Jacobian for some reason.\n  const Eigen::MatrixXs& getMassVelJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This computes and returns the whole pos-pos jacobian. For backprop, you\n  /// don't actually need this matrix, you can compute backprop directly. This\n  /// is here if you want access to the full Jacobian for some reason.\n  const Eigen::MatrixXs& getPosPosJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This computes and returns the whole vel-pos jacobian. For backprop, you\n  /// don't actually need this matrix, you can compute backprop directly. This\n  /// is here if you want access to the full Jacobian for some reason.\n  const Eigen::MatrixXs& getVelPosJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This computes and returns the component of the pos-pos and pos-vel\n  /// jacobians due to bounce approximation. For backprop, you don't actually\n  /// need this matrix, you can compute backprop directly. This is here if you\n  /// want access to the full Jacobian for some reason.\n  const Eigen::MatrixXs& getBounceApproximationJacobian(\n      simulation::WorldPtr world, PerformanceLog* perfLog = nullptr);\n\n  /// This returns the Jacobian for state_t -> state_{t+1}.\n  Eigen::MatrixXs getStateJacobian(simulation::WorldPtr world);\n\n  /// This returns the Jacobian for action_t -> state_{t+1}.\n  Eigen::MatrixXs getActionJacobian(simulation::WorldPtr world);\n\n  /// Returns a concatenated vector of all the Skeletons' position()'s in the\n  /// World, in order in which the Skeletons appear in the World's\n  /// getSkeleton(i) returns them, BEFORE the timestep.\n  Eigen::VectorXs getPreStepPosition();\n\n  /// Returns a concatenated vector of all the Skeletons' velocity()'s in the\n  /// World, in order in which the Skeletons appear in the World's\n  /// getSkeleton(i) returns them, BEFORE the timestep.\n  Eigen::VectorXs getPreStepVelocity();\n\n  /// Returns a concatenated vector of all the joint torques that were applied\n  /// during the forward pass, BEFORE the timestep.\n  Eigen::VectorXs getPreStepTorques();\n\n  /// Returns a concatenated vector of all the Skeletons' velocity()'s in the\n  /// World, in order in which the Skeletons appear in the World's\n  /// getSkeleton(i) returns them, AFTER integrating forward dynamics but BEFORE\n  /// running the LCP.\n  Eigen::VectorXs getPreConstraintVelocity();\n\n  /// Returns a concatenated vector of all the Skeletons' position()'s in the\n  /// World, in order in which the Skeletons appear in the World's\n  /// getSkeleton(i) returns them, AFTER the timestep.\n  Eigen::VectorXs getPostStepPosition();\n\n  /// Returns a concatenated vector of all the Skeletons' velocity()'s in the\n  /// World, in order in which the Skeletons appear in the World's\n  /// getSkeleton(i) returns them, AFTER the timestep.\n  Eigen::VectorXs getPostStepVelocity();\n\n  /// Returns a concatenated vector of all the joint torques that were applied\n  /// during the forward pass, AFTER the timestep.\n  Eigen::VectorXs getPostStepTorques();\n\n  /// Returns the LCP's cached solution from before the step\n  const Eigen::VectorXs& getPreStepLCPCache();\n\n  /////////////////////////////////////////////////////////////////////////////\n  /// Just public for testing\n  /////////////////////////////////////////////////////////////////////////////\n\n  /// This returns the A_c matrix. You shouldn't ever need this matrix, it's\n  /// just here to enable testing.\n  Eigen::MatrixXs getClampingConstraintMatrix(simulation::WorldPtr world);\n\n  /// This returns the V_c matrix. You shouldn't ever need this matrix, it's\n  /// just here to enable testing.\n  Eigen::MatrixXs getMassedClampingConstraintMatrix(simulation::WorldPtr world);\n\n  /// This returns the A_ub matrix. You shouldn't ever need this matrix, it's\n  /// just here to enable testing.\n  Eigen::MatrixXs getUpperBoundConstraintMatrix(simulation::WorldPtr world);\n\n  /// This returns the V_c matrix. You shouldn't ever need this matrix, it's\n  /// just here to enable testing.\n  Eigen::MatrixXs getMassedUpperBoundConstraintMatrix(\n      simulation::WorldPtr world);\n\n  /// This returns the E matrix. You shouldn't ever need this matrix, it's\n  /// just here to enable testing.\n  Eigen::MatrixXs getUpperBoundMappingMatrix();\n\n  /// This returns the B matrix. You shouldn't ever need this matrix, it's\n  /// just here to enable testing.\n  Eigen::MatrixXs getBouncingConstraintMatrix(simulation::WorldPtr world);\n\n  /// This returns the mass matrix for the whole world, a block diagonal\n  /// concatenation of the skeleton mass matrices.\n  Eigen::MatrixXs getMassMatrix(\n      simulation::WorldPtr world, bool forFiniteDifferencing = false);\n\n  /// This returns the inverse mass matrix for the whole world, a block diagonal\n  /// concatenation of the skeleton inverse mass matrices.\n  Eigen::MatrixXs getInvMassMatrix(\n      simulation::WorldPtr world, bool forFiniteDifferencing = false);\n\n  /// This is the subset of the A matrix from the original LCP that corresponds\n  /// to clamping indices.\n  Eigen::MatrixXs getClampingAMatrix();\n\n  /// This returns the pos-C(pos,vel) Jacobian for the whole world, a block\n  /// diagonal concatenation of the skeleton pos-C(pos,vel) Jacobians.\n  Eigen::MatrixXs getPosCJacobian(simulation::WorldPtr world);\n\n  /// This returns the vel-C(pos,vel) Jacobian for the whole world, a block\n  /// diagonal concatenation of the skeleton vel-C(pos,vel) Jacobians.\n  Eigen::MatrixXs getVelCJacobian(simulation::WorldPtr world);\n\n  /// This computes and returns the whole vel-vel jacobian by finite\n  /// differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceVelVelJacobian(\n      simulation::WorldPtr world, bool useRidders = true);\n\n  /// This computes and returns the whole vel-vel jacobian by Ridders\n  /// extrapolated finite differences. This is SUPER DUPER SLOW,\n  /// and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersVelVelJacobian(\n      simulation::WorldPtr world);\n\n  /// This computes and returns the whole pos-C(pos,vel) jacobian by finite\n  /// differences. This is SUPER SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferencePosVelJacobian(\n      simulation::WorldPtr world, bool useRidders = true);\n\n  /// This computes and returns the whole pos-C(pos,vel) jacobian by Ridders\n  /// extrapolated finite differences. This is SUPER DUPER SLOW,\n  /// and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersPosVelJacobian(\n      simulation::WorldPtr world);\n\n  /// This computes and returns the whole force-vel jacobian by finite\n  /// differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceForceVelJacobian(\n      simulation::WorldPtr world, bool useRidders = true);\n\n  /// This computes and returns the whole force-vel jacobian by Ridders\n  /// extrapolated finite differences. This is SUPER DUPER SLOW,\n  /// and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersForceVelJacobian(\n      simulation::WorldPtr world);\n\n  /// This computes and returns the whole mass-vel jacobian by finite\n  /// differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceMassVelJacobian(\n      simulation::WorldPtr world, bool useRidders = true);\n\n  /// This computes and returns the whole mass-vel jacobian by Ridders\n  /// extrapolated finite differences. This is SUPER DUPER SLOW,\n  /// and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersMassVelJacobian(\n      simulation::WorldPtr world);\n\n  /// This computes and returns the whole pos-pos jacobian by finite\n  /// differences. This is SUPER SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferencePosPosJacobian(\n      simulation::WorldPtr world,\n      std::size_t subdivisions = 20,\n      bool useRidders = true);\n\n  /// This computes and returns the whole pos-pos jacobian by Ridders\n  /// extrapolated finite differences. This is SUPER DUPER SUPER SLOW,\n  /// and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersPosPosJacobian(\n      simulation::WorldPtr world, std::size_t subdivisions = 20);\n\n  /// This computes and returns the whole vel-pos jacobian by finite\n  /// differences. This is SUPER SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceVelPosJacobian(\n      simulation::WorldPtr world,\n      std::size_t subdivisions = 20,\n      bool useRidders = true);\n\n  /// This computes and returns the whole vel-pos jacobian by Ridders\n  /// extrapolated finite differences. This is SUPER DUPER SUPER SLOW,\n  /// and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersVelPosJacobian(\n      simulation::WorldPtr world, std::size_t subdivisions = 20);\n\n  /// This computes and returns the whole wrt-vel jacobian by finite\n  /// differences. This is SUPER SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceVelJacobianWrt(\n      simulation::WorldPtr world, WithRespectTo* wrt, bool useRidders = true);\n\n  /// This computes and returns the whole wrt-vel jacobian by Ridders\n  /// extrapolated finite differences. This is SUPER SUPER SLOW,\n  /// and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersVelJacobianWrt(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This computes and returns the whole wrt-pos jacobian by finite\n  /// differences. This is SUPER SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferencePosJacobianWrt(\n      simulation::WorldPtr world, WithRespectTo* wrt, bool useRidders = true);\n\n  /// This computes and returns the whole wrt-pos jacobian by Ridders\n  /// extrapolated finite differences. This is SUPER SUPER SLOW,\n  /// and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersPosJacobianWrt(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the P_c matrix. You shouldn't ever need this matrix, it's\n  /// just here to enable testing.\n  Eigen::MatrixXs getProjectionIntoClampsMatrix(\n      simulation::WorldPtr world, bool forFiniteDifferencing = false);\n\n  /// This replaces x with the result of M*x in place, without explicitly\n  /// forming M\n  Eigen::VectorXs implicitMultiplyByMassMatrix(\n      simulation::WorldPtr world, const Eigen::VectorXs& x);\n\n  /// This replaces x with the result of Minv*x in place, without explicitly\n  /// forming Minv\n  Eigen::VectorXs implicitMultiplyByInvMassMatrix(\n      simulation::WorldPtr world, const Eigen::VectorXs& x);\n\n  /// TODO(keenon): Remove me\n  Eigen::MatrixXs getScratchAnalytical(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// TODO(keenon): Remove me\n  Eigen::MatrixXs getScratchFiniteDifference(\n      simulation::WorldPtr world, WithRespectTo* wrt, bool useRidders = true);\n\n  /// TODO(keenon): Remove me\n  Eigen::MatrixXs getScratchFiniteDifferenceRidders(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This predicts what the next velocity will be using our linear algebra\n  /// formula. This is only here for testing, to compare it against the actual\n  /// result of a timestep.\n  ///\n  /// The `morePreciseButSlower` flag tells this function to do brute force\n  /// steps to get constraint matrices A_c and A_ub, rather than use 1st order\n  /// approximations. This is important because when we're doing\n  /// finite-differencing over tiny EPS (1e-9) then tiny errors in the 1st order\n  /// approximations blow up to become huge errors in gradients.\n  Eigen::VectorXs getAnalyticalNextV(\n      simulation::WorldPtr world, bool morePreciseButSlower = false);\n\n  /// This computes and returns the whole wrt-vel jacobian. For backprop, you\n  /// don't actually need this matrix, you can compute backprop directly. This\n  /// is here if you want access to the full Jacobian for some reason.\n  Eigen::MatrixXs getVelJacobianWrt(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This computes and returns the whole wrt-pos jacobian. For backprop, you\n  /// don't actually need this matrix, you can compute backprop directly. This\n  /// is here if you want access to the full Jacobian for some reason.\n  Eigen::MatrixXs getPosJacobianWrt(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the jacobian of constraint force, holding everyhing constant\n  /// except the value of WithRespectTo\n  Eigen::MatrixXs getJacobianOfConstraintForce(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the analytical expression for the Jacobian of Q*b, holding b\n  /// constant, if there are some upper-bound indices\n  Eigen::MatrixXs dQ_WithUB(\n      simulation::WorldPtr world,\n      Eigen::MatrixXs& Minv,\n      Eigen::MatrixXs& A_c,\n      Eigen::MatrixXs& E,\n      Eigen::MatrixXs& A_c_ub_E,\n      Eigen::VectorXs rhs,\n      WithRespectTo* wrt);\n  /// This returns the analytical expression for the Jacobian of Q^T*b, holding\n  /// b constant, if there are some upper-bound indices\n  Eigen::MatrixXs dQT_WithUB(\n      simulation::WorldPtr world,\n      Eigen::MatrixXs& Minv,\n      Eigen::MatrixXs& A_c,\n      Eigen::MatrixXs& E,\n      Eigen::MatrixXs& A_ub,\n      Eigen::VectorXs rhs,\n      WithRespectTo* wrt);\n  /// This returns the analytical expression for the Jacobian of Q*b, holding b\n  /// constant, if there are no upper-bound indices\n  Eigen::MatrixXs dQ_WithoutUB(\n      simulation::WorldPtr world,\n      Eigen::MatrixXs& Minv,\n      Eigen::MatrixXs& A_c,\n      Eigen::VectorXs rhs,\n      WithRespectTo* wrt);\n\n  /// This returns the jacobian of Qb, holding b constant, with respect to\n  /// wrt, by finite differencing\n  Eigen::MatrixXs finiteDifferenceJacobianOfQb(\n      simulation::WorldPtr world,\n      Eigen::VectorXs b,\n      WithRespectTo* wrt,\n      bool useRidders = true);\n\n  /// This returns the jacobian of Qb, holding b constant, with respect to\n  /// wrt, by finite differencing\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfQb(\n      simulation::WorldPtr world, Eigen::VectorXs b, WithRespectTo* wrt);\n\n  /// This returns the vector of constants that get added to the diagonal of Q\n  /// to guarantee that Q is full-rank\n  Eigen::VectorXs getConstraintForceMixingDiagonal();\n\n  /// This returns the jacobian of Q^{-1}b, holding b constant, with respect to\n  /// wrt\n  Eigen::MatrixXs getJacobianOfLCPConstraintMatrixClampingSubset(\n      simulation::WorldPtr world, Eigen::VectorXs b, WithRespectTo* wrt);\n\n  /// This returns the jacobian of Q^{-1}b, holding b constant, with respect to\n  /// wrt, by finite differencing\n  Eigen::MatrixXs finiteDifferenceJacobianOfLCPConstraintMatrixClampingSubset(\n      simulation::WorldPtr world,\n      Eigen::VectorXs b,\n      WithRespectTo* wrt,\n      bool useRidders = true);\n\n  /// This returns the jacobian of Q^{-1}b, holding b constant, with respect to\n  /// wrt, by Ridders extrapolated finite differencing\n  Eigen::MatrixXs\n  finiteDifferenceRiddersJacobianOfLCPConstraintMatrixClampingSubset(\n      simulation::WorldPtr world, Eigen::VectorXs b, WithRespectTo* wrt);\n\n  /// This returns the jacobian of b (from Q^{-1}b) with respect to wrt\n  Eigen::MatrixXs getJacobianOfLCPOffsetClampingSubset(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the jacobian of b (from Q^{-1}b) with respect to wrt, by\n  /// finite differencing\n  Eigen::MatrixXs finiteDifferenceJacobianOfLCPOffsetClampingSubset(\n      simulation::WorldPtr world, WithRespectTo* wrt, bool useRidders = true);\n\n  /// This returns the jacobian of b (from Q^{-1}b) with respect to wrt, by\n  /// Ridders extrapolated finite differencing\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfLCPOffsetClampingSubset(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the jacobian of b (from Q^{-1}b) with respect to wrt, by\n  /// finite differencing\n  Eigen::MatrixXs finiteDifferenceJacobianOfLCPEstimatedOffsetClampingSubset(\n      simulation::WorldPtr world, WithRespectTo* wrt, bool useRidders = true);\n\n  /// This returns the jacobian of b (from Q^{-1}b) with respect to wrt, by\n  /// Ridders extrapolated finite differencing\n  Eigen::MatrixXs\n  finiteDifferenceRiddersJacobianOfLCPEstimatedOffsetClampingSubset(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the subset of the A matrix used by the original LCP for just\n  /// the clamping constraints. It relates constraint force to constraint\n  /// acceleration. It's a mass matrix, just in a weird frame.\n  void computeLCPConstraintMatrixClampingSubset(\n      simulation::WorldPtr world,\n      Eigen::MatrixXs& Q,\n      const Eigen::MatrixXs& A_c,\n      const Eigen::MatrixXs& A_ub,\n      const Eigen::MatrixXs& E);\n\n  /// This returns the subset of the b vector used by the original LCP for just\n  /// the clamping constraints. It's just the relative velocity at the clamping\n  /// contact points.\n  void computeLCPOffsetClampingSubset(\n      simulation::WorldPtr world,\n      Eigen::VectorXs& b,\n      const Eigen::MatrixXs& A_c);\n\n  /// This computes and returns an estimate of the constraint impulses for the\n  /// clamping constraints. This is based on a linear approximation of the\n  /// constraint impulses.\n  Eigen::VectorXs estimateClampingConstraintImpulses(\n      simulation::WorldPtr world,\n      const Eigen::MatrixXs& A_c,\n      const Eigen::MatrixXs& A_ub,\n      const Eigen::MatrixXs& E);\n\n  /// This returns the jacobian of P_c * v, holding everyhing constant except\n  /// the value of WithRespectTo\n  Eigen::MatrixXs getJacobianOfProjectionIntoClampsMatrix(\n      simulation::WorldPtr world, Eigen::VectorXs v, WithRespectTo* wrt);\n\n  /// This computes and returns the jacobian of P_c * v by finite\n  /// differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceJacobianOfProjectionIntoClampsMatrix(\n      simulation::WorldPtr world,\n      Eigen::VectorXs v,\n      WithRespectTo* wrt,\n      bool useRidders = true);\n\n  /// This computes and returns the jacobian of P_c * v by Ridders extrapolated\n  /// finite differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfProjectionIntoClampsMatrix(\n      simulation::WorldPtr world, Eigen::VectorXs v, WithRespectTo* wrt);\n\n  /// This returns the jacobian of M^{-1}(pos, inertia) * tau, holding\n  /// everything constant except the value of WithRespectTo\n  Eigen::MatrixXs getJacobianOfMinv(\n      simulation::WorldPtr world, Eigen::VectorXs tau, WithRespectTo* wrt);\n\n  /// This computes and returns the jacobian of M^{-1}(pos, inertia) * tau by\n  /// finite differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceJacobianOfMinv(\n      simulation::WorldPtr world,\n      Eigen::VectorXs tau,\n      WithRespectTo* wrt,\n      bool useRidders = true);\n\n  /// This computes and returns the jacobian of M^{-1}(pos, inertia) * tau by\n  /// Ridders extrapolated finite differences. This is SUPER SLOW, and is\n  /// only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfMinv(\n      simulation::WorldPtr world, Eigen::VectorXs tau, WithRespectTo* wrt);\n\n  /// This returns the jacobian of M(pos, inertia) * v, holding\n  /// everything constant except the value of WithRespectTo\n  Eigen::MatrixXs getJacobianOfM(\n      simulation::WorldPtr world, Eigen::VectorXs v, WithRespectTo* wrt);\n\n  /// This computes and returns the jacobian of M(pos, inertia) * v by\n  /// finite differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceJacobianOfM(\n      simulation::WorldPtr world,\n      Eigen::VectorXs v,\n      WithRespectTo* wrt,\n      bool useRidders = true);\n\n  /// This computes and returns the jacobian of M(pos, inertia) * v by\n  /// Ridders extrapolated finite differences. This is SUPER SLOW, and is\n  /// only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfM(\n      simulation::WorldPtr world, Eigen::VectorXs v, WithRespectTo* wrt);\n\n  /// This returns the jacobian of C(pos, inertia, vel), holding everything\n  /// constant except the value of WithRespectTo\n  Eigen::MatrixXs getJacobianOfC(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the jacobian of C(pos, inertia, vel), holding everything\n  /// constant except the value of WithRespectTo\n  Eigen::MatrixXs computeJacobianOfC(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This computes and returns the jacobian of C(pos, inertia, vel) by finite\n  /// differences. This is SUPER SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceJacobianOfC(\n      simulation::WorldPtr world, WithRespectTo* wrt, bool useRidders = true);\n\n  /// This computes and returns the jacobian of C(pos, inertia, vel) by Ridders\n  /// extrapolated finite differences. This is SUPER SLOW, and is only here\n  /// for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfC(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the jacobian of M^{-1}(pos, inertia) * (C(pos, inertia, vel)\n  /// + mPreStepTorques), holding everything constant except the value of\n  /// WithRespectTo\n  Eigen::MatrixXs getJacobianOfMinvC(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This computes and returns the jacobian of M^{-1}(pos, inertia) * C(pos,\n  /// inertia, vel) by finite differences. This is SUPER SLOW, and is only here\n  /// for testing.\n  Eigen::MatrixXs finiteDifferenceJacobianOfMinvC(\n      simulation::WorldPtr world, WithRespectTo* wrt, bool useRidders = false);\n\n  /// This computes and returns the jacobian of M^{-1}(pos, inertia) * C(pos,\n  /// inertia, vel) by Ridders extrapolated finite differences. This is SUPER\n  /// SLOW, and is only here for testing.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfMinvC(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns a fast approximation to A_c in the neighborhood of the\n  /// original\n  Eigen::MatrixXs estimateClampingConstraintMatrixAt(\n      simulation::WorldPtr world, Eigen::VectorXs pos);\n\n  /// This returns a fast approximation to A_ub in the neighborhood of the\n  /// original\n  Eigen::MatrixXs estimateUpperBoundConstraintMatrixAt(\n      simulation::WorldPtr world, Eigen::VectorXs pos);\n\n  /// Only for testing: VERY SLOW. This returns the actual value of A_c at the\n  /// desired position.\n  Eigen::MatrixXs getClampingConstraintMatrixAt(\n      simulation::WorldPtr world, Eigen::VectorXs pos);\n\n  /// Only for testing: VERY SLOW. This returns the actual value of A_ub at the\n  /// desired position.\n  Eigen::MatrixXs getUpperBoundConstraintMatrixAt(\n      simulation::WorldPtr world, Eigen::VectorXs pos);\n\n  /// Only for testing: VERY SLOW. This returns the actual value of E at the\n  /// desired position.\n  Eigen::MatrixXs getUpperBoundMappingMatrixAt(\n      simulation::WorldPtr world, Eigen::VectorXs pos);\n\n  /// Only for testing: VERY SLOW. This returns the actual value of the bounce\n  /// diagonals at the desired position.\n  Eigen::VectorXs getBounceDiagonalsAt(\n      simulation::WorldPtr world, Eigen::VectorXs pos);\n\n  /// This computes the Jacobian of A_c*f0 with respect to position using\n  /// impulse tests.\n  Eigen::MatrixXs getJacobianOfClampingConstraints(\n      simulation::WorldPtr world, Eigen::VectorXs f0);\n\n  /// This computes the finite difference Jacobian of A_c*f0 with respect to\n  /// position. This is AS SLOW AS FINITE DIFFERENCING THE WHOLE ENGINE, which\n  /// is way too slow to use in practice.\n  Eigen::MatrixXs finiteDifferenceJacobianOfClampingConstraints(\n      simulation::WorldPtr world, Eigen::VectorXs f0, bool useRidders = true);\n\n  /// This computes the finite difference Jacobian of A_c*f0 with respect to\n  /// position. This is AS SLOW AS FINITE DIFFERENCING THE WHOLE ENGINE, which\n  /// is way too slow to use in practice. Using Ridders, so even slower.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfClampingConstraints(\n      simulation::WorldPtr world, Eigen::VectorXs f0);\n\n  /// This computes the Jacobian of A_c^T*v0 with respect to position using\n  /// impulse tests.\n  Eigen::MatrixXs getJacobianOfClampingConstraintsTranspose(\n      simulation::WorldPtr world, Eigen::VectorXs v0);\n\n  /// This computes the finite difference Jacobian of A_c^T*v0 with respect to\n  /// position. This is AS SLOW AS FINITE DIFFERENCING THE WHOLE ENGINE, which\n  /// is way too slow to use in practice.\n  Eigen::MatrixXs finiteDifferenceJacobianOfClampingConstraintsTranspose(\n      simulation::WorldPtr world, Eigen::VectorXs v0, bool useRidders = true);\n\n  /// This computes the finite difference Jacobian of A_c^T*v0 with respect to\n  /// position. This is AS SLOW AS FINITE DIFFERENCING THE WHOLE ENGINE, which\n  /// is way too slow to use in practice. Using Ridders, so even slower.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfClampingConstraintsTranspose(\n      simulation::WorldPtr world, Eigen::VectorXs v0);\n\n  /// This computes the Jacobian of A_ub*(E*f0) with respect to position using\n  /// impulse tests.\n  Eigen::MatrixXs getJacobianOfUpperBoundConstraints(\n      simulation::WorldPtr world, Eigen::VectorXs E_f0);\n\n  /// This computes the finite difference Jacobian of A_ub*E*f0 with respect to\n  /// position. This is AS SLOW AS FINITE DIFFERENCING THE WHOLE ENGINE, which\n  /// is way too slow to use in practice.\n  Eigen::MatrixXs finiteDifferenceJacobianOfUpperBoundConstraints(\n      simulation::WorldPtr world, Eigen::VectorXs f0, bool useRidders = true);\n\n  /// This computes the finite difference Jacobian of A_ub*E*f0 with respect to\n  /// position. This is AS SLOW AS FINITE DIFFERENCING THE WHOLE ENGINE, which\n  /// is way too slow to use in practice. Uses Ridders method.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfUpperBoundConstraints(\n      simulation::WorldPtr world, Eigen::VectorXs f0);\n\n  /// This computes the Jacobian of A_ub^T*v0 with respect to position using\n  /// impulse tests.\n  Eigen::MatrixXs getJacobianOfUpperBoundConstraintsTranspose(\n      simulation::WorldPtr world, Eigen::VectorXs v0);\n\n  /// This returns the jacobian of constraint force, holding everything constant\n  /// except the value of WithRespectTo\n  Eigen::MatrixXs finiteDifferenceJacobianOfConstraintForce(\n      simulation::WorldPtr world, WithRespectTo* wrt, bool useRidders = true);\n\n  /// This returns the jacobian of constraint force, holding everything constant\n  /// except the value of WithRespectTo. Uses Ridders method.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfConstraintForce(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// This returns the jacobian of estimated constraint force, without actually\n  /// running forward passes, holding everyhing constant except the value of\n  /// WithRespectTo\n  Eigen::MatrixXs finiteDifferenceJacobianOfEstimatedConstraintForce(\n      simulation::WorldPtr world, WithRespectTo* wrt, bool useRidders = true);\n\n  /// This returns the jacobian of estimated constraint force, without actually\n  /// running forward passes, holding everyhing constant except the value of\n  /// WithRespectTo. Uses Ridders method.\n  Eigen::MatrixXs finiteDifferenceRiddersJacobianOfEstimatedConstraintForce(\n      simulation::WorldPtr world, WithRespectTo* wrt);\n\n  /// These was the mX() vector used to construct this. Pretty much only here\n  /// for testing.\n  Eigen::VectorXs getContactConstraintImpulses();\n\n  /// These was the fIndex() vector used to construct this. Pretty much only\n  /// here for testing.\n  Eigen::VectorXi getContactConstraintMappings();\n\n  /// Returns the vector of the coefficients on the diagonal of the bounce\n  /// matrix. These are 1+restitutionCoeff[i].\n  Eigen::VectorXs getBounceDiagonals();\n\n  /// Returns the vector of the restitution coeffs, sized for the number of\n  /// bouncing collisions.\n  Eigen::VectorXs getRestitutionDiagonals();\n\n  /// Returns the penetration correction hack \"bounce\" (or 0 if the contact is\n  /// not inter-penetrating or is actively bouncing) at each contact point.\n  Eigen::VectorXs getPenetrationCorrectionVelocities();\n\n  /// Returns the constraint impulses along the clamping constraints\n  Eigen::VectorXs getClampingConstraintImpulses();\n\n  /// Returns the relative velocities along the clamping constraints\n  Eigen::VectorXs getClampingConstraintRelativeVels();\n\n  /// Returns the velocity change caused by illegal impulses in the LCP this\n  /// timestep\n  Eigen::VectorXs getVelocityDueToIllegalImpulses();\n\n  /// Returns the velocity pre-LCP\n  Eigen::VectorXs getPreLCPVelocity();\n\n  /// Returns true if there were any bounces in this snapshot.\n  bool hasBounces();\n\n  /// Returns the number of contacts (regardless of state) in this snapshot.\n  std::size_t getNumContacts();\n\n  /// Returns the number of clamping contacts in this snapshot.\n  std::size_t getNumClamping();\n\n  /// Returns the number of upper bound contacts in this snapshot.\n  std::size_t getNumUpperBound();\n\n  /// These are the gradient constraint matrices from the LCP solver\n  std::vector<std::shared_ptr<ConstrainedGroupGradientMatrices>>\n      mGradientMatrices;\n\n  /// This is the clamping constraints from all the constrained\n  /// groups, concatenated together\n  std::vector<std::shared_ptr<DifferentiableContactConstraint>>\n  getDifferentiableConstraints();\n\n  /// This is the clamping constraints from all the constrained\n  /// groups, concatenated together\n  std::vector<std::shared_ptr<DifferentiableContactConstraint>>\n  getClampingConstraints();\n\n  /// This is the upper bound constraints from all the constrained\n  /// groups, concatenated together\n  std::vector<std::shared_ptr<DifferentiableContactConstraint>>\n  getUpperBoundConstraints();\n\n  /// This verifies that the two matrices are equal to some tolerance, and if\n  /// they're not it prints the information needed to replicated this scenario\n  /// and it exits the program.\n  void equalsOrCrash(\n      std::shared_ptr<simulation::World> world,\n      Eigen::MatrixXs analytical,\n      Eigen::MatrixXs bruteForce,\n      std::string name);\n\n  /// This compares our analytical sub-Jacobians (like dMinv), to attempt to\n  /// diagnose where there are differences creeping in between our finite\n  /// differencing and our analytical results.\n  void diagnoseSubJacobianErrors(\n      std::shared_ptr<simulation::World> world, WithRespectTo* wrt);\n\n  /// This prints code to the console to replicate a scenario for testing.\n  void printReplicationInstructions(std::shared_ptr<simulation::World> world);\n\n  /// Returns true if we were able to standardize our LCP results, false if we\n  /// weren't\n  bool areResultsStandardized() const;\n\n  /// If this is true, we use finite-differencing to compute all of the\n  /// requested Jacobians. This override can be useful to verify if there's a\n  /// bug in the analytical Jacobians that's causing learning to not converge.\n  void setUseFDOverride(bool override);\n\n  /// If this is true, we check all Jacobians against their finite-differencing\n  /// counterparts at runtime. If they aren't sufficiently close, we immediately\n  /// crash the program and print what went wrong and some simple replication\n  /// instructions.\n  void setSlowDebugResultsAgainstFD(bool slowDebug);\n\n  /// This does a battery of tests comparing the speeds to compute all the\n  /// different Jacobians, both with finite differencing and analytically, and\n  /// prints the results to std out.\n  void benchmarkJacobians(\n      std::shared_ptr<simulation::World> world, int numSamples);\n\nprotected:\n  /// If this is true, we use finite-differencing to compute all of the\n  /// requested Jacobians. This override can be useful to verify if there's a\n  /// bug in the analytical Jacobians that's causing learning to not converge.\n  bool mUseFDOverride;\n\n  /// If this is true, we check all Jacobians against their finite-differencing\n  /// counterparts at runtime. If they aren't sufficiently close, we immediately\n  /// crash the program and print what went wrong and some simple replication\n  /// instructions.\n  bool mSlowDebugResultsAgainstFD;\n\n  /// This is the global timestep length. This is included here because it shows\n  /// up as a constant in some of the matrices.\n  s_t mTimeStep;\n\n  /// This is the total DOFs for this World\n  std::size_t mNumDOFs;\n\n  /// This is the number of total dimensions on all the constraints active in\n  /// the world\n  std::size_t mNumConstraintDim;\n\n  /// This is the number of total constraint dimensions that are clamping\n  std::size_t mNumClamping;\n\n  /// This is the number of total constraint dimensions that are upper bounded\n  std::size_t mNumUpperBound;\n\n  /// This is the number of total constraint dimensions that are upper bounded\n  std::size_t mNumBouncing;\n\n  /// These are the offsets into the total degrees of freedom for each skeleton\n  std::unordered_map<std::string, std::size_t> mSkeletonOffset;\n\n  /// These are the number of degrees of freedom for each skeleton\n  std::unordered_map<std::string, std::size_t> mSkeletonDofs;\n\n  /// The position of all the DOFs of the world BEFORE the timestep\n  Eigen::VectorXs mPreStepPosition;\n\n  /// The velocities of all the DOFs of the world BEFORE the timestep\n  Eigen::VectorXs mPreStepVelocity;\n\n  /// The torques on all the DOFs of the world BEFORE the timestep\n  Eigen::VectorXs mPreStepTorques;\n\n  /// The LCP's initial cached value BEFORE the timestep\n  Eigen::VectorXs mPreStepLCPCache;\n\n  /// The velocities of all the DOFs of the world AFTER an unconstrained forward\n  /// step, but BEFORE the LCP runs\n  Eigen::VectorXs mPreConstraintVelocities;\n\n  /// The position of all the DOFs of the world AFTER the timestep\n  Eigen::VectorXs mPostStepPosition;\n\n  /// The velocities of all the DOFs of the world AFTER the timestep\n  /// created\n  Eigen::VectorXs mPostStepVelocity;\n\n  /// The torques on all the DOFs of the world AFTER the timestep\n  Eigen::VectorXs mPostStepTorques;\n\nprivate:\n  /// These are mCached versions of the various Jacobians\n  bool mCachedPosPosDirty;\n  Eigen::MatrixXs mCachedPosPos;\n  bool mCachedPosVelDirty;\n  Eigen::MatrixXs mCachedPosVel;\n  bool mCachedBounceApproximationDirty;\n  Eigen::MatrixXs mCachedBounceApproximation;\n  bool mCachedVelPosDirty;\n  Eigen::MatrixXs mCachedVelPos;\n  bool mCachedVelVelDirty;\n  Eigen::MatrixXs mCachedVelVel;\n  bool mCachedForcePosDirty;\n  Eigen::MatrixXs mCachedForcePos;\n  bool mCachedForceVelDirty;\n  Eigen::MatrixXs mCachedForceVel;\n  bool mCachedMassVelDirty;\n  Eigen::MatrixXs mCachedMassVel;\n  bool mCachedPosCDirty;\n  Eigen::MatrixXs mCachedPosC;\n  bool mCachedVelCDirty;\n  Eigen::MatrixXs mCachedVelC;\n\n  Eigen::VectorXs scratch(simulation::WorldPtr world);\n\n  enum MatrixToAssemble\n  {\n    CLAMPING,\n    MASSED_CLAMPING,\n    UPPER_BOUND,\n    MASSED_UPPER_BOUND,\n    BOUNCING\n  };\n\n  Eigen::MatrixXs assembleMatrix(\n      simulation::WorldPtr world, MatrixToAssemble whichMatrix);\n\n  enum BlockDiagonalMatrixToAssemble\n  {\n    MASS,\n    INV_MASS,\n    POS_C,\n    VEL_C\n  };\n\n  Eigen::MatrixXs assembleBlockDiagonalMatrix(\n      simulation::WorldPtr world,\n      BlockDiagonalMatrixToAssemble whichMatrix,\n      bool forFiniteDifferencing = false);\n\n  enum VectorToAssemble\n  {\n    CONTACT_CONSTRAINT_IMPULSES,\n    CONTACT_CONSTRAINT_MAPPINGS,\n    BOUNCE_DIAGONALS,\n    RESTITUTION_DIAGONALS,\n    PENETRATION_VELOCITY_HACK,\n    CLAMPING_CONSTRAINT_IMPULSES,\n    CLAMPING_CONSTRAINT_RELATIVE_VELS,\n    VEL_DUE_TO_ILLEGAL,\n    PRE_STEP_VEL,\n    PRE_STEP_TAU,\n    PRE_LCP_VEL,\n    CFM_CONSTANTS\n  };\n  template <typename Vec>\n  Vec assembleVector(VectorToAssemble whichVector);\n\n  template <typename Vec>\n  const Vec& getVectorToAssemble(\n      std::shared_ptr<ConstrainedGroupGradientMatrices> matrices,\n      VectorToAssemble whichVector);\n};\n\nusing BackpropSnapshotPtr = std::shared_ptr<BackpropSnapshot>;\n\n} // namespace neural\n} // namespace dart\n\n#endif", "meta": {"hexsha": "66e552b705006348347141b3cef45f95c004dd71", "size": 39514, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/neural/BackpropSnapshot.hpp", "max_stars_repo_name": "jyf588/nimblephysics", "max_stars_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T06:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T09:59:09.000Z", "max_issues_repo_path": "dart/neural/BackpropSnapshot.hpp", "max_issues_repo_name": "jyf588/nimblephysics", "max_issues_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dart/neural/BackpropSnapshot.hpp", "max_forks_repo_name": "jyf588/nimblephysics", "max_forks_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:56:14.000Z", "avg_line_length": 43.0435729847, "max_line_length": 80, "alphanum_fraction": 0.7396365845, "num_tokens": 9894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.66192288918838, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.22378097795688764}}
{"text": "// This file is part of the dune-gdt project:\n//   http://users.dune-project.org/projects/dune-gdt\n// Copyright holders: Felix Schindler\n// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)\n//\n// Contributors: Kirsten Weber\n\n#ifndef DUNE_GDT_EVALUATION_ELLIPTIC_HH\n#define DUNE_GDT_EVALUATION_ELLIPTIC_HH\n\n#include <tuple>\n\n#include <boost/numeric/conversion/cast.hpp>\n\n#include <dune/common/dynmatrix.hh>\n#include <dune/common/typetraits.hh>\n\n#include <dune/stuff/functions/interfaces.hh>\n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace LocalEvaluation {\n\n\n// forward\ntemplate< class DiffusionFactorImp, class DiffusionTensorImp = void >\nclass Elliptic;\n\n\nnamespace internal {\n\n\n/**\n * \\brief Traits for the Elliptic evaluation (variant for given diffusion factor and tensor).\n * \\sa    EllipticTraits (below) for a variant if only a diffusion is given.\n */\ntemplate< class DiffusionFactorType, class DiffusionTensorType >\nclass EllipticTraits\n{\n  static_assert(Stuff::is_localizable_function< DiffusionFactorType >::value,\n                \"DiffusionFactorType has to be a localizable function!\");\n  static_assert(Stuff::is_localizable_function< DiffusionTensorType >::value,\n                \"DiffusionTensorType has to be a localizable function!\");\n  static_assert(std::is_same< typename DiffusionFactorType::EntityType,\n                              typename DiffusionTensorType::EntityType >::value,\n                \"EntityTypes have to agree!\");\n  static_assert(std::is_same< typename DiffusionFactorType::DomainFieldType,\n                              typename DiffusionTensorType::DomainFieldType >::value,\n                \"DomainFieldTypes have to agree!\");\n  static_assert(DiffusionFactorType::dimDomain == DiffusionTensorType::dimDomain,\n                \"Dimensions have to agree!\");\npublic:\n  typedef Elliptic< DiffusionFactorType, DiffusionTensorType > derived_type;\n  typedef std::tuple< std::shared_ptr< typename DiffusionFactorType::LocalfunctionType >,\n                      std::shared_ptr< typename DiffusionTensorType::LocalfunctionType > > LocalfunctionTupleType;\n  typedef typename DiffusionFactorType::EntityType      EntityType;\n  typedef typename DiffusionFactorType::DomainFieldType DomainFieldType;\n  static const size_t                                   dimDomain = DiffusionFactorType::dimDomain;\n}; // class EllipticTraits\n\n\n/**\n * \\brief Traits for the Elliptic evaluation (variant for a given diffusion).\n * \\note  It does not matter if that function plays the role of the diffusion factor (scalar) or the diffusion\n *        tensor (matrix).\n * \\sa    EllipticTraits (above) for a variant if a diffusion factor and a diffusion tensor is given.\n */\ntemplate< class DiffusionType >\nclass EllipticTraits< DiffusionType, void >\n{\n  static_assert(Stuff::is_localizable_function< DiffusionType >::value,\n                \"DiffusionType has to be a localizable function!\");\npublic:\n  typedef Elliptic< DiffusionType, void >         derived_type;\n  typedef typename DiffusionType::EntityType      EntityType;\n  typedef typename DiffusionType::DomainFieldType DomainFieldType;\n  typedef std::tuple< std::shared_ptr< typename DiffusionType::LocalfunctionType > > LocalfunctionTupleType;\n  static const size_t                             dimDomain = DiffusionType::dimDomain;\n}; // class EllipticTraits< ..., void >\n\n\n} // namespace internal\n\n\n/**\n * \\brief Computes an elliptic evaluation (variant for given diffusion factor and tensor).\n * \\sa    Elliptic (below) for a variant if only a diffusion is given.\n */\ntemplate< class DiffusionFactorImp, class DiffusionTensorImp >\nclass Elliptic\n  : public LocalEvaluation::Codim0Interface< internal::EllipticTraits< DiffusionFactorImp, DiffusionTensorImp >, 2 >\n{\npublic:\n  typedef DiffusionFactorImp                                                   DiffusionFactorType;\n  typedef DiffusionTensorImp                                                   DiffusionTensorType;\n  typedef internal::EllipticTraits< DiffusionFactorType, DiffusionTensorType > Traits;\n  typedef typename Traits::LocalfunctionTupleType                              LocalfunctionTupleType;\n  typedef typename Traits::EntityType                                          EntityType;\n  typedef typename Traits::DomainFieldType                                     DomainFieldType;\n  static const size_t                                                          dimDomain = Traits::dimDomain;\n\n  Elliptic(const DiffusionFactorType& diffusion_factor,\n           const DiffusionTensorType& diffusion_tensor)\n    : diffusion_factor_(diffusion_factor)\n    , diffusion_tensor_(diffusion_tensor)\n  {}\n\n  LocalfunctionTupleType localFunctions(const EntityType& entity) const\n  {\n    return std::make_tuple(diffusion_factor_.local_function(entity),\n                           diffusion_tensor_.local_function(entity));\n  }\n\n  /**\n   * \\brief extracts the local functions and calls the correct order() method\n   */\n  template< class R, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  size_t order(const LocalfunctionTupleType& local_functions_tuple,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const\n  {\n    const auto local_diffusion_factor = std::get< 0 >(local_functions_tuple);\n    const auto local_diffusion_tensor = std::get< 1 >(local_functions_tuple);\n    return order(*local_diffusion_factor, *local_diffusion_tensor, testBase, ansatzBase);\n  } // ... order(...)\n\n  /**\n   * \\brief extracts the local functions and calls the correct evaluate() method\n   */\n  template< class R, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  void evaluate(const LocalfunctionTupleType& local_functions_tuple,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase,\n                const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n                Dune::DynamicMatrix< R >& ret) const\n  {\n    const auto local_diffusion_factor = std::get< 0 >(local_functions_tuple);\n    const auto local_diffusion_tensor = std::get< 1 >(local_functions_tuple);\n    evaluate(*local_diffusion_factor, *local_diffusion_tensor, testBase, ansatzBase, localPoint, ret);\n  }\n\nprivate:\n  template< class R, size_t rDF, size_t rCDF, size_t rDT, size_t rCDT, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  size_t order(const Stuff::LocalfunctionInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rDF, rCDF >& local_diffusion_factor,\n               const Stuff::LocalfunctionInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rDT, rCDT >& local_diffusion_tensor,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const\n  {\n    return local_diffusion_factor.order()\n        + local_diffusion_tensor.order()\n        + std::max(ssize_t(testBase.order()) - 1, ssize_t(0))\n        + std::max(ssize_t(ansatzBase.order()) - 1, ssize_t(0));\n  } // ... order(...)\n\n  template< class R, size_t r >\n  void evaluate(const Stuff::LocalfunctionInterface\n                    < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& local_diffusion_factor,\n                const Stuff::LocalfunctionInterface\n                    < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& local_diffusion_tensor,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, r, 1 >& testBase,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, r, 1 >& ansatzBase,\n                const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n                Dune::DynamicMatrix< R >& ret) const\n  {\n    // evaluate local functions\n    const auto local_diffusion_factor_value = local_diffusion_factor.evaluate(localPoint);\n    const auto local_diffusion_tensor_value = local_diffusion_tensor.evaluate(localPoint);\n    // evaluate test gradient\n    const auto rows = testBase.size();\n    const auto testGradients = testBase.jacobian(localPoint);\n    // evaluate ansatz gradient\n    const auto cols = ansatzBase.size();\n    const auto ansatzGradients = ansatzBase.jacobian(localPoint);\n    // compute products\n    assert(ret.rows() >= rows);\n    assert(ret.cols() >= cols);\n    for (size_t ii = 0; ii < rows; ++ii) {\n      auto& retRow = ret[ii];\n      for (size_t jj = 0; jj < cols; ++jj) {\n        retRow[jj] = local_diffusion_factor_value * local_diffusion_tensor_value\n                     * (ansatzGradients[jj][0] * testGradients[ii][0]);\n      }\n    }\n  } // ... evaluate(...)\n\n  template< class R >\n  void evaluate(const Stuff::LocalfunctionInterface\n                    < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& local_diffusion_factor,\n                const Stuff::LocalfunctionInterface\n                    < EntityType, DomainFieldType, dimDomain, R, 2, 2 >& local_diffusion_tensor,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase,\n                const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n                Dune::DynamicMatrix< R >& ret) const\n  {\n    evaluate_matrix_valued_(local_diffusion_factor, local_diffusion_tensor, testBase, ansatzBase, localPoint, ret);\n  }\n\n  template< class R >\n  void evaluate(const Stuff::LocalfunctionInterface\n                    < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& local_diffusion_factor,\n                const Stuff::LocalfunctionInterface\n                    < EntityType, DomainFieldType, dimDomain, R, 3, 3 >& local_diffusion_tensor,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase,\n                const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n                Dune::DynamicMatrix< R >& ret) const\n  {\n    evaluate_matrix_valued_(local_diffusion_factor, local_diffusion_tensor, testBase, ansatzBase, localPoint, ret);\n  }\n\n  template< class R >\n  void evaluate_matrix_valued_(const Stuff::LocalfunctionInterface\n                                   < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& local_diffusion_factor,\n                               const Stuff::LocalfunctionInterface\n                                   < EntityType, DomainFieldType, dimDomain, R, dimDomain, dimDomain >& local_diffusion_tensor,\n                               const Stuff::LocalfunctionSetInterface\n                                   < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase,\n                               const Stuff::LocalfunctionSetInterface\n                                   < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase,\n                               const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n                               Dune::DynamicMatrix< R >& ret) const\n  {\n    typedef typename Stuff::LocalfunctionSetInterface\n        < EntityType, DomainFieldType, dimDomain, R, 1, 1 >::JacobianRangeType JacobianRangeType;\n    // evaluate local functions\n    const auto local_diffusion_factor_value = local_diffusion_factor.evaluate(localPoint);\n    auto local_diffusion_tensor_value = local_diffusion_tensor.evaluate(localPoint);\n    local_diffusion_tensor_value *= local_diffusion_factor_value[0];\n    // evaluate test gradient\n    const size_t rows = testBase.size();\n    std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0));\n    testBase.jacobian(localPoint, testGradients);\n    // evaluate ansatz gradient\n    const size_t cols = ansatzBase.size();\n    std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0));\n    ansatzBase.jacobian(localPoint, ansatzGradients);\n    // compute products\n    assert(ret.rows() >= rows);\n    assert(ret.cols() >= cols);\n    FieldVector< DomainFieldType, dimDomain > product(0.0);\n    for (size_t ii = 0; ii < rows; ++ii) {\n      auto& retRow = ret[ii];\n      for (size_t jj = 0; jj < cols; ++jj) {\n        local_diffusion_tensor_value.mv(ansatzGradients[jj][0], product);\n        retRow[jj] = product * testGradients[ii][0];\n      }\n    }\n  } // ... evaluate_matrix_valued_(...)\n\n  const DiffusionFactorType& diffusion_factor_;\n  const DiffusionTensorType& diffusion_tensor_;\n}; // class Elliptic\n\n\n/**\n * \\brief Computes an elliptic evaluation (variant for a given diffusion).\n * \\note  It does not matter if that function plays the role of the diffusion factor (scalar) or the diffusion\n *        tensor (matrix).\n * \\sa    Elliptic (above) for a variant if a diffusion factor and a diffusion tensor is given.\n */\ntemplate< class DiffusionImp >\nclass Elliptic< DiffusionImp, void >\n  : public LocalEvaluation::Codim0Interface< internal::EllipticTraits< DiffusionImp, void >, 2 >\n{\npublic:\n  typedef DiffusionImp                                    DiffusionType;\n  typedef internal::EllipticTraits< DiffusionType, void > Traits;\n  typedef typename Traits::LocalfunctionTupleType         LocalfunctionTupleType;\n  typedef typename Traits::EntityType                     EntityType;\n  typedef typename Traits::DomainFieldType                DomainFieldType;\n  static const size_t                                     dimDomain = Traits::dimDomain;\n\n  explicit Elliptic(const DiffusionType& inducingFunction)\n    : diffusion_(inducingFunction)\n  {}\n\n  /// \\name Required by LocalEvaluation::Codim0Interface< ..., 2 >\n  /// \\{\n\n  LocalfunctionTupleType localFunctions(const EntityType& entity) const\n  {\n    return std::make_tuple(diffusion_.local_function(entity));\n  }\n\n  /**\n   * \\brief extracts the local functions and calls the correct order() method\n   */\n  template< class R, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  size_t order(const LocalfunctionTupleType& localFuncs,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,\n               const Stuff::LocalfunctionSetInterface\n                   < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase) const\n  {\n    return order(*std::get< 0 >(localFuncs), testBase, ansatzBase);\n  }\n\n  /**\n   * \\brief extracts the local functions and calls the correct evaluate() method\n   */\n  template< class R, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  void evaluate(const LocalfunctionTupleType& localFuncs,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,\n                const Stuff::LocalfunctionSetInterface\n                    < EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase,\n                const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n                Dune::DynamicMatrix< R >& ret) const\n  {\n    evaluate(*std::get< 0 >(localFuncs), testBase, ansatzBase, localPoint, ret);\n  }\n\n  /// \\}\n  /// \\name Actual implementations of order\n  /// \\{\n\n  /**\n   *  \\return localFunction.order() + (testBase.order() - 1) + (ansatzBase.order() - 1)\n   */\n  template< class R, size_t rL, size_t rCL, size_t rT, size_t rCT, size_t rA, size_t rCA >\n  size_t order(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, rL, rCL >& localFunction,\n               const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rT, rCT >& testBase,\n               const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, rA, rCA >& ansatzBase)\n  const\n  {\n    return localFunction.order()\n        + boost::numeric_cast< size_t >(std::max(ssize_t(testBase.order())   - 1, ssize_t(0)))\n        + boost::numeric_cast< size_t >(std::max(ssize_t(ansatzBase.order()) - 1, ssize_t(0)));\n  } // ... order( ... )\n\n  /// \\}\n  /// \\name Actual implementations of evaluate\n  /// \\{\n\n  /**\n   *  \\brief  Computes an elliptic evaluation for a scalar local function and scalar or vector valued basefunctionsets.\n   *  \\tparam R RangeFieldType\n   */\n  template< class R, size_t r >\n  void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& localFunction,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, 1 >& testBase,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, r, 1 >& ansatzBase,\n                const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n                Dune::DynamicMatrix< R >& ret) const\n  {\n    typedef typename Stuff::LocalfunctionSetInterface\n        < EntityType, DomainFieldType, dimDomain, R, r, 1 >::JacobianRangeType JacobianRangeType;\n    // evaluate local function\n    const auto functionValue = localFunction.evaluate(localPoint);\n    // evaluate test gradient\n    const size_t rows = testBase.size();\n    std::vector< JacobianRangeType > testGradients(rows, JacobianRangeType(0));\n    testBase.jacobian(localPoint, testGradients);\n    // evaluate ansatz gradient\n    const size_t cols = ansatzBase.size();\n    std::vector< JacobianRangeType > ansatzGradients(cols, JacobianRangeType(0));\n    ansatzBase.jacobian(localPoint, ansatzGradients);\n    // compute products\n    assert(ret.rows() >= rows);\n    assert(ret.cols() >= cols);\n    for (size_t ii = 0; ii < rows; ++ii) {\n      auto& retRow = ret[ii];\n      for (size_t jj = 0; jj < cols; ++jj) {\n        retRow[jj] = functionValue * (ansatzGradients[jj][0] * testGradients[ii][0]);\n      }\n    }\n  } // ... evaluate< ..., 1, ... >(...)\n\n  /**\n   *  \\brief  Computes an elliptic evaluation for a 2x2 matrix-valued local function and matrix-valued basefunctionsets.\n   *  \\tparam R RangeFieldType\n   *  \\note   Unfortunately we need this explicit specialization, otherwise the compiler will complain for 1d grids.\n   */\n  template< class R >\n  void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 2, 2 >& localFunction,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase,\n                const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n                Dune::DynamicMatrix< R >& ret) const\n  {\n    evaluate_matrix_valued_(localFunction, testBase, ansatzBase, localPoint, ret);\n  }\n\n  /**\n   *  \\brief  Computes an elliptic evaluation for a 3x3 matrix-valued local function and matrix-valued basefunctionsets.\n   *  \\tparam R RangeFieldType\n   *  \\note   Unfortunately we need this explicit specialization, otherwise the compiler will complain for 1d grids.\n   */\n  template< class R >\n  void evaluate(const Stuff::LocalfunctionInterface< EntityType, DomainFieldType, dimDomain, R, 3, 3 >& localFunction,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase,\n                const Stuff::LocalfunctionSetInterface< EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase,\n                const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n                Dune::DynamicMatrix< R >& ret) const\n  {\n    evaluate_matrix_valued_(localFunction, testBase, ansatzBase, localPoint, ret);\n  }\n\n  /// \\}\n\nprivate:\n  template< class R >\n  void evaluate_matrix_valued_(const Stuff::LocalfunctionInterface\n                                   < EntityType, DomainFieldType, dimDomain, R, dimDomain, dimDomain >& localFunction,\n                               const Stuff::LocalfunctionSetInterface\n                                   < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& testBase,\n                               const Stuff::LocalfunctionSetInterface\n                                   < EntityType, DomainFieldType, dimDomain, R, 1, 1 >& ansatzBase,\n                               const Dune::FieldVector< DomainFieldType, dimDomain >& localPoint,\n                               Dune::DynamicMatrix< R >& ret) const\n  {\n    // evaluate local function\n    const auto functionValue = localFunction.evaluate(localPoint);\n    // evaluate test gradient\n    const size_t rows = testBase.size();\n    const auto testGradients = testBase.jacobian(localPoint);\n    // evaluate ansatz gradient\n    const size_t cols = ansatzBase.size();\n    const auto ansatzGradients = ansatzBase.jacobian(localPoint);\n    // compute products\n    assert(ret.rows() >= rows);\n    assert(ret.cols() >= cols);\n    FieldVector< DomainFieldType, dimDomain > product(0.0);\n    for (size_t ii = 0; ii < rows; ++ii) {\n      auto& retRow = ret[ii];\n      for (size_t jj = 0; jj < cols; ++jj) {\n        functionValue.mv(ansatzGradients[jj][0], product);\n        retRow[jj] = product * testGradients[ii][0];\n      }\n    }\n  } // ... evaluate_matrix_valued_(...)\n\n  const DiffusionType& diffusion_;\n}; // class Elliptic< ...., void >\n\n\n} // namespace LocalEvaluation\n} // namespace GDT\n} // namespace Dune\n\n#endif // DUNE_GDT_EVALUATION_ELLIPTIC_HH\n", "meta": {"hexsha": "ff8f2a33820b1e7af9bc7f3db6fc7b86c79f8790", "size": 21928, "ext": "hh", "lang": "C++", "max_stars_repo_path": "dune/gdt/localevaluation/elliptic.hh", "max_stars_repo_name": "ftalbrecht/dune-gdt", "max_stars_repo_head_hexsha": "574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dune/gdt/localevaluation/elliptic.hh", "max_issues_repo_name": "ftalbrecht/dune-gdt", "max_issues_repo_head_hexsha": "574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dune/gdt/localevaluation/elliptic.hh", "max_forks_repo_name": "ftalbrecht/dune-gdt", "max_forks_repo_head_hexsha": "574bc4a3b28d2a6a6195a6b4df6727c61f0d73c9", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-08-13T11:51:27.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-13T11:51:27.000Z", "avg_line_length": 47.7734204793, "max_line_length": 127, "alphanum_fraction": 0.663124772, "num_tokens": 5102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.223769486307537}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_BLOCK_KASUMI_HPP\n#define CRYPTO3_BLOCK_KASUMI_HPP\n\n#include <boost/endian/arithmetic.hpp>\n#include <boost/endian/conversion.hpp>\n\n#include <nil/crypto3/block/detail/kasumi/kasumi_functions.hpp>\n\n#include <nil/crypto3/block/detail/block_stream_processor.hpp>\n#include <nil/crypto3/block/detail/cipher_modes.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace block {\n            /*!\n             * @brief Kasumi. A 64-bit cipher used in 3GPP mobile phone protocols.\n             * There is no reason to use it outside of this context.\n             *\n             * @ingroup block\n             */\n            class kasumi {\n            protected:\n                typedef detail::kasumi_functions policy_type;\n\n                constexpr static const std::size_t key_schedule_size = policy_type::key_schedule_size;\n                typedef typename policy_type::key_schedule_type key_schedule_type;\n\n            public:\n                constexpr static const std::size_t rounds = policy_type::rounds;\n\n                constexpr static const std::size_t word_bits = policy_type::word_bits;\n                typedef typename policy_type::word_type word_type;\n\n                constexpr static const std::size_t block_bits = policy_type::block_bits;\n                constexpr static const std::size_t block_words = policy_type::block_words;\n                typedef typename policy_type::block_type block_type;\n\n                constexpr static const std::size_t key_bits = policy_type::key_bits;\n                constexpr static const std::size_t key_words = policy_type::key_words;\n                typedef typename policy_type::key_type key_type;\n\n                template<class Mode, typename StateAccumulator, std::size_t ValueBits>\n                struct stream_processor {\n                    struct params_type {\n\n                        constexpr static const std::size_t value_bits = ValueBits;\n                        constexpr static const std::size_t length_bits = policy_type::word_bits * 2;\n                    };\n\n                    typedef block_stream_processor<Mode, StateAccumulator, params_type> type;\n                };\n\n                typedef typename stream_endian::little_octet_big_bit endian_type;\n\n                kasumi(const key_type &key) {\n                    schedule_key(key_schedule, key);\n                }\n\n                ~kasumi() {\n                    key_schedule.fill(0);\n                }\n\n                inline block_type encrypt(const block_type &plaintext) const {\n                    return encrypt_block(plaintext, key_schedule);\n                }\n\n                inline block_type decrypt(const block_type &ciphertext) const {\n                    return decrypt_block(ciphertext, key_schedule);\n                }\n\n            protected:\n                inline block_type encrypt_block(const block_type &plaintext,\n                                                const key_schedule_type &key_schedule) const {\n                    word_type B0 = boost::endian::native_to_big(plaintext[0]);\n                    word_type B1 = boost::endian::native_to_big(plaintext[1]);\n                    word_type B2 = boost::endian::native_to_big(plaintext[2]);\n                    word_type B3 = boost::endian::native_to_big(plaintext[3]);\n\n                    for (size_t j = 0; j != rounds; j += 2) {\n                        const word_type *K = &key_schedule[8 * j];\n\n                        word_type R = B1 ^ (policy_type::template rotl<1>(B0) & K[0]);\n                        word_type L = B0 ^ (policy_type::template rotl<1>(R) | K[1]);\n\n                        L = policy_type::FI(L ^ K[2], K[3]) ^ R;\n                        R = policy_type::FI(R ^ K[4], K[5]) ^ L;\n                        L = policy_type::FI(L ^ K[6], K[7]) ^ R;\n\n                        R = B2 ^= R;\n                        L = B3 ^= L;\n\n                        R = policy_type::FI(R ^ K[10], K[11]) ^ L;\n                        L = policy_type::FI(L ^ K[12], K[13]) ^ R;\n                        R = policy_type::FI(R ^ K[14], K[15]) ^ L;\n\n                        R ^= (policy_type::template rotl<1>(L) & K[8]);\n                        L ^= (policy_type::template rotl<1>(R) | K[9]);\n\n                        B0 ^= L;\n                        B1 ^= R;\n                    }\n\n                    return {boost::endian::big_to_native(B0), boost::endian::big_to_native(B1),\n                            boost::endian::big_to_native(B2), boost::endian::big_to_native(B3)};\n                }\n\n                inline block_type decrypt_block(const block_type &ciphertext,\n                                                const key_schedule_type &key_schedule) const {\n                    word_type B0 = boost::endian::native_to_big(ciphertext[0]);\n                    word_type B1 = boost::endian::native_to_big(ciphertext[1]);\n                    word_type B2 = boost::endian::native_to_big(ciphertext[2]);\n                    word_type B3 = boost::endian::native_to_big(ciphertext[3]);\n\n                    for (size_t j = 0; j != rounds; j += 2) {\n                        const word_type *K = &key_schedule[8 * (6 - j)];\n\n                        word_type L = B2, R = B3;\n\n                        L = policy_type::FI(L ^ K[10], K[11]) ^ R;\n                        R = policy_type::FI(R ^ K[12], K[13]) ^ L;\n                        L = policy_type::FI(L ^ K[14], K[15]) ^ R;\n\n                        L ^= (policy_type::template rotl<1>(R) & K[8]);\n                        R ^= (policy_type::template rotl<1>(L) | K[9]);\n\n                        R = B0 ^= R;\n                        L = B1 ^= L;\n\n                        L ^= (policy_type::template rotl<1>(R) & K[0]);\n                        R ^= (policy_type::template rotl<1>(L) | K[1]);\n\n                        R = policy_type::FI(R ^ K[2], K[3]) ^ L;\n                        L = policy_type::FI(L ^ K[4], K[5]) ^ R;\n                        R = policy_type::FI(R ^ K[6], K[7]) ^ L;\n\n                        B2 ^= L;\n                        B3 ^= R;\n                    }\n\n                    return {boost::endian::big_to_native(B0), boost::endian::big_to_native(B1),\n                            boost::endian::big_to_native(B2), boost::endian::big_to_native(B3)};\n                }\n\n                key_schedule_type key_schedule;\n\n                void schedule_key(key_schedule_type &key_schedule, const key_type &key) {\n                    std::array<word_type, 16> K = {0};\n                    for (size_t i = 0; i != rounds; ++i) {\n                        K[i] = boost::endian::native_to_big(key[i]);\n                        K[i + 8] = K[i] ^ policy_type::round_constants[i];\n                    }\n\n                    for (size_t i = 0; i != rounds; ++i) {\n                        key_schedule[8 * i] = policy_type::template rotl<2>(K[(i + 0) % 8]);\n                        key_schedule[8 * i + 1] = policy_type::template rotl<1>(K[(i + 2) % 8 + 8]);\n                        key_schedule[8 * i + 2] = policy_type::template rotl<5>(K[(i + 1) % 8]);\n                        key_schedule[8 * i + 3] = K[(i + 4) % 8 + 8];\n                        key_schedule[8 * i + 4] = policy_type::template rotl<8>(K[(i + 5) % 8]);\n                        key_schedule[8 * i + 5] = K[(i + 3) % 8 + 8];\n                        key_schedule[8 * i + 6] = policy_type::template rotl<13>(K[(i + 6) % 8]);\n                        key_schedule[8 * i + 7] = K[(i + 7) % 8 + 8];\n                    }\n\n                    K.fill(0);\n                }\n            };\n        }    // namespace block\n    }        // namespace crypto3\n}    // namespace nil\n#endif\n", "meta": {"hexsha": "c6f01eb96ea94fd8d42d13fb3ea564e3e0c8bab2", "size": 9000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/block/kasumi.hpp", "max_stars_repo_name": "NilFoundation/crypto3-block", "max_stars_repo_head_hexsha": "94f9cc42ac0fa62c5ee54e7d678abf48ffa9eec5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "include/nil/crypto3/block/kasumi.hpp", "max_issues_repo_name": "tonlabs/crypto3-block", "max_issues_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T23:11:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-16T18:04:20.000Z", "max_forks_repo_path": "include/nil/crypto3/block/kasumi.hpp", "max_forks_repo_name": "tonlabs/crypto3-block", "max_forks_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T15:37:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T21:47:05.000Z", "avg_line_length": 45.9183673469, "max_line_length": 102, "alphanum_fraction": 0.5084444444, "num_tokens": 2030, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.22375574452098243}}
{"text": "#include <string>\n#include <bitset>\n#include <iostream>\n#include <algorithm>\n#include <fstream>\n#include <vector>\n#include <cctype>\n#include <stack>\n#include <iomanip>\n//#include <boost/filesystem.hpp>\n\n\n\n\nusing std::string;\nusing std::bitset;\nusing std::max;\nusing std::ifstream;\nusing std::cout;\nusing std::cerr;\nusing std::vector;\n\n//namespace bfs = boost::filesystem;\n\nenum token_type {EMPTY, IDENTIFIER , KEYWORD,  OPERATOR , PUNCTUATOR , LITERAL, NUMBER};   //token types // glob\nconst char* token_name[] = {\"EMPTY\", \"IDENTIFIER\", \"KEYWORD\",  \"OPERATOR\", \"PUNCTUATOR\", \"LITERAL\", \"NUMBER\"};   //token types // glob\nconst int GAP_SCORE = -8;\n\n struct alignment\n\n {\n\n   bitset<3> both;\n   bitset<3> gap_x;\n   bitset<3> gap_y;\n\n   alignment()\n   {\n     both = 1;\n     gap_x = 2;\n     gap_y = 4;\n   }\n\n }align_type;\n\n struct tokens\n {\n\n    string token;\n    token_type type;\n\n }token;\n\n  class string_align\n{\n    private:\n    int nGap_score;\n    int id_matchScore,id_misScore,kw_matchScore,kw_misScore,op_matchScore,op_misScore,lit_matchScore,lit_misScore,num_matchScore,num_misScore;\n    int default_misScore;\n    std::vector<string> str_x,str_y;\n    std::vector<token_type> types_x, types_y;\n\n    public:\n    std::stack<string> str_x_aligned,str_y_aligned,str_match;\n\tstd::stack<tokens> token_x_aligned,token_y_aligned;\n\n    public:\n    string_align (std::vector<string> x, std::vector<token_type> x_types, std::vector<string> y, std::vector<token_type> y_types)\n     {\n        nGap_score = GAP_SCORE;\n        id_matchScore = 6;\n        id_misScore = 4;\n        kw_matchScore = 10;       //mis(match) score;\n        kw_misScore = -10;\n        op_matchScore = 8;\n        op_misScore = -10;\n        lit_matchScore = 7;\n        lit_misScore = 5;\n        num_matchScore = 7;\n        num_misScore = 0;\n        default_misScore = -10;\n        str_x = x;\n        types_x = x_types;\n        str_y = y;\n        types_y = y_types;\n     }\n\n    private:\n\n    bool has_flag(bitset<3> event, bitset<3> flag)\n    {\n        bitset<3> test = event & flag;\n        if (test.count() != 0) return true;\n        return false;\n    }\n\n   public:\n\n    int match_score (string x, token_type type_x , string y, token_type type_y)\n\n    {\n        if (type_x == type_y)\n        {\n            if (type_x == IDENTIFIER)\n            {\n                if (x==y) return id_matchScore;\n                return id_misScore;\n            }\n\n            if (type_x == KEYWORD)\n            {\n                if (x==y) return kw_matchScore;\n                return kw_misScore;\n            }\n\n            if (type_x == OPERATOR || type_x == PUNCTUATOR)\n            {\n                if (x==y) return op_matchScore;\n                return op_misScore;\n            }\n\n            if (type_x == LITERAL)\n            {\n                if (x==y) return lit_matchScore;\n                return lit_misScore;\n            }\n\n            if (type_x == NUMBER)\n            {\n                if (x==y) return num_matchScore;\n                return num_misScore;\n            }\n        }\n        return default_misScore;\n    }\n\n\n\n   int align()\n\n    {\n      int** scores = new int*[str_x.size()+1];\n      for(size_t i = 0; i < str_x.size()+1; ++i)\n      scores[i] = new int[str_y.size()+1];\n\n      scores[0][0] = 0;\n\n      bitset<3>** events = new bitset<3>*[str_x.size()+1];\n      for(size_t i = 0; i < str_x.size()+1; ++i)\n      events[i] = new bitset<3>[str_y.size()+1];\n\n\n\n      unsigned int i,j;\n\n      for (i = 1; i <= str_x.size(); i++)\n\t\t\t{\n\t\t\t\tscores[i][0] = scores[i - 1][0] + nGap_score;\n\t\t\t\tevents[i][0] = align_type.gap_y;\n\t\t\t}\n\n      for (j = 1; j <= str_y.size(); j++)\n\t\t\t{\n\t\t\t\tscores[0][j] = scores[0][j - 1] + nGap_score;\n\t\t\t\tevents[0][j] = align_type.gap_x;\n\t\t\t}\n\n\n\t  for (i = 1; i <= str_x.size(); i++)\n\t      for (j = 1; j <= str_y.size(); j++)\n\t  \t\t{\n\n\t          int m = scores[i-1][j-1] + match_score(str_x.at(i-1),types_x.at(i-1),str_y.at(j-1),types_y.at(j-1));\n\t          int g1 = scores[i-1][j] + nGap_score;\n\t          int g2 = scores[i][j-1] + nGap_score;\n\t          scores[i][j] = max(m,max(g1,g2));\n\t          bitset<3> type = align_type.both;\n\t          if (scores[i][j] == g1) type |= align_type.gap_y;\n\t          if (scores[i][j] == g2) type |= align_type.gap_x;\n\t          if (scores[i][j] > m ) type ^= align_type.both;\n\t          events[i][j] = type;\n\n\n            }\n\n       i = str_x.size();\n       j = str_y.size();\n\n      while (i > 0 || j > 0)\n\t\t\t{\n\t\t\t\tif (has_flag(events[i][j],align_type.both) && i > 0 && j > 0)\n\t\t\t\t{\n\t\t\t\t\tstr_x_aligned.push(str_x[--i]);\n\t\t\t\t\tstr_y_aligned.push(str_y[--j]);\n\t\t\t\t    str_match.push(str_x[i]==str_y[j] ? \"=\" : \"!\");\n\t\t\t\t\ttokens token_x = { str_x[i],types_x[i] },token_y = { str_y[j],types_y[j] };\n\t\t\t\t\ttoken_x_aligned.push(token_x);\n\t\t\t\t\ttoken_y_aligned.push(token_y);\n\t\t\t\t}\n\t\t\t\telse if (has_flag(events[i][j],align_type.gap_y) && i > 0)\n\t\t\t\t{\n\t\t\t\t\tstr_x_aligned.push(str_x[--i]);\n\t\t\t\t\tstr_y_aligned.push(\".\");\n\t\t\t\t\tstr_match.push(\"^\");\n\t\t\t\t\ttokens token_x = { str_x[i],types_x[i] },token_y = { \"\",EMPTY };\n\t\t\t\t\ttoken_x_aligned.push(token_x);\n\t\t\t\t\ttoken_y_aligned.push(token_y);\n\t\t\t\t}\n\t\t\t\telse if (has_flag(events[i][j],align_type.gap_x) && j > 0)\n\t\t\t\t{\n\t\t\t\t\tstr_x_aligned.push(\".\");\n\t\t\t\t\tstr_y_aligned.push(str_y[--j]);\n\t\t\t\t\tstr_match.push(\"v\");\n\t\t\t\t\ttokens token_x = { \"\",EMPTY },token_y = { str_y[j],types_y[j] };\n\t\t\t\t\ttoken_x_aligned.push(token_x);\n\t\t\t\t\ttoken_y_aligned.push(token_y);\n\t\t\t\t}\n\n            }\n\n\n     return scores[str_x.size()][str_y.size()];\n      }\n  };\n\n\nclass parsing\n{\n    public:\n    parsing (std::vector<string> kw)\n    {\n       kw_list = kw;\n    }\n\n\n    private:\n    std::vector<string> kw_list;\n    string entire;\n    std::string::iterator iter;\n\n\n    public:\n    std::vector<string> get_parsing()\n    {\n        return tokens;\n    }\n\n    public:\n    std::vector<token_type> get_types()\n    {\n        return types;\n    }\n\n\n\n    public:\n    int init (ifstream &f)\n          {\n            string extracted;\n            while (std::getline(f,extracted))\n                {\n                        for (iter = extracted.begin(); iter != extracted.end(); iter++)    // corr. testing\n                    {\n\n                              if (*iter == '\"')\n                         {\n                            iter++;\n                            if (iter == extracted.end()) return -1;\n                            while (*iter != '\"')\n                            {\n                              iter++;\n                              if (iter == extracted.end()) return -1;\n                            }\n                         }\n                           if (*iter == '\\'')\n                         {\n                            iter++;\n                            if (iter == extracted.end()) return -1;\n                            while (*iter != '\\'')\n                            {\n                              iter++;\n                              if (iter == extracted.end()) return -1;\n                            }\n                         }\n\n                         if (*iter == '/' && *(iter+1) == '/')\n                         {\n                            extracted.erase(iter, extracted.end());\n                            break;\n                         }\n\n                    }\n                    entire += extracted;\n                    extracted.clear();\n                }\n\n                for (iter = entire.begin(); iter != entire.end(); iter++)\n                {\n                    if (*iter == '\"')\n                    {\n                        iter++;\n                        while (*iter != '\"') iter++;\n                    }\n\n                    if (*iter == '\\'')\n                    {\n                        iter++;\n                        while (*iter != '\\'') iter++;\n                    }\n\n                    if (*iter == '/' && *(iter+1) == '*')\n                    {\n                        std::string::iterator tmp = iter;\n                        iter += 2;\n                        while ((*iter != '*' || *(iter+1) != '/')  && iter != entire.end())\n                        {\n                          iter++;\n                        }\n                        if (iter == entire.end())\n                        {\n                            entire.erase(tmp,entire.end());\n                            break;\n                        }\n                        iter += 2;\n                        iter = entire.erase(tmp,iter);\n                    }\n                }\n\n            return 0;\n          }\n\n\n    public:\n    void str_format ()\n    {\n\n       for (iter = entire.begin(); iter != entire.end(); iter++)     //deleting exc. ws\n             if (isspace(*iter))\n                if ((!is_idensym(*(iter+1)) || !is_idensym(*(iter-1))) && (!is_punsym((iter+1)) || !is_punsym((iter-1)))   )\n                {\n                    iter = entire.erase(iter) - 1;\n                }\n       for (iter = entire.begin(); iter != entire.end(); iter++)   //add req.\n       {\n          if (is_idensym(*iter))\n          {\n\n            switch (*(iter-1))\n            {\n                case '-':\n                if (*(iter-2) == '-') iter = entire.insert(iter-2,' ') + 3;\n                break;\n                case '+':\n                if (*(iter-2) == '+') iter = entire.insert(iter-2,' ') + 3;\n                break;\n            }\n\n\n            if (*(iter-1) == '!' || *(iter-1) == '~')\n             {\n                if (*(iter-2) == '+' || *(iter-2) == '-')\n                    if (*(iter-3) == '+' || *(iter-3) == '-')\n                    iter = entire.insert(iter-3,' ') + 4;\n                iter = entire.insert(iter-1,' ') + 2;\n             }\n\n\n             if (*(iter-1) == '*')\n             {\n                int k = 1;\n                iter--;\n                while (*iter == '*')\n                {\n                    iter--;\n                    k++;\n                }\n                iter++;\n                if (*(iter-1) == '+' || *(iter-1) == '-')\n                    if (*(iter-2) == '+' || *(iter-2) == '-')\n                      iter = entire.insert(iter-2,' ') + 3;\n                iter = entire.insert(iter,' ') + k;\n             }\n            if (*(iter-1) == '&')\n             {\n                int k = 1;\n                iter--;\n                while (*iter == '&')\n                {\n                    iter--;\n                    k++;\n                }\n                iter++;\n                if (*(iter-1) == '+' || *(iter-1) == '-')\n                    if (*(iter-2) == '+' || *(iter-2) == '-')\n                      iter = entire.insert(iter-2,' ') + 3;\n                iter = entire.insert(iter,' ') + k;\n             }\n\n              switch (*(iter+1))\n            {\n                case '-':\n                if (*(iter+2) == '-') iter = entire.insert(iter+3,' ') - 3;\n                break;\n                case '+':\n                if (*(iter+2) == '+') iter = entire.insert(iter+3,' ') - 3;\n                break;\n\n            }\n\n           if  (*(iter+1) == '*')\n            {\n                int k = 1;\n                iter++;\n                while (*iter == '*')\n                {\n                    iter++;\n                    k++;\n                }\n                iter = entire.insert(iter,' ') - k;\n            }\n             if  (*(iter+1) == '&')\n            {\n                int k = 1;\n                iter++;\n                while (*iter == '&')\n                {\n                    iter++;\n                    k++;\n                }\n                iter = entire.insert(iter,' ') - k;\n            }\n        }\n          switch (*iter)\n          {\n            case '(':case ')': case '[': case ']': case '{': case '}': case '\"': case '\\'': case '#':\n            iter = entire.insert(iter+1,' ') - 1;\n            iter = entire.insert(iter,' ') + 1;\n            break;\n            case '.':\n            if (!isdigit(*(iter-1))) iter = entire.insert(iter,' ') + 1;\n            break;\n          }\n\n       }\n    }\n\n    private:      //inspector functions\n\n    bool is_idensym(char c)\n    {\n        return isalnum(c) || c == '_' || c == '$';\n    }\n\n    bool is_punsym(std::string::iterator iter)\n    {\n      if (*iter == '.' && isdigit(*(iter+1))) return false;\n      static string pun_sym = \"(){}+-*/=<>.,;:[]%!&|~^#'\\\"?\";\n        return pun_sym.find(*iter) != std::string::npos;\n    }\n\n    bool is_keyword (string token)\n\n    {\n      for (std::vector<string>::iterator iter = kw_list.begin(); iter != kw_list.end(); iter ++)\n      {\n        if (token == *iter) return true;\n      }\n\n      return false;\n    }\n\n      bool is_numsym (std::string::iterator iter)\n\n    {\n      static string num_spsym = \"ex-.ABCDEF\";\n      if (*iter == '.')\n      {\n          return isdigit(*(iter + 1)) != 0;\n      }\n      if (*iter == '-')\n      {\n\n          return *(iter - 1) == 'e' || *(iter - 1) == 'E';\n\n      }\n        return isdigit(*iter) || num_spsym.find(*iter) != std::string::npos;\n    }\n\n\n\n    private:\n    vector<string> tokens;\n    vector<token_type> types;\n    string curr_tok;\n\n    public:\n    void dismember()\n    {\n\n      for (iter = entire.begin();iter != entire.end();)\n      {\n\n        if (isalpha(*iter) || (*iter) == '_' || (*iter == '$'))\n        {\n\n          while (is_idensym(*iter))\n           {\n                curr_tok += *iter;\n                iter++;\n           }\n\n          tokens.push_back(curr_tok);\n\n          if (is_keyword(curr_tok))\n          {\n           types.push_back(KEYWORD);\n          }\n          else\n          {\n            types.push_back(IDENTIFIER);\n          }\n          curr_tok.clear();\n        } else\n       if (is_punsym(iter))\n       {\n         int flag = 0;\n             if (*iter == '\"')\n             {\n                curr_tok += *iter++;\n                while (*iter != '\"')\n                {\n                    curr_tok += *iter++;\n                }\n                curr_tok += *iter++;\n                tokens.push_back(curr_tok);\n                types.push_back(LITERAL);\n                curr_tok.clear();\n                flag = 1;\n             }\n         if (!flag)\n         {\n             if (*iter == '\\'')\n             {\n                curr_tok += *iter++;\n                while (*iter != '\\'')\n                {\n                    curr_tok += *iter++;\n                }\n                curr_tok += *iter++;\n                tokens.push_back(curr_tok);\n                types.push_back(LITERAL);\n                curr_tok.clear();\n                flag = 1;\n             }\n         }\n         if (!flag)\n         {\n             while (is_punsym(iter))\n             {\n               curr_tok += *iter;\n               iter++;\n             }\n             tokens.push_back(curr_tok);\n             if (curr_tok == \"#\" || curr_tok == \";\") types.push_back(PUNCTUATOR); else types.push_back(OPERATOR);\n             curr_tok.clear();\n         }\n        } else\n\n       if (isdigit(*iter) || *iter == '.')\n       {\n         while (is_numsym(iter))\n         {\n            curr_tok += *iter;\n            iter++;\n         }\n         tokens.push_back(curr_tok);\n         types.push_back(NUMBER);\n         curr_tok.clear();\n       } else\n         iter++;\n     }\n   }\n\n\n  };\n\n\n\n\nint main (int argc, const char **argv)\n{\nifstream kw_list;\nstring extracted;\nkw_list.open(\"keywords_reserved.txt\");\nstd::vector<string> kw;\nwhile (std::getline(kw_list,extracted)) kw.push_back(extracted);\n\nif (argc < 3)\n    {\n        cerr << \"File isn't specified\";\n        return -1;\n    }\n\n\nstd::vector<string> file1_parsed,file2_parsed;\nstd::vector<token_type> file1_types,file2_types;\nifstream f1,f2;\nf1.open(argv[1]);\nf2.open(argv[2]);\n\nparsing file1 (kw);\nparsing file2 (kw);\nif (file1.init(f1) || file2.init(f2))\n{\n    cerr << \"Some of files are unsafe for parsing\";\n    return -1;\n}\n\nfile1.str_format();\nfile2.str_format();\n\nfile1.dismember();\nfile2.dismember();\nfile1_parsed = file1.get_parsing();\nfile2_parsed = file2.get_parsing();\nfile1_types = file1.get_types();\nfile2_types = file2.get_types();\nstring_align alignment(file1_parsed,file1_types,file2_parsed, file2_types);\nint scores = alignment.align();\n\n\n\n\nint amount = 0;\n\n//std::stack<string> *xa = &alignment.str_x_aligned,*ya = &alignment.str_y_aligned;\nstd::stack<tokens> *xa = &alignment.token_x_aligned,*ya = &alignment.token_y_aligned;\n\nwhile(!xa->empty() && !ya->empty())\n{\n//if(!xa->empty())\n//{\n\tcout << xa->top().token << '\\t' << ya->top().token << '\\t'\n\t\t<< (xa->top().type != EMPTY && ya->top().type != EMPTY\n\t\t\t? alignment.match_score(xa->top().token,xa->top().type,ya->top().token,ya->top().type)\n\t\t\t: GAP_SCORE)\n\t\t<< '/' << token_name[xa->top().type] << '/' << token_name[ya->top().type]\n\t\t<< std::endl;\n\n\txa->pop();\n\tya->pop();\n\tamount++;\n}\n\ncout << \"Score: \" << scores << std::endl << \"Amount: \" << amount << std::endl;\ndouble plag = ((double)scores) / (6*amount); // - 0.25;    //empirically\nif (plag < 0) plag = 0;\nif (plag > 1) plag = 1;\ndouble uniqueness = 1-plag;\ncout << \"Uniqueness:\" << uniqueness;\n\n\n}\n\n\n", "meta": {"hexsha": "3c135bbe0635154d5d94e733a2645bd11eba481e", "size": 16908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "old/main2.cpp", "max_stars_repo_name": "razorkam/schleiermacher", "max_stars_repo_head_hexsha": "f4bfb013613e08145ee9059e17d0f826cffb807b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-05T05:51:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-17T18:51:25.000Z", "max_issues_repo_path": "old/main2.cpp", "max_issues_repo_name": "razorkam/schleiermacher", "max_issues_repo_head_hexsha": "f4bfb013613e08145ee9059e17d0f826cffb807b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "old/main2.cpp", "max_forks_repo_name": "razorkam/schleiermacher", "max_forks_repo_head_hexsha": "f4bfb013613e08145ee9059e17d0f826cffb807b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3873873874, "max_line_length": 142, "alphanum_fraction": 0.4179086823, "num_tokens": 4137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.37754065479083276, "lm_q1q2_score": 0.22375573621931605}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#include \"piecewise_polynomial_continuous_scalar_space.hpp\"\n\n#include \"piecewise_polynomial_discontinuous_scalar_space.hpp\"\n#include \"space_helper.hpp\"\n\n#include \"../assembly/discrete_sparse_boundary_operator.hpp\"\n#include \"../common/acc.hpp\"\n#include \"../common/boost_make_shared_fwd.hpp\"\n#include \"../common/bounding_box_helpers.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../fiber/lagrange_scalar_shapeset.hpp\"\n#include \"../grid/entity.hpp\"\n#include \"../grid/entity_iterator.hpp\"\n#include \"../grid/geometry.hpp\"\n#include \"../grid/grid.hpp\"\n#include \"../grid/grid_segment.hpp\"\n#include \"../grid/grid_view.hpp\"\n#include \"../grid/mapper.hpp\"\n#include \"../grid/vtk_writer.hpp\"\n\n#include <stdexcept>\n#include <iostream>\n\n#include <boost/array.hpp>\n\nnamespace Bempp {\n\ntemplate <typename BasisFunctionType>\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::\n    PiecewisePolynomialContinuousScalarSpace(const shared_ptr<const Grid> &grid,\n                                             int polynomialOrder)\n    : ScalarSpace<BasisFunctionType>(grid), m_polynomialOrder(polynomialOrder),\n      m_segment(GridSegment::wholeGrid(*grid)), m_strictlyOnSegment(false),\n      m_flatLocalDofCount(0) {\n  initialize();\n}\n\ntemplate <typename BasisFunctionType>\nbool\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::spaceIsCompatible(\n    const Space<BasisFunctionType> &other) const {\n\n  typedef PiecewisePolynomialContinuousScalarSpace<BasisFunctionType>\n  thisSpaceType;\n\n  if (other.grid().get() != this->grid().get())\n    return false;\n\n  if (other.spaceIdentifier() == this->spaceIdentifier()) {\n    // Try to typecast the other space down.\n    const thisSpaceType &temp = dynamic_cast<const thisSpaceType &>(other);\n    if (this->m_polynomialOrder == temp.m_polynomialOrder)\n      return true;\n    else\n      return false;\n  } else\n    return false;\n}\n\ntemplate <typename BasisFunctionType>\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::\n    PiecewisePolynomialContinuousScalarSpace(const shared_ptr<const Grid> &grid,\n                                             int polynomialOrder,\n                                             const GridSegment &segment,\n                                             bool strictlyOnSegment)\n    : ScalarSpace<BasisFunctionType>(grid), m_polynomialOrder(polynomialOrder),\n      m_segment(segment), m_strictlyOnSegment(strictlyOnSegment),\n      m_flatLocalDofCount(0) {\n  initialize();\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::initialize() {\n  const int gridDim = this->grid()->dim();\n  if (gridDim != 2)\n    throw std::invalid_argument(\"PiecewisePolynomialContinuousScalarSpace::\"\n                                \"PiecewisePolynomialContinuousScalarSpace(): \"\n                                \"2-dimensional grids are supported\");\n  m_view = this->grid()->leafView();\n  if (m_polynomialOrder == 1)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarShapeset<3, BasisFunctionType, 1>());\n  else if (m_polynomialOrder == 2)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarShapeset<3, BasisFunctionType, 2>());\n  else if (m_polynomialOrder == 3)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarShapeset<3, BasisFunctionType, 3>());\n  else if (m_polynomialOrder == 4)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarShapeset<3, BasisFunctionType, 4>());\n  else if (m_polynomialOrder == 5)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarShapeset<3, BasisFunctionType, 5>());\n  else if (m_polynomialOrder == 6)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarShapeset<3, BasisFunctionType, 6>());\n  else if (m_polynomialOrder == 7)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarShapeset<3, BasisFunctionType, 7>());\n  else if (m_polynomialOrder == 8)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarShapeset<3, BasisFunctionType, 8>());\n  else if (m_polynomialOrder == 9)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarShapeset<3, BasisFunctionType, 9>());\n  else if (m_polynomialOrder == 10)\n    m_triangleShapeset.reset(\n        new Fiber::LagrangeScalarShapeset<3, BasisFunctionType, 10>());\n  else\n    throw std::invalid_argument(\"PiecewisePolynomialContinuousScalarSpace::\"\n                                \"PiecewisePolynomialContinuousScalarSpace(): \"\n                                \"polynomialOrder must be >= 1 and <= 10\");\n  assignDofsImpl();\n}\n\ntemplate <typename BasisFunctionType>\nPiecewisePolynomialContinuousScalarSpace<\n    BasisFunctionType>::~PiecewisePolynomialContinuousScalarSpace() {}\n\ntemplate <typename BasisFunctionType>\nint\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::domainDimension()\n    const {\n  return this->grid()->dim();\n}\n\ntemplate <typename BasisFunctionType>\nint\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::codomainDimension()\n    const {\n  return 1;\n}\n\ntemplate <typename BasisFunctionType>\nconst Fiber::Shapeset<BasisFunctionType> &\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::shapeset(\n    const Entity<0> &element) const {\n  if (elementVariant(element) == 3)\n    return *m_triangleShapeset;\n  throw std::logic_error(\n      \"PiecewisePolynomialContinuousScalarSpace::shapeset(): \"\n      \"invalid element variant, this shouldn't happen!\");\n}\n\ntemplate <typename BasisFunctionType>\nElementVariant\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::elementVariant(\n    const Entity<0> &element) const {\n  GeometryType type = element.type();\n  if (type.isLine())\n    return 2;\n  else if (type.isTriangle())\n    return 3;\n  else if (type.isQuadrilateral())\n    return 4;\n  else\n    throw std::runtime_error(\"PiecewisePolynomialContinuousScalarSpace::\"\n                             \"elementVariant(): invalid geometry type, \"\n                             \"this shouldn't happen!\");\n}\n\ntemplate <typename BasisFunctionType>\nvoid\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::setElementVariant(\n    const Entity<0> &element, ElementVariant variant) {\n  if (variant != elementVariant(element))\n    // for this space, the element variants are unmodifiable,\n    throw std::runtime_error(\"PiecewisePolynomialContinuousScalarSpace::\"\n                             \"setElementVariant(): invalid variant\");\n}\n\ntemplate <typename BasisFunctionType>\nshared_ptr<const Space<BasisFunctionType>>\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::discontinuousSpace(\n    const shared_ptr<const Space<BasisFunctionType>> &self) const {\n  if (!m_discontinuousSpace) {\n    tbb::mutex::scoped_lock lock(m_discontinuousSpaceMutex);\n    typedef PiecewisePolynomialDiscontinuousScalarSpace<BasisFunctionType>\n    DiscontinuousSpace;\n    if (!m_discontinuousSpace)\n      m_discontinuousSpace.reset(\n          new DiscontinuousSpace(this->grid(), m_polynomialOrder, m_segment));\n  }\n  return m_discontinuousSpace;\n}\n\ntemplate <typename BasisFunctionType>\nbool\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::isDiscontinuous()\n    const {\n  return false;\n}\n\ntemplate <typename BasisFunctionType>\nvoid\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::assignDofsImpl() {\n  // TODO: refactor this function, it's way too long!\n\n  // In addition to DOF assignment, this function also precalculates bounding\n  // boxes of global DOFs\n\n  const int elementCount = m_view->entityCount(0);\n  if (elementCount == 0)\n    return;\n  const int gridDim = this->domainDimension();\n  if (gridDim != 2)\n    throw std::runtime_error(\"PiecewisePolynomialContinuousScalarSpace::\"\n                             \"assignDofsImpl(): only 2-dimensional grids \"\n                             \"are supported at present\");\n  const int vertexCodim = gridDim;\n  const int edgeCodim = vertexCodim - 1;\n\n  // const Mapper& elementMapper = m_view->elementMapper();\n  const IndexSet &indexSet = m_view->indexSet();\n\n  // Map vertices to global dofs\n  const int vertexCount = m_view->entityCount(2);\n  // At first, the elements of this vector will be set to the number of\n  // DOFs corresponding to a given vertex or to -1 if that vertex is to be\n  // ignored\n  std::vector<GlobalDofIndex> vertexGlobalDofs(vertexCount);\n  for (int i = 0; i < vertexCount; ++i)\n    if (m_segment.contains(gridDim, i))\n      acc(vertexGlobalDofs, (size_t)i) = 1;\n    else\n      acc(vertexGlobalDofs, (size_t)i) = -1;\n\n  // Map edges to global dofs\n  const int edgeCount = m_view->entityCount(1);\n  const int internalDofCountPerEdge = m_polynomialOrder - 1;\n  // At first, the elements of this vector will be set to the number of\n  // DOFs corresponding to a given edge or to -1 if that edge is to be\n  // ignored\n  std::vector<GlobalDofIndex> edgeStartingGlobalDofs(edgeCount);\n  for (int i = 0; i < edgeCount; ++i)\n    if (m_segment.contains(gridDim - 1, i))\n      acc(edgeStartingGlobalDofs, i) = internalDofCountPerEdge;\n    else\n      acc(edgeStartingGlobalDofs, i) = -1;\n\n  // Map element interiors to global dofs\n  // and, if striclyOnSegment is set, detect vertices and edges not belonging\n  // to any element on segment\n  const int bubbleDofCountPerTriangle =\n      std::max(0, (m_polynomialOrder - 1) * (m_polynomialOrder - 2) / 2);\n  const int bubbleDofCountPerQuad =\n      std::max(0, (m_polynomialOrder - 1) * (m_polynomialOrder - 1));\n  // At first, the elements of this vector will be set to the number of\n  // DOFs corresponding to a given element or to -1 if that element is to be\n  // ignored\n  std::vector<GlobalDofIndex> bubbleStartingGlobalDofs(elementCount);\n  std::vector<bool> noElementAdjacentToVertexIsOnSegment(vertexCount, true);\n  std::vector<bool> noElementAdjacentToEdgeIsOnSegment(edgeCount, true);\n  std::unique_ptr<EntityIterator<0>> it = m_view->entityIterator<0>();\n  while (!it->finished()) {\n    const Entity<0> &element = it->entity();\n    EntityIndex elementIndex = indexSet.entityIndex(element);\n    int vertexCount = element.template subEntityCount<2>();\n    if (vertexCount != 3 && vertexCount != 4)\n      throw std::runtime_error(\"PiecewisePolynomialContinuousScalarSpace::\"\n                               \"assignDofsImpl(): elements must be \"\n                               \"triangular or quadrilateral\");\n    if (m_segment.contains(0, elementIndex)) {\n      acc(bubbleStartingGlobalDofs, elementIndex) =\n          vertexCount == 3 ? bubbleDofCountPerTriangle : bubbleDofCountPerQuad;\n      if (m_strictlyOnSegment)\n        for (int i = 0; i < vertexCount; ++i) {\n          int index = indexSet.subEntityIndex(element, i, gridDim);\n          acc(noElementAdjacentToVertexIsOnSegment, index) = false;\n          index = indexSet.subEntityIndex(element, i, gridDim - 1);\n          acc(noElementAdjacentToEdgeIsOnSegment, index) = false;\n        }\n    } else\n      acc(bubbleStartingGlobalDofs, elementIndex) = -1;\n    it->next();\n  }\n\n  // If strictlyOnSegment is set, deactivate vertices and edges not adjacent\n  // to any element in segment\n  if (m_strictlyOnSegment) {\n    for (int i = 0; i < vertexCount; ++i)\n      if (acc(noElementAdjacentToVertexIsOnSegment, i))\n        acc(vertexGlobalDofs, i) = -1;\n\n    for (int i = 0; i < edgeCount; ++i)\n      if (acc(noElementAdjacentToEdgeIsOnSegment, i))\n        acc(edgeStartingGlobalDofs, i) = -1;\n  }\n\n  // Assign global dofs to entities\n  int globalDofCount_ = 0;\n  for (int i = 0; i < vertexCount; ++i)\n    if (acc(vertexGlobalDofs, i) == 1)\n      acc(vertexGlobalDofs, i) = globalDofCount_++;\n  for (int i = 0; i < edgeCount; ++i) {\n    int dofCount = acc(edgeStartingGlobalDofs, i);\n    if (dofCount > 0) {\n      acc(edgeStartingGlobalDofs, i) = globalDofCount_;\n      globalDofCount_ += dofCount;\n    }\n  }\n  for (int i = 0; i < elementCount; ++i) {\n    int dofCount = acc(bubbleStartingGlobalDofs, i);\n    if (dofCount > 0) {\n      acc(bubbleStartingGlobalDofs, i) = globalDofCount_;\n      globalDofCount_ += dofCount;\n    }\n  }\n\n  // Initialise DOF maps\n  const int localDofCountPerTriangle =\n      (m_polynomialOrder + 1) * (m_polynomialOrder + 2) / 2;\n  m_local2globalDofs.clear();\n  std::vector<GlobalDofIndex> prototypeGlobalDofs;\n  prototypeGlobalDofs.reserve(localDofCountPerTriangle);\n  m_local2globalDofs.resize(elementCount, prototypeGlobalDofs);\n  m_global2localDofs.clear();\n  // std::vector<LocalDof> prototypeLocalDofs;\n  // prototypeLocalDofs.reserve(localDofCountPerTriangle);\n  m_global2localDofs.resize(globalDofCount_ /*, prototypeLocalDofs*/);\n\n  // Initialise bounding-box caches\n  BoundingBox<CoordinateType> model;\n  model.lbound.x = std::numeric_limits<CoordinateType>::max();\n  model.lbound.y = std::numeric_limits<CoordinateType>::max();\n  model.lbound.z = std::numeric_limits<CoordinateType>::max();\n  model.ubound.x = -std::numeric_limits<CoordinateType>::max();\n  model.ubound.y = -std::numeric_limits<CoordinateType>::max();\n  model.ubound.z = -std::numeric_limits<CoordinateType>::max();\n  m_globalDofBoundingBoxes.resize(globalDofCount_, model);\n\n  // Iterate over elements\n  it = m_view->entityIterator<0>();\n  arma::Mat<CoordinateType> vertices;\n  arma::Col<CoordinateType> dofPosition;\n  m_flatLocalDofCount = 0;\n  std::vector<int> gdofAccessCounts(globalDofCount_, 0);\n  while (!it->finished()) {\n    const Entity<0> &element = it->entity();\n    const Geometry &geo = element.geometry();\n    EntityIndex elementIndex = indexSet.entityIndex(element);\n    bool elementContained =\n        !m_strictlyOnSegment || m_segment.contains(0, elementIndex);\n\n    geo.getCorners(vertices);\n    int vertexCount = vertices.n_cols;\n\n    // List of global DOF indices corresponding to the local DOFs of the\n    // current element\n    std::vector<GlobalDofIndex> &globalDofs =\n        acc(m_local2globalDofs, elementIndex);\n    if (vertexCount == 3) {\n      std::vector<int> ldofAccessCounts(localDofCountPerTriangle, 0);\n      boost::array<int, 3> vertexIndices;\n      for (int i = 0; i < 3; ++i)\n        acc(vertexIndices, i) =\n            indexSet.subEntityIndex(element, i, vertexCodim);\n      globalDofs.resize(localDofCountPerTriangle);\n      // vertex dofs\n      {\n        int ldof, gdof;\n\n        ldof = 0;\n        if (elementContained)\n          gdof = vertexGlobalDofs[acc(vertexIndices, 0)];\n        else\n          gdof = -1;\n        if (gdof >= 0) {\n          acc(globalDofs, ldof) = gdof;\n          acc(m_global2localDofs, gdof).push_back(LocalDof(elementIndex, ldof));\n          ++acc(gdofAccessCounts, gdof);\n          extendBoundingBox(acc(m_globalDofBoundingBoxes, gdof), vertices);\n          setBoundingBoxReference<CoordinateType>(\n              acc(m_globalDofBoundingBoxes, gdof), vertices.col(0));\n          ++m_flatLocalDofCount;\n        } else\n          acc(globalDofs, ldof) = -1;\n        ++acc(ldofAccessCounts, ldof);\n\n        ldof = m_polynomialOrder;\n        if (elementContained)\n          gdof = vertexGlobalDofs[acc(vertexIndices, 1)];\n        else\n          gdof = -1;\n        if (gdof >= 0) {\n          acc(globalDofs, ldof) = gdof;\n          acc(m_global2localDofs, gdof).push_back(LocalDof(elementIndex, ldof));\n          ++acc(gdofAccessCounts, gdof);\n          extendBoundingBox(acc(m_globalDofBoundingBoxes, gdof), vertices);\n          setBoundingBoxReference<CoordinateType>(\n              acc(m_globalDofBoundingBoxes, gdof), vertices.col(1));\n          ++m_flatLocalDofCount;\n        } else\n          acc(globalDofs, ldof) = -1;\n        ++acc(ldofAccessCounts, ldof);\n\n        ldof = localDofCountPerTriangle - 1;\n        if (elementContained)\n          gdof = vertexGlobalDofs[acc(vertexIndices, 2)];\n        else\n          gdof = -1;\n        if (gdof >= 0) {\n          acc(globalDofs, ldof) = gdof;\n          acc(m_global2localDofs, gdof).push_back(LocalDof(elementIndex, ldof));\n          ++acc(gdofAccessCounts, gdof);\n          extendBoundingBox(acc(m_globalDofBoundingBoxes, gdof), vertices);\n          setBoundingBoxReference<CoordinateType>(\n              acc(m_globalDofBoundingBoxes, gdof), vertices.col(2));\n          ++m_flatLocalDofCount;\n        } else\n          acc(globalDofs, ldof) = -1;\n        ++acc(ldofAccessCounts, ldof);\n      }\n\n      // edge dofs\n      if (m_polynomialOrder >= 2) {\n        int start, end, step;\n        int edgeIndex;\n\n        edgeIndex = indexSet.subEntityIndex(element, 0, edgeCodim);\n        dofPosition = 0.5 * (vertices.col(0) + vertices.col(1));\n        if (acc(edgeStartingGlobalDofs, edgeIndex) >= 0 && elementContained) {\n          if (acc(vertexIndices, 0) < acc(vertexIndices, 1)) {\n            start = acc(edgeStartingGlobalDofs, edgeIndex);\n            end = start + internalDofCountPerEdge;\n            step = 1;\n          } else {\n            end = acc(edgeStartingGlobalDofs, edgeIndex) - 1;\n            start = end + internalDofCountPerEdge;\n            step = -1;\n          }\n          for (int ldof = 1, gdof = start; gdof != end; ++ldof, gdof += step) {\n            acc(globalDofs, ldof) = gdof;\n            acc(m_global2localDofs, gdof)\n                .push_back(LocalDof(elementIndex, ldof));\n            ++acc(ldofAccessCounts, ldof);\n            ++acc(gdofAccessCounts, gdof);\n            extendBoundingBox(acc(m_globalDofBoundingBoxes, gdof), vertices);\n            setBoundingBoxReference<CoordinateType>(\n                acc(m_globalDofBoundingBoxes, gdof), dofPosition);\n            ++m_flatLocalDofCount;\n          }\n        } else\n          for (int ldof = 1; ldof <= internalDofCountPerEdge; ++ldof) {\n            acc(globalDofs, ldof) = -1;\n            ++acc(ldofAccessCounts, ldof);\n          }\n\n        edgeIndex = indexSet.subEntityIndex(element, 1, edgeCodim);\n        dofPosition = 0.5 * (vertices.col(0) + vertices.col(2));\n        if (acc(edgeStartingGlobalDofs, edgeIndex) >= 0 && elementContained) {\n          if (acc(vertexIndices, 0) < acc(vertexIndices, 2)) {\n            start = acc(edgeStartingGlobalDofs, edgeIndex);\n            end = start + internalDofCountPerEdge;\n            step = 1;\n          } else {\n            end = acc(edgeStartingGlobalDofs, edgeIndex) - 1;\n            start = end + internalDofCountPerEdge;\n            step = -1;\n          }\n          for (int ldofy = 1, gdof = start; gdof != end;\n               ++ldofy, gdof += step) {\n            int ldof =\n                ldofy * (m_polynomialOrder + 1) - ldofy * (ldofy - 1) / 2;\n            acc(globalDofs, ldof) = gdof;\n            acc(m_global2localDofs, gdof)\n                .push_back(LocalDof(elementIndex, ldof));\n            ++acc(ldofAccessCounts, ldof);\n            ++acc(gdofAccessCounts, gdof);\n            extendBoundingBox(acc(m_globalDofBoundingBoxes, gdof), vertices);\n            setBoundingBoxReference<CoordinateType>(\n                acc(m_globalDofBoundingBoxes, gdof), dofPosition);\n            ++m_flatLocalDofCount;\n          }\n        } else\n          for (int ldofy = 1; ldofy <= internalDofCountPerEdge; ++ldofy) {\n            int ldof =\n                ldofy * (m_polynomialOrder + 1) - ldofy * (ldofy - 1) / 2;\n            acc(globalDofs, ldof) = -1;\n            ++acc(ldofAccessCounts, ldof);\n          }\n\n        edgeIndex = indexSet.subEntityIndex(element, 2, edgeCodim);\n        dofPosition = 0.5 * (vertices.col(1) + vertices.col(2));\n        if (acc(edgeStartingGlobalDofs, edgeIndex) >= 0 && elementContained) {\n          if (acc(vertexIndices, 1) < acc(vertexIndices, 2)) {\n            start = acc(edgeStartingGlobalDofs, edgeIndex);\n            end = start + internalDofCountPerEdge;\n            step = 1;\n          } else {\n            end = acc(edgeStartingGlobalDofs, edgeIndex) - 1;\n            start = end + internalDofCountPerEdge;\n            step = -1;\n          }\n          for (int ldofy = 1, gdof = start; gdof != end;\n               ++ldofy, gdof += step) {\n            int ldof = ldofy * (m_polynomialOrder + 1) -\n                       ldofy * (ldofy - 1) / 2 + (m_polynomialOrder - ldofy);\n            acc(globalDofs, ldof) = gdof;\n            acc(m_global2localDofs, gdof)\n                .push_back(LocalDof(elementIndex, ldof));\n            ++acc(ldofAccessCounts, ldof);\n            ++acc(gdofAccessCounts, gdof);\n            extendBoundingBox(acc(m_globalDofBoundingBoxes, gdof), vertices);\n            setBoundingBoxReference<CoordinateType>(\n                acc(m_globalDofBoundingBoxes, gdof), dofPosition);\n            ++m_flatLocalDofCount;\n          }\n        } else\n          for (int ldofy = 1; ldofy <= internalDofCountPerEdge; ++ldofy) {\n            int ldof = ldofy * (m_polynomialOrder + 1) -\n                       ldofy * (ldofy - 1) / 2 + (m_polynomialOrder - ldofy);\n            acc(globalDofs, ldof) = -1;\n            ++acc(ldofAccessCounts, ldof);\n          }\n      }\n\n      // bubble dofs\n      if (m_polynomialOrder >= 3) {\n        dofPosition =\n            (vertices.col(0) + vertices.col(1) + vertices.col(2)) / 3.;\n        bool useDofs = acc(bubbleStartingGlobalDofs, elementIndex) >= 0;\n        for (int ldofy = 1, gdof = acc(bubbleStartingGlobalDofs, elementIndex);\n             ldofy < m_polynomialOrder; ++ldofy)\n          for (int ldofx = 1; ldofx + ldofy < m_polynomialOrder;\n               ++ldofx, ++gdof) {\n            int ldof = ldofy * (m_polynomialOrder + 1) -\n                       ldofy * (ldofy - 1) / 2 + ldofx;\n            if (useDofs) {\n              acc(globalDofs, ldof) = gdof;\n              acc(m_global2localDofs, gdof)\n                  .push_back(LocalDof(elementIndex, ldof));\n              ++acc(gdofAccessCounts, gdof);\n              extendBoundingBox(acc(m_globalDofBoundingBoxes, gdof), vertices);\n              setBoundingBoxReference<CoordinateType>(\n                  acc(m_globalDofBoundingBoxes, gdof), dofPosition);\n              ++m_flatLocalDofCount;\n            } else\n              acc(globalDofs, ldof) = -1;\n            ++acc(ldofAccessCounts, ldof);\n          }\n      }\n      for (size_t i = 0; i < ldofAccessCounts.size(); ++i)\n        assert(acc(ldofAccessCounts, i) == 1);\n    } else\n      throw std::runtime_error(\"PiecewisePolynomialContinuousScalarSpace::\"\n                               \"assignDofsImpl(): quadrilateral elements \"\n                               \"are not supported yet\");\n\n    it->next();\n  }\n// for (size_t i = 0; i < gdofAccessCounts.size(); ++i)\n//     std::cout << i << \" \" << acc(gdofAccessCounts, i) << \"\\n\";\n\n#ifndef NDEBUG\n  for (size_t i = 0; i < globalDofCount_; ++i) {\n    const BoundingBox<CoordinateType> &bbox = acc(m_globalDofBoundingBoxes, i);\n\n    assert(bbox.reference.x >= bbox.lbound.x);\n    assert(bbox.reference.y >= bbox.lbound.y);\n    assert(bbox.reference.z >= bbox.lbound.z);\n    assert(bbox.reference.x <= bbox.ubound.x);\n    assert(bbox.reference.y <= bbox.ubound.y);\n    assert(bbox.reference.z <= bbox.ubound.z);\n  }\n#endif // NDEBUG\n\n  // Initialize the container mapping the flat local dof indices to\n  // local dof indices\n  SpaceHelper<BasisFunctionType>::initializeLocal2FlatLocalDofMap(\n      m_flatLocalDofCount, m_local2globalDofs, m_flatLocal2localDofs);\n}\n\ntemplate <typename BasisFunctionType>\nsize_t\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::globalDofCount()\n    const {\n  return m_global2localDofs.size();\n}\n\ntemplate <typename BasisFunctionType>\nsize_t\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::flatLocalDofCount()\n    const {\n  return m_flatLocalDofCount;\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::getGlobalDofs(\n    const Entity<0> &element, std::vector<GlobalDofIndex> &dofs) const {\n  const Mapper &mapper = m_view->elementMapper();\n  EntityIndex index = mapper.entityIndex(element);\n  dofs = m_local2globalDofs[index];\n}\n\ntemplate <typename BasisFunctionType>\nvoid\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::global2localDofs(\n    const std::vector<GlobalDofIndex> &globalDofs,\n    std::vector<std::vector<LocalDof>> &localDofs) const {\n  localDofs.resize(globalDofs.size());\n  for (size_t i = 0; i < globalDofs.size(); ++i)\n    localDofs[i] = m_global2localDofs[globalDofs[i]];\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::\n    flatLocal2localDofs(const std::vector<FlatLocalDofIndex> &flatLocalDofs,\n                        std::vector<LocalDof> &localDofs) const {\n  localDofs.resize(flatLocalDofs.size());\n  for (size_t i = 0; i < flatLocalDofs.size(); ++i)\n    localDofs[i] = m_flatLocal2localDofs[flatLocalDofs[i]];\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::\n    getGlobalDofPositions(std::vector<Point3D<CoordinateType>> &positions)\n    const {\n  positions.resize(m_globalDofBoundingBoxes.size());\n  for (size_t i = 0; i < m_globalDofBoundingBoxes.size(); ++i)\n    acc(positions, i) = acc(m_globalDofBoundingBoxes, i).reference;\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::\n    getFlatLocalDofPositions(std::vector<Point3D<CoordinateType>> &positions)\n    const {\n  throw std::runtime_error(\"PiecewisePolynomialContinuousScalarSpace::\"\n                           \"getFlatLocalDofPositions(): not implemented yet\");\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::\n    getGlobalDofBoundingBoxes(std::vector<BoundingBox<CoordinateType>> &bboxes)\n    const {\n  bboxes = m_globalDofBoundingBoxes;\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::\n    getFlatLocalDofBoundingBoxes(\n        std::vector<BoundingBox<CoordinateType>> &bboxes) const {\n  throw std::runtime_error(\n      \"PiecewisePolynomialContinuousScalarSpace::\"\n      \"getFlatLocalDofBoundingBoxes(): not implemented yet\");\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::\n    getGlobalDofNormals(std::vector<Point3D<CoordinateType>> &normals) const {\n  SpaceHelper<BasisFunctionType>::getGlobalDofNormals_defaultImplementation(\n      *m_view, m_global2localDofs, normals);\n}\n\ntemplate <typename BasisFunctionType>\nvoid PiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::\n    getFlatLocalDofNormals(std::vector<Point3D<CoordinateType>> &normals)\n    const {\n  throw std::runtime_error(\"PiecewisePolynomialContinuousScalarSpace::\"\n                           \"getFlatLocalDofNormals(): not implemented yet\");\n}\n\ntemplate <typename BasisFunctionType>\nvoid\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::dumpClusterIds(\n    const char *fileName,\n    const std::vector<unsigned int> &clusterIdsOfDofs) const {\n  dumpClusterIdsEx(fileName, clusterIdsOfDofs, GLOBAL_DOFS);\n}\n\ntemplate <typename BasisFunctionType>\nvoid\nPiecewisePolynomialContinuousScalarSpace<BasisFunctionType>::dumpClusterIdsEx(\n    const char *fileName, const std::vector<unsigned int> &clusterIdsOfDofs,\n    DofType dofType) const {\n  throw std::runtime_error(\"PiecewisePolynomialContinuousScalarSpace::\"\n                           \"dumpClusterIdsEx(): not implemented yet\");\n}\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS(\n    PiecewisePolynomialContinuousScalarSpace);\n\n} // namespace Bempp\n", "meta": {"hexsha": "e338ccf4074745eb5754ba71a440b7a8f068d053", "size": 28317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/space/piecewise_polynomial_continuous_scalar_space.cpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/space/piecewise_polynomial_continuous_scalar_space.cpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/space/piecewise_polynomial_continuous_scalar_space.cpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1659574468, "max_line_length": 80, "alphanum_fraction": 0.6738708196, "num_tokens": 7240, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.4148988457967689, "lm_q1q2_score": 0.22362351616714532}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#pragma once\n\n#include <algorithm>\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <functional>\n#include <tuple>\n#include <type_traits>\n#include <utility>  // IWYU pragma: keep // for std::forward\n\n#include \"DataStructures/DataBox/DataBoxTag.hpp\"\n#include \"DataStructures/DataBox/PrefixHelpers.hpp\"\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/Matrix.hpp\"\n#include \"DataStructures/Variables.hpp\"\n#include \"Domain/Direction.hpp\"\n#include \"Domain/ElementId.hpp\"\n#include \"Domain/Mesh.hpp\"\n#include \"ErrorHandling/Assert.hpp\"\n#include \"NumericalAlgorithms/DiscontinuousGalerkin/LiftFlux.hpp\"\n#include \"NumericalAlgorithms/LinearOperators/ApplyMatrices.hpp\"\n#include \"NumericalAlgorithms/Spectral/Projection.hpp\"\n#include \"Utilities/Algorithm.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/MakeArray.hpp\"\n#include \"Utilities/TMPL.hpp\"\n/// \\cond\ntemplate <size_t VolumeDim>\nclass ElementId;\ntemplate <size_t VolumeDim>\nclass OrientationMap;\n// IWYU pragma: no_forward_declare Variables\n/// \\endcond\n\nnamespace dg {\n\ntemplate <size_t VolumeDim>\nusing MortarId = std::pair<::Direction<VolumeDim>, ElementId<VolumeDim>>;\ntemplate <size_t MortarDim>\nusing MortarSize = std::array<Spectral::MortarSize, MortarDim>;\ntemplate <size_t VolumeDim, typename ValueType>\nusing MortarMap = std::unordered_map<MortarId<VolumeDim>, ValueType,\n                                     boost::hash<MortarId<VolumeDim>>>;\n\n/// \\ingroup DiscontinuousGalerkinGroup\n/// Find a mesh for a mortar capable of representing data from either\n/// of two faces.\ntemplate <size_t Dim>\nMesh<Dim> mortar_mesh(const Mesh<Dim>& face_mesh1,\n                      const Mesh<Dim>& face_mesh2) noexcept;\n\n/// \\ingroup DiscontinuousGalerkinGroup\n/// Determine the size of the mortar (i.e., the part of the face it\n/// covers) for communicating with a neighbor.  This is the size\n/// relative to the size of \\p self, and will not generally agree with\n/// that determined by \\p neighbor.\ntemplate <size_t Dim>\nMortarSize<Dim - 1> mortar_size(\n    const ElementId<Dim>& self, const ElementId<Dim>& neighbor,\n    size_t dimension, const OrientationMap<Dim>& orientation) noexcept;\n\n/// \\ingroup DiscontinuousGalerkinGroup\n/// Determine whether data on an element face needs to be projected to a mortar.\n/// If no projection is necessary the data may be used on the mortar as-is.\ntemplate <size_t Dim>\nbool needs_projection(const Mesh<Dim>& face_mesh, const Mesh<Dim>& mortar_mesh,\n                      const MortarSize<Dim>& mortar_size) noexcept {\n  return mortar_mesh != face_mesh or\n      alg::any_of(mortar_size, [](const Spectral::MortarSize& size) noexcept {\n        return size != Spectral::MortarSize::Full;\n      });\n}\n\n/// \\ingroup DiscontinuousGalerkinGroup\n/// Project variables from a face to a mortar.\ntemplate <typename Tags, size_t Dim>\nVariables<Tags> project_to_mortar(const Variables<Tags>& vars,\n                                  const Mesh<Dim>& face_mesh,\n                                  const Mesh<Dim>& mortar_mesh,\n                                  const MortarSize<Dim>& mortar_size) noexcept {\n  const Matrix identity{};\n  auto projection_matrices = make_array<Dim>(std::cref(identity));\n\n  const auto face_slice_meshes = face_mesh.slices();\n  const auto mortar_slice_meshes = mortar_mesh.slices();\n  for (size_t i = 0; i < Dim; ++i) {\n    const auto& face_slice_mesh = gsl::at(face_slice_meshes, i);\n    const auto& mortar_slice_mesh = gsl::at(mortar_slice_meshes, i);\n    const auto& slice_size = gsl::at(mortar_size, i);\n    if (slice_size != Spectral::MortarSize::Full or\n        face_slice_mesh != mortar_slice_mesh) {\n      gsl::at(projection_matrices, i) = projection_matrix_element_to_mortar(\n          slice_size, mortar_slice_mesh, face_slice_mesh);\n    }\n  }\n  return apply_matrices(projection_matrices, vars, face_mesh.extents());\n}\n\n/// \\ingroup DiscontinuousGalerkinGroup\n/// Project variables from a mortar to a face.\ntemplate <typename Tags, size_t Dim>\nVariables<Tags> project_from_mortar(\n    const Variables<Tags>& vars, const Mesh<Dim>& face_mesh,\n    const Mesh<Dim>& mortar_mesh, const MortarSize<Dim>& mortar_size) noexcept {\n  ASSERT(face_mesh != mortar_mesh or\n             alg::any_of(mortar_size,\n                         [](const Spectral::MortarSize& size) noexcept {\n                           return size != Spectral::MortarSize::Full;\n                         }),\n         \"project_from_mortar should not be called if the interface mesh and \"\n         \"mortar mesh are identical. Please elide the copy instead.\");\n\n  const Matrix identity{};\n  auto projection_matrices = make_array<Dim>(std::cref(identity));\n\n  const auto face_slice_meshes = face_mesh.slices();\n  const auto mortar_slice_meshes = mortar_mesh.slices();\n  for (size_t i = 0; i < Dim; ++i) {\n    const auto& face_slice_mesh = gsl::at(face_slice_meshes, i);\n    const auto& mortar_slice_mesh = gsl::at(mortar_slice_meshes, i);\n    const auto& slice_size = gsl::at(mortar_size, i);\n    if (slice_size != Spectral::MortarSize::Full or\n        face_slice_mesh != mortar_slice_mesh) {\n      gsl::at(projection_matrices, i) = projection_matrix_mortar_to_element(\n          slice_size, face_slice_mesh, mortar_slice_mesh);\n    }\n  }\n  return apply_matrices(projection_matrices, vars, mortar_mesh.extents());\n}\n\nnamespace MortarHelpers_detail {\ntemplate <typename NormalDotNumericalFluxComputer,\n          typename... NumericalFluxTags, typename... SelfTags,\n          typename... PackagedTags>\nvoid apply_normal_dot_numerical_flux(\n    const gsl::not_null<Variables<tmpl::list<NumericalFluxTags...>>*>\n        numerical_fluxes,\n    const NormalDotNumericalFluxComputer& normal_dot_numerical_flux_computer,\n    const Variables<tmpl::list<SelfTags...>>& self_packaged_data,\n    const Variables<tmpl::list<PackagedTags...>>&\n        neighbor_packaged_data) noexcept {\n  normal_dot_numerical_flux_computer(\n      make_not_null(&get<NumericalFluxTags>(*numerical_fluxes))...,\n      get<PackagedTags>(self_packaged_data)...,\n      get<PackagedTags>(neighbor_packaged_data)...);\n}\n}  // namespace MortarHelpers_detail\n\n/// \\ingroup DiscontinuousGalerkinGroup\n/// Compute the lifted data resulting from computing the numerical flux.\n///\n/// \\details\n/// This applies the numerical flux, projects the result to the face\n/// mesh if necessary, and then lifts it to the volume (still\n/// presented only on the face mesh as all other points are zero).\n///\n/// Projection must happen after the numerical flux calculation so\n/// that the elements on either side of the mortar calculate the same\n/// result.  Projection must happen before flux lifting because we\n/// want the factor of the magnitude of the unit normal added during\n/// the lift to cancel the Jacobian factor in integrals to preserve\n/// conservation; this only happens if the two operations are done on\n/// the same grid.\ntemplate <typename FluxCommTypes, typename NormalDotNumericalFluxComputer,\n          size_t Dim, typename LocalData>\nauto compute_boundary_flux_contribution(\n    const NormalDotNumericalFluxComputer& normal_dot_numerical_flux_computer,\n    LocalData&& local_data,\n    const typename FluxCommTypes::PackagedData& remote_data,\n    const Mesh<Dim>& face_mesh, const Mesh<Dim>& mortar_mesh,\n    const size_t extent_perpendicular_to_boundary,\n    const MortarSize<Dim>& mortar_size) noexcept\n    -> db::const_item_type<\n        db::remove_tag_prefix<typename FluxCommTypes::normal_dot_fluxes_tag>> {\n  static_assert(std::is_same_v<std::decay_t<LocalData>,\n                               typename FluxCommTypes::LocalData>,\n                \"Second argument must be a FluxCommTypes::LocalData\");\n  using variables_tag =\n      db::remove_tag_prefix<typename FluxCommTypes::normal_dot_fluxes_tag>;\n  db::const_item_type<db::add_tag_prefix<Tags::NormalDotNumericalFlux,\n                                         variables_tag>>\n      normal_dot_numerical_fluxes(mortar_mesh.number_of_grid_points(), 0.0);\n  MortarHelpers_detail::apply_normal_dot_numerical_flux(\n      make_not_null(&normal_dot_numerical_fluxes),\n      normal_dot_numerical_flux_computer, local_data.mortar_data, remote_data);\n\n  tmpl::for_each<db::get_variables_tags_list<variables_tag>>(\n      [&normal_dot_numerical_fluxes, &local_data](const auto tag) noexcept {\n        using Tag = tmpl::type_from<decltype(tag)>;\n        auto& numerical_flux =\n            get<Tags::NormalDotNumericalFlux<Tag>>(normal_dot_numerical_fluxes);\n        const auto& local_flux =\n            get<Tags::NormalDotFlux<Tag>>(local_data.mortar_data);\n        for (size_t i = 0; i < numerical_flux.size(); ++i) {\n          numerical_flux[i] -= local_flux[i];\n        }\n      });\n\n  const bool refining =\n      face_mesh != mortar_mesh or\n      std::any_of(mortar_size.begin(), mortar_size.end(),\n                  [](const Spectral::MortarSize s) noexcept {\n                    return s != Spectral::MortarSize::Full;\n                  });\n\n  return dg::lift_flux(\n      refining ? project_from_mortar(normal_dot_numerical_fluxes, face_mesh,\n                                     mortar_mesh, mortar_size)\n               : std::move(normal_dot_numerical_fluxes),\n      extent_perpendicular_to_boundary,\n      std::forward<LocalData>(local_data).magnitude_of_face_normal);\n}\n}  // namespace dg\n", "meta": {"hexsha": "0f6ba63764c658e86dd7e20a6c8b437fce8d069c", "size": 9407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/NumericalAlgorithms/DiscontinuousGalerkin/MortarHelpers.hpp", "max_stars_repo_name": "desperadoshi/spectre", "max_stars_repo_head_hexsha": "b61c12dce108a98a875a1e9476e5630bea634119", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NumericalAlgorithms/DiscontinuousGalerkin/MortarHelpers.hpp", "max_issues_repo_name": "desperadoshi/spectre", "max_issues_repo_head_hexsha": "b61c12dce108a98a875a1e9476e5630bea634119", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NumericalAlgorithms/DiscontinuousGalerkin/MortarHelpers.hpp", "max_forks_repo_name": "desperadoshi/spectre", "max_forks_repo_head_hexsha": "b61c12dce108a98a875a1e9476e5630bea634119", "max_forks_repo_licenses": ["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.1513761468, "max_line_length": 80, "alphanum_fraction": 0.7110662273, "num_tokens": 2217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2236235100222525}}
{"text": "/************************************************************************\n *\n *\n *  Copyright 2015  Arun Das (University of Waterloo)\n *                      [adas@uwaterloo.ca]\n *                  James Servos (University of Waterloo)\n *                      [jdservos@uwaterloo.ca]\n *\n *\n *************************************************************************/\n#include <Eigen/Eigenvalues>\n#include <wave/matching/groundSegmentation.hpp>\n#include <wave/matching/PointcloudXYZGD.hpp>\n\nnamespace wave {\n\nbool compareSignalPoints(const signalPoint &a, const signalPoint &b) {\n    return a.height < b.height;\n}\n\ngroundSegmentation::groundSegmentation(GroundSegmentationParams config) {\n    this->params = config;\n    this->pBG = new polarBinGrid;\n    initializePolarBinGrid();\n}\n\nvoid groundSegmentation::initializePolarBinGrid(void) {\n    this->pBG->aCell.resize(this->params.num_bins_a);\n    for (int i = 0; i < this->params.num_bins_a; i++) {\n        this->pBG->aCell[i].sigPoints.clear();\n        this->pBG->aCell[i].lCell.resize(this->params.num_bins_l);\n        this->pBG->aCell[i].sigPoints.resize(this->params.num_bins_l);\n        this->pBG->aCell[i].rangeHeightSignal.resize(this->params.num_bins_l);\n        std::vector<signalPoint>().swap(pBG->aCell[i].sigPoints);\n        for (int j = 0; j < this->params.num_bins_l; j++) {\n            pBG->aCell[i].lCell[j].binPoints.clear();\n            pBG->aCell[i].lCell[j].obsPoints.clear();\n            pBG->aCell[i].lCell[j].drvPoints.clear();\n            pBG->aCell[i].lCell[j].groundPoints.clear();\n            pBG->aCell[i].lCell[j].prototypePoint = PointXYZGD();\n            pBG->aCell[i].lCell[j].prototypePoint.x = NAN;\n            pBG->aCell[i].lCell[j].prototypePoint.y = NAN;\n            pBG->aCell[i].lCell[j].prototypePoint.z = NAN;\n            pBG->aCell[i].rangeHeightSignal[j].x = NAN;\n            pBG->aCell[i].rangeHeightSignal[j].y = NAN;\n            pBG->aCell[i].lCell[j].cAssigned = -1;\n\n            // force memory deletion of std::vectors\n            std::vector<PointXYZGD>().swap(pBG->aCell[i].lCell[j].binPoints);\n            std::vector<PointXYZGD>().swap(pBG->aCell[i].lCell[j].obsPoints);\n            std::vector<PointXYZGD>().swap(pBG->aCell[i].lCell[j].drvPoints);\n            std::vector<PointXYZGD>().swap(pBG->aCell[i].lCell[j].groundPoints);\n        }\n    }\n}\n\nvoid groundSegmentation::setupGroundSegmentation(\n  pcl::PointCloud<pcl::PointXYZ>::Ptr inputCloud,\n  pcl::PointCloud<PointXYZGD>::Ptr groundCloud,\n  pcl::PointCloud<PointXYZGD>::Ptr obsCloud,\n  pcl::PointCloud<PointXYZGD>::Ptr drvCloud) {\n    groundCloud->clear();\n    obsCloud->clear();\n\n    refCloud = inputCloud;  // set the cloud datastructure;\n    oCloud = obsCloud;      // set obs cloud\n    gCloud = groundCloud;   // set ground cloud\n    dCloud = drvCloud;\n\n    oCloud->clear();\n    gCloud->clear();\n    dCloud->clear();\n\n    genPolarBinGrid(refCloud);\n}\n\nvoid groundSegmentation::genPolarBinGrid(\n  pcl::PointCloud<pcl::PointXYZ>::Ptr inputCloud) {\n    initializePolarBinGrid();\n\n    size_t nPts = inputCloud->size();\n    double bsize_rad = (double) ((360.0) / this->params.num_bins_a);\n    double bsize_lin = (double) this->params.rmax / this->params.num_bins_l;\n    for (size_t i = 0; i < nPts; i++) {\n        PointXYZGD curPt;\n        float px = curPt.x = inputCloud->points[i].x;\n        float py = curPt.y = inputCloud->points[i].y;\n        float pz = curPt.z = inputCloud->points[i].z;\n\n        if (sqrt(px * px + py * py + pz * pz) < this->params.rmax) {\n            double ph = (atan2(py, px)) * (180 / M_PI);  // in degrees\n            if (ph < 0)\n                ph = 360.0 + ph;\n\n            // bin into sector\n\n            unsigned int bind_rad =\n              static_cast<unsigned int>(ph / bsize_rad);  // got the radial bin\n\n            if (bind_rad == this->params.num_bins_a) {\n                bind_rad = 0;\n            }\n\n            // get the linear bin\n            float xyDist = sqrt(px * px + py * py);\n\n            unsigned int bind_lin = static_cast<unsigned int>(\n              xyDist / bsize_lin);  // got the radial bin\n\n            pBG->aCell[bind_rad].lCell[bind_lin].binPoints.push_back(curPt);\n            // add the point to the bin\n            // check the protoype point\n\n            if (isnanf(pBG->aCell[bind_rad].lCell[bind_lin].prototypePoint.z) ||\n                pz < pBG->aCell[bind_rad]\n                       .lCell[bind_lin]\n                       .prototypePoint.z)  // smallest by z\n            {\n                pBG->aCell[bind_rad].lCell[bind_lin].prototypePoint = curPt;\n                pBG->aCell[bind_rad].rangeHeightSignal[bind_lin].x = xyDist;\n                pBG->aCell[bind_rad].rangeHeightSignal[bind_lin].y = pz;\n            }\n        }\n    }\n}\n\n\nMatX groundSegmentation::genGPModel(std::vector<signalPoint> &ps1,\n                                    std::vector<signalPoint> &ps2,\n                                    float sig_f,\n                                    float p_l) {\n    size_t nP1 = ps1.size();\n    size_t nP2 = ps2.size();\n\n    MatX CMAT;\n    CMAT.resize(nP1, nP2);\n    float coeff = (-1 / (2 * p_l * p_l));\n\n    for (size_t i = 0; i < nP1; i++) {\n        for (size_t j = 0; j < nP2; j++) {\n            double diff = (ps1[i].range - ps2[j].range);\n            CMAT(i, j) = sig_f * exp(coeff * (diff * diff));\n        }\n    }\n    return CMAT;\n}\n\nvoid groundSegmentation::segmentGround() {\n    for (int i = 0; i < this->params.num_bins_a; i++) {\n        sectorINSAC(i);\n    }\n}\n\nvoid groundSegmentation::sectorINSAC(int sectorIndex) {\n    if (sectorIndex >= this->params.num_bins_a) {\n        return;\n    }\n    int numFilled = 0;\n\n    // pull out the valid points from the sector\n    std::vector<signalPoint> &sigPtr = pBG->aCell[sectorIndex].sigPoints;\n    sigPtr.clear();\n    for (int i = 0; i < this->params.num_bins_l; i++) {\n        if (!std::isnan(pBG->aCell[sectorIndex].rangeHeightSignal[i].x) &&\n            pBG->aCell[sectorIndex].lCell[i].binPoints.size() > 5) {\n            // bin has a valid point, and enough points to make a good\n            // guess for a protopoint\n            signalPoint newPoint;\n            newPoint.range = pBG->aCell[sectorIndex].rangeHeightSignal[i].x;\n            newPoint.height = pBG->aCell[sectorIndex].rangeHeightSignal[i].y;\n            newPoint.idx = i;\n            sigPtr.push_back(newPoint);\n            numFilled++;\n        }\n    }\n    // get the seed points.  Select the 3 lowest points.  Sort based on height\n    // values\n    sort(sigPtr.begin(), sigPtr.end(), compareSignalPoints);\n\n    // now that the z points are sorted by height, take the\n    // this->params.num_seed_points worth\n    // as the seed\n    size_t npt =\n      sigPtr.size() < static_cast<size_t>(this->params.num_seed_points)\n        ? sigPtr.size()\n        : static_cast<size_t>(this->params.num_seed_points);\n    std::vector<signalPoint> currentModel;\n    int ptCtr = 0;\n    int currIdx = 0;\n    bool keepGoing = true;\n    bool sufficientModel = true;\n\n    while (true) {\n        if (static_cast<size_t>(currIdx) >= sigPtr.size())  // overflow\n        {\n            break;\n        }\n\n        if (sigPtr[currIdx].range < this->params.max_seed_range &&\n            fabs(sigPtr[currIdx].height) < this->params.max_seed_height) {\n            // close enough to\n            // robot and height\n            // makese sense in\n            // robot locality\n\n            sigPtr[currIdx].isGround = true;\n            currentModel.push_back(sigPtr[currIdx]);\n            sigPtr.erase(sigPtr.begin() + currIdx);\n            ptCtr++;\n\n        } else {\n            currIdx++;\n        }\n\n        if (static_cast<size_t>(ptCtr) >= npt)  // done\n        {\n            break;\n        }\n    }\n\n    // check size\n    if (currentModel.size() < 2)  // not enough for model, all obs pts\n    {\n        keepGoing = false;\n        sufficientModel = false;\n    }\n\n    // got the seedpoints, start theINSAC process\n    // cov matrices\n    MatX C_XsX;\n    MatX C_XX;\n    MatX C_XsXs;\n    MatX C_XXs;\n\n    if (sigPtr.size() == 0)\n        // no points to insac, put the seed points in as ground\n        keepGoing = false;\n\n    MatX temp;\n    MatX f_s;\n    MatX Vf_s;\n    while (keepGoing) {\n        // generate the covariance matrices\n\n        C_XsX =\n          genGPModel(sigPtr, currentModel, this->params.p_sf, this->params.p_l);\n        C_XX = genGPModel(\n          currentModel, currentModel, this->params.p_sf, this->params.p_l);\n        C_XsXs =\n          genGPModel(sigPtr, sigPtr, this->params.p_sf, this->params.p_l);\n        C_XXs = C_XsX.transpose();\n\n        // temporary calc\n        MatX tCalc1 =\n          C_XX + (this->params.p_sn * MatX::Identity(C_XX.rows(), C_XX.cols()));\n        MatX tCalc2 = C_XsX * tCalc1.inverse();\n\n        // test the points against the current model\n\n        MatX modelZ(currentModel.size(), 1);\n        for (unsigned int i = 0; i < currentModel.size(); i++) {\n            modelZ(i, 0) = currentModel[i].height;\n        }\n\n        f_s = tCalc2 * modelZ;\n        Vf_s = C_XsXs - tCalc2 * C_XXs;\n\n        if (Vf_s.rows() == 0) {\n            keepGoing = false;\n            LOG_INFO(\"WARNING BREAKING LOOP: VF_s does not exist\");\n            continue;\n        }\n\n        bool searchCandidatePoints = true;\n        unsigned int k = 0;\n        // test for inliers using INSAC algorithm\n        int startSize = currentModel.size();  // beginning size of the model set\n        while (searchCandidatePoints) {\n            double vf = Vf_s(k, k);\n            double met =\n              (sigPtr[k].height - f_s(k)) / (sqrt(this->params.p_sn + vf * vf));\n\n            if (vf < this->params.p_tmodel &&\n                abs(met) < this->params.p_tdata) {  // we have an inlier!\n                // add to model set\n                currentModel.push_back(sigPtr[k]);\n                // remove from sample set\n                sigPtr.erase(sigPtr.begin() + k);\n\n                // delete row from f_s\n                temp = f_s;\n                f_s.resize(f_s.rows() - 1, f_s.cols());\n                f_s.topRows(k) = temp.topRows(k);\n                f_s.bottomRows(temp.rows() - k - 1) =\n                  temp.bottomRows(temp.rows() - k - 1);\n\n                // delete row from Vf_s\n                temp = Vf_s;\n                Vf_s.resize(Vf_s.rows() - 1, Vf_s.cols());\n                Vf_s.topRows(k) = temp.topRows(k);\n                Vf_s.bottomRows(temp.rows() - k - 1) =\n                  temp.bottomRows(temp.rows() - k - 1);\n\n                // delete col from Vf_s\n                temp = Vf_s;\n                Vf_s.resize(Vf_s.rows(), Vf_s.cols() - 1);\n                Vf_s.leftCols(k) = temp.leftCols(k);\n                Vf_s.rightCols(temp.cols() - k - 1) =\n                  temp.rightCols(temp.cols() - k - 1);\n\n            } else {\n                k++;\n            }\n\n            if (sigPtr.size() == k) {\n                searchCandidatePoints = false;\n            }\n        }\n\n        int endSize = currentModel.size();  // end size of the model set\n        if (startSize == endSize || sigPtr.size() == 0) {\n            keepGoing = false;\n        }\n    }  // end INSAC\n\n    // fill in the ground and obs pointclouds\n\n    double numObs = 0;\n    Vec3 obsSum(0, 0, 0);\n\n    for (int i = 0; i < (int) currentModel.size(); i++) {\n        int currIdx = currentModel[i].idx;\n        linCell *curCell = &pBG->aCell[sectorIndex].lCell[currIdx];\n\n        // go through all the points in this cell and assign to ground/not\n        // ground\n        for (unsigned int j = 0; j < curCell->binPoints.size(); j++) {\n            float h = abs(currentModel[i].height - curCell->binPoints[j].z);\n            if (h < this->params.p_tg)  // z heights are close\n            {\n                gCloud->push_back(\n                  curCell->binPoints[j]);  // add the point to ground\n                curCell->groundPoints.push_back(curCell->binPoints[j]);\n            } else {\n                // check drivability\n                if (h > this->params.robot_height) {\n                    // drivable\n                    curCell->binPoints[j].drivable = 1;\n                } else {\n                    curCell->binPoints[j].drivable = 0;\n                    dCloud->push_back(curCell->binPoints[j]);  // add to obs\n                    curCell->drvPoints.push_back(curCell->binPoints[j]);\n                }\n                oCloud->push_back(curCell->binPoints[j]);  // add to obs\n                curCell->obsPoints.push_back(curCell->binPoints[j]);\n                obsSum += Vec3(curCell->binPoints[j].x,\n                               curCell->binPoints[j].y,\n                               curCell->binPoints[j].z);\n                numObs++;\n            }\n        }\n        // mean of obs points\n        curCell->obsMean = obsSum / numObs;\n    }\n\n    // FIXME: WHY IS F_S < SIGPTR SOMETIMES?\n    int i;\n    if (sufficientModel) {\n        // add all the obs points from the non ground classified pts\n        for (i = 0; i < (int) sigPtr.size(); i++) {\n            linCell *curCell = &pBG->aCell[sectorIndex].lCell[sigPtr[i].idx];\n\n            for (int j = 0; j < (int) curCell->binPoints.size(); j++) {\n                float h = abs(curCell->binPoints[j].z - f_s(i));\n                // check drivability\n                if (h > this->params.robot_height) {\n                    // drivable\n                    curCell->binPoints[j].drivable = 1;\n                } else {\n                    curCell->binPoints[j].drivable = 0;\n                    dCloud->push_back(curCell->binPoints[j]);  // add to obs\n                    curCell->drvPoints.push_back(curCell->binPoints[j]);\n                }\n                oCloud->push_back(curCell->binPoints[j]);  // add to obs\n                curCell->obsPoints.push_back(curCell->binPoints[j]);\n                obsSum += Vec3(curCell->binPoints[j].x,\n                               curCell->binPoints[j].y,\n                               curCell->binPoints[j].z);\n                numObs++;\n            }\n            // mean of obs points\n            curCell->obsMean = obsSum / numObs;\n        }\n    } else {\n        LOG_INFO(\"WARNING:Insufficnent Model for angular slice\");\n    }\n}\n\n}  // namespace wave\n", "meta": {"hexsha": "4043cd2065b7d69b116c02030d55ea5b77413d13", "size": 14190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wave_matching/src/groundSegmentation.cpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_matching/src/groundSegmentation.cpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_matching/src/groundSegmentation.cpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 35.475, "max_line_length": 80, "alphanum_fraction": 0.5306553911, "num_tokens": 3707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22357418291815262}}
{"text": "#include \"it/Entropy.hpp\"\n#include \"binomial.hpp\"\n#include <algorithm>\n#include <map>\n#include <set>\n\n#if BOOST_PYTHON_EXTENSIONS\n#include <boost/python/extract.hpp>\n#endif\n\n#include \"algorithm/TupleSpace.hpp\"\n#include \"it/EntropyCalculator.hpp\"\n\nusing namespace mist;\nusing namespace mist::algorithm;\n\nTupleSpace::TupleSpace()\n  : tuple_size(0){};\nTupleSpace::~TupleSpace(){};\n\n// default space for N variables in tuples size d\nTupleSpace::TupleSpace(int N, int d)\n  : tuple_size(d)\n{\n  if (N == 0 || d == 0) {\n    throw TupleSpaceException(\"TupleSpace\",\n                              \"Number of variables and dimension cannot be zero.\");\n  }\n  tuple_t vars(N);\n  for (int ii = 0; ii < N; ii++) {\n    vars[ii] = ii;\n  }\n  this->addVariableGroup(\"default\", vars);\n  tuple_t groupTuple(d, 0);\n  this->addVariableGroupTuple(groupTuple);\n};\n\nstd::vector<std::string>\nTupleSpace::names() const\n{\n  return variableNames;\n}\n\nvoid\nTupleSpace::set_names(std::vector<std::string> const& names)\n{\n  variableNames = names;\n}\n\nint\nTupleSpace::tupleSize() const\n{\n  return tuple_size;\n}\n\nvoid\nTupleSpace::addVariableGroupTuple(std::vector<std::string> const& groupNames)\n{\n  TupleSpace::tuple_t groupIndexes;\n  for (auto& name : groupNames) {\n    try {\n      groupIndexes.push_back(variableGroupNames[name]);\n    } catch (std::out_of_range& e) {\n      throw TupleSpaceException(\"addVariableGroupTuple\",\n                                \"group named \" + name + \" does not exist.\");\n    }\n  }\n  addVariableGroupTuple(groupIndexes);\n}\n\nvoid\nTupleSpace::addVariableGroupTuple(TupleSpace::tuple_t const& groupIndexes)\n{\n  // validate tuple size\n  if (!tuple_size) {\n    tuple_size = groupIndexes.size();\n  } else if (tuple_size != groupIndexes.size()) {\n    throw TupleSpaceException(\n      \"addVariableGroupTuple\",\n      \"Could not add group tuple, all tuples must be the same size\");\n  }\n  // validate group indexes\n  for (auto group : groupIndexes) {\n    if (group >= variableGroups.size()) {\n      throw TupleSpaceException(\"addVariableGroupTuple\",\n                                \"variable group index \" +\n                                  std::to_string(group) + \" out of range.\");\n    }\n  }\n  variableGroupTuples.push_back(groupIndexes);\n}\n\nint\nTupleSpace::addVariableGroup(std::string const& name,\n                             TupleSpace::tuple_t const& vars)\n{\n  std::set<int> unique_vars;\n  tuple_t group;\n  for (auto var : vars) {\n    // ignore duplicates within variable group\n    if (unique_vars.find(var) == unique_vars.end()) {\n      unique_vars.insert(var);\n      group.push_back(var);\n      // check for overlap with other variable groups\n      if (seen_vars.find(var) != seen_vars.end()) {\n        throw TupleSpaceException(\n          \"addVariableGroup\",\n          \"WARNING: variable \" + std::to_string(var) +\n            \" listed twice in variable group definitions. This exception can \"\n            \"be caught if overlapping variable groups are desired (unusual).\");\n      }\n      seen_vars.emplace(var);\n    }\n  }\n  std::sort(group.begin(), group.end());\n  variableGroups.push_back(group);\n  variableGroupSizes.push_back(group.size());\n  int index = variableGroups.size() - 1;\n  variableGroupNames.emplace(name, index);\n  return index;\n}\n\nTupleSpace::tuple_t const&\nTupleSpace::getVariableGroup(int index) const\n{\n  try {\n    return variableGroups.at(index);\n  } catch (std::out_of_range& e) {\n    throw TupleSpaceException(\"getVariableGroup\",\n                              \"group index \" + std::to_string(index) +\n                                \" out of range.\");\n  }\n}\n\nTupleSpace::tuple_t const&\nTupleSpace::getVariableGroup(std::string const& name) const\n{\n  try {\n    return variableGroups.at(variableGroupNames.at(name));\n  } catch (std::out_of_range& e) {\n    throw TupleSpaceException(\"getVariableGroup\",\n                              \"group named \" + name + \" does not exist.\");\n  }\n}\n\nstd::vector<std::size_t> const&\nTupleSpace::getVariableGroupSizes() const\n{\n    return variableGroupSizes;\n}\n\nstd::vector<TupleSpace::tuple_t> const&\nTupleSpace::getVariableGroups() const\n{\n  return variableGroups;\n}\n\nstd::vector<TupleSpace::tuple_t> const&\nTupleSpace::getVariableGroupTuples() const\n{\n  return variableGroupTuples;\n}\n\n#if BOOST_PYTHON_EXTENSIONS\nint\nTupleSpace::pyAddVariableGroup(std::string const& name, p::list const& list)\n{\n  int n = p::len(list);\n  // copy list in\n  algorithm::TupleSpace::tuple_t vars(n);\n  for (int ii = 0; ii < n; ii++) {\n    p::extract<int> var(list[ii]);\n    if (var.check()) {\n      vars[ii] = var;\n    } else {\n      throw TupleSpaceException(\"pyAddVariableGroup\",\n                                \"Expected list with elements type int\");\n    }\n  }\n  return addVariableGroup(name, vars);\n}\n\nvoid\nTupleSpace::pyAddVariableGroupTuple(p::list const& list)\n{\n  int n = p::len(list); // Doesn't give the right answer ...\n  algorithm::TupleSpace::tuple_t groups(n);\n  for (int ii = 0; ii < n; ii++) {\n    p::extract<int> gint(list[ii]); //TODO segaults\n    p::extract<std::string> gname(list[ii]);\n    if (gint.check()) {\n      groups[ii] = p::extract<int>(list[ii]);\n    } else if (gname.check()) {\n      std::string name(gname);\n      try {\n        groups[ii] = variableGroupNames.at(name);\n      } catch (std::exception& e) {\n        throw TupleSpaceException(\"pyAddVariableGroupTuple\",\n                                  \"group named \" + name + \" does not exist.\");\n      }\n    } else {\n      throw TupleSpaceException(\"pyAddVariableGroupTuple\",\n                                \"Expected list with elements type int or str\");\n    }\n  }\n  addVariableGroupTuple(groups);\n}\n#endif\n\nstatic std::vector<std::size_t>\ngroupSizes(std::vector<TupleSpace::tuple_t> const& groups)\n{\n  std::vector<std::size_t> group_sizes;\n  for (auto& group : groups) {\n    group_sizes.push_back(group.size());\n  }\n  return group_sizes;\n}\n\nstatic TupleSpace::tuple_t\ngroupAppearances(int d, TupleSpace::tuple_t const& group_tuple, int pos)\n{\n  // count group appearances following the current index\n  TupleSpace::tuple_t app(d, 0);\n  for (int gg = pos; gg < group_tuple.size(); gg++) {\n    app[group_tuple[gg]]++;\n  }\n  return app;\n}\n\nstatic TupleSpace::tuple_t\ngroupAppearances(int d, TupleSpace::tuple_t const& group_tuple)\n{\n  return groupAppearances(d, group_tuple, 0);\n}\n\nTupleSpace::count_t\nTupleSpace::count_tuples_group_tuple(tuple_t const& group_tuple) const\n{\n  count_t total = 1;\n  auto const& N = this->variableGroupSizes;\n  auto d = N.size();\n  auto a = groupAppearances(d, group_tuple);\n  for (int ii = 0; ii < d; ii++) {\n    total *= binomial(N[ii], a[ii]);\n  }\n  return total;\n}\n\nTupleSpace::count_t\nTupleSpace::count_tuples() const\n{\n  count_t total = 0;\n  for (auto const& group_tuple : this->variableGroupTuples) {\n    total += count_tuples_group_tuple(group_tuple);\n  }\n  return total;\n}\n\n// Fast-forward to the group containig the tuple at the target position.\nstatic int\nfind_group(TupleSpace::count_t* count, TupleSpace::count_t target, TupleSpace const& ts)\n{\n  auto const& group_tuples = ts.getVariableGroupTuples();\n  int gg = 0;\n  for (auto const& group_tuple : group_tuples) {\n    TupleSpace::count_t skip = ts.count_tuples_group_tuple(group_tuple);\n    if ((skip + *count) > target) {\n      break;\n    }\n    *count += skip;\n    gg++;\n  }\n  return gg;\n}\n\n// Fast-forward the index at position pos so that the target tuple is found by\n// incrementing indexes in the following positions. E.g. if the target 3-tuple\n// is (1,4,8), then\n//\n//      find_index(..., pos=0, ...) returns 1.\n//      find_index(..., pos=1, ...) returns 4.\n//      find_index(..., pos=2, ...) returns 8.\n//\nstatic int\nfind_index(TupleSpace::tuple_t const& group_tuple,\n           int pos,\n           TupleSpace::count_t* count,\n           TupleSpace::count_t target,\n           std::vector<std::size_t> const& N,\n           TupleSpace::tuple_t& starts)\n{\n  unsigned ii = 0;                // index\n  unsigned gi = group_tuple[pos]; // group corresponding to index\n  auto app = groupAppearances(N.size(), group_tuple, pos + 1);\n\n  for (ii = starts[gi]; ii < N[gi]; ii++) {\n    starts[gi] = ii + 1;\n    // count the number of tuples skipped over by incrementing index\n    // for last index skip = 1 (could be optimized with a special case)\n    TupleSpace::count_t skip = 1;\n    for (unsigned gg = 0; gg < N.size(); gg++) {\n      // binomial combination reduces to linear when appearances == 1\n      TupleSpace::count_t f = 1;\n      for (unsigned kk = 0; kk < app[gg]; kk++) {\n        skip = skip * (N[gg] - starts[gg] - kk);\n        f *= (kk + 1);\n      }\n      skip /= f;\n    }\n    if ((skip + *count) > target) {\n      break;\n    }\n    *count += skip;\n  }\n  if (ii >= N[gi]) {\n    throw TupleSpaceException(\"find_index\", \"Failed to FFW index, out of range\");\n  }\n  return ii;\n}\n\nTupleSpace::tuple_t\nTupleSpace::find_tuple(count_t target) const\n{\n  // The fast-forward algorithm maintains a skipped tuple count so that when\n  // the count equals the target count we have found the target tuple.\n  count_t count = 0;\n\n  auto const& N = this->variableGroupSizes;\n  auto const& group_tuples = this->variableGroupTuples;\n\n  // scan ahead to the group tuple that generates the target tuple\n  unsigned gg = find_group(&count, target, *this);\n  auto tuple_size = group_tuples[gg].size();\n  tuple_t ret(tuple_size + 1);\n  ret[0] = gg;\n\n  // scan to the target tuple\n  tuple_t starts(N.size(), 0);\n  for (unsigned ii = 0; ii < tuple_size; ii++) {\n    ret[ii + 1] = find_index(group_tuples[gg], ii, &count, target, N, starts);\n  }\n\n  return ret;\n}\n\nstatic void\ntraverse_d1(TupleSpace const& ts, TupleSpace::count_t start, TupleSpace::count_t stop, TupleSpaceTraverser& traverser)\n{\n  auto const& groups = ts.getVariableGroups();\n  auto const& group_tuples = ts.getVariableGroupTuples();\n  auto const& N = ts.getVariableGroupSizes();\n  unsigned ngroups = groups.size();\n  unsigned ngtuples = group_tuples.size();\n\n  // tuple generation state\n  bool init = true;\n  bool work = true;\n  auto count = start;\n  TupleSpace::tuple_t starts(ngroups);\n  starts.assign(ngroups,0);\n\n  // fast-forward to starting group and tuple\n  auto ffw = ts.find_tuple(start);\n\n  // sub tuples on the stack\n  TupleSpace::tuple_t t0(1);\n\n  for (unsigned gg = ffw[0]; gg < ngtuples && work; gg++) {\n    unsigned g0 = group_tuples[gg][0];\n\n    // loop through all tuples generated by this group_tuple\n    for (unsigned i0 = (init) ? ffw[1] : starts[g0]; i0 < N[g0] && work; i0++) {\n      starts[g0] = i0 + 1;\n      auto v0 = groups[g0][i0];\n      t0[0] = v0;\n      traverser.process_tuple(count, t0);\n      count++;\n      init = false;\n      work = count < stop;\n    }\n    starts[g0] = 0;\n  }\n}\n\nstatic void\ntraverse_d2(TupleSpace const& ts, TupleSpace::count_t start, TupleSpace::count_t stop, TupleSpaceTraverser& traverser)\n{\n  auto const& groups = ts.getVariableGroups();\n  auto const& group_tuples = ts.getVariableGroupTuples();\n  auto const& N = ts.getVariableGroupSizes();\n  unsigned ngroups = groups.size();\n  unsigned ngtuples = group_tuples.size();\n\n  // tuple generation state\n  bool init = true;\n  bool work = true;\n  auto count = start;\n  TupleSpace::tuple_t starts(ngroups);\n  starts.assign(ngroups,0);\n\n  // fast-forward to starting group and tuple\n  auto ffw = ts.find_tuple(start);\n\n  // sub tuples on the stack\n  TupleSpace::tuple_t t01(2);\n\n  for (unsigned gg = ffw[0]; gg < ngtuples && work; gg++) {\n    unsigned g0 = group_tuples[gg][0];\n    unsigned g1 = group_tuples[gg][1];\n\n    // loop through all tuples generated by this group_tuple\n    for (unsigned i0 = (init) ? ffw[1] : starts[g0]; i0 < N[g0] && work; i0++) {\n      starts[g0] = i0 + 1;\n      auto v0 = groups[g0][i0];\n      t01[0] = v0;\n      for (unsigned i1 = (init) ? ffw[2] : starts[g1]; i1 < N[g1] && work; i1++) {\n        starts[g1] = i1 + 1;\n        auto v1 = groups[g1][i1];\n        t01[1] = v1;\n        traverser.process_tuple(count, t01);\n        count++;\n        init = false;\n        work = count < stop;\n      }\n      starts[g1] = 0;\n    }\n    starts[g0] = 0;\n  }\n}\n\nstatic void\ntraverse_d2_entropy(TupleSpace const& ts, TupleSpace::count_t start, TupleSpace::count_t stop, TupleSpaceTraverser& traverser, it::EntropyCalculator & ecalc)\n{\n  auto const& groups = ts.getVariableGroups();\n  auto const& group_tuples = ts.getVariableGroupTuples();\n  auto const& N = ts.getVariableGroupSizes();\n  unsigned ngroups = groups.size();\n  unsigned ngtuples = group_tuples.size();\n\n  // tuple generation state\n  bool init = true;\n  bool work = true;\n  auto count = start;\n  TupleSpace::tuple_t starts(ngroups);\n  starts.assign(ngroups,0);\n  it::Entropy entropy((unsigned)it::d2::size);\n\n  // fast-forward to starting group and tuple\n  auto ffw = ts.find_tuple(start);\n\n  // sub tuples on the stack\n  TupleSpace::tuple_t t0(1);\n  TupleSpace::tuple_t t1(1);\n  TupleSpace::tuple_t t01(2);\n\n  for (unsigned gg = ffw[0]; gg < ngtuples && work; gg++) {\n    unsigned g0 = group_tuples[gg][0];\n    unsigned g1 = group_tuples[gg][1];\n\n    // loop through all tuples generated by this group_tuple\n    for (unsigned i0 = (init) ? ffw[1] : starts[g0]; i0 < N[g0] && work; i0++) {\n      starts[g0] = i0 + 1;\n      auto v0 = groups[g0][i0];\n      t0[0] = v0;\n      t01[0] = v0;\n      entropy[(unsigned)it::d2::e0] = ecalc.entropy(t0);\n      for (unsigned i1 = (init) ? ffw[2] : starts[g1]; i1 < N[g1] && work; i1++) {\n        starts[g1] = i1 + 1;\n        auto v1 = groups[g1][i1];\n        t1[0] = v1;\n        t01[1] = v1;\n        entropy[(unsigned)it::d2::e1]  = ecalc.entropy(t1);\n        entropy[(unsigned)it::d2::e01] = ecalc.entropy(t01);\n        traverser.process_tuple_entropy(count, t01, entropy);\n        count++;\n        init = false;\n        work = count < stop;\n      }\n      starts[g1] = 0;\n    }\n    starts[g0] = 0;\n  }\n}\n\nstatic void\ntraverse_d3(TupleSpace const& ts, TupleSpace::count_t start, TupleSpace::count_t stop, TupleSpaceTraverser& traverser)\n{\n  auto const& groups = ts.getVariableGroups();\n  auto const& group_tuples = ts.getVariableGroupTuples();\n  auto const& N = ts.getVariableGroupSizes();\n  unsigned ngroups = groups.size();\n  unsigned ngtuples = group_tuples.size();\n\n  // tuple generation state\n  bool init = true;\n  bool work = true;\n  auto count = start;\n  TupleSpace::tuple_t starts(ngroups);\n  starts.assign(ngroups,0);\n\n  // fast-forward to starting group and tuple\n  auto ffw = ts.find_tuple(start);\n\n  // sub tuples on the stack\n  TupleSpace::tuple_t t012(3);\n\n  for (unsigned gg = ffw[0]; gg < ngtuples && work; gg++) {\n    unsigned g0 = group_tuples[gg][0];\n    unsigned g1 = group_tuples[gg][1];\n    unsigned g2 = group_tuples[gg][2];\n\n    // loop through all tuples generated by this group_tuple\n    for (unsigned i0 = (init) ? ffw[1] : starts[g0]; i0 < N[g0] && work; i0++) {\n      starts[g0] = i0 + 1;\n      auto v0 = groups[g0][i0];\n      t012[0] = v0;\n      for (unsigned i1 = (init) ? ffw[2] : starts[g1]; i1 < N[g1] && work; i1++) {\n        starts[g1] = i1 + 1;\n        auto v1 = groups[g1][i1];\n        t012[1] = v1;\n        for (unsigned i2 = (init) ? ffw[3] : starts[g2]; i2 < N[g2] && work; i2++) {\n          starts[g2] = i2 + 1;\n          auto v2 = groups[g2][i2];\n          t012[2] = v2;\n          traverser.process_tuple(count, t012);\n          count++;\n          init = false;\n          work = count < stop;\n        }\n        starts[g2] = 0;\n      }\n      starts[g1] = 0;\n    }\n    starts[g0] = 0;\n  }\n}\n\nstatic void\ntraverse_d3_entropy(TupleSpace const& ts, TupleSpace::count_t start, TupleSpace::count_t stop, TupleSpaceTraverser& traverser, it::EntropyCalculator & ecalc)\n{\n  auto const& groups = ts.getVariableGroups();\n  auto const& group_tuples = ts.getVariableGroupTuples();\n  auto const& N = ts.getVariableGroupSizes();\n  unsigned ngroups = groups.size();\n  unsigned ngtuples = group_tuples.size();\n\n  // tuple generation state\n  bool init = true;\n  bool work = true;\n  auto count = start;\n  TupleSpace::tuple_t starts(ngroups);\n  starts.assign(ngroups,0);\n  it::Entropy entropy((unsigned)it::d3::size);\n\n  // sub tuples on the stack\n  TupleSpace::tuple_t t0(1);\n  TupleSpace::tuple_t t1(1);\n  TupleSpace::tuple_t t2(1);\n  TupleSpace::tuple_t t01(2);\n  TupleSpace::tuple_t t02(2);\n  TupleSpace::tuple_t t12(2);\n  TupleSpace::tuple_t t012(3);\n\n  // fast-forward to starting group and tuple\n  auto ffw = ts.find_tuple(start);\n\n  for (unsigned gg = ffw[0]; gg < ngtuples && work; gg++) {\n    unsigned g0 = group_tuples[gg][0];\n    unsigned g1 = group_tuples[gg][1];\n    unsigned g2 = group_tuples[gg][2];\n\n    // loop through all tuples generated by this group_tuple\n    for (unsigned i0 = (init) ? ffw[1] : starts[g0]; i0 < N[g0] && work; i0++) {\n      starts[g0] = i0 + 1;\n      auto v0 = groups[g0][i0];\n      t0[0] = v0;\n      t02[0] = v0;\n      t01[0] = v0;\n      t012[0] = v0;\n      entropy[(unsigned)it::d3::e0] = ecalc.entropy(t0);\n      for (unsigned i1 = (init) ? ffw[2] : starts[g1]; i1 < N[g1] && work; i1++) {\n        starts[g1] = i1 + 1;\n        auto v1 = groups[g1][i1];\n        t1[0] = v1;\n        t01[1] = v1;\n        t12[0] = v1;\n        t012[1] = v1;\n        entropy[(unsigned)it::d3::e1]  = ecalc.entropy(t1);\n        entropy[(unsigned)it::d3::e01] = ecalc.entropy(t01);\n        for (unsigned i2 = (init) ? ffw[3] : starts[g2]; i2 < N[g2] && work; i2++) {\n          starts[g2] = i2 + 1;\n          auto v2 = groups[g2][i2];\n          t2[0] = v2;\n          t02[1] = v2;\n          t12[1] = v2;\n          t012[2] = v2;\n          entropy[(unsigned)it::d3::e2]   = ecalc.entropy(t2);\n          entropy[(unsigned)it::d3::e02]  = ecalc.entropy(t02);\n          entropy[(unsigned)it::d3::e12]  = ecalc.entropy(t12);\n          entropy[(unsigned)it::d3::e012] = ecalc.entropy(t012);\n          traverser.process_tuple_entropy(count, t012, entropy);\n          count++;\n          init = false;\n          work = count < stop;\n        }\n        starts[g2] = 0;\n      }\n      starts[g1] = 0;\n    }\n    starts[g0] = 0;\n  }\n}\n\nstatic void\ntraverse_d4(TupleSpace const& ts, TupleSpace::count_t start, TupleSpace::count_t stop, TupleSpaceTraverser& traverser)\n{\n  auto const& groups = ts.getVariableGroups();\n  auto const& group_tuples = ts.getVariableGroupTuples();\n  auto const& N = ts.getVariableGroupSizes();\n  unsigned ngroups = groups.size();\n  unsigned ngtuples = group_tuples.size();\n\n  // tuple generation state\n  bool init = true;\n  bool work = true;\n  auto count = start;\n  TupleSpace::tuple_t starts(ngroups);\n  starts.assign(ngroups,0);\n\n  // fast-forward to starting group and tuple\n  auto ffw = ts.find_tuple(start);\n\n  // sub tuples on the stack\n  TupleSpace::tuple_t t0123(4);\n\n  for (unsigned gg = ffw[0]; gg < ngtuples && work; gg++) {\n    unsigned g0 = group_tuples[gg][0];\n    unsigned g1 = group_tuples[gg][1];\n    unsigned g2 = group_tuples[gg][2];\n    unsigned g3 = group_tuples[gg][3];\n\n    // loop through all tuples generated by this group_tuple\n    for (unsigned i0 = (init) ? ffw[1] : starts[g0]; i0 < N[g0] && work; i0++) {\n      starts[g0] = i0 + 1;\n      auto v0 = groups[g0][i0];\n      t0123[0] = v0;\n      for (unsigned i1 = (init) ? ffw[2] : starts[g1]; i1 < N[g1] && work; i1++) {\n        starts[g1] = i1 + 1;\n        auto v1 = groups[g1][i1];\n        t0123[1] = v1;\n        for (unsigned i2 = (init) ? ffw[3] : starts[g2]; i2 < N[g2] && work; i2++) {\n          starts[g2] = i2 + 1;\n          auto v2 = groups[g2][i2];\n          t0123[2] = v2;\n          for (unsigned i3 = (init) ? ffw[4] : starts[g3]; i3 < N[g3] && work; i3++) {\n            starts[g3] = i3 + 1;\n            auto v3 = groups[g3][i3];\n            t0123[3] = v3;\n            traverser.process_tuple(count, t0123);\n            count++;\n            init = false;\n            work = count < stop;\n          }\n          starts[g3] = 0;\n        }\n        starts[g2] = 0;\n      }\n      starts[g1] = 0;\n    }\n    starts[g0] = 0;\n  }\n}\n\nstatic void\ntraverse_d4_entropy(TupleSpace const& ts, TupleSpace::count_t start, TupleSpace::count_t stop, TupleSpaceTraverser& traverser, it::EntropyCalculator & ecalc)\n{\n  auto const& groups = ts.getVariableGroups();\n  auto const& group_tuples = ts.getVariableGroupTuples();\n  auto const& N = ts.getVariableGroupSizes();\n  unsigned ngroups = groups.size();\n  unsigned ngtuples = group_tuples.size();\n\n  // tuple generation state\n  bool init = true;\n  bool work = true;\n  auto count = start;\n  TupleSpace::tuple_t starts(ngroups);\n  starts.assign(ngroups,0);\n  it::Entropy entropy((unsigned)it::d4::size);\n\n  // sub tuples on the stack\n  TupleSpace::tuple_t t0(1);\n  TupleSpace::tuple_t t1(1);\n  TupleSpace::tuple_t t2(1);\n  TupleSpace::tuple_t t3(1);\n  TupleSpace::tuple_t t01(2);\n  TupleSpace::tuple_t t02(2);\n  TupleSpace::tuple_t t03(2);\n  TupleSpace::tuple_t t12(2);\n  TupleSpace::tuple_t t13(2);\n  TupleSpace::tuple_t t23(2);\n  TupleSpace::tuple_t t012(3);\n  TupleSpace::tuple_t t013(3);\n  TupleSpace::tuple_t t023(3);\n  TupleSpace::tuple_t t123(3);\n  TupleSpace::tuple_t t0123(4);\n\n  // fast-forward to starting group and tuple\n  auto ffw = ts.find_tuple(start);\n\n  for (unsigned gg = ffw[0]; gg < ngtuples && work; gg++) {\n    unsigned g0 = group_tuples[gg][0];\n    unsigned g1 = group_tuples[gg][1];\n    unsigned g2 = group_tuples[gg][2];\n    unsigned g3 = group_tuples[gg][3];\n\n    // loop through all tuples generated by this group_tuple\n    for (unsigned i0 = (init) ? ffw[1] : starts[g0]; i0 < N[g0] && work; i0++) {\n      starts[g0] = i0 + 1;\n      auto v0 = groups[g0][i0];\n      t0[0] = v0;\n      t01[0] = v0;\n      t02[0] = v0;\n      t03[0] = v0;\n      t012[0] = v0;\n      t013[0] = v0;\n      t023[0] = v0;\n      t0123[0] = v0;\n      entropy[(unsigned)it::d4::e0] = ecalc.entropy(t0);\n      for (unsigned i1 = (init) ? ffw[2] : starts[g1]; i1 < N[g1] && work; i1++) {\n        starts[g1] = i1 + 1;\n        auto v1 = groups[g1][i1];\n        t1[0] = v1;\n        t01[1] = v1;\n        t12[0] = v1;\n        t13[0] = v1;\n        t012[1] = v1;\n        t013[1] = v1;\n        t123[0] = v1;\n        t0123[1] = v1;\n        entropy[(unsigned)it::d4::e1]  = ecalc.entropy(t1);\n        entropy[(unsigned)it::d4::e01] = ecalc.entropy(t01);\n        for (unsigned i2 = (init) ? ffw[3] : starts[g2]; i2 < N[g2] && work; i2++) {\n          starts[g2] = i2 + 1;\n          auto v2 = groups[g2][i2];\n          t2[0] = v2;\n          t02[1] = v2;\n          t12[1] = v2;\n          t23[0] = v2;\n          t012[2] = v2;\n          t023[1] = v2;\n          t123[1] = v2;\n          t0123[2] = v2;\n          entropy[(unsigned)it::d4::e2]   = ecalc.entropy(t2);\n          entropy[(unsigned)it::d4::e02]  = ecalc.entropy(t02);\n          entropy[(unsigned)it::d4::e12]  = ecalc.entropy(t12);\n          entropy[(unsigned)it::d4::e012] = ecalc.entropy(t012);\n          for (unsigned i3 = (init) ? ffw[4] : starts[g3]; i3 < N[g3] && work; i3++) {\n            starts[g3] = i3 + 1;\n            auto v3 = groups[g3][i3];\n            t3[0] = v3;\n            t03[1] = v3;\n            t13[1] = v3;\n            t23[1] = v3;\n            t013[2] = v3;\n            t023[2] = v3;\n            t123[2] = v3;\n            t0123[3] = v3;\n            entropy[(unsigned)it::d4::e3]    = ecalc.entropy(t3);\n            entropy[(unsigned)it::d4::e03]   = ecalc.entropy(t03);\n            entropy[(unsigned)it::d4::e13]   = ecalc.entropy(t13);\n            entropy[(unsigned)it::d4::e23]   = ecalc.entropy(t23);\n            entropy[(unsigned)it::d4::e013]  = ecalc.entropy(t013);\n            entropy[(unsigned)it::d4::e023]  = ecalc.entropy(t023);\n            entropy[(unsigned)it::d4::e123]  = ecalc.entropy(t123);\n            entropy[(unsigned)it::d4::e0123] = ecalc.entropy(t0123);\n            traverser.process_tuple_entropy(count, t0123, entropy);\n            count++;\n            init = false;\n            work = count < stop;\n          }\n          starts[g3] = 0;\n        }\n        starts[g2] = 0;\n      }\n      starts[g1] = 0;\n    }\n    starts[g0] = 0;\n  }\n}\n\nvoid\nTupleSpace::traverse(TupleSpaceTraverser& traverser) const\n{\n  traverse(0, -1, traverser);\n}\n\nvoid\nTupleSpace::traverse_entropy(it::EntropyCalculator &ecalc, TupleSpaceTraverser& traverser) const\n{\n  traverse_entropy(0, -1, ecalc, traverser);\n}\n\nvoid\nTupleSpace::traverse(count_t start, count_t stop, TupleSpaceTraverser& traverser) const\n{\n  switch(tuple_size) {\n    case 1: traverse_d1(*this, start, stop, traverser); break;\n    case 2: traverse_d2(*this, start, stop, traverser); break;\n    case 3: traverse_d3(*this, start, stop, traverser); break;\n    case 4: traverse_d4(*this, start, stop, traverser); break;\n    default:\n      throw TupleSpaceException(\"traverse\", \"Tuple size greater than 4 unsupported.\");\n  }\n}\n\nvoid\nTupleSpace::traverse_entropy(count_t start, count_t stop, it::EntropyCalculator &ecalc, TupleSpaceTraverser& traverser) const\n{\n  switch(tuple_size) {\n    case 1:\n      throw TupleSpaceException(\"traverse_entropy\", \"Tuple size 1 unsupported.\");\n    case 2: traverse_d2_entropy(*this, start, stop, traverser, ecalc); break;\n    case 3: traverse_d3_entropy(*this, start, stop, traverser, ecalc); break;\n    case 4: traverse_d4_entropy(*this, start, stop, traverser, ecalc); break;\n    default:\n      throw TupleSpaceException(\"traverse\", \"Tuple size greater than 4 unsupported.\");\n  }\n}\n", "meta": {"hexsha": "0c194cba9bf8242540151f76ba498131d4f0b89b", "size": 25179, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mist/algorithm/TupleSpace.cpp", "max_stars_repo_name": "andbanman/mist", "max_stars_repo_head_hexsha": "2546fb41bccea1f89a43dbdbed7ce3a257926b54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mist/algorithm/TupleSpace.cpp", "max_issues_repo_name": "andbanman/mist", "max_issues_repo_head_hexsha": "2546fb41bccea1f89a43dbdbed7ce3a257926b54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-03-30T21:40:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-08T18:54:34.000Z", "max_forks_repo_path": "src/mist/algorithm/TupleSpace.cpp", "max_forks_repo_name": "andbanman/mist", "max_forks_repo_head_hexsha": "2546fb41bccea1f89a43dbdbed7ce3a257926b54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2996389892, "max_line_length": 157, "alphanum_fraction": 0.6097541602, "num_tokens": 7513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22347071917150488}}
{"text": "#include \"GPS_receiver.hh\"\n\n#include \"aux.hh\"\n\n#include \"global_constants.hh\"\n#include \"matrix/utility.hh\"\n#include \"stochastic.hh\"\n\n#include \"cad_utility.hh\"\n\n#include <tuple>\n\n#include <armadillo>\n\n#include \"Earth.hh\"\n#include \"Euler.hh\"\n#include \"GPS_satellites.hh\"\n#include \"Ins.hh\"\n#include \"Newton.hh\"\n\nGPS_Receiver::GPS_Receiver(Newton &ntn, _Euler_ &elr)\n    : newton(&ntn),\n      euler(&elr),\n      MATRIX_INIT(PP, 8, 8),\n      MATRIX_INIT(FF, 8, 8),\n      MATRIX_INIT(PHI, 8, 8),\n      VECTOR_INIT(SXH, 3),\n      VECTOR_INIT(VXH, 3),\n      VECTOR_INIT(CXH, 3) {\n  this->default_data();\n}\n\nGPS_Receiver::GPS_Receiver(const GPS_Receiver &other)\n    : newton(other.newton),\n      euler(other.euler),\n      gps_sats(other.gps_sats),\n      MATRIX_INIT(PP, 8, 8),\n      MATRIX_INIT(FF, 8, 8),\n      MATRIX_INIT(PHI, 8, 8),\n      VECTOR_INIT(SXH, 3),\n      VECTOR_INIT(VXH, 3),\n      VECTOR_INIT(CXH, 3) {\n  this->default_data();\n\n  /* Input File */\n  memcpy(this->slot, other.slot, sizeof(this->slot));\n\n  /* GPS Device parameters */\n  this->del_rearth = other.del_rearth;\n  this->gps_acqtime = other.gps_acqtime;\n  this->gps_step = other.gps_step;\n\n  this->ucfreq_noise = other.ucfreq_noise;\n  this->ucfreq_noise_sigma = other.ucfreq_noise_sigma;\n  this->ucfreq_noise_bcor = other.ucfreq_noise_bcor;\n  this->ucbias_error = other.ucbias_error;\n\n  memcpy(this->PR_BIAS, other.PR_BIAS, sizeof(this->PR_BIAS));\n  memcpy(this->PR_NOISE, other.PR_NOISE, sizeof(this->PR_NOISE));\n  memcpy(this->PR_NOISE_sigma, other.PR_NOISE_sigma,\n         sizeof(this->PR_NOISE_sigma));\n  memcpy(this->PR_NOISE_bcor, other.PR_NOISE_bcor, sizeof(this->PR_NOISE_bcor));\n  memcpy(this->DR_NOISE, other.DR_NOISE, sizeof(this->DR_NOISE));\n  memcpy(this->DR_NOISE_sigma, other.DR_NOISE_sigma,\n         sizeof(this->DR_NOISE_sigma));\n  memcpy(this->DR_NOISE_bcor, other.DR_NOISE_bcor, sizeof(this->DR_NOISE_bcor));\n\n  /* GPS EKF Parameters */\n  this->ppos = other.ppos;\n  this->pvel = other.pvel;\n  this->qpos = other.qpos;\n  this->qvel = other.qvel;\n  this->rpos = other.rpos;\n  this->rvel = other.rvel;\n  this->factr = other.factr;\n\n  /* Internal variables */\n  this->gps_acq = this->gps_acq;\n  this->gps_epoch = other.gps_epoch;\n  this->time_gps = other.time_gps;\n\n  this->FF = other.FF;\n  this->PHI = other.PHI;\n  this->PP = other.PP;\n\n  this->factq = other.factq;\n  this->qclockb = other.qclockb;\n  this->qclockf = other.qclockf;\n\n  this->slotsum = other.slotsum;\n\n  this->SXH = other.SXH;\n  this->VXH = other.VXH;\n  this->CXH = other.CXH;\n\n  /* GPS Outputs */\n  this->gdop = other.gdop;\n  memcpy(this->ssii_quad, other.ssii_quad, sizeof(this->ssii_quad));\n  memcpy(this->vsii_quad, other.vsii_quad, sizeof(this->vsii_quad));\n\n  this->ucfreq_error = other.ucfreq_error;\n  this->ucfreqm = other.ucfreqm;\n\n  this->std_pos = other.std_pos;\n  this->std_vel = other.std_vel;\n  this->std_ucbias = other.std_ucbias;\n\n  this->lat1 = other.lat1;\n  this->lat2 = other.lat2;\n  this->lat3 = other.lat3;\n  this->lat4 = other.lat4;\n  this->lon1 = other.lon1;\n  this->lon2 = other.lon2;\n  this->lon3 = other.lon3;\n  this->lon4 = other.lon4;\n  this->alt1 = other.alt1;\n  this->alt2 = other.alt2;\n  this->alt3 = other.alt3;\n  this->alt4 = other.alt4;\n\n  this->gps_pos_meas = other.gps_pos_meas;\n  this->gps_vel_meas = other.gps_vel_meas;\n  this->state_pos = other.state_pos;\n  this->state_vel = other.state_vel;\n}\n\nGPS_Receiver &GPS_Receiver::operator=(const GPS_Receiver &other) {\n  if (&other == this) return *this;\n\n  this->newton = other.newton;\n  this->euler = other.euler;\n  this->gps_sats = other.gps_sats;\n\n  /* Input File */\n  memcpy(this->slot, other.slot, sizeof(this->slot));\n\n  /* GPS Device parameters */\n  this->del_rearth = other.del_rearth;\n  this->gps_acqtime = other.gps_acqtime;\n  this->gps_step = other.gps_step;\n\n  this->ucfreq_noise = other.ucfreq_noise;\n  this->ucfreq_noise_sigma = other.ucfreq_noise_sigma;\n  this->ucfreq_noise_bcor = other.ucfreq_noise_bcor;\n  this->ucbias_error = other.ucbias_error;\n\n  memcpy(this->PR_BIAS, other.PR_BIAS, sizeof(this->PR_BIAS));\n  memcpy(this->PR_NOISE, other.PR_NOISE, sizeof(this->PR_NOISE));\n  memcpy(this->PR_NOISE_sigma, other.PR_NOISE_sigma,\n         sizeof(this->PR_NOISE_sigma));\n  memcpy(this->PR_NOISE_bcor, other.PR_NOISE_bcor, sizeof(this->PR_NOISE_bcor));\n  memcpy(this->DR_NOISE, other.DR_NOISE, sizeof(this->DR_NOISE));\n  memcpy(this->DR_NOISE_sigma, other.DR_NOISE_sigma,\n         sizeof(this->DR_NOISE_sigma));\n  memcpy(this->DR_NOISE_bcor, other.DR_NOISE_bcor, sizeof(this->DR_NOISE_bcor));\n\n  /* GPS EKF Parameters */\n  this->ppos = other.ppos;\n  this->pvel = other.pvel;\n  this->qpos = other.qpos;\n  this->qvel = other.qvel;\n  this->rpos = other.rpos;\n  this->rvel = other.rvel;\n  this->factr = other.factr;\n\n  /* Internal variables */\n  this->gps_acq = this->gps_acq;\n  this->gps_epoch = other.gps_epoch;\n  this->time_gps = other.time_gps;\n\n  this->FF = other.FF;\n  this->PHI = other.PHI;\n  this->PP = other.PP;\n\n  this->factq = other.factq;\n  this->qclockb = other.qclockb;\n  this->qclockf = other.qclockf;\n\n  this->slotsum = other.slotsum;\n\n  this->SXH = other.SXH;\n  this->VXH = other.VXH;\n  this->CXH = other.CXH;\n\n  /* GPS Outputs */\n  this->gdop = other.gdop;\n  memcpy(this->ssii_quad, other.ssii_quad, sizeof(this->ssii_quad));\n  memcpy(this->vsii_quad, other.vsii_quad, sizeof(this->vsii_quad));\n\n  this->ucfreq_error = other.ucfreq_error;\n  this->ucfreqm = other.ucfreqm;\n\n  this->std_pos = other.std_pos;\n  this->std_vel = other.std_vel;\n  this->std_ucbias = other.std_ucbias;\n\n  this->lat1 = other.lat1;\n  this->lat2 = other.lat2;\n  this->lat3 = other.lat3;\n  this->lat4 = other.lat4;\n  this->lon1 = other.lon1;\n  this->lon2 = other.lon2;\n  this->lon3 = other.lon3;\n  this->lon4 = other.lon4;\n  this->alt1 = other.alt1;\n  this->alt2 = other.alt2;\n  this->alt3 = other.alt3;\n  this->alt4 = other.alt4;\n\n  this->gps_pos_meas = other.gps_pos_meas;\n  this->gps_vel_meas = other.gps_vel_meas;\n  this->state_pos = other.state_pos;\n  this->state_vel = other.state_vel;\n\n  return *this;\n}\n\nvoid GPS_Receiver::default_data() {\n  gps_update = 0;\n\n  // setting inital acquisition flag\n  gps_acq = false;\n}\n\nvoid GPS_Receiver::setup_state_covariance_matrix(double factp, double pclockb,\n                                                 double pclockf) {\n  PP = arma::mat88(arma::fill::zeros);\n  for (int i = 0; i < 3; i++) {\n    PP(i, i) = pow(ppos * (1 + factp), 2);\n    PP(i + 3, i + 3) = pow(pvel * (1 + factp), 2);\n  }\n  PP(6, 6) = pow(pclockb * (1 + factp), 2);\n  PP(7, 7) = pow(pclockf * (1 + factp), 2);\n\n  return;\n}\n\nvoid GPS_Receiver::setup_error_covariance_matrix(double factq, double qclockb,\n                                                 double qclockf) {\n  this->factq = factq;\n  this->qclockb = qclockb;\n  this->qclockf = qclockf;\n\n  return;\n}\n\nvoid GPS_Receiver::setup_fundamental_dynamic_matrix(double uctime_cor) {\n  // fundamental dynamic matrix of filter - constant throughout\n  FF = arma::mat88(arma::fill::zeros);\n  FF(0, 3) = 1;\n  FF(1, 4) = 1;\n  FF(2, 5) = 1;\n  FF(6, 7) = 1;\n  FF(7, 7) = -1 / uctime_cor;\n\n  return;\n}\n\nvoid GPS_Receiver::initialize(GPS_Satellites *sats, double int_step) {\n  gps_sats = sats;\n\n  // state transition matrix - constant throughout\n  PHI = arma::mat88(arma::fill::eye) + FF * int_step +\n        FF * FF * (int_step * int_step / 2);\n\n  // initializing update clock\n  gps_epoch = get_elapsed_time();\n}\n\nvoid GPS_Receiver::update_markov(double int_step) {\n  int i;\n\n  ucfreq_noise = markov(ucfreq_noise_sigma, ucfreq_noise_bcor,\n                        get_elapsed_time(), int_step, ucfreq_noise);\n  for (i = 0; i < 4; i++) {\n    PR_NOISE[i] = markov(PR_NOISE_sigma[i], PR_NOISE_bcor[i],\n                         get_elapsed_time(), int_step, PR_NOISE[i]);\n  }\n  for (i = 0; i < 4; i++) {\n    DR_NOISE[i] = markov(DR_NOISE_sigma[i], DR_NOISE_bcor[i],\n                         get_elapsed_time(), int_step, DR_NOISE[i]);\n  }\n}\n\nvoid GPS_Receiver::get_quadriga() {\n  int i(0);\n  int j(0);\n  int m(0);\n\n  gdop = LARGE;\n  int quad[4] = {0, 0, 0, 0};  // location of quadriga SVs\n                               // in 'ssii_vis[visible_count]\n\n  // conversion to inertial (J2000) coordinates\n  double ssii[24][4];\n  double sin_incl = sin(gps_sats->inclination);\n  double cos_incl = cos(gps_sats->inclination);\n  for (i = 0; i < 24; i++) {\n    ssii[i][0] = gps_sats->radius *\n                 (cos(gps_sats->sv_data[i][0]) * cos(gps_sats->sv_data[i][1]) -\n                  sin(gps_sats->sv_data[i][0]) * sin(gps_sats->sv_data[i][1]) *\n                      cos_incl);\n    ssii[i][1] = gps_sats->radius *\n                 (sin(gps_sats->sv_data[i][0]) * cos(gps_sats->sv_data[i][1]) +\n                  cos(gps_sats->sv_data[i][0]) * sin(gps_sats->sv_data[i][1]) *\n                      cos_incl);\n    ssii[i][2] = gps_sats->radius * sin(gps_sats->sv_data[i][1]) * sin_incl;\n    ssii[i][3] = 0;\n    // last entry is a flag with the code:\n    // =0:not visible; >0:visible (not int but double!), where the\n    // number\n    // is the SV slot# (1,2,3,...,24)\n  }\n\n  // determining visible satellites\n  arma::vec3 SSII;\n  arma::vec3 SBII = newton->get_SBII();\n  int visible_count(0);\n\n  for (i = 0; i < 24; i++) {\n    SSII[0] = ssii[i][0];\n    SSII[1] = ssii[i][1];\n    SSII[2] = ssii[i][2];\n\n    // SV to user angle with vertex at Earth center\n    double delta = angle(SSII, SBII);\n\n    // grazing angle of SV beam with vertex at Earth center\n    double epsilon = acos((Earth::radius + del_rearth) / gps_sats->radius);\n\n    // min radius of user to have clear line-of-site to SV\n    double rmin = (Earth::radius + del_rearth) / cos(delta - epsilon);\n\n    if (delta < epsilon) {\n      // SV is in the visibility cone\n      ssii[i][3] = i + 1;\n      visible_count++;\n    } else {\n      // user is outside the visibility cone but high enough to have\n      // LOS to the SV\n      // (rmin can go negative if delta-epsilon>90deg; this can happen\n      // when the user is opposite (or nearly opposite) of the SV;\n      // this is always a no-visibility case)\n      double dbi = norm(SBII);\n      if (rmin > 0 && rmin < dbi) {\n        ssii[i][3] = i + 1;\n        visible_count++;\n      }\n    }\n  }\n  if (visible_count <\n      4) {  // re-acquiring GPS if not enough SVs visible (less than 4)\n    gps_epoch = get_elapsed_time();\n    gps_acq = false;\n  } else {  // selecting best 4 SVs if 4 or more are visible\n    // repackage visible SVs into 'ssii_vis' single-dimensioned array\n    // inertial displacement vector elements are stored sequentially in\n    // 'ssii_vis[4*visible_count]'\n    // 'ssii_vis' has 3 inertial coordinates and SV slot# of all visible\n    // SVs\n    double *ssii_vis;\n    ssii_vis = new double[4 * visible_count];\n    int k(0);\n    for (i = 0; i < 24; i++) {\n      if (ssii[i][3] > 0) {\n        *(ssii_vis + k) = ssii[i][0];\n        *(ssii_vis + k + 1) = ssii[i][1];\n        *(ssii_vis + k + 2) = ssii[i][2];\n        *(ssii_vis + k + 3) = ssii[i][3];\n        k = k + 4;\n      }\n    }\n    // selecting quadriga (four SVs) with smallest GDOP\n    // i1, i2, i3, i4 are the SVs picked by the binomial combination\n    int nm3 = visible_count - 3;  // nm3=1\n    int nm2 = visible_count - 2;  // nm2=2\n    int nm1 = visible_count - 1;  // nm1=3\n\n    for (int i1 = 0; i1 < nm3; i1++) {\n      for (int i2 = i1 + 1; i2 < nm2; i2++) {\n        for (int i3 = i2 + 1; i3 < nm1; i3++) {\n          for (int i4 = i3 + 1; i4 < visible_count; i4++) {\n            // pullling the quadriga inertial coordinates\n            arma::vec3 SSII1;\n            arma::vec3 SSII2;\n            arma::vec3 SSII3;\n            arma::vec3 SSII4;\n            for (m = 0; m < 3; m++) {\n              SSII1[m] = *(ssii_vis + 4 * i1 + m);\n              SSII2[m] = *(ssii_vis + 4 * i2 + m);\n              SSII3[m] = *(ssii_vis + 4 * i3 + m);\n              SSII4[m] = *(ssii_vis + 4 * i4 + m);\n            }\n            // calculating user wrt the SV displacement unit\n            // vectors\n            arma::vec UNI1 = normalise(SBII - SSII1);\n            arma::vec UNI2 = normalise(SBII - SSII2);\n            arma::vec UNI3 = normalise(SBII - SSII3);\n            arma::vec UNI4 = normalise(SBII - SSII4);\n\n            // building the GPS 'H' matrix\n            arma::mat44 HGPS(arma::fill::ones);\n            HGPS.col(0) = UNI1;\n            HGPS.col(1) = UNI2;\n            HGPS.col(2) = UNI3;\n            HGPS.col(3) = UNI4;\n            // calculating GDOP\n            arma::mat44 COV;\n            COV = arma::inv(HGPS * arma::trans(HGPS));\n            double gdop_local = sqrt(sum(COV.diag()));\n\n            // save slot # of quadriga SVs if GDOP has decreased\n            if (gdop_local < gdop) {\n              gdop = gdop_local;\n              quad[0] = i1;\n              quad[1] = i2;\n              quad[2] = i3;\n              quad[3] = i4;\n            }\n          }\n        }\n      }\n    }  // end of picking quadriga amongst visible SVs\n\n    // extracting \"best\" quadriga from visible SVs\n    // and storing inertial coordinates of the four SVs and their slot#\n    // in ssii_quad[16]\n    for (m = 0; m < 4; m++) {\n      for (int n = 0; n < 4; n++) {\n        *(ssii_quad + 4 * m + n) = *(ssii_vis + 4 * quad[m] + n);\n      }\n    }\n    delete[] ssii_vis;\n\n    // calculating inertial velocity of quadriga SVs\n    // getting slot# of quadriga\n    //\n    int *islot = new int[i];\n    for (i = 0; i < 4; i++) {\n      slot[i] = *(ssii_quad + 4 * i + 3);\n      // casting into an int\n      islot[i] = static_cast<int> slot[i];\n    }\n    // storing inertial velocities of the four SVs in vsii_quad[12]\n    double sin_incl = sin(gps_sats->inclination);\n    double cos_incl = cos(gps_sats->inclination);\n    double vel = gps_sats->radius * gps_sats->angular_velocity;\n    for (m = 0; m < 4; m++) {\n      int ii = islot[m] - 1;  // reminder: slot#=1,2,3...,24\n      *(vsii_quad + 3 * m + 0) =\n          vel *\n          (-sin(gps_sats->sv_data[ii][1]) * cos(gps_sats->sv_data[ii][0]) -\n           cos(gps_sats->sv_data[ii][1]) * sin(gps_sats->sv_data[ii][0]) *\n               cos_incl);\n      *(vsii_quad + 3 * m + 1) =\n          vel *\n          (-sin(gps_sats->sv_data[ii][1]) * sin(gps_sats->sv_data[ii][0]) +\n           cos(gps_sats->sv_data[ii][1]) * cos(gps_sats->sv_data[ii][0]) *\n               cos_incl);\n      *(vsii_quad + 3 * m + 2) =\n          vel * (cos(gps_sats->sv_data[ii][1]) * sin_incl);\n    }\n  }  // end of picking quadriga from 4 or more visible SVs\n}\n\nvoid GPS_Receiver::filter_extrapolation(double int_step) {\n  arma::mat88 QQ(arma::fill::zeros);  // local\n\n  // *** user-clock frequency and bias error growth between updates ***\n  // integrating 'ucfreq_noise' Markov process to\n  // obtain user-clock bias error 'ucbias_error' (trapezoidal\n  // integration)\n  // user-clock bias is updated at filter update epoch\n  ucfreq_error = ucfreq_noise;\n  ucbias_error = ucbias_error + (ucfreq_error + ucfreqm) * (int_step / 2);\n  ucfreqm = ucfreq_error;\n\n  // *** filter extrapolation ***\n  // dynamic error covariance matrix\n  for (int i = 0; i < 3; i++) {\n    QQ(i, i) = pow(qpos * (1 + factq), 2);\n    QQ(i + 3, i + 3) = pow(qvel * (1 + factq), 2);\n  }\n  QQ(6, 6) = pow(qclockb * (1 + factq), 2);\n  QQ(7, 7) = pow(qclockf * (1 + factq), 2);\n\n  // covariance estimate extrapolation\n  PP = PHI * (PP + QQ * (int_step / 2)) * trans(PHI) + QQ * (int_step / 2);\n\n  // diagnostics: st. deviations of the diagonals of the covariance matrix\n  std_pos = sqrt(PP(0, 0));\n  std_vel = sqrt(PP(3, 3));\n  std_ucbias = sqrt(PP(6, 6));\n}\n\nvoid GPS_Receiver::measure() {\n  double dtime_gps;\n  /* Testing GPS timing for update and acquire */\n  if (!gps_acq)\n    // saving delay-time for GPS signal acquisition\n    dtime_gps = gps_acqtime;\n  else\n    // saving delay-time for GPS update\n    dtime_gps = gps_step;\n  // checking when GPS update time has occured in order to initiate update\n  time_gps = get_elapsed_time() - gps_epoch;\n  if (time_gps < dtime_gps) {\n    return;\n  }\n\n  gps_acq = true;\n  gps_update++;\n  // resetting update clock\n  time_gps = 0;\n  gps_epoch = get_elapsed_time();\n\n  /* GPS Update and Measurement */\n  double slotm(0);\n\n  arma::vec8 ZZ(arma::fill::zeros);\n  arma::vec8 XH(arma::fill::zeros);   // local\n  arma::mat88 RR(arma::fill::zeros);  // local\n  arma::mat88 HH(arma::fill::zeros);  // local\n\n  // ***\n  // SV propagation and quadriga selection 'ssii_quad'\n  // (4 SVs with best GDOP)\n  // ***\n  // gps_quadriga(ssii_quad,vsii_quad,gdop,mgps,\n  // sv_init_data,rsi,wsi,incl,almanac_time,del_rearth,time,SBII);\n\n  // Pseudo-range and range-rate measurements\n  for (int i = 0; i < 4; i++) {\n    // unpacking i-th SV inertial position\n    arma::vec3 SSII;\n    for (int j = 0; j < 3; j++) {\n      SSII[j] = *(ssii_quad + 4 * i + j);\n    }\n    // Z150126 - start\n    // diagnostics: getting long, lat, alt of the four quadriga SVs for\n    // plotting in GLOBE\n    double lon(0), lat(0), alt(0);\n    std::tie(lon, lat, alt) = cad::geo84_in(SSII, gps_sats->time);\n    switch (i) {\n      case 0:\n        lon1 = lon * DEG;\n        lat1 = lat * DEG;\n        alt1 = alt;\n        break;\n      case 1:\n        lon2 = lon * DEG;\n        lat2 = lat * DEG;\n        alt2 = alt;\n        break;\n      case 2:\n        lon3 = lon * DEG;\n        lat3 = lat * DEG;\n        alt3 = alt;\n        break;\n      case 3:\n        lon4 = lon * DEG;\n        lat4 = lat * DEG;\n        alt4 = alt;\n        break;\n    }\n\n    arma::vec3 SBII = newton->get_SBII();\n    arma::vec3 VBII = newton->get_VBII();\n    arma::vec3 WBII = euler->get_WBII();\n\n    arma::vec3 SBIIC = grab_SBIIC();\n    arma::vec3 VBIIC = grab_VBIIC();\n    arma::vec3 WBICI = grab_WBICI();\n\n    // calculating true range to SV\n    arma::vec3 SSBI;\n\n    SSBI = SSII - SBII;\n    double dsb = norm(SSBI);\n\n    // measured pseudo-range\n    double dsb_meas = dsb + PR_BIAS[i] + PR_NOISE[i] + ucbias_error;\n\n    // unpacking i-th SV inertial velocity\n    arma::vec3 VSII;\n    for (int j = 0; j < 3; j++) {\n      VSII[j] = *(vsii_quad + 3 * i + j);\n    }\n    // velocity of SV wrt user\n    arma::vec3 VSBI;\n    VSBI = VSII - VBII - skew_sym(WBII) * SSBI;\n\n    // calculating true range-rate to SV\n    arma::vec3 USSBI;\n    USSBI = SSBI * (1 / dsb);\n    double dvsb = dot(VSBI, USSBI);\n\n    // measured delta-range rate\n    double dvsb_meas = dvsb + DR_NOISE[i] + ucfreq_error;\n\n    // INS derived range measurements\n    arma::vec3 SSBIC;\n    SSBIC = SSII - SBIIC;\n    double dsbc = norm(SSBIC);\n\n    // INS derived range-rate measurements\n    // velocity of SV wrt user\n    arma::vec3 VSBIC;\n    VSBIC = VSII - VBIIC - skew_sym(WBICI) * SSBIC;\n    // calculating range-rate to SV\n    arma::vec3 USSBIC;\n    USSBIC = SSBIC * (1 / dsb);\n    double dvsbc = dot(VSBIC, USSBIC);\n\n    // loading measurement residuals into measurement vector\n    // ZZ[0->3] range meas resid of SV's;\n    // ZZ[4->7] range-rate meas resid of SV's\n    ZZ[i] = dsb_meas - dsbc;\n    ZZ[i + 4] = dvsb_meas - dvsbc;\n\n    // observation matrix of filter\n    for (int j = 0; j < 3; j++) {\n      HH(i, j) = USSBI(j, 0);\n      HH(i + 4, j + 3) = USSBI(j, 0) * gps_step;\n    }\n    HH(i, 6) = 1;\n    HH(i + 4, 7) = gps_step;\n\n    // for diagnostics: loading the 4 SV slot # of the quadriga\n    *(slot + i) = *(ssii_quad + 4 * i + 3);\n    // accumulating sum of slots\n    slotm = slotm + slot[i];\n  }\n  // for diagnostics displaying the SV slot# of the quadriga on the\n  // console\n  // but only if they have changed (i.e., sum of slot# has changed)\n\n  if (slotsum != slotm) {\n    slotsum = slotm;\n    std::cout << \" *** GPS Quadriga slot # \" << slot[0] << \"  \" << slot[1]\n              << \"  \" << slot[2] << \"  \" << slot[3] << \" ;  GDOP = \" << gdop\n              << \" m ***\\n\";\n  }\n  // *** filter correction and update (to INS: 'SXH' and 'VXH') ***\n  // filter gain\n  arma::mat88 KK(arma::fill::zeros);\n\n  // measurement noise covariance matrix\n  for (int i = 0; i < 4; i++) {\n    RR(i, i) = pow(rpos * (1 + factr), 2);\n    RR(i + 4, i + 4) = pow(rvel * (1 + factr), 2);\n  }\n  // Kalman gain\n  KK = inv(PP * trans(HH) * (HH * PP * trans(HH) + RR));\n  // state correction\n  XH = KK * ZZ;\n  // covariance correction for next cycle\n  PP = (arma::mat88(arma::fill::eye) - KK * HH) * PP;\n\n  // clock error bias update\n  ucbias_error = ucbias_error - XH(6, 0);\n\n  // diagnostics of 1st SV of quadriga saved to plot file\n  gps_pos_meas = ZZ(0, 0);\n  gps_vel_meas = ZZ(4, 0);\n\n  // decomposing state vector for output\n  for (int m = 0; m < 3; m++) {\n    SXH(m, 0) = XH(m, 0);\n    VXH(m, 0) = XH(m + 3, 0);\n  }\n  CXH(0, 0) = XH(6, 0);\n  CXH(1, 0) = XH(7, 0);\n\n  // diagnostic\n  state_pos = norm(SXH);\n  state_vel = norm(VXH);\n}\n\narma::vec3 GPS_Receiver::get_SXH() { return SXH; }\narma::vec3 GPS_Receiver::get_VXH() { return VXH; }\narma::vec3 GPS_Receiver::get_CXH() { return CXH; }\n", "meta": {"hexsha": "d5b7055dcafb1f63bab2c66175e51a0aca2ddacd", "size": 20765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "models/dm/src/GPS_receiver.cpp", "max_stars_repo_name": "cihuang123/Next-simulation", "max_stars_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "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": "models/dm/src/GPS_receiver.cpp", "max_issues_repo_name": "cihuang123/Next-simulation", "max_issues_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/dm/src/GPS_receiver.cpp", "max_forks_repo_name": "cihuang123/Next-simulation", "max_forks_repo_head_hexsha": "e8552a5804184b30022d103d47c8728fb242b5bc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-05T14:59:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-17T03:19:45.000Z", "avg_line_length": 30.4026354319, "max_line_length": 80, "alphanum_fraction": 0.5939320973, "num_tokens": 6861, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22347071917150488}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020 Alexander Sokolov <asokolov@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n// Copyright (c) 2020 Mikhail Komarov <nemo@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------////\n\n#ifndef CRYPTO3_MERKLE_DAMGARD_PADDING_HPP\n#define CRYPTO3_MERKLE_DAMGARD_PADDING_HPP\n\n#include <boost/crypto3/detail/inject.hpp>\n#include <boost/crypto3/detail/pack.hpp>\n#include <boost/crypto3/detail/octet.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace hashes {\n            namespace detail {\n                template<typename Hash>\n                class merkle_damgard_padding {\n                    typedef Hash policy_type;\n\n                    typedef typename policy_type::digest_endian endian_type;\n\n                    constexpr static const std::size_t word_bits = policy_type::word_bits;\n                    typedef typename policy_type::word_type word_type;\n\n                    constexpr static const std::size_t state_bits = policy_type::state_bits;\n                    constexpr static const std::size_t state_words = policy_type::state_words;\n                    typedef typename policy_type::state_type state_type;\n\n                    constexpr static const std::size_t block_bits = policy_type::block_bits;\n                    constexpr static const std::size_t block_words = policy_type::block_words;\n                    typedef typename policy_type::block_type block_type;\n\n                    constexpr static const std::size_t digest_bits = policy_type::digest_bits;\n                    typedef typename policy_type::digest_type digest_type;\n\n                    typedef ::boost::crypto3::detail::injector<endian_type, word_bits, block_words, block_bits>\n                        injector_type;\n\n                public:\n                    void operator()(block_type &block, std::size_t &block_seen) {\n                        using namespace boost::crypto3::detail;\n                        // Remove garbage\n                        block_type block_of_zeros;\n                        std::size_t seen_copy = block_seen;\n                        std::fill(block_of_zeros.begin(), block_of_zeros.end(), 0);\n                        injector_type::inject(block_of_zeros, block_bits - block_seen, block, seen_copy);\n\n                        // Get bit 1 in the endianness used by the hashes\n                        std::array<octet_type, word_bits / octet_bits> bit_one = {{0x80}};\n                        std::array<word_type, 1> bit_one_word {};\n                        pack<stream_endian::big_octet_big_bit, endian_type, octet_bits, word_bits>(\n                            bit_one.begin(), bit_one.end(), bit_one_word.begin());\n\n                        // Add 1 bit to block\n                        injector_type::inject(bit_one_word[0], 1, block, block_seen);\n                    }\n                };\n            }    // namespace detail\n        }        // namespace hashes\n    }            // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_MERKLE_DAMGARD_PADDING_HPP\n", "meta": {"hexsha": "e79fa803ae506395e9cee5756de5a11882b510a8", "size": 3329, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/hash/detail/merkle_damgard_padding.hpp", "max_stars_repo_name": "NilFoundation/boost-crypto", "max_stars_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-02T06:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T04:55:03.000Z", "max_issues_repo_path": "include/boost/crypto3/hash/detail/merkle_damgard_padding.hpp", "max_issues_repo_name": "NilFoundation/boost-crypto", "max_issues_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-06T21:49:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T04:54:51.000Z", "max_forks_repo_path": "include/boost/crypto3/hash/detail/merkle_damgard_padding.hpp", "max_forks_repo_name": "NilFoundation/boost-crypto", "max_forks_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:14:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:14:37.000Z", "avg_line_length": 47.5571428571, "max_line_length": 111, "alphanum_fraction": 0.5683388405, "num_tokens": 650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22347071917150488}}
{"text": "#include <iostream>\n\n#include <armadillo>\n\n#include <cpp-argparse/OptionParser.h>\n#include <besiq/io/covariates.hpp>\n\n#include <plink/plink_file.hpp>\n#include <dcdflib/libdcdf.hpp>\n\nusing namespace arma;\nusing namespace optparse;\n\nconst std::string USAGE = \"besiq-var [OPTIONS] plink_file\";\nconst std::string DESCRIPTION = \"Computes variance hetrogenity for single variants.\";\nconst std::string VERSION = \"besiq 0.0.1\";\nconst std::string EPILOG = \"\";\n\narma::mat\ncompute_medians(const snp_row &row, const arma::vec &pheno, const arma::uvec &missing)\n{\n    std::vector<std::vector<double>> groups( 3 );\n    arma::mat medians = arma::zeros<arma::mat>( 3, 2 );\n    for(int i = 0; i < row.size( ); i++)\n    {\n        if( row[ i ] != 3 && missing[ i ] == 0 )\n        {\n            groups[ row[ i ] ].push_back( pheno[ i ] );\n            medians( row[ i ], 1 ) += 1.0;\n        }\n    }\n\n    for(int i = 0; i < 3; i++)\n    {\n        std::sort( groups[ i ].begin( ), groups[ i ].end( ) );\n        if( groups[ i ].size( ) > 0 )\n        {\n            medians( i, 0 ) = groups[ i ][ groups[ i ].size( ) / 2 ];\n        }\n        else\n        {\n            medians( i, 0 ) = 0.0;\n        }\n    }\n\n    return medians;\n}\n\nbool\ncompute_brown_forsythe(const snp_row &row, const arma::vec &pheno, const arma::uvec &missing, double *W, double *p, size_t *N)\n{\n    double k = 3;\n    arma::mat medians = compute_medians( row, pheno, missing );\n\n    if( arma::min( medians.col( 1 ) ) <= 20 )\n    {\n        *N = arma::accu( medians.col( 1 ) );\n        return false;\n    }\n    \n    arma::vec z_i = arma::zeros<arma::vec>( 3 );\n    double z = 0.0;\n    *N = arma::accu( medians.col( 1 ) );\n    for(int i = 0; i < row.size( ); i++)\n    {\n        if( row[ i ] != 3 && missing[ i ] == 0 )\n        {\n            double z_ij = std::abs( pheno[ i ] - medians( row[ i ], 0 ) );\n            z_i[ row[ i ] ] += z_ij / medians( row[ i ], 1 );\n            z += z_ij / *N;\n        }\n    }\n\n    double W_sq = 0.0;\n    for(int i = 0; i < row.size( ); i++)\n    {\n        if( row[ i ] != 3 && missing[ i ] == 0 )\n        {\n            double z_ij = std::abs( pheno[ i ] - medians( row[ i ], 0 ) );\n            W_sq += pow( z_ij - z_i[ row[ i ] ], 2 );\n        }\n    }\n\n    double numerator = dot( medians.col( 1 ), pow( z_i - z, 2 ) );\n\n    *W = ( (*N - k) * numerator ) / ( ( k - 1 ) * W_sq );\n    *p = 1 - f_cdf( *W, k - 1, *N - k );\n\n    return true;\n}\n\n\nint\nmain(int argc, char *argv[])\n{\n    OptionParser parser = OptionParser( ).usage( USAGE )\n                                         .version( VERSION )\n                                         .description( DESCRIPTION )\n                                         .epilog( EPILOG ); \n \n    parser.add_option( \"-p\", \"--pheno\" ).help( \"Read phenotypes from this file instead of a plink file.\" );\n    parser.add_option( \"-e\", \"--mpheno\" ).help( \"Name of the phenotype that you want to read (if there are more than one in the phenotype file).\" );\n    parser.add_option( \"-o\", \"--out\" ).help( \"The output file that will contain the results (binary).\" );\n\n    Values options = parser.parse_args( argc, argv );\n    if( parser.args( ).size( ) != 1 )\n    {\n        parser.print_help( );\n        exit( 1 );\n    }\n\n    std::ios_base::sync_with_stdio( false );\n    \n    /* Read all genotypes */\n    plink_file_ptr genotype_file = open_plink_file( parser.args( )[ 0 ] );\n    genotype_matrix_ptr genotypes = create_genotype_matrix( genotype_file );\n    std::vector<std::string> order = genotype_file->get_sample_iids( );\n\n    /* Parse phenotypes */\n    arma::uvec missing = arma::zeros<arma::uvec>( genotype_file->get_samples( ).size( ) );\n    arma::vec phenotypes;\n    if( options.is_set( \"pheno\" ) )\n    {\n        std::ifstream phenotype_file( options[ \"pheno\" ].c_str( ) );\n        phenotypes = parse_phenotypes( phenotype_file, missing, order, options[ \"mpheno\" ] );\n    }\n    else\n    {\n        phenotypes = create_phenotype_vector( genotype_file->get_samples( ), missing );\n    }\n\n\n    std::vector<pio_locus_t> loci = genotype_file->get_loci( );\n    std::cout << \"chr\\tpos\\tsnp\\tW\\tP\\tN\\n\";\n    for( int i = 0; i < loci.size( ); i++)\n    {\n        const snp_row &row = *genotypes->get_row( loci[ i ].name );\n        double W;\n        double p;\n        size_t N;\n        if( compute_brown_forsythe( row, phenotypes, missing, &W, &p, &N ) )\n        {\n            std::cout << (int) loci[ i ].chromosome << \"\\t\" << loci[ i ].bp_position << \"\\t\"  << loci[ i ].name << \"\\t\" << W << \"\\t\" << p << \"\\t\" << N << \"\\n\";\n        }\n        else\n        {\n            std::cout << (int) loci[ i ].chromosome << \"\\t\" << loci[ i ].bp_position << \"\\t\" << loci[ i ].name << \"\\t\" << \"NA\" << \"\\t\" << \"NA\" << \"\\t\" << N << \"\\n\";\n        }\n    }\n\n    return 0;\n}\n", "meta": {"hexsha": "1d2c00e7313bb5e3920df3fc50f5e15034277916", "size": 4745, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/besiq_var.cpp", "max_stars_repo_name": "hoehleatsu/besiq", "max_stars_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T14:22:12.000Z", "max_stars_repo_stars_event_max_datetime": "2015-10-21T14:22:12.000Z", "max_issues_repo_path": "src/besiq_var.cpp", "max_issues_repo_name": "hoehleatsu/besiq", "max_issues_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-26T20:52:31.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-28T16:19:49.000Z", "max_forks_repo_path": "src/besiq_var.cpp", "max_forks_repo_name": "hoehleatsu/besiq", "max_forks_repo_head_hexsha": "94959e2819251805e19311ce377919e6bccb7bf9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-11-06T14:58:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-26T14:03:13.000Z", "avg_line_length": 31.0130718954, "max_line_length": 164, "alphanum_fraction": 0.514857745, "num_tokens": 1463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635868562172, "lm_q2_score": 0.34864514886966624, "lm_q1q2_score": 0.2233545877661064}}
{"text": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <orea/aggregation/dynamiccreditxvacalculator.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/error_of_mean.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\n\nusing namespace boost::accumulators;\n\nnamespace ore {\nnamespace analytics {\n\nDynamicCreditXvaCalculator::DynamicCreditXvaCalculator(\n    //! Driving portfolio consistent with the cube below\n    const boost::shared_ptr<Portfolio> portfolio, const boost::shared_ptr<Market> market,\n    const string& configuration, const string& baseCurrency, const string& dvaName,\n    const string& fvaBorrowingCurve, const string& fvaLendingCurve,\n    const bool applyDynamicInitialMargin,\n    const boost::shared_ptr<DynamicInitialMarginCalculator> dimCalculator,\n    const boost::shared_ptr<NPVCube> tradeExposureCube,\n    const boost::shared_ptr<NPVCube> nettingSetExposureCube,\n    const boost::shared_ptr<NPVCube>& cptyCube,\n    const Size tradeEpeIndex, const Size tradeEneIndex,\n    const Size nettingSetEpeIndex, const Size nettingSetEneIndex, const Size cptySpIndex,\n    const bool flipViewXVA, const string& flipViewBorrowingCurvePostfix, const string& flipViewLendingCurvePostfix)\n    : ValueAdjustmentCalculator(portfolio, market, configuration, baseCurrency, dvaName,\n                                fvaBorrowingCurve, fvaLendingCurve, applyDynamicInitialMargin,\n                                dimCalculator, tradeExposureCube, nettingSetExposureCube, tradeEpeIndex, tradeEneIndex, \n                                nettingSetEpeIndex, nettingSetEneIndex, \n                                flipViewXVA, flipViewBorrowingCurvePostfix, flipViewLendingCurvePostfix),\n      cptyCube_(cptyCube), cptySpIndex_(cptySpIndex) {\n    // check consistency of input\n\n    QL_REQUIRE(tradeExposureCube_->numDates() == cptyCube->numDates(),\n        \"number of dates in tradeExposureCube and cptyCube mismatch (\"\n        << tradeExposureCube_->numDates() << \" vs \" << cptyCube->numDates() << \")\");\n\n    QL_REQUIRE(cptySpIndex < cptyCube->depth(), \"cptySpIndex(\"\n        << cptySpIndex << \") exceeds depth of cptyCube(\"\n        << cptyCube->depth() << \")\");\n    \n    for (Size i = 0; i < tradeExposureCube_->numDates(); i++) {\n        QL_REQUIRE(tradeExposureCube_->dates()[i] == cptyCube->dates()[i],\n            \"date at \" << i << \" in tradeExposureCube and cptyCube mismatch (\"\n            << tradeExposureCube_->dates()[i] << \" vs \" << cptyCube->dates()[i] << \")\");\n    }\n}\n\n\nconst Real DynamicCreditXvaCalculator::calculateCvaIncrement(\n    const string& tid, const string& cid, const Date& d0, const Date& d1, const Real& rr) {\n    Real increment = 0.0;\n    for (Size k = 0; k < tradeExposureCube_->samples(); ++k) {\n        Real s0 = d0 == asof() ? 1.0 : cptyCube_->get(cid, d0, k, cptySpIndex_);\n        Real s1 = cptyCube_->get(cid, d1, k, cptySpIndex_);\n        Real epe = tradeExposureCube_->get(tid, d1, k, tradeEpeIndex_);\n        increment += (s0 - s1) * epe;\n    }\n    return (1.0 - rr) * increment / tradeExposureCube_->samples();\n}\n\nconst Real DynamicCreditXvaCalculator::calculateDvaIncrement(\n    const string& tid, const Date& d0, const Date& d1, const Real& rr) {\n    Real increment = 0.0;\n    for (Size k = 0; k < tradeExposureCube_->samples(); ++k) {\n        Real s0 = d0 == asof() ? 1.0 : cptyCube_->get(dvaName_, d0, k, cptySpIndex_);\n        Real s1 = cptyCube_->get(dvaName_, d1, k, cptySpIndex_);\n        Real ene = tradeExposureCube_->get(tid, d1, k, tradeEneIndex_);\n        increment += (s0 - s1) * ene;\n    }\n    return (1.0 - rr) * increment / tradeExposureCube_->samples();\n}\n\nconst Real DynamicCreditXvaCalculator::calculateNettingSetCvaIncrement(\n    const string& nid, const string& cid, const Date& d0, const Date& d1, const Real& rr) {\n    Real increment = 0.0;\n    for (Size k = 0; k < nettingSetExposureCube_->samples(); ++k) {\n        Real s0 = d0 == asof() ? 1.0 : cptyCube_->get(cid, d0, k, cptySpIndex_);\n        Real s1 = cptyCube_->get(cid, d1, k, cptySpIndex_);\n        Real epe = nettingSetExposureCube_->get(nid, d1, k, nettingSetEpeIndex_);\n        increment += (s0 - s1) * epe;\n    }\n    return (1.0 - rr) * increment / nettingSetExposureCube_->samples();\n}\n\nconst Real DynamicCreditXvaCalculator::calculateNettingSetDvaIncrement(\n    const string& nid, const Date& d0, const Date& d1, const Real& rr) {\n    Real increment = 0.0;\n    for (Size k = 0; k < nettingSetExposureCube_->samples(); ++k) {\n        Real s0 = d0 == asof() ? 1.0 : cptyCube_->get(dvaName_, d0, k, cptySpIndex_);\n        Real s1 = cptyCube_->get(dvaName_, d1, k, cptySpIndex_);\n        Real ene = nettingSetExposureCube_->get(nid, d1, k, nettingSetEneIndex_);\n        increment += (s0 - s1) * ene;\n    }\n    return (1.0 - rr) * increment / nettingSetExposureCube_->samples();\n}\n\nconst Real DynamicCreditXvaCalculator::calculateFbaIncrement(\n    const string& tid, const string& cid, const string& dvaName,\n    const Date& d0, const Date& d1, const Real& dcf) {\n    Real increment = 0.0;\n    for (Size k = 0; k < tradeExposureCube_->samples(); ++k) {\n        Real s0 = (d0 == asof() || cid == \"\") ? 1.0 : cptyCube_->get(cid, d0, k, cptySpIndex_);\n        Real s1 = (d0 == asof() || dvaName == \"\") ? 1.0 : cptyCube_->get(dvaName_, d0, k, cptySpIndex_);\n        Real ene = tradeExposureCube_->get(tid, d1, k, tradeEneIndex_);\n        increment += s0 * s1 * ene;\n    }\n    return increment * dcf / tradeExposureCube_->samples();\n}\n\nconst Real DynamicCreditXvaCalculator::calculateFcaIncrement(\n    const string& tid, const string& cid, const string& dvaName,\n    const Date& d0, const Date& d1, const Real& dcf) {\n    Real increment = 0.0;\n    for (Size k = 0; k < tradeExposureCube_->samples(); ++k) {\n        Real s0 = (d0 == asof() || cid == \"\") ? 1.0 : cptyCube_->get(cid, d0, k, cptySpIndex_);\n        Real s1 = (d0 == asof() || dvaName == \"\") ? 1.0 : cptyCube_->get(dvaName_, d0, k, cptySpIndex_);\n        Real epe = tradeExposureCube_->get(tid, d1, k, tradeEpeIndex_);\n        increment += s0 * s1 * epe;\n    }\n    return increment * dcf / tradeExposureCube_->samples();\n}\n\nconst Real DynamicCreditXvaCalculator::calculateNettingSetFbaIncrement(\n    const string& nid, const string& cid, const string& dvaName,\n    const Date& d0, const Date& d1, const Real& dcf) {\n    Real increment = 0.0;\n    for (Size k = 0; k < nettingSetExposureCube_->samples(); ++k) {\n        Real s0 = (d0 == asof() || cid == \"\") ? 1.0 : cptyCube_->get(cid, d0, k, cptySpIndex_);\n        Real s1 = (d0 == asof() || dvaName == \"\") ? 1.0 : cptyCube_->get(dvaName_, d0, k, cptySpIndex_);\n        Real ene = nettingSetExposureCube_->get(nid, d1, k, nettingSetEneIndex_);\n        increment += s0 * s1 * ene;\n    }\n    return increment * dcf / nettingSetExposureCube_->samples();\n}\n\nconst Real DynamicCreditXvaCalculator::calculateNettingSetFcaIncrement(\n    const string& nid, const string& cid, const string& dvaName,\n    const Date& d0, const Date& d1, const Real& dcf) {\n    Real increment = 0.0;\n    for (Size k = 0; k < nettingSetExposureCube_->samples(); ++k) {\n        Real s0 = (d0 == asof() || cid == \"\") ? 1.0 : cptyCube_->get(cid, d0, k, cptySpIndex_);\n        Real s1 = (d0 == asof() || dvaName == \"\") ? 1.0 : cptyCube_->get(dvaName_, d0, k, cptySpIndex_);\n        Real epe = nettingSetExposureCube_->get(nid, d1, k, nettingSetEpeIndex_);\n        increment += s0 * s1 * epe;\n    }\n    return increment * dcf / nettingSetExposureCube_->samples();\n}\n\nconst Real DynamicCreditXvaCalculator::calculateNettingSetMvaIncrement(\n    const string& nid, const string& cid, const Date& d0, const Date& d1, const Real& dcf) {\n\n    Real increment = 0.0;\n    for (Size k = 0; k < nettingSetExposureCube_->samples(); ++k) {\n        Real s0 = (d0 == asof() || cid == \"\") ? 1.0 : cptyCube_->get(cid, d0, k, cptySpIndex_);\n        Real s1 = (d0 == asof() || dvaName_ == \"\") ? 1.0 : cptyCube_->get(dvaName_, d0, k, cptySpIndex_);\n        Real im = dimCalculator_->dimCube()->get(nid, d1, k);\n        increment += s0 * s1 * im;\n    }\n    return increment * dcf / nettingSetExposureCube_->samples();\n}\n\n} // namespace analytics\n} // namespace ore\n", "meta": {"hexsha": "947c209d9655e17f99894efb4b75cedaaf5b5431", "size": 8979, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/orea/aggregation/dynamiccreditxvacalculator.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "OREAnalytics/orea/aggregation/dynamiccreditxvacalculator.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "OREAnalytics/orea/aggregation/dynamiccreditxvacalculator.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 48.2741935484, "max_line_length": 120, "alphanum_fraction": 0.6637710213, "num_tokens": 2685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.22314539673029674}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n#ifndef GM2CALC_INTERFACE_H\n#define GM2CALC_INTERFACE_H\n\n#include <Eigen/Core>\n\n/**\n * @file gm2calc_interface.hpp\n * @brief contains declarations of GM2Calc interface functions\n */\n\nnamespace flexiblesusy {\n\n/**\n * @class GM2Calc_data\n * @brief data to be passed to GM2Calc\n */\nstruct GM2Calc_data {\n   GM2Calc_data();                ///< initializes members to GM2Calc default values\n   void initialize();             ///< initializes members to GM2Calc default values\n\n   double alpha_em_MZ;            ///< alpha_em(MZ)\n   double alpha_em_0;             ///< alpha_em(0)\n   double alpha_s_MZ;             ///< alpha_s(MZ) SM MS-bar\n   double MZ;                     ///< Z pole mass\n   double MW;                     ///< W pole mass\n   double mb_mb;                  ///< mb(mb) SM MS-bar\n   double MT;                     ///< top quark pole mass\n   double MTau;                   ///< tau lepton pole mass\n   double MM;                     ///< muon pole mass\n   double MA0;                    ///< CP-odd Higgs pole mass\n   double MSvm;                   ///< muon sneutrino pole mass\n   Eigen::Array<double,2,1> MSm;  ///< smuon pole masses\n   Eigen::Array<double,2,1> MCha; ///< chargino pole masses\n   Eigen::Array<double,4,1> MChi; ///< neutralino pole masses\n   double scale;                  ///< renormalization scale\n   double TB;                     ///< tan(beta) DR-bar\n   double Mu;                     ///< mu parameter (initial guess)\n   double M1;                     ///< bino mass parameter (initial guess)\n   double M2;                     ///< wino mass parameter (initial guess)\n   double M3;                     ///< gluino mass parameter\n   Eigen::Matrix<double,3,3> mq2; ///< left-handed squark mass parameters squared\n   Eigen::Matrix<double,3,3> mu2; ///< right-handed up-type squark mass parameters squared\n   Eigen::Matrix<double,3,3> md2; ///< right-handed down-type squark mass parameters squared\n   Eigen::Matrix<double,3,3> ml2; ///< left-handed slepton mass parameters squared\n   Eigen::Matrix<double,3,3> me2; ///< right-handed down-type slepton mass parameters squared\n   Eigen::Matrix<double,3,3> Au;  ///< up-type squark trilinear coupling\n   Eigen::Matrix<double,3,3> Ad;  ///< down-type squark trilinear coupling\n   Eigen::Matrix<double,3,3> Ae;  ///< down-type slepton trilinear coupling\n};\n\n/// calculates amu using GM2Calc\ndouble gm2calc_calculate_amu(const GM2Calc_data&);\n\n/// calculates uncertainty of amu using GM2Calc\ndouble gm2calc_calculate_amu_uncertainty(const GM2Calc_data&);\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "a8802f42a11f56b44961d044cbab5a73fbf60cb5", "size": 3407, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/gm2calc_interface.hpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/src/gm2calc_interface.hpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/src/gm2calc_interface.hpp", "max_forks_repo_name": "aaronvincent/gambit_aaron", "max_forks_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 43.6794871795, "max_line_length": 93, "alphanum_fraction": 0.6119753449, "num_tokens": 804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22305200822132848}}
{"text": "#include \"LanguageModel.h\"\n\n#include <iostream>\n#include <math.h>\n#include <random>\n#include <sstream>\n\n#include <boost/regex.hpp>\n\nusing namespace distrust;\nusing namespace Eigen;\n\nLanguageModel::LanguageModel(const ModelInfo &model_info) :\n  unif_(-1.0, 1.0),\n  batch_size_(0) {\n\n  window_size_ = model_info.window_size;\n  wordvec_dim_ = model_info.wordvec_dim;\n  hidden_dim_ = model_info.hidden_dim;\n  start_token_index_ = model_info.start_token_index;\n  end_token_index_ = model_info.end_token_index;\n  unk_token_index_ = model_info.unk_token_index;\n  vocab_size_ = model_info.vocab.size();\n  for (unsigned int i = 0; i < vocab_size_; i++) {\n    vocab_[model_info.vocab[i]] = i;\n  }\n\n  wordvec_w_.reserve(vocab_size_);\n  wordvec_w_buf_.reserve(vocab_size_);\n  input_hidden_w_.reserve(window_size_);\n  input_hidden_w_buf_.reserve(window_size_);\n\n  for (unsigned int i = 0; i < window_size_; i++) {\n    input_hidden_w_grad_.push_back(Matrix_t(hidden_dim_, wordvec_dim_));\n  }\n  input_hidden_b_grad_ = Vector_t(hidden_dim_);\n  hidden_output_w_grad_ = Matrix_t(vocab_size_, hidden_dim_);\n  hidden_output_b_grad_ = Vector_t(vocab_size_);\n\n  // adagrad\n  for (unsigned int i = 0; i < vocab_size_; i++) {\n    wordvec_w_var_.push_back(ArrayXd::Zero(wordvec_dim_));\n  }\n\n  for (unsigned int i = 0; i < window_size_; i++) {\n    input_hidden_w_var_.push_back(MArray_t::Zero(hidden_dim_, wordvec_dim_));\n  }\n\n  input_hidden_b_var_ = ArrayXd::Zero(hidden_dim_);\n  hidden_output_w_var_ = MArray_t::Zero(vocab_size_, hidden_dim_);\n  hidden_output_b_var_ = ArrayXd::Zero(vocab_size_);\n  zero_grad_params();\n}\n\nLanguageModel::LanguageModel(const LanguageModel &model) :\n  window_size_(model.window_size_),\n  wordvec_dim_(model.wordvec_dim_),\n  hidden_dim_(model.hidden_dim_),\n  start_token_index_(model.start_token_index_),\n  end_token_index_(model.end_token_index_),\n  unk_token_index_(model.unk_token_index_),\n  vocab_size_(model.vocab_size_),\n  vocab_(model.vocab_),\n  wordvec_w_buf_(model.wordvec_w_buf_),\n  input_hidden_w_buf_(model.input_hidden_w_buf_),\n  input_hidden_b_buf_(model.input_hidden_b_buf_),\n  hidden_output_w_buf_(model.hidden_output_w_buf_),\n  hidden_output_b_buf_(model.hidden_output_b_buf_),\n  input_hidden_w_grad_(model.input_hidden_w_grad_),\n  input_hidden_b_grad_(model.input_hidden_b_grad_),\n  hidden_output_w_grad_(model.hidden_output_w_grad_),\n  hidden_output_b_grad_(model.hidden_output_b_grad_) {\n  \n  zero_grad_params();\n  wrap_buffers();\n}\n\ndouble\nLanguageModel::sample() {\n  return unif_(re_);\n}\n\nvoid\nLanguageModel::wrap_buffers() {\n  wordvec_w_.clear();\n  for (unsigned int i = 0; i < vocab_size_; i++) {\n    wordvec_w_.push_back(Map<Vector_t>(&wordvec_w_buf_[i][0], wordvec_dim_));\n  } \n\n  input_hidden_w_.clear();\n  for (unsigned int i = 0; i < window_size_; i++) {\n    input_hidden_w_.push_back(Map<Matrix_t>(&input_hidden_w_buf_[i][0], hidden_dim_, wordvec_dim_));\n  }\n\n  input_hidden_b_ = std::unique_ptr<Map<Vector_t>>(\n    new Map<Vector_t>(&input_hidden_b_buf_[0], hidden_dim_));\n  hidden_output_w_ = std::unique_ptr<Map<Matrix_t>>(\n    new Map<Matrix_t>(&hidden_output_w_buf_[0], vocab_size_, hidden_dim_));\n  hidden_output_b_ = std::unique_ptr<Map<Vector_t>>(\n    new Map<Vector_t>(&hidden_output_b_buf_[0], vocab_size_));\n}\n\nvoid\nLanguageModel::random_init() {\n  wordvec_w_buf_.clear();\n  for (unsigned int i = 0; i < vocab_size_; i++) {\n    wordvec_w_buf_.push_back(std::vector<double>(wordvec_dim_));\n    for (unsigned int j = 0; j < wordvec_dim_; j++) {\n      wordvec_w_buf_[i][j] = 0.05 * sample();\n    }\n  }\n\n  input_hidden_w_buf_.clear();\n  for (unsigned int i = 0; i < window_size_; i++) {\n    input_hidden_w_buf_.push_back(std::vector<double>(hidden_dim_ * wordvec_dim_));\n    for (unsigned int j = 0; j < hidden_dim_ * wordvec_dim_; j++) {\n      input_hidden_w_buf_[i][j] = 0.05 * sample();\n    }\n  }\n\n  input_hidden_b_buf_ = std::vector<double>(hidden_dim_, 0.0);\n  hidden_output_w_buf_ = std::vector<double>(vocab_size_ * hidden_dim_, 0.0);\n  hidden_output_b_buf_ = std::vector<double>(vocab_size_, 0.0);\n  wrap_buffers();\n}\n\nvoid\nLanguageModel::set_params(Params &params) {\n  wordvec_w_buf_ = std::move(params.wordvec_w);\n  input_hidden_w_buf_ = std::move(params.input_hidden_w);\n  input_hidden_b_buf_ = std::move(params.input_hidden_b);\n  hidden_output_w_buf_ = std::move(params.hidden_output_w);\n  hidden_output_b_buf_ = std::move(params.hidden_output_b);\n  wrap_buffers();\n}\n\nvoid\nLanguageModel::update_params(const ParamUpdate &update) {\n  for (auto itr = update.wordvec_w.begin(); itr != update.wordvec_w.end(); itr++) {\n    uint32_t idx = itr->first;\n    for (unsigned int i = 0; i < wordvec_dim_; i++) {\n      wordvec_w_buf_[idx][i] += itr->second[i];\n    }\n  }\n\n  for (unsigned int i = 0; i < window_size_; i++) {\n    for (unsigned int j = 0; j < wordvec_dim_ * hidden_dim_; j++) {\n      input_hidden_w_buf_[i][j] += update.input_hidden_w[i][j];\n    }\n  }\n\n  for (unsigned int i = 0; i < hidden_dim_; i++) {\n    input_hidden_b_buf_[i] += update.input_hidden_b[i];\n  }\n\n  for (unsigned int i = 0; i < hidden_dim_ * vocab_size_; i++) {\n    hidden_output_w_buf_[i] += update.hidden_output_w[i];\n  }\n\n  for (unsigned int i = 0; i < vocab_size_; i++) {\n    hidden_output_b_buf_[i] += update.hidden_output_b[i];\n  }\n}\n\nvoid\nLanguageModel::get_params(Params &ret) {\n  ret.wordvec_w = wordvec_w_buf_;\n  ret.input_hidden_w = input_hidden_w_buf_;\n  ret.input_hidden_b = input_hidden_b_buf_;\n  ret.hidden_output_w = hidden_output_w_buf_;\n  ret.hidden_output_b = hidden_output_b_buf_;\n}\n\nvoid\nLanguageModel::get_update(ParamUpdate &ret, const double learn_rate) {\n  double *ptr;\n  for (auto itr = wordvec_w_grad_.begin(); itr != wordvec_w_grad_.end(); itr++) {\n    uint32_t idx = itr->first;\n    //ArrayXd a = itr->second.array() * (-learn_rate);\n    ArrayXd a = itr->second.array();\n    wordvec_w_var_[idx] += a.square();\n    a *= -learn_rate / (wordvec_w_var_[idx].sqrt() + 1e-4);\n    ptr = a.data();\n    ret.wordvec_w[idx] = std::vector<double>(ptr, ptr + wordvec_dim_);\n  }\n\n  for (unsigned int i = 0; i < window_size_; i++) {\n    //MArray_t a = input_hidden_w_grad_[i].array() * (-learn_rate);\n    MArray_t a = input_hidden_w_grad_[i].array();\n    input_hidden_w_var_[i] += a.square();\n    a *= -learn_rate / (input_hidden_w_var_[i].sqrt() + 1e-4);\n    ptr = a.data();\n    ret.input_hidden_w.push_back(std::vector<double>(ptr, ptr + hidden_dim_ * wordvec_dim_));\n  }\n\n  //ArrayXd a_ihb = input_hidden_b_grad_.array() * (-learn_rate);\n  ArrayXd a_ihb = input_hidden_b_grad_.array();\n  input_hidden_b_var_ += a_ihb.square();\n  a_ihb *= -learn_rate / (input_hidden_b_var_.sqrt() + 1e-4);\n  ptr = a_ihb.data();\n  ret.input_hidden_b = std::vector<double>(ptr, ptr + hidden_dim_);\n\n  //MArray_t a_how = hidden_output_w_grad_.array() * (-learn_rate);\n  MArray_t a_how = hidden_output_w_grad_.array();\n  hidden_output_w_var_ += a_how.square();\n  a_how *= -learn_rate / (hidden_output_w_var_.sqrt() + 1e-4);\n  ptr = a_how.data();\n  ret.hidden_output_w = std::vector<double>(ptr, ptr + vocab_size_ * hidden_dim_);\n\n  //ArrayXd a_hob = hidden_output_b_grad_.array() * (-learn_rate);\n  ArrayXd a_hob = hidden_output_b_grad_.array();\n  hidden_output_b_var_ += a_hob.square();\n  a_hob *= -learn_rate / (hidden_output_b_var_.sqrt() + 1e-4);\n  ptr = a_hob.data();\n  ret.hidden_output_b = std::vector<double>(ptr, ptr + vocab_size_);\n}\n\nVectorXd\nLanguageModel::tanh(const VectorXd &v) {\n  ArrayXd a = (v.array() * 2).exp();\n  return ((a - 1) / (a + 1)).matrix();\n}\n\ndouble\nLanguageModel::logZ(const VectorXd &v) {\n  return log(v.array().exp().sum());\n}\n\nuint32_t\nLanguageModel::word_index(const std::string &word) {\n  boost::regex re(\"[0-9]\");\n  std::string token = boost::regex_replace(word, re, \"0\");\n  uint32_t index = unk_token_index_;\n  auto itr = vocab_.find(token);\n  if (itr != vocab_.end()) {\n    index = itr->second;\n  }\n  return index;\n}\n\nstd::vector<uint32_t>\nLanguageModel::tokenize(const std::string &line) {\n  std::vector<uint32_t> tokens;\n  for (unsigned int i = 0; i < window_size_; i++) {\n    tokens.push_back(start_token_index_);\n  }\n\n  std::string word;\n  std::stringstream ss(line);\n  while (std::getline(ss, word, ' ')) {\n    tokens.push_back(word_index(word));\n  }\n  tokens.push_back(end_token_index_);\n  return tokens;\n}\n\nstd::vector<double>\nLanguageModel::forward(const std::vector<uint32_t> &input) {\n  if (input.size() != window_size_) {\n    throw std::invalid_argument(\"forward: input size does not equal window size\");\n  }\n\n  hidden_ = *input_hidden_b_;\n  for (unsigned int i = 0; i < window_size_; i++) {\n    hidden_ += input_hidden_w_[i] * wordvec_w_[input[i]];\n  }\n  hidden_tanh_ = tanh(hidden_);\n  output_ = (*hidden_output_w_) * hidden_tanh_ + (*hidden_output_b_);\n  logZ_ = logZ(output_);\n  output_normed_ = (output_.array() - logZ_).matrix();\n  double *ptr = output_normed_.data();\n  return std::vector<double>(ptr, ptr + vocab_size_);\n}\n\n// double\n// LanguageModel::forward(const std::vector<uint32_t> &tokens) {\n//   uint32_t size = tokens.size() - window_size_;\n//   Matrix<uint32_t, Dynamic, Dynamic> input(size, window_size_);\n//   for (unsigned int i = 0; i < size; i++) {\n//     for (unsigned int j = 0; j < window_size_; j++) {\n//       input(i, j) = tokens[i + j];\n//     }\n//   }\n\n\n// }\n\n// double\n// LanguageModel::forward(const std::vector<uint32_t> &input, const uint32_t target) {\n//   if (input.size() != window_size_) {\n//     throw std::invalid_argument(\"forward: input size does not equal window size\");\n//   }\n\n//   hidden_ = *input_hidden_b_;\n//   for (unsigned int i = 0; i < window_size_; i++) {\n//     hidden_ += input_hidden_w_[i] * wordvec_w_[input[i]];\n//   }\n//   hidden_tanh_ = tanh(hidden_);\n//   output_ = (*hidden_output_w_) * hidden_tanh_ + (*hidden_output_b_);\n//   logZ_ = logZ(output_);\n//   output_normed_ = (output_.array() - logZ_).matrix();\n//   return output_normed_(target);\n// }\n\n// std::vector<double>\n// LanguageModel::forward(const std::vector<uint32_t> &input, uint32_t target_idx) {\n//   hidden_ = *input_hidden_b_;\n//   for (unsigned int i = 0; i < window_size_; i++) {\n//     hidden_ += input_hidden_w_[i] * wordvec_w_[input[target_idx - window_size_ + i]];\n//   }\n//   hidden_tanh_ = tanh(hidden_);\n//   output_ = (*hidden_output_w_) * hidden_tanh_ + (*hidden_output_b_);\n//   logZ_ = logZ(output_);\n//   output_normed_ = (output_.array() - logZ_).matrix();\n\n//   double *ptr = output_normed_.data();\n//   return std::vector<double>(ptr, ptr + vocab_size_);\n// }\n\nvoid\nLanguageModel::backward(\n  const std::vector<uint32_t> &input,\n  const uint32_t target) {\n\n  batch_size_++;\n\n  // hidden-output gradients\n  Vector_t output_grad = output_normed_.array().exp().matrix();\n  output_grad(target) -= 1;\n  hidden_output_w_grad_ += output_grad * hidden_tanh_.transpose();\n  hidden_output_b_grad_ += output_grad;\n\n  // input-hidden gradients\n  Vector_t hidden_grad = output_grad.transpose() * (*hidden_output_w_);\n  hidden_grad = (hidden_grad.array() * \n    (1 - hidden_tanh_.array().square()))\n    .matrix();\n  for (unsigned int i = 0; i < window_size_; i++) {\n    input_hidden_w_grad_[i] += hidden_grad * wordvec_w_[input[i]].transpose();\n  }\n  input_hidden_b_grad_ += hidden_grad;\n\n  // word vector gradients\n  for (unsigned int i = 0; i < window_size_; i++) {\n    uint32_t idx = input[i];\n    Vector_t input_grad = hidden_grad.transpose() * input_hidden_w_[i];\n    auto itr = wordvec_w_grad_.find(idx);\n    if (itr == wordvec_w_grad_.end()) {\n      wordvec_w_grad_[idx] = input_grad;\n    } else {\n      wordvec_w_grad_[idx] += input_grad;\n    }\n  }\n}\n\nvoid\nLanguageModel::zero_grad_params() {\n  batch_size_ = 0;\n  wordvec_w_grad_.clear();\n  for (unsigned int i = 0; i < window_size_; i++) {\n    input_hidden_w_grad_[i].setZero();\n  }\n  input_hidden_b_grad_.setZero();\n  hidden_output_w_grad_.setZero();\n  hidden_output_b_grad_.setZero();\n}\n", "meta": {"hexsha": "b4413ed2d1b655495c05e0abad6d882c6ca62051", "size": 11852, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "LanguageModel.cpp", "max_stars_repo_name": "kaishengtai/distrust", "max_stars_repo_head_hexsha": "b237110e7d5a70c9e1c1da20a94c1f83d1577926", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-17T21:15:55.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-17T21:15:55.000Z", "max_issues_repo_path": "LanguageModel.cpp", "max_issues_repo_name": "kaishengtai/distrust", "max_issues_repo_head_hexsha": "b237110e7d5a70c9e1c1da20a94c1f83d1577926", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LanguageModel.cpp", "max_forks_repo_name": "kaishengtai/distrust", "max_forks_repo_head_hexsha": "b237110e7d5a70c9e1c1da20a94c1f83d1577926", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2942779292, "max_line_length": 100, "alphanum_fraction": 0.6925413432, "num_tokens": 3424, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.22299193865194877}}
{"text": "/**************************************************************************\\\n|\n|    Copyright (C) 2009 Marc Stevens\n|\n|    This program is free software: you can redistribute it and/or modify\n|    it under the terms of the GNU General Public License as published by\n|    the Free Software Foundation, either version 3 of the License, or\n|    (at your option) any later version.\n|\n|    This program is distributed in the hope that it will be useful,\n|    but WITHOUT ANY WARRANTY; without even the implied warranty of\n|    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n|    GNU General Public License for more details.\n|\n|    You should have received a copy of the GNU General Public License\n|    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n|\n\\**************************************************************************/\n\n#include \"main.hpp\"\n#include <hashclash/rng.hpp>\n#include <hashclash/progress_display.hpp>\n#include <hashclash/timer.hpp>\n#include <boost/lexical_cast.hpp>\n\nuint32 m[80];\nuint32 m2[80];\nuint32 Q[85];\nuint32 Q2[85];\nuint32 Qr30[85];\nuint32 Q2r30[85];\nuint32 dQ[85];\nuint32 dT[85];\nuint32 dR[85];\nuint32 dF[80];\n\nuint32 Qvaluemask[85];\nuint32 Qvalue[85];\nuint32 Qprev[85];\nuint32 Qprev2[85];\n\nvoid fill_tables(const sha1differentialpath& diffpath)\n{\n\tfor (int t = -4; t <= 80; ++t)\n\t{\n\t\tdF[t] = dQ[offset+t] = dT[offset+t] = dR[offset+t] = 0;\n\t\tQvaluemask[offset+t] = Qvalue[offset+t] = 0;\n\t\tQprev[offset+t] = Qprev2[offset+t] = 0;\n\t}\n\n\t// build tables\n\tfor (int t = diffpath.tbegin(); t < diffpath.tend(); ++t)\n\t{\n\t\tdQ[offset+t] = diffpath[t].diff();\n\t\tQprev[offset+t] = diffpath[t].prev() | diffpath[t].prevn();\n\t\tQprev2[offset+t] = diffpath[t].prev2() | diffpath[t].prev2n();\n\t\tQvaluemask[offset+t] = (~diffpath[t].set0()) | diffpath[t].set1()\n\t\t\t\t\t\t\t| diffpath[t].prev() | diffpath[t].prevn()\n\t\t\t\t\t\t\t| diffpath[t].prev2() | diffpath[t].prev2n();\n\t\tQvalue[offset+t] = diffpath[t].set1() | diffpath[t].prevn() | diffpath[t].prev2n();\n\t}\n\tbooleanfunction* F[4] = { &SHA1_F1_data, &SHA1_F2_data, &SHA1_F3_data, &SHA1_F4_data };\n\tfor (int t = diffpath.tbegin()+4; t+1 < diffpath.tend(); ++t) {\n\t\tbooleanfunction& FF = *F[t/20];\n\t\tuint32 dFt = 0;\n\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t\tdFt += FF.outcome(diffpath[t-1][b],diffpath[t-2][(b+2)&31],diffpath[t-3][(b+2)&31])(0,b);\n\t\tdF[t] = dFt;\n\t}\n\t\n\tQ[0] = Qvalue[0]; Q2[0] = Q[0] + dQ[0];\n\tQ[1] = Qvalue[1]; Q2[1] = Q[1] + dQ[1];\n\tQ[2] = Qvalue[2]; Q2[2] = Q[2] + dQ[2];\n\tQ[3] = Qvalue[3]; Q2[3] = Q[3] + dQ[3];\n\tQ[4] = Qvalue[4]; Q2[4] = Q[4] + dQ[4];\n}\n\n\nunsigned analyze_tunnel(const sha1differentialpath& tunnel, bool verbose, bool deepanalyze)\n{\n#define AT_TEST_COUNT (1<<18) // 16\n#define AT_MIN_PROB 0\n#define AT_MIN_COUNT (AT_TEST_COUNT>>AT_MIN_PROB)\n\n\tvector< vector<unsigned> > qtbcnts(80, vector<unsigned>(32,0));\n\tstatic uint32 tcnts[80], qmask[80];\n\tstatic uint32 mmask[80], mset1[80];\n\tfor (unsigned t = 0; t < 40; ++t) {\n\t\ttcnts[t] = 0;\n\t\tqmask[t] = maindiffpath[t].mask();\n\t}\n\tsha1differentialpath diffpath = tunnel;\n\tdiffpath.get(-4);\n\tdiffpath.get(80);\n\tfill_tables(diffpath);\n\tfor (int t = 16; t < 80; ++t) {\n\t\tif (t-4 >= tunnel.tbegin() && t+1 < tunnel.tend()) {\n\t\t\tmmask[t] = ~tunnel.getme(t).mask;\n\t\t\tmset1[t] = tunnel.getme(t).set1conditions();\n\t\t} else {\n\t\t\tmmask[t] = ~uint32(0);\n\t\t\tmset1[t] = 0;\n\t\t}\n\t}\n\t\n\n\tfor (unsigned k = 0; k < AT_TEST_COUNT; ++k) {\n//\t\tif (k == (AT_TEST_COUNT>>6) && double(tcnts[22])/double(k) >= 0.8) return 17;\n\t\tint t = -4;\n\t\twhile (t < 17) {\n\t\t\tbool ok = false;\n\t\t\tfor (unsigned j = 0; j < 3; ++j) {\n\t\t\t\tQ[offset+t] = (xrng128()&~Qvaluemask[offset+t]) ^ Qvalue[offset+t];\n\t\t\t\tif (t > -4)\n\t\t\t\t\tQ[offset+t] ^= Qprev[offset+t]&Q[offset+t-1];\n\t\t\t\tif (t > -3)\n\t\t\t\t\tQ[offset+t] ^= Qprev2[offset+t]&Q[offset+t-2];\n\t\t\t\tQ2[offset+t] = Q[offset+t] + dQ[offset+t];\n\t\t\t\tif (t >= 1) {\n\t\t\t\t\tm[t-1] = Q[offset+t] - (\n\t\t\t\t\t\tsha1_f1(Q[offset+t-2], rotate_left(Q[offset+t-3],30), rotate_left(Q[offset+t-4],30)) + sha1_ac[0] + rotate_left(Q[offset+t-1],5) + rotate_left(Q[offset+t-5],30)\n\t\t\t\t\t\t);\n\t\t\t\t\tm2[t-1] = Q2[offset+t] - (\n\t\t\t\t\t\tsha1_f1(Q2[offset+t-2], rotate_left(Q2[offset+t-3],30), rotate_left(Q2[offset+t-4],30)) + sha1_ac[0] + rotate_left(Q2[offset+t-1],5) + rotate_left(Q2[offset+t-5],30)\n\t\t\t\t\t\t);\n\t\t\t\t\tif ((m2[t-1]^m[t-1]) == diffpath.getme(t-1).mask) {\n\t\t\t\t\t\tok = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (verbose)\n\t\t\t\t\t\t\tcout << \"(\" << t << \":\" << naf(m2[t-1]^m[t-1]) << \"!=\" << diffpath.getme(t-1) << \") \" << flush;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} else\n\t\t\t\t\tok = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (ok)\n\t\t\t\t++t;\n\t\t\telse\n\t\t\t\tt -= 4;\n\t\t\tif (t < -4) throw std::runtime_error(\"t < -4\");\n\t\t}\n\t\tfor (unsigned i = 16; i < 26; ++i) {\n\t\t\tm[i]=rotate_left(m[i-3] ^ m[i-8] ^ m[i-14] ^ m[i-16], 1);\n\t\t\tm2[i]=rotate_left(m2[i-3] ^ m2[i-8] ^ m2[i-14] ^ m2[i-16], 1);\n\t\t\tuint32 md = m[i]^m2[i];\n\t\t\tm[i] = (m[i]&mmask[i])^mset1[i];\n\t\t\tm2[i] = m[i] ^ md;\n\t\t}\n\t\tfor (int t = 16; t < 20; ++t) {\n\t\t\tsha1_step_round1(t, Q, m);\n\t\t\tsha1_step_round1(t, Q2, m2);\n\t\t}\n\t\tfor (int t = 20; t < 26; ++t) {\n\t\t\tsha1_step_round2(t, Q, m);\n\t\t\tsha1_step_round2(t, Q2, m2);\n\t\t}\n\t\tfor (int t = 17; t < 27; ++t) {\n\t\t\tfor (unsigned b = 0; b < 32; ++b)\n\t\t\t\tif ((Q2[offset+t]^Q[offset+t])&(1<<b))\n\t\t\t\t\t++qtbcnts[t][b];\n\t\t}\n\t\tint breakt = 80;\n\t\tfor (int t = 17; t < 27; ++t) {\n\t\t\tif ((Q2[offset+t]^Q[offset+t])&(qmask[t]|0x00000000)) {\n\t\t\t\tbreakt = t;\n\t\t\t\tfor (int t1 = t; t1 < 27; ++t1)\n\t\t\t\t\t++tcnts[t1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tint tret = 80;\n\tfor (int t = 17; t < 27; ++t)\n\t{\n\t\tif (tcnts[t] >= AT_MIN_COUNT) { tret = t; break; }\n\t\tif (double(tcnts[t]) >= double(AT_TEST_COUNT)*0.1) { tret = t; break; }\n\t}\n\tif (!deepanalyze || tret < mainparameters.mintunnelpov || tret == 80)\n\t\treturn tret;\n\tcout << \"Tunnel: \" << endl;\n\tshow_path(tunnel);\n\tcout << \"  << \";\n\tfor (int t1 = 17; t1 <= 25; ++t1)\n\t\tcout << t1 << \":\" << ((double(100)*double(tcnts[t1]))/double(AT_TEST_COUNT)) << \"% \";\n\tcout << \">>  \" << flush;\n\tcout << tret << \"b[\";\n\tfor (unsigned b = 0; b < 32; ++b)\n\t\tcout << b << \":\" << unsigned((double(100)*double(qtbcnts[tret][b]))/double(AT_TEST_COUNT)) << \"%\" << (b==31?\"]\":\",\");\n\tcout << endl;\n\treturn tret;\n}\n\n\n\n\n\n\n\n\n\n\n#define GOODBIT(i,t,b) ((goodqtb[i][t]>>b)&1)\n#define BADBIT(i,t,b) ((badqtb[i][t]>>b)&1)\n#define STAT_TEST(ba,go) ((double(ba)/double(ba+go))<0.6*(double(badqtb.size())/double(badqtb.size()+goodqtb.size())))\n#define STAT_ANA(ba,go,s) if (STAT_TEST(ba,go)) { cout << \"poss. bc: q_\" << t << \"[\" << b << \"]=\" << s << \": \\t\" << (double(100*ba)/double(ba+go)) << \"%\" << endl; }\nvoid stat_ana(vector< vector<uint32> >& goodqtb, vector< vector<uint32> >& badqtb\n\t, vector< vector<uint32> >& goodq2tb, vector< vector<uint32> >& badq2tb\n\t, int t, int b)\n{\n\tunsigned g_zero = 0, g_one = 0, g_prev = 0, g_prevn = 0, g_prevr = 0, g_prevrn = 0, g_prev2 = 0, g_prev2n = 0;\n\tunsigned b_zero = 0, b_one = 0, b_prev = 0, b_prevn = 0, b_prevr = 0, b_prevrn = 0, b_prev2 = 0, b_prev2n = 0;\n\tfor (unsigned i = 0; i < goodqtb.size(); ++i) {\n\t\tif (GOODBIT(i,t,b)==0) ++g_zero; else ++g_one;\n\t\tif (GOODBIT(i,t,b)==GOODBIT(i,t-1,b)) ++g_prev; else ++g_prevn;\n\t\tif (GOODBIT(i,t,b)==GOODBIT(i,t-1,((b+2)&31))) ++g_prevr; else ++g_prevrn;\n\t\tif (GOODBIT(i,t,b)==GOODBIT(i,t-2,((b+2)&31))) ++g_prev2; else ++g_prev2n;\n\t}\n\tfor (unsigned i = 0; i < badqtb.size(); ++i) {\n\t\tif (BADBIT(i,t,b)==0) ++b_zero; else ++b_one;\n\t\tif (BADBIT(i,t,b)==BADBIT(i,t-1,b)) ++b_prev; else ++b_prevn;\n\t\tif (BADBIT(i,t,b)==BADBIT(i,t-1,((b+2)&31))) ++b_prevr; else ++b_prevrn;\n\t\tif (BADBIT(i,t,b)==BADBIT(i,t-2,((b+2)&31))) ++b_prev2; else ++b_prev2n;\n\t}\n\tdouble baseprob = double(badqtb.size())/double(badqtb.size()+goodqtb.size());\n\tSTAT_ANA(b_zero,g_zero,\"0\");\n\tSTAT_ANA(b_one,g_one,\"1\");\n\tSTAT_ANA(b_prev,g_prev,\"^\");\n\tSTAT_ANA(b_prevn,g_prevn,\"!\");\n\tSTAT_ANA(b_prevr,g_prevr,\"^r\");\n\tSTAT_ANA(b_prevrn,g_prevrn,\"!r\");\n\tSTAT_ANA(b_prev2,g_prev2,\"M\");\n\tSTAT_ANA(b_prev2n,g_prev2n,\"#\");\n\tif (b != 0) return;\n\tif (1) {\n\t\tmap<sdr, pair<unsigned,unsigned> > dqtstat;\n\t\tfor (unsigned i = 0; i < goodqtb.size(); ++i)\n\t\t\t++dqtstat[sdr(goodqtb[i][t],goodq2tb[i][t])].first;\n\t\tfor (unsigned i = 0; i < badqtb.size(); ++i)\n\t\t\t++dqtstat[sdr(badqtb[i][t],badq2tb[i][t])].second;\n\t\ttypedef map<sdr, pair<unsigned,unsigned> >::const_iterator dqtstatcit;\n\t\tvector<dqtstatcit> goodcits;\n\t\tunsigned goodcnt = 0, badcnt = 0;\t\n\t\tfor (dqtstatcit cit = dqtstat.begin(); cit != dqtstat.end(); ++cit)\n\t\t\tif ((double(cit->second.second)/double(cit->second.first+cit->second.second))<0.6*baseprob) {\n\t\t\t\tgoodcits.push_back(cit);\n\t\t\t\tgoodcnt += cit->second.first;\n\t\t\t\tbadcnt += cit->second.second;\n\t\t\t}\n\t\tif (goodcits.size() && double(goodcnt) > 0.25*double(goodqtb.size()) && goodcits.size()*2 < goodqtb.size()) {\n\t\t\tcout << \"good dQ_\" << t << \" \" << double(badcnt*100)/double(badcnt+goodcnt) << \"% bad #=\" << goodcits.size() << \":\\t\";\n\t\t\tfor (unsigned i = 0; i < goodcits.size(); ++i)\n\t\t\t\tif (double(goodcits[i]->second.first) > 0.01*double(goodqtb.size()))\n\t\t\t\tcout << (goodcits[i]->first) << \"(\" << 100.0*double(goodcits[i]->second.first)/double(goodcnt) << \"%) \";\n\t\t\tcout << endl;\n\t\t}\n\t}\n\tif (1) {\n\t\tmap<sdr, pair<unsigned,unsigned> > dftstat;\n\t\tif (t < 20) {\n\t\t\tfor (unsigned i = 0; i < goodqtb.size(); ++i) {\n\t\t\t\tuint32 F1 = sha1_f1(goodqtb[i][t-1], rotate_left(goodqtb[i][t-2],30), rotate_left(goodqtb[i][t-3],30));\n\t\t\t\tuint32 F2 = sha1_f1(goodq2tb[i][t-1], rotate_left(goodq2tb[i][t-2],30), rotate_left(goodq2tb[i][t-3],30));\n\t\t\t\t++dftstat[sdr(F1,F2)].first;\n\t\t\t}\n\t\t\tfor (unsigned i = 0; i < badqtb.size(); ++i) {\n\t\t\t\tuint32 F1 = sha1_f1(badqtb[i][t-1], rotate_left(badqtb[i][t-2],30), rotate_left(badqtb[i][t-3],30));\n\t\t\t\tuint32 F2 = sha1_f1(badq2tb[i][t-1], rotate_left(badq2tb[i][t-2],30), rotate_left(badq2tb[i][t-3],30));\n\t\t\t\t++dftstat[sdr(F1,F2)].second;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (unsigned i = 0; i < goodqtb.size(); ++i) {\n\t\t\t\tuint32 F1 = sha1_f2(goodqtb[i][t-1], rotate_left(goodqtb[i][t-2],30), rotate_left(goodqtb[i][t-3],30));\n\t\t\t\tuint32 F2 = sha1_f2(goodq2tb[i][t-1], rotate_left(goodq2tb[i][t-2],30), rotate_left(goodq2tb[i][t-3],30));\n\t\t\t\t++dftstat[sdr(F1,F2)].first;\n\t\t\t}\n\t\t\tfor (unsigned i = 0; i < badqtb.size(); ++i) {\n\t\t\t\tuint32 F1 = sha1_f2(badqtb[i][t-1], rotate_left(badqtb[i][t-2],30), rotate_left(badqtb[i][t-3],30));\n\t\t\t\tuint32 F2 = sha1_f2(badq2tb[i][t-1], rotate_left(badq2tb[i][t-2],30), rotate_left(badq2tb[i][t-3],30));\n\t\t\t\t++dftstat[sdr(F1,F2)].second;\n\t\t\t}\n\t\t}\n\t\ttypedef map<sdr, pair<unsigned,unsigned> >::const_iterator dftstatcit;\n\t\tvector<dftstatcit> goodcits;\n\t\tunsigned goodcnt = 0, badcnt = 0;\t\n\t\tfor (dftstatcit cit = dftstat.begin(); cit != dftstat.end(); ++cit)\n\t\t\tif ((double(cit->second.second)/double(cit->second.first+cit->second.second))<0.6*baseprob) {\n\t\t\t\tgoodcits.push_back(cit);\n\t\t\t\tgoodcnt += cit->second.first;\n\t\t\t\tbadcnt += cit->second.second;\n\t\t\t}\n\t\tif (goodcits.size() && double(goodcnt) > 0.25*double(goodqtb.size()) && goodcits.size()*2 < goodqtb.size()) {\n\t\t\tcout << \"good dF_\" << t << \" \" << double(badcnt*100)/double(badcnt+goodcnt) << \"% bad #=\" << goodcits.size() << \":\\t\";\n\t\t\tfor (unsigned i = 0; i < goodcits.size(); ++i)\n\t\t\t\tif (double(goodcits[i]->second.first) > 0.01*double(goodqtb.size()))\n\t\t\t\tcout << (goodcits[i]->first) << \"(\" << 100.0*double(goodcits[i]->second.first)/double(goodcnt) << \"%) \";\n\t\t\tcout << endl;\n\t\t}\n\t}\n}\n\nunsigned analyze_bc_tunnel(const sha1differentialpath& tunnel)\n{\n#define ATLC_TEST_COUNT (1<<18) // 16\n#define ATLC_MIN_PROB 0\n#define ATLC_MIN_COUNT (ATLC_TEST_COUNT>>ATLC_MIN_PROB)\n\tunsigned tend = analyze_tunnel(tunnel, false, mainparameters.changebitstat);\n\tmemset(m, 0, sizeof(uint32)*16);\n\tfor (int i = 0; i < 16; ++i)\n\t\tif (i >= tunnel.tbegin() && i < tunnel.tend())\n\t\t\tm[i] = tunnel.getme(i).mask;\n\tfor (unsigned i = 16; i < 32; ++i)\n\t\tm[i]=rotate_left(m[i-3] ^ m[i-8] ^ m[i-14] ^ m[i-16], 1);\n//\tif (tend < 21)\n//\t\treturn tend;\n\tshow_path(tunnel);\n\tcout << tend << endl;\n\tvector< vector<uint32> > dmes(80);\n\tunsigned tend2 = tend;\n\tuint64 mcnt = 1;\n\tfor (unsigned i = 16; i < tend; ++i) {\n\t\tsdr tmp;\n\t\ttmp.mask = m[i];\n\t\ttmp.sign = 0;\n\t\tdo {\n\t\t\tdmes[i].push_back(tmp.adddiff());\n\t\t\ttmp.sign += ~tmp.mask + 1;\n\t\t\ttmp.sign &= tmp.mask;\n\t\t} while (tmp.sign != 0);\n\t\tsort(dmes[i].begin(), dmes[i].end());\n\t\tdmes[i].erase( unique(dmes[i].begin(),dmes[i].end()), dmes[i].end());\n\t\tif ((mcnt * dmes[i].size()) > (1<<6)) {\n\t\t\t// don't let mcnt grow too big\n\t\t\ttend2 = i;\n\t\t\tbreak;\n\t\t}\n\t\tmcnt *= uint64(dmes[i].size());\n\t}\t\n\tcout << mcnt << endl;\n\tuint32 qmask[80];\n\tfor (unsigned t = 0; t < 40; ++t)\n\t\tqmask[t] = maindiffpath[t].mask();\n\n\tfor (unsigned mi = 0; mi < mcnt; ++mi) {\n\t\tvector< vector<uint32> > goodqtb, badqtb, goodq2tb, badq2tb;\n\t\tvector<unsigned> dmesindex(80,0);\n\t\tunsigned mi2 = mi;\n\t\tcout << mi << \": \";\n\t\tfor (unsigned i = 16; i < tend2; ++i)\t\t\n\t\t\tif (dmes[i].size() > 1) {\n\t\t\t\tdmesindex[i] = mi2 % dmes[i].size();\n\t\t\t\tmi2 /= dmes[i].size();\n\t\t\t\tcout << i << naf(dmes[i][dmesindex[i]]);\n\t\t\t}\n\t\tcout << \": \";\n\t\tsha1differentialpath diffpath = tunnel;\n\t\tdiffpath.get(-4);\n\t\tdiffpath.get(80);\n\t\tfill_tables(diffpath);\n\t\tfor (unsigned k = 0; k < ATLC_TEST_COUNT; ++k) {\n\t\t\tint t = -4;\n\t\t\twhile (t < 17) {\n\t\t\t\tbool ok = false;\n\t\t\t\tfor (unsigned j = 0; j < 3; ++j) {\n\t\t\t\t\tQ[offset+t] = (xrng128()&~Qvaluemask[offset+t]) ^ Qvalue[offset+t];\n\t\t\t\t\tif (t > -4)\n\t\t\t\t\t\tQ[offset+t] ^= Qprev[offset+t]&Q[offset+t-1];\n\t\t\t\t\tif (t > -3)\n\t\t\t\t\t\tQ[offset+t] ^= Qprev2[offset+t]&Q[offset+t-2];\n\t\t\t\t\tQ2[offset+t] = Q[offset+t] + dQ[offset+t];\n\t\t\t\t\tif (t >= 1) {\n\t\t\t\t\t\tm[t-1] = Q[offset+t] - (\n\t\t\t\t\t\t\tsha1_f1(Q[offset+t-2], rotate_left(Q[offset+t-3],30), rotate_left(Q[offset+t-4],30)) + sha1_ac[0] + rotate_left(Q[offset+t-1],5) + rotate_left(Q[offset+t-5],30)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tm2[t-1] = Q2[offset+t] - (\n\t\t\t\t\t\t\tsha1_f1(Q2[offset+t-2], rotate_left(Q2[offset+t-3],30), rotate_left(Q2[offset+t-4],30)) + sha1_ac[0] + rotate_left(Q2[offset+t-1],5) + rotate_left(Q2[offset+t-5],30)\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tif ((m2[t-1]^m[t-1]) == diffpath.getme(t-1).mask) {\n\t\t\t\t\t\t\tok = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else\n\t\t\t\t\t\tok = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (ok)\n\t\t\t\t\t++t;\n\t\t\t\telse\n\t\t\t\t\tt -= 4;\n\t\t\t\tif (t < -4) throw std::runtime_error(\"t < -4\");\n\t\t\t}\n\t\t\tfor (unsigned i = 16; i < 26; ++i) {\n\t\t\t\tm[i]=rotate_left(m[i-3] ^ m[i-8] ^ m[i-14] ^ m[i-16], 1);\n\t\t\t\tif (i < tend2)\n\t\t\t\t\tm2[i] = m[i] + dmes[i][dmesindex[i]];\n\t\t\t\telse\n\t\t\t\t\tm2[i]=rotate_left(m2[i-3] ^ m2[i-8] ^ m2[i-14] ^ m2[i-16], 1);\n\t\t\t}\n\t\t\tfor (int t = 16; t < 20; ++t) {\n\t\t\t\tsha1_step_round1(t, Q, m);\n\t\t\t\tsha1_step_round1(t, Q2, m2);\n\t\t\t}\n\t\t\tfor (int t = 20; t < 26; ++t) {\n\t\t\t\tsha1_step_round2(t, Q, m);\n\t\t\t\tsha1_step_round2(t, Q2, m2);\n\t\t\t}\n\t\t\tfor (int t = 17; t < 27; ++t) {\n\t\t\t\tif ((Q2[offset+t]^Q[offset+t])&(qmask[t]|0x00000000)) {\n\t\t\t\t\tstatic vector<uint32> tmpqtb(27);\n\t\t\t\t\tfor (int t1 = 0; t1 < tmpqtb.size(); ++t1)\n\t\t\t\t\t\ttmpqtb[t1] = Q[4+t1];\n\t\t\t\t\tif (t <= tend)\n\t\t\t\t\t\tbadqtb.push_back(tmpqtb);\n\t\t\t\t\telse\n\t\t\t\t\t\tgoodqtb.push_back(tmpqtb);\n\t\t\t\t\tfor (int t1 = 0; t1 < tmpqtb.size(); ++t1)\n\t\t\t\t\t\ttmpqtb[t1] = Q2[4+t1];\n\t\t\t\t\tif (t <= tend)\n\t\t\t\t\t\tbadq2tb.push_back(tmpqtb);\n\t\t\t\t\telse\n\t\t\t\t\t\tgoodq2tb.push_back(tmpqtb);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcout << goodqtb.size() << \" vs \" << badqtb.size() << \": \" << (double(100)*double(badqtb.size()))/double(goodqtb.size()+badqtb.size()) << \"% bad\" << endl;\n\t\tfor (unsigned t = 16-4; t < tend; ++t)\n\t\t\tfor (unsigned b = 0; b < 32; ++b) {\n\t\t\t\tstat_ana(goodqtb, badqtb, goodq2tb, badq2tb, t, b);\n\t\t\t}\n\t}\n\treturn tend;\n}\n\n\n\n\n\nvoid find_best_tunnel(vector< sha1differentialpath >& tunnels, const sha1differentialpath& mypath, const vector< vector<uint32> >& bitrels, bool force_lc = false) \n{\n//#define ADD_ME_CARRIES 0\n\tunsigned ADD_ME_CARRIES = mainparameters.mecarry;\n\tif (mainparameters.tunnelfilterbitcondition)\n\t\tfilter_tunnels_bitconditions(tunnels, mypath);\n\tstatic vector<sdr> sdrsvec[16];\n\tsdr metbu;\n\tstatic vector<unsigned> iQvec, ncvec;\n\tiQvec.assign(tunnels.size(),0);\n\tncvec.assign(tunnels.size(),1<<20);\n//\tcout << tunnels.size() << endl;\n\tfor (unsigned i = 0; i < tunnels.size(); ++i) {\n\t\tuint64 cnt = 1;\n\t\tfor (int t = 0; t < 16; ++t) {\n\t\t\tsdrsvec[t].clear();\n\t\t\tif (t < tunnels[i].tbegin() || t >= tunnels[i].tend()) continue;\n\t\t\tmetbu = tunnels[i].getme(t);\n\t\t\ttable_sdrs(sdrsvec[t], metbu.adddiff(), hw(metbu.mask)+ADD_ME_CARRIES);\n\t\t\tunsigned j = 0;\n\t\t\twhile (j < sdrsvec[t].size()) {\n\t\t\t\tif (sdrsvec[t][j].get(31) == -1) {\n\t\t\t\t\tswap(sdrsvec[t][j], sdrsvec[t][sdrsvec[t].size()-1]);\n\t\t\t\t\tsdrsvec[t].pop_back();\n\t\t\t\t} else\n\t\t\t\t\t++j;\n\t\t\t}\n\t\t\tcnt *= sdrsvec[t].size();\n\t\t}\n\t\tif (cnt == 0)\n\t\t\tthrow std::runtime_error(\"cnt == 0 ??\");\n\t\tunsigned bestiQ = 0, bestnc = 1<<20;\n\t\tuint64 bestc = cnt;\n\t\tunsigned basenc = tunnels[i].nrcond();\n\t\tfor (uint64 c = 0; c < cnt; ++c) {\n\t\t\tuint64 cc = c;\n\t\t\tfor (int t = 0; t < 16; ++t) {\n\t\t\t\tif (sdrsvec[t].size()>1) {\n\t\t\t\t\tuint64 k = cc % sdrsvec[t].size();\n\t\t\t\t\tcc /= sdrsvec[t].size();\n\t\t\t\t\ttunnels[i].getme(t) = sdrsvec[t][k];\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!filter_tunnel_bitrelations(tunnels[i],bitrels)) continue;\n\t\t\tunsigned iQ;\n\t\t\tif (force_lc)\n\t\t\t\tiQ = analyze_bc_tunnel(tunnels[i]);\n\t\t\telse\n\t\t\t\tiQ = analyze_tunnel(tunnels[i], false, mainparameters.changebitstat);\n\t\t\tif (iQ < bestiQ) continue;\n\t\t\tif (iQ > bestiQ) {\n\t\t\t\tbestiQ = iQ;\n\t\t\t\tbestnc = 1<<20;\n\t\t\t\tbestc = c;\n\t\t\t}\n\t\t\tunsigned nc = basenc;\n\t\t\tfor (int t = tunnels[i].tbegin(); t < tunnels[i].tend(); ++t)\n\t\t\t\tnc += hw(tunnels[i].getme(t).mask&0x7FFFFFFF);\n//\t\t\tif (nc >= 15) continue;\n\t\t\tif (nc < bestnc) {\n\t\t\t\tbestnc = nc;\n\t\t\t\tbestc = c;\n\t\t\t}\n\t\t}\n\t\tif (bestc == cnt) {\n\t\t\ttunnels[i].clear();\n\t\t\tcontinue;\n\t\t}\n\t\tuint64 cc = bestc;\n\t\tfor (int t = 0; t < 16; ++t) {\n\t\t\tif (sdrsvec[t].size()) {\n\t\t\t\tuint64 k = cc % sdrsvec[t].size();\n\t\t\t\tcc /= sdrsvec[t].size();\n\t\t\t\ttunnels[i].getme(t) = sdrsvec[t][k];\n\t\t\t}\n\t\t}\n\t\tiQvec[i] = bestiQ;\n\t\tncvec[i] = bestnc;\n//\t\tif (bestiQ >= 23) break;\n\t}\n\tunsigned bestiQ = 0, bestnc = 1<<20, besti = tunnels.size(), minnc = 1<<20;\n\tfor (unsigned i = 0; i < tunnels.size(); ++i) {\n\t\tif (tunnels[i].path.size()) {\n\t\t\tif (iQvec[i] > bestiQ) {\n\t\t\t\tbestiQ = iQvec[i];\n\t\t\t\tbestnc = ncvec[i];\n\t\t\t\tbesti = i;\n\t\t\t} else if (iQvec[i] == bestiQ && ncvec[i] < bestnc) {\n\t\t\t\tbestnc = ncvec[i];\n\t\t\t\tbesti = i;\n\t\t\t}\n\t\t\tif (ncvec[i] < minnc)\n\t\t\t\tminnc = ncvec[i];\n\t\t}\n\t}\n\tif (besti < tunnels.size()) {\n//\t\tif (bestiQ >= 21)\n\t\t\tcout << endl << bestiQ << \"(\" << bestnc << \",\" << minnc << \") \" << flush;\n\t\tif (bestiQ >= 16) { //21\n\t\t\t//show_path(tunnels[besti]);\n#if 0\n\t\t\tanalyze_tunnel(tunnels[besti], false, true);\n#else\n\t\t\tfor (unsigned j = 0; j < tunnels.size(); ++j)\n\t\t\t\tif (iQvec[j] == iQvec[besti])\n\t\t\t\t\tanalyze_tunnel(tunnels[j], false, true);\n#endif\n\t\t} \n\t\tsha1differentialpath bestpath;\n\t\tbestpath.swap(tunnels[besti]);\n\t\ttunnels.resize(1);\n\t\tbestpath.swap(tunnels[0]);\n\t\t\n\t\tif (bestiQ < 19) tunnels.clear();\n\t\t\n\t} else\n\t\ttunnels.clear();\n}\n\nvoid create_tunnel_stept(vector< sha1differentialpath >& tunnels, sha1differentialpath& tunnel, int t, bool force_lc = false)\n{\n\tif (t >= 0 && t+1 >= tunnel.tend()) {\n\t\tcreate_tunnel_stept(tunnels, tunnel, t-1, force_lc);\n\t\treturn;\n\t}\n\n\tif (t-4 < tunnel.tbegin() || t < 0) {\n\t\ttunnels.push_back(tunnel);\n\t\treturn;\n\t}\n\tif (tunnel[t-1].diff() == 0 && tunnel[t-2].diff() == 0 && tunnel[t-3].diff() == 0) {\n\t\t// dFt = 0\n\t\tuint32 dme = tunnel[t+1].diff() - tunnel[t].getsdr().rotate_left(5).adddiff() - tunnel[t-4].getsdr().rotate_left(30).adddiff();\n\t\ttunnel.getme(t) = naf(dme);\n\t\tcreate_tunnel_stept(tunnels, tunnel, t-1, force_lc);\n\t\treturn;\n\t}\n\n\tbf_conditions newconditions[32][2];\n\tbool bitactive[32];\n\tunsigned cnt = 1;\n\tfor (unsigned b = 0; b < 32; ++b) {\n\t\tbitactive[b] = false;\n\t\t//sha1_f1(Q[offset+t-1], rotate_left(Q[offset+t-2],30), rotate_left(Q[offset+t-3],30))\n\t\tbf_outcome bo = SHA1_F1_data.outcome(tunnel(t-1,b), tunnel(t-2,(b+2)&31), tunnel(t-3,(b+2)&31));\n\t\tif (bo.size() == 0) throw std::runtime_error(\"bo.size() == 0\");\n\t\tif (bo.size() == 1) continue;\n\t\tif (bo.size() == 2) {\n\t\t\tif (/*b == 31 &&*/ bo[0] != bc_constant && bo[1] != bc_constant)\n\t\t\t\tcontinue;\n\t\t\tif (force_lc) {\n\t\t\t\tbf_conditions bf;\n\t\t\t\tif (bo[0] != bc_constant)\n\t\t\t\t\tbf = SHA1_F1_data.backwardconditions( tunnel(t-1,b), tunnel(t-2,(b+2)&31), tunnel(t-3,(b+2)&31), bo[0] );\n\t\t\t\telse\n\t\t\t\t\tbf = SHA1_F1_data.backwardconditions( tunnel(t-1,b), tunnel(t-2,(b+2)&31), tunnel(t-3,(b+2)&31), bo[1] );\n\t\t\t\ttunnel.setbitcondition(t-1,b,bf.first);\n\t\t\t\ttunnel.setbitcondition(t-2,(b+2)&31,bf.second);\n\t\t\t\ttunnel.setbitcondition(t-3,(b+2)&31,bf.third);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnewconditions[b][0] = SHA1_F1_data.backwardconditions( tunnel(t-1,b), tunnel(t-2,(b+2)&31), tunnel(t-3,(b+2)&31), bo[0]);\n\t\t\tnewconditions[b][1] = SHA1_F1_data.backwardconditions( tunnel(t-1,b), tunnel(t-2,(b+2)&31), tunnel(t-3,(b+2)&31), bo[1]);\n\t\t\tcnt *= 2;\n\t\t\tbitactive[b] = true;\n\t\t} else { // bo.size() == 3\n\t\t\tbf_conditions bf = SHA1_F1_data.backwardconditions( tunnel(t-1,b), tunnel(t-2,(b+2)&31), tunnel(t-3,(b+2)&31), bc_constant );\n#if 1\n\t\t\tif (mainparameters.simpletunnels) {\n\t\t\t\ttunnel.setbitcondition(t-1,b,bf.first);\n\t\t\t\ttunnel.setbitcondition(t-2,(b+2)&31,bf.second);\n\t\t\t\ttunnel.setbitcondition(t-3,(b+2)&31,bf.third);\n\t\t\t\tcontinue;\n\t\t\t}\n#endif\n\t\t\tif (force_lc) {\n\t\t\t\ttunnel.setbitcondition(t-1,b,bf.first);\n\t\t\t\ttunnel.setbitcondition(t-2,(b+2)&31,bc_prevn);\n\t\t\t\ttunnel.setbitcondition(t-3,(b+2)&31,bf.third);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (bf.second != bc_prev) throw std::runtime_error(\"bf.second != bc_prev\");\n\t\t\tnewconditions[b][0] = bf;\n\t\t\tbf.second = bc_prevn;\n\t\t\tnewconditions[b][1] = bf;\n\t\t\tcnt *= 2;\n\t\t\tbitactive[b] = true;\n\t\t}\n\t}\n\tfor (unsigned c = 0; c < cnt; ++c) {\n\t\tunsigned cc = c;\n\t\tuint32 dFt = 0;\n\t\tfor (unsigned b = 0; b < 32; ++b) {\n\t\t\tif (bitactive[b]) {\n\t\t\t\tunsigned k = cc % 2;\n\t\t\t\tcc /= 2;\n\t\t\t\ttunnel.setbitcondition(t-1,b,newconditions[b][k].first);\n\t\t\t\ttunnel.setbitcondition(t-2,((b+2)&31),newconditions[b][k].second);\n\t\t\t\ttunnel.setbitcondition(t-3,((b+2)&31),newconditions[b][k].third);\n\t\t\t}\n\t\t\tdFt += SHA1_F1_data.outcome(tunnel(t-1,b), tunnel(t-2,(b+2)&31), tunnel(t-3,(b+2)&31))(0,b);\n\t\t}\n\n\t\tuint32 dme = tunnel[t+1].diff() - dFt - tunnel[t].getsdr().rotate_left(5).adddiff() - tunnel[t-4].getsdr().rotate_left(30).adddiff();\n\t\ttunnel.getme(t) = naf(dme);\n\t\tcreate_tunnel_stept(tunnels, tunnel, t-1, force_lc);\n\t}\n}\n\nvoid analyze_tunnels_diffpath(const sha1differentialpath& mypath, const vector< vector<uint32> >& bitrels, vector<sha1differentialpath> tunnelsin)\n{\n\tcout << \"Analyzing tunnels for differential path:\" << endl;\n\tsha1differentialpath path = mypath;\n\tcleanup_path(path);\n\tshow_path(path);\n\tmaindiffpath = path;\n\tcout << \"Message space determined by \" << bitrels.size() << \" bitrelations.\" << endl;\n\n\tbool deep_analysis = mainparameters.tunneldeepanalysis;\n\t\n\tif (tunnelsin.size()) {\n\t\tvector<sha1differentialpath> tunnelstmp;\n\t\tfor (unsigned i = 0; i < tunnelsin.size(); ++i)\n\t\t\tcreate_tunnel_stept(tunnelstmp, tunnelsin[i], 15);\n\t\tfind_best_tunnel(tunnelstmp, path, bitrels, deep_analysis);\t\n\t\treturn;\n\t}\n\n\tsha1differentialpath tunnelpath;\n\tvector< sha1differentialpath > tunnels, tunnelstmp, tunnelstmp2;\n\n\tcout << \"Generating tunnels...\" << endl;\n\tset<int> goodbits;\n\tset< pair<int,int> > good2bits;\n#if 1\n\tfor (int bit1 = 0; bit1 < 16*32; ++bit1) {\n\t\tint t1 = bit1 / 32;\n\t\tint b1 = bit1 % 32;\n\t\ttunnelpath.clear();\n\t\ttunnelpath.get(t1-4);\n\t\tif (t1 + 6 < 16)\n\t\t\ttunnelpath.get(t1+6);\n\t\telse\n\t\t\ttunnelpath.get(16);\n\t\ttunnelpath.setbitcondition(t1+1,b1,bc_plus);\n\t\ttunnelstmp.clear();\n\t\tcreate_tunnel_stept(tunnelstmp, tunnelpath, 15);\n\t\tfind_best_tunnel(tunnelstmp, path, bitrels, deep_analysis);\n\t\tif (tunnelstmp.size()) {\n\t\t\tgoodbits.insert(bit1);\n\t\t\tcontinue;\n\t\t}\n\t}\n#if 1\n\tfor (int bit1 = 0; bit1 < 16*32; ++bit1) {\n\t\tfor (int bit2 = bit1+1; bit2 < 16*32; ++bit2) {\n\t\t\tif (goodbits.find(bit1) != goodbits.end()) continue;\n\t\t\tif (goodbits.find(bit2) != goodbits.end()) continue;\n\t\t\tint t1 = bit1 / 32;\n\t\t\tint b1 = bit1 % 32;\n\t\t\tint t2 = bit2/32;\n\t\t\tint b2 = bit2%32;\n\t\t\ttunnelpath.clear();\n\t\t\ttunnelpath.get(t1-4);\n\t\t\tif (t2 + 6 < 16)\n\t\t\t\ttunnelpath.get(t2+6);\n\t\t\telse\n\t\t\t\ttunnelpath.get(16);\n\t\t\ttunnelpath.setbitcondition(t1+1,b1,bc_plus);\n\t\t\ttunnelpath.setbitcondition(t2+1,b2,bc_plus);\n\t\t\ttunnelstmp.clear();\n\t\t\tcreate_tunnel_stept(tunnelstmp, tunnelpath, 15);\n\t\t\tfind_best_tunnel(tunnelstmp, path, bitrels, deep_analysis);\n\t\t\tif (tunnelstmp.size())\n\t\t\t\tgood2bits.insert(pair<int,int>(bit1,bit2));\n\t\t}\n\t}\n#endif\n//\texit(0);\n#endif\n\tfor (int bit1 = 16*32-1; bit1 >= 0; --bit1) {\n//\tfor (int bit1 = 169; bit1 < 16*32; ++bit1) {\n\t\tcout << \"[\" << bit1 << \"] \" << flush;\n\t\tfor (int bit2 = bit1; bit2 < 16*32; ++bit2) {\n\t\t\tfor (int bit2sign = 0; bit2sign < 1; ++bit2sign)\n\t\t\tfor (int bit3 = bit2; bit3 < 16*32; ++bit3)\n\t\t\tfor (int bit3sign = 0; bit3sign < 1; ++bit3sign)\n\t\t\t{\n\t\t\t\t//if (bit2 != bit1 || bit3 != bit1) continue; // force single bit difference\n\t\t\t\tif (!mainparameters.threebittunnels && bit3 != bit2) continue; // force max 2 bit difference\n\t\t\t\tif (bit1 == bit2 && bit2sign == 1) continue;\n\t\t\t\tif (bit3 == bit2 && bit3sign != bit2sign) continue;\n\t\t\t\tif (bit1 == bit2 && bit3 > bit2) continue;\n\t\t\t\tif (goodbits.find(bit1) != goodbits.end()) continue;\n\t\t\t\tif (goodbits.find(bit2) != goodbits.end()) continue;\n\t\t\t\tif (goodbits.find(bit3) != goodbits.end()) continue;\n\t\t\t\tif (good2bits.find(pair<int,int>(bit1,bit2)) != good2bits.end()) continue;\n\t\t\t\tif (good2bits.find(pair<int,int>(bit1,bit3)) != good2bits.end()) continue;\n\t\t\t\tif (good2bits.find(pair<int,int>(bit2,bit3)) != good2bits.end()) continue;\n\t\t\t\t\n\t\t\t\t//cout << \"[\" << bit1 << \",\" << bit2 << \"] \" << flush;\n\t\t\t\tint t1 = bit1 / 32;\n\t\t\t\tint b1 = bit1 % 32;\n\t\t\t\tint t2 = bit2 / 32;\n\t\t\t\tint b2 = bit2 % 32;\n\t\t\t\tint t3 = bit3 / 32;\n\t\t\t\tint b3 = bit3 % 32;\n\t\t\t\ttunnelpath.clear();\n\t\t\t\ttunnelpath.get(t1-4);\n\t\t\t\tif (t3 + 6 < 16)\n\t\t\t\t\ttunnelpath.get(t3+6);\n\t\t\t\telse\n\t\t\t\t\ttunnelpath.get(16);\n\t\t\t\ttunnelpath.setbitcondition(t1+1,b1,bc_plus);\n\t\t\t\tif (bit2sign == 0)\n\t\t\t\t\ttunnelpath.setbitcondition(t2+1,b2,bc_plus);\n\t\t\t\telse\n\t\t\t\t\ttunnelpath.setbitcondition(t2+1,b2,bc_minus);\n\t\t\t\tif (bit3sign == 0)\n\t\t\t\t\ttunnelpath.setbitcondition(t3+1,b3,bc_plus);\n\t\t\t\telse\n\t\t\t\t\ttunnelpath.setbitcondition(t3+1,b3,bc_minus);\n\t\t\t\ttunnelstmp.clear();\n\t\t\t\tcreate_tunnel_stept(tunnelstmp, tunnelpath, 15);\n\t\t\t\tfind_best_tunnel(tunnelstmp, path, bitrels, deep_analysis);\n\t\t\t}\n\t\t}\n\t}\n\texit(0);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nstruct ihv_type {\n\tuint32 ihv[5];\n\tbool operator<(const ihv_type& r) const {\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tif (ihv[i] < r.ihv[i]) return true;\n\t\t\tif (ihv[i] > r.ihv[i]) return false;\n\t\t}\n\t\tif (ihv[4] < r.ihv[4]) return true;\n\t\treturn false;\n\t}\n\tbool operator==(const ihv_type& r) const {\n\t\tfor (int i = 0; i < 5; ++i)\n\t\t\tif (ihv[i] != r.ihv[i]) return false;\n\t\treturn true;\n\t}\n};\n\nvoid analyze_indepsection_prob()\n{\n\tvector< vector< vector<uint32> > > pathbitrelationsmatrix;\n\tmespace_to_pathbitrelationsmatrix(mainmespace, pathbitrelationsmatrix);\n\tsha1differentialpath path = maindiffpath;\n\tint tbegin = 16;\n\tfor (; tbegin < 80; ++tbegin)\n\t\tif (0 == (path[tbegin].diff() | path[tbegin-1].diff() | path[tbegin-2].diff() | path[tbegin-3].diff() | path[tbegin-4].diff()))\n\t\t\tbreak;\n\twhile (tbegin < 80) {\n\t\tint tend = tbegin+1;\n\t\tfor (; tend < 80; ++tend)\n\t\t\tif (0 == (path[tend].diff() | path[tend-1].diff() | path[tend-2].diff() | path[tend-3].diff() | path[tend-4].diff()))\n\t\t\t\tbreak;\n\t\tif (0 != (path[tend].diff() | path[tend-1].diff() | path[tend-2].diff() | path[tend-3].diff() | path[tend-4].diff()))\n\t\t\tbreak;\n\t\tif (tend == tbegin+1) {\n\t\t\ttbegin = tend;\n\t\t\tcontinue;\n\t\t}\n\t\tcout << \"Prob t=[\" << tbegin << \"-\" << tend << \"): \\t\" << flush;\n#if 0\n\t\ttbegin = tend; cout << endl; continue;\n#endif\n\t\tuint64 cnt = 0;\n\t\tuint32 okcnt = 0;\n\t\twhile (okcnt < (1<<15)) {\n\t\t\t++cnt; if (hw(cnt)==1) cout << cnt << \" \" << flush;\n\t\t\trandom_me(m, pathbitrelationsmatrix);\n\t\t\tfor (int t = 0; t < 16; ++t)\n\t\t\t\tm2[t] = m[t] ^ path.getme(t).mask;\n\t\t\tfor (int t = 16; t < 80; ++t)\n\t\t\t\tm2[t]=rotate_left(m2[t-3] ^ m2[t-8] ^ m2[t-14] ^ m2[t-16], 1);\n\t\t\tfor (int t = tbegin-4; t <= tbegin; ++t)\n\t\t\t\tQ2[offset+t] = Q[offset+t] = xrng64();\n\t\t\tfor (int t = tbegin; t < tend; ++t) {\n\t\t\t\tsha1_step(t, Q, m);\n\t\t\t\tsha1_step(t, Q2, m2);\n\t\t\t}\n\t\t\tbool ok = true;\n\t\t\tfor (int t = tend-4; t <= tend; ++t)\n\t\t\t\tif (Q2[offset+t] != Q[offset+t]) {\n\t\t\t\t\tok = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tif (ok)\n\t\t\t\tif (hw(++okcnt)==1) cout << \"[\" << okcnt << \"] \" << flush;\n\t\t}\n\t\tcout << \" prob=\" << log(double(okcnt)/double(cnt))/log(2.0) << endl;\n\t\t\n\t\ttbegin = tend;\n\t}\t\t\n\tcout << \"Prob t=[\" << tbegin << \"-\" << 80 << \"):\" << endl;\n\tvector<ihv_type> target_dihvs(20);\n\tvector<ihv_type> dihvs(1<<28);\n\tprogress_display pd(dihvs.size());\n\tfor (unsigned i = 0; i < dihvs.size(); ++i,++pd) {\n\t\trandom_me(m, pathbitrelationsmatrix);\n\t\tfor (int t = 0; t < 16; ++t)\n\t\t\tm2[t] = m[t] ^ path.getme(t).mask;\n\t\tfor (int t = 16; t < 80; ++t)\n\t\t\tm2[t]=rotate_left(m2[t-3] ^ m2[t-8] ^ m2[t-14] ^ m2[t-16], 1);\n\t\tfor (int t = tbegin-4; t <= tbegin; ++t)\n\t\t\tQ2[offset+t] = Q[offset+t] = xrng64();\n\t\tfor (int t = -4; t <= 0; ++t)\n\t\t\tQ2[offset+t] = Q[offset+t] = xrng64();\n\t\tfor (int t = tbegin; t < 80; ++t) {\n\t\t\tsha1_step(t, Q, m);\n\t\t\tsha1_step(t, Q2, m2);\n\t\t}\n\t\tdihvs[i].ihv[0] = rotate_left(Q2[offset+80-4],30)-rotate_left(Q[offset+80-4],30);\n\t\tdihvs[i].ihv[1] = rotate_left(Q2[offset+80-3],30)-rotate_left(Q[offset+80-3],30);\n\t\tdihvs[i].ihv[2] = rotate_left(Q2[offset+80-2],30)-rotate_left(Q[offset+80-2],30);\n\t\tdihvs[i].ihv[3] = Q2[offset+80-1]-Q[offset+80-1];\n\t\tdihvs[i].ihv[4] = Q2[offset+80]-Q[offset+80];\n\t}\n\tsort(dihvs.begin(), dihvs.end());\n\tunsigned i = 0;\n\tvector<unsigned> bestcnts;\n\twhile (i < dihvs.size()) {\n\t\tunsigned j = i+1;\n\t\twhile (j < dihvs.size() && dihvs[j] == dihvs[i]) ++j;\n\t\tbestcnts.push_back(j-i);\n\t\ti = j;\n\t}\n\tcout << \"Prob t=[\" << tbegin << \"-\" << 80 << \"): \" << flush;\n\tsort(bestcnts.begin(),bestcnts.end());\n\tunsigned bestcnt = bestcnts[bestcnts.size()-1];\n#if 1\n\ttarget_dihvs.clear();\n\ti = 0;\n\twhile (i < dihvs.size()) {\n\t\tunsigned j = i+1;\n\t\twhile (j < dihvs.size() && dihvs[j] == dihvs[i]) ++j;\n\t\tif ((j-i)*2 >= bestcnt) {\n\t\t\tcout << \"\\tprob=\" << log(double(j-i)/double(dihvs.size()))/log(2.0) << \":\\t\";\n\t\t\tfor (unsigned k = 0; k < 5; ++k)\n\t\t\t\tcout << naf(dihvs[i].ihv[k]) << \" \";\n\t\t\tcout << endl;\n\t\t\ttarget_dihvs.push_back(dihvs[i]);\n\t\t}\n\t\ti = j;\n\t}\n\t{ vector<ihv_type> tmptmp(1); dihvs.swap(tmptmp); } // free memory\n\tuint64 cnt = 0, okcnt = 0;\n\tihv_type dihv;\n\twhile (true) {\n\t\trandom_me(m, pathbitrelationsmatrix);\n\t\tfor (int t = 0; t < 16; ++t)\n\t\t\tm2[t] = m[t] ^ path.getme(t).mask;\n\t\tfor (int t = 16; t < 80; ++t)\n\t\t\tm2[t]=rotate_left(m2[t-3] ^ m2[t-8] ^ m2[t-14] ^ m2[t-16], 1);\n\t\tfor (int t = tbegin-4; t <= tbegin; ++t)\n\t\t\tQ2[offset+t] = Q[offset+t] = xrng64();\n\t\tfor (int t = -4; t <= 0; ++t)\n\t\t\tQ2[offset+t] = Q[offset+t] = xrng64();\n\t\tfor (int t = tbegin; t < 80; ++t) {\n\t\t\tsha1_step(t, Q, m);\n\t\t\tsha1_step(t, Q2, m2);\n\t\t}\n\t\tdihv.ihv[0] = rotate_left(Q2[offset+80-4],30)-rotate_left(Q[offset+80-4],30);\n\t\tdihv.ihv[1] = rotate_left(Q2[offset+80-3],30)-rotate_left(Q[offset+80-3],30);\n\t\tdihv.ihv[2] = rotate_left(Q2[offset+80-2],30)-rotate_left(Q[offset+80-2],30);\n\t\tdihv.ihv[3] = Q2[offset+80-1]-Q[offset+80-1];\n\t\tdihv.ihv[4] = Q2[offset+80]-Q[offset+80];\n\t\t++cnt;\n\t\tfor (unsigned k = 0; k < target_dihvs.size(); ++k)\n\t\t\tif (dihv == target_dihvs[k]) {\n\t\t\t\t++okcnt;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tif (hw(cnt)+hw(cnt>>32)==1 && okcnt > 1) {\n\t\t\tcout << \"[\" << cnt << \":p=\" << log(double(okcnt)/double(cnt))/log(2.0) << \"]\" << flush;\n\t\t}\n\t}\n#else\t\n\tfor (unsigned i = 0; i < bestcnts.size(); ++i)\n\t\tif (bestcnts[i]*2 >= bestcnt)\n\t\t\tcout << \" prob=\" << log(double(bestcnts[i])/double(dihvs.size()))/log(2.0) << flush;\n#endif\n\tcout << endl;\n\texit(0);\n}\n", "meta": {"hexsha": "89cb9aa8b3b5b51733c412967573f72c89bcf9f8", "size": 31559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sha1attackgenerator/tunnel_analysis.cpp", "max_stars_repo_name": "killua4564/hashclash", "max_stars_repo_head_hexsha": "f780f17ef579e4bb246f5c47f31765f665dab74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 398.0, "max_stars_repo_stars_event_min_datetime": "2017-10-16T19:46:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T23:45:05.000Z", "max_issues_repo_path": "src/sha1attackgenerator/tunnel_analysis.cpp", "max_issues_repo_name": "killua4564/hashclash", "max_issues_repo_head_hexsha": "f780f17ef579e4bb246f5c47f31765f665dab74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2019-10-23T08:14:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-10T09:33:44.000Z", "max_forks_repo_path": "src/sha1attackgenerator/tunnel_analysis.cpp", "max_forks_repo_name": "killua4564/hashclash", "max_forks_repo_head_hexsha": "f780f17ef579e4bb246f5c47f31765f665dab74f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 72.0, "max_forks_repo_forks_event_min_datetime": "2017-10-18T14:44:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T18:07:19.000Z", "avg_line_length": 32.2689161554, "max_line_length": 172, "alphanum_fraction": 0.5835102506, "num_tokens": 12024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749126, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.22294176500283125}}
{"text": "//////////////////////////////////////////////////////////////////////////\n//\n//  Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved.\n//\n//  Redistribution and use in source and binary forms, with or without\n//  modification, are permitted provided that the following conditions are\n//  met:\n//\n//      * Redistributions of source code must retain the above\n//        copyright notice, this list of conditions and the following\n//        disclaimer.\n//\n//      * Redistributions in binary form must reproduce the above\n//        copyright notice, this list of conditions and the following\n//        disclaimer in the documentation and/or other materials provided with\n//        the distribution.\n//\n//      * Neither the name of John Haddon nor the names of\n//        any other contributors to this software may be used to endorse or\n//        promote products derived from this software without specific prior\n//        written permission.\n//\n//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n//  IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n//  CONTRIBUTORS 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\n//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n//////////////////////////////////////////////////////////////////////////\n\n#include \"GafferScene/Constraint.h\"\n\n#include \"Gaffer/StringPlug.h\"\n\n#include \"IECoreScene/CurvesPrimitive.h\"\n#include \"IECoreScene/MeshPrimitive.h\"\n#include \"IECoreScene/PointsPrimitive.h\"\n\n#include <boost/format.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <limits>\n\nusing namespace Imath;\nusing namespace IECore;\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nnamespace\n{\n\ntemplate< typename Indexer >\nbool convexPolygon( const Indexer vertices, const int n )\n{\n\tassert( n >= 3 );\n\n\tif( n == 3 )\n\t{\n\t\treturn true;\n\t}\n\n\tint c[ 2 ] = { 0, 0 };\n\n\tfor( int i = 0; i < n; ++i )\n\t{\n\t\tconst int ip = ( i + n - 1 ) % n;\n\t\tconst int in = ( i     + 1 ) % n;\n\n\t\tconst Imath::V2f vi = vertices( i );\n\n\t\tconst float Av = ( vi - vertices( ip ) ) % ( vertices( in ) - vi );\n\n\t\t// NOTE : colinear edges are ok\n\n\t\tif( Av == 0.f )\n\t\t{\n\t\t\tc[ 0 ] += 1;\n\t\t\tc[ 1 ] += 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tc[ std::signbit( Av ) ? 0 : 1 ] += 1;\n\t\t}\n\t}\n\n\treturn\n\t\t( c[ 0 ] == n ) ||\n\t\t( c[ 1 ] == n );\n}\n\ntemplate< typename Indexer >\nbool ptInPolygon( const Indexer vertices, const Imath::V2f v, const int n )\n{\n\tbool result = false;\n\tfor( int i = 0; i < n; ++i )\n\t{\n\t\tconst Imath::V2f v0 = vertices( i );\n\t\tconst Imath::V2f v1 = vertices( ( i + 1 ) % n );\n\n\t\t// NOTE: Algorithm 3.5, \"Collision Detection in Interactive 3d Environments\", Gino Van Den Bergen\n\t\t//       with modifications to include end points and points on axis aligned edges.\n\n\t\tif( v0 == v )\n\t\t{\n\t\t\treturn true; // NOTE : end point\n\t\t}\n\t\telse if(\n\t\t\t( ( v0.y == v1.y ) && ( v.y == v0.y ) && ( ( v0.x >= v.x ) != ( v1.x >= v.x ) ) ) ||\n\t\t\t( ( v0.x == v1.x ) && ( v.x == v0.x ) && ( ( v0.y >= v.y ) != ( v1.y >= v.y ) ) ) )\n\t\t{\n\t\t\treturn true; // NOTE : axis aligned edge\n\t\t}\n\t\telse if( ( v0.y >= v.y ) != ( v1.y >= v.y ) )\n\t\t{\n\t\t\t// Edge crosses horizontal line `y == v.y`\n\n\t\t\tif( ( v0.x >= v.x ) != ( v1.x >= v.x ) )\n\t\t\t{\n\t\t\t\t// Edge crosses vertical line `x == v.x`\n\n\t\t\t\tif( v0.x + ( v.y - v0.y ) * ( v1.x - v0.x ) / ( v1.y - v0.y ) >= v.x )\n\t\t\t\t{\n\t\t\t\t\t// Edge crosses the ray `y == v.y, x >= v.x`\n\n\t\t\t\t\tresult = !result;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if( v0.x >= v.x )\n\t\t\t{\n\t\t\t\t// Edge crosses the ray `y == v.y, x >= v.x`\n\n\t\t\t\tresult = !result;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\ntemplate< typename PIndexer, typename UVIndexer >\nImath::V3f interpolateConvexPolygon( const PIndexer points, const UVIndexer uvs, const Imath::V2f uv, const int n )\n{\n\t// NOTE : compute vertex and edge triangle areas\n\t//\n\t//        Av[ i ] is 2 * area of the triangle formed by the vertices v(i-1), v(i) and v(i+1)\n\t//        Ae[ i ] is 2 * area of the triangle formed by the vertices v(i), v(i+1) and uv\n\n\tstd::unique_ptr< float[] > Av( new float[ n ] );\n\tstd::unique_ptr< float[] > Ae( new float[ n ] );\n\n\tfor( int i = 0; i < n; ++i )\n\t{\n\t\tconst Imath::V2f vi = uvs( i );\n\n\t\t// NOTE : avoid zero length edges by skipping past adjacent duplicate uv vertices\n\t\t//        in both directions, c is the number of times the duplicate vertex occurs\n\t\t//        in a consecutive run including the current vertex (vi). It is important\n\t\t//        that only adjacent duplicated vertices are included. The computed vertex\n\t\t//        area is weighted by the reciprocal of c to average the influence of the\n\t\t//        positions corresponding to the duplicated uv vertices.\n\n\t\tfloat c = 1.f;\n\n\t\tImath::V2f vp;\n\t\tfor( int j = 1; j < n; ++j )\n\t\t{\n\t\t\tvp = uvs( ( i + n - j ) % n );\n\t\t\tif( vp != vi ) break;\n\t\t\tc += 1.f;\n\t\t}\n\n\t\tImath::V2f vn;\n\t\tfor( int j = 1; j < n; ++j )\n\t\t{\n\t\t\tvn = uvs( ( i + j ) % n );\n\t\t\tif( vn != vi ) break;\n\t\t\tc += 1.f;\n\t\t}\n\n\t\tAv[ i ] = ( vi - vp ) % ( vn - vi );\n\t\tAe[ i ] = ( vn - vi ) % ( uv - vn );\n\n\t\t// NOTE : sign of vertex area depends on winding.\n\n\t\tif( std::signbit( Av[ i ] ) )\n\t\t{\n\t\t\tAv[ i ] = -( Av[ i ] );\n\t\t\tAe[ i ] = -( Ae[ i ] );\n\t\t}\n\n\t\t// NOTE : clamp edge area to minimum of zero to prevent negative weights\n\n\t\tAe[ i ] = std::max( Ae[ i ], 0.f );\n\n\t\t// NOTE : this clamp is done in two steps to prevent underflow to zero\n\n\t\tAv[ i ] = std::max( Av[ i ], c * std::numeric_limits< float >::min() );\n\t\tAv[ i ] /= c;\n\n\t\t// NOTE : uv is considered on an edge when the edge area is below threshold in which\n\t\t//        case lerp between average of all positions corresponding to end vertices\n\n\t\tif(\n\t\t\t( Ae[ i ] < std::sqrt( std::numeric_limits< float >::min() ) ) &&\n\t\t\t( ( ( uv - vi ) ^ ( uv - vn ) ) < std::numeric_limits< float >::min() ) )\n\t\t{\n\t\t\tconst float l2 = ( vn - vi ).length2();\n\t\t\tconst float t = std::min( std::max(\n\t\t\t\t( l2 > ( 2.f * std::numeric_limits< float >::min() ) )\n\t\t\t\t\t? std::sqrt( ( uv - vn ).length2() / l2 ) : 0.f, 0.f ), 1.f );\n\n\t\t\tImath::V3f pv( 0.f );\n\t\t\tImath::V3f pn( 0.f );\n\n\t\t\tfloat pvc = 0.f;\n\t\t\tfloat pnc = 0.f;\n\n\t\t\tfor( int j = 0; j < n; ++j )\n\t\t\t{\n\t\t\t\tif( uvs( j ) == vi )\n\t\t\t\t{\n\t\t\t\t\tpv += points( j );\n\t\t\t\t\tpvc += 1.f;\n\t\t\t\t}\n\t\t\t\tif( uvs( j ) == vn )\n\t\t\t\t{\n\t\t\t\t\tpn += points( j );\n\t\t\t\t\tpnc += 1.f;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tassert( pvc != 0.f );\n\t\t\tassert( pnc != 0.f );\n\n\t\t\treturn\n\t\t\t\t( pv / pvc ) * (       t ) +\n\t\t\t\t( pn / pnc ) * ( 1.0 - t );\n\t\t}\n\t}\n\n\t// NOTE : uv is not on any edges or coincident with any vertices use wachspress coordinates\n\t//        the factor of 2 in the denominator cancels out during normalisation\n\n\tfloat ws = 0.f;\n\tImath::V3f p( 0.f );\n\n\tfor( int i = 0; i < n; ++i )\n\t{\n\t\tconst Imath::V2f vi = uvs( i );\n\n\t\tint ip = 0;\n\t\tfor( int j = 1; j < n; ++j )\n\t\t{\n\t\t\tip = ( i + n - j ) % n;\n\t\t\tif( uvs( ip ) != vi )\n\t\t\t\tbreak;\n\t\t}\n\n\t\tconst float Ad = Ae[ ip ] * Ae[ i ];\n\n\t\tif( Ad != 0.f )\n\t\t{\n\t\t\tconst float w = Av[ i ] / Ad;\n\t\t\tp += points( i ) * w;\n\t\t\tws += w;\n\t\t}\n\t}\n\n\tif( ws != 0.f )\n\t{\n\t\tp /= ws;\n\t}\n\n\treturn p;\n}\n\ntemplate< typename PIndexer, typename UVIndexer >\nImath::V3f interpolateNonConvexPolygon( const PIndexer points, const UVIndexer uvs, const Imath::V2f uv, const int n )\n{\n\t// NOTE : a simple triangle fan from any vertex will cover the non convex polygon\n\t//        the generated triangles may cover areas outside the polygon this is fine\n\n\tImath::V3f p( 0.f );\n\n\tfor( int i = 2; i < n; ++i )\n\t{\n\t\tconst Imath::V2f tuv[ 3 ] =\n\t\t{\n\t\t\tuvs( 0 ),\n\t\t\tuvs( i - 1 ),\n\t\t\tuvs( i )\n\t\t};\n\n\t\tif( ptInPolygon( [ & tuv ]( const int ii ){ return tuv[ ii ]; }, uv, 3 ) )\n\t\t{\n\t\t\tconst float w = ( tuv[ 2 ] - tuv[ 0 ] ) % ( tuv[ 1 ] - tuv[ 0 ] );\n\n\t\t\tif( w == 0.f )\n\t\t\t{\n\t\t\t\t// NOTE : uv triangle numerically has zero area so is effectively a line or point.\n\t\t\t\t//        position in 3d space is ambiguous unless the triangle in 3d space is a point.\n\n\t\t\t\tconst Imath::V3f& vp = points( i - 1 );\n\n\t\t\t\tif(\n\t\t\t\t\t( ( points( 0 ) - vp ).length2() <= ( 2.f * std::numeric_limits< float >::min() ) ) &&\n\t\t\t\t\t( ( points( i ) - vp ).length2() <= ( 2.f * std::numeric_limits< float >::min() ) ) )\n\t\t\t\t{\n\t\t\t\t\tp = vp;\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tthrow IECore::InvalidArgumentException( (\n\t\t\t\t\tboost::format(\n\t\t\t\t\t\t\"Gaffer::Constraint : UV coordinates \\\"%s\\\" map to ambiguous point(s) in 3d space.\"\n\t\t\t\t\t) % ( uv ) ).str() );\n\t\t\t}\n\n\t\t\t// NOTE : ensure that the positive barycentric coordinates sum to a maximum of one.\n\n\t\t\tconst float b0 = std::max( 0.f, ( ( tuv[ 1 ] - tuv[ 2 ] ) % ( uv - tuv[ 1 ] ) ) / w );\n\t\t\tconst float b1 = std::max( 0.f, ( ( tuv[ 2 ] - tuv[ 0 ] ) % ( uv - tuv[ 2 ] ) ) / w );\n\t\t\tconst float b2 = std::max( 0.f, ( ( tuv[ 0 ] - tuv[ 1 ] ) % ( uv - tuv[ 0 ] ) ) / w );\n\n\t\t\tconst float bs = b0 + b1 + b2;\n\n\t\t\tif( bs != 0.f )\n\t\t\t{\n\t\t\t\tp =\n\t\t\t\t\tpoints(     0 ) * ( b0 / bs ) +\n\t\t\t\t\tpoints( i - 1 ) * ( b1 / bs ) +\n\t\t\t\t\tpoints( i     ) * ( b2 / bs );\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn p;\n}\n\nvoid constructMatrix( Imath::M44f& m, const Imath::V3f& p, const Imath::V3f& x, const Imath::V3f& y, const Imath::V3f& z )\n{\n\tm[ 0 ][ 0 ] = x[ 0 ];\n\tm[ 0 ][ 1 ] = x[ 1 ];\n\tm[ 0 ][ 2 ] = x[ 2 ];\n\tm[ 0 ][ 3 ] = 0.f;\n\n\tm[ 1 ][ 0 ] = y[ 0 ];\n\tm[ 1 ][ 1 ] = y[ 1 ];\n\tm[ 1 ][ 2 ] = y[ 2 ];\n\tm[ 1 ][ 3 ] = 0.f;\n\n\tm[ 2 ][ 0 ] = z[ 0 ];\n\tm[ 2 ][ 1 ] = z[ 1 ];\n\tm[ 2 ][ 2 ] = z[ 2 ];\n\tm[ 2 ][ 3 ] = 0.f;\n\n\tm[ 3 ][ 0 ] = p[ 0 ];\n\tm[ 3 ][ 1 ] = p[ 1 ];\n\tm[ 3 ][ 2 ] = p[ 2 ];\n\tm[ 3 ][ 3 ] = 1.f;\n}\n\nvoid constructLocalFrame( Imath::M44f& m, const Imath::V3f& p, const Imath::V3f& t, const Imath::V3f& b, const Imath::V3f& n )\n{\n\t// NOTE : use tangent and bitangent when both have non zero length and are not colinear\n\t//        and either the normal has zero length or both the tangent and bitangent are\n\t//        not colinear with the normal, otherwise use tangent and normal when they both\n\t//        have non zero length and are not colinear, otherwise use bitangent and normal\n\t//        when they both have non zero length and are not colinear\n\n\tconst Imath::V3f nt = t.normalized();\n\tconst Imath::V3f nb = b.normalized();\n\tconst Imath::V3f nn = n.normalized();\n\tconst Imath::V3f bxt = nb % nt;\n\tconst Imath::V3f txn = nt % nn;\n\tconst Imath::V3f nxb = nn % nb;\n\n\tif(\n\t\t( bxt.length2() > ( 2.f * std::numeric_limits< float >::min() ) ) &&\n\t\t( ( n.length2() < ( 2.f * std::numeric_limits< float >::min() ) ) ||\n\t\t\t( ( std::fabs( nt ^ nn ) < 0.999f ) && ( std::fabs( nb ^ nn ) < 0.999f ) ) ) )\n\t{\n\t\tImath::V3f y = bxt.normalized();\n\n\t\t// NOTE : ensure y axis of local frame points in same direction as normal\n\n\t\tif( n.dot( y ) < 0.f )\n\t\t{\n\t\t\ty *= -1.f;\n\t\t}\n\n\t\tconstructMatrix( m, p, nt, y, ( nt % y ).normalized() );\n\t}\n\telse if( txn.length2() > ( 2.f * std::numeric_limits< float >::min() ) )\n\t{\n\t\tconst Imath::V3f z = txn.normalized();\n\t\tconstructMatrix( m, p, nt, ( z % nt ).normalized(), z );\n\t}\n\telse if( nxb.length2() > ( 2.f * std::numeric_limits< float >::min() ) )\n\t{\n\t\tconst Imath::V3f x = nxb.normalized();\n\t\tconstructMatrix( m, p, x, ( nb % x ).normalized(), nb );\n\t}\n\telse\n\t{\n\t\tm.translate( p );\n\t}\n}\n\nstruct UVIndexer\n{\n\tUVIndexer( const IECoreScene::MeshPrimitive& primitive, const std::string& uvSet, const bool throwOnError )\n\t: m_indices( nullptr )\n\t, m_view()\n\t{\n\t\tconst IECoreScene::PrimitiveVariableMap::const_iterator it = primitive.variables.find( uvSet );\n\n\t\tif(\n\t\t\t( it == primitive.variables.end() ) ||\n\t\t\t( ( *it ).second.data->typeId() != IECore::V2fVectorDataTypeId ) )\n\t\t{\n\t\t\tif( throwOnError )\n\t\t\t{\n\t\t\t\tthrow IECore::InvalidArgumentException( (\n\t\t\t\t\tboost::format(\n\t\t\t\t\t\t\"Gaffer::Constraint : MeshPrimitive has no V2fVectorData primitive variable named \\\"%s\\\".\"\n\t\t\t\t\t) % ( uvSet ) ).str() );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// NOTE : for vertex and varying interpolation we need to redirect through the primitive indices\n\n\t\tif(\n\t\t\t( ( *it ).second.interpolation == IECoreScene::PrimitiveVariable::Vertex ) ||\n\t\t\t( ( *it ).second.interpolation == IECoreScene::PrimitiveVariable::Varying ) )\n\t\t{\n\t\t\tm_indices = &( primitive.vertexIds()->readable() );\n\t\t}\n\t\telse if( ( *it ).second.interpolation != IECoreScene::PrimitiveVariable::FaceVarying )\n\t\t{\n\t\t\tif( throwOnError )\n\t\t\t{\n\t\t\t\tthrow IECore::InvalidArgumentException( (\n\t\t\t\t\tboost::format(\n\t\t\t\t\t\t\"Gaffer::Constraint : Primitive variable named \\\"%s\\\" has incorrect interpolation, must be either Vertex, Varying or FaceVarying\"\n\t\t\t\t\t) % ( uvSet ) ).str() );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tm_view = IECoreScene::PrimitiveVariable::IndexedView< Imath::V2f >( ( *it ).second );\n\t}\n\n\tbool valid() const\n\t{\n\t\treturn static_cast< bool >( m_view );\n\t}\n\n\tconst Imath::V2f& operator[]( const int i ) const\n\t{\n\t\tassert( valid() );\n\t\tconst int index = ( m_indices != nullptr ) ? ( ( *m_indices )[ i ] ) : i;\n\t\treturn ( *m_view )[ index ];\n\t}\n\nprivate:\n\n\tconst std::vector< int >* m_indices;\n\tstd::optional<IECoreScene::PrimitiveVariable::IndexedView<Imath::V2f>> m_view;\n};\n\nvoid computePrimitiveVertexLocalFrame( const IECoreScene::Primitive& primitive, Imath::M44f& m, const int vertexId, const bool throwOnError )\n{\n\tconst IECore::V3fVectorData* const pdata = primitive.variableData< IECore::V3fVectorData >( \"P\" );\n\tif( pdata == nullptr )\n\t{\n\t\tif( throwOnError )\n\t\t{\n\t\t\tthrow IECore::InvalidArgumentException( \"Gaffer::Contraint : Primitive has no Vertex \\\"P\\\" primitive variable.\" );\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn;\n\t\t}\n\t}\n\tconst IECore::V3fVectorData::ValueType& points = pdata->readable();\n\n\tif( ( vertexId < 0 ) || ( vertexId >= static_cast< int >( points.size() ) ) )\n\t{\n\t\tif( throwOnError )\n\t\t{\n\t\t\tthrow IECore::InvalidArgumentException( (\n\t\t\t\tboost::format(\n\t\t\t\t\t\"Gaffer::Constraint : Vertex id \\\"%d\\\" is out of range.\"\n\t\t\t\t) % ( vertexId ) ).str() );\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn;\n\t\t}\n\t}\n\n\tm.translate( points[ vertexId ] );\n}\n\nvoid computeMeshVertexLocalFrame( const IECoreScene::MeshPrimitive& primitive, Imath::M44f& m, const int vertexId, const std::string& uvSet, const bool throwOnError, const IECore::Canceller* const canceller )\n{\n\tconst IECore::V3fVectorData* const pdata = primitive.variableData< IECore::V3fVectorData >( \"P\" );\n\n\tif( pdata == nullptr )\n\t{\n\t\tif( throwOnError )\n\t\t{\n\t\t\tthrow IECore::InvalidArgumentException( \"Gaffer::Contraint : MeshPrimitive has no Vertex \\\"P\\\" primitive variable.\" );\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn;\n\t\t}\n\t}\n\n\tconst IECore::V3fVectorData::ValueType& points = pdata->readable();\n\n\tif( ( vertexId < 0 ) || ( vertexId >= static_cast< int >( points.size() ) ) )\n\t{\n\t\tif( throwOnError )\n\t\t{\n\t\t\tthrow IECore::InvalidArgumentException( (\n\t\t\t\tboost::format(\n\t\t\t\t\t\"Gaffer::Constraint : Vertex id \\\"%d\\\" is out of range.\"\n\t\t\t\t) % ( vertexId ) ).str() );\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn;\n\t\t}\n\t}\n\n\tconst IECore::IntVectorData::ValueType& indices = primitive.vertexIds()->readable();\n\tconst IECore::IntVectorData::ValueType& faces = primitive.verticesPerFace()->readable();\n\n\tconst UVIndexer uvs( primitive, uvSet, throwOnError );\n\n\tImath::V3f t( 0.f );\n\tImath::V3f b( 0.f );\n\tImath::V3f n( 0.f );\n\n\tif( uvs.valid() )\n\t{\n\t\tint js = 0;\n\t\tfor( int i = 0; i < static_cast< int >( faces.size() ); ++i )\n\t\t{\n\t\t\tconst int ni = faces[ i ];\n\n\t\t\t// canceller support\n\n\t\t\tif( ( i % 100 ) == 0 )\n\t\t\t{\n\t\t\t\tIECore::Canceller::check( canceller );\n\t\t\t}\n\n\t\t\t// find matching face vertex index\n\n\t\t\tint jm = 0;\n\t\t\tfor( ; jm < ni; ++jm )\n\t\t\t{\n\t\t\t\tif( indices[ js + jm ] == vertexId )\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( jm < ni )\n\t\t\t{\n\t\t\t\t// compute face normal, tangent and bitangent\n\n\t\t\t\tImath::V3f ft( 0.f );\n\t\t\t\tImath::V3f fb( 0.f );\n\t\t\t\tImath::V3f fn( 0.f );\n\n\t\t\t\tfloat w = 0.f;\n\n\t\t\t\tfor( int j = 0; j < ni; ++j )\n\t\t\t\t{\n\t\t\t\t\tconst int iv = js + j;\n\t\t\t\t\tconst int ip = js + ( ( j + ni - 1 ) % ni );\n\t\t\t\t\tconst int in = js + ( ( j      + 1 ) % ni );\n\n\t\t\t\t\tconst Imath::V3f pv = points[ indices[ iv ] ];\n\t\t\t\t\tconst Imath::V3f v0 = points[ indices[ ip ] ] - pv;\n\t\t\t\t\tconst Imath::V3f v2 = points[ indices[ in ] ] - pv;\n\n\t\t\t\t\tconst Imath::V2f uv = uvs[ iv ];\n\t\t\t\t\tconst Imath::V2f e0 = uvs[ ip ] - uv;\n\t\t\t\t\tconst Imath::V2f e2 = uvs[ in ] - uv;\n\n\t\t\t\t\tft += ( v0 * -e2.y + v2 * e0.y ).normalized();\n\t\t\t\t\tfb += ( v0 * -e2.x + v2 * e0.x ).normalized();\n\t\t\t\t\tfn += ( -v0 % v2 ).normalized();\n\n\t\t\t\t\tif( j == jm )\n\t\t\t\t\t{\n\t\t\t\t\t\tconst float lv2 = v0.length2() * v2.length2();\n\n\t\t\t\t\t\tif( lv2 > ( 2.f * std::numeric_limits< float >::min() ) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst float lv = std::sqrt( lv2 );\n\n\t\t\t\t\t\t\tif( lv != 0.f )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tw = std::acos( std::min( std::max( ( v0 ^ v2 ) / lv, -1.f ), 1.f ) );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// accumulate angle weighted normal, tangent and bitangent\n\n\t\t\t\tt += ft.normalized() * w;\n\t\t\t\tb += fb.normalized() * w;\n\t\t\t\tn += fn.normalized() * w;\n\t\t\t}\n\n\t\t\tjs += ni;\n\t\t}\n\t}\n\n\tconstructLocalFrame( m, points[ vertexId ], t, b, n );\n}\n\nvoid computeVertexLocalFrame( const IECore::Object& object, Imath::M44f& m, const int vertexId, const std::string& uvSet, const bool throwOnError, const IECore::Canceller* const canceller )\n{\n\tswitch( static_cast< IECoreScene::TypeId >( object.typeId() ) )\n\t{\n\t\tcase IECoreScene::CurvesPrimitiveTypeId:\n\t\tcase IECoreScene::PointsPrimitiveTypeId:\n\t\t\tcomputePrimitiveVertexLocalFrame( static_cast< const IECoreScene::Primitive& >( object ), m, vertexId, throwOnError );\n\t\t\tbreak;\n\t\tcase IECoreScene::MeshPrimitiveTypeId:\n\t\t\tcomputeMeshVertexLocalFrame( static_cast< const IECoreScene::MeshPrimitive& >( object ), m, vertexId, uvSet, throwOnError, canceller );\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif( throwOnError )\n\t\t\t{\n\t\t\t\tthrow IECore::InvalidArgumentException( (\n\t\t\t\t\tboost::format(\n\t\t\t\t\t\t\"Gaffer::Constraint : Target primitive of type \\\"%s\\\" is not supported in Vertex target mode.\"\n\t\t\t\t\t) % ( object.typeName() ) ).str() );\n\t\t\t}\n\t\t\tbreak;\n\t}\n}\n\nvoid computeMeshUVLocalFrame( const IECoreScene::MeshPrimitive& primitive, Imath::M44f& m, const Imath::V2f& uv, const std::string& uvSet, const bool throwOnError, const IECore::Canceller* const canceller )\n{\n\tconst IECore::V3fVectorData* const pdata = primitive.variableData< IECore::V3fVectorData >( \"P\" );\n\n\tif( pdata == nullptr )\n\t{\n\t\tif( throwOnError )\n\t\t{\n\t\t\tthrow IECore::InvalidArgumentException( \"Gaffer::Contraint : MeshPrimitive has no Vertex \\\"P\\\" primitive variable.\" );\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn;\n\t\t}\n\t}\n\n\tconst IECore::V3fVectorData::ValueType& points = pdata->readable();\n\tconst IECore::IntVectorData::ValueType& indices = primitive.vertexIds()->readable();\n\tconst IECore::IntVectorData::ValueType& faces = primitive.verticesPerFace()->readable();\n\n\tconst UVIndexer uvs( primitive, uvSet, throwOnError );\n\tif( ! uvs.valid() )\n\t{\n\t\treturn;\n\t}\n\n\tint js = 0;\n\tfor( int i = 0; i < static_cast< int >( faces.size() ); ++i )\n\t{\n\t\tconst int ni = faces[ i ];\n\n\t\t// canceller support\n\n\t\tif( ( i % 100 ) == 0 )\n\t\t{\n\t\t\tIECore::Canceller::check( canceller );\n\t\t}\n\n\t\t// points and uv indexers\n\n\t\tconst auto pIndexer = [ & points, & indices, js ]( const int ii )\n\t\t{\n\t\t\treturn points[ indices[ js + ii ] ];\n\t\t};\n\n\t\tconst auto uvIndexer = [ & uvs, js ]( const int ii )\n\t\t{\n\t\t\treturn uvs[ js + ii ];\n\t\t};\n\n\t\t// determine if uv coordinate is inside face\n\n\t\tif( ptInPolygon( uvIndexer, uv, ni ) )\n\t\t{\n\t\t\tImath::V3f fp( 0.f );\n\t\t\tImath::V3f ft( 0.f );\n\t\t\tImath::V3f fb( 0.f );\n\t\t\tImath::V3f fn( 0.f );\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfp = ( convexPolygon( uvIndexer, ni ) )\n\t\t\t\t\t? interpolateConvexPolygon( pIndexer, uvIndexer, uv, ni )\n\t\t\t\t\t: interpolateNonConvexPolygon( pIndexer, uvIndexer, uv, ni );\n\n\t\t\t\t// compute face tangent and bitangent\n\n\t\t\t\tfor( int j = 0; j < ni; ++j )\n\t\t\t\t{\n\t\t\t\t\tconst int iv = js + j;\n\t\t\t\t\tconst int ip = js + ( ( j + ni - 1 ) % ni );\n\t\t\t\t\tconst int in = js + ( ( j      + 1 ) % ni );\n\n\t\t\t\t\tconst Imath::V3f pv = points[ indices[ iv ] ];\n\t\t\t\t\tconst Imath::V3f v0 = points[ indices[ ip ] ] - pv;\n\t\t\t\t\tconst Imath::V3f v2 = points[ indices[ in ] ] - pv;\n\n\t\t\t\t\tconst Imath::V2f uv = uvs[ iv ];\n\t\t\t\t\tconst Imath::V2f e0 = uvs[ ip ] - uv;\n\t\t\t\t\tconst Imath::V2f e2 = uvs[ in ] - uv;\n\n\t\t\t\t\tft += ( v0 * -e2.y + v2 * e0.y ).normalized();\n\t\t\t\t\tfb += ( v0 * -e2.x + v2 * e0.x ).normalized();\n\t\t\t\t\tfn += ( -v0 % v2 ).normalized();\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch( const IECore::Exception& e )\n\t\t\t{\n\t\t\t\tif( throwOnError )\n\t\t\t\t{\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconstructLocalFrame( m, fp, ft, fb, fn );\n\n\t\t\treturn;\n\t\t}\n\n\t\tjs += ni;\n\t}\n\n\tif( throwOnError )\n\t{\n\t\tthrow IECore::InvalidArgumentException( (\n\t\t\tboost::format(\n\t\t\t\t\"Gaffer::Constraint : UV coordinates \\\"%s\\\" are out of range.\"\n\t\t\t) % ( uv ) ).str() );\n\t}\n}\n\nvoid computeUVLocalFrame( const IECore::Object& object, Imath::M44f& m, const Imath::V2f& uv, const std::string& uvSet, const bool throwOnError, const IECore::Canceller* const canceller )\n{\n\tswitch( static_cast< IECoreScene::TypeId >( object.typeId() ) )\n\t{\n\t\tcase IECoreScene::MeshPrimitiveTypeId:\n\t\t\tcomputeMeshUVLocalFrame( static_cast< const IECoreScene::MeshPrimitive& >( object ), m, uv, uvSet, throwOnError, canceller );\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif( throwOnError )\n\t\t\t{\n\t\t\t\tthrow IECore::InvalidArgumentException( (\n\t\t\t\t\tboost::format(\n\t\t\t\t\t\t\"Gaffer::Constraint : Target primitive of type \\\"%s\\\" is not supported in UV target mode.\"\n\t\t\t\t\t) % ( object.typeName() ) ).str() );\n\t\t\t}\n\t\t\tbreak;\n\t}\n}\n\n} // namespace\n\nGAFFER_NODE_DEFINE_TYPE( Constraint );\n\nsize_t Constraint::g_firstPlugIndex = 0;\n\nConstraint::Constraint( const std::string &name )\n\t:\tSceneElementProcessor( name, IECore::PathMatcher::NoMatch )\n{\n\tstoreIndexOfNextChild( g_firstPlugIndex );\n\taddChild( new ScenePlug( \"targetScene\" ) );\n\taddChild( new StringPlug( \"target\" ) );\n\taddChild( new BoolPlug( \"ignoreMissingTarget\" ) );\n\taddChild( new IntPlug( \"targetMode\", Plug::In, Constraint::Origin, Constraint::Origin, Constraint::Vertex ) );\n\taddChild( new V2fPlug( \"targetUV\" ) );\n\taddChild( new IntPlug( \"targetVertex\", Plug::In, 0, 0 ) );\n\taddChild( new V3fPlug( \"targetOffset\" ) );\n\n\t// Pass through things we don't want to modify\n\toutPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() );\n\toutPlug()->objectPlug()->setInput( inPlug()->objectPlug() );\n}\n\nConstraint::~Constraint()\n{\n}\n\nScenePlug *Constraint::targetScenePlug()\n{\n\treturn getChild<ScenePlug>( g_firstPlugIndex );\n}\n\nconst ScenePlug *Constraint::targetScenePlug() const\n{\n\treturn getChild<ScenePlug>( g_firstPlugIndex );\n}\n\nGaffer::StringPlug *Constraint::targetPlug()\n{\n\treturn getChild<Gaffer::StringPlug>( g_firstPlugIndex + 1 );\n}\n\nconst Gaffer::StringPlug *Constraint::targetPlug() const\n{\n\treturn getChild<Gaffer::StringPlug>( g_firstPlugIndex + 1 );\n}\n\nGaffer::BoolPlug *Constraint::ignoreMissingTargetPlug()\n{\n\treturn getChild<Gaffer::BoolPlug>( g_firstPlugIndex + 2 );\n}\n\nconst Gaffer::BoolPlug *Constraint::ignoreMissingTargetPlug() const\n{\n\treturn getChild<Gaffer::BoolPlug>( g_firstPlugIndex + 2 );\n}\n\nGaffer::IntPlug *Constraint::targetModePlug()\n{\n\treturn getChild<Gaffer::IntPlug>( g_firstPlugIndex + 3 );\n}\n\nconst Gaffer::IntPlug *Constraint::targetModePlug() const\n{\n\treturn getChild<Gaffer::IntPlug>( g_firstPlugIndex + 3 );\n}\n\nGaffer::V2fPlug *Constraint::targetUVPlug()\n{\n\treturn getChild<Gaffer::V2fPlug>( g_firstPlugIndex + 4 );\n}\n\nconst Gaffer::V2fPlug *Constraint::targetUVPlug() const\n{\n\treturn getChild<Gaffer::V2fPlug>( g_firstPlugIndex + 4 );\n}\n\nGaffer::IntPlug *Constraint::targetVertexPlug()\n{\n\treturn getChild<Gaffer::IntPlug>( g_firstPlugIndex + 5 );\n}\n\nconst Gaffer::IntPlug *Constraint::targetVertexPlug() const\n{\n\treturn getChild<Gaffer::IntPlug>( g_firstPlugIndex + 5 );\n}\n\nGaffer::V3fPlug *Constraint::targetOffsetPlug()\n{\n\treturn getChild<Gaffer::V3fPlug>( g_firstPlugIndex + 6 );\n}\n\nconst Gaffer::V3fPlug *Constraint::targetOffsetPlug() const\n{\n\treturn getChild<Gaffer::V3fPlug>( g_firstPlugIndex + 6 );\n}\n\nvoid Constraint::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tSceneElementProcessor::affects( input, outputs );\n\n\tif(\n\t\tinput == targetPlug() ||\n\t\tinput == ignoreMissingTargetPlug() ||\n\t\tinput == inPlug()->existsPlug() ||\n\t\tinput == inPlug()->transformPlug() ||\n\t\tinput == inPlug()->boundPlug() ||\n\t\tinput == targetScenePlug()->existsPlug() ||\n\t\tinput == targetScenePlug()->transformPlug() ||\n\t\tinput == targetScenePlug()->boundPlug() ||\n\t\tinput == targetScenePlug()->objectPlug() ||\n\t\tinput == targetModePlug() ||\n\t\tinput->parent<Plug>() == targetOffsetPlug() ||\n\t\tinput->parent<Plug>() == targetUVPlug() ||\n\t\tinput == targetVertexPlug() ||\n\t\t// TypeId comparison is necessary to avoid calling pure virtual\n\t\t// if we're called before being fully constructed.\n\t\t( typeId() != staticTypeId() && affectsConstraint( input ) )\n\t)\n\t{\n\t\toutputs.push_back( outPlug()->transformPlug() );\n\t\toutputs.push_back( outPlug()->boundPlug() );\n\t}\n}\n\nbool Constraint::processesTransform() const\n{\n\treturn true;\n}\n\nvoid Constraint::hashProcessedTransform( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tauto targetOpt = target();\n\tif( !targetOpt )\n\t{\n\t\t// Pass through input unchanged\n\t\th = inPlug()->transformPlug()->hash();\n\t\treturn;\n\t}\n\n\tScenePath parentPath = path;\n\tparentPath.pop_back();\n\th.append( inPlug()->fullTransformHash( parentPath ) );\n\n\th.append( targetOpt->scene->fullTransformHash( targetOpt->path ) );\n\n\tconst TargetMode targetMode = (TargetMode)targetModePlug()->getValue();\n\th.append( targetMode );\n\tswitch( targetMode )\n\t{\n\t\tcase Constraint::BoundMin:\n\t\tcase Constraint::BoundMax:\n\t\tcase Constraint::BoundCenter:\n\t\t\th.append( targetOpt->scene->boundHash( targetOpt->path ) );\n\t\t\tbreak;\n\t\tcase Constraint::UV:\n\t\t\th.append( targetOpt->scene->objectHash( targetOpt->path ) );\n\t\t\tignoreMissingTargetPlug()->hash( h );\n\t\t\ttargetUVPlug()->hash( h );\n\t\t\tbreak;\n\t\tcase Constraint::Vertex:\n\t\t\th.append( targetOpt->scene->objectHash( targetOpt->path ) );\n\t\t\tignoreMissingTargetPlug()->hash( h );\n\t\t\ttargetVertexPlug()->hash( h );\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\ttargetOffsetPlug()->hash( h );\n\n\thashConstraint( context, h );\n}\n\nImath::M44f Constraint::computeProcessedTransform( const ScenePath &path, const Gaffer::Context *context, const Imath::M44f &inputTransform ) const\n{\n\tauto targetOpt = target();\n\tif( !targetOpt )\n\t{\n\t\treturn inputTransform;\n\t}\n\n\tScenePath parentPath = path;\n\tparentPath.pop_back();\n\n\tconst M44f parentTransform = inPlug()->fullTransform( parentPath );\n\tconst M44f fullInputTransform = inputTransform * parentTransform;\n\n\tM44f fullTargetTransform = targetOpt->scene->fullTransform( targetOpt->path );\n\n\tconst TargetMode targetMode = (TargetMode)targetModePlug()->getValue();\n\n\tswitch( targetMode )\n\t{\n\t\tcase Constraint::BoundMin:\n\t\t{\n\t\t\tconst Box3f targetBound = targetOpt->scene->bound( targetOpt->path );\n\t\t\tif( ! targetBound.isEmpty() )\n\t\t\t{\n\t\t\t\tfullTargetTransform.translate( targetBound.min );\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase Constraint::BoundMax:\n\t\t{\n\t\t\tconst Box3f targetBound = targetOpt->scene->bound( targetOpt->path );\n\t\t\tif( ! targetBound.isEmpty() )\n\t\t\t{\n\t\t\t\tfullTargetTransform.translate( targetBound.max );\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase Constraint::BoundCenter:\n\t\t{\n\t\t\tconst Box3f targetBound = targetOpt->scene->bound( targetOpt->path );\n\t\t\tif( ! targetBound.isEmpty() )\n\t\t\t{\n\t\t\t\tfullTargetTransform.translate( targetBound.center() );\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase Constraint::UV:\n\t\t{\n\t\t\tconst IECore::ConstObjectPtr object = targetOpt->scene->object( targetOpt->path );\n\t\t\tImath::M44f surfaceTransform;\n\t\t\tconst Imath::V2f uv = targetUVPlug()->getValue();\n\t\t\tconst bool throwOnError = !( ignoreMissingTargetPlug()->getValue() );\n\t\t\tcomputeUVLocalFrame( *object, surfaceTransform, uv, \"uv\", throwOnError, context->canceller() );\n\t\t\tfullTargetTransform = surfaceTransform * fullTargetTransform;\n\t\t\tbreak;\n\t\t}\n\t\tcase Constraint::Vertex:\n\t\t{\n\t\t\tconst IECore::ConstObjectPtr object = targetOpt->scene->object( targetOpt->path );\n\t\t\tImath::M44f surfaceTransform;\n\t\t\tconst int vertexId = targetVertexPlug()->getValue();\n\t\t\tconst bool throwOnError = !( ignoreMissingTargetPlug()->getValue() );\n\t\t\tcomputeVertexLocalFrame( *object, surfaceTransform, vertexId, \"uv\", throwOnError, context->canceller() );\n\t\t\tfullTargetTransform = surfaceTransform * fullTargetTransform;\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\tfullTargetTransform.translate( targetOffsetPlug()->getValue() );\n\n\tconst M44f fullConstrainedTransform = computeConstraint( fullTargetTransform, fullInputTransform, inputTransform );\n\treturn fullConstrainedTransform * parentTransform.inverse();\n}\n\nstd::optional<Constraint::Target> Constraint::target() const\n{\n\tstd::string targetPathAsString = targetPlug()->getValue();\n\tif( targetPathAsString == \"\" )\n\t{\n\t\treturn std::nullopt;\n\t}\n\n\tScenePath targetPath;\n\tScenePlug::stringToPath( targetPathAsString, targetPath );\n\n\tconst ScenePlug *targetScene = targetScenePlug();\n\tif( !targetScene->getInput() )\n\t{\n\t\t// Backwards compatibility for time when there was\n\t\t// no `targetScene` plug.\n\t\ttargetScene = inPlug();\n\t}\n\n\tif( !targetScene->exists( targetPath ) )\n\t{\n\t\tif( ignoreMissingTargetPlug()->getValue() )\n\t\t{\n\t\t\treturn std::nullopt;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow IECore::Exception( boost::str(\n\t\t\t\tboost::format( \"Constraint target does not exist: \\\"%s\\\".  Use 'ignoreMissingTarget' option if you want to just skip this constraint\" ) % targetPathAsString ) );\n\t\t}\n\t}\n\n\treturn Target( { targetPath, targetScene } );\n}\n", "meta": {"hexsha": "73ef99097768457a31bc2687faa48348f0e9e6c6", "size": 29431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/GafferScene/Constraint.cpp", "max_stars_repo_name": "pier-robot/gaffer", "max_stars_repo_head_hexsha": "9267f2ba3822b14430d8a283c745261110b0f570", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GafferScene/Constraint.cpp", "max_issues_repo_name": "pier-robot/gaffer", "max_issues_repo_head_hexsha": "9267f2ba3822b14430d8a283c745261110b0f570", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GafferScene/Constraint.cpp", "max_forks_repo_name": "pier-robot/gaffer", "max_forks_repo_head_hexsha": "9267f2ba3822b14430d8a283c745261110b0f570", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0754369825, "max_line_length": 208, "alphanum_fraction": 0.6153035915, "num_tokens": 9080, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.22279367514197143}}
{"text": "/*****************************************************************************\n*\n* Copyright (c) 2003-2018 by The University of Queensland\n* http://www.uq.edu.au\n*\n* Primary Business: Queensland, Australia\n* Licensed under the Apache License, version 2.0\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Development until 2012 by Earth Systems Science Computational Center (ESSCC)\n* Development 2012-2013 by School of Earth Sciences\n* Development from 2014 by Centre for Geoscience Computing (GeoComp)\n*\n*****************************************************************************/\n\n\n/****************************************************************************/\n\n/* Paso: SystemMatrix: controls iterative linear system solvers  */\n\n/****************************************************************************/\n\n/* Copyrights by ACcESS Australia 2003/04                     */\n/* Author: Lutz Gross, l.gross@uq.edu.au                      */\n\n/****************************************************************************/\n\n#include \"Solver.h\"\n#include \"Options.h\"\n#include \"SystemMatrix.h\"\n\n#include <boost/math/special_functions/fpclassify.hpp>  // for isnan\n\n#include <iostream>\n\nnamespace bm = boost::math;\n\nnamespace paso {\n\nvoid Solver_free(SystemMatrix<double>* A)\n{\n    A->freePreconditioner();\n}\n\n///  calls the iterative solver\nSolverResult Solver(SystemMatrix_ptr<double> A, double* x, double* b, Options* options,\n                    Performance* pp)\n{\n    const real_t EPSILON = escript::DataTypes::real_t_eps();\n    double norm2_of_b,tol,tolerance,time_iter,net_time_start;\n    double *r=NULL,norm2_of_residual,last_norm2_of_residual,norm_max_of_b;\n    double norm2_of_b_local,norm_max_of_b_local,norm2_of_residual_local;\n    double norm_max_of_residual_local,norm_max_of_residual;\n    double last_norm_max_of_residual;\n#ifdef ESYS_MPI\n    double loc_norm;\n#endif\n    dim_t i,totIter=0,cntIter,method;\n    bool finalizeIteration;\n    SolverResult errorCode = NoError;\n    const dim_t numSol = A->getTotalNumCols();\n    const dim_t numEqua = A->getTotalNumRows();\n    double *x0=NULL;\n\n    tolerance=options->tolerance;\n    if (tolerance < 100.* EPSILON) {\n        throw PasoException(\"Solver: Tolerance is too small.\");\n    }\n    if (tolerance >1.) {\n        throw PasoException(\"Solver: Tolerance must be less than one.\");\n    }\n    method=Options::getSolver(options->method, PASO_PASO, options->symmetric, A->mpi_info);\n    /* check matrix type */\n    if ((A->type & MATRIX_FORMAT_CSC) || (A->type & MATRIX_FORMAT_OFFSET1) ) {\n        throw PasoException(\"Solver: Iterative solver requires CSR format with unsymmetric storage scheme and index offset 0.\");\n    }\n    if (A->col_block_size != A->row_block_size) {\n        throw PasoException(\"Solver: Iterative solver requires row and column block sizes to be equal.\");\n    }\n    if (A->getGlobalNumCols() != A->getGlobalNumRows()) {\n        throw PasoException(\"Solver: Iterative solver requires a square matrix.\");\n    }\n    time_iter=escript::gettime();\n    /* this for testing only */\n    if (method==PASO_NONLINEAR_GMRES) {\n        LinearSystem* F = new LinearSystem(A, b, options);\n        A->solvePreconditioner(x, b);\n        errorCode = Solver_NewtonGMRES(F, x, options, pp);\n        if (errorCode != NoError) {\n            throw PasoException(\"Solver_NewtonGMRES: an error has occurred.\");\n        }\n        delete F;\n        return errorCode;\n    }\n\n    r = new double[numEqua];\n    x0 = new double[numEqua];\n    A->balance();\n    options->num_level=0;\n    options->num_inner_iter=0;\n\n    /* ========================= */\n    Performance_startMonitor(pp, PERFORMANCE_ALL);\n    A->applyBalance(r, b, true);\n    /* get the norm of the right hand side */\n    norm2_of_b=0.;\n    norm_max_of_b=0.;\n    #pragma omp parallel private(norm2_of_b_local,norm_max_of_b_local)\n    {\n        norm2_of_b_local=0.;\n        norm_max_of_b_local=0.;\n        #pragma omp for private(i) schedule(static)\n        for (i = 0; i < numEqua ; ++i) {\n            norm2_of_b_local += r[i] * r[i];\n            norm_max_of_b_local = std::max(std::abs(r[i]),norm_max_of_b_local);\n        }\n        #pragma omp critical\n        {\n            norm2_of_b += norm2_of_b_local;\n            norm_max_of_b = std::max(norm_max_of_b_local,norm_max_of_b);\n        }\n    }\n#ifdef ESYS_MPI\n    /* TODO: use one call */\n    loc_norm = norm2_of_b;\n    MPI_Allreduce(&loc_norm,&norm2_of_b, 1, MPI_DOUBLE, MPI_SUM, A->mpi_info->comm);\n    loc_norm = norm_max_of_b;\n    MPI_Allreduce(&loc_norm,&norm_max_of_b, 1, MPI_DOUBLE, MPI_MAX, A->mpi_info->comm);\n#endif\n    norm2_of_b=sqrt(norm2_of_b);\n    /* if norm2_of_b==0 we are ready: x=0 */\n    if (bm::isnan(norm2_of_b) || bm::isnan(norm_max_of_b)) {\n        throw PasoException(\"Solver: Matrix or right hand side contains undefined values.\");\n    } else if (norm2_of_b <= 0.) {\n#pragma omp parallel for private(i) schedule(static)\n        for (i = 0; i < numSol; i++) x[i]=0.;\n        if (options->verbose)\n            std::cout << \"right hand side is identical to zero.\" << std::endl;\n    } else {\n        if (options->verbose) {\n            std::cout << \"Solver: l2/lmax-norm of right hand side is \"\n                << norm2_of_b << \"/\" << norm_max_of_b << \".\" << std::endl\n                << \"Solver: l2/lmax-stopping criterion is \"\n                << norm2_of_b*tolerance << \"/\" << norm_max_of_b*tolerance\n                << \".\" << std::endl;\n            switch (method) {\n                case PASO_BICGSTAB:\n                    std::cout << \"Solver: Iterative method is BiCGStab.\\n\";\n                break;\n                case PASO_PCG:\n                    std::cout << \"Solver: Iterative method is PCG.\\n\";\n                break;\n                case PASO_TFQMR:\n                    std::cout << \"Solver: Iterative method is TFQMR.\\n\";\n                break;\n                case PASO_MINRES:\n                    std::cout << \"Solver: Iterative method is MINRES.\\n\";\n                break;\n                case PASO_PRES20:\n                    std::cout << \"Solver: Iterative method is PRES20.\\n\";\n                break;\n                case PASO_GMRES:\n                    if (options->restart > 0) {\n                        std::cout << \"Solver: Iterative method is GMRES(\"\n                            << options->truncation << \",\"\n                            << options->restart << \").\" << std::endl;\n                    } else {\n                        std::cout << \"Solver: Iterative method is GMRES(\"\n                            << options->truncation << \").\" << std::endl;\n                    }\n                break;\n            }\n        }\n\n        // construct the preconditioner\n        Performance_startMonitor(pp, PERFORMANCE_PRECONDITIONER_INIT);\n        A->setPreconditioner(options);\n        Performance_stopMonitor(pp, PERFORMANCE_PRECONDITIONER_INIT);\n        options->set_up_time=escript::gettime()-time_iter;\n        // get an initial guess by evaluating the preconditioner\n        A->solvePreconditioner(x, r);\n\n        totIter = 1;\n        finalizeIteration = false;\n        last_norm2_of_residual=norm2_of_b;\n        last_norm_max_of_residual=norm_max_of_b;\n        net_time_start=escript::gettime();\n\n        // main loop\n        while (!finalizeIteration) {\n            cntIter = options->iter_max - totIter;\n            finalizeIteration = true;\n\n            // Set initial residual\n            if (totIter > 1) {\n                // in the first iteration r = balance * b already\n                A->applyBalance(r, b, true);\n            }\n\n            A->MatrixVector_CSR_OFFSET0(-1., x, 1., r);\n            norm2_of_residual = 0;\n            norm_max_of_residual = 0;\n            #pragma omp parallel private(norm2_of_residual_local,norm_max_of_residual_local)\n            {\n                norm2_of_residual_local = 0;\n                norm_max_of_residual_local = 0;\n                #pragma omp for private(i) schedule(static)\n                for (i = 0; i < numEqua; i++) {\n                    norm2_of_residual_local+= r[i] * r[i];\n                    norm_max_of_residual_local=std::max(std::abs(r[i]),norm_max_of_residual_local);\n                }\n                #pragma omp critical\n                {\n                    norm2_of_residual += norm2_of_residual_local;\n                    norm_max_of_residual = std::max(norm_max_of_residual_local,norm_max_of_residual);\n                }\n            }\n#ifdef ESYS_MPI\n            // TODO: use one call\n            loc_norm = norm2_of_residual;\n            MPI_Allreduce(&loc_norm,&norm2_of_residual, 1, MPI_DOUBLE, MPI_SUM, A->mpi_info->comm);\n            loc_norm = norm_max_of_residual;\n            MPI_Allreduce(&loc_norm,&norm_max_of_residual, 1, MPI_DOUBLE, MPI_MAX, A->mpi_info->comm);\n#endif\n            norm2_of_residual =sqrt(norm2_of_residual);\n            options->residual_norm=norm2_of_residual;\n\n            if (options->verbose)\n                std::cout << \"Solver: Step \" << totIter\n                    << \": l2/lmax-norm of residual is \"\n                    << norm2_of_residual << \"/\" << norm_max_of_residual;\n\n            if (totIter > 1 &&\n                    norm2_of_residual >= last_norm2_of_residual &&\n                    norm_max_of_residual >= last_norm_max_of_residual) {\n\n                if (options->verbose) std::cout << \" divergence!\\n\";\n                throw PasoException(\"Solver: No improvement during iteration. Iterative solver gives up.\");\n\n            } else {\n                if (norm2_of_residual>tolerance*norm2_of_b ||\n                        norm_max_of_residual>tolerance*norm_max_of_b ) {\n\n                    tol=tolerance*std::min(norm2_of_b,0.1*norm2_of_residual/norm_max_of_residual*norm_max_of_b);\n                    if (options->verbose)\n                        std::cout << \" (new tolerance = \" << tol << \").\\n\";\n\n                    last_norm2_of_residual=norm2_of_residual;\n                    last_norm_max_of_residual=norm_max_of_residual;\n\n                    // call the solver\n                    switch (method) {\n                        case PASO_BICGSTAB:\n                            errorCode = Solver_BiCGStab(A, r, x, &cntIter, &tol, pp);\n                        break;\n                        case PASO_PCG:\n                            errorCode = Solver_PCG(A, r, x, &cntIter, &tol, pp);\n                        break;\n                        case PASO_TFQMR:\n                            tol=tolerance*norm2_of_residual/norm2_of_b;\n                            errorCode = Solver_TFQMR(A, r, x0, &cntIter, &tol, pp);\n                            #pragma omp for private(i) schedule(static)\n                            for (i = 0; i < numEqua; i++) {\n                                x[i]+= x0[i];\n                            }\n                        break;\n                        case PASO_MINRES:\n                            //tol=tolerance*norm2_of_residual/norm2_of_b;\n                            errorCode = Solver_MINRES(A, r, x, &cntIter, &tol, pp);\n                        break;\n                        case PASO_PRES20:\n                            errorCode = Solver_GMRES(A, r, x, &cntIter, &tol, 5, 20, pp);\n                        break;\n                        case PASO_GMRES:\n                            errorCode = Solver_GMRES(A, r, x, &cntIter, &tol, options->truncation, options->restart, pp);\n                        break;\n                    }\n\n                    totIter += cntIter;\n\n                    // error handling\n                    if (errorCode == NoError) {\n                        finalizeIteration = false;\n                    } else if (errorCode == MaxIterReached) {\n                        if (options->verbose)\n                            std::cout << \"Solver: Maximum number of \"\n                                \"iterations reached.\" << std::endl;\n                        break;\n                    } else if (errorCode == InputError) {\n                        if (options->verbose)\n                            std::cout << \"Solver: Internal error!\\n\";\n                        break;\n                    } else if (errorCode == NegativeNormError) {\n                        if (options->verbose)\n                            std::cout << \"Solver: negative energy norm\"\n                               \" (try other solver or preconditioner)!\\n\";\n                        break;\n                    } else if (errorCode == Breakdown) {\n                        if (cntIter <= 1) {\n                            if (options->verbose)\n                                std::cout << \"Solver: Uncurable break \"\n                                    \"down!\" << std::endl;\n                            break;\n                        } else {\n                            if (options->verbose)\n                                std::cout << \"Solver: Breakdown at iter \"\n                                    << totIter << \" (residual = \"\n                                    << tol << \"). Restarting ...\\n\";\n                            finalizeIteration = false;\n                            errorCode = NoError;\n                        }\n                    } else {\n                        if (options->verbose)\n                            std::cout << \"Solver: Generic error in solver!\\n\";\n                        break;\n                    }\n                } else {\n                    if (options->verbose)\n                        std::cout << \" convergence!\" << std::endl;\n                    options->converged = true;\n                }\n            }\n        } // while\n        options->net_time = escript::gettime()-net_time_start;\n        options->num_iter = totIter;\n        A->applyBalanceInPlace(x, false);\n    }\n    delete[] r;\n    delete[] x0;\n    options->time = escript::gettime()-time_iter;\n    Performance_stopMonitor(pp, PERFORMANCE_ALL);\n    return errorCode;\n}\n\nSolverResult Solver(SystemMatrix_ptr<cplx_t> A, cplx_t* x, cplx_t* b, Options* options,\n                    Performance* pp)\n{\n    throw PasoException(\"Solver(): complex not implemented.\");\n}\n\nvoid Solver_free(SystemMatrix<cplx_t>* A)\n{\n    throw PasoException(\"Solver_free(): complex not implemented.\");\n}\n\n} // namespace paso\n\n", "meta": {"hexsha": "7dd0212f3ad60cf663253798072460a935e6764d", "size": 14164, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "paso/src/Solver.cpp", "max_stars_repo_name": "markendr/esys-escript.github.io", "max_stars_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "paso/src/Solver.cpp", "max_issues_repo_name": "markendr/esys-escript.github.io", "max_issues_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "paso/src/Solver.cpp", "max_forks_repo_name": "markendr/esys-escript.github.io", "max_forks_repo_head_hexsha": "0023eab09cd71f830ab098cb3a468e6139191e8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7011494253, "max_line_length": 128, "alphanum_fraction": 0.5132730867, "num_tokens": 3111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631556226292, "lm_q2_score": 0.3665897294020099, "lm_q1q2_score": 0.22276307178727106}}
{"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n *            Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\\n\n *            See LICENSE.txt for details.\n */\n#include \"DavidsonDiagonalizer.h\"\n#include \"IndirectPreconditionerEvaluator.h\"\n#include \"IndirectSigmaVectorEvaluator.h\"\n#include <Utils/IO/Logger.h>\n#include <Eigen/Eigenvalues>\n\nnamespace Scine {\nnamespace Utils {\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nDavidsonDiagonalizer<MatrixType, s>::DavidsonDiagonalizer(int eigenvaluesToCompute, int numberGuessVectors, int totalDimension)\n  : eigenvaluesToCompute_(eigenvaluesToCompute), blockSize_(numberGuessVectors), subspaceDimension_(numberGuessVectors) {\n  assert(eigenvaluesToCompute > 0 &&\n         \"Unintended behaviour: calculate negative amount of eigenvalues in Davidson diagonalizer.\");\n  if (eigenvaluesToCompute_ > blockSize_)\n    throw InvalidDavidsonInputException();\n  initialize(totalDimension);\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::initialize(int dimension) {\n  if (eigenvaluesToCompute_ > dimension) {\n    eigenvaluesToCompute_ = dimension;\n    Utils::Log::warning() << \"Too many eigenvalues requested (\" << eigenvaluesToCompute_ << \"), they were set to \"\n                          << dimension << \".\";\n  }\n  if (subspaceDimension_ > dimension) {\n    subspaceDimension_ = eigenvaluesToCompute_;\n    blockSize_ = subspaceDimension_;\n    Utils::Log::warning() << \"Initial subspace dimension too big (\" << subspaceDimension_ << \"), it was reduced to \"\n                          << eigenvaluesToCompute_ << \".\";\n  }\n  assert(dimension >= blockSize_ && \"Matrix dimension cannot be smaller than number of guess vectors!\");\n  guessVectors_ = Eigen::MatrixXd::Zero(dimension, subspaceDimension_);\n  if (s == DavidsonBalancedType::standard) {\n    guessVectors_.block(0, 0, subspaceDimension_, subspaceDimension_) =\n        Eigen::MatrixXd::Identity(subspaceDimension_, subspaceDimension_);\n  }\n  else {\n    srand(seed_);\n    guessVectors_.block(0, 0, subspaceDimension_, subspaceDimension_) =\n        Eigen::MatrixXd::Random(subspaceDimension_, subspaceDimension_);\n  }\n  maxDimension_ = dimension;\n  maxIterations_ = dimension;\n  sigmaVectorEvaluator_.reset();\n  preconditionerEvaluator_.reset();\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::setMaxIterations(int maxIterations) {\n  maxIterations_ = maxIterations;\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::setMatrixToDiagonalize(const MatrixType& matrix) {\n  if (type_ == DavidsonDirectType::direct) { // if a direct method is in use, no matrix is needed.\n    return;\n  }\n  matrixToDiagonalize_ = matrix;\n  originalDiagonal_ = matrixToDiagonalize_.diagonal();\n  initialize(matrixToDiagonalize_.cols());\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::setGuess(const Eigen::MatrixXd& guessVectors) {\n  guessVectors_ = guessVectors.leftCols(subspaceDimension_);\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::setDavidsonType(DavidsonDirectType type) {\n  type_ = type;\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::setSeed(unsigned seed) {\n  seed_ = seed;\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::setSigmaVectorEvaluator(std::unique_ptr<SigmaVectorEvaluator<MatrixType>>&& evaluator) {\n  sigmaVectorEvaluator_ = std::move(evaluator);\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::setPreconditionerEvaluator(std::unique_ptr<PreconditionerEvaluator>&& evaluator) {\n  preconditionerEvaluator_ = std::move(evaluator);\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nEigenContainer DavidsonDiagonalizer<MatrixType, s>::solve() {\n  checkEvaluators();\n\n  // Set initial size of guess matrix\n  subspaceDimension_ = blockSize_;\n  for (int i = 0; i < maxIterations_; ++i) {\n    performIteration();\n    Log::info() << \"Iteration number: \" << i << \"\\tSubspace dimension: \" << subspaceDimension_ << \".\";\n    if (converged_) { // if full matrix still calculate everything\n      Log::info() << \"Converged in \" << i << \" iterations, dimensionality \" << subspaceDimension_ << \".\";\n      return eigenPairs_;\n    }\n  }\n  throw DavidsonNotConvergedException();\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::performIteration() {\n  // Orthogonalize the projection matrix\n  if (s == DavidsonBalancedType::standard) {\n    orthogonalizeSubspace(guessVectors_);\n    guessVectors_.leftCols(subspaceDimension_).colwise().normalize();\n  }\n\n  const Eigen::MatrixXd& projector = guessVectors_.leftCols(subspaceDimension_);\n  if (s == DavidsonBalancedType::balanced) {\n    for (int i = basisOverlap_.cols(); i < subspaceDimension_; ++i) {\n      basisOverlap_.conservativeResize(subspaceDimension_, subspaceDimension_);\n      basisOverlap_.col(i) = projector.transpose() * projector.col(i);\n      Eigen::VectorXd symmetricRow = basisOverlap_.col(i);\n      basisOverlap_.row(i) = symmetricRow;\n    }\n  }\n\n  Eigen::MatrixXd sigmaMatrix = sigmaVectorEvaluator_->evaluateSigmaVector(projector);\n  Eigen::MatrixXd projectedMatrix = projector.transpose() * sigmaMatrix;\n\n  Eigen::MatrixXd subspaceEVectors;\n  Eigen::VectorXd subspaceEValues;\n\n  if (s == DavidsonBalancedType::standard) {\n    Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> subspaceDiagonalizer(projectedMatrix);\n    subspaceEVectors = subspaceDiagonalizer.eigenvectors();\n    subspaceEValues = subspaceDiagonalizer.eigenvalues();\n  }\n  else if (s == DavidsonBalancedType::balanced) {\n    Eigen::GeneralizedSelfAdjointEigenSolver<Eigen::MatrixXd> subspaceDiagonalizer(projectedMatrix, basisOverlap_);\n    subspaceEVectors = subspaceDiagonalizer.eigenvectors();\n    subspaceEValues = subspaceDiagonalizer.eigenvalues();\n  }\n\n  // Check convergence:\n  // Get a matrix with the first *eigenvaluesToCompute_* residual vectors as column.\n  // basically, it calculated r_k = H*Psi_{k, approx} - h_k*Psi_{k, approx}\n  // = (sigmaMatrix - h_k * bMatrix) * v_k\n  // H: matrix to diagonalize\n  // Psi_{k, approx} k-th approximated Ritz eigenvectors for the subspace\n  // h_k: k-th approximated Ritz eigenvalue\n  // sigmaMatrix: matrix with as columns the sigma vectors\n  // bMatrix: matrix with as column the tentative vectors\n  // v_k: k-th subspace eigenvector\n  Eigen::MatrixXd residualVectors(sigmaMatrix.rows(), eigenvaluesToCompute_);\n  for (int col = 0; col < eigenvaluesToCompute_; ++col) {\n    residualVectors.col(col) = (sigmaMatrix - subspaceEValues(col) * projector) * subspaceEVectors.col(col);\n  }\n\n  Eigen::VectorXd residualNorms = residualVectors.colwise().norm();\n  converged_ = true;\n  for (int i = 0; i < residualNorms.size(); ++i) {\n    if (residualNorms(i) > eigenvalueTol)\n      converged_ = false;\n  }\n  if (converged_) {\n    eigenPairs_ = {subspaceEValues.head(eigenvaluesToCompute_), projector * subspaceEVectors.leftCols(eigenvaluesToCompute_)};\n    return;\n  }\n  expandSubspace(subspaceEValues, residualVectors, projector, residualNorms);\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::expandSubspace(const Eigen::VectorXd& subspaceEValues,\n                                                         const Eigen::MatrixXd& residualVectors, const Eigen::MatrixXd& projector,\n                                                         const Eigen::VectorXd& residualNorms) {\n  // look at each residual vector\n  for (int i = 0; i < eigenvaluesToCompute_; ++i) {\n    if (residualNorms(i) > eigenvalueTol) {\n      Eigen::VectorXd correctionVector =\n          residualVectors.col(i).cwiseProduct(-preconditionerEvaluator_->evaluate(subspaceEValues(i)));\n      if (s == DavidsonBalancedType::standard) {\n        Eigen::VectorXd orthogonalizedCorrectionVector(guessVectors_.rows());\n        orthogonalizedCorrectionVector = orthogonalizeToSubspace(correctionVector.normalized(), projector);\n\n        if (orthogonalizedCorrectionVector.norm() / correctionVector.norm() > /*correctionTol*/ 1e-3) {\n          if (subspaceDimension_ < maxDimension_) {\n            ++subspaceDimension_;\n            guessVectors_.conservativeResize(Eigen::NoChange, subspaceDimension_);\n            guessVectors_.col(subspaceDimension_ - 1) = orthogonalizedCorrectionVector.normalized();\n          }\n        }\n      }\n      else {\n        if (subspaceDimension_ < maxDimension_) {\n          ++subspaceDimension_;\n          guessVectors_.conservativeResize(Eigen::NoChange, subspaceDimension_);\n          guessVectors_.col(subspaceDimension_ - 1) = correctionVector;\n        }\n      }\n    }\n  }\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::checkEvaluators() {\n  if (!sigmaVectorEvaluator_ || !preconditionerEvaluator_) {\n    switch (type_) {\n      case DavidsonDirectType::standard:\n        setSigmaVectorEvaluator(std::make_unique<IndirectSigmaVectorEvaluator<MatrixType>>(matrixToDiagonalize_));\n        setPreconditionerEvaluator(std::make_unique<IndirectPreconditionerEvaluator>(originalDiagonal_));\n        break;\n      case DavidsonDirectType::direct:\n        throw InvalidSigmaVectorEvaluator();\n      default:\n        throw InvalidDavidsonTypeException();\n    }\n  }\n}\n\ntemplate<class MatrixType, DavidsonBalancedType s>\nvoid DavidsonDiagonalizer<MatrixType, s>::orthogonalizeSubspace(Eigen::MatrixXd& trialSpace) {\n  int spaceDimension = trialSpace.rows();\n  // Calculate modified Gram-Schmidt QR decomposition\n  Eigen::MatrixXd Q(spaceDimension, subspaceDimension_);\n  Eigen::MatrixXd R(subspaceDimension_, subspaceDimension_);\n\n  for (int i = 0; i < subspaceDimension_; ++i) {\n    R(i, i) = trialSpace.col(i).norm();\n    Q.col(i) = trialSpace.col(i) / R(i, i);\n    for (int j = i + 1; j < subspaceDimension_; ++j) {\n      R(i, j) = Q.col(i).transpose() * trialSpace.col(j);\n      trialSpace.col(j) -= Q.col(i) * R(i, j);\n    }\n  }\n}\ntemplate<class MatrixType, DavidsonBalancedType s>\nEigen::VectorXd DavidsonDiagonalizer<MatrixType, s>::orthogonalizeToSubspace(const Eigen::VectorXd& vector,\n                                                                             const Eigen::MatrixXd& subspace) const {\n  Eigen::VectorXd orthonormalizedVector = vector;\n  for (int basis = 0; basis < subspace.cols(); ++basis) {\n    orthonormalizedVector -= subspace.col(basis).dot(vector) * subspace.col(basis) / subspace.col(basis).norm();\n  }\n  return orthonormalizedVector;\n}\n\ntemplate class DavidsonDiagonalizer<Eigen::MatrixXd>;\ntemplate class DavidsonDiagonalizer<Eigen::SparseMatrix<double>>;\ntemplate class DavidsonDiagonalizer<Eigen::MatrixXd, DavidsonBalancedType::balanced>;\ntemplate class DavidsonDiagonalizer<Eigen::SparseMatrix<double>, DavidsonBalancedType::balanced>;\n\n} // namespace Utils\n} // namespace Scine\n", "meta": {"hexsha": "75fbcff9c9008e433dd3ae9d60944ad0282c1b43", "size": 11041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Math/IterativeDiagonalizer/DavidsonDiagonalizer.cpp", "max_stars_repo_name": "DockBio/utilities", "max_stars_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Utils/Math/IterativeDiagonalizer/DavidsonDiagonalizer.cpp", "max_issues_repo_name": "DockBio/utilities", "max_issues_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/Utils/Math/IterativeDiagonalizer/DavidsonDiagonalizer.cpp", "max_forks_repo_name": "DockBio/utilities", "max_forks_repo_head_hexsha": "213ed5ac2a64886b16d0fee1fcecb34d36eea9e9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.9610894942, "max_line_length": 130, "alphanum_fraction": 0.7251154787, "num_tokens": 2651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.2227592624797091}}
{"text": "/*=========================================================================\n *\n *   Program:   Bifurcation Analysis Library\n *   Module:    main.cpp\n *\n *   Copyright (C) 2009 Daniele Linaro\n *\n *   This program is free software: you can redistribute it and/or modify\n *   it under the terms of the GNU General Public License as published by\n *   the Free Software Foundation, either version 3 of the License, or\n *   (at your option) any later version.\n *   \n *   This program is distributed in the hope that it will be useful,\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *   GNU General Public License for more details.\n *   \n *   You should have received a copy of the GNU General Public License\n *   along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n *=========================================================================*/\n\n#include <unistd.h>\n#include <iostream>\n#include <cstdlib>\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\nusing boost::property_tree::ptree;\n\n#include <nvector/nvector_serial.h>\n\n#include \"balCommon.h\"\n#include \"balParameters.h\"\n#include \"balLogger.h\"\n#include \"balODESolver.h\"\n#include \"balBifurcationDiagram.h\"\n#include \"balBifurcationParameters.h\"\n#include \"balPLL.h\"\nusing namespace bal;\n\nconst realtype pi = 3.1415926535897931;\n\nint main(int argc, char *argv[]) {\n  if(argc == 1) {\n    fprintf(stderr, \"Usage: %s ConfigFile\\n\", argv[0]);\n    exit(1);\n  }\n  ptree config;\n  read_xml(argv[1], config);\n  char name[100];\n  \n  int steps[PLL::npar];\n  BifurcationParameters * bp = BifurcationParameters::Create();\n  bp->SetNumber(PLL::npar);\n  \n  for(int i=0; i<PLL::npar; i++) {\n    sprintf(name,\"pll.%s.steps\",PLL::parname[i]);\n    steps[i] = config.get<int>(name);\n    if(steps[i] == 1) {\n      sprintf(name,\"pll.%s.min\",PLL::parname[i]);\n      bp->SetIthParameter(i,config.get<double>(name));\n    }\n    else {\n      sprintf(name,\"pll.%s.min\",PLL::parname[i]);\n      bp->SetIthParameterLowerBound(i,config.get<double>(name));\n      sprintf(name,\"pll.%s.max\",PLL::parname[i]);\n      bp->SetIthParameterUpperBound(i,config.get<double>(name));\n    }\n  }\n  \n#ifdef WITHPHIERR\n#ifdef EXTEND\n  realtype x0[7] = {0.,0.,0.,0.,pi,0.,0.};\n#else\n  realtype x0[5] = {0.,0.,0.,0.,pi};\n#endif\n#else\n#ifdef EXTEND\n  realtype x0[6] = {0.,0.,0.,0.,0.,0.};\n#else\n  realtype x0[4] = {0.,0.,0.,0.};\n#endif\n#endif\n  x0[1] = config.get<double>(\"pll.vdd.min\");\t\n  \n  bp->SetNumberOfSteps(steps);\n  PLL * pll = PLL::Create();\n  pll->SetParameters(bp);\n  BifurcationDiagram * bifd = BifurcationDiagram::Create();\n  bifd->RestartFromX0(true);\n  bifd->SetDynamicalSystem(pll);\n  bifd->SetFilename((char *) config.get<std::string>(\"simulation.outputfile\").c_str());\n  if(config.get<bool>(\"simulation.trajectory\"))\n    bifd->GetODESolver()->SetIntegrationMode(BOTH);\n  else\n    bifd->GetODESolver()->SetIntegrationMode(EVENTS);\n  bifd->GetODESolver()->SetTransientDuration(config.get<double>(\"simulation.ttran\"));\n  bifd->GetODESolver()->HaltAtEquilibrium(false);\n  bifd->GetODESolver()->HaltAtCycle(false);\n  bifd->GetODESolver()->SetFinalTime(config.get<double>(\"simulation.tout\"));\n  bifd->GetODESolver()->SetTimeStep(1e-11);\n  bifd->GetODESolver()->SetMaxNumberOfIntersections((int) 1e7);\n  bifd->GetODESolver()->SetX0(x0);\n  bifd->GetODESolver()->SetRelativeTolerance(1e-10);\n  bifd->SetNumberOfThreads(1);\n  bifd->ComputeDiagram();\n  bifd->Destroy();\n  pll->Destroy();\n  bp->Destroy();\n  \n  return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "b622036dd42e0183f4feffd33459c4f76bf84911", "size": 3584, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pll.cpp", "max_stars_repo_name": "danielelinaro/BAL", "max_stars_repo_head_hexsha": "d735048d9962a0c424c29db93f774494c67b12a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-02T22:30:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-02T22:30:37.000Z", "max_issues_repo_path": "examples/pll.cpp", "max_issues_repo_name": "danielelinaro/BAL", "max_issues_repo_head_hexsha": "d735048d9962a0c424c29db93f774494c67b12a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/pll.cpp", "max_forks_repo_name": "danielelinaro/BAL", "max_forks_repo_head_hexsha": "d735048d9962a0c424c29db93f774494c67b12a9", "max_forks_repo_licenses": ["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.1652173913, "max_line_length": 87, "alphanum_fraction": 0.6512276786, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.22270471038272133}}
{"text": "//\n//  synthetic_data_helper.cpp\n//  synthetic_data_helper\n//\n//  Created by Cristián Garay on 10/15/16.\n//  Copyright © 2016 Cristian Garay. All rights reserved.\n//\n\n#define NPY_NO_DEPRECATED_API NPY_1_11_API_VERSION\n\n#include <iostream>\n#include <stdint.h>\n#include <alloca.h>\n#include <Eigen/Core>\n#include <boost/python.hpp>\n#include <boost/python/numeric.hpp>\n#include <boost/python/ptr.hpp>\n#include <Python.h>\n#include <numpy/ndarrayobject.h>\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace boost::python;\n\n#if PY_VERSION_HEX >= 0x03000000\nvoid *\n#else\nvoid\n#endif\ninit_numpy(){\n    //Py_Initialize;\n    import_array();\n}\n\nstruct double_to_python_float\n{\n    static PyObject* convert(double const& d)\n      {\n        return boost::python::incref(\n          boost::python::object(d).ptr());\n      }\n};\n\n//numpy scalar converters.\ntemplate <typename T, NPY_TYPES NumPyScalarType>\nstruct enable_numpy_scalar_converter\n{\n  enable_numpy_scalar_converter()\n  {\n    // Required NumPy call in order to use the NumPy C API within another\n    // extension module.\n    // import_array();\n    init_numpy();\n\n    boost::python::converter::registry::push_back(\n      &convertible,\n      &construct,\n      boost::python::type_id<T>());\n  }\n\n  static void* convertible(PyObject* object)\n  {\n    // The object is convertible if all of the following are true:\n    // - is a valid object.\n    // - is a numpy array scalar.\n    // - its descriptor type matches the type for this converter.\n    return (\n      object &&                                                    // Valid\n      PyArray_CheckScalar(object) &&                               // Scalar\n      PyArray_DescrFromScalar(object)->type_num == NumPyScalarType // Match\n    )\n      ? object // The Python object can be converted.\n      : NULL;\n  }\n\n  static void construct(\n    PyObject* object,\n    boost::python::converter::rvalue_from_python_stage1_data* data)\n  {\n    // Obtain a handle to the memory block that the converter has allocated\n    // for the C++ type.\n    namespace python = boost::python;\n    typedef python::converter::rvalue_from_python_storage<T> storage_type;\n    void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;\n\n    // Extract the array scalar type directly into the storage.\n    PyArray_ScalarAsCtype(object, storage);\n\n    // Set convertible to indicate success.\n    data->convertible = storage;\n  }\n};\n\ndict create_synthetic_data(dict& model, numeric::array& starts, numeric::array& lengths, numeric::array& resources){\n    //TODO: check if parameters are null.\n    //TODO: check that dicts have the required members.\n    //TODO: check that all parameters have the right sizes.\n    //TODO: i'm not sending any error messages.\n    \n    numeric::array learns = extract<numeric::array>(model[\"learns\"]);\n    int num_resources = len(learns);\n\n    numeric::array forgets = extract<numeric::array>(model[\"forgets\"]);\n    numeric::array guesses = extract<numeric::array>(model[\"guesses\"]);\n    \n    numeric::array slips = extract<numeric::array>(model[\"slips\"]);\n    int num_subparts = len(slips);\n    \n    Vector2d initial_distn;\n    double prior = extract<double>(model[\"prior\"]);\n    initial_distn << 1-prior, prior;\n    \n    MatrixXd As(2, 2*num_resources);\n    for (int n=0; n<num_resources; n++) {\n        double learn = extract<double>(learns[n]);\n        double forget = extract<double>(forgets[n]);\n        As.col(2*n) << 1-learn, learn;\n        As.col(2*n+1) << forget, 1-forget;\n    }\n    \n    int num_sequences = len(starts);\n    \n    int64_t bigT = 0;\n    for (int k=0; k<num_sequences; k++) {\n        bigT += extract<int64_t>(lengths[k]); //extract this as int??\n    }\n    \n    //// outputs\n    int all_stateseqs[1][bigT]; //used to be int8_t\n    int all_data[num_subparts][bigT]; //used to be int8_t\n    all_data[0][0] = 0;\n    dict result;\n    \n    /* COMPUTATION */\n    \n    for (int sequence_index=0; sequence_index < num_sequences; sequence_index++) {\n        int64_t sequence_start = extract<int64_t>(starts[sequence_index]) - 1; //should i extract these as ints?\n        int64_t T = extract<int64_t>(lengths[sequence_index]);\n        \n        Vector2d nextstate_distr = initial_distn;\n\n        for (int t=0; t<T; t++) {\n            all_stateseqs[0][sequence_start + t] = nextstate_distr(0) < ((double) rand()) / ((double) RAND_MAX); //always all_stateseqs[0]?\n            for (int n=0; n<num_subparts; n++) {\n                all_data[n][sequence_start+t] = ((all_stateseqs[0][sequence_start + t]) ? extract<double>(slips[n]) : (1-extract<double>(guesses[n]))) < (((double) rand()) / ((double) RAND_MAX));\n            }\n            \n            nextstate_distr = As.col(2*(extract<int64_t>(resources[sequence_start + t])-1)+all_stateseqs[0][sequence_start + t]); //extract int is right??\n        }\n    }\n    \n    //wrapping results in numpy objects.\n    npy_intp all_stateseqs_dims[2] = {1, bigT}; //just put directly this array into the PyArray_SimpleNewFromData function?\n    PyObject * all_stateseqs_pyObj = PyArray_SimpleNewFromData(2, all_stateseqs_dims, NPY_INT, all_stateseqs); //this should be NPY_INT8.\n    boost::python::handle<> all_stateseqs_handle( all_stateseqs_pyObj );\n    boost::python::numeric::array all_stateseqs_handle_arr( all_stateseqs_handle );\n    \n    npy_intp all_data_dims[2] = {num_subparts, bigT}; //just put directly this array into the PyArray_SimpleNewFromData function?\n    PyObject * all_data_pyObj = PyArray_SimpleNewFromData(2, all_data_dims, NPY_INT, all_data); //this should be NPY_INT8.\n    boost::python::handle<> all_data_handle( all_data_pyObj );\n    boost::python::numeric::array all_data_arr( all_data_handle );\n    \n    result[\"stateseqs\"] = all_stateseqs_handle_arr;\n    result[\"data\"] = all_data_arr;\n    return(result);\n    \n}\n\nBOOST_PYTHON_MODULE(synthetic_data_helper){\n    //import_array();\n    init_numpy();\n    /*if(PyArray_API == NULL)\n\t{\n\t    import_array();\n\t}*/\n    numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n    to_python_converter<double, double_to_python_float>();\n    enable_numpy_scalar_converter<boost::int8_t, NPY_INT8>();\n    enable_numpy_scalar_converter<boost::int16_t, NPY_INT16>();\n    enable_numpy_scalar_converter<boost::int32_t, NPY_INT32>();\n    enable_numpy_scalar_converter<boost::int64_t, NPY_INT64>();\n    \n    def(\"create_synthetic_data\", create_synthetic_data);\n    \n}", "meta": {"hexsha": "1d3519414b0207a33498878535bb7762cdacbaca", "size": 6385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "generate/synthetic_data_helper.cpp", "max_stars_repo_name": "rachelcusack/pyBKT", "max_stars_repo_head_hexsha": "af10442bcffcdd2dcbdd9ee7e437b81a002a55f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "generate/synthetic_data_helper.cpp", "max_issues_repo_name": "rachelcusack/pyBKT", "max_issues_repo_head_hexsha": "af10442bcffcdd2dcbdd9ee7e437b81a002a55f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generate/synthetic_data_helper.cpp", "max_forks_repo_name": "rachelcusack/pyBKT", "max_forks_repo_head_hexsha": "af10442bcffcdd2dcbdd9ee7e437b81a002a55f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5135135135, "max_line_length": 195, "alphanum_fraction": 0.6662490211, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565327, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22266022163880617}}
{"text": "/// @file DeconvolverEntropy.tcc\n/// @brief Class for a deconvolver based on entropy or min L1 norm\n/// @details This concrete class defines a deconvolver used to estimate an\n/// image from a residual image, psf optionally using a weights image.\n/// @ingroup Deconvolver\n///\n/// @copyright (c) 2007 CSIRO\n/// Australia Telescope National Facility (ATNF)\n/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n/// PO Box 76, Epping NSW 1710, Australia\n/// atnf-enquiries@csiro.au\n///\n/// This file is part of the ASKAP software distribution.\n///\n/// The ASKAP software distribution is free software: you can redistribute it\n/// and/or modify it under the terms of the GNU General Public License as\n/// published by the Free Software Foundation; either version 2 of the License,\n/// or (at your option) any later version.\n///\n/// This program is distributed in the hope that it will be useful,\n/// but WITHOUT ANY WARRANTY; without even the implied warranty of\n/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n/// GNU General Public License for more details.\n///\n/// You should have received a copy of the GNU General Public License\n/// along with this program; if not, write to the Free Software\n/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA\n///\n/// @author Tim Cornwell <tim.cornwell@csiro.au>\n///\n\n#include <string>\n\n#include <casacore/casa/aips.h>\n#include <casacore/casa/Arrays/Array.h>\n#include <casacore/casa/Arrays/ArrayMath.h>\n#include <boost/shared_ptr.hpp>\n#include <askap/AskapLogging.h>\nASKAP_LOGGER(decentropylogger, \".deconvolution.entropy\");\n\n#include <deconvolution/DeconvolverEntropy.h>\n#include <deconvolution/EntropyBase.h>\n#include <deconvolution/EntropyI.h>\n#include <deconvolution/Emptiness.h>\n\nusing namespace casa;\n\nnamespace askap {\n\n    namespace synthesis {\n\n        /// @brief Class for a deconvolver based on the Entropy algorithm of Cornwell and Evans\n        /// @details This base class defines a deconvolver used to estimate an\n        /// image from a residual image, psf optionally using a weights image.\n        /// The template argument T is the type, and FT is the transform\n        /// e.g. DeconvolverEntropy<Double, DComplex>\n        /// @ingroup Deconvolver\n\n        template<class T, class FT>\n        DeconvolverEntropy<T, FT>::~DeconvolverEntropy()\n        {\n        };\n\n        template<class T, class FT>\n        DeconvolverEntropy<T, FT>::DeconvolverEntropy(Vector<Array<T> >& dirty, Vector<Array<T> >& psf)\n                : DeconvolverBase<T, FT>::DeconvolverBase(dirty, psf)\n        {\n            if (this->itsNumberDirtyTerms > 1) {\n                throw(AskapError(\"Entropy deconvolver cannot perform multi-term deconvolutions\"));\n            }\n        };\n\n        template<class T, class FT>\n        DeconvolverEntropy<T, FT>::DeconvolverEntropy(Array<T>& dirty, Array<T>& psf)\n                : DeconvolverBase<T, FT>::DeconvolverBase(dirty, psf)\n        {\n        };\n        template<class T, class FT>\n        void DeconvolverEntropy<T, FT>::finalise()\n        {\n            // Find residuals for current model model\n            this->updateResiduals(this->itsModel);\n        }\n\n        template<class T, class FT>\n        void DeconvolverEntropy<T, FT>::initialise()\n        {\n            DeconvolverBase<T, FT>::initialise();\n\n            // Set the initial value of Q\n            T Q;\n            Q = sum(this->psf()(this->psf() > T(0.1)));\n            ASKAPLOG_INFO_STR(decentropylogger, \"Initial value of Q = \" << Q << \" pixels\");\n\n            this->itsEntropy->setQ(Q);\n        }\n\n        // This is basically the algorithm described in the Cornwell-Evans paper of 1985, with\n        // some improvements as suggested by Bob Sault.\n        template<class T, class FT>\n        bool DeconvolverEntropy<T, FT>::deconvolve()\n        {\n            this->initialise();\n\n            ASKAPLOG_INFO_STR(decentropylogger, \"Performing Entropy deconvolution for \"\n                                  << this->control()->targetIter() << \" iterations\");\n\n            ASKAPLOG_INFO_STR(decentropylogger, \"Target rms fit = \"\n                                  << this->control()->targetObjectiveFunction() << \" Jy/beam\");\n\n            uInt numberPixels = this->itsModel.shape().product();\n            T targetChisq = square(this->control()->targetObjectiveFunction()) * numberPixels;\n            T chisq;\n\n            Array<T> trialModel(this->model().shape());\n            trialModel.set(T(0.0));\n\n            this->updateResiduals(this->model());\n\n            T lipschitz(10.0);\n\n            this->model() = this->dirty().copy() / lipschitz;\n\n            Array<T> step(this->model().shape());\n            step.set(T(0.0));\n\n            T absPeakVal(max(abs(this->dirty())));\n            T peakSidelobe(0.1);\n            T aFit = max(peakSidelobe * absPeakVal, rms(this->dirty())) / lipschitz;\n            ASKAPLOG_INFO_STR(decentropylogger, \"Scaling = \" << aFit << \" Jy/pixel\");\n            this->itsEntropy->setScale(aFit);\n\n            this->model().set(aFit);\n\n            this->updateResiduals(this->model());\n\n            do {\n                // Find the current fit\n                chisq = sum(square(this->dirty()));\n\n                Matrix<T> GDG(this->itsEntropy->formGDGStep(this->model(), this->dirty(), step));\n\n                // Check to see if Alpha and Beta need to be initialised. If so then we need to\n                // do so and recalculate the gradients and step\n                if (this->itsEntropy->initialiseAlphaBeta(GDG)) {\n                    GDG = this->itsEntropy->formGDGStep(this->model(), this->dirty(), step);\n                }\n\n                T flux = sum(this->model());\n                this->itsEntropy->changeAlphaBeta(GDG, targetChisq, chisq, this->control()->targetFlux(), flux);\n\n                // Now find the normalised gradient - we will use this to limit the step taken\n                T length(this->itsEntropy->formLength(GDG));\n                if (length <= T(0.0)) {\n                    length = GDG(F, F);\n                }\n                T normGrad = GDG(J, J) / length;\n\n                //        relaxMin();\n\n                // We limit the step to less than the tolerance e.g. 0.1 so that the\n                // quadratic approximation in the Newton-Raphson is still valid.\n                T scale = 1.0;\n                T scalem = 1.0;\n                if (normGrad > 0.0) {\n                    scalem = this->control()->tolerance() / normGrad;\n                }\n                scale = min(T(1.0), scalem);\n\n                // OK - now we take the proposed step and evaluate the\n                // gradient there.\n                trialModel = this->model() + scale * step;\n\n                // Calculate residual for this new trial image\n                this->updateResiduals(trialModel);\n                chisq = sum(square(this->dirty()));\n\n                // Form the scalar Gradient . Step at this new location. Ideally this should be\n                // zero. Once we know the value of the gradient initially and for the trial image, we\n                // can determine the optimal step by interpolating the gradient to zero. Ideally the\n                // step should be O(1) times the original step\n                T eps = 1.0;\n                T gradDotStep0 = GDG(J, J);\n                T gradDotStep1(this->itsEntropy->formGDS(this->model(), this->dirty(), step));\n\n                if (gradDotStep0 != gradDotStep1) {\n                    eps = gradDotStep0 / (gradDotStep0 - gradDotStep1);\n                }\n                if (scale != T(0.0)) eps = min(eps, T(scalem / scale));\n                if (eps <= T(0.0)) {\n                    eps = T(1.0);\n                }\n\n                // Step to optimum point\n                this->model() = this->model() + scale * eps * step;\n\n                // Recalculate residual for the new image\n                this->updateResiduals(this->model());\n\n                chisq = sum(square(this->dirty()));\n\n                // readjust beam volume\n                //      itsQ = itsQ*(T(1.0)/max(T(0.5), min(T(2.0),eps))+T(1.0))/T(2.0);\n\n                flux = sum(this->model());\n                this->itsEntropy->changeAlphaBeta(GDG, targetChisq, chisq, this->control()->targetFlux(), flux);\n\n                absPeakVal = max(abs(this->dirty()));\n\n                T lipschitz(10.0);\n\n                aFit = max(peakSidelobe * absPeakVal, rms(this->dirty())) / lipschitz;\n                ASKAPLOG_INFO_STR(decentropylogger, \"Scaling = \" << aFit << \" Jy/pixel\");\n                this->itsEntropy->setScale(aFit);\n\n                this->state()->setPeakResidual(absPeakVal);\n                this->state()->setObjectiveFunction(sqrt(chisq / numberPixels));\n                this->state()->setTotalFlux(flux);\n\n                this->monitor()->monitor(*(this->state()));\n                this->state()->incIter();\n            } while (!this->control()->terminate(*(this->state())));\n\n            ASKAPLOG_INFO_STR(decentropylogger, \"Performed Entropy deconvolution for \"\n                                  << this->state()->currentIter() << \" iterations\");\n\n            ASKAPLOG_INFO_STR(decentropylogger, this->control()->terminationString());\n\n            this->finalise();\n\n            return True;\n        }\n\n        template<class T, class FT>\n        void DeconvolverEntropy<T, FT>::configure(const LOFAR::ParameterSet& parset)\n        {\n            DeconvolverBase<T, FT>::configure(parset);\n\n            String algorithm(parset.getString(\"algorithm\", \"Emptiness\"));\n            this->control()->setAlgorithm(algorithm);\n\n            if (algorithm == \"EntropyI\") {\n                ASKAPLOG_INFO_STR(decentropylogger, \"Maximising information entropy of model image\");\n                itsEntropy = boost::shared_ptr<EntropyBase<T> >(new EntropyI<T>());\n                itsEntropy->setTolerance(parset.getFloat(\"tolerance\", 0.3));\n            } else {\n                ASKAPLOG_INFO_STR(decentropylogger, \"Maximising emptiness (negative L1 norm) of model image\");\n                itsEntropy = boost::shared_ptr<EntropyBase<T> >(new Emptiness<T>());\n                itsEntropy->setTolerance(parset.getFloat(\"tolerance\", 0.3));\n            }\n        }\n\n    } // namespace synthesis\n\n} // namespace askap\n", "meta": {"hexsha": "8a79ba447006e189e20c78900b96a8b1d975e796", "size": 10311, "ext": "tcc", "lang": "C++", "max_stars_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverEntropy.tcc", "max_stars_repo_name": "rtobar/askapsoft", "max_stars_repo_head_hexsha": "6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-18T08:37:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:37:43.000Z", "max_issues_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverEntropy.tcc", "max_issues_repo_name": "ATNF/askapsoft", "max_issues_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Components/Synthesis/synthesis/current/deconvolution/DeconvolverEntropy.tcc", "max_forks_repo_name": "ATNF/askapsoft", "max_forks_repo_head_hexsha": "d839c052d5c62ad8a511e58cd4b6548491a6006f", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "OpenSSL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.27734375, "max_line_length": 112, "alphanum_fraction": 0.5729803123, "num_tokens": 2423, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.22266022163880614}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <qle/models/crossassetanalytics.hpp>\n#include <qle/models/crossassetmodel.hpp>\n\n#include <ql/math/matrixutilities/pseudosqrt.hpp>\n#include <ql/processes/eulerdiscretization.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantExt {\n\nusing namespace CrossAssetAnalytics;\nusing namespace QuantLib;\n\nnamespace {\ninline void setValue(Matrix& m, const Real& value, const QuantExt::CrossAssetModel* model,\n                     const QuantExt::CrossAssetModelTypes::AssetType& t1, const Size& i1,\n                     const QuantExt::CrossAssetModelTypes::AssetType& t2, const Size& i2, const Size& offset1 = 0,\n                     const Size& offset2 = 0) {\n    Size i = model->pIdx(t1, i1, offset1);\n    Size j = model->pIdx(t2, i2, offset2);\n    m[i][j] = m[j][i] = value;\n}\ninline void setValue(Array& a, const Real& value, const QuantExt::CrossAssetModel* model,\n                     const QuantExt::CrossAssetModelTypes::AssetType& t, const Size& i, const Size& offset = 0) {\n    a[model->pIdx(t, i, offset)] = value;\n}\n} // anonymous namespace\n\nCrossAssetStateProcess::CrossAssetStateProcess(const CrossAssetModel* const model, discretization disc,\n                                               SalvagingAlgorithm::Type salvaging)\n    : StochasticProcess(), model_(model), disc_(disc), salvaging_(salvaging), cirppCount_(0) {\n\n    updateSqrtCorrelation();\n    if (disc_ == euler) {\n        discretization_ = boost::make_shared<EulerDiscretization>();\n    } else {\n        discretization_ = boost::make_shared<CrossAssetStateProcess::ExactDiscretization>(model, salvaging);\n    }\n\n    // set up CR CIR++ processes, defer the euler discretisation check to evolve()\n    for (Size i = 0; i < model_->components(CR); ++i) {\n        if (model_->modelType(CR, i) == CIRPP) {\n            crCirpp_.push_back(model->crcirppModel(i)->stateProcess());\n            cirppCount_++;\n        } else {\n            crCirpp_.push_back(boost::shared_ptr<CrCirppStateProcess>());\n        }\n    }\n}\n\nSize CrossAssetStateProcess::size() const { return model_->dimension(); }\n\nvoid CrossAssetStateProcess::flushCache() const {\n    cache_m_.clear();\n    cache_md_.clear();\n    cache_v_.clear();\n    cache_d_.clear();\n    boost::shared_ptr<CrossAssetStateProcess::ExactDiscretization> tmp =\n        boost::dynamic_pointer_cast<CrossAssetStateProcess::ExactDiscretization>(discretization_);\n    if (tmp != NULL) {\n        tmp->flushCache();\n    }\n    updateSqrtCorrelation();\n}\n\nvoid CrossAssetStateProcess::updateSqrtCorrelation() const {\n    if (disc_ != euler)\n        return;\n    // build sqrt corr (for correlation matrix that covers all state variables)\n    // this can be simplified once we use as many brownians as model->brownians()\n    // instead of the full state vector\n    Matrix corr(model_->dimension(), model_->dimension(), 1.0);\n    Size brownianIndex = 0;\n    std::vector<Size> brownianIndices;\n    for (Size t = 0; t < crossAssetModelAssetTypes; ++t) {\n        AssetType assetType = AssetType(t);\n        for (Size i = 0; i < model_->components(assetType); ++i) {\n\n            // 3 possibilities for number of state variables vs. the number of Brownian motions for the i-th component\n            // within the current asset type.\n            // 1) They are equal. Make the assumption that there is a 1-1 correspondence. This is essentially what has\n            //    been happening until now outside of DK model i.e. always 1 state var and 1 Brownian motion.\n            // 2) number of state vars > number of Brownian motions. Happens with DK model. Think the code below will\n            //    only work when number of Brownian motions equals 1. Not changing it as not sure what was intended.\n            // 3) number of state vars < number of Brownian motions. Not covered below.\n            auto brownians = model_->brownians(assetType, i);\n            auto stateVars = model_->stateVariables(assetType, i);\n\n            if (brownians == stateVars) {\n                for (Size k = 0; k < brownians; ++k) {\n                    brownianIndices.push_back(brownianIndex++);\n                }\n            } else {\n                for (Size j = 0; j < brownians; ++j) {\n                    for (Size k = 0; k < stateVars; ++k) {\n                        brownianIndices.push_back(brownianIndex);\n                    }\n                    ++brownianIndex;\n                }\n            }\n        }\n    }\n    for (Size i = 0; i < corr.rows(); ++i) {\n        for (Size j = 0; j < i; ++j) {\n            corr[i][j] = corr[j][i] = model_->correlation()(brownianIndices[i], brownianIndices[j]);\n        }\n    }\n\n    sqrtCorrelation_ = pseudoSqrt(corr, salvaging_);\n}\n\nDisposable<Array> CrossAssetStateProcess::initialValues() const {\n    Array res(model_->dimension(), 0.0);\n    /* irlgm1f processes have initial value 0 */\n    for (Size i = 0; i < model_->components(FX); ++i) {\n        /* fxbs processes are in log spot */\n        res[model_->pIdx(FX, i, 0)] = std::log(model_->fxbs(i)->fxSpotToday()->value());\n    }\n    for (Size i = 0; i < model_->components(EQ); ++i) {\n        /* eqbs processes are in log spot */\n        res[model_->pIdx(EQ, i, 0)] = std::log(model_->eqbs(i)->eqSpotToday()->value());\n    }\n    // CR CIR++ components\n    for (Size i = 0; i < model_->components(CR); ++i) {\n        if (model_->modelType(CR, i) != CIRPP)\n            continue;\n        QL_REQUIRE(crCirpp_[i], \"crcirpp is null!\");\n        Array r = crCirpp_[i]->initialValues();\n        res[model_->pIdx(CR, i, 0)] = r[0]; // y0\n        res[model_->pIdx(CR, i, 1)] = r[1]; // S(0,0) = 1\n    }\n\n    for (Size i = 0; i < model_->components(INF); ++i) {\n        // Second component of JY model is the inflation index process.\n        if (model_->modelType(INF, i) == JY) {\n            res[model_->pIdx(INF, i, 1)] = std::log(model_->infjy(i)->index()->fxSpotToday()->value());\n        }\n    }\n    /* infdk, crlgm1f, aux processes have initial value 0 */\n    return res;\n}\n\nDisposable<Array> CrossAssetStateProcess::drift(Time t, const Array& x) const {\n    Array res(model_->dimension(), 0.0);\n    Size n = model_->components(IR);\n    Size n_eq = model_->components(EQ);\n    Real H0 = model_->irlgm1f(0)->H(t);\n    Real Hprime0 = model_->irlgm1f(0)->Hprime(t);\n    Real alpha0 = model_->irlgm1f(0)->alpha(t);\n    Real zeta0 = model_->irlgm1f(0)->zeta(t);\n    boost::unordered_map<double, Array>::const_iterator i = cache_m_.find(t);\n    if (i == cache_m_.end()) {\n        /* z0 has drift 0 in the LGM measure but non-zero drift in the bank account measure, so start loop at i = 0 */\n        for (Size i = 0; i < n; ++i) {\n            Real Hi = model_->irlgm1f(i)->H(t);\n            Real alphai = model_->irlgm1f(i)->alpha(t);\n            if (i == 0 && model_->measure() == Measure::BA) {\n                // ADD z0 drift in the BA measure\n                res[model_->pIdx(IR, i, 0)] = -Hi * alphai * alphai;\n                // the auxiliary state variable is drift-free\n                res[model_->pIdx(AUX, i, 0)] = 0.0;\n            }\n            if (i > 0) {\n                Real sigmai = model_->fxbs(i - 1)->sigma(t);\n                // ir-ir\n                Real rhozz0i = model_->correlation(IR, 0, IR, i);\n                // ir-fx\n                Real rhozx0i = model_->correlation(IR, 0, FX, i - 1);\n                Real rhozxii = model_->correlation(IR, i, FX, i - 1);\n                // ir drifts\n                res[model_->pIdx(IR, i, 0)] =\n                    -Hi * alphai * alphai + H0 * alpha0 * alphai * rhozz0i - sigmai * alphai * rhozxii;\n                // log spot fx drifts (z0, zi independent parts)\n                res[model_->pIdx(FX, i - 1, 0)] = H0 * alpha0 * sigmai * rhozx0i +\n                                                  model_->irlgm1f(0)->termStructure()->forwardRate(t, t, Continuous) -\n                                                  model_->irlgm1f(i)->termStructure()->forwardRate(t, t, Continuous) -\n                                                  0.5 * sigmai * sigmai;\n                if (model_->measure() == Measure::BA) {\n                    // REMOVE the LGM measure drift contributions above\n                    res[model_->pIdx(IR, i, 0)] -= H0 * alpha0 * alphai * rhozz0i;\n                    res[model_->pIdx(FX, i - 1, 0)] -= H0 * alpha0 * sigmai * rhozx0i;\n                }\n            }\n        }\n        /* log equity spot drifts (the cache-able parts) */\n        for (Size k = 0; k < n_eq; ++k) {\n            Size i = model_->ccyIndex(model_->eqbs(k)->currency());\n            // ir params (for equity currency)\n            Real eps_ccy = (i == 0) ? 0.0 : 1.0;\n            // Real Hi = model_->irlgm1f(i)->H(t);\n            // Real alphai = model_->irlgm1f(i)->alpha(t);\n            // eq vol\n            Real sigmask = model_->eqbs(k)->sigma(t);\n            // fx vol (eq ccy / base ccy)\n            Real sigmaxi = (i == 0) ? 0.0 : model_->fxbs(i - 1)->sigma(t);\n            // ir-eq corr\n            // Real rhozsik = model_->correlation(EQ, k, IR, i); // eq cur\n            Real rhozs0k = model_->correlation(EQ, k, IR, 0); // base cur\n            // fx-eq corr\n            Real rhoxsik = (i == 0) ? 0.0 : // no fx process for base-ccy\n                               model_->correlation(FX, i - 1, EQ, k);\n            // ir instantaneous forward rate (from curve used for eq forward projection)\n            Real fr_i = model_->eqbs(k)->equityIrCurveToday()->forwardRate(t, t, Continuous);\n            // div yield instantaneous forward rate\n            Real fq_k = model_->eqbs(k)->equityDivYieldCurveToday()->forwardRate(t, t, Continuous);\n            res[model_->pIdx(EQ, k, 0)] = fr_i - fq_k + (rhozs0k * H0 * alpha0 * sigmask) -\n                                          (eps_ccy * rhoxsik * sigmaxi * sigmask) - (0.5 * sigmask * sigmask);\n        }\n\n        // State independent pieces of JY inflation model, if there is a CAM JY component.\n        for (Size j = 0; j < model_->components(INF); ++j) {\n\n            if (model_->modelType(INF, j) == JY) {\n\n                auto p = model_->infjy(j);\n                Size i_j = model_->ccyIndex(p->currency());\n\n                // JY inflation parameter values.\n                Real H_y_j = p->realRate()->H(t);\n                Real Hp_y_j = p->realRate()->Hprime(t);\n                Real zeta_y_j = p->realRate()->zeta(t);\n                Real alpha_y_j = p->realRate()->alpha(t);\n                Real sigma_c_j = p->index()->sigma(t);\n\n                // Inflation nominal currency parameter values\n                Real H_i_j = model_->irlgm1f(i_j)->H(t);\n                Real Hp_i_j = model_->irlgm1f(i_j)->Hprime(t);\n                Real zeta_i_j = model_->irlgm1f(i_j)->zeta(t);\n\n                // Correlations\n                Real rho_zy_0j = model_->correlation(IR, 0, INF, j, 0, 0);\n                Real rho_yc_ij = model_->correlation(INF, j, INF, j, 0, 1);\n                Real rho_zc_0j = model_->correlation(IR, 0, INF, j, 0, 1);\n\n                // JY real rate drift. It is state independent\n                auto rrDrift = -alpha_y_j * alpha_y_j * H_y_j + rho_zy_0j * alpha0 * alpha_y_j * H_y_j -\n                               rho_yc_ij * alpha_y_j * sigma_c_j;\n\n                if (i_j > 0) {\n                    Real sigma_x_i_j = model_->fxbs(i_j - 1)->sigma(t);\n                    Real rho_yx_j_i_j = model_->correlation(INF, j, FX, i_j - 1, 0, 0);\n                    rrDrift -= rho_yx_j_i_j * alpha_y_j * sigma_x_i_j;\n                }\n\n                res[model_->pIdx(INF, j, 0)] = rrDrift;\n\n                // JY log inflation index drift (state independent piece).\n                auto indexDrift = rho_zc_0j * alpha0 * sigma_c_j * H0 - 0.5 * sigma_c_j * sigma_c_j +\n                                  zeta_i_j * Hp_i_j * H_i_j - zeta_y_j * Hp_y_j * H_y_j;\n\n                // Add on the f_n(0, t) - f_r(0, t) piece using the initial zero inflation term structure.\n                // Use the same dt below that is used in yield forward rate calculations.\n                auto ts = p->realRate()->termStructure();\n                Time dt = 0.0001;\n                Time t1 = std::max(t - dt / 2.0, 0.0);\n                Time t2 = t1 + dt;\n                auto z_t = ts->zeroRate(t);\n                auto z_t1 = ts->zeroRate(t1);\n                auto z_t2 = ts->zeroRate(t2);\n                indexDrift += std::log(1 + z_t) + (t / (1 + z_t)) * ((z_t2 - z_t1) / dt);\n\n                if (i_j > 0) {\n                    Real sigma_x_i_j = model_->fxbs(i_j - 1)->sigma(t);\n                    Real rho_cx_j_i_j = model_->correlation(INF, j, FX, i_j - 1, 1, 0);\n                    indexDrift -= rho_cx_j_i_j * sigma_c_j * sigma_x_i_j;\n                }\n\n                res[model_->pIdx(INF, j, 1)] = indexDrift;\n            }\n        }\n\n        cache_m_.insert(std::make_pair(t, res));\n    } else {\n        res = i->second;\n    }\n    // non-cacheable sections of drifts\n    for (Size i = 1; i < n; ++i) {\n        // log spot fx drifts (z0, zi dependent parts)\n        Real Hi = model_->irlgm1f(i)->H(t);\n        Real Hprimei = model_->irlgm1f(i)->Hprime(t);\n        Real zetai = model_->irlgm1f(i)->zeta(t);\n        res[model_->pIdx(FX, i - 1, 0)] += x[model_->pIdx(IR, 0, 0)] * Hprime0 + zeta0 * Hprime0 * H0 -\n                                           x[model_->pIdx(IR, i, 0)] * Hprimei - zetai * Hprimei * Hi;\n    }\n    for (Size k = 0; k < n_eq; ++k) {\n        // log equity spot drifts (path-dependent parts)\n        // notice the assumption in below that dividend yield curve is static\n        Size i = model_->ccyIndex(model_->eqbs(k)->currency());\n        // ir params (for equity currency)\n        Real Hi = model_->irlgm1f(i)->H(t);\n        Real Hprimei = model_->irlgm1f(i)->Hprime(t);\n        Real zetai = model_->irlgm1f(i)->zeta(t);\n        res[model_->pIdx(EQ, k, 0)] += (x[model_->pIdx(IR, i, 0)] * Hprimei) + (zetai * Hprimei * Hi);\n    }\n\n    // Non-cacheable portion of inflation JY drift, if there is a CAM JY component.\n    for (Size j = 0; j < model_->components(INF); ++j) {\n        if (model_->modelType(INF, j) == JY) {\n\n            auto p = model_->infjy(j);\n            Size i_j = model_->ccyIndex(p->currency());\n\n            // JY inflation parameter values.\n            Real Hp_y_j = p->realRate()->Hprime(t);\n\n            // Inflation nominal currency parameter values\n            Real Hp_i_j = model_->irlgm1f(i_j)->Hprime(t);\n\n            res[model_->pIdx(INF, j, 1)] += x[model_->pIdx(IR, i_j, 0)] * Hp_i_j - x[model_->pIdx(INF, j, 0)] * Hp_y_j;\n        }\n    }\n\n    /* no drift for infdk, crlgm1f components */\n    return res;\n}\n\nDisposable<Matrix> CrossAssetStateProcess::diffusion(Time t, const Array& x) const {\n    boost::unordered_map<double, Matrix>::const_iterator i = cache_d_.find(t);\n    if (i == cache_d_.end()) {\n        Matrix tmp = diffusionImpl(t, x);\n        cache_d_.insert(std::make_pair(t, tmp));\n        return tmp;\n    } else {\n        // we have to make a copy, otherwise we destroy the map entry\n        // since a disposable is returned\n        Matrix tmp = i->second;\n        return tmp;\n    }\n}\n\nDisposable<Array> CrossAssetStateProcess::marginalDiffusion(Time t, const Array& x) const {\n    boost::unordered_map<double, Array>::const_iterator i = cache_md_.find(t);\n    if (i == cache_md_.end()) {\n        Array tmp = marginalDiffusionImpl(t, x);\n        cache_md_.insert(std::make_pair(t, tmp));\n        return tmp;\n    } else {\n        // we have to make a copy, otherwise we destroy the map entry\n        // since a disposable is returned\n        Array tmp = i->second;\n        return tmp;\n    }\n}\n\nDisposable<Matrix> CrossAssetStateProcess::diffusionImpl(Time t, const Array& x) const {\n    Matrix res(model_->dimension(), model_->dimension(), 0.0);\n    Array diag = marginalDiffusion(t, x);\n    for (Size i = 0; i < x.size(); ++i) {\n        res[i][i] = diag[i];\n    }\n    return res * sqrtCorrelation_;\n} // namespace QuantExt\n\nDisposable<Array> CrossAssetStateProcess::marginalDiffusionImpl(Time t, const Array&) const {\n    Array res(model_->dimension(), 0.0);\n    Size n = model_->components(IR);\n    Size m = model_->components(FX);\n    Size d = model_->components(INF);\n    Size c = model_->components(CR);\n    Size e = model_->components(EQ);\n    // ir-ir\n    for (Size i = 0; i < n; ++i) {\n        Real alphai = model_->irlgm1f(i)->alpha(t);\n        setValue(res, alphai, model_, IR, i, 0);\n    }\n    // fx-fx\n    for (Size i = 0; i < m; ++i) {\n        Real sigmai = model_->fxbs(i)->sigma(t);\n        setValue(res, sigmai, model_, FX, i, 0);\n    }\n    // inf-inf\n    for (Size i = 0; i < d; ++i) {\n        if (model_->modelType(INF, i) == DK) {\n            Real alphai = model_->infdk(i)->alpha(t);\n            Real Hi = model_->infdk(i)->H(t);\n            // DK z diffusion coefficient\n            setValue(res, alphai, model_, INF, i, 0);\n            // DK y diffusion coefficient\n            setValue(res, alphai * Hi, model_, INF, i, 1);\n        } else {\n            auto p = model_->infjy(i);\n            // JY z diffusion coefficient\n            setValue(res, p->realRate()->alpha(t), model_, INF, i, 0);\n            // JY I diffusion coefficient\n            setValue(res, p->index()->sigma(t), model_, INF, i, 1);\n        }\n    }\n    for (Size i = 0; i < c; ++i) {\n        // Skip CR components that are not LGM\n        if (model_->modelType(CR, i) != LGM1F)\n            continue;\n        Real alphai = model_->crlgm1f(i)->alpha(t);\n        Real Hi = model_->crlgm1f(i)->H(t);\n        // crz-crz\n        setValue(res, alphai, model_, CR, i, 0);\n        // cry-cry\n        setValue(res, alphai * Hi, model_, CR, i, 1);\n    }\n    // eq-eq\n    for (Size i = 0; i < e; ++i) {\n        Real sigmai = model_->eqbs(i)->sigma(t);\n        setValue(res, sigmai, model_, EQ, i, 0);\n    }\n\n    if (model_->measure() == Measure::BA) {\n        // aux-aux\n        Real H0 = model_->irlgm1f(0)->H(t);\n        Real alpha0 = model_->irlgm1f(0)->alpha(t);\n        setValue(res, alpha0 * H0, model_, AUX, 0, 0);\n    }\n\n    return res;\n}\n\nDisposable<Array> CrossAssetStateProcess::evolve(Time t0, const Array& x0, Time dt, const Array& dw) const {\n\n    Array res;\n    if (disc_ == euler) {\n        const Array dz = sqrtCorrelation_ * dw;\n        const Array df = marginalDiffusion(t0, x0);\n        res = apply(expectation(t0, x0, dt), df * dz * std::sqrt(dt));\n\n        // CR CIRPP components\n        if (cirppCount_ > 0) {\n            for (Size i = 0; i < model_->components(CR); ++i) {\n                if (!crCirpp_[i])\n                    continue; // ignore non-cir cr model\n                Size idx1 = model_->pIdx(CR, i, 0);\n                Size idx2 = model_->pIdx(CR, i, 1);\n                Array x0Tmp(2), dwTmp(2);\n                x0Tmp[0] = x0[idx1];\n                x0Tmp[1] = x0[idx2];\n                dwTmp[0] = dz[idx1];\n                dwTmp[1] = 0.0; // not used\n                // evolve original process\n                auto r = crCirpp_[i]->evolve(t0, x0Tmp, dt, dwTmp);\n\n                // set result\n                res[idx1] = r[0]; // y\n                res[idx2] = r[1]; // S(0,T)\n            }\n        }\n    } else {\n        QL_REQUIRE(cirppCount_ == 0, \"only euler discretization is supported for CIR++\");\n        res = StochasticProcess::evolve(t0, x0, dt, dw);\n    }\n\n    return res;\n}\n\nCrossAssetStateProcess::ExactDiscretization::ExactDiscretization(const CrossAssetModel* const model,\n                                                                 SalvagingAlgorithm::Type salvaging)\n    : model_(model), salvaging_(salvaging) {}\n\nDisposable<Array> CrossAssetStateProcess::ExactDiscretization::drift(const StochasticProcess& p, Time t0,\n                                                                     const Array& x0, Time dt) const {\n    Array res;\n    cache_key k = {t0, dt};\n    boost::unordered_map<cache_key, Array>::const_iterator i = cache_m_.find(k);\n    if (i == cache_m_.end()) {\n        res = driftImpl1(p, t0, x0, dt);\n        cache_m_.insert(std::make_pair(k, res));\n    } else {\n        res = i->second;\n    }\n    Array res2 = driftImpl2(p, t0, x0, dt);\n    for (Size i = 0; i < res.size(); ++i) {\n        res[i] += res2[i];\n    }\n    return res - x0;\n}\n\nDisposable<Matrix> CrossAssetStateProcess::ExactDiscretization::diffusion(const StochasticProcess& p, Time t0,\n                                                                          const Array& x0, Time dt) const {\n    cache_key k = {t0, dt};\n    boost::unordered_map<cache_key, Matrix>::const_iterator i = cache_d_.find(k);\n    if (i == cache_d_.end()) {\n        Matrix res = pseudoSqrt(covariance(p, t0, x0, dt), salvaging_);\n        // note that covariance actually does not depend on x0\n        cache_d_.insert(std::make_pair(k, res));\n        return res;\n    } else {\n        // see above about the copy\n        Matrix tmp = i->second;\n        return tmp;\n    }\n}\n\nDisposable<Matrix> CrossAssetStateProcess::ExactDiscretization::covariance(const StochasticProcess& p, Time t0,\n                                                                           const Array& x0, Time dt) const {\n    cache_key k = {t0, dt};\n    boost::unordered_map<cache_key, Matrix>::const_iterator i = cache_v_.find(k);\n    if (i == cache_v_.end()) {\n        Matrix res = covarianceImpl(p, t0, x0, dt);\n        cache_v_.insert(std::make_pair(k, res));\n        return res;\n    } else {\n        // see above about the copy\n        Matrix tmp = i->second;\n        return tmp;\n    }\n}\n\nDisposable<Array> CrossAssetStateProcess::ExactDiscretization::driftImpl1(const StochasticProcess&, Time t0,\n                                                                          const Array&, Time dt) const {\n    Size n = model_->components(IR);\n    Size m = model_->components(FX);\n    Size e = model_->components(EQ);\n    Array res(model_->dimension(), 0.0);\n    for (Size i = 0; i < n; ++i) {\n        res[model_->pIdx(IR, i, 0)] = ir_expectation_1(model_, i, t0, dt);\n    }\n    for (Size j = 0; j < m; ++j) {\n        res[model_->pIdx(FX, j, 0)] = fx_expectation_1(model_, j, t0, dt);\n    }\n    for (Size k = 0; k < e; ++k) {\n        res[model_->pIdx(EQ, k, 0)] = eq_expectation_1(model_, k, t0, dt);\n    }\n\n    // If inflation is JY, need to take account of the drift.\n    for (Size i = 0; i < model_->components(INF); ++i) {\n        if (model_->modelType(INF, i) == JY) {\n            std::tie(res[model_->pIdx(INF, i, 0)], res[model_->pIdx(INF, i, 1)]) =\n                inf_jy_expectation_1(model_, i, t0, dt);\n        }\n    }\n\n    return res;\n}\n\nDisposable<Array> CrossAssetStateProcess::ExactDiscretization::driftImpl2(const StochasticProcess&, Time t0,\n                                                                          const Array& x0, Time dt) const {\n    Size n = model_->components(IR);\n    Size m = model_->components(FX);\n    Size e = model_->components(EQ);\n    Array res(model_->dimension(), 0.0);\n\n    if (model_->measure() == Measure::BA) {\n        // zero AUX state drift, i.e. conditional expectation equal to the previous level as for z_i\n        res[model_->pIdx(AUX, 0, 0)] += x0[model_->pIdx(AUX, 0, 0)];\n    }\n\n    for (Size i = 0; i < n; ++i) {\n        res[model_->pIdx(IR, i, 0)] += ir_expectation_2(model_, i, x0[model_->pIdx(IR, i, 0)]);\n    }\n    for (Size j = 0; j < m; ++j) {\n        res[model_->pIdx(FX, j, 0)] += fx_expectation_2(model_, j, t0, x0[model_->pIdx(FX, j, 0)],\n                                                        x0[model_->pIdx(IR, j + 1, 0)], x0[model_->pIdx(IR, 0, 0)], dt);\n    }\n    for (Size k = 0; k < e; ++k) {\n        Size eqCcyIdx = model_->ccyIndex(model_->eqbs(k)->currency());\n        res[model_->pIdx(EQ, k, 0)] +=\n            eq_expectation_2(model_, k, t0, x0[model_->pIdx(EQ, k, 0)], x0[model_->pIdx(IR, eqCcyIdx, 0)], dt);\n    }\n\n    // Inflation: JY is state dependent. DK is not. Even for DK, still need to return the conditional expected value.\n    for (Size i = 0; i < model_->components(INF); ++i) {\n        if (model_->modelType(INF, i) == JY) {\n            auto i_i = model_->ccyIndex(model_->infjy(i)->currency());\n            auto zi_i_0 = x0[model_->pIdx(IR, i_i, 0)];\n            auto state_0 = std::make_pair(x0[model_->pIdx(INF, i, 0)], x0[model_->pIdx(INF, i, 1)]);\n            std::tie(res[model_->pIdx(INF, i, 0)], res[model_->pIdx(INF, i, 1)]) =\n                inf_jy_expectation_2(model_, i, t0, state_0, zi_i_0, dt);\n        } else {\n            res[model_->pIdx(INF, i, 0)] = x0[model_->pIdx(INF, i, 0)];\n            res[model_->pIdx(INF, i, 1)] = x0[model_->pIdx(INF, i, 1)];\n        }\n    }\n\n    /*! cr components have integrated drift 0, we have to return the conditional\n        expected value though, since x0 is subtracted later */\n    Size c = model_->components(CR);\n    for (Size i = 0; i < c; ++i) {\n        res[model_->pIdx(CR, i, 0)] = x0[model_->pIdx(CR, i, 0)];\n        res[model_->pIdx(CR, i, 1)] = x0[model_->pIdx(CR, i, 1)];\n    }\n    return res;\n}\n\nDisposable<Matrix> CrossAssetStateProcess::ExactDiscretization::covarianceImpl(const StochasticProcess&, Time t0,\n                                                                               const Array&, Time dt) const {\n    Matrix res(model_->dimension(), model_->dimension());\n    Size n = model_->components(IR);\n    Size m = model_->components(FX);\n    Size d = model_->components(INF);\n    Size c = model_->components(CR);\n    Size e = model_->components(EQ);\n\n    if (model_->measure() == Measure::BA) {\n        // aux-aux\n        setValue(res, aux_aux_covariance(model_, t0, dt), model_, AUX, 0, AUX, 0, 0, 0);\n        // aux-ir\n        for (Size j = 0; j < n; ++j) {\n            setValue(res, aux_ir_covariance(model_, j, t0, dt), model_, AUX, 0, IR, j, 0, 0);\n        }\n        // aux-fx\n        for (Size j = 0; j < m; ++j) {\n            setValue(res, aux_fx_covariance(model_, j, t0, dt), model_, AUX, 0, FX, j, 0, 0);\n        }\n    }\n    // ir-ir\n    for (Size i = 0; i < n; ++i) {\n        for (Size j = 0; j <= i; ++j) {\n            setValue(res, ir_ir_covariance(model_, i, j, t0, dt), model_, IR, i, IR, j, 0, 0);\n        }\n    }\n    // ir-fx\n    for (Size i = 0; i < n; ++i) {\n        for (Size j = 0; j < m; ++j) {\n            setValue(res, ir_fx_covariance(model_, i, j, t0, dt), model_, IR, i, FX, j, 0, 0);\n        }\n    }\n    // fx-fx\n    for (Size i = 0; i < m; ++i) {\n        for (Size j = 0; j <= i; ++j) {\n            setValue(res, fx_fx_covariance(model_, i, j, t0, dt), model_, FX, i, FX, j);\n        }\n    }\n    // ir,fx,inf - inf\n    for (Size j = 0; j < d; ++j) {\n        for (Size i = 0; i <= j; ++i) {\n            // infz-infz\n            setValue(res, infz_infz_covariance(model_, i, j, t0, dt), model_, INF, i, INF, j, 0, 0);\n            // infz-infy\n            setValue(res, infz_infy_covariance(model_, i, j, t0, dt), model_, INF, i, INF, j, 0, 1);\n            setValue(res, infz_infy_covariance(model_, j, i, t0, dt), model_, INF, i, INF, j, 1, 0);\n            // infy-infy\n            setValue(res, infy_infy_covariance(model_, i, j, t0, dt), model_, INF, i, INF, j, 1, 1);\n        }\n        for (Size i = 0; i < n; ++i) {\n            // ir-inf\n            setValue(res, ir_infz_covariance(model_, i, j, t0, dt), model_, IR, i, INF, j, 0, 0);\n            setValue(res, ir_infy_covariance(model_, i, j, t0, dt), model_, IR, i, INF, j, 0, 1);\n        }\n        for (Size i = 0; i < (n - 1); ++i) {\n            // fx-inf\n            setValue(res, fx_infz_covariance(model_, i, j, t0, dt), model_, FX, i, INF, j, 0, 0);\n            setValue(res, fx_infy_covariance(model_, i, j, t0, dt), model_, FX, i, INF, j, 0, 1);\n        }\n    }\n    // ir,fx,inf,cr - cr\n    for (Size j = 0; j < c; ++j) {\n        // Skip CR components that are not LGM\n        if (model_->modelType(CR, j) != LGM1F)\n            continue;\n        for (Size i = 0; i <= j; ++i) {\n            // Skip CR components that are not LGM\n            if (model_->modelType(CR, i) != LGM1F)\n                continue;\n            // crz-crz\n            setValue(res, crz_crz_covariance(model_, i, j, t0, dt), model_, CR, i, CR, j, 0, 0);\n            // crz-cry\n            setValue(res, crz_cry_covariance(model_, i, j, t0, dt), model_, CR, i, CR, j, 0, 1);\n            setValue(res, crz_cry_covariance(model_, j, i, t0, dt), model_, CR, i, CR, j, 1, 0);\n            // cry-cry\n            setValue(res, cry_cry_covariance(model_, i, j, t0, dt), model_, CR, i, CR, j, 1, 1);\n        }\n        for (Size i = 0; i < n; ++i) {\n            // ir-cr\n            setValue(res, ir_crz_covariance(model_, i, j, t0, dt), model_, IR, i, CR, j, 0, 0);\n            setValue(res, ir_cry_covariance(model_, i, j, t0, dt), model_, IR, i, CR, j, 0, 1);\n        }\n        for (Size i = 0; i < (n - 1); ++i) {\n            // fx-cr\n            setValue(res, fx_crz_covariance(model_, i, j, t0, dt), model_, FX, i, CR, j, 0, 0);\n            setValue(res, fx_cry_covariance(model_, i, j, t0, dt), model_, FX, i, CR, j, 0, 1);\n        }\n        for (Size i = 0; i < d; ++i) {\n            // inf-cr\n            setValue(res, infz_crz_covariance(model_, i, j, t0, dt), model_, INF, i, CR, j, 0, 0);\n            setValue(res, infy_crz_covariance(model_, i, j, t0, dt), model_, INF, i, CR, j, 1, 0);\n            setValue(res, infz_cry_covariance(model_, i, j, t0, dt), model_, INF, i, CR, j, 0, 1);\n            setValue(res, infy_cry_covariance(model_, i, j, t0, dt), model_, INF, i, CR, j, 1, 1);\n        }\n    }\n    // ir,fx,inf,cr,eq - eq\n    for (Size j = 0; j < e; ++j) {\n        for (Size i = 0; i <= j; ++i) {\n            // eq-eq\n            setValue(res, eq_eq_covariance(model_, i, j, t0, dt), model_, EQ, i, EQ, j, 0, 0);\n        }\n        for (Size i = 0; i < n; ++i) {\n            // ir-eq\n            setValue(res, ir_eq_covariance(model_, i, j, t0, dt), model_, IR, i, EQ, j, 0, 0);\n        }\n        for (Size i = 0; i < (n - 1); ++i) {\n            // fx-eq\n            setValue(res, fx_eq_covariance(model_, i, j, t0, dt), model_, FX, i, EQ, j, 0, 0);\n        }\n        for (Size i = 0; i < d; ++i) {\n            // inf-eq\n            setValue(res, infz_eq_covariance(model_, i, j, t0, dt), model_, INF, i, EQ, j, 0, 0);\n            setValue(res, infy_eq_covariance(model_, i, j, t0, dt), model_, INF, i, EQ, j, 1, 0);\n        }\n        for (Size i = 0; i < c; ++i) {\n            // Skip CR components that are not LGM\n            if (model_->modelType(CR, i) != LGM1F)\n                continue;\n            // cr-eq\n            setValue(res, crz_eq_covariance(model_, i, j, t0, dt), model_, CR, i, EQ, j, 0, 0);\n            setValue(res, cry_eq_covariance(model_, i, j, t0, dt), model_, CR, i, EQ, j, 1, 0);\n        }\n    }\n    return res;\n}\n\nvoid CrossAssetStateProcess::ExactDiscretization::flushCache() const {\n    cache_m_.clear();\n    cache_v_.clear();\n    cache_d_.clear();\n}\n\n} // namespace QuantExt\n", "meta": {"hexsha": "808ddcddb5ab0fe78f652e212d13d7f9c7054ae6", "size": 31567, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/processes/crossassetstateprocess.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/processes/crossassetstateprocess.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/processes/crossassetstateprocess.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 43.1243169399, "max_line_length": 120, "alphanum_fraction": 0.5366363608, "num_tokens": 9302, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.33807712415000585, "lm_q1q2_score": 0.22259589507992866}}
{"text": "//  Copyright (c) 2006, Stephan Diederich\r\n//\r\n//  This code may be used under either of the following two licences:\r\n//\r\n//    Permission is hereby granted, free of charge, to any person\r\n//    obtaining a copy of this software and associated documentation\r\n//    files (the \"Software\"), to deal in the Software without\r\n//    restriction, including without limitation the rights to use,\r\n//    copy, modify, merge, publish, distribute, sublicense, and/or\r\n//    sell copies of the Software, and to permit persons to whom the\r\n//    Software is furnished to do so, subject to the following\r\n//    conditions:\r\n//\r\n//    The above copyright notice and this permission notice shall be\r\n//    included in all copies or substantial portions of the Software.\r\n//\r\n//    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n//    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n//    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n//    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n//    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n//    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n//    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n//    OTHER DEALINGS IN THE SOFTWARE. OF SUCH DAMAGE.\r\n//\r\n//  Or:\r\n//\r\n//    Distributed under the Boost Software License, Version 1.0.\r\n//    (See accompanying file LICENSE_1_0.txt or copy at\r\n//    http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_KOLMOGOROV_MAX_FLOW_HPP\r\n#define BOOST_KOLMOGOROV_MAX_FLOW_HPP\r\n\r\n#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__DMC__)\r\n#  pragma message (\"The kolmogorov_max_flow.hpp header is deprecated and will be removed in Boost 1.46. Use boykov_kolmogorov_max_flow.hpp instead.\")\r\n#elif defined(__GNUC__) || defined(__HP_aCC) || defined(__SUNPRO_CC) || defined(__IBMCPP__)\r\n#  warning \"The kolmogorov_max_flow.hpp header is deprecated and will be removed in Boost 1.46. Use boykov_kolmogorov_max_flow.hpp instead.\"\r\n#endif\r\n\r\n#include <boost/config.hpp>\r\n#include <cassert>\r\n#include <vector>\r\n#include <list>\r\n#include <utility>\r\n#include <iosfwd>\r\n#include <algorithm> // for std::min and std::max\r\n\r\n#include <boost/pending/queue.hpp>\r\n#include <boost/limits.hpp>\r\n#include <boost/property_map/property_map.hpp>\r\n#include <boost/none_t.hpp>\r\n#include <boost/graph/graph_concepts.hpp>\r\n#include <boost/graph/named_function_params.hpp>\r\n#include <boost/graph/lookup_edge.hpp>\r\n\r\nnamespace boost {\r\n  namespace detail {\r\n\r\n    template <class Graph,\r\n              class EdgeCapacityMap,\r\n              class ResidualCapacityEdgeMap,\r\n              class ReverseEdgeMap,\r\n              class PredecessorMap,\r\n              class ColorMap,\r\n              class DistanceMap,\r\n              class IndexMap>\r\n    class kolmogorov{\r\n      typedef typename property_traits<EdgeCapacityMap>::value_type tEdgeVal;\r\n      typedef graph_traits<Graph> tGraphTraits;\r\n      typedef typename tGraphTraits::vertex_iterator vertex_iterator;\r\n      typedef typename tGraphTraits::vertex_descriptor vertex_descriptor;\r\n      typedef typename tGraphTraits::edge_descriptor edge_descriptor;\r\n      typedef typename tGraphTraits::edge_iterator edge_iterator;\r\n      typedef typename tGraphTraits::out_edge_iterator out_edge_iterator;\r\n      typedef boost::queue<vertex_descriptor> tQueue;                               //queue of vertices, used in adoption-stage\r\n      typedef typename property_traits<ColorMap>::value_type tColorValue;\r\n      typedef color_traits<tColorValue> tColorTraits;\r\n      typedef typename property_traits<DistanceMap>::value_type tDistanceVal;\r\n\r\n        public:\r\n          kolmogorov(Graph& g,\r\n                     EdgeCapacityMap cap,\r\n                     ResidualCapacityEdgeMap res,\r\n                     ReverseEdgeMap rev,\r\n                     PredecessorMap pre,\r\n                     ColorMap color,\r\n                     DistanceMap dist,\r\n                     IndexMap idx,\r\n                     vertex_descriptor src,\r\n                     vertex_descriptor sink):\r\n          m_g(g),\r\n          m_index_map(idx),\r\n          m_cap_map(cap),\r\n          m_res_cap_map(res),\r\n          m_rev_edge_map(rev),\r\n          m_pre_map(pre),\r\n          m_tree_map(color),\r\n          m_dist_map(dist),\r\n          m_source(src),\r\n          m_sink(sink),\r\n          m_active_nodes(),\r\n          m_in_active_list_vec(num_vertices(g), false),\r\n          m_in_active_list_map(make_iterator_property_map(m_in_active_list_vec.begin(), m_index_map)),\r\n          m_has_parent_vec(num_vertices(g), false),\r\n          m_has_parent_map(make_iterator_property_map(m_has_parent_vec.begin(), m_index_map)),\r\n          m_time_vec(num_vertices(g), 0),\r\n          m_time_map(make_iterator_property_map(m_time_vec.begin(), m_index_map)),\r\n          m_flow(0),\r\n          m_time(1),\r\n          m_last_grow_vertex(graph_traits<Graph>::null_vertex()){\r\n            // initialize the color-map with gray-values\r\n            vertex_iterator vi, v_end;\r\n            for(boost::tie(vi, v_end) = vertices(m_g); vi != v_end; ++vi){\r\n              set_tree(*vi, tColorTraits::gray());\r\n            }\r\n            // Initialize flow to zero which means initializing\r\n            // the residual capacity equal to the capacity\r\n            edge_iterator ei, e_end;\r\n            for(boost::tie(ei, e_end) = edges(m_g); ei != e_end; ++ei) {\r\n              m_res_cap_map[*ei] = m_cap_map[*ei];\r\n              assert(m_rev_edge_map[m_rev_edge_map[*ei]] == *ei); //check if the reverse edge map is build up properly\r\n            }\r\n            //init the search trees with the two terminals\r\n            set_tree(m_source, tColorTraits::black());\r\n            set_tree(m_sink, tColorTraits::white());\r\n            m_time_map[m_source] = 1;\r\n            m_time_map[m_sink] = 1;\r\n          }\r\n\r\n          ~kolmogorov(){}\r\n\r\n          tEdgeVal max_flow(){\r\n            //augment direct paths from SOURCE->SINK and SOURCE->VERTEX->SINK\r\n            augment_direct_paths();\r\n            //start the main-loop\r\n            while(true){\r\n              bool path_found;\r\n              edge_descriptor connecting_edge;\r\n              boost::tie(connecting_edge, path_found) = grow(); //find a path from source to sink\r\n              if(!path_found){\r\n                //we're finished, no more paths were found\r\n                break;\r\n              }\r\n              ++m_time;\r\n              augment(connecting_edge); //augment that path\r\n              adopt(); //rebuild search tree structure\r\n            }\r\n            return m_flow;\r\n          }\r\n\r\n          //the complete class is protected, as we want access to members in derived test-class (see $(BOOST_ROOT)/libs/graph/test/kolmogorov_max_flow_test.cpp)\r\n        protected:\r\n          void augment_direct_paths(){\r\n            //in a first step, we augment all direct paths from source->NODE->sink\r\n            //and additionally paths from source->sink\r\n            //this improves especially graphcuts for segmentation, as most of the nodes have source/sink connects\r\n            //but shouldn't have an impact on other maxflow problems (this is done in grow() anyway)\r\n            out_edge_iterator ei, e_end;\r\n            for(boost::tie(ei, e_end) = out_edges(m_source, m_g); ei != e_end; ++ei){\r\n              edge_descriptor from_source = *ei;\r\n              vertex_descriptor current_node = target(from_source, m_g);\r\n              if(current_node == m_sink){\r\n                tEdgeVal cap = m_res_cap_map[from_source];\r\n                m_res_cap_map[from_source] = 0;\r\n                m_flow += cap;\r\n                continue;\r\n              }\r\n              edge_descriptor to_sink;\r\n              bool is_there;\r\n              boost::tie(to_sink, is_there) = lookup_edge(current_node, m_sink, m_g);\r\n              if(is_there){\r\n                tEdgeVal cap_from_source = m_res_cap_map[from_source];\r\n                tEdgeVal cap_to_sink = m_res_cap_map[to_sink];\r\n                if(cap_from_source > cap_to_sink){\r\n                  set_tree(current_node, tColorTraits::black());\r\n                  add_active_node(current_node);\r\n                  set_edge_to_parent(current_node, from_source);\r\n                  m_dist_map[current_node] = 1;\r\n                  m_time_map[current_node] = 1;\r\n                  //add stuff to flow and update residuals\r\n                  //we dont need to update reverse_edges, as incoming/outgoing edges to/from source/sink don't count for max-flow\r\n                  m_res_cap_map[from_source] -= cap_to_sink;\r\n                  m_res_cap_map[to_sink] = 0;\r\n                  m_flow += cap_to_sink;\r\n                } else if(cap_to_sink > 0){\r\n                  set_tree(current_node, tColorTraits::white());\r\n                  add_active_node(current_node);\r\n                  set_edge_to_parent(current_node, to_sink);\r\n                  m_dist_map[current_node] = 1;\r\n                  m_time_map[current_node] = 1;\r\n                  //add stuff to flow and update residuals\r\n                  //we dont need to update reverse_edges, as incoming/outgoing edges to/from source/sink don't count for max-flow\r\n                  m_res_cap_map[to_sink] -= cap_from_source;\r\n                  m_res_cap_map[from_source] = 0;\r\n                  m_flow += cap_from_source;\r\n                }\r\n              } else if(m_res_cap_map[from_source]){\r\n                //there is no sink connect, so we can't augment this path\r\n                //but to avoid adding m_source to the active nodes, we just activate this node and set the approciate things\r\n                set_tree(current_node, tColorTraits::black());\r\n                set_edge_to_parent(current_node, from_source);\r\n                m_dist_map[current_node] = 1;\r\n                m_time_map[current_node] = 1;\r\n                add_active_node(current_node);\r\n              }\r\n            }\r\n            for(boost::tie(ei, e_end) = out_edges(m_sink, m_g); ei != e_end; ++ei){\r\n              edge_descriptor to_sink = m_rev_edge_map[*ei];\r\n              vertex_descriptor current_node = source(to_sink, m_g);\r\n              if(m_res_cap_map[to_sink]){\r\n                set_tree(current_node, tColorTraits::white());\r\n                set_edge_to_parent(current_node, to_sink);\r\n                m_dist_map[current_node] = 1;\r\n                m_time_map[current_node] = 1;\r\n                add_active_node(current_node);\r\n              }\r\n            }\r\n          }\r\n\r\n          /**\r\n          * returns a pair of an edge and a boolean. if the bool is true, the edge is a connection of a found path from s->t , read \"the link\" and\r\n          *   source(returnVal, m_g) is the end of the path found in the source-tree\r\n          *   target(returnVal, m_g) is the beginning of the path found in the sink-tree\r\n          */\r\n          std::pair<edge_descriptor, bool> grow(){\r\n            assert(m_orphans.empty());\r\n            vertex_descriptor current_node;\r\n            while((current_node = get_next_active_node()) != graph_traits<Graph>::null_vertex()){ //if there is one\r\n              assert(get_tree(current_node) != tColorTraits::gray()  && (has_parent(current_node) || current_node==m_source || current_node==m_sink));\r\n              if(get_tree(current_node) == tColorTraits::black()){\r\n                //source tree growing\r\n                out_edge_iterator ei, e_end;\r\n                if(current_node != m_last_grow_vertex){\r\n                  m_last_grow_vertex = current_node;\r\n                  boost::tie(m_last_grow_edge_it, m_last_grow_edge_end) = out_edges(current_node, m_g);\r\n                }\r\n                for(; m_last_grow_edge_it != m_last_grow_edge_end; ++m_last_grow_edge_it){\r\n                  edge_descriptor out_edge = *m_last_grow_edge_it;\r\n                  if(m_res_cap_map[out_edge] > 0){ //check if we have capacity left on this edge\r\n                    vertex_descriptor other_node = target(out_edge, m_g);\r\n                    if(get_tree(other_node) == tColorTraits::gray()){ //it's a free node\r\n                      set_tree(other_node, tColorTraits::black()); //aquire other node to our search tree\r\n                      set_edge_to_parent(other_node, out_edge);   //set us as parent\r\n                      m_dist_map[other_node] = m_dist_map[current_node] + 1;  //and update the distance-heuristic\r\n                      m_time_map[other_node] = m_time_map[current_node];\r\n                      add_active_node(other_node);\r\n                    } else if(get_tree(other_node) == tColorTraits::black()){\r\n                      if(is_closer_to_terminal(current_node, other_node)){ //we do this to get shorter paths. check if we are nearer to the source as its parent is\r\n                        set_edge_to_parent(other_node, out_edge);\r\n                        m_dist_map[other_node] = m_dist_map[current_node] + 1;\r\n                        m_time_map[other_node] = m_time_map[current_node];\r\n                      }\r\n                    } else{\r\n                      assert(get_tree(other_node)==tColorTraits::white());\r\n                      //kewl, found a path from one to the other search tree, return the connecting edge in src->sink dir\r\n                      return std::make_pair(out_edge, true);\r\n                    }\r\n                  }\r\n                } //for all out-edges\r\n              } //source-tree-growing\r\n              else{\r\n                assert(get_tree(current_node) == tColorTraits::white());\r\n                out_edge_iterator ei, e_end;\r\n                if(current_node != m_last_grow_vertex){\r\n                  m_last_grow_vertex = current_node;\r\n                  boost::tie(m_last_grow_edge_it, m_last_grow_edge_end) = out_edges(current_node, m_g);\r\n                }\r\n                for(; m_last_grow_edge_it != m_last_grow_edge_end; ++m_last_grow_edge_it){\r\n                  edge_descriptor in_edge = m_rev_edge_map[*m_last_grow_edge_it];\r\n                  if(m_res_cap_map[in_edge] > 0){ //check if there is capacity left\r\n                    vertex_descriptor other_node = source(in_edge, m_g);\r\n                    if(get_tree(other_node) == tColorTraits::gray()){ //it's a free node\r\n                      set_tree(other_node, tColorTraits::white());      //aquire that node to our search tree\r\n                      set_edge_to_parent(other_node, in_edge);          //set us as parent\r\n                      add_active_node(other_node);                      //activate that node\r\n                      m_dist_map[other_node] = m_dist_map[current_node] + 1; //set its distance\r\n                      m_time_map[other_node] = m_time_map[current_node];     //and time\r\n                    } else if(get_tree(other_node) == tColorTraits::white()){\r\n                      if(is_closer_to_terminal(current_node, other_node)){\r\n                        //we are closer to the sink than its parent is, so we \"adopt\" him\r\n                        set_edge_to_parent(other_node, in_edge);\r\n                        m_dist_map[other_node] = m_dist_map[current_node] + 1;\r\n                        m_time_map[other_node] = m_time_map[current_node];\r\n                      }\r\n                    } else{\r\n                      assert(get_tree(other_node)==tColorTraits::black());\r\n                      //kewl, found a path from one to the other search tree, return the connecting edge in src->sink dir\r\n                      return std::make_pair(in_edge, true);\r\n                    }\r\n                  }\r\n                } //for all out-edges\r\n              } //sink-tree growing\r\n              //all edges of that node are processed, and no more paths were found. so remove if from the front of the active queue\r\n              finish_node(current_node);\r\n            } //while active_nodes not empty\r\n            return std::make_pair(edge_descriptor(), false); //no active nodes anymore and no path found, we're done\r\n          }\r\n\r\n          /**\r\n          * augments path from s->t and updates residual graph\r\n          * source(e, m_g) is the end of the path found in the source-tree\r\n          * target(e, m_g) is the beginning of the path found in the sink-tree\r\n          * this phase generates orphans on satured edges, if the attached verts are from different search-trees\r\n          * orphans are ordered in distance to sink/source. first the farest from the source are front_inserted into the orphans list,\r\n          * and after that the sink-tree-orphans are front_inserted. when going to adoption stage the orphans are popped_front, and so we process the nearest\r\n          * verts to the terminals first\r\n          */\r\n          void augment(edge_descriptor e){\r\n            assert(get_tree(target(e, m_g)) == tColorTraits::white());\r\n            assert(get_tree(source(e, m_g)) == tColorTraits::black());\r\n            assert(m_orphans.empty());\r\n\r\n            const tEdgeVal bottleneck = find_bottleneck(e);\r\n            //now we push the found flow through the path\r\n            //for each edge we saturate we have to look for the verts that belong to that edge, one of them becomes an orphans\r\n            //now process the connecting edge\r\n            m_res_cap_map[e] -= bottleneck;\r\n            assert(m_res_cap_map[e] >= 0);\r\n            m_res_cap_map[m_rev_edge_map[e]] += bottleneck;\r\n\r\n            //now we follow the path back to the source\r\n            vertex_descriptor current_node = source(e, m_g);\r\n            while(current_node != m_source){\r\n              edge_descriptor pred = get_edge_to_parent(current_node);\r\n              m_res_cap_map[pred] -= bottleneck;\r\n              assert(m_res_cap_map[pred] >= 0);\r\n              m_res_cap_map[m_rev_edge_map[pred]] += bottleneck;\r\n              if(m_res_cap_map[pred] == 0){\r\n                set_no_parent(current_node);\r\n                m_orphans.push_front(current_node);\r\n              }\r\n              current_node = source(pred, m_g);\r\n            }\r\n            //then go forward in the sink-tree\r\n            current_node = target(e, m_g);\r\n            while(current_node != m_sink){\r\n              edge_descriptor pred = get_edge_to_parent(current_node);\r\n              m_res_cap_map[pred] -= bottleneck;\r\n              assert(m_res_cap_map[pred] >= 0);\r\n              m_res_cap_map[m_rev_edge_map[pred]] += bottleneck;\r\n              if(m_res_cap_map[pred] == 0){\r\n                set_no_parent(current_node);\r\n                m_orphans.push_front(current_node);\r\n              }\r\n              current_node = target(pred, m_g);\r\n            }\r\n            //and add it to the max-flow\r\n            m_flow += bottleneck;\r\n          }\r\n\r\n          /**\r\n           * returns the bottleneck of a s->t path (end_of_path is last vertex in source-tree, begin_of_path is first vertex in sink-tree)\r\n           */\r\n          inline tEdgeVal find_bottleneck(edge_descriptor e){\r\n            BOOST_USING_STD_MIN();\r\n            tEdgeVal minimum_cap = m_res_cap_map[e];\r\n            vertex_descriptor current_node = source(e, m_g);\r\n            //first go back in the source tree\r\n            while(current_node != m_source){\r\n              edge_descriptor pred = get_edge_to_parent(current_node);\r\n              minimum_cap = min BOOST_PREVENT_MACRO_SUBSTITUTION(minimum_cap, m_res_cap_map[pred]);\r\n              current_node = source(pred, m_g);\r\n            }\r\n            //then go forward in the sink-tree\r\n            current_node = target(e, m_g);\r\n            while(current_node != m_sink){\r\n              edge_descriptor pred = get_edge_to_parent(current_node);\r\n              minimum_cap = min BOOST_PREVENT_MACRO_SUBSTITUTION(minimum_cap, m_res_cap_map[pred]);\r\n              current_node = target(pred, m_g);\r\n            }\r\n            return minimum_cap;\r\n          }\r\n\r\n          /**\r\n          * rebuild search trees\r\n          * empty the queue of orphans, and find new parents for them or just drop them from the search trees\r\n          */\r\n          void adopt(){\r\n            while(!m_orphans.empty() || !m_child_orphans.empty()){\r\n              vertex_descriptor current_node;\r\n              if(m_child_orphans.empty()){\r\n                //get the next orphan from the main-queue  and remove it\r\n                current_node = m_orphans.front();\r\n                m_orphans.pop_front();\r\n              } else{\r\n                current_node = m_child_orphans.front();\r\n                m_child_orphans.pop();\r\n              }\r\n              if(get_tree(current_node) == tColorTraits::black()){\r\n                //we're in the source-tree\r\n                tDistanceVal min_distance = (std::numeric_limits<tDistanceVal>::max)();\r\n                edge_descriptor new_parent_edge;\r\n                out_edge_iterator ei, e_end;\r\n                for(boost::tie(ei, e_end) = out_edges(current_node, m_g); ei != e_end; ++ei){\r\n                  const edge_descriptor in_edge = m_rev_edge_map[*ei];\r\n                  assert(target(in_edge, m_g) == current_node); //we should be the target of this edge\r\n                  if(m_res_cap_map[in_edge] > 0){\r\n                    vertex_descriptor other_node = source(in_edge, m_g);\r\n                    if(get_tree(other_node) == tColorTraits::black() && has_source_connect(other_node)){\r\n                      if(m_dist_map[other_node] < min_distance){\r\n                        min_distance = m_dist_map[other_node];\r\n                        new_parent_edge = in_edge;\r\n                      }\r\n                    }\r\n                  }\r\n                }\r\n                if(min_distance != (std::numeric_limits<tDistanceVal>::max)()){\r\n                  set_edge_to_parent(current_node, new_parent_edge);\r\n                  m_dist_map[current_node] = min_distance + 1;\r\n                  m_time_map[current_node] = m_time;\r\n                } else{\r\n                  m_time_map[current_node] = 0;\r\n                  for(boost::tie(ei, e_end) = out_edges(current_node, m_g); ei != e_end; ++ei){\r\n                    edge_descriptor in_edge = m_rev_edge_map[*ei];\r\n                    vertex_descriptor other_node = source(in_edge, m_g);\r\n                    if(get_tree(other_node) == tColorTraits::black() && has_parent(other_node)){\r\n                      if(m_res_cap_map[in_edge] > 0){\r\n                        add_active_node(other_node);\r\n                      }\r\n                      if(source(get_edge_to_parent(other_node), m_g) == current_node){\r\n                        //we are the parent of that node\r\n                        //it has to find a new parent, too\r\n                        set_no_parent(other_node);\r\n                        m_child_orphans.push(other_node);\r\n                      }\r\n                    }\r\n                  }\r\n                  set_tree(current_node, tColorTraits::gray());\r\n                } //no parent found\r\n              } //source-tree-adoption\r\n              else{\r\n                //now we should be in the sink-tree, check that...\r\n                assert(get_tree(current_node) == tColorTraits::white());\r\n                out_edge_iterator ei, e_end;\r\n                edge_descriptor new_parent_edge;\r\n                tDistanceVal min_distance = (std::numeric_limits<tDistanceVal>::max)();\r\n                for(boost::tie(ei, e_end) = out_edges(current_node, m_g); ei != e_end; ++ei){\r\n                  const edge_descriptor out_edge = *ei;\r\n                  if(m_res_cap_map[out_edge] > 0){\r\n                    const vertex_descriptor other_node = target(out_edge, m_g);\r\n                    if(get_tree(other_node) == tColorTraits::white() && has_sink_connect(other_node))\r\n                      if(m_dist_map[other_node] < min_distance){\r\n                        min_distance = m_dist_map[other_node];\r\n                        new_parent_edge = out_edge;\r\n                      }\r\n                  }\r\n                }\r\n                if(min_distance != (std::numeric_limits<tDistanceVal>::max)()){\r\n                  set_edge_to_parent(current_node, new_parent_edge);\r\n                  m_dist_map[current_node] = min_distance + 1;\r\n                  m_time_map[current_node] = m_time;\r\n                } else{\r\n                  m_time_map[current_node] = 0;\r\n                  for(boost::tie(ei, e_end) = out_edges(current_node, m_g); ei != e_end; ++ei){\r\n                    const edge_descriptor out_edge = *ei;\r\n                    const vertex_descriptor other_node = target(out_edge, m_g);\r\n                    if(get_tree(other_node) == tColorTraits::white() && has_parent(other_node)){\r\n                      if(m_res_cap_map[out_edge] > 0){\r\n                        add_active_node(other_node);\r\n                      }\r\n                      if(target(get_edge_to_parent(other_node), m_g) == current_node){\r\n                        //we were it's parent, so it has to find a new one, too\r\n                        set_no_parent(other_node);\r\n                        m_child_orphans.push(other_node);\r\n                      }\r\n                    }\r\n                  }\r\n                  set_tree(current_node, tColorTraits::gray());\r\n                } //no parent found\r\n              } //sink-tree adoption\r\n            } //while !orphans.empty()\r\n          } //adopt\r\n\r\n          /**\r\n          * return next active vertex if there is one, otherwise a null_vertex\r\n          */\r\n          inline vertex_descriptor get_next_active_node(){\r\n            while(true){\r\n              if(m_active_nodes.empty())\r\n                return graph_traits<Graph>::null_vertex();\r\n              vertex_descriptor v = m_active_nodes.front();\r\n\r\n              if(!has_parent(v) && v != m_source && v != m_sink){ //if it has no parent, this node can't be active(if its not source or sink)\r\n                m_active_nodes.pop();\r\n                m_in_active_list_map[v] = false;\r\n              } else{\r\n                assert(get_tree(v) == tColorTraits::black() || get_tree(v) == tColorTraits::white());\r\n                return v;\r\n              }\r\n            }\r\n          }\r\n\r\n          /**\r\n          * adds v as an active vertex, but only if its not in the list already\r\n          */\r\n          inline void add_active_node(vertex_descriptor v){\r\n            assert(get_tree(v) != tColorTraits::gray());\r\n            if(m_in_active_list_map[v]){\r\n              return;\r\n            } else{\r\n              m_in_active_list_map[v] = true;\r\n              m_active_nodes.push(v);\r\n            }\r\n          }\r\n\r\n          /**\r\n           * finish_node removes a node from the front of the active queue (its called in grow phase, if no more paths can be found using this node)\r\n           */\r\n          inline void finish_node(vertex_descriptor v){\r\n            assert(m_active_nodes.front() == v);\r\n            m_active_nodes.pop();\r\n            m_in_active_list_map[v] = false;\r\n            m_last_grow_vertex = graph_traits<Graph>::null_vertex();\r\n          }\r\n\r\n          /**\r\n          * removes a vertex from the queue of active nodes (actually this does nothing,\r\n          * but checks if this node has no parent edge, as this is the criteria for beeing no more active)\r\n          */\r\n          inline void remove_active_node(vertex_descriptor v){\r\n            assert(!has_parent(v));\r\n          }\r\n\r\n          /**\r\n          * returns the search tree of v; tColorValue::black() for source tree, white() for sink tree, gray() for no tree\r\n          */\r\n          inline tColorValue get_tree(vertex_descriptor v) const {\r\n            return m_tree_map[v];\r\n          }\r\n\r\n          /**\r\n          * sets search tree of v; tColorValue::black() for source tree, white() for sink tree, gray() for no tree\r\n          */\r\n          inline void set_tree(vertex_descriptor v, tColorValue t){\r\n            m_tree_map[v] = t;\r\n          }\r\n\r\n          /**\r\n           * returns edge to parent vertex of v;\r\n           */\r\n          inline edge_descriptor get_edge_to_parent(vertex_descriptor v) const{\r\n            return m_pre_map[v];\r\n          }\r\n\r\n          /**\r\n           * returns true if the edge stored in m_pre_map[v] is a valid entry\r\n           */\r\n          inline bool has_parent(vertex_descriptor v) const{\r\n            return m_has_parent_map[v];\r\n          }\r\n\r\n          /**\r\n           * sets edge to parent vertex of v;\r\n          */\r\n          inline void set_edge_to_parent(vertex_descriptor v, edge_descriptor f_edge_to_parent){\r\n            assert(m_res_cap_map[f_edge_to_parent] > 0);\r\n            m_pre_map[v] = f_edge_to_parent;\r\n            m_has_parent_map[v] = true;\r\n          }\r\n\r\n          /**\r\n           * removes the edge to parent of v (this is done by invalidating the entry an additional map)\r\n           */\r\n          inline void set_no_parent(vertex_descriptor v){\r\n            m_has_parent_map[v] = false;\r\n          }\r\n\r\n          /**\r\n           * checks if vertex v has a connect to the sink-vertex (@var m_sink)\r\n           * @param v the vertex which is checked\r\n           * @return true if a path to the sink was found, false if not\r\n           */\r\n          inline bool has_sink_connect(vertex_descriptor v){\r\n            tDistanceVal current_distance = 0;\r\n            vertex_descriptor current_vertex = v;\r\n            while(true){\r\n              if(m_time_map[current_vertex] == m_time){\r\n                //we found a node which was already checked this round. use it for distance calculations\r\n                current_distance += m_dist_map[current_vertex];\r\n                break;\r\n              }\r\n              if(current_vertex == m_sink){\r\n                m_time_map[m_sink] = m_time;\r\n                break;\r\n              }\r\n              if(has_parent(current_vertex)){\r\n                //it has a parent, so get it\r\n                current_vertex = target(get_edge_to_parent(current_vertex), m_g);\r\n                ++current_distance;\r\n              } else{\r\n                //no path found\r\n                return false;\r\n              }\r\n            }\r\n            current_vertex=v;\r\n            while(m_time_map[current_vertex] != m_time){\r\n              m_dist_map[current_vertex] = current_distance--;\r\n              m_time_map[current_vertex] = m_time;\r\n              current_vertex = target(get_edge_to_parent(current_vertex), m_g);\r\n            }\r\n            return true;\r\n          }\r\n\r\n          /**\r\n           * checks if vertex v has a connect to the source-vertex (@var m_source)\r\n           * @param v the vertex which is checked\r\n           * @return true if a path to the source was found, false if not\r\n           */\r\n          inline bool has_source_connect(vertex_descriptor v){\r\n            tDistanceVal current_distance = 0;\r\n            vertex_descriptor current_vertex = v;\r\n            while(true){\r\n              if(m_time_map[current_vertex] == m_time){\r\n                //we found a node which was already checked this round. use it for distance calculations\r\n                current_distance += m_dist_map[current_vertex];\r\n                break;\r\n              }\r\n              if(current_vertex == m_source){\r\n                m_time_map[m_source] = m_time;\r\n                break;\r\n              }\r\n              if(has_parent(current_vertex)){\r\n                //it has a parent, so get it\r\n                current_vertex = source(get_edge_to_parent(current_vertex), m_g);\r\n                ++current_distance;\r\n              } else{\r\n                //no path found\r\n                return false;\r\n              }\r\n            }\r\n            current_vertex=v;\r\n            while(m_time_map[current_vertex] != m_time){\r\n                m_dist_map[current_vertex] = current_distance-- ;\r\n                m_time_map[current_vertex] = m_time;\r\n                current_vertex = source(get_edge_to_parent(current_vertex), m_g);\r\n            }\r\n            return true;\r\n          }\r\n\r\n          /**\r\n          * returns true, if p is closer to a terminal than q\r\n          */\r\n          inline bool is_closer_to_terminal(vertex_descriptor p, vertex_descriptor q){\r\n            //checks the timestamps first, to build no cycles, and after that the real distance\r\n            return (m_time_map[q] <= m_time_map[p] && m_dist_map[q] > m_dist_map[p]+1);\r\n          }\r\n\r\n          ////////\r\n          // member vars\r\n          ////////\r\n          Graph& m_g;\r\n          IndexMap m_index_map;\r\n          EdgeCapacityMap m_cap_map;\r\n          ResidualCapacityEdgeMap m_res_cap_map;\r\n          ReverseEdgeMap m_rev_edge_map;\r\n          PredecessorMap m_pre_map; //stores paths found in the growth stage\r\n          ColorMap m_tree_map; //maps each vertex into one of the two search tree or none (gray())\r\n          DistanceMap m_dist_map; //stores distance to source/sink nodes\r\n          vertex_descriptor m_source;\r\n          vertex_descriptor m_sink;\r\n\r\n          tQueue m_active_nodes;\r\n          std::vector<bool> m_in_active_list_vec;\r\n          iterator_property_map<std::vector<bool>::iterator, IndexMap> m_in_active_list_map;\r\n\r\n          std::list<vertex_descriptor> m_orphans;\r\n          tQueue m_child_orphans; // we use a second queuqe for child orphans, as they are FIFO processed\r\n\r\n          std::vector<bool> m_has_parent_vec;\r\n          iterator_property_map<std::vector<bool>::iterator, IndexMap> m_has_parent_map;\r\n\r\n          std::vector<long> m_time_vec; //timestamp of each node, used for sink/source-path calculations\r\n          iterator_property_map<std::vector<long>::iterator, IndexMap> m_time_map;\r\n          tEdgeVal m_flow;\r\n          long m_time;\r\n          vertex_descriptor m_last_grow_vertex;\r\n          out_edge_iterator m_last_grow_edge_it;\r\n          out_edge_iterator m_last_grow_edge_end;\r\n    };\r\n  } //namespace detail\r\n\r\n  /**\r\n   * non-named-parameter version, given everything\r\n   * this is the catch all version\r\n   */\r\n  template <class Graph, class CapacityEdgeMap, class ResidualCapacityEdgeMap, class ReverseEdgeMap,\r\n    class PredecessorMap, class ColorMap, class DistanceMap, class IndexMap>\r\n  typename property_traits<CapacityEdgeMap>::value_type\r\n  kolmogorov_max_flow\r\n      (Graph& g,\r\n       CapacityEdgeMap cap,\r\n       ResidualCapacityEdgeMap res_cap,\r\n       ReverseEdgeMap rev_map,\r\n       PredecessorMap pre_map,\r\n       ColorMap color,\r\n       DistanceMap dist,\r\n       IndexMap idx,\r\n       typename graph_traits<Graph>::vertex_descriptor src,\r\n       typename graph_traits<Graph>::vertex_descriptor sink\r\n       )\r\n  {\r\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\r\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\r\n    //as this method is the last one before we instantiate the solver, we do the concept checks here\r\n    function_requires<VertexListGraphConcept<Graph> >(); //to have vertices(), num_vertices(),\r\n    function_requires<EdgeListGraphConcept<Graph> >(); //to have edges()\r\n    function_requires<IncidenceGraphConcept<Graph> >(); //to have source(), target() and out_edges()\r\n    function_requires<LvaluePropertyMapConcept<CapacityEdgeMap, edge_descriptor> >(); //read flow-values from edges\r\n    function_requires<Mutable_LvaluePropertyMapConcept<ResidualCapacityEdgeMap, edge_descriptor> >(); //write flow-values to residuals\r\n    function_requires<LvaluePropertyMapConcept<ReverseEdgeMap, edge_descriptor> >(); //read out reverse edges\r\n    function_requires<Mutable_LvaluePropertyMapConcept<PredecessorMap, vertex_descriptor> >(); //store predecessor there\r\n    function_requires<Mutable_LvaluePropertyMapConcept<ColorMap, vertex_descriptor> >(); //write corresponding tree\r\n    function_requires<Mutable_LvaluePropertyMapConcept<DistanceMap, vertex_descriptor> >(); //write distance to source/sink\r\n    function_requires<ReadablePropertyMapConcept<IndexMap, vertex_descriptor> >(); //get index 0...|V|-1\r\n    assert(num_vertices(g) >= 2 && src != sink);\r\n    detail::kolmogorov<Graph, CapacityEdgeMap, ResidualCapacityEdgeMap, ReverseEdgeMap, PredecessorMap, ColorMap, DistanceMap, IndexMap>\r\n        algo(g, cap, res_cap, rev_map, pre_map, color, dist, idx, src, sink);\r\n        return algo.max_flow();\r\n  }\r\n\r\n  /**\r\n   * non-named-parameter version, given: capacity, residucal_capacity, reverse_edges, and an index map.\r\n   */\r\n  template <class Graph, class CapacityEdgeMap, class ResidualCapacityEdgeMap, class ReverseEdgeMap, class IndexMap>\r\n  typename property_traits<CapacityEdgeMap>::value_type\r\n   kolmogorov_max_flow\r\n       (Graph& g,\r\n       CapacityEdgeMap cap,\r\n       ResidualCapacityEdgeMap res_cap,\r\n       ReverseEdgeMap rev,\r\n       IndexMap idx,\r\n       typename graph_traits<Graph>::vertex_descriptor src,\r\n       typename graph_traits<Graph>::vertex_descriptor sink)\r\n   {\r\n     typename graph_traits<Graph>::vertices_size_type n_verts = num_vertices(g);\r\n     std::vector<typename graph_traits<Graph>::edge_descriptor> predecessor_vec(n_verts);\r\n     std::vector<default_color_type> color_vec(n_verts);\r\n     std::vector<typename graph_traits<Graph>::vertices_size_type> distance_vec(n_verts);\r\n     return kolmogorov_max_flow\r\n         (g, cap, res_cap, rev,\r\n          make_iterator_property_map(predecessor_vec.begin(), idx),\r\n          make_iterator_property_map(color_vec.begin(), idx),\r\n          make_iterator_property_map(distance_vec.begin(), idx),\r\n          idx, src, sink);\r\n   }\r\n\r\n  /**\r\n   * non-named-parameter version, some given: capacity, residual_capacity, reverse_edges, color_map and an index map.\r\n   * Use this if you are interested in the minimum cut, as the color map provides that info\r\n   */\r\n   template <class Graph, class CapacityEdgeMap, class ResidualCapacityEdgeMap, class ReverseEdgeMap, class ColorMap, class IndexMap>\r\n   typename property_traits<CapacityEdgeMap>::value_type\r\n   kolmogorov_max_flow\r\n       (Graph& g,\r\n        CapacityEdgeMap cap,\r\n        ResidualCapacityEdgeMap res_cap,\r\n        ReverseEdgeMap rev,\r\n        ColorMap color,\r\n        IndexMap idx,\r\n        typename graph_traits<Graph>::vertex_descriptor src,\r\n        typename graph_traits<Graph>::vertex_descriptor sink)\r\n   {\r\n     typename graph_traits<Graph>::vertices_size_type n_verts = num_vertices(g);\r\n     std::vector<typename graph_traits<Graph>::edge_descriptor> predecessor_vec(n_verts);\r\n     std::vector<typename graph_traits<Graph>::vertices_size_type> distance_vec(n_verts);\r\n\r\n     return kolmogorov_max_flow\r\n         (g, cap, res_cap, rev,\r\n          make_iterator_property_map(predecessor_vec.begin(), idx),\r\n          color,\r\n          make_iterator_property_map(distance_vec.begin(), idx),\r\n          idx, src, sink);\r\n   }\r\n\r\n  /**\r\n   * named-parameter version, some given\r\n   */\r\n   template <class Graph, class P, class T, class R>\r\n   typename property_traits<typename property_map<Graph, edge_capacity_t>::const_type>::value_type\r\n   kolmogorov_max_flow\r\n       (Graph& g,\r\n        typename graph_traits<Graph>::vertex_descriptor src,\r\n        typename graph_traits<Graph>::vertex_descriptor sink,\r\n        const bgl_named_params<P, T, R>& params)\r\n   {\r\n     return kolmogorov_max_flow(g,\r\n                                choose_const_pmap(get_param(params, edge_capacity), g, edge_capacity),\r\n                                choose_pmap(get_param(params, edge_residual_capacity), g, edge_residual_capacity),\r\n                                choose_const_pmap(get_param(params, edge_reverse), g, edge_reverse),\r\n                                choose_pmap(get_param(params, vertex_predecessor), g, vertex_predecessor),\r\n                                choose_pmap(get_param(params, vertex_color), g, vertex_color),\r\n                                choose_pmap(get_param(params, vertex_distance), g, vertex_distance),\r\n                                choose_const_pmap(get_param(params, vertex_index), g, vertex_index),\r\n                                src, sink);\r\n   }\r\n\r\n  /**\r\n   * named-parameter version, none given\r\n   */\r\n   template <class Graph>\r\n   typename property_traits<typename property_map<Graph, edge_capacity_t>::const_type>::value_type\r\n   kolmogorov_max_flow\r\n       (Graph& g,\r\n        typename graph_traits<Graph>::vertex_descriptor src,\r\n        typename graph_traits<Graph>::vertex_descriptor sink)\r\n   {\r\n     bgl_named_params<int, buffer_param_t> params(0); // bogus empty param\r\n     return kolmogorov_max_flow(g, src, sink, params);\r\n   }\r\n} // namespace boost\r\n\r\n#endif // BOOST_KOLMOGOROV_MAX_FLOW_HPP\r\n\r\n", "meta": {"hexsha": "edb4b7eceb71d5ee231b4853a3485a975b3fa54c", "size": 40320, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Compiler/boost/boost/graph/kolmogorov_max_flow.hpp", "max_stars_repo_name": "davidov541/MiniC", "max_stars_repo_head_hexsha": "d3b16a1568b97a4d801880b110a8be04fe848adb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-16T01:05:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-26T07:38:43.000Z", "max_issues_repo_path": "LibsExternes/Includes/boost/graph/kolmogorov_max_flow.hpp", "max_issues_repo_name": "benkaraban/anima-games-engine", "max_issues_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-05T01:56:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-05T01:56:28.000Z", "max_forks_repo_path": "LibsExternes/Includes/boost/graph/kolmogorov_max_flow.hpp", "max_forks_repo_name": "benkaraban/anima-games-engine", "max_forks_repo_head_hexsha": "8aa7a5368933f1b82c90f24814f1447119346c3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.472392638, "max_line_length": 164, "alphanum_fraction": 0.5826140873, "num_tokens": 8269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.22256175291053032}}
{"text": "/**\n * @file dens_matrix.cpp\n * @brief full matrix\n * @date 2009-12-08\n */\n#ifdef BSPY_EXPORTING_PLUGIN\n#include <boost/python.hpp>\n#endif\n#include <sstream>\n\n#include \"dens_matrix.h\"\n#include \"bcsr_matrix_iface.h\"\n\n#include \"pyublas/numpy.hpp\"\n\nusing namespace std;\nusing namespace boost::python;\n\n\nnamespace blue_sky\n{\n  dens_matrix::dens_matrix (bs_type_ctor_param)\n        : dens_matrix_iface (),\n        values (BS_KERNEL.create_object (v_float::bs_type ()))\n    {\n    }\n\n  dens_matrix ::dens_matrix (const this_t & /*src*/) : bs_refcounter (),\n        values (BS_KERNEL.create_object (v_float::bs_type ()))\n    {\n    }\n\n  // TODO:\n  int\n  dens_matrix::matrix_vector_product (spv_double v_, spv_double r_) const\n    {\n      t_long block_rows;\n      t_long block_cols;\n      t_long clb = calc_block_size < 1 ? (n_rows + n_cols) : calc_block_size;\n\n      if (n_cols != (t_long) v_->size () || n_rows != (t_long) r_->size ())\n        return -1;\n\n      t_double *v = &(*v_)[0];\n      t_double *r = &(*r_)[0];\n\n      block_rows = n_rows / clb;\n      if (n_rows % clb)\n        ++block_rows;\n\n      block_cols = n_cols / clb;\n      if (n_cols % clb)\n        ++block_cols;\n\n      for (t_long i = 0; i < block_rows; ++i)\n        {\n          for (t_long j = 0; j < block_cols; ++j)\n            {\n              block_mv_product (i, j, v, r);\n            }\n        }\n      return 0;\n    }\n\n  // TODO:\n  int\n  dens_matrix::matrix_vector_product_t (spv_double v_,\n                                                 spv_double r_) const\n    {\n      t_long block_rows;\n      t_long block_cols;\n      t_long clb = calc_block_size < 1 ? (n_rows + n_cols) : calc_block_size;\n\n      if (n_cols != (t_long)r_->size () || n_rows != (t_long)v_->size ())\n        return -1;\n\n      t_double *v = &(*v_)[0];\n      t_double *r = &(*r_)[0];\n\n      block_rows = n_rows / clb;\n      if (n_rows % clb)\n        ++block_rows;\n\n      block_cols = n_cols / clb;\n      if (n_cols % clb)\n        ++block_cols;\n\n      for (t_long i = 0; i < block_rows; ++i)\n        {\n          for (t_long j = 0; j < block_cols; ++j)\n            {\n              block_mv_product_t (i, j, v, r);\n            }\n        }\n      return 0;\n    }\n\n  int\n  dens_matrix::calc_lin_comb (t_double alpha,\n                                       t_double beta,\n                                       spv_double u_,\n                                       spv_double v_,\n                                       spv_double r_) const\n    {\n      static const t_double eps = t_double (1.0e-12);\n      t_long i;\n      int r_code = 0;\n\n      t_double *v = &(*v_)[0];\n      t_double *r = &(*r_)[0];\n\n      memset (r, 0, sizeof (t_double) * n_rows);\n\n      if (fabs (alpha) > eps)\n        {\n          r_code = matrix_vector_product (u_, r_);\n          for (i = 0; i < n_rows; ++i)\n            r[i] *= alpha;\n        }\n      if (fabs (beta) > eps)\n        {\n          for (i = 0; i < n_rows; ++i)\n            r[i] += v[i] * beta;\n        }\n      return r_code;\n    }\n\n  int\n  dens_matrix::init_by_matrix (sp_base_t matrix_)\n    {\n      BS_ASSERT (matrix_);\n\n      typedef smart_ptr<bcsr_matrix_iface, true>  sp_bcsr_matrix_iface;\n\n      sp_dens_matrix_iface_t dense_matrix_ (matrix_, bs_dynamic_cast ());\n      sp_bcsr_matrix_iface   bcsr_matrix_  (matrix_, bs_dynamic_cast ());\n\n      if (dense_matrix_)\n        {\n          init (dense_matrix_->get_n_rows (), dense_matrix_->get_n_cols (),\n                dense_matrix_->get_calc_block_size ());\n          //TODO: copy values\n        }\n      else if (bcsr_matrix_)\n        {\n          t_long i, j, j1, j2, cl;\n          if (bcsr_matrix_->get_n_block_size () > 1)\n            {\n              bs_throw_exception (\"dens_matrix::init_by_matrix (bcsr) n_block_size must be = 1\");\n            }\n\n          if (init (bcsr_matrix_->get_n_rows (), bcsr_matrix_->get_n_cols (),\n                    bcsr_matrix_->get_n_block_size ()))\n             return -3;\n\n          t_long  *rows = &(*bcsr_matrix_->get_rows_ptr ())[0];\n          t_long  *cols = &(*bcsr_matrix_->get_cols_ind ())[0];\n          t_float *vals = &(*bcsr_matrix_->get_values ())[0];\n          t_float *values_ptr = &(*values)[0];\n\n          // set values zero. then copy matrix values to dense\n          memset (values_ptr, 0, n_rows * n_cols * sizeof (t_float));\n          for (i = 0; i < n_rows; ++i)\n            {\n              j1 = rows[i];\n              j2 = rows[i + 1];\n              for (j = j1; j < j2; ++j)\n                {\n                  cl = cols[j];\n                  values_ptr[i * n_rows + cl] = vals[j];\n                }\n            }\n        }\n      else\n        {\n          bs_throw_exception (\"dens_matrix::init_by_matrix: wrong type\");\n        }\n      return 0;\n    }\n\n  int\n  dens_matrix::init (const t_long new_n_rows,\n                     const t_long new_n_cols,\n                     const t_long block_size)\n    {\n      npy_intp dims[2];\n      if (new_n_rows < 1 || new_n_cols < 1)\n        return -1;\n      dims[0] = n_rows = new_n_rows;\n      dims[1] = n_cols = new_n_cols;\n      calc_block_size = block_size;\n      values->resize (n_rows * n_cols);\n      // TODO: add this method\n      //values->reshape (2, dims);\n      //std::fill (values->numpy.as_ublas ().data ().begin (), values->numpy.as_ublas ().data ().end (), 0);\n      if (values->size ())\n        std::fill (values->begin (), values->end (), 0);\n      return 0;\n    }\n\n  int\n  dens_matrix::copy (sp_dens_matrix_iface_t matrix)\n    {\n      if (init (matrix->get_n_rows (), matrix->get_n_cols (), matrix->get_calc_block_size ()))\n        return -3;\n      values = matrix->get_values ()->clone ();\n      //values->numpy.resize (matrix->get_values ()->numpy.size1 (), matrix->get_values ()->numpy.size2 ());\n      //values->numpy.as_ublas () = matrix->get_values ()->numpy.as_ublas ();\n                              //                  matrix->get_values ()->numpy.as_ublas ().data ().end ());\n\n\n      //memcpy (&values[0], &(matrix->get_values_const ())[0], n_rows * n_cols * sizeof (t_float));\n      return 0;\n    }\n\n  void\n  dens_matrix::block_mv_product (t_long row_block,\n                                          t_long col_block,\n                                          const t_double *v,\n                                          t_double *r) const\n    {\n      t_long block_n_rows;\n      t_long block_n_cols;\n      const t_float *block;\n      const t_double *block_v;\n      t_double *block_r;\n      t_long clb = calc_block_size < 1 ? (n_rows + n_cols) : calc_block_size;\n\n      // calculate block start position\n      //block = &values[row_block * clb * n_cols + col_block * clb];\n      block = &(*values)[0] + row_block * clb * n_cols + col_block * clb;\n      block_v = v + col_block * clb;\n      block_r = r + row_block * clb;\n\n      if ((row_block + 1) * clb <= n_rows)\n        block_n_rows = clb;\n      else\n        block_n_rows = n_rows - row_block * clb;\n\n      if ((col_block + 1) * clb <= n_cols)\n        block_n_cols = clb;\n      else\n        block_n_cols = n_cols - col_block * clb;\n\n      for (t_long i = 0; i < block_n_rows; ++i)\n        {\n          for (t_long j = 0; j < block_n_cols; ++j)\n            {\n              block_r[i] += block[i * n_rows + j] * block_v[j];\n            }\n        }\n    }\n\n  void\n  dens_matrix::block_mv_product_t (t_long row_block,\n                                            t_long col_block,\n                                            const t_double *v,\n                                            t_double *r) const\n    {\n      t_long block_n_rows;\n      t_long block_n_cols;\n      const t_float *block;\n      const t_double *block_v;\n      t_double *block_r;\n      t_long clb = calc_block_size < 1 ? (n_rows + n_cols) : calc_block_size;\n\n      // calculate block start position\n      block = &(*values)[0] + row_block * clb * n_cols + col_block * clb;\n      block_v = v + row_block * clb;\n      block_r = r + col_block * clb;\n\n      if ((row_block + 1) * clb <= n_rows)\n        block_n_rows = clb;\n      else\n        block_n_rows = n_rows - row_block * clb;\n\n      if ((col_block + 1) * clb <= n_cols)\n        block_n_cols = clb;\n      else\n        block_n_cols = n_cols - col_block * clb;\n\n      for (t_long i = 0; i < block_n_rows; ++i)\n        {\n          for (t_long j = 0; j < block_n_cols; ++j)\n            {\n              block_r[j] += block[i * n_rows + j] * block_v[i];\n            }\n        }\n    }\n\n#ifdef BSPY_EXPORTING_PLUGIN\n  std::string\n  dens_matrix::py_str () const\n    {\n      stringstream s;\n\n      s << \"Dens matrix\\n--------------------------------\\n\";\n      s << \"\\tRows:                  \" << n_rows << \"\\n\";\n      s << \"\\tColumns:               \" << n_cols << \"\\n\";\n      s << \"\\tCalc Block:            \" << calc_block_size << \"\\n\";\n      s << \"\\tAllocated memory (Mb): \" << get_allocated_memory_in_mbytes () << \"\\n\";\n      s << \"--------------------------------\\n\";\n      return s.str ();\n    }\n#endif //BSPY_EXPORTING_PLUGIN\n/////////////////////////////////BS Register\n/////////////////////////////////Stuff//////////////////////////\n\n  BLUE_SKY_TYPE_STD_CREATE (dens_matrix);\n  BLUE_SKY_TYPE_STD_COPY (dens_matrix);\n\n  BLUE_SKY_TYPE_IMPL (dens_matrix, dens_matrix_iface,  \"dens_matrix\", \"Dens Matrix class\", \"Realization of Dens Matricies\");\n}  // blue_sky namespace\n", "meta": {"hexsha": "871d8e2d0086c3d2446faba9725d9a4d294b2653", "size": 9274, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bs_mtx/src/dens_matrix.cpp", "max_stars_repo_name": "bs-eagle/bs-eagle", "max_stars_repo_head_hexsha": "b1017a4f6ac2dcafba2deafec84052ddde792671", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-07-16T22:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T10:16:42.000Z", "max_issues_repo_path": "bs_mtx/src/dens_matrix.cpp", "max_issues_repo_name": "bs-eagle/bs-eagle", "max_issues_repo_head_hexsha": "b1017a4f6ac2dcafba2deafec84052ddde792671", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bs_mtx/src/dens_matrix.cpp", "max_forks_repo_name": "bs-eagle/bs-eagle", "max_forks_repo_head_hexsha": "b1017a4f6ac2dcafba2deafec84052ddde792671", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-01-05T20:06:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-20T16:19:10.000Z", "avg_line_length": 29.5350318471, "max_line_length": 124, "alphanum_fraction": 0.5053914169, "num_tokens": 2472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.22256175291053032}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017, 2018.\r\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 5.0.0\r\n\r\n// Original copyright notice:\r\n\r\n// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef BOOST_GEOMETRY_PROJECTIONS_CHAMB_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_CHAMB_HPP\r\n\r\n#include <boost/geometry/util/math.hpp>\r\n#include <cstdio>\r\n\r\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\r\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\r\n#include <boost/geometry/srs/projections/impl/aasincos.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace projections\r\n{\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail { namespace chamb\r\n    {\r\n\r\n            //static const double third = 0.333333333333333333;\r\n            static const double tolerance = 1e-9;\r\n\r\n            // specific for 'chamb'\r\n            template <typename T>\r\n            struct vect_ra { T r, Az; };\r\n            template <typename T>\r\n            struct point_xy { T x, y; };\r\n\r\n            template <typename T>\r\n            struct par_chamb\r\n            {\r\n                struct { /* control point data */\r\n                    T phi, lam;\r\n                    T cosphi, sinphi;\r\n                    vect_ra<T> v;\r\n                    point_xy<T> p;\r\n                    T Az;\r\n                } c[3];\r\n                point_xy<T> p;\r\n                T beta_0, beta_1, beta_2;\r\n            };\r\n\r\n            /* distance and azimuth from point 1 to point 2 */\r\n            template <typename T>\r\n            inline vect_ra<T> vect(T const& dphi, T const& c1, T const& s1, T const& c2, T const& s2, T const& dlam)\r\n            {\r\n                vect_ra<T> v;\r\n                T cdl, dp, dl;\r\n\r\n                cdl = cos(dlam);\r\n                if (fabs(dphi) > 1. || fabs(dlam) > 1.)\r\n                    v.r = aacos(s1 * s2 + c1 * c2 * cdl);\r\n                else { /* more accurate for smaller distances */\r\n                    dp = sin(.5 * dphi);\r\n                    dl = sin(.5 * dlam);\r\n                    v.r = 2. * aasin(sqrt(dp * dp + c1 * c2 * dl * dl));\r\n                }\r\n                if (fabs(v.r) > tolerance)\r\n                    v.Az = atan2(c2 * sin(dlam), c1 * s2 - s1 * c2 * cdl);\r\n                else\r\n                    v.r = v.Az = 0.;\r\n                return v;\r\n            }\r\n\r\n            /* law of cosines */\r\n            template <typename T>\r\n            inline T lc(T const& b, T const& c, T const& a)\r\n            {\r\n                return aacos(.5 * (b * b + c * c - a * a) / (b * c));\r\n            }\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename T, typename Parameters>\r\n            struct base_chamb_spheroid\r\n                : public base_t_f<base_chamb_spheroid<T, Parameters>, T, Parameters>\r\n            {\r\n                par_chamb<T> m_proj_parm;\r\n\r\n                inline base_chamb_spheroid(const Parameters& par)\r\n                    : base_t_f<base_chamb_spheroid<T, Parameters>, T, Parameters>(*this, par)\r\n                {}\r\n\r\n                // FORWARD(s_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\r\n                {\r\n                    static const T third = detail::third<T>();\r\n\r\n                    T sinphi, cosphi, a;\r\n                    vect_ra<T> v[3];\r\n                    int i, j;\r\n\r\n                    sinphi = sin(lp_lat);\r\n                    cosphi = cos(lp_lat);\r\n                    for (i = 0; i < 3; ++i) { /* dist/azimiths from control */\r\n                        v[i] = vect(lp_lat - this->m_proj_parm.c[i].phi, this->m_proj_parm.c[i].cosphi, this->m_proj_parm.c[i].sinphi,\r\n                            cosphi, sinphi, lp_lon - this->m_proj_parm.c[i].lam);\r\n                        if (v[i].r == 0.0)\r\n                            break;\r\n                        v[i].Az = adjlon(v[i].Az - this->m_proj_parm.c[i].v.Az);\r\n                    }\r\n                    if (i < 3) /* current point at control point */\r\n                        { xy_x = this->m_proj_parm.c[i].p.x; xy_y = this->m_proj_parm.c[i].p.y; }\r\n                    else { /* point mean of intersepts */\r\n                        { xy_x = this->m_proj_parm.p.x; xy_y = this->m_proj_parm.p.y; }\r\n                        for (i = 0; i < 3; ++i) {\r\n                            j = i == 2 ? 0 : i + 1;\r\n                            a = lc(this->m_proj_parm.c[i].v.r, v[i].r, v[j].r);\r\n                            if (v[i].Az < 0.)\r\n                                a = -a;\r\n                            if (! i) { /* coord comp unique to each arc */\r\n                                xy_x += v[i].r * cos(a);\r\n                                xy_y -= v[i].r * sin(a);\r\n                            } else if (i == 1) {\r\n                                a = this->m_proj_parm.beta_1 - a;\r\n                                xy_x -= v[i].r * cos(a);\r\n                                xy_y -= v[i].r * sin(a);\r\n                            } else {\r\n                                a = this->m_proj_parm.beta_2 - a;\r\n                                xy_x += v[i].r * cos(a);\r\n                                xy_y += v[i].r * sin(a);\r\n                            }\r\n                        }\r\n                        xy_x *= third; /* mean of arc intercepts */\r\n                        xy_y *= third;\r\n                    }\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"chamb_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            template <typename T>\r\n            inline T chamb_init_lat(srs::detail::proj4_parameters const& params, int i)\r\n            {\r\n                static const std::string lat[3] = {\"lat_1\", \"lat_2\", \"lat_3\"};\r\n                return _pj_get_param_r<T>(params, lat[i]);\r\n            }\r\n            template <typename T>\r\n            inline T chamb_init_lat(srs::dpar::parameters<T> const& params, int i)\r\n            {\r\n                static const srs::dpar::name_r lat[3] = {srs::dpar::lat_1, srs::dpar::lat_2, srs::dpar::lat_3};\r\n                return _pj_get_param_r<T>(params, lat[i]);\r\n            }\r\n\r\n            template <typename T>\r\n            inline T chamb_init_lon(srs::detail::proj4_parameters const& params, int i)\r\n            {\r\n                static const std::string lon[3] = {\"lon_1\", \"lon_2\", \"lon_3\"};\r\n                return _pj_get_param_r<T>(params, lon[i]);\r\n            }\r\n            template <typename T>\r\n            inline T chamb_init_lon(srs::dpar::parameters<T> const& params, int i)\r\n            {\r\n                static const srs::dpar::name_r lon[3] = {srs::dpar::lon_1, srs::dpar::lon_2, srs::dpar::lon_3};\r\n                return _pj_get_param_r<T>(params, lon[i]);\r\n            }\r\n\r\n            // Chamberlin Trimetric\r\n            template <typename Params, typename Parameters, typename T>\r\n            inline void setup_chamb(Params const& params, Parameters& par, par_chamb<T>& proj_parm)\r\n            {\r\n                static const T pi = detail::pi<T>();\r\n\r\n                int i, j;\r\n\r\n                for (i = 0; i < 3; ++i) { /* get control point locations */\r\n                    proj_parm.c[i].phi = chamb_init_lat<T>(params, i);\r\n                    proj_parm.c[i].lam = chamb_init_lon<T>(params, i);\r\n                    proj_parm.c[i].lam = adjlon(proj_parm.c[i].lam - par.lam0);\r\n                    proj_parm.c[i].cosphi = cos(proj_parm.c[i].phi);\r\n                    proj_parm.c[i].sinphi = sin(proj_parm.c[i].phi);\r\n                }\r\n                for (i = 0; i < 3; ++i) { /* inter ctl pt. distances and azimuths */\r\n                    j = i == 2 ? 0 : i + 1;\r\n                    proj_parm.c[i].v = vect(proj_parm.c[j].phi - proj_parm.c[i].phi, proj_parm.c[i].cosphi, proj_parm.c[i].sinphi,\r\n                        proj_parm.c[j].cosphi, proj_parm.c[j].sinphi, proj_parm.c[j].lam - proj_parm.c[i].lam);\r\n                    if (proj_parm.c[i].v.r == 0.0)\r\n                        BOOST_THROW_EXCEPTION( projection_exception(error_control_point_no_dist) );\r\n                    /* co-linearity problem ignored for now */\r\n                }\r\n                proj_parm.beta_0 = lc(proj_parm.c[0].v.r, proj_parm.c[2].v.r, proj_parm.c[1].v.r);\r\n                proj_parm.beta_1 = lc(proj_parm.c[0].v.r, proj_parm.c[1].v.r, proj_parm.c[2].v.r);\r\n                proj_parm.beta_2 = pi - proj_parm.beta_0;\r\n                proj_parm.p.y = 2. * (proj_parm.c[0].p.y = proj_parm.c[1].p.y = proj_parm.c[2].v.r * sin(proj_parm.beta_0));\r\n                proj_parm.c[2].p.y = 0.;\r\n                proj_parm.c[0].p.x = - (proj_parm.c[1].p.x = 0.5 * proj_parm.c[0].v.r);\r\n                proj_parm.p.x = proj_parm.c[2].p.x = proj_parm.c[0].p.x + proj_parm.c[2].v.r * cos(proj_parm.beta_0);\r\n\r\n                par.es = 0.;\r\n            }\r\n\r\n    }} // namespace detail::chamb\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Chamberlin Trimetric projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Miscellaneous\r\n         - Spheroid\r\n         - no inverse\r\n        \\par Projection parameters\r\n         - lat_1: Latitude of control point 1 (degrees)\r\n         - lon_1: Longitude of control point 1 (degrees)\r\n         - lat_2: Latitude of control point 2 (degrees)\r\n         - lon_2: Longitude of control point 2 (degrees)\r\n         - lat_3: Latitude of control point 3 (degrees)\r\n         - lon_3: Longitude of control point 3 (degrees)\r\n        \\par Example\r\n        \\image html ex_chamb.gif\r\n    */\r\n    template <typename T, typename Parameters>\r\n    struct chamb_spheroid : public detail::chamb::base_chamb_spheroid<T, Parameters>\r\n    {\r\n        template <typename Params>\r\n        inline chamb_spheroid(Params const& params, Parameters const& par)\r\n            : detail::chamb::base_chamb_spheroid<T, Parameters>(par)\r\n        {\r\n            detail::chamb::setup_chamb(params, this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail\r\n    {\r\n\r\n        // Static projection\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_chamb, chamb_spheroid, chamb_spheroid)\r\n\r\n        // Factory entry(s)\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_F(chamb_entry, chamb_spheroid)\r\n        \r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(chamb_init)\r\n        {\r\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(chamb, chamb_entry);\r\n        }\r\n\r\n    } // namespace detail\r\n    #endif // doxygen\r\n\r\n} // namespace projections\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_CHAMB_HPP\r\n\r\n", "meta": {"hexsha": "cde301497b47b292738012db322e864e00ac9b7a", "size": 12784, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "externals/boost/boost/geometry/srs/projections/proj/chamb.hpp", "max_stars_repo_name": "YuukiTsuchida/v8_embeded", "max_stars_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "externals/boost/boost/geometry/srs/projections/proj/chamb.hpp", "max_issues_repo_name": "YuukiTsuchida/v8_embeded", "max_issues_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "externals/boost/boost/geometry/srs/projections/proj/chamb.hpp", "max_forks_repo_name": "YuukiTsuchida/v8_embeded", "max_forks_repo_head_hexsha": "c6e18f4e91fcc50607f8e3edc745a3afa30b2871", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-06-19T05:06:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-30T03:29:19.000Z", "avg_line_length": 43.3355932203, "max_line_length": 135, "alphanum_fraction": 0.5191645807, "num_tokens": 3072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.3276683139517237, "lm_q1q2_score": 0.22254533497511605}}
{"text": "//---------------------------------------------------------------------------//\n//  MIT License\n//\n//  Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>\n//  Copyright (c) 2020-2021 Nikita Kaskov <nemo@nil.foundation>\n//  Copyright (c) 2021-2022 Aleksei Moskvin <alalmoskvin@gmail.com>\n//  Copyright (c) 2021 Ilias Khairullin <ilias@nil.foundation>\n//\n//  Permission is hereby granted, free of charge, to any person obtaining a copy\n//  of this software and associated documentation files (the \"Software\"), to deal\n//  in the Software without restriction, including without limitation the rights\n//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n//  copies of the Software, and to permit persons to whom the Software is\n//  furnished to do so, subject to the following conditions:\n//\n//  The above copyright notice and this permission notice shall be included in all\n//  copies or substantial portions of the Software.\n//\n//  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n//  SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_MERKLE_PROOF_HPP\n#define CRYPTO3_MERKLE_PROOF_HPP\n\n#include <algorithm>\n#include <vector>\n\n#include <boost/variant.hpp>\n\n#include <nil/crypto3/container/merkle/tree.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace zk {\n            namespace components {\n                template<typename, typename, std::size_t>\n                struct merkle_proof;\n            }    // namespace components\n        }        // namespace zk\n        namespace marshalling {\n            namespace types {\n                template<typename, typename>\n                struct merkle_proof_marshalling;\n            }\n        }    // namespace marshalling\n        namespace containers {\n            namespace detail {\n                template<typename NodeType, std::size_t Arity = 2>\n                struct merkle_proof_impl {\n                    typedef NodeType node_type;\n                    typedef typename node_type::hash_type hash_type;\n\n                    constexpr static const std::size_t arity = Arity;\n\n                    constexpr static const std::size_t value_bits = node_type::value_bits;\n                    typedef typename node_type::value_type value_type;\n\n                    merkle_proof_impl() : _li(0) {};\n\n                    merkle_proof_impl(const merkle_tree<hash_type, arity> &tree, const std::size_t leaf_idx) {\n                        _root = tree.root();\n                        _path.resize(tree.row_count() - 1);\n                        _li = leaf_idx;\n\n                        typename std::vector<layer_type>::iterator v_itr = _path.begin();\n                        std::size_t cur_leaf = leaf_idx;\n                        std::size_t row_len = tree.leaves();\n                        std::size_t row_begin_idx = 0;\n                        while (cur_leaf != tree.size() - 1) {    // while it's not _root\n                            std::size_t cur_leaf_pos = cur_leaf % arity;\n                            std::size_t cur_leaf_arity_pos = (cur_leaf - row_begin_idx) / arity;\n                            std::size_t begin_this_arity = cur_leaf - cur_leaf_pos;\n                            typename layer_type::iterator a_itr = v_itr->begin();\n                            for (size_t i = 0; i < cur_leaf_pos; ++i, ++begin_this_arity, ++a_itr) {\n                                *a_itr = path_element_type(tree[begin_this_arity], i);\n                            }\n                            for (size_t i = cur_leaf_pos + 1; i < arity; ++i, ++begin_this_arity, ++a_itr) {\n                                *a_itr = path_element_type(tree[begin_this_arity + 1], i);\n                            }\n                            v_itr++;\n                            cur_leaf = row_len + row_begin_idx + cur_leaf_arity_pos;\n                            row_begin_idx += row_len;\n                            row_len /= arity;\n                        }\n                    }\n\n                    template<typename Hashable>\n                    bool validate(const Hashable &a) const {\n                        value_type d = crypto3::hash<hash_type>(a);\n                        for (auto &it : _path) {\n                            accumulator_set<hash_type> acc;\n                            size_t i = 0;\n                            for (; (i < arity - 1) && i == it[i]._position; ++i) {\n                                crypto3::hash<hash_type>(it[i]._hash.begin(), it[i]._hash.end(), acc);\n                            }\n                            crypto3::hash<hash_type>(d.begin(), d.end(), acc);\n                            for (; i < arity - 1; ++i) {\n                                crypto3::hash<hash_type>(it[i]._hash.begin(), it[i]._hash.end(), acc);\n                            }\n                            d = accumulators::extract::hash<hash_type>(acc);\n                        }\n                        return (d == _root);\n                    }\n\n                    std::size_t leaf_index() const {\n                        return _li;\n                    }\n\n                    bool operator==(const merkle_proof_impl &rhs) const {\n                        return _li == rhs._li && _root == rhs._root && _path == rhs._path;\n                    }\n                    bool operator!=(const merkle_proof_impl &rhs) const {\n                        return !(rhs == *this);\n                    }\n\n                    struct path_element_type {\n                        path_element_type(value_type x, size_t pos) : _hash(x), _position(pos) {\n                        }\n                        path_element_type() {\n                        }\n\n                        bool operator==(const path_element_type &rhs) const {\n                            return _hash == rhs._hash && _position == rhs._position;\n                        }\n                        bool operator!=(const path_element_type &rhs) const {\n                            return !(rhs == *this);\n                        }\n\n                        const value_type &hash() const {\n                            return _hash;\n                        }\n\n                        std::size_t position() const {\n                            return _position;\n                        }\n\n                        value_type _hash;\n                        std::size_t _position;\n\n                        template<typename, typename>\n                        friend class nil::crypto3::marshalling::types::merkle_proof_marshalling;\n                    };\n\n                    typedef std::array<path_element_type, Arity - 1> layer_type;\n                    typedef std::vector<layer_type> path_type;\n\n                    const value_type &root() const {\n                        return _root;\n                    }\n\n                    const path_type &path() const {\n                        return _path;\n                    }\n\n                private:\n                    std::size_t _li;\n                    value_type _root;\n                    path_type _path;\n\n                    template<typename, typename, std::size_t>\n                    friend class nil::crypto3::zk::components::merkle_proof;\n\n                    template<typename, typename>\n                    friend class nil::crypto3::marshalling::types::merkle_proof_marshalling;\n                };\n            }    // namespace detail\n\n            template<typename T, std::size_t Arity>\n            using merkle_proof =\n                typename std::conditional<nil::crypto3::detail::is_hash<T>::value,\n                                          detail::merkle_proof_impl<detail::merkle_tree_node<T>, Arity>,\n                                          detail::merkle_proof_impl<T, Arity>>::type;\n        }    // namespace containers\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif\n", "meta": {"hexsha": "7ae010a907b1aabab85f64024223d71a836c3cd7", "size": 8279, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/container/merkle/proof.hpp", "max_stars_repo_name": "NilFoundation/crypto3-containers", "max_stars_repo_head_hexsha": "5dd5be6bcec6f2f32a71a058052119e98da1ceff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/container/merkle/proof.hpp", "max_issues_repo_name": "NilFoundation/crypto3-containers", "max_issues_repo_head_hexsha": "5dd5be6bcec6f2f32a71a058052119e98da1ceff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-25T22:02:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T13:03:14.000Z", "max_forks_repo_path": "include/nil/crypto3/container/merkle/proof.hpp", "max_forks_repo_name": "NilFoundation/crypto3-containers", "max_forks_repo_head_hexsha": "5dd5be6bcec6f2f32a71a058052119e98da1ceff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9945652174, "max_line_length": 110, "alphanum_fraction": 0.4864114023, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.22241572285236272}}
{"text": "// Copyright 2019-2020 Josh Pieper, jjp@pobox.com.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"moteus/tool/calibrate.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <deque>\n\n#include <fmt/format.h>\n\n#include <Eigen/Core>\n\n#include <boost/algorithm/string.hpp>\n\n#include \"mjlib/base/system_error.h\"\n\nnamespace moteus {\nnamespace tool {\n\nnamespace {\n\nconstexpr double kPi = 3.14159265358979323846;\n\nstruct Entry {\n  int phase = 0;\n  int encoder = 0;\n};\n\nstruct File {\n  std::vector<Entry> phase_up;\n  std::vector<Entry> phase_down;\n};\n\nFile ParseFile(const std::vector<std::string>& lines_in) {\n  std::deque<std::string> lines;\n  std::copy(lines_in.begin(), lines_in.end(), std::back_inserter(lines));\n  if (lines.front() != \"CAL start\") {\n    mjlib::base::system_error::throw_if(\n        true, \"Does not start with magic line: \" + lines.front());\n  }\n\n  lines.pop_front();\n\n  File result;\n\n  while (!lines.empty()) {\n    const auto line = lines.front();\n    lines.pop_front();\n\n    if (line == \"CAL done\") {\n      return result;\n    }\n\n    std::vector<std::string> fields;\n    boost::split(fields, line, boost::is_any_of(\" \"));\n\n    if (fields.size() != 3) {\n      mjlib::base::system_error::throw_if(\n          true, \"malformed line: \" + line);\n    }\n\n    const auto phase = std::stoi(fields[1]);\n    const auto encoder = std::stoi(fields[2]);\n    const auto entry = Entry{phase, encoder};\n\n    if (fields[0] == \"1\") {\n      result.phase_up.push_back(entry);\n    } else if (fields[0] == \"2\") {\n      result.phase_down.push_back(entry);\n    } else {\n      mjlib::base::system_error::throw_if(\n          true, \"unknown phase code: \" + line);\n    }\n  }\n\n  mjlib::base::system_error::throw_if(\n      true, \"Does not end with magic line\");\n  return {};\n}\n\nint WrapInt16(int value) {\n  if (value > 32767) {\n    return value - 65536;\n  } else if (value < -32768) {\n    return 65536 + value;\n  }\n  return value;\n}\n\ndouble WrapNegPiToPi(double value) {\n  if (value >= -kPi && value <= kPi) { return value; }\n  if (value > 0.0) {\n    return std::fmod(value + kPi, 2 * kPi) - kPi;\n  } else {\n    return std::fmod(value - kPi, 2 * kPi) + kPi;\n  }\n}\n\nEigen::VectorXd Unwrap(const Eigen::VectorXd& value) {\n  Eigen::VectorXd result(value.size());\n  for (int i = 0; i < value.size(); i++) {\n    if (i == 0) {\n      result(i) = value(i);\n    } else {\n      result(i) = (result(i - 1) + WrapNegPiToPi(value(i) - result(i - 1)));\n    }\n  }\n\n  return result;\n}\n\nEigen::VectorXd Linspace(double start, double end, size_t count) {\n  Eigen::VectorXd result(count);\n  for (size_t i = 0; i < count; i++) {\n    result(i) = (\n        (i + 1) == count ?\n        end :\n        i * (end - start) / (count - 1) + start);\n  }\n  return result;\n}\n\nEigen::VectorXd Range(double start, double end, size_t count) {\n  Eigen::VectorXd result(count);\n  for (size_t i = 0; i < count; i++) {\n    result(i) = (i * (end - start) / count + start);\n  }\n  return result;\n}\n\nEigen::VectorXd Interpolate(const Eigen::VectorXd& sample_points,\n                            const Eigen::VectorXd& x,\n                            const Eigen::VectorXd& y) {\n  BOOST_ASSERT(x.size() > 1 && x.size() == y.size());\n\n  int xindex = 0;\n\n  Eigen::VectorXd result(sample_points.size());\n  for (int i = 0; i < sample_points.size(); i++) {\n    const auto point = sample_points[i];\n    result(i) = [&]() {\n      if (point < x[xindex]) {\n        // Whoops?  This can only legimately happen at the very beginning.\n        return y[xindex];\n      }\n      while ((xindex + 2) < x.size() &&\n             point >= x[xindex + 1]) {\n        xindex++;\n      }\n\n      if (point > x[xindex + 1]) {\n        // We're past the end.\n        return y[xindex + 1];\n      }\n\n      // Linearly interpolate.\n      const double length = x[xindex + 1] - x[xindex];\n      if (length == 0.0) {\n        return y[xindex + 1];\n      }\n      double ratio = (point - x[xindex]) / length;\n      return (y[xindex + 1] - y[xindex]) * ratio + y[xindex];\n    }();\n  }\n\n  return result;\n}\n\nEigen::VectorXd WindowAverage(const Eigen::VectorXd& values, int window_size) {\n  Eigen::VectorXd result(values.size());\n  for (int i = 0; i < values.size(); i++) {\n    int start = std::max<int>(0, i - window_size / 2);\n    int end = std::min<int>(values.size(), i + window_size / 2);\n    Eigen::VectorXd errs(end - start);\n    for (int i = start; i < end; i++) {\n      errs[i - start] = WrapNegPiToPi(values[i] - values[start]);\n    }\n    result[i] = values[start] + errs.mean();\n  }\n\n  return result;\n}\n\n}\n\nCalibrationResult Calibrate(const std::vector<std::string>& lines) {\n  auto file = ParseFile(lines);\n\n  if (file.phase_up.empty() ||\n      file.phase_down.empty()) {\n    mjlib::base::system_error::throw_if(\n        true, \"one or more phases was empty\");\n  }\n\n  double total_delta = 0;\n  for (size_t i = 0; i < file.phase_up.size() - 1; i++) {\n    total_delta += WrapInt16(file.phase_up[i + 1].encoder -\n                             file.phase_up[i].encoder);\n  }\n\n  if (std::abs(std::abs(total_delta) - 65536) > 5000) {\n    mjlib::base::system_error::throw_if(\n        true, \"phase_up did not traverse appropriate encoder distance\");\n  }\n\n  CalibrationResult result;\n\n  // Figure out inversion.\n  if (total_delta < 0) {\n    result.invert = true;\n    for (auto& item : file.phase_up) { item.encoder = 65535 - item.encoder; }\n    for (auto& item : file.phase_down) { item.encoder = 65535 - item.encoder; }\n    total_delta *= -1;\n  }\n\n  // Next, figure out the number of poles.  We compare the total\n  // encoder delta to the total phase delta.\n  double total_phase = 0;\n  for (size_t i = 0; i < file.phase_up.size() - 1; i++) {\n    total_phase += WrapInt16(file.phase_up[i + 1].phase -\n                             file.phase_up[i].phase);\n  }\n\n  const double ratio = total_phase / total_delta;\n  const double remainder = std::abs(std::round(ratio) - ratio);\n\n  const double kMaxRemainderError = 0.1;\n  if (remainder > kMaxRemainderError) {\n    mjlib::base::system_error::throw_if(\n        true, fmt::format(\n            \"encoder not an integral multiple of phase, {} > {}\",\n            remainder, kMaxRemainderError));\n  }\n\n  result.total_phase = total_phase;\n  result.total_delta = total_delta;\n  result.ratio = ratio;\n\n  result.poles = static_cast<int>(std::round(ratio) * 2);\n\n  // Now we need to figure out the phase offset at select points.  We\n  // interpolate and average the phase up and phase down sections.\n  std::vector<Entry> phase_up_by_encoder = file.phase_up;\n  const auto encoder_sort = [](const auto& lhs, const auto& rhs) {\n    return lhs.encoder < rhs.encoder;\n  };\n  std::sort(phase_up_by_encoder.begin(), phase_up_by_encoder.end(),\n            encoder_sort);\n  std::vector<Entry> phase_down_by_encoder = file.phase_down;\n  std::sort(phase_down_by_encoder.begin(), phase_down_by_encoder.end(),\n            encoder_sort);\n\n  double offset = phase_down_by_encoder[0].phase - phase_up_by_encoder[0].phase;\n  if (std::abs(offset) > 32767) {\n    // We need to shift it so that they start from the same place.\n    auto change = static_cast<int>(-65536 * std::round(offset / 65536.0));\n    for (auto& item : phase_down_by_encoder) { item.phase += change; }\n  }\n\n  Eigen::VectorXd phase_up_encoder(phase_up_by_encoder.size());\n  for (size_t i = 0; i < phase_up_by_encoder.size(); i++) {\n    phase_up_encoder[i] = phase_up_by_encoder[i].encoder;\n  }\n\n  Eigen::VectorXd phase_up_phase(phase_up_by_encoder.size());\n  for (size_t i = 0; i < phase_up_by_encoder.size(); i++) {\n    phase_up_phase[i] =\n        2.0 * kPi / 65536.0 * phase_up_by_encoder[i].phase;\n  }\n  phase_up_phase = Unwrap(phase_up_phase);\n\n  Eigen::VectorXd phase_down_encoder(phase_down_by_encoder.size());\n  for (size_t i = 0; i < phase_down_by_encoder.size(); i++) {\n    phase_down_encoder[i] = phase_down_by_encoder[i].encoder;\n  }\n\n  Eigen::VectorXd phase_down_phase(phase_down_by_encoder.size());\n  for (size_t i = 0; i < phase_down_by_encoder.size(); i++) {\n    phase_down_phase[i] =\n        2.0 * kPi / 65536.0 * phase_down_by_encoder[i].phase;\n  }\n  phase_down_phase = Unwrap(phase_down_phase);\n\n  Eigen::VectorXd xpos = Linspace(0, 65535.0, 10000);\n\n  const Eigen::VectorXd pu_interp =\n      Interpolate(xpos, phase_up_encoder, phase_up_phase);\n  const Eigen::VectorXd pd_interp =\n      Interpolate(xpos, phase_down_encoder, phase_down_phase);\n  const Eigen::VectorXd avg_interp = 0.5 * (pu_interp + pd_interp);\n\n  const Eigen::VectorXd expected =\n      (2.0 * kPi / 65536) * (result.poles / 2) * xpos;\n\n  Eigen::VectorXd err(expected.size());\n  for (int i = 0; i < expected.size(); i++) {\n    err[i] = WrapNegPiToPi(avg_interp[i] - expected[i]);\n  }\n\n  // Make the error seem reasonable, so unwrap if we happen to span\n  // the pi boundary.\n  if ((err.maxCoeff() - err.minCoeff()) > 1.5 * kPi) {\n    for (int i = 0; i < err.size(); i++) {\n      err[i] = (err[i] > 0) ? err[i] : (err[i] + 2 * kPi);\n    }\n  }\n\n  auto avg_window = static_cast<int>(err.size() / result.poles);\n  const Eigen::VectorXd avg_err = WindowAverage(err, avg_window);\n\n  const Eigen::VectorXd offset_x = Range(0, 65536, 64);\n  const Eigen::VectorXd offsets = Interpolate(offset_x, xpos, avg_err);\n\n  for (int i = 0; i < offsets.size(); i++) {\n    result.offset.push_back(offsets[i]);\n  }\n\n  return result;\n}\n\n}\n}\n", "meta": {"hexsha": "9c7bd88145c8841c0c78929c68134ce445a37cf1", "size": 9799, "ext": "cc", "lang": "C++", "max_stars_repo_path": "moteus/tool/calibrate.cc", "max_stars_repo_name": "annhan/moteus", "max_stars_repo_head_hexsha": "03cafe4472da1fe018ed90e24a2b1f00667c688e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moteus/tool/calibrate.cc", "max_issues_repo_name": "annhan/moteus", "max_issues_repo_head_hexsha": "03cafe4472da1fe018ed90e24a2b1f00667c688e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moteus/tool/calibrate.cc", "max_forks_repo_name": "annhan/moteus", "max_forks_repo_head_hexsha": "03cafe4472da1fe018ed90e24a2b1f00667c688e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2507462687, "max_line_length": 80, "alphanum_fraction": 0.624145321, "num_tokens": 2730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.3593641588823761, "lm_q1q2_score": 0.22236750505249436}}
{"text": "//\n//  Copyright (c) 2000-2002\n//  Joerg Walter, Mathias Koch\n//\n//  Distributed under the Boost Software License, Version 1.0. (See\n//  accompanying file LICENSE_1_0.txt or copy at\n//  http://www.boost.org/LICENSE_1_0.txt)\n//\n//  The authors gratefully acknowledge the support of\n//  GeNeSys mbH & Co. KG in producing this work.\n//\n\n#ifndef _BOOST_UBLAS_MATRIX_EXPRESSION_\n#define _BOOST_UBLAS_MATRIX_EXPRESSION_\n\n#include <boost/numeric/ublas/vector_expression.hpp>\n\n// Expression templates based on ideas of Todd Veldhuizen and Geoffrey Furnish\n// Iterators based on ideas of Jeremy Siek\n//\n// Classes that model the Matrix Expression concept\n\nnamespace boost { namespace numeric { namespace ublas {\n\n    template<class E>\n    class matrix_reference:\n        public matrix_expression<matrix_reference<E> > {\n\n        typedef matrix_reference<E> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using matrix_expression<self_type>::operator ();\n#endif\n        typedef typename E::size_type size_type;\n        typedef typename E::difference_type difference_type;\n        typedef typename E::value_type value_type;\n        typedef typename E::const_reference const_reference;\n        typedef typename boost::mpl::if_<boost::is_const<E>,\n                                          typename E::const_reference,\n                                          typename E::reference>::type reference;\n        typedef E referred_type;\n        typedef const self_type const_closure_type;\n        typedef self_type closure_type;\n        typedef typename E::orientation_category orientation_category;\n        typedef typename E::storage_category storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        explicit matrix_reference (referred_type &e):\n              e_ (e) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size1 () const {\n            return e_.size1 ();\n        }\n        BOOST_UBLAS_INLINE\n        size_type size2 () const {\n            return e_.size2 ();\n        }\n\n    public:\n        // Expression accessors - const correct\n        BOOST_UBLAS_INLINE\n        const referred_type &expression () const {\n            return e_;\n        }\n        BOOST_UBLAS_INLINE\n        referred_type &expression () {\n            return e_;\n        }\n\n    public:\n        // Element access\n#ifndef BOOST_UBLAS_REFERENCE_CONST_MEMBER\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i, size_type j) const {\n            return expression () (i, j);\n        }\n        BOOST_UBLAS_INLINE\n        reference operator () (size_type i, size_type j) {\n            return expression () (i, j);\n        }\n#else\n        BOOST_UBLAS_INLINE\n        reference operator () (size_type i, size_type j) const {\n            return expression () (i, j);\n        }\n#endif\n\n        // Assignment\n        BOOST_UBLAS_INLINE\n        matrix_reference &operator = (const matrix_reference &m) {\n            expression ().operator = (m);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        matrix_reference &operator = (const matrix_expression<AE> &ae) {\n            expression ().operator = (ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        matrix_reference &assign (const matrix_expression<AE> &ae) {\n            expression ().assign (ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        matrix_reference &operator += (const matrix_expression<AE> &ae) {\n            expression ().operator += (ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        matrix_reference &plus_assign (const matrix_expression<AE> &ae) {\n            expression ().plus_assign (ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        matrix_reference &operator -= (const matrix_expression<AE> &ae) {\n            expression ().operator -= (ae);\n            return *this;\n        }\n        template<class AE>\n        BOOST_UBLAS_INLINE\n        matrix_reference &minus_assign (const matrix_expression<AE> &ae) {\n            expression ().minus_assign (ae);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        matrix_reference &operator *= (const AT &at) {\n            expression ().operator *= (at);\n            return *this;\n        }\n        template<class AT>\n        BOOST_UBLAS_INLINE\n        matrix_reference &operator /= (const AT &at) {\n            expression ().operator /= (at);\n            return *this;\n        }\n\n         // Swapping\n        BOOST_UBLAS_INLINE\n        void swap (matrix_reference &m) {\n            expression ().swap (m.expression ());\n        }\n\n        // Closure comparison\n        BOOST_UBLAS_INLINE\n        bool same_closure (const matrix_reference &mr) const {\n            return &(*this).e_ == &mr.e_;\n        }\n\n        // Iterator types\n        typedef typename E::const_iterator1 const_iterator1;\n        typedef typename boost::mpl::if_<boost::is_const<E>,\n                                          typename E::const_iterator1,\n                                          typename E::iterator1>::type iterator1;\n        typedef typename E::const_iterator2 const_iterator2;\n        typedef typename boost::mpl::if_<boost::is_const<E>,\n                                          typename E::const_iterator2,\n                                          typename E::iterator2>::type iterator2;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator1 find1 (int rank, size_type i, size_type j) const {\n            return expression ().find1 (rank, i, j);\n        }\n        BOOST_UBLAS_INLINE\n        iterator1 find1 (int rank, size_type i, size_type j) {\n            return expression ().find1 (rank, i, j);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 find2 (int rank, size_type i, size_type j) const {\n            return expression ().find2 (rank, i, j);\n        }\n        BOOST_UBLAS_INLINE\n        iterator2 find2 (int rank, size_type i, size_type j) {\n            return expression ().find2 (rank, i, j);\n        }\n\n        // Iterators are the iterators of the referenced expression.\n\n        BOOST_UBLAS_INLINE\n        const_iterator1 begin1 () const {\n            return expression ().begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cbegin1 () const {\n            return begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 end1 () const {\n            return expression ().end1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cend1 () const {\n            return end1 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        iterator1 begin1 () {\n            return expression ().begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        iterator1 end1 () {\n            return expression ().end1 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        const_iterator2 begin2 () const {\n            return expression ().begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cbegin2 () const {\n            return begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 end2 () const {\n            return expression ().end2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cend2 () const {\n            return end2 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        iterator2 begin2 () {\n            return expression ().begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        iterator2 end2 () {\n            return expression ().end2 ();\n        }\n\n        // Reverse iterators\n        typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1;\n        typedef reverse_iterator_base1<iterator1> reverse_iterator1;\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rbegin1 () const {\n            return const_reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crbegin1 () const {\n            return rbegin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rend1 () const {\n            return const_reverse_iterator1 (begin1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crend1 () const {\n            return rend1 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        reverse_iterator1 rbegin1 () {\n            return reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator1 rend1 () {\n            return reverse_iterator1 (begin1 ());\n        }\n\n        typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2;\n        typedef reverse_iterator_base2<iterator2> reverse_iterator2;\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rbegin2 () const {\n            return const_reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crbegin2 () const {\n            return rbegin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rend2 () const {\n            return const_reverse_iterator2 (begin2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crend2 () const {\n            return rend2 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        reverse_iterator2 rbegin2 () {\n            return reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        reverse_iterator2 rend2 () {\n            return reverse_iterator2 (begin2 ());\n        }\n\n    private:\n        referred_type &e_;\n    };\n\n\n    template<class E1, class E2, class F>\n    class vector_matrix_binary:\n        public matrix_expression<vector_matrix_binary<E1, E2, F> > {\n\n        typedef E1 expression1_type;\n        typedef E2 expression2_type;\n    public:\n        typedef typename E1::const_closure_type expression1_closure_type;\n        typedef typename E2::const_closure_type expression2_closure_type;\n    private:\n        typedef vector_matrix_binary<E1, E2, F> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using matrix_expression<self_type>::operator ();\n#endif\n        typedef F functor_type;\n        typedef typename promote_traits<typename E1::size_type, typename E2::size_type>::promote_type size_type;\n        typedef typename promote_traits<typename E1::difference_type, typename E2::difference_type>::promote_type difference_type;\n        typedef typename F::result_type value_type;\n        typedef value_type const_reference;\n        typedef const_reference reference;\n        typedef const self_type const_closure_type;\n        typedef const_closure_type closure_type;\n        typedef unknown_orientation_tag orientation_category;\n        typedef unknown_storage_tag storage_category;\n\n        // Construction and destruction \n        BOOST_UBLAS_INLINE\n        vector_matrix_binary (const expression1_type &e1, const expression2_type &e2): \n            e1_ (e1), e2_ (e2) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size1 () const {\n            return e1_.size ();\n        }\n        BOOST_UBLAS_INLINE\n        size_type size2 () const { \n            return e2_.size ();\n        }\n\n    public:\n        // Expression accessors\n        BOOST_UBLAS_INLINE\n        const expression1_closure_type &expression1 () const {\n            return e1_;\n        }\n        BOOST_UBLAS_INLINE\n        const expression2_closure_type &expression2 () const {\n            return e2_;\n        }\n\n    public:\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i, size_type j) const {\n            return functor_type::apply (e1_ (i), e2_ (j));\n        }\n\n        // Closure comparison\n        BOOST_UBLAS_INLINE\n        bool same_closure (const vector_matrix_binary &vmb) const {\n            return (*this).expression1 ().same_closure (vmb.expression1 ()) &&\n                   (*this).expression2 ().same_closure (vmb.expression2 ());\n        }\n\n        // Iterator types\n    private:\n        typedef typename E1::const_iterator const_subiterator1_type;\n        typedef typename E2::const_iterator const_subiterator2_type;\n        typedef const value_type *const_pointer;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef typename iterator_restrict_traits<typename const_subiterator1_type::iterator_category,\n                                                  typename const_subiterator2_type::iterator_category>::iterator_category iterator_category;\n        typedef indexed_const_iterator1<const_closure_type, iterator_category> const_iterator1;\n        typedef const_iterator1 iterator1;\n        typedef indexed_const_iterator2<const_closure_type, iterator_category> const_iterator2;\n        typedef const_iterator2 iterator2;\n#else\n        class const_iterator1;\n        typedef const_iterator1 iterator1;\n        class const_iterator2;\n        typedef const_iterator2 iterator2;\n#endif\n        typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1;\n        typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator1 find1 (int rank, size_type i, size_type j) const {\n            const_subiterator1_type it1 (e1_.find (i));\n            const_subiterator1_type it1_end (e1_.find (size1 ()));\n            const_subiterator2_type it2 (e2_.find (j));\n            const_subiterator2_type it2_end (e2_.find (size2 ()));\n            if (it2 == it2_end || (rank == 1 && (it2.index () != j || *it2 == value_type/*zero*/()))) {\n                it1 = it1_end;\n                it2 = it2_end;\n            }\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator1 (*this, it1.index (), it2.index ());\n#else\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            return const_iterator1 (*this, it1, it2, it2 != it2_end ? *it2 : value_type/*zero*/());\n#else\n            return const_iterator1 (*this, it1, it2);\n#endif\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 find2 (int rank, size_type i, size_type j) const {\n            const_subiterator2_type it2 (e2_.find (j));\n            const_subiterator2_type it2_end (e2_.find (size2 ()));\n            const_subiterator1_type it1 (e1_.find (i));\n            const_subiterator1_type it1_end (e1_.find (size1 ()));\n            if (it1 == it1_end || (rank == 1 && (it1.index () != i || *it1 == value_type/*zero*/()))) {\n                it2 = it2_end;\n                it1 = it1_end;\n            }\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator2 (*this, it1.index (), it2.index ());\n#else\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            return const_iterator2 (*this, it1, it2, it1 != it1_end ? *it1 : value_type/*zero*/());\n#else\n            return const_iterator2 (*this, it1, it2);\n#endif\n#endif\n        }\n\n        // Iterators enhance the iterators of the referenced expressions\n        // with the binary functor.\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator1:\n            public container_const_reference<vector_matrix_binary>,\n            public iterator_base_traits<typename iterator_restrict_traits<typename E1::const_iterator::iterator_category,\n                                                                          typename E2::const_iterator::iterator_category>::iterator_category>::template\n                iterator_base<const_iterator1, value_type>::type {\n        public:\n            typedef typename iterator_restrict_traits<typename E1::const_iterator::iterator_category,\n                                                      typename E2::const_iterator::iterator_category>::iterator_category iterator_category;\n            typedef typename vector_matrix_binary::difference_type difference_type;\n            typedef typename vector_matrix_binary::value_type value_type;\n            typedef typename vector_matrix_binary::const_reference reference;\n            typedef typename vector_matrix_binary::const_pointer pointer;\n\n            typedef const_iterator2 dual_iterator_type;\n            typedef const_reverse_iterator2 dual_reverse_iterator_type;\n\n            // Construction and destruction\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            BOOST_UBLAS_INLINE\n            const_iterator1 ():\n                container_const_reference<self_type> (), it1_ (), it2_ (), t2_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const self_type &vmb, const const_subiterator1_type &it1, const const_subiterator2_type &it2, value_type t2):\n                container_const_reference<self_type> (vmb), it1_ (it1), it2_ (it2), t2_ (t2) {}\n#else\n            BOOST_UBLAS_INLINE\n            const_iterator1 ():\n                container_const_reference<self_type> (), it1_ (), it2_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const self_type &vmb, const const_subiterator1_type &it1, const const_subiterator2_type &it2):\n                container_const_reference<self_type> (vmb), it1_ (it1), it2_ (it2) {}\n#endif\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator ++ () {\n                ++ it1_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -- () {\n                -- it1_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator += (difference_type n) {\n                it1_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -= (difference_type n) {\n                it1_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ - it.it1_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (*it1_, t2_);\n#else\n                return functor_type::apply (*it1_, *it2_);\n#endif\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 begin () const {\n                return (*this) ().find2 (1, index1 (), 0);\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 end () const {\n                return (*this) ().find2 (1, index1 (), (*this) ().size2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rbegin () const {\n                return const_reverse_iterator2 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rend () const {\n                return const_reverse_iterator2 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it1_.index ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type  index2 () const {\n                return it2_.index ();\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator = (const const_iterator1 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it1_ = it.it1_;\n                it2_ = it.it2_;\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                t2_ = it.t2_;\n#endif\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ == it.it1_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ < it.it1_;\n            }\n\n        private:\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            const_subiterator1_type it1_;\n            // Mutable due to assignment\n            /* const */ const_subiterator2_type it2_;\n            value_type t2_;\n#else\n            const_subiterator1_type it1_;\n            const_subiterator2_type it2_;\n#endif\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator1 begin1 () const {\n            return find1 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cbegin1 () const {\n            return begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 end1 () const {\n            return find1 (0, size1 (), 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cend1 () const {\n            return end1 ();\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator2:\n            public container_const_reference<vector_matrix_binary>,\n            public iterator_base_traits<typename iterator_restrict_traits<typename E1::const_iterator::iterator_category,\n                                                                          typename E2::const_iterator::iterator_category>::iterator_category>::template\n                iterator_base<const_iterator2, value_type>::type {\n        public:\n            typedef typename iterator_restrict_traits<typename E1::const_iterator::iterator_category, \n                                                      typename E2::const_iterator::iterator_category>::iterator_category iterator_category;\n            typedef typename vector_matrix_binary::difference_type difference_type;\n            typedef typename vector_matrix_binary::value_type value_type;\n            typedef typename vector_matrix_binary::const_reference reference;\n            typedef typename vector_matrix_binary::const_pointer pointer;\n\n            typedef const_iterator1 dual_iterator_type;\n            typedef const_reverse_iterator1 dual_reverse_iterator_type;\n\n            // Construction and destruction\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            BOOST_UBLAS_INLINE\n            const_iterator2 ():\n                container_const_reference<self_type> (), it1_ (), it2_ (), t1_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const self_type &vmb, const const_subiterator1_type &it1, const const_subiterator2_type &it2, value_type t1):\n                container_const_reference<self_type> (vmb), it1_ (it1), it2_ (it2), t1_ (t1) {}\n#else\n            BOOST_UBLAS_INLINE\n            const_iterator2 ():\n                container_const_reference<self_type> (), it1_ (), it2_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const self_type &vmb, const const_subiterator1_type &it1, const const_subiterator2_type &it2):\n                container_const_reference<self_type> (vmb), it1_ (it1), it2_ (it2) {}\n#endif\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator ++ () {\n                ++ it2_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -- () {\n                -- it2_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator += (difference_type n) {\n                it2_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -= (difference_type n) {\n                it2_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure(it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ - it.it2_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (t1_, *it2_);\n#else\n                return functor_type::apply (*it1_, *it2_);\n#endif\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 begin () const {\n                return (*this) ().find1 (1, 0, index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 end () const {\n                return (*this) ().find1 (1, (*this) ().size1 (), index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rbegin () const {\n                return const_reverse_iterator1 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rend () const {\n                return const_reverse_iterator1 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it1_.index ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type  index2 () const {\n                return it2_.index ();\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator = (const const_iterator2 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it1_ = it.it1_;\n                it2_ = it.it2_;\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                t1_ = it.t1_;\n#endif\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure( it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ == it.it2_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ < it.it2_;\n            }\n\n        private:\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            // Mutable due to assignment\n            /* const */ const_subiterator1_type it1_;\n            const_subiterator2_type it2_;\n            value_type t1_;\n#else\n            const_subiterator1_type it1_;\n            const_subiterator2_type it2_;\n#endif\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator2 begin2 () const {\n            return find2 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cbegin2 () const {\n            return begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 end2 () const {\n            return find2 (0, 0, size2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cend2 () const {\n            return end2 ();\n        }\n\n        // Reverse iterators\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rbegin1 () const {\n            return const_reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crbegin1 () const {\n            return rbegin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rend1 () const {\n            return const_reverse_iterator1 (begin1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crend1 () const {\n            return rend1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rbegin2 () const {\n            return const_reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crbegin2 () const {\n            return rbegin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rend2 () const {\n            return const_reverse_iterator2 (begin2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crend2 () const {\n            return rend2 ();\n        }\n\n    private:\n        expression1_closure_type e1_;\n        expression2_closure_type e2_;\n    };\n\n    template<class E1, class E2, class F>\n    struct vector_matrix_binary_traits {\n        typedef vector_matrix_binary<E1, E2, F> expression_type;\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n        typedef expression_type result_type; \n#else\n        // ISSUE matrix is arbitary temporary type\n        typedef matrix<typename F::value_type> result_type;\n#endif\n    };\n\n    // (outer_prod (v1, v2)) [i] [j] = v1 [i] * v2 [j]\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename vector_matrix_binary_traits<E1, E2, scalar_multiplies<typename E1::value_type, typename E2::value_type> >::result_type\n    outer_prod (const vector_expression<E1> &e1,\n                const vector_expression<E2> &e2) {\n        BOOST_STATIC_ASSERT (E1::complexity == 0 && E2::complexity == 0);\n        typedef typename vector_matrix_binary_traits<E1, E2, scalar_multiplies<typename E1::value_type, typename E2::value_type> >::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    template<class E, class F>\n    class matrix_unary1:\n        public matrix_expression<matrix_unary1<E, F> > {\n\n        typedef E expression_type;\n        typedef F functor_type;\n    public:\n        typedef typename E::const_closure_type expression_closure_type;\n    private:\n        typedef matrix_unary1<E, F> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using matrix_expression<self_type>::operator ();\n#endif\n        typedef typename E::size_type size_type;\n        typedef typename E::difference_type difference_type;\n        typedef typename F::result_type value_type;\n        typedef value_type const_reference;\n        typedef const_reference reference;\n        typedef const self_type const_closure_type;\n        typedef const_closure_type closure_type;\n        typedef typename E::orientation_category orientation_category;\n        typedef unknown_storage_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        explicit matrix_unary1 (const expression_type &e):\n            e_ (e) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size1 () const {\n            return e_.size1 ();\n        }\n        BOOST_UBLAS_INLINE\n        size_type size2 () const {\n            return e_.size2 ();\n        }\n\n    public:\n        // Expression accessors\n        BOOST_UBLAS_INLINE\n        const expression_closure_type &expression () const {\n            return e_;\n        }\n\n    public:\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i, size_type j) const {\n            return functor_type::apply (e_ (i, j));\n        }\n\n        // Closure comparison\n        BOOST_UBLAS_INLINE\n        bool same_closure (const matrix_unary1 &mu1) const {\n            return (*this).expression ().same_closure (mu1.expression ());\n        }\n\n        // Iterator types\n    private:\n        typedef typename E::const_iterator1 const_subiterator1_type;\n        typedef typename E::const_iterator2 const_subiterator2_type;\n        typedef const value_type *const_pointer;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_const_iterator1<const_closure_type, typename const_subiterator1_type::iterator_category> const_iterator1;\n        typedef const_iterator1 iterator1;\n        typedef indexed_const_iterator2<const_closure_type, typename const_subiterator2_type::iterator_category> const_iterator2;\n        typedef const_iterator2 iterator2;\n#else\n        class const_iterator1;\n        typedef const_iterator1 iterator1;\n        class const_iterator2;\n        typedef const_iterator2 iterator2;\n#endif\n        typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1;\n        typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator1 find1 (int rank, size_type i, size_type j) const {\n            const_subiterator1_type it1 (e_.find1 (rank, i, j));\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator1 (*this, it1.index1 (), it1.index2 ());\n#else\n            return const_iterator1 (*this, it1);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 find2 (int rank, size_type i, size_type j) const {\n            const_subiterator2_type it2 (e_.find2 (rank, i, j));\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator2 (*this, it2.index1 (), it2.index2 ());\n#else\n            return const_iterator2 (*this, it2);\n#endif\n        }\n\n        // Iterators enhance the iterators of the referenced expression\n        // with the unary functor.\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator1:\n            public container_const_reference<matrix_unary1>,\n            public iterator_base_traits<typename E::const_iterator1::iterator_category>::template\n                iterator_base<const_iterator1, value_type>::type {\n        public:\n            typedef typename E::const_iterator1::iterator_category iterator_category;\n            typedef typename matrix_unary1::difference_type difference_type;\n            typedef typename matrix_unary1::value_type value_type;\n            typedef typename matrix_unary1::const_reference reference;\n            typedef typename matrix_unary1::const_pointer pointer;\n\n            typedef const_iterator2 dual_iterator_type;\n            typedef const_reverse_iterator2 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator1 ():\n                container_const_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const self_type &mu, const const_subiterator1_type &it):\n                container_const_reference<self_type> (mu), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return functor_type::apply (*it_);\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 begin () const {\n                return (*this) ().find2 (1, index1 (), 0);\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 end () const {\n                return (*this) ().find2 (1, index1 (), (*this) ().size2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rbegin () const {\n                return const_reverse_iterator2 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rend () const {\n                return const_reverse_iterator2 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it_.index1 ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return it_.index2 ();\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator = (const const_iterator1 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_subiterator1_type it_;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator1 begin1 () const {\n            return find1 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cbegin1 () const {\n            return begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 end1 () const {\n            return find1 (0, size1 (), 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cend1 () const {\n            return end1 ();\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator2:\n            public container_const_reference<matrix_unary1>,\n            public iterator_base_traits<typename E::const_iterator2::iterator_category>::template\n                iterator_base<const_iterator2, value_type>::type {\n        public:\n            typedef typename E::const_iterator2::iterator_category iterator_category;\n            typedef typename matrix_unary1::difference_type difference_type;\n            typedef typename matrix_unary1::value_type value_type;\n            typedef typename matrix_unary1::const_reference reference;\n            typedef typename matrix_unary1::const_pointer pointer;\n\n            typedef const_iterator1 dual_iterator_type;\n            typedef const_reverse_iterator1 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator2 ():\n                container_const_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const self_type &mu, const const_subiterator2_type &it):\n                container_const_reference<self_type> (mu), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return functor_type::apply (*it_);\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 begin () const {\n                return (*this) ().find1 (1, 0, index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 end () const {\n                return (*this) ().find1 (1, (*this) ().size1 (), index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rbegin () const {\n                return const_reverse_iterator1 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rend () const {\n                return const_reverse_iterator1 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it_.index1 ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return it_.index2 ();\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator = (const const_iterator2 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_subiterator2_type it_;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator2 begin2 () const {\n            return find2 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cbegin2 () const {\n            return begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 end2 () const {\n            return find2 (0, 0, size2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cend2 () const {\n            return end2 ();\n        }\n\n        // Reverse iterators\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rbegin1 () const {\n            return const_reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crbegin1 () const {\n            return rbegin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rend1 () const {\n            return const_reverse_iterator1 (begin1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crend1 () const {\n            return rend1 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rbegin2 () const {\n            return const_reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crbegin2 () const {\n            return rbegin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rend2 () const {\n            return const_reverse_iterator2 (begin2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crend2 () const {\n            return rend2 ();\n        }\n\n    private:\n        expression_closure_type e_;\n    };\n\n    template<class E, class F>\n    struct matrix_unary1_traits {\n        typedef matrix_unary1<E, F> expression_type;\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n        typedef expression_type result_type; \n#else\n        typedef typename E::matrix_temporary_type result_type;\n#endif\n    };\n\n    // (- m) [i] [j] = - m [i] [j]\n    template<class E>\n    BOOST_UBLAS_INLINE\n    typename matrix_unary1_traits<E, scalar_negate<typename E::value_type> >::result_type\n    operator - (const matrix_expression<E> &e) {\n        typedef typename matrix_unary1_traits<E, scalar_negate<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n    }\n\n    // (conj m) [i] [j] = conj (m [i] [j])\n    template<class E> \n    BOOST_UBLAS_INLINE\n    typename matrix_unary1_traits<E, scalar_conj<typename E::value_type> >::result_type\n    conj (const matrix_expression<E> &e) {\n        typedef typename matrix_unary1_traits<E, scalar_conj<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n    }\n\n    // (real m) [i] [j] = real (m [i] [j])\n    template<class E> \n    BOOST_UBLAS_INLINE\n    typename matrix_unary1_traits<E, scalar_real<typename E::value_type> >::result_type\n    real (const matrix_expression<E> &e) {\n        typedef typename matrix_unary1_traits<E, scalar_real<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n    }\n\n    // (imag m) [i] [j] = imag (m [i] [j])\n    template<class E> \n    BOOST_UBLAS_INLINE\n    typename matrix_unary1_traits<E, scalar_imag<typename E::value_type> >::result_type\n    imag (const matrix_expression<E> &e) {\n        typedef typename matrix_unary1_traits<E, scalar_imag<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n    }\n\n    template<class E, class F>\n    class matrix_unary2:\n        public matrix_expression<matrix_unary2<E, F> > {\n\n        typedef typename boost::mpl::if_<boost::is_same<F, scalar_identity<typename E::value_type> >,\n                                          E,\n                                          const E>::type expression_type;\n        typedef F functor_type;\n    public:\n        typedef typename boost::mpl::if_<boost::is_const<expression_type>,\n                                          typename E::const_closure_type,\n                                          typename E::closure_type>::type expression_closure_type;\n    private:\n        typedef matrix_unary2<E, F> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using matrix_expression<self_type>::operator ();\n#endif\n        typedef typename E::size_type size_type;\n        typedef typename E::difference_type difference_type;\n        typedef typename F::result_type value_type;\n        typedef value_type const_reference;\n        typedef typename boost::mpl::if_<boost::is_same<F, scalar_identity<value_type> >,\n                                          typename E::reference,\n                                          value_type>::type reference;\n\n        typedef const self_type const_closure_type;\n        typedef self_type closure_type;\n        typedef typename boost::mpl::if_<boost::is_same<typename E::orientation_category,\n                                                         row_major_tag>,\n                                          column_major_tag,\n                typename boost::mpl::if_<boost::is_same<typename E::orientation_category,\n                                                         column_major_tag>,\n                                          row_major_tag,\n                                          typename E::orientation_category>::type>::type orientation_category;\n        typedef typename E::storage_category storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        // matrix_unary2 may be used as mutable expression -\n        // this is the only non const expression constructor\n        explicit matrix_unary2 (expression_type &e):\n            e_ (e) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size1 () const {\n            return e_.size2 ();\n        }\n        BOOST_UBLAS_INLINE\n        size_type size2 () const {\n            return e_.size1 ();\n        }\n\n    public:\n        // Expression accessors\n        BOOST_UBLAS_INLINE\n        const expression_closure_type &expression () const {\n            return e_;\n        }\n\n    public:\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i, size_type j) const {\n            return functor_type::apply (e_ (j, i));\n        }\n        BOOST_UBLAS_INLINE\n        reference operator () (size_type i, size_type j) {\n            BOOST_STATIC_ASSERT ((boost::is_same<functor_type, scalar_identity<value_type > >::value));\n            return e_ (j, i);\n        }\n\n        // Closure comparison\n        BOOST_UBLAS_INLINE\n        bool same_closure (const matrix_unary2 &mu2) const {\n            return (*this).expression ().same_closure (mu2.expression ());\n        }\n\n        // Iterator types\n    private:\n        typedef typename E::const_iterator1 const_subiterator2_type;\n        typedef typename E::const_iterator2 const_subiterator1_type;\n        typedef const value_type *const_pointer;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_const_iterator1<const_closure_type, typename const_subiterator1_type::iterator_category> const_iterator1;\n        typedef const_iterator1 iterator1;\n        typedef indexed_const_iterator2<const_closure_type, typename const_subiterator2_type::iterator_category> const_iterator2;\n        typedef const_iterator2 iterator2;\n#else\n        class const_iterator1;\n        typedef const_iterator1 iterator1;\n        class const_iterator2;\n        typedef const_iterator2 iterator2;\n#endif\n        typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1;\n        typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator1 find1 (int rank, size_type i, size_type j) const {\n            const_subiterator1_type it1 (e_.find2 (rank, j, i));\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator1 (*this, it1.index2 (), it1.index1 ());\n#else\n            return const_iterator1 (*this, it1);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 find2 (int rank, size_type i, size_type j) const {\n            const_subiterator2_type it2 (e_.find1 (rank, j, i));\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator2 (*this, it2.index2 (), it2.index1 ());\n#else\n            return const_iterator2 (*this, it2);\n#endif\n        }\n\n        // Iterators enhance the iterators of the referenced expression\n        // with the unary functor.\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator1:\n            public container_const_reference<matrix_unary2>,\n            public iterator_base_traits<typename E::const_iterator2::iterator_category>::template\n                iterator_base<const_iterator1, value_type>::type {\n        public:\n            typedef typename E::const_iterator2::iterator_category iterator_category;\n            typedef typename matrix_unary2::difference_type difference_type;\n            typedef typename matrix_unary2::value_type value_type;\n            typedef typename matrix_unary2::const_reference reference;\n            typedef typename matrix_unary2::const_pointer pointer;\n\n            typedef const_iterator2 dual_iterator_type;\n            typedef const_reverse_iterator2 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator1 ():\n                container_const_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const self_type &mu, const const_subiterator1_type &it):\n                container_const_reference<self_type> (mu), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return functor_type::apply (*it_);\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 begin () const {\n                return (*this) ().find2 (1, index1 (), 0);\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 end () const {\n                return (*this) ().find2 (1, index1 (), (*this) ().size2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rbegin () const {\n                return const_reverse_iterator2 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rend () const {\n                return const_reverse_iterator2 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it_.index2 ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return it_.index1 ();\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator = (const const_iterator1 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_subiterator1_type it_;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator1 begin1 () const {\n            return find1 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cbegin1 () const {\n            return begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 end1 () const {\n            return find1 (0, size1 (), 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cend1 () const {\n            return end1 ();\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator2:\n            public container_const_reference<matrix_unary2>,\n            public iterator_base_traits<typename E::const_iterator1::iterator_category>::template\n                iterator_base<const_iterator2, value_type>::type {\n        public:\n            typedef typename E::const_iterator1::iterator_category iterator_category;\n            typedef typename matrix_unary2::difference_type difference_type;\n            typedef typename matrix_unary2::value_type value_type;\n            typedef typename matrix_unary2::const_reference reference;\n            typedef typename matrix_unary2::const_pointer pointer;\n\n            typedef const_iterator1 dual_iterator_type;\n            typedef const_reverse_iterator1 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator2 ():\n                container_const_reference<self_type> (), it_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const self_type &mu, const const_subiterator2_type &it):\n                container_const_reference<self_type> (mu), it_ (it) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator ++ () {\n                ++ it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -- () {\n                -- it_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator += (difference_type n) {\n                it_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -= (difference_type n) {\n                it_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ - it.it_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return functor_type::apply (*it_);\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 begin () const {\n                return (*this) ().find1 (1, 0, index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 end () const {\n                return (*this) ().find1 (1, (*this) ().size1 (), index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rbegin () const {\n                return const_reverse_iterator1 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rend () const {\n                return const_reverse_iterator1 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it_.index2 ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return it_.index1 ();\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator = (const const_iterator2 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it_ = it.it_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ == it.it_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it_ < it.it_;\n            }\n\n        private:\n            const_subiterator2_type it_;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator2 begin2 () const {\n            return find2 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cbegin2 () const {\n            return begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 end2 () const {\n            return find2 (0, 0, size2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cend2 () const {\n            return end2 ();\n        }\n\n        // Reverse iterators\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rbegin1 () const {\n            return const_reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crbegin1 () const {\n            return rbegin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rend1 () const {\n            return const_reverse_iterator1 (begin1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crend1 () const {\n            return rend1 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rbegin2 () const {\n            return const_reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crbegin2 () const {\n            return rbegin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rend2 () const {\n            return const_reverse_iterator2 (begin2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crend2 () const {\n            return rend2 ();\n        }\n\n    private:\n        expression_closure_type e_;\n    };\n\n    template<class E, class F>\n    struct matrix_unary2_traits {\n        typedef matrix_unary2<E, F> expression_type;\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n        typedef expression_type result_type; \n#else\n        typedef typename E::matrix_temporary_type result_type;\n#endif\n    };\n\n    // (trans m) [i] [j] = m [j] [i]\n    template<class E>\n    BOOST_UBLAS_INLINE\n    typename matrix_unary2_traits<const E, scalar_identity<typename E::value_type> >::result_type\n    trans (const matrix_expression<E> &e) {\n        typedef typename matrix_unary2_traits<const E, scalar_identity<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n    }\n    template<class E>\n    BOOST_UBLAS_INLINE\n    typename matrix_unary2_traits<E, scalar_identity<typename E::value_type> >::result_type\n    trans (matrix_expression<E> &e) {\n        typedef typename matrix_unary2_traits<E, scalar_identity<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n    }\n\n    // (herm m) [i] [j] = conj (m [j] [i])\n    template<class E>\n    BOOST_UBLAS_INLINE\n    typename matrix_unary2_traits<E, scalar_conj<typename E::value_type> >::result_type\n    herm (const matrix_expression<E> &e) {\n        typedef typename matrix_unary2_traits<E, scalar_conj<typename E::value_type> >::expression_type expression_type;\n        return expression_type (e ());\n    }\n\n    template<class E1, class E2, class F>\n    class matrix_binary:\n        public matrix_expression<matrix_binary<E1, E2, F> > {\n\n        typedef E1 expression1_type;\n        typedef E2 expression2_type;\n        typedef F functor_type;\n    public:\n        typedef typename E1::const_closure_type expression1_closure_type;\n        typedef typename E2::const_closure_type expression2_closure_type;\n    private:\n        typedef matrix_binary<E1, E2, F> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using matrix_expression<self_type>::operator ();\n#endif\n        typedef typename promote_traits<typename E1::size_type, typename E2::size_type>::promote_type size_type;\n        typedef typename promote_traits<typename E1::difference_type, typename E2::difference_type>::promote_type difference_type;\n        typedef typename F::result_type value_type;\n        typedef value_type const_reference;\n        typedef const_reference reference;\n        typedef const self_type const_closure_type;\n        typedef const_closure_type closure_type;\n        typedef unknown_orientation_tag orientation_category;\n        typedef unknown_storage_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        matrix_binary (const E1 &e1, const E2 &e2): \n            e1_ (e1), e2_ (e2) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size1 () const { \n            return BOOST_UBLAS_SAME (e1_.size1 (), e2_.size1 ());\n        }\n        BOOST_UBLAS_INLINE\n        size_type size2 () const {\n            return BOOST_UBLAS_SAME (e1_.size2 (), e2_.size2 ());\n        }\n\n    public:\n        // Expression accessors\n        BOOST_UBLAS_INLINE\n        const expression1_closure_type &expression1 () const {\n            return e1_;\n        }\n        BOOST_UBLAS_INLINE\n        const expression2_closure_type &expression2 () const {\n            return e2_;\n        }\n\n    public:\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i, size_type j) const {\n            return functor_type::apply (e1_ (i, j), e2_ (i, j));\n        }\n\n        // Closure comparison\n        BOOST_UBLAS_INLINE\n        bool same_closure (const matrix_binary &mb) const {\n            return (*this).expression1 ().same_closure (mb.expression1 ()) &&\n                   (*this).expression2 ().same_closure (mb.expression2 ());\n        }\n\n        // Iterator types\n    private:\n        typedef typename E1::const_iterator1 const_iterator11_type;\n        typedef typename E1::const_iterator2 const_iterator12_type;\n        typedef typename E2::const_iterator1 const_iterator21_type;\n        typedef typename E2::const_iterator2 const_iterator22_type;\n        typedef const value_type *const_pointer;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef typename iterator_restrict_traits<typename const_iterator11_type::iterator_category,\n                                                  typename const_iterator21_type::iterator_category>::iterator_category iterator_category1;\n        typedef indexed_const_iterator1<const_closure_type, iterator_category1> const_iterator1;\n        typedef const_iterator1 iterator1;\n        typedef typename iterator_restrict_traits<typename const_iterator12_type::iterator_category,\n                                                  typename const_iterator22_type::iterator_category>::iterator_category iterator_category2;\n        typedef indexed_const_iterator2<const_closure_type, iterator_category2> const_iterator2;\n        typedef const_iterator2 iterator2;\n#else\n        class const_iterator1;\n        typedef const_iterator1 iterator1;\n        class const_iterator2;\n        typedef const_iterator2 iterator2;\n#endif\n        typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1;\n        typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator1 find1 (int rank, size_type i, size_type j) const {\n            const_iterator11_type it11 (e1_.find1 (rank, i, j));\n            const_iterator11_type it11_end (e1_.find1 (rank, size1 (), j));\n            const_iterator21_type it21 (e2_.find1 (rank, i, j));\n            const_iterator21_type it21_end (e2_.find1 (rank, size1 (), j));\n            BOOST_UBLAS_CHECK (rank == 0 || it11 == it11_end || it11.index2 () == j, internal_logic ())\n            BOOST_UBLAS_CHECK (rank == 0 || it21 == it21_end || it21.index2 () == j, internal_logic ())\n            i = (std::min) (it11 != it11_end ? it11.index1 () : size1 (),\n                          it21 != it21_end ? it21.index1 () : size1 ());\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator1 (*this, i, j);\n#else\n            return const_iterator1 (*this, i, j, it11, it11_end, it21, it21_end);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 find2 (int rank, size_type i, size_type j) const {\n            const_iterator12_type it12 (e1_.find2 (rank, i, j));\n            const_iterator12_type it12_end (e1_.find2 (rank, i, size2 ()));\n            const_iterator22_type it22 (e2_.find2 (rank, i, j));\n            const_iterator22_type it22_end (e2_.find2 (rank, i, size2 ()));\n            BOOST_UBLAS_CHECK (rank == 0 || it12 == it12_end || it12.index1 () == i, internal_logic ())\n            BOOST_UBLAS_CHECK (rank == 0 || it22 == it22_end || it22.index1 () == i, internal_logic ())\n            j = (std::min) (it12 != it12_end ? it12.index2 () : size2 (),\n                          it22 != it22_end ? it22.index2 () : size2 ());\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator2 (*this, i, j);\n#else\n            return const_iterator2 (*this, i, j, it12, it12_end, it22, it22_end);\n#endif\n        }\n\n        // Iterators enhance the iterators of the referenced expression\n        // with the binary functor.\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator1:\n            public container_const_reference<matrix_binary>,\n            public iterator_base_traits<typename iterator_restrict_traits<typename E1::const_iterator1::iterator_category,\n                                                                          typename E2::const_iterator1::iterator_category>::iterator_category>::template\n                iterator_base<const_iterator1, value_type>::type {\n        public:\n            typedef typename iterator_restrict_traits<typename E1::const_iterator1::iterator_category,\n                                                      typename E2::const_iterator1::iterator_category>::iterator_category iterator_category;\n            typedef typename matrix_binary::difference_type difference_type;\n            typedef typename matrix_binary::value_type value_type;\n            typedef typename matrix_binary::const_reference reference;\n            typedef typename matrix_binary::const_pointer pointer;\n\n            typedef const_iterator2 dual_iterator_type;\n            typedef const_reverse_iterator2 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator1 ():\n                container_const_reference<self_type> (), i_ (), j_ (), it1_ (), it1_end_ (), it2_ (), it2_end_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const self_type &mb, size_type i, size_type j,\n                             const const_iterator11_type &it1, const const_iterator11_type &it1_end,\n                             const const_iterator21_type &it2, const const_iterator21_type &it2_end):\n                container_const_reference<self_type> (mb), i_ (i), j_ (j), it1_ (it1), it1_end_ (it1_end), it2_ (it2), it2_end_ (it2_end) {}\n\n        private:\n            // Dense specializations\n            BOOST_UBLAS_INLINE\n            void increment (dense_random_access_iterator_tag) {\n                ++ i_; ++ it1_; ++ it2_;\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (dense_random_access_iterator_tag) {\n                -- i_; -- it1_; -- it2_;\n            }\n            BOOST_UBLAS_INLINE\n            void increment (dense_random_access_iterator_tag, difference_type n) {\n                 i_ += n; it1_ += n; it2_ += n;\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (dense_random_access_iterator_tag, difference_type n) {\n                i_ -= n; it1_ -= n; it2_ -= n;\n            }\n            BOOST_UBLAS_INLINE\n            value_type dereference (dense_random_access_iterator_tag) const {\n                return functor_type::apply (*it1_, *it2_);\n            }\n\n            // Packed specializations\n            BOOST_UBLAS_INLINE\n            void increment (packed_random_access_iterator_tag) {\n                if (it1_ != it1_end_)\n                    if (it1_.index1 () <= i_)\n                        ++ it1_;\n                if (it2_ != it2_end_)\n                    if (it2_.index1 () <= i_)\n                        ++ it2_;\n                ++ i_;\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (packed_random_access_iterator_tag) {\n                if (it1_ != it1_end_)\n                    if (i_ <= it1_.index1 ())\n                        -- it1_;\n                if (it2_ != it2_end_)\n                    if (i_ <= it2_.index1 ())\n                        -- it2_;\n                -- i_;\n            }\n            BOOST_UBLAS_INLINE\n            void increment (packed_random_access_iterator_tag, difference_type n) {\n                while (n > 0) {\n                    increment (packed_random_access_iterator_tag ());\n                    --n;\n                }\n                while (n < 0) {\n                    decrement (packed_random_access_iterator_tag ());\n                    ++n;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (packed_random_access_iterator_tag, difference_type n) {\n                while (n > 0) {\n                    decrement (packed_random_access_iterator_tag ());\n                    --n;\n                }\n                while (n < 0) {\n                    increment (packed_random_access_iterator_tag ());\n                    ++n;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            value_type dereference (packed_random_access_iterator_tag) const {\n                value_type t1 = value_type/*zero*/();\n                if (it1_ != it1_end_) {\n                    BOOST_UBLAS_CHECK (it1_.index2 () == j_, internal_logic ());\n                    if (it1_.index1 () == i_)\n                        t1 = *it1_;\n                }\n                value_type t2 = value_type/*zero*/();\n                if (it2_ != it2_end_) {\n                    BOOST_UBLAS_CHECK (it2_.index2 () == j_, internal_logic ());\n                    if (it2_.index1 () == i_)\n                        t2 = *it2_;\n                }\n                return functor_type::apply (t1, t2);\n            }\n\n            // Sparse specializations\n            BOOST_UBLAS_INLINE\n            void increment (sparse_bidirectional_iterator_tag) {\n                size_type index1 = (*this) ().size1 ();\n                if (it1_ != it1_end_) {\n                    if (it1_.index1 () <= i_)\n                        ++ it1_;\n                    if (it1_ != it1_end_)\n                        index1 = it1_.index1 ();\n                }\n                size_type index2 = (*this) ().size1 ();\n                if (it2_ != it2_end_)\n                    if (it2_.index1 () <= i_)\n                        ++ it2_;\n                    if (it2_ != it2_end_) {\n                        index2 = it2_.index1 ();\n                }\n                i_ = (std::min) (index1, index2);\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (sparse_bidirectional_iterator_tag) {\n                size_type index1 = (*this) ().size1 ();\n                if (it1_ != it1_end_) {\n                    if (i_ <= it1_.index1 ())\n                        -- it1_;\n                    if (it1_ != it1_end_)\n                        index1 = it1_.index1 ();\n                }\n                size_type index2 = (*this) ().size1 ();\n                if (it2_ != it2_end_) {\n                    if (i_ <= it2_.index1 ())\n                        -- it2_;\n                    if (it2_ != it2_end_)\n                        index2 = it2_.index1 ();\n                }\n                i_ = (std::max) (index1, index2);\n            }\n            BOOST_UBLAS_INLINE\n            void increment (sparse_bidirectional_iterator_tag, difference_type n) {\n                while (n > 0) {\n                    increment (sparse_bidirectional_iterator_tag ());\n                    --n;\n                }\n                while (n < 0) {\n                    decrement (sparse_bidirectional_iterator_tag ());\n                    ++n;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (sparse_bidirectional_iterator_tag, difference_type n) {\n                while (n > 0) {\n                    decrement (sparse_bidirectional_iterator_tag ());\n                    --n;\n                }\n                while (n < 0) {\n                    increment (sparse_bidirectional_iterator_tag ());\n                    ++n;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            value_type dereference (sparse_bidirectional_iterator_tag) const {\n                value_type t1 = value_type/*zero*/();\n                if (it1_ != it1_end_) {\n                    BOOST_UBLAS_CHECK (it1_.index2 () == j_, internal_logic ());\n                    if (it1_.index1 () == i_)\n                        t1 = *it1_;\n                }\n                value_type t2 = value_type/*zero*/();\n                if (it2_ != it2_end_) {\n                    BOOST_UBLAS_CHECK (it2_.index2 () == j_, internal_logic ());\n                    if (it2_.index1 () == i_)\n                        t2 = *it2_;\n                }\n                return functor_type::apply (t1, t2);\n            }\n\n        public:\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator ++ () {\n                increment (iterator_category ());\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -- () {\n                decrement (iterator_category ());\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator += (difference_type n) {\n                increment (iterator_category (), n);\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -= (difference_type n) {\n                decrement (iterator_category (), n);\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (index2 () == it.index2 (), external_logic ());\n                return index1 () - it.index1 ();\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return dereference (iterator_category ());\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 begin () const {\n                return (*this) ().find2 (1, index1 (), 0);\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 end () const {\n                return (*this) ().find2 (1, index1 (), (*this) ().size2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rbegin () const {\n                return const_reverse_iterator2 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rend () const {\n                return const_reverse_iterator2 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return i_;\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                // if (it1_ != it1_end_ && it2_ != it2_end_)\n                //    return BOOST_UBLAS_SAME (it1_.index2 (), it2_.index2 ());\n                // else\n                    return j_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator = (const const_iterator1 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                i_ = it.i_;\n                j_ = it.j_;\n                it1_ = it.it1_;\n                it1_end_ = it.it1_end_;\n                it2_ = it.it2_;\n                it2_end_ = it.it2_end_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (index2 () == it.index2 (), external_logic ());\n                return index1 () == it.index1 ();\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (index2 () == it.index2 (), external_logic ());\n                return index1 () < it.index1 ();\n            }\n\n        private:\n            size_type i_;\n            size_type j_;\n            const_iterator11_type it1_;\n            const_iterator11_type it1_end_;\n            const_iterator21_type it2_;\n            const_iterator21_type it2_end_;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator1 begin1 () const {\n            return find1 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cbegin1 () const {\n            return begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 end1 () const {\n            return find1 (0, size1 (), 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cend1 () const {\n            return end1 ();\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator2:\n            public container_const_reference<matrix_binary>,\n            public iterator_base_traits<typename iterator_restrict_traits<typename E1::const_iterator2::iterator_category,\n                                                                          typename E2::const_iterator2::iterator_category>::iterator_category>::template\n                iterator_base<const_iterator2, value_type>::type {\n        public:\n            typedef typename iterator_restrict_traits<typename E1::const_iterator2::iterator_category,\n                                                      typename E2::const_iterator2::iterator_category>::iterator_category iterator_category;\n            typedef typename matrix_binary::difference_type difference_type;\n            typedef typename matrix_binary::value_type value_type;\n            typedef typename matrix_binary::const_reference reference;\n            typedef typename matrix_binary::const_pointer pointer;\n\n            typedef const_iterator1 dual_iterator_type;\n            typedef const_reverse_iterator1 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator2 ():\n                container_const_reference<self_type> (), i_ (), j_ (), it1_ (), it1_end_ (), it2_ (), it2_end_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const self_type &mb, size_type i, size_type j,\n                             const const_iterator12_type &it1, const const_iterator12_type &it1_end,\n                             const const_iterator22_type &it2, const const_iterator22_type &it2_end):\n                container_const_reference<self_type> (mb), i_ (i), j_ (j), it1_ (it1), it1_end_ (it1_end), it2_ (it2), it2_end_ (it2_end) {}\n\n        private:\n            // Dense access specializations\n            BOOST_UBLAS_INLINE\n            void increment (dense_random_access_iterator_tag) {\n                ++ j_; ++ it1_; ++ it2_;\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (dense_random_access_iterator_tag) {\n                -- j_; -- it1_; -- it2_;\n            }\n            BOOST_UBLAS_INLINE\n            void increment (dense_random_access_iterator_tag, difference_type n) {\n                j_ += n; it1_ += n; it2_ += n;\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (dense_random_access_iterator_tag, difference_type n) {\n                j_ -= n; it1_ -= n; it2_ -= n;\n            }\n            BOOST_UBLAS_INLINE\n            value_type dereference (dense_random_access_iterator_tag) const {\n                return functor_type::apply (*it1_, *it2_);\n            }\n\n            // Packed specializations\n            BOOST_UBLAS_INLINE\n            void increment (packed_random_access_iterator_tag) {\n                if (it1_ != it1_end_)\n                    if (it1_.index2 () <= j_)\n                        ++ it1_;\n                if (it2_ != it2_end_)\n                    if (it2_.index2 () <= j_)\n                        ++ it2_;\n                ++ j_;\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (packed_random_access_iterator_tag) {\n                if (it1_ != it1_end_)\n                    if (j_ <= it1_.index2 ())\n                        -- it1_;\n                if (it2_ != it2_end_)\n                    if (j_ <= it2_.index2 ())\n                        -- it2_;\n                -- j_;\n            }\n            BOOST_UBLAS_INLINE\n            void increment (packed_random_access_iterator_tag, difference_type n) {\n                while (n > 0) {\n                    increment (packed_random_access_iterator_tag ());\n                    --n;\n                }\n                while (n < 0) {\n                    decrement (packed_random_access_iterator_tag ());\n                    ++n;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (packed_random_access_iterator_tag, difference_type n) {\n                while (n > 0) {\n                    decrement (packed_random_access_iterator_tag ());\n                    --n;\n                }\n                while (n < 0) {\n                    increment (packed_random_access_iterator_tag ());\n                    ++n;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            value_type dereference (packed_random_access_iterator_tag) const {\n                value_type t1 = value_type/*zero*/();\n                if (it1_ != it1_end_) {\n                    BOOST_UBLAS_CHECK (it1_.index1 () == i_, internal_logic ());\n                    if (it1_.index2 () == j_)\n                        t1 = *it1_;\n                }\n                value_type t2 = value_type/*zero*/();\n                if (it2_ != it2_end_) {\n                    BOOST_UBLAS_CHECK (it2_.index1 () == i_, internal_logic ());\n                    if (it2_.index2 () == j_)\n                        t2 = *it2_;\n                }\n                return functor_type::apply (t1, t2);\n            }\n\n            // Sparse specializations\n            BOOST_UBLAS_INLINE\n            void increment (sparse_bidirectional_iterator_tag) {\n                size_type index1 = (*this) ().size2 ();\n                if (it1_ != it1_end_) {\n                    if (it1_.index2 () <= j_)\n                        ++ it1_;\n                    if (it1_ != it1_end_)\n                        index1 = it1_.index2 ();\n                }\n                size_type index2 = (*this) ().size2 ();\n                if (it2_ != it2_end_) {\n                    if (it2_.index2 () <= j_)\n                        ++ it2_;\n                    if (it2_ != it2_end_)\n                        index2 = it2_.index2 ();\n                }\n                j_ = (std::min) (index1, index2);\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (sparse_bidirectional_iterator_tag) {\n                size_type index1 = (*this) ().size2 ();\n                if (it1_ != it1_end_) {\n                    if (j_ <= it1_.index2 ())\n                        -- it1_;\n                    if (it1_ != it1_end_)\n                        index1 = it1_.index2 ();\n                }\n                size_type index2 = (*this) ().size2 ();\n                if (it2_ != it2_end_) {\n                    if (j_ <= it2_.index2 ())\n                        -- it2_;\n                    if (it2_ != it2_end_)\n                        index2 = it2_.index2 ();\n                }\n                j_ = (std::max) (index1, index2);\n            }\n            BOOST_UBLAS_INLINE\n            void increment (sparse_bidirectional_iterator_tag, difference_type n) {\n                while (n > 0) {\n                    increment (sparse_bidirectional_iterator_tag ());\n                    --n;\n                }\n                while (n < 0) {\n                    decrement (sparse_bidirectional_iterator_tag ());\n                    ++n;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            void decrement (sparse_bidirectional_iterator_tag, difference_type n) {\n                while (n > 0) {\n                    decrement (sparse_bidirectional_iterator_tag ());\n                    --n;\n                }\n                while (n < 0) {\n                    increment (sparse_bidirectional_iterator_tag ());\n                    ++n;\n                }\n            }\n            BOOST_UBLAS_INLINE\n            value_type dereference (sparse_bidirectional_iterator_tag) const {\n                value_type t1 = value_type/*zero*/();\n                if (it1_ != it1_end_) {\n                    BOOST_UBLAS_CHECK (it1_.index1 () == i_, internal_logic ());\n                    if (it1_.index2 () == j_)\n                        t1 = *it1_;\n                }\n                value_type t2 = value_type/*zero*/();\n                if (it2_ != it2_end_) {\n                    BOOST_UBLAS_CHECK (it2_.index1 () == i_, internal_logic ());\n                    if (it2_.index2 () == j_)\n                        t2 = *it2_;\n                }\n                return functor_type::apply (t1, t2);\n            }\n\n        public:\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator ++ () {\n                increment (iterator_category ());\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -- () {\n                decrement (iterator_category ());\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator += (difference_type n) {\n                increment (iterator_category (), n);\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -= (difference_type n) {\n                decrement (iterator_category (), n);\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (index1 () == it.index1 (), external_logic ());\n                return index2 () - it.index2 ();\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return dereference (iterator_category ());\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 begin () const {\n                return (*this) ().find1 (1, 0, index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 end () const {\n                return (*this) ().find1 (1, (*this) ().size1 (), index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rbegin () const {\n                return const_reverse_iterator1 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rend () const {\n                return const_reverse_iterator1 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                // if (it1_ != it1_end_ && it2_ != it2_end_)\n                //    return BOOST_UBLAS_SAME (it1_.index1 (), it2_.index1 ());\n                // else\n                    return i_;\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return j_;\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator = (const const_iterator2 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                i_ = it.i_;\n                j_ = it.j_;\n                it1_ = it.it1_;\n                it1_end_ = it.it1_end_;\n                it2_ = it.it2_;\n                it2_end_ = it.it2_end_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (index1 () == it.index1 (), external_logic ());\n                return index2 () == it.index2 ();\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (index1 () == it.index1 (), external_logic ());\n                return index2 () < it.index2 ();\n            }\n\n        private:\n            size_type i_;\n            size_type j_;\n            const_iterator12_type it1_;\n            const_iterator12_type it1_end_;\n            const_iterator22_type it2_;\n            const_iterator22_type it2_end_;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator2 begin2 () const {\n            return find2 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cbegin2 () const {\n            return begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 end2 () const {\n            return find2 (0, 0, size2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cend2 () const {\n            return end2 ();\n        }\n\n        // Reverse iterators\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rbegin1 () const {\n            return const_reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crbegin1 () const {\n            return rbegin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rend1 () const {\n            return const_reverse_iterator1 (begin1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crend1 () const {\n            return rend1 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rbegin2 () const {\n            return const_reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crbegin2 () const {\n            return rbegin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rend2 () const {\n            return const_reverse_iterator2 (begin2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crend2 () const {\n            return rend2 ();\n        }\n\n    private:\n        expression1_closure_type e1_;\n        expression2_closure_type e2_;\n    };\n\n    template<class E1, class E2, class F>\n    struct matrix_binary_traits {\n        typedef matrix_binary<E1, E2, F> expression_type;\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n        typedef expression_type result_type; \n#else\n        typedef typename E1::matrix_temporary_type result_type;\n#endif\n    };\n\n    // (m1 + m2) [i] [j] = m1 [i] [j] + m2 [i] [j]\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_binary_traits<E1, E2, scalar_plus<typename E1::value_type,\n                                                      typename E2::value_type> >::result_type\n    operator + (const matrix_expression<E1> &e1,\n                const matrix_expression<E2> &e2) {\n        typedef typename matrix_binary_traits<E1, E2, scalar_plus<typename E1::value_type,\n                                                                  typename E2::value_type> >::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    // (m1 - m2) [i] [j] = m1 [i] [j] - m2 [i] [j]\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_binary_traits<E1, E2, scalar_minus<typename E1::value_type,\n                                                       typename E2::value_type> >::result_type\n    operator - (const matrix_expression<E1> &e1,\n                const matrix_expression<E2> &e2) {\n        typedef typename matrix_binary_traits<E1, E2, scalar_minus<typename E1::value_type,\n                                                                   typename E2::value_type> >::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    // (m1 * m2) [i] [j] = m1 [i] [j] * m2 [i] [j]\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_binary_traits<E1, E2, scalar_multiplies<typename E1::value_type,\n                                                            typename E2::value_type> >::result_type\n    element_prod (const matrix_expression<E1> &e1,\n                  const matrix_expression<E2> &e2) {\n        typedef typename matrix_binary_traits<E1, E2, scalar_multiplies<typename E1::value_type,\n                                                                        typename E2::value_type> >::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    // (m1 / m2) [i] [j] = m1 [i] [j] / m2 [i] [j]\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_binary_traits<E1, E2, scalar_divides<typename E1::value_type,\n                                                         typename E2::value_type> >::result_type\n    element_div (const matrix_expression<E1> &e1,\n                 const matrix_expression<E2> &e2) {\n        typedef typename matrix_binary_traits<E1, E2, scalar_divides<typename E1::value_type,\n                                                                     typename E2::value_type> >::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    template<class E1, class E2, class F>\n    class matrix_binary_scalar1:\n        public matrix_expression<matrix_binary_scalar1<E1, E2, F> > {\n\n        typedef E1 expression1_type;\n        typedef E2 expression2_type;\n        typedef F functor_type;\n        typedef const E1& expression1_closure_type;\n        typedef typename E2::const_closure_type expression2_closure_type;\n        typedef matrix_binary_scalar1<E1, E2, F> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using matrix_expression<self_type>::operator ();\n#endif\n        typedef typename E2::size_type size_type;\n        typedef typename E2::difference_type difference_type;\n        typedef typename F::result_type value_type;\n        typedef value_type const_reference;\n        typedef const_reference reference;\n        typedef const self_type const_closure_type;\n        typedef const_closure_type closure_type;\n        typedef typename E2::orientation_category orientation_category;\n        typedef unknown_storage_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        matrix_binary_scalar1 (const expression1_type &e1, const expression2_type &e2):\n            e1_ (e1), e2_ (e2) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size1 () const {\n            return e2_.size1 ();\n        }\n        BOOST_UBLAS_INLINE\n        size_type size2 () const {\n            return e2_.size2 ();\n        }\n\n    public:\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i, size_type j) const {\n            return functor_type::apply (expression1_type (e1_), e2_ (i, j));\n        }\n\n        // Closure comparison\n        BOOST_UBLAS_INLINE\n        bool same_closure (const matrix_binary_scalar1 &mbs1) const {\n            return &e1_ == &(mbs1.e1_) &&\n                   (*this).e2_.same_closure (mbs1.e2_);\n        }\n\n        // Iterator types\n    private:\n        typedef expression1_type const_subiterator1_type;\n        typedef typename E2::const_iterator1 const_iterator21_type;\n        typedef typename E2::const_iterator2 const_iterator22_type;\n        typedef const value_type *const_pointer;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_const_iterator1<const_closure_type, typename const_iterator21_type::iterator_category> const_iterator1;\n        typedef const_iterator1 iterator1;\n        typedef indexed_const_iterator2<const_closure_type, typename const_iterator22_type::iterator_category> const_iterator2;\n        typedef const_iterator2 iterator2;\n#else\n        class const_iterator1;\n        typedef const_iterator1 iterator1;\n        class const_iterator2;\n        typedef const_iterator2 iterator2;\n#endif\n        typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1;\n        typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator1 find1 (int rank, size_type i, size_type j) const {\n            const_iterator21_type it21 (e2_.find1 (rank, i, j));\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator1 (*this, it21.index1 (), it21.index2 ());\n#else\n            return const_iterator1 (*this, const_subiterator1_type (e1_), it21);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 find2 (int rank, size_type i, size_type j) const {\n            const_iterator22_type it22 (e2_.find2 (rank, i, j));\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator2 (*this, it22.index1 (), it22.index2 ());\n#else\n            return const_iterator2 (*this, const_subiterator1_type (e1_), it22);\n#endif\n        }\n\n        // Iterators enhance the iterators of the referenced expression\n        // with the binary functor.\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator1:\n            public container_const_reference<matrix_binary_scalar1>,\n            public iterator_base_traits<typename E2::const_iterator1::iterator_category>::template\n                iterator_base<const_iterator1, value_type>::type {\n        public:\n            typedef typename E2::const_iterator1::iterator_category iterator_category;\n            typedef typename matrix_binary_scalar1::difference_type difference_type;\n            typedef typename matrix_binary_scalar1::value_type value_type;\n            typedef typename matrix_binary_scalar1::const_reference reference;\n            typedef typename matrix_binary_scalar1::const_pointer pointer;\n\n            typedef const_iterator2 dual_iterator_type;\n            typedef const_reverse_iterator2 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator1 ():\n                container_const_reference<self_type> (), it1_ (), it2_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const self_type &mbs, const const_subiterator1_type &it1, const const_iterator21_type &it2):\n                container_const_reference<self_type> (mbs), it1_ (it1), it2_ (it2) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator ++ () {\n                ++ it2_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -- () {\n                -- it2_ ;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator += (difference_type n) {\n                it2_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -= (difference_type n) {\n                it2_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ - it.it2_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return functor_type::apply (it1_, *it2_);\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 begin () const {\n                return (*this) ().find2 (1, index1 (), 0);\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 end () const {\n                return (*this) ().find2 (1, index1 (), (*this) ().size2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rbegin () const {\n                return const_reverse_iterator2 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rend () const {\n                return const_reverse_iterator2 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it2_.index1 ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return it2_.index2 ();\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator = (const const_iterator1 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it1_ = it.it1_;\n                it2_ = it.it2_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ == it.it2_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ < it.it2_;\n            }\n\n        private:\n            const_subiterator1_type it1_;\n            const_iterator21_type it2_;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator1 begin1 () const {\n            return find1 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cbegin1 () const {\n            return begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 end1 () const {\n            return find1 (0, size1 (), 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cend1 () const {\n            return end1 ();\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator2:\n            public container_const_reference<matrix_binary_scalar1>,\n            public iterator_base_traits<typename E2::const_iterator2::iterator_category>::template\n                iterator_base<const_iterator2, value_type>::type {\n        public:\n            typedef typename E2::const_iterator2::iterator_category iterator_category;\n            typedef typename matrix_binary_scalar1::difference_type difference_type;\n            typedef typename matrix_binary_scalar1::value_type value_type;\n            typedef typename matrix_binary_scalar1::const_reference reference;\n            typedef typename matrix_binary_scalar1::const_pointer pointer;\n\n            typedef const_iterator1 dual_iterator_type;\n            typedef const_reverse_iterator1 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator2 ():\n                container_const_reference<self_type> (), it1_ (), it2_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const self_type &mbs, const const_subiterator1_type &it1, const const_iterator22_type &it2):\n                container_const_reference<self_type> (mbs), it1_ (it1), it2_ (it2) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator ++ () {\n                ++ it2_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -- () {\n                -- it2_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator += (difference_type n) {\n                it2_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -= (difference_type n) {\n                it2_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ - it.it2_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return functor_type::apply (it1_, *it2_);\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 begin () const {\n                return (*this) ().find1 (1, 0, index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 end () const {\n                return (*this) ().find1 (1, (*this) ().size1 (), index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rbegin () const {\n                return const_reverse_iterator1 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rend () const {\n                return const_reverse_iterator1 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it2_.index1 ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return it2_.index2 ();\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator = (const const_iterator2 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it1_ = it.it1_;\n                it2_ = it.it2_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ == it.it2_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ < it.it2_;\n            }\n\n        private:\n            const_subiterator1_type it1_;\n            const_iterator22_type it2_;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator2 begin2 () const {\n            return find2 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cbegin2 () const {\n            return begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 end2 () const {\n            return find2 (0, 0, size2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cend2 () const {\n            return end2 ();\n        }\n\n        // Reverse iterators\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rbegin1 () const {\n            return const_reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crbegin1 () const {\n            return rbegin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rend1 () const {\n            return const_reverse_iterator1 (begin1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crend1 () const {\n            return rend1 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rbegin2 () const {\n            return const_reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crbegin2 () const {\n            return rbegin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rend2 () const {\n            return const_reverse_iterator2 (begin2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crend2 () const {\n            return rend2 ();\n        }\n\n    private:\n        expression1_closure_type e1_;\n        expression2_closure_type e2_;\n    };\n\n    template<class E1, class E2, class F>\n    struct matrix_binary_scalar1_traits {\n        typedef matrix_binary_scalar1<E1, E2, F> expression_type;   // allow E1 to be builtin type\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n        typedef expression_type result_type;\n#else\n        typedef typename E2::matrix_temporary_type result_type;\n#endif\n    };\n\n    // (t * m) [i] [j] = t * m [i] [j]\n    template<class T1, class E2>\n    BOOST_UBLAS_INLINE\n    typename enable_if< is_convertible<T1, typename E2::value_type >,\n    typename matrix_binary_scalar1_traits<const T1, E2, scalar_multiplies<T1, typename E2::value_type> >::result_type\n    >::type\n    operator * (const T1 &e1,\n                const matrix_expression<E2> &e2) {\n        typedef typename matrix_binary_scalar1_traits<const T1, E2, scalar_multiplies<T1, typename E2::value_type> >::expression_type expression_type;\n        return expression_type (e1, e2 ());\n    }\n\n\n    template<class E1, class E2, class F>\n    class matrix_binary_scalar2:\n        public matrix_expression<matrix_binary_scalar2<E1, E2, F> > {\n\n        typedef E1 expression1_type;\n        typedef E2 expression2_type;\n        typedef F functor_type;\n    public:\n        typedef typename E1::const_closure_type expression1_closure_type;\n        typedef const E2& expression2_closure_type;\n    private:\n        typedef matrix_binary_scalar2<E1, E2, F> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using matrix_expression<self_type>::operator ();\n#endif\n        typedef typename E1::size_type size_type;\n        typedef typename E1::difference_type difference_type;\n        typedef typename F::result_type value_type;\n        typedef value_type const_reference;\n        typedef const_reference reference;\n\n        typedef const self_type const_closure_type;\n        typedef const_closure_type closure_type;\n        typedef typename E1::orientation_category orientation_category;\n        typedef unknown_storage_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        matrix_binary_scalar2 (const expression1_type &e1, const expression2_type &e2): \n            e1_ (e1), e2_ (e2) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size1 () const {\n            return e1_.size1 ();\n        }\n        BOOST_UBLAS_INLINE\n        size_type size2 () const {\n            return e1_.size2 ();\n        }\n\n    public:\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i, size_type j) const {\n            return functor_type::apply (e1_ (i, j), expression2_type (e2_));\n        }\n\n        // Closure comparison\n        BOOST_UBLAS_INLINE\n        bool same_closure (const matrix_binary_scalar2 &mbs2) const {\n            return (*this).e1_.same_closure (mbs2.e1_) &&\n                   &e2_ == &(mbs2.e2_);\n        }\n\n        // Iterator types\n    private:\n        typedef typename E1::const_iterator1 const_iterator11_type;\n        typedef typename E1::const_iterator2 const_iterator12_type;\n        typedef expression2_type const_subiterator2_type;\n        typedef const value_type *const_pointer;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_const_iterator1<const_closure_type, typename const_iterator11_type::iterator_category> const_iterator1;\n        typedef const_iterator1 iterator1;\n        typedef indexed_const_iterator2<const_closure_type, typename const_iterator12_type::iterator_category> const_iterator2;\n        typedef const_iterator2 iterator2;\n#else\n        class const_iterator1;\n        typedef const_iterator1 iterator1;\n        class const_iterator2;\n        typedef const_iterator2 iterator2;\n#endif\n        typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1;\n        typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator1 find1 (int rank, size_type i, size_type j) const {\n            const_iterator11_type it11 (e1_.find1 (rank, i, j));\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator1 (*this, it11.index1 (), it11.index2 ());\n#else\n            return const_iterator1 (*this, it11, const_subiterator2_type (e2_));\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 find2 (int rank, size_type i, size_type j) const {\n            const_iterator12_type it12 (e1_.find2 (rank, i, j));\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator2 (*this, it12.index1 (), it12.index2 ());\n#else\n            return const_iterator2 (*this, it12, const_subiterator2_type (e2_));\n#endif\n        }\n\n        // Iterators enhance the iterators of the referenced expression\n        // with the binary functor.\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator1:\n            public container_const_reference<matrix_binary_scalar2>,\n            public iterator_base_traits<typename E1::const_iterator1::iterator_category>::template\n                iterator_base<const_iterator1, value_type>::type {\n        public:\n            typedef typename E1::const_iterator1::iterator_category iterator_category;\n            typedef typename matrix_binary_scalar2::difference_type difference_type;\n            typedef typename matrix_binary_scalar2::value_type value_type;\n            typedef typename matrix_binary_scalar2::const_reference reference;\n            typedef typename matrix_binary_scalar2::const_pointer pointer;\n\n            typedef const_iterator2 dual_iterator_type;\n            typedef const_reverse_iterator2 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator1 ():\n                container_const_reference<self_type> (), it1_ (), it2_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const self_type &mbs, const const_iterator11_type &it1, const const_subiterator2_type &it2):\n                container_const_reference<self_type> (mbs), it1_ (it1), it2_ (it2) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator ++ () {\n                ++ it1_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -- () {\n                -- it1_ ;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator += (difference_type n) {\n                it1_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -= (difference_type n) {\n                it1_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ - it.it1_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return functor_type::apply (*it1_, it2_);\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 begin () const {\n                return (*this) ().find2 (1, index1 (), 0);\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 end () const {\n                return (*this) ().find2 (1, index1 (), (*this) ().size2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rbegin () const {\n                return const_reverse_iterator2 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rend () const {\n                return const_reverse_iterator2 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it1_.index1 ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return it1_.index2 ();\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator = (const const_iterator1 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it1_ = it.it1_;\n                it2_ = it.it2_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ == it.it1_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ < it.it1_;\n            }\n\n        private:\n            const_iterator11_type it1_;\n            const_subiterator2_type it2_;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator1 begin1 () const {\n            return find1 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cbegin1 () const {\n            return begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 end1 () const {\n            return find1 (0, size1 (), 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cend1 () const {\n            return end1 ();\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator2:\n            public container_const_reference<matrix_binary_scalar2>,\n            public iterator_base_traits<typename E1::const_iterator2::iterator_category>::template\n                iterator_base<const_iterator2, value_type>::type {\n        public:\n            typedef typename E1::const_iterator2::iterator_category iterator_category;\n            typedef typename matrix_binary_scalar2::difference_type difference_type;\n            typedef typename matrix_binary_scalar2::value_type value_type;\n            typedef typename matrix_binary_scalar2::const_reference reference;\n            typedef typename matrix_binary_scalar2::const_pointer pointer;\n\n            typedef const_iterator1 dual_iterator_type;\n            typedef const_reverse_iterator1 dual_reverse_iterator_type;\n\n            // Construction and destruction\n            BOOST_UBLAS_INLINE\n            const_iterator2 ():\n                container_const_reference<self_type> (), it1_ (), it2_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const self_type &mbs, const const_iterator12_type &it1, const const_subiterator2_type &it2):\n                container_const_reference<self_type> (mbs), it1_ (it1), it2_ (it2) {}\n\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator ++ () {\n                ++ it1_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -- () {\n                -- it1_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator += (difference_type n) {\n                it1_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -= (difference_type n) {\n                it1_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ - it.it1_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return functor_type::apply (*it1_, it2_);\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 begin () const {\n                return (*this) ().find1 (1, 0, index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 end () const {\n                return (*this) ().find1 (1, (*this) ().size1 (), index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rbegin () const {\n                return const_reverse_iterator1 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rend () const {\n                return const_reverse_iterator1 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it1_.index1 ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return it1_.index2 ();\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator = (const const_iterator2 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it1_ = it.it1_;\n                it2_ = it.it2_;\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ == it.it1_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                // FIXME we shouldn't compare floats\n                // BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ < it.it1_;\n            }\n\n        private:\n            const_iterator12_type it1_;\n            const_subiterator2_type it2_;\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator2 begin2 () const {\n            return find2 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cbegin2 () const {\n            return begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 end2 () const {\n            return find2 (0, 0, size2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cend2 () const {\n            return end2 ();\n        }\n\n        // Reverse iterators\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rbegin1 () const {\n            return const_reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crbegin1 () const {\n            return rbegin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rend1 () const {\n            return const_reverse_iterator1 (begin1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crend1 () const {\n            return rend1 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rbegin2 () const {\n            return const_reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crbegin2 () const {\n            return rbegin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rend2 () const {\n            return const_reverse_iterator2 (begin2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crend2 () const {\n            return rend2 ();\n        }\n\n    private:\n        expression1_closure_type e1_;\n        expression2_closure_type e2_;\n    };\n\n    template<class E1, class E2, class F>\n    struct matrix_binary_scalar2_traits {\n        typedef matrix_binary_scalar2<E1, E2, F> expression_type;   // allow E2 to be builtin type\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n        typedef expression_type result_type; \n#else\n        typedef typename E1::matrix_temporary_type result_type;\n#endif\n    };\n\n    // (m * t) [i] [j] = m [i] [j] * t\n    template<class E1, class T2>\n    BOOST_UBLAS_INLINE\n    typename enable_if< is_convertible<T2, typename E1::value_type>,\n    typename matrix_binary_scalar2_traits<E1, const T2, scalar_multiplies<typename E1::value_type, T2> >::result_type\n    >::type\n    operator * (const matrix_expression<E1> &e1,\n                const T2 &e2) {\n        typedef typename matrix_binary_scalar2_traits<E1, const T2, scalar_multiplies<typename E1::value_type, T2> >::expression_type expression_type;\n        return expression_type (e1 (), e2);\n    }\n\n    // (m / t) [i] [j] = m [i] [j] / t\n    template<class E1, class T2>\n    BOOST_UBLAS_INLINE\n    typename enable_if< is_convertible<T2, typename E1::value_type>,\n    typename matrix_binary_scalar2_traits<E1, const T2, scalar_divides<typename E1::value_type, T2> >::result_type\n    >::type\n    operator / (const matrix_expression<E1> &e1,\n                const T2 &e2) {\n        typedef typename matrix_binary_scalar2_traits<E1, const T2, scalar_divides<typename E1::value_type, T2> >::expression_type expression_type;\n        return expression_type (e1 (), e2);\n    }\n\n\n    template<class E1, class E2, class F>\n    class matrix_vector_binary1:\n        public vector_expression<matrix_vector_binary1<E1, E2, F> > {\n\n    public:\n        typedef E1 expression1_type;\n        typedef E2 expression2_type;\n    private:\n        typedef F functor_type;\n    public:\n        typedef typename E1::const_closure_type expression1_closure_type;\n        typedef typename E2::const_closure_type expression2_closure_type;\n    private:\n        typedef matrix_vector_binary1<E1, E2, F> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using vector_expression<self_type>::operator ();\n#endif\n        static const unsigned complexity = 1;\n        typedef typename promote_traits<typename E1::size_type, typename E2::size_type>::promote_type size_type;\n        typedef typename promote_traits<typename E1::difference_type, typename E2::difference_type>::promote_type difference_type;\n        typedef typename F::result_type value_type;\n        typedef value_type const_reference;\n        typedef const_reference reference;\n        typedef const self_type const_closure_type;\n        typedef const_closure_type closure_type;\n        typedef unknown_storage_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        matrix_vector_binary1 (const expression1_type &e1, const expression2_type &e2):\n            e1_ (e1), e2_ (e2) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const {\n            return e1_.size1 ();\n        }\n\n    public:\n        // Expression accessors\n        BOOST_UBLAS_INLINE\n        const expression1_closure_type &expression1 () const {\n            return e1_;\n        }\n        BOOST_UBLAS_INLINE\n        const expression2_closure_type &expression2 () const {\n            return e2_;\n        }\n\n    public:\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i) const {\n            return functor_type::apply (e1_, e2_, i);\n        }\n\n        // Closure comparison\n        BOOST_UBLAS_INLINE\n        bool same_closure (const matrix_vector_binary1 &mvb1) const {\n            return (*this).expression1 ().same_closure (mvb1.expression1 ()) &&\n                   (*this).expression2 ().same_closure (mvb1.expression2 ());\n        }\n\n        // Iterator types\n    private:\n        typedef typename E1::const_iterator1 const_subiterator1_type;\n        typedef typename E2::const_iterator const_subiterator2_type;\n        typedef const value_type *const_pointer;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_const_iterator<const_closure_type, typename const_subiterator1_type::iterator_category> const_iterator;\n        typedef const_iterator iterator;\n#else\n        class const_iterator;\n        typedef const_iterator iterator;\n#endif\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find (size_type i) const {\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            const_subiterator1_type it1 (e1_.find1 (0, i, 0));\n            return const_iterator (*this, it1.index1 ());\n#else\n            return const_iterator (*this, e1_.find1 (0, i, 0));\n#endif\n        }\n\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator:\n            public container_const_reference<matrix_vector_binary1>,\n            public iterator_base_traits<typename iterator_restrict_traits<typename E1::const_iterator1::iterator_category,\n                                                                          typename E2::const_iterator::iterator_category>::iterator_category>::template\n                iterator_base<const_iterator, value_type>::type {\n        public:\n            typedef typename iterator_restrict_traits<typename E1::const_iterator1::iterator_category, \n                                                      typename E2::const_iterator::iterator_category>::iterator_category iterator_category;\n            typedef typename matrix_vector_binary1::difference_type difference_type;\n            typedef typename matrix_vector_binary1::value_type value_type;\n            typedef typename matrix_vector_binary1::const_reference reference;\n            typedef typename matrix_vector_binary1::const_pointer pointer;\n\n            // Construction and destruction\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<self_type> (), it1_ (), e2_begin_ (), e2_end_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const self_type &mvb, const const_subiterator1_type &it1):\n                container_const_reference<self_type> (mvb), it1_ (it1), e2_begin_ (mvb.expression2 ().begin ()), e2_end_ (mvb.expression2 ().end ()) {}\n#else\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<self_type> (), it1_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const self_type &mvb, const const_subiterator1_type &it1):\n                container_const_reference<self_type> (mvb), it1_ (it1) {}\n#endif\n\n        private:\n            // Dense random access specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (dense_random_access_iterator_tag) const {\n                const self_type &mvb = (*this) ();\n#ifdef BOOST_UBLAS_USE_INDEXING\n                return mvb (index ());\n#elif BOOST_UBLAS_USE_ITERATING\n                difference_type size = BOOST_UBLAS_SAME (mvb.expression1 ().size2 (), mvb.expression2 ().size ());\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (size, it1_.begin (), e2_begin_);\n#else\n                return functor_type::apply (size, it1_.begin (), mvb.expression2 ().begin ());\n#endif\n#else\n                difference_type size = BOOST_UBLAS_SAME (mvb.expression1 ().size2 (), mvb.expression2 ().size ());\n                if (size >= BOOST_UBLAS_ITERATOR_THRESHOLD)\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                    return functor_type::apply (size, it1_.begin (), e2_begin_);\n#else\n                    return functor_type::apply (size, it1_.begin (), mvb.expression2 ().begin ());\n#endif\n                else\n                    return mvb (index ());\n#endif\n            }\n\n            // Packed bidirectional specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (packed_random_access_iterator_tag) const {\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (it1_.begin (), it1_.end (), e2_begin_, e2_end_);\n#else\n                const self_type &mvb = (*this) ();\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n                return functor_type::apply (it1_.begin (), it1_.end (),\n                                        mvb.expression2 ().begin (), mvb.expression2 ().end ());\n#else\n                return functor_type::apply (boost::numeric::ublas::begin (it1_, iterator1_tag ()),\n                                        boost::numeric::ublas::end (it1_, iterator1_tag ()),\n                                        mvb.expression2 ().begin (), mvb.expression2 ().end ());\n#endif\n#endif\n            }\n\n            // Sparse bidirectional specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (sparse_bidirectional_iterator_tag) const {\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (it1_.begin (), it1_.end (), e2_begin_, e2_end_, sparse_bidirectional_iterator_tag ());\n#else\n                const self_type &mvb = (*this) ();\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n                return functor_type::apply (it1_.begin (), it1_.end (),\n                                        mvb.expression2 ().begin (), mvb.expression2 ().end (), sparse_bidirectional_iterator_tag ());\n#else\n                return functor_type::apply (boost::numeric::ublas::begin (it1_, iterator1_tag ()),\n                                        boost::numeric::ublas::end (it1_, iterator1_tag ()),\n                                        mvb.expression2 ().begin (), mvb.expression2 ().end (), sparse_bidirectional_iterator_tag ());\n#endif\n#endif\n            }\n\n        public:\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                ++ it1_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                -- it1_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator += (difference_type n) {\n                it1_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -= (difference_type n) {\n                it1_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it1_ - it.it1_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return dereference (iterator_category ());\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                return it1_.index1 ();\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it1_ = it.it1_;\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                e2_begin_ = it.e2_begin_;\n                e2_end_ = it.e2_end_;\n#endif\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it1_ == it.it1_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it1_ < it.it1_;\n            }\n\n        private:\n            const_subiterator1_type it1_;\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            // Mutable due to assignment\n            /* const */ const_subiterator2_type e2_begin_;\n            /* const */ const_subiterator2_type e2_end_;\n#endif\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return find (0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator cbegin () const {\n            return begin ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return find (size ()); \n        }\n        BOOST_UBLAS_INLINE\n        const_iterator cend () const {\n            return end ();\n        }\n\n        // Reverse iterator\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator crbegin () const {\n            return rbegin ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator crend () const {\n            return rend ();\n        }\n\n    private:\n        expression1_closure_type e1_;\n        expression2_closure_type e2_;\n    };\n\n    template<class T1, class E1, class T2, class E2>\n    struct matrix_vector_binary1_traits {\n        typedef unknown_storage_tag storage_category;\n        typedef row_major_tag orientation_category;\n        typedef typename promote_traits<T1, T2>::promote_type promote_type;\n        typedef matrix_vector_binary1<E1, E2, matrix_vector_prod1<E1, E2, promote_type> > expression_type;\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n        typedef expression_type result_type;\n#else\n        typedef typename E1::vector_temporary_type result_type;\n#endif\n    };\n\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_vector_binary1_traits<typename E1::value_type, E1,\n                                          typename E2::value_type, E2>::result_type\n    prod (const matrix_expression<E1> &e1,\n          const vector_expression<E2> &e2,\n          unknown_storage_tag,\n          row_major_tag) {\n        typedef typename matrix_vector_binary1_traits<typename E1::value_type, E1,\n                                                      typename E2::value_type, E2>::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    // Dispatcher\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_vector_binary1_traits<typename E1::value_type, E1,\n                                          typename E2::value_type, E2>::result_type\n    prod (const matrix_expression<E1> &e1,\n          const vector_expression<E2> &e2) {\n        BOOST_STATIC_ASSERT (E2::complexity == 0);\n        typedef typename matrix_vector_binary1_traits<typename E1::value_type, E1,\n                                                      typename E2::value_type, E2>::storage_category storage_category;\n        typedef typename matrix_vector_binary1_traits<typename E1::value_type, E1,\n                                                      typename E2::value_type, E2>::orientation_category orientation_category;\n        return prod (e1, e2, storage_category (), orientation_category ());\n    }\n\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_vector_binary1_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                          typename type_traits<typename E2::value_type>::precision_type, E2>::result_type\n    prec_prod (const matrix_expression<E1> &e1,\n               const vector_expression<E2> &e2,\n               unknown_storage_tag,\n               row_major_tag) {\n        typedef typename matrix_vector_binary1_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                                      typename type_traits<typename E2::value_type>::precision_type, E2>::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    // Dispatcher\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_vector_binary1_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                          typename type_traits<typename E2::value_type>::precision_type, E2>::result_type\n    prec_prod (const matrix_expression<E1> &e1,\n               const vector_expression<E2> &e2) {\n        BOOST_STATIC_ASSERT (E2::complexity == 0);\n        typedef typename matrix_vector_binary1_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                                      typename type_traits<typename E2::value_type>::precision_type, E2>::storage_category storage_category;\n        typedef typename matrix_vector_binary1_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                                      typename type_traits<typename E2::value_type>::precision_type, E2>::orientation_category orientation_category;\n        return prec_prod (e1, e2, storage_category (), orientation_category ());\n    }\n\n    template<class V, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    V &\n    prod (const matrix_expression<E1> &e1,\n          const vector_expression<E2> &e2,\n          V &v) {\n        return v.assign (prod (e1, e2));\n    }\n\n    template<class V, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    V &\n    prec_prod (const matrix_expression<E1> &e1,\n               const vector_expression<E2> &e2,\n               V &v) {\n        return v.assign (prec_prod (e1, e2));\n    }\n\n    template<class V, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    V\n    prod (const matrix_expression<E1> &e1,\n          const vector_expression<E2> &e2) {\n        return V (prod (e1, e2));\n    }\n\n    template<class V, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    V\n    prec_prod (const matrix_expression<E1> &e1,\n               const vector_expression<E2> &e2) {\n        return V (prec_prod (e1, e2));\n    }\n\n    template<class E1, class E2, class F>\n    class matrix_vector_binary2:\n        public vector_expression<matrix_vector_binary2<E1, E2, F> > {\n\n        typedef E1 expression1_type;\n        typedef E2 expression2_type;\n        typedef F functor_type;\n    public:\n        typedef typename E1::const_closure_type expression1_closure_type;\n        typedef typename E2::const_closure_type expression2_closure_type;\n    private:\n        typedef matrix_vector_binary2<E1, E2, F> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using vector_expression<self_type>::operator ();\n#endif\n        static const unsigned complexity = 1;\n        typedef typename promote_traits<typename E1::size_type, typename E2::size_type>::promote_type size_type;\n        typedef typename promote_traits<typename E1::difference_type, typename E2::difference_type>::promote_type difference_type;\n        typedef typename F::result_type value_type;\n        typedef value_type const_reference;\n        typedef const_reference reference;\n        typedef const self_type const_closure_type;\n        typedef const_closure_type closure_type;\n        typedef unknown_storage_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        matrix_vector_binary2 (const expression1_type &e1, const expression2_type &e2): \n            e1_ (e1), e2_ (e2) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size () const { \n            return e2_.size2 (); \n        }\n\n    public:\n        // Expression accessors\n        BOOST_UBLAS_INLINE\n        const expression1_closure_type &expression1 () const {\n            return e1_;\n        }\n        BOOST_UBLAS_INLINE\n        const expression2_closure_type &expression2 () const {\n            return e2_;\n        }\n    public:\n\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type j) const { \n            return functor_type::apply (e1_, e2_, j); \n        }\n\n        // Closure comparison\n        BOOST_UBLAS_INLINE\n        bool same_closure (const matrix_vector_binary2 &mvb2) const {\n            return (*this).expression1 ().same_closure (mvb2.expression1 ()) &&\n                   (*this).expression2 ().same_closure (mvb2.expression2 ());\n        }\n\n        // Iterator types\n    private:\n        typedef typename E1::const_iterator const_subiterator1_type;\n        typedef typename E2::const_iterator2 const_subiterator2_type;\n        typedef const value_type *const_pointer;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef indexed_const_iterator<const_closure_type, typename const_subiterator2_type::iterator_category> const_iterator;\n        typedef const_iterator iterator;\n#else\n        class const_iterator;\n        typedef const_iterator iterator;\n#endif\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator find (size_type j) const {\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            const_subiterator2_type it2 (e2_.find2 (0, 0, j));\n            return const_iterator (*this, it2.index2 ());\n#else\n            return const_iterator (*this, e2_.find2 (0, 0, j));\n#endif\n        }\n\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator:\n            public container_const_reference<matrix_vector_binary2>,\n            public iterator_base_traits<typename iterator_restrict_traits<typename E1::const_iterator::iterator_category,\n                                                                          typename E2::const_iterator2::iterator_category>::iterator_category>::template\n                iterator_base<const_iterator, value_type>::type {\n        public:\n            typedef typename iterator_restrict_traits<typename E1::const_iterator::iterator_category,\n                                                      typename E2::const_iterator2::iterator_category>::iterator_category iterator_category;\n            typedef typename matrix_vector_binary2::difference_type difference_type;\n            typedef typename matrix_vector_binary2::value_type value_type;\n            typedef typename matrix_vector_binary2::const_reference reference;\n            typedef typename matrix_vector_binary2::const_pointer pointer;\n\n            // Construction and destruction\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<self_type> (), it2_ (), e1_begin_ (), e1_end_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const self_type &mvb, const const_subiterator2_type &it2):\n                container_const_reference<self_type> (mvb), it2_ (it2), e1_begin_ (mvb.expression1 ().begin ()), e1_end_ (mvb.expression1 ().end ()) {}\n#else\n            BOOST_UBLAS_INLINE\n            const_iterator ():\n                container_const_reference<self_type> (), it2_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator (const self_type &mvb, const const_subiterator2_type &it2):\n                container_const_reference<self_type> (mvb), it2_ (it2) {}\n#endif\n\n        private:\n            // Dense random access specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (dense_random_access_iterator_tag) const {\n                const self_type &mvb = (*this) ();\n#ifdef BOOST_UBLAS_USE_INDEXING\n                return mvb (index ());\n#elif BOOST_UBLAS_USE_ITERATING\n                difference_type size = BOOST_UBLAS_SAME (mvb.expression2 ().size1 (), mvb.expression1 ().size ());\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (size, e1_begin_, it2_.begin ());\n#else\n                return functor_type::apply (size, mvb.expression1 ().begin (), it2_.begin ());\n#endif\n#else\n                difference_type size = BOOST_UBLAS_SAME (mvb.expression2 ().size1 (), mvb.expression1 ().size ());\n                if (size >= BOOST_UBLAS_ITERATOR_THRESHOLD)\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                    return functor_type::apply (size, e1_begin_, it2_.begin ());\n#else\n                    return functor_type::apply (size, mvb.expression1 ().begin (), it2_.begin ());\n#endif\n                else\n                    return mvb (index ());\n#endif\n            }\n\n            // Packed bidirectional specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (packed_random_access_iterator_tag) const {\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (e1_begin_, e1_end_, it2_.begin (), it2_.end ());\n#else\n                const self_type &mvb = (*this) ();\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n                return functor_type::apply (mvb.expression1 ().begin (), mvb.expression1 ().end (),\n                                        it2_.begin (), it2_.end ());\n#else\n                return functor_type::apply (mvb.expression1 ().begin (), mvb.expression1 ().end (),\n                                        boost::numeric::ublas::begin (it2_, iterator2_tag ()),\n                                        boost::numeric::ublas::end (it2_, iterator2_tag ()));\n#endif\n#endif\n            }\n\n            // Sparse bidirectional specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (sparse_bidirectional_iterator_tag) const {\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (e1_begin_, e1_end_, it2_.begin (), it2_.end (), sparse_bidirectional_iterator_tag ());\n#else\n                const self_type &mvb = (*this) ();\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n                return functor_type::apply (mvb.expression1 ().begin (), mvb.expression1 ().end (),\n                                        it2_.begin (), it2_.end (), sparse_bidirectional_iterator_tag ());\n#else\n                return functor_type::apply (mvb.expression1 ().begin (), mvb.expression1 ().end (),\n                                        boost::numeric::ublas::begin (it2_, iterator2_tag ()),\n                                        boost::numeric::ublas::end (it2_, iterator2_tag ()), sparse_bidirectional_iterator_tag ());\n#endif\n#endif\n            }\n\n        public:\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator &operator ++ () {\n                ++ it2_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -- () {\n                -- it2_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator += (difference_type n) {\n                it2_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator &operator -= (difference_type n) {\n                it2_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it2_ - it.it2_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return dereference (iterator_category ());\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n            // Index\n            BOOST_UBLAS_INLINE\n            size_type index () const {\n                return it2_.index2 ();\n            }\n\n            // Assignment \n            BOOST_UBLAS_INLINE\n            const_iterator &operator = (const const_iterator &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it2_ = it.it2_;\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                e1_begin_ = it.e1_begin_;\n                e1_end_ = it.e1_end_;\n#endif\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it2_ == it.it2_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                return it2_ < it.it2_;\n            }\n\n        private:\n            const_subiterator2_type it2_;\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            // Mutable due to assignment \n            /* const */ const_subiterator1_type e1_begin_;\n            /* const */ const_subiterator1_type e1_end_;\n#endif\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator begin () const {\n            return find (0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator cbegin () const {\n            return begin ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator end () const {\n            return find (size ()); \n        }\n        BOOST_UBLAS_INLINE\n        const_iterator cend () const {\n            return end ();\n        }\n\n        // Reverse iterator\n        typedef reverse_iterator_base<const_iterator> const_reverse_iterator;\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rbegin () const {\n            return const_reverse_iterator (end ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator crbegin () const {\n            return rbegin ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator rend () const {\n            return const_reverse_iterator (begin ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator crend () const {\n            return rend ();\n        }\n\n    private:\n        expression1_closure_type e1_;\n        expression2_closure_type e2_;\n    };\n\n    template<class T1, class E1, class T2, class E2>\n    struct matrix_vector_binary2_traits {\n        typedef unknown_storage_tag storage_category;\n        typedef column_major_tag orientation_category;\n        typedef typename promote_traits<T1, T2>::promote_type promote_type;\n        typedef matrix_vector_binary2<E1, E2, matrix_vector_prod2<E1, E2, promote_type> > expression_type;\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n        typedef expression_type result_type;\n#else\n        typedef typename E2::vector_temporary_type result_type;\n#endif\n    };\n\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_vector_binary2_traits<typename E1::value_type, E1,\n                                          typename E2::value_type, E2>::result_type\n    prod (const vector_expression<E1> &e1,\n          const matrix_expression<E2> &e2,\n          unknown_storage_tag,\n          column_major_tag) {\n        typedef typename matrix_vector_binary2_traits<typename E1::value_type, E1,\n                                                      typename E2::value_type, E2>::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    // Dispatcher\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_vector_binary2_traits<typename E1::value_type, E1,\n                                          typename E2::value_type, E2>::result_type\n    prod (const vector_expression<E1> &e1,\n          const matrix_expression<E2> &e2) {\n        BOOST_STATIC_ASSERT (E1::complexity == 0);\n        typedef typename matrix_vector_binary2_traits<typename E1::value_type, E1,\n                                                      typename E2::value_type, E2>::storage_category storage_category;\n        typedef typename matrix_vector_binary2_traits<typename E1::value_type, E1,\n                                                      typename E2::value_type, E2>::orientation_category orientation_category;\n        return prod (e1, e2, storage_category (), orientation_category ());\n    }\n\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_vector_binary2_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                          typename type_traits<typename E2::value_type>::precision_type, E2>::result_type\n    prec_prod (const vector_expression<E1> &e1,\n               const matrix_expression<E2> &e2,\n               unknown_storage_tag,\n               column_major_tag) {\n        typedef typename matrix_vector_binary2_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                                      typename type_traits<typename E2::value_type>::precision_type, E2>::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    // Dispatcher\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_vector_binary2_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                          typename type_traits<typename E2::value_type>::precision_type, E2>::result_type\n    prec_prod (const vector_expression<E1> &e1,\n               const matrix_expression<E2> &e2) {\n        BOOST_STATIC_ASSERT (E1::complexity == 0);\n        typedef typename matrix_vector_binary2_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                                      typename type_traits<typename E2::value_type>::precision_type, E2>::storage_category storage_category;\n        typedef typename matrix_vector_binary2_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                                      typename type_traits<typename E2::value_type>::precision_type, E2>::orientation_category orientation_category;\n        return prec_prod (e1, e2, storage_category (), orientation_category ());\n    }\n\n    template<class V, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    V &\n    prod (const vector_expression<E1> &e1,\n          const matrix_expression<E2> &e2,\n          V &v) {\n        return v.assign (prod (e1, e2));\n    }\n\n    template<class V, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    V &\n    prec_prod (const vector_expression<E1> &e1,\n               const matrix_expression<E2> &e2,\n               V &v) {\n        return v.assign (prec_prod (e1, e2));\n    }\n\n    template<class V, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    V\n    prod (const vector_expression<E1> &e1,\n          const matrix_expression<E2> &e2) {\n        return V (prod (e1, e2));\n    }\n\n    template<class V, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    V\n    prec_prod (const vector_expression<E1> &e1,\n               const matrix_expression<E2> &e2) {\n        return V (prec_prod (e1, e2));\n    }\n\n    template<class E1, class E2, class F>\n    class matrix_matrix_binary:\n        public matrix_expression<matrix_matrix_binary<E1, E2, F> > {\n\n    public:\n        typedef E1 expression1_type;\n        typedef E2 expression2_type;\n    private:\n        typedef F functor_type;\n    public:\n        typedef typename E1::const_closure_type expression1_closure_type;\n        typedef typename E2::const_closure_type expression2_closure_type;\n    private:\n        typedef matrix_matrix_binary<E1, E2, F> self_type;\n    public:\n#ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS\n        using matrix_expression<self_type>::operator ();\n#endif\n        static const unsigned complexity = 1;\n        typedef typename promote_traits<typename E1::size_type, typename E2::size_type>::promote_type size_type;\n        typedef typename promote_traits<typename E1::difference_type, typename E2::difference_type>::promote_type difference_type;\n        typedef typename F::result_type value_type;\n        typedef value_type const_reference;\n        typedef const_reference reference;\n        typedef const self_type const_closure_type;\n        typedef const_closure_type closure_type;\n        typedef unknown_orientation_tag orientation_category;\n        typedef unknown_storage_tag storage_category;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        matrix_matrix_binary (const expression1_type &e1, const expression2_type &e2):\n            e1_ (e1), e2_ (e2) {}\n\n        // Accessors\n        BOOST_UBLAS_INLINE\n        size_type size1 () const {\n            return e1_.size1 ();\n        }\n        BOOST_UBLAS_INLINE\n        size_type size2 () const {\n            return e2_.size2 ();\n        }\n\n    public:\n        // Expression accessors\n        BOOST_UBLAS_INLINE\n        const expression1_closure_type &expression1 () const {\n            return e1_;\n        }\n        BOOST_UBLAS_INLINE\n        const expression2_closure_type &expression2 () const {\n            return e2_;\n        }\n\n    public:\n        // Element access\n        BOOST_UBLAS_INLINE\n        const_reference operator () (size_type i, size_type j) const {\n            return functor_type::apply (e1_, e2_, i, j);\n        }\n\n        // Closure comparison\n        BOOST_UBLAS_INLINE\n        bool same_closure (const matrix_matrix_binary &mmb) const {\n            return (*this).expression1 ().same_closure (mmb.expression1 ()) &&\n                   (*this).expression2 ().same_closure (mmb.expression2 ());\n        }\n\n        // Iterator types\n    private:\n        typedef typename E1::const_iterator1 const_iterator11_type;\n        typedef typename E1::const_iterator2 const_iterator12_type;\n        typedef typename E2::const_iterator1 const_iterator21_type;\n        typedef typename E2::const_iterator2 const_iterator22_type;\n        typedef const value_type *const_pointer;\n\n    public:\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        typedef typename iterator_restrict_traits<typename const_iterator11_type::iterator_category,\n                                                  typename const_iterator22_type::iterator_category>::iterator_category iterator_category;\n        typedef indexed_const_iterator1<const_closure_type, iterator_category> const_iterator1;\n        typedef const_iterator1 iterator1;\n        typedef indexed_const_iterator2<const_closure_type, iterator_category> const_iterator2;\n        typedef const_iterator2 iterator2;\n#else\n        class const_iterator1;\n        typedef const_iterator1 iterator1;\n        class const_iterator2;\n        typedef const_iterator2 iterator2;\n#endif\n        typedef reverse_iterator_base1<const_iterator1> const_reverse_iterator1;\n        typedef reverse_iterator_base2<const_iterator2> const_reverse_iterator2;\n\n        // Element lookup\n        BOOST_UBLAS_INLINE\n        const_iterator1 find1 (int /* rank */, size_type i, size_type j) const {\n            // FIXME sparse matrix tests fail!\n            // const_iterator11_type it11 (e1_.find1 (rank, i, 0));\n            const_iterator11_type it11 (e1_.find1 (0, i, 0));\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator1 (*this, it11.index1 (), j);\n#else\n            // FIXME sparse matrix tests fail!\n            // const_iterator22_type it22 (e2_.find2 (rank, 0, j));\n            const_iterator22_type it22 (e2_.find2 (0, 0, j));\n            return const_iterator1 (*this, it11, it22);\n#endif\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 find2 (int /* rank */, size_type i, size_type j) const {\n            // FIXME sparse matrix tests fail!\n            // const_iterator22_type it22 (e2_.find2 (rank, 0, j));\n            const_iterator22_type it22 (e2_.find2 (0, 0, j));\n#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR\n            return const_iterator2 (*this, i, it22.index2 ());\n#else\n            // FIXME sparse matrix tests fail!\n            // const_iterator11_type it11 (e1_.find1 (rank, i, 0));\n            const_iterator11_type it11 (e1_.find1 (0, i, 0));\n            return const_iterator2 (*this, it11, it22);\n#endif\n        }\n\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator1:\n            public container_const_reference<matrix_matrix_binary>,\n            public iterator_base_traits<typename iterator_restrict_traits<typename E1::const_iterator1::iterator_category,\n                                                                          typename E2::const_iterator2::iterator_category>::iterator_category>::template\n                iterator_base<const_iterator1, value_type>::type {\n        public:\n            typedef typename iterator_restrict_traits<typename E1::const_iterator1::iterator_category,\n                                                      typename E2::const_iterator2::iterator_category>::iterator_category iterator_category;\n            typedef typename matrix_matrix_binary::difference_type difference_type;\n            typedef typename matrix_matrix_binary::value_type value_type;\n            typedef typename matrix_matrix_binary::const_reference reference;\n            typedef typename matrix_matrix_binary::const_pointer pointer;\n\n            typedef const_iterator2 dual_iterator_type;\n            typedef const_reverse_iterator2 dual_reverse_iterator_type;\n\n            // Construction and destruction\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            BOOST_UBLAS_INLINE\n            const_iterator1 ():\n                container_const_reference<self_type> (), it1_ (), it2_ (), it2_begin_ (), it2_end_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const self_type &mmb, const const_iterator11_type &it1, const const_iterator22_type &it2):\n                container_const_reference<self_type> (mmb), it1_ (it1), it2_ (it2), it2_begin_ (it2.begin ()), it2_end_ (it2.end ()) {}\n#else\n            BOOST_UBLAS_INLINE\n            const_iterator1 ():\n                container_const_reference<self_type> (), it1_ (), it2_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator1 (const self_type &mmb, const const_iterator11_type &it1, const const_iterator22_type &it2):\n                container_const_reference<self_type> (mmb), it1_ (it1), it2_ (it2) {}\n#endif\n\n        private:\n            // Random access specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (dense_random_access_iterator_tag) const {\n                const self_type &mmb = (*this) ();\n#ifdef BOOST_UBLAS_USE_INDEXING\n                return mmb (index1 (), index2 ());\n#elif BOOST_UBLAS_USE_ITERATING\n                difference_type size = BOOST_UBLAS_SAME (mmb.expression1 ().size2 (), mmb.expression2 ().size1 ());\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (size, it1_.begin (), it2_begin_);\n#else\n                return functor_type::apply (size, it1_.begin (), it2_.begin ());\n#endif\n#else\n                difference_type size = BOOST_UBLAS_SAME (mmb.expression1 ().size2 (), mmb.expression2 ().size1 ());\n                if (size >= BOOST_UBLAS_ITERATOR_THRESHOLD)\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                    return functor_type::apply (size, it1_.begin (), it2_begin_);\n#else\n                    return functor_type::apply (size, it1_.begin (), it2_.begin ());\n#endif\n                else\n                    return mmb (index1 (), index2 ());\n#endif\n            }\n\n            // Packed bidirectional specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (packed_random_access_iterator_tag) const {\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (it1_.begin (), it1_.end (),\n                                        it2_begin_, it2_end_, packed_random_access_iterator_tag ());\n#else\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n                return functor_type::apply (it1_.begin (), it1_.end (),\n                                        it2_.begin (), it2_.end (), packed_random_access_iterator_tag ());\n#else\n                return functor_type::apply (boost::numeric::ublas::begin (it1_, iterator1_tag ()),\n                                        boost::numeric::ublas::end (it1_, iterator1_tag ()),\n                                        boost::numeric::ublas::begin (it2_, iterator2_tag ()),\n                                        boost::numeric::ublas::end (it2_, iterator2_tag ()), packed_random_access_iterator_tag ());\n#endif\n#endif\n            }\n\n            // Sparse bidirectional specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (sparse_bidirectional_iterator_tag) const {\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (it1_.begin (), it1_.end (),\n                                        it2_begin_, it2_end_, sparse_bidirectional_iterator_tag ());\n#else\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n                return functor_type::apply (it1_.begin (), it1_.end (),\n                                        it2_.begin (), it2_.end (), sparse_bidirectional_iterator_tag ());\n#else\n                return functor_type::apply (boost::numeric::ublas::begin (it1_, iterator1_tag ()),\n                                        boost::numeric::ublas::end (it1_, iterator1_tag ()),\n                                        boost::numeric::ublas::begin (it2_, iterator2_tag ()),\n                                        boost::numeric::ublas::end (it2_, iterator2_tag ()), sparse_bidirectional_iterator_tag ());\n#endif\n#endif\n            }\n\n        public:\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator ++ () {\n                ++ it1_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -- () {\n                -- it1_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator += (difference_type n) {\n                it1_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator -= (difference_type n) {\n                it1_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ - it.it1_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return dereference (iterator_category ());\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 begin () const {\n                return (*this) ().find2 (1, index1 (), 0);\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 end () const {\n                return (*this) ().find2 (1, index1 (), (*this) ().size2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator2 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rbegin () const {\n                return const_reverse_iterator2 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 rend () const {\n                return const_reverse_iterator2 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator2 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it1_.index1 ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return it2_.index2 ();\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator1 &operator = (const const_iterator1 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it1_ = it.it1_;\n                it2_ = it.it2_;\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                it2_begin_ = it.it2_begin_;\n                it2_end_ = it.it2_end_;\n#endif\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ == it.it1_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator1 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it2_ == it.it2_, external_logic ());\n                return it1_ < it.it1_;\n            }\n\n        private:\n            const_iterator11_type it1_;\n            // Mutable due to assignment\n            /* const */ const_iterator22_type it2_;\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            /* const */ const_iterator21_type it2_begin_;\n            /* const */ const_iterator21_type it2_end_;\n#endif\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator1 begin1 () const {\n            return find1 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cbegin1 () const {\n            return begin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 end1 () const {\n            return find1 (0, size1 (), 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator1 cend1 () const {\n            return end1 ();\n        }\n\n#ifndef BOOST_UBLAS_USE_INDEXED_ITERATOR\n        class const_iterator2:\n            public container_const_reference<matrix_matrix_binary>,\n            public iterator_base_traits<typename iterator_restrict_traits<typename E1::const_iterator1::iterator_category,\n                                                                          typename E2::const_iterator2::iterator_category>::iterator_category>::template\n                iterator_base<const_iterator2, value_type>::type {\n        public:\n            typedef typename iterator_restrict_traits<typename E1::const_iterator1::iterator_category,\n                                                      typename E2::const_iterator2::iterator_category>::iterator_category iterator_category;\n            typedef typename matrix_matrix_binary::difference_type difference_type;\n            typedef typename matrix_matrix_binary::value_type value_type;\n            typedef typename matrix_matrix_binary::const_reference reference;\n            typedef typename matrix_matrix_binary::const_pointer pointer;\n\n            typedef const_iterator1 dual_iterator_type;\n            typedef const_reverse_iterator1 dual_reverse_iterator_type;\n\n            // Construction and destruction\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            BOOST_UBLAS_INLINE\n            const_iterator2 ():\n                container_const_reference<self_type> (), it1_ (), it2_ (), it1_begin_ (), it1_end_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const self_type &mmb, const const_iterator11_type &it1, const const_iterator22_type &it2):\n                container_const_reference<self_type> (mmb), it1_ (it1), it2_ (it2), it1_begin_ (it1.begin ()), it1_end_ (it1.end ()) {}\n#else\n            BOOST_UBLAS_INLINE\n            const_iterator2 ():\n                container_const_reference<self_type> (), it1_ (), it2_ () {}\n            BOOST_UBLAS_INLINE\n            const_iterator2 (const self_type &mmb, const const_iterator11_type &it1, const const_iterator22_type &it2):\n                container_const_reference<self_type> (mmb), it1_ (it1), it2_ (it2) {}\n#endif\n\n        private:\n            // Random access specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (dense_random_access_iterator_tag) const {\n                const self_type &mmb = (*this) ();\n#ifdef BOOST_UBLAS_USE_INDEXING\n                return mmb (index1 (), index2 ());\n#elif BOOST_UBLAS_USE_ITERATING\n                difference_type size = BOOST_UBLAS_SAME (mmb.expression1 ().size2 (), mmb.expression2 ().size1 ());\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (size, it1_begin_, it2_.begin ());\n#else\n                return functor_type::apply (size, it1_.begin (), it2_.begin ());\n#endif\n#else\n                difference_type size = BOOST_UBLAS_SAME (mmb.expression1 ().size2 (), mmb.expression2 ().size1 ());\n                if (size >= BOOST_UBLAS_ITERATOR_THRESHOLD)\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                    return functor_type::apply (size, it1_begin_, it2_.begin ());\n#else\n                    return functor_type::apply (size, it1_.begin (), it2_.begin ());\n#endif\n                else\n                    return mmb (index1 (), index2 ());\n#endif\n            }\n\n            // Packed bidirectional specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (packed_random_access_iterator_tag) const {\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (it1_begin_, it1_end_,\n                                        it2_.begin (), it2_.end (), packed_random_access_iterator_tag ());\n#else\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n                return functor_type::apply (it1_.begin (), it1_.end (),\n                                        it2_.begin (), it2_.end (), packed_random_access_iterator_tag ());\n#else\n                return functor_type::apply (boost::numeric::ublas::begin (it1_, iterator1_tag ()),\n                                        boost::numeric::ublas::end (it1_, iterator1_tag ()),\n                                        boost::numeric::ublas::begin (it2_, iterator2_tag ()),\n                                        boost::numeric::ublas::end (it2_, iterator2_tag ()), packed_random_access_iterator_tag ());\n#endif\n#endif\n            }\n\n            // Sparse bidirectional specialization\n            BOOST_UBLAS_INLINE\n            value_type dereference (sparse_bidirectional_iterator_tag) const {\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                return functor_type::apply (it1_begin_, it1_end_,\n                                        it2_.begin (), it2_.end (), sparse_bidirectional_iterator_tag ());\n#else\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n                return functor_type::apply (it1_.begin (), it1_.end (),\n                                        it2_.begin (), it2_.end (), sparse_bidirectional_iterator_tag ());\n#else\n                return functor_type::apply (boost::numeric::ublas::begin (it1_, iterator1_tag ()),\n                                        boost::numeric::ublas::end (it1_, iterator1_tag ()),\n                                        boost::numeric::ublas::begin (it2_, iterator2_tag ()),\n                                        boost::numeric::ublas::end (it2_, iterator2_tag ()), sparse_bidirectional_iterator_tag ());\n#endif\n#endif\n            }\n\n        public:\n            // Arithmetic\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator ++ () {\n                ++ it2_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -- () {\n                -- it2_;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator += (difference_type n) {\n                it2_ += n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator -= (difference_type n) {\n                it2_ -= n;\n                return *this;\n            }\n            BOOST_UBLAS_INLINE\n            difference_type operator - (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ - it.it2_;\n            }\n\n            // Dereference\n            BOOST_UBLAS_INLINE\n            const_reference operator * () const {\n                return dereference (iterator_category ());\n            }\n            BOOST_UBLAS_INLINE\n            const_reference operator [] (difference_type n) const {\n                return *(*this + n);\n            }\n\n#ifndef BOOST_UBLAS_NO_NESTED_CLASS_RELATION\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 begin () const {\n                return (*this) ().find1 (1, 0, index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cbegin () const {\n                return begin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 end () const {\n                return (*this) ().find1 (1, (*this) ().size1 (), index2 ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_iterator1 cend () const {\n                return end ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rbegin () const {\n                return const_reverse_iterator1 (end ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crbegin () const {\n                return rbegin ();\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 rend () const {\n                return const_reverse_iterator1 (begin ());\n            }\n            BOOST_UBLAS_INLINE\n#ifdef BOOST_UBLAS_MSVC_NESTED_CLASS_RELATION\n            typename self_type::\n#endif\n            const_reverse_iterator1 crend () const {\n                return rend ();\n            }\n#endif\n\n            // Indices\n            BOOST_UBLAS_INLINE\n            size_type index1 () const {\n                return it1_.index1 ();\n            }\n            BOOST_UBLAS_INLINE\n            size_type index2 () const {\n                return it2_.index2 ();\n            }\n\n            // Assignment\n            BOOST_UBLAS_INLINE\n            const_iterator2 &operator = (const const_iterator2 &it) {\n                container_const_reference<self_type>::assign (&it ());\n                it1_ = it.it1_;\n                it2_ = it.it2_;\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n                it1_begin_ = it.it1_begin_;\n                it1_end_ = it.it1_end_;\n#endif\n                return *this;\n            }\n\n            // Comparison\n            BOOST_UBLAS_INLINE\n            bool operator == (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ == it.it2_;\n            }\n            BOOST_UBLAS_INLINE\n            bool operator < (const const_iterator2 &it) const {\n                BOOST_UBLAS_CHECK ((*this) ().same_closure (it ()), external_logic ());\n                BOOST_UBLAS_CHECK (it1_ == it.it1_, external_logic ());\n                return it2_ < it.it2_;\n            }\n\n        private:\n            // Mutable due to assignment\n            /* const */ const_iterator11_type it1_;\n            const_iterator22_type it2_;\n#ifdef BOOST_UBLAS_USE_INVARIANT_HOISTING\n            /* const */ const_iterator12_type it1_begin_;\n            /* const */ const_iterator12_type it1_end_;\n#endif\n        };\n#endif\n\n        BOOST_UBLAS_INLINE\n        const_iterator2 begin2 () const {\n            return find2 (0, 0, 0);\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cbegin2 () const {\n            return begin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 end2 () const {\n            return find2 (0, 0, size2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_iterator2 cend2 () const {\n            return end2 ();\n        }\n\n        // Reverse iterators\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rbegin1 () const {\n            return const_reverse_iterator1 (end1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crbegin1 () const {\n            return rbegin1 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 rend1 () const {\n            return const_reverse_iterator1 (begin1 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator1 crend1 () const {\n            return rend1 ();\n        }\n\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rbegin2 () const {\n            return const_reverse_iterator2 (end2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crbegin2 () const {\n            return rbegin2 ();\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 rend2 () const {\n            return const_reverse_iterator2 (begin2 ());\n        }\n        BOOST_UBLAS_INLINE\n        const_reverse_iterator2 crend2 () const {\n            return rend2 ();\n        }\n\n    private:\n        expression1_closure_type e1_;\n        expression2_closure_type e2_;\n    };\n\n    template<class T1, class E1, class T2, class E2>\n    struct matrix_matrix_binary_traits {\n        typedef unknown_storage_tag storage_category;\n        typedef unknown_orientation_tag orientation_category;\n        typedef typename promote_traits<T1, T2>::promote_type promote_type;\n        typedef matrix_matrix_binary<E1, E2, matrix_matrix_prod<E1, E2, promote_type> > expression_type;\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n        typedef expression_type result_type;\n#else\n        typedef typename E1::matrix_temporary_type result_type;\n#endif\n    };\n\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_matrix_binary_traits<typename E1::value_type, E1,\n                                         typename E2::value_type, E2>::result_type\n    prod (const matrix_expression<E1> &e1,\n          const matrix_expression<E2> &e2,\n          unknown_storage_tag,\n          unknown_orientation_tag) {\n        typedef typename matrix_matrix_binary_traits<typename E1::value_type, E1,\n                                                     typename E2::value_type, E2>::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    // Dispatcher\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_matrix_binary_traits<typename E1::value_type, E1,\n                                         typename E2::value_type, E2>::result_type\n    prod (const matrix_expression<E1> &e1,\n          const matrix_expression<E2> &e2) {\n        BOOST_STATIC_ASSERT (E1::complexity == 0 && E2::complexity == 0);\n        typedef typename matrix_matrix_binary_traits<typename E1::value_type, E1,\n                                                     typename E2::value_type, E2>::storage_category storage_category;\n        typedef typename matrix_matrix_binary_traits<typename E1::value_type, E1,\n                                                     typename E2::value_type, E2>::orientation_category orientation_category;\n        return prod (e1, e2, storage_category (), orientation_category ());\n    }\n\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_matrix_binary_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                         typename type_traits<typename E2::value_type>::precision_type, E2>::result_type\n    prec_prod (const matrix_expression<E1> &e1,\n               const matrix_expression<E2> &e2,\n               unknown_storage_tag,\n               unknown_orientation_tag) {\n        typedef typename matrix_matrix_binary_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                                     typename type_traits<typename E2::value_type>::precision_type, E2>::expression_type expression_type;\n        return expression_type (e1 (), e2 ());\n    }\n\n    // Dispatcher\n    template<class E1, class E2>\n    BOOST_UBLAS_INLINE\n    typename matrix_matrix_binary_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                         typename type_traits<typename E2::value_type>::precision_type, E2>::result_type\n    prec_prod (const matrix_expression<E1> &e1,\n               const matrix_expression<E2> &e2) {\n        BOOST_STATIC_ASSERT (E1::complexity == 0 && E2::complexity == 0);\n        typedef typename matrix_matrix_binary_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                                     typename type_traits<typename E2::value_type>::precision_type, E2>::storage_category storage_category;\n        typedef typename matrix_matrix_binary_traits<typename type_traits<typename E1::value_type>::precision_type, E1,\n                                                     typename type_traits<typename E2::value_type>::precision_type, E2>::orientation_category orientation_category;\n        return prec_prod (e1, e2, storage_category (), orientation_category ());\n    }\n\n    template<class M, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    M &\n    prod (const matrix_expression<E1> &e1,\n          const matrix_expression<E2> &e2,\n          M &m) {\n        return m.assign (prod (e1, e2));\n    }\n\n    template<class M, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    M &\n    prec_prod (const matrix_expression<E1> &e1,\n               const matrix_expression<E2> &e2,\n               M &m) {\n        return m.assign (prec_prod (e1, e2));\n    }\n\n    template<class M, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    M\n    prod (const matrix_expression<E1> &e1,\n          const matrix_expression<E2> &e2) {\n        return M (prod (e1, e2));\n    }\n\n    template<class M, class E1, class E2>\n    BOOST_UBLAS_INLINE\n    M\n    prec_prod (const matrix_expression<E1> &e1,\n               const matrix_expression<E2> &e2) {\n        return M (prec_prod (e1, e2));\n    }\n\n    template<class E, class F>\n    class matrix_scalar_unary:\n        public scalar_expression<matrix_scalar_unary<E, F> > {\n    public:\n        typedef E expression_type;\n        typedef F functor_type;\n        typedef typename F::result_type value_type;\n        typedef typename E::const_closure_type expression_closure_type;\n\n        // Construction and destruction\n        BOOST_UBLAS_INLINE\n        explicit matrix_scalar_unary (const expression_type &e):\n            e_ (e) {}\n\n    private:\n        // Expression accessors\n        BOOST_UBLAS_INLINE\n        const expression_closure_type &expression () const {\n            return e_;\n        }\n\n    public:\n        BOOST_UBLAS_INLINE\n        operator value_type () const {\n            return functor_type::apply (e_);\n        }\n\n    private:\n        expression_closure_type e_;\n    };\n\n    template<class E, class F>\n    struct matrix_scalar_unary_traits {\n        typedef matrix_scalar_unary<E, F> expression_type;\n#ifndef BOOST_UBLAS_SIMPLE_ET_DEBUG\n         typedef expression_type result_type;\n#else\n         typedef typename F::result_type result_type;\n#endif\n    };\n\n    template<class E>\n    BOOST_UBLAS_INLINE\n    typename matrix_scalar_unary_traits<E, matrix_norm_1<E> >::result_type\n    norm_1 (const matrix_expression<E> &e) {\n        typedef typename matrix_scalar_unary_traits<E, matrix_norm_1<E> >::expression_type expression_type;\n        return expression_type (e ());\n    }\n\n    template<class E>\n    BOOST_UBLAS_INLINE\n    typename matrix_scalar_unary_traits<E, matrix_norm_frobenius<E> >::result_type\n    norm_frobenius (const matrix_expression<E> &e) {\n        typedef typename matrix_scalar_unary_traits<E, matrix_norm_frobenius<E> >::expression_type expression_type;\n        return expression_type (e ());\n    }\n\n    template<class E>\n    BOOST_UBLAS_INLINE\n    typename matrix_scalar_unary_traits<E, matrix_norm_inf<E> >::result_type\n    norm_inf (const matrix_expression<E> &e) {\n        typedef typename matrix_scalar_unary_traits<E, matrix_norm_inf<E> >::expression_type expression_type;\n        return expression_type (e ());\n    }\n\n}}}\n\n#endif\n", "meta": {"hexsha": "a36313096e45d47f0e3e9ea2d1c7ee2e7c1d8532", "size": 213106, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/libboost/boost_1_62_0/boost/numeric/ublas/matrix_expression.hpp", "max_stars_repo_name": "189569400/ClickHouse", "max_stars_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "contrib/libboost/boost_1_62_0/boost/numeric/ublas/matrix_expression.hpp", "max_issues_repo_name": "189569400/ClickHouse", "max_issues_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1074.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T15:08:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-22T20:28:39.000Z", "max_forks_repo_path": "contrib/libboost/boost_1_62_0/boost/numeric/ublas/matrix_expression.hpp", "max_forks_repo_name": "189569400/ClickHouse", "max_forks_repo_head_hexsha": "0b8683c8c9f0e17446bef5498403c39e9cb483b8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 534.0, "max_forks_repo_forks_event_min_datetime": "2016-10-20T21:00:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T10:02:27.000Z", "avg_line_length": 37.8249911253, "max_line_length": 164, "alphanum_fraction": 0.5824941578, "num_tokens": 45437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22233196731042748}}
{"text": "// Boost.Units - A C++ library for zero-overhead dimensional analysis and \n// unit/quantity manipulation and conversion\n//\n// Copyright (C) 2003-2008 Matthias Christian Schabel\n// Copyright (C) 2007-2008 Steven Watanabe\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_UNITS_DIM_HPP\n#define BOOST_UNITS_DIM_HPP\n\n#include <boost/static_assert.hpp>\n\n#include <boost/type_traits/is_same.hpp>\n\n#include <boost/mpl/arithmetic.hpp>\n\n#include <boost/units/config.hpp>\n#include <boost/units/static_rational.hpp>\n#include <boost/units/detail/dim_impl.hpp>\n\n/// \\file dim.hpp\n/// \\brief Handling of fundamental dimension/exponent pairs.\n\nnamespace boost {\n\nnamespace units {\n\nnamespace detail {\n\nstruct dim_tag { };\n\n}\n\n/// \\brief Dimension tag/exponent pair for a single fundamental dimension.\n///\n/// \\details \n/// The dim class represents a single dimension tag/dimension exponent pair.\n/// That is, @c dim<tag_type,value_type> is a pair where @c tag_type represents the\n/// fundamental dimension being represented and @c value_type represents the \n/// exponent of that fundamental dimension as a @c static_rational. @c tag_type must \n/// be a derived from a specialization of @c base_dimension.\n/// Specialization of the following Boost.MPL metafunctions are provided\n///\n///     - @c mpl::plus for two @c dims\n///     - @c mpl::minus for two @c dims\n///     - @c mpl::negate for a @c dim\n///\n/// These metafunctions all operate on the exponent, and require\n/// that the @c dim operands have the same base dimension tag.\n/// In addition, multiplication and division by @c static_rational\n/// is supported.\n///\n///     - @c mpl::times for a @c static_rational and a @c dim in either order\n///     - @c mpl::divides for a @c static_rational and a @c dim in either order\n///\n/// These metafunctions likewise operate on the exponent only.\ntemplate<typename T,typename V> \nstruct dim\n{\n    typedef dim             type;\n    typedef detail::dim_tag tag;\n    typedef T               tag_type;\n    typedef V               value_type;\n};\n\n} // namespace units\n\n} // namespace boost\n\n#if BOOST_UNITS_HAS_BOOST_TYPEOF\n\n#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()\n\nBOOST_TYPEOF_REGISTER_TEMPLATE(boost::units::dim, 2)\n\n#endif\n\n#ifndef BOOST_UNITS_DOXYGEN\n\nnamespace boost {\n\nnamespace mpl {\n\n// define MPL operators acting on dim<T,V>\n\ntemplate<>\nstruct plus_impl<boost::units::detail::dim_tag,boost::units::detail::dim_tag>\n{\n    template<class T0, class T1>\n    struct apply\n    {\n        BOOST_STATIC_ASSERT((boost::is_same<typename T0::tag_type,typename T1::tag_type>::value == true));\n        typedef boost::units::dim<typename T0::tag_type, typename mpl::plus<typename T0::value_type, typename T1::value_type>::type> type;\n    };\n};\n\ntemplate<>\nstruct minus_impl<boost::units::detail::dim_tag,boost::units::detail::dim_tag>\n{\n    template<class T0, class T1>\n    struct apply\n    {\n        BOOST_STATIC_ASSERT((boost::is_same<typename T0::tag_type,typename T1::tag_type>::value == true));\n        typedef boost::units::dim<typename T0::tag_type, typename mpl::minus<typename T0::value_type, typename T1::value_type>::type> type;\n    };\n};\n\ntemplate<>\nstruct times_impl<boost::units::detail::dim_tag,boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply\n    {\n        typedef boost::units::dim<typename T0::tag_type, typename mpl::times<typename T0::value_type, T1>::type> type;\n    };\n};\n\ntemplate<>\nstruct times_impl<boost::units::detail::static_rational_tag,boost::units::detail::dim_tag>\n{\n    template<class T0, class T1>\n    struct apply\n    {\n        typedef boost::units::dim<typename T1::tag_type, typename mpl::times<T0, typename T1::value_type>::type> type;\n    };\n};\n\ntemplate<>\nstruct divides_impl<boost::units::detail::dim_tag,boost::units::detail::static_rational_tag>\n{\n    template<class T0, class T1>\n    struct apply\n    {\n        typedef boost::units::dim<typename T0::tag_type, typename mpl::divides<typename T0::value_type, T1>::type> type;\n    };\n};\n\ntemplate<>\nstruct divides_impl<boost::units::detail::static_rational_tag,boost::units::detail::dim_tag>\n{\n    template<class T0, class T1>\n    struct apply\n    {\n        typedef boost::units::dim<typename T1::tag_type, typename mpl::divides<T0, typename T1::value_type>::type> type;\n    };\n};\n\ntemplate<>\nstruct negate_impl<boost::units::detail::dim_tag>\n{\n    template<class T0>\n    struct apply\n    {\n        typedef boost::units::dim<typename T0::tag_type,typename mpl::negate<typename T0::value_type>::type> type;\n    };\n};\n\n} // namespace mpl\n\n} // namespace boost\n\n#endif\n\n#endif // BOOST_UNITS_DIM_HPP\n", "meta": {"hexsha": "eb2813139e5eb59877231c15d49b93872be0bad9", "size": 4745, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/units/dim.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/boost/units/dim.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/boost/units/dim.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 28.244047619, "max_line_length": 139, "alphanum_fraction": 0.7051633298, "num_tokens": 1177, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22233196731042748}}
{"text": "#include \"calibrator.hpp\"\n\n\n#include <NaturalNeighbourInterpolator.hpp>\n#include <ChessboardSampling.hpp>\n#include <PlaneFit.hpp>\n#include <resampler.hpp>\n\n#include <boost/thread/thread.hpp>\n#include <boost/bind.hpp>\n\n\n#include <chrono>\n#include <cmath>\n\n#include <map>\n#include <algorithm>\n#include <random>\n#include <unistd.h>\n#include <limits>\n#include <fstream>\n\n#include <string.h> // memset\n\nnamespace{\n\n  template <class T>\n  inline std::string\n  toString(T value)\n  {\n    std::ostringstream stream;\n    stream << value;\n    return stream.str();\n  }\n\n\n  float\n  gauss(float x, float sigma, float mean){\n    return (1.0f/(sigma*sqrt(2.0f * M_PI))) * exp( -0.5f * ((x-mean)/sigma) * ((x-mean)/sigma) );\n  }\n\n\n}\n\n/*static*/ bool Calibrator::using_nni = false;\n\nCalibrator::Calibrator()\n  : m_nni_possible(0)\n{}\n\n\nCalibrator::~Calibrator(){\n  if(m_nni_possible){\n    delete [] m_nni_possible;\n  }\n}\n\nvoid\nCalibrator::postFilterSamples(CalibVolume* cv, std::vector<samplePoint>& sps, const RGBDConfig& cfg, const float post_filter_error_sd, const float post_filter_percentile){\n\n\n  std::vector<float> errors_3D;\n  std::vector<float> errors_2D;\n\n  std::vector<std::pair<float, unsigned>> errors_3D_VK;\n  std::vector<std::pair<float, unsigned>> errors_2D_VK;\n\n\n  const unsigned cv_width = cv->width;\n  const unsigned cv_height = cv->height;\n  const unsigned cv_depth = cv->depth;\n\n  for(unsigned i = 0; i < sps.size(); ++i){\n    \n    const float x = cv_width  *  ( sps[i].tex_depth.u) / cfg.size_d.x;\n    const float y = cv_height *  ( sps[i].tex_depth.v)/ cfg.size_d.y;\n    const float z = cv_depth  *  ( sps[i].depth - cv->min_d)/(cv->max_d - cv->min_d);\n\n    xyz pos = getTrilinear(cv->cv_xyz, cv_width, cv_height, cv_depth, x , y , z );\n    uv  tex = getTrilinear(cv->cv_uv,  cv_width, cv_height, cv_depth, x , y , z );\n\n    const float d_x = sps[i].pos_real[0] - pos.x;\n    const float d_y = sps[i].pos_real[1] - pos.y;\n    const float d_z = sps[i].pos_real[2] - pos.z;\n      \n    const float d_u = sps[i].tex_color.u/cfg.size_rgb.x - tex.u;\n    const float d_v = sps[i].tex_color.v/cfg.size_rgb.y - tex.v;\n\n    const float err_3D(glm::length(glm::vec3(d_x, d_y, d_z)));\n    const float err_2D(glm::length(glm::vec2(d_u * cfg.size_rgb.x, d_v * cfg.size_rgb.y)));\n    errors_3D.push_back(err_3D);\n    errors_2D.push_back(err_2D);\n\n    errors_3D_VK.push_back(std::pair<float, unsigned>(err_3D, i));\n    errors_2D_VK.push_back(std::pair<float, unsigned>(err_2D, i));\n  }\n\n  if(post_filter_error_sd > 0.0){\n    double mean3D, mean2D, sd3D, sd2D;\n    calcMeanSD(errors_3D, mean3D, sd3D);\n    calcMeanSD(errors_2D, mean2D, sd2D);\n\n    unsigned out_3D = 0;\n    const float out_3D_thresh = mean3D + post_filter_error_sd * sd3D;\n    for(const auto& s_id_VK : errors_3D_VK){\n      if(s_id_VK.first > out_3D_thresh){\n\tsps[s_id_VK.second].quality = 0.0;\n\t++out_3D;\n      }\n    }\n    std::cout << \"INFO: Calibrator::postFilterSamples 3D post filter samples and discard samples with << \"\n\t      << post_filter_error_sd << \" << more error than standard deviation: \" << out_3D << std::endl;\n\n    unsigned out_2D = 0;\n    const float out_2D_thresh = mean2D + post_filter_error_sd * sd2D;\n    for(const auto& s_id_VK : errors_2D_VK){\n      if(s_id_VK.first > out_2D_thresh){\n\tsps[s_id_VK.second].quality = 0.0;\n\t++out_2D;\n      }\n    }\n    std::cout << \"INFO: Calibrator::postFilterSamples 2D post filter samples and discard samples with << \"\n\t      << post_filter_error_sd << \" << more error than standard deviation: \" << out_2D << std::endl;  \n  }\n\n  if(post_filter_percentile > 0.0){\n    std::sort(errors_3D_VK.begin(), errors_3D_VK.end());\n    std::reverse(errors_3D_VK.begin(),errors_3D_VK.end());\n    std::sort(errors_2D_VK.begin(), errors_2D_VK.end());\n    std::reverse(errors_2D_VK.begin(),errors_2D_VK.end());\n    const unsigned last_outlier = std::min(sps.size(), size_t(sps.size() * post_filter_percentile));\n    std::cout << \"INFO: Calibrator::postFilterSamples post filter samples, order by error (both, 3D and 2D) and discard \" << post_filter_percentile << \" percentile: \" << last_outlier << std::endl;\n    for(unsigned o_id = 0; o_id < last_outlier; ++o_id){\n      sps[errors_3D_VK[o_id].second].quality = 0.0;\n      sps[errors_2D_VK[o_id].second].quality = 0.0;\n    }\n  }\n}\n\nvoid\nCalibrator::applySamples(CalibVolume* cv, const std::vector<samplePoint>& sps, const RGBDConfig& cfg, unsigned idwneighbours, const char* basefilename, RGBDSensor* sensor, const glm::mat4* eye_d_to_world){\n\n  auto start_time = std::chrono::system_clock::now();\n  //CGAL : build Tree, search 100 neighbors, try NNI of neighbourhood, fallback to IDW small neighborhood\n  std::cout << \"INFO: Calibrator::applySamples applying \" << sps.size()\n\t    << \" for volume using on-the-fly initial calibration: \" << (sensor != 0 ? \"yes\" : \"no\") << std::endl;\n\n  std::vector<nniSample> nnisamples;\n\n  for(unsigned s = 0; s < sps.size(); ++s){\n    \n    if( !(sps[s].quality > 0.0) ){\n      std::cout << \"INFO: calibrator.cpp: skipping sample because quality is zero: \" << sps[s] << std::endl;\n      continue;\n    }\n    nniSample nnis;\n    nnis.quality = sps[s].quality;\n    nnis.s_pos_cs  = sps[s].pos_real;\n\n    nnis.s_pos.x = cv->width *  ( sps[s].tex_depth.u)/ cfg.size_d.x;\n    nnis.s_pos.y = cv->height *  ( sps[s].tex_depth.v)/ cfg.size_d.y;\n    nnis.s_pos.z = cv->depth  *  (sps[s].depth - cv->min_d) / (cv->max_d - cv->min_d);\n    if( !((sps[s].depth > cv->min_d) && (sps[s].depth < cv->max_d)) ){\n      std::cerr << \"ERROR: calibrator.cpp: skipping sample because invalid depth: \" << sps[s] << std::endl;\n      continue;\n    }\n\n\n    // here we will introduce a small error because we have a tri-linear interpolation already in the first stage\n    nnis.s_pos_off = sps[s/*sample point*/].pos_offset; // in world coordinates (metric) \n    nnis.s_tex_off = sps[s/*sample point*/].tex_offset; // normalized between 0...1\n\n    if(0 && sensor && eye_d_to_world /*use on the fly offset computation from initial calibration to avoid above error*/){\n\n      const float depth = sps[s].depth;\n      const float xd = sps[s].tex_depth.u;\n      const float yd = sps[s].tex_depth.v;\n\n      glm::vec3 pos3D_local = sensor->calc_pos_d(xd, yd, depth);\n      glm::vec2 pos2D_rgb   = sensor->calc_pos_rgb(pos3D_local);\n      pos2D_rgb.x /= sensor->config.size_rgb.x;\n      pos2D_rgb.y /= sensor->config.size_rgb.y;\n\n      glm::vec4 pos3D_world = (*eye_d_to_world) * glm::vec4(pos3D_local.x, pos3D_local.y, pos3D_local.z, 1.0);\n\n      xyz pos3D;\n      pos3D.x = pos3D_world.x;\n      pos3D.y = pos3D_world.y;\n      pos3D.z = pos3D_world.z;\n      \n      \n      uv posUV;\n      posUV.u = pos2D_rgb.x;\n      posUV.v = pos2D_rgb.y;\n      std::cout << \"INFO: s_pos_off before: \" << nnis.s_pos_off << std::endl;\n#if 0\n      xyz pos_tmp;\n      xyz pos_tmp_tri = getTrilinear(cv->cv_xyz, cv->width, cv->height, cv->depth,\n\t\t\t\t     nnis.s_pos.x ,nnis.s_pos.y , nnis.s_pos.z );\n      pos_tmp.x = sps[s/*sample point*/].pos_real[0] - pos_tmp_tri.x;\n      pos_tmp.y = sps[s/*sample point*/].pos_real[1] - pos_tmp_tri.y;\n      pos_tmp.z = sps[s/*sample point*/].pos_real[2] - pos_tmp_tri.z;\n#endif\n      //std::cout << \"INFO: s_pos_off with Trilinear: \" << pos_tmp << std::endl;\n      //std::cout << \"INFO: pos_tmp_tri: \" << pos_tmp_tri << std::endl;\n      //std::cout << \"INFO: pos3D_onthefly: \" << pos3D << std::endl;\n      \n      nnis.s_pos_off.x = sps[s/*sample point*/].pos_real[0] - pos3D.x;\n      nnis.s_pos_off.y = sps[s/*sample point*/].pos_real[1] - pos3D.y;\n      nnis.s_pos_off.z = sps[s/*sample point*/].pos_real[2] - pos3D.z;\n      std::cout << \"INFO: s_pos_off after: \" << nnis.s_pos_off << std::endl;\n      uv sps_tex_color_norm = sps[s/*sample point*/].tex_color;\n      sps_tex_color_norm.u /= sensor->config.size_rgb.x;\n      sps_tex_color_norm.v /= sensor->config.size_rgb.y;\n      std::cout << \"INFO: s_tex_off before: \" << nnis.s_tex_off << std::endl;\n      nnis.s_tex_off = sps_tex_color_norm - posUV;\n      std::cout << \"INFO: s_tex_off after: \" << nnis.s_tex_off << std::endl;\n    }\n\n    \n    \n\n\n    //std::cerr << s << \" \" << nnis << std::endl;\n    nnisamples.push_back(nnis);\n  }\n\n  \n  Resampler rsa;\n  rsa.resampleGridBased(nnisamples, cv,\tbasefilename);\n\n#if 0\n  std::cout << \"INFO: initializing nearest neighbor search for border fill \" << nnisamples.size() << \" samples.\" << std::endl;\n  NearestNeighbourSearch nns_before_border_fill(nnisamples);\n  rsa.fillBorder(nnisamples, cv, &nns_before_border_fill, idwneighbours, basefilename);\n  //exit(0);\n#endif\n\n  std::cout << \"INFO: initializing nearest neighbor search for interpolation of calibvolume using \" << nnisamples.size() << \" samples.\" << std::endl;\n  NearestNeighbourSearch nns(nnisamples);\n\n  // init calib volume for natural neighbor interpolation\n  NaturalNeighbourInterpolator* nnip = 0;\n  CalibVolume* cv_nni = 0;\n  if(using_nni){\n    if(m_nni_possible == 0){\n      m_nni_possible = new unsigned char [cv->width * cv->height * cv->depth];\n    }\n    memset(m_nni_possible, 0, cv->width * cv->height * cv->depth);\n    cv_nni = new CalibVolume(cv->width, cv->height, cv->depth, cv->min_d, cv->max_d);\n    std::cout << \"INFO: initializing natural neighbor interpolation for interpolation of calibvolume using \" << nnisamples.size() << \" samples.\" << std::endl;\n    std::shuffle(std::begin(nnisamples), std::end(nnisamples), std::default_random_engine());\n    nnip =   new NaturalNeighbourInterpolator(nnisamples);\n  }\n\n  const unsigned numthreads = 32;\n  std::cout << \"INFO: start interpolation per thread for \" << numthreads << \" threads.\" << std::endl;\n  boost::thread_group threadGroup;\n  for (unsigned tid = 0; tid < numthreads; ++tid){\n    threadGroup.create_thread(boost::bind(&Calibrator::applySamplesPerThread, this, cv, &nns, tid, numthreads, idwneighbours, cv_nni, nnip));\n  }\n  threadGroup.join_all();\n\n  \n  if(using_nni){\n    blendIDW2NNI(cv, cv_nni, basefilename);\n  }\n\n  auto end_time = std::chrono::system_clock::now();\n  std::cout << \"INFO: finished interpolation in \"\n\t    <<  std::chrono::duration_cast<std::chrono::duration<double>>(end_time - start_time).count()\n\t    << \" seconds\" << std::endl;\n\n}\n\n\nvoid\nCalibrator::blendIDW2NNI(CalibVolume* cv, CalibVolume* cv_nni, const char* basefilename){\n\n  std::cerr << \"USING NNI therefore blending IDW into NNI\" << std::endl;\n\n  // print stats for nni_possible and write to volume file\n  size_t possible = 0;\n  for(size_t idx = 0; idx < (cv->width * cv->height * cv->depth); ++idx){\n    possible += m_nni_possible[idx] > 0 ? 1 : 0;\n  }\n  std::cerr << \"natural_neighbor_interpolation_was_possible for: \"\n\t    << possible << \" out of: \" << (cv->width * cv->height * cv->depth)\n\t    << std::endl;\n\n  // 1st pass detect border\n  unsigned char* nni_border = new unsigned char[cv->width * cv->height * cv->depth];\n  memset(nni_border, 0, cv->width * cv->height * cv->depth);\n  const int border_size = 1;\n  for(unsigned z = 0; z < cv->depth; ++z){\n    for(unsigned y = 0; y < cv->height; ++y){\n      for(unsigned x = 0; x < cv->width; ++x){\n\tconst unsigned cv_index = (z * cv->width * cv->height) + (y * cv->width) + x;\n\tif(m_nni_possible[cv_index]){\n\t  bool border = false;\n\t  for(int z_l = std::max(0 , (int(z) - border_size));\n\t      z_l < std::min(int(cv->depth), (int(z) + border_size + 1));\n\t      ++z_l){\n\t    for(int y_l = std::max(0 , (int(y) - border_size));\n\t\ty_l < std::min(int(cv->height), (int(y) + border_size + 1));\n\t\t++y_l){\n\t      for(int x_l = std::max(0 , (int(x) - border_size));\n\t\t  x_l < std::min(int(cv->width), (int(x) + border_size + 1));\n\t\t  ++x_l){\n\t\tconst unsigned cv_index_l = (z_l * cv->width * cv->height) + (y_l * cv->width) + x_l;\n\t\tif(0 == m_nni_possible[cv_index_l]){\n\t\t  border = true;\n\t\t}\n\t      }\n\t    }\n\t  }\n\t  nni_border[cv_index] = border ? 255 : 0;\n\t}\n      }\n    }\n  }\n\n  // 2nd pass blend between NNI and IDW\n  unsigned char* nni_percentage = new unsigned char [cv->width * cv->height * cv->depth];\n  memset(nni_percentage, 0, cv->width * cv->height * cv->depth);\n  const int kernel_size = 8;\n  const float min_dist = 1.0f;\n  const float max_dist = 6.0f;\n\n  for(unsigned z = 0; z < cv->depth; ++z){\n    for(unsigned y = 0; y < cv->height; ++y){\n      for(unsigned x = 0; x < cv->width; ++x){\n\tconst unsigned cv_index = (z * cv->width * cv->height) + (y * cv->width) + x;\n\tif(m_nni_possible[cv_index]){\n\t  float distance_to_border = std::numeric_limits<float>::max();\n\t  glm::vec3 voxel_curr(1.0f * x, 1.0f * y, 1.0f * z);\n\t  for(int z_l = std::max(0 , (int(z) - kernel_size));\n\t      z_l < std::min(int(cv->depth), (int(z) + kernel_size + 1));\n\t      ++z_l){\n\t    for(int y_l = std::max(0 , (int(y) - kernel_size));\n\t\ty_l < std::min(int(cv->height), (int(y) + kernel_size + 1));\n\t\t++y_l){\n\t      for(int x_l = std::max(0 , (int(x) - kernel_size));\n\t\t  x_l < std::min(int(cv->width), (int(x) + kernel_size + 1));\n\t\t  ++x_l){\n\t\tconst unsigned cv_index_l = (z_l * cv->width * cv->height) + (y_l * cv->width) + x_l;\n\t\tif(nni_border[cv_index_l] > 0){\n\t\t  distance_to_border = std::min(distance_to_border,\n\t\t\t\t\t\tglm::length(voxel_curr - glm::vec3(1.0f * x_l, 1.0f * y_l, 1.0f * z_l)));\n\t\t}\n\t      }\n\t    }\n\t  }\n  \n\t  const float t_blend = std::min( max_dist, std::max(min_dist, distance_to_border)) / max_dist;\n\t  if(t_blend > 1.0f || t_blend < 0.0f){\n\t    std::cerr << \"ERROR: invalid t_blend: \" << t_blend << std::endl;\n\t    exit(0);\n\t  }\n\n\t  nni_percentage[cv_index] = (unsigned char) std::max(0.0f, std::min(255.0f, 255.0f * t_blend));\n\t  const xyz xyz_idw = cv->cv_xyz[cv_index];\n\t  const xyz xyz_nni = cv_nni->cv_xyz[cv_index];\n\t  \n\t  const uv uv_idw = cv->cv_uv[cv_index];\n\t  const uv uv_nni = cv_nni->cv_uv[cv_index];\n\t  \n\t  cv->cv_xyz[cv_index] = interpolate(xyz_idw, xyz_nni, t_blend);\n\t  cv->cv_uv[cv_index]  = interpolate(uv_idw , uv_nni , t_blend);\n\n\t}\n      }\n    }\n  }\n\n\n  std::cerr << \"writing \" << (std::string(basefilename) + \"_nnistats\").c_str() << std::endl;\n  FILE* f_nni_stats = fopen((std::string(basefilename) + \"_nnistats\").c_str(), \"wb\");\n  fwrite(m_nni_possible, sizeof(unsigned char), (cv->width * cv->height * cv->depth), f_nni_stats);\n  fclose(f_nni_stats);\n\n\n  std::cerr << \"writing \" << (std::string(basefilename) + \"_nniborder\").c_str() << std::endl;\n  FILE* f_nni_border = fopen((std::string(basefilename) + \"_nniborder\").c_str(), \"wb\");\n  fwrite(nni_border, sizeof(unsigned char), (cv->width * cv->height * cv->depth), f_nni_border);\n  fclose(f_nni_border);\n  \n  std::cerr << \"writing \" << (std::string(basefilename) + \"_percentage\").c_str() << std::endl;\n  FILE* f_nni_percentage = fopen((std::string(basefilename) + \"_percentage\").c_str(), \"wb\");\n  fwrite(nni_percentage, sizeof(unsigned char), (cv->width * cv->height * cv->depth), f_nni_percentage);\n  fclose(f_nni_percentage);\n\n\n  delete [] nni_border;\n  delete [] nni_percentage;\n\n}\n\nvoid\nCalibrator::evaluateSamples(CalibVolume* cv, std::vector<samplePoint>& sps, const RGBDConfig& cfg, const char* basefilename, bool isnni, bool create_error_vis){\n\n  unsigned char* cv_nnistats = 0;\n  unsigned nni_valids = 0;\n  if(isnni){\n    cv_nnistats = new unsigned char [cv->width * cv->height * cv->depth];\n    // load .cv_nnistats if nni has to be evaluated\n    FILE* f_nni_stats = fopen((std::string(basefilename) + \"_nnistats\").c_str(), \"rb\");\n    fread(cv_nnistats, sizeof(unsigned char), (cv->width * cv->height * cv->depth), f_nni_stats);\n    fclose(f_nni_stats);\n  }\n\n  std::vector<nniSample> nnisamples_error_vol;\n\n  std::vector<float> errors_3D;\n  std::vector<float> errors_2D;\n  float max_3D = std::numeric_limits<float>::lowest();\n  float max_2D = std::numeric_limits<float>::lowest();\n\n\n  // ranges in depth 0.5-1.25 1.25-2.0 2.0-3.0\n  const float range_A_start = 0.5;\n  const float range_A_end   = 1.25;\n  float range_A_max_3D = std::numeric_limits<float>::lowest();\n  float range_A_max_2D = std::numeric_limits<float>::lowest();\n  std::vector<float> range_A_errors_3D;\n  std::vector<float> range_A_errors_2D;\n\n  const float range_B_start = 1.25;\n  const float range_B_end   = 2.0;\n  float range_B_max_3D = std::numeric_limits<float>::lowest();\n  float range_B_max_2D = std::numeric_limits<float>::lowest();\n  std::vector<float> range_B_errors_3D;\n  std::vector<float> range_B_errors_2D;\n\n  const float range_C_start = 2.0;\n  const float range_C_end   = 3.0;\n  float range_C_max_3D = std::numeric_limits<float>::lowest();\n  float range_C_max_2D = std::numeric_limits<float>::lowest();\n  std::vector<float> range_C_errors_3D;\n  std::vector<float> range_C_errors_2D;\n\n  unsigned num_skipped_due_quality = 0;\n  for(unsigned i = 0; i < sps.size(); ++i){\n\n    if(!(sps[i].quality > 0.0)){\n      ++num_skipped_due_quality;\n      continue;\n    }\n\n    const unsigned cv_width = cv->width;\n    const unsigned cv_height = cv->height;\n    const unsigned cv_depth = cv->depth;\n\n    const float x = cv_width  *  ( sps[i].tex_depth.u) / cfg.size_d.x;\n    const float y = cv_height *  ( sps[i].tex_depth.v)/ cfg.size_d.y;\n    const float z = cv_depth  *  ( sps[i].depth - cv->min_d)/(cv->max_d - cv->min_d);\n\n\n    if(isnni){\n      const unsigned cv_index000 = (std::floor(z) * cv_width * cv_height) + (std::floor(y) * cv_width) + std::floor(x);\n      const unsigned cv_index001 = (std::floor(z) * cv_width * cv_height) + (std::floor(y) * cv_width) + std::ceil(x);\n      const unsigned cv_index010 = (std::floor(z) * cv_width * cv_height) + (std::ceil(y) * cv_width) + std::floor(x);\n      const unsigned cv_index011 = (std::floor(z) * cv_width * cv_height) + (std::ceil(y) * cv_width) + std::ceil(x);\n      const unsigned cv_index100 = (std::ceil(z) * cv_width * cv_height) + (std::floor(y) * cv_width) + std::floor(x);\n      const unsigned cv_index101 = (std::ceil(z) * cv_width * cv_height) + (std::floor(y) * cv_width) + std::ceil(x);\n      const unsigned cv_index110 = (std::ceil(z) * cv_width * cv_height) + (std::ceil(y) * cv_width) + std::floor(x);\n      const unsigned cv_index111 = (std::ceil(z) * cv_width * cv_height) + (std::ceil(y) * cv_width) + std::ceil(x);\n      bool nni_valid  = ( cv_nnistats[cv_index000]\n\t\t\t  && cv_nnistats[cv_index001]\n\t\t\t  && cv_nnistats[cv_index010]\n\t\t\t  && cv_nnistats[cv_index011]\n\t\t\t  && cv_nnistats[cv_index100]\n\t\t\t  && cv_nnistats[cv_index101]\n\t\t\t  && cv_nnistats[cv_index110]\n\t\t\t  && cv_nnistats[cv_index111]);\n      if(!nni_valid){\n\tcontinue;\n      }\n      else{\n\t++nni_valids;\n      }\n    }\n\n\n    xyz pos = getTrilinear(cv->cv_xyz, cv_width, cv_height, cv_depth, x , y , z );\n    uv  tex = getTrilinear(cv->cv_uv,  cv_width, cv_height, cv_depth, x , y , z );\n\n    sps[i].pos_offset.x = sps[i].pos_real[0] - pos.x;\n    sps[i].pos_offset.y = sps[i].pos_real[1] - pos.y;\n    sps[i].pos_offset.z = sps[i].pos_real[2] - pos.z;\n      \n    sps[i].tex_offset.u = sps[i].tex_color.u/cfg.size_rgb.x - tex.u;\n    sps[i].tex_offset.v = sps[i].tex_color.v/cfg.size_rgb.y - tex.v;\n\n    sps[i].quality = 1.0f;\n\n    const float err_3D(glm::length(glm::vec3(sps[i].pos_offset.x,sps[i].pos_offset.y,sps[i].pos_offset.z)));\n    const float err_2D(glm::length(glm::vec3(sps[i].tex_offset.u * cfg.size_rgb.x,\n\t\t\t\t\t      sps[i].tex_offset.v * cfg.size_rgb.y,0.0)));\n\n\n    // only track if sample is inside sweet bbx \n    const glm::vec3 sweet_min(-0.6, 0.0, -0.6);\n    const glm::vec3 sweet_max( 0.6, 1.9,  0.6);\n    if(sps[i].pos_real[0] > sweet_min[0] &&\n       sps[i].pos_real[1] > sweet_min[1] &&\n       sps[i].pos_real[2] > sweet_min[2] &&\n\n       sps[i].pos_real[0] < sweet_max[0] &&\n       sps[i].pos_real[1] < sweet_max[1] &&\n       sps[i].pos_real[2] < sweet_max[2]){\n\n      errors_3D.push_back(err_3D);\n      errors_2D.push_back(err_2D);\n   \n      max_3D = std::max(max_3D, err_3D);\n      max_2D = std::max(max_2D, err_2D);\n\n      // track local error for volume vis\n      nniSample nnis;\n      nnis.s_tex_off.u = err_3D;\n      nnis.s_tex_off.v = err_2D;\n      \n      nnis.s_pos.x = x;\n      nnis.s_pos.y = y;\n      nnis.s_pos.z = z;\n      \n      nnisamples_error_vol.push_back(nnis);\n    }\n\n\n    if(range_A_start < sps[i].depth &&\n       range_A_end >=  sps[i].depth){\n      range_A_errors_3D.push_back(err_3D);\n      range_A_errors_2D.push_back(err_2D);\n      range_A_max_3D = std::max(range_A_max_3D, err_3D);\n      range_A_max_2D = std::max(range_A_max_2D, err_2D);\n    }\n    else if(range_B_start < sps[i].depth &&\n       range_B_end >=  sps[i].depth){\n      range_B_errors_3D.push_back(err_3D);\n      range_B_errors_2D.push_back(err_2D);\n      range_B_max_3D = std::max(range_B_max_3D, err_3D);\n      range_B_max_2D = std::max(range_B_max_2D, err_2D);\n    }\n    else if(range_C_start < sps[i].depth &&\n       range_C_end >=  sps[i].depth){\n      range_C_errors_3D.push_back(err_3D);\n      range_C_errors_2D.push_back(err_2D);\n      range_C_max_3D = std::max(range_C_max_3D, err_3D);\n      range_C_max_2D = std::max(range_C_max_2D, err_2D);\n    }\n    else{\n      ;//std::cout << \"ERROR: not in range: \" << sps[i].depth << std::endl;\n    }\n\n  }\n\n  std::cout << \"Calibrator::evaluateSamples INFO: skipped due to quality is zero: \" << num_skipped_due_quality << std::endl;\n\n  double mean3D, mean2D, sd3D, sd2D;\n  calcMeanSD(errors_3D, mean3D, sd3D);\n  calcMeanSD(errors_2D, mean2D, sd2D);\n  std::cout << \"---------------------------------------------------------\" << std::endl;\n  std::cout << \"Evaluation of ground truth samples: \" << errors_3D.size() << std::endl;\n  std::cout << \"mean_error_3D: \" << mean3D * 1000 << \" (\" << sd3D * 1000 << \") [\" << max_3D * 1000 << \"] (in millimeter)\" << std::endl;\n  std::cout << \"mean_error_2D: \" << mean2D << \" (\" << sd2D << \") [\" << max_2D << \"] (in pixels)\" << std::endl;\n  if(isnni){\n    std::cout << \"Calibrator::evaluateSamples INFO: could evaluate based on natural neighbour interpolation: \" << nni_valids << \" samples from \" << sps.size() << std::endl;\n  }\n  else{\n    std::cout << \"Calibrator::evaluateSamples INFO: natural neighbour based evalution is turned off\" << std::endl;\n  }\n\n  if(create_error_vis){\n    createErrorVis(nnisamples_error_vol, cv->width, cv->height, cv->depth, basefilename, isnni);\n  }\n\n\n  double range_A_mean3D, range_A_mean2D, range_A_sd3D, range_A_sd2D;\n  calcMeanSD(range_A_errors_3D, range_A_mean3D, range_A_sd3D);\n  calcMeanSD(range_A_errors_2D, range_A_mean2D, range_A_sd2D);\n  std::cout << \"---------------------------------------------------------\" << std::endl;\n  std::cout << \"(\" << range_A_start << \"m, \" << range_A_end << \"m]\" << std::endl;\n  std::cout << \"Evaluation of ground truth samples range_A: \" << range_A_errors_3D.size() << std::endl;\n  std::cout << \"range_A_mean_error_3D: \" << range_A_mean3D * 1000 << \" (\" << range_A_sd3D * 1000 << \") [\" << range_A_max_3D * 1000 << \"] (in millimeter)\" << std::endl;\n  std::cout << \"range_A_mean_error_2D: \" << range_A_mean2D << \" (\" << range_A_sd2D << \") [\" << range_A_max_2D << \"] (in pixels)\" << std::endl;\n\n  double range_B_mean3D, range_B_mean2D, range_B_sd3D, range_B_sd2D;\n  calcMeanSD(range_B_errors_3D, range_B_mean3D, range_B_sd3D);\n  calcMeanSD(range_B_errors_2D, range_B_mean2D, range_B_sd2D);\n  std::cout << \"---------------------------------------------------------\" << std::endl;\n  std::cout << \"(\" << range_B_start << \"m, \" << range_B_end << \"m]\" << std::endl;\n  std::cout << \"Evaluation of ground truth samples range_B: \" << range_B_errors_3D.size() << std::endl;\n  std::cout << \"range_B_mean_error_3D: \" << range_B_mean3D * 1000 << \" (\" << range_B_sd3D * 1000 << \") [\" << range_B_max_3D * 1000 << \"] (in millimeter)\" << std::endl;\n  std::cout << \"range_B_mean_error_2D: \" << range_B_mean2D << \" (\" << range_B_sd2D << \") [\" << range_B_max_2D << \"] (in pixels)\" << std::endl;\n\n  double range_C_mean3D, range_C_mean2D, range_C_sd3D, range_C_sd2D;\n  calcMeanSD(range_C_errors_3D, range_C_mean3D, range_C_sd3D);\n  calcMeanSD(range_C_errors_2D, range_C_mean2D, range_C_sd2D);\n  std::cout << \"---------------------------------------------------------\" << std::endl;\n  std::cout << \"(\" << range_C_start << \"m, \" << range_C_end << \"m]\" << std::endl;\n  std::cout << \"Evaluation of ground truth samples range_C: \" << range_C_errors_3D.size() << std::endl;\n  std::cout << \"range_C_mean_error_3D: \" << range_C_mean3D * 1000 << \" (\" << range_C_sd3D * 1000 << \") [\" << range_C_max_3D * 1000 << \"] (in millimeter)\" << std::endl;\n  std::cout << \"range_C_mean_error_2D: \" << range_C_mean2D << \" (\" << range_C_sd2D << \") [\" << range_C_max_2D << \"] (in pixels)\" << std::endl;\n\n  std::cout << \"---------------------------------------------------------\" << std::endl;\n\n#if 0 // this is used to print for automatic gnu plot stuff related to paper evaluation\n  // 0.0 (0.0)[0.0] & 0.0 (0.0)[0.0]\n  std::cout << std::setprecision(3) << mean3D * 1000 << \" (\" << sd3D * 1000 << \") [\" << max_3D * 1000 << \"] & \" << mean2D << \" (\" << sd2D << \") [\" << max_2D << \"]\" << std::endl;\n  std::cout << (range_A_errors_3D.size() > 0 ? range_A_mean3D * 1000 : 0.0) << std::endl;\n  std::cout << (range_A_errors_3D.size() > 0 ? range_A_sd3D * 1000 : 0.0) << std::endl;\n  std::cout << (range_A_errors_2D.size() > 0 ? range_A_mean2D : 0.0) << std::endl;\n  std::cout << (range_A_errors_2D.size() > 0 ? range_A_sd2D : 0.0) << std::endl;\n\n  std::cout << (range_B_errors_3D.size() > 0 ? range_B_mean3D * 1000 : 0.0) << std::endl;\n  std::cout << (range_B_errors_3D.size() > 0 ? range_B_sd3D * 1000 : 0.0) << std::endl;\n  std::cout << (range_B_errors_2D.size() > 0 ? range_B_mean2D : 0.0) << std::endl;\n  std::cout << (range_B_errors_2D.size() > 0 ? range_B_sd2D : 0.0) << std::endl;\n\n  std::cout << (range_C_errors_3D.size() > 0 ? range_C_mean3D * 1000 : 0.0) << std::endl;\n  std::cout << (range_C_errors_3D.size() > 0 ? range_C_sd3D * 1000 : 0.0) << std::endl;\n  std::cout << (range_C_errors_2D.size() > 0 ? range_C_mean2D : 0.0) << std::endl;\n  std::cout << (range_C_errors_2D.size() > 0 ? range_C_sd2D : 0.0) << std::endl;\n#endif\n\n}\n\nvoid\nCalibrator::createErrorVis(const std::vector<nniSample>& sps, const unsigned width, const unsigned height, const unsigned depth, const char* basefilename, bool isnni){\n\n  // create volumes for world and texture coordinates\n  unsigned char* error_vol_3D = new unsigned char [width * height * depth];\n  memset(error_vol_3D, 0, width * height * depth);\n  \n  unsigned char* error_vol_2D = new unsigned char [width * height * depth];\n  memset(error_vol_2D, 0, width * height * depth);\n\n  unsigned char* error_vol_3D_nni = new unsigned char [width * height * depth];\n  memset(error_vol_3D_nni, 0, width * height * depth);\n  \n  unsigned char* error_vol_2D_nni = new unsigned char [width * height * depth];\n  memset(error_vol_2D_nni, 0, width * height * depth);\n\n  \n  NearestNeighbourSearch nns(sps);\n  std::vector<nniSample> sps_tmp(sps);\n  std::shuffle(std::begin(sps_tmp), std::end(sps_tmp), std::default_random_engine());\n  NaturalNeighbourInterpolator nnip(sps_tmp);\n\n\n  // boost threads here\n  const unsigned numthreads = 32;\n  //std::cerr << \"start interpolation of error visualization volumes using \" << numthreads << \" threads.\" << std::endl;\n  boost::thread_group threadGroup;\n  for (unsigned tid = 0; tid < numthreads; ++tid){\n    //threadGroup.create_thread(boost::bind(&Calibrator::applyErrorVisPerThread, this, width, height, depth,\n    //\t\t\t\t\t  error_vol_3D, error_vol_2D, error_vol_3D_nni, error_vol_2D_nni, &nns, &nnip, tid, numthreads));\n    threadGroup.create_thread([width, height, depth,\n\t\t\t       error_vol_3D, error_vol_2D, error_vol_3D_nni, error_vol_2D_nni, &nns, &nnip, tid, numthreads, this](){\n\t\t\t\tthis->applyErrorVisPerThread(width, height, depth,\n\t\t\t\t\t\t\t     error_vol_3D, error_vol_2D, error_vol_3D_nni, error_vol_2D_nni, &nns, &nnip, tid, numthreads);\n\t\t\t      });\n  }\n  threadGroup.join_all();\n\n  \n  //std::cout << \"INFO: writing \" << (std::string(basefilename) + \"_error3D_idw\").c_str()<< std::endl;\n  FILE* f_error_vol_3D = fopen((std::string(basefilename) + \"_error3D_idw\").c_str(), \"wb\");\n  fwrite(error_vol_3D, sizeof(unsigned char), (width * height * depth), f_error_vol_3D);\n  fclose(f_error_vol_3D);\n\n  //std::cout << \"INFO: writing \" << (std::string(basefilename) + \"_error2D_idw\").c_str()<< std::endl;\n  FILE* f_error_vol_2D = fopen((std::string(basefilename) + \"_error2D_idw\").c_str(), \"wb\");\n  fwrite(error_vol_2D, sizeof(unsigned char), (width * height * depth), f_error_vol_2D);\n  fclose(f_error_vol_2D);\n\n  if(isnni){\n    //std::cout << \"INFO: writing \" << (std::string(basefilename) + \"_error3D_nni\").c_str()<< std::endl;\n    FILE* f_error_vol_3Dnni = fopen((std::string(basefilename) + \"_error3D_nni\").c_str(), \"wb\");\n    fwrite(error_vol_3D_nni, sizeof(unsigned char), (width * height * depth), f_error_vol_3Dnni);\n    fclose(f_error_vol_3Dnni);\n\n    //std::cout << \"INFO: writing \" << (std::string(basefilename) + \"_error2D_nni\").c_str()<< std::endl;\n    FILE* f_error_vol_2Dnni = fopen((std::string(basefilename) + \"_error2D_nni\").c_str(), \"wb\");\n    fwrite(error_vol_2D_nni, sizeof(unsigned char), (width * height * depth), f_error_vol_2Dnni);\n    fclose(f_error_vol_2Dnni);\n  }\n}\n\n\nvoid\nCalibrator::applyErrorVisPerThread(const unsigned width, const unsigned height, const unsigned depth,\n\t\t\t\t   unsigned char* error_vol_3D, unsigned char* error_vol_2D,\n\t\t\t\t   unsigned char* error_vol_3D_nni, unsigned char* error_vol_2D_nni,\n\t\t\t\t   const NearestNeighbourSearch* nns, const NaturalNeighbourInterpolator* nnip,\n\t\t\t\t   const unsigned tid, const unsigned numthreads){\n\n  const unsigned idwneighbours = 20;\n  const glm::vec3 diameter(width, height, depth);\n  const float max_influence_dist = glm::length(diameter);\n  const float max_error_3D_vol = 0.01; // 5cm\n  const float max_error_2D_vol = 2.0; // 5 pixel\n\n  for(unsigned z = tid; z < depth; z += numthreads){\n    for(unsigned y = 0; y < height; ++y){\n      for(unsigned x = 0; x < width; ++x){\n\t\n\tconst unsigned cv_index = (z * width * height) + (y * width) + x;\n\t\n\tnniSample ipolant;\n\tipolant.s_pos.x = x;\n\tipolant.s_pos.y = y;\n\tipolant.s_pos.z = z;\n\t\n\tipolant.s_pos_off.x = 0.0;\n\tipolant.s_pos_off.y = 0.0;\n\tipolant.s_pos_off.z = 0.0;\n\t\n\tipolant.s_tex_off.u = 0.0;\n\tipolant.s_tex_off.v = 0.0;\n\t\n\tstd::vector<nniSample> neighbours = nns->search(ipolant,idwneighbours);\n\tif(neighbours.empty()){\n\t  //std::cerr << \"ERROR in Calibrator::applySamplesPerThread -> no neighbours found, skipping voxel at pos \" << ipolant.s_pos << std::endl;\n\t  continue;\n\t}\n\tidw_interpolate(neighbours, idwneighbours, ipolant, max_influence_dist);\n\n\t// s_tex_off.u -> 3D error\n\terror_vol_3D[cv_index] = (unsigned char) (std::max(0.0f,\n\t\t\t\t\t\t\t   std::min(ipolant.s_tex_off.u, max_error_3D_vol))\n\t\t\t\t\t\t  * 255.0f/max_error_3D_vol);\n\t// s_tex_off.v -> 2D error\n\terror_vol_2D[cv_index] = (unsigned char) (std::max(0.0f,\n\t\t\t\t\t\t\t   std::min(ipolant.s_tex_off.v, max_error_2D_vol))\n\t\t\t\t\t\t  * 255.0f/max_error_2D_vol);\n\n\n\t{\n\t  nniSample ipolant_nni;\n\t  ipolant_nni.s_pos.x = x;\n\t  ipolant_nni.s_pos.y = y;\n\t  ipolant_nni.s_pos.z = z;\n\t  \n\t  ipolant_nni.s_pos_off.x = 0.0;\n\t  ipolant_nni.s_pos_off.y = 0.0;\n\t  ipolant_nni.s_pos_off.z = 0.0;\n\t  \n\t  ipolant_nni.s_tex_off.u = 0.0;\n\t  ipolant_nni.s_tex_off.v = 0.0;\n\n\t  bool nni_valid = nnip->interpolate(ipolant_nni);\n\t  if(nni_valid){\n\t    // s_tex_off.u -> 3D error\n\t    error_vol_3D_nni[cv_index] = (unsigned char) (std::max(0.0f,\n\t\t\t\t\t\t\t\t   std::min(ipolant_nni.s_tex_off.u, max_error_3D_vol))\n\t\t\t\t\t\t\t  * 255.0f/max_error_3D_vol);\n\t    // s_tex_off.v -> 2D error\n\t    error_vol_2D_nni[cv_index] = (unsigned char) (std::max(0.0f,\n\t\t\t\t\t\t\t\t   std::min(ipolant_nni.s_tex_off.v, max_error_2D_vol))\n\t\t\t\t\t\t\t  * 255.0f/max_error_2D_vol);\n\t  }\n\n\t}\n\n\n      }\n    }\n  }\n  \n}\n\n\n\n\n\ndouble\nCalibrator::evaluatePlanes(CalibVolume* cv, ChessboardSampling* cbs, const RGBDConfig& cfg, unsigned stride){\n\n  const unsigned cv_width = cv->width;\n  const unsigned cv_height = cv->height;\n  const unsigned cv_depth = cv->depth;\n\n\n  std::vector<double> plane_qualities;\n  const std::vector<ChessboardRange>& valid_ranges = cbs->getValidRanges();\n  const std::vector<ChessboardViewIR>& cb_irs = cbs->getIRs();\n  for(const auto& r : valid_ranges){\n    for(unsigned cb_id = r.start; cb_id != r.end; ++cb_id){\n      if((cb_id % stride) == 0){\n\tstd::vector<xyz> world_space_corners;\n\tfor(unsigned idx = 0; idx < (CB_WIDTH * CB_HEIGHT); ++idx){\n\t  if(cb_irs[cb_id].quality[idx] > 0.0){\n\t    const xyz corner = cb_irs[cb_id].corners[idx];\n\t    const float x = cv_width  *  ( corner.x)/ cfg.size_d.x;\n\t    const float y = cv_height *  ( corner.y)/ cfg.size_d.y;\n\t    const float z = cv_depth  *  ( corner.z - cv->min_d)/(cv->max_d - cv->min_d);\n\t    xyz pos = getTrilinear(cv->cv_xyz, cv_width, cv_height, cv_depth, x , y , z );\n\t  \n\t    pos.x *= 10;\n\t    pos.y *= 10;\n\t    pos.z *= 10;\n\t  \n\t    world_space_corners.push_back(pos);\n\t  }\n\t}\n\t\n\tconst auto pq = detectPlaneQuality(world_space_corners);\n\t//std::cout << \"cb_id: \" << cb_id << \" -> \" << pq << std::endl;\n\tplane_qualities.push_back(pq);\n      }\n\n    }\n  }\n  \n  double mean;\n  double sd;\n  calcMeanSD(plane_qualities, mean, sd);\n\n  return mean;\n}\n\n\ndouble\nCalibrator::evaluate3DError(CalibVolume* cv, ChessboardSampling* cbs, const Checkerboard* cb, const RGBDConfig& cfg, float delta_t_pose, unsigned stride){\n\n  const unsigned cv_width = cv->width;\n  const unsigned cv_height = cv->height;\n  const unsigned cv_depth = cv->depth;\n\n\n  std::vector<double> errors_3D;\n  const std::vector<ChessboardRange>& valid_ranges = cbs->getValidRanges();\n  const std::vector<ChessboardViewIR>& cb_irs = cbs->getIRs();\n\n  for(const auto& r : valid_ranges){\n    for(unsigned cb_id = r.start; cb_id != r.end; ++cb_id){\n\n      if((cb_id % stride) == 0){\n\n\tconst double time = cb_irs[cb_id].time;\n\t// retrieve chessboards_pose\n\tbool valid_pose = false;\n\tglm::mat4 cb_transform = cbs->interpolatePose(time + delta_t_pose, valid_pose);\n\tif(!valid_pose){\n\t  continue;\n\t}\n\n\n\tstd::vector<double> cb_errors_3D;\n\tfor(unsigned idx = 0; idx < (CB_WIDTH * CB_HEIGHT); ++idx){\n\n\t  // calculate calibrated position\n\t  if(cb_irs[cb_id].quality[idx] > 0.0){\n\t    const xyz corner = cb_irs[cb_id].corners[idx];\n\t    const float x = cv_width  *  ( corner.x)/ cfg.size_d.x;\n\t    const float y = cv_height *  ( corner.y)/ cfg.size_d.y;\n\t    const float z = cv_depth  *  ( corner.z - cv->min_d)/(cv->max_d - cv->min_d);\n\t    xyz pos = getTrilinear(cv->cv_xyz, cv_width, cv_height, cv_depth, x , y , z );\n\t    glm::vec3 pos_calib(pos.x,pos.y,pos.z);\n\t    // calculate ground truth position\n\t    glm::vec4 pos_realH = (cb->pose_offset * cb_transform) * glm::vec4(cb->points_local[idx].x,\n\t\t\t\t\t\t\t\t\t       cb->points_local[idx].y,\n\t\t\t\t\t\t\t\t\t       cb->points_local[idx].z, 1.0f);\n\t    glm::vec3 pos_gt = glm::vec3(pos_realH.x, pos_realH.y, pos_realH.z);\n\n\t    cb_errors_3D.push_back(glm::length(pos_calib - pos_gt));\n\t  }\n\t}\n\n\tdouble cb_mean;\n\tdouble cb_sd;\n\tcalcMeanSD(cb_errors_3D, cb_mean, cb_sd);\n\terrors_3D.push_back(cb_mean);\n      }\n\n    }\n  }\n\n\n  double mean;\n  double sd;\n  calcMeanSD(errors_3D, mean, sd);\n\n  return mean;\n\n}\n\n\ndouble\nCalibrator::evaluate2DError(CalibVolume* cv, ChessboardSampling* cbs, const RGBDConfig& cfg, float delta_t_color, unsigned stride){\n\n\n  const unsigned cv_width = cv->width;\n  const unsigned cv_height = cv->height;\n  const unsigned cv_depth = cv->depth;\n\n\n  std::vector<double> errors_2D;\n  const std::vector<ChessboardRange>& valid_ranges = cbs->getValidRanges();\n  const std::vector<ChessboardViewIR>& cb_irs = cbs->getIRs();\n\n  for(const auto& r : valid_ranges){\n    for(unsigned cb_id = r.start; cb_id != r.end; ++cb_id){\n\n      if((cb_id % stride) == 0){\n\n\tconst double time = cb_irs[cb_id].time;\n\t// retrieve color chessboard view\n\tbool valid_color = false;\n\tChessboardViewRGB cb_rgb_i = cbs->interpolateRGB(time + delta_t_color, valid_color);\n\tif(!valid_color){\n\t  continue;\n\t}\n\n\n\tstd::vector<double> cb_errors_2D;\n\tfor(unsigned idx = 0; idx < (CB_WIDTH * CB_HEIGHT); ++idx){\n\n\t  // look up calibrated color coordinate\n\t  if(cb_irs[cb_id].quality[idx] > 0.0){\n\t    const xyz corner = cb_irs[cb_id].corners[idx];\n\t    const float x = cv_width  *  ( corner.x)/ cfg.size_d.x;\n\t    const float y = cv_height *  ( corner.y)/ cfg.size_d.y;\n\t    const float z = cv_depth  *  ( corner.z - cv->min_d)/(cv->max_d - cv->min_d);\n\n\t    // normalized\n\t    uv  cc_calib = getTrilinear(cv->cv_uv, cv_width, cv_height, cv_depth, x , y , z );\n\t    // renormalize\n\t    glm::vec2 cc_calib_pixel(cc_calib.u * cfg.size_rgb.x, cc_calib.v * cfg.size_rgb.y);\n\n\t    // retrieve ground truth color coordinate, already in pixels\n\t    uv  cc_gt(cb_rgb_i.corners[idx]);\n\t    glm::vec2 cc_gt_pixel(cc_gt.u, cc_gt.v);\n#if 0\n\t    std::cerr << \"cb_id: \" << cb_id << \" corner idx: \" << idx\n\t\t      << \" cc_calib_pixel -> cc_gt_pixel: \"\n\t\t      << cc_calib_pixel[0] << \", \" << cc_calib_pixel[1] << \" -> \"\n\t\t      << cc_gt_pixel[0] << \", \" << cc_gt_pixel[1] << std::endl;\n#endif\n\t    cb_errors_2D.push_back(glm::length(cc_calib_pixel - cc_gt_pixel));\n\t  }\n\t}\n\n\tdouble cb_mean;\n\tdouble cb_sd;\n\tcalcMeanSD(cb_errors_2D, cb_mean, cb_sd);\n\terrors_2D.push_back(cb_mean);\n      }\n\n    }\n  }\n\n\n  double mean;\n  double sd;\n  calcMeanSD(errors_2D, mean, sd);\n\n  return mean;\n\n}\n\n\nvoid\nCalibrator::applySamplesPerThread(CalibVolume* cv, const NearestNeighbourSearch* nns, unsigned tid, unsigned numthreads, unsigned idwneighbours, CalibVolume* cv_nni, const NaturalNeighbourInterpolator* nnip){\n\n\n  const glm::vec3 diameter(cv->width, cv->height, cv->depth);\n  const float max_influence_dist = glm::length(diameter);\n\n  const unsigned cv_width  = cv->width;\n  const unsigned cv_height = cv->height;\n  const unsigned cv_depth  = cv->depth;\n    //unsigned having = 0;  \n    for(unsigned z = tid; z < cv_depth; z += numthreads){\n      //std::cerr << \"tid: having \" << ++having << \" from \" << cv_depth / numthreads <<  std::endl;\n      for(unsigned y = 0; y < cv_height; ++y){\n\tfor(unsigned x = 0; x < cv_width; ++x){\n\t  \n\t  const unsigned cv_index = (z * cv_width * cv_height) + (y * cv_width) + x;\n\n\t  nniSample ipolant;\n\t  ipolant.s_pos.x = x;\n\t  ipolant.s_pos.y = y;\n\t  ipolant.s_pos.z = z;\n\t  \n\t  ipolant.s_pos_off.x = 0.0;\n\t  ipolant.s_pos_off.y = 0.0;\n\t  ipolant.s_pos_off.z = 0.0;\n\n\t  ipolant.s_tex_off.u = 0.0;\n\t  ipolant.s_tex_off.v = 0.0;\n\t  \n\t  std::vector<nniSample> neighbours = nns->search(ipolant,idwneighbours);\n\t  if(neighbours.empty()){\n\t    std::cerr << \"ERROR in Calibrator::applySamplesPerThread -> no neighbours found, skipping voxel at pos \" << ipolant.s_pos << std::endl;\n\t    continue;\n\t  }\n\t  idw_interpolate(neighbours, idwneighbours, ipolant, max_influence_dist);\n\n\t  const xyz xyz_curr = cv->cv_xyz[cv_index];\n\t  const uv  uv_curr  = cv->cv_uv[cv_index];\n\n\t  cv->cv_xyz[cv_index] = cv->cv_xyz[cv_index] + ipolant.s_pos_off;\n\t  cv->cv_uv[cv_index]  = cv->cv_uv[cv_index]  + ipolant.s_tex_off;\n\t  \n\t  if(using_nni){\n\t    nniSample ipolant_nni;\n\t    ipolant_nni.s_pos.x = x;\n\t    ipolant_nni.s_pos.y = y;\n\t    ipolant_nni.s_pos.z = z;\n\t    \n\t    ipolant_nni.s_pos_off.x = 0.0;\n\t    ipolant_nni.s_pos_off.y = 0.0;\n\t    ipolant_nni.s_pos_off.z = 0.0;\n\t    \n\t    ipolant_nni.s_tex_off.u = 0.0;\n\t    ipolant_nni.s_tex_off.v = 0.0;\n\t    bool nni_valid = nnip->interpolate(ipolant_nni);\n\t    m_nni_possible[cv_index] = nni_valid ? 255 : 0;\n\t    if(nni_valid){\n\t      cv_nni->cv_xyz[cv_index] = xyz_curr + ipolant_nni.s_pos_off;\n\t      cv_nni->cv_uv[cv_index]  = uv_curr  + ipolant_nni.s_tex_off;\n\t      // STEPPO REMOVE\n\t      //std::cerr << \"IDW: \" << ipolant << std::endl;\n\t      //std::cerr << \"NNI: \" << ipolant_nni << std::endl;\n\t      //glm::vec3 pos_glm(ipolant_nni.s_pos_off.x,ipolant_nni.s_pos_off.y,ipolant_nni.s_pos_off.z);\n\t      //const float od = glm::length(pos_glm);\n\t      //if(od > 0.1){\n\t      //\tstd::cerr << tid << \" ERROR: outside offset_too_large at \" << ipolant_nni.s_pos_off << \" -> \" << od << std::endl;\n\t      //}\n\n\n\t    }\n\t  }\n\n\t}\n      }\n    }\n\n\n}\n\n\n/*static*/ void\nCalibrator::idw_interpolate(const std::vector<nniSample>& neighbours, const unsigned idw_neigbours, nniSample& ipolant, const float max_influence_dist){\n    \n\n  const float sigma = max_influence_dist * 1.0/3.3;\n  const float mean = 0;\n  const float norm = 1.0f/gauss(0.0f, sigma, mean);\n\n\n  double weight_d = 0.0;\n  xyz_d pos_offset;\n  pos_offset.x = 0.0;pos_offset.y = 0.0;pos_offset.z = 0.0;\n  uv_d tex_offset;\n  tex_offset.u = 0.0;tex_offset.v = 0.0;\n  glm::vec3 ipolant_pos(ipolant.s_pos.x,ipolant.s_pos.y,ipolant.s_pos.z);\n\n  for(unsigned i = 0; i < neighbours.size() && i < idw_neigbours; ++i){\n    nniSample s = neighbours[i];\n    //std::cerr << \"s.quality: \" << s.quality <<  std::endl;\n    glm::vec3 s_pos(s.s_pos.x,s.s_pos.y,s.s_pos.z);\n    const float influence_dist = std::min(max_influence_dist, glm::length(ipolant_pos - s_pos));\n    //std::cerr << \"influence dist: \" << influence_dist << \" of \" << max_influence_dist <<  std::endl;\n    const double s_weight = /*double(s.quality) * */gauss(influence_dist, sigma, mean) * norm;\n    //std::cerr << \"s_weight: \" << s_weight << std::endl;\n    \n    weight_d += s_weight;\n    pos_offset = pos_offset + s_weight * s.s_pos_off;\n    tex_offset = tex_offset + s_weight * s.s_tex_off;\n    \n  }\n\n  if(weight_d > 0.00001){\n    \n    ipolant.s_pos_off.x = pos_offset.x/weight_d;\n    ipolant.s_pos_off.y = pos_offset.y/weight_d;\n    ipolant.s_pos_off.z = pos_offset.z/weight_d;\n\n    ipolant.s_tex_off.u = tex_offset.u/weight_d;\n    ipolant.s_tex_off.v = tex_offset.v/weight_d;\n  }\n  else{\n    std::cerr << \"ERROR in Calibrator::idw_interpolate!!!! weight to low (weight_d < 0.0001) \" << std::endl;\n  }\n  \n}\n", "meta": {"hexsha": "9b091e6a9ae1e12c4c0da8d0dfa5dfee0f771d58", "size": 41363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "framework/calibrator.cpp", "max_stars_repo_name": "aosterthun/rgbdri", "max_stars_repo_head_hexsha": "8e513172f512c902f7d6d8631c7580b5b62277c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "framework/calibrator.cpp", "max_issues_repo_name": "aosterthun/rgbdri", "max_issues_repo_head_hexsha": "8e513172f512c902f7d6d8631c7580b5b62277c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "framework/calibrator.cpp", "max_forks_repo_name": "aosterthun/rgbdri", "max_forks_repo_head_hexsha": "8e513172f512c902f7d6d8631c7580b5b62277c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8782051282, "max_line_length": 208, "alphanum_fraction": 0.6443198027, "num_tokens": 13362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2220755216739912}}
{"text": "/* -----------------------------------------------------------------\n * File:    Recipe.cpp\n * Author:  Michael Gharbi <gharbi@mit.edu>\n * Created: 2015-07-24\n * -----------------------------------------------------------------\n * \n * \n * \n * ---------------------------------------------------------------*/\n\n\n#include <cmath>\n#include <algorithm>\n\n#ifndef __ANDROID__\n    #include <armadillo>\n    #include \"utils/image_io.h\"\n#endif\n\n// HALIDE\n#include \"utils/static_image.h\"\n\n#include \"recipe/hl_reconstruct.h\"\n#include \"recipe/hl_lowpass.h\"\n#include \"recipe/hl_highpass.h\"\n#include \"recipe/hl_compute_features.h\"\n#include \"recipe/hl_precompute_pyramid.h\"\n\n#include \"print_helper.h\"\n#include \"perf_measure.h\"\n\n\n#include \"recipe/Recipe.h\"\n\nnamespace xform {\n\nRecipe::Recipe( Image<uint32_t>& unprocessed ) {\n    m_model_width  = static_cast<int>(ceil(2.0f*unprocessed.width()/XFORM_WSIZE));\n    m_model_height = static_cast<int>(ceil(2.0f*unprocessed.height()/XFORM_WSIZE));\n    m_lp_width     = unprocessed.width()/XFORM_WSIZE;\n    m_lp_height    = unprocessed.height()/XFORM_WSIZE;\n    m_unprocessed_channels = 3;\n    m_processed_channels   = 3;\n}\n\n#ifndef __ANDROID__\nRecipe::Recipe( Image<uint32_t>& unprocessed, Image<uint32_t>& processed ):\n    Recipe(unprocessed)\n{\n    fit(unprocessed, processed);\n}\n#endif\n\n#ifndef __ANDROID__\nvoid Recipe::fit( Image<uint32_t>& unprocessed, Image<uint32_t>& processed )\n{\n    PRINT(\"Fit recipe\\n\");\n    m_lp_residual = std::make_shared<Image<uint32_t> >(m_lp_width,m_lp_height,m_processed_channels);\n    m_hp_coefs    = std::make_shared<Image<float> >(m_model_width,m_model_height,nCoefMaps());\n    m_qtable      = std::vector<float>(2*nCoefMaps());\n\n    int width  = unprocessed.width();\n    int height = unprocessed.height();\n\n    Image<float> processed_hp(width, height, 3);\n\n    // Compute and store lowpass of the processed image\n    auto start = get_time();\n    hl_lowpass(processed, *m_lp_residual);\n    PRINT(\"  - lowpass:\\t %ldms\\n\", get_duration(start,get_time()));\n\n    // Compute highpass of the output\n    start = get_time();\n    hl_highpass(processed, *m_lp_residual, processed_hp);\n    PRINT(\"  - highpass:\\t %ldms\\n\", get_duration(start,get_time()));\n\n    // Features\n    start = get_time();\n    Image<float> features(width, height, nFeatureChannels());\n    hl_compute_features(unprocessed, features);\n    PRINT(\"  - features:\\t %ldms\\n\", get_duration(start,get_time()));\n\n    start = get_time();\n    regression(features, processed_hp);\n    PRINT(\"  - regression:\\t %ldms\\n\", get_duration(start,get_time()));\n\n    quantize();\n}\n#endif\n\n\nvoid Recipe::precompute_features( const Image<uint32_t>& unprocessed)\n{\n    m_lp_unprocessed = Image<uint32_t>(m_lp_width, m_lp_height);\n    m_hp_unprocessed = Image<float>(unprocessed.width(), unprocessed.height(), 3);\n\n    auto start = get_time();\n    hl_lowpass(unprocessed, m_lp_unprocessed);\n    PRINT(\"  - lowpass : %ldms\\n\", get_duration(start,get_time()));\n\n    start = get_time();\n    hl_highpass(unprocessed, m_lp_unprocessed, m_hp_unprocessed);\n    PRINT(\"  - highpass : %ldms\\n\", get_duration(start,get_time()));\n\n    start = get_time();\n    m_pyramid_unprocessed = Image<float>(unprocessed.width(), unprocessed.height(), nPyrLevels()-1);\n    hl_precompute_pyramid(unprocessed,m_pyramid_unprocessed);\n    PRINT(\"  - precompute pyramid : %ldms\\n\", get_duration(start,get_time()));\n}\n\n\nvoid Recipe::reconstruct_with_features( Image<uint32_t> &output )\n{\n    dequantize();\n\n    output = Image<uint32_t>(m_pyramid_unprocessed.width(),\n            m_pyramid_unprocessed.height(), m_processed_channels);\n\n    auto start = get_time();\n    hl_reconstruct(\n            m_pyramid_unprocessed,\n            m_hp_unprocessed,\n            *m_hp_coefs,\n            *m_lp_residual,\n            output\n    );\n    PRINT(\"  - reconstruct precomputed: %ldms\\n\", get_duration(start,get_time()));\n}\n\n\nvoid Recipe::reconstruct_image( const Image<uint32_t>& unprocessed, Image<uint32_t> &output )\n{\n    precompute_features(unprocessed);\n    reconstruct_with_features(output);\n}\n\n\n#ifndef __ANDROID__\nvoid Recipe::regression( Image<float>& features, Image<float>& target) \n{\n    const int h_mdl           = m_model_height;\n    const int w_mdl           = m_model_width;\n    const int h               = target.height();\n    const int w               = target.width();\n    const int n_targets       = target.channels();\n    const int n_lumCoefs      = nLumCoefs();\n    const int n_chromCoefs    = nChromCoefs();\n    const int n_features      = features.channels();\n\n    float* pDataFeat   = features.data();\n    float* pDataTarget = target.data();\n    float* pLuminCoef  = m_hp_coefs->data();\n    float* pChromCoef  = pLuminCoef + h_mdl*w_mdl*n_lumCoefs;\n\n    int wSize = XFORM_WSIZE;\n    int step  = XFORM_WSIZE/2;\n\n    #pragma omp parallel for\n    for (int patch_idx = 0; patch_idx < h_mdl*w_mdl; ++patch_idx)\n    {\n        // temporary storage for the current patch\n        float* X = new float[wSize*wSize*n_lumCoefs]();\n        float* Y = new float[wSize*wSize*n_targets]();\n\n        // Patch indices (in the recipe)\n        int patch_x = patch_idx % w_mdl;\n        int patch_y = patch_idx / w_mdl;\n\n        // Pixel indices (in the image)\n        int x_min   = patch_x*step;\n        int x_max   = min(x_min+wSize, w);\n        int y_min   = patch_y*step;\n        int y_max   = min(y_min+wSize, h);\n        int n_samples = (y_max-y_min)*(x_max-x_min);\n\n        // Copy patch features\n        int idx = 0;\n        for (int f = 0; f < n_features; ++f)\n        for (int y = y_min; y < y_max; ++y)\n        for (int x = x_min; x < x_max; ++x)\n        {\n            X[idx] = pDataFeat[x+y*w+f*h*w];\n            ++idx;\n        }\n\n        // Make features for the non-linear luminance curve\n        int first_curve = idx;\n        auto minmax     = std::minmax_element(X,X + n_samples);\n        if(!XFORM_ADAPTIVE_LUMA_RANGE) {\n            *minmax.first = 0.0f;\n            *minmax.second = 1.0f;\n        }\n        float step_sz   = (*minmax.second-*minmax.first)/XFORM_LUMA_BANDS;\n        float mini      = *minmax.first;\n        for (int s = 0; s < XFORM_LUMA_BANDS-1; ++s){\n            float thresh = mini+(s+1)*step_sz;\n            for (idx = 0; idx < n_samples; ++idx)\n            {\n                X[first_curve + n_samples*s + idx] = std::max(X[idx]-thresh, 0.0f);\n            }\n        }\n\n        // Copy target variables\n        idx = 0;\n        for (int f = 0; f < n_targets; ++f)\n        for (int y = y_min; y < y_max; ++y)\n        for (int x = x_min; x < x_max; ++x)\n        {\n            Y[idx] = pDataTarget[x+y*w+f*h*w];\n            ++idx;\n        }\n\n        // Solve least-square regression\n        arma::Mat<float> matX(X, n_samples,n_lumCoefs, false);\n        arma::Mat<float> matY(Y, n_samples,n_targets, false);\n\n        // For the luminance\n        arma::Mat<float> result_lumin;\n        arma::Mat<float> Xview = matX.cols(0,n_lumCoefs-1);\n        arma::Mat<float> Yview = matY.cols(0,0);\n        arma::Mat<float> regularizer = arma::eye<arma::Mat<float>>(n_lumCoefs, n_lumCoefs);\n        regularizer(3,3) = 0.0f; //do not regularize affine offset\n        arma::Mat<float> lhs = arma::trans(Xview) * Xview + XFORM_EPSILON*regularizer;\n        arma::Mat<float> rhs = arma::trans(Xview) * Yview;\n        arma::solve(result_lumin,lhs,rhs);\n\n        // For the chrominance\n        arma::Mat<float> result_chrom;\n        Xview = matX.cols(0,n_chromCoefs-1);\n        Yview = matY.cols(1,2);\n        regularizer = arma::eye<arma::Mat<float>>(n_chromCoefs, n_chromCoefs);\n        regularizer(3,3) = 0.0f; //do not regularize affine offset\n        lhs = arma::trans(Xview) * Xview + XFORM_EPSILON*regularizer;\n        rhs = arma::trans(Xview) * Yview;\n        arma::solve(result_chrom,lhs,rhs);\n\n        // Fill-in the luminance regression coefficients\n        float* coefs = result_lumin.memptr();\n        idx = 0;\n        for (int f = 0; f < n_lumCoefs; ++f)\n        {\n            pLuminCoef[patch_x+patch_y*w_mdl+f*h_mdl*w_mdl] = coefs[idx];\n            ++idx;\n        }\n\n        // Fill in the chrominance regression coefficients\n        coefs = result_chrom.memptr();\n        idx = 0;\n        for (int c = 0; c < 2; ++c)\n        for (int f = 0; f < n_chromCoefs; ++f)\n        {\n            pChromCoef[patch_x + patch_y*w_mdl + f*h_mdl*w_mdl + c*n_chromCoefs*h_mdl*w_mdl] = coefs[idx];\n            ++idx;\n        }\n        coefs = nullptr;\n\n        delete[] X; X = nullptr;\n        delete[] Y; Y = nullptr;\n    }\n    pDataTarget = nullptr;\n    pDataFeat   = nullptr;\n}\n#endif \n\n\nvoid Recipe::quantize() \n{\n    const int h_mdl   = m_model_height;\n    const int w_mdl   = m_model_width;\n    const int n_feats = nCoefMaps();\n\n    // Get values range per regression channel\n    float* pCoef = m_hp_coefs->data();\n\n    // Compute min and max for each channel\n    for (int f = 0; f < n_feats; ++f){\n        m_qtable[2*f]   = pCoef[f*h_mdl*w_mdl];\n        m_qtable[2*f+1] = pCoef[f*h_mdl*w_mdl];\n        for (int y = 0; y < h_mdl; ++y)\n        for (int x = 0; x < w_mdl; ++x)\n        {\n            float val = pCoef[x + y*w_mdl + f*h_mdl*w_mdl];\n            // min\n            m_qtable[2*f] = min(m_qtable[2*f],val);\n            // max\n            m_qtable[2*f+1] = max(m_qtable[2*f+1],val);\n        }\n    }\n\n    // Quantize\n    for (int f = 0; f < n_feats; ++f)\n    {\n        float min = (m_qtable)[2*f];\n        float max = (m_qtable)[2*f+1];\n        float inv_rng = 1.0f/(max-min);\n        for (int y = 0; y < h_mdl; ++y)\n        for (int x = 0; x < w_mdl; ++x)\n        {\n            float *val = pCoef + (x+y*w_mdl+f*h_mdl*w_mdl);\n            *val -= min;\n            *val *= inv_rng;\n            *val = floor(255.0f*(*val)+0.5f);\n        }\n    }\n}\n\n\nvoid Recipe::dequantize() \n{\n    const int h_mdl        = m_model_height;\n    const int w_mdl        = m_model_width;\n    const int n_feats = nCoefMaps();\n\n    float* pCoef  = m_hp_coefs->data();\n\n    // Dequantize\n    for (int f = 0; f < n_feats; ++f)\n    {\n        float min = m_qtable[2*f];\n        float max = m_qtable[2*f+1];\n        float rng = (max-min)/255.0f;\n        for (int y = 0; y < h_mdl; ++y)\n        for (int x = 0; x < w_mdl; ++x) {\n            float *val = pCoef + (x+y*w_mdl+f*h_mdl*w_mdl);\n            *val *= rng;\n            *val += min;\n        }\n    }\n}\n\n} //namespace xform\n", "meta": {"hexsha": "4a90fff71418cb78419425a4bd01b1d388ebe03d", "size": 10341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xform_cpp/src/recipe/Recipe.cpp", "max_stars_repo_name": "mgharbi/xform_recipes", "max_stars_repo_head_hexsha": "69404155f07860a7c754670dcb61c5ce03d88809", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-01-11T16:58:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-11T02:05:57.000Z", "max_issues_repo_path": "xform_cpp/src/recipe/Recipe.cpp", "max_issues_repo_name": "mgharbi/xform_recipes", "max_issues_repo_head_hexsha": "69404155f07860a7c754670dcb61c5ce03d88809", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-04T07:09:03.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-04T07:09:03.000Z", "max_forks_repo_path": "xform_cpp/src/recipe/Recipe.cpp", "max_forks_repo_name": "mgharbi/xform_recipes", "max_forks_repo_head_hexsha": "69404155f07860a7c754670dcb61c5ce03d88809", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-04-03T09:09:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-04T10:09:08.000Z", "avg_line_length": 31.1475903614, "max_line_length": 106, "alphanum_fraction": 0.5805047868, "num_tokens": 2945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.22206991791466832}}
{"text": "/// \\file   python_module.cpp\n///\n/// \\brief\n///\n/// \\authors    Maarten P. Scholl\n/// \\date       2020-08-30\n/// \\copyright  Copyright 2017-2020 The Institute for New Economic Thinking,\n///             Oxford Martin School, University of Oxford\n///\n///             Licensed under the Apache License, Version 2.0 (the \"License\");\n///             you may not use this file except in compliance with the License.\n///             You may obtain a copy of the License at\n///\n///                 http://www.apache.org/licenses/LICENSE-2.0\n///\n///             Unless required by applicable law or agreed to in writing,\n///             software distributed under the License is distributed on an \"AS\n///             IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n///             express or implied. See the License for the specific language\n///             governing permissions and limitations under the License.\n///\n///             You may obtain instructions to fulfill the attribution\n///             requirements in CITATION.cff\n///\n#include <esl/mathematics/python_module_mathematics.hpp>\n\n\n#ifdef WITH_PYTHON\n\n#include <esl/mathematics/variable.hpp>\n\n#define BOOST_BIND_GLOBAL_PLACEHOLDERS\n#include <boost/python.hpp>\nusing namespace boost::python;\n\n#include <adept/Stack.h>\n\n\ntypedef adept::internal::BinaryOperation<double, adept::Active<double>, adept::internal::Multiply, adept::Active<double> > binary_operation_t;\n\nusing namespace esl;\n\n\nBOOST_PYTHON_MODULE(_mathematics)\n{\n    class_<variable>( \"variable\", init<>())\n        .def(init<double>())\n        .def(self == self)\n        .def(self != self)\n        .def(self < self)\n        .def(self <= self)\n        .def(self > self)\n        .def(self >= self)\n        .def(self + self)\n        .def(self += self)\n        .def(self - self)\n        .def(self -= self)\n        .def(self * self)\n        .def(self *= self)\n        .def(self / self)\n        .def(self /= self)\n        //.def(\"value\", &variable::value)\n        ;\n\n    class_<adept::Stack>(\"stack\", init<>())\n        .def(\"pause_recording\", &adept::Stack::pause_recording)\n        .def(\"continue_recording\", &adept::Stack::continue_recording)\n        .def(\"new_recording\", &adept::Stack::new_recording)\n        .def(\"compute_adjoint\", &adept::Stack::compute_adjoint)\n\n    ;\n\n    // TODO: verify that all opeartions on this are exported\n    class_<binary_operation_t>(\"binary_operation_t\", no_init)\n        .def(self == self)\n        .def(self != self)\n        .def(self < self)\n        .def(self <= self)\n        .def(self > self)\n        .def(self >= self)\n        .def(self + self)\n       // .def(self + variable())\n        .def(self - self)\n     //   .def(self - variable())\n        .def(self * self)\n      //  .def(self * variable())\n        .def(self / self)\n    //    .def(self / variable())\n        ;\n\n\n// TODO: export these\n//    def(\"get_gradients\", &adept::get_gradients);\n//    stack_.independent(&active_[0], active_.size());\n//    stack_.dependent(&values_[0], values_.size());\n//    stack_.jacobian(jacobian);\n\n\n\n}\n\n#endif", "meta": {"hexsha": "8f27b4232d537d31704f285125a90a72283c8edf", "size": 3066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "esl/mathematics/python_module_mathematics.cpp", "max_stars_repo_name": "rht/ESL", "max_stars_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "esl/mathematics/python_module_mathematics.cpp", "max_issues_repo_name": "rht/ESL", "max_issues_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "esl/mathematics/python_module_mathematics.cpp", "max_forks_repo_name": "rht/ESL", "max_forks_repo_head_hexsha": "f883155a167d3c48e5ecdca91c8302fefc901c22", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-27T12:11:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T12:11:48.000Z", "avg_line_length": 30.0588235294, "max_line_length": 142, "alphanum_fraction": 0.5945857795, "num_tokens": 727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.2220117204248458}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2021 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n/*! \\file BlockCSRMatrix.hpp\nDefinition of a compressed row sparse block matrix of SiconosMatrix*\n*/\n\n#ifndef BLOCKCSRMATRIX_H\n#define BLOCKCSRMATRIX_H\n\n#include \"NumericsFwd.h\"  // Numerics forward declarations\n#include \"SimulationTypeDef.hpp\"\n#include \"SiconosSerialization.hpp\" // for ACCEPT_SERIALIZATION\n#include <boost/numeric/ublas/fwd.hpp> // Boost forward declarations \n\n/* with signed int typedef  boost::numeric::ublas::compressed_matrix<double*> CompressedRowMat; */\n/* cf http://boost.2283326.n4.nabble.com/LU-decomposition-of-compressed-matrix-td3417929.html */\ntypedef boost::numeric::ublas::compressed_matrix <\ndouble*, boost::numeric::ublas::basic_row_major<unsigned int>, 0, boost::numeric::ublas::unbounded_array<std::size_t> >  CompressedRowMat;\nTYPEDEF_SPTR(CompressedRowMat)\nTYPEDEF_SPTR(SparseBlockStructuredMatrix)\n\n\n/** Definition of a compressed sparse row matrix of SiconosMatrix,\n * used in OneStepNSProblem to store the M matrix.\n *\n * This class defines a specific compressed row sparse storage for\n * blocks matrices, each block being a SiconosMatrix*.\n *\n * It handles:\n * - a SparseMat (boost-ublas) of SiconosMatrix*\n * - a vector<SiconosMatrix*> which handles the non-null blocks\n\n * - three vector<int> (IndexInt) to save non-null blocks position in\n     row, columns and the list of the sizes of diagonal blocks.\n\n * - two int, the number of blocks in a row and the number of non null blocks.\n *\n * Each block of the current object represents the connection between\n * two coupled Interactions, \\n (for example for Lagrangian\n * systems, a single \\f$ H W^{-1} H^t \\f$ block or for first order\n * systems \\f$ hCW^{-1}B \\f$ ...) \\n\n *\n * This objects is built using an index set of SP::Interaction,\n * that represents the \"active\" constraints in the OSNS problem and a\n * map<SP::Interaction u1, <SP::Interaction u2, SP::SiconosMatrix block> >, block being the link\n * between u1 and u2. Only Interaction present in the index set are picked out\n * in the map.\n *\n *  A convert method is also implemented to create a\n *  SparseBlockStructuredMatrix which is Numerics-readable.\n *\n * As an example, consider the index set I={u1, u3, u5, u8} and the\n * map where non null blocks are (ui,ui), (u1,u3), (u1,u8), (u3,u1),\n * (u8,u1).\\n Each block being a pointer to a 3x3 matrix.\\n Then the\n * resulting matrix has 4 X 4 blocks, with 8 non-null blocks and looks\n * like:\n *\n \\rst\n\n .. math::\n    :nowrap:\n\n    M=\\left\\lbrace\\begin{array}{cccc}\n    b11 & b13 & 0 & b18 \\\\\n    b31 & b22 & 0 & 0 \\\\\n    0   & 0   & b33&0 \\\\\n    b81 & 0   & 0 & b44\n    \\end{array}\\right.\n\n \\endrst\n *\n * with nc = 4, nbNonNullBlocks = 8, RowPos = [0 0 0 1 1 2 3 3],\n * RowCol = [0 1 3 0 1 2 0 3]\\n and _diagsize0 = [3 6 9 12].\n *\n * We use stl::vector (which may seems redundent with the double* of\n * the numerics SparseBlockStructuredMatrix) because memory can be\n * reserved during construction or initialized and then vectors are\n * resized when the object is filled in. This avoid some call to\n * malloc/free at each iteration.\n *\n */\nclass BlockCSRMatrix\n{\nprivate:\n  /** serialization hooks\n  */\n  ACCEPT_SERIALIZATION(BlockCSRMatrix);\n\n  /** Number of blocks rows (first dimension of the block matrix)*/\n  unsigned int _nr;\n\n  /** Number of blocks columns (second dimension of the block matrix)*/\n  unsigned int _nc;\n\n  /** Sparse-Block Boost Matrix. Each block is a SiconosMatrix**/\n  SP::CompressedRowMat _blockCSR;\n\n  /** Specific structure required when a (Numerics) solver block is used */\n  SP::SparseBlockStructuredMatrix _sparseBlockStructuredMatrix;\n\n  /** Vector used to save the sum of rows of diagonal blocks of M:\n      _diagsize0[i] = _diagsize0[i-1] + ni, ni being the size of the\n      diagonal block at row(block) i */\n  SP::IndexInt _diagsize0;\n\n  /** Vector used to save the sum of dim of diagonal blocks of M:\n      _diagsize0[i] = _diagsize0[i-1] + ni, ni being the size of the\n      diagonal block at row(block) i */\n  SP::IndexInt _diagsize1;\n\n  /** List of non null blocks positions (in row) */\n  SP::IndexInt rowPos;\n\n  /** List of non null blocks positions (in col) */\n  SP::IndexInt colPos;\n\n  /** Private copy constructor => no copy nor pass by value */\n  BlockCSRMatrix(const BlockCSRMatrix&);\n\n  /** Private assignment -> forbidden \n   * \\return  BlockCSRMatrix&\n   */\n  BlockCSRMatrix& operator=(const BlockCSRMatrix&);\n\npublic:\n\n  /** Default constructor -> empty matrix\n   */\n  BlockCSRMatrix();\n\n  /** Constructor with dimension (number of blocks)\n      \\param n number of blocks in a row/column (only square matrices allowed)\n  */\n  BlockCSRMatrix(unsigned int n);\n\n  /** Constructor from index set\n      \\param indexSet the index set of the active constraints\n  */\n  BlockCSRMatrix(InteractionsGraph& indexSet);\n\n  /** destructor\n   */\n  ~BlockCSRMatrix();\n\n  /** get size (in block-components) \n   * \\return unsigned int NumberOfBlocksInARow\n   */\n  inline unsigned int numberOfBlocksInARow() const\n  {\n    return _nr;\n  };\n\n  /** get total number of non-null blocks\n   * \\return unsigned int\n   */\n  unsigned int getNbNonNullBlocks() const;\n\n  /** get the numerics-readable structure\n   * \\return SP::SparseBlockStructuredMatrix\n   */\n  inline SP::SparseBlockStructuredMatrix getNumericsMatSparse()\n  {\n    return _sparseBlockStructuredMatrix;\n  };\n\n  /** get the ublas sparse mat\n   * \\return SP::CompressedRowMat\n   */\n  inline SP::CompressedRowMat getMSparse()\n  {\n    return _blockCSR;\n  };\n\n  /** get the dimension of the square-diagonal block number num\n   * \\param i block position\n   * \\return unsigned int\n  */\n  IndexInt::value_type getSizeOfDiagonalBlock(int i) const\n  {\n    if (i == 0) return _diagsize0->at(0);\n    else return (_diagsize0->at(i) - _diagsize0->at(i - 1));\n  };\n\n  /** get the index of blocks position (i=0 -> rows, i=1 -> columns)\n   * \\param i unsigned int, 0 for rows, 1 for columns\n   * \\return SP::IndexInt\n   */\n  inline SP::IndexInt getPositionsIndex(bool i)\n  {\n    if (i) return rowPos;\n    else return colPos;\n  };\n\n  /** fill the current class using an index set\n   *  \\param indexSet set of the active constraints\n   */\n  void fill(InteractionsGraph& indexSet);\n\n\n  /** fill the matrix with the Mass matrix \n   * \\warning only for NewtonEulerDS\n   * \\param indexSet of the active constraints\n   */\n  void fillM(InteractionsGraph& indexSet);\n\n  /** fill the matrix with the H matrix \n   * \\warning only for NewtonEuler3DR\n   * \\param indexSet of the active constraints\n   */\n  void fillH(InteractionsGraph& indexSet);\n\n  /** fill the numerics structure _sparseBlockStructuredMatrix using _blockCSR */\n  void convert();\n\n  /** display the current matrix\n   */\n  void display() const;\n};\n\n#endif\n", "meta": {"hexsha": "ef2e3a4d87fe2e058e3eb214db90a8f9a43311a5", "size": 7380, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "kernel/src/simulationTools/BlockCSRMatrix.hpp", "max_stars_repo_name": "BuildJet/siconos", "max_stars_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-11T11:21:09.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-11T11:21:09.000Z", "max_issues_repo_path": "kernel/src/simulationTools/BlockCSRMatrix.hpp", "max_issues_repo_name": "BuildJet/siconos", "max_issues_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/simulationTools/BlockCSRMatrix.hpp", "max_forks_repo_name": "BuildJet/siconos", "max_forks_repo_head_hexsha": "5e9c95806f0a01d62ab564ffb1d9d50c2dc32ef0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2711864407, "max_line_length": 138, "alphanum_fraction": 0.7031165312, "num_tokens": 1984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.22179253962631093}}
{"text": "#include <Core/Core.h>\n#include <Functions4U/Functions4U.h>\n#include <Eigen/Eigen.h>\n#include \"Sundials.h\"\n\nnamespace Upp {\n\nusing namespace Eigen;\n\n#include <kinsol/kinsol.h>           \t\t  /* access to KINSOL func., consts. */\n#include <ida/ida.h>                          /* prototypes for IDA fcts., consts.    */\n#include <nvector/nvector_serial.h>           /* access to serial N_Vector            */\n#include <sunmatrix/sunmatrix_dense.h>        /* access to dense SUNMatrix            */\n#include <sunlinsol/sunlinsol_dense.h>        /* access to dense SUNLinearSolver      */\n#include <sunnonlinsol/sunnonlinsol_newton.h> /* access to Newton SUNNonlinearSolver  */\n#include <sundials/sundials_types.h>          /* defs. of realtype, sunindextype      */\n#include <sundials/sundials_math.h>           /* defs. of SUNRabs, SUNRexp, etc.      */\n\n\nstatic void CheckMem(void *returnvalue, const char *funcname) {\n\tif (returnvalue == NULL) \n\t\tthrow Exc(Format(t_(\"SUNDIALS_ERROR: %s() failed - returned NULL pointer\"), funcname));\n}\n\nstatic void CheckRet(int returnvalue, const char *funcname) {\n\tif (returnvalue < 0) \n\t  \tthrow Exc(Format(t_(\"SUNDIALS_ERROR: %s() failed with retval = %d\"), funcname, returnvalue));\n}\n\nstatic void PrintFinalStats(void *mem) {\n\tint retval;\n\tlong int nst, nni, nje, nre, nreLS, netf, ncfn, nge;\n\t\n\tretval = IDAGetNumSteps(mem, &nst);\n\tCheckRet(retval, \"IDAGetNumSteps\");\n\tretval = IDAGetNumResEvals(mem, &nre);\n\tCheckRet(retval, \"IDAGetNumResEvals\");\n\tretval = IDAGetNumJacEvals(mem, &nje);\n\tCheckRet(retval, \"IDAGetNumJacEvals\");\n\tretval = IDAGetNumNonlinSolvIters(mem, &nni);\n\tCheckRet(retval, \"IDAGetNumNonlinSolvIters\");\n\tretval = IDAGetNumErrTestFails(mem, &netf);\n\tCheckRet(retval, \"IDAGetNumErrTestFails\");\n\tretval = IDAGetNumNonlinSolvConvFails(mem, &ncfn);\n\tCheckRet(retval, \"IDAGetNumNonlinSolvConvFails\");\n\tretval = IDAGetNumLinResEvals(mem, &nreLS);\n\tCheckRet(retval, \"IDAGetNumLinResEvals\");\n\tretval = IDAGetNumGEvals(mem, &nge);\n\tCheckRet(retval, \"IDAGetNumGEvals\");\n\t\n\tprintf(\"\\nFinal Run Statistics: \\n\\n\");\n\tprintf(\"Number of steps                    = %ld\\n\", nst);\n\tprintf(\"Number of residual evaluations     = %ld\\n\", nre+nreLS);\n\tprintf(\"Number of Jacobian evaluations     = %ld\\n\", nje);\n\tprintf(\"Number of nonlinear iterations     = %ld\\n\", nni);\n\tprintf(\"Number of error test failures      = %ld\\n\", netf);\n\tprintf(\"Number of nonlinear conv. failures = %ld\\n\", ncfn);\n\tprintf(\"Number of root fn. evaluations     = %ld\\n\", nge);\n}\n\nstatic void PrintIteration(realtype t, realtype *y, int neq) {\n\tCout() << \"\\n\" << Format(\"%7.3f \", t);\n\tfor (int i = 0; i < neq; ++i)\n\t\tCout() << Format(\"%12.4e \", y[i]);\n}\n\nstatic void PrintRootInfo(int *roots, int nroots) {\n\tCout() << \"\\nRoots found[] = \";\n\tfor (int i = 0; i < nroots; ++i)\n\t\tCout() << roots[i] << \" \";\n}\n\nstatic String GetIdaErrorMsg(int ret) {\n\tswitch (ret) {\n\tcase IDA_TOO_MUCH_WORK:\treturn \"IDASolve: IDA_TOO_MUCH_WORK\";\n\tcase IDA_TOO_MUCH_ACC:  return \"IDASolve: IDA_TOO_MUCH_ACC\";\n\tcase IDA_ERR_FAIL:      return \"IDASolve: IDA_ERR_FAIL\";\n\tcase IDA_MEM_NULL:\t\treturn \"ida_mem is NULL\";\n\tcase IDA_NO_MALLOC:\t\treturn \"ida_mem was not allocated\";\t\n\tcase IDA_ILL_INPUT:\t\treturn \"bad value for icopt, tout1, or id\";\n\tcase IDA_LINIT_FAIL:\treturn \"the linear solver linit routine failed\";\n \tcase IDA_BAD_EWT:\t\treturn \"zero value of some component of ewt\";\t\n \tcase IDA_RES_FAIL:\t\treturn \"res had a non-recoverable error\";\t\n \tcase IDA_FIRST_RES_FAIL:return \"res failed recoverably on the first call\";\t\n \tcase IDA_LSETUP_FAIL:\treturn \"lsetup had a non-recoverable error\";\t\n \tcase IDA_LSOLVE_FAIL:\treturn \"lsolve had a non-recoverable error\";\t\n \tcase IDA_NO_RECOVERY:\treturn \"res, lsetup, or lsolve had a recoverable error, but IDACalcIC could not recover\";\t\n \tcase IDA_CONSTR_FAIL:\treturn \"the inequality constraints could not be met\";\t\n \tcase IDA_LINESEARCH_FAIL:return\"the linesearch failed (either on steptol test or on the maxbacks test)\";\n \tcase IDA_CONV_FAIL:\t\treturn \"the Newton iterations failed to converge\";\n\tdefault:\t\t\t\treturn Format(\"Unknown Sundials error %d\", ret);\n\t}\n}\n                \t\nvoid SolveDAE(const VectorXd &y, const VectorXd &dy, double dt, double maxt, Upp::Array<VectorXd> &res,  \n\t\tFunction <bool(double t, Eigen::Index iiter, const double y[], const double dy[], double residual[])>Residual, int numZero,\n\t\tFunction <bool(double t, Eigen::Index iiter, const double y[], const double dy[], double residual[])>ResidualZero) {\n\tASSERT(y.size() == dy.size());\n\tEigen::Index numEq = y.size();\n\tres.SetCount(int(numEq));\n\tfor (int i = 0; i < numEq; ++i) {\n\t\tres[i].resize(int(maxt/dt)+1);\n\t\tres[i](0) = y[i];\n\t}\n\tSolveDAE(y.data(), dy.data(), int(numEq), dt, maxt, Residual, numZero, ResidualZero, [&](double t, Eigen::Index iiter, const double y[], const double dy[], bool isZero, int *whichZero)->int {\n\t\tfor (int i = 0; i < int(numEq); ++i)\n\t\t\tres[i](iiter) = y[i]; \n\t\treturn true;\n\t});\t\t\n}\n\nvoid SolveDAE(const VectorXd &y, const VectorXd &dy, double dt, double maxt, \n\t\tUpp::Array<VectorXd> &res, Upp::Array<VectorXd> &dres, \n\t\tFunction <bool(double t, Eigen::Index iiter, const double y[], const double dy[], double residual[])>Residual, int numZero,\n\t\tFunction <bool(double t, Eigen::Index iiter, const double y[], const double dy[], double residual[])>ResidualZero) {\n\tASSERT(y.size() == dy.size());\n\tEigen::Index numEq = y.size();\n\tres.SetCount(int(numEq));\n\tdres.SetCount(int(numEq));\n\tfor (int i = 0; i < numEq; ++i) {\n\t\tres[i].resize(int(maxt/dt)+1);\n\t\tres[i](0) = y[i];\n\t\tdres[i].resize(int(maxt/dt)+1);\n\t\tdres[i](0) = dy[i];\n\t}\n\tSolveDAE(y.data(), dy.data(), int(numEq), dt, maxt, Residual, numZero, ResidualZero, [&](double t, Eigen::Index iiter, const double y[], const double dy[], bool isZero, int *whichZero)->int {\n\t\tfor (int i = 0; i < int(numEq); ++i) {\n\t\t\tres[i](iiter) = y[i]; \n\t\t\tdres[i](iiter) = dy[i];\n\t\t}\n\t\treturn true;\n\t});\t\t\n}\n\nvoid SolveDAE(const double y[], const double dy[], int numEq, double dt, double maxt, \n\t\tFunction <bool(double t, Eigen::Index iiter, const double y[], const double dy[], double residual[])> Residual, int numZero,  \n\t\tFunction <bool(double t, Eigen::Index iiter, const double y[], const double dy[], double residual[])> ResidualZero,\n\t\tFunction <bool(double t, Eigen::Index iiter, const double y[], const double dy[], bool isZero, int *whichZero)>OnIteration) {\n\tint retval, retvalr;\n\tBuffer<int> rootsfound(numEq);\n\tSUNNonlinearSolver NLS = NULL;\n\tSUNLinearSolver LS = NULL;\n\tSUNMatrix A = NULL;\n\tvoid *mem = NULL;\n\tN_Vector avtol = NULL, yy = NULL, yp = NULL;\n\t\n\tExc error;\n\ttry {\n\t\tyy = N_VNew_Serial(numEq);\n\t\tCheckMem((void *)yy, \"N_VNew_Serial\");\n\t\typ = N_VNew_Serial(numEq);\n\t\tCheckMem((void *)yp, \"N_VNew_Serial\");\n\t\tavtol = N_VNew_Serial(numEq);\n\t\tCheckMem((void *)avtol, \"N_VNew_Serial\");\n\t\n\t  \t/* Create and initialize  y, y', and absolute tolerance vectors. */\n\t\tmemcpy(N_VGetArrayPointer(yy), y,  numEq*sizeof(double));\n\t\tmemcpy(N_VGetArrayPointer(yp), dy, numEq*sizeof(double));\n\t\t\n\t\trealtype rtol = 1.0e-5;\n\t\t\n\t\trealtype *atval = N_VGetArrayPointer(avtol);\n\t\tfor (int i = 0; i < numEq; ++i)\n\t\t\tatval[i] = 1.0e-8;\n\t\n\t  \tdouble t0 = 0;\n\t\n\t\tstruct UserData {\n\t\t\tFunction <bool(double t, Eigen::Index iiter, const double y[], const double dy[], double residual[])> Residual;\n\t\t\tFunction <bool(double t, Eigen::Index iiter, const double y[], const double dy[], double residual[])> ResidualZero;\n\t\t\tint iiter = 0;\n\t\t} userData;\n\t\t\n\t\tuserData.Residual = Residual;\n\t\tuserData.ResidualZero = ResidualZero;\n\t\t\n\t    auto ResFun = [](realtype t, N_Vector _y, N_Vector _dy, N_Vector _res, void *user_data) { \n\t\t\trealtype *y = N_VGetArrayPointer(_y);\n\t\t\trealtype *dy = N_VGetArrayPointer(_dy);\n\t\t\trealtype *res = N_VGetArrayPointer(_res);\n\t\t\t\n\t\t\tUserData &userData = *(UserData *)user_data;\n\t\t\t\n\t\t\treturn userData.Residual(t, userData.iiter, y, dy, res) ? 0 : -1;\n\t\t};\n\t    auto ResZeroFun = [](realtype t, N_Vector _y, N_Vector _dy, realtype *res, void *user_data) { \n\t\t\trealtype *y = N_VGetArrayPointer(_y);\n\t\t\trealtype *dy = N_VGetArrayPointer(_dy);\n\t\t\t\n\t\t\tUserData &userData = *(UserData *)user_data;\n\t\t\t\n\t\t\treturn userData.ResidualZero(t, userData.iiter, y, dy, res) ? 0 : -1;\n\t\t};\t\n\t\t\n\t\t/* Call IDACreate and IDAInit to initialize IDA memory */\n\t\tmem = IDACreate();\n\t\tCheckMem((void *)mem, \"IDACreate\");\t\n\t\t\n\t\tretval = IDASetUserData(mem, (void *)&userData);\n\t\tCheckRet(retval, \"IDASetUserData\");\n\t\n\t\tretval = IDAInit(mem, ResFun, t0, yy, yp);\n\t\tCheckRet(retval, \"IDAInit\");\n\t\t\n\t\tIDASetErrHandlerFn(mem, [](int error_code, const char *module, const char *function,\n                                char *msg, void *user_data) {\n        \tthrow Exc(Format(t_(\"Sundials %s error (%s): %s\"), module, function, msg));\n                                }, nullptr);\n                                       \n\t\t/* Call IDASVtolerances to set tolerances */\n\t\tretval = IDASVtolerances(mem, rtol, avtol);\n\t\tCheckRet(retval, \"IDASVtolerances\");\n\t\t\n\t\t/* Call IDARootInit to specify the root function grob with 2 components */\n\t\tif (ResidualZero && numZero > 0) {\n\t\t\tretval = IDARootInit(mem, numZero, ResZeroFun);\n\t\t\tCheckRet(retval, \"IDARootInit\");\n\t\t}\n\t\t\n\t\t/* Create dense SUNMatrix for use in linear solver */\n\t\tA = SUNDenseMatrix(numEq, numEq);\n\t\tCheckMem((void *)A, \"SUNDenseMatrix\");\n\t\t\n\t\t/* Create dense SUNLinearSolver object */\n\t\tLS = SUNLinSol_Dense(yy, A);\n\t\tCheckMem((void *)LS, \"SUNLinSol_Dense\");\n\t\t\n\t\t/* Attach the matrix and linear solver */\n\t\tretval = IDASetLinearSolver(mem, LS, A);\n\t\tCheckRet(retval, \"IDASetLinearSolver\");\n\t\t\n\t\tretval = IDASetMaxNumSteps(mem, 20000);\n\t\tCheckRet(retval, \"IDASetLinearSolver\");\n\t\t\n\t\t/* Create Newton SUNNonlinearSolver object. IDA uses a\n\t\t* Newton SUNNonlinearSolver by default, so it is unnecessary\n\t\t* to create it and attach it. It is done in this example code\n\t\t* solely for demonstration purposes. */\n\t\tNLS = SUNNonlinSol_Newton(yy);\n\t\tCheckMem((void *)NLS, \"SUNNonlinSol_Newton\");\n\t\t\n\t\t/* Attach the nonlinear solver */\n\t\tretval = IDASetNonlinearSolver(mem, NLS);\n\t\tCheckRet(retval, \"IDASetNonlinearSolver\");\n\t\t\n\t\tuserData.iiter = 0; \n\t\tdouble tnext = 0.000001;\n\t\tdouble titer;\n\t\twhile(tnext <= maxt && userData.iiter < int(maxt/dt)+1) {\n\t\t\tretval = IDASolve(mem, tnext, &titer, yy, yp, IDA_NORMAL);\n\t\t\tCheckRet(retval, \"IDASolve\");\n\t\t\n\t\t\trealtype *y  = N_VGetArrayPointer(yy);\n\t\t\trealtype *dy = N_VGetArrayPointer(yp);\n\t\t\t\n\t\t\t//PrintIteration(titer, y, numEq);\n\t\t\t\n\t\t\tif (retval == IDA_ROOT_RETURN) {\n\t\t\t\tretvalr = IDAGetRootInfo(mem, rootsfound);\n\t\t\t\tCheckRet(retvalr, \"IDAGetRootInfo\");\n\t\t\t\t//PrintRootInfo(rootsfound, numEq);\n\t\t\t} else if (retval == IDA_SUCCESS) \n\t\t\t\t;\n\t\t\telse\t\t\n\t\t\t\tthrow Exc(Format(t_(\"Sundials IDA error: %s\"), GetIdaErrorMsg(retval)));\n\t\t\t\n\t\t\tif(OnIteration && !OnIteration(titer, userData.iiter, y, dy, retval == IDA_ROOT_RETURN, rootsfound))\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tif (retval == IDA_SUCCESS) {\n\t\t\t\tuserData.iiter++;\n\t\t\t\ttnext = userData.iiter*dt;\n\t\t\t}\n\t  \t}\n\t  \t//PrintFinalStats(mem);\n\t} catch(Exc err) {\n\t\terror = err;\n\t}\n\tIDAFree(&mem);\n\tSUNNonlinSolFree(NLS);\n\tSUNLinSolFree(LS);\n\tSUNMatDestroy(A);\n\tN_VDestroy(avtol);\n\tN_VDestroy(yy);\n\tN_VDestroy(yp);\n\t\n\tif (!error.IsEmpty())\n\t\tthrow Exc(error);\n}\n\n/*\n0 \tthen no constraint is imposed on ui.\n1 \tthen ui will be constrained to be ui 0:0.\n-1 \tthen ui will be constrained to be ui 0:0.\n2 \tthen ui will be constrained to be ui > 0:0.\n-2 \tthen ui will be constrained to be ui < 0:0.\n*/\nvoid SolveNonLinearEquationsSun(double y[], int numEq, \n\t\t\tFunction <bool(const double b[], double residuals[])> Residual, int constraints[]) {\n\tN_Vector s = NULL;\n\tvoid *kmem = NULL;\n\t\n  \tExc error;\n  \ttry {\n  \t\tN_Vector u = N_VNew_Serial(numEq);\t\n\t\tCheckMem((void *)u, \"N_VNew_Serial\");\n  \t\trealtype *udata = NV_DATA_S(u);\n \t\tmemcpy(udata, y, numEq*sizeof(double));\t\t\n  \t\t\n\t\ts = N_VNew_Serial(numEq);\n\t  \tCheckMem((void *)s, \"N_VNew_Serial\");\n\t\n\t\tN_VConst_Serial(1. ,s); /* no scaling */\n\t\t\n\t\tdouble fnormtol = 1.e-6;\n\t\tdouble scsteptol = 1.e-6;\n\t\tint numIterations = 500;\n\n\t  \tkmem = KINCreate();\n\t  \tCheckMem((void *)kmem, \"KINCreate\");\n\t  \t\n\t  \tauto ErrorFun = [](int error_code, const char *module, const char *function, char *msg, void *data) {\n\t\t  \tString serror = Format(\"%d, module %s, function %s\", error_code, module, function);\n\t\t  \tif (error_code == KIN_WARNING)\n\t\t    \tCout() << Format(t_(\"Kinsol Warning (%s): %s\"), serror, msg);\n\t\t  \telse {\n\t\t  \t\tchar *str = KINGetReturnFlagName(error_code);\n\t\t  \t\tString cerror(str);\n\t\t  \t\tfree(str);\n\t\t    \tthrow Exc(Format(t_(\"Kinsol Error %s (%s): %s\"), cerror, serror, msg));\n\t\t  \t}\n\t\t};\n\t  \t\n\t  \tint flag;\n\t  \t\n\t\tflag = KINSetErrHandlerFn(kmem, ErrorFun, NULL); \n\t\tCheckRet(flag, \"KINSetErrHandlerFn\");\n\t  \t\n\t  \tstruct UserData {\n\t\t\tFunction <bool(const double y[], double residual[])> Residual;\n\t\t} userData;\n\t\t\n\t\tuserData.Residual = Residual;\t  \t\n\t  \t\n\t  \tflag = KINSetUserData(kmem, &userData);\n\t  \tCheckRet(flag, \"KINSetUserData\");\n\t\tflag = KINSetFuncNormTol(kmem, fnormtol);\n\t\tCheckRet(flag, \"KINSetFuncNormTol\");\n\t\tflag = KINSetScaledStepTol(kmem, scsteptol);\n\t\tCheckRet(flag, \"KINSetScaledStepTol\");\n\t\tflag = KINSetNumMaxIters(kmem, numIterations);\n\t  \tCheckRet(flag, \"KINSetNumMaxIters\");\n\t\t\n\t  \tauto ResFun = [](N_Vector u, N_Vector f, void *user_data) { \n\t\t\trealtype *y = NV_DATA_S(u);\n\t\t\trealtype *res = NV_DATA_S(f);\n\t\t\t\n\t\t\tUserData &userData = *(UserData *)user_data;\n\t\t\t\n\t\t\treturn userData.Residual(y, res) ? 0 : 1;\n\t\t};\n\t\t\n\t\tflag = KINInit(kmem, ResFun, u);\n\t\tCheckRet(flag, \"KINInit\");\n\t\n\t\tif (constraints != nullptr) {\n\t\t\tN_Vector constr = N_VNew_Serial(numEq);\t\n\t\t\tCheckMem((void *)constr, \"N_VNew_Serial\");\n\t\t\trealtype *constrdata = NV_DATA_S(constr);\n\t\t\tfor (int i = 0; i < numEq; ++i)\n\t\t\t\tconstrdata[i] = constraints[i];\n  \t\t\n\t\t \tflag = KINSetConstraints(kmem, constr);\n\t\t  \tCheckRet(flag, \"KINSetConstraints\");\n\t\t  \t\n\t\t\tN_VDestroy_Serial(constr);\n\t\t}\n\t\t\n\t\t/* Create dense SUNMatrix */\n\t\tSUNMatrix J = SUNDenseMatrix(numEq, numEq);\n\t\tCheckMem((void *)J, \"SUNDenseMatrix\");\n\t\t\n\t\t/* Create dense SUNLinearSolver object */\n\t\tSUNLinearSolver LS = SUNLinSol_Dense(u, J);\n\t\tCheckMem((void *)LS, \"SUNLinSol_Dense\");\n\t\t\n\t\t/* Attach the matrix and linear solver to KINSOL */\n\t\tflag = KINSetLinearSolver(kmem, LS, J);\n\t\tCheckRet(flag, \"KINSetLinearSolver\");\n\t\n\t\tint glstr = KIN_NONE;\t// KIN_NONE \t\tKIN_LINESEARCH\tUsing line search\n\t\tint mset = 1;\t\t\t// 1 Exact Newton\t0 Modified Newton\n\t\n\t\tflag = KINSetMaxSetupCalls(kmem, mset);\n\t\tCheckRet(flag, \"KINSetMaxSetupCalls\");\n\t\t\n\t\tflag = KINSol(kmem, u, glstr, s, s);\n\t\tCheckRet(flag, \"KINSol\");\n\t\t\n\t\tfor (int i = 0; i < numEq; ++i) \n\t\t\tif (udata[i] != udata[i]) \n\t\t\t\tthrow Exc(Format(t_(\"Obtained NaN in value %d\"), i));\n\t\t memcpy(y, udata, numEq*sizeof(double));\t\t\n\t\t\n  \t} catch(Exc err) {\n  \t\terror = err;\n  \t}\n \tN_VDestroy_Serial(s);\n  \tKINFree(&kmem);\n  \tif (!error.IsEmpty())\n  \t\tthrow Exc(error);\n}\n\n}\n", "meta": {"hexsha": "edb5d7ef54e9c3e2f6ab4612f478fa6de66ec09b", "size": 14817, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STEM4U/Sundials.cpp", "max_stars_repo_name": "XOULID/Anboto", "max_stars_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "STEM4U/Sundials.cpp", "max_issues_repo_name": "XOULID/Anboto", "max_issues_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "STEM4U/Sundials.cpp", "max_forks_repo_name": "XOULID/Anboto", "max_forks_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7036144578, "max_line_length": 192, "alphanum_fraction": 0.6607275427, "num_tokens": 4593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.22168374633758542}}
{"text": "#include \"farm_ng/calibration/multi_view_apriltag_rig_calibrator.h\"\n\n#include <map>\n\n#include <ceres/ceres.h>\n#include <google/protobuf/util/time_util.h>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/dijkstra_shortest_paths.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <opencv2/highgui.hpp>  // TODO remove.\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n#include <sophus/average.hpp>\n\n#include \"farm_ng/calibration/apriltag_rig_calibrator.h\"\n#include \"farm_ng/calibration/calibrator.pb.h\"\n#include \"farm_ng/calibration/camera_rig_apriltag_rig_cost_functor.h\"\n#include \"farm_ng/calibration/local_parameterization.h\"\n#include \"farm_ng/core/blobstore.h\"\n#include \"farm_ng/core/event_log_reader.h\"\n#include \"farm_ng/core/ipc.h\"\n#include \"farm_ng/perception/apriltag.h\"\n#include \"farm_ng/perception/apriltag.pb.h\"\n#include \"farm_ng/perception/camera_model.h\"\n#include \"farm_ng/perception/capture_video_dataset.pb.h\"\n#include \"farm_ng/perception/image_loader.h\"\n#include \"farm_ng/perception/image_utils.h\"\n#include \"farm_ng/perception/pose_graph.h\"\n#include \"farm_ng/perception/pose_utils.h\"\n#include \"farm_ng/perception/sophus_protobuf.h\"\n#include \"farm_ng/perception/time_series.h\"\n\nnamespace farm_ng {\nnamespace calibration {\ntypedef farm_ng::core::Event EventPb;\nusing farm_ng::core::EventLogReader;\nusing farm_ng::core::GetUniqueArchiveResource;\nusing farm_ng::core::ReadProtobufFromResource;\nusing farm_ng::core::Resource;\nusing farm_ng::perception::ApriltagDetections;\nusing farm_ng::perception::ApriltagRig;\nusing farm_ng::perception::ApriltagsFilter;\nusing farm_ng::perception::CameraModel;\nusing farm_ng::perception::PoseEdge;\n\nusing farm_ng::perception::ConstructGridImage;\nusing farm_ng::perception::FrameNameNumber;\nusing farm_ng::perception::FrameRigTag;\nusing farm_ng::perception::Image;\nusing farm_ng::perception::ImageLoader;\nusing farm_ng::perception::NamedSE3Pose;\nusing farm_ng::perception::PoseGraph;\nusing farm_ng::perception::SE3Map;\nusing farm_ng::perception::SophusToProto;\nusing farm_ng::perception::TimeSeries;\nusing Sophus::SE3d;\n\nusing farm_ng::core::Event;\nusing farm_ng::perception::CaptureVideoDatasetResult;\nusing farm_ng::perception::MultiViewApriltagDetections;\nusing Sophus::SE3d;\n\nvoid GetCameraRigPosesTagRig(const MultiViewApriltagRigModel& model,\n                             PoseGraph* pose_graph) {\n  std::string tag_rig_view_frame = model.apriltag_rig().name() + \"/view/\";\n  std::map<int, SE3d> camera_rig_poses_tag_rig;\n  for (const NamedSE3Pose& camera_rig_pose_tag_rig :\n       model.camera_rig_poses_apriltag_rig()) {\n    CHECK(camera_rig_pose_tag_rig.frame_b().rfind(tag_rig_view_frame) == 0)\n        << camera_rig_pose_tag_rig.frame_b()\n        << \" does not start with: \" << tag_rig_view_frame;\n    CHECK_EQ(camera_rig_pose_tag_rig.frame_a(), model.camera_rig().name());\n    int frame_n = std::stoi(\n        camera_rig_pose_tag_rig.frame_b().substr(tag_rig_view_frame.size()));\n    CHECK_GE(frame_n, 0);\n    CHECK_LT(frame_n, model.multi_view_detections_size());\n    pose_graph->AddPose(camera_rig_pose_tag_rig);\n  }\n}\n\nPoseGraph PoseGraphFromModel(const MultiViewApriltagRigModel& model) {\n  PoseGraph pose_graph;\n  for (const ApriltagRig::Node& node : model.apriltag_rig().nodes()) {\n    pose_graph.AddPose(node.pose());\n  }\n  pose_graph.AddPoses(model.camera_rig().camera_pose_rig());\n  GetCameraRigPosesTagRig(model, &pose_graph);\n  return pose_graph;\n}\nvoid UpdateModelFromPoseGraph(const PoseGraph& pose_graph,\n                              MultiViewApriltagRigModel* model) {\n  for (ApriltagRig::Node& node :\n       *model->mutable_apriltag_rig()->mutable_nodes()) {\n    pose_graph.UpdateNamedSE3Pose(node.mutable_pose());\n  }\n  pose_graph.UpdateNamedSE3Poses(\n      model->mutable_camera_rig()->mutable_camera_pose_rig());\n  pose_graph.UpdateNamedSE3Poses(\n      model->mutable_camera_rig_poses_apriltag_rig());\n}\n\nvoid ModelError(MultiViewApriltagRigModel* model,\n                bool output_reprojection_images) {\n  model->set_rmse(0.0);\n  model->clear_reprojection_images();\n  model->clear_tag_stats();\n  PoseGraph pose_graph = PoseGraphFromModel(*model);\n  std::string root_tag_frame = FrameRigTag(model->apriltag_rig().name(),\n                                           model->apriltag_rig().root_tag_id());\n  std::string tag_rig_frame = model->apriltag_rig().name();\n  std::string root_camera_frame = model->camera_rig().root_camera_name();\n  std::string camera_rig_frame = model->camera_rig().name();\n  int frame_num = -1;\n  double total_rmse = 0.0;\n  double total_count = 0.0;\n\n  double total_depth_error = 0.0;\n  double total_depth_count = 0.0;\n\n  std::map<int, ApriltagRigTagStats> tag_stats;\n\n  ImageLoader image_loader;\n\n  for (const auto& mv_detections : model->multi_view_detections()) {\n    frame_num++;\n    std::string tag_rig_view_frame =\n        tag_rig_frame + \"/view/\" + std::to_string(frame_num);\n\n    if (!pose_graph.HasEdge(camera_rig_frame, tag_rig_view_frame)) {\n      continue;\n    }\n    PoseEdge* camera_rig_to_tag_rig_view =\n        pose_graph.MutablePoseEdge(camera_rig_frame, tag_rig_view_frame);\n    std::vector<cv::Mat> images;\n\n    for (const auto& detections_per_view :\n         mv_detections.detections_per_view()) {\n      const auto& camera_model = detections_per_view.image().camera_model();\n      std::string camera_frame = camera_model.frame_name();\n\n      PoseEdge* camera_to_camera_rig =\n          pose_graph.MutablePoseEdge(camera_frame, camera_rig_frame);\n\n      if (output_reprojection_images) {\n        cv::Mat image = image_loader.LoadImage(detections_per_view.image());\n        if (image.channels() == 1) {\n          cv::Mat color;\n          cv::cvtColor(image, color, cv::COLOR_GRAY2BGR);\n          image = color;\n        }\n\n        for (const auto& node : model->apriltag_rig().nodes()) {\n          PoseEdge* tag_to_tag_rig =\n              pose_graph.MutablePoseEdge(node.frame_name(), tag_rig_frame);\n\n          auto camera_pose_tag =\n              camera_to_camera_rig->GetAPoseBMapped(camera_frame,\n                                                    camera_rig_frame) *\n              camera_rig_to_tag_rig_view->GetAPoseBMapped(camera_rig_frame,\n                                                          tag_rig_view_frame) *\n              tag_to_tag_rig->GetAPoseBMapped(tag_rig_frame, node.frame_name());\n          for (int i = 0; i < 4; ++i) {\n            Eigen::Vector3d point_tag(node.points_tag().Get(i).x(),\n                                      node.points_tag().Get(i).y(),\n                                      node.points_tag().Get(i).z());\n            Eigen::Vector3d point_camera = camera_pose_tag * point_tag;\n            if (point_camera.z() > 0.001) {\n              Eigen::Vector2d rp =\n                  ProjectPointToPixel(camera_model, point_camera);\n              cv::circle(image, cv::Point(rp.x(), rp.y()), 3,\n                         cv::Scalar(0, 0, 255), -1);\n            }\n          }\n          for (const auto& detection : detections_per_view.detections()) {\n            auto points_image = PointsImage(detection);\n            for (size_t i = 0; i < points_image.size(); ++i) {\n              cv::circle(image,\n                         cv::Point(points_image[i].x(), points_image[i].y()), 5,\n                         cv::Scalar(255, 0, 0));\n            }\n          }\n        }\n        images.push_back(image);\n      }\n\n      for (const auto& detection : detections_per_view.detections()) {\n        std::string tag_frame = FrameRigTag(tag_rig_frame, detection.id());\n        PoseEdge* tag_to_tag_rig =\n            pose_graph.MutablePoseEdge(tag_frame, tag_rig_frame);\n        auto points_image = PointsImage(detection);\n        CameraRigApriltagRigCostFunctor cost(\n            detections_per_view.image().camera_model(), detection,\n            camera_to_camera_rig->GetAPoseBMap(camera_frame, camera_rig_frame),\n            tag_to_tag_rig->GetAPoseBMap(tag_rig_frame, tag_frame),\n            camera_rig_to_tag_rig_view->GetAPoseBMap(camera_rig_frame,\n                                                     tag_rig_view_frame),\n            1.0);\n        Eigen::Matrix<double, 4, 3> residuals;\n        CHECK(cost(camera_to_camera_rig->GetAPoseB().data(),\n                   tag_to_tag_rig->GetAPoseB().data(),\n                   camera_rig_to_tag_rig_view->GetAPoseB().data(),\n                   residuals.data()));\n        double depth_error = 0;\n        int depth_count = 0;\n        for (int i = 0; i < 4; ++i) {\n          double d2 = residuals(i, 2) * residuals(i, 2);\n          if (d2 > 0.0) {\n            depth_error += residuals(i, 2);\n            depth_count += 1;\n          }\n        }\n        total_depth_count += depth_count;\n        total_depth_error += depth_error;\n        total_rmse += residuals.block<4, 2>(0, 0).squaredNorm();\n        total_count += 8;\n\n        ApriltagRigTagStats& stats = tag_stats[detection.id()];\n        stats.set_tag_id(detection.id());\n        stats.set_n_frames(stats.n_frames() + 1);\n        stats.set_tag_rig_rmse(stats.tag_rig_rmse() +\n                               residuals.block<4, 2>(0, 0).squaredNorm() / 8);\n        stats.set_tag_rig_depth_error(stats.tag_rig_depth_error() +\n                                      depth_error);\n        stats.set_tag_rig_depth_count(stats.tag_rig_depth_count() +\n                                      depth_count);\n\n        PerImageRmse* image_rmse = stats.add_per_image_rmse();\n        image_rmse->set_rmse(\n            std::sqrt(residuals.block<4, 2>(0, 0).squaredNorm() / 8));\n        image_rmse->set_frame_number(frame_num);\n        image_rmse->set_camera_name(\n            detections_per_view.image().camera_model().frame_name());\n        if (depth_count > 0) {\n          image_rmse->set_depth_error(  // std::sqrt\n              (depth_error / depth_count));\n        }\n      }\n    }\n    if (output_reprojection_images && !images.empty()) {\n      Image& reprojection_image = *model->add_reprojection_images();\n      int n_cols = 3;\n      int n_rows = std::ceil(float(images.size()) / n_cols);\n      if (n_cols > int(images.size())) {\n        n_cols = images.size();\n        n_rows = 1;\n      }\n\n      int image_width = images[0].size().width * n_cols;\n      int image_height = images[0].size().height * n_rows;\n      reprojection_image.mutable_camera_model()->set_image_width(image_width);\n      reprojection_image.mutable_camera_model()->set_image_height(image_height);\n      auto resource_path = GetUniqueArchiveResource(\n          FrameNameNumber(\n              \"reprojection-\" + SolverStatus_Name(model->solver_status()),\n              frame_num),\n          \"jpg\", \"image/jpeg\");\n      reprojection_image.mutable_resource()->CopyFrom(resource_path.first);\n      LOG(INFO) << resource_path.second.string();\n      CHECK(\n          cv::imwrite(resource_path.second.string(),\n                      ConstructGridImage(\n                          images, cv::Size(image_width, image_height), n_cols)))\n          << \"Could not write: \" << resource_path.second;\n    }\n  }\n  std::stringstream summary;\n  summary << \"# tag_id frame_number camera_name rmse depth_error\\n\";\n  for (auto& stats : tag_stats) {\n    for (auto& per_image : stats.second.per_image_rmse()) {\n      summary << stats.second.tag_id() << \" \" << per_image.frame_number() << \" \"\n              << per_image.camera_name() << \" \" << per_image.rmse() << \" \"\n              << per_image.depth_error() << \"\\n\";\n    }\n  }\n  for (auto& stats : tag_stats) {\n    stats.second.set_tag_rig_rmse(\n        std::sqrt(stats.second.tag_rig_rmse() / stats.second.n_frames()));\n    if (stats.second.tag_rig_depth_count() > 0) {\n      stats.second.set_tag_rig_depth_error(\n          // std::sqrt\n          (stats.second.tag_rig_depth_error() /\n           stats.second.tag_rig_depth_count()));\n    }\n\n    auto debug_stats = stats.second;\n    debug_stats.clear_per_image_rmse();\n    summary << debug_stats.DebugString() << \"\\n\\n\";\n    model->add_tag_stats()->CopyFrom(stats.second);\n  }\n  model->set_rmse(std::sqrt(total_rmse / total_count));\n  summary << \"model rmse (pixels): \" << model->rmse() << \"\\n\";\n  if (total_depth_count > 0) {\n    model->set_depth_error(  // std::sqrt\n        (total_depth_error / total_depth_count));\n    summary << \"model depth error (meters): \" << model->depth_error() << \"\\n\";\n  }\n  LOG(INFO) << \"Error Summary:\\n\" << summary.str();\n}\n\nstd::vector<MultiViewApriltagDetections> LoadMultiViewApriltagDetections(\n    const std::string& root_camera_name, const Resource& event_log,\n    const CalibrateMultiViewApriltagRigConfiguration& config) {\n  EventLogReader log_reader(event_log);\n\n  std::set<std::string> allowed_cameras;\n\n  for (auto camera_name : config.include_cameras()) {\n    allowed_cameras.insert(camera_name);\n    LOG(INFO) << \"allowed camera: \" << camera_name;\n  }\n  std::unordered_set<int> allowed_ids;\n\n  for (auto id : config.tag_ids()) {\n    allowed_ids.insert(id);\n    LOG(INFO) << \"allowed tag id: \" << id;\n  }\n\n  CHECK(allowed_ids.count(config.root_tag_id()) == 1)\n      << \"Please ensure root_tag_id is in the tag_ids list\";\n\n  std::map<std::string, TimeSeries<Event>> apriltag_series;\n\n  while (true) {\n    EventPb event;\n    try {\n      event = log_reader.ReadNext();\n    } catch (std::runtime_error& e) {\n      break;\n    }\n    ApriltagDetections unfiltered_detections;\n    if (event.data().UnpackTo(&unfiltered_detections)) {\n      auto camera_name =\n          unfiltered_detections.image().camera_model().frame_name();\n      CHECK(!camera_name.empty()) << \" camera_name is not set.\";\n      if (!allowed_cameras.empty() && !allowed_cameras.count(camera_name)) {\n        LOG(INFO) << \"skipping data from camera: \" << camera_name;\n        continue;\n      }\n      ApriltagDetections detections = unfiltered_detections;\n      detections.clear_detections();\n      for (const auto& detection : unfiltered_detections.detections()) {\n        if (allowed_ids.count(detection.id())) {\n          detections.add_detections()->CopyFrom(detection);\n        }\n      }\n      event.mutable_data()->PackFrom(detections);\n\n      event.set_name(detections.image().camera_model().frame_name() +\n                     \"/apriltags\");\n      apriltag_series[event.name()].insert(event);\n    }\n  }\n  {\n    std::stringstream ss;\n    ss << \"Raw detections\\n\";\n    for (const auto& series : apriltag_series) {\n      ss << series.first << \" \" << series.second.size() << \" detections\\n\";\n    }\n    LOG(INFO) << ss.str();\n  }\n\n  ApriltagsFilter tag_filter;\n  std::vector<MultiViewApriltagDetections> mv_detections_series;\n  auto time_window =\n      google::protobuf::util::TimeUtil::MillisecondsToDuration(1000.0 / 2);\n\n  std::map<std::string, int> detection_counts;\n  int steady_count = 5;\n  if (config.has_steady_count()) {\n    steady_count = config.steady_count().value();\n  }\n  LOG(INFO) << \"Steady count is: \" << steady_count;\n  for (const Event& event : apriltag_series[root_camera_name + \"/apriltags\"]) {\n    ApriltagDetections detections;\n    CHECK(event.data().UnpackTo(&detections));\n    if (!config.filter_stable_tags() ||\n        tag_filter.AddApriltags(detections, steady_count, 7)) {\n      MultiViewApriltagDetections mv_detections;\n      for (auto name_series : apriltag_series) {\n        auto nearest_event =\n            name_series.second.FindNearest(event.stamp(), time_window);\n        if (nearest_event) {\n          CHECK(nearest_event->data().UnpackTo(\n              mv_detections.add_detections_per_view()));\n          detection_counts[nearest_event->name()]++;\n        }\n      }\n      mv_detections_series.push_back(mv_detections);\n    }\n  }\n  {\n    std::stringstream ss;\n    ss << \"Stable multi-view detections: \" << mv_detections_series.size()\n       << \"\\n\";\n    for (const auto& name_count : detection_counts) {\n      ss << name_count.first << \" \" << name_count.second\n         << \" stable detections\\n\";\n    }\n    LOG(INFO) << ss.str();\n  }\n\n  return mv_detections_series;\n}\n\nPoseGraph TagRigFromMultiViewDetections(std::string tag_rig_name,\n                                        int root_tag_id,\n                                        MultiViewApriltagRigModel* model) {\n  model->mutable_apriltag_rig()->set_name(tag_rig_name);\n  model->mutable_apriltag_rig()->set_root_tag_id(root_tag_id);\n\n  PoseGraph tag_rig;\n  std::map<int, ApriltagRig::Node> tag_rig_nodes;\n\n  for (const auto& mv_detections : model->multi_view_detections()) {\n    for (const auto& detections_per_view :\n         mv_detections.detections_per_view()) {\n      if (detections_per_view.detections_size() <= 1) {\n        continue;\n      }\n      for (const auto& detection : detections_per_view.detections()) {\n        if (tag_rig_nodes.count(detection.id())) {\n          continue;\n        }\n        ApriltagRig::Node node;\n        node.set_id(detection.id());\n        node.set_frame_name(FrameRigTag(tag_rig_name, detection.id()));\n        node.set_tag_size(detection.tag_size());\n        for (const auto& v : PointsTag(detection)) {\n          EigenToProto(v, node.add_points_tag());\n        }\n        tag_rig_nodes.emplace(detection.id(), std::move(node));\n      }\n      for (int i = 0; i < detections_per_view.detections_size() - 1; ++i) {\n        for (int j = i + 1; j < detections_per_view.detections_size(); ++j) {\n          const auto& detection_i = detections_per_view.detections().Get(i);\n          const auto& detection_j = detections_per_view.detections().Get(j);\n          Sophus::SE3d c_pose_i, c_pose_j;\n          CHECK_EQ(detection_i.pose().frame_a(), detection_j.pose().frame_a());\n          ProtoToSophus(detection_i.pose().a_pose_b(), &c_pose_i);\n          ProtoToSophus(detection_j.pose().a_pose_b(), &c_pose_j);\n          tag_rig.AddPose(detection_i.pose().frame_b(),\n                          detection_j.pose().frame_b(),\n                          c_pose_i.inverse() * c_pose_j);\n        }\n      }\n    }\n  }\n  std::string root_tag = \"tag/\" + std::to_string(root_tag_id);\n\n  auto tag_rig_small = tag_rig.AveragePoseGraph(root_tag);\n\n  for (auto& node : tag_rig_nodes) {\n    std::string tag = \"tag/\" + std::to_string(node.first);\n    auto root_pose_tag = tag_rig_small.AverageAPoseB(root_tag, tag);\n    if (!root_pose_tag) {\n      continue;\n    }\n    SophusToProto(*root_pose_tag, tag_rig_name, node.second.frame_name(),\n                  node.second.mutable_pose());\n    model->mutable_apriltag_rig()->add_nodes()->CopyFrom(node.second);\n  }\n  return tag_rig_small;\n}\n\nvoid CameraRigFromMultiViewDetections(std::string camera_rig_name,\n                                      std::string root_camera_name,\n                                      const PoseGraph& tag_rig,\n                                      MultiViewApriltagRigModel* model) {\n  model->mutable_camera_rig()->set_root_camera_name(root_camera_name);\n  model->mutable_camera_rig()->set_name(camera_rig_name);\n\n  std::string root_tag_name =\n      \"tag/\" + std::to_string(model->apriltag_rig().root_tag_id());\n  PoseGraph camera_rig_inter;\n  PoseGraph camera_rig_tags;\n\n  int frame_num = -1;\n\n  std::map<std::string, CameraModel> camera_models;\n  for (const auto& mv_detections : model->multi_view_detections()) {\n    frame_num++;\n    PoseGraph camera_rig_step_i;\n\n    camera_rig_step_i.AddPose(camera_rig_name, root_camera_name, SE3d::rotX(0));\n\n    for (const auto& detections_per_view :\n         mv_detections.detections_per_view()) {\n      if (detections_per_view.detections_size() < 1) {\n        continue;\n      }\n      camera_models.emplace(\n          detections_per_view.image().camera_model().frame_name(),\n          detections_per_view.image().camera_model());\n\n      for (const auto& detection : detections_per_view.detections()) {\n        Sophus::SE3d c_pose_tag;\n        ProtoToSophus(detection.pose().a_pose_b(), &c_pose_tag);\n        auto o_tag_pose_root_tag =\n            tag_rig.AverageAPoseB(detection.pose().frame_b(), root_tag_name);\n        if (!o_tag_pose_root_tag) {\n          LOG(WARNING) << \"Unable to compute pose for: \"\n                       << detection.pose().frame_b() << \" <- \" << root_tag_name;\n          continue;\n        }\n        auto c_pose_root_tag = c_pose_tag * (*o_tag_pose_root_tag);\n        camera_rig_step_i.AddPose(detection.pose().frame_a(), root_tag_name,\n                                  c_pose_root_tag);\n      }\n    }\n    if (!camera_rig_step_i.HasName(root_camera_name)) {\n      continue;\n    }\n    auto camera_rig_i = camera_rig_step_i.AveragePoseGraph(camera_rig_name);\n\n    for (auto es = camera_rig_i.Edges(); es.first != es.second; es.first++) {\n      auto edge = camera_rig_i.PoseEdgeMap()[*es.first];\n      std::string frame_a = edge.frame_a;\n      std::string frame_b = edge.frame_b;\n      if (frame_a == root_tag_name || frame_b == root_tag_name) {\n        std::string rig_frame_name =\n            model->apriltag_rig().name() + \"/view/\" + std::to_string(frame_num);\n        if (frame_a == root_tag_name) {\n          frame_a = rig_frame_name;\n        }\n        if (frame_b == root_tag_name) {\n          frame_b = rig_frame_name;\n        }\n        camera_rig_tags.AddPose(frame_a, frame_b, edge.GetAPoseB());\n      } else {\n        camera_rig_inter.AddPose(frame_a, frame_b, edge.GetAPoseB());\n      }\n    }\n  }\n  for (auto camera : camera_models) {\n    model->mutable_camera_rig()->add_cameras()->CopyFrom(camera.second);\n  }\n\n  model->mutable_camera_rig()->mutable_camera_pose_rig()->CopyFrom(\n      camera_rig_inter.AveragePoseGraph(camera_rig_name).ToNamedSE3Poses());\n\n  model->mutable_camera_rig_poses_apriltag_rig()->CopyFrom(\n      camera_rig_tags.AveragePoseGraph(camera_rig_name).ToNamedSE3Poses());\n}\n\nMultiViewApriltagRigModel InitialMultiViewApriltagModelFromConfig(\n    const CalibrateMultiViewApriltagRigConfiguration& config) {\n  core::Resource event_log;\n  switch (config.input_case()) {\n    case CalibrateMultiViewApriltagRigConfiguration::InputCase::kVideoDataset: {\n      auto dataset_result = ReadProtobufFromResource<CaptureVideoDatasetResult>(\n          config.video_dataset());\n      event_log = dataset_result.dataset();\n      break;\n    }\n    case CalibrateMultiViewApriltagRigConfiguration::InputCase::kEventLog: {\n      event_log = config.event_log();\n      break;\n    }\n    default:\n      LOG(FATAL) << \"No input provided in config.\";\n  }\n  MultiViewApriltagRigModel model;\n  for (const auto& mv_detections : LoadMultiViewApriltagDetections(\n           config.root_camera_name(), event_log, config)) {\n    model.add_multi_view_detections()->CopyFrom(mv_detections);\n  }\n  auto tag_rig = TagRigFromMultiViewDetections(config.tag_rig_name(),\n                                               config.root_tag_id(), &model);\n  CameraRigFromMultiViewDetections(config.name(), config.root_camera_name(),\n                                   tag_rig, &model);\n\n  model.set_solver_status(SolverStatus::SOLVER_STATUS_INITIAL);\n  return model;\n}\n\nMultiViewApriltagRigModel SolveMultiViewApriltagModel(\n    MultiViewApriltagRigModel model) {\n  PoseGraph pose_graph = PoseGraphFromModel(model);\n  double depth_weight = 100.0;\n  ceres::Problem problem;\n  for (PoseEdge* pose_edge : pose_graph.MutablePoseEdges()) {\n    LOG(INFO) << *pose_edge;\n    problem.AddParameterBlock(pose_edge->GetAPoseB().data(),\n                              SE3d::num_parameters,\n                              new LocalParameterizationSE3);\n  }\n  std::string root_tag_frame = FrameRigTag(model.apriltag_rig().name(),\n                                           model.apriltag_rig().root_tag_id());\n  std::string tag_rig_frame = model.apriltag_rig().name();\n  problem.SetParameterBlockConstant(\n      pose_graph.MutablePoseEdge(root_tag_frame, tag_rig_frame)\n          ->GetAPoseB()\n          .data());\n\n  std::string root_camera_frame = model.camera_rig().root_camera_name();\n  std::string camera_rig_frame = model.camera_rig().name();\n\n  problem.SetParameterBlockConstant(\n      pose_graph.MutablePoseEdge(root_camera_frame, camera_rig_frame)\n          ->GetAPoseB()\n          .data());\n\n  int frame_num = -1;\n  for (const auto& mv_detections : model.multi_view_detections()) {\n    frame_num++;\n\n    std::string tag_rig_view_frame =\n        tag_rig_frame + \"/view/\" + std::to_string(frame_num);\n\n    if (!pose_graph.HasEdge(camera_rig_frame, tag_rig_view_frame)) {\n      continue;\n    }\n\n    PoseEdge* camera_rig_to_tag_rig_view =\n        pose_graph.MutablePoseEdge(camera_rig_frame, tag_rig_view_frame);\n\n    for (const auto& detections_per_view :\n         mv_detections.detections_per_view()) {\n      if (detections_per_view.detections_size() < 1) {\n        continue;\n      }\n      std::string camera_frame =\n          detections_per_view.image().camera_model().frame_name();\n\n      PoseEdge* camera_to_camera_rig =\n          pose_graph.MutablePoseEdge(camera_frame, camera_rig_frame);\n\n      for (const auto& detection : detections_per_view.detections()) {\n        std::string tag_frame = FrameRigTag(tag_rig_frame, detection.id());\n        PoseEdge* tag_to_tag_rig =\n            pose_graph.MutablePoseEdge(tag_frame, tag_rig_frame);\n\n        ceres::CostFunction* cost_function1 = new ceres::AutoDiffCostFunction<\n            CameraRigApriltagRigCostFunctor, 12, Sophus::SE3d::num_parameters,\n            Sophus::SE3d::num_parameters, Sophus::SE3d::num_parameters>(\n            new CameraRigApriltagRigCostFunctor(\n                detections_per_view.image().camera_model(), detection,\n                camera_to_camera_rig->GetAPoseBMap(camera_frame,\n                                                   camera_rig_frame),\n                tag_to_tag_rig->GetAPoseBMap(tag_rig_frame, tag_frame),\n                camera_rig_to_tag_rig_view->GetAPoseBMap(camera_rig_frame,\n                                                         tag_rig_view_frame),\n                depth_weight));\n        problem.AddResidualBlock(\n            cost_function1, new ceres::CauchyLoss(1.0),\n            camera_to_camera_rig->GetAPoseB().data(),\n            tag_to_tag_rig->GetAPoseB().data(),\n            camera_rig_to_tag_rig_view->GetAPoseB().data());\n      }\n    }\n  }\n\n  // Set solver options (precision / method)\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::SPARSE_SCHUR;\n  options.gradient_tolerance = 1e-18;\n  options.function_tolerance = 1e-18;\n  options.parameter_tolerance = 1e-18;\n  options.max_num_iterations = 2000;\n\n  // Solve\n  ceres::Solver::Summary summary;\n  options.logging_type = ceres::PER_MINIMIZER_ITERATION;\n  options.minimizer_progress_to_stdout = true;\n  ceres::Solve(options, &problem, &summary);\n  LOG(INFO) << summary.FullReport() << std::endl;\n  if (summary.termination_type == ceres::CONVERGENCE) {\n    model.set_solver_status(SolverStatus::SOLVER_STATUS_CONVERGED);\n  } else {\n    model.set_solver_status(SolverStatus::SOLVER_STATUS_FAILED);\n  }\n  UpdateModelFromPoseGraph(pose_graph, &model);\n  return model;\n}\n\nstd::optional<NamedSE3Pose> CameraRigPoseApriltagRigEstimateAverage(\n    const perception::MultiViewCameraRig& camera_rig,\n    const perception::ApriltagRig& apriltag_rig,\n    const perception::MultiViewApriltagDetections& mv_detections,\n    PoseGraph* pose_graph) {\n  perception::ApriltagRigIdMap tag_id_map;\n  tag_id_map.AddRig(apriltag_rig);\n\n  *pose_graph = PoseGraph();\n\n  for (const ApriltagRig::Node& node : apriltag_rig.nodes()) {\n    pose_graph->AddPose(node.pose());\n  }\n  pose_graph->AddPoses(camera_rig.camera_pose_rig());\n  for (const auto& detections_per_view : mv_detections.detections_per_view()) {\n    for (const auto& detection : detections_per_view.detections()) {\n      auto frame_names = tag_id_map.GetFrameNames(detection.id());\n      if (!frame_names) {\n        continue;\n      }\n      CHECK_EQ(detections_per_view.image().camera_model().frame_name(),\n               detection.pose().frame_a());\n\n      Sophus::SE3d c_pose_tag;\n      ProtoToSophus(detection.pose().a_pose_b(), &c_pose_tag);\n\n      auto tag_pose_tag_rig = pose_graph->CheckAverageAPoseB(\n          frame_names->tag_frame, frame_names->rig_frame);\n\n      auto camera_rig_pose_camera = pose_graph->CheckAverageAPoseB(\n          camera_rig.name(),\n          detections_per_view.image().camera_model().frame_name());\n\n      auto camera_rig_pose_tag_rig =\n          camera_rig_pose_camera * c_pose_tag * tag_pose_tag_rig;\n      pose_graph->AddPose(camera_rig.name(), apriltag_rig.name(),\n                          camera_rig_pose_tag_rig);\n    }\n  }\n  if (pose_graph->HasEdge(camera_rig.name(), apriltag_rig.name())) {\n    auto edge =\n        pose_graph->MutablePoseEdge(camera_rig.name(), apriltag_rig.name());\n\n    LOG(INFO) << camera_rig.name() << \" <- \" << apriltag_rig.name()\n              << \" has: \" << edge->a_poses_b.size() << \" estimates.\";\n    edge->Collapse();\n  }\n  return pose_graph->AverageNamedSE3Pose(camera_rig.name(),\n                                         apriltag_rig.name());\n}\n\nstd::optional<std::tuple<perception::NamedSE3Pose, double,\n                         std::vector<ApriltagRigTagStats>>>\nEstimateMultiViewCameraRigPoseApriltagRig(\n    const perception::MultiViewCameraRig& camera_rig,\n    const perception::ApriltagRig& apriltag_rig,\n    const perception::MultiViewApriltagDetections& mv_detections) {\n  PoseGraph pose_graph;\n  auto o_camera_rig_pose_tag_rig = CameraRigPoseApriltagRigEstimateAverage(\n      camera_rig, apriltag_rig, mv_detections, &pose_graph);\n  if (!o_camera_rig_pose_tag_rig) {\n    return std::nullopt;\n  }\n  double depth_weight = 100.0;\n  ceres::Problem problem;\n  for (PoseEdge* pose_edge : pose_graph.MutablePoseEdges()) {\n    VLOG(2) << *pose_edge;\n    problem.AddParameterBlock(pose_edge->GetAPoseB().data(),\n                              SE3d::num_parameters,\n                              new LocalParameterizationSE3);\n    if (!pose_edge->HasFrames(camera_rig.name(), apriltag_rig.name())) {\n      problem.SetParameterBlockConstant(pose_edge->GetAPoseB().data());\n    }\n  }\n\n  PoseEdge* camera_rig_to_tag_rig =\n      pose_graph.MutablePoseEdge(camera_rig.name(), apriltag_rig.name());\n\n  std::map<int, ApriltagRigTagStats> tag_stats;\n  std::map<int, std::vector<std::tuple<PerImageRmse, ceres::ResidualBlockId>>>\n      tag_id_to_per_image_rmse_block_id;\n\n  for (const auto& detections_per_view : mv_detections.detections_per_view()) {\n    if (detections_per_view.detections_size() < 1) {\n      continue;\n    }\n    std::string camera_frame =\n        detections_per_view.image().camera_model().frame_name();\n\n    PoseEdge* camera_to_camera_rig =\n        pose_graph.MutablePoseEdge(camera_frame, camera_rig.name());\n\n    for (const auto& detection : detections_per_view.detections()) {\n      std::string tag_frame = FrameRigTag(apriltag_rig.name(), detection.id());\n      if (!pose_graph.HasEdge(tag_frame, apriltag_rig.name())) {\n        continue;\n      }\n      ApriltagRigTagStats& stats = tag_stats[detection.id()];\n      stats.set_tag_id(detection.id());\n      stats.set_n_frames(stats.n_frames() + 1);\n\n      PoseEdge* tag_to_tag_rig =\n          pose_graph.MutablePoseEdge(tag_frame, apriltag_rig.name());\n\n      ceres::CostFunction* cost_function1 = new ceres::AutoDiffCostFunction<\n          CameraRigApriltagRigCostFunctor, 12, Sophus::SE3d::num_parameters,\n          Sophus::SE3d::num_parameters, Sophus::SE3d::num_parameters>(\n          new CameraRigApriltagRigCostFunctor(\n              detections_per_view.image().camera_model(), detection,\n              camera_to_camera_rig->GetAPoseBMap(camera_frame,\n                                                 camera_rig.name()),\n              tag_to_tag_rig->GetAPoseBMap(apriltag_rig.name(), tag_frame),\n              camera_rig_to_tag_rig->GetAPoseBMap(camera_rig.name(),\n                                                  apriltag_rig.name()),\n              depth_weight));\n      auto block_id =\n          problem.AddResidualBlock(cost_function1, new ceres::CauchyLoss(1.0),\n                                   camera_to_camera_rig->GetAPoseB().data(),\n                                   tag_to_tag_rig->GetAPoseB().data(),\n                                   camera_rig_to_tag_rig->GetAPoseB().data());\n      PerImageRmse per_image_rmse;\n      per_image_rmse.set_frame_number(0);\n      per_image_rmse.set_camera_name(camera_frame);\n\n      tag_id_to_per_image_rmse_block_id[detection.id()].push_back(\n          std::make_tuple(per_image_rmse, block_id));\n    }\n  }\n\n  // Set solver options (precision / method)\n  ceres::Solver::Options options;\n  options.linear_solver_type = ceres::SPARSE_SCHUR;\n  options.gradient_tolerance = 1e-18;\n  options.function_tolerance = 1e-18;\n  options.parameter_tolerance = 1e-18;\n  options.max_num_iterations = 2000;\n\n  // Solve\n  ceres::Solver::Summary summary;\n  // options.logging_type = ceres::PER_MINIMIZER_ITERATION;\n  // options.minimizer_progress_to_stdout = true;\n  ceres::Solve(options, &problem, &summary);\n  VLOG(2) << summary.FullReport() << std::endl;\n  if (!summary.IsSolutionUsable()) {\n    return std::nullopt;\n  }\n  double total_depth_count = 0;\n  double total_depth_error = 0;\n  double total_rmse = 0.0;\n  double total_count = 0;\n  std::vector<ApriltagRigTagStats> out_tag_stats;\n  for (auto it : tag_id_to_per_image_rmse_block_id) {\n    int tag_id = it.first;\n    auto& stats = tag_stats[tag_id];\n    for (auto per_image_rmse_block : it.second) {\n      auto [image_rmse, block] = per_image_rmse_block;\n      double cost;\n      Eigen::Matrix<double, 4, 3> residuals;\n      problem.EvaluateResidualBlockAssumingParametersUnchanged(\n          block, false, &cost, residuals.data(), nullptr);\n      double depth_error = 0;\n      int depth_count = 0;\n      for (int i = 0; i < 4; ++i) {\n        double d2 = residuals(i, 2) * residuals(i, 2);\n        if (d2 > 0.0) {\n          depth_error += residuals(i, 2) / depth_weight;\n          depth_count += 1;\n        }\n      }\n      total_depth_count += depth_count;\n      total_depth_error += depth_error;\n      total_rmse += residuals.block<4, 2>(0, 0).squaredNorm();\n      total_count += 8;\n\n      stats.set_tag_rig_rmse(stats.tag_rig_rmse() +\n                             residuals.block<4, 2>(0, 0).squaredNorm() / 8);\n      stats.set_tag_rig_depth_error(stats.tag_rig_depth_error() + depth_error);\n      stats.set_tag_rig_depth_count(stats.tag_rig_depth_count() + depth_count);\n\n      image_rmse.set_rmse(\n          std::sqrt(residuals.block<4, 2>(0, 0).squaredNorm() / 8));\n\n      if (depth_count > 0) {\n        image_rmse.set_depth_error(  // std::sqrt\n            (depth_error / depth_count));\n      }\n      stats.add_per_image_rmse()->CopyFrom(image_rmse);\n    }\n    stats.set_tag_rig_rmse(std::sqrt(stats.tag_rig_rmse() / stats.n_frames()));\n    if (stats.tag_rig_depth_count() > 0) {\n      stats.set_tag_rig_depth_error(\n          // std::sqrt\n          (stats.tag_rig_depth_error() / stats.tag_rig_depth_count()));\n    }\n    out_tag_stats.push_back(stats);\n  }\n  double rmse = std::sqrt(total_rmse / total_count);\n  std::stringstream ss;\n  ss << \"model rmse (pixels): \" << rmse << \"\\n\";\n  double depth_error = 0;\n  if (total_depth_count > 0) {\n    depth_error = (total_depth_error / total_depth_count);\n    ss << \"model depth error (meters): \" << depth_error << \"\\n\";\n  }\n\n  auto pose = pose_graph.CheckAverageNamedSE3Pose(camera_rig.name(),\n                                                  apriltag_rig.name());\n\n  LOG(INFO) << \"Solved pose:\" << pose.ShortDebugString() << \"\\n\" << ss.str();\n  return {{pose, rmse, out_tag_stats}};\n}\n}  // namespace calibration\n}  // namespace farm_ng\n", "meta": {"hexsha": "c0a76455f377063e7d070a452444f5e369747ece", "size": 35386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/calibration/cpp/farm_ng/calibration/multi_view_apriltag_rig_calibrator.cpp", "max_stars_repo_name": "ethanrublee/tractor", "max_stars_repo_head_hexsha": "f76da65ccb34d2d09d90559b53df4874f5770c09", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "modules/calibration/cpp/farm_ng/calibration/multi_view_apriltag_rig_calibrator.cpp", "max_issues_repo_name": "ethanrublee/tractor", "max_issues_repo_head_hexsha": "f76da65ccb34d2d09d90559b53df4874f5770c09", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/calibration/cpp/farm_ng/calibration/multi_view_apriltag_rig_calibrator.cpp", "max_forks_repo_name": "ethanrublee/tractor", "max_forks_repo_head_hexsha": "f76da65ccb34d2d09d90559b53df4874f5770c09", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.8042744657, "max_line_length": 80, "alphanum_fraction": 0.6530831402, "num_tokens": 8910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.38121955219593834, "lm_q1q2_score": 0.2216041094359542}}
{"text": "#pragma once\n#include <memory>\n#include <iostream>\n#include <vector>\n#include <Eigen/Core>\n#include <OpenMesh/Core/Mesh/PolyConnectivity.hh>\n#include \"../../container_cast.hh\"\n#include \"geodesic/geodesic_algorithm_dijkstra.h\"\n#include \"geodesic/geodesic_algorithm_exact.h\"\n#include \"geodesic/geodesic_algorithm_subdivision.h\"\n\nnamespace kt84 {\n\n    struct GeodesicPoint {\n        OpenMesh::PolyConnectivity::VHandle vhandle;\n        OpenMesh::PolyConnectivity::EHandle ehandle;\n        OpenMesh::PolyConnectivity::FHandle fhandle;\n        Eigen::Vector2d ecoord;         // barycentric coord for edge\n        Eigen::Vector3d fcoord;         // barycentric coord for face\n        GeodesicPoint(){}\n        GeodesicPoint(OpenMesh::PolyConnectivity::VHandle vhandle) : vhandle(vhandle) {}\n        GeodesicPoint(OpenMesh::PolyConnectivity::EHandle ehandle, const Eigen::Vector2d& ecoord) : ehandle(ehandle), ecoord(ecoord) {}\n        GeodesicPoint(OpenMesh::PolyConnectivity::FHandle fhandle, const Eigen::Vector3d& fcoord) : fhandle(fhandle), fcoord(fcoord) {}\n        GeodesicPoint(const geodesic::SurfacePoint& p) {\n            switch (p.type()) {\n            case geodesic::VERTEX:\n                vhandle = OpenMesh::PolyConnectivity::VHandle(p.base_element()->id());\n                break;\n            case geodesic::EDGE:\n                ehandle = OpenMesh::PolyConnectivity::EHandle(p.base_element()->id());\n                break;\n            }\n        }\n        operator geodesic::SurfacePoint() const {\n            geodesic::SurfacePoint p;\n            if (is_vertex()) {\n                \n            }\n            //...\n            return p;\n        }\n        bool is_vertex() const { return vhandle.is_valid(); }\n        bool is_edge  () const { return ehandle.is_valid(); }\n        bool is_face  () const { return fhandle.is_valid(); }\n    };\n    \n    template <class TMeshBase, class TMesh>\n    struct Geodesic : public DerivedPtrHolder<TMesh, Geodesic <TMeshBase, TMesh>> {\n        void geodesic_init() {\n            auto mesh = get_mesh();\n            std::vector<double> points;\n            points.reserve(mesh->n_vertices() * 3);\n            for (auto v : mesh->vertices()) {\n                auto p = mesh->point(v);\n                points.push_back(p[0]);\n                points.push_back(p[1]);\n                points.push_back(p[2]);\n            }\n            std::vector<unsigned> faces;\n            faces.reserve(mesh->n_faces() * 3);\n            for (auto f : mesh->faces()) {\n                if (mesh->valence(f) != 3) {\n                    std::cerr << \"Error: geodesic algorithm does not work on polygonal meshes!\\n\";\n                    assert(false);\n                }\n                for (auto v : mesh->fv_range(f))\n                    faces.push_back(v.idx());\n            }\n            geodesic.mesh.initialize_mesh_data(points, faces);\n            geodesic_set_algorithm_exact();      // default setting\n        }\n        void geodesic_set_algorithm_exact() {\n            geodesic.algorithm = std::make_shared<geodesic::GeodesicAlgorithmExact>(&geodesic.mesh);\n        }\n        void geodesic_set_algorithm_dijkstra() {\n            geodesic.algorithm = std::make_shared<geodesic::GeodesicAlgorithmDijkstra>(&geodesic.mesh);\n        }\n        void geodesic_set_algorithm_subdivision(int subdivision_level) {\n            geodesic.algorithm = std::make_shared<geodesic::GeodesicAlgorithmSubdivision>(&geodesic.mesh, subdivision_level);\n        }\n        std::vector<GeodesicPoint> geodesic_compute(const GeodesicPoint& source, const GeodesicPoint& target) {\n            assert(geodesic.algorithm);\n            std::vector<geodesic::SurfacePoint> path;\n            geodesic::SurfacePoint source_(source), target_(target);\n            geodesic.algorithm->geodesic(source_, target_, path);\n            return container_cast<GeodesicPoint>(path);\n        }\n        struct Data {\n            geodesic::Mesh mesh;\n            std::shared_ptr<geodesic::GeodesicAlgorithmBase> algorithm;\n            Data() {}\n            Data(const Data& src)\n                : mesh(src.mesh)\n            {\n                switch (src.algorithm->type()) {\n                case geodesic::GeodesicAlgorithmBase::EXACT:\n                    algorithm = std::make_shared<geodesic::GeodesicAlgorithmExact>(&mesh);\n                    break;\n                case geodesic::GeodesicAlgorithmBase::DIJKSTRA:\n                    algorithm = std::make_shared<geodesic::GeodesicAlgorithmDijkstra>(&mesh);\n                    break;\n                case geodesic::GeodesicAlgorithmBase::SUBDIVISION:\n                {\n                    auto subdivision_level = static_cast<geodesic::GeodesicAlgorithmSubdivision*>(algorithm.get())->subdivision_level();\n                    algorithm = std::make_shared<geodesic::GeodesicAlgorithmSubdivision>(&mesh, subdivision_level);\n                    break;\n                }\n                default:\n                    assert(false);\n                }\n            }\n            Data& Data::operator=(const Data& src) {\n                mesh = src.mesh;\n                switch (src.algorithm->type()) {\n                case geodesic::GeodesicAlgorithmBase::EXACT:\n                    algorithm = std::make_shared<geodesic::GeodesicAlgorithmExact>(&mesh);\n                    break;\n                case geodesic::GeodesicAlgorithmBase::DIJKSTRA:\n                    algorithm = std::make_shared<geodesic::GeodesicAlgorithmDijkstra>(&mesh);\n                    break;\n                case geodesic::GeodesicAlgorithmBase::SUBDIVISION:\n                {\n                    auto subdivision_level = static_cast<geodesic::GeodesicAlgorithmSubdivision*>(algorithm.get())->subdivision_level();\n                    algorithm = std::make_shared<geodesic::GeodesicAlgorithmSubdivision>(&mesh, subdivision_level);\n                    break;\n                }\n                default:\n                    assert(false);\n                }\n                return *this;\n            }\n        } geodesic;\n    private:\n        const TMesh* get_mesh() const { return DerivedPtrHolder<TMesh, Geodesic<TMeshBase, TMesh>>::derived_ptr; }\n    };\n}\n", "meta": {"hexsha": "009c95ccccbd01e97dadb0f14a0ea65dfcb88e45", "size": 6159, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/kt84/openmesh/base/TODO_Geodesic.hh", "max_stars_repo_name": "honoriocassiano/skbar", "max_stars_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kt84/openmesh/base/TODO_Geodesic.hh", "max_issues_repo_name": "honoriocassiano/skbar", "max_issues_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2020-09-01T12:16:28.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-01T12:21:41.000Z", "max_forks_repo_path": "src/kt84/openmesh/base/TODO_Geodesic.hh", "max_forks_repo_name": "honoriocassiano/skbar", "max_forks_repo_head_hexsha": "e2a8fca752f5a2f9d9a32f19cbe1f9032a0e1ac4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.9562043796, "max_line_length": 136, "alphanum_fraction": 0.572495535, "num_tokens": 1370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.3812195521959384, "lm_q1q2_score": 0.2216041039055401}}
{"text": "#include \"abstract_sph.hpp\"\n#include \"generic/is_finite.hpp\"\n#include \"generic/eigen.hpp\"\n\n#include <boost/log/trivial.hpp>\n\nnamespace GooBalls {\n\nnamespace d2 {\n\nnamespace Physics {\n\n#define INLINE_KERNELS 1\n\nvoid AbstractSph::initFluid(Scene& scene) {\n    BOOST_LOG_TRIVIAL(trace) << \"AbstractSph: initializing\";\n    const auto& pos = scene.fluid->particles_position();\n    int PN = pos.rows();\n    BOOST_LOG_TRIVIAL(trace) << \"Found \" << PN << \" fluid particles.\";\n    if(PN != scene.fluid->particles_velocity().rows()){\n        // by default, give the particles no speed\n        BOOST_LOG_TRIVIAL(warning) << \"No proper fluid particle velocity set, setting to zero.\";\n        scene.fluid->particles_velocity().setOnes(PN, Eigen::NoChange);\n    }\n    if(PN != scene.fluid->particles_mass().rows()){\n        BOOST_LOG_TRIVIAL(warning) << \"No proper fluid particle mass set, setting to ones.\";\n        scene.fluid->particles_mass().setOnes(PN);\n    }\n    if(PN != scene.fluid->particles_velocity_correction().rows()){\n        BOOST_LOG_TRIVIAL(warning) << \"No proper fluid particle velocity correction coefficients set, setting to 1.\";\n        scene.fluid->particles_velocity_correction().resize(PN, Eigen::NoChange);\n        scene.fluid->particles_velocity_correction().array() = 0.001;\n    }\n    if(PN != scene.fluid->particles_external_force().rows()){\n        BOOST_LOG_TRIVIAL(warning) << \"No proper external particle force set, setting zero.\";\n        scene.fluid->particles_external_force().setZero(PN, 2);\n    }\n\n\n    scene.fluid->particles_density().setZero(PN, 1);\n    scene.fluid->particles_total_force().setZero(PN, 2);\n    scene.fluid->particles_pressure().setZero(PN, 1);\n\n    scene.fluid->boundary_force().setZero(scene.fluid->boundary_position().rows(), 2);\n\n    FGravity.setZero(PN, 2);\n    FPressure.setZero(PN, 2);\n    FSurface.setZero(PN, 2);\n    FViscosity.setZero(PN, 2);\n\n\n    // initialize with some rough values such that the first frame looks ok\n    assert(scene.fluid->rest_density() > 0);\n    scene.fluid->particles_density().array() = scene.fluid->rest_density();\n    computeFluidPressure(scene);\n    BOOST_LOG_TRIVIAL(trace) << \"Abstract fluid initialized\";\n}\n\nvoid AbstractSph::prepareFluid(Scene& scene) const {\n    assert(scene.fluid.get() != nullptr);\n    assert(scene.fluid->sanity_check());\n    const auto& pos = scene.fluid->particles_position();\n    assert(is_finite(pos));\n    scene.fluid->fluid_neighborhood->inRange(pos, scene.fluid->h());\n}\n\nvoid AbstractSph::prepareBoundary(Scene& scene) const {\n    Coordinates1d& psi = scene.fluid->boundary_psi();\n    Float rho0 = scene.fluid->rest_density();\n    psi = rho0 * scene.fluid->boundary_volume();\n    auto h = scene.fluid->h();\n    scene.fluid->boundary_neighborhood->inRange(scene.fluid->particles_position(), scene.fluid->boundary_position(), h);\n}\n\nvoid AbstractSph::advance(Scene& scene, TimeStep dt){\n    if(scene.fluid.get() == nullptr){\n        return;\n    }\n    computeTotalForce(scene, dt);\n    // a_i = f_i / rho_i\n    const auto& rho = scene.fluid->particles_density();\n    const auto& Ftotal = scene.fluid->particles_total_force();\n    Coordinates2d a(rho.rows(), 2);\n    a.col(0) = Ftotal.col(0).array() / rho.array();\n    a.col(1) = Ftotal.col(1).array() / rho.array();\n    auto& pos = scene.fluid->particles_position();\n    auto& vs = scene.fluid->particles_velocity();\n    vs = vs + dt * a;\n    scene.room.restrictFluid(* scene.fluid);\n    pos = pos + dt * vs;\n    limitVelocity(scene);\n    assert(is_finite(pos));\n    assert(is_finite(vs));\n}\n\nvoid AbstractSph::computeGravityForce(const Scene& scene) {\n    const auto& rho = scene.fluid->particles_density();\n    FGravity.col(0) = scene.gravity[0] * rho;\n    FGravity.col(1) = scene.gravity[1] * rho;\n}\n\nvoid AbstractSph::computeFluidPressure(Scene& scene) const {\n    auto rho0 = scene.fluid->rest_density();\n    auto pressure_gamma = scene.fluid->pressure_gamma();\n    const auto& rho = scene.fluid->particles_density();\n    auto& ps = scene.fluid->particles_pressure();\n    auto K = scene.fluid->stiffnessConstant();\n    //ps = K * (rho.array() - rho0);\n    ps = K * rho0 / pressure_gamma * ((rho.array()/rho0).pow(pressure_gamma) - 1.0);\n    ps = ps.array().max(0);\n    assert(is_finite(ps));\n}\n\nvoid AbstractSph::computeStandardPressureForce(const Scene& scene, const Kernel& pressureKernel){\n    const auto& pos = scene.fluid->particles_position();\n    const auto& ms = scene.fluid->particles_mass();\n    const auto& rho = scene.fluid->particles_density();\n    const auto& ps = scene.fluid->particles_pressure();\n    int PN = pos.rows();\n    const auto& fluid_index = scene.fluid->fluid_neighborhood->indexes();\n    Coordinates2d jpos, jGrad, jPress;\n    for(int i = 0; i < PN; ++i){\n        const auto& index = fluid_index[i];\n        minSize(jPress, index.size());\n        pickRows(pos, index, jpos);\n        auto xij = -(jpos.rowwise() - pos.row(i));\n        pressureKernel.compute(xij, nullptr, &jGrad, nullptr);\n        for(size_t j = 0; j < index.size(); ++j){\n            int jj = index[j];\n            jPress.row(j) = ms[jj] / rho[jj] * (ps[jj] + ps[i]) * jGrad.row(j);\n        }\n        // f_i^pressure = - sum_j m_j*(p_i + p_j) / (2 rho_j) \\nabla W(r_i - r_j, h)\n        FPressure.row(i) = (- 1.0/2.0) * jPress.colwise().sum();\n    }\n}\n\nvoid AbstractSph::computeMomentumPreservingPressureForce(const Scene& scene, const Kernel& pressureKernel) {\n    const auto& pos = scene.fluid->particles_position();\n    const auto& ms = scene.fluid->particles_mass();\n    const auto& rho = scene.fluid->particles_density();\n    const auto& ps = scene.fluid->particles_pressure();\n    assert(is_finite(pos));\n    assert(is_finite(ms));\n    assert(is_finite(rho));\n    assert(is_finite(ps));\n    int PN = pos.rows();\n    const auto& fluid_index = scene.fluid->fluid_neighborhood->indexes();\n#if INLINE_KERNELS\n    Float h = scene.fluid->h();\n    Float kernelScale = -3*pressureKernel.scale2d();\n    Float epsilon = 0.000001;\n#endif\n    for(int i = 0; i < PN; ++i){\n        const auto& index = fluid_index[i];\n        int N = index.size();\n        Float A = ps[i]/(rho[i] * rho[i]);\n        TranslationVector vi = pos.row(i);\n        TranslationVector jPress;\n        jPress.setZero();\n        for(int j = 0; j < N; ++j){\n            int jj = index[j];\n            TranslationVector xij = vi - pos.row(jj);\n#if INLINE_KERNELS\n            Float r1 = xij.norm();\n            Float hr = h - r1;\n            Float hr2 = hr * hr;\n            TranslationVector jGrad = kernelScale * (xij * ( hr2 / (r1 + h*epsilon)));\n#else\n            TranslationVector jGrad = pressureKernel.computeGradient(xij);\n#endif\n            jPress += ms[jj] * (A + ps[jj] / (rho[jj] * rho[jj])) * jGrad;\n        }\n        // f_i^pressure = - m_i * sum_j m_j*(p_i/rho_i^2 + p_j/rho_j^2) \\nabla W(r_i - r_j, h)\n        FPressure.row(i) = - ms[i] * jPress;\n    }\n    assert(is_finite(FPressure));\n}\n\n\nvoid AbstractSph::computeStandardViscosityForce(const Scene& scene, const Kernel& viscosityKernel) {\n    const auto& pos = scene.fluid->particles_position();\n    const auto& ms = scene.fluid->particles_mass();\n    const auto& vs = scene.fluid->particles_velocity();\n    const auto mu = scene.fluid->fluid_viscosity();\n    const auto& rho = scene.fluid->particles_density();\n    int PN = pos.rows();\n    const auto& fluid_index = scene.fluid->fluid_neighborhood->indexes();\n#if INLINE_KERNELS\n    Float h = scene.fluid->h();\n    Float kernelScale = viscosityKernel.scale2d();\n#endif\n    for(int i = 0; i < PN; ++i){\n        const auto& index = fluid_index[i];\n        int N = index.size();\n        TranslationVector vi = pos.row(i);\n        TranslationVector vvi = vs.row(i);\n        TranslationVector jVisc;\n        jVisc.setZero();\n        for(int j = 0; j < N; ++j){\n            int jj = index[j];\n            auto xij = vi - pos.row(jj);\n#if INLINE_KERNELS\n            Float jLap = kernelScale * (h - xij.norm());\n#else\n            Float jLap = viscosityKernel.computeLaplacian(xij);\n#endif\n            jVisc += ms[jj] / rho[jj] * (vs.row(jj) - vvi) * jLap;\n        }\n        // f_i^viscosity = mu * sum_j m_j (v_j - v_i) / rho_j \\nabla^2 W(r_i - r_j, h)\n        FViscosity.row(i) = mu * jVisc;\n    }\n}\n\nvoid AbstractSph::computeStandardSurfaceTensionForce(const Scene& scene, const Kernel& kernel, Float color_relevant_normal_size) {\n    const auto& pos = scene.fluid->particles_position();\n    const auto& ms = scene.fluid->particles_mass();\n    const auto& rho = scene.fluid->particles_density();\n    auto color_sigma = scene.fluid->surface_tension();\n    int PN = pos.rows();\n    const auto& fluid_index = scene.fluid->fluid_neighborhood->indexes();\n    for(int i = 0; i < PN; ++i){\n        const auto& index = fluid_index[i];\n        Coordinates2d jpos;\n        Coordinates2d jGrad;\n        Coordinates1d jCLap;\n        Coordinates2d jColGrad(index.size(), 2);\n        Coordinates1d jColLap(index.size());\n        pickRows(pos, index, jpos);\n        // c_s(r_i) = sum_j m_j/rho-j W(r_i - r_j, h)\n        auto xij = -(jpos.rowwise() - pos.row(i));\n        kernel.compute(xij, nullptr, &jGrad, &jCLap);\n        for(size_t j = 0; j < index.size(); ++j){\n            int jj = index[j];\n            Float a = ms[jj] / rho[jj];\n            jColGrad.row(j) = a * jGrad.row(j);\n            jColLap[j] = a * jCLap[j];\n        }\n        TranslationVector colorN = jColGrad.colwise().sum();\n        Float colorLap = jColLap.sum();\n        Float colorNNorm = colorN.norm();\n        if(colorNNorm > color_relevant_normal_size){\n            Float aa = (-color_sigma * colorLap / colorNNorm);\n            FSurface.row(i) = aa * colorN;\n        }\n    }\n}\n\n/// computes rho_i += sum_j m_j W_ij\nvoid AbstractSph::computeFluidDensity(Scene& scene, const Kernel& densityKernel) const {\n    const auto& pos = scene.fluid->particles_position();\n    int PN = pos.rows();\n    const auto& ms = scene.fluid->particles_mass();\n    assert(ms.minCoeff() > 0.0);\n    auto& rho = scene.fluid->particles_density();\n    const auto& fluid_index = scene.fluid->fluid_neighborhood->indexes();\n#if INLINE_KERNELS\n    Float h = scene.fluid->h();\n    Float kernelScale = densityKernel.scale2d();\n    Float h2 = h * h;\n#endif\n    for(int i = 0; i < PN; ++i){\n        // density from fluid<->fluid\n        const auto& index = fluid_index[i];\n        int N = index.size();\n        TranslationVector vi = pos.row(i);\n        Float jW = 0.0;\n        for(int j = 0; j < N; ++j){\n            int jj = index[j];\n            TranslationVector xij = vi - pos.row(jj);\n#if INLINE_KERNELS\n            Float d = h2 - xij.squaredNorm();\n            Float v = kernelScale * d*d*d;\n#else\n            Float v = densityKernel.computeValue(xij);\n#endif\n            jW += ms[jj] * v;\n        }\n        rho[i] = jW;\n    }\n    assert(rho.minCoeff() > 0.0);\n    assert(is_finite(rho));\n}\n\n/// based on CFL condition: dt = lambda * h /max(sqrt(K), v_max)\nvoid AbstractSph::limitVelocity(const Scene& scene) const {\n    const Float vMax = std::sqrt(scene.fluid->stiffnessConstant());\n    auto& vs = scene.fluid->particles_velocity();\n\n    Coordinates1d vsMag2 = vs.rowwise().squaredNorm();\n    Float maxV2 = vsMag2.maxCoeff();\n    if(maxV2 > vMax*vMax){\n        BOOST_LOG_TRIVIAL(info) << \"Limiting particle speed from \" << std::sqrt(maxV2) << \" to \" << vMax;\n        for(int i = 0; i < vs.rows(); ++i){\n            if(vsMag2[i] > vMax*vMax){\n                vs.row(i) = vs.row(i) / std::sqrt(vsMag2[i]) * vMax;\n            }\n        }\n        vs.array().min(vMax).max(-vMax);\n    }\n}\n\n\n} // Physics\n\n} // d2\n\n} // GooBalls\n\n", "meta": {"hexsha": "2d6ea1ee1852503c1b525f3220561b352b5c2488", "size": 11599, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/lib/physics/2d/abstract_sph.cpp", "max_stars_repo_name": "Fluci/GooBalls", "max_stars_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lib/physics/2d/abstract_sph.cpp", "max_issues_repo_name": "Fluci/GooBalls", "max_issues_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lib/physics/2d/abstract_sph.cpp", "max_forks_repo_name": "Fluci/GooBalls", "max_forks_repo_head_hexsha": "4b68084303e66af368fd6bbf94aaec0950c9c6e3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5372168285, "max_line_length": 130, "alphanum_fraction": 0.6203120959, "num_tokens": 3166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.22158186035846728}}
{"text": "// SPDX-License-Identifier: MIT\n// SPDX-FileCopyrightText: Copyright 2019-2022 Heal Research\n\n#ifndef OPERON_EVAL_DETAIL\n#define OPERON_EVAL_DETAIL\n\n#include <Eigen/Dense>\n#include <fmt/core.h>\n#include <optional>\n#include <robin_hood.h>\n#include <cstddef>\n#include <tuple>\n\n#include \"operon/core/node.hpp\"\n#include \"operon/core/range.hpp\"\n#include \"operon/core/types.hpp\"\n#include \"functions.hpp\"\n\nnamespace Operon {\n\nnamespace detail {\n    // this should be good enough - tests show 512 is about optimal\n    template<typename T>\n    struct BatchSize {\n        static const size_t Value = 512 / sizeof(T);\n    };\n\n    template<typename T>\n    using Array = Eigen::Array<T, BatchSize<T>::Value, 1>;\n\n    template<typename T>\n    using Ref = Eigen::Ref<Array<T>>;\n\n    // dispatching mechanism\n    // compared to the simple/naive way of evaluating n-ary symbols, this method has the following advantages:\n    // 1) improved performance: the naive method accumulates into the result for each argument, leading to unnecessary assignments\n    // 2) minimizing the number of intermediate steps which might improve floating point accuracy of some operations\n    //    if arity > 4, one accumulation is performed every 4 args\n    template<NodeType Type, typename T>\n    inline void DispatchOpNary(Operon::Vector<Array<T>>& m, Operon::Vector<Node> const& nodes, size_t parentIndex, Operon::Range /* not used here - provided for dynamic symbols */)\n    {\n        static_assert(Type < NodeType::Aq);\n        auto result = Ref<T>(m[parentIndex]);\n        const auto f = [](bool cont, decltype(result) res, auto&&... args) {\n            if (cont) {\n                ContinuedFunction<Type>{}(res, std::forward<decltype(args)>(args)...);\n            } else {\n                Function<Type>{}(res, std::forward<decltype(args)>(args)...);\n            }\n        };\n        const auto nextArg = [&](size_t i) { return i - (nodes[i].Length + 1); };\n\n        auto arg1 = parentIndex - 1;\n\n        bool continued = false;\n\n        using R = Ref<T>;\n\n        int arity = nodes[parentIndex].Arity;\n        while (arity > 0) {\n            switch (arity) {\n            case 1: {\n                f(continued, result, R(m[arg1]));\n                arity = 0;\n                break;\n            }\n            case 2: {\n                auto arg2 = nextArg(arg1);\n                f(continued, result, R(m[arg1]), R(m[arg2]));\n                arity = 0;\n                break;\n            }\n            case 3: {\n                auto arg2 = nextArg(arg1);\n                auto arg3 = nextArg(arg2);\n                f(continued, result, R(m[arg1]), R(m[arg2]), R(m[arg3]));\n                arity = 0;\n                break;\n            }\n            default: {\n                auto arg2 = nextArg(arg1);\n                auto arg3 = nextArg(arg2);\n                auto arg4 = nextArg(arg3);\n                f(continued, result, R(m[arg1]), R(m[arg2]), R(m[arg3]), R(m[arg4]));\n                arity -= 4;\n                arg1 = nextArg(arg4);\n                break;\n            }\n            }\n            continued = true;\n        }\n    }\n\n    template<NodeType Type, typename T>\n    inline void DispatchOpUnary(Operon::Vector<Array<T>>& m, Operon::Vector<Node> const& /*unused*/, size_t i, Operon::Range /* not used here - provided for dynamic symbols */)\n    {\n        static_assert(Type < NodeType::Dynamic && Type > NodeType::Pow);\n        Function<Type>{}(Ref<T>(m[i]), Ref<T>(m[i-1]));\n    }\n\n    template<NodeType Type, typename T>\n    inline void DispatchOpBinary(Operon::Vector<Array<T>>& m, Operon::Vector<Node> const& nodes, size_t i, Operon::Range /* not used here - provided for dynamic symbols */)\n    {\n        static_assert(Type < NodeType::Abs && Type > NodeType::Fmax);\n        auto j = i - 1;\n        auto k = j - nodes[j].Length - 1;\n        Function<Type>{}(Ref<T>(m[i]), Ref<T>(m[j]), Ref<T>(m[k]));\n    }\n\n    template<NodeType Type, typename T>\n    inline void DispatchOpSimpleUnaryOrBinary(Operon::Vector<Array<T>>& m, Operon::Vector<Node> const& nodes, size_t parentIndex, Operon::Range /* not used here - provided for dynamic symbols */)\n    {\n        auto r = Ref<T>(m[parentIndex]);\n        size_t i = parentIndex - 1;\n        size_t arity = nodes[parentIndex].Arity;\n\n        Function<Type> f{};\n\n        if (arity == 1) {\n            f(r, Ref<T>(m[i]));\n        } else {\n            auto j = i - (nodes[i].Length + 1);\n            f(r, Ref<T>(m[j]));\n        }\n    }\n\n    template<NodeType Type, typename T>\n    inline void DispatchOpSimpleNary(Operon::Vector<Array<T>>& m, Operon::Vector<Node> const& nodes, size_t parentIndex, Operon::Range /* not used here - provided for dynamic symbols */)\n    {\n        auto r = Ref<T>(m[parentIndex]);\n        size_t arity = nodes[parentIndex].Arity;\n\n        auto i = parentIndex - 1;\n\n        Function<Type> f{};\n\n        if (arity == 1) {\n            f(r, Ref<T>(m[i]));\n        } else {\n            r = m[i];\n\n            for (size_t k = 1; k < arity; ++k) {\n                i -= nodes[i].Length + 1;\n                f(r, Ref<T>(m[i]));\n            }\n        }\n    }\n\n    struct Noop {\n        template<typename... Args>\n        void operator()(Args&&... /*unused*/) {}\n    };\n\n    template<typename X, typename Tuple>\n    class tuple_index;\n\n    template<typename X, typename... T>\n    class tuple_index<X, std::tuple<T...>> {\n        template<std::size_t... Idx>\n        static constexpr auto FindIdx(std::index_sequence<Idx...> /*unused*/) -> int64_t\n        {\n            return -1 + ((std::is_same<X, T>::value ? Idx + 1 : 0) + ...);\n        }\n\n    public:\n        static constexpr int64_t value = FindIdx(std::index_sequence_for<T...>{});\n    };\n\n    template<typename T>\n    using Callable = typename std::function<void(Operon::Vector<Array<T>>&, Operon::Vector<Node> const&, size_t, Operon::Range)>;\n\n    template<NodeType Type, typename T>\n    static constexpr auto MakeCall() -> Callable<T>\n    {\n        if constexpr (Type < NodeType::Aq) { // nary: add, sub, mul, div, fmin, fmax\n            return Callable<T>(detail::DispatchOpNary<Type, T>);\n        } else if constexpr (Type < NodeType::Abs) { // binary: aq, pow\n            return Callable<T>(detail::DispatchOpBinary<Type, T>);\n        } else if constexpr (Type < NodeType::Dynamic) { // unary: exp, log, sin, cos, tan, tanh, sqrt, cbrt, square\n            return Callable<T>(detail::DispatchOpUnary<Type, T>);\n        }\n    }\n\n    template<NodeType Type, typename... Ts, std::enable_if_t<sizeof...(Ts) != 0, bool> = true>\n    static constexpr auto MakeTuple()\n    {\n        return std::make_tuple(MakeCall<Type, Ts>()...);\n    };\n\n    template<typename F, typename... Ts, std::enable_if_t<sizeof...(Ts) != 0 && (std::is_invocable_r_v<void, F, detail::Array<Ts>&, Vector<Node> const&, size_t, Operon::Range> && ...), bool> = true>\n    static constexpr auto MakeTuple(F&& f)\n    {\n        return std::make_tuple(Callable<Ts>(std::forward<F&&>(f))...);\n    }\n} // namespace detail\n\ntemplate<typename... Ts>\nstruct DispatchTable {\n    template<typename T>\n    using Callable = detail::Callable<T>;\n\n    using Tuple    = std::tuple<Callable<Ts>...>;\n    using Map      = robin_hood::unordered_flat_map<Operon::Hash, Tuple>;\n\nprivate:\n    Map map_;\n\n    template<std::size_t... Is>\n    void InitMap(std::index_sequence<Is...> /*unused*/)\n    {\n        auto f = [](auto i) { return static_cast<NodeType>(1U << i); };\n        (map_.insert({ Node(f(Is)).HashValue, detail::MakeTuple<f(Is), Ts...>() }), ...);\n    }\n\npublic:\n    DispatchTable()\n    {\n        InitMap(std::make_index_sequence<NodeTypes::Count-3>{}); // exclude constant, variable, dynamic\n    }\n\n    ~DispatchTable() = default;\n\n    auto operator=(DispatchTable const& other) -> DispatchTable& {\n        if (this != &other) {\n            map_ = other.map_;\n        }\n        return *this;\n    }\n\n    auto operator=(DispatchTable&& other) noexcept -> DispatchTable& {\n        map_ = std::move(other.map_);\n        return *this;\n    }\n\n    DispatchTable(DispatchTable const& other) : map_(other.map_) { }\n    DispatchTable(DispatchTable &&other) noexcept : map_(std::move(other.map_)) { }\n\n    template<typename T>\n    inline auto Get(Operon::Hash const h) -> Callable<T>&\n    {\n        return const_cast<Callable<T>&>(const_cast<DispatchTable<Ts...> const*>(*this)->Get(h)); // NOLINT\n    }\n\n    template<typename T>\n    [[nodiscard]] inline auto Get(Operon::Hash const h) const -> Callable<T> const&\n    {\n        constexpr int64_t idx = detail::tuple_index<Callable<T>, Tuple>::value;\n        static_assert(idx >= 0, \"Tuple does not contain type T\");\n        if (auto it = map_.find(h); it != map_.end()) {\n            return std::get<static_cast<size_t>(idx)>(it->second);\n        }\n        throw std::runtime_error(fmt::format(\"Hash value {} is not in the map\\n\", h));\n    }\n\n    template<typename F>\n    void RegisterCallable(Operon::Hash hash, F&& f) {\n        map_[hash] = detail::MakeTuple<F, Ts...>(std::forward<F&&>(f));\n    }\n\n    template<typename T>\n    [[nodiscard]] inline auto TryGet(Operon::Hash const h) const noexcept -> std::optional<Callable<T>>\n    {\n        constexpr int64_t idx = detail::tuple_index<Callable<T>, Tuple>::value;\n        static_assert(idx >= 0, \"Tuple does not contain type T\");\n        if (auto it = map_.find(h); it != map_.end()) {\n            return { std::get<static_cast<size_t>(idx)>(it->second) };\n        }\n        return {};\n    }\n\n    [[nodiscard]] auto Contains(Operon::Hash hash) const noexcept -> bool { return map_.contains(hash); }\n};\n\n} // namespace Operon\n\n#endif\n", "meta": {"hexsha": "4ce7f05b65dc129a2faa74a8cfcedbf73201e3ec", "size": 9588, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/operon/interpreter/dispatch_table.hpp", "max_stars_repo_name": "foolnotion/operon", "max_stars_repo_head_hexsha": "5faa938b98e0ee40e224eca8793db5f6a9934673", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-10-29T09:36:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-17T08:31:37.000Z", "max_issues_repo_path": "include/operon/interpreter/dispatch_table.hpp", "max_issues_repo_name": "foolnotion/operon", "max_issues_repo_head_hexsha": "5faa938b98e0ee40e224eca8793db5f6a9934673", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-24T20:02:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-14T10:07:18.000Z", "max_forks_repo_path": "include/operon/interpreter/dispatch_table.hpp", "max_forks_repo_name": "foolnotion/operon", "max_forks_repo_head_hexsha": "5faa938b98e0ee40e224eca8793db5f6a9934673", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-01-29T05:36:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-31T06:48:52.000Z", "avg_line_length": 34.6137184116, "max_line_length": 198, "alphanum_fraction": 0.5729036295, "num_tokens": 2443, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.22145501290566572}}
{"text": "#ifndef GUNERO_MERKLE_TREE_GADGET_H_\n#define GUNERO_MERKLE_TREE_GADGET_H_\n\n#include <deque>\n#include <boost/optional.hpp>\n#include <boost/static_assert.hpp>\n#include <libff/common/utils.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/common/default_types/r1cs_gg_ppzksnark_pp.hpp>\n#include <libsnark/relations/constraint_satisfaction_problems/r1cs/examples/r1cs_examples.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/uscs_ppzksnark/uscs_ppzksnark.hpp>\n#include <libff/algebra/fields/field_utils.hpp>\n#include <libff/algebra/scalar_multiplication/multiexp.hpp>\n#include <libsnark/common/default_types/r1cs_ppzksnark_pp.hpp>\n#include <libsnark/zk_proof_systems/ppzksnark/r1cs_ppzksnark/r1cs_ppzksnark.hpp>\n#include <libff/algebra/curves/edwards/edwards_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt4/mnt4_pp.hpp>\n#include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp>\n#include <libff/common/utils.hpp>\n\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_read_gadget.hpp>\n#include <libsnark/gadgetlib1/gadgets/merkle_tree/merkle_tree_check_update_gadget.hpp>\n\n#include \"uint256.h\"\n#include \"serialize.h\"\n#include \"gunero_merkle_tree.hpp\"\n\nusing namespace libsnark;\n\nnamespace gunero {\n\ntemplate<typename FieldT, typename HashT, size_t tree_depth>\nclass gunero_merkle_tree_gadget : gadget<FieldT> {\nprivate:\n    pb_variable_array<FieldT> positions;\n    std::shared_ptr<gunero_merkle_authentication_path_variable<FieldT, HashT>> authvars;\n    std::shared_ptr<gunero_merkle_tree_check_read_gadget<FieldT, HashT>> auth;\n\npublic:\n    gunero_merkle_tree_gadget(\n        protoboard<FieldT>& pb,\n        digest_variable<FieldT>& leaf,\n        digest_variable<FieldT>& root,\n        const pb_variable<FieldT>& enforce,\n        const std::string &annotation_prefix\n    ) : gadget<FieldT>(pb, annotation_prefix) {\n        positions.allocate(pb, tree_depth);\n        authvars.reset(new gunero_merkle_authentication_path_variable<FieldT, HashT>(\n            pb, tree_depth, \"auth\"\n        ));\n        auth.reset(new gunero_merkle_tree_check_read_gadget<FieldT, HashT>(\n            pb,\n            tree_depth,\n            positions,\n            leaf,\n            root,\n            *authvars,\n            enforce,\n            \"path\"\n        ));\n    }\n\n    void generate_r1cs_constraints() {\n        for (size_t i = 0; i < tree_depth; i++) {\n            // TODO: This might not be necessary, and doesn't\n            // appear to be done in libsnark's tests, but there\n            // is no documentation, so let's do it anyway to\n            // be safe.\n            generate_boolean_r1cs_constraint<FieldT>(\n                this->pb,\n                positions[i],\n                \"boolean_positions\"\n            );\n        }\n\n        authvars->generate_r1cs_constraints();\n        auth->generate_r1cs_constraints();\n    }\n\n    void generate_r1cs_witness(const std::vector<gunero_merkle_authentication_node>& M_account, const libff::bit_vector& A_account)\n    {\n        // size_t path_index_account = convertVectorToInt(path.index_account);\n        // uint256 path_A_account = bool_vector_to_uint256(A_account);\n        // size_t path_index_account = convertVectorToInt(A_account);\n\n        // positions.fill_with_bits_of_ulong(this->pb, path_index_account);\n        libff::bit_vector A_account_LSB(tree_depth);\n        for(size_t i = 0; i < tree_depth; i++)\n        {\n            A_account_LSB.at(i) = A_account.at(tree_depth - 1 - i);\n        }\n        positions.fill_with_bits(this->pb, A_account_LSB);\n\n        // authvars->generate_r1cs_witness(path_index_account, path.authentication_path);\n        // auth->generate_r1cs_witness();\n\n        // positions.fill_with_bits(this->pb, A_account);\n\n        authvars->generate_r1cs_witness(A_account, M_account);\n        auth->generate_r1cs_witness();\n    }\n};\n\n} // end namespace `gunero`\n\n#endif /* GUNERO_MERKLE_TREE_GADGET_H_ */", "meta": {"hexsha": "340c556a4e91f4ee60383aeee8282f5d577f8eea", "size": 4091, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/gunero_merkle_tree_gadget.hpp", "max_stars_repo_name": "GunClear/Silencer", "max_stars_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T22:27:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-17T22:27:54.000Z", "max_issues_repo_path": "src/gunero_merkle_tree_gadget.hpp", "max_issues_repo_name": "GunClear/Silencer", "max_issues_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T19:57:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-01-04T15:49:02.000Z", "max_forks_repo_path": "src/gunero_merkle_tree_gadget.hpp", "max_forks_repo_name": "GunClear/Silencer", "max_forks_repo_head_hexsha": "625b5ce0860af98763aa2ce14d6b406d5ef368e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8796296296, "max_line_length": 131, "alphanum_fraction": 0.7088731362, "num_tokens": 1076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132315, "lm_q2_score": 0.33807711081162, "lm_q1q2_score": 0.22140492243459314}}
{"text": "#include \"tile/lib/lib.h\"\n\n#include <memory>\n#include <tuple>\n\n#include <boost/format.hpp>\n\n#include \"base/util/stream_container.h\"\n#include \"plaidml2/edsl/autodiff.h\"\n#include \"tile/util/tile_file.h\"\n\nnamespace vertexai {\nnamespace tile {\nnamespace lib {\n\nusing namespace plaidml::edsl;  // NOLINT\n\nnamespace {\n\nlang::RunInfo Evaluate(const std::string& name, const std::vector<Tensor>& vars) {\n  Program program(name, vars, {});\n  return *static_cast<const tile::lang::RunInfo*>(program.runinfo());\n}\n\nstd::shared_ptr<lang::BufferBase> MakeBuffer(const LogicalShape& shape) {\n  std::vector<size_t> sizes;\n  for (const auto& dim : shape.int_dims()) {\n    sizes.push_back(dim);\n  }\n  auto tensor_shape = tile::SimpleShape(static_cast<DataType>(shape.dtype()), sizes);\n  auto buffer = std::make_shared<util::SimpleBuffer>();\n  buffer->bytes.resize(tensor_shape.byte_size());\n  return buffer;\n}\n\nTensor MatMul(const Tensor& A, const Tensor& B) {\n  TensorDim M, N, K;\n  A.bind_dims(M, K);\n  B.bind_dims(K, N);\n  TensorIndex k(\"k\"), m(\"m\"), n(\"n\");\n  auto C = NamedTensorOutput(\"C\", M, N);\n  C(m, n) += A(m, k) * B(k, n);\n  return C;\n}\n\nTensor DilatedConvolution2(const Tensor& I, const Tensor& K) {\n  TensorDim N, Lx, Ly, LKx, LKy, CI, CO;\n  I.bind_dims(N, Lx, Ly, CI);\n  K.bind_dims(LKx, LKy, CI, CO);\n  auto O = NamedTensorOutput(\"O\", N, Lx - 2 * (LKx - 1), Ly - 3 * (LKy - 1), CO);\n  TensorIndex n, x, y, kx, ky, ci, co;\n  O(n, x, y, co) += I(n, x + 2 * kx, y + 3 * ky, ci) * K(kx, ky, ci, co);\n  return O;\n}\n\nTensor Relu(const Tensor& X) { return Call(\"relu\", X); }\n\nTensor Sin(const Tensor& X) { return Call(\"sin\", X); }\n\nTensor Tanh(const Tensor& X) { return Call(\"tanh\", X); }\n\n}  // namespace\n\nTensor Convolution(const Tensor& I,                      //\n                   const Tensor& K,                      //\n                   const std::vector<int64_t>& O_sizes,  //\n                   std::vector<size_t> strides,          //\n                   ConvolutionFormat I_format,           //\n                   ConvolutionFormat K_format) {\n  TensorDim N, CI, CO;\n  auto I_shape = I.shape();\n  auto K_shape = K.shape();\n  IVLOG(1, \"I.shape(): \" << I_shape);\n  IVLOG(1, \"K.shape(): \" << K_shape);\n  auto ndims = I_shape.ndims() - 2;\n  if (strides.empty()) {\n    for (size_t i = 0; i < ndims; i++) {\n      strides.push_back(1);\n    }\n  } else if (strides.size() != ndims) {\n    throw std::runtime_error(str(\n        boost::format(\"Convolution strides length inconsistent with input shape: %1% (ndims %2%) v %3% (ndims %4%)\") %\n        StreamContainer(strides) % strides.size() % I_shape % ndims));\n  }\n  TensorIndex n(\"n\"), co(\"co\"), ci(\"ci\");\n  std::vector<TensorDim> I_dims = {N};\n  std::vector<TensorDim> I_spatial_dims(ndims);\n  std::vector<TensorDim> K_dims;\n  std::vector<TensorDim> K_spatial_dims(ndims);\n  std::vector<TensorDim> O_dims;\n  for (const auto& size : O_sizes) {\n    O_dims.emplace_back(size);\n  }\n  std::vector<TensorIndex> K_idxs;\n  std::vector<TensorIndex> I_idxs = {n};\n  std::vector<TensorIndex> O_idxs = {n};\n  size_t K_spatial_dims_offset = 0;\n  if (K_format == ConvolutionFormat::ChannelsFirst) {\n    K_spatial_dims_offset = 2;\n    K_idxs.push_back(co);\n    K_idxs.push_back(ci);\n    K_dims.push_back(CO);\n    K_dims.push_back(CI);\n  }\n  if (I_format == ConvolutionFormat::ChannelsFirst) {\n    I_idxs.push_back(ci);\n    O_idxs.push_back(co);\n    I_dims.push_back(CI);\n  }\n  K_dims.insert(std::end(K_dims), std::begin(K_spatial_dims), std::end(K_spatial_dims));\n  I_dims.insert(std::end(I_dims), std::begin(I_spatial_dims), std::end(I_spatial_dims));\n  if (I_format == ConvolutionFormat::ChannelsLast) {\n    I_dims.push_back(CI);\n  }\n  if (K_format == ConvolutionFormat::ChannelsLast) {\n    K_dims.push_back(CI);\n    K_dims.push_back(CO);\n  }\n  I.bind_dims(I_dims);\n  K.bind_dims(K_dims);\n  for (size_t i = 0; i < ndims; i++) {\n    TensorIndex x(str(boost::format(\"x%1%\") % i));\n    TensorIndex k(str(boost::format(\"k%1%\") % i));\n    IVLOG(1, \"Adding \" << i);\n    I_idxs.emplace_back(strides[i] * x + k - K_dims[K_spatial_dims_offset + i] / 2);\n    K_idxs.push_back(k);\n    O_idxs.push_back(x);\n  }\n  if (I_format == ConvolutionFormat::ChannelsLast) {\n    I_idxs.push_back(ci);\n    O_idxs.push_back(co);\n  }\n  if (K_format == ConvolutionFormat::ChannelsLast) {\n    K_idxs.push_back(ci);\n    K_idxs.push_back(co);\n  }\n  Tensor O(\"O\", O_dims);\n  O(O_idxs) += I(I_idxs) * K(K_idxs);\n  return O;\n}\n\nlang::RunInfo LoadMatMul(const std::string& name, const LogicalShape& i1, const LogicalShape& i2) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  return Evaluate(name, {MatMul(A, B)});\n}\n\nlang::RunInfo LoadMatMulIntermediate(const std::string& name, const LogicalShape& i1, const LogicalShape& i2,\n                                     const LogicalShape& i3) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  auto C = Placeholder(i3, \"C\");\n  Tensor D = MatMul(A, B);\n  Tensor E = D + C;\n  return Evaluate(name, {D, E});\n}\n\nlang::RunInfo LoadEltwiseMulFlip(const std::string& name, const LogicalShape& i1, const LogicalShape& i2) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  return Evaluate(name, {~(A * B)});\n}\n\nlang::RunInfo LoadMatMulAmongEltwise(const std::string& name, const LogicalShape& i1, const LogicalShape& i2,\n                                     const LogicalShape& i3) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  auto C = Placeholder(i3, \"C\");\n  Tensor NegA = -A;\n  Tensor NegB = -B;\n  Tensor P = MatMul(NegA, NegB);\n  return Evaluate(name, {P + C});\n}\n\nlang::RunInfo LoadEltwiseAdd(const std::string& name, const LogicalShape& i1, const LogicalShape& i2) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  return Evaluate(name, {A + B});\n}\n\nlang::RunInfo LoadEltwiseMultiAdd(const std::string& name, const LogicalShape& i1, const LogicalShape& i2,\n                                  const LogicalShape& i3, const LogicalShape& i4) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  auto C = Placeholder(i3, \"C\");\n  auto D = Placeholder(i4, \"D\");\n  return Evaluate(name, {A + B + C + D});\n}\n\nlang::RunInfo LoadEltwiseDiv(const std::string& name, const LogicalShape& i1, const LogicalShape& i2) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  return Evaluate(name, {A / B});\n}\n\nlang::RunInfo LoadConstScalarMul(const std::string& name, const double s, const LogicalShape& i1) {\n  Tensor scalar(s);\n  auto A = Placeholder(i1, \"A\");\n  return Evaluate(name, {scalar * A});\n}\n\nlang::RunInfo LoadEltwiseMul(const std::string& name, const LogicalShape& i1, const LogicalShape& i2) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  return Evaluate(name, {A * B});\n}\n\nlang::RunInfo LoadEltwiseMultiMul(const std::string& name, const LogicalShape& i1, const LogicalShape& i2,\n                                  const LogicalShape& i3, const LogicalShape& i4) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  auto C = Placeholder(i3, \"C\");\n  auto D = Placeholder(i4, \"D\");\n  return Evaluate(name, {A * B * C * D});\n}\n\nlang::RunInfo LoadSin(const std::string& name, const LogicalShape& i1) {\n  auto A = Placeholder(i1, \"A\");\n  return Evaluate(name, {Sin(A)});\n}\n\nlang::RunInfo LoadTanh(const std::string& name, const LogicalShape& i1) {\n  auto A = Placeholder(i1, \"A\");\n  return Evaluate(name, {Tanh(A)});\n}\n\nlang::RunInfo LoadMulThenNeg(const std::string& name, const LogicalShape& i1, const LogicalShape& i2) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  Tensor C = A * B;\n  return Evaluate(name, {-C});\n}\n\nlang::RunInfo LoadNegThenMul(const std::string& name, const LogicalShape& i1, const LogicalShape& i2) {\n  auto A = Placeholder(i1, \"A\");\n  auto B = Placeholder(i2, \"B\");\n  Tensor NegA = -A;\n  Tensor NegB = -B;\n  return Evaluate(name, {NegA * NegB});\n}\n\nlang::RunInfo LoadConstCalc(const std::string& name) {\n  Tensor N(1);\n  Tensor F(0.0);\n  Tensor F2(3.7);\n  TensorIndex i;\n  auto Simple = TensorOutput(1);\n  Simple(i) = F();\n  auto DoubleN = TensorOutput(1);\n  DoubleN(i) = N();\n  Tensor Partial = Simple + DoubleN;\n  Tensor O = Partial + F2;\n  return Evaluate(name, {O});\n}\n\nlang::RunInfo LoadConv1d(const std::string& name,     //\n                         const LogicalShape& input,   //\n                         const LogicalShape& kernel,  //\n                         const std::vector<int64_t>& output) {\n  auto I = Placeholder(input, \"I\");\n  auto K = Placeholder(kernel, \"K\");\n  auto runinfo = Evaluate(name, {Convolution(I, K, output)});\n  runinfo.const_inputs = {\"K\"};\n  runinfo.input_buffers = {{\"K\", MakeBuffer(kernel)}};\n  return runinfo;\n}\n\nlang::RunInfo LoadConv2d(const std::string& name,     //\n                         const LogicalShape& input,   //\n                         const LogicalShape& kernel,  //\n                         const std::vector<int64_t>& output) {\n  auto I = Placeholder(input, \"I\");\n  auto K = Placeholder(kernel, \"K\");\n  auto runinfo = Evaluate(name, {Convolution(I, K, output)});\n  runinfo.const_inputs = {\"K\"};\n  runinfo.input_buffers = {{\"K\", MakeBuffer(kernel)}};\n  return runinfo;\n}\n\nlang::RunInfo LoadConv2dRelu(const std::string& name,     //\n                             const LogicalShape& input,   //\n                             const LogicalShape& kernel,  //\n                             const std::vector<int64_t>& output) {\n  auto I = Placeholder(input, \"I\");\n  auto K = Placeholder(kernel, \"K\");\n  auto runinfo = Evaluate(name, {Relu(Convolution(I, K, output))});\n  runinfo.const_inputs = {\"K\"};\n  runinfo.input_buffers = {{\"K\", MakeBuffer(kernel)}};\n  return runinfo;\n}\n\nlang::RunInfo LoadConv2dBnRelu(const std::string& name,       //\n                               const LogicalShape& input,     //\n                               const LogicalShape& kernel,    //\n                               const LogicalShape& channels,  //\n                               const std::vector<int64_t>& output) {\n  auto I = Placeholder(input, \"I\");\n  auto K = Placeholder(kernel, \"K\");\n  auto B = Placeholder(channels, \"B\");\n  auto S = Placeholder(channels, \"S\");\n  auto O = Convolution(I, K, output);\n  auto R = Relu((O + B) * S);\n  auto runinfo = Evaluate(name, {R});\n  runinfo.const_inputs = {\"K\"};\n  runinfo.input_buffers = {\n      {\"K\", MakeBuffer(kernel)},\n      {\"B\", MakeBuffer(channels)},\n      {\"S\", MakeBuffer(channels)},\n  };\n  return runinfo;\n}\n\nlang::RunInfo LoadConv2d3Deep(const std::string& name,      //\n                              const LogicalShape& input,    //\n                              const LogicalShape& kernel1,  //\n                              const LogicalShape& kernel2,  //\n                              const LogicalShape& kernel3) {\n  auto I = Placeholder(input, \"I\");\n  auto K1 = Placeholder(kernel1, \"K1\");\n  auto K2 = Placeholder(kernel2, \"K2\");\n  auto K3 = Placeholder(kernel3, \"K3\");\n  auto dims = input.int_dims();\n  auto O1 = Convolution(I, K1, {dims[0], dims[1], dims[2], kernel1.int_dims()[3]});\n  auto O2 = Convolution(O1, K2, {dims[0], dims[1], dims[2], kernel2.int_dims()[3]});\n  auto O3 = Convolution(O2, K3, {dims[0], dims[1], dims[2], kernel3.int_dims()[3]});\n  auto runinfo = Evaluate(name, {O3});\n  runinfo.const_inputs = {\"K1\", \"K2\", \"K3\"};\n  runinfo.input_buffers = {\n      {\"K1\", MakeBuffer(kernel1)},\n      {\"K2\", MakeBuffer(kernel2)},\n      {\"K3\", MakeBuffer(kernel3)},\n  };\n  return runinfo;\n}\n\nlang::RunInfo LoadDilatedConv2d(const std::string& name,    //\n                                const LogicalShape& input,  //\n                                const LogicalShape& kernel) {\n  auto I = Placeholder(input, \"I\");\n  auto K = Placeholder(kernel, \"K\");\n  return Evaluate(name, {DilatedConvolution2(I, K)});\n}\n\nTensor Normalize(const Tensor& X) {\n  auto XSqr = X * X;\n  auto X_MS = TensorOutput();\n  std::vector<TensorIndex> idxs(X.shape().ndims());\n  X_MS() += XSqr(idxs);\n  return sqrt(X_MS);\n}\n\nstd::tuple<Tensor, Tensor> LarsMomentum(const Tensor& X,           //\n                                        const Tensor& Grad,        //\n                                        const Tensor& Veloc,       //\n                                        const Tensor& LR,          //\n                                        double lars_coeff,         //\n                                        double lars_weight_decay,  //\n                                        double momentum) {\n  auto XNorm = Normalize(X);\n  auto GradNorm = Normalize(Grad);\n  auto LocLR = LR * lars_coeff * XNorm / (GradNorm + lars_weight_decay * XNorm);\n  auto NewVeloc = momentum * Veloc + LocLR * (Grad + lars_weight_decay * X);\n  return std::make_tuple(X - NewVeloc, NewVeloc);\n}\n\nlang::RunInfo LoadLarsMomentum4d(const std::string& name,      //\n                                 const LogicalShape& x_shape,  //\n                                 const LogicalShape& lr_shape) {\n  // Note: X/Grad/Veloc/NewX/NewVeloc should all have the same shape for the\n  // semantics of this operation to be correct, so we only pass in 1 shape for\n  // all of them.\n  double lars_coeff = 1. / 1024.;\n  double lars_weight_decay = 1. / 2048.;\n  double momentum = 1. / 8.;\n  auto X = Placeholder(x_shape);\n  auto Grad = Placeholder(x_shape);\n  auto Veloc = Placeholder(x_shape);\n  auto LR = Placeholder(lr_shape);\n  auto R = LarsMomentum(X, Grad, Veloc, LR, lars_coeff, lars_weight_decay, momentum);\n  return Evaluate(\"lars_momentum4d\", {std::get<0>(R), std::get<1>(R)});\n}\n\nlang::RunInfo LoadPow(const std::string& name,  //\n                      const LogicalShape& i1,   //\n                      const LogicalShape& i2) {\n  auto X = Placeholder(i1, \"X\");\n  auto Y = Placeholder(i2, \"Y\");\n  auto runinfo = Evaluate(name, {pow(X, Y)});\n  runinfo.input_buffers = {\n      {\"X\", MakeBuffer(i1)},\n      {\"Y\", MakeBuffer(i2)},\n  };\n  return runinfo;\n}\n\nTensor Norm4dAx2(const Tensor& I, const Tensor& G, const Tensor& B, const Tensor& Epsilon) {\n  TensorDim I0, I1, I2, I3;\n  I.bind_dims(I0, I1, I2, I3);\n  auto H = I2 * I3;\n  auto Sum = TensorOutput(I0, I1, 1, 1);\n  TensorIndex i0, i1, i2, i3;\n  Sum(i0, i1, 0, 0) += I(i0, i1, i2, i3);\n  auto Mu = Sum / H;\n  auto Diff = I - Mu;\n  auto SqDiff = Diff * Diff;\n  auto SumSqDiff = TensorOutput(I0, I1, 1, 1);\n  SumSqDiff(i0, i1, 0, 0) += SqDiff(i0, i1, i2, i3);\n  auto Stdev = sqrt(SumSqDiff + Epsilon) / H;\n  return (G / Stdev) * (I - Mu) + B;\n}\n\nlang::RunInfo LoadLayerNorm4dAx2(const std::string& name,  //\n                                 const LogicalShape& input) {\n  // Note: I/G/B/O should all have the same shape, so pass in one shape to share\n  auto I = Placeholder(input);\n  auto G = Placeholder(input);\n  auto B = Placeholder(input);\n  auto Epsilon = Placeholder(PLAIDML_DATA_FLOAT32, {});\n  return Evaluate(name, {Norm4dAx2(I, G, B, Epsilon)});\n}\n\nTensor PolygonBoxTransform(const Tensor& I) {\n  TensorDim N, C, H, W;\n  I.bind_dims(N, C, H, W);\n  auto TEpartial = TensorOutput(N, C, H, W);\n  auto TOpartial = TensorOutput(N, C, H, W);\n  TensorIndex n, c, h, w;\n  auto Widx = index(I, 3);\n  TEpartial(2 * n, c, h, w) = I(2 * n, c, h, w);\n  auto TE = 4 * Widx - TEpartial;\n  TOpartial(2 * n + 1, c, h, w) = I(2 * n + 1, c, h, w);\n  auto Hidx = index(I, 2);\n  auto TO = 4 * Hidx - TOpartial;\n  return TE + TO;\n}\n\nlang::RunInfo LoadPolygonBoxTransform(const std::string& name,  //\n                                      const LogicalShape& input) {\n  // Note: I and O have the same shape\n  auto I = Placeholder(input);\n  return Evaluate(name, {PolygonBoxTransform(I)});\n}\n\nlang::RunInfo LoadSoftmax(const std::string& name,      //\n                          const LogicalShape& input) {  //\n  auto X1 = Placeholder(input);\n  TensorDim I, J;\n  X1.bind_dims(I, J);\n  TensorIndex i(\"i\"), j(\"j\");\n  auto M = NamedTensorOutput(\"M\", I, 1);\n  M(i, 0) >= X1(i, j);\n  auto E = exp(X1 - M);\n  auto N = NamedTensorOutput(\"N\", I, 1);\n  N(i, 0) += E(i, j);\n  return Evaluate(name, {E / N});\n}\n\n}  // namespace lib\n}  // namespace tile\n}  // namespace vertexai\n", "meta": {"hexsha": "8b36a76ffe90322645061ab5606bf20f366c3844", "size": 16017, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tile/lib/lib.cc", "max_stars_repo_name": "TolyaTalamanov/plaidml", "max_stars_repo_head_hexsha": "275a79cd640def34c1b7bc7053397f5989ef55c2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-11T11:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-11T11:18:50.000Z", "max_issues_repo_path": "tile/lib/lib.cc", "max_issues_repo_name": "HubBucket-Team/plaidml", "max_issues_repo_head_hexsha": "762d5fff6467b43a15623f927502892ce8df91a4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tile/lib/lib.cc", "max_forks_repo_name": "HubBucket-Team/plaidml", "max_forks_repo_head_hexsha": "762d5fff6467b43a15623f927502892ce8df91a4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-09-11T11:18:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-11T11:18:52.000Z", "avg_line_length": 34.7440347072, "max_line_length": 118, "alphanum_fraction": 0.5959293251, "num_tokens": 4666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.4225046348141883, "lm_q1q2_score": 0.2211475233816566}}
{"text": "/*\n* LEGAL NOTICE\n* This computer software was prepared by Battelle Memorial Institute,\n* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830\n* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE\n* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY\n* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this\n* sentence must appear on any copies of this computer software.\n* \n* EXPORT CONTROL\n* User agrees that the Software will not be shipped, transferred or\n* exported into any country or used in any manner prohibited by the\n* United States Export Administration Act or any other applicable\n* export laws, restrictions or regulations (collectively the \"Export Laws\").\n* Export of the Software may require some form of license or other\n* authority from the U.S. Government, and failure to obtain such\n* export control license may result in criminal liability under\n* U.S. laws. In addition, if the Software is identified as export controlled\n* items under the Export Laws, User represents and warrants that User\n* is not a citizen, or otherwise located within, an embargoed nation\n* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)\n*     and that User is not otherwise prohibited\n* under the Export Laws from receiving the Software.\n* \n* Copyright 2011 Battelle Memorial Institute.  All Rights Reserved.\n* Distributed as open-source under the terms of the Educational Community \n* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php\n* \n* For further details, see: http://www.globalchange.umd.edu/models/gcam/\n*\n*/\n\n\n/*!\n * wind_technology.cpp\n * Created: 03/20/2007\n * Version: 04/16/2007\n *\n * This software, which is provided in confidence, was prepared by employees\n * of Pacific Northwest National Laboratory operated by Battelle Memorial\n * Institute. Battelle has certain unperfected rights in the software\n * which should not be copied or otherwise disseminated outside your\n * organization without the express written authorization from Battelle.\n * All rights to the software are reserved by Battelle.   Battelle makes no\n * warranty, express or implied, and assumes no liability or responsibility\n * for the use of this software.\n */\n\n// include files ***********************************************************\n\n#include \"util/base/include/definitions.h\"\n#include \"technologies/include/wind_technology.h\"\n#include \"technologies/include/marginal_profit_calculator.h\"\n#include \"technologies/include/iproduction_state.h\"\n#include \"marketplace/include/marketplace.h\"\n#include \"containers/include/iinfo.h\"\n#include \"util/base/include/TValidatorInfo.h\"\n#include \"util/base/include/util.h\"\n#include \"util/base/include/xml_helper.h\"\n#include \"technologies/include/ioutput.h\"\n#include \"functions/include/non_energy_input.h\"\n\n#include <sstream>\n#include <algorithm>\n#include <cmath>\n\n#include <boost/math/special_functions/erf.hpp>\nusing boost::math::erf;\n\n// namespaces **************************************************************\n\n// WindTechnology::kWhrtoGJ ************************************************\n\nconst double WindTechnology::kWhrtoGJ = 0.0036;\n\n// WindTechnology::sXMLTagNames ********************************************\n\nstd::string WindTechnology::sXMLTagNames[] =\n{\n   std::string( \"air-density\" ),\n   std::string( \"average-wind-speed\" ),\n   std::string( \"capital-cost\" ),\n   std::string( \"cutout-speed\" ),\n   std::string( \"fcr\" ),\n   std::string( \"grid-connection-cost\" ),\n   std::string( \"om\" ),\n   std::string( \"reference-height\" ),\n   std::string( \"rotor-diameter\" ),\n   std::string( \"turbine-density\" ),\n   std::string( \"turbine-derating\" ),\n   std::string( \"turbine-hub-height\" ),\n   std::string( \"turbine-rating\" ),\n   std::string( \"wind-farm-loss\" ),\n   std::string( \"wind-velocity-exponent\" )\n};\n\n// Constructor: WindTechnology *********************************************\n\n/*! Default constructor\n *  \\param aName the name of the technology\n *  \\param aYear the year\n */\nWindTechnology::WindTechnology(\n   const std::string& aName,\n   const int          aYear )\n   : IntermittentTechnology( aName, aYear )\n{\n    mCapitalCost = 261.83;\n    mConnectCost = -1;\n    mCutOutSpeed = -1;\n    mFCR = 0.0856;\n    mGenerationCost = -1;\n    mGridConnectionCost = 392.75;\n    mOM = 2.62;\n    mRealizedTurbineOutput = -1;\n    mRotorDiameter = -1;\n    mTurbineDensity = -1;\n    mTurbineDerating = -1;\n    mTurbineHubHeight = -1;\n    mTurbineRating = -1;\n    mWindCapacityFactor = -1;\n    mWindFarmLoss = -1;\n}\n\n// Destructor: WindTechnology **********************************************\n\nWindTechnology::~WindTechnology(void)\n{\n}\n\nvoid WindTechnology::copy( const WindTechnology& aOther ) {\n    IntermittentTechnology::copy( aOther );\n    mCapitalCost = aOther.mCapitalCost;\n    mConnectCost = aOther.mConnectCost;\n    mCutOutSpeed = aOther.mCutOutSpeed;\n    mFCR = aOther.mFCR;\n    mGenerationCost = aOther.mGenerationCost;\n    mGridConnectionCost = aOther.mGridConnectionCost;\n    mOM = aOther.mOM;\n    mRealizedTurbineOutput = aOther.mRealizedTurbineOutput;\n    mRotorDiameter = aOther.mRotorDiameter;\n    mTurbineDensity = aOther.mTurbineDensity;\n    mTurbineDerating = aOther.mTurbineDerating;\n    mTurbineHubHeight = aOther.mTurbineHubHeight;\n    mTurbineRating = aOther.mTurbineRating;\n    mWindCapacityFactor = aOther.mWindCapacityFactor;\n    mWindFarmLoss = aOther.mWindFarmLoss;\n}\n\n// WindTechnology::calcCost ************************************************\n\n// Documentation is inherited\nvoid WindTechnology::calcCost(\n   const std::string& aRegionName,\n   const std::string& aSectorName,\n   const int          aPeriod )\n{\n    if( !mProductionState[ aPeriod ]->isOperating() ){\n        return;\n    }\n\n   // Var to hold capital and operating costs\n   double totalTechCapOMCost = 0;\n\n   // Get marketplace and calculate costs\n   Marketplace*       pMarketplace = scenario->getMarketplace();\n   const IInfo*       pInfo        = pMarketplace->getMarketInfo( ( *mResourceInput )->getName(), aRegionName, aPeriod, true );\n\n   // Equation 4:\n   mRealizedTurbineOutput = calcRealizedTurbineOutput( pInfo );\n\n   // Equation 3:\n   // WindCapacityFactor = RealizedTurbineOutput / TurbineRating\n   mWindCapacityFactor = mRealizedTurbineOutput / mTurbineRating;\n\n   // Equation 6:\n   // CConnect = FCR * DConnect * ( gridConnectionCost / ( WindCapacityFactor * 1000.0 * kWhrtoGJ * 24 * 365 * 1 ) )\n   double dConnect = pMarketplace->getPrice( ( *mResourceInput )->getName(), aRegionName, aPeriod );\n   mConnectCost    = mFCR * dConnect * ( mGridConnectionCost / ( mWindCapacityFactor * 1000.0 * kWhrtoGJ * 24.0 * 365.0 ) );\n\n   // Equation 2:\n   // CGeneration = ( FCR * CapitalCost + OM ) / ( 24 * 365 * WindCapacityFactor * kWhrtoGJ )\n   mGenerationCost = ( mFCR * mCapitalCost + mOM ) / ( 24.0 * 365.0 * mWindCapacityFactor * kWhrtoGJ );\n\n   if( !mProductionState[ aPeriod ]->isNewInvestment() ||\n       mFixedOutput != IProductionState::fixedOutputDefault() )\n   {\n      // If an existing stock, only have O&M costs. \n      totalTechCapOMCost = mOM /  ( 24.0 * 365.0 * mWindCapacityFactor * kWhrtoGJ );\n   }\n   else {\n      // Generation plus connection costs. \n      totalTechCapOMCost = std::max( mGenerationCost + mConnectCost, util::getSmallNumber() );\n   }\n\n   // Set tech capital and operating costs to input object\n   ( *mTechCostInput )->setPrice( aRegionName, totalTechCapOMCost, aPeriod );\n    \n   // Call parent function to set costs and coefficients\n   IntermittentTechnology::calcCost( aRegionName, aSectorName, aPeriod );\n  \n}\n\n// WindTechnology::calcIdealTurbineOutput **********************************\n\n/*! \n *  \\param aAveWindSpeed the average Wind Speed\n *  \\param aDiameter the turbine blade diameter (in meters)\n *  \\param aAirDensity the average Air density (in g/m^3)\n */\ndouble WindTechnology::calcIdealTurbineOutput(\n   double aAveWindSpeed,\n    double aDiameter,\n    double aAirDensity )\n{\n   /*\n    * The ideal maximum extractable power, known as the Betz limit, has a\n    * coefficient of Cp = 16/27. At this limit, the integral evaluates to\n    * (Equation A-6):\n    *   Prb = p * ( 2 / 3 * D )^2 * V^3\n    * where:\n    *   p = the average Air density (in g/m^3)\n    *   D = the turbine blade diameter (in meters)\n    *   V = the average Wind Speed\n    */\n   return aAirDensity * std::pow( 2.0 / 3.0 * aDiameter, 2.0 ) * std::pow( aAveWindSpeed, 3.0 );\n}\n\n// WindTechnology::calcRealizedTurbineOutput *******************************\n/*! Compute the realized turbine output\n *  \\param apInfo pointer to the market info\n */\ndouble WindTechnology::calcRealizedTurbineOutput( const IInfo* apInfo ) const\n{\n   // Equation 5:\n   // aveWindSpeedAtHub = aveWindSpeed * ( turbineHubHeight / referenceHeight ) ^ windVelocityExponent\n   double aveWindSpeed = apInfo->getDouble( sXMLTagNames[ AVERAGE_WIND_SPEED_KEY ], true );\n   double referenceHeight = apInfo->getDouble( sXMLTagNames[ REFERENCE_HEIGHT_KEY ], true );\n   double windVelocityExponent = apInfo->getDouble( sXMLTagNames[ WIND_VELOCITY_EXPONENT_KEY ], true );\n   double aveWindSpeedAtHub = aveWindSpeed * std::pow( mTurbineHubHeight / referenceHeight, windVelocityExponent );\n\n   // Equation 4:\n   // RealizedTurbineOutput = ( IdealTurbineOutput / 10^6 ) * TurbineCoefficient * ( 1 - Derating ) * ( 1 - WindFarmLoss )\n   double airDensity = apInfo->getDouble( sXMLTagNames[ AIR_DENSITY_KEY ], true );\n   double realizedTurbineOutput = ( calcIdealTurbineOutput( aveWindSpeedAtHub, mRotorDiameter, airDensity ) / 1.0e6 ) * calcTurbineCoefficient( aveWindSpeedAtHub, mTurbineRating, mRotorDiameter, airDensity, mCutOutSpeed ) * ( 1.0 - mTurbineDerating ) * ( 1.0 - mWindFarmLoss );\n   mWindPowerVariance = computeWindPowerVariance( aveWindSpeedAtHub, mTurbineRating, mRotorDiameter, airDensity, mCutOutSpeed );\n   return realizedTurbineOutput;\n}\n\n// WindTechnology::calcResourceArea ****************************************\n\n/*! Calculate the resource area in km^2\n *  NOTE: Unlike solar techs, wind does not exclusively use this land. This need to be \n *  accounted for when setting land costs.\n *  \\param aRegionName the region name\n *  \\param aSectorName the sector name\n *  \\param aVariableDemand the variable demand\n *  \\param aPeriod the period\n *  \\return the resource area\n */\ndouble WindTechnology::calcResourceArea(\n   const std::string& aRegionName,\n   const std::string& aSectorName,\n   double             aVariableDemand,\n   const int          aPeriod )\n{\n   // Get info object for this resource \n   Marketplace*       pMarketplace = scenario->getMarketplace();\n   const IInfo*       pInfo        = pMarketplace->getMarketInfo( ( *mResourceInput )->getName(), aRegionName, aPeriod, true );\n\n   // Equation 4:\n   mRealizedTurbineOutput = calcRealizedTurbineOutput( pInfo );\n\n   // Equation 3:\n   // WindCapacityFactor = RealizedTurbineOutput / TurbineRating\n   mWindCapacityFactor = mRealizedTurbineOutput / mTurbineRating;\n\n   // Equation 7:\n   // WindGeneration / ( kWhrtoGJ * 10^-9 ) = TurbineDensity * ResourceArea * WindCapacityFactor * 1000 * 24 * 365\n   // ResourceArea = ( WindGeneration / ( kWhrtoGJ * 10^-9 ) ) / ( TurbineDensity * WindCapacityFactor * 1000 * 24 * 365 )\n   double windGeneration = aVariableDemand;\n   double resourceArea = ( windGeneration / ( kWhrtoGJ * 1.0e-9 ) ) / ( mTurbineDensity * mWindCapacityFactor * 1000.0 * 24.0 * 365.0 );\n\n   return resourceArea;\n}\n\n/*! \\brief Return amount of resource needed per unit of energy output.\n*  This method should be used when a technology uses a resource that is\n*  not in energy units. \n*  NOTE: Unlike solar techs, wind does not exclusively use this land. This need to be \n*  accounted for when setting land costs.\n* \\author Steve Smith\n* \\param aPeriod Model period.\n*/\ndouble WindTechnology::getResourceToEnergyRatio( const std::string& aRegionName,\n                                                 const std::string& aSectorName,\n                                                 const int aPeriod )\n{\n    // Default assumpion is that resource is in energy units\n   // Need to return the amount of resource (in km^2) needed per EJ of energy output\n   return calcResourceArea( aRegionName, aSectorName, 1.0, aPeriod );\n}\n\n// WindTechnology::calcTurbineCoefficient **********************************\n\n/*! Compute the capture coefficient for a turbine with a finite power rating.\n *  \\param aAveWindSpeed the average Wind Speed\n *  \\param aRating the turbine Rating (in MW)\n *  \\param aDiameter the turbine Blade Diameter (in meters)\n *  \\param aAirDensity the average Air density (in g/m^3)\n *  \\param aCutoutSpeed the cut-out Speed (m/s)\n */\ndouble WindTechnology::calcTurbineCoefficient(\n   double aAveWindSpeed,\n    double aRating,\n    double aDiameter,\n    double aAirDensity,\n    double aCutoutSpeed )\n{\n   static const double PI     = 2.0 * std::asin( 1.0 );\n   static const double sqrtPI = std::sqrt( PI );\n\n   /*\n    * Equation A-8\n    * Calculate the final cutout speed (Xf)\n    *   Xs = ( sqrt( pi ) / 2) * ( Vs / Vave )\n    */\n   double Xf = ( sqrtPI / 2.0 ) * ( aCutoutSpeed / aAveWindSpeed );\n\n   /*\n    * Equation A-10\n    * Calculate the velocity (solve for v)\n    * 1/8pD^2(16/27)v^3 = Prated\n    * v = cube-root( Prated / ( 1/8pD^2(16/27) )\n    */\n   double aRatingInWatts = aRating * 1.0e6;\n   double velocity = std::pow( aRatingInWatts / ( 1.0 / 8.0 * aAirDensity * PI * std::pow( aDiameter, 2.0 ) * 16.0 / 27.0 ), 1.0 / 3.0 );\n\n   /*\n    * Equation A-11\n    * Calculate the finite power rating (Xr)\n    * Xr = ( sqrt( pi ) / 2 ) * V / Vave\n    */\n   double Xr = ( sqrtPI / 2.0 ) * velocity / aAveWindSpeed;\n\n   /*\n    * Equation A-7:\n    * Compute the power up to a finite cutout for Xr\n    * speed is ():\n    *\n    *   CCfinite_cutout( Xs ) =\n    *      Erf( Xs ) - ( 4 / ( 3 * sqrt( pi ) ) ) * Xs * ( Xs^2 + 3 / 2 ) * e^-Xs^2\n    */\n   double CCfiniteCutout = erf( Xr ) - ( 4.0 / ( 3.0 * sqrtPI ) ) * Xr * ( std::pow( Xr, 2.0 ) + 3.0 / 2.0 ) * std::exp( -std::pow( Xr, 2.0 ) );\n\n   /*\n    * Equation A-9:\n    * Finally, compute the capture coefficient\n    * CCfinite_power( Xr, Xf ) = \n    *    CCfinite_cutout( Xr ) + ( Xr^3 / ( 3 / 4 * sqrt( pi ) ) ) * ( e ^-Xr^2 - e^-Xf^2 )\n    */\n   double CCfinitePower = CCfiniteCutout + ( std::pow( Xr, 3.0 ) / ( 3.0 / 4.0 * sqrtPI ) ) * ( std::exp( -std::pow( Xr, 2.0 ) ) - std::exp( -std::pow( Xf, 2.0 ) ) );\n\n   return CCfinitePower;\n}\n\n// WindTechnology::clone ***************************************************\n\n// Documentation is inherited\nWindTechnology* WindTechnology::clone( void ) const\n{\n    WindTechnology* clone = new WindTechnology( mName, mYear );\n    clone->copy( *this );\n    return clone;\n}\n\n// WindTechnology::completeInit ********************************************\n\n// Documentation is inherited\nvoid WindTechnology::completeInit(\n   const std::string&              aRegionName,\n   const std::string&              aSectorName,\n   const std::string&              aSubsectorName,\n   const IInfo*                    aSubsectorIInfo,\n   ILandAllocator*                 aLandAllocator )\n{\n   // Initialize a non-energy input to hold technology costs\n   if( util::searchForValue( mInputs, getTechCostName() ) == mInputs.end() ){\n        mInputs.push_back( new NonEnergyInput( getTechCostName() ) );\n    }\n\n   IntermittentTechnology::completeInit( aRegionName, aSectorName, aSubsectorName, aSubsectorIInfo, aLandAllocator );\n\n   // Validate input parameters\n   typedef ObjECTS::TValidatorInfo<> validator_type;\n   validator_type   validator[] =\n   {\n      validator_type( mCapitalCost, sXMLTagNames[ CAPITAL_COST_KEY ], mCapitalCost > 0 ),\n      validator_type( mCutOutSpeed, sXMLTagNames[ CUTOUT_SPEED_KEY ], mCutOutSpeed > 0 ),\n      validator_type( mFCR, sXMLTagNames[ FCR_KEY ], mFCR > 0 ),\n      validator_type( mRotorDiameter, sXMLTagNames[ ROTOR_DIAMETER_KEY ], mRotorDiameter > 0 ),\n      validator_type( mTurbineDensity, sXMLTagNames[ TURBINE_DENSITY_KEY ], mTurbineDensity > 0 ),\n      validator_type( mTurbineDerating, sXMLTagNames[ TURBINE_DERATING_KEY ], mTurbineDerating > 0 ),\n      validator_type( mTurbineHubHeight, sXMLTagNames[ TURBINE_HUB_HEIGHT_KEY ], mTurbineHubHeight > 0 ),\n      validator_type( mTurbineRating, sXMLTagNames[ TURBINE_RATING_KEY ], mTurbineRating > 0 ),\n      validator_type( mWindFarmLoss, sXMLTagNames[ WIND_FARM_LOSS_KEY ], mWindFarmLoss > 0 )\n   };\n\n   unsigned short numParams = sizeof( validator ) / sizeof( validator[0] );\n   std::string    msg       = ObjECTS::getInvalidNames(\n      &validator[0],\n      &validator[numParams] );\n\n   if ( msg.length() )\n   // Invalid input parameter\n   {\n      ILogger& mainLog = ILogger::getLogger( \"main_log\" );\n      mainLog.setLevel( ILogger::ERROR );\n      mainLog << \"Invalid input parameter(s) to \"\n         << getXMLNameStatic()\n         << \" in sector \" << aSectorName\n         << \": \" << msg << std::endl;\n      exit( -1 );\n   }\n}\n\n// WindTechnology::getXMLName1D ********************************************\n\n// Documentation is inherited\nconst std::string& WindTechnology::getXMLName1D( void ) const\n{\n   return getXMLNameStatic();\n}\n\n// WindTechnology::getXMLNameStatic1D **************************************\n\n// Documentation is inherited\nconst std::string& WindTechnology::getXMLNameStatic1D( void )\n{\n   static const std::string XML_NAME1D = \"wind-technology\";\n\n   return XML_NAME1D;\n}\n\n/*! \\brief Return name to be used for input object containing technology costs.\n*\n* This input object will contain technology capital, operation, and any other costs\n* exclusive of backup or fuel costs. Setting to blank indicates that this object does\n* not use this cost.\n*\n* \\author Steve Smith\n* \\return The constant XML_NAME as a static.\n*/\nconst std::string& WindTechnology::getTechCostName( ) const {\n   const static std::string TECH_COST_NAME = \"turbine-and-connect-costs\";\n   return TECH_COST_NAME;\n}\n\n// WindTechnology::initCalc ************************************************\n\n// Documentation is inherited\nvoid WindTechnology::initCalc(\n   const std::string& aRegionName,\n   const std::string& aSectorName,\n   const IInfo*       aSubsectorIInfo,\n   const Demographic* aDemographics,\n   PreviousPeriodInfo& aPrevPeriodInfo,\n   const int          aPeriod )\n{\n   IntermittentTechnology::initCalc( aRegionName, aSectorName, aSubsectorIInfo, aDemographics, \n       aPrevPeriodInfo, aPeriod );\n\n   // Get marketplace and make sure we have the correct type of resource\n   Marketplace*       pMarketplace = scenario->getMarketplace();\n   const IInfo*       pInfo        = pMarketplace->getMarketInfo( ( *mResourceInput )->getName(), aRegionName, aPeriod, true );\n   std::string        msg          = \"\";\n\n   if ( !pInfo )\n   {\n      std::ostringstream ostr;\n      ostr << \"Error getting marketplace info for ( \"\n           << ( *mResourceInput )->getName() << \", \"\n           << aRegionName << \", \"\n           << aPeriod << \" )\"\n           << std::ends;\n      msg = ostr.str();\n   }\n   else\n   {\n      typedef ObjECTS::TValidatorInfo<> validator_type;\n      double           notUsed=0.0;\n      validator_type   validator[] =\n      {\n         validator_type( notUsed, sXMLTagNames[ AVERAGE_WIND_SPEED_KEY ], pInfo->hasValue( sXMLTagNames[ AVERAGE_WIND_SPEED_KEY ] ) ),\n         validator_type( notUsed, sXMLTagNames[ AIR_DENSITY_KEY ], pInfo->hasValue( sXMLTagNames[ AIR_DENSITY_KEY ] ) ),\n         validator_type( notUsed, sXMLTagNames[ REFERENCE_HEIGHT_KEY ], pInfo->hasValue( sXMLTagNames[ REFERENCE_HEIGHT_KEY ] ) ),\n         validator_type( notUsed, sXMLTagNames[ WIND_VELOCITY_EXPONENT_KEY ], pInfo->hasValue( sXMLTagNames[ WIND_VELOCITY_EXPONENT_KEY ] ) )\n      };\n\n      unsigned short numParams = sizeof( validator ) / sizeof( validator[0] );\n      msg = ObjECTS::getInvalidNames(\n         &validator[0],\n         &validator[numParams] );\n      if ( msg.length() )\n      {\n         std::ostringstream ostr;\n         ostr << \"Invalid input parameter(s) to \"\n              << getXMLNameStatic()\n              << \" in sector \" << aSectorName\n              << \": \" << msg << std::ends;\n         msg = ostr.str();\n      }\n   }\n\n   if ( msg.length() )\n      // Invalid input parameter\n   {\n      ILogger& mainLog = ILogger::getLogger( \"main_log\" );\n      mainLog.setLevel( ILogger::ERROR );\n      mainLog << msg << std::endl;\n   }\n}\n\n// WindTechnology::production **********************************************\n\ndouble WindTechnology::getCalibrationOutput( const bool aHasRequiredInput,\n                                         const std::string& aRequiredInput,\n                                         const int aPeriod ) const\n{\n   return IntermittentTechnology::getCalibrationOutput( aHasRequiredInput, aRequiredInput, aPeriod );\n}\n\n// WindTechnology::toDebugXMLDerived ***************************************\n\n// Documentation is inherited\nvoid WindTechnology::toDebugXMLDerived(\n   const int     period,\n   std::ostream& out,\n   Tabs*         tabs ) const\n{\n   IntermittentTechnology::toDebugXMLDerived( period, out,  tabs );\n   XMLWriteElement( mCapitalCost, sXMLTagNames[ CAPITAL_COST_KEY ], out, tabs );\n   XMLWriteElement( mConnectCost, \"connection-cost\", out, tabs );\n   XMLWriteElement( mCutOutSpeed, sXMLTagNames[ CUTOUT_SPEED_KEY ], out, tabs );\n   XMLWriteElement( mFCR, sXMLTagNames[ FCR_KEY ], out, tabs );\n   XMLWriteElement( mGenerationCost, \"generation-cost\", out, tabs );\n   XMLWriteElement( mGridConnectionCost, sXMLTagNames[ GRID_CONNECTION_COST_KEY ], out, tabs );\n   XMLWriteElement( mOM, sXMLTagNames[ OM_KEY ], out, tabs );\n   XMLWriteElement( mRealizedTurbineOutput, \"realized-turbine-output\", out, tabs );\n   XMLWriteElement( mRotorDiameter, sXMLTagNames[ ROTOR_DIAMETER_KEY ], out, tabs );\n   XMLWriteElement( mTurbineDensity, sXMLTagNames[ TURBINE_DENSITY_KEY ], out, tabs );\n   XMLWriteElement( mTurbineDerating, sXMLTagNames[ TURBINE_DERATING_KEY ], out, tabs );\n   XMLWriteElement( mTurbineHubHeight, sXMLTagNames[ TURBINE_HUB_HEIGHT_KEY ], out, tabs );\n   XMLWriteElement( mTurbineRating, sXMLTagNames[ TURBINE_RATING_KEY ], out, tabs );\n   XMLWriteElement( mWindCapacityFactor, \"wind-capacity-factor\", out, tabs );\n   XMLWriteElement( mWindFarmLoss, sXMLTagNames[ WIND_FARM_LOSS_KEY ], out, tabs );\n   XMLWriteElement( mWindPowerVariance, \"wind-power-variance\", out, tabs );\n}\n\n// WindTechnology::toInputXMLDerived ***************************************\n\n// Documentation is inherited\nvoid WindTechnology::toInputXMLDerived(\n   std::ostream& out,\n   Tabs*         tabs ) const\n{\n   IntermittentTechnology::toInputXMLDerived( out,  tabs );\n   XMLWriteElementCheckDefault( mCapitalCost, sXMLTagNames[ CAPITAL_COST_KEY ], out, tabs, double( 1000.0 ) );\n   XMLWriteElement( mCutOutSpeed, sXMLTagNames[ CUTOUT_SPEED_KEY ], out, tabs );\n   XMLWriteElementCheckDefault( mFCR, sXMLTagNames[ FCR_KEY ], out, tabs, double( 0.0856 ) );\n   XMLWriteElementCheckDefault( mGridConnectionCost, sXMLTagNames[ GRID_CONNECTION_COST_KEY ], out, tabs, double( 1500.0 ) );\n   XMLWriteElementCheckDefault( mOM, sXMLTagNames[ OM_KEY ], out, tabs, double( 10.0 ) );\n   XMLWriteElement( mRotorDiameter, sXMLTagNames[ ROTOR_DIAMETER_KEY ], out, tabs );\n   XMLWriteElement( mTurbineDensity, sXMLTagNames[ TURBINE_DENSITY_KEY ], out, tabs );\n   XMLWriteElement( mTurbineDerating, sXMLTagNames[ TURBINE_DERATING_KEY ], out, tabs );\n   XMLWriteElement( mTurbineHubHeight, sXMLTagNames[ TURBINE_HUB_HEIGHT_KEY ], out, tabs );\n   XMLWriteElement( mTurbineRating, sXMLTagNames[ TURBINE_RATING_KEY ], out, tabs );\n   XMLWriteElement( mWindFarmLoss, sXMLTagNames[ WIND_FARM_LOSS_KEY ], out, tabs );\n}\n\n// WindTechnology::XMLDerivedClassParse ************************************\n\n// Documentation is inherited\nbool WindTechnology::XMLDerivedClassParse(\n   const std::string&      nodeName,\n   const xercesc::DOMNode* curr )\n{\n   if ( nodeName == sXMLTagNames[ CAPITAL_COST_KEY ] )\n   {\n      mCapitalCost = XMLHelper<double>::getValue( curr );\n   }\n   else if ( nodeName == sXMLTagNames[ CUTOUT_SPEED_KEY ] )\n   {\n      mCutOutSpeed = XMLHelper<double>::getValue( curr );\n   }\n   else if ( nodeName == sXMLTagNames[ FCR_KEY ] )\n   {\n      mFCR = XMLHelper<double>::getValue( curr );\n   }\n   else if ( nodeName == sXMLTagNames[ GRID_CONNECTION_COST_KEY ] )\n   {\n      mGridConnectionCost = XMLHelper<double>::getValue( curr );\n   }\n   else if ( nodeName == sXMLTagNames[ OM_KEY ] )\n   {\n      mOM = XMLHelper<double>::getValue( curr );\n   }\n   else if ( nodeName == sXMLTagNames[ ROTOR_DIAMETER_KEY ] )\n   {\n      mRotorDiameter = XMLHelper<double>::getValue( curr );\n   }\n   else if ( nodeName == sXMLTagNames[ TURBINE_DENSITY_KEY ] )\n   {\n      mTurbineDensity = XMLHelper<double>::getValue( curr );\n   }\n   else if ( nodeName == sXMLTagNames[ TURBINE_DERATING_KEY ] )\n   {\n      mTurbineDerating = XMLHelper<double>::getValue( curr );\n   }\n   else if ( nodeName == sXMLTagNames[ TURBINE_HUB_HEIGHT_KEY ] )\n   {\n      mTurbineHubHeight = XMLHelper<double>::getValue( curr );\n   }\n   else if ( nodeName == sXMLTagNames[ TURBINE_RATING_KEY ] )\n   {\n      mTurbineRating = XMLHelper<double>::getValue( curr );\n   }\n   else if ( nodeName == sXMLTagNames[ WIND_FARM_LOSS_KEY ] )\n   {\n      mWindFarmLoss = XMLHelper<double>::getValue( curr );\n   }\n   else if ( IntermittentTechnology::XMLDerivedClassParse( nodeName, curr ) ) {\n   }\n   else\n   {\n      return false;\n   }\n\n   return true;\n}\n\n\n/*\n   The one parameter Weibull distribution is (Equation A-1):\n   f( x ) = ( B / c ) * ( x / c )^(B - 1) * e^-( x / c )^B\n\n   The mean of the distribution is (Equation A-2):\n   X = c * gamma * ( 1 / B + 1)\n\n   The mean wind speed is (Equation A-3):\n   X = c * gamma * 1.5 = ( sqrt( pi ) / 2 ) * c\n   or\n   c = X / a = 2X / sqrt( pi ) * a = sqrt( pi ) / 2 = 0.88623\n\n   The wind distribution for a mean wind speed of is (Equation A-4):\n   f( v ) = ( pi * v / 2X^2 ) * e^( -pi * ( v / 2X )^2\n\n   Equation A-8:\n   Xf = ( sqrt( pi ) / 2 ) * ( Vf / Vave )\n\n   Equation A-10:\n   1/2 * p * A * Cp * v^3 = 1 / 8 * p * D^2 * ( 16 / 27 ) * v^3 = Prated\n\n   Equation A-18:\n   (16 / 9 * pi) * Prb^2 * { 6 - [ Xr^6 + 3 Xr^4 + 6Xr^2 + 6 ]e^(-(Xr)^2) + Xr^6[ e^(-(Xr)^2) - e^(-(Xf)^2)]} = (16 / 9 * pi) * G( Xr, Xf ) * Prb^2\n\n   Equation A-19:\n   Var(P^2) = [ ( 16 / 9 * pi ) * G( Xr, Xf ) - CCfinite-power^2( Xr, Xf ) ] * Prb^2\n*/\ndouble WindTechnology::computeWindPowerVariance(\n   double aAveWindSpeed,\n    double aRating,\n    double aDiameter,\n    double aAirDensity,\n    double aCutoutSpeed ) const\n{\n   static const double PI     = 2.0 * std::asin( 1.0 );\n\n   // Equation A-18:\n   // (16 / 9 * pi) * Prb^2 * { 6 - [ Xr^6 + 3 Xr^4 + 6Xr^2 + 6 ]e^(-(Xr)^2) + Xr^6[ e^(-(Xr)^2) - e^(-(Xf)^2)]} = (16 / 9 * pi) * G( Xr, Xf ) * Prb^2\n   // Xr = rating\n   // Xf = cutout speed\n   double G = ( 6.0 - ( std::pow( aRating, 6.0 ) + 3.0 * std::pow( aRating, 4.0 ) + 6.0 * std::pow( aRating, 2.0 ) + 6.0 ) * std::exp( -std::pow( aRating, 2.0) ) + std::pow( aRating, 6.0 ) * ( std::exp( -std::pow( aRating, 2.0) ) - std::exp( -std::pow( aCutoutSpeed, 2.0 ) ) ) );\n\n   // Equation A-19:\n   // Var(P^2) = [ ( 16 / 9 * pi ) * G( Xr, Xf ) - CCfinite-power^2( Xr, Xf ) ] * Prb^2\n   // Xr = rating\n   // Xf = cutout speed\n   double windPowerVariance = ( 16.0 / 9.0 * PI * G - std::pow( WindTechnology::calcTurbineCoefficient( aAveWindSpeed, aRating, aDiameter, aAirDensity, aCutoutSpeed ), 2.0 ) ) * std::pow( WindTechnology::calcIdealTurbineOutput( aAveWindSpeed, aDiameter, aAirDensity ), 2.0 );\n\n   return windPowerVariance;\n}\n\n// end of wind_technology.cpp **********************************************\n\n", "meta": {"hexsha": "a19de175f5a710b0795b09970cefb48d8bf1f24c", "size": 27535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cvs/objects/technologies/source/wind_technology.cpp", "max_stars_repo_name": "crvernon/gcam-core", "max_stars_repo_head_hexsha": "bbfb78aeb0cde4d75f307fc3967526d70157c2f8", "max_stars_repo_licenses": ["ECL-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": "cvs/objects/technologies/source/wind_technology.cpp", "max_issues_repo_name": "crvernon/gcam-core", "max_issues_repo_head_hexsha": "bbfb78aeb0cde4d75f307fc3967526d70157c2f8", "max_issues_repo_licenses": ["ECL-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": "cvs/objects/technologies/source/wind_technology.cpp", "max_forks_repo_name": "crvernon/gcam-core", "max_forks_repo_head_hexsha": "bbfb78aeb0cde4d75f307fc3967526d70157c2f8", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-26T05:56:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T10:29:30.000Z", "avg_line_length": 39.5617816092, "max_line_length": 279, "alphanum_fraction": 0.6514617759, "num_tokens": 7836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.22114751709966018}}
{"text": "/*\n Copyright (C) 2018 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n#include <qle/pricingengines/crossccyswapengine.hpp>\n#ifdef QL_USE_INDEXED_COUPON\n#include <ql/cashflows/floatingratecoupon.hpp>\n#endif\n\n#include <qle/termstructures/crossccybasismtmresetswaphelper.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantExt {\n\nnamespace {\nvoid no_deletion(YieldTermStructure*) {}\n} // namespace\n\nCrossCcyBasisMtMResetSwapHelper::CrossCcyBasisMtMResetSwapHelper(\n    const Handle<Quote>& spreadQuote, const Handle<Quote>& spotFX, Natural settlementDays,\n    const Calendar& settlementCalendar, const Period& swapTenor, BusinessDayConvention rollConvention,\n    const boost::shared_ptr<QuantLib::IborIndex>& foreignCcyIndex,\n    const boost::shared_ptr<QuantLib::IborIndex>& domesticCcyIndex,\n    const Handle<YieldTermStructure>& foreignCcyDiscountCurve,\n    const Handle<YieldTermStructure>& domesticCcyDiscountCurve,\n    const Handle<YieldTermStructure>& foreignCcyFxFwdRateCurve,\n    const Handle<YieldTermStructure>& domesticCcyFxFwdRateCurve, bool eom, bool spreadOnForeignCcy, bool invertFxIndex,\n    boost::optional<Period> foreignTenor, boost::optional<Period> domesticTenor)\n    : RelativeDateRateHelper(spreadQuote), spotFX_(spotFX), settlementDays_(settlementDays),\n      settlementCalendar_(settlementCalendar), swapTenor_(swapTenor), rollConvention_(rollConvention),\n      foreignCcyIndex_(foreignCcyIndex), domesticCcyIndex_(domesticCcyIndex),\n      foreignCcyDiscountCurve_(foreignCcyDiscountCurve), domesticCcyDiscountCurve_(domesticCcyDiscountCurve),\n      foreignCcyFxFwdRateCurve_(foreignCcyFxFwdRateCurve), domesticCcyFxFwdRateCurve_(domesticCcyFxFwdRateCurve),\n      eom_(eom), spreadOnForeignCcy_(spreadOnForeignCcy), invertFxIndex_(invertFxIndex),\n      foreignTenor_(foreignTenor ? *foreignTenor : foreignCcyIndex_->tenor()),\n      domesticTenor_(domesticTenor ? *domesticTenor : domesticCcyIndex_->tenor()) {\n\n    foreignCurrency_ = foreignCcyIndex_->currency();\n    domesticCurrency_ = domesticCcyIndex_->currency();\n    QL_REQUIRE(foreignCurrency_ != domesticCurrency_,\n               \"matching currencies not allowed on CrossCcyBasisMtMResetSwapHelper\");\n\n    bool foreignIndexHasCurve = !foreignCcyIndex_->forwardingTermStructure().empty();\n    bool domesticIndexHasCurve = !domesticCcyIndex_->forwardingTermStructure().empty();\n    bool haveForeignDiscountCurve = !foreignCcyDiscountCurve_.empty();\n    bool haveDomesticDiscountCurve = !domesticCcyDiscountCurve_.empty();\n\n    QL_REQUIRE(\n        !(foreignIndexHasCurve && domesticIndexHasCurve && haveForeignDiscountCurve && haveDomesticDiscountCurve),\n        \"CrossCcyBasisMtMResetSwapHelper - Have all curves, nothing to solve for.\");\n\n    /* Link the curve being bootstrapped to the index if the index has\n    no projection curve */\n    if (foreignIndexHasCurve && haveForeignDiscountCurve) {\n        if (!domesticIndexHasCurve) {\n            domesticCcyIndex_ = domesticCcyIndex_->clone(termStructureHandle_);\n            domesticCcyIndex_->unregisterWith(termStructureHandle_);\n        }\n        // if we have both index and discounting curve on foreign leg,\n        // check foreignCcyFxFwdRateCurve and link it to foreign discount curve if empty\n        // (we are bootstrapping on domestic leg in this instance, so foreign leg needs to be fully determined\n        if (foreignCcyFxFwdRateCurve_.empty())\n            foreignCcyFxFwdRateCurve_ = foreignCcyDiscountCurve_;\n    } else if (domesticIndexHasCurve && haveDomesticDiscountCurve) {\n        if (!foreignIndexHasCurve) {\n            foreignCcyIndex_ = foreignCcyIndex_->clone(termStructureHandle_);\n            foreignCcyIndex_->unregisterWith(termStructureHandle_);\n        }\n        // if we have both index and discounting curve on domestic leg,\n        // check domesticCcyFxFwdRateCurve and link it to domestic discount curve if empty\n        // (we are bootstrapping on foreign leg in this instance, so domestic leg needs to be fully determined\n        if (domesticCcyFxFwdRateCurve_.empty())\n            domesticCcyFxFwdRateCurve_ = domesticCcyDiscountCurve_;\n    } else {\n        QL_FAIL(\"Need one leg of the cross currency basis swap to \"\n                \"have all of its curves.\");\n    }\n\n    registerWith(spotFX_);\n    registerWith(domesticCcyIndex_);\n    registerWith(foreignCcyIndex_);\n    registerWith(foreignCcyDiscountCurve_);\n    registerWith(domesticCcyDiscountCurve_);\n    registerWith(foreignCcyFxFwdRateCurve_);\n    registerWith(domesticCcyFxFwdRateCurve_);\n\n    initializeDates();\n}\n\nvoid CrossCcyBasisMtMResetSwapHelper::initializeDates() {\n\n    Date refDate = evaluationDate_;\n    // if the evaluation date is not a business day\n    // then move to the next business day\n    refDate = settlementCalendar_.adjust(refDate);\n\n    Date settlementDate = settlementCalendar_.advance(refDate, settlementDays_, Days);\n    Date maturityDate = settlementDate + swapTenor_;\n\n    Schedule foreignLegSchedule = MakeSchedule()\n                                      .from(settlementDate)\n                                      .to(maturityDate)\n                                      .withTenor(foreignTenor_)\n                                      .withCalendar(settlementCalendar_)\n                                      .withConvention(rollConvention_)\n                                      .endOfMonth(eom_);\n\n    Schedule domesticLegSchedule = MakeSchedule()\n                                       .from(settlementDate)\n                                       .to(maturityDate)\n                                       .withTenor(domesticTenor_)\n                                       .withCalendar(settlementCalendar_)\n                                       .withConvention(rollConvention_)\n                                       .endOfMonth(eom_);\n\n    Real foreignNominal = 1.0;\n    // build an FX index for forward rate projection (TODO - review settlement and calendar)\n    boost::shared_ptr<FxIndex> fxIdx = boost::make_shared<FxIndex>(\n        \"dummy\", settlementDays_, foreignCurrency_, domesticCurrency_, settlementCalendar_, spotFX_,\n        foreignCcyFxFwdRateCurveRLH_, domesticCcyFxFwdRateCurveRLH_, invertFxIndex_);\n\n    swap_ = boost::shared_ptr<CrossCcyBasisMtMResetSwap>(\n        new CrossCcyBasisMtMResetSwap(foreignNominal, foreignCurrency_, foreignLegSchedule, foreignCcyIndex_, 0.0,\n                                      domesticCurrency_, domesticLegSchedule, domesticCcyIndex_, 0.0, fxIdx));\n\n    boost::shared_ptr<PricingEngine> engine;\n    if (invertFxIndex_) {\n        engine.reset(new CrossCcySwapEngine(foreignCurrency_, foreignDiscountRLH_, domesticCurrency_,\n                                            domesticDiscountRLH_, spotFX_));\n    } else {\n        engine.reset(new CrossCcySwapEngine(domesticCurrency_, domesticDiscountRLH_, foreignCurrency_,\n                                            foreignDiscountRLH_, spotFX_));\n    }\n    swap_->setPricingEngine(engine);\n\n    earliestDate_ = swap_->startDate();\n    latestDate_ = swap_->maturityDate();\n\n/* May need to adjust latestDate_ if you are projecting libor based\n   on tenor length rather than from accrual date to accrual date. */\n#ifdef QL_USE_INDEXED_COUPON\n    if (termStructureHandle_ == foreignCcyIndex_->forwardingTermStructure()) {\n        Size numCashflows = swap_->leg(0).size();\n        Date endDate = latestDate_;\n        if (numCashflows > 0) {\n            for (Size i = numCashflows - 1; i >= 0; i--) {\n                boost::shared_ptr<FloatingRateCoupon> lastFloating =\n                    boost::dynamic_pointer_cast<FloatingRateCoupon>(swap_->leg(0)[i]);\n                if (!lastFloating)\n                    continue;\n                else {\n                    Date fixingValueDate = foreignCcyIndex_->valueDate(lastFloating->fixingDate());\n                    endDate = domesticCcyIndex_->maturityDate(fixingValueDate);\n                    Date endValueDate = foreignCcyIndex_->maturityDate(fixingValueDate);\n                    latestDate_ = std::max(latestDate_, endValueDate);\n                    break;\n                }\n            }\n        }\n    }\n    if (termStructureHandle_ == domesticCcyIndex_->forwardingTermStructure()) {\n        Size numCashflows = swap_->leg(1).size();\n        Date endDate = latestDate_;\n        if (numCashflows > 0) {\n            for (Size i = numCashflows - 1; i >= 0; i--) {\n                boost::shared_ptr<FloatingRateCoupon> lastFloating =\n                    boost::dynamic_pointer_cast<FloatingRateCoupon>(swap_->leg(1)[i]);\n                if (!lastFloating)\n                    continue;\n                else {\n                    Date fixingValueDate = domesticCcyIndex_->valueDate(lastFloating->fixingDate());\n                    endDate = domesticCcyIndex_->maturityDate(fixingValueDate);\n                    Date endValueDate = domesticCcyIndex_->maturityDate(fixingValueDate);\n                    latestDate_ = std::max(latestDate_, endValueDate);\n                    break;\n                }\n            }\n        }\n    }\n#endif\n}\n\nvoid CrossCcyBasisMtMResetSwapHelper::setTermStructure(YieldTermStructure* t) {\n\n    bool observer = false;\n    boost::shared_ptr<YieldTermStructure> temp(t, no_deletion);\n\n    termStructureHandle_.linkTo(temp, observer);\n\n    if (foreignCcyDiscountCurve_.empty())\n        foreignDiscountRLH_.linkTo(temp, observer);\n    else\n        foreignDiscountRLH_.linkTo(*foreignCcyDiscountCurve_, observer);\n\n    if (domesticCcyDiscountCurve_.empty())\n        domesticDiscountRLH_.linkTo(temp, observer);\n    else\n        domesticDiscountRLH_.linkTo(*domesticCcyDiscountCurve_, observer);\n\n    // the below are the curves used for FX forward rate projection (for the resetting cashflows)\n    if (foreignCcyFxFwdRateCurve_.empty())\n        foreignCcyFxFwdRateCurveRLH_.linkTo(temp, observer);\n    else\n        foreignCcyFxFwdRateCurveRLH_.linkTo(*foreignCcyFxFwdRateCurve_, observer);\n\n    if (domesticCcyFxFwdRateCurve_.empty())\n        domesticCcyFxFwdRateCurveRLH_.linkTo(temp, observer);\n    else\n        domesticCcyFxFwdRateCurveRLH_.linkTo(*domesticCcyFxFwdRateCurve_, observer);\n\n    RelativeDateRateHelper::setTermStructure(t);\n}\n\nReal CrossCcyBasisMtMResetSwapHelper::impliedQuote() const {\n    QL_REQUIRE(termStructure_, \"Term structure needs to be set\");\n    swap_->recalculate();\n    if (spreadOnForeignCcy_)\n        return swap_->fairForeignSpread();\n    else\n        return swap_->fairDomesticSpread();\n}\n\nvoid CrossCcyBasisMtMResetSwapHelper::accept(AcyclicVisitor& v) {\n    Visitor<CrossCcyBasisMtMResetSwapHelper>* v1 = dynamic_cast<Visitor<CrossCcyBasisMtMResetSwapHelper>*>(&v);\n    if (v1)\n        v1->visit(*this);\n    else\n        RateHelper::accept(v);\n}\n} // namespace QuantExt\n", "meta": {"hexsha": "86ce997c0dbee977af59b360a37983a6bd2179ee", "size": 11417, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/termstructures/crossccybasismtmresetswaphelper.cpp", "max_stars_repo_name": "nvolfango/Engine", "max_stars_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T17:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T17:24:17.000Z", "max_issues_repo_path": "QuantExt/qle/termstructures/crossccybasismtmresetswaphelper.cpp", "max_issues_repo_name": "zhangjiayin/Engine", "max_issues_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantExt/qle/termstructures/crossccybasismtmresetswaphelper.cpp", "max_forks_repo_name": "zhangjiayin/Engine", "max_forks_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6, "max_line_length": 119, "alphanum_fraction": 0.6884470526, "num_tokens": 2651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2211263468947532}}
{"text": "/** \\file itasc/kdl/inertia.cpp\n *  \\ingroup itasc\n */\n// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n\n// Version: 1.0\n// Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be>\n// URL: http://www.orocos.org/kdl\n\n// This library is free software; you can redistribute it and/or\n// modify it under the terms of the GNU Lesser General Public\n// License as published by the Free Software Foundation; either\n// version 2.1 of the License, or (at your option) any later version.\n\n// This library is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// Lesser General Public License for more details.\n\n// You should have received a copy of the GNU Lesser General Public\n// License along with this library; if not, write to the Free Software\n// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n#include \"inertia.hpp\"\n\n#include <Eigen/Core>\n\nnamespace KDL {\nusing namespace Eigen;\n\nInertia::Inertia(double m,double Ixx,double Iyy,double Izz,double Ixy,double Ixz,double Iyz):\ndata(Matrix<double,6,6>::Zero())\n{\n    data(0,0)=Ixx;\n    data(1,1)=Iyy;\n    data(2,2)=Izz;\n    data(2,1)=data(1,2)=Ixy;\n    data(3,1)=data(1,3)=Ixz;\n    data(3,2)=data(2,3)=Iyz;\n\n\tdata.block(3,3,3,3)=m*Matrix<double,3,3>::Identity();\n}\n\nInertia::~Inertia()\n{\n}\n\n\n\n}\n", "meta": {"hexsha": "783bb04db70f02b147369b7983804a8a85bb41de", "size": 1514, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "intern/itasc/kdl/inertia.cpp", "max_stars_repo_name": "1-MillionParanoidTterabytes/Blender-2.79b-blackened", "max_stars_repo_head_hexsha": "e8d767324e69015aa66850d13bee7db1dc7d084b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-06-18T01:50:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-18T01:50:32.000Z", "max_issues_repo_path": "intern/itasc/kdl/inertia.cpp", "max_issues_repo_name": "1-MillionParanoidTterabytes/Blender-2.79b-blackened", "max_issues_repo_head_hexsha": "e8d767324e69015aa66850d13bee7db1dc7d084b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intern/itasc/kdl/inertia.cpp", "max_forks_repo_name": "1-MillionParanoidTterabytes/Blender-2.79b-blackened", "max_forks_repo_head_hexsha": "e8d767324e69015aa66850d13bee7db1dc7d084b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1153846154, "max_line_length": 93, "alphanum_fraction": 0.7073976222, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.3775406547908328, "lm_q1q2_score": 0.22089947287675993}}
{"text": "// ************************\n// ************************\n// Edited by CCJ:\n// evaldisp_lib.cpp, \n// which can be called\n// by python code;\n// ************************\n// ************************\n\n// evaluate disparity map\n// simple version for SDK\n// supports upsampling of disp map if GT has higher resolution\n\n// DS 7/2/2014\n// 10/14/2014 changed computation of average error\n// 1/27/2015 added clipping of valid (non-INF) disparities to [0 .. maxdisp]\n//    in fairness to those methods that do not utilize the given disparity range\n//    (maxdisp is specified at disp resolution, NOT GT resolution)\n\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n\n#include <stdio.h>\n#include <iostream>\n#include <stdlib.h>\n#include <math.h>\n#include <vector>\n#include \"imageLib/imageLib.h\"\n#include <stdint.h> /*for int32_t*/\n\n//added by CCJ for Python + CPP coding;\n#include <boost/python.hpp>\n#include \"boost/python/extract.hpp\"\n//#include \"boost/python/numeric.hpp\"\n/* Updated by CCJ for Boost version 1.65:\n * Boost 1.65 removes boost/python/numeric.hpp \n */\n// BOOST_LIB_VERSION and BOOST_VERSION are defined in this header file;\n#include <boost/version.hpp> \n#if BOOST_VERSION >= 106300 // >= 1.63.0\n   #include \"boost/python/numpy.hpp\"\n   namespace np = boost::python::numpy;\n#else\n   #include \"boost/python/numeric.hpp\"\n\t namespace np = boost::python::numeric;\n#endif\n\n#include <numpy/ndarrayobject.h>\nusing namespace boost::python;\n\n// see Fastest way to check if a file exist using standard C++/C++11/C?\n// at https://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c;\n#include <sys/stat.h>\ninline bool exists_file_test(const std::string & name){\n\tstruct stat buffer;\n\treturn (stat (name.c_str(), &buffer) == 0);\n}\n\n\n\nconst int verbose = 0;\n\n/* The `occlusion mask` for the left image is given as a file \"mask0nocc.png\":\n * - Pixels without ground truth have the color (0, 0, 0).                                                \n * - Pixels which are only observed by the left image have the color (128, 128, 128).\n * - Pixels which are observed by both images have the color (255, 255, 255).       \n * - For the \"non-occluded\" evaluation, the evaluation is limited to the pixels observed by both images.\t\t\n*/\n\n\nvoid evaldisp(\n\t\tCFloatImage disp, \n\t\tCFloatImage gtdisp, \n\t\tCByteImage mask, \n\t\tfloat badthresh, \n\t\tint maxdisp, \n\t\tint rounddisp,\n\t\tfloat * statistics\n\t\t){\n\n    CShape sh = gtdisp.Shape();\n    CShape sh2 = disp.Shape();\n    CShape msh = mask.Shape();\n\n    int width = sh.width, height = sh.height;\n    int width2 = sh2.width, height2 = sh2.height;\n    int scale = width / width2;\n\t\t//std::cout << \"scale = \" << scale << \"\\n\";\n\n    if ((!(scale == 1 || scale == 2 || scale == 4)) \n\t\t\t\t|| (scale * width2 != width)\n\t\t\t\t|| (scale * height2 != height)){\n\t\t\tprintf(\"   disp size = %4d x %4d\\n\", width2, height2);\n\t\t\tprintf(\"GT disp size = %4d x %4d\\n\", width,  height);\n\t\t\tthrow CError(\"GT disp size must be exactly 1, 2, or 4 * disp size\");\n    }\n\n    int usemask = (msh.width > 0 && msh.height > 0);\n    if (!usemask)\n\t\t\tthrow CError(\"No mask image's been read yet!\\n\");\n    if (usemask && (msh != sh))\n\t\t\tthrow CError(\"mask image must have same size as GT!\\n\");\n\n\t\t// all region;\n    int n_all = 0;\n    int bad_all = 0;\n    int invalid_all = 0;\n    float err_all = 0;\n\t\t// non-occluded region;\n    int invalid_noc = 0;\n\t\tint n_noc = 0;\n    int bad_noc = 0;\n    float err_noc = 0;\n\t\t// updated for mae and rmse error metric, on 2019/08/31\n    float err2_all = 0; // square \n    float err2_noc = 0;\n\t\t\n\n    for (int y = 0; y < height; y++) {\n\t\t\tfor (int x = 0; x < width; x++) {\n\t\t\t\tfloat gt = gtdisp.Pixel(x, y, 0);\n\t\t\t\tif (gt == INFINITY) // unknown\n\t\t\t\t\tcontinue;\n\t\t\t\tfloat d = scale * disp.Pixel(x / scale, y / scale, 0);\n\t      int valid = (d != INFINITY);\n\t\t\t\tif (valid) {\n\t\t\t\t\tfloat maxd = scale * maxdisp; // max disp range\n\t\t      d = __max(0, __min(maxd, d)); // clip disps to max disp range\n\t\t\t\t}\n\t      if (valid && rounddisp){\n\t\t\t\t\td = round(d);\n\t\t\t\t} \n\t\t\t\tfloat err = fabs(d - gt);\n        \n\t      if (mask.Pixel(x,y,0) == 0){ // no ground truth;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (mask.Pixel(x, y, 0) == 255){ // non-occluded region;\n\t\t\t\t\tn_noc++;\n\t\t\t\t\tif (valid) {\n\t\t\t\t\t\terr_noc += err;\n\t\t\t\t\t\terr2_noc += err*err;\n\n\t\t\t\t\t\tif (err > badthresh) {\n\t\t\t\t\t\t\tbad_noc++;\n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\t\t\t\t\telse {// invalid (i.e. hole in sparse disp map)\n\t\t\t\t\t\tinvalid_noc++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tn_all++;\n\t\t\t\tif(valid){\n\t\t\t\t\terr_all += err;\n\t\t\t\t\terr2_all += err * err;\n\n\t\t\t\t\tif (err > badthresh){\n\t\t\t\t\t\tbad_all++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {// invalid (i.e. hole in sparse disp map)\n\t\t\t\t\tinvalid_all++;\n\t\t\t\t} \n\t\t\t}/*end of width x*/\n\t\t}/*end of height y*/\n    \n\t\tfloat badpercent_all =  (float)bad_all / (float)n_all;\n    float avgErr_all = err_all / (float)(n_all - invalid_all); // CHANGED 10/14/2014 -- was: serr / n\n\t\tfloat badpercent_noc = (float) bad_noc / (float) n_noc;\n\t\tfloat avgErr_noc = err_noc /(float)(n_noc - invalid_noc);\n\t\tfloat rmse_all = sqrt(err2_all /(float)(n_all - invalid_all));\n\t\tfloat rmse_noc = sqrt(err2_noc /(float)(n_noc - invalid_noc));\n#if 0\n    float invalidpercent_all =  (float)invalid_all/(float)n_all;\n    float totalbadpercent_all =  (float)(bad_all+invalid_all)/(float)n_all;\n\t\tprintf(\"n_all = %d, n_noc = %d\\n\", n_all, n_noc);\n    printf(\"%4.1f%(N-rate-all)  %6.2f%(bad-%2.1f-all)  %6.2f%(invalid-all)  %6.2f%(totalBad-all)  %6.2f(avgErr-all)\\n\",   \n\t\t\t\t100.0*n_all/(width * height), 100.0*badpercent_all, badthresh, 100.0*invalidpercent_all, \n\t\t\t\t100.0*totalbadpercent_all, avgErr_all);\n    float invalidpercent_noc =  (float)invalid_noc / (float)n_noc;\n    float totalbadpercent_noc =  (float)(bad_noc+invalid_noc)/ (float)n_noc;\n    printf(\"%4.1f%(N-rate-noc)  %6.2f%(bad-%2.1f-noc)  %6.2f%(invalid-noc)  %6.2f%(totalBad-noc)  %6.2f(avgErr-noc)\\n\",   \n\t\t\t\t100.0*n_noc/(width * height), 100.0*badpercent_noc, badthresh, 100.0*invalidpercent_noc, \n\t\t\t\t100.0*totalbadpercent_noc, avgErr_noc);\n#endif\n\n\t\tstatistics[0] = badpercent_all;\n\t\tstatistics[1] = avgErr_all;\n\n\t\tstatistics[2] = badpercent_noc;\n\t\tstatistics[3] = avgErr_noc;\n\t\t\n\t\tstatistics[4] = rmse_all;\n\t\tstatistics[5] = rmse_noc;\n}\n\n// C++ code\ntypedef std::vector<std::string> StringList;\nclass IMG_NAMES{\n\tprivate:\n\t\tStringList myvec;\n\tpublic:\n\t\t// constructor\n\t\tIMG_NAMES(){\n\t\t\tthis -> myvec = StringList(0);\n\t\t}\n\tvoid set_img_names(boost::python::list & ns){\n\t\tfor(int i = 0; i < len(ns); ++i){\n\t\t\tthis -> myvec.push_back(boost::python::extract<std::string>(ns[i]));\n\t\t}\n\t}\n\n\tvoid show_img_names(){\n\t\tstd:: cout << \"Images :\\n\";\n\t\tfor(auto i: this-> myvec){\n\t\t\tstd::cout << i << \", \";\n\t\t}\n\t\tstd:: cout << \"\\n\";\n\t}\n\n\tStringList get_img_names(){\n\t\treturn this -> myvec;\n\t}\n};\n\n\nPyObject * eval_disp_mbv3_1_img(\n\t\tconst string & dispname,                // your predicted disparity results dir;\n\t  const string & disp_gt_trainingF_dir, \t// ground truth disparity dir to trainingF;\n\t\tfloat badthresh,                        // e.g., == 1.0 for Half resolution;\n\t\tconst int &  ndisp,                      // max_disp in groud truth disparity;\n\t\tconst int & rounddisp,\n    const std::string & img_name           // 1 image to evaluate;\n\t\t){\n\n\t\tnpy_intp * dims = new npy_intp[1];\n\t\tdims[0] = 4;\n\t\tPyObject * errs_A = PyArray_SimpleNew(1, dims, NPY_FLOAT32);\n\t  //std::cout << \"new PyObject errs_A, img_N = \" << img_N << std::endl;\n\t\tfloat * err_result = static_cast<float*>(PyArray_DATA(reinterpret_cast<PyArrayObject*>(errs_A)));\n\t\t\n\t\t//std::string dispname = disp_dir + img_name + \"/\" + disp_name; //\"disp0.pfm\"\n\t\tstd::string gtdispname = disp_gt_trainingF_dir + img_name + \"/disp0GT.pfm\";\n\t\t// updated for middlebury additional data, due to the lack of mask0nocc.png file;\n\t\tstd::string maskname = disp_gt_trainingF_dir + img_name + \"/mask0nocc.png\";\n\t\tbool readMask = true;\n\t\tif (!exists_file_test(maskname)){\n\t\t\tstd::cout << \"No mask0noc.png exists!\\n\";\n\t\t\treadMask = false;\n\t\t}\n\t\t\n\t\t//std::cout << \"maxdisp = \" << ndisp << \", \"<< dispname << \", \" << gtdispname << \", \" << maskname << \"\\n\";\n\n\t\tCFloatImage disp, gtdisp, gtdisp1;\n\t\tReadImageVerb(disp, dispname.c_str(), verbose);\n\t\tReadImageVerb(gtdisp, gtdispname.c_str(), verbose);\n\t\tCByteImage mask;\n\t\tif (readMask){\n\t\t\t//std::cout << \"read mask0noc.png!\\n\";\n\t\t\tReadImageVerb(mask, maskname.c_str(), verbose);\n\t\t}\n\n\t\tfloat statistics[4]= {-1.0, -1.0, -1.0, -1.0 };\n\t\tevaldisp(disp, gtdisp, mask, badthresh, ndisp, rounddisp, statistics);\n\t\terr_result[0] =  statistics[0];\n\t\terr_result[1] =  statistics[1];\n\t\terr_result[2] =  statistics[2];\n\t\terr_result[3] =  statistics[3];\n\t\t\n\t\t// release the memory\n\t\tdisp.DeAllocate();\n\t\tgtdisp.DeAllocate();\n\t\tgtdisp1.DeAllocate();\n\t\tif (maskname.c_str())\n\t\t\tmask.DeAllocate();\n\t\t//exit(0);\n\t\treturn errs_A;\n}\n\nPyObject * eval_disp_mbv3(\n\t\tconst string & disp_dir, // your prediction disparity results dir;\n\t  const string & disp_gt_trainingF_dir, \t// ground truth disparity dir to trainingF;\n\t\tfloat badthresh, // e.g., == 1.0 for Half resolution;\n\t\tconst string & disp_name, // e.g., == \"_disp0\" or \"_disp0_post\", or \"_rf_disp0PKLS\", and so on;\n\t\tPyObject * ndisps, // max_disp for each groud truth disparity \n\t\tPyObject * rounddisps, // disparity is int or float, specified in calib.txt files;\n    boost::python::list img_names // img_names to evaluate;\n\t\t){\n\n\t\t/*vector<std::string> mb_v3_imgs_1 = {\n\t\t\t\"Adirondack\",\n\t\t\t\"ArtL\", \n\t\t\t\"Jadeplant\", \n\t\t\t\"Motorcycle\",\n\t\t\t\"MotorcycleE\", \n\t\t\t\"Piano\", \n\t\t\t\"PianoL\", \n\t\t\t\"Pipes\", \n\t\t\t\"Playroom\", \n\t\t\t\"Playtable\", \n\t\t \t\"PlaytableP\", \n\t\t\t\"Recycle\", \n\t\t\t\"Shelves\",\n\t\t\t\"Teddy\", \n\t\t\t\"Vintage\", \n\t\t};\n\t\t*/\n    IMG_NAMES mb_v3; \n\t\tmb_v3.set_img_names(img_names);\n\t\t//mb_v3.show_img_names();\n\t\tvector<std::string> mb_v3_imgs = mb_v3.get_img_names();\n\n    PyArrayObject* ndispsA = reinterpret_cast<PyArrayObject*>(ndisps);\n    PyArrayObject* rounddispsA = reinterpret_cast<PyArrayObject*>(rounddisps);\n\t\t//int32_t * p_ndisps = reinterpret_cast<int32_t*>(PyArray_DATA(ndispsA));\n\t\tint * p_ndisps = reinterpret_cast<int*>(PyArray_DATA(ndispsA));\n\t\tint * p_rounddisps = reinterpret_cast<int*>(PyArray_DATA(rounddispsA));\n\n\t\tconst int img_N = mb_v3_imgs.size();\n\t\tnpy_intp * dims = new npy_intp[1];\n\t\tdims[0] = (4+2)*img_N;\n\t\tPyObject * errs_A = PyArray_SimpleNew(1, dims, NPY_FLOAT32);\n\t  //std::cout << \"new PyObject errs_A, img_N = \" << img_N << std::endl;\n\t\tfloat * err_result = static_cast<float*>(PyArray_DATA(reinterpret_cast<PyArrayObject*>(errs_A)));\n\t\tfor (int i = 0; i < img_N; i++){\n\t\t\tstd::string dispname = disp_dir + mb_v3_imgs[i] + \"/\" + disp_name + \".pfm\";\n\t\t\t// check if a file exists or not;\n\t\t\t// > see: https://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c;\n\t\t  if (!exists_file_test(dispname)){\n\t\t\t\t//std::cout << \"Not exist : \" << dispname << \", changed it to : \";\n\t\t\t\t\n\t\t\t\t//dispname = disp_dir + mb_v3_imgs[i] + \"_\" + disp_name;\n\t\t\t\t//Updated: delete \"_\" here;\n\t\t\t\tdispname = disp_dir + mb_v3_imgs[i] + disp_name + \".pfm\";\n\t\t\t\t//std::cout << dispname << \" \";\n\t\t\t\tif (!exists_file_test(dispname)){\n\t\t\t\t\tstd::cout << \"loading \" << dispname << \" ... but failed!\\n\"; \n\t\t\t\t}\n\t\t\t}\n      \n\t\t\tstd::string gtdispname = disp_gt_trainingF_dir + mb_v3_imgs[i] + \"/disp0GT.pfm\";\n\t\t\tstd::string maskname = disp_gt_trainingF_dir + mb_v3_imgs[i] + \"/mask0nocc.png\";\n\t\t\tbool readMask = true;\n\t\t\t// updated for middlebury additional data, due to the lack of mask0nocc.png file;\n\t\t\tif (!exists_file_test(maskname)){\n\t\t\t  std::cout << \"No mask0noc.png exists!\\n\";\n\t\t\t\treadMask = false;\n\t\t\t}\n\t    int maxdisp = p_ndisps[i];\n\t    int rounddisp = p_rounddisps[i];\n      //std::cout << \"maxdisp = \" << maxdisp << \", rounddisp = \" << rounddisp << \", \"<< dispname << \", \" << gtdispname << \", \" << maskname << \"\\n\";\n\n\t    CFloatImage disp, gtdisp, gtdisp1;\n\t    ReadImageVerb(disp, dispname.c_str(), verbose);\n\t    ReadImageVerb(gtdisp, gtdispname.c_str(), verbose);\n\t    CByteImage mask;\n\t    if (readMask){\n\t\t\t\t//std::cout << \"read mask0noc.png!\\n\";\n\t\t\t\tReadImageVerb(mask, maskname.c_str(), verbose);\n\t\t\t}\n\t    \n      //float statistics[4]= {-1.0, -1.0, -1.0, -1.0 };\n\t\t\t// updated for rmse metric on 2019/08/31;\n\t    float statistics[4 + 2]= {-1.0, -1.0, -1.0, -1.0, -1.0, -1.0 };\n\t\t\tevaldisp(disp, gtdisp, mask, badthresh, maxdisp, rounddisp, statistics);\n#if 0\n\t\t\tprintf(\"Processing: %10s, %6.2f%(bad-%2.1f-all), %6.2f(avgErr-all), %6.2f%(bad-%2.1f-noc), %6.2f(avgErr-nov)\\n\", \n\t\t\t\t\tmb_v3_imgs[i].c_str(), statistics[0]*100.0, badthresh, \n\t\t\t\t\tstatistics[1], statistics[2]*100.0, badthresh, statistics[3]);\n#endif\n\t\t\terr_result[6*i]     =  statistics[0];\n\t\t\terr_result[6*i + 1] =  statistics[1];\n\t\t\terr_result[6*i + 2] =  statistics[2];\n\t\t\terr_result[6*i + 3] =  statistics[3];\n\t\t\terr_result[6*i + 4] =  statistics[4];\n\t\t\terr_result[6*i + 5] =  statistics[5];\n      \n\t\t\t// release the memory\n\t\t\tdisp.DeAllocate();\n\t\t\tgtdisp.DeAllocate();\n\t\t\tgtdisp1.DeAllocate();\n\t    if (maskname.c_str())\n\t\t\t\tmask.DeAllocate();\n\n\t\t\t//exit(0);\n\t\t\n\t\t}/*end of each image*/\n\t\treturn errs_A;\n}\n\nBOOST_PYTHON_MODULE(libevaldisp_mbv3){\n\t/* for Boost <= version 1.63*/\n\t//numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n  /* for Boost > version 1.63*/\n\t//np::initialize();\n#if BOOST_VERSION >= 106300 // >= 1.63.0\n\tnp::initialize();\n#else\n\tnp::array::set_module_and_type(\"numpy\", \"ndarray\");\n#endif\n\tdef(\"evaluate_mbv3\", eval_disp_mbv3);\n\tdef(\"evaluate_mbv3_1_img\", eval_disp_mbv3_1_img);\n\t/* Error: return-statement with a value, in function returning 'void' [-fpermissive]\n\t *        #define NUMPY_IMPORT_ARRAY_RETVAL NULL\n\t * > See solution: https://github.com/numpy/numpy/issues/10486\n\t * > 1) Solution1: Okay, so the issue occurs only on py2 + py3c (the initialization function is nonstandard, and has py3 semantics). Solution appears to be to use `import_array1()`;\n\t * > 2) Solution2: Or call _import_array(), which allows you more control than just `return`;\n\t */ \n  //import_array(); // work well for Python2.7;\n\timport_array1(); // work well for python3.7;\n\t//_import_array(); // work well for python3.7;\n}\n", "meta": {"hexsha": "a62d1ea6b1ece46724a487973c0a73a07c269665", "size": 14027, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/MiddEval3/code/evaldisp_lib.cpp", "max_stars_repo_name": "ccj5351/DAFStereoNets", "max_stars_repo_head_hexsha": "66b720a4abbac9097a794eacef034bab641771d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2020-10-16T02:21:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T10:49:47.000Z", "max_issues_repo_path": "src/cpp/MiddEval3/code/evaldisp_lib.cpp", "max_issues_repo_name": "ccj5351/DAFStereoNets", "max_issues_repo_head_hexsha": "66b720a4abbac9097a794eacef034bab641771d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/MiddEval3/code/evaldisp_lib.cpp", "max_forks_repo_name": "ccj5351/DAFStereoNets", "max_forks_repo_head_hexsha": "66b720a4abbac9097a794eacef034bab641771d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-10-21T06:29:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T05:02:42.000Z", "avg_line_length": 33.8, "max_line_length": 182, "alphanum_fraction": 0.629927996, "num_tokens": 4442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22062196280627974}}
{"text": "/*\n  Copyright (c) 2012,2013,2014 Matthew H. Reilly (kb1vc)\n  All rights reserved.\n\n  Redistribution and use in source and binary forms, with or without\n  modification, are permitted provided that the following conditions are\n  met:\n\n  Redistributions of source code must retain the above copyright\n  notice, this list of conditions and the following disclaimer.\n  Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions and the following disclaimer in\n  the documentation and/or other materials provided with the\n  distribution.\n\n  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include \"ReSampler.hxx\"\n#include <string.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <boost/format.hpp>\n\nstatic void bindump(char * fn, std::complex<float> * buf, unsigned int num_elts, int append = 0) __attribute__ ((unused));\nstatic void bindump(char * fn, std::complex<float> * buf, unsigned int num_elts, int append)\n{\n  FILE * of;\n  if(append != 0) {\n    of = fopen(fn, \"a\");\n  }\n  else {\n    of = fopen(fn, \"w\");\n  }\n  unsigned int i;\n  for(i = 0; i < num_elts; i++) {\n    fprintf(of, \"%d %g %g\\n\", i + (append * num_elts), buf[i].real(), buf[i].imag()); \n  }\n  fclose(of); \n}\n\nstatic void bindump_2(char * fn, std::complex<float> * buf, unsigned int num_elts, unsigned int num_cols) __attribute__ ((unused));\nstatic void bindump_2(char * fn, std::complex<float> * buf, unsigned int num_elts, unsigned int num_cols)\n{\n  FILE * of;\n  of = fopen(fn, \"w\");\n  unsigned int i, j;\n  for(i = 0; i < num_elts; i++) {\n    fprintf(of, \"%d \", i);\n    for(j = 0; j < num_cols; j++) {\n      fprintf(of, \"%g %g \", buf[i * num_cols + j].real(), buf[i * num_cols + j].imag());\n    }\n    fprintf(of, \"\\n\");\n  }\n  fclose(of); \n}\n\nstatic unsigned int ipow(unsigned int a, unsigned int b)\n{\n  unsigned int ret = 1;\n  unsigned int i ;\n\n  for(i = 0; i < b; i++) {\n    ret *= a; \n  }\n\n  return ret; \n}\n\nSoDa::ReSampler::ReSampler(unsigned int interpolate_ratio,\n\t\t\t   unsigned int decimate_ratio,\n\t\t\t   unsigned int _inlen, \n\t\t\t   unsigned int _filter_len)\n{\n  // save the parameters\n  inlen = _inlen;\n  iM = interpolate_ratio;\n  dN = decimate_ratio;\n  filter_len = _filter_len; \n  Q = filter_len;\n  M = _inlen;\n\n\n  // give preferences to convenient powers of two.\n  // but let's search for the nearest solution that is\n  // a multiple of 2^a * 3^b * 5^c where b and c are in the range 0..3\n  // and a is in the range 1..16\n  unsigned int N_guess, N_best, E_best;\n  N_best = 2; \n  E_best = 0x80000000;\n  unsigned int i; \n  for(i = 1; i <= 0xff; i++) {\n    unsigned int a = i & 0xf;\n    unsigned int b = (i >> 4) & 0x3;\n    unsigned int c = (i >> 6) & 0x3; \n    N_guess = ipow(2, a) * ipow(3, b) * ipow(5, c);\n    if(N_guess >= (M + Q - 1)) {\n      unsigned slop = N_guess - (M + Q - 1);\n      if(slop < E_best) {\n\tN_best = N_guess;\n\tE_best = slop; \n      }\n    }\n  }\n  N = N_best; \n\n  \n  // now that we have N, we can back-calculate Q.\n  Q = N - M;\n\n  filter_len = Q; \n  \n  tail_index = M - (Q - 1);\n  \n  // create the buffers.\n  // a copy of the input sequence\n  inbuf = (std::complex<float> *) fftwf_alloc_complex(N);\n  // the transformed input\n  in_fft = (std::complex<float> *) fftwf_alloc_complex(N);\n\n  // zero out the whole of the input buffer\n  for(i = 0; i < N; i++) inbuf[i] = std::complex<float>(0.0,0.0);\n  \n  // the filter bank is really iM interleaved filters\n  // but we can't seem to make that work right now, so we're\n  // backing off to a simpler way. \n  c_filt = new std::complex<float>*[iM];\n  for(i = 0; i < iM; i++) {\n    c_filt[i] = (std::complex<float> *) fftwf_alloc_complex(N);\n  }\n\n  // the upsampled result\n  filt_fft = (std::complex<float> *) fftwf_alloc_complex(iM*N);\n  // the inverse transform of the upsampled result\n  interp_res = (std::complex<float> *) fftwf_alloc_complex(iM*N);\n\n  // the first plan is pretty simple. \n  in_fft_plan = fftwf_plan_dft_1d(N,\n\t\t\t\t  (fftwf_complex *) inbuf,\n\t\t\t\t  (fftwf_complex *) in_fft,\n\t\t\t\t  FFTW_FORWARD, FFTW_ESTIMATE);\n\n\n  // now create the inverting plans\n  int n[1];\n  n[0] = N; \n  mid_ifft_plan = fftwf_plan_many_dft(1, n, iM, \n\t\t\t\t      (fftwf_complex *) filt_fft, NULL, iM, 1,\n\t\t\t\t      (fftwf_complex *) interp_res, NULL, iM, 1,\n\t\t\t\t      FFTW_BACKWARD, FFTW_ESTIMATE);\n  \n\n  // now create the polyphase filter banks.\n  CreateFilter(filter_len);\n\n  transform_gain = 1.0 / ((float) N); \n}\n\nvoid SoDa::ReSampler::CreateFilter(unsigned int filter_len)\n{\n  // filter_len must be odd\n  int fN = filter_len;\n  if((fN & 1) == 0) fN--; \n  \n  unsigned int i, j, k;\n\n  // Use the plan of fischer in \"The mkfilter Digital Filter Generation Program\" mkshape...\n  // This is borrowed quite heavily and with tremendous gratitude from \n  // http://www-users.cs.york.ac.uk/~fisher   Thanks, Prof. Fisher...\n  float alpha, beta;\n  float cutdown = ((float) ((iM > dN) ? iM : dN));\n  beta = 1.0 / (2.2 * cutdown); // This is the transition freq -- a little shy of 0.5/cutdown\n  alpha = 0.1; // this is a shape factor\n\n  // create a frequency domain image of the filter.\n  float f1 = (1.0 - alpha) * beta;\n  float f2 = (1.0 + alpha) * beta;\n  float tau = 0.5 / alpha; \n\n  // now create the filter banks.\n  std::complex<float> * filt_FD = (std::complex<float>*) fftwf_alloc_complex(N); \n  std::complex<float> * filt_td = (std::complex<float>*) fftwf_alloc_complex(N); \n  std::complex<float> * filt_td2 = (std::complex<float>*) fftwf_alloc_complex(N); \n\n  float f;\n  float f_incr = 1.0 / ((float) (N));\n  unsigned int hlim = (N);\n  float gain_corr = 1.0 / ((float) hlim);\n  //  gain_corr = gain_corr * gain_corr; \n  for(i = 0, f = 0.0; i <= hlim / 2; i++, f += f_incr) {\n    if(f <= f1) {\n      filt_FD[i] = std::complex<float>(1.0, 0.0);\n    }\n    else if (f <= f2) {\n      float h = 0.5 * (1.0 + cos(M_PI * tau * (f - f1) / beta));\n      filt_FD[i] = std::complex<float>(h, 0.0);      \n    }\n    else {\n      filt_FD[i] = std::complex<float>(0.0, 0.0);            \n    }\n\n    filt_FD[i] *= tau * gain_corr;\n\n    if(i != 0) filt_FD[hlim - i] = filt_FD[i]; \n  }\n\n  // then ifft it to time domain\n  fftwf_plan filt_ifft_plan = fftwf_plan_dft_1d(hlim,\n\t\t\t\t\t\t(fftwf_complex *) filt_FD,\n\t\t\t\t\t\t(fftwf_complex *) filt_td,\n\t\t\t\t\t\tFFTW_BACKWARD, FFTW_ESTIMATE);\n  fftwf_execute(filt_ifft_plan);\n\n  float sum = 0.0;\n  for(i = 0; i < hlim; i++) sum += filt_td[i].real();\n\n  float sgain = 1.0 / sum; \n  for(i = 0; i < hlim; i++) filt_td[i] *= sgain; \n  \n  fftwf_destroy_plan(filt_ifft_plan); \n\n  // now truncate the filter\n  // We've got an image that is symmetric around 0.\n  for(i = 0; i < N; i++) {\n    filt_td2[i] = std::complex<float>(0.0,0.0);\n  }\n\n  // shift it up to be symmetric around filt_len / 2\n  for(i = 0, j = N - (filter_len/2); j < N; i++, j++) {\n    filt_td2[i] = filt_td[j]; \n  }\n  for(j = 0; j < filter_len / 2; j++, i++) {\n    filt_td2[i] = filt_td[j];     \n  }\n\n  //  bindump(\"filt_td2.dat\", filt_td2, N);\n  \n  // and fft back to frequency domain for each of the iM filters.\n  for(i = 0; i < iM; i++) {\n    // grab the slice of the filter that we need to transform.\n\n    for(j = i, k = 0; j < filter_len; k++, j += iM) {\n      filt_td[k] = filt_td2[j]; \n    }\n    for(; k < N; k++) filt_td[k] = std::complex<float>(0.0,0.0);\n    fftwf_plan filt_fft_plan = fftwf_plan_dft_1d(N,\n\t\t\t\t\t\t (fftwf_complex *) filt_td,\n\t\t\t\t\t\t (fftwf_complex *) c_filt[i],\n\t\t\t\t\t\t FFTW_FORWARD, FFTW_ESTIMATE);\n    fftwf_execute(filt_fft_plan);\n    fftwf_destroy_plan(filt_fft_plan); \n  }\n\n  // now free up buffers\n  fftwf_free(filt_td2);\n  fftwf_free(filt_td);\n  fftwf_free(filt_FD);  \n}\n\nunsigned int SoDa::ReSampler::apply(std::complex<float> * in,\n\t\t\t\t    std::complex<float> * out,\n\t\t\t\t    float gain)\n{\n  unsigned int i, j;\n  // copy the input buffer\n  memcpy(&(inbuf[Q-1]), in, sizeof(std::complex<float>) * M);\n  \n  // transform the input\n  fftwf_execute(in_fft_plan); // , (fftwf_complex *) in, (fftwf_complex *) in_fft);\n\n  // now multiply by the M filters\n  for(i = 0; i < N; i++) {\n    for(j = 0; j < iM; j++) {\n      filt_fft[j + i*iM] = in_fft[i] * c_filt[j][i]; \n    }\n  }\n  // do M inverse transforms on the filter result ...\n  // to produce M interleaved time domain vectors.\n  fftwf_execute(mid_ifft_plan);\n\t \n  // save the last bits of the input buffer to the Q-1 side of the FFT input vector\n  // Do this now incase inbuf and outbuf are the same buffers.  (we may\n  // over-write the outbuf with the downsample at the bottom.... )\n  memcpy(inbuf, &(in[tail_index]), sizeof(std::complex<float>) * (Q-1));\n\n  // now build the output buffer. \n\n  // now downsample by a factor of dN.\n  int idx = 0; \n  unsigned int mctr = 0;\n  unsigned int out_lim = (M * iM) / dN;\n  std::complex<float> * ir_clean = &(interp_res[(Q-1)]); \n  // std::cerr << \" iM, dN, M, N, out_lim = \"\n  // \t    << iM << \" \" << dN << \" \" << M << \" \" << N << \" \" << out_lim << std::endl; \n  for(j = 0; j < out_lim; j++) {\n    out[j] = ir_clean[mctr + idx * iM] * gain * transform_gain * ((float) iM);\n    mctr += dN;\n    while(mctr >= iM) {\n      mctr -= iM;\n      idx += 1; \n    }\n  }\n  //  bindump(\"out.dat\", out, j); \n\n  return 0; \n}\n\n\n\nunsigned int SoDa::ReSampler::apply(float * in,\n\t\t\t\t    float * out,\n\t\t\t\t    float gain)\n{\n  unsigned int i, j;\n  \n  for(i = 0; i < M; i++) {\n    inbuf[i+(Q-1)] = std::complex<float>(in[i], 0.0);\n  }\n\n  // transform the input\n  fftwf_execute(in_fft_plan); // , (fftwf_complex *) in, (fftwf_complex *) in_fft);\n  \n  // now multiply by the M filters\n  for(i = 0; i < N; i++) {\n    for(j = 0; j < iM; j++) {\n      filt_fft[j + i*iM] = in_fft[i] * c_filt[j][i]; \n    }\n  }\n  // do M inverse transforms on the filter result ...\n  // to produce M interleaved time domain vectors.\n  fftwf_execute(mid_ifft_plan);\n\t \n  // save the last bits of the input buffer to the Q-1 side of the FFT input vector\n  // Do this now incase inbuf and outbuf are the same buffers.  (we may\n  // over-write the outbuf with the downsample at the bottom.... )\n  for(i = 0; i < (Q-1); i++) {\n    inbuf[i] = std::complex<float>(in[i + tail_index], 0.0);\n  }\n\n  // now build the output buffer. \n\n  // now downsample by a factor of dN.\n  int idx = 0; \n  unsigned int mctr = 0;\n  unsigned int out_lim = (M * iM) / dN;\n  std::complex<float> * ir_clean = &(interp_res[(Q-1)]); \n  for(j = 0; j < out_lim; j++) {\n    out[j] = ir_clean[mctr + idx * iM].real() * gain * transform_gain * ((float) iM);\n    mctr += dN;\n    while(mctr >= iM) {\n      mctr -= iM;\n      idx += 1; \n    }\n  }\n\n  return 0; \n}\n", "meta": {"hexsha": "5b1365dab3d166928f02f5d69e863a6e11c204d8", "size": 11211, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/ReSampler.cxx", "max_stars_repo_name": "kb1vc/SoDaRadio", "max_stars_repo_head_hexsha": "0a41fa3d795b1c93795ad62ad17bf2de5f60a752", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2017-10-27T16:01:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T08:12:42.000Z", "max_issues_repo_path": "src/ReSampler.cxx", "max_issues_repo_name": "dd0vs/SoDaRadio", "max_issues_repo_head_hexsha": "0a41fa3d795b1c93795ad62ad17bf2de5f60a752", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-09-16T03:13:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-11T09:11:35.000Z", "max_forks_repo_path": "src/ReSampler.cxx", "max_forks_repo_name": "dd0vs/SoDaRadio", "max_forks_repo_head_hexsha": "0a41fa3d795b1c93795ad62ad17bf2de5f60a752", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2017-09-13T12:47:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-02T20:54:25.000Z", "avg_line_length": 30.3, "max_line_length": 131, "alphanum_fraction": 0.6151993578, "num_tokens": 3578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22062196280627974}}
{"text": "// *****************************************************************************\n/*!\n  \\file      src/RNG/RNGSSE.hpp\n  \\copyright 2012-2015 J. Bakosi,\n             2016-2018 Los Alamos National Security, LLC.,\n             2019 Triad National Security, LLC.\n             All rights reserved. See the LICENSE file for details.\n  \\brief     Interface to RNGSSE random number generators\n  \\details   Interface to RNGSSE random number generators\n*/\n// *****************************************************************************\n#ifndef RNGSSE_h\n#define RNGSSE_h\n\n#include <cstring>\n#include <random>\n\n#include \"NoWarning/beta_distribution.hpp\"\n#include <boost/random/gamma_distribution.hpp>\n\n#include \"Make_unique.hpp\"\n#include \"Exception.hpp\"\n#include \"Macro.hpp\"\n#include \"Options/RNGSSESeqLen.hpp\"\n\nnamespace tk {\n\n//! RNGSSE-based random number generator used polymorphically with tk::RNG\ntemplate< class State, typename SeqNumType, unsigned int (*Generate)(State*) >\nclass RNGSSE {\n\n  private:\n    using InitFn = void (*)( State*, SeqNumType );\n    using ncomp_t = kw::ncomp::info::expect::type;    \n\n    //! Adaptor to use a std distribution with the RNGSSE generator\n    //! \\see C++ concepts: UniformRandomNumberGenerator\n    struct Adaptor {\n      using result_type = unsigned int;\n      Adaptor( const std::unique_ptr< State[] >& s, int t ) : str(s), tid(t) {}\n      static constexpr result_type min() { return 0u; }\n      static constexpr result_type max() { return 4294967295u; }\n      result_type operator()()\n      { return Generate( &str[ static_cast<std::size_t>(tid) ] ); }\n      const std::unique_ptr< State[] >& str;\n      int tid;\n    };\n\n  public:\n    //! Constructor\n    //! \\param[in] n Initialize RNG using this many independent streams\n    //! \\param[in] fnShort RNG initializer function for short streams\n    //! \\param[in] seqlen Sequence length enum: short, medium or long\n    //! \\param[in] fnLong RNG initializer function for long streams\n    //! \\param[in] fnMed RNG initializer function for medium streams\n    explicit RNGSSE( SeqNumType n,\n                     InitFn fnShort,\n                     ctr::RNGSSESeqLenType seqlen = ctr::RNGSSESeqLenType::SHORT,\n                     InitFn fnLong = nullptr,\n                     InitFn fnMed = nullptr) :\n       m_nthreads( n ),\n       m_init( seqlen == ctr::RNGSSESeqLenType::LONG ? fnLong :\n               seqlen == ctr::RNGSSESeqLenType::MEDIUM ? fnMed : fnShort ),\n       m_stream()\n    {\n      Assert( m_init != nullptr, \"nullptr passed to RNGSSE constructor\" );\n      Assert( n > 0, \"Need at least one thread\" );\n      // Allocate array of stream-pointers for threads\n      m_stream = tk::make_unique< State[] >( n );\n      // Initialize thread-streams\n      for (SeqNumType i=0; i<n; ++i) m_init( &m_stream[i], i );\n    }\n\n    //! Uniform RNG: Generate uniform random numbers\n    //! \\param[in] tid Thread (or more precisely) stream ID\n    //! \\param[in] num Number of RNGs to generate\n    //! \\param[in,out] r Pointer to memory to write the random numbers to\n    void uniform( int tid, ncomp_t num, double* r ) const {\n      for (ncomp_t i=0; i<num; ++i)\n        r[i] = static_cast<double>(\n                 Generate( &m_stream[ static_cast<std::size_t>(tid) ] ) )\n               / 4294967296.0;\n    }\n\n    //! Gaussian RNG: Generate Gaussian random numbers\n    //! \\param[in] tid Thread (or more precisely stream) ID\n    //! \\param[in] num Number of RNGs to generate\n    //! \\param[in,out] r Pointer to memory to write the random numbers to\n    //! \\details Generating Gaussian random numbers is implemented via an\n    //!   adaptor, modeling std::UniformRandomNumberGenerator, outsourcing the\n    //!   transformation of uniform random numbers to Gaussian ones, to the\n    //!   standard library. The adaptor is instantiated here because a standard\n    //!   distribution, such as e.g., std::normal_distribution, generates\n    //!   numbers using operator() with no arguments, thus the RNG state and the\n    //!   thread ID (this latter only known here) must be stored in the adaptor\n    //!   functor's state. Even though creating the adaptor seems like a\n    //!   potentially costly operation for every call, using the standard\n    //!   library implementation is still faster than a hand-coded\n    //!   implementation of the Box-Muller algorithm. Note that libc++ uses a\n    //!   cache, as Box-Muller, implemented using the polar algorithm generates\n    //!   2 Gaussian numbers for each pair of uniform ones, caching every 2nd.\n    void gaussian( int tid, ncomp_t num, double* r ) const {\n      Adaptor generator( m_stream, tid );\n      std::normal_distribution<> gauss_dist( 0.0, 1.0 );\n      for (ncomp_t i=0; i<num; ++i) r[i] = gauss_dist( generator );\n    }\n\n    //! \\brief Multi-variate Gaussian RNG: Generate multi-variate Gaussian\n    //!    random numbers\n    //! \\param[in] tid Thread (or more precisely stream) ID\n    //! \\param[in] num Number of RNGs to generate\n    //! \\param[in] d Dimension d ( d ≥ 1) of output random vectors\n    //! \\param[in] mean Mean vector of dimension d\n    //! \\param[in] cov Lower triangle of covariance matrix, stored as a vector\n    //!   of length d(d+1)/2\n    //! \\param[in,out] r Pointer to memory to write the random numbers to\n    //! \\warning Not implemented!\n    void gaussianmv( int tid, ncomp_t num, ncomp_t d, const double* const mean,\n                     const double* const cov, double* r ) const\n    {\n      IGNORE(tid);\n      IGNORE(num);\n      IGNORE(d);\n      IGNORE(mean);\n      IGNORE(cov);\n      IGNORE(r);\n    }\n\n    //! Beta RNG: Generate beta random numbers\n    //! \\param[in] tid Thread (or more precisely stream) ID\n    //! \\param[in] num Number of RNGs to generate\n    //! \\param[in] p First beta shape parameter\n    //! \\param[in] q Second beta shape parameter\n    //! \\param[in] a Beta displacement parameter\n    //! \\param[in] b Beta scale factor\n    //! \\param[in,out] r Pointer to memory to write the random numbers to\n    //! \\details Generating beta-distributed random numbers is implemented via\n    //!   an adaptor, modeling boost::UniformRandomNumberGenerator, outsourcing\n    //!   the transformation of uniform random numbers to beta-distributed ones,\n    //!   to boost::random. The adaptor is instantiated here because a boost\n    //!   random number distribution, such as e.g.,\n    //!   boost::random::beta_distribution, generates numbers using operator()\n    //!   with no arguments, thus the RNG state and the thread ID (this latter\n    //!   only known here) must be stored in the adaptor functor's state.\n    void beta( int tid, ncomp_t num, double p, double q, double a, double b,\n               double* r ) const {\n      Adaptor generator( m_stream, tid );\n      boost::random::beta_distribution<> beta_dist( p, q );\n      for (ncomp_t i=0; i<num; ++i) r[i] = beta_dist( generator ) * b + a;\n    }\n\n    //! Gamma RNG: Generate gamma random numbers\n    //! \\param[in] tid Thread (or more precisely stream) ID\n    //! \\param[in] num Number of RNGs to generate\n    //! \\param[in] a Gamma shape parameter\n    //! \\param[in] b Gamma scale factor\n    //! \\param[in,out] r Pointer to memory to write the random numbers to\n    //! \\details Generating gamma-distributed random numbers is implemented via\n    //!   an adaptor, modeling boost::UniformRandomNumberGenerator, outsourcing\n    //!   the transformation of uniform random numbers to gamma-distributed\n    //!   ones, to boost::random. The adaptor is instantiated here because a\n    //!   boost random number distribution, such as e.g.,\n    //!   boost::random::gamma_distribution, generates numbers using operator()\n    //!   with no arguments, thus the RNG state and the thread ID (this latter\n    //!   only known here) must be stored in the adaptor functor's state.\n    void gamma( int tid, ncomp_t num, double a, double b, double* r ) const {\n      Adaptor generator( m_stream, tid );\n      boost::random::gamma_distribution<> gamma_dist( a, b );\n      for (ncomp_t i=0; i<num; ++i) r[i] = gamma_dist( generator );\n    }\n\n    //! Copy assignment\n    RNGSSE& operator=( const RNGSSE& x ) {\n      m_nthreads = x.m_nthreads;\n      m_init = x.m_init;\n      m_stream = tk::make_unique< State[] >( x.m_nthreads );\n      for (SeqNumType i=0; i<x.m_nthreads; ++i) m_init( &m_stream[i], i );\n      return *this;\n    }\n\n    //! Copy constructor: in terms of copy assignment\n    RNGSSE( const RNGSSE& x ) { operator=(x); }\n\n    //! Move assignment\n    RNGSSE& operator=( RNGSSE&& x ) {\n      m_nthreads = x.m_nthreads;\n      m_init = x.m_init;\n      m_stream = tk::make_unique< State[] >( x.m_nthreads );\n      for (SeqNumType i=0; i<x.m_nthreads; ++i) {\n        m_stream[i] = x.m_stream[i];\n        std::memset( &x.m_stream[i], 0, sizeof(x.m_stream[i]) );\n      }\n      x.m_nthreads = 0;\n      x.m_init = nullptr;\n      x.m_stream.reset( nullptr );\n      return *this;\n    }\n\n    //! Move constructor: in terms of move assignment\n    RNGSSE( RNGSSE&& x ) :\n      m_nthreads( 0 ),\n      m_init( nullptr ),\n      m_stream( nullptr )\n    { *this = std::move( x ); }\n\n    //! Accessor to the number of threads we operate on\n    SeqNumType nthreads() const noexcept { return m_nthreads; }\n\n  private:\n    SeqNumType m_nthreads;                 //!< Number of threads\n    InitFn m_init;                         //!< Sequence length initializer\n    std::unique_ptr< State[] > m_stream;   //!< Random number stream for threads\n};\n\n} // tk::\n\n#endif // RNGSSE_h\n", "meta": {"hexsha": "8a87ba9a3b4a40948b97bd8e6d939f73e6ed875a", "size": 9482, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/RNG/RNGSSE.hpp", "max_stars_repo_name": "franjgonzalez/Quinoa", "max_stars_repo_head_hexsha": "411eb8815e92618c563881b784e287e2dd916f89", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RNG/RNGSSE.hpp", "max_issues_repo_name": "franjgonzalez/Quinoa", "max_issues_repo_head_hexsha": "411eb8815e92618c563881b784e287e2dd916f89", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RNG/RNGSSE.hpp", "max_forks_repo_name": "franjgonzalez/Quinoa", "max_forks_repo_head_hexsha": "411eb8815e92618c563881b784e287e2dd916f89", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.495412844, "max_line_length": 81, "alphanum_fraction": 0.6309850243, "num_tokens": 2371, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.22062196280627974}}
{"text": "////////////////////////////////////////////////////////////////////////////\r\n//! \\file    robot.cpp\r\n//! \\date    February 2018\r\n//! \\author  Eric Barnett\r\n//!          Marc-Antoine Lacasse\r\n//!\r\n//! Copyright (C) 2018 Eric Barnett         <e.barnett@robotiq.com>\r\n//! Copyright (C) 2018 Marc-Antoine Lacasse <malacasse@robotiq.com>\r\n//! Copyright (C) 2018 Clément Gosselin     <gosselin@gmc.ulaval.ca>\r\n//!\r\n//! \\brief Robot-specific kinematics and dynamics\r\n//!\r\n//! This file is part of BA, a bisection algorithm for time-optimal trajectory\r\n//! planning\r\n//!\r\n//! This Source Code Form is subject to the terms of the Berkeley Software\r\n//! Distribution (BSD) 3-clause license . If a copy of the BSD license was not\r\n//! distributed with this file, you can obtain one at\r\n//! https://opensource.org/licenses/BSD-3-Clause.\r\n////////////////////////////////////////////////////////////////////////////////\r\n\r\n////////////////////////////////////////////////////////////////////////////////\r\n// Includes\r\n////////////////////////////////////////////////////////////////////////////////\r\n#include \"util.h\"\r\n#include \"robot.h\"\r\n#include \"config.h\"\r\n#include <array>\r\n#include <Eigen/Core> // for linear Algebra in fwdKinKuka()\r\n#ifndef isWin\r\n   #include <limits>\r\n   #include \"string.h\"\r\n#endif\r\n\r\nusing namespace Eigen;\r\n\r\nnamespace BATOTP{\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief set_robotType\r\n//!\r\n//! Set the robot type (define new robots here)\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::call_set_robotType(const std::string& robotTypeStr)\r\n{\r\n    return set_robotType(robotTypeStr);\r\n}\r\n\r\nint Robot::set_robotType(const std::string &robotTypeStr)\r\n{\r\n   _robotType=0;\r\n   _robotTypeStr=robotTypeStr;\r\n   if(_robotTypeStr==\"KUKA\")     _robotType=KUKA;\r\n   if(_robotTypeStr==\"UR\")       _robotType=UR;\r\n   if(_robotTypeStr==\"RR\")       _robotType=RR;\r\n   if(_robotTypeStr==\"CSPR3DOF\") _robotType=CSPR3DOF;\r\n   if(_robotTypeStr==\"GENJNT\")   _robotType=GENJNT;\r\n\r\n   return(_robotType);\r\n}\r\n\r\n//! FORWARD KINEMATICS\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief fwdKin\r\n//!\r\n//! Forward displacement problem\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::call_fwdKin(const std::vector<std::vector<double> >& theta,\r\n                       std::vector<std::vector<double>> &cart)\r\n{return(fwdKin(theta,cart));}\r\nint Robot::fwdKin(const std::vector<std::vector<double>> &theta,\r\n                  std::vector<std::vector<double>> &cart)\r\n{\r\n\r\n   switch(_robotType)\r\n   {\r\n   case KUKA: //KUKA-LWR IV+\r\n      fwdKinKuka(theta,cart);\r\n      break;\r\n   case RR: // planar RR positioning manipulator\r\n      fwdKinRR(theta,cart);\r\n      break;\r\n   default:\r\n      printf (\"No forward Kinematics model provided for robotType=%s.\\n\",\r\n              _robotTypeStr.c_str());\r\n      return -1;\r\n      assert(!\"Unhandled case\"); // Always assert unhandled cases\r\n      break;\r\n   }\r\n   return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief fwdKinKuka\r\n//!\r\n//! Forward displacement problem for the Kuka LWR IV+\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::fwdKinKuka(const std::vector<std::vector<double> >& theta,\r\n                      std::vector<std::vector<double>> &cart)\r\n{\r\n   int i;\r\n   Matrix3d Q12,Q34,Q567,Q1234,Q;\r\n   //op=[0; 0; .282];  .204+78 Robotiq hand with Robotiq fingers (center of pads)\r\n   //op=[0; 0; .3145]; Robotiq hand with Robotiq fingers (tips of pads)\r\n   Vector3d ToolPointVector(0,-.08,.545); // .468+.078 Robotiq hand with long fingers\r\n\r\n   int nPts=(int)theta[0].size();\r\n\r\n   double a0=.3105,a1=.4,a2=.39; // link lengths\r\n\r\n   double t1,t2,t3,t4,t5,t6,t7;\r\n   double c1,c2,c3,c4,c5,c6,c7;\r\n   double s1,s2,s3,s4,s5,s6,s7;\r\n   double x1,y1,z1;\r\n   double x2,y2,z2;\r\n   double x3,y3,z3;\r\n\r\n   cart.resize(3);\r\n   for(i=0;i<3;i++) cart[i].resize(nPts);\r\n\r\n   for(i=0; i<nPts; i++)\r\n   {\r\n      t1=_DEG2RAD*theta[0][i]; c1=cos(t1); s1=sin(t1);\r\n      t2=_DEG2RAD*theta[1][i]; c2=cos(t2); s2=sin(t2);\r\n      t3=_DEG2RAD*theta[2][i]; c3=cos(t3); s3=sin(t3);\r\n      t4=_DEG2RAD*theta[3][i]; c4=cos(t4); s4=sin(t4);\r\n      t5=_DEG2RAD*theta[4][i]; c5=cos(t5); s5=sin(t5);\r\n      t6=_DEG2RAD*theta[5][i]; c6=cos(t6); s6=sin(t6);\r\n      t7=_DEG2RAD*theta[6][i]; c7=cos(t7); s7=sin(t7);\r\n\r\n      Q12 <<  c1*c2, -s1, -c1*s2,\r\n            c2*s1,  c1, -s1*s2,\r\n            s2,   0,     c2;\r\n\r\n      Q34 << c3*c4, -s3, c3*s4,\r\n            c4*s3,  c3, s3*s4,\r\n            -s4,   0,    c4;\r\n\r\n      Q567 << c5*c6*c7 - s5*s7, - c7*s5 - c5*c6*s7, -c5*s6,\r\n            c5*s7 + c6*c7*s5,   c5*c7 - c6*s5*s7, -s5*s6,\r\n            c7*s6,             -s6*s7,     c6;\r\n\r\n      Q1234=Q12*Q34; Q=Q1234*Q567;\r\n\r\n      // elbow\r\n      x1=a1*Q12(0,2);\r\n      y1=a1*Q12(1,2);\r\n      z1=a1*Q12(2,2)+a0;\r\n\r\n      // wrist\r\n      x2=x1+a2*Q1234(0,2);\r\n      y2=y1+a2*Q1234(1,2);\r\n      z2=z1+a2*Q1234(2,2);\r\n\r\n      // tool point\r\n      x3=x2+Q.row(0)*ToolPointVector;\r\n      y3=y2+Q.row(1)*ToolPointVector;\r\n      z3=z2+Q.row(2)*ToolPointVector;\r\n\r\n      // normal (tool-pointing direction)\r\n      //n << x3-x2, y3-y2, z3-z2 ;\r\n      //n=n.normalized();\r\n\r\n      cart[0][i]=x3;\r\n      cart[1][i]=y3;\r\n      cart[2][i]=z3;\r\n   }\r\n   return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief fwdKinRR\r\n//!\r\n//! Forward displacement problem for a RR planar robot\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::fwdKinRR(const std::vector<std::vector<double> >& theta,\r\n                    std::vector<std::vector<double>> &cart)\r\n{\r\n   int i,nPts=(int)theta[0].size();\r\n   double a1=.4,a2=.6;\r\n   double th1,th2;\r\n   cart.resize(3);\r\n   for(i=0;i<3;i++) cart[i].resize(nPts);\r\n\r\n   for(i=0;i<nPts;i++)\r\n   {\r\n      th1=_DEG2RAD*theta[0][i];\r\n      th2=_DEG2RAD*theta[1][i];\r\n      cart[0][i]=a1*std::cos(th1)+a2*std::cos(th1+th2);\r\n      cart[1][i]=a1*std::sin(th1)+a2*std::sin(th1+th2);\r\n   }\r\n   return 0;\r\n}\r\n\r\n//! INVERSE KINEMATICS\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief invKin\r\n//!\r\n//! Inverse displacement problem\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::call_invKin(std::vector<std::vector<double>> &theta,\r\n                       const std::vector<std::vector<double>> &cart)\r\n{return(invKin(theta,cart));}\r\nint Robot::invKin(std::vector<std::vector<double>> &theta,\r\n                  const std::vector<std::vector<double>> &cart)\r\n{\r\n   switch(_robotType)\r\n   {\r\n   case CSPR3DOF:\r\n      invKinCSPR3DOF(theta,cart);\r\n      break;\r\n   default:\r\n      printf (\"No inverse Kinematics model provided for robotType=%s.\\n\",\r\n              _robotTypeStr.c_str());\r\n      assert(!\"Unhandled case\"); // Always assert unhandled cases\r\n      return -1;\r\n      break;\r\n   }\r\n   return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief invKinCSPR3DOF\r\n//!\r\n//! Inverse kinematics for the large 3-DOF point-mass CSPR in PLT-00370:\r\n//! finds cable lengths (theta) from Cartesian EE positions (cart) and\r\n//! cable attacment points (pmat)\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::invKinCSPR3DOF(std::vector<std::vector<double>> &theta,\r\n                          const std::vector<std::vector<double>> &cart)\r\n{\r\n\r\n   int i;\r\n   int nDim=(int)cart.size();\r\n\r\n   int nPts=(int)cart[0].size();\r\n   theta.resize(3);\r\n\r\n   for(i=0;i<nDim;i++) theta[i].resize(nPts);\r\n   double x,y,z,rho1,rho2,rho3;\r\n   std::array<double,3> rv1,rv2,rv3;\r\n\r\n   if(_pmat.size()==0)\r\n   {\r\n      findCSPR3DOFpmat(_pmat);\r\n   }\r\n\r\n   for(i=0;i<nPts;i++)\r\n   {\r\n      x=cart[0][i];\r\n      y=cart[1][i];\r\n      z=cart[2][i];\r\n      rv1={x-_pmat[0][0], y-_pmat[1][0], z-_pmat[2][0]};\r\n      rv2={x-_pmat[0][1], y-_pmat[1][1], z-_pmat[2][1]};\r\n      rv3={x-_pmat[0][2], y-_pmat[1][2], z-_pmat[2][2]};\r\n      rho1=norm(rv1);\r\n      rho2=norm(rv2);\r\n      rho3=norm(rv3);\r\n      theta[0][i]=rho1;\r\n      theta[1][i]=rho2;\r\n      theta[2][i]=rho3;\r\n   }\r\n   return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief findCSPR3DOFpmat\r\n//!\r\n//! Compute the cable attachment points for the large point-mass 3-DOF CSPR\r\n//! in PLT-00370 at Laval University\r\n//!\r\n//! \\param\r\n//! \\return\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::findCSPR3DOFpmat(std::vector<std::vector<double>> &pmat)\r\n{\r\n   int i,j;\r\n   std::array<double,3> cible1={1.0941, -4.9074, 2.5542};\r\n   std::array<double,3> delta1={-0.765, 0.112, 3.74};\r\n   std::array<double,3> cible3={0.2098, 5.3409, 2.6236};\r\n   std::array<double,3> delta2={0.43, 0.125, 3.615};\r\n\r\n   std::array<double,3> p1=cible1+delta1;\r\n   std::array<double,3> p2=cible3+delta2;\r\n   std::array<double,3> p3={-5.9751, 0.1399, 6.1543};\r\n\r\n   pmat.resize(3); for(i=0;i<3;i++) pmat[i].resize(3);\r\n\r\n   std::array<int,3> ind={1,0,2};\r\n   for(i=0;i<3;i++)\r\n   {\r\n      int it=ind[i];\r\n      pmat[i][0]=-p1[it];\r\n      pmat[i][1]=-p2[it];\r\n      pmat[i][2]=-p3[it];\r\n   }\r\n\r\n   std::array<double,3> centroide;\r\n   for(i=0;i<3;i++) centroide[i]=1/3.0*(pmat[i][0]+pmat[i][1]+pmat[i][2]);\r\n\r\n   for(i=0;i<3;i++)\r\n   {\r\n      for(j=0;j<3;j++) pmat[i][j]-=centroide[i];\r\n   }\r\n   return 0;\r\n}\r\n\r\n//! DYNAMICS\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief dynSerial\r\n//!\r\n//! Dynamics model for a serial robot\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::call_dynSerial(std::vector<std::vector<double>> &a1,\r\n                   std::vector<std::vector<double>> &a2,\r\n                   std::vector<std::vector<double>> &a3,\r\n                   std::vector<std::vector<double>> &a4,\r\n                   const std::vector<std::vector<double>> &theta,\r\n                   const std::vector<std::vector<double>> &thetaD,\r\n                   const std::vector<std::vector<double>> &thetaD2)\r\n{return(dynSerial(a1,a2,a3,a4,theta,thetaD,thetaD2));}\r\nint Robot::dynSerial(std::vector<std::vector<double>> &a1,\r\n                     std::vector<std::vector<double>> &a2,\r\n                     std::vector<std::vector<double>> &a3,\r\n                     std::vector<std::vector<double>> &a4,\r\n                     const std::vector<std::vector<double>> &theta,\r\n                     const std::vector<std::vector<double>> &thetaD,\r\n                     const std::vector<std::vector<double>> &thetaD2)\r\n{\r\n   switch(_robotType)\r\n   {\r\n   case RR:\r\n      dynRR(a1,a2,a3,a4,theta,thetaD,thetaD2);\r\n      break;\r\n   default:\r\n      printf (\"No dynamics model provided for serial robotType=%s.\\n\",\r\n              _robotTypeStr.c_str());\r\n      assert(!\"Unhandled case\"); // Always assert unhandled cases\r\n      return -1;\r\n      break;\r\n   }\r\n   return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief dynRR\r\n//!\r\n//! Dynamics model for an RR planar robot\r\n//!  - links are approximated as point masses\r\n//!  - tau = a1*sddot + a2*sdot^2 + a3*sdot + a4\r\n//!  - thetaD and thetaD2 are partial derivatives wrt s\r\n//!\r\n//! \\param\r\n//! \\return\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::dynRR(\r\n      std::vector<std::vector<double>> &a1,\r\n      std::vector<std::vector<double>> &a2,\r\n      std::vector<std::vector<double>> &a3,\r\n      std::vector<std::vector<double>> &a4,\r\n      const std::vector<std::vector<double>> &theta,\r\n      const std::vector<std::vector<double>> &thetaD,\r\n      const std::vector<std::vector<double>> &thetaD2)\r\n{\r\n   int i;\r\n   int nPts=(int)theta[0].size();\r\n   double A1=.4,A2=.6,m1=4,m2=8;\r\n   double th1,th2,dth1,dth2,ddth1,ddth2,c1,c2,c12,ccFact;\r\n   double A11,A12,A22;\r\n   for(i=0;i<2;i++)\r\n   {\r\n      a1[i].resize(nPts);\r\n      a2[i].resize(nPts);\r\n      a3[i].resize(nPts);\r\n      a4[i].resize(nPts);\r\n   }\r\n\r\n   for(i=0;i<nPts;i++)\r\n   {\r\n      th1  =_DEG2RAD*theta[0][i];\r\n      th2  =_DEG2RAD*theta[1][i];\r\n      dth1 =_DEG2RAD*thetaD[0][i];\r\n      dth2 =_DEG2RAD*thetaD[1][i];\r\n      ddth1=_DEG2RAD*thetaD2[0][i];\r\n      ddth2=_DEG2RAD*thetaD2[1][i];\r\n\r\n      c1 =std::cos(th1);\r\n      c2 =std::cos(th2);\r\n      c12=std::cos(th1+th2);\r\n\r\n      A11=.25*m1*A1*A1 + m2*(A1*A1 + .25*A2*A2 + A1*A2*c2);\r\n      A12=.5*m2*(.5*A2*A2 + A1*A2*c2);\r\n      A22=.25*m2*A2*A2;\r\n\r\n      a1[0][i]=A11*dth1 + A12*dth2;\r\n      a1[1][i]=A12*dth1 + A22*dth2;\r\n\r\n      ccFact=m2*A1*A2*sin(th2);\r\n      a2[0][i]=A11*ddth1 + A12*ddth2-ccFact*dth2*(dth1+.5*dth2);\r\n      a2[1][i]=A12*ddth1 + A22*ddth2-.5*ccFact*dth1*dth1;\r\n\r\n      //friction terms: (friction is zero if left unspecified)\r\n      a3[0][i]=10*dth1;\r\n      a3[1][i]=10*dth2;\r\n\r\n      a4[0][i]=.5*_g*(m1*A1*c1 + m2*(2.0*A1*c1 + A2*c12));\r\n      a4[1][i]=.5*_g*m2*A2*c12;\r\n   }\r\n   return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief dynParallel\r\n//!\r\n//! Dynamics model for a parallel robot\r\n//! \\return\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\n///\r\nint Robot::call_dynParallel(std::vector<std::vector<double>> &a1,\r\n                   std::vector<std::vector<double>> &a2,\r\n                   std::vector<std::vector<double>> &a3,\r\n                   std::vector<std::vector<double>> &a4,\r\n                   const std::vector<std::vector<double>> &cart,\r\n                   const std::vector<std::vector<double>> &cartD,\r\n                   const std::vector<std::vector<double>> &cartD2)\r\n{\r\n    return dynParallel(a1,a2,a3,a4,cart,cartD,cartD2);\r\n}\r\n\r\nint Robot::dynParallel(std::vector<std::vector<double>> &a1,\r\n                     std::vector<std::vector<double>> &a2,\r\n                     std::vector<std::vector<double>> &a3,\r\n                     std::vector<std::vector<double>> &a4,\r\n                     const std::vector<std::vector<double>> &cart,\r\n                     const std::vector<std::vector<double>> &cartD,\r\n                     const std::vector<std::vector<double>> &cartD2)\r\n{\r\n   (void)cart;\r\n\r\n   switch(_robotType)\r\n   {\r\n   case CSPR3DOF: //CSPR3DOF\r\n      dynCSPR3DOF(a1,a2,a3,a4,cartD,cartD2);\r\n      break;\r\n   default:\r\n      printf (\"No dynamics model provided for parallel robotType=%s.\\n\",\r\n              _robotTypeStr.c_str());\r\n      assert(!\"Unhandled case\"); // Always assert unhandled cases\r\n      return -1;\r\n      break;\r\n   }\r\n   return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief dynCSPR3DOF\r\n//!\r\n//! Dynamics model for the large 3-DOF point-mass CSPR in PLT-00370\r\n//!  - A*tau = a1*sddot + a2*sdot^2 + a3*sdot + a4\r\n//!  - cartD and cartD2 are partial derivatives wrt s\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::dynCSPR3DOF(\r\n      std::vector<std::vector<double>> &a1,\r\n      std::vector<std::vector<double>> &a2,\r\n      std::vector<std::vector<double>> &a3,\r\n      std::vector<std::vector<double>> &a4,\r\n      const std::vector<std::vector<double>> &cartD,\r\n      const std::vector<std::vector<double>> &cartD2)\r\n{\r\n   int i,j;\r\n   int nCart=3;\r\n   int nPts =(int)cartD[0].size();\r\n\r\n   for(i=0;i<nCart;i++)\r\n   {\r\n      a1[i].resize(nPts);\r\n      a2[i].resize(nPts);\r\n      a3[i].assign(nPts,0.0);\r\n      a4[i].assign(nPts,0.0);\r\n   }\r\n\r\n   for(i=0;i<nPts;i++)\r\n   {\r\n      for(j=0;j<nCart;j++)\r\n      {\r\n         a1[j][i]=-cartD[j][i];\r\n         a2[j][i]=-cartD2[j][i];\r\n      }\r\n      a4[2][i]=_g;\r\n   }\r\n   return 0;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//!\r\n//! \\brief setA\r\n//!\r\n//! Find the A matrix for the dynamics equation of a parallel robot\r\n//!\r\n//! \\param\r\n//! \\return\r\n//!\r\n//////////////////////////////////////////////////////////////////////////////\r\nint Robot::call_setA(const std::vector<double> &theta,\r\n         const std::vector<double> &cart,\r\n         std::vector<std::vector<double>> &A)\r\n{return(setA(theta,cart,A));}\r\n\r\nint Robot::setA(const std::vector<double> &theta,\r\n                const std::vector<double> &cart,\r\n                std::vector<std::vector<double>> &A)\r\n{\r\n   switch(_robotType)\r\n   {\r\n   case CSPR3DOF:\r\n      for(int i=0;i<3;i++)\r\n      {\r\n         for(int j=0;j<3;j++)\r\n         {\r\n            A[i][j]=(cart[i]-_pmat[i][j])/theta[j];\r\n         }\r\n      }\r\n      break;\r\n\r\n   default:\r\n      printf (\"isParallel=True and no code was provided to find the A matrix\");\r\n      printf(\"for robotType=%s.\\n\",_robotTypeStr.c_str());\r\n      assert(!\"Unhandled case\"); // Always assert unhandled cases\r\n      return -1;\r\n      break;\r\n   }\r\n   return 0;\r\n}\r\n\r\n}\r\n", "meta": {"hexsha": "635e7a3fc7b6d92973ad5ef609757503a75da766", "size": 17050, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "batotp/robot.cpp", "max_stars_repo_name": "lpdon/batotp", "max_stars_repo_head_hexsha": "f6b807dc10a8a7756adeb48223f426614af5aed6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-05-17T02:58:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T03:30:18.000Z", "max_issues_repo_path": "batotp/robot.cpp", "max_issues_repo_name": "lpdon/batotp", "max_issues_repo_head_hexsha": "f6b807dc10a8a7756adeb48223f426614af5aed6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-08-02T07:13:55.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-02T07:31:29.000Z", "max_forks_repo_path": "batotp/robot.cpp", "max_forks_repo_name": "lpdon/batotp", "max_forks_repo_head_hexsha": "f6b807dc10a8a7756adeb48223f426614af5aed6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-01T19:30:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-21T10:44:36.000Z", "avg_line_length": 30.3921568627, "max_line_length": 86, "alphanum_fraction": 0.4766568915, "num_tokens": 4940, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3923368443773709, "lm_q1q2_score": 0.2205625543406463}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_CLIP_LINESTRING_HPP\r\n#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_CLIP_LINESTRING_HPP\r\n\r\n#include <boost/range.hpp>\r\n\r\n#include <boost/geometry/algorithms/clear.hpp>\r\n#include <boost/geometry/algorithms/convert.hpp>\r\n\r\n#include <boost/geometry/algorithms/detail/overlay/append_no_duplicates.hpp>\r\n\r\n#include <boost/geometry/util/select_coordinate_type.hpp>\r\n#include <boost/geometry/geometries/segment.hpp>\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace intersection\r\n{\r\n\r\n/*!\r\n    \\brief Strategy: line clipping algorithm after Liang Barsky\r\n    \\ingroup overlay\r\n    \\details The Liang-Barsky line clipping algorithm clips a line with a clipping box.\r\n    It is slightly adapted in the sense that it returns which points are clipped\r\n    \\tparam B input box type of clipping box\r\n    \\tparam P input/output point-type of segments to be clipped\r\n    \\note The algorithm is currently only implemented for 2D Cartesian points\r\n    \\note Though it is implemented in namespace strategy, and theoretically another\r\n        strategy could be used, it is not (yet) updated to the general strategy concepts,\r\n        and not (yet) splitted into a file in folder strategies\r\n    \\author Barend Gehrels, and the following recourses\r\n    - A tutorial: http://www.skytopia.com/project/articles/compsci/clipping.html\r\n    - a German applet (link broken): http://ls7-www.cs.uni-dortmund.de/students/projectgroups/acit/lineclip.shtml\r\n*/\r\ntemplate<typename Box, typename Point>\r\nclass liang_barsky\r\n{\r\nprivate:\r\n    typedef model::referring_segment<Point> segment_type;\r\n\r\n    template <typename T>\r\n    inline bool check_edge(T const& p, T const& q, T& t1, T& t2) const\r\n    {\r\n        bool visible = true;\r\n\r\n        if(p < 0)\r\n        {\r\n            T const r = q / p;\r\n            if (r > t2)\r\n                visible = false;\r\n            else if (r > t1)\r\n                t1 = r;\r\n        }\r\n        else if(p > 0)\r\n        {\r\n            T const r = q / p;\r\n            if (r < t1)\r\n                visible = false;\r\n            else if (r < t2)\r\n                t2 = r;\r\n        }\r\n        else\r\n        {\r\n            if (q < 0)\r\n                visible = false;\r\n        }\r\n\r\n        return visible;\r\n    }\r\n\r\npublic:\r\n\r\n    inline bool clip_segment(Box const& b, segment_type& s, bool& sp1_clipped, bool& sp2_clipped) const\r\n    {\r\n        typedef typename select_coordinate_type<Box, Point>::type coordinate_type;\r\n\r\n        coordinate_type t1 = 0;\r\n        coordinate_type t2 = 1;\r\n\r\n        coordinate_type const dx = get<1, 0>(s) - get<0, 0>(s);\r\n        coordinate_type const dy = get<1, 1>(s) - get<0, 1>(s);\r\n\r\n        coordinate_type const p1 = -dx;\r\n        coordinate_type const p2 = dx;\r\n        coordinate_type const p3 = -dy;\r\n        coordinate_type const p4 = dy;\r\n\r\n        coordinate_type const q1 = get<0, 0>(s) - get<min_corner, 0>(b);\r\n        coordinate_type const q2 = get<max_corner, 0>(b) - get<0, 0>(s);\r\n        coordinate_type const q3 = get<0, 1>(s) - get<min_corner, 1>(b);\r\n        coordinate_type const q4 = get<max_corner, 1>(b) - get<0, 1>(s);\r\n\r\n        if (check_edge(p1, q1, t1, t2)      // left\r\n            && check_edge(p2, q2, t1, t2)   // right\r\n            && check_edge(p3, q3, t1, t2)   // bottom\r\n            && check_edge(p4, q4, t1, t2))   // top\r\n        {\r\n            sp1_clipped = t1 > 0;\r\n            sp2_clipped = t2 < 1;\r\n\r\n            if (sp2_clipped)\r\n            {\r\n                set<1, 0>(s, get<0, 0>(s) + t2 * dx);\r\n                set<1, 1>(s, get<0, 1>(s) + t2 * dy);\r\n            }\r\n\r\n            if(sp1_clipped)\r\n            {\r\n                set<0, 0>(s, get<0, 0>(s) + t1 * dx);\r\n                set<0, 1>(s, get<0, 1>(s) + t1 * dy);\r\n            }\r\n\r\n            return true;\r\n        }\r\n\r\n        return false;\r\n    }\r\n\r\n    template<typename Linestring, typename OutputIterator>\r\n    inline void apply(Linestring& line_out, OutputIterator out) const\r\n    {\r\n        if (!boost::empty(line_out))\r\n        {\r\n            *out = line_out;\r\n            ++out;\r\n            geometry::clear(line_out);\r\n        }\r\n    }\r\n};\r\n\r\n\r\n}} // namespace strategy::intersection\r\n\r\n\r\n#ifndef DOXYGEN_NO_DETAIL\r\nnamespace detail { namespace intersection\r\n{\r\n\r\n/*!\r\n    \\brief Clips a linestring with a box\r\n    \\details A linestring is intersected (clipped) by the specified box\r\n    and the resulting linestring, or pieces of linestrings, are sent to the specified output operator.\r\n    \\tparam OutputLinestring type of the output linestrings\r\n    \\tparam OutputIterator an output iterator which outputs linestrings\r\n    \\tparam Linestring linestring-type, for example a vector of points, matching the output-iterator type,\r\n         the points should also match the input-iterator type\r\n    \\tparam Box box type\r\n    \\tparam Strategy strategy, a clipping strategy which should implement the methods \"clip_segment\" and \"apply\"\r\n*/\r\ntemplate\r\n<\r\n    typename OutputLinestring,\r\n    typename OutputIterator,\r\n    typename Range,\r\n    typename Box,\r\n    typename Strategy\r\n>\r\nOutputIterator clip_range_with_box(Box const& b, Range const& range,\r\n            OutputIterator out, Strategy const& strategy)\r\n{\r\n    if (boost::begin(range) == boost::end(range))\r\n    {\r\n        return out;\r\n    }\r\n\r\n    typedef typename point_type<OutputLinestring>::type point_type;\r\n\r\n    OutputLinestring line_out;\r\n\r\n    typedef typename boost::range_iterator<Range const>::type iterator_type;\r\n    iterator_type vertex = boost::begin(range);\r\n    for(iterator_type previous = vertex++;\r\n            vertex != boost::end(range);\r\n            ++previous, ++vertex)\r\n    {\r\n        point_type p1, p2;\r\n        geometry::convert(*previous, p1);\r\n        geometry::convert(*vertex, p2);\r\n\r\n        // Clip the segment. Five situations:\r\n        // 1. Segment is invisible, finish line if any (shouldn't occur)\r\n        // 2. Segment is completely visible. Add (p1)-p2 to line\r\n        // 3. Point 1 is invisible (clipped), point 2 is visible. Start new line from p1-p2...\r\n        // 4. Point 1 is visible, point 2 is invisible (clipped). End the line with ...p2\r\n        // 5. Point 1 and point 2 are both invisible (clipped). Start/finish an independant line p1-p2\r\n        //\r\n        // This results in:\r\n        // a. if p1 is clipped, start new line\r\n        // b. if segment is partly or completely visible, add the segment\r\n        // c. if p2 is clipped, end the line\r\n\r\n        bool c1 = false;\r\n        bool c2 = false;\r\n        model::referring_segment<point_type> s(p1, p2);\r\n\r\n        if (!strategy.clip_segment(b, s, c1, c2))\r\n        {\r\n            strategy.apply(line_out, out);\r\n        }\r\n        else\r\n        {\r\n            // a. If necessary, finish the line and add a start a new one\r\n            if (c1)\r\n            {\r\n                strategy.apply(line_out, out);\r\n            }\r\n\r\n            // b. Add p1 only if it is the first point, then add p2\r\n            if (boost::empty(line_out))\r\n            {\r\n                detail::overlay::append_no_duplicates(line_out, p1, true);\r\n            }\r\n            detail::overlay::append_no_duplicates(line_out, p2);\r\n\r\n            // c. If c2 is clipped, finish the line\r\n            if (c2)\r\n            {\r\n                strategy.apply(line_out, out);\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    // Add last part\r\n    strategy.apply(line_out, out);\r\n    return out;\r\n}\r\n\r\n}} // namespace detail::intersection\r\n#endif // DOXYGEN_NO_DETAIL\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_CLIP_LINESTRING_HPP\r\n", "meta": {"hexsha": "9c6b01e7b2b867a312ed3441a21fc68f0e8d9a65", "size": 7958, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/geometry/algorithms/detail/overlay/clip_linestring.hpp", "max_stars_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_stars_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/geometry/algorithms/detail/overlay/clip_linestring.hpp", "max_issues_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_issues_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/geometry/algorithms/detail/overlay/clip_linestring.hpp", "max_forks_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_forks_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 32.7489711934, "max_line_length": 114, "alphanum_fraction": 0.5917315909, "num_tokens": 1956, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093585306514, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.22039814973080923}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_FUNCTIONS_GENERAL_MTIMES_HPP_INCLUDED\n#define NT2_LINALG_FUNCTIONS_GENERAL_MTIMES_HPP_INCLUDED\n\n#include <nt2/linalg/functions/mtimes.hpp>\n#include <nt2/linalg/details/blas/mm.hpp>\n#include <nt2/core/functions/transpose.hpp>\n#include <nt2/core/functions/ctranspose.hpp>\n#include <nt2/include/functions/zeros.hpp>\n#include <nt2/include/functions/multiplies.hpp>\n#include <nt2/include/functions/ndims.hpp>\n#include <nt2/include/constants/one.hpp>\n#include <nt2/include/constants/zero.hpp>\n#include <nt2/core/container/dsl/size.hpp>\n#include <nt2/core/container/dsl/alias.hpp>\n#include <nt2/core/container/dsl/as_terminal.hpp>\n#include <nt2/core/utility/assign_swap.hpp>\n#include <nt2/sdk/memory/forward/container.hpp>\n#include <nt2/sdk/memory/category.hpp>\n#include <boost/proto/traits.hpp>\n#include <boost/assert.hpp>\n\nnamespace nt2 { namespace tag\n{\n  struct blas_normal_\n  {\n    BOOST_FORCEINLINE static char call()\n    {\n      return 'N';\n    }\n  };\n\n  struct blas_transpose_\n  {\n    BOOST_FORCEINLINE static char call()\n    {\n      return 'T';\n    }\n  };\n\n  struct blas_ctranspose_\n  {\n    BOOST_FORCEINLINE static char call()\n    {\n      return 'C';\n    }\n  };\n} }\n\nnamespace nt2 { namespace ext\n{\n  template<class Domain, int N,class Expr>\n  struct size_of<tag::mtimes_, Domain, N, Expr>\n  {\n    typedef typename boost::proto::result_of::child_c<Expr&, 0>::value_type child0;\n    typedef typename boost::proto::result_of::child_c<Expr&, 1>::value_type child1;\n\n    typedef typename boost::proto::result_of::value< typename boost::proto::result_of::child_c<Expr&, 4>::value_type >::value_type trs0;\n    typedef typename boost::proto::result_of::value< typename boost::proto::result_of::child_c<Expr&, 5>::value_type >::value_type trs1;\n\n    typedef typename child0::extent_type sz0;\n    typedef typename child1::extent_type sz1;\n\n    static const std::size_t sz0_0 = boost::is_same<trs0, tag::blas_normal_>::value ? 0 : 1;\n    static const std::size_t sz0_1 = boost::is_same<trs0, tag::blas_normal_>::value ? 1 : 0;\n    static const std::size_t sz1_0 = boost::is_same<trs1, tag::blas_normal_>::value ? 0 : 1;\n    static const std::size_t sz1_1 = boost::is_same<trs1, tag::blas_normal_>::value ? 1 : 0;\n\n    typedef of_size_< mpl_value< typename boost::fusion::result_of::at_c<sz0, sz0_0>::type>::value\n                    , mpl_value< typename boost::fusion::result_of::at_c<sz1, sz1_1>::type>::value\n                    >  result_type;\n\n    result_type operator()(Expr& e) const\n    {\n      sz0 const& size0 = boost::proto::child_c<0>(e).extent();\n      sz1 const& size1 = boost::proto::child_c<1>(e).extent();\n\n      BOOST_ASSERT_MSG( ndims(size0) <= 2 && ndims(size1) <= 2\n                      , \"Inputs must be 2-D, or at least one input must be scalar\"\n                      );\n\n      BOOST_ASSERT_MSG( boost::fusion::at_c<sz0_1>(size0) == boost::fusion::at_c<sz1_0>(size1)\n                      , \"Inner dimensions must agree\"\n                      );\n\n      return result_type( boost::fusion::at_c<sz0_0>(size0)\n                        , boost::fusion::at_c<sz1_1>(size1)\n                        );\n    }\n  };\n\n  template<class Domain, int N,class Expr>\n  struct value_type<tag::mtimes_, Domain, N, Expr>\n  {\n    typedef typename boost::proto::result_of::child_c<Expr&, 0>::value_type child0;\n    typedef typename boost::proto::result_of::child_c<Expr&, 1>::value_type child1;\n    typedef typename meta::call<tag::multiplies_(typename child0::value_type, typename child1::value_type)>::type type;\n  };\n} }\n\nnamespace nt2 { namespace ext\n{\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                            )\n  {\n    typedef typename meta::call<tag::multiplies_(typename A0::value_type, typename A1::value_type)>::type T;\n    BOOST_DISPATCH_RETURNS(2, (A0 const& a0, A1 const& a1),\n      mtimes(a0, a1, Zero<T>(), One<T>(), tag::blas_normal_(), tag::blas_normal_())\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(A1)(A2)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((ast_<A1, nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                            )\n  {\n    typedef typename meta::call<tag::multiplies_(typename A0::value_type, typename A1::value_type)>::type T;\n    BOOST_DISPATCH_RETURNS(3, (A0 const& a0, A1 const& a1, A2 const& a2),\n      mtimes(a0, a1, a2, One<T>(), tag::blas_normal_(), tag::blas_normal_())\n    )\n  };\n\n  // Recognize scalar/matrix, matrix/scalar and scalar/scalar\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(A1)(T1)(N1)\n                            , (scalar_< unspecified_<A0> >)\n                              ((expr_< generic_< unspecified_<A1> >, T1, N1 >))\n                            )\n  {\n    typedef typename meta::call<tag::multiplies_(A0 const&, A1 const&)>::type result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 const& a1) const\n    {\n      return nt2::multiplies(a0, a1);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(T0)(N0)(A1)\n                            , ((expr_< generic_< unspecified_<A0> >, T0, N0 >))\n                              (scalar_< unspecified_<A1> >)\n                            )\n  {\n    typedef typename meta::call<tag::multiplies_(A0 const&, A1 const&)>::type result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 const& a1) const\n    {\n      return nt2::multiplies(a0, a1);\n    }\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_< unspecified_<A0> >)\n                              (scalar_< unspecified_<A1> >)\n                            )\n  {\n    typedef typename meta::call<tag::multiplies_(A0 const&, A1 const&)>::type result_type;\n    BOOST_FORCEINLINE result_type operator()(A0 const& a0, A1 const& a1) const\n    {\n      return nt2::multiplies(a0, a1);\n    }\n  };\n\n  // Recognize transpose\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(A1)(A2)(A3)(A4)(A5)\n                            , ((node_< A0, nt2::tag::transpose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              ((ast_< A1, nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                              (scalar_< unspecified_<A3> >)\n                              (unspecified_<A4>)\n                              (unspecified_<A5>)\n                            )\n  {\n    BOOST_DISPATCH_RETURNS_ARGS(6, (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const& a4, A5 const& a5), (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const&, A5 const& a5),\n      mtimes(boost::proto::child_c<0>(a0), a1, a2, a3, tag::blas_transpose_(), a5)\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(A1)(A2)(A3)(A4)(A5)\n                            , ((ast_< A0, nt2::container::domain>))\n                              ((node_< A1, nt2::tag::transpose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                              (scalar_< unspecified_<A3> >)\n                              (unspecified_<A4>)\n                              (unspecified_<A5>)\n                            )\n  {\n    BOOST_DISPATCH_RETURNS_ARGS(6, (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const& a4, A5 const& a5), (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const& a4, A5 const&),\n      mtimes(a0, boost::proto::child_c<0>(a1), a2, a3, a4, tag::blas_transpose_())\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(A1)(A2)(A3)(A4)(A5)\n                            , ((node_< A0, nt2::tag::transpose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              ((node_< A1, nt2::tag::transpose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                              (scalar_< unspecified_<A3> >)\n                              (unspecified_<A4>)\n                              (unspecified_<A5>)\n                            )\n  {\n    BOOST_DISPATCH_RETURNS_ARGS(6, (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const& a4, A5 const& a5), (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const&, A5 const&),\n      mtimes(boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1), a2, a3, tag::blas_transpose_(), tag::blas_transpose_())\n    )\n  };\n\n  // Recognize ctranspose\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(A1)(A2)(A3)(A4)(A5)\n                            , ((node_< A0, nt2::tag::ctranspose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              ((ast_< A1, nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                              (scalar_< unspecified_<A3> >)\n                              (unspecified_<A4>)\n                              (unspecified_<A5>)\n                            )\n  {\n    BOOST_DISPATCH_RETURNS_ARGS(6, (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const& a4, A5 const& a5), (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const&, A5 const& a5),\n      mtimes(boost::proto::child_c<0>(a0), a1, a2, a3, tag::blas_ctranspose_(), a5)\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(A1)(A2)(A3)(A4)(A5)\n                            , ((ast_< A0, nt2::container::domain>))\n                              ((node_< A1, nt2::tag::ctranspose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                              (scalar_< unspecified_<A3> >)\n                              (unspecified_<A4>)\n                              (unspecified_<A5>)\n                            )\n  {\n    BOOST_DISPATCH_RETURNS_ARGS(6, (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const& a4, A5 const& a5), (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const& a4, A5 const&),\n      mtimes(a0, boost::proto::child_c<0>(a1), a2, a3, a4, tag::blas_ctranspose_())\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( mtimes_, tag::cpu_\n                            , (A0)(A1)(A2)(A3)(A4)(A5)\n                            , ((node_< A0, nt2::tag::ctranspose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              ((node_< A1, nt2::tag::ctranspose_, boost::mpl::long_<1> , nt2::container::domain>))\n                              (scalar_< unspecified_<A2> >)\n                              (scalar_< unspecified_<A3> >)\n                              (unspecified_<A4>)\n                              (unspecified_<A5>)\n                            )\n  {\n    BOOST_DISPATCH_RETURNS_ARGS(6, (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const& a4, A5 const& a5), (A0 const& a0, A1 const& a1, A2 const& a2, A3 const& a3, A4 const&, A5 const&),\n      mtimes(boost::proto::child_c<0>(a0), boost::proto::child_c<0>(a1), a2, a3, tag::blas_ctranspose_(), tag::blas_ctranspose_())\n    )\n  };\n} }\n\nnamespace boost { namespace simd { namespace ext\n{\n  // Recognize alpha\n  BOOST_DISPATCH_IMPLEMENT  ( multiplies_, tag::cpu_\n                            , (A0)(A1)\n                            , (scalar_< unspecified_<A0> >)\n                              ((node_< A1, nt2::tag::mtimes_, boost::mpl::long_<6> , nt2::container::domain>))\n                            )\n  {\n    BOOST_DISPATCH_RETURNS(2, (A0 const& a0, A1 const& a1),\n      mtimes(boost::proto::child_c<0>(a1), boost::proto::child_c<1>(a1), boost::proto::child_c<2>(a1), a0 * boost::proto::value(boost::proto::child_c<3>(a1)), boost::proto::child_c<4>(a1), boost::proto::child_c<5>(a1))\n    )\n  };\n\n  BOOST_DISPATCH_IMPLEMENT  ( multiplies_, tag::cpu_\n                            , (A0)(A1)\n                            , ((node_< A0, nt2::tag::mtimes_, boost::mpl::long_<6> , nt2::container::domain>))\n                              (scalar_< unspecified_<A1> >)\n                            )\n  {\n    BOOST_DISPATCH_RETURNS(2, (A0 const& a0, A1 const& a1),\n      mtimes(boost::proto::child_c<0>(a0), boost::proto::child_c<1>(a0), boost::proto::child_c<2>(a0), a1 * boost::proto::value(boost::proto::child_c<3>(a0)), boost::proto::child_c<4>(a0), boost::proto::child_c<5>(a0))\n    )\n  };\n} } }\n\nnamespace nt2 { namespace ext\n{\n  // run_assign\n  BOOST_DISPATCH_IMPLEMENT  ( run_assign_, tag::cpu_\n                            , (A0)(A1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((node_< A1, nt2::tag::mtimes_, boost::mpl::long_<6> , nt2::container::domain>))\n                            )\n  {\n    typedef A0& result_type;\n\n    result_type operator()(A0& a0, A1& a1) const\n    {\n      using boost::fusion::at_c;\n      typedef typename A1::value_type value_type;\n\n      if(at_c<1>(boost::proto::child_c<0>(a1).extent()) == 0u)\n      {\n        a0 = zeros(a1.extent(), meta::as_<value_type>());\n        return a0;\n      }\n\n      typedef nt2::memory::container<tag::table_, value_type, nt2::_2D> desired_semantic;\n      NT2_AS_TERMINAL_IN(desired_semantic, child0, boost::proto::child_c<0>(a1));\n      NT2_AS_TERMINAL_IN(desired_semantic, child1, boost::proto::child_c<1>(a1));\n      NT2_AS_TERMINAL_OUT(desired_semantic, result, a0);\n\n      value_type alpha = boost::proto::value(boost::proto::child_c<3>(a1));\n      value_type beta = boost::proto::value(boost::proto::child_c<2>(a1));\n\n      char transA = A1::proto_child4::proto_child0::call();\n      char transB = A1::proto_child5::proto_child0::call();\n\n      nt2_la_int m = transA == 'N' ? nt2_la_int(at_c<0>(child0.extent())) : nt2_la_int(at_c<1>(child0.extent()));\n      nt2_la_int n = transB == 'N' ? nt2_la_int(at_c<1>(child1.extent())) : nt2_la_int(at_c<0>(child1.extent()));\n      nt2_la_int k = transA == 'N' ? nt2_la_int(at_c<1>(child0.extent())) : nt2_la_int(at_c<0>(child0.extent()));\n      nt2_la_int lda = at_c<0>(child0.extent());\n      nt2_la_int ldb = at_c<0>(child1.extent());\n      nt2_la_int ldc = at_c<0>(a1.extent());\n\n      typedef typename container::as_terminal<desired_semantic>::type dummy_type;\n      typedef typename container::as_view_impl<dummy_type>::type view_type;\n\n      dummy_type dummy;\n      view_type result_view;\n      bool swap = (void*)&result != (void*)&a0;\n\n      if( swap || ( container::alias(result, child0) || container::alias(result, child1) ) )\n      {\n        // overlapping of input and output data\n        // so we provide dummy space and put it back in result later\n        dummy.resize(a1.extent());\n        result_view.reset(dummy);\n        swap = true;\n      }\n      else\n      {\n        result.resize(a1.extent());\n        result_view.reset(result);\n      }\n\n      nt2::details::\n      gemm( &transA, &transB\n          , &m, &n, &k\n          , &alpha\n          , child0.data(), &lda\n          , child1.data(), &ldb\n          , &beta\n          , result_view.data(), &ldc\n          );\n\n      if(swap)\n        container::assign_swap(a0, dummy);\n      return a0;\n    }\n  };\n\n} }\n\n#endif\n\n", "meta": {"hexsha": "68f115efb389df53a108e1760c1a7f8c64102aa7", "size": 15976, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/functions/general/mtimes.hpp", "max_stars_repo_name": "psiha/nt2", "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/functions/general/mtimes.hpp", "max_issues_repo_name": "psiha/nt2", "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/linalg/include/nt2/linalg/functions/general/mtimes.hpp", "max_forks_repo_name": "psiha/nt2", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 42.6026666667, "max_line_length": 218, "alphanum_fraction": 0.5426890336, "num_tokens": 4532, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118791767282, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22038094316993687}}
{"text": "/**\nBSD 3-Clause License\n\nThis file is part of the code accompanying the paper\nGradient-SDF: A Semi-Implicit Surface Representation for 3D Reconstruction\nby Christiane Sommer*, Lu Sang*, David Schubert, and Daniel Cremers (* denotes equal contribution).\n\nCopyright (c) 2021, Christiane Sommer and Lu Sang.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n\n#include \"ColorUpsampler.h\"\n#include \"mesh/HrLayeredMarchingCubes.h\"\n\n#include <fstream>\n// #include <Eigen/Sparse>\n\nusing Vec8f = Vec8f;\nusing Arr8f = Eigen::Array<float, 8, 1>;\n\n// ========== non-class functions ==========\n\n//! from pose matrix to 6-DoF\nEigen::Matrix<float, 1, 7> MatrixTo7DoF(Mat4f& pose){\n\tEigen::Matrix<float, 1, 7> xi;\n\tVec3f t(pose.topRightCorner(3,1));\n\tEigen::Quaternion<float> q(pose.topLeftCorner<3,3>());\n\txi << t[0], t[1], t[2],  q.x(), q.y(), q.z(), q.w();\n\treturn xi;\n}\n\ntemplate<typename T>\nstatic void printVec(std::vector<T> vec){\n\tfor (const auto& i: vec)\n  \t\tstd::cout << i << \" \";\n}\n\n\n//! check for NaN values inside Eigen object\ntemplate<class S> \nbool checkNan(S vector)\n{\n    return vector.array().isNaN().sum(); \n}\n\n//! interpolation for RGB image\nstatic Vec3f interpolateImage(const float m, const float n, const cv::Mat& img)\n{\n\tint x = std::floor(m);\n\tint y = std::floor(n);\n\tcv::Vec3f tmp;\n\tif ((x+1) < img.rows && (y+1) < img.cols){\n\t\ttmp = (y+1.0-n)*(m-x)*img.at<cv::Vec3f>(x+1,y) + (y+1.0-n)*(x+1.0-m)*img.at<cv::Vec3f>(x,y) + (n-y)*(m-x)*img.at<cv::Vec3f>(x+1,y+1) + (n-y)*(x+1.0-m)*img.at<cv::Vec3f>(x,y+1);\n\t}\n\telse if ((y+1) < img.cols && x >= img.rows){\n\t\ttmp = (y+1.0-n)*img.at<cv::Vec3f>(x,y) + (n-y)*img.at<cv::Vec3f>(x,y+1);\n\t}\n\telse if ( y >= img.cols && (x+1) < img.rows){\n\t\ttmp = (m-x)*img.at<cv::Vec3f>(x+1,y) + (x+1.0-m)*img.at<cv::Vec3f>(x,y);\n\t}\n\telse{\n\t\ttmp = img.at<cv::Vec3f>(x,y);\n\t}\n\n\tVec3f intensity(tmp[2],tmp[1],tmp[0]); // OpenCV stores image colors as BGR.\n\treturn intensity;\n}\n\n\n//! corners of cube [-1, 1]^3\nEigen::Matrix<float, 3, 8> centeredCubeCorners()\n{\n\tEigen::Matrix<float, 3, 8> corners;\n\t\n\tcorners.col(0) << -1.0, -1.0, -1.0;\n\tcorners.col(1) << 1.0, -1.0, -1.0;\n\tcorners.col(2) << -1.0, 1.0, -1.0;\n\tcorners.col(3) << 1.0, 1.0, -1.0;\n\tcorners.col(4) << -1.0, -1.0, 1.0;\n\tcorners.col(5) << 1.0, -1.0, 1.0;\n\tcorners.col(6) << -1.0, 1.0, 1.0;\n\tcorners.col(7) << 1.0, 1.0, 1.0;\n\n\treturn corners;\n}\n\n\n// ========== initialization ==========\n\n//! constructor\nColorUpsampler::ColorUpsampler(const SdfLrMap& sdf_lr,\n                            phmap::parallel_flat_hash_map<Vec3i, std::vector<bool>>& vis_map,\n                            std::vector<std::shared_ptr<cv::Mat>>& images,\n                            std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>>& poses,\n                            std::vector<int>& frame_idx,\n                            const float voxel_size,\n                            const Mat3f& K) :\n    images_(images),\n    poses_(poses),\n    frame_idx_(frame_idx),\n    voxel_size_(voxel_size),\n    voxel_size_inv_(1.f / voxel_size),\n    K_(K)\n{\n    num_frames_ = frame_idx_.size(); // does not work inside colon initializer\n    init(sdf_lr, vis_map);\n    // selectPoses();\n}\n\n//! init\nvoid ColorUpsampler::init(const SdfLrMap& sdf_lr, phmap::parallel_flat_hash_map<Vec3i, std::vector<bool>>& vis_map)\n{\n\tindices_.clear();\n\tvis_.clear();\n    sdf_.clear();\n\t// convert low-res voxels to high-res voxels\n    const float voxel_diameter = std::sqrt(3.) * voxel_size_;\n\tfor (const auto& voxel: sdf_lr) {\n        if (std::fabs(voxel.second.dist) < voxel_diameter) { // only accept voxels close to surface\n            sdf_.emplace(voxel.first, SdfVoxelHr(voxel.second, voxel_size_));\n        }\n\t}\n\n\tnum_voxels_ = sdf_.size();\n\tindices_.resize(num_voxels_);\n\tvis_.resize(num_voxels_);\n\n\t// store indices and visibility vectors in correct order (that of high-res voxel map)\n\tint count = 0;\n\tfor (const auto& voxel: sdf_) {\n\t\tindices_[count] = voxel.first;\n\t\tvis_[count] = vis_map[voxel.first];\n\t\tvis_[count].resize(frame_idx_.back()+1);\n\t\t++count;\n    }\n}\n\n\n// ========== helper functions for Jacobians ==========\n\n//! get I_i(R_iv+t) RGB/gray value for 8 subvoxels \nbool ColorUpsampler::getIntensity(const int frame, const Vec3i& idx, const Mat3f& R, const Vec3f& t, Mat3x8f& intensity)\n{\n\tconst float fx = K_(0,0);\n\tconst float fy = K_(1,1);\n\tconst float cx = K_(0,2);\n\tconst float cy = K_(1,2);\n\n\tSdfVoxelHr voxel(getSdf(idx));\n\n\t\n\tMat3x8f point = R.transpose()*(getSubvoxelFloat(idx) - voxel.grad * voxel.d.transpose() - t.replicate(1,8));\n\n    auto m = fx * point.row(0).array()/point.row(2).array() + cx;\n    auto n = fy * point.row(1).array()/point.row(2).array() + cy;\n\n\t//DEBUG\n\tif (m.hasNaN()|| n.hasNaN()){\n\t\tstd::cout << \"invalid pixel coordinate at voxel \"<< idx.transpose() << \" at frame \" << frame << std::endl; \n\t\treturn false;\n\t}\n\n    const cv::Mat& img = getFrame(frame);\n\n\t// Mat3x8f intensity;\n\tfor (size_t i = 0; i < 8; i++){\n        if (m(i)<0 || m(i)>=img.cols || n(i)<0 || n(i)>=img.rows) {\n\t\t\t\n\t\t\treturn false;\n\t\t}\n        else {\n            intensity.col(i) = interpolateImage(n(i), m(i), img);\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\n\n//! coordinates of subvoxel centers\nMat3x8f ColorUpsampler::getSubvoxelFloat(const Vec3i& voxel_in)\n{\n\tVec3f voxel_float = voxel_in.cast<float>();\n    return voxel_size_ * (.25 * centeredCubeCorners() + voxel_float.replicate<1,8>());\n}\n\n// ========== set values for individual voxels ==========\n\n//! set albedo\nvoid ColorUpsampler::setAlbedo(const Vec3i& idx, const Vec8f& r, const Vec8f& g, const Vec8f& b)\n{\n\tVec8f rr, gg, bb;\n\trr = r;\n\trr = rr.cwiseMax(0.0);\n\trr = rr.cwiseMin(1.0);\n\n\tgg = g;\n\tgg = gg.cwiseMax(0.0);\n\tgg = gg.cwiseMin(1.0);\n\n\tbb = b;\n\tbb = bb.cwiseMax(0.0);\n\tbb = bb.cwiseMin(1.0);\n\n\tsdf_.at(idx).r = rr;\n\tsdf_.at(idx).g = gg;\n\tsdf_.at(idx).b = bb;\n\n}\n\n\n//! extract mesh from SDF to debug geometry\nbool ColorUpsampler::extractMesh(std::string filename)\n{\n    HrLayeredMarchingCubes lmc(Vec3f(voxel_size_, voxel_size_, voxel_size_));\n    lmc.computeIsoSurface(&sdf_);\n    bool success = lmc.savePly(filename + \".ply\");\n\tif (success)\n\t\tstd::cout << \"Mesh \" << filename << \".ply successfully saved.\" << std::endl;\n\n\treturn success;\n}\n\nbool ColorUpsampler::extractCloud(std::string filename)\n{\n\n\tconst float voxel_size_4 = .25 * voxel_size_;\n\tfilename += \".ply\";\n\n\tint voxel_id = 0;\n    std::vector<Eigen::Matrix<float, 9, 1>> points_normals_colors;\n    for (const auto& el : sdf_) {\n\n\t\tstd::vector<bool> vis = vis_[voxel_id];\n\t\tbool visible = false;\n\t\tfor (size_t i = 0; i < num_frames_; i++){\n\t\t\tif (vis[frame_idx_[i]]){\n\t\t\t\tvisible = true;\n\t\t\t\tbreak;\n\t\t\t}\t\n\t\t}\n\n\t\tif(!visible){\n\t\t\tvoxel_id++;\n\t\t\tcontinue;\n\t\t}\n\n        const SdfVoxelHr& v = el.second;\n        if (v.weight < 5){\n\t\t\tvoxel_id++;\n            continue;\n\t\t}\n\n\t\tMat3x8f voxel_normal = -v.grad.normalized().replicate(1,8);\n\t\tMat3x8f voxel_float = getSubvoxelFloat(el.first);\n\t\tMat3x8f distances = voxel_normal * v.d.asDiagonal();\n\t\tfor (int i=0; i<8; ++i)\n\t\t{\n\t\t\tVec3f d = distances.col(i);\n\t\t\tif (std::fabs(d[0]) < voxel_size_4 && std::fabs(d[1]) < voxel_size_4 && std::fabs(d[2]) < voxel_size_4 && !std::isnan(v.r[i]) && !std::isnan(v.g[i]) && !std::isnan(v.b[i]))\n\t\t\t{\n\t\t\t\tEigen::Matrix<float, 9, 1> pnc;\n\t\t\t\tpnc.segment<3>(0) = voxel_float.col(i) + d;\n\t\t\t\tpnc.segment<3>(3) = voxel_normal.col(i);\n\t\t\t\tpnc.segment<3>(6) = Vec3f(v.r[i], v.g[i], v.b[i]);\n\t\t\t\tpoints_normals_colors.push_back(pnc);\n\t\t\t}\n\t\t}\n\t\tvoxel_id++;\n    }    \n\n    std::ofstream plyFile;\n    plyFile.open(filename.c_str());\n    if (!plyFile.is_open())\n        return false;\n        \n    plyFile << \"ply\" << std::endl;\n    plyFile << \"format ascii 1.0\" << std::endl;\n    plyFile << \"element vertex \" << points_normals_colors.size() << std::endl;\n    plyFile << \"property float x\" << std::endl;\n    plyFile << \"property float y\" << std::endl;\n    plyFile << \"property float z\" << std::endl;\n    plyFile << \"property float nx\" << std::endl;\n    plyFile << \"property float ny\" << std::endl;\n    plyFile << \"property float nz\" << std::endl;\n    plyFile << \"property uchar red\" << std::endl;\n    plyFile << \"property uchar green\" << std::endl;\n    plyFile << \"property uchar blue\" << std::endl;\n    plyFile << \"end_header\" << std::endl;\n    \n    for (const Eigen::Matrix<float, 9, 1>& p : points_normals_colors)\n\t{\n        plyFile << p[0] << \" \" << p[1] << \" \" << p[2] << \" \" << p[3] << \" \" << p[4] << \" \" << p[5] << \" \" << int(255 * p[6]) << \" \" << int(255 * p[7]) << \" \" << int(255 * p[8]) << std::endl;\n    }\n    \n    plyFile.close();\n\n\tstd::cout << \"Cloud \" << filename << \" successfully saved.\" << std::endl;\n    return true;\n}\n\n\n // ------------------- solvers -----------------------------------------------------------------------------------------------------------------\n\n\n//! compute albedo from ambient light assumption, i.e. average over all observations\nvoid ColorUpsampler::computeColor()\n{\n\t// size_t num_tot_frames = getVis(0).size();\n\n\tsize_t count = 0; // counter (same for all three color channels)\n    Vec8f br, bb, bg;\n    int voxel_id = 0;\n\n\tfor (const auto& idx : indices_) {\n\n\t\tbr.setZero();\n\t\tbb.setZero();\n\t\tbg.setZero();\n\n\t\tstd::vector<bool> vis = getVis(voxel_id);\n\t\tSdfVoxelHr voxel(getSdf(idx));\n\t\t\n\t\tfor(size_t i = 0; i < num_frames_; i++){\n\t\t\tMat3f R = getRotation(i);\n\t\t\tVec3f t = getTranslation(i);\n\t\t\t\n            if(vis[frame_idx_[i]]) {\n\t\t\t\t// r(v) = \\sum_i (I(pi(Rv+t)) - pho(v)(<n(v),Rl>))\n\t\t\t\tMat3x8f intensity;\n\t\t\t\tif(!getIntensity(i, idx, R, t, intensity)){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbr += intensity.row(0);\n\t\t\t\tbg += intensity.row(1);\n\t\t\t\tbb += intensity.row(2);\n\t\t\t\t++count;\n\t\t\t}\n\t\t}\n\n\t\tVec8f r,g,b;\n\t\tfloat inv_count = 1.f / float(count);\n\t\tr = inv_count * br;\n\t\tg = inv_count * bg;\n\t\tb = inv_count * bb;\n\t\tsetAlbedo(idx, r, g, b); // cut-off happens here\n\t\tcount = 0;\n\t\tvoxel_id++;\n\t}\n}\n\n", "meta": {"hexsha": "5452d0d63d8b96d2ae3d010602dea5f6b8c4d70e", "size": 11211, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/include/ps_optimizer/ColorUpsampler.cpp", "max_stars_repo_name": "c-sommer/gradient-sdf", "max_stars_repo_head_hexsha": "8e777231e04ca138fc3118bd5851caa0280e503b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-27T11:06:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T11:06:45.000Z", "max_issues_repo_path": "cpp/include/ps_optimizer/ColorUpsampler.cpp", "max_issues_repo_name": "c-sommer/gradient-sdf", "max_issues_repo_head_hexsha": "8e777231e04ca138fc3118bd5851caa0280e503b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/include/ps_optimizer/ColorUpsampler.cpp", "max_forks_repo_name": "c-sommer/gradient-sdf", "max_forks_repo_head_hexsha": "8e777231e04ca138fc3118bd5851caa0280e503b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.580474934, "max_line_length": 190, "alphanum_fraction": 0.6187672821, "num_tokens": 3448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22038093670468767}}
{"text": "#ifndef DART_CONSTRAINT_LCPUTILS_HPP_\n#define DART_CONSTRAINT_LCPUTILS_HPP_\n\n#include <memory>\n\n#include <Eigen/Dense>\n\n#include \"dart/constraint/BoxedLcpSolver.hpp\"\n\nnamespace dart {\nnamespace constraint {\n\nclass LCPUtils\n{\npublic:\n  static bool isLCPSolutionValid(\n      const Eigen::MatrixXs& mA,\n      const Eigen::VectorXs& mX,\n      const Eigen::VectorXs& mB,\n      const Eigen::VectorXs& mHi,\n      const Eigen::VectorXs& mLo,\n      const Eigen::VectorXi& mFIndex,\n      bool ignoreFrictionIndices);\n\n  /// This applies a simple algorithm to guess the solution to the LCP problem.\n  /// It's not guaranteed to be correct, but it often can be if there is no\n  /// sliding friction on this timestep.\n  static Eigen::VectorXs guessSolution(\n      const Eigen::MatrixXs& mA,\n      const Eigen::VectorXs& mB,\n      const Eigen::VectorXs& mHi,\n      const Eigen::VectorXs& mLo,\n      const Eigen::VectorXi& mFIndex);\n\n  /// This reduces an LCP problem by merging any near-identical contact points.\n  /// It returns a mapOut matrix, such that if you solve this LCP and then\n  /// multiply the resulting x as mapOut*x, you'll get the solution to the\n  /// original LCP.\n  static Eigen::MatrixXs reduce(\n      Eigen::MatrixXs& A,\n      Eigen::VectorXs& X,\n      Eigen::VectorXs& b,\n      Eigen::VectorXs& hi,\n      Eigen::VectorXs& lo,\n      Eigen::VectorXi& fIndex);\n\n  /// This cuts a problem down to just the normal forces, ignoring friction.\n  /// It returns a mapOut matrix, such that if you solve this LCP and then\n  /// multiply the resulting x as mapOut*x, you'll get the solution to the\n  /// original LCP, but with friction forces all 0.\n  static Eigen::MatrixXs removeFriction(\n      Eigen::MatrixXs& A,\n      Eigen::VectorXs& X,\n      Eigen::VectorXs& b,\n      Eigen::VectorXs& hi,\n      Eigen::VectorXs& lo,\n      Eigen::VectorXi& fIndex);\n\n  /// This solves the LCP problem by first automatically de-duplicating columns\n  /// to create a reduced version of an equivalent problem, ideally with a\n  /// full-rank A. Then the solution to the original LCP is recovered by\n  /// re-inflating the solution to the reduced problem.\n  static bool solveDeduplicated(\n      std::shared_ptr<BoxedLcpSolver>& solver,\n      const Eigen::MatrixXs& A,\n      Eigen::VectorXs& X,\n      const Eigen::VectorXs& b,\n      const Eigen::VectorXs& hi,\n      const Eigen::VectorXs& lo,\n      const Eigen::VectorXi& fIndex);\n\n  /// This will modify the LCP problem formulation to merge two columns\n  /// together, and rewrite and resize all the matrices appropriately. It will\n  /// also yell and scream (throw asserts) if the columns shouldn't be merged.\n  /// It'll also update the mapOut matrix, so that it's possible to simply\n  /// multiply mapOut*x on the reduced problem to get a valid solution to the\n  /// larger problem.\n  static void mergeLCPColumns(\n      int colA,\n      int colB,\n      Eigen::MatrixXs& A,\n      Eigen::VectorXs& X,\n      Eigen::VectorXs& b,\n      Eigen::VectorXs& hi,\n      Eigen::VectorXs& lo,\n      Eigen::VectorXi& fIndex,\n      Eigen::MatrixXs& mapOut);\n\n  /// This will modify the LCP problem formulation to drop a column\n  /// and rewrite and resize all the matrices appropriately.\n  /// It'll also update the mapOut matrix, so that it's possible to simply\n  /// multiply mapOut*x on the reduced problem to get a valid solution to the\n  /// larger problem.\n  static void dropLCPColumn(\n      int col,\n      Eigen::MatrixXs& A,\n      Eigen::VectorXs& X,\n      Eigen::VectorXs& b,\n      Eigen::VectorXs& hi,\n      Eigen::VectorXs& lo,\n      Eigen::VectorXi& fIndex,\n      Eigen::MatrixXs& mapOut);\n\n  /// Print replication code info\n  static void printReplicationCode(\n      Eigen::MatrixXs A,\n      Eigen::VectorXs x,\n      Eigen::VectorXs lo,\n      Eigen::VectorXs hi,\n      Eigen::VectorXs b,\n      Eigen::VectorXi fIndex);\n};\n\n} // namespace constraint\n} // namespace dart\n\n#endif", "meta": {"hexsha": "1cfe3ec97f4d1bdfc312ab6c2aef46487605d6bc", "size": 3904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dart/constraint/LCPUtils.hpp", "max_stars_repo_name": "jyf588/nimblephysics", "max_stars_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-30T06:23:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T09:59:09.000Z", "max_issues_repo_path": "dart/constraint/LCPUtils.hpp", "max_issues_repo_name": "jyf588/nimblephysics", "max_issues_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dart/constraint/LCPUtils.hpp", "max_forks_repo_name": "jyf588/nimblephysics", "max_forks_repo_head_hexsha": "6c09228f0abcf7aa3526a8dd65cd2541aff32c4a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:56:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T13:56:14.000Z", "avg_line_length": 33.3675213675, "max_line_length": 79, "alphanum_fraction": 0.6785348361, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22038093670468767}}
{"text": "#ifndef AMGCL_BACKEND_VEXCL_HPP\n#define AMGCL_BACKEND_VEXCL_HPP\n\n/*\nThe MIT License\n\nCopyright (c) 2012-2020 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n/**\n * \\file   amgcl/backend/vexcl.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief  VexCL backend.\n */\n\n#include <iostream>\n#include <memory>\n\n#include <boost/range/iterator_range.hpp>\n\n#include <amgcl/solver/skyline_lu.hpp>\n#include <vexcl/vector.hpp>\n#include <vexcl/gather.hpp>\n#include <vexcl/sparse/matrix.hpp>\n#include <vexcl/sparse/distributed.hpp>\n\n#include <amgcl/util.hpp>\n#include <amgcl/backend/builtin.hpp>\n\nnamespace amgcl {\n\nnamespace solver {\n\n/** Wrapper around solver::skyline_lu for use with the VexCL backend.\n * Copies the rhs to the host memory, solves the problem using the host CPU,\n * then copies the solution back to the compute device(s).\n */\ntemplate <class value_type>\nstruct vexcl_skyline_lu : solver::skyline_lu<value_type> {\n    typedef solver::skyline_lu<value_type> Base;\n    typedef typename math::rhs_of<value_type>::type rhs_type;\n\n    mutable std::vector<rhs_type> _rhs, _x;\n\n    template <class Matrix, class Params>\n    vexcl_skyline_lu(const Matrix &A, const Params&)\n        : Base(*A), _rhs(backend::rows(*A)), _x(backend::rows(*A))\n    { }\n\n    template <class Vec1, class Vec2>\n    void operator()(const Vec1 &rhs, Vec2 &x) const {\n        vex::copy(rhs, _rhs);\n        static_cast<const Base*>(this)->operator()(_rhs, _x);\n        vex::copy(_x, x);\n    }\n\n    size_t bytes() const {\n        return\n            backend::bytes(*static_cast<const Base*>(this)) +\n            backend::bytes(_rhs) +\n            backend::bytes(_x);\n    }\n};\n\n}\n\nnamespace backend {\n\n/// The VexCL backend parameters.\nstruct vexcl_params {\n\n    std::vector< vex::backend::command_queue > q; ///< Command queues that identify compute devices to use with VexCL.\n\n    /// Do CSR to ELL conversion on the GPU side.\n    /** This will result in faster setup, but will require more GPU memory. */\n    bool fast_matrix_setup;\n\n    vexcl_params() : fast_matrix_setup(true) {}\n\n#ifndef AMGCL_NO_BOOST\n    vexcl_params(const boost::property_tree::ptree &p)\n        : fast_matrix_setup(p.get(\"fast_matrix_setup\", vexcl_params().fast_matrix_setup))\n    {\n        std::vector<vex::backend::command_queue> *ptr = 0;\n        ptr = p.get(\"q\", ptr);\n        if (ptr) q = *ptr;\n        check_params(p, {\"q\", \"fast_matrix_setup\"});\n    }\n\n    void get(boost::property_tree::ptree &p, const std::string &path) const {\n        p.put(path + \"q\", &q);\n        p.put(path + \"fast_matrix_setup\", fast_matrix_setup);\n    }\n#endif\n\n    const std::vector<vex::backend::command_queue>& context() const {\n        if (q.empty())\n            return vex::current_context().queue();\n        else\n            return q;\n    }\n};\n\n\n/**\n * The backend uses the <a href=\"https://github.com/ddemidov/vexcl\">VexCL</a>\n * library for accelerating solution on the modern GPUs and multicore\n * processors with the help of OpenCL or CUDA technologies.\n * The VexCL backend stores the system matrix as ``vex::SpMat<real>`` and\n * expects the right hand side and the solution vectors to be instances of the\n * ``vex::vector<real>`` type.\n */\ntemplate <typename real, class DirectSolver = solver::vexcl_skyline_lu<real> >\nstruct vexcl {\n    typedef real      value_type;\n    typedef ptrdiff_t index_type;\n\n    typedef vex::sparse::distributed<\n                vex::sparse::matrix<value_type, index_type, index_type>\n                > matrix;\n    typedef typename math::rhs_of<value_type>::type rhs_type;\n    typedef vex::vector<rhs_type>                          vector;\n    typedef vex::vector<value_type>                        matrix_diagonal;\n    typedef DirectSolver                                   direct_solver;\n\n    struct provides_row_iterator : std::false_type {};\n\n    typedef vexcl_params params;\n\n    static std::string name() { return \"vexcl\"; }\n\n    // Copy matrix from builtin backend.\n    static std::shared_ptr<matrix>\n    copy_matrix(std::shared_ptr< typename builtin<real>::matrix > A, const params &prm)\n    {\n        precondition(!prm.context().empty(), \"Empty VexCL context!\");\n\n        const typename builtin<real>::matrix &a = *A;\n\n        const size_t n   = rows(*A);\n        const size_t m   = cols(*A);\n        const size_t nnz = a.ptr[n];\n\n        return std::make_shared<matrix>(prm.context(), n, m,\n                boost::make_iterator_range(a.ptr, a.ptr + n+1),\n                boost::make_iterator_range(a.col, a.col + nnz),\n                boost::make_iterator_range(a.val, a.val + nnz),\n                prm.fast_matrix_setup\n                );\n    }\n\n    // Copy vector from builtin backend.\n    template <class T>\n    static std::shared_ptr< vex::vector<T> >\n    copy_vector(const std::vector<T> &x, const params &prm)\n    {\n        precondition(!prm.context().empty(), \"Empty VexCL context!\");\n        return std::make_shared< vex::vector<T> >(prm.context(), x);\n    }\n\n    template <class T>\n    static std::shared_ptr< vex::vector<T> >\n    copy_vector(const numa_vector<T> &x, const params &prm)\n    {\n        precondition(!prm.context().empty(), \"Empty VexCL context!\");\n        return std::make_shared< vex::vector<T> >(prm.context(), x.size(), x.data());\n    }\n\n    // Copy vector from builtin backend.\n    template <class T>\n    static std::shared_ptr< vex::vector<T> >\n    copy_vector(std::shared_ptr< numa_vector<T> > x, const params &prm)\n    {\n        return copy_vector(*x, prm);\n    }\n\n    // Create vector of the specified size.\n    static std::shared_ptr<vector>\n    create_vector(size_t size, const params &prm)\n    {\n        precondition(!prm.context().empty(), \"Empty VexCL context!\");\n\n        return std::make_shared<vector>(prm.context(), size);\n    }\n\n    struct gather {\n        size_t n;\n        mutable vex::gather G;\n        mutable std::vector<char> buf;\n\n        gather(size_t src_size, const std::vector<ptrdiff_t> &I, const params &prm)\n            : n(I.size()), G(prm.context(), src_size, std::vector<size_t>(I.begin(), I.end()))\n        { }\n\n        template <class S, class D>\n        void operator()(const vex::vector<S> &src, vex::vector<D> &dst) const {\n            if (buf.size() < sizeof(D) * n) buf.resize(sizeof(D) * n);\n            auto t = reinterpret_cast<D*>(buf.data());\n            G(src, t);\n            vex::copy(t, t + n, dst.begin());\n        }\n\n        template <class S, class D>\n        void operator()(const vex::vector<S> &vec, std::vector<D> &vals) const {\n            G(vec, vals);\n        }\n    };\n\n    struct scatter {\n        size_t n;\n        mutable vex::scatter S;\n        mutable std::vector<char> buf;\n\n        scatter(size_t size, const std::vector<ptrdiff_t> &I, const params &prm)\n            : n(I.size()), S(prm.context(), size, std::vector<size_t>(I.begin(), I.end()))\n        { }\n\n        template <class S, class D>\n        void operator()(const vex::vector<S> &src, vex::vector<D> &dst) const {\n            if (buf.size() < sizeof(D) * n) buf.resize(sizeof(D) * n);\n            auto t = reinterpret_cast<D*>(buf.data());\n            vex::copy(src.begin(), src.end(), t);\n            S(t, dst);\n        }\n    };\n\n\n    // Create direct solver for coarse level\n    static std::shared_ptr<direct_solver>\n    create_solver(std::shared_ptr< typename builtin<real>::matrix > A, const params &prm)\n    {\n        return std::make_shared<direct_solver>(A, prm);\n    }\n};\n\n//---------------------------------------------------------------------------\n// Backend interface implementation\n//---------------------------------------------------------------------------\ntemplate <typename T1, typename T2>\nstruct backends_compatible< vexcl<T1>, vexcl<T2> > : std::true_type {};\n\ntemplate < typename V, typename C, typename P >\nstruct bytes_impl< vex::sparse::distributed<vex::sparse::matrix<V,C,P> > > {\n    static size_t get(const vex::sparse::distributed<vex::sparse::matrix<V,C,P> > &A) {\n        return\n            sizeof(P) * (A.rows() + 1) +\n            sizeof(C) * A.nonzeros() +\n            sizeof(V) * A.nonzeros();\n    }\n};\n\ntemplate < typename V >\nstruct bytes_impl< vex::vector<V> > {\n    static size_t get(const vex::vector<V> &v) {\n        return v.size() * sizeof(V);\n    }\n};\n\ntemplate < typename Alpha, typename Beta, typename Va, typename Vx, typename Vy, typename C, typename P >\nstruct spmv_impl<\n    Alpha, vex::sparse::distributed<vex::sparse::matrix<Va,C,P>>, vex::vector<Vx>,\n    Beta,  vex::vector<Vy>,\n    typename std::enable_if<\n        math::static_rows<Va>::value == 1 &&\n        math::static_rows<Vx>::value == 1 &&\n        math::static_rows<Vy>::value == 1\n        >::type\n    >\n{\n    typedef vex::sparse::distributed<vex::sparse::matrix<Va,C,P>> matrix;\n\n    static void apply(Alpha alpha, const matrix &A, const vex::vector<Vx> &x,\n            Beta beta, vex::vector<Vy> &y)\n    {\n        if (beta)\n            y = alpha * (A * x) + beta * y;\n        else\n            y = alpha * (A * x);\n    }\n};\n\ntemplate < typename Va, typename Vf, typename Vx, typename Vr, typename C, typename P >\nstruct residual_impl<\n    vex::sparse::distributed<vex::sparse::matrix<Va,C,P>>,\n    vex::vector<Vf>,\n    vex::vector<Vx>,\n    vex::vector<Vr>\n    >\n{\n    typedef vex::sparse::distributed<vex::sparse::matrix<Va,C,P>> matrix;\n\n    static void apply(const vex::vector<Vf> &rhs, const matrix &A, const vex::vector<Vx> &x,\n            vex::vector<Vr> &r)\n    {\n        r = rhs - A * x;\n    }\n};\n\ntemplate < typename V >\nstruct clear_impl< vex::vector<V> >\n{\n    static void apply(vex::vector<V> &x)\n    {\n        x = 0;\n    }\n};\n\ntemplate < class V, class T >\nstruct copy_impl<V, vex::vector<T> >\n{\n    static void apply(const V &x, vex::vector<T> &y)\n    {\n        vex::copy(x, y);\n    }\n};\n\ntemplate < class T, class V >\nstruct copy_impl<vex::vector<T>, V>\n{\n    static void apply(const vex::vector<T> &x, V &y)\n    {\n        vex::copy(x, y);\n    }\n};\n\ntemplate < class T1, class T2 >\nstruct copy_impl<vex::vector<T1>, vex::vector<T2>>\n{\n    static void apply(const vex::vector<T1> &x, vex::vector<T2> &y)\n    {\n        vex::copy(x, y);\n    }\n};\n\ntemplate < typename V >\nstruct inner_product_impl<\n    vex::vector<V>,\n    vex::vector<V>\n    >\n{\n    static V get(const vex::vector<V> &x, const vex::vector<V> &y)\n    {\n        vex::Reductor<V, vex::SUM_Kahan> sum( x.queue_list() );\n        return sum(x * y);\n    }\n};\n\ntemplate < typename A, typename B, typename V1, typename V2 >\nstruct axpby_impl<\n    A, vex::vector<V1>,\n    B, vex::vector<V2>\n    > {\n    static void apply(A a, const vex::vector<V1> &x, B b, vex::vector<V2> &y)\n    {\n        if (b)\n            y = a * x + b * y;\n        else\n            y = a * x;\n    }\n};\n\ntemplate < typename A, typename B, typename C, typename V1, typename V2, typename V3 >\nstruct axpbypcz_impl<\n    A, vex::vector<V1>,\n    B, vex::vector<V2>,\n    C, vex::vector<V3>\n    >\n{\n    static void apply(\n            A a, const vex::vector<V1> &x,\n            B b, const vex::vector<V2> &y,\n            C c,       vex::vector<V3> &z\n            )\n    {\n        if (c)\n            z = a * x + b * y + c * z;\n        else\n            z = a * x + b * y;\n    }\n};\n\ntemplate < typename A, typename B, typename Vx, typename Vy, typename Vz >\nstruct vmul_impl<\n    A, vex::vector<Vx>, vex::vector<Vy>,\n    B, vex::vector<Vz>\n    >\n{\n    static void apply(A a, const vex::vector<Vx> &x, const vex::vector<Vy> &y,\n            B b, vex::vector<Vz> &z)\n    {\n        if (b)\n            z = a * x * y + b * z;\n        else\n            z = a * x * y;\n    }\n};\n\ntemplate <class T, class V>\nstruct reinterpret_impl<T, vex::vector<V>>\n{\n    typedef vex::vector<typename std::decay<T>::type> return_type;\n\n    static return_type get(const vex::vector<V> &x) {\n        return x.template reinterpret<typename std::decay<T>::type>();\n    }\n};\n\n\n} // namespace backend\n} // namespace amgcl\n\n#endif\n", "meta": {"hexsha": "a8b333425db4c406fbbc4d85dd9f21034710ed94", "size": 12901, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external_libraries/amgcl/backend/vexcl.hpp", "max_stars_repo_name": "lkusch/Kratos", "max_stars_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 778.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T16:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:01:51.000Z", "max_issues_repo_path": "external_libraries/amgcl/backend/vexcl.hpp", "max_issues_repo_name": "lkusch/Kratos", "max_issues_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 6634.0, "max_issues_repo_issues_event_min_datetime": "2017-01-15T22:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:03:36.000Z", "max_forks_repo_path": "external_libraries/amgcl/backend/vexcl.hpp", "max_forks_repo_name": "lkusch/Kratos", "max_forks_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2017-02-07T14:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:09:34.000Z", "avg_line_length": 29.9327146172, "max_line_length": 118, "alphanum_fraction": 0.6018913263, "num_tokens": 3363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.22038093670468767}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_OCEA_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_OCEA_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 4.9.1\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace ocea\n    {\n\n            struct par_ocea\n            {\n                double    rok;\n                double    rtk;\n                double    sinphi;\n                double    cosphi;\n                double    singam;\n                double    cosgam;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_ocea_spheroid : public base_t_fi<base_ocea_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_ocea m_proj_parm;\n\n                inline base_ocea_spheroid(const Parameters& par)\n                    : base_t_fi<base_ocea_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    double t;\n\n                    xy_y = sin(lp_lon);\n                /*\n                    xy_x = atan2((tan(lp_lat) * this->m_proj_parm.cosphi + this->m_proj_parm.sinphi * xy_y) , cos(lp_lon));\n                */\n                    t = cos(lp_lon);\n                    xy_x = atan((tan(lp_lat) * this->m_proj_parm.cosphi + this->m_proj_parm.sinphi * xy_y) / t);\n                    if (t < 0.)\n                        xy_x += geometry::math::pi<double>();\n                    xy_x *= this->m_proj_parm.rtk;\n                    xy_y = this->m_proj_parm.rok * (this->m_proj_parm.sinphi * sin(lp_lat) - this->m_proj_parm.cosphi * cos(lp_lat) * xy_y);\n                }\n\n                // INVERSE(s_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    double t, s;\n\n                    xy_y /= this->m_proj_parm.rok;\n                    xy_x /= this->m_proj_parm.rtk;\n                    t = sqrt(1. - xy_y * xy_y);\n                    lp_lat = asin(xy_y * this->m_proj_parm.sinphi + t * this->m_proj_parm.cosphi * (s = sin(xy_x)));\n                    lp_lon = atan2(t * this->m_proj_parm.sinphi * s - xy_y * this->m_proj_parm.cosphi,\n                        t * cos(xy_x));\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"ocea_spheroid\";\n                }\n\n            };\n\n            // Oblique Cylindrical Equal Area\n            template <typename Parameters>\n            void setup_ocea(Parameters& par, par_ocea& proj_parm)\n            {\n                double phi_0=0.0, phi_1, phi_2, lam_1, lam_2, lonz, alpha;\n\n                proj_parm.rok = par.a / par.k0;\n                proj_parm.rtk = par.a * par.k0;\n                if ( pj_param(par.params, \"talpha\").i) {\n                    alpha    = pj_param(par.params, \"ralpha\").f;\n                    lonz = pj_param(par.params, \"rlonc\").f;\n                    proj_parm.singam = atan(-cos(alpha)/(-sin(phi_0) * sin(alpha))) + lonz;\n                    proj_parm.sinphi = asin(cos(phi_0) * sin(alpha));\n                } else {\n                    phi_1 = pj_param(par.params, \"rlat_1\").f;\n                    phi_2 = pj_param(par.params, \"rlat_2\").f;\n                    lam_1 = pj_param(par.params, \"rlon_1\").f;\n                    lam_2 = pj_param(par.params, \"rlon_2\").f;\n                    proj_parm.singam = atan2(cos(phi_1) * sin(phi_2) * cos(lam_1) -\n                        sin(phi_1) * cos(phi_2) * cos(lam_2),\n                        sin(phi_1) * cos(phi_2) * sin(lam_2) -\n                        cos(phi_1) * sin(phi_2) * sin(lam_1) );\n                    proj_parm.sinphi = atan(-cos(proj_parm.singam - lam_1) / tan(phi_1));\n                }\n                par.lam0 = proj_parm.singam + geometry::math::half_pi<double>();\n                proj_parm.cosphi = cos(proj_parm.sinphi);\n                proj_parm.sinphi = sin(proj_parm.sinphi);\n                proj_parm.cosgam = cos(proj_parm.singam);\n                proj_parm.singam = sin(proj_parm.singam);\n                par.es = 0.;\n            }\n\n        }} // namespace detail::ocea\n    #endif // doxygen\n\n    /*!\n        \\brief Oblique Cylindrical Equal Area projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Cylindrical\n         - Spheroid\n        \\par Projection parameters\n         - lonc: Longitude (only used if alpha (or gamma) is specified) (degrees)\n         - alpha: Alpha (degrees)\n         - lat_1: Latitude of first standard parallel (degrees)\n         - lat_2: Latitude of second standard parallel (degrees)\n         - lon_1 (degrees)\n         - lon_2 (degrees)\n        \\par Example\n        \\image html ex_ocea.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct ocea_spheroid : public detail::ocea::base_ocea_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline ocea_spheroid(const Parameters& par) : detail::ocea::base_ocea_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::ocea::setup_ocea(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Factory entry(s)\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class ocea_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<ocea_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void ocea_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"ocea\", new ocea_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_OCEA_HPP\n\n", "meta": {"hexsha": "67f21ef857e22a89d1cb78b8d32fe7bb5b109317", "size": 9021, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/ocea.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T05:02:05.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/ocea.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/ocea.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-04T10:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T18:52:06.000Z", "avg_line_length": 43.3701923077, "max_line_length": 140, "alphanum_fraction": 0.601263718, "num_tokens": 2061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6513548646660543, "lm_q2_score": 0.3380771174808128, "lm_q1q2_score": 0.22020817510340457}}
{"text": "#include <boost/pending/disjoint_sets.hpp>\n#include <opencv2/highgui/highgui.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n\n#include <algorithm>\n#include <cfloat>\n#include <cmath>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iterator>\n#include <map>\n#include <numeric>\n#include <queue>\n#include <utility>\n#include <vector>\n\n#include \"caffe/layer.hpp\"\n#include \"caffe/layer_factory.hpp\"\n#include \"caffe/layers/malis_loss_layer.hpp\"\n#include \"caffe/util/math_functions.hpp\"\n\n\nnamespace caffe {\n\ntemplate<class Dtype>\nclass MalisAffinityGraphCompare {\n private:\n  const Dtype * mEdgeWeightArray;\n public:\n  explicit MalisAffinityGraphCompare(const Dtype * EdgeWeightArray) {\n    mEdgeWeightArray = EdgeWeightArray;\n  }\n  bool operator()(const uint64_t& ind1, const uint64_t& ind2) const {\n    return (mEdgeWeightArray[ind1] > mEdgeWeightArray[ind2]);\n  }\n};\n\n// Derived from https://github.com/srinituraga/malis/blob/master/matlab/malis_loss_mex.cpp\ntemplate<typename Dtype, typename MItype, typename MOtype>\nvoid MalisLossLayer<Dtype, MItype, MOtype>::Malis(const Dtype* conn_data,\n                                  const int_tp conn_num_dims,\n                                  const int_tp* conn_dims,\n                                  const int_tp* nhood_data,\n                                  const int_tp* nhood_dims,\n                                  const Dtype* seg_data, const bool pos,\n                                  Dtype* dloss_data, Dtype* loss_out,\n                                  Dtype *classerr_out, Dtype *rand_index_out) {\n  if ((nhood_dims[1] != (conn_num_dims - 1))\n      || (nhood_dims[0] != conn_dims[0])) {\n    LOG(FATAL) << \"nhood and conn dimensions don't match\"\n        << \" (\" << nhood_dims[1] << \" vs. \" << (conn_num_dims - 1)\n        << \" and \" << nhood_dims[0] << \" vs. \"\n        << conn_dims[conn_num_dims - 1] <<\")\";\n  }\n\n  /* Cache for speed to access neighbors */\n  // nVert stores (X * Y * z)\n  uint64_t nVert = 1;\n  for (uint64_t i = 1; i < conn_num_dims; ++i) {\n    nVert *= conn_dims[i];\n    // std::cout << i << \" nVert: \" << nVert << std::endl;\n  }\n\n  // prodDims stores X, X*Y, X*Y*z offsets\n  vector<uint64_t> prodDims(conn_num_dims - 1);\n  prodDims[conn_num_dims - 2] = 1;\n  for (uint64_t i = 1; i < conn_num_dims - 1; ++i) {\n    prodDims[conn_num_dims - 2 - i] = prodDims[conn_num_dims - 1 - i]\n                                      * conn_dims[conn_num_dims - i];\n    // std::cout << conn_num_dims - 2 - i << \" dims: \"\n    //   << prodDims[conn_num_dims - 2 - i] << std::endl;\n  }\n\n  /* convert n-d offset vectors into linear array offset scalars */\n  // nHood is a vector of size #edges\n\n  vector<uint32_t> nHood(nhood_dims[0]);\n  for (uint64_t i = 0; i < nhood_dims[0]; ++i) {\n    nHood[i] = 0;\n    for (uint64_t j = 0; j < nhood_dims[1]; ++j) {\n      nHood[i] += (uint32_t) nhood_data[j + i * nhood_dims[1]] * prodDims[j];\n    }\n    // std::cout << i << \" nHood: \" << nHood[i] << std::endl;\n  }\n\n  /* Disjoint sets and sparse overlap vectors */\n  vector<std::map<uint64_t, uint64_t> > overlap(nVert);\n  vector<uint64_t> rank(nVert);\n  vector<uint64_t> parent(nVert);\n  std::map<uint64_t, uint64_t> segSizes;\n  uint64_t nLabeledVert = 0;\n  uint64_t nPairPos = 0;\n  boost::disjoint_sets<uint64_t*, uint64_t*> dsets(&rank[0], &parent[0]);\n  // Loop over all seg data items\n  for (uint64_t i = 0; i < nVert; ++i) {\n    dsets.make_set(i);\n    if (0 != seg_data[i]) {\n      overlap[i].insert(std::pair<uint64_t, uint64_t>(seg_data[i], 1));\n      ++nLabeledVert;\n      ++segSizes[seg_data[i]];\n      nPairPos += (segSizes[seg_data[i]] - 1);\n    }\n  }\n\n  uint64_t nPairTot = (nLabeledVert * (nLabeledVert - 1)) / 2;\n  uint64_t nPairNeg = nPairTot - nPairPos;\n  uint64_t nPairNorm;\n\n  if (pos) {\n    nPairNorm = nPairPos;\n  } else {\n    nPairNorm = nPairNeg;\n  }\n\n  uint64_t edgeCount = 0;\n  // Loop over #edges\n  for (uint64_t d = 0, i = 0; d < conn_dims[0]; ++d) {\n    // Loop over Z\n    for (uint64_t z = 0; z < conn_dims[1]; ++z) {\n      // Loop over Y\n      for (uint64_t Y = 0; Y < conn_dims[2]; ++Y) {\n        // Loop over X\n        for (uint64_t X = 0; X < conn_dims[3]; ++X, ++i) {\n          // Out-of-bounds check:\n          if (!((z + nhood_data[d * nhood_dims[1] + 0] < 0)\n              ||(z + nhood_data[d * nhood_dims[1] + 0] >= conn_dims[1])\n              ||(Y + nhood_data[d * nhood_dims[1] + 1] < 0)\n              ||(Y + nhood_data[d * nhood_dims[1] + 1] >= conn_dims[2])\n              ||(X + nhood_data[d * nhood_dims[1] + 2] < 0)\n              ||(X + nhood_data[d * nhood_dims[1] + 2] >= conn_dims[3]))) {\n            ++edgeCount;\n          }\n        }\n      }\n    }\n  }\n\n  /* Sort all the edges in increasing order of weight */\n  vector<uint64_t> pqueue(edgeCount);\n  uint64_t j = 0;\n  // Loop over #edges\n  for (uint64_t d = 0, i = 0; d < conn_dims[0]; ++d) {\n    // Loop over Z\n    for (uint64_t z = 0; z < conn_dims[1]; ++z) {\n      // Loop over Y\n      for (uint64_t Y = 0; Y < conn_dims[2]; ++Y) {\n        // Loop over X\n        for (uint64_t X = 0; X < conn_dims[3]; ++X, ++i) {\n          // Out-of-bounds check:\n          if (!((z + nhood_data[d * nhood_dims[1] + 0] < 0)\n              ||(z + nhood_data[d * nhood_dims[1] + 0] >= conn_dims[1])\n              ||(Y + nhood_data[d * nhood_dims[1] + 1] < 0)\n              ||(Y + nhood_data[d * nhood_dims[1] + 1] >= conn_dims[2])\n              ||(X + nhood_data[d * nhood_dims[1] + 2] < 0)\n              ||(X + nhood_data[d * nhood_dims[1] + 2] >= conn_dims[3]))) {\n            pqueue[j++] = i;\n          }\n        }\n      }\n    }\n  }\n\n  pqueue.resize(j);\n\n  std::sort(pqueue.begin(), pqueue.end(),\n       MalisAffinityGraphCompare<Dtype>(conn_data));\n\n  /* Start MST */\n  uint64_t minEdge;\n  uint64_t e, v1, v2;\n  uint64_t set1, set2;\n  uint64_t nPair = 0;\n  double loss = 0, dl = 0;\n  uint64_t nPairIncorrect = 0;\n  std::map<uint64_t, uint64_t>::iterator it1, it2;\n\n  /* Start Kruskal's */\n  for (uint64_t i = 0; i < pqueue.size(); ++i) {\n    minEdge = pqueue[i];\n    // nVert = X * Y * z, minEdge in [0, X * Y * z * #edges]\n\n    // e: edge dimension\n    e = minEdge / nVert;\n\n    // v1: node at edge beginning\n    v1 = minEdge % nVert;\n\n    // v2: neighborhood node at edge e\n    v2 = v1 + nHood[e];\n\n    // std::cout << \"V1: \" << v1 << \", V2: \" << v2 << std::endl;\n\n    set1 = dsets.find_set(v1);\n    set2 = dsets.find_set(v2);\n\n\n    if (set1 != set2) {\n      dsets.link(set1, set2);\n\n      /* compute the dloss for this MST edge */\n      for (it1 = overlap[set1].begin(); it1 != overlap[set1].end(); ++it1) {\n        for (it2 = overlap[set2].begin(); it2 != overlap[set2].end(); ++it2) {\n          nPair = it1->second * it2->second;\n\n          if (pos && (it1->first == it2->first)) {\n            // +ve example pairs\n            dl = (Dtype(1.0) - conn_data[minEdge]);\n            loss += dl * dl * nPair;\n            // Use hinge loss\n            dloss_data[minEdge] += dl * nPair;\n            if (conn_data[minEdge] <= Dtype(0.5)) {  // an error\n              nPairIncorrect += nPair;\n            }\n\n          } else if ((!pos) && (it1->first != it2->first)) {\n            // -ve example pairs\n            dl = (-conn_data[minEdge]);\n            loss += dl * dl * nPair;\n            // Use hinge loss\n            dloss_data[minEdge] += dl * nPair;\n            if (conn_data[minEdge] > Dtype(0.5)) {  // an error\n              nPairIncorrect += nPair;\n            }\n          }\n        }\n      }\n\n      if (nPairNorm > 0) {\n        dloss_data[minEdge] /= nPairNorm;\n      } else {\n        dloss_data[minEdge] = 0;\n      }\n\n      if (dsets.find_set(set1) == set2) {\n        std::swap(set1, set2);\n      }\n\n      for (it2 = overlap[set2].begin();\n          it2 != overlap[set2].end(); ++it2) {\n        it1 = overlap[set1].find(it2->first);\n        if (it1 == overlap[set1].end()) {\n          overlap[set1].insert(pair<uint64_t, uint64_t>\n            (it2->first, it2->second));\n        } else {\n          it1->second += it2->second;\n        }\n      }\n      overlap[set2].clear();\n    }  // end link\n  }  // end while\n\n  /* Return items */\n  double classerr, randIndex;\n  if (nPairNorm > 0) {\n    loss /= nPairNorm;\n  } else {\n    loss = 0;\n  }\n\n  // std::cout << \"nPairIncorrect: \" << nPairIncorrect << std::endl;\n  // std::cout << \"nPairNorm: \" << nPairNorm << std::endl;\n\n  *loss_out = loss;\n  classerr = static_cast<double>(nPairIncorrect)\n      / static_cast<double>(nPairNorm);\n  *classerr_out = classerr;\n  randIndex = 1.0 - static_cast<double>(nPairIncorrect)\n      / static_cast<double>(nPairNorm);\n  *rand_index_out = randIndex;\n}\n\n\ntemplate<typename Dtype, typename MItype, typename MOtype>\nvoid MalisLossLayer<Dtype, MItype, MOtype>::LayerSetUp(\n    const vector<Blob<MItype>*>& bottom, const vector<Blob<MOtype>*>& top) {\n  LossLayer<Dtype, MItype, MOtype>::LayerSetUp(bottom, top);\n\n  // Expected inputs:\n  // Required (bottom 0 to 2):\n  // Bottom 0: Predicted affinity, shaped     (batch size, #edges, (Z), (Y), X)\n  // Bottom 1: Ground truth affinity, shaped  (batch size, #edges, (Z), (Y), X)\n  // Bottom 2: Segmented ground truth, shaped (batch size, 1,      (Z), (Y), X)\n\n  // Optional (bottom 3):\n  // Bottom 3: Edge connectivity, size #edges * 3, shaped (Z,Y,X);(Z,Y,X);...\n  // (this means pairs of 3 per edge)\n}\n\ntemplate<typename Dtype, typename MItype, typename MOtype>\nvoid MalisLossLayer<Dtype, MItype, MOtype>::Reshape(\n    const vector<Blob<MItype>*>& bottom, const vector<Blob<MOtype>*>& top) {\n  LossLayer<Dtype, MItype, MOtype>::Reshape(bottom, top);\n\n  if (top.size() >= 2) {\n    top[1]->ReshapeLike(*bottom[0]);\n  }\n\n  // Up to 5 dimensional; supported modes:\n  // batch, channels (edges), Z, Y, X    => 3D affinity\n  // batch, channels (edges), Y, X       => 2D affinity\n  // batch, channels (edges), X          => 1D affinity\n  vector<int_tp> shape = bottom[0]->shape();\n\n  conn_dims_.clear();\n  nhood_dims_.clear();\n\n  // #edges, Z, Y, X specification (4 dimensions)\n  conn_num_dims_ = 4;\n\n  // Channel axis equals number of edges\n  nedges_ = shape[1];\n\n  // #edges\n  conn_dims_.push_back(nedges_);\n  // Z-axis\n  conn_dims_.push_back(shape.size() >= 5 ? shape[shape.size() - 3] : 1);\n  // Y-axis\n  conn_dims_.push_back(shape.size() >= 4 ? shape[shape.size() - 2] : 1);\n  // X-axis\n  conn_dims_.push_back(shape.size() >= 3 ? shape[shape.size() - 1] : 1);\n\n  // #edges\n  nhood_dims_.push_back(nedges_);\n  // 3 dimensional (always, to simplify things;\n  // can just set unused spatials to 0)\n  nhood_dims_.push_back(3);\n\n  affinity_pos_.Reshape(shape);\n  affinity_neg_.Reshape(shape);\n  dloss_pos_.Reshape(shape);\n  dloss_neg_.Reshape(shape);\n}\n\ntemplate<typename Dtype, typename MItype, typename MOtype>\nvoid MalisLossLayer<Dtype, MItype, MOtype>::Forward_cpu(const vector<Blob<MItype>*>& bottom,\n                                        const vector<Blob<MOtype>*>& top) {\n  // Set up the neighborhood\n  nhood_data_.clear();\n  if (bottom.size() == 4) {\n    // Custom edges\n    for (int_tp i = 0; i < nedges_; ++i) {\n      // Z edge direction\n      nhood_data_.push_back(bottom[3]->cpu_data()[i * 3 + 0]);\n      // Y edge direction\n      nhood_data_.push_back(bottom[3]->cpu_data()[i * 3 + 1]);\n      // X edge direction\n      nhood_data_.push_back(bottom[3]->cpu_data()[i * 3 + 2]);\n    }\n  } else {\n    // Dimension primary edges (+Z, +Y, +X) only:\n    // 1 edge:    +X          (0,0,1)\n    // 2 edges:   +Y, +X      (0,1,0); (0,0,1)\n    // 3 edges:   +Z, +Y, +X  (1,0,0); (0,1,0); (0,0,1)\n    for (int_tp i = 3 - nedges_; i < 3; ++i) {\n      nhood_data_.push_back((i + 3) % 3 == 0 ? 1 : 0);\n      nhood_data_.push_back((i + 2) % 3 == 0 ? 1 : 0);\n      nhood_data_.push_back((i + 1) % 3 == 0 ? 1 : 0);\n    }\n  }\n\n  // Predicted affinity\n  const Dtype* affinity_prob = bottom[0]->cpu_data();\n\n  // Effective affinity\n  const Dtype* affinity = bottom[1]->cpu_data();\n\n  Dtype* affinity_data_pos = affinity_pos_.mutable_cpu_data();\n  Dtype* affinity_data_neg = affinity_neg_.mutable_cpu_data();\n\n// Affinity graph must be in the range (0,1)\n// square loss (euclidean) is used by MALIS\n  for (int_tp i = 0; i < bottom[0]->count(); ++i) {\n    affinity_data_pos[i] = std::min(affinity_prob[i], affinity[i]);\n    affinity_data_neg[i] = std::max(affinity_prob[i], affinity[i]);\n  }\n\n  uint_tp batch_offset = 1;\n  for (int_tp i = 1; i < bottom[0]->shape().size(); ++i) {\n    batch_offset *= bottom[0]->shape()[i];\n  }\n\n  uint_tp components_batch_offset = 1;\n  uint_tp components_channel_offset = bottom[2]->shape()[1] == 2 ? 1 : 0;\n  for (int_tp i = 1; i < bottom[2]->shape().size(); ++i) {\n    components_batch_offset *= bottom[2]->shape()[i];\n    if (i > 1) {\n      components_channel_offset *= bottom[2]->shape()[i];\n    }\n  }\n\n  float loss = 0;\n\n#pragma omp parallel for reduction(+:loss)\n  for (int_tp batch = 0; batch < bottom[0]->shape()[0]; ++batch) {\n    Dtype loss_out = 0;\n    Dtype classerr_out = 0;\n    Dtype rand_index_out = 0;\n\n    caffe_set(dloss_neg_.count(), Dtype(0.0), dloss_neg_.mutable_cpu_data());\n    caffe_set(dloss_pos_.count(), Dtype(0.0), dloss_pos_.mutable_cpu_data());\n\n    Malis(&affinity_data_neg[batch_offset * batch], conn_num_dims_,\n          &conn_dims_[0], &nhood_data_[0], &nhood_dims_[0],\n          bottom[2]->cpu_data() + components_batch_offset * batch, false,\n          dloss_neg_.mutable_cpu_data() + batch_offset * batch, &loss_out,\n          &classerr_out, &rand_index_out);\n\n    loss += 0.5 * loss_out;\n    // std::cout << \"NEG: \" << loss_out << std::endl;\n\n    Malis(&affinity_data_pos[batch_offset * batch], conn_num_dims_,\n          &conn_dims_[0], &nhood_data_[0], &nhood_dims_[0],\n          bottom[2]->cpu_data() + components_batch_offset * batch\n          + components_channel_offset, true,\n          dloss_pos_.mutable_cpu_data() + batch_offset * batch, &loss_out,\n          &classerr_out, &rand_index_out);\n\n    loss += 0.5 * loss_out;\n    // std::cout << \"POS: \" << loss_out << std::endl;\n  }\n\n  // Normalized loss over batch size\n  top[0]->mutable_cpu_data()[0] = loss\n      / (static_cast<Dtype>(bottom[0]->shape()[0]));\n\n  if (top.size() == 2) {\n    top[1]->ShareData(*(bottom[0]));\n  }\n}\n\ntemplate<typename Dtype, typename MItype, typename MOtype>\nvoid MalisLossLayer<Dtype, MItype, MOtype>::Backward_cpu(const vector<Blob<MOtype>*>& top,\n                                         const vector<bool>& propagate_down,\n                                         const vector<Blob<MItype>*>& bottom) {\n  if (propagate_down[0]) {\n    Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();\n    const Dtype* dloss_pos_data = dloss_pos_.cpu_data();\n    const Dtype* dloss_neg_data = dloss_neg_.cpu_data();\n\n    // Clear the diff\n    caffe_set(bottom[0]->count(), Dtype(0.0), bottom_diff);\n\n    for (int_tp i = 0; i < bottom[0]->count(); ++i) {\n      bottom_diff[i] = -(dloss_neg_data[i] + dloss_pos_data[i]) / 2.0;\n    }\n  }\n}\n\nINSTANTIATE_CLASS_3T_GUARDED(MalisLossLayer, (half_fp), (half_fp), (half_fp));\nINSTANTIATE_CLASS_3T_GUARDED(MalisLossLayer, (float), (float), (float));\nINSTANTIATE_CLASS_3T_GUARDED(MalisLossLayer, (double), (double), (double));\n\nREGISTER_LAYER_CLASS(MalisLoss);\nREGISTER_LAYER_CLASS_INST(MalisLoss, (half_fp), (half_fp), (half_fp));\nREGISTER_LAYER_CLASS_INST(MalisLoss, (float), (float), (float));\nREGISTER_LAYER_CLASS_INST(MalisLoss, (double), (double), (double));\n\n}  // namespace caffe\n", "meta": {"hexsha": "17b4d8040e6446ee9c2eb65fe3a5fd31bab68b39", "size": 15332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/caffe/layers/malis_loss_layer.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/layers/malis_loss_layer.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/layers/malis_loss_layer.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": 33.3304347826, "max_line_length": 92, "alphanum_fraction": 0.5806157057, "num_tokens": 4803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.22017141650390945}}
{"text": "/*\n * cuConebeamProjectionOperator.cpp\n *\n *  Created on: Feb 18, 2015\n *      Author: u051747\n */\n\n#include \"cuConebeamProjectionOperator.h\"\n#include \"conebeam_projection.h\"\n#include <boost/math/constants/constants.hpp>\n#include \"hoNDArray_math.h\"\nusing boost::math::constants::pi;\nnamespace Gadgetron {\n\ncuConebeamProjectionOperator::cuConebeamProjectionOperator() {\n\t// TODO Auto-generated constructor stub\n\n\tsamples_per_pixel_ = 1.5f;\n\tallow_offset_correction_override_=true;\n\n}\nvoid cuConebeamProjectionOperator\n::offset_correct(cuNDArray<float>* projections){\n\n\tif( !preprocessed_ ){\n\t\tthrow std::runtime_error( \"Error: cuConebeamProjectionOperator::offset_correct: setup not performed\");\n\t}\n\tfloat SDD = acquisition_->get_geometry()->get_SDD();\n\tfloat SAD = acquisition_->get_geometry()->get_SAD();\n\tfloatd2 ps_dims_in_mm = acquisition_->get_geometry()->get_FOV();\n\tapply_offset_correct( projections,acquisition_->get_geometry()->get_offsets(),ps_dims_in_mm, SDD, SAD);\n}\n\ncuConebeamProjectionOperator::~cuConebeamProjectionOperator() {\n\t// TODO Auto-generated destructor stub\n}\n\nvoid cuConebeamProjectionOperator::mult_M(cuNDArray<float>* input,\n\t\tcuNDArray<float>* output, bool accumulate) {\n\n\tauto dims = *input->get_dimensions();\n\tstd::vector<size_t> dims3d(dims);\n\n\tif (dims3d.size() ==4) dims3d.pop_back();\n\tauto outdims = *output->get_dimensions();\n\tstd::vector<size_t> outbindims(outdims);\n\tfloat* input_ptr = input->get_data_ptr();\n\tfloat* output_ptr = output->get_data_ptr();\n\tfor (int bin = 0; bin < binning_->get_number_of_bins(); bin++){\n\t\t//Check for empty bins\n\t\tif (binning_->get_bin(bin).size() == 0)\n\t\t\tcontinue;\n\t\tcuNDArray<float> input_view(dims3d,input_ptr);\n\t\toutbindims.back() = angles[bin].size();\n\t\tauto  output_view = boost::make_shared<cuNDArray<float>>(outbindims,output_ptr);\n\t\tauto output_view2 = output_view;\n\t\t/*\n\t\tif (use_offset_correction_ && accumulate){\n\t\t\toutput_view2 = boost::make_shared<cuNDArray<float>>(outbindims);\n\t\t\tclear(output_view2.get());\n\t\t}\n\t\t */\n\n\t\tconebeam_forwards_projection(output_view2.get(),&input_view,angles[bin],offsets[bin],samples_per_pixel_,is_dims_in_mm_,acquisition_->get_geometry()->get_FOV(),acquisition_->get_geometry()->get_SDD(),acquisition_->get_geometry()->get_SAD(),accumulate);\n\n\t\t/*\n\t\tif (use_offset_correction_){\n\t\t\tapply_offset_correct(output_view2.get(),offsets[bin],acquisition_->get_geometry()->get_FOV(),acquisition_->get_geometry()->get_SDD(),acquisition_->get_geometry()->get_SAD());\n\t\t\tif (accumulate)\n\t\t\t\t*output_view += *output_view2;\n\t\t}\n\t\t */\n\n\t\tinput_ptr += input_view.get_number_of_elements();\n\t\toutput_ptr += output_view->get_number_of_elements();\n\n\n\t}\n\n}\n\nvoid cuConebeamProjectionOperator::mult_MH(cuNDArray<float>* input,\n\t\tcuNDArray<float>* output, bool accumulate) {\n\tauto dims = *output->get_dimensions();\n\tstd::vector<size_t> dims3d = dims;\n\tif (dims3d.size() ==4) dims3d.pop_back();\n\n\tauto indims = *input->get_dimensions();\n\tstd::vector<size_t> inbindims(indims);\n\tfloat* input_ptr = input->get_data_ptr();\n\tfloat* output_ptr = output->get_data_ptr();\n\tfor (int bin = 0; bin < binning_->get_number_of_bins(); bin++){\n\t\t//Check for empty bins\n\t\tif (binning_->get_bin(bin).size() == 0)\n\t\t\tcontinue;\n\n\t\tcuNDArray<float> output_view(dims3d,output_ptr);\n\t\tinbindims.back() = angles[bin].size();\n\t\tauto input_view = boost::make_shared<cuNDArray<float>>(inbindims,input_ptr);\n\t\tauto input_view2 = input_view;\n\t\tif(use_offset_correction_)\n\t\t\tinput_view2 = boost::make_shared<cuNDArray<float>>(*input_view);\n\n\t\tvector_td<int,3> is_dims_in_pixels{dims3d[0], dims3d[1],dims3d[2]};\n\n\t\tconebeam_backwards_projection(input_view2.get(),&output_view, angles[bin],offsets[bin],is_dims_in_pixels, is_dims_in_mm_,acquisition_->get_geometry()->get_FOV(),acquisition_->get_geometry()->get_SDD(),acquisition_->get_geometry()->get_SAD(),use_offset_correction_,accumulate);\n\n\t\tinput_ptr += input_view->get_number_of_elements();\n\t\toutput_ptr += output_view.get_number_of_elements();\n\n\t}\n\n\tif (mask)\n\t\tapply_mask(output,mask.get());\n\n}\n\nboost::shared_ptr<cuNDArray<bool>> cuConebeamProjectionOperator::calculate_mask( cuNDArray<float>* projections,float limit)\n{\n\tauto dims = *this->get_domain_dimensions();\n\tstd::vector<size_t> dims3d(dims.begin(),dims.end()-1);\n\tauto indims = *projections->get_dimensions();\n\tstd::vector<size_t> inbindims(indims);\n\tfloat* input_ptr = projections->get_data_ptr();\n\tauto mask = boost::make_shared<cuNDArray<bool>>(dims);\n\tbool* mask_ptr = mask->get_data_ptr();\n\tfor (int bin = 0; bin < binning_->get_number_of_bins(); bin++){\n\t\t//Check for empty bins\n\t\tif (binning_->get_bin(bin).size() == 0)\n\t\t\tcontinue;\n\n\t\tcuNDArray<bool> mask_view(dims3d,mask_ptr);\n\t\tinbindims.back() = angles[bin].size();\n\t\tauto input_view = boost::make_shared<cuNDArray<float>>(inbindims,input_ptr);\n\n\t\tvector_td<int,3> is_dims_in_pixels{dims3d[0], dims3d[1],dims3d[2]};\n\n\t\tconebeam_spacecarver(input_view.get(),&mask_view, angles[bin],offsets[bin],is_dims_in_pixels, is_dims_in_mm_,acquisition_->get_geometry()->get_FOV(),acquisition_->get_geometry()->get_SDD(),acquisition_->get_geometry()->get_SAD(),limit);\n\n\t\tinput_ptr += input_view->get_number_of_elements();\n\t\tmask_ptr += mask_view.get_number_of_elements();\n\n\t}\n\n\treturn mask;\n\n}\nvoid Gadgetron::cuConebeamProjectionOperator::setup( boost::shared_ptr<CBCT_acquisition> acquisition,\n\t\tfloatd3 is_dims_in_mm, bool transform_angles )\n{\n\tacquisition_ = acquisition;\n\tis_dims_in_mm_ = is_dims_in_mm;\n\n\t// Determine the minimum and maximum angles scanned and transform array angles from [0;max_angle_].\n\t//\n\n\tstd::vector<float> &all_angles = acquisition->get_geometry()->get_angles();\n\tif (transform_angles){\n\t\tfloat min_value = *std::min_element(all_angles.begin(), all_angles.end() );\n\t\ttransform(all_angles.begin(), all_angles.end(), all_angles.begin(), bind2nd(std::minus<float>(), min_value));\n\t}\n\t// Are we in a short scan setup?\n\t// - we say yes if we have covered less than PI+3*delta radians\n\t//\n\n\tfloat angle_span = *std::max_element(all_angles.begin(), all_angles.end() );\n\tfloatd2 ps_dims_in_mm = acquisition_->get_geometry()->get_FOV();\n\tfloat SDD = acquisition_->get_geometry()->get_SDD();\n\tfloat delta = std::atan(ps_dims_in_mm[0]/(2.0f*SDD)); // Fan angle\n\n\tif( angle_span*pi<float>()/180.0f > pi<float>()+3.0f*delta )\n\t\tshort_scan_ = false;\n\telse\n\t\tshort_scan_ = true;\n\n\tstd::vector<floatd2> all_offsets = acquisition_->get_geometry()->get_offsets();\n\tfloatd2 mean_offset = std::accumulate(all_offsets.begin(),all_offsets.end(),floatd2(0,0))/float(all_offsets.size());\n\tif( allow_offset_correction_override_ && std::abs(mean_offset[0]) > ps_dims_in_mm[0]*0.1f )\n\t\tuse_offset_correction_ = true;\n\n\tstd::cout << \"Mean offset \" << mean_offset << \" Use offset correct: \" << (use_offset_correction_ ? \"true\" : \"false\") << std::endl;\n\tpreprocessed_ = true;\n\tif (!binning_){\n\t\tstd::vector<unsigned int> bins(angles.size());\n\t\tstd::iota(bins.begin(),bins.end(),0);\n\t\tbinning_ = boost::make_shared<CBCT_binning>(std::vector<std::vector<unsigned int>>(1,bins));\n\t}\n\n\tangles = std::vector<std::vector<float>>();\n\toffsets = std::vector<std::vector<floatd2>>();\n\tfor (int bin =0; bin < binning_->get_number_of_bins(); bin++){\n\t\tauto binvec = binning_->get_bin(bin);\n\t\tangles.push_back(std::vector<float>());\n\t\toffsets.push_back(std::vector<floatd2>());\n\t\tfor (auto index : binvec){\n\t\t\tangles.back().push_back(all_angles[index]);\n\t\t\toffsets.back().push_back(all_offsets[index]);\n\t\t}\n\n\t}\n\tauto permutations = new_order(binning_->get_bins());\n\tauto proj = acquisition->get_projections();\n\tif (proj)\n\t\t*proj =\t*permute_projections(proj,permutations);\n\n}\n\nvoid Gadgetron::cuConebeamProjectionOperator::setup( boost::shared_ptr<CBCT_acquisition> acquisition,\n\t\tboost::shared_ptr<CBCT_binning> binning,floatd3 is_dims_in_mm, \t\tbool transform_angles)\n\n{\n\n\tbinning_ = binning;\n\tsetup( acquisition, is_dims_in_mm,transform_angles );\n}\n\nstd::vector<unsigned int> Gadgetron::cuConebeamProjectionOperator::new_order(std::vector<std::vector<unsigned int>> bins){\n\tstd::vector<unsigned int> result;\n\tfor (auto & b : bins)\n\t\tfor (auto p : b)\n\t\t\tresult.push_back(p);\n\treturn result;\n}\n\nboost::shared_ptr<hoCuNDArray<float> > Gadgetron::cuConebeamProjectionOperator::permute_projections(\n\t\tboost::shared_ptr<hoCuNDArray<float> > projections,\n\t\tstd::vector<unsigned int>  & permutations) {\n\n\tstd::vector<size_t> new_proj_dims = {projections->get_size(0),projections->get_size(1),permutations.size()};\n\n\tauto result = boost::make_shared<hoCuNDArray<float>>(new_proj_dims);\n\n\tsize_t nproj = permutations.size();\n\tsize_t proj_size = projections->get_size(0)*projections->get_size(1);\n\n\tfloat * res_ptr = result->get_data_ptr();\n\tfloat * proj_ptr = projections->get_data_ptr();\n\n\tfor (unsigned int i = 0; i < nproj; i++){\n\t\tcudaMemcpy(res_ptr+i*proj_size,proj_ptr+proj_size*permutations[i],proj_size*sizeof(float),cudaMemcpyHostToHost);\n\t}\n\treturn result;\n\n\n}\n\n\n\n} /* namespace Gadgetron */\n", "meta": {"hexsha": "6789aa75bb1b5325fd78249a1a66c4d599366f9f", "size": 8913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xray/cuConebeamProjectionOperator.cpp", "max_stars_repo_name": "ahsanjav/gt-tomography", "max_stars_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-06-26T13:41:55.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-10T11:06:27.000Z", "max_issues_repo_path": "xray/cuConebeamProjectionOperator.cpp", "max_issues_repo_name": "ahsanjav/gt-tomography", "max_issues_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xray/cuConebeamProjectionOperator.cpp", "max_forks_repo_name": "ahsanjav/gt-tomography", "max_forks_repo_head_hexsha": "1f53d72672ccda417bc8966d8497af6d786e8935", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T14:37:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T14:37:29.000Z", "avg_line_length": 35.652, "max_line_length": 278, "alphanum_fraction": 0.7373499383, "num_tokens": 2418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891163376235, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.22017140289202636}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#include \"laplace_3d_hypersingular_boundary_operator.hpp\"\n\n#include \"blas_quadrature_helper.hpp\"\n#include \"context.hpp\"\n#include \"general_elementary_local_operator_imp.hpp\"\n#include \"general_hypersingular_integral_operator_imp.hpp\"\n#include \"laplace_3d_single_layer_boundary_operator.hpp\"\n#include \"synthetic_integral_operator.hpp\"\n\n#include \"../common/boost_make_shared_fwd.hpp\"\n\n#include \"../fiber/explicit_instantiation.hpp\"\n\n#include \"../fiber/laplace_3d_single_layer_potential_kernel_functor.hpp\"\n#include \"../fiber/laplace_3d_hypersingular_off_diagonal_kernel_functor.hpp\"\n#include \"../fiber/surface_curl_3d_functor.hpp\"\n#include \"../fiber/scalar_function_value_functor.hpp\"\n#include \"../fiber/simple_test_scalar_kernel_trial_integrand_functor.hpp\"\n#include \"../fiber/single_component_test_trial_integrand_functor.hpp\"\n\n#include \"../fiber/default_collection_of_kernels.hpp\"\n#include \"../fiber/default_collection_of_basis_transformations.hpp\"\n#include \"../fiber/default_test_kernel_trial_integral.hpp\"\n\n#include \"general_elementary_singular_integral_operator_imp.hpp\"\n#include \"../fiber/typical_test_scalar_kernel_trial_integral.hpp\"\n\n#include <boost/type_traits/is_complex.hpp>\n\nnamespace Bempp {\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBoundaryOperator<BasisFunctionType, ResultType>\nlaplace3dSyntheticHypersingularBoundaryOperator(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &domain,\n    const shared_ptr<const Space<BasisFunctionType>> &range,\n    const shared_ptr<const Space<BasisFunctionType>> &dualToRange,\n    std::string label, int internalSymmetry,\n    const BoundaryOperator<BasisFunctionType, ResultType> &externalSlp) {\n  typedef typename ScalarTraits<BasisFunctionType>::RealType CoordinateType;\n\n  typedef Fiber::ScalarFunctionValueFunctor<CoordinateType> ValueFunctor;\n  typedef Fiber::SurfaceCurl3dFunctor<CoordinateType> CurlFunctor;\n  typedef Fiber::SingleComponentTestTrialIntegrandFunctor<\n      BasisFunctionType, ResultType> IntegrandFunctor;\n\n  typedef GeneralElementaryLocalOperator<BasisFunctionType, ResultType> LocalOp;\n  typedef SyntheticIntegralOperator<BasisFunctionType, ResultType> SyntheticOp;\n\n  if (!domain || !range || !dualToRange)\n    throw std::invalid_argument(\n        \"laplace3dSyntheticHypersingularBoundaryOperator(): \"\n        \"domain, range and dualToRange must not be null\");\n\n  shared_ptr<const Space<BasisFunctionType>> newDomain = domain;\n  shared_ptr<const Space<BasisFunctionType>> newDualToRange = dualToRange;\n\n  bool isBarycentric =\n      (domain->isBarycentric() || dualToRange->isBarycentric());\n\n  if (isBarycentric) {\n    newDomain = domain->barycentricSpace(domain);\n    newDualToRange = dualToRange->barycentricSpace(dualToRange);\n  }\n\n  shared_ptr<const Context<BasisFunctionType, ResultType>> internalContext,\n      auxContext;\n  SyntheticOp::getContextsForInternalAndAuxiliaryOperators(\n      context, internalContext, auxContext);\n  shared_ptr<const Space<BasisFunctionType>> internalTrialSpace =\n      newDomain->discontinuousSpace(newDomain);\n  shared_ptr<const Space<BasisFunctionType>> internalTestSpace =\n      newDualToRange->discontinuousSpace(newDualToRange);\n\n  // Note: we don't really need to care about ranges and duals to domains of\n  // the internal operator. The only range space that matters is that of the\n  // leftmost operator in the product.\n\n  const char xyz[] = \"xyz\";\n  const size_t dimWorld = 3;\n\n  if (label.empty())\n    label =\n        AbstractBoundaryOperator<BasisFunctionType, ResultType>::uniqueLabel();\n\n  BoundaryOperator<BasisFunctionType, ResultType> slp;\n\n  if (!externalSlp.isInitialized()) {\n\n    slp = laplace3dSingleLayerBoundaryOperator<BasisFunctionType, ResultType>(\n        internalContext, internalTrialSpace,\n        internalTestSpace /* or whatever */, internalTestSpace,\n        \"(\" + label + \")_internal_SLP\", internalSymmetry);\n\n  } else {\n\n    slp = externalSlp;\n  }\n\n  std::vector<BoundaryOperator<BasisFunctionType, ResultType>>\n  trialCurlComponents;\n  std::vector<BoundaryOperator<BasisFunctionType, ResultType>>\n  testCurlComponents;\n  testCurlComponents.resize(3);\n  for (size_t i = 0; i < dimWorld; ++i)\n    testCurlComponents[i] = BoundaryOperator<BasisFunctionType, ResultType>(\n        auxContext, boost::make_shared<LocalOp>(\n                        internalTestSpace, range, newDualToRange,\n                        (\"(\" + label + \")_test_curl_\") + xyz[i], NO_SYMMETRY,\n                        CurlFunctor(), ValueFunctor(), IntegrandFunctor(i, 0)));\n  int syntheseSymmetry = 0; // symmetry of the decomposition\n  if (newDomain == newDualToRange && internalTrialSpace == internalTestSpace)\n    syntheseSymmetry =\n        HERMITIAN | (boost::is_complex<BasisFunctionType>() ? 0 : SYMMETRIC);\n  else {\n    trialCurlComponents.resize(3);\n    for (size_t i = 0; i < dimWorld; ++i)\n      trialCurlComponents[i] = BoundaryOperator<BasisFunctionType, ResultType>(\n          auxContext,\n          boost::make_shared<LocalOp>(\n              newDomain, internalTrialSpace /* or whatever */,\n              internalTrialSpace, (\"(\" + label + \")_trial_curl_\") + xyz[i],\n              NO_SYMMETRY, ValueFunctor(), CurlFunctor(),\n              IntegrandFunctor(0, i)));\n  }\n\n  return BoundaryOperator<BasisFunctionType, ResultType>(\n      context, boost::make_shared<SyntheticOp>(testCurlComponents, slp,\n                                               trialCurlComponents, label,\n                                               syntheseSymmetry));\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBoundaryOperator<BasisFunctionType, ResultType>\nlaplace3dHypersingularBoundaryOperator(\n    const shared_ptr<const Context<BasisFunctionType, ResultType>> &context,\n    const shared_ptr<const Space<BasisFunctionType>> &domain,\n    const shared_ptr<const Space<BasisFunctionType>> &range,\n    const shared_ptr<const Space<BasisFunctionType>> &dualToRange,\n    const std::string &label, int symmetry,\n    const BoundaryOperator<BasisFunctionType, ResultType> &externalSlp) {\n  const AssemblyOptions &assemblyOptions = context->assemblyOptions();\n  if ((assemblyOptions.assemblyMode() == AssemblyOptions::ACA &&\n       assemblyOptions.acaOptions().mode == AcaOptions::LOCAL_ASSEMBLY) ||\n      (externalSlp.isInitialized()))\n    return laplace3dSyntheticHypersingularBoundaryOperator(\n        context, domain, range, dualToRange, label, symmetry, externalSlp);\n\n  typedef typename ScalarTraits<BasisFunctionType>::RealType KernelType;\n  typedef typename ScalarTraits<BasisFunctionType>::RealType CoordinateType;\n\n  typedef Fiber::Laplace3dSingleLayerPotentialKernelFunctor<KernelType>\n  KernelFunctor;\n  typedef Fiber::SurfaceCurl3dFunctor<CoordinateType> TransformationFunctor;\n  typedef Fiber::SimpleTestScalarKernelTrialIntegrandFunctorExt<\n      BasisFunctionType, KernelType, ResultType, 3> IntegrandFunctor;\n\n  typedef Fiber::Laplace3dHypersingularOffDiagonalKernelFunctor<KernelType>\n  OffDiagonalKernelFunctor;\n  typedef Fiber::ScalarFunctionValueFunctor<CoordinateType>\n  OffDiagonalTransformationFunctor;\n  typedef Fiber::SimpleTestScalarKernelTrialIntegrandFunctorExt<\n      BasisFunctionType, KernelType, ResultType, 1> OffDiagonalIntegrandFunctor;\n\n  typedef GeneralHypersingularIntegralOperator<BasisFunctionType, KernelType,\n                                               ResultType> Op;\n\n  shared_ptr<Fiber::TestKernelTrialIntegral<BasisFunctionType, KernelType,\n                                            ResultType>> integral,\n      offDiagonalIntegral;\n  if (shouldUseBlasInQuadrature(assemblyOptions, *domain, *dualToRange)) {\n    integral.reset(new Fiber::TypicalTestScalarKernelTrialIntegral<\n        BasisFunctionType, KernelType, ResultType>());\n    offDiagonalIntegral = integral;\n  } else {\n    integral.reset(new Fiber::DefaultTestKernelTrialIntegral<IntegrandFunctor>(\n        IntegrandFunctor()));\n    offDiagonalIntegral.reset(\n        new Fiber::DefaultTestKernelTrialIntegral<OffDiagonalIntegrandFunctor>(\n            OffDiagonalIntegrandFunctor()));\n  }\n\n  shared_ptr<Op> newOp(\n      new Op(domain, range, dualToRange, label, symmetry, KernelFunctor(),\n             TransformationFunctor(), TransformationFunctor(), integral,\n             OffDiagonalKernelFunctor(), OffDiagonalTransformationFunctor(),\n             OffDiagonalTransformationFunctor(), offDiagonalIntegral));\n\n  return BoundaryOperator<BasisFunctionType, ResultType>(context, newOp);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBoundaryOperator<BasisFunctionType, ResultType>\nlaplace3dHypersingularBoundaryOperator(\n    const ParameterList& parameterList,\n    const shared_ptr<const Space<BasisFunctionType>> &domain,\n    const shared_ptr<const Space<BasisFunctionType>> &range,\n    const shared_ptr<const Space<BasisFunctionType>> &dualToRange,\n    const std::string &label, int symmetry,\n    const BoundaryOperator<BasisFunctionType, ResultType> &externalSlp){\n\n\n  shared_ptr<const Context<BasisFunctionType, ResultType>> context(\n      new Context<BasisFunctionType, ResultType>(parameterList));\n  return laplace3dHypersingularBoundaryOperator(context, domain, range,\n                                              dualToRange, label, symmetry,\n                                              externalSlp);\n\n\n}\n\n\n#define INSTANTIATE_NONMEMBER_CONSTRUCTOR(BASIS, RESULT)                       \\\n  template BoundaryOperator<BASIS, RESULT>                                     \\\n  laplace3dHypersingularBoundaryOperator(                                      \\\n      const ParameterList&,                                                    \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      const shared_ptr<const Space<BASIS>> &, const std::string &, int,        \\\n      const BoundaryOperator<BASIS, RESULT> &);                                \\\n  template BoundaryOperator<BASIS, RESULT>                                     \\\n  laplace3dHypersingularBoundaryOperator(                                      \\\n      const shared_ptr<const Context<BASIS, RESULT>> &,                        \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      const shared_ptr<const Space<BASIS>> &,                                  \\\n      const shared_ptr<const Space<BASIS>> &, const std::string &, int,        \\\n      const BoundaryOperator<BASIS, RESULT> &)\nFIBER_ITERATE_OVER_BASIS_AND_RESULT_TYPES(INSTANTIATE_NONMEMBER_CONSTRUCTOR);\n\n} // namespace Bempp\n", "meta": {"hexsha": "a99908695a2d3b396b29969c801d27d6e8f0cd0d", "size": 11767, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/laplace_3d_hypersingular_boundary_operator.cpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/assembly/laplace_3d_hypersingular_boundary_operator.cpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/assembly/laplace_3d_hypersingular_boundary_operator.cpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6944444444, "max_line_length": 80, "alphanum_fraction": 0.7208294383, "num_tokens": 2639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.2201525326310721}}
{"text": "#pragma once\n\n#include <fstream>\n#include <mutex>\n\n#include <basalt/utils/ba_utils.h>\n#include <Eigen/Dense>\n#include <Eigen/Sparse>\n#include <basalt/linearization/landmark_block.hpp>\n#include <basalt/utils/sophus_utils.hpp>\n\nnamespace basalt {\n\ntemplate <typename Scalar, int POSE_SIZE>\nclass LandmarkBlockAbsDynamic : public LandmarkBlock<Scalar> {\n public:\n  using Options = typename LandmarkBlock<Scalar>::Options;\n  using State = typename LandmarkBlock<Scalar>::State;\n\n  inline bool isNumericalFailure() const override {\n    return state == State::NumericalFailure;\n  }\n\n  using Vec2 = Eigen::Matrix<Scalar, 2, 1>;\n  using Vec3 = Eigen::Matrix<Scalar, 3, 1>;\n  using Vec4 = Eigen::Matrix<Scalar, 4, 1>;\n\n  using VecX = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n\n  using Mat36 = Eigen::Matrix<Scalar, 3, 6>;\n\n  using MatX = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n  using RowMatX =\n      Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\n  virtual inline void allocateLandmark(\n      Keypoint<Scalar>& lm,\n      const Eigen::aligned_unordered_map<std::pair<TimeCamId, TimeCamId>,\n                                         RelPoseLin<Scalar>>& relative_pose_lin,\n      const Calibration<Scalar>& calib, const AbsOrderMap& aom,\n      const Options& options,\n      const std::map<TimeCamId, size_t>* rel_order = nullptr) override {\n    // some of the logic assumes the members are at their initial values\n    BASALT_ASSERT(state == State::Uninitialized);\n\n    UNUSED(rel_order);\n\n    lm_ptr = &lm;\n    options_ = &options;\n    calib_ = &calib;\n\n    // TODO: consider for VIO that we have a lot of 0 columns if we just use aom\n    // --> add option to use different AOM with reduced size and/or just\n    // involved poses --> when accumulating results, check which case we have;\n    // if both aom are identical, we don't have to do block-wise operations.\n    aom_ = &aom;\n\n    pose_lin_vec.clear();\n    pose_lin_vec.reserve(lm.obs.size());\n    pose_tcid_vec.clear();\n    pose_tcid_vec.reserve(lm.obs.size());\n\n    // LMBs without host frame should not be created\n    BASALT_ASSERT(aom.abs_order_map.count(lm.host_kf_id.frame_id) > 0);\n\n    for (const auto& [tcid_t, pos] : lm.obs) {\n      size_t i = pose_lin_vec.size();\n\n      auto it = relative_pose_lin.find(std::make_pair(lm.host_kf_id, tcid_t));\n      BASALT_ASSERT(it != relative_pose_lin.end());\n\n      if (aom.abs_order_map.count(tcid_t.frame_id) > 0) {\n        pose_lin_vec.push_back(&it->second);\n      } else {\n        // Observation droped for marginalization\n        pose_lin_vec.push_back(nullptr);\n      }\n      pose_tcid_vec.push_back(&it->first);\n\n      res_idx_by_abs_pose_[it->first.first.frame_id].insert(i);   // host\n      res_idx_by_abs_pose_[it->first.second.frame_id].insert(i);  // target\n    }\n\n    // number of pose-jacobian columns is determined by oam\n    padding_idx = aom_->total_size;\n\n    num_rows = pose_lin_vec.size() * 2 + 3;  // residuals and lm damping\n\n    size_t pad = padding_idx % 4;\n    if (pad != 0) {\n      padding_size = 4 - pad;\n    }\n\n    lm_idx = padding_idx + padding_size;\n    res_idx = lm_idx + 3;\n    num_cols = res_idx + 1;\n\n    // number of columns should now be multiple of 4 for good memory alignment\n    // TODO: test extending this to 8 --> 32byte alignment for float?\n    BASALT_ASSERT(num_cols % 4 == 0);\n\n    storage.resize(num_rows, num_cols);\n\n    damping_rotations.clear();\n    damping_rotations.reserve(6);\n\n    state = State::Allocated;\n  }\n\n  // may set state to NumericalFailure --> linearization at this state is\n  // unusable. Numeric check is only performed for residuals that were\n  // considered to be used (valid), which depends on\n  // use_valid_projections_only setting.\n  virtual inline Scalar linearizeLandmark() override {\n    BASALT_ASSERT(state == State::Allocated ||\n                  state == State::NumericalFailure ||\n                  state == State::Linearized || state == State::Marginalized);\n\n    // storage.setZero(num_rows, num_cols);\n    storage.setZero();\n    damping_rotations.clear();\n    damping_rotations.reserve(6);\n\n    bool numerically_valid = true;\n\n    Scalar error_sum = 0;\n\n    size_t i = 0;\n    for (const auto& [tcid_t, obs] : lm_ptr->obs) {\n      std::visit(\n          [&, obs = obs](const auto& cam) {\n            // TODO: The pose_lin_vec[i] == nullptr is intended to deal with\n            // dropped measurements during marginalization. However, dropped\n            // measurements should only occur for the remaining frames, not for\n            // the marginalized frames. Maybe these are observations bewtween\n            // two marginalized frames, if more than one is marginalized at the\n            // same time? But those we would not have to drop... Double check if\n            // and when this happens and possibly resolve by fixing handling\n            // here, or else updating the measurements in lmdb before calling\n            // linearization. Otherwise, check where else we need a `if\n            // (pose_lin_vec[i])` check or `pose_lin_vec[i] != nullptr` assert\n            // in this class.\n\n            if (pose_lin_vec[i]) {\n              size_t obs_idx = i * 2;\n              size_t abs_h_idx =\n                  aom_->abs_order_map.at(pose_tcid_vec[i]->first.frame_id)\n                      .first;\n              size_t abs_t_idx =\n                  aom_->abs_order_map.at(pose_tcid_vec[i]->second.frame_id)\n                      .first;\n\n              Vec2 res;\n              Eigen::Matrix<Scalar, 2, POSE_SIZE> d_res_d_xi;\n              Eigen::Matrix<Scalar, 2, 3> d_res_d_p;\n\n              using CamT = std::decay_t<decltype(cam)>;\n              bool valid = linearizePoint<Scalar, CamT>(\n                  obs, *lm_ptr, pose_lin_vec[i]->T_t_h, cam, res, &d_res_d_xi,\n                  &d_res_d_p);\n\n              if (!options_->use_valid_projections_only || valid) {\n                numerically_valid = numerically_valid &&\n                                    d_res_d_xi.array().isFinite().all() &&\n                                    d_res_d_p.array().isFinite().all();\n\n                const Scalar res_squared = res.squaredNorm();\n                const auto [weighted_error, weight] =\n                    compute_error_weight(res_squared);\n                const Scalar sqrt_weight =\n                    std::sqrt(weight) / options_->obs_std_dev;\n\n                error_sum += weighted_error /\n                             (options_->obs_std_dev * options_->obs_std_dev);\n\n                storage.template block<2, 3>(obs_idx, lm_idx) =\n                    sqrt_weight * d_res_d_p;\n                storage.template block<2, 1>(obs_idx, res_idx) =\n                    sqrt_weight * res;\n\n                d_res_d_xi *= sqrt_weight;\n                storage.template block<2, 6>(obs_idx, abs_h_idx) +=\n                    d_res_d_xi * pose_lin_vec[i]->d_rel_d_h;\n                storage.template block<2, 6>(obs_idx, abs_t_idx) +=\n                    d_res_d_xi * pose_lin_vec[i]->d_rel_d_t;\n              }\n            }\n\n            i++;\n          },\n          calib_->intrinsics[tcid_t.cam_id].variant);\n    }\n\n    if (numerically_valid) {\n      state = State::Linearized;\n    } else {\n      state = State::NumericalFailure;\n    }\n\n    return error_sum;\n  }\n\n  virtual inline void performQR() override {\n    BASALT_ASSERT(state == State::Linearized);\n\n    // Since we use dense matrices Householder QR might be better:\n    // https://mathoverflow.net/questions/227543/why-householder-reflection-is-better-than-givens-rotation-in-dense-linear-algebr\n\n    if (options_->use_householder) {\n      performQRHouseholder();\n    } else {\n      performQRGivens();\n    }\n\n    state = State::Marginalized;\n  }\n\n  // Sets damping and maintains upper triangular matrix for landmarks.\n  virtual inline void setLandmarkDamping(Scalar lambda) override {\n    BASALT_ASSERT(state == State::Marginalized);\n    BASALT_ASSERT(lambda >= 0);\n\n    if (hasLandmarkDamping()) {\n      BASALT_ASSERT(damping_rotations.size() == 6);\n\n      // undo dampening\n      for (int n = 2; n >= 0; n--) {\n        for (int m = n; m >= 0; m--) {\n          storage.applyOnTheLeft(num_rows - 3 + n - m, n,\n                                 damping_rotations.back().adjoint());\n          damping_rotations.pop_back();\n        }\n      }\n    }\n\n    if (lambda == 0) {\n      storage.template block<3, 3>(num_rows - 3, lm_idx).diagonal().setZero();\n    } else {\n      BASALT_ASSERT(Jl_col_scale.array().isFinite().all());\n\n      storage.template block<3, 3>(num_rows - 3, lm_idx)\n          .diagonal()\n          .setConstant(sqrt(lambda));\n\n      BASALT_ASSERT(damping_rotations.empty());\n\n      // apply dampening and remember rotations to undo\n      for (int n = 0; n < 3; n++) {\n        for (int m = 0; m <= n; m++) {\n          damping_rotations.emplace_back();\n          damping_rotations.back().makeGivens(\n              storage(n, lm_idx + n),\n              storage(num_rows - 3 + n - m, lm_idx + n));\n          storage.applyOnTheLeft(num_rows - 3 + n - m, n,\n                                 damping_rotations.back());\n        }\n      }\n    }\n  }\n\n  // lambda < 0 means computing exact model cost change\n  virtual inline void backSubstitute(const VecX& pose_inc,\n                                     Scalar& l_diff) override {\n    BASALT_ASSERT(state == State::Marginalized);\n\n    // For now we include all columns in LMB\n    BASALT_ASSERT(pose_inc.size() == signed_cast(padding_idx));\n\n    const auto Q1Jl = storage.template block<3, 3>(0, lm_idx)\n                          .template triangularView<Eigen::Upper>();\n\n    const auto Q1Jr = storage.col(res_idx).template head<3>();\n    const auto Q1Jp = storage.topLeftCorner(3, padding_idx);\n\n    Vec3 inc = -Q1Jl.solve(Q1Jr + Q1Jp * pose_inc);\n\n    // We want to compute the model cost change. The model function is\n    //\n    //     L(inc) = F(x) + inc^T J^T r + 0.5 inc^T J^T J inc\n    //\n    // and thus the expected decrease in cost for the computed increment is\n    //\n    //     l_diff = L(0) - L(inc)\n    //            = - inc^T J^T r - 0.5 inc^T J^T J inc\n    //            = - inc^T J^T (r + 0.5 J inc)\n    //            = - (J inc)^T (r + 0.5 (J inc)).\n    //\n    // Here we have J = [Jp, Jl] under the orthogonal projection Q = [Q1, Q2],\n    // i.e. the linearized system (model cost) is\n    //\n    //    L(inc) = 0.5 || J inc + r ||^2 = 0.5 || Q^T J inc + Q^T r ||^2\n    //\n    // and below we thus compute\n    //\n    //    l_diff = - (Q^T J inc)^T (Q^T r + 0.5 (Q^T J inc)).\n    //\n    // We have\n    //             | Q1^T |            | Q1^T Jp   Q1^T Jl |\n    //    Q^T J =  |      | [Jp, Jl] = |                   |\n    //             | Q2^T |            | Q2^T Jp      0    |.\n    //\n    // Note that Q2 is the nullspace of Jl, and Q1^T Jl == R. So with inc =\n    // [incp^T, incl^T]^T we have\n    //\n    //                | Q1^T Jp incp + Q1^T Jl incl |\n    //    Q^T J inc = |                             |\n    //                | Q2^T Jp incp                |\n    //\n\n    // undo damping before we compute the model cost difference\n    setLandmarkDamping(0);\n\n    // compute \"Q^T J incp\"\n    VecX QJinc = storage.topLeftCorner(num_rows - 3, padding_idx) * pose_inc;\n\n    // add \"Q1^T Jl incl\" to the first 3 rows\n    QJinc.template head<3>() += Q1Jl * inc;\n\n    auto Qr = storage.col(res_idx).head(num_rows - 3);\n    l_diff -= QJinc.transpose() * (Scalar(0.5) * QJinc + Qr);\n\n    // TODO: detect and handle case like ceres, allowing a few iterations but\n    // stopping eventually\n    if (!inc.array().isFinite().all() ||\n        !lm_ptr->direction.array().isFinite().all() ||\n        !std::isfinite(lm_ptr->inv_dist)) {\n      std::cerr << \"Numerical failure in backsubstitution\\n\";\n    }\n\n    // Note: scale only after computing model cost change\n    inc.array() *= Jl_col_scale.array();\n\n    lm_ptr->direction += inc.template head<2>();\n    lm_ptr->inv_dist = std::max(Scalar(0), lm_ptr->inv_dist + inc[2]);\n  }\n\n  virtual inline size_t numReducedCams() const override {\n    BASALT_LOG_FATAL(\"check what we mean by numReducedCams for absolute poses\");\n    return pose_lin_vec.size();\n  }\n\n  inline void addQ2JpTQ2Jp_mult_x(VecX& res,\n                                  const VecX& x_pose) const override {\n    UNUSED(res);\n    UNUSED(x_pose);\n    BASALT_LOG_FATAL(\"not implemented\");\n  }\n\n  virtual inline void addQ2JpTQ2r(VecX& res) const override {\n    UNUSED(res);\n    BASALT_LOG_FATAL(\"not implemented\");\n  }\n\n  virtual inline void addJp_diag2(VecX& res) const override {\n    BASALT_ASSERT(state == State::Linearized);\n\n    for (const auto& [frame_id, idx_set] : res_idx_by_abs_pose_) {\n      const int pose_idx = aom_->abs_order_map.at(frame_id).first;\n      for (const int i : idx_set) {\n        const auto block = storage.block(2 * i, pose_idx, 2, POSE_SIZE);\n\n        res.template segment<POSE_SIZE>(pose_idx) +=\n            block.colwise().squaredNorm();\n      }\n    }\n  }\n\n  virtual inline void addQ2JpTQ2Jp_blockdiag(\n      BlockDiagonalAccumulator<Scalar>& accu) const override {\n    UNUSED(accu);\n    BASALT_LOG_FATAL(\"not implemented\");\n  }\n\n  virtual inline void scaleJl_cols() override {\n    BASALT_ASSERT(state == State::Linearized);\n\n    // ceres uses 1.0 / (1.0 + sqrt(SquaredColumnNorm))\n    // we use 1.0 / (eps + sqrt(SquaredColumnNorm))\n    Jl_col_scale =\n        (options_->jacobi_scaling_eps +\n         storage.block(0, lm_idx, num_rows - 3, 3).colwise().norm().array())\n            .inverse();\n\n    storage.block(0, lm_idx, num_rows - 3, 3) *= Jl_col_scale.asDiagonal();\n  }\n\n  virtual inline void scaleJp_cols(const VecX& jacobian_scaling) override {\n    BASALT_ASSERT(state == State::Marginalized);\n\n    // we assume we apply scaling before damping (we exclude the last 3 rows)\n    BASALT_ASSERT(!hasLandmarkDamping());\n\n    storage.topLeftCorner(num_rows - 3, padding_idx) *=\n        jacobian_scaling.asDiagonal();\n  }\n\n  inline bool hasLandmarkDamping() const { return !damping_rotations.empty(); }\n\n  virtual inline void printStorage(const std::string& filename) const override {\n    std::ofstream f(filename);\n\n    Eigen::IOFormat CleanFmt(4, 0, \" \", \"\\n\", \"\", \"\");\n\n    f << \"Storage (state: \" << state\n      << \", damping: \" << (hasLandmarkDamping() ? \"yes\" : \"no\")\n      << \" Jl_col_scale: \" << Jl_col_scale.transpose() << \"):\\n\"\n      << storage.format(CleanFmt) << std::endl;\n\n    f.close();\n  }\n#if 0\n  virtual inline void stage2(\n      Scalar lambda, const VecX* jacobian_scaling, VecX* precond_diagonal2,\n      BlockDiagonalAccumulator<Scalar>* precond_block_diagonal,\n      VecX& bref) override {\n    // 1. scale jacobian\n    if (jacobian_scaling) {\n      scaleJp_cols(*jacobian_scaling);\n    }\n\n    // 2. dampen landmarks\n    setLandmarkDamping(lambda);\n\n    // 3a. compute diagonal preconditioner (SCHUR_JACOBI_DIAGONAL)\n    if (precond_diagonal2) {\n      addQ2Jp_diag2(*precond_diagonal2);\n    }\n\n    // 3b. compute block diagonal preconditioner (SCHUR_JACOBI)\n    if (precond_block_diagonal) {\n      addQ2JpTQ2Jp_blockdiag(*precond_block_diagonal);\n    }\n\n    // 4. compute rhs of reduced camera normal equations\n    addQ2JpTQ2r(bref);\n  }\n#endif\n\n  inline State getState() const override { return state; }\n\n  virtual inline size_t numQ2rows() const override { return num_rows - 3; }\n\n protected:\n  inline void performQRGivens() {\n    // Based on \"Matrix Computations 4th Edition by Golub and Van Loan\"\n    // See page 252, Algorithm 5.2.4 for how these two loops work\n    Eigen::JacobiRotation<Scalar> gr;\n    for (size_t n = 0; n < 3; n++) {\n      for (size_t m = num_rows - 4; m > n; m--) {\n        gr.makeGivens(storage(m - 1, lm_idx + n), storage(m, lm_idx + n));\n        storage.applyOnTheLeft(m, m - 1, gr);\n      }\n    }\n  }\n\n  inline void performQRHouseholder() {\n    VecX tempVector1(num_cols);\n    VecX tempVector2(num_rows - 3);\n\n    for (size_t k = 0; k < 3; ++k) {\n      size_t remainingRows = num_rows - k - 3;\n\n      Scalar beta;\n      Scalar tau;\n      storage.col(lm_idx + k)\n          .segment(k, remainingRows)\n          .makeHouseholder(tempVector2, tau, beta);\n\n      storage.block(k, 0, remainingRows, num_cols)\n          .applyHouseholderOnTheLeft(tempVector2, tau, tempVector1.data());\n    }\n  }\n\n  inline std::tuple<Scalar, Scalar> compute_error_weight(\n      Scalar res_squared) const {\n    // Note: Definition of cost is 0.5 ||r(x)||^2 to be in line with ceres\n\n    if (options_->huber_parameter > 0) {\n      // use huber norm\n      const Scalar huber_weight =\n          res_squared <= options_->huber_parameter * options_->huber_parameter\n              ? Scalar(1)\n              : options_->huber_parameter / std::sqrt(res_squared);\n      const Scalar error =\n          Scalar(0.5) * (2 - huber_weight) * huber_weight * res_squared;\n      return {error, huber_weight};\n    } else {\n      // use squared norm\n      return {Scalar(0.5) * res_squared, Scalar(1)};\n    }\n  }\n\n  void get_dense_Q2Jp_Q2r(MatX& Q2Jp, VecX& Q2r,\n                          size_t start_idx) const override {\n    Q2r.segment(start_idx, num_rows - 3) =\n        storage.col(res_idx).tail(num_rows - 3);\n\n    BASALT_ASSERT(Q2Jp.cols() == signed_cast(padding_idx));\n\n    Q2Jp.block(start_idx, 0, num_rows - 3, padding_idx) =\n        storage.block(3, 0, num_rows - 3, padding_idx);\n  }\n\n  void get_dense_Q2Jp_Q2r_rel(\n      MatX& Q2Jp, VecX& Q2r, size_t start_idx,\n      const std::map<TimeCamId, size_t>& rel_order) const override {\n    UNUSED(Q2Jp);\n    UNUSED(Q2r);\n    UNUSED(start_idx);\n    UNUSED(rel_order);\n    BASALT_LOG_FATAL(\"not implemented\");\n  }\n\n  void add_dense_H_b(DenseAccumulator<Scalar>& accum) const override {\n    UNUSED(accum);\n    BASALT_LOG_FATAL(\"not implemented\");\n  }\n\n  void add_dense_H_b(MatX& H, VecX& b) const override {\n    const auto r = storage.col(res_idx).tail(num_rows - 3);\n    const auto J = storage.block(3, 0, num_rows - 3, padding_idx);\n\n    H.noalias() += J.transpose() * J;\n    b.noalias() += J.transpose() * r;\n  }\n\n  void add_dense_H_b_rel(\n      MatX& H_rel, VecX& b_rel,\n      const std::map<TimeCamId, size_t>& rel_order) const override {\n    UNUSED(H_rel);\n    UNUSED(b_rel);\n    UNUSED(rel_order);\n    BASALT_LOG_FATAL(\"not implemented\");\n  }\n\n  const Eigen::PermutationMatrix<Eigen::Dynamic>& get_rel_permutation()\n      const override {\n    BASALT_LOG_FATAL(\"not implemented\");\n  }\n\n  Eigen::PermutationMatrix<Eigen::Dynamic> compute_rel_permutation(\n      const std::map<TimeCamId, size_t>& rel_order) const override {\n    UNUSED(rel_order);\n    BASALT_LOG_FATAL(\"not implemented\");\n  }\n\n  void add_dense_H_b_rel_2(MatX& H_rel, VecX& b_rel) const override {\n    UNUSED(H_rel);\n    UNUSED(b_rel);\n    BASALT_LOG_FATAL(\"not implemented\");\n  }\n\n  virtual TimeCamId getHostKf() const override { return lm_ptr->host_kf_id; }\n\n private:\n  // Dense storage for pose Jacobians, padding, landmark Jacobians and\n  // residuals [J_p | pad | J_l | res]\n  Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>\n      storage;\n\n  Vec3 Jl_col_scale = Vec3::Ones();\n  std::vector<Eigen::JacobiRotation<Scalar>> damping_rotations;\n\n  std::vector<const RelPoseLin<Scalar>*> pose_lin_vec;\n  std::vector<const std::pair<TimeCamId, TimeCamId>*> pose_tcid_vec;\n  size_t padding_idx = 0;\n  size_t padding_size = 0;\n  size_t lm_idx = 0;\n  size_t res_idx = 0;\n\n  size_t num_cols = 0;\n  size_t num_rows = 0;\n\n  const Options* options_ = nullptr;\n\n  State state = State::Uninitialized;\n\n  Keypoint<Scalar>* lm_ptr = nullptr;\n  const Calibration<Scalar>* calib_ = nullptr;\n  const AbsOrderMap* aom_ = nullptr;\n\n  std::map<int64_t, std::set<int>> res_idx_by_abs_pose_;\n};\n\n}  // namespace basalt\n", "meta": {"hexsha": "cc10c99bc7522896ba1b73a2d58026ae820b8a4c", "size": 19639, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/basalt/linearization/landmark_block_abs_dynamic.hpp", "max_stars_repo_name": "kwang-12/basalt-mirror", "max_stars_repo_head_hexsha": "9dd7b2c8031283ec033211bc90ad70aa70323eaa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 445.0, "max_stars_repo_stars_event_min_datetime": "2019-04-18T01:13:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T20:54:45.000Z", "max_issues_repo_path": "include/basalt/linearization/landmark_block_abs_dynamic.hpp", "max_issues_repo_name": "kwang-12/basalt-mirror", "max_issues_repo_head_hexsha": "9dd7b2c8031283ec033211bc90ad70aa70323eaa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/basalt/linearization/landmark_block_abs_dynamic.hpp", "max_forks_repo_name": "kwang-12/basalt-mirror", "max_forks_repo_head_hexsha": "9dd7b2c8031283ec033211bc90ad70aa70323eaa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 162.0, "max_forks_repo_forks_event_min_datetime": "2019-04-18T09:10:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:35:39.000Z", "avg_line_length": 33.5136518771, "max_line_length": 129, "alphanum_fraction": 0.6140333011, "num_tokens": 5319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22015253263107204}}
{"text": "\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ASTRONOMY_COORDINATE_BASE_COORDINATE_SYSTEM_HPP\n#define BOOST_ASTRONOMY_COORDINATE_BASE_COORDINATE_SYSTEM_HPP\n\n#include <tuple>\n#include <cmath>\n\n#include <boost/geometry/geometries/point.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/algorithms/transform.hpp>\n#include <boost/geometry/algorithms/equals.hpp>\n#include <boost/static_assert.hpp>\n\n#include <boost/astronomy/coordinate/representation.hpp>\n#include <boost/astronomy/coordinate/differential.hpp>\n#include <boost/astronomy/detail/is_base_template_of.hpp>\n#include <boost/astronomy/coordinate/arithmetic.hpp>\n\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\ntypedef boost::geometry::degree degree;\ntypedef boost::geometry::radian radian;\n\nnamespace bu = boost::units;\nnamespace bg = boost::geometry;\n\ntemplate <typename Representation, typename Differential>\nstruct base_frame\n{\n    ///@cond INTERNAL\n    BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n        <boost::astronomy::coordinate::base_representation, Representation>::value),\n        \"First template argument is expected to be a representation class\");\n    BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n        <boost::astronomy::coordinate::base_differential, Differential>::value),\n        \"Second template argument is expected to be a differential class\");\n    ///@endcond\n\nprotected:\n    Representation data;\n    Differential motion;\n\npublic:\n    typedef Representation representation;\n    typedef Differential differential;\n\n    //!returns 2d propermotion\n    std::tuple\n    <\n        typename Differential::quantity1,\n        typename Differential::quantity2\n    > get_proper_motion() const\n    {\n        return std::make_tuple\n        (\n            Differential::quantity1::from_value(bg::get<0>(motion.get_differential())),\n            Differential::quantity2::from_value(bg::get<1>(motion.get_differential()))\n        );\n    }\n\n    //!returns radial velocity (line of sight velocity) of the object\n    typename Differential::quantity3 get_radial_velocity() const\n    {\n        return Differential::quantity3::from_value(bg::get<2>(motion.get_differential()));\n    }\n\n    /*!returns differential data in form of boost::geometry::model::point \n    having components (pm_lat, pm_lon, radial_velocity) including cos(lat) component*/\n    Differential get_differential() const\n    {\n        return motion;\n    }\n\n    //!set differential for the motion of the object\n    void set_differential(Differential const& other)\n    {\n        this->motion = other;\n    }\n\n    /*!returns coordinate data in form of boost::geometry::model::point\n    having components (lat, lon, distance)*/\n    Representation get_data() const\n    {\n        return data;\n    }\n\n    //!returns data in specified subclass of base_representation\n    //template <typename ReturnType>\n    //ReturnType represent_as() const\n    //{\n    //    BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n    //        <boost::astronomy::coordinate::base_representation, ReturnType>::value), \n    //        \"return type is expected to be a representation class\");\n\n    //    return ReturnType(data);\n    //}\n\n    //!angular separation between two coordinates in radians\n    bu::quantity<bu::si::plane_angle> get_angular_separation(base_frame const& other) const\n    {\n        return bu::quantity<bu::si::plane_angle>::from_value(\n            std::acos((dot(this->data, other.get_data()) / \n                (magnitude(this->data) * magnitude(other.get_data()))).value())\n        );\n    }\n                \n};\n}}} //namespace boost::astronomy::coordinate\n#endif  // !BOOST_ASTRONOMY_COORDINATE_BASE_COORDINATE_SYSTEM_HPP\n", "meta": {"hexsha": "29cb888103cf71e8a05aded7e6835e09f1474b8a", "size": 3886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/base_frame.hpp", "max_stars_repo_name": "Solariii/astronomy", "max_stars_repo_head_hexsha": "6adad8e3f10c318b61b61d0b1836f2be19da01e3", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/astronomy/coordinate/base_frame.hpp", "max_issues_repo_name": "Solariii/astronomy", "max_issues_repo_head_hexsha": "6adad8e3f10c318b61b61d0b1836f2be19da01e3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/astronomy/coordinate/base_frame.hpp", "max_forks_repo_name": "Solariii/astronomy", "max_forks_repo_head_hexsha": "6adad8e3f10c318b61b61d0b1836f2be19da01e3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7913043478, "max_line_length": 91, "alphanum_fraction": 0.7071538857, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.3557749071749625, "lm_q1q2_score": 0.2201465513769013}}
{"text": "/*! \\file hydrodynamics_2d.hpp\n  \\brief Various manipulations of hydrodynamic variables\n  \\author Almog Yalinewich\n*/\n\n#ifndef HYDRODYNAMICS_2D_HPP\n#define HYDRODYNAMICS_2D_HPP 1\n\n#include \"spatial_distribution2d.hpp\"\n#include \"../common/equation_of_state.hpp\"\n#include \"point_motion.hpp\"\n#include \"spatial_reconstruction.hpp\"\n#include \"SourceTerm.hpp\"\n#include \"../../misc/utils.hpp\"\n#include \"../../misc/lazy_list.hpp\"\n#include \"../common/hydrodynamics.hpp\"\n#include \"../../misc/universal_error.hpp\"\n#include \"../../tessellation/ConvexHull.hpp\"\n#include \"../../tessellation/polygon_overlap_area.hpp\"\n#include <boost/scoped_ptr.hpp>\n#include \"../../tessellation/EdgeLengthCorrect.hpp\"\n#include \"physical_geometry.hpp\"\n#include \"time_step_function.hpp\"\n#include \"cache_data.hpp\"\n#include \"../common/riemann_solver.hpp\"\n\n/*! \\brief Rotates primitive variables to align with edge\n  \\param n Normal directions\n  \\param p Parallel direction\n  \\param cell Primitive variables\n  \\return Rotated cell\n */\nPrimitive RotatePrimitive(const Vector2D& n,\n\tconst Vector2D& p,\n\tconst Primitive& cell);\n\n/*! \\brief Rotates flux from the edge frame back to the lab frame\n  \\param c Flux\n  \\param n Normal direction\n  \\param p Parallel direction\n  \\return Rotated flux\n */\nConserved RotateFluxBack(const Conserved& c,\n\tconst Vector2D& n,\n\tconst Vector2D& p);\n\n/*! \\brief Given an edge and an index of one neighbor, returns the index of another neighbor\n  \\param edge Voronoi edge\n  \\param index Index of one neighbor\n  \\return Index of the other neighbor\n */\nint get_other_index(const Edge& edge,\n\tconst int index);\n\n/*! \\brief Initialize computational cells\n  \\param density Density distribution\n  \\param pressure Pressure distribution\n  \\param xvelocity Distribution of the x component of the velocity\n  \\param yvelocity Distribution of the y component of the velocity\n  \\param eos Equation of state\n  \\param tess Tessellation\n  \\param CMvalue Determines whether to evaluate the spatial distributions in the mesh generating points or the center of mass\n  \\return List of primitive variables\n*/\nvector<Primitive> InitialiseCells\n(SpatialDistribution const& density,\n\tSpatialDistribution const& pressure,\n\tSpatialDistribution const& xvelocity,\n\tSpatialDistribution const& yvelocity,\n\tEquationOfState const& eos,\n\tTessellation const& tess, bool CMvalue = true);\n\n/*! \\brief Calculates the intensive conserved variables\n  \\param cells Hydrodynamical cells\n  \\return List of conserved variables\n*/\nvector<Conserved> CalcConservedIntensive\n(vector<Primitive> const& cells);\n\n/*! \\brief Calculates the extensive conserved variables\n  \\param cons_int Conserved intensive variables\n  \\param tess Tessellation\n  \\param pg Physical geometry\n  \\return List of conserved variables\n*/\nvector<Conserved> CalcConservedExtensive\n(const vector<Conserved>& cons_int,\n\tconst Tessellation& tess,\n\tconst PhysicalGeometry& pg);\n\n/*! \\brief Calculates the time step for a cell\n  \\param cell Computational cell\n  \\param width Cell width\n  \\param face_velocites Velocities of the edges of the cell\n  \\return Time step\n*/\ndouble TimeStepForCell(Primitive const& cell,\n\tdouble width, vector<Vector2D> const& face_velocites);\n\n/*! \\brief Move mesh points\n  \\param pointvelocity Velocities of all mesh points\n  \\param dt Time step\n  \\param tessellation Tessellation\n  \\param oldpoints Possible input for the location of the old points\n  \\param reorder Should we reorder the points\n  \\return The indeces of the hilbert order of the points\n*/\nvector<int> MoveMeshPoints(vector<Vector2D> const& pointvelocity,\n\tdouble dt, Tessellation& tessellation, bool reorder,\n\tvector<Vector2D> oldpoints = vector<Vector2D>());\n/*! \\brief Move mesh points\n  \\param pointvelocity Velocities of all mesh points\n  \\param dt Time step\n  \\param tessellation The local tessellation\n  \\param vproc The processor tessellation\n  \\param oldpoints Possible input for the location of the old points\n  \\param reorder Should we reorder the points\n  \\return The indeces of the hilbert order of the points\n*/\nvector<int> MoveMeshPoints(vector<Vector2D> const& pointvelocity,\n\tdouble dt, Tessellation& tessellation, Tessellation const& vproc, bool reorder,\n\tvector<Vector2D> oldpoints = vector<Vector2D>());\n\n/*! \\brief Calculates the intensive conserved variables\n  \\param tess Tessellation\n  \\param extensive Extensive conserved variables\n  \\param pg Physical geometry\n  \\return List of intensive conserved variables\n */\nvector<Conserved> calc_conserved_intensive\n(const Tessellation& tess,\n\tconst vector<Conserved>& extensive,\n\tconst PhysicalGeometry& pg);\n\n/*! \\brief Updates the intensive conserved variables\n  \\param tessellation Tessellation\n  \\param conservedextensive Extensive conserved variables\n  \\param conservedintensive Intensive conserved variables\n*/\nvoid UpdateConservedIntensive(Tessellation const& tessellation,\n\tvector<Conserved> const& conservedextensive,\n\tvector<Conserved>& conservedintensive);\n\n/*! \\brief Calculates the flux in the bulk of the fluid\n  \\param normaldir A unit vector normal to the interface\n  \\param paraldir A unit vector parallel to the interface\n  \\param left Primitive variables on the left side of the interface\n  \\param right Primitive variables on the right side of the interface\n  \\param edge_velocity Velocity of the interface\n  \\param rs Riemann solver\n  \\return Flux\n */\nConserved FluxInBulk(Vector2D const& normaldir,\n\tVector2D const& paraldir,\n\tPrimitive const& left,\n\tPrimitive const& right,\n\tVector2D const& edge_velocity,\n\tRiemannSolver const& rs);\n\n/*! \\brief Adds force contribution to the extensive conserved variables\n  \\param tess Tessellation\n  \\param pg Physical geometry\n  \\param cd Cache data\n  \\param cells Computational cells\n  \\param fluxes Fluxes\n  \\param point_velocities Velocities of the mesh generating points\n  \\param source Source term\n  \\param t Time\n  \\param dt Time step\n  \\param extensives Extensive variables\n  \\param tracerstickernames The names of the tracers and stickers\n */\nvoid ExternalForceContribution\n(const Tessellation& tess,\n\tconst PhysicalGeometry& pg,\n\tconst CacheData& cd,\n\tconst vector<ComputationalCell>& cells,\n\tconst vector<Extensive>& fluxes,\n\tconst vector<Vector2D>& point_velocities,\n\tconst SourceTerm& source,\n\tdouble t,\n\tdouble dt,\n\tvector<Extensive>& extensives,\n\tTracerStickerNames const& tracerstickernames);\n\n/*! \\brief Returns the position of all mesh generating points\n  \\param tess Tessellation\n  \\return Position of all mesh generating points\n */\nvector<Vector2D> get_all_mesh_points\n(Tessellation const& tess);\n\n/*! \\brief Changes the energy and sound speed so they would satisfy the equation of state\n  \\param vp Primitive variables\n  \\param eos Equation of state\n  \\return Primitive variable with corrected sound speed and energy\n */\nvector<Primitive> make_eos_consistent\n(vector<Primitive> const& vp,\n\tEquationOfState const& eos);\n\n/*! \\brief Returns the energies due to external potentials\n  \\param tess Tessellation\n  \\param g TBA\n  \\return TBA\n  \\todo Add documentation\n */\nvector<double> GetForceEnergy(Tessellation const& tess,\n\tvector<double> const& g);\n\n/*! \\brief Calculates extensive tracers\n  \\param intensive_tracer Intensive tracers\n  \\param tess Tessellation\n  \\param cells List of primitive variables\n  \\param pg Physical geometry\n  \\return List of extensive tracers\n */\nvector<vector<double> > calc_extensive_tracer\n(const vector<vector<double> > & intensive_tracer,\n\tconst Tessellation& tess,\n\tconst vector<Primitive>& cells,\n\tconst PhysicalGeometry& pg);\n\n/*! \\brief Calculates the extensive tracer\n  \\param tracer Intensive tracer\n  \\param tess Tessellation\n  \\param cells Fluid elements\n  \\param result List of extensive tracers\n */\nvoid MakeTracerExtensive\n(vector<vector<double> > const&tracer,\n\tTessellation const& tess, vector<Primitive> const& cells,\n\tvector<vector<double> > &result);\n\n/*! \\brief Makes a list of points to remove\n  \\param tess Tessellation\n  \\param point TBA\n  \\param R Radius?\n  \\param PointToRemove output\n  \\param Inner TBA\n  \\todo Add documentation\n */\nvoid GetPointToRemove(Tessellation const& tess, Vector2D const& point,\n\tdouble R, vector<int> & PointToRemove, int Inner);\n\n/*! \\brief Applies a correction to the extensive variables due to the change in volume during time step.\n  \\details This method calculates the change in extensive by calculating the volume swept by an edge and multiplying it by the intensive variables of the respective cell.\n  \\param extensive Extensive variables\n  \\param intensive Intensive variables\n  \\param tessold Old tessellation\n  \\param tessnew New tessellation\n  \\param facevelocity Face velocity\n  \\param dt Time step\n  \\param pointvelocity Velocities of mesh generating points\n */\nvoid FixAdvection(vector<Conserved>& extensive,\n\tvector<Conserved> const& intensive,\n\tTessellation const& tessold,\n\tTessellation const& tessnew,\n\tvector<Vector2D> const& facevelocity,\n\tdouble dt, vector<Vector2D> const& pointvelocity);\n\n/*! \\brief Determines the time step\n  \\param hydro_time_step Time step derived from hydrodynamics\n  \\param external_dt Time step suggested by user\n  \\param current_time Current simulation time\n  \\param end_time Termination time\n  \\return Time step\n */\ndouble determine_time_step(double hydro_time_step,\n\tdouble external_dt,\n\tdouble current_time,\n\tdouble end_time);\n\n#endif // HYDRODYNAMICS_2D_HPP\n", "meta": {"hexsha": "f1868d4f79205b95a634b4e35492d749e507632a", "size": 9341, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/two_dimensional/hydrodynamics_2d.hpp", "max_stars_repo_name": "GalaxyHunters/Vivid", "max_stars_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/two_dimensional/hydrodynamics_2d.hpp", "max_issues_repo_name": "GalaxyHunters/Vivid", "max_issues_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 222.0, "max_issues_repo_issues_event_min_datetime": "2018-07-25T18:13:57.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T14:54:04.000Z", "max_forks_repo_path": "lib/SurfacingAlgorithms/huji-rich-Elad3DFast/source/newtonian/two_dimensional/hydrodynamics_2d.hpp", "max_forks_repo_name": "GalaxyHunters/Vivid", "max_forks_repo_head_hexsha": "f724e5671b650433d0c26319c86231bd3b246e4e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-07-29T09:39:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-08-25T19:17:49.000Z", "avg_line_length": 33.8442028986, "max_line_length": 170, "alphanum_fraction": 0.7804303608, "num_tokens": 2192, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.22013924011468539}}
{"text": "/*\n * @file pppBayesTree.cpp\n * @brief Iterative GPS Range/Phase Estimator with collected data\n * @author Ryan Watson & Jason Gross\n */\n\n\n#include \"nonlinear/ISAM2.h\"\n#include \"nonlinear/NonlinearFactorGraph.h\"\n#include \"inference/Symbol.h\"\n\n#include \"slam/PriorFactor.h\"\n#include \"slam/BetweenFactor.h\"\n#include \"pppbayestree/gnssNavigation/GnssData.h\"\n#include \"pppbayestree/gnssNavigation/GnssTools.h\"\n#include \"pppbayestree/gnssNavigation/PhaseFactor.h\"\n#include \"pppbayestree/gnssNavigation/nonBiasStates.h\"\n#include \"pppbayestree/configReader/ConfDataReader.hpp\"\n\n#include \"pppbayestree/gnssNavigation/PseudorangeFactor.h\"\n\n\n// GPSTK\n#include \"pppbayestree/gpstk/MJD.hpp\"\n#include \"pppbayestree/gpstk/PowerSum.hpp\"\n#include \"pppbayestree/gpstk/Decimate.hpp\"\n#include \"pppbayestree/gpstk/SolidTides.hpp\"\n#include \"pppbayestree/gpstk/PoleTides.hpp\"\n#include \"pppbayestree/gpstk/TropModel.hpp\"\n#include \"pppbayestree/gpstk/BasicModel.hpp\"\n#include \"pppbayestree/gpstk/CommonTime.hpp\"\n#include \"pppbayestree/gpstk/PCSmoother.hpp\"\n#include \"pppbayestree/gpstk/OceanLoading.hpp\"\n#include \"pppbayestree/gpstk/CodeSmoother.hpp\"\n#include \"pppbayestree/gpstk/SimpleFilter.hpp\"\n#include \"pppbayestree/gpstk/MWCSDetector.hpp\"\n#include \"pppbayestree/gpstk/SatArcMarker.hpp\"\n#include \"pppbayestree/gpstk/DCBDataReader.hpp\"\n#include \"pppbayestree/gpstk/ComputeWindUp.hpp\"\n#include \"pppbayestree/gpstk/Rinex3NavData.hpp\"\n#include \"pppbayestree/gpstk/GNSSconstants.hpp\"\n#include \"pppbayestree/gpstk/ComputeLinear.hpp\"\n#include \"pppbayestree/gpstk/GPSWeekSecond.hpp\"\n#include \"pppbayestree/gpstk/LICSDetector2.hpp\"\n#include \"pppbayestree/gpstk/DataStructures.hpp\"\n#include \"pppbayestree/gpstk/RinexObsStream.hpp\"\n#include \"pppbayestree/gpstk/Rinex3ObsStream.hpp\"\n#include \"pppbayestree/gpstk/Rinex3NavStream.hpp\"\n#include \"pppbayestree/gpstk/ComputeTropModel.hpp\"\n#include \"pppbayestree/gpstk/SP3EphemerisStore.hpp\"\n#include \"pppbayestree/gpstk/ComputeSatPCenter.hpp\"\n#include \"pppbayestree/gpstk/EclipsedSatFilter.hpp\"\n#include \"pppbayestree/gpstk/GPSEphemerisStore.hpp\"\n#include \"pppbayestree/gpstk/CorrectCodeBiases.hpp\"\n#include \"pppbayestree/gpstk/ComputeSatPCenter.hpp\"\n#include \"pppbayestree/gpstk/RequireObservables.hpp\"\n#include \"pppbayestree/gpstk/CorrectObservables.hpp\"\n#include \"pppbayestree/gpstk/LinearCombinations.hpp\"\n#include \"pppbayestree/gpstk/GravitationalDelay.hpp\"\n#include \"pppbayestree/gpstk/PhaseCodeAlignment.hpp\"\n#include \"pppbayestree/slam/dataset.h\"\n\n// BOOST\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <boost/serialization/export.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n\n// STD\n#include <chrono>\n#include <iomanip>\n#include <fstream>\n#include <iostream>\n#include <unistd.h>\n#include <algorithm>\n#include <Eigen/Core>\n\nusing namespace std;\nusing namespace gpstk;\nusing namespace boost;\nusing namespace std::chrono;\nusing namespace minisam;\nnamespace po = boost::program_options;\n\n\nint main(int argc, char* argv[])\n{\n    // define std out print color\n    vector<int> prn_vec;\n    vector<rnxData> data;\n    const string red(\"\\033[0;31m\");\n    const string green(\"\\033[0;32m\");\n    string confFile, gnssFile, station, sp3File, p1p2File, p1c1File, antennaModel;\n    string rnx_file, nav_file, sp3_file, out_file, antexFile;\n    double xn, yn, zn, xp, yp, range, phase, rho, minElev, weightFactor;\n    double antennaOffSetH, antennaOffSetE, antennaOffSetN;\n    int startKey(0), currKey, startEpoch(0), svn, doy;\n    int nThreads(-1), phase_break, break_count(0), nextKey, dec_int, itsBelowThree=0, count=0;\n    bool printECEF, printENU, printAmb, printUpdateRate, first_ob(true), usingP1(false);\n\n    FILE *fprealtime=fopen(\"examples_tuning/gpsdata/pppgpsposbackcount.txt\",\"w+\");\n\n    cout.precision(12);\n\n    /*po::options_description desc(\"Available options\");\n    desc.add_options()\n            (\"help,h\", \"Print help message\")\n            (\"confFile,c\", po::value<string>(&confFile)->default_value(\"\"),\n            \"Input config file\" )\n            (\"out\", po::value<string>(&out_file)->default_value(\"\"),\n            \"output file.\")\n            (\"usingP1\", \"Are you using P1 instead of C1?\");\n    po::variables_map vm;\n    po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n    po::notify(vm);*/\n\n    ConfDataReader confReader;\n    confReader.open(\"examples_tuning/gpsdata/phastball.conf\");\n    ISAM2Data isam2data;\n\n    /*if (confFile.empty() ) {\n            cout << red << \"\\n\\n Currently, you need to provide a conf file \\n\"\n                 << \"\\n\\n\"  << green << desc << endl;\n    }*/\n\n    while ( (station = confReader.getEachSection()) != \"\" )\n    {\n        // Fetch nominal station location [m]\n        xn = confReader.fetchListValueAsDouble(\"nominalECEF\",station);\n        yn = confReader.fetchListValueAsDouble(\"nominalECEF\",station);\n        zn = confReader.fetchListValueAsDouble(\"nominalECEF\",station);\n        // day of year ( used for Niell Trop model)\n        doy = confReader.getValueAsInt(\"DOY\", station);\n        // Elevation cut-off\n        minElev = confReader.getValueAsDouble(\"minElev\", station);\n        // Code/carrier ratio\n        weightFactor = confReader.getValueAsDouble(\"weightFactor\", station);\n        // Data file names\n        gnssFile = confReader(\"rnxFile\", station);\n        sp3File = confReader(\"sp3File\", station);\n        p1p2File = confReader(\"p1p2\", station);\n        p1c1File = confReader(\"p1c1\", station);\n        // Print statements\n        printENU = confReader.getValueAsBoolean(\"printENU\", station);\n        printAmb = confReader.getValueAsBoolean(\"printAmb\", station);\n        printECEF = confReader.getValueAsBoolean(\"printECEF\", station);\n        printUpdateRate = confReader.getValueAsBoolean(\"printUpdateRate\", station);\n    }\n\n    //usingP1 = (vm.count(\"usingP1\")>0);\n\n    minivector nomXYZ(xn, yn, zn);\n    minivector prop_xyz = nomXYZ;\n\n\n    /*#ifdef USE_TBB\n    std::auto_ptr<tbb::task_scheduler_init> init;\n    if(nThreads > 0) {\n            init.reset(new tbb::task_scheduler_init(nThreads));\n    }\n    else\n            cout << green << \" \\n\\n Using threads for all processors\" << endl;\n    #else\n    */\n    if(nThreads > 0)\n    {\n        cout << red <<\" \\n\\n not compiled with TBB, so threading is\"\n             << \" disabled and the --threads option cannot be used.\"\n             << endl;\n        exit(1);\n    }\n    //#endif\n\n    //ISAM2DoglegParams doglegParams;\n    ISAM2Params parameters;\n    //parameters.optimizationParamsDogleg=new ISAM2DoglegParams;\n    parameters.optimizationParamsGaussNewton=new ISAM2GaussNewtonParams;\n    parameters.relinearizeThresholdDouble = 0.1;\n    parameters.relinearizeSkip = 10;\n    ISAM2 isam(parameters);\n\n    double output_time = 0.0;\n    double rw = 2.5;\n    double rangeWeight = pow(rw,2);\n    double phaseWeight = pow(rw*1/weightFactor,2);\n\n    string value;\n\n    minivector prior_nonBias(5,0.0);\n    //prior_nonBias<<0.0, 0.0, 0.0, 0.0, 0.0;\n\n    double bias_state(0.0);\n    minivector phase_arc(34,0.0);\n    //phase_arc.setZero();\n    minivector bias_counter(34,0.0);\n   // bias_counter.setZero();\n\n    for (int i=1; i<34; i++)\n    {\n        bias_counter.data[i] = bias_counter.data[i-1] + 10000;\n    }\n\n    minivector* initEst5=new minivector(5);\n    minivector_set_zero(initEst5);\n   // initEst5<<0.0, 0.0, 0.0, 0.0, 0.0;\n\n    minivector*  between_nonBias_State=new minivector(5);\n    minivector_set_zero(between_nonBias_State);\n    //between_nonBias_State<<0.0, 0.0, 0.0, 0.0, 0.0;\n\n    //Values initial_values;\n    std::map<int,minimatrix*> initial_values;\n   // std::map<int,Pose3> initial_valuesP;\n    //Values result;\n   // std::map<int,Eigen::VectorXd> result;\n\n    minivector BiasinitNoise(5);\n    BiasinitNoise.data[0]=10.0;BiasinitNoise.data[1]=10.0;BiasinitNoise.data[2]=10.0;\n    BiasinitNoise.data[3]=3e8;BiasinitNoise.data[4]=1e-1;\n    //BiasinitNoise<<10.0, 10.0, 10.0, 3e8, 1e-1;\n    minivector_cwisesqrt(&BiasinitNoise);\n   // GaussianNoiseModel* nonBias_InitNoise=new GaussianNoiseModel(BiasinitNoise.cwiseSqrt());\n    GaussianNoiseModel* nonBias_InitNoise=new GaussianNoiseModel(BiasinitNoise);\n\n    minivector nonBiasProcessNoise(5);\n    nonBiasProcessNoise.data[0]=0.1;nonBiasProcessNoise.data[1]=0.1;nonBiasProcessNoise.data[2]=0.1;\n    nonBiasProcessNoise.data[3]=3e6;nonBiasProcessNoise.data[4]=3e-5;\n    minivector_cwisesqrt(&nonBiasProcessNoise);\n\n     GaussianNoiseModel* nonBias_ProcessNoise=new GaussianNoiseModel(nonBiasProcessNoise);\n\n\n\n    //0.1, 0.1, 0.1, 3e6, 3e-5;\n    minivector init_Noise(1,100);//init_Noise[0]=100;\n    //init_Noise<<100;\n    minivector_cwisesqrt(&init_Noise);\n\n     GaussianNoiseModel* initNoise=new GaussianNoiseModel(init_Noise);\n\n    string obs_path = findExampleDataFile(gnssFile,\"examples_tuning/gpsdata\");\n    string p1p2_path = findExampleDataFile(p1p2File,\"examples_tuning/gpsdata\");\n    string p1c1_path = findExampleDataFile(p1c1File,\"examples_tuning/gpsdata\");\n\n\n\n    if ( obs_path.empty() )\n    {\n        // cout << \" Must pass in obs file !!! \" << desc << endl;\n        exit(1);\n    }\n    if ( sp3File.empty() )\n    {\n        //cout << \" Must pass in ephemeris file !!! \" << desc << endl;\n        exit(1);\n    }\n    // Declare a \"SP3EphemerisStore\" object to handle precise ephemeris\n    SP3EphemerisStore SP3EphList;\n\n    size_t pos = 0;\n    string path, token;\n    string delimiter = \" \";\n    while ((pos = sp3File.find(delimiter)) != string::npos)\n    {\n        path = findExampleDataFile(sp3File.substr(0,pos),\"examples_tuning/gpsdata\");\n        SP3EphList.loadFile(path);\n        sp3File.erase(0, pos + delimiter.length());\n    }\n    path = findExampleDataFile(sp3File,\"examples_tuning/gpsdata\");\n    SP3EphList.loadFile(path);\n\n    // Set flags to reject satellites with bad or absent positional\n    // values or clocks\n    SP3EphList.rejectBadPositions(true);\n    SP3EphList.rejectBadClocks(true);\n\n    // Create the input observation file stream\n    Rinex3ObsStream rin(obs_path);\n\n    // station nominal position\n    Position nominalPos(xn, yn, zn);\n\n    CorrectCodeBiases corrCode;\n    corrCode.setDCBFile(p1p2_path, p1c1_path);\n\n    if (!usingP1)\n    {\n        corrCode.setUsingC1(true);\n    }\n\n\n    // This is the GNSS data structure that will hold all the\n    // GNSS-related information\n    gnssRinex gRin;\n\n    RequireObservables requireObs;\n    requireObs.addRequiredType(TypeID::L1);\n    requireObs.addRequiredType(TypeID::L2);\n\n    SimpleFilter pObsFilter;\n    pObsFilter.setFilteredType(TypeID::C1);\n\n    if ( usingP1 )\n    {\n        requireObs.addRequiredType(TypeID::P1);\n        pObsFilter.addFilteredType(TypeID::P1);\n        requireObs.addRequiredType(TypeID::P2);\n        pObsFilter.addFilteredType(TypeID::P2);\n    }\n    else\n    {\n        requireObs.addRequiredType(TypeID::C1);\n        pObsFilter.addFilteredType(TypeID::C1);\n        requireObs.addRequiredType(TypeID::P2);\n        pObsFilter.addFilteredType(TypeID::P2);\n    }\n\n    // Declare a couple of basic modelers\n    BasicModel basic(nominalPos, SP3EphList);\n    basic.setMinElev(minElev);\n\n    // Object to correct for SP3 Sat Phase-center offset\n    ComputeSatPCenter svPcenter(SP3EphList, nominalPos);\n\n    // Objects to mark cycle slips\n    MWCSDetector markCSMW;  // Checks Merbourne-Wubbena cycle slip\n\n    // object def several linear combinations\n    LinearCombinations comb;\n\n    // Object to compute linear combinations for cycle slip detection\n    ComputeLinear linear1;\n    if ( usingP1 )\n    {\n        linear1.addLinear(comb.pdeltaCombination);\n        linear1.addLinear(comb.mwubbenaCombination);\n    }\n    else\n    {\n        linear1.addLinear(comb.pdeltaCombWithC1);\n        linear1.addLinear(comb.mwubbenaCombWithC1);\n    }\n    linear1.addLinear(comb.ldeltaCombination);\n    linear1.addLinear(comb.liCombination);\n\n    ComputeLinear linear2;\n\n    // Read if we should use C1 instead of P1\n    if ( usingP1 )\n    {\n        linear2.addLinear(comb.pcCombination);\n    }\n    else\n    {\n        linear2.addLinear(comb.pcCombWithC1);\n    }\n    linear2.addLinear(comb.lcCombination);\n\n    LICSDetector2 markCSLI2;       // Checks LI cycle slips\n\n    // Object to keep track of satellite arcs\n    SatArcMarker markArc;\n    markArc.setDeleteUnstableSats(true);\n\n    // Objects to compute gravitational delay effects\n    GravitationalDelay grDelay(nominalPos);\n\n    // Object to remove eclipsed satellites\n    EclipsedSatFilter eclipsedSV;\n\n    //Object to compute wind-up effect\n    ComputeWindUp windup( SP3EphList, nominalPos );\n\n    // Object to compute prefit-residuals\n    ComputeLinear linear3(comb.pcPrefit);\n    linear3.addLinear(comb.lcPrefit);\n\n    TypeIDSet tset;\n    tset.insert(TypeID::prefitC);\n    tset.insert(TypeID::prefitL);\n\n    // Declare a NeillTropModel object, setting the defaults\n    NeillTropModel neillTM( nominalPos.getAltitude(),\n                            nominalPos.getGeodeticLatitude(),\n                            doy);\n\n    // Objects to compute the tropospheric data\n    ComputeTropModel computeTropo(neillTM);\n\n    // initialize factor graph\n    //NonlinearFactorGraph *graph = new NonlinearFactorGraph();\n    NonlinearFactorGraph graph;\n\n    auto start = std::chrono::steady_clock::now();\n    auto end = std::chrono::steady_clock::now();\n    // Loop over all data epochs\n    while(rin >> gRin)\n    {\n        TimeSystem sys;\n        sys.fromString(\"GPS\");\n        CommonTime time(gRin.header.epoch);\n        time.setTimeSystem(sys);\n        GPSWeekSecond gpstime( time );\n\n        // update nominal ECEF with propogated pos.\n        NeillTropModel neillTM( nominalPos.getAltitude(),\n                                nominalPos.getGeodeticLatitude(),\n                                doy);\n        try\n        {\n            gRin >> requireObs // Check if required observations are present\n                 >> pObsFilter // Filter out spurious data\n                 >> linear1 // Compute linear combinations to detect CS\n                 >> markCSLI2 // Mark cycle slips\n                 >> markArc // Keep track of satellite arcs\n                 >> basic // Compute the basic components of model\n                 >> eclipsedSV // Remove satellites in eclipse\n                 >> grDelay // Compute gravitational delay\n                 >> svPcenter // Computer delta for sat. phase center\n                 >> corrCode // Correct for differential code biases\n                 >> windup // phase windup correction\n                 >> computeTropo // neill trop function\n                 >> linear2  // Compute ionosphere-free combinations\n                 >> linear3;   // Compute prefit residuals\n        }\n        catch(Exception& e)\n        {\n            continue;\n        }\n        catch(...)\n        {\n            cerr << \"Unknown exception at epoch: \" << time << endl;\n            continue;\n        }\n\n        // Iterate through the GNSS Data Structure\n        satTypeValueMap::const_iterator it;\n        typeValueMap::const_iterator itObs;\n        if ( itsBelowThree > 0 )\n        {\n            itsBelowThree = 0;\n            continue;\n        }\n\n        if (gRin.body.size() == 0)\n        {\n            continue;\n        }\n\n        // Loop over all observed sats at current epoch\n        for (it = gRin.body.begin(); it!= gRin.body.end(); it++)\n        {\n\n            start = std::chrono::steady_clock::now();\n            svn = ((*it).first).id;\n            double satX, satY, satZ;\n            satX = (*it).second.getValue(TypeID::satX);\n            satY = (*it).second.getValue(TypeID::satY);\n            satZ = (*it).second.getValue(TypeID::satZ);\n            minivector satXYZ(satX,satY,satZ);\n            double range, rangeRes;\n            range = (*it).second.getValue(TypeID::PC);\n            rangeRes = (*it).second.getValue(TypeID::prefitC);\n            double phase, phaseRes;\n            phase = (*it).second.getValue(TypeID::LC);\n            phaseRes = (*it).second.getValue(TypeID::prefitL);\n            int phase_break;\n            phase_break = (*it).second.getValue(TypeID::satArc);\n\n            if (first_ob)\n            {\n                startKey = count;\n                first_ob=false;\n                PriorFactor* npn=new PriorFactor(Symbol('X',count).key(), initEst5,  nonBias_InitNoise);\n\n                graph.push_back(npn);\n                initial_values.insert(std::make_pair(Symbol('X',count).key(), new minivector(initEst5)));\n\n            }\n\n            if (phase_arc.data[svn]!=phase_break)\n            {\n                bias_state = phase - range;\n                if (count > startKey)\n                {\n                    bias_counter.data[svn] = bias_counter.data[svn] +1;\n                }\n                minivector *biasb=new minivector(1);\n                biasb->data[0]=bias_state;\n               // biasb<<bias_state;\n\n                //GaussianNoiseModel* initNoise=new GaussianNoiseModel(init_Noise.cwiseSqrt());\n\n\n                PriorFactor* nphb=new PriorFactor(Symbol('B',bias_counter.data[svn]).key(),\n                biasb,initNoise);\n                graph.push_back(nphb);\n                initial_values.insert(std::make_pair(Symbol('B',bias_counter.data[svn]).key(), new minivector(biasb)));\n                phase_arc.data[svn] = phase_break;\n            }\n            // Generate pseudorange factor\n            minivector gpsRangeFactorvec(1,sqrt(elDepWeight(satXYZ, nomXYZ, rangeWeight)));\n\n            //gpsRangeFactorvec<<elDepWeight(satXYZ, nomXYZ, rangeWeight);\n            //GaussianNoiseModel* ngpsrfn=new GaussianNoiseModel(gpsRangeFactorvec.cwiseSqrt());\n            GaussianNoiseModel* ngpsrfn=new GaussianNoiseModel(gpsRangeFactorvec);\n            PseudorangeFactor* ngpsrf=new PseudorangeFactor(Symbol('X',count).key(), rangeRes,\n             new minivector(satXYZ), new minivector(nomXYZ),ngpsrfn);\n\n            graph.push_back(ngpsrf);\n            gpsRangeFactorvec.data[0]=sqrt(elDepWeight(satXYZ, nomXYZ, phaseWeight));\n            GaussianNoiseModel* ngpspfn2=new GaussianNoiseModel(gpsRangeFactorvec);\n            //GaussianNoiseModel* ngpspfn2=new GaussianNoiseModel(gpsRangeFactorvec.cwiseSqrt());\n            PhaseFactor* ngpspf=new PhaseFactor(Symbol('X',count).key(),\n             Symbol('B',bias_counter.data[svn]).key(),phaseRes, new minivector(satXYZ),\n             new minivector( nomXYZ),ngpspfn2);\n            graph.push_back(ngpspf);\n\n            prn_vec.push_back(svn);\n        }\n        if (count > startKey )\n        {\n           // GaussianNoiseModel* nonBias_ProcessNoise=\n           // new GaussianNoiseModel(nonBiasProcessNoise.cwiseSqrt());\n\n            BetweenFactor* nbfnbs=new BetweenFactor(Symbol('X',count).key(),\n            Symbol('X',count-1).key(), new minivector(between_nonBias_State), nonBias_ProcessNoise);\n            graph.push_back(nbfnbs);\n        }\n\n        isam.update(graph, initial_values,isam2data);\n        //result = isam.calculateEstimate(isam2data);\n        isam.calculateEstimate(isam2data);\n\n        end = std::chrono::steady_clock::now();\n\n\n        //prior_nonBias =result.at(Symbol('X',count).key());\n        //prior_nonBias =isam2data.result.at(Symbol('X',count).key());\n        minimatrix_memcpy(&prior_nonBias,isam2data.resulttheta_.at(Symbol('X',count).key()));\n\n        minivector delta_xyz(prior_nonBias.data[0], prior_nonBias.data[1], prior_nonBias.data[2]);\n        Position deltaPos(prior_nonBias.data[0], prior_nonBias.data[1], prior_nonBias.data[2]);\n        //prop_xyz = nomXYZ - delta_xyz;\n        minivector_sub(&prop_xyz,nomXYZ,delta_xyz);\n        nominalPos -= deltaPos;\n\n        if (printECEF)\n        {\n            cout << \"xyz \" << gpstime.week << \" \" << gpstime.sow << \" \" << prop_xyz.x() <<\n            \" \" << prop_xyz.y() << \" \" << prop_xyz.data[2] << endl;\n        }\n\n        if (printENU)\n        {\n            minivector enu = xyz2enu(prop_xyz, nomXYZ);\n            cout << \"enu \" << gpstime.week << \" \" << gpstime.sow << \" \" <<\n            enu.x() << \" \" << enu.y() << \" \" << enu.data[2] << endl;\n            fprintf(fprealtime,\"%d %.15f %.15f %.15f %.15f %d\\n\",\n                    gpstime.week,gpstime.sow,enu.x(),enu.y(),enu.data[2],\n                    isam.lastBacksubVariableCount);\n        }\n\n        if (printAmb)\n        {\n            for (int k=0; k<prn_vec.size(); k++)\n            {\n                cout << \"amb. \" << gpstime.week << \" \" << gpstime.sow << \" \";\n                cout << prn_vec[k] << \" \";\n                //cout << result.at(Symbol('B',bias_counter[prn_vec[k]]).key()) << endl;\n                minimatrix_print(isam2data.resulttheta_.at(Symbol('B',\n                bias_counter.data[prn_vec[k]]).key()));\n                cout << endl;\n            }\n        }\n\n        if (printUpdateRate)\n        {\n            cout << \"Elapsed time \"\n                 << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()\n                 << \" µs\" << endl;\n        }\n\n        output_time = output_time +1;\n        graph.resize(0);\n        initial_values.clear();\n        prn_vec.clear();\n        count++;\n        initial_values.insert(std::make_pair(Symbol('X',count).key(),\n        new minivector(prior_nonBias)));\n       if(count>20000)\n        {\n         isam.clearall();\n    isam2data.clearvalues();\n    isam2data.clearfactors();\n    delete parameters.optimizationParamsGaussNewton;\n    delete between_nonBias_State;\n    delete nonBias_InitNoise;\n    delete initNoise;\n     delete nonBias_ProcessNoise;\n     for(auto& dlt:initial_values)\n    {\n       if(dlt.second!=NULL)\n       delete dlt.second;\n    }\n    return 0;\n        }\n    }\n   // ofstream bs(\"examples_tuning/data/gnsstree.dot\");\n    //isam.saveGraph(bs);\n\n    isam.clearall();\n    isam2data.clearvalues();\n    isam2data.clearfactors();\n    delete parameters.optimizationParamsGaussNewton;\n    delete between_nonBias_State;\n    delete nonBias_InitNoise;\n    delete initNoise;\n    delete nonBias_ProcessNoise;\n    for(auto& dlt:initial_values)\n    {\n       if(dlt.second!=NULL)\n       delete dlt.second;\n    }\n\n    return 0;\n}\n/* ************************************************************************* */\n\n\n", "meta": {"hexsha": "eef96f6e8297dfa40717edc29056e9cff647bc48", "size": 22094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/pppbayestree/pppbayestree.cpp", "max_stars_repo_name": "shaolinbit/minisam_lib", "max_stars_repo_head_hexsha": "e2e904d1b6753976de1dee102f0b53e778c0f880", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 104.0, "max_stars_repo_stars_event_min_datetime": "2019-06-23T14:45:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T12:45:29.000Z", "max_issues_repo_path": "examples/pppbayestree/pppbayestree.cpp", "max_issues_repo_name": "shaolinbit/minisam_lib", "max_issues_repo_head_hexsha": "e2e904d1b6753976de1dee102f0b53e778c0f880", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-28T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-17T02:37:08.000Z", "max_forks_repo_path": "examples/pppbayestree/pppbayestree.cpp", "max_forks_repo_name": "shaolinbit/minisam_lib", "max_forks_repo_head_hexsha": "e2e904d1b6753976de1dee102f0b53e778c0f880", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2019-06-23T14:45:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T12:45:24.000Z", "avg_line_length": 34.9588607595, "max_line_length": 119, "alphanum_fraction": 0.6388612293, "num_tokens": 5893, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22013923421806053}}
{"text": "#pragma once\n/** @file KDTree\n * @brief A binary tree constructed by splitting each box by a median.\n */\n\n#include <vector>\n#include <algorithm>\n#include <type_traits>\n#include <iterator>\n\n#include <iostream>\n#include <iomanip>\n\n#include <boost/range.hpp>\n#include <boost/iterator/permutation_iterator.hpp>\n\n#include \"fmmtl/tree/util/CountedProxyIterator.hpp\"\n\n#include \"fmmtl/util/Logger.hpp\"\n#include \"fmmtl/numeric/Vec.hpp\"\n#include \"fmmtl/tree/BoundingBox.hpp\"\n\n#include \"fmmtl/numeric/bits.hpp\"\n\nnamespace fmmtl {\nusing boost::has_range_iterator;\n\n\n//! Class for tree structure\ntemplate <unsigned DIM>\nclass KDTree {\n  // Predeclarations\n  struct Box;\n  struct Body;\n  struct BoxData;\n\n  // The type of this tree\n  typedef KDTree<DIM> tree_type;\n\n public:\n  //! The type of indices and integers in this tree\n  typedef unsigned size_type;\n\n  //! The spacial point type used for centers and extents\n  typedef Vec<DIM,double> point_type;\n\n  //! Public type declarations\n  typedef Box           box_type;\n  typedef Body          body_type;\n  using box_iterator  = CountedProxyIterator<Box,  const KDTree, size_type>;\n  using body_iterator = CountedProxyIterator<Body, const KDTree, size_type>;\n\n private:\n  // Tree representation\n\n  // Permutation: permute_[i] is the current idx of originally ith point\n  std::vector<size_type> permute_;\n  // Vector of data describing a box\n  std::vector<BoxData> box_data_;\n\n  struct BoxData {\n    // Index of the first body in this box\n    size_type body_begin_;\n    // Index of one-past-last body in this box\n    size_type body_end_;\n\n    // Bounding Box of this box\n    BoundingBox<point_type> bounding_box_;\n\n    BoxData(size_type bb, size_type be,\n            const point_type& min, const point_type& max)\n        : body_begin_(bb), body_end_(be),\n          bounding_box_(min,max) {\n    }\n  };\n\n  struct Body {\n    /** Construct an invalid Body */\n    Body() {}\n    //! The original order this body was seen\n    size_type number() const {\n      return tree_->permute_[idx_];\n    }\n    //! The current order of this body\n    size_type index() const {\n      return idx_;\n    }\n   private:\n    size_type idx_;\n    tree_type* tree_;\n    friend body_iterator;\n    Body(size_type idx, const tree_type* tree)\n        : idx_(idx), tree_(const_cast<tree_type*>(tree)) {\n      FMMTL_ASSERT(idx_ < tree_->size());\n    }\n    friend class KDTree;\n  };\n\n  // A tree-aligned box\n  struct Box {\n    typedef typename tree_type::box_iterator  box_iterator;\n    typedef typename tree_type::body_iterator body_iterator;\n\n    //! Construct an invalid Box\n    Box() {}\n    //! The index of this box\n    size_type index() const {\n      return idx_;\n    }\n    //! The level of this box (root level is 0)\n    size_type level() const {\n      return std::log2(idx_+1);  // XXX: Slow? do this with bits\n    }\n\n    //! The dimension of each side of this box\n    point_type extents() const {\n      return data().bounding_box_.max() - data().bounding_box_.min();\n    }\n    //! The squared radius of this box\n    double radius_sq() const {\n      return norm_2_sq(extents()) / 4.0;\n    }\n    //! The center of this box\n    point_type center() const {\n      return (data().bounding_box_.max() + data().bounding_box_.min()) / 2.0;\n    }\n\n    //! The parent box of this box\n    Box parent() const {\n      FMMTL_ASSERT(!(*this == tree_->root()));\n      return Box((idx_-1)/2, tree_);\n    }\n\n    //! True if this box is a leaf and has no children\n    bool is_leaf() const {\n      return 2*idx_+1 >= tree_->box_data_.size();\n    }\n    //! The begin iterator to the child boxes contained in this box\n    box_iterator child_begin() const {\n      FMMTL_ASSERT(!is_leaf());\n      return box_iterator(2*idx_+1, tree_);\n    }\n    //! The end iterator to the child boxes contained in this box\n    box_iterator child_end() const {\n      FMMTL_ASSERT(!is_leaf());\n      return box_iterator(2*idx_+3, tree_);\n    }\n    //! The number of children this box has\n    static constexpr size_type num_children() {\n      return 2;\n    }\n\n    //! The begin iterator to the bodies contained in this box\n    body_iterator body_begin() const {\n      return body_iterator(data().body_begin_, tree_);\n    }\n    //! The end iterator to the bodies contained in this box\n    body_iterator body_end() const {\n      return body_iterator(data().body_end_, tree_);\n    }\n    //! The number of bodies this box contains\n    size_type num_bodies() const {\n      return std::distance(body_begin(), body_end());\n    }\n\n    //! Equality comparison operator\n    bool operator==(const Box& b) const {\n      FMMTL_ASSERT(tree_ == b.tree_);\n      return idx_ == b.idx_;\n    }\n    //! Comparison operator for std:: containers and algorithms\n    bool operator<(const Box& b) const {\n      FMMTL_ASSERT(tree_ == b.tree_);\n      return idx_ < b.idx_;\n    }\n\n    //! Write a Box to an output stream\n    inline friend std::ostream& operator<<(std::ostream& s,\n                                           const box_type& b) {\n      size_type num_bodies = b.num_bodies();\n      size_type first_body = b.body_begin()->index();\n      size_type last_body = first_body + num_bodies - 1;\n      size_type parent_idx = b.index()==0 ? 0 : b.parent().index();\n\n      return s << \"Box \" << b.index()\n               << \" (L\" << b.level() << \", P\" << parent_idx\n               << \", \" << num_bodies << (num_bodies == 1 ? \" body\" : \" bodies\")\n               << \" \" << first_body << \"-\" << last_body\n               << \"): \" << b.center() << \" - \" << b.extents();\n    }\n   private:\n    size_type idx_;\n    tree_type* tree_;\n    friend box_iterator;\n    Box(size_type idx, const tree_type* tree)\n        : idx_(idx), tree_(const_cast<tree_type*>(tree)) {\n      FMMTL_ASSERT(idx_ < tree_->boxes());\n    }\n    inline BoxData& data() const {\n      return tree_->box_data_[idx_];\n    }\n    friend class KDTree;\n  };\n\n public:\n\n  /** Construct a tree encompassing a bounding box\n   * and insert a range of points */\n  template <typename Range>\n  KDTree(const Range& rng, size_type n_crit = 256,\n         typename std::enable_if<has_range_iterator<Range>::value>::type* = 0)\n      : KDTree(rng.begin(), rng.end(), n_crit) {\n  }\n\n  /** Construct an tree encompassing a bounding box\n   * and insert a range of points */\n  template <typename PointIter>\n  KDTree(PointIter first, PointIter last, size_type n_crit = 256) {\n    insert(first, last, n_crit);\n  }\n\n  /** Return the Bounding Box that this KDTree encompasses */\n  BoundingBox<point_type> bounding_box() const {\n    return box_data_[0].bounding_box_;\n  }\n\n  /** Return the center of this KDTree */\n  point_type center() const {\n    return root().center();\n  }\n\n  /** The number of bodies contained in this tree */\n  inline size_type size() const {\n    return permute_.size();\n  }\n  /** The number of bodies contained in this tree */\n  inline size_type bodies() const {\n    return size();\n  }\n\n  /** The number of boxes contained in this tree */\n  inline size_type boxes() const {\n    return box_data_.size();\n  }\n\n  /** The number of boxes contained in level L of this tree */\n  inline size_type boxes(size_type L) const {\n    return (1 << L);\n  }\n\n  /** The maximum level of any box in this tree */\n  inline size_type levels() const {\n    return std::log2(boxes());  // XXX: Slow?\n  }\n\n  /** Returns true if the box is contained in this tree, false otherwise */\n  inline bool contains(const box_type& box) const {\n    return this == box.tree_;\n  }\n  /** Returns true if the body is contained in this tree, false otherwise */\n  inline bool contains(const body_type& body) const {\n    return this == body.tree_;\n  }\n\n  /** Return the root box of this tree */\n  box_type root() const {\n    return Box(0, this);\n  }\n  /** Return a box given its index */\n  box_type box(const size_type idx) const {\n    FMMTL_ASSERT(idx < box_data_.size());\n    return Box(idx, this);\n  }\n  /** Return a body given its index */\n  body_type body(const size_type idx) const {\n    FMMTL_ASSERT(idx < size());\n    return Body(idx, this);\n  }\n  /** Return an iterator to the first body in this tree */\n  body_iterator body_begin() const {\n    return body_iterator(0, this);\n  }\n  /** Return an iterator one past the last body in this tree */\n  body_iterator body_end() const {\n    return body_iterator(bodies(), this);\n  }\n  /** Return an iterator to the first box in this tree */\n  box_iterator box_begin() const {\n    return box_iterator(0, this);\n  }\n  /** Return an iterator one past the last box in this tree */\n  box_iterator box_end() const {\n    return box_iterator(boxes(), this);\n  }\n  /** Return an iterator to the first box at level L in this tree\n   * @pre L < levels()\n   */\n  box_iterator box_begin(size_type L) const {\n    FMMTL_ASSERT(L < levels());\n    return box_iterator((1 << L) - 1, this);\n  }\n  /** Return an iterator one past the last box at level L in this tree\n   * @pre L < levels()\n   */\n  box_iterator box_end(size_type L) const {\n    FMMTL_ASSERT(L < levels());\n    return box_iterator((1 << (L+1)) - 1, this);\n  }\n\n  template <typename RandomAccessIter>\n  struct body_permuted_iterator {\n    typedef typename std::vector<size_type>::const_iterator permute_iter;\n    typedef boost::permutation_iterator<RandomAccessIter, permute_iter> type;\n  };\n\n  /** Tranform (permute) an iterator so its traversal follows the same order as\n   * the bodies contained in this tree\n   */\n  template <typename RandomAccessIter>\n  typename body_permuted_iterator<RandomAccessIter>::type\n  body_permute(RandomAccessIter it, const body_iterator& bi) const {\n    return boost::make_permutation_iterator(it, permute_.cbegin() + bi.index());\n  }\n\n  /** Tranform (permute) an iterator so its traversal follows the same order as\n   * the bodies contained in this tree\n   *\n   * Specialized for bi = body_begin().\n   */\n  template <typename RandomAccessIter>\n  typename body_permuted_iterator<RandomAccessIter>::type\n  body_permute(RandomAccessIter it) const {\n    return body_permute(it, body_begin());\n  }\n\n  /** Write an KDTree to an output stream */\n  inline friend std::ostream& operator<<(std::ostream& s,\n                                         const tree_type& t) {\n    struct {\n      inline std::ostream& print(std::ostream& s,\n                                 const box_type& box) {\n        s << std::string(2*box.level(), ' ') << box;\n        if (!box.is_leaf())\n          for (auto ci = box.child_begin(); ci != box.child_end(); ++ci)\n            print(s << \"\\n\", *ci);\n        return s;\n      }\n    } recursive_box;\n\n    return recursive_box.print(s, t.root());\n  }\n\n private:\n  //! TODO: Make dynamic and public?\n  template <typename PointIter>\n  void insert(PointIter p_first, PointIter p_last, size_type NCRIT) {\n    FMMTL_LOG(\"KDTree Insert\");\n\n    FMMTL_ASSERT(p_first != p_last);\n\n    // Create a point-idx pair vector\n    typedef typename std::iterator_traits<PointIter>::value_type point_i_type;\n\n    // XXX: Generalize?\n    static_assert(std::is_same<point_i_type, point_type>::value,\n                  \"PointIter value_type must be point_type\");\n\n    typedef std::pair<point_type, unsigned> point_t;\n\n    std::vector<point_t> point;\n    // If iterators are random access, we can reserve space efficiently\n    // Compile-time predicate!\n    if (std::is_same<typename std::iterator_traits<PointIter>::iterator_category,\n                     std::random_access_iterator_tag>::value)\n      point.reserve(std::distance(p_first, p_last));\n\n    unsigned idx = 0;\n    BoundingBox<point_i_type> root_bb(*p_first);\n    for (PointIter pi = p_first; pi != p_last; ++pi, ++idx) {\n      point.emplace_back(*pi, idx);\n      root_bb |= point.back().first;\n    }\n\n    permute_.reserve(point.size());\n\n    // The number of leaf boxes that will be created\n    // (Smallest power of two greater than or equal to ceil(N/NCRIT))\n    unsigned leaves = ceil_pow_2((point.size() + NCRIT - 1) / NCRIT);\n    unsigned levels = std::log2(leaves);\n\n    // Reserve the number of boxes that will be added\n    box_data_.reserve(2*leaves - 1);\n    // Push the root box which contains all points\n    box_data_.emplace_back(0, size_type(point.size()),\n                           root_bb.min(), root_bb.max());\n\n    // For every box that is created\n    unsigned end_k = (1 << levels) - 1;\n    for (unsigned k = 0; k < end_k; ++k) {\n\n      // Get the bounding box of the current box\n      auto& bb = box_data_[k].bounding_box_;\n\n      // Make a comparator for the largest dimension\n      const unsigned dim = max_dim(bb.max() - bb.min());\n      auto comp = [=] (const point_t& a, const point_t& b) {\n        return a.first[dim] < b.first[dim];\n      };\n\n      // Partition the points on the median of this dimension\n      auto p_begin = point.begin() + box_data_[k].body_begin_;\n      auto p_end   = point.begin() + box_data_[k].body_end_;\n      auto p_mid   = p_begin + (p_end - p_begin + 1) / 2;\n      std::nth_element(p_begin, p_mid, p_end, comp);\n\n      // Record the child boxes\n      unsigned mid = p_mid - point.begin();\n      point_type split = bb.max();\n      split[dim] = (*p_mid).first[dim];\n      box_data_.emplace_back(box_data_[k].body_begin_, mid, bb.min(), split);\n      split = bb.min();\n      split[dim] = (*p_mid).first[dim];\n      box_data_.emplace_back(mid, box_data_[k].body_end_, split, bb.max());\n    }\n\n    // Assert no re-allocation\n    FMMTL_ASSERT(box_data_.size() <= 2*leaves-1);\n\n    // Extract the permutation idx\n    for (auto&& p : point)\n      permute_.push_back(p.second);\n  }\n\n  static unsigned max_dim(const point_type& p) {\n    return std::max_element(p.begin(), p.end()) - p.begin();\n  }\n\n  // Just making sure for now\n  KDTree(const KDTree&) {};\n  void operator=(const KDTree&) {};\n};\n\n} // end namespace fmmtl\n", "meta": {"hexsha": "0f536cccb9348263db8c144ad338ed5ebfb088a7", "size": 13701, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "source/fmmtl/fmmtl/tree/KDTree.hpp", "max_stars_repo_name": "sergeneren/BubbleH", "max_stars_repo_head_hexsha": "e018e5a008e101221a4f8a3bbb25e7ec03fc9662", "max_stars_repo_licenses": ["BSD-3-Clause-Clear"], "max_stars_count": 52.0, "max_stars_repo_stars_event_min_datetime": "2019-10-06T17:25:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T23:01:13.000Z", "max_issues_repo_path": "source/fmmtl/fmmtl/tree/KDTree.hpp", "max_issues_repo_name": "sergeneren/BubbleH", "max_issues_repo_head_hexsha": "e018e5a008e101221a4f8a3bbb25e7ec03fc9662", "max_issues_repo_licenses": ["BSD-3-Clause-Clear"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-10-08T18:44:41.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-09T07:48:31.000Z", "max_forks_repo_path": "source/fmmtl/fmmtl/tree/KDTree.hpp", "max_forks_repo_name": "sergeneren/BubbleH", "max_forks_repo_head_hexsha": "e018e5a008e101221a4f8a3bbb25e7ec03fc9662", "max_forks_repo_licenses": ["BSD-3-Clause-Clear"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-10-07T16:33:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-21T01:09:47.000Z", "avg_line_length": 30.8581081081, "max_line_length": 81, "alphanum_fraction": 0.639734326, "num_tokens": 3442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21998478011745345}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_CHAMB_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_CHAMB_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 4.9.1\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/geometry/util/math.hpp>\n#include <cstdio>\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/aasincos.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace chamb\n    {\n\n            static const double THIRD = 0.333333333333333333;\n            static const double TOL = 1e-9;\n\n            // specific for 'chamb'\n            struct VECT { double r, Az; };\n            struct XY { double x, y; };\n\n            struct par_chamb\n            {\n                struct { /* control point data */\n                double phi, lam;\n                double cosphi, sinphi;\n                VECT v;\n                XY    p;\n                double Az;\n                } c[3];\n                XY p;\n                double beta_0, beta_1, beta_2;\n            };\n\n                static VECT /* distance and azimuth from point 1 to point 2 */\n            vect(double dphi, double c1, double s1, double c2, double s2, double dlam) {\n                VECT v;\n                double cdl, dp, dl;\n\n                cdl = cos(dlam);\n                if (fabs(dphi) > 1. || fabs(dlam) > 1.)\n                    v.r = aacos(s1 * s2 + c1 * c2 * cdl);\n                else { /* more accurate for smaller distances */\n                    dp = sin(.5 * dphi);\n                    dl = sin(.5 * dlam);\n                    v.r = 2. * aasin(sqrt(dp * dp + c1 * c2 * dl * dl));\n                }\n                if (fabs(v.r) > TOL)\n                    v.Az = atan2(c2 * sin(dlam), c1 * s2 - s1 * c2 * cdl);\n                else\n                    v.r = v.Az = 0.;\n                return v;\n            }\n                static double /* law of cosines */\n            lc(double b,double c,double a) {\n                return aacos(.5 * (b * b + c * c - a * a) / (b * c));\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_chamb_spheroid : public base_t_f<base_chamb_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_chamb m_proj_parm;\n\n                inline base_chamb_spheroid(const Parameters& par)\n                    : base_t_f<base_chamb_spheroid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    double sinphi, cosphi, a;\n                    VECT v[3];\n                    int i, j;\n\n                    sinphi = sin(lp_lat);\n                    cosphi = cos(lp_lat);\n                    for (i = 0; i < 3; ++i) { /* dist/azimiths from control */\n                        v[i] = vect(lp_lat - this->m_proj_parm.c[i].phi, this->m_proj_parm.c[i].cosphi, this->m_proj_parm.c[i].sinphi,\n                            cosphi, sinphi, lp_lon - this->m_proj_parm.c[i].lam);\n                        if ( ! v[i].r)\n                            break;\n                        v[i].Az = adjlon(v[i].Az - this->m_proj_parm.c[i].v.Az);\n                    }\n                    if (i < 3) /* current point at control point */\n                        { xy_x = this->m_proj_parm.c[i].p.x; xy_y = this->m_proj_parm.c[i].p.y; }\n                    else { /* point mean of intersepts */\n                        { xy_x = this->m_proj_parm.p.x; xy_y = this->m_proj_parm.p.y; }\n                        for (i = 0; i < 3; ++i) {\n                            j = i == 2 ? 0 : i + 1;\n                            a = lc(this->m_proj_parm.c[i].v.r, v[i].r, v[j].r);\n                            if (v[i].Az < 0.)\n                                a = -a;\n                            if (! i) { /* coord comp unique to each arc */\n                                xy_x += v[i].r * cos(a);\n                                xy_y -= v[i].r * sin(a);\n                            } else if (i == 1) {\n                                a = this->m_proj_parm.beta_1 - a;\n                                xy_x -= v[i].r * cos(a);\n                                xy_y -= v[i].r * sin(a);\n                            } else {\n                                a = this->m_proj_parm.beta_2 - a;\n                                xy_x += v[i].r * cos(a);\n                                xy_y += v[i].r * sin(a);\n                            }\n                        }\n                        xy_x *= THIRD; /* mean of arc intercepts */\n                        xy_y *= THIRD;\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"chamb_spheroid\";\n                }\n\n            };\n\n            // Chamberlin Trimetric\n            template <typename Parameters>\n            void setup_chamb(Parameters& par, par_chamb& proj_parm)\n            {\n                int i, j;\n                char line[10];\n\n                for (i = 0; i < 3; ++i) { /* get control point locations */\n                    (void)sprintf(line, \"rlat_%d\", i+1);\n                    proj_parm.c[i].phi = pj_param(par.params, line).f;\n                    (void)sprintf(line, \"rlon_%d\", i+1);\n                    proj_parm.c[i].lam = pj_param(par.params, line).f;\n                    proj_parm.c[i].lam = adjlon(proj_parm.c[i].lam - par.lam0);\n                    proj_parm.c[i].cosphi = cos(proj_parm.c[i].phi);\n                    proj_parm.c[i].sinphi = sin(proj_parm.c[i].phi);\n                }\n                for (i = 0; i < 3; ++i) { /* inter ctl pt. distances and azimuths */\n                    j = i == 2 ? 0 : i + 1;\n                    proj_parm.c[i].v = vect(proj_parm.c[j].phi - proj_parm.c[i].phi, proj_parm.c[i].cosphi, proj_parm.c[i].sinphi,\n                        proj_parm.c[j].cosphi, proj_parm.c[j].sinphi, proj_parm.c[j].lam - proj_parm.c[i].lam);\n                    if (! proj_parm.c[i].v.r) throw proj_exception(-25);\n                    /* co-linearity problem ignored for now */\n                }\n                proj_parm.beta_0 = lc(proj_parm.c[0].v.r, proj_parm.c[2].v.r, proj_parm.c[1].v.r);\n                proj_parm.beta_1 = lc(proj_parm.c[0].v.r, proj_parm.c[1].v.r, proj_parm.c[2].v.r);\n                proj_parm.beta_2 = geometry::math::pi<double>() - proj_parm.beta_0;\n                proj_parm.p.y = 2. * (proj_parm.c[0].p.y = proj_parm.c[1].p.y = proj_parm.c[2].v.r * sin(proj_parm.beta_0));\n                proj_parm.c[2].p.y = 0.;\n                proj_parm.c[0].p.x = - (proj_parm.c[1].p.x = 0.5 * proj_parm.c[0].v.r);\n                proj_parm.p.x = proj_parm.c[2].p.x = proj_parm.c[0].p.x + proj_parm.c[2].v.r * cos(proj_parm.beta_0);\n                par.es = 0.;\n            }\n\n        }} // namespace detail::chamb\n    #endif // doxygen\n\n    /*!\n        \\brief Chamberlin Trimetric projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Miscellaneous\n         - Spheroid\n         - no inverse\n        \\par Projection parameters\n         - lat_1: Latitude of control point 1 (degrees)\n         - lon_1: Longitude of control point 1 (degrees)\n         - lat_2: Latitude of control point 2 (degrees)\n         - lon_2: Longitude of control point 2 (degrees)\n         - lat_3: Latitude of control point 3 (degrees)\n         - lon_3: Longitude of control point 3 (degrees)\n        \\par Example\n        \\image html ex_chamb.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct chamb_spheroid : public detail::chamb::base_chamb_spheroid<Geographic, Cartesian, Parameters>\n    {\n        inline chamb_spheroid(const Parameters& par) : detail::chamb::base_chamb_spheroid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::chamb::setup_chamb(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Factory entry(s)\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class chamb_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_f<chamb_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void chamb_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"chamb\", new chamb_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_CHAMB_HPP\n\n", "meta": {"hexsha": "8b11fde28c857b6cf8704e10e60bdac0cbd43d5f", "size": 11476, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/chamb.hpp", "max_stars_repo_name": "bowlofstew/omim", "max_stars_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-11T05:02:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-11T05:02:05.000Z", "max_issues_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/chamb.hpp", "max_issues_repo_name": "bowlofstew/omim", "max_issues_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "3party/boost/boost/geometry/extensions/gis/projections/proj/chamb.hpp", "max_forks_repo_name": "bowlofstew/omim", "max_forks_repo_head_hexsha": "8045157c95244aa8f862d47324df42a19b87e335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-04T10:55:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-23T18:52:06.000Z", "avg_line_length": 44.480620155, "max_line_length": 134, "alphanum_fraction": 0.5394736842, "num_tokens": 2697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.3451052642223204, "lm_q1q2_score": 0.21984268064690735}}
{"text": "#ifndef DCM_PLANNER_H\n#define DCM_PLANNER_H\n\n#include <PnC/PlannerSet/DCMPlanner/Footstep.hpp>\n#include <Utils/Math/minjerk_vec.hpp>\n#include <Utils/Math/hermite_quaternion_curve.hpp>\n#include <Utils/IO/IOUtilities.hpp>\n#include <Eigen/Dense>\n#include <cmath>\n#include <string>\n#include <iostream>\n#include <map>\n\nclass DCMPlanner{\npublic:\n  DCMPlanner();\n  ~DCMPlanner(); \n\n  static int const DCM_RL_SWING_VRP_TYPE;\n  static int const DCM_LL_SWING_VRP_TYPE;\n  static int const DCM_MIDSTEP_TRANSFER_VRP_TYPE;\n  static int const DCM_TRANSFER_VRP_TYPE;\n  static int const DCM_END_VRP_TYPE;\n\n  std::vector<int> rvrp_type_list; // List of type of virtual repelant point\n\n  std::vector<Footstep> footstep_list; // Footstep list to generate pattern\n\n  std::vector<Eigen::Vector3d> rvrp_list; // List of virtual repelant points.\n  std::vector<Eigen::Vector3d> dcm_ini_list; // List of initial DCM states \n  std::vector<Eigen::Vector3d> dcm_eos_list; // List of end-of-step DCM states\n\n  // Initial DCM states\n  Eigen::Vector3d ini_dcm_pos;\n  Eigen::Vector3d ini_dcm_vel;\n\n  // map containing the rvrp index that have a corresponding footstep swing\n  std::map<int, int> rvrp_index_to_footstep_index;\n  // Vector containing hermite quaternion curve objects for the pelvis orientation.\n  // one curve per RVRP.\n  std::vector<HermiteQuaternionCurve> pelvis_ori_quat_curves;\n\n  // Initial and Boundary Conditions for the continuous DS trajectory\n  std::vector<Eigen::Vector3d> dcm_ini_DS_list; \n  std::vector<Eigen::Vector3d> dcm_vel_ini_DS_list; \n  std::vector<Eigen::Vector3d> dcm_acc_ini_DS_list; \n  std::vector<Eigen::Vector3d> dcm_end_DS_list; \n  std::vector<Eigen::Vector3d> dcm_vel_end_DS_list; \n  std::vector<Eigen::Vector3d> dcm_acc_end_DS_list;  \n  std::vector<Eigen::MatrixXd> dcm_P; // polynomial matrices for polynomial interpolation\n  std::vector<MinJerkCurveVec> dcm_minjerk; // minjerk curves for interpolation\n\n  // DCM walking parameters\n  double t_transfer = 0.1; //0.125 ; //0.1; // exponential interpolation transfer time during initial transfer or same step transfer\n  double t_ds = 0.05; // double support polynomial transfer time\n  double t_ss = 0.3; // single support exponential interpolation  time\n  double percentage_settle = 0.99;//0.999; // percent to converge at the end of the trajectory\n  double alpha_ds = 0.5; // value between 0.0 and 1.0 for double support DCM interpolation\n\n\n  void paramInitialization(const YAML::Node& node);\n  void setRobotMass(double mass);\n  void setCoMHeight(double z_vrp_in); // Sets the desired CoM Height\n  void setInitialTime(double t_start_in); // Sets the initial offset time.\n  void setInitialOri(const Eigen::Quaterniond initial_ori_in);\n\n  double getInitialTime(); // Returns t_start;\n\n\n  // DCM trajectory calculation\n  // input: input_footstep_list - a list of footsteps to take not including the current stance configuration.\n  //        initial_footstance  - a footstep object describing the stance leg. \n  void initialize_footsteps_rvrp(const std::vector<Footstep> & input_footstep_list, const Footstep & initial_footstance, bool clear_list=false);\n\n  // input: input_footstep_list - a list of footsteps to take not including the current stance configuration.\n  //        initial_footstance  - a footstep object describing the stance leg. \n  //        initial_rvrp        - an initial virtual repelant point (eg: average of the stance feet's rvrp). \n  void initialize_footsteps_rvrp(const std::vector<Footstep> & input_footstep_list, const Footstep & initial_footstance, const Eigen::Vector3d & initial_rvrp);\n\n\n  // input: input_footstep_list - a list of footsteps to take not including the current stance configuration.\n  //        left_footstance        - a footstep object describing the left stance feet\n  //        right_footstance       - a footstep object describing the right stance feet\n  void initialize_footsteps_rvrp(const std::vector<Footstep> & input_footstep_list, const Footstep & left_footstance, const Footstep & right_footstance);\n\n  // input: input_footstep_list - a list of footsteps to take not including the current stance configuration.\n  //        left_footstance        - a footstep object describing the left stance feet\n  //        right_footstance       - a footstep object describing the right stance feet\n  //        initial_com            - the initial location of the com \n  void initialize_footsteps_rvrp(const std::vector<Footstep> & input_footstep_list, const Footstep & left_footstance, const Footstep & right_footstance, const Eigen::Vector3d & initial_com);\n\n  // input: input_footstep_list - a list of footsteps to take not including the current stance configuration.\n  //        left_footstance        - a footstep object describing the left stance feet\n  //        right_footstance       - a footstep object describing the right stance feet\n  //        initial_dcm            - the initial starting position of the dcm\n  //        initial_dcm_vel        - the initial starting velocity of the dcm\n  void initialize_footsteps_rvrp(const std::vector<Footstep> & input_footstep_list, \n                                 const Footstep & left_footstance, const Footstep & right_footstance, \n                                 const Eigen::Vector3d & initial_dcm, const Eigen::Vector3d & initial_dcm_vel);\n\n\n  // Compute: DCM, DCM vel, CoM, CoM Vel, given time, t.\n  // t is a global time.\n  void get_ref_dcm(const double t, Eigen::Vector3d & dcm_out);\n  void get_ref_dcm_vel(const double t, Eigen::Vector3d & dcm_vel_out);\n  void get_ref_com(const double t, Eigen::Vector3d & com_out);\n  void get_ref_com_vel(const double t, Eigen::Vector3d & com_vel_out);\n  void get_ref_r_vrp(const double t, Eigen::Vector3d & r_vrvp_out);\n  void get_ref_reaction_force(const double t, Eigen::Vector3d & f_out);\n\n  // Global reference quat, ang vel and ang acc\n  void get_ref_ori_ang_vel_acc(const double t, Eigen::Quaterniond & quat_out,\n                                               Eigen::Vector3d & ang_vel_out,\n                                               Eigen::Vector3d & ang_acc_out);\n\n  // computes the CoM velocity given the current CoM position and DCM velocity state.\n  void get_com_vel(const Eigen::Vector3d & com_pos, const Eigen::Vector3d & dcm, Eigen::Vector3d & com_vel_out);\n  // computes the CoM reaction force / leg reaction force given mass, CoM position and the r_vrp\n  void get_reaction_force(const double mass, const Eigen::Vector3d & com_pos, const Eigen::Vector3d & r_vrp, Eigen::Vector3d fr_out);\n  // computes the current r_vrp given \n  //   -the DCM dynamics time constant b,\n  //  - the current dcm \n  //  - and the current dcm_vel\n  void get_r_vrp(const double b_in, const Eigen::Vector3d & dcm, const Eigen::Vector3d & dcm_vel, Eigen::Vector3d & r_vrp_out);\n\n  // prints the boundary conditions of the DCM\n  void printBoundaryConditions();\n\n  // Helper Functions\n  // Returns the exponential step index the current time falls in.\n  int which_step_index(const double t);\n  // Returns the polynomial step index to use given the input time from t_start.\n  int which_step_index_to_use(const double t);\n\n  // returns the starting and ending time of the step_index from t_start.\n  double get_t_step_start(const int step_index);\n  double get_t_step_end(const int step_index);\n\n  // returns the double support starting and ending time of the step_index from t_start.\n  double get_double_support_t_start(const int step_index);\n  double get_double_support_t_end(const int step_index);\n\n  // if the step_index is a swing type, returns true an populates the swing start time and end\n  bool get_t_swing_start_end(const int step_index, double & swing_start_time, double & swing_end_time);\n\n  // returns the polynomial duration for the given step index\n  double get_polynomial_duration(const int step_index);\n\n  // Get the initial and end of double support transition times\n  double get_eoDS_transition_time();\n  double get_iniDS_transition_time();  \n\n  // Returns the type of VRP. Clamps the index to valid values.\n  int get_r_vrp_type(const int step_index);\n\n  // Returns t_end\n  double get_total_trajectory_time();\n\n  // Returns t_settle;\n  double get_settle_time(){\n    double t_settle = -b*log(1.0 - percentage_settle);\n    return t_settle;\n  }\n\nprivate:\n  // DCM parameters:\n  double robot_mass = 50; // kg\n  double gravity = 9.81;\n  double z_vrp = 0.75; // desired VRP height / CoM height\n  double b = std::sqrt(z_vrp/gravity); // time constant of DCM dynamics  \n\n  double t_start = 0.0; // the starting time for the DCM Walking reference\n\n   // Outputs the average r_vrp location given two footstances\n  void get_average_rvrp(const Footstep & footstance_1, const Footstep & footstance_2, Eigen::Vector3d & average_rvrp);\n\n    // computes all the dcm states. Computation properly populates the dcm_ini_list and dcm_eos_list\n  void computeDCM_states();\n\n  // Sums up the total trajectory time and stores the result in t_end\n  void compute_total_trajectory_time();\n  double t_end = 0.0;\n\n  // computes the reference com trajectories by integration\n  void compute_reference_com();\n  double dt_local = 1e-3; // discretization factor used \n  // containers for the integrated reference CoM position and velocites\n  std::vector<Eigen::Vector3d> ref_com_pos;\n  std::vector<Eigen::Vector3d> ref_com_vel;\n\n  // computes the reference pelvis orientation.\n  void compute_reference_pelvis_ori();\n  Footstep initial_leftfoot_stance;\n  Footstep initial_rightfoot_stance;\n  Eigen::Quaterniond initial_ori;\n\n\n  // input: r_vrp_d_i - the desired virtual repelant point for the i-th step.\n  //        t_step    - the time interval to use for backwards integration\n  //        dcm_eos_i - the DCM state at the end of the i-th step. \n  // computes the step i's initial DCM state and the end-of-step i-1's dcm state. \n  // The computation is stored in the dcm_ini_list and dcm_eos_list. \n  Eigen::Vector3d computeDCM_ini_i(const Eigen::Vector3d & r_vrp_d_i, const double & t_step, const Eigen::Vector3d & dcm_eos_i);\n\n  // Computes the double support DCM boundary conditions for continuous double support trajectories\n  // step_index the boundary condition for the step index\n  // t_DS_{ini, end} the interpolation duration away from a Virtual repelant point. \n  Eigen::Vector3d computeDCM_iniDS_i(const int & step_index, const double t_DS_ini);\n  Eigen::Vector3d computeDCM_eoDS_i(const int & step_index, const double t_DS_end);\n  Eigen::Vector3d computeDCMvel_iniDS_i(const int & step_index, const double t_DS_ini);\n  Eigen::Vector3d computeDCMvel_eoDS_i(const int & step_index, const double t_DS_end);\n  Eigen::Vector3d computeDCMacc_iniDS_i(const int & step_index, const double t_DS_ini);\n  Eigen::Vector3d computeDCMacc_eoDS_i(const int & step_index, const double t_DS_end);\n\n  // Returns the DCM exponential interpolation for the requested step_index.\n  // time, t, is clamped between 0.0 and t_step.\n  Eigen::Vector3d get_DCM_exp(const int & step_index, const double & t);\n\n  // Returns the DCM velocity exponential interpolation for the requested step_index.\n  // time, t, is clamped between 0.0 and t_step.\n  Eigen::Vector3d get_DCM_vel_exp(const int & step_index, const double & t);\n\n  // Returns the DCM acceleration exponential interpolation for the requested step_index.\n  // time, t, is clamped between 0.0 and t_step.\n  Eigen::Vector3d get_DCM_acc_exp(const int & step_index, const double & t);\n\n  // Returns the DCM double support polynomial interpolation for the requested step_index.\n  // time, t, is clamped between 0.0 and t_step.\n  Eigen::Vector3d get_DCM_DS_poly(const int & step_index, const double & t);\n\n  // Returns the DCM double support velocity polynomial interpolation for the requested step_index.\n  // time, t, is clamped between 0.0 and t_step.\n  Eigen::Vector3d get_DCM_DS_vel_poly(const int & step_index, const double & t);\n\n\n  // Returns the DCM double support min jerk interpolation for the requested step_index.\n  // time, t, is clamped between 0.0 and t_step.\n  Eigen::Vector3d get_DCM_DS_minjerk(const int & step_index, const double & t);\n\n  // Returns the DCM double support velocity min jerk interpolation for the requested step_index.\n  // time, t, is clamped between 0.0 and t_step.\n  Eigen::Vector3d get_DCM_DS_vel_minjerk(const int & step_index, const double & t);\n\n\n  // Get the t_step for step i.\n  double get_t_step(const int & step_i);\n\n  // returns matrix P \\in R^{4x3}\n  // P = mat_coeff * [dcm_ini^T; \\dot{dcm}_ini^T; dcm_end^T; \\dot{dcm}_end]\n  // where mat_coeff \\in R^{4x4} and ^T denotes a vector transpose transpose.\n  // Ts is the duration in seconds\n  Eigen::MatrixXd polynomialMatrix(const double Ts,\n                                   const Eigen::Vector3d & dcm_ini, const Eigen::Vector3d & dcm_vel_ini,\n                                   const Eigen::Vector3d & dcm_end, const Eigen::Vector3d & dcm_vel_end);\n\n\n  int clampINT(int input, int low_bound, int upper_bound);\n  double clampDOUBLE(double input, double low_bound, double upper_bound);\n\n};\n\n#endif\n", "meta": {"hexsha": "16fa2efb39e7ef2539fabf873080ae84711fd6e0", "size": 13007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "PnC/PlannerSet/DCMPlanner/DCMPlanner.hpp", "max_stars_repo_name": "stevenjj/PnC", "max_stars_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T22:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T22:36:54.000Z", "max_issues_repo_path": "PnC/PlannerSet/DCMPlanner/DCMPlanner.hpp", "max_issues_repo_name": "stevenjj/PnC", "max_issues_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PnC/PlannerSet/DCMPlanner/DCMPlanner.hpp", "max_forks_repo_name": "stevenjj/PnC", "max_forks_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.4562737643, "max_line_length": 190, "alphanum_fraction": 0.7395248712, "num_tokens": 3353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.21970876858869998}}
{"text": "/*\n *  Sparse linear solver.\n *  Copyright (C) 2004 Bruno Levy\n *  Copyright (C) 2005-2015 Blender Foundation\n *\n *  This program is free software; you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation; either version 2 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program; if not, write to the Free Software\n *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\n *  If you modify this software, you should include a notice giving the\n *  name of the person performing the modification, the date of modification,\n *  and the reason for such modification.\n */\n\n#include \"linear_solver.h\"\n\n#include <Eigen/Sparse>\n\n#include <algorithm>\n#include <cassert>\n#include <cstdlib>\n#include <iostream>\n#include <vector>\n\n/* Eigen data structures */\n\ntypedef Eigen::SparseMatrix<double, Eigen::ColMajor> EigenSparseMatrix;\ntypedef Eigen::SparseLU<EigenSparseMatrix> EigenSparseLU;\ntypedef Eigen::VectorXd EigenVectorX;\ntypedef Eigen::Triplet<double> EigenTriplet;\n\n/* Linear Solver data structure */\n\nstruct LinearSolver\n{\n\tstruct Coeff\n\t{\n\t\tCoeff()\n\t\t{\n\t\t\tindex = 0;\n\t\t\tvalue = 0.0;\n\t\t}\n\n\t\tint index;\n\t\tdouble value;\n\t};\n\n\tstruct Variable\n\t{\n\t\tVariable()\n\t\t{\n\t\t\tmemset(value, 0, sizeof(value));\n\t\t\tlocked = false;\n\t\t\tindex = 0;\n\t\t}\n\n\t\tdouble value[4];\n\t\tbool locked;\n\t\tint index;\n\t\tstd::vector<Coeff> a;\n\t};\n\n\tenum State\n\t{\n\t\tSTATE_VARIABLES_CONSTRUCT,\n\t\tSTATE_MATRIX_CONSTRUCT,\n\t\tSTATE_MATRIX_SOLVED\n\t};\n\n\tLinearSolver(int num_rows_, int num_variables_, int num_rhs_, bool lsq_)\n\t{\n\t\tassert(num_variables_ > 0);\n\t\tassert(num_rhs_ <= 4);\n\n\t\tstate = STATE_VARIABLES_CONSTRUCT;\n\t\tm = 0;\n\t\tn = 0;\n\t\tsparseLU = NULL;\n\t\tnum_variables = num_variables_;\n\t\tnum_rhs = num_rhs_;\n\t\tnum_rows = num_rows_;\n\t\tleast_squares = lsq_;\n\n\t\tvariable.resize(num_variables);\n\t}\n\n\t~LinearSolver()\n\t{\n\t\tdelete sparseLU;\n\t}\n\n\tState state;\n\n\tint n;\n\tint m;\n\n\tstd::vector<EigenTriplet> Mtriplets;\n\tEigenSparseMatrix M;\n\tEigenSparseMatrix MtM;\n\tstd::vector<EigenVectorX> b;\n\tstd::vector<EigenVectorX> x;\n\n\tEigenSparseLU *sparseLU;\n\n\tint num_variables;\n\tstd::vector<Variable> variable;\n\n\tint num_rows;\n\tint num_rhs;\n\n\tbool least_squares;\n};\n\nLinearSolver *EIG_linear_solver_new(int num_rows, int num_columns, int num_rhs)\n{\n\treturn new LinearSolver(num_rows, num_columns, num_rhs, false);\n}\n\nLinearSolver *EIG_linear_least_squares_solver_new(int num_rows, int num_columns, int num_rhs)\n{\n\treturn new LinearSolver(num_rows, num_columns, num_rhs, true);\n}\n\nvoid EIG_linear_solver_delete(LinearSolver *solver)\n{\n\tdelete solver;\n}\n\n/* Variables */\n\nvoid EIG_linear_solver_variable_set(LinearSolver *solver, int rhs, int index, double value)\n{\n\tsolver->variable[index].value[rhs] = value;\n}\n\ndouble EIG_linear_solver_variable_get(LinearSolver *solver, int rhs, int index)\n{\n\treturn solver->variable[index].value[rhs];\n}\n\nvoid EIG_linear_solver_variable_lock(LinearSolver *solver, int index)\n{\n\tif (!solver->variable[index].locked) {\n\t\tassert(solver->state == LinearSolver::STATE_VARIABLES_CONSTRUCT);\n\t\tsolver->variable[index].locked = true;\n\t}\n}\n\nvoid EIG_linear_solver_variable_unlock(LinearSolver *solver, int index)\n{\n\tif (solver->variable[index].locked) {\n\t\tassert(solver->state == LinearSolver::STATE_VARIABLES_CONSTRUCT);\n\t\tsolver->variable[index].locked = false;\n\t}\n}\n\nstatic void linear_solver_variables_to_vector(LinearSolver *solver)\n{\n\tint num_rhs = solver->num_rhs;\n\n\tfor (int i = 0; i < solver->num_variables; i++) {\n\t\tLinearSolver::Variable* v = &solver->variable[i];\n\t\tif (!v->locked) {\n\t\t\tfor (int j = 0; j < num_rhs; j++)\n\t\t\t\tsolver->x[j][v->index] = v->value[j];\n\t\t}\n\t}\n}\n\nstatic void linear_solver_vector_to_variables(LinearSolver *solver)\n{\n\tint num_rhs = solver->num_rhs;\n\n\tfor (int i = 0; i < solver->num_variables; i++) {\n\t\tLinearSolver::Variable* v = &solver->variable[i];\n\t\tif (!v->locked) {\n\t\t\tfor (int j = 0; j < num_rhs; j++)\n\t\t\t\tv->value[j] = solver->x[j][v->index];\n\t\t}\n\t}\n}\n\n/* Matrix */\n\nstatic void linear_solver_ensure_matrix_construct(LinearSolver *solver)\n{\n\t/* transition to matrix construction if necessary */\n\tif (solver->state == LinearSolver::STATE_VARIABLES_CONSTRUCT) {\n\t\tint n = 0;\n\n\t\tfor (int i = 0; i < solver->num_variables; i++) {\n\t\t\tif (solver->variable[i].locked)\n\t\t\t\tsolver->variable[i].index = ~0;\n\t\t\telse\n\t\t\t\tsolver->variable[i].index = n++;\n\t\t}\n\n\t\tint m = (solver->num_rows == 0)? n: solver->num_rows;\n\n\t\tsolver->m = m;\n\t\tsolver->n = n;\n\n\t\tassert(solver->least_squares || m == n);\n\n\t\t/* reserve reasonable estimate */\n\t\tsolver->Mtriplets.clear();\n\t\tsolver->Mtriplets.reserve(std::max(m, n)*3);\n\n\t\tsolver->b.resize(solver->num_rhs);\n\t\tsolver->x.resize(solver->num_rhs);\n\n\t\tfor (int i = 0; i < solver->num_rhs; i++) {\n\t\t\tsolver->b[i].setZero(m);\n\t\t\tsolver->x[i].setZero(n);\n\t\t}\n\n\t\tlinear_solver_variables_to_vector(solver);\n\n\t\tsolver->state = LinearSolver::STATE_MATRIX_CONSTRUCT;\n\t}\n}\n\nvoid EIG_linear_solver_matrix_add(LinearSolver *solver, int row, int col, double value)\n{\n\tif (solver->state == LinearSolver::STATE_MATRIX_SOLVED)\n\t\treturn;\n\n\tlinear_solver_ensure_matrix_construct(solver);\n\n\tif (!solver->least_squares && solver->variable[row].locked);\n\telse if (solver->variable[col].locked) {\n\t\tif (!solver->least_squares)\n\t\t\trow = solver->variable[row].index;\n\n\t\tLinearSolver::Coeff coeff;\n\t\tcoeff.index = row;\n\t\tcoeff.value = value;\n\t\tsolver->variable[col].a.push_back(coeff);\n\t}\n\telse {\n\t\tif (!solver->least_squares)\n\t\t\trow = solver->variable[row].index;\n\t\tcol = solver->variable[col].index;\n\n\t\t/* direct insert into matrix is too slow, so use triplets */\n\t\tEigenTriplet triplet(row, col, value);\n\t\tsolver->Mtriplets.push_back(triplet);\n\t}\n}\n\n/* Right hand side */\n\nvoid EIG_linear_solver_right_hand_side_add(LinearSolver *solver, int rhs, int index, double value)\n{\n\tlinear_solver_ensure_matrix_construct(solver);\n\n\tif (solver->least_squares) {\n\t\tsolver->b[rhs][index] += value;\n\t}\n\telse if (!solver->variable[index].locked) {\n\t\tindex = solver->variable[index].index;\n\t\tsolver->b[rhs][index] += value;\n\t}\n}\n\n/* Solve */\n\nbool EIG_linear_solver_solve(LinearSolver *solver)\n{\n\t/* nothing to solve, perhaps all variables were locked */\n\tif (solver->m == 0 || solver->n == 0)\n\t\treturn true;\n\n\tbool result = true;\n\n\tassert(solver->state != LinearSolver::STATE_VARIABLES_CONSTRUCT);\n\n\tif (solver->state == LinearSolver::STATE_MATRIX_CONSTRUCT) {\n\t\t/* create matrix from triplets */\n\t\tsolver->M.resize(solver->m, solver->n);\n\t\tsolver->M.setFromTriplets(solver->Mtriplets.begin(), solver->Mtriplets.end());\n\t\tsolver->Mtriplets.clear();\n\n\t\t/* create least squares matrix */\n\t\tif (solver->least_squares)\n\t\t\tsolver->MtM = solver->M.transpose() * solver->M;\n\n\t\t/* convert M to compressed column format */\n\t\tEigenSparseMatrix& M = (solver->least_squares)? solver->MtM: solver->M;\n\t\tM.makeCompressed();\n\n\t\t/* perform sparse LU factorization */\n\t\tEigenSparseLU *sparseLU = new EigenSparseLU();\n\t\tsolver->sparseLU = sparseLU;\n\n\t\tsparseLU->compute(M);\n\t\tresult = (sparseLU->info() == Eigen::Success);\n\n\t\tsolver->state = LinearSolver::STATE_MATRIX_SOLVED;\n\t}\n\n\tif (result) {\n\t\t/* solve for each right hand side */\n\t\tfor (int rhs = 0; rhs < solver->num_rhs; rhs++) {\n\t\t\t/* modify for locked variables */\n\t\t\tEigenVectorX& b = solver->b[rhs];\n\n\t\t\tfor (int i = 0; i < solver->num_variables; i++) {\n\t\t\t\tLinearSolver::Variable *variable = &solver->variable[i];\n\n\t\t\t\tif (variable->locked) {\n\t\t\t\t\tstd::vector<LinearSolver::Coeff>& a = variable->a;\n\n\t\t\t\t\tfor (int j = 0; j < a.size(); j++)\n\t\t\t\t\t\tb[a[j].index] -= a[j].value*variable->value[rhs];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* solve */\n\t\t\tif (solver->least_squares) {\n\t\t\t\tEigenVectorX Mtb = solver->M.transpose() * b;\n\t\t\t\tsolver->x[rhs] = solver->sparseLU->solve(Mtb);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tEigenVectorX& b = solver->b[rhs];\n\t\t\t\tsolver->x[rhs] = solver->sparseLU->solve(b);\n\t\t\t}\n\n\t\t\tif (solver->sparseLU->info() != Eigen::Success)\n\t\t\t\tresult = false;\n\t\t}\n\n\t\tif (result)\n\t\t\tlinear_solver_vector_to_variables(solver);\n\t}\n\n\t/* clear for next solve */\n\tfor (int rhs = 0; rhs < solver->num_rhs; rhs++)\n\t\tsolver->b[rhs].setZero(solver->m);\n\n\treturn result;\n}\n\n/* Debugging */\n\nvoid EIG_linear_solver_print_matrix(LinearSolver *solver)\n{\n\tstd::cout << \"A:\" << solver->M << std::endl;\n\n\tfor (int rhs = 0; rhs < solver->num_rhs; rhs++)\n\t\tstd::cout << \"b \" << rhs << \":\" << solver->b[rhs] << std::endl;\n\n\tif (solver->MtM.rows() && solver->MtM.cols())\n\t\tstd::cout << \"AtA:\" << solver->MtM << std::endl;\n}\n\n", "meta": {"hexsha": "0fc4d39309b4c53e915b1d8ed87bcb5f7d462297", "size": 8780, "ext": "cc", "lang": "C++", "max_stars_repo_path": "intern/eigen/intern/linear_solver.cc", "max_stars_repo_name": "1-MillionParanoidTterabytes/Blender-2.79b-blackened", "max_stars_repo_head_hexsha": "e8d767324e69015aa66850d13bee7db1dc7d084b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-06-18T01:50:25.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-18T01:50:32.000Z", "max_issues_repo_path": "intern/eigen/intern/linear_solver.cc", "max_issues_repo_name": "1-MillionParanoidTterabytes/Blender-2.79b-blackened", "max_issues_repo_head_hexsha": "e8d767324e69015aa66850d13bee7db1dc7d084b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "intern/eigen/intern/linear_solver.cc", "max_forks_repo_name": "1-MillionParanoidTterabytes/Blender-2.79b-blackened", "max_forks_repo_head_hexsha": "e8d767324e69015aa66850d13bee7db1dc7d084b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9237057221, "max_line_length": 98, "alphanum_fraction": 0.6864464692, "num_tokens": 2476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21960809447816032}}
{"text": "#include <engine/Vectormath.hpp>\n#include <engine/Manifoldmath.hpp>\n#include <utility/Constants.hpp>\n#include <utility/Logging.hpp>\n#include <utility/Exception.hpp>\n\n#include <Eigen/Dense>\n\n#include <GenEigsSolver.h>  // Also includes <MatOp/DenseGenMatProd.h>\n#include <GenEigsRealShiftSolver.h>\n\n#include <array>\n\nnamespace C = Utility::Constants;\n\n#ifndef SPIRIT_USE_CUDA\n\nnamespace Engine\n{\n    namespace Manifoldmath\n    {\n        void project_parallel(vectorfield & vf1, const vectorfield & vf2)\n        {\n            vectorfield vf3 = vf1;\n            project_orthogonal(vf3, vf2);\n            // TODO: replace the loop with Vectormath Kernel\n            #pragma omp parallel for\n            for (unsigned int i = 0; i < vf1.size(); ++i)\n                vf1[i] -= vf3[i];\n        }\n\n        void project_orthogonal(vectorfield & vf1, const vectorfield & vf2)\n        {\n            scalar x = Vectormath::dot(vf1, vf2);\n            // TODO: replace the loop with Vectormath Kernel\n            #pragma omp parallel for\n            for (unsigned int i=0; i<vf1.size(); ++i)\n                vf1[i] -= x*vf2[i];\n        }\n\n        void invert_parallel(vectorfield & vf1, const vectorfield & vf2)\n        {\n            scalar x = Vectormath::dot(vf1, vf2);\n            // TODO: replace the loop with Vectormath Kernel\n            #pragma omp parallel for\n            for (unsigned int i=0; i<vf1.size(); ++i)\n                vf1[i] -= 2*x*vf2[i];\n        }\n        \n        void invert_orthogonal(vectorfield & vf1, const vectorfield & vf2)\n        {\n            vectorfield vf3 = vf1;\n            project_orthogonal(vf3, vf2);\n            // TODO: replace the loop with Vectormath Kernel\n            #pragma omp parallel for\n            for (unsigned int i = 0; i < vf1.size(); ++i)\n                vf1[i] -= 2 * vf3[i];\n        }\n\n        void project_tangential(vectorfield & vf1, const vectorfield & vf2)\n        {\n            #pragma omp parallel for\n            for (unsigned int i = 0; i < vf1.size(); ++i)\n                vf1[i] -= vf1[i].dot(vf2[i]) * vf2[i];\n        }\n\n        scalar dist_geodesic(const vectorfield & v1, const vectorfield & v2)\n        {\n            scalar dist = 0;\n            #pragma omp parallel for reduction(+:dist)\n            for (unsigned int i = 0; i < v1.size(); ++i)\n                dist += pow(Vectormath::angle(v1[i], v2[i]), 2);\n            return sqrt(dist);\n        }\n\n\n        /*\n        Calculates the 'tangent' vectors, i.e.in crudest approximation the difference between an image and the neighbouring\n        */\n        void Tangents(std::vector<std::shared_ptr<vectorfield>> configurations, const std::vector<scalar> & energies, std::vector<vectorfield> & tangents)\n        {\n            int noi = configurations.size();\n            int nos = (*configurations[0]).size();\n\n            for (int idx_img = 0; idx_img < noi; ++idx_img)\n            {\n                auto& image = *configurations[idx_img];\n\n                // First Image\n                if (idx_img == 0)\n                {\n                    auto& image_plus = *configurations[idx_img + 1];\n                    Vectormath::set_c_a( 1, image_plus, tangents[idx_img]);\n                    Vectormath::add_c_a(-1, image,      tangents[idx_img]);\n                }\n                // Last Image\n                else if (idx_img == noi - 1)\n                {\n                    auto& image_minus = *configurations[idx_img - 1];\n                    Vectormath::set_c_a( 1, image,       tangents[idx_img]);\n                    Vectormath::add_c_a(-1, image_minus, tangents[idx_img]);\n                }\n                // Images Inbetween\n                else\n                {\n                    auto& image_plus  = *configurations[idx_img + 1];\n                    auto& image_minus = *configurations[idx_img - 1];\n\n                    // Energies\n                    scalar E_mid = 0, E_plus = 0, E_minus = 0;\n                    E_mid   = energies[idx_img];\n                    E_plus  = energies[idx_img + 1];\n                    E_minus = energies[idx_img - 1];\n\n                    // Vectors to neighbouring images\n                    vectorfield t_plus(nos), t_minus(nos);\n\n                    Vectormath::set_c_a( 1, image_plus, t_plus);\n                    Vectormath::add_c_a(-1, image,      t_plus);\n\n                    Vectormath::set_c_a( 1, image,       t_minus);\n                    Vectormath::add_c_a(-1, image_minus, t_minus);\n\n                    // Near maximum or minimum\n                    if ((E_plus < E_mid && E_mid > E_minus) || (E_plus > E_mid && E_mid < E_minus))\n                    {\n                        // Get a smooth transition between forward and backward tangent\n                        scalar E_max = std::max(std::abs(E_plus - E_mid), std::abs(E_minus - E_mid));\n                        scalar E_min = std::min(std::abs(E_plus - E_mid), std::abs(E_minus - E_mid));\n\n                        if (E_plus > E_minus)\n                        {\n                            Vectormath::set_c_a(E_max, t_plus,  tangents[idx_img]);\n                            Vectormath::add_c_a(E_min, t_minus, tangents[idx_img]);\n                        }\n                        else\n                        {\n                            Vectormath::set_c_a(E_min, t_plus,  tangents[idx_img]);\n                            Vectormath::add_c_a(E_max, t_minus, tangents[idx_img]);\n                        }\n                    }\n                    // Rising slope\n                    else if (E_plus > E_mid && E_mid > E_minus)\n                    {\n                        Vectormath::set_c_a(1, t_plus,  tangents[idx_img]);\n                    }\n                    // Falling slope\n                    else if (E_plus < E_mid && E_mid < E_minus)\n                    {\n                        Vectormath::set_c_a(1, t_minus,  tangents[idx_img]);\n                        //tangents = t_minus;\n                        for (int i = 0; i < nos; ++i)\n                        {\n                            tangents[idx_img][i] = t_minus[i];\n                        }\n                    }\n                    // No slope(constant energy)\n                    else\n                    {\n                        Vectormath::set_c_a(1, t_plus,  tangents[idx_img]);\n                        Vectormath::add_c_a(1, t_minus, tangents[idx_img]);\n                    }\n                }\n\n                // Project tangents into tangent planes of spin vectors to make them actual tangents\n                project_tangential(tangents[idx_img], image);\n\n                // Normalise in 3N - dimensional space\n                Manifoldmath::normalize(tangents[idx_img]);\n\n            }// end for idx_img\n        }// end Tangents\n    }\n}\n\n#endif\n\nnamespace Engine\n{\n    namespace Manifoldmath\n    {\n        scalar norm(const vectorfield & vf)\n        {\n            scalar x = Vectormath::dot(vf, vf);\n            return std::sqrt(x);\n        }\n\n        void normalize(vectorfield & vf)\n        {\n            scalar sc = 1.0/norm(vf);\n            Vectormath::scale(vf, sc);\n        }\n\n\n        MatrixX tangential_projector(const vectorfield & image)\n        {\n            int nos = image.size();\n            int size = 3*nos;\n\n            // Get projection matrix M=1-S, blockwise S=x*x^T\n            MatrixX proj = MatrixX::Identity(size, size);\n            for (int i = 0; i < nos; ++i)\n            {\n                proj.block<3, 3>(3*i, 3*i) -= image[i] * image[i].transpose();\n            }\n\n            return proj;\n        }\n\n        // This gives an orthogonal matrix of shape (3N, 2N), meaning M^T=M^-1 or M^T*M=1.\n        // This assumes that the vectors of vf are normalized and that basis is 3N x 2N\n        // It can be used to transform a vector into or back from the tangent space of a\n        //      sphere w.r.t. euclidean 3N space.\n        // It is generated by column-wise normalization of the Jacobi matrix for the\n        //      transformation from (unit-)spherical coordinates to euclidean.\n        // It therefore consists of the local basis vectors of the spherical coordinates\n        //      of a unit sphere, represented in 3N, as the two columns of the matrix.\n        void tangent_basis_spherical(const vectorfield & vf, MatrixX & basis)\n        {\n            Vector3 tmp, etheta, ephi;\n            basis.setZero();\n            for (unsigned int i=0; i < vf.size(); ++i)\n            {\n                if (vf[i][2] > 1-1e-8)\n                {\n                    tmp = Vector3{1, 0, 0};\n                    basis.block<3,1>(3*i,2*i)   = (tmp - tmp.dot(vf[i])*vf[i]).normalized();\n                    tmp = Vector3{0, 1, 0};\n                    basis.block<3,1>(3*i,2*i+1) = (tmp - tmp.dot(vf[i])*vf[i]).normalized();\n                }\n                else if (vf[i][2] < -1+1e-8)\n                {\n                    tmp = Vector3{1, 0, 0};\n                    basis.block<3,1>(3*i,2*i)   = (tmp - tmp.dot(vf[i])*vf[i]).normalized();\n                    tmp = Vector3{0, -1, 0};\n                    basis.block<3,1>(3*i,2*i+1) = (tmp - tmp.dot(vf[i])*vf[i]).normalized();\n                }\n                else\n                {\n                    scalar rxy = std::sqrt( 1 - vf[i][2]*vf[i][2] );\n                    scalar z_rxy = vf[i][2] / rxy;\n\n                    // Note: these are not unit vectors, but derivatives!\n                    etheta = Vector3{  vf[i][0]*z_rxy, vf[i][1]*z_rxy, -rxy };\n                    ephi   = Vector3{ -vf[i][1]/rxy,   vf[i][0]/rxy,    0   };\n\n                    basis.block<3,1>(3*i,2*i)   = (etheta - etheta.dot(vf[i])*vf[i]).normalized();\n                    basis.block<3,1>(3*i,2*i+1) = (ephi   - ephi.dot(vf[i])*vf[i]).normalized();\n                }\n            }\n        }\n\n        // This calculates the basis via calculation of cross products\n        // This assumes that the vectors of vf are normalized and that basis is 3N x 2N\n        void tangent_basis_cross(const vectorfield & vf, MatrixX & basis)\n        {\n            basis.setZero();\n            for(int i=0; i < vf.size(); ++i)\n            {\n                if (std::abs(vf[i].z()) > 1-1e-8)\n                {\n                    basis.block<3,1>(3*i,2*i)   = Vector3{0,1,0}.cross(vf[i]).normalized();\n                    basis.block<3,1>(3*i,2*i+1) = vf[i].cross(basis.block<3,1>(3*i,2*i));\n                }\n                else\n                {\n                    basis.block<3,1>(3*i,2*i)   = Vector3{0,0,1}.cross(vf[i]).normalized();\n                    basis.block<3,1>(3*i,2*i+1) = vf[i].cross(basis.block<3,1>(3*i,2*i));\n                }\n            }\n        }\n\n        // This calculates the basis via orthonormalization to a random vector\n        // This assumes that the vectors of vf are normalized and that basis is 3N x 2N\n        void tangent_basis_righthanded(const vectorfield & vf, MatrixX & basis)\n        {\n            int size = vf.size();\n            basis.setZero();\n\n            // vf should be 3N\n            // basis should be 3N x 2N\n\n            // e1 and e2 will form a righthanded vectorset with the axis (though not orthonormal!)\n            Vector3 e1, e2, v1;\n            Vector3 ex{1,0,0}, ey{0,1,0}, ez{0,0,1};\n\n            for(int i=0; i < size; ++i)\n            {\n                auto& axis = vf[i];\n\n                // Choose orthogonalisation basis for Grahm-Schmidt\n                //      We will need two vectors with which the axis always forms the\n                //      same orientation (händigkeit des vektor-dreibeins)\n                // If axis_z=0 its in the xy-plane\n                //      the vectors should be: axis, ez, (axis x ez)\n                if (axis[2] == 0)\n                {\n                    e1 = ez;\n                    e2 = axis.cross(ez);\n                }\n                // Else its either above or below the xy-plane.\n                //      if its above the xy-plane, it points in z-direction\n                //      the vectors should be: axis, ex, -ey\n                else if (axis[2] > 0)\n                {\n                    e1 = ex;\n                    e2 = -ey;\n                }\n                //      if its below the xy-plane, it points in -z-direction\n                //      the vectors should be: axis, ex, ey\n                else if (axis[2] < 0)\n                {\n                    e1 = ex;\n                    e2 = ey;\n                }\n\n                // First vector: orthogonalize e1 w.r.t. axis\n                v1 = ( e1 - e1.dot(axis) * axis ).normalized();\n                basis.block<3,1>(3*i,2*i)   = v1;\n\n                // Second vector: orthogonalize e2 w.r.t. axis and v1\n                basis.block<3,1>(3*i,2*i+1) = ( e2 - e2.dot(axis)*axis - e2.dot(v1)*v1 ).normalized();\n            }\n        }\n\n\n        // This gives the Jacobian matrix for the transformation from (unit-)spherical\n        // to euclidean coordinates. It consists of the derivative vectors d/d_theta\n        // and d/d_phi as the two columns of the matrix.\n        void spherical_to_cartesian_jacobian(const vectorfield & vf, MatrixX & jacobian)\n        {\n            Vector3 tmp, etheta, ephi;\n            jacobian.setZero();\n            for (unsigned int i=0; i < vf.size(); ++i)\n            {\n                if (vf[i][2] > 1-1e-8)\n                {\n                    tmp = Vector3{1, 0, 0};\n                    jacobian.block<3,1>(3*i,2*i)   = (tmp - tmp.dot(vf[i])*vf[i]).normalized();\n                    tmp = Vector3{0, 1, 0};\n                    jacobian.block<3,1>(3*i,2*i+1) = (tmp - tmp.dot(vf[i])*vf[i]).normalized();\n                }\n                else if (vf[i][2] < -1+1e-8)\n                {\n                    tmp = Vector3{1, 0, 0};\n                    jacobian.block<3,1>(3*i,2*i)   = (tmp - tmp.dot(vf[i])*vf[i]).normalized();\n                    tmp = Vector3{0, -1, 0};\n                    jacobian.block<3,1>(3*i,2*i+1) = (tmp - tmp.dot(vf[i])*vf[i]).normalized();\n                }\n                else\n                {\n                    scalar rxy = std::sqrt( 1 - vf[i][2]*vf[i][2] );\n                    scalar z_rxy = vf[i][2] / rxy;\n\n                    // Note: these are not unit vectors, but derivatives!\n                    etheta = Vector3{  vf[i][0]*z_rxy, vf[i][1]*z_rxy, -rxy };\n                    ephi   = Vector3{ -vf[i][1],       vf[i][0],        0   };\n\n                    jacobian.block<3,1>(3*i,2*i)   = etheta - etheta.dot(vf[i])*vf[i];\n                    jacobian.block<3,1>(3*i,2*i+1) = ephi   - ephi.dot(vf[i])*vf[i];\n                }\n            }\n        }\n\n        // The Hessian matrix of the transformation from spherical to euclidean coordinates\n        void spherical_to_cartesian_hessian(const vectorfield & vf, MatrixX & gamma_x, MatrixX & gamma_y, MatrixX & gamma_z)\n        {\n            int nos = vf.size();\n            gamma_x.setZero();\n            gamma_y.setZero();\n            gamma_z.setZero();\n\n            for (unsigned int i=0; i < nos; ++i)\n            {\n                scalar z_rxy = vf[i][2] / std::sqrt(1+1e-6-vf[i][2]*vf[i][2]);\n\n                gamma_x.block<2,2>(2*i,2*i) << -vf[i][0],       -vf[i][1]*z_rxy,\n                                                -vf[i][1]*z_rxy, -vf[i][0];\n\n                gamma_y.block<2,2>(2*i,2*i) << -vf[i][1],        vf[i][0]*z_rxy,\n                                                vf[i][0]*z_rxy, -vf[i][1];\n\n                gamma_z.block<2,2>(2*i,2*i) << -vf[i][2], 0,\n                                                0,        0;\n            }\n        }\n\n        // The (2Nx2N) Christoffel symbols of the transformation from (unit-)spherical coordinates to euclidean\n        void spherical_to_cartesian_christoffel_symbols(const vectorfield & vf, MatrixX & gamma_theta, MatrixX & gamma_phi)\n        {\n            using std::cos;\n            using std::sin;\n            using std::acos;\n            using std::tan;\n            using std::atan2;\n\n            int nos = vf.size();\n            gamma_theta = MatrixX::Zero(2*nos, 2*nos);\n            gamma_phi   = MatrixX::Zero(2*nos, 2*nos);\n\n            for (unsigned int i=0; i < nos; ++i)\n            {\n                scalar theta = acos(vf[i][2]);\n                scalar phi   = atan2(vf[i][1], vf[i][0]);\n                scalar cot = 0;\n                if (std::abs(theta) > 1e-4)\n                    cot = -tan(C::Pi_2 + theta);\n\n                gamma_theta(2*i+1,2*i+1) = -sin(theta)*cos(theta);\n\n                gamma_phi(2*i+1,2*i)   = cot;\n                gamma_phi(2*i,2*i+1)   = cot;\n            }\n        }\n\n\n\n        void hessian_bordered(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & tangent_basis, MatrixX & hessian_out)\n        {\n            // Calculates a 3Nx3N matrix in the bordered Hessian approach and transforms it into the tangent basis,\n            // making the result a 2Nx2N matrix. The bordered Hessian's Lagrange multipliers assume a local extremum.\n\n            int nos = image.size();\n            MatrixX tmp_3N = hessian;\n\n            VectorX lambda(nos);\n            for (int i=0; i<nos; ++i)\n                lambda[i] = image[i].dot(gradient[i]);\n\n            for (int i=0; i<nos; ++i)\n            {\n                for (int j=0; j<3; ++j)\n                {\n                    tmp_3N(3*i+j,3*i+j) -= lambda(i);\n                }\n            }\n\n            // Calculate the basis transformation matrix\n            tangent_basis = MatrixX::Zero(3*nos, 2*nos);\n            tangent_basis_spherical(image, tangent_basis);\n\n            // Result is a 2Nx2N matrix\n            hessian_out = tangent_basis.transpose() * tmp_3N * tangent_basis;\n        }\n\n\n        void hessian_projected(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & tangent_basis, MatrixX & hessian_out)\n        {\n            // Calculates a 3Nx3N matrix in the projector approach and transforms it into the tangent basis,\n            // making the result a 2Nx2N matrix\n\n            int nos = image.size();\n            hessian_out.setZero();\n\n            // Calculate projector matrix\n            auto P = tangential_projector(image);\n            \n            // Calculate tangential projection of Hessian\n            hessian_out = P * hessian * P;\n\n            // Calculate correction terms\n            for (unsigned int i = 0; i < nos; ++i)\n            {\n                hessian_out.block<3, 3>(3*i, 3*i) -=    P.block<3, 3>(3*i, 3*i) * ( image[i].dot(gradient[i]) )\n                                                    + ( P.block<3, 3>(3*i, 3*i) * gradient[i] ) * image[i].transpose();\n            }\n\n            // Calculate the basis transformation matrix\n            tangent_basis = MatrixX::Zero(3*nos, 2*nos);\n            tangent_basis_spherical(image, tangent_basis);\n\n            // Result is a 2Nx2N matrix\n            hessian_out = tangent_basis.transpose() * hessian_out * tangent_basis;\n        }\n\n\n        void hessian_weingarten(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & tangent_basis, MatrixX & hessian_out)\n        {\n            // Calculates a 3Nx3N matrix in the Weingarten map approach and transforms it into the tangent basis,\n            // making the result a 2Nx2N matrix\n\n            int nos = image.size();\n            hessian_out.setZero();\n\n            // Calculate projector matrix\n            auto P = tangential_projector(image);\n            \n            // Calculate tangential projection of Hessian\n            hessian_out = P * hessian;\n\n            // Add the Weingarten map\n            for (unsigned int i = 0; i < nos; ++i)\n            {\n                MatrixX proj = MatrixX::Identity(3, 3);\n                hessian_out.block<3, 3>(3*i, 3*i) -=  MatrixX::Identity(3, 3) * image[i].dot(gradient[i]);\n            }\n\n            // Calculate the basis transformation matrix\n            tangent_basis = MatrixX::Zero(3*nos, 2*nos);\n            tangent_basis_spherical(image, tangent_basis);\n\n            // Result is a 2Nx2N matrix\n            hessian_out = tangent_basis.transpose() * hessian_out * tangent_basis;\n        }\n\n\n        void hessian_spherical(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & hessian_out)\n        {\n            // Calculates a 2Nx2N hessian matrix containing second order spherical derivatives\n\n            int nos = image.size();\n\n            MatrixX jacobian   = MatrixX::Zero(3*nos, 2*nos);\n            MatrixX sph_hess_x = MatrixX::Zero(2*nos, 2*nos);\n            MatrixX sph_hess_y = MatrixX::Zero(2*nos, 2*nos);\n            MatrixX sph_hess_z = MatrixX::Zero(2*nos, 2*nos);\n\n            // Calculate coordinate transformation jacobian\n            Engine::Manifoldmath::spherical_to_cartesian_jacobian(image, jacobian);\n            \n            // Calculate coordinate transformation Hessian\n            Engine::Manifoldmath::spherical_to_cartesian_hessian(image, sph_hess_x, sph_hess_y, sph_hess_z);\n            \n            // Calculate transformed Hessian\n            hessian_out = jacobian.transpose() * hessian * jacobian;\n            for (int i=0; i < nos; ++i)\n            {\n                hessian_out.block<2,2>(2*i, 2*i) += gradient[i][0] * sph_hess_x.block<2,2>(2*i, 2*i)\n                                                    + gradient[i][1] * sph_hess_y.block<2,2>(2*i, 2*i)\n                                                    + gradient[i][2] * sph_hess_z.block<2,2>(2*i, 2*i);\n            }\n\n        }\n\n\n        void hessian_covariant(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & hessian_out)\n        {\n            // Calculates a 2Nx2N covariant hessian matrix containing second order spherical derivatives\n            // and correction terms (containing Christoffel symbols)\n            \n            int nos = image.size();\n\n            // Calculate coordinate transformation jacobian\n            MatrixX jacobian(3*nos, 2*nos);\n            Engine::Manifoldmath::spherical_to_cartesian_jacobian(image, jacobian);\n\n            // Calculate the gradient in spherical coordinates\n            Eigen::Ref<const VectorX> grad = Eigen::Map<const VectorX>(gradient[0].data(), 3 * nos);\n            VectorX gradient_spherical = jacobian.transpose() * grad;\n\n            // Calculate the Hessian in spherical coordinates\n            hessian_spherical(image, gradient, hessian, hessian_out);\n\n            // Calculate the Christoffel symbols for spherical coordinates\n            MatrixX christoffel_theta = MatrixX::Zero(2*nos, 2*nos);\n            MatrixX christoffel_phi   = MatrixX::Zero(2*nos, 2*nos);\n            Engine::Manifoldmath::spherical_to_cartesian_christoffel_symbols(image, christoffel_theta, christoffel_phi);\n\n            // Calculate the covariant Hessian\n            for (int i=0; i < nos; ++i)\n            {\n                hessian_out.block<2,2>(2*i, 2*i) -= gradient_spherical[2*i]   * christoffel_theta.block<2,2>(2*i, 2*i)\n                                                    + gradient_spherical[2*i+1] * christoffel_phi.block<2,2>(2*i, 2*i);\n            }\n        }\n\n    }\n}", "meta": {"hexsha": "8674022d4f52c1239c37bd7d10c447d44b1b7629", "size": 23113, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "core/src/engine/Manifoldmath.cpp", "max_stars_repo_name": "ddkn/spirit", "max_stars_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2020-08-24T22:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T06:54:54.000Z", "max_issues_repo_path": "core/src/engine/Manifoldmath.cpp", "max_issues_repo_name": "ddkn/spirit", "max_issues_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/src/engine/Manifoldmath.cpp", "max_forks_repo_name": "ddkn/spirit", "max_forks_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-05T13:24:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T07:46:47.000Z", "avg_line_length": 40.6919014085, "max_line_length": 161, "alphanum_fraction": 0.4904599143, "num_tokens": 5771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.3775406828054583, "lm_q1q2_score": 0.21946557123582147}}
{"text": "#include <algorithm>\n#include <cmath>\n#include <cstring>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iterator>\n#include <string>\n#include <vector>\n#include <map>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/program_options.hpp>\n\nnamespace po = boost::program_options;\n\nusing namespace std;\nusing namespace boost;\n\nclass Corpus {\npublic:\n    string text;\n    dynamic_bitset<> utt_boundaries;\n    dynamic_bitset<> boundaries;\n    map<char, double> p_phonemes;\n\n    Corpus(string path)\n    {\n        load_file({path});\n        compute_p_phonemes();\n    }\n\n    Corpus(string path, string trained_path,\n           dynamic_bitset<> &trained_boundaries)\n    {\n        load_file({path, trained_path});\n        compute_p_phonemes();\n\n        // set the trained boundaries as unchangable utterance boundaries\n        trained_boundaries.resize(text.size() + 1, false);\n        utt_boundaries |= trained_boundaries;\n    }\n\n    double p0(string word, double p_hash=0.5)\n    {\n        double p = 1;\n        for (char ph : word)\n            p *= p_phonemes[ph];\n\n        return p_hash * pow(1 - p_hash, word.size() - 1) * p;\n    }\n\n    vector<string> get_words()\n    {\n        vector<string> words;\n        dynamic_bitset<> bounds = utt_boundaries | boundaries;\n\n        for (int i = 0; i < text.size(); ++i) {\n            if (bounds[i])\n                words.push_back(string());\n\n            words.back().append(1, text[i]);\n        }\n\n        return words;\n    }\n\nprivate:\n    virtual void load_file(const vector<string> &paths)\n    {\n        string line;\n        stringstream text_stream;\n        vector<int> utt_indices = {0};\n\n        for (string path : paths) {\n            fstream in(path);\n\n            while (getline(in, line)) {\n                text_stream << line;\n                utt_indices.push_back(utt_indices.back() + line.size());\n            }\n\n            in.close();\n        }\n\n\n        text = text_stream.str();\n\n        utt_boundaries = dynamic_bitset<>(text.size() + 1);\n        boundaries = dynamic_bitset<>(text.size() + 1);\n\n        for (int index : utt_indices) {\n            utt_boundaries[index] = 1;\n        }\n    }\n\n    void compute_p_phonemes()\n    {\n        for (char phoneme : text) {\n            // only compute if the char isn't in the map yet\n            if (p_phonemes.find(phoneme) == p_phonemes.end())\n                p_phonemes[phoneme] = count(text.begin(), text.end(), phoneme) /\n                    (double)text.size();\n        }\n    }\n};\n\nmap<string, int> histogram(const vector<string> &vec)\n{\n    map<string, int> counts;\n    vector<string> unique_words;\n\n    unique_copy(vec.begin(), vec.end(), back_inserter(unique_words));\n\n    for (const string &word : unique_words) {\n        if (counts.find(word) == counts.end())\n            counts[word] = 1;\n        else\n            counts[word] += 1;\n    }\n\n    return counts;\n}\n\nvoid find_enclosing_boundaries(dynamic_bitset<> bounds, int i,\n                               int *lower, int *upper)\n{\n    *lower = i - 1;\n    while (!bounds[*lower])\n        *lower -= 1;\n\n    *upper = i + 1;\n    while (!bounds[*upper])\n        *upper += 1;\n}\n\nvoid gibbs_iteration(Corpus &corpus, double rho=2.0, double alpha=0.5,\n                     double p_hash=0.5)\n{\n    dynamic_bitset<> bounds = corpus.utt_boundaries | corpus.boundaries;\n    vector<string> words = corpus.get_words();\n    map<string, int> word_counts = histogram(words);\n\n    for (int i = 0; i < corpus.text.size(); ++i) {\n        char phoneme = corpus.text[i];\n\n        if (corpus.utt_boundaries[i])\n            continue;\n\n        int lower, upper;\n        find_enclosing_boundaries(bounds, i, &lower, &upper);\n\n        string w1 = corpus.text.substr(lower, (upper - lower));\n        string w2 = corpus.text.substr(lower, (i - lower));\n        string w3 = corpus.text.substr(i, (upper - i));\n\n        double n_;\n        if (!bounds[i])\n            n_ = words.size();\n        else\n            n_ = words.size() - 1;\n\n        double n_dollar = corpus.utt_boundaries.count() - 1;\n        double nu = corpus.utt_boundaries[upper] ? n_dollar : n_ - n_dollar;\n\n        double p_h1_factor1;\n        if (!bounds[i])\n            p_h1_factor1 = (word_counts[w1] - 1 + alpha * corpus.p0(w1, p_hash)) / (n_ + alpha);\n        else\n            p_h1_factor1 = (word_counts[w1] + alpha * corpus.p0(w1, p_hash)) / (n_ + alpha);\n\n        double p_h1_factor2 = (nu + rho/2) / (n_ + rho);\n\n        double p_h2_factor1, p_h2_factor3;\n        if (!bounds[i]) {\n            p_h2_factor1 = (word_counts[w2] + alpha * corpus.p0(w2, p_hash)) / (n_ + alpha);\n            p_h2_factor3 = ((word_counts[w3] + (w2 == w3 ? 1 : 0) + alpha *\n                             corpus.p0(w3, p_hash)) / (n_ + 1 + alpha));\n        } else {\n            p_h2_factor1 = (word_counts[w2] - 1 + alpha * corpus.p0(w2, p_hash)) / (n_ + alpha);\n            p_h2_factor3 = ((word_counts[w3] - 1 + (w2 == w3 ? 1 : 0) + alpha *\n                             corpus.p0(w3, p_hash)) / (n_ + 1 + alpha));\n        }\n\n        double p_h2_factor2 = (n_ - n_dollar + rho/2) / (n_ + rho);\n        double p_h2_factor4 = ((nu + (w2 == w3 ? 1 : 0) + rho/2) / (n_ + 1 + rho));\n\n        double p_h1 = p_h1_factor1 * p_h1_factor2;\n        double p_h2 = p_h2_factor1 * p_h2_factor2 * p_h2_factor3 * p_h2_factor4;\n\n        if (p_h2 > p_h1)\n            corpus.boundaries[i] = 1;\n        else\n            corpus.boundaries[i] = 0;\n    }\n}\n\nvoid write_boundaries(const Corpus &corpus, string filename)\n{\n    ofstream out(filename);\n    out << \"[\";\n\n    for (int i = 0; i < corpus.text.size(); ++i) {\n        if (i != 0)\n            out << \", \";\n        out << corpus.boundaries[i];\n    }\n\n    out << \"]\";\n    out.close();\n}\n\ndynamic_bitset<> read_boundaries(string path)\n{\n    fstream in(path);\n    string line;\n    getline(in, line);\n    in.close();\n\n    auto end_iter = remove_if(line.begin(), line.end(),\n                              [](char ch) {return !(ch == '1' || ch == '0');});\n    line.erase(end_iter, line.end());\n\n    return dynamic_bitset<>(line);\n}\n\nstring generate_filepath(const string &out_dir, double alpha, double p_hash, int i=-1)\n{\n    stringstream s;\n    s << out_dir << \"/\";\n    if (i >= 0)\n        s << \"iter_\" << i << \"_\";\n    s << alpha << \"_\" << p_hash << \".txt\";\n\n    return s.str();\n}\n\nint main(int argc, char *argv[])\n{\n    string out_dir;\n    string train_path;\n    string test_path;\n    string boundaries;\n    double alpha;\n    double p_hash;\n    vector<int> eval_points;\n\n    po::options_description desc(\"Usage\");\n    desc.add_options()\n        (\"alpha,a\", po::value<double>(&alpha)->default_value(0.5), \"alpha parameter\")\n        (\"p_hash,ph\", po::value<double>(&p_hash)->default_value(0.5), \"p# parameter\")\n        (\"out_dir\", po::value<string>(&out_dir), \"path to write output to\")\n        (\"train_path\", po::value<string>(&train_path), \"path to load training data\")\n        (\"test_path\", po::value<string>(&test_path), \"path to load test data\")\n        (\"test\", \"apply a learned model to test data (requires test_path and boundaries)\")\n        (\"help\", \"print usage information\")\n        (\"boundaries\", po::value<string>(&boundaries), \"path to a learned set of boundaries\")\n        (\",n\", po::value<vector<int> >(&eval_points)->multitoken(), \"points to evaluate\");\n\n    po::variables_map opts;\n    po::store(po::parse_command_line(argc, argv, desc), opts);\n    po::notify(opts);\n\n    if (opts.count(\"help\")) {\n        cout << desc << endl;\n        return 0;\n    }\n\n    string out_path = generate_filepath(out_dir, alpha, p_hash);\n\n    Corpus *corpus;\n    if (opts.count(\"test\")) {\n        cout << \"Testing\" << endl;\n        auto bounds = read_boundaries(boundaries);\n        corpus = new Corpus(train_path, test_path, bounds);\n    } else {\n        corpus = new Corpus(train_path);\n    }\n\n    // calculate the maximum iteration\n    int i_max = *max_element(eval_points.begin(), eval_points.end());\n\n    for (int i = 0; i < i_max; ++i) {\n        cout << \"Iteration \" << i << endl;\n        gibbs_iteration(*corpus, 2, alpha, p_hash);\n\n        if (find(eval_points.begin(), eval_points.end(), i) != eval_points.end()) {\n            string iterpath = generate_filepath(out_dir, alpha, p_hash, i);\n            write_boundaries(*corpus, iterpath);\n        }\n    }\n\n    write_boundaries(*corpus, out_path);\n\n    return 0;\n}\n", "meta": {"hexsha": "6fb857fd2663448e40a8f71861fc58d7205787e6", "size": 8348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "goldwater/segment.cpp", "max_stars_repo_name": "wenkokke/UoE-MT3-NMT", "max_stars_repo_head_hexsha": "242a4d8221f8a0462c5c23c057d954e18c88fc34", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "goldwater/segment.cpp", "max_issues_repo_name": "wenkokke/UoE-MT3-NMT", "max_issues_repo_head_hexsha": "242a4d8221f8a0462c5c23c057d954e18c88fc34", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "goldwater/segment.cpp", "max_forks_repo_name": "wenkokke/UoE-MT3-NMT", "max_forks_repo_head_hexsha": "242a4d8221f8a0462c5c23c057d954e18c88fc34", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2027027027, "max_line_length": 96, "alphanum_fraction": 0.5609726881, "num_tokens": 2209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.21942022755547622}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2010 Roland Lichters\n Copyright (C) 2014 Jose Aparicio\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <qlo/qladdindefines.hpp>\n#include <qlo/credit.hpp>\n#include <qlo/enumerations/factories/termstructuresfactory.hpp>\n\n#include <ql/instruments/stock.hpp>\n#include <ql/quote.hpp>\n#include <ql/currencies/europe.hpp>\n#include <ql/time/daycounter.hpp>\n#include <ql/time/daycounters/actual360.hpp>\n#include <ql/termstructures/credit/interpolatedhazardratecurve.hpp>\n#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>\n#include <ql/termstructures/credit/piecewisedefaultcurve.hpp>\n#include <ql/math/interpolations/backwardflatinterpolation.hpp>\n#include <ql/math/interpolations/loginterpolation.hpp>\n#include <ql/pricingengines/credit/midpointcdsengine.hpp>\n\n#include <ql/experimental/credit/riskybond.hpp>\n#include <ql/experimental/credit/syntheticcdo.hpp>\n#include <ql/experimental/credit/midpointcdoengine.hpp>\n#include <ql/experimental/credit/nthtodefault.hpp>\n#include <ql/experimental/credit/integralntdengine.hpp>\n\n#include <boost/algorithm/string/case_conv.hpp>\n#include <boost/make_shared.hpp>\n\n#include <ql/settings.hpp>\n\nusing boost::algorithm::to_upper_copy;\n\nnamespace QuantLibAddin {\n\n    Issuer::Issuer(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const boost::shared_ptr<QuantLib::DefaultProbabilityTermStructure>& dfts,\n            const boost::shared_ptr<QuantLib::DefaultEventSet>& evtSet,\n            bool permanent\n        )\n        : ObjectHandler::LibraryObject<QuantLib::Issuer>(properties, permanent) {\n\n        std::vector<QuantLib::Issuer::key_curve_pair> curves(1, std::make_pair(\n            QuantLib::NorthAmericaCorpDefaultKey(QuantLib::EURCurrency(),\n                                                     QuantLib::SeniorSec, \n                                                     QuantLib::Period(),\n                                                     1. // amount threshold\n                                                     ),\n            QuantLib::Handle<QuantLib::DefaultProbabilityTermStructure>(dfts)\n        ));\n        libraryObject_ = boost::shared_ptr<QuantLib::Issuer>(new QuantLib::Issuer(curves, *evtSet));\n    }\n\n    DefaultEventSet::DefaultEventSet(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const std::string& eventType,\n            const QuantLib::Date& eventDate,\n            const QuantLib::Currency& cur,\n            QuantLib::Seniority sen,\n            const QuantLib::Date& settlementDate,\n            QuantLib::Real settledRecovery,\n            bool permanent\n        ) \n    : ObjectHandler::LibraryObject<QuantLib::DefaultEventSet>(properties, permanent) {\n        // if no match return empty set\n        libraryObject_ = boost::shared_ptr<QuantLib::DefaultEventSet>(new QuantLib::DefaultEventSet());\n\n        // only one recovery parsed by now; bankruptcy events need the whole\n        //  set or they fail to construct.\n        std::map<QuantLib::Seniority, QuantLib::Real> rrs;\n        rrs.insert(std::pair<QuantLib::Seniority, QuantLib::Real>(sen, settledRecovery));\n        if(eventType==std::string(\"FailureToPayEvent\")) {\n            libraryObject_->insert(boost::shared_ptr<QuantLib::FailureToPayEvent> (\n                new QuantLib::FailureToPayEvent(eventDate, cur, sen, 1.e7, \n                //implSettlemt, \n                settlementDate,\n                rrs)));\n        }else if(eventType==std::string(\"BankruptcyEvent\")){\n            libraryObject_->insert(boost::shared_ptr<QuantLib::BankruptcyEvent> (\n                new QuantLib::BankruptcyEvent(eventDate, cur, sen, \n                settlementDate,\n                rrs)));\n        }\n    }\n\n    /* Code essentially copied from QuantLibAddIn::SimpleQuote. \n         Same considerations mentioned there apply. Here the\n         Seniority of the quote is considered a fixed \n         property, not a market value.\n    */\n    RecoveryRateQuote::RecoveryRateQuote(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            QuantLib::Seniority sen,\n            QuantLib::Real value,\n            bool permanent) : Quote(properties, permanent) {\n        libraryObject_ = recoveryQuote_ = boost::shared_ptr<QuantLib::RecoveryRateQuote>(\n            new QuantLib::RecoveryRateQuote(value, sen));\n    }\n\n\n   // CreditDefaultSwap::CreditDefaultSwap(\n   //           const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n   //           QuantLib::Protection::Side side,\n   //           QuantLib::Real notional,\n   //           QuantLib::Rate upfront,\n   //           QuantLib::Rate spread,\n   //           const boost::shared_ptr<QuantLib::Schedule>& schedule,\n   //           QuantLib::BusinessDayConvention paymentConvention,\n   //           const QuantLib::DayCounter& dayCounter,\n   //           bool settlesAccrual,\n   //           bool paysAtDefaultTime,\n   //           const QuantLib::Date& protectionStart,\n   //           const QuantLib::Date& upfrontDate,\n   //           bool permanent)\n   //     : Instrument(properties, permanent) {\n\t\t\t//// dirty way to decide if this is constructed through a run only version\n\t\t\t//if(upfrontDate == QuantLib::Null<QuantLib::Date>() && upfront == 0.) {\n\t\t\t//\tlibraryObject_ = boost::shared_ptr<QuantLib::CreditDefaultSwap>(\n\t\t\t//\t\t\t\tnew QuantLib::CreditDefaultSwap(side,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tnotional,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tspread,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t*schedule,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tpaymentConvention,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tdayCounter,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tsettlesAccrual,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tpaysAtDefaultTime,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tprotectionStart,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tboost::shared_ptr<QuantLib::Claim>()));\n\t\t\t//}else{\n\t\t\t//\tlibraryObject_ = boost::shared_ptr<QuantLib::CreditDefaultSwap>(\n\t\t\t//\t\t\t\tnew QuantLib::CreditDefaultSwap(side,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tnotional,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tupfront,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tspread,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\t*schedule,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tpaymentConvention,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tdayCounter,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tsettlesAccrual,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tpaysAtDefaultTime,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tprotectionStart,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tupfrontDate,\n\t\t\t//\t\t\t\t\t\t\t\t\t\t\t\tboost::shared_ptr<QuantLib::Claim>()));\n   //         }\n   // }\n   // \n    MidPointCdsEngine::MidPointCdsEngine(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const QuantLib::Handle<QuantLib::DefaultProbabilityTermStructure>& defaultTS,\n            QuantLib::Real recoveryRate,\n            const QuantLib::Handle<QuantLib::YieldTermStructure>& yieldTS,\n            bool permanent) \n        : PricingEngine(properties, permanent) {\n        libraryObject_ = boost::shared_ptr<QuantLib::PricingEngine>(new\n              QuantLib::MidPointCdsEngine(defaultTS, recoveryRate, yieldTS));\n    }\n\n\n\n    SpreadCdsHelper::SpreadCdsHelper(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const QuantLib::Handle<QuantLib::Quote>& quote,\n            const QuantLib::Period& period,\n            QuantLib::Natural settlementDays,\n            const QuantLib::Calendar& calendar,\n            QuantLib::Frequency frequency,\n            QuantLib::BusinessDayConvention paymentConvention,\n            QuantLib::DateGeneration::Rule rule,\n            const QuantLib::DayCounter& dayCounter,\n            QuantLib::Real recoveryRate,\n            const QuantLib::Handle<QuantLib::YieldTermStructure>& yieldTS,\n            bool settlesAccrual,\n            bool paysAtDefaultTime,\n            bool permanent) : DefaultProbabilityHelper(properties, permanent) {\n\n        libraryObject_ = boost::shared_ptr<QuantLib::DefaultProbabilityHelper>(new\n\t\t       QuantLib::SpreadCdsHelper(quote,\n\t\t\t\t\t\t period,\n\t\t\t\t\t\t settlementDays,\n\t\t\t\t\t\t calendar,\n\t\t\t\t\t\t frequency,\n\t\t\t\t\t\t paymentConvention,\n\t\t\t\t\t\t rule,\n\t\t\t\t\t\t dayCounter,\n\t\t\t\t\t\t recoveryRate,\n\t\t\t\t\t\t yieldTS,\n\t\t\t\t\t\t settlesAccrual,\n\t\t\t\t\t\t paysAtDefaultTime));\n    }\n\n    UpfrontCdsHelper::UpfrontCdsHelper(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const QuantLib::Handle<QuantLib::Quote>& quote,\n            QuantLib::Rate runningSpread,\n            const QuantLib::Period& period,\n            QuantLib::Natural settlementDays,\n            const QuantLib::Calendar& calendar,\n            QuantLib::Frequency frequency,\n            QuantLib::BusinessDayConvention paymentConvention,\n            QuantLib::DateGeneration::Rule rule,\n            const QuantLib::DayCounter& dayCounter,\n            QuantLib::Real recoveryRate,\n            const QuantLib::Handle<QuantLib::YieldTermStructure>& yieldTS,\n            QuantLib::Natural upfrontSettlementDays,\n            bool settlesAccrual,\n            bool paysAtDefaultTime,\n            bool permanent) : DefaultProbabilityHelper(properties, permanent) {\n        libraryObject_ = boost::shared_ptr<QuantLib::DefaultProbabilityHelper>(new\n\t\t       QuantLib::UpfrontCdsHelper(quote,\n                                          runningSpread,\n                                          period,\n                                          settlementDays,\n                                          calendar,\n                                          frequency,\n                                          paymentConvention,\n                                          rule,\n                                          dayCounter,\n                                          recoveryRate,\n                                          yieldTS,\n                                          upfrontSettlementDays,\n                                          settlesAccrual,\n                                          paysAtDefaultTime));\n    }\n\n    HazardRateCurve::HazardRateCurve(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const std::vector<QuantLib::Date>& dates,\n            const std::vector<QuantLib::Rate>& hazardRates,\n            const QuantLib::DayCounter& dayCounter,\n            bool permanent) \n        : DefaultProbabilityTermStructure(properties, permanent) {\n        QL_REQUIRE(!dates.empty(), \"no input dates given\");\n        QL_REQUIRE(dates.size() == hazardRates.size(), \n                   \"vector sizes differ\");\n        libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(\n        new QuantLib::InterpolatedHazardRateCurve<QuantLib::BackwardFlat>(\n \t\t\t\t dates, hazardRates, dayCounter));\n    }\n\n    PiecewiseHazardRateCurve::PiecewiseHazardRateCurve(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const std::vector<boost::shared_ptr<QuantLib::DefaultProbabilityHelper> >& helpers,\n            const QuantLib::DayCounter& dayCounter,\n            const QuantLib::Calendar& calendar,\n            const std::string& interpolator,\n            QuantLib::Real accuracy,\n            bool permanent) \n        : DefaultProbabilityTermStructure(properties, permanent) {\n\n        if(interpolator == std::string(\"LINEAR\")){\n            libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(new\n                   QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate,\n                        QuantLib::Linear>(\n                            0, \n                            calendar,\n                            helpers, \n                            dayCounter));\n        }else if(interpolator == std::string(\"BACKWARDFLAT\")) {\n            libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(new\n                   QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate,\n                        QuantLib::BackwardFlat>(\n                            0, \n                            calendar,\n                            helpers, \n                            dayCounter));\n        }else{\n            QL_FAIL(\"Unrecognised interpolator\");\n        }\n\n        libraryObject_->enableExtrapolation();\n    }\n\n    // ptr type check here would correspond to template spez in the  \n    //   subscribers factory solution.\n    const std::vector<QuantLib::Date>& PiecewiseHazardRateCurve::dates() const {\n        typedef QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate, QuantLib::BackwardFlat> flat_curve;\n        typedef QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate, QuantLib::Linear> lin_curve;\n        boost::shared_ptr<flat_curve> ptrBF =\n            boost::dynamic_pointer_cast<flat_curve>(libraryObject_);\n        if(ptrBF) return ptrBF->dates();\n        boost::shared_ptr<lin_curve> ptrLIN =\n            boost::dynamic_pointer_cast<lin_curve>(libraryObject_);\n        if(ptrLIN) return ptrLIN->dates();\n        QL_FAIL(\"Unable to cast default probability term structure.\");\n    }\n\n    const std::vector<QuantLib::Real>& PiecewiseHazardRateCurve::data() const {\n        typedef QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate, QuantLib::BackwardFlat> flat_curve;\n        typedef QuantLib::PiecewiseDefaultCurve<QuantLib::HazardRate, QuantLib::Linear> lin_curve;\n        boost::shared_ptr<flat_curve> ptrBF =\n            boost::dynamic_pointer_cast<flat_curve>(libraryObject_);\n        if(ptrBF) return ptrBF->data();\n        boost::shared_ptr<lin_curve> ptrLIN =\n            boost::dynamic_pointer_cast<lin_curve>(libraryObject_);\n        if(ptrLIN) return ptrLIN->data();\n        QL_FAIL(\"Unable to cast default probability term structure.\");\n        }        \n\n\n    PiecewiseFlatForwardCurve::PiecewiseFlatForwardCurve(\n            const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n            const QuantLib::Date& referenceDate,\n            const std::vector<boost::shared_ptr<QuantLib::RateHelper> >& helpers,\n            const QuantLib::DayCounter& dayCounter,\n            QuantLib::Real accuracy,\n            bool permanent)\n        : YieldTermStructure(properties, permanent) {\n        libraryObject_ = boost::shared_ptr<QuantLib::Extrapolator>(new\n               QuantLib::PiecewiseYieldCurve<QuantLib::Discount,QuantLib::LogLinear>(referenceDate, helpers, dayCounter));\n    }\n\n\n\n    RiskyFixedBond::RiskyFixedBond(\n        const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n        std::string name,\n        QuantLib::Currency ccy,\n        QuantLib::Real recoveryRate,\n        QuantLib::Handle<QuantLib::DefaultProbabilityTermStructure> defaultTS,\n        const boost::shared_ptr<QuantLib::Schedule>& schedule,\n        QuantLib::Real rate,\n        QuantLib::DayCounter dayCounter,\n        QuantLib::BusinessDayConvention paymentConvention,\n        QuantLib::Real notional,\n        QuantLib::Handle<QuantLib::YieldTermStructure> yieldTS,\n        QuantLib::Date npvDate, // unused by now\n        bool permanent)\n    : Instrument(properties, permanent) {\n\n        std::vector<QuantLib::Real> notionals(1,notional);\n\n        libraryObject_ = boost::shared_ptr<QuantLib::RiskyFixedBond>(\n            new QuantLib::RiskyFixedBond(\n                    name,ccy,recoveryRate,defaultTS,*schedule,rate,dayCounter,\n                    paymentConvention,notionals,yieldTS///, npvDate\n                                       ));\n\n    }\n\n\n    SyntheticCDO::SyntheticCDO(\n        const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n        const boost::shared_ptr<QuantLib::Basket>& bskt,\n        QuantLib::Protection::Side side,\n        const boost::shared_ptr<QuantLib::Schedule>& schedule,\n        QuantLib::Rate upfront,\n        QuantLib::Rate spread,\n        const QuantLib::DayCounter& dayCounter,\n        QuantLib::BusinessDayConvention paymentConvention,\n        bool permanent)\n    : Instrument(properties, permanent) {\n\t\tlibraryObject_ = boost::make_shared<QuantLib::SyntheticCDO>(\n            bskt,side,*schedule,upfront,spread,dayCounter,paymentConvention);\n    }\n\n    MidPointCDOEngine::MidPointCDOEngine(\n        const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n        const QuantLib::Handle<QuantLib::YieldTermStructure>& discTS,\n        bool permanent)\n    : PricingEngine(properties, permanent) {\n\t\tlibraryObject_ = \n            boost::make_shared<QuantLib::MidPointCDOEngine>(discTS);\n    }\n\n    NthToDefault::NthToDefault(\n          const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n          const boost::shared_ptr<QuantLib::Basket>& bskt,\n          QuantLib::Size order,\n          QuantLib::Protection::Side side,\n          const boost::shared_ptr<QuantLib::Schedule>& schedule,\n          QuantLib::Rate upfront,\n          QuantLib::Rate spread,\n          const QuantLib::DayCounter& dayCounter,\n          QuantLib::Real notional,\n          bool paysAccrual,\n          bool permanent)\n    : Instrument(properties, permanent) {\n\t\tlibraryObject_ = boost::make_shared<QuantLib::NthToDefault>(\n            bskt,order,side,*schedule,upfront,spread,dayCounter,\n            notional,paysAccrual);\n    }\n\n    IntegralNtdEngine::IntegralNtdEngine(\n        const boost::shared_ptr<ObjectHandler::ValueObject>& properties,\n        const QuantLib::Period& step,\n        const QuantLib::Handle<QuantLib::YieldTermStructure>& discTS,\n        bool permanent)\n    : PricingEngine(properties, permanent) {\n\t\tlibraryObject_ = \n            boost::make_shared<QuantLib::IntegralNtdEngine>(step, discTS);\n    }\n\n\n}\n", "meta": {"hexsha": "66101e30767f29bc2b426d7d84786e26f179556e", "size": 17840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuantLibAddin/qlo/credit.cpp", "max_stars_repo_name": "txu2014/quantlib", "max_stars_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "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": "QuantLibAddin/qlo/credit.cpp", "max_issues_repo_name": "txu2014/quantlib", "max_issues_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuantLibAddin/qlo/credit.cpp", "max_forks_repo_name": "txu2014/quantlib", "max_forks_repo_head_hexsha": "95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4063260341, "max_line_length": 122, "alphanum_fraction": 0.6224215247, "num_tokens": 3888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945416, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.21923127230331968}}
{"text": "#include <armadillo>\n#include <sys/sysinfo.h>\n#include \"energy.h\"\n#include \"mcpdft.h\"\n#include \"libMem.h\"\n#include \"openrdmConfig.h\"\n#include <string>\n//#include \"HDF5_Read_Contiguous.h\"\n//#include \"HDF5_Write_Contiguous.h\"\n//#include \"HDF5_Read_Compact.h\"\n//#include \"HDF5_Write_Compact.h\"\n//#include \"HDF5_Read_Chunked.h\"\n//#include \"HDF5_Write_Chunked.h\"\n//#include \"HDF5ContiguousFactory.h\"\n//#include \"HDF5CompactFactory.h\"\n//#include \"HDF5ChunkedFactory.h\"\n#include \"HDF5Client.h\"\n#ifdef WITH_LIBXC\n   #include <xc.h>\n#else\n   #include \"functional.h\"\n#endif\n\nnamespace mcpdft {\n\n   // calculates the MCPDFT energy\n   double mcpdft_energy(MCPDFT *mc,\n\t\t        std::string &functional,\n                        const arma::mat &D1a,\n                        const arma::mat &D1b,\n                        const arma::mat &D2ab) {\n\n      // Query memory information from linux\n      struct sysinfo info;\n      sysinfo(&info);\n\n      // Calculating the amount of available memory\n      LibMem *libmem;\n      libmem = new LibMem();\n      libmem->query_system_memory(&info);\n\n      double tot_energy = 0.0;\n\n      // getting the value of the classical energy\n      double eclass = mc->get_eclass();\n      // printf(\"eclass = %-20.15lf\\n\",eclass);\n\n      // building the one electron densities rho_a(r) and rho_b(r)\n      mc->build_rho();\n\n      // building the on-top pair density pi(r,r)\n      mc->build_pi(D2ab);\n\n      // building the R(r) factor for density translation\n      mc->build_R();\n\n      // translate the one-electron densities\n      mc->translate();\n\n      size_t npts = mc->get_npts();\n      arma::vec tr_rhoa(mc->get_tr_rhoa());\n      arma::vec tr_rhob(mc->get_tr_rhob());\n      arma::vec tr_sigma_aa(npts, arma::fill::zeros);\n      arma::vec tr_sigma_ab(npts, arma::fill::zeros);\n      arma::vec tr_sigma_bb(npts, arma::fill::zeros);\n      if(mc->is_gga()) {\n         tr_sigma_aa = mc->get_tr_sigma_aa();\n         tr_sigma_ab = mc->get_tr_sigma_ab();\n         tr_sigma_bb = mc->get_tr_sigma_bb();\n      }\n#ifdef WITH_LIBXC\n      arma::vec tr_rho(tr_rhoa);\n      arma::vec ex(npts);\n      arma::vec ec(npts);\n      arma::vec W(mc->get_w());\n      tr_rho = tr_rho + tr_rhob;\n      double * rhop = tr_rho.memptr();\n      double * exp = ex.memptr();\n      double * ecp = ec.memptr();\n\n      double Ex = 0.0;\n      double Ec = 0.0;\n\n      xc_func_type func_x;\n      if(xc_func_init(&func_x,XC_LDA_X, XC_UNPOLARIZED) != 0){\n        xc_lda_exc(&func_x, npts, rhop, exp);\n      }\n\n      double ans = 0.0;\n      for (int p = 0; p < npts; p++) {\n          if (tr_rho(p) > 1.0e-20)\n             ans += W(p) * ex(p) * tr_rho(p);\n      }\n      Ex=ans;\n\n      xc_func_type func_c;\n      if(xc_func_init(&func_c,XC_LDA_C_VWN_RPA, XC_UNPOLARIZED) != 0){\n        xc_lda_exc(&func_c, npts, rhop, ecp);\n      }\n\n      ans = 0.0;\n      for (int p = 0; p < npts; p++) {\n          if (tr_rho(p) > 1.0e-20)\n             ans += W(p) * ec(p) * tr_rho(p);\n      }\n      Ec=ans;\n      xc_func_end(&func_x);\n      xc_func_end(&func_c);\n#else\n      Functional* func = new Functional;\n\n      double Ex = 0.0;\n      double Ec = 0.0;\n      if (functional == \"SVWN\") {\n          Ex = func->EX_LSDA(mc, tr_rhoa, tr_rhob);\n          Ec = func->EC_VWN3(mc, tr_rhoa, tr_rhob);\n      }else{\n          Ex = func->EX_PBE(mc, tr_rhoa, tr_rhob, tr_sigma_aa, tr_sigma_bb);\n          Ec = func->EC_PBE(mc, tr_rhoa, tr_rhob, tr_sigma_aa, tr_sigma_ab, tr_sigma_bb);\n      }\n\n      delete func;\n#endif\n\n      size_t nbfs = mc->get_nbfs();\n      size_t nbfs2 = nbfs * nbfs;\n\n      arma::mat d1a(nbfs, nbfs, arma::fill::zeros);\n      arma::mat d1b(nbfs, nbfs, arma::fill::zeros);\n      arma::mat d2ab(nbfs2, nbfs2, arma::fill::zeros);\n\n      HDF5Client* h5client = new HDF5Client();\n\n      HDF5Client::factory_mode mode(HDF5Client::factory_mode::WRITE);\n      h5client->factory_client(H5D_COMPACT,mode,D1a,D1b,D2ab);\n\n      mode = HDF5Client::factory_mode::READ;\n      h5client->factory_client(H5D_COMPACT,mode,D1a,D1b,D2ab);\n\n      delete h5client;\n\n      // IOFactory* iof;\n      // IRead* ird;\n      // IWrite* iwt;\n\n//    //   iof = new HDF5ContiguousFactory;\n//    //   iof = new HDF5CompactFactory;\n      // iof = new HDF5ChunkedFactory;\n      // iwt = iof->create_IWrite();\n      // iwt->write_rdms(D1a,D1b,D2ab);\n      // ird = iof->create_IRead();\n      // ird->read_rdms(d1a,d1b,d2ab);\n      // delete iof;\n      // IWrite* h5w = iof->create_IWrite();\n      // h5w->write_opdm(D1a,D1b);\n      // DiskRW dskrw;\n      // dskrw.write_opdm(D1a,D1b);\n      // dskrw.write_tpdm(D2ab);\n      // size_t nbfs = mc->get_nbfs();\n      // size_t nbfs2 = nbfs * nbfs;\n      // try{\n      //    arma::mat d1a(nbfs, nbfs, arma::fill::zeros);\n      //    arma::mat d1b(nbfs, nbfs, arma::fill::zeros);\n      //    arma::mat d2ab(nbfs2, nbfs2, arma::fill::zeros);\n      //    dskrw.read_opdm(d1a,d1b);\n      //    // d1a.print(\"D1a =\");\n      //    // d1b.print(\"D1b =\");\n      //    dskrw.read_tpdm(d2ab);\n      //    // d2ab.print(\"D2ab =\");\n      // } catch(const char* err_msg) {\n      //    printf(\"%s\\n\",err_msg);\n      // }\n\n\n      printf(\"------------------------------------------\\n\");\n      printf(\"   Classical energy = %-20.12lf\\n\", eclass);\n      printf(\"   Ex               = %-20.12lf\\n\", Ex);\n      printf(\"   Ec               = %-20.12lf\\n\", Ec);\n      printf(\"------------------------------------------\\n\\n\");\n\n      tot_energy += eclass;\n      tot_energy += Ex;\n      tot_energy += Ec;\n\n      delete libmem;\n\n      return tot_energy;\n   }\n\n}\n", "meta": {"hexsha": "786432a69dc589216612ae5379d4184f502746ba", "size": 5520, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libmcpdft/energy.cc", "max_stars_repo_name": "SinaMostafanejad/libRDMInoles", "max_stars_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-11-19T14:23:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-14T08:41:55.000Z", "max_issues_repo_path": "src/libmcpdft/energy.cc", "max_issues_repo_name": "SinaMostafanejad/libRDMInoles", "max_issues_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libmcpdft/energy.cc", "max_forks_repo_name": "SinaMostafanejad/libRDMInoles", "max_forks_repo_head_hexsha": "0cc9fba75755cfa046f352a6aca80e77af261ca3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-11-13T05:00:51.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-29T02:39:04.000Z", "avg_line_length": 28.9005235602, "max_line_length": 89, "alphanum_fraction": 0.556884058, "num_tokens": 1729, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.21912087016053736}}
{"text": "#include <iostream>\r\n#include <string>\r\n#include <experimental/filesystem>\r\n#include <armadillo>\r\n#include <stdexcept>\r\n\r\n#include \"exciton_transfer.h\"\r\n#include \"cnt.h\"\r\n#include \"constants.h\"\r\n#include \"../helper/progress.hpp\"\r\n\r\n// calculate and plot Q matrix element between two exciton bands\r\nvoid exciton_transfer::save_Q_matrix_element(const int i_n_principal, const int f_n_principal)\r\n{\r\n  // set the donor and accdeptor cnts\r\n  const cnt& init_cnt = *_cnts[0];\r\n  const cnt& final_cnt = *_cnts[1];\r\n  \r\n  // set the donor and acceptor exciton structs\r\n  const cnt::exciton_struct& i_exciton = init_cnt.A2_singlet();\r\n  const cnt::exciton_struct& f_exciton = final_cnt.A2_singlet();\r\n\r\n  std::cout << \"\\n...calculating Q matrix element\\n\";\r\n\r\n  // some error checking\r\n  if ((i_n_principal >= i_exciton.n_principal) and (f_n_principal >= f_exciton.n_principal)){\r\n    throw std::invalid_argument(\"i_n_principal or f_n_principla are two large.\");\r\n  }\r\n\r\n  // find lists of relevant states in donor and acceptor excitons\r\n  auto get_exciton_band = [](const auto& exciton, const int i_principal){\r\n    std::vector<ex_state> states;\r\n    for (int ik_cm_idx=0; ik_cm_idx<exciton.nk_cm; ik_cm_idx++)\r\n    {\r\n      ex_state state(exciton,ik_cm_idx,i_principal);\r\n      states.emplace_back(state);\r\n    }\r\n    return states;\r\n  };\r\n  const auto i_relevant_states = get_exciton_band(i_exciton,i_n_principal);\r\n  const auto f_relevant_states = get_exciton_band(f_exciton,f_n_principal);\r\n\r\n\r\n  // match the states based on their energy\r\n  std::vector<matching_states> state_pairs = match_all_states(i_relevant_states, f_relevant_states);\r\n\r\n  // get min of ik_cm_idx from relevant states indices\r\n  auto get_min_ik_cm_idx = [](const auto& relevant_states){\r\n    int min_idx = 1.e9;\r\n    for (const auto& state: relevant_states)\r\n    {\r\n      min_idx = (min_idx < state.ik_cm_idx) ? min_idx : state.ik_cm_idx;\r\n    }\r\n    return min_idx;\r\n  };\r\n  // get max of ik_cm_idx from relevant states indices\r\n  auto get_max_ik_cm_idx = [](const auto& relevant_states){\r\n    int max_idx = -1.e9;\r\n    for (const auto& state: relevant_states)\r\n    {\r\n      max_idx = (max_idx > state.ik_cm_idx) ? max_idx : state.ik_cm_idx;\r\n    }\r\n    return max_idx;\r\n  };\r\n  int i_min_idx = get_min_ik_cm_idx(i_relevant_states);\r\n  int i_max_idx = get_max_ik_cm_idx(i_relevant_states);\r\n  int f_min_idx = get_min_ik_cm_idx(f_relevant_states);\r\n  int f_max_idx = get_max_ik_cm_idx(f_relevant_states);\r\n\r\n  arma::cx_mat Q_mat(i_max_idx-i_min_idx+1, f_max_idx-f_min_idx+1, arma::fill::zeros);\r\n  arma::vec init_ik_cm(i_max_idx-i_min_idx+1, arma::fill::zeros);\r\n  arma::vec final_ik_cm(f_max_idx-f_min_idx+1, arma::fill::zeros);\r\n\r\n  progress_bar prog(state_pairs.size(), \"calculate Q\");\r\n\r\n  for (const auto& pair:state_pairs)\r\n  { \r\n    Q_mat(pair.i.ik_cm_idx-i_min_idx, pair.f.ik_cm_idx-f_min_idx) = calculate_Q(pair);\r\n    init_ik_cm(pair.i.ik_cm_idx-i_min_idx) = pair.i.ik_cm;\r\n    final_ik_cm(pair.f.ik_cm_idx-f_min_idx) = pair.f.ik_cm;\r\n    prog.step();\r\n  }\r\n\r\n  arma::mat tmp;\r\n  \r\n  // save the real part matrix element Q to a file\r\n  tmp= arma::real(Q_mat);\r\n  std::string filename = _directory.path() / \"matrix_element_q.real.dat\";\r\n  tmp.save(filename,arma::arma_ascii);\r\n\r\n  // save the imaginary part matrix element Q to a file\r\n  tmp= arma::imag(Q_mat);\r\n  filename = _directory.path() / \"matrix_element_q.imag.dat\";\r\n  tmp.save(filename,arma::arma_ascii);\r\n\r\n  // save ik_cm of the inital states\r\n  filename = _directory.path() / \"matrix_element_q.init_ik_cm.dat\";\r\n  init_ik_cm.save(filename,arma::arma_ascii);\r\n\r\n  // save ik_cm of the final states\r\n  filename = _directory.path() / \"matrix_element_q.final_ik_cm.dat\";\r\n  final_ik_cm.save(filename,arma::arma_ascii);\r\n\r\n  std::cout << \"\\n...calculated and saved Q matrix element\\n\";\r\n\r\n}\r\n\r\n// calculate and plot J matrix element between two exciton bands\r\nvoid exciton_transfer::save_J_matrix_element(const int i_n_principal, const int f_n_principal)\r\n{\r\n  // set geometrical properties\r\n  double z_shift = 1.5e-9;\r\n  double theta = 0;\r\n  std::array<double,2> axis_shifts = {0., 0.};\r\n\r\n  // set the donor and accdeptor cnts\r\n  const cnt& init_cnt = *_cnts[0];\r\n  const cnt& final_cnt = *_cnts[1];\r\n  \r\n  // set the donor and acceptor exciton structs\r\n  const cnt::exciton_struct& i_exciton = init_cnt.A2_singlet();\r\n  const cnt::exciton_struct& f_exciton = final_cnt.A2_singlet();\r\n\r\n  std::cout << \"\\n...calculating J matrix element\\n\";\r\n  // std::cout << \"initial exciton ik_cm_range: [\" << i_exciton.ik_cm_range[0] << \",\" << i_exciton.ik_cm_range[1] << \"]\\n\";\r\n  // std::cout << \"final exciton ik_cm_range: [\" << f_exciton.ik_cm_range[0] << \",\" << f_exciton.ik_cm_range[1] << \"]\\n\";\r\n\r\n  // some error checking\r\n  if ((i_n_principal >= i_exciton.n_principal) and (f_n_principal >= f_exciton.n_principal)){\r\n    throw std::invalid_argument(\"i_n_principal or f_n_principla are two large.\");\r\n  }\r\n\r\n  // find lists of relevant states in donor and acceptor excitons\r\n  auto get_exciton_band = [](const auto& exciton, const int i_principal){\r\n    std::vector<ex_state> states;\r\n    // int ik_cm_min = exciton.ik_cm_range[0];\r\n    // int ik_cm_max = exciton.ik_cm_range[1];\r\n    int ik_cm_min = -50;\r\n    int ik_cm_max = -ik_cm_min+1;\r\n    for (int ik_cm=ik_cm_min; ik_cm<ik_cm_max; ik_cm++)\r\n    {\r\n      ex_state state(exciton,ik_cm-exciton.ik_cm_range[0],i_principal);\r\n      states.emplace_back(state);\r\n    }\r\n    return states;\r\n  };\r\n  const auto i_relevant_states = get_exciton_band(i_exciton,i_n_principal);\r\n  const auto f_relevant_states = get_exciton_band(f_exciton,f_n_principal);\r\n\r\n  std::cout << \"initial exciton length: \" << i_exciton.cnt_obj->length_in_meter()*1e9 << \" [nm]\\n\";\r\n  std::cout << \"final exciton length: \" << f_exciton.cnt_obj->length_in_meter()*1e9 << \" [nm]\\n\";\r\n\r\n\r\n  // match the states based on their energy\r\n  std::vector<matching_states> state_pairs = match_all_states(i_relevant_states, f_relevant_states);\r\n\r\n  // get min of ik_cm_idx from relevant states indices\r\n  auto get_min_ik_cm_idx = [](const auto& relevant_states){\r\n    int min_idx = 1.e9;\r\n    for (const auto& state: relevant_states)\r\n    {\r\n      min_idx = (min_idx < state.ik_cm_idx) ? min_idx : state.ik_cm_idx;\r\n    }\r\n    return min_idx;\r\n  };\r\n  // get max of ik_cm_idx from relevant states indices\r\n  auto get_max_ik_cm_idx = [](const auto& relevant_states){\r\n    int max_idx = -1.e9;\r\n    for (const auto& state: relevant_states)\r\n    {\r\n      max_idx = (max_idx > state.ik_cm_idx) ? max_idx : state.ik_cm_idx;\r\n    }\r\n    return max_idx;\r\n  };\r\n  int i_min_idx = get_min_ik_cm_idx(i_relevant_states);\r\n  int i_max_idx = get_max_ik_cm_idx(i_relevant_states);\r\n  int f_min_idx = get_min_ik_cm_idx(f_relevant_states);\r\n  int f_max_idx = get_max_ik_cm_idx(f_relevant_states);\r\n\r\n  arma::cx_mat J_mat(i_max_idx-i_min_idx+1, f_max_idx-f_min_idx+1, arma::fill::zeros);\r\n  arma::vec init_ik_cm(i_max_idx-i_min_idx+1, arma::fill::zeros);\r\n  arma::vec final_ik_cm(f_max_idx-f_min_idx+1, arma::fill::zeros);\r\n\r\n  // int count = 0;\r\n  // int number_of_pairs = state_pairs.size();\r\n  progress_bar prog(state_pairs.size(),\"calculate J\");\r\n\r\n  for (const auto& pair:state_pairs)\r\n  { \r\n    // count++;\r\n    // prog.step(count, number_of_pairs, \"calculate J\");\r\n    prog.step();\r\n    // std::cout << \"calculate J: \" << count << \"/\" << number_of_pairs << \"\\n\";\r\n\r\n    J_mat(pair.i.ik_cm_idx-i_min_idx, pair.f.ik_cm_idx-f_min_idx) = calculate_J(pair, axis_shifts, z_shift, theta);\r\n    init_ik_cm(pair.i.ik_cm_idx-i_min_idx) = pair.i.ik_cm;\r\n    final_ik_cm(pair.f.ik_cm_idx-f_min_idx) = pair.f.ik_cm;\r\n  }\r\n\r\n  arma::mat tmp;\r\n  \r\n\r\n  // save the real part matrix element Q to a file\r\n  tmp= arma::real(J_mat);\r\n  std::string filename = _directory.path() / \"matrix_element_j.real.dat\";\r\n  tmp.save(filename,arma::arma_ascii);\r\n\r\n  // save the imaginary part matrix element Q to a file\r\n  tmp= arma::imag(J_mat);\r\n  filename = _directory.path() / \"matrix_element_j.imag.dat\";\r\n  tmp.save(filename,arma::arma_ascii);\r\n\r\n  // save ik_cm of the inital states\r\n  filename = _directory.path() / \"matrix_element_j.init_ik_cm.dat\";\r\n  init_ik_cm.save(filename,arma::arma_ascii);\r\n\r\n  // save ik_cm of the final states\r\n  filename = _directory.path() / \"matrix_element_j.final_ik_cm.dat\";\r\n  final_ik_cm.save(filename,arma::arma_ascii);\r\n\r\n  std::cout << \"\\n...calculated and saved J matrix element\\n\";\r\n\r\n}\r\n\r\n// get the energetically relevant states in the form a vector of ex_state structs\r\nstd::vector<exciton_transfer::ex_state> exciton_transfer::get_relevant_states(const cnt::exciton_struct& exciton, const double min_energy)\r\n{\r\n  const double threshold_population = 1.e-3;\r\n  const double threshold_energy = min_energy+std::abs(std::log(threshold_population) * constants::kb*_temperature);\r\n\r\n  std::vector<ex_state> relevant_states;\r\n  \r\n  for (int i_n=0; i_n<exciton.n_principal; i_n++)\r\n  {\r\n    for (int ik_cm_idx=0; ik_cm_idx<exciton.nk_cm; ik_cm_idx++)\r\n    {\r\n      if (exciton.energy(ik_cm_idx,i_n) <= threshold_energy)\r\n      {\r\n        relevant_states.emplace_back(ex_state(exciton,ik_cm_idx,i_n));\r\n      }\r\n    }\r\n  }\r\n\r\n  // sort relevant states in order of their energies\r\n  std::sort(relevant_states.begin(),relevant_states.end(), \\\r\n              [](const auto& s1, const auto& s2) {\r\n                return s1.energy < s2.energy;\r\n              }\r\n            );\r\n\r\n  // calculate normalization factor\r\n  double normalization_factor = 0.;\r\n  for (const auto& state: relevant_states)\r\n  {\r\n    double delta_e = (state.energy-min_energy);\r\n    normalization_factor += std::exp(-delta_e/(constants::kb*_temperature));\r\n  }\r\n\r\n\r\n  // std::cout << \"\\n...calculated relevant states\\n\";\r\n  // std::cout << \"number of relevant states: \" << relevant_states.size() << \"\\n\";\r\n  // for (const auto& state: relevant_states)\r\n  // {\r\n  //   double delta_e = (state.energy-min_energy);\r\n  //   std::cout << \"[\" << state.ik_cm_idx << \",\" << state.i_principal <<\"] --> energy:\" << delta_e/constants::eV \r\n  //             << \" , population:\" << std::exp(-delta_e/(constants::kb*_temperature))/normalization_factor << \"\\n\";\r\n  // }\r\n  \r\n  return relevant_states;\r\n}\r\n\r\n// calculate Q()\r\nstd::complex<double> exciton_transfer::calculate_Q(const matching_states& pair) const\r\n{\r\n  // lambda function to calculate part of the Q matrix element that relates to each pair.\r\n  auto Q_partial = [](const ex_state& state)\r\n  {\r\n    const int ic = 1;\r\n    const int iv = 0;\r\n\r\n    const arma::vec dA = {0,0};\r\n    const arma::vec& dB = *(state.exciton->aCC_vec);\r\n    const arma::cx_vec exp_factor({std::exp(std::complex<double>(0.,+1.)*arma::dot(state.ik_cm*state.dk_l(),dA)),\\\r\n                                   std::exp(std::complex<double>(0.,+1.)*arma::dot(state.ik_cm*state.dk_l(),dB))});\r\n\r\n    std::complex<double> Q_partial = 0;\r\n    for (int ik_c_idx=0; ik_c_idx<state.exciton->nk_c; ik_c_idx++)\r\n    {\r\n      const arma::cx_vec& Cc = state.elec_struct->wavefunc(state.ik_idx(1,ik_c_idx)).slice(state.ik_idx(0,ik_c_idx)).col(ic);\r\n      const arma::cx_vec& Cv = state.elec_struct->wavefunc(state.ik_idx(3,ik_c_idx)).slice(state.ik_idx(2,ik_c_idx)).col(iv);\r\n      Q_partial += state.psi(ik_c_idx)*arma::accu(Cc%arma::conj(Cv)%exp_factor);\r\n    }\r\n\r\n    return Q_partial;\r\n\r\n  };\r\n\r\n  double coeff = (std::pow(constants::q0,2)*pair.i.cnt_obj->Au()*pair.f.cnt_obj->Au())/\\\r\n                 (16*std::pow(constants::pi,3)*constants::eps0*pair.i.cnt_obj->radius()*pair.f.cnt_obj->radius()*\\\r\n                  std::sqrt(pair.i.cnt_obj->length_in_meter()*pair.f.cnt_obj->length_in_meter()));\r\n\r\n  return std::complex<double>(coeff)*std::conj(Q_partial(pair.i))*Q_partial(pair.f);\r\n\r\n}\r\n\r\n// calculate J()\r\nstd::complex<double> exciton_transfer::calculate_J(const matching_states& pair, const std::array<double,2>& shifts_along_axis, const double& z_shift, const double& angle) const\r\n{\r\n  // make position of all atoms in the entire cnt length in 3d space\r\n  auto make_Ru_3d = [](const cnt &m_cnt, const double shift_along_axis, const double z_shift, const double angle) {\r\n    int n_atoms_in_cnt_unit_cell = m_cnt.pos_u_3d().n_rows;\r\n    int total_number_of_atoms = m_cnt.pos_u_3d().n_rows * m_cnt.length_in_cnt_unit_cell();\r\n    arma::mat all_atoms(total_number_of_atoms, 3);\r\n\r\n    for (int i = 0; i < m_cnt.length_in_cnt_unit_cell(); i++) {\r\n      all_atoms.rows(i * n_atoms_in_cnt_unit_cell, (i + 1) * n_atoms_in_cnt_unit_cell - 1) = m_cnt.pos_u_3d().each_row() + i * m_cnt.t_vec_3d().t();\r\n    }\r\n\r\n    // make the cnt center at the middle\r\n    double y_max = all_atoms.col(1).max();\r\n    double y_min = all_atoms.col(1).min();\r\n    all_atoms.col(1) -= ((y_max + y_min) / 2.);\r\n\r\n    // shift the center of the cnt axis along it's axis\r\n    all_atoms.col(1) += shift_along_axis;\r\n\r\n    // shift the atoms along the z axis\r\n    all_atoms.col(2) += z_shift;\r\n\r\n    // rotate by angle around the z axis\r\n    for (unsigned int i = 0; i < all_atoms.n_rows; i++) {\r\n      double x = all_atoms(i, 0) * std::cos(angle) - all_atoms(i, 1) * std::sin(angle);\r\n      double y = all_atoms(i, 0) * std::sin(angle) + all_atoms(i, 1) * std::cos(angle);\r\n      all_atoms(i, 0) = x;\r\n      all_atoms(i, 1) = y;\r\n    }\r\n    return all_atoms;\r\n  };\r\n\r\n  // make position of all atoms in the entire cnt length in 2d space of unrolled cnt\r\n  auto make_Ru_2d = [](const cnt& m_cnt) {\r\n    int n_atoms_in_cnt_unit_cell = m_cnt.pos_u_2d().n_rows;\r\n    int total_number_of_atoms = m_cnt.pos_u_2d().n_rows * m_cnt.length_in_cnt_unit_cell();\r\n    arma::mat all_atoms(total_number_of_atoms,2);\r\n\r\n    for (int i=0; i<m_cnt.length_in_cnt_unit_cell(); i++) {\r\n      all_atoms.rows(i*n_atoms_in_cnt_unit_cell,(i+1)*n_atoms_in_cnt_unit_cell-1) = m_cnt.pos_u_2d().each_row() + i * m_cnt.t_vec().t();\r\n    }\r\n\r\n    return all_atoms;\r\n  };\r\n\r\n  arma::mat i_Ru_3d = make_Ru_3d(*(pair.i.cnt_obj), shifts_along_axis[0], 0, 0);\r\n  arma::mat f_Ru_3d = make_Ru_3d(*(pair.f.cnt_obj), shifts_along_axis[1], z_shift, angle);\r\n\r\n  arma::mat i_Ru_2d = make_Ru_2d(*(pair.i.cnt_obj));\r\n  arma::mat f_Ru_2d = make_Ru_2d(*(pair.f.cnt_obj));\r\n\r\n  std::complex<double> J = 0;\r\n  const std::complex<double> i1(0,1);\r\n\r\n  // prebuild exponential factor for the inner loop\r\n  arma::cx_vec f_exp(f_Ru_2d.n_rows);\r\n  for (unsigned int j=0; j<f_Ru_2d.n_rows; j++) {\r\n    f_exp(j) = std::exp(+i1*arma::dot(pair.f.ik_cm*pair.f.dk_l(),f_Ru_2d.row(j)));\r\n  }\r\n\r\n  for (unsigned int i=0; i<i_Ru_2d.n_rows; i++)\r\n  {\r\n    std::complex<double> i_exp = std::exp(-i1*arma::dot(pair.i.ik_cm*pair.i.dk_l(),i_Ru_2d.row(i)));    \r\n    for (unsigned int j=0; j<f_Ru_2d.n_rows; j++)\r\n    {\r\n      J += i_exp*f_exp(j)/(arma::norm(i_Ru_3d.row(i)-f_Ru_3d.row(j)));\r\n    }\r\n  }\r\n  return J;\r\n}\r\n\r\n// calculate first order transfer rate\r\ndouble exciton_transfer::first_order(const double& z_shift, const std::array<double,2> axis_shifts, const double& theta, const bool& show_results)\r\n{\r\n  const cnt& donor = *_cnts[0];\r\n  const cnt& acceptor = *_cnts[1];\r\n\r\n  double min_energy = donor.A2_singlet().energy.min();\r\n\r\n  const cnt::exciton_struct& d_exciton = donor.A2_singlet();\r\n  const cnt::exciton_struct& a_exciton = acceptor.A2_singlet();\r\n\r\n  // find lists of relevant states in donor and acceptor excitons\r\n  std::vector<ex_state> d_relevant_states = get_relevant_states(d_exciton,min_energy);\r\n  std::vector<ex_state> a_relevant_states = get_relevant_states(a_exciton,min_energy);\r\n\r\n  double Z = 0;\r\n  for (const auto& state:d_relevant_states) {\r\n    Z += std::exp(-state.energy/(constants::kb*_temperature));\r\n  }\r\n\r\n  // match the states based on their energy\r\n  std::vector<matching_states> state_pairs = match_states(d_relevant_states, a_relevant_states);\r\n\r\n\r\n  // std::cout << \"number of matching states: \" << state_pairs.size() << std::endl;\r\n\r\n  // int i=0;\r\n\r\n\r\n  double transfer_rate = 0;\r\n\r\n  progress_bar prog(state_pairs.size(),\"calculate first-order exciton transfer rate\", !show_results);\r\n  for (const auto& pair:state_pairs) { \r\n    prog.step();\r\n    std::complex<double> Q = calculate_Q(pair);\r\n    std::complex<double> J = calculate_J(pair, axis_shifts, z_shift, theta);\r\n    double M = std::abs(Q * J) / std::sqrt(pair.i.cnt_obj->length_in_meter() * pair.f.cnt_obj->length_in_meter());\r\n    // double M = std::abs(Q * J);\r\n\r\n    // std::cout << std::showpos;\r\n    // std::cout << i   << \"---------> \";\r\n    // std::cout << \"(\" << pair.i.ik_cm << \",\" << pair.f.ik_cm << \")\" << \" E(i)=\" << pair.i.energy << \" , E(f)=\" << pair.f.energy;\r\n    // std::cout << \" , Q = \" << std::abs(Q);\r\n    // std::cout << \" , J = \" << std::abs(J);\r\n    // std::cout << \" , M = \" << std::abs(M) << std::endl;\r\n    // i++;\r\n\r\n    transfer_rate += (2*constants::pi/constants::hb)*(std::exp(-pair.i.energy/(constants::kb*_temperature))/Z)*std::pow(M,2)*lorentzian(pair.i.energy-pair.f.energy);\r\n  }\r\n\r\n  if (show_results) {\r\n    std::cout << \"\\n\\n\";\r\n    std::cout << \"cnt lengths: \" << _cnts[0]->length_in_meter()*1.e9 << \" [nm], \" << _cnts[1]->length_in_meter()*1.e9 << \" [nm]\\n\";\r\n    std::cout << \"center to center distance: \" << z_shift*1.e9 << \" [nm]\\n\";\r\n    std::cout << \"cnt1 radius: \" << _cnts[0]->radius()*1.e9 << \" [nm], cnt2 radius: \" << _cnts[1]->radius()*1.e9 << \" [nm]\\n\";\r\n    std::cout << \"wall to wall distance: \" << (z_shift - _cnts[0]->radius() - _cnts[1]->radius())*1.e9 << \" [nm]\\n\";\r\n    std::cout << \"theta: \" << theta/constants::pi*180 << \" [degrees]\\n\";\r\n    std::cout << \"axis shifts: \" << axis_shifts[0]*1e9 << \" [nm] and \" << axis_shifts[1]*1e9 << \" [nm]\\n\";\r\n    std::cout << \"exciton transfer rate: \" << transfer_rate << \"\\n\";\r\n  }\r\n\r\n  return transfer_rate;\r\n}\r\n\r\n// calculate first order transfer rate for varying angle\r\nvoid exciton_transfer::calculate_first_order_vs_angle(const arma::vec& angle_vec ,const double& z_shift, const std::array<double,2> axis_shifts) {\r\n  int n_theta = angle_vec.n_elem;\r\n  arma::vec transfer_rate(arma::size(angle_vec), arma::fill::zeros);\r\n\r\n  progress_bar prog(n_theta, \"first order transfer rate versus angle\");\r\n  for (int i=0; i<n_theta; i++)\r\n  {\r\n    prog.step();\r\n    transfer_rate(i) = first_order(z_shift, axis_shifts, angle_vec(i));\r\n  }\r\n\r\n  // save the transfer rate\r\n  std::string filename = _directory.path() / \"first_order_transfer_rate_vs_angle.dat\";\r\n  transfer_rate.save(filename,arma::arma_ascii);\r\n\r\n  // save theta vector\r\n  filename = _directory.path() / \"first_order_transfer_rate_vs_angle.theta.dat\";\r\n  angle_vec.save(filename,arma::arma_ascii);\r\n\r\n  std::cout << \"\\n\\n\";\r\n  std::cout << \"cnt lengths: \" << _cnts[0]->length_in_meter()*1.e9 << \" [nm], \" << _cnts[1]->length_in_meter()*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"center to center distance: \" << z_shift*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"cnt1 radius: \" << _cnts[0]->radius()*1.e9 << \" [nm], cnt2 radius: \" << _cnts[1]->radius()*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"wall to wall distance: \" << (z_shift - _cnts[0]->radius() - _cnts[1]->radius())*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"axis shifts: \" << axis_shifts[0]*1e9 << \" [nm] and \" << axis_shifts[1]*1e9 << \" [nm]\\n\";\r\n  std::cout << \"max transfer rate: \" << transfer_rate.max()/1e12 << \" [1/ps] at \" << angle_vec(transfer_rate.index_max())*180/constants::pi << \" [degrees]\\n\";\r\n  std::cout << \"min transfer rate: \" << transfer_rate.min()/1e12 << \" [1/ps] at \" << angle_vec(transfer_rate.index_min())*180/constants::pi << \" [degrees]\\n\";\r\n}\r\n\r\n// calculate first order transfer rate for center to center distance\r\nvoid exciton_transfer::calculate_first_order_vs_zshift(const arma::vec& z_shift_vec, const std::array<double,2> axis_shifts, const double& theta) {\r\n  int n = z_shift_vec.n_elem;\r\n  arma::vec transfer_rate(arma::size(z_shift_vec), arma::fill::zeros);\r\n\r\n  progress_bar prog(n, \"first order transfer rate versus z_shift\");\r\n  for (int i=0; i<n; i++)\r\n  {\r\n    prog.step();\r\n    transfer_rate(i) = first_order(z_shift_vec(i), axis_shifts, theta);\r\n  }\r\n\r\n  // save the transfer rate\r\n  std::string filename = _directory.path() / \"first_order_transfer_rate_vs_zshift.dat\";\r\n  transfer_rate.save(filename,arma::arma_ascii);\r\n\r\n  // save theta vector\r\n  filename = _directory.path() / \"first_order_transfer_rate_vs_zshift.distance.dat\";\r\n  z_shift_vec.save(filename,arma::arma_ascii);\r\n\r\n  std::cout << \"\\n\\n\";\r\n  std::cout << \"cnt lengths: \" << _cnts[0]->length_in_meter()*1.e9 << \" [nm], \" << _cnts[1]->length_in_meter()*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"cnt1 radius: \" << _cnts[0]->radius()*1.e9 << \" [nm], cnt2 radius: \" << _cnts[1]->radius()*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"theta: \" << theta*180/constants::pi << \" [degrees]\\n\";\r\n  std::cout << \"axis shifts: \" << axis_shifts[0]*1e9 << \" [nm] and \" << axis_shifts[1]*1e9 << \" [nm]\\n\";\r\n  std::cout << \"max transfer rate: \" << transfer_rate.max() << \" [1/s] at \" << z_shift_vec(transfer_rate.index_max())*1e9 << \" [nm]\\n\";\r\n  std::cout << \"min transfer rate: \" << transfer_rate.min() << \" [1/s] at \" << z_shift_vec(transfer_rate.index_min())*1e9 << \" [nm]\\n\";\r\n}\r\n\r\n// calculate first order transfer rate for varying axis shift for initial cnt\r\nvoid exciton_transfer::calculate_first_order_vs_axis_shift_1(const arma::vec& axis_shift_vec_1, const double axis_shift_2, const double z_shift, const double& theta) {\r\n  int n = axis_shift_vec_1.n_elem;\r\n  arma::vec transfer_rate(arma::size(axis_shift_vec_1), arma::fill::zeros);\r\n\r\n  progress_bar prog(n, \"first order transfer rate versus axis shift of initial cnt\");\r\n  for (int i=0; i<n; i++)\r\n  {\r\n    prog.step();\r\n    std::array<double,2> axis_shifts = {axis_shift_vec_1(i),axis_shift_2};\r\n    transfer_rate(i) = first_order(z_shift, axis_shifts, theta);\r\n  }\r\n\r\n  // save the transfer rate\r\n  std::string filename = _directory.path() / \"first_order_transfer_rate_vs_axis_shift_1.dat\";\r\n  transfer_rate.save(filename,arma::arma_ascii);\r\n\r\n  // save theta vector\r\n  filename = _directory.path() / \"first_order_transfer_rate_vs_axis_shift_1.shift.dat\";\r\n  axis_shift_vec_1.save(filename,arma::arma_ascii);\r\n\r\n  std::cout << \"\\n\\n\";\r\n  std::cout << \"cnt lengths: \" << _cnts[0]->length_in_meter()*1.e9 << \" [nm], \" << _cnts[1]->length_in_meter()*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"cnt1 radius: \" << _cnts[0]->radius()*1.e9 << \" [nm], cnt2 radius: \" << _cnts[1]->radius()*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"theta: \" << theta*180/constants::pi << \" [degrees]\\n\";\r\n  std::cout << \"center to center distance: \" << z_shift*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"max transfer rate: \" << transfer_rate.max() << \" [1/s] at \" << axis_shift_vec_1(transfer_rate.index_max())*1e9 << \" [nm]\\n\";\r\n  std::cout << \"min transfer rate: \" << transfer_rate.min() << \" [1/s] at \" << axis_shift_vec_1(transfer_rate.index_min())*1e9 << \" [nm]\\n\";\r\n}\r\n\r\n// calculate first order transfer rate for varying axis shift for final cnt\r\nvoid exciton_transfer::calculate_first_order_vs_axis_shift_2(const arma::vec& axis_shift_vec_2, const double axis_shift_1, const double z_shift, const double& theta) {\r\n  int n = axis_shift_vec_2.n_elem;\r\n  arma::vec transfer_rate(arma::size(axis_shift_vec_2), arma::fill::zeros);\r\n\r\n  progress_bar prog(n, \"first order transfer rate versus axis shift of final cnt\");\r\n  for (int i=0; i<n; i++)\r\n  {\r\n    prog.step();\r\n    std::array<double,2> axis_shifts = {axis_shift_1, axis_shift_vec_2(i)};\r\n    transfer_rate(i) = first_order(z_shift, axis_shifts, theta);\r\n  }\r\n\r\n  // save the transfer rate\r\n  std::string filename = _directory.path() / \"first_order_transfer_rate_vs_axis_shift_2.dat\";\r\n  transfer_rate.save(filename,arma::arma_ascii);\r\n\r\n  // save theta vector\r\n  filename = _directory.path() / \"first_order_transfer_rate_vs_axis_shift_2.shift.dat\";\r\n  axis_shift_vec_2.save(filename,arma::arma_ascii);\r\n\r\n  std::cout << \"\\n\\n\";\r\n  std::cout << \"cnt lengths: \" << _cnts[0]->length_in_meter()*1.e9 << \" [nm], \" << _cnts[1]->length_in_meter()*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"cnt1 radius: \" << _cnts[0]->radius()*1.e9 << \" [nm], cnt2 radius: \" << _cnts[1]->radius()*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"theta: \" << theta*180/constants::pi << \" [degrees]\\n\";\r\n  std::cout << \"center to center distance: \" << z_shift*1.e9 << \" [nm]\\n\";\r\n  std::cout << \"max transfer rate: \" << transfer_rate.max() << \" [1/s] at \" << axis_shift_vec_2(transfer_rate.index_max())*1e9 << \" [nm]\\n\";\r\n  std::cout << \"min transfer rate: \" << transfer_rate.min() << \" [1/s] at \" << axis_shift_vec_2(transfer_rate.index_min())*1e9 << \" [nm]\\n\";\r\n}\r\n\r\ntypedef std::experimental::filesystem::path path_t;\r\nvoid exciton_transfer::save_atom_locations(path_t path, const std::array<double, 2> &shifts_along_axis, const double &z_shift, const double &angle, std::string prefix) {\r\n  \r\n  std::cout << \"saving 3d atom locations for donor and acceptor cnts...\";\r\n\r\n  // make position of all atoms in the entire cnt length in 3d space\r\n  auto make_Ru_3d = [](const cnt &m_cnt, const double shift_along_axis, const double z_shift, const double angle) {\r\n    int n_atoms_in_cnt_unit_cell = m_cnt.pos_u_3d().n_rows;\r\n    int total_number_of_atoms = m_cnt.pos_u_3d().n_rows * m_cnt.length_in_cnt_unit_cell();\r\n    arma::mat all_atoms(total_number_of_atoms, 3);\r\n\r\n    for (int i = 0; i < m_cnt.length_in_cnt_unit_cell(); i++) {\r\n      all_atoms.rows(i * n_atoms_in_cnt_unit_cell, (i + 1) * n_atoms_in_cnt_unit_cell - 1) = m_cnt.pos_u_3d().each_row() + i*m_cnt.t_vec_3d().t();\r\n    }\r\n\r\n    // make the cnt center at the middle\r\n    double y_max = all_atoms.col(1).max();\r\n    double y_min = all_atoms.col(1).min();\r\n    all_atoms.col(1) -= ((y_max + y_min) / 2.);\r\n\r\n    // shift the center of the cnt axis along it's axis\r\n    all_atoms.col(1) += shift_along_axis;\r\n\r\n    // shift the atoms along the z axis\r\n    all_atoms.col(2) += z_shift;\r\n\r\n    // rotate by angle around the z axis\r\n    for (unsigned int i = 0; i < all_atoms.n_rows; i++)\r\n    {\r\n      double x = all_atoms(i, 0) * std::cos(angle) - all_atoms(i, 1) * std::sin(angle);\r\n      double y = all_atoms(i, 0) * std::sin(angle) + all_atoms(i, 1) * std::cos(angle);\r\n      all_atoms(i, 0) = x;\r\n      all_atoms(i, 1) = y;\r\n    }\r\n    return all_atoms;\r\n  };\r\n\r\n  const cnt* donor = _cnts[0];\r\n  const cnt* acceptor = _cnts[1];\r\n\r\n  arma::mat i_Ru_3d = make_Ru_3d(*donor, shifts_along_axis[0], 0, 0);\r\n  arma::mat f_Ru_3d = make_Ru_3d(*acceptor, shifts_along_axis[1], z_shift, angle);\r\n\r\n  path /= \"3d_coord\"+prefix;\r\n\r\n  std::ofstream file;\r\n\r\n  file.open(std::string(path) + \".cnt1.dat\");\r\n  file << i_Ru_3d;\r\n  file.close();\r\n\r\n  file.open(std::string(path) + \".cnt2.dat\");\r\n  file << f_Ru_3d;\r\n  file.close();\r\n\r\n  std::cout << \"done!!!\" << std::endl;\r\n}", "meta": {"hexsha": "25d3e34489fc08083cf9c8cbef1f1908dd84105b", "size": 26573, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "montecarlo/src/exciton_transfer/exciton_transfer.cpp", "max_stars_repo_name": "li779/DECaNT", "max_stars_repo_head_hexsha": "8fe0faedd372a8214f1bd475eb7451d2eee1ca56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T19:21:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T16:41:21.000Z", "max_issues_repo_path": "montecarlo/src/exciton_transfer/exciton_transfer.cpp", "max_issues_repo_name": "li779/DECaNT", "max_issues_repo_head_hexsha": "8fe0faedd372a8214f1bd475eb7451d2eee1ca56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "montecarlo/src/exciton_transfer/exciton_transfer.cpp", "max_forks_repo_name": "li779/DECaNT", "max_forks_repo_head_hexsha": "8fe0faedd372a8214f1bd475eb7451d2eee1ca56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-22T15:02:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-22T15:02:52.000Z", "avg_line_length": 42.998381877, "max_line_length": 177, "alphanum_fraction": 0.6546870884, "num_tokens": 7823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21908162719838362}}
{"text": "// Distributed under the MIT License.\n// See LICENSE.txt for details.\n\n#include \"Evolution/Systems/ScalarAdvection/FiniteDifference/MonotisedCentral.hpp\"\n\n#include <array>\n#include <boost/functional/hash.hpp>\n#include <cstddef>\n#include <memory>\n#include <pup.h>\n#include <utility>\n#include <vector>\n\n#include \"DataStructures/DataBox/Prefixes.hpp\"\n#include \"DataStructures/FixedHashMap.hpp\"\n#include \"DataStructures/Index.hpp\"\n#include \"DataStructures/Tensor/IndexType.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/Systems/ScalarAdvection/FiniteDifference/ReconstructWork.tpp\"\n#include \"Evolution/Systems/ScalarAdvection/FiniteDifference/Reconstructor.hpp\"\n#include \"Evolution/Systems/ScalarAdvection/Tags.hpp\"\n#include \"NumericalAlgorithms/FiniteDifference/MonotisedCentral.hpp\"\n#include \"NumericalAlgorithms/Spectral/Mesh.hpp\"\n#include \"Utilities/GenerateInstantiations.hpp\"\n#include \"Utilities/Gsl.hpp\"\n#include \"Utilities/TMPL.hpp\"\n\nnamespace ScalarAdvection::fd {\ntemplate <size_t Dim>\nMonotisedCentral<Dim>::MonotisedCentral(CkMigrateMessage* const msg)\n    : Reconstructor<Dim>(msg) {}\n\ntemplate <size_t Dim>\nstd::unique_ptr<Reconstructor<Dim>> MonotisedCentral<Dim>::get_clone() const {\n  return std::make_unique<MonotisedCentral>(*this);\n}\n\ntemplate <size_t Dim>\nvoid MonotisedCentral<Dim>::pup(PUP::er& p) {\n  Reconstructor<Dim>::pup(p);\n}\n\ntemplate <size_t Dim>\nPUP::able::PUP_ID MonotisedCentral<Dim>::my_PUP_ID = 0;\n\ntemplate <size_t Dim>\ntemplate <typename TagsList>\nvoid MonotisedCentral<Dim>::reconstruct(\n    const gsl::not_null<std::array<Variables<TagsList>, Dim>*>\n        vars_on_lower_face,\n    const gsl::not_null<std::array<Variables<TagsList>, Dim>*>\n        vars_on_upper_face,\n    const Variables<tmpl::list<Tags::U>>& volume_vars,\n    const Element<Dim>& element,\n    const FixedHashMap<\n        maximum_number_of_neighbors(Dim),\n        std::pair<Direction<Dim>, ElementId<Dim>>, std::vector<double>,\n        boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>& neighbor_data,\n    const Mesh<Dim>& subcell_mesh) const {\n  reconstruct_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_variables, 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_variables,\n            ghost_cell_vars, subcell_extents, number_of_variables);\n      },\n      volume_vars, element, neighbor_data, subcell_mesh, ghost_zone_size());\n}\n\ntemplate <size_t Dim>\ntemplate <typename TagsList>\nvoid MonotisedCentral<Dim>::reconstruct_fd_neighbor(\n    const gsl::not_null<Variables<TagsList>*> vars_on_face,\n    const Variables<tmpl::list<Tags::U>>& volume_vars,\n    const Element<Dim>& element,\n    const FixedHashMap<\n        maximum_number_of_neighbors(Dim),\n        std::pair<Direction<Dim>, ElementId<Dim>>, std::vector<double>,\n        boost::hash<std::pair<Direction<Dim>, ElementId<Dim>>>>& neighbor_data,\n    const Mesh<Dim>& subcell_mesh,\n    const Direction<Dim> 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, const auto& subcell_extents,\n         const auto& ghost_data_extents,\n         const auto& 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, const auto& subcell_extents,\n         const auto& ghost_data_extents,\n         const auto& 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      volume_vars, element, neighbor_data, subcell_mesh,\n      direction_to_reconstruct, ghost_zone_size());\n}\n\ntemplate <size_t Dim>\nbool operator==(const MonotisedCentral<Dim>& /*lhs*/,\n                const MonotisedCentral<Dim>& /*rhs*/) {\n  return true;\n}\n\ntemplate <size_t Dim>\nbool operator!=(const MonotisedCentral<Dim>& lhs,\n                const MonotisedCentral<Dim>& rhs) {\n  return not(lhs == rhs);\n}\n\n#define DIM(data) BOOST_PP_TUPLE_ELEM(0, data)\n#define TAGS_LIST(data)                                                       \\\n  tmpl::list<Tags::U,                                                         \\\n             ::Tags::Flux<Tags::U, tmpl::size_t<DIM(data)>, Frame::Inertial>, \\\n             Tags::VelocityField<DIM(data)>>\n\n#define INSTANTIATION(r, data)                                                \\\n  template class MonotisedCentral<DIM(data)>;                                 \\\n  template bool operator==                                                    \\\n      <DIM(data)>(const MonotisedCentral<DIM(data)>& /*lhs*/,                 \\\n                  const MonotisedCentral<DIM(data)>& /*rhs*/);                \\\n  template bool operator!=<DIM(data)>(const MonotisedCentral<DIM(data)>& lhs, \\\n                                      const MonotisedCentral<DIM(data)>& rhs);\n\nGENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2))\n#undef INSTANTIATION\n\n#define INSTANTIATION(r, data)                                                 \\\n  template void MonotisedCentral<DIM(data)>::reconstruct(                      \\\n      gsl::not_null<std::array<Variables<TAGS_LIST(data)>, DIM(data)>*>        \\\n          vars_on_lower_face,                                                  \\\n      gsl::not_null<std::array<Variables<TAGS_LIST(data)>, DIM(data)>*>        \\\n          vars_on_upper_face,                                                  \\\n      const Variables<tmpl::list<Tags::U>>& volume_vars,                       \\\n      const Element<DIM(data)>& element,                                       \\\n      const FixedHashMap<                                                      \\\n          maximum_number_of_neighbors(DIM(data)),                              \\\n          std::pair<Direction<DIM(data)>, ElementId<DIM(data)>>,               \\\n          std::vector<double>,                                                 \\\n          boost::hash<std::pair<Direction<DIM(data)>, ElementId<DIM(data)>>>>& \\\n          neighbor_data,                                                       \\\n      const Mesh<DIM(data)>& subcell_mesh) const;                              \\\n  template void MonotisedCentral<DIM(data)>::reconstruct_fd_neighbor(          \\\n      gsl::not_null<Variables<TAGS_LIST(data)>*> vars_on_face,                 \\\n      const Variables<tmpl::list<Tags::U>>& volume_vars,                       \\\n      const Element<DIM(data)>& element,                                       \\\n      const FixedHashMap<                                                      \\\n          maximum_number_of_neighbors(DIM(data)),                              \\\n          std::pair<Direction<DIM(data)>, ElementId<DIM(data)>>,               \\\n          std::vector<double>,                                                 \\\n          boost::hash<std::pair<Direction<DIM(data)>, ElementId<DIM(data)>>>>& \\\n          neighbor_data,                                                       \\\n      const Mesh<DIM(data)>& subcell_mesh,                                     \\\n      const Direction<DIM(data)> direction_to_reconstruct) const;\n\nGENERATE_INSTANTIATIONS(INSTANTIATION, (1, 2))\n\n#undef INSTANTIATION\n#undef TAGS_LIST\n#undef DIM\n}  // namespace ScalarAdvection::fd\n", "meta": {"hexsha": "2e06ee82a7f671f2870b64e30c491fe27224b1d8", "size": 8366, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Evolution/Systems/ScalarAdvection/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/ScalarAdvection/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/ScalarAdvection/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": 45.967032967, "max_line_length": 82, "alphanum_fraction": 0.614391585, "num_tokens": 1811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2190522431542699}}
{"text": "#pragma once\n\n#ifdef USE_FIBONACCI_HEAP\n#include <boost/heap/fibonacci_heap.hpp>\n#endif\n\n#include <boost/functional/hash.hpp>\n#include <boost/heap/d_ary_heap.hpp>\n\n#include <unordered_map>\n#include <unordered_set>\n\n// #include \"neighbor.hpp\"\n// #include \"planresult.hpp\"\n#include \"a_star.hpp\"\n\nnamespace libMultiRobotPlanning {\n\n/*!\n  \\example sipp.cpp Simple example using a 2D grid world and\n  up/down/left/right\n  actions\n*/\n\n/*! \\brief SIPP Algorithm to find the shortest path with dynamic obstacles\n\nThis class implements the SIPP algorithm. SIPP is an informed search algorithm\nthat finds the shortest path for a given map and dynamic a-priori known\nobstacles.\nIt can use a heuristic that needs to be admissible.\n\nDetails of the algorithm can be found in the following paper:\\n\nMike Phillips and Maxim Likhachev:\\n\n\"SIPP:  Safe  Interval  Path  Planning  for  Dynamic  Environments\". IEEE\nInternational Conference on Robotics and Automation (ICRA), 2011\\n\nhttps://doi.org/10.1109/ICRA.2011.5980306\n\nThis class can either use a fibonacci heap, or a d-ary heap. The latter is the\ndefault. Define \"USE_FIBONACCI_HEAP\" to use the fibonacci heap instead.\n\n\\tparam State Custom state for the search. Needs to be copy'able\n\\tparam Location Custom location type for the search. Needs to be copy'able\n\\tparam Cost Custom Cost type (integer or floating point types)\n\\tparam Environment This class needs to provide the custom A* logic. In\n    particular, it needs to support the following functions:\n  - `Cost admissibleHeuristic(const State& s)`\\n\n    This function can return 0 if no suitable heuristic is available.\n\n  - `bool isSolution(const State& s)`\\n\n    Return true if the given state is a goal state.\n\n  - `void getNeighbors(const State& s, std::vector<Neighbor<State, Action,\n   int> >& neighbors)`\\n\n    Fill the list of neighboring state for the given state s.\n\n  - `void onExpandNode(const State& s, int fScore, int gScore)`\\n\n    This function is called on every expansion and can be used for statistical\npurposes.\n\n  - `void onDiscover(const State& s, int fScore, int gScore)`\\n\n    This function is called on every node discovery and can be used for\n   statistical purposes.\n*/\ntemplate <typename State, typename Location, typename Action, typename Cost,\n          typename Environment>\nclass SIPP {\n public:\n  struct interval {\n    interval(Cost start, Cost end) : start(start), end(end) {}\n\n    Cost start;\n    Cost end;\n\n    friend bool operator<(const interval& a, const interval& b) {\n      return a.start < b.start;\n    }\n  };\n\n public:\n   struct edgeCollision{\n \t  edgeCollision(Cost t, Action action) : t(t), action(action){}\n\n \tCost t;\n \tAction action;\n \tfriend bool operator==(const edgeCollision& a, const edgeCollision& b){\n \t\treturn (a.t == b.t) && (a.action == b.action);\n \t}\n  };\n\n public:\n  SIPP(Environment& environment) : m_env(environment), m_astar(m_env) {}\n\n  void setCollisionIntervals(const Location& location,\n                             const std::vector<interval>& intervals) {\n    m_env.setCollisionIntervals(location, intervals);\n  }\n\n  void setEdgeCollisions(const Location& location,\n                             const std::vector<edgeCollision>& ec) {\n    m_env.setEdgeCollisions(location, ec);\n  }\n\n  bool mightHaveSolution(const State& goal) {\n    return m_env.mightHaveSolution(goal);\n  }\n\n  bool search(const State& startState, const Action& waitAction,\n              PlanResult<State, Action, Cost>& solution, Cost startTime = 0) {\n    PlanResult<SIPPState, SIPPAction, Cost> astarsolution;\n    solution.cost = 0;\n    solution.fmin = 0;\n    solution.actions.clear();\n    solution.states.clear();\n    size_t interval;\n    if (!m_env.findSafeInterval(startState, startTime, interval)) {\n      return false;\n    }\n    bool success = m_astar.search(SIPPState(startState, interval),\n                                  astarsolution, startTime);\n    solution.cost = astarsolution.cost - startTime;\n    solution.fmin = astarsolution.fmin;\n    for (size_t i = 0; i < astarsolution.actions.size(); ++i) {\n      Cost waitTime =\n          astarsolution.actions[i].second - astarsolution.actions[i].first.time;\n      if (waitTime == 0) {\n        solution.states.push_back(\n            std::make_pair<>(astarsolution.states[i].first.state,\n                             astarsolution.states[i].second));\n        solution.actions.push_back(\n            std::make_pair<>(astarsolution.actions[i].first.action,\n                             astarsolution.actions[i].second));\n      } else {\n        // additional wait action before\n        solution.states.push_back(\n            std::make_pair<>(astarsolution.states[i].first.state,\n                             astarsolution.states[i].second));\n        solution.actions.push_back(std::make_pair<>(waitAction, waitTime));\n        solution.states.push_back(\n            std::make_pair<>(astarsolution.states[i].first.state,\n                             astarsolution.states[i].second + waitTime));\n        solution.actions.push_back(\n            std::make_pair<>(astarsolution.actions[i].first.action,\n                             astarsolution.actions[i].first.time));\n      }\n    }\n    solution.states.push_back(\n        std::make_pair<>(astarsolution.states.back().first.state,\n                         astarsolution.states.back().second));\n\n    return success;\n  }\n\n private:\n  // public:\n  struct SIPPState {\n    SIPPState(const State& state, size_t interval)\n        : state(state), interval(interval) {}\n    SIPPState(const State& state, size_t interval, unsigned int dir)\n        : state(state), interval(interval), dir(dir) {}\n\n    bool operator==(const SIPPState& other) const {\n      return std::tie(state, interval) == std::tie(other.state, other.interval);\n    }\n\n    friend std::ostream& operator<<(std::ostream& os, const SIPPState& s) {\n      return os << \"(\" << s.state << \",\" << s.interval << \")\";\n    }\n\n    State state;\n    unsigned int dir;\n    size_t interval;\n  };\n\n  struct SIPPStateHasher {\n    size_t operator()(const SIPPState& s) const {\n      size_t seed = 0;\n      boost::hash_combine(seed, std::hash<State>()(s.state));\n      boost::hash_combine(seed, s.interval);\n      return seed;\n    }\n  };\n\n  struct SIPPAction {\n    SIPPAction(const Action& action, Cost time) : action(action), time(time) {}\n\n    Action action;\n    Cost time;\n  };\n\n  // private:\n  struct SIPPEnvironment {\n    SIPPEnvironment(Environment& env) : m_env(env) {}\n\n    Cost admissibleHeuristic(const SIPPState& s) {\n      return m_env.admissibleHeuristic(s.state);\n    }\n\n    bool mightHaveSolution(const State& goal) {\n      const auto& si = safeIntervals(m_env.getLocation(goal));\n      return m_env.isSolution(goal) && !si.empty() &&\n             si.back().end == std::numeric_limits<Cost>::max();\n    }\n\n    bool isSolution(const SIPPState& s) {\n      return m_env.isSolution(s.state) &&\n             safeIntervals(m_env.getLocation(s.state)).at(s.interval).end ==\n                 std::numeric_limits<Cost>::max();\n    }\n\n    void getNeighbors(\n        const SIPPState& s,\n        std::vector<Neighbor<SIPPState, SIPPAction, Cost> >& neighbors) {\n      std::vector<Neighbor<State, Action, Cost> > motions;\n// \t  std::cout << \"Current state ---------------------------------------GScore \" << m_lastGScore << \" \" << s.state.x << \" \" << s.state.y << \" dir \" << s.dir << \" \\n\";\n\n\n      m_env.getNeighbors(s.state, motions);\n      for (const auto& m : motions) {\n    \t  m_env.num_generation++;\n        // std::cout << \"gN \" << m.state << std::endl;\n        Cost m_time = m.cost;\n        // std::cout << m_lastGScore;\n        Cost start_t = m_lastGScore + m_time;\n        Cost end_t =\n            safeIntervals(m_env.getLocation(s.state)).at(s.interval).end;\n\n        const auto& sis = safeIntervals(m_env.getLocation(m.state));\n        for (size_t i = 0; i < sis.size(); ++i) {\n          const interval& si = sis[i];\n//          std::cout << m.state.x << \" \" << m.state.y << \"  i \" << i << \": \" << si.start << \" , \" << si.end << \" \" << start_t << \" \" << end_t<< \" \\n\";\n          // std::endl;\n          if (si.start - m_time > end_t || si.end < start_t) {\n            continue;\n          }\n//          std::cout << \" --------------\\n\";\n          int t;\n          unsigned int dir_1 = 0x00;\n          Action a_temp;\n          if(m.action == Action::Left) {a_temp = Action::Right;dir_1 = 0x01;}\n          else if(m.action == Action::Right) {a_temp = Action::Left; dir_1 = 0x02;}\n          else if(m.action == Action::Up) {a_temp = Action::Down;dir_1 = 0x04;}\n          else if(m.action == Action::Down){ a_temp = Action::Up; dir_1 = 0x08;}\n\n          if (m_env.isCommandValid(s.state, m.state, m.action, m_lastGScore,\n                                   end_t, si.start, si.end, t)\n        \t\t  && !IsEdgeCollisions(m.state, edgeCollision(t - 1, a_temp))) {\n            // std::cout << \"  gN: \" << m.state << \",\" << i << \",\" << t << \",\"\n            // << m_lastGScore << std::endl;\n            neighbors.emplace_back(Neighbor<SIPPState, SIPPAction, Cost>(\n                SIPPState(m.state, i, dir_1), SIPPAction(m.action, m.cost),\n                t - m_lastGScore));\n//               std::cout << \"Successor : \" << m.state.x << \" \" << m.state.y <<\" Cost \" << m.cost  << \" dir \" << dir_1 << \" Gscore \" << t << \" \\n\";\n          }\n        }\n      }\n    }\n\n    void onExpandNode(const SIPPState& s, Cost fScore, Cost gScore) {\n      // const auto& interval =\n      // safeIntervals(m_env.getLocation(s.state)).at(s.interval);\n      // std::cout << \"expand: \" << s.state << \",\" << interval.start << \" to \"\n      // << interval.end << \"(g: \" << gScore << \" f: \" << fScore << \")\" <<\n      // std::endl;\n      // This is called before getNeighbors(). We use the callback to find the\n      // current cost (=time) of the expanded node\n      m_env.num_expansion++;\n      m_lastGScore = gScore;\n      m_env.onExpandNode(s.state, fScore, gScore);\n    }\n\n    void onDiscover(const SIPPState& s, Cost fScore, Cost gScore) {\n      // const auto& interval =\n      // safeIntervals(m_env.getLocation(s.state)).at(s.interval);\n      // std::cout << \"discover: \" << s.state << \",\" << interval.start << \" to \"\n      // << interval.end << std::endl;\n      m_env.onDiscover(s.state, fScore, gScore);\n    }\n\n    void setCollisionIntervals(const Location& location,\n                               const std::vector<interval>& intervals) {\n      m_safeIntervals.erase(location);\n      std::vector<interval> sortedIntervals(intervals);\n      std::sort(sortedIntervals.begin(), sortedIntervals.end());\n\n      // std::cout << location << \": \" << std::endl;\n      if (intervals.size() > 0) {\n        m_safeIntervals[location];  // create empty safe interval\n        int start = 0;\n        int lastEnd = 0;\n        for (const auto& interval : sortedIntervals) {\n          // std::cout << \"  ci: \" << interval.start << \" - \" << interval.end <<\n          // std::endl;\n          assert(interval.start <= interval.end);\n          assert(start <= interval.start);\n          // if (start + 1 != interval.start - 1) {\n          // std::cout << start << \",\" << interval.start << std::endl;\n          // assert(start + 1 < interval.start - 1);\n          if (start <= interval.start - 1) {\n            m_safeIntervals[location].push_back({start, interval.start - 1});\n          }\n          // }\n          start = interval.end + 1;\n          lastEnd = interval.end;\n        }\n        if (lastEnd < std::numeric_limits<int>::max()) {\n          // assert(start < std::numeric_limits<int>::max());\n          m_safeIntervals[location].push_back(\n              {start, std::numeric_limits<int>::max()});\n        }\n      }\n\n      // auto iter = m_safeIntervals.find(location);\n      // if (iter != m_safeIntervals.end()) {\n      //   for (const auto& si : iter->second) {\n      //     std::cout << \"  si: \" << si.start << \" - \" << si.end << std::endl;\n      //   }\n      // }\n    }\n\n    bool findSafeInterval(const State& state, Cost time, size_t& interval) {\n      const auto& si = safeIntervals(m_env.getLocation(state));\n      for (size_t idx = 0; idx < si.size(); ++idx) {\n        if (si[idx].start <= time && si[idx].end >= time) {\n          interval = idx;\n          return true;\n        }\n      }\n      return false;\n    }\n\n    void setEdgeCollisions(const Location& location,\n  \t\t  \t  \t  \t  \tconst std::vector<edgeCollision>& edge_collision) {\n  \t  m_edgeCollision.erase(location);\n  \t  if(edge_collision.size() > 0){\n  \t\t  m_edgeCollision[location];\n  \t\t  for(const auto& ec : edge_collision){\n  \t\t\t  m_edgeCollision[location].push_back(ec);\n  \t\t  }\n  \t  }\n    }\n\n    bool IsEdgeCollisions(const Location& location, const edgeCollision& ec){\n//    \t\tstd::cout << location.x << \" \" << location.y << \" \" << ec.t << \" \" << ec.action << std::endl;\n//    \t\treturn false;\n    \t\tconst auto iter = m_edgeCollision.find(location);\n    \t\tif(iter == m_edgeCollision.end()) return false;\n    \t\tif((iter->second).size() == 0) return false;\n    \t\tfor (auto& cec : (iter->second)){\n    \t\t\tif( cec == ec ){\n    \t\t\t\treturn true;\n    \t\t\t}\n    \t\t}\n    \t\treturn false;\n    }\n\n   private:\n    const std::vector<interval>& safeIntervals(const Location& location) {\n      static std::vector<interval> defaultInterval(\n          1, {0, std::numeric_limits<Cost>::max()});\n      const auto iter = m_safeIntervals.find(location);\n      if (iter == m_safeIntervals.end()) {\n        return defaultInterval;\n      }\n      return iter->second;\n    }\n\n   private:\n    Environment& m_env;\n    Cost m_lastGScore;\n    std::unordered_map<Location, std::vector<interval> > m_safeIntervals;\n    std::unordered_map<Location, std::vector<edgeCollision>> m_edgeCollision;\n  };\n\n private:\n  SIPPEnvironment m_env;\n  AStar<SIPPState, SIPPAction, Cost, SIPPEnvironment, SIPPStateHasher> m_astar;\n};\n\n}  // namespace libMultiRobotPlanning\n", "meta": {"hexsha": "03324ee9b9d226b695cb607f5e8fe9723117d7ec", "size": 13836, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/libMultiRobotPlanning/sipp.hpp", "max_stars_repo_name": "husl903/Multi-pathfinding", "max_stars_repo_head_hexsha": "5629e9295904995e3dee075431802f435c0e12f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/libMultiRobotPlanning/sipp.hpp", "max_issues_repo_name": "husl903/Multi-pathfinding", "max_issues_repo_head_hexsha": "5629e9295904995e3dee075431802f435c0e12f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/libMultiRobotPlanning/sipp.hpp", "max_forks_repo_name": "husl903/Multi-pathfinding", "max_forks_repo_head_hexsha": "5629e9295904995e3dee075431802f435c0e12f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4105263158, "max_line_length": 167, "alphanum_fraction": 0.6012575889, "num_tokens": 3437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21878301691974728}}
{"text": "/* Copyright (c) 2016 - 2020, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#ifndef THERMAL_PHYSICS_TEMPLATES_HH\n#define THERMAL_PHYSICS_TEMPLATES_HH\n\n#include <ThermalOperator.hh>\n#ifdef ADAMANTINE_HAVE_CUDA\n#include <ThermalOperatorDevice.hh>\n#endif\n#include <ThermalPhysics.hh>\n\n#include <deal.II/dofs/dof_tools.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/grid/filtered_iterator.h>\n#include <deal.II/lac/precondition.h>\n#include <deal.II/lac/solver_gmres.h>\n\n#include <algorithm>\n\nnamespace adamantine\n{\nnamespace\n{\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value,\n              int> = 0>\ndealii::LA::distributed::Vector<double, MemorySpaceType> vmult_and_scale(\n    std::shared_ptr<ThermalOperatorBase<dim, MemorySpaceType>> thermal_operator,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &y,\n    dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> &value,\n    std::vector<Timer> &timers)\n{\n  // Apply the Thermal Operator.\n  thermal_operator->vmult_add(value, y);\n\n  // Multiply by the inverse of the mass matrix.\n  value.scale(*thermal_operator->get_inverse_mass_matrix());\n\n  timers[evol_time_eval_th_ph].stop();\n\n  return value;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value,\n              int> = 0>\nvoid init_dof_vector(\n    dealii::DoFHandler<dim> const &dof_handler, dealii::FE_Q<dim> const &fe,\n    double const value,\n    dealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType> &vector)\n{\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> dummy;\n  dealii::QGauss<dim> quadrature(1);\n  dealii::FEValues<dim> fe_values(fe, quadrature, dealii::update_values);\n  unsigned int const dofs_per_cell = fe.dofs_per_cell;\n  std::vector<dealii::types::global_dof_index> local_dof_indices(dofs_per_cell);\n  dealii::IndexSet local_elements = vector.locally_owned_elements();\n  for (auto cell :\n       dealii::filter_iterators(dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    fe_values.reinit(cell);\n    cell->get_dof_indices(local_dof_indices);\n    for (auto const dof_index : local_dof_indices)\n    {\n      if (local_elements.is_element(dof_index) == true)\n        vector[dof_index] = value;\n    }\n  }\n}\n\n#ifdef ADAMANTINE_HAVE_CUDA\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\ndealii::LA::distributed::Vector<double, MemorySpaceType> vmult_and_scale(\n    std::shared_ptr<ThermalOperatorBase<dim, MemorySpaceType>> thermal_operator,\n    dealii::LA::distributed::Vector<double, MemorySpaceType> const &y,\n    dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> &value,\n    std::vector<Timer> &timers)\n{\n  dealii::LA::distributed::Vector<double, MemorySpaceType> value_dev(\n      value.get_partitioner());\n  value_dev.import(value, dealii::VectorOperation::insert);\n\n  // Apply the Thermal Operator.\n  thermal_operator->vmult_add(value_dev, y);\n\n  // Multiply by the inverse of the mass matrix.\n  value_dev.scale(*thermal_operator->get_inverse_mass_matrix());\n\n  timers[evol_time_eval_th_ph].stop();\n\n  return value_dev;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          std::enable_if_t<\n              std::is_same<MemorySpaceType, dealii::MemorySpace::CUDA>::value,\n              int> = 0>\nvoid init_dof_vector(\n    dealii::DoFHandler<dim> const &dof_handler, dealii::FE_Q<dim> const &fe,\n    double const value,\n    dealii::LinearAlgebra::distributed::Vector<double, MemorySpaceType> &vector)\n{\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host>\n      vector_host(vector.get_partitioner());\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> dummy;\n\n  dealii::QGauss<dim> quadrature(1);\n  dealii::FEValues<dim> fe_values(fe, quadrature, dealii::update_values);\n  unsigned int const dofs_per_cell = fe.dofs_per_cell;\n  std::vector<dealii::types::global_dof_index> local_dof_indices(dofs_per_cell);\n  dealii::IndexSet local_elements = vector.locally_owned_elements();\n  for (auto cell :\n       dealii::filter_iterators(dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    fe_values.reinit(cell);\n    cell->get_dof_indices(local_dof_indices);\n    for (auto const dof_index : local_dof_indices)\n    {\n      if (local_elements.is_element(dof_index) == true)\n        vector_host[dof_index] = value;\n    }\n  }\n  vector.import(vector_host, dealii::VectorOperation::insert);\n}\n#endif\n} // namespace\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::ThermalPhysics(\n    MPI_Comm const &communicator, boost::property_tree::ptree const &database,\n    Geometry<dim> &geometry)\n    : _embedded_method(false), _implicit_method(false), _geometry(geometry),\n      _fe(fe_degree), _dof_handler(_geometry.get_triangulation()),\n      _quadrature(fe_degree + 1)\n{\n  // Create the material properties\n  boost::property_tree::ptree const &material_database =\n      database.get_child(\"materials\");\n  _material_properties.reset(new MaterialProperty<dim>(\n      communicator, _geometry.get_triangulation(), material_database));\n\n  // Create the electron beams\n  boost::property_tree::ptree const &source_database =\n      database.get_child(\"sources\");\n  unsigned int const n_beams = source_database.get<unsigned int>(\"n_beams\");\n  _electron_beams.resize(n_beams);\n  for (unsigned int i = 0; i < n_beams; ++i)\n  {\n    boost::property_tree::ptree const &beam_database =\n        source_database.get_child(\"beam_\" + std::to_string(i));\n    _electron_beams[i] = std::make_unique<ElectronBeam<dim>>(beam_database);\n    _electron_beams[i]->set_max_height(_geometry.get_max_height());\n  }\n\n  // Create the thermal operator\n  if (std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value)\n    _thermal_operator =\n        std::make_shared<ThermalOperator<dim, fe_degree, MemorySpaceType>>(\n            communicator, _material_properties);\n#ifdef ADAMANTINE_HAVE_CUDA\n  else\n    _thermal_operator = std::make_shared<\n        ThermalOperatorDevice<dim, fe_degree, MemorySpaceType>>(\n        communicator, _material_properties);\n#endif\n\n  // Create the time stepping scheme\n  boost::property_tree::ptree const &time_stepping_database =\n      database.get_child(\"time_stepping\");\n  std::string method = time_stepping_database.get<std::string>(\"method\");\n  std::transform(method.begin(), method.end(), method.begin(),\n                 [](unsigned char c) { return std::tolower(c); });\n  if (method.compare(\"forward_euler\") == 0)\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ExplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::FORWARD_EULER);\n  else if (method.compare(\"rk_third_order\") == 0)\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ExplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::RK_THIRD_ORDER);\n  else if (method.compare(\"rk_fourth_order\") == 0)\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ExplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::RK_CLASSIC_FOURTH_ORDER);\n  else if (method.compare(\"heun_euler\") == 0)\n  {\n    _time_stepping = std::make_unique<\n        dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector>>(\n        dealii::TimeStepping::HEUN_EULER);\n    _embedded_method = true;\n  }\n  else if (method.compare(\"bogacki_shampine\") == 0)\n  {\n    _time_stepping = std::make_unique<\n        dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector>>(\n        dealii::TimeStepping::BOGACKI_SHAMPINE);\n    _embedded_method = true;\n  }\n  else if (method.compare(\"dopri\") == 0)\n  {\n    _time_stepping = std::make_unique<\n        dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector>>(\n        dealii::TimeStepping::DOPRI);\n    _embedded_method = true;\n  }\n  else if (method.compare(\"fehlberg\") == 0)\n  {\n    _time_stepping = std::make_unique<\n        dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector>>(\n        dealii::TimeStepping::FEHLBERG);\n    _embedded_method = true;\n  }\n  else if (method.compare(\"cash_karp\") == 0)\n  {\n    _time_stepping = std::make_unique<\n        dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector>>(\n        dealii::TimeStepping::CASH_KARP);\n    _embedded_method = true;\n  }\n  else if (method.compare(\"backward_euler\") == 0)\n  {\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ImplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::BACKWARD_EULER);\n    _implicit_method = true;\n  }\n  else if (method.compare(\"implicit_midpoint\") == 0)\n  {\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ImplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::IMPLICIT_MIDPOINT);\n    _implicit_method = true;\n  }\n  else if (method.compare(\"crank_nicolson\") == 0)\n  {\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ImplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::CRANK_NICOLSON);\n    _implicit_method = true;\n  }\n  else if (method.compare(\"sdirk2\") == 0)\n  {\n    _time_stepping =\n        std::make_unique<dealii::TimeStepping::ImplicitRungeKutta<LA_Vector>>(\n            dealii::TimeStepping::SDIRK_TWO_STAGES);\n    _implicit_method = true;\n  }\n\n  if (_embedded_method == true)\n  {\n    double coarsen_param =\n        time_stepping_database.get(\"coarsening_parameter\", 1.2);\n    double refine_param = time_stepping_database.get(\"refining_parameter\", 0.8);\n    double min_delta = time_stepping_database.get(\"min_time_step\", 1e-14);\n    double max_delta = time_stepping_database.get(\"max_time_step\", 1e100);\n    double refine_tol = time_stepping_database.get(\"refining_tolerance\", 1e-8);\n    double coarsen_tol =\n        time_stepping_database.get(\"coarsening_tolerance\", 1e-12);\n    dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector> *embedded_rk =\n        static_cast<\n            dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector> *>(\n            _time_stepping.get());\n    embedded_rk->set_time_adaptation_parameters(coarsen_param, refine_param,\n                                                min_delta, max_delta,\n                                                refine_tol, coarsen_tol);\n  }\n\n  // If the time stepping scheme is implicit, set the parameters for the solver\n  // and create the implicit operator.\n  if (_implicit_method == true)\n  {\n    _max_iter = time_stepping_database.get(\"max_iteration\", 1000);\n    _tolerance = time_stepping_database.get(\"tolerance\", 1e-12);\n    _right_preconditioning =\n        time_stepping_database.get(\"right_preconditioning\", false);\n    _max_n_tmp_vectors = time_stepping_database.get(\"n_tmp_vectors\", 30);\n    unsigned int newton_max_iter =\n        time_stepping_database.get(\"newton_max_iteration\", 100);\n    double newton_tolerance =\n        time_stepping_database.get(\"newton_tolerance\", 1e-6);\n    dealii::TimeStepping::ImplicitRungeKutta<LA_Vector> *implicit_rk =\n        static_cast<dealii::TimeStepping::ImplicitRungeKutta<LA_Vector> *>(\n            _time_stepping.get());\n    implicit_rk->set_newton_solver_parameters(newton_max_iter,\n                                              newton_tolerance);\n\n    bool jfnk = time_stepping_database.get(\"jfnk\", false);\n    _implicit_operator = std::make_unique<ImplicitOperator<MemorySpaceType>>(\n        _thermal_operator, jfnk);\n  }\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                    QuadratureType>::setup_dofs()\n{\n  _dof_handler.distribute_dofs(_fe);\n  dealii::IndexSet locally_relevant_dofs;\n  dealii::DoFTools::extract_locally_relevant_dofs(_dof_handler,\n                                                  locally_relevant_dofs);\n  _affine_constraints.clear();\n  _affine_constraints.reinit(locally_relevant_dofs);\n  dealii::DoFTools::make_hanging_node_constraints(_dof_handler,\n                                                  _affine_constraints);\n  _affine_constraints.close();\n\n  _thermal_operator->reinit(_dof_handler, _affine_constraints, _quadrature);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType,\n                    QuadratureType>::compute_inverse_mass_matrix()\n{\n  _thermal_operator->compute_inverse_mass_matrix(_dof_handler,\n                                                 _affine_constraints);\n  if (_implicit_method == true)\n    _implicit_operator->set_inverse_mass_matrix(\n        _thermal_operator->get_inverse_mass_matrix());\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ndouble ThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    evolve_one_time_step(\n        double t, double delta_t,\n        dealii::LA::distributed::Vector<double, MemorySpaceType> &solution,\n        std::vector<Timer> &timers)\n{\n  auto eval = [&](double const t, LA_Vector const &y) {\n    return evaluate_thermal_physics(t, y, timers);\n  };\n  auto id_m_Jinv = [&](double const t, double const tau, LA_Vector const &y) {\n    return id_minus_tau_J_inverse(t, tau, y, timers);\n  };\n\n  double time = _time_stepping->evolve_one_time_step(eval, id_m_Jinv, t,\n                                                     delta_t, solution);\n\n  // If the method is embedded, get the next time step. Otherwise, just use the\n  // current time step.\n  if (_embedded_method == false)\n    _delta_t_guess = delta_t;\n  else\n  {\n    dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector> *embedded_rk =\n        static_cast<\n            dealii::TimeStepping::EmbeddedExplicitRungeKutta<LA_Vector> *>(\n            _time_stepping.get());\n    _delta_t_guess = embedded_rk->get_status().delta_t_guess;\n  }\n\n  // Return the time at the end of the time step. This may be different than\n  // t+delta_t for embedded methods.\n  return time;\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    initialize_dof_vector(\n        dealii::LA::distributed::Vector<double, MemorySpaceType> &vector) const\n{\n  _thermal_operator->initialize_dof_vector(vector);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\nvoid ThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    initialize_dof_vector(\n        double const value,\n        dealii::LA::distributed::Vector<double, MemorySpaceType> &vector) const\n{\n  // Resize the vector\n  _thermal_operator->initialize_dof_vector(vector);\n\n  init_dof_vector<dim, fe_degree, MemorySpaceType>(_dof_handler, _fe, value,\n                                                   vector);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ndealii::LA::distributed::Vector<double, MemorySpaceType>\nThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    evaluate_thermal_physics(\n        double const t,\n        dealii::LA::distributed::Vector<double, MemorySpaceType> const &y,\n        std::vector<Timer> &timers) const\n{\n  timers[evol_time_eval_mat_prop].start();\n  if (std::is_same<MemorySpaceType, dealii::MemorySpace::Host>::value)\n    _thermal_operator->evaluate_material_properties(y);\n  else\n  {\n    // TODO do this on the GPU\n    dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> y_host(\n        y.get_partitioner());\n    y_host.import(y, dealii::VectorOperation::insert);\n    _thermal_operator->evaluate_material_properties(y_host);\n  }\n  timers[evol_time_eval_mat_prop].stop();\n\n  timers[evol_time_eval_th_ph].start();\n  dealii::LA::distributed::Vector<double, dealii::MemorySpace::Host> source(\n      y.get_partitioner());\n  source = 0.;\n\n  // Compute the source term.\n  for (auto &beam : _electron_beams)\n    beam->set_time(t);\n  dealii::QGauss<dim> source_quadrature(fe_degree + 1);\n  dealii::FEValues<dim> fe_values(_fe, source_quadrature,\n                                  dealii::update_quadrature_points |\n                                      dealii::update_values |\n                                      dealii::update_JxW_values);\n  unsigned int const dofs_per_cell = _fe.dofs_per_cell;\n  unsigned int const n_q_points = source_quadrature.size();\n  std::vector<dealii::types::global_dof_index> local_dof_indices(dofs_per_cell);\n  dealii::Vector<double> cell_source(dofs_per_cell);\n\n  for (auto cell :\n       dealii::filter_iterators(_dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    cell_source = 0.;\n    fe_values.reinit(cell);\n    double const inv_rho_cp = _thermal_operator->get_inv_rho_cp(cell);\n\n    for (unsigned int i = 0; i < dofs_per_cell; ++i)\n    {\n      for (unsigned int q = 0; q < n_q_points; ++q)\n      {\n        double quad_pt_source = 0.;\n        dealii::Point<dim> const &q_point = fe_values.quadrature_point(q);\n        for (auto &beam : _electron_beams)\n          quad_pt_source += beam->value(q_point);\n\n        cell_source[i] += inv_rho_cp * quad_pt_source *\n                          fe_values.shape_value(i, q) * fe_values.JxW(q);\n      }\n    }\n    cell->get_dof_indices(local_dof_indices);\n    _affine_constraints.distribute_local_to_global(cell_source,\n                                                   local_dof_indices, source);\n  }\n\n  return vmult_and_scale<dim, fe_degree, MemorySpaceType>(_thermal_operator, y,\n                                                          source, timers);\n}\n\ntemplate <int dim, int fe_degree, typename MemorySpaceType,\n          typename QuadratureType>\ndealii::LA::distributed::Vector<double, MemorySpaceType>\nThermalPhysics<dim, fe_degree, MemorySpaceType, QuadratureType>::\n    id_minus_tau_J_inverse(\n        double const /*t*/, double const tau,\n        dealii::LA::distributed::Vector<double, MemorySpaceType> const &y,\n        std::vector<Timer> &timers) const\n{\n  timers[evol_time_J_inv].start();\n  _implicit_operator->set_tau(tau);\n  dealii::LA::distributed::Vector<double, MemorySpaceType> solution(\n      y.get_partitioner());\n\n  // TODO Add a geometric multigrid preconditioner.\n  dealii::PreconditionIdentity preconditioner;\n\n  dealii::SolverControl solver_control(_max_iter, _tolerance * y.l2_norm());\n  // We need to inverse (I - tau M^{-1} J). While M^{-1} and J are SPD,\n  // (I - tau M^{-1} J) is symmetric indefinite in the general case.\n  typename dealii::SolverGMRES<\n      dealii::LA::distributed::Vector<double, MemorySpaceType>>::AdditionalData\n      additional_data(_max_n_tmp_vectors, _right_preconditioning);\n  dealii::SolverGMRES<dealii::LA::distributed::Vector<double, MemorySpaceType>>\n      solver(solver_control, additional_data);\n  solver.solve(*_implicit_operator, solution, y, preconditioner);\n\n  timers[evol_time_J_inv].stop();\n\n  return solution;\n}\n} // namespace adamantine\n\n#endif\n", "meta": {"hexsha": "4e9c254d58d08bf252b89c62d3d88f13f413fc9e", "size": 19563, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/ThermalPhysics.templates.hh", "max_stars_repo_name": "stvdwtt/adamantine", "max_stars_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "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": "source/ThermalPhysics.templates.hh", "max_issues_repo_name": "stvdwtt/adamantine", "max_issues_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/ThermalPhysics.templates.hh", "max_forks_repo_name": "stvdwtt/adamantine", "max_forks_repo_head_hexsha": "af396f02089a488a35146ab83234974ae465ada2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.2044088176, "max_line_length": 80, "alphanum_fraction": 0.6955988345, "num_tokens": 4909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.37387582277169656, "lm_q1q2_score": 0.2187551700226091}}
{"text": "// Copyright 2015-2022 The ALMA Project Developers\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//   http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n// implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n#pragma once\n\n/// @file\n/// Classes and functions used to manipulate grids in reciprocal space.\n\n#include <boost/mpi.hpp>\n#include <structures.hpp>\n#include <dynamical_matrix.hpp>\n\nnamespace alma {\n/// Convenient shorthand for an array of four indices.\nusing Tetrahedron = std::array<std::size_t, 4>;\n/// Convenient shorthand for an array of three indices.\nusing Triangle = std::array<std::size_t, 3>;\n\n/// Objects of this class represent a regular grid with the Gamma\n/// point in one corner.\nclass Gamma_grid {\npublic:\n    /// Size of the grid along the first reciprocal axis.\n    const int na;\n    /// Size of the grid along the second reciprocal axis.\n    const int nb;\n    /// Size of the grid along the third reciprocal axis.\n    const int nc;\n    /// Total number of q points in the grid.\n    const std::size_t nqpoints;\n    /// Reciprocal lattice basis vectors.\n    const Eigen::MatrixXd rlattvec;\n    /// Side vectors of each element in reciprocal space.\n    const Eigen::MatrixXd dq;\n    /// Constructor: initialize all internal variables and compute\n    /// the spectrum at each q point. Do not correct the dynamical\n    /// matrix for the effect of long-range interactions.\n    Gamma_grid(const Crystal_structure& poscar,\n               const Symmetry_operations& symms,\n               const Harmonic_ifcs& force_constants,\n               int _na,\n               int _nb,\n               int _nc);\n\n\n    /// Constructor: initialize all internal variables and compute\n    /// the spectrum at each q point. Correct the dynamical\n    /// matrix for the effect of long-range interactions.\n    Gamma_grid(const Crystal_structure& poscar,\n               const Symmetry_operations& symms,\n               const Harmonic_ifcs& force_constants,\n               const Dielectric_parameters& born,\n               int _na,\n               int _nb,\n               int _nc);\n\n\n    /// Set the three lowest frequencies at Gamma to zero.\n    void enforce_asr() {\n        this->spectrum[0].omega.head(3).fill(0.);\n    }\n\n\n    /// Return the index of a q point identified by its position\n    /// along the three axes.\n    ///\n    /// Indices are interpreted modulo-{na, nb, nc}, so even\n    /// negative values are accepted.\n    /// @param[in] indices - positions of the q point\n    /// along the three axes\n    /// @return the index of the q point in this grid\n    std::size_t three_to_one(const std::array<int, 3>& indices) const {\n        auto ia = python_mod(indices[0], this->na);\n        auto ib = python_mod(indices[1], this->nb);\n        auto ic = python_mod(indices[2], this->nc);\n\n        return ic + nc * (ib + nb * ia);\n    }\n\n\n    /// Return the coordinates of a q point identified by its\n    /// index.\n    ///\n    /// @param[in] index - index of the q point\n    /// @return - an array with the positions of the q point\n    /// along the three axes.\n    std::array<int, 3> one_to_three(std::size_t iq) const {\n        std::array<int, 3> nruter;\n        nruter[2] = iq % nc;\n        iq /= nc;\n        nruter[1] = iq % nb;\n        nruter[0] = iq / nb;\n        return nruter;\n    }\n\n\n    /// @return the number of q-point equivalence classes in the grid.\n    std::size_t get_nequivalences() const {\n        return this->equivalences.size();\n    }\n\n\n    /// Access the harmonic properties at a point in the grid.\n    ///\n    /// The index is interpreted using modular arithmetic,\n    /// so even negative values are accepted.\n    /// @param[in] iq - index of the q point\n    /// @return the harmonic properties at the q point.\n    const Spectrum_at_point& get_spectrum_at_q(int iq) const {\n        std::size_t index = python_mod(iq, this->nqpoints);\n\n        return this->spectrum[index];\n    }\n\n\n    /// Return the cardinal of an equivalence class.\n    ///\n    /// @param[in] ic - index of the equivalence class.\n    /// @return the number of points in an equivalence class.\n    std::size_t get_cardinal(std::size_t ic) const {\n        if (ic > this->equivalences.size())\n            throw value_error(\"wrong equivalence class index\");\n        return this->equivalences[ic].size();\n    }\n\n\n    /// Return a representative of an equivalence class.\n    ///\n    /// The method is guaranteed to always return the same point.\n    /// @param[in] ic - index of the equivalence class.\n    /// @return a representative of the equivalence class.\n    std::size_t get_representative(std::size_t ic) const {\n        if (ic > this->equivalences.size())\n            throw value_error(\"wrong equivalence class index\");\n        return this->equivalences[ic][0];\n    }\n\n\n    /// Return the elements in an equivalence class.\n    ///\n    /// @param[in] ic - index of the equivalence class.\n    /// @return a vector with the elements in the equivalence\n    /// class.\n    std::vector<std::size_t> get_equivalence(std::size_t ic) const {\n        if (ic > this->equivalences.size())\n            throw value_error(\"wrong equivalence class index\");\n        return this->equivalences[ic];\n    }\n\n\n    /// Return the Cartesian coordinates of a q point.\n    ///\n    /// @param[in] iq - a q point index\n    /// @return three Cartesian coordinates\n    Eigen::VectorXd get_q(std::size_t iq) const {\n        std::size_t index = python_mod(iq, this->nqpoints);\n\n        return this->cpos.col(index);\n    }\n\n\n    /// Return the base broadening (without any prefactor) for a\n    /// mode.\n    ///\n    /// @param[in] v - group velocity, or difference\n    /// of group velocities in the case of three-phonon processes\n    /// @return - the standard deviation of a Gaussian\n    double base_sigma(const Eigen::VectorXd& v) const {\n        return (v.transpose() * this->dq).norm() / std::sqrt(12.);\n    }\n\n\n    /// Very basic constructor that builds a stub object. Useful\n    /// for deserialization or for obtaining an equivalences vector\n    /// without computing the spectrum.\n    Gamma_grid(const Crystal_structure& poscar,\n               const Symmetry_operations& symms,\n               int _na,\n               int _nb,\n               int _nc);\n\n\n    /// Find the index of the polar opposite q point.\n    ///\n    /// @param[in] q - a q point\n    /// @return the index of the polar opposite of q\n    std::size_t polar_opposite(std::size_t q) {\n        auto indices = this->one_to_three(q);\n\n        return this->three_to_one({{-indices[0], -indices[1], -indices[2]}});\n    }\n\n\n    /// Return the images of a q point through all the symmetry\n    /// operations, including inversions.\n    ///\n    /// @param[in] q - a q point\n    /// @return a vector of q point indices. Elements with even indices\n    /// correspond to operations in the space group,\n    /// while elements with odd indices compound them with time\n    /// reversal.\n    std::vector<size_t> equivalent_qpoints(std::size_t original) const {\n        std::size_t index = python_mod(original, this->nqpoints);\n        return this->symmetry_map[index];\n    }\n\n\n    /// Find all q-point pairs equivalent to the input.\n    ///\n    /// Given a pair of indices, obtain all equivalent pairs\n    /// after looking the up in the symmetry_map.\n    /// @param[in] pair a pair of q point indices\n    /// @return a vector of pairs, including the input\n    std::vector<std::array<std::size_t, 2>> equivalent_qpairs(\n        const std::array<std::size_t, 2>& original) const;\n\n\n    /// Find all q-point triplets equivalent to the input.\n    ///\n    /// Given a triplet of indices, obtain all equivalent triplets\n    /// after looking the up in the symmetry_map.\n    /// @param[in] a triplet of q point indices\n    /// @return a vector of triplets, including the input\n    std::vector<std::array<std::size_t, 3>> equivalent_qtriplets(\n        const std::array<std::size_t, 3>& original) const;\n\n\n    /// Decompose the q-th microcell in five tetrahedra.\n    ///\n    /// @param[in] q - the index of the q point\n    /// @return a vector of five Tetrahedron objects\n    std::vector<Tetrahedron> get_tetrahedra(std::size_t q) const {\n        // Find out the indices of the eight corners of the\n        // microcell.\n        std::size_t i000 = q;\n        auto indices = this->one_to_three(i000);\n        std::size_t i001 =\n            this->three_to_one({{indices[0], indices[1], indices[2] + 1}});\n        std::size_t i010 =\n            this->three_to_one({{indices[0], indices[1] + 1, indices[2]}});\n        std::size_t i011 =\n            this->three_to_one({{indices[0], indices[1] + 1, indices[2] + 1}});\n        std::size_t i100 =\n            this->three_to_one({{indices[0] + 1, indices[1], indices[2]}});\n        std::size_t i101 =\n            this->three_to_one({{indices[0] + 1, indices[1], indices[2] + 1}});\n        std::size_t i110 =\n            this->three_to_one({{indices[0] + 1, indices[1] + 1, indices[2]}});\n        std::size_t i111 = this->three_to_one(\n            {{indices[0] + 1, indices[1] + 1, indices[2] + 1}});\n\n        // Build the four equivalent tetrahedra.\n        std::vector<Tetrahedron> nruter;\n        nruter.reserve(5);\n        nruter.emplace_back(Tetrahedron({{i000, i001, i010, i100}}));\n        nruter.emplace_back(Tetrahedron({{i110, i111, i100, i010}}));\n        nruter.emplace_back(Tetrahedron({{i101, i100, i111, i001}}));\n        nruter.emplace_back(Tetrahedron({{i011, i010, i001, i111}}));\n        // And the central, inequivalent one.\n        nruter.emplace_back(Tetrahedron({{i010, i100, i111, i001}}));\n        return nruter;\n    }\n\n\n    /// @return a vector of triangle objects with each containing three\n    /// indices\n    std::vector<Triangle> get_triangles(std::size_t ia) const;\n\n\n    /// @return the index of the representative of the equivalence\n    /// class\n    /// of the provided q-point\n    std::size_t getParentIdx(std::size_t iq) const;\n\n\n    /// @return the index of the symmetry operation that maps the\n    /// provided q-point\n    /// to the representative of the equivalence class to which it\n    /// belongs\n    std::size_t getSymIdxToParent(std::size_t iq) const;\n\n\n    /// @return the grid's symmetry map\n    std::vector<std::vector<std::size_t>> getSymmetryMap() {\n        return this->symmetry_map;\n    }\n\n\n    /// Remove the component of a Cartesian vector which does transform as a\n    /// q-point in the grid.\n    ///\n    /// @param[in] iq - index of the q point\n    /// @param[in] symms - set of symmetry operations of the crystal\n    /// @param[in] x - vector in Cartesian coordinates. Several vectors can\n    /// be provided by making v a matrix and each vector a column\n    /// @return the symmetrized version of x\n    template <typename T>\n    auto copy_symmetry(std::size_t iq,\n                       const Symmetry_operations& symms,\n                       const Eigen::MatrixBase<T>& x) const\n        -> Eigen::Matrix<typename T::Scalar, Eigen::Dynamic, Eigen::Dynamic> {\n        std::size_t index = python_mod(iq, this->nqpoints);\n        std::size_t nops = symms.get_nsym();\n\n        typename T::PlainObject nruter(x);\n        nruter.fill(0.);\n        std::size_t nfound = 0;\n\n        for (std::size_t iop = 0; iop < nops; ++iop) {\n            if (this->symmetry_map[index][2 * iop] == index) {\n                nruter += symms.rotate_v(x, iop, true);\n                ++nfound;\n            }\n        }\n        nruter /= nfound;\n        return nruter;\n    }\n\nprivate:\n    friend void save_bulk_hdf5(const char* filename,\n                               const std::string& description,\n                               const Crystal_structure& cell,\n                               const Symmetry_operations& symmetries,\n                               const Gamma_grid& grid,\n                               const std::vector<Threeph_process>& processes,\n                               const boost::mpi::communicator& comm);\n\n    friend std::tuple<std::string,\n                      std::unique_ptr<Crystal_structure>,\n                      std::unique_ptr<Symmetry_operations>,\n                      std::unique_ptr<Gamma_grid>,\n                      std::unique_ptr<std::vector<Threeph_process>>>\n    load_bulk_hdf5(const char* filename, const boost::mpi::communicator& comm);\n\n    /// Cartesian coordinates of each q point.\n    Eigen::MatrixXd cpos;\n    /// Harmonic properties at each q point.\n    std::vector<Spectrum_at_point> spectrum;\n    /// Vector of equivalence classes. Two q points in the same\n    /// equivalence class are related by a symmetry operation.\n    /// Note that both space group symmetries and time reversal\n    /// symmetry are taken into account.\n    std::vector<std::vector<std::size_t>> equivalences;\n    /// Detailed map between q points through the symmetry\n    /// operations.\n    std::vector<std::vector<std::size_t>> symmetry_map;\n    /// Initialize the Cartesian coordinates of the q points.\n    /// @param[in] poscar - a description of the crystal structure\n    void initialize_cpos();\n\n    /// Compute the spectrum at a subset of the q points.\n    ///\n    /// That subset is selected on the basis of this process'\n    /// position in an MPI communicator.\n    /// @param[in] factory - object in charge of building the\n    /// dynamical matrix at each point.\n    /// @param[in] symms - set of symmetry operations of the crystal\n    /// @param[in] communicator - MPI communicator to use\n    std::vector<Spectrum_at_point> compute_my_spectrum(\n        const Dynamical_matrix_builder& factory,\n        const Symmetry_operations& symms,\n        const boost::mpi::communicator& communicator);\n\n    /// Fill the equivalences vector.\n    ///\n    /// @param[in] symms - the set of symmetry operations to try.\n    void fill_equivalences(const Symmetry_operations& symms);\n\n    /// Parentlookup table: stores for each q-point the index of\n    /// the representative of the equivalence class to which it\n    /// belongs.\n    std::vector<std::size_t> parentlookup;\n\n    /// Fill the parentlookup table\n    void fill_parentlookup();\n\n    /// Fill the symmetry_map vector.\n    ///\n    /// @param[in] symms - the set of symmetry operations to try.\n    void fill_map(const Symmetry_operations& symms);\n};\n} // namespace alma\n", "meta": {"hexsha": "1a82d232f38ef5ac63f6617c5da8ff7a7045a5cb", "size": 14635, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/qpoint_grid.hpp", "max_stars_repo_name": "sousaw/BTE-Barna", "max_stars_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T03:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:11:20.000Z", "max_issues_repo_path": "include/qpoint_grid.hpp", "max_issues_repo_name": "sousaw/BTE-Barna", "max_issues_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/qpoint_grid.hpp", "max_forks_repo_name": "sousaw/BTE-Barna", "max_forks_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.1446700508, "max_line_length": 79, "alphanum_fraction": 0.6271950803, "num_tokens": 3537, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.3812195521959384, "lm_q1q2_score": 0.21869742559352484}}
{"text": "/*\n    Copyright (c) 2014, Philipp Krähenbühl\n    All rights reserved.\n\t\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n        * Redistributions of source code must retain the above copyright\n        notice, this list of conditions and the following disclaimer.\n        * Redistributions in binary form must reproduce the above copyright\n        notice, this list of conditions and the following disclaimer in the\n        documentation and/or other materials provided with the distribution.\n        * Neither the name of the Stanford University nor the\n        names of its contributors may be used to endorse or promote products\n        derived from this software without specific prior written permission.\n\t\n    THIS SOFTWARE IS PROVIDED BY Philipp Krähenbühl ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL Philipp Krähenbühl BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\t LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\t ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n#include \"util/win_util.h\"\n#include \"gradient.h\"\n#include \"filter.h\"\n#include <stdexcept>\n#include <iostream>\n#include <Eigen/Core>\nusing namespace Eigen;\n\nstatic const float * acosTable(){\n\tstatic float table[2001];\n\tfloat * r = table+1000;\n\tfor( int i=-1000; i<1001; i++ )\n\t\tr[i] = acos( i / 1000. );\n\treturn r;\n}\nstatic void computeGradientOriAndMag( float * g, float * o, const float * gx, const float * gy, int N, int C ) {\n\tconst float * acost = acosTable();\n\tMap<const ArrayXXf> mgx( gx, C, N ), mgy( gy, C, N );\n\tArrayXXf mag = (mgx*mgx+mgy*mgy);\n\tfor( int i=0; i<N; i++ ) {\n\t\tint j;\n\t\tfloat m = mag.col(i).maxCoeff(&j);\n\t\tfloat gm = std::max((float)sqrt(m),1e-10f);\n\t\tfloat cm = mgx(j,i) / gm;\n\t\tif( mgy(j,i) <= -0 ) cm = -cm;\n\t\tif( cm > 1 )  cm = 1;\n\t\tif( cm < -1 ) cm = -1;\n\t\t\n\t\to[i] = acost[(int)(cm*1000)];\n\t\tg[i] = gm;\n\t}\n}\nstatic void computeGradientMag( float * g, const float * gx, const float * gy, int N, int C ) {\n\tMap<const ArrayXXf> mgx( gx, C, N ), mgy( gy, C, N );\n\tMap<VectorXf>(g,N) = (mgx*mgx+mgy*mgy).colwise().maxCoeff().sqrt();\n}\ntemplate <int BINS>\nstatic void computeGradHist( Image & hist, const RMatrixXf & gm, const RMatrixXf & go, int nori ) {\n\tconst int W = gm.cols(), H = gm.rows();\n\tconst int Wb = W/BINS, Hb = H/BINS;\n\tconst int W0 = Wb*BINS, H0 = Hb*BINS;\n\thist.create( Wb, Hb, nori );\n\thist = 0;\n\tfor(int j = 0; j < H0; j++){\n\t\tfloat * phist = hist.data() + (j/BINS)*Wb*nori;\n\t\tfor(int i = 0; i < W0; phist+=nori){\n\t\t\tfor(int k = 0; k < BINS && i<W; i++, k++){\n\t\t\t\tfloat o = go(j,i) / M_PI;\n\t\t\t\tunsigned int o0 = o*nori;\n\t\t\t\tfloat w = o*nori - o0;\n\t\t\t\tif( o0 >= nori )\n\t\t\t\t\to0 = 0;\n\t\t\t\tunsigned int o1 = o0+1;\n\t\t\t\tif( o1 >= nori )\n\t\t\t\t\to1 = 0;\n\t\t\t\tphist[o0] += (1-w)*gm(j,i) / (BINS*BINS);\n\t\t\t\tphist[o1] += w*gm(j,i) / (BINS*BINS);\n\t\t\t}\n\t\t}\n\t}\n}\nvoid gradientHist( Image & hist, const RMatrixXf & gm, const RMatrixXf & go, int nori, int nbins) {\n\tswitch(nbins){\n\t\tcase 1: return computeGradHist<1>(hist, gm, go, nori);\n\t\tcase 2: return computeGradHist<2>(hist, gm, go, nori);\n\t\tcase 3: return computeGradHist<3>(hist, gm, go, nori);\n\t\tcase 4: return computeGradHist<4>(hist, gm, go, nori);\n\t\tcase 5: return computeGradHist<5>(hist, gm, go, nori);\n\t\tcase 6: return computeGradHist<6>(hist, gm, go, nori);\n\t\tcase 7: return computeGradHist<7>(hist, gm, go, nori);\n\t\tcase 8: return computeGradHist<8>(hist, gm, go, nori);\n\t\tdefault: throw std::invalid_argument(\"Bin size too large!\");\n\t}\n}\nstatic void diff( float * r, const float * a, const float * b, int N, float w=1.0 ) {\n\tMap<VectorXf>( r, N ) = w*(Map<VectorXf>( (float*)a, N ) - Map<VectorXf>( (float*)b, N ));\n}\nvoid gradient( Image & gx, Image & gy, const Image & im ) {\n\tconst int W = im.W(), H = im.H(), C = im.C();\n\tgx.create( W, H, C );\n\tgy.create( W, H, C );\n\tfor( int j=0; j<H; j++ ) {\n\t\tfloat * pgx = gx.data()+j*W*C;\n\t\tfloat * pgy = gy.data()+j*W*C;\n\t\tconst float * pim = im.data()+j*W*C;\n\t\t// Compute the x gradient\n\t\tfor( int c=0; c<C; c++ ) {\n\t\t\tpgx[c        ] = (float)pim[C      +c]-(float)pim[c];\n\t\t\tpgx[(W-1)*C+c] = (float)pim[(W-1)*C+c]-(float)pim[(W-2)*C+c];\n\t\t}\n\t\tdiff( pgx+C, pim+2*C, pim, (W-2)*C, 0.5 );\n\t\t// Compute the y gradient\n\t\tif(j==0)\n\t\t\tdiff( pgy, pim+W*C, pim, W*C );\n\t\telse if( j==H-1 )\n\t\t\tdiff( pgy, pim, pim-W*C, W*C );\n\t\telse\n\t\t\tdiff( pgy, pim+W*C, pim-W*C, W*C, 0.5 );\n\t}\n}\nvoid gradientMagAndOri( RMatrixXf & gm, RMatrixXf & go, const Image & im, int norm_rad, float norm_const ) {\n\tImage gx, gy;\n\tgradient( gx, gy, im );\n\tconst int W = im.W(), H = im.H(), C = im.C();\n\tgo = RMatrixXf::Zero(H, W);\n\tgm = RMatrixXf::Zero(H, W);\n\tcomputeGradientOriAndMag( gm.data(), go.data(), gx.data(), gy.data(), W*H, C );\n\n\tif( norm_rad>0 ) {\n\t\tfloat * tmp = gx.data();\n\t\ttentFilter( tmp, gm.data(), W, H, 1, norm_rad );\n\t\tfor( int i=0; i<W*H; i++ )\n\t\t\tgm.data()[i] /= tmp[i] + norm_const;\n\t}\n}\nRMatrixXf gradientMag( const Image & im, int norm_rad, float norm_const ) {\n\tImage gx, gy;\n\tgradient( gx, gy, im );\n\tconst int W = im.W(), H = im.H(), C = im.C();\n\tRMatrixXf gm(H, W);\n\tcomputeGradientMag( gm.data(), gx.data(), gy.data(), W*H, C );\n\t\n\tif( norm_rad>0 ) {\n\t\tfloat * tmp = gx.data();\n\t\ttentFilter( tmp, gm.data(), W, H, 1, norm_rad );\n\t\tfor( int i=0; i<W*H; i++ )\n\t\t\tgm.data()[i] /= tmp[i] + norm_const;\n\t}\n\treturn gm;\n}\n", "meta": {"hexsha": "3557f70dccc2d34b545e7f13072d43fb4cb66b2f", "size": 5821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sd_maskrcnn/gop/lib/imgproc/gradient.cpp", "max_stars_repo_name": "PingCheng-Wei/SD-MaskRCNN", "max_stars_repo_head_hexsha": "8995945c38f510333cdcbdd409a189e1ad742ee2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 183.0, "max_stars_repo_stars_event_min_datetime": "2018-10-12T05:16:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T13:56:56.000Z", "max_issues_repo_path": "sd_maskrcnn/gop/lib/imgproc/gradient.cpp", "max_issues_repo_name": "PingCheng-Wei/SD-MaskRCNN", "max_issues_repo_head_hexsha": "8995945c38f510333cdcbdd409a189e1ad742ee2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2018-10-25T06:50:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T08:51:35.000Z", "max_forks_repo_path": "sd_maskrcnn/gop/lib/imgproc/gradient.cpp", "max_forks_repo_name": "PingCheng-Wei/SD-MaskRCNN", "max_forks_repo_head_hexsha": "8995945c38f510333cdcbdd409a189e1ad742ee2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2018-10-27T10:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:56:29.000Z", "avg_line_length": 37.076433121, "max_line_length": 112, "alphanum_fraction": 0.6242913589, "num_tokens": 1944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4339814648038986, "lm_q1q2_score": 0.21868593800993347}}
{"text": "#include <CGAL/Three/Polyhedron_demo_plugin_helper.h>\n#include <CGAL/Three/Three.h>\n#include <QApplication>\n#include <QObject>\n#include <QAction>\n#include <QMainWindow>\n#include <QInputDialog>\n#include <QColorDialog>\n#include <QPalette>\n#include <QColor>\n#include <QStyleFactory>\n#include <QMessageBox>\n\n#include <CGAL/boost/graph/helpers.h>\n#include <CGAL/Polygon_mesh_processing/compute_normal.h>\n#include <CGAL/Heat_method_3/Surface_mesh_geodesic_distances_3.h>\n\n#include \"Scene_points_with_normal_item.h\"\n\n#include \"Messages_interface.h\"\n#include \"Scene_surface_mesh_item.h\"\n#include \"Color_ramp.h\"\n#include <boost/unordered_map.hpp>\n#include \"ui_Display_property.h\"\n#include \"id_printing.h\"\n#include \"Scene.h\"\n#include \"triangulate_primitive.h\"\n#include <CGAL/Buffer_for_vao.h>\n#include <CGAL/Three/Triangle_container.h>\n#include <CGAL/Dynamic_property_map.h>\n\n#define ARBITRARY_DBL_MIN 1.0E-30\n#define ARBITRARY_DBL_MAX 1.0E+30\n\n\n//Item for heat values\ntypedef CGAL::Three::Triangle_container Tri;\ntypedef CGAL::Three::Viewer_interface VI;\n\nclass Scene_heat_item\n    : public CGAL::Three::Scene_item_rendering_helper\n{\n  Q_OBJECT\n  \npublic: \n  Scene_heat_item(Scene_surface_mesh_item* item)\n    :sm(item->face_graph()), parent(item)\n  {\n    setTriangleContainer(0, new Triangle_container(VI::PROGRAM_HEAT_INTENSITY,\n                                                   true));\n    setRenderingMode(Gouraud);\n  }\n  Scene_item* clone() const Q_DECL_OVERRIDE {return nullptr;}\n  QString toolTip() const Q_DECL_OVERRIDE{return QString(); }\n  void select(double orig_x,\n             double orig_y,\n             double orig_z,\n             double dir_x,\n             double dir_y,\n             double dir_z) Q_DECL_OVERRIDE\n  {\n    parent->select( orig_x, orig_y, orig_z, \n                    dir_x, dir_y, dir_z);\n  }\n  \n  void initializeBuffers(CGAL::Three::Viewer_interface *viewer) const Q_DECL_OVERRIDE\n  {\n    getTriangleContainer(0)->initializeBuffers(viewer); \n    getTriangleContainer(0)->setIdxSize(nb_idx);\n    verts.resize(0);\n    normals .resize(0);\n    colors.resize(0);\n    idx.clear();\n    idx.shrink_to_fit();\n    colors.shrink_to_fit();\n    verts.shrink_to_fit();\n    normals.shrink_to_fit();\n  }\n  \n  void draw(CGAL::Three::Viewer_interface *viewer) const Q_DECL_OVERRIDE\n  {\n    if(!visible())\n      return;\n    if(!isInit(viewer))\n      initGL(viewer);\n    if ( getBuffersFilled() &&\n         ! getBuffersInit(viewer))\n    {\n      initializeBuffers(viewer);\n      setBuffersInit(viewer, true);\n    }\n    if(!getBuffersFilled())\n    {\n      computeElements();\n      initializeBuffers(viewer);\n    }\n    \n    getTriangleContainer(0)->setAlpha(1.0f);\n    getTriangleContainer(0)->draw(viewer, false);\n  }\n  void compute_bbox() const Q_DECL_OVERRIDE\n  {\n    SMesh::Property_map<vertex_descriptor, Point_3> pprop = sm->points();\n    CGAL::Bbox_3 bbox ;\n    \n    for(vertex_descriptor vd :vertices(*sm))\n    {\n      bbox = bbox + pprop[vd].bbox();\n    }\n    _bbox = Bbox(bbox.xmin(),bbox.ymin(),bbox.zmin(),\n                 bbox.xmax(),bbox.ymax(),bbox.zmax());\n    is_bbox_computed = true;\n  }\n  Scene_item::Bbox bbox() const Q_DECL_OVERRIDE {\n    if(!is_bbox_computed)\n      compute_bbox();\n    is_bbox_computed = true;\n    return _bbox;\n  }\n\n  ~Scene_heat_item(){}\n  virtual bool supportsRenderingMode(RenderingMode m) const Q_DECL_OVERRIDE { return m==Gouraud; }\n  virtual void invalidateOpenGLBuffers() Q_DECL_OVERRIDE\n  {\n    \n    setBuffersFilled(false);\n    compute_bbox();\n    getTriangleContainer(0)->reset_vbos(NOT_INSTANCED);\n    is_bbox_computed = false;\n  }\n  void triangulate_convex_facet(face_descriptor fd,\n                                boost::property_map< SMesh, boost::vertex_index_t >::type *im) const\n  {\n    const CGAL::qglviewer::Vec v_offset = static_cast<CGAL::Three::Viewer_interface*>(CGAL::QGLViewer::QGLViewerPool().first())->offset();\n    EPICK::Vector_3 offset = EPICK::Vector_3(v_offset.x, v_offset.y, v_offset.z);\n    \n    EPICK::Point_3 p0,p1,p2;\n    SMesh::Halfedge_around_face_circulator he(halfedge(fd, *sm), *sm);\n    SMesh::Halfedge_around_face_circulator he_end = he;\n    \n    while(next(*he, *sm) != prev(*he_end, *sm))\n    {\n      ++he;\n      vertex_descriptor v0(target(*he_end, *sm)),\n          v1(target(*he, *sm)),\n          v2(target(next(*he, *sm), *sm));\n      p0 = sm->point(v0) + offset;\n      p1 = sm->point(v1) + offset;\n      p2 = sm->point(v2) + offset;\n      idx.push_back((*im)[v0]);\n      idx.push_back((*im)[v1]);\n      idx.push_back((*im)[v2]);\n    }\n  }\n  void triangulate_facet(face_descriptor fd,\n                         SMesh::Property_map<face_descriptor, EPICK::Vector_3> *fnormals,\n                         boost::property_map< SMesh, boost::vertex_index_t >::type *im) const\n  {\n    //Computes the normal of the facet\n    EPICK::Vector_3 normal = get(*fnormals, fd);\n    \n    //check if normal contains NaN values\n    if (normal.x() != normal.x() || normal.y() != normal.y() || normal.z() != normal.z())\n    {\n      qDebug()<<\"Warning : normal is not valid. Facet not displayed\";\n      return;\n    }\n    \n    typedef FacetTriangulator<SMesh, EPICK, boost::graph_traits<SMesh>::vertex_descriptor> FT;\n    const CGAL::qglviewer::Vec off = static_cast<CGAL::Three::Viewer_interface*>(CGAL::QGLViewer::QGLViewerPool().first())->offset();\n    EPICK::Vector_3 offset(off.x,off.y,off.z);\n    FT triangulation(fd,normal,sm, offset);\n    //iterates on the internal faces\n    for(FT::CDT::Finite_faces_iterator\n        ffit = triangulation.cdt->finite_faces_begin(),\n        end = triangulation.cdt->finite_faces_end();\n        ffit != end; ++ffit)\n    {\n      if(ffit->info().is_external)\n        continue;\n      //add the vertices to the positions\n      //adds the vertices, normals and colors to the appropriate vectors\n      //adds the indices to the appropriate vector\n      idx.push_back((*im)[triangulation.v2v[ffit->vertex(0)]]);\n      idx.push_back((*im)[triangulation.v2v[ffit->vertex(1)]]);\n      idx.push_back((*im)[triangulation.v2v[ffit->vertex(2)]]);\n    }\n  }\n  \n  void computeElements() const Q_DECL_OVERRIDE\n  {\n    typedef EPICK::Point_3 Point;\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n    const CGAL::qglviewer::Vec o = static_cast<CGAL::Three::Viewer_interface*>(CGAL::QGLViewer::QGLViewerPool().first())->offset();\n    EPICK::Vector_3 offset(o.x, o.y, o.z);\n    SMesh::Property_map<vertex_descriptor, SMesh::Point> positions =\n        sm->points();\n    SMesh::Property_map<vertex_descriptor, EPICK::Vector_3 > vnormals =\n        sm->property_map<vertex_descriptor, EPICK::Vector_3 >(\"v:normal\").first;\n    SMesh::Property_map<face_descriptor, EPICK::Vector_3 > fnormals =\n        sm->property_map<face_descriptor, EPICK::Vector_3 >(\"f:normal\").first;\n    typedef boost::graph_traits<SMesh>::face_descriptor face_descriptor;\n    typedef boost::graph_traits<SMesh>::halfedge_descriptor halfedge_descriptor;\n    typedef boost::graph_traits<SMesh>::vertex_descriptor vertex_descriptor;\n    SMesh::Property_map<vertex_descriptor, CGAL::Color> vcolors =\n        sm->property_map<vertex_descriptor, CGAL::Color >(\"v:color\").first;\n    SMesh::Property_map<vertex_descriptor, float> vdist=\n        sm->property_map<vertex_descriptor, float >(\"v:dist\").first;    \n    typedef CGAL::Buffer_for_vao<float, unsigned int> CPF;\n    verts.clear();\n    normals.clear();\n    idx.clear();\n    colors.clear();\n    boost::property_map< SMesh, boost::vertex_index_t >::type\n        im = get(boost::vertex_index, *sm);\n    \n    idx.reserve(num_faces(*sm) * 3);\n    for(face_descriptor fd : faces(*sm))\n    {\n      if(is_triangle(halfedge(fd,*sm),*sm))\n      {\n        for(halfedge_descriptor hd : halfedges_around_face(halfedge(fd, *sm),*sm))\n        {\n          idx.push_back(source(hd, *sm));\n        }\n      }\n      else\n      {\n        std::vector<Point> facet_points;\n        for(halfedge_descriptor hd : halfedges_around_face(halfedge(fd, *sm),*sm))\n        {\n          facet_points.push_back(positions[target(hd, *sm)]);\n        }\n        bool is_convex = CPF::is_facet_convex(facet_points, fnormals[fd]);\n        \n        if(is_convex && is_quad(halfedge(fd,*sm),*sm) )\n        {\n          halfedge_descriptor hd = halfedge(fd,*sm);\n          //1st half\n          idx.push_back(source(hd, *sm));\n          idx.push_back(source(next(hd, *sm), *sm));\n          idx.push_back(source(next(next(hd, *sm), *sm), *sm));\n          \n          //2nd half\n          idx.push_back(source(hd, *sm));\n          idx.push_back(source(next(next(hd, *sm), *sm), *sm));\n          idx.push_back(source(prev(hd, *sm), *sm));\n        }    \n        else if(is_convex)\n        {\n          triangulate_convex_facet(fd, &im);\n        }\n        else\n        {\n          triangulate_facet(fd, &fnormals, &im);\n        }\n      }\n    }\n    for(vertex_descriptor vd : vertices(*sm))\n    {\n      CGAL::Color c = vcolors[vd];\n      colors.push_back((float)c.red()/255);\n      colors.push_back((float)c.green()/255);\n      colors.push_back((float)c.blue()/255);\n      \n      \n      Point p = positions[vd] + offset;\n      CPF::add_point_in_buffer(p, verts);\n      EPICK::Vector_3 n = vnormals[vd];\n      CPF::add_normal_in_buffer(n, normals);\n      heat_values.push_back(vdist[vd]);\n    }\n    nb_idx = idx.size();\n    getTriangleContainer(0)->allocate(Tri::Vertex_indices, idx.data(),\n                                      static_cast<int>(idx.size()*sizeof(unsigned int)));\n    getTriangleContainer(0)->allocate(Tri::Smooth_vertices, verts.data(),\n                                      static_cast<int>(num_vertices(*sm)*3*sizeof(float)));\n    \n    getTriangleContainer(0)->allocate(Tri::Smooth_normals, normals.data(),\n                                      static_cast<int>(num_vertices(*sm)*3*sizeof(float)));\n    getTriangleContainer(0)->allocate(Tri::VColors, colors.data(),\n                                      static_cast<int>(colors.size()*sizeof(float)));\n    getTriangleContainer(0)->allocate(Tri::Distances, heat_values.data(),\n                                      static_cast<int>(heat_values.size()*sizeof(float)));\n    compute_bbox();\n    setBuffersFilled(true);\n     QApplication::restoreOverrideCursor();\n  }\n  \n  bool isEmpty() const Q_DECL_OVERRIDE {return false;}\n  SMesh *face_graph() { return sm;}\n  Scene_surface_mesh_item* getParent() { return parent; }\n\nprivate:\n  SMesh* sm;\n  Scene_surface_mesh_item* parent;\n  mutable std::vector<float> normals;\n  mutable std::vector<unsigned int> idx;\n  mutable std::vector<float> verts;\n  mutable std::vector<float> colors;\n  mutable std::vector<float> heat_values;\n  mutable std::size_t nb_idx;\n}; // end class Scene_heat_item\n\nclass DockWidget :\n    public QDockWidget,\n    public Ui::DisplayPropertyWidget\n{\npublic:\n  DockWidget(QString name, QWidget *parent)\n    :QDockWidget(name,parent)\n  {\n    setupUi(this);\n  }\n};\n\ntypedef boost::graph_traits<SMesh>::halfedge_descriptor halfedge_descriptor;\ntypedef boost::graph_traits<SMesh>::face_descriptor face_descriptor;\nCGAL::Three::Viewer_interface* (&getActiveViewer)() = CGAL::Three::Three::activeViewer;\nclass DisplayPropertyPlugin :\n    public QObject,\n    public CGAL::Three::Polyhedron_demo_plugin_helper\n{\n  Q_OBJECT\n  Q_INTERFACES(CGAL::Three::Polyhedron_demo_plugin_interface)\n  Q_PLUGIN_METADATA(IID \"com.geometryfactory.PolyhedronDemo.PluginInterface/1.0\")\n  typedef SMesh::Property_map<boost::graph_traits<SMesh>::vertex_descriptor, double> Vertex_distance_map;\n  typedef CGAL::Heat_method_3::Surface_mesh_geodesic_distances_3<SMesh> Heat_method;\n  typedef CGAL::Heat_method_3::Surface_mesh_geodesic_distances_3<SMesh, CGAL::Heat_method_3::Intrinsic_Delaunay> Heat_method_idt;\n  typedef CGAL::dynamic_vertex_property_t<bool>                        Vertex_source_tag;\n  typedef boost::property_map<SMesh, Vertex_source_tag>::type Vertex_source_map;\n  \npublic:\n\n  bool applicable(QAction*) const Q_DECL_OVERRIDE\n  {\n    CGAL::Three::Scene_item* item = scene->item(scene->mainSelectionIndex());\n    return qobject_cast<Scene_surface_mesh_item*>(item);\n  }\n\n  QList<QAction*> actions() const Q_DECL_OVERRIDE\n  {\n    return _actions;\n  }\n\n  QColor textColor(const QColor& color)\n  {\n    QColor text_color (255, 255, 255);\n    if (color.red() * 0.299 + color.green() * 0.587 + color.blue() * 0.114 > 128)\n      text_color = QColor (0, 0, 0);\n    return text_color;\n  }\n\n  void init(QMainWindow* mw, CGAL::Three::Scene_interface* sc, Messages_interface*) Q_DECL_OVERRIDE\n  {\n    this->scene = sc;\n    this->mw = mw;\n    this->current_item = NULL;\n\n    QAction *actionDisplayAngles= new QAction(QString(\"Display Properties\"), mw);\n    QAction *actionHeatMethod= new QAction(QString(\"Heat Method\"), mw);\n    actionHeatMethod->setProperty(\"submenuName\", \"Color\");\n\n    rm = 1.0;\n    rM = 0.0;\n    gm = 0.0;\n    gM = 1.0;\n    bm = 0.0;\n    bM = 0.0;\n    actionDisplayAngles->setProperty(\"submenuName\", \"Color\");\n\n    if(actionDisplayAngles) {\n      connect(actionDisplayAngles, SIGNAL(triggered()),\n              this, SLOT(openDialog()));\n      if(actionHeatMethod)\n      {\n        connect(actionHeatMethod, &QAction::triggered,\n                this, [this](){\n          this->dock_widget->propertyBox->setCurrentIndex(2);\n          this->dock_widget->show();\n        });\n      }\n      _actions << actionDisplayAngles;\n      _actions << actionHeatMethod;\n\n    }\n    dock_widget = new DockWidget(\"Property Displaying\", mw);\n    dock_widget->setVisible(false);\n    addDockWidget(dock_widget);\n    QPalette palette(Qt::red);\n    dock_widget->minColorButton->setPalette(palette);\n    dock_widget->minColorButton->setStyle(QStyleFactory::create(\"Fusion\"));\n    dock_widget->minColorButton->update();\n\n    palette = QPalette(Qt::green);\n    dock_widget->maxColorButton->setPalette(palette);\n    dock_widget->maxColorButton->setStyle(QStyleFactory::create(\"Fusion\"));\n    dock_widget->maxColorButton->update();\n    connect(dock_widget->colorizeButton, SIGNAL(clicked(bool)),\n            this, SLOT(colorize()));\n\n    connect(dock_widget->propertyBox, SIGNAL(currentIndexChanged(int)),\n            this, SLOT(on_propertyBox_currentIndexChanged(int)));\n    connect(dock_widget->zoomToMinButton, &QPushButton::pressed,\n            this, &DisplayPropertyPlugin::on_zoomToMinButton_pressed);\n    connect(dock_widget->zoomToMaxButton, &QPushButton::pressed,\n            this, &DisplayPropertyPlugin::on_zoomToMaxButton_pressed);\n    connect(dock_widget->minColorButton, &QPushButton::pressed,\n            this, [this]()\n    {\n      QColor minColor = QColorDialog::getColor();\n      if (!minColor.isValid())\n      {\n        return;\n      }\n      \n      rm = minColor.redF();\n      gm = minColor.greenF();\n      bm = minColor.blueF();\n      QPalette palette(minColor);\n      dock_widget->minColorButton->setPalette(palette);\n      dock_widget->minColorButton->update();\n      replaceRamp();\n    });\n    connect(dock_widget->maxColorButton, &QPushButton::pressed,\n            this, [this]()\n    {\n      QColor maxColor = QColorDialog::getColor();\n      if(!maxColor.isValid())\n        return;\n      QPalette palette(maxColor);\n      rM = maxColor.redF();\n      gM = maxColor.greenF();\n      bM = maxColor.blueF();\n\n      dock_widget->maxColorButton->setPalette(palette);\n      dock_widget->maxColorButton->update();\n      replaceRamp();\n    });\n\n    connect(dock_widget->sourcePointsButton, SIGNAL(toggled(bool)),\n            this, SLOT(on_sourcePointsButton_toggled(bool)));\n    connect(dock_widget->deleteButton, &QPushButton::clicked,\n            this, &DisplayPropertyPlugin::delete_group);\n\n    connect(dock_widget->resetButton, &QPushButton::pressed,\n            this, &DisplayPropertyPlugin::resetRampExtremas);\n\n    dock_widget->zoomToMaxButton->setEnabled(false);\n    dock_widget->zoomToMinButton->setEnabled(false);\n    Scene* scene_obj =static_cast<Scene*>(scene);\n    connect(scene_obj, &Scene::itemIndexSelected,\n            this, &DisplayPropertyPlugin::enableButtons);\n    on_propertyBox_currentIndexChanged(0);\n\n  }\nprivate Q_SLOTS:\n  void openDialog()\n  {\n    if(dock_widget->isVisible()) { dock_widget->hide(); }\n    else{\n      replaceRamp(); \n      dock_widget->show();\n      dock_widget->raise(); }\n  }\n\n  void resetRampExtremas()\n  {\n    Scene_surface_mesh_item* item =\n        qobject_cast<Scene_surface_mesh_item*>(scene->item(scene->mainSelectionIndex()));\n    if(!item)\n      return;\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n    item->face_graph()->collect_garbage();\n    bool ok;\n    switch(dock_widget->propertyBox->currentIndex())\n    {\n    case 0:\n      ok = resetAngles(item);\n      break;\n    default:\n      ok = resetScaledJacobian(item);\n      break;\n    }\n    QApplication::restoreOverrideCursor();\n    if(!ok)\n      QMessageBox::warning(mw, \"Error\", \"You must first run colorize once to initialize the values.\");\n  }\n  \n  void colorize()\n  {\n    Scene_heat_item* h_item = nullptr;\n    Scene_surface_mesh_item* item =\n        qobject_cast<Scene_surface_mesh_item*>(scene->item(scene->mainSelectionIndex()));\n    if(!item)\n    {\n      h_item = qobject_cast<Scene_heat_item*>(scene->item(scene->mainSelectionIndex()));\n      if(!h_item)\n        return;\n      item = h_item->getParent();\n    }\n    QApplication::setOverrideCursor(Qt::WaitCursor);\n\n    replaceRamp();\n    item->face_graph()->collect_garbage();\n\n    switch(dock_widget->propertyBox->currentIndex()){\n    case 0:\n      displayAngles(item);\n      break;\n      case 1:\n        displayScaledJacobian(item);\n        break;\n    case 2:\n      if(!displayHeatIntensity(item))\n        return;\n      item->setRenderingMode(Gouraud);\n      break;\n    default:  // Heat Method (Intrinsic Delaunay)\n      if(!displayHeatIntensity(item, true))\n        return;\n      item->setRenderingMode(Gouraud);\n      break;\n    }\n\n    connect(item, &Scene_surface_mesh_item::itemChanged,\n            this, [item](){\n      bool does_exist;\n      SMesh::Property_map<face_descriptor, double> pmap;\n      boost::tie(pmap, does_exist) = \n          item->face_graph()->property_map<face_descriptor,double>(\"f:jacobian\");\n      if(does_exist)\n        item->face_graph()->remove_property_map(pmap);\n      boost::tie(pmap, does_exist) = \n          item->face_graph()->property_map<face_descriptor,double>(\"f:angle\");\n      if(does_exist)\n        item->face_graph()->remove_property_map(pmap);\n    });\n    QApplication::restoreOverrideCursor();\n    item->invalidateOpenGLBuffers();\n    item->redraw();\n    if(dock_widget->propertyBox->currentIndex() != 2){\n      dock_widget->zoomToMinButton->setEnabled(true);\n      dock_widget->zoomToMaxButton->setEnabled(true);}\n  }\n\n  void enableButtons()\n  {\n    Scene_surface_mesh_item* item =\n        qobject_cast<Scene_surface_mesh_item*>(scene->item(scene->mainSelectionIndex()));\n    if(! item )\n    {\n      dock_widget->zoomToMinButton->setEnabled(false);\n      dock_widget->zoomToMaxButton->setEnabled(false);\n    }\n\n    switch(dock_widget->propertyBox->currentIndex())\n    {\n    case 0:\n      dock_widget->zoomToMinButton->setEnabled(angles_max.count(item)>0 );\n      dock_widget->zoomToMaxButton->setEnabled(angles_max.count(item)>0 );\n      break;\n    case 1:\n      dock_widget->zoomToMinButton->setEnabled(jacobian_max.count(item)>0);\n      dock_widget->zoomToMaxButton->setEnabled(jacobian_max.count(item)>0);\n      break;\n    default:\n      break;\n    }\n  }\n\n  void resetProperty()\n  {\n    Scene_surface_mesh_item* item =\n        qobject_cast<Scene_surface_mesh_item*>(sender());\n    if(!item)\n      return;\n    SMesh& smesh = *item->face_graph();\n    SMesh::Property_map<face_descriptor, double> jacobians;\n    bool found;\n    boost::tie(jacobians, found) = smesh.property_map<face_descriptor,double>(\"f:jacobian\");\n    if(found)\n    {\n      smesh.remove_property_map(jacobians);\n    }\n    SMesh::Property_map<face_descriptor, double> angles;\n    boost::tie(angles, found) = smesh.property_map<face_descriptor,double>(\"f:angle\");\n    if(found)\n    {\n      smesh.remove_property_map(angles);\n    }\n  }\n\n  void displayScaledJacobian(Scene_surface_mesh_item* item)\n  {\n\n    SMesh& smesh = *item->face_graph();\n    //compute and store the jacobian per face\n    bool non_init;\n    SMesh::Property_map<face_descriptor, double> fjacobian;\n    boost::tie(fjacobian, non_init) = smesh.add_property_map<face_descriptor, double>(\"f:jacobian\", 0);\n    if(non_init)\n    {\n      double res_min = ARBITRARY_DBL_MAX,\n          res_max = -ARBITRARY_DBL_MAX;\n      SMesh::Face_index min_index, max_index;\n      for(boost::graph_traits<SMesh>::face_iterator fit = faces(smesh).begin();\n          fit != faces(smesh).end();\n          ++fit)\n      {\n        fjacobian[*fit] = scaled_jacobian(*fit, smesh);\n        if(fjacobian[*fit] > res_max)\n        {\n          res_max = fjacobian[*fit];\n          max_index = *fit;\n        }\n        if(fjacobian[*fit] < res_min)\n        {\n          res_min = fjacobian[*fit];\n          min_index = *fit;\n        }\n      }\n      jacobian_min.erase(item);\n      jacobian_min.insert(std::make_pair(item, std::make_pair(res_min, min_index)));\n      jacobian_max.erase(item);\n      jacobian_max.insert(std::make_pair(item, std::make_pair(res_max, max_index)));\n      connect(item, &Scene_surface_mesh_item::itemChanged,\n              this, &DisplayPropertyPlugin::resetProperty);\n    }\n    //scale a color ramp between min and max\n    double max = maxBox;\n    double min = minBox;\n    //fill f:color pmap\n    SMesh::Property_map<face_descriptor, CGAL::Color> fcolors =\n        smesh.add_property_map<face_descriptor, CGAL::Color >(\"f:color\", CGAL::Color()).first;\n    for(boost::graph_traits<SMesh>::face_iterator fit = faces(smesh).begin();\n        fit != faces(smesh).end();\n        ++fit)\n    {\n      if(min == max)\n        --min;\n      double f = (fjacobian[*fit]-min)/(max-min);\n      if(f<min)\n        f = min;\n      if(f>max)\n        f = max;\n      CGAL::Color color(\n            255*color_ramp.r(f),\n            255*color_ramp.g(f),\n            255*color_ramp.b(f));\n      fcolors[*fit] = color;\n    }\n  }\n\n  bool resetScaledJacobian(Scene_surface_mesh_item* item)\n  {\n    SMesh& smesh = *item->face_graph();\n    if(!smesh.property_map<face_descriptor, double>(\"f:jacobian\").second)\n    {\n      return false;\n    }\n    dock_widget->minBox->setValue(jacobian_min[item].first-0.01);\n    dock_widget->maxBox->setValue(jacobian_max[item].first);\n    return true;\n  }\n  \n  void displayAngles(Scene_surface_mesh_item* item)\n  {\n    SMesh& smesh = *item->face_graph();\n    typedef boost::property_map<SMesh, boost::vertex_point_t>::type PMap;\n    PMap pmap = get(boost::vertex_point, smesh);\n    //compute and store smallest angle per face\n    bool non_init;\n    SMesh::Property_map<face_descriptor, double> fangle;\n    boost::tie(fangle, non_init) = smesh.add_property_map<face_descriptor, double>(\"f:angle\", 0);\n    if(non_init)\n    {\n      double res_min = ARBITRARY_DBL_MAX,\n          res_max = -ARBITRARY_DBL_MAX;\n      SMesh::Face_index index_min, index_max;\n      for(boost::graph_traits<SMesh>::face_iterator fit = faces(smesh).begin();\n          fit != faces(smesh).end();\n          ++fit)\n      {\n        bool is_face_triangle = is_triangle(halfedge(*fit, smesh), smesh);\n        bool normal_is_ok = true;\n        EPICK::Vector_3 normal(0,0,0);\n\n        EPICK::Orientation orientation = CGAL::POSITIVE;\n        if(!is_face_triangle)\n        {\n          face_descriptor f = *fit;\n          CGAL::Halfedge_around_face_circulator<SMesh>\n              he(halfedge(f, smesh), smesh),\n              he_end(he);\n          do{\n            normal_is_ok = true;\n\n            //Initializes the facet orientation\n\n            EPICK::Point_3 S,T;\n            T = get(pmap, source(*he, smesh));\n            S = get(pmap, target(*he, smesh));\n            EPICK::Vector_3 V1((T-S).x(), (T-S).y(), (T-S).z());\n            S = get(pmap,source(next(*he,smesh), smesh));\n            T = get(pmap, target(next(*he,smesh), smesh));\n            EPICK::Vector_3 V2((T-S).x(), (T-S).y(), (T-S).z());\n\n            if(normal == EPICK::Vector_3(0,0,0))\n              normal_is_ok = false;\n            {\n              normal = CGAL::cross_product(V1, V2);\n            }\n            if(normal_is_ok)\n            {\n              orientation = EPICK::Orientation_3()(V1, V2, normal);\n              if( orientation == CGAL::COPLANAR )\n                normal_is_ok = false;\n            }\n          }while( ++he != he_end && !normal_is_ok);\n        }\n\n        std::vector<float> local_angles;\n        local_angles.reserve(degree(*fit, smesh));\n        for(halfedge_descriptor hd :\n                      halfedges_around_face(halfedge(*fit, smesh),smesh))\n        {\n          halfedge_descriptor hdn = next(hd, smesh);\n          EPICK::Vector_3 v1(get(pmap, source(hd, smesh)), get(pmap, target(hd, smesh))),\n              v2(get(pmap, target(hdn, smesh)), get(pmap, source(hdn, smesh)));\n          float norm1(CGAL::approximate_sqrt(v1.squared_length())), norm2(CGAL::approximate_sqrt(v2.squared_length()));\n          float dot_prod = v1*v2;\n          float angle = std::acos(dot_prod/(norm1*norm2));\n          if(is_face_triangle || !normal_is_ok)\n            local_angles.push_back(angle * 180/CGAL_PI);\n          else\n          {\n            bool is_convex = true;\n            EPICK::Orientation res = EPICK::Orientation_3()(v1, v2, normal) ;\n            if(res!= orientation && res != CGAL::ZERO)\n              is_convex = false;\n            local_angles.push_back(is_convex ? angle * 180/CGAL_PI : 360 - angle * 180/CGAL_PI );\n          }\n        }\n        std::sort(local_angles.begin(), local_angles.end());\n        fangle[*fit]=local_angles.front();\n\n        if(fangle[*fit] > res_max)\n        {\n          res_max = fangle[*fit];\n          index_max = *fit;\n        }\n        if(fangle[*fit] < res_min)\n        {\n          res_min = fangle[*fit];\n          index_min = *fit;\n        }\n      }\n      angles_min.erase(item);\n      angles_min.insert(std::make_pair(item, std::make_pair(res_min, index_min)));\n      angles_max.erase(item);\n      angles_max.insert(std::make_pair(item, std::make_pair(res_max, index_max)));\n\n      connect(item, &Scene_surface_mesh_item::itemChanged,\n              this, &DisplayPropertyPlugin::resetProperty);\n    }\n    //scale a color ramp between min and max\n\n    float max = maxBox;\n    float min = minBox;\n\n    //fill f:color pmap\n    SMesh::Property_map<face_descriptor, CGAL::Color> fcolors =\n        smesh.add_property_map<face_descriptor, CGAL::Color >(\"f:color\", CGAL::Color()).first;\n    for(boost::graph_traits<SMesh>::face_iterator fit = faces(smesh).begin();\n        fit != faces(smesh).end();\n        ++fit)\n    {\n      if(min == max)\n        --min;\n      float f = (fangle[*fit]-min)/(max-min);\n      if(f<0)\n        f = 0;\n      if(f>1)\n        f = 1;\n      CGAL::Color color(\n            255*color_ramp.r(f),\n            255*color_ramp.g(f),\n            255*color_ramp.b(f));\n      fcolors[*fit] = color;\n    }\n  }\n\n  bool resetAngles(Scene_surface_mesh_item* item)\n  {\n    SMesh& smesh = *item->face_graph();\n    if(!smesh.property_map<face_descriptor, double>(\"f:angle\").second)\n    {\n      return false;\n    }\n    dock_widget->minBox->setValue(angles_min[item].first);\n    dock_widget->maxBox->setValue(angles_max[item].first);\n    return true;\n  }\n\n  // AF: This function gets called when we click on the button \"Colorize\"\n  bool displayHeatIntensity(Scene_surface_mesh_item* item, bool iDT = false)\n  {\n    SMesh& mesh = *item->face_graph();\n    bool found = is_source.find(item) != is_source.end();\n    if(!found\n       || ! source_points\n       || source_points->point_set()->is_empty())\n    {\n      QApplication::restoreOverrideCursor();\n      QMessageBox::warning(mw, \"Warning\",\"Source vertices are needed for this property.\");\n      return false;\n    }\n    if(!is_triangle_mesh(mesh))\n    {\n      QApplication::restoreOverrideCursor();\n      QMessageBox::warning(mw,\"Error\",\"The mesh must be triangulated.\");\n      return false;\n    }\n    Heat_method * hm = NULL;\n    Heat_method_idt * hm_idt = NULL;\n    SMesh::Property_map<vertex_descriptor, double> heat_intensity =\n      mesh.add_property_map<vertex_descriptor, double>(\"v:heat_intensity\", 0).first;\n    if(! iDT){\n      if(mesh_heat_method_map.find(item) != mesh_heat_method_map.end()){\n        hm = mesh_heat_method_map[item];\n      }else {\n        hm = new Heat_method(mesh);\n        mesh_heat_method_map[item] = hm;\n      }\n      connect(item, &Scene_surface_mesh_item::aboutToBeDestroyed,\n              [this,item](){\n                auto it =  mesh_heat_method_map.find(item);\n                delete it->second;\n                mesh_heat_method_map.erase(it);\n              }\n              );\n    } else {\n      if(mesh_heat_method_idt_map.find(item) != mesh_heat_method_idt_map.end()){\n        hm_idt = mesh_heat_method_idt_map[item];\n      }else {\n        hm_idt = new Heat_method_idt(mesh);\n        mesh_heat_method_idt_map[item] = hm_idt;\n      }\n      connect(item, &Scene_surface_mesh_item::aboutToBeDestroyed,\n              [this,item](){\n                auto it = mesh_heat_method_idt_map.find(item);\n                if(it == mesh_heat_method_idt_map.end())\n                  return;\n                Heat_method_idt *hm_idt = it->second;\n                delete hm_idt;\n                mesh_heat_method_idt_map.erase(it);\n              }\n              );\n    }\n\n    for(vertex_descriptor vd : vertices(mesh)){\n      if(get(is_source[item], vd)){\n        if(iDT){\n          hm_idt->add_source(vd);\n        } else\n          hm->add_source(vd);\n      }\n      else\n      {\n        if(iDT){\n          hm_idt->remove_source(vd);\n        } else\n          hm->remove_source(vd);\n      }\n    }\n\n    if(iDT){\n      hm_idt->estimate_geodesic_distances(heat_intensity);\n    }else{\n      hm->estimate_geodesic_distances(heat_intensity);\n    }\n\n    double max = 0;\n    double min = (std::numeric_limits<double>::max)();\n\n    for(vertex_descriptor vd : vertices(mesh)){\n      double hi = heat_intensity[vd];\n      if(hi < min)\n        min = hi;\n      if(hi > max)\n        max = hi;\n    }\n    color_ramp = Color_ramp(rm, rM, gm, gM, bm, bM);\n    dock_widget->minBox->setValue(min);\n    dock_widget->maxBox->setValue(max);\n\n    //}\n    SMesh::Property_map<vertex_descriptor, CGAL::Color> vcolors =\n        mesh.add_property_map<vertex_descriptor, CGAL::Color >(\"v:color\", CGAL::Color()).first;\n    SMesh::Property_map<vertex_descriptor, float> vdist=\n        mesh.add_property_map<vertex_descriptor, float >(\"v:dist\", 0.0).first;\n    for(boost::graph_traits<SMesh>::vertex_iterator vit = vertices(mesh).begin();\n        vit != vertices(mesh).end();\n        ++vit)\n    {\n      double h =(heat_intensity[*vit]-min)/(max-min);\n      CGAL::Color color(\n            255*color_ramp.r(h),\n            255*color_ramp.g(h),\n            255*color_ramp.b(h));\n      vcolors[*vit] = color;\n      vdist[*vit]=h;\n    }\n    Scene_group_item* group;\n    if(mesh_heat_item_map.find(item) != mesh_heat_item_map.end())\n    {\n      group = mesh_heat_item_map[item]->parentGroup();\n      group->unlockChild(mesh_heat_item_map[item]);\n      scene->erase(scene->item_id(mesh_heat_item_map[item]));\n    }\n    else\n    {\n      group = new Scene_group_item(\"Heat Visualization\");\n      group->setProperty(\"heat_group\", true);\n      scene->addItem(group);\n      scene->changeGroup(item, group);\n      scene->changeGroup(source_points, group);\n      group->lockChild(item);\n      group->lockChild(source_points);\n      dock_widget->deleteButton->setEnabled(true);\n      connect(group, &Scene_group_item::aboutToBeDestroyed,\n              this, [this](){\n        this->dock_widget->deleteButton->setEnabled(false);\n      });\n    }\n    mesh_heat_item_map[item] = new Scene_heat_item(item);\n    mesh_heat_item_map[item]->setName(tr(\"%1 heat\").arg(item->name()));\n    scene->addItem(mesh_heat_item_map[item]);\n    scene->changeGroup(mesh_heat_item_map[item], group);\n    group->lockChild(mesh_heat_item_map[item]);\n    item->setVisible(false);\n    displayLegend();\n    if(dock_widget->sourcePointsButton->isChecked())\n      dock_widget->sourcePointsButton->toggle();\n    return true;\n  }\n\n  void replaceRamp()\n  {\n    color_ramp = Color_ramp(rm, rM, gm, gM, bm, bM);\n    displayLegend();\n    minBox = dock_widget->minBox->value();\n    maxBox = dock_widget->maxBox->value();\n  }\n\n  void on_propertyBox_currentIndexChanged(int)\n  {\n    switch(dock_widget->propertyBox->currentIndex())\n    {\n    case 0:\n    {\n      dock_widget->groupBox->  setEnabled(true);\n      dock_widget->groupBox_3->setEnabled(true);\n\n      dock_widget->sourcePointsButton->setEnabled(false);\n\n      dock_widget->minBox->setMinimum(0);\n      dock_widget->minBox->setMaximum(360);\n      dock_widget->minBox->setValue(0);\n\n      dock_widget->maxBox->setMinimum(0);\n      dock_widget->maxBox->setMaximum(360);\n      Scene_surface_mesh_item* item =\n          qobject_cast<Scene_surface_mesh_item*>(scene->item(scene->mainSelectionIndex()));\n      if(! item )\n        dock_widget->maxBox->setValue(180);\n      else if(is_triangle_mesh(*item->face_graph()))\n        dock_widget->maxBox->setValue(60);\n      else if(is_quad_mesh(*item->face_graph()))\n        dock_widget->maxBox->setValue(90);\n      break;\n    }\n    case 1:\n      dock_widget->groupBox->  setEnabled(true);\n      dock_widget->groupBox_3->setEnabled(true);\n      dock_widget->sourcePointsButton->setEnabled(false);\n\n      dock_widget->minBox->setMinimum(-1000);\n      dock_widget->minBox->setMaximum(1000);\n      dock_widget->minBox->setValue(0);\n\n      dock_widget->maxBox->setMinimum(-1000);\n      dock_widget->maxBox->setMaximum(1000);\n      dock_widget->maxBox->setValue(2);\n      break;\n    default:\n      dock_widget->maxBox->setMinimum(0);\n      dock_widget->maxBox->setMaximum(99999999);\n      dock_widget->groupBox->  setEnabled(false);\n      dock_widget->groupBox_3->setEnabled(false);\n      dock_widget->sourcePointsButton->setEnabled(true);\n\n    }\n    replaceRamp();\n    enableButtons();\n  }\n\n  void closure()Q_DECL_OVERRIDE\n  {\n    dock_widget->hide();\n  }\n\n  void on_zoomToMinButton_pressed()\n  {\n    Scene_surface_mesh_item* item =\n        qobject_cast<Scene_surface_mesh_item*>(scene->item(scene->mainSelectionIndex()));\n    if(!item)\n      return;\n    face_descriptor dummy_fd;\n    Point_3 dummy_p;\n    switch(dock_widget->propertyBox->currentIndex())\n    {\n    case 0:\n    {\n      ::zoomToId(*item->face_graph(),\n                 QString(\"f%1\").arg(angles_min[item].second),\n                 getActiveViewer(),\n                 dummy_fd,\n                 dummy_p);\n    }\n      break;\n    case 1:\n    {\n      ::zoomToId(*item->face_graph(),\n                 QString(\"f%1\").arg(jacobian_min[item].second),\n                 getActiveViewer(),\n                 dummy_fd,\n                 dummy_p);\n    }\n      break;\n    default:\n      break;\n    }\n  }\n\n  void on_zoomToMaxButton_pressed()\n  {\n    Scene_surface_mesh_item* item =\n        qobject_cast<Scene_surface_mesh_item*>(scene->item(scene->mainSelectionIndex()));\n    if(!item)\n      return;\n    face_descriptor dummy_fd;\n    Point_3 dummy_p;\n    switch(dock_widget->propertyBox->currentIndex())\n    {\n    case 0:\n    {\n      ::zoomToId(*item->face_graph(),\n                 QString(\"f%1\").arg(angles_max[item].second),\n                 getActiveViewer(),\n                 dummy_fd,\n                 dummy_p);\n    }\n      break;\n    case 1:\n    {\n      ::zoomToId(*item->face_graph(),\n                 QString(\"f%1\").arg(jacobian_max[item].second),\n                 getActiveViewer(),\n                 dummy_fd,\n                 dummy_p);\n    }\n      break;\n    default:\n      break;\n    }\n  }\n\n  void delete_group()\n  {\n    Scene_item* item = scene->item(scene->selectionIndices().first());\n    Scene_group_item* group = qobject_cast<Scene_group_item*>(item);\n    if(!group || !group->property(\"heat_group\").toBool())\n      return;\n    for(auto child_id : group->getChildren())\n    {\n      if(Scene_surface_mesh_item* child = qobject_cast<Scene_surface_mesh_item*>(scene->item(child_id))){\n        group->unlockChild(child);\n         group->removeChild(child);\n         scene->addChild(child);\n         child->setVisible(true);\n         child->resetColors();\n        break;\n      }\n    }\n    scene->erase(scene->item_id(group));\n\n  }\n\n  void on_sourcePointsButton_toggled(bool b)\n  {\n    if(b)\n    {\n      Scene_heat_item* h_item = nullptr;\n      Scene_surface_mesh_item* item =\n          qobject_cast<Scene_surface_mesh_item*>(scene->item(scene->mainSelectionIndex()));\n      if(!item)\n      {\n        h_item = qobject_cast<Scene_heat_item*>(scene->item(scene->mainSelectionIndex()));\n        if(h_item)\n          item = h_item->getParent();\n      }\n      if(!item)\n      {\n        QMessageBox::warning(mw, \"Warning\", \"You must select a Surface_mesh_item to make this work. Aborting.\");\n        dock_widget->sourcePointsButton->setChecked(false);\n        return;\n      }\n      current_item = item;\n      connect(current_item, &Scene_surface_mesh_item::aboutToBeDestroyed,\n              this, [this]()\n      {\n        dock_widget->sourcePointsButton->setChecked(false);\n      });\n      if(mesh_sources_map.find(item) == mesh_sources_map.end())\n      {\n        source_points = new Scene_points_with_normal_item();\n        source_points->setName(QString(\"Source vertices for %1\").arg(current_item->name()));\n        source_points->setColor(QColor(Qt::red));\n        source_points->setPointSize(5);\n        scene->addItem(source_points);\n        connect(source_points, &Scene_points_with_normal_item::aboutToBeDestroyed,\n                [this](){\n          boost::unordered_map<Scene_surface_mesh_item*, Scene_points_with_normal_item*>::iterator it;\n          for(it = mesh_sources_map.begin();\n              it != mesh_sources_map.end();\n              ++it)\n          {\n            if(it->second == source_points)\n            {\n              mesh_sources_map.erase(it);\n              break;\n            }\n          }\n        });\n      mesh_sources_map[current_item] = source_points;\n      }\n      else\n      {\n        source_points=mesh_sources_map[current_item];\n      }\n      connect(item, SIGNAL(selected_vertex(void*)), this, SLOT(on_vertex_selected(void*)));\n      bool non_init = is_source.find(item) == is_source.end();\n      if(non_init)\n      {\n        Vertex_source_map map = get(Vertex_source_tag(), *item->face_graph());\n        is_source.insert(std::make_pair(item, map));\n        connect(item, &Scene_surface_mesh_item::itemChanged,\n                this, &DisplayPropertyPlugin::resetProperty);\n        connect(item, &Scene_surface_mesh_item::aboutToBeDestroyed,\n                [this, item](){\n          if(is_source.find(item) != is_source.end())\n          {\n            is_source.erase(item);\n          }\n        });\n      }\n    }\n    else\n    {\n      if(!current_item)\n        return;\n      disconnect(current_item, SIGNAL(selected_vertex(void*)), this, SLOT(on_vertex_selected(void*)));\n      current_item = NULL;\n    }\n  }\n\n  void on_vertex_selected(void* void_ptr)\n  {\n    typedef boost::graph_traits<SMesh>::vertices_size_type size_type;\n    size_type h = static_cast<size_type>(reinterpret_cast<std::size_t>(void_ptr));\n    vertex_descriptor vd = static_cast<vertex_descriptor>(h) ;\n    bool found = is_source.find(current_item) != is_source.end();\n    if(found)\n    {\n      if(!get(is_source[current_item], vd))\n      {\n        put(is_source[current_item], vd, true);\n        source_points->point_set()->insert(current_item->face_graph()->point(vd));\n      }\n      else\n      {\n        put(is_source[current_item], vd, false);\n        Point_set::iterator it;\n        for(it = source_points->point_set()->begin(); it != source_points->point_set()->end(); ++it)\n          if(source_points->point_set()->point(*it) == current_item->face_graph()->point(vd))\n          {\n            source_points->point_set()->remove(it);\n            source_points->point_set()->collect_garbage();\n            break;\n          }\n      }\n    }\n\n   source_points->invalidateOpenGLBuffers();\n   source_points->itemChanged();\n  }\nprivate:\n  void displayLegend()\n  {\n    // Create an legend_ and display it\n    const int height = 256;\n    const int width = 90;\n    const int cell_width = width/3;\n    const int top_margin = 5;\n    const int left_margin = 5;\n    const int drawing_height = height - top_margin * 2;\n    const int text_height = 20;\n\n    legend_ = QPixmap(width, height + text_height);\n    legend_.fill(QColor(200, 200, 200));\n\n    QPainter painter(&legend_);\n    painter.setPen(Qt::black);\n    painter.setBrush(QColor(200, 200, 200));\n\n    // Build legend_ data\n    double min_value(dock_widget->minBox->value()),\n        max_value(dock_widget->maxBox->value());\n    std::vector<double> graduations(100);\n    for(int i=0; i<100; ++i)\n      graduations[i] = i/100.0;\n\n    // draw\n    int i=0;\n    for (std::vector<double>::iterator it = graduations.begin(), end = graduations.end();\n         it != end; ++it, i+=2)\n    {\n      QColor color(255*color_ramp.r(*it),\n                   255*color_ramp.g(*it),\n                   255*color_ramp.b(*it));\n      painter.fillRect(left_margin,\n                       drawing_height - top_margin - i,\n                       cell_width,\n                       2,\n                       color);\n    }\n\n    // draw right vertical line\n    painter.setPen(Qt::blue);\n\n    painter.drawLine(QPoint(left_margin + cell_width+10, drawing_height - top_margin),\n                     QPoint(left_margin + cell_width+10,\n                            drawing_height - top_margin - static_cast<int>(graduations.size())*2));\n\n\n    // draw min value and max value\n    painter.setPen(Qt::blue);\n    QRect min_text_rect(left_margin + cell_width+10,drawing_height - top_margin,\n                        50, text_height);\n    painter.drawText(min_text_rect, Qt::AlignCenter, tr(\"%1\").arg(min_value, 0, 'f', 1));\n\n    QRect max_text_rect(left_margin + cell_width+10, drawing_height - top_margin - 200,\n                        50, text_height);\n    painter.drawText(max_text_rect, Qt::AlignCenter, tr(\"%1\").arg(max_value, 0, 'f', 1));\n\n    dock_widget->legendLabel->setPixmap(legend_);\n  }\n  double scaled_jacobian(const face_descriptor& f , const SMesh &mesh);\n  QList<QAction*> _actions;\n  Color_ramp color_ramp;\n  DockWidget* dock_widget;\n  double rm;\n  double rM;\n  double gm;\n  double gM;\n  double bm;\n  double bM;\n  boost::unordered_map<Scene_surface_mesh_item*, std::pair<double, SMesh::Face_index> > jacobian_min;\n  boost::unordered_map<Scene_surface_mesh_item*, std::pair<double, SMesh::Face_index> > jacobian_max;\n\n  boost::unordered_map<Scene_surface_mesh_item*, std::pair<double, SMesh::Face_index> > angles_min;\n  boost::unordered_map<Scene_surface_mesh_item*, std::pair<double, SMesh::Face_index> > angles_max;\n  boost::unordered_map<Scene_surface_mesh_item*, Vertex_source_map> is_source;\n\n\n  double minBox;\n  double maxBox;\n  QPixmap legend_;\n\n  Scene_surface_mesh_item* current_item;\n  Scene_points_with_normal_item* source_points;\n  boost::unordered_map<Scene_surface_mesh_item*, Scene_points_with_normal_item*> mesh_sources_map;\n  boost::unordered_map<Scene_surface_mesh_item*, Scene_heat_item*> mesh_heat_item_map;\n\n  boost::unordered_map<Scene_surface_mesh_item*, Heat_method*> mesh_heat_method_map;\n  boost::unordered_map<Scene_surface_mesh_item*, Heat_method_idt*> mesh_heat_method_idt_map;\n};\n\n  /// Code based on the verdict module of vtk\n\n  /*=========================================================================\n  Copyright (c) 2006 Sandia Corporation.\n  All rights reserved.\n  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.\n\n     This software is distributed WITHOUT ANY WARRANTY; without even\n     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n     PURPOSE.  See the above copyright notice for more information.\n=========================================================================*/\n\n  double DisplayPropertyPlugin::scaled_jacobian( const face_descriptor& f , const SMesh& mesh)\n  {\n    boost::property_map<SMesh, boost::vertex_point_t>::type\n        pmap = get(boost::vertex_point, mesh);\n    std::vector<double> corner_areas(degree(f, mesh));\n    std::vector<EPICK::Vector_3> edges;\n    for(halfedge_descriptor hd : CGAL::halfedges_around_face(halfedge(f, mesh), mesh))\n    {\n      edges.push_back(EPICK::Vector_3(get(pmap, source(hd, mesh)), get(pmap, target(hd, mesh))));\n    }\n    std::vector<EPICK::Vector_3> corner_normals;\n    for(std::size_t i = 0; i < edges.size(); ++i)\n    {\n      corner_normals.push_back(CGAL::cross_product(edges[i], edges[(i+1)%(edges.size())]));\n    }\n\n\n    EPICK::Vector_3 unit_center_normal = CGAL::Polygon_mesh_processing::compute_face_normal(f, mesh);\n    unit_center_normal *= 1.0/CGAL::approximate_sqrt(unit_center_normal.squared_length());\n\n    for(std::size_t i = 0; i < corner_areas.size(); ++i)\n    {\n      corner_areas[i] =  unit_center_normal*corner_normals[i];\n    }\n    std::vector<double> length;\n    for(std::size_t i=0; i<edges.size(); ++i)\n    {\n      length.push_back(CGAL::approximate_sqrt(edges[i].squared_length()));\n      if( length[i] < ARBITRARY_DBL_MIN)\n        return 0.0;\n    }\n    double min_scaled_jac = ARBITRARY_DBL_MAX;\n    for(std::size_t i=0; i<edges.size(); ++i)\n    {\n      double scaled_jac = corner_areas[i] / (length[i] * length[(i+edges.size()-1)%(edges.size())]);\n      min_scaled_jac = (std::min)( scaled_jac, min_scaled_jac );\n    }\n\n    if( min_scaled_jac > 0 )\n      return (double) (std::min)( min_scaled_jac, ARBITRARY_DBL_MAX );\n    return (double) (std::max)( min_scaled_jac, -ARBITRARY_DBL_MAX );\n\n  }\n\n\n#include \"Display_property_plugin.moc\"\n", "meta": {"hexsha": "71ffd20d3dff7d9a62150ade96b8a736c84b9262", "size": 45694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/demo/Polyhedron/Plugins/Display/Display_property_plugin.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/demo/Polyhedron/Plugins/Display/Display_property_plugin.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreSystem/lib/CGAL/demo/Polyhedron/Plugins/Display/Display_property_plugin.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 33.6232523915, "max_line_length": 138, "alphanum_fraction": 0.6289009498, "num_tokens": 11414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.21868593800993344}}
{"text": "#include \"framework/builder/cfem_framework_builder.h\"\n\n#include <fstream>\n#include <streambuf>\n#include <deal.II/base/mpi.h>\n#include <formulation/angular/self_adjoint_angular_flux.h>\n\n#include \"calculator/cell/integrated_fission_source.h\"\n#include \"calculator/cell/total_aggregated_fission_source.h\"\n#include \"convergence/moments/convergence_checker_l1_norm.hpp\"\n#include \"convergence/reporter/mpi_noisy.h\"\n#include \"domain/domain.hpp\"\n#include \"domain/finite_element/finite_element_gaussian.h\"\n#include \"domain/mesh/mesh_cartesian.hpp\"\n#include \"eigenvalue/k_effective/updater_via_fission_source.h\"\n#include \"formulation/cfem_diffusion_stamper.h\"\n#include \"formulation/scalar/diffusion.hpp\"\n#include \"formulation/cfem_saaf_stamper.h\"\n#include \"framework/framework.h\"\n#include \"iteration/updater/source_updater_gauss_seidel.h\"\n#include \"iteration/updater/angular_source_updater_gauss_seidel.h\"\n#include \"iteration/updater/fixed_updater.h\"\n#include \"iteration/updater/angular_fixed_updater.h\"\n#include \"iteration/initializer/initialize_fixed_terms_once.h\"\n#include \"iteration/initializer/set_fixed_terms_once.h\" // to be removed\n#include \"iteration/group/group_source_iteration.hpp\"\n#include \"iteration/outer/outer_power_iteration.h\"\n#include \"material/material_protobuf.h\"\n#include \"problem/parameter_types.h\"\n#include \"convergence/parameters/single_parameter_checker.h\"\n#include \"convergence/final_checker_or_n.h\"\n#include \"quadrature/utility/quadrature_utilities.h\"\n#include \"quadrature/factory/quadrature_factories.h\"\n#include \"results/output_dealii_vtu.h\"\n#include \"solver/group/single_group_solver.h\"\n#include \"solver/gmres.h\"\n#include \"system/system.h\"\n#include \"system/solution/mpi_group_angular_solution.h\"\n#include \"system/terms/term.h\"\n#include \"system/terms/term_types.h\"\n#include \"system/moments/spherical_harmonic.h\"\n#include \"system/system_functions.h\"\n\nnamespace bart {\n\nnamespace framework {\n\nnamespace builder {\n\ntemplate <int dim>\nstd::unique_ptr<FrameworkI> CFEM_FrameworkBuilder<dim>::BuildFramework(\n    problem::ParametersI &prm,\n    dealii::ParameterHandler &d2_prm) {\n\n  std::cout << \"Setting up materials\" << std::endl;\n\n  std::ifstream mapping_file(prm.MaterialMapFilename());\n  std::string material_mapping(\n      (std::istreambuf_iterator<char>(mapping_file)),\n      std::istreambuf_iterator<char>());\n\n  const int n_groups = prm.NEnergyGroups();\n  int n_angles;\n\n  MaterialProtobuf materials(d2_prm);\n  auto cross_sections_ptr = std::make_shared<bart::data::CrossSections>(materials);\n\n  std::cout << \"Building Finite Element\"<< std::endl;\n  std::shared_ptr<FiniteElement>finite_element_ptr(std::move(BuildFiniteElement(\n      &prm)));\n\n  std::cout << \"Building Domain\" << std::endl;\n  std::shared_ptr<Domain> domain_ptr(std::move(BuildDomain(\n      &prm,finite_element_ptr, material_mapping)));\n\n  std::cout << \"Setting up domain\" << std::endl;\n  domain_ptr->SetUpMesh().SetUpDOF();\n\n  std::shared_ptr<SourceUpdater> source_updater_ptr;\n  std::unique_ptr<Initializer> initializer_ptr;\n\n  std::shared_ptr<AngularQuadratureSet> quadrature_ptr = nullptr;\n\n  if (prm.TransportModel() == problem::EquationType::kSelfAdjointAngularFlux) {\n    printf(\"Building Quadrature Set\\n\");\n    quadrature_ptr = BuildAngularQuadratureSet(&prm);\n    n_angles = quadrature_ptr->size();\n  } else {\n    printf(\"Scalar solve\\n\");\n    n_angles = 1;\n  }\n\n  if (prm.TransportModel() == problem::EquationType::kSelfAdjointAngularFlux) {\n    printf(\"Building Stamper\\n\");\n    std::shared_ptr<CFEMAngularStamper> stamper_ptr(std::move(BuildAngularStamper(\n        &prm, domain_ptr, finite_element_ptr, cross_sections_ptr, quadrature_ptr)));\n    printf(\"Building Source Updater\\n\");\n    source_updater_ptr = std::move(BuildSourceUpdater(&prm, stamper_ptr, quadrature_ptr));\n    printf(\"Building Initializer\\n\");\n    initializer_ptr = BuildInitializer(&prm, stamper_ptr, quadrature_ptr);\n  } else {\n    printf(\"Building Scalar Stamper\\n\");\n    std::shared_ptr<CFEMStamper> stamper_ptr(std::move(BuildStamper(\n        &prm, domain_ptr, finite_element_ptr, cross_sections_ptr)));\n    printf(\"Building Source Updater\\n\");\n    source_updater_ptr = std::move(BuildSourceUpdater(&prm, stamper_ptr));\n    printf(\"Building Initializer\\n\");\n    initializer_ptr = BuildInitializer(&prm, stamper_ptr);\n  }\n\n  std::cout << \"Building single group solver\" << std::endl;\n  auto single_group_solver_ptr = BuildSingleGroupSolver();\n\n\n  std::cout << \"Building inner iteration objects\" << std::endl;\n\n  auto in_group_final_checker = BuildMomentConvergenceChecker(1e-10, 100);\n\n  // Build reporter\n  std::shared_ptr<ConvergenceReporter> reporter(std::move(BuildConvergenceReporter()));\n\n  auto moment_calculator_type = quadrature::MomentCalculatorImpl::kScalarMoment;\n\n  // Moment calculator\n  if (prm.TransportModel() == problem::EquationType::kSelfAdjointAngularFlux) {\n    moment_calculator_type = quadrature::MomentCalculatorImpl::kZerothMomentOnly;\n  }\n\n  auto moment_calculator_ptr = quadrature::factory::MakeMomentCalculator<dim>(\n      moment_calculator_type,\n      quadrature_ptr);\n\n  std::cout << \"Building and initializing system object\" << std::endl;\n\n  // Solution group\n  auto solution_ptr =\n      std::make_shared<system::solution::MPIGroupAngularSolution>(n_angles);\n\n  system::SetUpMPIAngularSolution(*solution_ptr, *domain_ptr);\n\n  std::cout << \"Building in-group iteration\" << std::endl;\n\n  auto in_group_iteration =\n      std::make_unique<iteration::group::GroupSourceIteration<dim>>(\n          std::move(single_group_solver_ptr),\n          std::move(in_group_final_checker),\n          std::move(moment_calculator_ptr),\n          solution_ptr,\n          source_updater_ptr,\n          reporter);\n\n  std::cout << \"Building K_Effective updater\" << std::endl;\n\n  // KEffectiveUpdater\n  using FissionSourceCalulator = calculator::cell::TotalAggregatedFissionSource<dim>;\n  using IntegratedFissionSourceCalc = calculator::cell::IntegratedFissionSource<dim>;\n  auto int_fission_ptr = std::make_unique<IntegratedFissionSourceCalc>(\n      finite_element_ptr, cross_sections_ptr);\n  auto fission_source_calc_ptr = std::make_unique<FissionSourceCalulator>(\n      std::move(int_fission_ptr), domain_ptr);\n  using KEffectiveUpdater = eigenvalue::k_effective::UpdaterViaFissionSource;\n\n  // KEffective convergence checker\n  using KEffConvChecker = bart::convergence::parameters::SingleParameterChecker;\n  auto k_eff_conv_checker = std::make_unique<KEffConvChecker>();\n  using KEffectiveFinalCovergence = bart::convergence::FinalCheckerOrN<double,\n      bart::convergence::parameters::SingleParameterChecker>;\n  auto k_eff_final_checker = std::make_unique<KEffectiveFinalCovergence>(\n      std::move(k_eff_conv_checker)\n      );\n\n  // KEffective updater\n  auto k_effective_updater = std::make_unique<KEffectiveUpdater>(\n      std::move(fission_source_calc_ptr), 2.0, 10);\n\n  std::cout << \"Building outer-iteration\" << std::endl;\n\n  using PowerIteration = iteration::outer::OuterPowerIteration;\n  auto power_iteration_ptr = std::make_unique<PowerIteration>(\n      std::move(in_group_iteration),\n      std::move(k_eff_final_checker),\n      std::move(k_effective_updater),\n      source_updater_ptr,\n      reporter\n  );\n\n  std::cout << \"Building System\" << std::endl;\n\n  auto system = std::make_unique<system::System>();\n\n  system->total_groups = n_groups;\n  std::unordered_set<bart::system::terms::VariableLinearTerms>\n      source_terms{bart::system::terms::VariableLinearTerms::kScatteringSource,\n                   bart::system::terms::VariableLinearTerms::kFissionSource};\n  system->right_hand_side_ptr_ =\n      std::make_unique<system::terms::MPILinearTerm>(source_terms);\n  system->left_hand_side_ptr_ =\n      std::make_unique<system::terms::MPIBilinearTerm>();\n\n  std::cout << \"Filling system\" << std::endl;\n\n  // Fill system with objects\n  for (int group = 0; group < n_groups; ++group) {\n    for (int angle = 0; angle < n_angles; ++angle) {\n      system::Index index{group, angle};\n      // LHS\n      auto fixed_matrix_ptr = domain_ptr->MakeSystemMatrix();\n      system->left_hand_side_ptr_->SetFixedTermPtr(index, fixed_matrix_ptr);\n\n      // RHS\n      auto fixed_vector_ptr =\n          std::make_shared<bart::system::MPIVector>(domain_ptr->locally_owned_dofs(),\n                                                    MPI_COMM_WORLD);\n      system->right_hand_side_ptr_->SetFixedTermPtr(index, fixed_vector_ptr);\n\n      for (auto term : source_terms) {\n        auto variable_vector_ptr =\n            std::make_shared<bart::system::MPIVector>(domain_ptr->locally_owned_dofs(),\n                                                      MPI_COMM_WORLD);\n        system->right_hand_side_ptr_->SetVariableTermPtr(\n            index, term, variable_vector_ptr);\n      }\n    }\n  }\n\n  std::cout << \"Fill system moments\" << std::endl;\n\n  // Moments\n  system->current_moments =\n      std::make_unique<system::moments::SphericalHarmonic>(n_groups, 0);\n  system->previous_moments =\n      std::make_unique<system::moments::SphericalHarmonic>(n_groups, 0);\n\n  for (auto& moment_pair : system->current_moments->moments()) {\n    auto index = moment_pair.first;\n    auto& current_moment = system->current_moments->operator[](index);\n    current_moment.reinit(solution_ptr->operator[](0).size());\n    auto& previous_moment = system->previous_moments->operator[](index);\n    previous_moment.reinit(solution_ptr->operator[](0).size());\n    current_moment = 1;\n    previous_moment = 1;\n  }\n\n  // Initialize System\n  system->k_effective = 1.0;\n  system->total_groups = n_groups;\n  system->total_angles = n_angles;\n\n  std::cout << \"Build Results Output\" << std::endl;\n  auto results_output_ptr =\n      std::make_unique<results::OutputDealiiVtu<dim>>(domain_ptr);\n\n\n  return std::make_unique<framework::Framework>(\n      std::move(system),\n      std::move(initializer_ptr),\n      std::move(power_iteration_ptr),\n      std::move(results_output_ptr));\n}\n\ntemplate <int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildAngularQuadratureSet(\n        problem::ParametersI* problem_parameters)\n-> std::shared_ptr<AngularQuadratureSet> {\n\n  std::shared_ptr<AngularQuadratureSet> return_ptr = nullptr;\n\n  std::shared_ptr<quadrature::QuadratureGeneratorI<dim>>\n      quadrature_generator_ptr = nullptr;\n\n  const int order_value = problem_parameters->AngularQuadOrder();\n  switch (problem_parameters->AngularQuad()) {\n    default: {\n      if (dim == 3) {\n        quadrature_generator_ptr =\n            quadrature::factory::MakeAngularQuadratureGeneratorPtr<dim>(\n                quadrature::Order(order_value),\n                quadrature::AngularQuadratureSetType::kLevelSymmetricGaussian);\n      } else {\n        AssertThrow(false,\n            dealii::ExcMessage(\"No supported quadratures for this dimension \"\n                               \"and transport model\"))\n      }\n    }\n  }\n\n  return_ptr = quadrature::factory::MakeQuadratureSetPtr<dim>();\n\n  auto quadrature_points = quadrature::utility::GenerateAllPositiveX<dim>(\n      quadrature_generator_ptr->GenerateSet());\n\n  quadrature::factory::FillQuadratureSet<dim>(return_ptr.get(),\n                                              quadrature_points);\n\n  return std::move(return_ptr);\n}\n\ntemplate <int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildConvergenceReporter()\n-> std::unique_ptr<ConvergenceReporter> {\n  std::unique_ptr<ConvergenceReporter> return_ptr = nullptr;\n\n  using Reporter = bart::convergence::reporter::MpiNoisy;\n  int this_process = dealii::Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);\n  auto pout_ptr = std::make_unique<dealii::ConditionalOStream>(std::cout, this_process == 0);\n  return_ptr = std::make_unique<Reporter>(std::move(pout_ptr));\n\n  return std::move(return_ptr);\n}\n\ntemplate<int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildDomain(\n    problem::ParametersI *problem_parameters,\n    const std::shared_ptr<FiniteElement> &finite_element_ptr,\n    std::string material_mapping)-> std::unique_ptr<Domain> {\n\n  // Build mesh\n  auto mesh_ptr = std::make_unique<domain::mesh::MeshCartesian<dim>>(\n      problem_parameters->SpatialMax(),\n      problem_parameters->NCells(),\n      material_mapping);\n\n  return std::make_unique<domain::Definition<dim>>(\n      std::move(mesh_ptr), finite_element_ptr);\n}\n\ntemplate<int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildFiniteElement(\n    problem::ParametersI *problem_parameters)-> std::unique_ptr<FiniteElement> {\n  return std::make_unique<domain::finite_element::FiniteElementGaussian<dim>>(\n      problem::DiscretizationType::kContinuousFEM,\n      problem_parameters->FEPolynomialDegree());\n}\n\ntemplate <int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildInitializer(\n    const problem::ParametersI *problem_parameters,\n    const std::shared_ptr<CFEMStamper> &stamper_ptr)\n-> std::unique_ptr<Initializer> {\n\n  std::unique_ptr<Initializer> return_ptr = nullptr;\n\n  using FixedUpdaterType = iteration::updater::FixedUpdater<CFEMStamper>;\n  auto fixed_updater_ptr = std::make_unique<FixedUpdaterType>(stamper_ptr);\n\n  if (problem_parameters->TransportModel() == problem::EquationType::kDiffusion) {\n    return_ptr = std::make_unique<iteration::initializer::SetFixedTermsOnce>(\n        std::move(fixed_updater_ptr), problem_parameters->NEnergyGroups(), 1);\n  }\n\n  return std::move(return_ptr);\n}\n\ntemplate <int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildInitializer(\n    const problem::ParametersI *problem_parameters,\n    const std::shared_ptr<CFEMAngularStamper> &stamper_ptr,\n    const std::shared_ptr<AngularQuadratureSet>& quadrature_set_ptr)\n-> std::unique_ptr<Initializer> {\n\n  std::unique_ptr<Initializer> return_ptr = nullptr;\n\n  using FixedUpdaterType = iteration::updater::AngularFixedUpdater<CFEMAngularStamper>;\n  auto fixed_updater_ptr = std::make_unique<FixedUpdaterType>(\n      stamper_ptr, quadrature_set_ptr);\n\n  if (problem_parameters->TransportModel() == problem::EquationType::kSelfAdjointAngularFlux) {\n    return_ptr = std::make_unique<iteration::initializer::SetFixedTermsOnce>(\n        std::move(fixed_updater_ptr),\n        problem_parameters->NEnergyGroups(),\n        quadrature_set_ptr->size());\n  }\n\n  return std::move(return_ptr);\n}\n\n\ntemplate<int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildMomentConvergenceChecker(\n    double max_delta, int max_iterations)\n-> std::unique_ptr<MomentConvergenceChecker>{\n  //TODO(Josh): Add option for using other than L1Norm\n\n  using CheckerType = convergence::moments::SingleMomentCheckerL1Norm;\n  using FinalCheckerType = convergence::FinalCheckerOrN<\n      system::moments::MomentVector,\n      convergence::moments::SingleMomentCheckerI>;\n\n  auto single_checker_ptr = std::make_unique<CheckerType>(max_delta);\n  auto return_ptr = std::make_unique<FinalCheckerType>(\n      std::move(single_checker_ptr));\n\n  return_ptr->SetMaxIterations(max_iterations);\n\n  return std::move(return_ptr);\n}\n\ntemplate<int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildParameterConvergenceChecker(\n    double max_delta, int max_iterations)\n-> std::unique_ptr<ParameterConvergenceChecker>{\n\n  using CheckerType = convergence::parameters::SingleParameterChecker;\n  using FinalCheckerType = convergence::FinalCheckerOrN<double, CheckerType>;\n\n  auto single_checker_ptr = std::make_unique<CheckerType>(max_delta);\n  auto return_ptr = std::make_unique<FinalCheckerType>(\n      std::move(single_checker_ptr));\n\n  return_ptr->SetMaxIterations(max_iterations);\n\n  return std::move(return_ptr);\n}\n\ntemplate<int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildSingleGroupSolver(\n    const int max_iterations,\n    const double convergence_tolerance) -> std::unique_ptr<SingleGroupSolver> {\n  std::unique_ptr<SingleGroupSolver> return_ptr = nullptr;\n\n  auto linear_solver_ptr = std::make_unique<solver::GMRES>(max_iterations,\n                                                           convergence_tolerance);\n\n  return_ptr = std::move(\n      std::make_unique<solver::group::SingleGroupSolver>(\n          std::move(linear_solver_ptr)));\n\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildSourceUpdater(\n    problem::ParametersI *,\n    const std::shared_ptr<CFEMStamper> stamper_ptr)\n    -> std::unique_ptr<SourceUpdater> {\n  // TODO(Josh): Add option for non-gauss-seidel updating\n  using SourceUpdater = iteration::updater::SourceUpdaterGaussSeidel<CFEMStamper>;\n  return std::make_unique<SourceUpdater>(stamper_ptr);\n}\n\ntemplate<int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildSourceUpdater(\n    problem::ParametersI *,\n    const std::shared_ptr<CFEMAngularStamper> stamper_ptr,\n    const std::shared_ptr<AngularQuadratureSet>& quadrature_set_ptr)\n-> std::unique_ptr<SourceUpdater> {\n  // TODO(Josh): Add option for non-gauss-seidel updating\n  using SourceUpdater = iteration::updater::AngularSourceUpdaterGaussSeidel<CFEMAngularStamper>;\n  return std::make_unique<SourceUpdater>(stamper_ptr, quadrature_set_ptr);\n}\n\ntemplate<int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildStamper(\n    problem::ParametersI *problem_parameters,\n    const std::shared_ptr<Domain> &domain_ptr,\n    const std::shared_ptr<FiniteElement> &finite_element_ptr,\n    const std::shared_ptr<CrossSections> &cross_sections_ptr)\n-> std::unique_ptr<CFEMStamper> {\n\n  std::unique_ptr<CFEMStamper> return_ptr = nullptr;\n\n  // Diffusion Stamper\n  if (problem_parameters->TransportModel() == problem::EquationType::kDiffusion) {\n\n    auto diffusion_ptr = std::make_unique<formulation::scalar::Diffusion<dim>>(\n        finite_element_ptr, cross_sections_ptr);\n\n    return_ptr = std::move(\n        std::make_unique<formulation::CFEM_DiffusionStamper<dim>>(\n            std::move(diffusion_ptr),\n            domain_ptr,\n            problem_parameters->ReflectiveBoundary()));\n\n  } else {\n    AssertThrow(false, dealii::ExcMessage(\"Unsuppored equation type passed\"\n                                          \" to BuildScalarFormulation\"));\n  }\n\n  return return_ptr;\n}\n\ntemplate<int dim>\nauto CFEM_FrameworkBuilder<dim>::BuildAngularStamper(\n    problem::ParametersI *problem_parameters,\n    const std::shared_ptr<Domain> &domain_ptr,\n    const std::shared_ptr<FiniteElement> &finite_element_ptr,\n    const std::shared_ptr<CrossSections> &cross_sections_ptr,\n    const std::shared_ptr<AngularQuadratureSet>& quadrature_set_ptr)\n-> std::unique_ptr<CFEMAngularStamper> {\n\n  std::unique_ptr<CFEMAngularStamper> return_ptr = nullptr;\n\n  if (problem_parameters->TransportModel() == problem::EquationType::kSelfAdjointAngularFlux) {\n\n    auto saaf_formulation_ptr =\n        std::make_unique<formulation::angular::SelfAdjointAngularFlux<dim>>(\n        finite_element_ptr, cross_sections_ptr, quadrature_set_ptr);\n\n    return_ptr = std::move(\n        std::make_unique<formulation::CFEM_SAAF_Stamper<dim>>(\n            std::move(saaf_formulation_ptr),\n            domain_ptr));\n  } else {\n    AssertThrow(false, dealii::ExcMessage(\"Unsuppored equation type passed\"\n                                          \"to BuildScalarFormulation\"));\n  }\n\n  return return_ptr;\n}\n\ntemplate class CFEM_FrameworkBuilder<1>;\ntemplate class CFEM_FrameworkBuilder<2>;\ntemplate class CFEM_FrameworkBuilder<3>;\n\n\n\n} // namespace builder\n\n} // namespace framework\n\n} // namespace bart", "meta": {"hexsha": "f32dffb739421ad78d4165226edb62ded8be93ce", "size": 19127, "ext": "cc", "lang": "C++", "max_stars_repo_path": "legacy_code/builder/cfem_framework_builder.cc", "max_stars_repo_name": "SlaybaughLab/Transport", "max_stars_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-03-14T12:30:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T14:46:44.000Z", "max_issues_repo_path": "legacy_code/builder/cfem_framework_builder.cc", "max_issues_repo_name": "SlaybaughLab/Transport", "max_issues_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 194.0, "max_issues_repo_issues_event_min_datetime": "2017-07-07T01:38:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T18:21:19.000Z", "max_forks_repo_path": "legacy_code/builder/cfem_framework_builder.cc", "max_forks_repo_name": "SlaybaughLab/Transport", "max_forks_repo_head_hexsha": "8eb32cb8ae50c92875526a7540350ef9a85bc050", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2017-07-06T22:58:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-15T07:01:21.000Z", "avg_line_length": 36.7120921305, "max_line_length": 96, "alphanum_fraction": 0.7343022952, "num_tokens": 4578, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.21859227760001193}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2021, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Licensed under the Boost Software License version 1.0.\n// http://www.boost.org/users/license.html\n\n#ifndef BOOST_GEOMETRY_STRATEGIES_DISTANCE_GEOGRAPHIC_HPP\n#define BOOST_GEOMETRY_STRATEGIES_DISTANCE_GEOGRAPHIC_HPP\n\n\n#include <boost/geometry/strategies/distance/comparable.hpp>\n#include <boost/geometry/strategies/distance/detail.hpp>\n#include <boost/geometry/strategies/distance/services.hpp>\n#include <boost/geometry/strategies/detail.hpp>\n\n#include <boost/geometry/strategies/geographic/azimuth.hpp>\n\n#include <boost/geometry/strategies/geographic/distance.hpp>\n#include <boost/geometry/strategies/geographic/distance_cross_track.hpp>\n#include <boost/geometry/strategies/geographic/distance_cross_track_box_box.hpp>\n#include <boost/geometry/strategies/geographic/distance_cross_track_point_box.hpp>\n#include <boost/geometry/strategies/geographic/distance_segment_box.hpp>\n// TODO - for backwards compatibility, remove?\n#include <boost/geometry/strategies/geographic/distance_andoyer.hpp>\n#include <boost/geometry/strategies/geographic/distance_thomas.hpp>\n#include <boost/geometry/strategies/geographic/distance_vincenty.hpp>\n\n#include <boost/geometry/strategies/normalize.hpp>\n#include <boost/geometry/strategies/relate/geographic.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\nnamespace strategies { namespace distance\n{\n\n// TODO: azimuth and normalize getters would not be needed if distance_segment_box was implemented differently\n//       right now it calls disjoint algorithm details.\n\ntemplate\n<\n    typename FormulaPolicy = strategy::andoyer,\n    std::size_t SeriesOrder = strategy::default_order<FormulaPolicy>::value,\n    typename Spheroid = srs::spheroid<double>,\n    typename CalculationType = void\n>\nclass geographic\n    : public strategies::relate::geographic<FormulaPolicy, SeriesOrder, Spheroid, CalculationType>\n{\n    using base_t = strategies::relate::geographic<FormulaPolicy, SeriesOrder, Spheroid, CalculationType>;\n\npublic:\n    geographic() = default;\n\n    explicit geographic(Spheroid const& spheroid)\n        : base_t(spheroid)\n    {}\n\n    // azimuth\n\n    auto azimuth() const\n    {\n        return strategy::azimuth::geographic\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    // distance\n\n    template <typename Geometry1, typename Geometry2>\n    auto distance(Geometry1 const&, Geometry2 const&,\n                  detail::enable_if_pp_t<Geometry1, Geometry2> * = nullptr) const\n    {\n        return strategy::distance::geographic\n                <\n                    FormulaPolicy, Spheroid, CalculationType\n                >(base_t::m_spheroid);\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    auto distance(Geometry1 const&, Geometry2 const&,\n                  detail::enable_if_ps_t<Geometry1, Geometry2> * = nullptr) const\n    {\n        return strategy::distance::geographic_cross_track\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    auto distance(Geometry1 const&, Geometry2 const&,\n                  detail::enable_if_pb_t<Geometry1, Geometry2> * = nullptr) const\n    {\n        return strategy::distance::geographic_cross_track_point_box\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    auto distance(Geometry1 const&, Geometry2 const&,\n                  detail::enable_if_sb_t<Geometry1, Geometry2> * = nullptr) const\n    {\n        return strategy::distance::geographic_segment_box\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    template <typename Geometry1, typename Geometry2>\n    auto distance(Geometry1 const&, Geometry2 const&,\n                  detail::enable_if_bb_t<Geometry1, Geometry2> * = nullptr) const\n    {\n        return strategy::distance::geographic_cross_track_box_box\n            <\n                FormulaPolicy, Spheroid, CalculationType\n            >(base_t::m_spheroid);\n    }\n\n    // normalize\n\n    template <typename Geometry>\n    static auto normalize(Geometry const&,\n                          std::enable_if_t\n                            <\n                                util::is_point<Geometry>::value\n                            > * = nullptr)\n    {\n        return strategy::normalize::spherical_point();\n    }\n};\n\n\nnamespace services\n{\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct default_strategy<Geometry1, Geometry2, geographic_tag, geographic_tag>\n{\n    using type = strategies::distance::geographic<>;\n};\n\n\ntemplate <typename FP, typename S, typename CT>\nstruct strategy_converter<strategy::distance::geographic<FP, S, CT> >\n{\n    static auto get(strategy::distance::geographic<FP, S, CT> const& s)\n    {\n        return strategies::distance::geographic<FP, strategy::default_order<FP>::value, S, CT>(s.model());\n    }\n};\n// TODO - for backwards compatibility, remove?\ntemplate <typename S, typename CT>\nstruct strategy_converter<strategy::distance::andoyer<S, CT> >\n{\n    static auto get(strategy::distance::andoyer<S, CT> const& s)\n    {\n        return strategies::distance::geographic<strategy::andoyer, strategy::default_order<strategy::andoyer>::value, S, CT>(s.model());\n    }\n};\n// TODO - for backwards compatibility, remove?\ntemplate <typename S, typename CT>\nstruct strategy_converter<strategy::distance::thomas<S, CT> >\n{\n    static auto get(strategy::distance::thomas<S, CT> const& s)\n    {\n        return strategies::distance::geographic<strategy::thomas, strategy::default_order<strategy::thomas>::value, S, CT>(s.model());\n    }\n};\n// TODO - for backwards compatibility, remove?\ntemplate <typename S, typename CT>\nstruct strategy_converter<strategy::distance::vincenty<S, CT> >\n{\n    static auto get(strategy::distance::vincenty<S, CT> const& s)\n    {\n        return strategies::distance::geographic<strategy::vincenty, strategy::default_order<strategy::vincenty>::value, S, CT>(s.model());\n    }\n};\n\ntemplate <typename FP, typename S, typename CT>\nstruct strategy_converter<strategy::distance::geographic_cross_track<FP, S, CT> >\n{\n    static auto get(strategy::distance::geographic_cross_track<FP, S, CT> const& s)\n    {\n        return strategies::distance::geographic<FP, strategy::default_order<FP>::value, S, CT>(s.model());\n    }\n};\n\ntemplate <typename FP, typename S, typename CT>\nstruct strategy_converter<strategy::distance::geographic_cross_track_point_box<FP, S, CT> >\n{\n    static auto get(strategy::distance::geographic_cross_track_point_box<FP, S, CT> const& s)\n    {\n        return strategies::distance::geographic<FP, strategy::default_order<FP>::value, S, CT>(s.model());\n    }\n};\n\ntemplate <typename FP, typename S, typename CT>\nstruct strategy_converter<strategy::distance::geographic_segment_box<FP, S, CT> >\n{\n    static auto get(strategy::distance::geographic_segment_box<FP, S, CT> const& s)\n    {\n        return strategies::distance::geographic<FP, strategy::default_order<FP>::value, S, CT>(s.model());\n    }\n};\n\ntemplate <typename FP, typename S, typename CT>\nstruct strategy_converter<strategy::distance::geographic_cross_track_box_box<FP, S, CT> >\n{\n    static auto get(strategy::distance::geographic_cross_track_box_box<FP, S, CT> const& s)\n    {\n        return strategies::distance::geographic<FP, strategy::default_order<FP>::value, S, CT>(s.model());\n    }\n};\n\n\n// details\n\n// TODO: This specialization wouldn't be needed if strategy::distance::geographic_cross_track was implemented as an alias\ntemplate <typename FP, typename S, typename CT, bool B, bool ECP>\nstruct strategy_converter<strategy::distance::detail::geographic_cross_track<FP, S, CT, B, ECP> >\n{\n    struct altered_strategy\n        : strategies::distance::geographic<FP, strategy::default_order<FP>::value, S, CT>\n    {\n        typedef strategies::distance::geographic<FP, strategy::default_order<FP>::value, S, CT> base_t;\n\n        explicit altered_strategy(S const& s) : base_t(s) {}\n\n        using base_t::distance;\n\n        template <typename Geometry1, typename Geometry2>\n        auto distance(Geometry1 const&, Geometry2 const&,\n                      std::enable_if_t\n                      <\n                            util::is_pointlike<Geometry1>::value\n                                && util::is_segmental<Geometry2>::value\n                         || util::is_segmental<Geometry1>::value\n                                && util::is_pointlike<Geometry2>::value\n                         || util::is_segmental<Geometry1>::value\n                                && util::is_segmental<Geometry2>::value\n                      > * = nullptr) const\n        {\n            return strategy::distance::detail::geographic_cross_track\n                <\n                    FP, S, CT, B, ECP\n                >(base_t::m_spheroid);\n        }\n    };\n\n    static auto get(strategy::distance::detail::geographic_cross_track<FP, S, CT, B, ECP> const& s)\n    {\n        return altered_strategy(s.model());\n    }\n};\n\n\n} // namespace services\n\n}} // namespace strategies::distance\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_STRATEGIES_DISTANCE_GEOGRAPHIC_HPP\n", "meta": {"hexsha": "4c9aadd91e210beb6464a4c8df4c6e5f95aa6d61", "size": 9409, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/strategies/distance/geographic.hpp", "max_stars_repo_name": "pranavgo/RRT", "max_stars_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/geometry/strategies/distance/geographic.hpp", "max_issues_repo_name": "pranavgo/RRT", "max_issues_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/geometry/strategies/distance/geographic.hpp", "max_forks_repo_name": "pranavgo/RRT", "max_forks_repo_head_hexsha": "87148c3ddb91600f4e74f00ffa8af14b54689aa4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8481481481, "max_line_length": 138, "alphanum_fraction": 0.674566904, "num_tokens": 2175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.2184339270001337}}
{"text": "﻿#include \"../checkpoint/checkpoint.h\"\n#include \"goexit/goexit.h\"\n#ifdef HAVE_SSE2\n\t#include \"myrandom/myrandsfmt.h\"\n#else\n\t#include \"myrandom/myrand.h\"\n#endif\n#include <array>                       \t// for std::array\n#include <cstdint>  \t               \t// for std::uint32_t\n#include <functional>                   // for std::hash\n#include <iomanip>\t\t               \t// for std::setiosflags, std::setprecision\n#include <iostream> \t               \t// for std::cout\n#include <string>                      \t// for std::string\n#include <utility>                      // for std::move\n#ifdef _CHECK_PARALELL_PERFORM\n    #include <vector>   \t            // for std::vector\n#endif\n#include <boost/container/flat_map.hpp>\t// for boost::container::flat_map\n#include <tbb/concurrent_hash_map.h>    // for tbb::concurrent_hash_map\n#include <tbb/concurrent_vector.h>     \t// for tbb::concurrent_vector\n#include <tbb/parallel_for.h>           // for tbb::parallel_for\n\nnamespace {\n    //! A global variable (constant expression).\n    /*!\n        モンテカルロシミュレーションの試行回数\n    */\n    static auto constexpr MCMAX = 1000000U;\n\n    //! A global variable (constant expression).\n    /*!\n        UかDの文字列の長さ\n    */\n    static auto constexpr RANDNUMTABLELEN = 100U;\n\n    //! A global variable (constant).\n    /*!\n        UとDの文字列の可能な集合の配列\n    */\n    static std::array<std::string, 8U> const udarray = { \"DDD\", \"DDU\", \"DUD\", \"DUU\", \"UDD\", \"UDU\", \"UUD\", \"UUU\" };\n\n    //! A typedef.\n    /*!\n        文字列とその文字列に対応する出現回数のstd::map\n    */\n    using mymap = boost::container::flat_map<std::string, std::uint32_t>;\n\n    //! A typedef.\n    /*!\n        文字列のペア\n    */\n    using strpair = std::pair<std::string, std::string>;\n    \n    //! A struct.\n    /*!\n        strpairを扱うハッシュと比較操作を定義する構造体\n    */\n    struct MyHashCompare final {\n        //! A public static member function.\n        /*!\n            strpairからハッシュを生成する\n            \\param sp 文字列のペア\n            \\return 与えられたstrpairのハッシュ\n        */\n        static std::size_t hash(strpair const & sp)\n        {\n            auto const h1 = std::hash<std::string>()(sp.first);\n            auto const h2 = std::hash<std::string>()(sp.second);\n            return h1 ^ (h2 << 1);\n        }\n\n        //! A public static member function.\n        /*!\n            二つのstrpairを比較する\n            \\param lhs 左辺のstrpair\n            \\param rhs 右辺のstrpair\n            \\return 文字列のペアが等しい場合にはtrue\n        */\n        static bool equal(strpair const & lhs, strpair const & rhs)\n        {\n            return lhs == rhs;\n        }\n    };\n\n    //! A typedef.\n    /*!\n        各文字列の順列に対応する勝利回数の結果を格納するtbb::concurrent_hash_map\n    */\n    using myhashmap = tbb::concurrent_hash_map<strpair, std::uint32_t, MyHashCompare>;\n    \n    //! A typedef.\n    /*!\n        文字列のペアと、どちらの文字列が勝ったかのstd::pair\n    */\n    using mymap2 = boost::container::flat_map<strpair, bool>;\n\n    //! A typedef.\n    /*!\n        文字列のペアと、文字列の勝利数のstd::pair\n    */\n    using mymap3 = boost::container::flat_map<strpair, std::uint32_t>;\n    \n    //! A function.\n    /*!\n        文字列の可能な順列を列挙する\n        \\return 文字列の可能な順列を列挙したstd::array\n    */\n    std::array<strpair, 56U> makecombination();\n\n    //! A global variable (constant).\n    /*!\n        udarrayから二つを抽出したときの可能な順列の配列\n    */\n    static std::array<strpair, 56U> const cbarray = makecombination();\n\n#ifdef _CHECK_PARALELL_PERFORM\n    //! A function.\n    /*!\n        文字列のペアの、前者が勝利した回数を集計する\n        \\param mcresultwinningavg 文字列のペアと、どちらの文字列が勝ったかの結果が格納された連想配列の可変長配列\n        \\return 文字列のペアの、前者が勝利した回数が格納された連想配列\n    */\n    mymap3 aggregateWinningAvg(std::vector<mymap2> const & mcresultwinningavg);\n#endif\n\n    //! A function.\n    /*!\n        文字列のペアの、前者が勝利した回数を集計する\n        \\param mcresultwinningavg 文字列のペアと、どちらの文字列が勝ったかの結果が格納された連想配列の可変長配列\n        \\return 文字列のペアの、前者が勝利した回数が格納された連想配列\n    */\n    mymap3 aggregateWinningAvg(tbb::concurrent_vector<mymap2> const & mcresultwinningavg);\n\n    template <typename T>\n    //! A template function.\n    /*!\n        UDのランダム文字列を生成する\n        \\param mr 自作乱数クラスのオブジェクト\n        \\return UDのランダム文字列を格納したstd::string\n    */\n    inline auto makerandomudstr(T & mr);\n\n#ifdef _CHECK_PARALELL_PERFORM\n    //! A function.\n    /*!\n        モンテカルロ・シミュレーションを行う\n        \\return 期待値と、どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果のstd::pair    \n    */\n    std::pair<std::vector<mymap>, std::vector<mymap2> > montecarlo();\n#endif\n\n    //! A function.\n    /*!\n        モンテカルロ・シミュレーションをTBBで並列化して行う\n        \\return 期待値と、どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果のstd::pair\n    */\n    std::pair< tbb::concurrent_vector<mymap>, tbb::concurrent_vector<mymap2> > montecarloTBB();\n\n    template <typename T>\n    //! A template function.\n    /*!\n        期待値に対するモンテカルロ・シミュレーションの実装\n        \\param mr 自作乱数クラスのオブジェクト\n        \\return 期待値に対するモンテカルロ・シミュレーションの結果が格納された連想配列\n    */\n    mymap montecarloImplAvg(T & mr);\n\n    template <typename T>\n    //! A template function.\n    /*!\n        文字列のペアのうち、どちらの文字列が先に出現したかのモンテカルロ・シミュレーションの実装\n        \\param mr 自作乱数クラスのオブジェクト\n        \\return 文字列のペアのうち、どちらの文字列が先に出現したかのモンテカルロ・シミュレーションの結果が格納された連想配列\n    */\n    mymap2 montecarloImplWinningAvg(T & mr);\n\n    //! A function.\n    /*!\n        UとDのランダム文字列から与えられた文字列の位置を検索し、文字列の末尾の位置を与える\n        \\param str 検索する文字列\n        \\param udstr UとDのランダム文字列\n        \\return 検索された文字列の末尾の位置\n    */\n    inline std::uint32_t myfind(std::string const & str, std::string const & udstr);\n\n    //! A template function.\n    /*!\n        期待値に対するモンテカルロ・シミュレーションの和を計算する\n        \\return 期待値に対するモンテカルロ・シミュレーションの結果の和の連想配列\n    */\n    template <typename T>\n    mymap sumMontecarloAvg(T const & mcresultavg);\n}\n\nint main()\n{\n    checkpoint::CheckPoint cp;\n\n    cp.checkpoint(\"処理開始\", __LINE__);\n\n#ifdef _CHECK_PARALELL_PERFORM\n    {\n        // モンテカルロ・シミュレーションの結果を代入\n        auto const mcresult(montecarlo());\n\n        // 各文字列のペアに対する勝率を計算する\n        auto const trialwinningavg(aggregateWinningAvg(mcresult.second));\n    }\n\n    cp.checkpoint(\"並列化無効\", __LINE__);\n#endif\n\n    // モンテカルロ・シミュレーションの結果を代入\n    auto const mcresultTBB(montecarloTBB());\n    \n    // 各文字列のペアに対する勝率を計算する\n    auto const trialwinningavg(aggregateWinningAvg(mcresultTBB.second));\n\n    cp.checkpoint(\"並列化有効\", __LINE__);\n\n    // 期待値に対するモンテカルロ・シミュレーションの結果の和を計算する\n    auto const trialavg(sumMontecarloAvg(mcresultTBB.first));\n    \n    // 各文字列に対する期待値の表示\n    std::cout << std::setprecision(1) << std::setiosflags(std::ios::fixed);\n    for (auto && itr = trialavg.begin(); itr != trialavg.end(); ++itr) {\n        std::cout << itr->first\n                  << \" が出るまでの期待値: \"\n                  << static_cast<double>(itr->second) / static_cast<double>(MCMAX)\n                  << \"回\\n\";\n    }\n    \n    // 各文字列のペアに対する勝率の表示\n    std::cout << \"\\n    \";\n    for (auto i = 0; i < 8; i++) {\n        std::cout << udarray[i] << \"  \";\n    }\n    std::cout << '\\n';\n\n    auto && itr = trialwinningavg.begin();\n    auto const len = udarray.size();\n    for (auto i = 0U; i < len; i++) {\n        std::cout << itr->first.first << ' ';\n        for (auto j = 0U; j < len; j++) {\n            if (i == j) {\n                std::cout << \"     \";\n            }\n            else {\n                std::cout << static_cast<double>(itr->second) / static_cast<double>(MCMAX) * 100.0\n                          << ' ';\n                ++itr;\n            }\n        }\n        std::cout << '\\n';\n    }\n\n    cp.checkpoint(\"それ以外の処理\", __LINE__);\n\n    cp.checkpoint_print();\n\n\tgoexit::goexit();\n\n    return 0;\n}\n\nnamespace {\n#ifdef _CHECK_PARALELL_PERFORM\n    mymap3 aggregateWinningAvg(std::vector<mymap2> const & mcresultwinningavg)\n    {\n        // 各文字列の順列に対応する勝利回数の結果を格納するboost::container::flat_map\n        mymap3 trialwinningavg;\n\n        // tbb::concurrent_hash_mapの初期化\n        for (auto const & sp : cbarray) {\n            trialwinningavg[sp] = 0U;\n        }\n\n        // 試行回数分繰り返す\n        for (auto const & mcr : mcresultwinningavg) {\n            for (auto && itr = mcr.begin(); itr != mcr.end(); ++itr) {\n                if (itr->second) {\n                    trialwinningavg[itr->first]++;\n                }\n            }\n        }\n\n        return trialwinningavg;\n    }\n#endif\n\n    mymap3 aggregateWinningAvg(tbb::concurrent_vector<mymap2> const & mcresultwinningavg)\n    {\n        // 各文字列の順列に対応する勝利回数の結果を格納するtbb::concurrent_hash_map\n        myhashmap trial;\n\n        // tbb::concurrent_hash_mapの初期化\n        for (auto const & sp : cbarray) {\n            myhashmap::accessor a;\n            trial.insert(a, sp);\n            a->second = 0U;\n        }\n\n        // MCMAX回のループを並列化して実行\n        tbb::parallel_for(\n            tbb::blocked_range<std::uint32_t>(0U, MCMAX),\n            [&mcresultwinningavg, &trial](auto const & range) {\n            for (auto && i = range.begin(); i != range.end(); ++i) {\n                auto const mcr = mcresultwinningavg[i];\n                for (auto && itr = mcr.begin(); itr != mcr.end(); ++itr) {\n                    if (itr->second) {\n                        myhashmap::accessor a;\n                        trial.insert(a, itr->first);\n                        a->second++;\n                    }\n                }\n            }\n        });\n\n        // boost::container::flat_mapに計算結果を複写\n        boost::container::flat_map<strpair, std::uint32_t> trialwinningavg;\n        for (auto && res : trial) {\n            trialwinningavg[res.first] = res.second;\n        }\n\n        return trialwinningavg;\n    }\n\n    std::array<strpair, 56U> makecombination()\n    {\n        // 全ての可能な順列を収納する配列\n        std::array<strpair, 56U> cb;\n\n        // カウンタ\n        auto cnt = 0;\n\n        // 全ての可能な順列を列挙\n        auto const len = udarray.size();\n        for (auto i = 0U; i < len; i++) {\n            for (auto j = 0U; j < len; j++) {\n                if (i != j) {\n                    cb[cnt++] = std::make_pair(udarray[i], udarray[j]);\n                }\n            }\n        }\n\n        return cb;\n    }\n\n    template <typename T>\n    auto makerandomudstr(T & mr)\n    {\n        // UDのランダム文字列を格納するstd::string\n        std::string udstring(RANDNUMTABLELEN, '\\0');\n\n        // UDのランダム文字列を格納\n        for (auto && c : udstring) {\n            c = mr.myrand() > 3 ? 'U' : 'D';\n        }\n\n\t\t// UDのランダム文字列を返す\n        return udstring;\n    }\n\n#ifdef _CHECK_PARALELL_PERFORM\n    std::pair<std::vector<mymap>, std::vector<mymap2> > montecarlo()\n    {\n        // 期待値に対するモンテカルロ・シミュレーションの結果を格納するための可変長配列\n        std::vector<mymap> mcresultavg;\n\n        // どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果を格納するための可変長配列\n        std::vector<mymap2> mcresultwinningavg;\n\n        // MCMAX個の容量を確保\n        mcresultavg.reserve(MCMAX);\n        mcresultwinningavg.reserve(MCMAX);\n\n#ifdef HAVE_SSE2\n\t\t// 自作乱数クラスを初期化\n\t\tmyrandom::MyRandSfmt mr(1, 6);\n#else\n\t\t// 自作乱数クラスを初期化\n\t\tmyrandom::MyRand mr(1, 6);\n#endif\n\n        // 試行回数分繰り返す\n        for (auto i = 0U; i < MCMAX; i++) {\n            // 期待値に対するモンテカルロ・シミュレーションの結果を代入\n            mcresultavg.emplace_back(montecarloImplAvg(mr));\n\n            // どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果を代入\n            mcresultwinningavg.emplace_back(montecarloImplWinningAvg(mr));\n        }\n\n        return std::make_pair(std::move(mcresultavg), std::move(mcresultwinningavg));\n    }\n#endif\n\n    std::pair<tbb::concurrent_vector<mymap>, tbb::concurrent_vector<mymap2> > montecarloTBB()\n    {\n        // 期待値に対するモンテカルロ・シミュレーションの結果を格納するための可変長配列\n        tbb::concurrent_vector<mymap> mcresultavg;\n\n        // どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果を格納するための可変長配列\n        tbb::concurrent_vector<mymap2> mcresultwinningavg;\n\n        // MCMAX個の容量を確保\n        mcresultavg.reserve(MCMAX);\n        mcresultwinningavg.reserve(MCMAX);\n        \n        // MCMAX回のループを並列化して実行\n        tbb::parallel_for(\n            0U,\n            MCMAX,\n            1U,\n            [&](auto) {\n\n#ifdef HAVE_SSE2\n\t\t        // 自作乱数クラスを初期化\n\t\t        myrandom::MyRandSfmt mr(1, 6);\n#else\n\t\t        // 自作乱数クラスを初期化\n\t\t        myrandom::MyRand mr(1, 6);\n#endif\n\n                // 期待値に対するモンテカルロ・シミュレーションの結果を代入\n                mcresultavg.emplace_back(montecarloImplAvg(mr));\n\n                // どちらの文字列が先に出現したかどうかのモンテカルロ・シミュレーションの結果を代入\n                mcresultwinningavg.emplace_back(montecarloImplWinningAvg(mr));\n        });\n\n        return std::make_pair(std::move(mcresultavg), std::move(mcresultwinningavg));\n    }\n\n    template <typename T>\n    mymap montecarloImplAvg(T & mr)\n    {\n        // UDのランダム文字列\n        auto const udstr(makerandomudstr(mr));\n\n        // 検索結果のstd::map\n        mymap result;\n\n        // 文字列が最初に出現するのは何文字目かを検索し結果を代入\n        for (auto const & str : udarray) {\n            result.insert(std::make_pair(str, myfind(str, udstr)));\n        }\n\n        return result;\n    }\n        \n    template <typename T>\n    mymap2 montecarloImplWinningAvg(T & mr)\n    {\n        // UDのランダム文字列\n        auto const udstr(makerandomudstr(mr));\n\n        // 検索結果のstd::map\n        mymap2 result;\n\n        // どちらの文字列が先に出現したかの結果を代入\n        for (auto const & sp : cbarray) {\n            result.insert(std::make_pair(sp, myfind(sp.first, udstr) < myfind(sp.second, udstr)));\n        }\n\n        // 検索結果を返す\n        return result;\n    }\n        \n    std::uint32_t myfind(std::string const & str, std::string const & udstr)\n    {\n        // 文字列の位置を検索\n        auto const pos = udstr.find(str);\n        \n        // posをその文字列の末尾の位置に変換\n        // もし文字列が見つかっていなかった場合はRANDNUMTABLELENに変換\n        return pos != std::string::npos ? static_cast<std::uint32_t>(pos + 3) : RANDNUMTABLELEN;\n    }\n    \n    template <typename T>\n    mymap sumMontecarloAvg(T const & mcresultavg)\n    {\n        // 各文字列に対して、期待値に対するモンテカルロ・シミュレーションの結果の和を格納するstd::map\n        mymap trial;\n\n        // std::mapの初期化\n        for (auto const & str : udarray) {\n            trial[str] = 0;\n        }\n\n        // 試行回数分繰り返す\n        for (auto const & mcr : mcresultavg) {\n            for (auto && itr = mcr.begin(); itr != mcr.end(); ++itr) {\n                trial[itr->first] += itr->second;\n            }\n        }\n\n        return trial;\n    }\n}\n\n", "meta": {"hexsha": "09ff89052dda52d9d81ea6892309110ba2ac7c4f", "size": 13818, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kakeguruitwin_MC/kakeguruitwin_mc.cpp", "max_stars_repo_name": "dc1394/kakeguruitwin_MC", "max_stars_repo_head_hexsha": "dffcf2da01c4e2a0afe7464d61c7c17e2079af50", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/kakeguruitwin_MC/kakeguruitwin_mc.cpp", "max_issues_repo_name": "dc1394/kakeguruitwin_MC", "max_issues_repo_head_hexsha": "dffcf2da01c4e2a0afe7464d61c7c17e2079af50", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kakeguruitwin_MC/kakeguruitwin_mc.cpp", "max_forks_repo_name": "dc1394/kakeguruitwin_MC", "max_forks_repo_head_hexsha": "dffcf2da01c4e2a0afe7464d61c7c17e2079af50", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5258964143, "max_line_length": 114, "alphanum_fraction": 0.5672311478, "num_tokens": 5194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.21843392700013367}}
{"text": "#include <stdio.h>\n#include <string.h>\n#include <iostream>\n#include <iterator>\n#include <vector>\n#include <algorithm>\n#include <Eigen/Core>\n#include <urdf/model.h>\n#include <kdl_parser/kdl_parser.hpp>\n#include \"ros/ros.h\"\n\n#include \"snoptProblem.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nconst string prefix     = \"j2s7s300\";\nconst double pi         = 3.1415926535897;\n\nconst int T             = 10.0;         // planning horizon\nconst double dt         = 0.5;          // timestep\nconst int dofRobot      = 3;            // num dofs of robot\nconst int dofEnv        = 1;            // num dofs of environment\nconst int dofLamb       =  1;           // dimension of contact forces \n\nconst double goal[] = {-0.4, 0.5};\nconst double obsLow[]   = {-1.0, 0.3};\nconst double obsHigh[]  = {1.0, 0.3};\n\n// --------- HELPER FUNCTIONS --------- //\n\nVectorXf config2DTo3D(VectorXf& q2D){\n  VectorXf q3D(10);\n  q3D << q2D(0), pi/2.0, pi/2.0, q2D(1), pi, q2D(2), pi, 0, 0, 0;\n  return q3D;\n}\n\nVectorXf config3DTo2D(VectorXf& q3D){\n  VectorXf q2D(3);\n  q2D << q3D(0), q3D(3), q3D(5);\n  return q2D;\n}\n\nVectorXf vel2DTo3D(VectorXf& dq2D){\n  VectorXf dq3D(10);\n  dq3D << dq2D(0), 0, 0, dq2D(1), 0, dq2D(2), 0, 0, 0, 0;\n  return dq3D;\n}\n\nVectorXf vel3DTo2D(VectorXf& dq3D){\n  VectorXf dq2D(3);\n  dq2D << dq3D(0), dq3D(3), dq3D(5);\n  return dq2D;\n}\n\nVectorXf control2DTo3D(VectorXf& u2D){\n  VectorXf u3D(10);\n  u3D << u2D(0), 0, 0, u2D(1), 0, u2D(2), 0, 0, 0, 0;\n  return u3D;\n}\n\nVectorXf control3DTo2D(VectorXf& u3D){\n  VectorXf u2D(3);\n  u2D << u3D(0), u3D(3), u3D(5);\n  return u2D;\n}\n\nVectorXf acc2DTo3D(VectorXf& ddq2D){\n  VectorXf ddq3D(10);\n  ddq3D << ddq2D(0), 0, 0, ddq2D(1), 0, ddq2D(2), 0, 0, 0, 0;\n  return ddq3D;\n}\n\nVectorXf acc3DTo2D(VectorXf& ddq3D){\n  VectorXf ddq2D(3);\n  ddq2D << ddq3D(0), ddq3D(3), ddq3D(5);\n  return ddq2D;\n}\n\n// --------- GETTER FUNCTIONS --------- //\n\ndouble getFinalCost(VectorXf& q, VectorXf& dq){\n  VectorXf q3D = config2DTo3D(q);\n  //string linkName = strcat(prefix, \"_link_7\");\n  //vector<double> eePose = getTransform(robot, q3d, linkName);\n  // VectorXf goal(2);\n  // goalPose << goal[0], goal[1];\n  //double gf = 30*(goalPose - eePose).norm();\n  double gf = 0.0;\n  return gf;\n}\n\ndouble getRunningCost(VectorXf& q, VectorXf& dq, VectorXf& u){\n  return 0.0;\n}\n\nVectorXf getConfigRobot(double *x, int t){\n  VectorXf qRobot(dofRobot); \n  int lowOffset = 2*(dofRobot + dofEnv)*t + 1;\n  int upOffset  = 2*(dofRobot + dofEnv)*t + dofRobot;\n  for(size_t ii=lowOffset; ii <= upOffset; ii++)    // TODO check if should be inclusive\n    qRobot(ii-lowOffset) = x[ii];\n  return qRobot;\n}\n\nVectorXf getVelRobot(double *x, int t){\n  VectorXf dqRobot(dofRobot); \n  int lowOffset = 2*(dofRobot + dofEnv)*t + (dofRobot + dofEnv) + 1;\n  int upOffset  = 2*(dofRobot + dofEnv)*t + (dofRobot + dofEnv) + dofRobot;\n  for(size_t ii=lowOffset; ii <= upOffset; ii++)    // TODO check if should be inclusive\n    dqRobot(ii-lowOffset) = x[ii];\n  return dqRobot;\n}\n\nVectorXf getConfigEnv(double *x, int t){\n  VectorXf qEnv(dofEnv); //= new double[dofEnv];\n  int lowOffset = 2*(dofRobot + dofEnv)*t + dofRobot + 1;\n  int upOffset  = 2*(dofRobot + dofEnv)*t + dofRobot + dofEnv;\n  for(size_t ii=lowOffset; ii <= upOffset; ii++)    // TODO check if should be inclusive\n    qEnv(ii-lowOffset) = x[ii];\n  return qEnv;\n}\n\nVectorXf getVelEnv(double *x, int t){\n  VectorXf dqEnv(dofEnv); \n  int lowOffset = 2*(dofRobot + dofEnv)*t + (dofRobot + dofEnv) + dofRobot + 1;\n  int upOffset  = 2*(dofRobot + dofEnv)*t + 2*(dofRobot + dofEnv);\n  for(size_t ii=lowOffset; ii <= upOffset; ii++)    // TODO check if should be inclusive\n    dqEnv(ii-lowOffset) = x[ii];\n  return dqEnv;\n}\n\nVectorXf getU(double *x, int t){\n  VectorXf u(dofRobot); \n  int nx = 2*(dofRobot+dofEnv)*(T+1);\n  int lowOffset = nx + 1 + dofRobot*(t - 1);\n  int upOffset  = nx + 1 + dofRobot*t - 1;\n  for(size_t ii=lowOffset; ii <= upOffset; ii++)    // TODO check if should be inclusive\n    u(ii-lowOffset) = x[ii];\n  return u;\n}\n// ------------------------------------ //\n\n// --------- SETTER FUNCTIONS --------- //\n\nvoid setConfigRobot(double *x, int t, double *q){\n  int lowOffset = 2*(dofRobot + dofEnv)*t + 1;\n  int upOffset  = 2*(dofRobot + dofEnv)*t + dofRobot;\n  copy(x + lowOffset, x + upOffset, q);\n}\n\nvoid setConfigEnv(double *x, int t, double *q){\n  int lowOffset = 2*(dofRobot + dofEnv)*t + dofRobot + 1;\n  int upOffset  = 2*(dofRobot + dofEnv)*t + dofRobot + dofEnv;\n  copy(x + lowOffset, x + upOffset, q);\n}\n\nvoid setVelRobot(double *x, int t, double *dq){\n  int lowOffset = 2*(dofRobot + dofEnv)*t + (dofRobot + dofEnv) + 1;\n  int upOffset  = 2*(dofRobot + dofEnv)*t + (dofRobot + dofEnv) + dofRobot;\n  copy(x + lowOffset, x + upOffset, dq);\n}\n\nvoid setVelEnv(double *x, int t, double *dq){\n  int lowOffset = 2*(dofRobot + dofEnv)*t + (dofRobot + dofEnv) + dofRobot + 1;\n  int upOffset  = 2*(dofRobot + dofEnv)*t + 2*(dofRobot + dofEnv);\n  copy(x + lowOffset, x + upOffset, dq);\n}\n\nvoid setU(double *x, int t, double *u, int nx){\n  int uStart    = nx + 1;\n  int lowOffset = uStart + dofRobot*(t-1);\n  int upOffset  = uStart + dofRobot*t - 1;\n  copy(x + lowOffset, x + upOffset, u);\n}\n\nvoid setLambda(double *x, int t, double *lambda, int nx, int nu){\n  int lambStart = nx + nu + 1;\n  int lowOffset = lambStart + dofLamb*(t-1);\n  int upOffset  = lambStart + dofLamb*t - 1;\n  copy(x + lowOffset, x + upOffset, lambda);\n}\n\n// ------------------------------------ //\n\nvoid userfun(int    *Status, int *n,    double x[],\n       int    *needF,  int *neF,  double F[],\n       int    *needG,  int *neG,  double G[],\n       char      *cu,  int *lencu,\n       int    iu[],    int *leniu,\n       double ru[],    int *lenru) {\n  \n  // TODO IMPLEMENT ME!\n  VectorXf qRobot_T   = getConfigRobot(x, T);\n  VectorXf dqRobot_T  = getVelRobot(x, T);\n  double obj          = getFinalCost(qRobot_T, dqRobot_T); \n\n  int kinLen  = (dofRobot + dofEnv)*T;\n  int dynLen  = (dofRobot + dofEnv)*T;\n  int collLen = T;\n\n  // Compute kinematic, dynamics, and collision constraints\n  double *kinConstraints = new double[kinLen];\n  double *dynConstraints = new double[dynLen];\n  double *collConstraints = new double[collLen];\n\n  for(int t=0; t<T-1; t++){\n    VectorXf qRobot_t  = getConfigRobot(x, t);\n    VectorXf qRobot_t1 = getConfigRobot(x, t+1); \n\n    VectorXf dqRobot_t   = getVelRobot(x, t);\n    VectorXf dqRobot_t1  = getVelRobot(x, t+1);\n\n    VectorXf dqEnv_t   = getVelEnv(x, t);\n    VectorXf dqEnv_t1  = getVelEnv(x, t+1); \n\n    VectorXf qEnv_t  = getConfigEnv(x, t);\n    VectorXf qEnv_t1 = getConfigEnv(x, t+1); \n\n    VectorXf ddqRobot_t1  = (dqRobot_t1 - dqRobot_t)/dt;\n    VectorXf ddqEnv_t1    = (dqEnv_t1 - dqEnv_t)/dt;\n\n    VectorXf qRobot3D_t1  = config2DTo3D(qRobot_t1);\n    VectorXf dqRobot3D_t1 = vel2DTo3D(qRobot_t1);\n\n    VectorXf u_t1   = getU(x, t+1);\n    VectorXf u3D_t1 = control2DTo3D(u_t1);\n\n    //VectorXf ddqRobot3D_t1_fwd  = forwardDynamics(robot, qRobot3D_t1, dqRobot3D_t1, u3D_t1);\n    //VectorXf ddqRobot_t1_fwd    = acc3DTo2D(ddqRobot3D_t1_fwd);\n\n    obj += dt*getRunningCost(qRobot_t, dqRobot_t, u_t1);\n  }\n\n  int kinStart  = 1;\n  int dynStart  = kinStart + kinLen + 1; \n  int collStart = dynStart + dynLen + 1;\n\n  // Set up the constraint vector\n  F[0] = obj;\n  copy(F + kinStart, F + kinStart + kinLen, kinConstraints);\n  copy(F + dynStart, F + dynStart + dynLen, dynConstraints);\n  copy(F + collStart, F + collStart + collLen, collConstraints);\n}\n\n\nint main(int argc, char **argv) {\n  snoptProblemA ToyProb;\n\n  string urdf_file = \"../urdf/jaco_dynamics.urdf\";\n\n  /*urdf::Model robot;\n  if (!robot.initString(urdf_file)) {\n    ROS_FATAL(\"Could not initialize robot model\");\n    return -1;\n  }\n\n  KDL::Tree tree;\n  if (!kdl_parser::treeFromFile(urdf_file, tree)){\n    ROS_ERROR(\"Failed to construct kdl tree\");\n    return false;\n  }*/\n\n  // Allocate and initialize;\n  int nx        =  2*(dofRobot+dofEnv)*(T+1); // num states over time horizon\n  int nu        =  dofRobot*T;        // num controls over time horizon\n  int nlamb     =  T;\n\n  int neF       =  1 + 2*(dofRobot+dofEnv)*T+T; // num constraints\n  int n         =  nx + nu + nlamb;\n\n  int nS = 0, nInf;\n  double sInf;\n\n  double *x      = new double[n];\n  double *xlow   = new double[n];\n  double *xupp   = new double[n];\n  double *xmul   = new double[n];\n  int    *xstate = new    int[n];\n\n  double *F      = new double[neF];\n  double *Flow   = new double[neF];\n  double *Fupp   = new double[neF];\n  double *Fmul   = new double[neF];\n  int    *Fstate = new int[neF];    // vector of inittial states of F(x)\n\n  int    ObjRow  = 0;   // constant value added to the objective\n  double ObjAdd  = 0;   // row of F(x) containing the objective\n\n  int Cold = 0, Basis = 1, Warm = 2;\n  int signedDistLinkStart = 1 + 2*(dofRobot + dofEnv)*T;\n\n  double *qRobotInit    = new double[dofRobot];\n  double *qRobotMin     = new double[dofRobot]; // all zeros\n  double *qRobotMax     = new double[dofRobot];\n  \n  double *qEnvInit      = new double[dofEnv];   // all zeros\n  double *qEnvMin       = new double[dofEnv];   // all zeros\n  double *qEnvMax       = new double[dofEnv];\n\n  double *dqRobotInit   = new double[dofRobot]; // all zeros\n  double *dqRobotMin    = new double[dofRobot]; // all zeros\n  double *dqRobotMax    = new double[dofRobot];\n\n  double *dqEnvInit     = new double[dofEnv];   // all zeros\n  double *dqEnvMin      = new double[dofEnv];   // all zeros\n  double *dqEnvMax      = new double[dofEnv];\n\n  double *lambMin       = new double[dofLamb];  // all zeros\n  double *lambMax       = new double[dofLamb];\n\n  double *uMin          = new double[dofRobot];\n  double *uMax          = new double[dofRobot];\n\n  // --------- Set up init, max and min  --------- //\n\n  fill(qRobotInit, qRobotInit + dofRobot, pi);\n  fill(qRobotMax, qRobotMax + dofRobot, 2.0*pi);\n\n  fill(dqRobotMin, dqRobotMin + dofRobot, -0.35);\n  fill(dqRobotMax, dqRobotMax + dofRobot, 0.35);\n\n  fill(qEnvMax, qEnvMax + dofEnv, 100.0);\n  fill(dqEnvMax, dqEnvMax + dofEnv, 10.0);\n\n  fill(uMin, uMin + dofRobot, -100.0);\n  fill(uMax, uMax + dofRobot, 100.0);\n\n  fill(lambMax, lambMax + dofLamb, 1000.0);\n\n  // --------------------------------------------- //\n\n  // --------- Set up the constraints on x --------- //\n  \n  for(int t = 0;t < T;t++){\n    if(t == 0){\n      // Constrain initial config and velocity\n      setConfigRobot(xlow, t, qRobotInit);\n      setConfigRobot(xupp, t, qRobotInit);\n\n      setVelRobot(xlow, t, dqRobotInit);\n      setVelRobot(xupp, t, dqRobotInit);\n\n      setConfigEnv(xlow, t, qEnvInit);\n      setConfigEnv(xupp, t, qEnvInit);\n\n      setVelEnv(xlow, t, dqEnvInit);\n      setVelEnv(xupp, t, dqEnvInit);\n\n    }else{\n      // Constrain joint limits for rest of trajectory\n      setConfigRobot(xlow, t, qRobotMin);\n      setConfigRobot(xupp, t, qRobotMax);\n\n      setVelRobot(xlow, t, dqRobotMin);\n      setVelRobot(xupp, t, dqRobotMax);\n\n      setConfigEnv(xlow, t, qEnvMin);\n      setConfigEnv(xupp, t, qEnvMax);\n\n      setVelEnv(xlow, t, dqEnvMin);\n      setVelEnv(xupp, t, dqEnvMax);\n    }\n\n    if(t > 0){\n      // Set torque limits\n      setU(xlow, t, uMin, nx);\n      setU(xupp, t, uMax, nx);\n\n      // Set lambda constraint forces\n      setLambda(xlow, t, lambMin, nx, nu);\n      setLambda(xupp, t, lambMax, nx, nu);\n    }\n  }\n\n  // ----------------------------------------------- //\n\n  // Set bounds on the objective\n  Flow[0] = -1e3; \n  Fupp[0] =  1e3; \n  fill(Fupp + signedDistLinkStart, Fupp + signedDistLinkStart + T, 1000.0);\n\n  // Load the data for planContact ...\n  ToyProb.initialize    (\"\", 1);          // no print file; summary on\n  ToyProb.setPrintFile  (\"Contact.out\");  // oh wait, i want a print file\n  ToyProb.setProbName   (\"Contact\");\n\n  // snopta will compute the Jacobian by finite-differences.\n  // snJac will be called  to define the\n  // coordinate arrays (iAfun,jAvar,A) and (iGfun, jGvar).\n  ToyProb.setIntParameter(\"Derivative option\", 0);\n  ToyProb.setIntParameter(\"Verify level \", 3);\n\n  // Solve the problem.\n  // snJac is called implicitly in this case to compute the Jacobian.\n  ToyProb.solve(Cold, neF, n, ObjAdd, ObjRow, userfun,\n\t\txlow, xupp, Flow, Fupp,\n\t\tx, xstate, xmul, F, Fstate, Fmul,\n\t\tnS, nInf, sInf);\n\n  for (int i = 0; i < n; i++){\n    cout << \"x = \" << x[i] << \" xstate = \" << xstate[i] << endl;\n  }\n\n  delete []x;      delete []xlow;   delete []xupp;\n  delete []xmul;   delete []xstate;\n\n  delete []F;      delete []Flow;   delete []Fupp;\n  delete []Fmul;   delete []Fstate;\n}\n", "meta": {"hexsha": "83962426c655ffda4ea03107b4ae610f61b82703", "size": 12466, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ros/src/contact_planner/src/planContact.cpp", "max_stars_repo_name": "abajcsy/jaco_contact_planning", "max_stars_repo_head_hexsha": "c47e71962346d9252a812d86da9c7fc2ca78acef", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-22T03:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-22T03:12:21.000Z", "max_issues_repo_path": "ros/src/contact_planner/src/planContact.cpp", "max_issues_repo_name": "abajcsy/jaco_contact_planning", "max_issues_repo_head_hexsha": "c47e71962346d9252a812d86da9c7fc2ca78acef", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ros/src/contact_planner/src/planContact.cpp", "max_forks_repo_name": "abajcsy/jaco_contact_planning", "max_forks_repo_head_hexsha": "c47e71962346d9252a812d86da9c7fc2ca78acef", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3309002433, "max_line_length": 94, "alphanum_fraction": 0.6124659073, "num_tokens": 4340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.21843392700013367}}
{"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb\n Copyright (C) 2006 Cristina Duminuco\n Copyright (C) 2006 Marco Bianchetti\n Copyright (C) 2007 StatPro Italia srl\n Copyright (C) 2014 Ferdinando Ametrano\n Copyright (C) 2016 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n/*! \\file swaption.hpp\n    \\brief Swaption class\n*/\n\n#ifndef quantlib_instruments_swaption_hpp\n#define quantlib_instruments_swaption_hpp\n\n#include <ql/option.hpp>\n#include <ql/instruments/vanillaswap.hpp>\n#include <ql/termstructures/yieldtermstructure.hpp>\n#include <ql/termstructures/volatility/volatilitytype.hpp>\n\nnamespace QuantLib {\n\n    //! %settlement information\n    struct Settlement {\n        enum Type { Physical, Cash };\n    };\n\n    std::ostream& operator<<(std::ostream& out,\n                             Settlement::Type type);\n\n    //! %Swaption class\n    /*! \\ingroup instruments\n\n        \\test\n        - the correctness of the returned value is tested by checking\n          that the price of a payer (resp. receiver) swaption\n          decreases (resp. increases) with the strike.\n        - the correctness of the returned value is tested by checking\n          that the price of a payer (resp. receiver) swaption\n          increases (resp. decreases) with the spread.\n        - the correctness of the returned value is tested by checking\n          it against that of a swaption on a swap with no spread and a\n          correspondingly adjusted fixed rate.\n        - the correctness of the returned value is tested by checking\n          it against a known good value.\n        - the correctness of the returned value of cash settled swaptions\n          is tested by checking the modified annuity against a value\n          calculated without using the Swaption class.\n\n\n        \\todo add greeks and explicit exercise lag\n    */\n    class Swaption : public Option {\n      public:\n        class arguments;\n        class engine;\n        Swaption(const boost::shared_ptr<VanillaSwap>& swap,\n                 const boost::shared_ptr<Exercise>& exercise,\n                 Settlement::Type delivery = Settlement::Physical);\n        //! \\name Instrument interface\n        //@{\n        bool isExpired() const;\n        void setupArguments(PricingEngine::arguments*) const;\n        //@}\n        //! \\name Inspectors\n        //@{\n        Settlement::Type settlementType() const { return settlementType_; }\n        VanillaSwap::Type type() const { return swap_->type(); }\n        const boost::shared_ptr<VanillaSwap>& underlyingSwap() const {\n            return swap_;\n        }\n        //@}\n        //! implied volatility\n        Volatility impliedVolatility(\n                              Real price,\n                              const Handle<YieldTermStructure>& discountCurve,\n                              Volatility guess,\n                              Real accuracy = 1.0e-4,\n                              Natural maxEvaluations = 100,\n                              Volatility minVol = 1.0e-7,\n                              Volatility maxVol = 4.0,\n                              VolatilityType type = ShiftedLognormal,\n                              Real displacement = 0.0) const;\n      private:\n        // arguments\n        boost::shared_ptr<VanillaSwap> swap_;\n        //Handle<YieldTermStructure> termStructure_;\n        Settlement::Type settlementType_;\n    };\n\n    //! %Arguments for swaption calculation\n    class Swaption::arguments : public VanillaSwap::arguments,\n                                public Option::arguments {\n      public:\n        arguments() : settlementType(Settlement::Physical) {}\n        boost::shared_ptr<VanillaSwap> swap;\n        Settlement::Type settlementType;\n        void validate() const;\n    };\n\n    //! base class for swaption engines\n    class Swaption::engine\n        : public GenericEngine<Swaption::arguments, Swaption::results> {};\n\n}\n\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb\n Copyright (C) 2006 Cristina Duminuco\n Copyright (C) 2006 Marco Bianchetti\n Copyright (C) 2007 StatPro Italia srl\n Copyright (C) 2014 Ferdinando Ametrano\n Copyright (C) 2016 Peter Caspers\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license.  You should have received a\n copy of the license along with this program; if not, please email\n <quantlib-dev@lists.sf.net>. The license is also available online at\n <http://quantlib.org/license.shtml>.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE.  See the license for more details.\n*/\n\n#include <ql/pricingengines/swaption/blackswaptionengine.hpp>\n#include <ql/math/solvers1d/newtonsafe.hpp>\n#include <ql/quotes/simplequote.hpp>\n#include <ql/exercise.hpp>\n\n#include <boost/make_shared.hpp>\n\nnamespace QuantLib {\n\n    namespace {\n\n        class ImpliedSwaptionVolHelper {\n          public:\n            ImpliedSwaptionVolHelper(const Swaption&,\n                                     const Handle<YieldTermStructure>& discountCurve,\n                                     Real targetValue,\n                                     Real displacement,\n                                     VolatilityType type);\n            Real operator()(Volatility x) const;\n            Real derivative(Volatility x) const;\n          private:\n            boost::shared_ptr<PricingEngine> engine_;\n            Handle<YieldTermStructure> discountCurve_;\n            Real targetValue_;\n            boost::shared_ptr<SimpleQuote> vol_;\n            const Instrument::results* results_;\n        };\n\n    inline     ImpliedSwaptionVolHelper::ImpliedSwaptionVolHelper(\n                              const Swaption& swaption,\n                              const Handle<YieldTermStructure>& discountCurve,\n                              Real targetValue,\n                              Real displacement,\n                              VolatilityType type)\n        : discountCurve_(discountCurve), targetValue_(targetValue) {\n\n            // set an implausible value, so that calculation is forced\n            // at first ImpliedSwaptionVolHelper::operator()(Volatility x) call\n            vol_ = boost::shared_ptr<SimpleQuote>(new SimpleQuote(-1.0));\n            Handle<Quote> h(vol_);\n\n            switch (type) {\n            case ShiftedLognormal:\n                engine_ = boost::make_shared<BlackSwaptionEngine>(\n                    discountCurve_, h, Actual365Fixed(), displacement);\n                break;\n            case Normal:\n                engine_ = boost::make_shared<BachelierSwaptionEngine>(\n                    discountCurve_, h, Actual365Fixed());\n                break;\n            default:\n                QL_FAIL(\"unknown VolatilityType (\" << type << \")\");\n                break;\n            }\n            swaption.setupArguments(engine_->getArguments());\n            results_ = dynamic_cast<const Instrument::results *>(\n                engine_->getResults());\n        }\n\n    inline     Real ImpliedSwaptionVolHelper::operator()(Volatility x) const {\n            if (x!=vol_->value()) {\n                vol_->setValue(x);\n                engine_->calculate();\n            }\n            return results_->value-targetValue_;\n        }\n\n    inline     Real ImpliedSwaptionVolHelper::derivative(Volatility x) const {\n            if (x!=vol_->value()) {\n                vol_->setValue(x);\n                engine_->calculate();\n            }\n            std::map<std::string,boost::any>::const_iterator vega_ =\n                results_->additionalResults.find(\"vega\");\n            QL_REQUIRE(vega_ != results_->additionalResults.end(),\n                       \"vega not provided\");\n            return boost::any_cast<Real>(vega_->second);\n        }\n    }\n\n    inline std::ostream& operator<<(std::ostream& out,\n                             Settlement::Type t) {\n        switch (t) {\n          case Settlement::Physical:\n            return out << \"Delivery\";\n          case Settlement::Cash:\n            return out << \"Cash\";\n          default:\n            QL_FAIL(\"unknown Settlement::Type(\" << Integer(t) << \")\");\n        }\n    }\n\n    inline Swaption::Swaption(const boost::shared_ptr<VanillaSwap>& swap,\n                       const boost::shared_ptr<Exercise>& exercise,\n                       Settlement::Type delivery)\n    : Option(boost::shared_ptr<Payoff>(), exercise), swap_(swap),\n      settlementType_(delivery) {\n        registerWith(swap_);\n        registerWithObservables(swap_);\n    }\n\n    inline bool Swaption::isExpired() const {\n        return detail::simple_event(exercise_->dates().back()).hasOccurred();\n    }\n\n    inline void Swaption::setupArguments(PricingEngine::arguments* args) const {\n\n        swap_->setupArguments(args);\n\n        Swaption::arguments* arguments =\n            dynamic_cast<Swaption::arguments*>(args);\n\n        QL_REQUIRE(arguments != 0, \"wrong argument type\");\n\n        arguments->swap = swap_;\n        arguments->settlementType = settlementType_;\n        arguments->exercise = exercise_;\n    }\n\n    inline void Swaption::arguments::validate() const {\n        VanillaSwap::arguments::validate();\n        QL_REQUIRE(swap, \"vanilla swap not set\");\n        QL_REQUIRE(exercise, \"exercise not set\");\n    }\n\n    inline Volatility Swaption::impliedVolatility(Real targetValue,\n                                           const Handle<YieldTermStructure>& d,\n                                           Volatility guess,\n                                           Real accuracy,\n                                           Natural maxEvaluations,\n                                           Volatility minVol,\n                                           Volatility maxVol,\n                                           VolatilityType type,\n                                           Real displacement) const {\n        //calculate();\n        QL_REQUIRE(!isExpired(), \"instrument expired\");\n\n        ImpliedSwaptionVolHelper f(*this, d, targetValue, displacement, type);\n        //Brent solver;\n        NewtonSafe solver;\n        solver.setMaxEvaluations(maxEvaluations);\n        return solver.solve(f, accuracy, guess, minVol, maxVol);\n    }\n\n}\n\n#endif\n", "meta": {"hexsha": "4df864119fd1bda7e753f89f8c07f985f4c8c9d6", "size": 11164, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/instruments/swaption.hpp", "max_stars_repo_name": "markxio/Quantuccia", "max_stars_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2017-03-20T14:17:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T08:00:52.000Z", "max_issues_repo_path": "ql/instruments/swaption.hpp", "max_issues_repo_name": "markxio/Quantuccia", "max_issues_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2017-04-02T14:34:07.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T05:31:12.000Z", "max_forks_repo_path": "ql/instruments/swaption.hpp", "max_forks_repo_name": "markxio/Quantuccia", "max_forks_repo_head_hexsha": "ebe71a1b9c2a9ee7fc4ea918a9602f100316869d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2017-03-19T05:56:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T13:30:20.000Z", "avg_line_length": 37.8440677966, "max_line_length": 85, "alphanum_fraction": 0.5966499463, "num_tokens": 2292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.21843392700013367}}
{"text": "// $Id$\n//\n//  Copyright (C) 2007-2013 Greg Landrum\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n\n#include <GraphMol/RDKitBase.h>\n#include <GraphMol/Fingerprints/AtomPairs.h>\n#include <GraphMol/Subgraphs/Subgraphs.h>\n#include <DataStructs/SparseIntVect.h>\n#include <RDGeneral/hash/hash.hpp>\n#include <boost/cstdint.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/foreach.hpp>\n\nnamespace RDKit {\nnamespace AtomPairs {\nunsigned int numPiElectrons(const Atom *atom) {\n  PRECONDITION(atom, \"no atom\");\n  unsigned int res = 0;\n  if (atom->getIsAromatic()) {\n    res = 1;\n  } else if (atom->getHybridization() != Atom::SP3) {\n    unsigned int val = static_cast<unsigned int>(atom->getExplicitValence());\n    val -= atom->getNumExplicitHs();\n    CHECK_INVARIANT(val >= atom->getDegree(),\n                    \"explicit valence exceeds atom degree\");\n    res = val - atom->getDegree();\n  }\n  return res;\n}\n\nboost::uint32_t getAtomCode(const Atom *atom, unsigned int branchSubtract,\n                            bool includeChirality) {\n  PRECONDITION(atom, \"no atom\");\n  boost::uint32_t code;\n\n  unsigned int numBranches = 0;\n  if (atom->getDegree() > branchSubtract) {\n    numBranches = atom->getDegree() - branchSubtract;\n  }\n\n  code = numBranches % maxNumBranches;\n  unsigned int nPi = numPiElectrons(atom) % maxNumPi;\n  code |= nPi << numBranchBits;\n\n  unsigned int typeIdx = 0;\n  unsigned int nTypes = 1 << numTypeBits;\n  while (typeIdx < nTypes) {\n    if (atomNumberTypes[typeIdx] ==\n        static_cast<unsigned int>(atom->getAtomicNum())) {\n      break;\n    } else if (atomNumberTypes[typeIdx] >\n               static_cast<unsigned int>(atom->getAtomicNum())) {\n      typeIdx = nTypes;\n      break;\n    }\n    ++typeIdx;\n  }\n  if (typeIdx == nTypes) --typeIdx;\n  code |= typeIdx << (numBranchBits + numPiBits);\n  if (includeChirality) {\n    std::string cipCode;\n    if (atom->getPropIfPresent(common_properties::_CIPCode, cipCode)) {\n      boost::uint32_t offset = numBranchBits + numPiBits + numTypeBits;\n      if (cipCode == \"R\") {\n        code |= 1 << offset;\n      } else if (cipCode == \"S\") {\n        code |= 2 << offset;\n      }\n    }\n  }\n  POSTCONDITION(code < static_cast<boost::uint32_t>(1 << (codeSize + (includeChirality ? 2 : 0))),\n                \"code exceeds number of bits\");\n  return code;\n};\n\nboost::uint32_t getAtomPairCode(boost::uint32_t codeI, boost::uint32_t codeJ,\n                                unsigned int dist, bool includeChirality) {\n  PRECONDITION(dist < maxPathLen, \"dist too long\");\n  boost::uint32_t res = dist;\n  res |= std::min(codeI, codeJ) << numPathBits;\n  res |= std::max(codeI, codeJ)\n         << (numPathBits + codeSize + (includeChirality ? numChiralBits : 0));\n  return res;\n}\n\ntemplate <typename T1, typename T2>\nvoid updateElement(SparseIntVect<T1> &v, T2 elem) {\n  v.setVal(elem, v.getVal(elem) + 1);\n}\n\ntemplate <typename T1>\nvoid updateElement(ExplicitBitVect &v, T1 elem) {\n  v.setBit(elem % v.getNumBits());\n}\n\ntemplate <typename T>\nvoid setAtomPairBit(boost::uint32_t i, boost::uint32_t j,\n                    boost::uint32_t nAtoms,\n                    const std::vector<boost::uint32_t> &atomCodes,\n                    const double *dm, T *bv, unsigned int minLength,\n                    unsigned int maxLength, bool includeChirality) {\n  unsigned int dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));\n  if (dist >= minLength && dist <= maxLength) {\n    boost::uint32_t bitId =\n        getAtomPairCode(atomCodes[i], atomCodes[j], dist, includeChirality);\n    updateElement(*bv, static_cast<boost::uint32_t>(bitId));\n  }\n}\n\nSparseIntVect<boost::int32_t> *getAtomPairFingerprint(\n    const ROMol &mol, const std::vector<boost::uint32_t> *fromAtoms,\n    const std::vector<boost::uint32_t> *ignoreAtoms,\n    const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,\n    bool use2D, int confId) {\n  return getAtomPairFingerprint(mol, 1, maxPathLen - 1, fromAtoms, ignoreAtoms,\n                                atomInvariants, includeChirality, use2D,\n                                confId);\n};\n\nSparseIntVect<boost::int32_t> *getAtomPairFingerprint(\n    const ROMol &mol, unsigned int minLength, unsigned int maxLength,\n    const std::vector<boost::uint32_t> *fromAtoms,\n    const std::vector<boost::uint32_t> *ignoreAtoms,\n    const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,\n    bool use2D, int confId) {\n  PRECONDITION(minLength <= maxLength, \"bad lengths provided\");\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  SparseIntVect<boost::int32_t> *res = new SparseIntVect<boost::int32_t>(\n      1 << (numAtomPairFingerprintBits + 2 * (includeChirality ? 2 : 0)));\n  const double *dm;\n  if (use2D) {\n    dm = MolOps::getDistanceMat(mol);\n  } else {\n    dm = MolOps::get3DDistanceMat(mol, confId);\n  }\n  const unsigned int nAtoms = mol.getNumAtoms();\n\n  std::vector<boost::uint32_t> atomCodes;\n  for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();\n       atomItI != mol.endAtoms(); ++atomItI) {\n    if (!atomInvariants) {\n      atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));\n    } else {\n      atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()] %\n                          ((1 << codeSize) - 1));\n    }\n  }\n\n  for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();\n       atomItI != mol.endAtoms(); ++atomItI) {\n    unsigned int i = (*atomItI)->getIdx();\n    if (ignoreAtoms &&\n        std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=\n            ignoreAtoms->end()) {\n      continue;\n    }\n    if (!fromAtoms) {\n      for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;\n           atomItJ != mol.endAtoms(); ++atomItJ) {\n        unsigned int j = (*atomItJ)->getIdx();\n        if (ignoreAtoms &&\n            std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=\n                ignoreAtoms->end()) {\n          continue;\n        }\n        setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,\n                       includeChirality);\n      }\n    } else {\n      BOOST_FOREACH (boost::uint32_t j, *fromAtoms) {\n        if (j != i) {\n          if (ignoreAtoms &&\n              std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=\n                  ignoreAtoms->end()) {\n            continue;\n          }\n          setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,\n                         includeChirality);\n        }\n      }\n    }\n  }\n  return res;\n}\n\nSparseIntVect<boost::int32_t> *getHashedAtomPairFingerprint(\n    const ROMol &mol, unsigned int nBits, unsigned int minLength,\n    unsigned int maxLength, const std::vector<boost::uint32_t> *fromAtoms,\n    const std::vector<boost::uint32_t> *ignoreAtoms,\n    const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality,\n    bool use2D, int confId) {\n  PRECONDITION(minLength <= maxLength, \"bad lengths provided\");\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  SparseIntVect<boost::int32_t> *res = new SparseIntVect<boost::int32_t>(nBits);\n  const double *dm;\n  if (use2D) {\n    dm = MolOps::getDistanceMat(mol);\n  } else {\n    dm = MolOps::get3DDistanceMat(mol, confId);\n  }\n\n  const unsigned int nAtoms = mol.getNumAtoms();\n\n  std::vector<boost::uint32_t> atomCodes;\n  atomCodes.reserve(nAtoms);\n  for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();\n       atomItI != mol.endAtoms(); ++atomItI) {\n    if (!atomInvariants) {\n      atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));\n    } else {\n      atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()]);\n    }\n  }\n\n  for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();\n       atomItI != mol.endAtoms(); ++atomItI) {\n    unsigned int i = (*atomItI)->getIdx();\n    if (ignoreAtoms &&\n        std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=\n            ignoreAtoms->end()) {\n      continue;\n    }\n    if (!fromAtoms) {\n      for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;\n           atomItJ != mol.endAtoms(); ++atomItJ) {\n        unsigned int j = (*atomItJ)->getIdx();\n        if (ignoreAtoms &&\n            std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=\n                ignoreAtoms->end()) {\n          continue;\n        }\n        unsigned int dist =\n            static_cast<unsigned int>(floor(dm[i * nAtoms + j]));\n        if (dist >= minLength && dist <= maxLength) {\n          boost::uint32_t bit = 0;\n          gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));\n          gboost::hash_combine(bit, dist);\n          gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));\n          updateElement(*res, static_cast<boost::int32_t>(bit % nBits));\n        }\n      }\n    } else {\n      BOOST_FOREACH (boost::uint32_t j, *fromAtoms) {\n        if (j != i) {\n          if (ignoreAtoms &&\n              std::find(ignoreAtoms->begin(), ignoreAtoms->end(), j) !=\n                  ignoreAtoms->end()) {\n            continue;\n          }\n          unsigned int dist =\n              static_cast<unsigned int>(floor(dm[i * nAtoms + j]));\n          if (dist >= minLength && dist <= maxLength) {\n            boost::uint32_t bit = 0;\n            gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));\n            gboost::hash_combine(bit, dist);\n            gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));\n            updateElement(*res, static_cast<boost::int32_t>(bit % nBits));\n          }\n        }\n      }\n    }\n  }\n  return res;\n}\n\nExplicitBitVect *getHashedAtomPairFingerprintAsBitVect(\n    const ROMol &mol, unsigned int nBits, unsigned int minLength,\n    unsigned int maxLength, const std::vector<boost::uint32_t> *fromAtoms,\n    const std::vector<boost::uint32_t> *ignoreAtoms,\n    const std::vector<boost::uint32_t> *atomInvariants,\n    unsigned int nBitsPerEntry, bool includeChirality, bool use2D, int confId) {\n  PRECONDITION(minLength <= maxLength, \"bad lengths provided\");\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  static int bounds[4] = {1, 2, 4, 8};\n\n  unsigned int blockLength = nBits / nBitsPerEntry;\n  SparseIntVect<boost::int32_t> *sres = getHashedAtomPairFingerprint(\n      mol, blockLength, minLength, maxLength, fromAtoms, ignoreAtoms,\n      atomInvariants, includeChirality, use2D, confId);\n  ExplicitBitVect *res = new ExplicitBitVect(nBits);\n  if (nBitsPerEntry != 4) {\n    BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,\n                   sres->getNonzeroElements()) {\n      for (unsigned int i = 0; i < nBitsPerEntry; ++i) {\n        if (val.second > static_cast<int>(i))\n          res->setBit(val.first * nBitsPerEntry + i);\n      }\n    }\n  } else {\n    BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,\n                   sres->getNonzeroElements()) {\n      for (unsigned int i = 0; i < nBitsPerEntry; ++i) {\n        if (val.second >= bounds[i]) {\n          res->setBit(val.first * nBitsPerEntry + i);\n        }\n      }\n    }\n  }\n  delete sres;\n  return res;\n}\n\nboost::uint64_t getTopologicalTorsionCode(\n    const std::vector<boost::uint32_t> &pathCodes, bool includeChirality) {\n  bool reverseIt = false;\n  unsigned int i = 0;\n  unsigned int j = pathCodes.size() - 1;\n  while (i < j) {\n    if (pathCodes[i] > pathCodes[j]) {\n      reverseIt = true;\n      break;\n    } else if (pathCodes[i] < pathCodes[j]) {\n      break;\n    }\n    ++i;\n    --j;\n  }\n\n  int shiftSize = codeSize + (includeChirality ? numChiralBits : 0);\n  boost::uint64_t res = 0;\n  if (reverseIt) {\n    for (unsigned int i = 0; i < pathCodes.size(); ++i) {\n      res |= static_cast<boost::uint64_t>(pathCodes[pathCodes.size() - i - 1])\n             << (shiftSize * i);\n    }\n  } else {\n    for (unsigned int i = 0; i < pathCodes.size(); ++i) {\n      res |= static_cast<boost::uint64_t>(pathCodes[i]) << (shiftSize * i);\n    }\n  }\n  return res;\n}\n\nsize_t getTopologicalTorsionHash(\n    const std::vector<boost::uint32_t> &pathCodes) {\n  bool reverseIt = false;\n  unsigned int i = 0;\n  unsigned int j = pathCodes.size() - 1;\n  while (i < j) {\n    if (pathCodes[i] > pathCodes[j]) {\n      reverseIt = true;\n      break;\n    } else if (pathCodes[i] < pathCodes[j]) {\n      break;\n    }\n    ++i;\n    --j;\n  }\n\n  boost::uint32_t res = 0;\n  if (reverseIt) {\n    for (unsigned int i = 0; i < pathCodes.size(); ++i) {\n      gboost::hash_combine(res, pathCodes[pathCodes.size() - i - 1]);\n    }\n  } else {\n    for (unsigned int i = 0; i < pathCodes.size(); ++i) {\n      gboost::hash_combine(res, pathCodes[i]);\n    }\n  }\n  return res;\n}\n\nSparseIntVect<boost::int64_t> *getTopologicalTorsionFingerprint(\n    const ROMol &mol, unsigned int targetSize,\n    const std::vector<boost::uint32_t> *fromAtoms,\n    const std::vector<boost::uint32_t> *ignoreAtoms,\n    const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality) {\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  boost::uint64_t sz = 1;\n  sz = (sz << (targetSize *\n               (codeSize + (includeChirality ? numChiralBits : 0))));\n  // NOTE: this -1 is incorrect but it's needed for backwards compatibility.\n  //  hopefully we'll never have a case with a torsion that hits this.\n  //\n  //  mmm, bug compatible.\n  sz -= 1;\n  SparseIntVect<boost::int64_t> *res = new SparseIntVect<boost::int64_t>(sz);\n\n  std::vector<boost::uint32_t> atomCodes;\n  atomCodes.reserve(mol.getNumAtoms());\n  for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();\n       atomItI != mol.endAtoms(); ++atomItI) {\n    if (!atomInvariants) {\n      atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));\n    } else {\n      // need to add to the atomCode here because we subtract off up to 2 below\n      // as part of the branch correction\n      atomCodes.push_back(\n          (*atomInvariants)[(*atomItI)->getIdx()] % ((1 << codeSize) - 1) + 2);\n    }\n  }\n\n  boost::dynamic_bitset<> *fromAtomsBV = 0;\n  if (fromAtoms) {\n    fromAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());\n    BOOST_FOREACH (boost::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }\n  }\n  boost::dynamic_bitset<> *ignoreAtomsBV = 0;\n  if (ignoreAtoms) {\n    ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());\n    BOOST_FOREACH (boost::uint32_t fAt, *ignoreAtoms) {\n      ignoreAtomsBV->set(fAt);\n    }\n  }\n  boost::dynamic_bitset<> pAtoms(mol.getNumAtoms());\n  PATH_LIST paths = findAllPathsOfLengthN(mol, targetSize, false);\n  for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();\n       ++pathIt) {\n    bool keepIt = true;\n    if (fromAtomsBV) {\n      keepIt = false;\n    }\n    std::vector<boost::uint32_t> pathCodes;\n    const PATH_TYPE &path = *pathIt;\n    if (fromAtomsBV) {\n      if (fromAtomsBV->test(static_cast<boost::uint32_t>(path.front())) ||\n          fromAtomsBV->test(static_cast<boost::uint32_t>(path.back()))) {\n        keepIt = true;\n      }\n    }\n    if (keepIt && ignoreAtomsBV) {\n      BOOST_FOREACH (int pElem, path) {\n        if (ignoreAtomsBV->test(pElem)) {\n          keepIt = false;\n          break;\n        }\n      }\n    }\n    if (keepIt) {\n      pAtoms.reset();\n      for (PATH_TYPE::const_iterator pIt = path.begin(); pIt < path.end();\n           ++pIt) {\n        // look for a cycle that doesn't start at the first atom\n        // we can't effectively canonicalize these at the moment\n        // (was github #811)\n        if (pIt != path.begin() && *pIt != *(path.begin()) && pAtoms[*pIt]) {\n          pathCodes.clear();\n          break;\n        }\n        pAtoms.set(*pIt);\n        unsigned int code = atomCodes[*pIt] - 1;\n        // subtract off the branching number:\n        if (pIt != path.begin() && pIt + 1 != path.end()) {\n          --code;\n        }\n        pathCodes.push_back(code);\n      }\n      if (pathCodes.size()) {\n        boost::int64_t code =\n            getTopologicalTorsionCode(pathCodes, includeChirality);\n        updateElement(*res, code);\n      }\n    }\n  }\n  delete fromAtomsBV;\n  delete ignoreAtomsBV;\n\n  return res;\n}\n\nnamespace {\ntemplate <typename T>\nvoid TorsionFpCalc(T *res, const ROMol &mol, unsigned int nBits,\n                   unsigned int targetSize,\n                   const std::vector<boost::uint32_t> *fromAtoms,\n                   const std::vector<boost::uint32_t> *ignoreAtoms,\n                   const std::vector<boost::uint32_t> *atomInvariants,\n                   bool includeChirality) {\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  std::vector<boost::uint32_t> atomCodes;\n  atomCodes.reserve(mol.getNumAtoms());\n  for (ROMol::ConstAtomIterator atomItI = mol.beginAtoms();\n       atomItI != mol.endAtoms(); ++atomItI) {\n    if (!atomInvariants) {\n      atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));\n    } else {\n      // need to add to the atomCode here because we subtract off up to 2 below\n      // as part of the branch correction\n      atomCodes.push_back(((*atomInvariants)[(*atomItI)->getIdx()] << 1) + 1);\n    }\n  }\n\n  boost::dynamic_bitset<> *fromAtomsBV = 0;\n  if (fromAtoms) {\n    fromAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());\n    BOOST_FOREACH (boost::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }\n  }\n  boost::dynamic_bitset<> *ignoreAtomsBV = 0;\n  if (ignoreAtoms) {\n    ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());\n    BOOST_FOREACH (boost::uint32_t fAt, *ignoreAtoms) {\n      ignoreAtomsBV->set(fAt);\n    }\n  }\n\n  PATH_LIST paths = findAllPathsOfLengthN(mol, targetSize, false);\n  for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();\n       ++pathIt) {\n    bool keepIt = true;\n    if (fromAtomsBV) {\n      keepIt = false;\n    }\n    const PATH_TYPE &path = *pathIt;\n    if (fromAtomsBV) {\n      if (fromAtomsBV->test(static_cast<boost::uint32_t>(path.front())) ||\n          fromAtomsBV->test(static_cast<boost::uint32_t>(path.back()))) {\n        keepIt = true;\n      }\n    }\n    if (keepIt && ignoreAtomsBV) {\n      BOOST_FOREACH (int pElem, path) {\n        if (ignoreAtomsBV->test(pElem)) {\n          keepIt = false;\n          break;\n        }\n      }\n    }\n    if (keepIt) {\n      std::vector<boost::uint32_t> pathCodes(targetSize);\n      for (unsigned int i = 0; i < targetSize; ++i) {\n        unsigned int code = atomCodes[path[i]] - 1;\n        // subtract off the branching number:\n        if (i > 0 && i < targetSize - 1) {\n          --code;\n        }\n        pathCodes[i] = code;\n      }\n      size_t bit = getTopologicalTorsionHash(pathCodes);\n      updateElement(*res, bit % nBits);\n    }\n  }\n  delete fromAtomsBV;\n  delete ignoreAtomsBV;\n}\n}  // end of local namespace\nSparseIntVect<boost::int64_t> *getHashedTopologicalTorsionFingerprint(\n    const ROMol &mol, unsigned int nBits, unsigned int targetSize,\n    const std::vector<boost::uint32_t> *fromAtoms,\n    const std::vector<boost::uint32_t> *ignoreAtoms,\n    const std::vector<boost::uint32_t> *atomInvariants, bool includeChirality) {\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  SparseIntVect<boost::int64_t> *res = new SparseIntVect<boost::int64_t>(nBits);\n  TorsionFpCalc(res, mol, nBits, targetSize, fromAtoms, ignoreAtoms,\n                atomInvariants, includeChirality);\n  return res;\n}\n\nExplicitBitVect *getHashedTopologicalTorsionFingerprintAsBitVect(\n    const ROMol &mol, unsigned int nBits, unsigned int targetSize,\n    const std::vector<boost::uint32_t> *fromAtoms,\n    const std::vector<boost::uint32_t> *ignoreAtoms,\n    const std::vector<boost::uint32_t> *atomInvariants,\n    unsigned int nBitsPerEntry, bool includeChirality) {\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  static int bounds[4] = {1, 2, 4, 8};\n  unsigned int blockLength = nBits / nBitsPerEntry;\n  SparseIntVect<boost::int64_t> *sres =\n      new SparseIntVect<boost::int64_t>(blockLength);\n  TorsionFpCalc(sres, mol, blockLength, targetSize, fromAtoms, ignoreAtoms,\n                atomInvariants, includeChirality);\n  ExplicitBitVect *res = new ExplicitBitVect(nBits);\n\n  if (nBitsPerEntry != 4) {\n    BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,\n                   sres->getNonzeroElements()) {\n      for (unsigned int i = 0; i < nBitsPerEntry; ++i) {\n        if (val.second > static_cast<int>(i))\n          res->setBit(val.first * nBitsPerEntry + i);\n      }\n    }\n  } else {\n    BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,\n                   sres->getNonzeroElements()) {\n      for (unsigned int i = 0; i < nBitsPerEntry; ++i) {\n        if (val.second >= bounds[i]) {\n          res->setBit(val.first * nBitsPerEntry + i);\n        }\n      }\n    }\n  }\n  delete sres;\n  return res;\n}\n}  // end of namespace AtomPairs\n}  // end of namespace RDKit\n", "meta": {"hexsha": "0937fbeac6690da6bb35834876c92d0c27355e6b", "size": 21305, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Fingerprints/AtomPairs.cpp", "max_stars_repo_name": "docking-org/rdk", "max_stars_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_stars_repo_licenses": ["PostgreSQL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/GraphMol/Fingerprints/AtomPairs.cpp", "max_issues_repo_name": "docking-org/rdk", "max_issues_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_issues_repo_licenses": ["PostgreSQL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/GraphMol/Fingerprints/AtomPairs.cpp", "max_forks_repo_name": "docking-org/rdk", "max_forks_repo_head_hexsha": "6eb710254f027b348a8e3089e6a92c3d40de0949", "max_forks_repo_licenses": ["PostgreSQL"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-04T02:28:18.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-29T01:18:46.000Z", "avg_line_length": 35.5083333333, "max_line_length": 98, "alphanum_fraction": 0.6196198076, "num_tokens": 5887, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21838594723196023}}
{"text": "/*\n *            Copyright 2009-2018 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n\n\n#include <votca/xtp/numerical_integrations.h>\n#include <boost/math/constants/constants.hpp>\n#include <votca/xtp/radial_euler_maclaurin_rule.h>\n#include <votca/xtp/sphere_lebedev_rule.h>\n#include <votca/xtp/aoshell.h>\n#include <votca/tools/constants.h>\n\n#include <votca/xtp/aomatrix.h>\n#include <fstream>\n#include <boost/algorithm/string.hpp>\n#include <cmath>\n#include <iterator>\n#include <string>\n\n\nnamespace votca {\n    namespace xtp {\n\n    NumericalIntegration::~NumericalIntegration(){\n      if (_setXC) {\n        xc_func_end(&xfunc);\n        if (_use_separate) {\n          xc_func_end(&cfunc);\n        }\n      }\n    }\n\n    \n\n    double NumericalIntegration::getExactExchange(const std::string& functional) {      \n\n      double exactexchange = 0.0;\n      Vxc_Functionals map;\n      std::vector<std::string> strs;\n\n      boost::split(strs, functional, boost::is_any_of(\" \"));\n      if (strs.size() > 2) {\n        throw std::runtime_error(\"Too many functional names\");\n      } else if (strs.size() < 1) {\n        throw std::runtime_error(\"Specify at least one functional\");\n      }\n\n      for (unsigned i = 0; i < strs.size(); i++) {\n\n        int func_id = map.getID(strs[i]);\n        if (func_id < 0) {\n          exactexchange = 0.0;\n          break;\n        }\n        xc_func_type func;\n        if (xc_func_init(&func, func_id, XC_UNPOLARIZED) != 0) {\n         throw std::runtime_error((boost::format(\"Functional %s not found\\n\") %strs[i]).str());\n        }\n        if (exactexchange > 0 && func.cam_alpha > 0) {\n          throw std::runtime_error(\"You have specified two functionals with exact exchange\");\n        }\n        exactexchange += func.cam_alpha;\n        xc_func_end(&func);\n      }\n      \n      return exactexchange;\n\n    }\n    \n    \n   void NumericalIntegration::setXCfunctional(const std::string& functional) {\n\n      Vxc_Functionals map;\n      std::vector<std::string> strs;\n      tools::Tokenizer tok(functional,\" ,\\n\\t\");\n      tok.ToVector(strs);\n      xfunc_id = 0;\n      _use_separate = false;\n      cfunc_id = 0;\n      if (strs.size() == 1) {\n        xfunc_id = map.getID(strs[0]);\n      } else if (strs.size() == 2) {\n        xfunc_id = map.getID(strs[0]);\n        cfunc_id = map.getID(strs[1]);\n        _use_separate = true;\n      } else {\n        std::cout << \"LIBXC \" << strs.size() << std::endl;\n        throw std::runtime_error(\"LIBXC. Please specify one combined or an exchange and a correlation functionals\");\n      }\n\n      if (xc_func_init(&xfunc, xfunc_id, XC_UNPOLARIZED) != 0) {\n        throw std::runtime_error((boost::format(\"Functional %s not found\\n\") %strs[0]).str());\n      }\n      if (xfunc.info->kind != 2 && !_use_separate) {\n        throw std::runtime_error(\"Your functional misses either correlation or exchange, please specify another functional, separated by whitespace\");\n      }\n      if (_use_separate) {\n        if (xc_func_init(&cfunc, cfunc_id, XC_UNPOLARIZED) != 0) {\n          throw std::runtime_error((boost::format(\"Functional %s not found\\n\") %strs[1]).str());\n        }\n        if ((xfunc.info->kind + cfunc.info->kind) != 1) {\n          throw std::runtime_error(\"Your functionals are not one exchange and one correlation\");\n        }\n      }\n      _setXC = true;\n      return;\n    }\n\n        \n        void NumericalIntegration::EvaluateXC(const double rho, const double sigma, double& f_xc, double& df_drho, double& df_dsigma) {\n\n        double exc[1];\n        double vsigma[1]; // libxc \n        double vrho[1]; // libxc df/drho\n        switch (xfunc.info->family) {\n          case XC_FAMILY_LDA:\n            xc_lda_exc_vxc(&xfunc, 1, &rho, exc, vrho);\n            break;\n          case XC_FAMILY_GGA:\n          case XC_FAMILY_HYB_GGA:\n            xc_gga_exc_vxc(&xfunc, 1, &rho, &sigma, exc, vrho, vsigma);\n            break;\n        }\n        f_xc = exc[0];\n        df_drho = vrho[0];\n        df_dsigma = vsigma[0];\n        if (_use_separate) {\n          // via libxc correlation part only\n          switch (cfunc.info->family) {\n            case XC_FAMILY_LDA:\n              xc_lda_exc_vxc(&cfunc, 1, &rho, exc, vrho);\n              break;\n            case XC_FAMILY_GGA:\n            case XC_FAMILY_HYB_GGA:\n              xc_gga_exc_vxc(&cfunc, 1, &rho, &sigma, exc, vrho, vsigma);\n              break;\n          }\n\n          f_xc += exc[0];\n          df_drho += vrho[0];\n          df_dsigma += vsigma[0];\n        }\n  \n      return;\n    }\n        \n        \n    double NumericalIntegration::IntegratePotential(const tools::vec& rvector) {\n\n      double result = 0.0;\n      assert(_density_set && \"Density not calculated\");\n      for (unsigned i = 0; i < _grid_boxes.size(); i++) {\n        const std::vector<tools::vec>& points = _grid_boxes[i].getGridPoints();\n        const std::vector<double>& weights = _grid_boxes[i].getGridWeights();\n        const std::vector<double>& densities = _grid_boxes[i].getGridDensities();\n        for (unsigned j = 0; j < points.size(); j++) {\n          double dist = abs(points[j] - rvector);\n          result -= weights[j] * densities[j] / dist;\n        }\n      }\n      return result;\n    }\n               \n        \n        \n        \n  void NumericalIntegration::SortGridpointsintoBlocks(std::vector< std::vector< GridContainers::Cartesian_gridpoint > >& grid) {\n      const double boxsize = 1;//1 bohr\n\n      std::vector< std::vector< std::vector< std::vector< GridContainers::Cartesian_gridpoint* > > > > boxes;\n      tools::vec min = tools::vec(std::numeric_limits<double>::max());\n      tools::vec max = tools::vec(std::numeric_limits<double>::min());\n\n      for (unsigned i = 0; i < grid.size(); i++) {\n        for (unsigned j = 0; j < grid[i].size(); j++) {\n          const tools::vec& pos = grid[i][j].grid_pos;\n          if (pos.getX() > max.getX()) {\n            max.x() = pos.getX();\n          } else if (pos.getX() < min.getX()) {\n            min.x() = pos.getX();\n          }\n          if (pos.getY() > max.getY()) {\n            max.y() = pos.getY();\n          } else if (pos.getY() < min.getY()) {\n            min.y() = pos.getY();\n          }\n          if (pos.getZ() > max.getZ()) {\n            max.z() = pos.getZ();\n          } else if (pos.getZ() < min.getZ()) {\n            min.z() = pos.getZ();\n          }\n        }\n      }\n\n      tools::vec molextension = (max - min);\n      tools::vec numberofboxes = molextension / boxsize;\n      tools::vec roundednumofbox = tools::vec(std::ceil(numberofboxes.getX()), std::ceil(numberofboxes.getY()), std::ceil(numberofboxes.getZ()));\n\n      //creating temparray\n      for (unsigned i = 0; i<unsigned(roundednumofbox.getX()); i++) {\n        std::vector< std::vector< std::vector< GridContainers::Cartesian_gridpoint* > > > boxes_yz;\n        for (unsigned j = 0; j<unsigned(roundednumofbox.getY()); j++) {\n          std::vector< std::vector< GridContainers::Cartesian_gridpoint* > > boxes_z;\n          for (unsigned k = 0; k<unsigned(roundednumofbox.getZ()); k++) {\n            std::vector< GridContainers::Cartesian_gridpoint* > box;\n            box.reserve(100);\n            boxes_z.push_back(box);\n          }\n          boxes_yz.push_back(boxes_z);\n        }\n        boxes.push_back(boxes_yz);\n      }\n\n      for (auto & atomgrid : grid) {\n        for (auto & gridpoint : atomgrid) {\n          tools::vec pos = gridpoint.grid_pos - min;\n          tools::vec index = pos / boxsize;\n          int i_x = int(index.getX());\n          int i_y = int(index.getY());\n          int i_z = int(index.getZ());\n          boxes[i_x][i_y][i_z].push_back(&gridpoint);\n        }\n      }\n\n      for (auto& boxes_xy : boxes) {\n        for (auto& boxes_z : boxes_xy) {\n          for (auto& box : boxes_z) {\n            if (box.size() < 1) {\n              continue;\n            }\n            GridBox gridbox;\n\n            for (const auto&point : box) {\n              gridbox.addGridPoint(*point);\n            }\n            _grid_boxes.push_back(gridbox);\n          }\n        }\n      }\n      return;\n    }\n        \n  void NumericalIntegration::FindSignificantShells(const AOBasis& basis) {\n      for (unsigned i = 0; i < _grid_boxes.size(); ++i) {\n        GridBox & box = _grid_boxes[i];\n        for (const AOShell* store:basis) {\n          const double decay = store->getMinDecay();\n          const tools::vec& shellpos =store->getPos();\n          for (const auto& point : box.getGridPoints()) {\n            tools::vec dist = shellpos - point;\n            double distsq = dist*dist;\n            // if contribution is smaller than -ln(1e-10), add shell to list\n            if ((decay * distsq) < 20.7) {\n              box.addShell(store);\n              break;\n            }\n          }\n        }\n      }\n\n      std::vector< GridBox > grid_boxes_copy;\n      int combined = 0;\n      //use vecot of bool to indicate if a gridbox has already been merged into another\n      std::vector<bool> Merged = std::vector<bool>(_grid_boxes.size(), false);\n      for (unsigned i = 0; i < _grid_boxes.size(); i++) {\n        if (Merged[i]) {\n          continue;\n        }\n        GridBox box = _grid_boxes[i];\n        if (box.Shellsize() < 1) {\n          continue;\n        }\n        Merged[i] = true;\n        for (unsigned j = i + 1; j < _grid_boxes.size(); j++) {\n          if (GridBox::compareGridboxes(_grid_boxes[i], _grid_boxes[j])) {\n            Merged[j] = true;\n            box.addGridBox(_grid_boxes[j]);\n            combined++;\n          }\n        }\n        grid_boxes_copy.push_back(box);\n      }\n      std::vector<unsigned> sizes;\n      sizes.reserve(grid_boxes_copy.size());\n      for (auto& box : grid_boxes_copy) {\n        sizes.push_back(box.size() * box.Matrixsize());\n      }\n      std::vector<unsigned> indexes = std::vector<unsigned>(sizes.size());\n      std::iota(indexes.begin(), indexes.end(), 0);\n      std::sort(indexes.begin(), indexes.end(), [&sizes](unsigned i1, unsigned i2) {\n        return sizes[i1] > sizes[i2];\n      });\n\n      unsigned nthreads = 1;\n#ifdef _OPENMP\n      nthreads = omp_get_max_threads();\n#endif\n      std::vector<unsigned> scores = std::vector<unsigned>(nthreads, 0);\n      std::vector< std::vector<unsigned> > indices;\n      for (unsigned i = 0; i < nthreads; ++i) {\n        std::vector<unsigned> thread_box_indices;\n        indices.push_back(thread_box_indices);\n      }\n      for (const auto index : indexes) {\n        unsigned thread = 0;\n        unsigned minimum = std::numeric_limits<unsigned>::max();\n        for (unsigned i = 0; i < scores.size(); ++i) {\n          if (scores[i] < minimum) {\n            minimum = scores[i];\n            thread = i;\n          }\n        }\n        indices[thread].push_back(index);\n        scores[thread] += sizes[index];\n      }\n      thread_start = std::vector<unsigned>(0);\n      thread_stop = std::vector<unsigned>(0);\n      unsigned start = 0;\n      unsigned stop = 0;\n      unsigned indexoffirstgridpoint = 0;\n      _grid_boxes.resize(0);\n      for (const std::vector<unsigned>& thread_index : indices) {\n        thread_start.push_back(start);\n        stop = start + thread_index.size();\n        thread_stop.push_back(stop);\n        start = stop;\n        for (const unsigned index : thread_index) {\n          GridBox newbox = grid_boxes_copy[index];\n          newbox.setIndexoffirstgridpoint(indexoffirstgridpoint);\n          indexoffirstgridpoint += newbox.size();\n          newbox.PrepareForIntegration();\n          _grid_boxes.push_back(newbox);\n        }\n      }\n      return;\n    }\n        \n        \n        \n  Eigen::MatrixXd NumericalIntegration::IntegrateVXC(const Eigen::MatrixXd& density_matrix) {\n      Eigen::MatrixXd Vxc = Eigen::MatrixXd::Zero(density_matrix.rows(), density_matrix.cols());\n      _EXC = 0;\n      unsigned nthreads = 1;\n#ifdef _OPENMP\n      nthreads = omp_get_max_threads();\n#endif\n      std::vector<Eigen::MatrixXd >vxc_thread;\n      std::vector<double> Exc_thread = std::vector<double>(nthreads, 0.0);\n      for (unsigned i = 0; i < nthreads; ++i) {\n        Eigen::MatrixXd Vxc_thread = Eigen::MatrixXd::Zero(density_matrix.rows(), density_matrix.cols());\n        vxc_thread.push_back(Vxc_thread);\n      }\n      \n#pragma omp parallel for\n      for (unsigned thread = 0; thread < nthreads; ++thread) {\n        for (unsigned i = thread_start[thread]; i < thread_stop[thread]; ++i) {\n\n          double EXC_box = 0.0;\n          const GridBox& box = _grid_boxes[i];\n          const Eigen::MatrixXd DMAT_here = box.ReadFromBigMatrix(density_matrix);\n          const Eigen::MatrixXd DMAT_symm= DMAT_here+DMAT_here.transpose();\n          double cutoff=1.e-40/density_matrix.rows()/density_matrix.rows();\n          if (DMAT_here.cwiseAbs2().maxCoeff()<cutoff ){\n            continue;\n          }     \n          Eigen::MatrixXd Vxc_here = Eigen::MatrixXd::Zero(DMAT_here.rows(), DMAT_here.cols());\n          const std::vector<tools::vec>& points = box.getGridPoints();\n          const std::vector<double>& weights = box.getGridWeights();\n          const std::vector<GridboxRange>& aoranges = box.getAOranges();\n          const std::vector<const AOShell* >& shells = box.getShells();\n          \n          //iterate over gridpoints\n          for (unsigned p = 0; p < box.size(); p++) {\n            Eigen::VectorXd ao = Eigen::VectorXd::Zero(box.Matrixsize());\n            Eigen::MatrixX3d ao_grad= Eigen::MatrixX3d::Zero(box.Matrixsize(),3);\n            for (unsigned j = 0; j < box.Shellsize(); ++j) {\n              Eigen::Block<Eigen::MatrixX3d> grad_block=ao_grad.block(aoranges[j].start,0,aoranges[j].size,3);\n              Eigen::VectorBlock<Eigen::VectorXd> ao_block=ao.segment(aoranges[j].start,aoranges[j].size);\n              shells[j]->EvalAOspace(ao_block,grad_block,points[p]);             \n            }\n            const double rho =0.5* (ao.transpose()*DMAT_symm*ao).value();\n            const double weight = weights[p];\n            if (rho*weight < 1.e-20) continue; // skip the rest, if density is very small\n            const Eigen::Vector3d rho_grad = ao.transpose()*DMAT_symm*ao_grad;\n            const double sigma = (rho_grad.transpose()*rho_grad).value();\n            const Eigen::VectorXd grad =ao_grad*rho_grad;\n            double f_xc; // E_xc[n] = int{n(r)*eps_xc[n(r)] d3r} = int{ f_xc(r) d3r }\n            double df_drho; // v_xc_rho(r) = df/drho\n            double df_dsigma; // df/dsigma ( df/dgrad(rho) = df/dsigma * dsigma/dgrad(rho) = df/dsigma * 2*grad(rho))\n            EvaluateXC(rho, sigma, f_xc, df_drho, df_dsigma); \n            EXC_box += weight * rho * f_xc;\n            auto addXC = weight * (0.5*df_drho * ao+ 2.0 * df_dsigma *grad);\n            // Exchange correlation energy\n            Vxc_here.noalias() += addXC* ao.transpose();\n          }\n          box.AddtoBigMatrix(vxc_thread[thread], Vxc_here);\n          Exc_thread[thread] += EXC_box;\n        }\n      }\n      for (unsigned i = 0; i < nthreads; ++i) {\n        Vxc += vxc_thread[i];\n        _EXC += Exc_thread[i];\n      }    \n      return Vxc+Vxc.transpose();\n    }\n  \n  \n   Eigen::MatrixXd NumericalIntegration::IntegrateExternalPotential(const std::vector<double>& Potentialvalues) {\n\n      Eigen::MatrixXd ExternalMat = Eigen::MatrixXd::Zero(_AOBasisSize, _AOBasisSize);\n      unsigned nthreads = 1;\n#ifdef _OPENMP\n      nthreads = omp_get_max_threads();\n#endif\n      std::vector<Eigen::MatrixXd >vex_thread;\n      std::vector<double> Exc_thread = std::vector<double>(nthreads, 0.0);\n      for (unsigned i = 0; i < nthreads; ++i) {\n        Eigen::MatrixXd Vex_thread = Eigen::MatrixXd::Zero(ExternalMat.rows(), ExternalMat.cols());\n        vex_thread.push_back(Vex_thread);\n      }\n\n#pragma omp parallel for\n      for (unsigned thread = 0; thread < nthreads; ++thread) {\n        for (unsigned i = thread_start[thread]; i < thread_stop[thread]; ++i) {\n\n          const GridBox& box = _grid_boxes[i];\n          Eigen::MatrixXd Vex_here = Eigen::MatrixXd::Zero(box.Matrixsize(), box.Matrixsize());\n          const std::vector<tools::vec>& points = box.getGridPoints();\n          const std::vector<double>& weights = box.getGridWeights();\n\n          //iterate over gridpoints\n          for (unsigned p = 0; p < box.size(); p++) {\n            Eigen::VectorXd ao = Eigen::VectorXd::Zero(box.Matrixsize());\n            const std::vector<GridboxRange>& aoranges = box.getAOranges();\n            const std::vector<const AOShell* > shells = box.getShells();\n            for (unsigned j = 0; j < box.Shellsize(); ++j) {\n              Eigen::VectorBlock<Eigen::VectorXd> ao_block=ao.segment(aoranges[j].start,aoranges[j].size);\n              shells[j]->EvalAOspace(ao_block, points[p]);\n            }\n            Eigen::VectorXd addEX = weights[p] * Potentialvalues[box.getIndexoffirstgridpoint() + p] * ao;\n            Vex_here += addEX.transpose() * ao;\n          }\n          box.AddtoBigMatrix(vex_thread[thread], Vex_here);\n        }\n      }\n      for (unsigned i = 0; i < nthreads; ++i) {\n        ExternalMat += vex_thread[i];\n      }\n      ExternalMat += ExternalMat.transpose();\n      return ExternalMat;\n    }\n      \n  double NumericalIntegration::IntegrateDensity(const Eigen::MatrixXd& density_matrix) {\n      double N = 0;\n      unsigned nthreads = 1;\n#ifdef _OPENMP\n      nthreads = omp_get_max_threads();\n#endif\n      std::vector<double> N_thread = std::vector<double>(nthreads, 0.0);\n\n#pragma omp parallel for\n      for (unsigned thread = 0; thread < nthreads; ++thread) {\n        for (unsigned i = thread_start[thread]; i < thread_stop[thread]; ++i) {\n\n          double N_box = 0.0;\n          GridBox& box = _grid_boxes[i];\n          const Eigen::MatrixXd DMAT_here = box.ReadFromBigMatrix(density_matrix);\n          const std::vector<tools::vec>& points = box.getGridPoints();\n          const std::vector<double>& weights = box.getGridWeights();\n          box.prepareDensity();\n          //iterate over gridpoints\n          for (unsigned p = 0; p < box.size(); p++) {\n            Eigen::VectorXd ao = Eigen::VectorXd::Zero(box.Matrixsize());\n            const std::vector<GridboxRange>& aoranges = box.getAOranges();\n            const std::vector<const AOShell* > shells = box.getShells();\n            for (unsigned j = 0; j < box.Shellsize(); ++j) {\n              Eigen::VectorBlock<Eigen::VectorXd> ao_block=ao.segment(aoranges[j].start,aoranges[j].size);\n              shells[j]->EvalAOspace(ao_block, points[p]);\n            }\n            double rho =(ao.transpose()*DMAT_here*ao)(0, 0);\n            box.addDensity(rho);\n            N_box += rho * weights[p];\n          }\n          N_thread[thread] += N_box;\n        }\n      }\n      for (unsigned i = 0; i < nthreads; ++i) {\n        N += N_thread[i];\n      }\n      _density_set = true;\n      return N;\n    }\n        \n      Gyrationtensor NumericalIntegration::IntegrateGyrationTensor(const Eigen::MatrixXd& density_matrix) {\n      double N = 0;\n      tools::vec centroid = tools::vec(0.0);\n      tools::matrix gyration = tools::matrix(0.0);\n      unsigned nthreads = 1;\n#ifdef _OPENMP\n      nthreads = omp_get_max_threads();\n#endif\n      std::vector<double> N_thread = std::vector<double>(nthreads, 0.0);\n      // centroid\n      std::vector<tools::vec> centroid_thread;\n      std::vector<tools::matrix> gyration_thread;\n      for (unsigned thread = 0; thread < nthreads; ++thread) {\n        tools::vec tempvec = tools::vec(0.0);\n        centroid_thread.push_back(tempvec);\n        tools::matrix tempmatrix = tools::matrix(0.0);\n        gyration_thread.push_back(tempmatrix);\n      }\n\n#pragma omp parallel for\n      for (unsigned thread = 0; thread < nthreads; ++thread) {\n        for (unsigned i = thread_start[thread]; i < thread_stop[thread]; ++i) {\n          double N_box = 0.0;\n          tools::vec centroid_box = tools::vec(0.0);\n          tools::matrix gyration_box = tools::matrix(0.0);\n          GridBox& box = _grid_boxes[i];\n          const Eigen::MatrixXd DMAT_here = box.ReadFromBigMatrix(density_matrix);\n          const std::vector<tools::vec>& points = box.getGridPoints();\n          const std::vector<double>& weights = box.getGridWeights();\n          box.prepareDensity();\n          //iterate over gridpoints\n          for (unsigned p = 0; p < box.size(); p++) {\n            Eigen::VectorXd ao = Eigen::VectorXd::Zero(box.Matrixsize());\n            const std::vector<GridboxRange>& aoranges = box.getAOranges();\n            const std::vector<const AOShell* > shells = box.getShells();\n            for (unsigned j = 0; j < box.Shellsize(); ++j) {\n              Eigen::VectorBlock<Eigen::VectorXd> ao_block=ao.segment(aoranges[j].start,aoranges[j].size);\n              shells[j]->EvalAOspace(ao_block, points[p]);\n            }\n            double rho =(ao.transpose()*DMAT_here*ao)(0, 0);\n            box.addDensity(rho);\n            N_box += rho * weights[p];\n            centroid_box+=rho * weights[p] * points[p];\n            gyration_box += rho * weights[p] * (points[p]|points[p]); \n          }\n          N_thread[thread] += N_box;\n          centroid_thread[thread] += centroid_box;\n          gyration_thread[thread] += gyration_box;\n        }\n      }\n      for (unsigned i = 0; i < nthreads; ++i) {\n        N += N_thread[i];\n        centroid += centroid_thread[i];\n        gyration += gyration_thread[i];\n      }\n      _density_set = true;\n      // Normalize\n      centroid = centroid / N;\n      gyration = gyration / N;\n      gyration=gyration-(centroid|centroid);\n      Gyrationtensor gyro;\n      gyro.mass=N;\n      gyro.centroid=centroid;\n      gyro.gyration=gyration;\n      \n      return gyro;\n    }\n\n        \nstd::vector<const tools::vec *> NumericalIntegration::getGridpoints() const{\n    std::vector<const tools::vec *> gridpoints;\n    for (unsigned i = 0; i < _grid_boxes.size(); i++) {\n      const std::vector<tools::vec>& points = _grid_boxes[i].getGridPoints();\n      for (unsigned j = 0; j < points.size(); j++) {\n        gridpoints.push_back(&points[j]);\n      }\n    }\n    return gridpoints;\n  }\n\n\nEigen::MatrixXd NumericalIntegration::IntegratePotential(const AOBasis& externalbasis){\n  Eigen::MatrixXd Potential=Eigen::MatrixXd::Zero(externalbasis.AOBasisSize(),externalbasis.AOBasisSize());\n  \n  assert(_density_set && \"Density not calculated\");\n  for (unsigned i = 0; i < _grid_boxes.size(); i++) {\n    const std::vector<tools::vec>& points = _grid_boxes[i].getGridPoints();\n    const std::vector<double>& weights = _grid_boxes[i].getGridWeights();\n    const std::vector<double>& densities = _grid_boxes[i].getGridDensities();\n    for (unsigned j = 0; j < points.size(); j++) {\n      double weighteddensity=weights[j]*densities[j];\n      if (weighteddensity<1e-12){\n        continue;\n      }\n      AOESP esp;\n      esp.setPosition(points[j]);\n      esp.Fill(externalbasis);\n      Potential+=weighteddensity*esp.Matrix();\n    }\n  }\n  return Potential; \n}\n        \n\nEigen::MatrixXd NumericalIntegration::CalcInverseAtomDist(std::vector<QMAtom*>& atoms){\n  Eigen::MatrixXd result=Eigen::MatrixXd::Zero(atoms.size(),atoms.size());\n#pragma omp parallel for\n  for (unsigned i=0;i<atoms.size();++i) {\n    QMAtom* atom_a=atoms[i];\n    const tools::vec& pos_a = atom_a->getPos();\n   for (unsigned j=0;j<i;++j) {\n      QMAtom* atom_b=atoms[j];\n      const tools::vec& pos_b = atom_b->getPos();\n      result(j,i)=1/tools::abs(pos_a-pos_b);\n    } \n  }\n  return result+result.transpose();\n}\n\nint NumericalIntegration::UpdateOrder(LebedevGrid& sphericalgridofElement, int maxorder, std::vector<double>& PruningIntervals, double r){\n  int order;\n  int maxindex=sphericalgridofElement.getIndexFromOrder(maxorder);\n  if (maxindex == 1) {\n    // smallest possible grid anyway, nothing to do\n    order = maxorder;\n  } else if (maxindex == 2) {\n    // only three intervals\n    if (r < PruningIntervals[0]) {\n      order = sphericalgridofElement.getOrderFromIndex(1); //1;\n    } else if ((r >= PruningIntervals[0]) && (r < PruningIntervals[3])) {\n      order = sphericalgridofElement.getOrderFromIndex(2);\n    } else {\n      order = sphericalgridofElement.getOrderFromIndex(1);\n    } // maxorder == 2\n  } else {\n    // five intervals\n    if (r < PruningIntervals[0]) {\n      order = sphericalgridofElement.getOrderFromIndex(2);\n    } else if ((r >= PruningIntervals[0]) && (r < PruningIntervals[1])) {\n      order = sphericalgridofElement.getOrderFromIndex(4);\n    } else if ((r >= PruningIntervals[1]) && (r < PruningIntervals[2])) {\n      order = sphericalgridofElement.getOrderFromIndex(std::max(maxindex - 1, 4));\n    } else if ((r >= PruningIntervals[2]) && (r < PruningIntervals[3])) {\n      order = maxorder;\n    } else {\n      order = sphericalgridofElement.getOrderFromIndex(std::max(maxindex - 1, 1));\n    }\n  }\n  return order;\n    }\n\n    GridContainers::Cartesian_gridpoint NumericalIntegration::CreateCartesianGridpoint(const tools::vec& atomA_pos,\n            GridContainers::radial_grid& radial_grid, GridContainers::spherical_grid& spherical_grid,\n            unsigned i_rad, unsigned i_sph) {\n      GridContainers::Cartesian_gridpoint gridpoint;\n      double p = spherical_grid.phi[i_sph];\n      double t = spherical_grid.theta[i_sph];\n      const tools::vec s = tools::vec(sin(p) * cos(t), sin(p) * sin(t), cos(p));\n      double r = radial_grid.radius[i_rad];\n      gridpoint.grid_pos = atomA_pos + r*s;\n      gridpoint.grid_weight = radial_grid.weight[i_rad] * spherical_grid.weight[i_sph];\n      return gridpoint;\n    }\n\n    Eigen::MatrixXd NumericalIntegration::CalcDistanceAtomsGridpoints(std::vector<QMAtom*>& atoms, std::vector<GridContainers::Cartesian_gridpoint>& atomgrid){\n      Eigen::MatrixXd result=Eigen::MatrixXd::Zero(atoms.size(),atomgrid.size());\n     #pragma omp parallel for\n      for (unsigned i=0;i<atoms.size();++i) {\n        QMAtom* atom=atoms[i];\n        const tools::vec & atom_pos =atom->getPos();\n        for (unsigned j=0;j<atomgrid.size();++j) {\n          const auto& gridpoint=atomgrid[j];\n          result(i,j)=tools::abs(atom_pos-gridpoint.grid_pos);\n        } \n      }\n      return result;\n    }\n\n    void NumericalIntegration::SSWpartitionAtom(std::vector<QMAtom*>& atoms, std::vector<GridContainers::Cartesian_gridpoint>& atomgrid\n                                                , unsigned i_atom, const Eigen::MatrixXd& Rij){\n      Eigen::MatrixXd AtomGridDist=CalcDistanceAtomsGridpoints(atoms, atomgrid);\n      \n#pragma omp parallel for schedule(guided)\n      for (unsigned i_grid = 0; i_grid < atomgrid.size(); i_grid++) {\n        Eigen::VectorXd p = SSWpartition(i_grid, AtomGridDist,Rij);\n        // check weight sum\n        double wsum = p.sum();\n        if (wsum != 0.0) {\n          // update the weight of this grid point\n          atomgrid[i_grid].grid_weight *= p[i_atom] / wsum;\n        } else {\n          std::cerr << \"\\nSum of partition weights of grid point \" << i_grid << \" of atom \" << i_atom << \" is zero! \";\n          throw std::runtime_error(\"\\nThis should never happen!\");\n        }\n      } // partition weight for each gridpoint\n    }\n        \nvoid NumericalIntegration::GridSetup(const std::string& type, std::vector<QMAtom*> atoms,const AOBasis& basis) {\n      _AOBasisSize=basis.AOBasisSize();\n      GridContainers initialgrids;\n      // get radial grid per element\n      EulerMaclaurinGrid radialgridofElement;\n      initialgrids.radial_grids=radialgridofElement.CalculateAtomicRadialGrids(basis, atoms, type); // this checks out 1:1 with NWChem results! AWESOME\n      LebedevGrid sphericalgridofElement;\n      initialgrids.spherical_grids=sphericalgridofElement.CalculateSphericalGrids(atoms,type);\n      \n      // for the partitioning, we need all inter-center distances later, stored in matrix\n      Eigen::MatrixXd Rij=CalcInverseAtomDist(atoms);\n      _totalgridsize = 0;\n      std::vector< std::vector< GridContainers::Cartesian_gridpoint > > grid;\n      \n      for (unsigned i_atom=0;i_atom<atoms.size();++i_atom) {\n        QMAtom* atom=atoms[i_atom];\n\n        const tools::vec & atomA_pos =atom->getPos();\n        const std::string & name = atom->getType();\n        GridContainers::radial_grid radial_grid = initialgrids.radial_grids.at(name);\n        GridContainers::spherical_grid spherical_grid = initialgrids.spherical_grids.at(name);\n                \n        // maximum order (= number of points) in spherical integration grid\n        int maxorder = sphericalgridofElement.Type2MaxOrder(name, type);\n        // for pruning of integration grid, get interval boundaries for this element\n        std::vector<double> PruningIntervals = radialgridofElement.CalculatePruningIntervals(name);\n        int current_order = 0;\n        // for each radial value\n        std::vector< GridContainers::Cartesian_gridpoint > atomgrid;\n        for (unsigned i_rad = 0; i_rad < radial_grid.radius.size(); i_rad++) {\n          double r = radial_grid.radius[i_rad];\n\n          // which Lebedev order for this point?\n          int order=UpdateOrder(sphericalgridofElement, maxorder, PruningIntervals, r);\n          // get new spherical grid, if order changed\n          if (order != current_order) {\n            spherical_grid=sphericalgridofElement.CalculateUnitSphereGrid(order);\n            current_order = order;\n          }\n\n          for (unsigned i_sph = 0; i_sph < spherical_grid.phi.size(); i_sph++) {\n            GridContainers::Cartesian_gridpoint gridpoint=CreateCartesianGridpoint(atomA_pos, radial_grid, spherical_grid, i_rad,i_sph);\n            atomgrid.push_back(gridpoint);\n          } // spherical gridpoints\n        } // radial gridpoint\n\n        SSWpartitionAtom(atoms, atomgrid, i_atom,Rij);\n\n        // now remove points from the grid with negligible weights\n        for (std::vector<GridContainers::Cartesian_gridpoint >::iterator git = atomgrid.begin(); git != atomgrid.end();) {\n          if (git->grid_weight < 1e-13) {\n            git = atomgrid.erase(git);\n          } else {\n            ++git;\n          }\n        }\n        _totalgridsize += atomgrid.size();\n        grid.push_back(atomgrid);\n      } // atoms\n      SortGridpointsintoBlocks(grid);\n      FindSignificantShells(basis);\n      return;\n    }\n\n    Eigen::VectorXd NumericalIntegration::SSWpartition(int igrid, const Eigen::MatrixXd & rq,const Eigen::MatrixXd& Rij) {\n      const double ass = 0.725;\n      // initialize partition vector to 1.0\n      Eigen::VectorXd p=Eigen::VectorXd::Ones(rq.rows());\n      const double tol_scr = 1e-10;\n      const double leps = 1e-6;\n      // go through centers\n      for (int i = 1; i < rq.rows(); i++) {\n        double rag = rq(i,igrid);\n        // through all other centers (one-directional)\n        for (int j = 0; j < i; j++) {\n          if ((std::abs(p[i]) > tol_scr) || (std::abs(p[j]) > tol_scr)) {\n            double mu = (rag - rq(j,igrid)) * Rij(j,i);\n            if (mu > ass) {\n              p[i] = 0.0;\n            } else if (mu < -ass) {\n              p[j] = 0.0;\n            } else {\n              double sk;\n              if (std::abs(mu) < leps) {\n                sk = -1.88603178008 * mu + 0.5;\n              } else {\n                sk =erf1c(mu);\n              }\n              if (mu > 0.0) sk = 1.0 - sk;\n              p[j] = p[j] * sk;\n              p[i] = p[i] * (1.0 - sk);\n            }\n          }\n        }\n      }\n      return p;\n    }\n\n    double NumericalIntegration::erf1c(double x){ \n        const static double alpha_erf1=1.0/0.30;\n        return 0.5*std::erfc(std::abs(x/(1.0-x*x))*alpha_erf1);              \n    }\n              \n   \n                                                                                                \n    }\n}\n", "meta": {"hexsha": "4e040104de64c664a75123814304638e252c2b86", "size": 32085, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/numerical_integration/numerical_integrations.cc", "max_stars_repo_name": "mbarbry/xtp", "max_stars_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/numerical_integration/numerical_integrations.cc", "max_issues_repo_name": "mbarbry/xtp", "max_issues_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/numerical_integration/numerical_integrations.cc", "max_forks_repo_name": "mbarbry/xtp", "max_forks_repo_head_hexsha": "e79828209d11ec25bf1750ab75499ecf50f584ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4164619165, "max_line_length": 159, "alphanum_fraction": 0.5887174692, "num_tokens": 8212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.21815583785047435}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017, 2018.\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 5.0.0\n\n// Original copyright notice:\n\n// This code was entirely written by Nathan Wagner\n// and is in the public domain.\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_ISEA_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_ISEA_HPP\n\n#include <sstream>\n\n#include <boost/core/ignore_unused.hpp>\n#include <boost/geometry/util/math.hpp>\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace isea\n    {\n            static const double epsilon = std::numeric_limits<double>::epsilon();\n\n            /* sqrt(5)/M_PI */\n            static const double isea_scale = 0.8301572857837594396028083;\n            /* 26.565051177 degrees */\n            static const double v_lat = 0.46364760899944494524;\n            /* 52.62263186 */\n            static const double e_rad = 0.91843818702186776133;\n            /* 10.81231696 */\n            static const double f_rad = 0.18871053072122403508;\n            /* R tan(g) sin(60) */\n            static const double table_g = 0.6615845383;\n            /* H = 0.25 R tan g = */\n            static const double table_h = 0.1909830056;\n            //static const double RPRIME = 0.91038328153090290025;\n            static const double isea_std_lat = 1.01722196792335072101;\n            static const double isea_std_lon = .19634954084936207740;\n\n            template <typename T>\n            inline T deg30_rad() { return T(30) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T deg120_rad() { return T(120) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T deg72_rad() { return T(72) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T deg90_rad() { return geometry::math::half_pi<T>(); }\n            template <typename T>\n            inline T deg144_rad() { return T(144) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T deg36_rad() { return T(36) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T deg108_rad() { return T(108) * geometry::math::d2r<T>(); }\n            template <typename T>\n            inline T deg180_rad() { return geometry::math::pi<T>(); }\n\n            inline bool downtri(int tri) { return (((tri - 1) / 5) % 2 == 1); }\n\n            /*\n             * Proj 4 provides its own entry points into\n             * the code, so none of the library functions\n             * need to be global\n             */\n\n            struct hex {\n                    int iso;\n                    int x, y, z;\n            };\n\n            /* y *must* be positive down as the xy /iso conversion assumes this */\n            inline\n            int hex_xy(struct hex *h) {\n                if (!h->iso) return 1;\n                if (h->x >= 0) {\n                    h->y = -h->y - (h->x+1)/2;\n                } else {\n                    /* need to round toward -inf, not toward zero, so x-1 */\n                    h->y = -h->y - h->x/2;\n                }\n                h->iso = 0;\n\n                return 1;\n            }\n\n            inline\n            int hex_iso(struct hex *h) {\n                if (h->iso) return 1;\n\n                if (h->x >= 0) {\n                    h->y = (-h->y - (h->x+1)/2);\n                } else {\n                    /* need to round toward -inf, not toward zero, so x-1 */\n                    h->y = (-h->y - (h->x)/2);\n                }\n\n                h->z = -h->x - h->y;\n                h->iso = 1;\n                return 1;\n            }\n\n            template <typename T>\n            inline\n            int hexbin2(T const& width, T x, T y, int *i, int *j)\n            {\n                T z, rx, ry, rz;\n                T abs_dx, abs_dy, abs_dz;\n                int ix, iy, iz, s;\n                struct hex h;\n\n                static const T cos_deg30 = cos(deg30_rad<T>());\n\n                x = x / cos_deg30; /* rotated X coord */\n                y = y - x / 2.0; /* adjustment for rotated X */\n\n                /* adjust for actual hexwidth */\n                x /= width;\n                y /= width;\n\n                z = -x - y;\n\n                rx = floor(x + 0.5);\n                ix = (int)rx;\n                ry = floor(y + 0.5);\n                iy = (int)ry;\n                rz = floor(z + 0.5);\n                iz = (int)rz;\n\n                s = ix + iy + iz;\n\n                if (s) {\n                    abs_dx = fabs(rx - x);\n                    abs_dy = fabs(ry - y);\n                    abs_dz = fabs(rz - z);\n\n                    if (abs_dx >= abs_dy && abs_dx >= abs_dz) {\n                        ix -= s;\n                    } else if (abs_dy >= abs_dx && abs_dy >= abs_dz) {\n                        iy -= s;\n                    } else {\n                        iz -= s;\n                    }\n                }\n                h.x = ix;\n                h.y = iy;\n                h.z = iz;\n                h.iso = 1;\n\n                hex_xy(&h);\n                *i = h.x;\n                *j = h.y;\n                return ix * 100 + iy;\n            }\n\n            //enum isea_poly { isea_none = 0, isea_icosahedron = 20 };\n            //enum isea_topology { isea_hexagon=6, isea_triangle=3, isea_diamond=4 };\n            enum isea_address_form {\n                isea_addr_geo, isea_addr_q2di, isea_addr_seqnum,\n                isea_addr_interleave, isea_addr_plane, isea_addr_q2dd,\n                isea_addr_projtri, isea_addr_vertex2dd, isea_addr_hex\n            };\n\n            template <typename T>\n            struct isea_dgg {\n                //isea_poly         polyhedron; /* ignored, icosahedron */\n                T                 o_lat, o_lon, o_az; /* orientation, radians */\n                int               pole; /* true if standard snyder */\n                //isea_topology     topology; /* ignored, hexagon */\n                int               aperture; /* valid values depend on partitioning method */\n                int               resolution;\n                T                 radius; /* radius of the earth in meters, ignored 1.0 */\n                isea_address_form output; /* an isea_address_form */\n                int               triangle; /* triangle of last transformed point */\n                int               quad; /* quad of last transformed point */\n                unsigned long     serial;\n            };\n\n            template <typename T>\n            struct isea_pt {\n                T x, y;\n            };\n\n            template <typename T>\n            struct isea_geo {\n                T lon, lat;\n            };\n\n            template <typename T>\n            struct isea_address {\n                int    type; /* enum isea_address_form */\n                int    number;\n                T      x,y; /* or i,j or lon,lat depending on type */\n            };\n\n            /* ENDINC */\n\n            enum snyder_polyhedron {\n                snyder_poly_hexagon = 0, snyder_poly_pentagon = 1,\n                snyder_poly_tetrahedron = 2, snyder_poly_cube = 3,\n                snyder_poly_octahedron = 4, snyder_poly_dodecahedron = 5,\n                snyder_poly_icosahedron = 6\n            };\n\n            template <typename T>\n            struct snyder_constants {\n                T          g, G, theta, ea_w, ea_a, ea_b, g_w, g_a, g_b;\n            };\n\n            template <typename T>\n            inline const snyder_constants<T> * constants()\n            {\n                /* TODO put these in radians to avoid a later conversion */\n                static snyder_constants<T> result[] = {\n                    {23.80018260, 62.15458023, 60.0, 3.75, 1.033, 0.968, 5.09, 1.195, 1.0},\n                    {20.07675127, 55.69063953, 54.0, 2.65, 1.030, 0.983, 3.59, 1.141, 1.027},\n                    {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},\n                    {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},\n                    {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},\n                    {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},\n                    {37.37736814, 36.0, 30.0, 17.27, 1.163, 0.860, 13.14, 1.584, 1.0}\n                };\n                return result;\n            }\n            \n            template <typename T>\n            inline const isea_geo<T> * vertex()\n            {\n                static isea_geo<T> result[] = {\n                    { 0.0,              deg90_rad<T>()},\n                    { deg180_rad<T>(),  v_lat},\n                    {-deg108_rad<T>(),  v_lat},\n                    {-deg36_rad<T>(),   v_lat},\n                    { deg36_rad<T>(),   v_lat},\n                    { deg108_rad<T>(),  v_lat},\n                    {-deg144_rad<T>(), -v_lat},\n                    {-deg72_rad<T>(),  -v_lat},\n                    { 0.0,             -v_lat},\n                    { deg72_rad<T>(),  -v_lat},\n                    { deg144_rad<T>(), -v_lat},\n                    { 0.0,             -deg90_rad<T>()}\n                };\n                return result;\n            }\n\n            /* TODO make an isea_pt array of the vertices as well */\n\n            static int      tri_v1[] = {0, 0, 0, 0, 0, 0, 6, 7, 8, 9, 10, 2, 3, 4, 5, 1, 11, 11, 11, 11, 11};\n\n            /* triangle Centers */\n            template <typename T>\n            inline const isea_geo<T> * icostriangles()\n            {\n                static isea_geo<T> result[] = {\n                    { 0.0,              0.0},\n                    {-deg144_rad<T>(),  e_rad},\n                    {-deg72_rad<T>(),   e_rad},\n                    { 0.0,              e_rad},\n                    { deg72_rad<T>(),   e_rad},\n                    { deg144_rad<T>(),  e_rad},\n                    {-deg144_rad<T>(),  f_rad},\n                    {-deg72_rad<T>(),   f_rad},\n                    { 0.0,              f_rad},\n                    { deg72_rad<T>(),   f_rad},\n                    { deg144_rad<T>(),  f_rad},\n                    {-deg108_rad<T>(), -f_rad},\n                    {-deg36_rad<T>(),  -f_rad},\n                    { deg36_rad<T>(),  -f_rad},\n                    { deg108_rad<T>(), -f_rad},\n                    { deg180_rad<T>(), -f_rad},\n                    {-deg108_rad<T>(), -e_rad},\n                    {-deg36_rad<T>(),  -e_rad},\n                    { deg36_rad<T>(),  -e_rad},\n                    { deg108_rad<T>(), -e_rad},\n                    { deg180_rad<T>(), -e_rad},\n                };\n                return result;\n            }\n\n            template <typename T>\n            inline T az_adjustment(int triangle)\n            {\n                T          adj;\n\n                isea_geo<T> v;\n                isea_geo<T> c;\n\n                v = vertex<T>()[tri_v1[triangle]];\n                c = icostriangles<T>()[triangle];\n\n                /* TODO looks like the adjustment is always either 0 or 180 */\n                /* at least if you pick your vertex carefully */\n                adj = atan2(cos(v.lat) * sin(v.lon - c.lon),\n                        cos(c.lat) * sin(v.lat)\n                        - sin(c.lat) * cos(v.lat) * cos(v.lon - c.lon));\n                return adj;\n            }\n\n            template <typename T>\n            inline isea_pt<T> isea_triangle_xy(int triangle)\n            {\n                isea_pt<T>  c;\n                T Rprime = 0.91038328153090290025;\n\n                triangle = (triangle - 1) % 20;\n\n                c.x = table_g * ((triangle % 5) - 2) * 2.0;\n                if (triangle > 9) {\n                    c.x += table_g;\n                }\n                switch (triangle / 5) {\n                case 0:\n                    c.y = 5.0 * table_h;\n                    break;\n                case 1:\n                    c.y = table_h;\n                    break;\n                case 2:\n                    c.y = -table_h;\n                    break;\n                case 3:\n                    c.y = -5.0 * table_h;\n                    break;\n                default:\n                    /* should be impossible */\n                    BOOST_THROW_EXCEPTION( projection_exception() );\n                };\n                c.x *= Rprime;\n                c.y *= Rprime;\n\n                return c;\n            }\n\n            /* snyder eq 14 */\n            template <typename T>\n            inline T sph_azimuth(T const& f_lon, T const& f_lat, T const& t_lon, T const& t_lat)\n            {\n                T          az;\n\n                az = atan2(cos(t_lat) * sin(t_lon - f_lon),\n                       cos(f_lat) * sin(t_lat)\n                       - sin(f_lat) * cos(t_lat) * cos(t_lon - f_lon)\n                    );\n                return az;\n            }\n\n            /* coord needs to be in radians */\n            template <typename T>\n            inline int isea_snyder_forward(isea_geo<T> * ll, isea_pt<T> * out)\n            {\n                static T const two_pi = detail::two_pi<T>();\n                static T const d2r = geometry::math::d2r<T>();\n\n                int             i;\n\n                /*\n                 * spherical distance from center of polygon face to any of its\n                 * vertexes on the globe\n                 */\n                T          g;\n\n                /*\n                 * spherical angle between radius vector to center and adjacent edge\n                 * of spherical polygon on the globe\n                 */\n                T          G;\n\n                /*\n                 * plane angle between radius vector to center and adjacent edge of\n                 * plane polygon\n                 */\n                T          theta;\n\n                /* additional variables from snyder */\n                T          q, Rprime, H, Ag, Azprime, Az, dprime, f, rho,\n                                x, y;\n\n                /* variables used to store intermediate results */\n                T          cot_theta, tan_g, az_offset;\n\n                /* how many multiples of 60 degrees we adjust the azimuth */\n                int             Az_adjust_multiples;\n\n                snyder_constants<T> c;\n\n                /*\n                 * TODO by locality of reference, start by trying the same triangle\n                 * as last time\n                 */\n\n                /* TODO put these constants in as radians to begin with */\n                c = constants<T>()[snyder_poly_icosahedron];\n                theta = c.theta * d2r;\n                g = c.g * d2r;\n                G = c.G * d2r;\n\n                for (i = 1; i <= 20; i++) {\n                    T          z;\n                    isea_geo<T> center;\n\n                    center = icostriangles<T>()[i];\n\n                    /* step 1 */\n                    z = acos(sin(center.lat) * sin(ll->lat)\n                         + cos(center.lat) * cos(ll->lat) * cos(ll->lon - center.lon));\n\n                    /* not on this triangle */\n                    if (z > g + 0.000005) { /* TODO DBL_EPSILON */\n                        continue;\n                    }\n\n                    Az = sph_azimuth(center.lon, center.lat, ll->lon, ll->lat);\n\n                    /* step 2 */\n\n                    /* This calculates \"some\" vertex coordinate */\n                    az_offset = az_adjustment<T>(i);\n\n                    Az -= az_offset;\n\n                    /* TODO I don't know why we do this.  It's not in snyder */\n                    /* maybe because we should have picked a better vertex */\n                    if (Az < 0.0) {\n                        Az += two_pi;\n                    }\n                    /*\n                     * adjust Az for the point to fall within the range of 0 to\n                     * 2(90 - theta) or 60 degrees for the hexagon, by\n                     * and therefore 120 degrees for the triangle\n                     * of the icosahedron\n                     * subtracting or adding multiples of 60 degrees to Az and\n                     * recording the amount of adjustment\n                     */\n\n                    Az_adjust_multiples = 0;\n                    while (Az < 0.0) {\n                        Az += deg120_rad<T>();\n                        Az_adjust_multiples--;\n                    }\n                    while (Az > deg120_rad<T>() + epsilon) {\n                        Az -= deg120_rad<T>();\n                        Az_adjust_multiples++;\n                    }\n\n                    /* step 3 */\n                    cot_theta = 1.0 / tan(theta);\n                    tan_g = tan(g);    /* TODO this is a constant */\n\n                    /* Calculate q from eq 9. */\n                    /* TODO cot_theta is cot(30) */\n                    q = atan2(tan_g, cos(Az) + sin(Az) * cot_theta);\n\n                    /* not in this triangle */\n                    if (z > q + 0.000005) {\n                        continue;\n                    }\n                    /* step 4 */\n\n                    /* Apply equations 5-8 and 10-12 in order */\n\n                    /* eq 5 */\n                    /* Rprime = 0.9449322893 * R; */\n                    /* R' in the paper is for the truncated */\n                    Rprime = 0.91038328153090290025;\n\n                    /* eq 6 */\n                    H = acos(sin(Az) * sin(G) * cos(g) - cos(Az) * cos(G));\n\n                    /* eq 7 */\n                    /* Ag = (Az + G + H - deg180_rad) * M_PI * R * R / deg180_rad; */\n                    Ag = Az + G + H - deg180_rad<T>();\n\n                    /* eq 8 */\n                    Azprime = atan2(2.0 * Ag, Rprime * Rprime * tan_g * tan_g - 2.0 * Ag * cot_theta);\n\n                    /* eq 10 */\n                    /* cot(theta) = 1.73205080756887729355 */\n                    dprime = Rprime * tan_g / (cos(Azprime) + sin(Azprime) * cot_theta);\n\n                    /* eq 11 */\n                    f = dprime / (2.0 * Rprime * sin(q / 2.0));\n\n                    /* eq 12 */\n                    rho = 2.0 * Rprime * f * sin(z / 2.0);\n\n                    /*\n                     * add back the same 60 degree multiple adjustment from step\n                     * 2 to Azprime\n                     */\n\n                    Azprime += deg120_rad<T>() * Az_adjust_multiples;\n\n                    /* calculate rectangular coordinates */\n\n                    x = rho * sin(Azprime);\n                    y = rho * cos(Azprime);\n\n                    /*\n                     * TODO\n                     * translate coordinates to the origin for the particular\n                     * hexagon on the flattened polyhedral map plot\n                     */\n\n                    out->x = x;\n                    out->y = y;\n\n                    return i;\n                }\n\n                /*\n                 * should be impossible, this implies that the coordinate is not on\n                 * any triangle\n                 */\n\n                //fprintf(stderr, \"impossible transform: %f %f is not on any triangle\\n\",\n                //    ll->lon * geometry::math::r2d<double>(), ll->lat * geometry::math::r2d<double>());\n                std::stringstream ss;\n                ss << \"impossible transform: \" << ll->lon * geometry::math::r2d<T>()\n                   << \" \" << ll->lat * geometry::math::r2d<T>() << \" is not on any triangle.\";\n\n                BOOST_THROW_EXCEPTION( projection_exception(ss.str()) );\n\n                /* not reached */\n                return 0;        /* supresses a warning */\n            }\n\n            /*\n             * return the new coordinates of any point in orginal coordinate system.\n             * Define a point (newNPold) in orginal coordinate system as the North Pole in\n             * new coordinate system, and the great circle connect the original and new\n             * North Pole as the lon0 longitude in new coordinate system, given any point\n             * in orginal coordinate system, this function return the new coordinates.\n             */\n\n\n            /* formula from Snyder, Map Projections: A working manual, p31 */\n            /*\n             * old north pole at np in new coordinates\n             * could be simplified a bit with fewer intermediates\n             *\n             * TODO take a result pointer\n             */\n            template <typename T>\n            inline isea_geo<T> snyder_ctran(isea_geo<T> * np, isea_geo<T> * pt)\n            {\n                static T const pi = detail::pi<T>();\n                static T const two_pi = detail::two_pi<T>();\n\n                isea_geo<T> npt;\n                T           alpha, phi, lambda, lambda0, beta, lambdap, phip;\n                T           sin_phip;\n                T           lp_b;    /* lambda prime minus beta */\n                T           cos_p, sin_a;\n\n                phi = pt->lat;\n                lambda = pt->lon;\n                alpha = np->lat;\n                beta = np->lon;\n                lambda0 = beta;\n\n                cos_p = cos(phi);\n                sin_a = sin(alpha);\n\n                /* mpawm 5-7 */\n                sin_phip = sin_a * sin(phi) - cos(alpha) * cos_p * cos(lambda - lambda0);\n\n                /* mpawm 5-8b */\n\n                /* use the two argument form so we end up in the right quadrant */\n                lp_b = atan2(cos_p * sin(lambda - lambda0),\n                   (sin_a * cos_p * cos(lambda - lambda0) + cos(alpha) * sin(phi)));\n\n                lambdap = lp_b + beta;\n\n                /* normalize longitude */\n                /* TODO can we just do a modulus ? */\n                lambdap = fmod(lambdap, two_pi);\n                while (lambdap > pi)\n                    lambdap -= two_pi;\n                while (lambdap < -pi)\n                    lambdap += two_pi;\n\n                phip = asin(sin_phip);\n\n                npt.lat = phip;\n                npt.lon = lambdap;\n\n                return npt;\n            }\n\n            template <typename T>\n            inline isea_geo<T> isea_ctran(isea_geo<T> * np, isea_geo<T> * pt, T const& lon0)\n            {\n                static T const pi = detail::pi<T>();\n                static T const two_pi = detail::two_pi<T>();\n\n                isea_geo<T> npt;\n\n                np->lon += pi;\n                npt = snyder_ctran(np, pt);\n                np->lon -= pi;\n\n                npt.lon -= (pi - lon0 + np->lon);\n\n                /*\n                 * snyder is down tri 3, isea is along side of tri1 from vertex 0 to\n                 * vertex 1 these are 180 degrees apart\n                 */\n                npt.lon += pi;\n                /* normalize longitude */\n                npt.lon = fmod(npt.lon, two_pi);\n                while (npt.lon > pi)\n                    npt.lon -= two_pi;\n                while (npt.lon < -pi)\n                    npt.lon += two_pi;\n\n                return npt;\n            }\n\n            /* in radians */\n\n            /* fuller's at 5.2454 west, 2.3009 N, adjacent at 7.46658 deg */\n\n            template <typename T>\n            inline int isea_grid_init(isea_dgg<T> * g)\n            {\n                if (!g)\n                    return 0;\n\n                //g->polyhedron = isea_icosahedron;\n                g->o_lat = isea_std_lat;\n                g->o_lon = isea_std_lon;\n                g->o_az = 0.0;\n                g->aperture = 4;\n                g->resolution = 6;\n                g->radius = 1.0;\n                //g->topology = isea_hexagon;\n\n                return 1;\n            }\n\n            template <typename T>\n            inline int isea_orient_isea(isea_dgg<T> * g)\n            {\n                if (!g)\n                    return 0;\n                g->o_lat = isea_std_lat;\n                g->o_lon = isea_std_lon;\n                g->o_az = 0.0;\n                return 1;\n            }\n\n            template <typename T>\n            inline int isea_orient_pole(isea_dgg<T> * g)\n            {\n                static T const half_pi = detail::half_pi<T>();\n\n                if (!g)\n                    return 0;\n                g->o_lat = half_pi;\n                g->o_lon = 0.0;\n                g->o_az = 0;\n                return 1;\n            }\n\n            template <typename T>\n            inline int isea_transform(isea_dgg<T> * g, isea_geo<T> * in,\n                                      isea_pt<T> * out)\n            {\n                isea_geo<T> i, pole;\n                int         tri;\n\n                pole.lat = g->o_lat;\n                pole.lon = g->o_lon;\n\n                i = isea_ctran(&pole, in, g->o_az);\n\n                tri = isea_snyder_forward(&i, out);\n                out->x *= g->radius;\n                out->y *= g->radius;\n                g->triangle = tri;\n\n                return tri;\n            }\n\n\n            template <typename T>\n            inline void isea_rotate(isea_pt<T> * pt, T const& degrees)\n            {\n                static T const d2r = geometry::math::d2r<T>();\n                static T const two_pi = detail::two_pi<T>();\n\n                T          rad;\n\n                T          x, y;\n\n                rad = -degrees * d2r;\n                while (rad >= two_pi) rad -= two_pi;\n                while (rad <= -two_pi) rad += two_pi;\n\n                x = pt->x * cos(rad) + pt->y * sin(rad);\n                y = -pt->x * sin(rad) + pt->y * cos(rad);\n\n                pt->x = x;\n                pt->y = y;\n            }\n\n            template <typename T>\n            inline int isea_tri_plane(int tri, isea_pt<T> *pt, T const& radius)\n            {\n                isea_pt<T> tc; /* center of triangle */\n\n                if (downtri(tri)) {\n                    isea_rotate(pt, 180.0);\n                }\n                tc = isea_triangle_xy<T>(tri);\n                tc.x *= radius;\n                tc.y *= radius;\n                pt->x += tc.x;\n                pt->y += tc.y;\n\n                return tri;\n            }\n\n            /* convert projected triangle coords to quad xy coords, return quad number */\n            template <typename T>\n            inline int isea_ptdd(int tri, isea_pt<T> *pt)\n            {\n                int             downtri, quad;\n\n                downtri = (((tri - 1) / 5) % 2 == 1);\n                quad = ((tri - 1) % 5) + ((tri - 1) / 10) * 5 + 1;\n\n                isea_rotate(pt, downtri ? 240.0 : 60.0);\n                if (downtri) {\n                    pt->x += 0.5;\n                    /* pt->y += cos(30.0 * M_PI / 180.0); */\n                    pt->y += .86602540378443864672;\n                }\n                return quad;\n            }\n\n            template <typename T>\n            inline int isea_dddi_ap3odd(isea_dgg<T> *g, int quad, isea_pt<T> *pt, isea_pt<T> *di)\n            {\n                static T const pi = detail::pi<T>();\n\n                isea_pt<T> v;\n                T          hexwidth;\n                T          sidelength;    /* in hexes */\n                int        d, i;\n                int        maxcoord;\n                hex        h;\n\n                /* This is the number of hexes from apex to base of a triangle */\n                sidelength = (math::pow(T(2), g->resolution) + T(1)) / T(2);\n\n                /* apex to base is cos(30deg) */\n                hexwidth = cos(pi / 6.0) / sidelength;\n\n                /* TODO I think sidelength is always x.5, so\n                 * (int)sidelength * 2 + 1 might be just as good\n                 */\n                maxcoord = (int) (sidelength * 2.0 + 0.5);\n\n                v = *pt;\n                hexbin2(hexwidth, v.x, v.y, &h.x, &h.y);\n                h.iso = 0;\n                hex_iso(&h);\n\n                d = h.x - h.z;\n                i = h.x + h.y + h.y;\n\n                /*\n                 * you want to test for max coords for the next quad in the same\n                 * \"row\" first to get the case where both are max\n                 */\n                if (quad <= 5) {\n                    if (d == 0 && i == maxcoord) {\n                        /* north pole */\n                        quad = 0;\n                        d = 0;\n                        i = 0;\n                    } else if (i == maxcoord) {\n                        /* upper right in next quad */\n                        quad += 1;\n                        if (quad == 6)\n                            quad = 1;\n                        i = maxcoord - d;\n                        d = 0;\n                    } else if (d == maxcoord) {\n                        /* lower right in quad to lower right */\n                        quad += 5;\n                        d = 0;\n                    }\n                } else if (quad >= 6) {\n                    if (i == 0 && d == maxcoord) {\n                        /* south pole */\n                        quad = 11;\n                        d = 0;\n                        i = 0;\n                    } else if (d == maxcoord) {\n                        /* lower right in next quad */\n                        quad += 1;\n                        if (quad == 11)\n                            quad = 6;\n                        d = maxcoord - i;\n                        i = 0;\n                    } else if (i == maxcoord) {\n                        /* upper right in quad to upper right */\n                        quad = (quad - 4) % 5;\n                        i = 0;\n                    }\n                }\n\n                di->x = d;\n                di->y = i;\n\n                g->quad = quad;\n                return quad;\n            }\n\n            template <typename T>\n            inline int isea_dddi(isea_dgg<T> *g, int quad, isea_pt<T> *pt, isea_pt<T> *di)\n            {\n                isea_pt<T> v;\n                T          hexwidth;\n                int        sidelength;    /* in hexes */\n                hex        h;\n\n                if (g->aperture == 3 && g->resolution % 2 != 0) {\n                    return isea_dddi_ap3odd(g, quad, pt, di);\n                }\n                /* todo might want to do this as an iterated loop */\n                if (g->aperture >0) {\n                    sidelength = (int) (math::pow(T(g->aperture), T(g->resolution / T(2))) + T(0.5));\n                } else {\n                    sidelength = g->resolution;\n                }\n\n                hexwidth = 1.0 / sidelength;\n\n                v = *pt;\n                isea_rotate(&v, -30.0);\n                hexbin2(hexwidth, v.x, v.y, &h.x, &h.y);\n                h.iso = 0;\n                hex_iso(&h);\n\n                /* we may actually be on another quad */\n                if (quad <= 5) {\n                    if (h.x == 0 && h.z == -sidelength) {\n                        /* north pole */\n                        quad = 0;\n                        h.z = 0;\n                        h.y = 0;\n                        h.x = 0;\n                    } else if (h.z == -sidelength) {\n                        quad = quad + 1;\n                        if (quad == 6)\n                            quad = 1;\n                        h.y = sidelength - h.x;\n                        h.z = h.x - sidelength;\n                        h.x = 0;\n                    } else if (h.x == sidelength) {\n                        quad += 5;\n                        h.y = -h.z;\n                        h.x = 0;\n                    }\n                } else if (quad >= 6) {\n                    if (h.z == 0 && h.x == sidelength) {\n                        /* south pole */\n                        quad = 11;\n                        h.x = 0;\n                        h.y = 0;\n                        h.z = 0;\n                    } else if (h.x == sidelength) {\n                        quad = quad + 1;\n                        if (quad == 11)\n                            quad = 6;\n                        h.x = h.y + sidelength;\n                        h.y = 0;\n                        h.z = -h.x;\n                    } else if (h.y == -sidelength) {\n                        quad -= 4;\n                        h.y = 0;\n                        h.z = -h.x;\n                    }\n                }\n                di->x = h.x;\n                di->y = -h.z;\n\n                g->quad = quad;\n                return quad;\n            }\n\n            template <typename T>\n            inline int isea_ptdi(isea_dgg<T> *g, int tri, isea_pt<T> *pt,\n                                 isea_pt<T> *di)\n            {\n                isea_pt<T> v;\n                int        quad;\n\n                v = *pt;\n                quad = isea_ptdd(tri, &v);\n                quad = isea_dddi(g, quad, &v, di);\n                return quad;\n            }\n\n            /* q2di to seqnum */\n            template <typename T>\n            inline int isea_disn(isea_dgg<T> *g, int quad, isea_pt<T> *di)\n            {\n                int             sidelength;\n                int             sn, height;\n                int             hexes;\n\n                if (quad == 0) {\n                    g->serial = 1;\n                    return g->serial;\n                }\n                /* hexes in a quad */\n                hexes = (int) (math::pow(T(g->aperture), T(g->resolution)) + T(0.5));\n                if (quad == 11) {\n                    g->serial = 1 + 10 * hexes + 1;\n                    return g->serial;\n                }\n                if (g->aperture == 3 && g->resolution % 2 == 1) {\n                    height = (int) (math::pow(T(g->aperture), T((g->resolution - 1) / T(2))));\n                    sn = ((int) di->x) * height;\n                    sn += ((int) di->y) / height;\n                    sn += (quad - 1) * hexes;\n                    sn += 2;\n                } else {\n                    sidelength = (int) (math::pow(T(g->aperture), T(g->resolution / T(2))) + T(0.5));\n                    sn = (int) ((quad - 1) * hexes + sidelength * di->x + di->y + 2);\n                }\n\n                g->serial = sn;\n                return sn;\n            }\n\n            /* TODO just encode the quad in the d or i coordinate\n             * quad is 0-11, which can be four bits.\n             * d' = d << 4 + q, d = d' >> 4, q = d' & 0xf\n             */\n            /* convert a q2di to global hex coord */\n            template <typename T>\n            inline int isea_hex(isea_dgg<T> *g, int tri, isea_pt<T> *pt,\n                                isea_pt<T> *hex)\n            {\n                isea_pt<T> v;\n#ifdef BOOST_GEOMETRY_PROJECTIONS_FIXME\n                int sidelength;\n                int d, i, x, y;\n#endif // BOOST_GEOMETRY_PROJECTIONS_FIXME\n                int quad;\n\n                quad = isea_ptdi(g, tri, pt, &v);\n\n                hex->x = ((int)v.x << 4) + quad;\n                hex->y = v.y;\n\n                return 1;\n#ifdef BOOST_GEOMETRY_PROJECTIONS_FIXME\n                d = (int)v.x;\n                i = (int)v.y;\n\n                /* Aperture 3 odd resolutions */\n                if (g->aperture == 3 && g->resolution % 2 != 0) {\n                    int offset = (int)(pow(T(3.0), T(g->resolution - 1)) + 0.5);\n\n                    d += offset * ((g->quad-1) % 5);\n                    i += offset * ((g->quad-1) % 5);\n\n                    if (quad == 0) {\n                        d = 0;\n                        i = offset;\n                    } else if (quad == 11) {\n                        d = 2 * offset;\n                        i = 0;\n                    } else if (quad > 5) {\n                        d += offset;\n                    }\n\n                    x = (2*d - i) /3;\n                    y = (2*i - d) /3;\n\n                    hex->x = x + offset / 3;\n                    hex->y = y + 2 * offset / 3;\n                    return 1;\n                }\n\n                /* aperture 3 even resolutions and aperture 4 */\n                sidelength = (int) (pow(T(g->aperture), T(g->resolution / 2.0)) + 0.5);\n                if (g->quad == 0) {\n                    hex->x = 0;\n                    hex->y = sidelength;\n                } else if (g->quad == 11) {\n                    hex->x = sidelength * 2;\n                    hex->y = 0;\n                } else {\n                    hex->x = d + sidelength * ((g->quad-1) % 5);\n                    if (g->quad > 5) hex->x += sidelength;\n                    hex->y = i + sidelength * ((g->quad-1) % 5);\n                }\n\n                return 1;\n#endif // BOOST_GEOMETRY_PROJECTIONS_FIXME\n            }\n\n            template <typename T>\n            inline isea_pt<T> isea_forward(isea_dgg<T> *g, isea_geo<T> *in)\n            {\n                int        tri;\n                isea_pt<T> out, coord;\n\n                tri = isea_transform(g, in, &out);\n\n                if (g->output == isea_addr_plane) {\n                    isea_tri_plane(tri, &out, g->radius);\n                    return out;\n                }\n\n                /* convert to isea standard triangle size */\n                out.x = out.x / g->radius * isea_scale;\n                out.y = out.y / g->radius * isea_scale;\n                out.x += 0.5;\n                out.y += 2.0 * .14433756729740644112;\n\n                switch (g->output) {\n                case isea_addr_projtri:\n                    /* nothing to do, already in projected triangle */\n                    break;\n                case isea_addr_vertex2dd:\n                    g->quad = isea_ptdd(tri, &out);\n                    break;\n                case isea_addr_q2dd:\n                    /* Same as above, we just don't print as much */\n                    g->quad = isea_ptdd(tri, &out);\n                    break;\n                case isea_addr_q2di:\n                    g->quad = isea_ptdi(g, tri, &out, &coord);\n                    return coord;\n                    break;\n                case isea_addr_seqnum:\n                    isea_ptdi(g, tri, &out, &coord);\n                    /* disn will set g->serial */\n                    isea_disn(g, g->quad, &coord);\n                    return coord;\n                    break;\n                case isea_addr_hex:\n                    isea_hex(g, tri, &out, &coord);\n                    return coord;\n                    break;\n                }\n\n                return out;\n            }\n            /*\n             * Proj 4 integration code follows\n             */\n\n            template <typename T>\n            struct par_isea\n            {\n                isea_dgg<T> dgg;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_isea_spheroid\n                : public base_t_f<base_isea_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_isea<T> m_proj_parm;\n\n                inline base_isea_spheroid(const Parameters& par)\n                    : base_t_f<base_isea_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_forward)\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    isea_pt<T> out;\n                    isea_geo<T> in;\n\n                    in.lon = lp_lon;\n                    in.lat = lp_lat;\n\n                    isea_dgg<T> copy = this->m_proj_parm.dgg;\n                    out = isea_forward(&copy, &in);\n\n                    xy_x = out.x;\n                    xy_y = out.y;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"isea_spheroid\";\n                }\n\n            };\n\n            template <typename T>\n            inline void isea_orient_init(srs::detail::proj4_parameters const& params,\n                                         par_isea<T>& proj_parm)\n            {\n                std::string opt = pj_get_param_s(params, \"orient\");\n                if (! opt.empty()) {\n                    if (opt == std::string(\"isea\")) {\n                        isea_orient_isea(&proj_parm.dgg);\n                    } else if (opt == std::string(\"pole\")) {\n                        isea_orient_pole(&proj_parm.dgg);\n                    } else {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_ellipsoid_use_required) );\n                    }\n                }\n            }\n\n            template <typename T>\n            inline void isea_orient_init(srs::dpar::parameters<T> const& params,\n                                         par_isea<T>& proj_parm)\n            {\n                typename srs::dpar::parameters<T>::const_iterator\n                    it = pj_param_find(params, srs::dpar::orient);\n                if (it != params.end()) {\n                    srs::dpar::value_orient o = static_cast<srs::dpar::value_orient>(it->template get_value<int>());\n                    if (o == srs::dpar::orient_isea) {\n                        isea_orient_isea(&proj_parm.dgg);\n                    } else if (o == srs::dpar::orient_pole) {\n                        isea_orient_pole(&proj_parm.dgg);\n                    } else {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_ellipsoid_use_required) );\n                    }\n                }\n            }\n\n            template <typename T>\n            inline void isea_mode_init(srs::detail::proj4_parameters const& params,\n                                       par_isea<T>& proj_parm)\n            {\n                std::string opt = pj_get_param_s(params, \"mode\");\n                if (! opt.empty()) {\n                    if (opt == std::string(\"plane\")) {\n                        proj_parm.dgg.output = isea_addr_plane;\n                    } else if (opt == std::string(\"di\")) {\n                        proj_parm.dgg.output = isea_addr_q2di;\n                    } else if (opt == std::string(\"dd\")) {\n                        proj_parm.dgg.output = isea_addr_q2dd;\n                    } else if (opt == std::string(\"hex\")) {\n                        proj_parm.dgg.output = isea_addr_hex;\n                    } else {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_ellipsoid_use_required) );\n                    }\n                }\n            }\n\n            template <typename T>\n            inline void isea_mode_init(srs::dpar::parameters<T> const& params,\n                                       par_isea<T>& proj_parm)\n            {\n                typename srs::dpar::parameters<T>::const_iterator\n                    it = pj_param_find(params, srs::dpar::mode);\n                if (it != params.end()) {\n                    srs::dpar::value_mode m = static_cast<srs::dpar::value_mode>(it->template get_value<int>());\n                    if (m == srs::dpar::mode_plane) {\n                        proj_parm.dgg.output = isea_addr_plane;\n                    } else if (m == srs::dpar::mode_di) {\n                        proj_parm.dgg.output = isea_addr_q2di;\n                    } else if (m == srs::dpar::mode_dd) {\n                        proj_parm.dgg.output = isea_addr_q2dd;\n                    } else if (m == srs::dpar::mode_hex) {\n                        proj_parm.dgg.output = isea_addr_hex;\n                    } else {\n                        BOOST_THROW_EXCEPTION( projection_exception(error_ellipsoid_use_required) );\n                    }\n                }\n            }\n\n            // Icosahedral Snyder Equal Area\n            template <typename Params, typename T>\n            inline void setup_isea(Params const& params, par_isea<T>& proj_parm)\n            {\n                std::string opt;\n\n                isea_grid_init(&proj_parm.dgg);\n\n                proj_parm.dgg.output = isea_addr_plane;\n            /*        proj_parm.dgg.radius = par.a; / * otherwise defaults to 1 */\n                /* calling library will scale, I think */\n\n                isea_orient_init(params, proj_parm);\n\n                pj_param_r<srs::spar::azi>(params, \"azi\", srs::dpar::azi, proj_parm.dgg.o_az);\n                pj_param_r<srs::spar::lon_0>(params, \"lon_0\", srs::dpar::lon_0, proj_parm.dgg.o_lon);\n                pj_param_r<srs::spar::lat_0>(params, \"lat_0\", srs::dpar::lat_0, proj_parm.dgg.o_lat);\n                // TODO: this parameter is set below second time\n                pj_param_i<srs::spar::aperture>(params, \"aperture\", srs::dpar::aperture, proj_parm.dgg.aperture);\n                // TODO: this parameter is set below second time\n                pj_param_i<srs::spar::resolution>(params, \"resolution\", srs::dpar::resolution, proj_parm.dgg.resolution);\n                \n                isea_mode_init(params, proj_parm);\n\n                // TODO: pj_param_exists -> pj_get_param_b ?\n                if (pj_param_exists<srs::spar::rescale>(params, \"rescale\", srs::dpar::rescale)) {\n                    proj_parm.dgg.radius = isea_scale;\n                }\n\n                if (pj_param_i<srs::spar::resolution>(params, \"resolution\", srs::dpar::resolution, proj_parm.dgg.resolution)) {\n                    /* empty */\n                } else {\n                    proj_parm.dgg.resolution = 4;\n                }\n\n                if (pj_param_i<srs::spar::aperture>(params, \"aperture\", srs::dpar::aperture, proj_parm.dgg.aperture)) {\n                    /* empty */\n                } else {\n                    proj_parm.dgg.aperture = 3;\n                }\n            }\n\n    }} // namespace detail::isea\n    #endif // doxygen\n\n    /*!\n        \\brief Icosahedral Snyder Equal Area projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Spheroid\n        \\par Projection parameters\n         - orient (string)\n         - azi: Azimuth (or Gamma) (degrees)\n         - lon_0: Central meridian (degrees)\n         - lat_0: Latitude of origin (degrees)\n         - aperture (integer)\n         - resolution (integer)\n         - mode (string)\n         - rescale\n        \\par Example\n        \\image html ex_isea.gif\n    */\n    template <typename T, typename Parameters>\n    struct isea_spheroid : public detail::isea::base_isea_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline isea_spheroid(Params const& params, Parameters const& par)\n            : detail::isea::base_isea_spheroid<T, Parameters>(par)\n        {\n            detail::isea::setup_isea(params, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_isea, isea_spheroid, isea_spheroid)\n\n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_F(isea_entry, isea_spheroid)\n        \n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(isea_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(isea, isea_entry)\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_ISEA_HPP\n\n", "meta": {"hexsha": "2320ac8206ee28f9d9909600b0a406682a1ffb51", "size": 48720, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/srs/projections/proj/isea.hpp", "max_stars_repo_name": "barendgehrels/geometry", "max_stars_repo_head_hexsha": "1998db08d6037681768c4e8dfc9f2593df0c32fa", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T17:40:19.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-07T17:40:19.000Z", "max_issues_repo_path": "include/boost/geometry/srs/projections/proj/isea.hpp", "max_issues_repo_name": "barendgehrels/geometry", "max_issues_repo_head_hexsha": "1998db08d6037681768c4e8dfc9f2593df0c32fa", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/geometry/srs/projections/proj/isea.hpp", "max_forks_repo_name": "barendgehrels/geometry", "max_forks_repo_head_hexsha": "1998db08d6037681768c4e8dfc9f2593df0c32fa", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9090909091, "max_line_length": 127, "alphanum_fraction": 0.4174466338, "num_tokens": 11352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410572017153, "lm_q2_score": 0.32766830738621877, "lm_q1q2_score": 0.21803395584975616}}
{"text": "// __BEGIN_LICENSE__\n// Copyright (C) 2006-2011 United States Government as represented by\n// the Administrator of the National Aeronautics and Space Administration.\n// All Rights Reserved.\n// __END_LICENSE__\n\n\n#include <vw/Image.h>\n#include <vw/Plate/PlateFile.h>\n#include <vw/Plate/TileManipulation.h>\nusing namespace vw;\nusing namespace vw::platefile;\n\n#include <boost/foreach.hpp>\n#include <boost/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <boost/math/distributions/fisher_f.hpp>\n\nusing namespace std;\n\n// --- Functions to Apply --------------------------\n\n// Reduce Base class\n//   defines interface\ntemplate <typename ImplT>\nstruct ReduceBase {\n  inline ImplT& impl() { return static_cast<ImplT&>(*this); }\n  inline ImplT const& impl() const { return static_cast<ImplT const&>(*this); }\n\n  template <class PixelT>\n  inline void operator()( list<ImageView<PixelT> > const& input,\n                          list<TileHeader> const& input_header,\n                          ImageView<PixelT> & output) {\n    impl()(input,input_header,output);\n  }\n};\n\n// Weighted Average Implementation\n//   mimick this with own functions\nstruct WeightedAverage : public ReduceBase<WeightedAverage> {\n\n  template <class PixelT>\n  inline void operator()( list<ImageView<PixelT> > const& input,\n                          list<TileHeader> const& /*input_header*/,\n                          ImageView<PixelT> & output) {\n    // Input Images will always have an alpha channel. That is a requirement of PlateFiles.\n    int num_channels = CompoundNumChannels<PixelT>::value;\n    std::vector<ImageView<float32> > sum_weighted_data;\n    for ( uint8 i = 0; i < num_channels-1; i++ )\n      sum_weighted_data.push_back(ImageView<float32>(input.front().cols(),\n                                                     input.front().rows()));\n    ImageView<float32> summed_weights(input.front().cols(),\n                                      input.front().rows());\n\n    // Summing multiple images\n    typedef typename list< ImageView<PixelT > >::const_iterator image_iter;\n    for ( image_iter image = input.begin();\n          image != input.end(); image++ ) {\n      summed_weights += channel_cast<float32>(select_channel(*image,num_channels-1));\n      // Iterating over non alpha channels\n      for ( uint8 i = 0; i < num_channels-1; i++ )\n        sum_weighted_data[i] += channel_cast<float32>(select_channel(*image,num_channels-1))*channel_cast<float32>(select_channel(*image,i));\n    }\n\n    // Normalizing\n    for ( uint8 i = 0; i < num_channels-1; i++ )\n      sum_weighted_data[i] /= summed_weights;\n    output.set_size(input.front().cols(),\n                    input.front().rows());\n    for ( uint8 i = 0; i < num_channels-1; i++ )\n      select_channel(output,i) = sum_weighted_data[i];\n    // Setting output alpha\n    select_channel(output,num_channels-1) = threshold(summed_weights,0,\n                                                      ChannelRange<typename PixelChannelType<PixelT>::type>::min(),\n                                                      ChannelRange<typename PixelChannelType<PixelT>::type>::max());\n  }\n};\n\n// Weighted Variance Implementation\nstruct WeightedVar2 : public ReduceBase<WeightedVar2> {\n\n  template <class PixelT>\n  inline void operator()( list<ImageView<PixelT> > const& input,\n                          list<TileHeader> const& /*input_header*/,\n                          ImageView<PixelT> & var2) {\n    // Input Images will always have an alpha channel. That is a requirement of PlateFiles.\n    int num_channels = CompoundNumChannels<PixelT>::value;\n    std::vector<ImageView<float32> > sum_weighted_data; //store the mean\n    std::vector<ImageView<float32> > sum_weighted_data2; //store the variance\n    std::vector<ImageView<float32> > sum_weighted_stdv; //store the standard deviation\n\n    for ( uint8 i = 0; i < num_channels-1; i++ ){\n      sum_weighted_data.push_back(ImageView<float32>(input.front().cols(),\n                                                     input.front().rows()));\n      sum_weighted_data2.push_back(ImageView<float32>(input.front().cols(),\n                                                     input.front().rows()));\n      sum_weighted_stdv.push_back(ImageView<float32>(input.front().cols(),\n                                                    input.front().rows()));\n    }\n\n    ImageView<float32> summed_weights(input.front().cols(),\n                                      input.front().rows());\n\n    // Summing multiple images\n    typedef typename list< ImageView<PixelT > >::const_iterator image_iter;\n    for ( image_iter image = input.begin();image != input.end(); image++ ) {\n      summed_weights += channel_cast<float32>(select_channel(*image,num_channels-1));\n\n      // Iterating over non alpha channels\n      for ( uint8 i = 0; i < num_channels-1; i++ ){\n        sum_weighted_data[i] += channel_cast<float32>(select_channel(*image,num_channels-1))*channel_cast<float32>(select_channel(*image,i));\n\n        sum_weighted_data2[i] += channel_cast<float32>(select_channel(*image,num_channels-1))\n                                 *channel_cast<float32>(select_channel(*image,i))*channel_cast<float32>(select_channel(*image,i));\n      }\n    }\n\n    // Normalizing\n    for ( uint8 i = 0; i < num_channels-1; i++ ){\n      sum_weighted_data[i] /= summed_weights;\n      sum_weighted_data2[i] = sum_weighted_data2[i]/summed_weights - sum_weighted_data[i]*sum_weighted_data[i];\n      sum_weighted_stdv[i]=sqrt(clamp(sum_weighted_data2[i],0, 999999999));\n    }\n\n    var2.set_size(input.front().cols(),\n                  input.front().rows());\n    for ( uint8 i = 0; i < num_channels-1; i++ )\n      select_channel(var2,i) = sum_weighted_stdv[i];\n    // Setting output alpha\n    select_channel(var2,num_channels-1) =\n      threshold(summed_weights,0,\n                ChannelRange<typename PixelChannelType<PixelT>::type>::min(),\n                ChannelRange<typename PixelChannelType<PixelT>::type>::max());\n  }\n};\n\n// Robust Mean Implementation\nstruct RobustMean : public ReduceBase<RobustMean> {\nprivate:\n  float smart_weighted_mean( vector<float> & weights,\n                             vector<float> const& samples,\n                             float const sign_level=0.3f,\n                             float const learn_rate=0.1f,\n                             float const error_tol=1e-5f,\n                             int32 const max_iter=1000 ) {\n    namespace bm = boost::math;\n    switch ( samples.size() ) {\n    case 1:\n      weights[0]=1;\n      return samples[0];\n    case 2:\n      weights[0]=1;\n      weights[1]=1;\n      return (samples[0]+samples[1])/2;\n    default:\n\n      float weighted_mean = 0;\n      std::vector<float> prev_wt = weights; // the previous weights\n      for (int i = 0; i < max_iter; ++i) {\n\n        // accumulation of all sums\n        float SW1 = 0;    // sum of weights\n        float SW2 = 0;    // sum of squared weights\n        float SWX = 0;    // weighted sum of samples\n        float WX2 = 0;    // weighted sum of squared data\n        for (size_t j = 0; j < samples.size(); ++j) {\n          SW1 += weights[j];\n          SW2 += weights[j]*weights[j];\n          SWX += weights[j]*samples[j];\n          WX2 += weights[j]*samples[j]*samples[j];\n        }\n\n        // weighted mean\n        weighted_mean = SWX/SW1;\n\n        float DN = SW1*WX2-SWX*SWX; // denominator\n        float v2 = SW1-SW2/SW1;     // the second degree of freedom\n        float sse_wt = 0;           // squared sum of weight differences\n        for (size_t j = 0; j < samples.size(); ++j) {\n\n          // F statistic\n          float DF = samples[j]-weighted_mean; // difference from the mean\n          float FS = (SW1*SW1-SW2)*DF*DF/DN;   // F statistic\n\n          // degree of freedom\n          float v1 = 1-weights[j]/SW1;         // the first degree of freedom\n\n          // p-value calculation\n          float p_value = 1;                   // p-value\n          if (SW1 > 1 && DN > 0) {             // basic assumptions\n            bm::fisher_f dist(v1,v2);\n            p_value = boost::numeric_cast<float>(1-cdf(dist, FS));\n          }\n\n          // gradient decent update\n          weights[j] += learn_rate*(p_value-sign_level);\n          if ( weights[j] < 0 ) weights[j] = 0; // 0.0 is lower bound of weight\n          if ( weights[j] > 1 ) weights[j] = 1; // 1.0 is upper bound of weight\n\n          // squared sum of weight differences\n          sse_wt += (weights[j]-prev_wt[j])*(weights[j]-prev_wt[j]);\n          prev_wt[j] = weights[j];              // update previous weight\n\n        }\n\n        // terminal condition: mean squared difference of weights is\n        // smaller than the tolerance\n        if ( sse_wt/float(weights.size()) < error_tol ) break;\n      }\n\n      return  weighted_mean;\n    }\n  }\n\npublic:\n  template <class PixelT>\n  inline void operator()( list<ImageView<PixelT> > const& input,\n                          list<TileHeader> const& /*input_header*/,\n                          ImageView<PixelT> & output ) {\n    uint8 num_v_channels = CompoundNumChannels<PixelT>::value-1;\n    output.set_size( input.front().cols(),\n                     input.front().rows() );\n\n    // Iterating through every pixel within a tile\n    for ( int32 ix = 0; ix < input.front().cols(); ix++ ) {\n      for ( int32 iy = 0; iy < input.front().rows(); iy++ ) {\n        vector<std::vector<float> > t_samples;\n        t_samples.resize(num_v_channels);\n        vector<float> t_weight;\n\n        // Seperating data out into vectors, only loading up data that\n        // is not empty.\n        typedef typename list<ImageView<PixelT> >::const_iterator iter_type;\n        for ( iter_type iter = input.begin();\n              iter != input.end(); iter++ ) {\n          if ( (*iter)(ix,iy)[num_v_channels] == 0 )\n            continue;\n          t_weight.push_back( float((*iter)(ix,iy)[num_v_channels])/float(ChannelRange<typename PixelChannelType<PixelT>::type>::max()) );\n          for ( uint8 iz = 0; iz < num_v_channels; iz++ )\n            t_samples[iz].push_back( (*iter)(ix,iy)[iz] );\n        }\n\n        if ( t_weight.empty() ) {\n          output(ix,iy) = PixelT();\n          continue;\n        }\n\n        typedef typename PixelChannelType<PixelT>::type ChannelT;\n        output(ix,iy)[num_v_channels] = ChannelRange<ChannelT>::max();\n        for ( uint8 iz = 0; iz < num_v_channels; iz++ ) {\n          vector<float> copy = t_weight;\n          output(ix,iy)[iz] =\n            boost::numeric_cast<ChannelT>(smart_weighted_mean( copy,\n                                                               t_samples[iz]));\n        }\n      } // iy - end loop\n    }   // ix - first loop\n  }     // end operator()\n};\n\n// --- Standard Terminal Argument ------------------\n\n// Standard Arguments\nstruct Options {\n  // Input\n  Url url;\n  int32 level;\n  TransactionOrNeg start_trans_id, end_trans_id;\n  std::string start_description;\n  bool finish;\n\n  // Output\n  string function;\n  TransactionOrNeg transaction_id;\n\n  // For spawning multiple jobs\n  int32 job_id, num_jobs;\n};\n\nvoid handle_arguments(int argc, char *argv[], Options& opt) {\n  po::options_description general_options(\"Perform weighted averages of all layers within a tile inside a plate file\");\n  general_options.add_options()\n    (\"job_id,j\", po::value(&opt.job_id)->default_value(0), \"\")\n    (\"num_jobs,n\", po::value(&opt.num_jobs)->default_value(1), \"\")\n    (\"begin_transaction\", po::value(&opt.start_trans_id)->default_value(0), \"Input starting transaction ID range.\")\n    (\"end_transaction\", po::value(&opt.end_trans_id), \"Input ending transaction ID range.\")\n    (\"level,l\", po::value(&opt.level)->default_value(-1), \"Level inside the plate in which to process. -1 will error out and show the number of levels available.\")\n    (\"function,f\", po::value(&opt.function)->default_value(\"WeightedAvg\"), \"Functions that are available are [WeightedAvg RobustMean WeightedVar]\")\n    (\"transaction-id,t\",po::value(&opt.transaction_id)->default_value(2000), \"Transaction id to write to\")\n    (\"start\", po::value(&opt.start_description), \"Starts a multi-part plate reduce.\")\n    (\"finish\", po::bool_switch(&opt.finish)->default_value(false), \"Finish a multi-part plate reduce\")\n    (\"help,h\", \"Display this help message\");\n\n  po::options_description hidden_options(\"\");\n  hidden_options.add_options()\n    (\"input-file\", po::value(&opt.url), \"\");\n\n  po::options_description options(\"\");\n  options.add(general_options).add(hidden_options);\n\n  po::positional_options_description p;\n  p.add(\"input-file\",-1);\n\n  po::variables_map vm;\n  try {\n    po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );\n    po::notify( vm );\n  } catch (const po::error& e) {\n    vw_throw( ArgumentErr() << \"Error parsing input:\\n\\t\"\n              << e.what() << options );\n  }\n\n  std::ostringstream usage;\n  usage << \"Usage: \" << argv[0] << \" <plate_filename> [options]\\n\";\n\n  if ( vm.count(\"help\") || vm.count(\"input-file\") != 1 || opt.transaction_id.newest())\n    vw_throw( ArgumentErr() << usage.str() << general_options );\n}\n\n// --- Meta Application of Above Functions ----------\n\n// apply_reduce\ntemplate <typename ReduceT, class PixelT>\nvoid apply_reduce( boost::shared_ptr<PlateFile> platefile,\n                   std::list<BBox2i> const& workunits,\n                   Options& opt, ReduceBase<ReduceT>& reduce) {\n\n  TerminalProgressCallback tpc(\"plate.platereduce\", \"Processing\");\n  double inc_tpc = 1.0/float(workunits.size());\n  BOOST_FOREACH( const BBox2i& workunit, workunits) {\n    tpc.report_incremental_progress(inc_tpc);\n    for ( int ix = 0; ix < workunit.width(); ix++ ) {\n      for ( int iy = 0; iy < workunit.height(); iy++ ) {\n        Vector2i location(ix,iy);\n        location += workunit.min();\n\n        // Polling for Tiles\n        std::list<TileHeader> tile_records;\n        tile_records = platefile->search_by_location(location[0],\n                                                     location[1],\n                                                     opt.level,\n                                                     TransactionRange(opt.start_trans_id, opt.end_trans_id));\n\n        // No Tiles? No Problem!\n        if (tile_records.empty())\n          continue;\n\n        // Loading images\n        std::list<ImageView<PixelT> > tiles;\n        BOOST_FOREACH( const TileHeader& tile, tile_records ) {\n          ImageView<PixelT> new_tile;\n          platefile->read( new_tile, location[0],\n                           location[1], opt.level,\n                           tile.transaction_id(), true );\n          tiles.push_back(new_tile);\n        }\n\n        // Calling function\n        ImageView<PixelT> result;\n        reduce(tiles, tile_records, result);\n\n        platefile->write_update(result, location[0], location[1], opt.level);\n      }\n    }\n  }\n  tpc.report_finished();\n}\n\n// Function that runs the apply_reduce over the plate file\ntemplate <typename ReduceT>\nvoid do_run( Options& opt, ReduceBase<ReduceT>& reduce ) {\n  boost::shared_ptr<PlateFile> platefile =\n    boost::shared_ptr<PlateFile>( new PlateFile(opt.url) );\n\n  if ( !opt.start_description.empty() ) {\n    platefile->transaction_begin(opt.start_description, opt.transaction_id );\n    vw_out() << \"Transaction started with ID = \" << platefile->transaction_id() << \"\\n\";\n    vw_out() << \"Plate has \" << platefile->num_levels() << \" levels.\\n\";\n    exit(0);\n  }\n\n  platefile->transaction_resume(opt.transaction_id.promote());\n\n  if ( opt.finish ) {\n    // Update the read cursor when the snapshot is complete!\n    platefile->transaction_end(true);\n    vw_out() << \"Transaction \" << opt.transaction_id << \" complete.\\n\";\n    exit(0);\n  }\n\n  if ( opt.level < 0 || opt.level >= boost::numeric_cast<int32>(platefile->num_levels()) ) {\n    vw_throw( ArgumentErr() << \"Incorrect level selection, \"\n              << opt.level << \".\\n\\nPlatefile \" << opt.url.string() << \" has \"\n              << platefile->num_levels() << \" levels internally.\\n\" );\n  }\n\n  // This is arbitrary, just needed to divide up jobs\n  int32 region_size = 1 << opt.level;\n  BBox2i full_region(0,0,region_size,region_size);\n  std::list<BBox2i> workunits = bbox_tiles(full_region,4,4);\n  std::list<BBox2i> mworkunits;\n  int32 count = 0;\n  BOOST_FOREACH(const BBox2i& c, workunits) {\n    if (count==opt.num_jobs)\n      count=0;\n    if (count==opt.job_id)\n      mworkunits.push_back(c);\n    count++;\n  }\n  vw_out() << \"Job \" << opt.job_id << \"/\" << opt.num_jobs << \" has \"\n           << mworkunits.size() << \" work units.\\n\";\n\n  platefile->audit_log()\n    << \"Started multi-part reduce (t_id = \" << opt.transaction_id\n    << \") -- level:\" << opt.level\n    << \" jobid:\" << opt.job_id << \"/\" << opt.num_jobs << \"\\n\";\n\n  platefile->write_request();\n\n  switch(platefile->pixel_format()) {\n  case VW_PIXEL_GRAYA:\n    switch(platefile->channel_type()) {\n    case VW_CHANNEL_UINT8:\n      apply_reduce<ReduceT, PixelGrayA<uint8> >(platefile, mworkunits,\n                                                opt, reduce);\n      break;\n    case VW_CHANNEL_INT16:\n      apply_reduce<ReduceT, PixelGrayA<int16> >(platefile, mworkunits,\n                                                opt, reduce);\n      break;\n    case VW_CHANNEL_FLOAT32:\n      apply_reduce<ReduceT, PixelGrayA<float32> >(platefile, mworkunits,\n                                                  opt, reduce);\n      break;\n    default:\n      vw_throw(InputErr() << \"Platefile contains unsupported channel type.\\n\" );\n    }\n    break;\n  case VW_PIXEL_RGBA:\n    switch(platefile->channel_type()) {\n    case VW_CHANNEL_UINT8:\n      apply_reduce<ReduceT, PixelRGBA<uint8> >(platefile, mworkunits,\n                                               opt, reduce);\n      break;\n    default:\n      vw_throw(InputErr() << \"Platefile contains unsupported channel type.\\n\" );\n    }\n    break;\n  default:\n    vw_throw(InputErr() << \"Platefile contains a pixel type thats unsupported.\\n\" );\n  }\n\n  platefile->write_complete();\n  platefile->audit_log()\n    << \"Finished multi-part reduce (t_id = \" << opt.transaction_id\n    << \") -- level:\" << opt.level\n    << \" jobid:\" << opt.job_id << \"/\" << opt.num_jobs << \"\\n\";\n}\n\nint main( int argc, char *argv[] ) {\n\n  Options opt;\n  try {\n    handle_arguments( argc, argv, opt );\n\n    // Handing out jobs now\n    boost::to_lower(opt.function);\n    if ( opt.function == \"weightedavg\" ) {\n      WeightedAverage f;\n      do_run<WeightedAverage>( opt, f );\n    } else if ( opt.function == \"robustmean\" ) {\n      RobustMean f;\n      do_run<RobustMean>( opt, f );\n    }\n    else if ( opt.function == \"weightedvar\" ) {\n      WeightedVar2 f;\n      do_run<WeightedVar2>( opt, f );\n    } else {\n      vw_throw( ArgumentErr() << \"Unknown function, \" << opt.function << \"\\n\" );\n    }\n\n  } catch ( const ArgumentErr& e ) {\n    vw_out() << e.what() << std::endl;\n    return 1;\n  } catch ( const Exception& e ) {\n    std::cerr << \"Error: \" << e.what() << std::endl;\n    return 1;\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "36ef35c48889d3787150cf075808fa0460cdd1a1", "size": 18923, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Plate/platereduce.cc", "max_stars_repo_name": "digimatronics/ComputerVision", "max_stars_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_stars_repo_licenses": ["NASA-1.3"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-16T23:57:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-16T23:57:32.000Z", "max_issues_repo_path": "src/vw/Plate/platereduce.cc", "max_issues_repo_name": "rkrishnasanka/visionworkbench", "max_issues_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_issues_repo_licenses": ["NASA-1.3"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vw/Plate/platereduce.cc", "max_forks_repo_name": "rkrishnasanka/visionworkbench", "max_forks_repo_head_hexsha": "2af5da17dfd277f0cb3f19a97e3d49ba19cc9d24", "max_forks_repo_licenses": ["NASA-1.3"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-03-18T04:06:32.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T10:34:39.000Z", "avg_line_length": 38.38336714, "max_line_length": 163, "alphanum_fraction": 0.5949902235, "num_tokens": 4601, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.3775406828054584, "lm_q1q2_score": 0.21802799448923887}}
{"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-2021.\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: Timo Sachsenberg $\n// $Authors: Eva Lange $\n// --------------------------------------------------------------------------\n#include <algorithm>\n#include <cmath>\n\n#include <boost/math/special_functions/acosh.hpp>\n\n#include <OpenMS/TRANSFORMATIONS/RAW2PEAK/OptimizePick.h>\n\n\nusing std::max;\n\n\nnamespace OpenMS\n{\n\n  OptimizePick::OptimizePick(\n      const struct OptimizationFunctions::PenaltyFactors & penalties,\n      const int max_iteration)\n  {\n\n    penalties_ = penalties;\n\n    max_iteration_ = max_iteration;\n\n#ifdef DEBUG_PEAK_PICKING\n    std::cout << \"max iteration \" << max_iteration_\n              << \"\\n penalty factor pos \" << penalties.pos\n              << \"\\n penalty factor left width \" << penalties.lWidth\n              << \"\\n penalty factor right width \" << penalties.rWidth\n              << std::endl;\n#endif\n\n  }\n\n  OptimizePick::~OptimizePick()\n  {\n  }\n\n  void OptimizePick::optimize(std::vector<PeakShape> & peaks, Data & data)\n  {\n    if (peaks.empty())\n      return;\n\n    size_t global_peak_number = 0;\n    data.peaks.assign(peaks.begin(), peaks.end());\n\n    size_t num_dimensions = 4 * data.peaks.size();\n    Eigen::VectorXd x_init (num_dimensions);\n    x_init.setZero();\n    // We have to initialize the parameters for the optimization\n    for (size_t i = 0; i < data.peaks.size(); i++)\n    {\n      PeakShape current_peak = data.peaks[i];\n      double h  = current_peak.height;\n      double wl = current_peak.left_width;\n      double wr = current_peak.right_width;\n      double p  = current_peak.mz_position;\n      if (boost::math::isnan(wl))\n      {\n        data.peaks[i].left_width = 1;\n        wl = 1.;\n      }\n      if (boost::math::isnan(wr))\n      {\n        data.peaks[i].right_width = 1;\n        wr = 1.;\n      }\n      x_init(4 * i) = h;\n      x_init(4 * i + 1) = wl;\n      x_init(4 * i + 2) = wr;\n      x_init(4 * i + 3) = p;\n    }\n\n    data.penalties = penalties_;\n\n    unsigned num_data_points = std::max(data.positions.size() + 1, num_dimensions);\n    OptPeakFunctor functor (num_dimensions, num_data_points, &data);\n    Eigen::LevenbergMarquardt<OptPeakFunctor> lmSolver (functor);\n    lmSolver.parameters.maxfev = max_iteration_;\n    Eigen::LevenbergMarquardtSpace::Status status = lmSolver.minimize(x_init);\n    //the states are poorly documented. after checking the source, we believe that\n    //all states except NotStarted, Running and ImproperInputParameters are good\n    //termination states.\n    if (status <= Eigen::LevenbergMarquardtSpace::ImproperInputParameters)\n    {\n        throw Exception::UnableToFit(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, \"UnableToFit-OptimizePeak:\", \"Could not fit the data: Error \" + String(status));\n    }\n\n    // iterate over all peaks and store the optimized values in peaks\n    for (size_t current_peak = 0; current_peak < data.peaks.size(); current_peak++)\n    {\n      // Store the current parameters for this peak\n      peaks[global_peak_number + current_peak].height =  x_init(4 * current_peak);\n      peaks[global_peak_number + current_peak].mz_position = x_init(4 * current_peak + 3);\n      peaks[global_peak_number + current_peak].left_width = x_init(4 * current_peak + 1);\n      peaks[global_peak_number + current_peak].right_width = x_init(4 * current_peak + 2);\n\n      // compute the area\n      // is it a Lorentz or a Sech - Peak?\n      if (peaks[global_peak_number + current_peak].type == PeakShape::LORENTZ_PEAK)\n      {\n        PeakShape p = peaks[global_peak_number + current_peak];\n        double x_left_endpoint = p.mz_position - 1 / p.left_width * sqrt(p.height / 1 - 1);\n        double x_right_endpoint = p.mz_position + 1 / p.right_width * sqrt(p.height / 1 - 1);\n        double area_left = -p.height / p.left_width * atan(p.left_width * (x_left_endpoint - p.mz_position));\n        double area_right = -p.height / p.right_width * atan(p.right_width * (p.mz_position - x_right_endpoint));\n        peaks[global_peak_number + current_peak].area = area_left + area_right;\n#ifdef DEBUG_PEAK_PICKING\n        std::cout << \"Lorentz \" << area_left << \" \" << area_right\n                  << \" \" << peaks[global_peak_number + current_peak].area << std::endl;\n#endif\n      }\n      else  //It's a Sech - Peak\n      {\n        PeakShape p = peaks[global_peak_number + current_peak];\n        double x_left_endpoint = p.mz_position - 1 / p.left_width * boost::math::acosh(sqrt(p.height / 0.001));\n        double x_right_endpoint = p.mz_position + 1 / p.right_width * boost::math::acosh(sqrt(p.height / 0.001));\n        double area_left = p.height / p.left_width * (sinh(p.left_width * (p.mz_position - x_left_endpoint)) / cosh(p.left_width * (p.mz_position - x_left_endpoint)));\n        double area_right = -p.height / p.right_width * (sinh(p.right_width * (p.mz_position - x_right_endpoint)) / cosh(p.right_width * (p.mz_position - x_right_endpoint)));\n        peaks[global_peak_number + current_peak].area = area_left + area_right;\n#ifdef DEBUG_PEAK_PICKING\n        std::cout << \"Sech \" << area_left << \" \" << area_right\n                  << \" \" << peaks[global_peak_number + current_peak].area << std::endl;\n        std::cout << p.mz_position << \" \" << x_left_endpoint << \" \" << x_right_endpoint << std::endl;\n#endif\n      }\n    }\n    //global_peak_number += data.peaks.size();\n\n  }\n\n  int OptimizePick::OptPeakFunctor::operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fvec)\n  {\n    const std::vector<double> & signal = m_data->signal;\n    const std::vector<double> & positions = m_data->positions;\n    const std::vector<PeakShape> & peaks = m_data->peaks;\n    const OptimizationFunctions::PenaltyFactors & penalties = m_data->penalties;\n    // iterate over all points of the signal\n    for (size_t current_point = 0; current_point < positions.size(); current_point++)\n    {\n      double computed_signal = 0.;\n      double current_position = positions[current_point];\n      double experimental_signal = signal[current_point];\n\n      // iterate over all peaks\n      for (size_t current_peak = 0; current_peak < peaks.size(); current_peak++)\n      {\n        // Store the current parameters for this peak\n        double p_height = x(4 * current_peak);\n        double p_position = x(4 * current_peak + 3);\n        double p_width\n            = (current_position <= p_position) ? x(4 * current_peak + 1)\n                                 : x(4 * current_peak + 2);\n\n        // is it a Lorentz or a Sech - Peak?\n        if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n        {\n          computed_signal += p_height / (1. + pow(p_width * (current_position - p_position), 2));\n        }\n        else // It's a Sech - Peak\n        {\n          computed_signal += p_height / pow(cosh(p_width * (current_position - p_position)), 2);\n        }\n      }\n      fvec(current_point) = computed_signal - experimental_signal;\n    }\n\n    double penalty = 0.;\n    double penalty_pos    = penalties.pos;\n    double penalty_lwidth = penalties.lWidth;\n    double penalty_rwidth = penalties.rWidth;\n\n    // iterate over all peaks again to compute the penalties\n    for (size_t current_peak = 0; current_peak < peaks.size(); current_peak++)\n    {\n      double old_position = peaks[current_peak].mz_position;\n      double old_width_l = peaks[current_peak].left_width;\n      double old_width_r = peaks[current_peak].right_width;\n      double p_position = x(4 * current_peak + 3);\n      double p_width_l = x(4 * current_peak + 1);\n      double p_width_r = x(4 * current_peak + 2);\n\n      //penalty += pow(p_position - old_position, 2) + pow(p_width_l - old_width_l, 2) + pow(p_width_r - old_width_r, 2);\n      penalty += penalty_pos * pow(p_position - old_position, 2)\n        + penalty_lwidth * pow(p_width_l - old_width_l, 2)\n        + penalty_rwidth * pow(p_width_r - old_width_r, 2);\n    }\n\n    fvec(positions.size()) = 100 * penalty;\n\n    return 0;\n  }\n  // compute Jacobian matrix for the different parameters\n  int OptimizePick::OptPeakFunctor::df(const Eigen::VectorXd &x, Eigen::MatrixXd &J)\n  {\n    std::cout << \"rows: \" << J.rows() << \" columns: \" << J.cols() << std::endl;//DEBUG\n    const std::vector<double> & positions = m_data->positions;\n    const std::vector<PeakShape> & peaks = m_data->peaks;\n    const OptimizationFunctions::PenaltyFactors & penalties = m_data->penalties;\n    // iterate over all points of the signal\n    for (size_t current_point = 0; current_point < positions.size(); current_point++)\n    {\n      double current_position = positions[current_point];\n\n      // iterate over all peaks\n      for (size_t current_peak = 0; current_peak < peaks.size(); current_peak++)\n      {\n        // Store the current parameters for this peak\n        double p_height = x(4 * current_peak);\n        double p_position = x(4 * current_peak + 3);\n        double p_width = (current_position <= p_position) ? x(4 * current_peak + 1)\n                          : x(4 * current_peak + 2);\n\n        // is it a Lorentz or a Sech - Peak?\n        if (peaks[current_peak].type == PeakShape::LORENTZ_PEAK)\n        {\n          double diff = current_position - p_position;\n          double denom_inv = 1. / (1. + pow(p_width * diff, 2));\n\n          double ddl_left = (current_position <= p_position)\n              ? -2 * p_height * pow(diff, 2) * p_width * pow(denom_inv, 2) : 0;\n\n          double ddl_right = (current_position  > p_position)\n              ? -2 * p_height * pow(diff, 2) * p_width * pow(denom_inv, 2) : 0;\n\n          double ddx0 = -2 * p_height * pow(p_width, 2) * diff * pow(denom_inv, 2);\n\n          J(current_point, 4 * current_peak) = denom_inv;\n          J(current_point, 4 * current_peak + 1) = ddl_left;\n          J(current_point, 4 * current_peak + 2) = ddl_right;\n          J(current_point, 4 * current_peak + 3) = ddx0;\n        }\n        else // It's a Sech - Peak\n        {\n          double diff = current_position - p_position;\n          double denom_inv = 1. / cosh(p_width * diff);\n\n          // The remaining computations are not stable if denom_inv == 0. In that case, we are far away from the peak\n          // and can assume that all derivatives vanish\n          double sinh_term = (fabs(denom_inv) < 1e-6) ? 0.0 : sinh(p_width * diff);\n          double ddl_left  = (current_position <= p_position)\n              ? -2 * p_height * sinh_term * diff * pow(denom_inv, 3) : 0;\n          double ddl_right = (current_position  > p_position)\n              ? -2 * p_height * sinh_term * diff * pow(denom_inv, 3) : 0;\n          double ddx0      = 2 * p_height * p_width * sinh_term * pow(denom_inv, 3);\n\n          J(current_point, 4 * current_peak) = pow(denom_inv, 2);\n          J(current_point, 4 * current_peak + 1) = ddl_left;\n          J(current_point, 4 * current_peak + 2) = ddl_right;\n          J(current_point, 4 * current_peak + 3) = ddx0;\n        }\n      }\n    }\n\n    // Now iterate over all peaks again to compute the penalties.\n    for (size_t current_peak = 0; current_peak < peaks.size(); current_peak++)\n    {\n      double p_width_left = x(4 * current_peak + 1);\n      double p_width_right = x(4 * current_peak + 2);\n      double p_position = x(4 * current_peak + 3);\n\n      double old_width_left = peaks[current_peak].left_width;\n      double old_width_right = peaks[current_peak].right_width;\n      double old_position = peaks[current_peak].mz_position;\n\n\n      double penalty_l = 2. * penalties.lWidth * (p_width_left - old_width_left);\n      double penalty_r = 2. * penalties.rWidth * (p_width_right - old_width_right);\n      double penalty_p = 0;\n      if (fabs(p_position - old_position) < 0.2)\n      {\n        penalty_p = 2. * penalties.pos * (p_position - old_position);\n      }\n\n      J(positions.size(), 4 * current_peak) = 0.;\n      J(positions.size(), 4 * current_peak + 1) = 100 * penalty_l;\n      J(positions.size(), 4 * current_peak + 2) = 100 * penalty_r;\n      J(positions.size(), 4 * current_peak + 3) = 100 * penalty_p;\n    }\n    return 0;\n  }\n}//namespace\n", "meta": {"hexsha": "dc28d5285ab9f140481d25ecd6aa796e3642cf74", "size": 13888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/TRANSFORMATIONS/RAW2PEAK/OptimizePick.cpp", "max_stars_repo_name": "rahul799/OpenMS", "max_stars_repo_head_hexsha": "962916f588789b6fab185d7f2d5fbac27226a99e", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_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/RAW2PEAK/OptimizePick.cpp", "max_issues_repo_name": "rahul799/OpenMS", "max_issues_repo_head_hexsha": "962916f588789b6fab185d7f2d5fbac27226a99e", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/source/TRANSFORMATIONS/RAW2PEAK/OptimizePick.cpp", "max_forks_repo_name": "rahul799/OpenMS", "max_forks_repo_head_hexsha": "962916f588789b6fab185d7f2d5fbac27226a99e", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0888888889, "max_line_length": 174, "alphanum_fraction": 0.6301123272, "num_tokens": 3483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2178674081999862}}
{"text": "#include <istream>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <algorithm>\n#include <iterator>\n#include <memory>\n#include <stdexcept>\n# if __cplusplus >= 201703L\n#   include <type_traits>\n# else\n#   include <boost/type_traits/is_nothrow_swappable.hpp>\n# endif\n\n#include <boost/lexical_cast.hpp>\n\n#include <boost/range/empty.hpp>\n#include <boost/range/size.hpp>\n\n#include <boost/algorithm/string/case_conv.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/algorithm/string/classification.hpp>\n\n#ifndef BRA_NO_MPI\n# include <yampi/communicator.hpp>\n# include <yampi/environment.hpp>\n#endif // BRA_NO_MPI\n\n#include <ket/qubit.hpp>\n#include <ket/control.hpp>\n#include <ket/utility/integer_log2.hpp>\n#include <ket/utility/integer_exp2.hpp>\n#include <ket/utility/generate_phase_coefficients.hpp>\n\n#include <bra/gates.hpp>\n#include <bra/state.hpp>\n#include <bra/gate/gate.hpp>\n#include <bra/gate/hadamard.hpp>\n#include <bra/gate/pauli_x.hpp>\n#include <bra/gate/pauli_y.hpp>\n#include <bra/gate/pauli_z.hpp>\n#include <bra/gate/s_gate.hpp>\n#include <bra/gate/adj_s_gate.hpp>\n#include <bra/gate/t_gate.hpp>\n#include <bra/gate/adj_t_gate.hpp>\n#include <bra/gate/u1.hpp>\n#include <bra/gate/u2.hpp>\n#include <bra/gate/u3.hpp>\n#include <bra/gate/phase_shift.hpp>\n#include <bra/gate/adj_phase_shift.hpp>\n#include <bra/gate/x_rotation_half_pi.hpp>\n#include <bra/gate/adj_x_rotation_half_pi.hpp>\n#include <bra/gate/y_rotation_half_pi.hpp>\n#include <bra/gate/adj_y_rotation_half_pi.hpp>\n#include <bra/gate/controlled_not.hpp>\n#include <bra/gate/controlled_phase_shift.hpp>\n#include <bra/gate/adj_controlled_phase_shift.hpp>\n#include <bra/gate/controlled_v.hpp>\n#include <bra/gate/adj_controlled_v.hpp>\n#include <bra/gate/toffoli.hpp>\n#include <bra/gate/projective_measurement.hpp>\n#include <bra/gate/measurement.hpp>\n#include <bra/gate/generate_events.hpp>\n#include <bra/gate/shor_box.hpp>\n#include <bra/gate/clear.hpp>\n#include <bra/gate/set.hpp>\n#include <bra/gate/depolarizing_channel.hpp>\n#include <bra/gate/exit.hpp>\n\n# if __cplusplus >= 201703L\n#   define BRA_is_nothrow_swappable std::is_nothrow_swappable\n# else\n#   define BRA_is_nothrow_swappable boost::is_nothrow_swappable\n# endif\n\n\nnamespace bra\n{\n  unsupported_mnemonic_error::unsupported_mnemonic_error(std::string const& mnemonic)\n    : std::runtime_error{(mnemonic + \" is not supported\").c_str()}\n  { }\n\n  wrong_mnemonics_error::wrong_mnemonics_error(::bra::gates::columns_type const& columns)\n    : std::runtime_error{generate_what_string(columns).c_str()}\n  { }\n\n  std::string wrong_mnemonics_error::generate_what_string(::bra::gates::columns_type const& columns)\n  {\n    auto result = std::string{};\n\n    auto const last = columns.end();\n    for (auto iter = columns.begin(); iter != last; ++iter)\n    {\n      result += *iter;\n      result += \" \";\n    }\n\n    return result;\n  }\n\n#ifndef BRA_NO_MPI\n  wrong_mpi_communicator_size_error::wrong_mpi_communicator_size_error()\n    : std::runtime_error{\"communicator size is wrong\"}\n  { }\n#endif // BRA_NO_MPI\n\n#ifndef BRA_NO_MPI\n  gates::gates()\n    : data_{}, num_qubits_{}, num_lqubits_{}, num_uqubits_{}, num_processes_per_unit_{1u},\n      initial_state_value_{}, initial_permutation_{}, phase_coefficients_{}, root_{}\n  { }\n\n  gates::gates(gates::allocator_type const& allocator)\n    : data_{allocator}, num_qubits_{}, num_lqubits_{}, num_uqubits_{}, num_processes_per_unit_{1u},\n      initial_state_value_{}, initial_permutation_{}, phase_coefficients_{}, root_{}\n  { }\n\n  gates::gates(gates&& other, gates::allocator_type const& allocator)\n      : data_{std::move(other.data_), allocator},\n        num_qubits_{std::move(other.num_qubits_)},\n        num_lqubits_{std::move(other.num_lqubits_)},\n        num_uqubits_{std::move(other.num_uqubits_)},\n        num_processes_per_unit_{std::move(other.num_processes_per_unit_)},\n        initial_state_value_{std::move(other.initial_state_value_)},\n        initial_permutation_{std::move(other.initial_permutation_)},\n        phase_coefficients_{std::move(other.phase_coefficients_)},\n        root_{std::move(other.root_)}\n  { }\n#else // BRA_NO_MPI\n  gates::gates()\n    : data_{}, num_qubits_{},\n      initial_state_value_{}, phase_coefficients_{}\n  { }\n\n  gates::gates(gates::allocator_type const& allocator)\n    : data_{allocator}, num_qubits_{},\n      initial_state_value_{}, phase_coefficients_{}\n  { }\n\n  gates::gates(gates&& other, gates::allocator_type const& allocator)\n      : data_{std::move(other.data_), allocator},\n        num_qubits_{std::move(other.num_qubits_)},\n        initial_state_value_{std::move(other.initial_state_value_)},\n        phase_coefficients_{std::move(other.phase_coefficients_)}\n  { }\n#endif // BRA_NO_MPI\n\n#ifndef BRA_NO_MPI\n  gates::gates(\n    std::istream& input_stream,\n    bit_integer_type num_uqubits, unsigned int num_processes_per_unit,\n    yampi::environment const& environment,\n    yampi::rank const root, yampi::communicator const& communicator,\n    size_type const num_reserved_gates)\n    : data_{}, num_qubits_{}, num_lqubits_{},\n      num_uqubits_{num_uqubits}, num_processes_per_unit_{num_processes_per_unit},\n      initial_state_value_{}, initial_permutation_{}, phase_coefficients_{}, root_{root}\n  {\n    assert(num_processes_per_unit >= 1u);\n    assign(input_stream, environment, communicator, num_reserved_gates);\n  }\n#else // BRA_NO_MPI\n  gates::gates(std::istream& input_stream)\n    : data_{}, num_qubits_{},\n      initial_state_value_{}, phase_coefficients_{}\n  { assign(input_stream, size_type{0u}); }\n\n  gates::gates(std::istream& input_stream, size_type const num_reserved_gates)\n    : data_{}, num_qubits_{},\n      initial_state_value_{}, phase_coefficients_{}\n  { assign(input_stream, num_reserved_gates); }\n#endif // BRA_NO_MPI\n\n  bool gates::operator==(gates const& other) const\n  {\n#ifndef BRA_NO_MPI\n    return data_ == other.data_\n      and num_qubits_ == other.num_qubits_\n      and num_lqubits_ == other.num_lqubits_\n      and num_uqubits_ == other.num_uqubits_\n      and num_processes_per_unit_ == other.num_processes_per_unit_\n      and initial_state_value_ == other.initial_state_value_\n      and initial_permutation_ == other.initial_permutation_\n      and phase_coefficients_ == other.phase_coefficients_\n      and root_ == other.root_;\n#else // BRA_NO_MPI\n    return data_ == other.data_\n      and num_qubits_ == other.num_qubits_\n      and initial_state_value_ == other.initial_state_value_\n      and phase_coefficients_ == other.phase_coefficients_;\n#endif // BRA_NO_MPI\n  }\n\n#ifndef BRA_NO_MPI\n  void gates::num_qubits(\n    bit_integer_type const new_num_qubits,\n    yampi::communicator const& communicator, yampi::environment const& environment)\n  {\n    auto const num_gqubits\n      = ket::utility::integer_log2<bit_integer_type>(\n          communicator.size(environment) / num_processes_per_unit_);\n    set_num_qubits_params(new_num_qubits - num_gqubits - num_uqubits_, num_gqubits, communicator, environment);\n  }\n\n  void gates::num_lqubits(\n    bit_integer_type const new_num_lqubits,\n    yampi::communicator const& communicator, yampi::environment const& environment)\n  {\n    set_num_qubits_params(\n      new_num_lqubits,\n      ket::utility::integer_log2<bit_integer_type>(\n        communicator.size(environment) / num_processes_per_unit_),\n      communicator, environment);\n  }\n#else // BRA_NO_MPI\n  void gates::num_qubits(bit_integer_type const new_num_qubits)\n  { set_num_qubits_params(new_num_qubits); }\n#endif // BRA_NO_MPI\n\n#ifndef BRA_NO_MPI\n  void gates::set_num_qubits_params(\n    bit_integer_type const new_num_lqubits, bit_integer_type const num_gqubits,\n    yampi::communicator const& communicator, yampi::environment const& environment)\n  {\n    if (ket::utility::integer_exp2<bit_integer_type>(num_gqubits) * num_processes_per_unit_\n        != static_cast<bit_integer_type>(communicator.size(environment)))\n      throw wrong_mpi_communicator_size_error{};\n\n    num_lqubits_ = new_num_lqubits;\n    num_qubits_ = new_num_lqubits + num_uqubits_ + num_gqubits;\n    ket::utility::generate_phase_coefficients(phase_coefficients_, num_qubits_);\n\n    initial_permutation_.clear();\n    initial_permutation_.reserve(num_qubits_);\n    for (auto bit = bit_integer_type{0u}; bit < num_qubits_; ++bit)\n      initial_permutation_.push_back(permutated_qubit_type{bit});\n  }\n#else // BRA_NO_MPI\n  void gates::set_num_qubits_params(bit_integer_type const new_num_qubits)\n  {\n    num_qubits_ = new_num_qubits;\n    ket::utility::generate_phase_coefficients(phase_coefficients_, num_qubits_);\n  }\n#endif // BRA_NO_MPI\n\n#ifndef BRA_NO_MPI\n  void gates::assign(\n    std::istream& input_stream, yampi::environment const& environment,\n    yampi::communicator const& communicator, size_type const num_reserved_gates)\n#else // BRA_NO_MPI\n  void gates::assign(std::istream& input_stream, size_type const num_reserved_gates)\n#endif // BRA_NO_MPI\n  {\n    data_.clear();\n    data_.reserve(num_reserved_gates);\n\n    auto line = std::string{};\n    auto columns = columns_type{};\n    columns.reserve(10u);\n\n    while (std::getline(input_stream, line))\n    {\n      if (line.empty())\n        continue;\n\n      line.erase(std::find(line.begin(), line.end(), '!'), line.end());\n      boost::algorithm::trim(line);\n      if (line.empty())\n        continue;\n\n      boost::algorithm::split(\n        columns, line, boost::algorithm::is_space(),\n        boost::algorithm::token_compress_on);\n\n      if (boost::empty(columns))\n        continue;\n\n      boost::algorithm::to_upper(columns.front());\n      auto const& first_mnemonic = columns.front();\n      if (first_mnemonic == \"QUBITS\")\n      {\n#ifndef BRA_NO_MPI\n        num_qubits(\n          static_cast< ::bra::state::bit_integer_type >(read_num_qubits(columns)),\n          communicator, environment);\n#else // BRA_NO_MPI\n        num_qubits(\n          static_cast< ::bra::state::bit_integer_type >(read_num_qubits(columns)));\n#endif // BRA_NO_MPI\n      }\n      else if (first_mnemonic == \"INITIAL\") // INITIAL STATE\n        initial_state_value_\n          = static_cast< ::bra::state::state_integer_type >(read_initial_state_value(columns));\n      else if (first_mnemonic == \"MPIPROCESSES\")\n      {\n        read_num_mpi_processes(columns);\n        // ignore this statement\n      }\n      else if (first_mnemonic == \"MPISWAPBUFFER\")\n      {\n        read_mpi_buffer_size(columns);\n        // ignore this statement\n      }\n      else if (first_mnemonic == \"BIT\") // BIT ASSIGNMENT\n      {\n        auto const statement = read_bit_statement(columns);\n\n        if (statement == ::bra::bit_statement::assignment)\n        {\n#ifndef BRA_NO_MPI\n          initial_permutation_ = read_initial_permutation(columns);\n#endif\n        }\n      }\n      else if (first_mnemonic == \"PERMUTATION\")\n        throw unsupported_mnemonic_error{first_mnemonic};\n      else if (first_mnemonic == \"RANDOM\") // RANDOM PERMUTATION\n        throw unsupported_mnemonic_error{first_mnemonic};\n      else if (first_mnemonic == \"I\")\n        continue;\n      else if (first_mnemonic == \"H\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::hadamard{read_hadamard(columns)}});\n      else if (first_mnemonic == \"X\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::pauli_x{read_pauli_x(columns)}});\n      else if (first_mnemonic == \"Y\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::pauli_y{read_pauli_y(columns)}});\n      else if (first_mnemonic == \"Z\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::pauli_z{read_pauli_z(columns)}});\n      else if (first_mnemonic == \"S\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::s_gate{\n              phase_coefficients_[2u], read_s_gate(columns)}});\n      else if (first_mnemonic == \"S+\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::adj_s_gate{\n              phase_coefficients_[2u], read_adj_s_gate(columns)}});\n      else if (first_mnemonic == \"T\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::t_gate{\n              phase_coefficients_[3u], read_t_gate(columns)}});\n      else if (first_mnemonic == \"T+\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::adj_t_gate{\n              phase_coefficients_[3u], read_adj_t_gate(columns)}});\n      else if (first_mnemonic == \"U1\")\n      {\n        auto target = qubit_type{};\n        auto phase = real_type{};\n        std::tie(target, phase) = read_u1(columns);\n\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::u1{phase, target}});\n      }\n      else if (first_mnemonic == \"U2\")\n      {\n        auto target = qubit_type{};\n        auto phase1 = real_type{};\n        auto phase2 = real_type{};\n        std::tie(target, phase1, phase2) = read_u2(columns);\n\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::u2{phase1, phase2, target}});\n      }\n      else if (first_mnemonic == \"U3\")\n      {\n        auto target = qubit_type{};\n        auto phase1 = real_type{};\n        auto phase2 = real_type{};\n        auto phase3 = real_type{};\n        std::tie(target, phase1, phase2, phase3) = read_u3(columns);\n\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::u3{phase1, phase2, phase3, target}});\n      }\n      else if (first_mnemonic == \"R\" or first_mnemonic == \"+R\")\n      {\n        auto target = qubit_type{};\n        auto phase_exponent = int{};\n        std::tie(target, phase_exponent) = read_phase_shift(columns);\n\n        if (phase_exponent >= 0)\n          data_.push_back(std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::phase_shift{\n              phase_exponent, phase_coefficients_[phase_exponent], target}});\n        else\n        {\n          phase_exponent *= -1;\n          data_.push_back(std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::adj_phase_shift{\n              phase_exponent, phase_coefficients_[phase_exponent], target}});\n        }\n      }\n      else if (first_mnemonic == \"-R\")\n      {\n        auto target = qubit_type{};\n        auto phase_exponent = int{};\n        std::tie(target, phase_exponent) = read_phase_shift(columns);\n\n        if (phase_exponent >= 0)\n          data_.push_back(std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::adj_phase_shift{\n              phase_exponent, phase_coefficients_[phase_exponent], target}});\n        else\n        {\n          phase_exponent *= -1;\n          data_.push_back(std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::phase_shift{\n              phase_exponent, phase_coefficients_[phase_exponent], target}});\n        }\n      }\n      else if (first_mnemonic == \"+X\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::x_rotation_half_pi{read_x_rotation_half_pi(columns)}});\n      else if (first_mnemonic == \"-X\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::adj_x_rotation_half_pi{read_adj_x_rotation_half_pi(columns)}});\n      else if (first_mnemonic == \"+Y\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::y_rotation_half_pi{read_y_rotation_half_pi(columns)}});\n      else if (first_mnemonic == \"-Y\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::adj_y_rotation_half_pi{read_adj_y_rotation_half_pi(columns)}});\n      else if (first_mnemonic == \"CNOT\")\n      {\n        auto control = control_qubit_type{};\n        auto target = qubit_type{};\n        std::tie(control, target) = read_controlled_not(columns);\n\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::controlled_not{target, control}});\n      }\n      else if (first_mnemonic == \"U\")\n      {\n        auto control = control_qubit_type{};\n        auto target = qubit_type{};\n        auto phase_exponent = int{};\n        std::tie(control, target, phase_exponent) = read_controlled_phase_shift(columns);\n\n        if (phase_exponent >= 0)\n          data_.push_back(\n            std::unique_ptr< ::bra::gate::gate >{\n              new ::bra::gate::controlled_phase_shift{\n                phase_exponent, phase_coefficients_[phase_exponent], target, control}});\n        else\n        {\n          phase_exponent *= -1;\n          data_.push_back(\n            std::unique_ptr< ::bra::gate::gate >{\n              new ::bra::gate::adj_controlled_phase_shift{\n                phase_exponent, phase_coefficients_[phase_exponent], target, control}});\n        }\n      }\n      else if (first_mnemonic == \"V\")\n      {\n        auto control = control_qubit_type{};\n        auto target = qubit_type{};\n        auto phase_exponent = int{};\n        std::tie(control, target, phase_exponent) = read_controlled_v(columns);\n\n        if (phase_exponent >= 0)\n          data_.push_back(\n            std::unique_ptr< ::bra::gate::gate >{\n              new ::bra::gate::controlled_v{\n                phase_exponent, phase_coefficients_[phase_exponent], target, control}});\n        else\n        {\n          phase_exponent *= -1;\n          data_.push_back(\n            std::unique_ptr< ::bra::gate::gate >{\n              new ::bra::gate::adj_controlled_v{\n                phase_exponent, phase_coefficients_[phase_exponent], target, control}});\n        }\n      }\n      else if (first_mnemonic == \"TOFFOLI\")\n      {\n        auto control1 = control_qubit_type{};\n        auto control2 = control_qubit_type{};\n        auto target = qubit_type{};\n        std::tie(control1, control2, target) = read_toffoli(columns);\n\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::toffoli{target, control1, control2}});\n      }\n      else if (first_mnemonic == \"M\")\n      {\n#ifndef BRA_NO_MPI\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::projective_measurement{read_projective_measurement(columns), root_}});\n#else // BRA_NO_MPI\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::projective_measurement{read_projective_measurement(columns)}});\n#endif // BRA_NO_MPI\n      }\n      else if (first_mnemonic == \"SHORBOX\")\n      {\n        auto num_exponent_qubits = bit_integer_type{};\n        auto divisor = state_integer_type{};\n        auto base = state_integer_type{};\n        std::tie(num_exponent_qubits, divisor, base) = read_shor_box(columns);\n\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::shor_box{num_exponent_qubits, divisor, base}});\n      }\n      else if (first_mnemonic == \"BEGIN\") // BEGIN MEASUREMENT/LEARNING MACHINE\n      {\n        auto const statement = read_begin_statement(columns);\n\n        if (statement == ::bra::begin_statement::measurement)\n        {\n#ifndef BRA_NO_MPI\n          data_.push_back(\n            std::unique_ptr< ::bra::gate::gate >{new ::bra::gate::measurement{root_}});\n#else // BRA_NO_MPI\n          data_.push_back(\n            std::unique_ptr< ::bra::gate::gate >{new ::bra::gate::measurement{}});\n#endif // BRA_NO_MPI\n        }\n        else if (statement == ::bra::begin_statement::learning_machine)\n          throw unsupported_mnemonic_error{first_mnemonic};\n      }\n      else if (first_mnemonic == \"DO\") // DO MEASUREMENT\n      {\n        /*\n        auto const statement = read_do_statement(columns);\n\n        if (statement == do_statement::error)\n          throw wrong_mnemonics_error{columns};\n        else if (statement == do_statement::measurement)\n          throw unsupported_mnemonic_error{first_mnemonic};\n          */\n        throw unsupported_mnemonic_error{first_mnemonic};\n      }\n      else if (first_mnemonic == \"END\") // END MEASUREMENT/LEARNING MACHINE\n      {\n        /*\n        auto const statement = read_end_statement(columns);\n\n        if (statement == ::bra::end_statement::measurement)\n        {\n#ifndef BRA_NO_MPI\n          data_.push_back(std::make_unique< ::bra::gate::measurement >(root_));\n#else // BRA_NO_MPI\n          data_.push_back(std::make_unique< ::bra::gate::measurement >());\n#endif // BRA_NO_MPI\n        }\n        else if (statement == ::bra::end_statement::learning_machine)\n          throw unsupported_mnemonic_error{first_mnemonic};\n*/\n        throw unsupported_mnemonic_error{first_mnemonic};\n      }\n      else if (first_mnemonic == \"GENERATE\") // GENERATE EVENTS\n      {\n        auto statement = ::bra::generate_statement{};\n        auto num_events = int{};\n        auto seed = int{};\n        std::tie(statement, num_events, seed) = read_generate_statement(columns);\n\n        if (statement == ::bra::generate_statement::events)\n        {\n#ifndef BRA_NO_MPI\n          data_.push_back(\n            std::unique_ptr< ::bra::gate::gate >{\n              new ::bra::gate::generate_events{root_, num_events, seed}});\n#else // BRA_NO_MPI\n          data_.push_back(\n            std::unique_ptr< ::bra::gate::gate >{\n              new ::bra::gate::generate_events{num_events, seed}});\n#endif // BRA_NO_MPI\n          break;\n        }\n      }\n      else if (first_mnemonic == \"CLEAR\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::clear{read_clear(columns)}});\n      else if (first_mnemonic == \"SET\")\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{\n            new ::bra::gate::set{read_set(columns)}});\n      else if (first_mnemonic == \"DEPOLARIZING\")\n      {\n        auto statement = ::bra::depolarizing_statement{};\n        auto px = real_type{};\n        auto py = real_type{};\n        auto pz = real_type{};\n        auto seed = int{};\n        std::tie(statement, px, py, pz, seed) = read_depolarizing_statement(columns);\n\n        if (statement == ::bra::depolarizing_statement::channel)\n          data_.push_back(\n            std::unique_ptr< ::bra::gate::gate >{\n              new ::bra::gate::depolarizing_channel{px, py, pz, seed}});\n        else\n          throw unsupported_mnemonic_error{first_mnemonic};\n      }\n      else if (first_mnemonic == \"EXIT\")\n      {\n        if (boost::size(columns) != 1u)\n          throw wrong_mnemonics_error{columns};\n\n#ifndef BRA_NO_MPI\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{new ::bra::gate::exit{root_}});\n#else // BRA_NO_MPI\n        data_.push_back(\n          std::unique_ptr< ::bra::gate::gate >{new ::bra::gate::exit{}});\n#endif // BRA_NO_MPI\n        break;\n      }\n      else\n        throw unsupported_mnemonic_error{first_mnemonic};\n    }\n  }\n\n  void gates::swap(gates& other)\n    noexcept(\n      BRA_is_nothrow_swappable<data_type>::value\n      and BRA_is_nothrow_swappable<bit_integer_type>::value\n      and BRA_is_nothrow_swappable<state_integer_type>::value\n      and BRA_is_nothrow_swappable<qubit_type>::value)\n  {\n    using std::swap;\n#ifndef BRA_NO_MPI\n    swap(data_, other.data_);\n    swap(num_qubits_, other.num_qubits_);\n    swap(num_lqubits_, other.num_lqubits_);\n    swap(initial_state_value_, other.initial_state_value_);\n    swap(initial_permutation_, other.initial_permutation_);\n    swap(phase_coefficients_, other.phase_coefficients_);\n    swap(root_, other.root_);\n#else // BRA_NO_MPI\n    swap(data_, other.data_);\n    swap(num_qubits_, other.num_qubits_);\n    swap(initial_state_value_, other.initial_state_value_);\n    swap(phase_coefficients_, other.phase_coefficients_);\n#endif // BRA_NO_MPI\n  }\n\n  gates::bit_integer_type gates::read_num_qubits(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 2u)\n      throw ::bra::wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    return boost::lexical_cast<bit_integer_type>(*++iter);\n  }\n\n  gates::state_integer_type gates::read_initial_state_value(gates::columns_type& columns) const\n  {\n    if (boost::size(columns) != 3u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    boost::algorithm::to_upper(*++iter);\n    if (columns[1] != \"STATE\")\n      throw wrong_mnemonics_error{columns};\n\n    return boost::lexical_cast<state_integer_type>(*++iter);\n  }\n\n  gates::bit_integer_type gates::read_num_mpi_processes(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 2u)\n      throw ::bra::wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    return boost::lexical_cast<bit_integer_type>(*++iter);\n  }\n\n  gates::state_integer_type gates::read_mpi_buffer_size(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 2u)\n      throw ::bra::wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    return boost::lexical_cast<state_integer_type>(*++iter);\n  }\n\n#ifndef BRA_NO_MPI\n  std::vector<gates::permutated_qubit_type>\n  gates::read_initial_permutation(gates::columns_type const& columns) const\n  {\n    auto result = std::vector<permutated_qubit_type>{};\n    result.reserve(boost::size(columns)-2u);\n\n    auto iter = std::begin(columns);\n    ++iter;\n    ++iter;\n\n    auto const last = std::end(columns);\n    for (; iter != last; ++iter)\n      result.push_back(static_cast<permutated_qubit_type>(boost::lexical_cast<bit_integer_type>(*iter)));\n\n    return result;\n  }\n#endif\n\n  gates::qubit_type gates::read_target(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 2u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    auto const target = boost::lexical_cast<bit_integer_type>(*++iter);\n\n    return ket::make_qubit<state_integer_type>(target);\n  }\n\n  std::tuple<gates::qubit_type, gates::real_type>\n  gates::read_target_phase(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 3u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    auto const target = boost::lexical_cast<bit_integer_type>(*++iter);\n    auto const phase = boost::lexical_cast<real_type>(*++iter);\n\n    return std::make_tuple(ket::make_qubit<state_integer_type>(target), phase);\n  }\n\n  std::tuple<gates::qubit_type, gates::real_type, gates::real_type>\n  gates::read_target_2phases(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 4u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    auto const target = boost::lexical_cast<bit_integer_type>(*++iter);\n    auto const phase1 = boost::lexical_cast<real_type>(*++iter);\n    auto const phase2 = boost::lexical_cast<real_type>(*++iter);\n\n    return std::make_tuple(ket::make_qubit<state_integer_type>(target), phase1, phase2);\n  }\n\n  std::tuple<gates::qubit_type, gates::real_type, gates::real_type, gates::real_type>\n  gates::read_target_3phases(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 5u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    auto const target = boost::lexical_cast<bit_integer_type>(*++iter);\n    auto const phase1 = boost::lexical_cast<real_type>(*++iter);\n    auto const phase2 = boost::lexical_cast<real_type>(*++iter);\n    auto const phase3 = boost::lexical_cast<real_type>(*++iter);\n\n    return std::make_tuple(ket::make_qubit<state_integer_type>(target), phase1, phase2, phase3);\n  }\n\n  std::tuple<gates::qubit_type, int> gates::read_target_phaseexp(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 3u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    auto const target = boost::lexical_cast<bit_integer_type>(*++iter);\n    auto const phase_exponent = boost::lexical_cast<int>(*++iter);\n\n    return std::make_tuple(ket::make_qubit<state_integer_type>(target), phase_exponent);\n  }\n\n  std::tuple<gates::control_qubit_type, gates::qubit_type> gates::read_control_target(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 3u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    auto const control = boost::lexical_cast<bit_integer_type>(*++iter);\n    auto const target = boost::lexical_cast<bit_integer_type>(*++iter);\n\n    return std::make_tuple(\n      ket::make_control(ket::make_qubit<state_integer_type>(control)),\n      ket::make_qubit<state_integer_type>(target));\n  }\n\n  std::tuple<gates::control_qubit_type, gates::qubit_type, int>\n  gates::read_control_target_phaseexp(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 4u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    auto const control = boost::lexical_cast<bit_integer_type>(*++iter);\n    auto const target = boost::lexical_cast<bit_integer_type>(*++iter);\n    auto const phase_exponent = boost::lexical_cast<int>(*++iter);\n\n    return std::make_tuple(\n      ket::make_control(ket::make_qubit<state_integer_type>(control)),\n      ket::make_qubit<state_integer_type>(target),\n      phase_exponent);\n  }\n\n  std::tuple<gates::control_qubit_type, gates::control_qubit_type, gates::qubit_type>\n  gates::read_2controls_target(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 4u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    auto const control1 = boost::lexical_cast<bit_integer_type>(*++iter);\n    auto const control2 = boost::lexical_cast<bit_integer_type>(*++iter);\n    auto const target = boost::lexical_cast<bit_integer_type>(*++iter);\n\n    return std::make_tuple(\n      ket::make_control(ket::make_qubit<state_integer_type>(control1)),\n      ket::make_control(ket::make_qubit<state_integer_type>(control2)),\n      ket::make_qubit<state_integer_type>(target));\n  }\n\n  ::bra::begin_statement gates::read_begin_statement(gates::columns_type& columns) const\n  {\n    auto const column_size = boost::size(columns);\n\n    if (column_size <= 1u or column_size >= 4u)\n      throw wrong_mnemonics_error{columns};\n\n    if (column_size == 3u)\n    {\n      auto iter = std::begin(columns);\n      boost::algorithm::to_upper(*++iter);\n      if (*iter == \"LEARNING\")\n      {\n        boost::algorithm::to_upper(*++iter);\n\n        if (*iter == \"MACHINE\")\n          return ::bra::begin_statement::learning_machine;\n        else\n          throw wrong_mnemonics_error{columns};\n      }\n      else\n        throw wrong_mnemonics_error{columns};\n    }\n\n    // if (column_size == 2u)\n    auto iter = std::begin(columns);\n    boost::algorithm::to_upper(*++iter);\n\n    if (*iter != \"MEASUREMENT\")\n      throw wrong_mnemonics_error{columns};\n\n    return ::bra::begin_statement::measurement;\n  }\n\n  ::bra::bit_statement gates::read_bit_statement(gates::columns_type& columns) const\n  {\n    if (boost::size(columns) <= 1u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    boost::algorithm::to_upper(*++iter);\n\n    if (*iter != \"ASSIGNMENT\")\n      throw wrong_mnemonics_error{columns};\n\n    return ::bra::bit_statement::assignment;\n  }\n\n  std::tuple<gates::bit_integer_type, gates::state_integer_type, gates::state_integer_type>\n  gates::read_shor_box(gates::columns_type const& columns) const\n  {\n    if (boost::size(columns) != 4u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    auto const num_exponent_qubits = boost::lexical_cast<bit_integer_type>(*++iter);\n    auto const divisor = boost::lexical_cast<state_integer_type>(*++iter);\n    auto const base = boost::lexical_cast<state_integer_type>(*++iter);\n\n    return std::make_tuple(num_exponent_qubits, divisor, base);\n  }\n\n  std::tuple< ::bra::generate_statement, int, int > gates::read_generate_statement(gates::columns_type& columns) const\n  {\n    if (boost::size(columns) != 4u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = std::begin(columns);\n    boost::algorithm::to_upper(*++iter);\n\n    if (*iter != \"EVENTS\")\n      throw wrong_mnemonics_error{columns};\n\n    auto const num_events = boost::lexical_cast<int>(*++iter);\n    auto const seed = boost::lexical_cast<int>(*++iter);\n    return std::make_tuple(::bra::generate_statement::events, num_events, seed);\n  }\n\n  std::tuple< ::bra::depolarizing_statement, gates::real_type, gates::real_type, gates::real_type, int >\n  gates::read_depolarizing_statement(gates::columns_type& columns) const\n  {\n    if (boost::size(columns) <= 2u)\n      throw wrong_mnemonics_error{columns};\n\n    auto iter = columns.cbegin();\n    auto present_string = std::string{*++iter}; // present_string == \"CHANNEL\"\n    boost::algorithm::to_upper(present_string);\n\n    if (present_string != \"CHANNEL\")\n      throw wrong_mnemonics_error{columns};\n\n    auto px = real_type{};\n    auto py = real_type{};\n    auto pz = real_type{};\n    auto seed = -1;\n    auto is_px_checked = false;\n    auto is_py_checked = false;\n    auto is_pz_checked = false;\n    auto is_seed_checked = false;\n\n    present_string = *++iter; // present_string == \"P_*\" or \"P_*=\" or \"P_*=0.xxx\" or \"P_*=0.xxx,\" or \"P_*=0.xxx,...\"\n    auto probability_string = std::string{\"    \"};\n    auto const last = columns.cend();\n    while (iter != last)\n    {\n      auto string_found = std::find(present_string.cbegin(), present_string.cend(), '=');\n      probability_string.assign(present_string.cbegin(), string_found);\n      boost::algorithm::to_upper(probability_string);\n      if (probability_string == \"P_X\")\n      {\n        if (is_px_checked)\n          throw wrong_mnemonics_error{columns};\n\n        ::bra::gates_detail::read_depolarizing_statement(px, present_string, iter, last, string_found, columns);\n        if (px < 0.0 or px > 1.0)\n          throw wrong_mnemonics_error{columns};\n\n        is_px_checked = true;\n      }\n      else if (probability_string == \"P_Y\")\n      {\n        if (is_py_checked)\n          throw wrong_mnemonics_error{columns};\n\n        ::bra::gates_detail::read_depolarizing_statement(py, present_string, iter, last, string_found, columns);\n        if (py < 0.0 or py > 1.0)\n          throw wrong_mnemonics_error{columns};\n\n        is_py_checked = true;\n      }\n      else if (probability_string == \"P_Z\")\n      {\n        if (is_pz_checked)\n          throw wrong_mnemonics_error{columns};\n\n        ::bra::gates_detail::read_depolarizing_statement(pz, present_string, iter, last, string_found, columns);\n        if (pz < 0.0 or pz > 1.0)\n          throw wrong_mnemonics_error{columns};\n\n        is_pz_checked = true;\n      }\n      else if (probability_string == \"SEED\")\n      {\n        if (is_seed_checked)\n          throw wrong_mnemonics_error{columns};\n\n        ::bra::gates_detail::read_depolarizing_statement(seed, present_string, iter, last, string_found, columns);\n        is_seed_checked = true;\n      }\n      else\n        throw wrong_mnemonics_error{columns};\n    }\n\n    if (is_px_checked and is_py_checked and is_pz_checked and px + py + pz > 1.0)\n      throw wrong_mnemonics_error{columns};\n    else if (is_px_checked and is_py_checked and not is_pz_checked and px + py < 1.0)\n      pz = 1.0 - px - py;\n    else if (is_px_checked and not is_py_checked and is_pz_checked and px + pz < 1.0)\n      py = 1.0 - px - pz;\n    else if (not is_px_checked and is_py_checked and is_pz_checked and py + pz < 1.0)\n      px = 1.0 - py - pz;\n    else\n      throw wrong_mnemonics_error{columns};\n\n    return std::make_tuple(::bra::depolarizing_statement::channel, px, py, pz, seed);\n  }\n} // namespace bra\n\n\n# undef BRA_is_nothrow_swappable\n", "meta": {"hexsha": "a81b274211098729decf9b27cf8c037ffc7913e6", "size": 35743, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bra/src/gates.cpp", "max_stars_repo_name": "naoki-yoshioka/bracket", "max_stars_repo_head_hexsha": "6eff40e6ee5768744974e9d79bf6ff892bd67390", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-26T21:50:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T07:35:14.000Z", "max_issues_repo_path": "bra/src/gates.cpp", "max_issues_repo_name": "naoki-yoshioka/braket", "max_issues_repo_head_hexsha": "d4fbf1b19691e71dbc6fa62d8a66c7c61b6c4d68", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 50.0, "max_issues_repo_issues_event_min_datetime": "2018-06-05T12:23:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-05T15:04:30.000Z", "max_forks_repo_path": "bra/src/gates.cpp", "max_forks_repo_name": "naoki-yoshioka/bracket", "max_forks_repo_head_hexsha": "6eff40e6ee5768744974e9d79bf6ff892bd67390", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5298210736, "max_line_length": 127, "alphanum_fraction": 0.6580868981, "num_tokens": 9106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21785180419547528}}
{"text": "//\r\n// $Id: IsotopeCalculator.cpp 2051 2010-06-15 18:39:13Z chambm $ \r\n//\r\n//\r\n// Original author: Darren Kessner <darren@proteowizard.org>\r\n//\r\n// Copyright 2006 Louis Warschaw Prostate Cancer Center\r\n//   Cedars Sinai Medical Center, Los Angeles, California  90048\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\"); \r\n// you may not use this file except in compliance with the License. \r\n// You may obtain a copy of the License at \r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software \r\n// distributed under the License is distributed on an \"AS IS\" BASIS, \r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \r\n// See the License for the specific language governing permissions and \r\n// limitations under the License.\r\n//\r\n\r\n\r\n#define PWIZ_SOURCE\r\n\r\n#include \"IsotopeCalculator.hpp\"\r\n#include \"IsotopeTable.hpp\"\r\n#include \"Ion.hpp\"\r\n#include \"pwiz/utility/misc/Std.hpp\"\r\n#include <boost/ptr_container/ptr_vector.hpp>\r\n\r\n\r\nnamespace pwiz {\r\nnamespace chemistry {\r\n\r\n\r\nusing boost::ptr_vector;\r\n\r\n\r\nclass IsotopeCalculator::Impl\r\n{\r\n    public:\r\n\r\n    Impl(double abundanceCutoff, double massPrecision);\r\n\r\n    MassDistribution distribution(const Formula& formula,\r\n                                  int chargeState,\r\n                                  int normalization) const;\r\n    private:\r\n\r\n    double abundanceCutoff_;\r\n    double massPrecision_; \r\n\r\n    ptr_vector<IsotopeTable> tableStorage_;\r\n    typedef map<Element::Type, const IsotopeTable*> TableMap;\r\n    TableMap tableMap_;\r\n\r\n    void initializeIsotopeTables();\r\n    MassDistribution distributionManually(Element::Type e, int atomCount) const;\r\n};\r\n\r\n\r\nIsotopeCalculator::Impl::Impl(double abundanceCutoff, double massPrecision)\r\n:   abundanceCutoff_(abundanceCutoff),\r\n    massPrecision_(massPrecision)\r\n{\r\n    initializeIsotopeTables();\r\n}\r\n\r\n\r\nnamespace {\r\n\r\nbool hasLessMass(const MassAbundance& a, const MassAbundance& b)\r\n{\r\n    return a.mass < b.mass;\r\n}\r\n\r\nMassAbundance coalesce(const MassAbundance& a, const MassAbundance& b)\r\n{\r\n    double abundance = a.abundance + b.abundance;\r\n    double mass = (a.abundance*a.mass + b.abundance*b.mass) / abundance;\r\n    return MassAbundance(mass, abundance);\r\n}\r\n\r\nclass Distinct\r\n{\r\n    public:\r\n\r\n    Distinct(double mass, double precision) \r\n    :   mass_(mass), precision_(precision) \r\n    {}\r\n\r\n    bool operator()(const MassAbundance& ma)\r\n    {\r\n        return fabs(ma.mass - mass_) > precision_;\r\n    }\r\n    \r\n    private:\r\n    double mass_;\r\n    double precision_;\r\n};\r\n\r\nMassDistribution coalesceDistribution(const MassDistribution& md, double precision)\r\n{\r\n    // assumes MassDistribution md is sorted by mass!\r\n\r\n    MassDistribution result;\r\n\r\n    for (MassDistribution::const_iterator it=md.begin(); it!=md.end();)\r\n    {\r\n        Distinct distinct(it->mass, precision);\r\n        MassDistribution::const_iterator next = find_if(it, md.end(), distinct);     \r\n        result.push_back(accumulate(it, next, MassAbundance(), coalesce));\r\n        it = next;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nclass Convolve\r\n{\r\n    public:\r\n\r\n    Convolve(double cutoff = 0)\r\n    :   cutoff_(cutoff)\r\n    {}\r\n\r\n    MassDistribution operator()(const MassDistribution& m, const MassDistribution& n)\r\n    {\r\n        if (m.empty()) return n;\r\n        if (n.empty()) return m;\r\n\r\n        MassDistribution result;\r\n\r\n        // we could break out of these loops early if the mass distributions \r\n        // are sorted by abundance\r\n\r\n        for (MassDistribution::const_iterator i=m.begin(); i!=m.end(); ++i)\r\n        for (MassDistribution::const_iterator j=n.begin(); j!=n.end(); ++j)\r\n        {\r\n            double mass = i->mass + j->mass;\r\n            double abundance = i->abundance * j->abundance;\r\n            if (abundance > cutoff_)\r\n                result.push_back(MassAbundance(mass, abundance));\r\n        }\r\n\r\n        return result;\r\n    }\r\n\r\n    private:\r\n    double cutoff_;\r\n};\r\n\r\nclass Ionize\r\n{\r\n    public:\r\n\r\n    Ionize(int chargeState)\r\n    :   chargeState_(chargeState)\r\n    {}\r\n\r\n    void operator()(MassAbundance& ma) const\r\n    {\r\n        ma.mass = Ion::mz(ma.mass, chargeState_);\r\n    }\r\n\r\n    private:\r\n    int chargeState_;\r\n};\r\n\r\nvoid normalize(MassDistribution& md, int normalization)\r\n{\r\n    if (md.empty()) \r\n        return;\r\n\r\n    double abundanceScale = 1;\r\n\r\n    if (normalization & IsotopeCalculator::NormalizeAbundance)\r\n    {\r\n        double sumSquaredAbundances = 0;\r\n        for (MassDistribution::iterator it=md.begin(); it!=md.end(); ++it)\r\n        {\r\n            double a = it->abundance;\r\n            sumSquaredAbundances += a*a;\r\n        }\r\n\r\n        abundanceScale = sqrt(sumSquaredAbundances);\r\n    }\r\n\r\n    double massShift = (normalization & IsotopeCalculator::NormalizeMass) ? md[0].mass : 0;\r\n\r\n    for (MassDistribution::iterator it=md.begin(); it!=md.end(); ++it)\r\n    {\r\n        it->mass -= massShift; \r\n        it->abundance /= abundanceScale; \r\n    }\r\n}\r\n\r\n} // namespace \r\n\r\n\r\nMassDistribution IsotopeCalculator::Impl::distribution(const Formula& formula,\r\n                                                       int chargeState,\r\n                                                       int normalization) const\r\n{\r\n    // collect the distributions for each element in the formula\r\n\r\n    vector<MassDistribution> distributions; \r\n\r\n    Formula::Map formulaData = formula.data();\r\n    for (Formula::Map::const_iterator it=formulaData.begin(); it!=formulaData.end(); ++it)\r\n    {\r\n        Element::Type e = it->first;\r\n        int atomCount = it->second;\r\n\r\n        TableMap::const_iterator table = tableMap_.find(e); \r\n        if (table != tableMap_.end())\r\n            distributions.push_back(table->second->distribution(atomCount));\r\n        else\r\n            distributions.push_back(distributionManually(e, atomCount));\r\n    }\r\n\r\n    // coalesce each elemental distribution   \r\n\r\n    vector<MassDistribution> coalescedDistributions;\r\n    for (vector<MassDistribution>::iterator it=distributions.begin(); it!=distributions.end(); ++it)\r\n        coalescedDistributions.push_back(coalesceDistribution(*it, massPrecision_)); \r\n\r\n    // combine the distributions and sort by mass\r\n\r\n    MassDistribution combined = accumulate(coalescedDistributions.begin(), coalescedDistributions.end(), \r\n                                           MassDistribution(), Convolve(abundanceCutoff_));\r\n\r\n    sort(combined.begin(), combined.end(), hasLessMass);\r\n\r\n    MassDistribution result = coalesceDistribution(combined, massPrecision_);\r\n\r\n    // adjust for charge state\r\n    \r\n    if (chargeState)\r\n        for_each(result.begin(), result.end(), Ionize(chargeState));\r\n\r\n    // normalize if requested\r\n\r\n    if (normalization)\r\n        normalize(result, normalization);\r\n    \r\n    return result;\r\n}\r\n\r\n\r\nnamespace {\r\n\r\nstruct TableInfo\r\n{\r\n    Element::Type element;\r\n    int maxAtomCount;\r\n};\r\n\r\nTableInfo tableInfo_[] = \r\n{\r\n    {Element::C, 5000}, \r\n    {Element::H, 8000}, \r\n    {Element::N, 1500}, \r\n    {Element::O, 1500}, \r\n    {Element::S, 50}, \r\n};\r\n\r\nconst int tableInfoSize_ = sizeof(tableInfo_)/sizeof(TableInfo);\r\n\r\n} // namespace\r\n\r\n\r\nvoid IsotopeCalculator::Impl::initializeIsotopeTables()\r\n{\r\n    for (TableInfo* it=tableInfo_; it!=tableInfo_+tableInfoSize_; ++it)\r\n    {\r\n        IsotopeTable* temp(new IsotopeTable(Element::Info::record(it->element).isotopes, \r\n                                            it->maxAtomCount, \r\n                                            abundanceCutoff_));\r\n        tableMap_[it->element] = temp; // store pointer in the map\r\n        tableStorage_.push_back(temp); // maintain ownership in the ptr_vector\r\n    }\r\n}\r\n\r\n\r\nMassDistribution IsotopeCalculator::Impl::distributionManually(Element::Type e, \r\n                                                                        int atomCount) const\r\n{\r\n    throw runtime_error(\"[IsotopeCalculator::distribution()] No table for element \" \r\n        + Element::Info::record(e).symbol); \r\n}\r\n\r\n\r\nPWIZ_API_DECL IsotopeCalculator::IsotopeCalculator(double abundanceCutoff, double massPrecision)\r\n:   impl_(new Impl(abundanceCutoff, massPrecision))\r\n{}\r\n\r\n\r\nPWIZ_API_DECL IsotopeCalculator::~IsotopeCalculator(){} // auto destruction of impl_\r\n\r\n\r\nPWIZ_API_DECL\r\nMassDistribution IsotopeCalculator::distribution(const Formula& formula,\r\n                                                 int chargeState,\r\n                                                 int normalization) const\r\n{\r\n    return impl_->distribution(formula, chargeState, normalization);\r\n}\r\n\r\n\r\n} // namespace chemistry\r\n} // namespace pwiz\r\n", "meta": {"hexsha": "be2136b7cfb6ed6381c2378fd379a88882a066c7", "size": 8659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pwiz/utility/chemistry/IsotopeCalculator.cpp", "max_stars_repo_name": "edyp-lab/pwiz-mzdb", "max_stars_repo_head_hexsha": "d13ce17f4061596c7e3daf9cf5671167b5996831", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-01-08T08:33:44.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-12T06:14:54.000Z", "max_issues_repo_path": "pwiz/utility/chemistry/IsotopeCalculator.cpp", "max_issues_repo_name": "shze/pwizard-deb", "max_issues_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "pwiz/utility/chemistry/IsotopeCalculator.cpp", "max_forks_repo_name": "shze/pwizard-deb", "max_forks_repo_head_hexsha": "4822829196e915525029a808470f02d24b8b8043", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-02-03T09:41:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-01T18:42:36.000Z", "avg_line_length": 27.576433121, "max_line_length": 106, "alphanum_fraction": 0.620279478, "num_tokens": 1874, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.21785180419547523}}
{"text": "/*\nCopyright 2020 Dennis Rohde\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n\n#include <vector>\n#include <limits>\n\n#include <boost/chrono/include.hpp>\n\n#include \"frechet.hpp\"\n\nnamespace Frechet {\n\nnamespace Continuous {\n    \ndistance_t epsilon = 0.001;\nbool round = true;\n    \nstd::string Distance::repr() const {\n    std::stringstream ss;\n    ss << value;\n    return ss.str();\n}\n\nDistance distance(const Curve &curve1, const Curve &curve2) {\n    if ((curve1.complexity() < 2) or (curve2.complexity() < 2)) {\n        std::cerr << \"WARNING: comparison possible only for curves of at least two points\" << std::endl;\n        Distance result;\n        result.value = std::numeric_limits<distance_t>::signaling_NaN();\n        return result;\n    }\n    if (curve1.dimensions() != curve2.dimensions()) {\n        std::cerr << \"WARNING: comparison possible only for curves of equal number of dimensions\" << std::endl;\n        Distance result;\n        result.value = std::numeric_limits<distance_t>::signaling_NaN();\n        return result;\n    }\n    \n    auto start = boost::chrono::process_real_cpu_clock::now();\n    const auto lb = std::sqrt(std::max(curve1[0].dist_sqr(curve2[0]), curve1[curve1.complexity()-1].dist_sqr(curve2[curve2.complexity()-1])));\n    const auto ub = _greedy_upper_bound(curve1, curve2);\n    auto end = boost::chrono::process_real_cpu_clock::now();\n\n    #if DEBUG\n    std::cout << \"narrowed to [\" << lb << \", \" << ub.value << \"]\" << std::endl;\n    #endif\n\n    auto dist = _distance(curve1, curve2, ub, lb);\n    dist.time_bounds = (end-start).count() / 1000000000.0;\n    if (round) dist.value =  std::round(dist.value * 1e3) / 1e3;\n\n    return dist;\n}\n\nDistance _distance(const Curve &curve1, const Curve &curve2, distance_t ub, distance_t lb) {\n    Distance result;\n    auto start = boost::chrono::process_real_cpu_clock::now();\n    \n    distance_t split = (ub + lb)/2;\n    std::size_t number_searches = 0;\n    \n    if (ub - lb > epsilon) {\n        auto infty = std::numeric_limits<distance_t>::infinity();\n        std::vector<std::vector<distance_t>> reachable1(curve1.complexity()-1, std::vector<distance_t>(curve2.complexity(), infty));\n        std::vector<std::vector<distance_t>> reachable2(curve1.complexity(), std::vector<distance_t>(curve2.complexity()-1, infty));\n        \n        std::vector<std::vector<Interval>> free_intervals1(curve2.complexity(), std::vector<Interval>(curve1.complexity(), Interval()));\n        std::vector<std::vector<Interval>> free_intervals2(curve1.complexity(), std::vector<Interval>(curve2.complexity(), Interval()));\n\n        if (std::isnan(lb) or std::isnan(ub)) {\n            result.value = std::numeric_limits<distance_t>::signaling_NaN();\n            return result;\n        }\n\n        //Binary search over the feasible distances\n        while (ub - lb > epsilon) {\n            ++number_searches;\n            split = (ub + lb)/2;\n            auto isLessThan = _less_than_or_equal(split, curve1, curve2, reachable1, reachable2, free_intervals1, free_intervals2);\n            if (isLessThan) {\n                ub = split;\n            }\n            else {\n                lb = split;\n            }\n            #if DEBUG\n            std::cout << \"narrowed to [\" << lb << \", \" << ub << \"]\" << std::endl;\n            #endif\n        }\n    }\n    \n    distance_t value = (ub + lb)/2.;\n    auto end = boost::chrono::process_real_cpu_clock::now();\n    result.value = value;\n    result.time_searches = (end-start).count() / 1000000000.0;\n    result.number_searches = number_searches;\n    return result;\n}\n\nbool _less_than_or_equal(const distance_t distance, Curve const& curve1, Curve const& curve2, \n        std::vector<std::vector<distance_t>> &reachable1, std::vector<std::vector<distance_t>> &reachable2,\n        std::vector<std::vector<Interval>> &free_intervals1, std::vector<std::vector<Interval>> &free_intervals2) {\n    assert(curve1.complexity() >= 2);\n    assert(curve2.complexity() >= 2);\n    \n    distance_t dist_sqr = distance * distance;\n    auto infty = std::numeric_limits<distance_t>::infinity();\n\n    if (curve1[0].dist_sqr(curve2[0]) > dist_sqr or curve1.back().dist_sqr(curve2.back()) > dist_sqr) return false;\n\n    for (auto &elem: reachable1) {\n        #pragma omp parallel for\n        for (curve_size_t i = 0; i < elem.size(); ++i) {\n            elem[i] = infty;\n        }\n    }\n    \n    for (auto &elem: reachable2) {\n        #pragma omp parallel for\n        for (curve_size_t i = 0; i < elem.size(); ++i) {\n            elem[i] = infty;\n        }\n    }\n    \n    for (auto &elem: free_intervals1) {\n        #pragma omp parallel for\n        for (curve_size_t i = 0; i < elem.size(); ++i) {\n            elem[i] = Interval();\n        }\n    }\n    \n    for (auto &elem: free_intervals2) {\n        #pragma omp parallel for\n        for (curve_size_t i = 0; i < elem.size(); ++i) {\n            elem[i] = Interval();\n        }\n    }\n    \n    for (curve_size_t i = 0; i < curve1.complexity() - 1; ++i) {\n        reachable1[i][0] = 0.;\n        if (curve2[0].dist_sqr(curve1[i+1]) > dist_sqr) break;\n    }\n    \n    for (curve_size_t j = 0; j < curve2.complexity() - 1; ++j) {\n        reachable2[0][j] = 0.;\n        if (curve1[0].dist_sqr(curve2[j+1]) > dist_sqr) break;\n    }\n    \n    #pragma omp parallel for collapse(2)\n    for (curve_size_t i = 0; i < curve1.complexity(); ++i) {\n        for (curve_size_t j = 0; j < curve2.complexity(); ++j) {\n            if ((i < curve1.complexity() - 1) and (j > 0)) {\n                free_intervals1[j][i] = curve2[j].intersection_interval(dist_sqr, curve1[i], curve1[i+1]);\n            }\n            if ((j < curve2.complexity() - 1) and (i > 0)) {\n                free_intervals2[i][j] = curve1[i].intersection_interval(dist_sqr, curve2[j], curve2[j+1]);\n            }\n        }\n    }\n    \n    for (curve_size_t i = 0; i < curve1.complexity(); ++i) {\n        for (curve_size_t j = 0; j < curve2.complexity(); ++j) {\n            if ((i < curve1.complexity() - 1) and (j > 0)) {\n                if (not free_intervals1[j][i].is_empty()) {\n                    if (reachable2[i][j-1] != infty) {\n                        reachable1[i][j] = free_intervals1[j][i].begin();\n                    }\n                    else if (reachable1[i][j-1] <= free_intervals1[j][i].end()) {\n                        reachable1[i][j] = std::max(free_intervals1[j][i].begin(), reachable1[i][j-1]);\n                    }\n                }\n            }\n            if ((j < curve2.complexity() - 1) and (i > 0)) {\n                if (not free_intervals2[i][j].is_empty()) {\n                    if (reachable1[i-1][j] != infty) {\n                        reachable2[i][j] = free_intervals2[i][j].begin();\n                    }\n                    else if (reachable2[i-1][j] <= free_intervals2[i][j].end()) {\n                        reachable2[i][j] = std::max(free_intervals2[i][j].begin(), reachable2[i-1][j]);\n                    }\n                }\n            }\n        }\n    }\n\n    assert((reachable1.back().back() < infty) == (reachable2.back().back() < infty));\n\n    return reachable1.back().back() < infty;\n}\n\ndistance_t _greedy_upper_bound(const Curve &curve1, const Curve &curve2) {\n    distance_t result = 0;\n    \n    const curve_size_t len1 = curve1.complexity(), len2 = curve2.complexity();\n    curve_size_t i = 0, j = 0;\n    \n    while ((i < len1 - 1) and (j < len2 - 1)) {\n        result = std::max(result, curve1[i].dist_sqr(curve2[j]));\n        \n        distance_t dist1 = curve1[i+1].dist_sqr(curve2[j]),\n            dist2 = curve1[i].dist_sqr(curve2[j+1]),\n            dist3 = curve1[i+1].dist_sqr(curve2[j+1]);\n        \n        if ((dist1 <= dist2) and (dist1 <= dist3)) ++i;\n        else if ((dist2 <= dist1) and (dist2 <= dist3)) ++j;\n        else {\n            ++i;\n            ++j;\n        }\n    }\n    \n    while (i < len1) result = std::max(result, curve1[i++].dist_sqr(curve2[j]));\n    \n    --i;\n    \n    while (j < len2) result = std::max(result, curve1[i].dist_sqr(curve2[j++]));\n    \n    return std::sqrt(result);\n}\n\n} // end namespace Continuous\n\nnamespace Discrete {\n    \nstd::string Distance::repr() const {\n    std::stringstream ss;\n    ss << value;\n    return ss.str();\n}\n    \nDistance distance(const Curve &curve1, const Curve &curve2) {\n    Distance result;\n    auto start = boost::chrono::process_real_cpu_clock::now();\n    std::vector<std::vector<distance_t>> a(curve1.complexity(), std::vector<distance_t>(curve2.complexity(), -1));\n    auto value = std::sqrt(_dp(a, curve1.complexity() - 1, curve2.complexity() - 1, curve1, curve2));\n    auto end = boost::chrono::process_real_cpu_clock::now();\n    result.time = (end-start).count() / 1000000000.0;\n    result.value = value;\n    return result;\n    \n}\n\ndistance_t _dp(std::vector<std::vector<distance_t>> &a, const curve_size_t i, const curve_size_t j, const Curve &curve1, const Curve &curve2) {\n    if (a[i][j] > -1) return a[i][j];\n    else if (i == 0 and j == 0) return curve1[i].dist_sqr(curve2[j]);\n    else if (i > 0 and j == 0) return std::max(_dp(a, i-1, 0, curve1, curve2), curve1[i].dist_sqr(curve2[j]));\n    else if (i == 0 and j > 0) return std::max(_dp(a, 0, j-1, curve1, curve2), curve1[i].dist_sqr(curve2[j]));\n    else {\n        a[i][j] = std::max(\n                    std::min(\n                        std::min(_dp(a, i-1, j, curve1, curve2), \n                            _dp(a, i-1, j-1, curve1, curve2)), \n                        _dp(a, i, j-1, curve1, curve2)), \n                    curve1[i].dist_sqr(curve2[j]));\n    }\n    return a[i][j];\n}\n\n} // end namespace Discrete\n\n} // end namespace Frechet\n", "meta": {"hexsha": "c17c40fab90af7593405fcbc70913f84e951c449", "size": 10564, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/frechet.cpp", "max_stars_repo_name": "hairbeRt/Fred", "max_stars_repo_head_hexsha": "ae3770e2ad62f83a7d2070e8e48087d89aa09bfc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/frechet.cpp", "max_issues_repo_name": "hairbeRt/Fred", "max_issues_repo_head_hexsha": "ae3770e2ad62f83a7d2070e8e48087d89aa09bfc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/frechet.cpp", "max_forks_repo_name": "hairbeRt/Fred", "max_forks_repo_head_hexsha": "ae3770e2ad62f83a7d2070e8e48087d89aa09bfc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.4179104478, "max_line_length": 460, "alphanum_fraction": 0.5841537296, "num_tokens": 2929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21751576258908772}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <ql/cashflows/coupon.hpp>\n#include <ql/cashflows/simplecashflow.hpp>\n#include <ql/exercise.hpp>\n#include <ql/instruments/compositeinstrument.hpp>\n#include <ql/instruments/nonstandardswaption.hpp>\n#include <ql/instruments/swaption.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n\n#include <qle/instruments/rebatedexercise.hpp>\n\n#include <ored/portfolio/builders/swap.hpp>\n#include <ored/portfolio/builders/swaption.hpp>\n#include <ored/portfolio/optionwrapper.hpp>\n#include <ored/portfolio/swaption.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/to_string.hpp>\n\n#include <boost/algorithm/string/case_conv.hpp>\n#include <boost/timer/timer.hpp>\n\n#include <algorithm>\n\nusing boost::timer::cpu_timer;\nusing boost::timer::default_places;\nusing namespace QuantLib;\nusing std::lower_bound;\nusing std::sort;\n\nnamespace ore {\nnamespace data {\n\nvoid Swaption::build(const boost::shared_ptr<EngineFactory>& engineFactory) {\n\n    QL_REQUIRE(swap_.size() == 2, \"underlying swap must have 2 legs\");\n\n    // we can assume 2 legs now\n    bool isCrossCcy = swap_[0].currency() != swap_[1].currency();\n\n    bool isFixedFloating = (swap_[0].legType() == \"Fixed\" && swap_[1].legType() == \"Floating\") ||\n                           (swap_[1].legType() == \"Fixed\" && swap_[0].legType() == \"Floating\");\n\n    // First elimate these\n    QL_REQUIRE(!isCrossCcy, \"Cross Currency Swaptions not supported\");\n    QL_REQUIRE(isFixedFloating, \"Basis Swaptions not supported\");\n\n    // check at least one exercise date is given\n    QL_REQUIRE(!option_.exerciseDates().empty(), \"No exercise dates given\");\n\n    // check if all exercise dates (adjusted by the notice period) are in the past and if so, build an expired\n    // instrument\n    Period noticePeriod = option_.noticePeriod().empty() ? 0 * Days : parsePeriod(option_.noticePeriod());\n    Calendar noticeCal = option_.noticeCalendar().empty() ? NullCalendar() : parseCalendar(option_.noticeCalendar());\n    BusinessDayConvention noticeBdc =\n        option_.noticeConvention().empty() ? Unadjusted : parseBusinessDayConvention(option_.noticeConvention());\n    std::vector<Date> exerciseDates(option_.exerciseDates().size());\n    for (Size i = 0; i < option_.exerciseDates().size(); ++i) {\n        exerciseDates.push_back(noticeCal.advance(parseDate(option_.exerciseDates()[i]), -noticePeriod, noticeBdc));\n    }\n\n    Date latestExerciseDate = *std::max_element(exerciseDates.begin(), exerciseDates.end());\n    if (QuantLib::detail::simple_event(latestExerciseDate).hasOccurred()) {\n        exercise_ = boost::make_shared<BermudanExercise>(exerciseDates);\n        legs_ = {{boost::make_shared<QuantLib::SimpleCashFlow>(0.0, latestExerciseDate)}};\n        instrument_ = boost::shared_ptr<InstrumentWrapper>(\n            new VanillaInstrument(boost::make_shared<QuantLib::Swap>(legs_, std::vector<bool>(1, false)), 1.0, {}, {}));\n        legCurrencies_ = {swap_[0].currency()};\n        legPayers_ = {false};\n        npvCurrency_ = swap_[0].currency();\n        notional_ = 0.0;\n        notionalCurrency_ = npvCurrency_;\n        maturity_ = latestExerciseDate;\n        return;\n    }\n\n    // build swaption with at least one alive exercise date\n    bool fixedFirst = swap_[0].legType() == \"Fixed\";\n    boost::shared_ptr<FixedLegData> fixedLegData =\n        boost::dynamic_pointer_cast<FixedLegData>(swap_[fixedFirst ? 0 : 1].concreteLegData());\n    boost::shared_ptr<FloatingLegData> floatingLegData =\n        boost::dynamic_pointer_cast<FloatingLegData>(swap_[fixedFirst ? 1 : 0].concreteLegData());\n    underlyingIndex_ = floatingLegData->index();\n\n    bool isNonStandard =\n        (swap_[0].notionals().size() > 1 || swap_[1].notionals().size() > 1 || floatingLegData->spreads().size() > 1 ||\n         floatingLegData->gearings().size() > 1 || fixedLegData->rates().size() > 1);\n\n    Exercise::Type exerciseType = parseExerciseType(option_.style());\n\n    // treat non standard europeans as bermudans, also if exercise fees are present\n    QL_REQUIRE(exerciseType == Exercise::Bermudan || exerciseType == Exercise::European,\n               \"Exercise type \" << option_.style() << \" not implemented for Swaptions\");\n    if (exerciseType == Exercise::Bermudan || (isNonStandard && exerciseType == Exercise::European) ||\n        !option_.exerciseFees().empty())\n        buildBermudan(engineFactory);\n    else\n        buildEuropean(engineFactory);\n\n    // add required fixings, we add the required fixing for the underlying swap, which might be more\n    // than actually required, i.e. we are conservative here\n    addToRequiredFixings(underlyingLeg_,\n                         boost::make_shared<FixingDateGetter>(\n                             requiredFixings_, std::map<string, string>{{underlyingIndexQlName_, underlyingIndex_}}));\n}\n\nnamespace {\nQuantLib::Settlement::Method defaultMethod(const QuantLib::Settlement::Type t) {\n    if (t == QuantLib::Settlement::Physical)\n        return QuantLib::Settlement::PhysicalOTC;\n    else\n        return QuantLib::Settlement::ParYieldCurve; // ql < 1.14 behaviour\n}\n} // namespace\n\nvoid Swaption::buildEuropean(const boost::shared_ptr<EngineFactory>& engineFactory) {\n\n    LOG(\"Building European Swaption \" << id());\n\n    // Swaption details\n    Settlement::Type settleType = parseSettlementType(option_.settlement());\n    Settlement::Method settleMethod = option_.settlementMethod() == \"\"\n                                          ? defaultMethod(settleType)\n                                          : parseSettlementMethod(option_.settlementMethod());\n    QL_REQUIRE(option_.exerciseDates().size() == 1, \"Only one exercise date expected for European Option\");\n\n    Period noticePeriod = option_.noticePeriod().empty() ? 0 * Days : parsePeriod(option_.noticePeriod());\n    Calendar noticeCal = option_.noticeCalendar().empty() ? NullCalendar() : parseCalendar(option_.noticeCalendar());\n    BusinessDayConvention noticeBdc =\n        option_.noticeConvention().empty() ? Unadjusted : parseBusinessDayConvention(option_.noticeConvention());\n    Date exDate = noticeCal.advance(parseDate(option_.exerciseDates().front()), -noticePeriod, noticeBdc);\n    QL_REQUIRE(exDate >= Settings::instance().evaluationDate(), \"Exercise date expected in the future.\");\n\n    boost::shared_ptr<VanillaSwap> swap = buildVanillaSwap(engineFactory, exDate);\n    underlyingLeg_ = swap->floatingLeg();\n\n    string ccy = swap_[0].currency();\n    Currency currency = parseCurrency(ccy);\n\n    exercise_ = boost::make_shared<EuropeanExercise>(exDate);\n\n    // Build Swaption\n    boost::shared_ptr<QuantLib::Swaption> swaption(new QuantLib::Swaption(swap, exercise_, settleType, settleMethod));\n\n    // Add Engine\n    string tt(\"EuropeanSwaption\");\n    boost::shared_ptr<EngineBuilder> builder = engineFactory->builder(tt);\n    QL_REQUIRE(builder, \"No builder found for \" << tt);\n    boost::shared_ptr<EuropeanSwaptionEngineBuilder> swaptionBuilder =\n        boost::dynamic_pointer_cast<EuropeanSwaptionEngineBuilder>(builder);\n    swaption->setPricingEngine(swaptionBuilder->engine(currency));\n\n    Position::Type positionType = parsePositionType(option_.longShort());\n    Real multiplier = (positionType == QuantLib::Position::Long ? 1.0 : -1.0);\n\n    // If premium data is provided\n    // 1) build the fee trade and pass it to the instrument wrapper for pricing\n    // 2) add fee payment as additional trade leg for cash flow reporting\n    std::vector<boost::shared_ptr<Instrument>> additionalInstruments;\n    std::vector<Real> additionalMultipliers;\n    if (option_.premiumPayDate() != \"\" && option_.premiumCcy() != \"\") {\n        Real premiumAmount = -multiplier * option_.premium(); // pay if long, receive if short\n        Currency premiumCurrency = parseCurrency(option_.premiumCcy());\n        Date premiumDate = parseDate(option_.premiumPayDate());\n        addPayment(additionalInstruments, additionalMultipliers, premiumDate, premiumAmount, premiumCurrency, currency,\n                   engineFactory, swaptionBuilder->configuration(MarketContext::pricing));\n        DLOG(\"option premium added for european swaption \" << id());\n    }\n\n    // Now set the instrument wrapper, depending on delivery\n    if (settleType == Settlement::Physical) {\n        // tracks state for any option flavour, including physical delivery\n        instrument_ = boost::shared_ptr<InstrumentWrapper>(\n            new EuropeanOptionWrapper(swaption, positionType == Position::Long ? true : false, exDate,\n                                      settleType == Settlement::Physical ? true : false, swap, 1.0, 1.0,\n                                      additionalInstruments, additionalMultipliers));\n        // maturity of underlying\n        maturity_ = std::max(swap->fixedSchedule().dates().back(), swap->floatingSchedule().dates().back());\n    } else {\n        instrument_ = boost::shared_ptr<InstrumentWrapper>(\n            new VanillaInstrument(swaption, multiplier, additionalInstruments, additionalMultipliers));\n        maturity_ = exDate;\n    }\n\n    DLOG(\"Building European Swaption done\");\n}\n\nvoid Swaption::buildBermudan(const boost::shared_ptr<EngineFactory>& engineFactory) {\n    DLOG(\"Building Bermudan Swaption \" << id());\n\n    QL_REQUIRE(swap_.size() >= 1, \"underlying swap must have at least 1 leg\");\n\n    string ccy_str = swap_[0].currency();\n    Currency currency = parseCurrency(ccy_str);\n\n    bool fixedFirst = swap_[0].legType() == \"Fixed\";\n    boost::shared_ptr<FixedLegData> fixedLegData =\n        boost::dynamic_pointer_cast<FixedLegData>(swap_[fixedFirst ? 0 : 1].concreteLegData());\n    boost::shared_ptr<FloatingLegData> floatingLegData =\n        boost::dynamic_pointer_cast<FloatingLegData>(swap_[fixedFirst ? 1 : 0].concreteLegData());\n    underlyingIndex_ = floatingLegData->index();\n\n    bool isNonStandard =\n        (swap_[0].notionals().size() > 1 || swap_[1].notionals().size() > 1 || floatingLegData->spreads().size() > 1 ||\n         floatingLegData->gearings().size() > 1 || fixedLegData->rates().size() > 1);\n\n    boost::shared_ptr<VanillaSwap> vanillaSwap;\n    boost::shared_ptr<NonstandardSwap> nonstandardSwap;\n    boost::shared_ptr<Swap> swap;\n    if (!isNonStandard) {\n        vanillaSwap = buildVanillaSwap(engineFactory);\n        underlyingLeg_ = vanillaSwap->floatingLeg();\n        swap = vanillaSwap;\n    } else {\n        nonstandardSwap = buildNonStandardSwap(engineFactory);\n        underlyingLeg_ = nonstandardSwap->floatingLeg();\n        swap = nonstandardSwap;\n    }\n\n    DLOG(\"Swaption::Build(): Underlying Start = \" << QuantLib::io::iso_date(swap->startDate()));\n\n    // build exercise: only keep a) future exercise dates and b) exercise dates that exercise into a whole\n    // accrual period of the underlying; TODO handle exercises into broken periods?\n    Date lastAccrualStartDate = Date::minDate();\n    for (Size i = 0; i < 2; ++i) {\n        for (auto const& c : swap->leg(i)) {\n            if (auto cpn = boost::dynamic_pointer_cast<Coupon>(c))\n                lastAccrualStartDate = std::max(lastAccrualStartDate, cpn->accrualStartDate());\n        }\n    }\n    Period noticePeriod = option_.noticePeriod().empty() ? 0 * Days : parsePeriod(option_.noticePeriod());\n    Calendar noticeCal = option_.noticeCalendar().empty() ? NullCalendar() : parseCalendar(option_.noticeCalendar());\n    BusinessDayConvention noticeBdc =\n        option_.noticeConvention().empty() ? Unadjusted : parseBusinessDayConvention(option_.noticeConvention());\n    std::vector<QuantLib::Date> sortedExerciseDates;\n    for (auto const& d : option_.exerciseDates())\n        sortedExerciseDates.push_back(parseDate(d));\n    std::sort(sortedExerciseDates.begin(), sortedExerciseDates.end());\n    std::vector<QuantLib::Date> noticeDates, exerciseDates;\n    std::vector<bool> isExerciseDateAlive(sortedExerciseDates.size(), false);\n    for (Size i = 0; i < sortedExerciseDates.size(); i++) {\n        Date noticeDate = noticeCal.advance(sortedExerciseDates[i], -noticePeriod, noticeBdc);\n        if (noticeDate > Settings::instance().evaluationDate() && noticeDate <= lastAccrualStartDate) {\n            isExerciseDateAlive[i] = true;\n            noticeDates.push_back(noticeDate);\n            exerciseDates.push_back(sortedExerciseDates[i]);\n            DLOG(\"Got notice date \" << QuantLib::io::iso_date(noticeDate) << \" using notice period \" << noticePeriod\n                                    << \", convention \" << noticeBdc << \", calendar \" << noticeCal.name()\n                                    << \" from exercise date \" << exerciseDates.back());\n        }\n        if (noticeDate > lastAccrualStartDate)\n            WLOG(\"Remove notice date \" << ore::data::to_string(noticeDate) << \" (exercise date \"\n                                       << sortedExerciseDates[i] << \") after last accrual start date \"\n                                       << ore ::data::to_string(lastAccrualStartDate));\n    }\n    QL_REQUIRE(noticeDates.size() > 0, \"Bermudan Swaption does not have any alive exercise dates\");\n    maturity_ = noticeDates.back();\n    exercise_ = boost::make_shared<BermudanExercise>(noticeDates);\n\n    // check for exercise fees, if present build a rebated exercise with rebates = -fee\n    if (!option_.exerciseFees().empty()) {\n        // build an exercise date \"schedule\" by adding the maximum possible date at the end\n        std::vector<Date> exDatesPlusInf(sortedExerciseDates);\n        exDatesPlusInf.push_back(Date::maxDate());\n        vector<double> allRebates =\n            buildScheduledVectorNormalised(option_.exerciseFees(), option_.exerciseFeeDates(), exDatesPlusInf, 0.0);\n        // filter on alive rebates, so that we can a vector of rebates corresponding to the exerciseDates vector\n        vector<double> rebates;\n        for (Size i = 0; i < sortedExerciseDates.size(); ++i) {\n            if (isExerciseDateAlive[i])\n                rebates.push_back(allRebates[i]);\n        }\n        // flip the sign of the fee to get a rebate\n        for (auto& r : rebates)\n            r = -r;\n        vector<string> feeType = buildScheduledVectorNormalised<string>(option_.exerciseFeeTypes(),\n                                                                        option_.exerciseFeeDates(), exDatesPlusInf, \"\");\n        // convert relative to absolute fees if required\n        for (Size i = 0; i < rebates.size(); ++i) {\n            // default to Absolute\n            if (feeType[i].empty())\n                feeType[i] = \"Absolute\";\n            if (feeType[i] == \"Percentage\") {\n                // get next float coupon after exercise to determine relevant notional\n                Real feeNotional = Null<Real>();\n                for (auto const& c : swap->leg(1)) {\n                    if (auto cpn = boost::dynamic_pointer_cast<Coupon>(c)) {\n                        if (feeNotional == Null<Real>() && cpn->accrualStartDate() >= exerciseDates[i])\n                            feeNotional = cpn->nominal();\n                    }\n                }\n                if (feeNotional == Null<Real>())\n                    rebates[i] = 0.0; // notional is zero\n                else {\n                    DLOG(\"Convert percentage rebate \"\n                         << rebates[i] << \" to absolute reabte \" << rebates[i] * feeNotional << \" using nominal \"\n                         << feeNotional << \" for exercise date \" << QuantLib::io::iso_date(exerciseDates[i]));\n                    rebates[i] *= feeNotional; // multiply percentage fee by relevant notional\n                }\n            } else {\n                QL_REQUIRE(feeType[i] == \"Absolute\", \"fee type must be Absolute or Relative\");\n            }\n        }\n        Period feeSettlPeriod = option_.exerciseFeeSettlementPeriod().empty()\n                                    ? 0 * Days\n                                    : parsePeriod(option_.exerciseFeeSettlementPeriod());\n        Calendar feeSettlCal = option_.exerciseFeeSettlementCalendar().empty()\n                                   ? NullCalendar()\n                                   : parseCalendar(option_.exerciseFeeSettlementCalendar());\n        BusinessDayConvention feeSettlBdc = option_.exerciseFeeSettlementConvention().empty()\n                                                ? Unadjusted\n                                                : parseBusinessDayConvention(option_.exerciseFeeSettlementConvention());\n        exercise_ = boost::make_shared<QuantExt::RebatedExercise>(*exercise_, exerciseDates, rebates, feeSettlPeriod,\n                                                                  feeSettlCal, feeSettlBdc);\n        // log rebates\n        auto dbgEx = boost::static_pointer_cast<QuantExt::RebatedExercise>(exercise_);\n        for (Size i = 0; i < exerciseDates.size(); ++i) {\n            DLOG(\"Got rebate \" << dbgEx->rebate(i) << \" with payment date \"\n                               << QuantLib::io::iso_date(dbgEx->rebatePaymentDate(i)) << \" (exercise date=\"\n                               << QuantLib::io::iso_date(exerciseDates[i]) << \") using rebate settl period \"\n                               << feeSettlPeriod << \", calendar \" << feeSettlCal << \", convention \" << feeSettlBdc);\n        }\n    }\n\n    Settlement::Type delivery = parseSettlementType(option_.settlement());\n    Settlement::Method deliveryMethod =\n        option_.settlementMethod() == \"\" ? defaultMethod(delivery) : parseSettlementMethod(option_.settlementMethod());\n\n    if (delivery == Settlement::Cash && deliveryMethod == Settlement::ParYieldCurve)\n        WLOG(\"Cash-settled Bermudan Swaption (id = \"\n             << id() << \") with ParYieldCurve settlement method not supported by Lgm engine. \"\n             << \"Approximate pricing using CollateralizedCashPrice pricing methodology\");\n\n    // Build swaption\n    DLOG(\"Build Swaption instrument\");\n    boost::shared_ptr<QuantLib::Instrument> swaption;\n    if (isNonStandard) {\n        swaption = boost::shared_ptr<QuantLib::Instrument>(\n            new QuantLib::NonstandardSwaption(nonstandardSwap, exercise_, delivery, deliveryMethod));\n        // workaround for missing registration in QL versions < 1.13\n        swaption->registerWithObservables(nonstandardSwap);\n    } else\n        swaption = boost::shared_ptr<QuantLib::Instrument>(\n            new QuantLib::Swaption(vanillaSwap, exercise_, delivery, deliveryMethod));\n\n    QuantLib::Position::Type positionType = parsePositionType(option_.longShort());\n    if (delivery == Settlement::Physical)\n        maturity_ = swap->maturityDate();\n\n    DLOG(\"Get/Build Bermudan Swaption engine\");\n    cpu_timer timer;\n\n    string tt(\"BermudanSwaption\");\n    boost::shared_ptr<EngineBuilder> builder = engineFactory->builder(tt);\n    QL_REQUIRE(builder, \"No builder found for \" << tt);\n    boost::shared_ptr<BermudanSwaptionEngineBuilder> swaptionBuilder =\n        boost::dynamic_pointer_cast<BermudanSwaptionEngineBuilder>(builder);\n\n    // determine strikes for calibration basket (simple approach, a la summit)\n    std::vector<Real> strikes(noticeDates.size(), Null<Real>());\n    if (!isNonStandard) {\n        Real tmp = vanillaSwap->fixedRate() - vanillaSwap->spread();\n        std::fill(strikes.begin(), strikes.end(), tmp);\n        DLOG(\"calibration strike is \" << tmp << \"(fixed rate \" << vanillaSwap->fixedRate() << \", spread \"\n                                      << vanillaSwap->spread() << \")\");\n    } else {\n        for (Size i = 0; i < noticeDates.size(); ++i) {\n            const Schedule& fix = nonstandardSwap->fixedSchedule();\n            const Schedule& flt = nonstandardSwap->floatingSchedule();\n            Size fixIdx =\n                std::lower_bound(fix.dates().begin(), fix.dates().end(), noticeDates[i]) - fix.dates().begin();\n            Size fltIdx =\n                std::lower_bound(flt.dates().begin(), flt.dates().end(), noticeDates[i]) - flt.dates().begin();\n            // play safe\n            fixIdx = std::min(fixIdx, nonstandardSwap->fixedRate().size() - 1);\n            fltIdx = std::min(fltIdx, nonstandardSwap->spreads().size() - 1);\n            strikes[i] = nonstandardSwap->fixedRate()[fixIdx] - nonstandardSwap->spreads()[fltIdx];\n            DLOG(\"calibration strike for ex date \" << QuantLib::io::iso_date(noticeDates[i]) << \" is \" << strikes[i]\n                                                   << \" (fixed rate \" << nonstandardSwap->fixedRate()[fixIdx]\n                                                   << \", spread \" << nonstandardSwap->spreads()[fltIdx] << \")\");\n        }\n    }\n\n    boost::shared_ptr<PricingEngine> engine =\n        swaptionBuilder->engine(id(), isNonStandard, ccy_str, noticeDates, swap->maturityDate(), strikes);\n\n    timer.stop();\n    DLOG(\"Swaption model calibration time: \" << timer.format(default_places, \"%w\") << \" s\");\n\n    swaption->setPricingEngine(engine);\n\n    // timer.restart();\n    // Real npv = swaption->NPV();\n    // Real pt = timer.elapsed();\n    // DLOG(\"Swaption pricing time: \" << pt*1000 << \" ms\");\n\n    boost::shared_ptr<EngineBuilder> tmp = engineFactory->builder(\"Swap\");\n    boost::shared_ptr<SwapEngineBuilderBase> swapBuilder = boost::dynamic_pointer_cast<SwapEngineBuilderBase>(tmp);\n    QL_REQUIRE(swapBuilder, \"No Swap Builder found for Swaption \" << id());\n    boost::shared_ptr<PricingEngine> swapEngine = swapBuilder->engine(currency);\n\n    std::vector<boost::shared_ptr<Instrument>> underlyingSwaps = buildUnderlyingSwaps(swapEngine, swap, noticeDates);\n\n    // If premium data is provided\n    // 1) build the fee trade and pass it to the instrument wrapper for pricing\n    // 2) add fee payment as additional trade leg for cash flow reporting\n    std::vector<boost::shared_ptr<Instrument>> additionalInstruments;\n    std::vector<Real> additionalMultipliers;\n    if (option_.premiumPayDate() != \"\" && option_.premiumCcy() != \"\") {\n        Real multiplier = positionType == Position::Long ? 1.0 : -1.0;\n        Real premiumAmount = -multiplier * option_.premium(); // pay if long, receive if short\n        Currency premiumCurrency = parseCurrency(option_.premiumCcy());\n        Date premiumDate = parseDate(option_.premiumPayDate());\n        addPayment(additionalInstruments, additionalMultipliers, premiumDate, premiumAmount, premiumCurrency, currency,\n                   engineFactory, swaptionBuilder->configuration(MarketContext::pricing));\n        DLOG(\"option premium added for bermudan swaption \" << id());\n    }\n\n    // instrument_ = boost::shared_ptr<InstrumentWrapper> (new VanillaInstrument (swaption, multiplier));\n    instrument_ = boost::shared_ptr<InstrumentWrapper>(\n        new BermudanOptionWrapper(swaption, positionType == Position::Long ? true : false, noticeDates,\n                                  delivery == Settlement::Physical ? true : false, underlyingSwaps, 1.0, 1.0,\n                                  additionalInstruments, additionalMultipliers));\n\n    DLOG(\"Building Bermudan Swaption done\");\n}\n\nboost::shared_ptr<VanillaSwap> Swaption::buildVanillaSwap(const boost::shared_ptr<EngineFactory>& engineFactory,\n                                                          const Date& firstExerciseDate) {\n    // Limitation to vanilla for now\n    QL_REQUIRE(swap_.size() == 2 && swap_[0].currency() == swap_[1].currency() &&\n                   swap_[0].isPayer() != swap_[1].isPayer() && swap_[0].notionals() == swap_[1].notionals() &&\n                   swap_[0].notionals().size() == 1,\n               \"Not a Vanilla Swap\");\n\n    Size fixedLegIndex, floatingLegIndex;\n    if (swap_[0].legType() == \"Floating\" && swap_[1].legType() == \"Fixed\") {\n        floatingLegIndex = 0;\n        fixedLegIndex = 1;\n    } else if (swap_[1].legType() == \"Floating\" && swap_[0].legType() == \"Fixed\") {\n        floatingLegIndex = 1;\n        fixedLegIndex = 0;\n    } else {\n        QL_FAIL(\"Invalid leg types \" << swap_[0].legType() << \" + \" << swap_[1].legType());\n    }\n    boost::shared_ptr<FixedLegData> fixedLegData =\n        boost::dynamic_pointer_cast<FixedLegData>(swap_[fixedLegIndex].concreteLegData());\n    boost::shared_ptr<FloatingLegData> floatingLegData =\n        boost::dynamic_pointer_cast<FloatingLegData>(swap_[floatingLegIndex].concreteLegData());\n\n    QL_REQUIRE(fixedLegData->rates().size() == 1, \"Vanilla Swaption: constant rate required\");\n    QL_REQUIRE(floatingLegData->spreads().size() <= 1, \"Vanilla Swaption: constant spread required\");\n\n    boost::shared_ptr<EngineBuilder> tmp = engineFactory->builder(\"Swap\");\n    boost::shared_ptr<SwapEngineBuilderBase> swapBuilder = boost::dynamic_pointer_cast<SwapEngineBuilderBase>(tmp);\n    QL_REQUIRE(swapBuilder, \"No Swap Builder found for Swaption \" << id());\n\n    // Get Trade details\n    string ccy = swap_[0].currency();\n    Currency currency = parseCurrency(ccy);\n    Real nominal = swap_[0].notionals().back();\n\n    Real rate = fixedLegData->rates().front();\n    Real spread = floatingLegData->spreads().empty() ? 0.0 : floatingLegData->spreads().front();\n    string indexName = floatingLegData->index();\n\n    Schedule fixedSchedule = makeSchedule(swap_[fixedLegIndex].schedule());\n    DayCounter fixedDayCounter = parseDayCounter(swap_[fixedLegIndex].dayCounter());\n\n    Schedule floatingSchedule = makeSchedule(swap_[floatingLegIndex].schedule());\n    Handle<IborIndex> index =\n        engineFactory->market()->iborIndex(indexName, swapBuilder->configuration(MarketContext::pricing));\n    underlyingIndexQlName_ = index->name();\n    DayCounter floatingDayCounter = parseDayCounter(swap_[floatingLegIndex].dayCounter());\n\n    BusinessDayConvention paymentConvention = parseBusinessDayConvention(swap_[floatingLegIndex].paymentConvention());\n\n    VanillaSwap::Type type = swap_[fixedLegIndex].isPayer() ? VanillaSwap::Payer : VanillaSwap::Receiver;\n\n    // We treat overnight and bma indices approximately as ibor indices and warn about this in the log\n    if (boost::dynamic_pointer_cast<OvernightIndex>(*index) ||\n        boost ::dynamic_pointer_cast<QuantExt::BMAIndexWrapper>(*index))\n        ALOG(\"Swaption trade \" << id() << \" on ON or BMA index '\" << underlyingIndex_\n                               << \"' built, will treat the index approximately as an ibor index\");\n\n    // only take into account accrual periods with start date on or after first exercise date (if given)\n    if (firstExerciseDate != Null<Date>()) {\n        std::vector<Date> fixDates = fixedSchedule.dates();\n        auto it1 = std::lower_bound(fixDates.begin(), fixDates.end(), firstExerciseDate);\n        fixDates.erase(fixDates.begin(), it1);\n        // check we have at least 1 to stop set fault on vector(fixDates.size() - 1, true) but maybe check should be 2\n        QL_REQUIRE(fixDates.size() >= 2,\n                   \"Not enough schedule dates are left in Swaption fixed leg (check exercise dates)\");\n        fixedSchedule = Schedule(fixDates, fixedSchedule.calendar(), Unadjusted, boost::none, boost::none, boost::none,\n                                 boost::none, std::vector<bool>(fixDates.size() - 1, true));\n        std::vector<Date> floatingDates = floatingSchedule.dates();\n        auto it2 = std::lower_bound(floatingDates.begin(), floatingDates.end(), firstExerciseDate);\n        floatingDates.erase(floatingDates.begin(), it2);\n        QL_REQUIRE(floatingDates.size() >= 2,\n                   \"Not enough schedule dates are left in Swaption floating leg (check exercise dates)\");\n        floatingSchedule = Schedule(floatingDates, floatingSchedule.calendar(), Unadjusted, boost::none, boost::none,\n                                    boost::none, boost::none, std::vector<bool>(floatingDates.size() - 1, true));\n    }\n\n    // Build a vanilla (bullet) swap underlying\n    boost::shared_ptr<VanillaSwap> swap(new VanillaSwap(type, nominal, fixedSchedule, rate, fixedDayCounter,\n                                                        floatingSchedule, *index, spread, floatingDayCounter,\n                                                        paymentConvention));\n\n    swap->setPricingEngine(swapBuilder->engine(currency));\n\n    // Set other ore::data::Trade details\n    npvCurrency_ = ccy;\n    notional_ = nominal;\n    notionalCurrency_ = ccy;\n    legCurrencies_ = vector<string>(2, ccy);\n    legs_.push_back(swap->fixedLeg());\n    legs_.push_back(swap->floatingLeg());\n    legPayers_.push_back(swap_[fixedLegIndex].isPayer());\n    legPayers_.push_back(swap_[floatingLegIndex].isPayer());\n\n    return swap;\n}\n\nboost::shared_ptr<NonstandardSwap>\nSwaption::buildNonStandardSwap(const boost::shared_ptr<EngineFactory>& engineFactory) {\n    QL_REQUIRE(swap_.size() == 2, \"Two swap legs expected\");\n    QL_REQUIRE(swap_[0].currency() == swap_[1].currency(), \"single currency swap expected\");\n    QL_REQUIRE(swap_[0].isPayer() != swap_[1].isPayer(), \"pay and receive leg expected\");\n\n    Size fixedLegIndex, floatingLegIndex;\n    if (swap_[0].legType() == \"Floating\" && swap_[1].legType() == \"Fixed\") {\n        floatingLegIndex = 0;\n        fixedLegIndex = 1;\n    } else if (swap_[1].legType() == \"Floating\" && swap_[0].legType() == \"Fixed\") {\n        floatingLegIndex = 1;\n        fixedLegIndex = 0;\n    } else {\n        QL_FAIL(\"Invalid leg types \" << swap_[0].legType() << \" + \" << swap_[1].legType());\n    }\n    boost::shared_ptr<FixedLegData> fixedLegData =\n        boost::dynamic_pointer_cast<FixedLegData>(swap_[fixedLegIndex].concreteLegData());\n    boost::shared_ptr<FloatingLegData> floatingLegData =\n        boost::dynamic_pointer_cast<FloatingLegData>(swap_[floatingLegIndex].concreteLegData());\n\n    boost::shared_ptr<EngineBuilder> tmp = engineFactory->builder(\"Swap\");\n    boost::shared_ptr<SwapEngineBuilderBase> swapBuilder = boost::dynamic_pointer_cast<SwapEngineBuilderBase>(tmp);\n    QL_REQUIRE(swapBuilder, \"No Swap Builder found for Swaption \" << id());\n\n    // Get Trade details\n    string ccy = swap_[0].currency();\n    Currency currency = parseCurrency(ccy);\n    Schedule fixedSchedule = makeSchedule(swap_[fixedLegIndex].schedule());\n    Schedule floatingSchedule = makeSchedule(swap_[floatingLegIndex].schedule());\n    vector<Real> fixedNominal = buildScheduledVectorNormalised(\n        swap_[fixedLegIndex].notionals(), swap_[fixedLegIndex].notionalDates(), fixedSchedule, (Real)Null<Real>());\n    vector<Real> floatNominal =\n        buildScheduledVectorNormalised(swap_[floatingLegIndex].notionals(), swap_[floatingLegIndex].notionalDates(),\n                                       floatingSchedule, (Real)Null<Real>());\n    vector<Real> fixedRate = buildScheduledVectorNormalised(fixedLegData->rates(), fixedLegData->rateDates(),\n                                                            fixedSchedule, (Real)Null<Real>());\n    vector<Real> spreads = buildScheduledVectorNormalised(floatingLegData->spreads(), floatingLegData->spreadDates(),\n                                                          floatingSchedule, (Real)Null<Real>());\n    // gearings are optional, i.e. may be empty\n    vector<Real> gearings = buildScheduledVectorNormalised(floatingLegData->gearings(), floatingLegData->gearingDates(),\n                                                           floatingSchedule, 1.0);\n    string indexName = floatingLegData->index();\n    DayCounter fixedDayCounter = parseDayCounter(swap_[fixedLegIndex].dayCounter());\n    Handle<IborIndex> index =\n        engineFactory->market()->iborIndex(indexName, swapBuilder->configuration(MarketContext::pricing));\n    underlyingIndexQlName_ = index->name();\n    DayCounter floatingDayCounter = parseDayCounter(swap_[floatingLegIndex].dayCounter());\n    BusinessDayConvention paymentConvention = parseBusinessDayConvention(swap_[floatingLegIndex].paymentConvention());\n\n    // We treat overnight and bma indices approximately as ibor indices and warn about this in the log\n    if (boost::dynamic_pointer_cast<OvernightIndex>(*index) ||\n        boost ::dynamic_pointer_cast<QuantExt::BMAIndexWrapper>(*index))\n        ALOG(\"Swaption trade \" << id() << \" on ON or BMA index '\" << underlyingIndex_\n                               << \"' built, will treat the index approximately as an ibor index\");\n\n    VanillaSwap::Type type = swap_[fixedLegIndex].isPayer() ? VanillaSwap::Payer : VanillaSwap::Receiver;\n\n    // Build a vanilla (bullet) swap underlying\n    boost::shared_ptr<NonstandardSwap> swap(new NonstandardSwap(type, fixedNominal, floatNominal, fixedSchedule,\n                                                                fixedRate, fixedDayCounter, floatingSchedule, *index,\n                                                                gearings, spreads, floatingDayCounter,\n                                                                false, // no intermediate notional exchanges\n                                                                false, // no final notional exchanges\n                                                                paymentConvention));\n\n    swap->setPricingEngine(swapBuilder->engine(currency));\n\n    // Set other ore::data::Trade details\n    npvCurrency_ = ccy;\n    notional_ = std::max(currentNotional(swap->fixedLeg()), currentNotional(swap->floatingLeg()));\n    notionalCurrency_ = npvCurrency_;\n    legCurrencies_ = vector<string>(2, ccy);\n    legs_.push_back(swap->fixedLeg());\n    legs_.push_back(swap->floatingLeg());\n    legPayers_.push_back(swap_[fixedLegIndex].isPayer());\n    legPayers_.push_back(swap_[floatingLegIndex].isPayer());\n\n    return swap;\n}\n\nstd::vector<boost::shared_ptr<Instrument>>\nSwaption::buildUnderlyingSwaps(const boost::shared_ptr<PricingEngine>& swapEngine,\n                               const boost::shared_ptr<Swap>& underlyingSwap, const std::vector<Date>& exerciseDates) {\n    std::vector<boost::shared_ptr<Instrument>> swaps;\n    for (Size i = 0; i < exerciseDates.size(); ++i) {\n        std::vector<Leg> legs(2);\n        std::vector<bool> payer(2);\n        for (Size j = 0; j < legs.size(); ++j) {\n            legs[j] = underlyingSwap->leg(j);\n            // if in the swap data the fixed leg is the first component, the legs in the underlying\n            // swap match the order of the legs in the swap data, otherwise they are swapped\n            payer[j] = swap_[0].legType() == \"Fixed\" ? swap_[j].isPayer() : swap_[1 - j].isPayer();\n            boost::shared_ptr<Coupon> coupon = boost::dynamic_pointer_cast<Coupon>(legs[j].front());\n            while (legs[j].size() > 0 && coupon->accrualStartDate() < exerciseDates[i]) {\n                legs[j].erase(legs[j].begin());\n                coupon = boost::dynamic_pointer_cast<Coupon>(legs[j].front());\n            }\n        }\n        boost::shared_ptr<Swap> newSwap(new Swap(legs, payer));\n        newSwap->setPricingEngine(swapEngine);\n        swaps.push_back(newSwap);\n        if (legs[0].size() > 0 && legs[1].size() > 0) {\n            boost::shared_ptr<Coupon> coupon1 = boost::dynamic_pointer_cast<Coupon>(legs[0].front());\n            boost::shared_ptr<Coupon> coupon2 = boost::dynamic_pointer_cast<Coupon>(legs[1].front());\n            DLOG(\"Added underlying Swap start \" << QuantLib::io::iso_date(coupon1->accrualStartDate()) << \" \"\n                                                << QuantLib::io::iso_date(coupon2->accrualStartDate()) << \" \"\n                                                << \"exercise \" << QuantLib::io::iso_date(exerciseDates[i]));\n        } else {\n            WLOG(\"Added underlying Swap with at least one empty leg for exercise \"\n                 << QuantLib::io::iso_date(exerciseDates[i]) << \"!\");\n        }\n    }\n    return swaps;\n}\n\nvoid Swaption::fromXML(XMLNode* node) {\n    Trade::fromXML(node);\n    XMLNode* swapNode = XMLUtils::getChildNode(node, \"SwaptionData\");\n    option_.fromXML(XMLUtils::getChildNode(swapNode, \"OptionData\"));\n    swap_.clear();\n    vector<XMLNode*> nodes = XMLUtils::getChildrenNodes(swapNode, \"LegData\");\n    for (Size i = 0; i < nodes.size(); i++) {\n        LegData ld;\n        ld.fromXML(nodes[i]);\n        swap_.push_back(ld);\n    }\n}\n\nXMLNode* Swaption::toXML(XMLDocument& doc) {\n    XMLNode* node = Trade::toXML(doc);\n    XMLNode* swaptionNode = doc.allocNode(\"SwaptionData\");\n    XMLUtils::appendNode(node, swaptionNode);\n\n    XMLUtils::appendNode(swaptionNode, option_.toXML(doc));\n    for (Size i = 0; i < swap_.size(); i++)\n        XMLUtils::appendNode(swaptionNode, swap_[i].toXML(doc));\n\n    return node;\n}\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "f6dc29952c6507a3db1d2fde92a29018fa24cb64", "size": 36956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/portfolio/swaption.cpp", "max_stars_repo_name": "nvolfango/Engine", "max_stars_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T17:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T17:24:17.000Z", "max_issues_repo_path": "OREData/ored/portfolio/swaption.cpp", "max_issues_repo_name": "zhangjiayin/Engine", "max_issues_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OREData/ored/portfolio/swaption.cpp", "max_forks_repo_name": "zhangjiayin/Engine", "max_forks_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "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": 54.1083455344, "max_line_length": 120, "alphanum_fraction": 0.6469314861, "num_tokens": 8576, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.2175157625890877}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_LSAT_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_LSAT_HPP\n\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\n// This file is automatically generated. DO NOT EDIT.\n\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Original copyright notice:\n \n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#include <boost/math/special_functions/hypot.hpp>\n\n#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>\n#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>\n\nnamespace boost { namespace geometry { namespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace lsat{ \n            static const double TOL = 1e-7;\n            static const double PI_HALFPI = 4.71238898038468985766;\n            static const double TWOPI_HALFPI = 7.85398163397448309610;\n\n            struct par_lsat\n            {\n                double a2, a4, b, c1, c3;\n                double q, t, u, w, p22, sa, ca, xj, rlm, rlm2;\n            };\n            /* based upon Snyder and Linck, USGS-NMD */\n            template <typename Parameters>\n                inline void\n            seraz0(double lam, double mult, Parameters& par, par_lsat& proj_parm) {\n                double sdsq, h, s, fc, sd, sq, d__1;\n            \n                lam *= DEG_TO_RAD;\n                sd = sin(lam);\n                sdsq = sd * sd;\n                s = proj_parm.p22 * proj_parm.sa * cos(lam) * sqrt((1. + proj_parm.t * sdsq) / ((\n                    1. + proj_parm.w * sdsq) * (1. + proj_parm.q * sdsq)));\n                d__1 = 1. + proj_parm.q * sdsq;\n                h = sqrt((1. + proj_parm.q * sdsq) / (1. + proj_parm.w * sdsq)) * ((1. + \n                    proj_parm.w * sdsq) / (d__1 * d__1) - proj_parm.p22 * proj_parm.ca);\n                sq = sqrt(proj_parm.xj * proj_parm.xj + s * s);\n                proj_parm.b += fc = mult * (h * proj_parm.xj - s * s) / sq;\n                proj_parm.a2 += fc * cos(lam + lam);\n                proj_parm.a4 += fc * cos(lam * 4.);\n                fc = mult * s * (h + proj_parm.xj) / sq;\n                proj_parm.c1 += fc * cos(lam);\n                proj_parm.c3 += fc * cos(lam * 3.);\n            }\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename Geographic, typename Cartesian, typename Parameters>\n            struct base_lsat_ellipsoid : public base_t_fi<base_lsat_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>\n            {\n\n                 typedef double geographic_type;\n                 typedef double cartesian_type;\n\n                par_lsat m_proj_parm;\n\n                inline base_lsat_ellipsoid(const Parameters& par)\n                    : base_t_fi<base_lsat_ellipsoid<Geographic, Cartesian, Parameters>,\n                     Geographic, Cartesian, Parameters>(*this, par) {}\n\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\n                {\n                    int l, nn;\n                    double lamt, xlam, sdsq, c, d, s, lamdp, phidp, lampp, tanph,\n                        lamtp, cl, sd, sp, fac, sav, tanphi;\n                \n                    if (lp_lat > HALFPI)\n                        lp_lat = HALFPI;\n                    else if (lp_lat < -HALFPI)\n                        lp_lat = -HALFPI;\n                    lampp = lp_lat >= 0. ? HALFPI : PI_HALFPI;\n                    tanphi = tan(lp_lat);\n                    for (nn = 0;;) {\n                        sav = lampp;\n                        lamtp = lp_lon + this->m_proj_parm.p22 * lampp;\n                        cl = cos(lamtp);\n                        if (fabs(cl) < TOL)\n                            lamtp -= TOL;\n                        fac = lampp - sin(lampp) * (cl < 0. ? -HALFPI : HALFPI);\n                        for (l = 50; l; --l) {\n                            lamt = lp_lon + this->m_proj_parm.p22 * sav;\n                            if (fabs(c = cos(lamt)) < TOL)\n                                lamt -= TOL;\n                            xlam = (this->m_par.one_es * tanphi * this->m_proj_parm.sa + sin(lamt) * this->m_proj_parm.ca) / c;\n                            lamdp = atan(xlam) + fac;\n                            if (fabs(fabs(sav) - fabs(lamdp)) < TOL)\n                                break;\n                            sav = lamdp;\n                        }\n                        if (!l || ++nn >= 3 || (lamdp > this->m_proj_parm.rlm && lamdp < this->m_proj_parm.rlm2))\n                            break;\n                        if (lamdp <= this->m_proj_parm.rlm)\n                            lampp = TWOPI_HALFPI;\n                        else if (lamdp >= this->m_proj_parm.rlm2)\n                            lampp = HALFPI;\n                    }\n                    if (l) {\n                        sp = sin(lp_lat);\n                        phidp = aasin((this->m_par.one_es * this->m_proj_parm.ca * sp - this->m_proj_parm.sa * cos(lp_lat) * \n                            sin(lamt)) / sqrt(1. - this->m_par.es * sp * sp));\n                        tanph = log(tan(FORTPI + .5 * phidp));\n                        sd = sin(lamdp);\n                        sdsq = sd * sd;\n                        s = this->m_proj_parm.p22 * this->m_proj_parm.sa * cos(lamdp) * sqrt((1. + this->m_proj_parm.t * sdsq)\n                             / ((1. + this->m_proj_parm.w * sdsq) * (1. + this->m_proj_parm.q * sdsq)));\n                        d = sqrt(this->m_proj_parm.xj * this->m_proj_parm.xj + s * s);\n                        xy_x = this->m_proj_parm.b * lamdp + this->m_proj_parm.a2 * sin(2. * lamdp) + this->m_proj_parm.a4 *\n                            sin(lamdp * 4.) - tanph * s / d;\n                        xy_y = this->m_proj_parm.c1 * sd + this->m_proj_parm.c3 * sin(lamdp * 3.) + tanph * this->m_proj_parm.xj / d;\n                    } else\n                        xy_x = xy_y = HUGE_VAL;\n                }\n\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\n                {\n                    int nn;\n                    double lamt, sdsq, s, lamdp, phidp, sppsq, dd, sd, sl, fac, scl, sav, spp;\n                \n                    lamdp = xy_x / this->m_proj_parm.b;\n                    nn = 50;\n                    do {\n                        sav = lamdp;\n                        sd = sin(lamdp);\n                        sdsq = sd * sd;\n                        s = this->m_proj_parm.p22 * this->m_proj_parm.sa * cos(lamdp) * sqrt((1. + this->m_proj_parm.t * sdsq)\n                             / ((1. + this->m_proj_parm.w * sdsq) * (1. + this->m_proj_parm.q * sdsq)));\n                        lamdp = xy_x + xy_y * s / this->m_proj_parm.xj - this->m_proj_parm.a2 * sin(\n                            2. * lamdp) - this->m_proj_parm.a4 * sin(lamdp * 4.) - s / this->m_proj_parm.xj * (\n                            this->m_proj_parm.c1 * sin(lamdp) + this->m_proj_parm.c3 * sin(lamdp * 3.));\n                        lamdp /= this->m_proj_parm.b;\n                    } while (fabs(lamdp - sav) >= TOL && --nn);\n                    sl = sin(lamdp);\n                    fac = exp(sqrt(1. + s * s / this->m_proj_parm.xj / this->m_proj_parm.xj) * (xy_y - \n                        this->m_proj_parm.c1 * sl - this->m_proj_parm.c3 * sin(lamdp * 3.)));\n                    phidp = 2. * (atan(fac) - FORTPI);\n                    dd = sl * sl;\n                    if (fabs(cos(lamdp)) < TOL)\n                        lamdp -= TOL;\n                    spp = sin(phidp);\n                    sppsq = spp * spp;\n                    lamt = atan(((1. - sppsq * this->m_par.rone_es) * tan(lamdp) * \n                        this->m_proj_parm.ca - spp * this->m_proj_parm.sa * sqrt((1. + this->m_proj_parm.q * dd) * (\n                        1. - sppsq) - sppsq * this->m_proj_parm.u) / cos(lamdp)) / (1. - sppsq \n                        * (1. + this->m_proj_parm.u)));\n                    sl = lamt >= 0. ? 1. : -1.;\n                    scl = cos(lamdp) >= 0. ? 1. : -1;\n                    lamt -= HALFPI * (1. - scl) * sl;\n                    lp_lon = lamt - this->m_proj_parm.p22 * lamdp;\n                    if (fabs(this->m_proj_parm.sa) < TOL)\n                        lp_lat = aasin(spp / sqrt(this->m_par.one_es * this->m_par.one_es + this->m_par.es * sppsq));\n                    else\n                        lp_lat = atan((tan(lamdp) * cos(lamt) - this->m_proj_parm.ca * sin(lamt)) /\n                            (this->m_par.one_es * this->m_proj_parm.sa));\n                }\n            };\n\n            // Space oblique for LANDSAT\n            template <typename Parameters>\n            void setup_lsat(Parameters& par, par_lsat& proj_parm)\n            {\n                int land, path;\n                double lam, alf, esc, ess;\n                land = pj_param(par.params, \"ilsat\").i;\n                if (land <= 0 || land > 5) throw proj_exception(-28);\n                path = pj_param(par.params, \"ipath\").i;\n                if (path <= 0 || path > (land <= 3 ? 251 : 233)) throw proj_exception(-29);\n                if (land <= 3) {\n                    par.lam0 = DEG_TO_RAD * 128.87 - TWOPI / 251. * path;\n                    proj_parm.p22 = 103.2669323;\n                    alf = DEG_TO_RAD * 99.092;\n                } else {\n                    par.lam0 = DEG_TO_RAD * 129.3 - TWOPI / 233. * path;\n                    proj_parm.p22 = 98.8841202;\n                    alf = DEG_TO_RAD * 98.2;\n                }\n                proj_parm.p22 /= 1440.;\n                proj_parm.sa = sin(alf);\n                proj_parm.ca = cos(alf);\n                if (fabs(proj_parm.ca) < 1e-9)\n                    proj_parm.ca = 1e-9;\n                esc = par.es * proj_parm.ca * proj_parm.ca;\n                ess = par.es * proj_parm.sa * proj_parm.sa;\n                proj_parm.w = (1. - esc) * par.rone_es;\n                proj_parm.w = proj_parm.w * proj_parm.w - 1.;\n                proj_parm.q = ess * par.rone_es;\n                proj_parm.t = ess * (2. - par.es) * par.rone_es * par.rone_es;\n                proj_parm.u = esc * par.rone_es;\n                proj_parm.xj = par.one_es * par.one_es * par.one_es;\n                proj_parm.rlm = PI * (1. / 248. + .5161290322580645);\n                proj_parm.rlm2 = proj_parm.rlm + TWOPI;\n                proj_parm.a2 = proj_parm.a4 = proj_parm.b = proj_parm.c1 = proj_parm.c3 = 0.;\n                seraz0(0., 1., par, proj_parm);\n                for (lam = 9.;\n             lam <= 81.0001;\n             lam += 18.)\n                    seraz0(lam, 4., par, proj_parm);\n                for (lam = 18;\n             lam <= 72.0001;\n             lam += 18.)\n                    seraz0(lam, 2., par, proj_parm);\n                seraz0(90., 1., par, proj_parm);\n                proj_parm.a2 /= 30.;\n                proj_parm.a4 /= 60.;\n                proj_parm.b /= 30.;\n                proj_parm.c1 /= 15.;\n                proj_parm.c3 /= 45.;\n                // par.inv = e_inverse;\n                // par.fwd = e_forward;\n            }\n\n        }} // namespace detail::lsat\n    #endif // doxygen \n\n    /*!\n        \\brief Space oblique for LANDSAT projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Cylindrical\n         - Spheroid\n         - Ellipsoid\n         - lsat= path=\n        \\par Example\n        \\image html ex_lsat.gif\n    */\n    template <typename Geographic, typename Cartesian, typename Parameters = parameters>\n    struct lsat_ellipsoid : public detail::lsat::base_lsat_ellipsoid<Geographic, Cartesian, Parameters>\n    {\n        inline lsat_ellipsoid(const Parameters& par) : detail::lsat::base_lsat_ellipsoid<Geographic, Cartesian, Parameters>(par)\n        {\n            detail::lsat::setup_lsat(this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Factory entry(s)\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        class lsat_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>\n        {\n            public :\n                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const\n                {\n                    return new base_v_fi<lsat_ellipsoid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);\n                }\n        };\n\n        template <typename Geographic, typename Cartesian, typename Parameters>\n        inline void lsat_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)\n        {\n            factory.add_to_factory(\"lsat\", new lsat_entry<Geographic, Cartesian, Parameters>);\n        }\n\n    } // namespace detail \n    #endif // doxygen\n\n}}} // namespace boost::geometry::projections\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_LSAT_HPP\n\n", "meta": {"hexsha": "816c63fbbebe0fca49a1a4fa6f370b3bf16e95b4", "size": 14665, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/geometry/extensions/gis/projections/proj/lsat.hpp", "max_stars_repo_name": "ballisticwhisper/boost", "max_stars_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-01-02T14:24:56.000Z", "max_stars_repo_stars_event_max_datetime": "2015-01-02T14:25:17.000Z", "max_issues_repo_path": "boost/geometry/extensions/gis/projections/proj/lsat.hpp", "max_issues_repo_name": "ballisticwhisper/boost", "max_issues_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-13T23:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-03T08:13:26.000Z", "max_forks_repo_path": "boost/geometry/extensions/gis/projections/proj/lsat.hpp", "max_forks_repo_name": "ballisticwhisper/boost", "max_forks_repo_head_hexsha": "f72119ab640b564c4b983bd457457046b52af9ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-05-29T13:41:15.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-29T13:41:15.000Z", "avg_line_length": 48.8833333333, "max_line_length": 133, "alphanum_fraction": 0.5091033072, "num_tokens": 3665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.217338523250886}}
{"text": "// Copyright (c) 2020 Vitaly Chipounov\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include <boost/foreach.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/xml_parser.hpp>\n#include <iomanip>\n#include <iostream>\n#include <math.h>\n\n#include <gpsmap/gpx.h>\n\nnamespace pt = boost::property_tree;\n\nnamespace gpsmap {\n\nstd::ostream &operator<<(std::ostream &os, TrackItem const &m) {\n    os << \"TrackItem \" << m.OriginalTimestamp << \" lat=\" << m.Latitude << \" lon=\" << m.Longitude << \" speed=\" << m.Speed\n       << \" alt=\" << m.Elevation;\n    return os;\n}\n\ntime_t parse_time(const std::string &iso) {\n    std::stringstream ss(iso);\n    std::tm t = {};\n    if (ss >> std::get_time(&t, \"%Y-%m-%dT%H:%M:%SZ\")) {\n        return std::mktime(&t) - timezone;\n    }\n    return 0;\n}\n\nstd::string time_to_str(time_t t) {\n    char buff[64];\n    struct tm *timeinfo;\n    timeinfo = localtime(&t);\n    strftime(buff, sizeof(buff), \"%Y-%m-%d %H:%M:%S\", timeinfo);\n    return buff;\n}\n\n// Returns the distance in meters between the given coordinates (in degrees)\nstatic double distance(double lat1, double lon1, double lat2, double lon2) {\n    // Radius of Earth in meters, R = 6371 * 1000\n    long double R = 6371 * 1000;\n\n    lat1 = to_rad(lat1);\n    lon1 = to_rad(lon1);\n    lat2 = to_rad(lat2);\n    lon2 = to_rad(lon2);\n\n    // Haversine Formula\n    long double dlon = lon2 - lon1;\n    long double dlat = lat2 - lat1;\n\n    long double ans = pow(sin(dlat / 2), 2) + cos(lat1) * cos(lat2) * pow(sin(dlon / 2), 2);\n\n    return R * 2 * asin(sqrt(ans));\n}\n\nstatic double bearing(double lat1, double lon1, double lat2, double lon2) {\n    lat1 = to_rad(lat1);\n    lon1 = to_rad(lon1);\n    lat2 = to_rad(lat2);\n    lon2 = to_rad(lon2);\n\n    auto x = cos(lat2) * sin(lon2 - lon1);\n    auto y = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(lon2 - lon1);\n    auto bearing = atan2(x, y);\n    return to_deg(bearing);\n}\n\nstatic double bearing(const TrackItem &i1, const TrackItem &i2) {\n    return bearing(i1.Latitude, i1.Longitude, i2.Latitude, i2.Longitude);\n}\n\nstatic double GetGrade(const std::vector<TrackItem> &items, int i) {\n    const double maxDist = 50.0;\n\n    // Get altitude and cumulative distance on the left\n    double ldist = 0.0;\n    double lelev = 0.0;\n    for (auto l = i; l >= 0; --l) {\n        ldist += items[l].DistanceDelta;\n        lelev = items[l].Elevation;\n        if (ldist >= maxDist) {\n            break;\n        }\n    }\n\n    // Get altitude and cumulative distance on the right\n    double rdist = 0.0;\n    double relev = 0.0;\n    for (size_t l = i; l < items.size(); ++l) {\n        rdist += items[l].DistanceDelta;\n        relev = items[l].Elevation;\n        if (rdist >= maxDist) {\n            break;\n        }\n    }\n\n    auto td = ldist + rdist;\n    if (td < 0.01) {\n        return 0.0;\n    }\n\n    return (relev - lelev) / td * 100;\n}\n\nstd::shared_ptr<GPX> GPX::Create() {\n    return std::shared_ptr<GPX>(new GPX());\n}\n\nvoid GPX::LoadFromFile(const std::string &path) {\n    pt::ptree tree;\n    pt::read_xml(path, tree);\n\n    bool first = true;\n\n    BOOST_FOREACH (pt::ptree::value_type &trkseg, tree.get_child(\"gpx.trk\")) {\n        BOOST_FOREACH (pt::ptree::value_type &trkpt, trkseg.second) {\n            TrackItem item;\n            auto lat = trkpt.second.get_child(\"<xmlattr>.lat\").get_value(\"\");\n            auto lon = trkpt.second.get_child(\"<xmlattr>.lon\").get_value(\"\");\n            auto speed = trkpt.second.get_child(\"speed\").get_value(\"\");\n            auto elevation = trkpt.second.get_child(\"ele\").get_value(\"\");\n            auto time = trkpt.second.get_child(\"time\").get_value(\"\");\n\n            item.Speed = strtod(speed.c_str(), nullptr);\n            item.Latitude = strtod(lat.c_str(), nullptr);\n            item.Longitude = strtod(lon.c_str(), nullptr);\n            item.Elevation = strtod(elevation.c_str(), nullptr);\n            item.OriginalTimestamp = time;\n            item.Timestamp = parse_time(time);\n            item.Grade = 0.0;\n            item.DistanceDelta = 0.0;\n            item.TotalDistance = 0.0;\n            item.Bearing = 0.0;\n            item.IsTrackStart = first;\n            first = false;\n\n            m_trackItems.push_back(item);\n        }\n    }\n\n    std::sort(m_trackItems.begin(), m_trackItems.end());\n\n    for (size_t i = 1; i < m_trackItems.size(); ++i) {\n        auto &ti0 = m_trackItems[i - 1];\n        if (i == 1) {\n            ti0.TotalDistance = m_initialDistance;\n        }\n\n        auto &ti1 = m_trackItems[i];\n        ti1.DistanceDelta = distance(ti0.Latitude, ti0.Longitude, ti1.Latitude, ti1.Longitude);\n        ti1.TotalDistance = ti0.TotalDistance + ti1.DistanceDelta;\n    }\n\n    for (size_t i = 0; i < m_trackItems.size() - 1; ++i) {\n        m_trackItems[i].Grade = GetGrade(m_trackItems, i);\n        auto b = bearing(m_trackItems[i], m_trackItems[i + 1]);\n        if (b == 0) {\n            if (i > 1) {\n                m_trackItems[i].Bearing = m_trackItems[i - 1].Bearing;\n            }\n        } else {\n            m_trackItems[i].Bearing = b;\n        }\n    }\n}\n\nvoid GPX::CreateSegments() {\n    std::vector<int> boundaries;\n\n    if (m_trackItems.size() == 0) {\n        return;\n    }\n\n    boundaries.push_back(0);\n\n    for (size_t i = 1; i < m_trackItems.size(); ++i) {\n        const auto &prevItem = m_trackItems[i - 1];\n        const auto &item = m_trackItems[i];\n\n        if (item.Latitude == prevItem.Latitude && item.Longitude == prevItem.Longitude) {\n            boundaries.push_back(i);\n        }\n    }\n\n    auto bs = boundaries.size();\n    for (size_t i = 0; i < bs; ++i) {\n        int start = boundaries[i];\n        int end = i == bs - 1 ? m_trackItems.size() - 1 : boundaries[i + 1];\n\n        if (i == bs - 1) {\n            if (start < end) {\n                m_segments.push_back(Segment(start, end));\n            }\n        } else {\n            assert(start < end);\n            m_segments.push_back(Segment(start, end));\n        }\n    }\n}\n\nbool GPX::GetItem(size_t index, TrackItem &item) {\n    if (index >= m_trackItems.size() || index < 0) {\n        return false;\n    }\n\n    item = m_trackItems[index];\n    return true;\n}\n\n// Return the first element i such that i.timestamp <= timestamp < (i+1).timestamp\nbool GPX::GetClosestItem(time_t timestamp, size_t &nextItem, TrackItem &item) {\n    if (nextItem >= m_trackItems.size() || nextItem < 0) {\n        return false;\n    }\n\n    if (timestamp < m_trackItems[nextItem].Timestamp) {\n        return false;\n    }\n\n    for (auto i = nextItem; i + 1 < m_trackItems.size(); ++i) {\n        const auto &i1 = m_trackItems[i];\n        const auto &i2 = m_trackItems[i + 1];\n        if (i1.Timestamp <= timestamp && timestamp < i2.Timestamp) {\n            item = i1;\n            nextItem = i;\n            return true;\n        }\n    }\n\n    return false;\n}\n\n} // namespace gpsmap\n", "meta": {"hexsha": "a4cdf9b0cbc06fb8624c6df8a4b4ac839858c4d5", "size": 7854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gpx.cpp", "max_stars_repo_name": "vitalych/gpsmap", "max_stars_repo_head_hexsha": "4716a6c9e52eda08beeaf6e19448a8fff5e00fb8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-20T08:13:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-20T08:13:32.000Z", "max_issues_repo_path": "src/gpx.cpp", "max_issues_repo_name": "vitalych/gpsmap", "max_issues_repo_head_hexsha": "4716a6c9e52eda08beeaf6e19448a8fff5e00fb8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-10-11T12:23:33.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-23T14:40:31.000Z", "max_forks_repo_path": "src/gpx.cpp", "max_forks_repo_name": "vitalych/gpsmap", "max_forks_repo_head_hexsha": "4716a6c9e52eda08beeaf6e19448a8fff5e00fb8", "max_forks_repo_licenses": ["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.9212598425, "max_line_length": 120, "alphanum_fraction": 0.5972752737, "num_tokens": 2144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526660244837, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.21723899418401352}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_RIPEMD_FUNCTIONS_HPP\n#define CRYPTO3_RIPEMD_FUNCTIONS_HPP\n\n#include <boost/crypto3/hash/detail/ripemd/ripemd_policy.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace hashes {\n            namespace detail {\n                template<std::size_t DigestBits>\n                struct ripemd_functions : public ripemd_policy<DigestBits> {\n                    typedef ripemd_policy<DigestBits> policy_type;\n\n                    typedef typename policy_type::word_type word_type;\n\n                    struct f1 {\n                        inline word_type operator()(word_type x, word_type y, word_type z) const {\n                            return x ^ y ^ z;\n                        }\n                    };\n\n                    struct f2 {\n                        inline word_type operator()(word_type x, word_type y, word_type z) const {\n                            return (x & y) | (~x & z);\n                        }\n                    };\n\n                    struct f3 {\n                        inline word_type operator()(word_type x, word_type y, word_type z) const {\n                            return (x | ~y) ^ z;\n                        }\n                    };\n\n                    struct f4 {\n                        inline word_type operator()(word_type x, word_type y, word_type z) const {\n                            return (x & z) | (y & ~z);\n                        }\n                    };\n\n                    struct f5 {\n                        inline word_type operator()(word_type x, word_type y, word_type z) const {\n                            return x ^ (y | ~z);\n                        }\n                    };\n\n                    template<typename F>\n                    inline static void transform(word_type &a, word_type &b, word_type &c, word_type &d, word_type x,\n                                                 word_type k, word_type s) {\n                        word_type T = policy_type::rotl(a + F()(b, c, d) + x + k, s);\n                        a = d;\n                        d = c;\n                        c = b;\n                        b = T;\n                    }\n\n                    template<typename Functor>\n                    inline static void transform(word_type &a, word_type &b, word_type &c, word_type &d, word_type &e,\n                                                 word_type x, word_type k, word_type s) {\n                        word_type T = policy_type::rotl(a + Functor()(b, c, d) + x + k, s) + e;\n                        a = e;\n                        e = d;\n                        d = policy_type::template rotl<10>(c);\n                        c = b;\n                        b = T;\n                    }\n                };\n            }    // namespace detail\n        }        // namespace hashes\n    }            // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_RIPEMD_FUNCTIONS_HPP\n", "meta": {"hexsha": "3ef69eb482416a51318e17f846aa073d03a56711", "size": 3334, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/hash/detail/ripemd/ripemd_functions.hpp", "max_stars_repo_name": "NilFoundation/boost-crypto", "max_stars_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-02T06:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T04:55:03.000Z", "max_issues_repo_path": "include/boost/crypto3/hash/detail/ripemd/ripemd_functions.hpp", "max_issues_repo_name": "NilFoundation/boost-crypto", "max_issues_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-06T21:49:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T04:54:51.000Z", "max_forks_repo_path": "include/boost/crypto3/hash/detail/ripemd/ripemd_functions.hpp", "max_forks_repo_name": "NilFoundation/boost-crypto", "max_forks_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:14:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:14:37.000Z", "avg_line_length": 40.6585365854, "max_line_length": 118, "alphanum_fraction": 0.4142171566, "num_tokens": 643, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.21723898060202199}}
{"text": "/*\n    This file is part of Mitsuba, a physically based rendering system.\n\n    Copyright (c) 2007-2014 by Wenzel Jakob and others.\n\n    Mitsuba is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License Version 3\n    as published by the Free Software Foundation.\n\n    Mitsuba is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <mitsuba/bidir/manifold.h>\n#include <mitsuba/bidir/path.h>\n#include <mitsuba/core/statistics.h>\n#define EIGEN_DONT_PARALLELIZE\n#define EIGEN_NO_DEBUG\n#include <Eigen/LU>\n#include <Eigen/Geometry>\n\nMTS_NAMESPACE_BEGIN\n\n/* Some statistics counters */\nstatic StatsCounter statsStepFailed(\n\t\t\"Specular manifold\", \"Retries (step failed)\");\nstatic StatsCounter statsStepTooFar(\n\t\t\"Specular manifold\", \"Retries (step increased distance)\");\nstatic StatsCounter statsStepSuccess(\n\t\t\"Specular manifold\", \"Successful steps\");\nstatic StatsCounter statsAvgIterations(\n\t\t\"Specular manifold\", \"Avg. iterations per walk\", EAverage);\nstatic StatsCounter statsAvgIterationsSuccess(\n\t\t\"Specular manifold\", \"Avg. iterations per successful walk\", EAverage);\nstatic StatsCounter statsAvgManifoldSize(\n\t\t\"Specular manifold\", \"Avg. manifold size\", EAverage);\nstatic StatsCounter statsSuccessfulWalks(\n\t\t\"Specular manifold\", \"Successful walks\", EPercentage);\nstatic StatsCounter statsMediumSuccess(\n\t\t\"Specular manifold\", \"Successful walks w/ media\", EPercentage);\nstatic StatsCounter statsNonManifold(\n\t\t\"Specular manifold\", \"Non-manifold\", EPercentage);\nstatic StatsCounter statsUpdateFailed(\n\t\t\"Specular manifold\", \"Update failed\");\nstatic StatsCounter statsMaxManifold(\n\t\t\"Specular manifold\", \"Max. manifold size\", EMaximumValue);\n\nSpecularManifold::SpecularManifold(const Scene *scene, int maxIterations)\n  : m_scene(scene) {\n\tm_maxIterations = maxIterations > 0 ? maxIterations :\n\t\tMTS_MANIFOLD_MAX_ITERATIONS;\n}\n\nbool SpecularManifold::init(const Path &path, int start, int end) {\n\tint step = start < end ? 1 : -1;\n\tif (path.vertex(start)->isSupernode())\n\t\tstart += step;\n\tif (path.vertex(end)->isSupernode())\n\t\tend -= step;\n\n\tconst PathVertex\n\t\t*vs = path.vertex(start),\n\t\t*ve = path.vertex(end);\n\n\t/* Create the initial vertex that is pinned in position by default */\n\tSimpleVertex v(EPinnedPosition, vs->getPosition());\n\n\t/* When the endpoint is on an orthographic camera or directional light\n\t   source, switch to a directionally pinned vertex instead */\n\tif (vs->getType() & (PathVertex::ESensorSample | PathVertex::EEmitterSample)) {\n\t\tconst PositionSamplingRecord &pRec\n\t\t\t= vs->getPositionSamplingRecord();\n\t\tuint32_t type = static_cast<const AbstractEmitter *>(pRec.object)->getType()\n\t\t\t& (AbstractEmitter::EDeltaDirection | AbstractEmitter::EDeltaPosition);\n\t\tif (type == AbstractEmitter::EDeltaDirection) {\n\t\t\tv.type = EPinnedDirection;\n\t\t\tv.gn = v.n = pRec.n;\n\t\t\tcoordinateSystem(pRec.n, v.dpdu, v.dpdv);\n\t\t}\n\t}\n\n\tm_time = vs->getTime();\n\tm_vertices.clear();\n\tm_vertices.push_back(v);\n\n\tfor (int i=start + step; i != end; i += step) {\n\t\tconst PathVertex\n\t\t\t*pred = path.vertex(i-step),\n\t\t\t*vertex = path.vertex(i),\n\t\t\t*succ = path.vertex(i+step);\n\n\t\tif (vertex->isSurfaceInteraction()) {\n\t\t\tconst Intersection &its = vertex->getIntersection();\n\t\t\tconst BSDF *bsdf = its.getBSDF();\n\n\t\t\tv.p = its.p;\n\t\t\tv.gn = its.geoFrame.n;\n\t\t\tv.n = its.shFrame.n;\n\t\t\tv.dpdu = its.dpdu;\n\t\t\tv.dpdv = its.dpdv;\n\t\t\tv.object = bsdf;\n\t\t\tv.degenerate = !vertex->isConnectable();\n\t\t\tconst Shape *shape = its.instance != NULL ? its.instance : its.shape;\n\t\t\tshape->getNormalDerivative(its, v.dndu, v.dndv);\n\n\t\t\t/* Turn into an orthonormal parameterization at 'p' */\n\t\t\tFloat invLen = 1 / v.dpdu.length();\n\t\t\tv.dpdu *= invLen;\n\t\t\tv.dndu *= invLen;\n\t\t\tFloat dp = dot(v.dpdu, v.dpdv);\n\t\t\tVector dpdv = v.dpdv - dp * v.dpdu;\n\t\t\tVector dndv = v.dndv - dp * v.dndu;\n\t\t\tinvLen = 1 / dpdv.length();\n\t\t\tv.dpdv = dpdv * invLen;\n\t\t\tv.dndv = dndv * invLen;\n\n\t\t\tVector wPred = pred->getPosition() - v.p;\n\t\t\tVector wSucc = succ->getPosition() - v.p;\n\n\t\t\tif (dot(v.gn, wPred) * dot(v.gn, wSucc) < 0) {\n\t\t\t\tv.type = ERefraction;\n\t\t\t\tv.eta = bsdf->getEta();\n\t\t\t} else {\n\t\t\t\tv.type = EReflection;\n\t\t\t\tv.eta = 1.0f;\n\t\t\t}\n\t\t} else if (vertex->isMediumInteraction()) {\n\t\t\tconst MediumSamplingRecord &mRec = vertex->getMediumSamplingRecord();\n\n\t\t\tVector wi = pred->getPosition() - mRec.p;\n\t\t\tFloat invLength = 1.0f / wi.length();\n\t\t\twi *= invLength;\n\n\t\t\tv.p = mRec.p;\n\t\t\tv.gn = v.n = Normal(0.0f);\n\n\t\t\tVector s, t;\n\t\t\tcoordinateSystem(wi, s, t);\n\n\t\t \tv.dpdu = s;\n\t\t\tv.dpdv = t;\n\t\t \tv.dndu = s * invLength;\n\t\t\tv.dndv = t * invLength;\n\n\t\t\tv.object = mRec.getPhaseFunction();\n\t\t\tv.eta = 1.0f;\n\t\t\tv.degenerate = false;\n\t\t\tv.type = EMedium;\n\t\t} else {\n\t\t\tLog(EError, \"Unknown vertex type! : %s\", vertex->toString().c_str());\n\t\t}\n\n\t\tm_vertices.push_back(v);\n\t}\n\n\tv = SimpleVertex(EMovable, ve->getPosition());\n\tm_vertices.push_back(v);\n\n\t#if MTS_MANIFOLD_DEBUG == 1\n\t\tcout << \"==========================================\" << endl;\n\t\tcout << \"Initialized specular manifold: \" << toString() << endl;\n\t#endif\n\n\treturn true;\n}\n\nbool SpecularManifold::computeTangents() {\n\tconst int n = static_cast<int>(m_vertices.size() - 1);\n\n\tm_vertices[0].Tp.setZero();\n\tm_vertices[m_vertices.size()-1].Tp.setIdentity();\n\n\tif (m_vertices.size() == 2) /* Nothing to do */\n\t\treturn true;\n\n\t/* Matrix assembly stage */\n\tfor (int i=0; i<n; ++i) {\n\t\tSimpleVertex *v = &m_vertices[i];\n\n\t\tVector wo = v[1].p - v[0].p;\n\t\tFloat ilo = wo.length();\n\n\t\tif (ilo == 0)\n\t\t\treturn false;\n\t\tilo = 1/ilo; wo *= ilo;\n\n\t\tif (v[0].type == EPinnedPosition) {\n\t\t\tv[0].a.setZero();\n\t\t\tv[0].b.setIdentity();\n\t\t\tv[0].c.setZero();\n\t\t\tcontinue;\n\t\t} else if (v[0].type == EPinnedDirection) {\n\n\t\t\tVector dC_dnext_u = (v[1].dpdu - wo * dot(wo, v[1].dpdu)) * ilo;\n\t\t\tVector dC_dnext_v = (v[1].dpdv - wo * dot(wo, v[1].dpdv)) * ilo;\n\t\t\tVector dC_dcur_u = (wo * dot(wo, v[0].dpdu) - v[0].dpdu) * ilo;\n\t\t\tVector dC_dcur_v = (wo * dot(wo, v[0].dpdv) - v[0].dpdv) * ilo;\n\n\t\t\tv[0].a.setZero();\n\t\t\tv[0].b = Matrix2x2(\n\t\t\t\tVector2(dot(dC_dcur_u, v[0].dpdu), dot(dC_dcur_u, v[0].dpdv)),\n\t\t\t\tVector2(dot(dC_dcur_v, v[0].dpdu), dot(dC_dcur_v, v[0].dpdv))\n\t\t\t);\n\t\t\tv[0].c = Matrix2x2(\n\t\t\t\tVector2(dot(dC_dnext_u, v[0].dpdu), dot(dC_dnext_u, v[0].dpdv)),\n\t\t\t\tVector2(dot(dC_dnext_v, v[0].dpdu), dot(dC_dnext_v, v[0].dpdv))\n\t\t\t);\n\t\t\tcontinue;\n\t\t}\n\n\t\tVector wi = v[-1].p - v[0].p;\n\t\tFloat ili = wi.length();\n\n\t\tif (ili == 0)\n\t\t\treturn false;\n\n\t\tili = 1/ili; wi *= ili;\n\n\t\tif (v[0].type == EReflection || v[0].type == ERefraction) {\n\t\t\tFloat eta = v[0].eta;\n\t\t\tbool normalizeH = !(v[0].type == ERefraction && eta == 1);\n\n\t\t\t/* Compute the half vector and a few useful projections */\n\t\t\tVector H;\n\t\t\tFloat ilh;\n\t\t\tif (normalizeH) {\n\t\t\t\t/* Generally compute derivatives with respect to the normalized\n\t\t\t\t   half-vector. When given an index-matched refraction event,\n\t\t\t\t   don't perform this normalization, since the desired vertex\n\t\t\t\t   configuration is actually where H = 0. */\n\n\t\t\t\tif (dot(wi, v[0].gn) < 0)\n\t\t\t\t\teta = 1 / eta;\n\n\t\t\t\tH = wi + eta * wo;\n\t\t\t\tilh = 1 / H.length();\n\t\t\t\tH *= ilh;\n\t\t\t} else {\n\t\t\t\tH = wi + wo;\n\t\t\t\tilh = 1.0f;\n\t\t\t}\n\n\t\t\t/* Orient the half-vector so that it points in the same\n\t\t\t   hemisphere as the geometric surface normal */\n\n\t\t\tFloat dot_H_n    = dot(v[0].n, H),\n\t\t\t      dot_H_dndu = dot(v[0].dndu, H),\n\t\t\t      dot_H_dndv = dot(v[0].dndv, H),\n\t\t\t      dot_u_n    = dot(v[0].dpdu, v[0].n),\n\t\t\t      dot_v_n    = dot(v[0].dpdv, v[0].n);\n\n\t\t\t/* Local shading tangent frame */\n\t\t\tVector s = v[0].dpdu - dot_u_n * v[0].n;\n\t\t\tVector t = v[0].dpdv - dot_v_n * v[0].n;\n\n\t\t\tilo *= eta * ilh; ili *= ilh;\n\n\t\t\t/* Derivatives of C with respect to x_{i-1} */\n\t\t\tVector\n\t\t\t    dH_du = (v[-1].dpdu - wi * dot(wi, v[-1].dpdu)) * ili,\n\t\t\t    dH_dv = (v[-1].dpdv - wi * dot(wi, v[-1].dpdv)) * ili;\n\n\t\t\tif (normalizeH) {\n\t\t\t\tdH_du -= H * dot(dH_du, H);\n\t\t\t\tdH_dv -= H * dot(dH_dv, H);\n\t\t\t}\n\n\t\t\tv[0].a = Matrix2x2(\n\t\t\t    dot(dH_du, s), dot(dH_dv, s),\n\t\t\t    dot(dH_du, t), dot(dH_dv, t));\n\n\t\t\t/* Derivatives of C with respect to x_i */\n\t\t\tdH_du = -v[0].dpdu * (ili + ilo) + wi * (dot(wi, v[0].dpdu) * ili)\n\t\t\t                                 + wo * (dot(wo, v[0].dpdu) * ilo);\n\t\t\tdH_dv = -v[0].dpdv * (ili + ilo) + wi * (dot(wi, v[0].dpdv) * ili)\n\t\t\t                                 + wo * (dot(wo, v[0].dpdv) * ilo);\n\n\t\t\tif (normalizeH) {\n\t\t\t\tdH_du -= H * dot(dH_du, H);\n\t\t\t\tdH_dv -= H * dot(dH_dv, H);\n\t\t\t}\n\n\t\t\tv[0].b = Matrix2x2(\n\t\t\t    dot(dH_du, s) - dot(v[0].dpdu, v[0].dndu) * dot_H_n - dot_u_n * dot_H_dndu,\n\t\t\t    dot(dH_dv, s) - dot(v[0].dpdu, v[0].dndv) * dot_H_n - dot_u_n * dot_H_dndv,\n\t\t\t    dot(dH_du, t) - dot(v[0].dpdv, v[0].dndu) * dot_H_n - dot_v_n * dot_H_dndu,\n\t\t\t    dot(dH_dv, t) - dot(v[0].dpdv, v[0].dndv) * dot_H_n - dot_v_n * dot_H_dndv);\n\n\t\t\t/* Derivatives of C with respect to x_{i+1} */\n\t\t\tdH_du = (v[1].dpdu - wo * dot(wo, v[1].dpdu)) * ilo;\n\t\t\tdH_dv = (v[1].dpdv - wo * dot(wo, v[1].dpdv)) * ilo;\n\n\t\t\tif (normalizeH) {\n\t\t\t\tdH_du -= H * dot(dH_du, H);\n\t\t\t\tdH_dv -= H * dot(dH_dv, H);\n\t\t\t}\n\n\t\t\tv[0].c = Matrix2x2(\n\t\t\t    dot(dH_du, s), dot(dH_dv, s),\n\t\t\t    dot(dH_du, t), dot(dH_dv, t));\n\n\t\t\t/* Store the microfacet normal wrt. the local (orthonormal) shading frame */\n\t\t\ts = normalize(s);\n\t\t\tt = cross(v[0].n, s);\n\t\t\tv[0].m = Vector(dot(s, H), dot(t, H), dot(v[0].n, H));\n\t\t\tif (dot(H, v[0].gn) < 0)\n\t\t\t\tv[0].m = -v[0].m;\n\t\t} else if (v[0].type == EMedium) {\n\t\t\tVector dwi_dpred_u = (v[-1].dpdu - wi * dot(wi, v[-1].dpdu)) * ili;\n\t\t\tVector dwi_dpred_v = (v[-1].dpdv - wi * dot(wi, v[-1].dpdv)) * ili;\n\t\t\tVector dwi_dcur_u  = (-v[0].dpdu + wi * dot(wi, v[ 0].dpdu)) * ili;\n\t\t\tVector dwi_dcur_v  = (-v[0].dpdv + wi * dot(wi, v[ 0].dpdv)) * ili;\n\n\t\t\tVector t, dt_dpred_u, dt_dpred_v, dt_dcur_u, dt_dcur_v;\n\n\t\t\t/* Compute the local frame and derivatives thereof */\n\t\t\tif (std::abs(wi.x) > std::abs(wi.y)) {\n\t\t\t\tFloat tl = 1.0f / std::sqrt(wi.x * wi.x + wi.z * wi.z);\n\t\t\t\tt = Vector(wi.z * tl, 0.0f, -wi.x * tl);\n\n\t\t\t\tdt_dpred_u = Vector(dwi_dpred_u.z*tl, 0.0f, -dwi_dpred_u.x*tl);\n\t\t\t\tdt_dpred_v = Vector(dwi_dpred_v.z*tl, 0.0f, -dwi_dpred_v.x*tl);\n\t\t\t\tdt_dcur_u  = Vector(dwi_dcur_u.z*tl,  0.0f, -dwi_dcur_u.x*tl);\n\t\t\t\tdt_dcur_v  = Vector(dwi_dcur_v.z*tl,  0.0f, -dwi_dcur_v.x*tl);\n\t\t\t} else {\n\t\t\t\tFloat tl = 1.0f / std::sqrt(wi.y * wi.y + wi.z * wi.z);\n\t\t\t\tt = Vector(0.0f, wi.z * tl, -wi.y * tl);\n\n\t\t\t\tdt_dpred_u = Vector(0.0f, dwi_dpred_u.z*tl, -dwi_dpred_u.y*tl);\n\t\t\t\tdt_dpred_v = Vector(0.0f, dwi_dpred_v.z*tl, -dwi_dpred_v.y*tl);\n\t\t\t\tdt_dcur_u  = Vector(0.0f, dwi_dcur_u.z*tl,  -dwi_dcur_u.y*tl);\n\t\t\t\tdt_dcur_v  = Vector(0.0f, dwi_dcur_v.z*tl,  -dwi_dcur_v.y*tl);\n\t\t\t}\n\n\t\t\tdt_dpred_u -= t * dot(t, dt_dpred_u);\n\t\t\tdt_dpred_v -= t * dot(t, dt_dpred_v);\n\t\t\tdt_dcur_u  -= t * dot(t, dt_dcur_u);\n\t\t\tdt_dcur_v  -= t * dot(t, dt_dcur_v);\n\n\t\t\tVector s = cross(t, wi);\n\t\t\tVector ds_dpred_u = cross(dt_dpred_u, wi) + cross(t, dwi_dpred_u);\n\t\t\tVector ds_dpred_v = cross(dt_dpred_v, wi) + cross(t, dwi_dpred_v);\n\t\t\tVector ds_dcur_u  = cross(dt_dcur_u, wi)  + cross(t, dwi_dcur_u);\n\t\t\tVector ds_dcur_v  = cross(dt_dcur_v, wi)  + cross(t, dwi_dcur_v);\n\n\t\t\t/* Some tangential projections */\n\t\t\tVector2\n\t\t\t\tt_cur_dpdu (dot(v[ 0].dpdu, s), dot(v[ 0].dpdu, t)),\n\t\t\t\tt_cur_dpdv (dot(v[ 0].dpdv, s), dot(v[ 0].dpdv, t)),\n\t\t\t\tt_next_dpdu(dot(v[ 1].dpdu, s), dot(v[ 1].dpdu, t)),\n\t\t\t\tt_next_dpdv(dot(v[ 1].dpdv, s), dot(v[ 1].dpdv, t)),\n\t\t\t\tt_wo = Vector2(dot(wo, s), dot(wo, t));\n\n\t\t\tv[0].a = Matrix2x2(\n\t\t\t\tVector2(dot(ds_dpred_u, wo), dot(dt_dpred_u, wo)),\n\t\t\t\tVector2(dot(ds_dpred_v, wo), dot(dt_dpred_v, wo))\n\t\t\t);\n\n\t\t\tv[0].b = Matrix2x2(\n\t\t\t\t(t_wo * dot(wo, v[0].dpdu) - t_cur_dpdu) * ilo +\n\t\t\t\tVector2(dot(ds_dcur_u, wo), dot(dt_dcur_u, wo)),\n\t\t\t\t(t_wo * dot(wo, v[0].dpdv) - t_cur_dpdv) * ilo +\n\t\t\t\tVector2(dot(ds_dcur_v, wo), dot(dt_dcur_v, wo)));\n\n\t\t\tv[0].c = Matrix2x2(\n\t\t\t\t(t_next_dpdu - t_wo * dot(wo, v[1].dpdu)) * ilo,\n\t\t\t\t(t_next_dpdv - t_wo * dot(wo, v[1].dpdv)) * ilo);\n\n\t\t\tv[0].m = Vector(dot(s, wo), dot(t, wo), dot(wi, wo));\n\t\t} else {\n\t\t\tLog(EError, \"Unknown vertex type!\");\n\t\t}\n\t}\n\n\t/* Find the tangent space with respect to translation of the last\n\t   vertex. For this, we must solve a tridiagonal system. The following is\n\t   simplified version of the block tridiagonal LU factorization algorithm\n\t   for this specific problem */\n\tMatrix2x2 Li;\n\tif (!m_vertices[0].b.invert(Li))\n\t\treturn false;\n\n\tfor (int i=0; i < n - 1; ++i) {\n\t\tm_vertices[i].u = Li * m_vertices[i].c;\n\t\tMatrix2x2 temp = m_vertices[i+1].b - m_vertices[i+1].a * m_vertices[i].u;\n\t\tif (!temp.invert(Li))\n\t\t\treturn false;\n\t}\n\n\tm_vertices[n-1].Tp = -Li * m_vertices[n-1].c;\n\n\tfor (int i=n-2; i>=0; --i)\n\t\tm_vertices[i].Tp = -m_vertices[i].u * m_vertices[i+1].Tp;\n\treturn true;\n}\n\nbool SpecularManifold::project(const Vector &d) {\n\tconst SimpleVertex &last = m_vertices[m_vertices.size()-1];\n\tFloat du = dot(d, last.dpdu), dv = dot(d, last.dpdv);\n\n\tRay ray(Point(0.0f), Vector(1.0f), 0); // make gcc happy\n\tIntersection its;\n\n\tm_proposal.clear();\n\tfor (size_t i=0; i<m_vertices.size(); ++i) {\n\t\tm_proposal.push_back(m_vertices[i]);\n\t\tSimpleVertex &vertex = m_proposal[i];\n\n\t\tif (i == 0) {\n\t\t\tPoint p0 = m_vertices[0].p + m_vertices[0].map(du, dv);\n\t\t\tPoint p1 = m_vertices[1].p + m_vertices[1].map(du, dv);\n\n\t\t\tray = Ray(p0, normalize(p1 - p0), m_time);\n\t\t\tvertex.p = ray.o;\n\t\t\tcontinue;\n\t\t} else if (vertex.type == EMovable) {\n\t\t\tFloat dp = dot(ray.d, vertex.n);\n\t\t\tif (std::abs(dp) < Epsilon)\n\t\t\t\treturn false;\n\n\t\t\tFloat t = dot(vertex.p - ray.o, vertex.n) / dp;\n\t\t\tvertex.p = ray(t);\n\t\t\tbreak;\n\t\t} else if (vertex.type == EReflection) {\n\t\t\tif (!m_scene->rayIntersect(ray, its))\n\t\t\t\treturn false;\n\n\t\t\tVector n = its.shFrame.n,\n\t\t\t\t   s = its.dpdu, t;\n\t\t\ts = normalize(s - n * dot(n, s));\n\t\t\tt = cross(n, s);\n\n\t\t\tVector m = s * vertex.m[0] + t * vertex.m[1] + n * vertex.m[2];\n\n\t\t\tray.setOrigin(its.p);\n\t\t\tray.setDirection(reflect(-ray.d, m));\n\t\t} else if (vertex.type == ERefraction) {\n\t\t\tif (!m_scene->rayIntersect(ray, its))\n\t\t\t\treturn false;\n\n\t\t\tVector n = its.shFrame.n,\n\t\t\t\t   s = its.dpdu, t;\n\t\t\ts = normalize(s - n * dot(n, s));\n\t\t\tt = cross(n, s);\n\n\t\t\tVector m = s * vertex.m[0] + t * vertex.m[1] + n * vertex.m[2];\n\t\t\tVector refracted = refract(-ray.d, m, its.shape->getBSDF()->getEta());\n\n\t\t\tif (refracted.isZero())\n\t\t\t\treturn false;\n\n\t\t\tray.setOrigin(its.p);\n\t\t\tray.setDirection(refracted);\n\t\t} else if (vertex.type == EMedium) {\n\t\t\tFloat length = (m_vertices[i].p - m_vertices[i-1].p).length(),\n\t\t\t\t  invLength = 1.0f / length;\n\n\t\t\t/* Check for occlusion */\n\t\t\tif (m_scene->rayIntersect(Ray(ray, Epsilon, length)))\n\t\t\t\treturn false;\n\n\t\t\tvertex.p = ray(length);\n\t\t\tvertex.n = Vector(0.0f);\n\n\t\t\tVector wi = -ray.d, s, t;\n\t\t\tcoordinateSystem(wi, s, t);\n\n\t\t \tvertex.dpdu = s;\n\t\t\tvertex.dpdv = t;\n\t\t \tvertex.dndu = s * invLength;\n\t\t\tvertex.dndv = t * invLength;\n\n\t\t\tray.setOrigin(vertex.p);\n\t\t\tray.setDirection(s * vertex.m[0] + t * vertex.m[1] + wi * vertex.m[2]);\n\t\t} else {\n\t\t\tLog(EError, \"Unsupported vertex type!\");\n\t\t}\n\n\t\tif (vertex.type != EMedium) {\n\t\t\tif (vertex.object != its.shape->getBSDF())\n\t\t\t\treturn false;\n\n\t\t\tvertex.p = its.p;\n\t\t\tvertex.n = its.shFrame.n;\n\t\t\tvertex.gn = its.geoFrame.n;\n\t\t\tvertex.dpdu = its.dpdu;\n\t\t\tvertex.dpdv = its.dpdv;\n\n\t\t\tconst Shape *shape = its.instance != NULL ? its.instance : its.shape;\n\t\t\tshape->getNormalDerivative(its,\n\t\t\t\tvertex.dndu, vertex.dndv);\n\n\t\t\t/* Turn into an orthonormal parameterization at 'p' */\n\t\t\tFloat invLen = 1 / vertex.dpdu.length();\n\t\t\tvertex.dpdu *= invLen; vertex.dndu *= invLen;\n\t\t\tFloat dp = dot(vertex.dpdu, vertex.dpdv);\n\t\t\tVector dpdv = vertex.dpdv - dp * vertex.dpdu;\n\t\t\tVector dndv = vertex.dndv - dp * vertex.dndu;\n\t\t\tinvLen = 1 / dpdv.length();\n\t\t\tvertex.dpdv = dpdv * invLen;\n\t\t\tvertex.dndv = dndv * invLen;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool SpecularManifold::move(const Point &target, const Normal &n) {\n\tSimpleVertex &last = m_vertices[m_vertices.size()-1];\n\n\t#if MTS_MANIFOLD_DEBUG == 1\n\t\tcout << \"moveTo(\" << last.p.toString() << \" => \" << target.toString() << \", n=\" << n.toString() << \")\" << endl;\n\t#endif\n\n\tif (m_vertices.size() == 2 && m_vertices[0].type == EPinnedPosition) {\n\t\t/* Nothing to do */\n\t\treturn true;\n\t}\n\n\tbool medium = false;\n\tfor (size_t i=0; i<m_vertices.size(); ++i) {\n\t\tif (m_vertices[i].type == EMedium)\n\t\t\tmedium = true;\n\t}\n\n\tif (medium)\n\t\tstatsMediumSuccess.incrementBase();\n\n\tstatsAvgManifoldSize.incrementBase();\n\tstatsAvgManifoldSize += m_vertices.size();\n\tstatsMaxManifold.recordMaximum(m_vertices.size());\n\n\tstatsSuccessfulWalks.incrementBase();\n\n\tFloat invScale = 1.0f / std::max(std::max(std::abs(target.x),\n\t\t\tstd::abs(target.y)), std::abs(target.z));\n\tFloat stepSize = 1;\n\n\tBDAssert(last.type == EMovable);\n\tcoordinateSystem(n, last.dpdu, last.dpdv);\n\tlast.n = n;\n\n\tm_proposal.reserve(m_vertices.size());\n\tm_iterations = 0;\n\tstatsAvgIterations.incrementBase();\n\twhile (m_iterations < m_maxIterations) {\n\t\tVector rel = target - m_vertices[m_vertices.size()-1].p;\n\t\tFloat dist = rel.length(), newDist;\n\t\tif (dist * invScale < MTS_MANIFOLD_EPSILON) {\n\t\t\t/* Check for an annoying corner-case where the last\n\t\t\t   two vertices converge to the same point (this can\n\t\t\t   happen e.g. on rough planar reflectors) */\n\t\t\tdist = (m_vertices[m_vertices.size()-1].p\n\t\t\t      - m_vertices[m_vertices.size()-2].p).length();\n\t\t\tif (dist * invScale < Epsilon) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t/* The manifold walk converged. */\n\t\t\t++statsSuccessfulWalks;\n\t\t\tstatsAvgIterationsSuccess.incrementBase();\n\t\t\tstatsAvgIterationsSuccess += m_iterations;\n\t\t\tif (medium)\n\t\t\t\t++statsMediumSuccess;\n\t\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\t\tcout << \"move(): converged after \" << m_iterations << \" iterations\" << endl;\n\t\t\t\tcout << \"Final configuration:\" << toString() << endl;\n\t\t\t#endif\n\t\t\treturn true;\n\t\t}\n\t\tm_iterations++;\n\t\t++statsAvgIterations;\n\n\t\t/* Compute the tangent vectors for the current path */\n\t\tstatsNonManifold.incrementBase();\n\t\tif (!computeTangents()) {\n\t\t\t++statsNonManifold;\n\t\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\t\tcout << \"move(): unable to compute tangents!\" << endl;\n\t\t\t#endif\n\t\t\treturn false;\n\t\t}\n\n\t\t/* Take a step using the computed tangents and project\n\t\t   back on the manifold */\n\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\tconst SimpleVertex &last = m_vertices[m_vertices.size()-1];\n\t\t\tFloat du = dot(rel, last.dpdu), dv = dot(rel, last.dpdv);\n\t\t\tcout << \"project(du=\" << du << \", dv=\" << dv << \", stepSize=\" << stepSize << \")\" << endl;\n\t\t#endif\n\n\t\tif (!project(rel * stepSize)) {\n\t\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\t\tcout << \"project failed!\" << endl;\n\t\t\t#endif\n\t\t\t++statsStepFailed;\n\t\t\tgoto failure;\n\t\t}\n\n\t\t/* Reject if the step increased the distance */\n\t\tnewDist = (target - m_proposal[m_proposal.size()-1].p).length();\n\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\tcout << \"Distance: \" << dist << \" -> \" << newDist << endl;\n\t\t#endif\n\t\tif (newDist > dist) {\n\t\t\t++statsStepTooFar;\n\t\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\t\tcout << \"-> Rejecting!\" << endl;\n\t\t\t#endif\n\t\t\tgoto failure;\n\t\t}\n\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\tcout << \"-> Accepting!\" << endl;\n\t\t#endif\n\t\t++statsStepSuccess;\n\n\t\tm_proposal.swap(m_vertices);\n\n\t\t/* Increase the step size */\n\t\tstepSize = std::min((Float) 1.0f, stepSize * 2.0f);\n\t\tcontinue;\n\tfailure:\n\t\t/* Reduce the step size */\n\t\tstepSize /= 2.0f;\n\t}\n\t#if MTS_MANIFOLD_DEBUG == 1\n\t\tcout << \"Exceeded the max. iteration count!\" << endl;\n\t#endif\n\n\treturn false;\n}\n\nbool SpecularManifold::update(Path &path, int start, int end) {\n\tint step;\n\tETransportMode mode;\n\n\tif (start < end) {\n\t\tstep = 1; mode = EImportance;\n\t} else {\n\t\tstep = -1; mode = ERadiance;\n\t}\n\n\tint last = (int) m_vertices.size() - 2;\n\tif (m_vertices[0].type == EPinnedDirection)\n\t\tlast = std::max(last, 1);\n\n\tfor (int j=0, i=start; j < last; ++j, i += step) {\n\t\tconst SimpleVertex\n\t\t\t&v = m_vertices[j],\n\t\t\t&vn = m_vertices[j+1];\n\n\t\tPathVertex\n\t\t\t*pred   = path.vertexOrNull(i-step),\n\t\t\t*vertex = path.vertex(i),\n\t\t\t*succ   = path.vertex(i+step);\n\n\t\tint predEdgeIdx = (mode == EImportance) ? i-step : i-step-1;\n\t\tPathEdge *predEdge = path.edgeOrNull(predEdgeIdx),\n\t\t         *succEdge = path.edge(predEdgeIdx + step);\n\n\t\tVector d = vn.p - v.p;\n\t\tFloat length = d.length();\n\t\td /= length;\n\t\tPathVertex::EVertexType desiredType = vn.type == EMedium ?\n\t\t\tPathVertex::EMediumInteraction : PathVertex::ESurfaceInteraction;\n\n\t\tif (v.type == EPinnedDirection) {\n\t\t\t/* Create a fake vertex and use it to call sampleDirect(). This is\n\t\t\t   kind of terrible -- a nicer API is needed to cleanly support this */\n\t\t\tPathVertex temp;\n\t\t\ttemp.type = PathVertex::EMediumInteraction;\n\t\t\ttemp.degenerate = false;\n\t\t\ttemp.measure = EArea;\n\t\t\tMediumSamplingRecord &mRec = temp.getMediumSamplingRecord();\n\t\t\tmRec.time = m_time;\n\t\t\tmRec.p = vn.p;\n\n\t\t\tif (temp.sampleDirect(m_scene, NULL, vertex, succEdge, succ, mode).isZero()) {\n\t\t\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\t\t\tcout << \"update(): failed in sampleDirect()!\" << endl;\n\t\t\t\t#endif\n\t\t\t\t++statsUpdateFailed;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (m_vertices.size() >= 3) {\n\t\t\t\tPathVertex *succ2 = path.vertex(i+2*step);\n\t\t\t\tPathEdge *succ2Edge = path.edge(predEdgeIdx + 2*step);\n\t\t\t\tif (!succ->sampleNext(m_scene, NULL, vertex, succEdge, succ2Edge, succ2, mode)) {\n\t\t\t\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\t\t\t\tcout << \"update(): failed in sampleNext() / pinned direction!\" << endl;\n\t\t\t\t\t#endif\n\t\t\t\t\t++statsUpdateFailed;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\ti += step;\n\t\t} else if (!v.degenerate) {\n\t\t\tif (!vertex->perturbDirection(m_scene,\n\t\t\t\t\tpred, predEdge, succEdge, succ, d,\n\t\t\t\t\tlength, desiredType, mode)) {\n\t\t\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\t\t\tcout << \"update(): failed in perturbDirection()\" << endl;\n\t\t\t\t#endif\n\t\t\t\t++statsUpdateFailed;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tFloat relerr = (vn.p - succ->getPosition()).length() /\n\t\t\t\tstd::max(std::max(std::abs(vn.p.x),\n\t\t\t\t\tstd::abs(vn.p.y)), std::abs(vn.p.z));\n\n\t\t\tif (relerr > 1e-3f) {\n\t\t\t\t// be extra-cautious\n\t\t\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\t\t\tcout << \"update(): failed, relative error of perturbDirection() too high:\" << relerr << endl;\n\t\t\t\t#endif\n\t\t\t\t++statsUpdateFailed;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\tunsigned int compType;\n\t\t\tif (v.type == ERefraction)\n\t\t\t\tcompType = v.eta != 1 ? BSDF::EDeltaTransmission : (BSDF::ENull | BSDF::EDeltaTransmission);\n\t\t\telse\n\t\t\t\tcompType = BSDF::EDeltaReflection;\n\n\t\t\tif (!vertex->propagatePerturbation(m_scene,\n\t\t\t\t\tpred, predEdge, succEdge, succ, compType,\n\t\t\t\t\tlength, desiredType, mode)) {\n\t\t\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\t\t\tcout << \"update(): failed in propagatePerturbation()\" << endl;\n\t\t\t\t#endif\n\t\t\t\t++statsUpdateFailed;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tFloat relerr = (vn.p - succ->getPosition()).length() /\n\t\t\t\tstd::max(std::max(std::abs(vn.p.x),\n\t\t\t\t\tstd::abs(vn.p.y)), std::abs(vn.p.z));\n\t\t\tif (relerr > 1e-3f) {\n\t\t\t\t// be extra-cautious\n\t\t\t\t#if MTS_MANIFOLD_DEBUG == 1\n\t\t\t\t\tcout << \"update(): failed, relative error of propagatePerturbation() too high:\" << relerr << endl;\n\t\t\t\t#endif\n\t\t\t\t++statsUpdateFailed;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\nFloat SpecularManifold::det(const Path &path, int a, int b, int c) {\n\tint k = path.length();\n\n\tif (a == 0 || a == k)\n\t\tstd::swap(a, c);\n\n\tint step = b > a ? 1 : -1, nGlossy = 0, nSpecular = 0;\n\n\tfor (int i=a + step; i != c; i += step) {\n\t\tif (path.vertex(i)->isConnectable())\n\t\t\t++nGlossy;\n\t\telse\n\t\t\t++nSpecular;\n\t}\n\n\tif (nGlossy <= 1) /* No glossy materials -- we don't need this derivative */\n\t\treturn 1.0f;\n\n\tbool success = init(path, a, c);\n\tBDAssert(success);\n\n\tint b_idx = std::abs(b-a);\n\tSimpleVertex &vb = m_vertices[b_idx];\n\tconst PathVertex *pb = path.vertex(b);\n\n\tif (pb->isMediumInteraction()) {\n\t\tvb.n = Vector(path.edge(a < b ? (b-1) : b)->d);\n\t} else {\n\t\tvb.n = pb->getShadingNormal();\n\t}\n\tcoordinateSystem(vb.n, vb.dpdu, vb.dpdv);\n\n\tif (!computeTangents()) {\n\t\tLog(EWarn, \"Could not compute tangents!\");\n\t\treturn 0.0f;\n\t}\n\n\tm_vertices[b_idx].a.setZero();\n\tm_vertices[b_idx].b.setIdentity();\n\tm_vertices[b_idx].c.setZero();\n\n\tif (nSpecular == 0) {\n\t\t/* The chain only consists of glossy vertices -- simply compute the\n\t\t   determinant of the block tridiagonal matrix A.\n\n\t\t   See D.K. Salkuyeh, Comments on \"A note on a three-term recurrence for a\n\t\t   tridiagonal matrix\", Appl. Math. Comput. 176 (2006) 442-444. */\n\n\t\tMatrix2x2 Di(0.0f), D = m_vertices[1].b;\n\n\t\tFloat det = D.det();\n\t\tfor (size_t i=2; i<m_vertices.size()-1; ++i) {\n\t\t\tif (!D.invert(Di)) {\n\t\t\t\tLog(EWarn, \"Could not invert matrix!\");\n\t\t\t\treturn 0.0f;\n\t\t\t}\n\n\t\t\tD = m_vertices[i].b - m_vertices[i].a * Di * m_vertices[i-1].c;\n\t\t\tdet *= D.det();\n\t\t}\n\n\t\treturn std::abs(1 / det);\n\t} else {\n\t\t/* The chain contains both glossy and specular materials. Compute the\n\t\t   determinant of A^-1, where rows corresponding to specular vertices\n\t\t   have been crossed out. The performance of the following is probably\n\t\t   terrible (lots of dynamic memory allocation), but it works and\n\t\t   this case happens rarely enough .. */\n\n\t\tEigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic> A(2*(nGlossy + nSpecular), 2*(nGlossy + nSpecular));\n\t\tA.setZero();\n\n\t\tfor (int j=0, i=0; j<nGlossy+nSpecular; ++j) {\n\t\t\tif (j-1 >= 0) {\n\t\t\t\tA(2*i,   2*(j-1))   = m_vertices[j+1].a(0,0);\n\t\t\t\tA(2*i,   2*(j-1)+1) = m_vertices[j+1].a(0,1);\n\t\t\t\tA(2*i+1, 2*(j-1))   = m_vertices[j+1].a(1,0);\n\t\t\t\tA(2*i+1, 2*(j-1)+1) = m_vertices[j+1].a(1,1);\n\t\t\t}\n\t\t\tA(2*i,   2*j)   = m_vertices[j+1].b(0,0);\n\t\t\tA(2*i,   2*j+1) = m_vertices[j+1].b(0,1);\n\t\t\tA(2*i+1, 2*j)   = m_vertices[j+1].b(1,0);\n\t\t\tA(2*i+1, 2*j+1) = m_vertices[j+1].b(1,1);\n\n\t\t\tif (j+1 < nGlossy + nSpecular) {\n\t\t\t\tA(2*i,   2*(j+1))   = m_vertices[j+1].c(0,0);\n\t\t\t\tA(2*i,   2*(j+1)+1) = m_vertices[j+1].c(0,1);\n\t\t\t\tA(2*i+1, 2*(j+1))   = m_vertices[j+1].c(1,0);\n\t\t\t\tA(2*i+1, 2*(j+1)+1) = m_vertices[j+1].c(1,1);\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\n\t\t/* Compute the inverse and \"cross out\" irrelevant columns and rows */\n\t\tEigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic> Ai = A.inverse();\n\n\t\tfor (int i=0; i<nGlossy+nSpecular; ++i) {\n\t\t\tif (!m_vertices[i+1].degenerate)\n\t\t\t\tcontinue;\n\n\t\t\tAi.row(2*i).setZero();\n\t\t\tAi.col(2*i).setZero();\n\t\t\tAi.row(2*i+1).setZero();\n\t\t\tAi.col(2*i+1).setZero();\n\n\t\t\tAi.block<2,2>(2*i, 2*i).setIdentity();\n\t\t}\n\n\t\treturn std::abs(Ai.determinant());\n\t}\n}\n\nFloat SpecularManifold::multiG(const Path &path, int a, int b) {\n\tif (a == 0)\n\t\t++a;\n\telse if (a == path.length())\n\t\t--a;\n\tif (b == 0)\n\t\t++b;\n\telse if (b == path.length())\n\t\t--b;\n\n\tint step = b > a ? 1 : -1;\n\twhile (!path.vertex(b)->isConnectable())\n\t\tb -= step;\n\twhile (!path.vertex(a)->isConnectable())\n\t\ta += step;\n\n\tFloat result = 1;\n\n\tBDAssert(path.vertex(a)->isConnectable() && path.vertex(b)->isConnectable());\n\tfor (int i = a + step, start = a; i != b + step; i += step) {\n\t\tif (path.vertex(i)->isConnectable()) {\n\t\t\tresult *= G(path, start, i);\n\t\t\tstart = i;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nFloat SpecularManifold::G(const Path &path, int a, int b) {\n\tif (std::abs(a-b) == 1) {\n\t\tif (a > b)\n\t\t\tstd::swap(a, b);\n\t\treturn path.edge(a)->evalCached(path.vertex(a),\n\t\t\tpath.vertex(b), PathEdge::EGeometricTerm)[0];\n\t}\n\n\tAssert(path.vertex(a)->isConnectable());\n\tAssert(path.vertex(b)->isConnectable());\n\tint step = b > a ? 1 : -1;\n\n\tbool success = init(path, a, b);\n\tBDAssert(success);\n\n\tSimpleVertex &last = m_vertices[m_vertices.size()-1];\n\tconst PathVertex *vb = path.vertex(b);\n\tif (!vb->isOnSurface()) {\n\t\tlast.n = Vector(path.edge(a < b ? (b-1) : b)->d);\n\t} else {\n\t\tlast.n = vb->getShadingNormal();\n\t}\n\tcoordinateSystem(last.n, last.dpdu, last.dpdv);\n\n\tstatsNonManifold.incrementBase();\n\tif (!computeTangents()) {\n\t\t++statsNonManifold;\n\t\tLog(EWarn, \"SpecularManifold::evalG(): non-manifold configuration!\");\n\t\treturn 0;\n\t}\n\n\tFloat result;\n\tif (m_vertices[0].type == EPinnedDirection) {\n\t\tresult = cross(m_vertices[0].map(1, 0), m_vertices[0].map(0, 1)).length();\n\t} else if (m_vertices[0].type == EPinnedPosition) {\n\t\tVector d = m_vertices[1].p - m_vertices[0].p;\n\t\tFloat lengthSqr = d.lengthSquared(), invLength = 1/std::sqrt(lengthSqr);\n\n\t\tresult = cross(m_vertices[1].map(1, 0), m_vertices[1].map(0, 1)).length() / lengthSqr;\n\n\t\tif (path.vertex(a)->isOnSurface())\n\t\t\tresult *= absDot(d, path.vertex(a)->getShadingNormal()) * invLength;\n\n\t\tif (path.vertex(a+step)->isOnSurface())\n\t\t\tresult *= absDot(d, path.vertex(a+step)->getShadingNormal()) * invLength;\n\t} else {\n\t\tLog(EError, \"Invalid vertex type!\");\n\t\treturn 0;\n\t}\n\n\treturn result;\n}\n\nstd::string SpecularManifold::SimpleVertex::toString() const {\n\tstd::ostringstream oss;\n\n\toss << \"SimpleVertex[\" << endl\n\t\t<< \"  type = \";\n\n\tswitch (type) {\n\t\tcase EPinnedPosition: oss << \"pinnedPosition\"; break;\n\t\tcase EPinnedDirection: oss << \"pinnedDirection\"; break;\n\t\tcase EReflection: oss << \"reflection\"; break;\n\t\tcase ERefraction: oss << \"refraction\"; break;\n\t\tcase EMedium: oss << \"medium\"; break;\n\t\tcase EMovable: oss << \"movable\"; break;\n\t\tdefault: SLog(EError, \"Unknown vertex type!\");\n\t}\n\n\toss << \",\" << endl\n\t\t<< \"  p = \" << p.toString() << \",\" << endl\n\t\t<< \"  n = \" << n.toString() << \",\" << endl\n\t\t<< \"  m = \" << m.toString() << \",\" << endl\n\t\t<< \"  dpdu = \" << dpdu.toString() << \",\" << endl\n\t\t<< \"  dpdv = \" << dpdv.toString() << \",\" << endl\n\t\t<< \"  dndu = \" << dndu.toString() << \",\" << endl\n\t\t<< \"  dndv = \" << dndv.toString() << \",\" << endl\n\t\t<< \"  eta = \" << eta << \",\" << endl\n\t\t<< \"  object = \" << (object ? indent(object->toString()).c_str() : \"null\") << endl\n\t\t<< \"]\";\n\n\treturn oss.str();\n}\n\nstd::string SpecularManifold::toString() const {\n\tstd::ostringstream oss;\n\n\toss << \"SpecularManifold[\" << endl;\n\tfor (size_t i=0; i<m_vertices.size(); ++i) {\n\t\toss << \"  \" << i << \" => \" << indent(m_vertices[i].toString());\n\t\tif (i+1 < m_vertices.size())\n\t\t\toss << \",\";\n\t\toss << endl;\n\t}\n\toss << \"]\";\n\n\treturn oss.str();\n}\n\nMTS_IMPLEMENT_CLASS(SpecularManifold, false, Object)\nMTS_NAMESPACE_END\n", "meta": {"hexsha": "17b9384b7659758ca9dd4ce5f0c76c574c086944", "size": 29883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "mitsuba-af602c6fd98a/src/libbidir/manifold.cpp", "max_stars_repo_name": "NTForked-ML/pbrs", "max_stars_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 139.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T00:22:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T20:33:10.000Z", "max_issues_repo_path": "mitsuba-af602c6fd98a/src/libbidir/manifold.cpp", "max_issues_repo_name": "NTForked-ML/pbrs", "max_issues_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2017-08-15T18:22:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-01T05:44:41.000Z", "max_forks_repo_path": "mitsuba-af602c6fd98a/src/libbidir/manifold.cpp", "max_forks_repo_name": "NTForked-ML/pbrs", "max_forks_repo_head_hexsha": "0b405d92c12d257e2581366542762c9f0c3facce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2017-07-21T03:56:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T06:55:34.000Z", "avg_line_length": 29.8531468531, "max_line_length": 113, "alphanum_fraction": 0.6151992772, "num_tokens": 10085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.21723897503227957}}
{"text": "#include <cstdlib>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n#include <vector>\n\n#include <boost/program_options.hpp>\n#include <boost/program_options/variables_map.hpp>\n\n#include \"filelib.h\"\n#include \"weights.h\"\n#include \"sparse_vector.h\"\n#include \"optimize.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\n// since this is a ranking model, there should be equal numbers of\n// positive and negative examples, so the bias should be 0\nstatic const double MAX_BIAS = 1e-10;\n\nvoid InitCommandLine(int argc, char** argv, po::variables_map* conf) {\n  po::options_description opts(\"Configuration options\");\n  opts.add_options()\n        (\"weights,w\", po::value<string>(), \"Weights from previous iteration (used as initialization and interpolation\")\n        (\"interpolation,p\",po::value<double>()->default_value(0.9), \"Output weights are p*w + (1-p)*w_prev\")\n        (\"memory_buffers,m\",po::value<unsigned>()->default_value(200), \"Number of memory buffers (LBFGS)\")\n        (\"sigma_squared,s\",po::value<double>()->default_value(0.1), \"Sigma squared for Gaussian prior\")\n        (\"min_reg,r\",po::value<double>()->default_value(1e-8), \"When tuning (-T) regularization strength, minimum regularization strenght\")\n        (\"max_reg,R\",po::value<double>()->default_value(10.0), \"When tuning (-T) regularization strength, maximum regularization strenght\")\n        (\"testset,t\",po::value<string>(), \"Optional held-out test set\")\n        (\"tune_regularizer,T\", \"Use the held out test set (-t) to tune the regularization strength\")\n        (\"help,h\", \"Help\");\n  po::options_description dcmdline_options;\n  dcmdline_options.add(opts);\n  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);\n  if (conf->count(\"help\")) {\n    cerr << dcmdline_options << endl;\n    exit(1);\n  }\n}\n\nvoid ParseSparseVector(string& line, size_t cur, SparseVector<double>* out) {\n  SparseVector<double>& x = *out;\n  size_t last_start = cur;\n  size_t last_comma = string::npos;\n  while(cur <= line.size()) {\n    if (line[cur] == ' ' || cur == line.size()) {\n      if (!(cur > last_start && last_comma != string::npos && cur > last_comma)) {\n        cerr << \"[ERROR] \" << line << endl << \"  position = \" << cur << endl;\n        exit(1);\n      }\n      const int fid = FD::Convert(line.substr(last_start, last_comma - last_start));\n      if (cur < line.size()) line[cur] = 0;\n      const double val = strtod(&line[last_comma + 1], NULL);\n      x.set_value(fid, val);\n\n      last_comma = string::npos;\n      last_start = cur+1;\n    } else {\n      if (line[cur] == '=')\n        last_comma = cur;\n    }\n    ++cur;\n  }\n}\n\nvoid ReadCorpus(istream* pin, vector<pair<bool, SparseVector<double> > >* corpus) {\n  istream& in = *pin;\n  corpus->clear();\n  bool flag = false;\n  int lc = 0;\n  string line;\n  SparseVector<double> x;\n  while(getline(in, line)) {\n    ++lc;\n    if (lc % 1000 == 0) { cerr << '.'; flag = true; }\n    if (lc % 40000 == 0) { cerr << \" [\" << lc << \"]\\n\"; flag = false; }\n    if (line.empty()) continue;\n    const size_t ks = line.find(\"\\t\");\n    assert(string::npos != ks);\n    assert(ks == 1);\n    const bool y = line[0] == '1';\n    x.clear();\n    ParseSparseVector(line, ks + 1, &x);\n    corpus->push_back(make_pair(y, x));\n  }\n  if (flag) cerr << endl;\n}\n\nvoid GradAdd(const SparseVector<double>& v, const double scale, vector<double>* acc) {\n  for (SparseVector<double>::const_iterator it = v.begin();\n       it != v.end(); ++it) {\n    (*acc)[it->first] += it->second * scale;\n  }\n}\n\ndouble TrainingInference(const vector<double>& x,\n                         const vector<pair<bool, SparseVector<double> > >& corpus,\n                         vector<double>* g = NULL) {\n  double cll = 0;\n  for (int i = 0; i < corpus.size(); ++i) {\n    const double dotprod = corpus[i].second.dot(x) + x[0]; // x[0] is bias\n    double lp_false = dotprod;\n    double lp_true = -dotprod;\n    if (0 < lp_true) {\n      lp_true += log1p(exp(-lp_true));\n      lp_false = log1p(exp(lp_false));\n    } else {\n      lp_true = log1p(exp(lp_true));\n      lp_false += log1p(exp(-lp_false));\n    }\n    lp_true*=-1;\n    lp_false*=-1;\n    if (corpus[i].first) {  // true label\n      cll -= lp_true;\n      if (g) {\n        // g -= corpus[i].second * exp(lp_false);\n        GradAdd(corpus[i].second, -exp(lp_false), g);\n        (*g)[0] -= exp(lp_false); // bias\n      }\n    } else {                  // false label\n      cll -= lp_false;\n      if (g) {\n        // g += corpus[i].second * exp(lp_true);\n        GradAdd(corpus[i].second, exp(lp_true), g);\n        (*g)[0] += exp(lp_true); // bias\n      }\n    }\n  }\n  return cll;\n}\n\n// return held-out log likelihood\ndouble LearnParameters(const vector<pair<bool, SparseVector<double> > >& training,\n                       const vector<pair<bool, SparseVector<double> > >& testing,\n                       const double sigsq,\n                       const unsigned memory_buffers,\n                       vector<double>* px) {\n  vector<double>& x = *px;\n  vector<double> vg(FD::NumFeats(), 0.0);\n  bool converged = false;\n  LBFGSOptimizer opt(FD::NumFeats(), memory_buffers);\n  double tppl = 0.0;\n  while(!converged) {\n    fill(vg.begin(), vg.end(), 0.0);\n    double cll = TrainingInference(x, training, &vg);\n    double ppl = cll / log(2);\n    ppl /= training.size();\n    ppl = pow(2.0, ppl);\n\n    // evaluate optional held-out test set\n    if (testing.size()) {\n      tppl = TrainingInference(x, testing) / log(2);\n      tppl /= testing.size();\n      tppl = pow(2.0, tppl);\n    }\n\n    // handle regularizer\n#if 1\n    double norm = 0;\n    for (int i = 1; i < x.size(); ++i) {\n      const double mean_i = 0.0;\n      const double param = (x[i] - mean_i);\n      norm += param * param;\n      vg[i] += param / sigsq;\n    } \n    const double reg = norm / (2.0 * sigsq);\n#else\n    double reg = 0;\n#endif\n    cll += reg;\n    cerr << cll << \" (REG=\" << reg << \")\\tPPL=\" << ppl << \"\\t TEST_PPL=\" << tppl << \"\\t\";\n    try {\n      vector<double> old_x = x;\n      do {\n        opt.Optimize(cll, vg, &x);\n        converged = opt.HasConverged();\n      } while (!converged && x == old_x);\n    } catch (...) {\n      cerr << \"Exception caught, assuming convergence is close enough...\\n\";\n      converged = true;\n    }\n    if (fabs(x[0]) > MAX_BIAS) {\n      cerr << \"Biased model learned. Are your training instances wrong?\\n\";\n      cerr << \"  BIAS: \" << x[0] << endl;\n    }\n  }\n  return tppl;\n}\n\nint main(int argc, char** argv) {\n  po::variables_map conf;\n  InitCommandLine(argc, argv, &conf);\n  string line;\n  vector<pair<bool, SparseVector<double> > > training, testing;\n  SparseVector<double> old_weights;\n  const bool tune_regularizer = conf.count(\"tune_regularizer\");\n  if (tune_regularizer && !conf.count(\"testset\")) {\n    cerr << \"--tune_regularizer requires --testset to be set\\n\";\n    return 1;\n  }\n  const double min_reg = conf[\"min_reg\"].as<double>();\n  const double max_reg = conf[\"max_reg\"].as<double>();\n  double sigsq = conf[\"sigma_squared\"].as<double>();\n  assert(sigsq > 0.0);\n  assert(min_reg > 0.0);\n  assert(max_reg > 0.0);\n  assert(max_reg > min_reg);\n  const double psi = conf[\"interpolation\"].as<double>();\n  if (psi < 0.0 || psi > 1.0) { cerr << \"Invalid interpolation weight: \" << psi << endl; }\n  if (conf.count(\"weights\")) {\n    Weights w;\n    w.InitFromFile(conf[\"weights\"].as<string>());\n    w.InitSparseVector(&old_weights);\n  }\n  ReadCorpus(&cin, &training);\n  if (conf.count(\"testset\")) {\n    ReadFile rf(conf[\"testset\"].as<string>());\n    ReadCorpus(rf.stream(), &testing);\n  }\n  cerr << \"Number of features: \" << FD::NumFeats() << endl;\n  vector<double> x(FD::NumFeats(), 0.0);  // x[0] is bias\n  for (SparseVector<double>::const_iterator it = old_weights.begin();\n       it != old_weights.end(); ++it)\n    x[it->first] = it->second;\n  double tppl = 0.0;\n  vector<pair<double,double> > sp;\n  vector<double> smoothed;\n  if (tune_regularizer) {\n    cerr << \"Tuning regularizer...\" << endl;\n\n    sigsq = min_reg;\n    const double steps = 18;\n    double sweep_factor = exp((log(max_reg) - log(min_reg)) / steps);\n    cerr << \"SWEEP FACTOR: \" << sweep_factor << endl;\n    while(sigsq < max_reg) {\n      tppl = LearnParameters(training, testing, sigsq, conf[\"memory_buffers\"].as<unsigned>(), &x);\n      sp.push_back(make_pair(sigsq, tppl));\n      sigsq *= sweep_factor;\n    }\n    smoothed.resize(sp.size(), 0);\n    smoothed[0] = sp[0].second;\n    smoothed.back() = sp.back().second; \n    for (int i = 1; i < sp.size()-1; ++i) {\n      double prev = sp[i-1].second;\n      double next = sp[i+1].second;\n      double cur = sp[i].second;\n      smoothed[i] = (prev*0.2) + cur * 0.6 + (0.2*next);\n    }\n    double best_ppl = 9999999;\n    unsigned best_i = 0;\n    for (unsigned i = 0; i < sp.size(); ++i) {\n      if (smoothed[i] < best_ppl) {\n        best_ppl = smoothed[i];\n        best_i = i;\n      }\n    }\n    sigsq = sp[best_i].first;\n  }\n  cerr << \"Learning parameters...\" << endl;\n  tppl = LearnParameters(training, testing, sigsq, conf[\"memory_buffers\"].as<unsigned>(), &x);\n\n  Weights w;\n  if (conf.count(\"weights\")) {\n    cerr << \"Interpolating with previous weight vectors...\" << endl;\n    for (int i = 1; i < x.size(); ++i)\n      x[i] = (x[i] * psi) + old_weights.get(i) * (1.0 - psi);\n  }\n  cout.precision(15);\n  cout << \"# sigma^2=\" << sigsq << \"\\theld out perplexity=\";\n  if (tppl) { cout << tppl << endl; } else { cout << \"N/A\\n\"; }\n  if (sp.size()) {\n    cout << \"# Parameter sweep:\\n\";\n    for (int i = 0; i < sp.size(); ++i) {\n      cout << \"# \" << sp[i].first << \"\\t\" << sp[i].second << \"\\t\" << smoothed[i] << endl;\n    }\n  }\n  w.InitFromVector(x);\n  w.WriteToFile(\"-\");\n  return 0;\n}\n", "meta": {"hexsha": "1264f535c4e5d02e8c643d3b3ae5626e942dd2ee", "size": 9632, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pro-train/mr_pro_reduce.cc", "max_stars_repo_name": "jhclark/cdec", "max_stars_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-03T00:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-03T00:44:01.000Z", "max_issues_repo_path": "pro-train/mr_pro_reduce.cc", "max_issues_repo_name": "jhclark/cdec", "max_issues_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pro-train/mr_pro_reduce.cc", "max_forks_repo_name": "jhclark/cdec", "max_forks_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.035335689, "max_line_length": 139, "alphanum_fraction": 0.5849252492, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.21697593479522084}}
{"text": "//  Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_STATS_EXTREME_VALUE_HPP\n#define BOOST_STATS_EXTREME_VALUE_HPP\n\n#include <boost/math/distributions/fwd.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/math/special_functions/log1p.hpp>\n#include <boost/math/special_functions/expm1.hpp>\n#include <boost/math/distributions/complement.hpp>\n#include <boost/math/distributions/detail/common_error_handling.hpp>\n\n//\n// This is the maximum extreme value distribution, see\n// http://www.itl.nist.gov/div898/handbook/eda/section3/eda366g.htm\n// and http://mathworld.wolfram.com/ExtremeValueDistribution.html\n// Also known as a Fisher-Tippett distribution, a log-Weibull\n// distribution or a Gumbel distribution.\n\n#include <utility>\n#include <cmath>\n\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4702) // unreachable code (return after domain_error throw).\n#endif\n\nnamespace boost{ namespace math{\n\nnamespace detail{\n//\n// Error check:\n//\ntemplate <class RealType, class Policy>\ninline bool verify_scale_b(const char* function, RealType b, RealType* presult, const Policy& pol)\n{\n   if((b <= 0) || !(boost::math::isfinite)(b))\n   {\n      *presult = policies::raise_domain_error<RealType>(\n         function,\n         \"The scale parameter \\\"b\\\" must be finite and > 0, but was: %1%.\", b, pol);\n      return false;\n   }\n   return true;\n}\n\n} // namespace detail\n\ntemplate <class RealType = double, class Policy = policies::policy<> >\nclass extreme_value_distribution\n{\npublic:\n   typedef RealType value_type;\n   typedef Policy policy_type;\n\n   extreme_value_distribution(RealType a = 0, RealType b = 1)\n      : m_a(a), m_b(b)\n   {\n      RealType err;\n      detail::verify_scale_b(\"boost::math::extreme_value_distribution<%1%>::extreme_value_distribution\", b, &err, Policy());\n      detail::check_finite(\"boost::math::extreme_value_distribution<%1%>::extreme_value_distribution\", a, &err, Policy());\n   } // extreme_value_distribution\n\n   RealType location()const { return m_a; }\n   RealType scale()const { return m_b; }\n\nprivate:\n   RealType m_a, m_b;\n};\n\ntypedef extreme_value_distribution<double> extreme_value;\n\n#ifdef __cpp_deduction_guides\ntemplate <class RealType>\nextreme_value_distribution(RealType)->extreme_value_distribution<typename boost::math::tools::promote_args<RealType>::type>;\ntemplate <class RealType>\nextreme_value_distribution(RealType,RealType)->extreme_value_distribution<typename boost::math::tools::promote_args<RealType>::type>;\n#endif\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> range(const extreme_value_distribution<RealType, Policy>& /*dist*/)\n{ // Range of permissible values for random variable x.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(\n      std::numeric_limits<RealType>::has_infinity ? -std::numeric_limits<RealType>::infinity() : -max_value<RealType>(), \n      std::numeric_limits<RealType>::has_infinity ? std::numeric_limits<RealType>::infinity() : max_value<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline const std::pair<RealType, RealType> support(const extreme_value_distribution<RealType, Policy>& /*dist*/)\n{ // Range of supported values for random variable x.\n   // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.\n   using boost::math::tools::max_value;\n   return std::pair<RealType, RealType>(-max_value<RealType>(),  max_value<RealType>());\n}\n\ntemplate <class RealType, class Policy>\ninline RealType pdf(const extreme_value_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   static const char* function = \"boost::math::pdf(const extreme_value_distribution<%1%>&, %1%)\";\n\n   RealType a = dist.location();\n   RealType b = dist.scale();\n   RealType result = 0;\n   if(0 == detail::verify_scale_b(function, b, &result, Policy()))\n      return result;\n   if(0 == detail::check_finite(function, a, &result, Policy()))\n      return result;\n   if((boost::math::isinf)(x))\n      return 0.0f;\n   if(0 == detail::check_x(function, x, &result, Policy()))\n      return result;\n   RealType e = (a - x) / b;\n   if(e < tools::log_max_value<RealType>())\n      result = exp(e) * exp(-exp(e)) / b;\n   // else.... result *must* be zero since exp(e) is infinite...\n   return result;\n} // pdf\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const extreme_value_distribution<RealType, Policy>& dist, const RealType& x)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   static const char* function = \"boost::math::cdf(const extreme_value_distribution<%1%>&, %1%)\";\n\n   if((boost::math::isinf)(x))\n      return x < 0 ? 0.0f : 1.0f;\n   RealType a = dist.location();\n   RealType b = dist.scale();\n   RealType result = 0;\n   if(0 == detail::verify_scale_b(function, b, &result, Policy()))\n      return result;\n   if(0 == detail::check_finite(function, a, &result, Policy()))\n      return result;\n   if(0 == detail::check_finite(function, a, &result, Policy()))\n      return result;\n   if(0 == detail::check_x(\"boost::math::cdf(const extreme_value_distribution<%1%>&, %1%)\", x, &result, Policy()))\n      return result;\n\n   result = exp(-exp((a-x)/b));\n\n   return result;\n} // cdf\n\ntemplate <class RealType, class Policy>\nRealType quantile(const extreme_value_distribution<RealType, Policy>& dist, const RealType& p)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   static const char* function = \"boost::math::quantile(const extreme_value_distribution<%1%>&, %1%)\";\n\n   RealType a = dist.location();\n   RealType b = dist.scale();\n   RealType result = 0;\n   if(0 == detail::verify_scale_b(function, b, &result, Policy()))\n      return result;\n   if(0 == detail::check_finite(function, a, &result, Policy()))\n      return result;\n   if(0 == detail::check_probability(function, p, &result, Policy()))\n      return result;\n\n   if(p == 0)\n      return -policies::raise_overflow_error<RealType>(function, 0, Policy());\n   if(p == 1)\n      return policies::raise_overflow_error<RealType>(function, 0, Policy());\n\n   result = a - log(-log(p)) * b;\n\n   return result;\n} // quantile\n\ntemplate <class RealType, class Policy>\ninline RealType cdf(const complemented2_type<extreme_value_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   static const char* function = \"boost::math::cdf(const extreme_value_distribution<%1%>&, %1%)\";\n\n   if((boost::math::isinf)(c.param))\n      return c.param < 0 ? 1.0f : 0.0f;\n   RealType a = c.dist.location();\n   RealType b = c.dist.scale();\n   RealType result = 0;\n   if(0 == detail::verify_scale_b(function, b, &result, Policy()))\n      return result;\n   if(0 == detail::check_finite(function, a, &result, Policy()))\n      return result;\n   if(0 == detail::check_x(function, c.param, &result, Policy()))\n      return result;\n\n   result = -boost::math::expm1(-exp((a-c.param)/b), Policy());\n\n   return result;\n}\n\ntemplate <class RealType, class Policy>\nRealType quantile(const complemented2_type<extreme_value_distribution<RealType, Policy>, RealType>& c)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions\n\n   static const char* function = \"boost::math::quantile(const extreme_value_distribution<%1%>&, %1%)\";\n\n   RealType a = c.dist.location();\n   RealType b = c.dist.scale();\n   RealType q = c.param;\n   RealType result = 0;\n   if(0 == detail::verify_scale_b(function, b, &result, Policy()))\n      return result;\n   if(0 == detail::check_finite(function, a, &result, Policy()))\n      return result;\n   if(0 == detail::check_probability(function, q, &result, Policy()))\n      return result;\n\n   if(q == 0)\n      return policies::raise_overflow_error<RealType>(function, 0, Policy());\n   if(q == 1)\n      return -policies::raise_overflow_error<RealType>(function, 0, Policy());\n\n   result = a - log(-boost::math::log1p(-q, Policy())) * b;\n\n   return result;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mean(const extreme_value_distribution<RealType, Policy>& dist)\n{\n   RealType a = dist.location();\n   RealType b = dist.scale();\n   RealType result = 0;\n   if(0 == detail::verify_scale_b(\"boost::math::mean(const extreme_value_distribution<%1%>&)\", b, &result, Policy()))\n      return result;\n   if (0 == detail::check_finite(\"boost::math::mean(const extreme_value_distribution<%1%>&)\", a, &result, Policy()))\n      return result;\n   return a + constants::euler<RealType>() * b;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType standard_deviation(const extreme_value_distribution<RealType, Policy>& dist)\n{\n   BOOST_MATH_STD_USING // for ADL of std functions.\n\n   RealType b = dist.scale();\n   RealType result = 0;\n   if(0 == detail::verify_scale_b(\"boost::math::standard_deviation(const extreme_value_distribution<%1%>&)\", b, &result, Policy()))\n      return result;\n   if(0 == detail::check_finite(\"boost::math::standard_deviation(const extreme_value_distribution<%1%>&)\", dist.location(), &result, Policy()))\n      return result;\n   return constants::pi<RealType>() * b / sqrt(static_cast<RealType>(6));\n}\n\ntemplate <class RealType, class Policy>\ninline RealType mode(const extreme_value_distribution<RealType, Policy>& dist)\n{\n   return dist.location();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType median(const extreme_value_distribution<RealType, Policy>& dist)\n{\n  using constants::ln_ln_two;\n   return dist.location() - dist.scale() * ln_ln_two<RealType>();\n}\n\ntemplate <class RealType, class Policy>\ninline RealType skewness(const extreme_value_distribution<RealType, Policy>& /*dist*/)\n{\n   //\n   // This is 12 * sqrt(6) * zeta(3) / pi^3:\n   // See http://mathworld.wolfram.com/ExtremeValueDistribution.html\n   //\n   return static_cast<RealType>(1.1395470994046486574927930193898461120875997958366L);\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis(const extreme_value_distribution<RealType, Policy>& /*dist*/)\n{\n   // See http://mathworld.wolfram.com/ExtremeValueDistribution.html\n   return RealType(27) / 5;\n}\n\ntemplate <class RealType, class Policy>\ninline RealType kurtosis_excess(const extreme_value_distribution<RealType, Policy>& /*dist*/)\n{\n   // See http://mathworld.wolfram.com/ExtremeValueDistribution.html\n   return RealType(12) / 5;\n}\n\n\n} // namespace math\n} // namespace boost\n\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n\n// This include must be at the end, *after* the accessors\n// for this distribution have been defined, in order to\n// keep compilers that support two-phase lookup happy.\n#include <boost/math/distributions/detail/derived_accessors.hpp>\n\n#endif // BOOST_STATS_EXTREME_VALUE_HPP\n", "meta": {"hexsha": "d503b31bc9097dfd071565b678554e10354b51a4", "size": 10812, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/distributions/extreme_value.hpp", "max_stars_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_stars_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/distributions/extreme_value.hpp", "max_issues_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_issues_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AqooleEngine/src/main/cpp/boost/boost/math/distributions/extreme_value.hpp", "max_forks_repo_name": "kodai731/Aqoole-Engine-Android-Vulkan-Rendering-Engine-", "max_forks_repo_head_hexsha": "72c8f34b6b6d507319069e681ff8c5008337b7c6", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1038961039, "max_line_length": 143, "alphanum_fraction": 0.7066222716, "num_tokens": 2794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795672, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21678555428705873}}
{"text": "/*\nCopyright (c) 2020 Naomasa Matsubayashi\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include <fstream>\n#include <iostream>\n#include <chrono>\n#include <boost/program_options.hpp>\n#include <nlohmann/json.hpp>\n#include \"ifm/bessel.h\"\nint main( int argc, char* argv[] ) {\n  boost::program_options::options_description options(\"オプション\");\n  options.add_options()\n    (\"help,h\",    \"ヘルプを表示\")\n    (\"bessel,b\", boost::program_options::value<std::string>()->default_value( \"bessel.mp\" ), \"ベッセル関数近似係数\");\n  boost::program_options::variables_map params;\n  boost::program_options::store( boost::program_options::parse_command_line( argc, argv, options ), params );\n  boost::program_options::notify( params );\n  if( params.count(\"help\") ) {\n    std::cout << options << std::endl;\n    return 0;\n  }\n  std::vector< std::pair< float, float > > pre;\n  {\n    std::ifstream bessel_file( params[\"bessel\"].as<std::string>(), std::ofstream::binary );\n    nlohmann::json bessel = nlohmann::json::from_msgpack( bessel_file );\n    for( const auto &v: bessel )\n      pre.emplace_back( v.at( 0 ), v.at( 1 ) );\n  }\n  const auto t0 = std::chrono::steady_clock::now();\n  for( unsigned int b_ = 0.f; b_ != 400; ++b_ ) {\n    float b = b_ * 0.1f;\n    for( unsigned int n = 0; n != 60; ++n ) {\n      ifm::bessel_kind1( b, n );\n    }\n  }\n  const auto t1 = std::chrono::steady_clock::now();\n  for( unsigned int b_ = 0.f; b_ != 400; ++b_ ) {\n    float b = b_ * 0.1f;\n    float l1 = 0;\n    float l2 = 0;\n    for( unsigned int n = 0; n != 60; ++n ) {\n      float y = ifm::bessel_kind1_approx_2019( b, n, l1, l2, pre );\n      l2 = l1;\n      l1 = y;\n    }\n  }\n  const auto t2 = std::chrono::steady_clock::now();\n  float e0 = float( std::chrono::duration_cast< std::chrono::microseconds >( t1 - t0 ).count() );\n  float e1 = float( std::chrono::duration_cast< std::chrono::microseconds >( t2 - t1 ).count() );\n  std::cout << \"台形公式: \" << (400*60)/e0 << \"Mbps(\" << 400*60 << \" samples in \" << e0 << \"microseconds)\" << std::endl;\n  std::cout << \"近似式: \" << (400*60)/e1 << \"Mbps(\" << 400*60 << \" samples in \" << e1 << \"microseconds)\" << std::endl;\n}\n\n", "meta": {"hexsha": "27289a7a1fabd7e998b0af8481147616f77521e2", "size": 3087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/bessel_benchmark.cpp", "max_stars_repo_name": "Fadis/ifm", "max_stars_repo_head_hexsha": "8e538c67e756cfc4056bf406e578809dc2b462f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T08:51:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T04:44:24.000Z", "max_issues_repo_path": "src/bessel_benchmark.cpp", "max_issues_repo_name": "Fadis/ifm", "max_issues_repo_head_hexsha": "8e538c67e756cfc4056bf406e578809dc2b462f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-01T18:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-01T18:31:50.000Z", "max_forks_repo_path": "src/bessel_benchmark.cpp", "max_forks_repo_name": "Fadis/ifm", "max_forks_repo_head_hexsha": "8e538c67e756cfc4056bf406e578809dc2b462f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2876712329, "max_line_length": 116, "alphanum_fraction": 0.6705539359, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21678555428705867}}
{"text": "//  Copyright John Maddock 2012 - 2021.\n//  Copyright Christopher Kormanyos 2016 - 2021.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n\n// Wrapper that works with e_float-2021, see also\n// https://github.com/ckormanyos/e_float-2021\n\n#ifndef E_FLOAT_2017_08_18_HPP_\n  #define E_FLOAT_2017_08_18_HPP_\n\n  #include <cstdint>\n  #include <sstream>\n  #include <tuple>\n  #include <type_traits>\n\n  #include <e_float/e_float.h>\n  #include <e_float/e_float_functions.h>\n\n  #include <boost/config.hpp>\n  #include <boost/multiprecision/number.hpp>\n\n  namespace boost { namespace math { namespace ef {\n\n  // Forward declaration of the e_float multiple precision class.\n  // This class binds native ::e_float to boost::multiprecsion::e_float.\n  class e_float;\n\n  } } }\n\n  // Define the number category as a floating-point kind\n  // for the e_float. This is needed for properly\n  // interacting as a backend with boost::muliprecision.\n  #if (BOOST_VERSION <= 107200)\n  template<>\n  struct boost::multiprecision::number_category<boost::math::ef::e_float>\n    : public boost::integral_constant<int, boost::multiprecision::number_kind_floating_point> { };\n  #elif (BOOST_VERSION <= 107500)\n  template<>\n  struct boost::multiprecision::number_category<boost::math::ef::e_float>\n    : public boost::integral_constant<int, boost::multiprecision::number_kind_floating_point> { };\n  #else\n  template<>\n  struct boost::multiprecision::number_category<boost::math::ef::e_float>\n    : public std::integral_constant<int, boost::multiprecision::number_kind_floating_point> { };\n  #endif\n\n  namespace boost { namespace math { namespace ef {\n\n  // This is the e_float multiple precision class.\n  class e_float\n  {\n  public:\n    #if (BOOST_VERSION <= 107500)\n    using signed_types   = mpl::list<std::int64_t>;\n    using unsigned_types = mpl::list<std::uint64_t>;\n    using float_types    = mpl::list<long double>;\n    #else\n    using   signed_types = std::tuple<  signed char,   signed short,   signed int,   signed long,   signed long long, std::intmax_t>;\n    using unsigned_types = std::tuple<unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long, std::uintmax_t>;\n    using float_types    = std::tuple<float, double, long double>;\n    #endif\n    using exponent_type  = std::int64_t;\n\n    e_float() : m_value() { }\n\n    explicit e_float(const ::e_float& rep) : m_value(rep) { }\n\n    e_float(const e_float& other) : m_value(other.m_value) { }\n    e_float(e_float&& other) : m_value(static_cast<::e_float&&>(other.m_value)) { }\n\n    template<typename UnsignedIntegralType,\n             typename std::enable_if<(   (std::is_integral<UnsignedIntegralType>::value == true)\n                                      && (std::is_unsigned<UnsignedIntegralType>::value == true))>::type const* = nullptr>\n    e_float(UnsignedIntegralType u) : m_value(::e_float(std::uint64_t(u))) { }\n\n    template<typename SignedIntegralType,\n             typename std::enable_if<(   (std::is_integral<SignedIntegralType>::value == true)\n                                      && (std::is_signed  <SignedIntegralType>::value == true))>::type const* = nullptr>\n    e_float(SignedIntegralType n) : m_value(::e_float(std::int64_t(n))) { }\n\n    template<typename FloatingPointType,\n             typename std::enable_if<std::is_floating_point<FloatingPointType>::value == true>::type const* = nullptr>\n    e_float(FloatingPointType f) : m_value(::e_float(static_cast<long double>(f))) { }\n\n    e_float(const char* c) : m_value(c) { }\n\n    e_float(const std::string& str) : m_value(str) { }\n\n    ~e_float() { }\n\n    e_float& operator=(const e_float& other)\n    {\n      if(this != &other)\n      {\n        m_value = other.m_value;\n      }\n\n      return *this;\n    }\n\n    e_float& operator=(e_float&& other)\n    {\n      m_value.operator=(static_cast<::e_float&&>(other.m_value));\n\n      return *this;\n    }\n\n    template<typename ArithmeticType,\n             typename std::enable_if<std::is_arithmetic<ArithmeticType>::value == true>::type const* = nullptr>\n    e_float& operator=(const ArithmeticType& x)\n    {\n      m_value = ::e_float(x);\n\n      return *this;\n    }\n\n    e_float& operator=(const std::string& str_rep)  { m_value = ::e_float(str_rep);  return *this; }\n    e_float& operator=(const char*        char_ptr) { m_value = ::e_float(char_ptr); return *this; }\n\n    void swap(e_float& other_mp_cpp_backend)\n    {\n      m_value.swap(other_mp_cpp_backend.m_value);\n    }\n\n          ::e_float&  representation()       { return m_value; }\n    const ::e_float&  representation() const { return m_value; }\n    const ::e_float& crepresentation() const { return m_value; }\n\n    std::string str(std::streamsize number_of_digits, const std::ios::fmtflags format_flags) const\n    {\n      std::string        my_result_str;\n      std::stringstream  my_stream_str;\n\n      my_stream_str.flags(format_flags);\n\n      static_cast<void>(my_stream_str.precision(number_of_digits));\n\n      m_value.wr_string(my_result_str, my_stream_str);\n\n      return my_result_str;\n    }\n\n    void negate()\n    {\n      m_value.negate();\n    }\n\n    int compare(const e_float& other_mp_cpp_backend) const\n    {\n      return static_cast<int>(m_value.compare(other_mp_cpp_backend.m_value));\n    }\n\n    template<typename ArithmeticType,\n             typename std::enable_if<std::is_arithmetic<ArithmeticType>::value == true>::type const* = nullptr>\n    int compare(ArithmeticType x)\n    {\n      return static_cast<int>(m_value.compare(::e_float(x)));\n    }\n\n  private:\n    ::e_float m_value;\n\n    e_float& operator=(const ::e_float&) = delete;\n  };\n\n  inline void eval_add(e_float& result, const e_float& x)\n  {\n    result.representation() += x.crepresentation();\n  }\n\n  inline void eval_subtract(e_float& result, const e_float& x)\n  {\n    result.representation() -= x.crepresentation();\n  }\n\n  inline void eval_multiply(e_float& result, const e_float& x)\n  {\n    result.representation() *= x.crepresentation();\n  }\n\n  inline void eval_multiply(e_float& result, const e_float& x, const e_float& y)\n  {\n    result.representation() = x.crepresentation() * y.crepresentation();\n  }\n\n  template<typename SignedIntegralType,\n           typename std::enable_if<(   (std::is_integral<SignedIntegralType>::value == true)\n                                    && (std::is_signed  <SignedIntegralType>::value == true))>::type const* = nullptr>\n  void eval_multiply(e_float& result, const SignedIntegralType& n)\n  {\n    result.representation().mul_signed_long_long(static_cast<std::int64_t>(n));\n  }\n\n  inline void eval_divide(e_float& result, const e_float& x)\n  {\n    result.representation() /= x.crepresentation();\n  }\n\n  template<typename SignedIntegralType,\n           typename std::enable_if<(   (std::is_integral<SignedIntegralType>::value == true)\n                                    && (std::is_signed  <SignedIntegralType>::value == true))>::type const* = nullptr>\n  void eval_divide(e_float& result, const SignedIntegralType& n)\n  {\n    result.representation().div_signed_long_long(static_cast<std::int64_t>(n));\n  }\n\n  inline bool eval_eq(const e_float& a, const e_float& b)\n  {\n    return (a.compare(b) == 0);\n  }\n\n  template<typename ArithmeticType,\n           typename std::enable_if<std::is_arithmetic<ArithmeticType>::value == true>::type const* = nullptr>\n  bool eval_eq(const e_float& a, const ArithmeticType& b)\n  {\n    return (a.compare(b) == 0);\n  }\n\n  template<typename ArithmeticType,\n           typename std::enable_if<std::is_arithmetic<ArithmeticType>::value == true>::type const* = nullptr>\n  bool eval_eq(const ArithmeticType& a, const e_float& b)\n  {\n    return (e_float(a).compare(b) == 0);\n  }\n\n  inline bool eval_gt(const e_float& a, const e_float& b)\n  {\n    return (a.compare(b) == 1);\n  }\n\n  template<typename ArithmeticType,\n           typename std::enable_if<std::is_arithmetic<ArithmeticType>::value == true>::type const* = nullptr>\n  bool eval_gt(const e_float& a, const ArithmeticType& b)\n  {\n    return (a.compare(b) == 1);\n  }\n\n  template<typename ArithmeticType,\n           typename std::enable_if<std::is_arithmetic<ArithmeticType>::value>::type const* = nullptr>\n  bool eval_gt(const ArithmeticType& a, const e_float& b)\n  {\n    return (e_float(a).compare(b) == 1);\n  }\n\n  inline bool eval_lt(const e_float& a, const e_float& b)\n  {\n    return (a.compare(b) == -1);\n  }\n\n  template<typename ArithmeticType,\n           typename std::enable_if<std::is_arithmetic<ArithmeticType>::value == true>::type const* = nullptr>\n  bool eval_lt(const e_float& a, const ArithmeticType& b)\n  {\n    return (a.compare(b) == -1);\n  }\n\n  template<typename ArithmeticType,\n           typename std::enable_if<std::is_arithmetic<ArithmeticType>::value == true>::type const* = nullptr>\n  bool eval_lt(const ArithmeticType& a, const e_float& b)\n  {\n    return (e_float(a).compare(b) == -1);\n  }\n\n  inline bool eval_is_zero(const e_float& x)\n  {\n    return x.crepresentation().iszero();\n  }\n\n  inline int eval_get_sign(const e_float& x)\n  {\n    if     (x.crepresentation().iszero()) { return  0; }\n    else if(x.crepresentation().isneg ()) { return -1; }\n    else                                  { return  1; }\n  }\n\n  inline void eval_convert_to(unsigned long long* result,\n                              const e_float& val)\n  {\n    *result = (val.crepresentation()).extract_unsigned_long_long();\n  }\n\n  inline void eval_convert_to(signed long long* result,\n                              const e_float& val)\n  {\n    *result = (val.crepresentation()).extract_signed_long_long();\n  }\n\n  inline void eval_convert_to(long double* result,\n                              const e_float& val)\n  {\n    *result = (val.crepresentation()).extract_long_double();\n  }\n\n  inline void eval_frexp(      e_float&                         result,\n                         const e_float&                         x,\n                               typename e_float::exponent_type* expptr)\n  {\n    using local_exponent_type = int;\n\n    local_exponent_type exp2;\n\n    result.representation() = ::ef::frexp(x.crepresentation(), &exp2);\n\n    *expptr = static_cast<typename e_float::exponent_type>(exp2);\n  }\n\n  inline void eval_frexp(      e_float& result,\n                         const e_float& x,\n                         int*           expptr,\n                         typename std::enable_if<std::is_same<typename e_float::exponent_type, int>::value == false>::type const* = nullptr)\n  {\n    result.representation() = ::ef::frexp(x.crepresentation(), expptr);\n  }\n\n  inline void eval_ldexp(      e_float& result,\n                         const e_float& x,\n                         const typename e_float::exponent_type exp_value)\n  {\n    using local_exponent_type = int;\n\n    result.representation() = ::ef::ldexp(x.crepresentation(), local_exponent_type(exp_value));\n  }\n\n  inline void eval_ldexp(      e_float& result,\n                         const e_float& x,\n                         int            exp_value,\n                         typename std::enable_if<std::is_same<typename e_float::exponent_type, int>::value == false>::type const* = nullptr)\n  {\n    using local_exponent_type = int;\n\n    result.representation() = ::ef::ldexp(x.crepresentation(), local_exponent_type(exp_value));\n  }\n\n  inline e_float::exponent_type eval_ilogb(const e_float& val)\n  {\n    if(val.crepresentation().iszero())\n    {\n      return (std::numeric_limits<e_float::exponent_type>::min)();\n    }\n\n    if ((val.crepresentation().isinf)())\n    {\n      return (std::numeric_limits<e_float::exponent_type>::max)();\n    }\n\n    if ((val.crepresentation().isnan)())\n    {\n      #if defined(FP_ILOGBNAN)\n      return FP_ILOGBNAN;\n      #else\n      return (std::numeric_limits<e_float::exponent_type>::max)();\n      #endif\n    }\n\n   // Set the result to base-10 exponent (order) of the value.\n   return val.crepresentation().order();\n  }\n\n  template<typename IntegralType,\n           typename std::enable_if<(   (std::is_fundamental<IntegralType>::value == true)\n                                    && (std::is_integral   <IntegralType>::value == true))>::type const* = nullptr>\n  void eval_scalbn(e_float& result, const e_float& val, IntegralType e)\n  {\n    const std::int64_t my_e = static_cast<std::int64_t>(e);\n\n    const e_float t(::e_float(1.0, my_e));\n\n    eval_multiply(result, val, t);\n  }\n\n  inline void eval_floor(      e_float& result,\n                         const e_float& x)\n  {\n    result.representation() = ::ef::floor(x.crepresentation());\n  }\n\n  inline void eval_ceil(      e_float& result,\n                        const e_float& x)\n  {\n    result.representation() = ::ef::ceil(x.crepresentation());\n  }\n\n  inline int eval_fpclassify(const e_float& x)\n  {\n    if     ((x.crepresentation().isinf)()) { return FP_INFINITE; }\n    else if((x.crepresentation().isnan)()) { return FP_NAN; }\n    else if( x.crepresentation().iszero()) { return FP_ZERO; }\n    else                                   { return FP_NORMAL; }\n  }\n\n  inline void eval_trunc(      e_float& result,\n                         const e_float& x)\n  {\n    result.representation() = ::ef::integer_part(x.crepresentation());\n  }\n\n  inline void eval_abs(      e_float& result,\n                       const e_float& x)\n  {\n    result.representation() = x.crepresentation();\n\n    if(result.crepresentation().isneg())\n    {\n      result.representation().negate();\n    }\n  }\n\n  inline void eval_fabs(      e_float& result,\n                        const e_float& x)\n  {\n    result.representation() = x.crepresentation();\n\n    if(result.crepresentation().isneg())\n    {\n      result.representation().negate();\n    }\n  }\n\n  inline void eval_sqrt(      e_float& result,\n                        const e_float& x)\n  {\n    result.representation() = ::ef::sqrt(x.crepresentation());\n  }\n\n  inline void eval_sin(      e_float& result,\n                       const e_float& x)\n  {\n    result.representation() = ::ef::sin(x.crepresentation());\n  }\n\n  inline void eval_cos(      e_float& result,\n                       const e_float& x)\n  {\n    result.representation() = ::ef::cos(x.crepresentation());\n  }\n\n  inline void eval_tan(      e_float& result,\n                       const e_float& x)\n  {\n    result.representation() = ::ef::tan(x.crepresentation());\n  }\n\n  inline void eval_asin(      e_float& result,\n                        const e_float& x)\n  {\n    result.representation() = ::ef::asin(x.crepresentation());\n  }\n\n  inline void eval_acos(      e_float& result,\n                        const e_float& x)\n  {\n    result.representation() = ::ef::acos(x.crepresentation());\n  }\n\n  inline void eval_atan(      e_float& result,\n                        const e_float& x)\n  {\n    result.representation() = ::ef::atan(x.crepresentation());\n  }\n\n  inline void eval_atan2(      e_float& result,\n                         const e_float& y,\n                         const e_float& x)\n  {\n    result.representation() = ::ef::atan2(y.crepresentation(), x.crepresentation());\n  }\n\n  inline void eval_log(      e_float& result,\n                       const e_float& x)\n  {\n    result.representation() = ::ef::log(x.crepresentation());\n  }\n\n  inline void eval_log10(      e_float& result,\n                         const e_float& x)\n  {\n    result.representation() = ::ef::log10(x.crepresentation());\n  }\n\n  inline void eval_exp(      e_float& result,\n                       const e_float& x)\n  {\n    result.representation() = ::ef::exp(x.crepresentation());\n  }\n\n  inline void eval_sinh(      e_float& result,\n                        const e_float& x)\n  {\n    result.representation() = ::ef::sinh(x.crepresentation());\n  }\n\n  inline void eval_cosh(      e_float& result,\n                        const e_float& x)\n  {\n    result.representation() = ::ef::cosh(x.crepresentation());\n  }\n\n  inline void eval_tanh(      e_float& result,\n                        const e_float& x)\n  {\n    result.representation() = ::ef::tanh(x.crepresentation());\n  }\n\n  inline void eval_fmod(      e_float& result,\n                        const e_float& x,\n                        const e_float& y)\n  {\n    if(y.crepresentation().iszero())\n    {\n      result.representation() = ::ef::zero();\n    }\n    else\n    {\n      // Calculate the fractional part of x such that:\n      //   x = (integer_part * y) + fractional_part,\n      // where\n      //   |fractional_part| < |y|,\n      // and fractional_part has the same sign as x.\n\n      const ::e_float integer_part = ::ef::floor(x.crepresentation() / y.crepresentation());\n\n      result.representation() =\n        x.crepresentation() - (integer_part * y.crepresentation());\n\n      if(x.crepresentation().isneg() != y.crepresentation().isneg())\n      {\n        result.representation() -= y.crepresentation();\n      }\n    }\n  }\n\n  inline void eval_pow(      e_float& result,\n                       const e_float& x,\n                       const e_float& a)\n  {\n    result.representation() = ::ef::pow(x.crepresentation(), a.crepresentation());\n  }\n\n  } } } // namespace boost::math::ef\n\n  namespace boost { namespace math { namespace policies {\n\n  // Specialization of the precision structure.\n  template<typename ThisPolicy,\n           const boost::multiprecision::expression_template_option ExpressionTemplates>\n  struct precision<boost::multiprecision::number<boost::math::ef::e_float,\n                                                 ExpressionTemplates>,\n                   ThisPolicy>\n  {\n    using precision_type = typename ThisPolicy::precision_type;\n\n    using local_digits_2 = digits2<((::e_float::ef_digits10 + 1LL) * 1000LL) / 301LL>;\n\n    #if (BOOST_VERSION <= 107500)\n    using type = typename mpl::if_c       <((local_digits_2::value <= precision_type::value) || (precision_type::value <= 0)),\n                                           local_digits_2,\n                                           precision_type>::type;\n    #else\n    using type = typename std::conditional<((local_digits_2::value <= precision_type::value) || (precision_type::value <= 0)),\n                                           local_digits_2,\n                                           precision_type>::type;\n    #endif\n  };\n\n  } } } // namespaces boost::math::policies\n\n  namespace std\n  {\n    template<const boost::multiprecision::expression_template_option ExpressionTemplates>\n    class numeric_limits<boost::multiprecision::number<boost::math::ef::e_float,\n                                                       ExpressionTemplates>>\n    {\n    public:\n      static constexpr bool is_specialized = true;\n      static constexpr bool is_signed      = true;\n      static constexpr bool is_integer     = false;\n      static constexpr bool is_exact       = false;\n      static constexpr bool is_bounded     = true;\n      static constexpr bool is_modulo      = false;\n      static constexpr bool is_iec559      = false;\n      static constexpr int  digits         = ::e_float::ef_digits10;\n      static constexpr int  digits10       = ::e_float::ef_digits10;\n      static constexpr int  max_digits10   = ::e_float::ef_digits10 + 1;\n\n      static constexpr std::int64_t max_exponent   = ::e_float::ef_max_exp;\n      static constexpr std::int64_t max_exponent10 = ::e_float::ef_max_exp10;\n      static constexpr std::int64_t min_exponent   = ::e_float::ef_min_exp;\n      static constexpr std::int64_t min_exponent10 = ::e_float::ef_min_exp10;\n\n      static constexpr int                     radix             = 10;\n      static constexpr std::float_round_style  round_style       = std::round_indeterminate;\n      static constexpr bool                    has_infinity      = true;\n      static constexpr bool                    has_quiet_NaN     = true;\n      static constexpr bool                    has_signaling_NaN = false;\n      static constexpr std::float_denorm_style has_denorm        = std::denorm_absent;\n      static constexpr bool                    has_denorm_loss   = false;\n      static constexpr bool                    traps             = false;\n      static constexpr bool                    tinyness_before   = false;\n\n      static constexpr boost::multiprecision::number<boost::math::ef::e_float, ExpressionTemplates> (min)        () { return boost::math::ef::e_float(ef::value_min()); }\n      static constexpr boost::multiprecision::number<boost::math::ef::e_float, ExpressionTemplates> (max)        () { return boost::math::ef::e_float(ef::value_max()); }\n      static constexpr boost::multiprecision::number<boost::math::ef::e_float, ExpressionTemplates> lowest       () { return boost::math::ef::e_float(ef::zero()); }\n      static constexpr boost::multiprecision::number<boost::math::ef::e_float, ExpressionTemplates> epsilon      () { return boost::math::ef::e_float(ef::value_eps()); }\n      static constexpr boost::multiprecision::number<boost::math::ef::e_float, ExpressionTemplates> round_error  () { return boost::math::ef::e_float(ef::half()); }\n      static constexpr boost::multiprecision::number<boost::math::ef::e_float, ExpressionTemplates> infinity     () { return boost::math::ef::e_float(ef::value_inf()); }\n      static constexpr boost::multiprecision::number<boost::math::ef::e_float, ExpressionTemplates> quiet_NaN    () { return boost::math::ef::e_float(ef::value_nan()); }\n      static constexpr boost::multiprecision::number<boost::math::ef::e_float, ExpressionTemplates> signaling_NaN() { return boost::math::ef::e_float(ef::zero()); }\n      static constexpr boost::multiprecision::number<boost::math::ef::e_float, ExpressionTemplates> denorm_min   () { return boost::math::ef::e_float(ef::zero()); }\n    };\n  } // namespace std\n\n#endif // E_FLOAT_2017_08_18_HPP_\n", "meta": {"hexsha": "4810f0ba832ec70780fadb85384df46db773d39d", "size": 21711, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/math/include/boost/math/bindings/e_float.hpp", "max_stars_repo_name": "ckormanyos/e_float-2021", "max_stars_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/math/include/boost/math/bindings/e_float.hpp", "max_issues_repo_name": "ckormanyos/e_float-2021", "max_issues_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T14:43:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:12:27.000Z", "max_forks_repo_path": "libs/math/include/boost/math/bindings/e_float.hpp", "max_forks_repo_name": "ckormanyos/e_float-2021", "max_forks_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2451298701, "max_line_length": 169, "alphanum_fraction": 0.6191792179, "num_tokens": 5210, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.21675390318912957}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2014-2021.\n// Modifications copyright (c) 2014-2021, Oracle and/or its affiliates.\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_AZIMUTH_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_AZIMUTH_HPP\n\n\n#include <boost/geometry/algorithms/not_implemented.hpp>\n\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/radian_access.hpp>\n#include <boost/geometry/core/tag.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/strategies/default_strategy.hpp>\n#include <boost/geometry/strategies/azimuth/cartesian.hpp>\n#include <boost/geometry/strategies/azimuth/geographic.hpp>\n#include <boost/geometry/strategies/azimuth/spherical.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n       \n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate\n<\n    typename Geometry1, typename Geometry2,\n    typename Tag1 = typename tag<Geometry1>::type,\n    typename Tag2 = typename tag<Geometry2>::type\n>\nstruct azimuth : not_implemented<Tag1, Tag2>\n{};\n\ntemplate <typename Point1, typename Point2>\nstruct azimuth<Point1, Point2, point_tag, point_tag>\n{\n    template <typename Strategy>\n    static auto apply(Point1 const& p1, Point2 const& p2, Strategy const& strategy)\n    {\n        typedef typename decltype(strategy.azimuth())::template result_type\n            <\n                typename coordinate_type<Point1>::type,\n                typename coordinate_type<Point2>::type\n            >::type calc_t;\n\n        calc_t result = 0;\n        calc_t const x1 = geometry::get_as_radian<0>(p1);\n        calc_t const y1 = geometry::get_as_radian<1>(p1);\n        calc_t const x2 = geometry::get_as_radian<0>(p2);\n        calc_t const y2 = geometry::get_as_radian<1>(p2);\n\n        strategy.azimuth().apply(x1, y1, x2, y2, result);\n\n        // NOTE: It is not clear which units we should use for the result.\n        //   For now radians are always returned but a user could expect\n        //   e.g. something like this:\n        /*\n        bool const both_degree = std::is_same\n                <\n                    typename detail::cs_angular_units<Point1>::type,\n                    geometry::degree\n                >::value\n            && std::is_same\n                <\n                    typename detail::cs_angular_units<Point2>::type,\n                    geometry::degree\n                >::value;\n        if (both_degree)\n        {\n            result *= math::r2d<calc_t>();\n        }\n        */\n\n        return result;\n    }\n};\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_strategy\n{\n\ntemplate\n<\n    typename Strategy,\n    bool IsUmbrella = strategies::detail::is_umbrella_strategy<Strategy>::value\n>\nstruct azimuth\n{\n    template <typename P1, typename P2>\n    static auto apply(P1 const& p1, P2 const& p2, Strategy const& strategy)\n    {\n        return dispatch::azimuth<P1, P2>::apply(p1, p2, strategy);\n    }\n};\n\ntemplate <typename Strategy>\nstruct azimuth<Strategy, false>\n{\n    template <typename P1, typename P2>\n    static auto apply(P1 const& p1, P2 const& p2, Strategy const& strategy)\n    {\n        using strategies::azimuth::services::strategy_converter;\n        return dispatch::azimuth\n            <\n                P1, P2\n            >::apply(p1, p2, strategy_converter<Strategy>::get(strategy));\n    }\n};\n\ntemplate <>\nstruct azimuth<default_strategy, false>\n{\n    template <typename P1, typename P2>\n    static auto apply(P1 const& p1, P2 const& p2, default_strategy)\n    {\n        typedef typename strategies::azimuth::services::default_strategy\n            <\n                P1, P2\n            >::type strategy_type;\n\n        return dispatch::azimuth<P1, P2>::apply(p1, p2, strategy_type());\n    }\n};\n\n\n} // namespace resolve_strategy\n\n\nnamespace resolve_variant\n{\n} // namespace resolve_variant\n\n\n/*!\n\\brief Calculate azimuth of a segment defined by a pair of points.\n\\ingroup azimuth\n\\tparam Point1 Type of the first point of a segment.\n\\tparam Point2 Type of the second point of a segment.\n\\param point1 First point of a segment.\n\\param point2 Second point of a segment.\n\\return Azimuth in radians.\n\n\\qbk{[include reference/algorithms/azimuth.qbk]}\n\n\\qbk{\n[heading Example]\n[azimuth]\n[azimuth_output]\n}\n*/\ntemplate <typename Point1, typename Point2>\ninline auto azimuth(Point1 const& point1, Point2 const& point2)\n{\n    concepts::check<Point1 const>();\n    concepts::check<Point2 const>();\n    \n    return resolve_strategy::azimuth\n            <\n                default_strategy\n            >::apply(point1, point2, default_strategy());\n}\n\n\n/*!\n\\brief Calculate azimuth of a segment defined by a pair of points.\n\\ingroup azimuth\n\\tparam Point1 Type of the first point of a segment.\n\\tparam Point2 Type of the second point of a segment.\n\\tparam Strategy Type of an umbrella strategy defining azimuth strategy.\n\\param point1 First point of a segment.\n\\param point2 Second point of a segment.\n\\param strategy Umbrella strategy defining azimuth strategy.\n\\return Azimuth in radians.\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/azimuth.qbk]}\n\n\\qbk{\n[heading Example]\n[azimuth_strategy]\n[azimuth_strategy_output]\n}\n*/\ntemplate <typename Point1, typename Point2, typename Strategy>\ninline auto azimuth(Point1 const& point1, Point2 const& point2, Strategy const& strategy)\n{\n    concepts::check<Point1 const>();\n    concepts::check<Point2 const>();\n\n    return resolve_strategy::azimuth<Strategy>::apply(point1, point2, strategy);\n}\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_AZIMUTH_HPP\n", "meta": {"hexsha": "28e5491e7a4ce423a201640e987d8383e460954b", "size": 6125, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/algorithms/azimuth.hpp", "max_stars_repo_name": "angryDuck2/PopcornTorrent", "max_stars_repo_head_hexsha": "63bed793cbd59117fc296f887ed91b937a85ce77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "include/boost/geometry/algorithms/azimuth.hpp", "max_issues_repo_name": "angryDuck2/PopcornTorrent", "max_issues_repo_head_hexsha": "63bed793cbd59117fc296f887ed91b937a85ce77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "include/boost/geometry/algorithms/azimuth.hpp", "max_forks_repo_name": "angryDuck2/PopcornTorrent", "max_forks_repo_head_hexsha": "63bed793cbd59117fc296f887ed91b937a85ce77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 27.1017699115, "max_line_length": 89, "alphanum_fraction": 0.6865306122, "num_tokens": 1464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.3345894545235253, "lm_q1q2_score": 0.21674645238590834}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// This file is manually converted from PROJ4 (projects.h)\n\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017.\n// Modifications copyright (c) 2017, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Geometry Library by Barend Gehrels (Geodan, Amsterdam)\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_IMPL_PROJECTS_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_IMPL_PROJECTS_HPP\n\n\n#include <cstring>\n#include <string>\n#include <vector>\n\n#include <boost/geometry/srs/projections/exception.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/mpl/if.hpp>\n#include <boost/type_traits/is_pod.hpp>\n\n\nnamespace boost { namespace geometry { namespace projections\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n/* some useful constants */\ntemplate <typename T>\ninline T ONEPI() { return boost::math::constants::pi<T>(); }\ntemplate <typename T>\ninline T HALFPI() { return boost::math::constants::half_pi<T>(); }\ntemplate <typename T>\ninline T FORTPI() { return boost::math::constants::pi<T>() / T(4); }\ntemplate <typename T>\ninline T TWOPI() { return boost::math::constants::two_pi<T>(); }\ntemplate <typename T>\ninline T TWO_D_PI() { return boost::math::constants::two_div_pi<T>(); }\ntemplate <typename T>\ninline T HALFPI_SQR() { return 2.4674011002723396547086227499689; }\ntemplate <typename T>\ninline T PI_SQR() { return boost::math::constants::pi_sqr<T>(); }\ntemplate <typename T>\ninline T THIRD() { return 0.3333333333333333333333333333333; }\ntemplate <typename T>\ninline T TWOTHIRD() { return 0.6666666666666666666666666666666; }\ntemplate <typename T>\ninline T PI_HALFPI() { return 4.7123889803846898576939650749193; }\ntemplate <typename T>\ninline T TWOPI_HALFPI() { return 7.8539816339744830961566084581988; }\ntemplate <typename T>\ninline T PI_DIV_3() { return 1.0471975511965977461542144610932; }\n\n/* datum_type values */\nstatic const int PJD_UNKNOWN = 0;\nstatic const int PJD_3PARAM = 1;\nstatic const int PJD_7PARAM = 2;\nstatic const int PJD_GRIDSHIFT = 3;\nstatic const int PJD_WGS84 = 4;   /* WGS84 (or anything considered equivelent) */\n\n/* library errors */\nstatic const int PJD_ERR_GEOCENTRIC = -45;\nstatic const int PJD_ERR_AXIS = -47;\nstatic const int PJD_ERR_GRID_AREA = -48;\nstatic const int PJD_ERR_CATALOG = -49;\n\ntemplate <typename T>\nstruct pvalue\n{\n    std::string param;\n    int used;\n\n    int i;\n    T f;\n    std::string s;\n};\n\ntemplate <typename T>\nstruct pj_const_pod\n{\n    int over;   /* over-range flag */\n    int geoc;   /* geocentric latitude flag */\n    int is_latlong; /* proj=latlong ... not really a projection at all */\n    int is_geocent; /* proj=geocent ... not really a projection at all */\n    T\n        a,  /* major axis or radius if es==0 */\n        a_orig, /* major axis before any +proj related adjustment */\n        es, /* e ^ 2 */\n        es_orig, /* es before any +proj related adjustment */\n        e,  /* eccentricity */\n        ra, /* 1/A */\n        one_es, /* 1 - e^2 */\n        rone_es, /* 1/one_es */\n        lam0, phi0, /* central longitude, latitude */\n        x0, y0, /* easting and northing */\n        k0,    /* general scaling factor */\n        to_meter, fr_meter, /* cartesian scaling */\n        vto_meter, vfr_meter;      /* Vertical scaling. Internal unit [m] */\n\n    int datum_type; /* PJD_UNKNOWN/3PARAM/7PARAM/GRIDSHIFT/WGS84 */\n    T  datum_params[7];\n    T  from_greenwich; /* prime meridian offset (in radians) */\n    T  long_wrap_center; /* 0.0 for -180 to 180, actually in radians*/\n    bool    is_long_wrap_set;\n\n    // Initialize all variables to zero\n    pj_const_pod()\n    {\n        std::memset(this, 0, sizeof(pj_const_pod));\n    }\n};\n\ntemplate <typename T>\nstruct pj_const_non_pod\n{\n    int over;   /* over-range flag */\n    int geoc;   /* geocentric latitude flag */\n    int is_latlong; /* proj=latlong ... not really a projection at all */\n    int is_geocent; /* proj=geocent ... not really a projection at all */\n    T\n        a,  /* major axis or radius if es==0 */\n        a_orig, /* major axis before any +proj related adjustment */\n        es, /* e ^ 2 */\n        es_orig, /* es before any +proj related adjustment */\n        e,  /* eccentricity */\n        ra, /* 1/A */\n        one_es, /* 1 - e^2 */\n        rone_es, /* 1/one_es */\n        lam0, phi0, /* central longitude, latitude */\n        x0, y0, /* easting and northing */\n        k0,    /* general scaling factor */\n        to_meter, fr_meter, /* cartesian scaling */\n        vto_meter, vfr_meter;      /* Vertical scaling. Internal unit [m] */\n\n    int datum_type; /* PJD_UNKNOWN/3PARAM/7PARAM/GRIDSHIFT/WGS84 */\n    T  datum_params[7];\n    T  from_greenwich; /* prime meridian offset (in radians) */\n    T  long_wrap_center; /* 0.0 for -180 to 180, actually in radians*/\n    bool    is_long_wrap_set;\n\n    // Initialize all variables to zero\n    pj_const_non_pod()\n        : over(0), geoc(0), is_latlong(0), is_geocent(0)\n        , a(0), a_orig(0), es(0), es_orig(0), e(0), ra(0)\n        , one_es(0), rone_es(0), lam0(0), phi0(0), x0(0), y0(0), k0(0)\n        , to_meter(0), fr_meter(0), vto_meter(0), vfr_meter(0)\n        , datum_type(PJD_UNKNOWN)\n        , from_greenwich(0), long_wrap_center(0), is_long_wrap_set(false)\n    {\n        datum_params[0] = 0;\n        datum_params[1] = 0;\n        datum_params[2] = 0;\n        datum_params[3] = 0;\n        datum_params[4] = 0;\n        datum_params[5] = 0;\n        datum_params[6] = 0;\n    }\n};\n\ntemplate <typename T>\nstruct pj_const\n    : boost::mpl::if_c\n        <\n            boost::is_pod<T>::value,\n            pj_const_pod<T>,\n            pj_const_non_pod<T>\n        >::type\n{};\n\n// PROJ4 complex. Might be replaced with std::complex\ntemplate <typename T>\nstruct COMPLEX { T r, i; };\n\nstruct PJ_ELLPS\n{\n    std::string id;    /* ellipse keyword name */\n    std::string major;    /* a= value */\n    std::string ell;    /* elliptical parameter */\n    std::string name;    /* comments */\n};\n\nstruct PJ_DATUMS\n{\n    std::string id;     /* datum keyword */\n    std::string defn;   /* ie. \"to_wgs84=...\" */\n    std::string ellipse_id; /* ie from ellipse table */\n    std::string comments; /* EPSG code, etc */\n};\n\nstruct PJ_PRIME_MERIDIANS\n{\n    std::string id;     /* prime meridian keyword */\n    std::string defn;   /* offset from greenwich in DMS format. */\n};\n\nstruct PJ_UNITS\n{\n    std::string id;    /* units keyword */\n    std::string to_meter;    /* multiply by value to get meters */\n    std::string name;    /* comments */\n};\n\ntemplate <typename T>\nstruct DERIVS\n{\n    T x_l, x_p; /* derivatives of x for lambda-phi */\n    T y_l, y_p; /* derivatives of y for lambda-phi */\n};\n\ntemplate <typename T>\nstruct FACTORS\n{\n    DERIVS<T> der;\n    T h, k;    /* meridinal, parallel scales */\n    T omega, thetap;    /* angular distortion, theta prime */\n    T conv;    /* convergence */\n    T s;        /* areal scale factor */\n    T a, b;    /* max-min scale error */\n    int code;        /* info as to analytics, see following */\n};\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n/*!\n    \\brief parameters, projection parameters\n    \\details This structure initializes all projections\n    \\ingroup projection\n*/\ntemplate <typename T>\nstruct parameters : public detail::pj_const<T>\n{\n    typedef T type;\n\n    std::string name;\n    std::vector<detail::pvalue<T> > params;\n};\n\n}}} // namespace boost::geometry::projections\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PROJECTS_HPP\n", "meta": {"hexsha": "232ae67ae953d9be741fa5416645f30702315d78", "size": 9017, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost_1_67_0/boost/geometry/srs/projections/impl/projects.hpp", "max_stars_repo_name": "ramcn/gemmx", "max_stars_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 354.0, "max_stars_repo_stars_event_min_datetime": "2018-08-13T18:19:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T10:37:20.000Z", "max_issues_repo_path": "boost_1_67_0/boost/geometry/srs/projections/impl/projects.hpp", "max_issues_repo_name": "ramcn/gemmx", "max_issues_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 79.0, "max_issues_repo_issues_event_min_datetime": "2018-08-01T11:50:45.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-17T13:40:06.000Z", "max_forks_repo_path": "boost_1_67_0/boost/geometry/srs/projections/impl/projects.hpp", "max_forks_repo_name": "ramcn/gemmx", "max_forks_repo_head_hexsha": "e23ab5358322a293110b642962b478bc92580636", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 90.0, "max_forks_repo_forks_event_min_datetime": "2018-11-15T12:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T11:12:39.000Z", "avg_line_length": 33.0293040293, "max_line_length": 81, "alphanum_fraction": 0.6641898636, "num_tokens": 2431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3522017684487511, "lm_q1q2_score": 0.21663503046410854}}
{"text": "#include <stdio.h>\r\n#include <fstream>\r\n#include <cmath>\r\n#include <malloc.h>\r\n#include <armadillo>\r\n#include <stdlib.h>\r\n#include <functions.h>\r\n#include <stdbool.h>\r\n#include <string.h>\r\nchar *outFile;\r\n\r\nchar* combine(char *a,char *b)\r\n{\r\n  char *c=(char*)malloc(strlen(a) + strlen(b) + 1);\r\n  strcpy(c,a);\r\n  strcat(c,b);\r\n  return c;\r\n}\r\n\r\n#define FOR(i,n) for(i=0;i<n;i++)\r\n#define error(i) printf(i); \r\nusing namespace arma;\r\nusing namespace std;\r\ntypedef double DD;\r\ntypedef long LL;\r\n\r\ntypedef struct{\r\n\tLL rows;\r\n\tLL columns;\r\n\tDD** matrix;\r\n} MAT;\r\n\r\ntypedef struct{\r\n    DD delta;       \r\n    LL nofIter;        \r\n    DD C;         \r\n    DD Cinit;      \r\n    DD Cfinal;         \r\n    LL nofNn;         \r\n    DD sigma;       \r\n    DD opt_tb;         \r\n    LL maxiter;         \r\n    DD tolfun;      \r\n    DD s;\r\n    DD* splits;\r\n} Opt;\r\n\r\ntypedef struct{\r\n\tDD tolX;\r\n\tLL length;\r\n\tDD tolFun;\r\n\t\r\n} Opt2;\r\n\r\ntypedef struct{\r\n    DD pathNorm;\r\n    LL nofNn;\r\n    DD annEps;\r\n    LL rbf;\r\n    DD sigma;\r\n} Param;\r\n\r\n#include \"CalcNnDists.c\"\r\n#include \"GraphDistKernelC.c\"\r\n#include \"MDS.c\"\r\n\r\ntypedef struct{\r\n\tDD obj;\r\n\tDD b;\r\n\tMAT Yu;\r\n\tMAT w;\r\n} Output_Primal;\r\n\r\nDD** Multiply_Matrices(DD **Mat1, DD **Mat2, LL M, LL Q, LL P)\r\n{\r\n\tLL i, c, d, k;\r\n\tDD Sum = 0;\r\n\tDD** Temp = (DD**)calloc(M, sizeof(DD*));\r\n\tFOR(i, M)\r\n\t\tTemp[i] = (DD*)calloc(Q, sizeof(DD));\r\n\tFOR(c, M)\r\n\t{\r\n\t\tFOR(d, Q)\r\n\t\t{\r\n\t\t\tFOR(k, P)\r\n\t\t\t{\r\n\t\t\t\tSum += (Mat1[c][k] * Mat2[k][d]);\r\n\t\t\t}\r\n\t\t\tTemp[c][d] = Sum;\r\n\t\t\tSum = 0;\r\n\t\t}\r\n\t}\r\n\treturn Temp;\r\n}\r\n\r\nDD** Transpose(DD **Mat1, LL Rows, LL Columns)\r\n{\r\n\tLL i, j;\r\n\tDD** Temp = (DD**)calloc(Columns, sizeof(DD*));\r\n\tfor (i = 0; i<Columns; i++)\r\n\t{\r\n\t\tTemp[i] = (DD*)calloc(Rows, sizeof(DD));\r\n\t}\r\n\tfor (i = 0; i<Rows; i++)\r\n\t{\r\n\t\tfor (j = 0; j<Columns; j++)\r\n\t\t{\r\n\t\t\tTemp[j][i] = Mat1[i][j];\r\n\t\t}\r\n\t}\r\n\treturn Temp;\r\n}\r\n#include \"minimize.c\"\r\nOutput_Primal primal_tsvm(MAT X, MAT Y, MAT w0, Opt opt);\r\ndouble ** train_one_split(MAT Xnldr, double *Yl, long Yl_rows, long m0, Opt opt, long classes);\r\n\r\nDD** LDS(DD **Xl, LL d0, LL m0, DD **Xu, LL d1, LL m1, DD *Yl, LL Yl_rows, LL classes, DD rho, Opt opt)\r\n{\r\n\t/* \r\n       --> Run the Low Density Separation algorithm as described in\r\n       --> \"Semi-supervised classification by Low Density Separation\" by O. Chapelle and A. Zien\r\n\t   --> Xl:  d0 x m0 matrix with the labeled points\r\n\t   --> Xu:  d1 x m1 matrix with the unlabeled points\r\n\t   --> Yl:  column vector of length n containing the labels (+1 or -1 for binary)\r\n\t   --> rho: constant \r\n\t   --> opt: optional structure containing the (optional) fields,\r\n\t   -->\t   C:       the soft margin parameter relative to 1/var^2\r\n\t   -->                  [default = 1]\r\n\t   -->     nofNn:   number of NN in the graph construction \r\n\t   -->               [default = 0, i.e. fully connected graph]\r\n\t   -->     sigma:   the width of the RBF kernel\r\n\t   -->     delta:   threshold\r\n\t   -->     nofIter: number of iterations for C* to reach C [default = 10]\r\n\t   -->     Cinit:   initial value for C* relative to C [default = 0.01] \r\n\t   -->     Cfinal:  final value of C* relative to C [default = 1]\r\n\t   -->     maxiter: maximum number of iterations in each gradient\r\n\t   -->              descent (multiplied by nb of variables) [default = 3]\r\n\t   -->     tolfun:  stopping criterion on the function value\r\n\t   -->              (relative to C) [default = 1e-5]\r\n   */\r\n\tLL i, j, k, K;\r\n\tParam param;\r\n\tMAT D2, NN;\r\n\topt.delta = 0.1;\r\n\topt.nofIter = 10;\r\n\topt.C = 0.390;\r\n\topt.Cinit = 0.01;\r\n\topt.Cfinal = 1;\r\n\topt.nofNn = 100;\r\n\topt.sigma = INFINITY;\r\n\topt.opt_tb = 1;\r\n\topt.maxiter = 3;\r\n\topt.tolfun = exp(-5);\r\n\tif((1>opt.nofIter)|(opt.C<0)|((opt.Cinit<0)&&(opt.Cinit>opt.Cfinal))|(opt.sigma<0))error(\"Assertion error\");\r\n\tLL m = m0 + m1;\r\n\tif((opt.nofNn<0)|(opt.nofNn>m))error(\"Assertion error\");\r\n\tDD** mat = (DD**)calloc(m, sizeof(DD*));\r\n\tFOR(i, m)mat[i] = (DD*)calloc(d0, sizeof(DD));\r\n\tMAT X;\r\n\tX.matrix = mat; X.rows = m; X.columns = d0;\r\n\tFOR(i, X.rows)\r\n\t{\r\n\t\tFOR(j, X.columns)\r\n\t\t{\r\n\t\t\tif (i < m0)\r\n\t\t\t{\r\n\t\t\t\tX.matrix[i][j] = Xl[j][i];\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tX.matrix[i][j] = Xu[j][i - m0];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tK = classes;\r\n\t//===================================================\r\n\t//    ****** Compute the full distance graph ******\r\n\t//===================================================\r\n\t\r\n\toutput t = CalcNnDists(X.matrix, X.rows, X.columns, opt.nofNn);\r\n\tD2 = t.D2; NN = t.NN;\r\n\tparam.pathNorm = rho;\r\n\tparam.sigma = INFINITY;\r\n\tparam.nofNn = opt.nofNn;\r\n\tDD* idx = (DD*)calloc(m, sizeof(DD));\r\n\tFOR(i, m)\r\n\t{\r\n\t\tidx[i] = i + 1;\r\n\t}\r\n\tMAT E2 = graphDistKernelC(X, D2, NN, param, idx, m);\r\n    FOR(i,X.rows)free(X.matrix[i]);free(X.matrix); \r\n    FOR(i,opt.nofNn){free(D2.matrix[i]);free(NN.matrix[i]);}free(D2.matrix);free(NN.matrix);\r\n    D2.rows=0;D2.columns=0;NN.rows=0;NN.columns=0; \r\n\tif (opt.nofNn != 0)\r\n\t{\r\n\t\tDD** new_E2 = (DD**)calloc(E2.rows, sizeof(DD*));\r\n\t\tDD max1 = E2.matrix[0][0];\r\n\t\tFOR(i, E2.rows)\r\n\t\t{\r\n\t\t\tnew_E2[i] = (DD*)calloc(E2.columns, sizeof(DD));\r\n\t\t\tFOR(j, E2.columns)\r\n\t\t\t{\r\n\t\t\t\tnew_E2[i][j] = min(E2.matrix[i][j], E2.matrix[j][i]);\r\n\t\t\t\tif ((new_E2[i][j] > max1) && (!isinf(new_E2[i][j])))\r\n\t\t\t\t{\r\n\t\t\t\t\tmax1 = new_E2[i][j];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tFOR(i, E2.rows)free(E2.matrix[i]);free(E2.matrix);\r\n\t\tE2.matrix = new_E2;\r\n\t\tFOR(i, E2.rows)\r\n\t\t{\r\n\t\t\tFOR(j, E2.columns)\r\n\t\t\t{\r\n\t\t\t\tif (isinf(E2.matrix[i][j]))E2.matrix[i][j] = 2 * max1;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tDD* E2_array = (DD*)calloc(E2.rows*E2.columns, sizeof(DD));\r\n\tbool isinf_E2 = false;\r\n\tFOR(i, E2.columns)\r\n\t{\r\n\t\tFOR(j, E2.rows)\r\n\t\t{\r\n\t\t\tif (isinf(E2.matrix[j][i]))isinf_E2 = true;\r\n\t\t\tE2_array[i*E2.rows + j] = E2.matrix[j][i];\r\n\t\t}\r\n\t}\r\n\t//===========================================================================\r\n\t//        ********* Compute the new kernel, do the MDS reduction **********\r\n\t//===========================================================================\r\n\t\r\n\tdouble defaultSigma = calcDefaultSigma(E2_array, 2, E2.columns*E2.rows);\r\n\tdouble sigma = opt.sigma * defaultSigma;\r\n\tOutput_mds mds;\r\n\tif (isinf(sigma))\r\n\t{\r\n\t\tif (isinf_E2)\r\n\t\t{\r\n\t\t\terror(\"Cannot do the MDS: The graph is not connected\");\r\n\t\t}\r\n\t\tmds = MDS(E2.matrix, E2.rows, E2.columns, opt.delta);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tparam.rbf = 1;// set RBF name equal to Gauss\r\n\t\t//=================================================\r\n\t\t//       ****** Calculate RBF Kernel *******\r\n\t\t//=================================================\r\n\t\tdouble **K = calcRbfKernel(E2.matrix, E2.rows, E2.columns, param.rbf, sigma, 1);\r\n\t\tFOR(i, E2.rows)\r\n\t\t{\r\n\t\t\tFOR(j, E2.columns)\r\n\t\t\t{\r\n\t\t\t\tK[i][j] = 2 - 2 * K[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t\tmds = MDS(K, E2.rows, E2.columns, opt.delta);\r\n\t}\r\n\tdouble **cumsum = 0, sum = 0;\r\n\tcumsum = (DD**)calloc(E2.rows, sizeof(DD*));\r\n\tFOR(i, E2.rows){\r\n\t\tcumsum[i] = (DD*)calloc(1, sizeof(DD));\r\n\t\tif (i == 0)cumsum[i][0] = mds.eigen[i];\r\n\t\telse cumsum[i][0] = mds.eigen[i] + cumsum[i - 1][0];\r\n\t}\r\n\tsum = cumsum[E2.rows - 1][0];\r\n\tLL nb_comp;\r\n\tif (opt.delta >= 0)\r\n\t{\r\n\t\tFOR(i, E2.rows)\r\n\t\t{\r\n\t\t\tif ((1 - cumsum[i][0] < opt.delta)&(mds.eigen[i] < opt.delta*mds.eigen[0]))\r\n\t\t\t{\r\n\t\t\t\tnb_comp = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tnb_comp = E2.rows;\r\n\t}\r\n\tdouble **Xnldr = (DD**)calloc(mds.Y.rows, sizeof(DD*));\r\n\tdouble *mean_Xnldr = (DD*)calloc(nb_comp, sizeof(DD));\r\n\tFOR(i, mds.Y.rows)\r\n\t{\r\n\t\tXnldr[i] = (DD*)calloc(nb_comp, sizeof(DD));\r\n\t\t// Keep only the first components\r\n\t\tFOR(j, nb_comp){\r\n\t\t\tXnldr[i][j] = mds.Y.matrix[i][j];\r\n\t\t\tmean_Xnldr[j] += mds.Y.matrix[i][j];\r\n\t\t\tif (i == mds.Y.rows - 1){\r\n\t\t\t\tmean_Xnldr[j] = (mean_Xnldr[j])/ mds.Y.rows;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tmds.Y.columns = nb_comp;\r\n\tmds.Y.matrix = Xnldr;\r\n\tdouble sum_var = 0;\r\n\tFOR(i, nb_comp)\r\n\t{\r\n\t\tdouble var = 0;\r\n\t\tFOR(j, mds.Y.rows)\r\n\t\t{\r\n\t\t\tvar += pow(Xnldr[j][i] - mean_Xnldr[i], 2);\r\n\t\t}\r\n\t\tsum_var += var / (mds.Y.rows - 1);\r\n\t}\r\n\t// Default value of C = invert of the variance\r\n\tdouble defaultC = 1 / sum_var;\r\n\tdouble C = opt.C*defaultC; opt.Cinit = C*opt.Cinit; opt.Cfinal = C*opt.Cfinal; opt.C = C;\r\n\topt.s = 3;\r\n\t//============================================\r\n\t//       ******* Train the TSVM ********\r\n\t//============================================\r\n\tdouble **Yu = train_one_split(mds.Y, Yl,Yl_rows,m0, opt, classes);\r\n\treturn Yu;\r\n}\r\ndouble ** train_one_split(MAT Xnldr, double *Yl,long Yl_rows,long m0, Opt opt,long classes){\r\n\tMAT Y0,w0;\r\n\tw0.matrix = NULL;\r\n\tY0.matrix = (DD**)calloc(Xnldr.rows, sizeof(DD*)); Y0.rows = Xnldr.rows; Y0.columns = 1;\r\n\tlong i, j;\r\n\tif (classes == 2){\r\n\t\tif (Yl_rows > m0)\r\n\t\t{\r\n\t\t\topt.Cinit = opt.Cfinal; opt.nofIter = 1;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tFOR(i, Y0.rows)\r\n\t\t\t{\r\n\t\t\t\tY0.matrix[i] = (DD*)calloc(1, sizeof(DD));\r\n\t\t\t\tif (i < Yl_rows)Y0.matrix[i][0] = Yl[i];\r\n\t\t\t}\r\n\t\t\tOutput_Primal pr = primal_tsvm(Xnldr, Y0, w0, opt);\r\n\t\t\tint count=0;\r\n            FOR(i,pr.Yu.rows)\r\n\t\t\t{\r\n\t\t\t\tdouble boo=(pr.Yu.matrix[i][0]>0)?1:-1;\r\n                                if(boo==1){\r\n                                 printf(\"%ld Kareena \\n\",i);\r\n                                }\r\n                                else{\r\n                                 printf(\"%ld Amir \\n\",i);\r\n                                 } \r\n            }\r\n            printf(\"\\n total %d\\n\\n\",count);\r\n               return pr.Yu.matrix;\r\n              }\r\n\t}\r\n\telse{\r\n\t\tMAT new_Y;\r\n\t\tDD final_obj=0;\r\n\t\tOutput_Primal pr;\r\n\t\tnew_Y.rows = Xnldr.rows - Yl_rows; new_Y.columns = classes;\r\n\t\tnew_Y.matrix = (DD**)calloc(new_Y.rows, sizeof(DD*));\r\n\t\tFOR(i, new_Y.rows)new_Y.matrix[i] = (DD*)calloc(new_Y.columns, sizeof(DD));\r\n\t\tFOR(i, Y0.rows)\r\n\t\t{\r\n\t\t\tY0.matrix[i] = (DD*)calloc(1, sizeof(DD));\r\n\t\t}\r\n\t\tFOR(i, classes)\r\n\t\t{\r\n\t\t\tFOR(j, Yl_rows)\r\n\t\t\t{\r\n\t\t\t\tif (Yl[j] == i+1)\r\n\t\t\t\t\tY0.matrix[j][0] = 1;\r\n\t\t\t\telse Y0.matrix[j][0] = -1;\r\n\t\t\t}\r\n\t\t\tpr = primal_tsvm(Xnldr, Y0, w0, opt);\r\n\t\t\tFOR(j, new_Y.rows)new_Y.matrix[j][i] = pr.Yu.matrix[j][0];\r\n\t\t\tfinal_obj += pr.obj;\r\n\t\t}\r\n        int count=0;\r\n        FOR(i,new_Y.rows){\r\n                        LL index=0;\r\n                        FOR(j,new_Y.columns)\r\n                        {\r\n                          if(new_Y.matrix[i][j]>new_Y.matrix[i][index])index=j;\r\n                        }\r\n                        new_Y.matrix[i][0]=index+1;\r\n                } \r\n        FILE *fp;\r\n        char *new_string;\r\n        new_string=combine(outFile,\"/../results.txt\");\r\n        fp=fopen(new_string,\"w\");\r\n        FOR(i,new_Y.rows)\r\n\t\t{ \r\n\t\t\tfprintf(fp,\"%lf\\n\",new_Y.matrix[i][0]);\r\n        }\r\n        fclose(fp);\r\n\t}\r\n\t\t\treturn NULL;\r\n}\r\nvoid SVD(double*** return_mat,MAT inp)\r\n{\t\r\n  // Calculate Singular Value Decomposition using Armadillo library\t  \r\n  long i ,j;\r\n  fmat A=randu<fmat>(inp.columns,inp.rows);\r\n  double **my_mat=(double**)calloc(inp.columns,sizeof(double*));\r\n  for(i=0;i<inp.columns;i++)\r\n  {\r\n   my_mat[i]=(double*)calloc(inp.columns,sizeof(double));\r\n   for(j=0;j<inp.rows;j++)A(i,j)=inp.matrix[j][i];\r\n  } \r\n  fmat U;\r\n  fvec S;\r\n  fmat V;\r\n  svd(U, S, V, A);\r\n  for(i=0;i<inp.columns;i++){\r\n    for(j=0;j<inp.columns;j++)\r\n    {\r\n     my_mat[i][j]=U(i,j);\r\n     }\r\n  }\r\n  *return_mat=my_mat;\r\n}\r\nOutput_Primal primal_tsvm(MAT X, MAT Y, MAT w0, Opt opt)\r\n{\r\n\t//======================================================\r\n\t//   **** Solve the TSVM problem in the primal**** \r\n\t//======================================================\r\n\t\r\n\tMAT new_X;\r\n\tnew_X.matrix = (double**)calloc(X.rows, sizeof(double*));\r\n\tnew_X.rows = X.rows; new_X.columns = X.columns + 1;\r\n\tdouble  C, C2, exponent, cbal = 0, sum_vbal = 0, tolfun2;\r\n\tMAT Xu, R, vbal;\r\n\tvbal.matrix = (double**)calloc(1, sizeof(double*)); vbal.rows = 1; vbal.columns = X.rows;\r\n\tvbal.matrix[0] = (double*)calloc(vbal.columns, sizeof(double));\r\n\tlong i, j, zeros = 0, n, maxiter2;\r\n\tfor (i = 0; i < new_X.rows; i++)\r\n\t{\r\n\t\tvbal.matrix[0][i] = 1;\r\n\t\tnew_X.matrix[i] = (double*)calloc(new_X.columns, sizeof(double));\r\n\t\tFOR(j, new_X.columns - 1)new_X.matrix[i][j] = X.matrix[i][j];\r\n\t\tnew_X.matrix[i][new_X.columns - 1] = 1;\r\n\t}\r\n\tfor (i = 0; i < Y.rows; i++){ if (Y.matrix[i][0] == 0)zeros++; }\r\n\tXu.matrix = (double**)calloc(zeros, sizeof(double*));\r\n\tXu.rows = zeros;\r\n\tXu.columns = new_X.columns;\r\n\tfor (i = 0; i < Xu.rows; i++)\r\n\t{\r\n\t\tXu.matrix[i] = (double*)calloc(Xu.columns, sizeof(double));\r\n\t}\r\n\tzeros = 0;\r\n\tfor (i = 0; i < Y.rows; i++)\r\n\t{\r\n\t\tif (Y.matrix[i][0] == 0)\r\n\t\t{\r\n\t\t\tfor (j = 0; j < Xu.columns; j++)\r\n\t\t\t{\r\n\t\t\t\tXu.matrix[zeros][j] = new_X.matrix[i][j];\r\n\t\t\t}\r\n\t\t\tzeros++;\r\n\t\t}\r\n\t}\r\n\tXu.matrix = Transpose(Xu.matrix, Xu.rows, Xu.columns); i = Xu.rows; Xu.rows = Xu.columns; Xu.columns = i;\r\n\texponent = pow(opt.Cfinal / opt.Cinit, 1 / (opt.nofIter + 1));\r\n\tC = opt.C;\r\n\tC2 = opt.Cinit;\r\n\tn = new_X.columns;\r\n\tif (zeros > 0)\r\n\t{\r\n\t\tfor (i = 0; i < Y.rows; i++)\r\n\t\t{\r\n\t\t\tif (Y.matrix[i][0] != 0)\r\n\t\t\t{\r\n\t\t\t\tvbal.matrix[0][i] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvbal.matrix = Multiply_Matrices(vbal.matrix, new_X.matrix, vbal.rows, new_X.columns, vbal.columns); vbal.columns = new_X.columns;\r\n\tj = 0;\r\n\tfor (i = 0; i < Y.rows; i++)\r\n\t{\r\n\t\tif (Y.matrix[i][0] != 0)\r\n\t\t{\r\n\t\t\tj += 1;\r\n\t\t\tcbal += Y.matrix[i][0];\r\n\t\t}\r\n\t}\r\n\tfor (i = 0; i < vbal.columns; i++)sum_vbal += vbal.matrix[0][i];\r\n\tcbal = (cbal / j)*sum_vbal;\r\n    R.rows = vbal.columns; R.columns = vbal.columns;\r\n\tSVD(&R.matrix,vbal);\t\r\n\tDD** newR = (double**)calloc(R.rows, sizeof(double*));\r\n\tfor (i = 0; i < R.rows; i++)\r\n\t{\r\n\t\tnewR[i] = (double*)calloc(1, sizeof(double));\r\n\t\tnewR[i][0] = R.matrix[i][0];\r\n\t}\r\n\tMAT w;\r\n\tw.matrix = Multiply_Matrices(vbal.matrix, newR, 1, 1, R.rows);\r\n\tDD w1 = cbal / w.matrix[0][0];\r\n\tif (w0.matrix == NULL)\r\n\t{\r\n\t\tw.matrix = (double**)calloc(n - 1, sizeof(double*));\r\n\t\tfor (i = 0; i < n - 1; i++)\r\n\t\t{\r\n\t\t\tw.matrix[i] = (double*)calloc(1, sizeof(double));\r\n\t\t\tfor (j = 0; j < 1; j++)w.matrix[i][j] = 0;\r\n\t\t}\r\n\t\tw.rows = n - 1; w.columns = 1;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tDD** new_newR = (double**)calloc(R.rows, sizeof(double*));\r\n\t\tfor (i = 0; i < R.rows; i++)\r\n\t\t{\r\n\t\t\tnew_newR[i] = (double*)calloc(R.columns - 1, sizeof(double));\r\n\t\t\tfor (j = 0; j < R.columns - 1; j++)\r\n\t\t\t{\r\n\t\t\t\tnew_newR[i][j] = R.matrix[i][j + 1];\r\n\t\t\t}\r\n\t\t}\r\n\t\tw.matrix = Multiply_Matrices(Transpose(new_newR, R.rows, R.columns - 1), w0.matrix, R.columns - 1, w0.rows, R.rows);\r\n\t\tw.rows = R.columns - 1; w.columns = w0.rows;\r\n\t}\r\n\tmaxiter2 = opt.maxiter*new_X.rows;\r\n\ttolfun2 = opt.tolfun*C;\r\n\tOpt2 opt2;\r\n\topt2.length = maxiter2;\r\n\topt2.tolX = 0;\r\n\topt2.tolFun = tolfun2;\r\n\tDD* y_temp = (DD*)calloc(Y.rows, sizeof(DD));\r\n\tFOR(i, Y.rows)\r\n\t{\r\n\t\ty_temp[i] = Y.matrix[i][0];\r\n\t}\r\n\tbool FLAG;\r\n\tOutput_Obj  oo;\r\n\tFOR(i, opt.nofIter)\r\n\t{\r\n\t\tC2 = C2*exponent;\r\n\t\tOutput_mini tt = minimize(w, w1, y_temp, Y.rows, C, C2, opt.s, new_X, Xu, R, opt2);\r\n\t\too = obj_fun(w, w1, y_temp, Y.rows, C, C2, opt.s,new_X,Xu,R);\r\n\t\tFLAG = (tt.FX < opt2.length) ? 1 : 0;\r\n\t}\r\n\tDD **Temp=(DD**)calloc(w.rows+1,sizeof(DD*));\r\n\tFOR(i, w.rows + 1)\r\n\t{\r\n\t\tTemp[i] = (DD*)calloc(1, sizeof(DD));\r\n\t\tif (i !=0)Temp[i][0] = w.matrix[i-1][0];\r\n\t\telse Temp[i][0] = w1;\r\n\t}\r\n\tw.matrix = Multiply_Matrices(R.matrix, Temp, R.rows, 1, w.rows + 1); w.rows = R.rows; w.columns = 1;\r\n\tMAT Yu;\r\n\tYu.matrix = Multiply_Matrices(Transpose(Xu.matrix, Xu.rows, Xu.columns), w.matrix, Xu.columns, w.columns, w.rows); Yu.rows = Xu.columns; Yu.columns = w.columns;\r\n\tOutput_Primal pr;\r\n\tpr.obj = oo.obj;\r\n\tpr.b = w.matrix[w.rows - 1][0];\r\n\tpr.Yu = Yu;\r\n\tfree(w.matrix[w.rows - 1]);\r\n\tw.rows = w.rows - 1;\r\n\tpr.w = w;\r\n\treturn pr;\r\n}\r\n\r\n//==============================\r\n//      ******  MAIN *******\r\n//==============================\r\n\r\nint main(int argc,char * argv[]){\r\n  long rows=atoi(argv[3]),columns=atoi(argv[2]),columns2=atoi(argv[1])-columns,i,j;\t\r\n  FILE *fp;\r\n  char *new_string;\r\n  new_string=combine(argv[4],\"/../data/final_file_train.txt\");\r\n  fp=fopen(new_string,\"r\");\r\n  DD** k=(DD**)calloc(rows,sizeof(DD*));\r\n  FOR(i,rows)\r\n  {\r\n\tk[i]=(DD*)calloc(columns,sizeof(DD));\t\r\n  }\r\n  FOR(j,columns)\r\n  {\r\n\t  FOR(i,rows)\r\n\t  {\r\n\t   fscanf(fp,\"%lf \",&k[i][j]);\r\n\t  }\r\n  }\r\n  fclose(fp);\r\n  new_string=combine(argv[4],\"/../data/final_file_test.txt\");\r\n  fp=fopen(new_string,\"r\");\r\n  DD** k2=(DD**)calloc(rows,sizeof(DD*));\r\n  FOR(i,rows)\r\n  {\r\n\tk2[i]=(DD*)calloc(columns2,sizeof(DD));\t\r\n  }\r\n  FOR(j,columns2)\r\n  {\r\n\t  FOR(i,rows)\r\n\t  {\r\n\t     fscanf(fp,\"%lf \",&k2[i][j]);\r\n\t  }\r\n  } \r\n  fclose(fp);\r\n  DD* Yl=(DD*)calloc(columns,sizeof(DD*));\r\n  FOR(i,columns)\r\n  {\r\n\t  if(i<columns/2)\r\n\t     Yl[i]=1;\r\n\t  else \r\n\t     Yl[i]=2;\r\n  }\r\n  Opt opt;\r\n  opt.delta = 0.1;\r\n  opt.nofIter = 10;\r\n  opt.C = 2;\r\n  opt.Cinit = 0.01;\r\n  opt.Cfinal = 1;\r\n  opt.nofNn = 50;\r\n  opt.sigma = INFINITY;\r\n  opt.opt_tb = 1;\r\n  opt.maxiter = 3;\r\n  opt.tolfun = exp(-5);\r\n  outFile=argv[4];\r\n  DD** y=LDS(k,rows,columns,k2,rows,columns2,Yl,columns,3,0.5,opt);\r\n  return 0;\r\n}\r\n", "meta": {"hexsha": "ec79f8642071d66c0bc75ff42a5695d9ea264a77", "size": 16681, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Source.cpp", "max_stars_repo_name": "vaibhav9518/FaceReck-", "max_stars_repo_head_hexsha": "424804344dbb874fab1cd5240963d5f6512a16b6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2015-05-27T19:53:14.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-27T12:22:19.000Z", "max_issues_repo_path": "src/Source.cpp", "max_issues_repo_name": "vaibhav9518/FaceReck-", "max_issues_repo_head_hexsha": "424804344dbb874fab1cd5240963d5f6512a16b6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Source.cpp", "max_forks_repo_name": "vaibhav9518/FaceReck-", "max_forks_repo_head_hexsha": "424804344dbb874fab1cd5240963d5f6512a16b6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7752808989, "max_line_length": 162, "alphanum_fraction": 0.5136982195, "num_tokens": 5556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.21654557728860438}}
{"text": "/***********************************************************************************************************************\n*  OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.\n*\n*  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n*  following conditions are met:\n*\n*  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n*  disclaimer.\n*\n*  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following\n*  disclaimer in the documentation and/or other materials provided with the distribution.\n*\n*  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products\n*  derived from this software without specific prior written permission from the respective party.\n*\n*  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works\n*  may not use the \"OpenStudio\" trademark, \"OS\", \"os\", or any other confusingly similar designation without specific prior\n*  written permission from Alliance for Sustainable Energy, LLC.\n*\n*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n*  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED\n*  STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n*  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n*  USE, DATA, OR PROFITS; OR BUSINESS 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 THE USE OF THIS SOFTWARE, EVEN IF\n*  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************************************************************/\n\n#include \"Geometry.hpp\"\n#include \"Intersection.hpp\"\n#include \"Transformation.hpp\"\n#include \"Vector3d.hpp\"\n\n#include \"../core/Assert.hpp\"\n\n#include <boost/math/constants/constants.hpp>\n\n#include <polypartition/polypartition.h>\n\n\nnamespace openstudio{\n  /// convert degrees to radians\n  double degToRad(double degrees)\n  {\n    return degrees*boost::math::constants::pi<double>()/180.0;\n  }\n\n  /// convert radians to degrees\n  double radToDeg(double radians)\n  {\n    return radians*180.0/boost::math::constants::pi<double>();\n  }\n\n  /// compute area from surface as Point3dVector\n  boost::optional<double> getArea(const Point3dVector& points)\n  {\n    boost::optional<double> result;\n    OptionalVector3d newall = getNewallVector(points);\n    if (newall){\n      result = newall->length() / 2.0;\n    }\n    return result;\n  }\n\n  // compute Newall vector from Point3dVector, direction is same as outward normal\n  // magnitude is twice the area\n  OptionalVector3d getNewallVector(const Point3dVector& points)\n  {\n    OptionalVector3d result;\n    size_t N = points.size();\n    if (N >= 3){\n      Vector3d vec;\n      for (unsigned i = 1; i < N-1; ++i){\n        Vector3d v1 = points[i] - points[0];\n        Vector3d v2 = points[i+1] - points[0];\n        vec += v1.cross(v2);\n      }\n     result = vec;\n   }\n   return result;\n  }\n\n  // compute outward normal from Point3dVector\n  OptionalVector3d getOutwardNormal(const Point3dVector& points)\n  {\n    OptionalVector3d result = getNewallVector(points);\n    if (result){\n      if (!result->normalize()){\n        result.reset();\n      }\n    }\n    return result;\n  }\n\n  /// compute centroid from surface as Point3dVector\n  OptionalPoint3d getCentroid(const Point3dVector& points)\n  {\n    OptionalPoint3d result;\n\n    if (points.size() >= 3){\n      // convert to face coordinates\n      Transformation alignFace = Transformation::alignFace(points);\n      Point3dVector surfacePoints = alignFace.inverse()*points;\n\n      size_t N = surfacePoints.size();\n      double A = 0;\n      double cx = 0;\n      double cy = 0;\n      for (size_t i = 0; i < N; ++i){\n        double x1, x2, y1, y2;\n        if (i == N-1){\n          x1 = surfacePoints[i].x();\n          x2 = surfacePoints[0].x();\n          y1 = surfacePoints[i].y();\n          y2 = surfacePoints[0].y();\n        }else{\n          x1 = surfacePoints[i].x();\n          x2 = surfacePoints[i+1].x();\n          y1 = surfacePoints[i].y();\n          y2 = surfacePoints[i+1].y();\n        }\n\n        double dA = (x1*y2-x2*y1);\n        A += 0.5*dA;\n        cx += (x1+x2)*dA;\n        cy += (y1+y2)*dA;\n      }\n\n      if (A > 0){\n        // centroid in face coordinates\n        Point3d surfaceCentroid(cx/(6.0*A), cy/(6.0*A), 0.0);\n\n        // centroid\n        result = alignFace*surfaceCentroid;\n      }\n    }\n    return result;\n  }\n\n  /// reorder points to upper-left-corner convention\n  Point3dVector reorderULC(const Point3dVector& points)\n  {\n    size_t N = points.size();\n    if (N < 3){\n      return Point3dVector();\n    }\n\n    // transformation to align face\n    Transformation t = Transformation::alignFace(points);\n    Point3dVector facePoints = t.inverse()*points;\n\n    // find ulc index in face coordinates\n    double maxY = std::numeric_limits<double>::min();\n    double minX = std::numeric_limits<double>::max();\n    unsigned ulcIndex = 0;\n    for(unsigned i = 0; i < N; ++i){\n      OS_ASSERT(std::abs(facePoints[i].z()) < 0.001);\n      if ((maxY < facePoints[i].y()) || ((maxY < facePoints[i].y() + 0.00001) && (minX > facePoints[i].x()))){\n        ulcIndex = i;\n        maxY = facePoints[i].y();\n        minX = facePoints[i].x();\n      }\n    }\n\n    // no-op\n    if (ulcIndex == 0){\n      return points;\n    }\n\n    // create result\n    Point3dVector result;\n    std::copy (points.begin() + ulcIndex, points.end(), std::back_inserter(result));\n    std::copy (points.begin(), points.begin() + ulcIndex, std::back_inserter(result));\n    OS_ASSERT(result.size() == N);\n    return result;\n  }\n\n  std::vector<Point3d> removeCollinear(const Point3dVector& points, double tol)\n  {\n    Transformation t = Transformation::alignFace(points);\n    std::vector<Point3d> result = t*simplify(t.inverse()*points, true, tol);\n    return result;\n  }\n\n\n  std::vector<Point3d> removeCollinearLegacy(const Point3dVector& points, double tol)\n  {\n    size_t N = points.size();\n    if (N < 3){\n      return points;\n    }\n\n    std::vector<Point3d> result;\n    Point3d lastPoint = points[0];\n    result.push_back(lastPoint);\n\n    for (unsigned i = 1; i < N; ++i){\n      Point3d currentPoint = points[i];\n      Point3d nextPoint = points[0];\n      if (i < N-1){\n        nextPoint = points[i+1];\n      }\n\n      Vector3d a = (currentPoint - lastPoint);\n      Vector3d b = (nextPoint - currentPoint);\n\n      // if these fail to normalize we have zero length vectors (e.g. adjacent points)\n      if (a.normalize()){\n        if (b.normalize()){\n\n          Vector3d c = a.cross(b);\n          if (c.length() >= tol){\n            // cross product is significant\n            result.push_back(currentPoint);\n            lastPoint = currentPoint;\n          }else{\n            // see if dot product is near -1\n            double d = a.dot(b);\n            if (d <= -1.0 + tol){\n              // this is a line reversal\n              result.push_back(currentPoint);\n              lastPoint = currentPoint;\n            }\n          }\n        }\n      }\n    }\n\n    size_t iBegin = 0;\n    size_t iEnd = result.size();\n\n    bool resizeBegin = true;\n    while (resizeBegin){\n      resizeBegin = false;\n      unsigned N = iEnd - iBegin;\n      if (N > 3){\n        Vector3d a = (result[iBegin] - result[iEnd - 1]);\n        Vector3d b = (result[iBegin + 1] - result[iBegin]);\n        if (a.normalize()){\n          if (b.normalize()){\n            double d = a.dot(b);\n            if (d >= 1.0 - tol){\n              iBegin++;\n              resizeBegin = true;\n            }\n          } else{\n            iBegin++;\n            resizeBegin = true;\n          }\n        } else{\n          iBegin++;\n          resizeBegin = true;\n        }\n      }\n    }\n\n    bool resizeEnd = true;\n    while (resizeEnd){\n      resizeEnd = false;\n      unsigned N = iEnd - iBegin;\n      if (N > 3){\n        Vector3d a = (result[iEnd - 1] - result[iEnd - 2]);\n        Vector3d b = (result[iBegin] - result[iEnd - 1]);\n        if (a.normalize()){\n          if (b.normalize()){\n            double d = a.dot(b);\n            if (d >= 1.0 - tol){\n              iEnd--;\n              resizeEnd = true;\n            }\n          } else{\n            iEnd--;\n            resizeEnd = true;\n          }\n        } else{\n          iEnd--;\n          resizeEnd = true;\n        }\n      }\n    }\n\n    result = std::vector<Point3d>(result.begin() + iBegin, result.begin() + iEnd);\n    return result;\n  }\n\n  double getDistance(const Point3d& point1, const Point3d& point2) {\n    double dx = point1.x() - point2.x();\n    double dy = point1.y() - point2.y();\n    double dz = point1.z() - point2.z();\n    double result = std::sqrt(dx*dx + dy*dy + dz*dz);\n    return result;\n  }\n\n  double getDistancePointToLineSegment(const Point3d& point, const std::vector<Point3d>& lineSegment)\n  {\n    if (lineSegment.size() != 2){\n      return 0;\n    }\n\n    // http://paulbourke.net/geometry/pointlineplane/\n\n    Point3d point1 = lineSegment[0];\n    Point3d point2 = lineSegment[1];\n\n    Vector3d p2p1 = point2-point1;\n    Vector3d p3p1 = point-point1;\n\n    double d12 = p2p1.length();\n    if (d12 < 1.0e-12){\n      return p3p1.length();\n    }\n\n    Point3d closestPoint;\n    double u = p3p1.dot(p2p1) / (d12*d12);\n    if (u < 0){\n      closestPoint = point1;\n    }else if (u > 1){\n      closestPoint = point2;\n    }else{\n      closestPoint = point1 + u*p2p1;\n    }\n\n    Vector3d diff = point - closestPoint;\n\n    return diff.length();\n  }\n\n  double getDistancePointToTriangle(const Point3d& point, const std::vector<Point3d>& triangle)\n  {\n    if (triangle.size() != 3){\n      return 0;\n    }\n\n    //Distance Between Point and Triangle in 3D\n    //David Eberly\n    //Geometric Tools, LLC\n    //http://www.geometrictools.com/\n\n    //T(s; t) = B+sE0+tE1\n\n    Point3d B = triangle[0];\n    Vector3d E0 = triangle[1] - triangle[0];\n    Vector3d E1 = triangle[2] - triangle[0];\n    Vector3d BminusP = B - point;\n\n    double b = E0.dot(E1);\n\n    if (std::abs(b) > 1.0-1.0E-12){\n      // triangle is collinear\n      return 0;\n    }\n\n    double a = E0.dot(E0);\n    double c = E1.dot(E1);\n    double d = E0.dot(BminusP);\n    double e = E1.dot(BminusP);\n    // double f = BminusP.dot(BminusP); // unused\n\n    double det = a*c-b*b;\n    double s = b*e-c*d;\n    double t = b*d-a*e;\n\n    Point3d closestPoint;\n\n    if ( s+t <= det ) {\n      if ( s < 0 ) {\n        if ( t < 0 ) {\n          //region 4, closest to point triangle[0]\n          return getDistance(point, triangle[0]);\n        } else {\n          //region 3, closest to line triangle[0] to triangle[2]\n          std::vector<Point3d> line;\n          line.push_back(triangle[0]);\n          line.push_back(triangle[2]);\n          return getDistancePointToLineSegment(point, line);\n        }\n      } else if ( t < 0 ) {\n        //region 5, closest to line triangle[0] to triangle[1]\n        std::vector<Point3d> line;\n        line.push_back(triangle[0]);\n        line.push_back(triangle[1]);\n        return getDistancePointToLineSegment(point, line);\n      } else {\n        //region 0, closest point is inside triangle\n        double invDet = 1.0/det;\n        closestPoint = B + invDet*s*E0 + invDet*t*E1;\n      }\n    } else {\n      if ( s < 0 ) {\n        //region 2, closest to point triangle[2]\n        return getDistance(point, triangle[2]);\n      } else if ( t < 0 ) {\n        //region 6, closest to point triangle[1]\n        return getDistance(point, triangle[1]);\n      } else {\n        //region 1, closest to line triangle[1] to triangle[2]\n        std::vector<Point3d> line;\n        line.push_back(triangle[1]);\n        line.push_back(triangle[2]);\n        return getDistancePointToLineSegment(point, line);\n      }\n    }\n\n    Vector3d diff = point-closestPoint;\n    return diff.length();\n  }\n\n  double getAngle(const Vector3d& vector1, const Vector3d& vector2) {\n    Vector3d working1(vector1);\n    working1.normalize();\n    Vector3d working2(vector2);\n    working2.normalize();\n    return acos(working1.dot(working2));\n  }\n\n  bool circularEqual(const Point3dVector& points1, const Point3dVector& points2, double tol)\n  {\n    size_t N = points1.size();\n    if (N != points2.size()){\n      return false;\n    }\n\n    if (N == 0){\n      return true;\n    }\n\n    bool result = false;\n\n    // look for a common starting point\n    for (size_t i = 0; i < N; ++i){\n      if (getDistance(points1[0], points2[i]) <= tol){\n\n        result = true;\n\n        // check all other points\n        for (unsigned j = 0; j < N; ++j){\n          if (getDistance(points1[j], points2[(i + j) % N]) > tol){\n            result = false;\n            break;\n          }\n        }\n      }\n\n      if (result){\n        return result;\n      }\n    }\n\n    return result;\n  }\n\n  Point3d getCombinedPoint(const Point3d& point3d, std::vector<Point3d>& allPoints, double tol)\n  {\n    for (const Point3d& otherPoint : allPoints){\n      if (std::sqrt(std::pow(point3d.x()-otherPoint.x(), 2) + std::pow(point3d.y()-otherPoint.y(), 2) + std::pow(point3d.z()-otherPoint.z(), 2)) < tol){\n        return otherPoint;\n      }\n    }\n    allPoints.push_back(point3d);\n    return point3d;\n  }\n\n  std::vector<std::vector<Point3d> > computeTriangulation(const Point3dVector& vertices, const std::vector<std::vector<Point3d> >& holes, double tol)\n  {\n    std::vector<std::vector<Point3d> > result;\n\n    // check input\n    if (vertices.size () < 3){\n      return result;\n    }\n\n    boost::optional<Vector3d> normal = getOutwardNormal(vertices);\n    if (!normal || normal->z() > -0.999){\n      return result;\n    }\n\n    for (const auto& hole : holes){\n      normal = getOutwardNormal(hole);\n      if (!normal || normal->z() > -0.999){\n        return result;\n      }\n    }\n\n    std::vector<Point3d> allPoints;\n\n    // PolyPartition does not support holes which intersect the polygon or share an edge\n    // if any hole is not fully contained we will use boost to remove all the holes\n    bool polyPartitionHoles = true;\n    for (const std::vector<Point3d>& hole : holes){\n      if (!within(hole, vertices, tol)){\n        // PolyPartition can't handle this\n        polyPartitionHoles = false;\n        break;\n      }\n    }\n\n    if (!polyPartitionHoles){\n      // use boost to do all the intersections\n      std::vector<std::vector<Point3d> > allFaces = subtract(vertices, holes, tol);\n      std::vector<std::vector<Point3d> > noHoles;\n      for (const std::vector<Point3d>& face : allFaces){\n        std::vector<std::vector<Point3d> > temp = computeTriangulation(face, noHoles);\n        result.insert(result.end(), temp.begin(), temp.end());\n      }\n      return result;\n    }\n\n    // convert input to vector of TPPLPoly\n    std::list<TPPLPoly> polys;\n\n    TPPLPoly outerPoly; // must be counter-clockwise, input vertices are clockwise\n    outerPoly.Init(vertices.size());\n    outerPoly.SetHole(false);\n    size_t n = vertices.size();\n    for(size_t i = 0; i < n; ++i){\n\n      // should all have zero z coordinate now\n      double z = vertices[n-i-1].z();\n      if (abs(z) > tol){\n        LOG_FREE(Error, \"utilities.geometry.computeTriangulation\", \"All points must be on z = 0 plane for triangulation methods\");\n        return result;\n      }\n\n      Point3d point = getCombinedPoint(vertices[n-i-1], allPoints, tol);\n      outerPoly[i].x = point.x();\n      outerPoly[i].y = point.y();\n    }\n    outerPoly.SetOrientation(TPPL_CCW);\n    polys.push_back(outerPoly);\n\n\n    for (const std::vector<Point3d>& holeVertices : holes){\n\n      if (holeVertices.size () < 3){\n        LOG_FREE(Error, \"utilities.geometry.computeTriangulation\", \"Hole has fewer than 3 points, ignoring\");\n        continue;\n      }\n\n      TPPLPoly innerPoly; // must be clockwise, input vertices are clockwise\n      innerPoly.Init(holeVertices.size());\n      innerPoly.SetHole(true);\n      //std::cout << \"inner :\";\n      for(unsigned i = 0; i < holeVertices.size(); ++i){\n\n        // should all have zero z coordinate now\n        double z = holeVertices[i].z();\n        if (abs(z) > tol){\n          LOG_FREE(Error, \"utilities.geometry.computeTriangulation\", \"All points must be on z = 0 plane for triangulation methods\");\n          return result;\n        }\n\n        Point3d point = getCombinedPoint(holeVertices[i], allPoints, tol);\n        innerPoly[i].x = point.x();\n        innerPoly[i].y = point.y();\n      }\n      innerPoly.SetOrientation(TPPL_CW);\n      polys.push_back(innerPoly);\n    }\n\n    // do partitioning\n    TPPLPartition pp;\n    std::list<TPPLPoly> resultPolys;\n    int test = pp.Triangulate_EC(&polys,&resultPolys);\n    if (test == 0){\n      test = pp.Triangulate_MONO(&polys, &resultPolys);\n    }\n    if (test == 0){\n      //std::stringstream ss;\n      //ss << \"Vertices: \" << vertices << std::endl;\n      //for (const auto& hole : holes){ ss << \"Hole:\" << hole << std::endl; }\n      //std::string testStr = ss.str();\n      LOG_FREE(Error, \"utilities.geometry.computeTriangulation\", \"Failed to partition polygon\");\n      return result;\n    }\n\n    // convert back to vertices\n    std::list<TPPLPoly>::iterator it, itend;\n    //std::cout << \"Start\" << std::endl;\n    for(it = resultPolys.begin(), itend = resultPolys.end(); it != itend; ++it){\n\n      it->SetOrientation(TPPL_CW);\n\n      std::vector<Point3d> triangle;\n      for (long i = 0; i < it->GetNumPoints(); ++i){\n        TPPLPoint point = it->GetPoint(i);\n        triangle.push_back(Point3d(point.x, point.y, 0));\n      }\n      //std::cout << triangle << std::endl;\n      result.push_back(triangle);\n    }\n    //std::cout << \"End\" << std::endl;\n\n    return result;\n  }\n\n  std::vector<Point3d> moveVerticesTowardsPoint(const Point3dVector& vertices, const Point3d& point, double distance)\n  {\n    Point3dVector result;\n    for (const Point3d& vertex : vertices){\n      Vector3d vector = point-vertex;\n      vector.setLength(distance);\n      result.push_back(vertex+vector);\n    }\n    return result;\n  }\n\n  std::vector<Point3d> reverse(const Point3dVector& vertices)\n  {\n    std::vector<Point3d> result(vertices);\n    std::reverse(result.begin(), result.end());\n    return result;\n  }\n\n  bool applyViewAndDaylightingGlassRatios(double viewGlassToWallRatio, double daylightingGlassToWallRatio,\n    double desiredViewGlassSillHeight, double desiredDaylightingGlassHeaderHeight,\n    double exteriorShadingProjectionFactor, double interiorShelfProjectionFactor,\n    const Point3dVector& vertices, Point3dVector& viewVertices,\n    Point3dVector& daylightingVertices, Point3dVector& exteriorShadingVertices,\n    Point3dVector& interiorShelfVertices)\n  {\n    // check inputs for reasonableness\n    double totalWWR = viewGlassToWallRatio + daylightingGlassToWallRatio;\n    if (totalWWR == 0){\n      // requesting no glass? remove existing windows?\n      return false;\n    }else if (totalWWR < 0.0 || totalWWR >= 1.0){\n      return false;\n    }\n\n    boost::optional<double> grossArea = getArea(vertices);\n    if (!grossArea){\n      return false;\n    }\n\n    Transformation transformation = Transformation::alignFace(vertices);\n    Point3dVector faceVertices = transformation.inverse() * vertices;\n\n    if (faceVertices.empty()){\n      return false;\n    }\n\n    bool doViewGlass = (viewGlassToWallRatio > 0);\n    bool doDaylightGlass = (daylightingGlassToWallRatio > 0);\n    bool doExteriorShading = (doViewGlass && (exteriorShadingProjectionFactor > 0));\n    bool doInteriorShelf = (doDaylightGlass && (interiorShelfProjectionFactor > 0));\n    bool doViewAndDaylightGlass = (doViewGlass && doDaylightGlass);\n\n    // ignore these user arguments?\n    if (!doViewGlass){\n      desiredViewGlassSillHeight = 0.0;\n    }\n    if (!doDaylightGlass){\n      desiredDaylightingGlassHeaderHeight = 0.0;\n    }\n\n    // new coordinate system has z' in direction of outward normal, y' is up\n    double xmin = std::numeric_limits<double>::max();\n    double xmax = std::numeric_limits<double>::min();\n    double ymin = std::numeric_limits<double>::max();\n    double ymax = std::numeric_limits<double>::min();\n    for (const Point3d& faceVertex : faceVertices){\n      xmin = std::min(xmin, faceVertex.x());\n      xmax = std::max(xmax, faceVertex.x());\n      ymin = std::min(ymin, faceVertex.y());\n      ymax = std::max(ymax, faceVertex.y());\n    }\n    if ((xmin > xmax) || (ymin > ymax)){\n      return false;\n    }\n\n    double oneInch = 0.0254;\n\n    // DLM: preserve a 1\" gap between window and edge to keep SketchUp happy\n    double minGlassToEdgeDistance = oneInch;\n    double minViewToDaylightDistance = 0;\n    if (doViewAndDaylightGlass){\n      minViewToDaylightDistance = oneInch;\n    }\n\n    // wall parameters\n    double wallWidth = xmax - xmin;\n    double wallHeight = ymax - ymin;\n    double wallArea = wallWidth*wallHeight;\n\n    if (wallWidth < 2*minGlassToEdgeDistance){\n      return false;\n    }\n\n    if (wallHeight < 2*minGlassToEdgeDistance + minViewToDaylightDistance){\n      return false;\n    }\n\n    // check against actual surface area to ensure this is a rectangle?\n    if (std::abs(wallArea - grossArea.get()) > oneInch*oneInch){\n      return false;\n    }\n\n    double maxWindowArea = wallArea - 2*wallHeight*minGlassToEdgeDistance - (wallWidth-2*minGlassToEdgeDistance)*(2*minGlassToEdgeDistance + minViewToDaylightDistance);\n    double requestedViewArea = viewGlassToWallRatio*wallArea;\n    double requestedDaylightingArea = daylightingGlassToWallRatio*wallArea;\n    double requestedTotalWindowArea = totalWWR*wallArea;\n\n    if (requestedTotalWindowArea > maxWindowArea){\n      return false;\n    }\n\n    // view glass parameters\n    double viewMinX = 0;\n    double viewMinY = 0;\n    double viewWidth = 0;\n    double viewHeight = 0;\n\n    // daylighting glass parameters\n    double daylightingWidth = 0;\n    double daylightingHeight = 0;\n    double daylightingMinX = 0;\n    double daylightingMinY = 0;\n\n    // initial free parameters\n    double viewWidthInset = minGlassToEdgeDistance;\n    double viewSillHeight = std::max(desiredViewGlassSillHeight, minGlassToEdgeDistance);\n    double daylightingWidthInset = minGlassToEdgeDistance;\n    double daylightingHeaderHeight = std::max(desiredDaylightingGlassHeaderHeight, minGlassToEdgeDistance);\n\n    bool converged = false;\n    for (unsigned i = 0; i < 100; ++i){\n\n      // view glass parameters\n      viewMinX = viewWidthInset;\n      viewMinY = viewSillHeight;\n      viewWidth = wallWidth - 2*viewWidthInset;\n      viewHeight = requestedViewArea/viewWidth;\n\n      // daylighting glass parameters\n      daylightingWidth = wallWidth - 2*daylightingWidthInset;\n      daylightingHeight = requestedDaylightingArea/daylightingWidth;\n      daylightingMinX = viewWidthInset;\n      daylightingMinY = wallHeight - daylightingHeaderHeight - daylightingHeight;\n\n      if (viewMinY + viewHeight + minViewToDaylightDistance > daylightingMinY){\n        // windows overlap or exceed maximum size\n\n        if (doViewAndDaylightGlass){\n\n          // try shrinking vertical offsets\n          viewSillHeight = std::max(viewSillHeight - oneInch, minGlassToEdgeDistance);\n          daylightingHeaderHeight = std::max(daylightingHeaderHeight - oneInch, minGlassToEdgeDistance);\n\n        }else if (doViewGlass){\n\n          // solve directly\n          viewSillHeight = wallHeight - minGlassToEdgeDistance - viewHeight;\n\n          if (viewSillHeight < minGlassToEdgeDistance){\n            // cannot make window this large\n            return false;\n          }\n\n        }else if (doDaylightGlass){\n\n          // solve directly\n          daylightingHeaderHeight = wallHeight - minGlassToEdgeDistance - daylightingHeight;\n\n          if (daylightingHeaderHeight < minGlassToEdgeDistance){\n            // cannot make window this large\n            return false;\n          }\n\n        }\n\n      }else{\n\n        converged = true;\n        break;\n\n      }\n    }\n\n    if (!converged){\n      return false;\n    }\n\n    Point3dVector surfacePolygon;\n    for (const Point3d& point : faceVertices){\n      if (std::abs(point.z()) > 0.001){\n        LOG_FREE(Warn, \"utilities.geometry.applyViewAndDaylightingGlassRatios\", \"Surface point z not on plane, z =\" << point.z());\n      }\n      surfacePolygon.push_back(Point3d(point.x(),point.y(), 0.0));\n    }\n    std::reverse(surfacePolygon.begin(), surfacePolygon.end());\n\n    if (doViewGlass){\n      viewVertices.push_back(Point3d(viewMinX, viewMinY + viewHeight, 0));\n      viewVertices.push_back(Point3d(viewMinX, viewMinY, 0));\n      viewVertices.push_back(Point3d(viewMinX + viewWidth, viewMinY, 0));\n      viewVertices.push_back(Point3d(viewMinX + viewWidth, viewMinY + viewHeight, 0));\n\n      Point3dVector windowPolygon;\n      for (const Point3d& point : viewVertices){\n        if (std::abs(point.z()) > 0.001){\n          LOG_FREE(Warn, \"utilities.geometry.applyViewAndDaylightingGlassRatios\", \"Surface point z not on plane, z =\" << point.z());\n        }\n        windowPolygon.push_back(Point3d(point.x(),point.y(), 0.0));\n      }\n\n      // sub surface must be fully contained by base surface\n      for (const Point3d& point : windowPolygon){\n        if (!within(point, surfacePolygon, 0.001)){\n          std::cout << \"point: \" << point << std::endl;\n          std::cout << \"surfacePolygon: \" << surfacePolygon << std::endl;\n          LOG_FREE(Debug, \"utilities.geometry.applyViewAndDaylightingGlassRatios\", \"Surface does not fully contain SubSurface\");\n          return false;\n        }\n      }\n    }\n\n    if (doDaylightGlass){\n      daylightingVertices.push_back(Point3d(daylightingMinX, daylightingMinY + daylightingHeight, 0));\n      daylightingVertices.push_back(Point3d(daylightingMinX, daylightingMinY, 0));\n      daylightingVertices.push_back(Point3d(daylightingMinX + daylightingWidth, daylightingMinY, 0));\n      daylightingVertices.push_back(Point3d(daylightingMinX + daylightingWidth, daylightingMinY + daylightingHeight, 0));\n\n      Point3dVector windowPolygon;\n      for (const Point3d& point : daylightingVertices){\n        if (std::abs(point.z()) > 0.001){\n          LOG_FREE(Warn, \"utilities.geometry.applyViewAndDaylightingGlassRatios\", \"Surface point z not on plane, z =\" << point.z());\n        }\n        windowPolygon.push_back(Point3d(point.x(),point.y(), 0.0));\n      }\n\n      // sub surface must be fully contained by base surface\n      for (const Point3d& point : windowPolygon){\n        if (!within(point, surfacePolygon, 0.001)){\n          LOG_FREE(Debug, \"utilities.geometry.applyViewAndDaylightingGlassRatios\", \"Surface does not fully contain SubSurface\");\n          return false;\n        }\n      }\n    }\n\n    if (doExteriorShading) {\n      exteriorShadingVertices.push_back(Point3d(viewMinX, viewMinY + viewHeight, 0));\n      exteriorShadingVertices.push_back(Point3d(viewMinX, viewMinY + viewHeight, exteriorShadingProjectionFactor*viewHeight));\n      exteriorShadingVertices.push_back(Point3d(viewMinX + viewWidth, viewMinY + viewHeight, exteriorShadingProjectionFactor*viewHeight));\n      exteriorShadingVertices.push_back(Point3d(viewMinX + viewWidth, viewMinY + viewHeight, 0));\n    }\n\n    if (doInteriorShelf) {\n      interiorShelfVertices.push_back(Point3d(daylightingMinX + daylightingWidth, daylightingMinY, 0));\n      interiorShelfVertices.push_back(Point3d(daylightingMinX + daylightingWidth, daylightingMinY, -interiorShelfProjectionFactor*daylightingHeight));\n      interiorShelfVertices.push_back(Point3d(daylightingMinX, daylightingMinY, -interiorShelfProjectionFactor*daylightingHeight));\n      interiorShelfVertices.push_back(Point3d(daylightingMinX, daylightingMinY, 0));\n    }\n\n    // put all vertices back into input coordinate system\n    viewVertices = transformation*viewVertices;\n    daylightingVertices = transformation*daylightingVertices;\n    exteriorShadingVertices = transformation*exteriorShadingVertices;\n    interiorShelfVertices = transformation*interiorShelfVertices;\n\n    return true;\n  }\n\n} // openstudio\n", "meta": {"hexsha": "b4ceb68d0e9e304a0c6a06333fb0902594ad904e", "size": 28411, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openstudiocore/src/utilities/geometry/Geometry.cpp", "max_stars_repo_name": "hellok-coder/OS-Testing", "max_stars_repo_head_hexsha": "e9e18ad9e99f709a3f992601ed8d2e0662175af4", "max_stars_repo_licenses": ["blessing"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-12T02:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T02:07:03.000Z", "max_issues_repo_path": "openstudiocore/src/utilities/geometry/Geometry.cpp", "max_issues_repo_name": "hellok-coder/OS-Testing", "max_issues_repo_head_hexsha": "e9e18ad9e99f709a3f992601ed8d2e0662175af4", "max_issues_repo_licenses": ["blessing"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-02-04T23:30:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-04T23:30:45.000Z", "max_forks_repo_path": "openstudiocore/src/utilities/geometry/Geometry.cpp", "max_forks_repo_name": "hellok-coder/OS-Testing", "max_forks_repo_head_hexsha": "e9e18ad9e99f709a3f992601ed8d2e0662175af4", "max_forks_repo_licenses": ["blessing"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8450867052, "max_line_length": 168, "alphanum_fraction": 0.6292281159, "num_tokens": 7417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21654557728860435}}
{"text": "﻿#include \"BlocksEngine/pch.h\"\n#include \"BlocksEngine/Core/Math/Vector3.h\"\n\n#include <boost/container_hash/hash.hpp>\n\nusing namespace BlocksEngine;\nusing namespace DirectX;\n\n//------------------------------------------------------------------------------\n// Constructors\n//------------------------------------------------------------------------------\n\ntemplate <class T>\nVector3<T>::Vector3() noexcept\n    : Vector3Base<T>::Base{0, 0, 0}\n{\n}\n\ntemplate <class T>\nconstexpr Vector3<T>::Vector3(const T a) noexcept\n    : Vector3Base<T>::Base{a, a, a}\n{\n}\n\n/*template <class T>\nconstexpr Vector3<T>::Vector3(const T x, const T y, const T z) noexcept\n    : Vector3Base<T>::Base{x, y, z}\n{\n}*/\n\ntemplate <typename T>\nVector3<T>::Vector3(const physx::PxVec3& vec3) noexcept\n    : Vector3Base<T>::Base{\n        static_cast<float>(vec3.x),\n        static_cast<float>(vec3.y),\n        static_cast<float>(vec3.z)\n    }\n{\n}\n\ntemplate <typename T>\nVector3<T>::Vector3(const physx::PxExtendedVec3& vec3) noexcept\n    : Vector3Base<T>::Base{\n        static_cast<float>(vec3.x),\n        static_cast<float>(vec3.y),\n        static_cast<float>(vec3.z)\n    }\n{\n}\n\ntemplate <class T>\nVector3<T>::Vector3(_In_reads_(3) const T* pArray) noexcept\n    : Vector3Base<T>::Base{pArray}\n{\n}\n\ntemplate <class T>\nVector3<T>::Vector3(FXMVECTOR v) noexcept // NOLINT(cppcoreguidelines-pro-type-member-init)\n{\n    Store(this, v);\n}\n\ntemplate <class T>\nVector3<T>::Vector3(const typename Vector3Base<T>::Base& v) noexcept\n    : Vector3Base<T>::Base{v.x, v.y, v.z}\n{\n}\n\ntemplate <>\nVector3<float>::Vector3(const Vector3Base<float>::Vector& v) noexcept\n    : Vector3Base<float>::Base{v.f[0], v.f[1], v.f[2]}\n{\n}\n\ntemplate <>\nVector3<int32_t>::Vector3(const Vector3Base<int32_t>::Vector& v) noexcept\n    : Vector3Base<int32_t>::Base{v.i[0], v.i[1], v.i[2]}\n{\n}\n\ntemplate <>\nVector3<uint32_t>::Vector3(const Vector3Base<uint32_t>::Vector& v) noexcept\n    : Vector3Base<uint32_t>::Base{v.u[0], v.u[1], v.u[2]}\n{\n}\n\n//------------------------------------------------------------------------------\n// Converter operators\n//------------------------------------------------------------------------------\n\ntemplate <class T>\nVector3<T>::operator XMVECTOR() const noexcept\n{\n    return Load(this);\n}\n\n//------------------------------------------------------------------------------\n// Comparision operators\n//------------------------------------------------------------------------------\n\ntemplate <class T>\nbool Vector3<T>::operator==(const Vector3& v) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    return XMVector3Equal(v1, v2);\n}\n\ntemplate <class T>\nbool Vector3<T>::operator!=(const Vector3& v) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    return XMVector3NotEqual(v1, v2);\n}\n\n//------------------------------------------------------------------------------\n// Assignment operators\n//------------------------------------------------------------------------------\n\ntemplate <>\nVector3<float>& Vector3<float>::operator=(const Vector3Base<float>::Vector& v) noexcept\n{\n    this->x = v.f[0];\n    this->y = v.f[1];\n    this->z = v.f[2];\n\n    return *this;\n}\n\ntemplate <>\nVector3<int32_t>& Vector3<int32_t>::operator=(const Vector3Base<int32_t>::Vector& v) noexcept\n{\n    this->x = v.i[0];\n    this->y = v.i[1];\n    this->z = v.i[2];\n\n    return *this;\n}\n\ntemplate <>\nVector3<uint32_t>& Vector3<uint32_t>::operator=(const Vector3Base<uint32_t>::Vector& v) noexcept\n{\n    this->x = v.u[0];\n    this->y = v.u[1];\n    this->z = v.u[2];\n\n    return *this;\n}\n\ntemplate <class T>\nVector3<T>& Vector3<T>::operator/=(const float s) noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVectorScale(v1, 1.0f / s);\n    Store(this, x);\n\n    return *this;\n}\n\n//------------------------------------------------------------------------------\n// Unary operators\n//------------------------------------------------------------------------------\n\ntemplate <class T>\nVector3<T> Vector3<T>::operator+() const noexcept\n{\n    return *this;\n}\n\ntemplate <class T>\nVector3<T> Vector3<T>::operator-() const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVectorNegate(v1);\n\n    Vector3<T> r;\n    Store(&r, x);\n    return r;\n}\n\n//------------------------------------------------------------------------------\n// Hashing\n//------------------------------------------------------------------------------\n\ntemplate <class T>\nstd::size_t hash_value(const Vector3<T>& v)\n{\n    std::size_t seed = 0;\n    boost::hash_combine(seed, v.x);\n    boost::hash_combine(seed, v.y);\n    boost::hash_combine(seed, v.z);\n\n    return seed;\n}\n\n//------------------------------------------------------------------------------\n// Vector operations\n//------------------------------------------------------------------------------\n\ntemplate <class T>\ntemplate <class U>\nbool Vector3<T>::InBounds(const Vector3<U>& bounds) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&bounds);\n    return XMVector3InBounds(v1, v2);\n}\n\ntemplate <class T>\nfloat Vector3<T>::Length() const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVector3Length(v1);\n    return XMVectorGetX(x);\n}\n\ntemplate <class T>\nfloat Vector3<T>::LengthSquared() const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVector3LengthSq(v1);\n    return XMVectorGetX(x);\n}\n\ntemplate <class T>\ntemplate <class U>\nfloat Vector3<T>::Dot(const Vector3<U>& v) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    const XMVECTOR x = XMVector3Dot(v1, v2);\n    return XMVectorGetX(x);\n}\n\ntemplate <class T>\ntemplate <class U>\nvoid Vector3<T>::Cross(const Vector3<U>& v, Vector3<T>& result) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    const XMVECTOR x = XMVector3Cross(v1, v2);\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U>\nVector3<T> Vector3<T>::Cross(const Vector3<U>& v) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR v2 = Load(&v);\n    const XMVECTOR x = XMVector3Cross(v1, v2);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\nvoid Vector3<T>::Normalize() noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVector3Normalize(v1);\n    Store(this, x);\n}\n\ntemplate <class T>\ntemplate <class U>\nvoid Vector3<T>::Normalize(Vector3<U>& result) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVector3Normalize(v1);\n    Store(&result, x);\n}\n\n\n//------------------------------------------------------------------------------\n// Static functions\n//------------------------------------------------------------------------------\n\ntemplate <typename T>\nvoid Vector3<T>::Abs() noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVectorAbs(v1);\n    Store(this, x);\n}\n\ntemplate <typename T>\nvoid Vector3<T>::Abs(Vector3<T>& result) const noexcept\n{\n    const XMVECTOR v1 = Load(this);\n    const XMVECTOR x = XMVectorAbs(v1);\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nfloat Vector3<T>::Distance(const Vector3<U>& v1, const Vector3<V>& v2) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR v = XMVectorSubtract(x2, x1);\n    const XMVECTOR x = XMVector3Length(v);\n\n    return XMVectorGetX(x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nfloat Vector3<T>::DistanceSquared(const Vector3<U>& v1, const Vector3<V>& v2) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR v = XMVectorSubtract(x2, x1);\n    const XMVECTOR x = XMVector3LengthSq(v);\n    return XMVectorGetX(x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector3<T>::Min(const Vector3<U>& v1, const Vector3<V>& v2, Vector3<T>& result) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorMin(x1, x2);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nVector3<T> Vector3<T>::Min(const Vector3<U>& v1, const Vector3<V>& v2) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorMin(x2, x1);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector3<T>::Max(const Vector3<U>& v1, const Vector3<V>& v2, Vector3<T>& result) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorMax(x2, x1);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nVector3<T> Vector3<T>::Max(const Vector3<U>& v1, const Vector3<V>& v2) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorMax(x2, x1);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector3<T>::Lerp(const Vector3<U>& v1, const Vector3<V>& v2, const float t, Vector3<T>& result) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorLerp(x2, x1, t);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nVector3<T> Vector3<T>::Lerp(const Vector3<U>& v1, const Vector3<V>& v2, const float t) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorLerp(x2, x1, t);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector3<T>::SmoothStep(const Vector3<U>& v1, const Vector3<V>& v2, float t, Vector3<T>& result) noexcept\n{\n    t = t > 1.0f ? 1.0f : t < 0.0f ? 0.0f : t; // Clamp value between 0 and 1\n    t = t * t * (3.0f - 2.0f * t);\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorLerp(x1, x2, t);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nVector3<T> Vector3<T>::SmoothStep(const Vector3<U>& v1, const Vector3<V>& v2, float t) noexcept\n{\n    t = t > 1.0f ? 1.0f : t < 0.0f ? 0.0f : t; // Clamp value between 0 and 1\n    t = t * t * (3.0f - 2.0f * t);\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x = XMVectorLerp(x1, x2, t);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V, class W>\nvoid Vector3<T>::Barycentric(const Vector3<U>& v1, const Vector3<V>& v2, const Vector3<W>& v3, const float f,\n                             const float g, Vector3<T>& result) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x3 = Load(&v3);\n    const XMVECTOR x = XMVectorBaryCentric(x1, x2, x3, f, g);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V, class W>\nVector3<T> Vector3<T>::Barycentric(const Vector3<U>& v1, const Vector3<V>& v2, const Vector3<W>& v3,\n                                   const float f, const float g) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x3 = Load(&v3);\n    const XMVECTOR x = XMVectorBaryCentric(x1, x2, x3, f, g);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V, class W, class X>\nvoid Vector3<T>::CatmullRom(const Vector3<U>& v1, const Vector3<V>& v2, const Vector3<W>& v3, const Vector3<X>& v4,\n                            const float t, Vector3<T>& result) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x3 = Load(&v3);\n    const XMVECTOR x4 = Load(&v4);\n    const XMVECTOR x = XMVectorCatmullRom(x1, x2, x3, x4, t);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V, class W, class X>\nVector3<T> Vector3<T>::CatmullRom(const Vector3<U>& v1, const Vector3<V>& v2, const Vector3<W>& v3,\n                                  const Vector3<X>& v4, const float t) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&v2);\n    const XMVECTOR x3 = Load(&v3);\n    const XMVECTOR x4 = Load(&v4);\n    const XMVECTOR x = XMVectorCatmullRom(x1, x2, x3, x4, t);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V, class W, class X>\nvoid Vector3<T>::Hermite(const Vector3<U>& v1, const Vector3<V>& t1, const Vector3<W>& v2, const Vector3<X>& t2,\n                         const float t, Vector3<T>& result) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&t1);\n    const XMVECTOR x3 = Load(&v2);\n    const XMVECTOR x4 = Load(&t2);\n    const XMVECTOR x = XMVectorHermite(x1, x2, x3, x4, t);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V, class W, class X>\nVector3<T> Vector3<T>::Hermite(const Vector3<U>& v1, const Vector3<V>& t1, const Vector3<W>& v2,\n                               const Vector3<X>& t2, const float t) noexcept\n{\n    const XMVECTOR x1 = Load(&v1);\n    const XMVECTOR x2 = Load(&t1);\n    const XMVECTOR x3 = Load(&v2);\n    const XMVECTOR x4 = Load(&t2);\n    const XMVECTOR x = XMVectorHermite(x1, x2, x3, x4, t);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector3<T>::Reflect(const Vector3<U>& iVec, const Vector3<V>& nVec, Vector3<T>& result) noexcept\n{\n    const XMVECTOR x1 = Load(&iVec);\n    const XMVECTOR x2 = Load(&nVec);\n    const XMVECTOR x = XMVector3Reflect(x1, x2);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nVector3<T> Vector3<T>::Reflect(const Vector3<U>& iVec, const Vector3<V>& nVec) noexcept\n{\n    const XMVECTOR x1 = Load(&iVec);\n    const XMVECTOR x2 = Load(&nVec);\n    const XMVECTOR x = XMVector3Reflect(x1, x2);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nvoid Vector3<T>::Refract(const Vector3<U>& iVec, const Vector3<V>& nVec, const float refractionIndex,\n                         Vector3<T>& result) noexcept\n{\n    const XMVECTOR x1 = Load(&iVec);\n    const XMVECTOR x2 = Load(&nVec);\n    const XMVECTOR x = XMVector3Refract(x1, x2, refractionIndex);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U, class V>\nVector3<T> Vector3<T>::Refract(const Vector3<U>& iVec, const Vector3<V>& nVec,\n                               const float refractionIndex) noexcept\n{\n    const XMVECTOR x1 = Load(&iVec);\n    const XMVECTOR x2 = Load(&nVec);\n    const XMVECTOR x = XMVector3Refract(x1, x2, refractionIndex);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\n\ntemplate <class T>\ntemplate <class U>\n_Use_decl_annotations_\n\nvoid Vector3<T>::Transform(const Vector3<U>* varray, const size_t count, const Matrix& m,\n                           Vector3<T>* resultArray) noexcept\n{\n    const XMMATRIX m1 = XMLoadFloat4x4(&m);\n    XMVector3TransformCoordStream(resultArray, sizeof Vector3Base<U>::Vector, varray, sizeof Vector3Base<T>::Vector,\n                                  count, m1);\n}\n\ntemplate <class T>\ntemplate <class U>\nvoid Vector3<T>::TransformNormal(const Vector3<U>& v, const Matrix& m, Vector3<T>& result) noexcept\n{\n    const XMVECTOR v1 = Load(&v);\n    const XMMATRIX m1 = XMLoadFloat4x4(&m);\n    const XMVECTOR x = XMVector3TransformNormal(v1, m1);\n\n    Store(&result, x);\n}\n\ntemplate <class T>\ntemplate <class U>\nVector3<T> Vector3<T>::TransformNormal(const Vector3<U>& v, const Matrix& m) noexcept\n{\n    const XMVECTOR v1 = Load(&v);\n    const XMMATRIX m1 = XMLoadFloat4x4(&m);\n    const XMVECTOR x = XMVector3TransformNormal(v1, m1);\n\n    Vector3<T> result;\n    Store(&result, x);\n    return result;\n}\n\ntemplate <class T>\ntemplate <class U>\n_Use_decl_annotations_\n\nvoid Vector3<T>::TransformNormal(const Vector3<U>* varray, const size_t count, const Matrix& m,\n                                 Vector3<T>* resultArray) noexcept\n{\n    const XMMATRIX m1 = XMLoadFloat4x4(&m);\n    XMVector3TransformNormalStream(resultArray, sizeof Vector3Base<U>::Vector, varray, sizeof Vector3Base<T>::Vector,\n                                   count, m1);\n}\n\ntemplate struct Vector3<float>;\ntemplate struct Vector3<int32_t>;\ntemplate struct Vector3<uint32_t>;\n", "meta": {"hexsha": "750929f5c58584d6c48f885cfcbeaf8f8eb76671", "size": 16380, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BlocksEngine/src/Core/Math/Vector3.cpp", "max_stars_repo_name": "jorgeparavicini/Blocks", "max_stars_repo_head_hexsha": "dd1654d5643ca3707d39ae6ef21667e9b72130ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BlocksEngine/src/Core/Math/Vector3.cpp", "max_issues_repo_name": "jorgeparavicini/Blocks", "max_issues_repo_head_hexsha": "dd1654d5643ca3707d39ae6ef21667e9b72130ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2022-01-02T10:10:49.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T10:25:53.000Z", "max_forks_repo_path": "BlocksEngine/src/Core/Math/Vector3.cpp", "max_forks_repo_name": "jorgeparavicini/Blocks", "max_forks_repo_head_hexsha": "dd1654d5643ca3707d39ae6ef21667e9b72130ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8524590164, "max_line_length": 117, "alphanum_fraction": 0.5943833944, "num_tokens": 4602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.21649116269402044}}
{"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file   Utility_InterpolationPolicy_def.hpp\n//! \\author Alex Robinson\n//! \\brief  Interpolation policy struct definitions\n//!\n//---------------------------------------------------------------------------//\n\n#ifndef UTILITY_INTERPOLATION_POLICY_DEF_HPP\n#define UTILITY_INTERPOLATION_POLICY_DEF_HPP\n\n// Std Lib Includes\n#include <cmath>\n\n// Boost Includes\n#include <boost/mpl/or.hpp>\n\n// FRENSIE Includes\n#include \"Utility_QuantityTraits.hpp\"\n#include \"Utility_IsFloatingPoint.hpp\"\n#include \"Utility_DesignByContract.hpp\"\n\nnamespace Utility{\n\n// Interpolate between two processed points\ntemplate<typename ParentInterpolationType>\ntemplate<typename T>\nT InterpolationHelper<ParentInterpolationType>::interpolate(\n                                                 const T processed_indep_var_0,\n                                                 const T processed_indep_var,\n                                                 const T processed_dep_var_0,\n                                                 const T processed_slope )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (std::is_floating_point<T>::value) );\n  // Make sure the processed independent variables are valid\n  testPrecondition( !Utility::QuantityTraits<T>::isnaninf(\n\t\t\t\t\t\t     processed_indep_var_0 ) );\n  testPrecondition( !Utility::QuantityTraits<T>::isnaninf(\n\t\t\t\t\t\t       processed_indep_var ) );\n  testPrecondition( processed_indep_var_0 <= processed_indep_var );\n  // Make sure the processed dependent variable is valid\n  testPrecondition( !Utility::QuantityTraits<T>::isnaninf(\n\t\t\t\t\t\t       processed_dep_var_0 ) );\n  // Make sure that the slope is valid\n  testPrecondition( !Utility::QuantityTraits<T>::isnaninf( processed_slope ) );\n\n  return ParentInterpolationType::recoverProcessedDepVar(\n               processed_dep_var_0 +\n               processed_slope*(processed_indep_var - processed_indep_var_0) );\n}\n\n// Interpolate between two processed points and return the processed value\ntemplate<typename ParentInterpolationType>\ntemplate<typename T>\nT InterpolationHelper<ParentInterpolationType>::interpolateAndProcess(\n                                                 const T processed_indep_var_0,\n                                                 const T processed_indep_var,\n                                                 const T processed_dep_var_0,\n                                                 const T processed_slope )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (std::is_floating_point<T>::value) );\n  // Make sure the processed independent variables are valid\n  testPrecondition( !Utility::QuantityTraits<T>::isnaninf(\n\t\t\t\t\t\t     processed_indep_var_0 ) );\n  testPrecondition( !Utility::QuantityTraits<T>::isnaninf(\n\t\t\t\t\t\t       processed_indep_var ) );\n  testPrecondition( processed_indep_var_0 <= processed_indep_var );\n  // Make sure the processed dependent variable is valid\n  testPrecondition( !Utility::QuantityTraits<T>::isnaninf(\n\t\t\t\t\t\t       processed_dep_var_0 ) );\n  // Make sure that the slope is valid\n  testPrecondition( !Utility::QuantityTraits<T>::isnaninf( processed_slope ) );\n\n  return processed_dep_var_0 +\n    processed_slope*(processed_indep_var - processed_indep_var_0);\n}\n\n// Calculate the unit base grid length (L)\n/*! \\details For LinLog and LogLog interpolation types the grid length\n * that is calculated is not a traditional length. It is the distance between\n * the processed upper independent value and the processed lower\n * independent value. This is why any units associated with the independent\n * grid limits are stripped away.\n */\ntemplate<typename ParentInterpolationType>\ntemplate<typename IndepType>\ninline typename QuantityTraits<IndepType>::RawType\nInterpolationHelper<ParentInterpolationType>::calculateUnitBaseGridLength(\n                                       const IndepType grid_lower_indep_value,\n                                       const IndepType grid_upper_indep_value )\n{\n  // Make sure the grid is valid\n  testPrecondition( grid_lower_indep_value <= grid_upper_indep_value );\n  testPrecondition( ParentInterpolationType::isIndepVarInValidRange(\n                                                    grid_lower_indep_value ) );\n\n  return ThisType::calculateUnitBaseGridLengthProcessed(\n          ParentInterpolationType::processIndepVar( grid_lower_indep_value ),\n          ParentInterpolationType::processIndepVar( grid_upper_indep_value ) );\n}\n\n// Calculate the unit base grid length from a processed grid (L)\n/*! \\details For LinLog and LogLog interpolation types the grid length\n * that is calculated is not a traditional length. It is the distance between\n * the processed upper independent value and the processed lower\n * independent value. This is why any units associated with the independent\n * grid limits are stripped away. Due to conversion of the independent\n * values from a cosine (mu) to a delta cosine ( 1 - mu ) + nudge for LogLogCos\n * and LinLogCos, it is assumed the processed grids are inverted to ensure they\n * are in ascending order.\n */\ntemplate<typename ParentInterpolationType>\ntemplate<typename T>\ninline T InterpolationHelper<ParentInterpolationType>::calculateUnitBaseGridLengthProcessed(\n                                     const T processed_grid_lower_indep_value,\n                                     const T processed_grid_upper_indep_value )\n{\n  // Make sure the grid is valid\n  testPrecondition( processed_grid_lower_indep_value <=\n                    processed_grid_upper_indep_value );\n\n  const T processed_grid_length =\n    processed_grid_upper_indep_value - processed_grid_lower_indep_value;\n\n  // Make sure the grid length is valid\n  testPrecondition( processed_grid_length >= 0.0 );\n\n  return processed_grid_length;\n}\n\n// Calculate the unit base independent variable (eta)\n/*! \\details The independent grid length is calculated using the\n * processed independent grid limits. It has been found that a tolerance of\n * 1e-3 works best for most applications.\n */\ntemplate<typename ParentInterpolationType>\ntemplate<typename IndepType>\ninline typename QuantityTraits<IndepType>::RawType\nInterpolationHelper<ParentInterpolationType>::calculateUnitBaseIndepVar(\n          const IndepType indep_var,\n          const IndepType indep_var_min,\n          const typename QuantityTraits<IndepType>::RawType indep_grid_length,\n          const double tol )\n{\n  // Make sure the intermediate grid min indep var is valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_min ) );\n  testPrecondition( ParentInterpolationType::isIndepVarInValidRange( indep_var_min ) );\n  // Make sure the intermediate grid length is valid\n  testPrecondition( !QuantityTraits<typename QuantityTraits<IndepType>::RawType>::isnaninf( indep_grid_length ) );\n  testPrecondition( indep_grid_length > 0.0 );\n  // Make sure the independent variable is valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( ParentInterpolationType::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var >=\n                    ThisType::calculateFuzzyLowerBound( indep_var_min, tol ) );\n  remember( typename QuantityTraits<IndepType>::RawType test_difference =\n            ParentInterpolationType::processIndepVar(indep_var) -\n            ParentInterpolationType::processIndepVar(indep_var_min) );\n\n  testPrecondition( test_difference <= ThisType::calculateFuzzyUpperBound(\n                                                    indep_grid_length, tol ) );\n\n  return calculateUnitBaseIndepVarProcessed(\n                       ParentInterpolationType::processIndepVar(indep_var),\n                       ParentInterpolationType::processIndepVar(indep_var_min),\n                       indep_grid_length,\n                       tol );\n}\n\n// Calculate the unit base independent variable (eta)\n/*! \\details It has been found that a tolerance of 1e-3 works best for most\n * applications.\n */\ntemplate<typename ParentInterpolationType>\ntemplate<typename T>\ninline T InterpolationHelper<ParentInterpolationType>::calculateUnitBaseIndepVarProcessed(\n                                               const T processed_indep_var,\n                                               const T processed_indep_var_min,\n                                               const T indep_grid_length,\n                                               const double tol )\n{\n  // Make sure the intermediate grid min indep var is valid\n  testPrecondition( !QuantityTraits<T>::isnaninf( processed_indep_var_min ) );\n  // Make sure the independent y variable is valid\n  testPrecondition( !QuantityTraits<T>::isnaninf(processed_indep_var) );\n  testPrecondition( processed_indep_var >= ThisType::calculateFuzzyLowerBound(\n                                              processed_indep_var_min, tol ) );\n  remember( T test_difference = processed_indep_var - processed_indep_var_min);\n  testPrecondition( test_difference <= ThisType::calculateFuzzyUpperBound(\n                                                    indep_grid_length, tol ) );\n  // Make sure the intermediate grid length is valid\n  testPrecondition( !QuantityTraits<T>::isnaninf( indep_grid_length ) );\n  testPrecondition( indep_grid_length > 0.0 );\n\n  T eta = (processed_indep_var - processed_indep_var_min)/indep_grid_length;\n\n  // Check for rounding errors and correct\n  if( eta > 1.0 )\n  {\n    if( eta - 1.0 < tol )\n      eta = 1.0;\n  }\n  else if( eta < 0.0 )\n  {\n    if( eta > -tol )\n      eta = 0.0;\n  }\n\n  // Make sure eta is valid\n  testPostcondition( eta >= 0.0 );\n  testPostcondition( eta <= 1.0 );\n\n  return eta;\n}\n\n// Calculate the independent variable (from eta)\n/*! \\details It has been found that a tolerance of 1e-3 works best for most\n * applications.\n */\ntemplate<typename ParentInterpolationType>\ntemplate<typename IndepType>\ninline IndepType\nInterpolationHelper<ParentInterpolationType>::calculateIndepVar(\n          const typename QuantityTraits<IndepType>::RawType eta,\n          const IndepType indep_var_min,\n          const typename QuantityTraits<IndepType>::RawType indep_grid_length,\n          const double tol )\n{\n  // Make sure the eta value is valid\n  testPrecondition( eta >= 0.0 );\n  testPrecondition( eta <= 1.0 );\n  // Make sure the grid min indep var is valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_min ) );\n  testPrecondition( ParentInterpolationType::isIndepVarInValidRange( indep_var_min ) );\n  // Make sure the grid length is valid\n  testPrecondition( !QuantityTraits<typename QuantityTraits<IndepType>::RawType>::isnaninf( indep_grid_length ) );\n  testPrecondition( indep_grid_length >= 0.0 );\n\n  IndepType grid_indep_var( QuantityTraits<IndepType>::initializeQuantity(\n    ParentInterpolationType::recoverProcessedIndepVar(\n                    ParentInterpolationType::processIndepVar( indep_var_min ) +\n                    indep_grid_length*eta ) ) );\n\n  // Check for rounding errors\n  if( grid_indep_var < indep_var_min &&\n      grid_indep_var >= ThisType::calculateFuzzyLowerBound(indep_var_min, tol))\n    grid_indep_var = indep_var_min;\n\n  // Make sure the calculated independent variable is valid\n  testPostcondition( grid_indep_var >= indep_var_min );\n\n  return grid_indep_var;\n}\n\n// Calculate the processed independent variable (from eta)\n/*! \\details A tolerance is not required with this method because no variable\n * processing is done. Due to conversion of the independent values from a cosine\n * (mu) to a delta cosine ( 1 - mu ) + nudge for LogLogCos and LinLogCos, it is\n * assumed the processed grids are inverted to ensure they are in ascending\n * order.\n */\ntemplate<typename ParentInterpolationType>\ntemplate<typename T>\ninline T InterpolationHelper<ParentInterpolationType>::calculateProcessedIndepVar(\n                                               const T eta,\n                                               const T processed_indep_var_min,\n                                               const T indep_grid_length )\n{\n  // Make sure the eta value is valid\n  testPrecondition( eta >= 0.0 );\n  testPrecondition( eta <= 1.0 );\n  // Make sure the grid min indep var is valid\n  testPrecondition( !QuantityTraits<T>::isnaninf( processed_indep_var_min ) );\n  // Make sure the grid length is valid\n  testPrecondition( !QuantityTraits<T>::isnaninf( indep_grid_length ) );\n  testPrecondition( indep_grid_length >= 0.0 );\n\n  return processed_indep_var_min + indep_grid_length*eta;\n}\n\n// Calculate the \"fuzzy\" lower bound (lower bound with roundoff tolerance)\n/*! \\details It has been found that a tolerance of 1e-3 works best for most\n * applications.\n */\ntemplate<typename ParentInterpolationType>\ntemplate<typename T>\ninline T InterpolationHelper<ParentInterpolationType>::calculateFuzzyLowerBound(\n                                                             const T value,\n                                                             const double tol )\n{\n  if( value < QuantityTraits<T>::zero() )\n    return value*(1+tol);\n  else\n    return value*(1-tol);\n}\n\n// Calculate the \"fuzzy\" upper bound (upper bound with roundoff tolerance)\n/*! \\details It has been found that a tolerance of 1e-3 works best for most\n * applications\n */\ntemplate<typename ParentInterpolationType>\ntemplate<typename T>\ninline T InterpolationHelper<ParentInterpolationType>::calculateFuzzyUpperBound(\n                                                             const T value,\n                                                             const double tol )\n{\n  if( value > QuantityTraits<T>::zero() )\n    return value*(1+tol);\n  else\n    return value*(1-tol);\n}\n\n// The name of the policy\ntemplate<typename ParentInterpolationType>\ninline std::string InterpolationHelper<ParentInterpolationType>::name()\n{\n  return Utility::typeName<ParentInterpolationType>();\n}\n\n// Get the interpolation type\ninline InterpolationType LogLog::getInterpolationType()\n{\n  return LOGLOG_INTERPOLATION;\n}\n\n// Interpolate between two points\ntemplate<typename IndepType, typename DepType>\ninline DepType LogLog::interpolate( const IndepType indep_var_0,\n\t\t\t\t    const IndepType indep_var_1,\n\t\t\t\t    const IndepType indep_var,\n\t\t\t\t    const DepType dep_var_0,\n\t\t\t\t    const DepType dep_var_1 )\n{\n  // The IndepType must be a floating point type\n  testStaticPrecondition( (Utility::IsFloatingPoint<IndepType>::value) );\n  testStaticPrecondition( (Utility::IsFloatingPoint<DepType>::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var_1 ) );\n\n  return dep_var_0*\n    pow((dep_var_1/dep_var_0),\n\tlog(indep_var/indep_var_0)/log(indep_var_1/indep_var_0));\n}\n\n// Interpolate between two points using the indep variable ratio (beta)\ntemplate<typename T, typename DepType>\ninline DepType LogLog::interpolate( const T beta,\n                                    const DepType dep_var_0,\n                                    const DepType dep_var_1 )\n{\n  // The IndepType must be a floating point type\n  testStaticPrecondition( (std::is_floating_point<typename QuantityTraits<T>::RawType>::value) );\n  testStaticPrecondition( (std::is_floating_point<typename QuantityTraits<DepType>::RawType>::value ) );\n  // Make sure the independent variables are valid\n  testPrecondition( beta >= QuantityTraits<T>::zero() );\n  testPrecondition( beta <= QuantityTraits<T>::one() );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var_1 ) );\n\n  return dep_var_0*pow((dep_var_1/dep_var_0),beta);\n}\n\n// Interpolate between two points and return the processed value\ntemplate<typename IndepType, typename DepType>\ninline typename QuantityTraits<DepType>::RawType\nLogLog::interpolateAndProcess( const IndepType indep_var_0,\n\t\t\t       const IndepType indep_var_1,\n\t\t\t       const IndepType indep_var,\n\t\t\t       const DepType dep_var_0,\n\t\t\t       const DepType dep_var_1 )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (Utility::IsFloatingPoint<IndepType>::value) );\n  testStaticPrecondition( (Utility::IsFloatingPoint<DepType>::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var_1 ) );\n\n  return log( getRawQuantity(dep_var_0) ) + log ( dep_var_1/dep_var_0 )*\n    log( indep_var/indep_var_0 )/log( indep_var_1/indep_var_0 );\n}\n\n// Process the independent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType\nLogLog::processIndepVar( const T indep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LogLog::isIndepVarInValidRange( indep_var ) );\n\n  return log( getRawQuantity(indep_var) );\n}\n\n// Process the dependent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType\nLogLog::processDepVar( const T dep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LogLog::isDepVarInValidRange( dep_var ) );\n\n  return log( getRawQuantity(dep_var) );\n}\n\n// Recover the processed independent value\ntemplate<typename T>\ninline T LogLog::recoverProcessedIndepVar( const T processed_indep_var )\n{\n  return exp( processed_indep_var );\n}\n\n// Recover the processed dependent value\ntemplate<typename T>\ninline T LogLog::recoverProcessedDepVar( const T processed_dep_var )\n{\n  return exp( processed_dep_var );\n}\n\n// Test if the independent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LogLog::isIndepVarInValidRange( const T indep_var )\n{\n  return indep_var > QuantityTraits<T>::zero();\n}\n\n// Test if the dependent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LogLog::isDepVarInValidRange( const T dep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( dep_var ) );\n\n  return dep_var > QuantityTraits<T>::zero();\n}\n\n// Get the interpolation type\ninline InterpolationType LogLin::getInterpolationType()\n{\n  return LOGLIN_INTERPOLATION;\n}\n\n// Interpolate between two points\ntemplate<typename IndepType, typename DepType>\ninline DepType LogLin::interpolate( const IndepType indep_var_0,\n\t\t\t\t    const IndepType indep_var_1,\n\t\t\t\t    const IndepType indep_var,\n\t\t\t\t    const DepType dep_var_0,\n\t\t\t\t    const DepType dep_var_1 )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (Utility::IsFloatingPoint<IndepType>::value) );\n  testStaticPrecondition( (Utility::IsFloatingPoint<DepType>::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var_1 ) );\n\n  return dep_var_0*pow((dep_var_1/dep_var_0), (indep_var-indep_var_0)/(indep_var_1-indep_var_0));\n}\n\n// Interpolate between two points using the indep variable ratio (beta)\ntemplate<typename T, typename DepType>\ninline DepType LogLin::interpolate( const T beta,\n                                    const DepType dep_var_0,\n                                    const DepType dep_var_1 )\n{\n  // The IndepType must be a floating point type\n  testStaticPrecondition( (std::is_floating_point<typename QuantityTraits<T>::RawType>::value) );\n  testStaticPrecondition( (std::is_floating_point<typename QuantityTraits<DepType>::RawType>::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( beta >= QuantityTraits<T>::zero() );\n  testPrecondition( beta <= QuantityTraits<T>::one() );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var_1 ) );\n\n  return dep_var_0*pow((dep_var_1/dep_var_0),beta);\n}\n\n// Interpolate between two points and return the processed value\ntemplate<typename IndepType, typename DepType>\ninline typename QuantityTraits<DepType>::RawType\nLogLin::interpolateAndProcess( const IndepType indep_var_0,\n\t\t\t       const IndepType indep_var_1,\n\t\t\t       const IndepType indep_var,\n\t\t\t       const DepType dep_var_0,\n\t\t\t       const DepType dep_var_1 )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (Utility::IsFloatingPoint<IndepType>::value) );\n  testStaticPrecondition( (Utility::IsFloatingPoint<DepType>::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var_1 ) );\n\n  return log( getRawQuantity(dep_var_0) ) + log( dep_var_1/dep_var_0 )*\n    (indep_var-indep_var_0)/(indep_var_1-indep_var_0);\n}\n\n// Process the independent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType\nLogLin::processIndepVar( const T indep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LogLin::isIndepVarInValidRange( indep_var ) );\n\n  return getRawQuantity(indep_var);\n}\n\n// Process the dependent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType\nLogLin::processDepVar( const T dep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LogLin::isDepVarInValidRange( dep_var ) );\n\n  return log( getRawQuantity(dep_var) );\n}\n\n// Recover the processed independent value\ntemplate<typename T>\ninline T LogLin::recoverProcessedIndepVar( const T processed_indep_var )\n{\n  return processed_indep_var;\n}\n\n// Recover the processed dependent value\ntemplate<typename T>\ninline T LogLin::recoverProcessedDepVar( const T processed_dep_var )\n{\n  return exp( processed_dep_var );\n}\n\n// Test if the independent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LogLin::isIndepVarInValidRange( const T indep_var )\n{\n  return true;\n}\n\n// Test if the dependent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LogLin::isDepVarInValidRange( const T dep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( dep_var ) );\n\n  return dep_var > QuantityTraits<T>::zero();\n}\n\n// Get the interpolation type\ninline InterpolationType LinLog::getInterpolationType()\n{\n  return LINLOG_INTERPOLATION;\n}\n\n// Interpolate between two points\ntemplate<typename IndepType, typename DepType>\ninline DepType LinLog::interpolate( const IndepType indep_var_0,\n\t\t\t\t    const IndepType indep_var_1,\n\t\t\t\t    const IndepType indep_var,\n\t\t\t\t    const DepType dep_var_0,\n\t\t\t\t    const DepType dep_var_1 )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (Utility::IsFloatingPoint<IndepType>::value) );\n  testStaticPrecondition( (Utility::IsFloatingPoint<DepType>::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LinLog::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LinLog::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LinLog::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LinLog::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LinLog::isDepVarInValidRange( dep_var_1 ) );\n\n  DepType term_2( (dep_var_1 - dep_var_0)*log(indep_var/indep_var_0)/\n\t\t  log(indep_var_1/indep_var_0) );\n\n  return dep_var_0 + term_2;\n}\n\n// Interpolate between two points using the indep variable ratio (beta)\ntemplate<typename T, typename DepType>\ninline DepType LinLog::interpolate( const T beta,\n                                    const DepType dep_var_0,\n                                    const DepType dep_var_1 )\n{\n  // The IndepType must be a floating point type\n  testStaticPrecondition( (std::is_floating_point<typename QuantityTraits<T>::RawType>::value) );\n  testStaticPrecondition( (std::is_floating_point<typename QuantityTraits<DepType>::RawType>::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( beta >= QuantityTraits<T>::zero() );\n  testPrecondition( beta <= QuantityTraits<T>::one() );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LinLog::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LinLog::isDepVarInValidRange( dep_var_1 ) );\n\n  return dep_var_0 + (dep_var_1 - dep_var_0)*beta;\n}\n\n// Interpolate between two points and return the processed value\ntemplate<typename IndepType, typename DepType>\ninline typename QuantityTraits<DepType>::RawType\nLinLog::interpolateAndProcess( const IndepType indep_var_0,\n\t\t\t       const IndepType indep_var_1,\n\t\t\t       const IndepType indep_var,\n\t\t\t       const DepType dep_var_0,\n\t\t\t       const DepType dep_var_1 )\n{\n  return getRawQuantity( interpolate( indep_var_0,\n\t\t\t\t      indep_var_1,\n\t\t\t\t      indep_var,\n\t\t\t\t      dep_var_0,\n\t\t\t\t      dep_var_1 ) );\n}\n\n// Process the independent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType\nLinLog::processIndepVar( const T indep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LinLog::isIndepVarInValidRange( indep_var ) );\n\n  return log( getRawQuantity(indep_var) );\n}\n\n// Process the dependent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType\nLinLog::processDepVar( const T dep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LinLog::isDepVarInValidRange( dep_var ) );\n\n  return getRawQuantity(dep_var);\n}\n\n// Recover the processed independent value\ntemplate<typename T>\ninline T LinLog::recoverProcessedIndepVar( const T processed_indep_var )\n{\n  return exp( processed_indep_var );\n}\n\n// Recover the processed dependent value\ntemplate<typename T>\ninline T LinLog::recoverProcessedDepVar( const T processed_dep_var )\n{\n  return processed_dep_var;\n}\n\n// Test if the independent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LinLog::isIndepVarInValidRange( const T indep_var )\n{\n  return indep_var > QuantityTraits<T>::zero();\n}\n\n// Test if the dependent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LinLog::isDepVarInValidRange( const T dep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( dep_var ) );\n\n  return true;\n}\n\n// Get the interpolation type\ninline InterpolationType LinLin::getInterpolationType()\n{\n  return LINLIN_INTERPOLATION;\n}\n\n// Interpolate between two points\ntemplate<typename IndepType, typename DepType>\ninline DepType LinLin::interpolate( const IndepType indep_var_0,\n\t\t\t\t    const IndepType indep_var_1,\n\t\t\t\t    const IndepType indep_var,\n\t\t\t\t    const DepType dep_var_0,\n\t\t\t\t    const DepType dep_var_1 )\n{\n  // T must be a floating point type\n  testStaticPrecondition( (Utility::IsFloatingPoint<IndepType>::value) );\n  testStaticPrecondition( (Utility::IsFloatingPoint<DepType>::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_0 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var_1 ) );\n  testPrecondition( !QuantityTraits<IndepType>::isnaninf( indep_var ) );\n  testPrecondition( LinLin::isIndepVarInValidRange( indep_var_0 ) );\n  testPrecondition( LinLin::isIndepVarInValidRange( indep_var_1 ) );\n  testPrecondition( LinLin::isIndepVarInValidRange( indep_var ) );\n  testPrecondition( indep_var_0 < indep_var_1 );\n  testPrecondition( indep_var >= indep_var_0 );\n  testPrecondition( indep_var <= indep_var_1 );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LinLin::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LinLin::isDepVarInValidRange( dep_var_1 ) );\n\n  DepType term_2( (dep_var_1 - dep_var_0)/(indep_var_1 - indep_var_0)*\n\t\t  (indep_var - indep_var_0) );\n\n  return dep_var_0 + term_2;\n}\n\n// Interpolate between two points using the indep variable ratio (beta)\ntemplate<typename T, typename DepType>\ninline DepType LinLin::interpolate( const T beta,\n                                    const DepType dep_var_0,\n                                    const DepType dep_var_1 )\n{\n  // The IndepType must be a floating point type\n  testStaticPrecondition( (std::is_floating_point<typename QuantityTraits<T>::RawType>::value) );\n  testStaticPrecondition( (std::is_floating_point<typename QuantityTraits<DepType>::RawType>::value) );\n  // Make sure the independent variables are valid\n  testPrecondition( beta >= QuantityTraits<T>::zero() );\n  testPrecondition( beta <= QuantityTraits<T>::one() );\n  // Make sure the dependent variables are valid\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_0 ) );\n  testPrecondition( !QuantityTraits<DepType>::isnaninf( dep_var_1 ) );\n  testPrecondition( LinLin::isDepVarInValidRange( dep_var_0 ) );\n  testPrecondition( LinLin::isDepVarInValidRange( dep_var_1 ) );\n\n  return dep_var_0 + (dep_var_1 - dep_var_0)*beta;\n}\n\n// Interpolate between two points and return the processed value\ntemplate<typename IndepType, typename DepType>\ninline typename QuantityTraits<DepType>::RawType\nLinLin::interpolateAndProcess( const IndepType indep_var_0,\n\t\t\t       const IndepType indep_var_1,\n\t\t\t       const IndepType indep_var,\n\t\t\t       const DepType dep_var_0,\n\t\t\t       const DepType dep_var_1 )\n{\n  return getRawQuantity( interpolate( indep_var_0,\n\t\t\t\t      indep_var_1,\n\t\t\t\t      indep_var,\n\t\t\t\t      dep_var_0,\n\t\t\t\t      dep_var_1 ) );\n}\n\n// Process the independent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType\nLinLin::processIndepVar( const T indep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LinLin::isIndepVarInValidRange( indep_var  ) );\n\n  return getRawQuantity(indep_var);\n}\n\n// Process the dependent value\ntemplate<typename T>\ninline typename QuantityTraits<T>::RawType\nLinLin::processDepVar( const T dep_var )\n{\n  // Make sure the indep var value is valid\n  testPrecondition( LinLin::isDepVarInValidRange( dep_var ) );\n\n  return getRawQuantity(dep_var);\n}\n\n// Recover the processed independent value\ntemplate<typename T>\ninline T LinLin::recoverProcessedIndepVar( const T processed_indep_var )\n{\n  return processed_indep_var;\n}\n\n// Recover the processed dependent value\ntemplate<typename T>\ninline T LinLin::recoverProcessedDepVar( const T processed_dep_var )\n{\n  return processed_dep_var;\n}\n\n// Test if the independent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LinLin::isIndepVarInValidRange( const T indep_var )\n{\n  return true;\n}\n\n// Test if the dependent value is in a valid range (doesn't check nan/inf)\ntemplate<typename T>\ninline bool LinLin::isDepVarInValidRange( const T dep_var )\n{\n  // Make sure the indep var is not inf or nan\n  testPrecondition( !QuantityTraits<T>::isnaninf( dep_var ) );\n\n  return true;\n}\n\n} // end Utility namespace\n\n#endif // end UTILITY_INTERPOLATION_POLICY_DEF_HPP\n\n//---------------------------------------------------------------------------//\n// end Utility_InterpolationPolicy_def.hpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "42e0c14abec47e9649ecb4055a357c9df22ba43c", "size": 35126, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "packages/utility/interpolation/src/Utility_InterpolationPolicy_def.hpp", "max_stars_repo_name": "bam241/FRENSIE", "max_stars_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-11-14T19:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-04T17:44:09.000Z", "max_issues_repo_path": "packages/utility/interpolation/src/Utility_InterpolationPolicy_def.hpp", "max_issues_repo_name": "bam241/FRENSIE", "max_issues_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2020-03-03T19:59:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-08T03:36:08.000Z", "max_forks_repo_path": "packages/utility/interpolation/src/Utility_InterpolationPolicy_def.hpp", "max_forks_repo_name": "bam241/FRENSIE", "max_forks_repo_head_hexsha": "e1760cd792928699c84f2bdce70ff54228e88094", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-02-12T17:37:07.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-08T18:59:51.000Z", "avg_line_length": 40.2359679267, "max_line_length": 114, "alphanum_fraction": 0.7186129932, "num_tokens": 8662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.21649116269402044}}
{"text": "/* CirKit: A circuit toolkit\n * Copyright (C) 2009-2015  University of Bremen\n * Copyright (C) 2015-2017  EPFL\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"error_metrics.hpp\"\n\n#include <cmath>\n#include <stack>\n\n#include <boost/algorithm/string/join.hpp>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/format.hpp>\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/combine.hpp>\n#include <boost/range/numeric.hpp>\n#include <boost/version.hpp>\n\n#include <core/utils/bitset_utils.hpp>\n#include <core/utils/timer.hpp>\n#include <classical/dd/arithmetic.hpp>\n#include <classical/dd/bdd_to_truth_table.hpp>\n#include <classical/dd/characteristic.hpp>\n#include <classical/dd/count_solutions.hpp>\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\ninline void assert_valid( const std::vector<bdd>& f, const std::vector<bdd>& fhat )\n{\n  assert( f.size() == fhat.size() );\n  assert( !f.empty() );\n}\n\nstd::vector<bdd> compute_diff( const std::vector<bdd>& f, const std::vector<bdd>& fhat, bool print_truthtables = false )\n{\n  assert_valid( f, fhat );\n\n  const auto to = f.size() + 1u;\n\n  const auto zf    = zero_extend( f, to );\n  const auto zfhat = zero_extend( fhat, to );\n  const auto subtr = bdd_subtract( zf, zfhat );\n  const auto diff  = bdd_abs( subtr );\n\n#if ( BOOST_VERSION / 100000 ) >= 1 && ( BOOST_VERSION / 100 % 1000 ) >= 56\n  if ( print_truthtables )\n  {\n    using boost::adaptors::transformed;\n    using boost::format;\n    using boost::str;\n\n    auto valid = true;\n    auto max   = 0u;\n    auto sum   = 0u;\n\n    std::cout << std::endl << \"    f    zf  fhat zfhat subtr  diff valid\" << std::endl\n              << boost::join( boost::combine( bdds_to_truth_table_unsigned( f ),\n                                              bdds_to_truth_table_unsigned( zf ),\n                                              bdds_to_truth_table_unsigned( fhat ),\n                                              bdds_to_truth_table_unsigned( zfhat ),\n                                              bdds_to_truth_table_signed( subtr ),\n                                              bdds_to_truth_table_unsigned( diff ) )\n                              | transformed( [&]( const boost::tuple<unsigned, unsigned, unsigned, unsigned, int, unsigned>& p ) {\n                                  const auto vf     = boost::get<0>( p );\n                                  const auto vzf    = boost::get<1>( p );\n                                  const auto vfhat  = boost::get<2>( p );\n                                  const auto vzfhat = boost::get<3>( p );\n                                  const auto vsubtr = boost::get<4>( p );\n                                  const auto vdiff  = boost::get<5>( p );\n\n                                  const auto row_valid = ( vf == vzf ) && ( vfhat == vzfhat ) && ( vsubtr == static_cast<int>( vzf - vzfhat ) ) && ( abs( vsubtr ) == static_cast<int>( vdiff ) );\n                                  valid = valid && row_valid;\n                                  max   = std::max( max, vdiff );\n                                  sum  += vdiff;\n\n                                  return str( format( \"%5d %5d %5d %5d %5d %5d     %d\") % vf % vzf % vfhat % vzfhat % vsubtr % vdiff % row_valid );\n                                } ), \"\\n\" ) << std::endl\n              << format( \"valid: %d, max: %d, avg: %.2f\" ) % valid % max % ( sum / pow( 2.0, f.front().manager->num_vars() ) ) << std::endl;\n  }\n#endif\n\n  assert( diff.size() == to );\n  assert( diff.back().index == 0u );\n\n  return diff;\n}\n\nboost::multiprecision::uint256_t get_max_value( const std::vector<bdd>& f )\n{\n  assert( !f.empty() );\n\n  boost::dynamic_bitset<> bs( f.size() );\n  auto mask = f.front().manager->bdd_top();\n\n  for ( int k = f.size() - 1; k >= 0; --k )\n  {\n    auto r = mask && f[k];\n    if ( r.index != 0 )\n    {\n      bs.set( k );\n      mask = r;\n    }\n  }\n\n  return to_multiprecision<boost::multiprecision::uint256_t>( bs );\n}\n\nboost::multiprecision::uint256_t get_max_value_with_chi( const std::vector<bdd>& f )\n{\n  bdd_manager mgr_chi( f.front().manager->num_vars() + f.size(), 10u ); /* can we approximate the number of used nodes? */\n\n  auto fr  = f; boost::reverse( fr );\n  auto chi = characteristic_function( fr, mgr_chi );\n\n  boost::dynamic_bitset<> bs( f.size() );\n\n  while ( chi.var() < f.size() )\n  {\n    if ( chi.high().is_bot() )\n    {\n      chi = chi.low();\n    }\n    else\n    {\n      bs.set( f.size() - 1u - chi.var() );\n      chi = chi.high();\n    }\n  }\n\n  return to_multiprecision<boost::multiprecision::uint256_t>( bs );\n}\n\nboost::multiprecision::uint256_t get_weighted_sum( const std::vector<bdd>& f )\n{\n  auto level = f.size();\n  bdd_manager mgr_chi( f.front().manager->num_vars() + level, 10u ); /* can we approximate the number of used nodes? */\n\n  auto fr = f; boost::reverse( fr );\n  auto chi = characteristic_function( fr, mgr_chi );\n\n  boost::multiprecision::uint256_t sum = 0;\n  const boost::multiprecision::uint256_t one = 1;\n  std::stack<std::pair<bdd, boost::dynamic_bitset<>>> stack;\n\n  stack.push( {chi, boost::dynamic_bitset<>( level )} );\n\n  while ( !stack.empty() )\n  {\n    auto p = stack.top(); stack.pop();\n\n    if ( p.first.var() >= level )\n    {\n      sum += to_multiprecision<boost::multiprecision::uint256_t>( p.second ) * ( count_solutions( p.first ) / ( one << level ) );\n    }\n    else\n    {\n      stack.push( {p.first.low(), p.second} );\n      p.second.set( p.first.var() );\n      stack.push( {p.first.high(), p.second} );\n    }\n  }\n\n  return sum;\n}\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nboost::multiprecision::uint256_t error_rate( const std::vector<bdd>& f, const std::vector<bdd>& fhat,\n                                             const properties::ptr& settings,\n                                             const properties::ptr& statistics )\n{\n  properties_timer t( statistics );\n\n  assert_valid( f, fhat );\n\n  auto h = f.front().manager->bdd_bot();\n\n  for ( auto i = 0u; i < f.size(); ++i )\n  {\n    h = h || ( f[i] ^ fhat[i] );\n  }\n\n  return count_solutions( h );\n}\n\nboost::multiprecision::uint256_t worst_case( const std::vector<bdd>& f, const std::vector<bdd>& fhat,\n                                             const properties::ptr& settings,\n                                             const properties::ptr& statistics )\n{\n  auto print_truthtables = get( settings, \"print_truthtables\", false );\n  auto maximum_method    = get( settings, \"maximum_method\",    worst_case_maximum_method::shift );\n\n  properties_timer t( statistics );\n\n  auto diff = compute_diff( f, fhat, print_truthtables );\n\n  switch ( maximum_method )\n  {\n  case worst_case_maximum_method::shift:\n    return get_max_value( diff );\n  case worst_case_maximum_method::chi:\n    return get_max_value_with_chi( diff );\n  default:\n    assert( false );\n  }\n}\n\nboost::multiprecision::cpp_dec_float_100 average_case( const std::vector<bdd>& f, const std::vector<bdd>& fhat,\n                                                       const properties::ptr& settings, const properties::ptr& statistics )\n{\n  auto print_truthtables = get( settings, \"print_truthtables\", false );\n\n  properties_timer t( statistics );\n\n  auto diff = compute_diff( f, fhat, print_truthtables );\n\n  const boost::multiprecision::uint256_t one = 1;\n  return boost::multiprecision::cpp_dec_float_100( get_weighted_sum( diff ) ) /\n         boost::multiprecision::cpp_dec_float_100( one << f.front().manager->num_vars() );\n}\n\n}\n\n// Local Variables:\n// c-basic-offset: 2\n// eval: (c-set-offset 'substatement-open 0)\n// eval: (c-set-offset 'innamespace 0)\n// End:\n", "meta": {"hexsha": "05646913c182d0abf9c46b68f390135ca905ccb6", "size": 9282, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/approximate/error_metrics.cpp", "max_stars_repo_name": "eletesta/cirkit", "max_stars_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classical/approximate/error_metrics.cpp", "max_issues_repo_name": "eletesta/cirkit", "max_issues_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classical/approximate/error_metrics.cpp", "max_forks_repo_name": "eletesta/cirkit", "max_forks_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.427480916, "max_line_length": 194, "alphanum_fraction": 0.5498814911, "num_tokens": 2188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.3849121585956185, "lm_q1q2_score": 0.21638857046768423}}
{"text": "/* Copyright (c) 2016 - 2021, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#include <MaterialProperty.hh>\n\n#include <deal.II/base/point.h>\n#include <deal.II/base/quadrature_lib.h>\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/fe/fe_values.h>\n#include <deal.II/hp/fe_values.h>\n#include <deal.II/hp/q_collection.h>\n\n#include <boost/algorithm/string/split.hpp>\n#include <boost/optional.hpp>\n\n#include <algorithm>\n\nnamespace adamantine\n{\n\ntemplate <int dim>\nMaterialProperty<dim>::MaterialProperty(\n    MPI_Comm const &communicator,\n    dealii::parallel::distributed::Triangulation<dim> const &tria,\n    boost::property_tree::ptree const &database)\n    : _communicator(communicator), _fe(0), _mp_dof_handler(tria)\n{\n  // Because deal.II cannot easily attach data to a cell. We store the state\n  // of the material in distributed::Vector. This allows to use deal.II to\n  // compute the new state after refinement of the mesh. However, this\n  // requires to use another DoFHandler.\n  reinit_dofs();\n\n  // Set the material state to the state defined in the geometry.\n  set_initial_state();\n\n  // Fill the _properties map\n  fill_properties(database);\n}\n\ntemplate <int dim>\ndouble MaterialProperty<dim>::get_cell_value(\n    typename dealii::Triangulation<dim>::active_cell_iterator const &cell,\n    StateProperty prop) const\n{\n  unsigned int property = static_cast<unsigned int>(prop);\n  auto const mp_dof_index = get_dof_index(cell);\n\n  return _property_values[property][mp_dof_index];\n}\n\ntemplate <int dim>\ndouble MaterialProperty<dim>::get_cell_value(\n    typename dealii::Triangulation<dim>::active_cell_iterator const &cell,\n    Property prop) const\n{\n  dealii::types::material_id material_id = cell->material_id();\n  unsigned int property = static_cast<unsigned int>(prop);\n\n  return _properties(material_id, property);\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::reinit_dofs()\n{\n  _mp_dof_handler.distribute_dofs(_fe);\n  // Initialize the state vectors\n  for (auto &vec : _state)\n    vec.reinit(_mp_dof_handler.locally_owned_dofs(), _communicator);\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::update(\n    dealii::DoFHandler<dim> const &temperature_dof_handler,\n    dealii::LA::distributed::Vector<double> const &temperature)\n{\n  auto temperature_average =\n      compute_average_temperature(temperature_dof_handler, temperature);\n  for (auto &val : _property_values)\n    val.reinit(temperature_average.get_partitioner());\n\n  std::vector<dealii::types::global_dof_index> mp_dof(1);\n  for (auto cell :\n       dealii::filter_iterators(_mp_dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    dealii::types::material_id material_id = cell->material_id();\n\n    unsigned int constexpr liquid =\n        static_cast<unsigned int>(MaterialState::liquid);\n    unsigned int constexpr powder =\n        static_cast<unsigned int>(MaterialState::powder);\n    unsigned int constexpr solid =\n        static_cast<unsigned int>(MaterialState::solid);\n    unsigned int constexpr prop_solidus =\n        static_cast<unsigned int>(Property::solidus);\n    unsigned int constexpr prop_liquidus =\n        static_cast<unsigned int>(Property::liquidus);\n\n    double const solidus = _properties(material_id, prop_solidus);\n    double const liquidus = _properties(material_id, prop_liquidus);\n    cell->get_dof_indices(mp_dof);\n    unsigned int const dof = mp_dof[0];\n\n    // First determine the ratio of liquid.\n    double liquid_ratio = -1.;\n    double powder_ratio = -1.;\n    double solid_ratio = -1.;\n    if (temperature_average[dof] < solidus)\n      liquid_ratio = 0.;\n    else if (temperature_average[dof] > liquidus)\n      liquid_ratio = 1.;\n    else\n      liquid_ratio =\n          (temperature_average[dof] - solidus) / (liquidus - solidus);\n    // Because the powder can only become liquid, the solid can only become\n    // liquid, and the liquid can only become solid, the ratio of powder can\n    // only decrease.\n    powder_ratio = std::min(1. - liquid_ratio, _state[powder][dof]);\n    // Use max to make sure that we don't create matter because of round-off.\n    solid_ratio = std::max(1 - liquid_ratio - powder_ratio, 0.);\n\n    // Update the value\n    _state[liquid][dof] = liquid_ratio;\n    _state[powder][dof] = powder_ratio;\n    _state[solid][dof] = solid_ratio;\n\n    if (_use_table)\n    {\n      for (unsigned int property = 0; property < _n_state_properties;\n           ++property)\n      {\n        for (unsigned int material_state = 0;\n             material_state < _n_material_states; ++material_state)\n        {\n          _property_values[property][dof] +=\n              _state[material_state][dof] *\n              compute_property_from_table(material_id, material_state, property,\n                                          temperature_average[dof]);\n        }\n      }\n    }\n    else\n    {\n      for (unsigned int property = 0; property < _n_state_properties;\n           ++property)\n      {\n        for (unsigned int material_state = 0;\n             material_state < _n_material_states; ++material_state)\n        {\n          for (unsigned int i = 0; i <= _polynomial_order; ++i)\n          {\n            _property_values[property][dof] +=\n                _state[material_state][dof] *\n                _state_property_polynomials(material_id, material_state,\n                                            property, i) *\n                std::pow(temperature_average[dof], i);\n          }\n        }\n      }\n    }\n\n    // If we are in the mushy state, i.e., part liquid part solid, we need to\n    // modify the rho C_p to take into account the latent heat.\n    if ((liquid_ratio > 0.) && (liquid_ratio < 1.))\n    {\n      unsigned int const specific_heat_prop =\n          static_cast<unsigned int>(StateProperty::specific_heat);\n      unsigned int const latent_heat_prop =\n          static_cast<unsigned int>(Property::latent_heat);\n      for (unsigned int material_state = 0; material_state < _n_material_states;\n           ++material_state)\n      {\n        _property_values[specific_heat_prop][dof] +=\n            _state[material_state][dof] *\n            _properties(material_id, latent_heat_prop) / (liquidus - solidus);\n      }\n    }\n\n    // The radiation heat transfer coefficient is not a real material property\n    // but it is derived from other material properties:\n    // h_rad = emissitivity * stefan-boltzmann constant * (T + T_infty) (T^2 +\n    // T^2_infty).\n    unsigned int const emissivity_prop =\n        static_cast<unsigned int>(StateProperty::emissivity);\n    unsigned int const radiation_heat_transfer_coef_prop =\n        static_cast<unsigned int>(StateProperty::radiation_heat_transfer_coef);\n    unsigned int const radiation_temperature_infty_prop =\n        static_cast<unsigned int>(Property::radiation_temperature_infty);\n    double const T = temperature_average[dof];\n    double const T_infty =\n        _properties(material_id, radiation_temperature_infty_prop);\n    double const emissivity = _property_values[emissivity_prop][dof];\n    _property_values[radiation_heat_transfer_coef_prop][dof] =\n        emissivity * Constant::stefan_boltzmann * (T + T_infty) *\n        (T * T + T_infty * T_infty);\n  }\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::update_boundary_material_properties(\n    dealii::DoFHandler<dim> const &temperature_dof_handler,\n    dealii::LA::distributed::Vector<double> const &temperature)\n{\n  auto temperature_average =\n      compute_average_temperature(temperature_dof_handler, temperature);\n  for (auto &val : _property_values)\n    val.reinit(temperature_average.get_partitioner());\n\n  std::vector<dealii::types::global_dof_index> mp_dof(1);\n  // We don't need to loop over all the active cells. We only need to loop over\n  // the cells at the boundary and at the interface with FE_Nothing. However, to\n  // do this we need to use the temperature_dof_handler instead of the\n  // _mp_dof_handler.\n  for (auto cell :\n       dealii::filter_iterators(_mp_dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    dealii::types::material_id material_id = cell->material_id();\n\n    cell->get_dof_indices(mp_dof);\n    unsigned int const dof = mp_dof[0];\n    if (_use_table)\n    {\n      // We only care about properties that are used to compute the boundary\n      // condition. So we start at 3.\n      for (unsigned int property = 3; property < _n_state_properties;\n           ++property)\n      {\n        for (unsigned int material_state = 0;\n             material_state < _n_material_states; ++material_state)\n        {\n          _property_values[property][dof] +=\n              _state[material_state][dof] *\n              compute_property_from_table(material_id, material_state, property,\n                                          temperature_average[dof]);\n        }\n      }\n    }\n    else\n    {\n      // We only care about properties that are used to compute the boundary\n      // condition. So we start at  3.\n      for (unsigned int property = 3; property < _n_state_properties;\n           ++property)\n      {\n        for (unsigned int material_state = 0;\n             material_state < _n_material_states; ++material_state)\n        {\n          for (unsigned int i = 0; i <= _polynomial_order; ++i)\n          {\n            _property_values[property][dof] +=\n                _state[material_state][dof] *\n                _state_property_polynomials(material_id, material_state,\n                                            property, i) *\n                std::pow(temperature_average[dof], i);\n          }\n        }\n      }\n    }\n\n    // The radiation heat transfer coefficient is not a real material property\n    // but it is derived from other material properties:\n    // h_rad = emissitivity * stefan-boltzmann constant * (T + T_infty) (T^2 +\n    // T^2_infty).\n    unsigned int const emissivity_prop =\n        static_cast<unsigned int>(StateProperty::emissivity);\n    unsigned int const radiation_heat_transfer_coef_prop =\n        static_cast<unsigned int>(StateProperty::radiation_heat_transfer_coef);\n    unsigned int const radiation_temperature_infty_prop =\n        static_cast<unsigned int>(Property::radiation_temperature_infty);\n    double const T = temperature_average[dof];\n    double const T_infty =\n        _properties(material_id, radiation_temperature_infty_prop);\n    double const emissivity = _property_values[emissivity_prop][dof];\n    _property_values[radiation_heat_transfer_coef_prop][dof] =\n        emissivity * Constant::stefan_boltzmann * (T + T_infty) *\n        (T * T + T_infty * T_infty);\n  }\n}\n\ntemplate <int dim>\nADAMANTINE_HOST_DEV dealii::VectorizedArray<double>\nMaterialProperty<dim>::compute_material_property(\n    StateProperty state_property, dealii::types::material_id const *material_id,\n    dealii::VectorizedArray<double> const *state_ratios,\n    dealii::VectorizedArray<double> temperature) const\n{\n  dealii::VectorizedArray<double> value = 0.0;\n  unsigned int const property_index = static_cast<unsigned int>(state_property);\n\n  if (_use_table)\n  {\n    for (unsigned int material_state = 0; material_state < _n_material_states;\n         ++material_state)\n    {\n      for (unsigned int n = 0; n < dealii::VectorizedArray<double>::size(); ++n)\n      {\n\n        const dealii::types::material_id m_id = material_id[n];\n\n        value[n] += state_ratios[material_state][n] *\n                    compute_property_from_table(m_id, material_state,\n                                                property_index, temperature[n]);\n      }\n    }\n  }\n  else\n  {\n    for (unsigned int material_state = 0; material_state < _n_material_states;\n         ++material_state)\n    {\n      for (unsigned int n = 0; n < dealii::VectorizedArray<double>::size(); ++n)\n      {\n\n        dealii::types::material_id m_id = material_id[n];\n\n        for (unsigned int i = 0; i <= _polynomial_order; ++i)\n        {\n          value[n] += state_ratios[material_state][n] *\n                      _state_property_polynomials(m_id, material_state,\n                                                  property_index, i) *\n                      std::pow(temperature[n], i);\n        }\n      }\n    }\n  }\n\n  return value;\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::set_state(\n    dealii::Table<2, dealii::VectorizedArray<double>> const &liquid_ratio,\n    dealii::Table<2, dealii::VectorizedArray<double>> const &powder_ratio,\n    std::map<typename dealii::DoFHandler<dim>::cell_iterator,\n             std::pair<unsigned int, unsigned int>> &cell_it_to_mf_cell_map,\n    dealii::DoFHandler<dim> const &dof_handler)\n{\n  auto const powder_state = static_cast<unsigned int>(MaterialState::powder);\n  auto const liquid_state = static_cast<unsigned int>(MaterialState::liquid);\n  auto const solid_state = static_cast<unsigned int>(MaterialState::solid);\n  std::vector<dealii::types::global_dof_index> mp_dof(1.);\n\n  for (auto cell :\n       dealii::filter_iterators(dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    typename dealii::Triangulation<dim>::active_cell_iterator cell_tria(cell);\n    auto mp_dof_index = get_dof_index(cell_tria);\n    auto const &mf_cell_vector = cell_it_to_mf_cell_map[cell];\n    unsigned int const n_q_points = dof_handler.get_fe().tensor_degree() + 1;\n    double liquid_ratio_sum = 0.;\n    double powder_ratio_sum = 0.;\n    for (unsigned int q = 0; q < n_q_points; ++q)\n    {\n      liquid_ratio_sum +=\n          liquid_ratio(mf_cell_vector.first, q)[mf_cell_vector.second];\n      powder_ratio_sum +=\n          powder_ratio(mf_cell_vector.first, q)[mf_cell_vector.second];\n    }\n    _state[liquid_state][mp_dof_index] = liquid_ratio_sum / n_q_points;\n    _state[powder_state][mp_dof_index] = powder_ratio_sum / n_q_points;\n    _state[solid_state][mp_dof_index] =\n        std::max(1. - _state[liquid_state][mp_dof_index] -\n                     _state[powder_state][mp_dof_index],\n                 0.);\n  }\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::set_initial_state()\n{\n  // Set the material state to the one defined by the user_index\n  std::vector<dealii::types::global_dof_index> mp_dof(1);\n  for (auto cell :\n       dealii::filter_iterators(_mp_dof_handler.active_cell_iterators(),\n                                dealii::IteratorFilters::LocallyOwnedCell()))\n  {\n    cell->get_dof_indices(mp_dof);\n    _state[cell->user_index()][mp_dof[0]] = 1.;\n  }\n}\n\ntemplate <int dim>\nvoid MaterialProperty<dim>::fill_properties(\n    boost::property_tree::ptree const &database)\n{\n  std::array<std::string, _n_material_states> material_state = {\n      {\"powder\", \"solid\", \"liquid\"}};\n  std::array<std::string, _n_properties> properties = {\n      {\"liquidus\", \"solidus\", \"latent_heat\", \"radiation_temperature_infty\",\n       \"convection_temperature_infty\"}};\n  std::array<std::string, _n_state_properties> state_properties = {\n      {\"density\", \"specific_heat\", \"thermal_conductivity\", \"emissivity\",\n       \"radiation_heat_transfer_coef\", \"convection_heat_transfer_coef\"}};\n\n  // PropertyTreeInput materials.property_format\n  std::string property_format = database.get<std::string>(\"property_format\");\n  ASSERT_THROW((property_format == \"table\") ||\n                   (property_format == \"polynomial\"),\n               \"property_format should be table or polynomial.\");\n  _use_table = (property_format == \"table\");\n  // PropertyTreeInput materials.n_materials\n  unsigned int const n_materials = database.get<unsigned int>(\"n_materials\");\n  // Find all the material_ids being used.\n  std::vector<dealii::types::material_id> material_ids;\n  for (dealii::types::material_id id = 0;\n       id < dealii::numbers::invalid_material_id; ++id)\n  {\n    if (database.count(\"material_\" + std::to_string(id)) != 0)\n      material_ids.push_back(id);\n    if (material_ids.size() == n_materials)\n      break;\n  }\n  ASSERT_THROW(material_ids.size() == n_materials,\n               \"Could not find all the material_ids.\");\n\n  // When using the polynomial format we allocate one contiguous block of\n  // memory. Thus, the largest material_id should be as small as possible\n  unsigned int const n_material_ids =\n      *std::max_element(material_ids.begin(), material_ids.end()) + 1;\n  _properties.reinit(n_material_ids);\n  if (_use_table)\n  {\n    // TODO read table size from input file\n    _table_size = 4;\n    _state_property_tables.reinit(n_material_ids, _table_size);\n    _state_property_tables.set_zero();\n  }\n  else\n  {\n    // TODO read polynomial_order from input file\n    _polynomial_order = 4;\n    _state_property_polynomials.reinit(n_material_ids + 1,\n                                       _polynomial_order + 1);\n    _state_property_polynomials.set_zero();\n  }\n\n  for (auto const material_id : material_ids)\n  {\n    // Get the material property tree.\n    boost::property_tree::ptree const &material_database =\n        database.get_child(\"material_\" + std::to_string(material_id));\n    // For each material, loop over the possible states.\n    bool valid_state = false;\n    for (unsigned int state = 0; state < _n_material_states; ++state)\n    {\n      // The state may or may not exist for the material.\n      boost::optional<boost::property_tree::ptree const &> state_database =\n          material_database.get_child_optional(material_state[state]);\n      if (state_database)\n      {\n        valid_state = true;\n        // For each state, loop over the possible properties.\n        for (unsigned int p = 0; p < _n_state_properties; ++p)\n        {\n          // The property may or may not exist for that state\n          boost::optional<std::string> const property =\n              state_database.get().get_optional<std::string>(\n                  state_properties[p]);\n          // If the property exists, put it in the map. If the property does not\n          // exist, we have a nullptr.\n          if (property)\n          {\n            // Remove blank spaces\n            std::string property_string = property.get();\n            property_string.erase(\n                std::remove_if(property_string.begin(), property_string.end(),\n                               [](unsigned char x) { return std::isspace(x); }),\n                property_string.end());\n            if (_use_table)\n            {\n              std::vector<std::string> parsed_property;\n              boost::split(parsed_property, property_string,\n                           [](char c) { return c == ';'; });\n              unsigned int const parsed_property_size = parsed_property.size();\n              ASSERT_THROW(parsed_property_size <= _table_size,\n                           \"Too many coefficients, increase the table size\");\n              for (unsigned int i = 0; i < parsed_property_size; ++i)\n              {\n                std::vector<std::string> t_v;\n                boost::split(t_v, parsed_property[i],\n                             [](char c) { return c == ','; });\n                ASSERT(t_v.size() == 2, \"Error reading material property.\");\n                _state_property_tables(material_id, state, p, i, 0) =\n                    std::stod(t_v[0]);\n                _state_property_tables(material_id, state, p, i, 1) =\n                    std::stod(t_v[1]);\n              }\n              // fill the rest  with the last value\n              for (unsigned int i = parsed_property_size; i < _table_size; ++i)\n              {\n                _state_property_tables(material_id, state, p, i, 0) =\n                    _state_property_tables(material_id, state, p, i - 1, 0);\n                _state_property_tables(material_id, state, p, i, 1) =\n                    _state_property_tables(material_id, state, p, i - 1, 1);\n              }\n            }\n            else\n            {\n              std::vector<std::string> parsed_property;\n              boost::split(parsed_property, property_string,\n                           [](char c) { return c == ','; });\n              unsigned int const parsed_property_size = parsed_property.size();\n              ASSERT_THROW(\n                  parsed_property_size <= _polynomial_order,\n                  \"Too many coefficients, increase the polynomial order\");\n              for (unsigned int i = 0; i < parsed_property_size; ++i)\n              {\n                _state_property_polynomials(material_id, state, p, i) =\n                    std::stod(parsed_property[i]);\n              }\n            }\n          }\n        }\n      }\n    }\n    // Check that there is at least one valid MaterialState\n    ASSERT_THROW(\n        valid_state == true,\n        \"Material without any valid state (solid, powder, or liquid).\");\n\n    // Check for the properties that are associated to a material but that\n    // are independent of an individual state. These properties are duplicated\n    // for every state.\n    for (unsigned int p = 0; p < _n_properties; ++p)\n    {\n      // The property may or may not exist for that state\n      boost::optional<double> const property =\n          material_database.get_optional<double>(properties[p]);\n      // If the property exists, put it in the map. If the property does not\n      // exist, we use the largest possible value. This is useful if the\n      // liquidus and the solidus are not set.\n      _properties(material_id, p) =\n          property ? property.get() : std::numeric_limits<double>::max();\n    }\n  }\n}\n\n// We need to compute the average temperature on the cell because we need the\n// material properties to be uniform over the cell. If there aren't then we have\n// problems with the weak form discretization.\ntemplate <int dim>\ndealii::LA::distributed::Vector<double>\nMaterialProperty<dim>::compute_average_temperature(\n    dealii::DoFHandler<dim> const &temperature_dof_handler,\n    dealii::LA::distributed::Vector<double> const &temperature) const\n{\n  // TODO: this should probably done in a matrix-free fashion.\n  // The triangulation is the same for both DoFHandler\n  dealii::LA::distributed::Vector<double> temperature_average(\n      _mp_dof_handler.locally_owned_dofs(), temperature.get_mpi_communicator());\n  temperature.update_ghost_values();\n  temperature_average = 0.;\n  auto mp_cell = _mp_dof_handler.begin_active();\n  auto mp_end_cell = _mp_dof_handler.end();\n  auto enth_cell = temperature_dof_handler.begin_active();\n  dealii::hp::FECollection<dim> const &fe_collection =\n      temperature_dof_handler.get_fe_collection();\n  dealii::hp::QCollection<dim> q_collection;\n  q_collection.push_back(dealii::QGauss<dim>(fe_collection.max_degree() + 1));\n  q_collection.push_back(dealii::QGauss<dim>(1));\n  dealii::hp::FEValues<dim> hp_fe_values(\n      fe_collection, q_collection,\n      dealii::UpdateFlags::update_values |\n          dealii::UpdateFlags::update_quadrature_points |\n          dealii::UpdateFlags::update_JxW_values);\n  std::vector<dealii::types::global_dof_index> mp_dof_indices(1);\n  unsigned int const n_q_points = q_collection.max_n_quadrature_points();\n  unsigned int const dofs_per_cell = fe_collection.max_dofs_per_cell();\n  std::vector<dealii::types::global_dof_index> enth_dof_indices(dofs_per_cell);\n  for (; mp_cell != mp_end_cell; ++enth_cell, ++mp_cell)\n  {\n    ASSERT(mp_cell->is_locally_owned() == enth_cell->is_locally_owned(),\n           \"Internal Error\");\n    if ((mp_cell->is_locally_owned()) && (enth_cell->active_fe_index() == 0))\n    {\n      hp_fe_values.reinit(enth_cell);\n      dealii::FEValues<dim> const &fe_values =\n          hp_fe_values.get_present_fe_values();\n      mp_cell->get_dof_indices(mp_dof_indices);\n      dealii::types::global_dof_index const mp_dof_index = mp_dof_indices[0];\n      enth_cell->get_dof_indices(enth_dof_indices);\n      double volume = 0.;\n      for (unsigned int q = 0; q < n_q_points; ++q)\n        for (unsigned int i = 0; i < dofs_per_cell; ++i)\n        {\n          volume += fe_values.shape_value(i, q) * fe_values.JxW(q);\n          temperature_average[mp_dof_index] +=\n              fe_values.shape_value(i, q) * temperature[enth_dof_indices[i]] *\n              fe_values.JxW(q);\n        }\n      temperature_average[mp_dof_index] /= volume;\n    }\n  }\n\n  return temperature_average;\n}\n\ntemplate <int dim>\ndouble MaterialProperty<dim>::compute_property_from_table(\n    unsigned int const material_id, unsigned int const material_state,\n    unsigned int const property, double const temperature) const\n{\n  if (temperature <=\n      _state_property_tables(material_id, material_state, property, 0, 0))\n  {\n    return _state_property_tables(material_id, material_state, property, 0, 1);\n  }\n  else\n  {\n    unsigned int i = 0;\n    unsigned int const size = _state_property_tables.extent(3);\n    for (; i < size; ++i)\n    {\n      if (temperature <\n          _state_property_tables(material_id, material_state, property, i, 0))\n      {\n        break;\n      }\n    }\n\n    if (i >= size - 1)\n    {\n      return _state_property_tables(material_id, material_state, property,\n                                    size - 1, 1);\n    }\n    else\n    {\n      auto tempertature_i =\n          _state_property_tables(material_id, material_state, property, i, 0);\n      auto tempertature_im1 = _state_property_tables(\n          material_id, material_state, property, i - 1, 0);\n      auto property_i =\n          _state_property_tables(material_id, material_state, property, i, 1);\n      auto property_im1 = _state_property_tables(material_id, material_state,\n                                                 property, i - 1, 1);\n      return property_im1 + (temperature - tempertature_im1) *\n                                (property_i - property_im1) /\n                                (tempertature_i - tempertature_im1);\n    }\n  }\n}\n\n} // namespace adamantine\n", "meta": {"hexsha": "9705d60539fb656e7762653bb106ac0e2175392c", "size": 25847, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/MaterialProperty.templates.hh", "max_stars_repo_name": "Rombur/adamantine", "max_stars_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-09-03T02:08:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-03T01:26:41.000Z", "max_issues_repo_path": "source/MaterialProperty.templates.hh", "max_issues_repo_name": "Rombur/adamantine", "max_issues_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 74.0, "max_issues_repo_issues_event_min_datetime": "2016-08-31T18:10:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T01:51:44.000Z", "max_forks_repo_path": "source/MaterialProperty.templates.hh", "max_forks_repo_name": "Rombur/adamantine", "max_forks_repo_head_hexsha": "45dd37397680fad1eaa64dbb311724c4f727a675", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-12T15:43:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-19T02:58:56.000Z", "avg_line_length": 39.7035330261, "max_line_length": 80, "alphanum_fraction": 0.652764344, "num_tokens": 6043, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2163793201926002}}
{"text": "\n\n#include \"UGCPopularity.hpp\"\n#include \"ContentElement.hpp\"\n#include <boost/random/mersenne_twister.hpp>\n#include <boost/random/uniform_01.hpp>\n#include <boost/random/gamma_distribution.hpp>\n#include \"boost/random/uniform_real_distribution.hpp\"\n#include <boost/math/distributions/lognormal.hpp>\n#include \"boost/random/uniform_int.hpp\"\n#include <algorithm>\n\nextern boost::mt19937 gen;\n\nUGCPopularity::UGCPopularity(unsigned int totalRounds,\n        bool perturbations) {\n  this->totalRounds = totalRounds;\n  this->ttpDist = new boost::math::ttpDistribution(totalRounds);\n  this->perturbations = perturbations;\n}\n\nUGCPopularity::~UGCPopularity() {\n  delete ttpDist;\n}\n\n// generate views for all the content elements at a given phase for this round only\nunsigned int UGCPopularity::generateViews(std::list<ContentElement*> contentList, \n      peakingPhase phase) {\n  unsigned int bodyCount, tailCount;\n  tailCount = std::floor(contentList.size() / 10);\n  bodyCount = contentList.size() - tailCount;\n  std::list<unsigned int> views;\n  if (phase == BEFORE_PEAK) {\n    for (unsigned int i = 0; i < tailCount; i++) {\n      views.push_back(this->getBeforePeakTailViews());\n    }\n    for (unsigned int i = 0; i < bodyCount; i++) {\n      views.push_back(this->getBeforePeakViews());\n    }\n  } else if (phase == AT_PEAK) {\n    for (unsigned int i = 0; i < tailCount; i++) {\n      views.push_back(this->getAtPeakTailViews());\n    }\n    for (unsigned int i = 0; i < bodyCount; i++) {\n      views.push_back(this->getAtPeakViews());\n    }\n  } else { // phase == AFTER_PEAK\n    for (unsigned int i = 0; i < tailCount; i++) {\n      views.push_back(this->getAfterPeakTailViews());\n    }\n    for (unsigned int i = 0; i < bodyCount; i++) {\n      views.push_back(this->getAfterPeakViews());\n    }\n  }\n  // sort the views in descending order and assign them to the contentList\n  // (which is ordered by ranking) so that relative ranking remains unaltered\n  views.sort(std::greater<unsigned int>());\n  std::list<unsigned int>::iterator viewsIt, mIt;\n  \n  // introduce perturbations in the number of views, by switching views between\n  // videos in the same phase and at a maximum distance g\n  if (this->perturbations && phase != AT_PEAK) {\n    uint g = 12; // suggested value from Borghol et al.\n    std::vector<std::pair<uint, uint> > winLimits;\n    uint minWin, maxWin;\n    uint maxViews = views.front();\n    // compute valid switching windows for each content\n    BOOST_FOREACH(uint v, views) {\n      minWin = std::floor(v / g);\n      maxWin = std::min(maxViews, v * g);\n      winLimits.push_back(std::make_pair(minWin,maxWin));\n    }\n    // switch views a \"sufficiently large number of times\" (!) between contents\n    // with compatible switching windows\n    \n    // NOTE: the following code is so ugly it makes me want to kill kittens. \n    // try to rewrite it in a half-decent way, ok?\n    boost::random::uniform_int_distribution<> uniDist(0, contentList.size()-1);\n    for (uint i = 0; i < contentList.size() / 3; i++) {\n      uint randC = uniDist(gen);\n      viewsIt = views.begin();\n      for (uint j = 0; j < randC; j++)\n        viewsIt++;\n      mIt = viewsIt;\n      int j = 0;\n      while (mIt != views.begin() && *mIt >= winLimits[randC].first) {\n        j--;\n        mIt--;\n      }\n      if (j != 0) j++;\n      mIt = viewsIt;\n      int k = 0;\n      while (mIt != views.end() && *mIt <= winLimits[randC].second) {\n        mIt++;\n        k++;\n      }\n      if (k != 0) k--;\n      if (j != 0 || k != 0) {\n        boost::random::uniform_int_distribution<> switchDist(0,k-j);\n        j = switchDist(gen) + j;\n        if (j < 0) {\n          std::swap(winLimits[randC], winLimits[randC+j]);\n          mIt = viewsIt;\n          while (j < 0) {\n            mIt--;\n            j++;\n          }\n          std::iter_swap(viewsIt, mIt);          \n        }\n        else if (j > 0) {\n          std::swap(winLimits[randC], winLimits[randC+j]);\n          mIt = viewsIt;\n          while (j > 0) {\n            mIt++;\n            j--;\n          }\n          std::iter_swap(viewsIt, mIt);          \n        }\n      }      \n    }\n  }\n  // assign views in the intended order (sorted or permuted)\n  uint totalViews = 0;\n  viewsIt = views.begin();\n  BOOST_FOREACH (ContentElement* content, contentList) {\n    content->setViewsThisRound(*viewsIt);\n    totalViews += *viewsIt;\n    viewsIt++;\n  }\n  return totalViews;\n}\n\n// Returns the round at which a content will peak in terms of views\nunsigned int UGCPopularity::generatePeakRound() {\n  boost::uniform_01<> uni;\n  double randVal = uni(gen);\n//  std::cout << \"Uniform Value: \" << randVal << std::endl;\n  return boost::math::quantile(*ttpDist, randVal);\n}\n\nunsigned int UGCPopularity::getBeforePeakTailViews() {\n  boost::math::lognormal logDist(2.000, 2.135);\n  boost::random::uniform_real_distribution<> uniDist(0.903, 1);\n  double randValue = uniDist(gen);\n  double retValue = boost::math::quantile(logDist, randValue);  \n  return static_cast<unsigned int>(0.5+retValue);\n}\n\nunsigned int UGCPopularity::getAtPeakTailViews() {\n  boost::math::lognormal logDist(-3.826, 3.477);\n  boost::random::uniform_real_distribution<> uniDist(0.997, 1);\n  double randValue = uniDist(gen);\n  double retValue = boost::math::quantile(logDist, randValue);  \n  return static_cast<unsigned int>(0.5+retValue);\n}\n\nunsigned int UGCPopularity::getAfterPeakTailViews() {\n  boost::math::lognormal logDist(-0.356, 2.533);\n  boost::random::uniform_real_distribution<> uniDist(0.931, 1);\n  double randValue = uniDist(gen);\n  double retValue = boost::math::quantile(logDist, randValue);  \n  return static_cast<unsigned int>(0.5+retValue);\n}\n\nunsigned int UGCPopularity::getBeforePeakViews() {\n  const unsigned int xMin = 0, xThresh = 119;\n  unsigned int retValue = 0;\n  boost::uniform_01<> uniDist;\n  double randVal = uniDist(gen);\n  // std::cout << \"Uniform Value: \" << randVal << std::endl;\n  boost::math::beta_distribution<> betaDist(0.191, 1.330);\n  retValue = std::floor(0.5+xMin+(xThresh-xMin)*\n          boost::math::quantile(betaDist, randVal));  \n  return retValue;\n}\n\nunsigned int UGCPopularity::getAtPeakViews() {\n  const unsigned int xMin = 4, xThresh = 297;\n  unsigned int retValue = 0;\n  boost::uniform_01<> uniDist;\n  double randVal = uniDist(gen);\n  // std::cout << \"Uniform Value: \" << randVal << std::endl;  \n  boost::math::beta_distribution<> betaDist(0.543, 2.259);\n  retValue = std::floor(0.5+xMin+(xThresh-xMin)*\n            boost::math::quantile(betaDist, randVal));\n  return retValue;\n}\n\nunsigned int UGCPopularity::getAfterPeakViews() {\n  const unsigned int xMin = 0, xThresh = 30;\n  unsigned int retValue = 0;\n  boost::uniform_01<> uniDist;\n  double randVal = uniDist(gen);\n  // std::cout << \"Uniform Value: \" << randVal << std::endl;\n  boost::math::beta_distribution<> betaDist(0.077, 0.968);\n  retValue = std::floor(0.5+xMin+(xThresh-xMin)*\n            boost::math::quantile(betaDist, randVal));\n  return retValue;\n}\n", "meta": {"hexsha": "e8735ef178714a9e6c78f033e9c9ab76d99069a6", "size": 6932, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/UGCPopularity.cpp", "max_stars_repo_name": "manuhalo/PLACeS", "max_stars_repo_head_hexsha": "1574a34a2a98468e72d072cc9d1f2b32fcee38f2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/UGCPopularity.cpp", "max_issues_repo_name": "manuhalo/PLACeS", "max_issues_repo_head_hexsha": "1574a34a2a98468e72d072cc9d1f2b32fcee38f2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-04-24T10:10:51.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-18T08:32:16.000Z", "max_forks_repo_path": "src/UGCPopularity.cpp", "max_forks_repo_name": "manuhalo/PLACeS", "max_forks_repo_head_hexsha": "1574a34a2a98468e72d072cc9d1f2b32fcee38f2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.66, "max_line_length": 83, "alphanum_fraction": 0.6419503751, "num_tokens": 1971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.341582499438317, "lm_q1q2_score": 0.2163618610369601}}
{"text": "/*\n * =====================================================================================\n *\n *       Filename:  EnvelopFinder.cpp\n *\n *    Description:  \n *\n *        Version:  1.0\n *        Created:  9/6/2012 4:48:20 PM\n *       Revision:  none\n *       Compiler:  msvc\n *\n *         Author:  Han Hu (hh1985@bu.edu), \n *   Organization:  Boston University\n *\n * =====================================================================================\n */\n\n#include <algorithm>\n#include <GAGPL/MISC/Param.h>\n#include <GAGPL/SPECTRUM/EnvelopFinder.h>\n#include <GAGPL/SPECTRUM/EnvelopReference.h>\n#include <GAGPL/SPECTRUM/IsotopicDistribution.h>\n#include <boost/utility.hpp>\n//#include <boost/math/distributions/normal.hpp>\n\nnamespace gag\n{\n\tEnvelopFinder::EnvelopFinder(RichList& spec)\n\t\t: spectrum(spec), param(Param::instance())\t\n\t{\n\t\t/* \n\t\tGuess the range of average formula. Usually we assume the difference between composition estimated from the base peak and the one estimated from monoisotopic peak can be safely ignored.\n\t\t\tNo Sulfur (100D)\t\tHigh Sulfur (100D) \n\t\t\tC: 3.7238523        1.9961864\n\t\t\tH: 5.4425534        2.9942796\n\t\t\tO: 2.8645018        3.1938983\n\t\t\tN: 0.2864502        0.1996186\n\t\t\tS: 0                0.5988559\n\t\t*/\n\t\tave1.insert(std::make_pair(\"C\", 3.7238523));\n\t\tave1.insert(std::make_pair(\"H\", 5.4425534));\n\t\tave1.insert(std::make_pair(\"O\", 2.8645018));\n\t\tave1.insert(std::make_pair(\"N\", 0.2864502));\n\t\tave1.insert(std::make_pair(\"S\", 0.0));\n\n\t\tave2.insert(std::make_pair(\"C\", 1.9961864));\n\t\tave2.insert(std::make_pair(\"H\", 2.9942796));\n\t\tave2.insert(std::make_pair(\"O\", 3.1938983));\n\t\tave2.insert(std::make_pair(\"N\", 0.1996186));\n\t\tave2.insert(std::make_pair(\"S\", 0.5988559));\n\n\t\trun();\n\t}\n\n\tvoid EnvelopFinder::run()\n\t{\n\t\t// Get/Set parameters.\n\t\tunsigned int precursor_charge = param.getParameter<unsigned int>(\"precursor_charge\").first;\n\n\t\t// Divide the spectrum into several independent islands.\n\t\tIslandList is_list = this->getPeakIslands(spectrum);\n\n\t\t// Iterate over all independent islands.\n\t\tfor(IslandList::iterator iter = is_list.begin(); iter != is_list.end(); iter++)\n\t\t{\n\t\t\tstd::set<EnvelopPtr> temp_env_set;\n\n\t\t\tRichList island_pks = *iter;\n\t\t\tstd::cout << \"Found island: \" << std::endl;\n\t\t\tisland_pks.printPeakList<peak_mz>();\n\t\t\t// Starts from the peak with highest intensity. Assuming it is the base peak.\n\t\t\tRichPeakListByResolution& pks_area = island_pks.getPeakListByType<peak_resolution>();\n\t\t\t\n\t\t\tRichPeakListByResolution::iterator iter_area = pks_area.begin();\n\t\t\tRichPeakListByResolution::iterator end_iter = pks_area.end();\n\t\t\t// The last peak cannot be considered as a base peak.\n\t\t\tend_iter--;\n\n\t\t\t/* Step 1. Envelop identification */\n\t\t\tfor(; iter_area != end_iter; iter_area++)\n\t\t\t{\n\t\t\t\t// Iterate over all possible charge states.\n\t\t\t\t// Notice that the sign of the charge is not used here.\n\t\t\t\tfor(unsigned int z=precursor_charge; z>=1; z--)\n\t\t\t\t{\n\t\t\t\t\t// All candidate envelops should be stored for records.\n\t\t\t\t\tthis->findNextEnvelops(island_pks, iter_area, z, temp_env_set);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\t\n\n\t\t\tstd::cout << \"Before optimizing, output all the envelop information...\" << std::endl;\n\t\t\tBOOST_FOREACH(EnvelopPtr env, temp_env_set)\n\t\t\t\tenv_ref.printEnvelopInformation(env);\n\n\t\t\tstd::cout << std::endl;\n\n\t\t\t// Adjust the fitting scores and splitting scores for envelop set.\n\t\t\tthis->optimizeEnvelopSet(temp_env_set);\n\n\t\t} \n\t}\n\n\tIslandList EnvelopFinder::getPeakIslands(RichList& pks)\n\t{\n\t\tdouble island_space = param.getParameter<double>(\"island_space\").first;\n\n\t\tIslandList is_list;\n\n\t\tRichList* temp_spec = new RichList();\n\n\t\tRichPeakListByMZ& pks_mz = pks.getPeakListByType<peak_mz>();\n\n\t\tfor(RichPeakListByMZ::const_iterator iter = pks_mz.begin(); iter != pks_mz.end(); iter++)\n\t\t{\n\t\t\tif(iter == pks_mz.begin()) {\n\t\t\t\ttemp_spec->addPeak(*iter);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif((*iter)->mz - (*boost::prior(iter))->mz < island_space) {\n\t\t\t\ttemp_spec->addPeak(*iter);\n\t\t\t} else { // \n\t\t\t\tis_list.push_back(*temp_spec);\n\t\t\t\t\n\t\t\t\t// Delete the container. Be careful of this section.\n\t\t\t\tdelete temp_spec;\n\n\t\t\t\ttemp_spec = new RichList();\n\t\t\t\ttemp_spec->addPeak(*iter);\n\t\t\t}\n\t\t}\n\t\tis_list.push_back(*temp_spec);\n\t\tdelete temp_spec;\n\t\t\n\t\treturn is_list;\n\t}\n\n\tvoid EnvelopFinder::findNextEnvelops(RichList& island, RichPeakListByResolution::iterator iter_area, unsigned int charge, std::set<EnvelopPtr>& env_set)\n\t{\n\t\t// 1. Find candidate envelops which extend from current peak.\n\t\t\n\t\t// Project the area iterator into corresponding mz iterator.\n\t\tRichPeakListByMZ::iterator iter_mz = island.getPeakContainer().project<peak_mz>(iter_area);\n\n\t\tstd::cout << \"Identify base peak: \" << (*iter_mz)->mz << \" Charge: \" << charge << std::endl;\n\t\t\n\t\tint mode = param.getParameter<int>(\"mode\").first;\n\t\tdouble pre_mz = param.getParameter<double>(\"precursor_mz\").first;\n\t\tint pre_z = param.getParameter<int>(\"precursor_charge\").first;\n\t\t\n\t\t// Convert m/z value to corresponding mass. \n\t\tdouble pre_mass = calculateMass(pre_mz, pre_z * mode);\n\n\t\t// If the calculated mass is larger than precursor mass, there is no need to continue identification.\n\t\tdouble mass = calculateMass((*iter_mz)->mz, charge * mode);\n\t\t\n\t\tif(mass > pre_mass)\n\t\t\treturn;\n\n\t\tstd::pair<PeakSet,size_t> pk_set = this->extendPeakSet(island, iter_mz, charge);\n\t\t\n\t\tif(pk_set.first.getSize()==1)\n\t\t\treturn;\n\n    // Container for temporary storage of envelops.\n\t\tstd::vector<EnvelopPtr> env_store;\n\t\tfor(size_t i=0; i < pk_set.second; i++) {\n\t\t\tEnvelopPtr env = createEnvelop(charge, pk_set.first.getBoundary());\n\t\t\tenv_store.push_back(env);\n\t\t}\n\n\t\t// 2. TBD: Estimate the validity of the pk_set.\n\t\t// e.g. the overall shifts and the continuity of the shifts.\n\n\t\t// 2.a If the base peak has been reported as a distal peak of other envelops.\n\t\t// 2.b If envelops which share the base peak have the same charge \n\t\t// 2.c No event report for the base peak.\n\t\t// 2.d no contribution of new peaks.\n\t\t// 2.e fitting score is worse than expected.\n\n\t\t// Get the maximum number of envelops.\n\n\t\t// Dynamically convert pk_set into vector of envelops.\n\t\tProtoEnv& peak_information = pk_set.first.getPeakInformation();\n\n\t\tProtoEnv::iterator pk_iter = peak_information.begin(); \n\t\t// Iterate over all shift, decide if all envelop will share.\n\t\tfor(; pk_iter != peak_information.end(); )\n\t\t{\n\t\t\tint count = peak_information.count(pk_iter->first);\n\t\t\tstd::pair<ProtoEnv::iterator, ProtoEnv::iterator> shift_pair = peak_information.equal_range(pk_iter->first);\n\t\t\tProtoEnv::iterator shift_iter = shift_pair.first;\n\t\t\tProtoEnv::iterator last_iter = shift_pair.second;\n\t\t\tlast_iter--;\n\n\t\t\tfor(size_t i=0; i<env_store.size(); i++)\n\t\t\t{\t\n\t\t\t\t// Clean the definition of the internal structure.\n\t\t\t\tint shift = shift_iter->first;\n\t\t\t\tRichPeakPtr pk = shift_iter->second.first;\t\t\t\n\t\t\t\tInfoPeakPtr info = shift_iter->second.second;\n\t\t\t\t// Register the (peak, env) pair, shift and peak info into the envelop reference table.\n\t\t\t\tInfoPeakPtr info_copy(new InfoPeak(*info));\n\t\t\t\tstd::cout << \"Register peak \" << pk->mz << \"for envelop \" << env_store[i]->id << std::endl;\n\t\t\t\tenv_ref.addDictionaryReference(pk, env_store.at(i), shift, info_copy);\n\n\t\t\t\t// Non_unique_key.\n\t\t\t\tif(shift_iter != last_iter)\n\t\t\t\t\tshift_iter++;\t\t\n\n\t\t\t}\n\n\t\t\tpk_iter = shift_pair.second;\n\t\t}\n\n\t\t// Update envelop lambda information for each envelop.\n\t\tthis->updateEnvelopParameter(env_store);\n\n\t\t// Store the envelops.\n\t\tenv_set.insert(env_store.begin(), env_store.end());\n\t}\n\t\nstd::pair<PeakSet, size_t> EnvelopFinder::extendPeakSet(RichList& island, RichPeakListByMZ::iterator iter_mz, unsigned int charge)\n\t{\n\t\t\n\t\t// Candidate base peak. Notice that this might not be the monoisotopic peak for molecules with high mass values.\n\t\tRichPeakPtr expr_base_pk = *iter_mz;\n\t\tint mode = param.getParameter<int>(\"mode\").first;\n\t\tdouble mass = calculateMass(expr_base_pk->mz, charge * mode);\n\t\tEnvelopBoundary bound = this->createBoundary(mass, charge);\n\n\t\t// The reason of creating an object called envelop is because during the extension of peakset towards different directions, there might be multiple matching for given shift. \n\t\tPeakSet pk_set(bound);\n\n\t\tInfoPeakPtr pk_infor = boost::make_shared<InfoPeak>(expr_base_pk->resolution, 0.0, 0.5, 0.0);\n\t\t\n\t\tpk_set.addPeak(0, expr_base_pk, pk_infor);\n\n\t\tRichPeakListByMZ& pks_mz = island.getPeakListByType<peak_mz>();\n\n\t\t// Shift towards right along the mz axis.\n\t\tsize_t max_env = this->extendPeak(pk_set, pks_mz, iter_mz, charge, 1);\n\t\t// TBD: Shift towards left along the mz axis.\n\t\t//this->extendPeak(pk_set, pks_mz, iter_mz, charge, -1);\n\n\t\treturn std::make_pair(pk_set,max_env);\n\t}\n\n\n\tEnvelopBoundary EnvelopFinder::createBoundary(const double mass, unsigned int charge)\n\t{\n\t\t// 1. Estimate the rounded version of compositions.\n\t\tdouble coef = mass / 100.0;\n\t\tComposition compo1, compo2;\n\n\t\tAveragineFormulae::iterator iter1 = ave1.begin();\n\t\tfor(; iter1 != ave1.end(); iter1++)\n\t\t\tcompo1.addElement(iter1->first, (int)floor(iter1->second * coef + 0.5));\n\n\t\tAveragineFormulae::iterator iter2 = ave2.begin();\n\t\tfor(; iter2 != ave2.end(); iter2++)\n\t\t\tcompo2.addElement(iter2->first, (int)floor(iter2->second * coef + 0.5));\n\t\t\n\t\tint mode = param.getParameter<int>(\"mode\").first;\n\n\t\tint z = mode > 0 ? charge : (-1)*charge;\n\t\t// 2. Get the range of the isotopic distribution\n\t\tIsotopicDistribution iso_up(compo1);\n\t\tAggregatedIsotopicVariants peakset1 = iso_up.getAggregatedIsotopicVariants(z);\n\t\tIsotopicDistribution iso_down(compo2);\n\t\tAggregatedIsotopicVariants peakset2 = iso_down.getAggregatedIsotopicVariants(z);\n\n\t\treturn EnvelopBoundary(peakset1, peakset2);\n\t}\n\n\tsize_t EnvelopFinder::extendPeak(PeakSet& pk_set, RichPeakListByMZ& pks_mz,RichPeakListByMZ::iterator iter_mz, unsigned int charge, int direction)\n\t{\n\t\t//int dist = direction > 0 ? std::distance(iter_mz, pks_mz.end())-1 : std::distance(pks_mz.begin(), iter_mz);\n\t\t\n\t\tunsigned int shift = 1;\n\t\t//int prev_dist = 0;\n\n\t\t// Experimental candidate base peak.\n\t\tRichPeakPtr expr_base_pk = *iter_mz;\n\n\t\tint mode = param.getParameter<int>(\"mode\").first;\n\t\t// For confidence estimation, using internal_accuracy.\n\t\tdouble internal_accuracy = param.getParameter<double>(\"internal_accuracy\").first;\n\n\t\t// For peak finding and lambda estimation, using external_accuracy.\n\t\tdouble external_accuracy = param.getParameter<double>(\"external_accuracy\").first;\n\n\t\t// Calculate the mass of the candidate base peak.\n\t\t// Notice that there will be mechanism where there is electron capture.\n\t\tdouble mass = calculateMass(expr_base_pk->mz, charge * mode);\n\n\t\t// Create theoretical boundary. The boundary has been adjusted to fit the charge.\n\t\t//EnvelopBoundary env_bound = this->createBoundary(mass, charge);\n\t\tEnvelopBoundary& env_bound = pk_set.getBoundary();\n\n\t\t//std::cout << \"Up Boundary: \" << std::endl;\n\t\t//env_bound.first.printPeakList<peak_mz>();\n\t\t//std::cout << \"Down Boundary: \" << std::endl;\n\t\t//env_bound.second.printPeakList<peak_mz>();\n\n\t\t// Get a copy of the base peak iterator for further move operation.\n\t\t//RichPeakListByMZ::iterator iter = iter_mz;\n\t\tint stop_flag = 1;\n\n\t\t// Dynamically convert pk_set into vector of envelops.\n\t\tstd::pair<unsigned int, size_t> shift_count(0,1);\n\t\tsize_t max_env = 0;\n\n\t\t//std::advance(iter_mz, direction);\n\t\tif(direction < 0 && iter_mz == pks_mz.begin())\n\t\t\treturn 0;\n\t\tstd::advance(iter_mz, direction);\n\t\tif(direction > 0 && iter_mz == pks_mz.end())\n\t\t\treturn 0;\n\n\t\t// TBD: the program should efficiently location the position of most likely peak. instead of sequentially search for it.\n\t\twhile(1)\n\t\t{\n\n\n\t\t\tstd::cout << \"Shift: \" << shift << std::endl;\n\n\t\t\t// Get the boundary peaks at current shift.\n\t\t\tPeakPtr theo_pk1 = env_bound.getUpperBound().getPeakByShift<peak_intensity>(direction * shift);\n\t\t\tPeakPtr theo_pk2 = env_bound.getLowerBound().getPeakByShift<peak_intensity>(direction * shift);\n\n\t\t\t// No extension any more.\n\t\t\tif(theo_pk1->mz == 0.0 && theo_pk2->mz == 0.0)\n\t\t\t\tbreak;\n\n\t\t\tRichPeakPtr current_pk = *iter_mz;\n\t\t\tstd::cout << \"Examine peak: \" << current_pk->mz << std::endl;\n\n\t\t\t// Experimental distance from current peak to base peak.\n\t\t\t// Notice that the value might be negative.\n\t\t\tdouble expr_dist = abs(current_pk->mz - expr_base_pk->mz);\n\n\t\t\t// Theoretical distance from current peak to base peak. Adjusted for charged peak.\n\t\t\tdouble theo_dist1 = abs(env_bound.getUpperBound().getMassDifferenceByShift<peak_intensity>(0, shift));\n\t\t\tdouble theo_dist2 = abs(env_bound.getLowerBound().getMassDifferenceByShift<peak_intensity>(0, shift));\n\n\t\t\tdouble max_dist = theo_dist1;\n\t\t\tdouble min_dist = theo_dist2;\n\n\t\t\tif(max_dist < min_dist) {\n\t\t\t\tswap(min_dist, max_dist);\n\t\t\t}\n\n\t\t\tdouble error1 = 1e6 * (expr_dist - min_dist)/expr_base_pk->mz;\n\t\t\tdouble error2 = 1e6 * (expr_dist - max_dist)/expr_base_pk->mz;\n\t\t\t\n\t\t\tif(error1 < -1 * external_accuracy) {\n\t\t\t\t// Before the shift region: keep moving the iterator.\n\t\t\t\t// std::advance(iter_mz, direction); continue;\n\t\t\t} else if(error2 > external_accuracy) { \n\t\t\t\t// Beyond the shift region: update shift.\n\t\t\t\tif(stop_flag == 0) {\n\t\t\t\t\tshift++; stop_flag = 1; continue;\n\t\t\t\t} else {\n\t\t\t\t\t// break means no missing peak is allowed in the middle. This might be controlled by some parameter.\n\t\t\t\t\tstop_flag = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// A matching peak. Notice the effect of charge state.\n\t\t\t\tstd::cout << \"A matching peak!\" << std::endl;\n\t\t\t\t\n\t\t\t\tif(shift == shift_count.first) {\n\t\t\t\t\tshift_count.second++;\n\t\t\t\t} else {\n\t\t\t\t\t// Reset shift_count.\n\t\t\t\t\tshift_count = std::make_pair(shift, 1);\n\t\t\t\t}\n\n\t\t\t\t// Update maximum number of envelops.\n\t\t\t\tif(shift_count.second > max_env)\n\t\t\t\t\tmax_env = shift_count.second;\n\n\t\t\t\tstop_flag = 0;\n\t\t\t\t// Estimate the confidence of the mz in terms of estimating lambda.\n\t\t\t\tdouble diff = max_dist - min_dist;\n\n\t\t\t\t// Error window is used for confidence estimation.\n\t\t\t\tdouble err_win = internal_accuracy * expr_base_pk->mz * 1e-6;\n\t\t\t\tdouble prob = diff/(diff + 2*err_win);\n\n\t\t\t\t// Indicate the sign of the error window.\n\t\t\t\tint err_sign = (theo_dist1 < theo_dist2 ? -1 : 1);\n\n\t\t\t\t//: lambda_mz should always be in (0, 1). If lambda is closed to 1, the pattern is closed to no-sulfate boundary, and 0 for high-sulfate boundary.\n\t\t\t\tdouble lambda_mz = (expr_dist - theo_dist2+err_sign*err_win)/(theo_dist1 - theo_dist2 + 2*err_sign*err_win);\n\n\t\t\t\t// Round the abnormal lambda_mz to the boundary.\n\t\t\t\tif(lambda_mz > 1) {\n\t\t\t\t\tlambda_mz = 1.0;\n\t\t\t\t\tprob = 1.0;\n\t\t\t\t} else if(lambda_mz < 0) {\n\t\t\t\t\tlambda_mz = 0.0;\n\t\t\t\t\tprob = 1.0;\n\t\t\t\t}\n\n\t\t\t\t// TBD: estimate lambda_abd (within 5%) and delta_lambda.\n\t\t\t\t// Notice: lambda_abd can be < 0 or > 1.\n\t\t\t\tdouble lambda_abd = (current_pk->resolution/expr_base_pk->resolution - theo_pk2->intensity)/(theo_pk1->intensity - theo_pk2->intensity);\n\n\t\t\t\tInfoPeakPtr pk_infor = boost::make_shared<InfoPeak>(current_pk->resolution, lambda_mz, lambda_abd, prob);\n\t\t\t\t// Notice: The abundance information should be initialized during the establish of global lambda value.\n\t\t\t\t//pk_infor.adjusted_abundance = env_bound.getTheoreticalPeak(lambda_abd, shift).intensity;\n\t\t\t\t\n\t\t\t\tpk_set.addPeak(shift, current_pk, pk_infor);\n\t\t\t\t\n\t\t\t}\n\t\t\tif(direction < 0 && iter_mz == pks_mz.begin())\n\t\t\t\tbreak;\n\t\t\tstd::advance(iter_mz, direction);\n\t\t\tif(direction > 0 && iter_mz == pks_mz.end())\n\t\t\t\tbreak;\n\t\t}\n\t\treturn max_env;\n\t}\n\n\tvoid EnvelopFinder::updateEnvelopParameter(EnvelopPtr env)\n\t{\n\t\tEnvEntry base_entry = env_ref.getEntryByShift(env, 0);\n\n\t\t// 1.a Find lambda value for each of the peak.\n\t\tstd::vector<EnvEntry> peak_entries = env_ref.getEntryByEnvelop(env);\n\n\t\tdouble current_prob = 0.0;\n\t\tBOOST_FOREACH(EnvEntry& entry, peak_entries)\n\t\t{\n\t\t\tif(entry.info->prob > current_prob) {\n\t\t\t\tcurrent_prob = entry.info->prob;\n\t\t\t\tenv->lambda_mz = entry.info->lambda_mz;\n\t\t\t}\n\n\t\t}\n\t\t//// 1.b Normalize the confidence value.\n\t\t//double sum_confidence = 0.0;\n\t\t//for(std::vector<EnvEntry>::iterator iter = peak_entries.begin(); \n\t\t//\titer != peak_entries.end(); iter++)\n\t\t//\tsum_confidence += pow(iter->info->prob,2);\n\n\t\t//double lambda_mz = 0.0;\n\t\t//for(std::vector<EnvEntry>::iterator iter = peak_entries.begin(); \n\t\t//\titer != peak_entries.end(); iter++) {\n\t\t//\t\t// Pass base peak.\n\t\t//\t\tif(iter->getShift() == 0) \n\t\t//\t\t\tcontinue;\n\n\t\t//\t\tlambda_mz += pow(iter->info->prob,2)/sum_confidence *  iter->info->lambda_mz;\n\t\t//}\n\t\t//env->lambda_mz = lambda_mz;\n\n\t\t// 2. Update theoretical abundance from the lambda.\n\t\tfor(std::vector<EnvEntry>::iterator iter = peak_entries.begin(); \n\t\t\titer != peak_entries.end(); iter++) {\n\t\t\t// The adjusted abundance is initialized as the exp data.\n\t\t\titer->info->adjusted_abundance = iter->pk->area;\n\t\t}\n\t}\n\n\tvoid EnvelopFinder::updateEnvelopParameter( std::vector<EnvelopPtr> env_list )\n\t{\n\t\tBOOST_FOREACH(EnvelopPtr env, env_list) {\n\t\t\tthis->updateEnvelopParameter(env);\n\n\t\t\t//this->updateSplittingPotential(env);\n\t\t}\n\t}\n\n\tvoid EnvelopFinder::optimizeEnvelopSet(std::set<EnvelopPtr>& env_set, double last_score)\n\t{\n\t\t/* New version */\n\t\tthis->updateSplittingPotential(env_set);\n\t\tthis->updateFittingScore(env_set);\n\n\t\t// Get all the peaks. \n\t\tRichList pk_list = env_ref.getRichPeakList(env_set);\n\n\t\tRichPeakListByMZ& pks_mz = pk_list.getPeakListByType<peak_mz>();\n\n\t\tfor(RichPeakListByMZ::iterator iter = pks_mz.begin(); iter != pks_mz.end(); iter++)\n\t\t{\n\t\t\t// Split the peak based on fitting score & estimated abundance.\n\t\t\t// Notice that the identification of FP will also happen here.\n\t\t\tthis->splitPeak(*iter);\n\t\t}\n\t\t// Calculate the overall fitting scores.\n\t\tdouble next_score = this->updateFittingScore(env_set);\n\t\tstd::cout << \"Old score: \" << last_score << \"\\t\" << \"New score: \" << next_score << std::endl;\n\t\tif(abs(next_score - last_score)/last_score < 1e-5)\n\t\t\treturn;\n\t\telse\n\t\t\tthis->optimizeEnvelopSet(env_set, next_score);\n\t\t/* Old version */\n\n\t\t//std::set<RichPeak> processed_peak_set;\n\t\t//std::set<RichPeak>::iterator peak_iter;\n\n\t\t//// Generate fitting score for each envelop.\n\t\t//// Estimate scaling factor for each envelop.\n\t\t//this->updateSplittingPotential(env_pool);\n\t\t//this->updateFittingScore(env_pool);\n\n\t\t//sort(env_pool.begin(), env_pool.end(), Envelop::scoreLarger);\n\n\t\t//// Iterate over all envelops with intensity from high to low.\n\t\t//BOOST_FOREACH(EnvelopPtr& env, env_pool)\n\t\t//{\n\t\t//\t// If the base peak has been processed.\n\t\t//\tEnvEntry base_entry = env_ref.getBasePeakForEnvelop(env);\n\t\t//\t\n\t\t//\tpeak_iter = processed_peak_set.find(base_entry->pk);\n\t\t//\tif(peak_iter != processed_peak_set.end())\n\t\t//\t\tcontinue;\n\n\t\t//\t// Split the base peak.\n\t\t//\tbool status = this->splitPeak(base_entry->pk);\n\t\t//\tif(status) {\n\t\t//\t\tthis->updateSplittingPotential(env);\n\t\t//\t\tthis->updateFittingScore(env);\n\t\t//\t}\n\n\t\t//\t// Get all belonging peaks.\n\t\t//\tstd::vector<EnvEntry> entry_vec = env_ref.getEntryByEnvelop(env);\n\n\t\t//\t// Iterate over all peaks with intensity from high to low.\n\t\t//\tBOOST_FOREACH(EnvEntry& entry, entry_vec)\n\t\t//\t{\n\t\t//\t\tif(entry->getShift()==0)\n\t\t//\t\t\tcontinue;\n\t\t//\t\t// Split the peak based on 1. splitting potential and 2. scaling factor.\n\t\t//\t\tthis->splitPeak(entry->pk);\n\t\t//\t\t// Update the records.\n\t\t//\t\tprocessed_peak_set.insert(entry->pk);\n\t\t//\t}\n\t\t\t\n\t\t//}\t\t\n\t}\n\n\tvoid EnvelopFinder::updateSplittingPotential(EnvelopPtr env)\n\t{\n\t\t\n\t\t//double scaling_factor = env->scaling_factor;\n\n\t\t// Entry for base peak.\n\t\tEnvEntry& base_entry = env_ref.getEntryByShift(env, 0);\n\t\tstd::cout << \"The base peak is: \" << base_entry.pk->mz << std::endl;\n\n\t\t// Get all peaks included by the envelop.\n\t\tstd::vector<EnvEntry> entry_vec = env_ref.getEntryByEnvelop(env);\n\n\t\t// Update the scaling factor. The value for base peak should be 1.\n\t\tBOOST_FOREACH(EnvEntry& entry, entry_vec)\n\t\t{\n\t\t\tdouble expected_abundance = env_ref.getTheoreticalAbundance(entry);\n\t\t\t// Adjusted abunance / Theoretical abundance.\n\t\t\tdouble scaling_factor = entry.info->adjusted_abundance/expected_abundance;\n\t\t\tif(scaling_factor < env->scaling_factor)\n\t\t\t\tenv->scaling_factor = scaling_factor;\n\t\t}\n\n\t\t// Update the adjusted abundance.\n\t\t// 1. Update base entry.\n\t\tbase_entry.info->adjusted_abundance *= env->scaling_factor;\n\t\t// 2. Update all the rest of the peaks.\n\t\tBOOST_FOREACH(EnvEntry& entry, entry_vec)\n\t\t{\n\t\t\tif(entry.getShift()==0)\n\t\t\t\tcontinue;\n\n\t\t\tentry.info->adjusted_abundance = env_ref.getTheoreticalAbundance(entry);\n\t\t}\n\t\t\n\n\n\t\t//// Iterate over all theoretical peaks (except base peak), calculate their relative shift.\n\t\t//double total_share = 0.0;\n\t\t//std::map<int, PeakPtr> pk_map = env->getTheoreticalPeaks();\n\t\t//for(std::map<int, PeakPtr>::iterator iter = pk_map.begin(); \n\t\t//\titer != pk_map.end(); iter++) \n\t\t//{\n\t\t//\ttotal_share += iter->second->intensity;\n\t\t//}\n\t\t//\t\n\t\t//double base_adjusted_abd = 0.0;\n\t\t//for(std::map<int, PeakPtr>::iterator iter = pk_map.begin(); \n\t\t//\titer != pk_map.end(); iter++)\n\t\t//{\n\t\t//\tint shift = iter->first; PeakPtr pk = iter->second;\n\n\t\t//\t// Get entry corresponding to the shift. Notice the problem if shift does not exist for the envelop..\n\t\t//\tEnvEntry entry = env_ref.getEntryByShift(env, shift);\n\t\n\t\t//\t// If EnvEntry is empty. Which means the experimental peak corresponds to the shift doesn't show up.\n\t\t//\tif(entry.isEmpty()) continue;\n\n\t\t//\tentry.info->relative_share = pk->intensity / total_share;\n\n\t\t//\tdouble expected_abundance = env_ref.getTheoreticalAbundance(entry);\n\n\t\t//\tif(expected_abundance > entry.info->adjusted_abundance) {\n\t\t//\t\t// Potential overlapping event for base peak. Scale the base peak.\n\t\t//\t\tbase_adjusted_abd += base_entry.info->adjusted_abundance * (entry.info->adjusted_abundance / expected_abundance) * entry.info->relative_share;\n\t\t//\t}\n\t\t//\t// Update adjusted abundance.\n\t\t//\tentry.info->adjusted_abundance = expected_abundance;\n\t\t//}\n\n\t\t//// Update base peak information.\n\t\t//base_entry.info->adjusted_abundance = base_adjusted_abd;\n\t}\n\n\tvoid EnvelopFinder::updateSplittingPotential( std::vector<EnvEntry> entry_vec )\n\t{ \n\t\tBOOST_FOREACH(EnvEntry entry, entry_vec)\n\t\t\tthis->updateSplittingPotential(entry.env);\n\t}\n\tvoid EnvelopFinder::updateSplittingPotential(std::set<EnvelopPtr>& env_set)\n\t{\n\t\tBOOST_FOREACH(EnvelopPtr env, env_set)\n\t\t\tthis->updateSplittingPotential(env);\n\t}\n\n\tdouble EnvelopFinder::updateFittingScore(EnvelopPtr env)\n\t{\n\t\tstd::vector<EnvEntry> entry_vec = env_ref.getEntryByEnvelop(env);\n\t\t//RichPeakPtr base_pk = env_ref.getBasePeakForEnvelop(env);\n\t\tEnvEntry base_entry = env_ref.getEntryByShift(env, 0);\n\t\t\n\t\tdouble fitting_score = 0.0;\n\t\tBOOST_FOREACH(EnvEntry& entry, entry_vec)\n\t\t{\n\t\t\t// For base peak, intensity_shift and mz_shift is always 1.\n\t\t\tif(entry.getShift()==0) {\t\t\t\n\t\t\t\tfitting_score += sqrt(base_entry.info->adjusted_abundance);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble expected_abundance = env_ref.getTheoreticalAbundance(entry);\n\t\t\t// The fitting score comes from 3 parts: \n\t\t\t// 1. the shift of intensity: abs(E-T)/T.\n\t\t\tdouble intensity_shift = 1.0 - abs(expected_abundance - entry.info->adjusted_abundance)/expected_abundance;\n\t\t\tif(intensity_shift < 0)\n\t\t\t\tintensity_shift = 0.0;\n\t\t\t//std::cout << \"Intensity shift: \" << intensity_shift << std::endl;\n\t\t\t\t\n\t\t\t// 2. the relative shift of mz.\n\t\t\tdouble internal_accuracy = param.getParameter<double>(\"internal_accuracy\").first;\n\t\t\t\n\t\t\tdouble mz_shift = 1.0 - abs(entry.pk->mz - base_entry.pk->mz - entry.env->getTheoreticalMZDistance(0, entry.getShift()))/(entry.env->getWindowSizeByShift(entry.getShift()));\n\t\t\t//std::cout << \"MZ shift: \" << mz_shift << std::endl;\n\n\t\t\t// 3. the square root of expected_abundance.\n\t\t\tdouble weight = sqrt(expected_abundance);\n\t\t\t//std::cout << \"Weight: \" << weight << std::endl;\n\t\t\tfitting_score += weight * intensity_shift * mz_shift;\n\t\t}\n\t\t//std::cout << \"Fitting score: \" << fitting_score << std::endl;\n\t\tenv->fitting_score = fitting_score;\n\t\treturn fitting_score;\n\t} \n\n\tdouble EnvelopFinder::updateFittingScore( std::vector<EnvEntry> entry_vec)\n\t{\n\t\tdouble sum_score = 0.0;\n\t\tBOOST_FOREACH(EnvEntry& entry, entry_vec)\n\t\t\tsum_score += this->updateFittingScore(entry.env);\n\t\treturn sum_score;\n\t}\n\n\tdouble EnvelopFinder::updateFittingScore(std::set<EnvelopPtr>& env_set)\n\t{\n\t\tdouble sum_score = 0.0;\n\t\tBOOST_FOREACH(EnvelopPtr env, env_set)\n\t\t\tsum_score += this->updateFittingScore(env);\n\t\treturn sum_score;\n\t}\n\n\tvoid EnvelopFinder::adjustLambdaFromProfile( EnvelopPtr env )\n\t{\n\t\tdouble last_score = this->updateFittingScore(env);\n\t\t// The value of lambda_bound has to be in between 0.0 and 1.0\n\t\tdouble lambda_bound = 0.0;\n\n\t\twhile(1)\n\t\t{\n\t\t\t// Adjust lambda. Notice the direction.\n\t\t\tenv->lambda_mz = (lambda_bound + env->lambda_mz)/2;\n\n\t\t\t// Update splitting score.\n\t\t\tthis->updateSplittingPotential(env);\n\n\t\t\tdouble new_score = this->updateFittingScore(env);\n\n\t\t\tdouble score_diff = new_score - last_score;\n\t\t\t\n\t\t\t// Converge.\n\t\t\tif(abs(score_diff) < 1e-6)\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tif(score_diff > 0.0) {\n\t\t\t\t\tenv->lambda_mz = (lambda_bound + env->lambda_mz)/2;\n\t\t\t} else {\n\t\t\t\t\t// Change the bound.\n\t\t\t\t\tlambda_bound = 1.0-lambda_bound;\n\t\t\t\t\tenv->lambda_mz = (lambda_bound + env->lambda_mz)/2;\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\tvoid EnvelopFinder::splitPeak(RichPeakPtr pk)\n\t{\n\t\t// Get all connecting envelops.\n\t\tstd::vector<EnvEntry> entry_vec = env_ref.getEntryByPeak(pk);\n\n\t\tif(entry_vec.size() == 1) // No need to split for single envelop.\n\t\t\treturn;\n\t\telse if(entry_vec.size() == 0)\n\t\t\tthrow std::runtime_error(\"Undefined peak in the dictionary\");\n\t\telse\n\t\t\t;\n\n\t\tdouble splitting_score = 0.0;\n\t\t\n\t\tBOOST_FOREACH(EnvEntry& entry, entry_vec)\n\t\t{\n\t\t\t// splitting_score += entry.info->adjusted_abundance;\n\t\t\tsplitting_score += sqrt(entry.env->fitting_score * entry.info->adjusted_abundance);\n\t\t}\n\t\t\t\n\t\t// Split the peak.\n\t\tBOOST_FOREACH(EnvEntry& entry, entry_vec)\n\t\t{\n\t\t\tdouble scale_coef = sqrt(entry.env->fitting_score * entry.info->adjusted_abundance)/ splitting_score;\n\n\t\t\t// Update the estimated abundance.\n\t\t\tentry.info->adjusted_abundance = pk->resolution * scale_coef;\n\n\t\t\tenv_ref.printEnvelopInformation(entry.env);\n\t\t}\n\n\t}\n\n\tvoid EnvelopFinder::printEnvelop( EnvelopPtr env )\n\t{\n\t\tstd::cout << \"Envelop ID: \" << env->id << std::endl;\n\t\tstd::cout << \"Charge: \" << env->charge_state << std::endl;\n\t\tstd::cout << \"Lambda: \" << env->lambda_mz << std::endl;\n\t\tstd::cout << \"Score: \" << env->fitting_score << std::endl;\n\t\tstd::cout << std::endl;\n\t\t// Peak information.\n\t\tstd::cout << \"Covered peaks:\" << std::endl;\n\t\tstd::cout << \"Shift\\tMZ\\tEXP_ABD\\tFIT_ABD\" << std::endl;\n\n\t\t// Get all peaks.\n\t\tstd::vector<EnvEntry> pk_entries = env_ref.getEntryByEnvelop(env);\n\t\tBOOST_FOREACH(EnvEntry& pk_entry, pk_entries)\n\t\t{\n\t\t\tstd::cout << pk_entry.getShift() << \"\\t\" << pk_entry.pk->mz << \"\\t\"\n\t\t\t\t<< pk_entry.pk->resolution << \"\\t\" << pk_entry.info->adjusted_abundance\n\t\t\t\t<< std::endl;\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\t//void EnvelopFinder::optimizeEnvelopSet(RichList& pk_list)\n\t//{\n\t//\t// 1. Iterate over peaks with m/z from low to high\n\t//\tRichPeakListByMZ& pks_by_mz = pk_list.getPeakListSortedByType<peak_mz>();\n\n\t//\tRichPeakListByMZ::iterator iter_mz = pks_by_mz.begin();\n\n\t//\t// Envelop set and corresponding fitting score.\n\t//\tEnvelopSetCollection last_frontier;\n\n\t//\t// TBD: how to decide the cluster group will end.\n\t//\tfor(; iter_mz != pks_by_mz.end(); iter_mz++)\n\t//\t{\n\t//\t\t// 2. For each peak, find all connecting envelops.\n\t//\t\tstd::vector<EnvEntry> entry_vec = env_ref.getEntryByPeak(*iter_mz);\n\n\t//\t\t// Empty information. Consider storing the information with a separate container.\n\t//\t\tif(entry_vec.size() == 0)\n\t//\t\t\tcontinue;\n\n\t//\t\tstd::vector<std::set<EnvelopPtr> > env_set_collection;\n\t//\t\tfor(size_t i = 0; i < entry_vec.size()-1; i++)\n\t//\t\t\tfor(size_t j=i; j<entry_vec.size(); j++)\n\t//\t\t\t{\n\t//\t\t\t\tstd::set<EnvelopPtr> temp_env;\n\t//\t\t\t\ttemp_env.insert(entry_vec[i]->env);\n\n\t//\t\t\t\tif(i != j) // Not just pairs.\n\t//\t\t\t\t\ttemp_env.insert(entry_vec[j]->env);\n\n\t//\t\t\t\tenv_set_collection.insert(temp_env);\n\t//\t\t\t}\n\n\t//\t\t// New frontier. \n\t//\t\tif(last_frontier.size() == 0)\n\t//\t\t{\n\t//\t\t\tstd::vector<std::set<EnvelopPtr> >::iterator iter = env_set_collection.begin();\n\t//\t\t\tfor(; iter != env_set_collection.end(); iter++)\n\t//\t\t\t{\n\t//\t\t\t\tdouble temp_score = this->calculateFittingScore(*iter);\n\t//\t\t\t\tlast_frontier.insert(std::make_pair(temp_score, *iter));\n\t//\t\t\t}\n\t//\t\t\tcontinue;\n\t//\t\t}\n\n\t//\t\tEnvelopSetCollection next_frontier;\n\t//\t\t// Update current frontier.\n\t//\t\tfor(EnvelopSetCollection::iterator fron_iter = last_frontier.begin(); fron_iter != last_frontier.end(); fron_iter++)\n\t//\t\t{\n\t//\t\t\tBOOST_FOREACH(std::set<EnvelopPtr>& env_set, env_set_collection)\n\t//\t\t\t{\n\t//\t\t\t\tstd::set<EnvelopPtr> temp_set(fron_iter->second);\n\t//\t\t\t\t// Append the set.\n\t//\t\t\t\tset_union(temp_set.begin(), temp_set.end(), \n\t//\t\t\t\t\tenv_set.begin(), env_set.end(),\n\t//\t\t\t\t\tinserter(temp_set, temp_set.begin()));\n\n\t//\t\t\t\t// Compare the fitting score between std::vector<EnvelopPtr> with and without new current envelops.\n\t//\t\t\t\tdouble score1 = fron_iter->first;\n\t//\t\t\t\tdouble score2 = this->calculateFittingScore(new_set);\n\n\t//\t\t\t\tif(score2 > score1)\n\t//\t\t\t\t\tnext_frontier.insert(std::make_pair(score2, temp_set));\n\t//\t\t\t\telse\n\t//\t\t\t\t\tnext_frontier.insert(std::make_pair(score1, fron_iter->second));\n\t//\t\t\t}\n\t//\t\t}\n\n\t//\t\tlast_frontier = next_frontier;\n\t//\t\n\t//\t}\n\n\t//\t// Select the set with maximum score. \n\t//\tstd::set<EnvelopPtr>& winner_set = last_frontier.rbegin()->second;\n\t//\t\n\t//\tenv_pool.insert(env_pool.end(), winner_set.begin(), winner_set.end());\n\t//\t\n\t//}\n\n\t//double EnvelopFinder::calculateFittingScore( std::set<EnvelopPtr> env_set )\n\t//{\n\t//\t/* Estimate the abundance based on current set selection. */\n\t//\t\n\n\n\t//\tdouble total_score = 0.0;\n\t//\tBOOST_FOREACH(EnvelopPtr& env, env_set)\n\t//\t{\n\t//\t\ttotal_score += this->calculateFittingScore(env);\n\t//\t}\n\t//\treturn total_score;\n\t//}\n\n\t//double EnvelopFinder::calculateFittingScore(EnvelopPtr env)\n\t//{\n\t//\tstd::vector<EnvEntry> entry_vec = env_ref.getEntryByEnvelop(env);\n\t//\t\n\t//\tif(entry_vec.size()==0)\n\t//\t\treturn 0.0;\n\n\t//\t// Get base entry.\n\t//\tEnvEntry base_entry = env_ref.getEntryByShift(env, 0);\n\n\t//\tdouble fitting_score = 0.0;\n\t//\tBOOST_FOREACH(EnvEntry& entry, entry_vec)\n\t//\t{\n\t//\t\t// For base peak, intensity_shift and mz_shift is always 1.\n\t//\t\tif(entry.getShift()==0) {\n\t//\t\t\tfitting_score += sqrt(base_entry.info->adjusted_abundance);\n\t//\t\t\tcontinue;\n\t//\t\t}\n\n\t//\t\tdouble expected_abundance = env_ref.getTheoreticalAbundance(entry);\n\t//\t\t\n\t//\t\t// The fitting score comes from 3 parts: \n\t//\t\t// 1. the shift of intensity: abs(E-T)/T.\n\t//\t\tdouble intensity_shift = 1.0 - abs(expected_abundance - entry.info->adjusted_abundance)/expected_abundance;\n\t//\t\tif(intensity_shift < 0)\n\t//\t\t\tintensity_shift = 0.0;\n\n\t//\t\t// 2. the relative shift of mz. Here the accuracy depends on the position of the peak in the envelop.\n\t//\t\tdouble mz_shift = 1.0 - abs(entry.pk->mz - base_entry.pk->mz - entry.env->getTheoreticalMZDistance(0, entry.getShift()))/(entry.env->getWindowSizeByShift(entry.getShift()));\n\n\t//\t\t// 3. the square root of expected_abundance.\n\t//\t\tdouble weight = sqrt(expected_abundance);\n\n\t//\t\tfitting_score += weight * intensity_shift * mz_shift;\n\t//\t}\n\n\t//\tenv->fitting_score = fitting_score;\n\t//\treturn fitting_score;\n\t//}\n}", "meta": {"hexsha": "34f38064d9e6a3872a58c484f7e4de36bdcf9a0f", "size": 30970, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GAG/src/GAGPL/SPECTRUM/EnvelopFinder.cpp", "max_stars_repo_name": "hh1985/multi_hs_seq", "max_stars_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-03T14:44:45.000Z", "max_stars_repo_stars_event_max_datetime": "2015-04-15T13:38:39.000Z", "max_issues_repo_path": "GAG/src/GAGPL/SPECTRUM/EnvelopFinder.cpp", "max_issues_repo_name": "hh1985/multi_hs_seq", "max_issues_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GAG/src/GAGPL/SPECTRUM/EnvelopFinder.cpp", "max_forks_repo_name": "hh1985/multi_hs_seq", "max_forks_repo_head_hexsha": "9cf4e70fb59283da30339499952c43a0684f7e77", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0704070407, "max_line_length": 187, "alphanum_fraction": 0.684178237, "num_tokens": 8958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.21620263719888966}}
{"text": "/** kmeans.cc\n    Jeremy Barnes, 16 December 2014\n    Copyright (c) 2014 mldb.ai inc.  All rights reserved.\n\n    This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n    Implementation of an KMEANS algorithm for embedding of a dataset.\n*/\n\n#include \"mldb/utils/distribution_simd.h\"\n#include \"kmeans_interface.h\"\n#include \"mldb/builtin/matrix.h\"\n#include \"mldb/core/mldb_engine.h\"\n#include \"mldb/core/dataset.h\"\n#include \"mldb/utils/distribution.h\"\n#include <boost/multi_array.hpp>\n#include \"mldb/base/scope.h\"\n#include \"mldb/base/parallel.h\"\n#include \"mldb/utils/pair_utils.h\"\n#include \"mldb/arch/timers.h\"\n#include \"mldb/arch/simd_vector.h\"\n#include \"mldb/utils/vector_utils.h\"\n#include \"mldb/types/basic_value_descriptions.h\"\n#include \"mldb/plugins/jml/kmeans.h\"\n#include \"mldb/sql/sql_expression.h\"\n#include \"mldb/builtin/sql_config_validator.h\"\n#include \"mldb/core/analytics.h\"\n#include \"mldb/types/any_impl.h\"\n#include \"mldb/types/optional_description.h\"\n#include \"mldb/vfs/fs_utils.h\"\n#include \"mldb/vfs/filter_streams.h\"\n\nusing namespace std;\n\n\n\nnamespace MLDB {\n\nDEFINE_STRUCTURE_DESCRIPTION(KmeansConfig);\n\n\nKmeansConfigDescription::\nKmeansConfigDescription()\n{\n    Optional<PolyConfigT<Dataset> > optional;\n    optional.emplace(PolyConfigT<Dataset>().\n                     withType(KmeansConfig::defaultOutputDatasetType));\n\n    addField(\"trainingData\", &KmeansConfig::trainingData,\n             \"Specification of the data for input to the k-means procedure.  This should be \"\n             \"organized as an embedding, with each selected row containing the same \"\n             \"set of columns with numeric values to be used as coordinates.  The select statement \"\n             \"does not support groupby and having clauses.\");\n    addField(\"outputDataset\", &KmeansConfig::output,\n             \"Dataset for cluster assignment.  This dataset will contain the same \"\n             \"row names as the input dataset, but the coordinates will be replaced \"\n             \"by a single column giving the cluster number that the row was assigned to.\",\n              optional);\n    addField(\"centroidsDataset\", &KmeansConfig::centroids,\n             \"Dataset in which the centroids will be recorded.  This dataset will \"\n             \"have the same coordinates (columns) as those selected from the input \"\n             \"dataset, but will have one row per cluster, providing the centroid of \"\n             \"the cluster.\",\n             optional);\n    addField(\"numInputDimensions\", &KmeansConfig::numInputDimensions,\n             \"Number of dimensions from the input to use (-1 = all).  This limits \"\n             \"the number of columns used.  Columns will be ordered alphabetically \"\n             \"and the lowest ones kept.\",\n             -1);\n    addField(\"numClusters\", &KmeansConfig::numClusters,\n             \"Number of clusters to create.  This will provide the total number of \"\n             \"centroids created.  There must be at least as many rows selected as \"\n             \"clusters.\", 10);\n    addField(\"maxIterations\", &KmeansConfig::maxIterations,\n             \"Maximum number of iterations to perform.  If no convergeance is \"\n             \"reached within this number of iterations, the current clustering \"\n             \"will be returned.\", 100);\n    addField(\"metric\", &KmeansConfig::metric,\n             \"Metric space in which the k-means distances will be calculated. \"\n             \"Normally this will be Cosine for an orthonormal basis, and \"\n             \"Euclidian for another basis\",\n             METRIC_COSINE);\n    addField(\"modelFileUrl\", &KmeansConfig::modelFileUrl,\n             \"URL where the model file (with extension '.kms') should be saved. \"\n             \"This file can be loaded by the ![](%%doclink kmeans function). \"\n             \"This parameter is optional unless the `functionName` parameter is used.\");\n    addField(\"functionName\", &KmeansConfig::functionName,\n             \"If specified, an instance of the ![](%%doclink kmeans function) of this name will be created using \"\n             \"the trained model. Note that to use this parameter, the `modelFileUrl` must \"\n             \"also be provided.\");\n    addParent<ProcedureConfig>();\n\n    onPostValidate = chain(validateQuery(&KmeansConfig::trainingData,\n                                         MustContainFrom(),\n                                         NoGroupByHaving()),\n                           validateFunction<KmeansConfig>());\n}\n\n// TODO: see http://www.eecs.tufts.edu/~dsculley/papers/fastkmeans.pdf\n\nnamespace {\n\nML::KMeansMetric * makeMetric(MetricSpace metric)\n{\n    switch (metric) {\n    case METRIC_EUCLIDEAN:\n        return new ML::KMeansEuclideanMetric();\n        break;\n    case METRIC_COSINE:\n        return new ML::KMeansCosineMetric();\n        break;\n    default:\n        throw MLDB::Exception(\"Unknown kmeans metric type\");\n    }\n}\n\n} // file scope\n\n/*****************************************************************************/\n/* KMEANS PROCEDURE                                                           */\n/*****************************************************************************/\n\nKmeansProcedure::\nKmeansProcedure(MldbEngine * owner,\n               PolyConfig config,\n               const std::function<bool (const Json::Value &)> & onProgress)\n    : Procedure(owner)\n{\n    kmeansConfig = config.params.convert<KmeansConfig>();\n}\n\nAny\nKmeansProcedure::\ngetStatus() const\n{\n    return Any();\n}\n\nRunOutput\nKmeansProcedure::\nrun(const ProcedureRunConfig & run,\n      const std::function<bool (const Json::Value &)> & onProgress) const\n{\n    auto runProcConf = applyRunConfOverProcConf(kmeansConfig, run);\n\n    // an empty url is allowed but other invalid urls are not\n    if(!runProcConf.modelFileUrl.empty() && !runProcConf.modelFileUrl.valid()) {\n        throw AnnotatedException(400, \"modelFileUrl \\\"\" +\n                                  runProcConf.modelFileUrl.toUtf8String()\n                                  + \"\\\" is not valid\");\n    }\n\n    if (!runProcConf.modelFileUrl.empty()) {\n        checkWritability(runProcConf.modelFileUrl.toDecodedString(), \"modelFileUrl\");\n    }\n\n    auto onProgress2 = [&] (const Json::Value & progress)\n        {\n            Json::Value value;\n            value[\"dataset\"] = progress;\n            return onProgress(value);\n        };\n\n    SqlExpressionMldbScope context(engine);\n\n    ConvertProgressToJson convertProgressToJson(onProgress);\n    auto embeddingOutput = getEmbedding(*runProcConf.trainingData.stm,\n                                        context,\n                                        runProcConf.numInputDimensions,\n                                        convertProgressToJson);\n\n    std::vector<std::tuple<RowHash, RowPath, std::vector<double>,\n                           std::vector<ExpressionValue> > > & rows\n        = embeddingOutput.first;\n    std::vector<KnownColumn> & vars = embeddingOutput.second;\n\n    std::vector<ColumnPath> columnNames;\n    for (auto & v: vars) {\n        columnNames.push_back(v.columnName);\n    }\n\n    std::vector<distribution<float> > vecs;\n\n    for (unsigned i = 0;  i < rows.size();  ++i) {\n        vecs.emplace_back(distribution<float>(std::get<2>(rows[i]).begin(),\n                                                  std::get<2>(rows[i]).end()));\n    }\n\n    if (vecs.size() == 0)\n        throw AnnotatedException(400, \"Kmeans training requires at least 1 datapoint. \"\n                                  \"Make sure your dataset is not empty and that your WHERE expression \"\n                                  \"does not filter all the rows\");\n\n    ML::KMeans kmeans;\n    kmeans.metric.reset(makeMetric(runProcConf.metric));\n\n    vector<int> inCluster;\n\n    int numClusters = runProcConf.numClusters;\n    int numIterations = runProcConf.maxIterations;\n\n    kmeans.train(vecs, inCluster, numClusters, numIterations);\n\n    bool saved = false;\n    if (!runProcConf.modelFileUrl.empty()) {\n        try {\n            makeUriDirectory(runProcConf.modelFileUrl.toDecodedString());\n            Json::Value md;\n            md[\"algorithm\"] = \"MLDB k-Means model\";\n            md[\"version\"] = 1;\n            md[\"columnNames\"] = jsonEncode(columnNames);\n\n            filter_ostream stream(runProcConf.modelFileUrl);\n            stream << md.toString();\n            MLDB::DB::Store_Writer writer(stream);\n            kmeans.serialize(writer);\n            saved = true;\n        }\n        catch (const std::exception & exc) {\n            throw AnnotatedException(400, \"Error saving kmeans centroids at location'\" +\n                                      runProcConf.modelFileUrl.toString() + \"': \" +\n                                      exc.what());\n        }\n    }\n\n    if (runProcConf.output.get()) {\n\n        PolyConfigT<Dataset> outputDataset = *runProcConf.output;\n        if (outputDataset.type.empty())\n            outputDataset.type = KmeansConfig::defaultOutputDatasetType;\n\n        auto output = createDataset(engine, outputDataset, onProgress2, true /*overwrite*/);\n\n        Date applyDate = Date::now();\n\n        for (unsigned i = 0;  i < rows.size();  ++i) {\n            std::vector<std::tuple<ColumnPath, CellValue, Date> > cols;\n            cols.emplace_back(ColumnPath(\"cluster\"), inCluster[i], applyDate);\n            output->recordRow(std::get<1>(rows[i]), cols);\n        }\n\n        output->commit();\n    }\n\n    if (runProcConf.centroids.get()) {\n\n        PolyConfigT<Dataset> centroidsDataset = *runProcConf.centroids;\n        if (centroidsDataset.type.empty())\n            centroidsDataset.type = KmeansConfig::defaultOutputDatasetType;\n\n        auto centroids = createDataset(engine, centroidsDataset, onProgress2, true /*overwrite*/);\n\n        Date applyDate = Date::now();\n\n        for (unsigned i = 0;  i < kmeans.clusters.size();  ++i) {\n            auto & cluster = kmeans.clusters[i];\n\n            std::vector<std::tuple<ColumnPath, CellValue, Date> > cols;\n\n            for (unsigned j = 0;  j < cluster.centroid.size();  ++j) {\n                cols.emplace_back(columnNames[j], cluster.centroid[j], applyDate);\n            }\n\n            centroids->recordRow(RowPath(MLDB::format(\"%i\", i)), cols);\n        }\n\n        centroids->commit();\n    }\n\n    if(!runProcConf.functionName.empty()) {\n        if (saved) {\n            KmeansFunctionConfig funcConf;\n            funcConf.modelFileUrl = runProcConf.modelFileUrl;\n\n            PolyConfig kmeansFuncPC;\n            kmeansFuncPC.type = \"kmeans\";\n            kmeansFuncPC.id = runProcConf.functionName;\n            kmeansFuncPC.params = funcConf;\n\n            createFunction(engine, kmeansFuncPC, onProgress, true);\n        } else {\n            throw AnnotatedException(400, \"Can't create kmeans function '\" +\n                                      runProcConf.functionName.rawString() +\n                                      \"'. Have you provided a valid modelFileUrl?\",\n                                      \"modelFileUrl\", runProcConf.modelFileUrl.toString());\n        }\n    }\n\n    return Any();\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(KmeansFunctionConfig);\n\nKmeansFunctionConfigDescription::\nKmeansFunctionConfigDescription()\n{\n    addField(\"modelFileUrl\", &KmeansFunctionConfig::modelFileUrl,\n             \"URL of the model file (with extension '.kms') to load. \"\n             \"This file is created by the ![](%%doclink kmeans.train procedure).\");\n\n    onPostValidate = [] (KmeansFunctionConfig * cfg,\n                         JsonParsingContext & context) {\n        // this includes empty url\n        if(!cfg->modelFileUrl.valid()) {\n            throw MLDB::Exception(\"modelFileUrl \\\"\" + cfg->modelFileUrl.toString()\n                                + \"\\\" is not valid\");\n        }\n    };\n}\n\n\n/*****************************************************************************/\n/* KMEANS FUNCTION                                                           */\n/*****************************************************************************/\n\nDEFINE_STRUCTURE_DESCRIPTION(KmeansFunctionArgs);\n\nKmeansFunctionArgsDescription::\nKmeansFunctionArgsDescription()\n{\n    addField(\"embedding\", &KmeansFunctionArgs::embedding,\n             \"Embedding values for the k-means function.  The column names in \"\n             \"this embedding must match those used in the original kmeans \"\n             \"dataset.\");\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(KmeansExpressionValue);\n\nKmeansExpressionValueDescription::KmeansExpressionValueDescription()\n{\n    addField(\"cluster\", &KmeansExpressionValue::cluster,\n             \"Index of the row in the `centroids` dataset whose columns describe \"\n             \"the point which is closest to the input according to the `metric` \"\n             \"specified in training.\");\n}\n\n\nstruct KmeansFunction::Impl {\n    ML::KMeans kmeans;\n    std::vector<ColumnPath> columnNames;\n\n    Impl(const Url & modelFileUrl)\n    {\n        filter_istream stream(modelFileUrl);\n        std::string firstLine;\n        std::getline(stream, firstLine);\n        Json::Value md = Json::parse(firstLine);\n        if (md[\"algorithm\"] != \"MLDB k-Means model\") {\n            throw AnnotatedException(400, \"Model file is not a k-means model\");\n        }\n        if (md[\"version\"].asInt() != 1) {\n            throw AnnotatedException(400, \"k-Means model version is wrong\");\n        }\n        columnNames = jsonDecode<std::vector<ColumnPath> >(md[\"columnNames\"]);\n        \n        MLDB::DB::Store_Reader store(stream);\n        kmeans.reconstitute(store);\n    }\n};\n\nKmeansFunction::\nKmeansFunction(MldbEngine * owner,\n               PolyConfig config,\n               const std::function<bool (const Json::Value &)> & onProgress)\n    : BaseT(owner, config)\n{\n    functionConfig = config.params.convert<KmeansFunctionConfig>();\n\n    impl.reset(new Impl(functionConfig.modelFileUrl));\n\n    dimension = impl->kmeans.clusters[0].centroid.size();\n}\n\nKmeansExpressionValue \nKmeansFunction::\ncall(KmeansFunctionArgs input) const\n{\n    Date ts = input.embedding.getEffectiveTimestamp();\n\n    return {ExpressionValue\n            (impl->kmeans.assign\n             (input.embedding.getEmbedding(impl->columnNames.data(),\n                                           impl->columnNames.size())\n              .cast<float>()),\n             ts)};\n}\n\nnamespace {\n\nRegisterProcedureType<KmeansProcedure, KmeansConfig>\nregKmeans(builtinPackage(),\n          \"Simple clustering algorithm based on cluster centroids in embedding space\",\n          \"procedures/KmeansProcedure.md.html\");\n\nRegisterFunctionType<KmeansFunction, KmeansFunctionConfig>\nregKmeansFunction(builtinPackage(),\n                  \"kmeans\",\n                  \"Apply a k-means clustering to new data\",\n                  \"functions/Kmeans.md.html\");\n\n} // file scope\n\n} // namespace MLDB\n\n", "meta": {"hexsha": "76aec64f63e3919c1608815742a64971fc405b16", "size": 14692, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/kmeans_interface.cc", "max_stars_repo_name": "mldbai/mldb", "max_stars_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 665.0, "max_stars_repo_stars_event_min_datetime": "2015-12-09T17:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:46:46.000Z", "max_issues_repo_path": "plugins/jml/kmeans_interface.cc", "max_issues_repo_name": "mldbai/mldb", "max_issues_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 797.0, "max_issues_repo_issues_event_min_datetime": "2015-12-09T19:48:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T02:19:47.000Z", "max_forks_repo_path": "plugins/jml/kmeans_interface.cc", "max_forks_repo_name": "mldbai/mldb", "max_forks_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 103.0, "max_forks_repo_forks_event_min_datetime": "2015-12-25T04:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T02:55:22.000Z", "avg_line_length": 36.3663366337, "max_line_length": 114, "alphanum_fraction": 0.6025728288, "num_tokens": 3145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.2161912995394521}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n#ifndef SUM_H\n#define SUM_H\n\n#include <type_traits>\n#include <cstddef>\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\n#define SUM(...) (get_sum(__VA_ARGS__)(__VA_ARGS__))\n\n#define get_sum(...) get_sum_macro(__VA_ARGS__, sum_user_t, sum_ptrdiff_t,)\n\n#define get_sum_macro(_1, _2, _3, _4, _5, name, ...) name\n\n#define sum_ptrdiff_t(idx, ini, fin, expr)      \\\n    sum<std::ptrdiff_t>((ini), (fin), [&](std::ptrdiff_t (idx)) { return (expr); })\n\n#define sum_user_t(type, idx, ini, fin, expr)\t\\\n    sum<type>((ini), (fin), [&](type (idx)) { return (expr); })\n\ntemplate<typename T>\nstruct is_eigen_type\n{\n    static constexpr auto value =\n\tstd::is_base_of<Eigen::EigenBase<T>, T>::value;\n};\n\ntemplate<typename Idx, typename Function, bool isEigenType>\nstruct EvalEigenXprImpl {\n    static auto eval(Idx i, Function f) -> decltype(f(i)) {\n\treturn f(i);\n    }\n};\n\ntemplate<typename Idx, typename Function>\nstruct EvalEigenXprImpl<Idx, Function, true> {\n    static auto eval(Idx i, Function f) ->\n\ttypename std::remove_reference<decltype(f(i).eval())>::type\n    {\n\treturn f(i).eval();\n    }\n};\n\ntemplate<typename Idx, typename Function>\nauto EvalEigenXpr(Idx i, Function f) ->\n    decltype(\n\tEvalEigenXprImpl<Idx, Function, is_eigen_type<decltype(f(i))>::value>::\n\teval(i, f))\n{\n    return\n\tEvalEigenXprImpl<Idx, Function, is_eigen_type<decltype(f(i))>::value>::\n\teval(i, f);\n}\n\ntemplate<typename T, bool isEigenType>\nstruct create_zero {\n    static const T zero() {\n\treturn T();\n    }\n};\n\ntemplate<typename T>\nstruct create_zero<T, true> {\n    static const T zero() {\n\tT z;\n\tz.setZero();\n\treturn z;\n    }\n};\n\ntemplate<class Idx, class Function>\nauto sum(Idx ini, Idx fin, Function f) -> decltype(EvalEigenXpr<Idx>(ini, f))\n{\n    using Evaled = decltype(EvalEigenXpr<Idx>(ini, f));\n    using Acc = typename std::remove_cv<Evaled>::type;\n    Acc s = create_zero<Acc, is_eigen_type<Evaled>::value>::zero();\n    for (Idx i = ini; i <= fin; i++) s += f(i);\n    return s;\n}\n\n} // namespace flexiblesusy\n\n#endif // sum_hpp\n", "meta": {"hexsha": "60ec2d67878e7770e4a0c4ae37c1dfc74100103a", "size": 2846, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/src/sum.hpp", "max_stars_repo_name": "sebhoof/gambit_1.5", "max_stars_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-08T20:05:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-26T07:57:56.000Z", "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/src/sum.hpp", "max_issues_repo_name": "sebhoof/gambit_1.5", "max_issues_repo_head_hexsha": "f9a3f788e3331067c555ae1a030420e903c6fdcd", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-10-19T09:56:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:12:03.000Z", "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/src/sum.hpp", "max_forks_repo_name": "patscott/gambit_1.4", "max_forks_repo_head_hexsha": "a50537419918089effc207e8b206489a5cfd2258", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-08T02:23:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-23T08:48:04.000Z", "avg_line_length": 27.6310679612, "max_line_length": 83, "alphanum_fraction": 0.6531974701, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837477, "lm_q2_score": 0.3923368301671083, "lm_q1q2_score": 0.21602355424714112}}
{"text": "/*\n * This file is part of the M. xanthus polarity simulator\n * Copyright (c) 2020 Filipe Tostevin\n *\n * This file contains the main routine that creates all simulator\n * objects and calls the propagation routines.\n */\n\n#include <iostream>\n#include <cstdlib>\n#include <boost/property_tree/ini_parser.hpp>\n#include <boost/program_options.hpp>\n#include \"state.h\"\n#include \"propagator.h\"\n\nusing namespace std;\nnamespace po = boost::program_options;\nnamespace pt = boost::property_tree;\n\nint main(\n\tint argc,\n\tchar* argv[]\n){\n\t// Command line options and help\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t\t(\"help,h\", \"print help message\")\n\t\t(\"conf,c\", po::value<string>(), \"parameter configuration file\")\n\t\t(\"mutants,m\", \"simulate deletion mutants\")\n\t;\n\tpo::variables_map vm;\n\tpo::store(po::parse_command_line(argc, argv, desc), vm);\n\tpo::notify(vm);\n\n\tif(vm.count(\"help\")) {\n\t\tcout << desc << \"\\n\";\n\t\treturn(EXIT_SUCCESS);\n\t}\n\n\t// Read the input file given by the \"--conf\" option, or otherwise from\n\t// \"params.in\"\n\tpt::ptree ptree;\n\tstring defaultconfig=\"params.in\";\n\tif(vm.count(\"conf\")) {\n\t\tcout << \"Reading parameters from: \" << vm[\"conf\"].as<string>() << endl;\n\t\tpt::read_ini(vm[\"conf\"].as<string>(), ptree);\n\t} else {\n\t\tcout << \"No parameter file specified. Reading parameters from default file: \" << defaultconfig << endl;\n\t\tpt::read_ini(defaultconfig, ptree);\n\t}\n\n\t// Get total simulation time from input file\n\tconst double t_total=ptree.get<double>(\"t_total\");\n\tconst double sampling_interval=ptree.get<double>(\"sampling_interval\");\n\n\t// Define the system state variable and initialize all elements to zero\n\tstate conc(NSPEC,NPOOL,0);\n\n\t// Set up simulation infrastructure\n\tpropagator P;\n\t// Read in parameter values from input file\n\tfor(auto p: ptree.get_child(\"model_parameters\")) {\n\t\tP.params.emplace(p.first, ptree.get<double>(\"model_parameters.\"+p.first));\n\t}\n\t//Run a test call of the propagator to check that all required parameters\n\t//exist\n\ttry{ P(conc, conc, 0); }\n\tcatch(...) {\n\t\tcout << \"Error in model definition, check that all parameters are specified in the input file.\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t// Deletion mutants are defined by an integer that when represented as a\n\t// binary string defines the presence/absence of each protein,\n\t// i.e. if the number of proteins in NSPEC=3, then\n\t// mutant_number=1==b100 indicates only the first-listed protein is present,\n\t// mutant_number=7==b111 indicates that all proteins are present\n\t// Here we define the first simulation to run depending on whether we are\n\t// simulating all mutants, or just the wild-type\n\tint mutant_number;\n\tif(vm.count(\"mutants\")) {\n\t\tcout << \"Simulating deletion mutants\" << endl;\n\t\tmutant_number=1;\n\t} else {\n\t\tcout << \"Simulating only wild-type\" << endl;\n\t\tmutant_number=(1<<NSPEC) -1;\n\t}\n\n\t// Loop over all mutants until we reach wild-type\n\twhile(mutant_number < 1<<NSPEC) {\n\t\tcout << mutant_number << endl;\n\t\t//Each mutant will be output to a separate data file.\n\t\t//Decode mutant number bitwise into whether protein is present or not and\n\t\t//reconstruct readable output string from it, to use in the name of the\n\t\t//output file\n\t\tstring mutant_string=\"\";\n\t\tfor(int s=0; s<NSPEC; ++s) {\n\t\t\tif( !( (mutant_number >> s) & 1) ) {\n\t\t\t\tmutant_string+=\".d\" + species_names[s];\n\t\t\t}\n\t\t}\n\t\tofstream datafile(\"data.txt\"+mutant_string);\n\n\t\t//Headings for output file\n\t\tdatafile << \"t \";\n\t\tfor(int s=0; s<NSPEC; ++s) {\n\t\t\tdatafile << species_names[s] << \"1 \"\n\t\t\t         << species_names[s] << \"2 \"\n\t\t\t         << species_names[s] << \"t \";\n\t\t} datafile << endl;\n\n\t\tfor(int s=0; s<NSPEC; ++s) {\n\t\t\t// Initialize total amounts of each protein to 1 or 0 according to the\n\t\t\t// deletion condition\n\t\t\tif( (mutant_number >> s) & 1 ) {\n\t\t\t\tconc(s,TOTAL)=1;\n\t\t\t} else {\n\t\t\t\tconc(s,TOTAL)=0;\n\t\t\t}\n\t\t\t// Initialize polar fractions\n\t\t\tconc(s,POLE1)=ptree.get<double>(\"initial_fractions_\"+species_names[s]+\".pole1\")*conc(s,TOTAL);\n\t\t\tconc(s,POLE2)=ptree.get<double>(\"initial_fractions_\"+species_names[s]+\".pole2\")*conc(s,TOTAL);\n\t\t}\n\n\t\t// Start at t=0\n\t\tdouble t=0;\n\t\twrite_state(conc, t, datafile);\n\n\t\t// Run until the end of the simulation time t_total\n\t\twhile(t<t_total) {\n\t\t\t// Call the ODE integrator to run until the next output time point\n\t\t\tboost::numeric::odeint::integrate(boost::ref(P), conc, t, t+sampling_interval, 0.2*sampling_interval);\n\t\t\tt+=sampling_interval;\n\n\t\t\twrite_state(conc, t, datafile);\n\t\t}\n\n\t\tdatafile.close();\n\t\t++mutant_number;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ded840ffa5c62d2f2137c88a3803f2b3ad2c7667", "size": 4494, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/polarity_sim.cpp", "max_stars_repo_name": "gerland-group/mxanthus_polarity", "max_stars_repo_head_hexsha": "5385fd41a5d276446ee7440d852eedf2a0a29b2a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polarity_sim.cpp", "max_issues_repo_name": "gerland-group/mxanthus_polarity", "max_issues_repo_head_hexsha": "5385fd41a5d276446ee7440d852eedf2a0a29b2a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polarity_sim.cpp", "max_forks_repo_name": "gerland-group/mxanthus_polarity", "max_forks_repo_head_hexsha": "5385fd41a5d276446ee7440d852eedf2a0a29b2a", "max_forks_repo_licenses": ["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.2083333333, "max_line_length": 106, "alphanum_fraction": 0.6862483311, "num_tokens": 1237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21594798927958447}}
{"text": "/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************/\n#include <cmath>\n#include <miopen/kernel_cache.hpp>\n#include <miopen/util.hpp>\n#include <miopen/logger.hpp>\n#include <miopen/datatype.hpp>\n\n#include <boost/range/adaptors.hpp>\n\n#define WG_SIZE 256\n#define MAX_ACTIVE_THREADS (64 * 4 * 64)\n#define MAX_LOCAL_MEM 65536\n\nnamespace miopen {\n\nfloat Im2d2ColGPU(Handle& handle,\n                  ConstData_t im,\n                  const int im_offset,\n                  const int c,\n                  const int in_h,\n                  const int in_w,\n                  const int wei_h,\n                  const int wei_w,\n                  const int out_h,\n                  const int out_w,\n                  const int pad_h,\n                  const int pad_w,\n                  const int stride_h,\n                  const int stride_w,\n                  const int dilation_h,\n                  const int dilation_w,\n                  Data_t col,\n                  miopenDataType_t type)\n{\n    std::string program_name = \"MIOpenIm2d2Col.cl\";\n    std::string kernel_name  = \"Im2d2Col\";\n\n    // clang-format off\n    std::string network_config =\n        \"c\" + std::to_string(c) + \n        \"i\" + std::to_string(in_h) + \n        \"_\" + std::to_string(in_w) + \n        \"w\" + std::to_string(wei_h) + \n        \"_\" + std::to_string(wei_w) + \n        \"p\" + std::to_string(pad_h) + \n        \"_\" + std::to_string(pad_w) + \n        \"s\" + std::to_string(stride_h) + \n        \"_\" + std::to_string(stride_w) + \n        \"d\" + std::to_string(dilation_h) + \n        \"_\" + std::to_string(dilation_w) + \n        \"t\" + std::to_string(type);\n    // clang-format on\n\n    auto&& kernels = handle.GetKernels(\"miopenIm2d2Col\", network_config);\n\n    int data_size_bound = c * in_h * in_w;\n\n    int data_size_bound_pack = type == miopenInt8x4 ? data_size_bound * 4 : data_size_bound;\n    int im_offset_pack       = type == miopenInt8x4 ? im_offset / 4 : im_offset;\n\n    if(!kernels.empty())\n    {\n        auto kernel = kernels.front();\n        kernel(data_size_bound_pack,\n               im,\n               im_offset_pack,\n               in_h,\n               in_w,\n               wei_h,\n               wei_w,\n               out_h,\n               out_w,\n               pad_h,\n               pad_w,\n               stride_h,\n               stride_w,\n               dilation_h,\n               dilation_w,\n               col);\n    }\n    else\n    {\n        const int c_pack = type == miopenInt8x4 ? c / 4 : c;\n\n        std::string params;\n        int num_ch_per_wg;\n        if((out_h <= 8 && out_w <= 8) && (stride_h == 1 && stride_w == 1) && (c_pack % 4 == 0))\n            num_ch_per_wg = 4;\n        else\n            num_ch_per_wg = 1;\n\n        int tile_sz_x  = 32;\n        int tile_sz_y  = 8;\n        int num_blks_x = std::ceil(static_cast<float>(out_w) / static_cast<float>(tile_sz_x));\n        int num_blks =\n            num_blks_x *\n            static_cast<int>(std::ceil(static_cast<float>(out_h) / static_cast<float>(tile_sz_y)));\n        int local_mem_sz;\n        if(num_ch_per_wg == 1)\n        {\n            local_mem_sz = ((tile_sz_x - 1) * stride_w + (wei_w - 1) * dilation_w + 1) *\n                           ((tile_sz_y - 1) * stride_h + (wei_h - 1) * dilation_h + 1);\n        }\n        else\n        {\n            auto uprdTileX = static_cast<int>(\n                std::ceil(static_cast<float>(tile_sz_x) / static_cast<float>(num_ch_per_wg)) - 1);\n            auto uprdTileY = static_cast<int>(\n                std::ceil(static_cast<float>(tile_sz_y) / static_cast<float>(num_ch_per_wg)) - 1);\n            auto memXsize = (num_ch_per_wg * uprdTileX * stride_w + (wei_w - 1) * dilation_w + 1) *\n                            ((tile_sz_y - 1) * stride_h + (wei_h - 1) * dilation_h + 1);\n            auto memYsize = num_ch_per_wg *\n                            ((tile_sz_x - 1) * stride_w + (wei_w - 1) * dilation_w + 1) *\n                            (uprdTileY * stride_h + (wei_h - 1) * dilation_h + 1);\n            local_mem_sz = static_cast<int>(std::max(memXsize, memYsize));\n        }\n\n        // adjust mapping for large kernel\n        int type_size    = 4; // Need to adjust for fp16, int8\n        int extreme_case = num_ch_per_wg * ((wei_w - 1) * dilation_w + 1) *\n                           ((wei_h - 1) * dilation_h + 1) * type_size;\n        if(extreme_case > MAX_LOCAL_MEM)\n        {\n            params += \" -DEXTREME_LARGE\";\n            params += \" -DNUM_CH_TOTAL=\" + std::to_string(c_pack);\n        }\n        else\n        {\n            while(local_mem_sz * type_size > MAX_LOCAL_MEM)\n            {\n                tile_sz_x  = tile_sz_x == 1 ? 1 : (tile_sz_y == 1 ? (tile_sz_x / 2) : tile_sz_x);\n                tile_sz_y  = tile_sz_y == 1 ? 1 : (tile_sz_y / 2);\n                num_blks_x = std::ceil(static_cast<float>(out_w) / static_cast<float>(tile_sz_x));\n                num_blks   = num_blks_x * static_cast<int>(std::ceil(static_cast<float>(out_h) /\n                                                                   static_cast<float>(tile_sz_y)));\n                if(num_ch_per_wg == 1)\n                {\n                    local_mem_sz = ((tile_sz_x - 1) * stride_w + (wei_w - 1) * dilation_w + 1) *\n                                   ((tile_sz_y - 1) * stride_h + (wei_h - 1) * dilation_h + 1);\n                }\n                else\n                {\n                    auto uprdTileX = static_cast<int>(std::ceil(static_cast<float>(tile_sz_x) /\n                                                                static_cast<float>(num_ch_per_wg)) -\n                                                      1);\n                    auto uprdTileY = static_cast<int>(std::ceil(static_cast<float>(tile_sz_y) /\n                                                                static_cast<float>(num_ch_per_wg)) -\n                                                      1);\n                    auto memXsize =\n                        (num_ch_per_wg * uprdTileX * stride_w + (wei_w - 1) * dilation_w + 1) *\n                        ((tile_sz_y - 1) * stride_h + (wei_h - 1) * dilation_h + 1);\n                    auto memYsize = num_ch_per_wg *\n                                    ((tile_sz_x - 1) * stride_w + (wei_w - 1) * dilation_w + 1) *\n                                    (uprdTileY * stride_h + (wei_h - 1) * dilation_h + 1);\n                    local_mem_sz = static_cast<int>(std::max(memXsize, memYsize));\n                }\n            }\n        }\n\n        params += \" -DNUM_CH_PER_WG=\" + std::to_string(num_ch_per_wg);\n        params += \" -DNUM_IM_BLKS_X=\" + std::to_string(num_blks_x);\n        params += \" -DNUM_IM_BLKS=\" + std::to_string(num_blks);\n        params += \" -DLOCAL_MEM_SIZE=\" + std::to_string(local_mem_sz);\n        params += \" -DSTRIDE_GT_1=\" + std::to_string(static_cast<int>(stride_h * stride_w > 1));\n        params += \" -DTILE_SZ_X=\" + std::to_string(tile_sz_x);\n        params += \" -DTILE_SZ_Y=\" + std::to_string(tile_sz_y);\n        params += \" -DUSE_IM_OFF_GUARD=1\";\n\n        params += GetDataTypeKernelParams(type);\n\n        const std::vector<size_t> vld{256, 1, 1};\n        size_t global_threads = 256 * std::max(1, (c_pack / num_ch_per_wg)) * num_blks;\n        const std::vector<size_t> vgd{global_threads, 1, 1};\n        handle.AddKernel(\n            \"miopenIm2Col\", network_config, program_name, kernel_name, vld, vgd, params)(\n            data_size_bound_pack,\n            im,\n            im_offset_pack,\n            in_h,\n            in_w,\n            wei_h,\n            wei_w,\n            out_h,\n            out_w,\n            pad_h,\n            pad_w,\n            stride_h,\n            stride_w,\n            dilation_h,\n            dilation_w,\n            col);\n    }\n\n    return handle.GetKernelTime();\n}\n\nfloat Im3d2ColGPU(Handle& handle,\n                  ConstData_t im,\n                  const int im_offset,\n                  const int im_c,\n                  const int im_d,\n                  const int im_h,\n                  const int im_w,\n                  const int wei_d,\n                  const int wei_h,\n                  const int wei_w,\n                  const int out_d,\n                  const int out_h,\n                  const int out_w,\n                  const int pad_d,\n                  const int pad_h,\n                  const int pad_w,\n                  const int stride_d,\n                  const int stride_h,\n                  const int stride_w,\n                  const int dilation_d,\n                  const int dilation_h,\n                  const int dilation_w,\n                  Data_t col,\n                  miopenDataType_t type)\n{\n    std::string program_name = \"MIOpenIm3d2Col.cl\";\n    std::string kernel_name  = \"Im3d2Col\";\n\n    // clang-format off\n    std::string network_config =\n        \"c\" + std::to_string(im_c) + \n        \"i\" + std::to_string(im_d) + \n        \"_\" + std::to_string(im_h) + \n        \"_\" + std::to_string(im_w) + \n        \"w\" + std::to_string(wei_d) + \n        \"_\" + std::to_string(wei_h) + \n        \"_\" + std::to_string(wei_w) + \n        \"p\" + std::to_string(pad_d) + \n        \"_\" + std::to_string(pad_h) + \n        \"_\" + std::to_string(pad_w) + \n        \"s\" + std::to_string(stride_d) + \n        \"_\" + std::to_string(stride_h) +\n        \"_\" + std::to_string(stride_w) + \n        \"d\" + std::to_string(dilation_d) + \n        \"_\" + std::to_string(dilation_h) + \n        \"_\" + std::to_string(dilation_w) + \n        \"t\" + std::to_string(type);\n    // clang-format on\n\n    auto&& kernels = handle.GetKernels(\"miopenIm3d2Col\", network_config);\n\n    // int8x4 vectorize-c format\n    int im_offset_pack = type == miopenInt8x4 ? im_offset / 4 : im_offset;\n    int im_c_pack      = type == miopenInt8x4 ? im_c / 4 : im_c;\n\n    if(!kernels.empty())\n    {\n        auto kernel = kernels.front();\n        kernel(im,\n               im_offset_pack,\n               im_c_pack,\n               im_d,\n               im_h,\n               im_w,\n               wei_d,\n               wei_h,\n               wei_w,\n               out_d,\n               out_h,\n               out_w,\n               pad_d,\n               pad_h,\n               pad_w,\n               stride_d,\n               stride_h,\n               stride_w,\n               dilation_d,\n               dilation_h,\n               dilation_w,\n               col);\n    }\n    else\n    {\n        std::string params = GetDataTypeKernelParams(type);\n\n        const std::vector<size_t> vld{256, 1, 1};\n        size_t global_threads = std::min(\n            256 * static_cast<std::size_t>(out_d * out_h * out_w * im_c * wei_d * wei_h * wei_w) /\n                8,\n            static_cast<std::size_t>(256) * 1024);\n        const std::vector<size_t> vgd{global_threads, 1, 1};\n\n        handle.AddKernel(\n            \"miopenIm3d2Col\", network_config, program_name, kernel_name, vld, vgd, params)(\n            im,\n            im_offset_pack,\n            im_c_pack,\n            im_d,\n            im_h,\n            im_w,\n            wei_d,\n            wei_h,\n            wei_w,\n            out_d,\n            out_h,\n            out_w,\n            pad_d,\n            pad_h,\n            pad_w,\n            stride_d,\n            stride_h,\n            stride_w,\n            dilation_d,\n            dilation_h,\n            dilation_w,\n            col);\n    }\n\n    return handle.GetKernelTime();\n}\n\nfloat Col2Im2dGPU(Handle& handle,\n                  ConstData_t col,\n                  const int out_h,\n                  const int out_w,\n                  const int wei_h,\n                  const int wei_w,\n                  const int pad_h,\n                  const int pad_w,\n                  const int stride_h,\n                  const int stride_w,\n                  const int dilation_h,\n                  const int dilation_w,\n                  const int in_c,\n                  const int in_h,\n                  const int in_w,\n                  Data_t im,\n                  int im_offset,\n                  miopenDataType_t type)\n{\n    std::string program_name = \"MIOpenCol2Im2d.cl\";\n    std::string kernel_name  = \"Col2Im2d\";\n\n    // clang-format off\n    std::string network_config =\n        \"c\" + std::to_string(in_c) + \n        \"in_h\" + std::to_string(in_h) +\n        \"in_w\" + std::to_string(in_w) + \n        \"y\" + std::to_string(wei_h) + \n        \"x\" + std::to_string(wei_w) + \n        \"p\" + std::to_string(pad_h) + \n        \"q\" + std::to_string(pad_w) + \n        \"u\" + std::to_string(stride_h) + \n        \"v\" + std::to_string(stride_w) + \n        \"l\" + std::to_string(dilation_h) + \n        \"j\" + std::to_string(dilation_w) + \n        \"t\" + std::to_string(type);\n    // clang-format on\n\n    auto&& kernels = handle.GetKernels(\"miopenCol2Im2d\", network_config);\n\n    if(!kernels.empty())\n    {\n        auto kernel = kernels.front();\n        kernel(col,\n               out_h,\n               out_w,\n               wei_h,\n               wei_w,\n               pad_h,\n               pad_w,\n               stride_h,\n               stride_w,\n               dilation_h,\n               dilation_w,\n               in_h,\n               in_w,\n               im,\n               im_offset);\n    }\n    else\n    {\n        std::string params = GetDataTypeKernelParams(type);\n\n        const std::vector<size_t> vld{256, 1, 1};\n        size_t global_threads = in_c * in_h * in_w;\n        const std::vector<size_t> vgd{global_threads, 1, 1};\n\n        handle.AddKernel(\n            \"miopenCol2Im2d\", network_config, program_name, kernel_name, vld, vgd, params)(\n            col,\n            out_h,\n            out_w,\n            wei_h,\n            wei_w,\n            pad_h,\n            pad_w,\n            stride_h,\n            stride_w,\n            dilation_h,\n            dilation_w,\n            in_h,\n            in_w,\n            im,\n            im_offset);\n    }\n    return handle.GetKernelTime();\n}\n\nfloat Col2Im3dGPU(Handle& handle,\n                  ConstData_t col,\n                  const int out_d,\n                  const int out_h,\n                  const int out_w,\n                  const int wei_d,\n                  const int wei_h,\n                  const int wei_w,\n                  const int pad_d,\n                  const int pad_h,\n                  const int pad_w,\n                  const int stride_d,\n                  const int stride_h,\n                  const int stride_w,\n                  const int dilation_d,\n                  const int dilation_h,\n                  const int dilation_w,\n                  const int in_c,\n                  const int in_d,\n                  const int in_h,\n                  const int in_w,\n                  Data_t im,\n                  int im_offset,\n                  miopenDataType_t type)\n{\n    std::string program_name = \"MIOpenCol2Im3d.cl\";\n    std::string kernel_name  = \"Col2Im3d\";\n\n    // clang-format off\n    std::string network_config =\n        \"c\" + std::to_string(in_c) + \n        \"i\" + std::to_string(in_d) + \n        \"_\" + std::to_string(in_h) + \n        \"_\" + std::to_string(in_w) + \n        \"w\" + std::to_string(wei_d) + \n        \"_\" + std::to_string(wei_h) + \n        \"_\" + std::to_string(wei_w) + \n        \"p\" + std::to_string(pad_d) + \n        \"_\" + std::to_string(pad_h) + \n        \"_\" + std::to_string(pad_w) + \n        \"s\" + std::to_string(stride_d) + \n        \"_\" + std::to_string(stride_h) +\n        \"_\" + std::to_string(stride_w) + \n        \"d\" + std::to_string(dilation_d) + \n        \"_\" + std::to_string(dilation_h) + \n        \"_\" + std::to_string(dilation_w) + \n        \"t\" + std::to_string(type);\n    // clang-format on\n\n    auto&& kernels = handle.GetKernels(\"miopenCol2Im3d\", network_config);\n\n    if(!kernels.empty())\n    {\n        auto kernel = kernels.front();\n        kernel(col,\n               out_d,\n               out_h,\n               out_w,\n               wei_d,\n               wei_h,\n               wei_w,\n               pad_d,\n               pad_h,\n               pad_w,\n               stride_d,\n               stride_h,\n               stride_w,\n               dilation_d,\n               dilation_h,\n               dilation_w,\n               in_d,\n               in_h,\n               in_w,\n               im,\n               im_offset);\n    }\n    else\n    {\n        std::string params = GetDataTypeKernelParams(type);\n\n        const std::vector<size_t> vld{256, 1, 1};\n        size_t global_threads = in_c * in_d * in_h * in_w;\n        const std::vector<size_t> vgd{global_threads, 1, 1};\n\n        handle.AddKernel(\n            \"miopenCol2Im3d\", network_config, program_name, kernel_name, vld, vgd, params)(\n            col,\n            out_d,\n            out_h,\n            out_w,\n            wei_d,\n            wei_h,\n            wei_w,\n            pad_d,\n            pad_h,\n            pad_w,\n            stride_d,\n            stride_h,\n            stride_w,\n            dilation_d,\n            dilation_h,\n            dilation_w,\n            in_d,\n            in_h,\n            in_w,\n            im,\n            im_offset);\n    }\n    return handle.GetKernelTime();\n}\n\nfloat Im2ColGPU(\n    Handle& handle,\n    std::size_t spatial_dim,\n    ConstData_t im,\n    std::size_t im_offset,\n    std::size_t in_c,\n    const decltype(boost::adaptors::slice(std::vector<std::size_t>(), 0, 1))& in_spatial,\n    const decltype(boost::adaptors::slice(std::vector<std::size_t>(), 0, 1))& wei_spatial,\n    const decltype(boost::adaptors::slice(std::vector<std::size_t>(), 0, 1))& out_spatial,\n    const std::vector<int>& pad_spatial,\n    const std::vector<int>& stride_spatial,\n    const std::vector<int>& dilation_spatial,\n    Data_t col,\n    miopenDataType_t type)\n{\n    switch(spatial_dim)\n    {\n    case 2:\n    {\n        return Im2d2ColGPU(handle,\n                           im,\n                           im_offset,\n                           in_c,\n                           in_spatial[0],\n                           in_spatial[1],\n                           wei_spatial[0],\n                           wei_spatial[1],\n                           out_spatial[0],\n                           out_spatial[1],\n                           pad_spatial[0],\n                           pad_spatial[1],\n                           stride_spatial[0],\n                           stride_spatial[1],\n                           dilation_spatial[0],\n                           dilation_spatial[1],\n                           col,\n                           type);\n    }\n    case 3:\n    {\n        return Im3d2ColGPU(handle,\n                           im,\n                           im_offset,\n                           in_c,\n                           in_spatial[0],\n                           in_spatial[1],\n                           in_spatial[2],\n                           wei_spatial[0],\n                           wei_spatial[1],\n                           wei_spatial[2],\n                           out_spatial[0],\n                           out_spatial[1],\n                           out_spatial[2],\n                           pad_spatial[0],\n                           pad_spatial[1],\n                           pad_spatial[2],\n                           stride_spatial[0],\n                           stride_spatial[1],\n                           stride_spatial[2],\n                           dilation_spatial[0],\n                           dilation_spatial[1],\n                           dilation_spatial[2],\n                           col,\n                           type);\n    }\n    default: { MIOPEN_THROW(\"unsupported convolution dimension\");\n    }\n    }\n}\n\nfloat Col2ImGPU(\n    Handle& handle,\n    std::size_t spatial_dim,\n    ConstData_t col,\n    const decltype(boost::adaptors::slice(std::vector<std::size_t>(), 0, 1))& out_spatial,\n    const decltype(boost::adaptors::slice(std::vector<std::size_t>(), 0, 1))& wei_spatial,\n    const std::vector<int>& pad_spatial,\n    const std::vector<int>& stride_spatial,\n    const std::vector<int>& dilation_spatial,\n    std::size_t in_c,\n    const decltype(boost::adaptors::slice(std::vector<std::size_t>(), 0, 1))& in_spatial,\n    Data_t im,\n    std::size_t im_offset,\n    miopenDataType_t type)\n{\n    switch(spatial_dim)\n    {\n    case 2:\n    {\n        return Col2Im2dGPU(handle,\n                           col,\n                           out_spatial[0],\n                           out_spatial[1],\n                           wei_spatial[0],\n                           wei_spatial[1],\n                           pad_spatial[0],\n                           pad_spatial[1],\n                           stride_spatial[0],\n                           stride_spatial[1],\n                           dilation_spatial[0],\n                           dilation_spatial[1],\n                           in_c,\n                           in_spatial[0],\n                           in_spatial[1],\n                           im,\n                           im_offset,\n                           type);\n    }\n    case 3:\n    {\n        return Col2Im3dGPU(handle,\n                           col,\n                           out_spatial[0],\n                           out_spatial[1],\n                           out_spatial[2],\n                           wei_spatial[0],\n                           wei_spatial[1],\n                           wei_spatial[2],\n                           pad_spatial[0],\n                           pad_spatial[1],\n                           pad_spatial[2],\n                           stride_spatial[0],\n                           stride_spatial[1],\n                           stride_spatial[2],\n                           dilation_spatial[0],\n                           dilation_spatial[1],\n                           dilation_spatial[2],\n                           in_c,\n                           in_spatial[0],\n                           in_spatial[1],\n                           in_spatial[2],\n                           im,\n                           im_offset,\n                           type);\n    }\n    default: { MIOPEN_THROW(\"unsupported convolution dimension\");\n    }\n    }\n\n    MIOPEN_THROW(\"unsupported convolution dimension\");\n}\n\nfloat transpose_NCHW2CNHW(Handle& handle,\n                          int n,\n                          int c,\n                          int h_in,\n                          int w_in,\n                          int h_out,\n                          int w_out,\n                          ConstData_t in,\n                          Data_t out,\n                          int in_offset,\n                          int out_offset,\n                          int h_stride,\n                          int w_stride,\n                          miopenDataType_t type)\n{\n\n    std::string program_name = \"MIOpenUtilKernels4.cl\";\n\n    std::string network_config = \"n\" + std::to_string(n) + \"c\" + std::to_string(c) + \"h\" +\n                                 std::to_string(h_in) + \"w\" + std::to_string(w_in) + \"inoff\" +\n                                 std::to_string(in_offset) + \"otoff\" + std::to_string(out_offset) +\n                                 \"u\" + std::to_string(h_stride) + \"v\" + std::to_string(w_stride) +\n                                 \"t\" + std::to_string(type);\n\n    std::string kernel_name = \"transpose_NCHW2CNHW\";\n\n    if(h_stride == 1 && w_stride == 1 && type == miopenFloat)\n        kernel_name += \"_opt\";\n\n    auto&& kernels = handle.GetKernels(kernel_name, network_config);\n\n    if(!kernels.empty())\n    {\n        auto kernel = kernels.front();\n        kernel(in, out);\n    }\n    else\n    {\n        std::string params = GetDataTypeKernelParams(type);\n\n        if(type == miopenInt8x4)\n        {\n            c /= 4;\n            in_offset /= 4;\n            out_offset /= 4;\n        }\n\n        if(h_stride == 1 && w_stride == 1 && type == miopenFloat)\n        {\n            params +=\n                \" -DNC_TRANS_NCHW_OPT=1 -DNC_TRANS_CNHW_OPT=0 -DNC_TRANS_NCHW=0 -DNC_TRANS_CNHW=0\";\n\n            int RD_BLCK      = ((h_in * w_in) % 4 == 0) ? 4 : ((h_in * w_in) % 2 == 0) ? 2 : 1;\n            int HW_RD        = (h_in * w_in) / RD_BLCK;\n            size_t MAP_RD    = HW_RD * c;\n            size_t lcl_size0 = WG_SIZE; //((MAP_RD + 63)/64 < 4) ? ((MAP_RD + 63)/64)*64 : 256;\n\n            std::string READ_TYPE = (RD_BLCK == 1) ? \"float\" : \"float\" + std::to_string(RD_BLCK);\n\n            params += \" -DIN_OFF=\" + std::to_string(in_offset);\n            params += \" -DOUT_OFF=\" + std::to_string(out_offset);\n            params += \" -DH=\" + std::to_string(h_in);\n            params += \" -DW=\" + std::to_string(w_in);\n            params += \" -DN=\" + std::to_string(n);\n            params += \" -DC=\" + std::to_string(c);\n            params += \" -DRD_BLCK=\" + std::to_string(RD_BLCK);\n            params += \" -DHW_RD=\" + std::to_string(HW_RD);\n            params += \" -DMAP_RD=\" + std::to_string(MAP_RD);\n            params += \" -DREAD_TYPE=\" + READ_TYPE;\n\n            const std::vector<size_t> vld{lcl_size0, 1, 1};\n            std::vector<size_t> vgd{MAP_RD, 1, 1};\n\n            if(MAP_RD < MAX_ACTIVE_THREADS)\n            {\n                vgd = {MAP_RD, static_cast<size_t>(n), 1};\n                params += \" -DIS_2D_WG=1\";\n            }\n            else\n            {\n                params += \" -DIS_2D_WG=0\";\n            }\n\n            handle.AddKernel(\n                kernel_name, network_config, program_name, kernel_name, vld, vgd, params)(in, out);\n        }\n        else\n        {\n            params +=\n                \" -DNC_TRANS_NCHW_OPT=0 -DNC_TRANS_CNHW_OPT=0 -DNC_TRANS_NCHW=1 -DNC_TRANS_CNHW=0\";\n\n            params += \" -DN=\" + std::to_string(n);\n            params += \" -DC=\" + std::to_string(c);\n            params += \" -DHW_IN=\" + std::to_string(h_in * w_in);\n            params += \" -DHW_OUT=\" + std::to_string(h_out * w_out);\n            params += \" -DW_IN=\" + std::to_string(w_in);\n            params += \" -DW_OUT=\" + std::to_string(w_out);\n            params += \" -DH_STRIDE=\" + std::to_string(h_stride);\n            params += \" -DW_STRIDE=\" + std::to_string(w_stride);\n            params += \" -DIN_OFF=\" + std::to_string(in_offset);\n            params += \" -DOUT_OFF=\" + std::to_string(out_offset);\n\n            size_t ld0 = WG_SIZE;\n            size_t gd0 = c * h_out * w_out;\n            const std::vector<size_t> vld{ld0, 1, 1};\n            std::vector<size_t> vgd{gd0, 1, 1};\n\n            if(gd0 < MAX_ACTIVE_THREADS)\n            {\n                vgd = {gd0, static_cast<size_t>(n), 1};\n                params += \" -DIS_2D_WG=1\";\n            }\n            else\n            {\n                params += \" -DIS_2D_WG=0\";\n            }\n\n            handle.AddKernel(\n                kernel_name, network_config, program_name, kernel_name, vld, vgd, params)(in, out);\n        }\n    }\n\n    return handle.GetKernelTime();\n}\n\nfloat transpose_CNHW2NCHW(Handle& handle,\n                          int n,\n                          int c,\n                          int h_out,\n                          int w_out,\n                          int h_in,\n                          int w_in,\n                          ConstData_t in,\n                          Data_t out,\n                          int in_offset,\n                          int out_offset,\n                          int h_stride,\n                          int w_stride,\n                          miopenDataType_t type)\n{\n\n    std::string program_name = \"MIOpenUtilKernels4.cl\";\n\n    std::string network_config = \"n\" + std::to_string(n) + \"c\" + std::to_string(c) + \"h\" +\n                                 std::to_string(h_in) + \"w\" + std::to_string(w_in) + \"inoff\" +\n                                 std::to_string(in_offset) + \"otoff\" + std::to_string(out_offset) +\n                                 \"h_stride\" + std::to_string(h_stride) + \"w_stride\" +\n                                 std::to_string(w_stride) + \"t\" + std::to_string(type);\n\n    std::string kernel_name = \"transpose_CNHW2NCHW\";\n\n    if(h_stride == 1 && w_stride == 1 && type == miopenFloat)\n        kernel_name += \"_opt\";\n\n    auto&& kernels = handle.GetKernels(kernel_name, network_config);\n\n    if(!kernels.empty())\n    {\n        auto kernel = kernels.front();\n        kernel(in, out);\n    }\n    else\n    {\n        std::string params = GetDataTypeKernelParams(type);\n\n        if(type == miopenInt8x4)\n        {\n            c /= 4;\n            in_offset /= 4;\n            out_offset /= 4;\n        }\n\n        if(h_stride == 1 && w_stride == 1 && type == miopenFloat)\n        {\n            params +=\n                \" -DNC_TRANS_NCHW_OPT=0 -DNC_TRANS_CNHW_OPT=1 -DNC_TRANS_NCHW=0 -DNC_TRANS_CNHW=0\";\n\n            int RD_BLCK      = ((h_out * w_out) % 4 == 0) ? 4 : ((h_out * w_out) % 2 == 0) ? 2 : 1;\n            int HW_RD        = (h_out * w_out) / RD_BLCK;\n            size_t MAP_RD    = HW_RD * c;\n            size_t lcl_size0 = WG_SIZE; //((MAP_RD + 63)/64 < 4) ? ((MAP_RD + 63)/64)*64 : 256;\n\n            std::string READ_TYPE = (RD_BLCK == 1) ? \"float\" : \"float\" + std::to_string(RD_BLCK);\n\n            params += \" -DIN_OFF=\" + std::to_string(in_offset);\n            params += \" -DOUT_OFF=\" + std::to_string(out_offset);\n            params += \" -DH=\" + std::to_string(h_out);\n            params += \" -DW=\" + std::to_string(w_out);\n            params += \" -DN=\" + std::to_string(n);\n            params += \" -DC=\" + std::to_string(c);\n            params += \" -DRD_BLCK=\" + std::to_string(RD_BLCK);\n            params += \" -DHW_RD=\" + std::to_string(HW_RD);\n            params += \" -DMAP_RD=\" + std::to_string(MAP_RD);\n            params += \" -DREAD_TYPE=\" + READ_TYPE;\n\n            const std::vector<size_t> vld{lcl_size0, 1, 1};\n            std::vector<size_t> vgd{MAP_RD, 1, 1};\n\n            if(MAP_RD < MAX_ACTIVE_THREADS)\n            {\n                vgd = {MAP_RD, static_cast<size_t>(n), 1};\n                params += \" -DIS_2D_WG=1\";\n            }\n            else\n            {\n                params += \" -DIS_2D_WG=0\";\n            }\n\n            handle.AddKernel(\n                kernel_name, network_config, program_name, kernel_name, vld, vgd, params)(in, out);\n        }\n        else\n        {\n            params +=\n                \" -DNC_TRANS_NCHW_OPT=0 -DNC_TRANS_CNHW_OPT=0 -DNC_TRANS_NCHW=0 -DNC_TRANS_CNHW=1\";\n\n            params += \" -DN=\" + std::to_string(n);\n            params += \" -DC=\" + std::to_string(c);\n            params += \" -DHW_IN=\" + std::to_string(h_in * w_in);\n            params += \" -DHW_OUT=\" + std::to_string(h_out * w_out);\n            params += \" -DW_IN=\" + std::to_string(w_in);\n            params += \" -DW_OUT=\" + std::to_string(w_out);\n            params += \" -DH_STRIDE=\" + std::to_string(h_stride);\n            params += \" -DW_STRIDE=\" + std::to_string(w_stride);\n            params += \" -DIN_OFF=\" + std::to_string(in_offset);\n            params += \" -DOUT_OFF=\" + std::to_string(out_offset);\n\n            size_t ld0 = WG_SIZE;\n            size_t gd0 = c * h_out * w_out;\n            const std::vector<size_t> vld{ld0, 1, 1};\n            std::vector<size_t> vgd{gd0, 1, 1};\n\n            if(gd0 < MAX_ACTIVE_THREADS)\n            {\n                vgd = {gd0, static_cast<size_t>(n), 1};\n                params += \" -DIS_2D_WG=1\";\n            }\n            else\n            {\n                params += \" -DIS_2D_WG=0\";\n            }\n\n            handle.AddKernel(\n                kernel_name, network_config, program_name, kernel_name, vld, vgd, params)(in, out);\n        }\n    }\n\n    return handle.GetKernelTime();\n}\n\n// NCHW (or NCDHW) to NCHW_C4 (or NCDHW_C4)\nfloat transpose_NCHW2Vec(Handle& handle,\n                         const std::vector<std::size_t>& lens,\n                         ConstData_t in,\n                         Data_t out,\n                         std::size_t vec_size,\n                         bool trans,\n                         bool forward)\n{\n    std::string program_name = \"MIOpenUtilKernels5.cl\";\n\n    if(!(vec_size == 2 || vec_size == 4))\n    {\n        MIOPEN_THROW(\"Only support type half and int8!\");\n    }\n\n    const auto n = lens[0];\n    const auto c = lens[1];\n\n    // \"hw\" is for any-D spatial data\n    const auto hw = std::accumulate(\n        lens.begin() + 2, lens.end(), std::size_t(1), std::multiplies<std::size_t>());\n\n    // clang-format off\n    std::string network_config = \n        \"n\" + std::to_string(n) +\n        \"c\" + std::to_string(c) +\n        \"hw\" + std::to_string(hw) +\n        \"t\" + std::to_string(static_cast<int>(trans)) +\n        \"v\" + std::to_string(vec_size) +\n        \"f\" + std::to_string(static_cast<int>(forward));\n    // clang-format on\n\n    std::string algo_name = \"transpose_NCHWVecForward\";\n\n    auto&& kernels = handle.GetKernels(algo_name, network_config);\n\n    if(!kernels.empty())\n    {\n        auto kernel = kernels.front();\n        kernel(in, out);\n    }\n    else\n    {\n        auto n_vec = (trans && (n % vec_size != 0)) ? (n + (vec_size - n % vec_size)) : n;\n        auto c_vec = (!trans && (c % vec_size != 0)) ? (c + (vec_size - c % vec_size)) : c;\n\n        std::string kernel_name = \"transpose_NCHW2Vec\";\n\n        const std::vector<size_t> vld{WG_SIZE, 1, 1};\n        std::vector<size_t> vgd{1, 1, 1};\n\n        int RD_BLCK = ((hw) % (vec_size * 2) == 0) ? static_cast<int>(vec_size) * 2\n                                                   : static_cast<int>(vec_size);\n        int HW_RD     = (static_cast<int>(hw) + RD_BLCK - 1) / RD_BLCK;\n        size_t MAP_RD = HW_RD * (trans ? c : (c_vec / vec_size));\n\n        std::string READ_TYPE =\n            (RD_BLCK == vec_size) ? \"uint\" : \"uint\" + std::to_string(RD_BLCK / vec_size);\n        int WR_BLCK            = RD_BLCK * static_cast<int>(vec_size);\n        std::string WRITE_TYPE = \"uint\" + std::to_string(WR_BLCK / vec_size);\n\n        std::string params;\n        params += \" -DFORWARD=\" + std::to_string(static_cast<int>(forward));\n        params += \" -DN=\" + std::to_string(n);\n        params += \" -DC=\" + std::to_string(c);\n        params += \" -DHW=\" + std::to_string(hw);\n        params += \" -DCHW=\" + std::to_string(c * hw);\n        params += \" -DVEC_SIZE=\" + std::to_string(vec_size);\n        params += vec_size == 4 ? \" -DDATA_TYPE=char\" : \" -DDATA_TYPE=ushort\";\n\n        params += \" -DTRANS=\" + std::to_string(static_cast<int>(trans));\n        if(trans)\n        {\n            params += \" -DNHW_OUT=\" + std::to_string(n_vec * hw);\n            params += \" -DN_OUT=\" + std::to_string(n_vec);\n            params += \" -DIS_N_ODD=\" + std::to_string(static_cast<int>((n % vec_size) != 0));\n        }\n        else\n        {\n            params += \" -DCHW_OUT=\" + std::to_string(c_vec * hw);\n            params += \" -DIS_C_ODD=\" + std::to_string(static_cast<int>((c % vec_size) != 0));\n        }\n\n        params += \" -DIS_HW_ODD=\" + std::to_string(static_cast<int>(((hw) % vec_size) != 0));\n        params += \" -DRD_BLCK=\" + std::to_string(RD_BLCK);\n        params += \" -DWR_BLCK=\" + std::to_string(WR_BLCK);\n        params += \" -DHW_RD=\" + std::to_string(HW_RD);\n        params += \" -DMAP_RD=\" + std::to_string(MAP_RD);\n        params += \" -DREAD_TYPE=\" + READ_TYPE;\n        params += \" -DWRITE_TYPE=\" + WRITE_TYPE;\n\n        vgd[0] = MAP_RD;\n\n        size_t gd1 = trans ? static_cast<size_t>(n_vec / vec_size) : static_cast<size_t>(n);\n\n        /// disable iteration of n due to perf degrade\n        /// \\to-do fix the perf issue\n        // if(vgd[0] < MAX_ACTIVE_THREADS)\n        {\n            vgd[1] = gd1;\n            params += \" -DIS_2D_WG=1\";\n        }\n        // else\n        //{\n        // params += \" -DIS_2D_WG=0\";\n        // params += \" -DGD_1=\" + std::to_string(gd1);\n        //}\n\n        handle.AddKernel(algo_name, network_config, program_name, kernel_name, vld, vgd, params)(\n            in, out);\n    }\n\n    return handle.GetKernelTime();\n}\n\nfloat transpose_packed_MN2NM(Handle& handle,\n                             int m,\n                             int n,\n                             int in_offset,\n                             int out_offset,\n                             ConstData_t in,\n                             Data_t out,\n                             miopenDataType_t type)\n{\n\n    std::string program_name = \"MIOpenUtilKernels4.cl\";\n\n    std::string network_config = \"n\" + std::to_string(n) + \"m\" + std::to_string(m) + \"inoff\" +\n                                 std::to_string(in_offset) + \"otoff\" + std::to_string(out_offset) +\n                                 \"t\" + std::to_string(type);\n\n    std::string kernel_name = \"transpose_packed_MN2NM\";\n\n    auto&& kernels = handle.GetKernels(kernel_name, network_config);\n\n    if(!kernels.empty())\n    {\n        auto kernel = kernels.front();\n        kernel(in, out);\n    }\n    else\n    {\n        std::string params = GetDataTypeKernelParams(type);\n        if(type == miopenInt8x4)\n        {\n            m /= 4;\n            in_offset /= 4;\n            out_offset /= 4;\n        }\n\n        if(!(type == miopenInt8x4 || type == miopenInt8))\n        {\n            MIOPEN_THROW(\"transpose_packed_MN2NM only meant for int8 variants.\");\n        }\n\n        params += \" -DNC_TRANS_MN2NM=1\";\n\n        params += \" -DN=\" + std::to_string(n);\n        params += \" -DM=\" + std::to_string(m);\n        params += \" -DIN_OFF=\" + std::to_string(in_offset);\n        params += \" -DOUT_OFF=\" + std::to_string(out_offset);\n\n        size_t ld0 = WG_SIZE;\n        size_t gd0 = m * n;\n        const std::vector<size_t> vld{ld0, 1, 1};\n        std::vector<size_t> vgd{gd0, 1, 1};\n\n        handle.AddKernel(kernel_name, network_config, program_name, kernel_name, vld, vgd, params)(\n            in, out);\n    }\n\n    return handle.GetKernelTime();\n}\n} // namespace miopen\n", "meta": {"hexsha": "81e544af70b61ecaafbbde6cbfa715375766eb2e", "size": 38657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ocl/utilocl.cpp", "max_stars_repo_name": "luxteam/MIOpen", "max_stars_repo_head_hexsha": "f7b73815c1f9c3ccb95ed759590277de0be74cef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-13T10:34:34.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-21T13:35:47.000Z", "max_issues_repo_path": "src/ocl/utilocl.cpp", "max_issues_repo_name": "luxteam/MIOpen", "max_issues_repo_head_hexsha": "f7b73815c1f9c3ccb95ed759590277de0be74cef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2019-07-22T09:45:51.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-21T08:35:47.000Z", "max_forks_repo_path": "src/ocl/utilocl.cpp", "max_forks_repo_name": "luxteam/MIOpen", "max_forks_repo_head_hexsha": "f7b73815c1f9c3ccb95ed759590277de0be74cef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-12T08:27:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-11T12:01:20.000Z", "avg_line_length": 34.8889891697, "max_line_length": 100, "alphanum_fraction": 0.4686602685, "num_tokens": 9582, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.3738758367247084, "lm_q1q2_score": 0.21591155742613397}}
{"text": "#pragma once\n#ifndef ALGORITHM_CALC_FIXPOINT_HPP\n#define ALGORITHM_CALC_FIXPOINT_HPP\n\n#include \"devavxprng.h\"\n#include \"dSFMTAVX2search.hpp\"\n//#include \"Annihilate.hpp\"\n#include <errno.h>\n#include <stdlib.h>\n#include <getopt.h>\n#include <errno.h>\n#include <NTL/GF2X.h>\n#include <NTL/GF2XFactoring.h>\n#include <MTToolBox/period.hpp>\n#include <MTToolBox/AlgorithmReducibleRecursionSearch.hpp>\n\nnamespace MTToolBox {\n    template<typename G, typename U>\n    U calc_fixpoint(const G& dsfmt, const NTL::GF2X& irreducible,\n                         const NTL::GF2X& quotient)\n    {\n        using namespace std;\n        GF2X a, b, d;\n        G dsfmt_const(dsfmt);\n        /* a*irreducible + b*quotient = d */\n        XGCD(d, a, b, irreducible, quotient);\n        if (deg(d) != 0) {\n            cout << \"failure d != 1\" << endl;\n            throw new logic_error(\"failure d != 1\");\n        }\n        b *= quotient;\n        a *= irreducible;\n        dsfmt_const.setConst();\n        //Annihilate<G> annihilate;\n        annihilate<U>(&dsfmt_const, b);\n\n        GF2X t1(1, 1);\n        SetCoeff(t1, 0);\n        /* a*irreducible + b*t1 = d */\n        XGCD(d, a, b, irreducible, t1);\n        if (deg(d) != 0) {\n            cout << \"failure d != 1\" << endl;\n            cout << \"deg(d) = \" << dec << deg(d) << endl;\n            cout << \"deg(irreducible) = \" << dec << deg(irreducible) << endl;\n            cout << \"deg(t1) = \" << dec << deg(t1) << endl;\n            throw new logic_error(\"failure d != 1\");\n        }\n        annihilate<U>(&dsfmt_const, b);\n        return dsfmt_const.getParityValue();\n    }\n}\n#endif // ALGORITHM_CALC_FIXPOINT_HPP\n", "meta": {"hexsha": "88393751be078076a400228f1f0a74e07da8219a", "size": 1631, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/AlgorithmCalcFixPoint.hpp", "max_stars_repo_name": "MSaito/DevAVXPRNG", "max_stars_repo_head_hexsha": "3860d6c89437a0aa6bf48f4b0baa2f4756683363", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/AlgorithmCalcFixPoint.hpp", "max_issues_repo_name": "MSaito/DevAVXPRNG", "max_issues_repo_head_hexsha": "3860d6c89437a0aa6bf48f4b0baa2f4756683363", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/AlgorithmCalcFixPoint.hpp", "max_forks_repo_name": "MSaito/DevAVXPRNG", "max_forks_repo_head_hexsha": "3860d6c89437a0aa6bf48f4b0baa2f4756683363", "max_forks_repo_licenses": ["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.7735849057, "max_line_length": 77, "alphanum_fraction": 0.5628448804, "num_tokens": 473, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804196836383, "lm_q2_score": 0.3486451285660856, "lm_q1q2_score": 0.21573477897477847}}
{"text": "// Copyright (c) 2017-2018 Steven Watanabe\n//\n// Distributed under the Boost Software License Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_UNITS2_ABSOLUTE_HPP_INCLUDED\n#define BOOST_UNITS2_ABSOlUTE_HPP_INCLUDED\n\n#include <boost/units2/unit.hpp>\n#include <type_traits>\n\nnamespace boost {\nnamespace units2 {\n\n// celsius - celsius = kelvin\n// celsius + kelvin = celsius\n// fahrenheit\ntemplate<class Unit, class Offset=std::ratio<0>>\nstruct absolute_unit {\n    absolute_unit() = default;\n    constexpr absolute_unit(Unit, Offset) {}\n    /// INTERNAL ONLY\n    template<class F, class T>\n    using _boost_units2_apply = typename F::template apply_absolute<Unit, Offset>;\n};\n\ntemplate<class Unit, class Offset, class Offset2>\noperator+(absolute_unit<U, Offset>, Offset2) -> absolute_unit<U, Offset + Offset2>;\n\ntemplate<class Unit, class Offset, class Scale, class=requires_scale<Scale>>\nauto operator*(absolute_unit<U, Offset>, Scale) -> absolute_unit<scaled_unit<absolute_unit<U, Offset>, Factor> >\n{ return {}; }\ntemplate<class Unit, std::intmax_t N1, std::intmax_t D1, std::intmax_t N2, std::intmax_t D2>\nauto operator*(absolute_unit<Unit, std::ratio<N1,D1>>, std::ratio<N2,D2>) -> absolute_unit<decltype(Unit{} * std::ratio<N2, D2>), std::ratio_divides<std::ratio<N1,D1>, std::ratio<N2,D2>>>\n{ return {}; }\n\nnamespace detail {\n\nstruct requires_absolute_impl\n{\n    template<class Unit, class Offset>\n    using apply_absolute = void;\n};\ntemplate<class T>\nusing requires_absolute = visit<requires_absolute_impl, T>;\n\nstruct unitdiff_visitor;\n\ntemplate<class Unit>\nusing unitdiff_visit = visit<unitdiff_visitor, T>;\n\ntemplate<class T>\nusing unitdiff_t = detected_or<T, unitdiff_visit, T>;\n\nstruct unitdiff_visitor\n{\n    template<class Unit, class Scale>\n    using apply_scaled = scaled_unit<unitdiff_visit<Unit>, Scale>;\n    template<class Unit, class Offset>\n    using apply_absolute = unitdiff_t<Unit>;\n};\n\n}\n\ntemplate<class Unit, class Offset>\nconstexpr auto operator-(absolute_unit<Unit, Offset>, abosolute_unit<Unit, Offset>) -> detail::unitdiff_t<Unit>\n{ return {}; }\n\ntemplate<class Unit, class Offset>\nconstexpr auto operator+(absolute_unit<Unit, Offset>, detail::unitdiff_t<Unit>) -> absolute_unit<Unit, Offset>\n{ return {}; }\n\ntemplate<class Unit, class Offset>\nconstexpr auto operator+(detail::unitdiff_t<Unit>, absolute_unit<Unit, Offset>) -> absolute_unit<Unit, Offset>\n{ return {}; }\n\ntemplate<class Unit, class Offset>\nconstexpr auto operator-(absolute_unit<Unit, Offset>, detail::unitdiff_t<Unit>) -> absolute_unit<Unit, Offset>\n{ return {}; }\n\ntemplate<class Unit, class Offset>\nconstexpr auto operator+(absolute_unit<Unit, Offset>) -> absolute_unit<Unit, Offset>\n{ return {}; }\n\nnamespace detail {\n\nstruct offset_base_case\n{\n    template<class Unit>\n    using apply_base = void;\n    template<class... T>\n    using apply_composite = void;\n};\n\ntemplate<class Unit, class=visit<offset_base_case, Unit>>\nconstexpr auto base_offset(Unit) -> double { return 0; }\ntemplate<class Unit, class Offset>\nconstexpr auto base_offset(absolute_unit<Unit, Offset>) -> double\n{ return detail::base_offset(Unit{}) + detail::get_value(Offset{}); }\ntemplate<class Unit, class Scale>\nconstexpr auto base_offset(scaled_unit<Unit, Scale>) -> double\n{ return detail::base_offset(Unit{}) * detail::get_value(Scale{}); }\n\n}\n\ntemplate<class From, class To>\nauto conversion_offset(From, To)\n{\n    if constexpr(is_absolute)\n}\n\ntemplate<class From, class To, class T, class=requires_absolute<From>, class=requires_absolute<To>>\nconstexpr auto convert(From, To, T&& value)\n{\n    return (value - detail::base_offset(From)) * conversion_factor(detail::unitdiff_t<From>{}, detail::unitdiff_t<To>{}) + detail::base_offset(To{});\n}\n\n}\n}\n", "meta": {"hexsha": "7250702b43b5610a8f80c224b410ce51c6f3bc62", "size": 3789, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/units2/absolute.hpp", "max_stars_repo_name": "swatanabe/cppnow17-units", "max_stars_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T20:46:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-21T21:21:46.000Z", "max_issues_repo_path": "include/boost/units2/absolute.hpp", "max_issues_repo_name": "swatanabe/cppnow17-units", "max_issues_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/units2/absolute.hpp", "max_forks_repo_name": "swatanabe/cppnow17-units", "max_forks_repo_head_hexsha": "e317aff5255afd11e3ebcd759ae3c824f6c95260", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3140495868, "max_line_length": 187, "alphanum_fraction": 0.7397730272, "num_tokens": 919, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883592602051, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.21568618077856236}}
{"text": "#include <jni.h>\n#include <android/log.h>\n\n#include <cpu-features.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#include <Eigen/Core>\n\nusing namespace std;\n\n#define  LOG_TAG\t\"MatrixOp\"\n#define  LOGI(...)\t__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)\n#define  LOGE(...)\t__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)\n\ntemplate <typename T1, typename T2> void c_mulVector(T1 matrix[], T2 vector[], int rows, int cols, T1 result[]);\n//void arm_neon_mulVector3F(float matrix[], float vector[], float result[]);\ntemplate <typename T1, typename T2> void c_mulMatrix(T1 matrix1[], T2 matrix2[], int rows1, int cols1, int cols2, T1 result[]);\n//void arm_neon_mulMatrix3F(float matrix1[], float matrix2[], float result[]);\n\n//bool neon = (android_getCpuFamily() == ANDROID_CPU_FAMILY_ARM) && ((android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) != 0);\n\nextern \"C\"\n{\n\tJNIEXPORT jfloatArray JNICALL Java_it_unibo_slam_datatypes_eigen_typefloat_EigenMatrixF_matrixMulVectorF(JNIEnv *env, jobject obj,\n\t\t\tjfloatArray m, jfloatArray v, jint numRowsMatrix, jint numColsMatrix);\n\tJNIEXPORT jfloatArray JNICALL Java_it_unibo_slam_datatypes_eigen_typefloat_EigenMatrixF_matrixMulMatrixF(JNIEnv *env, jobject obj,\n\t\t\tjfloatArray m1, jfloatArray m2, jint numRowsMatrix1, jint numColsMatrix1, jint numColsMatrix2);\n\tJNIEXPORT jfloatArray JNICALL Java_it_unibo_slam_datatypes_eigen_typefloat_EigenMatrixF_matrixMulVectorFD(JNIEnv *env, jobject obj,\n\t\t\tjfloatArray m, jdoubleArray v, jint numRowsMatrix, jint numColsMatrix);\n\tJNIEXPORT jfloatArray JNICALL Java_it_unibo_slam_datatypes_eigen_typefloat_EigenMatrixF_matrixMulMatrixFD(JNIEnv *env, jobject obj,\n\t\t\tjfloatArray m1, jdoubleArray m2, jint numRowsMatrix1, jint numColsMatrix1, jint numColsMatrix2);\n\tJNIEXPORT jdoubleArray JNICALL Java_it_unibo_slam_datatypes_eigen_typedouble_EigenMatrixD_matrixMulVectorD(JNIEnv *env, jobject obj,\n\t\t\tjdoubleArray m, jdoubleArray v, jint numRowsMatrix, jint numColsMatrix);\n\tJNIEXPORT jdoubleArray JNICALL Java_it_unibo_slam_datatypes_eigen_typedouble_EigenMatrixD_matrixMulMatrixD(JNIEnv *env, jobject obj,\n\t\t\tjdoubleArray m1, jdoubleArray m2, jint numRowsMatrix1, jint numColsMatrix1, jint numColsMatrix2);\n\tJNIEXPORT jdoubleArray JNICALL Java_it_unibo_slam_datatypes_eigen_typedouble_EigenMatrixD_matrixMulVectorDF(JNIEnv *env, jobject obj,\n\t\t\tjdoubleArray m, jfloatArray v, jint numRowsMatrix, jint numColsMatrix);\n\tJNIEXPORT jdoubleArray JNICALL Java_it_unibo_slam_datatypes_eigen_typedouble_EigenMatrixD_matrixMulMatrixDF(JNIEnv *env, jobject obj,\n\t\t\tjdoubleArray m1, jfloatArray m2, jint numRowsMatrix1, jint numColsMatrix1, jint numColsMatrix2);\n}\n\nJNIEXPORT jfloatArray JNICALL Java_it_unibo_slam_datatypes_eigen_typefloat_EigenMatrixF_matrixMulVectorF(JNIEnv *env, jobject obj,\n\t\tjfloatArray m, jfloatArray v, jint numRowsMatrix, jint numColsMatrix)\n{\n\tjfloatArray result;\n\tint rows = numRowsMatrix;\n\tint cols = numColsMatrix;\n\tint sizeMatrix = rows * cols;\n\tresult = env->NewFloatArray(rows);\n\n\tfloat *tempResult = new float[rows];\n\tfloat *tempM = new float[sizeMatrix];\n\tfloat *tempV = new float[cols];\n\n\tenv->GetFloatArrayRegion(m, 0, sizeMatrix, tempM);\n\tenv->GetFloatArrayRegion(v, 0, cols, tempV);\n\n\tc_mulVector<float, float>(tempM, tempV, rows, cols, tempResult);\n\n\tenv->SetFloatArrayRegion(result, 0, rows, tempResult);\n\n\tdelete [] tempResult;\n\tdelete [] tempM;\n\tdelete [] tempV;\n\n\treturn result;\n}\n\nJNIEXPORT jfloatArray JNICALL Java_it_unibo_slam_datatypes_eigen_typefloat_EigenMatrixF_matrixMulMatrixF(JNIEnv *env, jobject obj,\n\t\tjfloatArray m1, jfloatArray m2, jint numRowsMatrix1, jint numColsMatrix1, jint numColsMatrix2)\n{\n\tjfloatArray result;\n\tint rows1 = numRowsMatrix1;\n\tint cols1 = numColsMatrix1;\n\tint cols2 = numColsMatrix2;\n\tint sizeMatrix1 = rows1 * cols1;\n\tint sizeMatrix2 = cols1 * cols2;\n\tint sizeResult = rows1 * cols2;\n\tresult = env->NewFloatArray(sizeResult);\n\n\tfloat *tempResult = new float[sizeResult];\n\tfloat *tempM1 = new float[sizeMatrix1];\n\tfloat *tempM2 = new float[sizeMatrix2];\n\n\tenv->GetFloatArrayRegion(m1, 0, sizeMatrix1, tempM1);\n\tenv->GetFloatArrayRegion(m2, 0, sizeMatrix2, tempM2);\n\n\tc_mulMatrix<float, float>(tempM1, tempM2, rows1, cols1, cols2, tempResult);\n\n\tenv->SetFloatArrayRegion(result, 0, sizeResult, tempResult);\n\n\tdelete [] tempResult;\n\tdelete [] tempM1;\n\tdelete [] tempM2;\n\n\treturn result;\n}\n\nJNIEXPORT jfloatArray JNICALL Java_it_unibo_slam_datatypes_eigen_typefloat_EigenMatrixF_matrixMulVectorFD(JNIEnv *env, jobject obj,\n\t\tjfloatArray m, jdoubleArray v, jint numRowsMatrix, jint numColsMatrix)\n{\n\tjfloatArray result;\n\tint rows = numRowsMatrix;\n\tint cols = numColsMatrix;\n\tint sizeMatrix = rows * cols;\n\tresult = env->NewFloatArray(rows);\n\n\tfloat *tempResult = new float[rows];\n\tfloat *tempM = new float[sizeMatrix];\n\tdouble *tempV = new double[cols];\n\n\tenv->GetFloatArrayRegion(m, 0, sizeMatrix, tempM);\n\tenv->GetDoubleArrayRegion(v, 0, cols, tempV);\n\n\tc_mulVector<float, double>(tempM, tempV, rows, cols, tempResult);\n\n\tenv->SetFloatArrayRegion(result, 0, rows, tempResult);\n\n\tdelete [] tempResult;\n\tdelete [] tempM;\n\tdelete [] tempV;\n\n\treturn result;\n}\n\nJNIEXPORT jfloatArray JNICALL Java_it_unibo_slam_datatypes_eigen_typefloat_EigenMatrixF_matrixMulMatrixFD(JNIEnv *env, jobject obj,\n\t\tjfloatArray m1, jdoubleArray m2, jint numRowsMatrix1, jint numColsMatrix1, jint numColsMatrix2)\n{\n\tjfloatArray result;\n\tint rows1 = numRowsMatrix1;\n\tint cols1 = numColsMatrix1;\n\tint cols2 = numColsMatrix2;\n\tint sizeMatrix1 = rows1 * cols1;\n\tint sizeMatrix2 = cols1 * cols2;\n\tint sizeResult = rows1 * cols2;\n\tresult = env->NewFloatArray(sizeResult);\n\n\tfloat *tempResult = new float[sizeResult];\n\tfloat *tempM1 = new float[sizeMatrix1];\n\tdouble *tempM2 = new double[sizeMatrix2];\n\n\tenv->GetFloatArrayRegion(m1, 0, sizeMatrix1, tempM1);\n\tenv->GetDoubleArrayRegion(m2, 0, sizeMatrix2, tempM2);\n\n\tc_mulMatrix<float, double>(tempM1, tempM2, rows1, cols1, cols2, tempResult);\n\n\tenv->SetFloatArrayRegion(result, 0, sizeResult, tempResult);\n\n\tdelete [] tempResult;\n\tdelete [] tempM1;\n\tdelete [] tempM2;\n\n\treturn result;\n}\n\nJNIEXPORT jdoubleArray JNICALL Java_it_unibo_slam_datatypes_eigen_typedouble_EigenMatrixD_matrixMulVectorD(JNIEnv *env, jobject obj,\n\t\tjdoubleArray m, jdoubleArray v, jint numRowsMatrix, jint numColsMatrix)\n{\n\tjdoubleArray result;\n\tint rows = numRowsMatrix;\n\tint cols = numColsMatrix;\n\tint sizeMatrix = rows * cols;\n\tresult = env->NewDoubleArray(rows);\n\n\tdouble *tempResult = new double[rows];\n\tdouble *tempM = new double[sizeMatrix];\n\tdouble *tempV = new double[cols];\n\n\tenv->GetDoubleArrayRegion(m, 0, sizeMatrix, tempM);\n\tenv->GetDoubleArrayRegion(v, 0, cols, tempV);\n\n\tc_mulVector<double, double>(tempM, tempV, rows, cols, tempResult);\n\n\tenv->SetDoubleArrayRegion(result, 0, rows, tempResult);\n\n\tdelete [] tempResult;\n\tdelete [] tempM;\n\tdelete [] tempV;\n\n\treturn result;\n}\n\nJNIEXPORT jdoubleArray JNICALL Java_it_unibo_slam_datatypes_eigen_typedouble_EigenMatrixD_matrixMulMatrixD(JNIEnv *env, jobject obj,\n\t\tjdoubleArray m1, jdoubleArray m2, jint numRowsMatrix1, jint numColsMatrix1, jint numColsMatrix2)\n{\n\tjdoubleArray result;\n\tint rows1 = numRowsMatrix1;\n\tint cols1 = numColsMatrix1;\n\tint cols2 = numColsMatrix2;\n\tint sizeMatrix1 = rows1 * cols1;\n\tint sizeMatrix2 = cols1 * cols2;\n\tint sizeResult = rows1 * cols2;\n\tresult = env->NewDoubleArray(sizeResult);\n\n\tdouble *tempResult = new double[sizeResult];\n\tdouble *tempM1 = new double[sizeMatrix1];\n\tdouble *tempM2 = new double[sizeMatrix2];\n\n\tenv->GetDoubleArrayRegion(m1, 0, sizeMatrix1, tempM1);\n\tenv->GetDoubleArrayRegion(m2, 0, sizeMatrix2, tempM2);\n\n\tc_mulMatrix<double, double>(tempM1, tempM2, rows1, cols1, cols2, tempResult);\n\n\tenv->SetDoubleArrayRegion(result, 0, sizeResult, tempResult);\n\n\tdelete [] tempResult;\n\tdelete [] tempM1;\n\tdelete [] tempM2;\n\n\treturn result;\n}\n\nJNIEXPORT jdoubleArray JNICALL Java_it_unibo_slam_datatypes_eigen_typedouble_EigenMatrixD_matrixMulVectorDF(JNIEnv *env, jobject obj,\n\t\tjdoubleArray m, jfloatArray v, jint numRowsMatrix, jint numColsMatrix)\n{\n\tjdoubleArray result;\n\tint rows = numRowsMatrix;\n\tint cols = numColsMatrix;\n\tint sizeMatrix = rows * cols;\n\tresult = env->NewDoubleArray(rows);\n\n\tdouble *tempResult = new double[rows];\n\tdouble *tempM = new double[sizeMatrix];\n\tfloat *tempV = new float[cols];\n\n\tenv->GetDoubleArrayRegion(m, 0, sizeMatrix, tempM);\n\tenv->GetFloatArrayRegion(v, 0, cols, tempV);\n\n\tc_mulVector<double, float>(tempM, tempV, rows, cols, tempResult);\n\n\tenv->SetDoubleArrayRegion(result, 0, rows, tempResult);\n\n\tdelete [] tempResult;\n\tdelete [] tempM;\n\tdelete [] tempV;\n\n\treturn result;\n}\n\nJNIEXPORT jdoubleArray JNICALL Java_it_unibo_slam_datatypes_eigen_typedouble_EigenMatrixD_matrixMulMatrixDF(JNIEnv *env, jobject obj,\n\t\tjdoubleArray m1, jfloatArray m2, jint numRowsMatrix1, jint numColsMatrix1, jint numColsMatrix2)\n{\n\tjdoubleArray result;\n\tint rows1 = numRowsMatrix1;\n\tint cols1 = numColsMatrix1;\n\tint cols2 = numColsMatrix2;\n\tint sizeMatrix1 = rows1 * cols1;\n\tint sizeMatrix2 = cols1 * cols2;\n\tint sizeResult = rows1 * cols2;\n\tresult = env->NewDoubleArray(sizeResult);\n\n\tdouble *tempResult = new double[sizeResult];\n\tdouble *tempM1 = new double[sizeMatrix1];\n\tfloat *tempM2 = new float[sizeMatrix2];\n\n\tenv->GetDoubleArrayRegion(m1, 0, sizeMatrix1, tempM1);\n\tenv->GetFloatArrayRegion(m2, 0, sizeMatrix2, tempM2);\n\n\tc_mulMatrix<double, float>(tempM1, tempM2, rows1, cols1, cols2, tempResult);\n\n\tenv->SetDoubleArrayRegion(result, 0, sizeResult, tempResult);\n\n\tdelete [] tempResult;\n\tdelete [] tempM1;\n\tdelete [] tempM2;\n\n\treturn result;\n}\n\ntemplate <typename T1, typename T2>\nvoid c_mulMatrix(T1 matrix1[], T2 matrix2[], int rows1, int cols1, int cols2, T1 result[])\n{\n\tT1 tempVal;\n\n\tfor (int x = 0, y = 0; x < cols2; x++, y += cols1)\n\t{\n\t\tfor (int i = 0; i < rows1; i++, result++)\n\t\t{\n\t\t\ttempVal = 0;\n\t\t\tfor (int j = 0, k = 0; j < cols1; j++, k += rows1)\n\t\t\t\ttempVal += matrix1[i + k] * matrix2[j + y];\n\t\t\t*result = tempVal;\n\t\t}\n\t}\n}\n\ntemplate <typename T1, typename T2>\nvoid c_mulVector(T1 matrix[], T2 vector[], int rows, int cols, T1 result[])\n{\n\tT1 tempVal;\n\n\tfor (int i = 0; i < rows; i++)\n\t{\n\t\ttempVal = 0;\n\t\tfor (int j = 0, k = 0; j < cols; j++, k += rows)\n\t\t\ttempVal += matrix[i + k] * (T1)vector[j];\n\t\tresult[i] = tempVal;\n\t}\n}\n\n/*void arm_neon_mulVector3F(float matrix[], float vector[], float result[])\n{\n\tint temp;\n\tasm volatile\n\t(\n\t\t\"mov                    %3, #12\t\t\t\t\t\t\\n\\t\"   //r3 = 12\n\t\t\"vld1.32                {d0, d1}, [%1]             \t\\n\\t\"   //Q0 = v\n\t\t\"vld1.32                {d2, d3}, [%0], %3     \t\t\\n\\t\"   //Q1 = m\n\t\t\"vld1.32                {d4, d5}, [%0], %3        \t\\n\\t\"   //Q2 = m+12\n\t\t\"vld1.32                {d6, d7}, [%0], %3         \t\\n\\t\"   //Q3 = m+24\n\n\t\t\"vmul.f32               q9, q1, d0[0]             \t\\n\\t\"   //Q9 = Q1*Q0[0]\n\t\t\"vmla.f32               q9, q2, d0[1]              \t\\n\\t\"   //Q9 += Q2*Q0[1]\n\t\t\"vmla.f32               q9, q3, d1[0]              \t\\n\\t\"   //Q9 += Q3*Q0[2]\n\t\t\"vmov.f32               q0, q9           \t\t\t\\n\\t\"   //Q0 = q9\n\n\t\t\"vst1.32                d0, [%2]!                \t\\n\\t\"   //r2 = D24\n\t\t\"fsts                   s2, [%2]                 \t\\n\\t\"   //r2 = D25[0]\n\n\t\t:\n\t\t: \"r\" (matrix), \"r\" (vector), \"r\" (result), \"r\" (temp)\n\t\t: \"q0\", \"q9\", \"q10\", \"q11\", \"q12\", \"q13\", \"memory\"\n\t);\n}\n\nvoid arm_neon_mulMatrix3F(float matrix1[], float matrix2[], float result[])\n{\n\tasm volatile\n\t(\n\t\t\"vld1.32                {d0, d1}, [%1]!\t\t\t\\n\\t\"   //q0 = m1\n\t\t\"vld1.32                {d2, d3}, [%1]!\t\t\t\\n\\t\"   //q1 = m1+4\n\t\t\"flds                   s8, [%1]\t\t\t\t\\n\\t\"   //q2 = m1+8\n\n\t\t\"vld1.32                {d6, d7}, [%0]\t\t\t\\n\\t\"   //q3[0] = m0\n\t\t\"add                    %0, %0, #12\t\t\t\t\\n\\t\"   //q3[0] = m0\n\t\t\"vld1.32                {d8, d9}, [%0]\t\t\t\\n\\t\"   //q4[0] = m0+12\n\t\t\"add                    %0, %0, #12\t\t\t\t\\n\\t\"   //q3[0] = m0\n\t\t\"vld1.32                {d10}, [%0]\t\t\t\t\\n\\t\"   //q5[0] = m0+24\n\t\t\"add                    %0, %0, #8\t\t\t\t\\n\\t\"   //q3[0] = m0\n\t\t\"flds                   s22, [%0]\t\t\t\t\\n\\t\"   //q2 = m1+8\n\n\t\t\"vmul.f32               q6, q3, d0[0]\t\t\t\\n\\t\"   //q12 = q3 * d0[0]\n\t\t\"vmul.f32               q7, q3, d1[1]\t\t\t\\n\\t\"   //q13 = q3 * d2[0]\n\t\t\"vmul.f32               q8, q3, d3[0]\t\t\t\\n\\t\"   //q14 = q3 * d4[0]\n\t\t\"vmla.f32               q6, q4, d0[1] \t\t\t\\n\\t\"   //q12 = q9 * d0[1]\n\t\t\"vmla.f32               q7, q4, d2[0]    \t\t\\n\\t\"   //q13 = q9 * d2[1]\n\t\t\"vmla.f32               q8, q4, d3[1] \t\t\t\\n\\t\"   //q14 = q9 * d4[1]\n\t\t\"vmla.f32               q6, q5, d1[0]\t\t\t\\n\\t\"   //q12 = q10 * d0[0]\n\t\t\"vmla.f32               q7, q5, d2[1]\t\t\t\\n\\t\"   //q13 = q10 * d2[0]\n\t\t\"vmla.f32               q8, q5, d4[0]\t\t\t\\n\\t\"   //q14 = q10 * d4[0]\n\n\t\t\"vmov.f32               q0, q8\t\t\t\t\t\\n\\t\"   //q14 = q10 * d4[0]\n\t\t\"vst1.32                {d12, d13}, [%2]\t\t\\n\\t\"   //d = q12\n\t\t\"add                    %2, %2, #12\t\t\t\t\\n\\t\"   //q3[0] = m0\n\t\t\"vst1.32                {d14, d15}, [%2]\t\t\\n\\t\"   //d+4 = q13\n\t\t\"add                    %2, %2, #12\t\t\t\t\\n\\t\"   //q3[0] = m0\n\t\t\"vst1.32                {d0}, [%2]\t\t\t\t\\n\\t\"   //d+8 = q14\n\t\t\"add                    %2, %2, #8\t\t\t\t\\n\\t\"   //q3[0] = m0\n\t\t\"fsts                   s2, [%2]\t\t\t\t\\n\\t\"   //d = q12\n\n\t\t:\n\t\t: \"r\"(matrix1), \"r\"(matrix2), \"r\"(result)\n\t\t: \"d8\", \"d9\", \"d10\", \"d11\", \"d12\", \"d13\", \"d14\", \"d15\", \"memory\"\n\t);\n}*/\n", "meta": {"hexsha": "11d747a1eb97a139de8a67ef7512c38a0c95f516", "size": 13245, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jni/eigen/MatrixOp.cpp", "max_stars_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_stars_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T15:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T23:07:15.000Z", "max_issues_repo_path": "jni/eigen/MatrixOp.cpp", "max_issues_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_issues_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-01-31T05:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-26T14:06:53.000Z", "max_forks_repo_path": "jni/eigen/MatrixOp.cpp", "max_forks_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_forks_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-08-08T12:18:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T08:07:55.000Z", "avg_line_length": 35.8943089431, "max_line_length": 134, "alphanum_fraction": 0.6637976595, "num_tokens": 4348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21554879684473494}}
{"text": "// This file is part of LatNet Builder.\n//\n// Copyright (C) 2012-2021  The LatNet Builder author's, supervised by Pierre L'Ecuyer, Universite de Montreal.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"netbuilder/NetConstructionTraits.h\"\n#include \"netbuilder/Helpers/JoeKuo.h\"\n\n#include <sstream>\n#include <boost/algorithm/string/erase.hpp>\n\n\nnamespace NetBuilder {\n\n    const std::string NetConstructionTraits<NetConstruction::LMS>::name = \"LMS\";\n    \n    typedef typename NetConstructionTraits<NetConstruction::LMS>::GenValue GenValue;\n\n    typedef std::vector<uInteger> DirectionNumber;\n    typedef std::pair<unsigned int, unsigned int> PrimitivePolynomial; \n    typedef std::vector<std::vector<bool>> BinaryMatrix;\n\n    typedef NetConstructionTraits<NetConstruction::LMS>::SizeParameter SizeParameter;\n\n    bool NetConstructionTraits<NetConstruction::LMS>::checkGenValue(const GenValue& genValue, const SizeParameter& sizeParameter)\n    {\n        return genValue.nRows() == nRows(sizeParameter) && genValue.nCols() == nCols(sizeParameter);\n    }\n\n    unsigned int NetConstructionTraits<NetConstruction::LMS>::nRows(const SizeParameter& sizeParameter) {return (unsigned int) sizeParameter.first.first; }\n\n    unsigned int NetConstructionTraits<NetConstruction::LMS>::nCols(const SizeParameter& sizeParameter) {return (unsigned int) sizeParameter.first.second; }\n\n    GeneratingMatrix*  NetConstructionTraits<NetConstruction::LMS>::createGeneratingMatrix(const GenValue& genValue, const SizeParameter& sizeParameter, const Dimension& dimension_j, const unsigned int nRows)\n    {\n        GeneratingMatrix* result = new GeneratingMatrix(genValue * *sizeParameter.second[dimension_j]);\n        unsigned int finalnRows = (nRows == 0)? NetConstructionTraits<NetConstruction::LMS>::nRows(sizeParameter) : nRows;\n        result->resize(finalnRows, nCols(sizeParameter));\n        return result;\n    }\n\n    std::vector<GenValue> NetConstructionTraits<NetConstruction::LMS>::genValueSpaceCoord(Dimension coord, const SizeParameter& sizeParameter)\n    {\n        throw std::logic_error(\"The space of all matrices is far too big to be exhautively explored.\");\n        return std::vector<GenValue>{};\n    }\n\n    std::vector<std::vector<GenValue>> NetConstructionTraits<NetConstruction::LMS>::genValueSpace(Dimension dimension, const SizeParameter& sizeParameter)\n    {\n        throw std::logic_error(\"The space of all matrices is far too big to be exhautively explored.\");\n        return std::vector<std::vector<GenValue>>{};\n    }\n\n    std::string NetConstructionTraits<NetConstruction::LMS>::format(const std::vector<std::shared_ptr<GeneratingMatrix>>& genMatrices, const std::vector<std::shared_ptr<GenValue>>& genVals, const SizeParameter& sizeParameter, OutputStyle outputStyle, unsigned int interlacingFactor)\n    {\n        std::ostringstream stream;\n        \n        if (outputStyle == OutputStyle::TERMINAL){\n            stream << \"Left-Matrix-Scrambled Digital Net - Matrix size = \" << sizeParameter.first.first << \"x\" << sizeParameter.first.second << std::endl;\n            stream << \"Printing only the scrambled generating matrices - see output.txt file for original matrices and scrambling matrices.\\n\";\n            for (Dimension dim = 0; dim < genMatrices.size(); ++dim)\n            {\n                stream << \"Coordinate \" << dim << std::endl;\n                stream << *genMatrices[dim] << std::endl;\n            }\n        }\n\n        else if (outputStyle == OutputStyle::RANDOMIZED_NET){\n            unsigned long dimension = genMatrices.size();\n            unsigned int nb_col = sizeParameter.first.second;\n            stream << \"# Parameters for a digital net in base 2\\n\";\n            stream << dimension / interlacingFactor << \"    # s = \" << dimension / interlacingFactor << \" dimensions\\n\";\n            if (interlacingFactor > 1){\n                stream << interlacingFactor << \"    # Interlacing factor\" << \"\\n\";\n                stream << dimension << \"    # Number of components = interlacing factor x dimension\" << \"\\n\";\n            }\n            stream << nb_col << \"    # k = \" << nb_col << \",  n = 2^\" << nb_col << \" = \"; \n            stream << (int)pow(2,nb_col) << \" points\"<< std::endl;\n            stream << \"31    # r = 31 binary output digits\\n\";\n\n            if (interlacingFactor == 1){\n                stream << \"# Columns of original gen. matrices C_1,...,C_s, one matrix per line\\n\";\n            }\n            else {\n                stream << \"# Columns of original gen. matrices C_1,...,C_{ds}, one matrix per line\\n\";\n            }\n            for(unsigned int coord = 0; coord < dimension; coord++)\n            {\n                stream << sizeParameter.second[coord]->formatToColumnsReverse();\n                stream << \"\\n\";\n            }\n\n            if (interlacingFactor == 1){\n                stream << \"# Columns of scrambling matrices C_1,...,C_s, one matrix per line\\n\";\n            }\n            else {\n                stream << \"# Columns of scrambling matrices C_1,...,C_{ds}, one matrix per line\\n\";\n            }\n            for(unsigned int coord = 0; coord < dimension; coord++)\n            {\n                stream << genVals[coord]->formatToColumnsReverse();\n                stream << \"\\n\";\n            }\n\n            if (interlacingFactor == 1){\n                stream << \"# Columns of scrambled gen. matrices C_1,...,C_s, one matrix per line\\n\";\n            }\n            else {\n                stream << \"# Columns of scrambled gen. matrices C_1,...,C_{ds}, one matrix per line\\n\";\n            }\n            for(unsigned int coord = 0; coord < dimension; coord++)\n            {\n                stream << genMatrices[coord]->formatToColumnsReverse();\n                if (coord < dimension - 1){\n                    stream << \"\\n\";\n                }\n            }\n        }\n        return stream.str();\n    }  \n}\n", "meta": {"hexsha": "0b75dccfe3bbae806c89a82016434b64e0365ed1", "size": 6384, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/NetBuilder/NetConstructionTraits-LMS.cc", "max_stars_repo_name": "YochevedDarmon/latnetbuilder", "max_stars_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-01-21T06:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-24T16:11:31.000Z", "max_issues_repo_path": "src/NetBuilder/NetConstructionTraits-LMS.cc", "max_issues_repo_name": "YochevedDarmon/latnetbuilder", "max_issues_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-10-31T07:49:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-03T12:07:49.000Z", "max_forks_repo_path": "src/NetBuilder/NetConstructionTraits-LMS.cc", "max_forks_repo_name": "YochevedDarmon/latnetbuilder", "max_forks_repo_head_hexsha": "7df3a7ba89e10ca51d4af347b75cdb0987e5151c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2016-07-27T19:25:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-05-22T20:00:47.000Z", "avg_line_length": 48.0, "max_line_length": 282, "alphanum_fraction": 0.6296992481, "num_tokens": 1429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.21549177171580447}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2019 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Alexander Sokolov <asokolov@nil.foundation>\n//\n// Distributed under the Boost Software License, Version 1.0\n// See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_HASH_SPONGE_CONSTRUCTION_HPP\n#define CRYPTO3_HASH_SPONGE_CONSTRUCTION_HPP\n\n#include <boost/crypto3/detail/static_digest.hpp>\n#include <boost/crypto3/detail/pack.hpp>\n\n#include <boost/crypto3/hash/detail/nop_finalizer.hpp>\n\nnamespace boost {\n    namespace crypto3 {\n        namespace hashes {\n            /*!\n             * @brief\n             * @tparam DigestEndian\n             * @tparam DigestBits\n             * @tparam IV\n             * @tparam Compressor\n             * @tparam Finalizer\n             *\n             * The Sponge construction builds a block hashes from a\n             * one-way compressor.  As this version operated on the block\n             * level, it doesn't contain any padding or other strengthening.\n             * For a Wide Pipe construction, use a digest that will\n             * truncate the internal state.\n             */\n            template<typename Params,\n                     typename IV,\n                     typename Compressor,\n                     typename Padding,\n                     typename Finalizer = detail::nop_finalizer>\n            class sponge_construction {\n            public:\n                typedef IV iv_generator;\n                typedef Compressor compressor_functor;\n                typedef Padding padding_functor;\n                typedef Finalizer finalizer_functor;\n\n                typedef typename Params::digest_endian endian_type;\n\n                constexpr static const std::size_t word_bits = compressor_functor::word_bits;\n                typedef typename compressor_functor::word_type word_type;\n\n                constexpr static const std::size_t state_bits = compressor_functor::state_bits;\n                constexpr static const std::size_t state_words = compressor_functor::state_words;\n                typedef typename compressor_functor::state_type state_type;\n\n                constexpr static const std::size_t block_bits = compressor_functor::block_bits;\n                constexpr static const std::size_t block_words = compressor_functor::block_words;\n                typedef typename compressor_functor::block_type block_type;\n\n                constexpr static const std::size_t digest_bits = Params::digest_bits;\n                constexpr static const std::size_t digest_bytes = digest_bits / octet_bits;\n                constexpr static const std::size_t digest_words = digest_bits / word_bits;\n                typedef static_digest<digest_bits> digest_type;\n\n                template<typename Integer = std::size_t>\n                inline sponge_construction &process_block(const block_type &block, Integer seen = Integer()) {\n                    compressor_functor::process_block(state_, block);\n                    return *this;\n                }\n\n                inline digest_type digest(const block_type &block = block_type(),\n                                          std::size_t total_seen = std::size_t()) {\n                    using namespace boost::crypto3::detail;\n\n                    block_type b = block;\n                    std::size_t block_seen = total_seen % block_bits;\n                    // Process block if it is full\n                    if (total_seen && !block_seen)\n                        process_block(b);\n\n                    std::size_t copy_seen = block_seen;\n                    // Pad last message block\n                    padding_functor padding;\n                    padding(b, block_seen);\n                    process_block(b);\n\n                    // Process additional block if not all bits were padded\n                    if (!padding.is_last_block()) {\n                        std::fill(b.begin(), b.end(), 0);\n                        padding.process_last(b, copy_seen);\n                        process_block(b);\n                    }\n\n                    // Apply finalizer\n                    finalizer_functor()(state_);\n\n                    // Convert digest to byte representation\n                    std::array<octet_type, state_bits / octet_bits> d_full;\n                    pack_from<endian_type, word_bits, octet_bits>(state_.begin(), state_.end(), d_full.begin());\n\n                    digest_type d;\n                    std::copy(d_full.begin(), d_full.begin() + digest_bytes, d.begin());\n\n                    return d;\n                }\n\n                sponge_construction() {\n                    reset();\n                }\n\n                void reset(state_type const &s) {\n                    state_ = s;\n                }\n\n                void reset() {\n                    iv_generator iv;\n                    reset(iv());\n                }\n\n                state_type const &state() const {\n                    return state_;\n                }\n\n            private:\n                state_type state_;\n            };\n\n        }    // namespace hashes\n    }        // namespace crypto3\n}    // namespace boost\n\n#endif    // CRYPTO3_HASH_SPONGE_CONSTRUCTION_HPP\n", "meta": {"hexsha": "673ee28b117e1d5783e2818d6fb9301a4ad43d56", "size": 5367, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/crypto3/hash/detail/sponge_construction.hpp", "max_stars_repo_name": "NilFoundation/boost-crypto", "max_stars_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-02T06:19:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-07T04:55:03.000Z", "max_issues_repo_path": "include/boost/crypto3/hash/detail/sponge_construction.hpp", "max_issues_repo_name": "NilFoundation/boost-crypto", "max_issues_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-04-06T21:49:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-18T04:54:51.000Z", "max_forks_repo_path": "include/boost/crypto3/hash/detail/sponge_construction.hpp", "max_forks_repo_name": "NilFoundation/boost-crypto", "max_forks_repo_head_hexsha": "a3e599b780bbbbc063b7c8da0e498125769e08be", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-13T21:14:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-13T21:14:37.000Z", "avg_line_length": 40.3533834586, "max_line_length": 112, "alphanum_fraction": 0.5321408608, "num_tokens": 952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2154772179595958}}
{"text": "\n#ifndef OFFPOLSETACFITTED_HPP\n#define OFFPOLSETACFITTED_HPP\n\n#include <vector>\n#include <string>\n#include <boost/serialization/list.hpp>\n#include <boost/serialization/set.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/filesystem.hpp>\n#include <tbb/parallel_for.h>\n#include <tbb/blocked_range.h>\n\n#include \"arch/AACAgent.hpp\"\n#include \"bib/Seed.hpp\"\n#include \"bib/Utils.hpp\"\n#include <bib/MetropolisHasting.hpp>\n#include <bib/XMLEngine.hpp>\n#include \"MLP.hpp\"\n#include \"LinMLP.hpp\"\n#include \"kde.hpp\"\n#include \"kdtree++/kdtree.hpp\"\n\n#define DOUBLE_COMPARE_PRECISION 1e-9\n\ntypedef struct _sample {\n  std::vector<double> s;\n  std::vector<double> pure_a;\n  std::vector<double> a;\n  std::vector<double> next_s;\n  double r;\n  bool goal_reached;\n  double p0;\n\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive& ar, const unsigned int) {\n    ar& BOOST_SERIALIZATION_NVP(s);\n    ar& BOOST_SERIALIZATION_NVP(pure_a);\n    ar& BOOST_SERIALIZATION_NVP(a);\n    ar& BOOST_SERIALIZATION_NVP(next_s);\n    ar& BOOST_SERIALIZATION_NVP(r);\n    ar& BOOST_SERIALIZATION_NVP(goal_reached);\n  }\n\n  //Used to store all sample into a tree, might be stochastic\n  //only pure_a is negligate\n  bool operator< (const _sample& b) const {\n    for (uint i = 0; i < s.size(); i++) {\n      if(fabs(s[i] - b.s[i])>=DOUBLE_COMPARE_PRECISION)\n        return s[i] < b.s[i];\n    }\n    \n    for (uint i = 0; i < a.size(); i++) {\n      if(fabs(a[i] - b.a[i])>=DOUBLE_COMPARE_PRECISION)\n        return a[i] < b.a[i];\n    }\n    \n    for (uint i = 0; i < next_s.size(); i++) {\n      if(fabs(next_s[i] - b.next_s[i])>=DOUBLE_COMPARE_PRECISION)\n        return next_s[i] < b.next_s[i];\n    }\n    \n    if(fabs(r - b.r)>=DOUBLE_COMPARE_PRECISION)\n        return r < b.r;\n\n    return goal_reached < b.goal_reached;\n  }\n  \n  typedef double value_type;\n\n  inline double operator[](size_t const N) const{\n        return s[N];\n  }\n  \n  bool same_state(const _sample& b) const{\n    for (uint i = 0; i < s.size(); i++) {\n      if(fabs(s[i] - b.s[i])>=DOUBLE_COMPARE_PRECISION)\n        return false;\n    }\n    \n    return true;\n  }\n\n} sample;\n\n\nclass OffPolSetACFitted : public arch::AACAgent<MLP, arch::AgentProgOptions> {\n public:\n  typedef MLP PolicyImpl;\n   \n  OffPolSetACFitted(unsigned int _nb_motors, unsigned int _nb_sensors)\n    : arch::AACAgent<MLP, arch::AgentProgOptions>(_nb_motors), nb_sensors(_nb_sensors) {\n\n  }\n\n  virtual ~OffPolSetACFitted() {\n    delete kdtree_s;\n\n    delete vnn;\n    delete ann;\n  }\n\n  const std::vector<double>& _run(double reward, const std::vector<double>& sensors,\n                                 bool learning, bool goal_reached, bool) {\n\n    vector<double>* next_action = ann->computeOut(sensors);\n    \n    if (last_action.get() != nullptr && learning){\n      double p0 = 1.f;\n      for(uint i=0;i < nb_motors;i++)\n        p0 *= exp(-(last_pure_action->at(i)-last_action->at(i))*(last_pure_action->at(i)-last_action->at(i))/(2.f*noise*noise));\n      \n      trajectory.insert({last_state, *last_pure_action, *last_action, sensors, reward, goal_reached, p0});\n      last_trajectory.insert( {last_state, *last_pure_action, *last_action, sensors, reward, goal_reached, p0});\n      proba_s.add_data(last_state);\n      \n      sample sa = {last_state, *last_pure_action, *last_action, sensors, reward, goal_reached, p0};\n      \n      kdtree_s->insert(sa);\n      \n      std::vector<double> psa;\n      std::vector<double> psas;\n      mergeSA(psa, last_state, *last_action);\n      mergeSAS(psas, last_state, *last_action, sensors);\n      \n      proba_sa.add_data(psa);\n      proba_sas.add_data(psas);\n    }\n\n    last_pure_action.reset(new vector<double>(*next_action));\n    if(learning) {\n      if(gaussian_policy){\n        vector<double>* randomized_action = bib::Proba<double>::multidimentionnalGaussianWReject(*next_action, noise);\n        delete next_action;\n        next_action = randomized_action;\n      } else if(bib::Utils::rand01() < noise){ //e-greedy\n        for (uint i = 0; i < next_action->size(); i++)\n          next_action->at(i) = bib::Utils::randin(-1.f, 1.f);\n      }\n    }\n    last_action.reset(next_action);\n\n\n    last_state.clear();\n    for (uint i = 0; i < sensors.size(); i++)\n      last_state.push_back(sensors[i]);\n\n    return *next_action;\n  }\n\n\n  void _unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map*) override {\n    hidden_unit_v           = pt->get<int>(\"agent.hidden_unit_v\");\n    hidden_unit_a           = pt->get<int>(\"agent.hidden_unit_a\");\n    noise                   = pt->get<double>(\"agent.noise\");\n    gaussian_policy         = pt->get<bool>(\"agent.gaussian_policy\");\n    lecun_activation        = pt->get<bool>(\"agent.lecun_activation\");\n    determinist_vnn_update  = pt->get<bool>(\"agent.determinist_vnn_update\");\n    vnn_from_scratch        = pt->get<bool>(\"agent.vnn_from_scratch\");\n    change_policy_each      = pt->get<uint>(\"agent.change_policy_each\");\n    strategy_w              = pt->get<uint>(\"agent.strategy_w\");\n    current_loaded_policy   = pt->get<uint>(\"agent.index_starting_loaded_policy\");\n    converge_precision      = pt->get<double>(\"agent.converge_precision\");\n    number_fitted_iteration = pt->get<uint>(\"agent.number_fitted_iteration\");\n\n    if(hidden_unit_v == 0)\n      vnn = new LinMLP(nb_sensors + nb_motors , 1, 0.0, lecun_activation);\n    else\n      vnn = new MLP(nb_sensors + nb_motors, hidden_unit_v, nb_sensors, 0.0, lecun_activation);\n\n    if(hidden_unit_a == 0)\n      ann = new LinMLP(nb_sensors , nb_motors, 0.0, lecun_activation);\n    else\n      ann = new MLP(nb_sensors, hidden_unit_a, nb_motors, lecun_activation);\n    \n    kdtree_s = new kdtree_sample(nb_sensors);\n  }\n\n  bool learning;\n  void _start_episode(const std::vector<double>& sensors, bool _learning) override {\n    learning = _learning;\n    last_state.clear();\n    for (uint i = 0; i < sensors.size(); i++)\n      last_state.push_back(sensors[i]);\n\n    last_action = nullptr;\n    last_pure_action = nullptr;\n    \n    //trajectory.clear();\n    last_trajectory.clear();\n    \n    fann_reset_MSE(vnn->getNeuralNet());\n    \n    if(episode == 0 || episode % change_policy_each == 0){\n      if (! boost::filesystem::exists( \"polset.\"+std::to_string(current_loaded_policy) ) ){\n        LOG_ERROR(\"file doesn't exists \"<< \"polset.\"+std::to_string(current_loaded_policy));\n        exit(1);\n      }\n      \n      ann->load(\"polset.\"+std::to_string(current_loaded_policy));\n      current_loaded_policy++;\n      end_episode();\n    }\n  }\n  \n  void computePTheta(vector< sample >& vtraj, double *ptheta){\n    uint i=0;\n    for(auto it = vtraj.begin(); it != vtraj.end() ; ++it) {\n      sample sm = *it;\n      vector<double>* next_action = ann->computeOut(sm.s);\n      \n      double p0 = 1.f;\n      for(uint i=0;i < nb_motors;i++)\n        p0 *= exp(-(next_action->at(i)-sm.a[i])*(next_action->at(i)-sm.a[i])/(2.f*noise*noise));\n\n      ptheta[i] = p0;\n      i++;\n      delete next_action;\n    }\n  }\n\n  struct ParraVtoVNext {\n    ParraVtoVNext(const std::vector<sample>& _vtraj, const OffPolSetACFitted* _ptr) : vtraj(_vtraj), ptr(_ptr) {\n      data = fann_create_train(vtraj.size(), ptr->nb_sensors + ptr->nb_motors, 1);\n      for (uint n = 0; n < vtraj.size(); n++) {\n        sample sm = vtraj[n];\n        for (uint i = 0; i < ptr->nb_sensors ; i++)\n          data->input[n][i] = sm.s[i];\n        for (uint i= ptr->nb_sensors ; i < ptr->nb_sensors + ptr->nb_motors; i++)\n          data->input[n][i] = sm.a[i - ptr->nb_sensors];\n      }\n    }\n\n    ~ParraVtoVNext() { //must be empty cause of tbb\n\n    }\n\n    void free() {\n      fann_destroy_train(data);\n    }\n\n    void operator()(const tbb::blocked_range<size_t>& range) const {\n\n      struct fann* local_nn = fann_copy(ptr->vnn->getNeuralNet());\n      struct fann* local_pol = fann_copy(ptr->ann->getNeuralNet());\n\n      for (size_t n = range.begin(); n < range.end(); n++) {\n        sample sm = vtraj[n];\n\n        double delta = sm.r;\n        if (!sm.goal_reached) {\n          std::vector<double> * next_action = MLP::computeOut(local_pol, sm.next_s);\n          double nextQA = MLP::computeOutVF(local_nn, sm.next_s, *next_action);\n          delta += ptr->gamma * nextQA;\n          delete next_action;\n        }\n\n        data->output[n][0] = delta;\n      }\n\n      fann_destroy(local_nn);\n      fann_destroy(local_pol);\n    }\n\n    struct fann_train_data* data;\n    const std::vector<sample>& vtraj;\n    const OffPolSetACFitted* ptr;\n  };\n  \n    void update_critic(){\n      if (trajectory.size() > 2) {\n\n        std::vector<sample> *vtraj; \n        double *importance_sample = nullptr;\n        if(strategy_w == 0){//only on the last data\n          vtraj = new std::vector<sample>(last_trajectory.size());\n          std::copy(last_trajectory.begin(), last_trajectory.end(), vtraj->begin());\n        } else if(strategy_w >= 1 && strategy_w <= 5){\n          vtraj = new std::vector<sample>(trajectory.size());\n          std::copy(trajectory.begin(), trajectory.end(), vtraj->begin());\n          \n          if(strategy_w > 1)//on every data\n            importance_sample = new double [trajectory.size()];\n          \n          if(strategy_w == 2) {//on every data 1/p(s)\n            uint i=0;\n            for(auto it = vtraj->begin(); it != vtraj->end() ; ++it) {\n              importance_sample[i] = 1.f / proba_s.pdf(it->s);\n              i++;\n            }\n          } else if(strategy_w == 3) {//on every data 1/p(s) normalized\n            uint i=0;\n            double sum_ps = 0.00f;\n            for(auto it = vtraj->begin(); it != vtraj->end() ; ++it) {\n              sum_ps += 1.f / proba_s.pdf(it->s);\n              i++;\n            }\n            \n            i=0;\n            for(auto it = vtraj->begin(); it != vtraj->end() ; ++it) {\n              importance_sample[i] =  (1.f / proba_s.pdf(it->s)) / sum_ps;\n              i++;\n            }            \n          } else if(strategy_w >= 4 && strategy_w <= 5) {\n            \n            double * ptheta = new double [trajectory.size()];\n            computePTheta(*vtraj, ptheta);\n            \n            if(strategy_w == 4){\n              uint i=0;\n              for(auto it = vtraj->begin(); it != vtraj->end() ; ++it) {\n                importance_sample[i] = ptheta[i];\n                i++;\n              }\n            } else {\n              uint i=0;\n              for(auto it = vtraj->begin(); it != vtraj->end() ; ++it) {\n                importance_sample[i] = ptheta[i] / it->p0;\n                i++;\n              }\n            }\n            \n            delete[] ptheta;\n          \n          } else if(strategy_w != 1) {\n              LOG_ERROR(\"to be implemented\");\n              exit(1);\n          }\n          \n        } else if(strategy_w != 0) {\n          LOG_ERROR(\"to be implemented\");\n          exit(1);\n        }\n\t\n        ParraVtoVNext dq(*vtraj, this);\n\n        auto iter = [&]() {\n          tbb::parallel_for(tbb::blocked_range<size_t>(0, vtraj->size()), dq);\n\n          if(vnn_from_scratch)\n            fann_randomize_weights(vnn->getNeuralNet(), -0.025, 0.025);\n          \n          if(strategy_w <= 1)\n            vnn->learn_stoch(dq.data, 30000, 0, converge_precision);\n          else\n            vnn->learn_stoch_lw(dq.data, importance_sample, 30000, 0, converge_precision);\n        };\n\n        auto eval = [&]() {\n          return fann_get_MSE(vnn->getNeuralNet());\n        };\n\n        if(determinist_vnn_update)\n              bib::Converger::determinist<>(iter, eval, number_fitted_iteration, converge_precision, 0);\n        else {\n          NN best_nn = nullptr;\n          auto save_best = [&]() {\n            if(best_nn != nullptr)\n              fann_destroy(best_nn);\n            best_nn = fann_copy(vnn->getNeuralNet());\n          };\n\n          bib::Converger::min_stochastic<>(iter, eval, save_best, 30, converge_precision, 0, 10);\n          vnn->copy(best_nn);\n          fann_destroy(best_nn);\n        }\n\n        dq.free(); \n        if(strategy_w != 0)\n          delete[] importance_sample;\n        delete vtraj;\n      }\n  }\n\n  inline void mergeSA(std::vector<double>& AB, const std::vector<double>& A, const std::vector<double>& B) {\n    AB.reserve( A.size() + B.size() ); // preallocate memory\n    AB.insert( AB.end(), A.begin(), A.end() );\n    AB.insert( AB.end(), B.begin(), B.end() );\n  }\n  \n  inline void mergeSAS(std::vector<double>& AB, const std::vector<double>& A, const std::vector<double>& B, const std::vector<double>& C) {\n    AB.reserve( A.size() + B.size() + C.size() ); // preallocate memory\n    AB.insert( AB.end(), A.begin(), A.end() );\n    AB.insert( AB.end(), B.begin(), B.end() );\n    AB.insert( AB.end(), C.begin(), C.end() );\n  }\n\n  void end_episode() override {\n    if(learning)\n      update_critic();\n  }\n  \n  void learn_V(std::map<std::vector<double>, double>& bvf) override {\n    if((episode+1) % change_policy_each == 0){\n      trajectory.clear();\n      last_trajectory.clear();\n      \n    \n      struct fann_train_data* data = fann_create_train(bvf.size(), nb_sensors + nb_motors, 1);\n      \n      auto it = bvf.cbegin();\n      for (uint n = 0; n < bvf.size(); n++) {\n        \n        for (uint i = 0; i < nb_sensors + nb_motors ; i++){\n            data->input[n][i] = it->first[i];\n            LOG_FILE_NNL(\"vset.data.\"+std::to_string(current_loaded_policy-1), it->first[i] << \" \");\n        }\n        \n        data->output[n][0] = it->second;\n        LOG_FILE_NNL(\"vset.data.\"+std::to_string(current_loaded_policy-1), it->second << \"\\n\");\n        \n        ++it;\n      }\n      //clear all; close all ;X=load('vset.data.904');[xx,yy] = meshgrid (linspace (-pi,pi,300));griddata(X(:,1),X(:,3),X(:,end),xx,yy);\n      bib::Logger::getInstance()->closeFile(\"vset.data.\"+std::to_string(current_loaded_policy-1));\n      \n      fann_randomize_weights(vnn->getNeuralNet(), -0.025, 0.025);\n      vnn->learn_stoch(data, 10000, 200, 0.0000001, 200);\n      \n      fann_destroy_train(data);\n      \n      vnn->save(\"vset.\"+std::to_string(current_loaded_policy-1));\n      LOG_DEBUG(\"vset.\"+std::to_string(current_loaded_policy-1) << \" saved \" << bvf.size() );\n      bvf.clear();\n    }\n  }\n  \n  void end_instance(bool) override {\n    episode++;\n  }\n  \n  double criticEval(const std::vector<double>& perceptions, const std::vector<double>& actions) override {\n    return vnn->computeOutVF(perceptions, actions);\n  }\n  \n  arch::Policy<MLP>* getCopyCurrentPolicy() override {\n    return new arch::Policy<MLP>(new MLP(*ann) , gaussian_policy ? arch::policy_type::GAUSSIAN : arch::policy_type::GREEDY, noise, decision_each);\n  }\n\n  void save(const std::string& path) override {\n    ann->save(path+\".actor\");\n    vnn->save(path+\".critic\");\n    bib::XMLEngine::save<>(trajectory, \"trajectory\", \"trajectory.data\");\n  }\n\n  void load(const std::string& path) override {\n    ann->load(path+\".actor\");\n    vnn->load(path+\".critic\");\n  }\n\n protected:\n  void _display(std::ostream& out) const override {\n    out << std::setw(12) << std::fixed << std::setprecision(10) << sum_weighted_reward << \" \" << std::setw(\n          8) << std::fixed << std::setprecision(8) << vnn->error() << \" \" << noise << \" \" << trajectory.size() ;\n  }\n\n  void _dump(std::ostream& out) const override {\n    out <<\" \" << std::setw(25) << std::fixed << std::setprecision(22) <<\n        sum_weighted_reward << \" \" << std::setw(8) << std::fixed <<\n        std::setprecision(8) << vnn->error() << \" \" << trajectory.size() ;\n  }\n  \n\n private:\n  uint nb_sensors;\n  \n  uint episode = 0;\n  uint current_loaded_policy = 0;\n  uint change_policy_each;\n  uint strategy_w;\n\n  double noise, converge_precision;\n  bool gaussian_policy, vnn_from_scratch, lecun_activation, \n        determinist_vnn_update;\n  uint hidden_unit_v;\n  uint hidden_unit_a;\n  uint number_fitted_iteration;\n\n  std::shared_ptr<std::vector<double>> last_action;\n  std::shared_ptr<std::vector<double>> last_pure_action;\n  std::vector<double> last_state;\n\n  std::set<sample> trajectory;\n  std::set<sample> last_trajectory;\n//     std::list<sample> trajectory;\n  KDE proba_s;\n  KDE proba_sa, proba_sas;\n  \n  struct L1_distance\n  {\n    typedef double distance_type;\n    \n    double operator() (const double& __a, const double& __b, const size_t) const\n    {\n      double d = fabs(__a - __b);\n      return d;\n    }\n  };\n  typedef KDTree::KDTree<sample, KDTree::_Bracket_accessor<sample>, L1_distance> kdtree_sample;\n  kdtree_sample* kdtree_s;\n\n  MLP* ann;\n  MLP* vnn;\n};\n\n#endif\n\n", "meta": {"hexsha": "a2becc7711b2912198dec1e5f57b8f1c8877afeb", "size": 16446, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "agent/cacla/include/old/OffPolSetACFitted.hpp", "max_stars_repo_name": "matthieu637/ddrl", "max_stars_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T09:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T13:50:23.000Z", "max_issues_repo_path": "agent/cacla/include/old/OffPolSetACFitted.hpp", "max_issues_repo_name": "matthieu637/ddrl", "max_issues_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-10-09T14:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T15:01:00.000Z", "max_forks_repo_path": "agent/cacla/include/old/OffPolSetACFitted.hpp", "max_forks_repo_name": "matthieu637/ddrl", "max_forks_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-16T09:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-15T14:35:40.000Z", "avg_line_length": 32.3104125737, "max_line_length": 146, "alphanum_fraction": 0.5907819531, "num_tokens": 4538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604272, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21547721795959576}}
{"text": "#include <iostream>\n#include <vector>\n#include <cassert>\n#include <cstring>\n#include <limits>\n#include <mpi.h>\n//#include <Eigen/Eigenvalues>\n\nenum KernelType {CubicSpline = 0, WendlandC2 = 1, WendlandC4 = 2};\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\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\ntemplate <class Tsph,\n          class Tbhns>\nvoid calcDiskParameter(char * ofile,\n                       Tsph  & sph,\n                       Tbhns & bhns) {\n\n    for(PS::S64 i = 0; i < sph.getNumberOfParticleLocal(); i++) {\n        sph[i].pos -= bhns[0].pos;\n    }\n    \n    PS::F64 dz      = 1e6;\n    PS::F64 rbinmin = 1e7;\n    PS::F64 rbinmax = 1e10;\n    PS::S64 npd     = 10;\n    PS::F64 drbin   = pow(10., 1 / (PS::F64)npd);\n\n    FILE * fp = fopen(ofile, \"w\");    \n    for(PS::F64 rbin = rbinmin; rbin < rbinmax; rbin *= drbin) {\n        PS::F64 rbin02 = rbin * rbin;\n        PS::F64 rbin12 = (rbin * drbin) * (rbin * drbin);\n        PS::F64 mdisk  = 0.;\n        PS::F64 mcol   = 0.;\n        PS::F64 udisk  = 0.;\n        PS::S64 ncol   = 0;\n        PS::S64 ndisk  = 0;\n        for(PS::S64 i  = 0; i < sph.getNumberOfParticleLocal(); i++) {\n            PS::F64 r2 = sph[i].pos[0] * sph[i].pos[0] + sph[i].pos[1] * sph[i].pos[1];\n            if(r2 < rbin02 || rbin12 <= r2) {\n                continue;\n            }\n            mcol  += sph[i].mass;\n            ncol  += 1;\n            if(fabs(sph[i].pos[2]) > dz) {\n                continue;\n            }\n            mdisk += sph[i].mass;\n            udisk += sph[i].mass * sph[i].uene;\n            ndisk += 1;\n        }\n        PS::F64 surface = M_PI * (rbin12 - rbin02);\n        PS::F64 volume  = surface * (2. * dz);\n        PS::F64 sigma   = mcol / surface;\n        PS::F64 dens    = mdisk / volume;\n        PS::F64 uene    = udisk / mdisk;\n        PS::F64 tout    = 0.;\n        if(dens != 0.) {\n            NR::Nucleon cmps;\n            cmps[1] = cmps[2] = 0.5;\n            PS::F64 temp = 1e9;\n            PS::F64 pout, cout, sout;\n            flash_helmholtz_(&dens, &uene, &temp, cmps.getPointer(),\n                             &pout, &cout, &tout, &sout);\n        }\n        fprintf(fp, \"%+e %+e %+e %+e %6d %6d\\n\", rbin, sigma, dens, tout, ncol, ndisk);\n    }\n    fclose(fp);\n\n}\n\nint main(int argc, char ** argv) {\n    MPI_Init(&argc, &argv);\n\n    init_flash_helmholtz_(&CodeUnit::FractionOfCoulombCorrection);\n\n    PS::ParticleSystem<SPHAnalysis> sph;\n    sph.initialize();\n    sph.createParticle(0);\n    sph.setNumberOfParticleLocal(0);\n    PS::ParticleSystem<BlackHoleNeutronStarAnalysis> bhns;\n    bhns.initialize();\n    bhns.createParticle(0);\n    bhns.setNumberOfParticleLocal(0);\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    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        char ofile[1024];\n        sprintf(ofile, \"%s_t%04d.dat\", otype, itime);\n        printf(\"Output: %s\\n\", ofile);\n        calcDiskParameter(ofile, sph, bhns);\n\n    }\n\n    MPI_Finalize();\n\n    return 0;\n}\n", "meta": {"hexsha": "9925b0c056c2c7de0a894baf6510d77054069aea", "size": 7656, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tool.nswd/calc_disk/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_disk/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_disk/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": 33.0, "max_line_length": 89, "alphanum_fraction": 0.4772727273, "num_tokens": 2635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.21536554748988407}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_R1CS_GG_PPZKSNARK_IPP2_VERIFY_HPP\n#define CRYPTO3_R1CS_GG_PPZKSNARK_IPP2_VERIFY_HPP\n\n#include <memory>\n#include <vector>\n#include <tuple>\n\n#include <boost/iterator/zip_iterator.hpp>\n\n#include <nil/crypto3/detail/pack_numeric.hpp>\n\n#include <nil/crypto3/hash/algorithm/hash.hpp>\n#include <nil/crypto3/hash/sha2.hpp>\n\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/verification_key.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/proof.hpp>\n#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/srs.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace zk {\n            namespace snark {\n                template<typename CurveType>\n                struct Op {\n                    typedef CurveType curve_type;\n\n                    typedef typename curve_type::pairing::fqk_type::value_type TAB;\n                    typedef typename curve_type::pairing::fqk_type::value_type UAB;\n                    typedef typename curve_type::pairing::fqk_type::value_type ZAB;\n                    typedef typename curve_type::pairing::fqk_type::value_type TC;\n                    typedef typename curve_type::pairing::fqk_type::value_type UC;\n                    typedef typename curve_type::pairing::g1_type::value_type ZC;\n                };\n\n                /// Keeps track of the variables that have been sent by the prover and must\n                /// be multiplied together by the verifier. Both MIPP and TIPP are merged\n                /// together.\n                template<typename CurveType>\n                struct gipa_tuz {\n                    typedef CurveType curve_type;\n                    typedef typename curve_type::scalar_field_type::value_type fr_type;\n\n                    std::pair<typename curve_type::pairing::fqk_type::value_type, fr_type::value_type> tab;\n                    std::pair<typename curve_type::pairing::fqk_type::value_type, fr_type::value_type> uab;\n                    std::pair<typename curve_type::pairing::fqk_type::value_type, fr_type::value_type> zab;\n                    std::pair<typename curve_type::pairing::fqk_type::value_type, fr_type::value_type> tc;\n                    std::pair<typename curve_type::pairing::fqk_type::value_type, fr_type::value_type> uc;\n                    std::pair<typename curve_type::pairing::g1_type, fr_type> zc;\n                };\n\n                /// gipa_verify_tipp_mipp recurse on the proof and statement and produces the final\n                /// values to be checked by TIPP and MIPP verifier, namely, for TIPP for example:\n                /// * T,U: the final commitment values of A and B\n                /// * Z the final product between A and B.\n                /// * Challenges are returned in inverse order as well to avoid\n                /// repeating the operation multiple times later on.\n                /// * There are T,U,Z vectors as well for the MIPP relationship. Both TIPP and\n                /// MIPP share the same challenges however, enabling to re-use common operations\n                /// between them, such as the KZG proof for commitment keys.\n                template<typename CurveType, typename Hash = hashes::sha2<256>>\n                std::tuple<gipa_tuz<CurveType>, std::vector<typename CurveType::scalar_field_type::value_type>,\n                           std::vector<typename CurveType::scalar_field_type::value_type>>\n                    gipa_verify_tipp_mipp(const r1cs_gg_ppzksnark_aggregate_proof<CurveType> &proof) {\n                    std::vector<typename CurveType::scalar_field_type::value_type> challenges, challenges_inv;\n\n                    typename CurveType::scalar_field_type::value_type default_transcript =\n                        typename CurveType::scalar_field_type::value_type::zero();\n\n                    // We first generate all challenges as this is the only consecutive process\n                    // that can not be parallelized then we scale the commitments in a\n                    // parallelized way\n                    std::for_each(\n                        boost::make_zip_iterator(\n                            std::make_tuple(proof.tmipp.gipa.comms_ab.begin(), proof.tmipp.gipa.z_ab.begin(),\n                                            proof.tmipp.gipa.comms_c.begin(), proof.tmipp.gipa.z_c.begin())),\n                        boost::make_zip_iterator(\n                            std::make_tuple(proof.tmipp.gipa.comms_ab.end(), proof.tmipp.gipa.z_ab.end(),\n                                            proof.tmipp.gipa.comms_c.end(), proof.tmipp.gipa.z_c.end())),\n                        [&](const std::tuple<const std::pair<r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType>,\n                                                             r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType>> &,\n                                             const std::pair<typename CurveType::pairing::fqk_type::value_type,\n                                                             typename CurveType::pairing::fqk_type::value_type> &,\n                                             const std::pair<r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType>,\n                                                             r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType>> &,\n                                             const std::pair<typename CurveType::g1_type::value_type,\n                                                             typename CurveType::g1_type::value_type> &> &t) {\n                            auto tab_l = std::get<0>(std::get<0>(t));\n                            auto tab_r = std::get<1>(std::get<0>(t));\n\n                            auto zab_l = std::get<0>(std::get<1>(t));\n                            auto zab_r = std::get<1>(std::get<1>(t));\n\n                            auto tc_l = std::get<0>(std::get<2>(t));\n                            auto tc_r = std::get<1>(std::get<2>(t));\n\n                            auto zc_l = std::get<0>(std::get<3>(t));\n                            auto zc_r = std::get<1>(std::get<3>(t));\n\n                            // Fiat-Shamir challenge\n                            auto transcript = challenges.empty() ? *(challenges.end() - 1) : default_transcript;\n\n                            std::size_t counter_nonce = 1;\n                            std::array<std::uint8_t, sizeof(std::size_t)> counter_nonce_bytes;\n                            crypto3::detail::pack<stream_endian::big_byte_big_bit>({counter_nonce},\n                                                                                   counter_nonce_bytes);\n                            accumulator_set<Hash> acc;\n\n                            hash<Hash>(counter_nonce_bytes, acc);\n                            hash<Hash>(transcript, acc);\n                            hash<Hash>(std::get<0>(tab_l), acc);\n                            hash<Hash>(std::get<1>(tab_l), acc);\n                            hash<Hash>(std::get<0>(tab_r), acc);\n                            hash<Hash>(std::get<1>(tab_r), acc);\n                            hash<Hash>(zab_l, acc);\n                            hash<Hash>(zab_r, acc);\n                            hash<Hash>(zc_l, acc);\n                            hash<Hash>(zc_r, acc);\n                            hash<Hash>(std::get<0>(tc_l), acc);\n                            hash<Hash>(std::get<1>(tc_l), acc);\n                            hash<Hash>(std::get<0>(tc_r), acc);\n                            hash<Hash>(std::get<1>(tc_r), acc);\n\n                            typename Hash::digest_type d = accumulators::extract::hash<Hash>(acc);\n                            typename CurveType::scalar_field_type::value_type c;\n                            multiprecision::import_bits(c.data, d);\n\n                            challenges.emplace_back(c);\n                            challenges_inv.emplace_back(c.inversed());\n                        });\n\n                    gipa_tuz<CurveType> final_res = {std::get<0>(proof.com_ab), std::get<1>(proof.com_ab), proof.ip_ab,\n                                                     std::get<0>(proof.com_c),  std::get<1>(proof.com_c),  proof.agg_c};\n\n                    // we first multiply each entry of the Z U and L vectors by the respective\n                    // challenges independently\n                    // Since at the end we want to multiple all \"t\" values together, we do\n                    // multiply all of them in parrallel and then merge then back at the end.\n                    // same for u and z.\n                    std::for_each(\n                        boost::make_zip_iterator(\n                            std::make_tuple(proof.tmipp.gipa.comms_ab.begin(), proof.tmipp.gipa.z_ab.begin(),\n                                            proof.tmipp.gipa.comms_c.begin(), proof.tmipp.gipa.z_c.begin(),\n                                            challenges.begin(), challenges_inv.begin())),\n                        boost::make_zip_iterator(\n                            std::make_tuple(proof.tmipp.gipa.comms_ab.end(), proof.tmipp.gipa.z_ab.end(),\n                                            proof.tmipp.gipa.comms_c.end(), proof.tmipp.gipa.z_c.end(),\n                                            challenges.end(), challenges_inv.end())),\n                        [&](const std::tuple<const std::pair<r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType>,\n                                                             r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType>> &,\n                                             const std::pair<typename CurveType::pairing::fqk_type::value_type,\n                                                             typename CurveType::pairing::fqk_type::value_type> &,\n                                             const std::pair<r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType>,\n                                                             r1cs_gg_ppzksnark_ipp2_commitment_output<CurveType>> &,\n                                             const std::pair<typename CurveType::g1_type::value_type,\n                                                             typename CurveType::g1_type::value_type> &,\n                                             const typename CurveType::scalar_field_type::value_type &,\n                                             const typename CurveType::scalar_field_type::value_type &> &t) {\n                            // T and U values for right and left for AB part\n                            auto tab_l = std::get<0>(std::get<0>(std::get<0>(t)));\n                            auto uab_l = std::get<1>(std::get<0>(std::get<0>(t)));\n                            auto tab_r = std::get<0>(std::get<1>(std::get<0>(t)));\n                            auto uab_r = std::get<1>(std::get<1>(std::get<0>(t)));\n\n                            auto zab_l = std::get<0>(std::get<1>(t));\n                            auto zab_r = std::get<1>(std::get<1>(t));\n\n                            // T and U values for right and left for C part\n                            auto tc_l = std::get<0>(std::get<0>(std::get<2>(t)));\n                            auto uc_l = std::get<1>(std::get<0>(std::get<2>(t)));\n                            auto tc_r = std::get<0>(std::get<1>(std::get<2>(t)));\n                            auto uc_r = std::get<1>(std::get<1>(std::get<2>(t)));\n\n                            auto zc_l = std::get<0>(std::get<3>(t));\n                            auto zc_r = std::get<1>(std::get<3>(t));\n\n                            // we multiple left side by x and right side by x^-1\n                            vec ![\n                                Op<CurveType>::TAB(tab_l, std::get<4>(t)),\n                                Op<CurveType>::tab(tab_r, c_inv_repr),\n                                Op::UAB(uab_l, c_repr),\n                                Op::UAB(uab_r, c_inv_repr),\n                                Op::ZAB(zab_l, c_repr),\n                                Op::ZAB(zab_r, c_inv_repr),\n                                Op::TC::<E>(tc_l, c_repr),\n                                Op::TC(tc_r, c_inv_repr),\n                                Op::UC(uc_l, c_repr),\n                                Op::UC(uc_r, c_inv_repr),\n                                Op::ZC(zc_l, c_repr),\n                                Op::ZC(zc_r, c_inv_repr),\n                            ]\n                        });\n                }\n\n                /// verify_tipp_mipp returns a pairing equation to check the tipp proof.  $r$ is\n                /// the randomness used to produce a random linear combination of A and B and\n                /// used in the MIPP part with C\n                template<typename CurveType>\n                PairingCheck<CurveType> verify_tipp_mipp(const r1cs_gg_ppzksnark_verifying_srs<CurveType> &v_srs,\n                                                         const r1cs_gg_ppzksnark_aggregate_proof<CurveType> &proof,\n                                                         const typename CurveType::scalar_field_type::value_type &r_shift) {\n                    // (T,U), Z for TIPP and MIPP  and all challenges\n                    std::tuple<gipa_tuz<CurveType>, std::vector<typename CurveType::scalar_field_type::value_type>,\n                               std::vector<typename CurveType::scalar_field_type::value_type>>\n                        gtmp = gipa_verify_tipp_mipp(proof);\n                    auto &final_res = std::get<0>(gtmp);\n                    auto &challenges = std::get<1>(gtmp);\n                    auto &challenges_inv = std::get<2>(gtmp);\n\n                    // we reverse the order so the KZG polynomial have them in the expected\n                    // order to construct them in logn time.\n                    std::reverse(challenges.begin(), challenges.end());\n                    std::reverse(challenges_inv.begin(), challenges_inv.end());\n\n                    // Verify commitment keys wellformed\n                    auto fvkey = proof.tmipp.gipa.final_vkey;\n                    auto fwkey = proof.tmipp.gipa.final_wkey;\n                }\n\n                template<typename CurveType, typename InputPublicInputsIterator>\n                bool verify_aggregate_proof(const r1cs_gg_ppzksnark_verifying_srs<CurveType> &ip_verifier_srs,\n                                            const r1cs_gg_ppzksnark_processed_verification_key<CurveType> &pvk,\n                                            InputPublicInputsIterator public_inputs_first,\n                                            InputPublicInputsIterator public_inputs_last,\n                                            const r1cs_gg_ppzksnark_aggregate_proof<CurveType> &proof) {\n\n                    // Random linear combination of proofs\n                    std::size_t counter_nonce = 1;\n                    std::array<std::uint8_t, sizeof(std::size_t)> counter_nonce_bytes;\n                    crypto3::detail::pack<stream_endian::big_byte_big_bit>({counter_nonce}, counter_nonce_bytes);\n                    accumulator_set<hashes::sha2<256>> acc;\n\n                    hash<hashes::sha2<256>>(counter_nonce_bytes, acc);\n                    hash<hashes::sha2<256>>(std::get<0>(proof.com_ab), acc);\n                    hash<hashes::sha2<256>>(std::get<1>(proof.com_ab), acc);\n                    hash<hashes::sha2<256>>(std::get<0>(proof.com_c), acc);\n                    hash<hashes::sha2<256>>(std::get<1>(proof.com_c), acc);\n\n                    typename hashes::sha2<256>::digest_type d = accumulators::extract::hash<hashes::sha2<256>>(acc);\n                    typename CurveType::scalar_field_type::value_type r;\n                    crypto3::detail::pack(d, r.data);\n                    r = r.inversed();\n\n                    InputPublicInputsIterator vpitr = public_inputs_first;\n\n                    while (vpitr != public_inputs_last) {\n                        BOOST_ASSERT_MSG(vpitr->size() + 1 == pvk.ic.size(), \"malformed verification key!\");\n                        ++vpitr;\n                    }\n\n                    // 1.Check TIPA proof ab\n                    // 2.Check TIPA proof c\n                    auto tipa_ab =\n                        verify_tipp_mipp<CurveType>(ip_verifier_srs,\n                                                    proof,\n                                                    r    // we give the extra r as it's not part of the proof itself\n                                                         // - it is simply used on top for the groth16 aggregation\n                        );\n                }\n\n                /// verify_kzg_opening_g2 takes a KZG opening, the final commitment key, SRS and\n                /// any shift (in TIPP we shift the v commitment by r^-1) and returns a pairing\n                /// tuple to check if the opening is correct or not.\n                template<typename CurveType, typename InputScalarIterator>\n                PairingCheck<CurveType> verify_kzg_opening_g2(\n                    const r1cs_gg_ppzksnark_verifying_srs<CurveType> &v_srs,\n                    const r1cs_gg_ppzksnark_ipp2_vkey<CurveType> &final_vkey,\n                    const kzg_opening<typename CurveType::g2_type> &vkey_opening,\n                    InputScalarIterator challenges_first,\n                    InputScalarIterator challenges_last,\n                    const typename std::iterator_traits<InputScalarIterator>::value_type &r_shift,\n                    const typename std::iterator_traits<InputScalarIterator>::value_type &kzg_challenge) {\n                }\n\n                /// Similar to verify_kzg_opening_g2 but for g1.\n                template<typename CurveType, typename InputScalarIterator>\n                PairingCheck<CurveType> verify_kzg_opening_g1(\n                    const r1cs_gg_ppzksnark_verifier_srs<CurveType> &v_srs,\n                    const r1cs_gg_ppzksnark_ipp2_wkey<CurveType> &final_wkey,\n                    const kzg_opening<typename CurveType::g1_type> &wkey_opening, InputScalarIterator challenges_first,\n                    InputScalarIterator challenges_last, ,\n                    const typename std::iterator_traits<InputScalarIterator>::value_type &r_shift,\n                    const typename std::iterator_traits<InputScalarIterator>::value_type &kzg_challenge) {\n                }\n            }    // namespace snark\n        }        // namespace zk\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_R1CS_GG_PPZKSNARK_TYPES_POLICY_HPP\n", "meta": {"hexsha": "5e366833b8dc9fe51eece37c28d6e732d7035367", "size": 19781, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/verify.hpp", "max_stars_repo_name": "NoamDev/crypto3-zk", "max_stars_repo_head_hexsha": "5f03e49b737994a3cecf673b029a4e32a2a8aaa5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/verify.hpp", "max_issues_repo_name": "NoamDev/crypto3-zk", "max_issues_repo_head_hexsha": "5f03e49b737994a3cecf673b029a4e32a2a8aaa5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark/ipp2/verify.hpp", "max_forks_repo_name": "NoamDev/crypto3-zk", "max_forks_repo_head_hexsha": "5f03e49b737994a3cecf673b029a4e32a2a8aaa5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 62.7968253968, "max_line_length": 124, "alphanum_fraction": 0.5182751125, "num_tokens": 4153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.2152131568722564}}
{"text": "///////////////////////////////////////////////////////////////////////////////\r\n// Copyright Christopher Kormanyos 2014.\r\n// Copyright John Maddock 2014.\r\n// Copyright Paul Bristow 2014.\r\n// Distributed under the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n\r\n// Implement a specialization of std::complex<> for *anything* that\r\n// is defined as BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE.\r\n\r\n#ifndef _BOOST_CSTDFLOAT_COMPLEX_STD_2014_02_15_HPP_\r\n  #define _BOOST_CSTDFLOAT_COMPLEX_STD_2014_02_15_HPP_\r\n\r\n  #if defined(__GNUC__)\r\n  #pragma GCC system_header\r\n  #endif\r\n\r\n  #include <complex>\r\n  #include <boost/math/constants/constants.hpp>\r\n\r\n  namespace std\r\n  {\r\n    // Forward declarations.\r\n    template<class float_type>\r\n    class complex;\r\n\r\n    template<>\r\n    class complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>;\r\n\r\n    inline BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE real(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE imag(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    inline BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE abs (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE arg (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE norm(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> conj (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> proj (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> polar(const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE&,\r\n                                                                      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& = 0);\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> sqrt (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> sin  (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> cos  (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> tan  (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> asin (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> acos (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> atan (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> exp  (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> log  (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> log10(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> pow  (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&,\r\n                                                                      int);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> pow  (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&,\r\n                                                                      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> pow  (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&,\r\n                                                                      const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> pow  (const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE&,\r\n                                                                      const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> sinh (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> cosh (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> tanh (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> asinh(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> acosh(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> atanh(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    template<class char_type, class traits_type>\r\n    inline std::basic_ostream<char_type, traits_type>& operator<<(std::basic_ostream<char_type, traits_type>&, const std::complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    template<class char_type, class traits_type>\r\n    inline std::basic_istream<char_type, traits_type>& operator>>(std::basic_istream<char_type, traits_type>&, std::complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>&);\r\n\r\n    // Template specialization of the complex class.\r\n    template<>\r\n    class complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>\r\n    {\r\n    public:\r\n      typedef BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE value_type;\r\n\r\n      explicit complex(const complex<float>&);\r\n      explicit complex(const complex<double>&);\r\n      explicit complex(const complex<long double>&);\r\n\r\n      #if defined(BOOST_NO_CXX11_CONSTEXPR)\r\n      complex(const value_type& r = value_type(),\r\n              const value_type& i = value_type()) : re(r),\r\n                                                    im(i) { }\r\n\r\n      template<typename X>\r\n      complex(const complex<X>& x) : re(x.real()),\r\n                                     im(x.imag()) { }\r\n\r\n      const value_type& real() const { return re; }\r\n      const value_type& imag() const { return im; }\r\n\r\n      value_type& real() { return re; }\r\n      value_type& imag() { return im; }\r\n      #else\r\n      BOOST_CONSTEXPR complex(const value_type& r = value_type(),\r\n                              const value_type& i = value_type()) : re(r),\r\n                                                                    im(i) { }\r\n\r\n      template<typename X>\r\n      BOOST_CONSTEXPR complex(const complex<X>& x) : re(x.real()),\r\n                                                     im(x.imag()) { }\r\n\r\n      value_type real() const { return re; }\r\n      value_type imag() const { return im; }\r\n      #endif\r\n\r\n      void real(value_type r) { re = r; }\r\n      void imag(value_type i) { im = i; }\r\n\r\n      complex<value_type>& operator=(const value_type& v)\r\n      {\r\n        re = v;\r\n        im = value_type(0);\r\n        return *this;\r\n      }\r\n\r\n      complex<value_type>& operator+=(const value_type& v)\r\n      {\r\n        re += v;\r\n        return *this;\r\n      }\r\n\r\n      complex<value_type>& operator-=(const value_type& v)\r\n      {\r\n        re -= v;\r\n        return *this;\r\n      }\r\n\r\n      complex<value_type>& operator*=(const value_type& v)\r\n      {\r\n        re *= v;\r\n        im *= v;\r\n        return *this;\r\n      }\r\n\r\n      complex<value_type>& operator/=(const value_type& v)\r\n      {\r\n        re /= v;\r\n        im /= v;\r\n        return *this;\r\n      }\r\n\r\n      template<typename X>\r\n      complex<value_type>& operator=(const complex<X>& x)\r\n      {\r\n        re = x.real();\r\n        im = x.imag();\r\n        return *this;\r\n      }\r\n\r\n      template<typename X>\r\n      complex<value_type>& operator+=(const complex<X>& x)\r\n      {\r\n        re += x.real();\r\n        im += x.imag();\r\n        return *this;\r\n      }\r\n\r\n      template<typename X>\r\n      complex<value_type>& operator-=(const complex<X>& x)\r\n      {\r\n        re -= x.real();\r\n        im -= x.imag();\r\n        return *this;\r\n      }\r\n\r\n      template<typename X>\r\n      complex<value_type>& operator*=(const complex<X>& x)\r\n      {\r\n        const value_type tmp_real = (re * x.real()) - (im * x.imag());\r\n        im = (re * x.imag()) + (im * x.real());\r\n        re = tmp_real;\r\n        return *this;\r\n      }\r\n\r\n      template<typename X>\r\n      complex<value_type>& operator/=(const complex<X>& x)\r\n      {\r\n        const value_type tmp_real = (re * x.real()) + (im * x.imag());\r\n        const value_type the_norm = std::norm(x);\r\n        im = ((im * x.real()) - (re * x.imag())) / the_norm;\r\n        re = tmp_real / the_norm;\r\n        return *this;\r\n      }\r\n\r\n      private:\r\n        value_type re;\r\n        value_type im;\r\n    };\r\n\r\n    // Constructors from built-in complex representation of floating-point types.\r\n    complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::complex(const complex<float>& f)        : re(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE( f.real())), im(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE( f.imag())) { }\r\n    complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::complex(const complex<double>& d)       : re(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE( d.real())), im(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE( d.imag())) { }\r\n    complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::complex(const complex<long double>& ld) : re(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(ld.real())), im(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(ld.imag())) { }\r\n  } // namespace std\r\n\r\n  namespace boost { namespace math { namespace cstdfloat { namespace detail {\r\n  template<class float_type> std::complex<float_type> multiply_by_i(const std::complex<float_type>& x)\r\n  {\r\n    // Multiply x (in C) by I (the imaginary component), and return the result.\r\n    return std::complex<float_type>(-x.imag(), x.real());\r\n  }\r\n  } } } } // boost::math::cstdfloat::detail\r\n\r\n  namespace std\r\n  {\r\n    // ISO/IEC 14882:2011, Section 26.4.7, specific values.\r\n    inline BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE real(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x) { return x.real(); }\r\n    inline BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE imag(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x) { return x.imag(); }\r\n\r\n    inline BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE abs (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x) { using std::sqrt;  return sqrt ((real(x) * real(x)) + (imag(x) * imag(x))); }\r\n    inline BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE arg (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x) { using std::atan2; return atan2(x.imag(), x.real()); }\r\n    inline BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE norm(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x) { return (real(x) * real(x)) + (imag(x) * imag(x)); }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> conj (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(x.real(), -x.imag()); }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> proj (const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE m = (std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::max)();\r\n      if ((x.real() > m)\r\n        || (x.real() < -m)\r\n        || (x.imag() > m)\r\n        || (x.imag() < -m))\r\n      {\r\n        // We have an infinity, return a normalized infinity, respecting the sign of the imaginary part:\r\n         return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::infinity(), x.imag() < 0 ? -0 : 0);\r\n      }\r\n      return x;\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> polar(const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& rho,\r\n                                                                      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& theta)\r\n    {\r\n      using std::sin;\r\n      using std::cos;\r\n\r\n      return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(rho * cos(theta), rho * sin(theta));\r\n    }\r\n\r\n    // Global add, sub, mul, div.\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator+(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& u, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& v) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(u.real() + v.real(), u.imag() + v.imag()); }\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator-(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& u, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& v) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(u.real() - v.real(), u.imag() - v.imag()); }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator*(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& u, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& v)\r\n    {\r\n      return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>((u.real() * v.real()) - (u.imag() * v.imag()),\r\n                                                                  (u.real() * v.imag()) + (u.imag() * v.real()));\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator/(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& u, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& v)\r\n    {\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE the_norm = std::norm(v);\r\n\r\n      return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(((u.real() * v.real()) + (u.imag() * v.imag())) / the_norm,\r\n                                                                  ((u.imag() * v.real()) - (u.real() * v.imag())) / the_norm);\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator+(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& u, const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& v) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(u.real() + v, u.imag()); }\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator-(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& u, const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& v) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(u.real() - v, u.imag()); }\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator*(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& u, const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& v) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(u.real() * v, u.imag() * v); }\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator/(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& u, const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& v) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(u.real() / v, u.imag() / v); }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator+(const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& u, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& v) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(u + v.real(),     v.imag()); }\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator-(const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& u, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& v) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(u - v.real(),    -v.imag()); }\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator*(const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& u, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& v) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(u * v.real(), u * v.imag()); }\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator/(const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& u, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& v) { const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE v_norm = norm(v); return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>((u * v.real()) / v_norm, (-u * v.imag()) / v_norm); }\r\n\r\n    // Unary plus / minus.\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator+(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& u) { return u; }\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> operator-(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& u) { return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(-u.real(), -u.imag()); }\r\n\r\n    // Equality and inequality.\r\n    inline bool operator==(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& y) { return ((x.real() == y.real()) && (x.imag() == y.imag())); }\r\n    inline bool operator==(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x, const         BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE&  y) { return ((x.real() == y)        && (x.imag() == BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(0))); }\r\n    inline bool operator==(const         BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE&  x, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& y) { return ((x        == y.real()) && (y.imag() == BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(0))); }\r\n    inline bool operator!=(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& y) { return ((x.real() != y.real()) || (x.imag() != y.imag())); }\r\n    inline bool operator!=(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x, const         BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE&  y) { return ((x.real() != y)        || (x.imag() != BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(0))); }\r\n    inline bool operator!=(const         BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE&  x, const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& y) { return ((x        != y.real()) || (y.imag() != BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(0))); }\r\n\r\n    // ISO/IEC 14882:2011, Section 26.4.8, transcendentals.\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> sqrt(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      using std::fabs;\r\n      using std::sqrt;\r\n\r\n      // Compute sqrt(x) for x in C:\r\n      // sqrt(x) = (s       , xi / 2s) : for xr > 0,\r\n      //           (|xi| / 2s, +-s)    : for xr < 0,\r\n      //           (sqrt(xi), sqrt(xi) : for xr = 0,\r\n      // where s = sqrt{ [ |xr| + sqrt(xr^2 + xi^2) ] / 2 },\r\n      // and the +- sign is the same as the sign of xi.\r\n\r\n      if(x.real() > 0)\r\n      {\r\n        const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE s = sqrt((fabs(x.real()) + std::abs(x)) / 2);\r\n\r\n        return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(s, x.imag() / (s * 2));\r\n      }\r\n      else if(x.real() < 0)\r\n      {\r\n        const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE s = sqrt((fabs(x.real()) + std::abs(x)) / 2);\r\n\r\n        const bool imag_is_neg = (x.imag() < 0);\r\n\r\n        return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(fabs(x.imag()) / (s * 2), (imag_is_neg ? -s : s));\r\n      }\r\n      else\r\n      {\r\n        const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sqrt_xi_half = sqrt(x.imag() / 2);\r\n\r\n        return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(sqrt_xi_half, sqrt_xi_half);\r\n      }\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> sin(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      using std::sin;\r\n      using std::cos;\r\n      using std::exp;\r\n\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sin_x  = sin (x.real());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE cos_x  = cos (x.real());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE exp_yp = exp (x.imag());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE exp_ym = BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) / exp_yp;\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sinh_y = (exp_yp - exp_ym) / 2;\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE cosh_y = (exp_yp + exp_ym) / 2;\r\n\r\n      return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(sin_x * cosh_y, cos_x * sinh_y);\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> cos(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      using std::sin;\r\n      using std::cos;\r\n      using std::exp;\r\n\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sin_x  = sin (x.real());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE cos_x  = cos (x.real());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE exp_yp = exp (x.imag());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE exp_ym = BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) / exp_yp;\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sinh_y = (exp_yp - exp_ym) / 2;\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE cosh_y = (exp_yp + exp_ym) / 2;\r\n\r\n      return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(cos_x * cosh_y, -(sin_x * sinh_y));\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> tan(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      using std::sin;\r\n      using std::cos;\r\n      using std::exp;\r\n\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sin_x  = sin (x.real());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE cos_x  = cos (x.real());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE exp_yp = exp (x.imag());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE exp_ym = BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) / exp_yp;\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sinh_y = (exp_yp - exp_ym) / 2;\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE cosh_y = (exp_yp + exp_ym) / 2;\r\n\r\n      return (  complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(sin_x * cosh_y,  cos_x * sinh_y)\r\n              / complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(cos_x * cosh_y, -sin_x * sinh_y));\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> asin(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      return -boost::math::cstdfloat::detail::multiply_by_i(std::log(boost::math::cstdfloat::detail::multiply_by_i(x) + std::sqrt(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) - (x * x))));\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> acos(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      return boost::math::constants::half_pi<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>() - std::asin(x);\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> atan(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> izz = boost::math::cstdfloat::detail::multiply_by_i(x);\r\n\r\n      return boost::math::cstdfloat::detail::multiply_by_i(std::log(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) - izz) - std::log(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) + izz)) / 2;\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> exp(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      using std::exp;\r\n\r\n      return std::polar(exp(x.real()), x.imag());\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> log(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      using std::atan2;\r\n      using std::log;\r\n\r\n      return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(log(std::norm(x)) / 2, atan2(x.imag(), x.real()));\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> log10(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      return std::log(x) / boost::math::constants::ln_ten<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>();\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> pow(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x,\r\n                                                                    int p)\r\n    {\r\n      const bool re_isneg  = (x.real() < 0);\r\n      const bool re_isnan  = (x.real() != x.real());\r\n      const bool re_isinf  = ((!re_isneg) ? bool(+x.real() > (std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::max)())\r\n                                          : bool(-x.real() > (std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::max)()));\r\n\r\n      const bool im_isneg  = (x.imag() < 0);\r\n      const bool im_isnan  = (x.imag() != x.imag());\r\n      const bool im_isinf  = ((!im_isneg) ? bool(+x.imag() > (std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::max)())\r\n                                          : bool(-x.imag() > (std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::max)()));\r\n\r\n      if(re_isnan || im_isnan) { return x; }\r\n\r\n      if(re_isinf || im_isinf)\r\n      {\r\n        return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::quiet_NaN(),\r\n                                                                    std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::quiet_NaN());\r\n      }\r\n\r\n      if(p < 0)\r\n      {\r\n        if(std::abs(x) < (std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::min)())\r\n        {\r\n          return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::infinity(),\r\n                                                                      std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::infinity());\r\n        }\r\n        else\r\n        {\r\n          return BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) / std::pow(x, -p);\r\n        }\r\n      }\r\n\r\n      if(p == 0)\r\n      {\r\n        return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1));\r\n      }\r\n      else\r\n      {\r\n        if(p == 1) { return x; }\r\n\r\n        if(std::abs(x) > (std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::max)())\r\n        {\r\n          const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE re = (re_isneg ? -std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::infinity()\r\n                                                                           : +std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::infinity());\r\n\r\n          const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE im = (im_isneg ? -std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::infinity()\r\n                                                                           : +std::numeric_limits<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>::infinity());\r\n\r\n          return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(re, im);\r\n        }\r\n\r\n        if     (p == 2) { return  (x * x); }\r\n        else if(p == 3) { return ((x * x) * x); }\r\n        else if(p == 4) { const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> x2 = (x * x); return (x2 * x2); }\r\n        else\r\n        {\r\n          // The variable xn stores the binary powers of x.\r\n          complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> result(((p % 2) != 0) ? x : complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1)));\r\n          complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> xn    (x);\r\n\r\n          int p2 = p;\r\n\r\n          while((p2 /= 2) != 0)\r\n          {\r\n            // Square xn for each binary power.\r\n            xn *= xn;\r\n\r\n            const bool has_binary_power = ((p2 % 2) != 0);\r\n\r\n            if(has_binary_power)\r\n            {\r\n              // Multiply the result with each binary power contained in the exponent.\r\n              result *= xn;\r\n            }\r\n          }\r\n\r\n          return result;\r\n        }\r\n      }\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> pow(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x,\r\n                                                                    const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& a)\r\n    {\r\n      return std::exp(a * std::log(x));\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> pow(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x,\r\n                                                                    const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& a)\r\n    {\r\n      return std::exp(a * std::log(x));\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> pow(const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE& x,\r\n                                                                    const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& a)\r\n    {\r\n      return std::exp(a * std::log(x));\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> sinh(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      using std::sin;\r\n      using std::cos;\r\n      using std::exp;\r\n\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sin_y  = sin (x.imag());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE cos_y  = cos (x.imag());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE exp_xp = exp (x.real());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE exp_xm = BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) / exp_xp;\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sinh_x = (exp_xp - exp_xm) / 2;\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE cosh_x = (exp_xp + exp_xm) / 2;\r\n\r\n      return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(cos_y * sinh_x, cosh_x * sin_y);\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> cosh(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      using std::sin;\r\n      using std::cos;\r\n      using std::exp;\r\n\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sin_y  = sin (x.imag());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE cos_y  = cos (x.imag());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE exp_xp = exp (x.real());\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE exp_xm = BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) / exp_xp;\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE sinh_x = (exp_xp - exp_xm) / 2;\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE cosh_x = (exp_xp + exp_xm) / 2;\r\n\r\n      return complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(cos_y * cosh_x, sin_y * sinh_x);\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> tanh(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> ex_plus  = std::exp(x);\r\n      const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> ex_minus = BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) / ex_plus;\r\n\r\n      return (ex_plus - ex_minus) / (ex_plus + ex_minus);\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> asinh(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      return std::log(x + std::sqrt((x * x) + BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1)));\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> acosh(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      const BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE my_one(1);\r\n\r\n      const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> zp(x.real() + my_one, x.imag());\r\n      const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> zm(x.real() - my_one, x.imag());\r\n\r\n      return std::log(x + (zp * std::sqrt(zm / zp)));\r\n    }\r\n\r\n    inline complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE> atanh(const complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      return (std::log(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) + x) - std::log(BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE(1) - x)) / 2.0;\r\n    }\r\n\r\n    template<class char_type, class traits_type>\r\n    inline std::basic_ostream<char_type, traits_type>& operator<<(std::basic_ostream<char_type, traits_type>& os, const std::complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      std::basic_ostringstream<char_type, traits_type> ostr;\r\n\r\n      ostr.flags(os.flags());\r\n      ostr.imbue(os.getloc());\r\n      ostr.precision(os.precision());\r\n\r\n      ostr << char_type('(')\r\n           << x.real()\r\n           << char_type(',')\r\n           << x.imag()\r\n           << char_type(')');\r\n\r\n      return (os << ostr.str());\r\n    }\r\n\r\n    template<class char_type, class traits_type>\r\n    inline std::basic_istream<char_type, traits_type>& operator>>(std::basic_istream<char_type, traits_type>& is, std::complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>& x)\r\n    {\r\n      BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE rx;\r\n      BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE ix;\r\n\r\n      char_type the_char;\r\n\r\n      static_cast<void>(is >> the_char);\r\n\r\n      if(the_char == static_cast<char_type>('('))\r\n      {\r\n        static_cast<void>(is >> rx >> the_char);\r\n\r\n        if(the_char == static_cast<char_type>(','))\r\n        {\r\n          static_cast<void>(is >> ix >> the_char);\r\n\r\n          if(the_char == static_cast<char_type>(')'))\r\n          {\r\n            x = complex<BOOST_CSTDFLOAT_EXTENDED_COMPLEX_FLOAT_TYPE>(rx, ix);\r\n          }\r\n          else\r\n          {\r\n            is.setstate(ios_base::failbit);\r\n          }\r\n        }\r\n        else if(the_char == static_cast<char_type>(')'))\r\n        {\r\n          x = rx;\r\n        }\r\n        else\r\n        {\r\n          is.setstate(ios_base::failbit);\r\n        }\r\n      }\r\n      else\r\n      {\r\n        static_cast<void>(is.putback(the_char));\r\n\r\n        static_cast<void>(is >> rx);\r\n\r\n        x = rx;\r\n      }\r\n\r\n      return is;\r\n    }\r\n  } // namespace std\r\n\r\n#endif // _BOOST_CSTDFLOAT_COMPLEX_STD_2014_02_15_HPP_\r\n", "meta": {"hexsha": "81659ab5aa9d1b83e28845e17c3a139fcf9ca627", "size": 34507, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/cstdfloat/cstdfloat_complex_std.hpp", "max_stars_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_stars_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/cstdfloat/cstdfloat_complex_std.hpp", "max_issues_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_issues_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/math/cstdfloat/cstdfloat_complex_std.hpp", "max_forks_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_forks_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 53.7492211838, "max_line_length": 375, "alphanum_fraction": 0.6813979772, "num_tokens": 8184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2151425511312973}}
{"text": "// Boost.Geometry\n\n// Copyright (c) 2018, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_CONSTANTS_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_CONSTANTS_HPP\n\n\n#include <boost/geometry/util/math.hpp>\n#include <boost/math/constants/constants.hpp>\n\n\nnamespace boost { namespace geometry { namespace projections\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\n\ntemplate <typename T>\ninline T fourth_pi() { return T(0.78539816339744830961566084581988); }\ntemplate <typename T>\ninline T third_pi() { return boost::math::constants::third_pi<T>(); }\ntemplate <typename T>\ninline T half_pi() { return boost::math::constants::half_pi<T>(); }\ntemplate <typename T>\ninline T pi() { return boost::math::constants::pi<T>(); }\ntemplate <typename T>\ninline T one_and_half_pi() { return T(4.7123889803846898576939650749193); }\ntemplate <typename T>\ninline T two_pi() { return boost::math::constants::two_pi<T>(); }\ntemplate <typename T>\ninline T two_and_half_pi() { return T(7.8539816339744830961566084581988); }\n\ntemplate <typename T>\ninline T two_div_pi() { return boost::math::constants::two_div_pi<T>(); }\ntemplate <typename T>\ninline T half_pi_sqr() { return T(2.4674011002723396547086227499689); }\ntemplate <typename T>\ninline T pi_sqr() { return boost::math::constants::pi_sqr<T>(); }\n\ntemplate <typename T>\ninline T sixth() { return boost::math::constants::sixth<T>(); }\ntemplate <typename T>\ninline T third() { return boost::math::constants::third<T>(); }\ntemplate <typename T>\ninline T two_thirds() { return boost::math::constants::two_thirds<T>(); }\n\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n}}} // namespace boost::geometry::projections\n#endif // BOOST_GEOMETRY_PROJECTIONS_IMPL_PROJECTS_HPP\n", "meta": {"hexsha": "a8ebf2bca063a52d13832619c9dd8b98b8351b92", "size": 1974, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/srs/projections/constants.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/srs/projections/constants.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/srs/projections/constants.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 31.3333333333, "max_line_length": 79, "alphanum_fraction": 0.7497467072, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.3415825128436339, "lm_q1q2_score": 0.2151199976693983}}
{"text": "/*\n\nSoftware License Agreement (BSD License)\n\nCopyright (c) 2016--, Liana Bertoni (liana.bertoni@gmail.com)\n  All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder(s) nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nContact GitHub API Training Shop Blog About\n*/\n\n\n#include <ros/ros.h>\n#include <ros/package.h>\n#include <tf/transform_broadcaster.h>\n#include <geometry_msgs/PoseStamped.h>\n#include <geometry_msgs/Pose.h>\n\n#include <eigen3/Eigen/Core>\n#include <eigen3/Eigen/Dense>\n#include <eigen3/Eigen/Geometry>\n\n#include <kdl/chain.hpp>\n#include <kdl/chainfksolver.hpp>\n#include <kdl/chainfksolverpos_recursive.hpp>\n#include <kdl/frames_io.hpp>\n\n#include <boost/scoped_ptr.hpp>\n#include <kdl/chainjnttojacsolver.hpp>\n#include <kdl/chainfksolverpos_recursive.hpp>\n\n#include <kdl_parser/kdl_parser.hpp>\n#include <urdf/model.h>\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdlib>\n#include <string>\n\n#include <math.h>\n#include <stdio.h>\n#include <ctime>\n#include <time.h>\n\n#include \"quality.h\"\n#include \"PGR_5.h\"\n#include \"normal_component_box_surface.h\"\n\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace KDL;\nconst double PPI_  = 3.141592653589793238463;\n\nconst double PI_  = 3.141592653589793238463;\n\n//////////////////////////////////  BOX\n\nstd::vector<double> box;\n//////////////////////////////////////////////\n\n\n/////////////////////////////////// CONTACT POINTS\n\nstd::vector<double> contact_points;\n///////////////////////////////////////\n\n\n////////////////////////////////////  CONTACT FORCE\n\nstd::vector<double> contact_forces;\n/////////////////////////////////////////////\n\n\n////////////////////////////////////// JOINTS\n\nstd::vector<double> joints;\n////////////////////////////////////////////\n\n\nint n_c = 0;\nint n_q = 0;\ndouble quality_i = 0;\ndouble contact_stiffness = 100;\ndouble joint_stiffness = 1; \ndouble mu = 1.5;\ndouble f_i_max = 200;\n\n\n//////////////////////////////////////////// ROBOT SCTRUCTURE\n\nKDL::Tree hand_tree(\"RootName\");\n\n\n  KDL::Chain chain_palm;\n\n  KDL::Chain chain_finger_right_0;\n  KDL::Chain chain_finger_left_0;\n  KDL::Chain chain_finger_right_1;\n  KDL::Chain chain_finger_left_1;\n  KDL::Chain chain_finger_right_2;\n  KDL::Chain chain_finger_left_2;\n\n  KDL::Chain chain_palm_finger_left_0; // return the result\n  KDL::Chain chain_palm_finger_left_1;\n  KDL::Chain chain_palm_finger_left_2; \n  KDL::Chain chain_palm_finger_right_0;\n  KDL::Chain chain_palm_finger_right_1;\n  KDL::Chain chain_palm_finger_right_2;\n\n  KDL::JntArray jointpositions_right_0 = JntArray(8);  \n  KDL::JntArray jointpositions_right_1 = JntArray(8);  \n  KDL::JntArray jointpositions_right_2 = JntArray(8);  \n  KDL::JntArray jointpositions_left_0 = JntArray(8);\n  KDL::JntArray jointpositions_left_1 = JntArray(8);\n  KDL::JntArray jointpositions_left_2 = JntArray(8);\n\n  KDL::Jacobian jacobian_right_0;\n  KDL::Jacobian jacobian_left_0;\n  KDL::Jacobian jacobian_right_1;\n  KDL::Jacobian jacobian_left_1;\n  KDL::Jacobian jacobian_right_2;\n  KDL::Jacobian jacobian_left_2;\n\n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_right_0;\n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_left_0;\n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_right_1;\n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_left_1; \n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_right_2;\n  boost::scoped_ptr<KDL::ChainJntToJacSolver> jnt_to_jac_left_2;\n\n///////////////////////////////////////////////////////////\n\n\n\n//------------------------------------------------------------------------------------------\nvoid createStructureKDL()\n{\n\n  chain_palm.addSegment(Segment(\"palm_trasl_x_link\",Joint(Joint::TransX),Frame(Vector(0.0,0.0,0.0))));  \n  chain_palm.addSegment(Segment(\"palm_trasl_y_link\",Joint(Joint::TransY),Frame(Vector(0.0,0.0,0.0))));\n  chain_palm.addSegment(Segment(\"palm_trasl_z_link\",Joint(Joint::TransZ),Frame(Vector(0.0,0.0,0.0))));\n  chain_palm.addSegment(Segment(\"palm_rot_x_link\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.0))));\n  chain_palm.addSegment(Segment(\"palm_rot_y_link\",Joint(Joint::RotY),Frame(Vector(0.0,0.0,0.0))));\n  chain_palm.addSegment(Segment(\"palm_rot_z_link\",Joint(Joint::RotZ),Frame(Vector(0.0,0.0,0.0))));\n\n  chain_finger_right_0.addSegment(Segment(\"finger_right_proximal_link_0\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.03))));\n  chain_finger_right_0.addSegment(Segment(\"finger_right_distal_link_0\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.03))));\n\n  chain_finger_left_0.addSegment(Segment(\"finger_left_proximal_link_0\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.3))));\n  chain_finger_left_0.addSegment(Segment(\"finger_left_distal_link_0\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.03))));\n\n  chain_finger_right_1.addSegment(Segment(\"finger_right_proximal_link_1\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.03))));\n  chain_finger_right_1.addSegment(Segment(\"finger_right_distal_link_1\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.03))));\n\n  chain_finger_left_1.addSegment(Segment(\"finger_left_proximal_link_1\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.3))));\n  chain_finger_left_1.addSegment(Segment(\"finger_left_distal_link_1\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.03))));\n\n  chain_finger_right_2.addSegment(Segment(\"finger_right_proximal_link_2\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.03))));\n  chain_finger_right_2.addSegment(Segment(\"finger_right_distal_link_2\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.03))));\n\n  chain_finger_left_2.addSegment(Segment(\"finger_left_proximal_link_2\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.3))));\n  chain_finger_left_2.addSegment(Segment(\"finger_left_distal_link_2\",Joint(Joint::RotX),Frame(Vector(0.0,0.0,0.03))));\n    \n    \n\n  hand_tree.addChain(chain_palm,\"RootName\");    \n  hand_tree.addChain(chain_finger_right_0,\"palm_rot_z_link\");\n  hand_tree.addChain(chain_finger_left_0, \"palm_rot_z_link\"); \n  hand_tree.addChain(chain_finger_right_1,\"palm_rot_z_link\");\n  hand_tree.addChain(chain_finger_left_1, \"palm_rot_z_link\"); \n  hand_tree.addChain(chain_finger_right_2,\"palm_rot_z_link\");\n  hand_tree.addChain(chain_finger_left_2, \"palm_rot_z_link\"); \n\n\n\n  hand_tree.getChain(\"RootName\", \"finger_right_distal_link_0\", chain_palm_finger_right_0);\n  hand_tree.getChain(\"RootName\", \"finger_left_distal_link_0\", chain_palm_finger_left_0);\n  hand_tree.getChain(\"RootName\", \"finger_right_distal_link_1\", chain_palm_finger_right_1);\n  hand_tree.getChain(\"RootName\", \"finger_left_distal_link_1\", chain_palm_finger_left_1); \n  hand_tree.getChain(\"RootName\", \"finger_right_distal_link_2\", chain_palm_finger_right_2);\n  hand_tree.getChain(\"RootName\", \"finger_left_distal_link_2\", chain_palm_finger_left_2);\n\n}\n//-------------------------------------------------------------------------------------------\n\n\n//-------------------------------------------------------------------------------------------\nvoid setJoints(std::vector<double>  joints_in)\n{\n  for(int i=0 ; i < 6 ; i++)\n      jointpositions_right_0(i) = jointpositions_left_0(i) = jointpositions_right_1(i) = jointpositions_left_1(i) = jointpositions_right_2(i) = jointpositions_left_2(i) = joints[i];\n \n    jointpositions_right_0(6) = joints_in[6];\n    jointpositions_right_0(7) = joints_in[7];\n\n    jointpositions_left_0(6) = joints_in[8];\n    jointpositions_left_0(7) = joints_in[9];\n\n    jointpositions_right_1(6) = joints_in[10];\n    jointpositions_right_1(7) = joints_in[11];\n\n    jointpositions_left_1(6) = joints_in[12];\n    jointpositions_left_1(7) = joints_in[13];\n\n    jointpositions_right_2(6) = joints_in[14];\n    jointpositions_right_2(7) = joints_in[15];\n\n    jointpositions_left_2(6) = joints_in[16];\n    jointpositions_left_2(7) = joints_in[17];\n\n  jointpositions_right_0.resize(chain_palm_finger_right_0.getNrOfJoints());\n  jointpositions_left_0.resize(chain_palm_finger_left_0.getNrOfJoints());\n\n  jointpositions_right_1.resize(chain_palm_finger_right_1.getNrOfJoints());\n  jointpositions_left_1.resize(chain_palm_finger_left_1.getNrOfJoints());\n\n  jointpositions_right_2.resize(chain_palm_finger_right_2.getNrOfJoints());\n  jointpositions_left_2.resize(chain_palm_finger_left_2.getNrOfJoints());\n}\n\n\n\nvoid initJacobian()\n{\n    jacobian_right_0.resize(chain_palm_finger_right_0.getNrOfJoints());\n    jacobian_left_0.resize(chain_palm_finger_left_0.getNrOfJoints());\n\n    jnt_to_jac_right_0.reset(new KDL::ChainJntToJacSolver(chain_palm_finger_right_0));\n    jnt_to_jac_left_0.reset(new KDL::ChainJntToJacSolver(chain_palm_finger_left_0));\n\n    jacobian_right_1.resize(chain_palm_finger_right_1.getNrOfJoints());\n    jacobian_left_1.resize(chain_palm_finger_left_1.getNrOfJoints());\n\n    jnt_to_jac_right_1.reset(new KDL::ChainJntToJacSolver(chain_palm_finger_right_1));\n    jnt_to_jac_left_1.reset(new KDL::ChainJntToJacSolver(chain_palm_finger_left_1));\n\n    jacobian_right_2.resize(chain_palm_finger_right_2.getNrOfJoints());\n    jacobian_left_2.resize(chain_palm_finger_left_2.getNrOfJoints());\n\n    jnt_to_jac_right_2.reset(new KDL::ChainJntToJacSolver(chain_palm_finger_right_2));\n    jnt_to_jac_left_2.reset(new KDL::ChainJntToJacSolver(chain_palm_finger_left_2));\n}\n\n\n\nint main (int argc, char **argv)\n{\n\n  ros::init(argc, argv, \"Test_file_4_finger\"); \n  ros::NodeHandle nh;\n\n  \n\n\n  nh.param<std::vector<double>>(\"box\", box, std::vector<double>{1, 1, 1});\n  nh.param<std::vector<double>>(\"contact_points\", contact_points, std::vector<double>{1,1,1,1,1,1});\n  nh.param<std::vector<double>>(\"contact_forces\", contact_forces, std::vector<double>{1,1,1,1,1,1});\n  nh.param<std::vector<double>>(\"joints\", joints, std::vector<double>{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});\n  nh.param<double>(\"mu\", mu, 0.5);\n  nh.param<double>(\"f_i_max\", f_i_max, 1);\n  nh.param<int>(\"n_c\", n_c, 0);\n  nh.param<int>(\"n_q\", n_q, 0);\n\n\n  if(n_c <= 0) \n    return 0;\n\n  createStructureKDL();\n  setJoints(joints);\n  initJacobian();\n\n  Eigen::MatrixXd Skew_Matrix1(3,3);\n  Eigen::MatrixXd Skew_Matrix2(3,3);\n  Eigen::MatrixXd Skew_Matrix3(3,3);\n  Eigen::MatrixXd Skew_Matrix4(3,3);\n  Eigen::MatrixXd Skew_Matrix5(3,3);\n  Eigen::MatrixXd Skew_Matrix6(3,3);\n\n  Skew_Matrix1(0,0) = Skew_Matrix1(1,1) = Skew_Matrix1(2,2) = 0;\n      Skew_Matrix1(0,1) = - contact_points[2]; // -rz    \n      Skew_Matrix1(0,2) = contact_points[1];   // ry\n      Skew_Matrix1(1,0) = contact_points[2];   // rz\n      Skew_Matrix1(2,0) = - contact_points[1]; // -ry\n      Skew_Matrix1(1,2) = - contact_points[0]; // -rx\n      Skew_Matrix1(2,1) = contact_points[0];   // rx\n  // left\n\n\n Skew_Matrix2(0,0) = Skew_Matrix2(1,1) = Skew_Matrix2(2,2) = 0;\n      Skew_Matrix2(0,1) = - contact_points[5]; // -rz    \n      Skew_Matrix2(0,2) = contact_points[4];   // ry\n      Skew_Matrix2(1,0) = contact_points[5];   // rz\n      Skew_Matrix2(2,0) = - contact_points[4]; // -ry\n      Skew_Matrix2(1,2) = - contact_points[3]; // -rx\n      Skew_Matrix2(2,1) = contact_points[3];   // rx\n  // right\n\n\n  Skew_Matrix3(0,0) = Skew_Matrix3(1,1) = Skew_Matrix3(2,2) = 0;\n      Skew_Matrix3(0,1) = - contact_points[8]; // -rz    \n      Skew_Matrix3(0,2) = contact_points[7];   // ry\n      Skew_Matrix3(1,0) = contact_points[8];   // rz\n      Skew_Matrix3(2,0) = - contact_points[7]; // -ry\n      Skew_Matrix3(1,2) = - contact_points[6]; // -rx\n      Skew_Matrix3(2,1) = contact_points[6];   // rx\n  // up\n\n\n Skew_Matrix4(0,0) = Skew_Matrix4(1,1) = Skew_Matrix4(2,2) = 0;\n      Skew_Matrix4(0,1) = - contact_points[11]; // -rz    \n      Skew_Matrix4(0,2) = contact_points[10];   // ry\n      Skew_Matrix4(1,0) = contact_points[11];   // rz\n      Skew_Matrix4(2,0) = - contact_points[10]; // -ry\n      Skew_Matrix4(1,2) = - contact_points[9]; // -rx\n      Skew_Matrix4(2,1) = contact_points[9];   // rx\n  // down\n\n  Skew_Matrix5(0,0) = Skew_Matrix5(1,1) = Skew_Matrix5(2,2) = 0;\n      Skew_Matrix5(0,1) = - contact_points[14]; // -rz    \n      Skew_Matrix5(0,2) = contact_points[13];   // ry\n      Skew_Matrix5(1,0) = contact_points[14];   // rz\n      Skew_Matrix5(2,0) = - contact_points[13]; // -ry\n      Skew_Matrix5(1,2) = - contact_points[12]; // -rx\n      Skew_Matrix5(2,1) = contact_points[12];   // rx\n  // front of\n\n\n Skew_Matrix6(0,0) = Skew_Matrix6(1,1) = Skew_Matrix6(2,2) = 0;\n      Skew_Matrix6(0,1) = - contact_points[17]; // -rz    \n      Skew_Matrix6(0,2) = contact_points[16];   // ry\n      Skew_Matrix6(1,0) = contact_points[17];   // rz\n      Skew_Matrix6(2,0) = - contact_points[16]; // -ry\n      Skew_Matrix6(1,2) = - contact_points[15]; // -rx\n      Skew_Matrix6(2,1) = contact_points[15];   // rx\n  // behind\n\n\n\nEigen::MatrixXd G_c_t = MatrixXd::Zero(6, 6*n_c);\nEigen::MatrixXd G1 = MatrixXd::Zero(6,6);\nEigen::MatrixXd G2 = MatrixXd::Zero(6,6);\nEigen::MatrixXd G3 = MatrixXd::Zero(6,6);\nEigen::MatrixXd G4 = MatrixXd::Zero(6,6);\nEigen::MatrixXd G5 = MatrixXd::Zero(6,6);\nEigen::MatrixXd G6 = MatrixXd::Zero(6,6);\n\nEigen::MatrixXd R1(3,3);\nEigen::MatrixXd R2(3,3);\nEigen::MatrixXd R3(3,3);\nEigen::MatrixXd R4(3,3);\nEigen::MatrixXd R5(3,3);\nEigen::MatrixXd R6(3,3);\n\nR1 << 1, 0, 0,\n       0, cos(-90*PPI_/180), -sin(-90*PPI_/180),\n       0, sin(-90*PPI_/180), cos(-90*PPI_/180);\n// left\n\nR2 << 1, 0, 0,\n      0, cos(90*PPI_/180), -sin(90*PPI_/180),\n      0, sin(90*PPI_/180), cos(90*PPI_/180);\n// right\n\nR3 << 1, 0, 0,\n      0, cos(180*PPI_/180), -sin(180*PPI_/180),\n      0, sin(180*PPI_/180), cos(180*PPI_/180);\n// up\n\nR4 << 1, 0, 0,\n      0, 1, 0,\n      0, 0, 1;\n// down\n\nR5 <<  cos(-90*PPI/180),  0, sin(-90*PPI/180),\n                   0   ,  1,    0 ,\n      -sin(-90*PPI/180),  0, cos(-90*PPI/180);\n//front of\n\nR6 << cos(90*PPI/180),  0, sin(90*PPI/180),\n                 0   ,  1,    0 ,\n      -sin(90*PPI/180), 0, cos(90*PPI/180);\n//behind\n\n\n\n\nG1.block<3,3>(0,0) = R1.transpose();\nG1.block<3,3>(3,3) = R1.transpose();\nG1.block<3,3>(3,0) = Skew_Matrix1 * R1.transpose();\n\nG2.block<3,3>(0,0) = R2.transpose();\nG2.block<3,3>(3,3) = R2.transpose();\nG2.block<3,3>(3,0) = Skew_Matrix2 * R2.transpose();\n\nG3.block<3,3>(0,0) = R3.transpose();\nG3.block<3,3>(3,3) = R3.transpose();\nG3.block<3,3>(3,0) = Skew_Matrix3 * R3.transpose();\n\nG4.block<3,3>(0,0) = R4.transpose();\nG4.block<3,3>(3,3) = R4.transpose();\nG4.block<3,3>(3,0) = Skew_Matrix4 * R4.transpose();\n\nG5.block<3,3>(0,0) = R5.transpose();\nG5.block<3,3>(3,3) = R5.transpose();\nG5.block<3,3>(3,0) = Skew_Matrix5 * R5.transpose();\n\nG6.block<3,3>(0,0) = R6.transpose();\nG6.block<3,3>(3,3) = R6.transpose();\nG6.block<3,3>(3,0) = Skew_Matrix6 * R6.transpose();\n\nG_c_t.block<6,6>(0,0) = G1;\nG_c_t.block<6,6>(0,6) = G2;\nG_c_t.block<6,6>(0,12) = G3;\nG_c_t.block<6,6>(0,18) = G4;\nG_c_t.block<6,6>(0,24) = G5;\nG_c_t.block<6,6>(0,30) = G6;\n\n\n\nEigen::MatrixXd Jacobian = MatrixXd::Zero(6*n_c,n_q);\n\njnt_to_jac_right_0->JntToJac(jointpositions_right_0, jacobian_right_0);\njnt_to_jac_left_0->JntToJac(jointpositions_left_0, jacobian_left_0);\n\njnt_to_jac_right_1->JntToJac(jointpositions_right_1, jacobian_right_1);\njnt_to_jac_left_1->JntToJac(jointpositions_left_1, jacobian_left_1);\n\njnt_to_jac_right_2->JntToJac(jointpositions_right_2, jacobian_right_2);\njnt_to_jac_left_2->JntToJac(jointpositions_left_2, jacobian_left_2);\n\n\n    \nJacobian.block<6,8>(0,0) = jacobian_right_0.data;                  // first contact - first finger\n\nJacobian.block<6,6>(6,0) = jacobian_left_0.data.block<6,6>(0,0);   // second contact - second finger\nJacobian.block<6,2>(6,8) = jacobian_left_0.data.block<6,2>(0,6);\n\nJacobian.block<6,6>(12,0) = jacobian_right_1.data.block<6,6>(0,0); // third contact - third finger\nJacobian.block<6,2>(12,10) = jacobian_right_1.data.block<6,2>(0,6);\n\nJacobian.block<6,6>(18,0) = jacobian_left_1.data.block<6,6>(0,0);  // four-th contact - four-th finger\nJacobian.block<6,2>(18,12) = jacobian_left_1.data.block<6,2>(0,6);\n \nJacobian.block<6,6>(24,0) = jacobian_right_2.data.block<6,6>(0,0);  // five-th contact - five-th finger\nJacobian.block<6,2>(24,14) = jacobian_right_2.data.block<6,2>(0,6);\n \nJacobian.block<6,6>(30,0) = jacobian_left_2.data.block<6,6>(0,0);  // six-th contact - six-th finger\nJacobian.block<6,2>(30,16) = jacobian_left_2.data.block<6,2>(0,6);\n \n\n\n\n\n    Eigen::MatrixXd R_c = MatrixXd::Zero(3*n_c,3*n_c);\n    int k = 0; \n    for(int i = 0 ; i < n_c ; i++)\n    { \n      R_c.block<3,3>(k,k) = MatrixXd::Identity(3,3);\n      k += 3;\n    }\n\n    Eigen::VectorXd f_c_(contact_forces.size());\n    for(int i = 0 ; i < contact_forces.size() ; i++ )\n      f_c_(i) = contact_forces[i];\n\n    Eigen::MatrixXd Contact_Stiffness_Matrix = MatrixXd::Zero(3,3);   // Kis\n      for(int i = 0 ; i < Contact_Stiffness_Matrix.rows() ; i++) //Kis\n          Contact_Stiffness_Matrix(i,i) = contact_stiffness;\n\n\n    Eigen::MatrixXd Joint_Stiffness_Matrix = MatrixXd::Zero(n_q,n_q);    // Kp            \n      for(int j = 0 ; j < Joint_Stiffness_Matrix.rows() ; j++) //Kp\n          Joint_Stiffness_Matrix(j,j) = joint_stiffness;\n  \n  //quality_i = quality_pcr_pgr_5(f_c_, G_c, Jacobian, R_c, Contact_Stiffness_Matrix, Joint_Stiffness_Matrix, mu, f_i_max);\n // quality_i = quality_pcr_pgr_5(f_c_, G_b, Jacobian, R_c, Contact_Stiffness_Matrix, Joint_Stiffness_Matrix, mu, f_i_max);\n\n\n\n  quality_i = quality_pcr_pgr_5(f_c_, G_c_t, Jacobian, R_c, Contact_Stiffness_Matrix, Joint_Stiffness_Matrix, mu, f_i_max);\n\n\n  cout << \" quality : \" << quality_i << endl;\n\n  ros::spinOnce();\n  return 0;\n}", "meta": {"hexsha": "bae9ed9b7fdd1bd37609b925658b83ac7d86d9da", "size": 18565, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test_file_6_fingers.cpp", "max_stars_repo_name": "lia2790/grasp-learning", "max_stars_repo_head_hexsha": "e32c58eff37c1a951e914705a916452044c1d019", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-11-08T12:51:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-26T12:17:22.000Z", "max_issues_repo_path": "src/test_file_6_fingers.cpp", "max_issues_repo_name": "lia2790/grasp-learning", "max_issues_repo_head_hexsha": "e32c58eff37c1a951e914705a916452044c1d019", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test_file_6_fingers.cpp", "max_forks_repo_name": "lia2790/grasp-learning", "max_forks_repo_head_hexsha": "e32c58eff37c1a951e914705a916452044c1d019", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-05-30T14:59:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-11T13:34:27.000Z", "avg_line_length": 36.259765625, "max_line_length": 181, "alphanum_fraction": 0.6844600054, "num_tokens": 6197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.36296921241058616, "lm_q1q2_score": 0.21511972900738865}}
{"text": "/* Copyright (C) 2012-2020 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *   http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n#include <NTL/BasicThreadPool.h>\n\n#include <helib/recryption.h>\n#include <helib/EncryptedArray.h>\n#include <helib/EvalMap.h>\n#include <helib/powerful.h>\n#include <helib/CtPtrs.h>\n#include <helib/intraSlot.h>\n#include <helib/norms.h>\n#include <helib/sample.h>\n#include <helib/debugging.h>\n#include <helib/fhe_stats.h>\n#include <helib/log.h>\n\n#ifdef HELIB_DEBUG\n\n#include <helib/debugging.h>\n\nnamespace helib {\n\nlong printFlag = FLAG_PRINT_VEC;\n/************************ Some local functions ***********************/\n/*********************************************************************/\n\nstatic void checkCriticalValue(const std::vector<NTL::ZZX>& zzParts,\n                               const DoubleCRT& sKey,\n                               const RecryptData& rcData,\n                               long q);\n\nstatic void checkRecryptBounds(const std::vector<NTL::ZZX>& zzParts,\n                               const DoubleCRT& sKey,\n                               const Context& context,\n                               long q);\n\nstatic void checkRecryptBounds_v(const std::vector<NTL::ZZX>& v,\n                                 const DoubleCRT& sKey,\n                                 const Context& context,\n                                 long q);\n} // namespace helib\n\n#endif // HELIB_DEBUG\n\nnamespace helib {\n\n// Return in poly a polynomial with X^i encoded in all the slots\nstatic void x2iInSlots(NTL::ZZX& poly,\n                       long i,\n                       std::vector<NTL::ZZX>& xVec,\n                       const EncryptedArray& ea)\n{\n  xVec.resize(ea.size());\n  NTL::ZZX x2i = NTL::ZZX(i, 1);\n  for (long j = 0; j < (long)xVec.size(); j++)\n    xVec[j] = x2i;\n  ea.encode(poly, xVec);\n}\n\n// Make every entry of vec divisible by p2e by adding/subtracting q, while\n// keeping the added multiples small.  Specifically, for q = 1 mod p2e and any\n// integer z can be made divisible by p2e via z' = z + v*q, with |v| <= p2e/2.\n\nstatic void newMakeDivisible(NTL::ZZX& poly,\n                             long p2e,\n                             long q,\n                             const Context& context,\n                             NTL::ZZX& vpoly)\n{\n  if (p2e == 1) {\n    vpoly = 0;\n    return;\n  }\n\n  assertTrue<InvalidArgument>(q > 0l, \"q must be positive\");\n  assertTrue<InvalidArgument>(p2e > 0l, \"p2e must be positive\");\n\n  assertEq<InvalidArgument>(q % p2e, 1l, \"q must equal 1 modulo p2e\");\n\n  long p = context.getP();\n\n  const RecryptData& rcData = context.getRcData();\n  const PowerfulDCRT& p2d_conv = *rcData.p2dConv;\n\n  NTL::Vec<NTL::ZZ> pwrfl;\n  p2d_conv.ZZXtoPowerful(pwrfl, poly);\n\n#ifdef HELIB_DEBUG\n  NTL::Vec<NTL::ZZ> vvec(NTL::INIT_SIZE, pwrfl.length());\n#endif\n\n  for (long i : range(pwrfl.length())) {\n    NTL::ZZ& z = pwrfl[i];\n    long v;\n\n    // What to add to z to make it divisible by p2e?\n    long zMod = rem(z, p2e); // zMod is in [0,p2e-1]\n    // NOTE: this makes sure we get a truly balanced remainder\n    if (zMod > p2e / 2 || (p == 2 && zMod == p2e / 2 && NTL::RandomBnd(2))) {\n      // randomize so that v has expected value 0\n      zMod = p2e - zMod;\n    } else {\n      // need to add a negative number\n      zMod = -zMod;\n    }\n    v = zMod;\n    z += NTL::to_ZZ(q) * v; // make z divisible by p2e\n\n    if (rem(z, p2e) != 0) { // sanity check\n      std::cerr << \"**error: original z[\" << i\n                << \"]=\" << (z - (NTL::to_ZZ(q) * v)) << std::dec\n                << \", p^e=\" << p2e << std::endl;\n      std::cerr << \"z' = z + \" << v << \"*q = \" << z << std::endl;\n      exit(1);\n    }\n\n#ifdef HELIB_DEBUG\n    vvec[i] = v;\n#endif\n  }\n\n  p2d_conv.powerfulToZZX(poly, pwrfl);\n\n#ifdef HELIB_DEBUG\n  p2d_conv.powerfulToZZX(vpoly, vvec);\n#endif\n}\n\n/*********************************************************************/\n/*********************************************************************/\n\n/**\n * Summary of Appendix A from https://ia.cr/2014/873 (version from 2019):\n * Assume that we already chosen e, e' and t.\n *\n * Based in this analysis, we need\n *    (1) (f*p^{e'} + 2*p^r+2))*B <= p^e/2\n * where B is a certain high-probability bound and f is a certain\n * fudge factor.\n *\n **/\n\n// the routine compute_fudge is used to correct for the fact that\n// the v-coeffs are not quite uniform\n\nstatic double compute_fudge(long p2ePrime, long p2e)\n{\n  double eps = 0;\n\n  if (p2ePrime > 1) {\n\n    if (p2ePrime % 2 == 0) {\n      eps = 1 / fsquare(p2ePrime);\n\n      // The exact variance in this case is at most the variance\n      // of a random variable that is distributed over\n      //    -N..+N\n      // where N = 2^{e'}/2.\n      // Each endpoint occurs with probability 1/(4*N),\n      // and the remaining values each occur with the same probability\n      // 1/(2*N)\n\n      // This variance is exactly computed as\n      //    (N^2)/3 + 1/6 = ((N^2)/3)*(1 + 1/(2*N^2)), where N = 2^{e'}/2\n      // So the std dev is at most\n      //    N/sqrt(3)*(1 + 1/(4*N^2))\n\n    } else {\n      eps = 1 / double(p2e);\n\n      // We are computing X + Y mod p^{e'}, where\n      // X and Y are independent.\n      // Y is uniformly distributed over\n      //    -floor(p^{r}/2)..floor(p^{r}/2)\n      // X is distributed over\n      //    -floor(p^e/2)-1..floor(p^e/2)+1,\n      // where each endpoint occurs with probability 1 / (2*(p^e+1)),\n      // and the remaining p^e values are equally likely\n\n      // The variance in this case is bounded by\n      //   (N^2)/3*(1-eps) + (N^2)*eps = (N^2)/3*(1+2*eps),\n      //       where N = p^{e'}/2 and eps < 1/p^e\n      // So the std dev is bounded by\n      //    N/sqrt(3)*sqrt(1+2*eps) <= N/sqrt(3)*(1+eps)\n    }\n  }\n\n  return 1 + eps;\n}\n\nvoid RecryptData::setAE(long& e, long& ePrime, const Context& context)\n{\n  double coeff_bound = context.boundForRecryption();\n  // coeff_bound is ultimately a high prob bound on |w0+w1*s|,\n  // the coeffs of w0, w1 are chosen uniformly on [-1/2,1/2]\n\n  long p = context.getP();\n  long p2r = context.getAlMod().getPPowR();\n  long r = context.getAlMod().getR();\n  long frstTerm = 2 * p2r + 2;\n\n  long e_bnd = 0;\n  long p2e_bnd = 1;\n  while (p2e_bnd <= ((1L << 30) - 2) / p) { // NOTE: this avoids overflow\n    e_bnd++;\n    p2e_bnd *= p;\n  }\n  // e_bnd is largest e such that p^e+1 < 2^30\n\n  // Start with the smallest e s.t. p^e/2 >= frstTerm*coeff_bound\n  ePrime = 0;\n  e = r + 1;\n  while (e <= e_bnd && NTL::power_long(p, e) < frstTerm * coeff_bound * 2)\n    e++;\n\n  //  if (e > e_bnd) Error(\"setAE: cannot find suitable e\");\n  assertFalse<RuntimeError>(e > e_bnd, \"setAE: cannot find suitable e\");\n\n  // long ePrimeTry = r+1;\n  long ePrimeTry = 1;\n\n  while (ePrimeTry <= e_bnd) {\n    long p2ePrimeTry = NTL::power_long(p, ePrimeTry);\n    // long eTry = ePrimeTry+1;\n    long eTry = std::max(r + 1, ePrimeTry + 1);\n    while (eTry <= e_bnd && eTry - ePrimeTry < e - ePrime) {\n      long p2eTry = NTL::power_long(p, eTry);\n      double fudge = compute_fudge(p2ePrimeTry, p2eTry);\n      if (p2eTry >= (p2ePrimeTry * fudge + frstTerm) * coeff_bound * 2)\n        break;\n\n      eTry++;\n    }\n\n    if (eTry <= e_bnd && eTry - ePrimeTry < e - ePrime) {\n      e = eTry;\n      ePrime = ePrimeTry;\n    }\n\n    ePrimeTry++;\n  }\n\n#ifdef HELIB_DEBUG\n  std::cerr << \"RecryptData::setAE(): e=\" << e << \", e'=\" << ePrime\n            << std::endl;\n#endif\n}\n\nbool RecryptData::operator==(const RecryptData& other) const\n{\n  if (mvec != other.mvec)\n    return false;\n\n  if (skHwt != other.skHwt)\n    return false;\n\n  return true;\n}\n\n// The main method\nvoid RecryptData::init(const Context& context,\n                       const NTL::Vec<long>& mvec_,\n                       bool enableThick,\n                       bool build_cache_,\n                       bool minimal)\n{\n  if (alMod != nullptr) { // were we called for a second time?\n    std::cerr << \"@Warning: multiple calls to RecryptData::init\\n\";\n    return;\n  }\n\n  // sanity check\n  assertEq(computeProd(mvec_),\n           context.getM(),\n           \"Cyclotomic polynomial mismatch\");\n\n  // Record the arguments to this function\n  mvec = mvec_;\n  build_cache = build_cache_;\n  alsoThick = enableThick;\n\n  bool mvec_ok = true;\n  for (long i : range(mvec.length())) {\n    NTL::Vec<NTL::Pair<long, long>> factors;\n    factorize(factors, mvec[i]);\n    if (factors.length() > 1)\n      mvec_ok = false;\n  }\n\n  if (!mvec_ok) {\n    Warning(\"prime power factorization recommended for bootstrapping\");\n  }\n\n  skHwt = context.getHwt();\n  e = context.getE();\n  ePrime = context.getEPrime();\n\n  long r = context.getAlMod().getR();\n\n  // First part of Bootstrapping works wrt plaintext space p^{r'}\n  alMod = std::make_shared<PAlgebraMod>(context.getZMStar(), e - ePrime + r);\n  ea = std::make_shared<EncryptedArray>(context, *alMod);\n  // Polynomial defaults to F0, PAlgebraMod explicitly given\n\n  p2dConv = std::make_shared<PowerfulDCRT>(context, mvec);\n\n  if (!enableThick)\n    return;\n\n  // Initialize the linear polynomial for unpacking the slots\n  NTL::zz_pBak bak;\n  bak.save();\n  ea->getAlMod().restoreContext();\n  long nslots = ea->size();\n  long d = ea->getDegree();\n\n  const NTL::Mat<NTL::zz_p>& CBi =\n      ea->getDerived(PA_zz_p()).getNormalBasisMatrixInverse();\n\n  std::vector<NTL::ZZX> LM;\n  LM.resize(d);\n  for (long i = 0; i < d; i++) // prepare the linear polynomial\n    LM[i] = rep(CBi[i][0]);\n\n  std::vector<NTL::ZZX> C;\n  ea->buildLinPolyCoeffs(C, LM); // \"build\" the linear polynomial\n\n  unpackSlotEncoding.resize(d); // encode the coefficients\n\n  for (long j = 0; j < d; j++) {\n    std::vector<NTL::ZZX> v(nslots);\n    for (long k = 0; k < nslots; k++)\n      v[k] = C[j];\n    ea->encode(unpackSlotEncoding[j], v);\n  }\n  firstMap = std::make_shared<EvalMap>(*ea, minimal, mvec, true, build_cache);\n  secondMap = std::make_shared<EvalMap>(context.getEA(),\n                                        minimal,\n                                        mvec,\n                                        false,\n                                        build_cache);\n}\n\n/********************************************************************/\n/********************************************************************/\n\n// Extract digits from fully packed slots\nvoid extractDigitsPacked(Ctxt& ctxt,\n                         long botHigh,\n                         long r,\n                         long ePrime,\n                         const std::vector<NTL::ZZX>& unpackSlotEncoding);\n\n// Extract digits from unpacked slots\nvoid extractDigitsThin(Ctxt& ctxt, long botHigh, long r, long ePrime);\n\n// bootstrap a ciphertext to reduce noise\nvoid PubKey::reCrypt(Ctxt& ctxt) const\n{\n  HELIB_TIMER_START;\n\n  // Some sanity checks for dummy ciphertext\n  long ptxtSpace = ctxt.getPtxtSpace();\n  if (ctxt.isEmpty())\n    return;\n  if (ctxt.parts.size() == 1 && ctxt.parts[0].skHandle.isOne()) {\n    // Dummy encryption, just ensure that it is reduced mod p\n    NTL::ZZX poly = to_ZZX(ctxt.parts[0]);\n    for (long i = 0; i < poly.rep.length(); i++)\n      poly[i] = NTL::to_ZZ(rem(poly[i], ptxtSpace));\n    poly.normalize();\n    ctxt.DummyEncrypt(poly);\n    return;\n  }\n\n  // check that we have bootstrapping data\n  assertTrue(recryptKeyID >= 0l, \"No bootstrapping data\");\n\n  long p = getContext().getP();\n  long r = getContext().getAlMod().getR();\n  long p2r = getContext().getAlMod().getPPowR();\n\n  long intFactor = ctxt.intFactor;\n\n  // the bootstrapping key is encrypted relative to plaintext space p^{e-e'+r}.\n  const RecryptData& rcData = getContext().getRcData();\n  long e = rcData.e;\n  long ePrime = rcData.ePrime;\n  long p2ePrime = NTL::power_long(p, ePrime);\n  long q = NTL::power_long(p, e) + 1;\n  assertTrue(e >= r, \"rcData.e must be at least alMod.r\");\n\n#ifdef HELIB_DEBUG\n  std::cerr << \"reCrypt: p=\" << p << \", r=\" << r << \", e=\" << e\n            << \" ePrime=\" << ePrime << \", q=\" << q << std::endl;\n  CheckCtxt(ctxt, \"init\");\n#endif\n\n  // can only bootstrap ciphertext with plaintext-space dividing p^r\n  assertEq(p2r % ptxtSpace, 0l, \"ptxtSpace must divide p^r when bootstrapping\");\n\n  ctxt.dropSmallAndSpecialPrimes();\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after mod down\");\n#endif\n\n  HELIB_NTIMER_START(AAA_preProcess);\n\n  // Make sure that this ciphertext is in canonical form\n  if (!ctxt.inCanonicalForm())\n    ctxt.reLinearize();\n\n  // Mod-switch down if needed\n  IndexSet s = ctxt.getPrimeSet() / context.getSpecialPrimes();\n  assertTrue(s <= context.getCtxtPrimes(), \"prime set is messed up\");\n  if (s.card() > 3) { // leave only first three ciphertext primes\n    long first = s.first();\n    IndexSet s3(first, first + 2);\n    s.retain(s3);\n  }\n  ctxt.modDownToSet(s);\n\n  // key-switch to the bootstrapping key\n  ctxt.reLinearize(recryptKeyID);\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after key switching\");\n#endif\n\n  // \"raw mod-switch\" to the bootstrapping modulus q=p^e+1.\n  std::vector<NTL::ZZX> zzParts; // the mod-switched parts, in ZZX format\n\n  double mfac = ctxt.getContext().getZMStar().getNormBnd();\n  double noise_est = ctxt.rawModSwitch(zzParts, q) * mfac;\n  // noise_est is an upper bound on the L-infty norm of the scaled noise\n  // in the pwrfl basis\n  double noise_bnd =\n      HELIB_MIN_CAP_FRAC * p2r * ctxt.getContext().boundForRecryption();\n  // noise_bnd is the bound assumed in selecting the parameters\n  double noise_rat = noise_est / noise_bnd;\n\n  HELIB_STATS_UPDATE(\"raw-mod-switch-noise\", noise_rat);\n\n  if (noise_rat > 1) {\n    // TODO: Turn the following preprocessor logics into a warnOrThrow function\n    std::string message =\n        \"rawModSwitch scaled noise exceeds bound: \" + std::to_string(noise_rat);\n#ifdef HELIB_DEBUG\n    Warning(message);\n#else\n    throw LogicError(message);\n#endif\n  }\n\n  assertEq(zzParts.size(),\n           (std::size_t)2,\n           \"Exactly 2 parts required for mod-switching in thin bootstrapping\");\n\n#ifdef HELIB_DEBUG\n  if (dbgKey) {\n    checkRecryptBounds(zzParts, dbgKey->getRecryptKey(), ctxt.getContext(), q);\n  }\n#endif\n\n  std::vector<NTL::ZZX> v;\n  v.resize(2);\n\n  // Add multiples of q to make the zzParts divisible by p^{e'}\n  for (long i : range(2)) {\n    // make divisible by p^{e'}\n\n    newMakeDivisible(zzParts[i], p2ePrime, q, ctxt.getContext(), v[i]);\n  }\n\n#ifdef HELIB_DEBUG\n  if (dbgKey) {\n    checkRecryptBounds_v(v, dbgKey->getRecryptKey(), ctxt.getContext(), q);\n    checkCriticalValue(zzParts,\n                       dbgKey->getRecryptKey(),\n                       ctxt.getContext().getRcData(),\n                       q);\n  }\n#endif\n\n  for (long i : range(zzParts.size())) {\n    zzParts[i] /= p2ePrime; // divide by p^{e'}\n  }\n\n  // NOTE: here we lose the intFactor associated with ctxt.\n  // We will restore it below.\n  ctxt = recryptEkey;\n\n  ctxt.multByConstant(zzParts[1]);\n  ctxt.addConstant(zzParts[0]);\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after preProcess\");\n#endif\n  HELIB_NTIMER_STOP(AAA_preProcess);\n\n  // Move the powerful-basis coefficients to the plaintext slots\n  HELIB_NTIMER_START(AAA_LinearTransform1);\n  ctxt.getContext().getRcData().firstMap->apply(ctxt);\n  HELIB_NTIMER_STOP(AAA_LinearTransform1);\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after LinearTransform1\");\n#endif\n\n  // Extract the digits e-e'+r-1,...,e-e' (from fully packed slots)\n  HELIB_NTIMER_START(AAA_extractDigitsPacked);\n  extractDigitsPacked(ctxt,\n                      e - ePrime,\n                      r,\n                      ePrime,\n                      context.getRcData().unpackSlotEncoding);\n  HELIB_NTIMER_STOP(AAA_extractDigitsPacked);\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after extractDigitsPacked\");\n#endif\n\n  // Move the slots back to powerful-basis coefficients\n  HELIB_NTIMER_START(AAA_LinearTransform2);\n  ctxt.getContext().getRcData().secondMap->apply(ctxt);\n  HELIB_NTIMER_STOP(AAA_LinearTransform2);\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after linearTransform2\");\n#endif\n\n  // restore intFactor\n  if (intFactor != 1)\n    ctxt.intFactor = NTL::MulMod(ctxt.intFactor, intFactor, ptxtSpace);\n}\n\n#ifdef HELIB_BOOT_THREADS\n\n// Extract digits from fully packed slots, multithreaded version\nvoid extractDigitsPacked(Ctxt& ctxt,\n                         long botHigh,\n                         long r,\n                         long ePrime,\n                         const std::vector<NTL::ZZX>& unpackSlotEncoding)\n{\n  HELIB_TIMER_START;\n\n  // Step 1: unpack the slots of ctxt\n  HELIB_NTIMER_START(unpack);\n  ctxt.cleanUp();\n\n  // Apply the d automorphisms and store them in scratch area\n  long d = ctxt.getContext().getOrdP();\n\n  std::vector<Ctxt> unpacked(d, Ctxt(ZeroCtxtLike, ctxt));\n  { // explicit scope to force all temporaries to be released\n    std::vector<std::shared_ptr<DoubleCRT>> coeff_vector;\n    std::vector<double> coeff_vector_sz;\n    coeff_vector.resize(d);\n    coeff_vector_sz.resize(d);\n\n    HELIB_NTIMER_START(unpack1);\n    for (long i = 0; i < d; i++) {\n      coeff_vector[i] = std::make_shared<DoubleCRT>(unpackSlotEncoding[i],\n                                                    ctxt.getContext(),\n                                                    ctxt.getPrimeSet());\n      coeff_vector_sz[i] = NTL::conv<double>(\n          embeddingLargestCoeff(unpackSlotEncoding[i],\n                                ctxt.getContext().getZMStar()));\n    }\n    HELIB_NTIMER_STOP(unpack1);\n\n    HELIB_NTIMER_START(unpack2);\n    std::vector<Ctxt> frob(d, Ctxt(ZeroCtxtLike, ctxt));\n\n    NTL_EXEC_RANGE(d, first, last)\n    // FIXME: implement using hoisting!\n    for (long j = first; j < last; j++) { // process jth Frobenius\n      frob[j] = ctxt;\n      frob[j].frobeniusAutomorph(j);\n      frob[j].cleanUp();\n      // FIXME: not clear if we should call cleanUp here\n    }\n    NTL_EXEC_RANGE_END\n\n    HELIB_NTIMER_STOP(unpack2);\n\n    HELIB_NTIMER_START(unpack3);\n    Ctxt tmp1(ZeroCtxtLike, ctxt);\n    for (long i = 0; i < d; i++) {\n      for (long j = 0; j < d; j++) {\n        tmp1 = frob[j];\n        tmp1.multByConstant(*coeff_vector[mcMod(i + j, d)],\n                            coeff_vector_sz[mcMod(i + j, d)]);\n        unpacked[i] += tmp1;\n      }\n    }\n    HELIB_NTIMER_STOP(unpack3);\n  }\n  HELIB_NTIMER_STOP(unpack);\n\n  //#ifdef HELIB_DEBUG\n  //  CheckCtxt(unpacked[0], \"after unpack\");\n  //#endif\n\n  NTL_EXEC_RANGE(d, first, last)\n  for (long i = first; i < last; i++) {\n    extractDigitsThin(unpacked[i], botHigh, r, ePrime);\n  }\n  NTL_EXEC_RANGE_END\n\n  //#ifdef HELIB_DEBUG\n  // CheckCtxt(unpacked[0], \"before repack\");\n  //#endif\n\n  // Step 3: re-pack the slots\n  HELIB_NTIMER_START(repack);\n  const EncryptedArray& ea2 = ctxt.getContext().getEA();\n  NTL::ZZX xInSlots;\n  std::vector<NTL::ZZX> xVec(ea2.size());\n  ctxt = unpacked[0];\n  for (long i = 1; i < d; i++) {\n    x2iInSlots(xInSlots, i, xVec, ea2);\n    unpacked[i].multByConstant(xInSlots);\n    ctxt += unpacked[i];\n  }\n  HELIB_NTIMER_STOP(repack);\n  //#ifdef HELIB_DEBUG\n  // CheckCtxt(ctxt, \"after repack\");\n  //#endif\n}\n\n#else\n\n// Extract digits from fully packed slots\nvoid extractDigitsPacked(Ctxt& ctxt,\n                         long botHigh,\n                         long r,\n                         long ePrime,\n                         const std::vector<NTL::ZZX>& unpackSlotEncoding)\n{\n  HELIB_TIMER_START;\n\n  // Step 1: unpack the slots of ctxt\n  HELIB_NTIMER_START(unpack);\n  ctxt.cleanUp();\n\n  // Apply the d automorphisms and store them in scratch area\n  long d = ctxt.getContext().getOrdP();\n\n  std::vector<Ctxt> unpacked(d, Ctxt(ZeroCtxtLike, ctxt));\n  { // explicit scope to force all temporaries to be released\n    std::vector<std::shared_ptr<DoubleCRT>> coeff_vector;\n    std::vector<double> coeff_vector_sz;\n    coeff_vector.resize(d);\n    coeff_vector_sz.resize(d);\n    for (long i = 0; i < d; i++) {\n      coeff_vector[i] = std::make_shared<DoubleCRT>(unpackSlotEncoding[i],\n                                                    ctxt.getContext(),\n                                                    ctxt.getPrimeSet());\n      coeff_vector_sz[i] = NTL::conv<double>(\n          embeddingLargestCoeff(unpackSlotEncoding[i],\n                                ctxt.getContext().getZMStar()));\n    }\n\n    Ctxt tmp1(ZeroCtxtLike, ctxt);\n    Ctxt tmp2(ZeroCtxtLike, ctxt);\n\n    // FIXME: implement using hoisting!\n    for (long j = 0; j < d; j++) { // process jth Frobenius\n      tmp1 = ctxt;\n      tmp1.frobeniusAutomorph(j);\n      tmp1.cleanUp();\n      // FIXME: not clear if we should call cleanUp here\n\n      for (long i = 0; i < d; i++) {\n        tmp2 = tmp1;\n        tmp2.multByConstant(*coeff_vector[mcMod(i + j, d)],\n                            coeff_vector_sz[mcMod(i + j, d)]);\n        unpacked[i] += tmp2;\n      }\n    }\n  }\n  HELIB_NTIMER_STOP(unpack);\n\n  //#ifdef HELIB_DEBUG\n  //  CheckCtxt(unpacked[0], \"after unpack\");\n  //#endif\n\n  for (long i = 0; i < (long)unpacked.size(); i++) {\n    extractDigitsThin(unpacked[i], botHigh, r, ePrime);\n  }\n\n  //#ifdef HELIB_DEBUG\n  //  CheckCtxt(unpacked[0], \"before repack\");\n  //#endif\n\n  // Step 3: re-pack the slots\n  HELIB_NTIMER_START(repack);\n  const EncryptedArray& ea2 = *ctxt.getContext().ea;\n  NTL::ZZX xInSlots;\n  std::vector<NTL::ZZX> xVec(ea2.size());\n  ctxt = unpacked[0];\n  for (long i = 1; i < d; i++) {\n    x2iInSlots(xInSlots, i, xVec, ea2);\n    unpacked[i].multByConstant(xInSlots);\n    ctxt += unpacked[i];\n  }\n  HELIB_NTIMER_STOP(repack);\n}\n\n#endif\n\n// Use packed bootstrapping, so we can bootstrap all in just one go.\nvoid packedRecrypt(const CtPtrs& cPtrs,\n                   const std::vector<zzX>& unpackConsts,\n                   const EncryptedArray& ea)\n{\n  PubKey& pKey = (PubKey&)cPtrs[0]->getPubKey();\n\n  // Allocate temporary ciphertexts for the recryption\n  int nPacked = divc(cPtrs.size(), ea.getDegree()); // ceil(totalNum/d)\n  std::vector<Ctxt> cts(nPacked, Ctxt(pKey));\n\n  repack(CtPtrs_vectorCt(cts), cPtrs, ea); // pack ciphertexts\n  //  cout << \"@\"<< lsize(cts)<<std::flush;\n  for (Ctxt& c : cts) {   // then recrypt them\n    c.reducePtxtSpace(2); // we only have recryption data for binary ctxt\n    pKey.reCrypt(c);\n  }\n  unpack(cPtrs, CtPtrs_vectorCt(cts), ea, unpackConsts);\n}\n\n// recrypt all ctxt at level < belowLvl\nvoid packedRecrypt(const CtPtrs& array,\n                   const std::vector<zzX>& unpackConsts,\n                   const EncryptedArray& ea,\n                   long belowLvl)\n{\n  std::vector<Ctxt*> v;\n  for (long i = 0; i < array.size(); i++)\n    if (array.isSet(i) && !array[i]->isEmpty() &&\n        array[i]->bitCapacity() < belowLvl * (array[i]->getContext().BPL()))\n      v.push_back(array[i]);\n  packedRecrypt(CtPtrs_vectorPt(v), unpackConsts, ea);\n}\nvoid packedRecrypt(const CtPtrMat& m,\n                   const std::vector<zzX>& unpackConsts,\n                   const EncryptedArray& ea,\n                   long belowLvl)\n{\n  std::vector<Ctxt*> v;\n  for (long i = 0; i < m.size(); i++)\n    for (long j = 0; j < m[i].size(); j++)\n      if (m[i].isSet(j) && !m[i][j]->isEmpty() &&\n          m[i][j]->bitCapacity() < belowLvl * (m[i][j]->getContext().BPL()))\n        v.push_back(m[i][j]);\n  packedRecrypt(CtPtrs_vectorPt(v), unpackConsts, ea);\n}\n\n//===================== Thin Bootstrapping stuff ==================\n\nvoid ThinRecryptData::init(const Context& context,\n                           const NTL::Vec<long>& mvec_,\n                           bool alsoThick,\n                           bool build_cache_,\n                           bool minimal)\n{\n  RecryptData::init(context, mvec_, alsoThick, build_cache_, minimal);\n  coeffToSlot =\n      std::make_shared<ThinEvalMap>(*ea, minimal, mvec, true, build_cache);\n  slotToCoeff = std::make_shared<ThinEvalMap>(context.getEA(),\n                                              minimal,\n                                              mvec,\n                                              false,\n                                              build_cache);\n}\n\n// Extract digits from thinly packed slots\n\nlong fhe_force_chen_han = 0;\n\nvoid extractDigitsThin(Ctxt& ctxt, long botHigh, long r, long ePrime)\n{\n  HELIB_TIMER_START;\n\n  Ctxt unpacked(ctxt);\n  unpacked.cleanUp();\n\n  std::vector<Ctxt> scratch;\n\n  long p = ctxt.getContext().getP();\n  long p2r = NTL::power_long(p, r);\n  long topHigh = botHigh + r - 1;\n\n  // degree Chen/Han technique is p^{bot-1}(p-1)r\n  // degree of basic technique is p^{bot-1}p^r,\n  //     or p^{bot-1}p^{r-1} if p==2, r > 1, and bot+r > 2\n\n  bool use_chen_han = false;\n  if (r > 1) {\n    double chen_han_cost = log(p - 1) + log(r);\n    double basic_cost;\n    if (p == 2 && r > 2 && botHigh + r > 2)\n      basic_cost = (r - 1) * log(p);\n    else\n      basic_cost = r * log(p);\n\n    // std::cerr << \"*** basic: \" << basic_cost << \"\\n\";\n    // std::cerr << \"*** chen/han: \" << chen_han_cost << \"\\n\";\n\n    double thresh = 1.5;\n    if (p == 2)\n      thresh = 1.75;\n    // increasing thresh makes chen_han less likely to be chosen.\n    // For p == 2, the basic algorithm is just squaring,\n    // and so is a bit cheaper, so we raise thresh a bit.\n    // This is all a bit heuristic.\n\n    if (basic_cost > thresh * chen_han_cost)\n      use_chen_han = true;\n  }\n\n  if (fhe_force_chen_han > 0)\n    use_chen_han = true;\n  else if (fhe_force_chen_han < 0)\n    use_chen_han = false;\n\n  if (use_chen_han) {\n    // use Chen and Han technique\n\n    extendExtractDigits(scratch, unpacked, botHigh, r);\n\n#if 0\n    for (long i: range(scratch.size())) {\n      CheckCtxt(scratch[i], \"**\");\n    }\n#endif\n\n    for (long j = 0; j < botHigh; j++) {\n      unpacked -= scratch[j];\n      unpacked.divideByP();\n    }\n\n    if (p == 2 && botHigh > 0) // For p==2, subtract also the previous bit\n      unpacked += scratch[botHigh - 1];\n    unpacked.negate();\n\n    if (r > ePrime) { // Add in digits from the bottom part, if any\n      long topLow = r - 1 - ePrime;\n      Ctxt tmp = scratch[topLow];\n      for (long j = topLow - 1; j >= 0; --j) {\n        tmp.multByP();\n        tmp += scratch[j];\n      }\n      if (ePrime > 0)\n        tmp.multByP(ePrime); // multiply by p^e'\n      unpacked += tmp;\n    }\n    unpacked.reducePtxtSpace(p2r); // Our plaintext space is now mod p^r\n\n    ctxt = unpacked;\n  } else {\n\n    if (p == 2 && r > 2 && topHigh + 1 > 2)\n      topHigh--; // For p==2 we sometime get a bit for free\n\n    extractDigits(scratch, unpacked, topHigh + 1);\n\n    // set unpacked = -\\sum_{j=botHigh}^{topHigh} scratch[j] * p^{j-botHigh}\n    if (topHigh >= LONG(scratch.size())) {\n      topHigh = scratch.size() - 1;\n      std::cerr << \" @ suspect: not enough digits in extractDigitsPacked\\n\";\n    }\n\n    unpacked = scratch[topHigh];\n    for (long j = topHigh - 1; j >= botHigh; --j) {\n      unpacked.multByP();\n      unpacked += scratch[j];\n    }\n    if (p == 2 && botHigh > 0) // For p==2, subtract also the previous bit\n      unpacked += scratch[botHigh - 1];\n    unpacked.negate();\n\n    if (r > ePrime) { // Add in digits from the bottom part, if any\n      long topLow = r - 1 - ePrime;\n      Ctxt tmp = scratch[topLow];\n      for (long j = topLow - 1; j >= 0; --j) {\n        tmp.multByP();\n        tmp += scratch[j];\n      }\n      if (ePrime > 0)\n        tmp.multByP(ePrime); // multiply by p^e'\n      unpacked += tmp;\n    }\n    unpacked.reducePtxtSpace(p2r); // Our plaintext space is now mod p^r\n    ctxt = unpacked;\n  }\n}\n\n// Hack to get at private fields of public key\nstruct PubKeyHack\n{                         // The public key\n  const Context& context; // The context\n\n  //! @var Ctxt pubEncrKey\n  //! The public encryption key is an encryption of 0,\n  //! relative to the first secret key\n  Ctxt pubEncrKey;\n\n  std::vector<long> skHwts;            // The Hamming weight of the secret keys\n  std::vector<KeySwitch> keySwitching; // The key-switching matrices\n\n  // The keySwitchMap structure contains pointers to key-switching matrices\n  // for re-linearizing automorphisms. The entry keySwitchMap[i][n] contains\n  // the index j such that keySwitching[j] is the first matrix one needs to\n  // use when re-linearizing s_i(X^n).\n  std::vector<std::vector<long>> keySwitchMap;\n\n  NTL::Vec<int> KS_strategy; // NTL Vec's support I/O, which is\n                             // more convenient\n\n  // bootstrapping data\n\n  long recryptKeyID; // index of the bootstrapping key\n  Ctxt recryptEkey;  // the key itself, encrypted under key #0\n};\n\n// bootstrap a ciphertext to reduce noise\nvoid PubKey::thinReCrypt(Ctxt& ctxt) const\n{\n  HELIB_TIMER_START;\n\n  // Some sanity checks for dummy ciphertext\n  long ptxtSpace = ctxt.getPtxtSpace();\n  if (ctxt.isEmpty())\n    return;\n\n  if (ctxt.parts.size() == 1 && ctxt.parts[0].skHandle.isOne()) {\n    // Dummy encryption, just ensure that it is reduced mod p\n    NTL::ZZX poly = to_ZZX(ctxt.parts[0]);\n    for (long i = 0; i < poly.rep.length(); i++)\n      poly[i] = NTL::to_ZZ(rem(poly[i], ptxtSpace));\n    poly.normalize();\n    ctxt.DummyEncrypt(poly);\n    return;\n  }\n\n  // check that we have bootstrapping data\n  assertTrue(recryptKeyID >= 0l, \"Bootstrapping data not present\");\n\n  long p = ctxt.getContext().getP();\n  long r = ctxt.getContext().getAlMod().getR();\n  long p2r = ctxt.getContext().getAlMod().getPPowR();\n\n  long intFactor = ctxt.intFactor;\n\n  const ThinRecryptData& trcData = ctxt.getContext().getRcData();\n\n  // the bootstrapping key is encrypted relative to plaintext space p^{e-e'+r}.\n  long e = trcData.e;\n  long ePrime = trcData.ePrime;\n  long p2ePrime = NTL::power_long(p, ePrime);\n  long q = NTL::power_long(p, e) + 1;\n  assertTrue(e >= r, \"trcData.e must be at least alMod.r\");\n\n  // can only bootstrap ciphertext with plaintext-space dividing p^r\n  assertEq(p2r % ptxtSpace,\n           0l,\n           \"ptxtSpace must divide p^r when thin bootstrapping\");\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"init\");\n#endif\n\n  ctxt.dropSmallAndSpecialPrimes();\n\n#define DROP_BEFORE_THIN_RECRYPT\n#define THIN_RECRYPT_NLEVELS (3)\n#ifdef DROP_BEFORE_THIN_RECRYPT\n  // experimental code...we should drop down to a reasonably low level\n  // before doing the first linear map.\n  long first = context.getCtxtPrimes().first();\n  long last = std::min(context.getCtxtPrimes().last(),\n                       first + THIN_RECRYPT_NLEVELS - 1);\n  ctxt.bringToSet(IndexSet(first, last));\n#endif\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after mod down\");\n#endif\n\n  // Move the slots to powerful-basis coefficients\n  HELIB_NTIMER_START(AAA_slotToCoeff);\n  trcData.slotToCoeff->apply(ctxt);\n  HELIB_NTIMER_STOP(AAA_slotToCoeff);\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after slotToCoeff\");\n#endif\n\n  HELIB_NTIMER_START(AAA_bootKeySwitch);\n\n  // Make sure that this ciphertext is in canonical form\n  if (!ctxt.inCanonicalForm())\n    ctxt.reLinearize();\n\n  // Mod-switch down if needed\n  IndexSet s = ctxt.getPrimeSet() / context.getSpecialPrimes();\n  assertTrue(s <= context.getCtxtPrimes(), \"prime set is messed up\");\n  if (s.card() > 3) { // leave only first three ciphertext primes\n    long first = s.first();\n    IndexSet s3(first, first + 2);\n    s.retain(s3);\n  }\n  ctxt.modDownToSet(s);\n\n  // key-switch to the bootstrapping key\n  ctxt.reLinearize(recryptKeyID);\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after key switching\");\n#endif\n\n  // \"raw mod-switch\" to the bootstrapping mosulus q=p^e+1.\n  std::vector<NTL::ZZX> zzParts; // the mod-switched parts, in ZZX format\n\n  double mfac = ctxt.getContext().getZMStar().getNormBnd();\n  double noise_est = ctxt.rawModSwitch(zzParts, q) * mfac;\n  // noise_est is an upper bound on the L-infty norm of the scaled noise\n  // in the pwrfl basis\n  double noise_bnd =\n      HELIB_MIN_CAP_FRAC * p2r * ctxt.getContext().boundForRecryption();\n  // noise_bnd is the bound assumed in selecting the parameters\n  double noise_rat = noise_est / noise_bnd;\n\n  HELIB_STATS_UPDATE(\"raw-mod-switch-noise\", noise_rat);\n\n  if (noise_rat > 1) {\n    // TODO: Turn the following preprocessor logics into a warnOrThrow function\n    std::string message =\n        \"rawModSwitch scaled noise exceeds bound: \" + std::to_string(noise_rat);\n#ifdef HELIB_DEBUG\n    Warning(message);\n#else\n    throw LogicError(message);\n#endif\n  }\n\n  assertEq(zzParts.size(),\n           (std::size_t)2,\n           \"Exactly 2 parts required for mod-switching in thin bootstrapping\");\n\n#ifdef HELIB_DEBUG\n  if (dbgKey) {\n    checkRecryptBounds(zzParts, dbgKey->getRecryptKey(), ctxt.getContext(), q);\n  }\n#endif\n\n  std::vector<NTL::ZZX> v;\n  v.resize(2);\n\n  // Add multiples of q to make the zzParts divisible by p^{e'}\n  for (long i : range(2)) {\n    // make divisible by p^{e'}\n\n    newMakeDivisible(zzParts[i], p2ePrime, q, ctxt.getContext(), v[i]);\n  }\n\n#ifdef HELIB_DEBUG\n  if (dbgKey) {\n    checkRecryptBounds_v(v, dbgKey->getRecryptKey(), ctxt.getContext(), q);\n    checkCriticalValue(zzParts,\n                       dbgKey->getRecryptKey(),\n                       ctxt.getContext().getRcData(),\n                       q);\n  }\n#endif\n\n  for (long i : range(zzParts.size())) {\n    zzParts[i] /= p2ePrime; // divide by p^{e'}\n  }\n\n  // NOTE: here we lose the intFactor associated with ctxt.\n  // We will restore it below.\n  ctxt = recryptEkey;\n\n  ctxt.multByConstant(zzParts[1]);\n  ctxt.addConstant(zzParts[0]);\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after bootKeySwitch\");\n#endif\n\n  HELIB_NTIMER_STOP(AAA_bootKeySwitch);\n\n  // Move the powerful-basis coefficients to the plaintext slots\n  HELIB_NTIMER_START(AAA_coeffToSlot);\n  trcData.coeffToSlot->apply(ctxt);\n  HELIB_NTIMER_STOP(AAA_coeffToSlot);\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after coeffToSlot\");\n#endif\n\n  // Extract the digits e-e'+r-1,...,e-e' (from fully packed slots)\n  HELIB_NTIMER_START(AAA_extractDigitsThin);\n  extractDigitsThin(ctxt, e - ePrime, r, ePrime);\n  HELIB_NTIMER_STOP(AAA_extractDigitsThin);\n\n#ifdef HELIB_DEBUG\n  CheckCtxt(ctxt, \"after extractDigitsThin\");\n#endif\n\n  // restore intFactor\n  if (intFactor != 1)\n    ctxt.intFactor = NTL::MulMod(ctxt.intFactor, intFactor, ptxtSpace);\n}\n\n#ifdef HELIB_DEBUG\n\nstatic void checkCriticalValue(const std::vector<NTL::ZZX>& zzParts,\n                               const DoubleCRT& sKey,\n                               const RecryptData& rcData,\n                               long q)\n{\n  NTL::ZZX ptxt;\n  rawDecrypt(ptxt, zzParts, sKey); // no mod q\n\n  NTL::Vec<NTL::ZZ> powerful;\n  rcData.p2dConv->ZZXtoPowerful(powerful, ptxt);\n  NTL::xdouble max_pwrfl = NTL::conv<NTL::xdouble>(largestCoeff(powerful));\n  double critical_value = NTL::conv<double>((max_pwrfl / q) / q);\n\n  vecRed(powerful, powerful, q, false);\n  max_pwrfl = NTL::conv<NTL::xdouble>(largestCoeff(powerful));\n  critical_value += NTL::conv<double>(max_pwrfl / q);\n\n  HELIB_STATS_UPDATE(\"critical-value\", critical_value);\n\n  std::cerr << \"=== critical_value=\" << critical_value;\n  if (critical_value > 0.5)\n    std::cerr << \" BAD-BOUND\";\n\n  std::cerr << \"\\n\";\n}\n\nstatic void checkRecryptBounds(const std::vector<NTL::ZZX>& zzParts,\n                               const DoubleCRT& sKey,\n                               const Context& context,\n                               long q)\n{\n  const RecryptData& rcData = context.getRcData();\n  double coeff_bound = context.boundForRecryption();\n  long p2r = context.getAlMod().getPPowR();\n\n  NTL::ZZX ptxt;\n  rawDecrypt(ptxt, zzParts, sKey); // no mod q\n\n  NTL::Vec<NTL::ZZ> powerful;\n  rcData.p2dConv->ZZXtoPowerful(powerful, ptxt);\n  double max_pwrfl = NTL::conv<double>(largestCoeff(powerful));\n  double ratio = max_pwrfl / (2 * q * coeff_bound);\n\n  HELIB_STATS_UPDATE(\"|x|/bound\", ratio);\n\n  std::cerr << \"=== |x|/bound=\" << ratio;\n  if (ratio > 1.0)\n    std::cerr << \" BAD-BOUND\";\n\n  vecRed(powerful, powerful, q, false);\n  max_pwrfl = NTL::conv<double>(largestCoeff(powerful));\n  ratio = max_pwrfl / (2 * p2r * coeff_bound);\n\n  HELIB_STATS_UPDATE(\"|x%q|/bound\", ratio);\n\n  std::cerr << \", (|x%q|)/bound=\" << ratio;\n  if (ratio > 1.0)\n    std::cerr << \" BAD-BOUND\";\n\n  std::cerr << \"\\n\";\n}\n\nstatic void checkRecryptBounds_v(const std::vector<NTL::ZZX>& v,\n                                 const DoubleCRT& sKey,\n                                 const Context& context,\n                                 UNUSED long q)\n{\n  const RecryptData& rcData = context.getRcData();\n\n  long p = context.getP();\n  long e = rcData.e;\n  long p2e = NTL::power_long(p, e);\n  long ePrime = rcData.ePrime;\n  long p2ePrime = NTL::power_long(p, ePrime);\n  long phim = context.getPhiM();\n\n  double fudge = compute_fudge(p2ePrime, p2e);\n\n  double coeff_bound = context.boundForRecryption() * fudge;\n\n  double sigma = context.stdDevForRecryption() * fudge;\n\n  NTL::ZZX ptxt;\n  rawDecrypt(ptxt, v, sKey); // no mod q\n\n  NTL::Vec<NTL::ZZ> powerful;\n  rcData.p2dConv->ZZXtoPowerful(powerful, ptxt);\n  double max_pwrfl = NTL::conv<double>(largestCoeff(powerful));\n\n  double denom = p2ePrime * coeff_bound;\n  double ratio = max_pwrfl / denom;\n\n  HELIB_STATS_UPDATE(\"|v|/bound\", ratio);\n\n  std::cerr << \"=== |v|/bound=\" << ratio;\n  if (ratio > 1.0)\n    std::cerr << \" BAD-BOUND\";\n  std::cerr << \"\\n\";\n\n  ptxt -= v[0]; // so now ptxt is just sKey * v[1]\n  rcData.p2dConv->ZZXtoPowerful(powerful, ptxt);\n\n  assertEq(powerful.length(), phim, \"length should be phim\");\n\n  double ran_pwrfl = NTL::conv<double>(powerful[NTL::RandomBnd(phim)]);\n  // pick a random coefficient in the poweful basis\n\n  double std_devs = fabs(ran_pwrfl) / (p2ePrime * sigma);\n  // number of standard deviations away from mean\n\n  // update various indicator variables\n  HELIB_STATS_UPDATE(\"sigma_0_5\", double(std_devs <= 0.5)); // 0.383\n  HELIB_STATS_UPDATE(\"sigma_1_0\", double(std_devs <= 1.0)); // 0.683\n  HELIB_STATS_UPDATE(\"sigma_1_5\", double(std_devs <= 1.5)); // 0.866\n  HELIB_STATS_UPDATE(\"sigma_2_0\", double(std_devs <= 2.0)); // 0.954\n  HELIB_STATS_UPDATE(\"sigma_2_5\", double(std_devs <= 2.5)); // 0.988\n  HELIB_STATS_UPDATE(\"sigma_3_0\", double(std_devs <= 3.0)); // 0.997, 1 in 370\n  HELIB_STATS_UPDATE(\"sigma_3_5\",\n                     double(std_devs <= 3.5)); // 0.999535, 1 in 2149\n  HELIB_STATS_UPDATE(\"sigma_4_0\",\n                     double(std_devs <= 4.0)); // 0.999937, 1 in 15787\n\n  // compute sample variance, and scale by the variance we expect\n  HELIB_STATS_UPDATE(\"sigma_calc\",\n                     fsquare(ran_pwrfl) / fsquare(p2ePrime * sigma));\n\n  // save the scaled value for application of other tests\n  HELIB_STATS_SAVE(\"v_values\", ran_pwrfl / (p2ePrime * sigma));\n}\n\n#endif\n\n#if 0\nvoid fhe_stats_print(long iter, const Context& context)\n{\n   long phim = context.getPhiM();\n\n   std::cerr << \"||||| recryption stats ||||\\n\";\n   std::cerr << \"**** averages ****\\n\";\n   std::cerr << \"=== critical_value=\" << (fhe_stats_cv_sum/iter) << \"\\n\";\n   std::cerr << \"=== |x|/bound=\" << (fhe_stats_x_sum/iter) << \"\\n\";\n   std::cerr << \"=== |x%q|/bound=\" << (fhe_stats_xmod_sum/iter) << \"\\n\";\n   std::cerr << \"=== |u|/bound=\" << (fhe_stats_u_sum/iter) << \"\\n\";\n   std::cerr << \"=== |v|/bound=\" << (fhe_stats_v_sum/iter) << \"\\n\";\n   std::cerr << \"**** maxima ****\\n\";\n   std::cerr << \"=== critical_value=\" << (fhe_stats_cv_max) << \"\\n\";\n   std::cerr << \"=== |x|/bound=\" << (fhe_stats_x_max) << \"\\n\";\n   std::cerr << \"=== |x%q|/bound=\" << (fhe_stats_xmod_max) << \"\\n\";\n   std::cerr << \"=== |u|/bound=\" << (fhe_stats_u_max) << \"\\n\";\n   std::cerr << \"=== |v|/bound=\" << (fhe_stats_v_max) << \"\\n\";\n   std::cerr << \"**** theoretical bounds ***\\n\";\n   std::cerr << \"=== single-max=\" << (sqrt(2.0*log(phim))/context.scale) << \"\\n\";\n   std::cerr << \"=== global-max=\" << (sqrt(2.0*(log(iter)+log(phim)))/context.scale) << \"\\n\";\n\n\n}\n#endif\n\n} // namespace helib\n", "meta": {"hexsha": "0215fba3c8faad2299ce2b2e3cf524d7e1c9394f", "size": 39814, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/recryption.cpp", "max_stars_repo_name": "msh086/HElib", "max_stars_repo_head_hexsha": "7b919ce4ff22a04f1fb394d875172b91ae2c4c11", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-04-29T16:10:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-29T16:11:10.000Z", "max_issues_repo_path": "src/recryption.cpp", "max_issues_repo_name": "maliasadi/HElib", "max_issues_repo_head_hexsha": "7b919ce4ff22a04f1fb394d875172b91ae2c4c11", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/recryption.cpp", "max_forks_repo_name": "maliasadi/HElib", "max_forks_repo_head_hexsha": "7b919ce4ff22a04f1fb394d875172b91ae2c4c11", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8396591789, "max_line_length": 93, "alphanum_fraction": 0.6046616768, "num_tokens": 11619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632979641571, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21501087096214241}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\n// Copyright (c) 2014-2015 Adam Wulkiewicz, Lodz, Poland.\n\n// This file was modified by Oracle on 2014, 2015.\n// Modifications copyright (c) 2014-2015 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_EQUALS_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_EQUALS_HPP\n\n\n#include <cstddef>\n#include <vector>\n\n#include <boost/range.hpp>\n\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/static_visitor.hpp>\n#include <boost/variant/variant_fwd.hpp>\n\n#include <boost/geometry/core/access.hpp>\n#include <boost/geometry/core/coordinate_dimension.hpp>\n#include <boost/geometry/core/geometry_id.hpp>\n#include <boost/geometry/core/reverse_dispatch.hpp>\n#include <boost/geometry/core/tags.hpp>\n\n#include <boost/geometry/geometries/concepts/check.hpp>\n\n#include <boost/geometry/algorithms/detail/equals/point_point.hpp>\n#include <boost/geometry/algorithms/detail/not.hpp>\n#include <boost/geometry/algorithms/not_implemented.hpp>\n\n// For trivial checks\n#include <boost/geometry/algorithms/area.hpp>\n#include <boost/geometry/algorithms/length.hpp>\n#include <boost/geometry/util/math.hpp>\n#include <boost/geometry/util/select_coordinate_type.hpp>\n#include <boost/geometry/util/select_most_precise.hpp>\n\n#include <boost/geometry/algorithms/detail/equals/collect_vectors.hpp>\n#include <boost/geometry/algorithms/relate.hpp>\n#include <boost/geometry/algorithms/detail/relate/relate_impl.hpp>\n\n#include <boost/geometry/views/detail/indexed_point_view.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace equals\n{\n\n\ntemplate\n<\n    std::size_t Dimension,\n    std::size_t DimensionCount\n>\nstruct box_box\n{\n    template <typename Box1, typename Box2>\n    static inline bool apply(Box1 const& box1, Box2 const& box2)\n    {\n        if (!geometry::math::equals(get<min_corner, Dimension>(box1), get<min_corner, Dimension>(box2))\n            || !geometry::math::equals(get<max_corner, Dimension>(box1), get<max_corner, Dimension>(box2)))\n        {\n            return false;\n        }\n        return box_box<Dimension + 1, DimensionCount>::apply(box1, box2);\n    }\n};\n\ntemplate <std::size_t DimensionCount>\nstruct box_box<DimensionCount, DimensionCount>\n{\n    template <typename Box1, typename Box2>\n    static inline bool apply(Box1 const& , Box2 const& )\n    {\n        return true;\n    }\n};\n\n\nstruct segment_segment\n{\n    template <typename Segment1, typename Segment2>\n    static inline bool apply(Segment1 const& segment1, Segment2 const& segment2)\n    {\n        return equals::equals_point_point(\n                    indexed_point_view<Segment1 const, 0>(segment1),\n                    indexed_point_view<Segment2 const, 0>(segment2) )\n                ? equals::equals_point_point(\n                    indexed_point_view<Segment1 const, 1>(segment1),\n                    indexed_point_view<Segment2 const, 1>(segment2) )\n                : ( equals::equals_point_point(\n                        indexed_point_view<Segment1 const, 0>(segment1),\n                        indexed_point_view<Segment2 const, 1>(segment2) )\n                 && equals::equals_point_point(\n                        indexed_point_view<Segment1 const, 1>(segment1),\n                        indexed_point_view<Segment2 const, 0>(segment2) )\n                  );\n    }\n};\n\n\nstruct area_check\n{\n    template <typename Geometry1, typename Geometry2>\n    static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2)\n    {\n        return geometry::math::equals(\n                geometry::area(geometry1),\n                geometry::area(geometry2));\n    }\n};\n\n\nstruct length_check\n{\n    template <typename Geometry1, typename Geometry2>\n    static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2)\n    {\n        return geometry::math::equals(\n                geometry::length(geometry1),\n                geometry::length(geometry2));\n    }\n};\n\n\ntemplate <typename TrivialCheck>\nstruct equals_by_collection\n{\n    template <typename Geometry1, typename Geometry2>\n    static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2)\n    {\n        if (! TrivialCheck::apply(geometry1, geometry2))\n        {\n            return false;\n        }\n\n        typedef typename geometry::select_most_precise\n            <\n                typename select_coordinate_type\n                    <\n                        Geometry1, Geometry2\n                    >::type,\n                double\n            >::type calculation_type;\n\n        typedef std::vector<collected_vector<calculation_type> > v;\n        v c1, c2;\n\n        geometry::collect_vectors(c1, geometry1);\n        geometry::collect_vectors(c2, geometry2);\n\n        if (boost::size(c1) != boost::size(c2))\n        {\n            return false;\n        }\n\n        std::sort(c1.begin(), c1.end());\n        std::sort(c2.begin(), c2.end());\n\n        // Just check if these vectors are equal.\n        return std::equal(c1.begin(), c1.end(), c2.begin());\n    }\n};\n\ntemplate<typename Geometry1, typename Geometry2>\nstruct equals_by_relate\n    : detail::relate::relate_impl\n        <\n            detail::de9im::static_mask_equals_type,\n            Geometry1,\n            Geometry2\n        >\n{};\n\n}} // namespace detail::equals\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\ntemplate\n<\n    typename Geometry1,\n    typename Geometry2,\n    typename Tag1 = typename tag<Geometry1>::type,\n    typename Tag2 = typename tag<Geometry2>::type,\n    std::size_t DimensionCount = dimension<Geometry1>::type::value,\n    bool Reverse = reverse_dispatch<Geometry1, Geometry2>::type::value\n>\nstruct equals: not_implemented<Tag1, Tag2>\n{};\n\n\n// If reversal is needed, perform it\ntemplate\n<\n    typename Geometry1, typename Geometry2,\n    typename Tag1, typename Tag2,\n    std::size_t DimensionCount\n>\nstruct equals<Geometry1, Geometry2, Tag1, Tag2, DimensionCount, true>\n    : equals<Geometry2, Geometry1, Tag2, Tag1, DimensionCount, false>\n{\n    static inline bool apply(Geometry1 const& g1, Geometry2 const& g2)\n    {\n        return equals\n            <\n                Geometry2, Geometry1,\n                Tag2, Tag1,\n                DimensionCount,\n                false\n            >::apply(g2, g1);\n    }\n};\n\n\ntemplate <typename P1, typename P2, std::size_t DimensionCount, bool Reverse>\nstruct equals<P1, P2, point_tag, point_tag, DimensionCount, Reverse>\n    : geometry::detail::not_\n        <\n            detail::disjoint::point_point<P1, P2, 0, DimensionCount>\n        >\n{};\n\n\ntemplate <typename Box1, typename Box2, std::size_t DimensionCount, bool Reverse>\nstruct equals<Box1, Box2, box_tag, box_tag, DimensionCount, Reverse>\n    : detail::equals::box_box<0, DimensionCount>\n{};\n\n\ntemplate <typename Ring1, typename Ring2, bool Reverse>\nstruct equals<Ring1, Ring2, ring_tag, ring_tag, 2, Reverse>\n    : detail::equals::equals_by_collection<detail::equals::area_check>\n{};\n\n\ntemplate <typename Polygon1, typename Polygon2, bool Reverse>\nstruct equals<Polygon1, Polygon2, polygon_tag, polygon_tag, 2, Reverse>\n    : detail::equals::equals_by_collection<detail::equals::area_check>\n{};\n\n\ntemplate <typename Polygon, typename Ring, bool Reverse>\nstruct equals<Polygon, Ring, polygon_tag, ring_tag, 2, Reverse>\n    : detail::equals::equals_by_collection<detail::equals::area_check>\n{};\n\n\ntemplate <typename Ring, typename Box, bool Reverse>\nstruct equals<Ring, Box, ring_tag, box_tag, 2, Reverse>\n    : detail::equals::equals_by_collection<detail::equals::area_check>\n{};\n\n\ntemplate <typename Polygon, typename Box, bool Reverse>\nstruct equals<Polygon, Box, polygon_tag, box_tag, 2, Reverse>\n    : detail::equals::equals_by_collection<detail::equals::area_check>\n{};\n\ntemplate <typename Segment1, typename Segment2, std::size_t DimensionCount, bool Reverse>\nstruct equals<Segment1, Segment2, segment_tag, segment_tag, DimensionCount, Reverse>\n    : detail::equals::segment_segment\n{};\n\ntemplate <typename LineString1, typename LineString2, bool Reverse>\nstruct equals<LineString1, LineString2, linestring_tag, linestring_tag, 2, Reverse>\n    //: detail::equals::equals_by_collection<detail::equals::length_check>\n    : detail::equals::equals_by_relate<LineString1, LineString2>\n{};\n\ntemplate <typename LineString, typename MultiLineString, bool Reverse>\nstruct equals<LineString, MultiLineString, linestring_tag, multi_linestring_tag, 2, Reverse>\n    : detail::equals::equals_by_relate<LineString, MultiLineString>\n{};\n\ntemplate <typename MultiLineString1, typename MultiLineString2, bool Reverse>\nstruct equals<MultiLineString1, MultiLineString2, multi_linestring_tag, multi_linestring_tag, 2, Reverse>\n    : detail::equals::equals_by_relate<MultiLineString1, MultiLineString2>\n{};\n\n\ntemplate <typename MultiPolygon1, typename MultiPolygon2, bool Reverse>\nstruct equals\n    <\n        MultiPolygon1, MultiPolygon2,\n        multi_polygon_tag, multi_polygon_tag,\n        2,\n        Reverse\n    >\n    : detail::equals::equals_by_collection<detail::equals::area_check>\n{};\n\n\ntemplate <typename Polygon, typename MultiPolygon, bool Reverse>\nstruct equals\n    <\n        Polygon, MultiPolygon,\n        polygon_tag, multi_polygon_tag,\n        2,\n        Reverse\n    >\n    : detail::equals::equals_by_collection<detail::equals::area_check>\n{};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_variant {\n\ntemplate <typename Geometry1, typename Geometry2>\nstruct equals\n{\n    static inline bool apply(Geometry1 const& geometry1,\n                             Geometry2 const& geometry2)\n    {\n        concept::check_concepts_and_equal_dimensions\n        <\n            Geometry1 const,\n            Geometry2 const\n        >();\n\n        return dispatch::equals<Geometry1, Geometry2>\n                       ::apply(geometry1, geometry2);\n    }\n};\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T), typename Geometry2>\nstruct equals<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2>\n{\n    struct visitor: static_visitor<bool>\n    {\n        Geometry2 const& m_geometry2;\n\n        visitor(Geometry2 const& geometry2)\n            : m_geometry2(geometry2)\n        {}\n\n        template <typename Geometry1>\n        inline bool operator()(Geometry1 const& geometry1) const\n        {\n            return equals<Geometry1, Geometry2>\n                   ::apply(geometry1, m_geometry2);\n        }\n\n    };\n\n    static inline bool apply(\n        boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry1,\n        Geometry2 const& geometry2\n    )\n    {\n        return boost::apply_visitor(visitor(geometry2), geometry1);\n    }\n};\n\ntemplate <typename Geometry1, BOOST_VARIANT_ENUM_PARAMS(typename T)>\nstruct equals<Geometry1, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >\n{\n    struct visitor: static_visitor<bool>\n    {\n        Geometry1 const& m_geometry1;\n\n        visitor(Geometry1 const& geometry1)\n            : m_geometry1(geometry1)\n        {}\n\n        template <typename Geometry2>\n        inline bool operator()(Geometry2 const& geometry2) const\n        {\n            return equals<Geometry1, Geometry2>\n                   ::apply(m_geometry1, geometry2);\n        }\n\n    };\n\n    static inline bool apply(\n        Geometry1 const& geometry1,\n        boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry2\n    )\n    {\n        return boost::apply_visitor(visitor(geometry1), geometry2);\n    }\n};\n\ntemplate <\n    BOOST_VARIANT_ENUM_PARAMS(typename T1),\n    BOOST_VARIANT_ENUM_PARAMS(typename T2)\n>\nstruct equals<\n    boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)>,\n    boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)>\n>\n{\n    struct visitor: static_visitor<bool>\n    {\n        template <typename Geometry1, typename Geometry2>\n        inline bool operator()(Geometry1 const& geometry1,\n                               Geometry2 const& geometry2) const\n        {\n            return equals<Geometry1, Geometry2>\n                   ::apply(geometry1, geometry2);\n        }\n\n    };\n\n    static inline bool apply(\n        boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)> const& geometry1,\n        boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)> const& geometry2\n    )\n    {\n        return boost::apply_visitor(visitor(), geometry1, geometry2);\n    }\n};\n\n} // namespace resolve_variant\n\n\n/*!\n\\brief \\brief_check{are spatially equal}\n\\details \\details_check12{equals, is spatially equal}. Spatially equal means\n    that the same point set is included. A box can therefore be spatially equal\n    to a ring or a polygon, or a linestring can be spatially equal to a\n    multi-linestring or a segment. This only works theoretically, not all\n    combinations are implemented yet.\n\\ingroup equals\n\\tparam Geometry1 \\tparam_geometry\n\\tparam Geometry2 \\tparam_geometry\n\\param geometry1 \\param_geometry\n\\param geometry2 \\param_geometry\n\\return \\return_check2{are spatially equal}\n\n\\qbk{[include reference/algorithms/equals.qbk]}\n\n */\ntemplate <typename Geometry1, typename Geometry2>\ninline bool equals(Geometry1 const& geometry1, Geometry2 const& geometry2)\n{\n    return resolve_variant::equals<Geometry1, Geometry2>\n                          ::apply(geometry1, geometry2);\n}\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_EQUALS_HPP\n\n", "meta": {"hexsha": "0f0bdde5848654ea4ba0c0cc411229ba35ed77a0", "size": 13914, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clm/src/main/clm/jni/boost/armv7a/include/boost/geometry/algorithms/equals.hpp", "max_stars_repo_name": "BruceNUAA/gaze-detection-android-app", "max_stars_repo_head_hexsha": "5daa2c8a0e51eb506fe435a6f8d03758162d0579", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "libs/boost/include/boost/geometry/algorithms/equals.hpp", "max_issues_repo_name": "dnevera/ofxiOSBoost", "max_issues_repo_head_hexsha": "aae717bf8c5229f644057a17ccc971abf1c68bc3", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2019-07-06T02:51:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T11:48:33.000Z", "max_forks_repo_path": "libs/boost/include/boost/geometry/algorithms/equals.hpp", "max_forks_repo_name": "dnevera/ofxiOSBoost", "max_forks_repo_head_hexsha": "aae717bf8c5229f644057a17ccc971abf1c68bc3", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 275.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T08:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:06:07.000Z", "avg_line_length": 29.5414012739, "max_line_length": 107, "alphanum_fraction": 0.6840592209, "num_tokens": 3250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.21501086510363995}}
{"text": "#include <Python.h>\n#include <numpy/arrayobject.h>\n#include <Eigen/Dense>\n\n#include \"george.h\"\n\n#if PY_MAJOR_VERSION >= 3\n#define PyInt_AsLong PyLong_AsLong\n#endif\n\nusing namespace george;\n\nusing george::HODLRSolver;\n\n// Eigen is column major and numpy is row major. Barf.\ntypedef Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,\n                          Eigen::RowMajor> > RowMajorMap;\n\n#define PARSE_ARRAY(o) (PyArrayObject*) PyArray_FROM_OTF(o, NPY_DOUBLE, \\\n        NPY_IN_ARRAY)\n\nextern \"C\" {\n\n// Type definition.\ntypedef struct {\n\n    PyObject_HEAD\n    kernels::Kernel* kernel;\n    HODLRSolver<kernels::Kernel>* solver;\n\n} _george_object;\n\n// Allocation/deallocation.\nstatic void _george_dealloc (_george_object* self);\nstatic PyObject* _george_new (PyTypeObject* type, PyObject* args, PyObject* kwds);\nstatic int _george_init (_george_object* self, PyObject* args, PyObject* kwds);\n\n// Methods.\nstatic PyObject* _george_compute (_george_object* self, PyObject* args);\nstatic PyObject* _george_lnlikelihood (_george_object* self, PyObject* args);\nstatic PyObject* _george_computed (_george_object* self, PyObject* args);\nstatic PyObject* _george_predict (_george_object* self, PyObject* args);\nstatic PyObject* _george_get_matrix (_george_object* self, PyObject* args);\n\n// Python 3.\n\n#if PY_MAJOR_VERSION >= 3\n\nPyObject *PyInit__george (void);\nstatic int _george_traverse(PyObject* m, visitproc visit, void* arg);\nstatic int _george_clear(PyObject* m);\n\n#else\n\nvoid init_george (void);\n\n#endif\n\n}\n\nstatic void _george_dealloc (_george_object* self)\n{\n    if (self->kernel != NULL) delete self->kernel;\n    if (self->solver != NULL) delete self->solver;\n    Py_TYPE(self)->tp_free((PyObject*)self);\n}\n\nstatic PyObject *_george_new (PyTypeObject* type, PyObject* args, PyObject* kwds)\n{\n    _george_object* self = (_george_object*)type->tp_alloc(type, 0);\n    self->kernel = NULL;\n    self->solver = NULL;\n    return (PyObject*)self;\n}\n\nkernels::Kernel* parse_kernel (PyObject* kernel)\n{\n    // Check the kernel.\n    if (!PyObject_HasAttrString(kernel, \"is_kernel\")) {\n        PyErr_SetString(PyExc_TypeError, \"Invalid kernel\");\n        return NULL;\n    }\n\n    // Deal with operators.\n    PyObject* is_kernel_obj = PyObject_GetAttrString(kernel, \"is_kernel\");\n    if (is_kernel_obj == Py_False) {\n        Py_DECREF(is_kernel_obj);\n\n        // Get the Python kernel objects and the type of operator.\n        PyObject* k1 = PyObject_GetAttrString(kernel, \"k1\"),\n                * k2 = PyObject_GetAttrString(kernel, \"k2\"),\n                * otype_obj = PyObject_GetAttrString(kernel, \"operator_type\");\n        long otype = PyInt_AsLong(otype_obj);\n        Py_XDECREF(otype_obj);\n\n        // Validate the kernels.\n        if (k1 == NULL || k2 == NULL || PyErr_Occurred() != NULL) {\n            PyErr_SetString(PyExc_TypeError, \"Invalid operator\");\n            Py_XDECREF(k1);\n            Py_XDECREF(k2);\n            return NULL;\n        }\n\n        // Parse the combined kernels.\n        kernels::Kernel* kernel1 = parse_kernel(k1);\n        kernels::Kernel* kernel2 = parse_kernel(k2);\n        Py_DECREF(k1);\n        Py_DECREF(k2);\n\n        // Check that these were successfully parsed.\n        if (kernel1 == NULL || kernel2 == NULL) {\n            if (kernel1 != NULL) delete kernel1;\n            if (kernel2 != NULL) delete kernel2;\n            return NULL;\n        }\n\n        // Combine the kernels.\n        if (otype == 0)\n            return new kernels::Sum (kernel1, kernel2);\n        else if (otype == 1)\n            return new kernels::Product (kernel1, kernel2);\n\n        // If we get here then the operator type was unknown.\n        if (kernel1 != NULL) delete kernel1;\n        if (kernel2 != NULL) delete kernel2;\n        PyErr_SetString(PyExc_TypeError, \"Unknown operator\");\n        return NULL;\n    }\n\n    // If we get here then the object claims to be a kernel.\n    Py_DECREF(is_kernel_obj);\n\n    // Get the kernel type.\n    PyObject* ktype_obj = PyObject_GetAttrString(kernel, \"kernel_type\");\n    long ktype = PyInt_AsLong(ktype_obj);\n    Py_XDECREF(ktype_obj);\n    if (PyErr_Occurred() != NULL) {\n        PyErr_SetString(PyExc_TypeError, \"Invalid kernel type\");\n        return NULL;\n    }\n\n    // Get the number of dimensions.\n    PyObject* ndim_obj = PyObject_GetAttrString(kernel, \"ndim\");\n    long ndim = PyInt_AsLong(ndim_obj);\n    Py_XDECREF(ndim_obj);\n    if (PyErr_Occurred() != NULL) {\n        PyErr_SetString(PyExc_TypeError,\n                        \"Couldn't parse number of kernel dimensions\");\n        return NULL;\n    }\n\n    // Get the parameter vector.\n    PyObject* pars_obj = PyObject_GetAttrString(kernel, \"pars\");\n    PyArrayObject* pars_array = PARSE_ARRAY(pars_obj);\n    Py_XDECREF(pars_obj);\n    if (pars_array == NULL) {\n        PyErr_SetString(PyExc_ValueError, \"Invalid parameter vector\");\n        Py_XDECREF(pars_array);\n        return NULL;\n    }\n\n    // Get the number of parameters and a pointer to the parameter data.\n    int npars = PyArray_DIM(pars_array, 0);\n    double* pars = (double*)PyArray_DATA(pars_array);\n\n    // Build the kernel.\n    kernels::Kernel* k = NULL;\n\n#define GEORGE_DEFINE_KERNEL(N,NAME) { \\\n    if (npars != N) { \\\n        PyErr_SetString(PyExc_ValueError, \"The NAME requires N parameters.\"); \\\n        Py_DECREF(pars_array); \\\n        return NULL; \\\n    } \\\n    k = new kernels::NAME(ndim, pars); \\\n}\n\n    if (ktype == 0)      GEORGE_DEFINE_KERNEL (1, ConstantKernel)\n    else if (ktype == 1) GEORGE_DEFINE_KERNEL (0, DotProductKernel)\n    else if (ktype == 2) GEORGE_DEFINE_KERNEL ((ndim*ndim+ndim)/2, ExpKernel)\n    else if (ktype == 3) GEORGE_DEFINE_KERNEL ((ndim*ndim+ndim)/2, RBFKernel)\n    else if (ktype == 4) GEORGE_DEFINE_KERNEL (1, CosineKernel)\n    else if (ktype == 5) GEORGE_DEFINE_KERNEL (2, ExpSine2Kernel)\n    else if (ktype == 6) GEORGE_DEFINE_KERNEL ((ndim*ndim+ndim)/2, Matern32Kernel)\n    else if (ktype == 7) GEORGE_DEFINE_KERNEL ((ndim*ndim+ndim)/2, Matern52Kernel)\n    else if (ktype == 8) GEORGE_DEFINE_KERNEL (1, WhiteKernel)\n    else if (ktype == 9) GEORGE_DEFINE_KERNEL (1+(ndim*ndim+ndim)/2, RationalQuadraticKernel)\n    else PyErr_SetString(PyExc_TypeError, \"Unknown kernel\");\n\n#undef GEORGE_DEFINE_KERNEL\n\n    Py_DECREF(pars_array);\n    return k;\n}\n\nstatic int _george_init(_george_object* self, PyObject* args, PyObject* kwds)\n{\n    int nleaf;\n    double tol;\n    PyObject* kernel = NULL;\n    if (!PyArg_ParseTuple(args, \"Oid\", &kernel, &nleaf, &tol))\n        return -1;\n\n    // Parse the kernel.\n    self->kernel = parse_kernel (kernel);\n    if (self->kernel == NULL) return -2;\n\n    // Set up the solver.\n    self->solver = new HODLRSolver<kernels::Kernel> (self->kernel, nleaf, tol);\n\n    return 0;\n}\n\nstatic PyObject* _george_compute (_george_object* self, PyObject* args)\n{\n    int seed;\n    PyObject* x_obj, * yerr_obj;\n\n    // Parse the input arguments.\n    if (!PyArg_ParseTuple(args, \"OOi\", &x_obj, &yerr_obj, &seed))\n        return NULL;\n\n    // Decode the numpy arrays.\n    PyArrayObject * x_array = PARSE_ARRAY(x_obj),\n                  * yerr_array = PARSE_ARRAY(yerr_obj);\n    if (x_array == NULL || yerr_array == NULL) {\n        Py_XDECREF(x_array);\n        Py_XDECREF(yerr_array);\n        PyErr_SetString(PyExc_ValueError,\n            \"Failed to parse input objects as numpy arrays\");\n        return NULL;\n    }\n\n    // Get the dimensions.\n    int nsamples = (int)PyArray_DIM(x_array, 0),\n        ndim = (int)PyArray_DIM(x_array, 1);\n    if ((int)PyArray_NDIM(x_array) != 2 ||\n            (int)PyArray_DIM(yerr_array, 0) != nsamples) {\n        Py_DECREF(x_array);\n        Py_DECREF(yerr_array);\n        PyErr_SetString(PyExc_ValueError, \"Dimension mismatch\");\n        return NULL;\n    }\n\n    // Access the data.\n    double * x = (double*)PyArray_DATA(x_array),\n           * yerr = (double*)PyArray_DATA(yerr_array);\n\n    // Map to vectors.\n    MatrixXd x_vec = RowMajorMap(x, nsamples, ndim);\n    VectorXd yerr_vec = VectorXd::Map(yerr, nsamples);\n\n    // Pre-compute the factorization.\n    int info = self->solver->compute (x_vec, yerr_vec, seed);\n\n    // Clean up.\n    Py_DECREF(x_array);\n    Py_DECREF(yerr_array);\n\n    // Check success.\n    if (info != george::SOLVER_OK) {\n        PyErr_SetString(PyExc_RuntimeError, \"Failed to compute model\");\n        return NULL;\n    }\n\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic PyObject* _george_lnlikelihood (_george_object* self, PyObject* args)\n{\n    PyObject *y_obj;\n    if (!PyArg_ParseTuple(args, \"O\", &y_obj)) return NULL;\n\n    if (!self->solver->get_computed()) {\n        PyErr_SetString(PyExc_RuntimeError,\n            \"You need to compute the model first\");\n        return NULL;\n    }\n\n    PyArrayObject *y_array = PARSE_ARRAY(y_obj);\n    if (y_array == NULL) {\n        Py_XDECREF(y_array);\n        PyErr_SetString(PyExc_ValueError,\n            \"Failed to parse input object as a numpy array\");\n        return NULL;\n    }\n\n    // Get the data.\n    int nsamples = (int)PyArray_DIM(y_array, 0);\n    double* y = (double*)PyArray_DATA(y_array);\n    VectorXd y_vec = VectorXd::Map(y, nsamples);\n\n    // Compute the likelihood.\n    double lnlike = self->solver->log_likelihood(y_vec);\n    Py_DECREF(y_array);\n\n    // Check success.\n    if (self->solver->get_status() != george::SOLVER_OK) {\n        PyErr_SetString(PyExc_RuntimeError, \"Failed to compute likelihood\");\n        return NULL;\n    }\n\n    return Py_BuildValue(\"d\", lnlike);\n}\n\nstatic PyObject* _george_predict (_george_object* self, PyObject* args)\n{\n    PyObject* y_obj, * x_obj;\n    if (!PyArg_ParseTuple(args, \"OO\", &y_obj, &x_obj)) return NULL;\n\n    if (!self->solver->get_computed()) {\n        PyErr_SetString(PyExc_RuntimeError,\n            \"You need to compute the model first\");\n        return NULL;\n    }\n\n    PyArrayObject *y_array = PARSE_ARRAY(y_obj),\n                  *x_array = PARSE_ARRAY(x_obj);\n    if (y_array == NULL || x_array == NULL) {\n        Py_XDECREF(y_array);\n        Py_XDECREF(x_array);\n        PyErr_SetString(PyExc_ValueError,\n            \"Failed to parse input objects as numpy arrays\");\n        return NULL;\n    }\n\n    // Get the dimensions.\n    int nsamples = (int)PyArray_DIM(y_array, 0),\n        ntest = (int)PyArray_DIM(x_array, 0),\n        ndim = (int)PyArray_DIM(x_array, 1);\n    if ((int)PyArray_NDIM(x_array) != 2 ||\n            self->solver->get_dimension() != nsamples) {\n        Py_DECREF(x_array);\n        Py_DECREF(y_array);\n        PyErr_SetString(PyExc_ValueError, \"Dimension mismatch\");\n        return NULL;\n    }\n\n    // Access the data.\n    double* y = (double*) PyArray_DATA(y_array),\n          * x = (double*) PyArray_DATA(x_array);\n\n    // Compute the mean.\n    VectorXd y_vec = VectorXd::Map(y, nsamples),\n             mu_vec;\n    MatrixXd x_vec = RowMajorMap(x, ntest, ndim);\n    MatrixXd cov_mat;\n    self->solver->predict(y_vec, x_vec, mu_vec, cov_mat);\n\n    // Clean up.\n    Py_DECREF(y_array);\n    Py_DECREF(x_array);\n\n    // Check success.\n    if (self->solver->get_status() != george::SOLVER_OK) {\n        PyErr_SetString(PyExc_RuntimeError, \"Failed to compute model\");\n        return NULL;\n    }\n\n    // Allocate the output arrays.\n    npy_intp dim[] = {ntest}, dim2[] = {ntest, ntest};\n    PyArrayObject* mu_array = (PyArrayObject*)PyArray_SimpleNew(1, dim, NPY_DOUBLE),\n                 * cov_array = (PyArrayObject*)PyArray_SimpleNew(2, dim2, NPY_DOUBLE);\n    if (mu_array == NULL || cov_array == NULL) {\n        Py_XDECREF(mu_array);\n        Py_XDECREF(cov_array);\n        return NULL;\n    }\n\n    // Copy over the result.\n    double *mu = (double*)PyArray_DATA(mu_array),\n           *cov = (double*)PyArray_DATA(cov_array);\n    for (int i = 0; i < ntest; ++i) {\n        mu[i] = mu_vec[i];\n        for (int j = 0; j < ntest; ++j) cov[i*ntest+j] = cov_mat(i, j);\n    }\n\n    // Build the result.\n    PyObject *ret = Py_BuildValue(\"OO\", mu_array, cov_array);\n    Py_DECREF(mu_array);\n    Py_DECREF(cov_array);\n\n    if (ret == NULL) {\n        PyErr_SetString(PyExc_RuntimeError, \"Couldn't build output tuple\");\n        Py_XDECREF(ret);\n        return NULL;\n    }\n\n    return ret;\n}\n\nstatic PyObject* _george_get_matrix (_george_object* self, PyObject* args)\n{\n    PyObject* t_obj;\n    if (!PyArg_ParseTuple(args, \"O\", &t_obj)) return NULL;\n\n    PyArrayObject* t_array = PARSE_ARRAY(t_obj);\n    if (t_array == NULL) {\n        Py_XDECREF(t_array);\n        PyErr_SetString(PyExc_ValueError,\n            \"Failed to parse input object as numpy array\");\n        return NULL;\n    }\n\n    // Check the shape of the input array.\n    if ((int)PyArray_NDIM(t_array) != 2) {\n        Py_DECREF(t_array);\n        PyErr_SetString(PyExc_ValueError, \"Dimension mismatch\");\n        return NULL;\n    }\n\n    // Get the dimensions of the problem.\n    int n = (int)PyArray_DIM(t_array, 0),\n        ndim = (int)PyArray_DIM(t_array, 1);\n\n    // Access the data.\n    double* t = (double*) PyArray_DATA(t_array);\n    MatrixXd tm = RowMajorMap(t, n, ndim);\n\n    // Allocate the output arrays.\n    npy_intp dim[] = {n, n};\n    PyArrayObject* out_array = (PyArrayObject*)PyArray_SimpleNew(2, dim, NPY_DOUBLE);\n    if (out_array == NULL) {\n        Py_DECREF(t_array);\n        Py_XDECREF(out_array);\n        return NULL;\n    }\n\n    // Copy over the result.\n    double* matrix = (double*)PyArray_DATA(out_array), value;\n    kernels::Kernel* kernel = self->kernel;\n    for (int i = 0; i < n; ++i) {\n        matrix[i*n+i] = kernel->evaluate(tm.row(i), tm.row(i));\n        for (int j = 0; j < i; ++j) {\n            value = kernel->evaluate(tm.row(i), tm.row(j));\n            matrix[i*n+j] = value;\n            matrix[j*n+i] = value;\n        }\n    }\n\n    Py_DECREF(t_array);\n    return (PyObject*)out_array;\n}\n\nstatic PyObject* _george_computed(_george_object* self, PyObject* args)\n{\n    if (self->solver->get_computed()) Py_RETURN_TRUE;\n    Py_RETURN_FALSE;\n}\n\nstatic PyMethodDef _george_methods[] = {\n    {\"compute\",\n     (PyCFunction)_george_compute,\n     METH_VARARGS,\n     \"Fit the GP.\"},\n    {\"lnlikelihood\",\n     (PyCFunction)_george_lnlikelihood,\n     METH_VARARGS,\n     \"Get the marginalized ln likelihood of some values.\"\n    },\n    {\"predict\",\n     (PyCFunction)_george_predict,\n     METH_VARARGS,\n     \"Predict the mean function\"\n    },\n    {\"get_matrix\",\n     (PyCFunction)_george_get_matrix,\n     METH_VARARGS,\n     \"Get the covariance matrix for a set of times.\"\n    },\n    {\"computed\",\n     (PyCFunction)_george_computed,\n     METH_NOARGS,\n     \"Has the GP been computed?\"\n    },\n    {NULL}  /* Sentinel */\n};\n\nstatic char _george_doc[] = \"This is the ``_george`` object. \"\n                            \"There is some black magic.\";\nstatic PyTypeObject _george_type = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    \"_george._george\",           /*tp_name*/\n    sizeof(_george_object),      /*tp_basicsize*/\n    0,                           /*tp_itemsize*/\n    (destructor)_george_dealloc, /*tp_dealloc*/\n    0,                           /*tp_print*/\n    0,                           /*tp_getattr*/\n    0,                           /*tp_setattr*/\n    0,                           /*tp_compare*/\n    0,                           /*tp_repr*/\n    0,                           /*tp_as_number*/\n    0,                           /*tp_as_sequence*/\n    0,                           /*tp_as_mapping*/\n    0,                           /*tp_hash */\n    0,                           /*tp_call*/\n    0,                           /*tp_str*/\n    0,                           /*tp_getattro*/\n    0,                           /*tp_setattro*/\n    0,                           /*tp_as_buffer*/\n    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,\n                                 /*tp_flags*/\n    _george_doc,                 /* tp_doc */\n    0,                           /* tp_traverse */\n    0,                           /* tp_clear */\n    0,                           /* tp_richcompare */\n    0,                           /* tp_weaklistoffset */\n    0,                           /* tp_iter */\n    0,                           /* tp_iternext */\n    _george_methods,             /* tp_methods */\n    0,                           /* tp_members */\n    0,                           /* tp_getset */\n    0,                           /* tp_base */\n    0,                           /* tp_dict */\n    0,                           /* tp_descr_get */\n    0,                           /* tp_descr_set */\n    0,                           /* tp_dictoffset */\n    (initproc)_george_init,      /* tp_init */\n    0,                           /* tp_alloc */\n    _george_new,                 /* tp_new */\n};\n\n\n//\n// Initialize the module.\n//\n\nstatic char module_doc[] = \"GP Module\";\n\n#if PY_MAJOR_VERSION >= 3\n\nstruct george_state {\n    PyObject *error;\n};\n#define GETSTATE(m) ((struct george_state*)PyModule_GetState(m))\n\nstatic int _george_traverse(PyObject* m, visitproc visit, void* arg) {\n    Py_VISIT(GETSTATE(m)->error);\n    return 0;\n}\n\nstatic int _george_clear(PyObject* m) {\n    Py_CLEAR(GETSTATE(m)->error);\n    return 0;\n}\n\nextern \"C\" {\nstatic struct PyModuleDef moduledef = {\n    PyModuleDef_HEAD_INIT,\n    \"_george\",\n    module_doc,\n    sizeof(struct george_state),\n    _george_methods,\n    NULL,\n    _george_traverse,\n    _george_clear,\n    NULL\n};\n}\n\n#define INITERROR return NULL\n\nPyObject *PyInit__george (void)\n\n#else\n#define INITERROR return\n\nvoid init_george (void)\n\n#endif\n{\n    PyObject *m;\n    if (PyType_Ready(&_george_type) < 0) INITERROR;\n\n#if PY_MAJOR_VERSION >= 3\n    m = PyModule_Create(&moduledef);\n#else\n    m = Py_InitModule3(\"_george\", _george_methods, module_doc);\n#endif\n\n    if (m == NULL) INITERROR;\n\n    // Add the _george type.\n    Py_INCREF(&_george_type);\n    PyModule_AddObject(m, \"_george\", (PyObject *)&_george_type);\n\n    // Numpy.\n    import_array();\n\n#if PY_MAJOR_VERSION >= 3\n    return m;\n#endif\n}\n", "meta": {"hexsha": "e80afbcc651c43bd8047a35576f19c86255ccfb6", "size": 17787, "ext": "cc", "lang": "C++", "max_stars_repo_path": "george/_george.cc", "max_stars_repo_name": "kastnerkyle/george", "max_stars_repo_head_hexsha": "8c33a837e8922be142bf7adbe80726dc611c9b25", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-24T02:30:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-24T02:30:22.000Z", "max_issues_repo_path": "george/_george.cc", "max_issues_repo_name": "kastnerkyle/george", "max_issues_repo_head_hexsha": "8c33a837e8922be142bf7adbe80726dc611c9b25", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "george/_george.cc", "max_forks_repo_name": "kastnerkyle/george", "max_forks_repo_head_hexsha": "8c33a837e8922be142bf7adbe80726dc611c9b25", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.8941176471, "max_line_length": 93, "alphanum_fraction": 0.6017878226, "num_tokens": 4659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3960681662740416, "lm_q1q2_score": 0.21501086510363993}}
{"text": "#pragma once\n#include <Eigen/Core>\n#include <Eigen/Sparse>\n#include <algorithm>\n#include <atomic>\n#include <cstddef>\n#include <cstdint>\n#include <future>\n#include <iostream>\n#include <random>\n#include <stdexcept>\n#include <thread>\n#include <tuple>\n#include <vector>\n\n#include \"argcheck.hpp\"\n\nnamespace irspack {\nnamespace sparse_util {\n\ntemplate <typename Real>\nusing CSRMatrix = Eigen::SparseMatrix<Real, Eigen::RowMajor>;\n\ntemplate <typename Real>\nusing RowMajorMatrix =\n    Eigen::Matrix<Real, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;\n\ntemplate <typename Real>\nusing ColMajorMatrix =\n    Eigen::Matrix<Real, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;\n\ntemplate <typename Real>\nusing DenseVector = Eigen::Matrix<Real, Eigen::Dynamic, 1>;\n\ntemplate <typename Real>\nusing DenseColVector = Eigen::Matrix<Real, 1, Eigen::Dynamic, Eigen::RowMajor>;\n\ntemplate <typename Real>\nusing CSCMatrix = Eigen::SparseMatrix<Real, Eigen::ColMajor>;\n\ntemplate <typename Real>\ninline RowMajorMatrix<Real>\nparallel_sparse_product(const CSRMatrix<Real> &left,\n                        const CSCMatrix<Real> &right, const size_t n_threads) {\n  RowMajorMatrix<Real> result(left.rows(), right.cols());\n  result.array() = 0;\n  check_arg(n_threads > 0, \"n_thraed must be > 0\");\n  const int64_t n_row = left.rows();\n  std::atomic<int64_t> cursor(0);\n  std::vector<std::thread> workers;\n  for (int i = 0; i < static_cast<int>(n_threads); i++) {\n    workers.emplace_back([&left, &right, &cursor, n_row, &result]() {\n      const int64_t chunk_size = 16;\n      while (true) {\n        auto current_position = cursor.fetch_add(chunk_size);\n        if (current_position >= n_row) {\n          break;\n        }\n        auto block_size =\n            std::min(current_position + chunk_size, n_row) - current_position;\n        result.middleRows(current_position, block_size) +=\n            left.middleRows(current_position, block_size) * right;\n      }\n    });\n  }\n  for (auto &worker : workers) {\n    worker.join();\n  }\n  return result;\n}\n\ntemplate <typename Real, class Derived, typename Integer = int64_t>\nstruct SplitFunction {\n  template <typename... Args>\n  static std::pair<CSRMatrix<Real>, CSRMatrix<Real>>\n  split_imple(const CSRMatrix<Real> &X, std::int64_t random_seed,\n              Args... args) {\n    Derived::check_args(args...);\n    using Triplet = Eigen::Triplet<Integer>;\n    std::mt19937 random_state(random_seed);\n    std::vector<Integer> col_buffer;\n    std::vector<Real> data_buffer;\n    std::vector<uint64_t> index_;\n    std::vector<Triplet> train_data, test_data;\n    for (int row = 0; row < X.outerSize(); ++row) {\n      col_buffer.clear(); // does not change capacity\n      data_buffer.clear();\n      index_.clear();\n      Integer cnt = 0;\n      for (typename CSRMatrix<Real>::InnerIterator it(X, row); it; ++it) {\n        index_.push_back(cnt);\n        col_buffer.push_back(it.col());\n        data_buffer.push_back(it.value());\n        cnt += 1;\n      }\n      std::shuffle(index_.begin(), index_.end(), random_state);\n      size_t n_test = Derived::get_n_test(cnt, args...);\n      for (size_t i = 0; i < n_test; i++) {\n        test_data.emplace_back(row, col_buffer[index_[i]],\n                               data_buffer[index_[i]]);\n      }\n      for (size_t i = n_test; i < col_buffer.size(); i++) {\n        train_data.emplace_back(row, col_buffer[index_[i]],\n                                data_buffer[index_[i]]);\n      }\n    }\n    CSRMatrix<Real> X_train(X.rows(), X.cols()), X_test(X.rows(), X.cols());\n    auto dupfunction = [](const Integer &a, const Integer &b) { return a + b; };\n    X_train.setFromTriplets(train_data.begin(), train_data.end(), dupfunction);\n    X_test.setFromTriplets(test_data.begin(), test_data.end(), dupfunction);\n    X_train.makeCompressed();\n    X_test.makeCompressed();\n    return {X_train, X_test};\n  }\n};\n\ntemplate <typename Real, typename Integer = int64_t>\nstruct SplitByRatioFunction\n    : SplitFunction<Real, SplitByRatioFunction<Real, Integer>, Integer> {\n  using Base =\n      SplitFunction<Real, SplitByRatioFunction<Real, Integer>, Integer>;\n  static void check_args(double test_ratio, bool n_test_ceil) {\n    check_arg(((test_ratio <= 1.0 && (test_ratio >= 0.0))),\n              \"test_ratio must be within [0.0, 1.0]\");\n  }\n\n  static size_t get_n_test(size_t nnz_row, double test_ratio,\n                           bool n_test_ceil) {\n    if (n_test_ceil) {\n      return std::ceil(nnz_row * test_ratio);\n    } else {\n      return std::floor(nnz_row * test_ratio);\n    }\n  };\n\n  static std::pair<CSRMatrix<Real>, CSRMatrix<Real>>\n  split(const CSRMatrix<Real> &X, std::int64_t random_seed, Real heldout_ratio,\n        bool n_test_ceil) {\n    return Base::split_imple(X, random_seed, heldout_ratio, n_test_ceil);\n  }\n};\n\ntemplate <typename Real, typename Integer = int64_t>\nstruct SplitFixedN : SplitFunction<Real, SplitFixedN<Real, Integer>, Integer> {\n  using Base = SplitFunction<Real, SplitFixedN<Real, Integer>, Integer>;\n  static void check_args(size_t n_held_out) {}\n\n  static size_t get_n_test(size_t nnz_row, size_t n_held_out) {\n    return std::min(nnz_row, n_held_out);\n  };\n\n  static std::pair<CSRMatrix<Real>, CSRMatrix<Real>>\n  split(const CSRMatrix<Real> &X, std::int64_t random_seed, size_t n_held_out) {\n    return Base::split_imple(X, random_seed, n_held_out);\n  }\n};\n\ntemplate <typename Real>\nCSRMatrix<Real> okapi_BM_25_weight(const CSRMatrix<Real> &X, Real k1, Real b) {\n  CSRMatrix<Real> result(X);\n  using itertype = typename CSRMatrix<Real>::InnerIterator;\n  const int N = X.rows();\n  result.makeCompressed();\n  DenseVector<Real> idf(X.cols());\n  DenseVector<Real> doc_length(N);\n  idf.array() = 0;\n  doc_length.array() = 0;\n\n  for (int i = 0; i < N; i++) {\n    for (itertype iter(X, i); iter; ++iter) {\n      idf(iter.col()) += 1;\n      doc_length(i) += iter.value();\n    }\n  }\n  Real avgdl = doc_length.sum() / N;\n  idf.array() =\n      (N / (idf.array() + static_cast<Real>(1)) + static_cast<Real>(1)).log();\n  for (int i = 0; i < N; i++) {\n    Real regularizer = k1 * (1 - b + b * doc_length(i) / avgdl);\n    for (itertype iter(result, i); iter; ++iter) {\n      iter.valueRef() = idf(iter.col()) * (iter.valueRef() * (k1 + 1)) /\n                        (iter.valueRef() + regularizer);\n    }\n  }\n  return result;\n}\n\ntemplate <typename Real>\nCSRMatrix<Real> tf_idf_weight(const CSRMatrix<Real> &X, bool smooth) {\n  CSRMatrix<Real> result(X);\n  using itertype = typename CSRMatrix<Real>::InnerIterator;\n  const int N = X.rows();\n  result.makeCompressed();\n  DenseVector<Real> idf(X.cols());\n  idf.array() = 0;\n\n  for (int i = 0; i < N; i++) {\n    for (itertype iter(X, i); iter; ++iter) {\n      idf(iter.col()) += 1;\n    }\n  }\n  idf.array() = (N / (idf.array() + static_cast<Real>(smooth))).log();\n  for (int i = 0; i < N; i++) {\n    for (itertype iter(result, i); iter; ++iter) {\n      iter.valueRef() *= idf(iter.col());\n    }\n  }\n  return result;\n}\n\ntemplate <typename Real>\nCSRMatrix<Real> remove_diagonal(const CSRMatrix<Real> &X) {\n  check_arg(X.rows() == X.cols(), \"X must be square\");\n  CSRMatrix<Real> result(X);\n  using itertype = typename CSRMatrix<Real>::InnerIterator;\n  const int N = X.rows();\n  result.makeCompressed();\n  for (int i = 0; i < N; i++) {\n    for (itertype iter(result, i); iter; ++iter) {\n      if (i == iter.col()) {\n        iter.valueRef() = static_cast<Real>(0);\n      }\n    }\n  }\n  return result;\n}\n\ntemplate <typename Real, bool positive_only = false,\n          int block_size = Eigen::internal::packet_traits<Real>::size>\ninline CSCMatrix<Real> SLIM(const CSRMatrix<Real> &X, size_t n_threads,\n                            size_t n_iter, Real l2_coeff, Real l1_coeff,\n                            Real tol, int64_t top_k) {\n  check_arg(n_threads > 0, \"n_threads must be > 0.\");\n  check_arg(n_iter > 0, \"n_iter must be > 0.\");\n  check_arg(l2_coeff >= 0, \"l2_coeff must be > 0.\");\n  check_arg(l1_coeff >= 0, \"l1_coeff must be > 0.\");\n  using MatrixType =\n      Eigen::Matrix<Real, block_size, Eigen::Dynamic, Eigen::ColMajor>;\n  using VectorType = Eigen::Matrix<Real, block_size, 1>;\n\n  CSCMatrix<Real> X_csc(X);\n  X_csc.makeCompressed();\n  using TripletType = Eigen::Triplet<Real>;\n  using CSCIter = typename CSCMatrix<Real>::InnerIterator;\n  using RealAndIndex = std::pair<Real, int64_t>;\n  std::vector<std::future<std::vector<TripletType>>> workers;\n  std::atomic<int64_t> cursor(0);\n  for (size_t th = 0; th < n_threads; th++) {\n    workers.emplace_back(std::async(std::launch::async, [&cursor, &X_csc,\n                                                         l2_coeff, l1_coeff,\n                                                         n_iter, tol, top_k] {\n      const int64_t F = X_csc.cols();\n      std::mt19937 gen(0);\n      std::vector<int64_t> indices(F);\n      for (int64_t i = 0; i < F; i++) {\n        indices[i] = i;\n      }\n      MatrixType remnants(block_size, X_csc.rows());\n      MatrixType coeffs(block_size, F);\n      VectorType coeff_temp(block_size);\n      VectorType diff(block_size);\n      VectorType linear(block_size);\n      VectorType linear_plus(block_size);\n      VectorType linear_minus(block_size);\n\n      std::vector<RealAndIndex> argsort_buffer;\n      if (top_k >= 0) {\n        argsort_buffer.resize(F);\n      }\n\n      std::vector<TripletType> local_results;\n      while (true) {\n        int64_t current_cursor = cursor.fetch_add(block_size);\n        if (current_cursor >= F) {\n          break;\n        }\n\n        int64_t block_begin = current_cursor;\n        int64_t block_end = std::min(block_begin + block_size, F);\n        int64_t valid_block_size = block_end - block_begin;\n        remnants.setZero();\n        coeffs.setZero();\n\n        for (int64_t f_cursor = block_begin; f_cursor < block_end; f_cursor++) {\n          const int64_t internal_col_position = f_cursor - block_begin;\n          for (CSCIter iter(X_csc, f_cursor); iter; ++iter) {\n            remnants(internal_col_position, iter.row()) = -iter.value();\n          }\n        }\n\n        for (size_t cd_iteration = 0; cd_iteration < n_iter; cd_iteration++) {\n          std::shuffle(indices.begin(), indices.end(), gen);\n          Real delta = 0;\n          for (int64_t feature_index = 0; feature_index < F; feature_index++) {\n            int64_t shuffled_feature_index = indices[feature_index];\n            coeff_temp = coeffs.col(shuffled_feature_index);\n            diff = coeff_temp;\n            linear.setZero();\n            Real x2_sum = 0.0;\n            for (CSCIter nnz_iter(X_csc, shuffled_feature_index); nnz_iter;\n                 ++nnz_iter) {\n              Real x = nnz_iter.value();\n              x2_sum += x * x;\n              linear.noalias() += x * remnants.col(nnz_iter.row());\n            }\n            linear.noalias() -= x2_sum * coeff_temp;\n\n            Real quadratic = x2_sum + l2_coeff;\n            linear_plus.array() = (-linear.array() - l1_coeff) / quadratic;\n            if (!positive_only) {\n              linear_minus.array() = (-linear.array() + l1_coeff) / quadratic;\n            }\n\n            Real *ptr_location =\n                coeffs.data() + shuffled_feature_index * block_size;\n            Real *lp_ptr = linear_plus.data();\n            Real *lm_ptr = linear_minus.data();\n\n            for (int64_t inner_cursor_position = 0;\n                 inner_cursor_position < block_size; inner_cursor_position++) {\n              Real lplus = *(lp_ptr++);\n              Real lminus = *(lm_ptr++);\n              int64_t original_cursor_position =\n                  inner_cursor_position + block_begin;\n              if (original_cursor_position == shuffled_feature_index) {\n                *(ptr_location++) = 0.0;\n                continue;\n              }\n              if (positive_only) {\n                if (lplus > 0) {\n                  *(ptr_location++) = lplus;\n                } else {\n                  *(ptr_location++) = static_cast<Real>(0.0);\n                }\n\n              } else {\n                if (lplus > 0) {\n                  *(ptr_location++) = lplus;\n                } else {\n                  if (lminus < 0) {\n                    *(ptr_location++) = lminus;\n                  } else {\n                    *(ptr_location++) = static_cast<Real>(0.0);\n                  }\n                }\n              } // allow nagative block\n            }\n            coeff_temp.noalias() =\n                coeffs.col(shuffled_feature_index) - coeff_temp;\n\n            if (!coeff_temp.isZero()) {\n              for (CSCIter nnz_iter(X_csc, shuffled_feature_index); nnz_iter;\n                   ++nnz_iter) {\n                const int64_t row = nnz_iter.row();\n                remnants.col(row).noalias() += nnz_iter.valueRef() * coeff_temp;\n              }\n              delta = std::max(delta, coeff_temp.cwiseAbs().array().maxCoeff());\n            }\n          }\n          if (delta < tol) {\n            break;\n          }\n        }\n\n        if (top_k < 0) {\n          for (int64_t f = 0; f < F; f++) {\n            for (int64_t inner_cursor_position = 0;\n                 inner_cursor_position < valid_block_size;\n                 inner_cursor_position++) {\n              int64_t original_location = inner_cursor_position + block_begin;\n              Real c = coeffs(inner_cursor_position, f);\n              if (c != 0.0) {\n                local_results.emplace_back(f, original_location, c);\n              }\n            }\n          }\n        } else {\n          for (int64_t inner_cursor_position = 0;\n               inner_cursor_position < valid_block_size;\n               inner_cursor_position++) {\n            int64_t original_location = inner_cursor_position + block_begin;\n            auto iter = argsort_buffer.begin();\n            int64_t nnz = 0;\n            for (int64_t f = 0; f < F; f++) {\n              Real c = coeffs(inner_cursor_position, f);\n              if (c != 0.0) {\n                iter->first = c;\n                iter->second = f;\n                iter++;\n                nnz++;\n              }\n            }\n            int64_t n_taken_coeffs = nnz;\n            if (nnz > top_k) {\n              std::sort(argsort_buffer.begin(), argsort_buffer.end(),\n                        [](RealAndIndex &val1, RealAndIndex &val2) {\n                          return val1.first > val2.first;\n                        });\n              n_taken_coeffs = top_k;\n            }\n            for (int64_t i = 0; i < n_taken_coeffs; i++) {\n              local_results.emplace_back(argsort_buffer[i].second,\n                                         original_location,\n                                         argsort_buffer[i].first);\n            }\n          }\n        }\n      }\n      return local_results;\n    }));\n  }\n  std::vector<TripletType> nnzs;\n  for (auto &fres : workers) {\n    auto result = fres.get();\n    for (const auto &w : result) {\n      nnzs.emplace_back(w);\n    }\n  }\n\n  CSCMatrix<Real> result(X.cols(), X.cols());\n  result.setFromTriplets(nnzs.begin(), nnzs.end());\n  result.makeCompressed();\n  return result;\n}\n\ntemplate <typename Real>\ninline std::vector<std::vector<std::pair<int64_t, float>>>\nretrieve_recommend_from_score(\n    const RowMajorMatrix<Real> &score,\n    const std::vector<std::vector<int64_t>> &allowed_indices,\n    const size_t cutoff, size_t n_threads) {\n  using score_and_index = std::pair<int64_t, float>;\n  check_arg(n_threads > 0, \"n_threads must not be 0.\");\n  check_arg(\n      (score.rows() == static_cast<int64_t>(allowed_indices.size())) ||\n          allowed_indices.empty(),\n      \"allowed_indices, if not empty, must have a size equal to X.rows()\");\n  std::vector<std::vector<score_and_index>> result(score.rows());\n  std::vector<std::future<void>> workers;\n  std::atomic<size_t> cursor(0);\n  const size_t n_users = static_cast<size_t>(score.rows());\n  for (size_t thread = 0; thread < std::min(n_threads, n_users); thread++) {\n    workers.emplace_back(\n        std::async([&score, cutoff, &allowed_indices, &cursor, &result]() {\n          const int64_t n_rows = score.rows();\n          const int64_t n_items = score.cols();\n          std::vector<score_and_index> index_holder;\n          index_holder.reserve(n_items);\n\n          while (true) {\n            int64_t current = cursor.fetch_add(1);\n            if (current >= n_rows) {\n              break;\n            }\n\n            std::vector<score_and_index> inserted;\n            const Real *score_ptr = score.data() + n_items * current;\n\n            index_holder.clear();\n            if (!allowed_indices.empty()) {\n              for (auto item_index : allowed_indices.at(current)) {\n                if ((item_index < n_items) && (item_index >= 0)) {\n                  index_holder.emplace_back(item_index, score_ptr[item_index]);\n                }\n              }\n            } else {\n              for (int64_t i = 0; i < n_items; i++) {\n                index_holder.emplace_back(i, *(score_ptr++));\n              }\n            }\n            std::partial_sort(\n                index_holder.begin(),\n                index_holder.begin() + std::min(cutoff, index_holder.size()),\n                index_holder.end(), [](score_and_index i1, score_and_index i2) {\n                  return i1.second > i2.second;\n                });\n\n            size_t items_recommended = 0;\n            for (auto item_index : index_holder) {\n              if (items_recommended >= cutoff) {\n                break;\n              }\n\n              if (item_index.second == -std::numeric_limits<Real>::infinity()) {\n                break;\n              }\n              result[current].emplace_back(item_index);\n              items_recommended++;\n            }\n          }\n        }));\n  }\n  workers.clear();\n  return result;\n}\n\n} // namespace sparse_util\n} // namespace irspack\n", "meta": {"hexsha": "ba9fb8fe4ae1d33d069655b0f848f9843528a180", "size": 17701, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp_source/util.hpp", "max_stars_repo_name": "Random1992/irspack", "max_stars_repo_head_hexsha": "c49b05841318049c72a4b09c3edefdd90bc314d6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-12-23T08:08:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:48:55.000Z", "max_issues_repo_path": "cpp_source/util.hpp", "max_issues_repo_name": "Random1992/irspack", "max_issues_repo_head_hexsha": "c49b05841318049c72a4b09c3edefdd90bc314d6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 38.0, "max_issues_repo_issues_event_min_datetime": "2021-01-03T12:29:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T12:58:05.000Z", "max_forks_repo_path": "cpp_source/util.hpp", "max_forks_repo_name": "Random1992/irspack", "max_forks_repo_head_hexsha": "c49b05841318049c72a4b09c3edefdd90bc314d6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-12-24T10:23:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T12:53:20.000Z", "avg_line_length": 35.4729458918, "max_line_length": 80, "alphanum_fraction": 0.5764646065, "num_tokens": 4325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353744, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21490684071289795}}
{"text": "/**\n * @file environment.hpp\n * @author Licheng Wen (wenlc@zju.edu.cn)\n * @brief Environment class header\n * @date 2020-11-12\n *\n * @copyright Copyright (c) 2020\n *\n */\n\n#pragma once\n#include <ompl/base/State.h>\n#include <ompl/base/spaces/DubinsStateSpace.h>\n#include <ompl/base/spaces/ReedsSheppStateSpace.h>\n#include <ompl/base/spaces/SE2StateSpace.h>\n\n#include <boost/functional/hash.hpp>\n#include <boost/geometry.hpp>\n#include <boost/geometry/algorithms/intersection.hpp>\n#include <boost/geometry/geometries/linestring.hpp>\n#include <boost/geometry/geometries/point_xy.hpp>\n#include <boost/heap/fibonacci_heap.hpp>\n#include <unordered_map>\n#include <unordered_set>\n\n#include \"neighbor.hpp\"\n#include \"planresult.hpp\"\n\nnamespace Constants {\n// [m] --- The minimum turning radius of the vehicle\nstatic float r = 3;\nstatic float deltat = 6.75 * 6 / 180.0 * M_PI;\n// [#] --- A movement cost penalty for turning (choosing non straight motion\n// primitives)\nstatic float penaltyTurning = 1.5;\n// [#] --- A movement cost penalty for reversing (choosing motion primitives >\n// 2)\nstatic float penaltyReversing = 2.0;\n// [#] --- A movement cost penalty for change of direction (changing from\n// primitives < 3 to primitives > 2)\nstatic float penaltyCOD = 2.0;\n// map resolution\nstatic float mapResolution = 2.0;\n// change to set calcIndex resolution\nstatic float xyResolution = r * deltat;\nstatic float yawResolution = deltat;\n\n// width of car\nstatic float carWidth = 2.0;\n// distance from rear to vehicle front end\nstatic float LF = 2.0;\n// distance from rear to vehicle back end\nstatic float LB = 1.0;\n// obstacle default radius\nstatic float obsRadius = 1;\n// least time to wait for constraint\nstatic int constraintWaitTime = 2;\n\n// R = 3, 6.75 DEG\nstd::vector<double> dyaw = {0, deltat, -deltat, 0, -deltat, deltat};\nstd::vector<double> dx = {r * deltat, r *sin(deltat),  r *sin(deltat),\n                          -r *deltat, -r *sin(deltat), -r *sin(deltat)};\nstd::vector<double> dy = {0, -r *(1 - cos(deltat)), r *(1 - cos(deltat)),\n                          0, -r *(1 - cos(deltat)), r *(1 - cos(deltat))};\n\nstatic inline float normalizeHeadingRad(float t) {\n  if (t < 0) {\n    t = t - 2.f * M_PI * (int)(t / (2.f * M_PI));\n    return 2.f * M_PI + t;\n  }\n\n  return t - 2.f * M_PI * (int)(t / (2.f * M_PI));\n}\n}  // namespace Constants\n\nnamespace libMultiRobotPlanning {\n\nusing libMultiRobotPlanning::Neighbor;\nusing libMultiRobotPlanning::PlanResult;\nusing namespace libMultiRobotPlanning;\ntypedef ompl::base::SE2StateSpace::StateType OmplState;\ntypedef boost::geometry::model::d2::point_xy<double> Point;\ntypedef boost::geometry::model::segment<Point> Segment;\n/**\n * @brief  Environment class\n *\n * @tparam Location\n * @tparam State\n * @tparam Action\n * @tparam Cost\n * @tparam Conflict\n * @tparam Constraint\n * @tparam Constraints\n */\ntemplate <typename Location, typename State, typename Action, typename Cost,\n          typename Conflict, typename Constraint, typename Constraints>\nclass Environment {\n public:\n  Environment(size_t maxx, size_t maxy, std::unordered_set<Location> obstacles,\n              std::multimap<int, State> dynamic_obstacles,\n              std::vector<State> goals)\n      : m_obstacles(std::move(obstacles)),\n        m_dynamic_obstacles(std::move(dynamic_obstacles)),\n        m_agentIdx(0),\n        m_constraints(nullptr),\n        m_lastGoalConstraint(-1),\n        m_highLevelExpanded(0),\n        m_lowLevelExpanded(0) {\n    m_dimx = (int)maxx / Constants::mapResolution;\n    m_dimy = (int)maxy / Constants::mapResolution;\n    // std::cout << \"env build \" << m_dimx << \" \" << m_dimy << \" \"\n    //           << m_obstacles.size() << std::endl;\n    holonomic_cost_maps = std::vector<std::vector<std::vector<double>>>(\n        goals.size(), std::vector<std::vector<double>>(\n                          m_dimx, std::vector<double>(m_dimy, 0)));\n    m_goals.clear();\n    for (const auto &g : goals) {\n      if (g.x < 0 || g.x > maxx || g.y < 0 || g.y > maxy) {\n        std::cout << \"\\033[1m\\033[31m Goal out of boundary, Fail to build \"\n                     \"environment \\033[0m\\n\";\n        return;\n      }\n      m_goals.emplace_back(\n          State(g.x, g.y, Constants::normalizeHeadingRad(g.yaw)));\n    }\n    updateCostmap();\n  }\n\n  Environment(const Environment &) = delete;\n  Environment &operator=(const Environment &) = delete;\n\n  /// High Level Environment functions\n  bool getFirstConflict(\n      const std::vector<PlanResult<State, Action, double>> &solution,\n      Conflict &result) {\n    int max_t = 0;\n    for (const auto &sol : solution) {\n      max_t = std::max<int>(max_t, sol.states.size() - 1);\n    }\n    for (int t = 0; t < max_t; ++t) {\n      // check drive-drive collisions\n      for (size_t i = 0; i < solution.size(); ++i) {\n        State state1 = getState(i, solution, t);\n        for (size_t j = i + 1; j < solution.size(); ++j) {\n          State state2 = getState(j, solution, t);\n          if (state1.agentCollision(state2)) {\n            result.time = t;\n            result.agent1 = i;\n            result.agent2 = j;\n            result.s1 = state1;\n            result.s2 = state2;\n            return true;\n          }\n        }\n      }\n    }\n    return false;\n  }\n\n  void createConstraintsFromConflict(\n      const Conflict &conflict, std::map<size_t, Constraints> &constraints) {\n    Constraints c1;\n    c1.constraints.emplace(\n        Constraint(conflict.time, conflict.s2, conflict.agent2));\n    constraints[conflict.agent1] = c1;\n    Constraints c2;\n    c2.constraints.emplace(\n        Constraint(conflict.time, conflict.s1, conflict.agent1));\n    constraints[conflict.agent2] = c2;\n  }\n\n  void onExpandHighLevelNode(int /*cost*/) {\n    m_highLevelExpanded++;\n    if (m_highLevelExpanded % 50 == 0)\n      std::cout << \"Now expand \" << m_highLevelExpanded\n                << \" high level nodes.\\n\";\n  }\n\n  int highLevelExpanded() { return m_highLevelExpanded; }\n\n  /// Low Level Environment functions\n  void setLowLevelContext(size_t agentIdx, const Constraints *constraints) {\n    assert(constraints);  // NOLINT\n    m_agentIdx = agentIdx;\n    m_constraints = constraints;\n    m_lastGoalConstraint = -1;\n    for (const auto &c : constraints->constraints) {\n      if (m_goals[m_agentIdx].agentCollision(c.s)) {\n        m_lastGoalConstraint = std::max(m_lastGoalConstraint, c.time);\n      }\n    }\n\n    // std::cout << \"Setting Lowlevel agent idx:\" << agentIdx\n    //           << \" Constraints:\" << constraints->constraints.size()\n    //           << \"  lastGoalConstraints:\" << m_lastGoalConstraint <<\n    //           std::endl;\n  }\n\n  int admissibleHeuristic(const State &s) {\n    // non-holonomic-without-obstacles heuristic: use a Reeds-Shepp\n    ompl::base::ReedsSheppStateSpace reedsSheppPath(Constants::r);\n    OmplState *rsStart = (OmplState *)reedsSheppPath.allocState();\n    OmplState *rsEnd = (OmplState *)reedsSheppPath.allocState();\n    rsStart->setXY(s.x, s.y);\n    rsStart->setYaw(s.yaw);\n    rsEnd->setXY(m_goals[m_agentIdx].x, m_goals[m_agentIdx].y);\n    rsEnd->setYaw(m_goals[m_agentIdx].yaw);\n    double reedsSheppCost = reedsSheppPath.distance(rsStart, rsEnd);\n    // std::cout << \"ReedsShepps cost:\" << reedsSheppCost << std::endl;\n    // Euclidean distance\n    double euclideanCost = sqrt(pow(m_goals[m_agentIdx].x - s.x, 2) +\n                                pow(m_goals[m_agentIdx].y - s.y, 2));\n    // std::cout << \"Euclidean cost:\" << euclideanCost << std::endl;\n    // holonomic-with-obstacles heuristic\n    double twoDoffset =\n        sqrt(pow((s.x - (int)s.x) -\n                     (m_goals[m_agentIdx].x - (int)m_goals[m_agentIdx].x),\n                 2) +\n             pow((s.y - (int)s.y) -\n                     (m_goals[m_agentIdx].y - (int)m_goals[m_agentIdx].y),\n                 2));\n    double twoDCost =\n        holonomic_cost_maps[m_agentIdx][(int)s.x / Constants::mapResolution]\n                           [(int)s.y / Constants::mapResolution] -\n        twoDoffset;\n    // std::cout << \"holonomic cost:\" << twoDCost << std::endl;\n\n    return std::max({reedsSheppCost, euclideanCost, twoDCost});\n    return 0;\n  }\n\n  bool isSolution(\n      const State &state, double gscore,\n      std::unordered_map<State, std::tuple<State, Action, double, double>,\n                         std::hash<State>> &_camefrom) {\n    double goal_distance =\n        sqrt(pow(state.x - getGoal().x, 2) + pow(state.y - getGoal().y, 2));\n    if (goal_distance > 3 * (Constants::LB + Constants::LF)) return false;\n    ompl::base::ReedsSheppStateSpace reedsSheppSpace(Constants::r);\n    OmplState *rsStart = (OmplState *)reedsSheppSpace.allocState();\n    OmplState *rsEnd = (OmplState *)reedsSheppSpace.allocState();\n    rsStart->setXY(state.x, state.y);\n    rsStart->setYaw(-state.yaw);\n    rsEnd->setXY(getGoal().x, getGoal().y);\n    rsEnd->setYaw(-getGoal().yaw);\n    ompl::base::ReedsSheppStateSpace::ReedsSheppPath reedsShepppath =\n        reedsSheppSpace.reedsShepp(rsStart, rsEnd);\n\n    std::vector<State> path;\n    std::unordered_map<State, std::tuple<State, Action, double, double>,\n                       std::hash<State>>\n        cameFrom;\n    cameFrom.clear();\n    path.emplace_back(state);\n    for (auto pathidx = 0; pathidx < 5; pathidx++) {\n      if (fabs(reedsShepppath.length_[pathidx]) < 1e-6) continue;\n      double deltat = 0, dx = 0, act = 0, cost = 0;\n      switch (reedsShepppath.type_[pathidx]) {\n        case 0:  // RS_NOP\n          continue;\n          break;\n        case 1:  // RS_LEFT\n          deltat = -reedsShepppath.length_[pathidx];\n          dx = Constants::r * sin(-deltat);\n          // dy = Constants::r * (1 - cos(-deltat));\n          act = 2;\n          cost = reedsShepppath.length_[pathidx] * Constants::r *\n                 Constants::penaltyTurning;\n          break;\n        case 2:  // RS_STRAIGHT\n          deltat = 0;\n          dx = reedsShepppath.length_[pathidx] * Constants::r;\n          // dy = 0;\n          act = 0;\n          cost = dx;\n          break;\n        case 3:  // RS_RIGHT\n          deltat = reedsShepppath.length_[pathidx];\n          dx = Constants::r * sin(deltat);\n          // dy = -Constants::r * (1 - cos(deltat));\n          act = 1;\n          cost = reedsShepppath.length_[pathidx] * Constants::r *\n                 Constants::penaltyTurning;\n          break;\n        default:\n          std::cout << \"\\033[1m\\033[31m\"\n                    << \"Warning: Receive unknown ReedsSheppPath type\"\n                    << \"\\033[0m\\n\";\n          break;\n      }\n      if (cost < 0) {\n        cost = -cost * Constants::penaltyReversing;\n        act = act + 3;\n      }\n      State s = path.back();\n      std::vector<std::pair<State, double>> next_path;\n      if (generatePath(s, act, deltat, dx, next_path)) {\n        for (auto iter = next_path.begin(); iter != next_path.end(); iter++) {\n          State next_s = iter->first;\n          gscore += iter->second;\n          if (!(next_s == path.back())) {\n            cameFrom.insert(std::make_pair<>(\n                next_s,\n                std::make_tuple<>(path.back(), act, iter->second, gscore)));\n          }\n          path.emplace_back(next_s);\n        }\n      } else {\n        return false;\n      }\n    }\n\n    if (path.back().time <= m_lastGoalConstraint) {\n      return false;\n    }\n\n    m_goals[m_agentIdx] = path.back();\n\n    _camefrom.insert(cameFrom.begin(), cameFrom.end());\n    return true;\n  }\n\n  void getNeighbors(const State &s, Action action,\n                    std::vector<Neighbor<State, Action, double>> &neighbors) {\n    neighbors.clear();\n    double g = Constants::dx[0];\n    for (Action act = 0; act < 6; act++) {  // has 6 directions for Reeds-Shepp\n      double xSucc, ySucc, yawSucc;\n      g = Constants::dx[0];\n      xSucc = s.x + Constants::dx[act] * cos(-s.yaw) -\n              Constants::dy[act] * sin(-s.yaw);\n      ySucc = s.y + Constants::dx[act] * sin(-s.yaw) +\n              Constants::dy[act] * cos(-s.yaw);\n      yawSucc = Constants::normalizeHeadingRad(s.yaw + Constants::dyaw[act]);\n      // if (act != action) {  // penalize turning\n      //   g = g * Constants::penaltyTurning;\n      //   if (act >= 3)  // penalize change of direction\n      //     g = g * Constants::penaltyCOD;\n      // }\n      // if (act > 3) {  // backwards\n      //   g = g * Constants::penaltyReversing;\n      // }\n      if (act % 3 != 0) {  // penalize turning\n        g = g * Constants::penaltyTurning;\n      }\n      if ((act < 3 && action >= 3) || (action < 3 && act >= 3)) {\n        // penalize change of direction\n        g = g * Constants::penaltyCOD;\n      }\n      if (act >= 3) {  // backwards\n        g = g * Constants::penaltyReversing;\n      }\n      State tempState(xSucc, ySucc, yawSucc, s.time + 1);\n      if (stateValid(tempState)) {\n        neighbors.emplace_back(\n            Neighbor<State, Action, double>(tempState, act, g));\n      }\n    }\n    // wait\n    g = Constants::dx[0];\n    State tempState(s.x, s.y, s.yaw, s.time + 1);\n    if (stateValid(tempState)) {\n      neighbors.emplace_back(Neighbor<State, Action, double>(tempState, 6, g));\n    }\n  }\n  State getGoal() { return m_goals[m_agentIdx]; }\n  uint64_t calcIndex(const State &s) {\n    return (uint64_t)s.time * (2 * M_PI / Constants::deltat) *\n               (m_dimx / Constants::xyResolution) *\n               (m_dimy / Constants::xyResolution) +\n           (uint64_t)(Constants::normalizeHeadingRad(s.yaw) /\n                      Constants::yawResolution) *\n               (m_dimx / Constants::xyResolution) *\n               (m_dimy / Constants::xyResolution) +\n           (uint64_t)(s.y / Constants::xyResolution) *\n               (m_dimx / Constants::xyResolution) +\n           (uint64_t)(s.x / Constants::xyResolution);\n  }\n\n  void onExpandLowLevelNode(const State & /*s*/, int /*fScore*/,\n                            int /*gScore*/) {\n    m_lowLevelExpanded++;\n  }\n\n  int lowLevelExpanded() const { return m_lowLevelExpanded; }\n\n  bool startAndGoalValid(const std::vector<State> &m_starts, const size_t iter,\n                         const int batchsize) {\n    assert(m_goals.size() == m_starts.size());\n    for (size_t i = 0; i < m_goals.size(); i++)\n      for (size_t j = i + 1; j < m_goals.size(); j++) {\n        if (m_goals[i].agentCollision(m_goals[j])) {\n          std::cout << \"ERROR: Goal point of \" << i + iter * batchsize << \" & \"\n                    << j + iter * batchsize << \" collide!\\n\";\n          return false;\n        }\n        if (m_starts[i].agentCollision(m_starts[j])) {\n          std::cout << \"ERROR: Start point of \" << i + iter * batchsize << \" & \"\n                    << j + iter * batchsize << \" collide!\\n\";\n          return false;\n        }\n      }\n    return true;\n  }\n\n private:\n  State getState(size_t agentIdx,\n                 const std::vector<PlanResult<State, Action, double>> &solution,\n                 size_t t) {\n    assert(agentIdx < solution.size());\n    if (t < solution[agentIdx].states.size()) {\n      return solution[agentIdx].states[t].first;\n    }\n    assert(!solution[agentIdx].states.empty());\n    return solution[agentIdx].states.back().first;\n  }\n\n  bool stateValid(const State &s) {\n    double x_ind = s.x / Constants::mapResolution;\n    double y_ind = s.y / Constants::mapResolution;\n    if (x_ind < 0 || x_ind >= m_dimx || y_ind < 0 || y_ind >= m_dimy)\n      return false;\n\n    for (auto it = m_obstacles.begin(); it != m_obstacles.end(); it++) {\n      if (s.obsCollision(*it)) return false;\n    }\n\n    auto it = m_dynamic_obstacles.equal_range(s.time);\n    for (auto itr = it.first; itr != it.second; ++itr) {\n      if (s.agentCollision(itr->second)) return false;\n    }\n    auto itlow = m_dynamic_obstacles.lower_bound(-s.time);\n    auto itup = m_dynamic_obstacles.upper_bound(-1);\n    for (auto it = itlow; it != itup; ++it)\n      if (s.agentCollision(it->second)) return false;\n\n    for (auto it = m_constraints->constraints.begin();\n         it != m_constraints->constraints.end(); it++) {\n      if (!it->satisfyConstraint(s)) return false;\n    }\n\n    return true;\n  }\n\n private:\n  struct compare_node {\n    bool operator()(const std::pair<State, double> &n1,\n                    const std::pair<State, double> &n2) const {\n      return (n1.second > n2.second);\n    }\n  };\n  void updateCostmap() {\n    boost::heap::fibonacci_heap<std::pair<State, double>,\n                                boost::heap::compare<compare_node>>\n        heap;\n\n    std::set<std::pair<int, int>> temp_obs_set;\n    for (auto it = m_obstacles.begin(); it != m_obstacles.end(); it++) {\n      temp_obs_set.insert(\n          std::make_pair((int)it->x / Constants::mapResolution,\n                         (int)it->y / Constants::mapResolution));\n    }\n\n    for (size_t idx = 0; idx < m_goals.size(); idx++) {\n      heap.clear();\n      int goal_x = (int)m_goals[idx].x / Constants::mapResolution;\n      int goal_y = (int)m_goals[idx].y / Constants::mapResolution;\n      heap.push(std::make_pair(State(goal_x, goal_y, 0), 0));\n\n      while (!heap.empty()) {\n        std::pair<State, double> node = heap.top();\n        heap.pop();\n\n        int x = node.first.x;\n        int y = node.first.y;\n        for (int dx = -1; dx <= 1; dx++)\n          for (int dy = -1; dy <= 1; dy++) {\n            if (dx == 0 && dy == 0) continue;\n            int new_x = x + dx;\n            int new_y = y + dy;\n            if (new_x == goal_x && new_y == goal_y) continue;\n            if (new_x >= 0 && new_x < m_dimx && new_y >= 0 && new_y < m_dimy &&\n                holonomic_cost_maps[idx][new_x][new_y] == 0 &&\n                temp_obs_set.find(std::make_pair(new_x, new_y)) ==\n                    temp_obs_set.end()) {\n              holonomic_cost_maps[idx][new_x][new_y] =\n                  holonomic_cost_maps[idx][x][y] +\n                  sqrt(pow(dx * Constants::mapResolution, 2) +\n                       pow(dy * Constants::mapResolution, 2));\n              heap.push(std::make_pair(State(new_x, new_y, 0),\n                                       holonomic_cost_maps[idx][new_x][new_y]));\n            }\n          }\n      }\n    }\n\n    // for (size_t idx = 0; idx < m_goals.size(); idx++) {\n    //   std::cout << \"---------Cost Map -------Agent: \" << idx\n    //             << \"------------\\n\";\n    //   for (size_t i = 0; i < m_dimx; i++) {\n    //     for (size_t j = 0; j < m_dimy; j++)\n    //       std::cout << holonomic_cost_maps[idx][i][j] << \"\\t\";\n    //     std::cout << std::endl;\n    //   }\n    // }\n  }\n\n  bool generatePath(State startState, int act, double deltaSteer,\n                    double deltaLength,\n                    std::vector<std::pair<State, double>> &result) {\n    double xSucc, ySucc, yawSucc, dx, dy, dyaw, ratio;\n    result.emplace_back(std::make_pair<>(startState, 0));\n    if (act == 0 || act == 3) {\n      for (size_t i = 0; i < (size_t)(deltaLength / Constants::dx[act]); i++) {\n        State s = result.back().first;\n        xSucc = s.x + Constants::dx[act] * cos(-s.yaw) -\n                Constants::dy[act] * sin(-s.yaw);\n        ySucc = s.y + Constants::dx[act] * sin(-s.yaw) +\n                Constants::dy[act] * cos(-s.yaw);\n        yawSucc = Constants::normalizeHeadingRad(s.yaw + Constants::dyaw[act]);\n        State nextState(xSucc, ySucc, yawSucc, result.back().first.time + 1);\n        if (!stateValid(nextState)) return false;\n        result.emplace_back(std::make_pair<>(nextState, Constants::dx[0]));\n      }\n      ratio = (deltaLength -\n               (int)(deltaLength / Constants::dx[act]) * Constants::dx[act]) /\n              Constants::dx[act];\n      dyaw = 0;\n      dx = ratio * Constants::dx[act];\n      dy = 0;\n    } else {\n      for (size_t i = 0; i < (size_t)(deltaSteer / Constants::dyaw[act]); i++) {\n        State s = result.back().first;\n        xSucc = s.x + Constants::dx[act] * cos(-s.yaw) -\n                Constants::dy[act] * sin(-s.yaw);\n        ySucc = s.y + Constants::dx[act] * sin(-s.yaw) +\n                Constants::dy[act] * cos(-s.yaw);\n        yawSucc = Constants::normalizeHeadingRad(s.yaw + Constants::dyaw[act]);\n        State nextState(xSucc, ySucc, yawSucc, result.back().first.time + 1);\n        if (!stateValid(nextState)) return false;\n        result.emplace_back(std::make_pair<>(\n            nextState, Constants::dx[0] * Constants::penaltyTurning));\n      }\n      ratio = (deltaSteer - (int)(deltaSteer / Constants::dyaw[act]) *\n                                Constants::dyaw[act]) /\n              Constants::dyaw[act];\n      dyaw = ratio * Constants::dyaw[act];\n      dx = Constants::r * sin(dyaw);\n      dy = -Constants::r * (1 - cos(dyaw));\n      if (act == 2 || act == 5) {\n        dx = -dx;\n        dy = -dy;\n      }\n    }\n    State s = result.back().first;\n    xSucc = s.x + dx * cos(-s.yaw) - dy * sin(-s.yaw);\n    ySucc = s.y + dx * sin(-s.yaw) + dy * cos(-s.yaw);\n    yawSucc = Constants::normalizeHeadingRad(s.yaw + dyaw);\n    // std::cout << m_agentIdx << \" ratio::\" << ratio << std::endl;\n    State nextState(xSucc, ySucc, yawSucc, result.back().first.time + 1);\n    if (!stateValid(nextState)) return false;\n    result.emplace_back(std::make_pair<>(nextState, ratio * Constants::dx[0]));\n\n    // std::cout << \"Have generate \" << result.size() << \" path segments:\\n\\t\";\n    // for (auto iter = result.begin(); iter != result.end(); iter++)\n    //   std::cout << iter->first << \":\" << iter->second << \"->\";\n    // std::cout << std::endl;\n\n    return true;\n  }\n\n private:\n  int m_dimx;\n  int m_dimy;\n  std::vector<std::vector<std::vector<double>>> holonomic_cost_maps;\n  std::unordered_set<Location> m_obstacles;\n  std::multimap<int, State> m_dynamic_obstacles;\n  std::vector<State> m_goals;\n  // std::vector< std::vector<int> > m_heuristic;\n  std::vector<double> m_vel_limit;\n  size_t m_agentIdx;\n  const Constraints *m_constraints;\n  int m_lastGoalConstraint;\n  int m_highLevelExpanded;\n  int m_lowLevelExpanded;\n};\n\n}  // namespace libMultiRobotPlanning", "meta": {"hexsha": "ffa469e0b2b0a42c35e4503852e74ba59dfe0cf4", "size": 21839, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/environment.hpp", "max_stars_repo_name": "LIJUNCHENG001/CL-CBS", "max_stars_repo_head_hexsha": "b353759a3e34962ee57475a031026416fbbc2382", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2020-10-29T05:01:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:17:08.000Z", "max_issues_repo_path": "include/environment.hpp", "max_issues_repo_name": "mieximiemie/CL-CBS", "max_issues_repo_head_hexsha": "b353759a3e34962ee57475a031026416fbbc2382", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T17:48:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T02:57:54.000Z", "max_forks_repo_path": "include/environment.hpp", "max_forks_repo_name": "mieximiemie/CL-CBS", "max_forks_repo_head_hexsha": "b353759a3e34962ee57475a031026416fbbc2382", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 29.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T05:09:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T09:17:10.000Z", "avg_line_length": 37.1411564626, "max_line_length": 80, "alphanum_fraction": 0.5767663355, "num_tokens": 6019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.21486378383334434}}
{"text": "// Copyright (c) 2019, The Monero And Italo 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#include <boost/multiprecision/cpp_int.hpp>\n\nvoid div128_64(uint64_t dividend_hi, uint64_t dividend_lo, uint64_t divisor, uint64_t* quotient_hi, uint64_t *quotient_lo, uint64_t *remainder_hi, uint64_t *remainder_lo)\n{\n  typedef boost::multiprecision::uint128_t uint128_t;\n\n  uint128_t dividend = dividend_hi;\n  dividend <<= 64;\n  dividend |= dividend_lo;\n\n  uint128_t q, r;\n  divide_qr(dividend, uint128_t(divisor), q, r);\n\n  *quotient_hi = ((q >> 64) & 0xffffffffffffffffull).convert_to<uint64_t>();\n  *quotient_lo = (q & 0xffffffffffffffffull).convert_to<uint64_t>();\n  if (remainder_hi)\n    *remainder_hi = ((r >> 64) & 0xffffffffffffffffull).convert_to<uint64_t>();\n  if (remainder_lo)\n    *remainder_lo = (r & 0xffffffffffffffffull).convert_to<uint64_t>();\n}\n", "meta": {"hexsha": "b84919020dc6fbe08db61b0bf63f41765232edd6", "size": 2361, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contrib/epee/src/int-util.cpp", "max_stars_repo_name": "blackrangersoftware/brs-italo-core", "max_stars_repo_head_hexsha": "0837150243470bb45b388aea376cc1c12479fd91", "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": "contrib/epee/src/int-util.cpp", "max_issues_repo_name": "blackrangersoftware/brs-italo-core", "max_issues_repo_head_hexsha": "0837150243470bb45b388aea376cc1c12479fd91", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contrib/epee/src/int-util.cpp", "max_forks_repo_name": "blackrangersoftware/brs-italo-core", "max_forks_repo_head_hexsha": "0837150243470bb45b388aea376cc1c12479fd91", "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": 48.1836734694, "max_line_length": 170, "alphanum_fraction": 0.7581533249, "num_tokens": 551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.21482608111446486}}
{"text": "//  (C) Copyright Jeremy William Murphy 2016.\n\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_INTEGER_COMMON_FACTOR_RT_HPP\n#define BOOST_INTEGER_COMMON_FACTOR_RT_HPP\n\n#include <boost/assert.hpp>\n#include <boost/core/enable_if.hpp>\n\n#include <boost/config.hpp>  // for BOOST_NESTED_TEMPLATE, etc.\n#include <boost/limits.hpp>  // for std::numeric_limits\n#include <climits>           // for CHAR_MIN\n#include <boost/detail/workaround.hpp>\n#include <iterator>\n#include <algorithm>\n#include <limits>\n#ifndef BOOST_NO_CXX11_HDR_TYPE_TRAITS\n#include <type_traits>\n#endif\n#ifdef BOOST_NO_CXX11_HDR_FUNCTIONAL\n#include <functional>\n#endif\n\n#if ((defined(BOOST_MSVC) && (BOOST_MSVC >= 1600)) || (defined(__clang__) && defined(__c2__)) || (defined(BOOST_INTEL) && defined(_MSC_VER))) && (defined(_M_IX86) || defined(_M_X64))\n#include <intrin.h>\n#endif\n\n#ifdef BOOST_MSVC\n#pragma warning(push)\n#pragma warning(disable:4127 4244)  // Conditional expression is constant\n#endif\n\n#if !defined(BOOST_NO_CXX11_HDR_TYPE_TRAITS) && !defined(BOOST_NO_CXX11_NOEXCEPT)\n#define BOOST_GCD_NOEXCEPT(T) noexcept(std::is_arithmetic<T>::value)\n#else\n#define BOOST_GCD_NOEXCEPT(T)\n#endif\n\nnamespace boost {\n\n   template <class I>\n   class rational;\n\n   namespace integer {\n\n      namespace gcd_detail{\n\n         //\n         // some helper functions which really should be constexpr already, but sadly aren't:\n         //\n#ifndef BOOST_NO_CXX14_CONSTEXPR\n         template <class T>\n         inline constexpr T constexpr_min(T const& a, T const& b) BOOST_GCD_NOEXCEPT(T)\n         {\n            return a < b ? a : b;\n         }\n         template <class T>\n         inline constexpr auto constexpr_swap(T&a, T& b) BOOST_GCD_NOEXCEPT(T) -> decltype(a.swap(b))\n         {\n            return a.swap(b);\n         }\n         template <class T, class U>\n         inline constexpr void constexpr_swap(T&a, U& b...) BOOST_GCD_NOEXCEPT(T)\n         {\n            T t(static_cast<T&&>(a));\n            a = static_cast<T&&>(b);\n            b = static_cast<T&&>(t);\n         }\n#else\n         template <class T>\n         inline T constexpr_min(T const& a, T const& b) BOOST_GCD_NOEXCEPT(T)\n         {\n            return a < b ? a : b;\n         }\n         template <class T>\n         inline void constexpr_swap(T&a, T& b) BOOST_GCD_NOEXCEPT(T)\n         {\n            using std::swap;\n            swap(a, b);\n         }\n#endif\n\n      template <class T, bool a =\n#ifndef BOOST_NO_CXX11_HDR_TYPE_TRAITS\n         std::is_unsigned<T>::value ||\n#endif\n         (std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_signed)>\n      struct gcd_traits_abs_defaults\n      {\n         inline static BOOST_CXX14_CONSTEXPR const T& abs(const T& val) BOOST_GCD_NOEXCEPT(T) { return val; }\n      };\n      template <class T>\n      struct gcd_traits_abs_defaults<T, false>\n      {\n         inline static T BOOST_CXX14_CONSTEXPR abs(const T& val) BOOST_GCD_NOEXCEPT(T)\n         {\n            // This sucks, but std::abs is not constexpr :(\n            return val < T(0) ? -val : val;\n         }\n      };\n\n      enum method_type\n      {\n         method_euclid = 0,\n         method_binary = 1,\n         method_mixed = 2\n      };\n\n      struct any_convert\n      {\n         template <class T>\n         any_convert(const T&);\n      };\n\n      struct unlikely_size\n      {\n         char buf[9973];\n      };\n\n      unlikely_size operator <<= (any_convert, any_convert);\n      unlikely_size operator >>= (any_convert, any_convert);\n\n      template <class T>\n      struct gcd_traits_defaults : public gcd_traits_abs_defaults<T>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(T& val) BOOST_GCD_NOEXCEPT(T)\n         {\n            unsigned r = 0;\n            while(0 == (val & 1u))\n            {\n#ifdef _MSC_VER  // VC++ can't handle operator >>= in constexpr code for some reason\n               val = val >> 1;\n#else\n               val >>= 1;\n#endif\n               ++r;\n            }\n            return r;\n         }\n         inline static BOOST_CXX14_CONSTEXPR bool less(const T& a, const T& b) BOOST_GCD_NOEXCEPT(T)\n         {\n            return a < b;\n         }\n\n         static T& get_value();\n\n#ifndef BOOST_NO_SFINAE\n         static const bool has_operator_left_shift_equal = sizeof(get_value() <<= 2) != sizeof(unlikely_size);\n         static const bool has_operator_right_shift_equal = sizeof(get_value() >>= 2) != sizeof(unlikely_size);\n#else\n         static const bool has_operator_left_shift_equal = true;\n         static const bool has_operator_right_shift_equal = true;\n#endif\n         static const method_type method = std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && has_operator_left_shift_equal && has_operator_right_shift_equal ? method_mixed : method_euclid;\n      };\n      //\n      // Default gcd_traits just inherits from defaults:\n      //\n      template <class T>\n      struct gcd_traits : public gcd_traits_defaults<T> {};\n\n      //\n      // Some platforms have fast bitscan operations, that allow us to implement\n      // make_odd much more efficiently, unfortunately we can't use these if we want\n      // the functions to be constexpr as the compiler intrinsics aren't constexpr.\n      //\n#if defined(BOOST_NO_CXX14_CONSTEXPR) && ((defined(BOOST_MSVC) && (BOOST_MSVC >= 1600)) || (defined(__clang__) && defined(__c2__)) || (defined(BOOST_INTEL) && defined(_MSC_VER))) && (defined(_M_IX86) || defined(_M_X64))\n#pragma intrinsic(_BitScanForward,)\n      template <>\n      struct gcd_traits<unsigned long> : public gcd_traits_defaults<unsigned long>\n      {\n         BOOST_FORCEINLINE static unsigned find_lsb(unsigned long val) BOOST_NOEXCEPT\n         {\n            unsigned long result;\n            _BitScanForward(&result, val);\n            return result;\n         }\n         BOOST_FORCEINLINE static unsigned make_odd(unsigned long& val) BOOST_NOEXCEPT\n         {\n            unsigned result = find_lsb(val);\n            val >>= result;\n            return result;\n         }\n      };\n\n#ifdef _M_X64\n#pragma intrinsic(_BitScanForward64)\n      template <>\n      struct gcd_traits<unsigned __int64> : public gcd_traits_defaults<unsigned __int64>\n      {\n         BOOST_FORCEINLINE static unsigned find_lsb(unsigned __int64 mask) BOOST_NOEXCEPT\n         {\n            unsigned long result;\n            _BitScanForward64(&result, mask);\n            return result;\n         }\n         BOOST_FORCEINLINE static unsigned make_odd(unsigned __int64& val) BOOST_NOEXCEPT\n         {\n            unsigned result = find_lsb(val);\n            val >>= result;\n            return result;\n         }\n      };\n#endif\n      //\n      // Other integer type are trivial adaptations of the above,\n      // this works for signed types too, as by the time these functions\n      // are called, all values are > 0.\n      //\n      template <> struct gcd_traits<long> : public gcd_traits_defaults<long>\n      { BOOST_FORCEINLINE static unsigned make_odd(long& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<unsigned int> : public gcd_traits_defaults<unsigned int>\n      { BOOST_FORCEINLINE static unsigned make_odd(unsigned int& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<int> : public gcd_traits_defaults<int>\n      { BOOST_FORCEINLINE static unsigned make_odd(int& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<unsigned short> : public gcd_traits_defaults<unsigned short>\n      { BOOST_FORCEINLINE static unsigned make_odd(unsigned short& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<short> : public gcd_traits_defaults<short>\n      { BOOST_FORCEINLINE static unsigned make_odd(short& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<unsigned char> : public gcd_traits_defaults<unsigned char>\n      { BOOST_FORCEINLINE static unsigned make_odd(unsigned char& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<signed char> : public gcd_traits_defaults<signed char>\n      { BOOST_FORCEINLINE static signed make_odd(signed char& val)BOOST_NOEXCEPT{ signed result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n      template <> struct gcd_traits<char> : public gcd_traits_defaults<char>\n      { BOOST_FORCEINLINE static unsigned make_odd(char& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\n      template <> struct gcd_traits<wchar_t> : public gcd_traits_defaults<wchar_t>\n      { BOOST_FORCEINLINE static unsigned make_odd(wchar_t& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };\n#endif\n#ifdef _M_X64\n      template <> struct gcd_traits<__int64> : public gcd_traits_defaults<__int64>\n      { BOOST_FORCEINLINE static unsigned make_odd(__int64& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned __int64>::find_lsb(val); val >>= result; return result; } };\n#endif\n\n#elif defined(BOOST_GCC) || defined(__clang__) || (defined(BOOST_INTEL) && defined(__GNUC__))\n\n      template <>\n      struct gcd_traits<unsigned> : public gcd_traits_defaults<unsigned>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned find_lsb(unsigned mask)BOOST_NOEXCEPT\n         {\n            return __builtin_ctz(mask);\n         }\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(unsigned& val)BOOST_NOEXCEPT\n         {\n            unsigned result = find_lsb(val);\n            val >>= result;\n            return result;\n         }\n      };\n      template <>\n      struct gcd_traits<unsigned long> : public gcd_traits_defaults<unsigned long>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned find_lsb(unsigned long mask)BOOST_NOEXCEPT\n         {\n            return __builtin_ctzl(mask);\n         }\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(unsigned long& val)BOOST_NOEXCEPT\n         {\n            unsigned result = find_lsb(val);\n            val >>= result;\n            return result;\n         }\n      };\n      template <>\n      struct gcd_traits<boost::ulong_long_type> : public gcd_traits_defaults<boost::ulong_long_type>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned find_lsb(boost::ulong_long_type mask)BOOST_NOEXCEPT\n         {\n            return __builtin_ctzll(mask);\n         }\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(boost::ulong_long_type& val)BOOST_NOEXCEPT\n         {\n            unsigned result = find_lsb(val);\n            val >>= result;\n            return result;\n         }\n      };\n      //\n      // Other integer type are trivial adaptations of the above,\n      // this works for signed types too, as by the time these functions\n      // are called, all values are > 0.\n      //\n      template <> struct gcd_traits<boost::long_long_type> : public gcd_traits_defaults<boost::long_long_type>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(boost::long_long_type& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<boost::ulong_long_type>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<long> : public gcd_traits_defaults<long>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(long& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<int> : public gcd_traits_defaults<int>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(int& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<unsigned short> : public gcd_traits_defaults<unsigned short>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(unsigned short& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<short> : public gcd_traits_defaults<short>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(short& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<unsigned char> : public gcd_traits_defaults<unsigned char>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(unsigned char& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<signed char> : public gcd_traits_defaults<signed char>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR signed make_odd(signed char& val)BOOST_NOEXCEPT { signed result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n      template <> struct gcd_traits<char> : public gcd_traits_defaults<char>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(char& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n#ifndef BOOST_NO_INTRINSIC_WCHAR_T\n      template <> struct gcd_traits<wchar_t> : public gcd_traits_defaults<wchar_t>\n      {\n         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(wchar_t& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }\n      };\n#endif\n#endif\n   //\n   // The Mixed Binary Euclid Algorithm\n   // Sidi Mohamed Sedjelmaci\n   // Electronic Notes in Discrete Mathematics 35 (2009) 169-176\n   //\n   template <class T>\n   BOOST_CXX14_CONSTEXPR T mixed_binary_gcd(T u, T v) BOOST_GCD_NOEXCEPT(T)\n   {\n      if(gcd_traits<T>::less(u, v))\n         constexpr_swap(u, v);\n\n      unsigned shifts = 0;\n\n      if(u == T(0))\n         return v;\n      if(v == T(0))\n         return u;\n\n      shifts = constexpr_min(gcd_traits<T>::make_odd(u), gcd_traits<T>::make_odd(v));\n\n      while(gcd_traits<T>::less(1, v))\n      {\n         u %= v;\n         v -= u;\n         if(u == T(0))\n            return v << shifts;\n         if(v == T(0))\n            return u << shifts;\n         gcd_traits<T>::make_odd(u);\n         gcd_traits<T>::make_odd(v);\n         if(gcd_traits<T>::less(u, v))\n            constexpr_swap(u, v);\n      }\n      return (v == 1 ? v : u) << shifts;\n   }\n\n    /** Stein gcd (aka 'binary gcd')\n     *\n     * From Mathematics to Generic Programming, Alexander Stepanov, Daniel Rose\n     */\n    template <typename SteinDomain>\n    BOOST_CXX14_CONSTEXPR SteinDomain Stein_gcd(SteinDomain m, SteinDomain n) BOOST_GCD_NOEXCEPT(SteinDomain)\n    {\n        BOOST_ASSERT(m >= 0);\n        BOOST_ASSERT(n >= 0);\n        if (m == SteinDomain(0))\n            return n;\n        if (n == SteinDomain(0))\n            return m;\n        // m > 0 && n > 0\n        int d_m = gcd_traits<SteinDomain>::make_odd(m);\n        int d_n = gcd_traits<SteinDomain>::make_odd(n);\n        // odd(m) && odd(n)\n        while (m != n)\n        {\n            if (n > m)\n               constexpr_swap(n, m);\n            m -= n;\n            gcd_traits<SteinDomain>::make_odd(m);\n        }\n        // m == n\n        m <<= constexpr_min(d_m, d_n);\n        return m;\n    }\n\n\n    /** Euclidean algorithm\n     *\n     * From Mathematics to Generic Programming, Alexander Stepanov, Daniel Rose\n     *\n     */\n    template <typename EuclideanDomain>\n    inline BOOST_CXX14_CONSTEXPR EuclideanDomain Euclid_gcd(EuclideanDomain a, EuclideanDomain b) BOOST_GCD_NOEXCEPT(EuclideanDomain)\n    {\n        while (b != EuclideanDomain(0))\n        {\n            a %= b;\n            constexpr_swap(a, b);\n        }\n        return a;\n    }\n\n\n    template <typename T>\n    inline BOOST_CXX14_CONSTEXPR BOOST_DEDUCED_TYPENAME enable_if_c<gcd_traits<T>::method == method_mixed, T>::type\n       optimal_gcd_select(T const &a, T const &b) BOOST_GCD_NOEXCEPT(T)\n    {\n       return gcd_detail::mixed_binary_gcd(a, b);\n    }\n\n    template <typename T>\n    inline BOOST_CXX14_CONSTEXPR BOOST_DEDUCED_TYPENAME enable_if_c<gcd_traits<T>::method == method_binary, T>::type\n       optimal_gcd_select(T const &a, T const &b) BOOST_GCD_NOEXCEPT(T)\n    {\n       return gcd_detail::Stein_gcd(a, b);\n    }\n\n    template <typename T>\n    inline BOOST_CXX14_CONSTEXPR BOOST_DEDUCED_TYPENAME enable_if_c<gcd_traits<T>::method == method_euclid, T>::type\n       optimal_gcd_select(T const &a, T const &b) BOOST_GCD_NOEXCEPT(T)\n    {\n       return gcd_detail::Euclid_gcd(a, b);\n    }\n\n    template <class T>\n    inline BOOST_CXX14_CONSTEXPR T lcm_imp(const T& a, const T& b) BOOST_GCD_NOEXCEPT(T)\n    {\n       T temp = boost::integer::gcd_detail::optimal_gcd_select(a, b);\n#if BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40500)\n       return (temp != T(0)) ? T(a / temp * b) : T(0);\n#else\n       return temp != T(0) ? T(a / temp * b) : T(0);\n#endif\n    }\n\n} // namespace detail\n\n\ntemplate <typename Integer>\ninline BOOST_CXX14_CONSTEXPR Integer gcd(Integer const &a, Integer const &b) BOOST_GCD_NOEXCEPT(Integer)\n{\n    if(a == (std::numeric_limits<Integer>::min)())\n       return a == static_cast<Integer>(0) ? gcd_detail::gcd_traits<Integer>::abs(b) : boost::integer::gcd(static_cast<Integer>(a % b), b);\n    else if (b == (std::numeric_limits<Integer>::min)())\n       return b == static_cast<Integer>(0) ? gcd_detail::gcd_traits<Integer>::abs(a) : boost::integer::gcd(a, static_cast<Integer>(b % a));\n    return gcd_detail::optimal_gcd_select(static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(a)), static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(b)));\n}\n\ntemplate <typename Integer>\ninline BOOST_CXX14_CONSTEXPR Integer lcm(Integer const &a, Integer const &b) BOOST_GCD_NOEXCEPT(Integer)\n{\n   return gcd_detail::lcm_imp(static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(a)), static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(b)));\n}\n#ifndef BOOST_NO_CXX11_VARIADIC_TEMPLATES\n//\n// This looks slightly odd, but the variadic forms must have 3 or more arguments, and the variadic argument pack may be empty.\n// This matters not at all for most compilers, but Oracle C++ selects the wrong overload in the 2-arg case unless we do this.\n//\ntemplate <typename Integer, typename... Args>\ninline BOOST_CXX14_CONSTEXPR Integer gcd(Integer const &a, Integer const &b, const Integer& c, Args const&... args) BOOST_GCD_NOEXCEPT(Integer)\n{\n   Integer t = gcd(b, c, args...);\n   return t == 1 ? 1 : gcd(a, t);\n}\n\ntemplate <typename Integer, typename... Args>\ninline BOOST_CXX14_CONSTEXPR Integer lcm(Integer const &a, Integer const &b, Integer const& c, Args const&... args) BOOST_GCD_NOEXCEPT(Integer)\n{\n   return lcm(a, lcm(b, c, args...));\n}\n#endif\n//\n// Special handling for rationals:\n//\ntemplate <typename Integer>\ninline typename boost::enable_if_c<std::numeric_limits<Integer>::is_specialized, boost::rational<Integer> >::type gcd(boost::rational<Integer> const &a, boost::rational<Integer> const &b)\n{\n   return boost::rational<Integer>(static_cast<Integer>(gcd(a.numerator(), b.numerator())), static_cast<Integer>(lcm(a.denominator(), b.denominator())));\n}\n\ntemplate <typename Integer>\ninline typename boost::enable_if_c<std::numeric_limits<Integer>::is_specialized, boost::rational<Integer> >::type lcm(boost::rational<Integer> const &a, boost::rational<Integer> const &b)\n{\n   return boost::rational<Integer>(static_cast<Integer>(lcm(a.numerator(), b.numerator())), static_cast<Integer>(gcd(a.denominator(), b.denominator())));\n}\n/**\n * Knuth, The Art of Computer Programming: Volume 2, Third edition, 1998\n * Chapter 4.5.2, Algorithm C: Greatest common divisor of n integers.\n *\n * Knuth counts down from n to zero but we naturally go from first to last.\n * We also return the termination position because it might be useful to know.\n *\n * Partly by quirk, partly by design, this algorithm is defined for n = 1,\n * because the gcd of {x} is x. It is not defined for n = 0.\n *\n * @tparam  I   Input iterator.\n * @return  The gcd of the range and the iterator position at termination.\n */\ntemplate <typename I>\nstd::pair<typename std::iterator_traits<I>::value_type, I>\ngcd_range(I first, I last) BOOST_GCD_NOEXCEPT(I)\n{\n    BOOST_ASSERT(first != last);\n    typedef typename std::iterator_traits<I>::value_type T;\n\n    T d = *first++;\n    while (d != T(1) && first != last)\n    {\n        d = gcd(d, *first);\n        first++;\n    }\n    return std::make_pair(d, first);\n}\ntemplate <typename I>\nstd::pair<typename std::iterator_traits<I>::value_type, I>\nlcm_range(I first, I last) BOOST_GCD_NOEXCEPT(I)\n{\n    BOOST_ASSERT(first != last);\n    typedef typename std::iterator_traits<I>::value_type T;\n\n    T d = *first++;\n    while (d != T(1) && first != last)\n    {\n        d = lcm(d, *first);\n        first++;\n    }\n    return std::make_pair(d, first);\n}\n\ntemplate < typename IntegerType >\nclass gcd_evaluator\n#ifdef BOOST_NO_CXX11_HDR_FUNCTIONAL\n   : public std::binary_function<IntegerType, IntegerType, IntegerType>\n#endif\n{\npublic:\n#ifndef BOOST_NO_CXX11_HDR_FUNCTIONAL\n   typedef IntegerType first_argument_type;\n   typedef IntegerType second_argument_type;\n   typedef IntegerType result_type;\n#endif\n   IntegerType operator()(IntegerType const &a, IntegerType const &b)const\n   {\n      return boost::integer::gcd(a, b);\n   }\n};\n\ntemplate < typename IntegerType >\nclass lcm_evaluator\n#ifdef BOOST_NO_CXX11_HDR_FUNCTIONAL\n   : public std::binary_function<IntegerType, IntegerType, IntegerType>\n#endif\n{\npublic:\n#ifndef BOOST_NO_CXX11_HDR_FUNCTIONAL\n   typedef IntegerType first_argument_type;\n   typedef IntegerType second_argument_type;\n   typedef IntegerType result_type;\n#endif\n   IntegerType operator()(IntegerType const &a, IntegerType const &b)const\n   {\n      return boost::integer::lcm(a, b);\n   }\n};\n\n}  // namespace integer\n}  // namespace boost\n\n#ifdef BOOST_MSVC\n#pragma warning(pop)\n#endif\n\n#endif  // BOOST_INTEGER_COMMON_FACTOR_RT_HPP\n", "meta": {"hexsha": "f6e02bfff3e76a59a5d6f355a6b6c78c2069e4d8", "size": 22731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/integer/common_factor_rt.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/integer/common_factor_rt.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/integer/common_factor_rt.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 39.2590673575, "max_line_length": 219, "alphanum_fraction": 0.6659187893, "num_tokens": 5469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.21482608111446483}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/make_shared.hpp>\n#include <boost/shared_ptr.hpp>\n\n#include <Eigen/Core>\n\n#include <tudat/astro/basic_astro/physicalConstants.h>\n#include <tudat/basics/testMacros.h>\n#include <tudat/math/basic/mathematicalConstants.h>\n#include \"tudat/astro/basic_astro/unitConversions.h\"\n#include <tudat/astro/basic_astro/orbitalElementConversions.h>\n\n#include <tudat/io/basicInputOutput.h>\n#include <tudat/io/applicationOutput.h>\n\n#include \"tudat/simulation/propagation_setup/propagationPatchedConicFullProblem.h\"\n#include \"tudat/simulation/propagation_setup/propagationLambertTargeterFullProblem.h\"\n\n\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/astro/trajectory_design/trajectory.h\"\n#include \"tudat/astro/trajectory_design/exportTrajectory.h\"\n#include \"tudat/astro/trajectory_design/planetTrajectory.h\"\n#include <tudat/simulation/simulation.h>\n\nint main( )\n{\n    using namespace tudat;\n    using namespace tudat::input_output;\n    using namespace tudat::input_output::parsed_data_vector_utilities;\n    using namespace tudat::transfer_trajectories;\n\n\n    ///  Characteristics of the interplanetary trajectory\n\n    // Define central body of the trajectory and body to be propagated.\n    std::vector< std::string > centralBody;\n    centralBody.push_back( \"Sun\" );\n    std::string bodyToPropagate = \"spacecraft\";\n\n    // Specify the number and types of legs and type of legs.\n    int numberOfLegs = 5;\n    std::vector< TransferLegType > legTypeVector( numberOfLegs );\n    legTypeVector[ 0 ] = mga1DsmVelocity_Departure;\n    legTypeVector[ 1 ] = mga1DsmVelocity_Swingby;\n    legTypeVector[ 2 ] = mga1DsmVelocity_Swingby;\n    legTypeVector[ 3 ] = mga1DsmVelocity_Swingby;\n    legTypeVector[ 4 ] = capture;\n\n\n    // Name of the bodies involved in the trajectory\n    std::vector< std::string > transferBodyTrajectory;\n    transferBodyTrajectory.push_back(\"Earth\");\n    transferBodyTrajectory.push_back(\"Earth\");\n    transferBodyTrajectory.push_back(\"Venus\");\n    transferBodyTrajectory.push_back(\"Venus\");\n    transferBodyTrajectory.push_back(\"Mercury\");\n\n\n    // Create variable vector.\n    std::vector< double > variableVector;\n\n    // Add the time of flight and start epoch.\n    variableVector.push_back( 1171.64503236 * physical_constants::JULIAN_DAY);\n    variableVector.push_back( 399.999999715 * physical_constants::JULIAN_DAY);\n    variableVector.push_back( 178.372255301 * physical_constants::JULIAN_DAY);\n    variableVector.push_back( 299.223139512 * physical_constants::JULIAN_DAY);\n    variableVector.push_back( 180.510754824 * physical_constants::JULIAN_DAY);\n    variableVector.push_back( 1.0 ); // The capture time is irrelevant for the final leg.\n\n    // Add the additional variables.\n    // 1st leg.\n    variableVector.push_back( 0.234594654679 );\n    variableVector.push_back( 1408.99421278 );\n    variableVector.push_back( 0.37992647165 * 2.0 * 3.14159265358979 );\n    variableVector.push_back( std::acos(  2.0 * 0.498004040298 - 1. ) - 3.14159265358979 / 2.0 );\n    // 2nd leg.\n    variableVector.push_back( 0.0964769387134 );\n    variableVector.push_back( 1.35077257078 );\n    variableVector.push_back( 1.80629232251 * 6.378e6 );\n    variableVector.push_back( 0.0 );\n    // 3rd leg.\n    variableVector.push_back( 0.829948744508);\n    variableVector.push_back( 1.09554368115 );\n    variableVector.push_back( 3.04129845698 * 6.052e6 );\n    variableVector.push_back( 0.0 );\n    // 4th leg.\n    variableVector.push_back( 0.317174785637 );\n    variableVector.push_back( 1.34317576594 );\n    variableVector.push_back( 1.10000000891 * 6.052e6 );\n    variableVector.push_back( 0.0 );\n\n\n    // Create minimum pericenter radii vector\n    std::vector< double > minimumPericenterRadii;\n    minimumPericenterRadii.push_back( TUDAT_NAN ); minimumPericenterRadii.push_back( TUDAT_NAN ); minimumPericenterRadii.push_back( TUDAT_NAN );\n    minimumPericenterRadii.push_back( TUDAT_NAN ); minimumPericenterRadii.push_back( TUDAT_NAN );\n\n    // Create departure and capture variables.\n    std::vector< double > semiMajorAxes;\n    semiMajorAxes.push_back( std::numeric_limits< double >::infinity( ) ); semiMajorAxes.push_back( std::numeric_limits< double >::infinity( ) );\n    std::vector< double > eccentricities;\n    eccentricities.push_back( 0.0 ); eccentricities.push_back( 0.0 );\n\n    // Define integrator settings.\n    double initialTime = 0.0;\n    double fixedStepSize = 1000.0;\n    std::shared_ptr< numerical_integrators::IntegratorSettings< double > > integratorSettings =\n            std::make_shared < numerical_integrators::IntegratorSettings < > > (\n                numerical_integrators::rungeKutta4, initialTime, fixedStepSize);\n\n\n\n    /// Ideal case\n\n    // Create system of bodies.\n    std::vector< double > gravitationalParametersTransferBodies;\n    gravitationalParametersTransferBodies.push_back( 3.9860119e14 );\n    gravitationalParametersTransferBodies.push_back( 3.9860119e14 );\n    gravitationalParametersTransferBodies.push_back( 3.24860e14 );\n    gravitationalParametersTransferBodies.push_back( 3.24860e14 );\n    gravitationalParametersTransferBodies.push_back( 2.2321e13 );\n\n    std::vector< ephemerides::EphemerisPointer > ephemerisVectorTransferBodies;\n    ephemerisVectorTransferBodies.push_back( std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter) ) ;\n    ephemerisVectorTransferBodies.push_back( std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::earthMoonBarycenter) ) ;\n    ephemerisVectorTransferBodies.push_back( std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::venus) );\n    ephemerisVectorTransferBodies.push_back( std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::venus) );\n    ephemerisVectorTransferBodies.push_back( std::make_shared< ephemerides::ApproximatePlanetPositions>(\n                ephemerides::ApproximatePlanetPositionsBase::BodiesWithEphemerisData::mercury) );\n\n    simulation_setup::SystemOfBodies bodies = propagators::setupBodyMapFromUserDefinedEphemeridesForPatchedConicsTrajectory(\n            centralBody[0], bodyToPropagate, transferBodyTrajectory,\n            ephemerisVectorTransferBodies, gravitationalParametersTransferBodies, \"ECLIPJ2000\" );\n\n\n    // Create acceleration map.\n    std::vector< basic_astrodynamics::AccelerationMap > accelerationMap = propagators::setupAccelerationMapPatchedConicsTrajectory(\n                transferBodyTrajectory.size(), centralBody[0], bodyToPropagate, bodies);\n\n    // Calculate the patched conics solution and the propagation results of the associated full dynamics problem for each leg.\n    std::map< int, std::map< double, Eigen::Vector6d > > patchedConicsTrajectory;\n    std::map< int, std::map< double, Eigen::Vector6d > > fullProblemTrajectory;\n    std::map< int, std::map< double, Eigen::VectorXd > > dependentVariablesTrajectory;\n\n    propagators::fullPropagationPatchedConicsTrajectory(\n                bodies, accelerationMap, transferBodyTrajectory, centralBody[0], bodyToPropagate,\n            legTypeVector, variableVector, minimumPericenterRadii, semiMajorAxes, eccentricities, integratorSettings,\n            patchedConicsTrajectory, fullProblemTrajectory, dependentVariablesTrajectory, false );\n\n\n    for( auto itr : patchedConicsTrajectory )\n    {\n        std::cout << \"Leg \" << itr.first << \"\\n\\n\";\n        std::cout << \"Departure: \" << fullProblemTrajectory[ itr.first ].begin( )->second -\n                  patchedConicsTrajectory[ itr.first ].begin( )->second<< \"\\n\\n\";\n        std::cout << \"Arrival: \" << fullProblemTrajectory[ itr.first ].rbegin( )->second -\n                     patchedConicsTrajectory[ itr.first ].rbegin( )->second << \"\\n\\n\";\n    }\n\n\n\n    /// Perturbed case\n\n    // Define accelerations acting on the spacecraft.\n    std::map< std::string, std::vector< std::shared_ptr< simulation_setup::AccelerationSettings > > > bodyToPropagateAccelerations;\n    bodyToPropagateAccelerations[ \"Sun\" ].push_back(std::make_shared< simulation_setup::AccelerationSettings >(\n                                                                basic_astrodynamics::central_gravity ) );\n    bodyToPropagateAccelerations[ \"Earth\" ].push_back(std::make_shared< simulation_setup::AccelerationSettings >(\n                                                                basic_astrodynamics::central_gravity ) );\n    bodyToPropagateAccelerations[ \"Venus\" ].push_back(std::make_shared< simulation_setup::AccelerationSettings >(\n                                                                basic_astrodynamics::central_gravity ) );\n    bodyToPropagateAccelerations[ \"Mercury\" ].push_back(std::make_shared< simulation_setup::AccelerationSettings >(\n                                                                basic_astrodynamics::central_gravity ) );\n    simulation_setup::SelectedAccelerationMap accelerationMapPerturbedCase;\n    accelerationMapPerturbedCase[ \"spacecraft\" ] = bodyToPropagateAccelerations;\n\n\n    // Create the acceleration map.\n    basic_astrodynamics::AccelerationMap accelerationModelMapPerturbedCase = simulation_setup::createAccelerationModelsMap(\n                bodies, accelerationMapPerturbedCase, {bodyToPropagate}, {centralBody} );\n    std::vector<  basic_astrodynamics::AccelerationMap > accelerationMapVectorPerturbedCase;\n    for (int i = 0 ; i < numberOfLegs ; i++){\n        accelerationMapVectorPerturbedCase.push_back( accelerationModelMapPerturbedCase );\n    }\n\n\n    // Calculate the patched conics trajectory and propagate the full dynamics problem jointly.\n    std::map< int, std::map< double, Eigen::Vector6d > > patchedConicsTrajectoryPerturbedCase;\n    std::map< int, std::map< double, Eigen::Vector6d > > fullProblemTrajectoryPerturbedCase;\n    std::map< int, std::map< double, Eigen::VectorXd > > dependentVariablesPerturbedCase;\n\n    propagators::fullPropagationPatchedConicsTrajectory( bodies, accelerationMapVectorPerturbedCase,\n            transferBodyTrajectory, centralBody[0], bodyToPropagate, legTypeVector, variableVector, minimumPericenterRadii,\n            semiMajorAxes, eccentricities, integratorSettings, patchedConicsTrajectoryPerturbedCase,\n            fullProblemTrajectoryPerturbedCase, dependentVariablesPerturbedCase, true );\n\n    for( auto itr : patchedConicsTrajectoryPerturbedCase )\n    {\n        std::cout << \"Leg \" << itr.first << \"\\n\\n\";\n        std::cout << \"Departure: \" << fullProblemTrajectoryPerturbedCase[ itr.first ].begin( )->second -\n                  patchedConicsTrajectoryPerturbedCase[ itr.first ].begin( )->second<< \"\\n\\n\";\n        std::cout << \"Arrival: \" << fullProblemTrajectoryPerturbedCase[ itr.first ].rbegin( )->second -\n                     patchedConicsTrajectoryPerturbedCase[ itr.first ].rbegin( )->second << \"\\n\\n\";\n    }\n\n\n\n\n    /// Outputs\n\n    for( std::map< int, std::map< double, Eigen::Vector6d > >::iterator itr = patchedConicsTrajectory.begin( );\n         itr != patchedConicsTrajectory.end( ); itr++ ){\n\n        input_output::writeDataMapToTextFile( fullProblemTrajectory[itr->first],\n                                              \"fullProblemInterplanetaryTrajectory_0_leg_\" + std::to_string(itr->first) + \".dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n\n        input_output::writeDataMapToTextFile( fullProblemTrajectoryPerturbedCase[itr->first],\n                                              \"fullProblemInterplanetaryTrajectory_1_leg_\" + std::to_string(itr->first) + \".dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n\n        input_output::writeDataMapToTextFile( patchedConicsTrajectory[itr->first],\n                                              \"patchedConicsInterplanetaryTrajectory_0_leg_\" + std::to_string(itr->first) + \".dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n\n        input_output::writeDataMapToTextFile( patchedConicsTrajectoryPerturbedCase[itr->first],\n                                              \"patchedConicsInterplanetaryTrajectory_1_leg_\" + std::to_string(itr->first) + \".dat\",\n                                              tudat_applications::getOutputPath( ),\n                                              \"\",\n                                              std::numeric_limits< double >::digits10,\n                                              std::numeric_limits< double >::digits10,\n                                              \",\" );\n\n    }\n\n\n    // Final statement.\n    // The exit code EXIT_SUCCESS indicates that the program was successfully executed.\n    return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "a4dc4747818077328168820eeeb13598bb635ed8", "size": 14163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tudat/satellite_propagation/fullPropagationMga.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tudat/satellite_propagation/fullPropagationMga.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tudat/satellite_propagation/fullPropagationMga.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.0449438202, "max_line_length": 145, "alphanum_fraction": 0.6714679093, "num_tokens": 3334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593171945417, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.2148139913206746}}
{"text": "#include <iostream>\n#include <cstdlib>\n#include <cmath>\n#include <boost/pending/disjoint_sets.hpp>\n#include <vector>\n#include <queue>\n#include <map>\n#include <cstdio>\n#include <cstddef>\n#include <cstdint>\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\n\ntemplate <class T>\nclass AffinityGraphCompare{\n    private:\n        const T * mEdgeWeightArray;\n    public:\n        AffinityGraphCompare(const T * EdgeWeightArray){\n            mEdgeWeightArray = EdgeWeightArray;\n        }\n        bool operator() (const int& ind1, const int& ind2) const {\n            return (mEdgeWeightArray[ind1] > mEdgeWeightArray[ind2]);\n        }\n};\n\n/*\n * Compute the MALIS loss function and its derivative wrt the affinity graph\n * MAXIMUM spanning tree\n * Author: Srini Turaga (sturaga@mit.edu)\n * All rights reserved\n */\nvoid preCompute(const uint64_t* conn_dims, const int32_t* nhood_data, const uint64_t* nhood_dims,\n        uint64_t* pre_ve, uint64_t* pre_prodDims, int32_t* pre_nHood){\n\n  uint64_t conn_num_dims = nhood_dims[1]+1; //4\n  // nVert stores (x * y * z)\n  uint64_t nVert = 1;\n  for (int64_t i = 1; i < conn_num_dims; ++i) {\n      nVert *= conn_dims[i];\n  }\n  pre_ve[0] = nVert;\n  /* get number of edges */\n  uint64_t nEdge = 0;\n  // Loop over #edges\n  for (int d = 0, i = 0; d < conn_dims[0]; ++d) {\n    // Loop over Z\n    for (int z = 0; z < conn_dims[1]; ++z) {\n      // Loop over Y\n      for (int y = 0; y < conn_dims[2]; ++y) {\n        // Loop over X\n        for (int x = 0; x < conn_dims[3]; ++x, ++i) {\n          // Out-of-bounds check:\n          if (!((z + nhood_data[d * nhood_dims[1] + 0] < 0)\n              ||(z + nhood_data[d * nhood_dims[1] + 0] >= conn_dims[1])\n              ||(y + nhood_data[d * nhood_dims[1] + 1] < 0)\n              ||(y + nhood_data[d * nhood_dims[1] + 1] >= conn_dims[2])\n              ||(x + nhood_data[d * nhood_dims[1] + 2] < 0)\n              ||(x + nhood_data[d * nhood_dims[1] + 2] >= conn_dims[3]))) {\n              ++nEdge;\n          }\n        }\n      }\n    }\n  }\n  pre_ve[1] = nEdge;\n\n  // prodDims stores x, x*y, x*y*z offsets\n  pre_prodDims[conn_num_dims - 2] = 1;\n  for (int64_t i = 1; i < conn_num_dims - 1; ++i) {\n      pre_prodDims[conn_num_dims - 2 - i] = pre_prodDims[conn_num_dims - 1 - i]\n                                      * conn_dims[conn_num_dims - i];\n  }\n\n  /* convert n-d offset vectors into linear array offset scalars */\n  // nHood is a vector of size #edges\n    for (int64_t i = 0; i < nhood_dims[0]; ++i) {\n        pre_nHood[i] = 0;\n        for (int64_t j = 0; j < nhood_dims[1]; ++j) {\n            pre_nHood[i] += nhood_data[j + i * nhood_dims[1]] * pre_prodDims[j];\n        }\n    }\n}\n\nconst std::vector<int64_t> & initPqueue(const int64_t nEdge,\n               const uint64_t* conn_dims, const int32_t* nhood_data, const uint64_t* nhood_dims ){\n    static std::vector<int64_t> pqueue;\n    if(pqueue.empty()){\n        // initialization\n        pqueue.resize(nEdge);\n        int j = 0;\n          // Loop over #edges\n          for (int d = 0, i = 0; d < conn_dims[0]; ++d) {\n            // Loop over Z\n            for (int z = 0; z < conn_dims[1]; ++z) {\n              // Loop over Y\n              for (int y = 0; y < conn_dims[2]; ++y) {\n                // Loop over X\n                for (int x = 0; x < conn_dims[3]; ++x, ++i) {\n                  // Out-of-bounds check:\n                  if (!((z + nhood_data[d * nhood_dims[1] + 0] < 0)\n                      ||(z + nhood_data[d * nhood_dims[1] + 0] >= conn_dims[1])\n                      ||(y + nhood_data[d * nhood_dims[1] + 1] < 0)\n                      ||(y + nhood_data[d * nhood_dims[1] + 1] >= conn_dims[2])\n                      ||(x + nhood_data[d * nhood_dims[1] + 2] < 0)\n                      ||(x + nhood_data[d * nhood_dims[1] + 2] >= conn_dims[3]))) {\n                        pqueue[j++] = i;\n                  }\n                }\n              }\n            }\n          }\n        }\n    return pqueue;\n}\n\nvoid malis_loss_weights_cpp_both(const uint64_t* seg,\n               const uint64_t* conn_dims, const int32_t* nhood_data, const uint64_t* nhood_dims,\n               const float* edgeWeight,\n               float* nPairPerEdge,\n               const uint64_t* pre_ve, const uint64_t* pre_prodDims, const int32_t* pre_nHood, \n               const int pos, const float weight_opt){\n\n    /* Disjoint sets and sparse overlap vectors */\n    const uint64_t nVert = pre_ve[0];\n    const uint64_t nEdge = pre_ve[1];\n    uint64_t conn_num_dims = nhood_dims[1]+1;\n    \n    vector<map<uint64_t,uint64_t> > overlap(nVert);\n    vector<uint64_t> rank(nVert);\n    vector<uint64_t> parent(nVert);\n    boost::disjoint_sets<uint64_t*, uint64_t*> dsets(&rank[0],&parent[0]);\n    std::map<int64_t, int64_t> segSizes;\n    uint64_t nLabeledVert = 0;\n    uint64_t nPairPos = 0;\n    // int mm=0;\n    for (int i=0; i<nVert; ++i){\n        dsets.make_set(i);\n        if (0!=seg[i]) {\n            overlap[i].insert(pair<uint64_t,uint64_t>(seg[i],1));\n            ++nLabeledVert;\n            ++segSizes[seg[i]];\n            nPairPos += (segSizes[seg[i]] - 1); //add pair with previous seg label\n            //if(seg[i]>mm){mm=seg[i];}\n        }\n    }\n\n    // for (int i=0; i<=mm; ++i){std::cout<<segSizes[i]<<\",\";}std::cout<<std::endl;\n    float nPairPosNormInv;\n    if (pos==1){\n        nPairPosNormInv = 1.0/(float)nPairPos;\n    }else{\n        nPairPosNormInv = 1.0/(nLabeledVert*(nLabeledVert-1)*0.5-nPairPos);\n    }\n    //std::cout<<nLabeledVert<<\"hh: \"<<nLabeledVert*(nLabeledVert-1)*0.5<<\",\"<<nPairPos<<std::endl;\n    if(weight_opt<=1){\n        if (pos==1){\n            nPairPosNormInv *= weight_opt;\n        }else{\n            nPairPosNormInv *= (1-weight_opt);\n        }\n    }\n    //std::cout<<\"norm:\"<<nPairPosNormInv<<\"\\n\";\n\n    /* 2. Sort all the edges in increasing order of weight */\n    const std::vector<int64_t> Pqueue1 = initPqueue(nEdge, conn_dims, nhood_data, nhood_dims);\n    static std::vector<int64_t> Pqueue2(nEdge);\n    std::copy(Pqueue1.begin(), Pqueue1.end(), Pqueue2.begin());\n   \n    sort( Pqueue2.begin(), Pqueue2.end(), AffinityGraphCompare<float>( edgeWeight ) );\n\n    /* Start MST */\n    uint64_t minEdge, e, v1, v2;\n    uint64_t set1, set2;\n    float nPair = 0;\n    map<uint64_t,uint64_t>::iterator it1, it2;\n\n    //std::ofstream db;\n    //if(pos==1){ db.open(\"/n/coxfs01/donglai/malis_trans/db/mst-pt-pos.txt\");}\n    float ll=0;\n    /* Start Kruskal's */\n    for (uint64_t i = 0; i < Pqueue2.size(); ++i ) {\n        minEdge = Pqueue2[i];\n        // std::cout <<\"do:\"<<i<<\",\"<<minEdge<< \"\\n\";\n        e =  minEdge / nVert;\n        // v1: node at edge beginning\n        v1 = minEdge % nVert;\n        // v2: neighborhood node at edge e\n        v2 = v1 + pre_nHood[e];\n        set1 = dsets.find_set(v1);\n        set2 = dsets.find_set(v2);\n        if (set1!=set2){\n            dsets.link(set1, set2);\n            /* compute the number of pairs merged by this MST edge */\n            for (it1 = overlap[set1].begin();\n                    it1 != overlap[set1].end(); ++it1) {\n                for (it2 = overlap[set2].begin();\n                        it2 != overlap[set2].end(); ++it2) {\n                    nPair = (float)(it1->second * it2->second);\n                    if ((pos==1 && it1->first == it2->first) || (pos==0 && it1->first != it2->first)) { //pos\n                        nPairPerEdge[minEdge] += nPairPosNormInv * nPair;\n                        //if (pos==1){db <<minEdge<<\",\"<<edgeWeight[minEdge]<<\",\"<<v1<<\",\"<<v2<<\",\"<<nPair << \"\\n\";}\n                        // if (pos==1){ll+=nPairPosNormInv *(1-edgeWeight[minEdge])*(1-edgeWeight[minEdge])*nPair;db <<minEdge<<\",\"<<ll << \",\"<<edgeWeight[minEdge]<<\",\" <<nPairPosNormInv << \"\\n\";}\n                    }\n                }\n            }\n            /* move the pixel bags of the non-representative to the representative */\n            if (dsets.find_set(set1) == set2) // make set1 the rep to keep and set2 the rep to empty\n                swap(set1,set2);\n            it2 = overlap[set2].begin();\n            while (it2 != overlap[set2].end()) {\n                it1 = overlap[set1].find(it2->first);\n                if (it1 == overlap[set1].end()) {\n                    overlap[set1].insert(pair<uint64_t,uint64_t>(it2->first,it2->second));\n                } else {\n                    it1->second += it2->second;\n                }\n                overlap[set2].erase(it2++);\n            }\n        } // end link\n    } // end while\n    // if(pos==1){ db.close();}\n}\n\n// for a given segmentation map (if not all 0), there are two cases:\n// 1. only positive edges: single segmentation label\n// 2. both positive and negative edges\nvoid malis_loss_weights_cpp_pre(const uint64_t* seg,\n               const uint64_t* conn_dims, const int32_t* nhood_data, const uint64_t* nhood_dims,\n               const float* edgeWeight,\n               float* nPairPerEdge,\n               const uint64_t* pre_ve, const uint64_t* pre_prodDims, const int32_t* pre_nHood, const int pos){\n\n    /* Disjoint sets and sparse overlap vectors */\n    const int64_t nVert = pre_ve[0];\n    const int64_t nEdge = pre_ve[1];\n    uint64_t conn_num_dims = nhood_dims[1]+1;\n    \n    vector<map<uint64_t,uint64_t> > overlap(nVert);\n    vector<uint64_t> rank(nVert);\n    vector<uint64_t> parent(nVert);\n    boost::disjoint_sets<uint64_t*, uint64_t*> dsets(&rank[0],&parent[0]);\n    std::map<int64_t, int64_t> segSizes;\n    int nLabeledVert = 0;\n    int nPairPos = 0;\n    for (int i=0; i<nVert; ++i){\n        dsets.make_set(i);\n        if (0!=seg[i]) {\n            overlap[i].insert(pair<uint64_t,uint64_t>(seg[i],1));\n            ++nLabeledVert;\n            ++segSizes[seg[i]];\n            nPairPos += (segSizes[seg[i]] - 1); //add pair with previous seg label\n        }\n    }\n\n    float nPairPosNormInv;\n    if (pos==1){\n        nPairPosNormInv = 1.0/(float)nPairPos;\n    }else{\n        nPairPosNormInv = 1.0/(nLabeledVert*(nLabeledVert-1)*0.5-nPairPos);\n    }\n    //std::cout<<\"norm:\"<<nPairPosNormInv<<\"\\n\";\n\n    /* 2. Sort all the edges in increasing order of weight */\n    const std::vector<int64_t> Pqueue1 = initPqueue(nEdge, conn_dims, nhood_data, nhood_dims);\n    static std::vector<int64_t> Pqueue2(nEdge);\n    std::copy(Pqueue1.begin(), Pqueue1.end(), Pqueue2.begin());\n   \n    sort( Pqueue2.begin(), Pqueue2.end(), AffinityGraphCompare<float>( edgeWeight ) );\n\n    /* Start MST */\n    int minEdge, e, v1, v2;\n    uint64_t set1, set2;\n    float nPair = 0;\n    map<uint64_t,uint64_t>::iterator it1, it2;\n\n    //std::ofstream db;\n    //if(pos==1){ db.open(\"/n/coxfs01/donglai/malis_trans/db/mst-pt-pos.txt\");}\n    float ll=0;\n    /* Start Kruskal's */\n    for (unsigned int i = 0; i < Pqueue2.size(); ++i ) {\n        minEdge = Pqueue2[i];\n        // std::cout <<\"do:\"<<i<<\",\"<<minEdge<< \"\\n\";\n        e =  minEdge / nVert;\n        // v1: node at edge beginning\n        v1 = minEdge % nVert;\n        // v2: neighborhood node at edge e\n        v2 = v1 + pre_nHood[e];\n        set1 = dsets.find_set(v1);\n        set2 = dsets.find_set(v2);\n        if (set1!=set2){\n            dsets.link(set1, set2);\n            /* compute the number of pairs merged by this MST edge */\n            for (it1 = overlap[set1].begin();\n                    it1 != overlap[set1].end(); ++it1) {\n                for (it2 = overlap[set2].begin();\n                        it2 != overlap[set2].end(); ++it2) {\n                    nPair = (float)(it1->second * it2->second);\n                    if ((pos==1 && it1->first == it2->first) || (pos==0 && it1->first != it2->first)) { //pos\n                        nPairPerEdge[minEdge] += nPairPosNormInv * nPair;\n                        //if (pos==1){db <<minEdge<<\",\"<<edgeWeight[minEdge]<<\",\"<<v1<<\",\"<<v2<<\",\"<<nPair << \"\\n\";}\n                        // if (pos==1){ll+=nPairPosNormInv *(1-edgeWeight[minEdge])*(1-edgeWeight[minEdge])*nPair;db <<minEdge<<\",\"<<ll << \",\"<<edgeWeight[minEdge]<<\",\" <<nPairPosNormInv << \"\\n\";}\n                    }\n                }\n            }\n            /* move the pixel bags of the non-representative to the representative */\n            if (dsets.find_set(set1) == set2) // make set1 the rep to keep and set2 the rep to empty\n                swap(set1,set2);\n            it2 = overlap[set2].begin();\n            while (it2 != overlap[set2].end()) {\n                it1 = overlap[set1].find(it2->first);\n                if (it1 == overlap[set1].end()) {\n                    overlap[set1].insert(pair<uint64_t,uint64_t>(it2->first,it2->second));\n                } else {\n                    it1->second += it2->second;\n                }\n                overlap[set2].erase(it2++);\n            }\n        } // end link\n    } // end while\n    // if(pos==1){ db.close();}\n}\n\nvoid malis_loss_weights_cpp(const uint64_t* seg,\n               const uint64_t* conn_dims, const int32_t* nhood_data, const uint64_t* nhood_dims,\n               const float* edgeWeight,\n               const int pos,\n               float* nPairPerEdge){\n\n  uint64_t conn_num_dims = nhood_dims[1]+1;\n  /* Cache for speed to access neighbors */\n  // nVert stores (x * y * z)\n  int64_t nVert = 1;\n  for (int64_t i = 1; i < conn_num_dims; ++i) {\n      nVert *= conn_dims[i];\n  }\n\n  // prodDims stores x, x*y, x*y*z offsets\n  std::vector<int64_t> prodDims(conn_num_dims - 1);\n  prodDims[conn_num_dims - 2] = 1;\n  for (int64_t i = 1; i < conn_num_dims - 1; ++i) {\n      prodDims[conn_num_dims - 2 - i] = prodDims[conn_num_dims - 1 - i]\n                                      * conn_dims[conn_num_dims - i];\n  }\n\n  /* convert n-d offset vectors into linear array offset scalars */\n  // nHood is a vector of size #edges\n    std::vector<int32_t> nHood(nhood_dims[0]);\n    for (int64_t i = 0; i < nhood_dims[0]; ++i) {\n        nHood[i] = 0;\n        for (int64_t j = 0; j < nhood_dims[1]; ++j) {\n            nHood[i] += (int32_t) nhood_data[j + i * nhood_dims[1]] * prodDims[j];\n        }\n    }\n\n    /* Disjoint sets and sparse overlap vectors */\n    vector<map<uint64_t,uint64_t> > overlap(nVert);\n    vector<uint64_t> rank(nVert);\n    vector<uint64_t> parent(nVert);\n    boost::disjoint_sets<uint64_t*, uint64_t*> dsets(&rank[0],&parent[0]);\n    std::map<int64_t, int64_t> segSizes;\n    int nLabeledVert = 0;\n    int nPairPos = 0;\n    for (int i=0; i<nVert; ++i){\n        dsets.make_set(i);\n        if (0!=seg[i]) {\n            overlap[i].insert(pair<uint64_t,uint64_t>(seg[i],1));\n            ++nLabeledVert;\n            ++segSizes[seg[i]];\n            nPairPos += (segSizes[seg[i]] - 1); //add pair with previous seg label\n        }\n    }\n\n    int nPairTot = (nLabeledVert * (nLabeledVert - 1)) / 2;\n    int nPairNeg = nPairTot - nPairPos;\n    float nPairNormR;\n    if(pos==1){\n        nPairNormR = (float)nPairPos;\n    }else{\n        nPairNormR = (float)nPairNeg;\n    }\n\n    if (nPairNormR ==0){\n        return;\n    }else{\n        nPairNormR = 1.0/nPairNormR;\n    }\n    /* get number of edges */\n  int nEdge = 0;\n  // Loop over #edges\n  for (int d = 0, i = 0; d < conn_dims[0]; ++d) {\n    // Loop over Z\n    for (int z = 0; z < conn_dims[1]; ++z) {\n      // Loop over Y\n      for (int y = 0; y < conn_dims[2]; ++y) {\n        // Loop over X\n        for (int x = 0; x < conn_dims[3]; ++x, ++i) {\n          // Out-of-bounds check:\n          if (!((z + nhood_data[d * nhood_dims[1] + 0] < 0)\n              ||(z + nhood_data[d * nhood_dims[1] + 0] >= conn_dims[1])\n              ||(y + nhood_data[d * nhood_dims[1] + 1] < 0)\n              ||(y + nhood_data[d * nhood_dims[1] + 1] >= conn_dims[2])\n              ||(x + nhood_data[d * nhood_dims[1] + 2] < 0)\n              ||(x + nhood_data[d * nhood_dims[1] + 2] >= conn_dims[3]))) {\n              ++nEdge;\n          }\n        }\n      }\n    }\n  }\n    /* Sort all the edges in increasing order of weight */\n    std::vector< int > pqueue( nEdge );\n    int j = 0;\n      // Loop over #edges\n      for (int d = 0, i = 0; d < conn_dims[0]; ++d) {\n        // Loop over Z\n        for (int z = 0; z < conn_dims[1]; ++z) {\n          // Loop over Y\n          for (int y = 0; y < conn_dims[2]; ++y) {\n            // Loop over X\n            for (int x = 0; x < conn_dims[3]; ++x, ++i) {\n              // Out-of-bounds check:\n              if (!((z + nhood_data[d * nhood_dims[1] + 0] < 0)\n                  ||(z + nhood_data[d * nhood_dims[1] + 0] >= conn_dims[1])\n                  ||(y + nhood_data[d * nhood_dims[1] + 1] < 0)\n                  ||(y + nhood_data[d * nhood_dims[1] + 1] >= conn_dims[2])\n                  ||(x + nhood_data[d * nhood_dims[1] + 2] < 0)\n                  ||(x + nhood_data[d * nhood_dims[1] + 2] >= conn_dims[3]))) {\n                    pqueue[j++] = i;\n              }\n            }\n          }\n        }\n      }\n    pqueue.resize(j);\n    sort( pqueue.begin(), pqueue.end(), AffinityGraphCompare<float>( edgeWeight ) );\n\n    /* Start MST */\n    int minEdge, e, v1, v2;\n    uint64_t set1, set2;\n    float nPair = 0;\n    map<uint64_t,uint64_t>::iterator it1, it2;\n\n    /* Start Kruskal's */\n    // std::ofstream db;\n    // db.open(\"/n/coxfs01/donglai/malis_trans/db/mst-pt.txt\");\n    \n    //std::cout<<\"hi:\"<<std::endl;for (unsigned int i = 0; i < pqueue.size(); ++i ) {std::cout<<i<<\",\";}\n    for (unsigned int i = 0; i < pqueue.size(); ++i ) {\n        minEdge = pqueue[i];\n        e =  minEdge / nVert;\n        // v1: node at edge beginning\n        v1 = minEdge % nVert;\n        // v2: neighborhood node at edge e\n        v2 = v1 + nHood[e];\n\n        set1 = dsets.find_set(v1);\n        set2 = dsets.find_set(v2);\n\n        if (set1!=set2){\n            dsets.link(set1, set2);\n\n            /* compute the number of pairs merged by this MST edge */\n            for (it1 = overlap[set1].begin();\n                    it1 != overlap[set1].end(); ++it1) {\n                for (it2 = overlap[set2].begin();\n                        it2 != overlap[set2].end(); ++it2) {\n\n                    nPair = (float)(it1->second * it2->second);\n\n                    if (pos>0 && (it1->first == it2->first)) {\n                        nPairPerEdge[minEdge] += nPairNormR * nPair;\n                        //db <<minEdge<<\",\"<<edgeWeight[minEdge]<<\",\"<<v1<<\",\"<<v2<<\",\"<<nPair << \"\\n\";\n                    } else if ((pos==0) && (it1->first != it2->first)) {\n                        nPairPerEdge[minEdge] += nPairNormR * nPair;\n                    }\n                }\n            }\n\n            /* move the pixel bags of the non-representative to the representative */\n            if (dsets.find_set(set1) == set2) // make set1 the rep to keep and set2 the rep to empty\n                swap(set1,set2);\n\n            it2 = overlap[set2].begin();\n            while (it2 != overlap[set2].end()) {\n                it1 = overlap[set1].find(it2->first);\n                if (it1 == overlap[set1].end()) {\n                    overlap[set1].insert(pair<uint64_t,uint64_t>(it2->first,it2->second));\n                } else {\n                    it1->second += it2->second;\n                }\n                overlap[set2].erase(it2++);\n            }\n        } // end link\n\n    } // end while\n    //db.close();\n}\n\n\n", "meta": {"hexsha": "69fa6f28dd122ff5cb18836be5ca6923fff53f70", "size": 19042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "torch_connectomics/utils/seg/cpp/seg_malis/cpp-malis_core.cpp", "max_stars_repo_name": "aarushgupta/pytorch_connectomics", "max_stars_repo_head_hexsha": "eb90ada14dbd425a741f481761d1ed9ea633e67c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-09-28T02:20:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T18:18:18.000Z", "max_issues_repo_path": "torch_connectomics/utils/seg/cpp/seg_malis/cpp-malis_core.cpp", "max_issues_repo_name": "HoraceKem/pytorch_connectomics", "max_issues_repo_head_hexsha": "2cd4e17b6fa83005a13c1347a01b8b6964e746c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-22T08:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-22T08:49:04.000Z", "max_forks_repo_path": "torch_connectomics/utils/seg/cpp/seg_malis/cpp-malis_core.cpp", "max_forks_repo_name": "HoraceKem/pytorch_connectomics", "max_forks_repo_head_hexsha": "2cd4e17b6fa83005a13c1347a01b8b6964e746c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8568588469, "max_line_length": 196, "alphanum_fraction": 0.516752442, "num_tokens": 5785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.37387581579519075, "lm_q1q2_score": 0.21448448804060383}}
{"text": "/*************************************************************************\nCopyright (c) 2019 Cognitics, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n****************************************************************************/\n\n//#pragma optimize( \"\", off )\n#include <list>\n#include \"sfa/Buffer.h\"\n#include \"sfa/PointMath.h\"\n#include \"sfa/LineString.h\"\n#include \"sfa/Polygon.h\"\n#include \"sfa/PolyhedralSurface.h\"\n#include \"sfa/GeometryCollection.h\"\n#include \"sfa/RingMath.h\"\n#include \"sfa/PointMath.h\"\n#include \"sfa/SegmentIntersector.h\"\n#include \"sfa/BSP.h\"\n#include \"sfa/File.h\"\n#include <cmath>\n#include <fstream>\n#include <boost/foreach.hpp>\n\n#undef min\n#undef max\n\nnamespace sfa {\n\n    const double Buffer::pi = atan(1.0)*4.0;\n\n    void Buffer::addPoint(const Point& point)\n    {\n        if (points.empty())\n            points.push_back(point);\n        else if (points.back() != point)\n            points.push_back(point);\n    }\n\n    void Buffer::closePoints(void)\n    {\n        if (points.size() < 3)\n            return;\n        else if (points.back() != points.front())\n            points.push_back(points.front());\n    }\n\n    void Buffer::addTurn(const Point& p, const Point& p0, const Point& p1, int direction)\n    {\n        double x = p.X();\n        double y = p.Y();\n        double dx0 = p0.X() - p.X();\n        double dy0 = p0.Y() - p.Y();\n        double dx1 = p1.X() - p.X();\n        double dy1 = p1.Y() - p.Y();\n\n        double startAngle = atan2(dy0, dx0);\n        double endAngle = atan2(dy1, dx1);\n        // Check for bad geometry that creates indeterminates.\n        if (startAngle != startAngle)\n        {\n            return;\n        }\n        if (endAngle != endAngle)\n        {\n            return;\n        }\n        if (direction == COUNTERCLOCKWISE)\n        {\n            if (startAngle >= endAngle) startAngle -= 2.0*pi;\n        }\n        else //if (direction == CLOCKWISE)\n        {\n            if (startAngle <= endAngle) startAngle += 2.0*pi;\n        }\n\n        double totalAngle = abs(startAngle - endAngle);\n        int nsegs = int((totalAngle / angle) + 0.5);\n        //Detect overflow caused by bad math (previous div by 0)\n        if (nsegs < (nsegs - 1))\n            return;\n        addPoint(p0);\n        for (int i = 0; i < nsegs - 1; i++)\n        {\n            //    User rotational matrix on initial vector. This is much faster than computing the angle and transforming every time.\n            //    We just need to know which direction to rotate.\n            if (direction == COUNTERCLOCKWISE)\n            {\n                dx1 = cos_angle*dx0 - sin_angle*dy0;\n                dy1 = sin_angle*dx0 + cos_angle*dy0;\n            }\n            else\n            {\n                dx1 = cos_angle*dx0 + sin_angle*dy0;\n                dy1 = -sin_angle*dx0 + cos_angle*dy0;\n            }\n            addPoint(Point(x + dx1, y + dy1));\n            dx0 = dx1;\n            dy0 = dy1;\n        }\n        addPoint(p1);\n    }\n\n    void Buffer::computeOffset(const Point& p0, const Point& p1, Point& o0, Point& o1)\n    {\n        if (p0 == p1)\n        {\n            o0 = p0;\n            o1 = p1;\n            return;\n        }\n        double dx = p1.X() - p0.X();\n        double dy = p1.Y() - p0.Y();\n        double len = sqrt(dx*dx + dy*dy);\n        len = distance / len;\n        //    Compute offset vector\n        double ux = dy * len;\n        double uy = -dx * len;\n        //    Offset points\n        o0.setX(p0.X() + ux);\n        o0.setY(p0.Y() + uy);\n        o1.setX(p1.X() + ux);\n        o1.setY(p1.Y() + uy);\n    }\n\n    void Buffer::addSegment(const Point& p)\n    {\n        s0 = s1;\n        s1 = s2;\n        s2 = p;\n        offset00 = offset10;\n        offset01 = offset11;\n        computeOffset(s1, s2, offset10, offset11);\n\n        if (s1 == s2) return;\n\n        int orientation = CrossProduct(s0, s1, s1, s2);\n\n        if (orientation == 1)        // COUNTERCLOCKWISE turn\n            addTurn(s1, offset01, offset10, COUNTERCLOCKWISE);\n        else if (orientation == -1)    // CLOCKWISE turn\n        {\n            //    Compute intersection\n            Geometry* intersection = NULL;\n            SegmentIntersector::Intersection(&offset00, &offset01, &offset10, &offset11, intersection);\n\n            Point* intPoint = dynamic_cast<Point*>(intersection);\n            if (intPoint)\n                addPoint(*intPoint);\n            else\n            {\n                //    If there is no intersection ,it means the angle is so small and/or the offset so large the segments won't intersect,\n                //    so a temporary inner loop must be created which will be fixed later.\n                if (offset01.distance(&offset10) < distance / 1000.0)\n                    addPoint(offset01);\n                else\n                {\n                    addPoint(offset01);\n                    addPoint(s1);\n                    addPoint(offset10);\n                }\n            }\n\n            if (intersection) delete intersection;\n        }\n        //    else do nothing, the points are collinear\n    }\n\n    void Buffer::addLineEnd(const Point& p0, const Point& p1)\n    {\n        Point right0, right1;\n        Point left0, left1;\n\n        computeOffset(p1, p0, left1, left0);\n        computeOffset(p0, p1, right0, right1);\n\n        switch (end_policy)\n        {\n        case ROUND_ENDS:\n            addTurn(p1, right1, left1, COUNTERCLOCKWISE);\n            break;\n        case FLATTEN_ENDS:\n            addPoint(right1);\n            addPoint(left1);\n            break;\n            //case SQUARE_ENDS:\n            //    TODO\n            //    break;\n        default:\n            break;\n        }\n    }\n\n#define DEBUG_NODE_WITH_ID 0\n#if DEBUG_NODE_WITH_ID\n    static int dbgid = 0;\n#endif\n    class LineDeconvolute\n    {\n        double position_epsilon;\n        class NodeSegment;\n        //Multiple nodes may exist with the same point value, but each unique Node is a different position in the linestring\n        struct Node\n        {\n            Point pt;\n#if DEBUG_NODE_WITH_ID\n            int id;\n#endif\n            std::set<NodeSegment *> segments;//weak, for quick removal from the BSP since it works on pointers\n            std::set<Node *> neighbors;//Weak\n            std::set<Node *> reverse_neighbors;//Weak, to allow quick changes\n            virtual ~Node()\n            {\n            }\n\n            Node(Point _pt)\n            {\n                pt = _pt;\n#if DEBUG_NODE_WITH_ID\n                id = dbgid++;\n#endif\n            }\n\n            bool hasNeighbor(Node *neighbor)\n            {\n                if (this == neighbor)\n                    return false;\n                std::set<Node *>::iterator iter = neighbors.find(neighbor);\n                if (neighbors.end() != iter)\n                {\n                    return true;\n                }\n                return false;\n            }\n\n            void addNeighbor(Node *neighbor)\n            {\n                if (neighbor != this)\n                {\n                    neighbors.insert(neighbor);\n                    //Add myself to the neighbors reverse list\n                    neighbor->reverse_neighbors.insert(this);\n                }\n            }\n            void removeNeighbor(Node *neighbor)\n            {\n                if (neighbor == this)\n                    return;\n                std::set<Node *>::iterator iter = neighbors.find(neighbor);\n                if (neighbors.end() != iter)\n                {\n                    neighbors.erase(iter);\n                }\n                //Update the reverse map\n                iter = neighbor->reverse_neighbors.find(this);\n                if (neighbor->reverse_neighbors.end() != iter)\n                {\n                    neighbor->reverse_neighbors.erase(iter);\n                }\n\n            }\n\n            bool alreadyTraversed(const std::set<Node *> &traversed, Node *n)\n            {\n                return (traversed.find(n) != traversed.end());\n            }\n\n            //Returns true if c is to the right of the line between a and b\n            bool isRight(Point a, Point b, Point c)\n            {\n                double cpval = CrossProduct(a, b, a, c);\n                if (cpval < 0)\n                    return true;\n                /*\n                double val = (b.X() - a.X())*(c.Y() - a.Y()) - (b.Y() - a.Y())*(c.X() - a.X());\n                if (val < 0)\n                    return true;\n                    */\n                return false;\n            }\n\n            //Return the neighboring edge that is the most to the right side of all the other edges\n            //if no neighbors, return NULL\n            Node *findRightMostNeighbor(const std::set<Node *> &traversed)\n            {\n                std::set<Node *>::iterator iter = neighbors.begin();\n                Node *right_most = NULL;\n                bool found_right = false;\n                while (iter != neighbors.end())\n                {\n                    if (alreadyTraversed(traversed, *iter))\n                    {\n                        iter++;\n                        continue;\n                    }\n                    if (!right_most)\n                        right_most = *iter;\n                    else\n                    {\n                        double val = (right_most->pt.X() - pt.X())*((*iter)->pt.Y() - pt.Y()) - (right_most->pt.Y() - pt.Y())*((*iter)->pt.X() - pt.X());\n                        if (val<0)\n                        {\n                            right_most = *iter;\n                            found_right = true;\n                        }\n                        else if (val == 0)\n                        {\n                            double dist = pt.distance2D2(&(*iter)->pt);\n                            double right_most_dist = pt.distance2D2(&right_most->pt);\n                            if (dist < right_most_dist)\n                            {\n                                right_most = *iter;\n                                found_right = true;\n                            }\n                        }\n\n                    }\n                    iter++;\n                }\n                \n                return right_most;                \n            }            \n        };\n\n        class NodeSegment : public sfa::LineString\n        {\n        public:\n            Node *first;//weak\n            Node *second;//weak\n        \n            virtual ~NodeSegment()\n            {\n            }\n\n            NodeSegment(Node *a, Node *b)\n            {\n                first = a;\n                second = b;\n                addPoint(a->pt);\n                addPoint(b->pt);\n            }\n\n        };\n\n        std::set<Node *> frontier;        \n        std::vector<LineString> exteriorRings;\n        std::vector<LineString> interiorRings;\n        \n        std::list<NodeSegment *> segments;\n        BSP bsp;\n        \n        bool Intersection(const Point& p1, const Point& p2, const Point& p3, const Point& p4, Point* &result)\n        {\n            Point u = p2 - p1;\n            Point v = p4 - p3;\n            Point w = p1 - p3;\n\n            double denom = v.X()*u.Y() - v.Y()*u.X();\n\n            if (abs(denom) < SFA_EPSILON)\n                return false;\n\n            double s = (v.Y()*w.X() - v.X()*w.Y()) / denom;\n            if (s < -SFA_EPSILON || s > 1 + SFA_EPSILON) \n                return false;\n            double t = (u.Y()*w.X() - u.X()*w.Y()) / denom;\n            if (t < -SFA_EPSILON || t > 1 + SFA_EPSILON) \n                return false;\n\n            result = new Point(p1 + u*s);\n            return true;\n        }\n\n\n        bool isCounterClockwise(LineString *line)\n        {\n            /**\n              * Sum over the edges, (x2 - x1)(y2 + y1). If the result is positive the curve is clockwise, \n              * if it's negative the curve is counter-clockwise. (The result is twice the enclosed area, with a +/- convention.)\n            **/\n            int numPoints = line->getNumPoints();\n            double sum = 0;\n            for (int i = 1; i < numPoints; i++)\n            {\n                Point p1 = line->getPointN(i - 1);\n                Point p2 = line->getPointN(i);\n                sum += ((p2.X() - p1.X())*(p2.Y() + p1.Y()));\n            }\n            if (sum <= 0)\n                return true;\n            return false;\n        }\n    public:\n\n        sfa::Geometry *getPolygon()\n        {\n            sfa::Polygon *ret = new sfa::Polygon();\n            if (!extractRings())\n            {\n                return ret;\n            }\n\n            std::vector<LineString>::iterator ext_iter = exteriorRings.begin();\n            while (ext_iter != exteriorRings.end())\n            {\n                ret->addRing(*ext_iter++);\n            }\n\n            std::vector<LineString>::iterator int_iter = interiorRings.begin();\n            while (int_iter != interiorRings.end())\n            {\n                ret->addRing(*int_iter++);\n            }\n            return ret;\n        }\n\n        \n\n            struct{\n                bool operator()(const Node *n1, const Node *n2)\n                {\n                    return n1->pt.X() < n2->pt.X();\n                }\n            } customLess;\n\n\n        bool extractRings()\n        {\n            std::set<Node *> traversed;\n            std::set<Node *> nodes = frontier;\n            std::vector<Node *> sorted_nodes;\n            sorted_nodes.insert(sorted_nodes.begin(), frontier.begin(), frontier.end());\n            std::sort(sorted_nodes.begin(), sorted_nodes.end(), customLess);\n\n            //We need to start with an outside point, so we'll use the left most edge\n\n            //pick some random point, and iterate along the left edge until either:\n            //    a) we've iterated over frontier.size() points and found no cycle (wtf?)\n            //        -Return an empty LineString\n            //  b) we come across a node we've already visited\n            //        -Return all the points in the cycle, removing them from the frontier as we collect them\n\n            std::vector<Node *>::iterator iter = sorted_nodes.begin();\n            size_t numNodes = sorted_nodes.size();\n            while (iter != sorted_nodes.end())\n            {\n                Node *n = *iter++;\n                if (traversed.find(n) != traversed.end())\n                    continue;\n                std::vector<Node *> path;\n                path.push_back(n);\n                size_t i = 0;\n                bool found_cycle = false;\n                while (i < numNodes && !found_cycle)\n                {\n                    Node *right = n->findRightMostNeighbor(traversed);\n                    if (right)\n                    {\n                        n = right;\n                    }\n                    else\n                    {\n                        break;\n                    }\n                    // Look to see if we've completed a cycle\n                    for (size_t j = 0, jc = path.size(); j < jc; j++)\n                    {\n                        if (path.at(j) == n)\n                        {\n                            found_cycle = true;\n                            //We have a cycle! from j to (jc-1) + n\n                            LineString ring;\n                            for (size_t k = j; k < jc; k++)\n                            {\n                                ring.addPoint(path.at(k)->pt);\n                                traversed.insert(path.at(k));\n                            }\n                            ring.addPoint(n->pt);//Close the ring\n                            //Only add a true polygon\n                            if (ring.getNumPoints() > 3)\n                            {\n                                bool CCW = isCounterClockwise(&ring);\n\n                                //Add the ring\n                                if (CCW)\n                                    exteriorRings.push_back(ring);\n                                else\n                                    interiorRings.push_back(ring);\n                            }\n                        }\n                        if (found_cycle)\n                            break;\n                    }\n                    if (!found_cycle)\n                        path.push_back(n);\n                    i++;\n                }\n\n            }\n            return exteriorRings.size() > 0;//No exterior ring means failure\n        }\n\n        ~LineDeconvolute()\n        {\n            std::set<Node *>::iterator iter = frontier.begin();\n            while (iter != frontier.end())\n            {\n                Node *n = *iter++;\n                delete n;\n            }\n            frontier.clear();\n            std::list<NodeSegment *>::iterator segiter = segments.begin();\n            while (segiter != segments.end())\n            {\n                delete *segiter++;\n            }\n            segments.clear();\n        }\n\n        typedef std::pair<Node *, Node *> node_pair_t;\n\n        void removePair(std::list<node_pair_t> &plist, node_pair_t &thepair)\n        {\n            std::list<node_pair_t>::iterator iter = plist.begin();\n            while (iter != plist.end())\n            {\n                if (thepair == *iter)\n                {\n                    plist.erase(iter);\n                    return;\n                }\n                iter++;\n            }\n        }\n\n        bool addNeighbor(Node *node, Node *neighbor, std::list<node_pair_t> &segment_pair)\n        {\n            if (node == neighbor)\n                return false;\n            if (node->hasNeighbor(neighbor))\n                return false;\n            //Add \n            node->addNeighbor(neighbor);\n            NodeSegment *seg1 = new NodeSegment(node, neighbor);\n            node->segments.insert(seg1);\n            segments.push_back(seg1);\n            //Add the segment to the BSP\n            sfa::BSPEditVisitor insertEditor;\n            insertEditor.setVisitMode(sfa::INSERT);\n            insertEditor.setEditElement(seg1);\n            insertEditor.visiting(&bsp);\n            segment_pair.push_back(std::make_pair(node, neighbor));\n            return true;\n        }\n\n        bool removeNeighbor(Node *node, Node *neighbor, std::list<node_pair_t> &segment_pair)\n        {\n            //Remove the segment from the BSP\n            std::set<NodeSegment *>::iterator segment_iter = node->segments.begin();\n            while (segment_iter != node->segments.end())\n            {\n                NodeSegment *remove_seg = *segment_iter++;\n                if (remove_seg->second == neighbor)\n                {\n                    sfa::BSPEditVisitor removeEditor;\n                    removeEditor.setVisitMode(sfa::REMOVE);\n                    removeEditor.setEditElement(remove_seg);\n                    removeEditor.visiting(&bsp);\n                }\n            }            \n            node->removeNeighbor(neighbor);\n                        node_pair_t np = std::make_pair(node, neighbor);\n            removePair(segment_pair, np);\n\n            return true;\n        }\n\n        // If node has neighbor 'oldNeighbor', remove oldNeighbor and add newNeighbor\n        bool replaceNeighbor(Node *node, Node *oldNeighbor, Node *newNeighbor, NodeSegment *ns, std::list<node_pair_t> &segment_pair)\n        {\n            if (node == newNeighbor)\n                return false;\n            if (node->hasNeighbor(oldNeighbor))\n            {\n#if DEBUG_NODE_WITH_ID\n                printf(\"Node %d: replacing neighbor of %d with %d\\n\", node->id, oldNeighbor->id, newNeighbor->id);\n#endif\n                addNeighbor(node, newNeighbor,segment_pair);\n                removeNeighbor(node, oldNeighbor, segment_pair);\n                return true;\n            }\n\n            return false;\n\n        }\n\n        void consolidateDuplicateNodes(Node *keepNode, Node *delNode, NodeSegment *ns, std::list<node_pair_t> &segment_pair)\n        {\n#if DEBUG_NODE_WITH_ID\n            printf(\"Consolidating %d into %d\\n\", delNode->id, keepNode->id);\n#endif\n                \n            //Update any node that points to delNode to instead point to keepNode                                \n            std::set<Node *>::iterator f_neighbor_iter = delNode->neighbors.begin();\n            while (f_neighbor_iter != delNode->neighbors.end())\n            {\n                Node *neighbor = *f_neighbor_iter++;\n                removeNeighbor(delNode, neighbor, segment_pair);\n                addNeighbor(keepNode, neighbor, segment_pair);\n            }\n\n            //Update any other node that points to delNode to point to keepNode instead\n            std::set<Node *>::iterator front_iter = delNode->reverse_neighbors.begin();\n            while (front_iter != delNode->reverse_neighbors.end())\n            {\n                Node *f = *front_iter++;\n                removeNeighbor(f, delNode, segment_pair);//Remove delNode from being a neighbor of f                    \n                addNeighbor(f, keepNode, segment_pair);//Add keepNode as a neighbor to f\n            }\n\n        }\n\n        bool PointEqualsEpsilon(sfa::Point *p1, sfa::Point *p2, double epsilon = sfa::SFA_EPSILON)\n        {\n            double deltax = p1->X() - p2->X();\n            double deltay = p1->Y() - p2->Y();\n            double deltaz = p1->Z() - p2->Z();\n            if (deltax == 0 && deltay == 0 )//&& deltaz == 0\n                return true;\n\n            double dist2 = (deltax * deltax) + (deltay*deltay);// +(deltaz*deltaz);\n            if (dist2 < (epsilon*epsilon))\n                return true;\n            return false;\n        }\n        \n        LineDeconvolute(std::vector<Point>& points, const sfa::LineString *refLine, double bufferDist)\n        {\n            //Use a larger epsilon for positional duplication\n            position_epsilon = sfa::SFA_EPSILON * 10;\n#if DEBUG_NODE_WITH_ID\n            dbgid = 0;\n#endif\n            if (points.size() < 3)\n                return;\n            if (points.at(points.size() - 1) != points.at(0))\n                points.push_back(points.at(0));            \n            \n\n            std::list<node_pair_t> segment_pair;\n            //Build the initial 'graph'\n            std::vector<Point>::const_iterator prev = points.begin();\n            if (prev != points.end())\n            {\n                Node *prevNode = new Node(*prev++);\n                Node *firstNode = prevNode;\n                frontier.insert(prevNode);\n                std::vector<Point>::const_iterator iter = prev;\n                while (iter != points.end())\n                {\n                    Node *n = new Node(*iter);                    \n                    frontier.insert(n);\n                    prevNode->addNeighbor(n);\n                    segment_pair.push_back(std::make_pair(prevNode, n));\n                    NodeSegment *seg = new NodeSegment(prevNode, n);\n                    segments.push_back(seg);\n                    prevNode->segments.insert(seg);\n                    bsp.addGeometry(seg);\n                    //printf(\"Node %d connects to %d\\n\", prevNode->id, n->id);\n                    prevNode = n;\n                    iter++;\n                }\n                prevNode->addNeighbor(firstNode);\n                segment_pair.push_back(std::make_pair(prevNode, firstNode));\n                NodeSegment *seg = new NodeSegment(prevNode, firstNode);\n                segments.push_back(seg);\n                prevNode->segments.insert(seg);\n                bsp.addGeometry(seg);\n            }\n\n            {\n                \n                std::set<Node *> traversed;\n                std::set<Node *>::iterator iter = frontier.begin();\n                size_t numNodes = frontier.size();\n                while (iter != frontier.end())\n                {\n                    Node *n = *iter++;\n                    \n                    BSPCollectGeometriesVisitor collector;\n                    collector.setBounds(n->pt.X() - position_epsilon, n->pt.Y() - position_epsilon, n->pt.X() + position_epsilon, n->pt.Y() + position_epsilon);\n                    collector.visiting(&bsp);\n                    std::list<sfa::Geometry *> results = collector.results;\n                    std::list<sfa::Geometry *>::iterator isect_iter = results.begin();\n                    while (!results.empty())\n                    {\n                        sfa::Geometry *result = results.back();\n                        results.pop_back();\n                        NodeSegment *ns = dynamic_cast<NodeSegment*>(result);\n\n                        if (n == ns->first || n == ns->second)\n                            continue;\n                        if (PointEqualsEpsilon(&n->pt, &ns->first->pt, position_epsilon))\n                        {\n                            //If we do this we need to update the geometry of n and all of its nodes in the BSP\n                            //n->pt = (n->pt + ns->first->pt) / 2;\n\n                            consolidateDuplicateNodes(n, ns->first, ns, segment_pair);\n                            \n                            //Requery the bsp now\n                            collector.results.clear();\n                            collector.visiting(&bsp);\n                            results = collector.results;\n                        }\n                        if (PointEqualsEpsilon(&n->pt, &ns->second->pt, position_epsilon))\n                        {\n                            //If we do this we need to update the geometry of n and all of its nodes in the BSP\n                            //n->pt = (n->pt + ns->second->pt) / 2;\n                            consolidateDuplicateNodes(n, ns->second, ns, segment_pair);\n                            //Requery the bsp now\n                            collector.results.clear();\n                            collector.visiting(&bsp);\n                            results = collector.results;\n                        }\n                    }\n                }\n\n            }\n\n            std::map<Geometry *, LineString *> envelopes;\n            bsp.generate(envelopes);\n            //When a pair is broken up, remove that pair from the segment_pair list!\n            while (!segment_pair.empty())\n            {\n                node_pair_t pair = segment_pair.back();\n                segment_pair.pop_back();\n                Node *n = pair.first;\n                Node *neighbor = pair.second;                \n\n                NodeSegment seg1(n, neighbor);\n                BSPCollectGeometriesVisitor collector;\n                sfa::LineString *env = dynamic_cast<sfa::LineString*>(seg1.getEnvelope());\n                sfa::Point *lsMin = dynamic_cast<sfa::Point *>(env->getPointN(0));\n                sfa::Point *lsMax = dynamic_cast<sfa::Point *>(env->getPointN(1));\n                collector.setBounds(lsMin->X(), lsMin->Y(), lsMax->X(), lsMax->Y());\n                delete env;\n                collector.visiting(&bsp);\n                std::list<sfa::Geometry *> results = collector.results;\n\n                std::list<sfa::Geometry *>::iterator isect_iter = results.begin();\n                while (!results.empty())\n                {\n                    sfa::Geometry *result = results.back();\n                    results.pop_back();\n                    NodeSegment *ns = dynamic_cast<NodeSegment*>(result);\n                    Node *f = ns->first;\n                    Node *f_neighbor = ns->second;\n\n                    //seg2 is f and f_neighbor\n                    if (n == f)\n                        continue;\n                    if (n == f_neighbor)\n                        continue;\n                    if (neighbor == f)\n                        continue;\n                    if (f_neighbor == neighbor)\n                        continue;\n                    //We don't want to compare f_neighbor with f or neighbor\n                    if (f->hasNeighbor(n))\n                        continue;\n                    if (f_neighbor->hasNeighbor(neighbor))\n                        continue;\n                    if (f->hasNeighbor(neighbor))\n                        continue;\n#if DEBUG_NODE_WITH_ID\n                    printf(\"testing %d -> %d against %d -> %d\\n\", n->id, neighbor->id, f->id, f_neighbor->id);\n#endif\n                    if (PointEqualsEpsilon(&n->pt, &f_neighbor->pt, position_epsilon))\n                    {\n                        consolidateDuplicateNodes(n, f_neighbor, ns, segment_pair);\n                        //Requery the bsp now\n                        collector.results.clear();\n                        collector.visiting(&bsp);\n                        results = collector.results;\n                        continue;\n                    }\n                    if (PointEqualsEpsilon(&f->pt, &neighbor->pt, position_epsilon))\n                    {\n                        consolidateDuplicateNodes(f, neighbor, ns, segment_pair);\n                        //Neighbor is now f!\n                        neighbor = f;\n                        \n                        //Requery the bsp now\n                        collector.results.clear();\n                        collector.visiting(&bsp);\n                        results = collector.results;\n                        continue;\n                    }\n\n                    // look for an intersection between seg1 and seg2\n                    sfa::Point *ipoint = NULL;\n                    if (Intersection(n->pt, neighbor->pt, f->pt, f_neighbor->pt, ipoint))\n                    {\n                        if (ipoint)\n                        {\n#if DEBUG_NODE_WITH_ID\n                            printf(\"Intersection between %d<-->%d and %d<-->%d\\n\", n->id, neighbor->id, f->id, f_neighbor->id);\n#endif\n                            if (PointEqualsEpsilon(ipoint, &n->pt) || \n                                PointEqualsEpsilon(ipoint, &neighbor->pt) ||\n                                PointEqualsEpsilon(ipoint, &f->pt) ||\n                                PointEqualsEpsilon(ipoint, &f_neighbor->pt))\n                            {\n                                delete ipoint;\n                                continue;\n                            }\n                            // Add the intersection point (int_node) as a node\n                            Node *int_node = new Node(*ipoint);\n                            delete ipoint;\n#if DEBUG_NODE_WITH_ID\n                            if (int_node->id == 39)\n                                printf(\"\");\n                            printf(\"Adding node %d\\n\", int_node->id);\n#endif        \n                            //Add it to the master list of nodes\n                            frontier.insert(int_node);\n                            // Add a neighbor relationship between int_node and (n,neighbor,f,f_neighbor)\n                            if (replaceNeighbor(f, f_neighbor, int_node, ns, segment_pair))\n                            {\n                                //Above we added a node from f -> int_pair, so now we complete it by adding from int_pair to f\n                                addNeighbor(int_node, f_neighbor, segment_pair);                                \n                            }                                \n                            else\n                            {\n                                replaceNeighbor(f_neighbor, f, int_node, ns, segment_pair);\n                                addNeighbor(int_node, f, segment_pair);\n                            }\n\n                            if (replaceNeighbor(n, neighbor, int_node, ns, segment_pair))\n                            {\n                                addNeighbor(int_node, neighbor, segment_pair);                                \n                            }\n                            else\n                            {\n                                replaceNeighbor(neighbor, n, int_node, ns, segment_pair);\n                                addNeighbor(int_node, n, segment_pair);\n                            }\n                                \n                            //Requery the bsp now\n                            collector.results.clear();\n                            collector.visiting(&bsp);\n                            results = collector.results;\n                            break;\n                        }\n                        else\n                        {\n                            //Something broke in Intersection\n                        }\n                    }\n                }\n            }\n            //Iterate over the frontier, and remove any neighbors for any nodes closer than the buffer length from the refLine\n            std::set<Node *>::iterator iter = frontier.begin();\n            while (iter != frontier.end())\n            {\n                Node *n = *iter++;\n                double dist = n->pt.distance(refLine);\n                //This is a magic number (just a number that seems to work reliably), but it's trying to account for the approximation of a circle\n                //that we form with facets of a turn\n                if (dist < (bufferDist *.8))\n                {\n#if DEBUG_NODE_WITH_ID\n                    printf(\"Removing node %d\\n\", n->id);\n#endif\n                    //This node should be removed from the graph (by breaking the links)\n                    //First remove any neighbors I have\n                    std::set<Node *>::iterator niter = n->neighbors.begin();\n                    while (niter != n->neighbors.end())\n                    {\n                        Node *neighbor = *niter++;\n                        n->removeNeighbor(neighbor);\n                    }\n                    //Next update any nodes that have me as a neighbor, to not have me as a neighbor\n                    niter = n->reverse_neighbors.begin();\n                    while (niter != n->reverse_neighbors.end())\n                    {\n                        Node *neighbor = *niter++;\n                        neighbor->removeNeighbor(n);\n                    }\n                }\n            }\n\n#if DEBUG_NODE_WITH_ID\n            if (1)\n            {\n                std::string gvfilename(\"dot.gv\");\n                std::remove(gvfilename.c_str());\n                std::ofstream of(gvfilename.c_str());\n                of << \"digraph {\\n\";\n                std::set<Node *> traversed;\n                std::set<Node *>::iterator iter = frontier.begin();\n                size_t numNodes = frontier.size();\n                while (iter != frontier.end())\n                {\n                    Node *n = *iter++;\n                    //of << \"\\t\\\"\" << n->id << \"\\\"\\n\";\n                    Node *rightmost = n->findRightMostNeighbor(traversed);\n                    //if (rightmost)\n                    //    of << \"\\t\\\"\" << n->id << \"\\\" -> \\\"\" << rightmost->id << \"\\\"\\n\";\n                    std::set<Node *>::iterator niter = n->neighbors.begin();\n                    while (niter != n->neighbors.end())\n                    {\n                        Node *neighbor = *niter++;\n                        if (neighbor == rightmost)\n                        {\n                            of << \"\\t\" << n->id << \" -> \" << neighbor->id << \"[color=red,penwidth=3.0]\\n\";\n                        }\n                        else\n                        {\n                            of << \"\\t\" << n->id << \" -> \" << neighbor->id << \"\\n\";\n                        }\n                    }\n                }\n                of << \"}\\n\";\n            }\n\n\n            if (1)\n            {\n                std::set<Node *> nodes = frontier;\n                FeatureList features;\n                std::set<Node *> traversed;\n                //Write a feature (segment) for each node connection.\n                std::set<Node *>::iterator iter = frontier.begin();\n                size_t numNodes = frontier.size();\n                while (iter != frontier.end())\n                {\n                    Node *n = *iter++;\n\n                    {\n                        sfa::Feature *f = new sfa::Feature;\n                        f->geometry = new sfa::Point(n->pt.X(), n->pt.Y(), 0);\n                        f->attributes.setAttribute(\"nodeid\", n->id);\n                        features.push_back(f);\n                    }\n                    Node *rightmost = n->findRightMostNeighbor(traversed);\n                    if (rightmost)\n                    {\n                        LineString *seg = new LineString;\n                        seg->addPoint(sfa::Point(n->pt.X(), n->pt.Y(), 0));\n                        seg->addPoint(sfa::Point(rightmost->pt.X(),rightmost->pt.Y(),0));\n                        sfa::Feature *f = new sfa::Feature;\n                        f->geometry = seg;\n                        f->attributes.setAttribute(\"nodeid\", n->id);\n                        f->attributes.setAttribute(\"rightmost\", rightmost->id);\n                        features.push_back(f);\n                    }                    \n                }\n                sfa::Feature origFeature;\n                origFeature.attributes.setAttribute(\"name\", \"original\");\n                origFeature.geometry = refLine->copy();\n                features.push_back(&origFeature);\n                sfa::writeSFAFile(features, \"features.sfa\");\n            }\n#endif\n\n        }\n\n        \n\n\n    };\n\n    /*\n    DE_CONVOLUTE\n    ===============================================================================================\n    */\n    Geometry* Buffer::de_convolute(const std::vector<Point>& points)\n    {\n        /*\n        We can detect loops in the convolution by running a ray-tracing backwards when we attemp to add a new Point to the result.\n        If it intersects a previous edge, then the first intersection point acts as the point to \"pinch\" the loop closed.\n        If the loop is found to be counter-clockwise, the loop is excessive and can be discarded, else if it is clockwise, then we\n        should keep the loop and use it as a hole.\n\n        When detecting if an edge intersects the ray, we do not count any intersections that occur at an endpoint of an edge; although,\n        we do count intersections that occur at the start point of an edge.\n\n        Use brute force for now, with queries in linear time.\n        Later implement MonotonicChain to allow optimal log(n) query time.\n        */\n\n        //    Holds the currently processed points to the list\n        std::vector<Point> processed;\n        std::vector< std::vector<Point> > holes;\n\n        //    Find the first point to start on. This must be on the exterior or else problems may ocur, so we just choose the point further in one direction.\n        int start = 0;\n        int rev_start = 0;\n        for (int i = 0; i < int(points.size()); i++)\n        {\n            if (points[start].X() < points[i].X())\n                start = i;\n            if (points[rev_start].X() > points[i].X())\n                rev_start = i;\n        }\n\n        // we want to use a start that is the furthest distance possible from the endpoint\n        int start_dist = std::min(start, int(points.size()) - start);\n        int rev_dist = std::min(rev_start, int(points.size()) - rev_start);\n        if (rev_dist > start_dist)\n            start = rev_start;\n\n\n        processed.push_back(points[start]);\n\n        /*    Itterate through the points and try to add the next point. Shoot a ray back and try to intersect all the edges already added.\n        If there is an intersection, attempt to handle the loop.\n        */\n        for (size_t offset = 1; offset < int(points.size()); offset++)\n        {\n            size_t i = (offset + start) % points.size();\n\n            Point next = points[i];\n            bool intersection = false;\n\n            //    Shoot ray backwards\n            double U[2] = { next.X() - processed.back().X(), next.Y() - processed.back().Y() };\n\n            //    Find s such that next + s*dnext = intersection\n            //    find t such that p1 + t*(p2-p1) = intersection\n            double s;\n            double t;\n\n            //    Index of point after intersection\n            int j;\n            //    CCW or CW\n            bool CCW;\n\n            //    Don't start at the end, start just before the end...we already know that the segment will be intersecting the processed list at the\n            //    previous point by definition.\n            for (j = int(processed.size() - 2); j > 0; j--)\n            {\n                Point p1 = processed[j - 1];\n                Point p2 = processed[j];\n\n                double V[2] = { p2.X() - p1.X(), p2.Y() - p1.Y() };\n                double W[2] = { next.X() - p1.X(), next.Y() - p1.Y() };\n\n                double denom = V[0] * U[1] - V[1] * U[0];\n\n                if (denom == 0)\n                    continue;\n                else\n                {\n                    s = (V[1] * W[0] - V[0] * W[1]) / denom;\n                    t = (U[1] * W[0] - U[0] * W[1]) / denom;\n                }\n\n                if (s > 0 || s < -1)\n                    continue;\n                else if (t < 0 || t > 1)\n                    continue;\n                else\n                {\n                    CCW = (denom < 0);\n                    intersection = true;\n                    //printf(\"Intersection at i=%d j=%d\\n\", i, j);\n                    break;\n                }\n            }\n\n            if (intersection)\n            {\n                Point intPoint(next.X() + s*U[0], next.Y() + s*U[1]);\n\n                if (!CCW)    //    Save loop as a hole\n                {\n                    //    Note that hole will NOT be closed yet\n                    std::vector<Point> hole;\n                    hole.push_back(intPoint);\n                    for (int k = j; k < int(processed.size()); k++)\n                        hole.push_back(processed[k]);\n\n                    holes.push_back(hole);\n                }\n\n                //    Cut away loop from main processed values\n\n                size_t d = processed.size() - j;\n                //printf(\"Cutting %d points from the end\\n\", d);\n                for (size_t k = 0; k < d; k++)\n                    processed.pop_back();\n                //printf(\"Pushing back point at %f %f\\n\", intPoint.X(), intPoint.Y());\n                processed.push_back(intPoint);\n                offset--;\n                continue;\n\n            }\n            else processed.push_back(next);\n        }\n\n        Polygon* result = new Polygon;\n\n        //    Add boundary\n        LineString* boundary = new LineString;\n        for (unsigned int i = 0; i < processed.size(); i++)\n            boundary->addPoint(processed[i]); // create new pointer\n\n        boundary->addPoint(processed[0]); // close\n        result->addRing(boundary);\n\n\n        //    Add holes\n        for (std::vector< std::vector<Point> >::iterator it = holes.begin(); it != holes.end(); ++it)\n        {\n            LineString* hole = new LineString;\n            for (unsigned int i = 0; i < it->size(); i++)\n                hole->addPoint((*it)[i]); // create new pointer\n\n            hole->addPoint((*it)[0]);\n\n            //    Check if interior ring hasn't collapsed\n            double area = GetRingArea(hole);\n            if (area <-SFA_EPSILON)\n                result->addRing(hole);\n        }\n\n        return result;\n    }\n\n    /*\n    Point buffer\n    ===============================================================================================\n    */\n    Geometry* Buffer::bufferPoint(const Geometry* point)\n    {\n        //    You cannot buffer a Point with a negative distance. It results in nothing, so wer return nothing.\n        if (distance < 0) return NULL;\n\n        const Point* p = dynamic_cast<const Point*>(point);\n        LineString* ring = new LineString;\n\n        double dx0, dy0, dx1, dy1;\n        dx0 = distance;\n        dy0 = 0;\n\n        for (unsigned int i = 0; i < 4 * quad_segments; i++)\n        {\n            dx1 = cos_angle*dx0 - sin_angle*dy0;\n            dy1 = sin_angle*dx0 + cos_angle*dy0;\n\n            ring->addPoint(Point(p->X() + dx1, p->Y() + dy1));\n\n            dx0 = dx1;\n            dy0 = dy1;\n        }\n\n        ring->addPoint(*ring->getPointN(0));\n\n        Polygon* poly = new Polygon;\n        poly->addRing(ring);\n        return poly;\n    }\n\n\n\n    /*\n    LineString buffer\n    ===============================================================================================\n    */\n    Geometry* Buffer::bufferLineString(const Geometry* origLine)\n    {\n        sfa::Geometry *geomcopy = origLine->copy();\n        sfa::LineString *line = dynamic_cast<sfa::LineString *>(geomcopy);\n        \n        if (!line)\n        {\n            if (geomcopy)\n                delete geomcopy;\n            return NULL;\n        }\n        line->removeColinearPoints(sfa::SFA_EPSILON);\n\n        if (distance < 0)\n        {\n            if (geomcopy)\n                delete geomcopy;\n            return NULL;\n        }\n\n        points.clear();\n        const LineString* linestring = line;\n\n        int num = linestring->getNumPoints();\n        if (num == 0)\n        {\n            if (geomcopy)\n                delete geomcopy;\n            return NULL;\n        }\n        else if (num == 1)\n            return bufferPoint(linestring->getPointN(0));\n        else if (num == 2)\n        {\n            addLineEnd(*linestring->getPointN(0), *linestring->getPointN(1));\n            addLineEnd(*linestring->getPointN(1), *linestring->getPointN(0));\n        }\n        else\n        {\n            Point next, first;\n\n            //    Move down the line\n            s1 = *linestring->getPointN(0);\n            s2 = *linestring->getPointN(1);\n            computeOffset(s1, s2, offset10, offset11);\n            for (int i = 2; i < num; i++)\n                addSegment(*linestring->getPointN(i));\n\n            //    Add end cap\n            first = *linestring->getPointN(num - 1);\n            for (int i = 2; i <= num; i++)\n            {\n                next = *linestring->getPointN(num - i);\n                if (next != first) break;\n                else if (i == num)\n                {\n                    if (geomcopy)\n                        delete geomcopy;\n                    //    ERROR!! All points of the line are equal!\n                    return NULL;\n                }\n            }\n            addLineEnd(next, first);\n\n            //    Move back up the line\n            s1 = *linestring->getPointN(num - 1);\n            s2 = *linestring->getPointN(num - 2);\n            computeOffset(s1, s2, offset10, offset11);\n            for (int i = num - 3; i >= 0; i--)\n                addSegment(*linestring->getPointN(i));\n\n            //    Add end cap\n            first = *linestring->getPointN(0);\n            for (int i = 1; i <= num; i++)\n            {\n                next = *linestring->getPointN(i);\n                if (next != first) break;\n                else if (i == num)\n                {\n                    if (geomcopy)\n                        delete geomcopy;\n                    //    ERROR!! All point of the line are equal!\n                    return NULL;\n                }\n            }\n\n            addLineEnd(next, first);\n        }\n    \n        LineDeconvolute dc(points, linestring, distance);\n        if (geomcopy)\n            delete geomcopy;\n        sfa::Polygon *ret = dynamic_cast<sfa::Polygon *>(dc.getPolygon());\n        //Return NULL on failure rather than an empty polygon\n        if (ret->isEmpty())\n        {\n            delete ret;\n            ret = NULL;\n        }\n        return ret;\n    }\n\n\n    /*\n    Polygon buffer\n    ===============================================================================================\n    */\n    Geometry* Buffer::bufferPolygon(const Geometry* poly)\n    {\n        bool negativeDistance = distance < 0;\n        distance = abs(distance);\n\n        //    Only supports rounded end policies\n        int backupEndPolicy = end_policy;\n        end_policy = ROUND_ENDS;\n\n        const Polygon* polygon = dynamic_cast<const Polygon*>(poly);\n        Geometry* result = NULL;\n\n        //    Buffer exterior ring\n        Geometry* outerRingBuffer = bufferLineString(polygon->getExteriorRing());\n\n        if (outerRingBuffer)\n        {\n            if (outerRingBuffer->isEmpty())\n                return NULL;\n            Polygon* outerRingBufferPolygon = dynamic_cast<Polygon*>(outerRingBuffer);\n\n            if (negativeDistance) // Use interior rings\n            {\n                int n = outerRingBufferPolygon->getNumInteriorRing();\n                if (n == 1) // Result is a single polygon\n                {\n                    Polygon* polygonResult = new Polygon();\n                    polygonResult->addRing(*outerRingBufferPolygon->getInteriorRingN(0));\n                    polygonResult->reverse();\n                    result = polygonResult;\n                }\n                else if (n>1) // Result is a multi polygon\n                {\n                    MultiPolygon* multiPolygonResult = new MultiPolygon();\n                    for (int i = 0; i<n; i++)\n                    {\n                        Polygon* next = new Polygon();\n                        next->addRing(*outerRingBufferPolygon->getInteriorRingN(i));\n                        next->reverse();\n                        multiPolygonResult->addGeometry(next);\n                    }\n                    result = multiPolygonResult;\n                }\n            }\n            else //    Use exterior rings\n            {\n                Polygon* polygonResult = new Polygon();\n                polygonResult->addRing(*outerRingBufferPolygon->getExteriorRing());\n                result = polygonResult;\n            }\n\n            delete outerRingBuffer;\n        }\n\n        //    Buffer all interior rings and use them as a difference\n        for (int i = 0; i<polygon->getNumInteriorRing(); i++)\n        {\n            if (!result) break;\n\n            Geometry* nextBuffer = bufferLineString(polygon->getInteriorRingN(i));\n            if (nextBuffer)\n            {\n                Polygon* polygonBuffer = dynamic_cast<Polygon*>(nextBuffer);\n\n                if (negativeDistance) // Use exterior ring\n                {\n                    Geometry* temp = result->difference(polygonBuffer->getExteriorRing());\n                    delete result;\n                    result = temp;\n                }\n                else //    Use Interior rings\n                {\n                    for (int j = 0; j<polygonBuffer->getNumInteriorRing(); j++)\n                    {\n                        if (!result) break;\n\n                        Polygon ring;\n                        ring.addRing(*polygonBuffer->getInteriorRingN(j));\n                        ring.reverse();\n                        Geometry* temp = result->difference(&ring);\n                        delete result;\n                        result = temp;\n                    }\n                }\n\n                delete nextBuffer;\n            }\n        }\n\n        //    Restore original settings\n        end_policy = backupEndPolicy;\n        if (negativeDistance) distance *= -1;\n\n        return result;\n    }\n\n    /*\n    PolyhedralSurface buffer\n    ===============================================================================================\n    */\n    Geometry* Buffer::bufferPolyhedralSurface(const Geometry* surface)\n    {\n        const PolyhedralSurface* polyhedralSurface = dynamic_cast<const PolyhedralSurface*>(surface);\n\n        if (union_policy == DISJOINT_RESULTS)\n        {\n            GeometryCollection* result = new GeometryCollection;\n\n            for (int i = 0; i<polyhedralSurface->getNumPatches(); i++)\n            {\n                Geometry* temp = polyhedralSurface->getPatchN(i)->buffer(distance, end_policy, union_policy, quad_segments);\n                if (temp)\n                    result->addGeometry(temp);\n            }\n\n            return result;\n        }\n        else\n        {\n            Geometry* result = NULL;\n\n            for (int i = 0; i<polyhedralSurface->getNumPatches(); i++)\n            {\n                if (result)\n                {\n                    Geometry* geometryBuffer = polyhedralSurface->getPatchN(i)->buffer(distance, end_policy, union_policy, quad_segments);\n                    Geometry* temp = result->Union(geometryBuffer);\n                    delete geometryBuffer;\n                    delete result;\n                    result = temp;\n                }\n                else\n                    result = polyhedralSurface->getPatchN(i)->buffer(distance, end_policy, union_policy, quad_segments);\n            }\n\n            return result;\n        }\n    }\n\n    /*\n    Collection buffer\n    ===============================================================================================\n    */\n    Geometry* Buffer::bufferCollection(const Geometry* collection)\n    {\n        const GeometryCollection* geometryCollection = dynamic_cast<const GeometryCollection*>(collection);\n\n        if (union_policy == DISJOINT_RESULTS)\n        {\n            GeometryCollection* result = new GeometryCollection;\n\n            for (int i = 1; i <= geometryCollection->getNumGeometries(); i++)\n            {\n                Geometry* temp = geometryCollection->getGeometryN(i)->buffer(distance, end_policy, union_policy, quad_segments);\n                if (temp)\n                    result->addGeometry(temp);\n            }\n\n            return result;\n        }\n        else\n        {\n            Geometry* result = NULL;\n\n            for (int i = 1; i <= geometryCollection->getNumGeometries(); i++)\n            {\n                if (result)\n                {\n                    Geometry* geometryBuffer = geometryCollection->getGeometryN(i)->buffer(distance, end_policy, union_policy, quad_segments);\n                    Geometry* temp = result->Union(geometryBuffer);\n                    delete geometryBuffer;\n                    delete result;\n                    result = temp;\n                }\n                else\n                    result = geometryCollection->getGeometryN(i)->buffer(distance, end_policy, union_policy, quad_segments);\n            }\n\n            return result;\n        }\n    }\n\n    /*\n    Geometry buffer\n    ===============================================================================================\n    */\n    Geometry* Buffer::bufferGeometry(const Geometry* geom)\n    {\n        int type = geom->getWKBGeometryType(false, false);\n\n        switch (type)\n        {\n        case (wkbPoint) :\n            return bufferPoint(geom);\n            break;\n        case (wkbLineString) :\n            return bufferLineString(geom);\n            break;\n        case (wkbPolygon) :\n        case (wkbTriangle) :\n                           return bufferPolygon(geom);\n            break;\n        case (wkbMultiPoint) :\n        case (wkbMultiLineString) :\n        case (wkbMultiPolygon) :\n        case (wkbGeometryCollection) :\n                                     return bufferCollection(geom);\n            break;\n        case (wkbPolyhedralSurface) :\n        case (wkbTIN) :\n                      return bufferPolyhedralSurface(geom);\n            break;\n        default:\n            throw std::runtime_error(\"Buffer::apply() Unknown Geometry!\");\n        }\n    }\n\n    //    PUBLIC METHODS ================================================================================\n    //    ===============================================================================================\n\n    Buffer::Buffer(unsigned int quadrantSegments, int endPolicy, int unionPolicy)\n    {\n        end_policy = endPolicy;\n        union_policy = unionPolicy;\n\n        distance = 0;\n\n        if (quadrantSegments < 1) quadrantSegments = 1;\n\n        //    Compute quadrant segment information\n        quad_segments = quadrantSegments;\n        angle = (pi / 2) / quad_segments;\n        sin_angle = sin(angle);\n        cos_angle = cos(angle);\n    }\n\n    int Buffer::getEndPolicy(void) const\n    {\n        return end_policy;\n    }\n\n    void Buffer::setEndPolicy(int policy)\n    {\n        switch (policy)\n        {\n        case ROUND_ENDS:\n        case FLATTEN_ENDS:\n            end_policy = policy;\n            break;\n        default:\n            end_policy = ROUND_ENDS;\n        }\n    }\n\n    int Buffer::getUnionPolicy(void) const\n    {\n        return union_policy;\n    }\n\n    void Buffer::setUnionPolicy(int policy)\n    {\n        switch (policy)\n        {\n        case UNION_RESULTS:\n        case DISJOINT_RESULTS:\n            union_policy = policy;\n            break;\n        default:\n            union_policy = UNION_RESULTS;\n        }\n    }\n\n    Geometry* Buffer::apply(const Geometry* geom, double d)\n    {\n        if (!geom) return NULL;\n        if (d == 0 || geom->isEmpty()) return geom->copy();\n\n        distance = d;\n        return bufferGeometry(geom);\n    }\n\n}\n", "meta": {"hexsha": "eb4f80cd2c2dcb26e98b78f7a25fe551c15c8717", "size": 57394, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cognitics/src/sfa/Buffer.cpp", "max_stars_repo_name": "mikedig/cdb-productivity-api", "max_stars_repo_head_hexsha": "e2bedaa550a8afa780c01f864d72e0aebd87dd5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cognitics/src/sfa/Buffer.cpp", "max_issues_repo_name": "mikedig/cdb-productivity-api", "max_issues_repo_head_hexsha": "e2bedaa550a8afa780c01f864d72e0aebd87dd5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cognitics/src/sfa/Buffer.cpp", "max_forks_repo_name": "mikedig/cdb-productivity-api", "max_forks_repo_head_hexsha": "e2bedaa550a8afa780c01f864d72e0aebd87dd5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4175126904, "max_line_length": 160, "alphanum_fraction": 0.4528870614, "num_tokens": 11598, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3486451488696663, "lm_q1q2_score": 0.2144473969543228}}
{"text": "/*******************************************************************************\n *\n * Generic implementation of non-relational domains.\n *\n * Author: Arnaud J. Venet (arnaud.j.venet@nasa.gov)\n *\n * Notices:\n *\n * Copyright (c) 2011 United States Government as represented by the\n * Administrator of the National Aeronautics and Space Administration.\n * All Rights Reserved.\n *\n * Disclaimers:\n *\n * No Warranty: THE SUBJECT SOFTWARE IS PROVIDED \"AS IS\" WITHOUT ANY WARRANTY OF\n * ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED\n * TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS,\n * ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,\n * OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE\n * ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO\n * THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN\n * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS,\n * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS\n * RESULTING FROM USE OF THE SUBJECT SOFTWARE.  FURTHER, GOVERNMENT AGENCY\n * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE,\n * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT \"AS IS.\"\n *\n * Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST\n * THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL\n * AS ANY PRIOR RECIPIENT.  IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS\n * IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH\n * USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM,\n * RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD\n * HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS,\n * AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW.\n * RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE,\n * UNILATERAL TERMINATION OF THIS AGREEMENT.\n *\n ******************************************************************************/\n\n#pragma once\n\n#include <crab/domains/patricia_trees.hpp>\n#include  <crab/domains/discrete_domains.hpp>\n#include <crab/support/debug.hpp>\n\n#include <boost/optional.hpp>\n\n#include <algorithm>\n#include <set>\n#include <vector>\n\nnamespace ikos {\n\n/* Environment from Key to Value with all lattice operations */ \ntemplate <typename Key, typename Value> class separate_domain {\n\nprivate:\n  using patricia_tree_t = patricia_tree<Key, Value>;\n  using unary_op_t = typename patricia_tree_t::unary_op_t;\n  using binary_op_t = typename patricia_tree_t::binary_op_t;\n  using partial_order_t = typename patricia_tree_t::partial_order_t;\n\npublic:\n  using separate_domain_t = separate_domain<Key, Value>;\n  using iterator = typename patricia_tree_t::iterator;\n  using key_type = Key;\n  using value_type = Value;\n\nprivate:\n  bool _is_bottom;\n  patricia_tree_t _tree;\n\npublic:\n  class join_op : public binary_op_t {\n    std::pair<bool, boost::optional<Value>> apply(Value x, Value y) {\n      Value z = x.operator|(y);\n      if (z.is_top()) {\n        return {false, boost::optional<Value>()};\n      } else {\n        return {false, boost::optional<Value>(z)};\n      }\n    };\n\n    bool default_is_absorbing() { return true; }\n  }; // class join_op\n\n  class widening_op : public binary_op_t {\n    std::pair<bool, boost::optional<Value>> apply(Value x, Value y) {\n      Value z = x.operator||(y);\n      if (z.is_top()) {\n        return {false, boost::optional<Value>()};\n      } else {\n        return {false, boost::optional<Value>(z)};\n      }\n    };\n\n    bool default_is_absorbing() { return true; }\n\n  }; // class widening_op\n\n  template <typename Thresholds>\n  class widening_thresholds_op : public binary_op_t {\n    const Thresholds &m_ts;\n\n  public:\n    widening_thresholds_op(const Thresholds &ts) : m_ts(ts) {}\n\n    std::pair<bool, boost::optional<Value>> apply(Value x, Value y) {\n      Value z = x.widening_thresholds(y, m_ts);\n      if (z.is_top()) {\n        return {false, boost::optional<Value>()};\n      } else {\n        return {false, boost::optional<Value>(z)};\n      }\n    };\n\n    bool default_is_absorbing() { return true; }\n\n  }; // class widening_thresholds_op\n\n  class meet_op : public binary_op_t {\n    std::pair<bool, boost::optional<Value>> apply(Value x, Value y) {\n      Value z = x.operator&(y);\n      if (z.is_bottom()) {\n        return {true, boost::optional<Value>()};\n      } else {\n        return {false, boost::optional<Value>(z)};\n      }\n    };\n\n    bool default_is_absorbing() { return false; }\n\n  }; // class meet_op\n\n  class narrowing_op : public binary_op_t {\n    std::pair<bool, boost::optional<Value>> apply(Value x, Value y) {\n      Value z = x.operator&&(y);\n      if (z.is_bottom()) {\n        return {true, boost::optional<Value>()};\n      } else {\n        return {false, boost::optional<Value>(z)};\n      }\n    };\n\n    bool default_is_absorbing() { return false; }\n\n  }; // class narrowing_op\n\n  class domain_po : public partial_order_t {\n    bool leq(Value x, Value y) { return x.operator<=(y); }\n\n    bool default_is_top() { return true; }\n\n  }; // class domain_po\n\npublic:\n  static separate_domain_t top() { return separate_domain_t(); }\n\n  static separate_domain_t bottom() { return separate_domain_t(false); }\n\nprivate:\n  static patricia_tree_t apply_operation(binary_op_t &o, patricia_tree_t t1,\n                                         const patricia_tree_t &t2,\n                                         bool &is_bottom) {\n    is_bottom = t1.merge_with(t2, o);\n    return t1;\n  }\n\n  separate_domain(patricia_tree_t t) : _is_bottom(false), _tree(t) {}\n\n  separate_domain(bool b) : _is_bottom(!b) {}\n\npublic:\n  separate_domain() : _is_bottom(false) {}\n\n  separate_domain(const separate_domain_t &e)\n      : _is_bottom(e._is_bottom), _tree(e._tree) {}\n\n  separate_domain(const separate_domain_t &&e)\n      : _is_bottom(e._is_bottom), _tree(std::move(e._tree)) {}\n\n  separate_domain_t &operator=(separate_domain_t e) {\n    this->_is_bottom = e._is_bottom;\n    this->_tree = e._tree;\n    return *this;\n  }\n\n  iterator begin() const {\n    if (this->is_bottom()) {\n      CRAB_ERROR(\"Separate domain: trying to invoke iterator on bottom\");\n    } else {\n      return this->_tree.begin();\n    }\n  }\n\n  iterator end() const {\n    if (this->is_bottom()) {\n      CRAB_ERROR(\"Separate domain: trying to invoke iterator on bottom\");\n    } else {\n      return this->_tree.end();\n    }\n  }\n\n  bool is_bottom() const { return this->_is_bottom; }\n\n  bool is_top() const {\n    return (!this->is_bottom() && this->_tree.size() == 0);\n  }\n\n  bool operator<=(const separate_domain_t &e) const {\n    if (this->is_bottom()) {\n      return true;\n    } else if (e.is_bottom()) {\n      return false;\n    } else {\n      domain_po po;\n      return this->_tree.leq(e._tree, po);\n    }\n  }\n\n  bool operator==(const separate_domain_t &e) const {\n    return (this->operator<=(e) && e.operator<=(*this));\n  }\n\n  // Join\n  separate_domain_t operator|(const separate_domain_t &e) const {\n    if (this->is_bottom()) {\n      return e;\n    } else if (e.is_bottom()) {\n      return *this;\n    } else {\n      join_op o;\n      bool is_bottom /*unused*/;\n      patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom);\n      return separate_domain_t(std::move(res));\n    }\n  }\n\n  // Meet\n  separate_domain_t operator&(const separate_domain_t &e) const {\n    if (this->is_bottom() || e.is_bottom()) {\n      return this->bottom();\n    } else {\n      meet_op o;\n      bool is_bottom;\n      patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom);\n      if (is_bottom) {\n        return this->bottom();\n      } else {\n        return separate_domain_t(std::move(res));\n      }\n    }\n  }\n\n  // Widening\n  separate_domain_t operator||(const separate_domain_t &e) const {\n    if (this->is_bottom()) {\n      return e;\n    } else if (e.is_bottom()) {\n      return *this;\n    } else {\n      widening_op o;\n      bool is_bottom /*unused*/;\n      patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom);\n      return separate_domain_t(std::move(res));\n    }\n  }\n\n  // Widening with thresholds\n  template <typename Thresholds>\n  separate_domain_t widening_thresholds(const separate_domain_t &e,\n                                        const Thresholds &ts) const {\n    if (this->is_bottom()) {\n      return e;\n    } else if (e.is_bottom()) {\n      return *this;\n    } else {\n      widening_thresholds_op<Thresholds> o(ts);\n      bool is_bottom /*unused*/;\n      patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom);\n      return separate_domain_t(std::move(res));\n    }\n  }\n\n  // Narrowing\n  separate_domain_t operator&&(const separate_domain_t &e) const {\n    if (this->is_bottom() || e.is_bottom()) {\n      return separate_domain_t(false);\n    } else {\n      narrowing_op o;\n      bool is_bottom;\n      patricia_tree_t res = apply_operation(o, this->_tree, e._tree, is_bottom);\n      if (is_bottom) {\n        return this->bottom();\n      } else {\n        return separate_domain_t(std::move(res));\n      }\n    }\n  }\n\n  void set(Key k, Value v) {\n    if (!this->is_bottom()) {\n      if (v.is_bottom()) {\n        set_to_bottom();\n      } else if (v.is_top()) {\n        this->_tree.remove(k);\n      } else {\n        this->_tree.insert(k, v);\n      }\n    }\n  }\n\n  void set_to_bottom() {\n    this->_is_bottom = true;\n    this->_tree = patricia_tree_t();\n  }\n\n  separate_domain_t &operator-=(const Key &k) {\n    if (!this->is_bottom()) {\n      this->_tree.remove(k);\n    }\n    return *this;\n  }\n\n  Value operator[](const Key &k) const {\n    if (this->is_bottom()) {\n      return Value::bottom();\n    } else {\n      boost::optional<Value> v = this->_tree.lookup(k);\n      if (v) {\n        return *v;\n      } else {\n        return Value::top();\n      }\n    }\n  }\n\n  std::size_t size() const {\n    if (is_bottom()) {\n      return 0;\n    } else if (is_top()) {\n      CRAB_ERROR(\"separate_domains::size() is undefined if top\");\n    } else {\n      return this->_tree.size();\n    }\n  }\n\n  void write(crab::crab_os &o) const {\n    if (this->is_bottom()) {\n      o << \"_|_\";\n    } else {\n      o << \"{\";\n      for (typename patricia_tree_t::iterator it = this->_tree.begin();\n           it != this->_tree.end();) {\n        Key k = it->first;\n        k.write(o);\n        o << \" -> \";\n        Value v = it->second;\n        v.write(o);\n        ++it;\n        if (it != this->_tree.end()) {\n          o << \"; \";\n        }\n      }\n      o << \"}\";\n    }\n  }\n\n  void project(const std::vector<Key> &keys) {\n    if (is_bottom() || is_top()) {\n      return;\n    }\n    const int factor = 60;   // between 0 and 100\n    const int small_env = 5; // size of a small environment\n    int num_total_keys = (int)this->_tree.size();\n    int num_keys = (int)keys.size();\n    if (num_total_keys <= small_env ||\n        num_keys < num_total_keys * factor / 100) {\n      // project on less than factor% of keys: we copy\n      separate_domain_t env;\n      for (auto key : keys) {\n        env.set(key, operator[](key));\n      }\n      std::swap(*this, env);\n    } else {\n      // project on more or equal then factor% of keys: that\n      // might be too many copies so we remove instead.\n      std::vector<Key> sorted_keys(keys);\n      std::sort(sorted_keys.begin(), sorted_keys.end());\n      std::vector<Key> project_out_keys;\n      project_out_keys.reserve(num_total_keys);\n      for (auto it = this->_tree.begin(); it != this->_tree.end(); ++it) {\n        Key key = it->first;\n        if (!std::binary_search(sorted_keys.begin(), sorted_keys.end(), key)) {\n          project_out_keys.push_back(key);\n        }\n      }\n      for (auto const &key : project_out_keys) {\n        this->operator-=(key);\n      }\n    }\n  }\n\n  // Assume that from does not have duplicates.\n  void rename(const std::vector<Key> &from, const std::vector<Key> &to) {\n    if (is_top() || is_bottom()) {\n      // nothing to rename\n      return;\n    }\n    if (from.size() != to.size()) {\n      CRAB_ERROR(\n          \"separate_domain::rename with input vectors of different sizes\");\n    }\n\n    if (::crab::CrabSanityCheckFlag) {\n      std::set<Key> s1, s2;\n      s1.insert(from.begin(), from.end());\n      if (s1.size() != from.size()) {\n        CRAB_ERROR(\"separate_domain::rename expects no duplicates\");\n      }\n      s2.insert(to.begin(), to.end());\n      if (s2.size() != to.size()) {\n        CRAB_ERROR(\"separate_domain::rename expects no duplicates\");\n      }\n    }\n\n    for (unsigned i = 0, sz = from.size(); i < sz; ++i) {\n      Key k = from[i];\n      Key new_k = to[i];\n      if (k == new_k) { // nothing to rename\n        continue;\n      }\n      if (::crab::CrabSanityCheckFlag) {\n        if (_tree.lookup(new_k)) {\n          CRAB_ERROR(\"separate_domain::rename assumes that  \", new_k,\n                     \" does not exist in \", *this);\n        }\n      }\n      if (boost::optional<Value> k_val_opt = _tree.lookup(k)) {\n        if (!(*k_val_opt).is_top()) {\n          _tree.insert(new_k, *k_val_opt);\n        }\n        _tree.remove(k);\n      }\n    }\n  }\n\n  friend crab::crab_os &operator<<(crab::crab_os &o,\n                                   const separate_domain<Key, Value> &d) {\n    d.write(o);\n    return o;\n  }\n}; // class separate_domain\n\n} // namespace ikos\n\n\n\n\nnamespace crab {\nnamespace domains {\n//===================================================================//  \n//        The NOSA license does not apply to this code  \n//===================================================================//  \n\n/* \n * Environment from Key to discrete_domain<Element>\n *\n * We cannot use separate_domain because if the value of a key-value\n * pair is bottom then the whole environment becomes bottom. Here, if\n * the value is bottom then it means that the value is simply the\n * \"empty set\" so we want to allow entries whose values are\n * bottom. But, similar to separate_domain, the whole environment can\n * still be bottom meaning failure/undefined/unreachable.\n */ \ntemplate <typename Key, typename Element> class separate_discrete_domain {\n\nprivate:\n  using discrete_domain_t = ikos::discrete_domain<Element>;\n  using patricia_tree_t = ikos::patricia_tree<Key, discrete_domain_t>;\n  using unary_op_t = typename patricia_tree_t::unary_op_t;\n  using binary_op_t = typename patricia_tree_t::binary_op_t;\n  using partial_order_t = typename patricia_tree_t::partial_order_t;\n\npublic:\n  using key_type = Key;\n  using value_type = discrete_domain_t;    \n  using separate_discrete_domain_t = separate_discrete_domain<Key, Element>;\n  using iterator = typename patricia_tree_t::iterator;\n\nprivate:\n  bool m_is_bottom;\n  patricia_tree_t m_tree;\n\n  static patricia_tree_t apply_operation(binary_op_t &o,\n                                         const patricia_tree_t &t1,\n                                         const patricia_tree_t &t2) {\n    patricia_tree_t res(t1);\n    res.merge_with(t2, o);\n    return res;\n  }\n  /* begin patricia_tree API */\n  class join_op : public binary_op_t {\n    std::pair<bool, boost::optional<value_type>> apply(value_type x, value_type y) override {\n      value_type z = x.operator|(y);\n      if (z.is_top()) {\n\t// special encoding for top: the patricia tree will not keep\n\t// top values.\n        return {false, boost::optional<value_type>()};\n      } else {\n        return {false, boost::optional<value_type>(z)};\n      }\n    }\n    bool default_is_absorbing() override { return true; }    \n  }; // class join_op\n\n  class meet_op : public binary_op_t {\n    std::pair<bool, boost::optional<value_type>> apply(value_type x,  value_type y) override {\n      value_type z = x.operator&(y);\n      // Returning this pair means that if z is bottom do not treat it\n      // special and just update the patricia tree with z.\n      return {false, boost::optional<value_type>(z)};\n    };\n    bool default_is_absorbing() override { return false; }\n  }; // class meet_op\n\n  class domain_po : public partial_order_t {\n    bool leq(value_type x, value_type y) { return x.operator<=(y); }\n    bool default_is_top() { return true; }\n  }; // class domain_po\n  /* end patricia_tree API */\n\n  \n  separate_discrete_domain(patricia_tree_t &&t)\n    : m_is_bottom(false), m_tree(std::move(t)) {}\n\npublic:\n  \n  static separate_discrete_domain_t top() {\n    return separate_discrete_domain_t();\n  }\n\n  static separate_discrete_domain_t bottom() {\n    return separate_discrete_domain_t(true);\n  }\n\n  // Default constructor returns a top environment\n  separate_discrete_domain(bool is_bottom = false)\n    : m_is_bottom(is_bottom), m_tree(patricia_tree_t()) {}\n  \n  separate_discrete_domain(const separate_discrete_domain_t &o) = default;\n  separate_discrete_domain(separate_discrete_domain_t &&o) = default;\n  separate_discrete_domain_t &operator=(const separate_discrete_domain_t &o)  = default;\n  separate_discrete_domain_t &operator=(separate_discrete_domain_t &&o)  = default;\n  \n  iterator begin() const {\n    if (is_bottom()) {\n      CRAB_ERROR(\"Separate discrete domain: trying to invoke iterator on bottom\");\n    } else {\n      return m_tree.begin();\n    }\n  }\n\n  iterator end() const {\n    if (is_bottom()) {\n      CRAB_ERROR(\"Separate discrete domain: trying to invoke iterator on bottom\");\n    } else {\n      return m_tree.end();\n    }\n  }\n\n  bool is_bottom() const { return m_is_bottom; }\n\n  bool is_top() const {\n    return (!is_bottom()&& m_tree.size() == 0);\n  }\n\n  bool operator<=(const separate_discrete_domain_t &other) const {\n    if (is_bottom() || other.is_top()) {\n      return true;\n    } else if (other.is_bottom() || is_top()) {\n      return false;\n    } else {\n      domain_po po;\n      return m_tree.leq(other.m_tree, po);\n    }\n  }\n  \n  separate_discrete_domain_t\n  operator|(const separate_discrete_domain_t &o) const {\n    CRAB_LOG(\"separate-domain\",\n\t     crab::outs() << \"Join \" << *this << \" and \" << o << \"=\";);      \n    \n    if (is_bottom() || o.is_top()) {\n      CRAB_LOG(\"separate-domain\",\n\t       crab::outs() << \"Res=\" << o << \"\\n\";);\n      return o;\n    } else if (o.is_bottom() || is_top()) {\n      CRAB_LOG(\"separate-domain\",\n\t       crab::outs() << \"Res=\" << *this << \"\\n\";);      \n      return *this;\n    } else {\n      join_op op;\n      patricia_tree_t res = apply_operation(op, m_tree, o.m_tree);\n      auto out = separate_discrete_domain_t(std::move(res));\n      CRAB_LOG(\"separate-domain\",\n\t       crab::outs() << \"Res=\" << out << \"\\n\";);\n      return out;\n    }\n  }\n\n  separate_discrete_domain_t\n  operator&(const separate_discrete_domain_t &o) const {\n    CRAB_LOG(\"separate-domain\",\n\t     crab::outs() << \"Meet \" << *this << \" and \" << o << \"=\";);      \n    \n    if (is_top() || o.is_bottom()) {\n      CRAB_LOG(\"separate-domain\",\n\t       crab::outs() << \"Res=\" << o << \"\\n\";);\n      \n      return o;\n    } else if (o.is_top() || is_bottom()) {\n      CRAB_LOG(\"separate-domain\",\n\t       crab::outs() << \"Res=\" << *this << \"\\n\";);\n      \n      return *this;\n    } else {\n      meet_op op;\n      patricia_tree_t res = apply_operation(op, m_tree, o.m_tree);\n      auto out = separate_discrete_domain_t(std::move(res));\n      CRAB_LOG(\"separate-domain\",\n\t       crab::outs() << \"Res=\" << out << \"\\n\";);\n      return out;\n    }\n  }\n\n  void set(const Key &k, value_type v) {\n    // Note that we can store a key-value pair where the value is\n    // bottom because bottom means empty set.\n    if (!is_bottom()) {\n      if (v.is_top()) {\n\tm_tree.remove(k);\n      } else {\n\tm_tree.insert(k, v);\n      }\n    }\n  }\n\n  separate_discrete_domain_t &operator-=(const Key &k) {\n    if (!is_bottom()) {\n      m_tree.remove(k);\n    }\n    return *this;\n  }\n\n  value_type operator[](const Key &k) {\n    if (is_bottom()) {\n      CRAB_ERROR(\"separate_discrete_domain::operator[] is undefined on bottom\");\n    } else if (is_top()) {\n      return value_type::top();\n    } else {\n      if (boost::optional<value_type> v = m_tree.lookup(k)) {\n        return *v;\n      } else {\n        return value_type::top();\n      }\n    }\n  }\n\n  void project(const std::vector<Key> &keys) {\n    if (is_bottom() || is_top()) {\n      return;\n    }\n    const int factor = 60;   // between 0 and 100\n    const int small_env = 5; // size of a small environment\n    int num_total_keys = (int)m_tree.size();\n    int num_keys = (int)keys.size();\n    if (num_total_keys <= small_env ||\n        num_keys < num_total_keys * factor / 100) {\n      // project on less than factor% of keys: we copy\n      separate_discrete_domain_t env;\n      for (auto key : keys) {\n        env.set(key, operator[](key));\n      }\n      std::swap(*this, env);\n    } else {\n      // project on more or equal then factor% of keys: that\n      // might be too many copies so we remove instead.\n      std::vector<Key> sorted_keys(keys);\n      std::sort(sorted_keys.begin(), sorted_keys.end());\n      std::vector<Key> project_out_keys;\n      project_out_keys.reserve(num_total_keys);\n      for (auto it = m_tree.begin(); it != m_tree.end(); ++it) {\n        Key key = it->first;\n        if (!std::binary_search(sorted_keys.begin(), sorted_keys.end(), key)) {\n          project_out_keys.push_back(key);\n        }\n      }\n      for (auto const &key : project_out_keys) {\n        this->operator-=(key);\n      }\n    }\n  }\n\n  // Assume that from does not have duplicates.\n  void rename(const std::vector<Key> &from, const std::vector<Key> &to) {\n    if (is_top() || is_bottom()) {\n      // nothing to rename\n      return;\n    }\n    if (from.size() != to.size()) {\n      CRAB_ERROR(\n          \"separate_discrete_domain::rename with input vectors of different sizes\");\n    }\n\n    if (::crab::CrabSanityCheckFlag) {\n      std::set<Key> s1, s2;\n      s1.insert(from.begin(), from.end());\n      if (s1.size() != from.size()) {\n        CRAB_ERROR(\"separate_discrete_domain::rename expects no duplicates\");\n      }\n      s2.insert(to.begin(), to.end());\n      if (s2.size() != to.size()) {\n        CRAB_ERROR(\"separate_discrete_domain::rename expects no duplicates\");\n      }\n    }\n\n    for (unsigned i = 0, sz = from.size(); i < sz; ++i) {\n      Key k = from[i];\n      Key new_k = to[i];\n      if (k == new_k) { // nothing to rename\n        continue;\n      }\n      if (::crab::CrabSanityCheckFlag) {\n        if (m_tree.lookup(new_k)) {\n          CRAB_ERROR(\"separate_discrete_domain::rename assumes that  \",\n\t\t     new_k, \" does not exist in \", *this);\n        }\n      }\n      if (boost::optional<value_type> val_opt = m_tree.lookup(k)) {\n        if (!(*val_opt).is_top()) {\n          m_tree.insert(new_k, *val_opt);\n        }\n        m_tree.remove(k);\n      }\n    }\n  }\n\n  \n  void write(crab::crab_os &o) const {\n    if (is_top()) {\n      o << \"{}\";\n    } else if (is_bottom()) {\n      o << \"_|_\";\n    } else {\n      o << \"{\";\n      for (typename patricia_tree_t::iterator it = m_tree.begin();\n           it != m_tree.end();) {\n        Key k = it->first;\n        k.write(o);\n        o << \" -> \";\n        value_type v = it->second;\n        v.write(o);\n        ++it;\n        if (it != m_tree.end()) {\n          o << \"; \";\n        }\n      }\n      o << \"}\";\n    }\n  }\n}; // class separate_discrete_domain\n\ntemplate <typename Key, typename Element>\ninline crab_os &operator<<(crab_os &o,\n                           const separate_discrete_domain<Key, Element> &env) {\n  env.write(o);\n  return o;\n}\n\n} //end namespace domains  \n} //end namespace crab\n", "meta": {"hexsha": "79f00e58e005dcc36805e69f9e975744e2f9f6e3", "size": 23430, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crab/domains/separate_domains.hpp", "max_stars_repo_name": "LinerSu/crab", "max_stars_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 152.0, "max_stars_repo_stars_event_min_datetime": "2016-02-28T06:04:02.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T10:44:56.000Z", "max_issues_repo_path": "include/crab/domains/separate_domains.hpp", "max_issues_repo_name": "LinerSu/crab", "max_issues_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2017-07-03T06:25:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T21:09:32.000Z", "max_forks_repo_path": "include/crab/domains/separate_domains.hpp", "max_forks_repo_name": "LinerSu/crab", "max_forks_repo_head_hexsha": "8f3516f4b4765f4a093bb3c3a94ac2daa174130c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2015-11-22T15:51:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-30T00:46:57.000Z", "avg_line_length": 29.8852040816, "max_line_length": 94, "alphanum_fraction": 0.6015364917, "num_tokens": 5993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.21437849548718665}}
{"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n#include \"Tracking\\ComputeEssential.h\"\n#include \"Tracking\\MapInitialization.h\"\n#include \"Mapping\\NewMapPointsCreation.h\"\n#include \"Tracking\\Triangulation.h\"\n#include \"Tracking\\Reprojection.h\"\n#include \"MageSettings.h\"\n#include \"Utils\\Epipolar.h\"\n#include \"Map\\Map.h\"\n#include \"Map\\MapPoint.h\"\n#include \"KeyframeBuilder.h\"\n#include \"Utils\\format.h\"\n#include \"Utils\\cv.h\"\n#include \"FeatureMatcher.h\"\n#include \"BundleAdjustment\\BundleAdjust.h\"\n#include \"Debugging\\SkeletonLogger.h\"\n#include \"arcana\\analysis\\determinator.h\"\n#include \"Analysis\\binary_iterators.h\"\n\n#include <opencv2\\core.hpp>\n#include <opencv2\\imgproc.hpp>\n\n#include \"Utils\\Logging.h\"\n\n#include <boost\\format.hpp>\n\n#include <chrono>\n#include <assert.h>\n\nusing namespace std;\n\nnamespace mage\n{\n    namespace\n    {\n        float ComputePerpDistanceSquared(\n            const cv::Matx31f& line,\n            const cv::Matx31f& point)\n        {\n            auto A = line(0, 0);\n            auto B = line(1, 0);\n            auto C = line(2, 0);\n            auto X = point(0, 0);\n            auto Y = point(1, 0);\n\n            auto numerator = (A * X) + (B*Y) + C;\n            auto denominatorSquared = (A*A) + (B*B);\n\n            return numerator * numerator / denominatorSquared;\n        }\n\n        long long ComputeFrameTimeDifference(const shared_ptr<const AnalyzedImage>& frame1, const shared_ptr<const AnalyzedImage>& frame2)\n        {\n            return std::chrono::duration_cast<std::chrono::milliseconds>(frame2->GetTimeStamp() - frame1->GetTimeStamp()).count();\n        }\n\n        void CreateNewMapPointsHelper(InitializationData& initializationData, mage::temp::vector<MappingKeyframe>& Kcs, const KeyframeProxy& Ki, BaseBow& bagOfWords, const MonoMapInitializationSettings& settings, const PerCameraSettings& cameraSettings, thread_memory memory)\n        {\n            // compute the current scale for the initialization pair\n            float scale = static_cast<float>(cv::norm(initializationData.Frames.back()->GetPose().GetViewSpacePosition(), cv::NORM_L2));\n            float minParallaxScale = settings.MapInitializationNewPointsCreationMinDistance * scale;\n\n            vector<MapPointKeyframeAssociations> newMapPoints;\n            NewMapPointsCreation(bagOfWords, Ki, cameraSettings,\n                settings.NewMapPointsCreationSettings,\n                minParallaxScale, memory, Kcs, newMapPoints);\n\n            //associate new map points with the keyframes it is visible in\n            for (const auto& curMapPoint : newMapPoints)\n            {\n                initializationData.MapPoints.emplace_back(curMapPoint.MapPoint);\n                for (const KeyframeAssociation& curKeyframeAssoc : curMapPoint.Keyframes)\n                {\n                    auto found = std::find_if(initializationData.Frames.begin(), initializationData.Frames.end(),\n                        [curKeyframeAssoc](const auto& keyframe) { return keyframe->GetId() == curKeyframeAssoc.KeyframeId; });\n                    assert(found != initializationData.Frames.end());\n                    (*found)->AddAssociation(curMapPoint.MapPoint.As<MapPointTrackingProxy>(), curKeyframeAssoc.KeypointDescriptorIndex);\n                }\n            }\n        }\n    }\n\n    vector<Pose> MapInitialization::FindEssentialPotientialPoses(\n        const cv::Matx33f& essentialMatrix)\n    {\n        cv::Mat R1, R2;\n        cv::Mat T;\n\n        //This gives us back 2 possible rotations, and a translation that can be negative\n        // From the docs:\n        //      Generally 4 possible poses exists for a given E.\n        //      They are[R1, t], [R1, -t], [R2, t], [R2, -t].\n        cv::decomposeEssentialMat(essentialMatrix, R1, R2, T);\n\n        const cv::Vec3f normalizedTranslationViewSpace = Normalize(cv::Vec3f{ T });\n        const cv::Vec3f negT = -1 * normalizedTranslationViewSpace;\n\n        vector<Pose> poses;\n        poses.reserve(4);\n\n        //pose of R1, T\n        Pose p1 = { normalizedTranslationViewSpace, R1 };\n        poses.emplace_back(p1);\n        poses.emplace_back(negT, R1);\n\n        //pose of R2, T\n        Pose p2 = { T, R2 };\n        poses.emplace_back(p2);\n        poses.emplace_back(negT, R2);\n\n        return poses;\n    }\n\n    MapInitialization::MapInitialization(\n        const MonoMapInitializationSettings& settings,\n        const PerCameraSettings& cameraSettings,\n        const device::IMUCharacterization& imuCharacterization,\n        mira::determinator& determinator)\n        :   m_settings{ settings },\n            m_cameraSettings{ cameraSettings },\n            m_imuCharacterization{ imuCharacterization },\n            m_determinator{ determinator }\n    {\n        ResetMapInitialization();\n    }\n\n    bool HasConsistentCheirality(const vector<Pose>& frame2Poses, /*cv::Vec3f& dominantDirection,*/\n        const CameraCalibration& frame1Calibration, const CameraCalibration& frame2Calibration,\n        const vector<cv::Point2f>& frame1Points, const vector<cv::Point2f>& frame2Points)\n    {\n        assert(frame1Points.size() == frame2Points.size());\n\n        // Find any of the poses that have the expected orientation, to simplify cheirality computations.\n        auto found = find_if(frame2Poses.begin(), frame2Poses.end(), [](const Pose& p) { return p.GetWorldSpaceRight()[0] > 0; });\n        if (found == frame2Poses.end())\n            return false;\n        const Pose& frame2Pose = *found;\n\n        // First frame is always at origin and identity.\n        const Pose frame1Pose;\n\n        const cv::Matx33f& frame1InvCam = frame1Calibration.GetInverseCameraMatrix();\n        const cv::Matx33f& frame2InvCam = frame2Calibration.GetInverseCameraMatrix();\n        const cv::Matx44f& frame1World = frame1Pose.GetInverseViewMatrix();\n        const cv::Matx44f& frame2World = frame2Pose.GetInverseViewMatrix();\n\n        const cv::Vec3f frame1Forward = frame1Pose.GetWorldSpaceForward();\n        const cv::Vec3f frame2Forward = frame2Pose.GetWorldSpaceForward();\n\n        int concensus = 1;\n        {\n            const cv::Point3f current3DPoint = TriangulatePointWorldSpace(frame1InvCam, frame1World, frame2InvCam, frame2World,\n                frame1Points[0], frame2Points[0]);\n\n            const cv::Vec3f fromFrame1 = current3DPoint - frame1Pose.GetWorldSpacePosition();\n            const cv::Vec3f fromFrame2 = current3DPoint - frame2Pose.GetWorldSpacePosition();\n\n            if (frame1Forward.dot(fromFrame1) <= 0.f || frame2Forward.dot(fromFrame2) <= 0.f)\n                concensus = -1;\n        }\n\n        for (size_t pointIterator = 1; pointIterator < frame1Points.size(); pointIterator++)\n        {\n            const cv::Point3f current3DPoint = TriangulatePointWorldSpace(frame1InvCam, frame1World, frame2InvCam, frame2World,\n                frame1Points[pointIterator], frame2Points[pointIterator]);\n\n            const cv::Vec3f fromFrame1 = current3DPoint - frame1Pose.GetWorldSpacePosition();\n            const cv::Vec3f fromFrame2 = current3DPoint - frame2Pose.GetWorldSpacePosition();\n\n            if (concensus * frame1Forward.dot(fromFrame1) <= 0.f || concensus * frame2Forward.dot(fromFrame2) <= 0.f)\n                return false;\n        }\n\n        //dominantDirection = frame2Pose.GetWorldSpacePosition() * concensus;\n        \n        return true;\n    }\n\n    vector<Pose> MapInitialization::FindPossiblePoses(\n        gsl::span<const cv::Point2f> frame1Points,\n        gsl::span<const cv::Point2f> frame2Points,\n        const CameraCalibration& frame1Calibration,\n        const CameraCalibration& frame2Calibration)\n    {\n        SCOPE_TIMER(MapInitialization::FindPossiblePoses);\n        struct InitialPoseEstimate\n        {\n            float Score;\n            std::vector<Pose> Candidates;\n        };\n\n        InitialPoseEstimate bestFive{ 0.0f, {} };\n\n        cv::RNG rng(12345);\n\n        const size_t pointCount = 5;\n\n        std::vector<cv::Point2f> frame1Points_subset;\n        std::vector<cv::Point2f> frame2Points_subset;\n        frame1Points_subset.reserve(pointCount);\n        frame2Points_subset.reserve(pointCount);\n\n        const cv::Point2f principalPoint{ frame1Calibration.GetPrincipalPointX(),frame1Calibration.GetPrincipalPointY() };\n        const cv::Matx33f inverseCalibrationCamera2Transpose = frame2Calibration.GetInverseCameraMatrix().t();\n        const cv::Matx33f inverseCalibrationCamera1 = frame1Calibration.GetInverseCameraMatrix();\n        \n        const float minPixelDiffSquared = m_settings.MinPixelSpread * m_settings.MinPixelSpread;\n        for (unsigned int i = 0; i < m_settings.RansacIterationsForModels; i++)\n        {\n            frame1Points_subset.clear();\n            frame2Points_subset.clear();\n            \n            size_t tryCount = 0;\n            std::set<int> randomIndices;\n            while (randomIndices.size() < pointCount && tryCount < 100)\n            {\n                tryCount++;\n                int candidateIndex = rng.uniform(0, frame1Points.size());\n\n                bool tooClose = std::any_of(randomIndices.cbegin(), randomIndices.cend(), [&](int value)\n                {\n                    const auto pixelDiff1 = frame1Points[value] - frame1Points[candidateIndex];\n                    const float dist2_1 = pixelDiff1.dot(pixelDiff1);\n\n                    const auto pixelDiff2 = frame2Points[value] - frame2Points[candidateIndex];\n                    const float dist2_2 = pixelDiff2.dot(pixelDiff2);\n\n                    return dist2_1 < minPixelDiffSquared || dist2_2 < minPixelDiffSquared;\n                });\n\n                if (!tooClose)\n                {\n                    randomIndices.insert(candidateIndex);\n                }\n            }\n\n            // if we weren't able to find a set of points, reset and try again\n            if (randomIndices.size() < pointCount)\n            {\n                continue;\n            }\n\n            for (auto index : randomIndices)\n            {\n                frame1Points_subset.push_back(frame1Points[index]);\n                frame2Points_subset.push_back(frame2Points[index]);\n            }\n\n            // Essential Matrix estimation (5 point)\n            cv::Mat essentialMat1To2 = mira::FindEssentialMat(frame1Points_subset, frame2Points_subset, frame1Calibration.GetFocalLengthX(), frame1Calibration.GetFocalLengthY(), principalPoint, 1e-6f);\n\n            // openCV may actually compute several essential matrixes\n            int rowIterator = 0;\n            while (essentialMat1To2.rows - rowIterator >= 3)\n            {\n                cv::Matx33f ess = cv::Matx33f{ essentialMat1To2.rowRange(rowIterator, rowIterator + 3) };\n                cv::Matx33f fundamental1to2 = inverseCalibrationCamera2Transpose * ess * inverseCalibrationCamera1;\n                cv::Matx33f fundamental2to1 = fundamental1to2.t();\n                float fiveScore = ScoreFundamentalMatrix(frame1Points, frame2Points, fundamental1to2, fundamental2to1);\n\n                if (fiveScore > bestFive.Score)\n                {\n                    auto possiblePoses = FindEssentialPotientialPoses(ess);\n                    if (possiblePoses.size() > 0 && HasConsistentCheirality(possiblePoses, frame1Calibration, frame2Calibration, frame1Points_subset, frame2Points_subset))\n                    {\n                        bestFive = { fiveScore, possiblePoses };\n                    }\n                }\n\n                rowIterator += 3;\n            }\n        }\n\n        return bestFive.Candidates;\n    }\n\n    float MapInitialization::ScoreFundamentalMatrix(\n        gsl::span<const cv::Point2f> frame1Points,\n        gsl::span<const cv::Point2f> frame2Points,\n        const cv::Matx33f& fundamentalMat1To2,\n        const cv::Matx33f& fundamentalMat2To1)\n    {\n        float Total_F_sum = 0;\n        size_t inlierCount = 0;\n\n        //compute the difference between:\n        //      point1 * (Fundamental Matrix) vs actual points 2\n        //      point2 * (Fundamental Matrix Transpose) vs actual points 1\n        for (auto frame1 = frame1Points.begin(), frame2 = frame2Points.begin();\n            frame1 != frame1Points.end() && frame2 != frame2Points.end(); ++frame1, ++frame2)\n        {\n            cv::Matx31f  m1{ frame1->x, frame1->y, 1 };\n            cv::Matx31f  m2{ frame2->x, frame2->y, 1 };\n\n            cv::Matx31f result12 = fundamentalMat1To2 * m1;\n            cv::Matx31f result21 = fundamentalMat2To1 * m2;\n\n            float diff12Squared = ComputePerpDistanceSquared(result12, m2);\n            float diff21Squared = ComputePerpDistanceSquared(result21, m1);\n\n            //only add to the sum if the squared difference is less than the inlier threshold\n            if (diff12Squared < m_settings.FundamentalTransferErrorThreshold\n                && diff21Squared < m_settings.FundamentalTransferErrorThreshold)\n            {\n                Total_F_sum += (m_settings.FundamentalTransferErrorThreshold - diff12Squared);\n                Total_F_sum += (m_settings.FundamentalTransferErrorThreshold - diff21Squared);\n                inlierCount++;\n            }\n        }\n\n        if (inlierCount >= m_settings.MinScoringInliers\n            && (float)inlierCount / (float)frame1Points.size() > m_settings.MinInlierPercentage)\n        {\n            return Total_F_sum;\n        }\n        else\n        {\n            return 0;\n        }\n    }\n\n    bool MapInitialization::FindCorrectPose(\n        gsl::span<const cv::Point2f> frame1Points,\n        gsl::span<const cv::Point2f> frame2Points,\n        gsl::span<const cv::DMatch> matches,\n        const CameraCalibration& frame1Calibration,\n        const CameraCalibration& frame2Calibration,\n        const Pose& referencePose,\n        const vector<Pose>& poses,\n        Pose& correctPose,\n        std::vector<std::pair<cv::DMatch, cv::Point3f>>& triangulated3Dpoints)\n    {\n        SCOPE_TIMER(MapInitialization::FindCorrectPose);\n        assert(frame1Points.size() == frame2Points.size());\n        assert(triangulated3Dpoints.size() == 0);\n\n        cv::Matx34f firstPoseMatrix = referencePose.GetViewMatrix();\n        float maxEpipolarError = 2 * m_settings.MaxEpipolarError;\n\n        float nextBestPoseScore = 0;\n        float selectedPoseScore = 0;\n        int selectedPoseIndex = -1;\n\n        vector<pair<cv::DMatch, cv::Point3f>> selectedPosePoints;\n        vector<pair<cv::DMatch, cv::Point3f>> candidatePosePoints;\n        candidatePosePoints.reserve(frame1Points.size());\n        selectedPosePoints.reserve(frame1Points.size());\n        for (uint poseIterator = 0; poseIterator < poses.size(); poseIterator++)\n        {\n            candidatePosePoints.clear();\n\n            const Pose& currentPose = poses.at(poseIterator);\n\n            // From a given essential matrix, there are four possible solutions for the relative\n            // camera pose; two of these will have a sensible rotation, and two will be \"twisted\"\n            // a half-turn around the first camera's forward vector (see Nister's five-point paper,\n            // section 3.1).  Because we know that such a twist will never occur in the brief \n            // interval between our initialization frames, we can early-out if we detect that we're\n            // dealing with one of the twisted poses.\n            if (currentPose.GetWorldSpaceRight().dot(referencePose.GetWorldSpaceRight()) <= 0.f)\n            {\n                continue;\n            }\n\n            const cv::Matx33f fundamentalMat = ComputeFundamentalMatrix(referencePose, frame1Calibration, currentPose, frame2Calibration);\n            const cv::Matx33f fundamentalMat2 = ComputeFundamentalMatrix(currentPose, frame2Calibration, referencePose, frame1Calibration);\n\n            //Triangulate the points from the first and second frame with the first (identity) matrix and one of the possible poses.\n            const cv::Matx33f& frame1InvCam = frame1Calibration.GetInverseCameraMatrix();\n            const cv::Matx33f& frame2InvCam = frame2Calibration.GetInverseCameraMatrix();\n            const cv::Matx44f& frame1World = referencePose.GetInverseViewMatrix();\n            const cv::Matx44f& frame2World = currentPose.GetInverseViewMatrix();\n\n            // compute a scale factor so that the distance between the computed poses can be \"1\" for calculations\n            assert(referencePose.GetWorldSpacePosition().x == 0 && \"referencePose should be identity\");\n            assert(referencePose.GetWorldSpacePosition().y == 0 && \"referencePose should be identity\");\n            assert(referencePose.GetWorldSpacePosition().z == 0 && \"referencePose should be identity\");\n            const float scale = 1.0f / currentPose.GetWorldSpacePosition().dot(currentPose.GetWorldSpacePosition());\n\n            float score = 0;\n            for (int pointIterator = 0; pointIterator < frame1Points.size(); pointIterator++)\n            {\n                const cv::Point3f current3DPoint = TriangulatePointWorldSpace(frame1InvCam, frame1World, frame2InvCam, frame2World,\n                    frame1Points[pointIterator], frame2Points[pointIterator]);\n\n                // we only want to accept points which don't project out too far in the Z direction\n                // we can get away with just testing the Z direction because the first pose is identity\n                // but we do need to compute a normalization for the frame pair for this test to be reasonable\n\n                // test that the point is in front\n                if (current3DPoint.z < 0)\n                {\n                    continue;\n                }\n\n                // parallax test\n                if (current3DPoint.z * scale > m_settings.MaxParallax3dDistance)\n                {\n                    continue;\n                }\n\n                const float KcToKiEpipolarError = DistanceFromEpipolarLine(fundamentalMat, frame1Points[pointIterator], frame2Points[pointIterator]);\n                const float KiToKcEpiploarError = DistanceFromEpipolarLine(fundamentalMat2, frame2Points[pointIterator], frame1Points[pointIterator]);\n\n                float temp = KiToKcEpiploarError + KcToKiEpipolarError;\n\n                if (temp < maxEpipolarError)\n                {\n                    score += maxEpipolarError - temp;\n\n                    candidatePosePoints.emplace_back(matches[pointIterator], current3DPoint);\n                }\n            }\n            \n            assert(score >= 0);\n\n            if (candidatePosePoints.size() >= m_settings.MinScoringInliers\n                && (float)candidatePosePoints.size() / (float)frame1Points.size() > m_settings.MinInlierPercentage)\n            {\n                //better parallax test\n                {\n                    size_t middleIndex = candidatePosePoints.size() / 2;\n                    std::nth_element(candidatePosePoints.begin(), candidatePosePoints.begin() + middleIndex, candidatePosePoints.end(),\n                        [](const pair<cv::DMatch, cv::Point3f>& matchAndPoint1, const pair<cv::DMatch, cv::Point3f>& matchAndPoint2)\n                    {\n                        return matchAndPoint1.second.z < matchAndPoint2.second.z;\n                    });\n                    auto medianDepth = candidatePosePoints[middleIndex].second.z;\n\n                    // ensure that the depths of the traingulated points match the expected 'good' range\n                    if (medianDepth <= m_settings.MaxParallax3dMedianDistance)\n                    {\n                        if (selectedPoseIndex == -1 || score > selectedPoseScore)\n                        {\n                            nextBestPoseScore = selectedPoseScore;\n                            selectedPoseScore = score;\n                            selectedPoseIndex = poseIterator;\n                            std::swap(selectedPosePoints, candidatePosePoints);\n                        }\n                        else\n                        {\n                            // handle the case that this score isn't best, but is better than next best score\n                            nextBestPoseScore = max(nextBestPoseScore, score);\n                        }\n                    }\n                }\n            }\n        }\n\n        // None of the potiential poses are valid\n        if (selectedPoseScore <= 0)\n        {\n            LogMessage<Tracing::TraceLevels::Verbose>(L\"MapInitialization  No pose with valid score\");\n            return false;\n        }\n\n        // compute the difference between the two best pose scores, if they are too similar, reject the pairing\n        float scoreRatio = (selectedPoseScore - nextBestPoseScore) / selectedPoseScore;\n        if (scoreRatio < m_settings.MinCandidatePoseDisimilarity)\n        {\n            LogMessage<Tracing::TraceLevels::Verbose>(L\"MapInitialization  Best poses too similar\");\n            return false;\n        }\n\n        // validate for z-direction constraint\n        if (abs(poses.at(selectedPoseIndex).GetWorldSpacePosition().z) > m_settings.MaxPoseContributionZ)\n        {\n            LogMessage<Tracing::TraceLevels::Verbose>(L\"MapInitialization  Best pose too biased in Z direction\");\n            return false;\n        }\n\n        // At least one of the poses is valid, and the most accurate is chosen\n        {\n            correctPose = poses.at(selectedPoseIndex);\n            triangulated3Dpoints = selectedPosePoints;\n            return true;\n        }\n    }\n\n    void MapInitialization::ResetMapInitialization()\n    {\n        LogMessage<>(L\"MapInitialization  ResetMapInitialization\");\n        m_initializationFrames.clear();\n        m_initializationDescriptorsCounters.clear();\n    }\n\n    MapInitialization::InitializationAttemptState MapInitialization::TryInitializeMap(\n        const shared_ptr<const AnalyzedImage>& frame,\n        thread_memory memory,\n        InitializationData& initializationData,\n        BaseBow& bagOfWords)\n    {\n        SCOPE_TIMER(MapInitialization::TryInitializeMap);\n\n        // ensure that too much time hasn't passed, if so then re-init\n        if (m_initializationFrames.size() != 0)\n        {\n            long long frameTimeDeltaMillisecondsFront = ComputeFrameTimeDifference(m_initializationFrames.front().Image, frame);\n            // reset initialization\n            if (frameTimeDeltaMillisecondsFront > m_settings.MaxInitializationIntervalMilliseconds)\n            {\n                ResetMapInitialization();\n            }\n            else\n            {\n                // deterministic skipping of frames during initialization period\n                // if we are trying to compute poses, then only accept frames which are beyond the interval time delta\n                if (frameTimeDeltaMillisecondsFront > m_settings.MinInitializationIntervalMilliseconds)\n                {\n                    long long frameTimeDeltaMillisecondsBack = ComputeFrameTimeDifference(m_initializationFrames.back().Image, frame);\n                    if (frameTimeDeltaMillisecondsBack < m_settings.MapInitFrameIntervalMilliseconds)\n                    {\n                        return InitializationAttemptState::Skipped;\n                    }\n                }\n            }\n        }\n\n        // add the new frame to our list of frames\n        m_initializationFrames.emplace_back(frame);\n\n        // bootstrap just the call and set things up\n        if (m_initializationFrames.size() == 1)\n        {\n            unsigned int numDescriptors = m_initializationFrames.front().Image->GetDescriptors().size();\n\n            if (numDescriptors < m_settings.MinFeatureMatches)\n            {\n                // not enough matches, reset and try again\n                ResetMapInitialization();\n                return InitializationAttemptState::ResetInit;\n            }\n            m_initializationDescriptorsCounters.clear();\n            m_initializationDescriptorsCounters.resize(numDescriptors, 1); // each descriptor has been seen in one frame\n\n            return InitializationAttemptState::NoPose;\n        }\n        LogMessage<Tracing::TraceLevels::Verbose>((boost::wformat(L\"MapInitialization frame %d Initializing has %d frames\") % frame->GetFrameId().CorrelationId % m_initializationFrames.size()).str());\n\n        if (!TryIntializeMapWithProvidedFrames(m_initializationFrames.front(), m_initializationFrames.back(), memory, initializationData, bagOfWords))\n        {\n            return InitializationAttemptState::NoPose;\n        }\n\n        return InitializationAttemptState::FinishInit;\n    }\n\n    bool MapInitialization::TryIntializeMapWithProvidedFrames(\n        const MatchedImage& referenceFrame,\n        MatchedImage& currentFrame,\n        thread_memory memory,\n        InitializationData& initializationData,\n        BaseBow& bagOfWords)\n    {\n        SCOPE_TIMER(MapInitialization::TryIntializeMapWithProvidedFrames);\n\n        // match points with the descriptors that have been valid over the set of initialization frames\n        //QUERY IMAGE: referenceFrame\n        //TRAIN IMAGE: current frame\n        int descriptorSizeFrame1 = gsl::narrow_cast<int>(referenceFrame.Image->GetDescriptorsCount());\n        int trueCountFrame1 = 0;\n        vector<bool> flagsFrame1(descriptorSizeFrame1, false);\n        for (int i = 0; i < descriptorSizeFrame1; i++)\n        {\n            if (referenceFrame.Image->GetKeyPoint(i).octave == 0)\n            {\n                flagsFrame1[i] = true;\n                trueCountFrame1 += 1;\n            }\n        }\n        int descriptorSizeFrame2 = gsl::narrow_cast<int>(currentFrame.Image->GetDescriptorsCount());\n        int trueCountFrame2 = 0;\n        vector<bool> flagsFrame2(descriptorSizeFrame2, false);\n        for (int i = 0; i < descriptorSizeFrame2; i++)\n        {\n            if (currentFrame.Image->GetKeyPoint(i).octave == 0)\n            {\n                flagsFrame2[i] = true;\n                trueCountFrame2 += 1;\n            }\n        }\n\n        unsigned int numMatches = Match(referenceFrame.Image,\n            currentFrame.Image, flagsFrame1, flagsFrame2, trueCountFrame1, trueCountFrame2,\n            m_settings.FivePointMatchingSettings.MaxHammingDistance,\n            m_settings.FivePointMatchingSettings.MinHammingDifference, currentFrame.Matches);\n\n        SkeletonLogger::MapInitialization::LogMatches(currentFrame.Matches, *referenceFrame.Image, *currentFrame.Image);\n\n        if (numMatches < m_settings.MinFeatureMatches)\n        {\n            SkeletonLogger::MapInitialization::LogFailure(\"numMatches < m_mapInitializationSettings.MinFeatureMatches\");\n\n            ResetMapInitialization();\n            return false;\n        }\n        // increment the counter for each feature that we matched\n        for (unsigned int row = 0; row < numMatches; row++)\n        {\n            m_initializationDescriptorsCounters[currentFrame.Matches[row].queryIdx]++;\n        }\n\n        long long frameTimeDeltaMilliseconds = ComputeFrameTimeDifference(referenceFrame.Image, currentFrame.Image);\n        size_t frameCount = m_initializationFrames.size();\n        // if the frame count crosses the threshold, then we have a candidate match to try and initialize with\n        if (frameTimeDeltaMilliseconds >= m_settings.MinInitializationIntervalMilliseconds)\n        {\n            // check to make sure that enough of the common features were seen in many of the frames which we have matched\n            vector<cv::DMatch> bestMatches;\n\n            assert(frameCount * m_settings.FeatureCovisibilityThreshold < 256);\n            uint8_t goodFeatureThreshold = (uint8_t)(frameCount * m_settings.FeatureCovisibilityThreshold);\n            \n            for (unsigned int row = 0; row < numMatches; row++)\n            {\n                const auto& currentMatch = currentFrame.Matches[row];\n                if (m_initializationDescriptorsCounters[currentMatch.queryIdx] > goodFeatureThreshold)\n                {\n                    bestMatches.push_back(currentMatch);\n                }\n            }\n\n            // ensure that we still have enough matches\n            if (bestMatches.size() < m_settings.MinFeatureMatches)\n            {\n                ResetMapInitialization();\n                SkeletonLogger::MapInitialization::LogFailure(\"bestMatches.size() < m_mapInitializationSettings.MinFeatureMatches\");\n                LogMessage<Tracing::TraceLevels::Verbose>((boost::wformat(L\"MapInitialization  Not enough matches : %d\") % bestMatches.size()).str());\n                return false;\n            }\n\n            // try to compute the pose for the frame pairing\n            bool initializeSucceeded = InitializeWithFrames(bestMatches, referenceFrame.Image, currentFrame.Image, initializationData, memory);\n            LogMessage<Tracing::TraceLevels::Verbose>((boost::wformat(L\"MapInitialization  Initializing attempt success? %s\") % (initializeSucceeded ? \"true\" : \"false\")).str());\n            SkeletonLogger::MapInitialization::LogFailure(initializeSucceeded ? \"Initialize succeeded\" : \"Initialize failed\");\n\n            if (!initializeSucceeded)\n            {\n                return false;\n            }\n\n            DETERMINISTIC_CHECK(m_determinator, initializationData.Frames.begin(), initializationData.Frames.end());\n            DETERMINISTIC_CHECK(m_determinator, initializationData.MapPoints.begin(), initializationData.MapPoints.end());\n\n            // perform new map points creation before bundling this solution to add additional datapoints\n            // clear out any existing map points, because we're going to add new ones\n            initializationData.MapPoints.clear();\n            for (auto& keyframe : initializationData.Frames)\n            {\n                keyframe->ClearAssociations();\n            }\n            std::unique_ptr<BaseBow> tempBagOfWords = bagOfWords.CreateTemporaryBow();\n\n            for (const auto& keyframe : initializationData.Frames)\n            {\n                tempBagOfWords->AddImage(keyframe->GetId(), *keyframe->GetAnalyzedImage());\n            }\n            \n            // Create a list of connected keyframes which in this case is just thhe first frame\n            mage::temp::vector<MappingKeyframe> Kcs = memory.stack_vector<MappingKeyframe>(initializationData.Frames.size());\n            Kcs.emplace_back(*initializationData.Frames.front());\n\n            CreateNewMapPointsHelper(initializationData, Kcs, *initializationData.Frames.back(), *tempBagOfWords, m_settings, m_cameraSettings, memory);\n\n            // Validate that we were able to create a minimal set of map points using the NewMapPointsCreation technique\n            if ((float)initializationData.MapPoints.size() < m_settings.MinInitialMapPoints)\n            {\n                return false;\n            }\n\n            // perform an initial bundle adjust of the map before creating new map points\n            BundlerSettings bundlerSettings1{\n                m_settings.BundleAdjustmentHuberWidth,\n                m_settings.MaxOutlierError,\n                1.0f,\n                0.0f,\n                false,\n                m_settings.BundleAdjustmentG2OSteps,\n                m_settings.BundleAdjustmentG2OSteps,\n                0 };\n\n            BundleAdjustInitializationData(initializationData, m_determinator, true, bundlerSettings1, memory);\n\n            DETERMINISTIC_CHECK(m_determinator, initializationData.Frames.begin(), initializationData.Frames.end());\n            DETERMINISTIC_CHECK(m_determinator, initializationData.MapPoints.begin(), initializationData.MapPoints.end());\n\n            // re-validate that we have enough map points following post-BA outlier culling\n            if ((float)initializationData.MapPoints.size() < m_settings.MinInitialMapPoints)\n            {\n                return false;\n            }\n\n            // now we'll add in a third frame and its associations to the existing set of map points\n            bool addThirdFrame = m_initializationFrames.size() > 2;\n            if (addThirdFrame)\n            {\n                SCOPE_TIMER(MapInitialization::InitializeWithFrames::LocateThirdFrame);\n                \n                const auto& frame0 = initializationData.Frames.front();\n                const auto& frame1 = initializationData.Frames.back();\n                auto& thirdFrame = initializationData.Frames[1];\n                const auto& image0 = frame0->GetAnalyzedImage();\n                const auto& image1 = frame1->GetAnalyzedImage();\n                const auto& image_thirdFrame = thirdFrame->GetAnalyzedImage();\n                const Pose& pose0 = frame0->GetPose();\n                const Pose& pose1 = frame1->GetPose();\n\n                // need to estimate a pose for this new frame.  For now just assume in the middle of the initialization pair\n                const mage::Quaternion worldRotationQuat = ToQuat(Rotation(pose1.GetInverseViewMatrix()));\n                const cv::Vec3f halfPosition = (pose0.GetWorldSpacePosition() + pose1.GetWorldSpacePosition()) / 2;\n                const mage::Quaternion halfRotation = ToQuat(Rotation(pose0.GetInverseViewMatrix())).slerp(0.5f, worldRotationQuat);\n                Pose additionalPose{ To4x4(ToMat(halfRotation), halfPosition) };\n\n                const cv::Matx33f& calibration = image_thirdFrame->GetUndistortedCalibration().GetCameraMatrix();\n                std::vector<bool> unassociatedKeypointsMask = std::vector<bool>(image_thirdFrame->GetDescriptorsCount(), true);\n                auto mapPoints = memory.stack_vector<TrackLocalMap::ProjectedMapPoint>(initializationData.MapPoints.size());\n                auto mapPointIds = memory.stack_vector<Id<MapPoint>>(initializationData.MapPoints.size());\n\n                // project the triangulated point back into the third frame and\n                // perform a radius match to find the best matching point\n                for (const auto& mapPoint : initializationData.MapPoints)\n                {\n                    const mage::Projection projection = mage::ProjectUndistorted(additionalPose.GetViewMatrix(), calibration, mapPoint.GetPosition());\n\n                    // skip point projected behind the image\n                    if (projection.Distance < 0) continue;\n\n                    auto keypointIndex = frame0->GetAssociatedIndex(mapPoint);\n\n                    cv::DMatch referenceMatch;\n                    const cv::KeyPoint mapPointKeypoint(projection.Point, -1.0f, 0.0f, 0.0f, 0, -1);\n                    bool referenceMatched = RadiusMatch(\n                        mapPointKeypoint,\n                        nullptr,\n                        ORBDescriptor::Ref{ image0->GetDescriptor(keypointIndex) },\n                        image_thirdFrame->GetKeyPoints(),\n                        image_thirdFrame->GetKeypointSpatialIndex(),\n                        &unassociatedKeypointsMask,\n                        image_thirdFrame->GetDescriptors(),\n                        m_settings.ExtraFrame_SearchRadius,\n                        m_settings.ExtraFrameMatchingSettings.MaxHammingDistance,\n                        m_settings.ExtraFrameMatchingSettings.MinHammingDifference,\n                        memory,\n                        referenceMatch);\n                    referenceMatch.queryIdx = gsl::narrow_cast<int>(keypointIndex);\n\n                    keypointIndex = frame1->GetAssociatedIndex(mapPoint);\n                    cv::DMatch currentMatch;\n                    bool currentMatched = RadiusMatch(\n                        mapPointKeypoint,\n                        nullptr,\n                        ORBDescriptor::Ref{ image1->GetDescriptor(keypointIndex) },\n                        image_thirdFrame->GetKeyPoints(),\n                        image_thirdFrame->GetKeypointSpatialIndex(),\n                        &unassociatedKeypointsMask,\n                        image_thirdFrame->GetDescriptors(),\n                        m_settings.ExtraFrame_SearchRadius,\n                        m_settings.FivePointMatchingSettings.MaxHammingDistance,\n                        m_settings.FivePointMatchingSettings.MinHammingDifference,\n                        memory,\n                        currentMatch);\n                    currentMatch.queryIdx = gsl::narrow_cast<int>(keypointIndex);\n\n                    // if only one match, use that match\n                    // if both matched, but to different keypoints then choose the closest match\n                    if (currentMatched && referenceMatched)\n                    {\n                        if (currentMatch.distance < referenceMatch.distance)\n                        {\n                            unassociatedKeypointsMask[currentMatch.trainIdx] = false;\n                            mapPoints.emplace_back(mapPoint.GetPosition(), image_thirdFrame->GetKeyPoint(currentMatch.trainIdx).pt, 1);\n                            mapPointIds.emplace_back(mapPoint.GetId());\n                            thirdFrame->AddAssociation(mapPoint, currentMatch.trainIdx);\n                        }\n                        else\n                        {\n                            unassociatedKeypointsMask[referenceMatch.trainIdx] = false;\n                            mapPoints.emplace_back(mapPoint.GetPosition(), image_thirdFrame->GetKeyPoint(referenceMatch.trainIdx).pt, 1);\n                            mapPointIds.emplace_back(mapPoint.GetId());\n                            thirdFrame->AddAssociation(mapPoint, referenceMatch.trainIdx);\n                        }\n                    }\n                    else if (currentMatched)\n                    {\n                        unassociatedKeypointsMask[currentMatch.trainIdx] = false;\n                        mapPoints.emplace_back(mapPoint.GetPosition(), image_thirdFrame->GetKeyPoint(currentMatch.trainIdx).pt, 1);\n                        mapPointIds.emplace_back(mapPoint.GetId());\n                        thirdFrame->AddAssociation(mapPoint, currentMatch.trainIdx);\n                    }\n                    else if (referenceMatched)\n                    {\n                        unassociatedKeypointsMask[referenceMatch.trainIdx] = false;\n                        mapPoints.emplace_back(mapPoint.GetPosition(), image_thirdFrame->GetKeyPoint(referenceMatch.trainIdx).pt, 1);\n                        mapPointIds.emplace_back(mapPoint.GetId());\n                        thirdFrame->AddAssociation(mapPoint, referenceMatch.trainIdx);\n                    }\n                }\n\n                // if the middle initialization frame isn't adding enough value then abort this init\n                // and look for a better trio of frames\n                if ((float)thirdFrame->GetAssociatedKeypointCount() / (float)initializationData.MapPoints.size() < m_settings.MinThirdFrameMatchPercentage)\n                {\n                    return false;\n                }\n\n                // perform a track local map like bundle adjust of only this third frame to better align it\n                // with the map points that were match above without adjusting the points and culling outliers\n                std::vector<unsigned int> outliers;\n                outliers.reserve(mapPoints.size());\n                const float outlierErrorSquared = m_settings.ExtraFrame_MaxOutlierError * m_settings.ExtraFrame_MaxOutlierError;\n                Pose updatedPose;\n                {\n                    SCOPE_TIMER(MapInitialization::OptimizeThirdCameraPose);\n                    updatedPose = TrackLocalMap::OptimizeCameraPose(\n                        additionalPose,\n                        image_thirdFrame->GetUndistortedCalibration(),\n                        mapPoints,\n                        m_settings.ExtraFrame_BundleAdjustmentSteps,\n                        outlierErrorSquared,\n                        m_settings.ExtraFrame_HuberWidth,\n                        m_determinator,\n                        memory,\n                        outliers);\n                }\n\n                // Cull outliers\n                for (const size_t outlierIndex : outliers)\n                {\n                    thirdFrame->RemoveAssociation(mapPointIds[outlierIndex]);\n                }\n\n                // recheck that outlier culling hasn't dropped our match percentage too low\n                if ((float)thirdFrame->GetAssociatedKeypointCount() / (float)initializationData.MapPoints.size() < m_settings.MinThirdFrameMatchPercentage)\n                {\n                    return false;\n                }\n\n                initializationData.Frames[1]->SetPose(additionalPose);\n                // Create a list of connected keyframes of all of the previous inputed frames\n                // note that Kcs is already expected to contain the 'front' element\n                assert(Kcs.size() == 1 && \"Kcs should contain only one element\");\n                assert(Kcs.front().GetId() == initializationData.Frames.front()->GetId() && \"Kcs should contain the first element\");\n                Kcs.emplace_back(*initializationData.Frames.back());\n\n                // use the middle frame as the seed for creating new map points\n                assert(initializationData.Frames.size() == 3 && \"Expecting three frame initialization\");\n                CreateNewMapPointsHelper(initializationData, Kcs, *initializationData.Frames[1], *tempBagOfWords, m_settings, m_cameraSettings, memory);\n                \n                DETERMINISTIC_CHECK(m_determinator, initializationData.Frames.begin(), initializationData.Frames.end());\n                DETERMINISTIC_CHECK(m_determinator, initializationData.MapPoints.begin(), initializationData.MapPoints.end());\n\n                BundlerSettings finalBundlerSettings{\n                    m_settings.FinalBA_HuberWidth,\n                    m_settings.FinalBA_MaxOutlierError,\n                    m_settings.FinalBA_MaxOutlierErrorScaleFactor,\n                    m_settings.FinalBA_MinMeanSquareError,\n                    false,\n                    m_settings.FinalBA_NumStepsPerRun,\n                    m_settings.FinalBA_NumSteps,\n                    0 };\n\n                BundleAdjustInitializationData(initializationData, m_determinator, true, finalBundlerSettings, memory);\n\n                DETERMINISTIC_CHECK(m_determinator, initializationData.Frames.begin(), initializationData.Frames.end());\n                DETERMINISTIC_CHECK(m_determinator, initializationData.MapPoints.begin(), initializationData.MapPoints.end());\n\n            }\n\n            if (!ValidateInitializationData(initializationData,\n                m_settings.MaxPoseContributionZ,\n                m_settings.AmountBACanChangePose,\n                m_settings.MinMapPoints))\n            {\n                DETERMINISTIC_CHECK(m_determinator, 8794548);\n                return false;\n            }\n\n            LogMessage<Tracing::TraceLevels::Verbose>((boost::wformat(L\"MapInitialization  Initializing attempt success? %s\") % (initializeSucceeded ? \"true\" : \"false\")).str());\n\n            SkeletonLogger::MapInitialization::LogFailure(initializeSucceeded ? \"Initialize succeeded\" : \"Initialize failed\");\n\n            return initializeSucceeded;\n        }\n        return false;\n    }\n\n    void MapInitialization::CollectMatchPoints(\n        const shared_ptr<const AnalyzedImage>& referenceFrame,\n        const shared_ptr<const AnalyzedImage>& currentFrame,\n        gsl::span<const cv::DMatch> matches,\n        vector<cv::Point2f>& frame1_points,\n        vector<cv::Point2f>& frame2_points)\n    {\n        frame1_points.reserve(matches.size());\n        frame2_points.reserve(matches.size());\n\n        const auto& current_kp = currentFrame->GetKeyPoints();\n        const auto& ref_kp = referenceFrame->GetKeyPoints();\n        for (const auto& match : matches)\n        {\n            cv::Point2f point1 = ref_kp[match.queryIdx].pt;\n            cv::Point2f point2 = current_kp[match.trainIdx].pt;\n\n            frame1_points.push_back(point1);\n            frame2_points.push_back(point2);\n        }\n    }\n\n    void MapInitialization::TriangulatePoints(const shared_ptr<const AnalyzedImage>& referenceFrame, \n                                              const shared_ptr<const AnalyzedImage>& currentFrame,\n                                              const Pose& referencePose,\n                                              const Pose& currentPose,\n                                              gsl::span<const cv::DMatch> matches,\n                                              gsl::span<const cv::Point2f> frame1_points,\n                                              gsl::span<const cv::Point2f> frame2_points,\n                                              float pixelMaxEpipolarDistance,\n                                              float minAcceptanceDistanceRatio,\n                                              std::vector<pair<cv::DMatch, cv::Point3f>>& initial3DPoints)\n    {\n        const cv::Matx33f& frame1InvCam = referenceFrame->GetUndistortedCalibration().GetInverseCameraMatrix();\n        const cv::Matx33f& frame2InvCam = currentFrame->GetUndistortedCalibration().GetInverseCameraMatrix();\n        const cv::Matx44f& frame1World = referencePose.GetInverseViewMatrix();\n        const cv::Matx44f& frame2World = currentPose.GetInverseViewMatrix();\n\n        // computed frame elements used for match filtering\n        const auto fundamentalMatrixKcToKi = ComputeFundamentalMatrix(currentPose, currentFrame->GetUndistortedCalibration(), referencePose, referenceFrame->GetUndistortedCalibration());\n        const auto fundamentalMatrixKiToKc = ComputeFundamentalMatrix(referencePose, referenceFrame->GetUndistortedCalibration(), currentPose, currentFrame->GetUndistortedCalibration());\n\n        for (ptrdiff_t pointIterator = 0; pointIterator < frame1_points.size(); pointIterator++)\n        {\n//#define DGBEPI\n#ifdef DBGEPI\n            cv::Mat dbgImg2;\n            cv::cvtColor( referenceFrame->GetDebugImage().clone(), dbgImg2, CV_GRAY2RGB);\n            DebugRenderEpipolarLine(fundamentalMatrixKcToKi, currentFrame->GetKeyPoint(matches[pointIterator].trainIdx).pt, referenceFrame->GetKeyPoint(matches[pointIterator].queryIdx).pt, dbgImg2);\n\n            cv::Mat dbgImg1;\n            cv::cvtColor(currentFrame->GetDebugImage().clone(), dbgImg1, CV_GRAY2RGB);\n            DebugRenderEpipolarLine(fundamentalMatrixKiToKc, referenceFrame->GetKeyPoint(matches[pointIterator].queryIdx).pt, currentFrame->GetKeyPoint(matches[pointIterator].trainIdx).pt, dbgImg1);\n#endif\n\n            // epipolar line test\n            const float KcToKiEpipolarDistance = DistanceFromEpipolarLine(fundamentalMatrixKcToKi, currentFrame->GetKeyPoint(matches[pointIterator].trainIdx).pt, referenceFrame->GetKeyPoint(matches[pointIterator].queryIdx).pt);\n            const float KiToKcEpipolarDistance = DistanceFromEpipolarLine(fundamentalMatrixKiToKc, referenceFrame->GetKeyPoint(matches[pointIterator].queryIdx).pt, currentFrame->GetKeyPoint(matches[pointIterator].trainIdx).pt);\n            if (KiToKcEpipolarDistance + KcToKiEpipolarDistance > 2 * pixelMaxEpipolarDistance)\n            {\n                continue;\n            }\n\n            const cv::Point3f current3DPoint = TriangulatePointWorldSpace(frame1InvCam, frame1World, frame2InvCam, frame2World,\n                frame1_points[pointIterator], frame2_points[pointIterator]);\n         \n            // Validate that the points projects in front of the camera\n            if (!VerifyProjectInFront(referencePose.GetViewMatrix(), referenceFrame->GetUndistortedCalibration().GetCameraMatrix(), current3DPoint)\n                || !VerifyProjectInFront(currentPose.GetViewMatrix(), currentFrame->GetUndistortedCalibration().GetCameraMatrix(), current3DPoint))\n            {\n                continue;\n            }\n\n            // Distance Ratio Test\n            // To avoid creating points near the camera that will be culled later, we do a distance ratio test, where \n            // points that are near the keyframe, relative to the distance between the keyframes that see the point, are\n            // not added.\n            cv::Vec3f KiToTriangulatedPoint = current3DPoint - referencePose.GetWorldSpacePosition();\n            float KiToTriangulatedPointDistance = sqrtf(KiToTriangulatedPoint.dot(KiToTriangulatedPoint));\n            cv::Vec3f KiToKc = referencePose.GetWorldSpacePosition() - currentPose.GetWorldSpacePosition();\n            float KiToKcDistance = sqrtf(KiToKc.dot(KiToKc));\n            float distanceRatio = KiToTriangulatedPointDistance / KiToKcDistance;\n            if (distanceRatio < minAcceptanceDistanceRatio)\n            {\n                continue;\n            }\n\n            // enforce the octaves to match\n            if (referenceFrame->GetKeyPoint(matches[pointIterator].queryIdx).octave != currentFrame->GetKeyPoint(matches[pointIterator].trainIdx).octave)\n            {\n                continue;\n            }\n\n            // TODO enforce gridding?\n\n            initial3DPoints.emplace_back(matches[pointIterator], current3DPoint);\n        }\n    }\n\n    bool MapInitialization::InitializeWithFrames(\n        gsl::span<const cv::DMatch> matches,\n        const shared_ptr<const AnalyzedImage>& referenceFrame, //query\n        const shared_ptr<const AnalyzedImage>& currentFrame,   //train\n        InitializationData& initializationData,\n        thread_memory memory)\n    {\n        SCOPE_TIMER(MapInitialization::InitializeWithFrames);\n\n        // TODO try to refactor so that we use KeyframeBuilders throughout instead?\n        mage::temp::vector<InitializationPose> initializationPoses = memory.stack_vector<InitializationPose>(3);\n\n        std::vector<pair<cv::DMatch, cv::Point3f>> initial3DPoints;\n        // ensure that enough matches have been accepted during the collection step\n        if (matches.size() < (int)m_settings.MinFeatureMatches)\n        {\n            LogMessage<Tracing::TraceLevels::Verbose>(L\"MapInitialization  Not enough accepted matches\");\n            return false;\n        }\n\n        vector<cv::Point2f> frame1_points;\n        vector<cv::Point2f> frame2_points;\n        CollectMatchPoints(referenceFrame, currentFrame, matches, frame1_points, frame2_points);\n\n        Pose referencePose{};\n        Pose currentPose{};\n\n        vector<Pose> possiblePoses = FindPossiblePoses(frame1_points, frame2_points, referenceFrame->GetUndistortedCalibration(), currentFrame->GetUndistortedCalibration());\n        DETERMINISTIC_CHECK(m_determinator, possiblePoses.begin(), possiblePoses.end());\n\n        bool foundPose = FindCorrectPose(frame1_points, frame2_points, matches, referenceFrame->GetUndistortedCalibration(), currentFrame->GetUndistortedCalibration(), referencePose, possiblePoses, currentPose, initial3DPoints);\n        DETERMINISTIC_CHECK(m_determinator, foundPose);\n\n        if (!foundPose)\n        {\n            LogMessage<Tracing::TraceLevels::Verbose>(L\"MapInitialization didn't find correct pose\");\n            return false;\n        }\n\n        assert(m_initializationFrames.size() >= 2);\n        DETERMINISTIC_CHECK(m_determinator, initial3DPoints.data(), sizeof(initial3DPoints.front()) * initial3DPoints.size());\n\n        // compute the associations with the resulting map points\n        std::vector<PointAssociation> frontAssociations;\n        std::vector<PointAssociation> backAssociations;\n        frontAssociations.reserve(initial3DPoints.size());\n        backAssociations.reserve(initial3DPoints.size());\n\n        for (size_t iterator = 0; iterator < initial3DPoints.size(); iterator++)\n        {\n            frontAssociations.emplace_back(static_cast<size_t>(initial3DPoints[iterator].first.queryIdx), iterator);\n            backAssociations.emplace_back(static_cast<size_t>(initial3DPoints[iterator].first.trainIdx), iterator);\n        }\n\n        initializationPoses.clear();\n        initializationPoses.emplace_back(m_initializationFrames.front().Image, referencePose, frontAssociations);\n\n        // add a placeholder for the third frame\n        bool addThirdFrame = m_initializationFrames.size() > 2;\n        if (addThirdFrame)\n        {\n            MatchedImage additionalImage = m_initializationFrames[m_initializationFrames.size() / 2];\n            initializationPoses.emplace_back(additionalImage.Image, Pose(), std::vector<PointAssociation>{});\n        }\n\n        // add the back frame\n        initializationPoses.emplace_back(m_initializationFrames.back().Image, currentPose, backAssociations);\n\n        // create the initialization map\n        {\n            // create the mappoint proxies to link the keyframe builders to\n            initializationData.Clear();\n\n            std::transform(initial3DPoints.cbegin(), initial3DPoints.cend(), std::back_inserter(initializationData.MapPoints),\n                [](const auto& point3D)\n            {\n                // MapInitialization map points are special and get treated as though they have been adjusted once already (which is technically true)\n                return MapPointTrackingProxy::CreateNew(point3D.second, 1);\n            });\n\n            DETERMINISTIC_CHECK(m_determinator, initializationData.Frames.begin(), initializationData.Frames.end());\n\n            // populate up keyframebuilders with the information we have created thus far\n            for (size_t i = 0; i < initializationPoses.size(); i++)\n            {\n                const InitializationPose& initializationPose = initializationPoses[i];\n                const std::shared_ptr<KeyframeBuilder>& keyframeBuilder = initializationData.AddKeyframeBuilder(initializationPose.Image, initializationPose.Pose);\n\n                DETERMINISTIC_CHECK(m_determinator, *keyframeBuilder);\n\n                // add all the point associations to the first and last frames\n                if (i == 0 || i == initializationPoses.size() - 1)\n                {\n                    for (const auto& assoc : initializationPose.Associations)\n                    {\n                        keyframeBuilder->AddAssociation(initializationData.MapPoints[assoc.PointIndex3d], assoc.PointIndex2d);\n                    }\n                }\n\n                DETERMINISTIC_CHECK(m_determinator, *keyframeBuilder);\n            }\n\n            DETERMINISTIC_CHECK(m_determinator, initializationData.Frames.begin(), initializationData.Frames.end());\n        }\n\n        return true;\n    }\n\n    void MapInitialization::BundleAdjustInitializationData(InitializationData& initializationData, mira::determinator& determinator, bool cullOutliers, const BundlerSettings& bundlerSettings, thread_memory memory)\n    {\n        // now bundle adjust the whole system to get a better positions and map point locations\n        AdjustableData baData{};\n\n        baData.Keyframes.reserve(initializationData.Frames.size());\n        for (const auto& builder : initializationData.Frames)\n        {\n            baData.Keyframes.emplace_back(Proxy<Keyframe, proxy::Image, proxy::Pose, proxy::Intrinsics, proxy::PoseConstraints>{*builder});\n\n            builder->IterateAssociations([&](const MapPointTrackingProxy& mp, KeypointDescriptorIndex idx)\n            {\n                baData.MapPointAssociations.emplace_back(builder->GetAnalyzedImage()->GetKeyPoint(idx).pt, mp.GetId(), builder->GetId());\n            });\n        }\n\n        // only the first keyframe is fixed, all others are allowed to float\n        baData.Keyframes.front().SetFixed(true);\n\n        std::swap(baData.MapPoints, initializationData.MapPoints);\n\n        BundleAdjust ba{ baData, determinator, memory };\n        ba.RunBundleAdjustment(\n            BundleAdjust::NoOpScheduler{},\n            bundlerSettings.HuberWidth,\n            bundlerSettings.MaxOutlierError,\n            bundlerSettings.MaxOutlierErrorScaleFactor,\n            bundlerSettings.MinMeanSquareError,\n            bundlerSettings.FixMapPoints,\n            bundlerSettings.NumStepsPerRun,\n            bundlerSettings.NumSteps,\n            bundlerSettings.MinSteps,\n            memory);\n\n        auto outliers = ba.GetOutliers();\n\n        DETERMINISTIC_CHECK(determinator, baData.Keyframes);\n        DETERMINISTIC_CHECK(determinator, baData.MapPoints);\n        DETERMINISTIC_CHECK(determinator, baData.MapPointAssociations);\n        DETERMINISTIC_CHECK(determinator, outliers.data(), sizeof(outliers[0]) * outliers.size());\n\n        std::swap(baData.MapPoints, initializationData.MapPoints);\n\n        // update the keyframes\n        for (size_t keyframeIterator = 0; keyframeIterator < baData.Keyframes.size(); keyframeIterator++)\n        {\n            // skip keyframes that were marked as fixed\n            if (!baData.Keyframes[keyframeIterator].IsFixed())\n            {\n                initializationData.Frames[keyframeIterator]->SetPose(baData.Keyframes[keyframeIterator].GetPose());\n            }\n\n            // update the position of the mappoints in the keyframe builders by iterating over the associations\n            initializationData.Frames[keyframeIterator]->IterateAssociations([&initializationData](MapPointTrackingProxy& mp, KeypointDescriptorIndex /*idx*/)\n            {\n                auto foundMapPoint = std::find_if(initializationData.MapPoints.begin(), initializationData.MapPoints.end(), [&mp](const MapPointTrackingProxy& adjustedMapPoint)\n                {\n                    return mp.GetId() == adjustedMapPoint.GetId();\n                });\n                assert(foundMapPoint != initializationData.MapPoints.end());\n\n                mp.SetPosition(foundMapPoint->GetPosition());\n            });\n        }\n\n        DETERMINISTIC_CHECK(determinator, initializationData.Frames.begin(), initializationData.Frames.end());\n\n        if (cullOutliers)\n        {\n\n            // compute initial association counts for map points\n            mage::temp::vector<std::pair<const Id<MapPoint>, int>> mapPointAssociationCounts = memory.stack_vector<std::pair<const Id<MapPoint>, int>>(initializationData.MapPoints.size());\n            for (const MapPointTrackingProxy& proxy : initializationData.MapPoints)\n            {\n                mapPointAssociationCounts.emplace_back(proxy.GetId(), 0);\n            };\n            for (const auto& keyframe : initializationData.Frames)\n            {\n                std::vector<MapPointAssociations<MapPointTrackingProxy>::Association> associations;\n                keyframe->GetAssociations(associations);\n                for (const MapPointAssociations<MapPointTrackingProxy>::Association& assoc : associations)\n                {\n                    auto pair = std::find_if(mapPointAssociationCounts.begin(), mapPointAssociationCounts.end(), [assoc](auto& candidatePair) { return assoc.MapPoint.GetId() == candidatePair.first; });\n                    pair->second++;\n                }\n            }\n\n            DETERMINISTIC_CHECK(determinator, initializationData.Frames.begin(), initializationData.Frames.end());\n\n            // cull the outlier associations\n            for (const auto& outlierAssociation : outliers)\n            {\n                // find the associated keyframe\n                auto keyframe = std::find_if(initializationData.Frames.begin(), initializationData.Frames.end(),\n                    [outlierAssociation](auto& kb) { return kb->GetId() == outlierAssociation.second; });\n                assert(keyframe != initializationData.Frames.end());\n\n                // find the associated map point\n                auto mapPoint = std::find_if(initializationData.MapPoints.cbegin(), initializationData.MapPoints.cend(),\n                    [outlierAssociation](auto& mp) { return mp.GetId() == outlierAssociation.first; });\n                assert(mapPoint != initializationData.MapPoints.end());\n\n                keyframe->get()->RemoveAssociation(mapPoint->GetId());\n                auto pair = std::find_if(mapPointAssociationCounts.begin(), mapPointAssociationCounts.end(), [mapPoint](auto& candidatePair) { return mapPoint->GetId() == candidatePair.first; });\n                pair->second--;\n            }\n\n            DETERMINISTIC_CHECK(determinator, initializationData.Frames.begin(), initializationData.Frames.end());\n\n            // now we need to go through and remove any map points which no longer have enough connections and disassociate them\n            for (const auto& associationCount : mapPointAssociationCounts)\n            {\n                if (associationCount.second < 2)\n                {\n                    // remove this from any keyframes, and then remove the map point all together\n                    for (auto& keyframe : initializationData.Frames)\n                    {\n                        keyframe->TryRemoveAssociation(associationCount.first);\n                    }\n\n                    // remove the element from the vector by swapping the back (order doesn't matter for us)\n                    auto iter = std::find_if(initializationData.MapPoints.begin(), initializationData.MapPoints.end(), [associationCount](const MapPointTrackingProxy& proxy) { return associationCount.first == proxy.GetId(); });\n                    assert(iter != initializationData.MapPoints.end());\n                    std::swap(*iter, initializationData.MapPoints.back());\n                    initializationData.MapPoints.pop_back();\n                }\n            }\n\n            DETERMINISTIC_CHECK(determinator, initializationData.Frames.begin(), initializationData.Frames.end());\n        }\n    }\n\n    bool MapInitialization::ValidateInitializationData(const InitializationData& initializationData,\n        float maxPoseContributionZ,\n        float amountBACanChangePose,\n        size_t minMapPoints)\n    {\n        if (initializationData.MapPoints.size() < minMapPoints)\n        {\n            return false;\n        }\n\n        //TODO: check for reversed init after bundle adjustment\n\n        // make sure that normalized the bundled system isn't too Z biassed\n        const cv::Point3f& world = initializationData.Frames.back()->GetPose().GetWorldSpacePosition();\n        const cv::Point3f normalizedWorld = Normalize(world);\n        if (abs(normalizedWorld.z) > maxPoseContributionZ)\n        {\n            return false;\n        }\n\n        // enforce that the 'back' frame is close to initial scale (1.0)\n        float scale = sqrt(world.dot(world));\n        if ((amountBACanChangePose != 0) && ((scale < 1.0f / amountBACanChangePose) || (scale > 1.0f * amountBACanChangePose)))\n        {\n            return false;\n        }\n\n        // enforce that any extra frames are at a reasonable scale 2x initial scale\n        // note that pose[0] should be identity, and pose[size-1] should be near to 1 as verified above\n        for (size_t iterator = 1; iterator < initializationData.Frames.size() - 1; iterator++)\n        {\n            const cv::Point3f& position = initializationData.Frames[iterator]->GetPose().GetWorldSpacePosition();\n            float norm = sqrt(position.dot(position));\n            if (norm > 2.0f * scale)\n            {\n                return false;\n            }\n        }\n\n        return true;\n    }\n}\n", "meta": {"hexsha": "2c22c3401d05bda3acb0250afa9ddddbd2e64cc6", "size": 62621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Core/MAGESLAM/Source/Tracking/MapInitialization.cpp", "max_stars_repo_name": "syntheticmagus/mageslam", "max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z", "max_issues_repo_path": "Core/MAGESLAM/Source/Tracking/MapInitialization.cpp", "max_issues_repo_name": "syntheticmagus/mageslam", "max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z", "max_forks_repo_path": "Core/MAGESLAM/Source/Tracking/MapInitialization.cpp", "max_forks_repo_name": "syntheticmagus/mageslam", "max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z", "avg_line_length": 49.3078740157, "max_line_length": 275, "alphanum_fraction": 0.6268823558, "num_tokens": 12991, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.21434999271763866}}
{"text": "////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n/// @project        Open Space Toolkit ▸ Physics\n/// @file           OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/IERS/Finals2000A.cpp\n/// @author         Lucas Brémond <lucas@loftorbital.com>\n/// @license        Apache License 2.0\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n#include <OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/IERS/Finals2000A.hpp>\n\n#include <OpenSpaceToolkit/Core/Types/String.hpp>\n#include <OpenSpaceToolkit/Core/Error.hpp>\n#include <OpenSpaceToolkit/Core/Utilities.hpp>\n\n#include <boost/lexical_cast.hpp>\n\n#include <sstream>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nnamespace ostk\n{\nnamespace physics\n{\nnamespace coord\n{\nnamespace frame\n{\nnamespace provider\n{\nnamespace iers\n{\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nstd::ostream&                   operator <<                                 (           std::ostream&               anOutputStream,\n                                                                                const   Finals2000A&                aFinals2000A                                )\n{\n\n    using ostk::core::types::String ;\n\n    using ostk::physics::time::Scale ;\n\n    ostk::core::utils::Print::Header(anOutputStream, \"Finals 2000A\") ;\n\n    ostk::core::utils::Print::Line(anOutputStream) << \"Interval:\" << (aFinals2000A.getInterval().isDefined() ? aFinals2000A.getInterval().toString(Scale::UTC) : \"Undefined\") ;\n\n    ostk::core::utils::Print::Footer(anOutputStream) ;\n\n    return anOutputStream ;\n\n}\n\nbool                            Finals2000A::isDefined                      ( ) const\n{\n    return !data_.empty() ;\n}\n\nInterval                        Finals2000A::getInterval                    ( ) const\n{\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Finals 2000A\") ;\n    }\n\n    return span_ ;\n\n}\n\nVector2d                        Finals2000A::getPolarMotionAt               (   const   Instant&                    anInstant                                   ) const\n{\n\n    using ostk::physics::time::Scale ;\n\n    if (!anInstant.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Instant\") ;\n    }\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Finals 2000A\") ;\n    }\n\n    const Pair<const Finals2000A::Data*, const Finals2000A::Data*> dataRange = this->accessDataRange(anInstant) ;\n\n    if ((dataRange.first != nullptr) && (dataRange.second != nullptr))\n    {\n\n        const Finals2000A::Data& previousData = *(dataRange.first) ;\n        const Finals2000A::Data& nextData = *(dataRange.second) ;\n\n        if (previousData.x_A.isDefined() && previousData.y_A.isDefined() && nextData.x_A.isDefined() && nextData.y_A.isDefined())\n        {\n\n            const Real instantMjd_UTC = anInstant.getModifiedJulianDate(Scale::UTC) ;\n\n            const Real ratio = (instantMjd_UTC - previousData.mjd) / (nextData.mjd - previousData.mjd) ;\n\n            const Real x_A = previousData.x_A + ratio * (nextData.x_A - previousData.x_A) ;\n            const Real y_A = previousData.y_A + ratio * (nextData.y_A - previousData.y_A) ;\n\n            return { x_A, y_A } ;\n\n        }\n        else\n        {\n            return Vector2d::Undefined() ;\n        }\n\n    }\n\n    throw ostk::core::error::RuntimeError(\"Cannot get polar motion at [{}].\", anInstant.toString(Scale::UTC)) ;\n\n}\n\nReal                            Finals2000A::getUt1MinusUtcAt               (   const   Instant&                    anInstant                                   ) const\n{\n\n    using ostk::physics::time::Scale ;\n\n    if (!anInstant.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Instant\") ;\n    }\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Finals 2000A\") ;\n    }\n\n    const Pair<const Finals2000A::Data*, const Finals2000A::Data*> dataRange = this->accessDataRange(anInstant) ;\n\n    if ((dataRange.first != nullptr) && (dataRange.second != nullptr))\n    {\n\n        const Finals2000A::Data& previousData = *(dataRange.first) ;\n        const Finals2000A::Data& nextData = *(dataRange.second) ;\n\n        if (previousData.ut1MinusUtc_A.isDefined() && nextData.ut1MinusUtc_A.isDefined())\n        {\n\n            const Real instantMjd_UTC = anInstant.getModifiedJulianDate(Scale::UTC) ;\n\n            const Real ratio = (instantMjd_UTC - previousData.mjd) / (nextData.mjd - previousData.mjd) ;\n\n            const Real ut1MinusUtc_A = previousData.ut1MinusUtc_A + ratio * (nextData.ut1MinusUtc_A - previousData.ut1MinusUtc_A) ;\n            // const Real ut1MinusUtc_B = previousData.ut1MinusUtc_B + ratio * (nextData.ut1MinusUtc_B - previousData.ut1MinusUtc_B) ;\n\n            return ut1MinusUtc_A ;\n\n        }\n        else\n        {\n            return Real::Undefined() ;\n        }\n\n    }\n\n    throw ostk::core::error::RuntimeError(\"Cannot get UT1 - UTC at [{}].\", anInstant.toString(Scale::UTC)) ;\n\n}\n\nReal                            Finals2000A::getLodAt                       (   const   Instant&                    anInstant                                   ) const\n{\n\n    using ostk::physics::time::Scale ;\n\n    if (!anInstant.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Instant\") ;\n    }\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Finals 2000A\") ;\n    }\n\n    const Pair<const Finals2000A::Data*, const Finals2000A::Data*> dataRange = this->accessDataRange(anInstant) ;\n\n    if ((dataRange.first != nullptr) && (dataRange.second != nullptr))\n    {\n\n        const Finals2000A::Data& previousData = *(dataRange.first) ;\n        const Finals2000A::Data& nextData = *(dataRange.second) ;\n\n        if (previousData.lod_A.isDefined() && nextData.lod_A.isDefined())\n        {\n\n            const Real instantMjd_UTC = anInstant.getModifiedJulianDate(Scale::UTC) ;\n\n            const Real ratio = (instantMjd_UTC - previousData.mjd) / (nextData.mjd - previousData.mjd) ;\n\n            const Real lod_A = previousData.lod_A + ratio * (nextData.lod_A - previousData.lod_A) ;\n\n            return lod_A ;\n\n        }\n        else\n        {\n            return Real::Undefined() ;\n        }\n\n    }\n\n    throw ostk::core::error::RuntimeError(\"Cannot get length of day at [{}].\", anInstant.toString(Scale::UTC)) ;\n\n}\n\nFinals2000A::Data               Finals2000A::getDataAt                      (   const   Instant&                    anInstant                                   ) const\n{\n\n    using ostk::physics::time::Scale ;\n\n    if (!anInstant.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Instant\") ;\n    }\n\n    if (!this->isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"Finals 2000A\") ;\n    }\n\n    const Pair<const Finals2000A::Data*, const Finals2000A::Data*> dataRange = this->accessDataRange(anInstant) ;\n\n    if ((dataRange.first != nullptr) && (dataRange.second != nullptr))\n    {\n\n        auto interpolate = [] (const Real& aPreviousValue, const Real& aNextValue, const Real& aRatio) -> Real\n        {\n\n            if (!aRatio.isDefined())\n            {\n                throw ostk::core::error::runtime::Undefined(\"Ratio\") ;\n            }\n\n            if (aPreviousValue.isDefined() && aNextValue.isDefined())\n            {\n                return aPreviousValue + aRatio * (aNextValue - aPreviousValue) ;\n            }\n\n            return Real::Undefined() ;\n\n        } ;\n\n        const Finals2000A::Data& previousData = *(dataRange.first) ;\n        const Finals2000A::Data& nextData = *(dataRange.second) ;\n\n        const Real instantMjd_UTC = anInstant.getModifiedJulianDate(Scale::UTC) ;\n\n        const Real ratio = (instantMjd_UTC - previousData.mjd) / (nextData.mjd - previousData.mjd) ;\n\n        const Integer year = previousData.year ;\n        const Integer month = previousData.month ;\n        const Integer day = previousData.day ;\n\n        const Real mjd = interpolate(previousData.mjd, nextData.mjd, ratio) ;\n\n        const char polarMotionflag = (previousData.polarMotionflag == nextData.polarMotionflag) ? previousData.polarMotionflag : '?' ;\n\n        const Real x_A = interpolate(previousData.x_A, nextData.x_A, ratio) ;\n        const Real xError_A = interpolate(previousData.xError_A, nextData.xError_A, ratio) ;\n        const Real y_A = interpolate(previousData.y_A, nextData.y_A, ratio) ;\n        const Real yError_A = interpolate(previousData.yError_A, nextData.yError_A, ratio) ;\n\n        const char ut1MinusUtcFlag = (previousData.ut1MinusUtcFlag == nextData.ut1MinusUtcFlag) ? previousData.ut1MinusUtcFlag : '?' ;\n\n        const Real ut1MinusUtc_A = interpolate(previousData.ut1MinusUtc_A, nextData.ut1MinusUtc_A, ratio) ;\n        const Real ut1MinusUtcError_A = interpolate(previousData.ut1MinusUtcError_A, nextData.ut1MinusUtcError_A, ratio) ;\n        const Real lod_A = interpolate(previousData.lod_A, nextData.lod_A, ratio) ;\n        const Real lodError_A = interpolate(previousData.lodError_A, nextData.lodError_A, ratio) ;\n\n        const char nutationFlag = (previousData.nutationFlag == nextData.nutationFlag) ? previousData.nutationFlag : '?' ;\n\n        const Real dx_A = interpolate(previousData.dx_A, nextData.dx_A, ratio) ;\n        const Real dxError_A = interpolate(previousData.dxError_A, nextData.dxError_A, ratio) ;\n        const Real dy_A = interpolate(previousData.dy_A, nextData.dy_A, ratio) ;\n        const Real dyError_A = interpolate(previousData.dyError_A, nextData.dyError_A, ratio) ;\n        const Real x_B = interpolate(previousData.x_B, nextData.x_B, ratio) ;\n        const Real y_B = interpolate(previousData.y_B, nextData.y_B, ratio) ;\n        const Real ut1MinusUtc_B = interpolate(previousData.ut1MinusUtc_B, nextData.ut1MinusUtc_B, ratio) ;\n        const Real dx_B = interpolate(previousData.dx_B, nextData.dx_B, ratio) ;\n        const Real dy_B = interpolate(previousData.dy_B, nextData.dy_B, ratio) ;\n\n        const Finals2000A::Data data =\n        {\n            year,\n            month,\n            day,\n            mjd,\n            polarMotionflag,\n            x_A,\n            xError_A,\n            y_A,\n            yError_A,\n            ut1MinusUtcFlag,\n            ut1MinusUtc_A,\n            ut1MinusUtcError_A,\n            lod_A,\n            lodError_A,\n            nutationFlag,\n            dx_A,\n            dxError_A,\n            dy_A,\n            dyError_A,\n            x_B,\n            y_B,\n            ut1MinusUtc_B,\n            dx_B,\n            dy_B\n        } ;\n\n        return data ;\n\n    }\n\n    throw ostk::core::error::RuntimeError(\"Cannot get data at [{}].\", anInstant.toString(Scale::UTC)) ;\n\n}\n\nFinals2000A                     Finals2000A::Undefined                      ( )\n{\n    return Finals2000A() ;\n}\n\nFinals2000A                     Finals2000A::Load                           (   const   fs::File&                   aFile                                       )\n{\n\n    using ostk::core::types::Index ;\n    using ostk::core::types::Uint8 ;\n    using ostk::core::types::Uint16 ;\n    using ostk::core::types::Real ;\n    using ostk::core::types::String ;\n    using ostk::core::ctnr::Array ;\n\n    using ostk::physics::time::Scale ;\n    using ostk::physics::time::Time ;\n    using ostk::physics::time::DateTime ;\n\n    if (!aFile.isDefined())\n    {\n        throw ostk::core::error::runtime::Undefined(\"File\") ;\n    }\n\n    if (!aFile.exists())\n    {\n        throw ostk::core::error::RuntimeError(\"File [{}] does not exist.\", aFile.toString()) ;\n    }\n\n    Finals2000A finals2000a ;\n\n    std::ifstream fileStream(aFile.getPath().toString()) ;\n\n    Index lineIndex = 0 ;\n    String line ;\n\n    // auto splitString = [] (const String& aString, char aDelimiter) -> Array<String>\n    // {\n\n    //     Array<String> aStringArray = Array<String>::Empty() ;\n\n    //     std::stringstream stringStream(aString) ;\n\n    //     String item ;\n\n    //     while (std::getline(stringStream, item, aDelimiter))\n    //     {\n\n    //         if (!item.empty())\n    //         {\n    //             aStringArray.add(item) ;\n    //         }\n\n    //     }\n\n    //     return aStringArray ;\n\n    // } ;\n\n    auto parseReal = [] (const String& aLine, const Index& aStartColumnNumber, const Index& anEndColumnNumber) -> Real\n    {\n\n        String string = aLine.getSubstring(aStartColumnNumber - 1, anEndColumnNumber - aStartColumnNumber + 1).trim() ;\n\n        if (string.isEmpty())\n        {\n            return Real::Undefined() ;\n        }\n\n        if ((string.getLength() > 2) && (string.getHead(1) == \".\"))\n        {\n            string = \"0.\" + string.getTail(string.getLength() - 1) ;\n        }\n\n        if ((string.getLength() > 2) && (string.getHead(2) == \"-.\"))\n        {\n            string = \"-0.\" + string.getTail(string.getLength() - 2) ;\n        }\n\n        return Real::Parse(string) ;\n\n    } ;\n\n    while (std::getline(fileStream, line))\n    {\n\n        const Integer year = Integer::Parse(line.getSubstring(0, 2).trim()) ;\n        const Integer month = Integer::Parse(line.getSubstring(2, 2).trim()) ;\n        const Integer day = Integer::Parse(line.getSubstring(4, 2).trim()) ;\n\n        const Real mjd = parseReal(line, 8, 15) ;\n\n        const char polarMotionflag = line.at(16) ;\n\n        const Real x_A = parseReal(line, 19, 27) ;\n        const Real xError_A = parseReal(line, 28, 36) ;\n        const Real y_A = parseReal(line, 38, 46) ;\n        const Real yError_A = parseReal(line, 47, 55) ;\n\n        const char ut1MinusUtcFlag = line.at(57) ;\n\n        const Real ut1MinusUtc_A = parseReal(line, 59, 68) ;\n        const Real ut1MinusUtcError_A = parseReal(line, 69, 78) ;\n        const Real lod_A = parseReal(line, 80, 86) ;\n        const Real lodError_A = parseReal(line, 87, 93) ;\n\n        const char nutationFlag = line.at(95) ;\n\n        const Real dx_A = parseReal(line, 98, 106) ;\n        const Real dxError_A = parseReal(line, 107, 115) ;\n        const Real dy_A = parseReal(line, 117, 125) ;\n        const Real dyError_A = parseReal(line, 126, 134) ;\n        const Real x_B = parseReal(line, 135, 144) ;\n        const Real y_B = parseReal(line, 145, 154) ;\n        const Real ut1MinusUtc_B = parseReal(line, 155, 165) ;\n        const Real dx_B = parseReal(line, 166, 175) ;\n        const Real dy_B = parseReal(line, 176, 185) ;\n\n        const Finals2000A::Data data =\n        {\n            year,\n            month,\n            day,\n            mjd,\n            polarMotionflag,\n            x_A,\n            xError_A,\n            y_A,\n            yError_A,\n            ut1MinusUtcFlag,\n            ut1MinusUtc_A,\n            ut1MinusUtcError_A,\n            lod_A,\n            lodError_A,\n            nutationFlag,\n            dx_A,\n            dxError_A,\n            dy_A,\n            dyError_A,\n            x_B,\n            y_B,\n            ut1MinusUtc_B,\n            dx_B,\n            dy_B\n        } ;\n\n        finals2000a.data_.insert({ mjd, data }) ;\n\n        lineIndex++ ;\n\n    }\n\n    if (!finals2000a.data_.empty())\n    {\n\n        const Instant startInstant = Instant::ModifiedJulianDate(finals2000a.data_.begin()->first, Scale::UTC) ;\n        const Instant endInstant = Instant::ModifiedJulianDate(finals2000a.data_.rbegin()->first, Scale::UTC) ;\n\n        finals2000a.span_ = Interval::Closed(startInstant, endInstant) ;\n\n    }\n\n    return finals2000a ;\n\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n                                Finals2000A::Finals2000A                    ( )\n                                :   span_(Interval::Undefined()),\n                                    data_(Map<Real, Finals2000A::Data>())\n{\n\n}\n\nPair<const Finals2000A::Data*, const Finals2000A::Data*> Finals2000A::accessDataRange ( const Instant&              anInstant                                   ) const\n{\n\n    using ostk::physics::time::Scale ;\n\n    const Real instantMjd_UTC = anInstant.getModifiedJulianDate(Scale::UTC) ;\n\n    const auto nextDataIt = data_.lower_bound(instantMjd_UTC) ;\n\n    if (nextDataIt == data_.end())\n    {\n        return { &(data_.rbegin()->second), nullptr } ;\n    }\n    else if (nextDataIt == data_.begin())\n    {\n        return { nullptr, &(nextDataIt->second) } ;\n    }\n    else\n    {\n\n        const auto previousDataIt = std::prev(nextDataIt) ;\n\n        return { &(previousDataIt->second), &(nextDataIt->second) } ;\n\n    }\n\n    return { nullptr, nullptr } ;\n\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n}\n}\n}\n}\n}\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n", "meta": {"hexsha": "3d80321564b269886018d4b5408ec88488f037b9", "size": 17320, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/IERS/Finals2000A.cpp", "max_stars_repo_name": "robinpdm/open-space-toolkit-physics", "max_stars_repo_head_hexsha": "b53e5d4287fa6568d700cb8942c9a56d57b8d7cf", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-03-30T11:51:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-02T15:20:44.000Z", "max_issues_repo_path": "src/OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/IERS/Finals2000A.cpp", "max_issues_repo_name": "robinpdm/open-space-toolkit-physics", "max_issues_repo_head_hexsha": "b53e5d4287fa6568d700cb8942c9a56d57b8d7cf", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 24.0, "max_issues_repo_issues_event_min_datetime": "2018-06-25T08:06:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-05T20:34:02.000Z", "max_forks_repo_path": "src/OpenSpaceToolkit/Physics/Coordinate/Frame/Providers/IERS/Finals2000A.cpp", "max_forks_repo_name": "robinpdm/open-space-toolkit-physics", "max_forks_repo_head_hexsha": "b53e5d4287fa6568d700cb8942c9a56d57b8d7cf", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T18:18:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-02T05:06:53.000Z", "avg_line_length": 31.9557195572, "max_line_length": 175, "alphanum_fraction": 0.5344688222, "num_tokens": 4055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.21431268182708402}}
{"text": "/**\n * @file   ev_record.hpp\n * @author Yi Zhang <yiz@Yis-MacBook-Pro.local>\n * @date   Wed Aug 26 23:43:13 2020\n * \n * @brief  raw event record\n * \n * \n */\n#ifndef STAN_MATH_TORSTEN_NONMEN_EVENTS_RECORD_HPP\n#define STAN_MATH_TORSTEN_NONMEN_EVENTS_RECORD_HPP\n\n#include <stan/math/prim/fun/value_of.hpp>\n#include <stan/math/rev/fun/value_of.hpp>\n#include <stan/math/prim/meta/return_type.hpp>\n#include <Eigen/Dense>\n#include <numeric>\n#include <string>\n#include <vector>\n\nnamespace torsten {\n\n  /**\n   * Raw events record in the form of NONMEN, except that\n   * for the population input @c len consisting of data record\n   * length for each individual.\n   * @tparam T0 type of scalar for time of events. \n   * @tparam T1 type of scalar for amount at each event.\n   * @tparam T2 type of scalar for rate at each event.\n   * @tparam T3 type of scalar for inter-dose inteveral at each event.\n   * @tparam theta_container type of container for parameter. <code>linode</code> model uses\n   *         matrix as parameter, other than <code>std::vector</code> used by others.\n   */\n  template <typename T0, typename T1, typename T2, typename T3>\n  struct NONMENEventsRecord {\n    using T_scalar = typename stan::return_type_t<T0, T1, T2, T3>;\n    using T_time = typename stan::return_type_t<T0, T1, T2, T3>;\n    using T_rate = T2;\n    using T_amt = T1;\n    using T_par_rate = T2;\n    using T_par_ii = T3;\n\n  private:\n    /// <code>len</code> needs actual variable to ref to.\n    const std::vector<int> len_1_;\n\n  public:\n    static const double lag_time_min; /**< minimum lag time allowed */\n\n    /// nb. of compartments\n    const int ncmt;\n    /// begin id for each subject in concat vector <code>time_</code>, etc\n    std::vector<int> begin_;\n    /// data length for each subject\n    const std::vector<int>& len_;\n    /// nb. of events in the entire population\n    const int total_num_event_times;\n    /// event time\n    const std::vector<T0>& time_;\n    /// dosing amount\n    const std::vector<T1>& amt_;\n    /// dosing rate\n    const std::vector<T2>& rate_;\n    /// dosing interval\n    const std::vector<T3>& ii_;\n    /// dosing event id\\n\n    ///      (0) observation\\n\n    ///      (1) dosing\\n\n    ///      (2) other\\n\n    ///      (3) reset\\n\n    ///      (4) reset AND dosing\n    const std::vector<int>& evid_;\n    /// event compartment\n    const std::vector<int>& cmt_;\n    /// nb. of additional doses\n    const std::vector<int>& addl_;\n    /// steady-states flag\n    const std::vector<int>& ss_;\n\n    /**\n     * Constructor using population data with parameter give as\n     * matrix, such as in linear ODE models\n     * @param[in] n number of compartments in model\n     * @param[in] len record length for each individual.\n     * @param[in] time times of events  \n     * @param[in] amt amount at each event\n     * @param[in] rate rate at each event\n     * @param[in] ii inter-dose interval at each event\n     * @param[in] evid event identity: \\n\n     *                    (0) observation\\n \n     *                    (1) dosing\\n\n     *                    (2) other \\n\n     *                    (3) reset \\n\n     *                    (4) reset AND dosing \n     * @param[in] cmt compartment number at each event \n     * @param[in] addl additional dosing at each event \n     * @param[in] ss steady state approximation at each event (0: no, 1: yes)\n     */\n    template <typename T0_, typename T1_, typename T2_, typename T3_>\n    NONMENEventsRecord(int n,\n                       const std::vector<int>& len,\n                       const std::vector<T0_>& time,\n                       const std::vector<T1_>& amt,\n                       const std::vector<T2_>& rate,\n                       const std::vector<T3_>& ii,\n                       const std::vector<int>& evid,\n                       const std::vector<int>& cmt,\n                       const std::vector<int>& addl,\n                       const std::vector<int>& ss) :\n      len_1_(),\n      ncmt(n),\n      begin_(len.size()),\n      len_(len),\n      total_num_event_times(std::accumulate(len_.begin(), len_.end(), 0)),\n      time_   (time  ),\n      amt_    (amt   ),\n      rate_   (rate   ),\n      ii_     (ii     ),\n      evid_   (evid   ),\n      cmt_    (cmt    ),\n      addl_   (addl   ),\n      ss_     (ss     )\n    {\n      begin_[0] = 0;\n      std::partial_sum(len.begin(), len.end() - 1, begin_.begin() + 1);\n    }\n\n    /**\n     * Constructor using individual data with parameter give as\n     * matrix, such as in linear ODE models\n     * @param[in] n number of compartments in model\n     * @param[in] time times of events  \n     * @param[in] amt amount at each event\n     * @param[in] rate rate at each event\n     * @param[in] ii inter-dose interval at each event\n     * @param[in] evid event identity: \\n\n     *                    (0) observation \\n\n     *                    (1) dosing\\n\n     *                    (2) other \\n\n     *                    (3) reset \\n\n     *                    (4) reset AND dosing \n     * @param[in] cmt compartment number at each event \n     * @param[in] addl additional dosing at each event \n     * @param[in] ss steady state approximation at each event (0: no, 1: yes)\n     */\n    template <typename T0_, typename T1_, typename T2_, typename T3_>\n    NONMENEventsRecord(int n,\n                       const std::vector<T0_>& time,\n                       const std::vector<T1_>& amt,\n                       const std::vector<T2_>& rate,\n                       const std::vector<T3_>& ii,\n                       const std::vector<int>& evid,\n                       const std::vector<int>& cmt,\n                       const std::vector<int>& addl,\n                       const std::vector<int>& ss) :\n      len_1_(1, time.size()),\n      ncmt(n),\n      begin_{0},\n      len_(len_1_),\n      total_num_event_times(std::accumulate(len_.begin(), len_.end(), 0)),\n      time_   (time   ),\n      amt_    (amt    ),\n      rate_   (rate   ),\n      ii_     (ii     ),\n      evid_   (evid   ),\n      cmt_    (cmt    ),\n      addl_   (addl   ),\n      ss_     (ss     )\n    {}\n  \n    /** \n     * begin of parameters for a subject @c id\n     * in @c pMatrix. It is assumed that all the paramter are\n     * either constant or time dependent.\n     *\n     * @param id subject id\n     * \n     * @return begin index in @c pMatrix for the subject\n     */\n    template<typename T>\n    int begin_param(int id, const std::vector<T>& param) const {\n      return param.size() == len_.size() ? id : begin_[id];\n    }\n\n    /**\n     * length of parameters for a subject @c id\n     * in @c pMatrix. It is assumed that all the paramter are\n     * either constant or time dependent.\n     *\n     * @param id subject id\n     * \n     * @return len in @c pMatrix for the subject\n     */\n    template<typename T>\n    int len_param(int id, const std::vector<T>& param) const {\n      return param.size() == len_.size() ? 1 : len_[id]; \n    }\n\n    /** \n     * check the exisitence of steady state dosing events\n     * for the 1st subject, used for single-individual data.\n     * \n     * @return if the subject has any SS dosing event.\n     */\n    inline bool has_ss_dosing() const {\n      return has_ss_dosing(0);\n    }\n\n    /** \n     * check the exisitence of steady state dosing events\n     * \n     * @param id subject id\n     * \n     * @return if the subject has any SS dosing event.\n     */\n    inline bool has_ss_dosing(int id) const {\n      bool res = false;\n      int begin = begin_[id];\n      int end = size_t(id + 1) == len_.size() ? time_.size() : begin_[id + 1];\n      for (int i = begin; i < end; ++i) {\n        if ((evid_[i] == 1 || evid_[i] == 4) && ss_[i] != 0) {\n          res = true;\n          break;\n        }\n      }\n      return res;\n    }\n\n    /** \n     * check the exisitence of time-lagged events\n     * \n     * @param id subject id\n     * \n     * @return if the subject has any time-lagged dosing event.\n     */\n    template<typename T>\n    inline bool has_positive_param(int id, const std::vector<std::vector<T>>& params) const {\n      using stan::math::value_of;\n      return std::any_of(params.begin() + begin_param(id, params),\n                         params.begin() + begin_param(id, params) + len_param(id, params),\n                         [](const std::vector<T>& v) {\n                           return std::any_of(v.begin(), v.end(), [](const T& x) { return std::abs(value_of(x)) > lag_time_min; });\n                         });\n    }\n\n    /** \n     * check the exisitence of time-lagged dosing events\n     * for the 1st subject, used for single-individual data.\n     * \n     * @return if the subject has any time-lagged dosing event.\n     */\n    template<typename T>\n    inline bool has_positive_param(const std::vector<std::vector<T>>& params) const {\n      return has_positive_param(0, params);\n    }\n\n    /** \n     * @param id subject id\n     * \n     * @return nb. of events for the subject\n     */\n    inline int num_event_times(int id) const {\n      return len_.at(id);\n    }\n\n    /** \n     * @return nb. of events for subject 0.\n     */\n    inline int num_event_times() const {\n      return len_.at(0);\n    }\n\n    /** \n     * @return population size.\n     */\n    inline int num_subjects() const {\n      return len_.size();\n    }\n  };\n\n  template <typename T0, typename T1, typename T2, typename T3>\n  const double NONMENEventsRecord<T0, T1, T2, T3>::lag_time_min = 1.e-12;\n\n}\n\n#endif\n", "meta": {"hexsha": "847f3091214ace5f9292b3e91b2815558d701d4a", "size": 9382, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ev_record.hpp", "max_stars_repo_name": "metrumresearchgroup/torsten_math", "max_stars_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "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": "ev_record.hpp", "max_issues_repo_name": "metrumresearchgroup/torsten_math", "max_issues_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-27T23:53:22.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-27T23:57:43.000Z", "max_forks_repo_path": "ev_record.hpp", "max_forks_repo_name": "metrumresearchgroup/torsten_math", "max_forks_repo_head_hexsha": "318cee4199342bd36d5f2b1241c6760acfcf58b7", "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.6898954704, "max_line_length": 131, "alphanum_fraction": 0.5571306758, "num_tokens": 2520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.2142541608556196}}
{"text": "#include \"tuw_marker_slam/ekf_slam.h\"\n#include \"tuw_marker_slam/munkre.h\"\n#include <boost/math/distributions/chi_squared.hpp>\n\nusing namespace tuw;\n\nEKFSLAM::EKFSLAM( const std::vector<double> beta ) :\n    SLAMTechnique ( EKF ),\n    beta_ ( beta ) {\n}\n\nvoid EKFSLAM::init() {\n    reset_ = false;\n\n    // initial mean\n    y = cv::Mat_<double> ( 3, 1, 0.0 );\n\n    // initial covariance\n    C_Y = cv::Mat_<double> ( 3, 3, 0.0 );\n\n    // initialize covariance submatrices pointing to the same data (no copy!)\n    x = cv::Mat_<double> ( y, cv::Range ( 0, 3 ), cv::Range ( 0, 1 ) );\n    C_X = cv::Mat_<double> ( C_Y, cv::Range ( 0, 3 ), cv::Range ( 0, 3 ) );\n\n    // reset marker landmark correspondences\n    f_kj.clear();\n}\n\nvoid EKFSLAM::cycle ( std::vector<Pose2D> &yt, cv::Mat_<double> &C_Yt, const Command &ut, const MeasurementConstPtr &zt ) {\n    if ( reset_ ) init();\n\n    // invariance check\n    assert ( y.rows % 3 == 0 && y.cols == 1 );\n    assert ( x.rows == 3 && x.cols == 1 );\n    assert ( C_Y.rows == C_Y.cols && C_Y.rows == y.rows );\n    assert ( C_X.rows == C_X.cols && C_X.rows == x.rows );\n\n    prediction ( ut );\n    if ( zt->getType() == tuw::Measurement::Type::MARKER && updateTimestamp ( zt->stamp() ) ) {\n        MeasurementMarkerConstPtr z = std::static_pointer_cast<MeasurementMarker const> ( zt );\n\n        data_association ( z );\n        update();\n        integration ( z );\n    }\n\n    // implicit return\n    yt.resize ( y.rows/3 );\n    for ( size_t i = 0; i < yt.size(); i++ ) {\n        yt[i].x() = y[3*i + 0][0];\n        yt[i].y() = y[3*i + 1][0];\n        yt[i].theta() = y[3*i + 2][0];\n    }\n    C_Yt = C_Y;\n}\n\nvoid EKFSLAM::setConfig ( const void *config ) {\n    config_ = * ( ( tuw_marker_slam::EKFSLAMConfig* ) config );\n}\n\nvoid EKFSLAM::prediction ( const Command &ut ) {\n    if ( !config_.enable_prediction ) return;\n\n    // control noise\n    cv::Matx<double, 2, 2> M = cv::Matx<double, 2, 2> ( config_.alpha_1*ut.v() *ut.v() + config_.alpha_2*ut.w() *ut.w(), 0,\n                               0, config_.alpha_3*ut.v() *ut.v() + config_.alpha_4*ut.w() *ut.w() );\n\n    // pre-calculate needed data\n    double dt = duration_last_update_.total_microseconds() /1000000.0;\n    double r = ut.v() /ut.w();\n    double s = sin ( x[2][0] );\n    double c = cos ( x[2][0] );\n    double s_dt = sin ( x[2][0] + ut.w() *dt );\n    double c_dt = cos ( x[2][0] + ut.w() *dt );\n\n    // calculate update and its derivatives (= jacobian matrices)\n    cv::Vec<double, 3> dx_;\n    cv::Matx<double, 3, 3> G_x_;\n    cv::Matx<double, 3, 2> G_u;\n    if ( std::abs ( ut.w() ) > __DBL_MIN__ ) {\n        dx_ = cv::Vec<double, 3> ( -r*s + r*s_dt,\n                                   r*c - r*c_dt,\n                                   ut.w() *dt );\n        G_x_ = cv::Matx<double, 3, 3> ( 1, 0, -r*c + r*c_dt,\n                                        0, 1, -r*s + r*s_dt,\n                                        0, 0, 1 );\n        G_u = cv::Matx<double, 3, 2> ( ( -s + s_dt ) /ut.w(),  r * ( s - s_dt ) / ut.w() + r*c_dt*dt,\n                                       ( c - c_dt ) /ut.w(), -r * ( c - c_dt ) / ut.w() + r*s_dt*dt,\n                                       0, dt );\n    } else {\n        dx_ = cv::Vec<double, 3> ( ut.v() *dt*c,\n                                   ut.v() *dt*s,\n                                   0 );\n        G_x_ = cv::Matx<double, 3, 3> ( 1, 0, -ut.v() *dt*s,\n                                        0, 1,  ut.v() *dt*c,\n                                        0, 0, 1 );\n        G_u = cv::Matx<double, 3, 2> ( dt*c, -0.5*dt*dt*ut.v() *s,\n                                       dt*s, 0.5*dt*dt*ut.v() *c,\n                                       0, dt );\n    }\n\n    // convert from Matx/Vec to Mat_ in order to use +/* operations on submatrices\n    cv::Mat_<double> dx = cv::Mat_<double> ( dx_ );\n    cv::Mat_<double> G_x = cv::Mat_<double> ( G_x_ );\n    cv::Mat_<double> R = cv::Mat_<double> ( G_u * M * G_u.t() );\n\n    // update mean and covariance\n    x = x + dx;\n    C_X = G_x*C_X*G_x.t() + R;\n    for ( size_t i = 3; i < C_Y.cols; i += 3 ) {\n        // references to submatrices\n        cv::Mat_<double> C_XM_i = cv::Mat_<double> ( C_Y, cv::Range ( 0, 3 ), cv::Range ( i, i + 3 ) );\n        cv::Mat_<double> C_MX_i = cv::Mat_<double> ( C_Y, cv::Range ( i, i + 3 ), cv::Range ( 0, 3 ) );\n\n        // calculation & matrix update\n        C_XM_i = G_x*C_XM_i;\n        C_MX_i = C_XM_i.t();\n    }\n\n    // normalize angle\n    x[2][0] = angle_normalize ( x[2][0] );\n}\n\nvoid EKFSLAM::data_association ( const MeasurementMarkerConstPtr &zt ) {\n    // initialization\n    c_ij = std::vector<CorrDataPtr> ( zt->size() );\n    c_ji = std::vector<CorrDataPtr> ( y.rows/3 );\n    z_known.clear();\n    z_new.clear();\n\n    // gamma is a threshold such that 100*(1-alpha)% of true measurements are rejected\n    boost::math::chi_squared chi_squared = boost::math::chi_squared ( 3 );\n    double gamma = boost::math::quantile(chi_squared, config_.alpha);\n\n    // find correspondences based on measurement marker IDs\n    for ( size_t i = 0; i < zt->size(); i++ ) {\n        if ( zt->operator[] ( i ).ids.size() == 0 ) {\n            // invalid measurement\n        } else {\n            // valid measurement\n            std::map<int, size_t>::iterator it = f_kj.find ( zt->operator[] ( i ).ids[0] );\n\n            if ( it != f_kj.end() ) {\n                // known landmark j\n                size_t j = it->second;\n                assert ( 0 < j && j < c_ji.size() );\n\n                // create correspondence data\n                CorrDataPtr c = std::make_shared<CorrData>();\n                c->ij = std::pair<size_t, size_t> ( i, j );\n                measurement ( zt, c );\n\n                // document founded correspondence\n                assert ( c_ij[i] == nullptr && c_ji[j] == nullptr );\n                c_ij[i] = c;\n                c_ji[j] = c;\n                z_known.push_back(i);\n            } else {\n                // new landmark\n                z_new.push_back( i );\n            }\n        }\n    }\n\n    // complement correspondences based on probability\n    switch (config_.data_association_mode) {\n        case ID:\n            // Nothing to do anymore\n            break;\n        case NNSF_LOCAL:\n            NNSF_local ( zt, gamma );\n            break;\n        case NNSF_GLOBAL:\n            NNSF_global ( zt, gamma );\n            break;\n        default:\n            assert ( false );\n    }\n}\n\nvoid EKFSLAM::NNSF_local ( const MeasurementMarkerConstPtr &zt, const double gamma ) {\n    std::vector<size_t> m_reject;\n\n    // find correspondences based on Mahalanobis distance\n    for ( size_t i = 0; i < c_ij.size(); i++ ) {\n        assert ( c_ij[i] == nullptr || c_ij[i]->ij.first == i );\n\n        // consider only measurements without marker IDs\n        if ( zt->operator[] ( i ).ids.size() > 0) continue;\n        assert ( c_ij[i] == nullptr );\n\n        double min_d_2 = std::numeric_limits<double>::infinity();\n        CorrDataPtr min_c = nullptr;\n        for ( size_t j = 1; j < c_ji.size(); j++ ) {\n            assert ( c_ji[j] == nullptr || c_ji[j]->ij.second == j );\n\n            // consider only landmarks without correspondences based on measurement marker IDs\n            if ( c_ji[j] != nullptr && zt->operator[] ( c_ji[j]->ij.first ).ids.size() > 0 ) continue;\n\n            // create correspondence data\n            CorrDataPtr c = std::make_shared<CorrData>();\n            c->ij = std::pair<size_t, size_t> ( i, j );\n            measurement ( zt, c );\n\n            // calculate Mahalanobis distance: d = sqrt(v^T S^(-1) v)\n            double d_2 = ( c->v.t() * c->S_inv * c->v ) [0];\n            if (d_2 < min_d_2) {\n                min_d_2 = d_2;\n                min_c = c;\n            }\n        }\n\n        // update correspondences\n        if ( min_c == nullptr || min_d_2 > gamma ) continue;\n\n        // new (possible) correspondence found\n        size_t min_i = min_c->ij.first;\n        size_t min_j = min_c->ij.second;\n        assert ( i == min_i && 0 < min_j && min_j < c_ji.size() );\n\n        if ( c_ji[min_j] != nullptr ) {\n            // landmark already correspond to another measurement\n            size_t old_i = c_ji[min_j]->ij.first;\n            ROS_INFO ( \"measurements %lu and %lu correspond both to landmark %lu\", old_i, min_i, min_j );\n            if ( zt->operator[] ( old_i ).ids.size() > 0 ) {\n                // old correspondence is fix -> reject current measurement\n                ROS_INFO ( \"reject measurement %lu\", min_i );\n            } else {\n                // old correspondence is just probably -> reject both measurements\n                ROS_INFO ( \"reject measurement %lu (conservative approach)\", i );\n\n                if ( c_ij[old_i] != nullptr ) {\n                    ROS_INFO ( \"reject measurement %lu (conservative approach)\", old_i );\n\n                    // remove already added old measurement from known measurements\n                    std::vector<size_t>::iterator it = std::find ( z_known.begin(), z_known.end(), old_i );\n                    assert ( it != z_known.end() );\n                    z_known.erase( it );\n\n                    // reset old correspondence c_ij at the first time and\n                    // remember old correspondence c_ji for later reset\n                    c_ij[old_i] = nullptr;\n                    m_reject.push_back( min_j );\n                }\n            }\n        } else {\n            // document founded correspondence\n            assert ( c_ij[min_i] == nullptr && c_ji[min_j] == nullptr );\n            c_ij[min_i] = min_c;\n            c_ji[min_j] = min_c;\n            z_known.push_back( min_i );\n        }\n    }\n\n    // reset correspondences c_ji found but invalidated again during corresponde update\n    for (auto j: m_reject) c_ji[j] = nullptr;\n}\n\nvoid EKFSLAM::NNSF_global ( const MeasurementMarkerConstPtr &zt, const double gamma ) {\n    // book keeping: measurements\n    std::vector<size_t> map_i;\n    for ( size_t i = 0; i < c_ij.size(); i++ ) {\n        assert ( c_ij[i] == nullptr || c_ij[i]->ij.first == i );\n\n        // consider only measurements without marker IDs\n        if ( zt->operator[] ( i ).ids.size() > 0 ) continue;\n        assert ( c_ij[i] == nullptr );\n\n        map_i.push_back(i);\n    }\n\n    // no further correspondences possible\n    if (map_i.size() == 0) return;\n\n    // book keeping: landmarks\n    std::vector<size_t> map_j;\n    for ( size_t j = 1; j < c_ji.size(); j++ ) {\n        assert ( c_ji[j] == nullptr || c_ji[j]->ij.second == j );\n\n        // consider only landmarks without correspondences based on measurement marker IDs\n        assert ( c_ji[j] == nullptr || zt->operator[] ( c_ji[j]->ij.first ).ids.size() > 0);\n        if ( c_ji[j] != nullptr ) continue;\n\n        map_j.push_back(j);\n    }\n\n    // no further correspondences possible\n    if (map_j.size() == 0) return;\n\n    // build assignment matrix (Mahalanobis distance)\n    std::vector<std::vector<CorrDataPtr>> C = std::vector<std::vector<CorrDataPtr>> ( map_i.size() );\n    cv::Mat_<double> D_2 = cv::Mat_<double> ( map_i.size(), map_j.size() );\n    for ( size_t x = 0; x < map_i.size(); x++ ) {\n        C[x] = std::vector<CorrDataPtr> ( map_j.size() );\n        for ( size_t y = 0; y < map_j.size(); y++ ) {\n            // create correspondence data\n            CorrDataPtr c = std::make_shared<CorrData>();\n            c->ij = std::pair<size_t, size_t> ( map_i[x], map_j[y] );\n            measurement ( zt, c );\n\n            // calculate Mahalanobis distance: d = sqrt(v^T S^(-1) v)\n            double d_2 = ( c->v.t() * c->S_inv * c->v ) [0];\n            assert ( d_2 >= 0 );\n\n            // book keeping: correspondence data\n            C[x][y] = c;\n            D_2[x][y] = d_2;\n        }\n    }\n\n    // update correspondences\n    std::vector<std::pair<size_t, size_t>> assignment = Munkre::find_minimum_assignment(D_2);\n    for (size_t k = 0; k < assignment.size(); k++) {\n        // book keeping measurement and landmark\n        size_t x = assignment[k].first;\n        size_t y = assignment[k].second;\n\n        if ( D_2[x][y] > gamma ) continue;\n\n        // new correspondence found\n        assert ( x < C.size() && y < C[x].size() );\n        size_t i = C[x][y]->ij.first;\n        size_t j = C[x][y]->ij.second;\n        assert ( i < c_ij.size() && 0 < j && j < c_ji.size() );\n\n        // document founded correspondence\n        assert ( c_ij[i] == nullptr && c_ji[j] == nullptr );\n        c_ij[i] = C[x][y];\n        c_ji[j] = C[x][y];\n        z_known.push_back( i );\n    }\n}\n\nvoid EKFSLAM::measurement ( const MeasurementMarkerConstPtr &zt, const CorrDataPtr &corr ) {\n    const size_t i = corr->ij.first;\n    const size_t j = corr->ij.second;\n    assert ( i < zt->size() && 0 < j && j < y.rows/3 );\n\n    // transformation matrix from robot coordinates in global coordinates\n    Pose2D p(x[0][0], x[1][0], x[2][0] );\n    cv::Matx<double, 4, 4> T_x = cv::Matx44d ( p.theta_cos(), -p.theta_sin(), 0, p.x(), p.theta_sin(), p.theta_cos(), 0, p.y(), 0, 0, 1, p.theta(), 0, 0, 0, 1 );\n\n    // measurement prediction of landmark j\n    cv::Vec<double, 4> homogenious_stage_vector = append(zt->pose2d().state_vector(), 1);\n    cv::Vec<double, 4> sensor = T_x * homogenious_stage_vector;\n    cv::Vec<double, 2> delta = cv::Vec<double, 2> ( y[3*j + 0][0] - sensor[0],\n                               y[3*j + 1][0] - sensor[1] );\n    double q = ( delta.t() * delta ) [0];\n\n    // predicted measurement\n    cv::Vec<double, 3> z_ = cv::Vec<double, 3> ( sqrt ( q ),\n                            angle_difference ( atan2 ( delta[1], delta[0] ), sensor[2] ),\n                            angle_difference ( y[3*j + 2][0], sensor[2] ) );\n\n    // obtained measurement\n    cv::Vec<double, 3> z = cv::Vec<double, 3> ( zt->operator[] ( i ).length,\n                           zt->operator[] ( i ).angle ,\n                           zt->operator[] ( i ).orientation );\n\n    // compare predicted and obtainend measurement\n    corr->v[0] = z[0] - z_[0];\n    corr->v[1] = angle_difference ( z[1], z_[1] );\n    corr->v[2] = angle_difference ( z[2], z_[2] );\n    //corr->v[2] = 0;\n\n    // pre-calculate needed data\n    assert ( q > 0 );\n    double s = sin ( x[2][0] );\n    double c = cos ( x[2][0] );\n    double ddeltax =  zt->pose2d().x() *s + zt->pose2d().y() *c;\n    double ddeltay = -zt->pose2d().x() *c + zt->pose2d().y() *s;\n    double dx_sq = delta[0]/sqrt ( q );\n    double dy_sq = delta[1]/sqrt ( q );\n    double dx_q = delta[0]/q;\n    double dy_q = delta[1]/q;\n\n    //H_ij = (dx 0 .. 0 dm 0 .. 0)\n    corr->dx = cv::Matx<double, 3, 3> ( -dx_sq, -dy_sq, dx_sq*ddeltax + dy_sq*ddeltay,\n                                        dy_q, -dx_q, ddeltay*dx_q - ddeltax*dy_q - 1,\n                                        0, 0, -1 );\n\n    corr->dm = cv::Matx<double, 3, 3> ( dx_sq, dy_sq, 0,\n                                        -dy_q, dx_q, 0,\n                                        0, 0, 1 );\n\n    // measurement noise\n    corr->Q = measurement_noise( zt->operator[]( i ) );\n\n    // S_i = H_i*C_Y*H_i^T + Q\n    cv::Matx<double, 3, 3> C_X_ = cv::Mat_<double> ( C_Y, cv::Range ( 0, 3 ), cv::Range ( 0, 3 ) );\n    cv::Matx<double, 3, 3> C_M = cv::Mat_<double> ( C_Y, cv::Range ( 3*j, 3*j + 3 ), cv::Range ( 3*j, 3*j + 3 ) );\n    cv::Matx<double, 3, 3> C_XM = cv::Mat_<double> ( C_Y, cv::Range ( 0, 3 ), cv::Range ( 3*j, 3*j + 3 ) );\n\n    cv::Matx<double, 3, 3> tmp = corr->dx*C_XM*corr->dm.t();\n    cv::Matx<double, 3, 3> S = corr->dx*C_X_*corr->dx.t() + tmp + tmp.t() + corr->dm*C_M*corr->dm.t() + corr->Q;\n    corr->S_inv = S.inv();\n}\n\ncv::Matx<double, 3, 3> EKFSLAM::measurement_noise ( MeasurementMarker::Marker zi ) {\n    double l = zi.length;\n    double a = zi.angle;\n    double o = zi.orientation;\n\n    double var_l = std::max<double> ( beta_[0]*l*l  + beta_[1], 0 )  + std::max<double> ( std::min<double> ( beta_[2]*a*a  + beta_[3], M_PI*M_PI ), 0 )  + std::max<double> ( std::min<double> ( beta_[4]*o*o  + beta_[5], M_PI*M_PI ), 0 );\n    double var_a = std::min<double> ( std::max<double> ( beta_[6]/l/l  + beta_[7], 0 )  + std::max<double> ( std::min<double> ( beta_[8]*a*a  + beta_[9], M_PI*M_PI ), 0 )  + std::max<double> ( std::min<double> ( beta_[10]*o*o + beta_[11], M_PI*M_PI ), 0 ), M_PI*M_PI );\n    double var_o = std::min<double> ( std::max<double> ( beta_[12]*l*l + beta_[13], 0 ) + std::max<double> ( std::min<double> ( beta_[14]*a*a + beta_[15], M_PI*M_PI ), 0 ) + std::max<double> ( std::min<double> ( beta_[16]*o*o + beta_[17], M_PI*M_PI ), 0 ), M_PI*M_PI );\n\n    return cv::Matx<double, 3,3> ( var_l, 0, 0,\n                                   0, var_a, 0,\n                                   0, 0, var_o );\n}\n\nvoid EKFSLAM::update() {\n    switch (config_.update_mode) {\n        case None:\n            // Nothing to do\n            break;\n        case Single:\n            update_single();\n            break;\n        case Combined:\n            update_combined();\n            break;\n        default:\n            assert ( false );\n    }\n}\n\nvoid EKFSLAM::update_single() {\n    if ( z_known.size() == 0 ) return;\n\n    for ( auto i: z_known ) {\n        assert ( i < c_ij.size() && c_ij[i] != nullptr );\n\n        // obtained measurement i corresponds to landmark j\n        int j = c_ij[i]->ij.second;\n        assert ( 0 < j && j < y.rows/3 && c_ji[j] == c_ij[i] );\n\n        // fetch needed data\n        cv::Mat_<double> v = cv::Mat_<double> ( c_ij[i]->v );\n        cv::Mat_<double> S_inv = cv::Mat_<double> ( c_ij[i]->S_inv );\n\n        // K_i = C_Y*H_i^T*S_i^(-1)\n        cv::Mat_<double> K_i = cv::Mat_<double> ( C_Y.rows, 3, 0.0 );\n        for ( size_t k = 0; k < K_i.rows; k += 3 ) {\n            // reference to submatrix\n            cv::Mat_<double> K_i_k = cv::Mat_<double> ( K_i, cv::Range ( k, k + 3 ), cv::Range ( 0, 3 ) );\n\n            // calculation & matrix update\n            cv::Matx<double, 3, 3> C_MX_k = cv::Mat_<double> ( C_Y, cv::Range ( k, k + 3 ), cv::Range ( 0, 3 ) );\n            cv::Matx<double, 3, 3> C_M_kj = cv::Mat_<double> ( C_Y, cv::Range ( k, k + 3 ), cv::Range ( 3*j, 3*j + 3 ) );\n            cv::Mat_<double> tmp = cv::Mat_<double> ( C_MX_k*c_ij[i]->dx.t() + C_M_kj*c_ij[i]->dm.t() );\n            K_i_k = tmp * S_inv;\n        }\n\n        // I - K_i*H_i\n        cv::Mat_<double> I_K_i_H_i = cv::Mat_<double>::eye ( C_Y.rows,  C_Y.cols );\n        for ( size_t k = 0; k < C_Y.rows; k += 3 ) {\n            // references to submatrices\n            cv::Mat_<double> I_K_i_H_i_k0 = cv::Mat_<double> ( I_K_i_H_i, cv::Range ( k, k + 3 ), cv::Range ( 0, 3 ) );\n            cv::Mat_<double> I_K_i_H_i_kj = cv::Mat_<double> ( I_K_i_H_i, cv::Range ( k, k + 3 ), cv::Range ( 3*j, 3*j + 3 ) );\n\n            // calculation & matrix update\n            cv::Matx<double, 3, 3> K_i_k = cv::Mat_<double> ( K_i, cv::Range ( k, k + 3 ), cv::Range ( 0, 3 ) );\n            I_K_i_H_i_k0 -= cv::Mat_<double> ( K_i_k * c_ij[i]->dx );\n            I_K_i_H_i_kj -= cv::Mat_<double> ( K_i_k * c_ij[i]->dm );\n        }\n\n        // update mean and covariance\n        y = y + K_i*v;\n        C_Y = I_K_i_H_i*C_Y;\n\n        // normalize angles\n        for ( size_t i = 2; i < y.rows; i += 3 )\n            y[i][0] = angle_normalize ( y[i][0] );\n\n        // re-establish diagonalization\n        C_Y = 0.5 * ( C_Y + C_Y.t() );\n    }\n}\n\nvoid EKFSLAM::update_combined() {\n    if ( z_known.size() == 0 ) return;\n\n    // initialization\n    cv::Mat_<double> v = cv::Mat_<double> ( 3*z_known.size(), 1, 0.0 );\n    cv::Mat_<double> H = cv::Mat_<double> ( 3*z_known.size(), C_Y.cols, 0.0 );\n    cv::Mat_<double> R = cv::Mat_<double> ( 3*z_known.size(), 3*z_known.size(), 0.0 );\n    size_t k = 0;\n\n    for ( auto i: z_known ) {\n        assert ( i < c_ij.size() && c_ij[i] != nullptr );\n\n        // obtained measurement i corresponds to landmark j\n        int j = c_ij[i]->ij.second;\n        assert ( 0 < j && j < y.rows/3 && c_ji[j] == c_ij[i] );\n\n        // references to submatrices\n        cv::Mat_<double> v_k = cv::Mat_<double> ( v, cv::Range ( k, k + 3 ), cv::Range ( 0, 1 ) );\n        cv::Mat_<double> Hx_kj = cv::Mat_<double> ( H, cv::Range ( k, k + 3 ), cv::Range ( 0, 3 ) );\n        cv::Mat_<double> Hm_kj = cv::Mat_<double> ( H, cv::Range ( k, k + 3 ), cv::Range ( 3*j, 3*j + 3 ) );\n        cv::Mat_<double> R_k = cv::Mat_<double> ( R, cv::Range ( k, k + 3 ), cv::Range ( k, k + 3 ) );\n\n        // calculation & update\n        // H = (H_1j H_2j' ... H_Nj'')^T\n        // H_kj = (dx_kj 0 .. 0 dm_kj 0 .. 0)\n        v_k += cv::Mat_<double> ( c_ij[i]->v );\n        Hx_kj += cv::Mat_<double> ( c_ij[i]->dx );\n        Hm_kj += cv::Mat_<double> ( c_ij[i]->dm );\n        R_k += cv::Mat_<double> ( c_ij[i]->Q );\n        k += 3;\n    }\n\n    // calculation\n    cv::Mat_<double> S = R + H*C_Y*H.t();\n    cv::Mat_<double> K = C_Y*H.t() *S.inv();\n\n    // update mean and covariance\n    y = y + K*v;\n    C_Y = ( cv::Mat_<double>::eye ( C_Y.rows, C_Y.cols ) - K*H ) *C_Y;\n\n    // normalize angles\n    for ( size_t i = 2; i < y.rows; i += 3 )\n        y[i][0] = angle_normalize ( y[i][0] );\n\n    // re-establish diagonalization\n    C_Y = 0.5 * ( C_Y + C_Y.t() );\n}\n\nvoid EKFSLAM::integration ( const MeasurementMarkerConstPtr &zt ) {\n    if ( !config_.enable_integration || z_new.size() == 0 ) return;\n\n    for ( auto i: z_new ) {\n        // consider only measurements with marker IDs for new landmarks\n        assert ( zt->operator[] ( i ).ids.size() > 0 );\n\n        // measurement noise\n        cv::Matx<double, 3,3> Q = measurement_noise( zt->operator[]( i ) );\n\n        // number landmarks found in ascending order\n        int j = y.rows/3;\n        f_kj.insert ( std::pair<int,size_t> ( zt->operator[] ( i ).ids[0], j ) );\n        ROS_INFO ( \"new landmark found: marker %d corresponds to landmark %d\", zt->operator[] ( i ).ids[0], j );\n\n        // pre-calculate needed data\n        double r = zt->operator[] ( i ).length;\n        double T_s = sin ( x[2][0] );\n        double T_c = cos ( x[2][0] );\n        double F_s = sin ( zt->operator[] ( i ).angle );\n        double F_c = cos ( zt->operator[] ( i ).angle );\n\n        // transformation matrix from robot coordinates in global coordinates\n        Pose2D px(x[0][0], x[1][0], x[2][0] );\n        cv::Matx<double, 4, 4> T_x = cv::Matx44d ( px.theta_cos(), -px.theta_sin(), 0, px.x(), px.theta_sin(), px.theta_cos(), 0, px.y(), 0, 0, 1, px.theta(), 0, 0, 0, 1 );\n\n        // transformation matrix from sensor coordinates in robot coordinates\n        Pose2D pz = zt->pose2d();\n        cv::Matx<double, 4, 4> T_z = cv::Matx44d ( pz.theta_cos(), -pz.theta_sin(), 0, pz.x(), pz.theta_sin(), pz.theta_cos(), 0, pz.y(), 0, 0, 1, pz.theta(), 0, 0, 0, 1 );\n\n        // transformation matrix from sensor coordinates in global coordinates\n        cv::Matx<double, 4, 4> T_x_T_z = T_x * T_z;\n\n        // derivation of T_x by theta\n        cv::Matx<double, 4, 4> T_x_theta = cv::Matx<double, 4, 4> ( -T_s, -T_c, 0, 0,\n                                           T_c, -T_s, 0, 0,\n                                           0, 0, 0, 1,\n                                           0, 0, 0, 0 );\n\n        // adapt size of global mean\n        y.resize ( y.rows + 3 );\n\n        // update gloabl mean with mean of landmark j: m_j = g(x, z) = T_x(x) * T_z * f(z)\n        // with f(z) = (r*cos(a), r*sin(a), o), r..radius, a..alpha, o..orientation\n        // (function f transforms measurements from spheric coordinates into cartesian coordinates)\n        cv::Vec<double, 4> homogenious_stage_vector_i = append(zt->operator[] ( i ).pose.state_vector(), 1);\n        cv::Vec<double, 4> m_j = T_x_T_z * homogenious_stage_vector_i;\n        y[3*j + 0][0] = m_j[0];\n        y[3*j + 1][0] = m_j[1];\n        y[3*j + 2][0] = m_j[2];\n\n        // jacobian matrix of f\n        cv::Matx<double, 4, 3> F_z = cv::Matx<double, 4, 3> ( F_c, -r*F_s, 0,\n                                     F_s,  r*F_c, 0,\n                                     0,      0, 1,\n                                     0,      0, 0 );\n\n        // jacobian matrix of G in respect to x\n        cv::Mat_<double> G_x = cv::Mat_<double>::eye ( 3, 3 );\n        cv::Vec<double, 4> G_theta = T_x_theta * T_z * homogenious_stage_vector_i;\n        G_x[0][2] = G_theta[0];\n        G_x[1][2] = G_theta[1];\n\n        // jacobian matrix of G in respect to z\n        cv::Matx<double, 3, 3> G_z = cv::Mat_<double> ( cv::Mat_<double> ( T_x_T_z * F_z ), cv::Range ( 0, 3 ), cv::Range ( 0, 3 ) );\n\n        // create horizontal covariance of landmark j\n        cv::Mat_<double> C_M_j = cv::Mat_<double> ( 3, C_Y.cols, 0.0 );\n        for ( size_t k = 0; k < C_M_j.cols; k += 3 ) {\n            // references to submatrices\n            cv::Mat_<double> C_M_jk = cv::Mat_<double> ( C_M_j, cv::Range ( 0, 3 ), cv::Range ( k, k + 3 ) );\n            cv::Mat_<double> C_XM_k = cv::Mat_<double> ( C_Y, cv::Range ( 0, 3 ), cv::Range ( k, k + 3 ) );\n\n            // calculation & matrix update\n            C_M_jk = G_x*C_XM_k;\n        }\n\n        // append horizontal covariance of landmark j to global covariance\n        cv::Mat tmp_v[] = { C_Y, C_M_j };\n        cv::vconcat ( tmp_v, 2, C_Y );\n\n        // create vertical covariance of landmark j\n        C_M_j = C_M_j.t();\n        C_M_j.resize ( C_M_j.rows + 3 );\n\n        // reference to submatrix\n        cv::Mat_<double> C_M_jj = cv::Mat_<double> ( C_M_j, cv::Range ( 3*j, 3*j + 3 ), cv::Range ( 0, 3 ) );\n\n        // calculation & matrix update\n        cv::Mat_<double> R = cv::Mat_<double> ( G_z*Q*G_z.t() );\n        C_M_jj = G_x*C_X*G_x.t() + R;\n\n        // append vertical covariance of landmark j to global covariance\n        cv::Mat tmp_h[] = { C_Y, C_M_j };\n        cv::hconcat ( tmp_h, 2, C_Y );\n\n        // reinitialize covariance submatrices pointing to the same data (no copy!)\n        x = cv::Mat_<double> ( y, cv::Range ( 0, 3 ), cv::Range ( 0, 1 ) );\n        C_X = cv::Mat_<double> ( C_Y, cv::Range ( 0, 3 ), cv::Range ( 0, 3 ) );\n    }\n}\n", "meta": {"hexsha": "054d32c1467522279e4d4a74bb5c18a1f4293958", "size": 25822, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tuw_marker_slam/src/tuw_marker_slam/ekf_slam.cpp", "max_stars_repo_name": "tuw-robotics/tuw_marker_slam", "max_stars_repo_head_hexsha": "3ebbc5385f1fe882d94814bf717890a05f4c883e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-12-20T16:42:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T09:47:38.000Z", "max_issues_repo_path": "tuw_marker_slam/src/tuw_marker_slam/ekf_slam.cpp", "max_issues_repo_name": "tuw-robotics/tuw_marker_slam", "max_issues_repo_head_hexsha": "3ebbc5385f1fe882d94814bf717890a05f4c883e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-08-21T02:50:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T08:14:49.000Z", "max_forks_repo_path": "tuw_marker_slam/src/tuw_marker_slam/ekf_slam.cpp", "max_forks_repo_name": "tuw-robotics/tuw_marker_slam", "max_forks_repo_head_hexsha": "3ebbc5385f1fe882d94814bf717890a05f4c883e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-02-11T12:06:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T12:08:48.000Z", "avg_line_length": 40.9223454834, "max_line_length": 269, "alphanum_fraction": 0.5086360468, "num_tokens": 8169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328917, "lm_q2_score": 0.3522017752483203, "lm_q1q2_score": 0.21402004716816603}}
{"text": "#include <boost/foreach.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/ptr_container/ptr_vector.hpp>\n#include <algorithm>\n#include <fstream>\n#include <cmath>\n\n#include \"kinect_view.h\"\n\nnamespace kinect_merge {\n\n// This is used for deciding whether two points are similar enough to be merged.\nstatic const float SIMILARITY_THRESHOLD = 3.0f; // in units of standard deviations\n\n// Measurement variance constants\nstatic const float ALPHA_0 = 0.0032225f;\nstatic const float ALPHA_1 = -0.0020925f;\nstatic const float ALPHA_2 = 0.0022078f;\nstatic const float BETA_X = 0.0017228f;\nstatic const float BETA_Y = 0.0017092f;\n\nCPoint::CPoint() {}\n\nCPoint::CPoint(const cv::Matx31f& position, const cv::Matx33f& covariance, const cv::Matx<unsigned char, 3, 1>& color) :\n    pos(position),\n    cov(covariance),\n    col_sum(color),\n    num_merged(1) {}\n\ncv::Matx<unsigned char, 3, 1> CPoint::get_color() const {\n    // NOTE: The following line would segfault on cv::Mat(col_sum). An alternate method follows.\n    // return cv::Mat(col_sum) / num_merged;\n    cv::Matx<unsigned char, 3, 1> m;\n    for(int i = 0; i < 3; i++)\n        m(i) = col_sum(i) / num_merged;\n    return m;\n}\n\nCView::CView(const std::string &extrinsic_file,\n             const std::string &disparity_file,\n             const std::string &color_file,\n             float covariance_scale_xy,\n             float covariance_scale_z,\n             CKinectCalibration &calibration_) :\n    calibration(calibration_),\n    original_pointmap(boost::extents[IMAGE_HEIGHT][IMAGE_WIDTH]),\n    pointmap(boost::extents[IMAGE_HEIGHT][IMAGE_WIDTH]),\n    num_missing(0),\n#ifdef DEBUG // The measurement_used vector is used for outputting debug images.\n    num_added(0),\n    measurement_used(IMAGE_HEIGHT) {\n#else\n    num_added(0) {\n#endif\n\n    // Initialize the depth map.\n    for(int v = 0; v < IMAGE_HEIGHT; v++) {\n        for(int u = 0; u < IMAGE_WIDTH; u++) {\n            depthmap(v, u) = -1;\n        }\n    }\n\n    // Load extrinsic data.\n\n    cv::Mat inv_transformation_tmp = cv::Mat_<float>::eye(4, 4);\n    cv::Mat inv_rotation(inv_transformation_tmp, cv::Rect(0, 0, 3, 3));\n    cv::Mat inv_translation(inv_transformation_tmp, cv::Rect(3, 0, 1, 3));\n\n    try {\n        cv::FileStorage fs(extrinsic_file, cv::FileStorage::READ);\n        fs[\"R\"] >> inv_rotation;\n        fs[\"T\"] >> inv_translation;\n    } catch(cv::Exception &e) {\n        std::cerr << std::endl << \"Error reading extrinsic data: \" << e.what() << std::endl;\n        exit(4);\n    }\n\n    inv_transformation = inv_transformation_tmp;\n    cv::Mat transformation = inv_transformation_tmp.inv();\n    cv::Mat rotation = inv_rotation.t();\n\n    // Load disparity map.\n    int flags = -1; // Load as-is (greyscale). Using 0 (force grayscale) results in a segfault.\n    cv::Mat1s disparitymap = cv::imread(disparity_file, flags);\n\n    if(disparitymap.cols != IMAGE_WIDTH || disparitymap.rows != IMAGE_HEIGHT) {\n        std::cerr << std::endl << \"Disparity map has dimensions \" << disparitymap.cols << \"x\" << disparitymap.rows <<\n                                  \" instead of \" << IMAGE_WIDTH << \"x\" << IMAGE_HEIGHT << std::endl;\n        exit(5);\n    }\n\n    // Load color map.\n    cv::Mat3b colormap = cv::imread(color_file, flags);\n\n    if(colormap.cols != IMAGE_WIDTH || colormap.rows != IMAGE_HEIGHT) {\n        std::cerr << std::endl << \"Color map has dimensions \" << colormap.cols << \"x\" << colormap.rows <<\n                                  \" instead of \" << IMAGE_WIDTH << \"x\" << IMAGE_HEIGHT << std::endl;\n        exit(6);\n    }\n\n    // Convert to a point cloud in global coordinates and calculate the covariance matrix.\n    cv::Matx31f local_point;\n    cv::Mat local_point_tmp = (cv::Mat_<float>(4, 1) << 0, 0, 0, 1);\n    cv::Mat global_point;\n    cv::Mat covariance;\n    for(int v = 0; v < disparitymap.rows; v++) {\n        for(int u = 0; u < disparitymap.cols; u++) {\n            const short disparity = disparitymap(v, u);\n            if(disparity == 2047) {\n                continue;\n            }\n\n            // Convert to local and then global coordinates.\n            calibration.disparity2point(u, v, disparity, local_point);\n            local_point_tmp.at<float>(0) = local_point(0);\n            local_point_tmp.at<float>(1) = local_point(1);\n            local_point_tmp.at<float>(2) = local_point(2);\n            global_point = transformation * local_point_tmp;\n            global_point.pop_back(); // Turn into a 3 by 1 matrix.\n\n            float depth = local_point(2);\n            if(depth < 0) {\n                // The point projects behind the camera. Ignore it.\n                continue;\n            }\n\n            // Calculate the covariance matrix.\n            covariance = cv::Mat_<float>::eye(3, 3);\n            covariance.at<float>(0, 0) = BETA_X * BETA_X * depth * depth / 12;\n            covariance.at<float>(1, 1) = BETA_Y * BETA_Y * depth * depth / 12;\n            covariance.at<float>(2, 2) = pow(ALPHA_2 * depth * depth + ALPHA_1 * depth + ALPHA_0, 2);\n            covariance.at<float>(0, 0) *= covariance_scale_xy;\n            covariance.at<float>(1, 1) *= covariance_scale_xy;\n            covariance.at<float>(2, 2) *= covariance_scale_z;\n\n            // Convert the covariance matrix to the global reference frame.\n            covariance = rotation * covariance * inv_rotation;\n            assert(covariance.at<float>(0, 0) >= 0);\n            assert(covariance.at<float>(1, 1) >= 0);\n            assert(covariance.at<float>(2, 2) >= 0);\n\n            // Get the pixel coordinates for the measurement.\n            int uc, vc;\n            to_image_plane(local_point_tmp, uc, vc);\n            if(uc < 0 || uc >= IMAGE_WIDTH || vc < 0 || vc >= IMAGE_HEIGHT) {\n                continue;\n            }\n\n            if(!original_pointmap[vc][uc] || depthmap(vc, uc) > depth) {\n                depthmap(vc, uc) = depth;\n                original_pointmap[vc][uc] = boost::make_shared<CPoint>(global_point,\n                                                                       covariance,\n                                                                       colormap(vc, uc));\n            }\n        }\n    }\n}\n\nvoid CView::to_image_plane(const cv::Matx41f &local_pos, int &uc, int &vc) const {\n    cv::Matx31f local_pos_tmp(local_pos(0), local_pos(1), local_pos(2));\n    cv::Matx21f cf;\n    calibration.point2rgb(local_pos_tmp, cf);\n    uc = cf(0) + 0.5;\n    vc = cf(1) + 0.5;\n}\n\nstatic float calculate_mahalanobis_distance(const CPoint &refined_point, const CPoint &p) {\n    cv::Matx<float, 1, 1> operand = (p.pos - refined_point.pos).t() * p.cov.inv() * (p.pos - refined_point.pos);\n    return sqrt(operand(0));\n}\n\n// Calculate a new position estimate, covariance matrix and color for an existing point given a new measurement.\nstatic void refine_point(const CPoint &existing_point, const CPoint &new_measurement, CPoint &refined_point) {\n    cv::Matx33f new_measurement_cov_inv = new_measurement.cov.inv();\n\n    // Combine the covariance matrices.\n    refined_point.cov = (existing_point.cov.inv() + new_measurement_cov_inv).inv();\n\n    // Calculate the refined position estimate.\n    refined_point.pos = existing_point.pos + refined_point.cov * new_measurement_cov_inv * (new_measurement.pos - existing_point.pos);\n\n    // Add the color values.\n    refined_point.col_sum = existing_point.col_sum + new_measurement.col_sum;\n    refined_point.num_merged = existing_point.num_merged + new_measurement.num_merged;\n}\n\nvoid CView::refine_points(CView &connected_view, std::vector<std::vector<bool> > &measurement_used) const {\n    for(int v = 0; v < IMAGE_HEIGHT; v++) {\n        for(int u = 0; u < IMAGE_WIDTH; u++) {\n            if(!connected_view.has_point(u, v)) {\n                continue;\n            }\n\n            // Project the point onto the current view image plane.\n            // NOTE: Only points which were added to cloud from the connected view are projected.\n            // Each point in the cloud is pointed to by exactly one view. This means that a single\n            // point in the cloud will NOT be refined multiple times with the same new measurement\n            // through different connected views.\n            int proj_u, proj_v;\n            float proj_depth;\n            CPoint &connected_view_point = connected_view.get_point(u, v);\n            project(connected_view_point, proj_u, proj_v, proj_depth);\n\n            if(proj_depth < 0) {\n                // The point projects outside the image plane.\n                continue;\n            }\n\n            if(!has_measurement(proj_u, proj_v)) {\n                // There is nothing to merge with at this pixel.\n                continue;\n            }\n\n            const CPoint &current_view_point = get_original_point(proj_u, proj_v);\n\n            // Calculate the refined point and use it if it's close enough to the existing point and\n            // new measurement.\n            CPoint refined_point;\n            refine_point(connected_view_point, current_view_point, refined_point);\n            if(calculate_mahalanobis_distance(refined_point, connected_view_point) < SIMILARITY_THRESHOLD &&\n               calculate_mahalanobis_distance(refined_point, current_view_point) < SIMILARITY_THRESHOLD) {\n                connected_view_point = refined_point;\n                measurement_used[proj_v][proj_u] = true;\n            }\n        }\n    }\n}\n\nvoid CView::insert_into_point_cloud(std::vector<CPoint::const_ptr> &point_cloud) {\n    for(int v = 0; v < IMAGE_HEIGHT; v++) {\n        for(int u = 0; u < IMAGE_WIDTH; u++) {\n            if(has_measurement(u, v)) {\n                point_cloud.push_back(original_pointmap[v][u]);\n            }\n        }\n    }\n}\n\nvoid CView::project(const CPoint &global_point, int &proj_u, int &proj_v, float &proj_depth) const {\n    cv::Matx41f global_pos(global_point.pos(0),\n                           global_point.pos(1),\n                           global_point.pos(2),\n                           1);\n    cv::Matx41f local_pos = inv_transformation * global_pos;\n    to_image_plane(local_pos, proj_u, proj_v);\n\n    if(proj_u < 0 || proj_u >= IMAGE_WIDTH ||\n       proj_v < 0 || proj_v >= IMAGE_HEIGHT) {\n        // The point projects outside the image plane.\n        proj_depth = -1;\n    } else {\n        proj_depth = local_pos(2);\n    }\n}\n\nvoid CView::merge(boost::ptr_vector<CView> &views,\n                  unsigned int view_idx,\n                  const cv::Mat view_connectivity,\n                  std::vector<CPoint::ptr> &global_point_cloud) {\n    // Initialize vectors.\n    // A measurement is marked as used if an existing point is refined with it.\n#ifndef DEBUG\n    // Use a local variable instead of a member variable.\n    std::vector<std::vector<bool> > measurement_used(IMAGE_HEIGHT);\n#endif\n    for(int v = 0; v < IMAGE_HEIGHT; v++) {\n        measurement_used[v].resize(IMAGE_WIDTH);\n        for(int u = 0; u < IMAGE_WIDTH; u++) {\n            measurement_used[v][u] = false;\n        }\n    }\n\n    // Project all connected views into the current view to find points to be refined.\n    for(unsigned int connected_idx = 0; connected_idx < view_idx; connected_idx++) {\n        if(!view_connectivity.at<bool>(view_idx, connected_idx)) {\n            // The view is not connected. Skip it.\n            continue;\n        }\n\n        CView &connected_view = views[connected_idx];\n\n        refine_points(connected_view, measurement_used);\n    }\n\n    // Add all the points that weren't used to refine existing points to the point cloud.\n    for(int v = 0; v < IMAGE_HEIGHT; v++) {\n        for(int u = 0; u < IMAGE_WIDTH; u++) {\n            if(has_measurement(u, v)) {\n                if(!measurement_used[v][u]) {\n                    pointmap[v][u] = original_pointmap[v][u];\n                    global_point_cloud.push_back(pointmap[v][u]);\n                    num_added++;\n                }\n            } else {\n                num_missing++;\n            }\n        }\n    }\n}\n\n}\n", "meta": {"hexsha": "b327759a577daf3f60be9dec1618ba6adbdde5dd", "size": 11947, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/kinect_view.cpp", "max_stars_repo_name": "tomikyos/kinect-merge", "max_stars_repo_head_hexsha": "28e66a2e3cd720eb48bb2470611ed7e8f1fd89e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2015-07-16T01:15:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-24T05:28:12.000Z", "max_issues_repo_path": "src/kinect_view.cpp", "max_issues_repo_name": "tomikyos/kinect-merge", "max_issues_repo_head_hexsha": "28e66a2e3cd720eb48bb2470611ed7e8f1fd89e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kinect_view.cpp", "max_forks_repo_name": "tomikyos/kinect-merge", "max_forks_repo_head_hexsha": "28e66a2e3cd720eb48bb2470611ed7e8f1fd89e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-07-16T21:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-28T12:16:09.000Z", "avg_line_length": 39.4290429043, "max_line_length": 134, "alphanum_fraction": 0.6013225077, "num_tokens": 2907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984434543458, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2139385866347924}}
{"text": "/*\n\tSatellite Attitude Dynamics Stepper\n\n\t@author\t\t:\tsiddharth deore\n\t@licence\t:\tMIT\n*/\n\n#define _CRT_SECURE_NO_WARNINGS\n#include <iostream>\n// reading a text file\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include <boost/array.hpp>\n#include <boost/numeric/odeint.hpp>\n#include \"Satellite.h\"\n#include <ctime>\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n\nint main(int argc, char** argv)\n{\n\tsystem(\"cls\");\n\t// Initial condition\n\tdouble IC[7] = { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 };\n\t// Read Configration file for initial condiion Each line is state, TODO:: some kind of parser!\n\tstring line;\n\tifstream myfile(\"conf.txt\");\n\tint i = 0;\n\tif (myfile.is_open())\n\t{\n\t\twhile (getline(myfile, line))\n\t\t{\n\t\t\tIC[i++] = std::stod(line);\n\t\t\t//cout << IC[i-1] <<std::endl;\n\t\t}\n\t\tmyfile.close();\n\t}\n\n\telse cout << \"Unable to open file\";\n\t// Clean Results file\n\n\tstd::ofstream outfile;\n\n\toutfile.open(\"results.csv\"); // overwrite\n\toutfile << \"time, q0, q1, q2, q3, wx, wy, wz\" << endl;\n\toutfile.close();\n\n\tSatellite sat;\n\tSatellite::state_type x;\n\ttime_t t1, t2;\n\t//double q0, q1, q2, q3, w0, w1, w2, w3;\n\tsat.setInnertia(1.0, 2.0, 3.0);\n\tsat.setControllerGains(0.005, 0.01); // (Kp,Kd)\n\tsat.setTargetQuaternion(0.0, 1.0, 0.0, 0.0); //(q0,q1,q2,q3)\n\tsat.setState(IC[0], IC[1], IC[2], IC[3], IC[4], IC[5], IC[6]);\n\ttime(&t1);\n\tsat.step(10000.0, 0.01, x);\n\ttime(&t2);\n\tstd::cout << \"Execution time \" << t2 - t1 << std::endl;\n}\n", "meta": {"hexsha": "8727ed6ccea0a3606dcaad45e95e8a0c4b5de371", "size": 1443, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "satellite_dynamics.cpp", "max_stars_repo_name": "siddharthdeore/satellite_dynamics_cpp", "max_stars_repo_head_hexsha": "3fe6148b99ad2391242a2aa9e413fa3723b998f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "satellite_dynamics.cpp", "max_issues_repo_name": "siddharthdeore/satellite_dynamics_cpp", "max_issues_repo_head_hexsha": "3fe6148b99ad2391242a2aa9e413fa3723b998f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "satellite_dynamics.cpp", "max_forks_repo_name": "siddharthdeore/satellite_dynamics_cpp", "max_forks_repo_head_hexsha": "3fe6148b99ad2391242a2aa9e413fa3723b998f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.546875, "max_line_length": 95, "alphanum_fraction": 0.6382536383, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2139385807064917}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_MULTI_ALGORITHMS_INTERSECTION_HPP\n#define BOOST_GEOMETRY_MULTI_ALGORITHMS_INTERSECTION_HPP\n\n\n#include <boost/geometry/multi/core/closure.hpp>\n#include <boost/geometry/multi/core/geometry_id.hpp>\n#include <boost/geometry/multi/core/is_areal.hpp>\n#include <boost/geometry/multi/core/point_order.hpp>\n#include <boost/geometry/multi/algorithms/envelope.hpp>\n#include <boost/geometry/multi/algorithms/num_points.hpp>\n#include <boost/geometry/multi/algorithms/detail/overlay/get_ring.hpp>\n#include <boost/geometry/multi/algorithms/detail/overlay/get_turns.hpp>\n#include <boost/geometry/multi/algorithms/detail/overlay/copy_segments.hpp>\n#include <boost/geometry/multi/algorithms/detail/overlay/copy_segment_point.hpp>\n#include <boost/geometry/multi/algorithms/detail/overlay/select_rings.hpp>\n#include <boost/geometry/multi/algorithms/detail/sections/range_by_section.hpp>\n#include <boost/geometry/multi/algorithms/detail/sections/sectionalize.hpp>\n\n#include <boost/geometry/algorithms/intersection.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace intersection\n{\n\n\ntemplate\n<\n    typename MultiLinestring1, typename MultiLinestring2,\n    typename OutputIterator, typename PointOut,\n    typename Strategy\n>\nstruct intersection_multi_linestring_multi_linestring_point\n{\n    static inline OutputIterator apply(MultiLinestring1 const& ml1,\n            MultiLinestring2 const& ml2, OutputIterator out,\n            Strategy const& strategy)\n    {\n        // Note, this loop is quadratic w.r.t. number of linestrings per input.\n        // Future Enhancement: first do the sections of each, then intersect.\n        for (typename boost::range_iterator\n                <\n                    MultiLinestring1 const\n                >::type it1 = boost::begin(ml1);\n            it1 != boost::end(ml1);\n            ++it1)\n        {\n            for (typename boost::range_iterator\n                    <\n                        MultiLinestring2 const\n                    >::type it2 = boost::begin(ml2);\n                it2 != boost::end(ml2);\n                ++it2)\n            {\n                out = intersection_linestring_linestring_point\n                    <\n                        typename boost::range_value<MultiLinestring1>::type,\n                        typename boost::range_value<MultiLinestring2>::type,\n                        OutputIterator, PointOut, Strategy\n                    >::apply(*it1, *it2, out, strategy);\n            }\n        }\n\n        return out;\n    }\n};\n\n\ntemplate\n<\n    typename Linestring, typename MultiLinestring,\n    typename OutputIterator, typename PointOut,\n    typename Strategy\n>\nstruct intersection_linestring_multi_linestring_point\n{\n    static inline OutputIterator apply(Linestring const& linestring,\n            MultiLinestring const& ml, OutputIterator out,\n            Strategy const& strategy)\n    {\n        for (typename boost::range_iterator\n                <\n                    MultiLinestring const\n                >::type it = boost::begin(ml);\n            it != boost::end(ml);\n            ++it)\n        {\n            out = intersection_linestring_linestring_point\n                <\n                    Linestring,\n                    typename boost::range_value<MultiLinestring>::type,\n                    OutputIterator, PointOut, Strategy\n                >::apply(linestring, *it, out, strategy);\n        }\n\n        return out;\n    }\n};\n\n\ntemplate\n<\n    typename MultiLinestring, typename Box,\n    typename OutputIterator, typename LinestringOut,\n    typename Strategy\n>\nstruct clip_multi_linestring\n{\n    static inline OutputIterator apply(MultiLinestring const& multi_linestring,\n            Box const& box, OutputIterator out, Strategy const& strategy)\n    {\n        typedef typename point_type<LinestringOut>::type point_type;\n        strategy::intersection::liang_barsky<Box, point_type> lb_strategy;\n        for (typename boost::range_iterator<MultiLinestring const>::type it\n            = boost::begin(multi_linestring);\n            it != boost::end(multi_linestring); ++it)\n        {\n            out = detail::intersection::clip_range_with_box\n                <LinestringOut>(box, *it, out, lb_strategy);\n        }\n        return out;\n    }\n};\n\n\n}} // namespace detail::intersection\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\n// Linear\ntemplate\n<\n    typename MultiLinestring1, typename MultiLinestring2,\n    bool Reverse1, bool Reverse2, bool ReverseOut,\n    typename OutputIterator, typename GeometryOut,\n    overlay_type OverlayType,\n    typename Strategy\n>\nstruct intersection_insert\n    <\n        multi_linestring_tag, multi_linestring_tag, point_tag,\n        false, false, false,\n        MultiLinestring1, MultiLinestring2,\n        Reverse1, Reverse2, ReverseOut,\n        OutputIterator, GeometryOut,\n        OverlayType,\n        Strategy\n    > : detail::intersection::intersection_multi_linestring_multi_linestring_point\n            <\n                MultiLinestring1, MultiLinestring2,\n                OutputIterator, GeometryOut,\n                Strategy\n            >\n{};\n\n\ntemplate\n<\n    typename Linestring, typename MultiLinestring,\n    typename OutputIterator, typename GeometryOut,\n    bool Reverse1, bool Reverse2, bool ReverseOut,\n    overlay_type OverlayType,\n    typename Strategy\n>\nstruct intersection_insert\n    <\n        linestring_tag, multi_linestring_tag, point_tag,\n        false, false, false,\n        Linestring, MultiLinestring,\n        Reverse1, Reverse2, ReverseOut,\n        OutputIterator, GeometryOut,\n        OverlayType,\n        Strategy\n    > : detail::intersection::intersection_linestring_multi_linestring_point\n            <\n                Linestring, MultiLinestring,\n                OutputIterator, GeometryOut,\n                Strategy\n            >\n{};\n\n\ntemplate\n<\n    typename MultiLinestring, typename Box,\n    bool Reverse1, bool Reverse2, bool ReverseOut,\n    typename OutputIterator, typename GeometryOut,\n    overlay_type OverlayType,\n    typename Strategy\n>\nstruct intersection_insert\n    <\n        multi_linestring_tag, box_tag, linestring_tag,\n        false, true, false,\n        MultiLinestring, Box,\n        Reverse1, Reverse2, ReverseOut,\n        OutputIterator, GeometryOut,\n        OverlayType,\n        Strategy\n    > : detail::intersection::clip_multi_linestring\n            <\n                MultiLinestring, Box,\n                OutputIterator, GeometryOut,\n                Strategy\n            >\n{};\n\n\n} // namespace dispatch\n#endif\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_MULTI_ALGORITHMS_INTERSECTION_HPP\n\n", "meta": {"hexsha": "870a1b2ab4eaa4670ec62f94b802d533c653c1a4", "size": 6970, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external/boost_1_47_0/boost/geometry/multi/algorithms/intersection.hpp", "max_stars_repo_name": "zigaosolin/Raytracer", "max_stars_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 47.0, "max_stars_repo_stars_event_min_datetime": "2015-01-01T14:37:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-25T07:38:07.000Z", "max_issues_repo_path": "external/boost_1_47_0/boost/geometry/multi/algorithms/intersection.hpp", "max_issues_repo_name": "zigaosolin/Raytracer", "max_issues_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2016-01-11T05:20:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-06T11:37:24.000Z", "max_forks_repo_path": "external/boost_1_47_0/boost/geometry/multi/algorithms/intersection.hpp", "max_forks_repo_name": "zigaosolin/Raytracer", "max_forks_repo_head_hexsha": "df17f77e814b2e4b90c4a194e18cc81fa84dcb27", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2015-01-05T15:10:43.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T04:59:16.000Z", "avg_line_length": 29.9141630901, "max_line_length": 82, "alphanum_fraction": 0.6578192253, "num_tokens": 1461, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2139385807064917}}
{"text": "// Copyright (C) 2004-2006 The Trustees of Indiana University.\n\n// Use, modification and distribution is subject to the Boost Software\n// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//  Authors: Douglas Gregor\n//           Andrew Lumsdaine\n\n/**\n * This header implements four distributed algorithms to compute\n * the minimum spanning tree (actually, minimum spanning forest) of a\n * graph. All of the algorithms were implemented as specified in the\n * paper by Dehne and Gotz:\n *\n *   Frank Dehne and Silvia Gotz. Practical Parallel Algorithms for Minimum\n *   Spanning Trees. In Symposium on Reliable Distributed Systems,\n *   pages 366--371, 1998.\n *\n * There are four algorithm variants implemented.\n */\n\n#ifndef BOOST_DEHNE_GOTZ_MIN_SPANNING_TREE_HPP\n#define BOOST_DEHNE_GOTZ_MIN_SPANNING_TREE_HPP\n\n#ifndef BOOST_GRAPH_USE_MPI\n#error \"Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included\"\n#endif\n\n#include <boost/graph/graph_traits.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <vector>\n#include <boost/graph/parallel/algorithm.hpp>\n#include <boost/limits.hpp>\n#include <utility>\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/pending/indirect_cmp.hpp>\n#include <boost/property_map/parallel/caching_property_map.hpp>\n#include <boost/graph/vertex_and_edge_range.hpp>\n#include <boost/graph/kruskal_min_spanning_tree.hpp>\n#include <boost/iterator/counting_iterator.hpp>\n#include <boost/iterator/transform_iterator.hpp>\n#include <boost/graph/parallel/container_traits.hpp>\n#include <boost/graph/parallel/detail/untracked_pair.hpp>\n#include <cmath>\n\nnamespace boost { namespace graph { namespace distributed {\n\nnamespace detail {\n  /**\n   * Binary function object type that selects the (edge, weight) pair\n   * with the minimum weight. Used within a Boruvka merge step to select\n   * the candidate edges incident to each supervertex.\n   */\n  struct smaller_weighted_edge\n  {\n    template<typename Edge, typename Weight>\n    std::pair<Edge, Weight>\n    operator()(const std::pair<Edge, Weight>& x,\n               const std::pair<Edge, Weight>& y) const\n    { return x.second < y.second? x : y; }\n  };\n\n  /**\n   * Unary predicate that determines if the source and target vertices\n   * of the given edge have the same representative within a disjoint\n   * sets data structure. Used to indicate when an edge is now a\n   * self-loop because of supervertex merging in Boruvka's algorithm.\n   */\n  template<typename DisjointSets, typename Graph>\n  class do_has_same_supervertex\n  {\n  public:\n    typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n\n    do_has_same_supervertex(DisjointSets& dset, const Graph& g)\n      : dset(dset), g(g) { }\n\n    bool operator()(edge_descriptor e)\n    { return dset.find_set(source(e, g)) == dset.find_set(target(e, g));    }\n\n  private:\n    DisjointSets&  dset;\n    const Graph&   g;\n  };\n\n  /**\n   * Build a @ref do_has_same_supervertex object.\n   */\n  template<typename DisjointSets, typename Graph>\n  inline do_has_same_supervertex<DisjointSets, Graph>\n  has_same_supervertex(DisjointSets& dset, const Graph& g)\n  { return do_has_same_supervertex<DisjointSets, Graph>(dset, g); }\n\n  /** \\brief A single distributed Boruvka merge step.\n   *\n   * A distributed Boruvka merge step involves computing (globally)\n   * the minimum weight edges incident on each supervertex and then\n   * merging supervertices along these edges. Once supervertices are\n   * merged, self-loops are eliminated.\n   *\n   * The set of parameters passed to this algorithm is large, and\n   * considering this algorithm in isolation there are several\n   * redundancies. However, the more asymptotically efficient\n   * distributed MSF algorithms require mixing Boruvka steps with the\n   * merging of local MSFs (implemented in\n   * merge_local_minimum_spanning_trees_step): the interaction of the\n   * two algorithms mandates the addition of these parameters.\n   *\n   * \\param pg The process group over which communication should be\n   * performed. Within the distributed Boruvka algorithm, this will be\n   * equivalent to \\code process_group(g); however, in the context of\n   * the mixed MSF algorithms, the process group @p pg will be a\n   * (non-strict) process subgroup of \\code process_group(g).\n   *\n   * \\param g The underlying graph on which the MSF is being\n   * computed. The type of @p g must model DistributedGraph, but there\n   * are no other requirements because the edge and (super)vertex\n   * lists are passed separately.\n   *\n   * \\param weight_map Property map containing the weights of each\n   * edge. The type of this property map must model\n   * ReadablePropertyMap and must support caching.\n   *\n   * \\param out An output iterator that will be written with the set\n   * of edges selected to build the MSF. Every process within the\n   * process group @p pg will receive all edges in the MSF.\n   *\n   * \\param dset Disjoint sets data structure mapping from vertices in\n   * the graph @p g to their representative supervertex.\n   *\n   * \\param supervertex_map Mapping from supervertex descriptors to\n   * indices.\n   *\n   * \\param supervertices A vector containing all of the\n   * supervertices. Will be modified to include only the remaining\n   * supervertices after merging occurs.\n   *\n   * \\param edge_list The list of edges that remain in the graph. This\n   * list will be pruned to remove self-loops once MSF edges have been\n   * found.\n   */\n  template<typename ProcessGroup, typename Graph, typename WeightMap,\n           typename OutputIterator, typename RankMap, typename ParentMap,\n           typename SupervertexMap, typename Vertex, typename EdgeList>\n  OutputIterator\n  boruvka_merge_step(ProcessGroup pg, const Graph& g, WeightMap weight_map,\n                     OutputIterator out,\n                     disjoint_sets<RankMap, ParentMap>& dset,\n                     SupervertexMap supervertex_map,\n                     std::vector<Vertex>& supervertices,\n                     EdgeList& edge_list)\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor\n                                                           vertex_descriptor;\n    typedef typename graph_traits<Graph>::vertices_size_type\n                                                           vertices_size_type;\n    typedef typename graph_traits<Graph>::edge_descriptor  edge_descriptor;\n    typedef typename EdgeList::iterator                    edge_iterator;\n    typedef typename property_traits<WeightMap>::value_type\n                                                           weight_type;\n    typedef boost::parallel::detail::untracked_pair<edge_descriptor, \n                                       weight_type>        w_edge;\n    typedef typename property_traits<SupervertexMap>::value_type\n                                                           supervertex_index;\n\n    smaller_weighted_edge min_edge;\n    weight_type inf = (std::numeric_limits<weight_type>::max)();\n\n    // Renumber the supervertices\n    for (std::size_t i = 0; i < supervertices.size(); ++i)\n      put(supervertex_map, supervertices[i], i);\n\n    // BSP-B1: Find local minimum-weight edges for each supervertex\n    std::vector<w_edge> candidate_edges(supervertices.size(),\n                                        w_edge(edge_descriptor(), inf));\n    for (edge_iterator ei = edge_list.begin(); ei != edge_list.end(); ++ei) {\n      weight_type w = get(weight_map, *ei);\n      supervertex_index u =\n        get(supervertex_map, dset.find_set(source(*ei, g)));\n      supervertex_index v =\n        get(supervertex_map, dset.find_set(target(*ei, g)));\n\n      if (u != v) {\n        candidate_edges[u] = min_edge(candidate_edges[u], w_edge(*ei, w));\n        candidate_edges[v] = min_edge(candidate_edges[v], w_edge(*ei, w));\n      }\n    }\n\n    // BSP-B2 (a): Compute global minimum edges for each supervertex\n    all_reduce(pg,\n               &candidate_edges[0],\n               &candidate_edges[0] + candidate_edges.size(),\n               &candidate_edges[0], min_edge);\n\n    // BSP-B2 (b): Use the edges to compute sequentially the new\n    // connected components and emit the edges.\n    for (vertices_size_type i = 0; i < candidate_edges.size(); ++i) {\n      if (candidate_edges[i].second != inf) {\n        edge_descriptor e = candidate_edges[i].first;\n        vertex_descriptor u = dset.find_set(source(e, g));\n        vertex_descriptor v = dset.find_set(target(e, g));\n        if (u != v) {\n          // Emit the edge, but cache the weight so everyone knows it\n          cache(weight_map, e, candidate_edges[i].second);\n          *out++ = e;\n\n          // Link the two supervertices\n          dset.link(u, v);\n\n          // Whichever vertex was reparented will be removed from the\n          // list of supervertices.\n          vertex_descriptor victim = u;\n          if (dset.find_set(u) == u) victim = v;\n          supervertices[get(supervertex_map, victim)] =\n            graph_traits<Graph>::null_vertex();\n        }\n      }\n    }\n\n    // BSP-B3: Eliminate self-loops\n    edge_list.erase(std::remove_if(edge_list.begin(), edge_list.end(),\n                                   has_same_supervertex(dset, g)),\n                    edge_list.end());\n\n    // TBD: might also eliminate multiple edges between supervertices\n    // when the edges do not have the best weight, but this is not\n    // strictly necessary.\n\n    // Eliminate supervertices that have been absorbed\n    supervertices.erase(std::remove(supervertices.begin(),\n                                    supervertices.end(),\n                                    graph_traits<Graph>::null_vertex()),\n                        supervertices.end());\n\n    return out;\n  }\n\n  /**\n   * An edge descriptor adaptor that reroutes the source and target\n   * edges to different vertices, but retains the original edge\n   * descriptor for, e.g., property maps. This is used when we want to\n   * turn a set of edges in the overall graph into a set of edges\n   * between supervertices.\n   */\n  template<typename Graph>\n  struct supervertex_edge_descriptor\n  {\n    typedef supervertex_edge_descriptor self_type;\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::edge_descriptor Edge;\n\n    Vertex source;\n    Vertex target;\n    Edge e;\n\n    operator Edge() const { return e; }\n\n    friend inline bool operator==(const self_type& x, const self_type& y)\n    { return x.e == y.e; }\n\n    friend inline bool operator!=(const self_type& x, const self_type& y)\n    { return x.e != y.e; }\n  };\n\n  template<typename Graph>\n  inline typename supervertex_edge_descriptor<Graph>::Vertex\n  source(supervertex_edge_descriptor<Graph> se, const Graph&)\n  { return se.source; }\n\n  template<typename Graph>\n  inline typename supervertex_edge_descriptor<Graph>::Vertex\n  target(supervertex_edge_descriptor<Graph> se, const Graph&)\n  { return se.target; }\n\n  /**\n   * Build a supervertex edge descriptor from a normal edge descriptor\n   * using the given disjoint sets data structure to identify\n   * supervertex representatives.\n   */\n  template<typename Graph, typename DisjointSets>\n  struct build_supervertex_edge_descriptor\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::edge_descriptor   Edge;\n\n    typedef Edge argument_type;\n    typedef supervertex_edge_descriptor<Graph> result_type;\n\n    build_supervertex_edge_descriptor() : g(0), dsets(0) { }\n\n    build_supervertex_edge_descriptor(const Graph& g, DisjointSets& dsets)\n      : g(&g), dsets(&dsets) { }\n\n    result_type operator()(argument_type e) const\n    {\n      result_type result;\n      result.source = dsets->find_set(source(e, *g));\n      result.target = dsets->find_set(target(e, *g));\n      result.e = e;\n      return result;\n    }\n\n  private:\n    const Graph* g;\n    DisjointSets* dsets;\n  };\n\n  template<typename Graph, typename DisjointSets>\n  inline build_supervertex_edge_descriptor<Graph, DisjointSets>\n  make_supervertex_edge_descriptor(const Graph& g, DisjointSets& dsets)\n  { return build_supervertex_edge_descriptor<Graph, DisjointSets>(g, dsets); }\n\n  template<typename T>\n  struct identity_function\n  {\n    typedef T argument_type;\n    typedef T result_type;\n\n    result_type operator()(argument_type x) const { return x; }\n  };\n\n  template<typename Graph, typename DisjointSets, typename EdgeMapper>\n  class is_not_msf_edge\n  {\n    typedef typename graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename graph_traits<Graph>::edge_descriptor Edge;\n\n  public:\n    is_not_msf_edge(const Graph& g, DisjointSets dset, EdgeMapper edge_mapper)\n      : g(g), dset(dset), edge_mapper(edge_mapper) { }\n\n    bool operator()(Edge e)\n    {\n      Vertex u = dset.find_set(source(edge_mapper(e), g));\n      Vertex v = dset.find_set(target(edge_mapper(e), g));\n      if (u == v) return true;\n      else {\n        dset.link(u, v);\n        return false;\n      }\n    }\n\n  private:\n    const Graph& g;\n    DisjointSets dset;\n    EdgeMapper edge_mapper;\n  };\n\n  template<typename Graph, typename ForwardIterator, typename EdgeList,\n           typename EdgeMapper, typename RankMap, typename ParentMap>\n  void\n  sorted_mutating_kruskal(const Graph& g,\n                          ForwardIterator first_vertex,\n                          ForwardIterator last_vertex,\n                          EdgeList& edge_list, EdgeMapper edge_mapper,\n                          RankMap rank_map, ParentMap parent_map)\n  {\n    typedef disjoint_sets<RankMap, ParentMap> DisjointSets;\n\n    // Build and initialize disjoint-sets data structure\n    DisjointSets dset(rank_map, parent_map);\n    for (ForwardIterator v = first_vertex; v != last_vertex; ++v)\n      dset.make_set(*v);\n\n    is_not_msf_edge<Graph, DisjointSets, EdgeMapper>\n      remove_non_msf_edges(g, dset, edge_mapper);\n    edge_list.erase(std::remove_if(edge_list.begin(), edge_list.end(),\n                                   remove_non_msf_edges),\n                    edge_list.end());\n  }\n\n  /**\n   * Merge local minimum spanning forests from p processes into\n   * minimum spanning forests on p/D processes (where D is the tree\n   * factor, currently fixed at 3), eliminating unnecessary edges in\n   * the process.\n   *\n   * As with @ref boruvka_merge_step, this routine has many\n   * parameters, not all of which make sense within the limited\n   * context of this routine. The parameters are required for the\n   * Boruvka and local MSF merging steps to interoperate.\n   *\n   * \\param pg The process group on which local minimum spanning\n   * forests should be merged. The top (D-1)p/D processes will be\n   * eliminated, and a new process subgroup containing p/D processors\n   * will be returned. The value D is a constant factor that is\n   * currently fixed to 3.\n   *\n   * \\param g The underlying graph whose MSF is being computed. It must model\n   * the DistributedGraph concept.\n   *\n   * \\param first_vertex Iterator to the first vertex in the graph\n   * that should be considered. While the local MSF merging algorithm\n   * typically operates on the entire vertex set, within the hybrid\n   * distributed MSF algorithms this will refer to the first\n   * supervertex.\n   *\n   * \\param last_vertex The past-the-end iterator for the vertex list.\n   *\n   * \\param edge_list The list of local edges that will be\n   * considered. For the p/D processes that remain, this list will\n   * contain edges in the MSF known to the vertex after other\n   * processes' edge lists have been merged. The edge list must be\n   * sorted in order of increasing weight.\n   *\n   * \\param weight Property map containing the weights of each\n   * edge. The type of this property map must model\n   * ReadablePropertyMap and must support caching.\n   *\n   * \\param global_index Mapping from vertex descriptors to a global\n   * index. The type must model ReadablePropertyMap.\n   *\n   * \\param edge_mapper A function object that can remap edge descriptors\n   * in the edge list to any alternative edge descriptor. This\n   * function object will be the identity function when a pure merging\n   * of local MSFs is required, but may be a mapping to a supervertex\n   * edge when the local MSF merging occurs on a supervertex\n   * graph. This function object saves us the trouble of having to\n   * build a supervertex graph adaptor.\n   *\n   * \\param already_local_msf True when the edge list already\n   * constitutes a local MSF. If false, Kruskal's algorithm will first\n   * be applied to the local edge list to select MSF edges.\n   *\n   * \\returns The process subgroup containing the remaining p/D\n   * processes. If the size of this process group is greater than one,\n   * the MSF edges contained in the edge list do not constitute an MSF\n   * for the entire graph.\n   */\n  template<typename ProcessGroup, typename Graph, typename ForwardIterator,\n           typename EdgeList, typename WeightMap, typename GlobalIndexMap,\n           typename EdgeMapper>\n  ProcessGroup\n  merge_local_minimum_spanning_trees_step(ProcessGroup pg,\n                                          const Graph& g,\n                                          ForwardIterator first_vertex,\n                                          ForwardIterator last_vertex,\n                                          EdgeList& edge_list,\n                                          WeightMap weight,\n                                          GlobalIndexMap global_index,\n                                          EdgeMapper edge_mapper,\n                                          bool already_local_msf)\n  {\n    typedef typename ProcessGroup::process_id_type process_id_type;\n    typedef typename EdgeList::value_type edge_descriptor;\n    typedef typename property_traits<WeightMap>::value_type weight_type;\n    typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n\n    // The tree factor, often called \"D\"\n    process_id_type const tree_factor = 3;\n    process_id_type num_procs = num_processes(pg);\n    process_id_type id = process_id(pg);\n    process_id_type procs_left = (num_procs + tree_factor - 1) / tree_factor;\n    std::size_t n = std::size_t(last_vertex - first_vertex);\n\n    if (!already_local_msf) {\n      // Compute local minimum spanning forest. We only care about the\n      // edges in the MSF, because only edges in the local MSF can be in\n      // the global MSF.\n      std::vector<std::size_t> ranks(n);\n      std::vector<vertex_descriptor> parents(n);\n      detail::sorted_mutating_kruskal\n        (g, first_vertex, last_vertex,\n         edge_list, edge_mapper,\n         make_iterator_property_map(ranks.begin(), global_index),\n         make_iterator_property_map(parents.begin(), global_index));\n    }\n\n    typedef std::pair<edge_descriptor, weight_type> w_edge;\n\n    // Order edges based on their weights.\n    indirect_cmp<WeightMap, std::less<weight_type> > cmp_edge_weight(weight);\n\n    if (id < procs_left) {\n      // The p/D processes that remain will receive local MSF edges from\n      // D-1 other processes.\n      synchronize(pg);\n      for (process_id_type from_id = procs_left + id; from_id < num_procs;\n           from_id += procs_left) {\n        std::size_t num_incoming_edges;\n        receive(pg, from_id, 0, num_incoming_edges);\n        if (num_incoming_edges > 0) {\n          std::vector<w_edge> incoming_edges(num_incoming_edges);\n          receive(pg, from_id, 1, &incoming_edges[0], num_incoming_edges);\n\n          edge_list.reserve(edge_list.size() + num_incoming_edges);\n          for (std::size_t i = 0; i < num_incoming_edges; ++i) {\n            cache(weight, incoming_edges[i].first, incoming_edges[i].second);\n            edge_list.push_back(incoming_edges[i].first);\n          }\n          std::inplace_merge(edge_list.begin(),\n                             edge_list.end() - num_incoming_edges,\n                             edge_list.end(),\n                             cmp_edge_weight);\n        }\n      }\n\n      // Compute the local MSF from union of the edges in the MSFs of\n      // all children.\n      std::vector<std::size_t> ranks(n);\n      std::vector<vertex_descriptor> parents(n);\n      detail::sorted_mutating_kruskal\n        (g, first_vertex, last_vertex,\n         edge_list, edge_mapper,\n         make_iterator_property_map(ranks.begin(), global_index),\n         make_iterator_property_map(parents.begin(), global_index));\n    } else {\n      // The (D-1)p/D processes that are dropping out of further\n      // computations merely send their MSF edges to their parent\n      // process in the process tree.\n      send(pg, id % procs_left, 0, edge_list.size());\n      if (edge_list.size() > 0) {\n        std::vector<w_edge> outgoing_edges;\n        outgoing_edges.reserve(edge_list.size());\n        for (std::size_t i = 0; i < edge_list.size(); ++i) {\n          outgoing_edges.push_back(std::make_pair(edge_list[i],\n                                                  get(weight, edge_list[i])));\n        }\n        send(pg, id % procs_left, 1, &outgoing_edges[0],\n             outgoing_edges.size());\n      }\n      synchronize(pg);\n    }\n\n    // Return a process subgroup containing the p/D parent processes\n    return process_subgroup(pg,\n                            make_counting_iterator(process_id_type(0)),\n                            make_counting_iterator(procs_left));\n  }\n} // end namespace detail\n\n// ---------------------------------------------------------------------\n// Dense Boruvka MSF algorithm\n// ---------------------------------------------------------------------\ntemplate<typename Graph, typename WeightMap, typename OutputIterator,\n         typename VertexIndexMap, typename RankMap, typename ParentMap,\n         typename SupervertexMap>\nOutputIterator\ndense_boruvka_minimum_spanning_tree(const Graph& g, WeightMap weight_map,\n                                    OutputIterator out,\n                                    VertexIndexMap index_map,\n                                    RankMap rank_map, ParentMap parent_map,\n                                    SupervertexMap supervertex_map)\n{\n  using boost::graph::parallel::process_group;\n\n  typedef typename graph_traits<Graph>::traversal_category traversal_category;\n\n  BOOST_STATIC_ASSERT((is_convertible<traversal_category*,\n                                      vertex_list_graph_tag*>::value));\n\n  typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n  typedef typename graph_traits<Graph>::vertex_descriptor  vertex_descriptor;\n  typedef typename graph_traits<Graph>::vertex_iterator    vertex_iterator;\n  typedef typename graph_traits<Graph>::edge_descriptor    edge_descriptor;\n\n  // Don't throw away cached edge weights\n  weight_map.set_max_ghost_cells(0);\n\n  // Initialize the disjoint sets structures\n  disjoint_sets<RankMap, ParentMap> dset(rank_map, parent_map);\n  vertex_iterator vi, vi_end;\n  for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n    dset.make_set(*vi);\n\n  std::vector<vertex_descriptor> supervertices;\n  supervertices.assign(vertices(g).first, vertices(g).second);\n\n  // Use Kruskal's algorithm to find the minimum spanning forest\n  // considering only the local edges. The resulting edges are not\n  // necessarily going to be in the final minimum spanning\n  // forest. However, any edge not part of the local MSF cannot be a\n  // part of the global MSF, so we should have eliminated some edges\n  // from consideration.\n  std::vector<edge_descriptor> edge_list;\n  kruskal_minimum_spanning_tree\n    (make_vertex_and_edge_range(g, vertices(g).first, vertices(g).second,\n                                edges(g).first, edges(g).second),\n     std::back_inserter(edge_list),\n     boost::weight_map(weight_map).\n     vertex_index_map(index_map));\n\n  // While the number of supervertices is decreasing, keep executing\n  // Boruvka steps to identify additional MSF edges. This loop will\n  // execute log |V| times.\n  vertices_size_type old_num_supervertices;\n  do {\n    old_num_supervertices = supervertices.size();\n    out = detail::boruvka_merge_step(process_group(g), g,\n                                     weight_map, out,\n                                     dset, supervertex_map, supervertices,\n                                     edge_list);\n  } while (supervertices.size() < old_num_supervertices);\n\n  return out;\n}\n\ntemplate<typename Graph, typename WeightMap, typename OutputIterator,\n         typename VertexIndex>\nOutputIterator\ndense_boruvka_minimum_spanning_tree(const Graph& g, WeightMap weight_map,\n                                    OutputIterator out, VertexIndex i_map)\n{\n  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n\n  std::vector<std::size_t> ranks(num_vertices(g));\n  std::vector<vertex_descriptor> parents(num_vertices(g));\n  std::vector<std::size_t> supervertices(num_vertices(g));\n\n  return dense_boruvka_minimum_spanning_tree\n           (g, weight_map, out, i_map,\n            make_iterator_property_map(ranks.begin(), i_map),\n            make_iterator_property_map(parents.begin(), i_map),\n            make_iterator_property_map(supervertices.begin(), i_map));\n}\n\ntemplate<typename Graph, typename WeightMap, typename OutputIterator>\nOutputIterator\ndense_boruvka_minimum_spanning_tree(const Graph& g, WeightMap weight_map,\n                                    OutputIterator out)\n{\n  return dense_boruvka_minimum_spanning_tree(g, weight_map, out,\n                                             get(vertex_index, g));\n}\n\n// ---------------------------------------------------------------------\n// Merge local MSFs MSF algorithm\n// ---------------------------------------------------------------------\ntemplate<typename Graph, typename WeightMap, typename OutputIterator,\n         typename GlobalIndexMap>\nOutputIterator\nmerge_local_minimum_spanning_trees(const Graph& g, WeightMap weight,\n                                   OutputIterator out,\n                                   GlobalIndexMap global_index)\n{\n  using boost::graph::parallel::process_group_type;\n  using boost::graph::parallel::process_group;\n\n  typedef typename graph_traits<Graph>::traversal_category traversal_category;\n\n  BOOST_STATIC_ASSERT((is_convertible<traversal_category*,\n                                      vertex_list_graph_tag*>::value));\n\n  typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;\n\n  // Don't throw away cached edge weights\n  weight.set_max_ghost_cells(0);\n\n  // Compute the initial local minimum spanning forests\n  std::vector<edge_descriptor> edge_list;\n  kruskal_minimum_spanning_tree\n    (make_vertex_and_edge_range(g, vertices(g).first, vertices(g).second,\n                                edges(g).first, edges(g).second),\n     std::back_inserter(edge_list),\n     boost::weight_map(weight).vertex_index_map(global_index));\n\n  // Merge the local MSFs from p processes into p/D processes,\n  // reducing the number of processes in each step. Continue looping\n  // until either (a) the current process drops out or (b) only one\n  // process remains in the group. This loop will execute log_D p\n  // times.\n  typename process_group_type<Graph>::type pg = process_group(g);\n  while (pg && num_processes(pg) > 1) {\n    pg = detail::merge_local_minimum_spanning_trees_step\n           (pg, g, vertices(g).first, vertices(g).second,\n            edge_list, weight, global_index,\n            detail::identity_function<edge_descriptor>(), true);\n  }\n\n  // Only process 0 has the entire edge list, so emit it to the output\n  // iterator.\n  if (pg && process_id(pg) == 0) {\n    out = std::copy(edge_list.begin(), edge_list.end(), out);\n  }\n\n  synchronize(process_group(g));\n  return out;\n}\n\ntemplate<typename Graph, typename WeightMap, typename OutputIterator>\ninline OutputIterator\nmerge_local_minimum_spanning_trees(const Graph& g, WeightMap weight,\n                                   OutputIterator out)\n{\n  return merge_local_minimum_spanning_trees(g, weight, out,\n                                            get(vertex_index, g));\n}\n\n// ---------------------------------------------------------------------\n// Boruvka-then-merge MSF algorithm\n// ---------------------------------------------------------------------\ntemplate<typename Graph, typename WeightMap, typename OutputIterator,\n         typename GlobalIndexMap, typename RankMap, typename ParentMap,\n         typename SupervertexMap>\nOutputIterator\nboruvka_then_merge(const Graph& g, WeightMap weight, OutputIterator out,\n                   GlobalIndexMap index, RankMap rank_map,\n                   ParentMap parent_map, SupervertexMap supervertex_map)\n{\n  using std::log;\n  using boost::graph::parallel::process_group_type;\n  using boost::graph::parallel::process_group;\n\n  typedef typename graph_traits<Graph>::traversal_category traversal_category;\n\n  BOOST_STATIC_ASSERT((is_convertible<traversal_category*,\n                                      vertex_list_graph_tag*>::value));\n\n  typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n  typedef typename graph_traits<Graph>::vertex_descriptor  vertex_descriptor;\n  typedef typename graph_traits<Graph>::vertex_iterator    vertex_iterator;\n  typedef typename graph_traits<Graph>::edge_descriptor    edge_descriptor;\n\n  // Don't throw away cached edge weights\n  weight.set_max_ghost_cells(0);\n\n  // Compute the initial local minimum spanning forests\n  std::vector<edge_descriptor> edge_list;\n  kruskal_minimum_spanning_tree\n    (make_vertex_and_edge_range(g, vertices(g).first, vertices(g).second,\n                                edges(g).first, edges(g).second),\n     std::back_inserter(edge_list),\n     boost::weight_map(weight).\n     vertex_index_map(index));\n\n  // Initialize the disjoint sets structures for Boruvka steps\n  disjoint_sets<RankMap, ParentMap> dset(rank_map, parent_map);\n  vertex_iterator vi, vi_end;\n  for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n    dset.make_set(*vi);\n\n  // Construct the initial set of supervertices (all vertices)\n  std::vector<vertex_descriptor> supervertices;\n  supervertices.assign(vertices(g).first, vertices(g).second);\n\n  // Continue performing Boruvka merge steps until the number of\n  // supervertices reaches |V| / (log_D p)^2.\n  const std::size_t tree_factor = 3; // TBD: same as above! should be param\n  double log_d_p = log((double)num_processes(process_group(g)))\n                 / log((double)tree_factor);\n  vertices_size_type target_supervertices =\n    vertices_size_type(num_vertices(g) / (log_d_p * log_d_p));\n  vertices_size_type old_num_supervertices;\n  while (supervertices.size() > target_supervertices) {\n    old_num_supervertices = supervertices.size();\n    out = detail::boruvka_merge_step(process_group(g), g,\n                                     weight, out, dset,\n                                     supervertex_map, supervertices,\n                                     edge_list);\n    if (supervertices.size() == old_num_supervertices)\n      return out;\n  }\n\n  // Renumber the supervertices\n  for (std::size_t i = 0; i < supervertices.size(); ++i)\n    put(supervertex_map, supervertices[i], i);\n\n  // Merge local MSFs on the supervertices. (D-1)p/D processors drop\n  // out each iteration, so this loop executes log_D p times.\n  typename process_group_type<Graph>::type pg = process_group(g);\n  bool have_msf = false;\n  while (pg && num_processes(pg) > 1) {\n    pg = detail::merge_local_minimum_spanning_trees_step\n           (pg, g, supervertices.begin(), supervertices.end(),\n            edge_list, weight, supervertex_map,\n            detail::make_supervertex_edge_descriptor(g, dset),\n            have_msf);\n    have_msf = true;\n  }\n\n  // Only process 0 has the complete list of _supervertex_ MST edges,\n  // so emit those to the output iterator. This is not the complete\n  // list of edges in the MSF, however: the Boruvka steps in the\n  // beginning of the algorithm emitted any edges used to merge\n  // supervertices.\n  if (pg && process_id(pg) == 0)\n    out = std::copy(edge_list.begin(), edge_list.end(), out);\n\n  synchronize(process_group(g));\n  return out;\n}\n\ntemplate<typename Graph, typename WeightMap, typename OutputIterator,\n         typename GlobalIndexMap>\ninline OutputIterator\nboruvka_then_merge(const Graph& g, WeightMap weight, OutputIterator out,\n                    GlobalIndexMap index)\n{\n  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n  typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n  std::vector<vertices_size_type> ranks(num_vertices(g));\n  std::vector<vertex_descriptor> parents(num_vertices(g));\n  std::vector<vertices_size_type> supervertex_indices(num_vertices(g));\n\n  return boruvka_then_merge\n           (g, weight, out, index,\n            make_iterator_property_map(ranks.begin(), index),\n            make_iterator_property_map(parents.begin(), index),\n            make_iterator_property_map(supervertex_indices.begin(), index));\n}\n\ntemplate<typename Graph, typename WeightMap, typename OutputIterator>\ninline OutputIterator\nboruvka_then_merge(const Graph& g, WeightMap weight, OutputIterator out)\n{ return boruvka_then_merge(g, weight, out, get(vertex_index, g)); }\n\n// ---------------------------------------------------------------------\n// Boruvka-mixed-merge MSF algorithm\n// ---------------------------------------------------------------------\ntemplate<typename Graph, typename WeightMap, typename OutputIterator,\n         typename GlobalIndexMap, typename RankMap, typename ParentMap,\n         typename SupervertexMap>\nOutputIterator\nboruvka_mixed_merge(const Graph& g, WeightMap weight, OutputIterator out,\n                    GlobalIndexMap index, RankMap rank_map,\n                    ParentMap parent_map, SupervertexMap supervertex_map)\n{\n  using boost::graph::parallel::process_group_type;\n  using boost::graph::parallel::process_group;\n\n  typedef typename graph_traits<Graph>::traversal_category traversal_category;\n\n  BOOST_STATIC_ASSERT((is_convertible<traversal_category*,\n                                      vertex_list_graph_tag*>::value));\n\n  typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n  typedef typename graph_traits<Graph>::vertex_descriptor  vertex_descriptor;\n  typedef typename graph_traits<Graph>::vertex_iterator    vertex_iterator;\n  typedef typename graph_traits<Graph>::edge_descriptor    edge_descriptor;\n\n  // Don't throw away cached edge weights\n  weight.set_max_ghost_cells(0);\n\n  // Initialize the disjoint sets structures for Boruvka steps\n  disjoint_sets<RankMap, ParentMap> dset(rank_map, parent_map);\n  vertex_iterator vi, vi_end;\n  for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)\n    dset.make_set(*vi);\n\n  // Construct the initial set of supervertices (all vertices)\n  std::vector<vertex_descriptor> supervertices;\n  supervertices.assign(vertices(g).first, vertices(g).second);\n\n  // Compute the initial local minimum spanning forests\n  std::vector<edge_descriptor> edge_list;\n  kruskal_minimum_spanning_tree\n    (make_vertex_and_edge_range(g, vertices(g).first, vertices(g).second,\n                                edges(g).first, edges(g).second),\n     std::back_inserter(edge_list),\n     boost::weight_map(weight).\n     vertex_index_map(index));\n\n  if (num_processes(process_group(g)) == 1) {\n    return std::copy(edge_list.begin(), edge_list.end(), out);\n  }\n\n  // Like the merging local MSFs algorithm and the Boruvka-then-merge\n  // algorithm, each iteration of this loop reduces the number of\n  // processes by a constant factor D, and therefore we require log_D\n  // p iterations. Note also that the number of edges in the edge list\n  // decreases geometrically, giving us an efficient distributed MSF\n  // algorithm.\n  typename process_group_type<Graph>::type pg = process_group(g);\n  vertices_size_type old_num_supervertices;\n  while (pg && num_processes(pg) > 1) {\n    // A single Boruvka step. If this doesn't change anything, we're done\n    old_num_supervertices = supervertices.size();\n    out = detail::boruvka_merge_step(pg, g, weight, out, dset,\n                                     supervertex_map, supervertices,\n                                     edge_list);\n    if (old_num_supervertices == supervertices.size()) {\n      edge_list.clear();\n      break;\n    }\n\n    // Renumber the supervertices\n    for (std::size_t i = 0; i < supervertices.size(); ++i)\n      put(supervertex_map, supervertices[i], i);\n\n    // A single merging of local MSTs, which reduces the number of\n    // processes we're using by a constant factor D.\n    pg = detail::merge_local_minimum_spanning_trees_step\n           (pg, g, supervertices.begin(), supervertices.end(),\n            edge_list, weight, supervertex_map,\n            detail::make_supervertex_edge_descriptor(g, dset),\n            true);\n\n  }\n\n  // Only process 0 has the complete edge list, so emit it for the\n  // user. Note that list edge list only contains the MSF edges in the\n  // final supervertex graph: all of the other edges were used to\n  // merge supervertices and have been emitted by the Boruvka steps,\n  // although only process 0 has received the complete set.\n  if (pg && process_id(pg) == 0)\n    out = std::copy(edge_list.begin(), edge_list.end(), out);\n\n  synchronize(process_group(g));\n  return out;\n}\n\ntemplate<typename Graph, typename WeightMap, typename OutputIterator,\n         typename GlobalIndexMap>\ninline OutputIterator\nboruvka_mixed_merge(const Graph& g, WeightMap weight, OutputIterator out,\n                    GlobalIndexMap index)\n{\n  typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;\n  typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;\n  std::vector<vertices_size_type> ranks(num_vertices(g));\n  std::vector<vertex_descriptor> parents(num_vertices(g));\n  std::vector<vertices_size_type> supervertex_indices(num_vertices(g));\n\n  return boruvka_mixed_merge\n           (g, weight, out, index,\n            make_iterator_property_map(ranks.begin(), index),\n            make_iterator_property_map(parents.begin(), index),\n            make_iterator_property_map(supervertex_indices.begin(), index));\n}\n\ntemplate<typename Graph, typename WeightMap, typename OutputIterator>\ninline OutputIterator\nboruvka_mixed_merge(const Graph& g, WeightMap weight, OutputIterator out)\n{ return boruvka_mixed_merge(g, weight, out, get(vertex_index, g)); }\n\n} // end namespace distributed\n\nusing distributed::dense_boruvka_minimum_spanning_tree;\nusing distributed::merge_local_minimum_spanning_trees;\nusing distributed::boruvka_then_merge;\nusing distributed::boruvka_mixed_merge;\n\n} } // end namespace boost::graph\n\n\n#endif // BOOST_DEHNE_GOTZ_MIN_SPANNING_TREE_HPP\n", "meta": {"hexsha": "0e7c1cf23bf9383f32f944a74ffdb9643b6d8544", "size": 38687, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/graph/distributed/dehne_gotz_min_spanning_tree.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/graph/distributed/dehne_gotz_min_spanning_tree.hpp", "max_issues_repo_name": "c7yrus/alyson-v3", "max_issues_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/graph/distributed/dehne_gotz_min_spanning_tree.hpp", "max_forks_repo_name": "c7yrus/alyson-v3", "max_forks_repo_head_hexsha": "5ad95a8f782f5f5d2fd543d44ca6a8b093395965", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 41.2441364606, "max_line_length": 101, "alphanum_fraction": 0.674283351, "num_tokens": 8439, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21393010790330644}}
{"text": "// graph-tool -- a general graph modification and manipulation thingy\n//\n// Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 3\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"graph_filtering.hh\"\n#include \"graph.hh\"\n#include \"graph_properties.hh\"\n\n#include <boost/graph/boyer_myrvold_planar_test.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\nstruct get_planar_embedding\n{\n    template <class EdgeMap>\n    class edge_inserter\n    {\n    public:\n        edge_inserter(EdgeMap edge_map): _edge_map(edge_map) {}\n\n        edge_inserter& operator++() { return *this; }\n        edge_inserter& operator++(int) { return *this; }\n        edge_inserter& operator*() { return *this; }\n\n        template <class Key>\n        edge_inserter& operator=(const Key& e)\n        {\n            _edge_map[e] = 1;\n            return *this;\n        }\n\n    private:\n        EdgeMap _edge_map;\n    };\n\n    template <class Graph, class VertexIndex, class EdgeIndex, class EmbedMap,\n              class KurMap>\n    void operator()(Graph& g, VertexIndex vertex_index, EdgeIndex edge_index,\n                    EmbedMap embed_map, KurMap kur_map, bool& is_planar) const\n    {\n        edge_inserter<KurMap> kur_insert(kur_map);\n        unchecked_vector_property_map\n            <vector<typename graph_traits<Graph>::edge_descriptor>, VertexIndex>\n            embedding(vertex_index, num_vertices(g));\n        is_planar = boyer_myrvold_planarity_test\n            (boyer_myrvold_params::graph = g,\n             boyer_myrvold_params::edge_index_map = edge_index,\n             boyer_myrvold_params::embedding = embedding,\n             boyer_myrvold_params::kuratowski_subgraph = kur_insert);\n\n        int i, N = num_vertices(g);\n        #pragma omp parallel for default(shared) private(i) schedule(runtime) if (N > 100)\n        for (i = 0; i < N; ++i)\n        {\n            typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);\n            if (v == graph_traits<Graph>::null_vertex())\n                continue;\n            embed_map[v].resize(embedding[v].size());\n            for (size_t j = 0; j < embedding[v].size(); ++j)\n                embed_map[v][j] = edge_index[embedding[v][j]];\n        }\n    }\n\n    template <class Graph, class VertexIndex, class EdgeIndex, class KurMap>\n    void operator()(Graph& g, VertexIndex, EdgeIndex edge_index,\n                    dummy_property_map, KurMap kur_map,\n                    bool& is_planar) const\n    {\n        edge_inserter<KurMap> kur_insert(kur_map);\n        is_planar = boyer_myrvold_planarity_test\n            (boyer_myrvold_params::graph = g,\n             boyer_myrvold_params::edge_index_map = edge_index,\n             boyer_myrvold_params::kuratowski_subgraph = kur_insert);\n    }\n\n};\n\nbool is_planar(GraphInterface& gi, boost::any embed_map, boost::any kur_map)\n{\n    bool is_planar;\n\n    if (embed_map.empty())\n        embed_map = dummy_property_map();\n    if (kur_map.empty())\n        kur_map = dummy_property_map();\n\n    typedef mpl::push_back<writable_edge_scalar_properties,\n                           dummy_property_map>::type edge_map_types;\n    typedef mpl::push_back<vertex_scalar_vector_properties,\n                           dummy_property_map>::type vertex_map_types;\n\n    run_action<graph_tool::detail::never_directed>()\n        (gi, std::bind(get_planar_embedding(), placeholders::_1, gi.GetVertexIndex(),\n                       gi.GetEdgeIndex(), placeholders::_2, placeholders::_3,\n                       std::ref(is_planar)),\n         vertex_map_types(), edge_map_types())\n        (embed_map, kur_map);\n    return is_planar;\n}\n", "meta": {"hexsha": "93859946c45170fe72aa5c1c4b44c1f1cc20592f", "size": 4235, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/topology/graph_planar.cc", "max_stars_repo_name": "johankaito/fufuka", "max_stars_repo_head_hexsha": "32a96ecf98ce305c2206c38443e58fdec88c788d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-04T19:41:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-04T19:41:53.000Z", "max_issues_repo_path": "graph-tool/src/graph/topology/graph_planar.cc", "max_issues_repo_name": "johankaito/fufuka", "max_issues_repo_head_hexsha": "32a96ecf98ce305c2206c38443e58fdec88c788d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graph-tool/src/graph/topology/graph_planar.cc", "max_forks_repo_name": "johankaito/fufuka", "max_forks_repo_head_hexsha": "32a96ecf98ce305c2206c38443e58fdec88c788d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8260869565, "max_line_length": 90, "alphanum_fraction": 0.6498229044, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21393010790330638}}
{"text": "/*** \n   HiCapTools.\n   Copyright (c) 2017 Pelin Sahlén <pelin.akan@scilifelab.se>\n\n\tPermission is hereby granted, free of charge, to any person obtaining a \n\tcopy of this software and associated documentation files (the \"Software\"), \n\tto deal in the Software with some restriction, including without limitation \n\tthe rights to use, copy, modify, merge, publish, distribute the Software, \n\tand to permit persons to whom the Software is furnished to do so, subject to\n\tthe following conditions:\n\n\tThe above copyright notice and this permission notice shall be included in all \n\tcopies or substantial portions of the Software. The Software shall not be used \n\tfor commercial purposes.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, \n\tINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A \n\tPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT \n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF \n\tCONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE \n\tOR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n***/\n\n//\n//  BackgroundInteractionFrequency.cpp\n//  HiCapTools\n//\n//  Created by Pelin Sahlen and Anandashankar Anil.\n//\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n#include <boost/accumulators/statistics/rolling_mean.hpp>\nusing namespace boost::accumulators;\n\n#include \"BackgroundInteractionFrequency.h\"\n#include \"Global.h\"\n#include \"linear.h\"\n#include <fstream>\n#include <cmath>\n\n\n///For Probe-Distal and Probe-Probe\nvoid DetermineBackgroundLevels::CalculateMeanandStdRegress(std::string eName, int ExperimentNo, std::string DesignName, BG_signals& bglevelsloc, int binsize, std::string whichProx, int MinimumJunctionDistance, OutStream& log, int WindowSizeloc){\n\n\n\texpName= eName; //set experiment name\n\t\n\tstd::map< int, int > nofentries_perBin; // required for calculating mean\n\tstd::map< int, int > signal_square; // required for calculating stdev\n    double sum_square, variance;\n\tint distance;\n    std::string feature_id;\n\n\t\n    std::map< int, Junction >::const_iterator iter;\n\tfor(int i = 0; i < Design_NegCtrl[DesignName].Probes.size(); i++){\n        feature_id = Design_NegCtrl[DesignName].Probes[i].feature_id;\n        //////////Probe-distal\n        if(whichProx==\"ProbeDistal\"){\n\t\t\tfor (iter = Features[feature_id].proximities.junctions.begin(); iter != Features[feature_id].proximities.junctions.end(); ++iter){\n\t\t\t\t\n\t\t\t\tdistance = iter->first - Design_NegCtrl[DesignName].Probes[i].end;\n            \n\t\t\t\tint bin = abs(distance) / binsize;\n\n\t\t\t\tif(iter->second.paircount[ExperimentNo] > 0){\n           \n\t\t\t\t\tif(bglevelsloc.mean.find(bin) == bglevelsloc.mean.end())\n\t\t\t\t\t\tbglevelsloc.mean[bin] = iter->second.paircount[ExperimentNo];\n\t\t\t\t\telse\n\t\t\t\t\t\tbglevelsloc.mean[bin] = bglevelsloc.mean[bin] + iter->second.paircount[ExperimentNo];\n                \n\t\t\t\t\tif(nofentries_perBin.find(bin) == nofentries_perBin.end()){\n\t\t\t\t\t\tnofentries_perBin[bin] = 1;\n\t\t\t\t\t\tsignal_square[bin] = (iter->second.paircount[ExperimentNo])*(iter->second.paircount[ExperimentNo]);\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\tnofentries_perBin[bin] = nofentries_perBin[bin] + 1;\n\t\t\t\t\t\tsignal_square[bin] = (signal_square[bin] + ((iter->second.paircount[ExperimentNo])*(iter->second.paircount[ExperimentNo])));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t///////////Probe-Probe\n        else if(whichProx==\"ProbeProbe\"){\n\t\t\tfor (auto iter = Features[feature_id].Inter_feature_ints.begin(); iter != Features[feature_id].Inter_feature_ints.end(); ++iter){\n\t\t\t\t\t\t\t\t\n\t\t\t\tdistance = Features[feature_id].start - Features[(*iter).interacting_feature_id].start;\n\t\t\t\t\n\t\t\t\tif((Features[feature_id].FeatureType == 3 && Features[(*iter).interacting_feature_id].FeatureType == 3) && Features[feature_id].TranscriptName != Features[(*iter).interacting_feature_id].TranscriptName && (abs(distance) >= MinimumJunctionDistance)){\n            \n\t\t\t\t\tint bin = abs(distance) / binsize; \n\t\t\t\t\tif((*iter).signal[ExperimentNo] > 0){\n\t\t\t\t\t\tif(bglevelsloc.mean.find(bin) == bglevelsloc.mean.end())\n\t\t\t\t\t\t\tbglevelsloc.mean[bin] = (*iter).signal[ExperimentNo];\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbglevelsloc.mean[bin] = bglevelsloc.mean[bin] + (*iter).signal[ExperimentNo];\n                \n\t\t\t\t\t\tif(nofentries_perBin.find(bin) == nofentries_perBin.end()){\n\t\t\t\t\t\t\tnofentries_perBin[bin] = 1;\n\t\t\t\t\t\t\tsignal_square[bin] = ((*iter).signal[ExperimentNo])*((*iter).signal[ExperimentNo]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tnofentries_perBin[bin] = nofentries_perBin[bin] + 1;\n\t\t\t\t\t\t\tsignal_square[bin] = (signal_square[bin] + (((*iter).signal[ExperimentNo])*((*iter).signal[ExperimentNo])));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}        \n    }\n    \n// Calculate Mean and stdev\n\tstd::map< int, double>::iterator it; // iterator for bin signals\n\tfor (it = bglevelsloc.mean.begin(); it != bglevelsloc.mean.end(); ++it){\n        bglevelsloc.samplesize[it->first] = nofentries_perBin[it->first];\n        if(bglevelsloc.samplesize[it->first] == 0){\n            it->second = 1; //Mean\n        }\n        else{\n            it->second /= nofentries_perBin[it->first]; //Mean\n        }\n        if(bglevelsloc.samplesize[it->first] <= 1){\n            bglevelsloc.stdev[it->first] = 0;\n        }\n        else{\n            sum_square = ((it->second)*(it->second));\n            sum_square /= (double(nofentries_perBin[it->first])); // Average Sum Squared\n            variance = signal_square[it->first] - sum_square;\n            variance /= (nofentries_perBin[it->first] -1);\n            bglevelsloc.stdev[it->first] = sqrt(variance); //stdev\n        }\n\t}\n    \n    int first25kb = ceil(25000/(double)binsize); // to exclude bins of first 25 kb from smoothing \n    \n    boost::accumulators::accumulator_set<double, stats<tag::rolling_mean> > acc(tag::rolling_window::window_size = (WindowSizeloc*2));\n    boost::accumulators::accumulator_set<double, stats<tag::rolling_mean> > acc2(tag::rolling_window::window_size = (WindowSizeloc*2));\n    \n    int w = 0, z = 0, s = 0, a=0;\n    std::deque< double > dm, ds, db, dwm, dws;\n\n    \n    // Put values into a queue\n    for (it = bglevelsloc.mean.begin(); it != bglevelsloc.mean.end(); ++it){\n\t\n        dm.push_back(it->second);\n        ds.push_back(bglevelsloc.stdev[it->first]);\n        db.push_back(it->first);\n\t\n    }\n    //Push the first WindowSize-1 elements into a queue\n\tif(dm.empty())\n\t\tlog<<\"No Element in dm Outloop\"<<std::endl;\n\t\t\n\tbool firstpass=true;\n    for(w = 0; w < (dm.size()); ++w){\n\t\tif(w < first25kb){\n\t\t\tbglevelsloc.smoothed[db[w]] = dm[w];\n\t\t\tbglevelsloc.smoothed_stdev[db[w]] = ds[w];\n\t\t}\n\t\telse{\n\t\t\tboost::accumulators::accumulator_set<double, stats<tag::rolling_mean> > acc(tag::rolling_window::window_size = (WindowSizeloc));\n\t\t\tboost::accumulators::accumulator_set<double, stats<tag::rolling_mean> > acc2(tag::rolling_window::window_size = (WindowSizeloc));\n\t\t\t\n\t\t\tif(w >= first25kb && w < first25kb + WindowSizeloc - 1){\n\t\t\t\t\n\t\n\t\t\t\t/**\n\t\t\t\tif(dwm.size()==WindowSizeloc){\n\t\t\t\t\tfor(z = 0; z < WindowSizeloc;++z){\n\t\t\t\t\t\tstd::cout<<dwm[z]<<std::endl;\n\t\t\t\t\t}\n\t\t\t\t\tdwm.pop_front();\n\t\t\t\t}\n\t\t\t**/\n\t\t\t\t//change to rolling mean if needed\n\t\t\t\tbglevelsloc.smoothed[db[w]] = dm[w];\n\t\t\t\tbglevelsloc.smoothed_stdev[db[w]] = ds[w];\n\t\t\t\t\n\n\t\t\t}\n\t\t\telse {\n\t\t\t    if(firstpass){\n\t\t\t        for(auto it=w-(WindowSizeloc/2); it<w+WindowSizeloc/2;++it){ //for the first bin that is to be smoothed\n\t\t\t            dwm.push_back(dm[it]);\n\t\t\t            dws.push_back(ds[it]);\n\t\t\t        }\n\t\t\t        firstpass=false;\n\t\t\t    }\n\t\t\t\tbool ifrolling=false;\n\t\t\t\t\n\t\t\t\t//To check that the window stops at the last bin\n\t\t\t\tif(w+WindowSizeloc/2 < dm.size()){\n\t\t\t\t    dwm.push_back(dm.at(w+WindowSizeloc/2));\n\t\t\t\t    dws.push_back(ds.at(w+WindowSizeloc/2));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\n\t\t\t\tif(dwm.size()==WindowSizeloc){\n\t\t\t\t\tifrolling=true;\n\t\t\t\t\tfor(z = 0; z < WindowSizeloc;++z){\n\t\t\t\t\t\tacc(dwm[z]);\n\t\t\t\t\t\tacc2(dws[z]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(ifrolling){\n\t\t\t\t\tbglevelsloc.smoothed[db[w]] = rolling_mean(acc);\n\t\t\t\t\tbglevelsloc.smoothed_stdev[db[w]] = rolling_mean(acc2); \n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tbglevelsloc.smoothed[db[w]] = dm[w];\n\t\t\t\t\tbglevelsloc.smoothed_stdev[db[w]] = ds[w]; \n\t\t\t\t\t\n\t\t\t\t}\n\t\t\n\t\t\t\tdwm.pop_front();\n\t\t\t\tdws.pop_front();\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid DetermineBackgroundLevels::PrintBackgroundFrequency(int bSize, int bSizePP, PrDes::RENFileInfo& reInfo){\n\t\n\tstd::string FileNamePE, FileNamePP;\n\t\n\tFileNamePE.append(expName);\n\tFileNamePE.append(\".\");\n\tFileNamePE.append(reInfo.genomeAssembly.substr(0, reInfo.genomeAssembly.find_first_of(',')));\n\tFileNamePE.append(\".Probe_Distal.BackgroundLevels.\");\n\tFileNamePE.append(reInfo.currTime);\n\tFileNamePE.append(\".txt\");\n\t\n\tFileNamePP.append(expName);\n\tFileNamePP.append(\".\");\n\tFileNamePP.append(reInfo.genomeAssembly.substr(0, reInfo.genomeAssembly.find_first_of(',')));\t\n\tFileNamePP.append(\".Probe_Probe.BackgroundLevels.\");\n\tFileNamePP.append(reInfo.currTime);\n\tFileNamePP.append(\".txt\");\n\t\n\tstd::ofstream outfPE(FileNamePE.c_str());\n\tstd::ofstream outfPP(FileNamePP.c_str());\n    outfPE << \"Distance Bin\" << '\\t' << \"Interaction Distance\" << '\\t' << \"Mean \" << '\\t' << \"Stdev\" << '\\t' << \"Sample Size\" << '\\t' << \"Mean (Smoothed)\" << '\\t' << \"StDev (Smoothed)\" <<  std::endl;\n    \n\tfor (auto it = bglevels.smoothed.begin(); it != bglevels.smoothed.end(); ++it){\n        outfPE << (it->first) << '\\t'<< (it->first)*bSize << '\\t' << bglevels.mean[it->first] << '\\t' << bglevels.stdev[it->first] << '\\t' << bglevels.samplesize[it->first] << '\\t' << it->second << '\\t' << bglevels.smoothed_stdev[it->first] << std::endl;\t\n\t}\n\t\n\toutfPP << \"Distance Bin\" << '\\t' << \"Interaction Distance\" << '\\t' << \"Mean \" << '\\t' << \"Stdev\" << '\\t' << \"Sample Size\" << '\\t' << \"Mean (Smoothed)\" << '\\t' << \"StDev (Smoothed)\" <<  std::endl;\n\t\n\tfor (auto it = bglevelsProbeProbe.smoothed.begin(); it != bglevelsProbeProbe.smoothed.end(); ++it){\n        outfPP << (it->first) << '\\t' << (it->first)*bSizePP << '\\t' << bglevelsProbeProbe.mean[it->first] << '\\t' << bglevelsProbeProbe.stdev[it->first] << '\\t' << bglevelsProbeProbe.samplesize[it->first] << '\\t' << it->second << '\\t' << bglevelsProbeProbe.smoothed_stdev[it->first] << std::endl;\t\n\t}\n\t\n}\n\n", "meta": {"hexsha": "be1901808230496c1e472dc5ad062127e18f7934", "size": 10193, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BackgroundInteractionFrequency.cpp", "max_stars_repo_name": "aanil/HiCapTools", "max_stars_repo_head_hexsha": "21783926679f1045dcda36f806baa6608b7cf67c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-02-13T16:19:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T09:15:42.000Z", "max_issues_repo_path": "src/BackgroundInteractionFrequency.cpp", "max_issues_repo_name": "aanil/HiCapTools", "max_issues_repo_head_hexsha": "21783926679f1045dcda36f806baa6608b7cf67c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T11:13:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-06T18:28:42.000Z", "max_forks_repo_path": "src/BackgroundInteractionFrequency.cpp", "max_forks_repo_name": "aanil/HiCapTools", "max_forks_repo_head_hexsha": "21783926679f1045dcda36f806baa6608b7cf67c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-06-27T15:03:55.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-03T10:54:20.000Z", "avg_line_length": 39.0536398467, "max_line_length": 298, "alphanum_fraction": 0.6477975081, "num_tokens": 2835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.21393010790330638}}
{"text": "/* Copyright (c) 2016 - 2019, the adamantine authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n */\n\n#ifndef THERMAL_OPERATOR_HH\n#define THERMAL_OPERATOR_HH\n\n#include <MaterialProperty.hh>\n#include <Operator.hh>\n\n#include <deal.II/dofs/dof_handler.h>\n#include <deal.II/lac/affine_constraints.h>\n#include <deal.II/matrix_free/cuda_matrix_free.h>\n#include <deal.II/matrix_free/cuda_fe_evaluation.h>\n\nnamespace adamantine\n{\n  template <int dim, int fe_degree, typename NumberType>\n  class ThermalOperatorQuad\n{\npublic:\n__device__ ThermalOperatorQuad(NumberType thermal_conductivity, NumberType alpha, NumberType beta):\n_thermal_conductivity(thermal_conductivity),\n_alpha(alpha),\n_beta(beta)\n{}\n\n__device__ void \noperator()(dealii::CUDAWrappers::FEEvaluation<dim, fe_degree, fe_degree+1, 1, NumberType> *fe_eval) const;\n\nprivate:\nNumberType _thermal_conductivity;\nNumberType _alpha;\nNumberType _beta;\n};\n\ntemplate <int dim, int fe_degree, typename NumberType>\nclass LocalThermalOperator\n{\npublic:\nLocalThermalOperator(NumberType *thermal_conductivity, NumberType *alpha, NumberType *beta)\n: _thermal_conductivity(thermal_conductivity),\n_alpha(alpha),\n_beta(beta)\n{}\n\n__device__ void operator()(\n    const unsigned int cell,\n    const typename dealii::CUDAWrappers::MatrixFree<dim, NumberType>::Data *gpu_data,\n    dealii::CUDAWrappers::SharedData<dim, NumberType> * shared_data,\n    const NumberType *src,\n    NumberType* dst) const;\n\n    static const unsigned int n_dofs_1d    = fe_degree + 1;\n    static const unsigned int n_local_dofs = dealii::Utilities::pow(fe_degree + 1, dim);\n    static const unsigned int n_q_points   = dealii::Utilities::pow(fe_degree + 1, dim);\n  private:\n    NumberType *_thermal_conductivity;\nNumberType *_alpha;\nNumberType *_beta;\n  };\n\n/**\n * This class is the operator associated with the heat equation, i.e., vmult\n * performs \\f$ dst = -\\nabla k \\nabla src \\f$.\n */\ntemplate <int dim, int fe_degree, typename NumberType>\nclass ThermalOperator : public Operator<NumberType>\n{\npublic:\n  ThermalOperator(MPI_Comm const &communicator,\n                  std::shared_ptr<MaterialProperty<dim>> material_properties);\n\n  /**\n   * Associate the AffineConstraints<NumberType> and the MatrixFree objects to the\n   * underlying Triangulation.\n   */\n  template <typename QuadratureType>\n  void setup_dofs(dealii::DoFHandler<dim> const &dof_handler,\n                  dealii::AffineConstraints<NumberType> const &affine_constraints,\n                  QuadratureType const &quad);\n\n  /**\n   * Compute the inverse of the mass matrix and update the material properties.\n   */\n  void reinit(dealii::DoFHandler<dim> const &dof_handler,\n              dealii::AffineConstraints<NumberType> const &affine_constraints);\n\n  /**\n   * Clear the MatrixFree object and resize the inverse of the mass matrix to\n   * zero.\n   */\n  void clear();\n\n  dealii::types::global_dof_index m() const override;\n\n  dealii::types::global_dof_index n() const override;\n\n  /**\n   * Return a shared pointer to the inverse of the mass matrix.\n   */\n  std::shared_ptr<dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA>>\n  get_inverse_mass_matrix() const;\n\n  /**\n   * Return a shared pointer to the underlying MatrixFree object.\n   */\n  dealii::CUDAWrappers::MatrixFree<dim, NumberType> const &get_matrix_free() const;\n\n  void\n  vmult(dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> &dst,\n        dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &src) const override;\n\n  void\n  Tvmult(dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> &dst,\n         dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &src) const override;\n\n  void vmult_add(\n      dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> &dst,\n      dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &src) const override;\n\n  void Tvmult_add(\n      dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> &dst,\n      dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &src) const override;\n\n  void jacobian_vmult(\n      dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> &dst,\n      dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &src) const override;\n\n  /**\n   * Evaluate the material properties for a given state field.\n   */\n  void evaluate_material_properties(\n      dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &state);\n\nprivate:\n  /**\n   * Apply the operator on a given set of quadrature points.\n   */\n  void\n  local_apply(dealii::CUDAWrappers::MatrixFree<dim, NumberType> const &data,\n              dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> &dst,\n              dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &src,\n              std::pair<unsigned int, unsigned int> const &cell_range) const;\n\n  /**\n   * MPI communicator.\n   */\n  MPI_Comm const &_communicator;\n  /**\n   * Data to configure the MatrixFree object.\n   */\n  typename dealii::CUDAWrappers::MatrixFree<dim, NumberType>::AdditionalData\n      _matrix_free_data;\n  /**\n   * Store the \\f$ \\alpha \\f$ coefficient described in\n   * MaterialProperty::compute_constants()\n   */\n  dealii::LinearAlgebra::CUDAWrappers::Vector<NumberType> _alpha;\n  /**\n   * Store the \\f$ \\beta \\f$ coefficient described in\n   * MaterialProperty::compute_constants()\n   */\n  dealii::LinearAlgebra::CUDAWrappers::Vector<NumberType> _beta;\n  /**\n   * Table of thermal conductivity coefficient.\n   */\n  dealii::LinearAlgebra::CUDAWrappers::Vector<NumberType> _thermal_conductivity;\n  /**\n   * Material properties associated with the domain.\n   */\n  std::shared_ptr<MaterialProperty<dim>> _material_properties;\n  /**\n   * Underlying MatrixFree object.\n   */\n  dealii::CUDAWrappers::MatrixFree<dim, NumberType> _matrix_free;\n  /**\n   * The inverse of the mass matrix is computed using an inexact Gauss-Lobatto\n   * quadrature. This inexact quadrature makes the mass matrix and therefore\n   * also its inverse, a diagonal matrix.\n   */\n  std::shared_ptr<dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA>>\n      _inverse_mass_matrix;\n\n  dealii::types::global_dof_index _m;\n\n  dealii::DoFHandler<dim>const * _dof_handler;\n};\n\ntemplate <int dim, int fe_degree, typename NumberType>\ninline dealii::types::global_dof_index\nThermalOperator<dim, fe_degree, NumberType>::m() const\n{\n  return _m;\n}\n\ntemplate <int dim, int fe_degree, typename NumberType>\ninline dealii::types::global_dof_index\nThermalOperator<dim, fe_degree, NumberType>::n() const\n{\n  return _m;\n}\n\ntemplate <int dim, int fe_degree, typename NumberType>\ninline std::shared_ptr<dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA>>\nThermalOperator<dim, fe_degree, NumberType>::get_inverse_mass_matrix() const\n{\n  return _inverse_mass_matrix;\n}\n\ntemplate <int dim, int fe_degree, typename NumberType>\ninline dealii::CUDAWrappers::MatrixFree<dim, NumberType> const &\nThermalOperator<dim, fe_degree, NumberType>::get_matrix_free() const\n{\n  return _matrix_free;\n}\n\ntemplate <int dim, int fe_degree, typename NumberType>\ninline void ThermalOperator<dim, fe_degree, NumberType>::jacobian_vmult(\n    dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> &dst,\n    dealii::LA::distributed::Vector<NumberType, dealii::MemorySpace::CUDA> const &src) const\n{\n  vmult(dst, src);\n}\n} // namespace adamantine\n\n#endif\n", "meta": {"hexsha": "a0e0ccad80ade8e7867b59e85336133c5f91e190", "size": 7717, "ext": "hh", "lang": "C++", "max_stars_repo_path": "source/ThermalOperator.hh", "max_stars_repo_name": "masterleinad/adamantine", "max_stars_repo_head_hexsha": "f5de64d869bf419273946d4f25fb0a8ddc016eaf", "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": "source/ThermalOperator.hh", "max_issues_repo_name": "masterleinad/adamantine", "max_issues_repo_head_hexsha": "f5de64d869bf419273946d4f25fb0a8ddc016eaf", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/ThermalOperator.hh", "max_forks_repo_name": "masterleinad/adamantine", "max_forks_repo_head_hexsha": "f5de64d869bf419273946d4f25fb0a8ddc016eaf", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4069264069, "max_line_length": 107, "alphanum_fraction": 0.7343527277, "num_tokens": 2012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.3702254064929193, "lm_q1q2_score": 0.213803456323694}}
{"text": "/*=============================================================================\nCopyright 2018 Pranam Lashkari <plashkari628@gmail.com>\n\nDistributed under the Boost Software License, Version 1.0. (See accompanying\nfile License.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n\n#ifndef BOOST_ASTRONOMY_COORDINATE_SUPERGALACTIC_HPP\n#define BOOST_ASTRONOMY_COORDINATE_SUPERGALACTIC_HPP\n\n#include <boost/astronomy/coordinate/ref_frame/base_frame.hpp>\n#include <boost/astronomy/coordinate/rep/spherical_representation.hpp>\n#include <boost/astronomy/coordinate/diff/spherical_coslat_differential.hpp>\n\nnamespace boost { namespace astronomy { namespace coordinate {\n\ntemplate <typename Representation, typename Differential>\nstruct supergalactic : public base_frame<Representation, Differential>\n{\n    ///@cond INTERNAL\n    BOOST_STATIC_ASSERT_MSG((std::is_base_of\n        <spherical_representation<typename Representation::type,\n        typename Representation::quantity1, typename Representation::quantity2,\n        typename Representation::quantity3>, Representation>::value),\n        \"argument type is expected to be a spherical_representation class\");\n    BOOST_STATIC_ASSERT_MSG((std::is_base_of\n        <spherical_coslat_differential<typename Differential::type,\n        typename Differential::quantity1, typename Differential::quantity2,\n        typename Differential::quantity3>, Differential>::value),\n        \"argument type is expected to be a spherical_coslat_differential class\");\n    ///@endcond\n\npublic:\n    //default constructor no initialization\n    supergalactic() {}\n\n    //!creates coordinate in supergalactic frame using any subclass of base_representation\n    template <typename OtherRepresentation>\n    supergalactic(OtherRepresentation const& representation_data)\n    {\n        BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n         <boost::astronomy::coordinate::base_representation, OtherRepresentation>::value),\n         \"Invalid representation class\");\n\n        auto temp = make_spherical_representation\n            <\n            typename Representation::type,\n            typename Representation::quantity1,\n            typename Representation::quantity2,\n            typename Representation::quantity3,\n            typename OtherRepresentation::type,\n            typename OtherRepresentation::quantity1,\n            typename OtherRepresentation::quantity2,\n            typename OtherRepresentation::quantity3\n            >(representation_data);\n\n        this->data = temp;\n    }\n\n    //!creates coordinate from given values\n    //!sgb -> latitude, sgl -> longitude\n    supergalactic\n    (\n        typename Representation::quantity1 const& sgb,\n        typename Representation::quantity2 const& sgl,\n        typename Representation::quantity3 const& distance\n    )\n    {\n        this->data.set_lat_lon_dist(sgb, sgl, distance);\n    }\n\n    //!creates coordinate with motion from given values\n    //!sgb -> latitude, sgl -> longitude\n    //!pm_sgb -> proper motion in sgb, pm_sgl_cossgb -> proper motion in sgl including cos(sgb)\n    supergalactic\n    (\n        typename Representation::quantity1 const& sgb,\n        typename Representation::quantity2 const& sgl,\n        typename Representation::quantity3 const& distance,\n        typename Differential::quantity1 const& pm_sgb,\n        typename Differential::quantity2 const& pm_sgl_cossgb,\n        typename Differential::quantity3 const& radial_velocity\n    ) : supergalactic(sgb, sgl, distance)\n    {\n        this->motion.set_dlat_dlon_coslat_ddist(pm_sgb, pm_sgl_cossgb, radial_velocity);\n    }\n\n    //!creates coordinate with motion\n    //!representation class is used for coordinate data\n    //!differential class is used for motion data\n    template <typename OtherRepresentation, typename OtherDifferential>\n    supergalactic\n    (\n        OtherRepresentation const& representation_data,\n        OtherDifferential const& differential_data\n    )\n    {\n        BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n         <boost::astronomy::coordinate::base_representation, OtherRepresentation>::value),\n         \"argument type is expected to be a differential class\");\n\n        BOOST_STATIC_ASSERT_MSG((boost::astronomy::detail::is_base_template_of\n            <boost::astronomy::coordinate::base_differential, OtherDifferential>::value),\n            \"argument type is expected to be a differential class\");\n\n        auto rep_temp = make_spherical_representation\n            <\n                typename Representation::type,\n                typename Representation::quantity1,\n                typename Representation::quantity2,\n                typename Representation::quantity3,\n                typename OtherRepresentation::type,\n                typename OtherRepresentation::quantity1,\n                typename OtherRepresentation::quantity2,\n                typename OtherRepresentation::quantity3\n            >(representation_data);\n        this->data = rep_temp;\n\n        auto dif_temp = make_spherical_coslat_differential\n            <\n                typename Differential::type,\n                typename Differential::quantity1,\n                typename Differential::quantity2,\n                typename Differential::quantity3,\n                typename OtherDifferential::type,\n                typename OtherDifferential::quantity1,\n                typename OtherDifferential::quantity2,\n                typename OtherDifferential::quantity3\n            >(differential_data);\n        this->motion = dif_temp;\n    }\n\n    //copy constructor\n    supergalactic(supergalactic<Representation, Differential> const& other)\n    {\n        this->data = other.get_data();\n        this->motion = other.get_differential();\n    }\n\n    //!returns component sgb of the supergalactic coordinate\n    typename Representation::quantity1 get_sgb() const\n    {\n        return this->data.get_lat();\n    }\n\n    //!returns component sgl of the supergalactic coordinate\n    typename Representation::quantity2 get_sgl() const\n    {\n        return this->data.get_lon();\n    }\n\n    //!returns distance component of the supergalactic coordinate\n    typename Representation::quantity3 get_distance() const\n    {\n        return this->data.get_dist();\n    }\n\n    //!returns the (sgb, sgl, dist) in the form of tuple\n    std::tuple\n    <\n        typename Representation::quantity1,\n        typename Representation::quantity2,\n        typename Representation::quantity3\n    > get_sgb_sgl_dist() const\n    {\n        return this->data.get_lat_lon_dist();\n    }\n\n    //!returns proper motion in supergalactic latitude\n    typename Differential::quantity1 get_pm_sgb() const\n    {\n        return this->motion.get_dlat();\n    }\n\n    //!returns proper motion in supergalactic longitude including cos(b)\n    typename Differential::quantity2 get_pm_sgl_cossgb() const\n    {\n        return this->motion.get_dlon_coslat();\n    }\n\n    //!returns radial_velocity\n    typename Differential::quantity3 get_radial_velocity() const\n    {\n        return this->motion.get_ddist();\n    }\n\n    //!returns the proper motion in form of tuple including cos(b)\n    std::tuple\n    <\n        typename Differential::quantity1,\n        typename Differential::quantity2,\n        typename Differential::quantity3\n    > get_pm_sgb_sgl_radial() const\n    {\n        return this->motion.get_dlat_dlon_coslat_ddist();\n    }\n\n    //!sets value of component b of the supergalactic coordinate\n    void set_sgb(typename Representation::quantity1 const& sgb)\n    {\n        this->data.set_lat(sgb);\n    }\n\n    //!sets value of component sgl of the supergalactic coordinate\n    void set_sgl(typename Representation::quantity2 const& sgl) const\n    {\n        this->data.set_lon(sgl);\n    }\n\n    //!sets value of distance component of the supergalactic coordinate\n    void set_distance(typename Representation::quantity3 const& distance)\n    {\n        this->data.set_dist(distance);\n    }\n\n    //!sets value of all component of the coordinate\n    void set_sgb_sgl_dist\n    (\n        typename Representation::quantity1 const& sgb,\n        typename Representation::quantity2 const& sgl,\n        typename Representation::quantity3 const& dist\n    )\n    {\n        this->data.set_lat_lon_dist(sgb, sgl, dist);\n    }\n\n    //!sets the proper motion in supergalactic latitude\n    void set_pm_sgb(typename Differential::quantity1 const& pm_sgb)\n    {\n        this->motion.set_dlat(pm_sgb);\n    }\n\n    //!sets the proper motion in supergalactic longitude including cos(b)\n    void set_pm_sgl_cossgb(typename Differential::quantity2 const& pm_sgl_cossgb)\n    {\n        this->motion.set_dlon_coslat(pm_sgl_cossgb);\n    }\n\n    //!sets the radial_velocity\n    void set_radial_velocity(typename Differential::quantity3 const& radial_velocity)\n    {\n        this->motion.set_ddist(radial_velocity);\n    }\n\n    //!set value of motion including cos(b)\n    void set_pm_sgb_sgl_radial\n    (\n        typename Differential::quantity1 const& pm_sgb,\n        typename Differential::quantity2 const& pm_sgl_cosb,\n        typename Differential::quantity3 const& radial_velocity\n    )\n    {\n        this->motion.set_dlat_dlon_coslat_ddist(pm_sgb, pm_sgl_cosb, radial_velocity);\n    }\n\n};\n\n}}} //namespace boost::astronomy::coordinate\n\n#endif // !BOOST_ASTRONOMY_COORDINATE_SUPERGALACTIC_HPP\n\n", "meta": {"hexsha": "66047bde8ae9f73e8ee446508e48de38c0abf84e", "size": 9402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/astronomy/coordinate/coord_sys/supergalactic.hpp", "max_stars_repo_name": "lpranam/Astronomy", "max_stars_repo_head_hexsha": "63aa055a3ce849210680451d81db4cc1ddc8d402", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-05-14T08:23:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-23T05:26:19.000Z", "max_issues_repo_path": "include/boost/astronomy/coordinate/coord_sys/supergalactic.hpp", "max_issues_repo_name": "Zyro9922/astronomy", "max_issues_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/astronomy/coordinate/coord_sys/supergalactic.hpp", "max_forks_repo_name": "Zyro9922/astronomy", "max_forks_repo_head_hexsha": "56be0f8dfb103520ffbec0b793a92a531cd4b714", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8854961832, "max_line_length": 95, "alphanum_fraction": 0.678366305, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.21380344829804884}}
{"text": "#ifndef BOOST_GEOMETRY_PROJECTIONS_CASS_HPP\r\n#define BOOST_GEOMETRY_PROJECTIONS_CASS_HPP\r\n\r\n// Boost.Geometry - extensions-gis-projections (based on PROJ4)\r\n// This file is automatically generated. DO NOT EDIT.\r\n\r\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\r\n\r\n// This file was modified by Oracle on 2017.\r\n// Modifications copyright (c) 2017, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\r\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\r\n// PROJ4 is maintained by Frank Warmerdam\r\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\r\n\r\n// Last updated version of proj: 4.9.1\r\n\r\n// Original copyright notice:\r\n\r\n// Permission is hereby granted, free of charge, to any person obtaining a\r\n// copy of this software and associated documentation files (the \"Software\"),\r\n// to deal in the Software without restriction, including without limitation\r\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\r\n// and/or sell copies of the Software, and to permit persons to whom the\r\n// Software is furnished to do so, subject to the following conditions:\r\n\r\n// The above copyright notice and this permission notice shall be included\r\n// in all copies or substantial portions of the Software.\r\n\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\r\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\r\n// DEALINGS IN THE SOFTWARE.\r\n\r\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\r\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\r\n#include <boost/geometry/srs/projections/impl/projects.hpp>\r\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\r\n#include <boost/geometry/srs/projections/impl/pj_mlfn.hpp>\r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace srs { namespace par4\r\n{\r\n    struct cass {};\r\n\r\n}} //namespace srs::par4\r\n\r\nnamespace projections\r\n{\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail { namespace cass\r\n    {\r\n\r\n            //static const double EPS10 = 1e-10;\r\n            //static const double C1 = .16666666666666666666;\r\n            //static const double C2 = .00833333333333333333;\r\n            //static const double C3 = .04166666666666666666;\r\n            //static const double C4 = .33333333333333333333;\r\n            //static const double C5 = .06666666666666666666;\r\n\r\n            template <typename T>\r\n            inline T C1() { return .16666666666666666666666666666666666666; }\r\n            template <typename T>\r\n            inline T C2() { return .00833333333333333333333333333333333333; }\r\n            template <typename T>\r\n            inline T C3() { return .04166666666666666666666666666666666666; }\r\n            template <typename T>\r\n            inline T C4() { return .33333333333333333333333333333333333333; }\r\n            template <typename T>\r\n            inline T C5() { return .06666666666666666666666666666666666666; }\r\n\r\n            template <typename T>\r\n            struct par_cass\r\n            {\r\n                T m0;\r\n                T en[EN_SIZE];\r\n            };\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename CalculationType, typename Parameters>\r\n            struct base_cass_ellipsoid : public base_t_fi<base_cass_ellipsoid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>\r\n            {\r\n\r\n                typedef CalculationType geographic_type;\r\n                typedef CalculationType cartesian_type;\r\n\r\n                par_cass<CalculationType> m_proj_parm;\r\n\r\n                inline base_cass_ellipsoid(const Parameters& par)\r\n                    : base_t_fi<base_cass_ellipsoid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par) {}\r\n\r\n                // FORWARD(e_forward)  ellipsoid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\r\n                {\r\n                    static const CalculationType C1 = cass::C1<CalculationType>();\r\n                    static const CalculationType C2 = cass::C2<CalculationType>();\r\n                    static const CalculationType C3 = cass::C3<CalculationType>();\r\n\r\n                    CalculationType n = sin(lp_lat);\r\n                    CalculationType c = cos(lp_lat);\r\n                    xy_y = pj_mlfn(lp_lat, n, c, this->m_proj_parm.en);\r\n                    n = 1./sqrt(1. - this->m_par.es * n * n);\r\n                    CalculationType tn = tan(lp_lat); CalculationType t = tn * tn;\r\n                    CalculationType a1 = lp_lon * c;\r\n                    c *= this->m_par.es * c / (1 - this->m_par.es);\r\n                    CalculationType a2 = a1 * a1;\r\n                    xy_x = n * a1 * (1. - a2 * t *\r\n                        (C1 - (8. - t + 8. * c) * a2 * C2));\r\n                    xy_y -= this->m_proj_parm.m0 - n * tn * a2 *\r\n                        (.5 + (5. - t + 6. * c) * a2 * C3);\r\n                }\r\n\r\n                // INVERSE(e_inverse)  ellipsoid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\r\n                {\r\n                    static const CalculationType C3 = cass::C3<CalculationType>();\r\n                    static const CalculationType C4 = cass::C4<CalculationType>();\r\n                    static const CalculationType C5 = cass::C5<CalculationType>();\r\n\r\n                    CalculationType ph1;\r\n\r\n                    ph1 = pj_inv_mlfn(this->m_proj_parm.m0 + xy_y, this->m_par.es, this->m_proj_parm.en);\r\n                    CalculationType tn = tan(ph1); CalculationType t = tn * tn;\r\n                    CalculationType n = sin(ph1);\r\n                    CalculationType r = 1. / (1. - this->m_par.es * n * n);\r\n                    n = sqrt(r);\r\n                    r *= (1. - this->m_par.es) * n;\r\n                    CalculationType dd = xy_x / n;\r\n                    CalculationType d2 = dd * dd;\r\n                    lp_lat = ph1 - (n * tn / r) * d2 *\r\n                        (.5 - (1. + 3. * t) * d2 * C3);\r\n                    lp_lon = dd * (1. + t * d2 *\r\n                        (-C4 + (1. + 3. * t) * d2 * C5)) / cos(ph1);\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"cass_ellipsoid\";\r\n                }\r\n\r\n            };\r\n\r\n            // template class, using CRTP to implement forward/inverse\r\n            template <typename CalculationType, typename Parameters>\r\n            struct base_cass_spheroid : public base_t_fi<base_cass_spheroid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>\r\n            {\r\n\r\n                typedef CalculationType geographic_type;\r\n                typedef CalculationType cartesian_type;\r\n\r\n                par_cass<CalculationType> m_proj_parm;\r\n\r\n                inline base_cass_spheroid(const Parameters& par)\r\n                    : base_t_fi<base_cass_spheroid<CalculationType, Parameters>,\r\n                     CalculationType, Parameters>(*this, par) {}\r\n\r\n                // FORWARD(s_forward)  spheroid\r\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\r\n                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const\r\n                {\r\n                    xy_x = asin(cos(lp_lat) * sin(lp_lon));\r\n                    xy_y = atan2(tan(lp_lat) , cos(lp_lon)) - this->m_par.phi0;\r\n                }\r\n\r\n                // INVERSE(s_inverse)  spheroid\r\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\r\n                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const\r\n                {\r\n                    CalculationType dd = xy_y + this->m_par.phi0;\r\n                    lp_lat = asin(sin(dd) * cos(xy_x));\r\n                    lp_lon = atan2(tan(xy_x), cos(dd));\r\n                }\r\n\r\n                static inline std::string get_name()\r\n                {\r\n                    return \"cass_spheroid\";\r\n                }\r\n\r\n            };\r\n\r\n            // Cassini\r\n            template <typename Parameters, typename T>\r\n            inline void setup_cass(Parameters& par, par_cass<T>& proj_parm)\r\n            {\r\n                if (par.es) {\r\n                    if (!pj_enfn(par.es, proj_parm.en))\r\n                        BOOST_THROW_EXCEPTION( projection_exception(0) );\r\n                    proj_parm.m0 = pj_mlfn(par.phi0, sin(par.phi0), cos(par.phi0), proj_parm.en);\r\n                } else {\r\n                }\r\n            }\r\n\r\n    }} // namespace detail::cass\r\n    #endif // doxygen\r\n\r\n    /*!\r\n        \\brief Cassini projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Cylindrical\r\n         - Spheroid\r\n         - Ellipsoid\r\n        \\par Example\r\n        \\image html ex_cass.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct cass_ellipsoid : public detail::cass::base_cass_ellipsoid<CalculationType, Parameters>\r\n    {\r\n        inline cass_ellipsoid(const Parameters& par) : detail::cass::base_cass_ellipsoid<CalculationType, Parameters>(par)\r\n        {\r\n            detail::cass::setup_cass(this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    /*!\r\n        \\brief Cassini projection\r\n        \\ingroup projections\r\n        \\tparam Geographic latlong point type\r\n        \\tparam Cartesian xy point type\r\n        \\tparam Parameters parameter type\r\n        \\par Projection characteristics\r\n         - Cylindrical\r\n         - Spheroid\r\n         - Ellipsoid\r\n        \\par Example\r\n        \\image html ex_cass.gif\r\n    */\r\n    template <typename CalculationType, typename Parameters>\r\n    struct cass_spheroid : public detail::cass::base_cass_spheroid<CalculationType, Parameters>\r\n    {\r\n        inline cass_spheroid(const Parameters& par) : detail::cass::base_cass_spheroid<CalculationType, Parameters>(par)\r\n        {\r\n            detail::cass::setup_cass(this->m_par, this->m_proj_parm);\r\n        }\r\n    };\r\n\r\n    #ifndef DOXYGEN_NO_DETAIL\r\n    namespace detail\r\n    {\r\n\r\n        // Static projection\r\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::cass, cass_spheroid, cass_ellipsoid)\r\n\r\n        // Factory entry(s)\r\n        template <typename CalculationType, typename Parameters>\r\n        class cass_entry : public detail::factory_entry<CalculationType, Parameters>\r\n        {\r\n            public :\r\n                virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const\r\n                {\r\n                    if (par.es)\r\n                        return new base_v_fi<cass_ellipsoid<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                    else\r\n                        return new base_v_fi<cass_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par);\r\n                }\r\n        };\r\n\r\n        template <typename CalculationType, typename Parameters>\r\n        inline void cass_init(detail::base_factory<CalculationType, Parameters>& factory)\r\n        {\r\n            factory.add_to_factory(\"cass\", new cass_entry<CalculationType, Parameters>);\r\n        }\r\n\r\n    } // namespace detail\r\n    #endif // doxygen\r\n\r\n} // namespace projections\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_PROJECTIONS_CASS_HPP\r\n\r\n", "meta": {"hexsha": "8d653ea23b39f567c263c5c204a3c318c8e635d2", "size": 12456, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/cass.hpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/cass.hpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/cass.hpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5119453925, "max_line_length": 132, "alphanum_fraction": 0.5848587026, "num_tokens": 2769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5660185205547238, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.21369501080236727}}
{"text": "// Copyright (c) 2014-2018, The Enro Project Copyright (c) 2014-2018, The Monero 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// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers\n\n#include \"include_base_utils.h\"\nusing namespace epee;\n\n#include <atomic>\n#include <boost/algorithm/string.hpp>\n#include \"wipeable_string.h\"\n#include \"string_tools.h\"\n#include \"serialization/string.h\"\n#include \"cryptonote_format_utils.h\"\n#include \"cryptonote_config.h\"\n#include \"crypto/crypto.h\"\n#include \"crypto/hash.h\"\n#include \"ringct/rctSigs.h\"\n\n#undef MONERO_DEFAULT_LOG_CATEGORY\n#define MONERO_DEFAULT_LOG_CATEGORY \"cn\"\n\n#define ENCRYPTED_PAYMENT_ID_TAIL 0x8d\n\n// #define ENABLE_HASH_CASH_INTEGRITY_CHECK\n\nusing namespace crypto;\n\nstatic const uint64_t valid_decomposed_outputs[] = {\n  (uint64_t)1, (uint64_t)2, (uint64_t)3, (uint64_t)4, (uint64_t)5, (uint64_t)6, (uint64_t)7, (uint64_t)8, (uint64_t)9, // 1 piconero\n  (uint64_t)10, (uint64_t)20, (uint64_t)30, (uint64_t)40, (uint64_t)50, (uint64_t)60, (uint64_t)70, (uint64_t)80, (uint64_t)90,\n  (uint64_t)100, (uint64_t)200, (uint64_t)300, (uint64_t)400, (uint64_t)500, (uint64_t)600, (uint64_t)700, (uint64_t)800, (uint64_t)900,\n  (uint64_t)1000, (uint64_t)2000, (uint64_t)3000, (uint64_t)4000, (uint64_t)5000, (uint64_t)6000, (uint64_t)7000, (uint64_t)8000, (uint64_t)9000,\n  (uint64_t)10000, (uint64_t)20000, (uint64_t)30000, (uint64_t)40000, (uint64_t)50000, (uint64_t)60000, (uint64_t)70000, (uint64_t)80000, (uint64_t)90000,\n  (uint64_t)100000, (uint64_t)200000, (uint64_t)300000, (uint64_t)400000, (uint64_t)500000, (uint64_t)600000, (uint64_t)700000, (uint64_t)800000, (uint64_t)900000,\n  (uint64_t)1000000, (uint64_t)2000000, (uint64_t)3000000, (uint64_t)4000000, (uint64_t)5000000, (uint64_t)6000000, (uint64_t)7000000, (uint64_t)8000000, (uint64_t)9000000, // 1 micronero\n  (uint64_t)10000000, (uint64_t)20000000, (uint64_t)30000000, (uint64_t)40000000, (uint64_t)50000000, (uint64_t)60000000, (uint64_t)70000000, (uint64_t)80000000, (uint64_t)90000000,\n  (uint64_t)100000000, (uint64_t)200000000, (uint64_t)300000000, (uint64_t)400000000, (uint64_t)500000000, (uint64_t)600000000, (uint64_t)700000000, (uint64_t)800000000, (uint64_t)900000000,\n  (uint64_t)1000000000, (uint64_t)2000000000, (uint64_t)3000000000, (uint64_t)4000000000, (uint64_t)5000000000, (uint64_t)6000000000, (uint64_t)7000000000, (uint64_t)8000000000, (uint64_t)9000000000,\n  (uint64_t)10000000000, (uint64_t)20000000000, (uint64_t)30000000000, (uint64_t)40000000000, (uint64_t)50000000000, (uint64_t)60000000000, (uint64_t)70000000000, (uint64_t)80000000000, (uint64_t)90000000000,\n  (uint64_t)100000000000, (uint64_t)200000000000, (uint64_t)300000000000, (uint64_t)400000000000, (uint64_t)500000000000, (uint64_t)600000000000, (uint64_t)700000000000, (uint64_t)800000000000, (uint64_t)900000000000,\n  (uint64_t)1000000000000, (uint64_t)2000000000000, (uint64_t)3000000000000, (uint64_t)4000000000000, (uint64_t)5000000000000, (uint64_t)6000000000000, (uint64_t)7000000000000, (uint64_t)8000000000000, (uint64_t)9000000000000, // 1 enro\n  (uint64_t)10000000000000, (uint64_t)20000000000000, (uint64_t)30000000000000, (uint64_t)40000000000000, (uint64_t)50000000000000, (uint64_t)60000000000000, (uint64_t)70000000000000, (uint64_t)80000000000000, (uint64_t)90000000000000,\n  (uint64_t)100000000000000, (uint64_t)200000000000000, (uint64_t)300000000000000, (uint64_t)400000000000000, (uint64_t)500000000000000, (uint64_t)600000000000000, (uint64_t)700000000000000, (uint64_t)800000000000000, (uint64_t)900000000000000,\n  (uint64_t)1000000000000000, (uint64_t)2000000000000000, (uint64_t)3000000000000000, (uint64_t)4000000000000000, (uint64_t)5000000000000000, (uint64_t)6000000000000000, (uint64_t)7000000000000000, (uint64_t)8000000000000000, (uint64_t)9000000000000000,\n  (uint64_t)10000000000000000, (uint64_t)20000000000000000, (uint64_t)30000000000000000, (uint64_t)40000000000000000, (uint64_t)50000000000000000, (uint64_t)60000000000000000, (uint64_t)70000000000000000, (uint64_t)80000000000000000, (uint64_t)90000000000000000,\n  (uint64_t)100000000000000000, (uint64_t)200000000000000000, (uint64_t)300000000000000000, (uint64_t)400000000000000000, (uint64_t)500000000000000000, (uint64_t)600000000000000000, (uint64_t)700000000000000000, (uint64_t)800000000000000000, (uint64_t)900000000000000000,\n  (uint64_t)1000000000000000000, (uint64_t)2000000000000000000, (uint64_t)3000000000000000000, (uint64_t)4000000000000000000, (uint64_t)5000000000000000000, (uint64_t)6000000000000000000, (uint64_t)7000000000000000000, (uint64_t)8000000000000000000, (uint64_t)9000000000000000000, // 1 meganero\n  (uint64_t)10000000000000000000ull\n};\n\nstatic std::atomic<unsigned int> default_decimal_point(CRYPTONOTE_DISPLAY_DECIMAL_POINT);\n\nstatic std::atomic<uint64_t> tx_hashes_calculated_count(0);\nstatic std::atomic<uint64_t> tx_hashes_cached_count(0);\nstatic std::atomic<uint64_t> block_hashes_calculated_count(0);\nstatic std::atomic<uint64_t> block_hashes_cached_count(0);\n\n#define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {MWARNING(message); throw std::runtime_error(message);}}\n\nnamespace cryptonote\n{\n  static inline unsigned char *operator &(ec_point &point) {\n    return &reinterpret_cast<unsigned char &>(point);\n  }\n  static inline const unsigned char *operator &(const ec_point &point) {\n    return &reinterpret_cast<const unsigned char &>(point);\n  }\n\n  // a copy of rct::addKeys, since we can't link to libringct to avoid circular dependencies\n  static void add_public_key(crypto::public_key &AB, const crypto::public_key &A, const crypto::public_key &B) {\n      ge_p3 B2, A2;\n      CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, &B) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n      CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, &A) == 0, \"ge_frombytes_vartime failed at \"+boost::lexical_cast<std::string>(__LINE__));\n      ge_cached tmp2;\n      ge_p3_to_cached(&tmp2, &B2);\n      ge_p1p1 tmp3;\n      ge_add(&tmp3, &A2, &tmp2);\n      ge_p1p1_to_p3(&A2, &tmp3);\n      ge_p3_tobytes(&AB, &A2);\n  }\n}\n\nnamespace cryptonote\n{\n  //---------------------------------------------------------------\n  void get_transaction_prefix_hash(const transaction_prefix& tx, crypto::hash& h)\n  {\n    std::ostringstream s;\n    binary_archive<true> a(s);\n    ::serialization::serialize(a, const_cast<transaction_prefix&>(tx));\n    crypto::cn_fast_hash(s.str().data(), s.str().size(), h);\n  }\n  //---------------------------------------------------------------\n  crypto::hash get_transaction_prefix_hash(const transaction_prefix& tx)\n  {\n    crypto::hash h = null_hash;\n    get_transaction_prefix_hash(tx, h);\n    return h;\n  }\n  //---------------------------------------------------------------\n  bool expand_transaction_1(transaction &tx, bool base_only)\n  {\n    if (tx.version >= 2 && !is_coinbase(tx))\n    {\n      rct::rctSig &rv = tx.rct_signatures;\n      if (rv.outPk.size() != tx.vout.size())\n      {\n        LOG_PRINT_L1(\"Failed to parse transaction from blob, bad outPk size in tx \" << get_transaction_hash(tx));\n        return false;\n      }\n      for (size_t n = 0; n < tx.rct_signatures.outPk.size(); ++n)\n      {\n        if (tx.vout[n].target.type() != typeid(txout_to_key))\n        {\n          LOG_PRINT_L1(\"Unsupported output type in tx \" << get_transaction_hash(tx));\n          return false;\n        }\n        rv.outPk[n].dest = rct::pk2rct(boost::get<txout_to_key>(tx.vout[n].target).key);\n      }\n\n      if (!base_only)\n      {\n        const bool bulletproof = rct::is_rct_bulletproof(rv.type);\n        if (bulletproof)\n        {\n          if (rv.p.bulletproofs.size() != 1)\n          {\n            LOG_PRINT_L1(\"Failed to parse transaction from blob, bad bulletproofs size in tx \" << get_transaction_hash(tx));\n            return false;\n          }\n          if (rv.p.bulletproofs[0].L.size() < 6)\n          {\n            LOG_PRINT_L1(\"Failed to parse transaction from blob, bad bulletproofs L size in tx \" << get_transaction_hash(tx));\n            return false;\n          }\n          const size_t max_outputs = 1 << (rv.p.bulletproofs[0].L.size() - 6);\n          if (max_outputs < tx.vout.size())\n          {\n            LOG_PRINT_L1(\"Failed to parse transaction from blob, bad bulletproofs max outputs in tx \" << get_transaction_hash(tx));\n            return false;\n          }\n          const size_t n_amounts = tx.vout.size();\n          CHECK_AND_ASSERT_MES(n_amounts == rv.outPk.size(), false, \"Internal error filling out V\");\n          rv.p.bulletproofs[0].V.resize(n_amounts);\n          for (size_t i = 0; i < n_amounts; ++i)\n            rv.p.bulletproofs[0].V[i] = rct::scalarmultKey(rv.outPk[i].mask, rct::INV_EIGHT);\n        }\n      }\n    }\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool parse_and_validate_tx_from_blob(const blobdata& tx_blob, transaction& tx)\n  {\n    std::stringstream ss;\n    ss << tx_blob;\n    binary_archive<false> ba(ss);\n    bool r = ::serialization::serialize(ba, tx);\n    CHECK_AND_ASSERT_MES(r, false, \"Failed to parse transaction from blob\");\n    CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, \"Failed to expand transaction data\");\n    tx.invalidate_hashes();\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool parse_and_validate_tx_base_from_blob(const blobdata& tx_blob, transaction& tx)\n  {\n    std::stringstream ss;\n    ss << tx_blob;\n    binary_archive<false> ba(ss);\n    bool r = tx.serialize_base(ba);\n    CHECK_AND_ASSERT_MES(r, false, \"Failed to parse transaction from blob\");\n    CHECK_AND_ASSERT_MES(expand_transaction_1(tx, true), false, \"Failed to expand transaction data\");\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool parse_and_validate_tx_from_blob(const blobdata& tx_blob, transaction& tx, crypto::hash& tx_hash, crypto::hash& tx_prefix_hash)\n  {\n    std::stringstream ss;\n    ss << tx_blob;\n    binary_archive<false> ba(ss);\n    bool r = ::serialization::serialize(ba, tx);\n    CHECK_AND_ASSERT_MES(r, false, \"Failed to parse transaction from blob\");\n    CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, \"Failed to expand transaction data\");\n    tx.invalidate_hashes();\n    //TODO: validate tx\n\n    get_transaction_hash(tx, tx_hash);\n    get_transaction_prefix_hash(tx, tx_prefix_hash);\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool generate_key_image_helper(const account_keys& ack, const std::unordered_map<crypto::public_key, subaddress_index>& subaddresses, const crypto::public_key& out_key, const crypto::public_key& tx_public_key, const std::vector<crypto::public_key>& additional_tx_public_keys, size_t real_output_index, keypair& in_ephemeral, crypto::key_image& ki, hw::device &hwdev)\n  {\n    crypto::key_derivation recv_derivation = AUTO_VAL_INIT(recv_derivation);\n    bool r = hwdev.generate_key_derivation(tx_public_key, ack.m_view_secret_key, recv_derivation);\n    if (!r)\n    {\n      MWARNING(\"key image helper: failed to generate_key_derivation(\" << tx_public_key << \", \" << ack.m_view_secret_key << \")\");\n      memcpy(&recv_derivation, rct::identity().bytes, sizeof(recv_derivation));\n    }\n\n    std::vector<crypto::key_derivation> additional_recv_derivations;\n    for (size_t i = 0; i < additional_tx_public_keys.size(); ++i)\n    {\n      crypto::key_derivation additional_recv_derivation = AUTO_VAL_INIT(additional_recv_derivation);\n      r = hwdev.generate_key_derivation(additional_tx_public_keys[i], ack.m_view_secret_key, additional_recv_derivation);\n      if (!r)\n      {\n        MWARNING(\"key image helper: failed to generate_key_derivation(\" << additional_tx_public_keys[i] << \", \" << ack.m_view_secret_key << \")\");\n      }\n      else\n      {\n        additional_recv_derivations.push_back(additional_recv_derivation);\n      }\n    }\n\n    boost::optional<subaddress_receive_info> subaddr_recv_info = is_out_to_acc_precomp(subaddresses, out_key, recv_derivation, additional_recv_derivations, real_output_index,hwdev);\n    CHECK_AND_ASSERT_MES(subaddr_recv_info, false, \"key image helper: given output pubkey doesn't seem to belong to this address\");\n\n    return generate_key_image_helper_precomp(ack, out_key, subaddr_recv_info->derivation, real_output_index, subaddr_recv_info->index, in_ephemeral, ki, hwdev);\n  }\n  //---------------------------------------------------------------\n  bool generate_key_image_helper_precomp(const account_keys& ack, const crypto::public_key& out_key, const crypto::key_derivation& recv_derivation, size_t real_output_index, const subaddress_index& received_index, keypair& in_ephemeral, crypto::key_image& ki, hw::device &hwdev)\n  {\n    if (ack.m_spend_secret_key == crypto::null_skey)\n    {\n      // for watch-only wallet, simply copy the known output pubkey\n      in_ephemeral.pub = out_key;\n      in_ephemeral.sec = crypto::null_skey;\n    }\n    else\n    {\n      // derive secret key with subaddress - step 1: original CN derivation\n      crypto::secret_key scalar_step1;\n      hwdev.derive_secret_key(recv_derivation, real_output_index, ack.m_spend_secret_key, scalar_step1); // computes Hs(a*R || idx) + b\n\n      // step 2: add Hs(a || index_major || index_minor)\n      crypto::secret_key subaddr_sk;\n      crypto::secret_key scalar_step2;\n      if (received_index.is_zero())\n      {\n        scalar_step2 = scalar_step1;    // treat index=(0,0) as a special case representing the main address\n      }\n      else\n      {\n        subaddr_sk = hwdev.get_subaddress_secret_key(ack.m_view_secret_key, received_index);\n        hwdev.sc_secret_add(scalar_step2, scalar_step1,subaddr_sk);\n      }\n\n      in_ephemeral.sec = scalar_step2;\n\n      if (ack.m_multisig_keys.empty())\n      {\n        // when not in multisig, we know the full spend secret key, so the output pubkey can be obtained by scalarmultBase\n        CHECK_AND_ASSERT_MES(hwdev.secret_key_to_public_key(in_ephemeral.sec, in_ephemeral.pub), false, \"Failed to derive public key\");\n      }\n      else\n      {\n        // when in multisig, we only know the partial spend secret key. but we do know the full spend public key, so the output pubkey can be obtained by using the standard CN key derivation\n        CHECK_AND_ASSERT_MES(hwdev.derive_public_key(recv_derivation, real_output_index, ack.m_account_address.m_spend_public_key, in_ephemeral.pub), false, \"Failed to derive public key\");\n        // and don't forget to add the contribution from the subaddress part\n        if (!received_index.is_zero())\n        {\n          crypto::public_key subaddr_pk;\n          CHECK_AND_ASSERT_MES(hwdev.secret_key_to_public_key(subaddr_sk, subaddr_pk), false, \"Failed to derive public key\");\n          add_public_key(in_ephemeral.pub, in_ephemeral.pub, subaddr_pk);\n        }\n      }\n\n      CHECK_AND_ASSERT_MES(in_ephemeral.pub == out_key,\n           false, \"key image helper precomp: given output pubkey doesn't match the derived one\");\n    }\n\n    hwdev.generate_key_image(in_ephemeral.pub, in_ephemeral.sec, ki);\n    return true;\n  }\n  //---------------------------------------------------------------\n  uint64_t power_integral(uint64_t a, uint64_t b)\n  {\n    if(b == 0)\n      return 1;\n    uint64_t total = a;\n    for(uint64_t i = 1; i != b; i++)\n      total *= a;\n    return total;\n  }\n  //---------------------------------------------------------------\n  bool parse_amount(uint64_t& amount, const std::string& str_amount_)\n  {\n    std::string str_amount = str_amount_;\n    boost::algorithm::trim(str_amount);\n\n    size_t point_index = str_amount.find_first_of('.');\n    size_t fraction_size;\n    if (std::string::npos != point_index)\n    {\n      fraction_size = str_amount.size() - point_index - 1;\n      while (default_decimal_point < fraction_size && '0' == str_amount.back())\n      {\n        str_amount.erase(str_amount.size() - 1, 1);\n        --fraction_size;\n      }\n      if (default_decimal_point < fraction_size)\n        return false;\n      str_amount.erase(point_index, 1);\n    }\n    else\n    {\n      fraction_size = 0;\n    }\n\n    if (str_amount.empty())\n      return false;\n\n    if (fraction_size < default_decimal_point)\n    {\n      str_amount.append(default_decimal_point - fraction_size, '0');\n    }\n\n    return string_tools::get_xtype_from_string(amount, str_amount);\n  }\n  //---------------------------------------------------------------\n  uint64_t get_transaction_weight(const transaction &tx, size_t blob_size)\n  {\n    if (tx.version < 2)\n      return blob_size;\n    const rct::rctSig &rv = tx.rct_signatures;\n    if (!rct::is_rct_bulletproof(rv.type))\n      return blob_size;\n    const size_t n_outputs = tx.vout.size();\n    if (n_outputs <= 2)\n      return blob_size;\n    const uint64_t bp_base = 368;\n    const size_t n_padded_outputs = rct::n_bulletproof_max_amounts(rv.p.bulletproofs);\n    size_t nlr = 0;\n    for (const auto &bp: rv.p.bulletproofs)\n      nlr += bp.L.size() * 2;\n    const size_t bp_size = 32 * (9 + nlr);\n    CHECK_AND_ASSERT_THROW_MES_L1(bp_base * n_padded_outputs >= bp_size, \"Invalid bulletproof clawback\");\n    const uint64_t bp_clawback = (bp_base * n_padded_outputs - bp_size) * 4 / 5;\n    CHECK_AND_ASSERT_THROW_MES_L1(bp_clawback <= std::numeric_limits<uint64_t>::max() - blob_size, \"Weight overflow\");\n    return blob_size + bp_clawback;\n  }\n  //---------------------------------------------------------------\n  uint64_t get_transaction_weight(const transaction &tx)\n  {\n    std::ostringstream s;\n    binary_archive<true> a(s);\n    ::serialization::serialize(a, const_cast<transaction&>(tx));\n    const cryptonote::blobdata blob = s.str();\n    return get_transaction_weight(tx, blob.size());\n  }\n  //---------------------------------------------------------------\n  bool get_tx_fee(const transaction& tx, uint64_t & fee)\n  {\n    if (tx.version > 1)\n    {\n      fee = tx.rct_signatures.txnFee;\n      return true;\n    }\n    uint64_t amount_in = 0;\n    uint64_t amount_out = 0;\n    for(auto& in: tx.vin)\n    {\n      CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), 0, \"unexpected type id in transaction\");\n      amount_in += boost::get<txin_to_key>(in).amount;\n    }\n    for(auto& o: tx.vout)\n      amount_out += o.amount;\n\n    CHECK_AND_ASSERT_MES(amount_in >= amount_out, false, \"transaction spend (\" <<amount_in << \") more than it has (\" << amount_out << \")\");\n    fee = amount_in - amount_out;\n    return true;\n  }\n  //---------------------------------------------------------------\n  uint64_t get_tx_fee(const transaction& tx)\n  {\n    uint64_t r = 0;\n    if(!get_tx_fee(tx, r))\n      return 0;\n    return r;\n  }\n  //---------------------------------------------------------------\n  bool parse_tx_extra(const std::vector<uint8_t>& tx_extra, std::vector<tx_extra_field>& tx_extra_fields)\n  {\n    tx_extra_fields.clear();\n\n    if(tx_extra.empty())\n      return true;\n\n    std::string extra_str(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size());\n    std::istringstream iss(extra_str);\n    binary_archive<false> ar(iss);\n\n    bool eof = false;\n    while (!eof)\n    {\n      tx_extra_field field;\n      bool r = ::do_serialize(ar, field);\n      CHECK_AND_NO_ASSERT_MES_L1(r, false, \"failed to deserialize extra field. extra = \" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));\n      tx_extra_fields.push_back(field);\n\n      std::ios_base::iostate state = iss.rdstate();\n      eof = (EOF == iss.peek());\n      iss.clear(state);\n    }\n    CHECK_AND_NO_ASSERT_MES_L1(::serialization::check_stream_state(ar), false, \"failed to deserialize extra field. extra = \" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));\n\n    return true;\n  }\n  //---------------------------------------------------------------\n  crypto::public_key get_tx_pub_key_from_extra(const std::vector<uint8_t>& tx_extra, size_t pk_index)\n  {\n    std::vector<tx_extra_field> tx_extra_fields;\n    parse_tx_extra(tx_extra, tx_extra_fields);\n\n    tx_extra_pub_key pub_key_field;\n    if(!find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, pk_index))\n      return null_pkey;\n\n    return pub_key_field.pub_key;\n  }\n  //---------------------------------------------------------------\n  crypto::public_key get_tx_pub_key_from_extra(const transaction_prefix& tx_prefix, size_t pk_index)\n  {\n    return get_tx_pub_key_from_extra(tx_prefix.extra, pk_index);\n  }\n  //---------------------------------------------------------------\n  crypto::public_key get_tx_pub_key_from_extra(const transaction& tx, size_t pk_index)\n  {\n    return get_tx_pub_key_from_extra(tx.extra, pk_index);\n  }\n  //---------------------------------------------------------------\n  bool add_tx_pub_key_to_extra(transaction& tx, const crypto::public_key& tx_pub_key)\n  {\n    return add_tx_pub_key_to_extra(tx.extra, tx_pub_key);\n  }\n  //---------------------------------------------------------------\n  bool add_tx_pub_key_to_extra(transaction_prefix& tx, const crypto::public_key& tx_pub_key)\n  {\n    return add_tx_pub_key_to_extra(tx.extra, tx_pub_key);\n  }\n  //---------------------------------------------------------------\n  bool add_tx_pub_key_to_extra(std::vector<uint8_t>& tx_extra, const crypto::public_key& tx_pub_key)\n  {\n    tx_extra.resize(tx_extra.size() + 1 + sizeof(crypto::public_key));\n    tx_extra[tx_extra.size() - 1 - sizeof(crypto::public_key)] = TX_EXTRA_TAG_PUBKEY;\n    *reinterpret_cast<crypto::public_key*>(&tx_extra[tx_extra.size() - sizeof(crypto::public_key)]) = tx_pub_key;\n    return true;\n  }\n  //---------------------------------------------------------------\n  std::vector<crypto::public_key> get_additional_tx_pub_keys_from_extra(const std::vector<uint8_t>& tx_extra)\n  {\n    // parse\n    std::vector<tx_extra_field> tx_extra_fields;\n    parse_tx_extra(tx_extra, tx_extra_fields);\n    // find corresponding field\n    tx_extra_additional_pub_keys additional_pub_keys;\n    if(!find_tx_extra_field_by_type(tx_extra_fields, additional_pub_keys))\n      return {};\n    return additional_pub_keys.data;\n  }\n  //---------------------------------------------------------------\n  std::vector<crypto::public_key> get_additional_tx_pub_keys_from_extra(const transaction_prefix& tx)\n  {\n    return get_additional_tx_pub_keys_from_extra(tx.extra);\n  }\n  //---------------------------------------------------------------\n  bool add_additional_tx_pub_keys_to_extra(std::vector<uint8_t>& tx_extra, const std::vector<crypto::public_key>& additional_pub_keys)\n  {\n    // convert to variant\n    tx_extra_field field = tx_extra_additional_pub_keys{ additional_pub_keys };\n    // serialize\n    std::ostringstream oss;\n    binary_archive<true> ar(oss);\n    bool r = ::do_serialize(ar, field);\n    CHECK_AND_NO_ASSERT_MES_L1(r, false, \"failed to serialize tx extra additional tx pub keys\");\n    // append\n    std::string tx_extra_str = oss.str();\n    size_t pos = tx_extra.size();\n    tx_extra.resize(tx_extra.size() + tx_extra_str.size());\n    memcpy(&tx_extra[pos], tx_extra_str.data(), tx_extra_str.size());\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool add_extra_nonce_to_tx_extra(std::vector<uint8_t>& tx_extra, const blobdata& extra_nonce)\n  {\n    CHECK_AND_ASSERT_MES(extra_nonce.size() <= TX_EXTRA_NONCE_MAX_COUNT, false, \"extra nonce could be 255 bytes max\");\n    size_t start_pos = tx_extra.size();\n    tx_extra.resize(tx_extra.size() + 2 + extra_nonce.size());\n    //write tag\n    tx_extra[start_pos] = TX_EXTRA_NONCE;\n    //write len\n    ++start_pos;\n    tx_extra[start_pos] = static_cast<uint8_t>(extra_nonce.size());\n    //write data\n    ++start_pos;\n    memcpy(&tx_extra[start_pos], extra_nonce.data(), extra_nonce.size());\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool remove_field_from_tx_extra(std::vector<uint8_t>& tx_extra, const std::type_info &type)\n  {\n    if (tx_extra.empty())\n      return true;\n    std::string extra_str(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size());\n    std::istringstream iss(extra_str);\n    binary_archive<false> ar(iss);\n    std::ostringstream oss;\n    binary_archive<true> newar(oss);\n\n    bool eof = false;\n    while (!eof)\n    {\n      tx_extra_field field;\n      bool r = ::do_serialize(ar, field);\n      CHECK_AND_NO_ASSERT_MES_L1(r, false, \"failed to deserialize extra field. extra = \" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));\n      if (field.type() != type)\n        ::do_serialize(newar, field);\n\n      std::ios_base::iostate state = iss.rdstate();\n      eof = (EOF == iss.peek());\n      iss.clear(state);\n    }\n    CHECK_AND_NO_ASSERT_MES_L1(::serialization::check_stream_state(ar), false, \"failed to deserialize extra field. extra = \" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast<const char*>(tx_extra.data()), tx_extra.size())));\n    tx_extra.clear();\n    std::string s = oss.str();\n    tx_extra.reserve(s.size());\n    std::copy(s.begin(), s.end(), std::back_inserter(tx_extra));\n    return true;\n  }\n  //---------------------------------------------------------------\n  void set_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash& payment_id)\n  {\n    extra_nonce.clear();\n    extra_nonce.push_back(TX_EXTRA_NONCE_PAYMENT_ID);\n    const uint8_t* payment_id_ptr = reinterpret_cast<const uint8_t*>(&payment_id);\n    std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce));\n  }\n  //---------------------------------------------------------------\n  void set_encrypted_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash8& payment_id)\n  {\n    extra_nonce.clear();\n    extra_nonce.push_back(TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID);\n    const uint8_t* payment_id_ptr = reinterpret_cast<const uint8_t*>(&payment_id);\n    std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce));\n  }\n  //---------------------------------------------------------------\n  bool get_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash& payment_id)\n  {\n    if(sizeof(crypto::hash) + 1 != extra_nonce.size())\n      return false;\n    if(TX_EXTRA_NONCE_PAYMENT_ID != extra_nonce[0])\n      return false;\n    payment_id = *reinterpret_cast<const crypto::hash*>(extra_nonce.data() + 1);\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool get_encrypted_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash8& payment_id)\n  {\n    if(sizeof(crypto::hash8) + 1 != extra_nonce.size())\n      return false;\n    if (TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID != extra_nonce[0])\n      return false;\n    payment_id = *reinterpret_cast<const crypto::hash8*>(extra_nonce.data() + 1);\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool get_inputs_money_amount(const transaction& tx, uint64_t& money)\n  {\n    money = 0;\n    for(const auto& in: tx.vin)\n    {\n      CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);\n      money += tokey_in.amount;\n    }\n    return true;\n  }\n  //---------------------------------------------------------------\n  uint64_t get_block_height(const block& b)\n  {\n    CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, 0, \"wrong miner tx in block: \" << get_block_hash(b) << \", b.miner_tx.vin.size() != 1\");\n    CHECKED_GET_SPECIFIC_VARIANT(b.miner_tx.vin[0], const txin_gen, coinbase_in, 0);\n    return coinbase_in.height;\n  }\n  //---------------------------------------------------------------\n  bool check_inputs_types_supported(const transaction& tx)\n  {\n    for(const auto& in: tx.vin)\n    {\n      CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), false, \"wrong variant type: \"\n        << in.type().name() << \", expected \" << typeid(txin_to_key).name()\n        << \", in transaction id=\" << get_transaction_hash(tx));\n\n    }\n    return true;\n  }\n  //-----------------------------------------------------------------------------------------------\n  bool check_outs_valid(const transaction& tx)\n  {\n    for(const tx_out& out: tx.vout)\n    {\n      CHECK_AND_ASSERT_MES(out.target.type() == typeid(txout_to_key), false, \"wrong variant type: \"\n        << out.target.type().name() << \", expected \" << typeid(txout_to_key).name()\n        << \", in transaction id=\" << get_transaction_hash(tx));\n\n      if (tx.version == 1)\n      {\n        CHECK_AND_NO_ASSERT_MES(0 < out.amount, false, \"zero amount output in transaction id=\" << get_transaction_hash(tx));\n      }\n\n      if(!check_key(boost::get<txout_to_key>(out.target).key))\n        return false;\n    }\n    return true;\n  }\n  //-----------------------------------------------------------------------------------------------\n  bool check_money_overflow(const transaction& tx)\n  {\n    return check_inputs_overflow(tx) && check_outs_overflow(tx);\n  }\n  //---------------------------------------------------------------\n  bool check_inputs_overflow(const transaction& tx)\n  {\n    uint64_t money = 0;\n    for(const auto& in: tx.vin)\n    {\n      CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);\n      if(money > tokey_in.amount + money)\n        return false;\n      money += tokey_in.amount;\n    }\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool check_outs_overflow(const transaction& tx)\n  {\n    uint64_t money = 0;\n    for(const auto& o: tx.vout)\n    {\n      if(money > o.amount + money)\n        return false;\n      money += o.amount;\n    }\n    return true;\n  }\n  //---------------------------------------------------------------\n  uint64_t get_outs_money_amount(const transaction& tx)\n  {\n    uint64_t outputs_amount = 0;\n    for(const auto& o: tx.vout)\n      outputs_amount += o.amount;\n    return outputs_amount;\n  }\n  //---------------------------------------------------------------\n  std::string short_hash_str(const crypto::hash& h)\n  {\n    std::string res = string_tools::pod_to_hex(h);\n    CHECK_AND_ASSERT_MES(res.size() == 64, res, \"wrong hash256 with string_tools::pod_to_hex conversion\");\n    auto erased_pos = res.erase(8, 48);\n    res.insert(8, \"....\");\n    return res;\n  }\n  //---------------------------------------------------------------\n  bool is_out_to_acc(const account_keys& acc, const txout_to_key& out_key, const crypto::public_key& tx_pub_key, const std::vector<crypto::public_key>& additional_tx_pub_keys, size_t output_index)\n  {\n    crypto::key_derivation derivation;\n    bool r = acc.get_device().generate_key_derivation(tx_pub_key, acc.m_view_secret_key, derivation);\n    CHECK_AND_ASSERT_MES(r, false, \"Failed to generate key derivation\");\n    crypto::public_key pk;\n    r = acc.get_device().derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk);\n    CHECK_AND_ASSERT_MES(r, false, \"Failed to derive public key\");\n    if (pk == out_key.key)\n      return true;\n    // try additional tx pubkeys if available\n    if (!additional_tx_pub_keys.empty())\n    {\n      CHECK_AND_ASSERT_MES(output_index < additional_tx_pub_keys.size(), false, \"wrong number of additional tx pubkeys\");\n      r = acc.get_device().generate_key_derivation(additional_tx_pub_keys[output_index], acc.m_view_secret_key, derivation);\n      CHECK_AND_ASSERT_MES(r, false, \"Failed to generate key derivation\");\n      r = acc.get_device().derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk);\n      CHECK_AND_ASSERT_MES(r, false, \"Failed to derive public key\");\n      return pk == out_key.key;\n    }\n    return false;\n  }\n  //---------------------------------------------------------------\n  boost::optional<subaddress_receive_info> is_out_to_acc_precomp(const std::unordered_map<crypto::public_key, subaddress_index>& subaddresses, const crypto::public_key& out_key, const crypto::key_derivation& derivation, const std::vector<crypto::key_derivation>& additional_derivations, size_t output_index, hw::device &hwdev)\n  {\n    // try the shared tx pubkey\n    crypto::public_key subaddress_spendkey;\n    hwdev.derive_subaddress_public_key(out_key, derivation, output_index, subaddress_spendkey);\n    auto found = subaddresses.find(subaddress_spendkey);\n    if (found != subaddresses.end())\n      return subaddress_receive_info{ found->second, derivation };\n    // try additional tx pubkeys if available\n    if (!additional_derivations.empty())\n    {\n      CHECK_AND_ASSERT_MES(output_index < additional_derivations.size(), boost::none, \"wrong number of additional derivations\");\n      hwdev.derive_subaddress_public_key(out_key, additional_derivations[output_index], output_index, subaddress_spendkey);\n      found = subaddresses.find(subaddress_spendkey);\n      if (found != subaddresses.end())\n        return subaddress_receive_info{ found->second, additional_derivations[output_index] };\n    }\n    return boost::none;\n  }\n  //---------------------------------------------------------------\n  bool lookup_acc_outs(const account_keys& acc, const transaction& tx, std::vector<size_t>& outs, uint64_t& money_transfered)\n  {\n    crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx);\n    if(null_pkey == tx_pub_key)\n      return false;\n    std::vector<crypto::public_key> additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx);\n    return lookup_acc_outs(acc, tx, tx_pub_key, additional_tx_pub_keys, outs, money_transfered);\n  }\n  //---------------------------------------------------------------\n  bool lookup_acc_outs(const account_keys& acc, const transaction& tx, const crypto::public_key& tx_pub_key, const std::vector<crypto::public_key>& additional_tx_pub_keys, std::vector<size_t>& outs, uint64_t& money_transfered)\n  {\n    CHECK_AND_ASSERT_MES(additional_tx_pub_keys.empty() || additional_tx_pub_keys.size() == tx.vout.size(), false, \"wrong number of additional pubkeys\" );\n    money_transfered = 0;\n    size_t i = 0;\n    for(const tx_out& o:  tx.vout)\n    {\n      CHECK_AND_ASSERT_MES(o.target.type() ==  typeid(txout_to_key), false, \"wrong type id in transaction out\" );\n      if(is_out_to_acc(acc, boost::get<txout_to_key>(o.target), tx_pub_key, additional_tx_pub_keys, i))\n      {\n        outs.push_back(i);\n        money_transfered += o.amount;\n      }\n      i++;\n    }\n    return true;\n  }\n  //---------------------------------------------------------------\n  void get_blob_hash(const blobdata& blob, crypto::hash& res)\n  {\n    cn_fast_hash(blob.data(), blob.size(), res);\n  }\n  //---------------------------------------------------------------\n  void set_default_decimal_point(unsigned int decimal_point)\n  {\n    switch (decimal_point)\n    {\n      case 12:\n      case 9:\n      case 6:\n      case 3:\n      case 0:\n        default_decimal_point = decimal_point;\n        break;\n      default:\n        ASSERT_MES_AND_THROW(\"Invalid decimal point specification: \" << decimal_point);\n    }\n  }\n  //---------------------------------------------------------------\n  unsigned int get_default_decimal_point()\n  {\n    return default_decimal_point;\n  }\n  //---------------------------------------------------------------\n  std::string get_unit(unsigned int decimal_point)\n  {\n    if (decimal_point == (unsigned int)-1)\n      decimal_point = default_decimal_point;\n    switch (std::atomic_load(&default_decimal_point))\n    {\n      case 12:\n        return \"enro\";\n      case 9:\n        return \"millinero\";\n      case 6:\n        return \"micronero\";\n      case 3:\n        return \"nanonero\";\n      case 0:\n        return \"piconero\";\n      default:\n        ASSERT_MES_AND_THROW(\"Invalid decimal point specification: \" << default_decimal_point);\n    }\n  }\n  //---------------------------------------------------------------\n  std::string print_money(uint64_t amount, unsigned int decimal_point)\n  {\n    if (decimal_point == (unsigned int)-1)\n      decimal_point = default_decimal_point;\n    std::string s = std::to_string(amount);\n    if(s.size() < decimal_point+1)\n    {\n      s.insert(0, decimal_point+1 - s.size(), '0');\n    }\n    if (decimal_point > 0)\n      s.insert(s.size() - decimal_point, \".\");\n    return s;\n  }\n  //---------------------------------------------------------------\n  crypto::hash get_blob_hash(const blobdata& blob)\n  {\n    crypto::hash h = null_hash;\n    get_blob_hash(blob, h);\n    return h;\n  }\n  //---------------------------------------------------------------\n  crypto::hash get_transaction_hash(const transaction& t)\n  {\n    crypto::hash h = null_hash;\n    get_transaction_hash(t, h, NULL);\n    return h;\n  }\n  //---------------------------------------------------------------\n  bool get_transaction_hash(const transaction& t, crypto::hash& res)\n  {\n    return get_transaction_hash(t, res, NULL);\n  }\n  //---------------------------------------------------------------\n  bool calculate_transaction_prunable_hash(const transaction& t, crypto::hash& res)\n  {\n    if (t.version == 1)\n      return false;\n    transaction &tt = const_cast<transaction&>(t);\n    std::stringstream ss;\n    binary_archive<true> ba(ss);\n    const size_t inputs = t.vin.size();\n    const size_t outputs = t.vout.size();\n    const size_t mixin = t.vin.empty() ? 0 : t.vin[0].type() == typeid(txin_to_key) ? boost::get<txin_to_key>(t.vin[0]).key_offsets.size() - 1 : 0;\n    bool r = tt.rct_signatures.p.serialize_rctsig_prunable(ba, t.rct_signatures.type, inputs, outputs, mixin);\n    CHECK_AND_ASSERT_MES(r, false, \"Failed to serialize rct signatures prunable\");\n    cryptonote::get_blob_hash(ss.str(), res);\n    return true;\n  }\n  //---------------------------------------------------------------\n  crypto::hash get_transaction_prunable_hash(const transaction& t)\n  {\n    crypto::hash res;\n    CHECK_AND_ASSERT_THROW_MES(calculate_transaction_prunable_hash(t, res), \"Failed to calculate tx prunable hash\");\n    return res;\n  }\n  //---------------------------------------------------------------\n  crypto::hash get_pruned_transaction_hash(const transaction& t, const crypto::hash &pruned_data_hash)\n  {\n    // v1 transactions hash the entire blob\n    CHECK_AND_ASSERT_THROW_MES(t.version > 1, \"Hash for pruned v1 tx cannot be calculated\");\n\n    // v2 transactions hash different parts together, than hash the set of those hashes\n    crypto::hash hashes[3];\n\n    // prefix\n    get_transaction_prefix_hash(t, hashes[0]);\n\n    transaction &tt = const_cast<transaction&>(t);\n\n    // base rct\n    {\n      std::stringstream ss;\n      binary_archive<true> ba(ss);\n      const size_t inputs = t.vin.size();\n      const size_t outputs = t.vout.size();\n      bool r = tt.rct_signatures.serialize_rctsig_base(ba, inputs, outputs);\n      CHECK_AND_ASSERT_THROW_MES(r, \"Failed to serialize rct signatures base\");\n      cryptonote::get_blob_hash(ss.str(), hashes[1]);\n    }\n\n    // prunable rct\n    hashes[2] = pruned_data_hash;\n\n    // the tx hash is the hash of the 3 hashes\n    crypto::hash res = cn_fast_hash(hashes, sizeof(hashes));\n    return res;\n  }\n  //---------------------------------------------------------------\n  bool calculate_transaction_hash(const transaction& t, crypto::hash& res, size_t* blob_size)\n  {\n    // v1 transactions hash the entire blob\n    if (t.version == 1)\n    {\n      size_t ignored_blob_size, &blob_size_ref = blob_size ? *blob_size : ignored_blob_size;\n      return get_object_hash(t, res, blob_size_ref);\n    }\n\n    // v2 transactions hash different parts together, than hash the set of those hashes\n    crypto::hash hashes[3];\n\n    // prefix\n    get_transaction_prefix_hash(t, hashes[0]);\n\n    transaction &tt = const_cast<transaction&>(t);\n\n    // base rct\n    {\n      std::stringstream ss;\n      binary_archive<true> ba(ss);\n      const size_t inputs = t.vin.size();\n      const size_t outputs = t.vout.size();\n      bool r = tt.rct_signatures.serialize_rctsig_base(ba, inputs, outputs);\n      CHECK_AND_ASSERT_MES(r, false, \"Failed to serialize rct signatures base\");\n      cryptonote::get_blob_hash(ss.str(), hashes[1]);\n    }\n\n    // prunable rct\n    if (t.rct_signatures.type == rct::RCTTypeNull)\n    {\n      hashes[2] = crypto::null_hash;\n    }\n    else\n    {\n      CHECK_AND_ASSERT_MES(calculate_transaction_prunable_hash(t, hashes[2]), false, \"Failed to get tx prunable hash\");\n    }\n\n    // the tx hash is the hash of the 3 hashes\n    res = cn_fast_hash(hashes, sizeof(hashes));\n\n    // we still need the size\n    if (blob_size)\n      *blob_size = get_object_blobsize(t);\n\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t* blob_size)\n  {\n    if (t.is_hash_valid())\n    {\n#ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK\n      CHECK_AND_ASSERT_THROW_MES(!calculate_transaction_hash(t, res, blob_size) || t.hash == res, \"tx hash cash integrity failure\");\n#endif\n      res = t.hash;\n      if (blob_size)\n      {\n        if (!t.is_blob_size_valid())\n        {\n          t.blob_size = get_object_blobsize(t);\n          t.set_blob_size_valid(true);\n        }\n        *blob_size = t.blob_size;\n      }\n      ++tx_hashes_cached_count;\n      return true;\n    }\n    ++tx_hashes_calculated_count;\n    bool ret = calculate_transaction_hash(t, res, blob_size);\n    if (!ret)\n      return false;\n    t.hash = res;\n    t.set_hash_valid(true);\n    if (blob_size)\n    {\n      t.blob_size = *blob_size;\n      t.set_blob_size_valid(true);\n    }\n    return true;\n  }\n  //---------------------------------------------------------------\n  bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t& blob_size)\n  {\n    return get_transaction_hash(t, res, &blob_size);\n  }\n  //---------------------------------------------------------------\n  blobdata get_block_hashing_blob(const block& b)\n  {\n    blobdata blob = t_serializable_object_to_blob(static_cast<block_header>(b));\n    crypto::hash tree_root_hash = get_tx_tree_hash(b);\n    blob.append(reinterpret_cast<const char*>(&tree_root_hash), sizeof(tree_root_hash));\n    blob.append(tools::get_varint_data(b.tx_hashes.size()+1));\n    return blob;\n  }\n  //---------------------------------------------------------------\n  bool calculate_block_hash(const block& b, crypto::hash& res)\n  {\n    // EXCEPTION FOR BLOCK 202612\n    const std::string correct_blob_hash_202612 = \"3a8a2b3a29b50fc86ff73dd087ea43c6f0d6b8f936c849194d5c84c737903966\";\n    const std::string existing_block_id_202612 = \"bbd604d2ba11ba27935e006ed39c9bfdd99b76bf4a50654bc1e1e61217962698\";\n    crypto::hash block_blob_hash = get_blob_hash(block_to_blob(b));\n\n    if (string_tools::pod_to_hex(block_blob_hash) == correct_blob_hash_202612)\n    {\n      string_tools::hex_to_pod(existing_block_id_202612, res);\n      return true;\n    }\n    bool hash_result = get_object_hash(get_block_hashing_blob(b), res);\n\n    if (hash_result)\n    {\n      // make sure that we aren't looking at a block with the 202612 block id but not the correct blobdata\n      if (string_tools::pod_to_hex(res) == existing_block_id_202612)\n      {\n        LOG_ERROR(\"Block with block id for 202612 but incorrect block blob hash found!\");\n        res = null_hash;\n        return false;\n      }\n    }\n    return hash_result;\n  }\n  //---------------------------------------------------------------\n  bool get_block_hash(const block& b, crypto::hash& res)\n  {\n    if (b.is_hash_valid())\n    {\n#ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK\n      CHECK_AND_ASSERT_THROW_MES(!calculate_block_hash(b, res) || b.hash == res, \"block hash cash integrity failure\");\n#endif\n      res = b.hash;\n      ++block_hashes_cached_count;\n      return true;\n    }\n    ++block_hashes_calculated_count;\n    bool ret = calculate_block_hash(b, res);\n    if (!ret)\n      return false;\n    b.hash = res;\n    b.set_hash_valid(true);\n    return true;\n  }\n  //---------------------------------------------------------------\n  crypto::hash get_block_hash(const block& b)\n  {\n    crypto::hash p = null_hash;\n    get_block_hash(b, p);\n    return p;\n  }\n  //---------------------------------------------------------------\n  bool get_block_longhash(const block& b, crypto::hash& res, uint64_t height)\n  {\n    // block 202612 bug workaround\n    const std::string longhash_202612 = \"84f64766475d51837ac9efbef1926486e58563c95a19fef4aec3254f03000000\";\n    if (height == 202612)\n    {\n      string_tools::hex_to_pod(longhash_202612, res);\n      return true;\n    }\n    blobdata bd = get_block_hashing_blob(b);\n    const int cn_variant = b.major_version >= 7 ? b.major_version - 6 : 0;\n    crypto::cn_slow_hash(bd.data(), bd.size(), res, cn_variant);\n    return true;\n  }\n  //---------------------------------------------------------------\n  std::vector<uint64_t> relative_output_offsets_to_absolute(const std::vector<uint64_t>& off)\n  {\n    std::vector<uint64_t> res = off;\n    for(size_t i = 1; i < res.size(); i++)\n      res[i] += res[i-1];\n    return res;\n  }\n  //---------------------------------------------------------------\n  std::vector<uint64_t> absolute_output_offsets_to_relative(const std::vector<uint64_t>& off)\n  {\n    std::vector<uint64_t> res = off;\n    if(!off.size())\n      return res;\n    std::sort(res.begin(), res.end());//just to be sure, actually it is already should be sorted\n    for(size_t i = res.size()-1; i != 0; i--)\n      res[i] -= res[i-1];\n\n    return res;\n  }\n  //---------------------------------------------------------------\n  crypto::hash get_block_longhash(const block& b, uint64_t height)\n  {\n    crypto::hash p = null_hash;\n    get_block_longhash(b, p, height);\n    return p;\n  }\n  //---------------------------------------------------------------\n  bool parse_and_validate_block_from_blob(const blobdata& b_blob, block& b)\n  {\n    std::stringstream ss;\n    ss << b_blob;\n    binary_archive<false> ba(ss);\n    bool r = ::serialization::serialize(ba, b);\n    CHECK_AND_ASSERT_MES(r, false, \"Failed to parse block from blob\");\n    b.invalidate_hashes();\n    b.miner_tx.invalidate_hashes();\n    return true;\n  }\n  //---------------------------------------------------------------\n  blobdata block_to_blob(const block& b)\n  {\n    return t_serializable_object_to_blob(b);\n  }\n  //---------------------------------------------------------------\n  bool block_to_blob(const block& b, blobdata& b_blob)\n  {\n    return t_serializable_object_to_blob(b, b_blob);\n  }\n  //---------------------------------------------------------------\n  blobdata tx_to_blob(const transaction& tx)\n  {\n    return t_serializable_object_to_blob(tx);\n  }\n  //---------------------------------------------------------------\n  bool tx_to_blob(const transaction& tx, blobdata& b_blob)\n  {\n    return t_serializable_object_to_blob(tx, b_blob);\n  }\n  //---------------------------------------------------------------\n  void get_tx_tree_hash(const std::vector<crypto::hash>& tx_hashes, crypto::hash& h)\n  {\n    tree_hash(tx_hashes.data(), tx_hashes.size(), h);\n  }\n  //---------------------------------------------------------------\n  crypto::hash get_tx_tree_hash(const std::vector<crypto::hash>& tx_hashes)\n  {\n    crypto::hash h = null_hash;\n    get_tx_tree_hash(tx_hashes, h);\n    return h;\n  }\n  //---------------------------------------------------------------\n  crypto::hash get_tx_tree_hash(const block& b)\n  {\n    std::vector<crypto::hash> txs_ids;\n    crypto::hash h = null_hash;\n    size_t bl_sz = 0;\n    get_transaction_hash(b.miner_tx, h, bl_sz);\n    txs_ids.push_back(h);\n    for(auto& th: b.tx_hashes)\n      txs_ids.push_back(th);\n    return get_tx_tree_hash(txs_ids);\n  }\n  //---------------------------------------------------------------\n  bool is_valid_decomposed_amount(uint64_t amount)\n  {\n    const uint64_t *begin = valid_decomposed_outputs;\n    const uint64_t *end = valid_decomposed_outputs + sizeof(valid_decomposed_outputs) / sizeof(valid_decomposed_outputs[0]);\n    return std::binary_search(begin, end, amount);\n  }\n  //---------------------------------------------------------------\n  void get_hash_stats(uint64_t &tx_hashes_calculated, uint64_t &tx_hashes_cached, uint64_t &block_hashes_calculated, uint64_t & block_hashes_cached)\n  {\n    tx_hashes_calculated = tx_hashes_calculated_count;\n    tx_hashes_cached = tx_hashes_cached_count;\n    block_hashes_calculated = block_hashes_calculated_count;\n    block_hashes_cached = block_hashes_cached_count;\n  }\n  //---------------------------------------------------------------\n  crypto::secret_key encrypt_key(crypto::secret_key key, const epee::wipeable_string &passphrase)\n  {\n    crypto::hash hash;\n    crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash);\n    sc_add((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data);\n    return key;\n  }\n  //---------------------------------------------------------------\n  crypto::secret_key decrypt_key(crypto::secret_key key, const epee::wipeable_string &passphrase)\n  {\n    crypto::hash hash;\n    crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash);\n    sc_sub((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data);\n    return key;\n  }\n}\n", "meta": {"hexsha": "4f4546c037d9f765813c2621ffb904dee2799836", "size": 50719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cryptonote_basic/cryptonote_format_utils.cpp", "max_stars_repo_name": "enrocoin/enro", "max_stars_repo_head_hexsha": "c58592b6bda2ebd7495fb9438a7ac270746b58b4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cryptonote_basic/cryptonote_format_utils.cpp", "max_issues_repo_name": "enrocoin/enro", "max_issues_repo_head_hexsha": "c58592b6bda2ebd7495fb9438a7ac270746b58b4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cryptonote_basic/cryptonote_format_utils.cpp", "max_forks_repo_name": "enrocoin/enro", "max_forks_repo_head_hexsha": "c58592b6bda2ebd7495fb9438a7ac270746b58b4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.165106383, "max_line_length": 368, "alphanum_fraction": 0.631676492, "num_tokens": 12662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21358086225236994}}
{"text": "/*\n Copyright 2012 Google Inc. All Rights Reserved.\n Author: blakely@google.com (Tim Blakely)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n#include <boost/random/taus88.hpp>\n#include <stddef.h>\n\n#include \"base_types.h\"\n#include \"boost/random/uniform_01.hpp\"\n#include \"network/objects/connections/ampa.h\"\n#include \"network/objects/neuron.h\"\n#include \"protos/basics.pb.h\"\n#include \"protos/neuron.pb.h\"\n\nnamespace google {\nnamespace protobuf {\nclass Message;\n}  // namespace protobuf\n}  // namespace google\n\nnamespace bigbrain {\n\nusing boost::random::uniform_01;\nusing std::string;\n\nSynapseAmpa::SynapseAmpa()\n    : params_(NULL) {\n}\n\nSynapseAmpa::~SynapseAmpa() {\n}\n\nbool SynapseAmpa::CalculateDerivatives(\n    const float& time, const google::protobuf::Message* input_state,\n    google::protobuf::Message* output_state) {\n  return false;\n}\n\nbool SynapseAmpa::UpdateState(const float& time, const float& dt) {\n  double decay;\n  double newdGdt;\n  double noiseScalar = 1.0;\n\n  AccumulateDelayedInput(time);\n\n  // note: ignoring Synthesis' noise cutofftable here\n\n  uniform_01<> random;\n\n  if (params_->noise_rate() > 0) {\n    if (params_->noise_mode() == \"Poisson\") {\n      if (random(rand_num_gen_) <= params_->noise_rate() * dt) {\n        double input = state_.input()\n            + noiseScalar * params_->noise_amplitude();\n        state_.set_input(input);\n      }\n    }\n  }\n\n  decay = expx(-dt / params_->time_constant_1());\n\n  newdGdt = state_.dg_dt() * decay\n      + state_.input() / dt * params_->time_constant_1() * (1.0 - decay);\n  decay = expx(-dt / params_->time_constant_2());\n  double new_g = state_.g() * decay\n      + state_.dg_dt() * params_->time_constant_2() * (1.0 - decay);\n  double new_g_lower = state_.g() / params_->peak_response()\n      * params_->g_peak();\n\n  state_.set_g(new_g);\n  state_.set_dg_dt(newdGdt);\n  state_.set_g_lower(new_g_lower);\n  state_.set_input(0);\n\n  return true;\n}\n\nvoid SynapseAmpa::add_delayed_input(const double& value) {\n  state_.set_input(state_.input() + value);\n}\n\nbool SynapseAmpa::UpdateConnection(const float& time, const float& dt) {\n  // The following functions from Synthesis are not implemented:\n  // > Short term plasticity\n  // > Probabilistic modeling\n  // > Connection strength (hardcoded to \"5\" to be in line with Synthesis)\n  // > Mini spiking\n\n  double delay = 0;\n\n  uniform_01<> random;\n\n  if (random(rand_num_gen_) <= params_->probability()) {\n    DelayInput(time, state_.input() + 5);\n  }\n\n  return true;\n}\n\ndouble SynapseAmpa::get_current() {\n  // The following functions from Synthesis are not implemented:\n  // > Conductance tables\n  double mp = get_parent()->get_membrane_potential();\n  state_.set_output(\n      (params_->reverse_potential() - get_parent()->get_membrane_potential())\n          * state_.g_lower());\n  return state_.output();\n}\n\nvoid SynapseAmpa::set_params(google::protobuf::Message* params) {\n  // The following functions from Synthesis are not implemented:\n  // > Conductance tables\n\n  // Need to downcast. Kludgy, but extendable\n  params_ = static_cast<AmpaParams*>(params);\n\n  if (params_->time_constant_1() == params_->time_constant_2()) {\n    params_->set_peak_response(params_->time_constant_1() / 2.718281828);\n  } else {\n    double tPeak = params_->time_constant_1() * params_->time_constant_2()\n        / (params_->time_constant_1() - params_->time_constant_2())\n        * log(params_->time_constant_1() / params_->time_constant_2());\n    double peak_response = params_->time_constant_1()\n        * params_->time_constant_2()\n        / (params_->time_constant_1() - params_->time_constant_2())\n        * (expx(-tPeak / params_->time_constant_1())\n            - expx(-tPeak / params_->time_constant_2()));\n    params_->set_peak_response(peak_response);\n  }\n\n  get_common_params()->set_diff_eq_solver(NONE);\n}\n\ngoogle::protobuf::Message* SynapseAmpa::get_state() {\n  return &state_;\n}\n\nstring SynapseAmpa::get_description() {\n  string description = \"AMPA connection\";\n  return description;\n}\n\ngoogle::protobuf::Message* SynapseAmpa::get_unique_params() {\n  return params_;\n}\n\n}  // namespace bigbrain\n", "meta": {"hexsha": "0c9f982d7793f46190a6116f6f80d5cc3898e4d5", "size": 4585, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/network/objects/connections/ampa.cc", "max_stars_repo_name": "slhill/bigbrain", "max_stars_repo_head_hexsha": "69dcf775c450c867c8c65c1b05e06cb6d3a7e5d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/network/objects/connections/ampa.cc", "max_issues_repo_name": "slhill/bigbrain", "max_issues_repo_head_hexsha": "69dcf775c450c867c8c65c1b05e06cb6d3a7e5d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/network/objects/connections/ampa.cc", "max_forks_repo_name": "slhill/bigbrain", "max_forks_repo_head_hexsha": "69dcf775c450c867c8c65c1b05e06cb6d3a7e5d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.4782608696, "max_line_length": 77, "alphanum_fraction": 0.7011995638, "num_tokens": 1206, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883735630721, "lm_q2_score": 0.35577488668296436, "lm_q1q2_score": 0.21353195059283467}}
{"text": "#include \"generalized_eigensolver.h\"\n\n#include <immintrin.h>\n#include <Eigen/Eigen>\n\n#include \"gefast/math/cayley.h\"\n#include \"gefast/util/macros.h\"\n\nnamespace gefast {\n\nnamespace {\n\nEigen::Matrix4d ComposeG(const Matrix38dRowMajor &ray_directions_matrix1,\n                         const Matrix38dRowMajor &ray_directions_matrix2,\n                         const Matrix38dRowMajor &ray_centers_matrix1,\n                         const Matrix38dRowMajor &rcm2_cross_rdm2,\n                         const cayley_t &cayley) {\n  rotation_t rotation = CayleyToRotationMatrixUnscaled(cayley);\n\n  Matrix38dRowMajor rot_ray_directions_matrix2 =\n      rotation * ray_directions_matrix2;\n  Matrix38dRowMajor rot_rcm2_cross_rdm2 = rotation * rcm2_cross_rdm2;\n\n  Eigen::Matrix<double, 4, 8, Eigen::RowMajor> g;\n#ifdef GEFAST_INTRINSICS_AVAILABLE\n  for (auto i = 0; i < 2; ++i) {\n    __m256d _a_1 = _mm256_load_pd(ray_centers_matrix1.data() + i * 4);\n    __m256d _a_2 = _mm256_load_pd(ray_centers_matrix1.data() + 8 + i * 4);\n    __m256d _a_3 = _mm256_load_pd(ray_centers_matrix1.data() + 16 + i * 4);\n\n    __m256d _b_1 = _mm256_load_pd(rot_ray_directions_matrix2.data() + i * 4);\n    __m256d _b_2 =\n        _mm256_load_pd(rot_ray_directions_matrix2.data() + 8 + i * 4);\n    __m256d _b_3 =\n        _mm256_load_pd(rot_ray_directions_matrix2.data() + 16 + i * 4);\n\n    __m256d _rdm1_1 = _mm256_load_pd(ray_directions_matrix1.data() + i * 4);\n    __m256d _rdm1_2 = _mm256_load_pd(ray_directions_matrix1.data() + 8 + i * 4);\n    __m256d _rdm1_3 =\n        _mm256_load_pd(ray_directions_matrix1.data() + 16 + i * 4);\n\n    // ray_centers_matrix1 cross rot_ray_directions_matrix2\n    __m256d _res1 = _mm256_mul_pd(_a_3, _b_2);\n    _res1 = _mm256_fmsub_pd(_a_2, _b_3, _res1);\n\n    __m256d _res2 = _mm256_mul_pd(_a_1, _b_3);\n    _res2 = _mm256_fmsub_pd(_a_3, _b_1, _res2);\n\n    __m256d _res3 = _mm256_mul_pd(_a_2, _b_1);\n    _res3 = _mm256_fmsub_pd(_a_1, _b_2, _res3);\n\n    // rdm1 dot rcm1_cross_rot_rdm2\n\n    __m256d _rdm1_dot_rcm1_cross_rot_rdm2 = _mm256_mul_pd(_rdm1_1, _res1);\n    _rdm1_dot_rcm1_cross_rot_rdm2 =\n        _mm256_fmadd_pd(_rdm1_2, _res2, _rdm1_dot_rcm1_cross_rot_rdm2);\n    _rdm1_dot_rcm1_cross_rot_rdm2 =\n        _mm256_fmadd_pd(_rdm1_3, _res3, _rdm1_dot_rcm1_cross_rot_rdm2);\n\n    // rdm1 cross rot_rdm2\n\n    _res1 = _mm256_mul_pd(_rdm1_3, _b_2);\n    _res1 = _mm256_fmsub_pd(_rdm1_2, _b_3, _res1);\n\n    _res2 = _mm256_mul_pd(_rdm1_1, _b_3);\n    _res2 = _mm256_fmsub_pd(_rdm1_3, _b_1, _res2);\n\n    _res3 = _mm256_mul_pd(_rdm1_2, _b_1);\n    _res3 = _mm256_fmsub_pd(_rdm1_1, _b_2, _res3);\n\n    _mm256_store_pd(g.data() + i * 4, _res1);\n    _mm256_store_pd(g.data() + 8 + i * 4, _res2);\n    _mm256_store_pd(g.data() + 16 + i * 4, _res3);\n\n    // rdm1 dot rot_rcm2_cross_rdm2\n\n    _a_1 = _mm256_load_pd(rot_rcm2_cross_rdm2.data() + i * 4);\n    _a_2 = _mm256_load_pd(rot_rcm2_cross_rdm2.data() + 8 + i * 4);\n    _a_3 = _mm256_load_pd(rot_rcm2_cross_rdm2.data() + 16 + i * 4);\n\n    __m256d _rdm1_dot_rot_rcm2_cross_rdm2 = _mm256_mul_pd(_rdm1_1, _a_1);\n    _rdm1_dot_rot_rcm2_cross_rdm2 =\n        _mm256_fmadd_pd(_rdm1_2, _a_2, _rdm1_dot_rot_rcm2_cross_rdm2);\n    _rdm1_dot_rot_rcm2_cross_rdm2 =\n        _mm256_fmadd_pd(_rdm1_3, _a_3, _rdm1_dot_rot_rcm2_cross_rdm2);\n\n    _mm256_store_pd(g.data() + 24 + i * 4,\n                    _mm256_sub_pd(_rdm1_dot_rcm1_cross_rot_rdm2,\n                                  _rdm1_dot_rot_rcm2_cross_rdm2));\n  }\n#else\n  for (auto i = 0; i != ray_directions_matrix1.cols(); ++i) {\n    g.block<3, 1>(0, i) =\n        ray_directions_matrix1.col(i).cross(rot_ray_directions_matrix2.col(i));\n    g(3, i) =\n        ray_directions_matrix1.col(i).transpose() *\n        (ray_centers_matrix1.col(i).cross(rot_ray_directions_matrix2.col(i)) -\n         rot_rcm2_cross_rdm2.col(i));\n  }\n#endif\n  return g * g.transpose();\n}\n\neigenvalues_t GetEigenvalues(const Matrix38dRowMajor &ray_directions_matrix1,\n                             const Matrix38dRowMajor &ray_directions_matrix2,\n                             const Matrix38dRowMajor &ray_centers_matrix1,\n                             const Matrix38dRowMajor &rcm2_cross_rdm2,\n                             const cayley_t &cayley) {\n  Eigen::Matrix4d G = ComposeG(ray_directions_matrix1, ray_directions_matrix2,\n                               ray_centers_matrix1, rcm2_cross_rdm2, cayley);\n\n  // now compute the roots in closed-form\n  const auto G33 = G(3, 3);\n  const auto G22 = G(2, 2);\n  const auto G11 = G(1, 1);\n  const auto G00 = G(0, 0);\n  const auto G12 = G(1, 2);\n  const auto G13 = G(1, 3);\n  const auto G23 = G(2, 3);\n  const auto G01 = G(0, 1);\n  const auto G02 = G(0, 2);\n  const auto G03 = G(0, 3);\n  const auto G11_plus_G22 = G11 + G22;\n  const auto G22_plus_G33 = G22 + G33;\n  const auto G00_plus_G11 = G00 + G11;\n  const auto G01_2 = G01 * G01;\n  const auto G02_2 = G02 * G02;\n  const auto G03_2 = G03 * G03;\n  const auto G12_2 = G12 * G12;\n  const auto G13_2 = G13 * G13;\n  const auto G23_2 = G23 * G23;\n  const auto G12_2_plus_G13_2_plus_G23_3 = G12_2 + G13_2 + G23_2;\n\n  const double B = -(G00_plus_G11 + G22_plus_G33);\n  const double C = -G12_2_plus_G13_2_plus_G23_3 + G33 * (G00_plus_G11 + G22) +\n                   G11 * G22 - (G03_2 + G02_2 + G01_2) + G00 * (G11_plus_G22);\n  const double D =\n      G13_2 * G22 -\n      2.0 * (G12 * (G13 * G23 + G01 * G02) + G03 * (G02 * G23 + G01 * G13)) +\n      G11 * G23_2 - (G22 * G33 * (G00_plus_G11) + G00 * G11 * (G22_plus_G33)) +\n      G03_2 * G11_plus_G22 + G02_2 * (G33 + G11) + G01_2 * G22_plus_G33 +\n      G00 * (G12_2_plus_G13_2_plus_G23_3) + G12_2 * G33;\n\n  const double E = G.determinant();\n\n  double B_pw2 = B * B;\n  double B_pw3 = B_pw2 * B;\n  double B_pw4 = B_pw3 * B;\n  double alpha = -0.375 * B_pw2 + C;\n  double beta = B_pw3 / 8.0 - B * C / 2.0 + D;\n  double gamma = -0.01171875 * B_pw4 + B_pw2 * C / 16.0 - B * D / 4.0 + E;\n  double alpha_pw2 = alpha * alpha;\n  double alpha_pw3 = alpha_pw2 * alpha;\n  double p = -alpha_pw2 / 12.0 - gamma;\n  double q = -alpha_pw3 / 108.0 + alpha * gamma / 3.0 - beta * beta / 8.0;\n\n  double theta2 = -p / 3.0;\n  double theta1 = sqrt(theta2) *\n                  cos((1.0 / 3.0) * acos((-q / 2.0) / sqrt(-p * p * p / 27.0)));\n  double y = -(5.0 / 6.0) * alpha -\n             ((1.0 / 3.0) * p * theta1 - theta1 * theta2) / theta2;\n  double w = sqrt(alpha + 2.0 * y);\n\n  // we currently disable the computation of all other roots, they are not used\n  double temp1 = -B / 4.0 - 0.5 * w;\n  double temp2 = 0.5 * sqrt(-3.0 * alpha - 2.0 * y + 2.0 * beta / w);\n\n  eigenvalues_t roots;\n  roots[0] = temp1 + temp2;\n  roots[1] = temp1 - temp2;\n  return roots;\n}\n\ndouble GetCost(const Matrix38dRowMajor &ray_directions_matrix1,\n               const Matrix38dRowMajor &ray_directions_matrix2,\n               const Matrix38dRowMajor &ray_centers_matrix1,\n               const Matrix38dRowMajor &rcm2_cross_rdm2, const cayley_t &cayley,\n               bool use_smallest_ev) {\n  Eigen::Vector2d roots =\n      GetEigenvalues(ray_directions_matrix1, ray_directions_matrix2,\n                     ray_centers_matrix1, rcm2_cross_rdm2, cayley);\n\n  if (use_smallest_ev) return roots[1];\n  return roots[0];\n}\n\njacobian_t GetJacobian(const Matrix38dRowMajor &ray_directions_matrix1,\n                       const Matrix38dRowMajor &ray_directions_matrix2,\n                       const Matrix38dRowMajor &ray_centers_matrix1,\n                       const Matrix38dRowMajor &rcm2_cross_rdm2,\n                       const cayley_t &cayley, double current_eigenvalue,\n                       bool use_smallest_ev) {\n  jacobian_t jacobian;\n  const double kEpsilon = 0.00000001;\n\n  for (auto j = 0; j != 3; ++j) {\n    cayley_t cayley_j = cayley;\n    cayley_j(j) += kEpsilon;\n    auto cost_j = GetCost(ray_directions_matrix1, ray_directions_matrix2,\n                          ray_centers_matrix1, rcm2_cross_rdm2, cayley_j,\n                          use_smallest_ev);\n    jacobian(j) =\n        cost_j - current_eigenvalue;  // division by eps can be ommited\n  }\n  return jacobian;\n}\n\nvoid FindModel(const Matrix38dRowMajor &ray_directions_matrix1,\n               const Matrix38dRowMajor &ray_directions_matrix2,\n               const Matrix38dRowMajor &ray_centers_matrix1,\n               const Matrix38dRowMajor &rcm2_cross_rdm2,\n               const cayley_t &starting_point, RelativePose &model) {\n  double lambda = 0.017;\n  double lambda_modifier = 2.0;\n  const double kMaxLambda = 0.07;\n  const double kMinLambda = 0.00001;\n  const int kMaxIterations = 11;\n  const bool kDisableIncrements = false;\n\n  double disturbance_amplitude = 0.3;\n  bool found = false;\n  int random_trials = 0;\n  const int kMaxRandomTrials = 5;\n  cayley_t cayley;\n\n  while (!found && random_trials < kMaxRandomTrials) {\n    int iterations = 0;\n    if (random_trials > 2) disturbance_amplitude = 0.6;\n    cayley.noalias() = starting_point;\n    if (random_trials != 0)\n      cayley.noalias() += disturbance_amplitude * Eigen::Vector3d::Random();\n\n    double smallestEV =\n        GetCost(ray_directions_matrix1, ray_directions_matrix2,\n                ray_centers_matrix1, rcm2_cross_rdm2, cayley, true);\n\n    jacobian_t jacobian = GetJacobian(\n        ray_directions_matrix1, ray_directions_matrix2, ray_centers_matrix1,\n        rcm2_cross_rdm2, cayley, smallestEV, true);\n    jacobian.normalize();\n    Eigen::Matrix3d inverse_hessian = Eigen::Matrix3d::Identity();\n\n    while (iterations < kMaxIterations) {\n      Eigen::Vector3d searchDirection = -inverse_hessian * jacobian;\n      searchDirection.normalize();\n\n      if (jacobian.dot(searchDirection) > 0) {\n        inverse_hessian = Eigen::Matrix3d::Identity();\n        searchDirection = -jacobian;\n      }\n\n      lambda = 0.017;\n      cayley_t next_cayley = cayley + lambda * searchDirection;\n\n      double nextEV =\n          GetCost(ray_directions_matrix1, ray_directions_matrix2,\n                  ray_centers_matrix1, rcm2_cross_rdm2, next_cayley, true);\n\n      if (iterations == 0 || !kDisableIncrements) {\n        while (nextEV < smallestEV) {\n          smallestEV = nextEV;\n          if (lambda * lambda_modifier > kMaxLambda) break;\n          lambda *= lambda_modifier;\n          next_cayley.noalias() = cayley + lambda * searchDirection;\n          nextEV =\n              GetCost(ray_directions_matrix1, ray_directions_matrix2,\n                      ray_centers_matrix1, rcm2_cross_rdm2, next_cayley, true);\n        }\n      }\n\n      while (nextEV > smallestEV) {\n        lambda /= lambda_modifier;\n        if (lambda < kMinLambda) break;\n        next_cayley = cayley + lambda * searchDirection;\n        nextEV =\n            GetCost(ray_directions_matrix1, ray_directions_matrix2,\n                    ray_centers_matrix1, rcm2_cross_rdm2, next_cayley, true);\n      }\n\n      jacobian_t next_jacobian = GetJacobian(\n          ray_directions_matrix1, ray_directions_matrix2, ray_centers_matrix1,\n          rcm2_cross_rdm2, next_cayley, nextEV, true);\n      next_jacobian.normalize();\n\n      Eigen::Vector3d s = lambda * searchDirection;\n      Eigen::Vector3d y = next_jacobian - jacobian;\n      double rho = 1.0 / (y.dot(s));\n\n      inverse_hessian =\n          inverse_hessian -\n          rho * (s * (y.transpose() * inverse_hessian) +\n                 (inverse_hessian * y) * s.transpose()) +\n          rho * (rho * (y).dot(inverse_hessian * y) + 1) * (s * s.transpose());\n\n      cayley = next_cayley;\n      smallestEV = nextEV;\n      jacobian = next_jacobian;\n\n      if (lambda < kMinLambda) break;\n      ++iterations;\n    }\n\n    if (cayley.norm() < 0.01) {\n      // we are close to the origin, test the EV 2\n      double ev2 = GetCost(ray_directions_matrix1, ray_directions_matrix2,\n                           ray_centers_matrix1, rcm2_cross_rdm2, cayley, false);\n      if (ev2 > 0.001)\n        ++random_trials;\n      else\n        found = true;\n    } else\n      found = true;\n  }\n\n  Eigen::Matrix4d G = ComposeG(ray_directions_matrix1, ray_directions_matrix2,\n                               ray_centers_matrix1, rcm2_cross_rdm2, cayley);\n\n  Eigen::EigenSolver<Eigen::Matrix4d> eigensolver_G(G, true);\n  Eigen::Vector4d D = eigensolver_G.eigenvalues().real();\n  Eigen::Matrix4d V = eigensolver_G.eigenvectors().real();\n\n  auto min_eigenvalue_idx = 0;\n  D.minCoeff(&min_eigenvalue_idx);\n\n  model.rotation = CayleyToRotationMatrix(cayley);\n  model.translation = V.col(min_eigenvalue_idx).hnormalized();\n}\n\n}  // namespace\n\nvoid SolveGE(std::vector<Eigen::Vector3d> &ray_centers1,\n             std::vector<Eigen::Vector3d> &ray_directions1,\n             std::vector<Eigen::Vector3d> &ray_centers2,\n             std::vector<Eigen::Vector3d> &ray_directions2,\n             RelativePose &output) {\n  const int kCorrespondencesNumber = static_cast<int>(ray_centers1.size());\n  GEFAST_ASSERT(kCorrespondencesNumber == 8,\n                \"the solver only works with 8 correspondences\");\n  GEFAST_ASSERT(ray_centers2.size() == kCorrespondencesNumber,\n                \"the number of second camera ray centers must be 8\");\n  GEFAST_ASSERT(ray_directions1.size() == kCorrespondencesNumber,\n                \"the number of first camera ray directions must be 8\");\n  GEFAST_ASSERT(ray_directions2.size() == kCorrespondencesNumber,\n                \"the number of second camera ray directions must be 8\");\n\n  Matrix38dRowMajor ray_directions_matrix1 = Eigen::Map<Matrix38dColMajor>(\n      reinterpret_cast<double *>(ray_directions1.data()));\n  Matrix38dRowMajor ray_directions_matrix2 = Eigen::Map<Matrix38dColMajor>(\n      reinterpret_cast<double *>(ray_directions2.data()));\n  Matrix38dRowMajor ray_centers_matrix1 = Eigen::Map<Matrix38dColMajor>(\n      reinterpret_cast<double *>(ray_centers1.data()));\n  Matrix38dRowMajor ray_centers_matrix2 = Eigen::Map<Matrix38dColMajor>(\n      reinterpret_cast<double *>(ray_centers2.data()));\n  Matrix38dRowMajor rcm2_cross_rdm2;\n\n  Eigen::Vector3d points_center1 = ray_directions_matrix1.rowwise().sum();\n  Eigen::Vector3d points_center2 = ray_directions_matrix2.rowwise().sum();\n\n#ifdef GEFAST_INTRINSICS_AVAILABLE\n  for (auto i = 0; i < kCorrespondencesNumber / 4; ++i) {\n    __m256d _rcm2_1 = _mm256_load_pd(ray_centers_matrix2.data() + i * 4);\n    __m256d _rcm2_2 = _mm256_load_pd(ray_centers_matrix2.data() + 8 + i * 4);\n    __m256d _rcm2_3 = _mm256_load_pd(ray_centers_matrix2.data() + 16 + i * 4);\n\n    __m256d _rdm2_1 = _mm256_load_pd(ray_directions_matrix2.data() + i * 4);\n    __m256d _rdm2_2 = _mm256_load_pd(ray_directions_matrix2.data() + 8 + i * 4);\n    __m256d _rdm2_3 =\n        _mm256_load_pd(ray_directions_matrix2.data() + 16 + i * 4);\n\n    __m256d _res1 = _mm256_mul_pd(_rcm2_3, _rdm2_2);\n    _res1 = _mm256_fmsub_pd(_rcm2_2, _rdm2_3, _res1);\n\n    __m256d _res2 = _mm256_mul_pd(_rcm2_1, _rdm2_3);\n    _res2 = _mm256_fmsub_pd(_rcm2_3, _rdm2_1, _res2);\n\n    __m256d _res3 = _mm256_mul_pd(_rcm2_2, _rdm2_1);\n    _res3 = _mm256_fmsub_pd(_rcm2_1, _rdm2_2, _res3);\n\n    _mm256_store_pd(rcm2_cross_rdm2.data() + i * 4, _res1);\n    _mm256_store_pd(rcm2_cross_rdm2.data() + 8 + i * 4, _res2);\n    _mm256_store_pd(rcm2_cross_rdm2.data() + 16 + i * 4, _res3);\n  }\n#else\n  for (auto i = 0; i < kCorrespondencesNumber; ++i) {\n    rcm2_cross_rdm2.col(i).noalias() =\n        ray_centers_matrix2.col(i).cross(ray_directions_matrix2.col(i));\n  }\n#endif\n\n  points_center1 /= kCorrespondencesNumber;\n  points_center2 /= kCorrespondencesNumber;\n\n  Eigen::Matrix3d Hcross =\n      (ray_directions_matrix2.colwise() - points_center2) *\n      (ray_directions_matrix1.colwise() - points_center1).transpose();\n\n  // SVD decomposition of matrix Hcross to obtain initial rotation\n  Eigen::JacobiSVD<Eigen::Matrix3d> svd(\n      Hcross, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n  Eigen::Matrix3d V = svd.matrixV();\n  Eigen::Matrix3d U = svd.matrixU();\n  rotation_t starting_rotation = V * U.transpose();\n\n  if (starting_rotation.determinant() < 0) {\n    Eigen::Matrix3d V_prime;\n    V_prime.col(0) = V.col(0);\n    V_prime.col(1) = V.col(1);\n    V_prime.col(2) = -V.col(2);\n    starting_rotation.noalias() = V_prime * U.transpose();\n  }\n\n  FindModel(ray_directions_matrix1, ray_directions_matrix2, ray_centers_matrix1,\n            rcm2_cross_rdm2, RotationMatrixToCayley(starting_rotation), output);\n}\n\n}  // namespace gefast\n", "meta": {"hexsha": "831c41dbe52a82a160315e91acbe890f76780d0c", "size": 16215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gefast/solver/generalized_eigensolver.cpp", "max_stars_repo_name": "kirill-ivanov-a/GEFast", "max_stars_repo_head_hexsha": "074369cc79f23290586c4cf1df20552224db4134", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-26T18:15:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T18:15:23.000Z", "max_issues_repo_path": "gefast/solver/generalized_eigensolver.cpp", "max_issues_repo_name": "kirill-ivanov-a/gefast", "max_issues_repo_head_hexsha": "074369cc79f23290586c4cf1df20552224db4134", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-03-24T20:38:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-26T13:34:00.000Z", "max_forks_repo_path": "gefast/solver/generalized_eigensolver.cpp", "max_forks_repo_name": "kirill-ivanov-a/GEFast", "max_forks_repo_head_hexsha": "074369cc79f23290586c4cf1df20552224db4134", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7918660287, "max_line_length": 80, "alphanum_fraction": 0.6618563059, "num_tokens": 5278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.658417500561683, "lm_q2_score": 0.3242353924510608, "lm_q1q2_score": 0.21348225669126383}}
{"text": "#include \"kondo.h\"\n#include \"iostream_util.h\"\n#include <cstdio>\n#include <sstream>\n#include <boost/filesystem.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/json_parser.hpp>\n\nusing boost::property_tree::ptree;\nusing boost::property_tree::read_json;\n//using boost::property_tree::write_json;\n\ntemplate <typename T>\nstd::vector<T> as_vector(ptree const& pt, ptree::key_type const& key)\n{\n    std::vector<T> r;\n    for (auto& item : pt.get_child(key))\n        r.push_back(item.second.get_value<T>());\n    return r;\n}\n\n\nvoid triangular(int argc, char *argv[]) {\n    auto engine = fkpm::mk_engine<cx_flt>();\n    if (engine == nullptr) std::exit(EXIT_FAILURE);\n    if (argc != 2) {\n        cout << \"Usage: \" << argv[0] << \" <base_dir>\\n\";\n        std::exit(EXIT_SUCCESS);\n    }\n    \n    std::string base_dir(argv[1]);\n    auto input_name = base_dir + \"/config.toml\";\n    std::cout << \"using toml file `\" << input_name << \"`!\\n\";\n    toml_ptr g = toml_from_file(input_name);\n    \n    auto m = SimpleModel::mk_triangular(toml_get<int64_t>(g, \"model.w\"), toml_get<int64_t>(g, \"model.h\"));\n    m->J  = toml_get<double>(g, \"model.J\");\n    m->t1 = toml_get(g, \"model.t1\", 0.0);\n    m->t2 = toml_get(g, \"model.t2\", 0.0);\n    m->t3 = toml_get(g, \"model.t3\", 0.0);\n    m->kT_init  = toml_get<double>(g, \"model.kT\");\n    m->kT_decay = toml_get(g, \"model.kT_decay\", 0.0);\n    m->zeeman   = {toml_get(g, \"model.zeeman_x\", 0.0), toml_get(g, \"model.zeeman_y\", 0.0), toml_get(g, \"model.zeeman_z\", 0.0)};\n    m->easy_z   = toml_get(g, \"model.easy_z\", 0.0);\n    m->s1       = toml_get(g, \"model.s1\", 0.0);\n    m->s2       = toml_get(g, \"model.s2\", 0.0);\n    m->s3       = toml_get(g, \"model.s3\", 0.0);\n    \n    std::string json_name;\n    std::cout << \"Input dumpfile name:\" << std::endl;\n    std::cin >> json_name;\n    std::cout << json_name << std::endl;\n    json_name = base_dir + \"/dump/\" + json_name;\n    std::ifstream json_file(json_name);\n    if (!json_file.is_open()) {\n        cerr << \"Unable to open file `\" << json_name << \"`!\\n\";\n        std::exit(EXIT_FAILURE);\n    }\n    cout << \"Using json file `\" << json_name << \"`!\\n\";\n    ptree pt_json;        // used for reading the json file\n    std::string json_eachline, json_contents;\n    while (std::getline(json_file, json_eachline)) {\n        json_contents += json_eachline;\n    }\n    std::istringstream is (json_contents);\n    read_json (is, pt_json);\n    auto time    = pt_json.get<int>    (\"time\");\n    auto action  = pt_json.get<double> (\"action\");\n    auto filling = pt_json.get<double> (\"filling\");\n    auto mu      = pt_json.get<double> (\"mu\");\n    auto spin    = as_vector<double>(pt_json, \"spin\");\n    \n    std::cout << \"lattice: \" << toml_get<std::string>(g, \"model.lattice\") << std::endl;\n    std::cout << \"time:    \" << time << std::endl;\n    std::cout << \"action:  \" << action << std::endl;\n    std::cout << \"filling: \" << filling << std::endl;\n    std::cout << \"mu:      \" << mu << std::endl;\n    std::cout << \"J:       \" << m->J << std::endl;\n    std::cout << \"t:       \" << m->t1 << std::endl;\n    std::cout << \"kT:      \" << m->kT() << std::endl;\n    \n    assert(spin.size() == m->n_sites * 3);              // build spin configuration from dump file\n    for (int i = 0; i < m->n_sites; i++) {\n        m->spin[i] = vec3(spin[3*i],spin[3*i+1],spin[3*i+2]);\n    }\n    m->set_hamiltonian(m->spin);\n    \n    int purpose, M, Mq, use_correlated, n_colors, seed;\n    std::cout << \"Inut 0/1/2 for calculating sigma_xx/sigma_xy/both: \" << std::endl;\n    std::cin >> purpose;\n    fkpm::EnergyScale es;\n    es = engine->energy_scale(m->H, 0.1);\n    std::cout << \"energyscale: [\" << es.lo << \", \" << es.hi << \"]\" << std::endl;\n    std::cout << \"Input M:\" << std::endl;\n    std::cin >> M;\n    std::cout << M << std::endl;\n    std::cout << \"Input Mq:\" << std::endl;\n    std::cin >> Mq;\n    std::cout << Mq << std::endl;\n    std::cout << \"Input 0/1 for using uncorrelated/correlated random numbers:\" << std::endl;\n    std::cin >> use_correlated;\n    std::cout << use_correlated << std::endl;\n    std::cout << \"Input n_colors:\" << std::endl;\n    std::cin >> n_colors;\n    std::cout << n_colors << std::endl;\n    std::cout << \"Input seed:\" << std::endl;\n    std::cin >> seed;\n    std::cout << seed << std::endl;\n    \n    fkpm::RNG rng(seed);\n    if (use_correlated) {\n        engine->set_R_correlated(m->groups(n_colors), rng);\n    } else {\n        engine->set_R_uncorrelated(m->H.n_rows, 2*n_colors, rng);\n    }\n    \n    auto kernel = fkpm::jackson_kernel(M);\n    engine->set_H(m->H, es);\n    \n    auto jx = m->electric_current_operator(m->spin, {1,0,0});\n    auto jy = m->electric_current_operator(m->spin, {0,1,0});\n    \n    json_file.close();\n    \n    auto mu_dos = engine->moments(M);\n    auto gamma = fkpm::moment_transform(mu_dos, Mq);\n    fkpm::Vec<double> mu_list, rho;\n    fkpm::density_function(gamma, es, mu_list, rho);\n    for (int i = 0; i < rho.size(); i++) {\n        rho[i]/=m->n_sites;\n    }\n    \n    std::cout << \"calculating moments2... \" << std::flush;\n    fkpm::timer[0].reset();\n    Vec<Vec<fkpm::cx_double>> mu_xx, mu_xy;\n    if (purpose == 0) {\n        mu_xx = engine->moments2_v1(M, jx, jx, 10, 16);\n        mu_xy = mu_xx; // invalid\n    } else if (purpose == 1){\n        mu_xy = engine->moments2_v1(M, jx, jy, 10, 16);\n        mu_xx = mu_xy; // invalid\n    } else {\n        mu_xx = engine->moments2_v1(M, jx, jx, 10, 16);\n        mu_xy = engine->moments2_v1(M, jx, jy, 10, 16);\n    }\n    cout << \" done. \" << fkpm::timer[0].measure() << \"s.\\n\";\n    \n    cout << \"calculating dc conductivities... \" << std::flush;\n    std::ofstream fout2(\"full_time\"+std::to_string(time)+\"_M\"+std::to_string(M)+\"_corr\"+std::to_string(use_correlated)+\n                        \"_color\"+std::to_string(n_colors)+\"_seed\"+std::to_string(seed)+\".dat\", std::ios::out);\n    fout2 << std::scientific << std::right;\n    fout2 << std::setw(20) << \"#(1)\" << std::setw(20) << \"(2)\" << std::setw(20) << \"(3)\"\n          << std::setw(20) << \"(4)\" << std::setw(20) << \"(5)\" << std::setw(20) << \"(6)\" << std::endl;\n    fout2 << std::setw(20) << \"M\" << std::setw(20) << \"kT\" << std::setw(20) << \"mu\"\n          << std::setw(20) << \"rho\" << std::setw(20) << \"sigma_xx\" << std::setw(20) << \"sigma_xy\" << std::endl;\n    int interval = std::max(Mq/400,5);\n    for (int i = 0; i < Mq; i+=interval) {\n        auto cmn = electrical_conductivity_coefficients(M, Mq, m->kT(), mu_list[i], 0.0, es, kernel);\n        auto sigma_xx = std::real(fkpm::moment_product(cmn, mu_xx));\n        auto sigma_xy = std::real(fkpm::moment_product(cmn, mu_xy));\n        fout2 << std::setw(20) << M << std::setw(20) << m->kT() << std::setw(20) << mu_list[i]\n              << std::setw(20) << rho[i] << std::setw(20) << sigma_xx << std::setw(20) << sigma_xy << std::endl;\n    }\n    fout2.close();\n    cout << \" done. \" << fkpm::timer[0].measure() << \"s.\\n\";\n    \n    std::ifstream fin0(\"result_time\"+std::to_string(time)+\".dat\");\n    if (! fin0.good()) {\n        fin0.close();\n        std::ofstream fout3(\"result_time\"+std::to_string(time)+\".dat\", std::ios::out | std::ios::app );\n        fout3 << std::setw(20) << \"#(1)\" << std::setw(20) << \"(2)\" << std::setw(20) << \"(3)\"\n              << std::setw(20) << \"(4)\" << std::setw(20) << \"(5)\" << std::setw(20) << \"(6)\"\n              << std::setw(20) << \"(7)\" << std::setw(20) << \"(8)\" << std::endl;\n        fout3 << std::setw(20) << \"M\" << std::setw(20) << \"correlated\" << std::setw(20) << \"colors\"\n              << std::setw(20) << \"seed\" << std::setw(20) << \"F\" << std::setw(20) << \"mu\"\n              << std::setw(20) << \"sigma_xx\" << std::setw(20) << \"sigma_xy\" << std::endl;\n        fout3.close();\n    }\n    std::ofstream fout3(\"result_time\"+std::to_string(time)+\".dat\", std::ios::out | std::ios::app );\n    fout3 << std::scientific << std::right;\n    auto cmn       = electrical_conductivity_coefficients(M, Mq, m->kT(), mu, 0.0, es, kernel);\n\n    fout3 << std::setw(20) << M << std::setw(20) << use_correlated << std::setw(20) << n_colors\n          << std::setw(20) << seed\n          << std::setw(20) << fkpm::electronic_energy(gamma, es, m->kT(), filling, mu)/m->n_sites\n          << std::setw(20) << mu\n          << std::setw(20) << std::real(fkpm::moment_product(cmn, mu_xx))\n          << std::setw(20) << std::real(fkpm::moment_product(cmn, mu_xy))\n          << std::endl;\n    fout3.close();\n    std::cout << std::endl;\n    std::remove(\"dump_device0.dat\");\n    std::remove(\"dump_device1.dat\");\n}\n\n\n\nint main(int argc, char *argv[]) {\n    triangular(argc, argv);\n}\n", "meta": {"hexsha": "9d582306b0ab3927f6330d737e6ab91100565b5c", "size": 8546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/extra/conductivity.cpp", "max_stars_repo_name": "wztzjhn/Kondo", "max_stars_repo_head_hexsha": "aced2a7c9ec7be07f4de26fdf72d24bbbb82a005", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-12T01:22:45.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-12T03:20:05.000Z", "max_issues_repo_path": "src/extra/conductivity.cpp", "max_issues_repo_name": "wztzjhn/Kondo", "max_issues_repo_head_hexsha": "aced2a7c9ec7be07f4de26fdf72d24bbbb82a005", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/extra/conductivity.cpp", "max_forks_repo_name": "wztzjhn/Kondo", "max_forks_repo_head_hexsha": "aced2a7c9ec7be07f4de26fdf72d24bbbb82a005", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-03-12T01:22:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-12T02:47:18.000Z", "avg_line_length": 42.5174129353, "max_line_length": 127, "alphanum_fraction": 0.5483267026, "num_tokens": 2803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604274, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.21342241572092183}}
{"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-2017.\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: Timo Sachsenberg $\n// $Authors: Clemens Groepl, Chris Bielow $\n// --------------------------------------------------------------------------\n\n#include <boost/math/distributions/cauchy.hpp>\n#include <OpenMS/TRANSFORMATIONS/FEATUREFINDER/IsotopeModel.h>\n#include <OpenMS/MATH/STATISTICS/BasicStatistics.h>\n#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>\n\nnamespace OpenMS\n{\n  IsotopeModel::IsotopeModel() :\n    InterpolationModel(),\n    charge_(0),\n    monoisotopic_mz_(0.0)\n  {\n    setName(getProductName());\n\n    defaults_.setValue(\"averagines:C\", 0.04443989f, \"Number of C atoms per Dalton of mass.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"averagines:H\", 0.06981572f, \"Number of H atoms per Dalton of mass.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"averagines:N\", 0.01221773f, \"Number of N atoms per Dalton of mass.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"averagines:O\", 0.01329399f, \"Number of O atoms per Dalton of mass.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"averagines:S\", 0.00037525f, \"Number of S atoms per Dalton of mass.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"isotope:trim_right_cutoff\", 0.001, \"Cutoff in averagine distribution, trailing isotopes below this relative intensity are not considered.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"isotope:maximum\", 100, \"Maximum isotopic rank to be considered.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"isotope:distance\", 1.000495, \"Distance between consecutive isotopic peaks.\", ListUtils::create<String>(\"advanced\"));\n\n\n    defaults_.setValue(\"isotope:mode:mode\", \"Gaussian\", \"Peak Shape used around each isotope peak.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValidStrings(\"isotope:mode:mode\", ListUtils::create<String>(\"Gaussian,Lorentzian\"));\n    defaults_.setValue(\"isotope:mode:LorentzFWHM\", 0.3, \"Full width of the Lorentzian (Cauchy) function applied to the averagine isotopic pattern to simulate the inaccuracy of the mass spectrometer.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"isotope:mode:GaussianSD\", 0.1, \"Standard deviation of Gaussian applied to the averagine isotopic pattern to simulate the inaccuracy of the mass spectrometer.\", ListUtils::create<String>(\"advanced\"));\n\n\n    defaults_.setValue(\"charge\", 1, \"Charge state of the model.\", ListUtils::create<String>(\"advanced\"));\n    defaults_.setValue(\"statistics:mean\", 0.0, \"Centroid m/z (as opposed to monoisotopic m/z).\", ListUtils::create<String>(\"advanced\"));\n\n    defaultsToParam_();\n  }\n\n  IsotopeModel::IsotopeModel(const IsotopeModel & source) :\n    InterpolationModel(source)\n  {\n    setParameters(source.getParameters());\n    updateMembers_();\n  }\n\n  IsotopeModel::~IsotopeModel()\n  {\n  }\n\n  IsotopeModel & IsotopeModel::operator=(const IsotopeModel & source)\n  {\n    if (&source == this)\n      return *this;\n\n    InterpolationModel::operator=(source);\n    setParameters(source.getParameters());\n    updateMembers_();\n\n    return *this;\n  }\n\n  EmpiricalFormula IsotopeModel::getFormula()\n  {\n    CoordinateType mass = mean_ * charge_;\n\n    Int C_num = Int(0.5 + mass * averagine_[C]);\n    Int N_num = Int(0.5 + mass * averagine_[N]);\n    Int O_num = Int(0.5 + mass * averagine_[O]);\n    Int H_num = Int(0.5 + mass * averagine_[H]);\n    Int S_num = Int(0.5 + mass * averagine_[S]);\n\n    String form;\n    if (C_num)\n      form.append(\"C\").append(String(C_num));\n    if (H_num)\n      form.append(\"H\").append(String(H_num));\n    if (N_num)\n      form.append(\"N\").append(String(N_num));\n    if (O_num)\n      form.append(\"O\").append(String(O_num));\n    if (S_num)\n      form.append(\"S\").append(String(S_num));\n\n    return EmpiricalFormula(form);\n  }\n\n  const IsotopeDistribution & IsotopeModel::getIsotopeDistribution() const\n  {\n    return isotope_distribution_;\n  }\n\n  void IsotopeModel::setSamples(const EmpiricalFormula & formula)\n  {\n    typedef std::vector<double> ContainerType;\n    ContainerType isotopes_exact;\n\n    isotope_distribution_ = formula.getIsotopeDistribution(max_isotope_);\n\n    isotope_distribution_.trimRight(trim_right_cutoff_);\n    isotope_distribution_.renormalize();\n\n    // compute the average mass (-offset)\n    CoordinateType isotopes_mean = 0;\n    {\n      Int cnt = 0;\n      for (IsotopeDistribution::iterator iter = isotope_distribution_.begin();\n           iter != isotope_distribution_.end(); ++iter, ++cnt)\n      {\n        isotopes_exact.push_back(iter->second);\n        isotopes_mean += iter->second * cnt;\n      }\n      isotopes_mean *= isotope_distance_ / charge_;\n    }\n    // (Need not divide by sum of probabilities, which is 1.)\n\n    ///\n    // \"stretch\" the averagine isotope distribution (so we can add datapoints between isotope peaks)\n    ///\n    size_t isotopes_exact_size = isotopes_exact.size();\n    isotopes_exact.resize(size_t((isotopes_exact_size - 1) * isotope_distance_ / interpolation_step_ + 1.6)); // round up a bit more\n\n    for (Size i = isotopes_exact_size - 1; i; --i)\n    {\n      // we don't need to move the 0-th entry\n      isotopes_exact[size_t(CoordinateType(i) * isotope_distance_ / interpolation_step_ / charge_ + 0.5)]\n        =   isotopes_exact[i];\n      isotopes_exact[i] = 0;\n    }\n\n    ////\n    // compute the Gaussian/Cauchy distribution (to be added for widening the averagine isotope distribution)\n    ////\n    ContainerType peak_shape_values_y;\n    // fill a container with CoordinateType points (x values)\n    CoordinateType peak_width = 0.0;\n    if (param_.getValue(\"isotope:mode:mode\") == \"Gaussian\")\n    {\n      // Actual width for values in the smooth table for normal distribution\n      peak_width = isotope_stdev_ * 4.0;  // MAGIC alert, num stdev for smooth table for normal distribution\n      ContainerType peak_shape_values_x;\n      for (double coord = -peak_width; coord <= peak_width;\n           coord += interpolation_step_)\n      {\n        peak_shape_values_x.push_back(coord);\n      }\n      // compute normal approximation at these CoordinateType points (y values)\n      Math::BasicStatistics<> normal_widening_model;\n      normal_widening_model.setSum(1);\n      normal_widening_model.setMean(0);\n      normal_widening_model.setVariance(isotope_stdev_ * isotope_stdev_);\n      normal_widening_model.normalApproximation(peak_shape_values_y, peak_shape_values_x);\n    }\n    else if (param_.getValue(\"isotope:mode:mode\") == \"Lorentzian\")\n    {\n      peak_width = isotope_lorentz_fwhm_ * 8.0; // MAGIC alert: Lorentzian has infinite support, but we need to stop sampling at some point: 8*FWHM\n      for (double coord = -peak_width; coord <= peak_width;\n           coord += interpolation_step_)\n      {\n        boost::math::cauchy_distribution<double> cauchy(0., isotope_lorentz_fwhm_ / 2.0);\n        double x = boost::math::pdf(cauchy, coord);\n        peak_shape_values_y.push_back(x); //cauchy is using HWHM not FWHM\n      }\n    }\n\n    ///\n    // fold the Gaussian/Lorentzian at each averagine peak, i.e. fill linear interpolation\n    ///\n    const ContainerType & left = isotopes_exact;\n    const ContainerType & right = peak_shape_values_y;\n    ContainerType & result = interpolation_.getData();\n    result.clear();\n\n    SignedSize r_max = std::min(SignedSize(left.size() + right.size() - 1),\n                                SignedSize(2 * peak_width / interpolation_step_ * max_isotope_ + 1));\n    result.resize(r_max, 0);\n\n    // we loop backwards because then the small products tend to come first\n    // (for better numerics)\n    for (SignedSize i = left.size() - 1; i >= 0; --i)\n    {\n      if (left[i] == 0)\n        continue;\n      for (SignedSize j = std::min(r_max - i, SignedSize(right.size())) - 1; j >= 0; --j)\n      {\n        result[i + j] += left[i] * right[j];\n      }\n    }\n\n    monoisotopic_mz_ = mean_ - isotopes_mean;\n    interpolation_.setMapping(interpolation_step_, peak_width / interpolation_step_, monoisotopic_mz_);\n\n    //std::cerr << \"mono now: \" << monoisotopic_mz_ << \" mono easy: \" << formula.getMonoWeight()/formula.getCharge() << \"\\n\";\n\n    // scale data so that integral over distribution equals one\n    // multiply sum by interpolation_step_ -> rectangular approximation of integral\n    IntensityType factor = scaling_ / (interpolation_step_ * std::accumulate(result.begin(), result.end(), IntensityType(0)));\n    for (ContainerType::iterator iter = result.begin(); iter != result.end(); ++iter)\n    {\n      *iter *= factor;\n    }\n  }\n\n  void IsotopeModel::setOffset(CoordinateType offset)\n  {\n    double diff = offset - getInterpolation().getOffset();\n    mean_ += diff;\n    monoisotopic_mz_ += diff;\n\n    InterpolationModel::setOffset(offset);\n\n    param_.setValue(\"statistics:mean\", mean_);\n  }\n\n  IsotopeModel::CoordinateType IsotopeModel::getOffset()\n  {\n    return getInterpolation().getOffset();\n  }\n\n  UInt IsotopeModel::getCharge()\n  {\n    return charge_;\n  }\n\n  IsotopeModel::CoordinateType IsotopeModel::getCenter() const\n  {\n    return monoisotopic_mz_;\n  }\n\n  void IsotopeModel::updateMembers_()\n  {\n    InterpolationModel::updateMembers_();\n\n    charge_ = param_.getValue(\"charge\");\n    isotope_stdev_ = param_.getValue(\"isotope:mode:GaussianSD\");\n    isotope_lorentz_fwhm_ = param_.getValue(\"isotope:mode:LorentzFWHM\");\n    mean_ = param_.getValue(\"statistics:mean\");\n    max_isotope_ = param_.getValue(\"isotope:maximum\");\n    trim_right_cutoff_ = param_.getValue(\"isotope:trim_right_cutoff\");\n    isotope_distance_ = param_.getValue(\"isotope:distance\");\n\n    averagine_[C] = param_.getValue(\"averagines:C\");\n    averagine_[H] = param_.getValue(\"averagines:H\");\n    averagine_[N] = param_.getValue(\"averagines:N\");\n    averagine_[O] = param_.getValue(\"averagines:O\");\n    averagine_[S] = param_.getValue(\"averagines:S\");\n\n  }\n\n}\n", "meta": {"hexsha": "606f2ce030229287f95f9202fe9ff35f842c84f6", "size": 11809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/openms/source/TRANSFORMATIONS/FEATUREFINDER/IsotopeModel.cpp", "max_stars_repo_name": "raghav17083/OpenMS", "max_stars_repo_head_hexsha": "ddcdd3068a93a7c415675c39bac43d796a845f1d", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_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/IsotopeModel.cpp", "max_issues_repo_name": "raghav17083/OpenMS", "max_issues_repo_head_hexsha": "ddcdd3068a93a7c415675c39bac43d796a845f1d", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/openms/source/TRANSFORMATIONS/FEATUREFINDER/IsotopeModel.cpp", "max_forks_repo_name": "raghav17083/OpenMS", "max_forks_repo_head_hexsha": "ddcdd3068a93a7c415675c39bac43d796a845f1d", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0", "Zlib"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8758865248, "max_line_length": 240, "alphanum_fraction": 0.6759251418, "num_tokens": 2889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.36658972248186, "lm_q1q2_score": 0.21309973867714632}}
{"text": "#ifndef COSMO_PROFILES\n#define COSMO_PROFILES\n\n#include \"COSMO_SAC/util.hpp\"\n#include <Eigen/Dense>\n#include <map>\n#include <limits>\n#include <iterator>\n#include <algorithm>\n#include <cctype>\n#include <functional>\n#include \"nlohmann/json.hpp\"\n\nnamespace COSMOSAC {\n\n/**\nA single sigma profile.  In this data structure (for consistency with the 2005 Virginia Tech\ndatabase of COSMO-SAC parameters), the first column is the electron density in [e/A^2], and the second column\nis the probability of finding a segment with this electron density, multiplied by the segment area, in A^2\n*/\nclass SigmaProfile {\npublic:\n    Eigen::ArrayXd m_sigma, m_psigmaA;\n    /// Default constructor\n    SigmaProfile() {};\n    /// Copy-by-reference constructor\n    SigmaProfile(const Eigen::ArrayXd &sigma, const Eigen::ArrayXd &psigmaA) : m_sigma(sigma), m_psigmaA(psigmaA) {};\n    /// Move constructor\n    SigmaProfile(Eigen::ArrayXd &&sigma, Eigen::ArrayXd &&psigmaA) : m_sigma(sigma), m_psigmaA(psigmaA) {};\n    const Eigen::ArrayXd &psigmaA() const { return m_psigmaA; }\n    const Eigen::ArrayXd &sigma() const { return m_sigma; }\n    const Eigen::ArrayXd psigma(double A_i) const { return m_psigmaA/A_i; }\n\n};\n\nstruct SigmaProfileSet {\n    SigmaProfile nhb, ///< The profile for the non-hydrogen-bonding segments\n        oh, ///< The profile for the OH-bonding segments\n        ot; ///< The profile for the \"other\" segments\n};\n\n/// The sigma profiles (and some more metadata) associated with the fluid\nstruct FluidProfiles {\n    enum class dispersion_classes{DISP_WATER, DISP_COOH, DISP_NHB, DISP_ONLY_ACCEPTOR, DISP_DONOR_ACCEPTOR};\n    SigmaProfileSet profiles;\n    std::string name;\n    std::size_t VTnumber;\n    double A_COSMO_A2; ///< The surface area of the molecule as calculated by COSMO-SAC, in A^2\n    double V_COSMO_A3; ///< The volume of the molecule as calculated by COSMO-SAC, in A^3\n    dispersion_classes dispersion_flag;\n    double dispersion_eoverkB;\n    nlohmann::json meta; ///< Any additional metadata, stored in JSON format\n};\n\n///\nclass ProfileDatabase {\nprivate:\n    std::map<std::string, FluidProfiles> datadb;\npublic:\n    FluidProfiles get_profile(const std::string & identifier) const{\n        if (datadb.find(identifier) != datadb.cend()) {\n            return datadb.find(identifier)->second;\n        }\n        else {\n            throw std::invalid_argument(\"Unable to load the profile for the identifier [\" + identifier + \"]\");\n        }\n    }\n    virtual std::string normalize_identifier(const std::string &identifier) const { return identifier; };\n    std::size_t length(const std::string & identifier) {\n        return datadb.size();\n    }\n    void clear() {\n        datadb.clear();\n    }\n    void add_to_db(const std::string & identifier, FluidProfiles &&value) {\n        datadb[identifier] = value;\n    }\n};\n\nstruct VTFluidInfo {\n    int VTIndex;\n    std::string numstring;\n    std::string name;\n    std::string CAS;\n    double V_COSMO_A3;\n};\nvoid to_json(nlohmann::json& j, const VTFluidInfo& p) {\n    j = nlohmann::json{{\"VTIndex\", p.VTIndex}, {\"numstring\", p.numstring}, {\"name\", p.name}, {\"CAS\", p.CAS},  {\"V_COSMO_A3\", p.V_COSMO_A3}};\n}\nvoid from_json(const nlohmann::json& j, VTFluidInfo& p) {\n    j.at(\"VTIndex\").get_to(p.VTIndex);\n    j.at(\"numstring\").get_to(p.numstring);\n    j.at(\"name\").get_to(p.name);\n    j.at(\"CAS\").get_to(p.CAS);\n    j.at(\"V_COSMO_A3\").get_to(p.V_COSMO_A3);\n}\n\n/// The format of the VirginiaTech database of profiles\nclass VirginiaTechProfileDatabase : public ProfileDatabase{\nprivate:\n    \n    std::map<std::string, VTFluidInfo> m_VTdata;\n    const std::string m_dbpath;\npublic:    \n    VirginiaTechProfileDatabase(const std::string &tab_delimited_summary, const std::string &dbpath) : m_dbpath(dbpath) {\n        // First, read in the file of summary information\n        auto lines = str_split(get_file_contents(tab_delimited_summary), \"\\n\");\n        if (lines.size() == 1){\n            lines = str_split(get_file_contents(tab_delimited_summary), \"\\r\");\n        }\n        if (lines.size() == 1){\n            throw std::invalid_argument(\"Unable to match the line endings in file \" + tab_delimited_summary);\n        }\n        // Iterate over the lines, storing an entry for each one\n        for (auto &&line : lines) {\n            VTFluidInfo fluid;\n            if (line.empty()) { continue; }\n            auto elements = str_split(strstrip(line), \"\\t\");\n            if (elements.size() < 6) {\n                throw std::invalid_argument(\"Need at least 6 entries in line\");\n            }\n            if (elements[0] == \"Index No.\") {\n                continue;\n            }\n            fluid.VTIndex = mystrtoi(elements[0]);\n            // Index 1 is a chemical formula, but non-standard form\n            fluid.name = elements[2];\n            fluid.CAS = elements[3];\n            fluid.V_COSMO_A3 = mystrtod(elements[5]);\n            char num[5];\n            snprintf(num, sizeof(num), \"%04d\", static_cast<int>(fluid.VTIndex));\n            fluid.numstring = num;\n            if (m_VTdata.find(fluid.numstring) != m_VTdata.end()) {\n                throw std::invalid_argument(\"Cannot have duplicate key: \"+ fluid.numstring);\n            }\n            else{\n                m_VTdata[fluid.numstring] = fluid;\n            }\n            \n        }\n    }\n    std::string normalize_identifier(const std::string &identifier) const override {\n        // The key is in the database, return it\n        if (m_VTdata.find(identifier) != m_VTdata.end()) {\n            return identifier;\n        }\n        for (auto &el : m_VTdata) {\n            auto &fluid = el.second;\n            if (fluid.name == identifier)\n            { \n                // Construct the fluid identifier from the identifier that is provided\n                char num[5];\n                snprintf(num, sizeof(num), \"%04d\", static_cast<int>(fluid.VTIndex));\n                return num;\n            }\n            if (fluid.CAS == identifier)\n            { \n                // Construct the fluid identifier from the identifier that is provided\n                char num[5];\n                snprintf(num, sizeof(num), \"%04d\", static_cast<int>(fluid.VTIndex));\n                return num;\n            }\n        }\n        throw std::invalid_argument(\"Unable to match identifier in secondary lookup\");\n    }\n    void add_profile(std::string identifier) {\n        auto info = m_VTdata[identifier];\n        // Now we load the sigma profile(s) from the file\n        auto lines = str_split(get_file_contents(m_dbpath + \"/VT2005-\" + info.numstring + \"-PROF.txt\"));\n        std::vector<double> sigma, psigmaA;\n        FluidProfiles fluid;\n        for (auto &&line : lines) {\n            if (line.size() > 10) {\n                auto _sigma = mystrtod(line.substr(0, 25));\n                auto _psigmaA = mystrtod(line.substr(25, 25));\n                sigma.push_back(_sigma);\n                psigmaA.push_back(_psigmaA);\n            }\n        }\n        fluid.name = info.name;\n        fluid.VTnumber = info.VTIndex;\n        fluid.V_COSMO_A3 = info.V_COSMO_A3;\n        if (sigma.size() == 51 && psigmaA.size() == 51) {\n            fluid.profiles.nhb = SigmaProfile(Eigen::Map<Eigen::ArrayXd>(&(sigma[0]), sigma.size()),\n                Eigen::Map<Eigen::ArrayXd>(&(psigmaA[0]), psigmaA.size()));\n            fluid.A_COSMO_A2 = fluid.profiles.nhb.psigmaA().sum();\n        }\n        else {\n            throw std::invalid_argument(\"Don't support 2 & 3 sigma profiles yet\");\n        }\n        add_to_db(info.numstring, std::move(fluid));\n    }\n    std::string to_JSON(){\n        auto nspaces = 2;\n        nlohmann::json j = m_VTdata;\n        return j.dump(nspaces);\n    }\n};\n\nstruct DelawareFluidInfo {\n    std::size_t DelIndex;\n    std::string CAS;\n    std::string formula;\n    std::string name;\n    std::string SMILES;\n    std::string InChIString; ///< Standard InChI string\n    std::string InChIKey; ///< Standard InChI key\n    double V_COSMO_A3;\n    nlohmann::json meta;\n};\nvoid to_json(nlohmann::json& j, const DelawareFluidInfo& p) {\n    j = nlohmann::json{\n        {\"DelIndex\", p.DelIndex}, {\"CAS\", p.CAS}, {\"formula\", p.formula},  {\"name\", p.name},\n        {\"SMILES\", p.SMILES}, {\"InChIString\", p.InChIString}, {\"InChIKey\", p.InChIKey},  {\"V_COSMO_A3\", p.V_COSMO_A3}\n};\n}\nvoid from_json(const nlohmann::json& j, DelawareFluidInfo& p) {\n    j.at(\"DelIndex\").get_to(p.DelIndex);\n    j.at(\"CAS\").get_to(p.CAS);\n    j.at(\"formula\").get_to(p.formula);\n    j.at(\"name\").get_to(p.name);\n    j.at(\"SMILES\").get_to(p.SMILES);\n    j.at(\"InChIString\").get_to(p.InChIString);\n    j.at(\"InChIKey\").get_to(p.InChIKey);\n    j.at(\"V_COSMO_A3\").get_to(p.V_COSMO_A3);\n    j.at(\"name\").get_to(p.name);\n}\n    \n/// The format of the Delaware database of profiles\nclass DelawareProfileDatabase : public ProfileDatabase {\nprivate:\n    \n    std::map<std::string, DelawareFluidInfo> m_Deldata;\n    const std::string m_dbpath;\npublic:\n    DelawareProfileDatabase(const std::string &space_delimited_summary, const std::string &dbpath) : m_dbpath(dbpath) {\n        // First, read in the file of summary information\n        auto lines = str_split(get_file_contents(space_delimited_summary), \"\\n\");\n        // Iterate over the lines, storing an entry for each one\n        for (auto &&line : lines) {\n            DelawareFluidInfo fluid;\n            if (line.empty()) { continue; }\n            auto elements = str_split(strrstrip(line), \" \");\n            if (elements[0] == \"ID\") {\n                continue;\n            }\n            fluid.DelIndex = mystrtoi(elements[0]);\n            fluid.formula = elements[1];\n            fluid.CAS = elements[2];\n            fluid.name = elements[3];\n            fluid.SMILES = elements[4];\n            fluid.InChIString = elements[5];\n            fluid.InChIKey = elements[6];\n            m_Deldata[fluid.InChIKey] = fluid;\n        }\n    }\n    std::string normalize_identifier(const std::string &identifier) const override {\n        // The key is in the database, return it\n        if (m_Deldata.find(identifier) != m_Deldata.end()) {\n            return identifier;\n        }\n        for (auto &el : m_Deldata) {\n            auto &fluid = el.second;\n            if (fluid.name == identifier)\n            {\n                return fluid.InChIKey;\n            }\n            if (fluid.CAS == identifier)\n            {\n                return fluid.InChIKey;\n            }\n        }\n        throw std::invalid_argument(\"Unable to match identifier in secondary lookup\");\n    }\n    void add_profile(std::string identifier) {\n        auto info = m_Deldata[identifier];\n        // Now we load the sigma profile(s) from the file\n        auto lines = str_split(get_file_contents(m_dbpath + \"/\" + info.InChIKey + \".sigma\"));\n\n        std::vector<double> _sigma, _psigmaA;\n        FluidProfiles fluid;\n        std::string meta;\n        for (auto &&line : lines) {\n            if (line.substr(0,8) == \"# Name: \"){ std::string check_name = line.substr(8,line.size()-8); continue;}\n            if (line.substr(0,8) == \"# CASn: \") { std::string check_CAS = line.substr(8, line.size() - 8); continue; }\n            if (line.substr(0, 8) == \"# meta: \") { meta = line.substr(8, line.size() - 8); continue; }\n            if (line[0] == '#'){ continue; }\n            auto v = str_split(strrstrip(line), \" \");\n            if (v.empty() || (v.size() ==1 && v[0].empty())){ continue; }\n            _sigma.push_back(mystrtod(v[0]));\n            _psigmaA.push_back(mystrtod(v[1]));\n        }\n        Eigen::Map<Eigen::ArrayXd> sigma(&(_sigma[0]), _sigma.size());\n        Eigen::Map<Eigen::ArrayXd> psigmaA(&(_psigmaA[0]), _psigmaA.size());\n        fluid.name = info.name;\n        \n        fluid.VTnumber = info.DelIndex;\n        if (sigma.size() == 51 && psigmaA.size() == 51) {\n            fluid.profiles.nhb = SigmaProfile(sigma, psigmaA);\n            fluid.A_COSMO_A2 = fluid.profiles.nhb.psigmaA().sum();\n        }\n        else if (sigma.size() == 51*3 && psigmaA.size() == 51*3){\n            fluid.profiles.nhb = SigmaProfile(sigma.segment(0*51, 51), psigmaA.segment(0*51, 51));\n            fluid.profiles.oh =  SigmaProfile(sigma.segment(1*51, 51), psigmaA.segment(1*51, 51));\n            fluid.profiles.ot =  SigmaProfile(sigma.segment(2*51, 51), psigmaA.segment(2*51, 51));\n            double check_Area2 = fluid.profiles.nhb.psigmaA().sum() + fluid.profiles.oh.psigmaA().sum() + fluid.profiles.ot.psigmaA().sum();\n            fluid.A_COSMO_A2 = check_Area2;\n        }\n        else{\n            throw std::invalid_argument(\"Length of sigma profile [\"+std::to_string(sigma.size())+\"] is neither 51 nor 51*3\");\n        }\n        fluid.meta = nlohmann::json::parse(meta);\n        fluid.V_COSMO_A3 = fluid.meta[\"volume [A^3]\"];\n        std::string flag = fluid.meta[\"disp. flag\"];\n        if (flag == \"COOH\") {\n            fluid.dispersion_flag = FluidProfiles::dispersion_classes::DISP_COOH;\n        }\n        else if (flag == \"H2O\") {\n            fluid.dispersion_flag = FluidProfiles::dispersion_classes::DISP_WATER;\n        }\n        else if (flag == \"NHB\") {\n            fluid.dispersion_flag = FluidProfiles::dispersion_classes::DISP_NHB;\n        }\n        else if (flag == \"HB-ACCEPTOR\") {\n            fluid.dispersion_flag = FluidProfiles::dispersion_classes::DISP_ONLY_ACCEPTOR;\n        }\n        else if (flag == \"HB-DONOR-ACCEPTOR\") {\n            fluid.dispersion_flag = FluidProfiles::dispersion_classes::DISP_DONOR_ACCEPTOR;\n        }\n        else {\n            throw std::invalid_argument(\"Unable to match dispersion flag: \\\"\"+flag+\"\\\"\");\n        }\n        if (fluid.meta[\"disp. e/kB [K]\"].is_null()){\n            // The null from JSON is mapped to a NaN of C++\n            fluid.dispersion_eoverkB = std::numeric_limits<double>::quiet_NaN();\n        }\n        else {\n            fluid.dispersion_eoverkB = fluid.meta[\"disp. e/kB [K]\"];\n        }\n        add_to_db(info.InChIKey, std::move(fluid));\n    }\n    std::string to_JSON(){\n        auto nspaces = 2;\n        nlohmann::json j = m_Deldata;\n        return j.dump(nspaces);\n    }\n};\n\n} /* namespace COSMOSAC */\n\n#endif\n", "meta": {"hexsha": "1bbfe84c212ef21c6e6b15decc3abd33351176d4", "size": 14070, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/COSMO_SAC/profile_db.hpp", "max_stars_repo_name": "kypss93034/COSMOSAC", "max_stars_repo_head_hexsha": "baba5063ca3495e59d21ce7e03885fe31c0d0018", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-09-30T21:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-18T15:28:36.000Z", "max_issues_repo_path": "include/COSMO_SAC/profile_db.hpp", "max_issues_repo_name": "kypss93034/COSMOSAC", "max_issues_repo_head_hexsha": "baba5063ca3495e59d21ce7e03885fe31c0d0018", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2020-06-25T18:28:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T15:51:08.000Z", "max_forks_repo_path": "include/COSMO_SAC/profile_db.hpp", "max_forks_repo_name": "kypss93034/COSMOSAC", "max_forks_repo_head_hexsha": "baba5063ca3495e59d21ce7e03885fe31c0d0018", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2019-09-14T01:23:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T16:45:41.000Z", "avg_line_length": 39.9715909091, "max_line_length": 140, "alphanum_fraction": 0.5958777541, "num_tokens": 3644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.21305412890610081}}
{"text": "// Last update: April 5, 2013\n// This is main.\n// This is MD simulation of an electrolyte confined within planar walls\n// Problem : Compute density profiles of ions trapped within planar walls\n/* Useful studies :\t\n\t\t     1. Role of dielectric contrast\n\t\t     2. Role of valency of ions\n\t\t     3. Role of varying salt concentration\n// To implement:\n\t\t     1. Charged walls\n\t\t     \n*/\n/* lessons learned :\n\t\t     1. do not use exit(1) to exit the program. this leads to memory leaks.\n\n*/\n\n#include <boost/program_options.hpp>\n#include <time.h>\n#include \"utility.h\"\n#include \"interface.h\"\n#include \"particle.h\"\n#include \"vertex.h\"\n#include \"BIN.h\"\n#include \"control.h\"\n#include \"functions.h\"\n#include \"precalculations.h\"\n#include \"thermostat.h\"\n#include \"fmd.h\"\n\n//MPI boundary parameters\nunsigned int lowerBoundIons;\nunsigned int upperBoundIons;\nunsigned int sizFVecIons;\nunsigned int lowerBoundMesh;\nunsigned int upperBoundMesh;\nunsigned int sizFVecMesh;\n\nmpi::environment env;\nmpi::communicator world;\n\nvoid\ncpmd(vector<PARTICLE> &, INTERFACE &, vector<THERMOSTAT> &, vector<THERMOSTAT> &, vector<BIN> &, CONTROL &, CONTROL &);\n// removed particle colloid, fake thermostat and fmdremote\n\nint main(int argc, char *argv[]) {\n\n    // Electrostatic system variables\n    double bx, by, bz;        // lengths of the box\n    double ein;            // permittivity of inside medium\n    double e_left;                // permittivity of leftside medium\n    double e_right;               // permittivity of rightside medium\n    int pz_in;            // positive valency of ions inside\n    int nz_in;            // negative valency of ions inside\n    double salt_conc_in;        // salt concentration outside\t(enter in M)\n    double saltion_diameter_in;    // inside salt ion diameter\t(positive and negative ions assumed to have same diameter at this point)\n    double T, fake_T;            // temperature at which the system of ions is\n\n    // Simulation related variables\n    double fraction_diameter;        // fraction that multiplies the diameter to generate the discretization width for the interface\n    double Q, fake_Q;                // thermostat mass required to generate canonical ensemble\n    unsigned int chain_length_real, chain_length_fake;\n    double bin_width;            // width of the bins used to compute density profiles\n    CONTROL fmdremote, cpmdremote;            // remote control for cpmd\n\n    // Different parts of the system\n    vector<PARTICLE> saltion_in;        // salt ions inside\n    vector<PARTICLE> ion;        // all ions in the system\n    INTERFACE box;            // interface, z planes hard walls; rest periodic boundaries\n\n    // Analysis\n    vector<BIN> bin;            // bins\n\n    // Fake system\n    double fakemass;\n\n    // Get input values from the user\n    options_description desc(\"Usage:\\nrandom_mesh <options>\");\n    desc.add_options()\n            (\"help,h\", \"print usage message\")\n            (\"bx,X\", value<double>(&bx)->default_value(22.848),\n             \"box length in x direction in nanometers\")                    // enter in nanometers\n            (\"by,Y\", value<double>(&by)->default_value(22.848),\n             \"box length in y direction in nanometers\")                    // enter in nanometers\n            (\"bz,Z\", value<double>(&bz)->default_value(3),\n             \"box length in z direction in nanometers\")                    // enter in nanometers\n            (\"epsilon_in,e\", value<double>(&ein)->default_value(80.1), \"dielectric const inside\")\n            (\"epsilon_left,l\", value<double>(&e_left)->default_value(20), \"dielectric const leftside\")\n            (\"epsilon_right,r\", value<double>(&e_right)->default_value(80.1), \"dielectric const rightside\")\n            (\"pz_in,p\", value<int>(&pz_in)->default_value(1), \"positive valency inside\")\n            (\"nz_in,n\", value<int>(&nz_in)->default_value(-1), \"negative valency inside\")\n            (\"salt_conc_in,c\", value<double>(&salt_conc_in)->default_value(0.1), \"salt concentration inside\")\n            (\"saltion_diameter_in,d\", value<double>(&saltion_diameter_in)->default_value(0.714),\n             \"salt ion diameter inside\")        // enter in nanometers\n            (\"fraction_diameter,g\", value<double>(&fraction_diameter)->default_value(1.4),\n             \"for interface discretization width\")\n            (\"thermostat_mass,Q\", value<double>(&Q)->default_value(1.0), \"thermostat mass\")\n            (\"chain_length_real,L\", value<unsigned int>(&chain_length_real)->default_value(5),\n             \"chain length for real system: enter L+1 if you want L thermostats\")\n            (\"fake_temperature,k\", value<double>(&fake_T)->default_value(0.002), \"fake temperature\")\n            (\"fake_thermostat_mass,q\", value<double>(&fake_Q)->default_value(1.0), \"fake thermostat mass\")\n            (\"chain_length_fake,D\", value<unsigned int>(&chain_length_fake)->default_value(5),\n             \"chain length for fake system: enter L+1 if you want L thermostats\")\n            (\"fakemass,f\", value<double>(&fakemass)->default_value(100.0), \"fake mass\")\n            (\"cpmd_fake_mass,M\", value<double>(&cpmdremote.fakemass)->default_value(1.0), \"cpmd fake mass\")\n            (\"bin_width,B\", value<double>(&bin_width)->default_value(0.1), \"bin width\")\n            (\"cpmd_timestep,T\", value<double>(&cpmdremote.timestep)->default_value(0.0005), \"time step used in cpmd\")\n            (\"fmd_steps,s\", value<int>(&fmdremote.steps)->default_value(200), \"steps used in fmd\")\n            (\"cpmd_steps,S\", value<int>(&cpmdremote.steps)->default_value(1000), \"steps used in cpmd\")\n            (\"cpmd_eqm,P\", value<int>(&cpmdremote.hiteqm)->default_value(10), \"production begin (cpmd)\")\n            (\"cpmd_freq,F\", value<int>(&cpmdremote.freq)->default_value(10), \"sample frequency (cpmd)\")\n            (\"cpmd_verify,y\", value<int>(&cpmdremote.verify)->default_value(1000), \"verify (cpmd)\")\n            (\"cpmd_extra_compute,x\", value<int>(&cpmdremote.extra_compute)->default_value(10),\n             \"compute additional (cpmd)\")\n            (\"cpmd_writedensity,w\", value<int>(&cpmdremote.writedensity)->default_value(100), \"write density files\")\n            (\"cpmd_movie_freq,m\", value<int>(&cpmdremote.moviefreq)->default_value(100), \"compute additional (cpmd)\");\n\n    variables_map vm;\n    store(parse_command_line(argc, argv, desc), vm);\n    notify(vm);\n    if (vm.count(\"help\")) {\n        std::cout << desc << \"\\n\";\n        return 0;\n    }\n\n    // Set up the system\n    T = 1;        // set temperature\n    box.ein = ein;\n    box.e_left = e_left;\n    box.e_right = e_right;\n    box.set_up(salt_conc_in, 0, 0, pz_in, 0, 0, bx / unitlength, by / unitlength, bz / unitlength);\n    box.put_saltions_inside(saltion_in, pz_in, nz_in, salt_conc_in, saltion_diameter_in, ion);\n    // box.put_one_saltion_in_center(saltion_in, pz_in, nz_in, saltion_diameter_in, ion);\t\t\t\t\t\t//put one ion in center\n\n    make_bins(bin, box, bin_width);    // set up bins to be used for computing density profiles\n    vector<double> initial_density;\n    bin_ions(ion, box, initial_density, bin);    // bin the ions to get initial density profile\n\n//   box.number_of_vertices = total_gridpoints;\n    box.discretize(saltion_diameter_in / unitlength, fraction_diameter);\n\n    fmdremote.fakemass = fakemass;\n\n    // output to screen the parameters of the problem\n    if (world.rank() == 0) {\n        cout << \"\\nProgram starts\\n\";\n        cout << \"Dielectric constant of water is \" << epsilon_water << endl;\n        cout << \"Reduced units: scalefactor entering in Coloumb interaction is \" << scalefactor << endl;\n        cout << \"Box dimensions x | y | z \" << setw(15) << box.lx << setw(15) << box.ly << setw(15) << box.lz << endl;\n        cout << \"Permittivity inside \" << box.ein << endl;\n        cout << \"Permittivity leftside \" << box.e_left << endl;\n        cout << \"Permittivity rightside \" << box.e_right << endl;\n        cout << \"Contrast strength left \" << 2 * (box.e_left - box.ein) / (box.e_left + box.ein) << endl;\n        cout << \"Contrast strength right \" << 2 * (box.e_right - box.ein) / (box.e_right + box.ein) << endl;\n        cout << \"Positive ion valency inside \" << pz_in << endl;\n        cout << \"Negative ion valency inside \" << nz_in << endl;\n        cout << \"Salt ion diameter inside \" << saltion_diameter_in / unitlength << endl;\n        cout << \"Salt concentration inside \" << salt_conc_in << endl;\n        cout << \"Debye length inside \" << box.inv_kappa_in << endl;\n        cout << \"Mean separation inside \" << box.mean_sep_in << endl;\n        cout << \"Number of salt ions inside \" << saltion_in.size() << endl;\n        cout << \"Temperature \" << T << endl;\n        cout << \"Binning width (uniform) \" << bin[0].width << endl;\n        cout << \"Number of bins \" << bin.size() << endl;\n        cout << \"Number of points discretizing the left and right z planes \" << box.leftplane.size() << setw(10)\n             << box.rightplane.size() << endl;\n    }\n\n    int numOfNodes = world.size();\n    if (world.rank() == 0) {\n#pragma omp parallel default(shared)\n        {\n            if (omp_get_thread_num() == 0) {\n                printf(\"The app comes with MPI and OpenMP (Hybrid) parallelization)\\n\");\n                printf(\"Number of MPI processes used %d\\n\", numOfNodes);\n                printf(\"Number of OpenMP threads per MPI process %d\\n\", omp_get_num_threads());\n                printf(\"Make sure that number of grid points / ions is greater than %d\\n\",\n                       omp_get_num_threads() * numOfNodes);\n            }\n        }\n    }\n\n    // write to files\n\n    // initial configuration\n    if (world.rank() == 0) {\n        ofstream initial_configuration(\"outfiles/initialconfig.dat\");\n        for (unsigned int i = 0; i < ion.size(); i++)\n            initial_configuration << \"ion\" << setw(5) << ion[i].id << setw(15) << \"charge\" << setw(5) << ion[i].q\n                                  << setw(15) << \"position\" << setw(15) << ion[i].posvec << endl;\n        initial_configuration.close();\n\n        // initial density\n        ofstream density_profile(\"outfiles/initial_density_profile.dat\", ios::out);\n        for (unsigned int b = 0; b < initial_density.size(); b++)\n            density_profile << bin[b].lower << setw(15) << initial_density.at(b) << endl;\n        density_profile.close();\n    }\n    // check point\n    double totalions = 0;\n    for (unsigned int b = 0; b < initial_density.size(); b++)\n        totalions += initial_density.at(b) * bin[b].volume;\n    if (world.rank() == 0)\n        cout << \"total ions \" << totalions << \"  should be \" << ion.size() << endl;\n    int totalpions = 0, totalnions = 0;\n    for (unsigned int i = 0; i < ion.size(); i++) {\n        if (ion[i].valency > 0)\n            totalpions += 1;\n        else if (ion[i].valency < 0)\n            totalnions += 1;\n    }\n\n    // some calculations before simulation begins\n    double charge = box.total_charge_inside(ion);\n\n    if (world.rank() == 0) {\n        cout << \"Total positive ions \" << totalpions << endl;\n        cout << \"Total negative ions \" << totalnions << endl;\n        cout << \"Total charge inside\" << charge << endl;\n    }\n    // prepare for cpmd : make real baths\n    vector<THERMOSTAT> real_bath;\n    if (chain_length_real == 1)\n        real_bath.push_back(THERMOSTAT(0, T, 3 * ion.size(), 0.0, 0, 0));\n    else {\n        real_bath.push_back(THERMOSTAT(Q, T, 3 * ion.size(), 0, 0, 0));\n        while (real_bath.size() != chain_length_real - 1)\n            real_bath.push_back(THERMOSTAT(Q / (3 * ion.size()), T, 1, 0, 0, 0));\n        real_bath.push_back(THERMOSTAT(0, T, 3 * ion.size(), 0.0, 0, 0));\n        // final bath is dummy bath (dummy bath always has zero mass)\n    }\n\n    vector<THERMOSTAT> fake_bath;\n    if (chain_length_fake == 1)\n        fake_bath.push_back(THERMOSTAT(0, fake_T, box.leftplane.size(), 0.0, 0, 0));\n    else {\n        fake_bath.push_back(THERMOSTAT(fake_Q, fake_T, box.leftplane.size(), 0, 0, 0));\n        while (fake_bath.size() != chain_length_fake - 1)\n            fake_bath.push_back(THERMOSTAT(fake_Q / box.leftplane.size(), fake_T, 1, 0, 0, 0));\n        fake_bath.push_back(THERMOSTAT(0, fake_T, box.leftplane.size(), 0.0, 0,\n                                       0));            // finally, the coding trick: dummy bath (dummy bath always has zero mass)\n    }\n\n    // Induced charge system\n    // fake positions initialized\n    for (unsigned int i = 0; i < box.leftplane.size(); i++)\n        box.leftplane[i].w = 0.0;\n    double total_ind_charge_left = 0;\n    for (unsigned int i = 0; i < box.leftplane.size(); i++)\n        total_ind_charge_left += box.leftplane[i].w * box.leftplane[i].a;\n\n    for (unsigned int i = 0; i < box.rightplane.size(); i++)\n        box.rightplane[i].w = 0.0;\n    double total_ind_charge_right = 0;\n    for (unsigned int i = 0; i < box.rightplane.size(); i++)\n        total_ind_charge_right += box.rightplane[i].w * box.rightplane[i].a;\n\n    if (world.rank() == 0) {\n        cout << \"total induced left interface\" << total_ind_charge_left << endl;\n        cout << \"total induced right interface\" << total_ind_charge_right << endl;\n    }\n\n    clock_t t;\n    t = clock();\n    precalculate(box); // calculate the Greens function within interface or between interface\n    t = clock() - t;\n    //exact incuded charge density calculation\n    //vector<VERTEX> exact_induced_density_left;\n    //vector<VERTEX> exact_induced_density_right;\n\n    //exact_induced_density_left = box.compute_exact_induced_density(ion,'l');\n    //exact_induced_density_right = box.compute_exact_induced_density(ion,'r');\n    //double total_energy = box.exact_total_energy(exact_induced_density_left, exact_induced_density_right, ion);\n    //cout << \"total energy should be \" << total_energy << endl;\n    if (world.rank() == 0)\n        cout << \"pre_calculation finished,  time taken: \" << ((double) t) / CLOCKS_PER_SEC << \" seconds\" << endl;\n\n    // Fictitious Molecular Dynamics\n\n    t = clock();\n    fmdremote.timestep = 0.0005;\n    fmdremote.verify = 0;\n    fmdremote.anneal = 'y';\n    fmd(ion, box, fmdremote, cpmdremote);\n    t = clock() - t;\n    if (world.rank() == 0)\n        cout << \"fmd calculation finished,  time taken: \" << ((double) t) / CLOCKS_PER_SEC << \" seconds\" << endl;\n/*\n  ofstream induced_density_left (\"outfiles_windows/induced_density_left.dat\");\n  for (unsigned int k = 0; k < box.leftplane.size(); k++)\n    induced_density_left << k+1 <<setw(15) << box.leftplane[k].posvec << setw(15) << \n    sqrt(box.leftplane[k].posvec.x * box.leftplane[k].posvec.x + box.leftplane[k].posvec.y * box.leftplane[k].posvec.y) << setw(15) << \n    box.leftplane[k].w << setw(15) << box.leftplane[k].wmean << setw(15)<< exact_induced_density_left[k].w << endl;\t\t// NOTE plotting also the cartesian coordinates\n  induced_density_left.close();\n  ofstream induced_density_right(\"outfiles_windows/induced_density_right.dat\");\n  for (unsigned int k = 0; k < box.rightplane.size(); k++)\n    induced_density_right << k+1 <<setw(15) << box.rightplane[k].posvec << setw(15) <<\n    sqrt(box.rightplane[k].posvec.x * box.rightplane[k].posvec.x + box.rightplane[k].posvec.y * box.rightplane[k].posvec.y) << setw(15) <<\n    box.rightplane[k].w << setw(15) << box.rightplane[k].wmean << setw(15)<< exact_induced_density_right[k].w << endl;\t\t// NOTE plotting also the cartesian coordinates\n  induced_density_right.close();\n */\n\n\n\n    //MPI Boundary calculations for ions\n    unsigned int rangeIons = (ion.size() + world.size() - 1) / (1.0 * world.size());\n    lowerBoundIons = world.rank() * rangeIons;\n    upperBoundIons = (world.rank() + 1) * rangeIons - 1;\n    sizFVecIons = rangeIons;\n    if (world.rank() == world.size() - 1) {\n        upperBoundIons = ion.size() - 1;\n    }\n\n    //MPI Boundary calculations for meshPoints\n    unsigned int rangeMesh = (box.leftplane.size() + world.size() - 1) / (1.0 * world.size());\n    lowerBoundMesh = world.rank() * rangeMesh;\n    upperBoundMesh = (world.rank() + 1) * rangeMesh - 1;\n    sizFVecMesh = rangeMesh;\n    if (world.rank() == world.size() - 1) {\n        upperBoundMesh = box.leftplane.size() - 1;\n    }\n\n    // Car-Parrinello Molecular Dynamics\n    cpmd(ion, box, real_bath, fake_bath, bin, fmdremote, cpmdremote);\n\n//   // Post simulation analysis (useful for short runs, but performed otherwise too)\n    //   auto_correlation_function();\n    if (world.rank() == 0) {\n        cout << \"MD trust factor R (should be < 0.05) is \" << compute_MD_trust_factor_R(cpmdremote.hiteqm) << endl;\n        cout << \"Program ends \\n\\n\";\n    }\n\n    return 0;\n}\n// End of main\n\n// useful codes\n\n/* random number generation code from gsl\nint N = 10;  // number of random numbers to generate\n\n// random nmbr declarations\n\nconst gsl_rng_type * T;\ngsl_rng * r;\n\nT = gsl_rng_default;\nr = gsl_rng_alloc (T);\n\n\n// prepare for seeding of gsl random nmbr generator:\n\n//   srand((time(0)));                // srand & time are built-in\n//   unsigned long int s = random();  // gsl_rng_uniform will eventually\nunsigned long int s = 23897897;  // gsl_rng_uniform will eventually\n                                 // want a non-negative \"long\" integer\n\n\ngsl_rng_env_setup();\ngsl_rng_set(r,s); // seed the random number generator;\n\n// generate N random numbers:\n\nfor(int i = 0; i < N; ++i) {\n  cout << \" random number = \" << gsl_rng_uniform (r) << endl;;\n  }\n\ngsl_rng_free (r);\n\nreturn 0;\n*/\n\n", "meta": {"hexsha": "6f0e7ac92e9e7d7dcf21a87cbaf5b47dc9d1e8c7", "size": 17329, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "softmaterialslab/nanoconfinement-cpmd", "max_stars_repo_head_hexsha": "0e59ba29c5f411bd67dc6d3b7daf6c3e76b42b0a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "softmaterialslab/nanoconfinement-cpmd", "max_issues_repo_head_hexsha": "0e59ba29c5f411bd67dc6d3b7daf6c3e76b42b0a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "softmaterialslab/nanoconfinement-cpmd", "max_forks_repo_head_hexsha": "0e59ba29c5f411bd67dc6d3b7daf6c3e76b42b0a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.4584450402, "max_line_length": 167, "alphanum_fraction": 0.6259449478, "num_tokens": 4563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.21290269256000524}}
{"text": "// Copyright 2008 John Maddock\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_DISTRIBUTIONS_DETAIL_HG_QUANTILE_HPP\n#define BOOST_MATH_DISTRIBUTIONS_DETAIL_HG_QUANTILE_HPP\n\n#include <boost/math/policies/error_handling.hpp>\n#include <boost/math/distributions/detail/hypergeometric_pdf.hpp>\n\nnamespace boost{ namespace math{ namespace detail{\n\ntemplate <class T>\ninline unsigned round_x_from_p(unsigned x, T p, T cum, T fudge_factor, unsigned lbound, unsigned /*ubound*/, const policies::discrete_quantile<policies::integer_round_down>&)\n{\n   if((p < cum * fudge_factor) && (x != lbound))\n   {\n      BOOST_MATH_INSTRUMENT_VARIABLE(x-1);\n      return --x;\n   }\n   return x;\n}\n\ntemplate <class T>\ninline unsigned round_x_from_p(unsigned x, T p, T cum, T fudge_factor, unsigned /*lbound*/, unsigned ubound, const policies::discrete_quantile<policies::integer_round_up>&)\n{\n   if((cum < p * fudge_factor) && (x != ubound))\n   {\n      BOOST_MATH_INSTRUMENT_VARIABLE(x+1);\n      return ++x;\n   }\n   return x;\n}\n\ntemplate <class T>\ninline unsigned round_x_from_p(unsigned x, T p, T cum, T fudge_factor, unsigned lbound, unsigned ubound, const policies::discrete_quantile<policies::integer_round_inwards>&)\n{\n   if(p >= 0.5)\n      return round_x_from_p(x, p, cum, fudge_factor, lbound, ubound, policies::discrete_quantile<policies::integer_round_down>());\n   return round_x_from_p(x, p, cum, fudge_factor, lbound, ubound, policies::discrete_quantile<policies::integer_round_up>());\n}\n\ntemplate <class T>\ninline unsigned round_x_from_p(unsigned x, T p, T cum, T fudge_factor, unsigned lbound, unsigned ubound, const policies::discrete_quantile<policies::integer_round_outwards>&)\n{\n   if(p >= 0.5)\n      return round_x_from_p(x, p, cum, fudge_factor, lbound, ubound, policies::discrete_quantile<policies::integer_round_up>());\n   return round_x_from_p(x, p, cum, fudge_factor, lbound, ubound, policies::discrete_quantile<policies::integer_round_down>());\n}\n\ntemplate <class T>\ninline unsigned round_x_from_p(unsigned x, T /*p*/, T /*cum*/, T /*fudge_factor*/, unsigned /*lbound*/, unsigned /*ubound*/, const policies::discrete_quantile<policies::integer_round_nearest>&)\n{\n   return x;\n}\n\ntemplate <class T>\ninline unsigned round_x_from_q(unsigned x, T q, T cum, T fudge_factor, unsigned lbound, unsigned /*ubound*/, const policies::discrete_quantile<policies::integer_round_down>&)\n{\n   if((q * fudge_factor > cum) && (x != lbound))\n   {\n      BOOST_MATH_INSTRUMENT_VARIABLE(x-1);\n      return --x;\n   }\n   return x;\n}\n\ntemplate <class T>\ninline unsigned round_x_from_q(unsigned x, T q, T cum, T fudge_factor, unsigned /*lbound*/, unsigned ubound, const policies::discrete_quantile<policies::integer_round_up>&)\n{\n   if((q < cum * fudge_factor) && (x != ubound))\n   {\n      BOOST_MATH_INSTRUMENT_VARIABLE(x+1);\n      return ++x;\n   }\n   return x;\n}\n\ntemplate <class T>\ninline unsigned round_x_from_q(unsigned x, T q, T cum, T fudge_factor, unsigned lbound, unsigned ubound, const policies::discrete_quantile<policies::integer_round_inwards>&)\n{\n   if(q < 0.5)\n      return round_x_from_q(x, q, cum, fudge_factor, lbound, ubound, policies::discrete_quantile<policies::integer_round_down>());\n   return round_x_from_q(x, q, cum, fudge_factor, lbound, ubound, policies::discrete_quantile<policies::integer_round_up>());\n}\n\ntemplate <class T>\ninline unsigned round_x_from_q(unsigned x, T q, T cum, T fudge_factor, unsigned lbound, unsigned ubound, const policies::discrete_quantile<policies::integer_round_outwards>&)\n{\n   if(q >= 0.5)\n      return round_x_from_q(x, q, cum, fudge_factor, lbound, ubound, policies::discrete_quantile<policies::integer_round_down>());\n   return round_x_from_q(x, q, cum, fudge_factor, lbound, ubound, policies::discrete_quantile<policies::integer_round_up>());\n}\n\ntemplate <class T>\ninline unsigned round_x_from_q(unsigned x, T /*q*/, T /*cum*/, T /*fudge_factor*/, unsigned /*lbound*/, unsigned /*ubound*/, const policies::discrete_quantile<policies::integer_round_nearest>&)\n{\n   return x;\n}\n\ntemplate <class T, class Policy>\nunsigned hypergeometric_quantile_imp(T p, T q, unsigned r, unsigned n, unsigned N, const Policy& pol)\n{\n#ifdef BOOST_MSVC\n#  pragma warning(push)\n#  pragma warning(disable:4267)\n#endif\n   typedef typename Policy::discrete_quantile_type discrete_quantile_type;\n   BOOST_MATH_STD_USING\n   BOOST_FPU_EXCEPTION_GUARD\n   T result;\n   T fudge_factor = 1 + tools::epsilon<T>() * ((N <= boost::math::prime(boost::math::max_prime - 1)) ? 50 : 2 * N);\n   unsigned base = static_cast<unsigned>((std::max)(0, (int)(n + r) - (int)(N)));\n   unsigned lim = (std::min)(r, n);\n\n   BOOST_MATH_INSTRUMENT_VARIABLE(p);\n   BOOST_MATH_INSTRUMENT_VARIABLE(q);\n   BOOST_MATH_INSTRUMENT_VARIABLE(r);\n   BOOST_MATH_INSTRUMENT_VARIABLE(n);\n   BOOST_MATH_INSTRUMENT_VARIABLE(N);\n   BOOST_MATH_INSTRUMENT_VARIABLE(fudge_factor);\n   BOOST_MATH_INSTRUMENT_VARIABLE(base);\n   BOOST_MATH_INSTRUMENT_VARIABLE(lim);\n\n   if(p <= 0.5)\n   {\n      unsigned x = base;\n      result = hypergeometric_pdf<T>(x, r, n, N, pol);\n      T diff = result;\n      while(result < p)\n      {\n         diff = (diff > tools::min_value<T>() * 8) \n            ? T(n - x) * T(r - x) * diff / (T(x + 1) * T(N + x + 1 - n - r))\n            : hypergeometric_pdf<T>(x + 1, r, n, N, pol);\n         if(result + diff / 2 > p)\n            break;\n         ++x;\n         result += diff;\n#ifdef BOOST_MATH_INSTRUMENT\n         if(diff != 0)\n         {\n            BOOST_MATH_INSTRUMENT_VARIABLE(x);\n            BOOST_MATH_INSTRUMENT_VARIABLE(diff);\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\n         }\n#endif\n      }\n      return round_x_from_p(x, p, result, fudge_factor, base, lim, discrete_quantile_type());\n   }\n   else\n   {\n      unsigned x = lim;\n      result = 0;\n      T diff = hypergeometric_pdf<T>(x, r, n, N, pol);\n      while(result + diff / 2 < q)\n      {\n         result += diff;\n         diff = (diff > tools::min_value<T>() * 8)\n            ? x * T(N + x - n - r) * diff / (T(1 + n - x) * T(1 + r - x))\n            : hypergeometric_pdf<T>(x - 1, r, n, N, pol);\n         --x;\n#ifdef BOOST_MATH_INSTRUMENT\n         if(diff != 0)\n         {\n            BOOST_MATH_INSTRUMENT_VARIABLE(x);\n            BOOST_MATH_INSTRUMENT_VARIABLE(diff);\n            BOOST_MATH_INSTRUMENT_VARIABLE(result);\n         }\n#endif\n      }\n      return round_x_from_q(x, q, result, fudge_factor, base, lim, discrete_quantile_type());\n   }\n#ifdef BOOST_MSVC\n#  pragma warning(pop)\n#endif\n}\n\ntemplate <class T, class Policy>\ninline unsigned hypergeometric_quantile(T p, T q, unsigned r, unsigned n, unsigned N, const Policy&)\n{\n   BOOST_FPU_EXCEPTION_GUARD\n   typedef typename tools::promote_args<T>::type result_type;\n   typedef typename policies::evaluation<result_type, Policy>::type value_type;\n   typedef typename policies::normalise<\n      Policy, \n      policies::promote_float<false>, \n      policies::promote_double<false>, \n      policies::assert_undefined<> >::type forwarding_policy;\n\n   return detail::hypergeometric_quantile_imp<value_type>(p, q, r, n, N, forwarding_policy());\n}\n\n}}} // namespaces\n\n#endif\n\n", "meta": {"hexsha": "a855a4a777a45a57fa66ad196ce2245c5fc49218", "size": 7260, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/math/distributions/detail/hypergeometric_quantile.hpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1210.0, "max_stars_repo_stars_event_min_datetime": "2020-08-18T07:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T15:06:05.000Z", "max_issues_repo_path": "boost/boost/math/distributions/detail/hypergeometric_quantile.hpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1667.0, "max_issues_repo_issues_event_min_datetime": "2017-03-27T14:41:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:50:06.000Z", "max_forks_repo_path": "boost/boost/math/distributions/detail/hypergeometric_quantile.hpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 275.0, "max_forks_repo_forks_event_min_datetime": "2020-08-18T08:35:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T15:06:07.000Z", "avg_line_length": 36.3, "max_line_length": 193, "alphanum_fraction": 0.68815427, "num_tokens": 1976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.21290269256000519}}
{"text": "#include \"solver.h\"\n\n#include <boost/format.hpp>\n#include <cmath>\n#include <cstdlib>\n#include <fstream>\n#include <functional>\n#include <string>\n#include <unordered_set>\n#include <utility>\n#include \"../injector.h\"\n#include \"../omp_hash_map/src/omp_hash_map.h\"\n#include \"../omp_hash_map/src/reducer.h\"\n#include \"../vector_stats.h\"\n#include \"davidson_util.h\"\n#include \"spin_det_util.h\"\n\n#define ENERGY_FORMAT \"%.12f\"\n#define TABLE_FORMAT_ITEM_NAME \"%20s\"\n#define TABLE_FORMAT_F \"%17.10f\"\n#define TABLE_FORMAT_D \"%'17d\"\n#define TABLE_FORMAT_LL \"%'17llu\"\n#define MAX_HASH_LOAD 1.618\n#define MAX_DETS_PER_FILE 20000000\n\nclass UncertainResult {\n public:\n  double value = 0.0;\n  double uncertainty = 0.0;\n};\n\nclass SolverImpl : public Solver {\n public:\n  ~SolverImpl();\n\n  SolverImpl(\n      Session* const session,\n      Connections* const connections,\n      AbstractSystem* const abstrct_system);\n\n  void setup_hf() override;\n\n  void variation(const double eps_var) override;\n\n  void save_variation_result(const std::string& filename) override;\n\n  bool load_variation_result(const std::string& filename) override;\n\n  std::vector<double> apply_hamiltonian(\n      const std::vector<double>& vec, const bool first_iteration) override;\n\n  void perturbation(\n      const int n_orbs_var,\n      const double eps_var,\n      const std::vector<int>& n_orbs_pts,\n      const std::vector<double>& eps_pts) override;\n\n private:\n  int n_up = 0;\n\n  int n_dn = 0;\n\n  double energy_hf = 0.0;\n\n  double energy_var = 0.0;\n\n  std::unordered_set<std::string> var_dets_set;\n\n  bool verbose = false;\n\n  void print_var_result() const;\n\n  std::vector<data::Determinant> tmp_dets;\n\n  std::vector<double> get_energy_pts_pre_dtm(\n      const std::vector<int>& n_orbs_pts);\n\n  std::vector<UncertainResult> get_energy_pts_dtm(\n      const std::vector<int>& n_orbs_pts,\n      const std::vector<double>& energy_pts_pre_dtm);\n\n  std::vector<std::vector<UncertainResult>> get_energy_pts_stc(\n      const std::vector<int>& n_orbs_pts,\n      const std::vector<double>& eps_pts,\n      const std::vector<UncertainResult>& energy_pts_dtm);\n\n  double get_weight(const int i) const;\n};\n\nSolverImpl::SolverImpl(\n    Session* const session,\n    Connections* const connections,\n    AbstractSystem* const abstract_system)\n    : Solver(session, connections, abstract_system) {\n  Parallel* const parallel = session->get_parallel();\n  Config* const config = session->get_config();\n  verbose = parallel->is_master();\n  tmp_dets.resize(parallel->get_n_threads());\n  n_up = config->get_int(\"n_up\");\n  n_dn = config->get_int(\"n_dn\");\n}\n\nSolverImpl::~SolverImpl() {}\n\nvoid SolverImpl::setup_hf() {\n  // Create or clear wavefunction.\n  abstract_system->dets.clear();\n  abstract_system->coefs.clear();\n\n  // Add a single term with coef 1.0 and no diffs.\n  auto& det_hf = tmp_dets[0];\n  det_hf.Clear();\n  det_hf.mutable_up()->set_n_hf_elecs(n_up);\n  det_hf.mutable_dn()->set_n_hf_elecs(n_dn);\n  abstract_system->dets.push_back(det_hf.SerializeAsString());\n  abstract_system->coefs.push_back(1.0);\n\n  // Update HF and variational energy.\n  energy_hf = energy_var = abstract_system->hamiltonian(&det_hf, &det_hf);\n\n  // Clear connections.\n  connections->clear();\n\n  if (verbose) printf(\"HF det setup.\\n\");\n};\n\nvoid SolverImpl::variation(const double eps_var) {\n  Timer* const timer = session->get_timer();\n\n  // Contruct variational determinant hash set.\n  const int n_start_dets = abstract_system->dets.size();\n  var_dets_set.clear();\n  std::vector<double> prev_coefs;\n  var_dets_set.reserve(n_start_dets);\n  prev_coefs.resize(n_start_dets, 0.0);\n  for (int i = 0; i < n_start_dets; i++) {\n    var_dets_set.insert(abstract_system->dets[i]);\n  }\n\n  // Variation iterations.\n  bool converged = false;\n  int iteration = 0;\n  int n_new_dets = 0;\n\n  // Add to the var wf if not exists and set its coef to zero.\n  const auto& connected_det_handler =\n      [&](const data::Determinant* const connected_det) {\n        std::string det_code = connected_det->SerializeAsString();\n        if (var_dets_set.count(det_code) == 0) {\n          var_dets_set.insert(det_code);\n          abstract_system->dets.push_back(det_code);\n          abstract_system->coefs.push_back(0.0);\n          n_new_dets++;\n        }\n      };\n\n  // Apply hamiltonian to a vec (with partially cached hamiltonian).\n  const auto& apply_hamiltonian_func = std::bind(\n      &SolverImpl::apply_hamiltonian,\n      this,\n      std::placeholders::_1,\n      std::placeholders::_2);\n\n  while (!converged) {\n    timer->start(\"loop \" + std::to_string(iteration));\n\n    // Find new dets.\n    n_new_dets = 0;\n    const int n_old_dets = abstract_system->dets.size();\n    for (int i = 0; i < n_old_dets; i++) {\n      const double coef = abstract_system->coefs[i];\n      auto& det = tmp_dets[0];\n      det.ParseFromString(abstract_system->dets[i]);\n      if (std::abs(coef) <= std::abs(prev_coefs[i])) continue;\n      abstract_system->find_connected_dets(\n          &det, eps_var / std::abs(coef), connected_det_handler);\n    }\n    const int n_total_dets = abstract_system->dets.size();\n    if (verbose) {\n      printf(\"New / total dets: %'d / %'d\\n\", n_new_dets, n_total_dets);\n    }\n    timer->checkpoint(\"found new dets\");\n\n    // Update prev coefs.\n    prev_coefs.resize(n_total_dets);\n    for (int i = 0; i < n_total_dets; i++) {\n      prev_coefs[i] = abstract_system->coefs[i];\n    }\n\n    // Diagonalize.\n    connections->update();\n    timer->checkpoint(\"updated connections\");\n    std::vector<double> diagonal(n_total_dets, 0.0);\n#pragma omp parallel for schedule(static, 1)\n    for (int i = 0; i < n_total_dets; i++) {\n      const int thread_id = omp_get_thread_num();\n      auto& tmp_det = tmp_dets[thread_id];\n      tmp_det.ParseFromString(abstract_system->dets[i]);\n      diagonal[i] = abstract_system->hamiltonian(&tmp_det, &tmp_det);\n    }\n    const auto& diagonalization_result = DavidsonUtil::diagonalize(\n        prev_coefs, diagonal, apply_hamiltonian_func, 5, verbose);\n    const double energy_var_new = diagonalization_result.first;\n    const auto& new_coefs = diagonalization_result.second;\n    for (int i = 0; i < n_total_dets; i++) {\n      abstract_system->coefs[i] = new_coefs[i];\n    }\n\n    // Determine convergence.\n    if (std::abs(energy_var_new - energy_var) < 1.0e-7) {\n      converged = true;\n    }\n\n    energy_var = energy_var_new;\n    iteration++;\n\n    if (verbose) print_var_result();\n\n    timer->end();  // iteration.\n  }\n};\n\nvoid SolverImpl::save_variation_result(const std::string& filename) {\n  // Write summary.\n  std::fstream var_file(\n      filename, std::ios::out | std::ios::trunc | std::ios::binary);\n  data::VariationResult res;\n  data::Wavefunction trunk_wf;\n  res.set_energy_hf(energy_hf);\n  res.set_energy_var(energy_var);\n  const int n_dets = abstract_system->dets.size();\n  res.set_n_dets(n_dets);\n  res.SerializeToOstream(&var_file);\n  var_file.close();\n  if (verbose) {\n    printf(\"Saved summary to: %s\\n\", filename.c_str());\n  }\n\n  // Write wavefunction trunks. (Due to the 2GB serialization limit of Protobuf)\n  int trunk_n_dets = 0;\n  int trunk_id = 0;\n  for (int i = 0; i < n_dets; i++) {\n    data::Term* const new_term = trunk_wf.add_terms();\n    new_term->set_coef(abstract_system->coefs[i]);\n    new_term->mutable_det()->ParseFromString(abstract_system->dets[i]);\n    trunk_n_dets++;\n    if (trunk_n_dets >= MAX_DETS_PER_FILE || i == n_dets - 1) {\n      const auto& wf_filename = filename + \".part\" + std::to_string(trunk_id);\n      std::fstream wf_file(\n          wf_filename, std::ios::out | std::ios::trunc | std::ios::binary);\n      trunk_wf.SerializeToOstream(&wf_file);\n      wf_file.close();\n      if (verbose) {\n        printf(\"Saved %'d dets to: %s\\n\", trunk_n_dets, wf_filename.c_str());\n      }\n      trunk_wf.Clear();\n      trunk_n_dets = 0;\n      trunk_id++;\n    }\n  }\n}\n\nbool SolverImpl::load_variation_result(const std::string& filename) {\n  // Load summary.\n  std::fstream var_file(filename, std::ios::in | std::ios::binary);\n  data::VariationResult res;\n  if (!res.ParseFromIstream(&var_file)) {\n    return false;\n  }\n  var_file.close();\n  energy_hf = res.energy_hf();\n  energy_var = res.energy_var();\n  const int n_dets_total = res.n_dets();\n  if (verbose) {\n    printf(\"Loaded summary from: %s\\n\", filename.c_str());\n  }\n\n  // Load wavefunctions from trunks.\n  abstract_system->dets.clear();\n  abstract_system->coefs.clear();\n  int n_dets_read = 0;\n  int trunk_id = 0;\n  data::Wavefunction trunk_wf;\n  while (n_dets_read < n_dets_total) {\n    const auto& wf_filename = filename + \".part\" + std::to_string(trunk_id);\n    trunk_id++;\n    std::fstream var_file(wf_filename, std::ios::in | std::ios::binary);\n    if (!trunk_wf.ParseFromIstream(&var_file)) {\n      throw std::runtime_error(\"variational results corrupted\");\n    }\n    const int trunk_n_dets = trunk_wf.terms_size();\n    for (int i = 0; i < trunk_n_dets; i++) {\n      const auto& term = trunk_wf.terms(i);\n      abstract_system->coefs.push_back(term.coef());\n      abstract_system->dets.push_back(term.det().SerializeAsString());\n      n_dets_read++;\n    }\n    if (verbose) {\n      printf(\"Loaded %'d dets from: %s\\n\", trunk_n_dets, wf_filename.c_str());\n    }\n  }\n\n  if (verbose) {\n    print_var_result();\n  }\n\n  return true;\n}\n\nvoid SolverImpl::print_var_result() const {\n  printf(\"Number of dets: %'zu\\n\", abstract_system->dets.size());\n  printf(\"Variation energy: \" ENERGY_FORMAT \" Ha\\n\", energy_var);\n  const double energy_corr = energy_var - energy_hf;\n  printf(\"Correlation energy (variation): \" ENERGY_FORMAT \" Ha\\n\", energy_corr);\n}\n\nstd::vector<double> SolverImpl::apply_hamiltonian(\n    const std::vector<double>& vec, const bool first_iteration) {\n  const int n_dets = vec.size();\n  Parallel* const parallel = session->get_parallel();\n  const int proc_id = parallel->get_proc_id();\n  const int n_procs = parallel->get_n_procs();\n  const int n_threads = parallel->get_n_threads();\n  std::vector<std::vector<double>> res(n_threads);\n  for (int i = 0; i < n_threads; i++) res[i].resize(n_dets, 0.0);\n  std::vector<unsigned long long> n_nonzero_elems(n_threads, 0);\n\n#pragma omp parallel for schedule(static, 1)\n  for (int i = proc_id; i < n_dets; i += n_procs) {\n    const int thread_id = omp_get_thread_num();\n    const auto& conns = connections->get_connections(i);\n    for (const auto conn : conns) {\n      const int j = conn.first;\n      const double H_ij = conn.second;\n      res[thread_id][i] += H_ij * vec[j];\n      if (i != j) {\n        res[thread_id][j] += H_ij * vec[i];\n        n_nonzero_elems[thread_id] += 2;\n      } else {\n        n_nonzero_elems[thread_id]++;\n      }\n    }\n  }\n\n  for (int i = 1; i < n_threads; i++) {\n    n_nonzero_elems[0] += n_nonzero_elems[i];\n    for (int j = 0; j < n_dets; j++) {\n      res[0][j] += res[i][j];\n    }\n  }\n  parallel->reduce_to_sum(res[0]);\n  parallel->reduce_to_sum(n_nonzero_elems[0]);\n  if (verbose && first_iteration) {\n    printf(\"Number of non-zero elements: %'llu\\n\", n_nonzero_elems[0]);\n  }\n\n  session->get_timer()->checkpoint(\"hamiltonian applied\");\n\n  return res[0];\n};\n\nvoid SolverImpl::perturbation(\n    const int n_orbs_var,\n    const double eps_var,\n    const std::vector<int>& n_orbs_pts,\n    const std::vector<double>& eps_pts) {\n  // Check if the results already exists.\n  const auto result_filename =\n      str(boost::format(\"pt_%d_%#.4g.csv\") % n_orbs_var % eps_var);\n  if (std::ifstream(result_filename)) {\n    if (verbose) printf(\"PT results found in: %s\\n\", result_filename.c_str());\n    return;\n  }\n\n  // Clean variation variables.\n  connections->clear();\n\n  // Construct var dets set.\n  var_dets_set.clear();\n  var_dets_set.reserve(abstract_system->dets.size());\n  for (const auto& det_string : abstract_system->dets) {\n    var_dets_set.insert(det_string);\n  }\n\n  // Get Deterministic PT correction.\n  const auto& energy_pts_pre_dtm = get_energy_pts_pre_dtm(n_orbs_pts);\n  const auto& energy_pts_dtm =\n      get_energy_pts_dtm(n_orbs_pts, energy_pts_pre_dtm);\n\n  // Check eps_pts validity.\n  const double eps_dtm_pt = config->get_double(\"eps_dtm_pt\");\n  const int n_eps_pts = eps_pts.size();\n  for (int i = 1; i < n_eps_pts; i++) {\n    assert(eps_pts[i] <= eps_dtm_pt);\n    assert(eps_pts[i] < eps_pts[i - 1]);\n  }\n\n  // Get Stochastic PT correction.\n  const auto& energy_pts_stc =\n      get_energy_pts_stc(n_orbs_pts, eps_pts, energy_pts_dtm);\n\n  // Record results.\n  std::ofstream result_file(result_filename);\n  result_file << \"n_orbs_var,eps_var,n_orbs_pt,eps_pt,energy_corr,uncert,\"\n              << \"energy_hf,energy_var,energy_pt\" << std::endl;\n\n  const int n_n_orbs_pts = n_orbs_pts.size();\n  for (int i = 0; i < n_eps_pts; i++) {\n    for (int j = 0; j < n_n_orbs_pts; j++) {\n      const double eps_pt = eps_pts[i];\n      const int n_orbs_pt = n_orbs_pts[j];\n      const double energy_pt_dtm = energy_pts_dtm[j].value;\n      const double energy_pt_stc = energy_pts_stc[i][j].value;\n      const double energy_pt = energy_pt_dtm + energy_pt_stc;\n      const double uncert = std::sqrt(\n          std::pow(energy_pts_stc[i][j].uncertainty, 2) +\n          std::pow(energy_pts_dtm[j].uncertainty, 2));\n      const double energy_corr = energy_var + energy_pt - energy_hf;\n      result_file << str(boost::format(\"%d, %#.4g, %d, %#.4g, %#.15g, %#.15g, \"\n                                       \"%#.15g, %#.15g, %#.15g\") %\n                         n_orbs_var % eps_var % n_orbs_pt % eps_pt %\n                         energy_corr % uncert % energy_hf % energy_var %\n                         energy_pt)\n                  << std::endl;\n    }\n  }\n\n  if (verbose) {\n    printf(\"Results saved to: %s\\n\", result_filename.c_str());\n  }\n\n  result_file.close();\n}\n\nstd::vector<double> SolverImpl::get_energy_pts_pre_dtm(\n    const std::vector<int>& n_orbs_pts) {\n  // Cache commonly used variables.\n  const int n_n_orbs_pts = n_orbs_pts.size();\n  const int n_var_dets = var_dets_set.size();\n  const double eps_pre_dtm_pt = config->get_double(\"eps_pre_dtm_pt\");\n  std::hash<std::string> string_hasher;\n\n  // Construct partial sums store and pt results store.\n  omp_hash_map<std::string, double> partial_sums_pre;\n  partial_sums_pre.set_max_load_factor(MAX_HASH_LOAD);\n  std::vector<double> energy_pts_pre_dtm(n_n_orbs_pts, 0.0);\n  std::vector<unsigned long long> n_pt_dets_pre_dtm(n_n_orbs_pts, 0);\n\n  timer->start(\"pre_dtm\");\n  if (verbose) printf(\">>> eps_pre_dtm_pt %#.4g\\n\", eps_pre_dtm_pt);\n  timer->start(\"search\");\n  double target_progress = 0.25;\n#pragma omp parallel for schedule(dynamic, 5)\n  for (int i = 0; i < n_var_dets; i++) {\n    auto& var_det = tmp_dets[omp_get_thread_num()];\n    var_det.ParseFromString(abstract_system->dets[i]);\n    const double coef = abstract_system->coefs[i];\n\n    const auto& pt_det_handler = [&](const auto& det_a) {\n      const auto& det_a_code = det_a->SerializeAsString();\n      const size_t det_a_hash = string_hasher(det_a_code);\n      if (var_dets_set.count(det_a_code) == 1) return;\n      if (det_a_hash % n_procs != proc_id) return;\n      const double H_ai = abstract_system->hamiltonian(&var_det, det_a);\n      const double partial_sum_term = H_ai * coef;\n      partial_sums_pre.set(\n          det_a_code, [&](double& value) { value += partial_sum_term; }, 0.0);\n    };\n\n    abstract_system->find_connected_dets(\n        &var_det, eps_pre_dtm_pt / std::abs(coef), pt_det_handler);\n\n    // Report progress. (every time progress reaches 2^n %).\n    const double current_progress = i * 100.0 / n_var_dets;\n    if (target_progress <= current_progress) {\n      if (omp_get_thread_num() == 0) {\n        if (verbose) {\n          printf(\"Master node PT dets: %'zu\\n\", partial_sums_pre.get_n_keys());\n        }\n        std::string event =\n            str(boost::format(\"Progress: %.2f %%\") % target_progress);\n        timer->checkpoint(event);\n        target_progress *= 2.0;\n      }\n    }\n  }\n  while (target_progress <= 100) {\n    std::string event =\n        str(boost::format(\"Progress: %.2f %%\") % target_progress);\n    timer->checkpoint(event);\n    target_progress *= 2.0;\n  }\n  timer->end();  // Search.\n\n  timer->start(\"accumulate\");\n  partial_sums_pre.apply([&](const std::string& det_code, const double value) {\n    const int thread_id = omp_get_thread_num();\n    auto& det = tmp_dets[thread_id];\n    det.ParseFromString(det_code);\n    const int n_orbs_used = SpinDetUtil::get_n_orbs_used(det);\n    const double H_aa = abstract_system->hamiltonian(&det, &det);\n    const double contribution = value * value / (energy_var - H_aa);\n    for (int i = 0; i < n_n_orbs_pts; i++) {\n      if (n_orbs_used > n_orbs_pts[i]) continue;\n#pragma omp atomic\n      n_pt_dets_pre_dtm[i]++;\n#pragma omp atomic\n      energy_pts_pre_dtm[i] += contribution;\n    }\n  });\n  partial_sums_pre.clear();\n  parallel->reduce_to_sum(n_pt_dets_pre_dtm);\n  parallel->reduce_to_sum(energy_pts_pre_dtm);\n\n  if (verbose) {\n    printf(TABLE_FORMAT_ITEM_NAME, \"# orbitals PT:\");\n    for (int i = 0; i < n_n_orbs_pts; i++) {\n      printf(TABLE_FORMAT_D, n_orbs_pts[i]);\n    }\n    printf(\"\\n\");\n    printf(TABLE_FORMAT_ITEM_NAME, \"Pre DTM energy PT:\");\n    for (int i = 0; i < n_n_orbs_pts; i++) {\n      printf(TABLE_FORMAT_F, energy_pts_pre_dtm[i]);\n    }\n    printf(\"\\n\");\n    printf(TABLE_FORMAT_ITEM_NAME, \"EST. CORR. energy:\");\n    for (int i = 0; i < n_n_orbs_pts; i++) {\n      const double energy_corr = energy_pts_pre_dtm[i] + energy_var - energy_hf;\n      printf(TABLE_FORMAT_F, energy_corr);\n    }\n    printf(\"\\n\");\n    printf(TABLE_FORMAT_ITEM_NAME, \"# DTM PT dets:\");\n    for (int i = 0; i < n_n_orbs_pts; i++) {\n      printf(TABLE_FORMAT_LL, n_pt_dets_pre_dtm[i]);\n    }\n    printf(\"\\n\");\n  }\n  timer->end();  // Accumulate.\n  timer->end();  // pre dtm.\n\n  return energy_pts_pre_dtm;\n}\n\nstd::vector<UncertainResult> SolverImpl::get_energy_pts_dtm(\n    const std::vector<int>& n_orbs_pts,\n    const std::vector<double>& energy_pts_pre_dtm) {\n  // Cache commonly used variables.\n  const int n_n_orbs_pts = n_orbs_pts.size();\n  const int n_var_dets = var_dets_set.size();\n  const size_t n_pt_batches_dtm = config->get_int(\"n_batches_dtm_pt\");\n  const double eps_pre_dtm_pt = config->get_double(\"eps_pre_dtm_pt\");\n  const double eps_dtm_pt = config->get_double(\"eps_dtm_pt\");\n  std::hash<std::string> string_hasher;\n\n  // Construct partial sums store and pt results store.\n  omp_hash_map<std::string, double> partial_sums_pre;\n  omp_hash_map<std::string, double> partial_sums;\n  partial_sums.set_max_load_factor(MAX_HASH_LOAD);\n  partial_sums_pre.set_max_load_factor(MAX_HASH_LOAD);\n  std::vector<UncertainResult> energy_pts_dtm(n_n_orbs_pts);\n  std::vector<std::vector<double>> energy_pts_dtm_batches(n_n_orbs_pts);\n  std::vector<unsigned long long> n_pt_dets_dtm(n_n_orbs_pts, 0);\n  const double target_error = config->get_double(\"target_error\");\n\n  timer->start(\"dtm\");\n  if (verbose) printf(\">>> eps_dtm_pt %#.4g\\n\", eps_dtm_pt);\n  // Process batch by batch to achieve a larger run in a constrained mem env.\n  for (size_t b = 0; b < n_pt_batches_dtm; b++) {\n    timer->start(str(boost::format(\"%d/%d\") % (b + 1) % n_pt_batches_dtm));\n\n    double target_progress = 0.25;\n    timer->start(\"search\");\n#pragma omp parallel for schedule(dynamic, 5)\n    for (int i = 0; i < n_var_dets; i++) {\n      auto& var_det = tmp_dets[omp_get_thread_num()];\n      var_det.ParseFromString(abstract_system->dets[i]);\n      const double coef = abstract_system->coefs[i];\n\n      // Process only if:\n      // 1. is not a var det, and\n      // 2. belongs to the current proc_id, and\n      // 3. belongs to the current batch.\n      const auto& pt_det_handler = [&](const auto& det_a) {\n        const auto& det_a_code = det_a->SerializeAsString();\n        const size_t det_a_hash = string_hasher(det_a_code);\n        if (var_dets_set.count(det_a_code) == 1) return;\n        if (det_a_hash % n_procs != proc_id) return;\n        if ((det_a_hash / n_procs) % n_pt_batches_dtm != b) return;\n        const double H_ai = abstract_system->hamiltonian(&var_det, det_a);\n        const double partial_sum_term = H_ai * coef;\n        if (std::abs(partial_sum_term) >= eps_pre_dtm_pt) {\n          partial_sums_pre.set(\n              det_a_code,\n              [&](double& value) { value += partial_sum_term; },\n              0.0);\n        }\n        partial_sums.set(\n            det_a_code, [&](double& value) { value += partial_sum_term; }, 0.0);\n      };\n\n      abstract_system->find_connected_dets(\n          &var_det, eps_dtm_pt / std::abs(coef), pt_det_handler);\n\n      // Report progress. (every time progress reaches 2^n %).\n      const double current_progress = i * 100.0 / n_var_dets;\n      if (target_progress <= current_progress) {\n        if (omp_get_thread_num() == 0) {\n          if (verbose) {\n            printf(\"Master node PT dets: %'zu\\n\", partial_sums.get_n_keys());\n          }\n          std::string event =\n              str(boost::format(\"Progress: %.2f %%\") % target_progress);\n          timer->checkpoint(event);\n          target_progress *= 2.0;\n        }\n      }\n    }\n    while (target_progress <= 100) {\n      std::string event =\n          str(boost::format(\"Progress: %.2f %%\") % target_progress);\n      timer->checkpoint(event);\n      target_progress *= 2.0;\n    }\n    timer->end();  // Search.\n\n    timer->start(\"accumulate\");\n\n    // For reduction after each batch.\n    std::vector<double> energy_pts_dtm_batch(n_n_orbs_pts, 0.0);\n\n    // Apply to each key, value pair:\n    // 1. Calculate the contribution.\n    // 2. For each n_orbs_pt interested:\n    //      If the n_orbs used by the key is less than n_orbs_pt:\n    //        Increase n_pt_dets by one and add contribution to energy_pt.\n    partial_sums.apply([&](const std::string& det_code, const double value) {\n      const int thread_id = omp_get_thread_num();\n      auto& det = tmp_dets[thread_id];\n      det.ParseFromString(det_code);\n      const int n_orbs_used = SpinDetUtil::get_n_orbs_used(det);\n      const double H_aa = abstract_system->hamiltonian(&det, &det);\n      const double value_pre =\n          partial_sums_pre.get_copy_or_default(det_code, 0.0);\n      partial_sums_pre.unset(det_code);\n      const double contribution =\n          (value * value - value_pre * value_pre) / (energy_var - H_aa);\n      for (int i = 0; i < n_n_orbs_pts; i++) {\n        if (n_orbs_used > n_orbs_pts[i]) continue;\n#pragma omp atomic\n        n_pt_dets_dtm[i]++;\n#pragma omp atomic\n        energy_pts_dtm_batch[i] += contribution;\n      }\n    });\n\n    // Aggregate the results from each proc.\n    parallel->reduce_to_sum(energy_pts_dtm_batch);\n    double max_uncert = 0.0;\n    for (int i = 0; i < n_n_orbs_pts; i++) {\n      energy_pts_dtm_batches[i].push_back(energy_pts_dtm_batch[i]);\n    }\n    for (int i = 0; i < n_n_orbs_pts; i++) {\n      energy_pts_dtm[i].value =\n          get_avg(energy_pts_dtm_batches[i]) * n_pt_batches_dtm +\n          energy_pts_pre_dtm[i];\n      if (b == n_pt_batches_dtm - 1) {\n        energy_pts_dtm[i].uncertainty = 0.0;  // All batches finished.\n      } else {\n        energy_pts_dtm[i].uncertainty =\n            get_stdev(energy_pts_dtm_batches[i]) * n_pt_batches_dtm / b;\n      }\n      max_uncert = std::max(max_uncert, energy_pts_dtm[i].uncertainty);\n    }\n\n    // Print batch result and estimated total correction.\n    if (verbose) {\n      printf(TABLE_FORMAT_ITEM_NAME, \"# orbitals PT:\");\n      for (int i = 0; i < n_n_orbs_pts; i++) {\n        printf(TABLE_FORMAT_D, n_orbs_pts[i]);\n      }\n      printf(\"\\n\");\n      printf(TABLE_FORMAT_ITEM_NAME, \"Batch DTM energy PT:\");\n      for (int i = 0; i < n_n_orbs_pts; i++) {\n        printf(TABLE_FORMAT_F, energy_pts_dtm_batch[i]);\n      }\n      printf(\"\\n\");\n      printf(TABLE_FORMAT_ITEM_NAME, \"EST. DTM energy PT:\");\n      for (int i = 0; i < n_n_orbs_pts; i++) {\n        printf(TABLE_FORMAT_F, energy_pts_dtm[i].value - energy_pts_pre_dtm[i]);\n      }\n      printf(\"\\n\");\n      printf(TABLE_FORMAT_ITEM_NAME, \"(including pre dtm):\");\n      for (int i = 0; i < n_n_orbs_pts; i++) {\n        printf(TABLE_FORMAT_F, energy_pts_dtm[i].value);\n      }\n      printf(\"\\n\");\n      printf(TABLE_FORMAT_ITEM_NAME, \"Uncertainty:\");\n      for (int i = 0; i < n_n_orbs_pts; i++) {\n        printf(TABLE_FORMAT_F, energy_pts_dtm[i].uncertainty);\n      }\n      printf(\"\\n\");\n      printf(TABLE_FORMAT_ITEM_NAME, \"EST. CORR. energy:\");\n      for (int i = 0; i < n_n_orbs_pts; i++) {\n        const double energy_corr =\n            energy_pts_dtm[i].value + energy_var - energy_hf;\n        printf(TABLE_FORMAT_F, energy_corr);\n      }\n      printf(\"\\n\");\n    }\n\n    timer->end();  // Accumulation.\n\n    partial_sums.clear();\n    partial_sums_pre.clear();\n    timer->end();  // Batch.\n\n    if (b > 0 && b < n_pt_batches_dtm - 2 && max_uncert < 0.2 * target_error) {\n      if (verbose) {\n        printf(\n            \"\\n>>> Skip remaining batches since uncertainty is significantly \"\n            \"smaller than target error.\\n\");\n      }\n      break;\n    }\n  }\n\n  parallel->reduce_to_sum(n_pt_dets_dtm);\n\n  // Print total PT dets.\n  if (verbose) {\n    printf(TABLE_FORMAT_ITEM_NAME, \"# DTM PT dets:\");\n    for (int i = 0; i < n_n_orbs_pts; i++) {\n      printf(TABLE_FORMAT_LL, n_pt_dets_dtm[i]);\n    }\n    printf(\"\\n\");\n  }\n\n  timer->end();\n\n  return energy_pts_dtm;\n}\n\nstd::vector<std::vector<UncertainResult>> SolverImpl::get_energy_pts_stc(\n    const std::vector<int>& n_orbs_pts,\n    const std::vector<double>& eps_pts,\n    const std::vector<UncertainResult>& energy_pts_dtm) {\n  const int n_n_orbs_pts = n_orbs_pts.size();\n  const int n_eps_pts = eps_pts.size();\n\n  // Construct results store.\n  std::vector<std::vector<UncertainResult>> energy_pts_stc(n_eps_pts);\n  std::vector<std::vector<std::vector<double>>> energy_pts_loops(n_eps_pts);\n  std::vector<omp_hash_map<std::string, double>> partial_sums(n_eps_pts);\n  omp_hash_map<std::string, double> partial_sums_dtm;\n  for (int i = 0; i < n_eps_pts; i++) {\n    energy_pts_stc[i].resize(n_n_orbs_pts);\n    energy_pts_loops[i].resize(n_n_orbs_pts);\n    partial_sums[i].set_max_load_factor(MAX_HASH_LOAD);\n  }\n  partial_sums_dtm.set_max_load_factor(MAX_HASH_LOAD);\n\n  // Construct probabilities from normalized weights.\n  const int n_var_dets = var_dets_set.size();\n  double sum_weights = 0.0;\n  for (int i = 0; i < n_var_dets; i++) {\n    sum_weights += get_weight(i);\n  }\n  std::vector<double> probs(n_var_dets);\n  std::vector<double> cum_probs(n_var_dets);  // For sampling.\n  for (int i = 0; i < n_var_dets; i++) {\n    probs[i] = get_weight(i) / sum_weights;\n    if (i == 0) {\n      cum_probs[i] = probs[i];\n    } else {\n      cum_probs[i] = probs[i] + cum_probs[i - 1];\n    }\n  }\n\n  // Stochastic iterations.\n  int iteration = 0;\n  const int max_n_iterations = config->get_int(\"max_n_iterations_stc_pt\");\n  std::unordered_map<int, int> stc_pt_sample_dets;\n  std::vector<int> stc_pt_sample_dets_list;\n  const int n_samples = config->get_int(\"n_samples_stc_pt\");\n  srand(time(NULL));\n  const double eps_dtm_pt = config->get_double(\"eps_dtm_pt\");\n  const double eps_pts_min = eps_pts.back();\n  const size_t n_batches = config->get_int(\"n_batches_stc_pt\");\n  std::hash<std::string> string_hasher;\n  const double target_error = config->get_double(\"target_error\");\n\n  timer->start(\"stc\");\n  while (iteration < max_n_iterations) {\n    timer->start(str(boost::format(\"loop %d\") % iteration));\n\n    // Cleanup.\n    for (int i = 0; i < n_eps_pts; i++) {\n      partial_sums[i].clear();\n    }\n    partial_sums_dtm.clear();\n    stc_pt_sample_dets.clear();\n    stc_pt_sample_dets_list.clear();\n\n    std::vector<std::vector<double>> energy_pts_loop(n_eps_pts);\n    std::vector<std::vector<unsigned long long>> n_pt_dets_loop(n_eps_pts);\n    for (int i = 0; i < n_eps_pts; i++) {\n      energy_pts_loop[i].resize(n_n_orbs_pts, 0.0);\n      n_pt_dets_loop[i].resize(n_n_orbs_pts, 0);\n    }\n\n    // Generate random samples.\n    for (int i = 0; i < n_samples; i++) {\n      const double rand_01 = ((double)rand() / (RAND_MAX));\n      const int sample_det_id =\n          std::lower_bound(cum_probs.begin(), cum_probs.end(), rand_01) -\n          cum_probs.begin();\n      if (stc_pt_sample_dets.count(sample_det_id) == 0) {\n        stc_pt_sample_dets_list.push_back(sample_det_id);\n      }\n      stc_pt_sample_dets[sample_det_id]++;\n    }\n\n    // Use one batch to estimate contribution from all batches.\n    const size_t selected_batch = rand() % n_batches;\n\n    // Search PT dets from selected sample var dets.\n    const int n_stc_pt_sample_dets = stc_pt_sample_dets_list.size();\n\n#pragma omp parallel for schedule(dynamic, 2)\n    for (int s = 0; s < n_stc_pt_sample_dets; s++) {\n      const int var_det_id = stc_pt_sample_dets_list[s];\n      const double prob = probs[var_det_id];\n      const double cnt = static_cast<double>(stc_pt_sample_dets[var_det_id]);\n      auto& var_det = tmp_dets[omp_get_thread_num()];\n      var_det.ParseFromString(abstract_system->dets[var_det_id]);\n      const double coef = abstract_system->coefs[var_det_id];\n\n      const auto& pt_det_handler = [&](const auto& det_a) {\n        const auto& det_a_code = det_a->SerializeAsString();\n        const size_t det_a_hash = string_hasher(det_a_code);\n        if (var_dets_set.count(det_a_code) == 1) return;\n        if (det_a_hash % n_procs != proc_id) return;\n        if ((det_a_hash / n_procs) % n_batches != selected_batch) {\n          return;  // Only use one batch.\n        }\n        const double H_ai = abstract_system->hamiltonian(&var_det, det_a);\n        const double H_aa = abstract_system->hamiltonian(det_a, det_a);\n        const double factor =\n            n_batches / ((energy_var - H_aa) * n_samples * (n_samples - 1));\n        const double partial_sum_term = H_ai * coef;\n        const double contrib_1 = cnt * partial_sum_term / prob * sqrt(-factor);\n\n        // Add to dtm partial sums.\n        if (std::abs(partial_sum_term) >= eps_dtm_pt) {\n          partial_sums_dtm.set(\n              det_a_code, [&](double& value) { value += contrib_1; }, 0.0);\n        }\n\n        // Add to partial sums.\n        for (int i = 0; i < n_eps_pts; i++) {\n          if (std::abs(partial_sum_term) >= eps_pts[i]) {\n            partial_sums[i].set(\n                det_a_code, [&](double& value) { value += contrib_1; }, 0.0);\n            break;\n          }\n        }\n\n        // Calculate 2nd order contribution if not belong to dtm pt .\n        if (std::abs(partial_sum_term) >= eps_dtm_pt) return;\n\n        const double contrib_2 =\n            (cnt * (n_samples - 1) / prob - (cnt * cnt) / (prob * prob)) *\n            partial_sum_term * partial_sum_term * factor;\n        const int n_orbs_used = SpinDetUtil::get_n_orbs_used(*det_a);\n        for (int i = 0; i < n_eps_pts; i++) {\n          if (std::abs(partial_sum_term) < eps_pts[i]) continue;\n          for (int j = 0; j < n_n_orbs_pts; j++) {\n            if (n_orbs_pts[j] < n_orbs_used) continue;\n#pragma omp atomic\n            energy_pts_loop[i][j] += contrib_2;\n          }\n        }\n      };\n\n      abstract_system->find_connected_dets(\n          &var_det, eps_pts_min / std::abs(coef), pt_det_handler);\n    }\n\n    // Accumulate and get PT correction from batch.\n    for (int i = 0; i < n_eps_pts; i++) {\n      partial_sums[i].apply(\n          [&](const std::string& det_code, const double value) {\n            const int thread_id = omp_get_thread_num();\n            auto& det = tmp_dets[thread_id];\n            det.ParseFromString(det_code);\n\n            double cum_value = value;\n            const double value_dtm =\n                partial_sums_dtm.get_copy_or_default(det_code, 0.0);\n            partial_sums_dtm.unset(det_code);\n\n            const int n_orbs_used = SpinDetUtil::get_n_orbs_used(det);\n            for (int j = i; j < n_eps_pts; j++) {\n              if (j > i) {\n                const double value_j =\n                    partial_sums[j].get_copy_or_default(det_code, 0.0);\n                partial_sums[j].unset(det_code);\n                cum_value += value_j;\n              }\n\n              const double contrib_1 =\n                  -cum_value * cum_value + value_dtm * value_dtm;\n\n              for (int k = 0; k < n_n_orbs_pts; k++) {\n                if (n_orbs_pts[k] < n_orbs_used) continue;\n#pragma omp atomic\n                energy_pts_loop[j][k] += contrib_1;\n#pragma omp atomic\n                n_pt_dets_loop[j][k]++;\n              }\n            }\n          });\n    }\n\n    // Append loop results store.\n    for (int i = 0; i < n_eps_pts; i++) {\n      parallel->reduce_to_sum(energy_pts_loop[i]);\n      parallel->reduce_to_sum(n_pt_dets_loop[i]);\n      for (int j = 0; j < n_n_orbs_pts; j++) {\n        energy_pts_loops[i][j].push_back(energy_pts_loop[i][j]);\n      }\n    }\n\n    // Calculate statistics.\n    double max_uncert = 0.0;\n    for (int i = 0; i < n_eps_pts; i++) {\n      for (int j = 0; j < n_n_orbs_pts; j++) {\n        const double avg = get_avg(energy_pts_loops[i][j]);\n        const double stdev = get_stdev(energy_pts_loops[i][j]);\n        energy_pts_stc[i][j].value = avg;\n        energy_pts_stc[i][j].uncertainty = stdev / sqrt(iteration);\n        max_uncert = std::max(energy_pts_stc[i][j].uncertainty, max_uncert);\n      }\n    }\n\n    // Report results.\n    if (verbose) {\n      printf(TABLE_FORMAT_ITEM_NAME, \"# orbitals PT:\");\n      for (int j = 0; j < n_n_orbs_pts; j++) {\n        printf(TABLE_FORMAT_D, n_orbs_pts[j]);\n      }\n      printf(\"\\n\");\n      for (int i = 0; i < n_eps_pts; i++) {\n        printf(\">>> eps_stc_pt %#.4g\\n\", eps_pts[i]);\n        printf(TABLE_FORMAT_ITEM_NAME, \"Loop # STC PT dets:\");\n        for (int j = 0; j < n_n_orbs_pts; j++) {\n          printf(TABLE_FORMAT_LL, n_pt_dets_loop[i][j]);\n        }\n        printf(\"\\n\");\n        printf(TABLE_FORMAT_ITEM_NAME, \"Loop STC energy PT:\");\n        for (int j = 0; j < n_n_orbs_pts; j++) {\n          printf(TABLE_FORMAT_F, energy_pts_loops[i][j][iteration]);\n        }\n        printf(\"\\n\");\n        printf(TABLE_FORMAT_ITEM_NAME, \"EST. STC energy PT:\");\n        for (int j = 0; j < n_n_orbs_pts; j++) {\n          printf(TABLE_FORMAT_F, energy_pts_stc[i][j].value);\n        }\n        printf(\"\\n\");\n        printf(TABLE_FORMAT_ITEM_NAME, \"Uncertainty:\");\n        for (int j = 0; j < n_n_orbs_pts; j++) {\n          printf(TABLE_FORMAT_F, energy_pts_stc[i][j].uncertainty);\n        }\n        printf(\"\\n\");\n        printf(TABLE_FORMAT_ITEM_NAME, \"EST. energy PT:\");\n        for (int j = 0; j < n_n_orbs_pts; j++) {\n          printf(\n              TABLE_FORMAT_F,\n              energy_pts_stc[i][j].value + energy_pts_dtm[j].value);\n        }\n        printf(\"\\n\");\n        printf(TABLE_FORMAT_ITEM_NAME, \"EST. CORR. energy:\");\n        for (int j = 0; j < n_n_orbs_pts; j++) {\n          const double energy_corr = energy_pts_stc[i][j].value +\n                                     energy_pts_dtm[j].value + energy_var -\n                                     energy_hf;\n          printf(TABLE_FORMAT_F, energy_corr);\n        }\n        printf(\"\\n\");\n      }\n    }\n\n    timer->end();\n\n    if (iteration >= 10 && max_uncert <= target_error) break;\n\n    iteration++;\n  }\n\n  timer->end();\n\n  return energy_pts_stc;\n}\n\ndouble SolverImpl::get_weight(const int i) const {\n  const double coef = abstract_system->coefs[i];\n  const double abs_coef = std::abs(coef);\n  return abs_coef;\n}\n\nSolver* Injector::new_solver(\n    Session* const session,\n    Connections* const connections,\n    AbstractSystem* const abstract_system) {\n  return new SolverImpl(session, connections, abstract_system);\n}\n", "meta": {"hexsha": "4804ddf88092a03708675144057a3deb06ee8dc6", "size": 35381, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/solver/solver.cc", "max_stars_repo_name": "jl2922/hci", "max_stars_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-09-23T17:52:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-01T20:15:01.000Z", "max_issues_repo_path": "src/solver/solver.cc", "max_issues_repo_name": "jl2922/hci", "max_issues_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-09-24T14:29:03.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-24T14:44:12.000Z", "max_forks_repo_path": "src/solver/solver.cc", "max_forks_repo_name": "jl2922/hci", "max_forks_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7895771878, "max_line_length": 80, "alphanum_fraction": 0.6389304994, "num_tokens": 9748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.4035668537353745, "lm_q1q2_score": 0.21280747026296795}}
{"text": "//Copyright (c) 2015 Zachary Kann\n//\n//Permission is hereby granted, free of charge, to any person obtaining a copy\n//of this software and associated documentation files (the \"Software\"), to deal\n//in the Software without restriction, including without limitation the rights\n//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n//copies of the Software, and to permit persons to whom the Software is\n//furnished to do so, subject to the following conditions:\n//\n//The above copyright notice and this permission notice shall be included in all\n//copies or substantial portions of the Software.\n//\n//THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n//SOFTWARE.\n\n// ---\n// Author: Zachary Kann\n\n// A set of functions for calculation of electric field / frequency maps\n// as outlined in the papers of Skinner et al. See, for example, S.M. Gruenbaum,\n// et al. J. Chem. Theory Comput. 2013 9 (7), 3109. These maps are necessary\n// for calculation of vibrational spectra using the methodology  outline in the\n// aforementioned papers.\n\n// Abbreviations:\n//   FTIR = fourier-transform infrared\n//   SFG = sum-frequency generation\n\n#include <armadillo>\n#include \"z_frequency_map.hpp\"\n#include \"z_histogram.hpp\"\n#include \"z_molecule_group.hpp\"\n#include \"z_cx_tcf.hpp\"\n\n#ifndef _Z_INFRARED_MAP_HPP_\n#define _Z_INFRARED_MAP_HPP_\n\nclass InfraredMap:\n  public FrequencyMap {\n public:\n  inline InfraredMap(const MoleculeGroup& group, const Chromophore chromophore,\n                      const double timestep, const int correlation_length = 200)\n      : FrequencyMap(group, chromophore, timestep, correlation_length) {\n    mu_01_ = arma::zeros<arma::cube>(DIMS, steps_guess_, num_chromophores());\n  }\n\n private:\n  arma::cube mu_01_;\n\n  inline void ResizeArrays() {\n    omega_01_.resize(num_chromophores(), steps_guess_);\n    mu_01_.resize(DIMS, steps_guess_, num_chromophores());\n  }\n\n  inline double MuOrAlphaProduct(const int chromophore, const int corr_start,\n                                 const int i_corr) {\n    return arma::dot(mu_01_.slice(chromophore).col(corr_start),\n                     mu_01_.slice(chromophore).col(corr_start+i_corr));\n  }\n\n  // Calculates omega and mu/alpha using the frequency maps.\r\n  void UseMapping(const int chromophore,\n                  const arma::rowvec& box);\n};\n#endif\n", "meta": {"hexsha": "a0e7e00d9917644cce5b1b84e038e0f4b0e23777", "size": 2735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/z_infrared_map.hpp", "max_stars_repo_name": "thekannman/z_infrared", "max_stars_repo_head_hexsha": "a091041ad744d8591e4d9cb98eb7b650950bacaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-06-12T04:49:11.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-12T04:49:11.000Z", "max_issues_repo_path": "include/z_infrared_map.hpp", "max_issues_repo_name": "thekannman/z_infrared", "max_issues_repo_head_hexsha": "a091041ad744d8591e4d9cb98eb7b650950bacaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/z_infrared_map.hpp", "max_forks_repo_name": "thekannman/z_infrared", "max_forks_repo_head_hexsha": "a091041ad744d8591e4d9cb98eb7b650950bacaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.5211267606, "max_line_length": 80, "alphanum_fraction": 0.7341864717, "num_tokens": 649, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.21261925810785234}}
{"text": "#define NPY_NO_DEPRECATED_API NPY_1_11_API_VERSION\n\n#include <iostream>\n#include <stdint.h>\n#include <alloca.h>\n#include <Eigen/Core>\n#include <boost/python.hpp>\n#include <boost/python/numeric.hpp>\n#include <boost/python/ptr.hpp>\n#include <Python.h>\n#include <numpy/ndarrayobject.h>\n//#include <numpy/arrayobject.h>\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace boost::python;\n\n#if PY_VERSION_HEX >= 0x03000000\nvoid *\n#else\nvoid\n#endif\ninit_numpy(){\n    //Py_Initialize;\n    import_array();\n}\n\n//original comment:\n//\"TODO if we aren't outputting gamma, don't need to write it to memory (just\n//need t and t+1), so we can save the stack array for each HMM at the cost of\n//a branch\"\n\n/*struct double_to_python_float\n{\n    static PyObject* convert(double const& d)\n      {\n        return boost::python::incref(\n          boost::python::object(d).ptr());\n      }\n};*/\n\n//numpy scalar converters.\ntemplate <typename T, NPY_TYPES NumPyScalarType>\nstruct enable_numpy_scalar_converter\n{\n  enable_numpy_scalar_converter()\n  {\n    // Required NumPy call in order to use the NumPy C API within another\n    // extension module.\n    // import_array();\n    init_numpy();\n\n    boost::python::converter::registry::push_back(\n      &convertible,\n      &construct,\n      boost::python::type_id<T>());\n  }\n\n  static void* convertible(PyObject* object)\n  {\n    // The object is convertible if all of the following are true:\n    // - is a valid object.\n    // - is a numpy array scalar.\n    // - its descriptor type matches the type for this converter.\n    return (\n      object &&                                                    // Valid\n      PyArray_CheckScalar(object) &&                               // Scalar\n      PyArray_DescrFromScalar(object)->type_num == NumPyScalarType // Match\n    )\n      ? object // The Python object can be converted.\n      : NULL;\n  }\n\n  static void construct(\n    PyObject* object,\n    boost::python::converter::rvalue_from_python_stage1_data* data)\n  {\n    // Obtain a handle to the memory block that the converter has allocated\n    // for the C++ type.\n    namespace python = boost::python;\n    typedef python::converter::rvalue_from_python_storage<T> storage_type;\n    void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;\n\n    // Extract the array scalar type directly into the storage.\n    PyArray_ScalarAsCtype(object, storage);\n\n    // Set convertible to indicate success.\n    data->convertible = storage;\n  }\n};\n\n// TODO openmp version\n\nnumeric::array run(dict& data, dict& model, numeric::array& forward_messages){\n    //TODO: check if parameters are null.\n    //TODO: check that dicts have the required members.\n    //TODO: check that all parameters have the right sizes.\n    //TODO: i'm not sending any error messages.\n\n    numeric::array alldata = extract<numeric::array>(data[\"data\"]); //multidimensional array, so i need to keep extracting arrays.\n    int bigT = len(alldata[0]); //this should be the number of columns in the alldata object. i'm assuming is 2d array.\n    int num_subparts = len(alldata);\n\n    numeric::array allresources = extract<numeric::array>(data[\"resources\"]);\n\n    numeric::array starts = extract<numeric::array>(data[\"starts\"]);\n    int num_sequences = len(starts);\n\n    numeric::array lengths = extract<numeric::array>(data[\"lengths\"]);\n\n    numeric::array learns = extract<numeric::array>(model[\"learns\"]);\n    int num_resources = len(learns);\n\n    numeric::array forgets = extract<numeric::array>(model[\"forgets\"]);\n\n    numeric::array guesses = extract<numeric::array>(model[\"guesses\"]);\n\n    numeric::array slips = extract<numeric::array>(model[\"slips\"]);\n\n    double prior = extract<double>(model[\"prior\"]);\n\n    Array2d initial_distn;\n    initial_distn << 1-prior, prior;\n\n    MatrixXd As(2,2*num_resources);\n    for (int n=0; n<num_resources; n++) {\n        double learn = extract<double>(learns[n]);\n        double forget = extract<double>(forgets[n]);\n        As.col(2*n) << 1-learn, learn;\n        As.col(2*n+1) << forget, 1-forget;\n    }\n\n    // forward messages\n    //numeric::array all_forward_messages = extract<numeric::array>(forward_messages);\n    double * forward_messages_temp = new double[2*bigT];\n    for (int i=0; i<2; i++) {\n        for (int j=0; j<bigT; j++){\n            forward_messages_temp[i* bigT +j] = extract<double>(forward_messages[i][j]);\n        }\n    }\n\n    //// outputs\n\n    double * all_predictions = new double[2*bigT];\n    Map<Array2Xd,Aligned> predictions(all_predictions,2,bigT);\n\n    /* COMPUTATION */\n\n    for (int sequence_index=0; sequence_index < num_sequences; sequence_index++) {\n        // NOTE: -1 because Matlab indexing starts at 1\n        int64_t sequence_start = extract<int64_t>(starts[sequence_index]) - 1;\n        int64_t T = extract<int64_t>(lengths[sequence_index]);\n\n        //int16_t *resources = allresources + sequence_start;\n        Map<MatrixXd> forward_messages(forward_messages_temp + 2*sequence_start,2,T);\n        Map<MatrixXd> predictions(all_predictions + 2*sequence_start,2,T);\n\n        predictions.col(0) = initial_distn;\n        for (int t=0; t<T-1; t++) {\n            int64_t resources_temp = extract<int64_t>(allresources[sequence_start+t]);\n            predictions.col(t+1) = As.block(0,2*(resources_temp-1),2,2) * forward_messages.col(t);\n        }\n    }\n\n    npy_intp all_predictions_dims[2] = {2,bigT}; //TODO: just put directly this array into the PyArray_SimpleNewFromData function?\n    PyObject * all_predictions_pyObj = PyArray_New(&PyArray_Type, 2, all_predictions_dims, NPY_DOUBLE, NULL, all_predictions, 0, NPY_ARRAY_CARRAY, NULL);\n    boost::python::handle<> all_predictions_handle( all_predictions_pyObj );\n    boost::python::numeric::array all_predictions_arr( all_predictions_handle );\n\n    delete all_predictions;\n    delete forward_messages_temp;\n\n    return(all_predictions_arr);\n}\n\nBOOST_PYTHON_MODULE(predict_onestep_states){\n    //import_array();\n    init_numpy();\n    numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n    //to_python_converter<double, double_to_python_float>();\n    enable_numpy_scalar_converter<boost::int8_t, NPY_INT8>();\n    enable_numpy_scalar_converter<boost::int16_t, NPY_INT16>();\n    enable_numpy_scalar_converter<boost::int32_t, NPY_INT32>();\n    enable_numpy_scalar_converter<boost::int64_t, NPY_INT64>();\n\n    def(\"run\", run);\n\n}\n\n", "meta": {"hexsha": "884a3cbbea555a1b7deabfe439098913178f34ee", "size": 6356, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-cpp/.DEPRECATED/predict_onestep_states.cpp", "max_stars_repo_name": "themrzmaster/pyBKT", "max_stars_repo_head_hexsha": "f004ae72e0e09c59de7c8d63040e7f90c0b43c0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-13T02:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-13T02:10:34.000Z", "max_issues_repo_path": "source-cpp/.DEPRECATED/predict_onestep_states.cpp", "max_issues_repo_name": "themrzmaster/pyBKT", "max_issues_repo_head_hexsha": "f004ae72e0e09c59de7c8d63040e7f90c0b43c0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source-cpp/.DEPRECATED/predict_onestep_states.cpp", "max_forks_repo_name": "themrzmaster/pyBKT", "max_forks_repo_head_hexsha": "f004ae72e0e09c59de7c8d63040e7f90c0b43c0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4526315789, "max_line_length": 153, "alphanum_fraction": 0.6787287602, "num_tokens": 1553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.3702253925955866, "lm_q1q2_score": 0.2123903136227163}}
{"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#ifndef CorriasBuistICCModified_HPP_\n#define CorriasBuistICCModified_HPP_\n\n#include \"ChasteSerialization.hpp\"\n#include <boost/serialization/base_object.hpp>\n#include \"AbstractCardiacCell.hpp\"\n#include \"AbstractStimulusFunction.hpp\"\n\n/**\n * This class is a modified version of the  model of a gastric\n * Interstitial Cell of Cajal.\n *\n * Reference publication is:\n *\n * Corrias A, Buist ML.\n * \"Quantitative cellular description of gastric slow wave activity.\"\n * Am J Physiol Gastrointest Liver Physiol. 2008 Apr;294(4):G989-95. Epub 2008 Feb 14.\n *\n * Modifications include:\n * - simplified mitochondria dynamics (assumed mitochondrial potential is almost constant\n * - ability to set K+ channels-affecting CO concentrations\n * - ability to deflect a fraction of VDDR channels into the pacemaker unit.\n */\nclass CorriasBuistICCModified : public AbstractCardiacCell\n{\n    friend class boost::serialization::access;\n    /**\n     * Boost Serialization method for archiving/checkpointing.\n     * Archives the object and its member variables.\n     *\n     * @param archive  The boost archive.\n     * @param version  The current version of this class.\n     */\n    template<class Archive>\n    void serialize(Archive & archive, const unsigned int version)\n    {\n        archive & boost::serialization::base_object<AbstractCardiacCell >(*this);\n        archive &  mFractionOfVDDRInPU;\n        archive &  mIP3Concentration;\n        archive &  mScaleFactorSerca;\n        archive &  mScaleFactorCarbonMonoxide;\n    }\n\nprivate:\n\n    /**fraction of VDDR channel in the PU, initialised to zero*/\n    double mFractionOfVDDRInPU;\n    /**the IP3 concentration, defaults to 0.0006 mM*/\n    double mIP3Concentration;\n    /**scales the flux through the SERCA pump.1.0-> control. 0.0-> blocked*/\n    double mScaleFactorSerca;\n    /**\n     * Scale factor for CO-affected currents\n     * Note that this the number that multiply the currents, hence it is not [CO],\n     * but a function of [CO] (for example, 2.8*[CO] - 0.1)\n     */\n    double mScaleFactorCarbonMonoxide;\n\n    /* Concentrations */\n    double Ca_o;/**<  mM */\n    double Cl_o;/**<  mM */\n    double K_o;/**<  mM */\n    double Na_o;/**<  mM */\n\n    /* Nernst parameters */\n    double R;/**<  pJ/nmol/K */\n    double T;/**<  degK */\n    double F;/**<  nC/nmol */\n    double FoRT;/**<  1/mV */\n    double RToF;/**<  mV */\n\n    double  Cm ;/**<  pF */\n    double Asurf_in_cm_square;/**< cm2 */\n    double  Asurf ;/**<  mm2 */\n    double  Cl_i  ;/**<  mM */\n    double  K_i   ;/**<  mM */\n    double  Na_i    ;/**<  mM */\n    double  P_cyto;/**<  dim */\n    double  Vol  ;/**<  mm3 */\n    double  fc ;/**<  dim */\n    double  fe  ;/**<  dim */\n    double  fm ;/**<  dim */\n    double  Q10Ca ;/**<  dim */\n    double  Q10K ;/**<  dim */\n    double  Q10Na  ;/**<  dim */\n    double  T_exp  ;/**<  degK */\n\n    double  G_max_BK  ;/**<  nS */\n    double  G_max_CaCl  ;/**<  nS */\n    double  G_max_ERG  ;/**<  nS */\n    double  G_max_Ltype ;/**<  nS */\n    double  G_max_NSCC  ;/**<  nS */\n    double  G_max_Na ;/**<  nS */\n    double  G_max_VDDR ;/**<  nS */\n    double  G_max_bk    ;/**<  nS */\n    double  G_max_kv11 ;/**<  nS */\n\n\n    double  J_max_PMCA  ;/**<  mM/ms   (mM/s) * 1/1000 (s/ms) = mM/ms */\n    double  J_max_PMCA_PU ;/**<  mM/ms   (mM/s) * 1/1000 (s/ms) = mM/ms */\n    double  J_ERleak   ;/**<  1/ms    (1/s) * 1/1000 (ms/s) = 1/ms */\n    double  J_max_leak ;/**<  1/ms    (1/s) * 1/1000 (ms/s) = 1/ms */\n    double  Jmax_IP3  ;/**<  1/ms    (1/s) * 1/1000 (ms/s) = 1/ms */\n    double  Jmax_NaCa ;/**<  mM/ms   (mM/s) * 1/1000 (s/ms) = mM/ms */\n    double  Jmax_serca   ;/**<  mM/ms   (mM/s) * 1/1000 (s/ms) = mM/ms */\n    double  Jmax_uni    ;/**<  1/ms    (1/s) * 1/1000 (ms/s) = 1/ms */\n\n    double  NaPerm_o_Kperm   ;/**<  dim */\n    double  L    ;/**<  dim */\n    double  P_ER  ;/**<  dim */\n    double  P_PU   ;/**<  dim */\n    double  P_mito ;/**<  dim */\n    double  b ;/**<  dim */\n    double  na ;/**<  dim */\n\n    double  K_Ca   ;/**<  mM */\n    double  K_Na ;/**<  mM */\n    double  K_act ;/**<  mM */\n    double  K_trans   ;/**<  mM */\n    double  k_serca ;/**<  mM */\n    double  conc   ;/**<  mM */\n    double  d_ACT   ;/**<  mM */\n    double  d_IP3 ;/**<  mM */\n    double  d_INH  ;/**<  mM */\n\n    double  tau_d_CaCl;/**<  ms(s) * 1000 (ms/s) = ms */\n    double  tau_d_NSCC ;/**<  ms(s) * 1000 (ms/s) = ms */\n    double  tauh;/**<  ms(s ) * 1000 (ms/s) = ms */\n\n    double  deltaPsi_B;/**<  mV */\n    double  deltaPsi_star;/**<  mV */\n    double  deltaPsi;/**<  mV */\n\n\n     /////////////////////\n     //Calculated constants\n     ////////////////////\n     /* Volumes */\n     double V_cyto;              /**<  mm3 */\n     double V_ER;                /**<  mm3 */\n     double V_MITO;              /**<  mm3 */\n     double V_PU;                /**<  mm3 */\n\n     /* Temperature corrections */\n     double T_correction_Ca;     /**<  dim */\n     double T_correction_K;      /**<  dim */\n     double T_correction_Na;     /**<  dim */\n     double T_correction_BK;     /**<  uA/mm2 */\n\n     /* Nernst potentials */\n     double E_Na;                /**<  mV */\n     double E_K;                 /**<  mV */\n     double E_Cl;                /**<  mV */\n     double E_NSCC;              /**<  mV */\n\n     /* Activation gate time constants */\n     double tau_d_ERG;           /**<  ms */\n     double tau_d_Ltype;         /**<  ms */\n     double tau_d_Na;            /**<  ms */\n     double tau_d_VDDR;          /**<  ms */\n     double tau_d_kv11;          /**<  ms */\n\n     /* Inactivation gate time constants */\n     double tau_f_Ltype;         /**<  ms */\n     double tau_f_Na;            /**<  ms */\n     double tau_f_VDDR;          /**<  ms */\n     double tau_f_ca_Ltype;      /**<  ms */\n     double tau_f_kv11;          /**<  ms */\n\n     /* Speed ups */\n     double e2FoRTdPsiMdPsiS;/**< speed-up constant*/\n     double ebFoRTdPsiMdPsiS;/**< speed-up constant*/\n\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     CorriasBuistICCModified(boost::shared_ptr<AbstractIvpOdeSolver> pSolver, boost::shared_ptr<AbstractStimulusFunction> pIntracellularStimulus);\n\n    /**\n     * Destructor\n     */\n    ~CorriasBuistICCModified();\n\n    /**\n     * Now empty\n     */\n    void VerifyStateVariables();\n\n    /**\n     * Calculates the ionic current\n     *\n     * @param pStateVariables the state variables of this model\n     * @return the total ionic current\n     */\n    double GetIIonic(const std::vector<double>* pStateVariables=NULL);\n\n    /**\n     * Compute the RHS of the FitHugh-Nagumo system of ODEs\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<double>& rY, std::vector<double>& rDY);\n\n    /**\n     * Sets the fraction of VDDR channels in the Pacemaker unit\n     *\n     * @param fraction the fraction of VDDr channels in the PU\n     */\n    void SetFractionOfVDDRInPU(double fraction);\n\n    /**\n     * Set the value of IP3 concentration in the cell\n     *\n     * @param concentration the concentration of IP3\n     */\n    void SetIP3Concentration(double concentration);\n\n    /**\n     * Set a multiplying factor for the influx of Ca2+ into the Er via the SERCA pump (set to zero will block the SW generation)\n     *\n     * @param scaleFactor the scale factor (=0 --> no Ca2+ uptake into the ER and, consequently, no SW)\n     */\n    void SetSercaPumpScaleFactor(double scaleFactor);\n\n    /**\n     * Set the carbon monoxide scale factor.\n     * This will multiply the following currents: I_kv11, I_ERG, Ibk\n     *\n     * @param scaleFactor the scale factor that multiply the currents.\n     */\n    void SetCarbonMonoxideScaleFactor(double scaleFactor);\n\n    /**\n     * @return the Carbon Monoxide scale factor\n     */\n    double GetCarbonMonoxideScaleFactor();\n};\n\n\n// Needs to be included last\n#include \"SerializationExportWrapper.hpp\"\nCHASTE_CLASS_EXPORT(CorriasBuistICCModified)\n\nnamespace boost\n{\n    namespace serialization\n    {\n        template<class Archive>\n        inline void save_construct_data(\n            Archive & ar, const CorriasBuistICCModified * t, const unsigned int fileVersion)\n        {\n            const boost::shared_ptr<AbstractIvpOdeSolver> p_solver = t->GetSolver();\n            const boost::shared_ptr<AbstractStimulusFunction> p_stimulus = t->GetStimulusFunction();\n            ar << p_solver;\n            ar << p_stimulus;\n        }\n\n        template<class Archive>\n        inline void load_construct_data(\n            Archive & ar, CorriasBuistICCModified * t, const unsigned int fileVersion)\n        {\n            boost::shared_ptr<AbstractIvpOdeSolver> p_solver;\n            boost::shared_ptr<AbstractStimulusFunction> p_stimulus;\n            ar >> p_solver;\n            ar >> p_stimulus;\n            ::new(t)CorriasBuistICCModified(p_solver, p_stimulus);\n        }\n    }\n}\n\n#endif // CorriasBuistICCModified_HPP_\n", "meta": {"hexsha": "f511d5b188212a33037b89d1c21b21cf2a092c75", "size": 10841, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "heart/src/odes/ionicmodels/noncardiac/CorriasBuistICCModified.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/odes/ionicmodels/noncardiac/CorriasBuistICCModified.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/odes/ionicmodels/noncardiac/CorriasBuistICCModified.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": 34.525477707, "max_line_length": 146, "alphanum_fraction": 0.6128585924, "num_tokens": 2894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2123836911449199}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Sat 27 Aug 2016 12:48:12\n\n#ifndef MSSMatMGUT_TWO_SCALE_LOW_SCALE_CONSTRAINT_H\n#define MSSMatMGUT_TWO_SCALE_LOW_SCALE_CONSTRAINT_H\n\n#include \"MSSMatMGUT_low_scale_constraint.hpp\"\n#include \"MSSMatMGUT_input_parameters.hpp\"\n#include \"two_scale_constraint.hpp\"\n#include \"lowe.h\"\n#include <Eigen/Core>\n\nnamespace flexiblesusy {\n\ntemplate <class T>\nclass MSSMatMGUT;\n\nclass Two_scale;\n\ntemplate<>\nclass MSSMatMGUT_low_scale_constraint<Two_scale> : public Constraint<Two_scale> {\npublic:\n   MSSMatMGUT_low_scale_constraint();\n   MSSMatMGUT_low_scale_constraint(MSSMatMGUT<Two_scale>*, const softsusy::QedQcd&);\n   virtual ~MSSMatMGUT_low_scale_constraint();\n   virtual void apply();\n   virtual double get_scale() const;\n   virtual void set_model(Two_scale_model*);\n\n   void clear();\n   const Eigen::Matrix<std::complex<double>,3,3>& get_ckm();\n   const Eigen::Matrix<std::complex<double>,3,3>& get_pmns();\n   double get_initial_scale_guess() const;\n   void initialize();\n   const softsusy::QedQcd& get_sm_parameters() const;\n   void set_sm_parameters(const softsusy::QedQcd&);\n   void set_threshold_corrections_loop_order(unsigned); ///< threshold corrections loop order\n\nprivate:\n   double scale;\n   double initial_scale_guess;\n   MSSMatMGUT<Two_scale>* model;\n   softsusy::QedQcd qedqcd;\n   Eigen::Matrix<std::complex<double>,3,3> ckm;\n   Eigen::Matrix<std::complex<double>,3,3> pmns;\n   Eigen::Matrix<double,3,3> neutrinoDRbar;\n   double MWDRbar;\n   double MZDRbar;\n   double AlphaS;\n   double EDRbar;\n   double ThetaWDRbar;\n   double new_g1, new_g2, new_g3;\n   double self_energy_w_at_mw;\n   unsigned threshold_corrections_loop_order; ///< threshold corrections loop order\n\n   double calculate_theta_w(double);\n   void calculate_threshold_corrections();\n   void calculate_DRbar_gauge_couplings();\n   void calculate_DRbar_yukawa_couplings();\n   void calculate_Yu_DRbar();\n   void calculate_Yd_DRbar();\n   void calculate_Ye_DRbar();\n   void calculate_MNeutrino_DRbar();\n   double calculate_delta_alpha_em(double) const;\n   double calculate_delta_alpha_s(double) const;\n   void recalculate_mw_pole();\n   void update_scale();\n};\n\n} // namespace flexiblesusy\n\n#endif\n", "meta": {"hexsha": "401e269e386d79efb6d95860248cf7ba4d5b6724", "size": 3015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMatMGUT/MSSMatMGUT_two_scale_low_scale_constraint.hpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMatMGUT/MSSMatMGUT_two_scale_low_scale_constraint.hpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/MSSMatMGUT/MSSMatMGUT_two_scale_low_scale_constraint.hpp", "max_forks_repo_name": "aaronvincent/gambit_aaron", "max_forks_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5, "max_line_length": 93, "alphanum_fraction": 0.7266998342, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.21227006104076881}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2020 Nikita Kaskov <nbering@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_BLOCK_SHACAL2_HPP\n#define CRYPTO3_BLOCK_SHACAL2_HPP\n\n#include <nil/crypto3/block/detail/shacal/shacal2_policy.hpp>\n\n#include <nil/crypto3/block/detail/block_stream_processor.hpp>\n#include <nil/crypto3/block/detail/cipher_modes.hpp>\n\n#include <boost/static_assert.hpp>\n\n#ifdef CRYPTO3_BLOCK_SHOW_PROGRESS\n#include <cstdio>\n#endif\n\nnamespace nil {\n    namespace crypto3 {\n        namespace block {\n\n            /*!\n             * @brief Shacal2. Merkle-Damgård construction foundation for\n             * @ref nil::crypto3::hashes::sha2 \"SHA2\" hashes. Accepts\n             * up to a 512-bit key. Fast and seemingly very secure, but obscure.\n             * Standardized by NESSIE.\n             *\n             * @ingroup block\n             *\n             * Encrypt implemented directly from the SHA standard as found at\n             * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf\n             *\n             * Decrypt is a straight-forward inverse\n             *\n             * In SHA terminology:\n             * - plaintext = H^(i-1)\n             * - ciphertext = H^(i)\n             * - key = M^(i)\n             * - schedule = W\n             *\n             * @tparam BlockBits Block cipher block bits. Available values are: 256, 512\n             */\n            template<std::size_t BlockBits>\n            class shacal2 {\n\n                typedef detail::shacal2_policy<BlockBits> policy_type;\n\n            public:\n                constexpr static const std::size_t version = BlockBits;\n\n                constexpr static const std::size_t word_bits = policy_type::word_bits;\n                typedef typename policy_type::word_type word_type;\n\n                constexpr static const std::size_t key_bits = policy_type::key_bits;\n                constexpr static const std::size_t key_words = policy_type::key_words;\n                typedef typename policy_type::key_type key_type;\n\n                constexpr static const std::size_t block_bits = policy_type::block_bits;\n                constexpr static const std::size_t block_words = policy_type::block_words;\n                typedef typename policy_type::block_type block_type;\n\n                static const std::size_t rounds = policy_type::rounds;\n                typedef typename policy_type::key_schedule_type key_schedule_type;\n\n                template<class Mode, typename StateAccumulator, std::size_t ValueBits>\n                struct stream_processor {\n                    struct params_type {\n\n                        constexpr static const std::size_t value_bits = ValueBits;\n                        constexpr static const std::size_t length_bits = policy_type::word_bits * 2;\n                    };\n\n                    typedef block_stream_processor<Mode, StateAccumulator, params_type> type;\n                };\n\n                typedef typename stream_endian::little_octet_big_bit endian_type;\n\n                shacal2(const key_type &key) : schedule(build_schedule(key)) {\n                }\n\n                shacal2(key_schedule_type s) : schedule((prepare_schedule(s), s)) {\n                }\n\n                block_type encrypt(block_type const &plaintext) const {\n                    return encrypt_block(plaintext);\n                }\n\n                inline block_type decrypt(const block_type &ciphertext) const {\n                    return decrypt_block(ciphertext);\n                }\n\n            protected:\n                const key_schedule_type schedule;\n\n                static key_schedule_type build_schedule(const key_type &key) {\n                    // Copy key into beginning of round_constants_words\n                    key_schedule_type schedule;\n                    for (unsigned t = 0; t < key_words; ++t) {\n                        schedule[t] = key[t];\n                    }\n                    prepare_schedule(schedule);\n                    return schedule;\n                }\n\n                static void prepare_schedule(key_schedule_type &schedule) {\n                    for (unsigned t = key_words; t < rounds; ++t) {\n                        schedule[t] = policy_type::sigma_1(schedule[t - 2]) + schedule[t - 7] +\n                                      policy_type::sigma_0(schedule[t - 15]) + schedule[t - 16];\n                    }\n                }\n\n                block_type encrypt_block(const block_type &plaintext) const {\n                    return encrypt_block(schedule, plaintext);\n                }\n\n                inline static block_type encrypt_block(const key_schedule_type &schedule, block_type const &plaintext) {\n\n                    // Initialize working variables with block\n                    word_type a = plaintext[0], b = plaintext[1], c = plaintext[2], d = plaintext[3], e = plaintext[4],\n                              f = plaintext[5], g = plaintext[6], h = plaintext[7];\n\n                    // Encipher block\n#ifdef CRYPTO3_BLOCK_NO_OPTIMIZATION\n\n                    for (unsigned t = 0; t < rounds; ++t) {\n                        word_type T1 = h + policy_type::Sigma_1(e) + policy_type::Ch(e, f, g) +\n                                       policy_type::constants[t] + round_constants_words[t];\n                        word_type T2 = policy_type::Sigma_0(a) + policy_type::Maj(a, b, c);\n\n                        h = g;\n                        g = f;\n                        f = e;\n                        e = d + T1;\n                        d = c;\n                        c = b;\n                        b = a;\n                        a = T1 + T2;\n                    }\n\n#else    // CRYPTO3_BLOCK_NO_OPTIMIZATION\n\n                    BOOST_STATIC_ASSERT(rounds % block_words == 0);\n                    for (unsigned t = 0; t < rounds;) {\n                        for (int n = block_words; n--; ++t) {\n                            word_type T1 = h + policy_type::Sigma_1(e) + policy_type::Ch(e, f, g) +\n                                           policy_type::constants[t] + schedule[t];\n                            word_type T2 = policy_type::Sigma_0(a) + policy_type::Maj(a, b, c);\n\n                            h = g;\n                            g = f;\n                            f = e;\n                            e = d + T1;\n                            d = c;\n                            c = b;\n                            b = a;\n                            a = T1 + T2;\n                        }\n                    }\n\n#endif\n\n                    return {{a, b, c, d, e, f, g, h}};\n                }\n\n                block_type decrypt_block(const block_type &ciphertext) const {\n                    return decrypt_block(schedule, ciphertext);\n                }\n\n                inline static block_type decrypt_block(const key_schedule_type &schedule,\n                                                       const block_type &ciphertext) {\n                    // Initialize working variables with block\n                    word_type a = ciphertext[0], b = ciphertext[1], c = ciphertext[2], d = ciphertext[3],\n                              e = ciphertext[4], f = ciphertext[5], g = ciphertext[6], h = ciphertext[7];\n\n                    // Decipher block\n                    for (unsigned t = rounds; t--;) {\n                        word_type T2 = policy_type::Sigma_0(b) + policy_type::Maj(b, c, d);\n                        word_type T1 = a - T2;\n\n                        a = b;\n                        b = c;\n                        c = d;\n                        d = e - T1;\n                        e = f;\n                        f = g;\n                        g = h;\n                        h = T1 - policy_type::Sigma_1(e) - policy_type::Ch(e, f, g) - policy_type::constants[t] -\n                            schedule[t];\n                    }\n                    return {{a, b, c, d, e, f, g, h}};\n                }\n            };\n        }    // namespace block\n    }        // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_BLOCK_CIPHERS_SHACAL2_HPP\n", "meta": {"hexsha": "d4c9c25489d6be9d8e4269523e1533350827a9be", "size": 9307, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/block/shacal2.hpp", "max_stars_repo_name": "NilFoundation/crypto3-block", "max_stars_repo_head_hexsha": "94f9cc42ac0fa62c5ee54e7d678abf48ffa9eec5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-14T18:09:38.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T18:09:38.000Z", "max_issues_repo_path": "include/nil/crypto3/block/shacal2.hpp", "max_issues_repo_name": "tonlabs/crypto3-block", "max_issues_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T23:11:20.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-16T18:04:20.000Z", "max_forks_repo_path": "include/nil/crypto3/block/shacal2.hpp", "max_forks_repo_name": "tonlabs/crypto3-block", "max_forks_repo_head_hexsha": "d7eede022f6130797d28bc39eb312bff9afebf07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T15:37:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-26T21:47:05.000Z", "avg_line_length": 42.3045454545, "max_line_length": 120, "alphanum_fraction": 0.5084345117, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.37754067580180184, "lm_q1q2_score": 0.21224449606431645}}
{"text": "// Copyright (c) 2020 CNES\n//\n// All rights reserved. Use of this source code is governed by a\n// BSD-style license that can be found in the LICENSE file.\n#pragma once\n#include <Eigen/Core>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <stdexcept>\n#include \"pyinterp/detail/math.hpp\"\n\nnamespace pyinterp::detail::axis::container {\n\n/// Abstraction of a container of values representing a mathematical axis.\n///\n/// @tparam T type of data handled by this container\ntemplate <typename T>\nclass Abstract {\n public:\n  /// Default constructor\n  Abstract() = default;\n\n  /// Default destructor\n  virtual ~Abstract() = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Abstract(const Abstract& rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Abstract(Abstract&& rhs) = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Abstract& rhs) -> Abstract& = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Abstract&& rhs) -> Abstract& = default;\n\n  /// Returns true if the data is arranged in ascending order.\n  [[nodiscard]] inline auto is_ascending() const -> bool {\n    return is_ascending_;\n  }\n\n  /// Reverse the order of elements in this axis\n  virtual auto flip() -> void = 0;\n\n  /// Checks thats axis is monotonic\n  [[nodiscard]] virtual auto is_monotonic() const -> bool { return true; }\n\n  /// Get the ith coordinate value.\n  ///\n  /// @param index which coordinate. Between 0 and size()-1 inclusive\n  /// @return coordinate value\n  [[nodiscard]] virtual auto coordinate_value(size_t index) const -> T = 0;\n\n  /// Get the minimum coordinate value.\n  ///\n  /// @return minimum coordinate value\n  [[nodiscard]] virtual auto min_value() const -> T = 0;\n\n  /// Get the maximum coordinate value.\n  ///\n  /// @return maximum coordinate value\n  [[nodiscard]] virtual auto max_value() const -> T = 0;\n\n  /// Get the number of values for this axis\n  ///\n  /// @return the number of values\n  [[nodiscard]] virtual auto size() const -> int64_t = 0;\n\n  /// Gets the first element in the container\n  ///\n  /// @return the first element\n  [[nodiscard]] virtual auto front() const -> T = 0;\n\n  /// Gets the last element in the container\n  ///\n  /// @return the last element\n  [[nodiscard]] virtual auto back() const -> T = 0;\n\n  /// Search for the index corresponding to the requested value.\n  ///\n  /// @param coordinate position in this coordinate system\n  /// @param bounded if true, returns \"-1\" if the value is located outside this\n  /// coordinate system, otherwise the value of the first element if the value\n  /// is located before, or the value of the last element of this container if\n  /// the requested value is located after.\n  /// @return index of the requested value it or -1 if outside this coordinate\n  /// system area.\n  [[nodiscard]] virtual auto find_index(T coordinate, bool bounded) const\n      -> int64_t = 0;\n\n  /// compare two variables instances\n  ///\n  /// @param rhs A variable to compare\n  /// @return if variables are equals\n  virtual auto operator==(const Abstract& rhs) const -> bool = 0;\n\n protected:\n  /// Indicates whether the data is stored in the ascending order.\n  bool is_ascending_{true};\n\n  /// Calculate if the data is arranged in ascending order.\n  [[nodiscard]] inline auto calculate_is_ascending() const -> bool {\n    return size() < 2 ? true : coordinate_value(0) < coordinate_value(1);\n  }\n};\n\n/// Represents a container for an undefined axis\n///\n/// @tparam T type of data handled by this container\ntemplate <typename T>\nclass Undefined : public Abstract<T> {\n public:\n  /// Default constructor\n  Undefined() = default;\n\n  /// Default destructor\n  ~Undefined() override = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Undefined(const Undefined& rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Undefined(Undefined&& rhs) = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Undefined& rhs) -> Undefined& = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Undefined&& rhs) -> Undefined& = default;\n\n  /// @copydoc Abstract::flip()\n  auto flip() -> void override {}\n\n  /// @copydoc Abstract::coordinate_value(const size_t) const\n  [[nodiscard]] inline auto coordinate_value(const size_t /* index */) const\n      noexcept -> T override {\n    return math::Fill<T>::value();\n  }\n\n  /// @copydoc Abstract::min_value() const\n  [[nodiscard]] inline auto min_value() const noexcept -> T override {\n    return coordinate_value(0);\n  }\n\n  /// @copydoc Abstract::max_value() const\n  [[nodiscard]] inline auto max_value() const noexcept -> T override {\n    return coordinate_value(0);\n  }\n\n  /// @copydoc Abstract::size() const\n  [[nodiscard]] inline auto size() const noexcept -> int64_t override {\n    return 0;\n  }\n\n  /// @copydoc Abstract::front() const\n  [[nodiscard]] inline auto front() const noexcept -> T override {\n    return coordinate_value(0);\n  }\n\n  /// @copydoc Abstract::back() const\n  [[nodiscard]] inline auto back() const noexcept -> T override {\n    return coordinate_value(0);\n  }\n\n  /// @copydoc Abstract::find_index(double,bool) const\n  inline int64_t find_index(T /* coordinate */,\n                            bool /* bounded */) const  /// NOLINT\n      noexcept override {\n    return -1;\n  }\n\n  /// @copydoc Abstract::operator==(const Abstract&) const\n  inline auto operator==(const Abstract<T>& rhs) const noexcept\n      -> bool override {\n    return dynamic_cast<const Undefined<T>*>(&rhs) != nullptr;\n  }\n};\n\n/// Represents a container for an irregularly spaced axis\n///\n/// @tparam T type of data handled by this container\ntemplate <typename T>\nclass Irregular : public Abstract<T> {\n public:\n  /// Creation of a container representing an irregularly spaced coordinate\n  /// system.\n  ///\n  /// @param points axis values\n  explicit Irregular(Eigen::Matrix<T, Eigen::Dynamic, 1> points)\n      : points_(std::move(points)) {\n    if (points_.size() == 0) {\n      throw std::invalid_argument(\"unable to create an empty container.\");\n    }\n    this->is_ascending_ = this->calculate_is_ascending();\n    make_edges();\n  }\n\n  /// Destructor\n  ~Irregular() override = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Irregular(const Irregular& rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Irregular(Irregular&& rhs) = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Irregular& rhs) -> Irregular& = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Irregular&& rhs) -> Irregular& = default;\n\n  /// @copydoc Abstract::flip()\n  auto flip() -> void override {\n    std::reverse(points_.data(), points_.data() + points_.size());\n    this->is_ascending_ = !this->is_ascending_;\n    make_edges();\n  }\n\n  /// @copydoc Abstract::is_monotonic() const\n  [[nodiscard]] inline auto is_monotonic() const noexcept -> bool override {\n    if (this->is_ascending_) {\n      return std::is_sorted(points_.data(), points_.data() + points_.size());\n    }\n    return std::is_sorted(points_.data(), points_.data() + points_.size(),\n                          std::greater<>());\n  };\n\n  /// @copydoc Abstract::coordinate_value(const size_t) const\n  [[nodiscard]] inline auto coordinate_value(const size_t index) const\n      -> T override {\n    return points_[index];\n  }\n\n  /// @copydoc Abstract::min_value() const\n  [[nodiscard]] inline auto min_value() const -> T override {\n    return this->is_ascending_ ? front() : back();\n  }\n\n  /// @copydoc Abstract::max_value() const\n  [[nodiscard]] inline auto max_value() const -> T override {\n    return this->is_ascending_ ? back() : front();\n  }\n\n  /// @copydoc Abstract::size() const\n  [[nodiscard]] inline auto size() const noexcept -> int64_t override {\n    return points_.size();\n  }\n\n  /// @copydoc Abstract::front() const\n  [[nodiscard]] inline auto front() const -> T override { return points_[0]; }\n\n  /// @copydoc Abstract::back() const\n  [[nodiscard]] inline auto back() const -> T override {\n    return points_[points_.size() - 1];\n  }\n\n  /// @copydoc Abstract::find_index(double,bool) const\n  [[nodiscard]] auto find_index(T coordinate, bool bounded) const\n      -> int64_t override {\n    int64_t low = 0;\n    int64_t mid = 0;\n    int64_t high = size();\n\n    if (this->is_ascending_) {\n      if (coordinate < edges_[0]) {\n        return bounded ? 0 : -1;\n      }\n\n      if (coordinate > edges_[edges_.size() - 1]) {\n        return bounded ? high - 1 : -1;\n      }\n\n      while (high > low + 1) {\n        // low and high are strictly positive\n        mid = (low + high) >> 1;  // NOLINT\n        auto value = edges_[mid];\n\n        if (value == coordinate) {\n          return mid;\n        }\n        value < coordinate ? low = mid : high = mid;\n      }\n      return low;\n    }\n\n    if (coordinate < edges_[edges_.size() - 1]) {\n      return bounded ? high - 1 : -1;\n    }\n\n    if (coordinate > edges_[0]) {\n      return bounded ? 0 : -1;\n    }\n\n    while (high > low + 1) {\n      // low and high are strictly positive\n      mid = (low + high) >> 1;  // NOLINT\n      auto value = edges_[mid];\n\n      if (value == coordinate) {\n        return mid;\n      }\n      value < coordinate ? high = mid : low = mid;\n    }\n    return low;\n  }\n\n  /// @copydoc Abstract::operator==(const Abstract&) const\n  auto operator==(const Abstract<T>& rhs) const noexcept -> bool override {\n    const auto ptr = dynamic_cast<const Irregular<T>*>(&rhs);\n    if (ptr != nullptr) {\n      return ptr->points_.size() == points_.size() && ptr->points_ == points_;\n    }\n    return false;\n  }\n\n private:\n  Eigen::Matrix<T, Eigen::Dynamic, 1> points_{};\n  Eigen::Matrix<T, Eigen::Dynamic, 1> edges_{};\n\n  /// Computes the edges, if the axis data are not spaced regularly.\n  void make_edges() {\n    auto n = points_.size();\n    edges_.resize(n + 1);\n\n    for (Eigen::Index ix = 1; ix < n; ++ix) {\n      edges_[ix] = (points_[ix - 1] + points_[ix]) / 2;\n    }\n\n    edges_[0] = 2 * points_[0] - edges_[1];\n    edges_[n] = 2 * points_[n - 1] - edges_[n - 1];\n  }\n};\n\n/// Represents a container for an regularly spaced axis\n///\n/// @tparam T type of data handled by this container\ntemplate <typename T>\nclass Regular : public Abstract<T> {\n public:\n  /// Create a container from evenly spaced numbers over a specified\n  /// interval.\n  ///\n  /// @param start the starting value of the sequence\n  /// @param stop the end value of the sequence\n  /// @param num number of samples in the container\n  Regular(const T start, const T stop, const T num)\n      : size_(static_cast<int64_t>(num)), start_(start) {\n    if (num == 0) {\n      throw std::invalid_argument(\"unable to create an empty container.\");\n    }\n    step_ = num == 1 ? stop - start : (stop - start) / (num - 1);\n    // The inverse step of this axis is stored in order to optimize the search\n    // for an index for a given value by avoiding a division.\n    inv_step_ = 1.0 / step_;\n    this->is_ascending_ = this->calculate_is_ascending();\n  }\n\n  /// Destructor\n  ~Regular() override = default;\n\n  /// Copy constructor\n  ///\n  /// @param rhs right value\n  Regular(const Regular& rhs) = default;\n\n  /// Move constructor\n  ///\n  /// @param rhs right value\n  Regular(Regular&& rhs) = default;\n\n  /// Copy assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(const Regular& rhs) -> Regular& = default;\n\n  /// Move assignment operator\n  ///\n  /// @param rhs right value\n  auto operator=(Regular&& rhs) -> Regular& = default;\n\n  /// Get the step between two successive values.\n  ///\n  /// @return increment value\n  [[nodiscard]] auto step() const -> T { return step_; }\n\n  /// @copydoc Abstract::flip()\n  auto flip() -> void override {\n    start_ = back();\n    step_ = -step_;\n    inv_step_ = -inv_step_;\n    this->is_ascending_ = !this->is_ascending_;\n  }\n\n  /// @copydoc Abstract::coordinate_value(const size_t) const\n  [[nodiscard]] inline auto coordinate_value(const size_t index) const noexcept\n      -> T override {\n    return start_ + index * step_;\n  }\n\n  /// @copydoc Abstract::find_index(double,bool) const\n  [[nodiscard]] auto find_index(T coordinate, bool bounded) const noexcept\n      -> int64_t override {\n    auto index =\n        static_cast<int64_t>(std::round((coordinate - start_) * inv_step_));\n\n    if (index < 0) {\n      return bounded ? 0 : -1;\n    }\n\n    if (index >= size_) {\n      return bounded ? size_ - 1 : -1;\n    }\n    return index;\n  }\n\n  /// @copydoc Abstract::min_value() const\n  [[nodiscard]] inline auto min_value() const noexcept -> T override {\n    return coordinate_value(this->is_ascending_ ? 0 : size_ - 1);\n  }\n\n  /// @copydoc Abstract::max_value() const\n  [[nodiscard]] inline auto max_value() const noexcept -> T override {\n    return coordinate_value(this->is_ascending_ ? size_ - 1 : 0);\n  }\n\n  /// @copydoc Abstract::front() const\n  [[nodiscard]] inline auto front() const noexcept -> T override {\n    return start_;\n  }\n\n  /// @copydoc Abstract::back() const\n  [[nodiscard]] inline auto back() const noexcept -> T override {\n    return coordinate_value(size_ - 1);\n  }\n\n  /// @copydoc Abstract::size() const\n  [[nodiscard]] inline auto size() const noexcept -> int64_t override {\n    return size_;\n  }\n\n  /// @copydoc Abstract::operator==(const Abstract&) const\n  auto operator==(const Abstract<T>& rhs) const noexcept -> bool override {\n    const auto ptr = dynamic_cast<const Regular<T>*>(&rhs);\n    if (ptr != nullptr) {\n      return ptr->step_ == step_ && ptr->start_ == start_ &&\n             ptr->size_ == size_;\n    }\n    return false;\n  }\n\n private:\n  /// Container size.\n  int64_t size_{};\n  /// Value of the first item in the container.\n  T start_{};\n  /// The step between two succeeding values.\n  T step_{};\n  /// The inverse of the step (to avoid a division between real numbers).\n  double inv_step_{};\n};\n\n}  // namespace pyinterp::detail::axis::container\n", "meta": {"hexsha": "b4958c4fbf039042f37d4e3aa285e3c93191953b", "size": 14067, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/axis/container.hpp", "max_stars_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_stars_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-02-19T14:54:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-19T14:54:23.000Z", "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/detail/axis/container.hpp", "max_issues_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_issues_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/detail/axis/container.hpp", "max_forks_repo_name": "Geospatial-Data-Science/pangeo-pyinterp", "max_forks_repo_head_hexsha": "aa36a6fdbc4acea4206ebfd97d60aceffe0d98df", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7081632653, "max_line_length": 79, "alphanum_fraction": 0.6379469681, "num_tokens": 3534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.21193546751369802}}
{"text": "// Boost.Geometry Index\n//\n// R-tree R*-tree split algorithm implementation\n//\n// Copyright (c) 2011-2014 Adam Wulkiewicz, Lodz, Poland.\n//\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_INDEX_DETAIL_RTREE_RSTAR_REDISTRIBUTE_ELEMENTS_HPP\n#define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_RSTAR_REDISTRIBUTE_ELEMENTS_HPP\n\n#include <boost/geometry/index/detail/algorithms/intersection_content.hpp>\n#include <boost/geometry/index/detail/algorithms/union_content.hpp>\n#include <boost/geometry/index/detail/algorithms/margin.hpp>\n\n#include <boost/geometry/index/detail/bounded_view.hpp>\n\n#include <boost/geometry/index/detail/rtree/node/node.hpp>\n#include <boost/geometry/index/detail/rtree/visitors/insert.hpp>\n#include <boost/geometry/index/detail/rtree/visitors/is_leaf.hpp>\n\nnamespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { namespace index {\n\nnamespace detail { namespace rtree {\n\nnamespace rstar {\n\ntemplate <typename Element, typename Translator, typename Tag, size_t Corner, size_t AxisIndex>\nclass element_axis_corner_less\n{\n    typedef typename rtree::element_indexable_type<Element, Translator>::type indexable_type;\n    typedef typename geometry::point_type<indexable_type>::type point_type;\n    typedef geometry::model::box<point_type> bounds_type;\n    typedef index::detail::bounded_view<indexable_type, bounds_type> bounded_view_type;\n\npublic:\n    element_axis_corner_less(Translator const& tr)\n        : m_tr(tr)\n    {}\n\n    bool operator()(Element const& e1, Element const& e2) const\n    {\n        bounded_view_type bounded_ind1(rtree::element_indexable(e1, m_tr));\n        bounded_view_type bounded_ind2(rtree::element_indexable(e2, m_tr));\n\n        return geometry::get<Corner, AxisIndex>(bounded_ind1)\n            < geometry::get<Corner, AxisIndex>(bounded_ind2);\n    }\n\nprivate:\n    Translator const& m_tr;\n};\n\ntemplate <typename Element, typename Translator, size_t Corner, size_t AxisIndex>\nclass element_axis_corner_less<Element, Translator, box_tag, Corner, AxisIndex>\n{\npublic:\n    element_axis_corner_less(Translator const& tr)\n        : m_tr(tr)\n    {}\n\n    bool operator()(Element const& e1, Element const& e2) const\n    {\n        return geometry::get<Corner, AxisIndex>(rtree::element_indexable(e1, m_tr))\n            < geometry::get<Corner, AxisIndex>(rtree::element_indexable(e2, m_tr));\n    }\n\nprivate:\n    Translator const& m_tr;\n};\n\ntemplate <typename Element, typename Translator, size_t Corner, size_t AxisIndex>\nclass element_axis_corner_less<Element, Translator, point_tag, Corner, AxisIndex>\n{\npublic:\n    element_axis_corner_less(Translator const& tr)\n        : m_tr(tr)\n    {}\n\n    bool operator()(Element const& e1, Element const& e2) const\n    {\n        return geometry::get<AxisIndex>(rtree::element_indexable(e1, m_tr))\n            < geometry::get<AxisIndex>(rtree::element_indexable(e2, m_tr));\n    }\n\nprivate:\n    Translator const& m_tr;\n};\n\ntemplate <typename Box, size_t Corner, size_t AxisIndex>\nstruct choose_split_axis_and_index_for_corner\n{\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\n    typedef typename index::detail::default_content_result<Box>::type content_type;\n\n    template <typename Elements, typename Parameters, typename Translator>\n    static inline void apply(Elements const& elements,\n                             size_t & choosen_index,\n                             margin_type & sum_of_margins,\n                             content_type & smallest_overlap,\n                             content_type & smallest_content,\n                             Parameters const& parameters,\n                             Translator const& translator)\n    {\n        typedef typename Elements::value_type element_type;\n        typedef typename rtree::element_indexable_type<element_type, Translator>::type indexable_type;\n        typedef typename tag<indexable_type>::type indexable_tag;\n\n        BOOST_GEOMETRY_INDEX_ASSERT(elements.size() == parameters.get_max_elements() + 1, \"wrong number of elements\");\n\n        // copy elements\n        Elements elements_copy(elements);                                                                       // MAY THROW, STRONG (alloc, copy)\n        \n        size_t const index_first = parameters.get_min_elements();\n        size_t const index_last = parameters.get_max_elements() - parameters.get_min_elements() + 2;\n\n        // sort elements\n        element_axis_corner_less<element_type, Translator, indexable_tag, Corner, AxisIndex> elements_less(translator);\n        std::sort(elements_copy.begin(), elements_copy.end(), elements_less);                                   // MAY THROW, BASIC (copy)\n//        {\n//            typename Elements::iterator f = elements_copy.begin() + index_first;\n//            typename Elements::iterator l = elements_copy.begin() + index_last;\n//            std::nth_element(elements_copy.begin(), f, elements_copy.end(), elements_less);                   // MAY THROW, BASIC (copy)\n//            std::nth_element(f, l, elements_copy.end(), elements_less);                                       // MAY THROW, BASIC (copy)\n//            std::sort(f, l, elements_less);                                                                   // MAY THROW, BASIC (copy)\n//        }\n\n        // init outputs\n        choosen_index = index_first;\n        sum_of_margins = 0;\n        smallest_overlap = (std::numeric_limits<content_type>::max)();\n        smallest_content = (std::numeric_limits<content_type>::max)();\n\n        // calculate sum of margins for all distributions\n        for ( size_t i = index_first ; i < index_last ; ++i )\n        {\n            // TODO - awulkiew: may be optimized - box of group 1 may be initialized with\n            // box of min_elems number of elements and expanded for each iteration by another element\n\n            Box box1 = rtree::elements_box<Box>(elements_copy.begin(), elements_copy.begin() + i, translator);\n            Box box2 = rtree::elements_box<Box>(elements_copy.begin() + i, elements_copy.end(), translator);\n            \n            sum_of_margins += index::detail::comparable_margin(box1) + index::detail::comparable_margin(box2);\n\n            content_type ovl = index::detail::intersection_content(box1, box2);\n            content_type con = index::detail::content(box1) + index::detail::content(box2);\n\n            // TODO - shouldn't here be < instead of <= ?\n            if ( ovl < smallest_overlap || (ovl == smallest_overlap && con <= smallest_content) )\n            {\n                choosen_index = i;\n                smallest_overlap = ovl;\n                smallest_content = con;\n            }\n        }\n\n        ::geofeatures_boost::ignore_unused_variable_warning(parameters);\n    }\n};\n\n//template <typename Box, size_t AxisIndex, typename ElementIndexableTag>\n//struct choose_split_axis_and_index_for_axis\n//{\n//    BOOST_MPL_ASSERT_MSG(false, NOT_IMPLEMENTED_FOR_THIS_TAG, (ElementIndexableTag));\n//};\n\ntemplate <typename Box, size_t AxisIndex, typename ElementIndexableTag>\nstruct choose_split_axis_and_index_for_axis\n{\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\n    typedef typename index::detail::default_content_result<Box>::type content_type;\n\n    template <typename Elements, typename Parameters, typename Translator>\n    static inline void apply(Elements const& elements,\n                             size_t & choosen_corner,\n                             size_t & choosen_index,\n                             margin_type & sum_of_margins,\n                             content_type & smallest_overlap,\n                             content_type & smallest_content,\n                             Parameters const& parameters,\n                             Translator const& translator)\n    {\n        size_t index1 = 0;\n        margin_type som1 = 0;\n        content_type ovl1 = (std::numeric_limits<content_type>::max)();\n        content_type con1 = (std::numeric_limits<content_type>::max)();\n\n        choose_split_axis_and_index_for_corner<Box, min_corner, AxisIndex>\n            ::apply(elements, index1,\n                    som1, ovl1, con1,\n                    parameters, translator);                                                                // MAY THROW, STRONG\n\n        size_t index2 = 0;\n        margin_type som2 = 0;\n        content_type ovl2 = (std::numeric_limits<content_type>::max)();\n        content_type con2 = (std::numeric_limits<content_type>::max)();\n\n        choose_split_axis_and_index_for_corner<Box, max_corner, AxisIndex>\n            ::apply(elements, index2,\n                    som2, ovl2, con2,\n                    parameters, translator);                                                                // MAY THROW, STRONG\n\n        sum_of_margins = som1 + som2;\n\n        if ( ovl1 < ovl2 || (ovl1 == ovl2 && con1 <= con2) )\n        {\n            choosen_corner = min_corner;\n            choosen_index = index1;\n            smallest_overlap = ovl1;\n            smallest_content = con1;\n        }\n        else\n        {\n            choosen_corner = max_corner;\n            choosen_index = index2;\n            smallest_overlap = ovl2;\n            smallest_content = con2;\n        }\n    }\n};\n\ntemplate <typename Box, size_t AxisIndex>\nstruct choose_split_axis_and_index_for_axis<Box, AxisIndex, point_tag>\n{\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\n    typedef typename index::detail::default_content_result<Box>::type content_type;\n\n    template <typename Elements, typename Parameters, typename Translator>\n    static inline void apply(Elements const& elements,\n                             size_t & choosen_corner,\n                             size_t & choosen_index,\n                             margin_type & sum_of_margins,\n                             content_type & smallest_overlap,\n                             content_type & smallest_content,\n                             Parameters const& parameters,\n                             Translator const& translator)\n    {\n        choose_split_axis_and_index_for_corner<Box, min_corner, AxisIndex>\n            ::apply(elements, choosen_index,\n                    sum_of_margins, smallest_overlap, smallest_content,\n                    parameters, translator);                                                                // MAY THROW, STRONG\n\n        choosen_corner = min_corner;\n    }\n};\n\ntemplate <typename Box, size_t Dimension>\nstruct choose_split_axis_and_index\n{\n    BOOST_STATIC_ASSERT(0 < Dimension);\n\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\n    typedef typename index::detail::default_content_result<Box>::type content_type;\n\n    template <typename Elements, typename Parameters, typename Translator>\n    static inline void apply(Elements const& elements,\n                             size_t & choosen_axis,\n                             size_t & choosen_corner,\n                             size_t & choosen_index,\n                             margin_type & smallest_sum_of_margins,\n                             content_type & smallest_overlap,\n                             content_type & smallest_content,\n                             Parameters const& parameters,\n                             Translator const& translator)\n    {\n        typedef typename rtree::element_indexable_type<typename Elements::value_type, Translator>::type element_indexable_type;\n\n        choose_split_axis_and_index<Box, Dimension - 1>\n            ::apply(elements, choosen_axis, choosen_corner, choosen_index,\n                    smallest_sum_of_margins, smallest_overlap, smallest_content,\n                    parameters, translator);                                                                // MAY THROW, STRONG\n\n        margin_type sum_of_margins = 0;\n\n        size_t corner = min_corner;\n        size_t index = 0;\n\n        content_type overlap_val = (std::numeric_limits<content_type>::max)();\n        content_type content_val = (std::numeric_limits<content_type>::max)();\n\n        choose_split_axis_and_index_for_axis<\n            Box,\n            Dimension - 1,\n            typename tag<element_indexable_type>::type\n        >::apply(elements, corner, index, sum_of_margins, overlap_val, content_val, parameters, translator); // MAY THROW, STRONG\n\n        if ( sum_of_margins < smallest_sum_of_margins )\n        {\n            choosen_axis = Dimension - 1;\n            choosen_corner = corner;\n            choosen_index = index;\n            smallest_sum_of_margins = sum_of_margins;\n            smallest_overlap = overlap_val;\n            smallest_content = content_val;\n        }\n    }\n};\n\ntemplate <typename Box>\nstruct choose_split_axis_and_index<Box, 1>\n{\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\n    typedef typename index::detail::default_content_result<Box>::type content_type;\n\n    template <typename Elements, typename Parameters, typename Translator>\n    static inline void apply(Elements const& elements,\n                             size_t & choosen_axis,\n                             size_t & choosen_corner,\n                             size_t & choosen_index,\n                             margin_type & smallest_sum_of_margins,\n                             content_type & smallest_overlap,\n                             content_type & smallest_content,\n                             Parameters const& parameters,\n                             Translator const& translator)\n    {\n        typedef typename rtree::element_indexable_type<typename Elements::value_type, Translator>::type element_indexable_type;\n\n        choosen_axis = 0;\n\n        choose_split_axis_and_index_for_axis<\n            Box,\n            0,\n            typename tag<element_indexable_type>::type\n        >::apply(elements, choosen_corner, choosen_index, smallest_sum_of_margins, smallest_overlap, smallest_content, parameters, translator); // MAY THROW\n    }\n};\n\ntemplate <size_t Corner, size_t Dimension, size_t I = 0>\nstruct nth_element\n{\n    BOOST_STATIC_ASSERT(0 < Dimension);\n    BOOST_STATIC_ASSERT(I < Dimension);\n\n    template <typename Elements, typename Translator>\n    static inline void apply(Elements & elements, const size_t axis, const size_t index, Translator const& tr)\n    {\n        //BOOST_GEOMETRY_INDEX_ASSERT(axis < Dimension, \"unexpected axis value\");\n\n        if ( axis != I )\n        {\n            nth_element<Corner, Dimension, I + 1>::apply(elements, axis, index, tr);                          // MAY THROW, BASIC (copy)\n        }\n        else\n        {\n            typedef typename Elements::value_type element_type;\n            typedef typename rtree::element_indexable_type<element_type, Translator>::type indexable_type;\n            typedef typename tag<indexable_type>::type indexable_tag;\n\n            element_axis_corner_less<element_type, Translator, indexable_tag, Corner, I> less(tr);\n            std::nth_element(elements.begin(), elements.begin() + index, elements.end(), less);            // MAY THROW, BASIC (copy)\n        }\n    }\n};\n\ntemplate <size_t Corner, size_t Dimension>\nstruct nth_element<Corner, Dimension, Dimension>\n{\n    template <typename Elements, typename Translator>\n    static inline void apply(Elements & /*elements*/, const size_t /*axis*/, const size_t /*index*/, Translator const& /*tr*/)\n    {}\n};\n\n} // namespace rstar\n\ntemplate <typename Value, typename Options, typename Translator, typename Box, typename Allocators>\nstruct redistribute_elements<Value, Options, Translator, Box, Allocators, rstar_tag>\n{\n    typedef typename rtree::node<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type node;\n    typedef typename rtree::internal_node<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type internal_node;\n    typedef typename rtree::leaf<Value, typename Options::parameters_type, Box, Allocators, typename Options::node_tag>::type leaf;\n\n    typedef typename Options::parameters_type parameters_type;\n\n    static const size_t dimension = geometry::dimension<Box>::value;\n\n    typedef typename index::detail::default_margin_result<Box>::type margin_type;\n    typedef typename index::detail::default_content_result<Box>::type content_type;\n\n    template <typename Node>\n    static inline void apply(\n        Node & n,\n        Node & second_node,\n        Box & box1,\n        Box & box2,\n        parameters_type const& parameters,\n        Translator const& translator,\n        Allocators & allocators)\n    {\n        typedef typename rtree::elements_type<Node>::type elements_type;\n        typedef typename elements_type::value_type element_type;\n        \n        elements_type & elements1 = rtree::elements(n);\n        elements_type & elements2 = rtree::elements(second_node);\n\n        // copy original elements - use in-memory storage (std::allocator)\n        // TODO: move if noexcept\n        typedef typename rtree::container_from_elements_type<elements_type, element_type>::type\n            container_type;\n        container_type elements_copy(elements1.begin(), elements1.end());                               // MAY THROW, STRONG\n        container_type elements_backup(elements1.begin(), elements1.end());                             // MAY THROW, STRONG\n\n        size_t split_axis = 0;\n        size_t split_corner = 0;\n        size_t split_index = parameters.get_min_elements();\n        margin_type smallest_sum_of_margins = (std::numeric_limits<margin_type>::max)();\n        content_type smallest_overlap = (std::numeric_limits<content_type>::max)();\n        content_type smallest_content = (std::numeric_limits<content_type>::max)();\n\n        // NOTE: this function internally copies passed elements\n        //       why not pass mutable elements and use the same container for all axes/corners\n        //       and again, the same below calling partial_sort/nth_element\n        //       It would be even possible to not re-sort/find nth_element if the axis/corner\n        //       was found for the last sorting - last combination of axis/corner\n        rstar::choose_split_axis_and_index<Box, dimension>\n            ::apply(elements_copy,\n                    split_axis, split_corner, split_index,\n                    smallest_sum_of_margins, smallest_overlap, smallest_content,\n                    parameters, translator);                                                            // MAY THROW, STRONG\n\n        // TODO: awulkiew - get rid of following static_casts?\n        BOOST_GEOMETRY_INDEX_ASSERT(split_axis < dimension, \"unexpected value\");\n        BOOST_GEOMETRY_INDEX_ASSERT(split_corner == static_cast<size_t>(min_corner) || split_corner == static_cast<size_t>(max_corner), \"unexpected value\");\n        BOOST_GEOMETRY_INDEX_ASSERT(parameters.get_min_elements() <= split_index && split_index <= parameters.get_max_elements() - parameters.get_min_elements() + 1, \"unexpected value\");\n\n        // TODO: consider using nth_element\n        if ( split_corner == static_cast<size_t>(min_corner) )\n        {\n            rstar::nth_element<min_corner, dimension>\n                ::apply(elements_copy, split_axis, split_index, translator);                            // MAY THROW, BASIC (copy)\n        }\n        else\n        {\n            rstar::nth_element<max_corner, dimension>\n                ::apply(elements_copy, split_axis, split_index, translator);                            // MAY THROW, BASIC (copy)\n        }\n\n        BOOST_TRY\n        {\n            // copy elements to nodes\n            elements1.assign(elements_copy.begin(), elements_copy.begin() + split_index);               // MAY THROW, BASIC\n            elements2.assign(elements_copy.begin() + split_index, elements_copy.end());                 // MAY THROW, BASIC\n\n            // calculate boxes\n            box1 = rtree::elements_box<Box>(elements1.begin(), elements1.end(), translator);\n            box2 = rtree::elements_box<Box>(elements2.begin(), elements2.end(), translator);\n        }\n        BOOST_CATCH(...)\n        {\n            //elements_copy.clear();\n            elements1.clear();\n            elements2.clear();\n\n            rtree::destroy_elements<Value, Options, Translator, Box, Allocators>::apply(elements_backup, allocators);\n            //elements_backup.clear();\n\n            BOOST_RETHROW                                                                                 // RETHROW, BASIC\n        }\n        BOOST_CATCH_END\n    }\n};\n\n}} // namespace detail::rtree\n\n}}} // namespace geofeatures_boost::geometry::index\n\n#endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_RSTAR_REDISTRIBUTE_ELEMENTS_HPP\n", "meta": {"hexsha": "9c9f00fa0993bf4ee172c40f3047ead010df5a09", "size": 20822, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost/geometry/index/detail/rtree/rstar/redistribute_elements.hpp", "max_stars_repo_name": "tonystone/geofeatures", "max_stars_repo_head_hexsha": "25aca530a9140b3f259e9ee0833c93522e83a697", "max_stars_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2015-08-25T05:35:37.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-24T14:21:59.000Z", "max_issues_repo_path": "boost/boost/geometry/index/detail/rtree/rstar/redistribute_elements.hpp", "max_issues_repo_name": "tonystone/geofeatures", "max_issues_repo_head_hexsha": "25aca530a9140b3f259e9ee0833c93522e83a697", "max_issues_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_issues_count": 97.0, "max_issues_repo_issues_event_min_datetime": "2015-08-25T16:11:16.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-17T00:54:32.000Z", "max_forks_repo_path": "boost/boost/geometry/index/detail/rtree/rstar/redistribute_elements.hpp", "max_forks_repo_name": "tonystone/geofeatures", "max_forks_repo_head_hexsha": "25aca530a9140b3f259e9ee0833c93522e83a697", "max_forks_repo_licenses": ["BSL-1.0", "Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-08-26T03:11:38.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-21T07:16:29.000Z", "avg_line_length": 44.3965884861, "max_line_length": 186, "alphanum_fraction": 0.6303909327, "num_tokens": 4161, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2119354534022632}}
{"text": "#include <ctime>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <stdexcept>\n#include <sys/stat.h>\n#include <algorithm>\n#include \"qm_model.hpp\"\n#include \"properties.hpp\"\n#include <armadillo>\n#include <unordered_map>\n\nConfigBlockReader QM_Model::model_reader() {\n  ConfigBlockReader reader{\"qmmodel\"};\n  reader.add_entry(\"model\", \"avoided-crossing\");\n  return reader;\n}\n\nQM_Model::QM_Model(FileHandle& fh, \n                   const arma::uvec& in_qmids, \n\t\t   arma::mat& in_qm_crd, \n\t\t   arma::mat& in_mm_crd, \n\t\t   arma::vec& in_mm_chg, \n\t\t   const int charge, \n\t\t   const int mult,\n\t\t   const int excited_states,\n                   const int min_state):\n  QMInterface(in_qmids, in_qm_crd, in_mm_crd, in_mm_chg, charge, mult, excited_states, min_state)\n{\n\n  if (NQM > 1){\n    throw std::logic_error(\"Model systems only work on the x component of a single atom!\");\n  }\n\n  if (NMM != 0){\n    throw std::logic_error(\"Model systems don't support QM/MM!\");\n  }\n  \n  ConfigBlockReader reader = model_reader();\n  reader.parse(fh);\n\n  {\n    std::string model_in;\n    reader.get_data(\"model\", model_in);\n\n    if (model_in == \"avoided-crossing\"){\n      model= new AvoidedCrossing();\n    }\n    else if (model_in == \"reflective-avoided-crossing\"){\n      model= new ReflectiveAvoidedCrossing();\n    }\n    else{\n      throw std::runtime_error(\"Unknown Model: `\" + model_in + \"`!\");\n    }\n  }\n}\n\nvoid QM_Model::update(void){  \n  QMInterface::update();\n  // always take the x component of the first atom\n  model->update(crd_qm(0));\n}\n\nvoid QM_Model::get_properties(PropMap &props){\n  for (QMProperty p: props.keys()){\n    switch(p){\n      \n    case QMProperty::wfoverlap:{\n      arma::mat &U = props.get(QMProperty::wfoverlap);\n      U = model->overlaps();\n      break;\n    }\n\n    case QMProperty::nacvector:{\n      arma::mat & nac = props.get(QMProperty::nacvector);\n      nac.zeros();\n\n      const arma::uvec &idx = *props.get_idx(QMProperty::nacvector);\n      size_t A = idx[0]; size_t B = idx[1];      \n\n      nac(0) = model->nacs()(A,B);\n      break;\n    }\n      \n    case QMProperty::qmgradient:{\n      arma::mat & g_qm = props.get(QMProperty::qmgradient);\n      g_qm.zeros();\n      \n      arma::uword surface = 0; //assume ground state\n      if (props.has_idx(QMProperty::qmgradient)){\n\tsurface = (*props.get_idx(QMProperty::qmgradient))[0];\n      }\n      g_qm(0) = model->gradients()(surface);\n\n      break;\n    }\n      \n    case QMProperty::qmgradient_multi:{\n      arma::cube & g_qm = props.get(QMProperty::qmgradient_multi);\n      g_qm.zeros();\n      \n      arma::uvec surfaces = arma::regspace<arma::uvec>(0,excited_states); //assume all\n      if (props.has_idx(QMProperty::qmgradient_multi)){ // specific states\n\tsurfaces = *props.get_idx(QMProperty::qmgradient_multi);\n      }\n\n      if (g_qm.n_slices != surfaces.n_elem){\n\tthrow std::range_error(\"Insufficient space for requested gradients!\");\n      }\n     \n      arma::uword i=0;\n      for (arma::uword surface: surfaces){\n        g_qm.slice(i)(0) = model->gradients()(surface);\n        i++;\n      }\n      break;\n    }\n      \n    case QMProperty::energies:{\n      arma::vec & energies = props.get(QMProperty::energies);\n      energies.zeros();\n      \n      if (props.has_idx(QMProperty::energies)){\n      \tenergies = model->energies();\n      }\n      else{\n      \tenergies = model->energies()(0);\n      }\n      break;\n    }\n\n    case QMProperty::mmgradient: //explicit fall-through\n    case QMProperty::mmgradient_multi:\n      break;\n      \n    default:\n      throw std::invalid_argument(\"Unknown QMProperty!\");\n      break;\n    }\n  }\n}\n\n\n// updates overlap and, phase matches the new eigen vectors to the old ones.\nvoid HamiltonianDynamics::update_overlap(arma::mat &evec){\n  static arma::mat evec_last = evec;\n  overlap = evec_last.t() * evec;\n\n  while (arma::any(overlap.diag() < 0)){ // phase match\n    arma::uword c = overlap.diag().index_min();\n    evec.col(c) *= -1.0;\n    \n    overlap = evec_last.t() * evec;\n  }\n  \n  evec_last = evec;\n}\n\nvoid HamiltonianDynamics::save_state(double x){\n  std::vector<double> state;\n     \n  state.push_back( x );\n  state.push_back( energy(0) );\n  state.push_back( energy(1) );\n  state.push_back( gradient(0) );\n  state.push_back( gradient(1) );\n  state.push_back( overlap(0,1) );\n  state.push_back( nac(0,1) );\n    \n  std::ofstream stream;\n  stream.open(state_file, std::ios::out | std::ios::app | std::ios::binary);\n  if (!stream){\n    throw std::runtime_error(\"Cannot open data file!\");\n  }\n  else{\n    for (auto e: state){\n      stream << e << \" \";\n    }\n    stream << std::endl;\n  }\n}\n\nvoid HamiltonianDynamics::scan(double a, double b, int N){\n  record = true;\n\n  if ((b-a < 0) || (N < 0)){\n    throw::std::logic_error(\"Can only scan on [a,b) in N>0 steps!\");\n  }\n  \n  const double dx = (b-a)/N;\n\n  for (double x = a; x < b; x += dx){\n    update(x);\n  }\n  \n}\n  \nReflectiveAvoidedCrossing::ReflectiveAvoidedCrossing(void){\n  energy.set_size(2);\n  gradient.set_size(2);\n  nac.set_size(2,2);\n  overlap.set_size(2,2);\n}\n\nvoid ReflectiveAvoidedCrossing::update(double x){\n  double e2 = A*std::tanh(B*(x+7));\n  double e1 = e2 + 2*A*std::tanh(B*x) + 2*A;\n  \n  double v = C * std::exp(-1.0*(x+7)*(x+7));\n\n  arma::mat H = {{e1, v },\n                 {v, -e2}};\n\n  arma::vec eval;\n  arma::mat evec;\n  eig_sym(eval, evec, H);\n\n  update_overlap(evec);\n\n  energy = eval;\n\n  // compute gradients\n  {\n    double de2 = A*B / std::pow(std::cosh(B*(x+7)),2) ;\n    double de1 = A*B / std::pow(std::cosh(B*x)    ,2) + de2 ;\n    double dv = -C * 2 * (x+7) *  std::exp(-1.0*(x+7)*(x+7));\n\n    // gradient = 0.5*((de1 - de2) +\n    //                 ((de2-de1)*(e2-e1) + 2*(e1*de2 + e2*de1) + 4*v*dv) /\n    //                 ((e2-e1) + 2 * energy));\n\n    \n    double gl = 0.5 * (de1 - de2);\n    double gr = 0.5 * ((de2-de1)*(e2-e1) + 2*(e1*de2 + e2*de1) + 4*v*dv) /\n      std::sqrt((e2-e1)*(e2-e1) + 4*e1*e2+4*v*v);\n\n    gradient(0) = gl - gr;\n    gradient(1) = gl + gr;\n  }\n\n\n  // compute NAC\n  nac = evec.t() * arma::diagmat(gradient) * evec;\n  nac.diag().zeros();\n  {\n    double gap = energy(1) - energy(0);\n    nac(0,1) /=  gap;\n    nac(1,0) /= -gap;\n  }\n  \n\n  if(record){\n    save_state(x);\n  }\n}\n\n\n\nAvoidedCrossing::AvoidedCrossing(void){\n  energy.set_size(2);\n  gradient.set_size(2);\n  nac.set_size(2,2);\n  overlap.set_size(2,2);\n}\n\nvoid AvoidedCrossing::update(double x){\n  double xs = x+7;\n  \n  double e = A * std::tanh(B*xs);\n  double v = C * std::exp(-1.0*xs*xs);\n\n  arma::mat H = {{e,  v},\n                 {v, -e}};\n\n  arma::vec eval;\n  arma::mat evec;\n  eig_sym(eval, evec, H);\n\n  update_overlap(evec);\n\n  energy = eval;\n\n  // compute gradients\n  double f;\n  {\n    double sech = 1.0 / std::cosh(B*xs);\n    f = e*A*B*sech*sech + -2.0*xs*v*v;\n  }\n  gradient = f / energy;\n\n\n  // compute NAC\n  nac = evec.t() * arma::diagmat(gradient) * evec;\n  nac.diag().zeros();\n  {\n    double gap = energy(1) - energy(0);\n    nac(0,1) /=  gap;\n    nac(1,0) /= -gap;\n  }\n\n  // save a bunch of things\n  if(record)\n  {\n    save_state(x);\n  }\n}\n", "meta": {"hexsha": "351117c794f517824513928624394f8bb84d28ac", "size": 7067, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/qm_model.cpp", "max_stars_repo_name": "INAQS/inaqs", "max_stars_repo_head_hexsha": "f85b39aef0cb67cda4b3cfa61017268fe410c362", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_issues_repo_path": "src/qm_model.cpp", "max_issues_repo_name": "INAQS/inaqs", "max_issues_repo_head_hexsha": "f85b39aef0cb67cda4b3cfa61017268fe410c362", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qm_model.cpp", "max_forks_repo_name": "INAQS/inaqs", "max_forks_repo_head_hexsha": "f85b39aef0cb67cda4b3cfa61017268fe410c362", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8705501618, "max_line_length": 97, "alphanum_fraction": 0.5839818876, "num_tokens": 2226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6893056295505783, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.21186361131272796}}
{"text": "// g2o - General Graph Optimization\n// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   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//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n// IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"solver_slam2d_linear.h\"\n\n#include <Eigen/Core>\n\n#include \"g2o/core/sparse_block_matrix.h\"\n#include \"g2o/core/sparse_optimizer.h\"\n#include \"g2o/core/hyper_dijkstra.h\"\n\n#include \"g2o/types/slam2d/edge_se2.h\"\n\n#include \"g2o/stuff/misc.h\"\n#include \"g2o/stuff/scoped_pointer.h\"\n\n#include \"g2o/solvers/csparse/linear_solver_csparse.h\"\n\n#include \"g2o/core/solver.h\"\n\nusing namespace std;\n\nnamespace g2o {\n\n  /**\n   * \\brief compute the initial guess of theta while travelling along the MST\n   */\n  class ThetaTreeAction : public HyperDijkstra::TreeAction\n  {\n    public:\n      ThetaTreeAction(double* theta) : HyperDijkstra::TreeAction(), _thetaGuess(theta) {}\n      virtual double perform(HyperGraph::Vertex* v, HyperGraph::Vertex* vParent, HyperGraph::Edge* e)\n      {\n        if (! vParent)\n          return 0.;\n        EdgeSE2* odom    = static_cast<EdgeSE2*>(e);\n        VertexSE2* from  = static_cast<VertexSE2*>(vParent);\n        VertexSE2* to    = static_cast<VertexSE2*>(v);\n        assert(to->hessianIndex() >= 0);\n        double fromTheta = from->hessianIndex() < 0 ? 0. : _thetaGuess[from->hessianIndex()];\n        bool direct      = odom->vertices()[0] == from;\n        if (direct) \n          _thetaGuess[to->hessianIndex()] = fromTheta + odom->measurement().rotation().angle();\n        else\n          _thetaGuess[to->hessianIndex()] = fromTheta - odom->measurement().rotation().angle();\n        return 1.;\n      }\n    protected:\n      double* _thetaGuess;\n  };\n\n  SolverSLAM2DLinear::SolverSLAM2DLinear(std::unique_ptr<Solver> solver)\n    : OptimizationAlgorithmGaussNewton(std::move(solver))\n  {}\n\n  SolverSLAM2DLinear::~SolverSLAM2DLinear()\n  {}\n\n  OptimizationAlgorithm::SolverResult SolverSLAM2DLinear::solve(int iteration, bool online)\n  {\n    if (iteration == 0) {\n      bool status = solveOrientation();\n      if (! status)\n        return OptimizationAlgorithm::Fail;\n    }\n\n    return OptimizationAlgorithmGaussNewton::solve(iteration, online);\n  }\n\n  bool SolverSLAM2DLinear::solveOrientation()\n  {\n    assert(_optimizer->indexMapping().size() + 1 == _optimizer->vertices().size() && \"Needs to operate on full graph\");\n    assert(_optimizer->vertex(0)->fixed() && \"Graph is not fixed by vertex 0\");\n    VectorXD b, x; // will be used for theta and x/y update\n    b.setZero(_optimizer->indexMapping().size());\n    x.setZero(_optimizer->indexMapping().size());\n\n    typedef Eigen::Matrix<double, 1, 1, Eigen::ColMajor> ScalarMatrix;\n\n    ScopedArray<int> blockIndeces(new int[_optimizer->indexMapping().size()]);\n    for (size_t i = 0; i < _optimizer->indexMapping().size(); ++i)\n      blockIndeces[i] = i+1;\n\n    SparseBlockMatrix<ScalarMatrix> H(blockIndeces.get(), blockIndeces.get(), _optimizer->indexMapping().size(), _optimizer->indexMapping().size());\n\n    // building the structure, diagonal for each active vertex\n    for (size_t i = 0; i < _optimizer->indexMapping().size(); ++i) {\n      OptimizableGraph::Vertex* v = _optimizer->indexMapping()[i];\n      int poseIdx = v->hessianIndex();\n      ScalarMatrix* m = H.block(poseIdx, poseIdx, true);\n      m->setZero();\n    }\n\n    HyperGraph::VertexSet fixedSet;\n\n    // off diagonal for each edge\n    for (SparseOptimizer::EdgeContainer::const_iterator it = _optimizer->activeEdges().begin(); it != _optimizer->activeEdges().end(); ++it) {\n#    ifndef NDEBUG\n      EdgeSE2* e = dynamic_cast<EdgeSE2*>(*it);\n      assert(e && \"Active edges contain non-odometry edge\"); //\n#    else\n      EdgeSE2* e = static_cast<EdgeSE2*>(*it);\n#    endif\n      OptimizableGraph::Vertex* from = static_cast<OptimizableGraph::Vertex*>(e->vertices()[0]);\n      OptimizableGraph::Vertex* to   = static_cast<OptimizableGraph::Vertex*>(e->vertices()[1]);\n\n      int ind1 = from->hessianIndex();\n      int ind2 = to->hessianIndex();\n      if (ind1 == -1 || ind2 == -1) {\n        if (ind1 == -1) fixedSet.insert(from); // collect the fixed vertices\n        if (ind2 == -1) fixedSet.insert(to);\n        continue;\n      }\n\n      bool transposedBlock = ind1 > ind2;\n      if (transposedBlock){ // make sure, we allocate the upper triangle block\n        std::swap(ind1, ind2);\n      }\n\n      ScalarMatrix* m = H.block(ind1, ind2, true);\n      m->setZero();\n    }\n\n    // walk along the Minimal Spanning Tree to compute the guess for the robot orientation\n    assert(fixedSet.size() == 1);\n    VertexSE2* root = static_cast<VertexSE2*>(*fixedSet.begin());\n    VectorXD thetaGuess;\n    thetaGuess.setZero(_optimizer->indexMapping().size());\n    UniformCostFunction uniformCost;\n    HyperDijkstra hyperDijkstra(_optimizer);\n    hyperDijkstra.shortestPaths(root, &uniformCost);\n\n    HyperDijkstra::computeTree(hyperDijkstra.adjacencyMap());\n    ThetaTreeAction thetaTreeAction(thetaGuess.data());\n    HyperDijkstra::visitAdjacencyMap(hyperDijkstra.adjacencyMap(), &thetaTreeAction);\n\n    // construct for the orientation\n    for (SparseOptimizer::EdgeContainer::const_iterator it = _optimizer->activeEdges().begin(); it != _optimizer->activeEdges().end(); ++it) {\n      EdgeSE2* e = static_cast<EdgeSE2*>(*it);\n      VertexSE2* from = static_cast<VertexSE2*>(e->vertices()[0]);\n      VertexSE2* to   = static_cast<VertexSE2*>(e->vertices()[1]);\n\n      double omega = e->information()(2,2);\n\n      double fromThetaGuess = from->hessianIndex() < 0 ? 0. : thetaGuess[from->hessianIndex()];\n      double toThetaGuess   = to->hessianIndex() < 0 ? 0. : thetaGuess[to->hessianIndex()];\n      double error          = normalize_theta(-e->measurement().rotation().angle() + toThetaGuess - fromThetaGuess);\n\n      bool fromNotFixed = !(from->fixed());\n      bool toNotFixed   = !(to->fixed());\n\n      if (fromNotFixed || toNotFixed) {\n        double omega_r = - omega * error;\n        if (fromNotFixed) {\n          b(from->hessianIndex()) -= omega_r;\n          (*H.block(from->hessianIndex(), from->hessianIndex()))(0,0) += omega;\n          if (toNotFixed) {\n            if (from->hessianIndex() > to->hessianIndex())\n              (*H.block(to->hessianIndex(), from->hessianIndex()))(0,0) -= omega;\n            else\n              (*H.block(from->hessianIndex(), to->hessianIndex()))(0,0) -= omega;\n          }\n        } \n        if (toNotFixed ) {\n          b(to->hessianIndex()) += omega_r;\n          (*H.block(to->hessianIndex(), to->hessianIndex()))(0,0) += omega;\n        }\n      }\n    }\n\n    // solve orientation\n    typedef LinearSolverCSparse<ScalarMatrix> SystemSolver;\n    SystemSolver linearSystemSolver;\n    linearSystemSolver.init();\n    bool ok = linearSystemSolver.solve(H, x.data(), b.data());\n    if (!ok) {\n      cerr << __PRETTY_FUNCTION__ << \"Failure while solving linear system\" << endl;\n      return false;\n    }\n\n    // update the orientation of the 2D poses and set translation to 0, GN shall solve that\n    root->setToOrigin();\n    for (size_t i = 0; i < _optimizer->indexMapping().size(); ++i) {\n      VertexSE2* v = static_cast<VertexSE2*>(_optimizer->indexMapping()[i]);\n      int poseIdx = v->hessianIndex();\n      SE2 poseUpdate(0, 0, normalize_theta(thetaGuess(poseIdx) + x(poseIdx)));\n      v->setEstimate(poseUpdate);\n    }\n\n    return true;\n  }\n\n} // end namespace\n", "meta": {"hexsha": "9ed9797441063bcbf56ad6c4e5662ec7004d3104", "size": 8560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "g2opy/g2o/solvers/slam2d_linear/solver_slam2d_linear.cpp", "max_stars_repo_name": "alecone/ROS_project", "max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-06-20T08:29:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-12T06:05:52.000Z", "max_issues_repo_path": "thirdparty/g2opy/g2o/solvers/slam2d_linear/solver_slam2d_linear.cpp", "max_issues_repo_name": "rpng/suo_slam", "max_issues_repo_head_hexsha": "5de01433d177fde5cac4423f05fd554e3c00794e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "thirdparty/g2opy/g2o/solvers/slam2d_linear/solver_slam2d_linear.cpp", "max_forks_repo_name": "rpng/suo_slam", "max_forks_repo_head_hexsha": "5de01433d177fde5cac4423f05fd554e3c00794e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-21T13:38:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-21T13:38:45.000Z", "avg_line_length": 39.4470046083, "max_line_length": 148, "alphanum_fraction": 0.6640186916, "num_tokens": 2197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.211462968317865}}
{"text": "#include <boost/multiprecision/cpp_int.hpp>\n#include <peersafe/crypto/LibSnark.h>\n#include <peersafe/precompiled/PreContractRegister.h>\n#include <peersafe/basics/TypeTransform.h>\n#include <ripple/protocol/digest.h>\n#include <ripple/protocol/CommonKey.h>\n#include <ripple/basics/Blob.h>\n#include <ripple/basics/Slice.h>\nusing namespace std;\n\nnamespace ripple {\n\nPrecompiledRegistrar* PrecompiledRegistrar::s_this = nullptr;\n\nPrecompiledExecutor const& PrecompiledRegistrar::executor(std::string const& _name)\n{\n    if (!get()->m_execs.count(_name))\n        BOOST_THROW_EXCEPTION(ExecutorNotFound());\n    return get()->m_execs[_name];\n}\n\nPrecompiledPricer const& PrecompiledRegistrar::pricer(std::string const& _name)\n{\n    if (!get()->m_pricers.count(_name))\n        BOOST_THROW_EXCEPTION(PricerNotFound());\n    return get()->m_pricers[_name];\n}\n\nnamespace\n{\n\n// // Big-endian to/from host endian conversion functions.\n\n// /// Converts a templated integer value to the big-endian byte-stream represented on a templated collection.\n// /// The size of the collection object will be unchanged. If it is too small, it will not represent the\n// /// value properly, if too big then the additional elements will be zeroed out.\n// /// @a Out will typically be either std::string or bytes.\n// /// @a T will typically by unsigned, u160, u256 or bigint.\n// template <class T, class Out>\n// inline void toBigEndian(T _val, Out& o_out)\n// {\n// \tstatic_assert(std::is_same<eth::bigint, T>::value || !std::numeric_limits<T>::is_signed, \"only unsigned types or bigint supported\"); //bigint does not carry sign bit on shift\n// \tfor (auto i = o_out.size(); i != 0; _val >>= 8, i--)\n// \t{\n// \t\tT v = _val & (T)0xff;\n// \t\to_out[i - 1] = (typename Out::value_type)(uint8_t)v;\n// \t}\n// }\n\n// /// Converts a big-endian byte-stream represented on a templated collection to a templated integer value.\n// /// @a _In will typically be either std::string or bytes.\n// /// @a T will typically by unsigned, u160, u256 or bigint.\n// template <class T, class _In>\n// inline T fromBigEndian(_In const& _bytes)\n// {\n// \tT ret = (T)0;\n// \tfor (auto i: _bytes)\n// \t\tret = (T)((ret << 8) | (eth::byte)(typename std::make_unsigned<decltype(i)>::type)i);\n// \treturn ret;\n// }\n\nint64_t linearPricer(unsigned _base, unsigned _word, eth::bytesConstRef _in)\n{\n    int64_t const s = _in.size();\n    int64_t const b = _base;\n    int64_t const w = _word;\n    return b + (s + 31) / 32 * w;\n}\n\n// ETH_REGISTER_PRECOMPILED_PRICER(ecrecover)\n// (eth::bytesConstRef /*_in*/, ChainOperationParams const& /*_chainParams*/, int64_t const& /*_blockNumber*/)\n// {\n//     return 3000;\n// }\n\n// ETH_REGISTER_PRECOMPILED(ecrecover)(eth::bytesConstRef _in)\n// {\n//     struct\n//     {\n//         h256 hash;\n//         h256 v;\n//         h256 r;\n//         h256 s;\n//     } in;\n\n//     memcpy(&in, _in.data(), min(_in.size(), sizeof(in)));\n\n//     h256 ret;\n//     u256 v = (u256)in.v;\n//     if (v >= 27 && v <= 28)\n//     {\n//         SignatureStruct sig(in.r, in.s, (byte)((int)v - 27));\n//         if (sig.isValid())\n//         {\n//             try\n//             {\n//                 if (Public rec = recover(sig, in.hash))\n//                 {\n//                     ret = dev::sha3(rec);\n//                     memset(ret.data(), 0, 12);\n//                     return {true, ret.asBytes()};\n//                 }\n//             }\n//             catch (...) {}\n//         }\n//     }\n//     return {true, {}};\n// }\n\nETH_REGISTER_PRECOMPILED_PRICER(sha256)\n(eth::bytesConstRef _in, int64_t const& /*_blockNumber*/)\n{\n    return linearPricer(60, 12, _in);\n}\n\nETH_REGISTER_PRECOMPILED(sha256)(eth::bytesConstRef _in)\n{\n    auto hashRet = sha512Half<CommonKey::sha>(Slice(_in.data(), _in.size()));\n    return {true, Blob(hashRet.begin(), hashRet.end())};\n}\n\nETH_REGISTER_PRECOMPILED_PRICER(sm3)\n(eth::bytesConstRef _in, int64_t const& /*_blockNumber*/)\n{\n    return linearPricer(60, 12, _in);\n}\n\nETH_REGISTER_PRECOMPILED(sm3)(eth::bytesConstRef _in)\n{\n    auto hashRet = sha512Half<CommonKey::sm3>(Slice(_in.data(), _in.size()));\n    return {true, Blob(hashRet.begin(), hashRet.end())};\n}\n\nETH_REGISTER_PRECOMPILED_PRICER(ripemd160)\n(eth::bytesConstRef _in, int64_t const& /*_blockNumber*/)\n{\n    return linearPricer(600, 120, _in);\n}\n\nETH_REGISTER_PRECOMPILED(ripemd160)(eth::bytesConstRef _in)\n{\n    // return {true, h256(dev::ripemd160(_in), h256::AlignRight).asBytes()};\n    ripemd160_hasher rh;\n    rh(_in.data(), _in.size());\n    auto rhRet = ripemd160_hasher::result_type(rh);\n    return {true, Blob(rhRet.begin(), rhRet.end())};\n}\n\nETH_REGISTER_PRECOMPILED_PRICER(identity)\n(eth::bytesConstRef _in, int64_t const& /*_blockNumber*/)\n{\n    return linearPricer(15, 3, _in);\n}\n\nETH_REGISTER_PRECOMPILED(identity)(eth::bytesConstRef _in)\n{\n    return {true, _in.toBytes()};\n}\n\nETH_REGISTER_PRECOMPILED_PRICER(enbase58)\n(eth::bytesConstRef _in, int64_t const& /*_blockNumber*/)\n{\n    return linearPricer(60, 12, _in);\n}\n\nETH_REGISTER_PRECOMPILED(enbase58)(eth::bytesConstRef _in/*, std::uint8_t tokenType = (std::uint8_t)TokenType::AccountID*/)\n{\n    auto enRet = base58EncodeToken(TokenType::AccountID, _in.data(), _in.size());\n    return { true, Blob(enRet.begin(), enRet.end()) };\n}\n\nETH_REGISTER_PRECOMPILED_PRICER(debase58)\n(eth::bytesConstRef _in, int64_t const& /*_blockNumber*/)\n{\n    return linearPricer(60, 12, _in);\n}\n\nETH_REGISTER_PRECOMPILED(debase58)(eth::bytesConstRef _in/*, std::uint8_t tokenType = (std::uint8_t)TokenType::AccountID*/)\n{\n    auto enRet = decodeBase58Token(std::string((const char*)_in.data(), _in.size()), TokenType::AccountID);\n    return { true, Blob(enRet.begin(), enRet.end()) };\n}\n\n// Parse _count bytes of _in starting with _begin offset as big endian int.\n// If there's not enough bytes in _in, consider it infinitely right-padded with zeroes.\neth::bigint parseBigEndianRightPadded(eth::bytesConstRef _in, eth::bigint const& _begin, eth::bigint const& _count)\n{\n    if (_begin > _in.count())\n        return 0;\n    assert(_count <= numeric_limits<size_t>::max() / 8); // Otherwise, the return value would not fit in the memory.\n\n    size_t const begin{_begin};\n    size_t const count{_count};\n\n    // crop _in, not going beyond its size\n    eth::bytesConstRef cropped = _in.cropped(begin, min(count, _in.count() - begin));\n\n    eth::bigint ret = ripple::fromBigEndian<eth::bigint>(cropped);\n    // shift as if we had right-padding zeroes\n    assert(count - cropped.count() <= numeric_limits<size_t>::max() / 8);\n    ret <<= 8 * (count - cropped.count());\n\n    return ret;\n}\n\n ETH_REGISTER_PRECOMPILED(modexp)(eth::bytesConstRef _in)\n {\n     eth::bigint const baseLength(parseBigEndianRightPadded(_in, 0, 32));\n     eth::bigint const expLength(parseBigEndianRightPadded(_in, 32, 32));\n     eth::bigint const modLength(parseBigEndianRightPadded(_in, 64, 32));\n     assert(modLength <= numeric_limits<size_t>::max() / 8); // Otherwise gas should be too expensive.\n     assert(baseLength <= numeric_limits<size_t>::max() / 8); // Otherwise, gas should be too expensive.\n     if (modLength == 0 && baseLength == 0)\n         return {true, eth::bytes{}}; // This is a special case where expLength can be very big.\n     assert(expLength <= numeric_limits<size_t>::max() / 8);\n\n     eth::bigint const base(parseBigEndianRightPadded(_in, 96, baseLength));\n     eth::bigint const exp(parseBigEndianRightPadded(_in, 96 + baseLength, expLength));\n     eth::bigint const mod(parseBigEndianRightPadded(_in, 96 + baseLength + expLength, modLength));\n\n     eth::bigint const result = mod != 0 ? boost::multiprecision::powm(base, exp, mod) : eth::bigint{0};\n\n     size_t const retLength(modLength);\n     eth::bytes ret(retLength);\n     ripple::toBigEndian(result, ret);\n\n     return {true, ret};\n }\n\n namespace\n {\n     int64_t expLengthAdjust(int64_t const& _expOffset, int64_t const& _expLength, eth::bytesConstRef _in)\n     {\n         if (_expLength <= 32)\n         {\n             eth::bigint const exp(parseBigEndianRightPadded(_in, _expOffset, _expLength));\n             return exp ? boost::multiprecision::msb(exp) : 0;\n         }\n         else\n         {\n             eth::bigint const expFirstWord(parseBigEndianRightPadded(_in, _expOffset, 32));\n             size_t const highestBit(expFirstWord ? boost::multiprecision::msb(expFirstWord) : 0);\n             return 8 * (_expLength - 32) + highestBit;\n         }\n     }\n\n     int64_t multComplexity(int64_t const& _x)\n     {\n         if (_x <= 64)\n             return _x * _x;\n         if (_x <= 1024)\n             return (_x * _x) / 4 + 96 * _x - 3072;\n         else\n             return (_x * _x) / 16 + 480 * _x - 199680;\n     }\n }\n\n ETH_REGISTER_PRECOMPILED_PRICER(modexp)(eth::bytesConstRef _in, int64_t const&)\n {\n     int64_t const baseLength(parseBigEndianRightPadded(_in, 0, 32));\n     int64_t const expLength(parseBigEndianRightPadded(_in, 32, 32));\n     int64_t const modLength(parseBigEndianRightPadded(_in, 64, 32));\n\n     int64_t const maxLength(max(modLength, baseLength));\n     int64_t const adjustedExpLength(expLengthAdjust(baseLength + 96, expLength, _in));\n\n     return multComplexity(maxLength) * max<int64_t>(adjustedExpLength, 1) / 20;\n }\n\n ETH_REGISTER_PRECOMPILED(alt_bn128_G1_add)(eth::bytesConstRef _in)\n {\n     return peersafe::alt_bn128_G1_add(_in);\n }\n\n ETH_REGISTER_PRECOMPILED_PRICER(alt_bn128_G1_add)\n (eth::bytesConstRef /*_in*/, int64_t const& _blockNumber)\n {\n     return 150;\n     // return _blockNumber < _chainParams.istanbulForkBlock ? 500 : 150;\n }\n\n ETH_REGISTER_PRECOMPILED(alt_bn128_G1_mul)(eth::bytesConstRef _in)\n {\n     return  peersafe::alt_bn128_G1_mul(_in);\n }\n\n ETH_REGISTER_PRECOMPILED_PRICER(alt_bn128_G1_mul)\n (eth::bytesConstRef /*_in*/, int64_t const& _blockNumber)\n {\n     return 6000;\n     // return _blockNumber < _chainParams.istanbulForkBlock ? 40000 : 6000;\n }\n\n ETH_REGISTER_PRECOMPILED(alt_bn128_pairing_product)(eth::bytesConstRef _in)\n {\n     return  peersafe::alt_bn128_pairing_product(_in);\n }\n\n ETH_REGISTER_PRECOMPILED_PRICER(alt_bn128_pairing_product)\n (eth::bytesConstRef _in, int64_t const& _blockNumber)\n {\n     auto const k = _in.size() / 192;\n     return 45000 + k * 34000;\n     // return _blockNumber < _chainParams.istanbulForkBlock ? 100000 + k * 80000 : 45000 + k * 34000;\n }\n\n// ETH_REGISTER_PRECOMPILED(blake2_compression)(eth::bytesConstRef _in)\n// {\n//     static constexpr size_t roundsSize = 4;\n//     static constexpr size_t stateVectorSize = 8 * 8;\n//     static constexpr size_t messageBlockSize = 16 * 8;\n//     static constexpr size_t offsetCounterSize = 8;\n//     static constexpr size_t finalBlockIndicatorSize = 1;\n//     static constexpr size_t totalInputSize = roundsSize + stateVectorSize + messageBlockSize +\n//                                              2 * offsetCounterSize + finalBlockIndicatorSize;\n\n//     if (_in.size() != totalInputSize)\n//         return {false, {}};\n\n//     auto const rounds = fromBigEndian<uint32_t>(_in.cropped(0, roundsSize));\n//     auto const stateVector = _in.cropped(roundsSize, stateVectorSize);\n//     auto const messageBlockVector = _in.cropped(roundsSize + stateVectorSize, messageBlockSize);\n//     auto const offsetCounter0 =\n//         _in.cropped(roundsSize + stateVectorSize + messageBlockSize, offsetCounterSize);\n//     auto const offsetCounter1 = _in.cropped(\n//         roundsSize + stateVectorSize + messageBlockSize + offsetCounterSize, offsetCounterSize);\n//     uint8_t const finalBlockIndicator =\n//         _in[roundsSize + stateVectorSize + messageBlockSize + 2 * offsetCounterSize];\n\n//     if (finalBlockIndicator != 0 && finalBlockIndicator != 1)\n//         return {false, {}};\n\n//     return {true, dev::crypto::blake2FCompression(rounds, stateVector, offsetCounter0,\n//                       offsetCounter1, finalBlockIndicator, messageBlockVector)};\n// }\n\n// ETH_REGISTER_PRECOMPILED_PRICER(blake2_compression)\n// (eth::bytesConstRef _in, int64_t const&)\n// {\n//     auto const rounds = fromBigEndian<uint32_t>(_in.cropped(0, 4));\n//     return rounds;\n// }\n}\n\n}", "meta": {"hexsha": "c88ef9ee3b77d0b0e599b97b2e2c1c0f35d996f5", "size": 12042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/peersafe/precompiled/PreContractRegister.cpp", "max_stars_repo_name": "ChainSQL/chainsqld", "max_stars_repo_head_hexsha": "6af7eb0624c67776098250a39eae9f195d8a473a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 211.0, "max_stars_repo_stars_event_min_datetime": "2017-12-11T03:11:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T12:38:19.000Z", "max_issues_repo_path": "src/peersafe/precompiled/PreContractRegister.cpp", "max_issues_repo_name": "ChainSQL/chainsqld", "max_issues_repo_head_hexsha": "6af7eb0624c67776098250a39eae9f195d8a473a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2017-12-18T07:22:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T10:24:29.000Z", "max_forks_repo_path": "src/peersafe/precompiled/PreContractRegister.cpp", "max_forks_repo_name": "ChainSQL/chainsqld", "max_forks_repo_head_hexsha": "6af7eb0624c67776098250a39eae9f195d8a473a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 81.0, "max_forks_repo_forks_event_min_datetime": "2017-12-11T03:09:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T09:42:42.000Z", "avg_line_length": 34.9043478261, "max_line_length": 178, "alphanum_fraction": 0.6660853679, "num_tokens": 3403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2112351034013042}}
{"text": "// graph-tool -- a general graph modification and manipulation thingy\n//\n// Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>\n//\n// This program is free software; you can redistribute it and/or\n// modify it under the terms of the GNU General Public License\n// as published by the Free Software Foundation; either version 3\n// of the License, or (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n#include \"graph.hh\"\n#include \"graph_filtering.hh\"\n#include \"graph_properties.hh\"\n#include \"graph_selectors.hh\"\n\n#include <boost/python.hpp>\n\n#include <boost/graph/johnson_all_pairs_shortest.hpp>\n#include <boost/graph/floyd_warshall_shortest.hpp>\n\nusing namespace std;\nusing namespace boost;\nusing namespace graph_tool;\n\nstruct do_all_pairs_search\n{\n    template <class Graph, class VertexIndexMap, class DistMap, class WeightMap>\n    void operator()(const Graph& g, VertexIndexMap vertex_index,\n                    DistMap dist_map, WeightMap weight, bool dense) const\n    {\n        typedef typename property_traits<DistMap>::value_type::value_type\n            dist_t;\n\n        int i, N = num_vertices(g);\n        #pragma omp parallel for default(shared) private(i) schedule(runtime) if (N > 100)\n        for (i = 0; i < N; ++i)\n        {\n            dist_map[i].clear();\n            dist_map[i].resize(num_vertices(g), 0);\n        }\n\n        if (dense)\n        {\n            floyd_warshall_all_pairs_shortest_paths\n                (g, dist_map,\n                 weight_map(ConvertedPropertyMap<WeightMap,dist_t>(weight)).\n                 vertex_index_map(vertex_index));\n        }\n        else\n        {\n            johnson_all_pairs_shortest_paths\n                (g, dist_map,\n                 weight_map(ConvertedPropertyMap<WeightMap,dist_t>(weight)).\n                 vertex_index_map(vertex_index));\n        }\n    }\n};\n\nvoid get_all_dists(GraphInterface& gi, boost::any dist_map, boost::any weight,\n                   bool dense)\n{\n    typedef ConstantPropertyMap<size_t,GraphInterface::edge_t> cweight_map_t;\n\n    if (weight.empty())\n        weight = boost::any(cweight_map_t(1));\n\n    run_action<>()\n        (gi, std::bind(do_all_pairs_search(), placeholders::_1,\n                       gi.GetVertexIndex(), placeholders::_2, placeholders::_3,\n                       dense),\n         vertex_scalar_vector_properties(),\n         mpl::push_back<edge_scalar_properties,cweight_map_t>::type())\n        (dist_map, weight);\n}\n\nvoid export_all_dists()\n{\n    python::def(\"get_all_dists\", &get_all_dists);\n};\n", "meta": {"hexsha": "e65d96071f44b55443b30b92bdcdada2e969d9b0", "size": 2900, "ext": "cc", "lang": "C++", "max_stars_repo_path": "graph-tool/src/graph/topology/graph_all_distances.cc", "max_stars_repo_name": "johankaito/fufuka", "max_stars_repo_head_hexsha": "32a96ecf98ce305c2206c38443e58fdec88c788d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-08-04T19:41:53.000Z", "max_stars_repo_stars_event_max_datetime": "2015-08-04T19:41:53.000Z", "max_issues_repo_path": "graph-tool/src/graph/topology/graph_all_distances.cc", "max_issues_repo_name": "johankaito/fufuka", "max_issues_repo_head_hexsha": "32a96ecf98ce305c2206c38443e58fdec88c788d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graph-tool/src/graph/topology/graph_all_distances.cc", "max_forks_repo_name": "johankaito/fufuka", "max_forks_repo_head_hexsha": "32a96ecf98ce305c2206c38443e58fdec88c788d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3333333333, "max_line_length": 90, "alphanum_fraction": 0.6589655172, "num_tokens": 652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061854293322, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.21098396244447495}}
{"text": "//    Copyright (C) Dimitrios Michail 2019 - 2021.\n// Distributed under the Boost Software License, Version 1.0.\n//    (See accompanying file LICENSE_1_0.txt or copy at\n//          https://www.boost.org/LICENSE_1_0.txt)\n\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <list>\n\n#include <boost/config.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/property_map/property_map.hpp>\n#include <boost/program_options.hpp>\n#include <boost/timer/timer.hpp>\n#include <boost/thread.hpp>\n\n#include <parmcb/parmcb.hpp>\n#include <parmcb/util.hpp>\n#include <parmcb/detail/cycles.hpp>\n#include <parmcb/sptrees.hpp>\n\nusing namespace boost;\nnamespace po = boost::program_options;\n\n#define USAGE \"Computes statistics on FVS and ISO cycle collections given a weighted undirected graph in DIMACS format.\"\n\n\ntemplate<class Graph, class WeightMap>\nclass CandidateCycleBuilder {\npublic:\n    typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;\n    typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n    typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n    CandidateCycleBuilder(const Graph &g, const WeightMap &weight_map) :\n            g(g), weight_map(weight_map) {\n    }\n\n    std::tuple<std::set<Edge>, WeightType> operator()(const std::vector<parmcb::SPTree<Graph, WeightMap>> &trees,\n            const parmcb::CandidateCycle<Graph, WeightMap> &c) const {\n\n        std::shared_ptr<parmcb::SPNode<Graph, WeightMap>> v = trees[c.tree()].node(boost::source(c.edge(), g));\n        std::shared_ptr<parmcb::SPNode<Graph, WeightMap>> u = trees[c.tree()].node(boost::target(c.edge(), g));\n\n        Edge e = c.edge();\n        bool valid = true;\n        WeightType cycle_weight = boost::get(weight_map, e);\n        std::set<Edge> result;\n        result.insert(e);\n\n        // first part\n        Vertex w = boost::source(c.edge(), g);\n        std::shared_ptr<parmcb::SPNode<Graph, WeightMap>> ws = trees[c.tree()].node(w);\n        while (ws->has_pred()) {\n            Edge a = ws->pred();\n            if (result.insert(a).second == false) {\n                valid = false;\n                break;\n            }\n            cycle_weight += boost::get(weight_map, a);\n            w = boost::opposite(a, w, g);\n            ws = trees[c.tree()].node(w);\n        }\n\n        if (!valid) {\n            return std::make_tuple(std::set<Edge> { }, 0.0);\n        }\n\n        // second part\n        w = boost::target(c.edge(), g);\n        ws = trees[c.tree()].node(w);\n        while (ws->has_pred()) {\n            Edge a = ws->pred();\n            if (result.insert(a).second == false) {\n                valid = false;\n                break;\n            }\n            cycle_weight += boost::get(weight_map, a);\n            w = boost::opposite(a, w, g);\n            ws = trees[c.tree()].node(w);\n        }\n\n        if (!valid) {\n            return std::make_tuple(std::set<Edge> { }, 0.0);\n        }\n\n        return std::make_tuple(result, cycle_weight);\n    }\n\nprivate:\n    const Graph &g;\n    const WeightMap &weight_map;\n};\n\n\n\ntemplate<class Graph, class WeightMap, class CyclesBuilder>\nvoid print_tree_stats(const char *name, const Graph &g, WeightMap weight_map) {\n    std::vector<parmcb::SPTree<Graph, WeightMap>> trees;\n    std::vector<parmcb::CandidateCycle<Graph, WeightMap>> cycles;\n    CyclesBuilder cycles_builder;\n    cycles_builder(g, weight_map, trees, cycles);\n    std::cout << name << \" cycles: \" << cycles.size() << std::endl;\n\n    CandidateCycleBuilder<Graph, WeightMap> candidate_cycle_builder(g, weight_map);\n\n    typedef typename boost::graph_traits<Graph>::edge_descriptor Edge;\n    typedef typename boost::property_traits<WeightMap>::value_type WeightType;\n\n    double total_weight = 0.0;\n    long total_card = 0;\n    for (parmcb::CandidateCycle<Graph, WeightMap> c : cycles) {\n        std::tuple<std::set<Edge>, WeightType> cc = candidate_cycle_builder(trees, c);\n\n        total_weight += std::get<1>(cc);\n        total_card += std::get<0>(cc).size();\n    }\n\n    std::cout << name << \" total cycles weight: \" << total_weight << std::endl;\n    std::cout << name << \" total cycles cardinality: \" << total_card << std::endl;\n}\n\ntemplate <class Graph, class WeightMap>\nvoid print_all_tree_stats(const Graph& g, WeightMap weight_map) {\n    print_tree_stats<Graph, WeightMap, parmcb::detail::FVSCyclesBuilder<Graph, WeightMap>>(\"FVS\", g, weight_map);\n    print_tree_stats<Graph, WeightMap, parmcb::detail::ISOCyclesBuilder<Graph, WeightMap>>(\"ISO\", g, weight_map);\n    print_tree_stats<Graph, WeightMap, parmcb::detail::HortonCyclesBuilder<Graph, WeightMap>>(\"HORTON\", g, weight_map);\n}\n\nint main(int argc, char *argv[]) {\n\n    po::variables_map vm;\n    try {\n        po::options_description desc(USAGE);\n        // @formatter:off\n        desc.add_options()\n                (\"help,h\", \"Help\")\n                (\"verbose,v\", po::value<bool>()->default_value(false)->implicit_value(true), \"Verbose\")\n                (\"input-file,I\",po::value<std::string>(), \"Input filename\");\n        // @formatter:on\n        po::positional_options_description pos_desc;\n        pos_desc.add(\"input-file\", 1);\n        po::command_line_parser parser { argc, argv };\n        parser.options(desc).positional(pos_desc).allow_unregistered();\n        po::parsed_options parsed_options = parser.run();\n        po::store(parsed_options, vm);\n\n        if (vm.count(\"help\")) {\n            std::cout << desc << std::endl;\n            return EXIT_SUCCESS;\n        }\n        po::notify(vm);\n\n        if (!vm.count(\"input-file\")) {\n            std::cerr << \"Input file missing. See usage by calling with -h .\" << std::endl;\n            exit(EXIT_FAILURE);\n        }\n\n    } catch (const po::error &ex) {\n        std::cerr << \"Invalid arguments:\" << ex.what() << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    typedef adjacency_list<vecS, vecS, undirectedS, no_property, property<edge_weight_t, double> > graph_t;\n\n    // create graph\n    graph_t graph;\n    FILE *fp = fopen(vm[\"input-file\"].as<std::string>().c_str(), \"r\");\n    if (fp == NULL) {\n        std::cerr << \"Failed to open input file.\" << std::endl;\n        exit(EXIT_FAILURE);\n    }\n    parmcb::read_dimacs_from_file(fp, graph);\n    fclose(fp);\n\n    if (parmcb::has_loops(graph)) {\n        std::cerr << \"Graph has loops, aborting..\" << std::endl;\n        return EXIT_FAILURE;\n    }\n    if (parmcb::has_multiple_edges(graph)) {\n        std::cerr << \"Graph has multiple edges, aborting..\" << std::endl;\n        return EXIT_FAILURE;\n    }\n    if (parmcb::has_non_positive_weights(graph, get(boost::edge_weight, graph))) {\n        std::cerr << \"Graph has negative or zero weight edges, aborting..\" << std::endl;\n        return EXIT_FAILURE;\n    }\n\n    std::cout << \"graph n: \" << num_vertices(graph) << std::endl;\n    std::cout << \"graph m: \" << num_edges(graph) << std::endl;\n    std::cout << \"graph n*m: \" << num_vertices(graph)*num_edges(graph) << std::endl;\n    std::cout << std::flush;\n\n    print_all_tree_stats(graph, get(boost::edge_weight, graph));\n\n    return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "cbf0a8523726022816a66cb2fd5baf16f06af597", "size": 7116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/collection-stats-dimacs.cpp", "max_stars_repo_name": "d-michail/parmcb", "max_stars_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/collection-stats-dimacs.cpp", "max_issues_repo_name": "d-michail/parmcb", "max_issues_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/collection-stats-dimacs.cpp", "max_forks_repo_name": "d-michail/parmcb", "max_forks_repo_head_hexsha": "19d0b7eb01735600c851b969d9e5a87c78b8c711", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4029850746, "max_line_length": 120, "alphanum_fraction": 0.6187464868, "num_tokens": 1771, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21096645787755747}}
{"text": "/* -*- c++ -*- */\n/*\n * Copyright 2003,2008,2011,2012 Free Software Foundation, Inc.\n *\n * This file is part of GNU Radio\n *\n * GNU Radio is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3, or (at your option)\n * any later version.\n *\n * GNU Radio is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with GNU Radio; see the file COPYING.  If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street,\n * Boston, MA 02110-1301, USA.\n */\n\n#include <gnuradio/fft/fft.h>\n#include <gnuradio/sys_paths.h>\n#include <gnuradio/gr_complex.h>\n#include <volk/volk.h>\n#include <fftw3.h>\n\n#ifdef _WIN32 //http://www.fftw.org/install/windows.html#DLLwisdom\nstatic void my_fftw_write_char(char c, void *f) { fputc(c, (FILE *) f); }\n#define fftw_export_wisdom_to_file(f) fftw_export_wisdom(my_fftw_write_char, (void*) (f))\n#define fftwf_export_wisdom_to_file(f) fftwf_export_wisdom(my_fftw_write_char, (void*) (f))\n#define fftwl_export_wisdom_to_file(f) fftwl_export_wisdom(my_fftw_write_char, (void*) (f))\n\nstatic int my_fftw_read_char(void *f) { return fgetc((FILE *) f); }\n#define fftw_import_wisdom_from_file(f) fftw_import_wisdom(my_fftw_read_char, (void*) (f))\n#define fftwf_import_wisdom_from_file(f) fftwf_import_wisdom(my_fftw_read_char, (void*) (f))\n#define fftwl_import_wisdom_from_file(f) fftwl_import_wisdom(my_fftw_read_char, (void*) (f))\n#include <fcntl.h> \n#include <io.h>\n#define O_NOCTTY 0\n#define O_NONBLOCK 0\n#endif //_WIN32\n\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <cassert>\n#include <stdexcept>\n\n#include <boost/filesystem/operations.hpp>\n#include <boost/filesystem/path.hpp>\n#include <boost/interprocess/sync/file_lock.hpp>\nnamespace fs = boost::filesystem;\n\nnamespace gr {\n  namespace fft {\n    static boost::mutex wisdom_thread_mutex;\n    boost::interprocess::file_lock wisdom_lock;\n    static bool wisdom_lock_init_done = false; // Modify while holding 'wisdom_thread_mutex'\n\n    gr_complex *\n    malloc_complex(int size)\n    {\n      return (gr_complex*) volk_malloc (sizeof (gr_complex)*size, volk_get_alignment ());\n    }\n\n    float *\n    malloc_float(int size)\n    {\n      return (float*) volk_malloc (sizeof (float)*size, volk_get_alignment ());\n    }\n\n    double *\n    malloc_double(int size)\n    {\n      return (double*) volk_malloc (sizeof (double)*size, volk_get_alignment ());\n    }\n\n    void\n    free(void *b)\n    {\n      volk_free(b);\n    }\n\n    boost::mutex &\n    planner::mutex()\n    {\n      static boost::mutex  s_planning_mutex;\n\n      return s_planning_mutex;\n    }\n\n    static std::string\n    wisdom_filename()\n    {\n      static fs::path path;\n      path = fs::path(gr::appdata_path()) / \".gr_fftw_wisdom\";\n      return path.string();\n    }\n\n    static void\n    wisdom_lock_init()\n    {\n      if (wisdom_lock_init_done)\n        return;\n\n      const std::string wisdom_lock_file = wisdom_filename() + \".lock\";\n      // std::cerr << \"Creating FFTW wisdom lockfile: \" << wisdom_lock_file << std::endl;\n      int fd = open(wisdom_lock_file.c_str(),\n        O_WRONLY | O_CREAT | O_NOCTTY | O_NONBLOCK,\n        0666);\n      if (fd < 0) {\n        throw std::runtime_error(\"Failed to create FFTW wisdom lockfile: \" + wisdom_lock_file);\n      }\n      close(fd);\n      wisdom_lock = boost::interprocess::file_lock(wisdom_lock_file.c_str());\n      wisdom_lock_init_done = true;\n    }\n\n    static void\n    lock_wisdom()\n    {\n      wisdom_thread_mutex.lock();\n      wisdom_lock_init();\n      wisdom_lock.lock();\n    }\n\n    static void\n    unlock_wisdom()\n    {\n      // Assumes 'lock_wisdom' has already been called (i.e. this file_lock is valid)\n      wisdom_lock.unlock();\n      wisdom_thread_mutex.unlock();\n    }\n\n    static void\n    import_wisdom()\n    {\n      const std::string filename = wisdom_filename ();\n      FILE *fp = fopen (filename.c_str(), \"r\");\n      if (fp != 0){\n        int r = fftwf_import_wisdom_from_file (fp);\n        fclose (fp);\n        if (!r){\n          fprintf (stderr, \"gr::fft: can't import wisdom from %s\\n\", filename.c_str());\n        }\n      }\n    }\n\n    static void\n    config_threading(int nthreads)\n    {\n      static int fftw_threads_inited = 0;\n\n#ifdef FFTW3F_THREADS\n      if (fftw_threads_inited == 0)\n    {\n      fftw_threads_inited = 1;\n      fftwf_init_threads();\n    }\n\n      fftwf_plan_with_nthreads(nthreads);\n#endif\n    }\n\n    static void\n    export_wisdom()\n    {\n      const std::string filename = wisdom_filename ();\n      FILE *fp = fopen (filename.c_str(), \"w\");\n      if (fp != 0){\n        fftwf_export_wisdom_to_file (fp);\n        fclose (fp);\n      }\n      else {\n        fprintf (stderr, \"fft_impl_fftw: \");\n        perror (filename.c_str());\n      }\n    }\n\n// ----------------------------------------------------------------\n\n    fft_complex::fft_complex(int fft_size, bool forward, int nthreads)\n    {\n      // Hold global mutex during plan construction and destruction.\n      planner::scoped_lock lock(planner::mutex());\n\n      assert (sizeof (fftwf_complex) == sizeof (gr_complex));\n\n      if (fft_size <= 0){\n        throw std::out_of_range (\"fft_impl_fftw: invalid fft_size\");\n      }\n\n      d_fft_size = fft_size;\n      d_inbuf = (gr_complex *) volk_malloc (sizeof (gr_complex) * inbuf_length (), volk_get_alignment ());\n      if (d_inbuf == 0) {\n        throw std::runtime_error (\"volk_malloc\");\n      }\n      d_outbuf = (gr_complex *) volk_malloc (sizeof (gr_complex) * outbuf_length (), volk_get_alignment ());\n      if (d_outbuf == 0) {\n        volk_free (d_inbuf);\n        throw std::runtime_error (\"volk_malloc\");\n      }\n\n      d_nthreads = nthreads;\n      config_threading(nthreads);\n      lock_wisdom();\n      import_wisdom();\t// load prior wisdom from disk\n\n      d_plan = fftwf_plan_dft_1d (fft_size,\n                  reinterpret_cast<fftwf_complex *>(d_inbuf),\n                  reinterpret_cast<fftwf_complex *>(d_outbuf),\n                  forward ? FFTW_FORWARD : FFTW_BACKWARD,\n                  FFTW_MEASURE);\n\n      if (d_plan == NULL) {\n        fprintf(stderr, \"gr::fft: error creating plan\\n\");\n        throw std::runtime_error (\"fftwf_plan_dft_1d failed\");\n      }\n      export_wisdom();\t// store new wisdom to disk\n      unlock_wisdom();\n    }\n\n    fft_complex::~fft_complex()\n    {\n      // Hold global mutex during plan construction and destruction.\n      planner::scoped_lock lock(planner::mutex());\n\n      fftwf_destroy_plan ((fftwf_plan) d_plan);\n      volk_free (d_inbuf);\n      volk_free (d_outbuf);\n    }\n\n    void\n    fft_complex::set_nthreads(int n)\n    {\n      if (n <= 0) {\n        throw std::out_of_range (\"gr::fft: invalid number of threads\");\n      }\n      d_nthreads = n;\n\n#ifdef FFTW3F_THREADS\n      fftwf_plan_with_nthreads(d_nthreads);\n#endif\n    }\n\n    void\n    fft_complex::execute()\n    {\n      fftwf_execute((fftwf_plan) d_plan);\n    }\n\n// ----------------------------------------------------------------\n\n    fft_real_fwd::fft_real_fwd (int fft_size, int nthreads)\n    {\n      // Hold global mutex during plan construction and destruction.\n      planner::scoped_lock lock(planner::mutex());\n\n      assert (sizeof (fftwf_complex) == sizeof (gr_complex));\n\n      if (fft_size <= 0) {\n        throw std::out_of_range (\"gr::fft: invalid fft_size\");\n      }\n\n      d_fft_size = fft_size;\n      d_inbuf = (float *) volk_malloc (sizeof (float) * inbuf_length (), volk_get_alignment ());\n      if (d_inbuf == 0) {\n        throw std::runtime_error (\"volk_malloc\");\n      }\n\n      d_outbuf = (gr_complex *) volk_malloc (sizeof (gr_complex) * outbuf_length (), volk_get_alignment ());\n      if (d_outbuf == 0) {\n        volk_free (d_inbuf);\n        throw std::runtime_error (\"volk_malloc\");\n      }\n\n      d_nthreads = nthreads;\n      config_threading(nthreads);\n      lock_wisdom();\n      import_wisdom();\t// load prior wisdom from disk\n\n      d_plan = fftwf_plan_dft_r2c_1d (fft_size,\n                      d_inbuf,\n                      reinterpret_cast<fftwf_complex *>(d_outbuf),\n                      FFTW_MEASURE);\n\n      if (d_plan == NULL) {\n        fprintf(stderr, \"gr::fft::fft_real_fwd: error creating plan\\n\");\n        throw std::runtime_error (\"fftwf_plan_dft_r2c_1d failed\");\n      }\n      export_wisdom();\t// store new wisdom to disk\n      unlock_wisdom();\n    }\n\n    fft_real_fwd::~fft_real_fwd()\n    {\n      // Hold global mutex during plan construction and destruction.\n      planner::scoped_lock lock(planner::mutex());\n\n      fftwf_destroy_plan ((fftwf_plan) d_plan);\n      volk_free (d_inbuf);\n      volk_free (d_outbuf);\n    }\n\n    void\n    fft_real_fwd::set_nthreads(int n)\n    {\n      if (n <= 0) {\n        throw std::out_of_range (\"gr::fft::fft_real_fwd::set_nthreads: invalid number of threads\");\n      }\n      d_nthreads = n;\n\n#ifdef FFTW3F_THREADS\n      fftwf_plan_with_nthreads(d_nthreads);\n#endif\n    }\n\n    void\n    fft_real_fwd::execute()\n    {\n      fftwf_execute ((fftwf_plan) d_plan);\n    }\n\n    // ----------------------------------------------------------------\n\n    fft_real_rev::fft_real_rev(int fft_size, int nthreads)\n    {\n      // Hold global mutex during plan construction and destruction.\n      planner::scoped_lock lock(planner::mutex());\n\n      assert (sizeof (fftwf_complex) == sizeof (gr_complex));\n\n      if (fft_size <= 0) {\n        throw std::out_of_range (\"gr::fft::fft_real_rev: invalid fft_size\");\n      }\n\n      d_fft_size = fft_size;\n      d_inbuf = (gr_complex *) volk_malloc (sizeof (gr_complex) * inbuf_length (), volk_get_alignment ());\n      if (d_inbuf == 0) {\n        throw std::runtime_error (\"volk_malloc\");\n      }\n\n      d_outbuf = (float *) volk_malloc (sizeof (float) * outbuf_length (), volk_get_alignment ());\n      if (d_outbuf == 0) {\n        volk_free (d_inbuf);\n        throw std::runtime_error (\"volk_malloc\");\n      }\n\n      d_nthreads = nthreads;\n      config_threading(nthreads);\n      lock_wisdom();\n      import_wisdom();\t// load prior wisdom from disk\n\n      // FIXME If there's ever a chance that the planning functions\n      // will be called in multiple threads, we've got to ensure single\n      // threaded access.  They are not thread-safe.\n      d_plan = fftwf_plan_dft_c2r_1d (fft_size,\n                      reinterpret_cast<fftwf_complex *>(d_inbuf),\n                      d_outbuf,\n                      FFTW_MEASURE);\n\n      if (d_plan == NULL) {\n        fprintf(stderr, \"gr::fft::fft_real_rev: error creating plan\\n\");\n        throw std::runtime_error (\"fftwf_plan_dft_c2r_1d failed\");\n      }\n      export_wisdom ();\t// store new wisdom to disk\n      unlock_wisdom();\n    }\n\n    fft_real_rev::~fft_real_rev ()\n    {\n      // Hold global mutex during plan construction and destruction.\n      planner::scoped_lock lock(planner::mutex());\n\n      fftwf_destroy_plan ((fftwf_plan) d_plan);\n      volk_free (d_inbuf);\n      volk_free (d_outbuf);\n    }\n\n    void\n    fft_real_rev::set_nthreads(int n)\n    {\n      if (n <= 0) {\n        throw std::out_of_range (\"gr::fft::fft_real_rev::set_nthreads: invalid number of threads\");\n      }\n      d_nthreads = n;\n\n#ifdef FFTW3F_THREADS\n      fftwf_plan_with_nthreads(d_nthreads);\n#endif\n    }\n\n    void\n    fft_real_rev::execute ()\n    {\n      fftwf_execute ((fftwf_plan) d_plan);\n    }\n\n  } /* namespace fft */\n} /* namespace gr */\n", "meta": {"hexsha": "718cd0990f666eb9898c096934c6957cb8088faa", "size": 11611, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gnuradio-3.7.13.4/gr-fft/lib/fft.cc", "max_stars_repo_name": "v1259397/cosmic-gnuradio", "max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z", "max_issues_repo_path": "gnuradio-3.7.13.4/gr-fft/lib/fft.cc", "max_issues_repo_name": "v1259397/cosmic-gnuradio", "max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gnuradio-3.7.13.4/gr-fft/lib/fft.cc", "max_forks_repo_name": "v1259397/cosmic-gnuradio", "max_forks_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8114143921, "max_line_length": 108, "alphanum_fraction": 0.6206183791, "num_tokens": 2980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.21096645787755747}}
{"text": "// This file is part of LatticeTester.\n//\n// LatticeTester\n// Copyright (C) 2012-2018  Pierre L'Ecuyer and Universite de Montreal\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/*\n * The purpose of this example is to compare the time\n *  of each reduction method. We compute several\n * random matrix and apply algorithms. The parameters of this\n * analysis are defined at the beginning of this file,\n * after include part. The output is a graphic generated by R.\n * The User need R distribution and the header RInside.h\n */\n\n\n// Include Header\n#include <iostream>\n#include <map>\n#include <fstream>\n#include <iterator>\n#include <string>\n#include <sstream>\n#include <iomanip>\n#include <time.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n\n// Include LatticeTester Header\n#include \"latticetester/Util.h\"\n#include \"latticetester/Const.h\"\n#include \"latticetester/IntFactor.h\"\n#include \"latticetester/IntLatticeBasis.h\"\n#include \"latticetester/Reducer.h\"\n#include \"latticetester/ParamReader.h\"\n#include \"latticetester/Config.h\"\n#include \"latticetester/LatticeAnalysis.h\"\n\n// Include NTL Header\n#include <NTL/tools.h>\n#include <NTL/ctools.h>\n#include <NTL/ZZ.h>\n#include <NTL/ZZ_p.h>\n#include \"NTL/vec_ZZ.h\"\n#include \"NTL/vec_ZZ_p.h\"\n#include <NTL/vec_vec_ZZ.h>\n#include <NTL/vec_vec_ZZ_p.h>\n#include <NTL/mat_ZZ.h>\n#include <NTL/matrix.h>\n#include <NTL/LLL.h>\n\nusing namespace std;\nusing namespace LatticeTester;\n\nint ZZRR(int argc, char* argv[]) {\n  LatticeAnalysis<NTL::ZZ, NTL::ZZ, NTL::RR, NTL::RR> latAnalysis;\n  struct stat buf; // properties of a file or directory\n  int status = 0;\n\n  for (int j = 2; j < argc; j++) {\n    // Do the test for each data file or directory on the command line\n\n    stat(argv[j], &buf);\n    if (0 != S_ISDIR(buf.st_mode)) // directory\n      status |= latAnalysis.doTestFromDirectory (argv[j]);\n    else {\n      string dataname(argv[j]);\n      dataname.append(\".dat\");\n      stat(dataname.c_str(), &buf);\n      status |= latAnalysis.doTestFromInputFile (argv[j]);\n    }\n  }\n  return 1;\n}\nint ZZDD(int argc, char* argv[]) {\n  LatticeAnalysis<NTL::ZZ, NTL::ZZ, double, double> latAnalysis;\n  struct stat buf; // properties of a file or directory\n  int status = 0;\n\n  for (int j = 2; j < argc; j++) {\n    // Do the test for each data file or directory on the command line\n\n    stat(argv[j], &buf);\n    if (0 != S_ISDIR(buf.st_mode)) // directory\n      status |= latAnalysis.doTestFromDirectory (argv[j]);\n    else {\n      string dataname(argv[j]);\n      dataname.append(\".dat\");\n      stat(dataname.c_str(), &buf);\n      status |= latAnalysis.doTestFromInputFile (argv[j]);\n    }\n  }\n  return 1;\n}\nint LLDD(int argc, char* argv[]) {\n  LatticeAnalysis<std::int64_t, std::int64_t, double, double> latAnalysis;\n  struct stat buf; // properties of a file or directory\n  int status = 0;\n\n  for (int j = 2; j < argc; j++) {\n    // Do the test for each data file or directory on the command line\n\n    stat(argv[j], &buf);\n    if (0 != S_ISDIR(buf.st_mode)) // directory\n      status |= latAnalysis.doTestFromDirectory (argv[j]);\n    else {\n      string dataname(argv[j]);\n      dataname.append(\".dat\");\n      stat(dataname.c_str(), &buf);\n      status |= latAnalysis.doTestFromInputFile (argv[j]);\n    }\n  }\n  return 1;\n}\n//==============================================================================\n\nint main (int argc, char *argv[])\n{\n  std::clock_t start_t = std::clock();\n  if (argc < 2) {\n    cerr << \"\\n*** Usage:\\n   \"\n      << argv[0] << \" data_file1 data_file2 ....\" << endl\n      << \"or\\n   \"\n      << argv[0] << \" dir1 dir2 ....\" << endl\n      << endl;\n    return -1;\n  } else if (argc < 3) {\n    cerr << \"Must specify types\\n\";\n    return -1;\n  }\n  //cout << \"ARGC \" << argc << endl;\n  if (!strcmp(argv[1], \"ZZRR\")) {\n    ZZRR(argc, argv);\n    std::clock_t end_t = std::clock();\n    cout << \"Time: \" << (double)(end_t-start_t)/CLOCKS_PER_SEC << \" sec\\n\";\n  } else if (!strcmp(argv[1], \"ZZDD\")) {\n    ZZDD(argc, argv);\n    std::clock_t end_t = std::clock();\n    cout << \"Time: \" << (double)(end_t-start_t)/CLOCKS_PER_SEC << \" sec\\n\";\n  } else if (!strcmp(argv[1], \"LLDD\")) {\n    LLDD(argc, argv);\n    std::clock_t end_t = std::clock();\n    cout << \"Time: \" << (double)(end_t-start_t)/CLOCKS_PER_SEC << \" sec\\n\";\n  } else {\n    cerr << \"No valid type name has been specified\\n\";\n  }\n\n  return 0;\n}\n\n\n", "meta": {"hexsha": "ae8987f1336f87bcf07d69daa26cd67ab1769b9e", "size": 4845, "ext": "cc", "lang": "C++", "max_stars_repo_path": "progs/TestLattice.cc", "max_stars_repo_name": "edoars/latticetester", "max_stars_repo_head_hexsha": "980179abe2da78b8a13d2b912d2215b97509c528", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "progs/TestLattice.cc", "max_issues_repo_name": "edoars/latticetester", "max_issues_repo_head_hexsha": "980179abe2da78b8a13d2b912d2215b97509c528", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-27T15:41:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-05T17:41:14.000Z", "max_forks_repo_path": "progs/TestLattice.cc", "max_forks_repo_name": "edoars/latticetester", "max_forks_repo_head_hexsha": "980179abe2da78b8a13d2b912d2215b97509c528", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-24T01:11:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-24T01:11:53.000Z", "avg_line_length": 29.7239263804, "max_line_length": 80, "alphanum_fraction": 0.6392156863, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165085228825, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.21082727846171376}}
{"text": "// Boost.Polygon library detail/voronoi_ctypes.hpp header file\r\n\r\n//          Copyright Andrii Sydorchuk 2010-2012.\r\n// Distributed under the Boost Software License, Version 1.0.\r\n//    (See accompanying file LICENSE_1_0.txt or copy at\r\n//          http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// See http://www.boost.org for updates, documentation, and revision history.\r\n\r\n#ifndef BOOST_POLYGON_DETAIL_VORONOI_CTYPES\r\n#define BOOST_POLYGON_DETAIL_VORONOI_CTYPES\r\n\r\n#include <boost/cstdint.hpp>\r\n\r\n#include <cmath>\r\n#include <cstring>\r\n#include <utility>\r\n#include <vector>\r\n\r\nnamespace boost {\r\nnamespace polygon {\r\nnamespace detail {\r\n\r\ntypedef boost::int32_t int32;\r\ntypedef boost::int64_t int64;\r\ntypedef boost::uint32_t uint32;\r\ntypedef boost::uint64_t uint64;\r\ntypedef double fpt64;\r\n\r\n// If two floating-point numbers in the same format are ordered (x < y),\r\n// then they are ordered the same way when their bits are reinterpreted as\r\n// sign-magnitude integers. Values are considered to be almost equal if\r\n// their integer bits reinterpretations differ in not more than maxUlps units.\r\ntemplate <typename _fpt>\r\nstruct ulp_comparison;\r\n\r\ntemplate <>\r\nstruct ulp_comparison<fpt64> {\r\n  enum Result {\r\n    LESS = -1,\r\n    EQUAL = 0,\r\n    MORE = 1\r\n  };\r\n\r\n  Result operator()(fpt64 a, fpt64 b, unsigned int maxUlps) const {\r\n    uint64 ll_a, ll_b;\r\n\r\n    // Reinterpret double bits as 64-bit signed integer.\r\n    std::memcpy(&ll_a, &a, sizeof(fpt64));\r\n    std::memcpy(&ll_b, &b, sizeof(fpt64));\r\n\r\n    // Positive 0.0 is integer zero. Negative 0.0 is 0x8000000000000000.\r\n    // Map negative zero to an integer zero representation - making it\r\n    // identical to positive zero - the smallest negative number is\r\n    // represented by negative one, and downwards from there.\r\n    if (ll_a < 0x8000000000000000ULL)\r\n      ll_a = 0x8000000000000000ULL - ll_a;\r\n    if (ll_b < 0x8000000000000000ULL)\r\n      ll_b = 0x8000000000000000ULL - ll_b;\r\n\r\n    // Compare 64-bit signed integer representations of input values.\r\n    // Difference in 1 Ulp is equivalent to a relative error of between\r\n    // 1/4,000,000,000,000,000 and 1/8,000,000,000,000,000.\r\n    if (ll_a > ll_b)\r\n      return (ll_a - ll_b <= maxUlps) ? EQUAL : LESS;\r\n    return (ll_b - ll_a <= maxUlps) ? EQUAL : MORE;\r\n  }\r\n};\r\n\r\ntemplate <typename _fpt>\r\nstruct extened_exponent_fpt_traits;\r\n\r\ntemplate <>\r\nstruct extened_exponent_fpt_traits<fpt64> {\r\n public:\r\n  typedef int exp_type;\r\n  enum {\r\n    MAX_SIGNIFICANT_EXP_DIF = 54\r\n  };\r\n};\r\n\r\n// Floating point type wrapper. Allows to extend exponent boundaries to the\r\n// integer type range. This class does not handle division by zero, subnormal\r\n// numbers or NaNs.\r\ntemplate <typename _fpt, typename _traits = extened_exponent_fpt_traits<_fpt> >\r\nclass extended_exponent_fpt {\r\n public:\r\n  typedef _fpt fpt_type;\r\n  typedef typename _traits::exp_type exp_type;\r\n\r\n  explicit extended_exponent_fpt(fpt_type val) {\r\n    val_ = std::frexp(val, &exp_);\r\n  }\r\n\r\n  extended_exponent_fpt(fpt_type val, exp_type exp) {\r\n    val_ = std::frexp(val, &exp_);\r\n    exp_ += exp;\r\n  }\r\n\r\n  bool is_pos() const {\r\n    return val_ > 0;\r\n  }\r\n\r\n  bool is_neg() const {\r\n    return val_ < 0;\r\n  }\r\n\r\n  bool is_zero() const {\r\n    return val_ == 0;\r\n  }\r\n\r\n  extended_exponent_fpt operator-() const {\r\n    return extended_exponent_fpt(-val_, exp_);\r\n  }\r\n\r\n  extended_exponent_fpt operator+(const extended_exponent_fpt& that) const {\r\n    if (this->val_ == 0.0 ||\r\n        that.exp_ > this->exp_ + _traits::MAX_SIGNIFICANT_EXP_DIF) {\r\n      return that;\r\n    }\r\n    if (that.val_ == 0.0 ||\r\n        this->exp_ > that.exp_ + _traits::MAX_SIGNIFICANT_EXP_DIF) {\r\n      return *this;\r\n    }\r\n    if (this->exp_ >= that.exp_) {\r\n      exp_type exp_dif = this->exp_ - that.exp_;\r\n      fpt_type val = std::ldexp(this->val_, exp_dif) + that.val_;\r\n      return extended_exponent_fpt(val, that.exp_);\r\n    } else {\r\n      exp_type exp_dif = that.exp_ - this->exp_;\r\n      fpt_type val = std::ldexp(that.val_, exp_dif) + this->val_;\r\n      return extended_exponent_fpt(val, this->exp_);\r\n    }\r\n  }\r\n\r\n  extended_exponent_fpt operator-(const extended_exponent_fpt& that) const {\r\n    if (this->val_ == 0.0 ||\r\n        that.exp_ > this->exp_ + _traits::MAX_SIGNIFICANT_EXP_DIF) {\r\n      return extended_exponent_fpt(-that.val_, that.exp_);\r\n    }\r\n    if (that.val_ == 0.0 ||\r\n        this->exp_ > that.exp_ + _traits::MAX_SIGNIFICANT_EXP_DIF) {\r\n      return *this;\r\n    }\r\n    if (this->exp_ >= that.exp_) {\r\n      exp_type exp_dif = this->exp_ - that.exp_;\r\n      fpt_type val = std::ldexp(this->val_, exp_dif) - that.val_;\r\n      return extended_exponent_fpt(val, that.exp_);\r\n    } else {\r\n      exp_type exp_dif = that.exp_ - this->exp_;\r\n      fpt_type val = std::ldexp(-that.val_, exp_dif) + this->val_;\r\n      return extended_exponent_fpt(val, this->exp_);\r\n    }\r\n  }\r\n\r\n  extended_exponent_fpt operator*(const extended_exponent_fpt& that) const {\r\n    fpt_type val = this->val_ * that.val_;\r\n    exp_type exp = this->exp_ + that.exp_;\r\n    return extended_exponent_fpt(val, exp);\r\n  }\r\n\r\n  extended_exponent_fpt operator/(const extended_exponent_fpt& that) const {\r\n    fpt_type val = this->val_ / that.val_;\r\n    exp_type exp = this->exp_ - that.exp_;\r\n    return extended_exponent_fpt(val, exp);\r\n  }\r\n\r\n  extended_exponent_fpt& operator+=(const extended_exponent_fpt& that) {\r\n    return *this = *this + that;\r\n  }\r\n\r\n  extended_exponent_fpt& operator-=(const extended_exponent_fpt& that) {\r\n    return *this = *this - that;\r\n  }\r\n\r\n  extended_exponent_fpt& operator*=(const extended_exponent_fpt& that) {\r\n    return *this = *this * that;\r\n  }\r\n\r\n  extended_exponent_fpt& operator/=(const extended_exponent_fpt& that) {\r\n    return *this = *this / that;\r\n  }\r\n\r\n  extended_exponent_fpt sqrt() const {\r\n    fpt_type val = val_;\r\n    exp_type exp = exp_;\r\n    if (exp & 1) {\r\n      val *= 2.0;\r\n      --exp;\r\n    }\r\n    return extended_exponent_fpt(std::sqrt(val), exp >> 1);\r\n  }\r\n\r\n  fpt_type d() const {\r\n    return std::ldexp(val_, exp_);\r\n  }\r\n\r\n private:\r\n  fpt_type val_;\r\n  exp_type exp_;\r\n};\r\ntypedef extended_exponent_fpt<double> efpt64;\r\n\r\ntemplate <typename _fpt>\r\nextended_exponent_fpt<_fpt> get_sqrt(const extended_exponent_fpt<_fpt>& that) {\r\n  return that.sqrt();\r\n}\r\n\r\ntemplate <typename _fpt>\r\nbool is_pos(const extended_exponent_fpt<_fpt>& that) {\r\n  return that.is_pos();\r\n}\r\n\r\ntemplate <typename _fpt>\r\nbool is_neg(const extended_exponent_fpt<_fpt>& that) {\r\n  return that.is_neg();\r\n}\r\n\r\ntemplate <typename _fpt>\r\nbool is_zero(const extended_exponent_fpt<_fpt>& that) {\r\n  return that.is_zero();\r\n}\r\n\r\n// Very efficient stack allocated big integer class.\r\n// Supports next set of arithmetic operations: +, -, *.\r\ntemplate<std::size_t N>\r\nclass extended_int {\r\n public:\r\n  extended_int() {}\r\n\r\n  extended_int(int32 that) {\r\n    if (that > 0) {\r\n      this->chunks_[0] = that;\r\n      this->count_ = 1;\r\n    } else if (that < 0) {\r\n      this->chunks_[0] = -that;\r\n      this->count_ = -1;\r\n    } else {\r\n      this->count_ = 0;\r\n    }\r\n  }\r\n\r\n  extended_int(int64 that) {\r\n    if (that > 0) {\r\n      this->chunks_[0] = static_cast<uint32>(that);\r\n      this->chunks_[1] = that >> 32;\r\n      this->count_ = this->chunks_[1] ? 2 : 1;\r\n    } else if (that < 0) {\r\n      that = -that;\r\n      this->chunks_[0] = static_cast<uint32>(that);\r\n      this->chunks_[1] = that >> 32;\r\n      this->count_ = this->chunks_[1] ? -2 : -1;\r\n    } else {\r\n      this->count_ = 0;\r\n    }\r\n  }\r\n\r\n  extended_int(const std::vector<uint32>& chunks, bool plus = true) {\r\n    this->count_ = static_cast<int32>((std::min)(N, chunks.size()));\r\n    for (int i = 0; i < this->count_; ++i)\r\n      this->chunks_[i] = chunks[chunks.size() - i - 1];\r\n    if (!plus)\r\n      this->count_ = -this->count_;\r\n  }\r\n\r\n  template<std::size_t M>\r\n  extended_int(const extended_int<M>& that) {\r\n    this->count_ = that.count();\r\n    std::memcpy(this->chunks_, that.chunks(), that.size() * sizeof(uint32));\r\n  }\r\n\r\n  extended_int& operator=(int32 that) {\r\n    if (that > 0) {\r\n      this->chunks_[0] = that;\r\n      this->count_ = 1;\r\n    } else if (that < 0) {\r\n      this->chunks_[0] = -that;\r\n      this->count_ = -1;\r\n    } else {\r\n      this->count_ = 0;\r\n    }\r\n    return *this;\r\n  }\r\n\r\n  extended_int& operator=(int64 that) {\r\n    if (that > 0) {\r\n      this->chunks_[0] = static_cast<uint32>(that);\r\n      this->chunks_[1] = that >> 32;\r\n      this->count_ = this->chunks_[1] ? 2 : 1;\r\n    } else if (that < 0) {\r\n      that = -that;\r\n      this->chunks_[0] = static_cast<uint32>(that);\r\n      this->chunks_[1] = that >> 32;\r\n      this->count_ = this->chunks_[1] ? -2 : -1;\r\n    } else {\r\n      this->count_ = 0;\r\n    }\r\n    return *this;\r\n  }\r\n\r\n  template<std::size_t M>\r\n  extended_int& operator=(const extended_int<M>& that) {\r\n    this->count_ = that.count();\r\n    std::memcpy(this->chunks_, that.chunks(), that.size() * sizeof(uint32));\r\n    return *this;\r\n  }\r\n\r\n  bool is_pos() const {\r\n    return this->count_ > 0;\r\n  }\r\n\r\n  bool is_neg() const {\r\n    return this->count_ < 0;\r\n  }\r\n\r\n  bool is_zero() const {\r\n    return this->count_ == 0;\r\n  }\r\n\r\n  bool operator==(const extended_int& that) const {\r\n    if (this->count_ != that.count())\r\n      return false;\r\n    for (std::size_t i = 0; i < this->size(); ++i)\r\n      if (this->chunks_[i] != that.chunks()[i])\r\n        return false;\r\n    return true;\r\n  }\r\n\r\n  bool operator!=(const extended_int& that) const {\r\n    return !(*this == that);\r\n  }\r\n\r\n  bool operator<(const extended_int& that) const {\r\n    if (this->count_ != that.count())\r\n      return this->count_ < that.count();\r\n    std::size_t i = this->size();\r\n    if (!i)\r\n      return false;\r\n    do {\r\n      --i;\r\n      if (this->chunks_[i] != that.chunks()[i])\r\n        return (this->chunks_[i] < that.chunks()[i]) ^ (this->count_ < 0);\r\n    } while (i);\r\n    return false;\r\n  }\r\n\r\n  bool operator>(const extended_int& that) const {\r\n    return that < *this;\r\n  }\r\n\r\n  bool operator<=(const extended_int& that) const {\r\n    return !(that < *this);\r\n  }\r\n\r\n  bool operator>=(const extended_int& that) const {\r\n    return !(*this < that);\r\n  }\r\n\r\n  extended_int operator-() const {\r\n    extended_int ret_val = *this;\r\n    ret_val.neg();\r\n    return ret_val;\r\n  }\r\n\r\n  void neg() {\r\n    this->count_ = -this->count_;\r\n  }\r\n\r\n  extended_int operator+(const extended_int& that) const {\r\n    extended_int ret_val;\r\n    ret_val.add(*this, that);\r\n    return ret_val;\r\n  }\r\n\r\n  void add(const extended_int& e1, const extended_int& e2) {\r\n    if (!e1.count()) {\r\n      *this = e2;\r\n      return;\r\n    }\r\n    if (!e2.count()) {\r\n      *this = e1;\r\n      return;\r\n    }\r\n    if ((e1.count() > 0) ^ (e2.count() > 0)) {\r\n      dif(e1.chunks(), e1.size(), e2.chunks(), e2.size());\r\n    } else {\r\n      add(e1.chunks(), e1.size(), e2.chunks(), e2.size());\r\n    }\r\n    if (e1.count() < 0)\r\n      this->count_ = -this->count_;\r\n  }\r\n\r\n  extended_int operator-(const extended_int& that) const {\r\n    extended_int ret_val;\r\n    ret_val.dif(*this, that);\r\n    return ret_val;\r\n  }\r\n\r\n  void dif(const extended_int& e1, const extended_int& e2) {\r\n    if (!e1.count()) {\r\n      *this = e2;\r\n      this->count_ = -this->count_;\r\n      return;\r\n    }\r\n    if (!e2.count()) {\r\n      *this = e1;\r\n      return;\r\n    }\r\n    if ((e1.count() > 0) ^ (e2.count() > 0)) {\r\n      add(e1.chunks(), e1.size(), e2.chunks(), e2.size());\r\n    } else {\r\n      dif(e1.chunks(), e1.size(), e2.chunks(), e2.size());\r\n    }\r\n    if (e1.count() < 0)\r\n      this->count_ = -this->count_;\r\n  }\r\n\r\n  extended_int operator*(int32 that) const {\r\n    extended_int temp(that);\r\n    return (*this) * temp;\r\n  }\r\n\r\n  extended_int operator*(int64 that) const {\r\n    extended_int temp(that);\r\n    return (*this) * temp;\r\n  }\r\n\r\n  extended_int operator*(const extended_int& that) const {\r\n    extended_int ret_val;\r\n    ret_val.mul(*this, that);\r\n    return ret_val;\r\n  }\r\n\r\n  void mul(const extended_int& e1, const extended_int& e2) {\r\n    if (!e1.count() || !e2.count()) {\r\n      this->count_ = 0;\r\n      return;\r\n    }\r\n    mul(e1.chunks(), e1.size(), e2.chunks(), e2.size());\r\n    if ((e1.count() > 0) ^ (e2.count() > 0))\r\n      this->count_ = -this->count_;\r\n  }\r\n\r\n  const uint32* chunks() const {\r\n    return chunks_;\r\n  }\r\n\r\n  int32 count() const {\r\n    return count_;\r\n  }\r\n\r\n  std::size_t size() const {\r\n    return (std::abs)(count_);\r\n  }\r\n\r\n  std::pair<fpt64, int> p() const {\r\n    std::pair<fpt64, int> ret_val(0, 0);\r\n    std::size_t sz = this->size();\r\n    if (!sz) {\r\n      return ret_val;\r\n    } else {\r\n      if (sz == 1) {\r\n        ret_val.first = static_cast<fpt64>(this->chunks_[0]);\r\n      } else if (sz == 2) {\r\n        ret_val.first = static_cast<fpt64>(this->chunks_[1]) *\r\n                        static_cast<fpt64>(0x100000000LL) +\r\n                        static_cast<fpt64>(this->chunks_[0]);\r\n      } else {\r\n        for (std::size_t i = 1; i <= 3; ++i) {\r\n          ret_val.first *= static_cast<fpt64>(0x100000000LL);\r\n          ret_val.first += static_cast<fpt64>(this->chunks_[sz - i]);\r\n        }\r\n        ret_val.second = (sz - 3) << 5;\r\n      }\r\n    }\r\n    if (this->count_ < 0)\r\n      ret_val.first = -ret_val.first;\r\n    return ret_val;\r\n  }\r\n\r\n  fpt64 d() const {\r\n    std::pair<fpt64, int> p = this->p();\r\n    return std::ldexp(p.first, p.second);\r\n  }\r\n\r\n private:\r\n  void add(const uint32* c1, std::size_t sz1,\r\n           const uint32* c2, std::size_t sz2) {\r\n    if (sz1 < sz2) {\r\n      add(c2, sz2, c1, sz1);\r\n      return;\r\n    }\r\n    this->count_ = sz1;\r\n    uint64 temp = 0;\r\n    for (std::size_t i = 0; i < sz2; ++i) {\r\n      temp += static_cast<uint64>(c1[i]) + static_cast<uint64>(c2[i]);\r\n      this->chunks_[i] = static_cast<uint32>(temp);\r\n      temp >>= 32;\r\n    }\r\n    for (std::size_t i = sz2; i < sz1; ++i) {\r\n      temp += static_cast<uint64>(c1[i]);\r\n      this->chunks_[i] = static_cast<uint32>(temp);\r\n      temp >>= 32;\r\n    }\r\n    if (temp && (this->count_ != N)) {\r\n      this->chunks_[this->count_] = static_cast<uint32>(temp);\r\n      ++this->count_;\r\n    }\r\n  }\r\n\r\n  void dif(const uint32* c1, std::size_t sz1,\r\n           const uint32* c2, std::size_t sz2,\r\n           bool rec = false) {\r\n    if (sz1 < sz2) {\r\n      dif(c2, sz2, c1, sz1, true);\r\n      this->count_ = -this->count_;\r\n      return;\r\n    } else if ((sz1 == sz2) && !rec) {\r\n      do {\r\n        --sz1;\r\n        if (c1[sz1] < c2[sz1]) {\r\n          ++sz1;\r\n          dif(c2, sz1, c1, sz1, true);\r\n          this->count_ = -this->count_;\r\n          return;\r\n        } else if (c1[sz1] > c2[sz1]) {\r\n          ++sz1;\r\n          break;\r\n        }\r\n      } while (sz1);\r\n      if (!sz1) {\r\n        this->count_ = 0;\r\n        return;\r\n      }\r\n      sz2 = sz1;\r\n    }\r\n    this->count_ = sz1-1;\r\n    bool flag = false;\r\n    for (std::size_t i = 0; i < sz2; ++i) {\r\n      this->chunks_[i] = c1[i] - c2[i] - (flag?1:0);\r\n      flag = (c1[i] < c2[i]) || ((c1[i] == c2[i]) && flag);\r\n    }\r\n    for (std::size_t i = sz2; i < sz1; ++i) {\r\n      this->chunks_[i] = c1[i] - (flag?1:0);\r\n      flag = !c1[i] && flag;\r\n    }\r\n    if (this->chunks_[this->count_])\r\n      ++this->count_;\r\n  }\r\n\r\n  void mul(const uint32* c1, std::size_t sz1,\r\n           const uint32* c2, std::size_t sz2) {\r\n    uint64 cur = 0, nxt, tmp;\r\n    this->count_ = static_cast<int32>((std::min)(N, sz1 + sz2 - 1));\r\n    for (std::size_t shift = 0; shift < static_cast<std::size_t>(this->count_);\r\n         ++shift) {\r\n      nxt = 0;\r\n      for (std::size_t first = 0; first <= shift; ++first) {\r\n        if (first >= sz1)\r\n          break;\r\n        std::size_t second = shift - first;\r\n        if (second >= sz2)\r\n          continue;\r\n        tmp = static_cast<uint64>(c1[first]) * static_cast<uint64>(c2[second]);\r\n        cur += static_cast<uint32>(tmp);\r\n        nxt += tmp >> 32;\r\n      }\r\n      this->chunks_[shift] = static_cast<uint32>(cur);\r\n      cur = nxt + (cur >> 32);\r\n    }\r\n    if (cur && (this->count_ != N)) {\r\n      this->chunks_[this->count_] = static_cast<uint32>(cur);\r\n      ++this->count_;\r\n    }\r\n  }\r\n\r\n  uint32 chunks_[N];\r\n  int32 count_;\r\n};\r\n\r\ntemplate <std::size_t N>\r\nbool is_pos(const extended_int<N>& that) {\r\n  return that.count() > 0;\r\n}\r\n\r\ntemplate <std::size_t N>\r\nbool is_neg(const extended_int<N>& that) {\r\n  return that.count() < 0;\r\n}\r\n\r\ntemplate <std::size_t N>\r\nbool is_zero(const extended_int<N>& that) {\r\n  return !that.count();\r\n}\r\n\r\nstruct type_converter_fpt {\r\n  template <typename T>\r\n  fpt64 operator()(const T& that) const {\r\n    return static_cast<fpt64>(that);\r\n  }\r\n\r\n  template <std::size_t N>\r\n  fpt64 operator()(const extended_int<N>& that) const {\r\n    return that.d();\r\n  }\r\n\r\n  fpt64 operator()(const extended_exponent_fpt<fpt64>& that) const {\r\n    return that.d();\r\n  }\r\n};\r\n\r\nstruct type_converter_efpt {\r\n  template <std::size_t N>\r\n  extended_exponent_fpt<fpt64> operator()(const extended_int<N>& that) const {\r\n    std::pair<fpt64, int> p = that.p();\r\n    return extended_exponent_fpt<fpt64>(p.first, p.second);\r\n  }\r\n};\r\n\r\n// Voronoi coordinate type traits make it possible to extend algorithm\r\n// input coordinate range to any user provided integer type and algorithm\r\n// output coordinate range to any ieee-754 like floating point type.\r\ntemplate <typename T>\r\nstruct voronoi_ctype_traits;\r\n\r\ntemplate <>\r\nstruct voronoi_ctype_traits<int32> {\r\n  typedef int32 int_type;\r\n  typedef int64 int_x2_type;\r\n  typedef uint64 uint_x2_type;\r\n  typedef extended_int<64> big_int_type;\r\n  typedef fpt64 fpt_type;\r\n  typedef extended_exponent_fpt<fpt_type> efpt_type;\r\n  typedef ulp_comparison<fpt_type> ulp_cmp_type;\r\n  typedef type_converter_fpt to_fpt_converter_type;\r\n  typedef type_converter_efpt to_efpt_converter_type;\r\n};\r\n}  // detail\r\n}  // polygon\r\n}  // boost\r\n\r\n#endif  // BOOST_POLYGON_DETAIL_VORONOI_CTYPES\r\n", "meta": {"hexsha": "f358355ceef767c41affadbf43f491853fb7ac3b", "size": 17827, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/polygon/detail/voronoi_ctypes.hpp", "max_stars_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_stars_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_issues_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/polygon/detail/voronoi_ctypes.hpp", "max_issues_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_issues_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "ReactAndroid/build/third-party-ndk/boost/boost_1_57_0/boost/polygon/detail/voronoi_ctypes.hpp", "max_forks_repo_name": "kimwoongkyu/react-native-0-36-1-woogie", "max_forks_repo_head_hexsha": "4fb2d44945a6305ae3ca87be3872f9432d16f1fb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 27.0, "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "avg_line_length": 27.7247278383, "max_line_length": 80, "alphanum_fraction": 0.5859090144, "num_tokens": 5215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.38491213037224875, "lm_q1q2_score": 0.21044614683618404}}
{"text": "#ifndef STAN_MATH_TORSTEN_PKMODELONECPT_HPP\n#define STAN_MATH_TORSTEN_PKMODELONECPT_HPP\n\n#include <Eigen/Dense>\n#include <boost/math/tools/promotion.hpp>\n#include <stan/math/torsten/PKModel/PKModel.hpp>\n#include <stan/math/torsten/PKModel/Pred/Pred1_oneCpt.hpp>\n#include <stan/math/torsten/PKModel/Pred/PredSS_oneCpt.hpp>\n#include <string>\n#include <vector>\n\nnamespace torsten {\n\n/**\n * Computes the predicted amounts in each compartment at each event\n * for a one compartment model with first oder absorption.\n *\n * @tparam T0 type of scalar for time of events.\n * @tparam T1 type of scalar for amount at each event.\n * @tparam T2 type of scalar for rate at each event.\n * @tparam T3 type of scalar for inter-dose inteveral at each event.\n * @tparam T4 type of scalars for the model parameters.\n * @tparam T5 type of scalar for bio-variability F.\n * @tparam T6 type of scalar for lag times.\n * @param[in] pMatrix parameters at each event\n * @param[in] time times of events\n * @param[in] amt amount at each event\n * @param[in] rate rate at each event\n * @param[in] ii inter-dose interval at each event\n * @param[in] evid event identity:\n *                    (0) observation\n *                    (1) dosing\n *                    (2) other\n *                    (3) reset\n *                    (4) reset AND dosing\n * @param[in] cmt compartment number at each event\n * @param[in] addl additional dosing at each event\n * @param[in] ss steady state approximation at each event (0: no, 1: yes)\n * @return a matrix with predicted amount in each compartment\n *         at each event.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nPKModelOneCpt(const std::vector<T0>& time,\n              const std::vector<T1>& amt,\n              const std::vector<T2>& rate,\n              const std::vector<T3>& ii,\n              const std::vector<int>& evid,\n              const std::vector<int>& cmt,\n              const std::vector<int>& addl,\n              const std::vector<int>& ss,\n              const std::vector<std::vector<T4> >& pMatrix,\n              const std::vector<std::vector<T5> >& biovar,\n              const std::vector<std::vector<T6> >& tlag) {\n  using std::vector;\n  using Eigen::Dynamic;\n  using Eigen::Matrix;\n  using boost::math::tools::promote_args;\n  using stan::math::check_positive_finite;\n\n  int nCmt = 2;\n  int nParm = 3;\n\n  // Check arguments -- FIX ME: handle the new parameter arguments\n  static const char* function(\"PKModelOneCpt\");\n  torsten::pmetricsCheck(time, amt, rate, ii, evid, cmt, addl, ss,\n                pMatrix, biovar, tlag, function);\n  for (size_t i = 0; i < pMatrix.size(); i++) {\n    check_positive_finite(function, \"PK parameter CL\", pMatrix[i][0]);\n    check_positive_finite(function, \"PK parameter V2\", pMatrix[i][1]);\n  }\n\n  // FIX ME - we want to check every array of pMatrix, not\n  // just the first one (at index 0)\n  std::string message4 = \", but must equal the number of parameters in the model: \" // NOLINT\n    + boost::lexical_cast<std::string>(nParm) + \"!\";\n  const char* length_error4 = message4.c_str();\n  if (!(pMatrix[0].size() == (size_t) nParm))\n    stan::math::invalid_argument(function,\n    \"The number of parameters per event (length of a vector in the ninth argument) is\", // NOLINT\n    pMatrix[0].size(), \"\", length_error4);\n\n  std::string message5 = \", but must equal the number of compartments in the model: \" // NOLINT\n    + boost::lexical_cast<std::string>(nCmt) + \"!\";\n  const char* length_error5 = message5.c_str();\n  if (!(biovar[0].size() == (size_t) nCmt))\n    stan::math::invalid_argument(function,\n    \"The number of biovariability parameters per event (length of a vector in the tenth argument) is\", // NOLINT\n    biovar[0].size(), \"\", length_error5);\n\n  if (!(tlag[0].size() == (size_t) nCmt))\n    stan::math::invalid_argument(function,\n                                 \"The number of lag times parameters per event (length of a vector in the eleventh argument) is\", // NOLINT\n                                 tlag[0].size(), \"\", length_error5);\n\n  // Construct dummy matrix for last argument of pred\n  Eigen::Matrix<T4, Eigen::Dynamic, Eigen::Dynamic> dummy_system;\n  std::vector<Eigen::Matrix<T4, Eigen::Dynamic, Eigen::Dynamic> >\n    dummy_systems(1, dummy_system);\n\n  return Pred(time, amt, rate, ii, evid, cmt, addl, ss,\n              pMatrix, biovar, tlag,\n              nCmt, dummy_systems,\n              Pred1_oneCpt(), PredSS_oneCpt());\n}\n\n/**\n * Overload function to allow user to pass an std::vector for pMatrix.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nPKModelOneCpt(const std::vector<T0>& time,\n              const std::vector<T1>& amt,\n              const std::vector<T2>& rate,\n              const std::vector<T3>& ii,\n              const std::vector<int>& evid,\n              const std::vector<int>& cmt,\n              const std::vector<int>& addl,\n              const std::vector<int>& ss,\n              const std::vector<T4>& pMatrix,\n              const std::vector<std::vector<T5> >& biovar,\n              const std::vector<std::vector<T6> >& tlag) {\n  std::vector<std::vector<T4> > vec_pMatrix(1, pMatrix);\n\n  return PKModelOneCpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                       vec_pMatrix, biovar, tlag);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for pMatrix,\n * and biovar.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nPKModelOneCpt(const std::vector<T0>& time,\n              const std::vector<T1>& amt,\n              const std::vector<T2>& rate,\n              const std::vector<T3>& ii,\n              const std::vector<int>& evid,\n              const std::vector<int>& cmt,\n              const std::vector<int>& addl,\n              const std::vector<int>& ss,\n              const std::vector<T4>& pMatrix,\n              const std::vector<T5>& biovar,\n              const std::vector<std::vector<T6> >& tlag) {\n  std::vector<std::vector<T4> > vec_pMatrix(1, pMatrix);\n  std::vector<std::vector<T5> > vec_biovar(1, biovar);\n\n  return PKModelOneCpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                       vec_pMatrix, vec_biovar, tlag);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for pMatrix,\n * and tlag.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nPKModelOneCpt(const std::vector<T0>& time,\n              const std::vector<T1>& amt,\n              const std::vector<T2>& rate,\n              const std::vector<T3>& ii,\n              const std::vector<int>& evid,\n              const std::vector<int>& cmt,\n              const std::vector<int>& addl,\n              const std::vector<int>& ss,\n              const std::vector<T4>& pMatrix,\n              const std::vector<std::vector<T5> >& biovar,\n              const std::vector<T6>& tlag) {\n  std::vector<std::vector<T4> > vec_pMatrix(1, pMatrix);\n  std::vector<std::vector<T6> > vec_tlag(1, tlag);\n\n  return PKModelOneCpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                       vec_pMatrix, biovar, vec_tlag);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for pMatrix,\n * biovar, and tlag.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nPKModelOneCpt(const std::vector<T0>& time,\n              const std::vector<T1>& amt,\n              const std::vector<T2>& rate,\n              const std::vector<T3>& ii,\n              const std::vector<int>& evid,\n              const std::vector<int>& cmt,\n              const std::vector<int>& addl,\n              const std::vector<int>& ss,\n              const std::vector<T4>& pMatrix,\n              const std::vector<T5>& biovar,\n              const std::vector<T6>& tlag) {\n  std::vector<std::vector<T4> > vec_pMatrix(1, pMatrix);\n  std::vector<std::vector<T5> > vec_biovar(1, biovar);\n  std::vector<std::vector<T6> > vec_tlag(1, tlag);\n\n  return PKModelOneCpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                       vec_pMatrix, vec_biovar, vec_tlag);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for biovar.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nPKModelOneCpt(const std::vector<T0>& time,\n              const std::vector<T1>& amt,\n              const std::vector<T2>& rate,\n              const std::vector<T3>& ii,\n              const std::vector<int>& evid,\n              const std::vector<int>& cmt,\n              const std::vector<int>& addl,\n              const std::vector<int>& ss,\n              const std::vector<std::vector<T4> >& pMatrix,\n              const std::vector<T5>& biovar,\n              const std::vector<std::vector<T6> >& tlag) {\n  std::vector<std::vector<T5> > vec_biovar(1, biovar);\n\n  return PKModelOneCpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                       pMatrix, vec_biovar, tlag);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for biovar,\n * and tlag.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nPKModelOneCpt(const std::vector<T0>& time,\n              const std::vector<T1>& amt,\n              const std::vector<T2>& rate,\n              const std::vector<T3>& ii,\n              const std::vector<int>& evid,\n              const std::vector<int>& cmt,\n              const std::vector<int>& addl,\n              const std::vector<int>& ss,\n              const std::vector<std::vector<T4> >& pMatrix,\n              const std::vector<T5>& biovar,\n              const std::vector<T6>& tlag) {\n  std::vector<std::vector<T5> > vec_biovar(1, biovar);\n  std::vector<std::vector<T6> > vec_tlag(1, tlag);\n\n  return PKModelOneCpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                       pMatrix, vec_biovar, vec_tlag);\n}\n\n/**\n * Overload function to allow user to pass an std::vector for tlag.\n */\ntemplate <typename T0, typename T1, typename T2, typename T3, typename T4,\n          typename T5, typename T6>\nEigen::Matrix <typename boost::math::tools::promote_args<T0, T1, T2, T3,\n  typename boost::math::tools::promote_args<T4, T5, T6>::type>::type,\n  Eigen::Dynamic, Eigen::Dynamic>\nPKModelOneCpt(const std::vector<T0>& time,\n              const std::vector<T1>& amt,\n              const std::vector<T2>& rate,\n              const std::vector<T3>& ii,\n              const std::vector<int>& evid,\n              const std::vector<int>& cmt,\n              const std::vector<int>& addl,\n              const std::vector<int>& ss,\n              const std::vector<std::vector<T4> >& pMatrix,\n              const std::vector<std::vector<T5> >& biovar,\n              const std::vector<T6>& tlag) {\n  std::vector<std::vector<T6> > vec_tlag(1, tlag);\n\n  return PKModelOneCpt(time, amt, rate, ii, evid, cmt, addl, ss,\n                       pMatrix, biovar, vec_tlag);\n}\n\n}\n#endif\n", "meta": {"hexsha": "eeb2b464e98b2e2b2530c24388c3caf3239ba4aa", "size": 12283, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/PKModelOneCpt.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/PKModelOneCpt.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/torsten/PKModelOneCpt.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4966216216, "max_line_length": 139, "alphanum_fraction": 0.6115769763, "num_tokens": 3405, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.210264372097974}}
{"text": "#ifndef OFFNFACAG_HPP\n#define OFFNFACAG_HPP\n\n#include <vector>\n#include <string>\n#include <boost/serialization/list.hpp>\n#include <boost/serialization/set.hpp>\n#include <boost/serialization/vector.hpp>\n\n#include \"arch/ARLAgent.hpp\"\n#include \"bib/Seed.hpp\"\n#include \"bib/Utils.hpp\"\n#include <bib/MetropolisHasting.hpp>\n#include <bib/XMLEngine.hpp>\n#include \"nn/MLP.hpp\"\n#include \"nn/DODevMLP.hpp\"\n\ntypedef struct _sample {\n  std::vector<double> s;\n  std::vector<double> pure_a;\n  std::vector<double> a;\n  std::vector<double> next_s;\n  double r;\n  bool goal_reached;\n  double dpmu;\n\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive& ar, const unsigned int) {\n    ar& BOOST_SERIALIZATION_NVP(s);\n    ar& BOOST_SERIALIZATION_NVP(pure_a);\n    ar& BOOST_SERIALIZATION_NVP(a);\n    ar& BOOST_SERIALIZATION_NVP(next_s);\n    ar& BOOST_SERIALIZATION_NVP(r);\n    ar& BOOST_SERIALIZATION_NVP(goal_reached);\n  }\n\n  bool operator< (const _sample& b) const {\n    for (uint i = 0; i < s.size(); i++) {\n      if(s[i] != b.s[i])\n        return s[i] < b.s[i];\n    }\n\n    for (uint i = 0; i < a.size(); i++) {\n      if(a[i] != b.a[i])\n        return a[i] < b.a[i];\n    }\n\n    return false;\n  }\n\n} sample;\n\ntypedef struct _trajectory {\n  std::shared_ptr<std::deque<sample>> transitions;\n  double rewards;\n} trajectory;\n\ntemplate<typename NN = MLP>\nclass OffNFACAg : public arch::ARLAgent<arch::AgentProgOptions> {\n public:\n  typedef NN PolicyImpl;\n\n  OffNFACAg(unsigned int _nb_motors, unsigned int _nb_sensors)\n    : arch::ARLAgent<arch::AgentProgOptions>(_nb_motors, _nb_sensors), empty_action(0) {\n\n  }\n\n  virtual ~OffNFACAg() {\n    delete vnn;\n    delete ann;\n\n    delete ann_testing;\n\n    delete hidden_unit_v;\n    delete hidden_unit_a;\n  }\n\n  const std::vector<double>& _run(double reward, const std::vector<double>& sensors,\n                                  bool learning, bool goal_reached, bool) override {\n\n    // protect batch norm from testing data and poor data\n    vector<double>* next_action = ann_testing->computeOut(sensors);\n    \n    if (last_action.get() != nullptr && learning) {\n      double p0 = 1.f;\n      for(uint i=0; i < this->nb_motors; i++) {\n        p0 *= bib::Proba<double>::truncatedGaussianDensity(last_action->at(i), last_pure_action->at(i), noise);\n      }\n      trajectories.back()->transitions->push_back( {last_state, *last_pure_action, *last_action, sensors, reward, goal_reached, p0});\n    }\n\n    last_pure_action.reset(new vector<double>(*next_action));\n    if(learning) {\n      if(gaussian_policy) {\n        vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*next_action, noise);\n        delete next_action;\n        next_action = randomized_action;\n      } else if(bib::Utils::rand01() < noise) { //e-greedy\n        for (uint i = 0; i < next_action->size(); i++)\n          next_action->at(i) = bib::Utils::randin(-1.f, 1.f);\n      }\n    }\n    last_action.reset(next_action);\n\n\n    last_state.clear();\n    for (uint i = 0; i < sensors.size(); i++)\n      last_state.push_back(sensors[i]);\n\n    return *next_action;\n  }\n\n\n  void _unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map*) override {\n//     bib::Seed::setFixedSeedUTest();\n    hidden_unit_v           = bib::to_array<uint>(pt->get<std::string>(\"agent.hidden_unit_v\"));\n    hidden_unit_a           = bib::to_array<uint>(pt->get<std::string>(\"agent.hidden_unit_a\"));\n    noise                   = pt->get<double>(\"agent.noise\");\n    gaussian_policy         = pt->get<bool>(\"agent.gaussian_policy\");\n    update_delta_neg        = pt->get<bool>(\"agent.update_delta_neg\");\n    vnn_from_scratch        = pt->get<bool>(\"agent.vnn_from_scratch\");\n    update_critic_first     = pt->get<bool>(\"agent.update_critic_first\");\n    number_fitted_iteration = pt->get<uint>(\"agent.number_fitted_iteration\");\n    stoch_iter_actor        = pt->get<uint>(\"agent.stoch_iter_actor\");\n    stoch_iter_critic       = pt->get<uint>(\"agent.stoch_iter_critic\");\n    batch_norm_actor        = pt->get<uint>(\"agent.batch_norm_actor\");\n    batch_norm_critic       = pt->get<uint>(\"agent.batch_norm_critic\");\n    actor_output_layer_type = pt->get<uint>(\"agent.actor_output_layer_type\");\n    hidden_layer_type       = pt->get<uint>(\"agent.hidden_layer_type\");\n    alpha_a                 = pt->get<double>(\"agent.alpha_a\");\n    alpha_v                 = pt->get<double>(\"agent.alpha_v\");\n    lambda                  = pt->get<double>(\"agent.lambda\");\n    max_trajectory          = pt->get<uint>(\"agent.max_trajectory\");\n    offpolicy_strategy      = pt->get<uint>(\"agent.offpolicy_strategy\");\n    add_v_corrector         = pt->get<bool>(\"agent.add_v_corrector\");\n    offpolicy_actor         = pt->get<bool>(\"agent.offpolicy_actor\");\n    number_global_fitted_iteration         = pt->get<uint>(\"agent.number_global_fitted_iteration\");\n    a3c                                    = pt->get<bool>(\"agent.a3c\");\n    offpolicy_critic                       = pt->get<bool>(\"agent.offpolicy_critic\");\n    shuffle_buffer                         = pt->get<bool>(\"agent.shuffle_buffer\");\n    testing_ann_offpolicy                  = pt->get<bool>(\"agent.testing_ann_offpolicy\");\n    uint momentum           = pt->get<uint>(\"agent.momentum\");\n    testing_ann_offpolicy = false;\n//     testing_vnn                            = pt->get<bool>(\"agent.testing_vnn\");\n    gae                     = false;\n\n    if(lambda >= 0.)\n      gae = pt->get<bool>(\"agent.gae\");\n\n    if(lambda < 0. && offpolicy_critic) {\n      LOG_DEBUG(\"set lambda please!\");\n      exit(1);\n    }\n    \n    if(offpolicy_actor && !gae) {\n      LOG_DEBUG(\"to be done? (offpolicy_actor without gae)\");\n      exit(1);\n    }\n    \n    if(offpolicy_actor && a3c) {\n      LOG_DEBUG(\"a3c is on-policy\");\n      exit(1);\n    }\n    \n    if(gae && a3c) {\n      LOG_DEBUG(\"choose either gae or a3c\");\n      exit(1);\n    }\n\n    if(offpolicy_actor && gae && stoch_iter_actor > 1) {\n      LOG_DEBUG(\"to be done!\");\n      exit(1);\n    }\n\n    ann = new NN(this->get_state_size(), *hidden_unit_a, this->nb_motors, alpha_a, 1, hidden_layer_type, actor_output_layer_type,\n                 batch_norm_actor, true, momentum);\n//     if(std::is_same<NN, DODevMLP>::value)\n//       ann->exploit(pt, nullptr);\n\n    vnn = new NN(this->get_state_size(), this->get_state_size(), *hidden_unit_v, alpha_v, 1, -1, hidden_layer_type, batch_norm_critic,\n                 add_v_corrector && offpolicy_critic && offpolicy_strategy != 0, momentum);\n//     if(std::is_same<NN, DODevMLP>::value)\n//       vnn->exploit(pt, ann);\n\n    ann_testing = new NN(*ann, false, ::caffe::Phase::TEST);\n    ann_testing->increase_batchsize(1);\n\n//     if(std::is_same<NN, DODevMLP>::value) {\n//       try {\n//         if(pt->get<bool>(\"devnn.reset_learning_algo\")) {\n//           LOG_ERROR(\"NFAC cannot reset anything with DODevMLP\");\n//           exit(1);\n//         }\n//       } catch(boost::exception const& ) {\n//       }\n//     }\n    \n    best_testing_score = std::numeric_limits<double>::lowest();\n  }\n\n  void _start_episode(const std::vector<double>& sensors, bool learning) override {\n    last_state.clear();\n    for (uint i = 0; i < sensors.size(); i++)\n      last_state.push_back(sensors[i]);\n\n    last_action = nullptr;\n    last_pure_action = nullptr;\n\n    if(learning) {\n      if(trajectories.size() >= max_trajectory)\n        trajectories.pop_front();\n\n      trajectory* t = new trajectory;\n      t->transitions.reset(new std::deque<sample>);\n      t->rewards = 0;\n      trajectories.push_back(std::shared_ptr<trajectory>(t));\n    }\n\n//     if(std::is_same<NN, DODevMLP>::value && learning) {\n//       static_cast<DODevMLP *>(vnn)->inform(episode, last_sum_weighted_reward);\n//       static_cast<DODevMLP *>(ann)->inform(episode, last_sum_weighted_reward);\n//       static_cast<DODevMLP *>(ann_testing)->inform(episode, last_sum_weighted_reward);\n//     }\n\n    double* weights = new double[ann->number_of_parameters(false)];\n    ann->copyWeightsTo(weights, false);\n    ann_testing->copyWeightsFrom(weights, false);\n    delete[] weights;\n  }\n\n  void update_critic() {\n    int all_size = alltransitions();\n    if (all_size > 0) {\n      //remove trace of old policy\n      auto iter = [&]() {\n        std::vector<double> all_states(all_size * this->get_state_size());\n        std::vector<double> all_next_states(all_size * this->get_state_size());\n        std::vector<double> v_target(all_size);\n\n        int li=0;\n        for(auto one_trajectory : trajectories) {\n          const std::deque<sample>& trajectory = *one_trajectory->transitions;\n\n          for (auto it : trajectory) {\n            std::copy(it.s.begin(), it.s.end(), all_states.begin() + li * this->get_state_size());\n            std::copy(it.next_s.begin(), it.next_s.end(), all_next_states.begin() + li * this->get_state_size());\n            li++;\n          }\n        }\n        ASSERT(li == all_size, \"pb\");\n\n        decltype(vnn->computeOutVFBatch(all_next_states, empty_action)) all_nextV;\n        all_nextV = vnn->computeOutVFBatch(all_next_states, empty_action);\n\n        li=0;\n        for(auto one_trajectory : trajectories) {\n          const std::deque<sample>& trajectory = *one_trajectory->transitions;\n          for (auto it : trajectory) {\n            double target = it.r;\n            if (!it.goal_reached) {\n              double nextV = all_nextV->at(li);\n              target += this->gamma * nextV;\n            }\n\n            v_target[li] = target;\n            li++;\n          }\n        }\n        ASSERT(li == all_size, \"pb\");\n//         bib::Logger::PRINT_ELEMENTS(v_target, \"v_target\");\n\n        if(vnn_from_scratch) {\n          delete vnn;\n          vnn = new NN(this->get_state_size(), this->get_state_size(), *hidden_unit_v, alpha_v, all_size, -1, hidden_layer_type,\n                       batch_norm_critic, add_v_corrector);\n        }\n        if(lambda < 0.f)\n          vnn->learn_batch(all_states, empty_action, v_target, stoch_iter_critic);\n        else {\n          auto all_V = vnn->computeOutVFBatch(all_states, empty_action);\n          std::vector<double> deltas(all_size);\n          //\n          //        Simple computation for lambda return\n          //\n          for (int i=0; i<all_size; i++)\n            deltas[i] = v_target[i] - all_V->at(i);\n\n          std::vector<double>* all_pi;\n          double* ptheta;\n          double max_ptheta;\n          std::vector<double>* sample_weight;\n          if(offpolicy_strategy != 0 && offpolicy_critic) {\n            ann->increase_batchsize(all_size);\n            if(testing_ann_offpolicy){\n              ann_testing->copyParametersFrom(ann);\n              ann_testing->increase_batchsize(all_size);\n              all_pi = ann_testing->computeOutBatch(all_states);\n              ann_testing->increase_batchsize(1);\n            }\n            else\n              all_pi = ann->computeOutBatch(all_states);\n            ptheta = new double[all_size];\n\n            uint i=0;\n            if(offpolicy_strategy >= 1 && offpolicy_strategy <= 3) {\n              for(auto one_trajectory : trajectories) {\n                const std::deque<sample>& trajectory = *one_trajectory->transitions;\n                for (auto it : trajectory) {\n                  double p0 = 1.f;\n                  for(uint j=0; j < this->nb_motors; j++)\n                    p0 *= bib::Proba<double>::truncatedGaussianDensity(it.a[j], all_pi->at(i*this->nb_motors+j), noise);\n\n                  ptheta[i] = p0;\n                  i++;\n                }\n              }\n              max_ptheta = *std::max_element(ptheta, ptheta+all_size);\n            }\n\n            if(add_v_corrector)\n              sample_weight = new std::vector<double>(all_size);\n          }\n\n          std::vector<double> diff(all_size);\n          int index_shift=0;\n          for(auto one_trajectory : trajectories) {\n            const std::deque<sample>& trajectory = *one_trajectory->transitions;\n            li=0;\n            for (auto it : trajectory) {\n              diff[index_shift+li] = 0;\n//               offpolicy_strategy\n//               0 : lambda only\n//               1 : lambda \\pi (TB)\n//               2 : \\pi / \\mu (IS)\n//               3 : lambda min(1,\\pi / \\mu) (Retrace)\n//               4 : lambda * (1-||a_t - \\pi||) (ours)\n//               5 : lambda * (1-min(||a_t - \\pi||, ||u_t - \\pi|| )) (ours)\n              if(offpolicy_strategy == 0 || !offpolicy_critic) {\n                for (uint n=li; n<trajectory.size(); n++)\n                  diff[index_shift+li] += std::pow(this->gamma * lambda, n-li) * deltas[index_shift+n];\n              } else if(offpolicy_strategy == 1) {\n//                 for (int n=trajectory.size()-1; n>=li; n--){\n//                   double ci = 1.f;\n//                   for(int subn = 0;subn<n-li;subn++)\n//                     ci = ci * lambda;\n//                   diff[index_shift+li] += std::pow(this->gamma, n-li) * ci * deltas[index_shift+n];\n//                 }\n                double target_sum = 0;\n                for (int n=trajectory.size()-1; n>=li; n--) {\n                  target_sum += deltas[index_shift+n];\n                  diff[index_shift+li] = target_sum;\n                  target_sum *= this->gamma * lambda * (ptheta[index_shift+n]/max_ptheta);\n                }\n                if(add_v_corrector)\n                  sample_weight->at(index_shift+li) = ptheta[index_shift+li]/max_ptheta;\n              } else if(offpolicy_strategy == 2) {\n                double target_sum = 0;\n                for (int n=trajectory.size()-1; n>=li; n--) {\n                  target_sum += deltas[index_shift+n];\n                  diff[index_shift+li] = target_sum;\n                  target_sum *= this->gamma * lambda * (ptheta[index_shift+n]/trajectory[n].dpmu);\n                }\n                if(add_v_corrector)\n                  sample_weight->at(index_shift+li) = ptheta[index_shift+li]/trajectory[li].dpmu;\n              } else if(offpolicy_strategy == 3) {\n                double target_sum = 0;\n                for (int n=trajectory.size()-1; n>=li; n--) {\n                  target_sum += deltas[index_shift+n];\n                  diff[index_shift+li] = target_sum;\n                  target_sum *= this->gamma * lambda * std::min((double)1.f,ptheta[index_shift+n]/trajectory[n].dpmu);\n                }\n                if(add_v_corrector)\n                  sample_weight->at(index_shift+li) = std::min((double)1.f,ptheta[index_shift+li]/trajectory[li].dpmu);\n              } else if(offpolicy_strategy == 4) {\n                double target_sum = 0;\n                for (int n=trajectory.size()-1; n>=li; n--) {\n                  target_sum += deltas[index_shift+n];\n                  diff[index_shift+li] = target_sum;\n                  target_sum *= this->gamma * lambda * (1.f - l2dist(trajectory[n].a, *all_pi, index_shift+n));\n                }\n                if(add_v_corrector)\n                  sample_weight->at(index_shift+li) = 1.f - l2dist(trajectory[li].a, *all_pi, index_shift+li);\n              } else if(offpolicy_strategy == 5) {\n                double target_sum = 0;\n                for (int n=trajectory.size()-1; n>=li; n--) {\n                  target_sum += deltas[index_shift+n];\n                  diff[index_shift+li] = target_sum;\n                  target_sum *= this->gamma * lambda *\n                                (1.f - std::min(l2dist(trajectory[n].a, *all_pi, index_shift+n),\n                                                l2dist(trajectory[n].pure_a, *all_pi, index_shift+n)));\n                }\n                if(add_v_corrector)\n                  sample_weight->at(index_shift+li) = 1.f - std::min(l2dist(trajectory[li].a, *all_pi, index_shift+li),\n                                                      l2dist(trajectory[li].pure_a, *all_pi, index_shift+li));\n              }\n\n              li++;\n            }\n            ASSERT(diff[index_shift+trajectory.size() -1] == deltas[index_shift+trajectory.size() -1], \"pb lambda \");\n            index_shift += trajectory.size();\n          }\n          ASSERT(index_shift == all_size, \"index pb\");\n\n          // comment following lines to compare with the other formula\n          for (int i=0; i<all_size; i++)\n            diff[i] = diff[i] + all_V->at(i);\n\n//           bib::Logger::PRINT_ELEMENTS(*all_V, \"all v \");\n//           bib::Logger::PRINT_ELEMENTS(diff, \"final diff \");\n          if(!offpolicy_critic){\n            int size_last_traj = trajectories.back()->transitions->size();\n            vnn->increase_batchsize(size_last_traj);\n            \n            std::vector<double> subdiff(size_last_traj);\n            std::vector<double> subsensors(size_last_traj * this->get_state_size());\n            \n            const std::deque<sample>& trajectory = *trajectories.back()->transitions;\n            \n            li=0;\n            for (auto it : trajectory){\n              std::copy(it.s.begin(), it.s.end(), subsensors.begin() + li * this->get_state_size());\n              li++;\n            }\n            \n            int index=size_last_traj-1;\n            for(li=all_size - 1;li>=(all_size-size_last_traj);li--){\n              subdiff[index]=diff[li];\n              index--;\n            }\n            vnn->learn_batch(subsensors, empty_action, subdiff, stoch_iter_critic);\n            \n            vnn->increase_batchsize(all_size);\n          } else if(offpolicy_strategy != 0 && add_v_corrector)\n            vnn->learn_batch_lw(all_states, empty_action, diff, *sample_weight, stoch_iter_critic);\n          else\n            vnn->learn_batch(all_states, empty_action, diff, stoch_iter_critic);\n\n          if(offpolicy_strategy != 0 && offpolicy_critic) {\n            delete[] ptheta;\n            delete all_pi;\n            if(add_v_corrector)\n              delete sample_weight;\n          }\n\n          delete all_V;\n        }\n\n        delete all_nextV;\n      };\n\n      for(uint i=0; i<number_fitted_iteration; i++)\n        iter();\n    }\n  }\n\n  void end_episode(bool learning) override {\n    //     LOG_FILE(\"policy_exploration\", ann->hash());\n    if(!learning)\n      return;\n    \n    ann->update_best_param_previous_task(sum_weighted_reward);\n    vnn->update_best_param_previous_task(sum_weighted_reward);\n    ann_testing->update_best_param_previous_task(sum_weighted_reward);\n\n    uint all_size = alltransitions();\n    if(all_size > 0) {\n      vnn->increase_batchsize(all_size);\n    }\n\n    for(uint fi = 0 ; fi < number_global_fitted_iteration; fi++){\n      if(update_critic_first)\n        update_critic();\n\n      if(!offpolicy_actor){\n        if(a3c)\n          actor_update_onpolicy_a3c();\n        else\n          actor_update_onpolicy();\n      } else\n        actor_update_offpolicy();\n\n      if(!update_critic_first) {\n        if(all_size > 0 && !offpolicy_actor) {\n          vnn->increase_batchsize(all_size);\n        }\n        update_critic();\n      }\n    }\n    \n    if(shuffle_buffer){\n      std::random_shuffle(trajectories.begin(), trajectories.end());\n    }\n  }\n\n  void end_instance(bool learning) override {\n    if(learning)\n      episode++;\n  }\n\n  void actor_update_onpolicy() {\n    const std::deque<sample>& trajectory = *trajectories.back()->transitions;\n    vnn->increase_batchsize(trajectory.size());\n    if (trajectory.size() > 0) {\n      std::vector<double> sensors(trajectory.size() * this->get_state_size());\n      std::vector<double> actions(trajectory.size() * this->nb_motors);\n      std::vector<bool> disable_back(trajectory.size() * this->nb_motors, false);\n      const std::vector<bool> disable_back_ac(this->nb_motors, true);\n      std::vector<double> deltas_blob(trajectory.size() * this->nb_motors);\n      std::vector<double> deltas(trajectory.size());\n\n      std::vector<double> all_states(trajectory.size() * this->get_state_size());\n      std::vector<double> all_next_states(trajectory.size() * this->get_state_size());\n      uint li=0;\n      for (auto it : trajectory) {\n        std::copy(it.s.begin(), it.s.end(), all_states.begin() + li * this->get_state_size());\n        std::copy(it.next_s.begin(), it.next_s.end(), all_next_states.begin() + li * this->get_state_size());\n        li++;\n      }\n\n      decltype(vnn->computeOutVFBatch(all_next_states, empty_action)) all_nextV, all_mine;\n      all_nextV = vnn->computeOutVFBatch(all_next_states, empty_action);\n      all_mine = vnn->computeOutVFBatch(all_states, empty_action);\n\n      li=0;\n      for (auto it : trajectory) {\n        sample sm = it;\n        double v_target = sm.r;\n        if (!sm.goal_reached) {\n          double nextV = all_nextV->at(li);\n          v_target += this->gamma * nextV;\n        }\n\n        deltas[li] = v_target - all_mine->at(li);\n        ++li;\n      }\n\n      if(gae) {\n        //\n        //        Simple computation for lambda return\n        //\n        std::vector<double> diff(trajectory.size());\n        li=0;\n        for (auto it : trajectory) {\n          diff[li] = 0;\n          for (uint n=li; n<trajectory.size(); n++)\n            diff[li] += std::pow(this->gamma * lambda, n-li) * deltas[n];\n          li++;\n        }\n\n        ASSERT(diff[trajectory.size() -1] == deltas[trajectory.size() -1], \"pb lambda\");\n        li=0;\n        for (auto it : trajectory) {\n          //           diff[li] = diff[li] + all_V->at(li);\n          deltas[li] = diff[li];\n          ++li;\n        }\n      }\n\n      uint n=0;\n      li=0;\n      for(auto it = trajectory.begin(); it != trajectory.end() ; ++it) {\n        sample sm = *it;\n\n        std::copy(it->s.begin(), it->s.end(), sensors.begin() + li * this->get_state_size());\n        if(deltas[li] > 0.) {\n          std::copy(it->a.begin(), it->a.end(), actions.begin() + li * this->nb_motors);\n          n++;\n        } else if(update_delta_neg) {\n          std::copy(it->pure_a.begin(), it->pure_a.end(), actions.begin() + li * this->nb_motors);\n        } else {\n          std::copy(it->a.begin(), it->a.end(), actions.begin() + li * this->nb_motors);\n          std::copy(disable_back_ac.begin(), disable_back_ac.end(), disable_back.begin() + li * this->nb_motors);\n        }\n        std::fill(deltas_blob.begin() + li * this->nb_motors, deltas_blob.begin() + (li+1) * this->nb_motors, deltas[li]);\n        li++;\n      }\n\n      ann->increase_batchsize(trajectory.size());\n      if(n > 0) {\n        for(uint sia = 0; sia < stoch_iter_actor; sia++) {\n          //learn BN\n          std::vector<double>* ac_out = ann->computeOutBatch(sensors);\n          if(batch_norm_actor != 0){\n            //re-compute ac_out with BN as testing\n            ann_testing->copyParametersFrom(ann);\n            ann_testing->increase_batchsize(trajectory.size());\n            delete ac_out;\n            ac_out = ann_testing->computeOutBatch(sensors);\n            if(sia + 1 == stoch_iter_actor )\n              ann_testing->increase_batchsize(1);\n          }\n\n          const auto actor_actions_blob = ann->getNN()->blob_by_name(MLP::actions_blob_name);\n          auto ac_diff = actor_actions_blob->mutable_cpu_diff();\n          for(int i=0; i<actor_actions_blob->count(); i++) {\n            if(disable_back[i]) {\n              ac_diff[i] = 0.00000000f;\n            } else {\n              double x = actions[i] - ac_out->at(i);\n              ac_diff[i] = -x;\n            }\n          }\n          ann->actor_backward();\n          ann->regularize();\n          ann->getSolver()->ApplyUpdate();\n          ann->getSolver()->set_iter(ann->getSolver()->iter() + 1);\n          delete ac_out;\n        }\n      }\n\n      delete all_nextV;\n      delete all_mine;\n    }\n  }\n  \n  void actor_update_onpolicy_a3c() {\n    const std::deque<sample>& trajectory = *trajectories.back()->transitions;\n    vnn->increase_batchsize(trajectory.size());\n    if (trajectory.size() > 0) {\n      std::vector<double> sensors(trajectory.size() * this->get_state_size());\n      std::vector<double> actions(trajectory.size() * this->nb_motors);\n      std::vector<double> deltas_blob(trajectory.size() * this->nb_motors);\n      std::vector<double> deltas(trajectory.size());\n      \n      std::vector<double> all_states(trajectory.size() * this->get_state_size());\n      std::vector<double> all_next_states(trajectory.size() * this->get_state_size());\n      uint li=0;\n      for (auto it : trajectory) {\n        std::copy(it.s.begin(), it.s.end(), all_states.begin() + li * this->get_state_size());\n        std::copy(it.next_s.begin(), it.next_s.end(), all_next_states.begin() + li * this->get_state_size());\n        li++;\n      }\n      \n      decltype(vnn->computeOutVFBatch(all_next_states, empty_action)) all_nextV, all_mine;\n      all_nextV = vnn->computeOutVFBatch(all_next_states, empty_action);\n      all_mine = vnn->computeOutVFBatch(all_states, empty_action);\n      \n      li=0;\n      double sum_gamma_rt = 0;\n      for (auto it : trajectory) {\n        sample sm = it;\n        sum_gamma_rt += std::pow(gamma, li) * sm.r;\n        double v_target = sum_gamma_rt;\n        if (!sm.goal_reached) {\n          double nextV = all_nextV->at(li);\n          v_target += std::pow(this->gamma, li+1) * nextV;\n        }\n        \n        deltas[li] =  v_target - all_mine->at(li);\n        ++li;\n      }\n\n      li=0;\n      for(auto it = trajectory.begin(); it != trajectory.end() ; ++it) {\n        sample sm = *it;\n        \n        std::copy(it->s.begin(), it->s.end(), sensors.begin() + li * this->get_state_size());\n        std::copy(it->a.begin(), it->a.end(), actions.begin() + li * this->nb_motors);\n        std::fill(deltas_blob.begin() + li * this->nb_motors, deltas_blob.begin() + (li+1) * this->nb_motors, deltas[li]);\n        li++;\n      }\n      \n      for(uint sia = 0; sia < stoch_iter_actor; sia++) {\n        ann->increase_batchsize(trajectory.size());\n        auto ac_out = ann->computeOutBatch(sensors);\n        if(batch_norm_actor != 0){\n          //re-compute ac_out with BN as testing\n          ann_testing->copyParametersFrom(ann);\n          ann_testing->increase_batchsize(trajectory.size());\n          delete ac_out;\n          ac_out = ann_testing->computeOutBatch(sensors);\n          if(sia + 1 == stoch_iter_actor )\n            ann_testing->increase_batchsize(1);\n        }\n        \n        const auto actor_actions_blob = ann->getNN()->blob_by_name(MLP::actions_blob_name);\n        auto ac_diff = actor_actions_blob->mutable_cpu_diff();\n        for(int i=0; i<actor_actions_blob->count(); i++) {\n            double x = actions[i] - ac_out->at(i);\n            ac_diff[i] = -x*deltas_blob[i];\n        }\n        ann->actor_backward();\n        ann->regularize();\n        ann->getSolver()->ApplyUpdate();\n        ann->getSolver()->set_iter(ann->getSolver()->iter() + 1);\n        delete ac_out;\n      }\n      \n      delete all_nextV;\n      delete all_mine;\n    }\n  }\n\n  void actor_update_offpolicy() {\n    int all_size = alltransitions();\n    ann->increase_batchsize(all_size);\n\n    std::vector<double> sensors(all_size * this->get_state_size());\n    std::vector<double> actions(all_size * this->nb_motors);\n    std::vector<bool> disable_back(all_size * this->nb_motors, false);\n    const std::vector<bool> disable_back_ac(this->nb_motors, true);\n    std::vector<double> deltas_blob(all_size * this->nb_motors);\n    std::vector<double> deltas(all_size);\n\n    std::vector<double> all_states(all_size * this->get_state_size());\n    std::vector<double> all_next_states(all_size * this->get_state_size());\n\n    int li=0;\n    for(auto one_trajectory : trajectories) {\n      const std::deque<sample>& trajectory = *one_trajectory->transitions;\n      for (auto it : trajectory) {\n        std::copy(it.s.begin(), it.s.end(), all_states.begin() + li * this->get_state_size());\n        std::copy(it.next_s.begin(), it.next_s.end(), all_next_states.begin() + li * this->get_state_size());\n        li++;\n      }\n    }\n\n    decltype(vnn->computeOutVFBatch(all_next_states, empty_action)) all_nextV, all_mine;\n    all_nextV = vnn->computeOutVFBatch(all_next_states, empty_action);\n    all_mine = vnn->computeOutVFBatch(all_states, empty_action);\n\n    li=0;\n    for(auto one_trajectory : trajectories) {\n      const std::deque<sample>& trajectory = *one_trajectory->transitions;\n      for (auto it : trajectory) {\n        sample sm = it;\n        double v_target = sm.r;\n        if (!sm.goal_reached) {\n          double nextV = all_nextV->at(li);\n          v_target += this->gamma * nextV;\n        }\n\n        deltas[li] = v_target - all_mine->at(li);\n        ++li;\n      }\n    }\n\n    \n    if(gae) {\n      //\n      //        Simple computation for lambda return\n      //\n      std::vector<double>* all_pi;\n      std::vector<double> diff(all_size);\n      int index_shift=0;\n      double* ptheta;\n      double max_ptheta;\n      if(offpolicy_strategy != 0) {\n        if(testing_ann_offpolicy){\n          ann_testing->copyParametersFrom(ann);\n          ann_testing->increase_batchsize(all_size);\n          all_pi = ann_testing->computeOutBatch(all_states);\n          ann_testing->increase_batchsize(1);\n        } else\n          all_pi = ann->computeOutBatch(all_states);\n        ptheta = new double[all_size];\n\n        uint i=0;\n        if(offpolicy_strategy >= 1 && offpolicy_strategy <= 3) {\n          for(auto one_trajectory : trajectories) {\n            const std::deque<sample>& trajectory = *one_trajectory->transitions;\n            for (auto it : trajectory) {\n              double p0 = 1.f;\n              for(uint j=0; j < this->nb_motors; j++)\n                p0 *= bib::Proba<double>::truncatedGaussianDensity(it.a[j], all_pi->at(i*this->nb_motors+j), noise);\n\n              ptheta[i] = p0;\n              i++;\n            }\n          }\n          max_ptheta = *std::max_element(ptheta, ptheta+all_size);\n        }\n      }\n      for(auto one_trajectory : trajectories) {\n        li=0;\n        const std::deque<sample>& trajectory = *one_trajectory->transitions;\n        for (auto it : trajectory) {\n          diff[index_shift+li] = 0;\n          if(offpolicy_strategy == 0) {\n            for (uint n=li; n<trajectory.size(); n++)\n              diff[index_shift+li] += std::pow(this->gamma * lambda, n-li) * deltas[index_shift+n];\n          } else if(offpolicy_strategy == 1) {\n            double target_sum = 0;\n            for (int n=trajectory.size()-1; n>=li; n--) {\n              target_sum += deltas[index_shift+n];\n              diff[index_shift+li] = target_sum;\n              target_sum *= this->gamma * lambda * (ptheta[index_shift+n]/max_ptheta);\n            }\n            if(add_v_corrector)\n              diff[index_shift+li] *= ptheta[index_shift+li]/max_ptheta;\n          } else if(offpolicy_strategy == 2) {\n            double target_sum = 0;\n            for (int n=trajectory.size()-1; n>=li; n--) {\n              target_sum += deltas[index_shift+n];\n              diff[index_shift+li] = target_sum;\n              target_sum *= this->gamma * lambda * (ptheta[index_shift+n]/trajectory[n].dpmu);\n            }\n            if(add_v_corrector)\n              diff[index_shift+li] *= ptheta[index_shift+li]/trajectory[li].dpmu;\n          } else if(offpolicy_strategy == 3) {\n            double target_sum = 0;\n            for (int n=trajectory.size()-1; n>=li; n--) {\n              target_sum += deltas[index_shift+n];\n              diff[index_shift+li] = target_sum;\n              target_sum *= this->gamma * lambda * std::min((double)1.f,ptheta[index_shift+n]/trajectory[n].dpmu);\n            }\n            if(add_v_corrector)\n              diff[index_shift+li] *= std::min((double)1.f,ptheta[index_shift+li]/trajectory[li].dpmu);\n          } else if(offpolicy_strategy == 4) {\n            double target_sum = 0;\n            for (int n=trajectory.size()-1; n>=li; n--) {\n              target_sum += deltas[index_shift+n];\n              diff[index_shift+li] = target_sum;\n              target_sum *= this->gamma * lambda * (1.f - l2dist(trajectory[n].a, *all_pi, index_shift+n));\n            }\n            if(add_v_corrector)\n              diff[index_shift+li] *= 1.f - l2dist(trajectory[li].a, *all_pi, index_shift+li);\n          } else if(offpolicy_strategy == 5) {\n            double target_sum = 0;\n            for (int n=trajectory.size()-1; n>=li; n--) {\n              target_sum += deltas[index_shift+n];\n              diff[index_shift+li] = target_sum;\n              target_sum *= this->gamma * lambda *\n                            (1.f - std::min(l2dist(trajectory[n].a, *all_pi, index_shift+n),\n                                            l2dist(trajectory[n].pure_a, *all_pi, index_shift+n)));\n            }\n            if(add_v_corrector)\n              diff[index_shift+li] *= 1.f - std::min(l2dist(trajectory[li].a, *all_pi, index_shift+li),\n                                                     l2dist(trajectory[li].pure_a, *all_pi, index_shift+li));\n          }\n          li++;\n        }\n        ASSERT(diff[index_shift+trajectory.size() -1] == deltas[index_shift+trajectory.size() -1], \"pb lambda\");\n        index_shift += trajectory.size();\n      }\n\n      if(offpolicy_strategy != 0) {\n        delete all_pi;\n        delete [] ptheta;\n      }\n\n      for (li=0; li < all_size; li++) {\n        //           diff[li] = diff[li] + all_V->at(li);\n        deltas[li] = diff[li];\n      }\n    }\n\n    uint n=0;\n    li=0;\n    for(auto one_trajectory : trajectories) {\n      const std::deque<sample>& trajectory = *one_trajectory->transitions;\n      for(auto it = trajectory.begin(); it != trajectory.end() ; ++it) {\n        std::copy(it->s.begin(), it->s.end(), sensors.begin() + li * this->get_state_size());\n        if(deltas[li] > 0.) {\n          std::copy(it->a.begin(), it->a.end(), actions.begin() + li * this->nb_motors);\n          n++;\n        } else if(update_delta_neg) {\n          std::copy(it->pure_a.begin(), it->pure_a.end(), actions.begin() + li * this->nb_motors);\n        } else {\n          std::copy(it->a.begin(), it->a.end(), actions.begin() + li * this->nb_motors);\n          std::copy(disable_back_ac.begin(), disable_back_ac.end(), disable_back.begin() + li * this->nb_motors);\n        }\n        std::fill(deltas_blob.begin() + li * this->nb_motors, deltas_blob.begin() + (li+1) * this->nb_motors, deltas[li]);\n        li++;\n      }\n    }\n\n    if(n > 0) {\n      for(uint sia = 0; sia < stoch_iter_actor; sia++) {\n        std::vector<double>* ac_out = ann->computeOutBatch(sensors);\n        if(batch_norm_actor != 0){\n          //re-compute ac_out with BN as testing\n          ann_testing->copyParametersFrom(ann);\n          ann_testing->increase_batchsize(all_size);\n          delete ac_out;\n          ac_out = ann_testing->computeOutBatch(sensors);\n          if(sia + 1 == stoch_iter_actor )\n            ann_testing->increase_batchsize(1);\n        }\n\n        const auto actor_actions_blob = ann->getNN()->blob_by_name(MLP::actions_blob_name);\n        auto ac_diff = actor_actions_blob->mutable_cpu_diff();\n        for(int i=0; i<actor_actions_blob->count(); i++) {\n          if(disable_back[i]) {\n            ac_diff[i] = 0.00000000f;\n          } else {\n            double x = actions[i] - ac_out->at(i);\n            ac_diff[i] = -x;\n          }\n        }\n        ann->actor_backward();\n        ann->regularize();\n        ann->getSolver()->ApplyUpdate();\n        ann->getSolver()->set_iter(ann->getSolver()->iter() + 1);\n        delete ac_out;\n      }\n    }\n\n    delete all_nextV;\n    delete all_mine;\n  }\n\n  void save(const std::string& path, bool save_best, bool learning) override {\n    if(save_best && !learning && best_testing_score < this->sum_weighted_reward){\n      ann->save(path+\".actor\");\n      best_testing_score = this->sum_weighted_reward;\n    } else if(!save_best && learning){\n      ann->save(path+\".actor\");\n      vnn->save(path+\".critic\");\n    }\n  }\n\n  void save_run() override {\n    ann->save(\"continue.actor\");\n    vnn->save(\"continue.critic\");\n    struct algo_state st = {episode};\n    bib::XMLEngine::save(st, \"algo_state\", \"continue.algo_state.data\");\n  }\n\n  void load(const std::string& path) override {\n    ann->load(path+\".actor\");\n    vnn->load(path+\".critic\");\n  }\n\n  void load_previous_run() override {\n    ann->load(\"continue.actor\");\n    vnn->load(\"continue.critic\");\n    auto p3 = bib::XMLEngine::load<struct algo_state>(\"algo_state\", \"continue.algo_state.data\");\n    episode = p3->episode;\n    delete p3;\n  }\n\n protected:\n\n  void _display(std::ostream& out) const override {\n    out << std::setw(12) << std::fixed << std::setprecision(10) << this->sum_weighted_reward << \" \" << std::setw(\n          8) << std::fixed << std::setprecision(5) << vnn->error() << \" \" << noise << \" \" << alltransitions();\n  }\n\n  void _dump(std::ostream& out) const override {\n    out << std::setw(25) << std::fixed << std::setprecision(22) <<\n        this->sum_weighted_reward << \" \" << std::setw(8) << std::fixed <<\n        std::setprecision(5) << vnn->error() << \" \" << alltransitions() ;\n  }\n\n  uint alltransitions() const {\n    uint count=0;\n    for (auto it : trajectories)\n      count += it->transitions->size();\n    return count;\n  }\n\n  double sign(double x) {\n    if(x>=0)\n      return 1.f;\n    return -1.f;\n  }\n\n  double l2dist(const std::vector<double>& a, const std::vector<double>& b, const uint start) const {\n    double r = 0.f;\n    for(uint i=0; i<a.size(); i++) {\n      double d = (a[i] - b[start+i]);\n      r += d*d;\n    }\n    return sqrt(r)/(2.f *((double) a.size()));\n  }\n\n private:\n  uint episode = 0;\n\n  double noise;\n  bool gaussian_policy, vnn_from_scratch, update_critic_first,\n       update_delta_neg, gae, add_v_corrector, offpolicy_actor;\n  uint number_fitted_iteration, stoch_iter_actor, stoch_iter_critic;\n  uint batch_norm_actor, batch_norm_critic, actor_output_layer_type,\n       hidden_layer_type, max_trajectory, offpolicy_strategy;\n  double lambda;\n  uint number_global_fitted_iteration;\n  bool offpolicy_critic, a3c, shuffle_buffer, testing_ann_offpolicy;\n\n  std::shared_ptr<std::vector<double>> last_action;\n  std::shared_ptr<std::vector<double>> last_pure_action;\n  std::vector<double> last_state;\n  double alpha_v, alpha_a;\n\n  std::deque<std::shared_ptr<trajectory>> trajectories;\n\n  NN* ann;\n  NN* vnn;\n  NN* ann_testing;\n  //to make video on determinist env\n  double best_testing_score;\n\n  std::vector<uint>* hidden_unit_v;\n  std::vector<uint>* hidden_unit_a;\n  std::vector<double> empty_action; //dummy action cause c++ cannot accept null reference\n\n  struct algo_state {\n    uint episode;\n\n    friend class boost::serialization::access;\n    template <typename Archive>\n    void serialize(Archive& ar, const unsigned int) {\n      ar& BOOST_SERIALIZATION_NVP(episode);\n    }\n  };\n};\n\n#endif\n\n\n", "meta": {"hexsha": "db4d2403980f8e458d66527b1f99a61654760abe", "size": 38498, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "agent/cacla/include/OffNFACAg.hpp", "max_stars_repo_name": "matthieu637/ddrl", "max_stars_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T09:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T13:50:23.000Z", "max_issues_repo_path": "agent/cacla/include/OffNFACAg.hpp", "max_issues_repo_name": "matthieu637/ddrl", "max_issues_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-10-09T14:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T15:01:00.000Z", "max_forks_repo_path": "agent/cacla/include/OffNFACAg.hpp", "max_forks_repo_name": "matthieu637/ddrl", "max_forks_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-16T09:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-15T14:35:40.000Z", "avg_line_length": 38.0039486673, "max_line_length": 134, "alphanum_fraction": 0.5737440906, "num_tokens": 9670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.21018419632655821}}
{"text": "#include <Eigen/Dense>\n#include \"control.hpp\"\n#include \"defines.hpp\"\n#include \"fad.hpp\"\n#include \"global_residual.hpp\"\n#include \"J2.hpp\"\n#include \"material_params.hpp\"\n\nnamespace calibr8 {\n\nstatic ParameterList get_valid_local_residual_params() {\n  ParameterList p;\n  p.set<std::string>(\"type\", \"J2\");\n  p.set<int>(\"nonlinear max iters\", 0);\n  p.set<double>(\"nonlinear absolute tol\", 0.);\n  p.set<double>(\"nonlinear relative tol\", 0.);\n  p.sublist(\"materials\");\n  return p;\n}\n\nstatic ParameterList get_valid_material_params() {\n  ParameterList p;\n  p.set<double>(\"E\", 0.);\n  p.set<double>(\"nu\", 0.);\n  p.set<double>(\"K\", 0.);\n  p.set<double>(\"Y\", 0.);\n  return p;\n}\n\ntemplate <typename T>\nJ2<T>::J2(ParameterList const& inputs, int ndims) {\n\n  this->m_params_list = inputs;\n  this->m_params_list.validateParameters(get_valid_local_residual_params(), 0);\n\n  int const num_residuals = 3;\n\n  this->m_num_residuals = num_residuals;\n  this->m_num_eqs.resize(num_residuals);\n  this->m_var_types.resize(num_residuals);\n  this->m_resid_names.resize(num_residuals);\n\n\n  this->m_resid_names[0] = \"zeta\";\n  this->m_var_types[0] = SYM_TENSOR;\n  this->m_num_eqs[0] = get_num_eqs(SYM_TENSOR, ndims);\n\n  this->m_resid_names[1] = \"Ie\";\n  this->m_var_types[1] = SCALAR;\n  this->m_num_eqs[1] = get_num_eqs(SCALAR, ndims);\n\n  this->m_resid_names[2] = \"alpha\";\n  this->m_var_types[2] = SCALAR;\n  this->m_num_eqs[2] = get_num_eqs(SCALAR, ndims);\n\n  m_max_iters = inputs.get<int>(\"nonlinear max iters\");\n  m_abs_tol = inputs.get<double>(\"nonlinear absolute tol\");\n  m_rel_tol = inputs.get<double>(\"nonlinear relative tol\");\n\n}\n\ntemplate <typename T>\nJ2<T>::~J2() {\n}\n\ntemplate <typename T>\nvoid J2<T>::init_params() {\n\n  int const num_params = 4;\n  this->m_params.resize(num_params);\n  this->m_param_names.resize(num_params);\n\n  this->m_param_names.resize(num_params);\n  this->m_param_names[0] = \"E\";\n  this->m_param_names[1] = \"nu\";\n  this->m_param_names[2] = \"K\";\n  this->m_param_names[3] = \"Y\";\n\n  int const num_elem_sets = this->m_elem_set_names.size();\n  resize(this->m_param_values, num_elem_sets, num_params);\n\n  ParameterList& all_material_params =\n      this->m_params_list.sublist(\"materials\", true);\n\n  for (int es = 0; es < num_elem_sets; ++es) {\n    std::string const& elem_set_name = this->m_elem_set_names[es];\n    ParameterList& material_params =\n        all_material_params.sublist(elem_set_name, true);\n    material_params.validateParameters(get_valid_material_params(), 0);\n    this->m_param_values[es][0] = material_params.get<double>(\"E\");\n    this->m_param_values[es][1] = material_params.get<double>(\"nu\");\n    this->m_param_values[es][2] = material_params.get<double>(\"K\");\n    this->m_param_values[es][3] = material_params.get<double>(\"Y\");\n  }\n\n  this->m_active_indices.resize(1);\n  this->m_active_indices[0].resize(1);\n  this->m_active_indices[0][0] = 0;\n}\n\ntemplate <typename T>\nvoid J2<T>::init_variables_impl() {\n\n  int const ndims = this->m_num_dims;\n  int const zeta_idx = 0;\n  int const Ie_idx = 1;\n  int const alpha_idx = 2;\n\n  T const Ie = 1.0;\n  T const alpha = 0.0;\n  Tensor<T> const zeta = minitensor::zero<T>(ndims);\n\n  this->set_scalar_xi(Ie_idx, Ie);\n  this->set_scalar_xi(alpha_idx, alpha);\n  this->set_sym_tensor_xi(zeta_idx, zeta);\n\n}\n\ntemplate <typename T>\nTensor<T> eval_be_bar(\n    RCP<GlobalResidual<T>> global,\n    Tensor<T> const& zeta,\n    T const& Ie) {\n  int const ndims = global->num_dims();\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  Tensor<T> const grad_u = global->grad_vector_x(0);\n  Tensor<T> const grad_u_prev = global->grad_vector_x_prev(0);\n  Tensor<T> const F = grad_u + I;\n  Tensor<T> const F_prev = grad_u_prev + I;\n  Tensor<T> const rF = F * minitensor::inverse(F_prev);\n  T const det_rF = minitensor::det(rF);\n  T const det_rF_13 = cbrt(det_rF);\n  Tensor<T> const rF_bar = rF / det_rF_13;\n  Tensor<T> const rF_barT = minitensor::transpose(rF_bar);\n  Tensor<T> const be_bar = rF_bar * (zeta + Ie * I) * rF_barT;\n  return be_bar;\n}\n\ntemplate <>\nint J2<double>::solve_nonlinear(RCP<GlobalResidual<double>>) {\n  return 0;\n}\n\ntemplate <>\nint J2<FADT>::solve_nonlinear(RCP<GlobalResidual<FADT>> global) {\n\n  int path;\n\n  // pick an initial guess for the local variables\n  {\n    Tensor<FADT> const zeta_old = this->sym_tensor_xi_prev(0);\n    FADT const Ie_old = this->scalar_xi_prev(1);\n    FADT const alpha_old = this->scalar_xi_prev(2);\n    Tensor<FADT> const be_bar_trial = eval_be_bar(global, zeta_old, Ie_old);\n    Tensor<FADT> const zeta = minitensor::dev(be_bar_trial);\n    FADT const Ie = minitensor::trace(be_bar_trial) / 3.;\n    FADT const alpha = alpha_old;\n    this->set_sym_tensor_xi(0, zeta);\n    this->set_scalar_xi(1, Ie);\n    this->set_scalar_xi(2, alpha);\n    path = ELASTIC;\n  }\n\n  // newton iteration until convergence\n\n  int iter = 1;\n  double R_norm_0 = 1.;\n  bool converged = false;\n\n  while ((iter <= m_max_iters) && (!converged)) {\n\n    path = this->evaluate(global);\n\n    double const R_norm = this->norm_residual();\n    if (iter == 1) R_norm_0 = R_norm;\n    double const R_norm_rel = R_norm / R_norm_0;\n    if ((R_norm_rel < m_rel_tol) || (R_norm < m_abs_tol)) {\n      converged = true;\n      break;\n    }\n\n    EMatrix const J = this->eigen_jacobian();\n    EVector const R = this->eigen_residual();\n    EVector const dxi = J.fullPivLu().solve(-R);\n\n    this->add_to_sym_tensor_xi(0, dxi);\n    this->add_to_scalar_xi(1, dxi);\n    this->add_to_scalar_xi(2, dxi);\n\n    iter++;\n\n  }\n\n  // fail if convergence was not achieved\n  if ((iter > m_max_iters) && (!converged)) {\n    fail(\"J2:solve_nonlinear failed in %d iterations\", m_max_iters);\n  }\n\n  return path;\n\n}\n\ntemplate <typename T>\nint J2<T>::evaluate(\n    RCP<GlobalResidual<T>> global,\n    bool force_path,\n    int path_in) {\n\n  int path = ELASTIC;\n  int const ndims = this->m_num_dims;\n  double const sqrt_23 = std::sqrt(2./3.);\n  double const sqrt_32 = std::sqrt(3./2.);\n\n  T const E = this->m_params[0];\n  T const nu = this->m_params[1];\n  T const K = this->m_params[2];\n  T const Y = this->m_params[3];\n  T const mu = compute_mu(E, nu);\n\n  Tensor<T> const zeta_old = this->sym_tensor_xi_prev(0);\n  T const Ie_old = this->scalar_xi_prev(1);\n  T const alpha_old = this->scalar_xi_prev(2);\n\n  Tensor<T> const zeta = this->sym_tensor_xi(0);\n  T const Ie = this->scalar_xi(1);\n  T const alpha = this->scalar_xi(2);\n\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  Tensor<T> const be_bar_trial = eval_be_bar(global, zeta_old, Ie_old);\n  Tensor<T> const s = mu * zeta;\n  T const s_mag = minitensor::norm(s);\n  Tensor<T> const n = s / s_mag;\n  T const sigma_yield = Y + K * alpha;\n  T const f = s_mag - sqrt_23 * sigma_yield;\n\n  Tensor<T> R_zeta;\n  T R_Ie;\n  T R_alpha;\n\n  if (!force_path) {\n    // plastic step\n    if (f > m_abs_tol || std::abs(f) < m_abs_tol) {\n      T const dgam = sqrt_32 * (alpha - alpha_old);\n      R_zeta = zeta - minitensor::dev(be_bar_trial) + 2. * dgam * Ie * n;\n      R_Ie = minitensor::det(zeta + Ie * I) - 1.;\n      R_alpha = (s_mag - sqrt_23 * sigma_yield) / val(mu);\n      path = PLASTIC;\n    }\n    // elastic step\n    else {\n      R_zeta = (0. * mu + 1.) * zeta - minitensor::dev(be_bar_trial);\n      R_Ie = Ie - minitensor::trace(be_bar_trial) / 3. + 0. * mu;\n      R_alpha = alpha - alpha_old + 0. * mu;\n      path = ELASTIC;\n    }\n  }\n\n  // force the path\n  else {\n    path = path_in;\n    // plastic step\n    if (path == PLASTIC) {\n      T const dgam = sqrt_32 * (alpha - alpha_old);\n      R_zeta = zeta - minitensor::dev(be_bar_trial) + 2. * dgam * Ie * n;\n      R_Ie = minitensor::det(zeta + Ie * I) - 1.;\n      R_alpha = (s_mag - sqrt_23 * sigma_yield) / val(mu);\n    }\n    // elastic step\n    else {\n      R_zeta = (0. * mu + 1.) * zeta - minitensor::dev(be_bar_trial);\n      R_Ie = Ie - minitensor::trace(be_bar_trial) / 3. + 0. * mu;\n      R_alpha = alpha - alpha_old + 0. * mu;\n    }\n  }\n\n  this->set_sym_tensor_R(0, R_zeta);\n  this->set_scalar_R(1, R_Ie);\n  this->set_scalar_R(2, R_alpha);\n\n  return path;\n\n}\n\ntemplate <typename T>\nTensor<T> J2<T>::dev_cauchy(RCP<GlobalResidual<T>> global) {\n  int const ndims = global->num_dims();\n  T const E = this->m_params[0];\n  T const nu = this->m_params[1];\n  T const mu = E / (2. * (1. + nu));\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  Tensor<T> const grad_u = global->grad_vector_x(0);\n  Tensor<T> const F = grad_u + I;\n  Tensor<T> const zeta = this->sym_tensor_xi(0);\n  T const J = minitensor::det(F);\n  return mu * zeta / J;\n}\n\ntemplate <typename T>\nTensor<T> J2<T>::cauchy(RCP<GlobalResidual<T>> global, T p) {\n  int const ndims = global->num_dims();\n  Tensor<T> const I = minitensor::eye<T>(ndims);\n  Tensor<T> const dev_sigma = this->dev_cauchy(global);\n  Tensor<T> const sigma = dev_sigma - p * I;\n  return sigma;\n}\n\ntemplate class J2<double>;\ntemplate class J2<FADT>;\n\n}\n", "meta": {"hexsha": "192cdfeec473ad875f6c8dc5a1cad9f2ecac0481", "size": 8800, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/J2.cpp", "max_stars_repo_name": "sandialabs/calibr8", "max_stars_repo_head_hexsha": "a7be9213a49eb2b56f58041a2a88b0184382de4d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-08-31T00:33:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T17:10:28.000Z", "max_issues_repo_path": "src/J2.cpp", "max_issues_repo_name": "sandialabs/calibr8", "max_issues_repo_head_hexsha": "a7be9213a49eb2b56f58041a2a88b0184382de4d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/J2.cpp", "max_forks_repo_name": "sandialabs/calibr8", "max_forks_repo_head_hexsha": "a7be9213a49eb2b56f58041a2a88b0184382de4d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2958199357, "max_line_length": 79, "alphanum_fraction": 0.6573863636, "num_tokens": 2829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228625116081, "lm_q2_score": 0.31742627850202554, "lm_q1q2_score": 0.2101117109024677}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#include \"bempp/common/config_ahmed.hpp\"\n#include \"bempp/common/config_trilinos.hpp\"\n\n#include \"aca_global_assembler.hpp\"\n\n#include \"assembly_options.hpp\"\n#include \"cluster_construction_helper.hpp\"\n#include \"evaluation_options.hpp\"\n#include \"index_permutation.hpp\"\n#include \"discrete_boundary_operator_composition.hpp\"\n#include \"discrete_sparse_boundary_operator.hpp\"\n\n#include \"../common/armadillo_fwd.hpp\"\n#include \"../common/auto_timer.hpp\"\n#include \"../common/boost_shared_array_fwd.hpp\"\n#include \"../common/chunk_statistics.hpp\"\n#include \"../common/to_string.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../fiber/local_assembler_for_operators.hpp\"\n#include \"../fiber/local_assembler_for_potential_operators.hpp\"\n#include \"../fiber/serial_blas_region.hpp\"\n#include \"../fiber/scalar_traits.hpp\"\n#include \"../space/space.hpp\"\n\n#include <stdexcept>\n#include <fstream>\n#include <iostream>\n\n#include <boost/type_traits/is_complex.hpp>\n\n#include <tbb/atomic.h>\n#include <tbb/parallel_for.h>\n#include <tbb/task_scheduler_init.h>\n#include <tbb/concurrent_queue.h>\n\n#ifdef WITH_AHMED\n#include \"ahmed_aux.hpp\"\n\n#ifdef __INTEL_COMPILER\n#pragma warning(disable:381)\n#endif\n\n#include <apprx.h>\n\n#ifdef __INTEL_COMPILER\n#pragma warning(default:381)\n#endif\n\n#include \"discrete_aca_boundary_operator.hpp\"\n#include \"modified_aca.hpp\"\n#include \"potential_operator_aca_assembly_helper.hpp\"\n#include \"scattered_range.hpp\"\n#include \"weak_form_aca_assembly_helper.hpp\"\n#endif\n\n// #define DUMP_DENSE_BLOCKS // if defined, contents and DOF lists of blocks\n                             // stored as dense matrices will be printed to the\n                             // screen\n\nnamespace Bempp\n{\n\n// Body of parallel loop\nnamespace\n{\n\n#ifdef WITH_AHMED\ntemplate <typename BasisFunctionType, typename ResultType,\n          typename AcaAssemblyHelper>\nclass AcaAssemblerLoopBody\n{\n    typedef typename Fiber::ScalarTraits<ResultType>::RealType CoordinateType;\n    typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n    typedef bemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n    typedef mblock<typename AhmedTypeTraits<ResultType>::Type> AhmedMblock;\npublic:\n    typedef tbb::concurrent_queue<size_t> LeafClusterIndexQueue;\n\n    AcaAssemblerLoopBody(\n            AcaAssemblyHelper& helper,\n            AhmedLeafClusterArray& leafClusters,\n            boost::shared_array<AhmedMblock*> blocks,\n            const AcaOptions& options,\n            tbb::atomic<size_t>& done,\n            bool verbose,\n            LeafClusterIndexQueue& leafClusterIndexQueue,\n            bool symmetric,\n            std::vector<ChunkStatistics>& stats) :\n        m_helper(helper),\n        m_leafClusters(leafClusters), m_blocks(blocks),\n        m_options(options), m_done(done), m_verbose(verbose),\n        m_leafClusterIndexQueue(leafClusterIndexQueue),\n        m_symmetric(symmetric),\n        m_stats(stats)\n    {\n    }\n\n    template <typename Range>\n    void operator() (const Range& r) const {\n        const char* TEXT = \"Approximating ... \";\n        for (typename Range::const_iterator i = r.begin(); i != r.end(); ++i) {\n            size_t leafClusterIndex = 0;\n            if (!m_leafClusterIndexQueue.try_pop(leafClusterIndex)) {\n                std::cerr << \"AcaWeakFormAssemblerLoopBody::operator(): \"\n                             \"Warning: try_pop failed; this shouldn't happen!\"\n                          << std::endl;\n                continue;\n            }\n            m_stats[leafClusterIndex].valid = true;\n            m_stats[leafClusterIndex].chunkStart = r.begin();\n            m_stats[leafClusterIndex].chunkSize = r.size();\n            m_stats[leafClusterIndex].startTime = tbb::tick_count::now();\n\n            AhmedBemBlcluster* cluster =\n                    dynamic_cast<AhmedBemBlcluster*>(m_leafClusters[leafClusterIndex]);\n            if (m_symmetric)\n                apprx_sym(m_helper, m_blocks[cluster->getidx()],\n                          cluster, m_options.eps, m_options.maximumRank,\n                          true /* complex_sym */);\n            else {\n                if (m_options.useAhmedAca)\n                    apprx_unsym(m_helper, m_blocks[cluster->getidx()],\n                                cluster, m_options.eps, m_options.maximumRank);\n                else\n                    apprx_unsym_shooting(\n                                m_helper, m_blocks[cluster->getidx()],\n                                cluster, m_options.eps, m_options.maximumRank);\n            }\n            m_stats[leafClusterIndex].endTime = tbb::tick_count::now();\n            // TODO: recompress\n            const int HASH_COUNT = 20;\n            if (m_verbose)\n                progressbar(std::cout, TEXT, (++m_done) - 1,\n                            m_leafClusters.size(), HASH_COUNT, true);\n        }\n\n    }\n\nprivate:\n    AcaAssemblyHelper& m_helper;\n    AhmedLeafClusterArray& m_leafClusters;\n    boost::shared_array<AhmedMblock*> m_blocks;\n    const AcaOptions& m_options;\n    tbb::atomic<size_t>& m_done;\n    bool m_verbose;\n    LeafClusterIndexQueue& m_leafClusterIndexQueue;\n    bool m_symmetric;\n    std::vector<ChunkStatistics>& m_stats;\n};\n\nvoid reallyGetClusterIds(const cluster& clusterTree,\n                         const std::vector<unsigned int>& p2oDofs,\n                         std::vector<unsigned int>& clusterIds,\n                         unsigned int& id)\n{\n    if (clusterTree.isleaf())\n        for (unsigned int nDof = clusterTree.getnbeg(); nDof < clusterTree.getnend(); ++nDof)\n            clusterIds[p2oDofs[nDof]] = id;\n    else\n        for (unsigned int nSon = 0; nSon < clusterTree.getns(); ++nSon)\n            reallyGetClusterIds(*clusterTree.getson(nSon), p2oDofs, clusterIds, ++id);\n}\n\nvoid getClusterIds(const cluster& clusterTree,\n                   const std::vector<unsigned int>& p2oDofs,\n                   std::vector<unsigned int>& clusterIds)\n{\n    clusterIds.resize(p2oDofs.size());\n    unsigned int id = 0;\n    reallyGetClusterIds(clusterTree, p2oDofs, clusterIds, id);\n}\n\ntemplate <typename T>\nvoid save_arma_matrix(const arma::Mat<T>& a, const std::string& fname)\n{\n    std::ofstream out;\n    out.precision(17);\n    out.open(fname.c_str());\n    arma::diskio::save_raw_ascii(a, out);\n    out.close();\n}\ntemplate <typename T>\nvoid save_arma_matrix(const arma::Mat<std::complex<T> >& a, const std::string& fname)\n{\n    std::ofstream out;\n    out.precision(17);\n    out.open((fname + \"-real.txt\").c_str());\n    arma::Mat<T> component = arma::real(a);\n    arma::diskio::save_raw_ascii(component, out);\n    out.close();\n    out.open((fname + \"-imag.txt\").c_str());\n    component = arma::imag(a);\n    arma::diskio::save_raw_ascii(component, out);\n    out.close();\n}\n\ntemplate <typename ValueType>\nvoid dumpDenseBlocks(\n        typename DiscreteAcaBoundaryOperator<ValueType>::AhmedBemBlcluster* clusterTree,\n        typename DiscreteAcaBoundaryOperator<ValueType>::AhmedMblockArray& blocks,\n        const std::vector<unsigned int>& p2oRows,\n        const std::vector<unsigned int>& p2oCols,\n        const std::vector<Point3D<typename Fiber::ScalarTraits<ValueType>::RealType> >& rowDofs,\n        const std::vector<Point3D<typename Fiber::ScalarTraits<ValueType>::RealType> >& colDofs)\n{\n    if (!clusterTree)\n        return;\n    typedef typename Fiber::ScalarTraits<ValueType>::RealType CoordinateType;\n    typedef DiscreteAcaBoundaryOperator<ValueType> AcaOp;\n    typedef typename AcaOp::AhmedDofType AhmedDofType;\n    typedef typename AcaOp::AhmedMblock AhmedMblock;\n    typedef bemcluster<AhmedDofType> Cluster;\n    if (clusterTree->isleaf()) {\n        unsigned int idx = clusterTree->getidx();\n        std::cout << \"LEAF; idx = \" << idx << std::endl;\n        if (clusterTree->isGeM(blocks.get()) && clusterTree->isadm()) {\n            std::cout << \"Dense block; \" << clusterTree->getb1()\n                      << \" \" << clusterTree->getb2()\n                      << \" \" << clusterTree->getn1()\n                      << \" \" << clusterTree->getn2() << \"\\n\";\n            // if (clusterTree->getn1() < 500 || clusterTree->getn2() < 500)\n            //     return;\n            Cluster* clRow = clusterTree->getcl1();\n            assert(clRow);\n            std::cout << \"Row center of mass: (\"\n                      << clRow->getcom(0) << \", \"\n                      << clRow->getcom(1) << \", \"\n                      << clRow->getcom(2) << \")\\n\";\n            std::cout << \"Row icm: \"\n                      << clRow->geticom() - clusterTree->getb1() << std::endl;\n            for (unsigned int nDof = clRow->getnbeg();\n                 nDof < clRow->getnend(); ++nDof) {\n                assert(nDof < p2oRows.size());\n                assert(p2oRows[nDof] < rowDofs.size());\n                const Point3D<CoordinateType> dofPos = rowDofs[p2oRows[nDof]];\n                std::cout << \"  Row dof #\" << p2oRows[nDof] << \" at \"\n                          << dofPos.x << \", \" << dofPos.y << \", \"\n                          << dofPos.z << \"\\n\";\n            }\n            Cluster* clCol = clusterTree->getcl2();\n            assert(clCol);\n            std::cout << \"Col center of mass: (\"\n                      << clCol->getcom(0) << \", \"\n                      << clCol->getcom(1) << \", \"\n                      << clCol->getcom(2) << \")\\n\";\n            std::cout << \"Column icm: \"\n                      << clCol->geticom() - clusterTree->getb2() << std::endl;\n            for (unsigned int nDof = clCol->getnbeg();\n                 nDof < clCol->getnend(); ++nDof) {\n                assert(nDof < p2oCols.size());\n                assert(p2oCols[nDof] < colDofs.size());\n                const Point3D<CoordinateType> dofPos = colDofs[p2oCols[nDof]];\n                std::cout << \"  Col dof #\" << p2oCols[nDof] << \" at \"\n                          << dofPos.x << \", \" << dofPos.y << \", \"\n                          << dofPos.z << \"\\n\";\n            }\n            AhmedMblock* block = blocks[idx];\n            arma::Mat<ValueType> ablock(clusterTree->getn1(),\n                                        clusterTree->getn2());\n            for (size_t i = 0; i < block->nvals(); ++i)\n                ablock[i] = block->getdata()[i];\n            save_arma_matrix(ablock, \"block-\" + toString(idx) + \".txt\");\n        }\n    }\n    else\n        for (unsigned int nRowSon = 0; nRowSon < clusterTree->getnrs(); ++nRowSon)\n            for (unsigned int nColSon = 0; nColSon < clusterTree->getncs(); ++nColSon)\n            dumpDenseBlocks<ValueType>(\n                        dynamic_cast<typename AcaOp::AhmedBemBlcluster*>(\n                            clusterTree->getson(nRowSon, nColSon)),\n                        blocks,\n                        p2oRows, p2oCols, rowDofs, colDofs);\n}\n\ntemplate <typename AcaAssemblyHelper,\n          typename BasisFunctionType, typename ResultType>\nstd::auto_ptr<DiscreteAcaBoundaryOperator<ResultType> >\nassembleAcaOperator(\n        AcaAssemblyHelper& helper,\n        const shared_ptr<typename DiscreteAcaBoundaryOperator<ResultType>::\n            AhmedBemBlcluster>& bemBlclusterTree,\n        const ParallelizationOptions& parallelOptions,\n        const AcaOptions& acaOptions,\n        bool verbosityAtLeastDefault,\n        bool symmetric,\n        const shared_ptr<IndexPermutation>& test_o2pPermutation,\n        const shared_ptr<IndexPermutation>& trial_o2pPermutation\n#ifdef DUMP_DENSE_BLOCKS\n        ,\n        const shared_ptr<IndexPermutation>& test_p2oPermutation,\n        const shared_ptr<IndexPermutation>& trial_p2oPermutation,\n        const std::vector<Point3D<\n            typename Fiber::ScalarTraits<ResultType>::RealType> >& testDofCenters,\n        const std::vector<Point3D<\n            typename Fiber::ScalarTraits<ResultType>::RealType> >& trialDofCenters\n#endif // DUMP_DENSE_BLOCKS\n        )\n{\n    typedef mblock<typename AhmedTypeTraits<ResultType>::Type> AhmedMblock;\n    boost::shared_array<AhmedMblock*> blocks =\n            allocateAhmedMblockArray<ResultType>(bemBlclusterTree.get());\n\n    const size_t testDofCount = test_o2pPermutation->size();\n    const size_t trialDofCount = trial_o2pPermutation->size();\n\n    AhmedLeafClusterArray leafClusters(bemBlclusterTree.get());\n    leafClusters.sortAccordingToClusterSize();\n    const size_t leafClusterCount = leafClusters.size();\n\n    int maxThreadCount = 1;\n    if (!parallelOptions.isOpenClEnabled())\n    {\n        if (parallelOptions.maxThreadCount() == ParallelizationOptions::AUTO)\n            maxThreadCount = tbb::task_scheduler_init::automatic;\n        else\n            maxThreadCount = parallelOptions.maxThreadCount();\n    }\n    tbb::task_scheduler_init scheduler(maxThreadCount);\n    tbb::atomic<size_t> done;\n    done = 0;\n\n    std::vector<ChunkStatistics> chunkStats(leafClusterCount);\n\n    typedef AcaAssemblerLoopBody<\n            BasisFunctionType, ResultType, AcaAssemblyHelper> Body;\n    typename Body::LeafClusterIndexQueue leafClusterIndexQueue;\n    for (size_t i = 0; i < leafClusterCount; ++i)\n        leafClusterIndexQueue.push(i);\n\n    if (verbosityAtLeastDefault)\n        std::cout << \"About to start the ACA assembly loop\" << std::endl;\n    tbb::tick_count loopStart = tbb::tick_count::now();\n    {\n        Fiber::SerialBlasRegion region; // if possible, ensure that BLAS is single-threaded\n        tbb::parallel_for(tbb::blocked_range<size_t>(0, leafClusterCount),\n                          Body(helper, leafClusters, blocks, acaOptions, done,\n                               verbosityAtLeastDefault,\n                               leafClusterIndexQueue, symmetric, chunkStats));\n    }\n    tbb::tick_count loopEnd = tbb::tick_count::now();\n    if (verbosityAtLeastDefault) {\n        std::cout << \"\\n\"; // the progress bar doesn't print the final \\n\n        std::cout << \"ACA loop took \" << (loopEnd - loopStart).seconds() << \" s\"\n                  << std::endl;\n    }\n\n    // TODO: parallelise!\n    if (acaOptions.recompress) {\n        if (verbosityAtLeastDefault)\n            std::cout << \"About to start ACA agglomeration\" << std::endl;\n        agglH(bemBlclusterTree.get(), blocks.get(),\n              acaOptions.eps, acaOptions.maximumRank);\n        if (verbosityAtLeastDefault)\n            std::cout << \"Agglomeration finished\" << std::endl;\n    }\n\n#ifdef DUMP_DENSE_BLOCKS\n    dumpDenseBlocks<ResultType>(bemBlclusterTree.get(), blocks,\n                                test_p2oPermutation->permutedIndices(),\n                                trial_p2oPermutation->permutedIndices(),\n                                testDofCenters, trialDofCenters);\n#endif // DUMP_DENSE_BLOCKS\n\n    //    dumpAhmedMblockArray<ResultType>(blocks, blockCount);\n\n    // // Dump timing data of individual chunks\n    //    std::cout << \"\\nChunks:\\n\";\n    //    for (int i = 0; i < leafClusterCount; ++i)\n    //        if (chunkStats[i].valid) {\n    //            int blockIndex = leafClusters[i]->getidx();\n    //            std::cout << chunkStats[i].chunkStart << \"\\t\"\n    //                      << chunkStats[i].chunkSize << \"\\t\"\n    //                      << (chunkStats[i].startTime - loopStart).seconds() << \"\\t\"\n    //                      << (chunkStats[i].endTime - loopStart).seconds() << \"\\t\"\n    //                      << (chunkStats[i].endTime - chunkStats[i].startTime).seconds() << \"\\t\"\n    //                      << blocks[blockIndex]->getn1() << \"\\t\"\n    //                      << blocks[blockIndex]->getn2() << \"\\t\"\n    //                      << blocks[blockIndex]->islwr() << \"\\t\"\n    //                      << (blocks[blockIndex]->islwr() ? blocks[blockIndex]->rank() : 0) << \"\\n\";\n    //        }\n\n    if (verbosityAtLeastDefault) {\n#ifdef CHECK_ACA_ERROR // a define from include/AHMED/apprx.h\n        std::cout << \"ACA finished. Max error: \" << ACA_error_max << std::endl;\n#endif\n        size_t totalEntryCount = testDofCount * trialDofCount;\n        size_t origMemory = sizeof(ResultType) * totalEntryCount;\n        size_t ahmedMemory = sizeH(bemBlclusterTree.get(), blocks.get());\n        int maximumRank = Hmax_rank(bemBlclusterTree.get(), blocks.get());\n        size_t accessedEntryCount = helper.accessedEntryCount();\n        double accessedFraction = double(accessedEntryCount) / totalEntryCount;\n        std::cout << \"\\nNeeded storage: \"\n                  << ahmedMemory / 1024. / 1024. << \" MB.\\n\"\n                  << \"Without approximation: \"\n                  << origMemory / 1024. / 1024. << \" MB.\\n\"\n                  << \"Compressed to \"\n                  << (100. * ahmedMemory) / origMemory << \"%.\\n\"\n                  << \"Maximum rank: \" << maximumRank << \".\\n\"\n                  << \"Accessed \"\n                  << 100. * accessedFraction << \"% matrix entries.\\n\"\n                  << std::endl;\n    }\n\n    if (acaOptions.outputPostscript) {\n        if (verbosityAtLeastDefault)\n            std::cout << \"Writing matrix partition ...\" << std::flush;\n        std::ofstream os(acaOptions.outputFname.c_str());\n        if (symmetric)\n            // psoutputHeH() seems to work also for symmetric matrices\n            psoutputHeH(os, bemBlclusterTree.get(),\n                        trialDofCount, blocks.get());\n        else\n            psoutputGeH(os, bemBlclusterTree.get(),\n                        std::max(testDofCount, trialDofCount), blocks.get());\n        os.close();\n        if (verbosityAtLeastDefault)\n            std::cout << \" done.\" << std::endl;\n    }\n\n    int outSymmetry = NO_SYMMETRY;\n    if (symmetric) {\n        outSymmetry = SYMMETRIC;\n        if (!boost::is_complex<ResultType>())\n            outSymmetry |= HERMITIAN;\n    }\n    typedef DiscreteAcaBoundaryOperator<ResultType> DiscreteAcaLinOp;\n    std::auto_ptr<DiscreteAcaLinOp> acaOp(\n                new DiscreteAcaLinOp(testDofCount, trialDofCount,\n                                     acaOptions.eps,\n                                     acaOptions.maximumRank,\n                                     outSymmetry,\n                                     bemBlclusterTree, blocks,\n                                     *trial_o2pPermutation, // domain\n                                     *test_o2pPermutation, // range\n                                     parallelOptions));\n    return acaOp;\n}\n\n#endif\n\n} // namespace\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::auto_ptr<DiscreteBoundaryOperator<ResultType> >\nAcaGlobalAssembler<BasisFunctionType, ResultType>::assembleDetachedWeakForm(\n        const Space<BasisFunctionType>& testSpace,\n        const Space<BasisFunctionType>& trialSpace,\n        const std::vector<LocalAssemblerForBoundaryOperators*>& localAssemblers,\n        const std::vector<const DiscreteBndOp*>& sparseTermsToAdd,\n        const std::vector<ResultType>& denseTermMultipliers,\n        const std::vector<ResultType>& sparseTermMultipliers,\n        const AssemblyOptions& options,\n        int symmetry)\n{\n#ifdef WITH_AHMED\n    typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n    typedef ExtendedBemCluster<AhmedDofType> AhmedBemCluster;\n    typedef bemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n    typedef DiscreteAcaBoundaryOperator<ResultType> DiscreteAcaLinOp;\n\n    const AcaOptions& acaOptions = options.acaOptions();\n    const bool indexWithGlobalDofs = acaOptions.globalAssemblyBeforeCompression;\n    const bool verbosityAtLeastDefault =\n            (options.verbosityLevel() >= VerbosityLevel::DEFAULT);\n    const bool verbosityAtLeastHigh =\n            (options.verbosityLevel() >= VerbosityLevel::HIGH);\n\n    // Currently we don't support Hermitian ACA operators. This is because we\n    // don't have the means to really test them -- we would need complex-valued\n    // basis functions for that. (Assembly of such a matrix would be very easy\n    // -- just change complex_sym from true to false in the call to apprx_sym()\n    // in AcaWeakFormAssemblerLoopBody::operator() -- but operations on\n    // symmetric/Hermitian matrices are not always trivial and we do need to be\n    // able to test them properly.)\n    bool symmetric = symmetry & SYMMETRIC;\n    if (symmetry & HERMITIAN && !(symmetry & SYMMETRIC) &&\n            verbosityAtLeastDefault)\n        std::cout << \"Warning: assembly of non-symmetric Hermitian H-matrices \"\n                     \"is not supported yet. A general H-matrix will be assembled\"\n                  << std::endl;\n\n#ifndef WITH_TRILINOS\n    if (!indexWithGlobalDofs)\n        throw std::runtime_error(\"AcaGlobalAssembler::assembleDetachedWeakForm(): \"\n                                 \"ACA assembly with globalAssemblyBeforeCompression \"\n                                 \"set to false requires BEM++ to be linked with \"\n                                 \"Trilinos\");\n#endif // WITH_TRILINOS\n\n    const size_t testDofCount = indexWithGlobalDofs ?\n                testSpace.globalDofCount() : testSpace.flatLocalDofCount();\n    const size_t trialDofCount = indexWithGlobalDofs ?\n                trialSpace.globalDofCount() : trialSpace.flatLocalDofCount();\n\n    if (symmetric && testDofCount != trialDofCount)\n        throw std::invalid_argument(\"AcaGlobalAssembler::assembleDetachedWeakForm(): \"\n                                    \"you cannot generate a symmetric weak form \"\n                                    \"using test and trial spaces with different \"\n                                    \"numbers of DOFs\");\n\n    // o2p: map of original indices to permuted indices\n    // p2o: map of permuted indices to original indices\n    typedef ClusterConstructionHelper<BasisFunctionType> CCH;\n    shared_ptr<AhmedBemCluster> testClusterTree;\n    shared_ptr<IndexPermutation> test_o2pPermutation, test_p2oPermutation;\n    CCH::constructBemCluster(testSpace, indexWithGlobalDofs, acaOptions,\n                             testClusterTree,\n                             test_o2pPermutation, test_p2oPermutation);\n    shared_ptr<AhmedBemCluster> trialClusterTree;\n    shared_ptr<IndexPermutation> trial_o2pPermutation, trial_p2oPermutation;\n    if (symmetric || &testSpace == &trialSpace) {\n        trialClusterTree = testClusterTree;\n        trial_o2pPermutation = test_o2pPermutation;\n        trial_p2oPermutation = test_p2oPermutation;\n    } else\n        CCH::constructBemCluster(trialSpace, indexWithGlobalDofs, acaOptions,\n                                 trialClusterTree,\n                                 trial_o2pPermutation, trial_p2oPermutation);\n\n//    // Export VTK plots showing the disctribution of leaf cluster ids\n//    std::vector<unsigned int> testClusterIds;\n//    getClusterIds(*testClusterTree, test_p2oPermutation->permutedIndices(), testClusterIds);\n//    testSpace.dumpClusterIds(\"testClusterIds\", testClusterIds,\n//                             indexWithGlobalDofs ? GLOBAL_DOFS : FLAT_LOCAL_DOFS);\n//    std::vector<unsigned int> trialClusterIds;\n//    getClusterIds(*trialClusterTree, trial_p2oPermutation->permutedIndices(), trialClusterIds);\n//    trialSpace.dumpClusterIds(\"trialClusterIds\", trialClusterIds,\n//                              indexWithGlobalDofs ? GLOBAL_DOFS : FLAT_LOCAL_DOFS);\n\n    if (verbosityAtLeastHigh)\n        std::cout << \"Test cluster count: \" << testClusterTree->getncl()\n                  << \"\\nTrial cluster count: \" << trialClusterTree->getncl()\n                  << std::endl;\n\n    unsigned int blockCount = 0;\n    shared_ptr<AhmedBemBlcluster> bemBlclusterTree(\n                CCH::constructBemBlockCluster(acaOptions, symmetric,\n                                              *testClusterTree, *trialClusterTree,\n                                              blockCount).release());\n\n    if (verbosityAtLeastHigh)\n        std::cout << \"Mblock count: \" << blockCount << std::endl;\n\n    std::vector<unsigned int> p2oTestDofs =\n        test_p2oPermutation->permutedIndices();\n    std::vector<unsigned int> p2oTrialDofs =\n        trial_p2oPermutation->permutedIndices();\n    assert(p2oTestDofs.size() == testDofCount);\n    assert(p2oTrialDofs.size() == trialDofCount);\n\n#ifdef DUMP_DENSE_BLOCKS\n    std::vector<Point3D<CoordinateType> > testDofCenters, trialDofCenters;\n    if (indexWithGlobalDofs) {\n        testSpace.getGlobalDofPositions(testDofCenters);\n        trialSpace.getGlobalDofPositions(trialDofCenters);\n    } else {\n        testSpace.getFlatLocalDofPositions(testDofCenters);\n        trialSpace.getFlatLocalDofPositions(trialDofCenters);\n    }\n#endif // DUMP_DENSE_BLOCKS\n\n    typedef WeakFormAcaAssemblyHelper<BasisFunctionType, ResultType>\n            AcaAssemblyHelper;\n    // TODO: It might be better (more efficient and elegant)\n    // to pass p2oPermutation than p2oDofs.\n    // Also, it might be more logical to rename IndexPermutation to IndexMapping\n    // and permute/unpermute to map/unmap.\n    AcaAssemblyHelper helper(\n                testSpace, trialSpace, p2oTestDofs, p2oTrialDofs,\n                localAssemblers, sparseTermsToAdd,\n                denseTermMultipliers, sparseTermMultipliers, options);\n\n    std::auto_ptr<DiscreteAcaBoundaryOperator<ResultType> > acaOp =\n    assembleAcaOperator<AcaAssemblyHelper, BasisFunctionType, ResultType>(\n                helper, bemBlclusterTree,\n                options.parallelizationOptions(), options.acaOptions(),\n                verbosityAtLeastDefault, symmetric,\n                test_o2pPermutation, trial_o2pPermutation\n#ifdef DUMP_DENSE_BLOCKS\n                ,\n                test_p2oPermutation, trial_p2oPermutation,\n                testDofCenters, trialDofCenters\n#endif // DUMP_DENSE_BLOCKS\n                );\n\n    std::auto_ptr<DiscreteBndOp> result;\n    if (indexWithGlobalDofs)\n        result = acaOp;\n    else {\n#ifdef WITH_TRILINOS\n        // without Trilinos, this code will never be reached -- an exception\n        // will be thrown earlier in this function\n        typedef DiscreteBoundaryOperatorComposition<ResultType> DiscreteBndOpComp;\n        shared_ptr<DiscreteBndOp> acaOpShared(acaOp.release());\n        shared_ptr<DiscreteBndOp> trialGlobalToLocal =\n                constructOperatorMappingGlobalToFlatLocalDofs<\n                BasisFunctionType, ResultType>(trialSpace);\n        shared_ptr<DiscreteBndOp> testLocalToGlobal =\n                constructOperatorMappingFlatLocalToGlobalDofs<\n                BasisFunctionType, ResultType>(testSpace);\n        shared_ptr<DiscreteBndOp> tmp(\n                    new DiscreteBndOpComp(acaOpShared, trialGlobalToLocal));\n        result.reset(new DiscreteBndOpComp(testLocalToGlobal, tmp));\n#endif // WITH_TRILINOS\n    }\n    return result;\n\n#else // without Ahmed\n    throw std::runtime_error(\"AcaGlobalAssembler::assembleDetachedWeakForm(): \"\n                             \"To enable assembly in ACA mode, recompile BEM++ \"\n                             \"with the symbol WITH_AHMED defined.\");\n#endif // WITH_AHMED\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::auto_ptr<DiscreteBoundaryOperator<ResultType> >\nAcaGlobalAssembler<BasisFunctionType, ResultType>::assembleDetachedWeakForm(\n        const Space<BasisFunctionType>& testSpace,\n        const Space<BasisFunctionType>& trialSpace,\n        LocalAssemblerForBoundaryOperators& localAssembler,\n        const AssemblyOptions& options,\n        int symmetry)\n{\n    std::vector<LocalAssemblerForBoundaryOperators*> localAssemblers(\n                1, &localAssembler);\n    std::vector<const DiscreteBndOp*> sparseTermsToAdd;\n    std::vector<ResultType> denseTermsMultipliers(1, 1.0);\n    std::vector<ResultType> sparseTermsMultipliers;\n\n    return assembleDetachedWeakForm(testSpace, trialSpace, localAssemblers,\n                            sparseTermsToAdd,\n                            denseTermsMultipliers,\n                            sparseTermsMultipliers,\n                            options, symmetry);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::auto_ptr<DiscreteBoundaryOperator<ResultType> >\nAcaGlobalAssembler<BasisFunctionType, ResultType>::assemblePotentialOperator(\n        const arma::Mat<CoordinateType>& points,\n        const Space<BasisFunctionType>& trialSpace,\n        const std::vector<LocalAssemblerForPotentialOperators*>& localAssemblers,\n        const std::vector<ResultType>& termMultipliers,\n        const EvaluationOptions& options)\n{\n    const int symmetric = false;\n\n#ifdef WITH_AHMED\n    typedef AhmedDofWrapper<CoordinateType> AhmedDofType;\n    typedef ExtendedBemCluster<AhmedDofType> AhmedBemCluster;\n    typedef bemblcluster<AhmedDofType, AhmedDofType> AhmedBemBlcluster;\n    typedef DiscreteAcaBoundaryOperator<ResultType> DiscreteAcaLinOp;\n\n    const AcaOptions& acaOptions = options.acaOptions();\n    const bool indexWithGlobalDofs = acaOptions.globalAssemblyBeforeCompression;\n    const bool verbosityAtLeastDefault =\n            (options.verbosityLevel() >= VerbosityLevel::DEFAULT);\n    const bool verbosityAtLeastHigh =\n            (options.verbosityLevel() >= VerbosityLevel::HIGH);\n\n#ifndef WITH_TRILINOS\n    if (!indexWithGlobalDofs)\n        throw std::runtime_error(\"AcaGlobalAssembler::assemblePotentialOperator(): \"\n                                 \"ACA assembly with globalAssemblyBeforeCompression \"\n                                 \"set to false requires BEM++ to be linked with \"\n                                 \"Trilinos\");\n#endif // WITH_TRILINOS\n\n    if (localAssemblers.empty())\n        throw std::runtime_error(\"AcaGlobalAssembler::assemblePotentialOperator(): \"\n                                 \"the 'localAssemblers' vector must not be empty\");\n\n    const size_t pointCount = points.n_cols;\n    const int componentCount = localAssemblers[0]->resultDimension();\n    const size_t testDofCount = pointCount * componentCount;\n    const size_t trialDofCount = indexWithGlobalDofs ?\n                trialSpace.globalDofCount() : trialSpace.flatLocalDofCount();\n\n    // o2p: map of original indices to permuted indices\n    // p2o: map of permuted indices to original indices\n    typedef ClusterConstructionHelper<BasisFunctionType> CCH;\n    shared_ptr<AhmedBemCluster> testClusterTree;\n    shared_ptr<IndexPermutation> test_o2pPermutation, test_p2oPermutation;\n    CCH::constructBemCluster(points, componentCount, acaOptions,\n                             testClusterTree,\n                             test_o2pPermutation, test_p2oPermutation);\n    shared_ptr<AhmedBemCluster> trialClusterTree;\n    shared_ptr<IndexPermutation> trial_o2pPermutation, trial_p2oPermutation;\n    CCH::constructBemCluster(trialSpace, indexWithGlobalDofs, acaOptions,\n                             trialClusterTree,\n                             trial_o2pPermutation, trial_p2oPermutation);\n\n    // Print the distribution of cluster ids\n#ifdef DUMP_DENSE_BLOCKS\n    std::vector<Point3D<CoordinateType> > testDofCenters, trialDofCenters;\n    CCH::getComponentDofPositions(points, componentCount, testDofCenters);\n    if (indexWithGlobalDofs)\n        trialSpace.getGlobalDofPositions(trialDofCenters);\n    else\n        trialSpace.getFlatLocalDofPositions(trialDofCenters);\n#endif // DUMP_DENSE_BLOCKS\n\n    if (verbosityAtLeastHigh)\n        std::cout << \"Test cluster count: \" << testClusterTree->getncl()\n                  << \"\\nTrial cluster count: \" << trialClusterTree->getncl()\n                  << std::endl;\n\n    unsigned int blockCount = 0;\n    shared_ptr<AhmedBemBlcluster> bemBlclusterTree(\n                CCH::constructBemBlockCluster(acaOptions, false /* symmetric */,\n                                              *testClusterTree, *trialClusterTree,\n                                              blockCount).release());\n\n    if (verbosityAtLeastHigh)\n        std::cout << \"Mblock count: \" << blockCount << std::endl;\n\n    std::vector<unsigned int> p2oPoints =\n        test_p2oPermutation->permutedIndices();\n    std::vector<unsigned int> p2oTrialDofs =\n        trial_p2oPermutation->permutedIndices();\n    typedef PotentialOperatorAcaAssemblyHelper<BasisFunctionType, ResultType>\n            AcaAssemblyHelper;\n    AcaAssemblyHelper helper(points, trialSpace, p2oPoints, p2oTrialDofs,\n                             localAssemblers, termMultipliers, options);\n\n    std::auto_ptr<DiscreteAcaBoundaryOperator<ResultType> > acaOp =\n    assembleAcaOperator<AcaAssemblyHelper, BasisFunctionType, ResultType>(\n                helper, bemBlclusterTree,\n                options.parallelizationOptions(), options.acaOptions(),\n                verbosityAtLeastDefault, symmetric,\n                test_o2pPermutation, trial_o2pPermutation\n#ifdef DUMP_DENSE_BLOCKS\n                ,\n                test_p2oPermutation, trial_p2oPermutation,\n                testDofCenters, trialDofCenters\n#endif // DUMP_DENSE_BLOCKS\n                );\n\n    std::auto_ptr<DiscreteBndOp> result;\n    if (indexWithGlobalDofs)\n        result = acaOp;\n    else {\n#ifdef WITH_TRILINOS\n        // without Trilinos, this code will never be reached -- an exception\n        // will be thrown earlier in this function\n        typedef DiscreteBoundaryOperatorComposition<ResultType> DiscreteBndOpComp;\n        shared_ptr<DiscreteBndOp> acaOpShared(acaOp.release());\n        shared_ptr<DiscreteBndOp> trialGlobalToLocal =\n                constructOperatorMappingGlobalToFlatLocalDofs<\n                BasisFunctionType, ResultType>(trialSpace);\n        result.reset(new DiscreteBndOpComp(acaOpShared, trialGlobalToLocal));\n#endif // WITH_TRILINOS\n    }\n    return result;\n\n#else // without Ahmed\n    throw std::runtime_error(\"AcaGlobalAssembler::assemblePotentialOperator(): \"\n                             \"To enable assembly in ACA mode, recompile BEM++ \"\n                             \"with the symbol WITH_AHMED defined.\");\n#endif // WITH_AHMED\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstd::auto_ptr<DiscreteBoundaryOperator<ResultType> >\nAcaGlobalAssembler<BasisFunctionType, ResultType>::assemblePotentialOperator(\n        const arma::Mat<CoordinateType>& points,\n        const Space<BasisFunctionType>& trialSpace,\n        LocalAssemblerForPotentialOperators& localAssembler,\n        const EvaluationOptions& options)\n{\n    std::vector<LocalAssemblerForPotentialOperators*> localAssemblers(\n                1, &localAssembler);\n    std::vector<ResultType> termMultipliers(1, 1.0);\n\n    return assemblePotentialOperator(points, trialSpace, localAssemblers,\n                                     termMultipliers, options);\n}\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS_AND_RESULT(AcaGlobalAssembler);\n\n} // namespace Bempp\n", "meta": {"hexsha": "3c043e7a720c02afb641db1c8bce1b6de0bbf308", "size": 35399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/assembly/aca_global_assembler.cpp", "max_stars_repo_name": "UCL/bempp", "max_stars_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-22T13:34:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-22T13:35:20.000Z", "max_issues_repo_path": "lib/assembly/aca_global_assembler.cpp", "max_issues_repo_name": "UCL/bempp", "max_issues_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/assembly/aca_global_assembler.cpp", "max_forks_repo_name": "UCL/bempp", "max_forks_repo_head_hexsha": "f768ec7d319c02d6e0142512fb61db0607cadf10", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.13840399, "max_line_length": 102, "alphanum_fraction": 0.636599904, "num_tokens": 8293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4073334000459303, "lm_q1q2_score": 0.21002921340285202}}
{"text": "// ====================================================================\n// This file is part of FlexibleSUSY.\n//\n// FlexibleSUSY is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published\n// by the Free Software Foundation, either version 3 of the License,\n// or (at your option) any later version.\n//\n// FlexibleSUSY is distributed in the hope that it will be useful, but\n// WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n// General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FlexibleSUSY.  If not, see\n// <http://www.gnu.org/licenses/>.\n// ====================================================================\n\n// File generated at Sat 27 Aug 2016 12:43:04\n\n#include \"SingletDM_two_scale_initial_guesser.hpp\"\n#include \"SingletDM_two_scale_model.hpp\"\n#include \"lowe.h\"\n#include \"error.hpp\"\n#include \"ew_input.hpp\"\n#include \"wrappers.hpp\"\n\n#include <Eigen/Core>\n#include <cassert>\n\nnamespace flexiblesusy {\n\n#define DERIVEDPARAMETER(p) model->p()\n#define INPUTPARAMETER(p) model->get_input().p\n#define MODELPARAMETER(p) model->get_##p()\n#define PHASE(p) model->get_##p()\n#define LowEnergyConstant(p) Electroweak_constants::p\n#define MODEL model\n\nSingletDM_initial_guesser<Two_scale>::SingletDM_initial_guesser(\n   SingletDM<Two_scale>* model_,\n   const softsusy::QedQcd& qedqcd_,\n   const SingletDM_low_scale_constraint<Two_scale>& low_constraint_,\n   const SingletDM_susy_scale_constraint<Two_scale>& susy_constraint_,\n   const SingletDM_high_scale_constraint<Two_scale>& high_constraint_\n)\n   : Initial_guesser<Two_scale>()\n   , model(model_)\n   , qedqcd(qedqcd_)\n   , mu_guess(0.)\n   , mc_guess(0.)\n   , mt_guess(0.)\n   , md_guess(0.)\n   , ms_guess(0.)\n   , mb_guess(0.)\n   , me_guess(0.)\n   , mm_guess(0.)\n   , mtau_guess(0.)\n   , running_precision(1.0e-3)\n   , low_constraint(low_constraint_)\n   , susy_constraint(susy_constraint_)\n   , high_constraint(high_constraint_)\n{\n   assert(model && \"SingletDM_initial_guesser: Error: pointer to model\"\n          \" SingletDM<Two_scale> must not be zero\");\n}\n\nSingletDM_initial_guesser<Two_scale>::~SingletDM_initial_guesser()\n{\n}\n\n/**\n * Guesses the DR-bar model parameters by calling\n * guess_susy_parameters() and guess_soft_parameters() .\n */\nvoid SingletDM_initial_guesser<Two_scale>::guess()\n{\n   guess_susy_parameters();\n   guess_soft_parameters();\n}\n\n/**\n * Guesses the SUSY parameters (gauge, Yukawa couplings) at\n * \\f$m_\\text{top}^\\text{pole}\\f$ from the Standard Model gauge\n * couplings and fermion masses.  Threshold corrections are ignored.\n * The user-defined initial guess at the low-scale\n * (InitialGuessAtLowScale) is applied here:\n *\n * \\code{.cpp}\n   const auto LamSHInput = INPUTPARAMETER(LamSHInput);\n   const auto LamSInput = INPUTPARAMETER(LamSInput);\n   const auto muSInput = INPUTPARAMETER(muSInput);\n   const auto HiggsIN = INPUTPARAMETER(HiggsIN);\n\n   MODEL->set_v(Re(LowEnergyConstant(vev)));\n   calculate_Yu_DRbar();\n   calculate_Yd_DRbar();\n   calculate_Ye_DRbar();\n   MODEL->set_LamSH(Re(LamSHInput));\n   MODEL->set_LamS(Re(LamSInput));\n   MODEL->set_muS(Re(muSInput));\n   MODEL->set_muH(Re(HiggsIN));\n\n * \\endcode\n */\nvoid SingletDM_initial_guesser<Two_scale>::guess_susy_parameters()\n{\n   using namespace softsusy;\n\n   softsusy::QedQcd leAtMt(qedqcd);\n   const double MZ = Electroweak_constants::MZ;\n   const double MW = Electroweak_constants::MW;\n   const double sinThetaW2 = 1.0 - Sqr(MW / MZ);\n   const double mtpole = leAtMt.displayPoleMt();\n\n   mu_guess = leAtMt.displayMass(mUp);\n   mc_guess = leAtMt.displayMass(mCharm);\n   mt_guess = model->get_thresholds() > 0 ?\n      leAtMt.displayMass(mTop) - 30.0 :\n      leAtMt.displayPoleMt();\n   md_guess = leAtMt.displayMass(mDown);\n   ms_guess = leAtMt.displayMass(mStrange);\n   mb_guess = leAtMt.displayMass(mBottom);\n   me_guess = model->get_thresholds() > 0 ?\n      leAtMt.displayMass(mElectron) :\n      leAtMt.displayPoleMel();\n   mm_guess = model->get_thresholds() > 0 ?\n      leAtMt.displayMass(mMuon) :\n      leAtMt.displayPoleMmuon();\n   mtau_guess = leAtMt.displayMass(mTau);\n\n   // guess gauge couplings at mt\n   const DoubleVector alpha_sm(leAtMt.getGaugeMu(mtpole, sinThetaW2));\n\n   MODEL->set_g1(Sqrt(4. * Pi * alpha_sm(1)));\n   MODEL->set_g2(Sqrt(4. * Pi * alpha_sm(2)));\n   MODEL->set_g3(Sqrt(4. * Pi * alpha_sm(3)));\n\n\n   model->set_scale(mtpole);\n\n   // apply user-defined initial guess at the low scale\n   const auto LamSHInput = INPUTPARAMETER(LamSHInput);\n   const auto LamSInput = INPUTPARAMETER(LamSInput);\n   const auto muSInput = INPUTPARAMETER(muSInput);\n   const auto HiggsIN = INPUTPARAMETER(HiggsIN);\n\n   MODEL->set_v(Re(LowEnergyConstant(vev)));\n   calculate_Yu_DRbar();\n   calculate_Yd_DRbar();\n   calculate_Ye_DRbar();\n   MODEL->set_LamSH(Re(LamSHInput));\n   MODEL->set_LamS(Re(LamSInput));\n   MODEL->set_muS(Re(muSInput));\n   MODEL->set_muH(Re(HiggsIN));\n\n}\n\nvoid SingletDM_initial_guesser<Two_scale>::calculate_DRbar_yukawa_couplings()\n{\n   calculate_Yu_DRbar();\n   calculate_Yd_DRbar();\n   calculate_Ye_DRbar();\n}\n\n/**\n * Calculates the Yukawa couplings Yu of the up-type quarks\n * from the Standard Model up-type quark masses (ignoring threshold\n * corrections).\n */\nvoid SingletDM_initial_guesser<Two_scale>::calculate_Yu_DRbar()\n{\n   Eigen::Matrix<std::complex<double>,3,3> upQuarksDRbar(ZEROMATRIXCOMPLEX(3,3));\n   upQuarksDRbar(0,0) = mu_guess;\n   upQuarksDRbar(1,1) = mc_guess;\n   upQuarksDRbar(2,2) = mt_guess;\n\n   const auto v = MODELPARAMETER(v);\n   MODEL->set_Yu((-((1.4142135623730951*upQuarksDRbar)/v).transpose()).real());\n\n}\n\n/**\n * Calculates the Yukawa couplings Yd of the down-type\n * quarks from the Standard Model down-type quark masses (ignoring\n * threshold corrections).\n */\nvoid SingletDM_initial_guesser<Two_scale>::calculate_Yd_DRbar()\n{\n   Eigen::Matrix<std::complex<double>,3,3> downQuarksDRbar(ZEROMATRIXCOMPLEX(3,3));\n   downQuarksDRbar(0,0) = md_guess;\n   downQuarksDRbar(1,1) = ms_guess;\n   downQuarksDRbar(2,2) = mb_guess;\n\n   const auto v = MODELPARAMETER(v);\n   MODEL->set_Yd((((1.4142135623730951*downQuarksDRbar)/v).transpose()).real())\n      ;\n\n}\n\n/**\n * Calculates the Yukawa couplings Ye of the leptons\n * from the Standard Model down-type lepton masses (ignoring threshold\n * corrections).\n */\nvoid SingletDM_initial_guesser<Two_scale>::calculate_Ye_DRbar()\n{\n   Eigen::Matrix<std::complex<double>,3,3> downLeptonsDRbar(ZEROMATRIXCOMPLEX(3,3));\n   downLeptonsDRbar(0,0) = me_guess;\n   downLeptonsDRbar(1,1) = mm_guess;\n   downLeptonsDRbar(2,2) = mtau_guess;\n\n   const auto v = MODELPARAMETER(v);\n   MODEL->set_Ye((((1.4142135623730951*downLeptonsDRbar)/v).transpose()).real()\n      );\n\n}\n\n/**\n * Guesses the soft-breaking parameters.  At first it runs to the\n * guess of the high-scale (HighScaleFirstGuess) and imposes the\n * high-scale constraint (HighScaleInput):\n *\n * \\code{.cpp}\n\n * \\endcode\n *\n * Afterwards, it runs to the low-scale guess (LowScaleFirstGuess) and\n * solves the EWSB conditions at the tree-level.  Finally the DR-bar\n * mass spectrum is calculated.\n */\nvoid SingletDM_initial_guesser<Two_scale>::guess_soft_parameters()\n{\n   const double low_scale_guess = low_constraint.get_initial_scale_guess();\n   const double high_scale_guess = high_constraint.get_initial_scale_guess();\n\n   model->run_to(high_scale_guess, running_precision);\n\n   // apply high-scale constraint\n   high_constraint.set_model(model);\n   high_constraint.apply();\n\n   // apply user-defined initial guess at the high scale\n\n\n   model->run_to(low_scale_guess, running_precision);\n\n   // apply EWSB constraint\n   model->solve_ewsb_tree_level();\n\n   // calculate tree-level spectrum\n   model->calculate_DRbar_masses();\n}\n\n} // namespace flexiblesusy\n", "meta": {"hexsha": "28d83bcccd7d6441e18d28795c2dd67c5f221137", "size": 7867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contrib/MassSpectra/flexiblesusy/models/SingletDM/SingletDM_two_scale_initial_guesser.cpp", "max_stars_repo_name": "aaronvincent/gambit_aaron", "max_stars_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contrib/MassSpectra/flexiblesusy/models/SingletDM/SingletDM_two_scale_initial_guesser.cpp", "max_issues_repo_name": "aaronvincent/gambit_aaron", "max_issues_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contrib/MassSpectra/flexiblesusy/models/SingletDM/SingletDM_two_scale_initial_guesser.cpp", "max_forks_repo_name": "aaronvincent/gambit_aaron", "max_forks_repo_head_hexsha": "a38bd6fc10d781e71f2adafd401c76e1e3476b05", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.73046875, "max_line_length": 84, "alphanum_fraction": 0.7150120758, "num_tokens": 2201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984137988772, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2099388154972992}}
{"text": "#include \"CoverageStats.h\"\r\nusing reseq::CoverageStats;\r\n\r\n//include <algorithm>\r\nusing std::min;\r\nusing std::max;\r\nusing std::sort;\r\n//include <array>\r\nusing std::array;\r\n//include <cmath>\r\nusing std::ceil;\r\nusing std::exp;\r\nusing std::pow;\r\nusing std::round;\r\n#include <limits>\r\nusing std::numeric_limits;\r\n//include <mutex>\r\nusing std::mutex;\r\nusing std::lock_guard;\r\n//include <utility>\r\nusing std::pair;\r\n\r\n#include <boost/math/distributions/poisson.hpp>\r\nusing boost::math::cdf;\r\nusing boost::math::poisson_distribution;\r\n\r\n//include <seqan/bam_io.h>\r\nusing seqan::Dna;\r\nusing seqan::Dna5;\r\nusing seqan::hasFlagRC;\r\nusing seqan::hasFlagLast;\r\n\r\n//include \"utilities.hpp\"\r\nusing reseq::utilities::ConstDna5StringReverseComplement;\r\nusing reseq::utilities::ConstIupacStringReverseComplement;\r\nusing reseq::utilities::ReversedConstCharString;\r\nusing reseq::utilities::ReversedConstCigarString;\r\nusing reseq::utilities::Complement;\r\nusing reseq::utilities::at;\r\nusing reseq::utilities::Divide;\r\nusing reseq::utilities::DominantBase;\r\nusing reseq::utilities::IsN;\r\nusing reseq::utilities::Percent;\r\nusing reseq::utilities::SafePercent;\r\nusing reseq::utilities::SetToMax;\r\nusing reseq::utilities::SetToMin;\r\nusing reseq::utilities::TransformDistanceToStartOfErrorRegion;\r\n\r\n// Definitions so that referencing a const static is valid\r\nconst reseq::uintCovCount reseq::CoverageStats::kMaxCoverage;\r\n\r\nvoid CoverageStats::EvalRead( FullRecord *record, CoverageStats::CoverageBlock *coverage_block, const Reference &reference, QualityStats &qualities, ErrorStats &errors, uintQual phred_quality_offset){\r\n\t// Fragments that did not made the filters have to_ref_pos_=0\r\n\tif(record->to_ref_pos_){\r\n\t\tConstIupacStringReverseComplement reversed_seq(record->record_.seq);\r\n\t\tReversedConstCharString reversed_qual(record->record_.qual);\r\n\t\tReversedConstCigarString rev_cigar(record->record_.cigar);\r\n\r\n\t\tintSeqShift coverage_pos; // Can be before the start of the block, so negative values need to be allowed\r\n\t\tuintSeqLen ref_pos;\r\n\t\tif( hasFlagRC(record->record_) ){\r\n\t\t\tcoverage_pos = record->to_ref_pos_-coverage_block->start_pos_-1;\r\n\t\t\tref_pos = record->to_ref_pos_-1;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tcoverage_pos = record->from_ref_pos_-coverage_block->start_pos_;\r\n\t\t\tref_pos = record->from_ref_pos_;\r\n\t\t}\r\n\r\n\t\tuintReadLen read_pos(0), not_considered_ref_bases(0);\r\n\t\tDna ref_base;\r\n\t\tDna5 base, dom_error;\r\n\t\tuintQual qual(0), last_qual(1);\r\n\t\tuintReadLen num_errors = 0;\r\n\t\tuintPercent error_rate;\r\n\t\tuintReadLenCalc error_rate_sum(0);\r\n\t\tfor( const auto &cigar_element : (hasFlagRC(record->record_)?rev_cigar:record->record_.cigar) ){\r\n\t\t\tswitch( cigar_element.operation ){\r\n\t\t\tcase 'M':\r\n\t\t\tcase '=':\r\n\t\t\tcase 'X':\r\n\t\t\tcase 'S': // Treat soft-clipping as match, so that bwa and bowtie2 behave the same\r\n\t\t\t\tfor(auto i=cigar_element.count; i--; ){\r\n\t\t\t\t\tif(record->from_ref_pos_ <= ref_pos && ref_pos < record->to_ref_pos_){\r\n\t\t\t\t\t\t// We are currently not comparing the adapter to the reference\r\n\t\t\t\t\t\tif( hasFlagRC(record->record_) ){\r\n\t\t\t\t\t\t\tbase = at(reversed_seq, read_pos);\r\n\t\t\t\t\t\t\tqual = at(reversed_qual, read_pos)-phred_quality_offset;\r\n\t\t\t\t\t\t\tref_base = Complement::Dna5(at(reference.ReferenceSequence(record->record_.rID), ref_pos));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\tbase = at(record->record_.seq, read_pos);\r\n\t\t\t\t\t\t\tqual = at(record->record_.qual, read_pos)-phred_quality_offset;\r\n\t\t\t\t\t\t\tref_base = at(reference.ReferenceSequence(record->record_.rID), ref_pos);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif( !CoveragePosValid(coverage_pos, coverage_block) ){\r\n\t\t\t\t\t\t\t++(not_considered_ref_bases);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\tif(0 > coverage_pos){\r\n\t\t\t\t\t\t\t\terror_rate = coverage_block->previous_coverage_.at(-1*coverage_pos-1).error_rate_.at(hasFlagRC(record->record_));\r\n\t\t\t\t\t\t\t\tdom_error = coverage_block->previous_coverage_.at(-1*coverage_pos-1).dom_error_.at(hasFlagRC(record->record_));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t\terror_rate = coverage_block->coverage_.at(coverage_pos).error_rate_.at(hasFlagRC(record->record_));\r\n\t\t\t\t\t\t\t\tdom_error = coverage_block->coverage_.at(coverage_pos).dom_error_.at(hasFlagRC(record->record_));\r\n\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\tqualities.AddRefBase(hasFlagLast(record->record_), ref_base, dom_error, record->tile_id_, qual, error_rate, last_qual, record->sequence_quality_, read_pos);\r\n\t\t\t\t\t\t\terrors.AddBase(hasFlagLast(record->record_), ref_base, dom_error, record->tile_id_, base, qual, read_pos, num_errors, error_rate);\r\n\r\n\t\t\t\t\t\t\terror_rate_sum += error_rate;\r\n\r\n\t\t\t\t\t\t\tif( ref_base != base ){\r\n\t\t\t\t\t\t\t\t++num_errors;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tlast_qual = qual;\r\n\r\n\t\t\t\t\t\t++read_pos;\r\n\r\n\t\t\t\t\t\tif( hasFlagRC(record->record_) ){\r\n\t\t\t\t\t\t\t--coverage_pos;\r\n\t\t\t\t\t\t\t--ref_pos;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t++coverage_pos;\r\n\t\t\t\t\t\t\t++ref_pos;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'N':\r\n\t\t\tcase 'D':\r\n\t\t\t\tfor(auto i=cigar_element.count; i--; ){\r\n\t\t\t\t\tif(record->from_ref_pos_ <= ref_pos && ref_pos < record->to_ref_pos_){\r\n\t\t\t\t\t\t// We are currently not comparing the adapter to the reference\r\n\t\t\t\t\t\tif( hasFlagRC(record->record_) ){\r\n\t\t\t\t\t\t\tref_base = Complement::Dna5(at(reference.ReferenceSequence(record->record_.rID), ref_pos));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\tref_base = at(reference.ReferenceSequence(record->record_.rID), ref_pos);\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif( !CoveragePosValid(coverage_pos, coverage_block) ){\r\n\t\t\t\t\t\t\t++(not_considered_ref_bases);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\tif(0 > coverage_pos){\r\n\t\t\t\t\t\t\t\terror_rate_sum += coverage_block->previous_coverage_.at(-1*coverage_pos-1).error_rate_.at(hasFlagRC(record->record_));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t\terror_rate_sum += coverage_block->coverage_.at(coverage_pos).error_rate_.at(hasFlagRC(record->record_));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t++num_errors;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif( hasFlagRC(record->record_) ){\r\n\t\t\t\t\t\t\t--coverage_pos;\r\n\t\t\t\t\t\t\t--ref_pos;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t++coverage_pos;\r\n\t\t\t\t\t\t\t++ref_pos;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'I':\r\n\t\t\t\tif(record->from_ref_pos_ <= ref_pos && ref_pos < record->to_ref_pos_){\r\n\t\t\t\t\tif( hasFlagRC(record->record_) ){\r\n\t\t\t\t\t\tlast_qual = at(reversed_qual, read_pos+cigar_element.count-1)-phred_quality_offset; // Directly fill last_qual as qual is not needed here\r\n\t\t\t\t\t\tref_base = Complement::Dna5(at(reference.ReferenceSequence(record->record_.rID), ref_pos));\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse{\r\n\t\t\t\t\t\tlast_qual = at(record->record_.qual, read_pos+cigar_element.count-1)-phred_quality_offset; // Directly fill last_qual as qual is not needed here\r\n\t\t\t\t\t\tref_base = at(reference.ReferenceSequence(record->record_.rID), ref_pos);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif( CoveragePosValid(coverage_pos, coverage_block) ){\r\n\t\t\t\t\t\tnum_errors += cigar_element.count;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tread_pos += cigar_element.count;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(not_considered_ref_bases < record->to_ref_pos_-record->from_ref_pos_){ // At least one base was considered\r\n\t\t\tqualities.AddRefRead(hasFlagLast(record->record_), record->tile_id_, record->reference_gc_, record->sequence_quality_, utilities::Divide(error_rate_sum, static_cast<uintReadLenCalc>(record->to_ref_pos_-record->from_ref_pos_-not_considered_ref_bases)), record->fragment_length_);\r\n\t\t\terrors.AddRead(hasFlagLast(record->record_), num_errors);\r\n\t\t}\r\n\t}\r\n\r\n\tdelete record;\r\n}\r\n\r\ninline void CoverageStats::ApplyZeroCoverageRegion(){\r\n\ttmp_coverage_.at( 0 ) += zero_coverage_region_;\r\n\ttmp_coverage_.at( 0 ) -= excluded_bases_;\r\n\tfor( int strand=2; strand--; ){\r\n\t\ttmp_coverage_stranded_.at(strand).at(0) += zero_coverage_region_;\r\n\t\ttmp_coverage_stranded_.at(strand).at(0) -= excluded_bases_;\r\n\t}\r\n}\r\n\r\ndouble CoverageStats::GetPositionProbabilities(CoverageBlock *block, const Reference &reference, ThreadData &thread){\r\n\t// Get coverage weighted median error rate\r\n\tthread.block_coverage_.clear();\r\n\tthread.block_coverage_.resize(block->coverage_.size(), {0,0});\r\n\tthread.error_rates_sorted_.clear();\r\n\r\n\tuintNucCount total_bases(0), correct_bases(0);\r\n\tfor( uintSeqLen pos = 0; pos < block->coverage_.size(); ++pos ){\r\n\t\tif( block->coverage_.at(pos).valid_ ){\r\n\t\t\tauto ref_base = at(reference.ReferenceSequence(block->sequence_id_), block->start_pos_ + pos);\r\n\t\t\tauto rev_base = Complement::Dna5(ref_base);\r\n\t\t\tfor( int i=5; i--; ){\r\n\t\t\t\tthread.block_coverage_.at(pos).at(0) += block->coverage_.at(pos).coverage_forward_.at(i);\r\n\t\t\t\tif(block->coverage_.at(pos).coverage_forward_.at(i) > block->coverage_.at(pos).coverage_forward_.at( block->coverage_.at(pos).dom_error_.at(0) ) && i != ref_base){\r\n\t\t\t\t\tblock->coverage_.at(pos).dom_error_.at(0) = i;\r\n\t\t\t\t}\r\n\t\t\t\tthread.block_coverage_.at(pos).at(1) += block->coverage_.at(pos).coverage_reverse_.at(i);\r\n\t\t\t\tif(block->coverage_.at(pos).coverage_reverse_.at(i) > block->coverage_.at(pos).coverage_reverse_.at( block->coverage_.at(pos).dom_error_.at(1) ) && i != rev_base){\r\n\t\t\t\t\tblock->coverage_.at(pos).dom_error_.at(1) = i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\ttotal_bases += thread.block_coverage_.at(pos).at(0) + thread.block_coverage_.at(pos).at(1);\r\n\t\t\tcorrect_bases += block->coverage_.at(pos).coverage_forward_.at(ref_base) + block->coverage_.at(pos).coverage_reverse_.at(rev_base);\r\n\r\n\t\t\tthread.error_rates_sorted_.emplace_back(static_cast<double>(thread.block_coverage_.at(pos).at(0)-block->coverage_.at(pos).coverage_forward_.at(ref_base)) / thread.block_coverage_.at(pos).at(0), thread.block_coverage_.at(pos).at(0));\r\n\t\t\tthread.error_rates_sorted_.emplace_back(static_cast<double>(thread.block_coverage_.at(pos).at(1)-block->coverage_.at(pos).coverage_reverse_.at(rev_base)) / thread.block_coverage_.at(pos).at(1), thread.block_coverage_.at(pos).at(1));\r\n\t\t}\r\n\t}\r\n\r\n\tthread.non_sytematic_probability_.clear();\r\n\tthread.non_sytematic_probability_.resize(block->coverage_.size(), {1.0,1.0});\r\n\tthread.non_sytematic_probability_sorted_.clear();\r\n\r\n\tif(correct_bases == total_bases){\r\n\t\treturn 0.0; // Nothing is systematic if we don't have errors\r\n\t}\r\n\r\n\tsort(thread.error_rates_sorted_.begin(), thread.error_rates_sorted_.end());\r\n\tuintNucCount sum_bases(0);\r\n\tuintSeqLen median_error_pos(0);\r\n\twhile(sum_bases < total_bases/2){\r\n\t\tsum_bases += thread.error_rates_sorted_.at(median_error_pos++).second;\r\n\t}\r\n\twhile( median_error_pos < thread.error_rates_sorted_.size() && thread.error_rates_sorted_.at(median_error_pos).first == 0.0 ){ // If the median error is exactly zero, get next non-zero error\r\n\t\t++median_error_pos;\r\n\t}\r\n\tif(median_error_pos == thread.error_rates_sorted_.size()){\r\n\t\treturn 0.0;\r\n\t}\r\n\r\n\tdouble error_rate = thread.error_rates_sorted_.at(median_error_pos).first;\r\n\tSetToMin( error_rate, static_cast<double>(total_bases-correct_bases) / total_bases ); // If the mean is lower than the median use mean (should only happen if we shift median to non-zero value before)\r\n\r\n\t++tmp_block_error_rate_.at(static_cast<uintPercent>(round(error_rate*100)));\r\n\terror_rate /= 3.0; // Systematic is only for one base\r\n\r\n\tif(0.0 == error_rate){\r\n\t\treturn 0.0; // Nothing is systematic if we have super low error rates\r\n\t}\r\n\r\n\tfor( uintSeqLen pos = 0; pos < block->coverage_.size(); ++pos ){\r\n\t\tif( block->coverage_.at(pos).valid_ ){\r\n\t\t\t// Handle forward direction\r\n\t\t\tuintCovCount errors = block->coverage_.at(pos).coverage_forward_.at(block->coverage_.at(pos).dom_error_.at(0));\r\n\t\t\tif( 0 < thread.block_coverage_.at(pos).at(0) ){\r\n\t\t\t\tif(0 == errors){\r\n\t\t\t\t\tthread.non_sytematic_probability_sorted_.push_back(1.0);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tpoisson_distribution<> pois_dist( thread.block_coverage_.at(pos).at(0)*error_rate );\r\n\t\t\t\t\tthread.non_sytematic_probability_sorted_.push_back( 1-cdf( pois_dist, errors-1 ) ); // Probability to have at least that many errors (1-probability to have less errors)\r\n\t\t\t\t}\r\n\t\t\t\tthread.non_sytematic_probability_.at(pos).at(0) = thread.non_sytematic_probability_sorted_.back();\r\n\t\t\t\t++tmp_systematic_error_p_values_.at(static_cast<size_t>(thread.non_sytematic_probability_sorted_.back()*kPValueHistBins));\r\n\t\t\t}\r\n\r\n\t\t\t// Handle reverse direction\r\n\t\t\tif( 0 < thread.block_coverage_.at(pos).at(1) ){\r\n\t\t\t\terrors = block->coverage_.at(pos).coverage_reverse_.at(block->coverage_.at(pos).dom_error_.at(1));\r\n\t\t\t\tif(0 == errors){\r\n\t\t\t\t\tthread.non_sytematic_probability_sorted_.push_back(1.0);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tpoisson_distribution<> pois_dist( thread.block_coverage_.at(pos).at(1)*error_rate );\r\n\t\t\t\t\tthread.non_sytematic_probability_sorted_.push_back( 1-cdf( pois_dist, errors-1 ) ); // Probability to have at least that many errors (1-probability to have less errors)\r\n\t\t\t\t}\r\n\t\t\t\tthread.non_sytematic_probability_.at(pos).at(1) = thread.non_sytematic_probability_sorted_.back();\r\n\t\t\t\t++tmp_systematic_error_p_values_.at(static_cast<size_t>(thread.non_sytematic_probability_sorted_.back()*kPValueHistBins));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// Bejamini-Hochberg\r\n\tsort(thread.non_sytematic_probability_sorted_.begin(), thread.non_sytematic_probability_sorted_.end());\r\n\tsize_t last_systematic(thread.non_sytematic_probability_sorted_.size());\r\n\twhile(--last_systematic && thread.non_sytematic_probability_sorted_.at(last_systematic) > kSystematicErrorFDR*(last_systematic+1)/thread.non_sytematic_probability_sorted_.size() );\r\n\r\n\tif( 0==last_systematic && thread.non_sytematic_probability_sorted_.at(0) > kSystematicErrorFDR/thread.non_sytematic_probability_sorted_.size() ){\r\n\t\t++tmp_block_percent_systematic_.at(0);\r\n\t\treturn 0.0; // No index has a probability lower than expected, so seems like we don't have systematic errors\r\n\t}\r\n\telse if( last_systematic == thread.non_sytematic_probability_sorted_.size()-1 ){\r\n\t\t++tmp_block_percent_systematic_.at(100);\r\n\t\treturn 1.0; // Final probability is lower than expected, so seems like we only have systematic errors;\r\n\t}\r\n\telse{\r\n\t\t++tmp_block_percent_systematic_.at(Percent(last_systematic+1, thread.non_sytematic_probability_sorted_.size()));\r\n\t\treturn thread.non_sytematic_probability_sorted_.at(last_systematic);\r\n\t}\r\n}\r\n\r\nvoid CoverageStats::UpdateCoverageAtSinglePosition(CoveragePosition &nuc_coverage, array<uintCovCount, 2> &coverage, Dna5 ref_base){\r\n\tDna5 reverse_base = Complement::Dna5(ref_base);\r\n\r\n\tif( coverage_threshold_ > coverage.at(0) ){\r\n\t\tnuc_coverage.coverage_sufficient_.at(0) = false;\r\n\t}\r\n\tif( coverage_threshold_ > coverage.at(1) ){\r\n\t\tnuc_coverage.coverage_sufficient_.at(1) = false;\r\n\t}\r\n\r\n\tauto errors_forward = coverage.at(0) - nuc_coverage.coverage_forward_.at(ref_base);\r\n\tauto errors_reverse = coverage.at(1) - nuc_coverage.coverage_reverse_.at(reverse_base);\r\n\r\n\tauto cov_sum = coverage.at(0) + coverage.at(1);\r\n\tauto error_sum = errors_forward + errors_reverse;\r\n\r\n\t// Account for coverage and error_coverage at that position\r\n\t++tmp_coverage_.at( min(cov_sum, kMaxCoverage) );\r\n\t++tmp_coverage_stranded_.at(0).at( min(coverage.at(0), kMaxCoverage) );\r\n\t++tmp_coverage_stranded_.at(1).at( min(coverage.at(1), kMaxCoverage) );\r\n\tif(cov_sum){\r\n\t\t++tmp_coverage_stranded_percent_.at(0).at( Percent(coverage.at(0), cov_sum) );\r\n\t\t++tmp_coverage_stranded_percent_.at(1).at( Percent(coverage.at(1), cov_sum) );\r\n\r\n\t\tif(nuc_coverage.valid_){\r\n\t\t\t++tmp_error_coverage_.at( min(error_sum, kMaxCoverage) );\r\n\t\t\t++tmp_error_coverage_percent_.at( Percent(error_sum, cov_sum) );\r\n\t\t\tif(coverage.at(0) && coverage.at(1)){\r\n\t\t\t\t++tmp_error_coverage_percent_stranded_.at( Percent(errors_forward, coverage.at(0)) ).at( Percent(errors_reverse, coverage.at(1)) );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif( 10 <= cov_sum ){\r\n\t\t\t++tmp_coverage_stranded_percent_min_cov_10_.at(0).at( Percent(coverage.at(0), cov_sum) );\r\n\t\t\t++tmp_coverage_stranded_percent_min_cov_10_.at(1).at( Percent(coverage.at(1), cov_sum) );\r\n\t\t\tif(nuc_coverage.valid_){\r\n\t\t\t\t++tmp_error_coverage_percent_min_cov_10_.at( Percent(error_sum, cov_sum) );\r\n\t\t\t}\r\n\r\n\t\t\tif( 20 <= cov_sum ){\r\n\t\t\t\t++tmp_coverage_stranded_percent_min_cov_20_.at(0).at( Percent(coverage.at(0), cov_sum) );\r\n\t\t\t\t++tmp_coverage_stranded_percent_min_cov_20_.at(1).at( Percent(coverage.at(1), cov_sum) );\r\n\t\t\t\tif(nuc_coverage.valid_){\r\n\t\t\t\t\t++tmp_error_coverage_percent_min_cov_20_.at( Percent(error_sum, cov_sum) );\r\n\r\n\t\t\t\t\tif(10 <= coverage.at(0) && 10 <= coverage.at(1)){\r\n\t\t\t\t\t\t++tmp_error_coverage_percent_stranded_min_strand_cov_10_.at( Percent(errors_forward, coverage.at(0)) ).at( Percent(errors_reverse, coverage.at(1)) );\r\n\t\t\t\t\t\tif(20 <= coverage.at(0) && 20 <= coverage.at(1)){\r\n\t\t\t\t\t\t\t++tmp_error_coverage_percent_stranded_min_strand_cov_20_.at( Percent(errors_forward, coverage.at(0)) ).at( Percent(errors_reverse, coverage.at(1)) );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid CoverageStats::UpdateDistances(uintSeqLen &distance_to_start_of_error_region, uintPercent &start_rate, uintPercent error_rate) const{\r\n\tif( distance_to_start_of_error_region ){\r\n\t\tif(start_rate < error_rate){\r\n\t\t\tdistance_to_start_of_error_region = 0;\r\n\t\t\tstart_rate = error_rate;\r\n\t\t}\r\n\t\telse if( ++distance_to_start_of_error_region >= reset_distance_ ){\r\n\t\t\tdistance_to_start_of_error_region = 0;\r\n\t\t\tstart_rate = 0;\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tif(error_rate){ // If we assign an error rate it is systematic\r\n\t\t\tdistance_to_start_of_error_region = 1;\r\n\t\t\tstart_rate = error_rate;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nCoverageStats::CoverageBlock *CoverageStats::CreateBlock(uintRefSeqId seq_id, uintSeqLen start_pos){\r\n\tCoverageBlock *new_block;\r\n\tif( reuse_mutex_.try_lock() ){\r\n\t\tif( reusable_blocks_.size() ){\r\n\t\t\tnew_block = reusable_blocks_.back();\r\n\t\t\treusable_blocks_.pop_back();\r\n\t\t\treuse_mutex_.unlock();\r\n\r\n\t\t\tnew_block->sequence_id_ = seq_id;\r\n\t\t\tnew_block->start_pos_ = start_pos;\r\n\t\t\tnew_block->previous_block_ = last_block_;\r\n\t\t\tnew_block->next_block_ = NULL;\r\n\t\t\tnew_block->coverage_.clear();\r\n\t\t\tnew_block->previous_coverage_.clear();\r\n\t\t\tnew_block->reads_.clear();\r\n\t\t\tnew_block->scheduled_for_processing_.clear();\r\n\t\t\tnew_block->processed_ = false;\r\n\t\t}\r\n\t\telse{\r\n\t\t\treuse_mutex_.unlock();\r\n\t\t\tnew_block = new CoverageBlock(seq_id, start_pos, last_block_);\r\n\t\t\tnew_block->previous_coverage_.reserve(maximum_read_length_on_reference_);\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tnew_block = new CoverageBlock(seq_id, start_pos, last_block_);\r\n\t\tnew_block->previous_coverage_.reserve(maximum_read_length_on_reference_);\r\n\t}\r\n\r\n\tnew_block->reads_.reserve( (*last_block_).reads_.capacity() );\r\n\tnew_block->coverage_.resize( kBlockSize );\r\n\tnew_block->first_variant_id_ = (*last_block_).first_variant_id_;\r\n\t(*last_block_).next_block_ = new_block;\r\n\r\n\treturn new_block;\r\n}\r\n\r\nvoid CoverageStats::UpdateFirstVariant(CoverageBlock &block, const Reference &reference){\r\n\tif( reference.VariantPositionsLoaded() ){\r\n\t\twhile( block.first_variant_id_ < reference.VariantPositions(block.sequence_id_).size() && reference.VariantPositions(block.sequence_id_).at(block.first_variant_id_) < (*last_block_).start_pos_ ){\r\n\t\t\t++block.first_variant_id_;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool CoverageStats::IsVariantPosition( intVariantId &cur_var, uintRefSeqId ref_seq_id, uintSeqLen pos, const Reference &reference ) const{\r\n\tif( reference.VariantPositionsLoaded() ){\r\n\t\twhile(cur_var < reference.VariantPositions(ref_seq_id).size() && reference.VariantPositions(ref_seq_id).at(cur_var) < pos){\r\n\t\t\t++cur_var;\r\n\t\t}\r\n\r\n\t\treturn cur_var < reference.VariantPositions(ref_seq_id).size() && reference.VariantPositions(ref_seq_id).at(cur_var) == pos;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nvoid CoverageStats::InitBlock(CoverageBlock &block, const Reference &reference){\r\n\t// Ensure that the block is not reaching over the end of the reference sequence\r\n\tif( reference.SequenceLength(block.sequence_id_) < block.start_pos_+kBlockSize){\r\n\t\tblock.coverage_.resize( reference.SequenceLength(block.sequence_id_)-block.start_pos_ );\r\n\t}\r\n\r\n\t// Check for invalid positions\r\n\tauto cur_var = block.first_variant_id_;\r\n\tfor(auto pos = block.start_pos_; pos < block.start_pos_+block.coverage_.size(); ++pos){\r\n\t\tif( IsN( at(reference.ReferenceSequence(block.sequence_id_), pos) ) || IsVariantPosition( cur_var, block.sequence_id_, pos, reference  ) ){\r\n\t\t\tblock.coverage_.at(pos-block.start_pos_).valid_ = false;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid CoverageStats::ProcessBlock(CoverageBlock *block, const Reference &reference, ThreadData &thread){\r\n\tauto max_probability_systematic = GetPositionProbabilities(block, reference, thread);\r\n\r\n\tfor( uintSeqLen pos = 0; pos < block->coverage_.size(); ++pos ){\r\n\t\t// Set systematic errors and filter out variants\r\n\t\tarray<uintCovCount, 2> errors = {block->coverage_.at(pos).coverage_forward_.at(block->coverage_.at(pos).dom_error_.at(0)), block->coverage_.at(pos).coverage_reverse_.at(block->coverage_.at(pos).dom_error_.at(1))};\r\n\t\tarray<uintCovCount, 2> &coverage = thread.block_coverage_.at(pos);\r\n\t\tif(block->coverage_.at(pos).valid_){\r\n\t\t\tfor(uintTempSeq strand=0; strand < 2; ++strand){\r\n\t\t\t\tif(coverage.at(strand)){\r\n\t\t\t\t\tif( NonSystematicError(coverage.at(strand), errors.at(strand), thread.non_sytematic_probability_.at(pos).at(strand), max_probability_systematic) ){\r\n\t\t\t\t\t\tblock->coverage_.at(pos).dom_error_.at(strand) = 4;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse{\r\n\t\t\t\t\t\tblock->coverage_.at(pos).error_rate_.at(strand) = Percent(errors.at(strand),coverage.at(strand));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif( 4 != block->coverage_.at(pos).dom_error_.at(0) && 4 != block->coverage_.at(pos).dom_error_.at(1) && block->coverage_.at(pos).dom_error_.at(0) == Complement::Dna5(block->coverage_.at(pos).dom_error_.at(1)) ){\r\n\t\t\t\t// Variant not in the vcf file\r\n\t\t\t\tblock->coverage_.at(pos).valid_ = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Store coverage and errors\r\n\t\tUpdateCoverageAtSinglePosition( block->coverage_.at(pos), thread.block_coverage_.at(pos), at(reference.ReferenceSequence(block->sequence_id_), block->start_pos_ + pos) );\r\n\t}\r\n\r\n\t// Save information that is still needed in next_block_\r\n\tif( block->next_block_ && (*(block->next_block_)).sequence_id_ == block->sequence_id_ ){\r\n\t\t// Next block is on the same reference sequence\r\n\t\tuintSeqLen overlap(0);\r\n\t\tif( reset_distance_-1 > (*(block->next_block_)).start_pos_ - (block->start_pos_ + block->coverage_.size()) ){\r\n\t\t\toverlap = BasesWithInSysErrorResetDistance(block);\r\n\t\t}\r\n\r\n\t\tuintSeqLen overlap_start(1);\r\n\t\tif(block->start_pos_+kBlockSize == (*block->next_block_).start_pos_){\r\n\t\t\t// Blocks are directly connected, so reads that are shared between both potentially exist\r\n\t\t\tSetToMax(overlap, 2*maximum_read_length_on_reference_);\r\n\t\t}\r\n\t\telse{\r\n\t\t\t// No shared reads exists as blocks are not connected, only systematic errors have to be propagated taking the gap into account\r\n\t\t\toverlap_start += reset_distance_ - overlap;\r\n\t\t}\r\n\r\n\t\tfor(uintReadLen pos_before = 1; pos_before < overlap_start; ++pos_before){\r\n\t\t\t(*block->next_block_).previous_coverage_.emplace_back(); // Insert dummy as we have a short empty region between the two blocks\r\n\t\t}\r\n\t\tfor(uintReadLen pos_overlap = 1; pos_overlap <= overlap; ++pos_overlap){\r\n\t\t\t(*block->next_block_).previous_coverage_.emplace_back( block->coverage_.at(kBlockSize-pos_overlap) );\r\n\t\t}\r\n\t}\r\n\r\n\tblock->processed_ = true;\r\n}\r\n\r\nvoid CoverageStats::CountBlock(CoverageBlock *block, const Reference &reference){\r\n\t// Enter error_rates_ and dominant_errors_ in forward direction\r\n\tDna5 ref_base, prev_ref_base(4);\r\n\tDominantBase dom_ref_base;\r\n\tif(block->start_pos_){\r\n\t\tprev_ref_base = at(reference.ReferenceSequence(block->sequence_id_), block->start_pos_ - 1);\r\n\t\tdom_ref_base.Set( reference.ReferenceSequence(block->sequence_id_), block->start_pos_ );\r\n\t}\r\n\tuintSeqLen gc_bases = min(block->start_pos_, gc_range_);\r\n\tuintSeqLen n_count(0);\r\n\tuintSeqLen gc = reference.GCContentAbsolut( n_count, block->sequence_id_, block->start_pos_-gc_bases, block->start_pos_);\r\n\r\n\t// Initialize distance and start_rate\r\n\tuintSeqLen distance_to_start_of_error_region_forward(0);\r\n\tuintPercent start_rate_forward(0);\r\n\tif( block->previous_coverage_.size() ){\r\n\t\tfor(auto rev_pos = reset_distance_; --rev_pos; ){ // Index 0 is the one directly before this block, so correct order from low to high reference pos is reverse order in previous_coverage_\r\n\t\t\tUpdateDistances(distance_to_start_of_error_region_forward, start_rate_forward, (block->previous_coverage_.at(rev_pos).valid_ && block->previous_coverage_.at(rev_pos).coverage_sufficient_.at(0)?block->previous_coverage_.at(rev_pos).error_rate_.at(0):0));\r\n\t\t}\r\n\t}\r\n\r\n\tfor( uintSeqLen pos = 0; pos < block->coverage_.size(); ++pos ){\r\n\t\tref_base = at(reference.ReferenceSequence(block->sequence_id_), block->start_pos_ + pos);\r\n\r\n\t\t// Enter values\r\n\t\tif(block->coverage_.at(pos).valid_ && block->coverage_.at(pos).coverage_sufficient_.at(0)){\r\n\t\t\tAddSysError(ref_base, prev_ref_base, dom_ref_base.Get(), block->coverage_.at(pos).dom_error_.at(0), block->coverage_.at(pos).error_rate_.at(0), TransformDistanceToStartOfErrorRegion(distance_to_start_of_error_region_forward), SafePercent(gc,gc_bases-n_count), start_rate_forward);\r\n\t\t}\r\n\r\n\t\t// Set values for next iteration\r\n\t\tprev_ref_base = ref_base;\r\n\t\tdom_ref_base.Update( ref_base, reference.ReferenceSequence(block->sequence_id_), block->start_pos_ + pos);\r\n\t\tUpdateDistances(distance_to_start_of_error_region_forward, start_rate_forward, (block->coverage_.at(pos).valid_ && block->coverage_.at(pos).coverage_sufficient_.at(0)?block->coverage_.at(pos).error_rate_.at(0):0));\r\n\t\tauto new_pos = block->start_pos_ + pos;\r\n\t\tif(gc_bases<gc_range_){\r\n\t\t\t++gc_bases;\r\n\t\t\tif( reference.GC( block->sequence_id_, new_pos ) ){\r\n\t\t\t\t++gc;\r\n\t\t\t}\r\n\t\t\telse if( reference.N( block->sequence_id_, new_pos ) ){\r\n\t\t\t\t++n_count;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse{\r\n\t\t\treference.UpdateGC( gc, n_count, block->sequence_id_, new_pos - gc_bases, new_pos);\r\n\t\t}\r\n\t}\r\n\r\n\t// Enter error_rates_ and dominant_errors_ in reverse direction\r\n\tuintSeqLen last_pos = block->coverage_.size();\r\n\tif( NextBlockWithInSysErrorResetDistance(block) ){\r\n\t\t// Next block is at the same reference sequence and closer than reset_distance: Everything that is potentially in an error region starting in the next block cannot be handled yet\r\n\t\tlast_pos -= BasesWithInSysErrorResetDistance(block);\r\n\t}\r\n\t--last_pos; // Shift it from end pos to last valid pos\r\n\r\n\tConstDna5StringReverseComplement reversed_seq(reference.ReferenceSequence(block->sequence_id_));\r\n\tuintSeqLen ref_pos = reference.SequenceLength(block->sequence_id_) - (block->start_pos_ + last_pos) - 1;\r\n\tdom_ref_base.Clear();\r\n\tif(ref_pos){\r\n\t\tprev_ref_base = at(reversed_seq, ref_pos - 1);\r\n\t\tdom_ref_base.Set( reversed_seq, ref_pos );\r\n\t}\r\n\telse{\r\n\t\tprev_ref_base = 4;\r\n\t}\r\n\tgc_bases = min(ref_pos, gc_range_);\r\n\tn_count = 0;\r\n\tgc = reference.GCContentAbsolut( n_count, block->sequence_id_, block->start_pos_+last_pos + 1, block->start_pos_+last_pos + 1 + gc_bases); // + 1 because we want the bases after first one we handle (previous bases in reverse direction)\r\n\r\n\t// Initialize distance and start_rate\r\n\tuintSeqLen distance_to_start_of_error_region_reverse(0);\r\n\tuintPercent start_rate_reverse(0);\r\n\tfor( uintSeqLen pos = block->coverage_.size(); pos-- > last_pos; ){\r\n\t\tUpdateDistances(distance_to_start_of_error_region_reverse, start_rate_reverse, (block->coverage_.at(pos).valid_ && block->coverage_.at(pos).coverage_sufficient_.at(1)?block->coverage_.at(pos).error_rate_.at(1):0));\r\n\t}\r\n\r\n\tfor( uintSeqLen pos = last_pos+1; pos--; ){\r\n\t\tref_base = at(reversed_seq, ref_pos);\r\n\r\n\t\t// Enter values\r\n\t\tif(block->coverage_.at(pos).valid_ && block->coverage_.at(pos).coverage_sufficient_.at(1)){\r\n\t\t\tAddSysError(ref_base, prev_ref_base, dom_ref_base.Get(), block->coverage_.at(pos).dom_error_.at(1), block->coverage_.at(pos).error_rate_.at(1), TransformDistanceToStartOfErrorRegion(distance_to_start_of_error_region_reverse), SafePercent(gc,gc_bases-n_count), start_rate_reverse);\r\n\t\t}\r\n\r\n\t\t// Set values for next iteration\r\n\t\tprev_ref_base = ref_base;\r\n\t\tdom_ref_base.Update( ref_base, reversed_seq, ref_pos);\r\n\t\tUpdateDistances(distance_to_start_of_error_region_reverse, start_rate_reverse, (block->coverage_.at(pos).valid_ && block->coverage_.at(pos).coverage_sufficient_.at(1)?block->coverage_.at(pos).error_rate_.at(1):0));\r\n\t\tauto new_pos = block->start_pos_+pos;\r\n\t\tif(gc_bases<gc_range_){\r\n\t\t\t++gc_bases;\r\n\t\t\tif( reference.GC( block->sequence_id_, new_pos ) ){\r\n\t\t\t\t++gc;\r\n\t\t\t}\r\n\t\t\telse if( reference.N( block->sequence_id_, new_pos ) ){\r\n\t\t\t\t++n_count;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse{\r\n\t\t\treference.UpdateGC( gc, n_count, block->sequence_id_, new_pos + gc_bases, new_pos);\r\n\t\t}\r\n\t\tref_pos++;\r\n\t}\r\n\r\n\t// Handle values from last block that are not added yet due to the overlap based on reset_distance\r\n\tif( block->previous_coverage_.size() ){\r\n\t\tfor(auto rev_pos = 0; rev_pos < reset_distance_; ++rev_pos){ // Index 0 is the one directly before this block, so correct order from high to low reference pos is normal order in previous_coverage_\r\n\t\t\tref_base = at(reversed_seq, ref_pos);\r\n\r\n\t\t\t// Enter values\r\n\t\t\tif(block->previous_coverage_.at(rev_pos).valid_ && block->previous_coverage_.at(rev_pos).coverage_sufficient_.at(1)){\r\n\t\t\t\tAddSysError(ref_base, prev_ref_base, dom_ref_base.Get(), block->previous_coverage_.at(rev_pos).dom_error_.at(1), block->previous_coverage_.at(rev_pos).error_rate_.at(1), TransformDistanceToStartOfErrorRegion(distance_to_start_of_error_region_reverse), SafePercent(gc,gc_bases-n_count), start_rate_reverse);\r\n\t\t\t}\r\n\r\n\t\t\t// Set values for next iteration\r\n\t\t\tprev_ref_base = ref_base;\r\n\t\t\tdom_ref_base.Update( ref_base, reversed_seq, ref_pos);\r\n\t\t\tUpdateDistances(distance_to_start_of_error_region_reverse, start_rate_reverse, (block->previous_coverage_.at(rev_pos).valid_ && block->previous_coverage_.at(rev_pos).coverage_sufficient_.at(1)?block->previous_coverage_.at(rev_pos).error_rate_.at(1):0));\r\n\t\t\tauto new_pos = block->start_pos_-rev_pos-1;\r\n\t\t\tif(gc_bases<gc_range_){\r\n\t\t\t\t++gc_bases;\r\n\t\t\t\tif( reference.GC( block->sequence_id_, new_pos ) ){\r\n\t\t\t\t\t++gc;\r\n\t\t\t\t}\r\n\t\t\t\telse if( reference.N( block->sequence_id_, new_pos ) ){\r\n\t\t\t\t\t++n_count;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\treference.UpdateGC( gc, n_count, block->sequence_id_, new_pos + gc_bases, new_pos);\r\n\t\t\t}\r\n\t\t\tref_pos++;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nCoverageStats::CoverageBlock *CoverageStats::RemoveBlock(CoverageBlock *block){\r\n\treusable_blocks_.push_back(block);\r\n\r\n\treturn block->next_block_;\r\n}\r\n\r\nvoid CoverageStats::Prepare(uintCovCount average_coverage, uintReadLen average_read_length, uintReadLen maximum_read_length_on_reference){\r\n\treusable_blocks_.reserve(100);\r\n\r\n\tif(coverage_threshold_ > average_coverage/4 ){\r\n\t\tif( 1 < average_coverage/4 ){\r\n\t\t\tcoverage_threshold_ = average_coverage/4; // If half the average coverage is lower than the threshold, so we do not just take the statistics from repeat regions (the coverage per strand is already half the total coverage, so in total we have a quarter)\r\n\t\t}\r\n\t\telse{\r\n\t\t\tcoverage_threshold_ = 1; // Do not set anything without having coverage\r\n\t\t}\r\n\t}\r\n\tgc_range_ = average_read_length/2;\r\n\treset_distance_ = average_read_length;\r\n\r\n\tmaximum_read_length_on_reference_ = maximum_read_length_on_reference;\r\n\r\n\tauto max_error_dist = TransformDistanceToStartOfErrorRegion(reset_distance_-1)+1;\r\n\tfor( auto ref_base=4; ref_base--; ){\r\n\t\tfor( auto prev_ref_base=5; prev_ref_base--; ){\r\n\t\t\tfor( auto dom_base=4; dom_base--; ){\r\n\t\t\t\tSetDimensions( tmp_dominant_errors_by_distance_.at(ref_base).at(prev_ref_base).at(dom_base), max_error_dist, 5 );\r\n\t\t\t\tSetDimensions( tmp_dominant_errors_by_gc_.at(ref_base).at(prev_ref_base).at(dom_base), 101, 5 );\r\n\t\t\t\tSetDimensions( tmp_gc_by_distance_de_.at(ref_base).at(prev_ref_base).at(dom_base), max_error_dist, 101 );\r\n\t\t\t\tSetDimensions( tmp_dominant_errors_by_start_rates_.at(ref_base).at(prev_ref_base).at(dom_base), 101, 5 );\r\n\t\t\t\tSetDimensions( tmp_start_rates_by_distance_de_.at(ref_base).at(prev_ref_base).at(dom_base), max_error_dist, 101 );\r\n\t\t\t\tSetDimensions( tmp_start_rates_by_gc_de_.at(ref_base).at(prev_ref_base).at(dom_base), 101, 101 );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor( auto dom_error=5; dom_error--; ){\r\n\t\t\tSetDimensions( tmp_error_rates_by_distance_.at(ref_base).at(dom_error), max_error_dist, 101 );\r\n\t\t\tSetDimensions( tmp_error_rates_by_gc_.at(ref_base).at(dom_error), 101, 101 );\r\n\t\t\tSetDimensions( tmp_gc_by_distance_er_.at(ref_base).at(dom_error), max_error_dist, 101 );\r\n\t\t\tSetDimensions( tmp_error_rates_by_start_rates_.at(ref_base).at(dom_error), 101, 101 );\r\n\t\t\tSetDimensions( tmp_start_rates_by_distance_er_.at(ref_base).at(dom_error), max_error_dist, 101 );\r\n\t\t\tSetDimensions( tmp_start_rates_by_gc_er_.at(ref_base).at(dom_error), 101, 101 );\r\n\t\t}\r\n\t}\r\n\r\n\t// Setting the size, those aren't atomics\r\n\ttmp_block_error_rate_.resize(101);\r\n\ttmp_block_percent_systematic_.resize(101);\r\n\ttmp_systematic_error_p_values_.resize(kPValueHistBins+1);\r\n\r\n\ttmp_coverage_.resize(kMaxCoverage+1);\r\n\tfor( auto strand=2; strand--; ){\r\n\t\ttmp_coverage_stranded_.at(strand).resize(kMaxCoverage+1);\r\n\t\ttmp_coverage_stranded_percent_.at(strand).resize(101);\r\n\t\ttmp_coverage_stranded_percent_min_cov_10_.at(strand).resize(101);\r\n\t\ttmp_coverage_stranded_percent_min_cov_20_.at(strand).resize(101);\r\n\t}\r\n\ttmp_error_coverage_.resize(kMaxCoverage+1);\r\n\ttmp_error_coverage_percent_.resize(101);\r\n\ttmp_error_coverage_percent_min_cov_10_.resize(101);\r\n\ttmp_error_coverage_percent_min_cov_20_.resize(101);\r\n\tSetDimensions( tmp_error_coverage_percent_stranded_, 101, 101 );\r\n\tSetDimensions( tmp_error_coverage_percent_stranded_min_strand_cov_10_, 101, 101 );\r\n\tSetDimensions( tmp_error_coverage_percent_stranded_min_strand_cov_20_, 101, 101 );\r\n}\r\n\r\n\r\nCoverageStats::CoverageBlock *CoverageStats::FindBlock(uintRefSeqId ref_seq_id, uintSeqLen ref_pos){\r\n\tCoverageBlock *block = last_block_;\r\n\twhile(block->sequence_id_ > ref_seq_id){\r\n\t\tblock = block->previous_block_;\r\n\t}\r\n\twhile(block->start_pos_ > ref_pos){\r\n\t\tblock = block->previous_block_;\r\n\t}\r\n\r\n\treturn block;\r\n}\r\n\r\nbool CoverageStats::EnsureSpace(uintRefSeqId ref_seq_id, uintSeqLen start_pos, uintSeqLen end_pos, FullRecord *record, Reference &reference){\r\n\t// Make sure the variation for the given reference sequence is already loaded\r\n\tif( reference.VariantPositionsLoaded() && !reference.VariantPositionsLoadedForSequence(ref_seq_id) ){\r\n\t\tlock_guard<mutex> lock(variant_loading_mutex_);\r\n\t\tif(!reference.ReadVariantPositions(ref_seq_id+1)){ // End is specified, so to get the current one +1 is needed\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\tSetToMin(end_pos, reference.SequenceLength(ref_seq_id));\r\n\tif( last_block_ ){\r\n\t\t// As reads are ordered by position, we can jump over not covered regions\r\n\t\tif((*last_block_).sequence_id_ < ref_seq_id){\r\n\t\t\t// Account for the not covered region at the end of the last reference sequence\r\n\t\t\tCountEmptyEndOfSequence(reference);\r\n\r\n\t\t\t// Account for the not covered reference sequences in between\r\n\t\t\tfor( auto seq_id = ref_seq_id; --seq_id > (*last_block_).sequence_id_ ; ){\r\n\t\t\t\tzero_coverage_region_ += reference.SequenceLength(seq_id);\r\n\t\t\t\texcluded_bases_ += reference.SumExcludedBases(seq_id);\r\n\t\t\t\tnum_exclusion_regions_ += reference.NumExcludedRegions(seq_id);\r\n\t\t\t}\r\n\r\n\t\t\t// Account for the not covered region in the current reference sequence before the first position\r\n\t\t\tzero_coverage_region_ += start_pos;\r\n\t\t\texcluded_bases_ += reference.SumExcludedBases(ref_seq_id);\r\n\t\t\tnum_exclusion_regions_ += reference.NumExcludedRegions(ref_seq_id);\r\n\r\n\t\t\t// Create first block of next reference sequence\r\n\t\t\tlast_block_ = CreateBlock(ref_seq_id, start_pos);\r\n\t\t\tInitBlock(*last_block_, reference);\r\n\t\t}\r\n\t\telse if((*last_block_).start_pos_+kBlockSize < start_pos){\r\n\t\t\t// Account for the empty coverage region\r\n\t\t\tzero_coverage_region_ += start_pos - (*last_block_).start_pos_ - kBlockSize;\r\n\r\n\t\t\t// Create first block after the empty coverage region\r\n\t\t\tlast_block_ = CreateBlock(ref_seq_id, start_pos);\r\n\t\t\tUpdateFirstVariant(*last_block_, reference);\r\n\t\t\tInitBlock(*last_block_, reference);\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\t// Initialize first block\r\n\t\t// Account for the not covered reference sequences before the first position\r\n\t\tfor( auto seq_id = ref_seq_id; seq_id-- ; ){\r\n\t\t\tzero_coverage_region_ += reference.SequenceLength(seq_id);\r\n\t\t\texcluded_bases_ += reference.SumExcludedBases(seq_id);\r\n\t\t\tnum_exclusion_regions_ += reference.NumExcludedRegions(seq_id);\r\n\t\t}\r\n\r\n\t\t// Account for the not covered region in the current reference sequence before the first position\r\n\t\tzero_coverage_region_ += start_pos;\r\n\t\texcluded_bases_ += reference.SumExcludedBases(ref_seq_id);\r\n\t\tnum_exclusion_regions_ += reference.NumExcludedRegions(ref_seq_id);\r\n\r\n\t\t// Create new block\r\n\t\tauto new_block = new CoverageBlock(ref_seq_id, start_pos, NULL);\r\n\t\tnew_block->coverage_.resize( kBlockSize );\r\n\t\tnew_block->previous_coverage_.reserve(maximum_read_length_on_reference_);\r\n\t\tnew_block->reads_.reserve( 2*kBlockSize );\r\n\t\tInitBlock(*new_block, reference);\r\n\r\n\t\tfirst_block_ = new_block;\r\n\t\tlast_block_ = new_block;\r\n\t}\r\n\r\n\t// Create blocks until end_pos is reached\r\n\twhile((*last_block_).start_pos_+kBlockSize < end_pos){\r\n\t\tlast_block_ = CreateBlock((*last_block_).sequence_id_, (*last_block_).start_pos_+kBlockSize);\r\n\t\tUpdateFirstVariant(*last_block_, reference);\r\n\t\tInitBlock(*last_block_, reference);\r\n\t}\r\n\r\n\t// Add read to last block it potentially overlaps (most of the time it is last_block_, but it is not guaranteed so use FindBlock)\r\n\tauto reg_block = FindBlock(ref_seq_id, end_pos);\r\n\treg_block->reads_.push_back(record);\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid CoverageStats::AddFragment( uintRefSeqId ref_seq_id, uintSeqLen ref_pos, CoverageBlock *&block ){\r\n\tif(block){\r\n\t\twhile( block->start_pos_+kBlockSize <= ref_pos || block->sequence_id_ < ref_seq_id ){\r\n\t\t\tblock = block->next_block_;\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tblock = FindBlock(ref_seq_id, ref_pos);\r\n\t}\r\n\t++(block->unprocessed_fragments_);\r\n}\r\n\r\nvoid CoverageStats::RemoveFragment( uintRefSeqId ref_seq_id, uintSeqLen ref_pos, CoverageBlock *&block, uintFragCount &processed_fragments ){\r\n\tif(block){\r\n\t\tif( block->start_pos_+kBlockSize <= ref_pos || block->sequence_id_ < ref_seq_id ){\r\n\t\t\tauto old_block = block;\r\n\t\t\tdo{\r\n\t\t\t\tblock = block->next_block_;\r\n\t\t\t} while( block->start_pos_+kBlockSize <= ref_pos || block->sequence_id_ < ref_seq_id );\r\n\r\n\t\t\t// Subtract processed_fragments from old_block only after finding the new block, as it potentially allows other threads to remove old_block\r\n\t\t\told_block->unprocessed_fragments_ -= processed_fragments;\r\n\t\t\tprocessed_fragments = 0;\r\n\t\t}\r\n\t\telse if(block->start_pos_ > ref_pos){ // Here we don't need to compare to sequence_id as pairs with reads on different contigs are not added to unprocessed_fragments_\r\n\t\t\t// Here we don't need to care if we set unprocessed_fragments_ to zero before finding the new block, as it is before this block and must have at least one unprocessed_fragments_\r\n\t\t\tblock->unprocessed_fragments_ -= processed_fragments;\r\n\t\t\tprocessed_fragments = 0;\r\n\r\n\t\t\tdo{\r\n\t\t\t\tblock = block->previous_block_;\r\n\t\t\t} while( block->start_pos_ > ref_pos );\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tblock = FindBlock(ref_seq_id, ref_pos);\r\n\t}\r\n\r\n\t++processed_fragments; // Store processed fragments instead of subtracting them directly so that last fragments from this batch can be removed after the CleanUp step, so at least one block remains during CleanUp\r\n}\r\n\r\nreseq::uintRefSeqId CoverageStats::CleanUp(uintSeqLen &still_needed_position, Reference &reference, QualityStats &qualities, ErrorStats &errors, uintQual phred_quality_offset, CoverageBlock *cov_block, uintFragCount &processed_fragments, ThreadData &thread){\r\n\t// Process all blocks that are not needed anymore\r\n\tCoverageBlock *until_block = first_block_;\r\n\twhile(!until_block->unprocessed_fragments_){ // The unprocessed fragments from the current read haven't been removed yet, so end of list cannot be reached\r\n\t\tif( !until_block->scheduled_for_processing_.test_and_set() ){\r\n\t\t\tProcessBlock(until_block, reference, thread);\r\n\t\t}\r\n\r\n\t\tuntil_block = until_block->next_block_;\r\n\t}\r\n\r\n\t// Remove pointers to blocks that are not needed anymore\r\n\tuintRefSeqId still_needed_reference_sequence(0);\r\n\tstill_needed_position = 0;\r\n\t{\r\n\t\tlock_guard<mutex> lock(clean_up_mutex_);\r\n\r\n\t\tuntil_block = first_block_;\r\n\t\twhile(!until_block->unprocessed_fragments_ && until_block->processed_){ // The unprocessed fragments from the current read haven't been removed yet, so end of list cannot be reached\r\n\t\t\tuntil_block = until_block->next_block_;\r\n\t\t\tfirst_block_ = until_block;\r\n\t\t}\r\n\t\tuntil_block = until_block->previous_block_;\r\n\r\n\t\tif(until_block){\r\n\t\t\t(*first_block_).previous_block_ = NULL;\r\n\t\t\tuntil_block->next_block_ = NULL;\r\n\t\t\tstill_needed_reference_sequence = (*first_block_).sequence_id_;\r\n\t\t\tstill_needed_position = (*first_block_).start_pos_;\r\n\t\t}\r\n\t}\r\n\r\n\t// Subtract processed_fragments from cov_block after until_block is determined, as it potentially allows to remove cov_block\r\n\tcov_block->unprocessed_fragments_ -= processed_fragments;\r\n\tprocessed_fragments = 0;\r\n\r\n\t// Count and remove blocks, where we removed the pointers before\r\n\tif(until_block){\r\n\t\twhile(until_block->previous_block_){\r\n\t\t\tCountBlock(until_block, reference);\r\n\t\t\tfor( auto rec : until_block->reads_){\r\n\t\t\t\tEvalRead(rec, until_block, reference, qualities, errors, phred_quality_offset);\r\n\t\t\t}\r\n\t\t\tuntil_block = until_block->previous_block_;\r\n\t\t}\r\n\r\n\t\tCountBlock(until_block, reference);\r\n\t\tfor( auto rec : until_block->reads_){\r\n\t\t\tEvalRead(rec, until_block, reference, qualities, errors, phred_quality_offset);\r\n\t\t}\r\n\r\n\t\tlock_guard<mutex> lock(reuse_mutex_);\r\n\t\tdo{\r\n\t\t\tuntil_block = RemoveBlock(until_block);\r\n\t\t} while(until_block);\r\n\t}\r\n\r\n\treference.ClearVariants(still_needed_reference_sequence);\r\n\r\n\treturn still_needed_reference_sequence;\r\n}\r\n\r\nbool CoverageStats::PreLoadVariants(Reference &reference){\r\n\tif(reference.VariantPositionsLoaded() && !reference.VariantPositionsCompletelyLoaded() && !reference.VariantPositionsLoadedForSequence((*last_block_).sequence_id_+2)){\r\n\t\tif( variant_loading_mutex_.try_lock() ){\r\n\t\t\tif( !reference.ReadVariantPositions((*last_block_).sequence_id_+2) ){\r\n\t\t\t\tvariant_loading_mutex_.unlock();\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tvariant_loading_mutex_.unlock();\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nbool CoverageStats::Finalize(const Reference &reference, QualityStats &qualities, ErrorStats &errors, uintQual phred_quality_offset, mutex &print_mutex, ThreadData &thread){\r\n\t// Remove all reusable_blocks_ as they are not needed anymore\r\n\tfor( auto block : reusable_blocks_ ){\r\n\t\tdelete block;\r\n\t}\r\n\tauto final_num_blocks = reusable_blocks_.size();\r\n\treusable_blocks_.clear();\r\n\r\n\tif(first_block_){\r\n\t\tif( last_block_ ){\r\n\t\t\t// Update not covered regions after last block\r\n\t\t\tCountEmptyEndOfSequence(reference);\r\n\r\n\t\t\tfor( auto seq_id = (*last_block_).sequence_id_+1; seq_id < reference.NumberSequences(); ++seq_id ){\r\n\t\t\t\tzero_coverage_region_ += reference.SequenceLength(seq_id);\r\n\t\t\t\texcluded_bases_ += reference.SumExcludedBases(seq_id);\r\n\t\t\t\tnum_exclusion_regions_ += reference.NumExcludedRegions(seq_id);\r\n\t\t\t}\r\n\r\n\t\t\t// Update coverage of remaining blocks and delete them\r\n\t\t\tCoverageBlock *first_block = first_block_; // Use non atomic pointer for the finalization\r\n\t\t\tfirst_block_ = NULL;\r\n\t\t\tlast_block_ = NULL;\r\n\r\n\t\t\twhile(first_block->next_block_){\r\n\t\t\t\t++final_num_blocks;\r\n\t\t\t\tProcessBlock(first_block, reference, thread);\r\n\t\t\t\tCountBlock(first_block, reference);\r\n\t\t\t\tfor( auto rec : first_block->reads_){\r\n\t\t\t\t\tEvalRead(rec, first_block, reference, qualities, errors, phred_quality_offset);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfirst_block = first_block->next_block_;\r\n\t\t\t\tdelete first_block->previous_block_;\r\n\t\t\t}\r\n\r\n\t\t\t++final_num_blocks;\r\n\t\t\tProcessBlock(first_block, reference, thread);\r\n\t\t\tCountBlock(first_block, reference);\r\n\t\t\tfor( auto rec : first_block->reads_){\r\n\t\t\t\tEvalRead(rec, first_block, reference, qualities, errors, phred_quality_offset);\r\n\t\t\t}\r\n\t\t\tdelete first_block;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tprintErr << \"first_block_ set, but last_block_ not. Something dodgy is going on here\" << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tif( last_block_ ){\r\n\t\t\tprintErr << \"last_block_ set, but first_block_ not. Something dodgy is going on here\" << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\telse{\r\n\t\t\t// There have been reads in the file (or Finalize wouldn't have been called), but none made the criteria to add coverage\r\n\t\t\tSetAllZero(reference);\r\n\t\t}\r\n\t}\r\n\r\n\t{\r\n\t\tlock_guard<mutex> lock(print_mutex);\r\n\t\tprintInfo << \"Needed to create \" << final_num_blocks << \" coverage blocks.\" << std::endl;\r\n\t\tauto total_size = reference.TotalSize();\r\n\t\tprintInfo << \"Excluded \" << excluded_bases_ << \" of \" << total_size << \" bases [\" << static_cast<uintPercentPrint>(Percent(excluded_bases_, total_size)) << \"%] in the reference due to contig ends and N's over \" << num_exclusion_regions_ << \" regions.\" << std::endl;\r\n\t}\r\n\r\n\tApplyZeroCoverageRegion();\r\n\r\n\tfor( auto ref_base=4; ref_base--; ){\r\n\t\tfor( auto prev_ref_base=5; prev_ref_base--; ){\r\n\t\t\tfor( auto dom_base=4; dom_base--; ){\r\n\t\t\t\tdominant_errors_by_distance_.at(ref_base).at(prev_ref_base).at(dom_base).Acquire( tmp_dominant_errors_by_distance_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t\tdominant_errors_by_gc_.at(ref_base).at(prev_ref_base).at(dom_base).Acquire( tmp_dominant_errors_by_gc_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t\tgc_by_distance_de_.at(ref_base).at(prev_ref_base).at(dom_base).Acquire( tmp_gc_by_distance_de_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t\tdominant_errors_by_start_rates_.at(ref_base).at(prev_ref_base).at(dom_base).Acquire( tmp_dominant_errors_by_start_rates_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t\tstart_rates_by_distance_de_.at(ref_base).at(prev_ref_base).at(dom_base).Acquire( tmp_start_rates_by_distance_de_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t\tstart_rates_by_gc_de_.at(ref_base).at(prev_ref_base).at(dom_base).Acquire( tmp_start_rates_by_gc_de_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor( auto dom_error=5; dom_error--; ){\r\n\t\t\terror_rates_by_distance_.at(ref_base).at(dom_error).Acquire( tmp_error_rates_by_distance_.at(ref_base).at(dom_error) );\r\n\t\t\terror_rates_by_gc_.at(ref_base).at(dom_error).Acquire( tmp_error_rates_by_gc_.at(ref_base).at(dom_error) );\r\n\t\t\tgc_by_distance_er_.at(ref_base).at(dom_error).Acquire( tmp_gc_by_distance_er_.at(ref_base).at(dom_error) );\r\n\t\t\terror_rates_by_start_rates_.at(ref_base).at(dom_error).Acquire( tmp_error_rates_by_start_rates_.at(ref_base).at(dom_error) );\r\n\t\t\tstart_rates_by_distance_er_.at(ref_base).at(dom_error).Acquire( tmp_start_rates_by_distance_er_.at(ref_base).at(dom_error) );\r\n\t\t\tstart_rates_by_gc_er_.at(ref_base).at(dom_error).Acquire( tmp_start_rates_by_gc_er_.at(ref_base).at(dom_error) );\r\n\t\t}\r\n\t}\r\n\r\n\tblock_error_rate_.Acquire( tmp_block_error_rate_ );\r\n\tblock_percent_systematic_.Acquire( tmp_block_percent_systematic_ );\r\n\ttmp_systematic_error_p_values_.at(kPValueHistBins-1) += tmp_systematic_error_p_values_.at(kPValueHistBins); // Last bin only contains p-values of exactly 1.0, so merge it with the one before\r\n\ttmp_systematic_error_p_values_.at(kPValueHistBins) = 0;\r\n\tsystematic_error_p_values_.Acquire( tmp_systematic_error_p_values_ );\r\n\r\n\tcoverage_.Acquire( tmp_coverage_ );\r\n\tfor( auto strand=2; strand--; ){\r\n\t\tcoverage_stranded_.at(strand).Acquire( tmp_coverage_stranded_.at(strand) );\r\n\t\tcoverage_stranded_percent_.at(strand).Acquire( tmp_coverage_stranded_percent_.at(strand) );\r\n\t\tcoverage_stranded_percent_min_cov_10_.at(strand).Acquire( tmp_coverage_stranded_percent_min_cov_10_.at(strand) );\r\n\t\tcoverage_stranded_percent_min_cov_20_.at(strand).Acquire( tmp_coverage_stranded_percent_min_cov_20_.at(strand) );\r\n\t}\r\n\terror_coverage_.Acquire( tmp_error_coverage_ );\r\n\terror_coverage_percent_.Acquire( tmp_error_coverage_percent_ );\r\n\terror_coverage_percent_min_cov_10_.Acquire( tmp_error_coverage_percent_min_cov_10_ );\r\n\terror_coverage_percent_min_cov_20_.Acquire( tmp_error_coverage_percent_min_cov_20_ );\r\n\terror_coverage_percent_stranded_.Acquire( tmp_error_coverage_percent_stranded_ );\r\n\terror_coverage_percent_stranded_min_strand_cov_10_.Acquire( tmp_error_coverage_percent_stranded_min_strand_cov_10_ );\r\n\terror_coverage_percent_stranded_min_strand_cov_20_.Acquire( tmp_error_coverage_percent_stranded_min_strand_cov_20_ );\r\n\r\n\treturn true;\r\n}\r\n\r\nvoid CoverageStats::Shrink(){\r\n\tfor( auto ref_base=4; ref_base--; ){\r\n\t\tfor( auto prev_ref_base=5; prev_ref_base--; ){\r\n\t\t\tfor( auto dom_base=4; dom_base--; ){\r\n\t\t\t\tShrinkVect( dominant_errors_by_distance_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t\tShrinkVect( dominant_errors_by_gc_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t\tShrinkVect( gc_by_distance_de_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t\tShrinkVect( dominant_errors_by_start_rates_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t\tShrinkVect( start_rates_by_distance_de_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t\tShrinkVect( start_rates_by_gc_de_.at(ref_base).at(prev_ref_base).at(dom_base) );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor( auto dom_error=5; dom_error--; ){\r\n\t\t\tShrinkVect( error_rates_by_distance_.at(ref_base).at(dom_error) );\r\n\t\t\tShrinkVect( error_rates_by_gc_.at(ref_base).at(dom_error) );\r\n\t\t\tShrinkVect( gc_by_distance_er_.at(ref_base).at(dom_error) );\r\n\t\t\tShrinkVect( error_rates_by_start_rates_.at(ref_base).at(dom_error) );\r\n\t\t\tShrinkVect( start_rates_by_distance_er_.at(ref_base).at(dom_error) );\r\n\t\t\tShrinkVect( start_rates_by_gc_er_.at(ref_base).at(dom_error) );\r\n\t\t}\r\n\t}\r\n\r\n\tShrinkVect( error_coverage_percent_stranded_ );\r\n\tShrinkVect( error_coverage_percent_stranded_min_strand_cov_10_ );\r\n\tShrinkVect( error_coverage_percent_stranded_min_strand_cov_20_ );\r\n}\r\n\r\nvoid CoverageStats::PreparePlotting(){\r\n\terror_rates_by_distance_sum_.Clear();\r\n\terror_rates_by_gc_sum_.Clear();\r\n\tfor( int ref_base=4; ref_base--; ){\r\n\t\tfor( int dom_error=5; dom_error--; ){\r\n\t\t\terror_rates_by_distance_sum_ += error_rates_by_distance_.at(ref_base).at(dom_error);\r\n\t\t\terror_rates_by_gc_sum_ += error_rates_by_gc_.at(ref_base).at(dom_error);\r\n\t\t}\r\n\t}\r\n}\r\n", "meta": {"hexsha": "63d5ade4f63f04922ad151ccf9c30a6b34145089", "size": 49541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "reseq/CoverageStats.cpp", "max_stars_repo_name": "schmeing/ReSeq", "max_stars_repo_head_hexsha": "053b8d1af635bf0019dc818b3eb0825023abd037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 29.0, "max_stars_repo_stars_event_min_datetime": "2020-07-18T22:04:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T16:48:53.000Z", "max_issues_repo_path": "reseq/CoverageStats.cpp", "max_issues_repo_name": "schmeing/ReSeq", "max_issues_repo_head_hexsha": "053b8d1af635bf0019dc818b3eb0825023abd037", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2020-08-03T18:10:44.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-03T12:52:16.000Z", "max_forks_repo_path": "reseq/CoverageStats.cpp", "max_forks_repo_name": "schmeing/ReSequenceR", "max_forks_repo_head_hexsha": "053b8d1af635bf0019dc818b3eb0825023abd037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-03-08T15:09:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-25T14:14:43.000Z", "avg_line_length": 45.2016423358, "max_line_length": 311, "alphanum_fraction": 0.7365414505, "num_tokens": 12810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.38121956625615, "lm_q1q2_score": 0.20990230106678576}}
{"text": "#ifndef VEXCL_MBA_HPP\n#define VEXCL_MBA_HPP\n\n/*\nThe MIT License\n\nCopyright (c) 2012-2018 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n/**\n * \\file   vexcl/mba.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief  Scattered data interpolation with multilevel B-Splines.\n */\n\n#include <vector>\n#include <array>\n#include <sstream>\n#include <memory>\n#include <algorithm>\n#include <numeric>\n#include <type_traits>\n#include <cassert>\n\n#include <boost/tuple/tuple.hpp>\n#include <boost/fusion/adapted/boost_tuple.hpp>\n\n#include <vexcl/operations.hpp>\n\n// Include boost.preprocessor header if variadic templates are not available.\n// Also include it if we use gcc v4.6.\n// This is required due to bug http://gcc.gnu.org/bugzilla/show_bug.cgi?id=35722\n#if defined(BOOST_NO_VARIADIC_TEMPLATES) || (defined(__GNUC__) && !defined(__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ == 6)\n#  include <boost/preprocessor/repetition.hpp>\n#  ifndef VEXCL_MAX_ARITY\n#    define VEXCL_MAX_ARITY BOOST_PROTO_MAX_ARITY\n#  endif\n#endif\nnamespace vex {\n\nstruct mba_terminal {};\n\ntypedef vector_expression<\n    typename boost::proto::terminal< mba_terminal >::type\n    > mba_terminal_expression;\n\ntemplate <class MBA, class ExprTuple>\nstruct mba_interp : public mba_terminal_expression {\n    typedef typename MBA::value_type value_type;\n\n    const MBA      &cloud;\n    const ExprTuple coord;\n\n    mba_interp(const MBA &cloud, const ExprTuple coord)\n        : cloud(cloud), coord(coord) {}\n};\n\nnamespace detail {\n    // Compile time value of N^M.\n    template <size_t N, size_t M>\n    struct power : std::integral_constant<size_t, N * power<N, M-1>::value> {};\n\n    template <size_t N>\n    struct power<N, 0> : std::integral_constant<size_t, 1> {};\n\n    // Nested loop counter of compile-time size (M loops of size N).\n    template <size_t N, size_t M>\n    class scounter {\n        public:\n            scounter() : idx(0) {\n                std::fill(i.begin(), i.end(), static_cast<size_t>(0));\n            }\n\n            size_t operator[](size_t d) const {\n                return i[d];\n            }\n\n            scounter& operator++() {\n                for(size_t d = M; d--; ) {\n                    if (++i[d] < N) break;\n                    i[d] = 0;\n                }\n\n                ++idx;\n\n                return *this;\n            }\n\n            operator size_t() const {\n                return idx;\n            }\n\n            bool valid() const {\n                return idx < power<N, M>::value;\n            }\n        private:\n            size_t idx;\n            std::array<size_t, M> i;\n    };\n\n    // Nested loop counter of run-time size (M loops of given sizes).\n    template <size_t M>\n    class dcounter {\n        public:\n            dcounter(const std::array<size_t, M> &N)\n                : idx(0),\n                  size(std::accumulate(N.begin(), N.end(),\n                            static_cast<size_t>(1), std::multiplies<size_t>())),\n                  N(N)\n            {\n                std::fill(i.begin(), i.end(), static_cast<size_t>(0));\n            }\n\n            size_t operator[](size_t d) const {\n                return i[d];\n            }\n\n            dcounter& operator++() {\n                for(size_t d = M; d--; ) {\n                    if (++i[d] < N[d]) break;\n                    i[d] = 0;\n                }\n\n                ++idx;\n\n                return *this;\n            }\n\n            operator size_t() const {\n                return idx;\n            }\n\n            bool valid() const {\n                return idx < size;\n            }\n        private:\n            size_t idx, size;\n            std::array<size_t, M> N, i;\n    };\n} // namespace detail\n\n/// Scattered data interpolation with multilevel B-Splines.\ntemplate <size_t NDIM, typename real = double>\nclass mba {\n    public:\n        typedef real value_type;\n        typedef std::array<real,   NDIM> point;\n        typedef std::array<size_t, NDIM> index;\n\n        static const size_t ndim = NDIM;\n\n        std::vector< backend::command_queue >       queue;\n        std::vector< backend::device_vector<real> > phi;\n        point xmin, hinv;\n        index n, stride;\n\n        /** Creates the approximation functor.\n         * `cmin` and `cmax` specify the domain boundaries, `coo` and `val`\n         * contain coordinates and values of the data points. `grid` is the\n         * initial control grid size. The approximation hierarchy will have at\n         * most `levels` and will stop when the desired approximation precision\n         * `tol` will be reached.\n         */\n        mba(\n                const std::vector<backend::command_queue> &queue,\n                const point &cmin, const point &cmax,\n                const std::vector<point> &coo, std::vector<real> val,\n                std::array<size_t, NDIM> grid, size_t levels = 8, real tol = 1e-8\n           ) : queue(queue)\n        {\n            init(cmin, cmax, coo.begin(), coo.end(), val.begin(), grid, levels, tol);\n        }\n\n        /** Creates the approximation functor.\n         * `cmin` and `cmax` specify the domain boundaries. Coordinates and\n         * values of the data points are passed as iterator ranges. `grid` is\n         * the initial control grid size. The approximation hierarchy will have\n         * at most `levels` and will stop when the desired approximation\n         * precision `tol` will be reached.\n         */\n        template <class CooIter, class ValIter>\n        mba(\n                const std::vector<backend::command_queue> &queue,\n                const point &cmin, const point &cmax,\n                CooIter coo_begin, CooIter coo_end, ValIter val_begin,\n                std::array<size_t, NDIM> grid, size_t levels = 8, real tol = 1e-8\n           ) : queue(queue)\n        {\n            init(cmin, cmax, coo_begin, coo_end, val_begin, grid, levels, tol);\n        }\n\n#if !defined(BOOST_NO_VARIADIC_TEMPLATES) && ((!defined(__GNUC__) || (__GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ > 6)) || defined(__clang__))\n        /// Provide interpolated values at given coordinates.\n        template <class... Expr>\n        auto operator()(const Expr&... expr) const ->\n            mba_interp< mba, boost::tuple<const Expr&...> >\n        {\n            static_assert(sizeof...(Expr) == NDIM, \"Wrong number of parameters\");\n            return mba_interp< mba, boost::tuple<const Expr&...> >(*this, boost::tie(expr...));\n        }\n#else\n\n#define VEXCL_FUNCALL_OPERATOR(z, n, data)                                     \\\n  template <BOOST_PP_ENUM_PARAMS(n, class Expr)>                               \\\n  mba_interp<mba, boost::tuple<BOOST_PP_ENUM_BINARY_PARAMS(                    \\\n                      n, const Expr, &BOOST_PP_INTERCEPT)> >                   \\\n  operator()(BOOST_PP_ENUM_BINARY_PARAMS(n, const Expr, &expr)) {              \\\n    return mba_interp<mba, boost::tuple<BOOST_PP_ENUM_BINARY_PARAMS(           \\\n                               n, const Expr, &BOOST_PP_INTERCEPT)> >(         \\\n        *this, boost::tie(BOOST_PP_ENUM_PARAMS(n, expr)));                     \\\n  }\n\nBOOST_PP_REPEAT_FROM_TO(1, 10, VEXCL_FUNCALL_OPERATOR, ~)\n\n#undef VEXCL_FUNCALL_OPERATOR\n#endif\n    private:\n        template <class CooIter, class ValIter>\n        void init(\n                const point &cmin, const point &cmax,\n                CooIter coo_begin, CooIter coo_end, ValIter val_begin,\n                std::array<size_t, NDIM> grid, size_t levels = 8, real tol = 1e-8\n                )\n        {\n            for(size_t k = 0; k < NDIM; ++k)\n                assert(grid[k] > 1);\n\n            double res0 = std::accumulate(\n                    val_begin, val_begin + (coo_end - coo_begin),\n                    static_cast<real>(0),\n                    [](real sum, real v) { return sum + v * v; }\n                    );\n\n            std::unique_ptr<lattice> psi(\n                    new lattice(cmin, cmax, grid, coo_begin, coo_end, val_begin)\n                    );\n            double res = psi->update_data(coo_begin, coo_end, val_begin);\n#ifdef VEXCL_MBA_VERBOSE\n            std::cout << \"level  0: res = \" << std::scientific << res << std::endl;\n#endif\n\n            for (size_t k = 1; (res > res0 * tol) && (k < levels); ++k) {\n                for(size_t d = 0; d < NDIM; ++d) grid[d] = 2 * grid[d] - 1;\n\n                std::unique_ptr<lattice> f(\n                        new lattice(cmin, cmax, grid, coo_begin, coo_end, val_begin)\n                        );\n                res = f->update_data(coo_begin, coo_end, val_begin);\n#ifdef VEXCL_MBA_VERBOSE\n                std::cout << \"level \" << k << std::scientific << \": res = \" << res << std::endl;\n#endif\n\n                f->append_refined(*psi);\n                psi = std::move(f);\n            }\n\n            xmin   = psi->xmin;\n            hinv   = psi->hinv;\n            n      = psi->n;\n            stride = psi->stride;\n\n            phi.reserve(queue.size());\n\n            for(auto q = queue.begin(); q != queue.end(); ++q)\n                phi.push_back( backend::device_vector<real>(\n                            *q, psi->phi.size(), psi->phi.data(), backend::MEM_READ_ONLY\n                            ) );\n        }\n\n        // Control lattice.\n        struct lattice {\n            point xmin, hinv;\n            index n, stride;\n            std::vector<real> phi;\n\n            template <class CooIter, class ValIter>\n            lattice(\n                    const point &cmin, const point &cmax, std::array<size_t, NDIM> grid,\n                    CooIter coo_begin, CooIter coo_end, ValIter val_begin\n                   ) : xmin(cmin), n(grid)\n            {\n                for(size_t d = 0; d < NDIM; ++d) {\n                    hinv[d] = (grid[d] - 1) / (cmax[d] - cmin[d]);\n                    xmin[d] -= 1 / hinv[d];\n                    n[d]    += 2;\n                }\n\n                stride[NDIM - 1] = 1;\n                for(size_t d = NDIM - 1; d--; )\n                    stride[d] = stride[d + 1] * n[d + 1];\n\n                std::vector<real> delta(n[0] * stride[0], 0.0);\n                std::vector<real> omega(n[0] * stride[0], 0.0);\n\n                auto p = coo_begin;\n                auto v = val_begin;\n                for(; p != coo_end; ++p, ++v) {\n                    if (!contained(cmin, cmax, *p)) continue;\n\n                    index i;\n                    point s;\n\n                    for(size_t d = 0; d < NDIM; ++d) {\n                        real u = ((*p)[d] - xmin[d]) * hinv[d];\n                        i[d] = static_cast<size_t>(std::floor(u) - 1);\n                        s[d] = u - std::floor(u);\n                    }\n\n                    std::array<real, detail::power<4, NDIM>::value> w;\n                    real sw2 = 0;\n\n                    for(detail::scounter<4, NDIM> d; d.valid(); ++d) {\n                        real buf = 1;\n                        for(size_t k = 0; k < NDIM; ++k)\n                            buf *= B(d[k], s[k]);\n\n                        w[d] = buf;\n                        sw2 += buf * buf;\n                    }\n\n                    for(detail::scounter<4, NDIM> d; d.valid(); ++d) {\n                        real phi = (*v) * w[d] / sw2;\n\n                        size_t idx = 0;\n                        for(size_t k = 0; k < NDIM; ++k) {\n                            assert(i[k] + d[k] < n[k]);\n\n                            idx += (i[k] + d[k]) * stride[k];\n                        }\n\n                        real w2 = w[d] * w[d];\n\n                        assert(idx < delta.size());\n\n                        delta[idx] += w2 * phi;\n                        omega[idx] += w2;\n                    }\n                }\n\n                phi.resize(omega.size());\n\n                for(auto w = omega.begin(), d = delta.begin(), f = phi.begin();\n                        w != omega.end();\n                        ++w, ++d, ++f\n                   )\n                {\n                    if (std::fabs(*w) < 1e-32)\n                        *f = 0;\n                    else\n                        *f = (*d) / (*w);\n                }\n            }\n\n            // Get interpolated value at given position.\n            real operator()(const point &p) const {\n                index i;\n                point s;\n\n                for(size_t d = 0; d < NDIM; ++d) {\n                    real u = (p[d] - xmin[d]) * hinv[d];\n                    i[d] = static_cast<size_t>(std::floor(u) - 1);\n                    s[d] = u - std::floor(u);\n                }\n\n                real f = 0;\n\n                for(detail::scounter<4, NDIM> d; d.valid(); ++d) {\n                    real w = 1;\n                    for(size_t k = 0; k < NDIM; ++k)\n                        w *= B(d[k], s[k]);\n\n                    f += w * get(i, d);\n                }\n\n                return f;\n            }\n\n            // Subtract interpolated values from data points.\n            template <class CooIter, class ValIter>\n            real update_data(\n                    CooIter coo_begin, CooIter coo_end, ValIter val_begin\n                    ) const\n            {\n                auto c = coo_begin;\n                auto v = val_begin;\n\n                real res = 0;\n\n                for(; c != coo_end; ++c, ++v) {\n                    *v -= (*this)(*c);\n\n                    res += (*v) * (*v);\n                }\n\n                return res;\n            }\n\n            // Refine r and append it to the current control lattice.\n            void append_refined(const lattice &r) {\n                static const std::array<real, 5> s = {{\n                    0.125, 0.500, 0.750, 0.500, 0.125\n                }};\n\n                for(detail::dcounter<NDIM> i(r.n); i.valid(); ++i) {\n                    real f = r.phi[i];\n                    for(detail::scounter<5, NDIM> d; d.valid(); ++d) {\n                        index j;\n                        bool skip = false;\n                        size_t idx = 0;\n                        for(size_t k = 0; k < NDIM; ++k) {\n                            j[k] = 2 * i[k] + d[k] - 3;\n                            if (j[k] >= n[k]) { skip = true; break; }\n\n                            idx += j[k] * stride[k];\n                        }\n\n                        if (skip) continue;\n\n                        real c = 1;\n                        for(size_t k = 0; k < NDIM; ++k) c *= s[d[k]];\n\n                        phi[idx] += f * c;\n                    }\n                }\n            }\n\n            private:\n                // Value of k-th B-Spline at t.\n                static inline real B(size_t k, real t) {\n                    assert(0 <= t && t < 1);\n                    assert(k < 4);\n\n                    switch (k) {\n                        case 0:\n                            return (t * (t * (-t + 3) - 3) + 1) / 6;\n                        case 1:\n                            return (t * t * (3 * t - 6) + 4) / 6;\n                        case 2:\n                            return (t * (t * (-3 * t + 3) + 3) + 1) / 6;\n                        case 3:\n                        default:\n                            return t * t * t / 6;\n                    }\n                }\n\n                // x is within [xmin, xmax].\n                static bool contained(\n                        const point &xmin, const point &xmax, const point &x)\n                {\n                    for(size_t d = 0; d < NDIM; ++d) {\n                        static const real eps = 1e-12;\n\n                        if (x[d] - eps <  xmin[d]) return false;\n                        if (x[d] + eps >= xmax[d]) return false;\n                    }\n\n                    return true;\n                }\n\n                // Get value of phi at index (i + d).\n                template <class Shift>\n                inline real get(const index &i, const Shift &d) const {\n                    size_t idx = 0;\n\n                    for(size_t k = 0; k < NDIM; ++k) {\n                        size_t j = i[k] + d[k];\n\n                        if (j >= n[k]) return 0;\n                        idx += j * stride[k];\n                    }\n\n                    return phi[idx];\n                }\n        };\n};\n\nnamespace traits {\n\ntemplate <>\nstruct is_vector_expr_terminal< mba_terminal > : std::true_type {};\n\ntemplate <>\nstruct proto_terminal_is_value< mba_terminal > : std::true_type {};\n\ntemplate <class MBA, class ExprTuple>\nstruct terminal_preamble< mba_interp<MBA, ExprTuple> > {\n    static void get(backend::source_generator &src,\n            const mba_interp<MBA, ExprTuple>&,\n            const backend::command_queue&, const std::string &prm_name,\n            detail::kernel_generator_state_ptr)\n    {\n        typedef typename MBA::value_type real;\n\n        std::string B = prm_name + \"_B\";\n\n        src.begin_function<real>(B + \"0\");\n        src.begin_function_parameters();\n        src.template parameter<real>(\"t\");\n        src.end_function_parameters();\n        src.new_line() << \"return (t * (t * (-t + 3) - 3) + 1) / 6;\";\n        src.end_function();\n\n        src.begin_function<real>(B + \"1\");\n        src.begin_function_parameters();\n        src.template parameter<real>(\"t\");\n        src.end_function_parameters();\n        src.new_line() << \"return (t * t * (3 * t - 6) + 4) / 6;\";\n        src.end_function();\n\n        src.begin_function<real>(B + \"2\");\n        src.begin_function_parameters();\n        src.template parameter<real>(\"t\");\n        src.end_function_parameters();\n        src.new_line() << \"return (t * (t * (-3 * t + 3) + 3) + 1) / 6;\";\n        src.end_function();\n\n        src.begin_function<real>(B + \"3\");\n        src.begin_function_parameters();\n        src.template parameter<real>(\"t\");\n        src.end_function_parameters();\n        src.new_line() << \"return t * t * t / 6;\";\n        src.end_function();\n\n        src.begin_function<real>(prm_name + \"_mba\");\n        src.begin_function_parameters();\n\n        for(size_t k = 0; k < MBA::ndim; ++k)\n            src.template parameter<real>(\"x\") << k;\n\n        for(size_t k = 0; k < MBA::ndim; ++k) {\n            src.template parameter<real>(\"c\" + std::to_string(k));\n            src.template parameter<real>(\"h\" + std::to_string(k));\n            src.parameter<size_t>(\"n\" + std::to_string(k));\n            src.parameter<size_t>(\"m\" + std::to_string(k));\n        }\n\n        src.template parameter< global_ptr<const real> >(\"phi\");\n        src.end_function_parameters();\n        src.new_line() << type_name<real>() << \" u;\";\n        for(size_t k = 0; k < MBA::ndim; ++k) {\n            src.new_line() << \"u = (x\" << k << \" - c\" << k << \") * h\" << k << \";\";\n            src.new_line() << type_name<size_t>() << \" i\" << k << \" = floor(u) - 1;\";\n            src.new_line() << type_name<real>() << \" s\" << k << \" = u - floor(u);\";\n        }\n        src.new_line() << type_name<real>() << \" f = 0;\";\n        src.new_line() << type_name<size_t>() << \" j, idx;\";\n\n        for(detail::scounter<4,MBA::ndim> d; d.valid(); ++d) {\n            src.new_line() << \"idx = 0;\";\n            for(size_t k = 0; k < MBA::ndim; ++k) {\n                src.new_line() << \"j = i\" << k << \" + \" << d[k] << \";\";\n                src.new_line() << \"if (j < n\" << k << \")\";\n                src.open(\"{\").new_line() << \"idx += j * m\" << k << \";\";\n            }\n\n            src.new_line() << \"f += \";\n            for(size_t k = 0; k < MBA::ndim; ++k) {\n                if (k) src << \" * \";\n                src << B << d[k] << \"(s\" << k << \")\";\n            }\n\n            src << \" * phi[idx];\";\n\n            for(size_t k = 0; k < MBA::ndim; ++k)\n                src.close(\"}\");\n        }\n        src.new_line() << \"return f;\";\n        src.end_function();\n    }\n};\n\ntemplate <class MBA, class ExprTuple>\nstruct kernel_param_declaration< mba_interp<MBA, ExprTuple> > {\n    static void get(backend::source_generator &src,\n            const mba_interp<MBA, ExprTuple> &term,\n            const backend::command_queue &queue, const std::string &prm_name,\n            detail::kernel_generator_state_ptr state)\n    {\n        typedef typename MBA::value_type real;\n        boost::fusion::for_each(term.coord, prmdecl(src, queue, prm_name, state));\n\n        for(size_t k = 0; k < MBA::ndim; ++k) {\n            src.template parameter<real>(prm_name + \"_c\" + std::to_string(k));\n            src.template parameter<real>(prm_name + \"_h\" + std::to_string(k));\n            src.parameter<size_t>(prm_name + \"_n\" + std::to_string(k));\n            src.parameter<size_t>(prm_name + \"_m\" + std::to_string(k));\n        }\n\n        src.parameter< global_ptr<const real> >(prm_name + \"_phi\");\n    }\n\n    struct prmdecl {\n        backend::source_generator &s;\n        const backend::command_queue &queue;\n        const std::string &prm_name;\n        detail::kernel_generator_state_ptr state;\n        mutable int pos;\n\n        prmdecl(backend::source_generator &s,\n                const backend::command_queue &queue, const std::string &prm_name,\n                detail::kernel_generator_state_ptr state\n            ) : s(s), queue(queue), prm_name(prm_name), state(state), pos(0)\n        {}\n\n        template <class Expr>\n        void operator()(const Expr &expr) const {\n            std::ostringstream prefix;\n            prefix << prm_name << \"_x\" << pos;\n            detail::declare_expression_parameter ctx(s, queue, prefix.str(), state);\n            detail::extract_terminals()(boost::proto::as_child(expr), ctx);\n\n            pos++;\n        }\n    };\n};\n\ntemplate <class MBA, class ExprTuple>\nstruct local_terminal_init< mba_interp<MBA, ExprTuple> > {\n    static void get(backend::source_generator &src,\n            const mba_interp<MBA, ExprTuple> &term,\n            const backend::command_queue &queue, const std::string &prm_name,\n            detail::kernel_generator_state_ptr state)\n    {\n        boost::fusion::for_each(term.coord, local_init(src, queue, prm_name, state));\n    }\n\n    struct local_init {\n        backend::source_generator &s;\n        const backend::command_queue &queue;\n        const std::string &prm_name;\n        detail::kernel_generator_state_ptr state;\n        mutable int pos;\n\n        local_init(backend::source_generator &s,\n                const backend::command_queue &queue, const std::string &prm_name,\n                detail::kernel_generator_state_ptr state\n            ) : s(s), queue(queue), prm_name(prm_name), state(state), pos(0)\n        {}\n\n        template <class Expr>\n        void operator()(const Expr &expr) const {\n            std::ostringstream prefix;\n            prefix << prm_name << \"_x\" << pos;\n\n            detail::output_local_preamble init_ctx(s, queue, prefix.str(), state);\n            boost::proto::eval(boost::proto::as_child(expr), init_ctx);\n\n            pos++;\n        }\n    };\n};\n\ntemplate <class MBA, class ExprTuple>\nstruct partial_vector_expr< mba_interp<MBA, ExprTuple> > {\n    static void get(backend::source_generator &src,\n            const mba_interp<MBA, ExprTuple> &term,\n            const backend::command_queue &queue, const std::string &prm_name,\n            detail::kernel_generator_state_ptr state)\n    {\n        src << prm_name << \"_mba(\";\n\n        boost::fusion::for_each(term.coord, buildexpr(src, queue, prm_name, state));\n\n        for(size_t k = 0; k < MBA::ndim; ++k) {\n            src << \", \" << prm_name << \"_c\" << k\n                << \", \" << prm_name << \"_h\" << k\n                << \", \" << prm_name << \"_n\" << k\n                << \", \" << prm_name << \"_m\" << k;\n        }\n\n        src << \", \" << prm_name << \"_phi)\";\n    }\n\n    struct buildexpr {\n        backend::source_generator &s;\n        const backend::command_queue &queue;\n        const std::string &prm_name;\n        detail::kernel_generator_state_ptr state;\n        mutable int pos;\n\n        buildexpr(backend::source_generator &s,\n                const backend::command_queue &queue, const std::string &prm_name,\n                detail::kernel_generator_state_ptr state\n            ) : s(s), queue(queue), prm_name(prm_name), state(state), pos(0)\n        {}\n\n        template <class Expr>\n        void operator()(const Expr &expr) const {\n            if(pos) s << \", \";\n\n            std::ostringstream prefix;\n            prefix << prm_name << \"_x\" << pos;\n\n            detail::vector_expr_context ctx(s, queue, prefix.str(), state);\n            boost::proto::eval(boost::proto::as_child(expr), ctx);\n\n            pos++;\n        }\n    };\n};\n\ntemplate <class MBA, class ExprTuple>\nstruct kernel_arg_setter< mba_interp<MBA, ExprTuple> > {\n    static void set(const mba_interp<MBA, ExprTuple> &term,\n            backend::kernel &kernel, unsigned part, size_t index_offset,\n            detail::kernel_generator_state_ptr state)\n    {\n\n        boost::fusion::for_each(term.coord,\n                setargs(kernel, part, index_offset, state));\n\n        for(size_t k = 0; k < MBA::ndim; ++k) {\n            kernel.push_arg(term.cloud.xmin[k]);\n            kernel.push_arg(term.cloud.hinv[k]);\n            kernel.push_arg(term.cloud.n[k]);\n            kernel.push_arg(term.cloud.stride[k]);\n        }\n        kernel.push_arg(term.cloud.phi[part]);\n    }\n\n    struct setargs {\n        backend::kernel &kernel;\n        unsigned part;\n        size_t index_offset;\n        detail::kernel_generator_state_ptr state;\n\n        setargs(\n                backend::kernel &kernel, unsigned part, size_t index_offset,\n                detail::kernel_generator_state_ptr state\n               )\n            : kernel(kernel), part(part), index_offset(index_offset), state(state)\n        {}\n\n        template <class Expr>\n        void operator()(const Expr &expr) const {\n            detail::set_expression_argument ctx(kernel, part, index_offset, state);\n            detail::extract_terminals()( boost::proto::as_child(expr), ctx);\n        }\n    };\n};\n\ntemplate <class MBA, class ExprTuple>\nstruct expression_properties< mba_interp<MBA, ExprTuple> > {\n    static void get(const mba_interp<MBA, ExprTuple> &term,\n            std::vector<backend::command_queue> &queue_list,\n            std::vector<size_t> &partition,\n            size_t &size\n            )\n    {\n        boost::fusion::for_each(term.coord, extrprop(queue_list, partition, size));\n    }\n\n    struct extrprop {\n        std::vector<backend::command_queue> &queue_list;\n        std::vector<size_t> &partition;\n        size_t &size;\n\n        extrprop(std::vector<backend::command_queue> &queue_list,\n            std::vector<size_t> &partition, size_t &size\n            ) : queue_list(queue_list), partition(partition), size(size)\n        {}\n\n        template <class Expr>\n        void operator()(const Expr &expr) const {\n            if (queue_list.empty()) {\n                detail::get_expression_properties prop;\n                detail::extract_terminals()(boost::proto::as_child(expr), prop);\n\n                queue_list = prop.queue;\n                partition  = prop.part;\n                size       = prop.size;\n            }\n        }\n    };\n};\n\n} //namespace traits\n\n} // namespace vex\n\n\n#endif\n", "meta": {"hexsha": "50be317007f2acbee3f5200b31da369f3a52e7c4", "size": 27908, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "external_libraries/vexcl/vexcl/mba.hpp", "max_stars_repo_name": "lkusch/Kratos", "max_stars_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 778.0, "max_stars_repo_stars_event_min_datetime": "2017-01-27T16:29:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:01:51.000Z", "max_issues_repo_path": "external_libraries/vexcl/vexcl/mba.hpp", "max_issues_repo_name": "lkusch/Kratos", "max_issues_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 6634.0, "max_issues_repo_issues_event_min_datetime": "2017-01-15T22:56:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:03:36.000Z", "max_forks_repo_path": "external_libraries/vexcl/vexcl/mba.hpp", "max_forks_repo_name": "lkusch/Kratos", "max_forks_repo_head_hexsha": "e8072d8e24ab6f312765185b19d439f01ab7b27b", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 224.0, "max_forks_repo_forks_event_min_datetime": "2017-02-07T14:12:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T23:09:34.000Z", "avg_line_length": 34.8414481898, "max_line_length": 146, "alphanum_fraction": 0.4960226458, "num_tokens": 6660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.2099023010667857}}
{"text": "/*\n * @file pppBayesTree.cpp\n * @brief Iterative GPS Range/Phase Estimator with collected data\n * @author Ryan Watson & Jason Gross\n */\n\n// GTSAM related includes.\n#include <gtsam/slam/dataset.h>\n#include <gtsam/nonlinear/ISAM2.h>\n#include <gtsam/inference/Symbol.h>\n#include <gtsam/slam/PriorFactor.h>\n#include <gtsam/slam/BetweenFactor.h>\n#include <gtsam/gnssNavigation/GnssData.h>\n#include <gtsam/gnssNavigation/GnssTools.h>\n#include <gtsam/gnssNavigation/PhaseFactor.h>\n#include <gtsam/gnssNavigation/nonBiasStates.h>\n#include <gtsam/configReader/ConfDataReader.hpp>\n#include <gtsam/nonlinear/NonlinearFactorGraph.h>\n#include <gtsam/gnssNavigation/PseudorangeFactor.h>\n#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>\n\n// GPSTK\n#include <gtsam/gpstk/MJD.hpp>\n#include <gtsam/gpstk/PowerSum.hpp>\n#include <gtsam/gpstk/Decimate.hpp>\n#include <gtsam/gpstk/SolidTides.hpp>\n#include <gtsam/gpstk/PoleTides.hpp>\n#include <gtsam/gpstk/TropModel.hpp>\n#include <gtsam/gpstk/BasicModel.hpp>\n#include <gtsam/gpstk/CommonTime.hpp>\n#include <gtsam/gpstk/PCSmoother.hpp>\n#include <gtsam/gpstk/OceanLoading.hpp>\n#include <gtsam/gpstk/CodeSmoother.hpp>\n#include <gtsam/gpstk/SimpleFilter.hpp>\n#include <gtsam/gpstk/MWCSDetector.hpp>\n#include <gtsam/gpstk/SatArcMarker.hpp>\n#include <gtsam/gpstk/DCBDataReader.hpp>\n#include <gtsam/gpstk/ComputeWindUp.hpp>\n#include <gtsam/gpstk/Rinex3NavData.hpp>\n#include <gtsam/gpstk/GNSSconstants.hpp>\n#include <gtsam/gpstk/ComputeLinear.hpp>\n#include <gtsam/gpstk/GPSWeekSecond.hpp>\n#include <gtsam/gpstk/LICSDetector2.hpp>\n#include <gtsam/gpstk/DataStructures.hpp>\n#include <gtsam/gpstk/RinexObsStream.hpp>\n#include <gtsam/gpstk/Rinex3ObsStream.hpp>\n#include <gtsam/gpstk/Rinex3NavStream.hpp>\n#include <gtsam/gpstk/ComputeTropModel.hpp>\n#include <gtsam/gpstk/SP3EphemerisStore.hpp>\n#include <gtsam/gpstk/ComputeSatPCenter.hpp>\n#include <gtsam/gpstk/EclipsedSatFilter.hpp>\n#include <gtsam/gpstk/GPSEphemerisStore.hpp>\n#include <gtsam/gpstk/CorrectCodeBiases.hpp>\n#include <gtsam/gpstk/ComputeSatPCenter.hpp>\n#include <gtsam/gpstk/RequireObservables.hpp>\n#include <gtsam/gpstk/CorrectObservables.hpp>\n#include <gtsam/gpstk/LinearCombinations.hpp>\n#include <gtsam/gpstk/GravitationalDelay.hpp>\n#include <gtsam/gpstk/PhaseCodeAlignment.hpp>\n\n\n// BOOST\n#include <boost/filesystem.hpp>\n#include <boost/program_options.hpp>\n#include <boost/serialization/export.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n\n// STD\n#include <chrono>\n#include <iomanip>\n#include <fstream>\n#include <iostream>\n#include <unistd.h>\n#include <algorithm>\n\nusing namespace std;\nusing namespace gtsam;\nusing namespace gpstk;\nusing namespace boost;\nusing namespace std::chrono;\nnamespace NM = gtsam::noiseModel;\nnamespace po = boost::program_options;\ntypedef noiseModel::Diagonal diagNoise;\n\n// Intel Threading Building Block\n#ifdef GTSAM_USE_TBB\n  #include <tbb/tbb.h>\n  #undef max // TBB seems to include windows.h and we don't want these macros\n  #undef min\n#endif\n\nusing symbol_shorthand::X; // nonBiasStates ( dx, dy, dz, trop, cb )\nusing symbol_shorthand::G;   // bias states ( Phase Biases )\n\nint main(int argc, char* argv[])\n{\n        // define std out print color\n        vector<int> prn_vec;\n        vector<rnxData> data;\n        const string red(\"\\033[0;31m\");\n        const string green(\"\\033[0;32m\");\n        string confFile, gnssFile, station, sp3File, p1p2File, p1c1File, antennaModel;\n        string rnx_file, nav_file, sp3_file, out_file, antexFile;\n        double xn, yn, zn, xp, yp, range, phase, rho, minElev, weightFactor;\n        double antennaOffSetH, antennaOffSetE, antennaOffSetN;\n        int startKey(0), currKey, startEpoch(0), svn, doy;\n        int nThreads(-1), phase_break, break_count(0), nextKey, dec_int, itsBelowThree=0, count=0;\n        bool printECEF, printENU, printAmb, printUpdateRate, first_ob(true), usingP1(false);\n\n        cout.precision(12);\n\n        po::options_description desc(\"Available options\");\n        desc.add_options()\n                (\"help,h\", \"Print help message\")\n                (\"confFile,c\", po::value<string>(&confFile)->default_value(\"\"),\n                \"Input config file\" )\n                (\"out\", po::value<string>(&out_file)->default_value(\"\"),\n                \"output file.\")\n                (\"usingP1\", \"Are you using P1 instead of C1?\");\n        po::variables_map vm;\n        po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n        po::notify(vm);\n\n        ConfDataReader confReader;\n        confReader.open(confFile);\n\n        if (confFile.empty() ) {\n                cout << red << \"\\n\\n Currently, you need to provide a conf file \\n\"\n                     << \"\\n\\n\"  << green << desc << endl;\n        }\n\n        while ( (station = confReader.getEachSection()) != \"\" )\n        {\n                // Fetch nominal station location [m]\n                xn = confReader.fetchListValueAsDouble(\"nominalECEF\",station);\n                yn = confReader.fetchListValueAsDouble(\"nominalECEF\",station);\n                zn = confReader.fetchListValueAsDouble(\"nominalECEF\",station);\n                // day of year ( used for Niell Trop model)\n                doy = confReader.getValueAsInt(\"DOY\", station);\n                // Elevation cut-off\n                minElev = confReader.getValueAsDouble(\"minElev\", station);\n                // Code/carrier ratio\n                weightFactor = confReader.getValueAsDouble(\"weightFactor\", station);\n                // Data file names\n                gnssFile = confReader(\"rnxFile\", station);\n                sp3File = confReader(\"sp3File\", station);\n                p1p2File = confReader(\"p1p2\", station);\n                p1c1File = confReader(\"p1c1\", station);\n                // Print statements\n                printENU = confReader.getValueAsBoolean(\"printENU\", station);\n                printAmb = confReader.getValueAsBoolean(\"printAmb\", station);\n                printECEF = confReader.getValueAsBoolean(\"printECEF\", station);\n                printUpdateRate = confReader.getValueAsBoolean(\"printUpdateRate\", station);\n        }\n\n        usingP1 = (vm.count(\"usingP1\")>0);\n\n        Point3 nomXYZ(xn, yn, zn);\n        Point3 prop_xyz = nomXYZ;\n\n\n        #ifdef GTSAM_USE_TBB\n        std::auto_ptr<tbb::task_scheduler_init> init;\n        if(nThreads > 0) {\n                init.reset(new tbb::task_scheduler_init(nThreads));\n        }\n        else\n                cout << green << \" \\n\\n Using threads for all processors\" << endl;\n        #else\n        if(nThreads > 0) {\n                cout << red <<\" \\n\\n GTSAM is not compiled with TBB, so threading is\"\n                     << \" disabled and the --threads option cannot be used.\"\n                     << endl;\n                exit(1);\n        }\n        #endif\n\n        ISAM2DoglegParams doglegParams;\n        ISAM2Params parameters;\n        parameters.relinearizeThreshold = 0.1;\n        parameters.relinearizeSkip = 100;\n        ISAM2 isam(parameters);\n\n        double output_time = 0.0;\n        double rw = 2.5;\n        double rangeWeight = pow(rw,2);\n        double phaseWeight = pow(rw*1/weightFactor,2);\n\n        string value;\n\n        nonBiasStates prior_nonBias = (gtsam::Vector(5) << 0.0, 0.0, 0.0, 0.0, 0.0).finished();\n\n        phaseBias bias_state(Z_1x1);\n        gnssStateVector phase_arc(Z_34x1);\n        gnssStateVector bias_counter(Z_34x1);\n        for (int i=1; i<34; i++) {bias_counter(i) = bias_counter(i-1) + 10000; }\n\n        nonBiasStates initEst(Z_5x1);\n        nonBiasStates between_nonBias_State(Z_5x1);\n\n        Values initial_values;\n        Values result;\n\n        noiseModel::Diagonal::shared_ptr nonBias_InitNoise = noiseModel::Diagonal::Variances((gtsam::Vector(5) << 10.0, 10.0, 10.0, 3e8, 1e-1).finished());\n\n        noiseModel::Diagonal::shared_ptr nonBias_ProcessNoise = noiseModel::Diagonal::Variances((gtsam::Vector(5) << 0.1, 0.1, 0.1, 3e6, 3e-5).finished());\n\n        noiseModel::Diagonal::shared_ptr initNoise = noiseModel::Diagonal::Variances((gtsam::Vector(1) << 100).finished());\n\n        string obs_path = findExampleDataFile(gnssFile);\n        string p1p2_path = findExampleDataFile(p1p2File);\n        string p1c1_path = findExampleDataFile(p1c1File);\n\n        if ( obs_path.empty() )\n        {\n                cout << \" Must pass in obs file !!! \" << desc << endl;\n                exit(1);\n        }\n        if ( sp3File.empty() )\n        {\n                cout << \" Must pass in ephemeris file !!! \" << desc << endl;\n                exit(1);\n        }\n        // Declare a \"SP3EphemerisStore\" object to handle precise ephemeris\n        SP3EphemerisStore SP3EphList;\n\n        size_t pos = 0;\n        string path, token;\n        string delimiter = \" \";\n        while ((pos = sp3File.find(delimiter)) != string::npos) {\n                path = findExampleDataFile(sp3File.substr(0,pos));\n                SP3EphList.loadFile(path);\n                sp3File.erase(0, pos + delimiter.length());\n        }\n        path = findExampleDataFile(sp3File);\n        SP3EphList.loadFile(path);\n\n        // Set flags to reject satellites with bad or absent positional\n        // values or clocks\n        SP3EphList.rejectBadPositions(true);\n        SP3EphList.rejectBadClocks(true);\n\n        // Create the input observation file stream\n        Rinex3ObsStream rin(obs_path);\n\n        // station nominal position\n        Position nominalPos(xn, yn, zn);\n\n        CorrectCodeBiases corrCode;\n        corrCode.setDCBFile(p1p2_path, p1c1_path);\n\n        if (!usingP1) {\n                corrCode.setUsingC1(true);\n        }\n\n\n        // This is the GNSS data structure that will hold all the\n        // GNSS-related information\n        gnssRinex gRin;\n\n        RequireObservables requireObs;\n        requireObs.addRequiredType(TypeID::L1);\n        requireObs.addRequiredType(TypeID::L2);\n\n        SimpleFilter pObsFilter;\n        pObsFilter.setFilteredType(TypeID::C1);\n\n        if ( usingP1 )\n        {\n                requireObs.addRequiredType(TypeID::P1);\n                pObsFilter.addFilteredType(TypeID::P1);\n                requireObs.addRequiredType(TypeID::P2);\n                pObsFilter.addFilteredType(TypeID::P2);\n        }\n        else\n        {\n                requireObs.addRequiredType(TypeID::C1);\n                pObsFilter.addFilteredType(TypeID::C1);\n                requireObs.addRequiredType(TypeID::P2);\n                pObsFilter.addFilteredType(TypeID::P2);\n        }\n\n        // Declare a couple of basic modelers\n        BasicModel basic(nominalPos, SP3EphList);\n        basic.setMinElev(minElev);\n\n        // Object to correct for SP3 Sat Phase-center offset\n        ComputeSatPCenter svPcenter(SP3EphList, nominalPos);\n\n        // Objects to mark cycle slips\n        MWCSDetector markCSMW;  // Checks Merbourne-Wubbena cycle slip\n\n        // object def several linear combinations\n        LinearCombinations comb;\n\n        // Object to compute linear combinations for cycle slip detection\n        ComputeLinear linear1;\n        if ( usingP1 )\n        {\n                linear1.addLinear(comb.pdeltaCombination);\n                linear1.addLinear(comb.mwubbenaCombination);\n        }\n        else\n        {\n                linear1.addLinear(comb.pdeltaCombWithC1);\n                linear1.addLinear(comb.mwubbenaCombWithC1);\n        }\n        linear1.addLinear(comb.ldeltaCombination);\n        linear1.addLinear(comb.liCombination);\n\n        ComputeLinear linear2;\n\n        // Read if we should use C1 instead of P1\n        if ( usingP1 ) { linear2.addLinear(comb.pcCombination); }\n        else {  linear2.addLinear(comb.pcCombWithC1); }\n        linear2.addLinear(comb.lcCombination);\n\n        LICSDetector2 markCSLI2;       // Checks LI cycle slips\n\n        // Object to keep track of satellite arcs\n        SatArcMarker markArc;\n        markArc.setDeleteUnstableSats(true);\n\n        // Objects to compute gravitational delay effects\n        GravitationalDelay grDelay(nominalPos);\n\n        // Object to remove eclipsed satellites\n        EclipsedSatFilter eclipsedSV;\n\n        //Object to compute wind-up effect\n        ComputeWindUp windup( SP3EphList, nominalPos );\n\n        // Object to compute prefit-residuals\n        ComputeLinear linear3(comb.pcPrefit);\n        linear3.addLinear(comb.lcPrefit);\n\n        TypeIDSet tset;\n        tset.insert(TypeID::prefitC);\n        tset.insert(TypeID::prefitL);\n\n        // Declare a NeillTropModel object, setting the defaults\n        NeillTropModel neillTM( nominalPos.getAltitude(),\n                                nominalPos.getGeodeticLatitude(),\n                                doy);\n\n        // Objects to compute the tropospheric data\n        ComputeTropModel computeTropo(neillTM);\n\n        // initialize factor graph\n        NonlinearFactorGraph *graph = new NonlinearFactorGraph();\n\n        auto start = std::chrono::steady_clock::now();\n        auto end = std::chrono::steady_clock::now();\n        // Loop over all data epochs\n        while(rin >> gRin)\n        {\n                TimeSystem sys;\n                sys.fromString(\"GPS\");\n                CommonTime time(gRin.header.epoch);\n                time.setTimeSystem(sys);\n                GPSWeekSecond gpstime( time );\n\n                // update nominal ECEF with propogated pos.\n                NeillTropModel neillTM( nominalPos.getAltitude(),\n                                        nominalPos.getGeodeticLatitude(),\n                                        doy);\n                try\n                {\n                        gRin >> requireObs // Check if required observations are present\n                        >> pObsFilter // Filter out spurious data\n                        >> linear1 // Compute linear combinations to detect CS\n                        >> markCSLI2 // Mark cycle slips\n                        >> markArc // Keep track of satellite arcs\n                        >> basic // Compute the basic components of model\n                        >> eclipsedSV // Remove satellites in eclipse\n                        >> grDelay // Compute gravitational delay\n                        >> svPcenter // Computer delta for sat. phase center\n                        >> corrCode // Correct for differential code biases\n                        >> windup // phase windup correction\n                        >> computeTropo // neill trop function\n                        >> linear2  // Compute ionosphere-free combinations\n                        >> linear3;   // Compute prefit residuals\n                }\n                catch(Exception& e) {continue; }\n                catch(...)\n                {\n                        cerr << \"Unknown exception at epoch: \" << time << endl;\n                        continue;\n                }\n\n                // Iterate through the GNSS Data Structure\n                satTypeValueMap::const_iterator it;\n                typeValueMap::const_iterator itObs;\n                if ( itsBelowThree > 0 )\n                {\n                        itsBelowThree = 0;\n                        continue;\n                }\n\n                if (gRin.body.size() == 0) { continue; }\n\n                // Loop over all observed sats at current epoch\n                for (it = gRin.body.begin(); it!= gRin.body.end(); it++)\n                {\n\n                        start = std::chrono::steady_clock::now();\n                        svn = ((*it).first).id;\n                        double satX, satY, satZ;\n                        satX = (*it).second.getValue(TypeID::satX);\n                        satY = (*it).second.getValue(TypeID::satY);\n                        satZ = (*it).second.getValue(TypeID::satZ);\n                        Point3 satXYZ = Point3(satX,satY,satZ);\n                        double range, rangeRes;\n                        range = (*it).second.getValue(TypeID::PC);\n                        rangeRes = (*it).second.getValue(TypeID::prefitC);\n                        double phase, phaseRes;\n                        phase = (*it).second.getValue(TypeID::LC);\n                        phaseRes = (*it).second.getValue(TypeID::prefitL);\n                        int phase_break;\n                        phase_break = (*it).second.getValue(TypeID::satArc);\n\n                        if (first_ob) {\n                                startKey = count; first_ob=false;\n                                graph->add(PriorFactor<nonBiasStates>(X(count), initEst,  nonBias_InitNoise));\n                                initial_values.insert(X(count), initEst);\n                        }\n\n                        if (phase_arc[svn]!=phase_break)\n                        {\n                                bias_state[0] = phase - range;\n                                if (count > startKey) { bias_counter[svn] = bias_counter[svn] +1; }\n                                graph->add(PriorFactor<phaseBias>(G(bias_counter[svn]), bias_state,  initNoise));\n                                initial_values.insert(G(bias_counter[svn]), bias_state);\n                                phase_arc[svn] = phase_break;\n                        }\n                        // Generate pseudorange factor\n                        PseudorangeFactor gpsRangeFactor(X(count), rangeRes, satXYZ, nomXYZ, diagNoise::Variances( (gtsam::Vector(1) << elDepWeight(satXYZ, nomXYZ, rangeWeight)).finished()));\n\n                        graph->add(gpsRangeFactor);\n\n                        // Generate phase factor\n                        PhaseFactor gpsPhaseFactor(X(count), G(bias_counter[svn]), phaseRes, satXYZ, nomXYZ, diagNoise::Variances( (gtsam::Vector(1) << elDepWeight(satXYZ, nomXYZ, phaseWeight)).finished() ));\n\n                        graph->add(gpsPhaseFactor);\n                        prn_vec.push_back(svn);\n                }\n                if (count > startKey ) {\n                        graph->add(BetweenFactor<nonBiasStates>(X(count), X(count-1), between_nonBias_State, nonBias_ProcessNoise));\n                }\n                isam.update(*graph, initial_values);\n                result = isam.calculateEstimate();\n\n                end = std::chrono::steady_clock::now();\n\n\n                prior_nonBias = result.at<nonBiasStates>(X(count));\n                Point3 delta_xyz = (gtsam::Vector(3) << prior_nonBias.x(), prior_nonBias.y(), prior_nonBias.z()).finished();\n                Position deltaPos(prior_nonBias.x(), prior_nonBias.y(), prior_nonBias.z());\n                prop_xyz = nomXYZ - delta_xyz;\n                nominalPos -= deltaPos;\n\n                if (printECEF) {\n                        cout << \"xyz \" << gpstime.week << \" \" << gpstime.sow << \" \" << prop_xyz.x() << \" \" << prop_xyz.y() << \" \" << prop_xyz.z() << endl;\n                }\n\n                if (printENU) {\n                        Point3 enu = xyz2enu(prop_xyz, nomXYZ);\n                        cout << \"enu \" << gpstime.week << \" \" << gpstime.sow << \" \" << enu.x() << \" \" << enu.y() << \" \" << enu.z() << endl;\n                }\n\n                if (printAmb) {\n                        for (int k=0; k<prn_vec.size(); k++) {\n                                cout << \"amb. \" << gpstime.week << \" \" << gpstime.sow << \" \";\n                                cout << prn_vec[k] << \" \";\n                                cout << result.at<phaseBias>(G(bias_counter[prn_vec[k]])) << endl;\n                        }\n                }\n\n                if (printUpdateRate) {\n                        cout << \"Elapsed time \"\n                             << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count()\n                             << \" µs\" << endl;\n                }\n\n                output_time = output_time +1;\n                graph->resize(0);\n                initial_values.clear();\n                prn_vec.clear();\n                count++;\n                initial_values.insert(X(count), prior_nonBias);\n        }\n        isam.saveGraph(\"gnss.tree\");\n        return 0;\n}\n", "meta": {"hexsha": "efcaf0255701a3b34b99166ab9917ae79398c609", "size": 19884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "trunk/examples/pppBayesTree.cpp", "max_stars_repo_name": "wvu-navLab/PPP-BayesTree", "max_stars_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 40.0, "max_stars_repo_stars_event_min_datetime": "2018-04-23T02:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T14:41:03.000Z", "max_issues_repo_path": "trunk/examples/pppBayesTree.cpp", "max_issues_repo_name": "shaolinbit/PPP-BayesTree", "max_issues_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-01-02T15:03:54.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-23T03:04:04.000Z", "max_forks_repo_path": "trunk/examples/pppBayesTree.cpp", "max_forks_repo_name": "shaolinbit/PPP-BayesTree", "max_forks_repo_head_hexsha": "6f469775277a1a33447bf4c19603c796c2c63c75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2018-05-18T05:59:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T13:51:18.000Z", "avg_line_length": 40.0887096774, "max_line_length": 208, "alphanum_fraction": 0.5701066184, "num_tokens": 4765, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.3557748935136304, "lm_q1q2_score": 0.2095119729241656}}
{"text": "#include <Eigen/Core>\n#include <Eigen/Dense>\n#include <assert.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <iostream>\n#include <ros/ros.h>\n#include <sensor_msgs/Imu.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/time.h>\n#include <sys/types.h>\n#include <termios.h>\n#include <time.h>\n#include <unistd.h>\n\nstatic int ret;\nstatic int fd;\n\nros::Publisher pubImu;\n#define BAUD 115200 // 115200 for JY61 ,9600 for others\n\ntemplate <typename Derived>\nstatic Eigen::Matrix<typename Derived::Scalar, 3, 3>\n\nypr2R(const Eigen::MatrixBase<Derived> &ypr) {\n  typedef typename Derived::Scalar Scalar_t;\n\n  Scalar_t y = ypr(0) / 180.0 * M_PI;\n  Scalar_t p = ypr(1) / 180.0 * M_PI;\n  Scalar_t r = ypr(2) / 180.0 * M_PI;\n\n  Eigen::Matrix<Scalar_t, 3, 3> Rz;\n  Rz << cos(y), -sin(y), 0, sin(y), cos(y), 0, 0, 0, 1;\n\n  Eigen::Matrix<Scalar_t, 3, 3> Ry;\n  Ry << cos(p), 0., sin(p), 0., 1., 0., -sin(p), 0., cos(p);\n\n  Eigen::Matrix<Scalar_t, 3, 3> Rx;\n  Rx << 1., 0., 0., 0., cos(r), -sin(r), 0., sin(r), cos(r);\n\n  return Rz * Ry * Rx;\n}\n\nint uart_open(int fd, const char *pathname) {\n  fd = open(pathname, O_RDWR | O_NOCTTY);\n  if (-1 == fd) {\n    perror(\"Can't Open Serial Port\");\n    return (-1);\n  } else\n    printf(\"open %s success!\\n\", pathname);\n  if (isatty(STDIN_FILENO) == 0)\n    printf(\"standard input is not a terminal device\\n\");\n  else\n    printf(\"isatty success!\\n\");\n  return fd;\n}\n\nint uart_set(int fd, int nSpeed, int nBits, char nEvent, int nStop) {\n  struct termios newtio, oldtio;\n  if (tcgetattr(fd, &oldtio) != 0) {\n    perror(\"SetupSerial 1\");\n    printf(\"tcgetattr( fd,&oldtio) -> %d\\n\", tcgetattr(fd, &oldtio));\n    return -1;\n  }\n  bzero(&newtio, sizeof(newtio));\n  newtio.c_cflag |= CLOCAL | CREAD;\n  newtio.c_cflag &= ~CSIZE;\n  switch (nBits) {\n  case 7:\n    newtio.c_cflag |= CS7;\n    break;\n  case 8:\n    newtio.c_cflag |= CS8;\n    break;\n  }\n  switch (nEvent) {\n  case 'o':\n  case 'O':\n    newtio.c_cflag |= PARENB;\n    newtio.c_cflag |= PARODD;\n    newtio.c_iflag |= (INPCK | ISTRIP);\n    break;\n  case 'e':\n  case 'E':\n    newtio.c_iflag |= (INPCK | ISTRIP);\n    newtio.c_cflag |= PARENB;\n    newtio.c_cflag &= ~PARODD;\n    break;\n  case 'n':\n  case 'N':\n    newtio.c_cflag &= ~PARENB;\n    break;\n  default:\n    break;\n  }\n\n  /*设置波特率*/\n\n  switch (nSpeed) {\n  case 2400:\n    cfsetispeed(&newtio, B2400);\n    cfsetospeed(&newtio, B2400);\n    break;\n  case 4800:\n    cfsetispeed(&newtio, B4800);\n    cfsetospeed(&newtio, B4800);\n    break;\n  case 9600:\n    cfsetispeed(&newtio, B9600);\n    cfsetospeed(&newtio, B9600);\n    break;\n  case 115200:\n    cfsetispeed(&newtio, B115200);\n    cfsetospeed(&newtio, B115200);\n    break;\n  case 460800:\n    cfsetispeed(&newtio, B460800);\n    cfsetospeed(&newtio, B460800);\n    break;\n  default:\n    cfsetispeed(&newtio, B9600);\n    cfsetospeed(&newtio, B9600);\n    break;\n  }\n  if (nStop == 1)\n    newtio.c_cflag &= ~CSTOPB;\n  else if (nStop == 2)\n    newtio.c_cflag |= CSTOPB;\n  newtio.c_cc[VTIME] = 0;\n  newtio.c_cc[VMIN] = 0;\n  tcflush(fd, TCIFLUSH);\n\n  if ((tcsetattr(fd, TCSANOW, &newtio)) != 0) {\n    perror(\"com set error\");\n    return -1;\n  }\n  printf(\"set done!\\n\");\n  return 0;\n}\n\nint uart_close(int fd) {\n  assert(fd);\n  close(fd);\n\n  return 0;\n}\nint send_data(int fd, char *send_buffer, int length) {\n  length = write(fd, send_buffer, length * sizeof(unsigned char));\n  return length;\n}\n\nint recv_data(int fd, char *recv_buffer, int length) {\n  int has_receive_length = 0;\n  while (length - has_receive_length > 0) {\n\n    has_receive_length +=\n        read(fd, recv_buffer + has_receive_length, length - has_receive_length);\n    usleep(1000);\n    //        std::cout << \"has_receive_length: \" << has_receive_length <<\n    //        std::endl;\n  }\n  return length;\n}\n\nfloat a[3], w[3], Angle[3], h[3];\nvoid ParseData(char *buffer) {\n  char chrBuf[100];\n  signed short sData[4];\n\n  for (int i = 0; i < 4; i++) {\n    memcpy(&chrBuf[0], buffer + 11 * i, 11);\n\n    //        std::cout << \"i: \" << i << std::endl;\n    //        for(int m =0; m< 11; m++)\n    //        {\n    //            printf(\"%x  \", chrBuf[m]);\n    //        }\n    memcpy(&sData[0], &chrBuf[2], 8);\n    char cTemp = 0;\n    time_t now;\n    for (int j = 0; j < 10; j++) {\n      cTemp += chrBuf[j];\n    }\n\n    if ((chrBuf[0] != 0x55) || ((chrBuf[1] & 0x50) != 0x50) ||\n        (cTemp != chrBuf[10])) {\n      printf(\"Error:%x  %x\\r\\n\", chrBuf[0], chrBuf[1]);\n      return;\n    }\n    switch (chrBuf[1]) {\n    case 0x51:\n      for (int k = 0; k < 3; k++) {\n        a[k] = (float)sData[k] / 32768.0 * 16.0 * 9.81;\n      }\n      time(&now);\n      printf(\"\\r\\nT:%s a:%6.3f %6.3f %6.3f \", asctime(localtime(&now)), a[0],\n             a[1], a[2]);\n\n      break;\n    case 0x52:\n      for (int k = 0; k < 3; k++) {\n        w[k] = (float)sData[k] / 32768.0 * 2000.0/180*M_PI;\n      }\n      printf(\"w:%7.3f %7.3f %7.3f \", w[0], w[1], w[2]);\n      break;\n    case 0x53:\n      for (int k = 0; k < 3; k++) {\n        Angle[k] = (float)sData[k] / 32768.0 * 180.0;\n      }\n      printf(\"A:%7.3f %7.3f %7.3f \", Angle[0], Angle[1], Angle[2]);\n\n      break;\n\n    case 0x54:\n      for (int k = 0; k < 3; k++) {\n        h[k] = (float)sData[k];\n      }\n      printf(\"h:%4.0f %4.0f %4.0f \", h[0], h[1], h[2]);\n\n      break;\n    }\n  }\n\n  sensor_msgs::Imu imu_msg;\n\n  imu_msg.header.stamp = ros::Time::now();\n  imu_msg.header.frame_id = \"/imu\";\n  imu_msg.angular_velocity.x = w[0];\n  imu_msg.angular_velocity.y = w[1];\n  imu_msg.angular_velocity.z = w[2];\n\n  Eigen::Vector3d ypr;\n  ypr << Angle[2], Angle[1], Angle[0];\n  Eigen::Matrix R = ypr2R(ypr);\n  std::cout << \"R:\\n \" << R << std::endl;\n  Eigen::Quaterniond q(R);\n  q.normalize();\n\n  imu_msg.orientation.w = q.w();\n  imu_msg.orientation.x = q.x();\n  imu_msg.orientation.y = q.y();\n  imu_msg.orientation.z = q.z();\n\n  imu_msg.linear_acceleration.x = a[0];\n  imu_msg.linear_acceleration.y = a[1];\n  imu_msg.linear_acceleration.z = a[2];\n\n  pubImu.publish(imu_msg);\n}\n\nint main(int argc, char **argv) {\n  ros::init(argc, argv, \"xense_driver\");\n  ros::NodeHandle n_private(\"~\");\n\n  char r_buf[1024];\n  bzero(r_buf, 1024);\n\n  fd = uart_open(fd, \"/dev/ttyUSB0\"); /*串口号/dev/ttySn,USB口号/dev/ttyUSBn */\n  if (fd == -1) {\n    fprintf(stderr, \"uart_open error\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  if (uart_set(fd, BAUD, 8, 'N', 1) == -1) {\n    fprintf(stderr, \"uart set failed!\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  pubImu = n_private.advertise<sensor_msgs::Imu>(\"/imu/data\", 3000);\n\n  while (ros::ok()) {\n    ret = recv_data(fd, r_buf, 1);\n\n    if (r_buf[0] != 0x55)\n      continue;\n    ret = recv_data(fd, r_buf + 1, 1);\n    if (r_buf[1] != 0x51) {\n      continue;\n    }\n\n    ret = recv_data(fd, r_buf + 2, 44 - 2);\n\n    //        for(int i =0; i< 44; i++)\n    //        {\n    //            printf(\"%x  \", r_buf[i]);\n    //        }\n    std::cout << std::endl;\n    ParseData(r_buf);\n    usleep(1000);\n  }\n\n  ret = uart_close(fd);\n  if (ret == -1) {\n    fprintf(stderr, \"uart_close error\\n\");\n    exit(EXIT_FAILURE);\n  }\n\n  exit(EXIT_SUCCESS);\n}", "meta": {"hexsha": "410d69715372e96316f491e9a9439fe22271c8a3", "size": 7018, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nodes/HWT905Device.cpp", "max_stars_repo_name": "minxuanjun/imu_driver", "max_stars_repo_head_hexsha": "ec905390d50f119154d47285e1412ae09c8cc4dc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nodes/HWT905Device.cpp", "max_issues_repo_name": "minxuanjun/imu_driver", "max_issues_repo_head_hexsha": "ec905390d50f119154d47285e1412ae09c8cc4dc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nodes/HWT905Device.cpp", "max_forks_repo_name": "minxuanjun/imu_driver", "max_forks_repo_head_hexsha": "ec905390d50f119154d47285e1412ae09c8cc4dc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3156146179, "max_line_length": 80, "alphanum_fraction": 0.5635508692, "num_tokens": 2527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.35577487985229844, "lm_q1q2_score": 0.2095119597452499}}
{"text": "// This file is part of DM-HEOM (https://github.com/noma/dm-heom)\n//\n// Copyright (c) 2015-2019 Matthias Noack, Zuse Institute Berlin\n//\n// Licensed under the 3-clause BSD License, see accompanying LICENSE,\n// CONTRIBUTORS.md, and README.md for further information.\n\n#include <exception>\n#include <fstream>\n#include <iostream>\n\n#include <boost/format.hpp>\n#include <noma/num/meta_stepper.hpp>\n\n#include \"heom/command_line.hpp\"\n#include \"heom/common.hpp\"\n#include \"heom/dipole_matrix.hpp\"\n#include \"heom/dipole_pseudo_pathway.hpp\"\n#include \"heom/handle_main_exception.hpp\"\n#include \"heom/hierarchy_mask.hpp\"\n#include \"heom/hierarchy_norm.hpp\"\n#include \"heom/instance.hpp\"\n#include \"heom/make_file_observer_list.hpp\"\n#include \"heom/ocl_config.hpp\"\n#include \"heom/ode.hpp\"\n#include \"heom/circular_dichroism_config.hpp\"\n#include \"heom/population_dynamics_solver.hpp\"\n#include \"heom/sites_to_states.hpp\"\n\nnamespace bmt = ::heom::bmt;\nnamespace num = ::heom::num;\nnamespace ocl = ::heom::ocl;\nusing num::int_t;\nusing num::real_t;\n\nint main(int argc, char* argv[])\n{\n\t// start runtime measurement\n\tbmt::timer app_timer;\n\n\t// output compile time configuration\n\tstd::cout << \"-------------------- Compile-Time Configuration ------------\" << std::endl;\n\theom::write_compile_config(std::cout);\n\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\tstd::exception_ptr eptr;\n\ttry {\n\t\t// command line parsing\n\t\theom::command_line command_line { argc, argv };\n\n\t\tstd::cout << \"Parsing OpenCL configuration from file: \" << command_line.ocl_config_filename() << std::endl;\n\t\theom::ocl_config ocl_config(command_line.ocl_config_filename());\n\t\tstd::cout << \"Parsing HEOM configuration from file: \" << command_line.heom_config_filename() << std::endl;\n\t\theom::circular_dichroism_config heom_config(command_line.heom_config_filename());\n\n\t\theom::hierarchy_graph complete_graph(heom_config.baths_number(), heom_config.baths_matsubaras(), heom_config.system_ado_depth());\n\n\t\tusing stepper_t = num::meta_stepper; // uses solver_stepper_type from config\n\t\tusing solver_t = heom::population_dynamics_solver<heom::ode, stepper_t, heom::hierarchy_norm>;\n\n\t\t// prepare output file (so we run into possible file errors before starting the computation)\n\t\tauto& observation_filename = heom_config.observations().get().front().get().second; // filename of first specified observation, guaranteed to exist by config checks\n\t\tstd::ofstream observation_file(observation_filename);\n\t\tif (observation_file.fail())\n\t\t\tthrow std::runtime_error(\"Error: could not open output file: \" + observation_filename);\n\n\t\tint_t iterations = heom_config.solver_steps() / heom_config.program_observe_steps();\n\t\tint_t steps_per_iteration = heom_config.program_observe_steps();\n\t\tint_t total_steps = iterations * heom_config.program_observe_steps();\n\n\t\t//output data structure for traces\n\t\tconst size_t num_dipole_matrices = heom_config.dipole_tensor_prefactors().size();\n\t\tconst int_t num_observations = iterations + 1;\n\t\tstd::vector<heom::matrix_trace_observation_view> observations(num_observations);\n\n\t\t// circular dichroism pseudo pathway with ground state\n\t\tconst auto& pathway_spec = heom::dipole_pseudo_pathway_wgs_spec;\n\t\tconst auto sts_mode = pathway_spec.sites_to_states_mode();\n\n\t\t// for progress estimate\n\t\tconst size_t solver_runs = num_dipole_matrices;\n\t\tsize_t solver_run = 0;\n\n\t\t// iterate over all dipoles and compute population dynamics\n\t\tfor (size_t tensor_index = 0; tensor_index < heom_config.dipole_tensor_prefactors().size(); ++tensor_index) {\n\t\t\theom::instance heom_instance(heom_config, sts_mode, complete_graph);\n\t\t\theom_instance.set_hierarchy_top(); // NOTE: hierarchy top is initialised to zero with first element being complex_t(1.0,0.0) here\n\n\t\t\t// OpenCL range\n\t\t\tocl::nd_range range {\n\t\t\t\t{}, // offset\n\t\t\t\t{1, static_cast<std::uint64_t>(heom_instance.matrices())}, // global size\n\t\t\t\t{1, 1} // local size\n\t\t\t};\n\n\t\t\t// create a solver from configuration and instance\n\t\t\tsolver_t solver(ocl_config, range, heom_config, heom_instance);\n\t\t\tstd::cout << \"-------------------- OpenCL Runtime Configuration ----------\" << std::endl;\n\t\t\tsolver.write_ocl_runtime_config(std::cout);\n\t\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\t\t\t++solver_run; // for progress estimate\n\n\t\t\t// compute dipole matrices\n\t\t\tauto dipole_matrix_minus = heom::get_dipole_matrix_for_pathway_circular(pathway_spec, 0, heom_config.system_sites(), heom_config, tensor_index);\n\t\t\tauto dipole_matrix_plus  = heom::get_dipole_matrix_for_pathway(pathway_spec, 1, heom_config.system_sites(), heom_config, tensor_index);\n\n\t\t\t// pre-scale D- for observer\n\t\t\tdipole_matrix_minus.scale(heom::get_dipole_tensor_prefactor(pathway_spec, heom_config, tensor_index));\n\n\t\t\t// multiply D+ from left\n\t\t\tsolver.hierarchy_mmult_left(dipole_matrix_plus.data());\n\n\t\t\t// setup observer with pre-scaled D-\n\t\t\theom::matrix_trace_observer<solver_t> trace_observer(complete_graph, solver, dipole_matrix_minus.data()); // D- from left via observer\n\n\t\t\t// generate first observation with initial value\n\t\t\tobservations[0] += trace_observer.observe_trace(0.0);\n\n\t\t\t// write header once\n\t\t\tif (tensor_index == 0)\n\t\t\t\ttrace_observer.write_header(observation_file, true);\n\n\t\t\tfor (int_t i = 0; i < iterations; ++i) {\n\t\t\t\t// propagate\n\t\t\t\tsolver.step_forward(steps_per_iteration);\n\n\t\t\t\t// after propagation, we are at:\n\t\t\t\tconst auto current_step = (i + 1) * steps_per_iteration;\n\t\t\t\tconst real_t current_time = current_step * heom_config.solver_step_size();\n\n\t\t\t\t// observe\n\t\t\t\tobservations[i + 1] += trace_observer.observe_trace(current_time);\n\n\t\t\t\t// update status\n\t\t\t\theom::write_progress(current_step - 1, total_steps, solver_run, solver_runs, \"Calculation circular dichroism: \", std::cout);\n\t\t\t}\n\n\t\t\t// write_complex_matrix(result_buffer_top, heom_instance.states(), std::cout);\n\t\t\tstd::cout << \"-------------------- Solver Runtime Summary ----------------\" << std::endl;\n\t\t\tsolver.write_runtime_summary(std::cout);\n\t\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\t\t} // for tensor_index\n\n\t\t// write averaged traces\n\t\tfor (auto& obs : observations) {\n\t\t\tobs.avg(num_dipole_matrices);\n\t\t\tobservation_file << obs << '\\n';\n\t\t}\n\t\tobservation_file << std::flush; // tell the OS to write to disk\n\n\t\tstd::cout   << \"-------------------- Memory Summary ------------------------\" << std::endl;\n\t\tstd::cout   << \"max. heap via aligned::allocate(..):    \"\n\t\t            << boost::format(\"%11.2f MiB\") % (heom::memory::aligned::instance().allocated_byte_max() / 1024.0 / 1024.0)\n\t\t            << \" (\"\n\t\t            << boost::format(\"count: %6i\") % heom::memory::aligned::instance().allocations_max()\n\t\t            << ')' << std::endl;\n//\t\tstd::cout   << \"max. OpenCL buffer allocations:         \"\n//\t\t            << boost::format(\"%11.2f MiB\") % (solver.ocl_helper().allocated_byte_max() / 1024.0 / 1024.0)\n//\t\t            << \" (\"\n//\t\t            << boost::format(\"count: %6i\") % solver.ocl_helper().allocations_max()\n//\t\t            << ')' << std::endl;\n\t\tstd::cout << \"------------------------------------------------------------\" << std::endl;\n\n\t} catch (...) {\n\t\teptr = std::current_exception();\n\t}\n\tint ret = heom::handle_main_exception(eptr);\n\n\t// print application runtime\n\tstd::cout << \"time in main():\\t\" << boost::format(\"%11.2f\") % std::chrono::duration_cast<bmt::seconds>(bmt::duration(app_timer.elapsed())).count() << \" s\" << std::endl;\n\n\treturn ret;\n}\n\n\n", "meta": {"hexsha": "b72181d728290d21879dc0e15903b21b0b362ef4", "size": 7502, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dm-heom/src/app_circular_dichroism.cpp", "max_stars_repo_name": "noma/dm-heom", "max_stars_repo_head_hexsha": "85c94f947190064d21bd38544094731113c15412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-07-28T01:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-09T04:01:36.000Z", "max_issues_repo_path": "dm-heom/src/app_circular_dichroism.cpp", "max_issues_repo_name": "noma/dm-heom", "max_issues_repo_head_hexsha": "85c94f947190064d21bd38544094731113c15412", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dm-heom/src/app_circular_dichroism.cpp", "max_forks_repo_name": "noma/dm-heom", "max_forks_repo_head_hexsha": "85c94f947190064d21bd38544094731113c15412", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-04T15:20:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-24T15:16:40.000Z", "avg_line_length": 42.384180791, "max_line_length": 169, "alphanum_fraction": 0.6767528659, "num_tokens": 1910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2094585956512109}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/make_shared.hpp>\n\n#include \"Tudat/Astrodynamics/Propagators/stateTransitionMatrixInterface.h\"\n\nnamespace tudat\n{\n\nnamespace propagators\n{\n\n//! Function to reset the state transition and sensitivity matrix interpolators\nvoid SingleArcCombinedStateTransitionAndSensitivityMatrixInterface::updateMatrixInterpolators(\n        const std::shared_ptr< interpolators::OneDimensionalInterpolator< double, Eigen::MatrixXd > >\n        stateTransitionMatrixInterpolator,\n        const std::shared_ptr< interpolators::OneDimensionalInterpolator< double, Eigen::MatrixXd > >\n<<<<<<< HEAD\n        sensitivityMatrixInterpolator )\n=======\n        sensitivityMatrixInterpolator,\n        const std::vector< std::pair< int, int > >& statePartialAdditionIndices )\n>>>>>>> origin/master\n{\n    stateTransitionMatrixInterpolator_ = stateTransitionMatrixInterpolator;\n    sensitivityMatrixInterpolator_ = sensitivityMatrixInterpolator;\n    statePartialAdditionIndices_ = statePartialAdditionIndices;\n}\n\n//! Function to get the concatenated state transition and sensitivity matrix at a given time.\nEigen::MatrixXd SingleArcCombinedStateTransitionAndSensitivityMatrixInterface::getCombinedStateTransitionAndSensitivityMatrix(\n        const double evaluationTime )\n{\n    combinedStateTransitionMatrix_.setZero( );\n\n\n    // Set Phi and S matrices.\n    combinedStateTransitionMatrix_.block( 0, 0, stateTransitionMatrixSize_, stateTransitionMatrixSize_ ) =\n            stateTransitionMatrixInterpolator_->interpolate( evaluationTime );\n\n    if( sensitivityMatrixSize_ > 0 )\n    {\n        combinedStateTransitionMatrix_.block( 0, stateTransitionMatrixSize_, stateTransitionMatrixSize_, sensitivityMatrixSize_ ) =\n                sensitivityMatrixInterpolator_->interpolate( evaluationTime );\n    }\n\n    for( unsigned int i = 0; i < statePartialAdditionIndices_.size( ); i++ )\n    {\n        combinedStateTransitionMatrix_.block( statePartialAdditionIndices_.at( i ).first, 0, 6, stateTransitionMatrixSize_ + sensitivityMatrixSize_ ) +=\n                combinedStateTransitionMatrix_.block( statePartialAdditionIndices_.at( i ).second, 0, 6, stateTransitionMatrixSize_ + sensitivityMatrixSize_ );\n    }\n\n\n    return combinedStateTransitionMatrix_;\n}\n\n//! Constructor\nMultiArcCombinedStateTransitionAndSensitivityMatrixInterface::MultiArcCombinedStateTransitionAndSensitivityMatrixInterface(\n        const std::vector< std::shared_ptr< interpolators::OneDimensionalInterpolator< double, Eigen::MatrixXd > > >\n        stateTransitionMatrixInterpolators,\n        const std::vector< std::shared_ptr< interpolators::OneDimensionalInterpolator< double, Eigen::MatrixXd > > >\n        sensitivityMatrixInterpolators,\n        const std::vector< double >& arcStartTimes,\n        const std::vector< double >& arcEndTimes,\n        const int numberOfInitialDynamicalParameters,\n        const int numberOfParameters,\n        const std::vector< std::vector< std::pair< int, int > > >& statePartialAdditionIndices ):\n    CombinedStateTransitionAndSensitivityMatrixInterface( numberOfInitialDynamicalParameters, numberOfParameters ),\n    stateTransitionMatrixInterpolators_( stateTransitionMatrixInterpolators ),\n    sensitivityMatrixInterpolators_( sensitivityMatrixInterpolators ),\n    arcStartTimes_( arcStartTimes ),\n    arcEndTimes_( arcEndTimes ),\n    statePartialAdditionIndices_( statePartialAdditionIndices )\n{\n    if( arcStartTimes_.size( ) != arcEndTimes_.size( ) )\n    {\n        throw std::runtime_error( \"Error when making MultiArcCombinedStateTransitionAndSensitivityMatrixInterface, incompatible time lists\" );\n    }\n    numberOfStateArcs_ = arcStartTimes_.size( );\n\n    sensitivityMatrixSize_ = numberOfParameters - numberOfStateArcs_ * stateTransitionMatrixSize_;\n\n    if( stateTransitionMatrixInterpolators_.size( ) != sensitivityMatrixInterpolators_.size( ) ||\n            stateTransitionMatrixInterpolators_.size( ) != static_cast< unsigned int >( numberOfStateArcs_ ) )\n    {\n        throw std::runtime_error(\n                    \"Error when making multi arc state transition and sensitivity interface, vector sizes are inconsistent\" );\n    }\n\n    std::vector< double > arcSplitTimes = arcStartTimes_;\n    arcSplitTimes.push_back(  std::numeric_limits< double >::max( ));\n    lookUpscheme_ = std::make_shared< interpolators::HuntingAlgorithmLookupScheme< double > >(\n                arcSplitTimes );\n}\n\n//! Function to reset the state transition and sensitivity matrix interpolators\nvoid MultiArcCombinedStateTransitionAndSensitivityMatrixInterface::updateMatrixInterpolators(\n        const std::vector< std::shared_ptr< interpolators::OneDimensionalInterpolator< double, Eigen::MatrixXd > > >\n        stateTransitionMatrixInterpolators,\n        const std::vector< std::shared_ptr< interpolators::OneDimensionalInterpolator< double, Eigen::MatrixXd > > >\n        sensitivityMatrixInterpolators,\n        const std::vector< double >& arcStartTimes,\n        const std::vector< double >& arcEndTimes,\n        const std::vector< std::vector< std::pair< int, int > > >& statePartialAdditionIndices )\n{\n    stateTransitionMatrixInterpolators_ = stateTransitionMatrixInterpolators;\n    sensitivityMatrixInterpolators_ = sensitivityMatrixInterpolators;\n    arcStartTimes_ =  arcStartTimes;\n    arcEndTimes_ = arcEndTimes;\n    statePartialAdditionIndices_ = statePartialAdditionIndices;\n\n    if( stateTransitionMatrixInterpolators_.size( ) != sensitivityMatrixInterpolators_.size( ) ||\n            stateTransitionMatrixInterpolators_.size( ) != static_cast< unsigned int >( numberOfStateArcs_ ) )\n    {\n        throw std::runtime_error(\n                    \"Error when resetting multi arc state transition and sensitivity interface, vector sizes are inconsistent.\" );\n    }\n\n    std::vector< double > arcSplitTimes = arcStartTimes_;\n    arcSplitTimes.push_back( std::numeric_limits< double >::max( ) );\n\n    lookUpscheme_ = std::make_shared< interpolators::HuntingAlgorithmLookupScheme< double > >(\n                arcSplitTimes );\n}\n\n//! Function to get the concatenated single-arc state transition and sensitivity matrix at a given time.\nEigen::MatrixXd MultiArcCombinedStateTransitionAndSensitivityMatrixInterface::getCombinedStateTransitionAndSensitivityMatrix(\n        const double evaluationTime,\n        const bool addCentralBodySensitivity )\n{\n    Eigen::MatrixXd combinedStateTransitionMatrix = Eigen::MatrixXd::Zero(\n                stateTransitionMatrixSize_, stateTransitionMatrixSize_ + sensitivityMatrixSize_ );\n\n    int currentArc = getCurrentArc( evaluationTime ).first;\n\n    // Set Phi and S matrices.\n    if( currentArc >= 0 )\n    {\n        combinedStateTransitionMatrix.block( 0, 0, stateTransitionMatrixSize_, stateTransitionMatrixSize_ ) =\n                stateTransitionMatrixInterpolators_.at( currentArc )->interpolate( evaluationTime );\n        combinedStateTransitionMatrix.block( 0, stateTransitionMatrixSize_, stateTransitionMatrixSize_, sensitivityMatrixSize_ ) =\n                sensitivityMatrixInterpolators_.at( currentArc )->interpolate( evaluationTime );\n\n        for( unsigned int i = 0; i < statePartialAdditionIndices_.at( currentArc ).size( ); i++ )\n        {\n            int indicesToAdd = addCentralBodySensitivity ?\n                        ( stateTransitionMatrixSize_ + sensitivityMatrixSize_ ) : stateTransitionMatrixSize_;\n            combinedStateTransitionMatrix.block(\n                        statePartialAdditionIndices_.at( currentArc ).at( i ).first, 0, 6, indicesToAdd ) +=\n                    combinedStateTransitionMatrix.block(\n                        statePartialAdditionIndices_.at( currentArc ).at( i ).second, 0, 6, indicesToAdd );\n        }\n    }\n    return combinedStateTransitionMatrix;\n}\n\n//! Function to get the concatenated single-arc state transition and sensitivity matrix at a given time.\nEigen::MatrixXd MultiArcCombinedStateTransitionAndSensitivityMatrixInterface::getCombinedStateTransitionAndSensitivityMatrix(\n        const double evaluationTime )\n{\n    return getCombinedStateTransitionAndSensitivityMatrix( evaluationTime, true );\n}\n\n//! Function to get the concatenated state transition matrices for each arc and sensitivity matrix at a given time.\nEigen::MatrixXd MultiArcCombinedStateTransitionAndSensitivityMatrixInterface::getFullCombinedStateTransitionAndSensitivityMatrix(\n        const double evaluationTime,\n        const bool addCentralBodySensitivity )\n{\n    Eigen::MatrixXd combinedStateTransitionMatrix = getCombinedStateTransitionAndSensitivityMatrix(\n                evaluationTime, addCentralBodySensitivity );\n    Eigen::MatrixXd fullCombinedStateTransitionMatrix = Eigen::MatrixXd::Zero(\n                stateTransitionMatrixSize_, numberOfStateArcs_ * stateTransitionMatrixSize_ + sensitivityMatrixSize_ );\n\n    int currentArc = getCurrentArc( evaluationTime ).first;\n\n    // Set Phi and S matrices of current arc.\n<<<<<<< HEAD\n    combinedStateTransitionMatrix.block( 0, currentArc * stateTransitionMatrixSize_, stateTransitionMatrixSize_, stateTransitionMatrixSize_ ) =\n            stateTransitionMatrixInterpolators_.at( currentArc )->interpolate( evaluationTime );\n\n    combinedStateTransitionMatrix.block(\n                0, numberOfStateArcs_ * stateTransitionMatrixSize_, stateTransitionMatrixSize_, sensitivityMatrixSize_ ) =\n            sensitivityMatrixInterpolators_.at( currentArc )->interpolate( evaluationTime );\n=======\n    if( currentArc >= 0 )\n    {\n        fullCombinedStateTransitionMatrix.block(\n                    0, currentArc * stateTransitionMatrixSize_, stateTransitionMatrixSize_, stateTransitionMatrixSize_ ) =\n                stateTransitionMatrixInterpolators_.at( currentArc )->interpolate( evaluationTime );\n        fullCombinedStateTransitionMatrix.block(\n                    0, numberOfStateArcs_ * stateTransitionMatrixSize_, stateTransitionMatrixSize_, sensitivityMatrixSize_ ) =\n                combinedStateTransitionMatrix.block( 0, 0, stateTransitionMatrixSize_, sensitivityMatrixSize_ );\n    }\n    return fullCombinedStateTransitionMatrix;\n}\n>>>>>>> origin/master\n\n//! Function to get the concatenated state transition matrices for each arc and sensitivity matrix at a given time.\nEigen::MatrixXd MultiArcCombinedStateTransitionAndSensitivityMatrixInterface::getFullCombinedStateTransitionAndSensitivityMatrix(\n        const double evaluationTime )\n{\n    return getFullCombinedStateTransitionAndSensitivityMatrix( evaluationTime, true );\n}\n\n//! Function to retrieve the current arc for a given time\nstd::pair< int, double > MultiArcCombinedStateTransitionAndSensitivityMatrixInterface::getCurrentArc( const double evaluationTime )\n{\n\n    int currentArc =  lookUpscheme_->findNearestLowerNeighbour( evaluationTime );\n    if( evaluationTime < arcEndTimes_.at( currentArc ) && evaluationTime > arcStartTimes_.at( currentArc ) )\n    {\n        return std::make_pair( currentArc, arcStartTimes_.at( currentArc ) );\n    }\n    else\n    {\n        return std::make_pair( -1, TUDAT_NAN );\n    }\n}\n\n//! Function to get the concatenated state transition and sensitivity matrix at a given time.\nEigen::MatrixXd HybridArcCombinedStateTransitionAndSensitivityMatrixInterface::getCombinedStateTransitionAndSensitivityMatrix(\n        const double evaluationTime )\n{\n    Eigen::MatrixXd combinedStateTransitionMatrix = Eigen::MatrixXd::Zero(\n                stateTransitionMatrixSize_, stateTransitionMatrixSize_ + sensitivityMatrixSize_ );\n\n    // Get single-arc matrices\n    Eigen::MatrixXd singleArcStateTransition = singleArcInterface_->getCombinedStateTransitionAndSensitivityMatrix(\n                evaluationTime );\n\n    // Get multi-arc matrices\n    Eigen::MatrixXd multiArcStateTransition = multiArcInterface_->getCombinedStateTransitionAndSensitivityMatrix(\n                evaluationTime, false );\n    std::pair< int, double >  currentArc = multiArcInterface_->getCurrentArc( evaluationTime );\n\n    // Set single-arc block\n    combinedStateTransitionMatrix.block( 0, 0, singleArcStateSize_, singleArcStateSize_ ) =\n            singleArcStateTransition.block( 0, 0, singleArcStateSize_, singleArcStateSize_ );\n\n    // Set single-arc sensitivity block\n    combinedStateTransitionMatrix.block( 0, multiArcStateSize_, singleArcStateSize_, sensitivityMatrixSize_ ) =\n            singleArcStateTransition.block( 0, singleArcStateSize_, singleArcStateSize_, sensitivityMatrixSize_ );\n\n    if( !( currentArc.first < 0 ) )\n    {\n        // Set multi-arc block\n        combinedStateTransitionMatrix.block(\n                    singleArcStateSize_, singleArcStateSize_, originalMultiArcStateSize_, originalMultiArcStateSize_ ) =\n                multiArcStateTransition.block(\n                    singleArcStateSize_, singleArcStateSize_, originalMultiArcStateSize_, originalMultiArcStateSize_ );\n\n        // Get single-arc matrices at current arc start\n        Eigen::MatrixXd singleArcStateTransitionAtArcStart = singleArcInterface_->getCombinedStateTransitionAndSensitivityMatrix(\n                    currentArc.second );\n\n        // Set coupled block\n        combinedStateTransitionMatrix.block(\n                    singleArcStateSize_, 0, originalMultiArcStateSize_, singleArcStateSize_ ) =\n                multiArcStateTransition.block(\n                    singleArcStateSize_, 0, originalMultiArcStateSize_, singleArcStateSize_ ) *\n                singleArcStateTransitionAtArcStart.block(\n                    0, 0, singleArcStateSize_, singleArcStateSize_ );\n\n        // Set multi-arc sensitivity block\n        combinedStateTransitionMatrix.block(\n                    singleArcStateSize_, multiArcStateSize_, originalMultiArcStateSize_, sensitivityMatrixSize_ ) =\n                multiArcStateTransition.block(\n                    singleArcStateSize_, multiArcStateSize_, originalMultiArcStateSize_, sensitivityMatrixSize_ );\n\n        std::vector< std::pair< int, int > > statePartialAdditionIndices =\n                multiArcInterface_->getStatePartialAdditionIndices( currentArc.first );\n\n        for( unsigned int i = 0; i < statePartialAdditionIndices.size( ); i++ )\n        {\n            combinedStateTransitionMatrix.block(\n                        statePartialAdditionIndices.at( i ).first, multiArcStateSize_,\n                        6, sensitivityMatrixSize_ ) +=\n                    combinedStateTransitionMatrix.block(\n                        statePartialAdditionIndices.at( i ).second, multiArcStateSize_,\n                        6, sensitivityMatrixSize_ );\n\n        }\n    }\n\n    return combinedStateTransitionMatrix;\n\n}\n\n//! Function to get the concatenated state transition matrices for each arc and sensitivity matrix at a given time.\nEigen::MatrixXd HybridArcCombinedStateTransitionAndSensitivityMatrixInterface::getFullCombinedStateTransitionAndSensitivityMatrix(\n        const double evaluationTime )\n{\n    Eigen::MatrixXd combinedStateTransitionMatrix = getCombinedStateTransitionAndSensitivityMatrix( evaluationTime );\n    Eigen::MatrixXd fullCombinedStateTransitionMatrix = Eigen::MatrixXd::Zero(\n                stateTransitionMatrixSize_, singleArcStateSize_ + numberOfMultiArcs_ * originalMultiArcStateSize_ + sensitivityMatrixSize_ );\n\n    fullCombinedStateTransitionMatrix.block(\n                0, 0, singleArcStateSize_, singleArcStateSize_ ) =\n            combinedStateTransitionMatrix.block(\n                0, 0, singleArcStateSize_, singleArcStateSize_ );\n\n    fullCombinedStateTransitionMatrix.block(\n                0, singleArcStateSize_ + numberOfMultiArcs_ * originalMultiArcStateSize_, singleArcStateSize_, sensitivityMatrixSize_ ) =\n            combinedStateTransitionMatrix.block(\n                0, multiArcStateSize_, singleArcStateSize_, sensitivityMatrixSize_ );\n\n    int currentArc = multiArcInterface_->getCurrentArc( evaluationTime ).first;\n\n    // Set Phi and S matrices of current arc.\n    if( currentArc >= 0 )\n    {\n\n        // Set multi-arc block\n        fullCombinedStateTransitionMatrix.block(\n                    singleArcStateSize_, singleArcStateSize_ + currentArc * originalMultiArcStateSize_,\n                    originalMultiArcStateSize_, originalMultiArcStateSize_ ) =\n                combinedStateTransitionMatrix.block(\n                    singleArcStateSize_, singleArcStateSize_, originalMultiArcStateSize_, originalMultiArcStateSize_ );\n\n\n<<<<<<< HEAD\n    // Set sensitivity block\n    combinedStateTransitionMatrix.block(\n                0, singleArcStateSize_ + numberOfMultiArcs_ * originalMultiArcStateSize_,\n                singleArcStateSize_, sensitivityMatrixSize_ ) =\n            singleArcStateTransition.block( 0, singleArcStateSize_, singleArcStateSize_, sensitivityMatrixSize_ );\n    combinedStateTransitionMatrix.block(\n                singleArcStateSize_, singleArcStateSize_ + numberOfMultiArcs_ * originalMultiArcStateSize_,\n                originalMultiArcStateSize_, sensitivityMatrixSize_ ) =\n            multiArcStateTransition.block(\n                singleArcStateSize_, multiArcStateSize_, originalMultiArcStateSize_, sensitivityMatrixSize_ );\n=======\n        // Set coupled block\n        fullCombinedStateTransitionMatrix.block(\n                    singleArcStateSize_, 0, originalMultiArcStateSize_, singleArcStateSize_ ) =\n                combinedStateTransitionMatrix.block(\n                    singleArcStateSize_, 0, originalMultiArcStateSize_, singleArcStateSize_ );\n>>>>>>> origin/master\n\n        // Set multi-arc sensitivity block\n        fullCombinedStateTransitionMatrix.block(\n                    singleArcStateSize_, singleArcStateSize_ + numberOfMultiArcs_ * originalMultiArcStateSize_,\n                    originalMultiArcStateSize_, sensitivityMatrixSize_ ) =\n                combinedStateTransitionMatrix.block(\n                    singleArcStateSize_, multiArcStateSize_, originalMultiArcStateSize_, sensitivityMatrixSize_ );\n\n    }\n\n    return fullCombinedStateTransitionMatrix;\n}\n\n}\n\n}\n\n", "meta": {"hexsha": "33bd454a7d1359f5880bf62d07a7fa4804a75c77", "size": 18429, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Propagators/stateTransitionMatrixInterface.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Propagators/stateTransitionMatrixInterface.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Propagators/stateTransitionMatrixInterface.cpp", "max_forks_repo_name": "ViktorJordanov/tudat", "max_forks_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.0788043478, "max_line_length": 159, "alphanum_fraction": 0.7330837267, "num_tokens": 3821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2093351501699784}}
{"text": "/*\n qe2alm.cpp\n\n Copyright (c) 2015 Terumasa Tadano\n\n This file is distributed under the terms of the MIT license.\n Please see the file 'LICENCE.txt' in the root directory \n or http://opensource.org/licenses/mit-license.php for information.\n*/\n\n#include <iostream>\n#include <fstream>\n#include <stdlib.h>\n#include <boost/property_tree/xml_parser.hpp>\n#include <boost/property_tree/ptree.hpp>\n#include <boost/version.hpp>\n#include <boost/lexical_cast.hpp>\n#include \"memory.h\"\n#include \"constants.h\"\n#include \"mathfunctions.h\"\n#include \"qe2alm.h\"\n\nusing namespace std;\n\nint main()\n{\n    cout << \" QE2ALM -- a converter of harmonic FCs\" << endl;\n    cout << \" Input file (QE fc file generated by q2r.x) : \";\n    cin >> file_fc2qe;\n    cout << \" Output file (xml file for ALAMODE) : \";\n    cin >> file_xmlout;\n    cout << \" Impose acoustic sum rule ? [y/n] : \";\n    cin >> flag_asr;\n\n    ifs_fc2qe.open(file_fc2qe.c_str(), std::ios::in);\n    if (!ifs_fc2qe) {\n        cout << \" ERROR: Cannot open file \" << file_fc2qe << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    transform(flag_asr.begin(), flag_asr.end(), flag_asr.begin(), ::tolower);\n    if (flag_asr[0] == 'y') {\n        consider_asr = true;\n    } else if (flag_asr[0] == 'n') {\n        consider_asr = false;\n    } else {\n        cout << \" ERROR: Please specify 'y' or 'n' for the acoustic sum rule.\" << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    // Read structural parameters\n\n    ifs_fc2qe >> nkd >> natmin >> ibrav\n              >> celldm[0] >> celldm[1] >> celldm[2]\n              >> celldm[3] >> celldm[4] >> celldm[5];\n\n    if (ibrav == 0) {\n        for (i = 0; i < 3; ++i) {\n            ifs_fc2qe >> lavec[0][i] >> lavec[1][i] >> lavec[2][i];\n        }\n\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                lavec[i][j] *= celldm[0];\n            }\n        }\n    } else {\n        calc_lattice_vector(ibrav, celldm, lavec);\n    }\n\n    recips(lavec, rlavec);\n\n    int dummy;\n    string str_dummy;\n    double tmp;\n\n    allocate(kd_symbol, nkd);\n\n    for (i = 0; i < nkd; ++i) {\n        ifs_fc2qe >> dummy >> kd_symbol[i] >> str_dummy >> tmp;\n        kd_symbol[i] = kd_symbol[i].substr(1);\n    }\n\n    allocate(kd, natmin);\n    allocate(xcrd, natmin, 3);\n\n    for (i = 0; i < natmin; ++i) {\n        ifs_fc2qe >> dummy >> kd[i] >> xcrd[i][0] >> xcrd[i][1] >> xcrd[i][2];\n    }\n\n    std::string str_na;\n    ifs_fc2qe >> str_na;\n\n    if (str_na[0] == 'T') {\n        include_na = true;\n    } else if (str_na[0] == 'F') {\n        include_na = false;\n    } else {\n        cout << \" ERROR: This cannot happen \" << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    if (include_na) {\n        cout << \" WARNING: The given force constant file contains information of\" << endl;\n        cout << \"          dielectric constants and Born effective charges.\" << endl;\n        cout << \"          The program skips these parts and converts the\" << endl;\n        cout << \"          short-range terms only.\" << endl;\n    }\n\n    if (include_na) {\n        allocate(born, natmin, 3, 3);\n        for (i = 0; i < 3; ++i) {\n            for (j = 0; j < 3; ++j) {\n                ifs_fc2qe >> dielec[i][j];\n            }\n        }\n        for (i = 0; i < natmin; ++i) {\n            ifs_fc2qe >> dummy;\n            for (j = 0; j < 3; ++j) {\n                for (k = 0; k < 3; ++k) {\n                    ifs_fc2qe >> born[i][j][k];\n                }\n            }\n        }\n    }\n\n    // Read force constant info\n\n    ifs_fc2qe >> nq[0] >> nq[1] >> nq[2];\n    nsize = nq[0] * nq[1] * nq[2];\n\n    allocate(fc2, 3 * natmin, 3 * natmin, nsize);\n\n    int icell = 0;\n    int m1, m2, m3;\n    int icrd, jcrd;\n    int iat, jat;\n\n    for (icrd = 0; icrd < 3; ++icrd) {\n        for (jcrd = 0; jcrd < 3; ++jcrd) {\n            for (iat = 0; iat < natmin; ++iat) {\n                for (jat = 0; jat < natmin; ++jat) {\n                    ifs_fc2qe >> dummy >> dummy >> dummy >> dummy;\n\n                    icell = 0;\n                    for (m3 = 0; m3 < nq[2]; ++m3) {\n                        for (m2 = 0; m2 < nq[1]; ++m2) {\n                            for (m1 = 0; m1 < nq[0]; ++m1) {\n                                ifs_fc2qe >> dummy >> dummy >> dummy;\n\n                                // Force constant matrix should be transposed here.\n                                ifs_fc2qe >> fc2[3 * jat + jcrd][3 * iat + icrd][icell];\n\n                                ++icell;\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    if (consider_asr) {\n\n        double sum_fc;\n\n        for (icrd = 0; icrd < 3; ++icrd) {\n            for (jcrd = 0; jcrd < 3; ++jcrd) {\n                for (iat = 0; iat < natmin; ++iat) {\n                    sum_fc = 0.0;\n                    for (jat = 0; jat < natmin; ++jat) {\n                        for (icell = 0; icell < nsize; ++icell) {\n                            sum_fc += fc2[3 * iat + icrd][3 * jat + jcrd][icell];\n                        }\n                    }\n                    fc2[3 * iat + icrd][3 * iat + jcrd][0] -= sum_fc;\n                }\n            }\n        }\n    }\n\n    // Convert positions from alat to crystal basis\n    for (i = 0; i < natmin; ++i) {\n        rotvec(xcrd[i], xcrd[i], rlavec);\n        for (j = 0; j < 3; ++j) {\n            xcrd[i][j] *= celldm[0] / (2.0 * pi);\n        }\n    }\n\n    // Extend the system to the supercell\n\n    nat = natmin * nsize;\n\n    allocate(xcrd_super, nat, 3);\n    allocate(kd_super, nsize, natmin);\n    allocate(map_p2s, nsize, natmin);\n\n    icell = 0;\n    int icount = 0;\n\n    for (m3 = 0; m3 < nq[2]; ++m3) {\n        for (m2 = 0; m2 < nq[1]; ++m2) {\n            for (m1 = 0; m1 < nq[0]; ++m1) {\n                for (i = 0; i < natmin; ++i) {\n                    xcrd_super[icount][0] = (xcrd[i][0] + static_cast<double>(m1)) / static_cast<double>(nq[0]);\n                    xcrd_super[icount][1] = (xcrd[i][1] + static_cast<double>(m2)) / static_cast<double>(nq[1]);\n                    xcrd_super[icount][2] = (xcrd[i][2] + static_cast<double>(m3)) / static_cast<double>(nq[2]);\n                    kd_super[icell][i] = kd[i];\n\n                    map_p2s[icell][i] = icount;\n                    ++icount;\n                }\n                ++icell;\n            }\n        }\n    }\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            lavec[i][j] *= static_cast<double>(nq[j]);\n        }\n    }\n\n    allocate(mindist, natmin, nat);\n\n    get_pairs_of_minimum_distance(natmin, nat, map_p2s, xcrd_super, mindist);\n\n    // Write to XML file\n\n    using boost::property_tree::ptree;\n\n    ptree pt;\n    string str_pos[3], str_tmp;\n\n    str_tmp.clear();\n\n    //    for (i = 0; i < 3; ++i) {\n    //        str_tmp += \" \" + std::to_string(nq[i]);\n    //    }\n\n\n    pt.put(\"Data.FilenameOfQE\", file_fc2qe);\n    //    pt.put(\"Data.Qmesh\", str_tmp);\n\n    pt.put(\"Data.Structure.NumberOfAtoms\", nat);\n    pt.put(\"Data.Structure.NumberOfElements\", nkd);\n\n    for (i = 0; i < nkd; ++i) {\n        ptree &child = pt.add(\"Data.Structure.AtomicElements.element\", kd_symbol[i]);\n        child.put(\"<xmlattr>.number\", i + 1);\n    }\n\n    for (i = 0; i < 3; ++i) {\n        str_pos[i].clear();\n        for (j = 0; j < 3; ++j) {\n            str_pos[i] += \" \" + double2string(lavec[j][i]);\n        }\n    }\n    pt.put(\"Data.Structure.LatticeVector\", \"\");\n    pt.put(\"Data.Structure.LatticeVector.a1\", str_pos[0]);\n    pt.put(\"Data.Structure.LatticeVector.a2\", str_pos[1]);\n    pt.put(\"Data.Structure.LatticeVector.a3\", str_pos[2]);\n\n    pt.put(\"Data.Structure.Position\", \"\");\n\n    icount = 0;\n\n    for (i = 0; i < nsize; ++i) {\n\n        for (j = 0; j < natmin; ++j) {\n            str_tmp.clear();\n            for (k = 0; k < 3; ++k) str_tmp += \" \" + double2string(xcrd_super[map_p2s[i][j]][k]);\n            ptree &child = pt.add(\"Data.Structure.Position.pos\", str_tmp);\n            child.put(\"<xmlattr>.index\", icount + 1);\n            child.put(\"<xmlattr>.element\", kd_symbol[kd_super[i][j] - 1]);\n\n            ++icount;\n        }\n    }\n\n    pt.put(\"Data.Symmetry.NumberOfTranslations\", nsize);\n    for (i = 0; i < nsize; ++i) {\n        for (j = 0; j < natmin; ++j) {\n            ptree &child = pt.add(\"Data.Symmetry.Translations.map\", map_p2s[i][j] + 1);\n            child.put(\"<xmlattr>.tran\", i + 1);\n            child.put(\"<xmlattr>.atom\", j + 1);\n        }\n    }\n\n\n    pt.put(\"Data.ForceConstants\", \"\");\n    str_tmp.clear();\n\n    int nmulti, kat;\n\n    for (iat = 0; iat < natmin; ++iat) {\n        for (icrd = 0; icrd < 3; ++icrd) {\n            for (icell = 0; icell < nsize; ++icell) {\n                for (jat = 0; jat < natmin; ++jat) {\n                    kat = map_p2s[icell][jat];\n                    nmulti = mindist[iat][kat].size();\n                    for (jcrd = 0; jcrd < 3; ++jcrd) {\n                        if (std::abs(fc2[3 * iat + icrd][3 * jat + jcrd][icell]) < eps15) continue;\n                        for (i = 0; i < nmulti; ++i) {\n                            ptree &child = pt.add(\"Data.ForceConstants.HARMONIC.FC2\",\n                                                  double2string(fc2[3 * iat + icrd][3 * jat + jcrd][icell] /\n                                                                static_cast<double>(nmulti)));\n\n                            child.put(\"<xmlattr>.pair1\", boost::lexical_cast<std::string>(iat + 1)\n                                                         + \" \" + boost::lexical_cast<std::string>(icrd + 1));\n                            child.put(\"<xmlattr>.pair2\", boost::lexical_cast<std::string>(kat + 1)\n                                                         + \" \" + boost::lexical_cast<std::string>(jcrd + 1)\n                                                         + \" \" + boost::lexical_cast<std::string>(\n                                    mindist[iat][kat][i].cell + 1));\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n\n    using namespace boost::property_tree::xml_parser;\n    const int indent = 2;\n\n#if BOOST_VERSION >= 105600\n    write_xml(file_xmlout, pt, std::locale(),\n              xml_writer_make_settings<ptree::key_type>(' ', indent, widen<std::string>(\"utf-8\")));\n#else\n    write_xml(file_xmlout, pt, std::locale(),\n              xml_writer_make_settings(' ', indent, widen<char>(\"utf-8\")));\n#endif\n\n\n    deallocate(kd);\n    deallocate(kd_symbol);\n    deallocate(xcrd);\n    deallocate(fc2);\n    deallocate(xcrd_super);\n    deallocate(kd_super);\n    deallocate(map_p2s);\n\n    if (include_na) {\n        deallocate(born);\n    }\n}\n\n\nvoid calc_lattice_vector(const int ibrav, double celldm[6], double aa[3][3])\n{\n    double a, b, c;\n    double alpha, beta, gamma;\n    double tx, ty, tz;\n    double a2, b2, c2;\n    double cosalpha, a_prime, u, v;\n\n    switch (ibrav) {\n        case 1:\n            a = celldm[0];\n            aa[0][0] = a;\n            aa[0][1] = 0.0;\n            aa[0][2] = 0.0;\n            aa[1][0] = 0.0;\n            aa[1][1] = a;\n            aa[1][2] = 0.0;\n            aa[2][0] = 0.0;\n            aa[2][1] = 0.0;\n            aa[2][2] = a;\n\n            break;\n\n        case 2:\n            a = celldm[0] / 2.0;\n            aa[0][0] = -a;\n            aa[0][1] = 0.0;\n            aa[0][2] = a;\n            aa[1][0] = 0.0;\n            aa[1][1] = a;\n            aa[1][2] = a;\n            aa[2][0] = -a;\n            aa[2][1] = a;\n            aa[2][2] = 0.0;\n\n            break;\n\n        case 3:\n            a = celldm[0] / 2.0;\n            aa[0][0] = a;\n            aa[0][1] = a;\n            aa[0][2] = a;\n            aa[1][0] = -a;\n            aa[1][1] = a;\n            aa[1][2] = a;\n            aa[2][0] = -a;\n            aa[2][1] = -a;\n            aa[2][2] = a;\n\n            break;\n\n        case 4:\n            a = celldm[0];\n            c = celldm[0] * celldm[2];\n            aa[0][0] = a;\n            aa[0][1] = 0.0;\n            aa[0][2] = 0.0;\n            aa[1][0] = -0.5 * a;\n            aa[1][1] = sqrt(3.0) / 2.0 * a;\n            aa[1][2] = 0.0;\n            aa[2][0] = 0.0;\n            aa[2][1] = 0.0;\n            aa[2][2] = c;\n\n            break;\n\n        case 5:\n        case -5:\n            a = celldm[0];\n            cosalpha = celldm[3];\n            tx = a * sqrt((1.0 - cosalpha) / 2.0);\n            ty = a * sqrt((1.0 - cosalpha) / 6.0);\n            tz = a * sqrt((1.0 + 2.0 * cosalpha) / 3.0);\n\n            if (ibrav == 5) {\n                aa[0][0] = tx;\n                aa[0][1] = -ty;\n                aa[0][2] = tz;\n                aa[1][0] = 0.0;\n                aa[1][1] = 2.0 * ty;\n                aa[1][2] = tz;\n                aa[2][0] = -tx;\n                aa[2][1] = -ty;\n                aa[2][2] = tz;\n            } else {\n                a_prime = a / sqrt(3.0);\n                u = tz - 2.0 * sqrt(2.0) * ty;\n                v = tz + sqrt(2.0) * ty;\n                aa[0][0] = u;\n                aa[0][1] = v;\n                aa[0][2] = v;\n                aa[1][0] = v;\n                aa[1][1] = u;\n                aa[1][2] = v;\n                aa[2][0] = v;\n                aa[2][1] = v;\n                aa[2][2] = u;\n            }\n\n            break;\n\n        case 6:\n            a = celldm[0];\n            c = celldm[0] * celldm[2];\n            aa[0][0] = a;\n            aa[0][1] = 0.0;\n            aa[0][2] = 0.0;\n            aa[1][0] = 0.0;\n            aa[1][1] = a;\n            aa[1][2] = 0.0;\n            aa[2][0] = 0.0;\n            aa[2][1] = 0.0;\n            aa[2][2] = c;\n\n            break;\n\n        case 7:\n            a = celldm[0];\n            c = celldm[0] * celldm[2];\n            a2 = a * 0.5;\n            c2 = c * 0.5;\n            aa[0][0] = a2;\n            aa[0][1] = -a2;\n            aa[0][2] = c2;\n            aa[1][0] = a2;\n            aa[1][1] = a2;\n            aa[1][2] = c2;\n            aa[2][0] = -a2;\n            aa[2][1] = -a2;\n            aa[2][2] = c2;\n\n            break;\n\n        case 8:\n            a = celldm[0];\n            b = celldm[0] * celldm[1];\n            c = celldm[0] * celldm[2];\n            aa[0][0] = a;\n            aa[0][1] = 0.0;\n            aa[0][2] = 0.0;\n            aa[1][0] = 0.0;\n            aa[1][1] = b;\n            aa[1][2] = 0.0;\n            aa[2][0] = 0.0;\n            aa[2][1] = 0.0;\n            aa[2][2] = c;\n\n            break;\n\n        case 9:\n        case -9:\n            a = celldm[0];\n            b = celldm[0] * celldm[1];\n            c = celldm[0] * celldm[2];\n            a2 = a * 0.5;\n            b2 = b * 0.5;\n\n            if (ibrav == 9) {\n                aa[0][0] = a2;\n                aa[0][1] = b2;\n                aa[0][2] = 0.0;\n                aa[1][0] = -a2;\n                aa[1][1] = b2;\n                aa[1][2] = 0.0;\n                aa[2][0] = 0.0;\n                aa[2][1] = 0.0;\n                aa[2][2] = c;\n            } else {\n                aa[0][0] = a2;\n                aa[0][1] = -b2;\n                aa[0][2] = 0.0;\n                aa[1][0] = a2;\n                aa[1][1] = b2;\n                aa[1][2] = 0.0;\n                aa[2][0] = 0.0;\n                aa[2][1] = 0.0;\n                aa[2][2] = c;\n            }\n\n            break;\n\n        case 10:\n            a2 = celldm[0] * 0.5;\n            b2 = celldm[0] * celldm[1] * 0.5;\n            c2 = celldm[0] * celldm[2] * 0.5;\n            aa[0][0] = a2;\n            aa[0][1] = 0.0;\n            aa[0][2] = c2;\n            aa[1][0] = a2;\n            aa[1][1] = b2;\n            aa[1][2] = 0.0;\n            aa[2][0] = 0.0;\n            aa[2][1] = b2;\n            aa[2][2] = c2;\n\n            break;\n\n        case 11:\n            a2 = celldm[0] * 0.5;\n            b2 = celldm[0] * celldm[1] * 0.5;\n            c2 = celldm[0] * celldm[2] * 0.5;\n            aa[0][0] = a2;\n            aa[0][1] = b2;\n            aa[0][2] = c2;\n            aa[1][0] = -a2;\n            aa[1][1] = b2;\n            aa[1][2] = c2;\n            aa[2][0] = -a2;\n            aa[2][1] = -b2;\n            aa[2][2] = c2;\n\n            break;\n\n        case 12:\n            a = celldm[0];\n            b = celldm[0] * celldm[1];\n            c = celldm[0] * celldm[2];\n            gamma = acos(celldm[3]);\n            aa[0][0] = a;\n            aa[0][1] = 0.0;\n            aa[0][2] = 0.0;\n            aa[1][0] = b * cos(gamma);\n            aa[1][1] = b * sin(gamma);\n            aa[1][2] = 0.0;\n            aa[2][0] = 0.0;\n            aa[2][1] = 0.0;\n            aa[2][2] = c;\n\n            break;\n\n        case -12:\n            a = celldm[0];\n            b = celldm[0] * celldm[1];\n            c = celldm[0] * celldm[2];\n            beta = acos(celldm[4]);\n            aa[0][0] = a;\n            aa[0][1] = 0.0;\n            aa[0][2] = 0.0;\n            aa[1][0] = 0.0;\n            aa[1][1] = b;\n            aa[1][2] = 0.0;\n            aa[2][0] = c * cos(beta);\n            aa[2][1] = 0.0;\n            aa[2][2] = c * sin(beta);\n\n            break;\n\n        case 13:\n            a = celldm[0];\n            b = celldm[0] * celldm[1];\n            c = celldm[0] * celldm[2];\n            gamma = acos(celldm[3]);\n            aa[0][0] = 0.5 * a;\n            aa[0][1] = 0.0;\n            aa[0][2] = -0.5 * c;\n            aa[1][0] = b * cos(gamma);\n            aa[1][1] = b * sin(gamma);\n            aa[1][2] = 0.0;\n            aa[2][0] = 0.5 * a;\n            aa[2][1] = 0.0;\n            aa[2][2] = 0.5 * c;\n\n            break;\n\n        case 14:\n            a = celldm[0];\n            b = celldm[0] * celldm[1];\n            c = celldm[0] * celldm[2];\n            alpha = acos(celldm[3]);\n            beta = acos(celldm[4]);\n            gamma = acos(celldm[5]);\n            aa[0][0] = a;\n            aa[0][1] = 0.0;\n            aa[0][2] = 0.0;\n            aa[1][0] = b * cos(gamma);\n            aa[1][1] = b * sin(gamma);\n            aa[1][2] = 0.0;\n            aa[2][0] = c * cos(beta);\n            aa[2][1] = c * (cos(alpha) - cos(beta) * cos(gamma)) / sin(gamma);\n            aa[2][2] = c * sqrt(1.0 + 2.0 * cos(alpha) * cos(beta) * cos(gamma)\n                                - cos(alpha) * cos(alpha) - cos(beta) * cos(beta) - cos(gamma) * cos(gamma)) /\n                       sin(gamma);\n\n            break;\n\n        default:\n\n            cout << \"ERROR: Invalid ibrav.\" << endl;\n            exit(EXIT_FAILURE);\n    }\n\n\n    // Transpose lavec for later use\n\n    double tmp[3][3];\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            tmp[i][j] = aa[i][j];\n        }\n    }\n\n    for (i = 0; i < 3; ++i) {\n        for (j = 0; j < 3; ++j) {\n            aa[i][j] = tmp[j][i];\n        }\n    }\n}\n\n\nvoid recips(double aa[3][3], double bb[3][3])\n{\n    /*\n    Calculate Reciprocal Lattice Vectors\n\n    Here, BB is just the inverse matrix of AA (multiplied by factor 2 Pi)\n\n    BB = 2 Pi AA^{-1},\n    = t(b1, b2, b3)\n\n    = (b11 b12 b13)\n      (b21 b22 b23)\n      (b31 b32 b33),\n\n    b1 = t(b11, b12, b13) etc.\n    */\n\n    double det;\n    det = aa[0][0] * aa[1][1] * aa[2][2]\n          + aa[1][0] * aa[2][1] * aa[0][2]\n          + aa[2][0] * aa[0][1] * aa[1][2]\n          - aa[0][0] * aa[2][1] * aa[1][2]\n          - aa[2][0] * aa[1][1] * aa[0][2]\n          - aa[1][0] * aa[0][1] * aa[2][2];\n\n    if (std::abs(det) < eps12) {\n        cout << \" ERROR: Lattice vector is singular\" << endl;\n        exit(EXIT_FAILURE);\n    }\n\n    double factor = 2.0 * pi / det;\n\n    bb[0][0] = (aa[1][1] * aa[2][2] - aa[1][2] * aa[2][1]) * factor;\n    bb[0][1] = (aa[0][2] * aa[2][1] - aa[0][1] * aa[2][2]) * factor;\n    bb[0][2] = (aa[0][1] * aa[1][2] - aa[0][2] * aa[1][1]) * factor;\n\n    bb[1][0] = (aa[1][2] * aa[2][0] - aa[1][0] * aa[2][2]) * factor;\n    bb[1][1] = (aa[0][0] * aa[2][2] - aa[0][2] * aa[2][0]) * factor;\n    bb[1][2] = (aa[0][2] * aa[1][0] - aa[0][0] * aa[1][2]) * factor;\n\n    bb[2][0] = (aa[1][0] * aa[2][1] - aa[1][1] * aa[2][0]) * factor;\n    bb[2][1] = (aa[0][1] * aa[2][0] - aa[0][0] * aa[2][1]) * factor;\n    bb[2][2] = (aa[0][0] * aa[1][1] - aa[0][1] * aa[1][0]) * factor;\n}\n\n\nstring double2string(const double d)\n{\n    std::string rt;\n    std::stringstream ss;\n\n    ss << std::scientific << std::setprecision(15) << d;\n    ss >> rt;\n    return rt;\n}\n\n\nvoid get_pairs_of_minimum_distance(const int natmin, const int nat, int **map_p2s,\n                                   double **xf, std::vector<DistInfo> **mindist_pairs)\n{\n    int icell = 0;\n    int i, j, k;\n    int isize, jsize, ksize;\n    int iat;\n    double dist_tmp;\n    double vec[3];\n    std::vector<DistInfo> **distall;\n    int nneib = 27;\n\n    double ***xcrd;\n\n    allocate(distall, natmin, nat);\n    allocate(xcrd, nneib, nat, 3);\n\n    for (i = 0; i < nat; ++i) {\n        for (j = 0; j < 3; ++j) {\n            xcrd[0][i][j] = xf[i][j];\n        }\n    }\n\n    for (isize = -1; isize <= 1; ++isize) {\n        for (jsize = -1; jsize <= 1; ++jsize) {\n            for (ksize = -1; ksize <= 1; ++ksize) {\n\n                if (isize == 0 && jsize == 0 && ksize == 0) continue;\n\n                ++icell;\n                for (i = 0; i < nat; ++i) {\n                    xcrd[icell][i][0] = xf[i][0] + static_cast<double>(isize);\n                    xcrd[icell][i][1] = xf[i][1] + static_cast<double>(jsize);\n                    xcrd[icell][i][2] = xf[i][2] + static_cast<double>(ksize);\n                }\n            }\n        }\n    }\n\n    for (icell = 0; icell < nneib; ++icell) {\n        for (i = 0; i < nat; ++i) {\n            rotvec(xcrd[icell][i], xcrd[icell][i], lavec);\n        }\n    }\n\n\n    for (i = 0; i < natmin; ++i) {\n        iat = map_p2s[0][i];\n        for (j = 0; j < nat; ++j) {\n            for (icell = 0; icell < nneib; ++icell) {\n\n                dist_tmp = distance(xcrd[0][iat], xcrd[icell][j]);\n\n                for (k = 0; k < 3; ++k) vec[k] = xcrd[icell][j][k] - xcrd[0][iat][k];\n\n                distall[i][j].push_back(DistInfo(icell, dist_tmp, vec));\n            }\n            std::sort(distall[i][j].begin(), distall[i][j].end());\n        }\n        /*\n                for (j = 0; j < nat; ++j) {\n                    for (k = 0; k < distall[i][j].size(); ++k) {\n                        std::cout << std::setw(5) << i + 1;\n                        std::cout << std::setw(5) << j + 1;\n                        std::cout << std::setw(5) << k + 1;\n                        std::cout << std::setw(15) << distall[i][j][k].dist << endl;\n                    }\n                }\n        */\n    }\n\n    // Construct pairs of minimum distance.\n\n    double dist_min;\n    for (i = 0; i < natmin; ++i) {\n        for (j = 0; j < nat; ++j) {\n            mindist_pairs[i][j].clear();\n\n            dist_min = distall[i][j][0].dist;\n            for (std::vector<DistInfo>::const_iterator it = distall[i][j].begin(); it != distall[i][j].end(); ++it) {\n                if (std::abs((*it).dist - dist_min) < 1.e-3) {\n                    mindist_pairs[i][j].push_back(DistInfo(*it));\n                }\n            }\n        }\n    }\n\n    deallocate(distall);\n    deallocate(xcrd);\n}\n\n\ndouble distance(double *x1, double *x2)\n{\n    double dist;\n    dist = std::pow(x1[0] - x2[0], 2) + std::pow(x1[1] - x2[1], 2) + std::pow(x1[2] - x2[2], 2);\n    dist = std::sqrt(dist);\n\n    return dist;\n}\n", "meta": {"hexsha": "70c729aa64a5de2906b24ae2769bc901c509b673", "size": 23028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/qe2alm.cpp", "max_stars_repo_name": "r-masuki/alamode", "max_stars_repo_head_hexsha": "6a75ac277e1e4bdaff4218b28a8d9ab7e5130b3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 93.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T17:19:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T14:26:02.000Z", "max_issues_repo_path": "tools/qe2alm.cpp", "max_issues_repo_name": "r-masuki/alamode", "max_issues_repo_head_hexsha": "6a75ac277e1e4bdaff4218b28a8d9ab7e5130b3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2016-05-28T12:31:55.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-24T05:46:08.000Z", "max_forks_repo_path": "tools/qe2alm.cpp", "max_forks_repo_name": "r-masuki/alamode", "max_forks_repo_head_hexsha": "6a75ac277e1e4bdaff4218b28a8d9ab7e5130b3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T02:17:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-04T09:13:40.000Z", "avg_line_length": 28.2205882353, "max_line_length": 117, "alphanum_fraction": 0.3900468994, "num_tokens": 7891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6001883449573377, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.20925274675350794}}
{"text": "#include <chrono>\n#include <cmath>\n#include <exception>\n#include <thread>\n\n#include <boost/log/trivial.hpp>\n#include <casadi/casadi.hpp>\n\n#include \"mimir/algorithm/TestAlgorithm.hpp\"\n#include \"mimir/StateMachineFwd.hpp\"\n#include \"mimir/FkinDds.hpp\"\n\n// ReaderLifespan\n#include \"dds/core/detail/ProprietaryApi.hpp\"\n\nnamespace mimir\n{\n  namespace algorithm\n  {\n    class TestAlgorithm::Impl\n    {\n    public:\n      Impl(\n          const YAML::Node& config,\n          dds::pub::Publisher publisher,\n          dds::sub::Subscriber subscriber) :\n        inputReader(dds::core::null),\n        outputWriter(dds::core::null)\n      {\n\n        // Setup input reader\n        const auto test_config = config[\"inputs\"][\"signal\"];\n        auto test_age = test_config[\"max_age_ms\"].as<std::int64_t>();\n\n        auto readerQos = subscriber.default_datareader_qos();\n        //readerQos << dds::core::policy::Durability::TransientLocal()\n        //          << dds::core::policy::Reliability::Reliable()\n        readerQos << org::opensplice::core::policy::ReaderLifespan(\n                      true,\n                      dds::core::Duration::from_millisecs(test_age));\n\n        const auto topicName = test_config[\"topic\"].as<std::string>();\n        const auto id = test_config[\"id\"].as<std::string>(); // For filter topic\n        auto topic = dds::topic::Topic<fkin::IdVec1d>(\n            subscriber.participant(),\n            topicName);\n        auto filter = dds::topic::Filter(\"id = %0\", {id});\n\n        inputReader = dds::sub::DataReader<fkin::IdVec1d>(\n            subscriber,\n            dds::topic::ContentFilteredTopic<fkin::IdVec1d>(\n                topic,\n                topicName + id,\n                filter),\n            readerQos);\n\n        // Setup output writer\n        auto writerQos = publisher.default_datawriter_qos();\n        //writerQos << dds::core::policy::Durability::TransientLocal();\n\n        outputWriter = dds::pub::DataWriter<fkin::IdVec1d>(\n            publisher,\n            dds::topic::Topic<fkin::IdVec1d>(\n                publisher.participant(),\n                config[\"outputs\"][\"response\"][\"topic\"].as<std::string>()),\n            writerQos);\n\n        outputId = config[\"outputs\"][\"response\"][\"id\"].as<std::string>();\n\n        // Setup model description\n        casadi::SX x = casadi::SX::sym(\"x\", 1);     // state\n        casadi::SX x_d = casadi::SX::sym(\"x_d\", 1); // set-point\n        casadi::SX T = casadi::SX::sym(\"T\", 1);     // time constant\n        casadi::SX rhs = -(x-x_d)/T;                // prop-ctrl with time constant T\n        casadi::SXDict ode = {{\"x\", x}, {\"p\", vertcat(x_d,T)}, {\"ode\", rhs}};\n\n        integrator = casadi::integrator(\n            \"F\", \"cvodes\", ode,\n            {{\"tf\", config[\"time_step_ms\"].as<double>()/1000.}});\n\n        p_vec = casadi::DM(std::vector<double>{5.,5.});\n\n      }\n      ~Impl() {}\n      dds::sub::DataReader<fkin::IdVec1d> inputReader;\n      dds::pub::DataWriter<fkin::IdVec1d> outputWriter;\n      std::string outputId;\n      casadi::Function integrator;\n      casadi::DM p_vec;\n      casadi::DM x_k;\n    };\n\n    TestAlgorithm::TestAlgorithm(\n        const YAML::Node& config,\n        boost::statechart::fifo_scheduler<> & scheduler,\n        boost::statechart::fifo_scheduler<>::processor_handle machine,\n        dds::pub::Publisher publisher,\n        dds::sub::Subscriber subscriber) :\n      m_impl( new TestAlgorithm::Impl(config, publisher, subscriber)),\n      m_scheduler(scheduler),\n      m_stateMachine(machine),\n      m_time_step(std::chrono::milliseconds(config[\"time_step_ms\"].as<std::int32_t>())),\n      m_next_step(std::chrono::steady_clock::now()),\n      m_config(config)\n    {}\n    void TestAlgorithm::solve(const std::atomic<bool>& cancel_token)\n    {\n      try\n      {\n        BOOST_LOG_TRIVIAL(trace) << \"Solving \" << name();\n\n        // Publish x_k(t_now) (we do not publish future samples)\n        m_impl->outputWriter << fkin::IdVec1d(\n            m_impl->outputId,\n            fkin::Vector1d(m_impl->x_k.get_nonzeros()[0]));\n\n        // Fetch input, sample and hold\n        auto samples = m_impl->inputReader.read();\n        // waitset with short timeout, allowing run in \"open loop\"\n\n        // Set new desired value\n        if(samples.length() > 0)\n        {\n          auto sample = (--samples.end());\n          if(sample->info().valid())\n          {\n            m_impl->p_vec(0,0) = sample->data().vec().x();\n            BOOST_LOG_TRIVIAL(trace) << \"Got a sample: \" << sample->data().vec().x();\n          }\n        }\n        else\n        {\n          // TODO: In case of measurements: Disable feedback gain\n          BOOST_LOG_TRIVIAL(trace) << \"No valid sample for \" << name() << \", using old\";\n        }\n\n        if(cancel_token)\n        {\n          event(new mimir::EvInterrupt());\n          return;\n        }\n\n        // Integrate\n        auto result = m_impl->integrator(\n            casadi::DMDict( {{\"x0\",m_impl->x_k}, {\"p\", m_impl->p_vec}} ));\n\n        if(cancel_token)\n        {\n          event(new mimir::EvInterrupt());\n          return;\n        }\n\n        // Update output (not published yet)\n        m_impl->x_k = result[\"xf\"];\n        step_time();\n        event(new mimir::EvReady());\n\n      }\n      catch (...)\n      {\n        // Need to post event in case of exception so that the state machine\n        // knows that the job has finished.\n        BOOST_LOG_TRIVIAL(fatal) << name() << \" exception thrown\";\n        event(new mimir::EvError());\n        throw;\n      }\n    }\n\n    void TestAlgorithm::initialize(const std::atomic<bool>&)\n    {\n      try\n      {\n        BOOST_LOG_TRIVIAL(debug) << name() << \" is initializing\";\n\n        // waitset to get initial measurements that meet requirements.\n        // set initial state vector..\n        m_impl->x_k = casadi::DM(std::vector<double>{0.});\n        // set parameters as well?\n        m_next_step = std::chrono::steady_clock::now();\n\n        event(new mimir::EvReady());\n      }\n      catch (...)\n      {\n        event(new mimir::EvError());\n        throw;\n      }\n    }\n\n    void TestAlgorithm::timer(const std::atomic<bool>& cancel_token)\n    {\n\n      // There is no sanity checks in terms of real-timeliness of execution.\n      // probably want external time point to wait until.\n      typedef std::chrono::milliseconds scm;\n      auto now = std::chrono::steady_clock::now();\n      auto time_p = m_next_step;\n      auto timeleft = std::chrono::duration_cast<scm>(time_p - now).count();\n      BOOST_LOG_TRIVIAL(trace) << \"Time left: \" << timeleft;\n\n      auto fraction = (m_time_step/100 > scm(0) ? m_time_step/100 :\n       (m_time_step/50 > scm(0) ? m_time_step/50 :\n        (m_time_step/25 > scm(0) ? m_time_step/25 :\n         (m_time_step/10 > scm(0) ? m_time_step/10 :\n          (m_time_step/2 > scm(0) ?  m_time_step/2  : scm(1))))));\n\n      while(now < time_p)\n      {\n        auto diff = time_p - now;\n        std::this_thread::sleep_for(diff < fraction ? diff : fraction);\n        if(cancel_token)\n          break;\n        now = std::chrono::steady_clock::now();\n      }\n\n      if(cancel_token)\n      {\n        BOOST_LOG_TRIVIAL(trace) << \"Timer Canceled\";\n        event(new mimir::EvInterrupt());\n      }\n      else\n      {\n        BOOST_LOG_TRIVIAL(trace) << \"Timeout\";\n        event(new mimir::EvTimeout());\n      }\n    }\n\n    void TestAlgorithm::event(boost::statechart::event_base * const event)\n    {\n      // who is responsible for the pointer?\n      m_scheduler.queue_event(\n          m_stateMachine,\n          make_intrusive(event));\n    }\n\n    TestAlgorithm::~TestAlgorithm() = default;\n  }\n}\n", "meta": {"hexsha": "f9de72ca6043969bffdc62ecf65dd84ab501dcc3", "size": 7580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mimir/algorithm/TestAlgorithm.cpp", "max_stars_repo_name": "sintef-ocean/mimir", "max_stars_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mimir/algorithm/TestAlgorithm.cpp", "max_issues_repo_name": "sintef-ocean/mimir", "max_issues_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mimir/algorithm/TestAlgorithm.cpp", "max_forks_repo_name": "sintef-ocean/mimir", "max_forks_repo_head_hexsha": "c1d9671ee61e543e631f04d8b343a8f5e9229f6f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7154811715, "max_line_length": 88, "alphanum_fraction": 0.5645118734, "num_tokens": 1896, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.41489884579676883, "lm_q1q2_score": 0.20907008854238526}}
{"text": "///////////////////////////////////////////////////////////////////////////////\n// Orkid\n// Copyrigh 1996-2009, Michael T. Mayers\n// See License at OrkidRoot/license.html or http://www.tweakoz.com/orkid/license.html\n///////////////////////////////////////////////////////////////////////////////\n\n#include <ork/pch.h>\n\n#include <cmath>\n#include <ork/orkconfig.h>\n#include <ork/orktypes.h>\n#include <ork/math/cfloat.h>\n#include <ork/math/spheretree.h>\n#include <ork/math/raytracer.h>\n#include <ork/math/sphere.h>\n#include <ork/math/plane.h>\n#include <ork/math/octree.h>\n#include <ork/math/collision_test.h>\n#include <ork/kernel/Array.h>\n#include <ork/kernel/Array.hpp>\n#include <ork/kernel/gstack.h>\n#include <ork/file/chunkfile.h>\n#include <ork/file/chunkfile.inl>\n#include <queue>\n//#include <boost/gil/typedefs.hpp>\n//#include <boost/cast.hpp>\n//#include <boost/gil/extension/io/png_dynamic_io.hpp>\n//#include <IL/il.h>\n//#include <IL/ilut.h>\n//#include <pthread.h>\n\n#if defined(ORK_CONFIG_IX)\n#include <unistd.h>\n#endif\n\ns64 giNumRays = 0;\n\nnamespace ork {\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nstatic const int kIW       = 2048;\nstatic const int kOS       = 0;\nstatic const float kJITTER = 0.5f; // 0.5\n\nstatic int GetNumCores() {\n  return OldSchool::GetNumCores();\n}\n\nvoid RgmTri::Compute() {\n  mFacePlane.CalcPlaneFromTriangle(mpv0->pos, mpv1->pos, mpv2->pos);\n  const fvec3 vn = mFacePlane.n;\n  mEdgePlane0.CalcPlaneFromTriangle(mpv0->pos, vn + mpv0->pos, mpv1->pos);\n  mEdgePlane1.CalcPlaneFromTriangle(mpv1->pos, vn + mpv1->pos, mpv2->pos);\n  mEdgePlane2.CalcPlaneFromTriangle(mpv2->pos, vn + mpv2->pos, mpv0->pos);\n  mArea = (mpv0->pos - mpv2->pos).Cross(mpv1->pos - mpv2->pos).Mag() * 0.5f;\n}\n\nJitterer::Jitterer(int ikos, float fradius, const fvec3& dX, const fvec3& dY) {\n  miKos = ikos;\n\n  int idim     = (miKos * 2) + 1;\n  miNumSamples = idim * idim;\n\n  int isamp = 0;\n\n  int idiv = (ikos == 0) ? 1 : ikos;\n\n  for (int iy = -ikos; iy <= ikos; iy++) {\n    float fy = fradius * float(iy) / float(idiv);\n    for (int ix = -ikos; ix <= ikos; ix++) {\n      float fx        = fradius * float(ix) / float(idiv);\n      sample[isamp++] = dX * fx + dY * fy;\n    }\n  }\n  OrkAssert(isamp == miNumSamples);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nMaterial::Material()\n    : mColor(0.2f, 0.2f, 0.2f)\n    , m_Refl(0)\n    , m_Diff(0.2f)\n    , m_Spec(0.8f)\n    , m_RIndex(1.5f)\n    , m_DRefl(0) {\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid Material::SetParameters(float a_Refl, float a_Refr, const fvec3& a_Col, float a_Diff, float a_Spec) {\n  m_Refl = a_Refl;\n  m_Refr = a_Refr;\n  mColor = a_Col;\n  m_Diff = a_Diff;\n  m_Spec = a_Spec;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nPrimitive::~Primitive() {\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nfvec3 Primitive::GetColor(const fvec3& a_Pos) const {\n  return mMaterial->GetColor();\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\n#define FINDMINMAX(x0, x1, x2, min, max)                                                                                           \\\n  min = max = x0;                                                                                                                  \\\n  if (x1 < min)                                                                                                                    \\\n    min = x1;                                                                                                                      \\\n  if (x1 > max)                                                                                                                    \\\n    max = x1;                                                                                                                      \\\n  if (x2 < min)                                                                                                                    \\\n    min = x2;                                                                                                                      \\\n  if (x2 > max)                                                                                                                    \\\n    max = x2;\n// X-tests\n#define AXISTEST_X01(a, b, fa, fb)                                                                                                 \\\n  p0 = a * v0[1] - b * v0[2], p2 = a * v2[1] - b * v2[2];                                                                          \\\n  if (p0 < p2) {                                                                                                                   \\\n    min = p0;                                                                                                                      \\\n    max = p2;                                                                                                                      \\\n  } else {                                                                                                                         \\\n    min = p2;                                                                                                                      \\\n    max = p0;                                                                                                                      \\\n  }                                                                                                                                \\\n  rad = fa * a_BoxHalfsize[1] + fb * a_BoxHalfsize[2];                                                                             \\\n  if (min > rad || max < -rad)                                                                                                     \\\n    return 0;\n#define AXISTEST_X2(a, b, fa, fb)                                                                                                  \\\n  p0 = a * v0[1] - b * v0[2], p1 = a * v1[1] - b * v1[2];                                                                          \\\n  if (p0 < p1) {                                                                                                                   \\\n    min = p0;                                                                                                                      \\\n    max = p1;                                                                                                                      \\\n  } else {                                                                                                                         \\\n    min = p1;                                                                                                                      \\\n    max = p0;                                                                                                                      \\\n  }                                                                                                                                \\\n  rad = fa * a_BoxHalfsize[1] + fb * a_BoxHalfsize[2];                                                                             \\\n  if (min > rad || max < -rad)                                                                                                     \\\n    return 0;\n// Y-tests\n#define AXISTEST_Y02(a, b, fa, fb)                                                                                                 \\\n  p0 = -a * v0[0] + b * v0[2], p2 = -a * v2[0] + b * v2[2];                                                                        \\\n  if (p0 < p2) {                                                                                                                   \\\n    min = p0;                                                                                                                      \\\n    max = p2;                                                                                                                      \\\n  } else {                                                                                                                         \\\n    min = p2;                                                                                                                      \\\n    max = p0;                                                                                                                      \\\n  }                                                                                                                                \\\n  rad = fa * a_BoxHalfsize[0] + fb * a_BoxHalfsize[2];                                                                             \\\n  if (min > rad || max < -rad)                                                                                                     \\\n    return 0;\n#define AXISTEST_Y1(a, b, fa, fb)                                                                                                  \\\n  p0 = -a * v0[0] + b * v0[2], p1 = -a * v1[0] + b * v1[2];                                                                        \\\n  if (p0 < p1) {                                                                                                                   \\\n    min = p0;                                                                                                                      \\\n    max = p1;                                                                                                                      \\\n  } else {                                                                                                                         \\\n    min = p1;                                                                                                                      \\\n    max = p0;                                                                                                                      \\\n  }                                                                                                                                \\\n  rad = fa * a_BoxHalfsize[0] + fb * a_BoxHalfsize[2];                                                                             \\\n  if (min > rad || max < -rad)                                                                                                     \\\n    return 0;\n// Z-tests\n#define AXISTEST_Z12(a, b, fa, fb)                                                                                                 \\\n  p1 = a * v1[0] - b * v1[1], p2 = a * v2[0] - b * v2[1];                                                                          \\\n  if (p2 < p1) {                                                                                                                   \\\n    min = p2;                                                                                                                      \\\n    max = p1;                                                                                                                      \\\n  } else {                                                                                                                         \\\n    min = p1;                                                                                                                      \\\n    max = p2;                                                                                                                      \\\n  }                                                                                                                                \\\n  rad = fa * a_BoxHalfsize[0] + fb * a_BoxHalfsize[1];                                                                             \\\n  if (min > rad || max < -rad)                                                                                                     \\\n    return 0;\n#define AXISTEST_Z0(a, b, fa, fb)                                                                                                  \\\n  p0 = a * v0[0] - b * v0[1], p1 = a * v1[0] - b * v1[1];                                                                          \\\n  if (p0 < p1) {                                                                                                                   \\\n    min = p0;                                                                                                                      \\\n    max = p1;                                                                                                                      \\\n  } else {                                                                                                                         \\\n    min = p1;                                                                                                                      \\\n    max = p0;                                                                                                                      \\\n  }                                                                                                                                \\\n  rad = fa * a_BoxHalfsize[0] + fb * a_BoxHalfsize[1];                                                                             \\\n  if (min > rad || max < -rad)                                                                                                     \\\n    return 0;\n\n///////////////////////////////////////////////////////////////////////////////\n\nbool Primitive::PlaneBoxOverlap(const fvec3& a_Normal, const fvec3& a_Vert, const fvec3& a_MaxBox) {\n  fvec3 vmin, vmax;\n  for (int q = 0; q < 3; q++) {\n    float v = a_Vert[q];\n    if (a_Normal[q] > 0.0f) {\n      vmin[q] = -a_MaxBox[q] - v;\n      vmax[q] = a_MaxBox[q] - v;\n    } else {\n      vmin[q] = a_MaxBox[q] - v;\n      vmax[q] = -a_MaxBox[q] - v;\n    }\n  }\n  if (a_Normal.Dot(vmin) > 0.0f)\n    return false;\n  if (a_Normal.Dot(vmax) >= 0.0f)\n    return true;\n  return false;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nbool Primitive::IntersectTriBox(\n    const fvec3& a_BoxCentre,\n    const fvec3& a_BoxHalfsize,\n    const fvec3& a_V0,\n    const fvec3& a_V1,\n    const fvec3& a_V2) {\n  fvec3 v0, v1, v2, normal, e0, e1, e2;\n  float min, max, p0, p1, p2, rad, fex, fey, fez;\n  v0 = a_V0 - a_BoxCentre;\n  v1 = a_V1 - a_BoxCentre;\n  v2 = a_V2 - a_BoxCentre;\n  e0 = v1 - v0, e1 = v2 - v1, e2 = v0 - v2;\n  fex = fabsf(e0[0]);\n  fey = fabsf(e0[1]);\n  fez = fabsf(e0[2]);\n  AXISTEST_X01(e0[2], e0[1], fez, fey);\n  AXISTEST_Y02(e0[2], e0[0], fez, fex);\n  AXISTEST_Z12(e0[1], e0[0], fey, fex);\n  fex = fabsf(e1[0]);\n  fey = fabsf(e1[1]);\n  fez = fabsf(e1[2]);\n  AXISTEST_X01(e1[2], e1[1], fez, fey);\n  AXISTEST_Y02(e1[2], e1[0], fez, fex);\n  AXISTEST_Z0(e1[1], e1[0], fey, fex);\n  fex = fabsf(e2[0]);\n  fey = fabsf(e2[1]);\n  fez = fabsf(e2[2]);\n  AXISTEST_X2(e2[2], e2[1], fez, fey);\n  AXISTEST_Y1(e2[2], e2[0], fez, fex);\n  AXISTEST_Z12(e2[1], e2[0], fey, fex);\n  FINDMINMAX(v0[0], v1[0], v2[0], min, max);\n  if (min > a_BoxHalfsize[0] || max < -a_BoxHalfsize[0])\n    return false;\n  FINDMINMAX(v0[1], v1[1], v2[1], min, max);\n  if (min > a_BoxHalfsize[1] || max < -a_BoxHalfsize[1])\n    return false;\n  FINDMINMAX(v0[2], v1[2], v2[2], min, max);\n  if (min > a_BoxHalfsize[2] || max < -a_BoxHalfsize[2])\n    return false;\n  normal = e0.Cross(e1);\n  if (!PlaneBoxOverlap(normal, v0, a_BoxHalfsize))\n    return false;\n  return true;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nRaytTriangle::RaytTriangle(const RgmVertex* v1, const RgmVertex* v2, const RgmVertex* v3) {\n  mMaterial  = 0;\n  mVertex[0] = v1;\n  mVertex[1] = v2;\n  mVertex[2] = v3;\n\n  //////////////////////////////////////\n  // precompute what we can\n  //////////////////////////////////////\n\n  fvec3 A = mVertex[0]->pos;\n  fvec3 B = mVertex[1]->pos;\n  fvec3 C = mVertex[2]->pos;\n  fvec3 c = B - A;\n  fvec3 b = C - A;\n  mN      = b.Cross(c);\n  int u, v;\n  if (fabs(mN.x) > fabs(mN.y)) {\n    if (fabs(mN.x) > fabs(mN.z))\n      k = 0;\n    else\n      k = 2;\n  } else {\n    if (fabs(mN.y) > fabs(mN.z))\n      k = 1;\n    else\n      k = 2;\n  }\n  u = (k + 1) % 3;\n  v = (k + 2) % 3;\n  // precomp\n  float krec = 1.0f / mN[k];\n  nu         = mN[u] * krec;\n  nv         = mN[v] * krec;\n  nd         = mN.Dot(A) * krec;\n  // first line equation\n  float reci = 1.0f / (b[u] * c[v] - b[v] * c[u]);\n  bnu        = b[u] * reci;\n  bnv        = -b[v] * reci;\n  // second line equation\n  cnu = c[v] * reci;\n  cnv = -c[u] * reci;\n  // finalize normal\n  mN.Normalize();\n  // mVertex[0]->SetNormal( m_N );\n  // mVertex[1]->SetNormal( m_N );\n  // mVertex[2]->SetNormal( m_N );\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nAABox RaytTriangle::GetAABox() const {\n  AABox ret;\n  ret.BeginGrow();\n  ret.Grow(mVertex[0]->pos);\n  ret.Grow(mVertex[1]->pos);\n  ret.Grow(mVertex[2]->pos);\n  ret.EndGrow();\n  return ret;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nint RaytTriangle::Intersect(const fray3& a_Ray, fvec3& isect, float& a_Dist) const {\n  const RgmTri* tri  = this->mRgmPoly;\n  const fvec3& v0    = mVertex[0]->pos;\n  const fvec3& v1    = mVertex[1]->pos;\n  const fvec3& v2    = mVertex[2]->pos;\n  const fplane3& fp  = tri->mFacePlane;\n  const fplane3& ep0 = tri->mEdgePlane0;\n  const fplane3& ep1 = tri->mEdgePlane1;\n  const fplane3& ep2 = tri->mEdgePlane2;\n  float s, t;\n  bool bv = CollisionTester::RayTriangleTest(a_Ray, fp, ep0, ep1, ep2, isect, a_Dist);\n  return bv;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nfvec3 RaytTriangle::GetNormal(const fvec3& a_Pos) const {\n  fvec3 N1 = mVertex[0]->nrm;\n  fvec3 N2 = mVertex[1]->nrm;\n  fvec3 N3 = mVertex[2]->nrm;\n  fvec3 N  = N1 + mU * (N2 - N1) + mV * (N3 - N1);\n  N.Normalize();\n  return N;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nbool RaytTriangle::IntersectBox(const AABox& a_Box) const {\n  return IntersectTriBox(\n      a_Box.Min() + a_Box.GetSize() * 0.5f, a_Box.GetSize() * 0.5f, mVertex[0]->pos, mVertex[1]->pos, mVertex[2]->pos);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid RaytTriangle::Rasterize(Engine* peng) const {\n  int iw = peng->width();\n  int ih = peng->height();\n\n  const BakeShader* bshader = GetBakeShader();\n  const fvec2& uv0          = mRgmPoly->mpv0->uv;\n  const fvec2& uv1          = mRgmPoly->mpv1->uv;\n  const fvec2& uv2          = mRgmPoly->mpv2->uv;\n\n  fvec3 v0(uv0.x * iw, uv0.y * ih, 0.0f);\n  fvec3 v1(uv1.x * iw, uv1.y * ih, 0.0f);\n  fvec3 v2(uv2.x * iw, uv2.y * ih, 0.0f);\n\n  BakeShadowFragment bv0, bv1, bv2;\n  bv0.mPos = mRgmPoly->mpv0->pos;\n  bv1.mPos = mRgmPoly->mpv1->pos;\n  bv2.mPos = mRgmPoly->mpv2->pos;\n  bv0.mNrm = mRgmPoly->mpv0->nrm;\n  bv1.mNrm = mRgmPoly->mpv1->nrm;\n  bv2.mNrm = mRgmPoly->mpv2->nrm;\n\n  peng->RasterizeTriangle(\n      *bshader, int(v0.x), int(v0.y), bv0, int(v1.x), int(v1.y), bv1, int(v2.x), int(v2.y), bv2);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nRaytSphere::RaytSphere(fvec3& center, float radius) {\n  mCenter   = center;\n  mSqRadius = radius * radius;\n  mRadius   = radius;\n  mRRadius  = 1.0f / radius;\n  // mMaterial = new Material();\n  // set vectors for texture mapping\n  mVn = fvec3(0, 1, 0);\n  mVe = fvec3(1, 0, 0);\n  mVc = mVn.Cross(mVe);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nbool RaytSphere::IntersectSphereBox(const fvec3& a_Centre, const AABox& a_Box) const {\n  float dmin  = 0;\n  fvec3 spos  = a_Centre;\n  fvec3 bpos  = a_Box.Min();\n  fvec3 bsize = a_Box.GetSize();\n  for (int i = 0; i < 3; i++) {\n    if (spos[i] < bpos[i]) {\n      dmin = dmin + (spos[i] - bpos[i]) * (spos[i] - bpos[i]);\n    } else if (spos[i] > (bpos[i] + bsize[i])) {\n      dmin = dmin + (spos[i] - (bpos[i] + bsize[i])) * (spos[i] - (bpos[i] + bsize[i]));\n    }\n  }\n  return (dmin <= mSqRadius);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nbool RaytSphere::IntersectBox(const AABox& a_Box) const {\n  return IntersectSphereBox(mCenter, a_Box);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid RaytSphere::Rasterize(Engine* peng) const {\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nAABox RaytSphere::GetAABox() const {\n  AABox ret;\n  return ret;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nint RaytSphere::Intersect(const fray3& a_Ray, fvec3& isect, float& a_Dist) const {\n  fvec3 v    = a_Ray.mOrigin - mCenter;\n  float b    = -v.Dot(a_Ray.mDirection);\n  float det  = (b * b) - v.Dot(v) + mSqRadius;\n  int retval = MISS;\n  if (det > 0) {\n    det      = sqrtf(det);\n    float i1 = b - det;\n    float i2 = b + det;\n    if (i2 > 0) {\n      if (i1 < 0) {\n        if (i2 < a_Dist) {\n          a_Dist = i2;\n          retval = INPRIM;\n        }\n      } else {\n        if (i1 < a_Dist) {\n          a_Dist = i1;\n          retval = HIT;\n        }\n      }\n    }\n  }\n  return retval;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nfvec3 RaytSphere::GetNormal(const fvec3& a_Pos) const {\n  return (a_Pos - mCenter) * mRRadius;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nScene::Scene()\n    : mExtends()\n    , mpFixedGrid(0) {\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nScene::~Scene() {\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid Scene::ExitScene() {\n  if (mpFixedGrid)\n    delete mpFixedGrid;\n  mpFixedGrid = 0;\n}\n\nbool Scene::InitScene(const AABox& scene_box) {\n  // Material* mat = new Material();\n  // mat->SetParameters( 0.0f, 0.0f, fvec3( 0.4f, 0.3f, 0.3f ), 1.0f, 0.0f );\n  // mat = new Material();\n  // mat->SetParameters( 0.0f, 0.0f, fvec3( 0.5f, 0.3f, 0.5f ), 0.6f, 0.0f );\n  // mat = new Material();\n  // mat->SetParameters( 0.0f, 0.0f, fvec3( 0.4f, 0.7f, 0.7f ), 0.5f, 0.0f );\n  // mat = new Material();\n  // mat->SetParameters( 0.9f, 0, fvec3( 0.9f, 0.9f, 1 ), 0.3f, 0.7f );\n  // mat->SetRefrIndex( 1.3f );\n\n  mExtends = scene_box;\n\n  mpFixedGrid = new FixedGrid;\n\n  orkvector<const Primitive*> Prims;\n\n  for (orkmap<std::string, const RgmGeoSet*>::const_iterator it = mGeoSets.begin(); it != mGeoSets.end(); it++) {\n    const std::string& name = it->first;\n    const RgmGeoSet* pset   = it->second;\n\n    // if( name.find( \"caster_\" ) != std::string::npos )\n    {\n      int inump = pset->NumPrimitives();\n      for (int ip = 0; ip < inump; ip++) {\n        const Primitive* prim = pset->GetPrimitive(ip);\n\n        Prims.push_back(prim);\n      }\n    }\n  }\n\n  mpFixedGrid->BuildGrid(scene_box, Prims);\n\n  return true;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nvoid RgmLightContainer::LoadLitFile(const char* pfilename) {\n  chunkfile::DefaultLoadAllocator allocator;\n  chunkfile::Reader chunkreader(pfilename, \"lit\", allocator);\n  if (chunkreader.IsOk()) {\n    chunkfile::InputStream* HeaderStream = chunkreader.GetStream(\"header\");\n    ///////////////////////////////////////////////////\n    int inumlights = 0;\n    HeaderStream->GetItem(inumlights);\n    for (int il = 0; il < inumlights; il++) {\n      int iname, itype;\n      fmtx4 mtxW;\n      fvec3 clr;\n      float intens;\n      int icastsshadows;\n      HeaderStream->GetItem(iname);\n      HeaderStream->GetItem(mtxW);\n      HeaderStream->GetItem(clr);\n      HeaderStream->GetItem(intens);\n      HeaderStream->GetItem(icastsshadows);\n      HeaderStream->GetItem(itype);\n      const char* pname = chunkreader.GetString(iname);\n      const char* ptype = chunkreader.GetString(itype);\n\n      if (0 == strcmp(ptype, \"PointLight\")) {\n        RgmLight rlite(fvec3::Black(), clr);\n        HeaderStream->GetItem(rlite.mPos);\n        HeaderStream->GetItem(rlite.mFalloff);\n        HeaderStream->GetItem(rlite.mRadius);\n\n        rlite.mCastsShadows = bool(icastsshadows);\n        mLights[pname]      = rlite;\n      } else // Dir Light\n      {\n        RgmLight rlite(mtxW.GetTranslation(), clr);\n\n        rlite.mDir          = mtxW.GetZNormal();\n        rlite.mCastsShadows = bool(icastsshadows);\n        mLights[pname]      = rlite;\n      }\n    }\n  }\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nRgmModel* LoadRgmFile(const char* pfilename, RgmShaderBuilder& shbuilder) {\n  RgmModel* mdl = new RgmModel;\n\n  mdl->_aaBox.BeginGrow();\n  chunkfile::DefaultLoadAllocator allocator;\n  chunkfile::Reader chunkreader(pfilename, \"rgm\", allocator);\n  if (chunkreader.IsOk()) {\n    chunkfile::InputStream* HeaderStream    = chunkreader.GetStream(\"header\");\n    chunkfile::InputStream* ModelDataStream = chunkreader.GetStream(\"modeldata\");\n    ///////////////////////////////////////////////////\n    int inumannos = 0;\n    HeaderStream->GetItem(inumannos);\n    for (int ia = 0; ia < inumannos; ia++) {\n      int ikey, ival;\n      HeaderStream->GetItem(ikey);\n      HeaderStream->GetItem(ival);\n      const char* pkey  = chunkreader.GetString(ikey);\n      const char* pval  = chunkreader.GetString(ival);\n      mdl->mAnnos[pkey] = pval;\n    }\n    ///////////////////////////////////////////////////\n    HeaderStream->GetItem(mdl->minumsubs);\n    mdl->msubmeshes = new RgmSubMesh[mdl->minumsubs];\n    for (int is = 0; is < mdl->minumsubs; is++) {\n      RgmSubMesh& sub     = mdl->msubmeshes[is];\n      sub.mGeoSet         = new RgmGeoSet;\n      BakeShader* pshader = shbuilder.CreateShader(sub);\n      Material* pmaterial = shbuilder.CreateMaterial(sub);\n      sub.mpShader        = pshader;\n      sub.mpMaterial      = pmaterial;\n      ///////////////////////////////////////////////////\n      int inumsubannos = 0;\n      HeaderStream->GetItem(inumsubannos);\n      for (int ia = 0; ia < inumsubannos; ia++) {\n        int ikey, ival;\n        HeaderStream->GetItem(ikey);\n        HeaderStream->GetItem(ival);\n        const char* pkey = chunkreader.GetString(ikey);\n        const char* pval = chunkreader.GetString(ival);\n        sub.mAnnos[pkey] = pval;\n      }\n      ///////////////////////////////////////////////////\n      int inumtotv;\n      int iname;\n      HeaderStream->GetItem(iname);\n      HeaderStream->GetItem(sub.minumverts);\n      HeaderStream->GetItem(inumtotv);\n      sub.mpVertices              = new RgmVertex[sub.minumverts];\n      sub.mname                   = chunkreader.GetString(iname);\n      mdl->mSubMeshMap[sub.mname] = &sub;\n      for (int iv = 0; iv < sub.minumverts; iv++) {\n        RgmVertex& vtx = sub.mpVertices[iv];\n        ModelDataStream->GetItem(vtx.pos);\n        ModelDataStream->GetItem(vtx.nrm);\n        float fu = fmod((vtx.pos.x) * 0.01f, 1.0f);\n        float fv = fmod((vtx.pos.z) * 0.01f, 1.0f);\n        ModelDataStream->GetItem(vtx.uv);\n        vtx.uv.setX(fu);\n        vtx.uv.setY(fv);\n      }\n      int inumtotp;\n      HeaderStream->GetItem(sub.minumtris);\n      HeaderStream->GetItem(inumtotp);\n      sub.mtriangles = new RgmTri[sub.minumtris];\n      for (int ip = 0; ip < sub.minumtris; ip++) {\n        RgmTri& tri = sub.mtriangles[ip];\n        int inumv;\n        HeaderStream->GetItem(inumv);\n        OrkAssert(inumv == 3);\n        int ivA, ivB, ivC;\n        ModelDataStream->GetItem(ivA);\n        ModelDataStream->GetItem(ivB);\n        ModelDataStream->GetItem(ivC);\n        tri.mpv0 = sub.mpVertices + ivA;\n        tri.mpv1 = sub.mpVertices + ivB;\n        tri.mpv2 = sub.mpVertices + ivC;\n        tri.Compute();\n      }\n      sub.mGeoSet->GetAABox() = AABox();\n      sub.mGeoSet->GetAABox().BeginGrow();\n      for (int ip = 0; ip < sub.minumtris; ip += 4) // ip++ )\n      {\n        const RgmTri& tri   = sub.mtriangles[ip];\n        const RgmVertex* v0 = tri.mpv0;\n        const RgmVertex* v1 = tri.mpv1;\n        const RgmVertex* v2 = tri.mpv2;\n        RaytTriangle* prim  = new RaytTriangle(v0, v1, v2);\n        prim->mRgmPoly      = &tri;\n        prim->SetMaterial(pmaterial);\n        prim->SetBakeShader(pshader);\n        sub.mGeoSet->AddPrimitive(prim);\n        sub.mGeoSet->GetAABox().Grow(v0->pos);\n        sub.mGeoSet->GetAABox().Grow(v1->pos);\n        sub.mGeoSet->GetAABox().Grow(v2->pos);\n        mdl->_aaBox.Grow(v0->pos);\n        mdl->_aaBox.Grow(v1->pos);\n        mdl->_aaBox.Grow(v2->pos);\n      }\n      sub.mGeoSet->GetAABox().EndGrow();\n    }\n  }\n  mdl->_aaBox.EndGrow();\n  return mdl;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nEngine::Engine() {\n  mScene = new Scene();\n  // KdTree::SetMemoryManager( new MManager() );\n  mMod    = new int[64];\n  mMod    = (int*)((((unsigned long)mMod) + 32) & (0xffffffff - 31));\n  mMod[0] = 0, mMod[1] = 1, mMod[2] = 2, mMod[3] = 0, mMod[4] = 1;\n  // m_Stack = new kdstack[64];\n  // m_Stack = (kdstack*)((((unsigned long)m_Stack) + 32) & (0xffffffff - 31));\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nEngine::~Engine() {\n  delete mScene;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid Engine::setTarget(RayPixel* dest, int w, int h) {\n  // set pixel buffer address & size\n  mDest = dest;\n  miW   = w;\n  miH   = h;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nstatic float AreaOfTri(const fvec3& A, const fvec3& B, const fvec3& C) {\n  float farea = (A - C).Cross(B - C).Mag() * 0.5f;\n  return farea;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nconst Primitive* Engine::Raytrace(const fray3& ray, const int irecdepth, const float irindex, fvec3& acc, float& dist) {\n  const Primitive* prim = 0;\n\n  ////////////////////////////////////////////////////\n  // find the nearest intersection\n  ////////////////////////////////////////////////////\n\n  acc = fvec3(0.1f, 0.1f, 0.2f);\n  fvec3 P;\n  bool bhit = GetScene()->GetFixedGrid()->FindNearest(ray, dist, P, prim);\n  if (false == bhit)\n    return 0;\n\n  /*\tconst RgmTri& tri = *prim->mRgmPoly;\n\n      ////////////////////////////////////////////////////\n      // Compute Barycentric\n      ////////////////////////////////////////////////////\n\n      const fvec3& NA = tri.mpv0->nrm;\n      const fvec3& NB = tri.mpv1->nrm;\n      const fvec3& NC = tri.mpv2->nrm;\n      const fvec3& A = tri.mpv0->pos;\n      const fvec3& B = tri.mpv1->pos;\n      const fvec3& C = tri.mpv2->pos;\n\n      float PBC = ( AreaOfTri(P,B,C) );\n      float PCA = ( AreaOfTri(P,C,A) );\n      float PAB = ( AreaOfTri(P,A,B) );\n      float ABC = tri.mArea;\n\n      float a = PBC/ABC;\n      float b = PCA/ABC;\n      float c = 1.0f - a - b;\n\n      //////////////////////////\n      // Interpolated Normal\n      //////////////////////////\n\n      fvec3 N = (NA*a+NB*b+NC*c);\n\n      ////////////////////////////////////////////////////\n      // lighting\n      ////////////////////////////////////////////////////\n\n      fvec3 LightPos = fvec3(76,-15,-900);\n      fvec3 LMP = (LightPos-P);\n      fvec3 LightDir = LMP.Normal();\n\n      float fdot = N.Dot(LightDir);\n\n      if( fdot<0.0f ) fdot=0.0f;\n\n      acc = fvec3(fdot,fdot,fdot);\n\n      /////////////////////////////////////////////\n      // backfacing to light automatically black\n      /////////////////////////////////////////////\n      if( fdot <= 0.0f )\n      {\n          acc = fvec3::Black();\n          return prim;\n      }\n      /////////////////////////////////////////////\n      // perform shadowing test\n      /////////////////////////////////////////////\n      else\n      {\n          const float shadowbias = 0.1f;\n          Ray3 RayToLight( P+LightDir*shadowbias, LightDir );\n          const Primitive* primL = 0;\n\n          float shadowdist = 100000.0f;\n          fvec3 ShadowPos;\n          bool bshadowhit = GetScene()->GetFixedGrid()->FindNearest( RayToLight, shadowdist, ShadowPos, primL );\n\n          if( bshadowhit )\n          {\n              float disttolight = LMP.Mag();\n              if( shadowdist<disttolight )\n              {\tacc *= 0.5f;\n                  return primL;\n              }\n          }\n      }*/\n\n  return prim;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nstatic inline int round(float a) {\n  int iret = (a > 0) ? int(a + .5f) : int(a - .5f);\n  return iret;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid Engine::DrawSpan(\n    const BakeShader& shader,\n    int x1,\n    int y1,\n    const BakeShadowFragment& d1,\n    int x2,\n    int y2,\n    const BakeShadowFragment& d2,\n    SpanCtx& ctx,\n    orkset<SpanFragment>* output) {\n  OrkAssert(x2 - x1 >= 0 && x2 - x1 >= y2 - y1 && y2 - y1 >= 0);\n\n  bool horizontal = y1 == y2;\n  bool diagonal   = (y2 - y1) == (x2 - x1);\n\n  float scale = 1.0 / (x2 - x1);\n\n  BakeShadowFragment d      = d1;\n  BakeShadowFragment d_step = (d2 - d1) * scale * .99999f;\n\n  int y        = y1;\n  float yy     = y1;\n  float y_step = (y2 - y1) * scale;\n\n  for (int x = x1; x <= x2; ++x, d += d_step) {\n    int X(x);\n    int Y(y);\n    if (ctx.swap_xy) {\n      std::swap(X, Y);\n    }\n    if (ctx.flip_y) {\n      Y = -Y;\n    }\n    if (output) {\n      output->insert(SpanFragment(X, Y, d));\n    } else {\n      int ipix         = (Y * miW) + X;\n      mFragments[ipix] = d;\n      shader.Compute(X, Y);\n    }\n\n    if (!horizontal) {\n      y = diagonal ? (y + 1) : int(round(yy += y_step));\n    }\n  }\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid Engine::DrawSpanE(\n    const BakeShader& shader,\n    int x1,\n    int y1,\n    BakeShadowFragment c1,\n    int x2,\n    int y2,\n    BakeShadowFragment c2,\n    SpanCtx& ctx,\n    orkset<SpanFragment>* output) {\n  if (x1 > x2)\n  // force left to right.\n  {\n    std::swap(x1, x2);\n    std::swap(y1, y2);\n    std::swap(c1, c2);\n  }\n  if ((ctx.flip_y = y1 > y2))\n  // force down to up.\n  {\n    y1 = -y1;\n    y2 = -y2;\n  }\n  if ((ctx.swap_xy = y2 - y1 > x2 - x1))\n  // force line with <= 45 deg to x-axis.\n  {\n    std::swap(x1, y1);\n    std::swap(x2, y2);\n  }\n  DrawSpan(shader, x1, y1, c1, x2, y2, c2, ctx, output);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid Engine::RasterizeTriangle(\n    const BakeShader& shader,\n    int x1,\n    int y1,\n    const BakeShadowFragment& d1,\n    int x2,\n    int y2,\n    const BakeShadowFragment& d2,\n    int x3,\n    int y3,\n    const BakeShadowFragment& d3)\n\n{\n  SpanCtx ctx;\n\n  orkset<SpanFragment> scanned_pnts;\n  // sorted in y val, and in x val if y val the same.\n  DrawSpanE(shader, x1, y1, d1, x2, y2, d2, ctx, &scanned_pnts);\n  DrawSpanE(shader, x2, y2, d2, x3, y3, d3, ctx, &scanned_pnts);\n  DrawSpanE(shader, x3, y3, d3, x1, y1, d1, ctx, &scanned_pnts);\n  int cur_yval = miH / 2;         // initialize to an invalid value.\n  orkset<SpanFragment> same_yval; // of the scanned result.\n  for (orkset<SpanFragment>::iterator it = scanned_pnts.begin(); it != scanned_pnts.end(); ++it) {\n    int y = it->y;\n    if (y != cur_yval) {\n      if (same_yval.size()) {\n        orkset<SpanFragment>::iterator it1 = same_yval.begin();\n        orkset<SpanFragment>::iterator it2 = --same_yval.end();\n        DrawSpanE(shader, it1->x, cur_yval, it1->mData, it2->x, cur_yval, it2->mData, ctx, 0);\n        same_yval.clear();\n      }\n      cur_yval = y;\n    }\n    same_yval.insert(*it);\n  }\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid Engine::InitRender(fvec3& eye, fvec3& target) {\n  ///////////////////////////////////////\n  // calculate lookat matrix\n  ///////////////////////////////////////\n\n  fvec3 zdir  = (target - eye).Normal();\n  fvec3 cross = zdir.Cross(fvec3(0.0f, 1.0f, 0.0f));\n  if (cross.Mag() == 0.0f)\n    cross = zdir.Cross(fvec3(1.0f, 0.0f, 0.0f));\n  if (cross.Mag() == 0.0f)\n    cross = zdir.Cross(fvec3(0.0f, 0.0f, 1.0f));\n\n  fvec3 up = zdir.Cross(cross);\n\n  fmtx4 mtxLookat;\n  mtxLookat.LookAt(eye, target, up);\n\n  ///////////////////////////////////////\n  // set projection matrix\n  ///////////////////////////////////////\n\n  fmtx4 mtxP;\n\n  float faspect = float(width()) / float(height());\n  mtxP.Perspective(45, faspect, 1.0f, 10000.0f);\n  // mtxP.Ortho( -1, 1, -1, 1, 1, 10000  );\n\n  fvec3 vo(0.0f, 0.0f, 0.0f);\n  fvec3 vpn(0.0f, 0.0f, 1.0f);\n  fvec3 vpf(0.0f, 0.0f, 10000.0f);\n\n  fvec3 pvo = vo.Transform(mtxP);\n  fvec3 pvn = vpn.Transform(mtxP);\n  fvec3 pvf = vpf.Transform(mtxP);\n\n  ///////////////////////////////////////\n\n  // fmtx4 mtxViewport;\n  // float xs = 2.0f/\n  // mtxViewport.Scale(\n  ///////////////////////////////////////\n\n  const fmtx4 matVP = (mtxLookat * mtxP);\n  fmtx4 matIVP;\n  matIVP.inverseOf(matVP);\n\n  // set eye and screen plane position\n  mEye = eye;\n\n  float x1 = 0.0f; //-m_Width;//*0.5f;\n  float x2 = miW;\n  float y1 = 0.0f; //-m_Height;\n  float y2 = miH;\n\n  SRect VP(x1, y1, x2, y2);\n\n  fvec4 Vxcyc((x1 + x2) * 0.5f, (y1 + y2) * 0.5f, 0.0f, 1.0f);\n  fvec4 Vx0y0(x1, y1, 0.0f, 1.0f);\n  fvec4 Vx1y0(x2, y1, 0.0f, 1.0f);\n  fvec4 Vx1y1(x2, y2, 0.0f, 1.0f);\n  fvec4 Vx0y1(x1, y2, 0.0f, 1.0f);\n\n  fvec3 Center, CenterDir;\n\n  fmtx4::UnProject(Vxcyc, matIVP, VP, Center);\n  fmtx4::UnProject(Vx0y0, matIVP, VP, mCornerTL);\n  fmtx4::UnProject(Vx1y0, matIVP, VP, mCornerTR);\n  fmtx4::UnProject(Vx1y1, matIVP, VP, mCornerBR);\n  fmtx4::UnProject(Vx0y1, matIVP, VP, mCornerBL);\n\n  CenterDir = (Center - eye).Normal();\n\n  // calculate screen plane interpolation vectors\n  mDX = (mCornerTR - mCornerTL) * (1.0f / miW);\n  mDY = (mCornerBL - mCornerTL) * (1.0f / miH);\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nconst Primitive* Engine::RenderRay(fvec3 screen_pos, fvec3& acc) {\n  AABox e   = mScene->GetExtends();\n  fvec3 dir = (screen_pos - mEye);\n  dir.Normalize();\n  Ray3 r(mEye, dir);\n  float dist            = 100000.0f;\n  const Primitive* prim = Raytrace(r, 1, 1.0f, acc, dist);\n  return prim;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n\nstruct RenderingJobCtx {\n  Engine* mpEngine;\n  int miCore;\n  int miNumCores;\n  int miNumRays;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid* RenderingJobThread(void* vptr_args) {\n  RenderingJobCtx* mpCtx = (RenderingJobCtx*)vptr_args;\n\n  mpCtx->miNumRays = 0;\n  int ih           = mpCtx->mpEngine->height();\n  int iw           = mpCtx->mpEngine->width();\n\n  const fvec3& cTL = mpCtx->mpEngine->CornerTL();\n  const fvec3& cTR = mpCtx->mpEngine->CornerTR();\n  const fvec3& cBL = mpCtx->mpEngine->CornerBL();\n  const fvec3& cBR = mpCtx->mpEngine->CornerBR();\n\n  const fvec3& cQX = (cTR - cTL) * 1.0f / float(iw);\n  const fvec3& cQY = (cBL - cTL) * 1.0f / float(ih);\n\n  const Jitterer my_jitter(kOS, kJITTER, cQX, cQY);\n\n  for (int y = mpCtx->miCore; y < ih; y += mpCtx->miNumCores) {\n    if (y % 64 == mpCtx->miCore)\n      orkprintf(\"core<%d> y<%d>\\n\", mpCtx->miCore, y);\n\n    float fy = float(y) / float(ih);\n    fvec3 lSC, rSC;\n    lSC.lerp(cTL, cBL, fy);\n    rSC.lerp(cTR, cBR, fy);\n    for (int x = 0; x < iw; x++) {\n      float fx = float(x) / float(iw);\n      fvec3 screen_pos, jittered_pos;\n      screen_pos.lerp(lSC, rSC, fx);\n\n      fvec3 acc(0, 0, 0);\n      for (int isamp = 0; isamp < my_jitter.miNumSamples; isamp++) {\n        jittered_pos = screen_pos + my_jitter.GetSample(isamp);\n\n        fvec3 sample(0, 0, 0);\n\n        const Primitive* prim = mpCtx->mpEngine->RenderRay(jittered_pos, sample);\n        acc += sample;\n        mpCtx->miNumRays++;\n      }\n\n      acc = acc * (1.0f / float(my_jitter.miNumSamples));\n      int red, green, blue;\n      red   = (int)(acc.x * 256);\n      green = (int)(acc.y * 256);\n      blue  = (int)(acc.z * 256);\n      if (red > 255)\n        red = 255;\n      if (green > 255)\n        green = 255;\n      if (blue > 255)\n        blue = 255;\n      if (red < 0)\n        red = 0;\n      if (green < 0)\n        green = 0;\n      if (blue < 0)\n        blue = 0;\n      int ipix     = (y * iw) + ((iw - 1) - x);\n      RayPixel& rp = mpCtx->mpEngine->RefPixel(ipix);\n      rp.r         = red;\n      rp.g         = green;\n      rp.b         = blue;\n    }\n  }\n  return 0;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nbool Engine::Render(const AABox& bbox, const std::string& OutputName) {\n  RayPixel* pixels = new RayPixel[kIW * kIW];\n  memset((void*)pixels, 0, sizeof(RayPixel) * kIW * kIW);\n\n  fvec3 dim = (bbox.Max() - bbox.Min());\n  fvec3 ctr = fvec3(0.0f, 275.0f, 0.0f) + (bbox.Min() + bbox.Max()) * 0.5f;\n  fvec3 eye = ctr + fvec3(0.0f, 30.0f, 75.0f);\n\n  setTarget(pixels, kIW, kIW);\n\n  GetScene()->InitScene(bbox);\n  InitRender(eye, ctr);\n\n  /////////////////////////////////////////////////////////////////\n\n  int inumcores = GetNumCores();\n  orkvector<RenderingJobCtx*> JobCtxVect;\n#if 0\n\torkvector<pthread_t>\t\tThreadVect;\n\tf64 ftimeA = OldSchool::GetRef().GetSystemRelTime(  );\n\tfor( int ic=0; ic<inumcores; ic++ )\n\t{\n\t\tRenderingJobCtx* ctx = new RenderingJobCtx;\n\t\tctx->mpEngine = this;\n\t\tctx->miNumCores = inumcores;\n\t\tctx->miCore = ic;\n\n\t\tpthread_t job_thread;\n\t\tif (pthread_create(&job_thread, NULL, RenderingJobThread, (void*)ctx) != 0)\n\t\t{\n\t\t\tOrkAssert(false);\n\t\t}\n\n\t\tThreadVect.push_back(job_thread);\n\t\tJobCtxVect.push_back(ctx);\n\t}\n\tfor( orkvector<pthread_t>::iterator it=ThreadVect.begin(); it!=ThreadVect.end(); it++ )\n\t{\n\t\tpthread_t job = (*it);\n\t\tpthread_join(job, NULL);\n\t}\n\tint inumrays = 0;\n\tfor( orkvector<RenderingJobCtx*>::iterator it=JobCtxVect.begin(); it!=JobCtxVect.end(); it++ )\n\t{\n\t\tRenderingJobCtx* ctx = *it;\n\t\tinumrays += ctx->miNumRays;\n\t}\n\tf64 ftimeB = OldSchool::GetRef().GetSystemRelTime(  );\n\tf64 ftime = ftimeB-ftimeA;\n\tfloat frayspersec = float(inumrays)/ftime;\n\torkprintf( \"Rays<%d> Time<%f? RaysPerSec<%f>\\n\", inumrays, ftime,  frayspersec );\n\n\t/////////////////////////////////////////////////////////////////\n\tGetScene()->ExitScene();\n#endif\n\n  /*\tilInit();\n      ILuint image;\n      ilGenImages(1, &image);\n      ilBindImage(image);\n      if (!ilTexImage(kIW, kIW, 1, 3, IL_RGB, IL_UNSIGNED_BYTE, pixels))\n      {\n          ILenum error = ilGetError();\n          orkprintf(\"Failed to create image (%04X)\\n\", error);\n      }\n\n      ilEnable(IL_FILE_OVERWRITE);\n      if (!ilSaveImage(OutputName.c_str()))\n      {\n          ILenum error = ilGetError();\n          orkprintf(\"Failed to save to %s (%04X)\\n\", OutputName.c_str(), error);\n      }\n  */\n  return true;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nstruct BakingJobCtx {\n  Engine* mpEngine;\n  int miCore;\n  int miNumCores;\n  int miNumRays;\n};\n\n///////////////////////////////////////////////////////////////////////////////\n\nvoid* BakingJobThread(void* pval) {\n  BakingJobCtx* mpCtx = (BakingJobCtx*)pval;\n\n  const orkmap<std::string, const RgmGeoSet*>& geosets = mpCtx->mpEngine->GetScene()->GetGeoSets();\n\n  for (orkmap<std::string, const RgmGeoSet*>::const_iterator it = geosets.begin(); it != geosets.end(); it++) {\n    const std::string& geoname = it->first;\n    if (geoname.find(\"raster_\") != std::string::npos) {\n      const RgmGeoSet* RasterSet = it->second;\n\n      int inumtri = RasterSet->NumPrimitives();\n      int iw      = mpCtx->mpEngine->width();\n      int ih      = mpCtx->mpEngine->height();\n      int itrictr = inumtri / mpCtx->miNumCores;\n\n      int icntdwn = (inumtri >> 8); //\n\n      if (0 == icntdwn)\n        icntdwn = 1;\n\n      for (int ip = mpCtx->miCore; ip < inumtri; ip += mpCtx->miNumCores) {\n        if (itrictr % icntdwn == 0)\n          orkprintf(\"core<%d> numleft<%d> geoname<%s>\\n\", mpCtx->miCore, itrictr, geoname.c_str());\n        itrictr--;\n        const Primitive* prim = RasterSet->GetPrimitive(ip);\n        prim->Rasterize(mpCtx->mpEngine);\n      }\n    }\n  }\n  return 0;\n}\n\nbool Engine::Bake(const AABox& bbox, const std::string& OutputName) {\n  int iKKos = kOS;\n\n  int idim        = (iKKos * 2) + 1;\n  int iNumSamples = idim * idim;\n\n  int idiv = (kOS == 0) ? 1 : kOS;\n  int iKIW = idim * kIW;\n\n  RayPixel* pixels = new RayPixel[iKIW * iKIW];\n  memset((void*)pixels, 0, sizeof(RayPixel) * iKIW * iKIW);\n  mFragments = new BakeShadowFragment[iKIW * iKIW];\n  memset((void*)mFragments, 0, sizeof(BakeShadowFragment) * kIW * kIW);\n\n  fvec3 dim = (bbox.Max() - bbox.Min());\n  fvec3 ctr = (bbox.Min() + bbox.Max()) * 0.5f;\n  fvec3 eye = ctr + fvec3(0.0f, 0.0f, 75.0f);\n\n  setTarget(pixels, iKIW, iKIW);\n\n  orkprintf(\"Initializing Scene\\n\");\n\n  GetScene()->InitScene(bbox);\n  InitRender(eye, ctr);\n\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n  // f64 ftimeA = OldSchool::GetRef().GetSystemRelTime(  );\n  {\n    int inumcores = GetNumCores();\n    orkvector<BakingJobCtx*> JobCtxVect;\n#if 0\n\t\torkvector<pthread_t>\tThreadVect;\n\t\tfor( int ic=0; ic<inumcores; ic++ )\n\t\t{\n\t\t\tBakingJobCtx* ctx = new BakingJobCtx;\n\t\t\tctx->mpEngine = this;\n\t\t\tctx->miNumCores = inumcores;\n\t\t\tctx->miCore = ic;\n\n\t\t\tpthread_t job_thread;\n\t\t\tif (pthread_create(&job_thread, NULL, BakingJobThread, (void*)ctx) != 0)\n\t\t\t{\n\t\t\t\tOrkAssert(false);\n\t\t\t}\n\n\t\t\tThreadVect.push_back(job_thread);\n\n\t\t\tJobCtxVect.push_back(ctx);\n\t\t}\n\t\tfor( orkvector<pthread_t>::iterator it=ThreadVect.begin(); it!=ThreadVect.end(); it++ )\n\t\t{\n\t\t\tpthread_t job = (*it);\n\t\t\tpthread_join(job, NULL);\n\t\t}\n\t\tint inumrays = 0;\n\t\t//for( orkvector<BakingJobCtx*>::iterator it=JobCtxVect.begin(); it!=JobCtxVect.end(); it++ )\n\t\t//{\n\t\t//\tRenderingJobCtx* ctx = *it;\n\t\t//\tinumrays += ctx->miNumRays;\n\t\t//}\n#endif\n  }\n  // f64 ftimeB = OldSchool::GetRef().GetSystemRelTime(  );\n  f64 ftime  = 1.0; // ftimeB-ftimeA;\n  int inrays = int(giNumRays);\n\n  float frayspersec = float(inrays) / ftime;\n  orkprintf(\"Rays<%d> Time<%f> RaysPerSec<%f>\\n\", inrays, ftime, frayspersec);\n  giNumRays = 0;\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n  GetScene()->ExitScene();\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n  orkprintf(\"growing uv shells...\\n\");\n  static const int kgrowamt = 7;\n  for (int iy = 0; iy < iKIW; iy++) {\n    for (int ix = 0; ix < iKIW; ix++) {\n      int ipix        = (iy * iKIW) + ix;\n      RayPixel& pixel = pixels[ipix];\n      //////////////////////////////\n      // we will only ever grow pixels that have not been written to\n      if (pixel.a == 0) {\n        float faccr = 0.0f;\n        float faccg = 0.0f;\n        float faccb = 0.0f;\n        float fnums = 0.0f;\n        for (int oy = -kgrowamt; oy <= kgrowamt; oy++) {\n          int iny = iy + oy;\n          if (iny < 0)\n            continue;\n          if (iny >= iKIW)\n            continue;\n          for (int ox = -kgrowamt; ox <= kgrowamt; ox++) {\n            int inx = ix + ox;\n            if (ox == 0 && oy == 0)\n              continue;\n            if (inx < 0)\n              continue;\n            if (inx >= iKIW)\n              continue;\n            int ipix2            = (iny * kIW) + inx;\n            const RayPixel& opix = pixels[ipix2];\n            if (opix.a != 0) {\n              faccr += float(opix.r);\n              faccg += float(opix.g);\n              faccb += float(opix.b);\n              fnums += 1.0f;\n            }\n          }\n        }\n        if (fnums != 0.0f) {\n          pixel.r = u8(faccr / fnums);\n          pixel.g = u8(faccg / fnums);\n          pixel.b = u8(faccb / fnums);\n        }\n      }\n    }\n  }\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n  /////////////////////////////////////////////////////////////////\n\n  /*\tboost::gil::rgb8_image_t img(iKIW,iKIW);\n      boost::gil::rgb8_view_t myview = boost::gil::view(img);\n\n      for( int iy=0; iy<iKIW; iy++ )\n      {\n          for( int ix=0; ix<iKIW; ix++ )\n          {\n              int ipix = (iy*iKIW)+ix;\n              const RayPixel& pixel = pixels[ipix];\n              boost::gil::rgb8_pixel_t mypix( pixel.r, pixel.g, pixel.b );\n              myview(ix,iy)=mypix;\n          }\n      }\n\n      orkprintf( \"blurring image...\\n\" );\n\n      orkprintf( \"saving image...\\n\" );\n\n      //boost::gil::png_write_view(OutputName.c_str(), boost::gil::view(img));\n\n      delete[] pixels;\n      delete[] mFragments;\n      delete GetScene()->GetFixedGrid();\n      */\n\n  return true;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\nvoid Scene::AddGeoset(const std::string& name, RgmGeoSet* pset) {\n  mGeoSets[name] = pset;\n}\nvoid Scene::RemoveGeoset(const std::string& name) {\n  orkmap<std::string, const RgmGeoSet*>::iterator it = mGeoSets.find(name);\n  if (it != mGeoSets.end()) {\n    const RgmGeoSet* rval = it->second;\n    mGeoSets.erase(it);\n    if (rval) {\n      delete rval;\n    }\n  }\n}\n\nconst RgmGeoSet* Scene::FindGeoset(const std::string& name) const {\n  const RgmGeoSet* rval                                    = 0;\n  orkmap<std::string, const RgmGeoSet*>::const_iterator it = mGeoSets.find(name);\n  if (it != mGeoSets.end())\n    rval = it->second;\n  return rval;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n///////////////////////////////////////////////////////////////////////////////\n\n} // namespace ork\n", "meta": {"hexsha": "fb71fc49836aa86ff7d9a5ebaca4b0a9a657e309", "size": 51022, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ork.core/src/math/raytracer.cpp", "max_stars_repo_name": "tweakoz/orkid", "max_stars_repo_head_hexsha": "e3f78dfb3375853fd512a9d0828b009075a18345", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 25.0, "max_stars_repo_stars_event_min_datetime": "2015-02-21T04:21:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T05:19:27.000Z", "max_issues_repo_path": "ork.core/src/math/raytracer.cpp", "max_issues_repo_name": "tweakoz/orkid", "max_issues_repo_head_hexsha": "e3f78dfb3375853fd512a9d0828b009075a18345", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 113.0, "max_issues_repo_issues_event_min_datetime": "2019-08-23T04:52:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-13T04:04:11.000Z", "max_forks_repo_path": "ork.core/src/math/raytracer.cpp", "max_forks_repo_name": "tweakoz/orkid", "max_forks_repo_head_hexsha": "e3f78dfb3375853fd512a9d0828b009075a18345", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-02-20T18:17:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-28T03:47:55.000Z", "avg_line_length": 35.6298882682, "max_line_length": 132, "alphanum_fraction": 0.39839677, "num_tokens": 13250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20895467048751784}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017, 2018.\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 5.0.0\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_LAGRNG_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_LAGRNG_HPP\n\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace lagrng\n    {\n\n            static const double tolerance = 1e-10;\n\n            template <typename T>\n            struct par_lagrng\n            {\n                T    a1;\n                T    rw;\n                T    hrw;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_lagrng_spheroid\n                : public base_t_f<base_lagrng_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_lagrng<T> m_proj_parm;\n\n                inline base_lagrng_spheroid(const Parameters& par)\n                    : base_t_f<base_lagrng_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T lp_lon, T lp_lat, T& xy_x, T& xy_y) const\n                {\n                    static const T half_pi = detail::half_pi<T>();\n\n                    T v, c;\n\n                    if (fabs(fabs(lp_lat) - half_pi) < tolerance) {\n                        xy_x = 0;\n                        xy_y = lp_lat < 0 ? -2. : 2.;\n                    } else {\n                        lp_lat = sin(lp_lat);\n                        v = this->m_proj_parm.a1 * math::pow((T(1) + lp_lat)/(T(1) - lp_lat), this->m_proj_parm.hrw);\n                        if ((c = 0.5 * (v + 1./v) + cos(lp_lon *= this->m_proj_parm.rw)) < tolerance) {\n                            BOOST_THROW_EXCEPTION( projection_exception(error_tolerance_condition) );\n                        }\n                        xy_x = 2. * sin(lp_lon) / c;\n                        xy_y = (v - 1./v) / c;\n                    }\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"lagrng_spheroid\";\n                }\n\n            };\n\n            // Lagrange\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_lagrng(Params const& params, Parameters& par, par_lagrng<T>& proj_parm)\n            {\n                T phi1;\n\n                proj_parm.rw = 0.0;\n                bool is_w_set = pj_param_f<srs::spar::w>(params, \"W\", srs::dpar::w, proj_parm.rw);\n                \n                // Boost.Geometry specific, set default parameters manually\n                if (! is_w_set) {\n                    bool const use_defaults = ! pj_get_param_b<srs::spar::no_defs>(params, \"no_defs\", srs::dpar::no_defs);\n                    if (use_defaults) {\n                        proj_parm.rw = 2;\n                    }\n                }\n\n                if (proj_parm.rw <= 0)\n                    BOOST_THROW_EXCEPTION( projection_exception(error_w_or_m_zero_or_less) );\n\n                proj_parm.rw = 1. / proj_parm.rw;\n                proj_parm.hrw = 0.5 * proj_parm.rw;\n                phi1 = pj_get_param_r<T, srs::spar::lat_1>(params, \"lat_1\", srs::dpar::lat_1);\n                if (fabs(fabs(phi1 = sin(phi1)) - 1.) < tolerance)\n                    BOOST_THROW_EXCEPTION( projection_exception(error_lat_larger_than_90) );\n\n                proj_parm.a1 = math::pow((T(1) - phi1)/(T(1) + phi1), proj_parm.hrw);\n\n                par.es = 0.;\n            }\n\n    }} // namespace detail::lagrng\n    #endif // doxygen\n\n    /*!\n        \\brief Lagrange projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Miscellaneous\n         - Spheroid\n         - no inverse\n        \\par Projection parameters\n         - W (real)\n         - lat_1: Latitude of first standard parallel (degrees)\n        \\par Example\n        \\image html ex_lagrng.gif\n    */\n    template <typename T, typename Parameters>\n    struct lagrng_spheroid : public detail::lagrng::base_lagrng_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline lagrng_spheroid(Params const& params, Parameters const& par)\n            : detail::lagrng::base_lagrng_spheroid<T, Parameters>(par)\n        {\n            detail::lagrng::setup_lagrng(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_lagrng, lagrng_spheroid, lagrng_spheroid)\n\n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_F(lagrng_entry, lagrng_spheroid)\n        \n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(lagrng_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(lagrng, lagrng_entry);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_LAGRNG_HPP\n\n", "meta": {"hexsha": "6df4459624709c27629ee6d99a1d23531c9d92d7", "size": 7406, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/lagrng.hpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/lagrng.hpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/lagrng.hpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 37.9794871795, "max_line_length": 122, "alphanum_fraction": 0.61031596, "num_tokens": 1727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746213017459, "lm_q2_score": 0.33111973302838926, "lm_q1q2_score": 0.20853080447348904}}
{"text": "/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\\n|  Phycas: Python software for phylogenetic analysis                          |\n|  Copyright (C) 2006 Mark T. Holder, Paul O. Lewis and David L. Swofford     |\n|                                                                             |\n|  This program is free software; you can redistribute it and/or modify       |\n|  it under the terms of the GNU General Public License as published by       |\n|  the Free Software Foundation; either version 2 of the License, or          |\n|  (at your option) any later version.                                        |\n|                                                                             |\n|  This program is distributed in the hope that it will be useful,            |\n|  but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n|  GNU General Public License for more details.                               |\n|                                                                             |\n|  You should have received a copy of the GNU General Public License along    |\n|  with this program; if not, write to the Free Software Foundation, Inc.,    |\n|  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.                |\n\\~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/\n#include <boost/cast.hpp>       //temporary!\n#include <sstream>\n#include <boost/math/special_functions/fpclassify.hpp>\n#include \"probability_distribution.hpp\"\n#include \"relative_rate_distribution.hpp\"\n#include \"model.hpp\"\n#include \"basic_tree_node.hpp\"\n#include \"tree_likelihood.hpp\"\n#include \"xlikelihood.hpp\"\n#include \"mcmc_chain_manager.hpp\"\n#include \"dirichlet_move.hpp\"\n#include \"subset_relrates_move.hpp\"\n#include \"basic_tree.hpp\"\n#include \"tree_manip.hpp\"\n#include \"gtr.hpp\"\n#include \"hky.hpp\"\n\nusing namespace phycas;\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tThe constructor simply calls the base class (DirichletMove) constructor.\n*/\nSubsetRelRatesMove::SubsetRelRatesMove()\n  : DirichletMove()\n\t{\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets the relative rates of the associated partition model to those in the supplied vector `v'. No transformation of\n|\tthe relative rates is done by this function.\n*/\nvoid SubsetRelRatesMove::sendCurrValuesToModel(const double_vect_t & v)\n\t{\n\tPHYCAS_ASSERT(dim == v.size());\n\tpartition_model->setSubsetRelRatesVect(v);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tObtains the current relative rates from the model, storing them in the supplied vector `v'. No transformation of\n|\tthe relative rates is done by this function.\n*/\nvoid SubsetRelRatesMove::getCurrValuesFromModel(double_vect_t & v) const\n\t{\n\tconst std::vector<double> & rrates = partition_model->getSubsetRelRatesVect();\n\n    //std::cerr << \"@#@#@#@#@# SubsetRelRatesMove::getCurrValuesFromModel\" << std::endl;\n    //std::copy(rrates.begin(), rrates.end(), std::ostream_iterator<double>(std::cerr, \" \"));\n    //std::cerr << std::endl;\n    //std::cerr << \"@#@#@#@#@# SubsetRelRatesMove::getCurrValuesFromModel\" << std::endl;\n\n\tPHYCAS_ASSERT(dim == rrates.size());\n\tv.resize(rrates.size());\n\tstd::copy(rrates.begin(), rrates.end(), v.begin());\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tObtains the current relative rates from the model, returning them as an anonymous vector. No transformation of\n|\tthe relative rates is done by this function.\n*/\ndouble_vect_t SubsetRelRatesMove::listCurrValuesFromModel()\n\t{\n\tdouble_vect_t v(dim);\n\tconst double_vect_t & rrates = partition_model->getSubsetRelRatesVect();\n\tPHYCAS_ASSERT(dim == rrates.size());\n\tstd::copy(rrates.begin(), rrates.end(), v.begin());\n\treturn v;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tSets `partition_model' to the supplied `m'.\n*/\nvoid SubsetRelRatesMove::setPartitionModel(\n  PartitionModelShPtr m)    /*< is a shared pointer to the new partition model */\n\t{\n\tpartition_model = m;\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tObtains the current relative rates from the model by calling SubsetRelRatesMove::getCurrValuesFromModel.\n*/\nvoid SubsetRelRatesMove::getParams()\n\t{\n\tgetCurrValuesFromModel(orig_relrates);\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tReplaces the relative rates in the model with those supplied in the vector `v'.\n*/\nvoid SubsetRelRatesMove::setParams(\n  const double_vect_t & v)    /*< is the vector of parameter values to send to the model */\n\t{\n\tPHYCAS_ASSERT(v.size() == dim);\n    sendCurrValuesToModel(v);\n\t}\n\n/*--------------------------------------------------------------------------------------------------------------------------\n|   Returns current subset relative rates, proportions and transformed relative rates as well as the weighted average of the\n|   relative rates, which should always be 1.0.\n*/\nstd::string SubsetRelRatesMove::debugShowTransformedRelativeRates(const std::string msg) const\n\t{\n    std::stringstream ss;\n\tss << \">>>>>>>>>> \" << msg << \" <<<<<<<<<<\" << std::endl;\n\tss << \"Relative rates: \";\n\tstd::copy(orig_relrates.begin(), orig_relrates.end(), std::ostream_iterator<double>(ss, \" \"));\n\tss << boost::str(boost::format(\" sum = %.15f\") % std::accumulate(orig_relrates.begin(), orig_relrates.end(), 0.0)) << std::endl;\n\n\tss << \"Subset proportions: \";\n    const std::vector<unsigned> & nsites = partition_model->getNumSitesVect();\n    double total_sites = (double)partition_model->getTotalNumSites();\n    double_vect_t p;\n    p.resize(nsites.size());\n    std::transform(nsites.begin(), nsites.end(), p.begin(), boost::lambda::_1/total_sites);\n\tstd::copy(p.begin(), p.end(), std::ostream_iterator<double>(ss, \" \"));\n\tss << boost::str(boost::format(\" sum = %.15f\") % std::accumulate(p.begin(), p.end(), 0.0)) << std::endl;\n\n\t// transform relative rates using coefficients so that elements of orig_params sum to 1\n\tss << \"Weighted relative rates: \";\n    std::vector<double> tmp(orig_relrates.size(), 0.0);\n\tstd::transform(orig_relrates.begin(), orig_relrates.end(), p.begin(), tmp.begin(), boost::lambda::_1*boost::lambda::_2);\n\tstd::copy(tmp.begin(), tmp.end(), std::ostream_iterator<double>(ss, \" \"));\n\tss << boost::str(boost::format(\" sum = %.15f\") %  std::accumulate(tmp.begin(), tmp.end(), 0.0)) << std::endl;\n    return ss.str();\n    }\n\n/*--------------------------------------------------------------------------------------------------------------------------\n|   Chooses a new vector of state frequencies using a sharp Dirichlet distribution centered at the original frequencies.\n*/\nvoid SubsetRelRatesMove::proposeNewState()\n\t{\n\t// transform relative rates using coefficients so that elements of orig_params sum to 1\n\torig_params.resize(orig_relrates.size());\n    SubsetProportionsShPtr ptr = partition_model->getSubsetProportions();\n    std::vector<double> const & p = ptr->getSubsetProportions();\n    //double total_sites = (double)partition_model->getTotalNumSites();\n\tstd::transform(orig_relrates.begin(), orig_relrates.end(), p.begin(), orig_params.begin(), boost::lambda::_1*boost::lambda::_2);\n\n    // create vector of Dirichlet parameters for selecting new relative rate values\n\t// The parameter vector for this temporary distribution is obtained by multiplying\n    // each of the current relative rates by the value `psi', which is usually very large (e.g. 1000)\n    c_forward.resize(orig_params.size());\n\tstd::transform(orig_params.begin(), orig_params.end(), c_forward.begin(), 1.0 + boost::lambda::_1*psi);\n\n\t// create Dirichlet distribution and sample from it\n    dir_forward = DirichletShPtr(new DirichletDistribution(c_forward));\n    dir_forward->SetLot(getLot().get());\n\tnew_params.resize(orig_params.size());\n    new_params = dir_forward->Sample();\n\n    // create vector of Dirichlet parameters for selecting old frequencies (needed for Hastings ratio calculation)\n    c_reverse.resize(new_params.size());\n\tstd::transform(new_params.begin(), new_params.end(), c_reverse.begin(), 1.0 + boost::lambda::_1*psi);\n    dir_reverse = DirichletShPtr(new DirichletDistribution(c_reverse));\n\n\t// transform new_params using coefficients so that elements of new_relrates are equal to proposed new relative rates\n\tnew_relrates.resize(new_params.size());\n\tstd::transform(new_params.begin(), new_params.end(), p.begin(), new_relrates.begin(), boost::lambda::_1/boost::lambda::_2);\n\n#if 0\n    std::cerr << \"\\n^^^^^ orig_relrates ^^^^^\" << std::endl;\n    std::copy(orig_relrates.begin(), orig_relrates.end(), std::ostream_iterator<double>(std::cerr, \"|\"));\n    std::cerr << \"\\n^^^^^ orig_params ^^^^^\" << std::endl;\n    std::copy(orig_params.begin(), orig_params.end(), std::ostream_iterator<double>(std::cerr, \"|\"));\n    std::cerr << \"\\n^^^^^ c_forward ^^^^^\" << std::endl;\n    std::copy(c_forward.begin(), c_forward.end(), std::ostream_iterator<double>(std::cerr, \"|\"));\n    std::cerr << \"\\n^^^^^ c_reverse ^^^^^\" << std::endl;\n    std::copy(c_reverse.begin(), c_reverse.end(), std::ostream_iterator<double>(std::cerr, \"|\"));\n    std::cerr << \"\\n^^^^^ new_params ^^^^^\" << std::endl;\n    std::copy(new_params.begin(), new_params.end(), std::ostream_iterator<double>(std::cerr, \"|\"));\n    std::cerr << \"\\n^^^^^ new_relrates ^^^^^\" << std::endl;\n    std::copy(new_relrates.begin(), new_relrates.end(), std::ostream_iterator<double>(std::cerr, \"|\"));\n    std::cerr << std::endl;\n#endif\n\t}\n\n/*--------------------------------------------------------------------------------------------------------------------------\n|\tCalled if the proposed move is accepted. Simply calls the reset() function.\n*/\nvoid SubsetRelRatesMove::accept()\n\t{\n\tMCMCUpdater::accept();\n\treset();\n\t}\n\n/*--------------------------------------------------------------------------------------------------------------------------\n|\tCalled if the proposed move is rejected. Calls the reset() function after reinstating the original relative rates\n|   and ensuring that all conditional likelihood arrays will be recalculated when the likelihood is next calculated.\n*/\nvoid SubsetRelRatesMove::revert()\n\t{\n\tMCMCUpdater::revert();\n    setParams(orig_relrates);\n\n\tChainManagerShPtr p = chain_mgr.lock();\n\tPHYCAS_ASSERT(p);\n    JointPriorManagerShPtr jpm = p->getJointPriorManager();\n    jpm->multivariateModified(name, orig_relrates);\n    curr_ln_prior = jpm->getLogJointPrior();\n\n    // invalidate all CLAs\n    likelihood->useAsLikelihoodRoot(NULL);\n    likelihood->storeAllCLAs(tree);\n\n\treset();\n\t}\n\n/*----------------------------------------------------------------------------------------------------------------------\n|\tCalls proposeNewState(), then decides whether to accept or reject the proposed new state, calling accept() or\n|\trevert(), whichever is appropriate.\n*/\nbool SubsetRelRatesMove::update()\n\t{\n\tif (is_fixed)\n\t\treturn false;\n\n\tChainManagerShPtr p = chain_mgr.lock();\n\tPHYCAS_ASSERT(p);\n    JointPriorManagerShPtr jpm = p->getJointPriorManager();\n\n    // copy the current subset relative rates from the model to the data member orig_params\n    getParams();\n\n\tproposeNewState();\n\n    double prev_ln_prior\t\t= jpm->getLogJointPrior();\n\n\tdouble prev_ln_like\t\t\t= p->getLastLnLike();\n\tPHYCAS_ASSERT(!use_ref_dist || mv_ref_dist);\n\tdouble prev_ln_ref_dist = (use_ref_dist ? mv_ref_dist->GetLnPDF(orig_relrates) : 0.0);\n\n    // replace current parameter values with new ones\n    setParams(new_relrates);\n\n    jpm->multivariateModified(name, new_relrates);\n    double curr_ln_prior    = jpm->getLogJointPrior();\n\n    likelihood->useAsLikelihoodRoot(NULL);\t// invalidates all CLAs\n\tdouble curr_ln_like\t\t\t= (heating_power > 0.0 ? likelihood->calcLnL(tree) : 0.0);\n\tdouble curr_ln_ref_dist = (use_ref_dist ? mv_ref_dist->GetLnPDF(new_relrates) : 0.0);\n\n    double prev_posterior = 0.0;\n\tdouble curr_posterior = 0.0;\n\n\tif (is_standard_heating)\n\t\t{\n\t\tprev_posterior = heating_power*(prev_ln_like + prev_ln_prior);\n\t\tcurr_posterior = heating_power*(curr_ln_like + curr_ln_prior);\n\t\tif (use_ref_dist)\n\t\t\t{\n\t\t\tprev_posterior += (1.0 - heating_power)*prev_ln_ref_dist;\n\t\t\tcurr_posterior += (1.0 - heating_power)*curr_ln_ref_dist;\n\t\t\t}\n\t\t}\n\telse\n\t\t{\n\t\tprev_posterior = heating_power*prev_ln_like + prev_ln_prior;\n\t\tcurr_posterior = heating_power*curr_ln_like + curr_ln_prior;\n\t\t}\n\n\tdouble ln_hastings\t\t\t= getLnHastingsRatio();\n\tdouble ln_accept_ratio\t\t= curr_posterior - prev_posterior + ln_hastings;\n\n    double lnu = std::log(rng->Uniform());\n\n    bool accepted = false;\n\n\tif (ln_accept_ratio >= 0.0 || lnu <= ln_accept_ratio)\n\t\t{\n\t    if (save_debug_info)\n    \t    {\n\t\t\tdebug_info = boost::str(boost::format(\"ACCEPT, prev_ln_like = %.5f, getLastLnLike() = %.5f, curr_ln_like = %.5f, prev_ln_ref_dist = %.5f, curr_ln_ref_dist = %.5f, prev_ln_prior = %.5f, curr_ln_prior = %.5f, lnu = %.5f, ln_accept_ratio = %.5f\\n\") % prev_ln_like % p->getLastLnLike() % curr_ln_like % prev_ln_ref_dist % curr_ln_ref_dist % prev_ln_prior % curr_ln_prior % lnu % ln_accept_ratio);\n            debug_info += debugShowTransformedRelativeRates(\"Details\");\n\t\t\t//for (std::vector<double>::const_iterator it = orig_params.begin(); it != orig_params.end(); ++it)\n\t\t\t//\tdebug_info += boost::str(boost::format(\"%15.8f \") % (*it));\n\t\t\t//debug_info += \"\\nnew_params:  \";\n\t\t\t//for (std::vector<double>::const_iterator it = new_params.begin(); it != new_params.end(); ++it)\n\t\t\t//\tdebug_info += boost::str(boost::format(\"%15.8f \") % (*it));\n\t\t\t//debug_info += \"\\nc_forward:  \";\n\t\t\t//for (std::vector<double>::const_iterator it = c_forward.begin(); it != c_forward.end(); ++it)\n\t\t\t//\tdebug_info += boost::str(boost::format(\"%15.8f \") % (*it));\n\t\t\t//debug_info += \"\\ndir_forward:  \";\n\t\t\t//debug_info += dir_forward->GetDistributionDescription();\n\t\t\t}\n\t\tp->setLastLnLike(curr_ln_like);\n\n\t\taccept();\n\t\taccepted = true;\n\t\t}\n\telse\n\t\t{\n\t    if (save_debug_info)\n    \t    {\n\t\t\tdebug_info = boost::str(boost::format(\"REJECT, prev_ln_like = %.5f, getLastLnLike() = %.5f, curr_ln_like = %.5f, prev_ln_ref_dist = %.5f, curr_ln_ref_dist = %.5f, prev_ln_prior = %.5f, curr_ln_prior = %.5f, lnu = %.5f, ln_accept_ratio = %.5f\\n\") % prev_ln_like % p->getLastLnLike() % curr_ln_like % prev_ln_ref_dist % curr_ln_ref_dist % prev_ln_prior % curr_ln_prior % lnu % ln_accept_ratio);\n            debug_info += debugShowTransformedRelativeRates(\"Details\");\n            //for (std::vector<double>::const_iterator it = orig_params.begin(); it != orig_params.end(); ++it)\n            //    debug_info += boost::str(boost::format(\"%15.8f \") % (*it));\n            //debug_info += \"\\nnew_params:  \";\n            //for (std::vector<double>::const_iterator it = new_params.begin(); it != new_params.end(); ++it)\n            //    debug_info += boost::str(boost::format(\"%15.8f \") % (*it));\n            //debug_info += \"\\nc_forward:  \";\n            //for (std::vector<double>::const_iterator it = c_forward.begin(); it != c_forward.end(); ++it)\n            //    debug_info += boost::str(boost::format(\"%15.8f \") % (*it));\n            //debug_info += \"\\ndir_forward:  \";\n            //debug_info += dir_forward->GetDistributionDescription();\n\t\t\t}\n\t\tcurr_ln_like\t= p->getLastLnLike();\n\t\trevert();\n\t\taccepted = false;\n\t\t}\n\n    double inverse_psi = 1.0/psi;\n    inverse_psi = p->adaptUpdater(inverse_psi, nattempts, accepted);\n    psi = 1.0/inverse_psi;\n\n    return accepted;\n\t}\n\n", "meta": {"hexsha": "10ed8dfb054a3ec198914f2e3a0c32647ca6fd0f", "size": 15839, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/subset_relrates_move.cpp", "max_stars_repo_name": "plewis/phycas", "max_stars_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2015-09-24T23:12:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-12T07:07:01.000Z", "max_issues_repo_path": "src/cpp/subset_relrates_move.cpp", "max_issues_repo_name": "plewis/phycas", "max_issues_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/subset_relrates_move.cpp", "max_forks_repo_name": "plewis/phycas", "max_forks_repo_head_hexsha": "9f5a4d9b2342dab907d14a46eb91f92ad80a5605", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2015-11-23T10:35:43.000Z", "max_forks_repo_forks_event_max_datetime": "2015-11-23T10:35:43.000Z", "avg_line_length": 47.1398809524, "max_line_length": 395, "alphanum_fraction": 0.6056569228, "num_tokens": 3665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.20843926445410696}}
{"text": "/*\n *  @file   rnxToGtsam.cpp\n *  @author Ryan\n *  @brief  Script to convert Rinex File format to format utilized by GTSAM.\n\n * To do ::\n * Currenlty only works with SP3\n * Need to get nom. pos. from rinex header\n * Get DOY from header for trop estimation\n * need to write to file. Currently only prints to screen.\n */\n\n// GPSTK\n#include <gtsam/gpstk/MJD.hpp>\n#include <gtsam/gpstk/PowerSum.hpp>\n#include <gtsam/gpstk/Decimate.hpp>\n#include <gtsam/gpstk/TropModel.hpp>\n#include <gtsam/gpstk/BasicModel.hpp>\n#include <gtsam/gpstk/CommonTime.hpp>\n#include <gtsam/gpstk/PCSmoother.hpp>\n#include <gtsam/gpstk/CodeSmoother.hpp>\n#include <gtsam/gpstk/SimpleFilter.hpp>\n#include <gtsam/gpstk/MWCSDetector.hpp>\n#include <gtsam/gpstk/SatArcMarker.hpp>\n#include <gtsam/gpstk/DCBDataReader.hpp>\n#include <gtsam/gpstk/ComputeWindUp.hpp>\n#include <gtsam/gpstk/Rinex3NavData.hpp>\n#include <gtsam/gpstk/GNSSconstants.hpp>\n#include <gtsam/gpstk/ComputeLinear.hpp>\n#include <gtsam/gpstk/GPSWeekSecond.hpp>\n#include <gtsam/gpstk/LICSDetector2.hpp>\n#include <gtsam/gpstk/DataStructures.hpp>\n#include <gtsam/gpstk/Rinex3ObsStream.hpp>\n#include <gtsam/gpstk/Rinex3NavStream.hpp>\n#include <gtsam/gpstk/ComputeTropModel.hpp>\n#include <gtsam/gpstk/SP3EphemerisStore.hpp>\n#include <gtsam/gpstk/ComputeSatPCenter.hpp>\n#include <gtsam/gpstk/EclipsedSatFilter.hpp>\n#include <gtsam/gpstk/GPSEphemerisStore.hpp>\n#include <gtsam/gpstk/CorrectCodeBiases.hpp>\n#include <gtsam/gpstk/ComputeSatPCenter.hpp>\n#include <gtsam/gpstk/RequireObservables.hpp>\n#include <gtsam/gpstk/CorrectObservables.hpp>\n#include <gtsam/gpstk/LinearCombinations.hpp>\n#include <gtsam/gpstk/GravitationalDelay.hpp>\n#include <gtsam/gpstk/PhaseCodeAlignment.hpp>\n\n// GTSAM\n#include <gtsam/slam/dataset.h>\n#include <gtsam/gnssNavigation/GnssData.h>\n\n// BOOST\n#include <boost/program_options.hpp>\n\n// STD\n#include <iomanip>\n#include <iostream>\n\nusing namespace std;\nusing namespace gpstk;\nusing namespace gtsam;\nusing namespace boost;\n\nnamespace po = boost::program_options;\n\nint main(int argc, char *argv[])\n{\n\n        bool usingP1 = false;\n        int dec_int, itsBelowThree = 0, count = 0;\n        string rnx_file, nav_file, sp3_file, out_file;\n\n        cout << fixed << setprecision(12); // Set a proper output format\n\n        po::options_description desc(\"Available options\");\n        desc.add_options()\n                (\"help,h\", \"Print help message\")\n                (\"obs\", po::value<string>(&rnx_file)->default_value(\"\"),\n                \"Observation file to read\")\n                (\"sp3\", po::value<string>(&sp3_file)->default_value(\"\"),\n                \"SP3 file to read.\")\n                (\"out\", po::value<string>(&out_file)->default_value(\"\"),\n                \"output file.\")\n                (\"usingP1\", \"Are you using P1 instead of C1?\")\n                (\"dec\", po::value<int>(&dec_int)->default_value(0),\n                \"decimate input obs file\");\n        po::variables_map vm;\n        po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n        po::notify(vm);\n\n        usingP1 = (vm.count(\"usingP1\")>0);\n\n        if ( rnx_file.empty() )\n        {\n                cout << \" Must pass in obs file !!! Try --obs \" << desc << endl;\n                exit(1);\n        }\n        if ( nav_file.empty() && sp3_file.empty() )\n        {\n                cout << \" Must pass in ephemeris file !!! Try --sp3 or --nav\" << desc << endl;\n                exit(1);\n        }\n\n        string obs_path = findExampleDataFile(rnx_file);\n        string nav_path = findExampleDataFile(sp3_file);\n\n        // Create the input observation file stream\n        Rinex3ObsStream rin(obs_path);\n\n        // Declare a \"SP3EphemerisStore\" object to handle precise ephemeris\n        SP3EphemerisStore SP3EphList;\n\n        // Set flags to reject satellites with bad or absent positional\n        // values or clocks\n        SP3EphList.rejectBadPositions(true);\n        SP3EphList.rejectBadClocks(true);\n\n        // Load all the SP3 ephemerides files\n        SP3EphList.loadFile(nav_path);\n\n        // BELL station nominal position\n        Position nominalPos(856295.3346, -4843033.4111, 4048017.6649);\n\n        CorrectCodeBiases corrCode;\n        corrCode.setDCBFile(\"p1p2.DCB\", \"p1c1.DCB\");\n\n        if (!usingP1) {\n                corrCode.setUsingC1(true);\n        }\n\n\n        // This is the GNSS data structure that will hold all the\n        // GNSS-related information\n        gnssRinex gRin;\n\n        RequireObservables requireObs;\n        requireObs.addRequiredType(TypeID::L1);\n        requireObs.addRequiredType(TypeID::L2);\n\n        SimpleFilter pObsFilter;\n        pObsFilter.setFilteredType(TypeID::C1);\n\n        if ( usingP1 )\n        {\n                requireObs.addRequiredType(TypeID::P1);\n                pObsFilter.addFilteredType(TypeID::P1);\n                requireObs.addRequiredType(TypeID::P2);\n                pObsFilter.addFilteredType(TypeID::P2);\n        }\n        else\n        {\n                requireObs.addRequiredType(TypeID::C1);\n                pObsFilter.addFilteredType(TypeID::C1);\n                requireObs.addRequiredType(TypeID::P2);\n                pObsFilter.addFilteredType(TypeID::P2);\n        }\n\n        // Declare a couple of basic modelers\n        BasicModel basic(nominalPos, SP3EphList);\n\n        // Object to correct for SP3 Sat Phase-center offset\n        AntexReader antexread;\n        antexread.open( \"antenna_corr.atx\" );\n        ComputeSatPCenter svPcenter(SP3EphList, nominalPos);\n        svPcenter.setAntexReader( antexread );\n\n        // Objects to mark cycle slips\n        MWCSDetector markCSMW;  // Checks Merbourne-Wubbena cycle slip\n\n        // Declare an object to correct observables\n        CorrectObservables corr(SP3EphList);\n\n\n        // object def several linear combinations\n        LinearCombinations comb;\n\n        // Object to compute linear combinations for cycle slip detection\n        ComputeLinear linear1;\n        if ( usingP1 )\n        {\n                linear1.addLinear(comb.pdeltaCombination);\n                linear1.addLinear(comb.mwubbenaCombination);\n        }\n        else\n        {\n                linear1.addLinear(comb.pdeltaCombWithC1);\n                linear1.addLinear(comb.mwubbenaCombWithC1);\n        }\n        linear1.addLinear(comb.ldeltaCombination);\n        linear1.addLinear(comb.liCombination);\n\n        ComputeLinear linear2;\n\n        // Read if we should use C1 instead of P1\n        if ( usingP1 )\n        {\n                linear2.addLinear(comb.pcCombination);\n        }\n        else\n        {\n                // WARNING: When using C1 instead of P1 to compute PC combination,\n                //          be aware that instrumental errors will NOT cancel,\n                //          introducing a bias that must be taken into account by\n                //          other means. This won't be taken into account in this\n                //          example.\n                linear2.addLinear(comb.pcCombWithC1);\n        }\n        linear2.addLinear(comb.lcCombination);\n\n        LICSDetector2 markCSLI2;       // Checks LI cycle slips\n\n        // Object to keep track of satellite arcs\n        SatArcMarker markArc;\n        markArc.setDeleteUnstableSats(true);\n\n        // Objects to compute gravitational delay effects\n        GravitationalDelay grDelay(nominalPos);\n\n        // Object to align phase with code measurements\n        PhaseCodeAlignment phaseAlign;\n\n        // Object to remove eclipsed satellites\n        EclipsedSatFilter eclipsedSV;\n\n        //Object to compute wind-up effect\n        ComputeWindUp windup( SP3EphList,\n                              nominalPos );\n\n\n        // Object to compute prefit-residuals\n        ComputeLinear linear3(comb.pcPrefit);\n        linear3.addLinear(comb.lcPrefit);\n\n        CodeSmoother smoothC1;\n\n        TypeIDSet tset;\n        tset.insert(TypeID::prefitC);\n        tset.insert(TypeID::prefitL);\n\n        // Declare a NeillTropModel object, setting the defaults\n        NeillTropModel neillTM( 310, 39.09, 319);\n\n        // Objects to compute the tropospheric data\n        ComputeTropModel computeTropo(neillTM);\n\n        SimpleFilter pcFilter;\n        pcFilter.setFilteredType(TypeID::PC);\n\n        // Loop over all data epochs\n        while(rin >> gRin)\n        {\n                TimeSystem sys;\n                sys.fromString(\"GPS\");\n                CommonTime time(gRin.header.epoch);\n                time.setTimeSystem(sys);\n                GPSWeekSecond gpstime( time );\n\n                try\n                {\n                        gRin >> requireObs // Check if required observations are present\n                        >> pObsFilter // Filter out spurious data\n                        >> linear1 // Compute linear combinations to detect CS\n                        >> markCSLI2 // Mark cycle slips\n                        >> markCSMW // Mark cycle slips: Melbourne-Wubbena\n                        >> markArc // Keep track of satellite arcs\n                        >> basic // Compute the basic components of model\n                        >> eclipsedSV // Remove satellites in eclipse\n                        >> svPcenter // Computer delta for sat. phase center\n                        >> linear2  // Compute ionosphere-free combinations\n                        >> corr // SP3 Corrections\n                        >> corrCode // Correct for differential code biases\n                        >> windup // phase windup correction\n                        >> grDelay // Compute gravitational delay\n                        >> computeTropo // neill trop function\n                        >> pcFilter  // screen PC\n                        >> phaseAlign; // Align phases with codes\n\n                }\n                catch(Exception& e)\n                {\n                        //cerr << \"Exception at epoch: \" << time << \"; \" << e << endl;\n                        continue;\n                }\n                catch(...)\n                {\n                        cerr << \"Unknown exception at epoch: \" << time << endl;\n                        continue;\n                }\n                TypeIDSet types;\n                types.insert(TypeID::satX);\n                types.insert(TypeID::satY);\n                types.insert(TypeID::satZ);\n                types.insert(TypeID::PC);\n                types.insert(TypeID::LC);\n                types.insert(TypeID::rho);\n                types.insert(TypeID::tropo);\n                types.insert(TypeID::tropoSlant);\n                types.insert(TypeID::dtSat);\n                types.insert(TypeID::rel);\n                types.insert(TypeID::gravDelay);\n                types.insert(TypeID::instC1);\n                types.insert(TypeID::instC2);\n                types.insert(TypeID::satArc);\n                types.insert(TypeID::satPCenter);\n                types.insert(TypeID::windUp);\n                gRin.keepOnlyTypeID(types);\n\n                // Iterate through the GNSS Data Structure\n                satTypeValueMap::const_iterator it;\n                typeValueMap::const_iterator itObs;\n                if (gRin.numSats() > 4)\n                {\n                        if ( itsBelowThree > 0 )\n                        {\n                                itsBelowThree = 0;\n                                continue;\n                        }\n                        for (it = gRin.body.begin(); it!= gRin.body.end(); it++)\n                        {\n                                cout << gpstime.week << \" \";\n                                cout << gpstime.sow << \" \";\n                                cout << count << \" \";\n                                cout << (*it).first << \" \";\n\n                                typeValueMap::const_iterator itObs;\n                                for( itObs  = (*it).second.begin(); itObs != (*it).second.end(); itObs++ )\n                                {\n                                        //cout << (*itObs).first << \" \";\n                                        cout << (*itObs).second << \" \";\n                                }\n                                cout << endl;\n                        }\n                        count++;\n                }\n                else { itsBelowThree++; }\n        }\n        return 0;\n}\n", "meta": {"hexsha": "e198521742db8fbb9d84f173cd05dbc56f80844a", "size": 12209, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gtsam/gnssExamples/rnx2Gtsam.cpp", "max_stars_repo_name": "mfkiwl/RobustGNSS", "max_stars_repo_head_hexsha": "f7774af62eb6eaf2198b5a7ca6f2a63dc87a4f7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 105.0, "max_stars_repo_stars_event_min_datetime": "2017-12-02T14:39:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-19T18:20:25.000Z", "max_issues_repo_path": "gtsam/gnssExamples/rnx2Gtsam.cpp", "max_issues_repo_name": "jianlun37/RobustGNSS", "max_issues_repo_head_hexsha": "5c0ea1861b651a79e880ea8d23b9c2458dc11e10", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-09-04T15:15:59.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-08T08:51:02.000Z", "max_forks_repo_path": "gtsam/gnssExamples/rnx2Gtsam.cpp", "max_forks_repo_name": "jianlun37/RobustGNSS", "max_forks_repo_head_hexsha": "5c0ea1861b651a79e880ea8d23b9c2458dc11e10", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 31.0, "max_forks_repo_forks_event_min_datetime": "2018-01-10T03:21:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-06T06:18:35.000Z", "avg_line_length": 36.0147492625, "max_line_length": 106, "alphanum_fraction": 0.5527070194, "num_tokens": 2798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.20841300170451543}}
{"text": "#include \"lingua/chat.hxx\"\n#include <FlexLexer.h>\n#include <re2/re2.h>\n#include <boost/tokenizer.hpp>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <algorithm>\n#include <random>\n#include <fstream>\n#include <iostream>\n#include <cstdio>\n#include <cmath>\n#include <cfloat>\n#include <chrono>\n\nnamespace lingua {\n    float operator*(const SemanticVector &lhs, const SemanticVector &rhs) {\n        float result = 0;\n        auto vl = ChatEngine::instance->getVectorLength();\n        for (auto i = 0; i < vl; ++i)\n            result += lhs.values[i] * rhs.values[i];\n        return result;\n    }\n\n    float cosine(const SemanticVector &lhs, const SemanticVector &rhs) {\n        return (lhs * rhs) / (lhs.magnitude() * rhs.magnitude());\n    }\n\n    SemanticVector::SemanticVector() : values(new float[ChatEngine::instance->getVectorLength()]) {\n        auto vl = ChatEngine::instance->getVectorLength();\n        auto seed = std::chrono::system_clock::now().time_since_epoch().count();\n        std::default_random_engine gen(seed);\n        std::uniform_real_distribution<float> dist(-1.0, 1.0);\n\n        for (auto i = 0; i < vl; ++i)\n            values[i] = dist(gen);\n    }\n\n    SemanticVector::SemanticVector(const float *vs) : values(new float[ChatEngine::instance->getVectorLength()]) {\n        auto vl = ChatEngine::instance->getVectorLength();\n\n        for (auto i = 0; i < vl; ++i)\n            values[i] = vs[i];\n    }\n\n    SemanticVector& SemanticVector::operator=(const SemanticVector &other) {\n        values = other.values;\n        return *this;\n    }\n\n    const float* SemanticVector::getValues() const {\n        return values;\n    }\n\n    float SemanticVector::getValue(size_t ix) const {\n        return values[ix];\n    }\n\n    void SemanticVector::setValues(const float *vs) {\n        auto vl = ChatEngine::instance->getVectorLength();\n\n        for (auto i = 0; i < vl; ++i)\n            values[i] = vs[i];\n    }\n\n    void SemanticVector::setValue(size_t ix, float value) {\n        values[ix] = value;\n    }\n\n    float SemanticVector::magnitude() const {\n        auto vl = ChatEngine::instance->getVectorLength();\n        float result = 0;\n\n        for (auto i = 0; i < vl; ++i)\n            result += values[i] * values[i];\n\n        return std::sqrt(result);\n    }\n\n    WordInfo::WordInfo(tag_t t, const std::string &txt) : tag(t), text(txt), semEmb(new SemanticVector), ctxEmb(new SemanticVector) { }\n\n    tag_t WordInfo::getTag() const {\n        return tag;\n    }\n\n    std::string WordInfo::getText() const {\n        return text;\n    }\n\n    SemanticVector* WordInfo::getSemanticEmbedding() {\n        return semEmb;\n    }\n\n    SemanticVector* WordInfo::getContextEmbedding() {\n        return ctxEmb;\n    }\n\n    void WordInfo::setSemanticEmbedding(const SemanticVector &sv) {\n        if (semEmb)\n            *semEmb = sv;\n        else {\n            semEmb = new SemanticVector(sv);\n        }\n    }\n\n    void WordInfo::setContextEmbedding(const SemanticVector &cv) {\n        if (ctxEmb)\n            *ctxEmb = cv;\n        else {\n            ctxEmb = new SemanticVector(cv);\n        }\n    }\n\n    std::string ChatEngine::Tokenizer::currentTitle = \"\";\n\n    std::string ChatEngine::Tokenizer::currentBody;\n\n    ChatEngine* ChatEngine::instance = nullptr;\n\n    ChatEngine::ChatEngine(unsigned pvl, unsigned pcn, unsigned pnr) : sourceFile(\"-\"), docs(), pVectorLength(pvl), pContextNeighborhood(pcn), pNoiseRatio(pnr), learningRate(PARAM_DEFAULT_INITIAL_LEARNING_RATE), dict(), infotbl() { }\n\n    ChatEngine::ChatEngine(const std::string &src, unsigned pvl, unsigned pcn, unsigned pnr) : sourceFile(src), docs(), pVectorLength(pvl), pContextNeighborhood(pcn), pNoiseRatio(pnr), learningRate(PARAM_DEFAULT_INITIAL_LEARNING_RATE), dict(), infotbl() { }\n\n    void ChatEngine::initialize(unsigned pvl, unsigned pcn, unsigned pnr) {\n        instance = new ChatEngine(pvl, pcn, pnr);\n    }\n\n    void ChatEngine::initialize(const std::string &src, unsigned pvl, unsigned pvn, unsigned pnr) {\n        instance = new ChatEngine(src, pvl, pvn, pnr);\n    }\n\n    void ChatEngine::analyzeSemantics() {\n        preprocess();\n        learnSemantics();\n    }\n\n    void ChatEngine::learnSemantics() {\n        for (auto it = docs.begin(); it != docs.end(); ++it)\n            trainOn(*it);\n    }\n\n    void ChatEngine::trainOn(const Document &doc) {\n        auto toks = doc.getTokens();\n        std::size_t targetIndex = pContextNeighborhood;\n        std::size_t lastTargetIndex = toks.size() - pContextNeighborhood - 1;\n\n        while (targetIndex < lastTargetIndex) {\n            auto beginContext = toks.begin() + targetIndex - pContextNeighborhood;\n            auto targetPos = toks.begin() + targetIndex;\n            auto endContext = toks.begin() + targetIndex + pContextNeighborhood;\n            WordInfo targetInfo = infotbl[toks[targetIndex]];\n            auto targetEmbedding = targetInfo.getSemanticEmbedding();\n            std::vector<WordInfo> contextInfo;\n            std::vector<WordInfo> noiseInfo;\n            std::vector<SemanticVector*> contextEmbeddings;\n            std::vector<SemanticVector*> noiseEmbeddings;\n            std::vector<tag_t> contextTags(beginContext, targetPos);\n            std::vector<tag_t> backContextTags(targetPos + 1, endContext);\n            std::vector<tag_t> noiseTags;\n\n            contextTags.resize(contextTags.size() << 1);\n            contextTags.insert(contextTags.end(), backContextTags.begin(), backContextTags.end());\n\n            noiseTags = generateNoise(contextTags);\n\n            contextInfo.resize(contextTags.size());\n            std::transform(contextTags.begin(), contextTags.end(),\n                           contextInfo.begin(), [&](auto tag) { return this->getInfotbl()[tag]; });\n\n            contextEmbeddings.resize(contextInfo.size());\n            std::transform(contextInfo.begin(), contextInfo.end(),\n                           contextEmbeddings.begin(), [&](auto ci) { return ci.getSemanticEmbedding(); });\n\n            noiseInfo.resize(noiseTags.size());\n            std::transform(noiseTags.begin(), noiseTags.end(),\n                           noiseInfo.begin(), [&](auto tag) { return this->getInfotbl()[tag]; });\n\n            noiseEmbeddings.resize(noiseInfo.size());\n            std::transform(noiseInfo.begin(), noiseInfo.end(),\n                           noiseEmbeddings.begin(), [&](auto ni) { return ni.getSemanticEmbedding(); });\n\n            trainTargetEmbedding(targetEmbedding, contextEmbeddings, noiseEmbeddings);\n            ++targetIndex;\n            break; // DEBUG\n        }\n    }\n\n    void ChatEngine::trainTargetEmbedding(SemanticVector *targetEmbedding, const std::vector<SemanticVector*> &contextEmbeddings, const std::vector<SemanticVector*> &noiseEmbeddings) {\n\n    }\n\n    std::vector<tag_t> ChatEngine::generateNoise(const std::vector<tag_t> &ctx) {\n        auto seed = std::chrono::system_clock::now().time_since_epoch().count();\n        std::default_random_engine gen(seed);\n        std::uniform_int_distribution<tag_t> dist;\n        auto limit = infotbl.size();\n        auto needed = ctx.size() * pNoiseRatio;\n        std::vector<tag_t> noise;\n\n        while (noise.size() < needed) {\n            auto candidate = dist(gen) % limit;\n            if (std::find(ctx.cbegin(), ctx.cend(), candidate) == ctx.cend())\n                noise.push_back(candidate);\n        }\n\n        return noise;\n    }\n\n    std::string ChatEngine::getSourceFile() const {\n        return sourceFile;\n    }\n\n    std::vector<Document> ChatEngine::getDocs() const {\n        return docs;\n    }\n\n    unsigned ChatEngine::getVectorLength() const {\n        return pVectorLength;\n    }\n\n    unsigned ChatEngine::getContextNeighborhood() const {\n        return pContextNeighborhood;\n    }\n\n    unsigned ChatEngine::getNoiseRatio() const {\n        return pNoiseRatio;\n    }\n\n    float ChatEngine::getLearningRate() const {\n        return learningRate;\n    }\n\n    Dictionary ChatEngine::getDict() const {\n        return dict;\n    }\n\n    Infotbl ChatEngine::getInfotbl() const {\n        return infotbl;\n    }\n\n    void ChatEngine::setSourceFile(const std::string &src) {\n        sourceFile = src;\n    }\n\n    void ChatEngine::addDoc(const Document &doc) {\n        docs.push_back(doc);\n    }\n\n    Document ChatEngine::tokenize(const std::string &text) {\n        boost::tokenizer<> tknzr(text);\n        std::vector<tag_t> toks;\n\n        for (auto it = tknzr.begin(); it != tknzr.end(); ++it) {\n            if (dict.find(*it) != dict.end())\n                toks.push_back(dict[*it]);\n            else {\n                tag_t tkn = dict.size();\n                dict[*it] = tkn;\n                infotbl[tkn] = WordInfo(tkn, *it);\n                toks.push_back(tkn);\n            }\n        }\n\n        return Document(toks);\n    }\n\n    void ChatEngine::printDocuments() const {\n        for (auto it = docs.begin(); it != docs.end(); ++it)\n            it->printTokens();\n    }\n\n    void ChatEngine::preprocess() {\n        std::ifstream fh(sourceFile);\n        std::ofstream nullDev(\"/dev/null\");\n        FlexLexer *lexer = new yyFlexLexer(fh, nullDev);\n\n        lexer->yylex();\n    }\n}\n", "meta": {"hexsha": "e59467d36149f82d21bf7e70e29bf3f3bb7427d6", "size": 9119, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/chat.cxx", "max_stars_repo_name": "jamesbolden/lingua", "max_stars_repo_head_hexsha": "3824458338c572c83051031208d660958c085944", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/chat.cxx", "max_issues_repo_name": "jamesbolden/lingua", "max_issues_repo_head_hexsha": "3824458338c572c83051031208d660958c085944", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/chat.cxx", "max_forks_repo_name": "jamesbolden/lingua", "max_forks_repo_head_hexsha": "3824458338c572c83051031208d660958c085944", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5678571429, "max_line_length": 257, "alphanum_fraction": 0.6044522426, "num_tokens": 2153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.3007455852086007, "lm_q1q2_score": 0.2083090147416879}}
{"text": "#include \"RayTrace.h\"\n#include <cmath>\n#include <iterator>\n#include <algorithm>\n#include <limits>\n#include <queue>\n\n#include <boost/scoped_ptr.hpp>\n\nnamespace RayTrace{\n\t\n\tconst double TraceRecord::noReflection(100.0);\n\t\n\t//========== minimalRayPosition ==========//\n\t\n\tminimalRayPosition::minimalRayPosition():\n\tx(0.0),z(0.0),theta(0.0){}\n\t\n\tminimalRayPosition::minimalRayPosition(double x_, double z_, double theta_):\n\tx(x_),z(z_),theta(theta_){}\n\t\n\tminimalRayPosition& minimalRayPosition::operator +=(const minimalRayPosition& p){\n\t\tx+=p.x;\n\t\tz+=p.z;\n\t\ttheta+=p.theta;\n\t\treturn(*this);\n\t}\n\t\n\tminimalRayPosition& minimalRayPosition::operator -=(const minimalRayPosition& p){\n\t\tx-=p.x;\n\t\tz-=p.z;\n\t\ttheta-=p.theta;\n\t\treturn(*this);\n\t}\n\t\n\tminimalRayPosition& minimalRayPosition::operator *=(double m){\n\t\tx*=m;\n\t\tz*=m;\n\t\ttheta*=m;\n\t\treturn(*this);\n\t}\n\t\n\tconst minimalRayPosition minimalRayPosition::operator +(const minimalRayPosition& p) const{\n\t\tminimalRayPosition res=*this;\n\t\treturn(res+=p);\n\t}\n\t\n\tconst minimalRayPosition minimalRayPosition::operator -(const minimalRayPosition& p) const{\n\t\tminimalRayPosition res=*this;\n\t\treturn(res-=p);\n\t}\n\t\n\tconst minimalRayPosition minimalRayPosition::operator *(double m) const{\n\t\tminimalRayPosition res=*this;\n\t\treturn(res*=m);\n\t}\n\t\n\tconst minimalRayPosition operator *(double m, const minimalRayPosition& p){\n\t\treturn(p*m);\n\t}\n\t\n\tminimalRayPosition abs(const minimalRayPosition& p){\n\t\treturn(minimalRayPosition(std::abs(p.x), std::abs(p.z), std::abs(p.theta)));\n\t}\n\t\n\tvoid minimalRayPosition::makeTiny(double s){\n\t\tx=s;\n\t\tz=s;\n\t\ttheta=s;\n\t}\n\t\n\tvoid minimalRayPosition::giveData(TraceRecord& trace) const{\n\t\ttrace.pathTime=-1.0;\n\t\ttrace.receiptAngle=theta;\n\t\ttrace.attenuation=-1.0;\n\t}\n\t\n\t//========== rayPosition ==========//\n\t\n\trayPosition::rayPosition():\n\tx(0.0),z(0.0),theta(0.0),time(0.0){}\n\t\n\trayPosition::rayPosition(double x_, double z_, double theta_, double time_):\n\tx(x_),z(z_),theta(theta_),time(time_){}\n\t\n\trayPosition& rayPosition::operator +=(const rayPosition& p){\n\t\tx+=p.x;\n\t\tz+=p.z;\n\t\ttheta+=p.theta;\n\t\ttime+=p.time;\n\t\treturn(*this);\n\t}\n\t\n\trayPosition& rayPosition::operator -=(const rayPosition& p){\n\t\tx-=p.x;\n\t\tz-=p.z;\n\t\ttheta-=p.theta;\n\t\ttime-=p.time;\n\t\treturn(*this);\n\t}\n\t\n\trayPosition& rayPosition::operator *=(double m){\n\t\tx*=m;\n\t\tz*=m;\n\t\ttheta*=m;\n\t\ttime*=m;\n\t\treturn(*this);\n\t}\n\t\n\tconst rayPosition rayPosition::operator +(const rayPosition& p) const{\n\t\trayPosition res=*this;\n\t\treturn(res+=p);\n\t}\n\t\n\tconst rayPosition rayPosition::operator -(const rayPosition& p) const{\n\t\trayPosition res=*this;\n\t\treturn(res-=p);\n\t}\n\t\n\tconst rayPosition rayPosition::operator *(double m) const{\n\t\trayPosition res=*this;\n\t\treturn(res*=m);\n\t}\n\t\n\tconst rayPosition operator *(double m, const rayPosition& p){\n\t\treturn(p*m);\n\t}\n\t\n\trayPosition abs(const rayPosition& p){\n\t\treturn(rayPosition(std::abs(p.x), std::abs(p.z), std::abs(p.theta), std::abs(p.time)));\n\t}\n\t\n\tvoid rayPosition::makeTiny(double s){\n\t\tx=s;\n\t\tz=s;\n\t\ttheta=s;\n\t\ttime=s;\n\t}\n\t\n\tvoid rayPosition::giveData(TraceRecord& trace) const{\n\t\ttrace.pathTime=time;\n\t\ttrace.receiptAngle=theta;\n\t\ttrace.attenuation=-1.0;\n\t}\n\n\t//========== fullRayPosition ==========//\n\t\n\tfullRayPosition::fullRayPosition():\n\tx(0.0),z(0.0),theta(0.0),time(0.0),attenuation(1.0){}\n\t\n\tfullRayPosition::fullRayPosition(double x_, double z_, double theta_, double time_, double attenuation_):\n\tx(x_),z(z_),theta(theta_),time(time_),attenuation(attenuation_){}\n\t\n\tfullRayPosition& fullRayPosition::operator +=(const fullRayPosition& p){\n\t\tx+=p.x;\n\t\tz+=p.z;\n\t\ttheta+=p.theta;\n\t\ttime+=p.time;\n\t\tattenuation+=p.attenuation;\n\t\treturn(*this);\n\t}\n\t\n\tfullRayPosition& fullRayPosition::operator -=(const fullRayPosition& p){\n\t\tx-=p.x;\n\t\tz-=p.z;\n\t\ttheta-=p.theta;\n\t\ttime-=p.time;\n\t\tattenuation-=p.attenuation;\n\t\treturn(*this);\n\t}\n\t\n\tfullRayPosition& fullRayPosition::operator *=(double m){\n\t\tx*=m;\n\t\tz*=m;\n\t\ttheta*=m;\n\t\ttime*=m;\n\t\tattenuation*=m;\n\t\treturn(*this);\n\t}\n\t\n\tconst fullRayPosition fullRayPosition::operator +(const fullRayPosition& p) const{\n\t\tfullRayPosition res=*this;\n\t\treturn(res+=p);\n\t}\n\t\n\tconst fullRayPosition fullRayPosition::operator -(const fullRayPosition& p) const{\n\t\tfullRayPosition res=*this;\n\t\treturn(res-=p);\n\t}\n\t\n\tconst fullRayPosition fullRayPosition::operator *(double m) const{\n\t\tfullRayPosition res=*this;\n\t\treturn(res*=m);\n\t}\n\t\n\tconst fullRayPosition operator *(double m, const fullRayPosition& p){\n\t\treturn(p*m);\n\t}\n\t\n\tfullRayPosition abs(const fullRayPosition& p){\n\t\treturn(fullRayPosition(std::abs(p.x), std::abs(p.z), std::abs(p.theta), std::abs(p.time), std::abs(p.attenuation)));\n\t}\n\t\n\tvoid fullRayPosition::makeTiny(double s){\n\t\tx=s;\n\t\tz=s;\n\t\ttheta=s;\n\t\ttime=s;\n\t\tattenuation=s;\n\t}\n\t\n\tvoid fullRayPosition::giveData(TraceRecord& trace) const{\n\t\ttrace.pathTime=time;\n\t\ttrace.receiptAngle=theta;\n\t\ttrace.attenuation=attenuation;\n\t}\n\n\t//========== TraceFinder ==========//\n\n\t//const double TraceFinder::maximum_ice_depth = -2850.0;\n\tconst double TraceFinder::maximum_ice_depth = -3500.0; // changed for testing max ice depth\n\t\n\t///\\brief Computes the derivatives of the position coordinates with respect to path length\n\t///\n\t///This specialization computes the minimum usable set of coordinates: the radial and vertical \n\t///position and the angle. \n\t///\n\t///\\param pos The position at which the derivatives are to be computed\n\t///\\param der The object into which to record the calculated derivatives\n\t///\\param frequency The frequency of the signal being propogated, in GHz\n\ttemplate<>\n\tvoid TraceFinder::computeRayDerivatives<minimalRayPosition>(const minimalRayPosition& pos, minimalRayPosition& der, double frequency) const{\n\t\t//put dn/dz into der.theta\n\t\tdouble n;\n\t\trModel->indexOfRefractionWithDerivative(pos.z,n,der.theta);\n\t\tder.x = sin(pos.theta);\n\t\tder.z = cos(pos.theta);\n\t\tder.theta = -(der.x * der.theta)/n;\n\t}\n\t\n\t///\\brief Computes the derivatives of the position coordinates with respect to path length\n\t///\n\t///This specialization computes an intermediate set of coordinates: the radial and \n\t///vertical position, the angle, and the time of flight. \n\t///\n\t///\\param pos The position at which the derivatives are to be computed\n\t///\\param der The object into which to record the calculated derivatives\n\t///\\param frequency The frequency of the signal being propogated, in GHz\n\ttemplate<>\n\tvoid TraceFinder::computeRayDerivatives<rayPosition>(const rayPosition& pos, rayPosition& der, double frequency) const{\n\t\t//put n int der.time, put dn/dz into der.theta\n\t\trModel->indexOfRefractionWithDerivative(pos.z,der.time,der.theta);\n\t\tder.x = sin(pos.theta);\n\t\tder.z = cos(pos.theta);\n\t\tder.theta = -(der.x * der.theta)/der.time;\n\t\tder.time /= speedOfLight;\n\t}\n\t\n\t///\\brief Computes the derivatives of the position coordinates with respect to path length\n\t///\n\t///This specialization computes a complete set of coordinates: the radial and vertical \n\t///position, the angle, the time of flight, and the amplitude correction. \n\t///\n\t///\\param pos The position at which the derivatives are to be computed\n\t///\\param der The object into which to record the calculated derivatives\n\t///\\param frequency The frequency of the signal being propogated, in GHz\n\ttemplate<>\n\tvoid TraceFinder::computeRayDerivatives<fullRayPosition>(const fullRayPosition& pos, fullRayPosition& der, double frequency) const{\n\t\t//put n int der.time, put dn/dz into der.theta\n\t\trModel->indexOfRefractionWithDerivative(pos.z,der.time,der.theta);\n\t\tder.x = sin(pos.theta);\n\t\tder.z = cos(pos.theta);\n\t\tder.theta = -(der.x * der.theta)/der.time;\n\t\tder.time /= speedOfLight;\n\t\tder.attenuation=-pos.attenuation/aModel->attenuationLength(pos.z,frequency);\n\t\t//std::cout << \"  eval with z=\" << pos.z << \" att=\" << pos.attenuation << \" yields \" << der.attenuation << std::endl;\n\t}\n\n\ttemplate<typename positionType>\n\tvoid TraceFinder::rkStep(const positionType& pos, const typename positionType::derivativeType& der, const double h, positionType& newPos, positionType& errors, const double frequency) const{\n\t\t//const double a[5] = {0.2, 0.3, 0.6, 1.0, 0.875};\n\t\tconst double b[15] = {0.2, 0.075, 0.3, -11.0/54.0, 1631.0/55296.0, \n\t\t\t0.225, -0.9, 2.5, 175.0/512.0, \n\t\t\t1.2, -70.0/27.0, 575.0/13824.0, \n\t\t\t35.0/27.0, 44275.0/110592.0, \n\t\t\t253.0/4096.0};\n\t\tconst double c[6] = {37.0/378.0, 0, 250.0/621.0, 125.0/594.0, 0, 512.0/1771.0};\n\t\tconst double cp[6] = {c[0]-2825.0/27648.0, 0, c[2]-18575.0/48384.0, c[3]-13525.0/55296.0, c[4]-277.0/14336.0, c[5]-0.25};\n\t\t\n\t\tpositionType temp;\n\t\ttypename positionType::derivativeType ak2, ak3, ak4, ak5, ak6; //derivatives\n\t\t//first step\n\t\ttemp = pos + h*b[0]*der;\n\t\t//second step\n\t\tcomputeRayDerivatives(temp,ak2,frequency);\n\t\ttemp = pos + h*(b[1]*der + b[5]*ak2);\n\t\t//third step\n\t\tcomputeRayDerivatives(temp,ak3,frequency);\n\t\ttemp = pos + h*(b[2]*der + b[6]*ak2 + b[9]*ak3);\n\t\t//fourth step\n\t\tcomputeRayDerivatives(temp,ak4,frequency);\n\t\ttemp = pos + h*(b[3]*der + b[7]*ak2 + b[10]*ak3 + b[12]*ak4);\n\t\t//fifth step\n\t\tcomputeRayDerivatives(temp,ak5,frequency);\n\t\ttemp = pos + h*(b[4]*der + b[8]*ak2 + b[11]*ak3 + b[13]*ak4 + b[14]*ak5);\n\t\t//sixth step\n\t\tcomputeRayDerivatives(temp,ak6,frequency);\n\t\tnewPos = pos + h*(c[0]*der + c[2]*ak3 + c[3]*ak4 + c[5]*ak6);\n\t\t//estimate error\n\t\terrors = h*(cp[0]*der + cp[2]*ak3 + cp[3]*ak4 + cp[4]*ak5 + cp[5]*ak6);\n\t}\n\t\n\ttemplate<typename positionType>\n\tvoid TraceFinder::rkStep(const positionRecordingWrapper<positionType>& pos, const typename positionRecordingWrapper<positionType>::derivativeType& der, const double h, positionRecordingWrapper<positionType>& newPos, positionRecordingWrapper<positionType>& errors, const double frequency) const{\n\t\t//const double a[5] = {0.2, 0.3, 0.6, 1.0, 0.875};\n\t\tconst double b[15] = {0.2, 0.075, 0.3, -11.0/54.0, 1631.0/55296.0, \n\t\t\t0.225, -0.9, 2.5, 175.0/512.0, \n\t\t\t1.2, -70.0/27.0, 575.0/13824.0, \n\t\t\t35.0/27.0, 44275.0/110592.0, \n\t\t\t253.0/4096.0};\n\t\tconst double c[6] = {37.0/378.0, 0, 250.0/621.0, 125.0/594.0, 0, 512.0/1771.0};\n\t\tconst double cp[6] = {c[0]-2825.0/27648.0, 0, c[2]-18575.0/48384.0, c[3]-13525.0/55296.0, c[4]-277.0/14336.0, c[5]-0.25};\n\t\t\n\t\tpositionRecordingWrapper<positionType> temp;\n\t\ttypename positionRecordingWrapper<positionType>::derivativeType ak2, ak3, ak4, ak5, ak6; //derivatives\n\t\t//first step\n\t\ttemp = pos + h*b[0]*der;\n\t\ttemp.recordStep(1);\n\t\t//second step\n\t\tcomputeRayDerivatives(temp,ak2,frequency);\n\t\ttemp = pos + h*(b[1]*der + b[5]*ak2);\n\t\ttemp.recordStep(2);\n\t\t//third step\n\t\tcomputeRayDerivatives(temp,ak3,frequency);\n\t\ttemp = pos + h*(b[2]*der + b[6]*ak2 + b[9]*ak3);\n\t\ttemp.recordStep(3);\n\t\t//fourth step\n\t\tcomputeRayDerivatives(temp,ak4,frequency);\n\t\ttemp = pos + h*(b[3]*der + b[7]*ak2 + b[10]*ak3 + b[12]*ak4);\n\t\ttemp.recordStep(4);\n\t\t//fifth step\n\t\tcomputeRayDerivatives(temp,ak5,frequency);\n\t\ttemp = pos + h*(b[4]*der + b[8]*ak2 + b[11]*ak3 + b[13]*ak4 + b[14]*ak5);\n\t\ttemp.recordStep(5);\n\t\t//sixth step\n\t\tcomputeRayDerivatives(temp,ak6,frequency);\n\t\tnewPos = pos + h*(c[0]*der + c[2]*ak3 + c[3]*ak4 + c[5]*ak6);\n\t\tnewPos.takeStepData(temp);\n\t\t//estimate error\n\t\terrors = h*(cp[0]*der + cp[2]*ak3 + cp[3]*ak4 + cp[4]*ak5 + cp[5]*ak6);\n\t}\n\t\n\tvoid TraceFinder::replayRkStep(const rkStepRecord& step, const double atten, const double& attenDer, double& newAtten, const double frequency) const{\n\t\tconst double b[15] = {0.2, 0.075, 0.3, -11.0/54.0, 1631.0/55296.0, \n\t\t\t0.225, -0.9, 2.5, 175.0/512.0, \n\t\t\t1.2, -70.0/27.0, 575.0/13824.0, \n\t\t\t35.0/27.0, 44275.0/110592.0, \n\t\t\t253.0/4096.0};\n\t\tconst double c[6] = {37.0/378.0, 0, 250.0/621.0, 125.0/594.0, 0, 512.0/1771.0};\n\t\t\n\t\tdouble temp;\n\t\tdouble ak2, ak3, ak4, ak5, ak6; //derivatives\n\t\t\n\t\t//first step\n\t\ttemp = atten + step.length*b[0]*attenDer;\n\t\t//second step\n\t\tak2=-temp/aModel->attenuationLength(step.z[1],frequency);\n\t\t//std::cout << \"  eval with z=\" << step.z[1] << \" att=\" << temp << \" yields \" << ak2 << std::endl;\n\t\ttemp = atten + step.length*(b[1]*attenDer + b[5]*ak2);\n\t\t//third step\n\t\tak3=-temp/aModel->attenuationLength(step.z[2],frequency);\n\t\t//std::cout << \"  eval with z=\" << step.z[2] << \" att=\" << temp << \" yields \" << ak3 << std::endl;\n\t\ttemp = atten + step.length*(b[2]*attenDer + b[6]*ak2 + b[9]*ak3);\n\t\t//fourth step\n\t\tak4=-temp/aModel->attenuationLength(step.z[3],frequency);\n\t\t//std::cout << \"  eval with z=\" << step.z[3] << \" att=\" << temp << \" yields \" << ak4 << std::endl;\n\t\ttemp = atten + step.length*(b[3]*attenDer + b[7]*ak2 + b[10]*ak3 + b[12]*ak4);\n\t\t//fifth step\n\t\tak5=-temp/aModel->attenuationLength(step.z[4],frequency);\n\t\t//std::cout << \"  eval with z=\" << step.z[4] << \" att=\" << temp << \" yields \" << ak5 << std::endl;\n\t\ttemp = atten + step.length*(b[4]*attenDer + b[8]*ak2 + b[11]*ak3 + b[13]*ak4 + b[14]*ak5);\n\t\t//sixth step\n\t\tak6=-temp/aModel->attenuationLength(step.z[5],frequency);\n\t\t//std::cout << \"  eval with z=\" << step.z[5] << \" att=\" << temp << \" yields \" << ak6 << std::endl;\n\t\tnewAtten = atten + step.length*(c[0]*attenDer + c[2]*ak3 + c[3]*ak4 + c[5]*ak6);\n\t}\n\t\n\t///\\brief Computes the maximum of a set of coordinate errors, scaled by given factors\n\t///\n\t///This specialization computes the minimum usable set of coordinates: the radial and \n\t///vertical position and the angle. \n\t///\n\t///\\param errors The coordinate errors\n\t///\\param scale The scaling factors for the errors\n\t///\\return The maximum error divided by its associated scale\n\ttemplate<>\n\tdouble TraceFinder::maxError<minimalRayPosition>(const minimalRayPosition& errors, const minimalRayPosition& scale) const{\n\t\tdouble result=std::abs(errors.x/scale.x);\n\t\tresult=std::max(result,std::abs(errors.z/scale.z));\n\t\tresult=std::max(result,std::abs(errors.theta/scale.theta));\n\t\treturn(result);\n\t}\n\t\n\t///\\brief Computes the maximum of a set of coordinate errors, scaled by given factors\n\t///\n\t///This specialization computes an intermediate set of coordinates: the radial and \n\t///vertical position, the angle, and the time of flight. \n\t///\n\t///\\param errors The coordinate errors\n\t///\\param scale The scaling factors for the errors\n\t///\\return The maximum error divided by its associated scale\n\ttemplate<>\n\tdouble TraceFinder::maxError<rayPosition>(const rayPosition& errors, const rayPosition& scale) const{\n\t\tdouble result=std::abs(errors.x/scale.x);\n\t\tresult=std::max(result,std::abs(errors.z/scale.z));\n\t\tresult=std::max(result,std::abs(errors.theta/scale.theta));\n\t\tresult=std::max(result,std::abs(errors.time/scale.time));\n\t\treturn(result);\n\t}\n\t\n\t///\\brief Computes the maximum of a set of coordinate errors, scaled by given factors\n\t///\n\t///This specialization computes a complete set of coordinates: the radial and vertical \n\t///position, the angle, the time of flight, and the amplitude correction. \n\t///\n\t///\\param errors The coordinate errors\n\t///\\param scale The scaling factors for the errors\n\t///\\return The maximum error divided by its associated scale\n\ttemplate<>\n\tdouble TraceFinder::maxError<fullRayPosition>(const fullRayPosition& errors, const fullRayPosition& scale) const{\n\t\tdouble result=std::abs(errors.x/scale.x);\n\t\tresult=std::max(result,std::abs(errors.z/scale.z));\n\t\tresult=std::max(result,std::abs(errors.theta/scale.theta));\n\t\tresult=std::max(result,std::abs(errors.time/scale.time));\n\t\tresult=std::max(result,std::abs(errors.attenuation/scale.attenuation));\n\t\treturn(result);\n\t}\n\t\n\ttemplate<typename positionType>\n\tvoid confirmFinalStepPosition(positionType& pos, const positionType& temp, const double& length){\n\t\tpos=temp;\n\t}\n\t\n\ttemplate<typename positionType>\n\tvoid confirmFinalStepPosition(positionRecordingWrapper<positionType>& pos, const positionRecordingWrapper<positionType>& temp, const double& length){\n\t\tdouble startZ=pos.z;\n\t\tpos=temp;\n\t\tpos.setFirstStep(startZ);\n\t\tpos.setStepLength(length);\n\t\t//pos.dumpData();\n\t}\n\n\t//requires htry>0 !!!\n\ttemplate<typename positionType>\n\tvoid TraceFinder::rkStepControl(double& length, double frequency, positionType& pos, typename positionType::derivativeType& der, const positionType& scale, const double htry, const double eps, double& hdid, double& hnext) const{\n\t\tconst double SAFETY=0.9;\n\t\t//const double growthPower=-0.2;\n\t\t//const double shrinkPower=-0.25;\n\t\tconst double growLimit=1.89e-4; //=(5.0/SAFETY)**(1/growthPower)\n\t\tconst double shrinkLimit=6561.0; //=(.1/SAFETY)**(1/shrinkPower)\n\t\t\n\t\t//std::cout << \"\\tTrying RK(CK) step of size \" << htry << std::endl;\n\t\t\n\t\tdouble h=htry, errMax;\n\t\tpositionType errors, temp;\n                //std::cerr<<\"begin while loop\"<<std::endl;\n\t\twhile(true){\n\t\t\t//take step\n\t\t\trkStep(pos,der,h,temp,errors,frequency);\n\t\t\terrMax=maxError(errors,scale)/eps;\n\t\t\tif(errMax<=1.0) {\n                                //std::cout<<\"errMax<=1, break\"<<std::endl;\n\t\t\t\tbreak; //error is tolerable\n                        }\n\t\t\t//need to decrease step size\n\t\t\tif(errMax < shrinkLimit) {\n                                //std::cout<<\"errMax (\"<<errMax<<\")<shrinkLimit (\"<<shrinkLimit<<\"), h = \"<<h;\n\t\t\t\th=SAFETY*h/sqrt(sqrt(errMax)); // 1/sqrt(sqrt(errMax)) == errMax**shrinkPower\n                                //std::cout<<\" to \"<<h<<std::endl;\n                        }\n\t\t\telse {\n                                //std::cout<<\"errMax (\"<<errMax<<\")>=shrinkLimit (\"<<shrinkLimit<<\"), h = \"<<h;\n\t\t\t\th*=0.1;\n                                //std::cout<<\" to \"<<h<<std::endl;\n                        }\n\n                        // test errMax !!\n                        if( errMax != errMax ) { // error... nan errMax\n                            //std::cout<<\"errMax weird!\"<<std::endl;\n                            break;\n                        }\n\n\t\t\t//std::cout << \"\\tError too big, reducing step size to \" << h << std::endl;\n\t\t\tif((length+h)==length)\n\t\t\t\tthrow std::runtime_error(\"TraceFinder::rkStepControl: stepsize underflow\");\n\n\t\t}\n\t\t//increase step size\n\t\tif(errMax > growLimit){\n\t\t\t//Here, we use a taylor expansion (about 1) for errMax**growthPower. This \n\t\t\t//expansion always underestimates the true function (in the domain [0,1])\n\t\t\t//so it will give conservative advice for the next step's size\n\t\t\terrMax-=1.0;\n\t\t\thnext = SAFETY*h* (1.+errMax*(-.2+errMax*(.12+errMax*(-.088+errMax*.0704))));\n\t\t}\n\t\telse\n\t\t\thnext = 5.0*h;\n\t\t//std::cout << \"\\tError acceptable, plan next step size to be \" << hnext << std::endl;\n\t\tlength+=(hdid=h);\n\t\tconfirmFinalStepPosition(pos,temp,hdid);//pos=temp;\n\t}\n\t\n\tdouble fresnelReflect(double theta, double& polarization, double n1, double n2){\n\t\tdouble s=sin(theta);\n\t\tif(n1*s > n2){ //total internal reflection!\n\t\t\t//std::cout << \"Total internal refraction\" << std::endl;\n\t\t\treturn(1.0);\n\t\t}\n\t\tdouble c=cos(theta);\n\t\tdouble d=sqrt(n2*n2 - n1*n1*s*s);\n\t\tdouble rPerpedicular=(n1*c-d)/(n1*c+d);\n\t\tdouble rParallel=(n2*n2*c-n1*d)/(n2*n2*c+n1*d);\n\t\tdouble cp=cos(polarization);\n\t\tdouble sp=sin(polarization);\n\t\tdouble R=sqrt(rPerpedicular*rPerpedicular*cp*cp + rParallel*rParallel*sp*sp);\n\t\tpolarization=atan((rParallel*sp)/(rPerpedicular*cp));\n\t\treturn(R);\n\t}\n\t\n\tdouble fresnelTransmit(double theta, double& polarization, double n1, double n2){\n\t\tdouble s=sin(theta);\n\t\tif(n1*s > n2){ //total internal reflection!\n\t\t\t//std::cout << \"Total internal refraction\" << std::endl;\n\t\t\treturn(0.0);\n\t\t}\n\t\tdouble c=cos(theta);\n\t\tdouble d=sqrt(n2*n2 - n1*n1*s*s);\n\t\tdouble tPerpedicular=(2.*n1*c)/(n1*c+d);\n\t\tdouble tParallel=(2*n1*n2*c)/(n2*n2*c+n1*d);\n\t\tdouble cp=cos(polarization);\n\t\tdouble sp=sin(polarization);\n\t\tdouble T=sqrt(tPerpedicular*tPerpedicular*cp*cp + tParallel*tParallel*sp*sp);\n\t\tpolarization=atan((tParallel*sp)/(tPerpedicular*cp));\n\t\treturn(T);\n\t}\n\t\n\ttemplate <>\n\tvoid correctAmplitudeReflect<fullRayPosition>(fullRayPosition& pos, double polarization, double n1, double n2){\n\t\tpos.attenuation*=fresnelReflect(pos.theta, polarization, n1, n2);\n\t}\n\t\n\ttemplate <>\n\tvoid correctAmplitudeTransmit<fullRayPosition>(fullRayPosition& pos, double polarization, double n1, double n2){\n\t\tpos.attenuation*=fresnelTransmit(pos.theta, polarization, n1, n2);\n\t}\n\t\n\ttemplate <>\n\tvoid correctAmplitudeReflect<positionRecordingWrapper<fullRayPosition> >(positionRecordingWrapper<fullRayPosition>& pos, double polarization, double n1, double n2){\n\t\tpos.attenuation*=fresnelReflect(pos.theta, polarization, n1, n2);\n\t}\n\t\n\ttemplate <>\n\tvoid correctAmplitudeTransmit<positionRecordingWrapper<fullRayPosition> >(positionRecordingWrapper<fullRayPosition>& pos, double polarization, double n1, double n2){\n\t\tpos.attenuation*=fresnelTransmit(pos.theta, polarization, n1, n2);\n\t}\n\t\n\tdouble TraceFinder::recalculateAmplitude(const traceReplayRecord& trace, double frequency, double polarization){\n\t\tdouble attenuation=1.0, attenuationDerivative,nextAttenuation;\n\t\t//std::cout << \" att: \" << attenuation << std::endl;\n\t\tfor(std::vector<stepRecord>::const_iterator step=trace.steps.begin(), end=trace.steps.end(); step!=end; ++step){\n\t\t\tswitch(step->stepType){\n\t\t\t\tcase RK_FIRST_STEP:\n\t\t\t\t\t//do nothing; should never occur\n\t\t\t\t\tbreak;\n\t\t\t\tcase RK_AIR_STEP:\n\t\t\t\t\t//TODO: implement this!\n\t\t\t\t\tattenuation*=fresnelTransmit(step->angle, polarization, 1.0, rModel->indexOfRefraction(0.0));\n\t\t\t\t\tbreak;\n\t\t\t\tcase RK_STEP:\n\t\t\t\t\tattenuationDerivative=-attenuation/aModel->attenuationLength(step->rkData.z[0],frequency);\n\t\t\t\t\t//std::cout << \"  eval with z=\" << step->rkData.z[0] << \" att=\" << attenuation << \" yields \" << attenuationDerivative << std::endl;\n\t\t\t\t\treplayRkStep(step->rkData, attenuation, attenuationDerivative, nextAttenuation, frequency);\n\t\t\t\t\tattenuation=nextAttenuation;\n\t\t\t\t\tbreak;\n\t\t\t\tcase RK_REFLECT_STEP:\n\t\t\t\t\tif(step->angle<(pi/2.)){ //ray was reflected down from the ice surface\n\t\t\t\t\t\t//use the angle _after_ reflection\n\t\t\t\t\t\tattenuation*=fresnelReflect(step->angle, polarization, rModel->indexOfRefraction(maximum_ice_depth),1.0);\n\t\t\t\t\t}\n\t\t\t\t\telse{ //ray was reflected up from bedrock\n\t\t\t\t\t\t//use the angle _before_ reflection\n\t\t\t\t\t\tattenuation*=fresnelReflect(pi-step->angle, polarization, rModel->indexOfRefraction(0.0),1.0);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\t//std::cout << \" att: \" << attenuation << std::endl;\n\t\t}\n\t\treturn(attenuation);\n\t}\n\n\tstd::pair<bool, double> TraceFinder::traceMax(double emit_depth, const rayTargetRecord& target, int &sol_error, double left, double right ) const{\n\n            // test sol_error\n            //int sol_error;\n\n\t\t//std::cout << \"traceMax within domain [\" << left << ',' << right << ']' << std::endl;\n\t\t//unsigned int steps=1;\n\t\tstd::pair<bool,double> result;\n\t\tdouble a=left; //the left boundary of the search interval\n\t\tdouble b=right; //the right boundary of the search interval\n\t\tconst double w=(3.0-sqrt(5.0))/2.0;\n\t\tdouble c=a+w*(b-a); //the best estimate point\n\t\t//frequency and polarization are unimportant\n\t\t//double cy=doTrace<minimalRayPosition>(emit_depth,c,target,SurfaceReflection,0.0,0.0).miss;\n\t\tdouble cy=doTrace<minimalRayPosition>(emit_depth,c,target,SurfaceReflection,0.0,0.0, sol_error).miss;\n\t\t//std::cout << \"f(\" << c << \")=\" << cy << std::endl;\n\t\tdouble d,dy;\n\t\tconst double tol=1e-3;\n\t\twhile(cy<0.0 && fabs(b-a)>tol*c){\n\t\t\t//std::cout << \"\\tsearch domain is now [\" << a << ',' << b << ']' << std::endl;\n\t\t\tif((c-a)>=(b-c)){ //the left subinterval is larger, so search within it\n\t\t\t\td=c-w*(c-a);\n\t\t\t\tdy=doTrace<minimalRayPosition>(emit_depth,d,target,SurfaceReflection,0.0,0.0, sol_error ).miss; //evaluate the miss distance\n\t\t\t\t//std::cout << \"\\t \" << d << ' ' << dy << std::endl;\n\t\t\t\tif(dy>cy){\n\t\t\t\t\tb=c;\n\t\t\t\t\tc=d;\n\t\t\t\t\tcy=dy;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\ta=d;\n\t\t\t}\n\t\t\telse{ //otherwise seach within the right subinterval\n\t\t\t\td=c+w*(b-c);\n\t\t\t\tdy=doTrace<minimalRayPosition>(emit_depth,d,target,SurfaceReflection,0.0,0.0, sol_error ).miss; //evaluate the miss distance\n\t\t\t\t//std::cout << \"\\t \" << d << ' ' << dy << std::endl;\n\t\t\t\tif(dy>cy){\n\t\t\t\t\ta=c;\n\t\t\t\t\tc=d;\n\t\t\t\t\tcy=dy;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tb=d;\n\t\t\t}\n\t\t\t//steps++;\n\t\t}\n\t\t//std::cout << \"traceMax stopped at c=\" << c << \" f(c)=\" << cy << std::endl;\n\t\tresult.first = cy>0.0; //whether the best point indicates the existance of roots\n\t\tresult.second=c;\n\t\t//std::cout << \"traceMax took \" << steps << \" steps\" << std::endl;\n\t\treturn(result);\n\t}\n\n\tstd::pair<bool, double> TraceFinder::traceMin(double emit_depth, const rayTargetRecord& target, int &sol_error, double left, double right ) const{\n\n            // test sol_error\n            //int sol_error;\n\n\t\t//std::cout << \"traceMin within domain [\" << left << ',' << right << ']' << std::endl;\n\t\t//unsigned int steps=1;\n\t\tstd::pair<bool,double> result;\n\t\tdouble a=left; //the left boundary of the search interval\n\t\tdouble b=right; //the right boundary of the search interval\n\t\tconst double w=(3.0-sqrt(5.0))/2.0;\n\t\tdouble c=a+w*(b-a); //the best estimate point\n\t\t//frequency and polarization are unimportant\n\t\tdouble cy=doTrace<minimalRayPosition>(emit_depth,c,target,BedrockReflection,0.0,0.0, sol_error ).miss;\n\t\t//std::cout << \"f(\" << c << \")=\" << cy << std::endl;\n\t\tdouble d,dy;\n\t\tconst double tol=1e-3;\n\t\twhile(cy>0.0 && fabs(b-a)>tol*c){\n\t\t\t//std::cout << \"\\tsearch domain is now [\" << a << ',' << b << ']' << std::endl;\n\t\t\tif((c-a)>=(b-c)){ //the left subinterval is larger, so search within it\n\t\t\t\t//std::cout << \"\\t left sub-interval\\n\";\n\t\t\t\td=c-w*(c-a);\n\t\t\t\tdy=doTrace<minimalRayPosition>(emit_depth,d,target,BedrockReflection,0.0,0.0, sol_error ).miss; //evaluate the miss distance\n\t\t\t\t//std::cout << \"\\t \" << d << ' ' << dy << std::endl;\n\t\t\t\tif(dy<cy){\n\t\t\t\t\tb=c;\n\t\t\t\t\tc=d;\n\t\t\t\t\tcy=dy;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\ta=d;\n\t\t\t}\n\t\t\telse{ //otherwise seach within the right subinterval\n\t\t\t\t//std::cout << \"\\t right sub-interval\\n\";\n\t\t\t\td=c+w*(b-c);\n\t\t\t\tdy=doTrace<minimalRayPosition>(emit_depth,d,target,BedrockReflection,0.0,0.0, sol_error ).miss; //evaluate the miss distance\n\t\t\t\t//std::cout << \"\\t \" << d << ' ' << dy << std::endl;\n\t\t\t\tif(dy<cy){\n\t\t\t\t\ta=c;\n\t\t\t\t\tc=d;\n\t\t\t\t\tcy=dy;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tb=d;\n\t\t\t}\n\t\t\t//steps++;\n\t\t}\n\t\t//std::cout << \"traceMin stopped at c=\" << c << \" f(c)=\" << cy << std::endl;\n\t\tresult.first = cy<0.0; //whether the best point indicates the existance of roots\n\t\tresult.second=c;\n\t\t//std::cout << \"traceMin took \" << steps << \" steps\" << std::endl;\n\t\treturn(result);\n\t}\n\n\tstd::pair<double,double> TraceFinder::traceRootImpl(double emit_depth, const rayTargetRecord& target, bool rising, unsigned short allowedReflections, double requiredAccuracy, \n\t\t\t\t\t\t\t\t\t  double a, TraceRecord& aTrace, double c, TraceRecord& cTrace, double angle, int &sol_error ) const{\n\n            // test sol_error\n            //int sol_error;\n\n\t\tconst double miss_eps=requiredAccuracy/100.0;\n\t\tconst double angle_eps=1e-10;\n\t\tdouble lastMiss;\n\t\tTraceRecord trace;\n\t\t\n\t\tdouble e=0.0,ep=0.0,p,q,r,s,t;\n\t\t\n\t\t//initialize these so that the miss change check won't fail accidentally\n\t\ttrace.miss=1.0e3*miss_eps;\n\t\tlastMiss=-1.0e3*miss_eps;\n\t\t\n\t\twhile((c-a)>angle_eps && fabs(trace.miss-lastMiss)>miss_eps){\n                    // changed\n\t\t\t//std::cout << \"\\tAngular range=\" << (c-a) << \", miss change=\" << fabs(trace.miss-lastMiss) << std::endl;\n\t\t\tlastMiss=trace.miss;\n\t\t\t//std::cout << \" Angular range is now [\" << a << ',' << c << \"]\\n\";\n\t\t\t//std::cout << \" Trying angle=\" << angle << std::endl;\n\t\t\ttrace=doTrace<minimalRayPosition>(emit_depth,angle,target,allowedReflections,0.0,0.0, sol_error );\n\t\t\t//steps++;\n\t\t\t//std::cout << \"  miss distance was \" << trace.miss << '\\n';\n\t\t\tif(std::abs(trace.miss) < requiredAccuracy){\n\t\t\t\t//std::cout << \"traceRoot took \" << steps << \" steps\" << std::endl;\n\t\t\t\t//doTrace<fullRayPosition>(emit_depth,angle,target,allowedReflections,frequency,polarization)\n\t\t\t\treturn(std::make_pair(angle,trace.miss));\n\t\t\t}\n\t\t\t\n\t\t\t//calculate the quadratic interpolation\n\t\t\tr=trace.miss/cTrace.miss;\n\t\t\ts=trace.miss/aTrace.miss;\n\t\t\tt=aTrace.miss/cTrace.miss;\n\t\t\tp=s*(t*(r-t)*(c-angle)+(r-1)*(angle-a));\n\t\t\tq=(r-1)*(s-1)*(t-1);\n\t\t\t\n\t\t\t//collapse the interval\n\t\t\tif((trace.miss>0.0) != rising){\n\t\t\t\ta=angle;\n\t\t\t\taTrace=trace;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tc=angle;\n\t\t\t\tcTrace=trace;\n\t\t\t}\n\t\t\t\n\t\t\t//accept the interpolation only if it falls within the current boundaries\n\t\t\tif((angle+(p/q))>=a && (angle+(p/q))<=c){\n\t\t\t\t//would like to interpolate, but only do so if recent convergence has been suitably rapid\n\t\t\t\tif(std::abs(p/q) >= 0.5*std::abs(e)){ //it has not; bisect instead\n\t\t\t\t\t//std::cout << \" will bisect\" << std::endl;\n\t\t\t\t\te=ep;\n\t\t\t\t\tep=0.5*(a+c)-angle;\n\t\t\t\t\tangle=0.5*(a+c);\n\t\t\t\t}\n\t\t\t\telse{ //it has; use the interpolation\n\t\t\t\t\t//std::cout << \" will interpolate\" << std::endl;\n\t\t\t\t\tangle+=p/q;\n\t\t\t\t\te=ep;\n\t\t\t\t\tep=p/q;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{ //otherwise, bisect\n\t\t\t\t//std::cout << \" will bisect\" << std::endl;\n\t\t\t\te=ep;\n\t\t\t\tep=0.5*(a+c)-angle;\n\t\t\t\tangle=0.5*(a+c);\n\t\t\t}\n\t\t}\n\t\t//std::cout << \"traceRoot took \" << steps << \" steps and bailed out\" << std::endl;\n\t\treturn(std::make_pair(angle,trace.miss));\n\t}\n\t\n\t//rough implementation of Brent's method\n\t//This implementation neglects some of the checks made by Brent to ensure \n\t//rapidity of convergence, and does not bother to use secant interpolation. \n\t//In practice it seems not to matter, as it is still capable of the same \n\t//best-case behavior as the full Brent's method. \n\t//This implementation is more conveniently controllable for this purpose \n\t//than NR's zbrent, with regard to the stopping conditions\n\tstd::pair<double,double> TraceFinder::traceRoot(double emit_depth, const rayTargetRecord& target, double minAngle, double maxAngle, bool rising, unsigned short allowedReflections, double requiredAccuracy, int &sol_error ) const{\n\n            // test sol_error\n            //int sol_error;\n\n\n\t\tdouble a=minAngle,c=maxAngle;\n\t\tTraceRecord aTrace, cTrace;\n\t\t//frequency and polarization are irrelevant on all traces except the final one\n\t\taTrace = doTrace<minimalRayPosition>(emit_depth,a,target,allowedReflections,0.0,0.0, sol_error );\n\t\tcTrace = doTrace<minimalRayPosition>(emit_depth,c,target,allowedReflections,0.0,0.0, sol_error );\n\t\tdouble angle=0.5*(minAngle+maxAngle);\n\t\t//std::cout << \"Attempting to find root in range [\" << minAngle << ',' << maxAngle << ']' << std::endl;\n\t\t//std::cout << \" end point miss values are \" << aTrace.miss << ',' << cTrace.miss << std::endl;\n\t\tif((aTrace.miss>0) == (cTrace.miss>0)) //didn't bracket a root. Return a nonsense angle and a huge error\n\t\t\treturn(std::make_pair(-1.,1e6));\n\t\treturn(traceRootImpl(emit_depth, target, rising, allowedReflections, requiredAccuracy, a, aTrace, c, cTrace, angle, sol_error ));\n\t}\n\t\n        /*\n\tstd::pair<double,double> TraceFinder::refineRoot(double emit_depth, const rayTargetRecord& target, const TraceRecord& seed, bool rising, unsigned short allowedReflections, double requiredAccuracy, int &sol_error ) const{\n\n            // test sol_error\n            //int sol_error;\n\n\n\t\t//bracket the root\n\t\t//std::cout << \"Attempting to refine root near theta=\" << seed.launchAngle << std::endl;\n\t\tdouble a, c;\n\t\tTraceRecord aTrace, cTrace;\n\t\tdouble testDisp=.001; //TODO: this is a problem since there could be a second root arbitrarily close to the one we seek\n\t\t//If we start with testDisp larger than the distance betwee these roots we can bracket them both and incorrectly conclude that we've bracketed nothing\n\t\tconst unsigned int maxTests=(unsigned int)std::ceil(0.5*(sqrt(1.0+(8*pi/testDisp))-1.0));\n\t\tif((seed.miss>0.0)==rising)\n\t\t\ttestDisp*=-1;\n\t\tunsigned int i;\n\t\ta=seed.launchAngle;\n\t\tfor(i=0; i<maxTests; i++){\n\t\t\ta+=testDisp;\n\t\t\ttestDisp*=2.0;\n\t\t\tif(a<0.0)\n\t\t\t\ta=0.0;\n\t\t\telse if(a>pi)\n\t\t\t\ta=pi;\n\t\t\t//std::cout << \"\\ttesting theta=\" << a << std::endl;\n\t\t\taTrace=doTrace<minimalRayPosition>(emit_depth,a,target,allowedReflections,0.0,0.0, sol_error );\n                        // changed\n\t\t\tstd::cout << \"\\t (miss=\" << aTrace.miss << \")\" << std::endl;\n\t\t\tif(std::abs(aTrace.miss) < requiredAccuracy) {\n                                // changed\n                                std::cout << \"miss<requiredAccuracy\" << std::endl;\n\t\t\t\treturn(std::make_pair(a,aTrace.miss));\n                        }\n\t\t\t\t//return(doTrace<fullRayPosition>(emit_depth,a,target,allowedReflections,0.0,0.0));\n\t\t\tif((aTrace.miss*seed.miss)<0.0) {\n                                // changed\n                                std::cout << \"trace.miss * seed.miss < 0, break\" << std::endl;\n\t\t\t\tbreak;\n                        }\n\t\t}\n\t\tif(i==maxTests){\n                        // changed\n                        std::cout << \"refineRoot, reached maxTests\" << std::endl;\n\n\t\t\t//std::cerr << \"Last attempt at bracketing was: [\" << seed.launchAngle << \"->\" << seed.miss << ',' << a << \"->\" << aTrace.miss << ']' << std::endl;\n\t\t\t//std::cerr << \"\\trising edge = \" << std::boolalpha << rising << std::endl;\n\t\t\tthrow std::runtime_error(\"TraceFinder::refineRoot: exceeded maximum allowed number of steps for bracketing.\");\n\t\t}\n\t\tif((seed.miss>0.0)==rising){\n\t\t\tc=seed.launchAngle;\n\t\t\tcTrace=seed;\n\t\t}\n\t\telse{\n\t\t\tc=a;\n\t\t\tcTrace=aTrace;\n\t\t\ta=seed.launchAngle;\n\t\t\taTrace=seed;\n\t\t}\n\t\t\n\t\t//std::cout << \"Endpoint miss distances are \" << aTrace.miss << \" and \" << cTrace.miss << std::endl;\n\t\tdouble angle=0.5*(a+c);\n\t\treturn(traceRootImpl(emit_depth, target, rising, allowedReflections, requiredAccuracy, a, aTrace, c, cTrace, angle, sol_error ));\n\t}\n        */\n\n\n\n        /*\n        // changed\n        // test obtaining min value case\n\tstd::pair<double,double> TraceFinder::refineRoot(double emit_depth, const rayTargetRecord& target, const TraceRecord& seed, bool rising, unsigned short allowedReflections, double requiredAccuracy, int &sol_error ) const{\n\n            // test sol_error\n            //int sol_error;\n\n            double min_angle, min_angle_plus, min_angle_minus;\n            double min_miss = 1e10; // start with big value\n\n\n\t\t//bracket the root\n\t\t//std::cout << \"Attempting to refine root near theta=\" << seed.launchAngle << std::endl;\n\t\tdouble a, c;\n\t\tTraceRecord aTrace, cTrace;\n\t\tdouble testDisp=.001; //TODO: this is a problem since there could be a second root arbitrarily close to the one we seek\n\t\t//If we start with testDisp larger than the distance betwee these roots we can bracket them both and incorrectly conclude that we've bracketed nothing\n\t\tconst unsigned int maxTests=(unsigned int)std::ceil(0.5*(sqrt(1.0+(8*pi/testDisp))-1.0));\n\t\tif((seed.miss>0.0)==rising)\n\t\t\ttestDisp*=-1;\n\t\tunsigned int i;\n\t\ta=seed.launchAngle;\n\t\tfor(i=0; i<maxTests; i++){\n\t\t\ta+=testDisp;\n\t\t\ttestDisp*=2.0;\n\t\t\tif(a<0.0)\n\t\t\t\ta=0.0;\n\t\t\telse if(a>pi)\n\t\t\t\ta=pi;\n\t\t\t//std::cout << \"\\ttesting theta=\" << a << std::endl;\n\t\t\taTrace=doTrace<minimalRayPosition>(emit_depth,a,target,allowedReflections,0.0,0.0, sol_error );\n\n                        if ( min_miss > std::abs(aTrace.miss) ) {\n                            min_miss = std::abs(aTrace.miss);\n                            min_angle = a;\n\t\t\n                            if((seed.miss>0.0)==rising) {\n                                min_angle_plus = a - testDisp;\n                                min_angle_minus = a + testDisp;\n                            }\n                            else {\n                                min_angle_plus = a + testDisp;\n                                min_angle_minus = a - testDisp;\n                            }\n                        }\n\n                        // changed\n\t\t\tstd::cout << \"\\t (miss=\" << aTrace.miss << \") at angle: \"<<a<< std::endl;\n\t\t\tif(std::abs(aTrace.miss) < requiredAccuracy) {\n                                // changed\n                                std::cout << \"miss<requiredAccuracy\" << std::endl;\n\t\t\t\treturn(std::make_pair(a,aTrace.miss));\n                        }\n\t\t\t\t//return(doTrace<fullRayPosition>(emit_depth,a,target,allowedReflections,0.0,0.0));\n\t\t\tif((aTrace.miss*seed.miss)<0.0) {\n                                // changed\n                                std::cout << \"trace.miss * seed.miss < 0, break\" << std::endl;\n\t\t\t\tbreak;\n                        }\n\t\t}\n\t\tif(i==maxTests){\n                        // changed\n                        std::cout << \"refineRoot, reached maxTests\" << std::endl;\n\n\t\t\t//std::cerr << \"Last attempt at bracketing was: [\" << seed.launchAngle << \"->\" << seed.miss << ',' << a << \"->\" << aTrace.miss << ']' << std::endl;\n\t\t\t//std::cerr << \"\\trising edge = \" << std::boolalpha << rising << std::endl;\n\t\t\tthrow std::runtime_error(\"TraceFinder::refineRoot: exceeded maximum allowed number of steps for bracketing.\");\n\t\t}\n\t\tif((seed.miss>0.0)==rising){\n\t\t\tc=seed.launchAngle;\n\t\t\tcTrace=seed;\n\t\t}\n\t\telse{\n\t\t\tc=a;\n\t\t\tcTrace=aTrace;\n\t\t\ta=seed.launchAngle;\n\t\t\taTrace=seed;\n\t\t}\n\t\t\n                // changed\n                std::cout<<\"min miss : \"<<min_miss<<\" at angle : \"<<min_angle<<\", test w/ min angle : \"<<min_angle_minus<<\" max angle : \"<<min_angle_plus<<std::endl;\n\n\t\t//std::cout << \"Endpoint miss distances are \" << aTrace.miss << \" and \" << cTrace.miss << std::endl;\n\t\tdouble angle=0.5*(a+c);\n                // changed\n\t\t//return(traceRootImpl(emit_depth, target, rising, allowedReflections, requiredAccuracy, a, aTrace, c, cTrace, angle, sol_error ));\n\t\treturn(evenmore_refineRoot(emit_depth, target, seed, min_angle_minus, min_angle_plus, rising, allowedReflections, requiredAccuracy, sol_error ));\n\t}\n        */\n\n        // changed\n        // test obtaining min value case more carefully\n\tstd::pair<double,double> TraceFinder::evenmore_refineRoot(double emit_depth, const rayTargetRecord& target, const TraceRecord& seed, double angle_min, double angle_max, bool rising, unsigned short allowedReflections, double requiredAccuracy, int &sol_error ) const{\n\n            // test sol_error\n            //int sol_error;\n\n            double min_angle;\n            double min_miss = 1e10; // start with big value\n\n\n\t\t//bracket the root\n\t\t//std::cout << \"Attempting to refine root near theta=\" << seed.launchAngle << std::endl;\n\t\tdouble a, c;\n\t\tTraceRecord aTrace, cTrace;\n\t\t//double testDisp=.001; //TODO: this is a problem since there could be a second root arbitrarily close to the one we seek\n\t\tdouble testDisp=.00001; //TODO: this is a problem since there could be a second root arbitrarily close to the one we seek\n\t\t//If we start with testDisp larger than the distance betwee these roots we can bracket them both and incorrectly conclude that we've bracketed nothing\n\t\t//const unsigned int maxTests=(unsigned int)std::ceil(0.5*(sqrt(1.0+(8*pi/testDisp))-1.0));\n\t\tconst unsigned int maxTests=(unsigned int)((angle_max - angle_min)/testDisp);\n\n\t\t//if((seed.miss>0.0)==rising)\n\t\t\t//testDisp*=-1;\n\t\tunsigned int i;\n\t\t//a=seed.launchAngle;\n\t\ta=angle_min;\n\t\tfor(i=0; i<maxTests; i++){\n\t\t\ta+=testDisp;\n\t\t\ttestDisp*=2.0;\n\t\t\tif(a<0.0)\n\t\t\t\ta=0.0;\n\t\t\telse if(a>pi)\n\t\t\t\ta=pi;\n\t\t\t//std::cout << \"\\ttesting theta=\" << a << std::endl;\n\t\t\taTrace=doTrace<minimalRayPosition>(emit_depth,a,target,allowedReflections,0.0,0.0, sol_error );\n\n                        if ( min_miss > std::abs(aTrace.miss) ) {\n                            min_miss = std::abs(aTrace.miss);\n                            min_angle = a;\n                        }\n\n                        // changed\n\t\t\t//std::cout << \"\\t second (miss=\" << aTrace.miss << \") at angle: \"<<a<< std::endl;\n\t\t\tif(std::abs(aTrace.miss) < requiredAccuracy) {\n                                // changed\n                                //std::cout << \"miss<requiredAccuracy\" << std::endl;\n\t\t\t\treturn(std::make_pair(a,aTrace.miss));\n                        }\n\t\t\t\t//return(doTrace<fullRayPosition>(emit_depth,a,target,allowedReflections,0.0,0.0));\n\t\t\tif((aTrace.miss*seed.miss)<0.0) {\n                                // changed\n                                //std::cout << \"second trace.miss * seed.miss < 0, break\" << std::endl;\n\t\t\t\tbreak;\n                        }\n\t\t}\n\n\n\n\n\n\t\tif(i==maxTests){\n                        // changed\n                        //std::cout << \"refineRoot, reached maxTests\" << std::endl;\n\n\t\t\t//std::cerr << \"Last attempt at bracketing was: [\" << seed.launchAngle << \"->\" << seed.miss << ',' << a << \"->\" << aTrace.miss << ']' << std::endl;\n\t\t\t//std::cerr << \"\\trising edge = \" << std::boolalpha << rising << std::endl;\n\t\t\tthrow std::runtime_error(\"TraceFinder::refineRoot: exceeded maximum allowed number of steps for bracketing.\");\n\t\t}\n\t\tif((seed.miss>0.0)==rising){\n\t\t\tc=seed.launchAngle;\n\t\t\tcTrace=seed;\n\t\t}\n\t\telse{\n\t\t\tc=a;\n\t\t\tcTrace=aTrace;\n\t\t\ta=seed.launchAngle;\n\t\t\taTrace=seed;\n\t\t}\n\t\t\n                // changed\n                //std::cout<<\"min miss : \"<<min_miss<<\" at angle : \"<<min_angle<<std::endl;\n\n\t\t//std::cout << \"Endpoint miss distances are \" << aTrace.miss << \" and \" << cTrace.miss << std::endl;\n\t\tdouble angle=0.5*(a+c);\n                // changed\n\t\treturn(traceRootImpl(emit_depth, target, rising, allowedReflections, requiredAccuracy, a, aTrace, c, cTrace, angle, sol_error ));\n\t}\n\n\n        // changed\n        // test obtaining min value case\n        // loosen required accuracy and see if they pass\n\tstd::pair<double,double> TraceFinder::refineRoot(double emit_depth, const rayTargetRecord& target, const TraceRecord& seed, bool rising, unsigned short allowedReflections, double requiredAccuracy, int &sol_error ) const{\n\n            // test sol_error\n            //int sol_error;\n\n            double min_angle, min_angle_plus, min_angle_minus;\n            double min_miss = 1e10; // start with big value\n\n\n\t\t//bracket the root\n\t\t//std::cout << \"Attempting to refine root near theta=\" << seed.launchAngle << std::endl;\n\t\tdouble a, c;\n\t\tTraceRecord aTrace, cTrace, minmissTrace;\n\t\tdouble testDisp=.001; //TODO: this is a problem since there could be a second root arbitrarily close to the one we seek\n\t\t//If we start with testDisp larger than the distance betwee these roots we can bracket them both and incorrectly conclude that we've bracketed nothing\n\t\tconst unsigned int maxTests=(unsigned int)std::ceil(0.5*(sqrt(1.0+(8*pi/testDisp))-1.0));\n\t\tif((seed.miss>0.0)==rising)\n\t\t\ttestDisp*=-1;\n\t\tunsigned int i;\n\t\ta=seed.launchAngle;\n\t\tfor(i=0; i<maxTests; i++){\n\t\t\ta+=testDisp;\n\t\t\ttestDisp*=2.0;\n\t\t\tif(a<0.0)\n\t\t\t\ta=0.0;\n\t\t\telse if(a>pi)\n\t\t\t\ta=pi;\n\t\t\t//std::cout << \"\\ttesting theta=\" << a << std::endl;\n\t\t\taTrace=doTrace<minimalRayPosition>(emit_depth,a,target,allowedReflections,0.0,0.0, sol_error );\n\n                        if ( min_miss > std::abs(aTrace.miss) ) {\n                            min_miss = std::abs(aTrace.miss);\n                            min_angle = a;\n                            minmissTrace = aTrace;\n\t\t\n                            if((seed.miss>0.0)==rising) {\n                                min_angle_plus = a - testDisp;\n                                min_angle_minus = a + testDisp;\n                            }\n                            else {\n                                min_angle_plus = a + testDisp;\n                                min_angle_minus = a - testDisp;\n                            }\n                        }\n\n                        // changed\n\t\t\t//std::cout << \"\\t (miss=\" << aTrace.miss << \") at angle: \"<<a<< std::endl;\n\t\t\tif(std::abs(aTrace.miss) < requiredAccuracy) {\n                                // changed\n                                //std::cout << \"miss<requiredAccuracy\" << std::endl;\n\t\t\t\treturn(std::make_pair(a,aTrace.miss));\n                        }\n\t\t\t\t//return(doTrace<fullRayPosition>(emit_depth,a,target,allowedReflections,0.0,0.0));\n\t\t\tif((aTrace.miss*seed.miss)<0.0) {\n                                // changed\n                                //std::cout << \"trace.miss * seed.miss < 0, break\" << std::endl;\n\t\t\t\tbreak;\n                        }\n\t\t}\n\t\tif(i==maxTests){\n                        // changed\n                        //std::cout << \"refineRoot, reached maxTests\" << std::endl;\n\n\t\t\t//std::cerr << \"Last attempt at bracketing was: [\" << seed.launchAngle << \"->\" << seed.miss << ',' << a << \"->\" << aTrace.miss << ']' << std::endl;\n\t\t\t//std::cerr << \"\\trising edge = \" << std::boolalpha << rising << std::endl;\n\t\t\tthrow std::runtime_error(\"TraceFinder::refineRoot: exceeded maximum allowed number of steps for bracketing.\");\n\t\t}\n\t\tif((seed.miss>0.0)==rising){\n\t\t\tc=seed.launchAngle;\n\t\t\tcTrace=seed;\n\t\t}\n\t\telse{\n\t\t\tc=a;\n\t\t\tcTrace=aTrace;\n\t\t\ta=seed.launchAngle;\n\t\t\taTrace=seed;\n\t\t}\n\t\t\n                // changed\n                //std::cout<<\"min miss : \"<<min_miss<<\" at angle : \"<<min_angle<<\", test w/ min angle : \"<<min_angle_minus<<\" max angle : \"<<min_angle_plus<<std::endl;\n\n\n                /*\n                // changed\n                // test loosen required accuray \n                double loosen_cut = 5.; // const value for now\n                if ( min_miss < loosen_cut ) {\n\n                    std::cout<<\"min miss : \"<<min_miss<<\" at angle : \"<<min_angle<<\", passed loosen cut \"<<loosen_cut<<std::endl;\n                    return(std::make_pair(min_angle,min_miss));\n                }\n                */\n\n\n\n\t\t//std::cout << \"Endpoint miss distances are \" << aTrace.miss << \" and \" << cTrace.miss << std::endl;\n\t\tdouble angle=0.5*(a+c);\n                // changed\n\t\t//return(traceRootImpl(emit_depth, target, rising, allowedReflections, requiredAccuracy, a, aTrace, c, cTrace, angle, sol_error ));\n\t\treturn(evenmore_refineRoot(emit_depth, target, seed, min_angle_minus, min_angle_plus, rising, allowedReflections, requiredAccuracy, sol_error ));\n\t}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\tbool shorterPath(const TraceRecord& a, const TraceRecord& b){\n\t\treturn(a.pathLen < b.pathLen);\n\t}\n\t\n\t///A quick-and-dirty function to simultaneously sort two sequences according to the values in the first sequence. \n\t///That is, the first sequence is sorted in the normal way, and the second sequence undergoes the same permutation. \n\t///This is only expected to be used on very short sequences, so it uses the inefficient but simple insertion sort algorithm. \n\t///\n\t///\\param begin1 An iterator to the beginning of the first sequence\n\t///\\param end1 An iterator to the end of the first sequence\n\t///\\param begin2 An iterator to the beginning of the second sequence \n\t////\t\t(which must be the same length as the first sequence)\n\t///\\param comp The comparison function object used to determine the \n\t///\t\tproper ordering of the elements in the first sequence\n\ttemplate<typename RandomAccessIterator1, typename RandomAccessIterator2, class Compare>\n\tvoid dual_insertion_sort(RandomAccessIterator1 begin1, RandomAccessIterator1 end1, RandomAccessIterator2 begin2, Compare comp){\n\t\tRandomAccessIterator2 frontier2=begin2+1;\n\t\tfor(RandomAccessIterator1 frontier1=begin1+1; frontier1!=end1; ++frontier1,++frontier2){\n\t\t\tRandomAccessIterator1 it1=frontier1;\n\t\t\tRandomAccessIterator2 it2=frontier2;\n\t\t\twhile(it1!=begin1){\n\t\t\t\tRandomAccessIterator1 nit=it1-1;\n\t\t\t\tif(comp(*it1,*nit)){\n\t\t\t\t\tstd::iter_swap(it1,nit);\n\t\t\t\t\tstd::iter_swap(it2,it2-1);\n\t\t\t\t\tit1=nit;\n\t\t\t\t\t--it2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t//std::vector<TraceRecord> TraceFinder::findPaths(Vector sourcePos, Vector targetPos, double frequency, double polarization, unsigned short allowedReflections, double requiredAccuracy, std::vector<traceReplayRecord>* replayBuffer) const{\n\tstd::vector<TraceRecord> TraceFinder::findPaths(Vector sourcePos, Vector targetPos, double frequency, double polarization, int &sol_cnt, int &sol_error, unsigned short allowedReflections, double requiredAccuracy, std::vector<traceReplayRecord>* replayBuffer) const{\n\t//std::vector<TraceRecord> TraceFinder::findPaths(Vector sourcePos, Vector targetPos, double frequency, double polarization, int &sol_cnt, int &sol_error, int mode, unsigned short allowedReflections, double requiredAccuracy, std::vector<traceReplayRecord>* replayBuffer) const{\n\n                sol_cnt = 0;\n                sol_error = 0;\n                \n\n                // changed\n                //std::cout<<\"begin findPaths\"<<std::endl;\n                /*\n                std::cout<<\"findPaths mode : \"<<mode<<std::endl;\n                if (mode == 1) {    // mode 1 for src, trg exchanged\n                    Vector Pos_tmp;\n                    Pos_tmp = sourcePos;\n                    sourcePos = targetPos;\n                    targetPos = Pos_tmp;\n                }\n                */\n\n\n\n\n\t\tconst double initialSafety=1.e-2;\n\t\tconst double minimumSafety=1.e-5;\n\t\t\n\t\tstd::vector<TraceRecord> results;\n\t\tboost::scoped_ptr<pathRecorder<fullRayPosition> > recorder;\n\t\tif(replayBuffer!=NULL)\n\t\t\trecorder.reset(new pathRecorder<fullRayPosition>());\n\t\t//std::cout << \"Finding paths from (\" << sourcePos.GetX() << ',' << sourcePos.GetY() << ',' << sourcePos.GetZ() << \") to (\" << targetPos.GetX() << ',' << targetPos.GetY() << ',' << targetPos.GetZ() << ')' << std::endl;\n\t\tif(sourcePos.GetZ()<maximum_ice_depth || targetPos.GetZ()<maximum_ice_depth)\n                        {\n\t\t\treturn(results);\n                        }\n\t\tbool fullyContained=(sourcePos.GetZ()<=0.0 && targetPos.GetZ()<=0.0); //whether the ray is entirely inside the ice\n\t\tdouble dist = sqrt((targetPos.GetX()-sourcePos.GetX())*(targetPos.GetX()-sourcePos.GetX())+(targetPos.GetY()-sourcePos.GetY())*(targetPos.GetY()-sourcePos.GetY()));\n\t\trayTargetRecord target(targetPos.GetZ(),dist);\n\t\tbool dualDirect=false; //whether there are knwon to be two direct solution rays\n\t\t\n\t\t//special case for pesky near-vertical rays\n\t\tif(dist<=requiredAccuracy){\n\t\t\t\n                    // changed\n                    //std::cout << \"Computing direct ray (vertical)\" << std::endl;\n\n\t\t\tif(replayBuffer==NULL)\n                                {\n\t\t\t\tresults.push_back(doVerticalTrace<fullRayPosition>(sourcePos.GetZ(), (sourcePos.GetZ()<targetPos.GetZ()?0.0:pi), target, NoReflection, frequency, polarization));\n                                sol_cnt++;\n                                //std::cout<<\"\\n\\tSOL_CNT ADDED! 1\\n\"<<std::endl;\n                                }\n\t\t\telse{\n\t\t\t\tresults.push_back(doVerticalTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(), (sourcePos.GetZ()<targetPos.GetZ()?0.0:pi), target, NoReflection, frequency, polarization, recorder.get()));\n\t\t\t\treplayBuffer->push_back(recorder->getData());\n\t\t\t\trecorder->clearData();\n                                sol_cnt++;\n                                //std::cout<<\"\\n\\tSOL_CNT ADDED! 2\\n\"<<std::endl;\n\t\t\t}\n\t\t\tif((allowedReflections & SurfaceReflection) && fullyContained){\n\t\t\t\t//std::cout << \"Computing surface-reflected ray\" << std::endl;\n\t\t\t\tif(replayBuffer==NULL)\n                                        {\n\t\t\t\t\tresults.push_back(doVerticalTrace<fullRayPosition>(sourcePos.GetZ(), 0.0, target, SurfaceReflection, frequency, polarization));\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 3\\n\"<<std::endl;\n                                        }\n\t\t\t\telse{\n\t\t\t\t\tresults.push_back(doVerticalTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(), 0.0, target, SurfaceReflection, frequency, polarization, recorder.get()));\n\t\t\t\t\treplayBuffer->push_back(recorder->getData());\n\t\t\t\t\trecorder->clearData();\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 4\\n\"<<std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(allowedReflections & BedrockReflection){\n\t\t\t\t//std::cout << \"Computing bedrock-reflected ray\" << std::endl;\n\t\t\t\tif(replayBuffer==NULL)\n                                        {\n\t\t\t\t\tresults.push_back(doVerticalTrace<fullRayPosition>(sourcePos.GetZ(), pi, target, BedrockReflection, frequency, polarization));\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 5\\n\"<<std::endl;\n                                        }\n\t\t\t\telse{\n\t\t\t\t\tresults.push_back(doVerticalTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(), pi, target, BedrockReflection, frequency, polarization, recorder.get()));\n\t\t\t\t\treplayBuffer->push_back(recorder->getData());\n\t\t\t\t\trecorder->clearData();\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 6\\n\"<<std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstd::sort(results.begin(),results.end(),&shorterPath);\n\t\t\treturn(results);\n\t\t} // if special case for pesky near-vertical rays\n\t\t\n\n                // if either src or trg not in the ice\n\t\tif(!fullyContained){\n\t\t\t\n                    // changed\n                    //std::cout << \"Ray not fully contained\" << std::endl;\n\n\t\t\tif(replayBuffer==NULL)\n                                {\n\t\t\t\tresults.push_back(findUncontainedFast(sourcePos, targetPos, frequency, polarization, requiredAccuracy, sol_error ));\n                                sol_cnt++;\n                                //std::cout<<\"\\n\\tSOL_CNT ADDED! 7\\n\"<<std::endl;\n                                }\n\t\t\telse{\n\t\t\t\tresults.push_back(findUncontainedFast(sourcePos, targetPos, frequency, polarization, requiredAccuracy, sol_error, recorder.get()));\n\t\t\t\treplayBuffer->push_back(recorder->getData());\n                                sol_cnt++;\n                                //std::cout<<\"\\n\\tSOL_CNT ADDED! 8\\n\"<<std::endl;\n\t\t\t}\n\t\t\treturn(results);\n\t\t} // if either src or trg not in the ice\n\n\n                // changed \n                // both cout\n\t\t//std::cout << \"Looking for estimate\" << std::endl;\n\t\tindexOfRefractionModel::RayEstimate est=rModel->estimateRayAngle(sourcePos.GetZ(), targetPos.GetZ(), dist); //TODO: put this back!!!\n\t\t//std::cout << \"Estimate result : \" << est.status << \" refractionmodel solution : \"<< indexOfRefractionModel::SOLUTION << std::endl;\n\n\n\t\tif(est.status==indexOfRefractionModel::SOLUTION){ //got a solution estimate\n\t\t\t\n                    // changed\n                    //std::cout << \"Got fast solution, est.angle: \" << est.angle << std::endl;\n\n\t\t\t//std::cout << \"\\t(theta=\" << est.angle << ')' << std::endl;\n\t\t\tif(replayBuffer==NULL)\n                                {\n                                //std::cout << \"replayBuffer==NULL\" <<std::endl;\n\t\t\t\tresults.push_back(doTrace<fullRayPosition>(sourcePos.GetZ(), est.angle, target, NoReflection, frequency, polarization, sol_error )); //this is supposed to be a direct ray, so no reflections should be needed\n                                        \n                                // changed always (if)?\n                                //std::cout << \"done 1st doTrace (if)\\n\" << std::endl;\n                                //std::cout << \"results pathLen: \"<<results.front().pathLen<<\" miss: \"<<results.front().miss<<\"\\n\" << std::endl;\n                                sol_cnt++;\n                                //std::cout<<\"\\n\\tSOL_CNT ADDED! 9\\n\"<<std::endl;\n                                }\n\t\t\telse{\n                                //std::cout << \"replayBuffer!=NULL\" <<std::endl;\n\t\t\t\tresults.push_back(doTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(), est.angle, target, NoReflection, frequency, polarization, sol_error, recorder.get())); //this is supposed to be a direct ray, so no reflections should be needed\n\n                                // changed\n                                //std::cout << \"done 1st doTrace (else)\\n\" << std::endl;\n\t\t\t\treplayBuffer->push_back(recorder->getData());\n\t\t\t\trecorder->clearData();\n                                sol_cnt++;\n                                //std::cout<<\"\\n\\tSOL_CNT ADDED! 10\\n\"<<std::endl;\n\t\t\t}\n\t\t\tif(std::abs(results.front().miss) > requiredAccuracy){\n                            // changed\n                            //std::cout << \"Fast Solution not close enough (\" << results.front().miss << \"), pathLen: \"<<results.front().pathLen<<\"; refining\" << std::endl;\n\n\t\t\t\test.angle=refineRoot(sourcePos.GetZ(), target, results.front(), false, NoReflection, requiredAccuracy, sol_error ).first;\n                            // changed\n                            //std::cout << \"done refining\" << std::endl;\n\n\t\t\t\tif(replayBuffer==NULL)\n                                        {\n                                        //std::cout << \"Begin 2nd doTrace\" << std::endl;\n\t\t\t\t\tresults.front()=doTrace<fullRayPosition>(sourcePos.GetZ(), est.angle, target, NoReflection, frequency, polarization, sol_error );\n                                \n                                        // changed\n                                        //std::cout << \"done 2nd doTrace (if)\\n\" << std::endl;\n                                        //std::cout << \"results pathLen: \"<<results.front().pathLen<<\" miss: \"<<results.front().miss<<\"\\n\" << std::endl;\n\n                                        // changed\n                                        // if still don't satisfy accuracy, remove\n                                        if ( std::abs(results.front().miss) > requiredAccuracy ) {\n                                            //std::cout << \"missed too much, pop back!\" << std::endl;\n                                            results.pop_back();\n                                            sol_cnt--;\n                                        }\n                                        else if ( std::isnan(results.front().miss) ) {\n                                            //std::cout << \"nan info! pop back!\" << std::endl;\n                                            results.pop_back();\n                                            sol_cnt--;\n                                        }\n                                        //else\n                                            //sol_cnt++; // sol_cnt already done\n\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 11\\n\"<<std::endl;\n                                        }\n\t\t\t\telse{\n                                        //std::cout << \"Begin 2nd doTrace\" << std::endl;\n\t\t\t\t\tresults.front()=doTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(), est.angle, target, NoReflection, frequency, polarization, sol_error, recorder.get());\n                                        \n                                        // changed\n                                        //std::cout << \"done 2nd doTrace (else)\\n\" << std::endl;\n                                        //sol_cnt++;\n\n                                        // changed\n                                        // if still don't satisfy accuracy, remove\n                                        if ( std::abs(results.front().miss) > requiredAccuracy ) {\n                                            //std::cout << \"missed too much, pop back!\" << std::endl;\n                                            results.pop_back();\n                                            recorder->clearData();\n                                            replayBuffer->pop_back();\n                                            sol_cnt--;\n                                        }\n                                        else if ( std::isnan(results.front().miss) ) {\n                                            //std::cout << \"nan info! pop back!\" << std::endl;\n                                            results.pop_back();\n                                            recorder->clearData();\n                                            replayBuffer->pop_back();\n                                            sol_cnt--;\n                                        }\n                                        else {\n                                            replayBuffer->front()=recorder->getData();\n                                            recorder->clearData();\n                                            //sol_cnt++; // sol_cnt already done\n                                        }\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED!  12\\n\"<<std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//if(allowedReflections & SurfaceReflection){\n\t\t\tif((allowedReflections & SurfaceReflection) && (sol_cnt>0) ){ // try reflect solution if there was 1st solution existing\n\t\t\t\t\n                            // changed\n                            //std::cout << \"Looking for surface reflected solution, prev est.angle: \" << est.angle << std::endl;\n\n\t\t\t\t//double angle=traceRoot(sourcePos.GetZ(),target,0.0,est.angle-1e-1,true,SurfaceReflection,requiredAccuracy);\n\t\t\t\t\n\t\t\t\t//Here, we want to find another root, potentially near the direct solution, but distinct from it. \n\t\t\t\t//We expect this root to be in the damain [0,est.angle], but we don't want the root finding algorithm\n\t\t\t\t//to get distracted by the root that we know is at est.angle, so we subtract a small angle from the upper \n\t\t\t\t//bound. However, the roots may be arbitrarily close together, so any guess for this safety value may be too large\n\t\t\t\t//and we may end up exlusing the part of the domain which contains the root we want. So, if the root finding\n\t\t\t\t//doesn't manage to find a suitable root we decrease the safety value. \n\t\t\t\tdouble safety=initialSafety;\n\t\t\t\twhile(est.angle-safety < 0)\n\t\t\t\t\tsafety/=10.;\n\t\t\t\tstd::pair<double,double> root(-1.,10.*requiredAccuracy); //first element is the launch angle, second is miss distance\n\t\t\t\tdo{\n\t\t\t\t\troot=traceRoot(sourcePos.GetZ(),target,\n\t\t\t\t\t\t\t\t   0.0, //minimum angle\n\t\t\t\t\t\t\t\t   est.angle-safety, //maximum angle\n\t\t\t\t\t\t\t\t   true,SurfaceReflection,requiredAccuracy, sol_error );\n\t\t\t\t\tsafety/=10.;\n\t\t\t\t}while(safety>=minimumSafety && std::abs(root.second)>requiredAccuracy);\n\t\t\t\t//TODO: check here that root.first is within [0.0,est.angle-safety]\n\t\t\t\tif(replayBuffer==NULL)\n                                        {\n                                        // I guess here occurs one kind of error (log_ray_solver), (not occur when NO surface reflection)\n                                        // error which shows\n                                        // errMax>shrinkLimit, h = inf\n                                        //\n                                        // (infinite loop shows above)\n                                        //\n                                        //std::cout << \"Begin 3rd doTrace (replayBuffer==NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<fullRayPosition>(sourcePos.GetZ(),root.first,target,allowedReflections,frequency,polarization, sol_error ));\n                                        // changed\n                                        //std::cout << \"Done 3rd doTrace (if)\\n\" << std::endl;\n                                        //std::cout << \"results pathLen: \"<<results[1].pathLen<<\" miss: \"<<results[1].miss<<\"\\n\" << std::endl;\n                                        //sol_cnt++;\n\n                                        // changed\n                                        // if still don't satisfy accuracy, remove\n                                        if ( std::abs(results[1].miss) > requiredAccuracy ) {\n                                            //std::cout << \"missed too much, pop back!\" << std::endl;\n                                            results.pop_back();\n                                        }\n                                        else if ( std::isnan(results[1].miss) ) {\n                                            //std::cout << \"nan info! pop back!\" << std::endl;\n                                            results.pop_back();\n                                        }\n                                        else\n                                            sol_cnt++;\n\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 13\\n\"<<std::endl;\n                                        }\n\t\t\t\telse{\n                                        //std::cout << \"Begin 3rd doTrace (replayBuffer!=NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(),root.first,target,allowedReflections,frequency,polarization,sol_error, recorder.get()));\n                                        // changed\n                                        //std::cout << \"Done 3rd doTrace (else)\\n\" << std::endl;\n\t\t\t\t\t//replayBuffer->push_back(recorder->getData());\n\t\t\t\t\t//recorder->clearData();\n                                        //sol_cnt++;\n\n                                        // changed\n                                        // if still don't satisfy accuracy, remove\n                                        if ( std::abs(results[1].miss) > requiredAccuracy ) {\n                                            //std::cout << \"missed too much, pop back!\" << std::endl;\n                                            results.pop_back();\n                                            recorder->clearData();\n                                            replayBuffer->pop_back();\n                                        }\n                                        else if ( std::isnan(results[1].miss) ) {\n                                            //std::cout << \"nan info! pop back!\" << std::endl;\n                                            results.pop_back();\n                                            recorder->clearData();\n                                            replayBuffer->pop_back();\n                                        }\n                                        else {\n                                            replayBuffer->front()=recorder->getData();\n                                            recorder->clearData();\n                                            sol_cnt++;\n                                        }\n\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 14\\n\"<<std::endl;\n\t\t\t\t}\n\t\t\t} // if allowedreflections & SurfaceReflection\n                        \n                        // changed\n                        // bedrock reflect part not modified yet!\n\t\t\tif(allowedReflections & BedrockReflection){\n\t\t\t\t\n                            // changed\n                            //std::cout << \"Looking for bedrock reflected solution\" << std::endl;\n\n\t\t\t\t//double angle=traceRoot(sourcePos.GetZ(),target,est.angle+1e-4,pi,true,BedrockReflection,requiredAccuracy).first;\n\t\t\t\t\n\t\t\t\t//this is the same logic as for the surface reflected case, but the seacrh is in the domain [est.angle,pi]\n\t\t\t\tdouble safety=initialSafety;\n\t\t\t\twhile(est.angle+safety > pi)\n\t\t\t\t\tsafety/=10;\n\t\t\t\tstd::pair<double,double> root(-1.,10.*requiredAccuracy); //first element is the launch angle, second is miss distance\n\t\t\t\tdo{\n\t\t\t\t\troot=traceRoot(sourcePos.GetZ(),target,\n\t\t\t\t\t\t\t\t   est.angle+safety, //minimum angle\n\t\t\t\t\t\t\t\t   pi, //maximum angle\n\t\t\t\t\t\t\t\t   true,BedrockReflection,requiredAccuracy, sol_error );\n\t\t\t\t\tsafety/=10.;\n\t\t\t\t}while(safety>=minimumSafety && std::abs(root.second)>requiredAccuracy);\n\t\t\t\tif(replayBuffer==NULL)\n                                        {\n                                        //std::cout << \"Begin 4th doTrace (replayBuffer==NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<fullRayPosition>(sourcePos.GetZ(),root.first,target,allowedReflections,frequency,polarization, sol_error ));\n                                        //std::cout << \"Done 4th doTrace\" << std::endl;\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 15\\n\"<<std::endl;\n                                        }\n\t\t\t\telse{\n                                        //std::cout << \"Begin 4th doTrace (replayBuffer!=NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(),root.first,target,allowedReflections,frequency,polarization,sol_error, recorder.get()));\n                                        //std::cout << \"Done 4th doTrace\" << std::endl;\n\t\t\t\t\treplayBuffer->push_back(recorder->getData());\n\t\t\t\t\trecorder->clearData();\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 16\\n\"<<std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t} //got a solution estimate\n\n\t\telse{ //did not get a solution estimate\n\t\t\t\n                    \n                    // changed\n                    //std::cout << \"Didn't get fast solution\" << std::endl;\n\n\t\t\tdouble a=0.0,b=pi; //the endpoints of a range bracketing a root\n\t\t\tstd::pair<bool, double> minRes, maxRes, altMinRes;\n\t\t\tswitch(est.status){\n\t\t\t\tcase indexOfRefractionModel::SOLUTION:\n\t\t\t\t\t//impossible, this case was handled above\n\t\t\t\t\tbreak;\n\t\t\t\tcase indexOfRefractionModel::UPPER_LIMIT:\n\t\t\t\t\t//std::cout << \"UPPER_LIMIT, Got only upper limit of \" << est.angle << std::endl;\n\t\t\t\t\tb=est.angle;//std::min(pi,est.angle+.1); //add a small amount in case the solution is right at the boundary given by the estimate\n\t\t\t\t\tminRes = traceMin(sourcePos.GetZ(),target, sol_error, b,pi );\n\t\t\t\t\tmaxRes = traceMax(sourcePos.GetZ(),target, sol_error, 0.0,b );\n\t\t\t\t\tbreak;\n\t\t\t\tcase indexOfRefractionModel::LOWER_LIMIT:\n\t\t\t\t\t//std::cout << \"LOWER_LIMIT, Got only lower limit of \" << est.angle << std::endl;\n\t\t\t\t\ta=est.angle;//std::max(0.0,est.angle-.1);\n\t\t\t\t\tminRes = traceMin(sourcePos.GetZ(),target, sol_error, a,pi );\n\t\t\t\t\tmaxRes = traceMax(sourcePos.GetZ(),target, sol_error, 0.0,a );\n\t\t\t\t\tbreak;\n\t\t\t\tcase indexOfRefractionModel::NO_SOLUTION:\n\t\t\t\t\t//std::cout << \"NO_SOLUTION, Got no solution\" << std::endl;\n\t\t\t\t\t//Note that getting indexOfRefractionModel::NO_SOLUTION implies no _direct_ solution exists\n\t\t\t\t\t//if we were instructed to find reflected rays, we still need to do the work to look for them\n\t\t\t\t\tif((allowedReflections & SurfaceReflection) || (allowedReflections & BedrockReflection)){\n\t\t\t\t\t\tmaxRes = traceMax(sourcePos.GetZ(),target, sol_error, 0.0,pi );\n\t\t\t\t\t\tminRes = traceMin(sourcePos.GetZ(),target, sol_error, 0.0,pi );\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase indexOfRefractionModel::UNKNOWN:\n                                        // I guess here occurs one kind of error (log_ray_solver2), (occur whether or not surface reflection)\n                                        // error which shows\n                                        // terminate called throwing an exceptionAbort trap: 6\n                                        //\n\t\t\t\t\t//std::cout << \"UNKNOWN, Got no information\" << std::endl;\n\t\t\t\t\tmaxRes = traceMax(sourcePos.GetZ(),target, sol_error, 0.0,pi );\n\t\t\t\t\t//std::cout << \"maxRes : \" << maxRes.first << std::endl;\n\t\t\t\t\tminRes = traceMin(sourcePos.GetZ(),target, sol_error, 0.0,pi );\n\t\t\t\t\t//std::cout << \"minRes : \" << minRes.first << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t}\n                        //std::cout << \"done est.status switch\" << std::endl;\n\n\t\t\tif(minRes.first && maxRes.first){\n                            //std::cout<<\" minRes & maxRes true\" << std::endl;\n\t\t\t\tif(maxRes.second>minRes.second){\n\t\t\t\t\t//watch out; there must be two direct solutions\n\t\t\t\t\tdualDirect=true;\n\t\t\t\t\taltMinRes=minRes;\n\t\t\t\t\tminRes = traceMin(sourcePos.GetZ(),target, sol_error, maxRes.second,pi ); //look for the other minimum which should exist\n\t\t\t\t}\n\t\t\t\telse{ //we need to waste some time checking for another minimum\n\t\t\t\t\taltMinRes = traceMin(sourcePos.GetZ(),target, sol_error, 0.0,maxRes.second );\n\t\t\t\t\tdualDirect=altMinRes.first; //if a minimum is found, which is negative, then there is second direct solution\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(minRes.first && (allowedReflections & BedrockReflection)){\n\t\t\t\t//std::cout << \"Looking for bedrock reflected solution\" << std::endl;\n\t\t\t\tdouble angle=traceRoot(sourcePos.GetZ(),target,minRes.second,pi,true,BedrockReflection,requiredAccuracy, sol_error ).first;\n\t\t\t\tif(replayBuffer==NULL)\n                                        {\n                                        //std::cout << \"Begin 1st doTrace (replayBuffer==NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<fullRayPosition>(sourcePos.GetZ(),angle,target,allowedReflections,frequency,polarization, sol_error ));\n                                        //std::cout << \"Done 1st doTrace\" << std::endl;\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 17\\n\"<<std::endl;\n                                        }\n\t\t\t\telse{\n                                        //std::cout << \"Begin 1st doTrace (replayBuffer!=NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(),angle,target,allowedReflections,frequency,polarization,sol_error, recorder.get()));\n                                        //std::cout << \"Done 1st doTrace\" << std::endl;\n\t\t\t\t\treplayBuffer->push_back(recorder->getData());\n\t\t\t\t\trecorder->clearData();\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 18\\n\"<<std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(maxRes.first && (allowedReflections & SurfaceReflection) && fullyContained && !dualDirect){ //can't reflect frpom the surface if passing through the ice or if two direct solutions exist\n\t\t\t\t//std::cout << \"Looking for surface reflected solution\" << std::endl;\n\t\t\t\tdouble angle=traceRoot(sourcePos.GetZ(),target,0.0,maxRes.second,true,SurfaceReflection,requiredAccuracy, sol_error ).first;\n\t\t\t\tif(replayBuffer==NULL)\n                                        {\n                                        //std::cout << \"Begin 2nd doTrace (replayBuffer==NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<fullRayPosition>(sourcePos.GetZ(),angle,target,allowedReflections,frequency,polarization, sol_error ));\n                                        //std::cout << \"Done 2nd doTrace\" << std::endl;\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 19\\n\"<<std::endl;\n                                        }\n\t\t\t\telse{\n                                        //std::cout << \"Begin 2nd doTrace (replayBuffer!=NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(),angle,target,allowedReflections,frequency,polarization,sol_error, recorder.get()));\n                                        //std::cout << \"Done 2nd doTrace\" << std::endl;\n\t\t\t\t\treplayBuffer->push_back(recorder->getData());\n\t\t\t\t\trecorder->clearData();\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 20\\n\"<<std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif((minRes.first || maxRes.first) && est.status!=indexOfRefractionModel::NO_SOLUTION){\n\t\t\t\tif(minRes.first && minRes.second<b)\n\t\t\t\t\tb=minRes.second;\n\t\t\t\tif(maxRes.first && maxRes.second>a)\n\t\t\t\t\ta=maxRes.second;\n\t\t\t\t//std::cout << \"Looking for direct solution\" << std::endl;\n\t\t\t\tdouble angle=traceRoot(sourcePos.GetZ(),target,a,b,false,NoReflection,requiredAccuracy, sol_error ).first;\n\t\t\t\t//std::cout << \"Angle for direct ray is \" << angle << std::endl;\n\t\t\t\tif(replayBuffer==NULL)\n                                        {\n                                        //std::cout << \"Begin 3rd doTrace (replayBuffer==NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<fullRayPosition>(sourcePos.GetZ(),angle,target,allowedReflections,frequency,polarization, sol_error ));\n                                        //std::cout << \"Done 3rd doTrace\" << std::endl;\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 21\\n\"<<std::endl;\n                                        }\n\t\t\t\telse{\n                                        //std::cout << \"Begin 3rd doTrace (replayBuffer!=NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(),angle,target,allowedReflections,frequency,polarization,sol_error, recorder.get()));\n                                        //std::cout << \"Done 3rd doTrace\" << std::endl;\n\t\t\t\t\treplayBuffer->push_back(recorder->getData());\n\t\t\t\t\trecorder->clearData();\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 22\\n\"<<std::endl;\n\t\t\t\t}\n\t\t\t\t//TODO: should this next part be kept?\n\t\t\t\tif(std::abs(results.back().miss) > 10.0*requiredAccuracy){ //if it wasn't really a solution, throw it away\n\t\t\t\t\t//std::cout << \"Supposed solution missed by \" << results.back().miss << \" meters, rejecting\" << std::endl;\n\t\t\t\t\tresults.pop_back();\n\t\t\t\t\tif(replayBuffer!=NULL)\n\t\t\t\t\t\treplayBuffer->pop_back();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(dualDirect){\n\t\t\t\t//std::cout << \"Looking for secondary direct ray\" << std::endl;\n\t\t\t\tdouble angle=traceRoot(sourcePos.GetZ(),target,altMinRes.second,maxRes.second,true,NoReflection,requiredAccuracy, sol_error ).first;\n\t\t\t\t//std::cout << \"Angle for second direct ray is \" << angle << std::endl;\n\t\t\t\tif(replayBuffer==NULL)\n                                        {\n                                        //std::cout << \"Begin 4th doTrace (replayBuffer==NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<fullRayPosition>(sourcePos.GetZ(),angle,target,NoReflection,frequency,polarization, sol_error ));\n                                        //std::cout << \"Done 4th doTrace\" << std::endl;\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 23\\n\"<<std::endl;\n                                        }\n\t\t\t\telse{\n                                        //std::cout << \"Begin 4th doTrace (replayBuffer!=NULL)\" << std::endl;\n\t\t\t\t\tresults.push_back(doTrace<positionRecordingWrapper<fullRayPosition> >(sourcePos.GetZ(),angle,target,NoReflection,frequency,polarization, sol_error, recorder.get()));\n                                        //std::cout << \"Done 4th doTrace\" << std::endl;\n\t\t\t\t\treplayBuffer->push_back(recorder->getData());\n\t\t\t\t\trecorder->clearData();\n                                        sol_cnt++;\n                                        //std::cout<<\"\\n\\tSOL_CNT ADDED! 24\\n\"<<std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t} //did not get a solution estimate\n\t\t//std::cout << \"Have \" << results.size() << \" solution\" << (results.size()!=1?\"s\":\"\") << std::endl;\n                //\n\n\t\tif(results.size() > 1){\n\t\t\tif(replayBuffer==NULL)\n                                {\n                                //std::cout << \"replayBuffer==NULL\" <<std::endl;\n\t\t\t\tstd::sort(results.begin(),results.end(),&shorterPath);\n                                }\n\t\t\telse\n                                {\n                                //std::cout << \"replayBuffer!=NULL\" <<std::endl;\n\t\t\t\tdual_insertion_sort(results.begin(),results.end(),replayBuffer->begin(),&shorterPath);\n                                }\n\t\t}\n                else {  // no solution case\n                    sol_cnt = 0;\n                    //std::cout<<\"\\n\\tSOL_CNT 0 as no sol\\n\"<<std::endl;\n                }\n\t\treturn(results);\n\t}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\tTraceRecord TraceFinder::findUncontainedFast(Vector sourcePos, Vector targetPos, double frequency, double polarization, double requiredAccuracy, int &sol_error, pathRecorder<fullRayPosition>* recorder ) const{\n\n            // test sol_error\n            //int sol_error;\n\n\n\t\tTraceRecord trace;\n\t\t//TODO: if both points are above surface, give obvious answers\n\t\tif(sourcePos.GetZ()<maximum_ice_depth || targetPos.GetZ()<maximum_ice_depth)\n\t\t\treturn(trace);\n\t\t//the index of refraction of the ice at the surface\n\t\tconst double surfaceN = rModel->indexOfRefraction(0.0);\n\t\tdouble wholeDist = sqrt((targetPos.GetX()-sourcePos.GetX())*(targetPos.GetX()-sourcePos.GetX())+(targetPos.GetY()-sourcePos.GetY())*(targetPos.GetY()-sourcePos.GetY()));\n\t\tdouble upper=std::max(sourcePos.GetZ(),targetPos.GetZ());\n\t\tdouble lower=std::min(sourcePos.GetZ(),targetPos.GetZ());\n\t\trayTargetRecord target(lower,wholeDist);\n\t\tdouble minDist=0.0, maxDist=wholeDist;\n\t\tdouble dist=(minDist+maxDist)/2.; //the distance which will be covered by the ray while in the ice\n\t\tdouble thetaA=0.0,thetaB=0.0;\n\t\twhile((maxDist-minDist)>requiredAccuracy/10.){\n\t\t\t//std::cout << \"Trying dist=\" << dist << std::endl;\n\t\t\t//thetaA is the angle of the straight line ray above the ice\n\t\t\tthetaA=pi-atan((wholeDist-dist)/upper);\n\t\t\t//thetaB is the angle the straight line ray would have below the ice\n\t\t\tthetaB=pi-asin(sin(pi-thetaA)/surfaceN);\n\t\t\t//std::cout << \"Angles are \" << thetaA << ' ' << thetaB << std::endl;\n\t\t\t\n\t\t\tindexOfRefractionModel::RayEstimate est=rModel->estimateRayAngle(0.0, lower, dist);\n\t\t\tif(est.status == indexOfRefractionModel::SOLUTION){\n\t\t\t\t//std::cout << \"Got estimate at angle \" << est.angle << std::endl;\n\t\t\t\tif(est.angle<thetaB)\n\t\t\t\t\tmaxDist=dist;\n\t\t\t\telse if(est.angle>thetaB)\n\t\t\t\t\tminDist=dist;\n\t\t\t\telse //we got lucky\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse{\n\t\t\t\ttarget.distance = dist;\n\t\t\t\ttrace = doTrace<minimalRayPosition>(0.0,thetaB,target,NoReflection,0.0,0.0, sol_error );\n\t\t\t\t//std::cout << \"Trace missed by \" << trace.miss << std::endl;\n\t\t\t\tif(std::abs(trace.miss) <= requiredAccuracy)\n\t\t\t\t\tbreak;\n\t\t\t\tif(trace.miss<0.0)\n\t\t\t\t\tmaxDist=dist;\n\t\t\t\telse if(trace.miss>0.0)\n\t\t\t\t\tminDist=dist;\n\t\t\t}\n\t\t\t\n\t\t\tdist=(minDist+maxDist)/2.;\n\t\t}\n\t\t\n\t\t//compute the path length the above ice segment\n\t\tdouble extraLength=sqrt(upper*upper+(wholeDist-dist)*(wholeDist-dist));\n\t\t//compute attenuation due to passing through the ice surface\n\t\tdouble transmissionAttenuation;\n\t\tif(sourcePos.GetZ() > targetPos.GetZ())\n\t\t\ttransmissionAttenuation=fresnelTransmit(pi-thetaA, polarization, 1.0, surfaceN);\n\t\telse\n\t\t\ttransmissionAttenuation=fresnelTransmit(pi-thetaB, polarization, surfaceN, 1.0);\n\t\t//do the final version trace\n\t\ttarget.distance = dist;\t\n\t\tif(recorder==NULL)\n\t\t\ttrace = doTrace<fullRayPosition>(0.0,thetaB,target,NoReflection,frequency,polarization, sol_error );\n\t\telse{\n\t\t\tcallCallback(recorder,positionRecordingWrapper<fullRayPosition>(fullRayPosition(0.0,upper,((sourcePos.GetZ() > targetPos.GetZ())?thetaA:thetaB)-pi,extraLength/speedOfLight,transmissionAttenuation)),RK_AIR_STEP);\n\t\t\ttrace = doTrace<positionRecordingWrapper<fullRayPosition> >(0.0,thetaB,target,NoReflection,frequency,polarization, sol_error, recorder);\n\t\t}\n\t\t//include surface crossing attenuation\n\t\ttrace.attenuation*=transmissionAttenuation;\n\t\t//add on path length the above ice segment\n\t\ttrace.pathLen+=extraLength;\n\t\ttrace.pathTime+=extraLength/speedOfLight;\n\t\t//fix up the angles\n\t\tif(sourcePos.GetZ() > targetPos.GetZ()){ //upper is the source depth\n\t\t\ttrace.launchAngle=thetaA;\n\t\t\t//receipt angle is as calculated by doTrace\n\t\t\ttrace.reflectionAngle=-thetaA;\n\t\t}\n\t\telse{ //lower is the source depth\n\t\t\ttrace.launchAngle=pi-trace.receiptAngle;\n\t\t\ttrace.receiptAngle=pi-thetaA;\n\t\t\ttrace.reflectionAngle=thetaB-pi;\n\t\t}\n\t\treturn(trace);\n\t}\n\t\n\tdouble TraceFinder::signalStrength(const TraceRecord& ray, const Vector& src, const Vector& trg, unsigned short allowedReflections, int &sol_error ) const{\n\n            // test sol_error\n            //int sol_error;\n\n\n\t\tconst double changeThresh=1e-3; //10^(-n) should give about n digits of accuracy\n\t\tconst double startDelta=.002;\n\t\t//std::cout << \"Considering focusing from \" << src << \" to \" << trg << \" at angle \" << ray.launchAngle << std::endl;\n\t\tdouble dist = sqrt((trg.GetX()-src.GetX())*(trg.GetX()-src.GetX())+(trg.GetY()-src.GetY())*(trg.GetY()-src.GetY()));\n\t\tif(ray.launchAngle<.01 || ray.launchAngle>(pi-.01)){\n\t\t\t//std::cout << \"ray too close to vertical\" << std::endl;\n\t\t\treturn(-1.0);\n\t\t}\n\t\t\n\t\t//std::cout << \"Original ray miss distance: \" << ray.miss << std::endl;\n\t\tunsigned int steps=1;\n\t\tdouble scaledChange=1e10;\n\t\tdouble lastChange=0.0;\n\t\tunsigned int scaleIncrease=0;\n\t\tconst double multInc=2.0;\n\t\tdouble ratio,accel;\n\t\tstd::vector<double> terms;\n\t\tstd::queue<double> past;\n\t\tfor(double deltaTheta=startDelta; scaledChange>changeThresh; deltaTheta/=multInc){\n\t\t\t//std::cout << \"\\tdeltaTheta = \" << deltaTheta << std::endl;\n\t\t\t//std::cout << \"\\tlaunch angle will be \" << ray.launchAngle-deltaTheta << std::endl;\n\t\t\tTraceRecord testRay = doTrace<minimalRayPosition>(src.GetZ(), ray.launchAngle+deltaTheta, rayTargetRecord(trg.GetZ(),dist), allowedReflections, 0.0, 0.0, sol_error );\n\t\t\t//std::cout << \"\\t\\ttest ray miss distance: \" << testRay.miss << std::endl;\n\t\t\tratio=std::abs(deltaTheta/(ray.miss-testRay.miss));\n\t\t\t//std::cout << \"\\t\\tdeltaTheta/deltaZ =  \" << ratio << std::endl;\n\t\t\tterms.push_back(ratio);\n\t\t\tif(!past.empty()){\n\t\t\t\tdouble old=past.back();\n\t\t\t\tdouble mult=multInc;\n\t\t\t\taccel=ratio;\n\t\t\t\tpast.push(ratio);\n\t\t\t\tfor(unsigned int i=0; i<steps-1; i++){\n\t\t\t\t\tmult*=multInc;\n\t\t\t\t\taccel=(mult*accel-past.front())/(mult-1.0);\n\t\t\t\t\tpast.pop();\n\t\t\t\t\tpast.push(accel);\n\t\t\t\t}\n\t\t\t\t//std::cout << \"\\t\\textrapolated value = \" << accel << std::endl;\n\t\t\t\tscaledChange=std::abs(old-accel)/accel;\n\t\t\t\t//std::cout << \"\\t\\tscaled change = \" << scaledChange << std::endl;\n\t\t\t\tif(scaledChange>lastChange){\n\t\t\t\t\t//std::cout << \"\\t\\tWARNING: SCALE INCREASE!\" << std::endl;\n\t\t\t\t\tscaleIncrease++;\n\t\t\t\t\tif(scaleIncrease>=3){\n\t\t\t\t\t\t//std::cout << \"\\t\\tWARNING: scale increased over \" << scaleIncrease <<  \" consecutive steps\" << std::endl;\n\t\t\t\t\t\t//scaleIncrease>=n means terms.size()>=n+1\n\t\t\t\t\t\t//accel=(8**(terms.end()-2)-6**(terms.end()-1)+terms.back())/3.0; //n=2 case\n\t\t\t\t\t\taccel=(64.**(terms.end()-3)-56.**(terms.end()-2)+14.**(terms.end()-1)-terms.back())/21.0; //n=3 case\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t//break;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tscaleIncrease=0;\n\t\t\t\tlastChange=scaledChange;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tpast.push(ratio);\n\t\t\t\taccel=ratio;\n\t\t\t}\n\t\t\tsteps++;\n\t\t}\n\t\t\n\t\tdouble ir=rModel->indexOfRefraction(trg.GetZ())/rModel->indexOfRefraction(src.GetZ());\n\t\treturn(sqrt(ir*accel/dist));\n\t}\n\t\n\t//explicitly instantiate\n\ttemplate void TraceFinder::rkStepControl<minimalRayPosition>(double&, double, minimalRayPosition&, minimalRayPosition&, const minimalRayPosition&, const double, const double, double&, double&) const;\n\n} //namespace RayTrace\n", "meta": {"hexsha": "4fa67064d735a659d93da84c6c43ac53590cdb09", "size": 84693, "ext": "cc", "lang": "C++", "max_stars_repo_path": "RayTrace.cc", "max_stars_repo_name": "shrishabh/phasedArrayARA", "max_stars_repo_head_hexsha": "bb10fcbf7b0b26c5db34a7aeffbadfef7f1aacf5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-09T15:08:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-09T15:08:56.000Z", "max_issues_repo_path": "RayTrace.cc", "max_issues_repo_name": "shrishabh/phasedArrayOptimized", "max_issues_repo_head_hexsha": "013df1e759b12f08b1c83bba675de6a5e287103a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RayTrace.cc", "max_forks_repo_name": "shrishabh/phasedArrayOptimized", "max_forks_repo_head_hexsha": "013df1e759b12f08b1c83bba675de6a5e287103a", "max_forks_repo_licenses": ["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.5663580247, "max_line_length": 295, "alphanum_fraction": 0.5842513549, "num_tokens": 22243, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5851011397337391, "lm_q2_score": 0.3557748798522984, "lm_q1q2_score": 0.2081642876902139}}
{"text": "#include <android/sensor.h>\r\n#include <sys/sysinfo.h>\r\n#include <stdlib.h>\r\n#include <stdio.h>\r\n#include <unistd.h>\r\n#include <math.h>\r\n#include <vector>\r\n#include <string>\r\n#include <strings.h>\r\n#include <iostream>\r\n#include <iomanip>\r\n#include <sstream>\r\n#include <time.h>\r\n#include <sys/socket.h>\r\n#include <arpa/inet.h>\r\n\r\n#include <Eigen>\r\n\r\n#include <ros/ros.h>\r\n#include <sandshark_common/main.h>\r\n#include <sandshark_common/task_base.h>\r\n#include <sandshark_common/driver_base.h>\r\n\r\n#include <sandshark_msgs/OrientationEuler.h>\r\n#include <sandshark_msgs/OrientationQuaternion.h>\r\n#include <sandshark_msgs/OrientationDebug.h>\r\n#include <sandshark_msgs/MotionRaw.h>\r\n#include <sandshark_msgs/MotionCorrected.h>\r\n#include <sandshark_msgs/AccelCalib.h>\r\n#include <sandshark_msgs/MagCalib.h>\r\n\r\n#define LOOPER_ID_USER 3\r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\nnamespace bluefin {\r\nnamespace sandshark {\r\n\r\nclass MotionDriver: public DriverBase {\r\n  private:\r\n    ALooper* _looper;\r\n    ASensorManager* _sensorManager;\r\n    vector<const ASensor*> _sensorList;\r\n    vector<ASensorEventQueue*> _queueList;\r\n    vector<ASensorEvent> _eventList;\r\n\r\n    ros::Publisher _orientPub;\r\n    sandshark_msgs::OrientationEuler _orientMsg;\r\n\r\n    ros::Publisher _orientDebugPub;\r\n    sandshark_msgs::OrientationDebug _orientDebugMsg;\r\n\r\n    ros::Publisher _orientQuaternionPub;\r\n    sandshark_msgs::OrientationQuaternion _orientQuaternionMsg;\r\n\r\n    ros::Publisher _rawPub;\r\n    sandshark_msgs::MotionRaw _rawMsg;\r\n\r\n    ros::Publisher _correctedPub;\r\n    sandshark_msgs::MotionCorrected _correctedMsg;\r\n\r\n    ros::ServiceServer _accelService;\r\n    ros::ServiceServer _magService;\r\n\r\n    struct timespec _start;\r\n    bool _firstRun;\r\n    bool _needSleep;\r\n    Vector3d _correctedAccel;\r\n    Vector3d _gravityAccel;\r\n    Vector3d _linearAccel;\r\n\r\n    Vector3d _accelOffset;\r\n    Vector3d _accelScaling;\r\n\r\n    Vector3d _correctedMag;\r\n\r\n    Vector3d _magOffset;\r\n    Vector3d _magScaling;\r\n    Matrix3d _magAdjust;\r\n\r\n    Quaternion<double> _attitudeEstimate;\r\n\r\n    Quaternion<double> _rCQuaternion;\r\n\r\n    double _alpha;\r\n    double _beta;\r\n    double _zeta;\r\n\r\n    double _gyroBiasX;\r\n    double _gyroBiasY;\r\n    double _gyroBiasZ;\r\n\r\n    double _firstBetaDuration;\r\n    double _firstBeta;\r\n    double _start_time;\r\n\r\n    bool _imuFilterEnabled;\r\n    bool _imuFilterAfterBeta;\r\n    bool _imuFilterWithBadMag;\r\n    double _minGoodMag;\r\n    double _maxGoodMag;\r\n\r\n    bool _sendUDP;\r\n    std::string _sendIPAddress;\r\n    int _sendIPPort;\r\n    int _sendSocket;\r\n    struct sockaddr_in _sendAddrStruct;\r\n    bool _sendAndroidQuaternion;\r\n\r\n    void convertAndPublishEuler();\r\n\r\n    bool ahrsEnabled(double magMagnitude);\r\n    void publishEulerAngles();\r\n    void publishDebug();\r\n\r\n    void reset(bool writeParams);\r\n\r\n    void cleanup();\r\n  protected:\r\n    void startupInitCallback();\r\n    bool doInitialize();\r\n    bool doRun();\r\n  public:\r\n    MotionDriver() :\r\n        DriverBase(\"MotionDriver\", \"motion\") {\r\n    }\r\n\r\n    bool handleAccelCalibUpdate(sandshark_msgs::AccelCalib::Request &req, sandshark_msgs::AccelCalib::Response &res);\r\n    bool handleMagCalibUpdate(sandshark_msgs::MagCalib::Request &req, sandshark_msgs::MagCalib::Response &res);\r\n\r\n    void handleSleep();\r\n    void handleShutdown() {\r\n      cleanup();\r\n    }\r\n};\r\n\r\nvoid MotionDriver::startupInitCallback() {\r\n  ROS_INFO(\"Task init! - creating orient node\");\r\n  fflush( stdout);\r\n\r\n  _orientPub = _publicNode->advertise<sandshark_msgs::OrientationEuler>(\"orientation_euler\", 1);\r\n  _orientDebugPub = _publicNode->advertise<sandshark_msgs::OrientationDebug>(\"orientation_debug\", 1);\r\n  _orientQuaternionPub = _publicNode->advertise<sandshark_msgs::OrientationQuaternion>(\"orientation_quaternion\", 1);\r\n  _rawPub = _publicNode->advertise<sandshark_msgs::MotionRaw>(\"raw_sensors\", 1);\r\n  _correctedPub = _publicNode->advertise<sandshark_msgs::MotionCorrected>(\"corrected_sensors\", 1);\r\n\r\n  _accelService = _publicNode->advertiseService(\"calibrateAccel\", &MotionDriver::handleAccelCalibUpdate, this);\r\n  _magService = _publicNode->advertiseService(\"calibrateMag\", &MotionDriver::handleMagCalibUpdate, this);\r\n\r\n  _sensorManager = ASensorManager_getInstance();\r\n  _looper = ALooper_forThread();\r\n  if (_looper == NULL) {\r\n    _looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);\r\n    ROS_INFO(\"Looper was NULL called prepare!\");\r\n  }\r\n  ROS_INFO(\"Task init! Param stuff looper is %p\", _looper);\r\n  fflush( stdout);\r\n\r\n  string key;\r\n  vector<double> values;\r\n  char comma;\r\n  double value;\r\n\r\n  _accelOffset << 0.0, 0.0, 0.0;\r\n  values.clear();\r\n  if (ros::param::search(\"accel_offset\", key)) {\r\n    string accel_offset;\r\n    ros::param::get(key, accel_offset);\r\n\r\n    istringstream iss(accel_offset);\r\n    while (iss >> value) {\r\n      values.push_back(value);\r\n      iss >> comma;\r\n    }\r\n\r\n    if (values.size() == 3) {\r\n      for (unsigned int i = 0; i < values.size(); ++i) {\r\n        _accelOffset[i] = values[i];\r\n      }\r\n    }\r\n  }\r\n  cout << \"Accel Offset: \" << _accelOffset << std::endl;\r\n\r\n  ROS_INFO(\"Task init! Param aOffset\");\r\n  fflush( stdout);\r\n\r\n  _accelScaling << 9.8, 9.8, 9.8;\r\n  values.clear();\r\n  if (ros::param::search(\"accel_scaling\", key)) {\r\n    string accel_scaling;\r\n    ros::param::get(key, accel_scaling);\r\n\r\n    istringstream iss(accel_scaling);\r\n    while (iss >> value) {\r\n      values.push_back(value);\r\n      iss >> comma;\r\n    }\r\n\r\n    if (values.size() == 3) {\r\n      for (unsigned int i = 0; i < values.size(); ++i) {\r\n        _accelScaling[i] = values[i];\r\n      }\r\n    }\r\n  }\r\n\r\n  cout << \"Accel Scaling \" << _accelScaling << std::endl;\r\n\r\n  _magOffset << 0.0, 0.0, 0.0;\r\n  values.clear();\r\n  if (ros::param::search(\"mag_offset\", key)) {\r\n    string mag_offset;\r\n    ros::param::get(key, mag_offset);\r\n\r\n    istringstream iss(mag_offset);\r\n    while (iss >> value) {\r\n      values.push_back(value);\r\n      iss >> comma;\r\n    }\r\n\r\n    if (values.size() == 3) {\r\n      for (unsigned int i = 0; i < values.size(); ++i) {\r\n        _magOffset[i] = (values[i]);\r\n      }\r\n    }\r\n  }\r\n  cout << \"Mag Offset: \" << _magOffset << std::endl;\r\n\r\n  fflush( stdout);\r\n  _magAdjust = Matrix3d::Identity();\r\n  values.clear();\r\n  if (ros::param::search(\"mag_adjust\", key)) {\r\n    string mag_adjust;\r\n    ros::param::get(key, mag_adjust);\r\n\r\n    istringstream iss(mag_adjust);\r\n    while (iss >> value) {\r\n      values.push_back(value);\r\n      iss >> comma;\r\n    }\r\n\r\n    if (values.size() == 9) {\r\n      for (unsigned int i = 0; i < values.size(); ++i) {\r\n        int row = i / 3;\r\n        int col = i % 3;\r\n        ROS_INFO(\"i %d row %d col %d val %f\", i, row, col, values[i]);\r\n        fflush( stdout);\r\n        _magAdjust(row, col) = values[i];\r\n      }\r\n    }\r\n  }\r\n  cout << \"Mag Adjust: \" << _magAdjust << std::endl;\r\n\r\n  _magScaling << 1.0, 1.0, 1.0;\r\n  values.clear();\r\n  if (ros::param::search(\"mag_scaling\", key)) {\r\n    string mag_scaling;\r\n    ros::param::get(key, mag_scaling);\r\n\r\n    istringstream iss(mag_scaling);\r\n    while (iss >> value) {\r\n      values.push_back(value);\r\n      iss >> comma;\r\n    }\r\n\r\n    if (values.size() == 3) {\r\n      for (unsigned int i = 0; i < values.size(); ++i) {\r\n        _magScaling[i] = values[i];\r\n      }\r\n    }\r\n  }\r\n\r\n  cout << \"Mag Scaling: \" << _magScaling << std::endl;\r\n\r\n  ROS_INFO(\"Task init! Private Param stuff\");\r\n  fflush( stdout);\r\n  _privateNode->param(\"alpha\", _alpha, double(0.8));\r\n  _privateNode->param(\"beta\", _beta, double(0.2));\r\n  _privateNode->param(\"zeta\", _zeta, double(0.05));\r\n\r\n  _privateNode->param(\"firstBetaDuration\", _firstBetaDuration, double(10.0));\r\n  _privateNode->param(\"firstBeta\", _firstBeta, double(2.5));\r\n\r\n  _privateNode->param(\"sendUDP\", _sendUDP, false);\r\n  _privateNode->param(\"sendIPAddress\", _sendIPAddress, std::string(\"127.0.0.1\"));\r\n  _privateNode->param(\"sendIPPort\", _sendIPPort, int(5555));\r\n  ROS_INFO(\"SendIP %s : %d\", _sendIPAddress.c_str(), _sendIPPort);\r\n  _privateNode->param(\"sendAndroidQuaternion\", _sendAndroidQuaternion, false);\r\n\r\n  _privateNode->param(\"imuFilterEnabled\", _imuFilterEnabled, false);\r\n  _privateNode->param(\"imuFilterAfterBeta\", _imuFilterAfterBeta, false);\r\n  _privateNode->param(\"imuFilterWithBadMag\", _imuFilterWithBadMag, false);\r\n  _privateNode->param(\"minGoodMag\", _minGoodMag, double(25)); //Units ?!?!?\r\n  _privateNode->param(\"maxGoodMag\", _maxGoodMag, double(65));\r\n\r\n  _sendSocket = -1;\r\n  if (_sendUDP) {\r\n    _sendSocket = socket( AF_INET, SOCK_DGRAM, 0);\r\n    if (_sendSocket < 0) {\r\n      fprintf( stderr, \"Socket is bad!\\n\");\r\n      exit(-1);\r\n    }\r\n\r\n    struct sockaddr_in myaddr;\r\n    memset((char *) &myaddr, 0, sizeof(myaddr));\r\n    myaddr.sin_family = AF_INET;\r\n    myaddr.sin_addr.s_addr = htonl( INADDR_ANY);\r\n    myaddr.sin_port = htons(0);\r\n    if (::bind(_sendSocket, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0) {\r\n      fprintf( stderr, \"bind failed! %d:%s\\n\", errno, strerror( errno));\r\n      exit(-1);\r\n    }\r\n\r\n    memset(&_sendAddrStruct, 0, sizeof(_sendAddrStruct));\r\n    _sendAddrStruct.sin_addr.s_addr = inet_addr(_sendIPAddress.c_str());\r\n    _sendAddrStruct.sin_family = AF_INET;\r\n    _sendAddrStruct.sin_port = htons(_sendIPPort);\r\n\r\n  }\r\n  ROS_INFO(\"Param alpha %f beta %f zeta %f\", _alpha, _beta, _zeta);\r\n  ROS_INFO(\"Task start! Param stuff complete\");\r\n  fflush( stdout);\r\n}\r\n\r\nbool MotionDriver::handleAccelCalibUpdate(sandshark_msgs::AccelCalib::Request &req,\r\n    sandshark_msgs::AccelCalib::Response &res) {\r\n  std::ostringstream strs;\r\n  if ((req.accelOffset.size() < 3) || (req.accelScaling.size() < 3)) {\r\n    res.accepted = false;\r\n    return true;\r\n  }\r\n\r\n  _accelOffset << req.accelOffset[0], req.accelOffset[1], req.accelOffset[2];\r\n  strs << _accelOffset[0] << \",\" << _accelOffset[1] << \",\" << _accelOffset[2];\r\n  _privateNode->setParam(\"accel_offset\", strs.str());\r\n\r\n  strs.str(\"\");\r\n  strs.clear();\r\n\r\n  _accelScaling << req.accelScaling[0], req.accelScaling[1], req.accelScaling[2];\r\n  strs << _accelScaling[0] << \",\" << _accelScaling[1] << \",\" << _accelScaling[2];\r\n  _privateNode->setParam(\"accel_scaling\", strs.str());\r\n\r\n  cout << \"Service UPDATE Accel Offset: \" << _accelOffset << std::endl;\r\n  cout << \"Service UPDATE Accel Scaling: \" << _accelScaling << std::endl;\r\n  res.accepted = true;\r\n  reset(true);\r\n  return true;\r\n}\r\n\r\nbool MotionDriver::handleMagCalibUpdate(sandshark_msgs::MagCalib::Request &req,\r\n    sandshark_msgs::MagCalib::Response &res) {\r\n  std::ostringstream strs;\r\n  if ((req.magOffset.size() < 3) || (req.magScaling.size() < 3) || (req.magAdjust.size() < 9)) {\r\n    res.accepted = false;\r\n    return true;\r\n  }\r\n\r\n  _magOffset << req.magOffset[0], req.magOffset[1], req.magOffset[2];\r\n  strs << _magOffset[0] << \",\" << _magOffset[1] << \",\" << _magOffset[2];\r\n  _privateNode->setParam(\"mag_offset\", strs.str());\r\n\r\n  strs.str(\"\");\r\n  strs.clear();\r\n\r\n  _magScaling << req.magScaling[0], req.magScaling[1], req.magScaling[2];\r\n  strs << _magScaling[0] << \",\" << _magScaling[1] << \",\" << _magScaling[2];\r\n  _privateNode->setParam(\"mag_scaling\", strs.str());\r\n\r\n  strs.str(\"\");\r\n  strs.clear();\r\n\r\n  _magAdjust << req.magAdjust[0], req.magAdjust[1], req.magAdjust[2], req.magAdjust[3], req.magAdjust[4], req.magAdjust[5], req.magAdjust[6], req.magAdjust[7], req.magAdjust[8];\r\n  strs << _magAdjust(0, 0) << \",\" << _magAdjust(0, 1) << \",\" << _magAdjust(0, 2) << \",\" << _magAdjust(1, 0) << \",\"\r\n      << _magAdjust(1, 1) << \",\" << _magAdjust(1, 2) << \",\" << _magAdjust(2, 0) << \",\" << _magAdjust(2, 1) << \",\"\r\n      << _magAdjust(2, 2);\r\n  _privateNode->setParam(\"mag_adjust\", strs.str());\r\n\r\n  cout << \"Service UPDATE Mag Offset: \" << _magOffset << std::endl;\r\n  cout << \"Service UPDATE Mag Scaling: \" << _magScaling << std::endl;\r\n  cout << \"Service UPDATE Mag Adjust: \" << _magAdjust << std::endl;\r\n\r\n  res.accepted = true;\r\n  reset(true);\r\n  return true;\r\n}\r\n\r\nbool MotionDriver::doInitialize() {\r\n  cleanup();\r\n\r\n  _needSleep = false;\r\n  ASensorList senList;\r\n  int numAllSensors = ASensorManager_getSensorList(_sensorManager, &senList);\r\n\r\n  ROS_INFO(\"Task init! Motion numsen %d\", numAllSensors);\r\n  fflush( stdout);\r\n  int rc;\r\n  for (int i = 0; i < numAllSensors; ++i) {\r\n    const ASensor *sensor = senList[i];\r\n    ROS_INFO(\"Sensor Name %s Vendor %s Res %f Type %d\", ASensor_getName(sensor), ASensor_getVendor(sensor),\r\n        ASensor_getResolution(sensor), ASensor_getType(sensor));\r\n    if ((std::string(ASensor_getName(sensor)) == \"MPL magnetic field\")\r\n        || (std::string(ASensor_getName(sensor)) == \"MPL accel\") || (std::string(ASensor_getName(sensor)) == \"MPL Gyro\")\r\n        || (_sendAndroidQuaternion && (std::string(ASensor_getName(sensor)) == \"MPL rotation vector\"))) {\r\n      ASensorEventQueue* queue = ASensorManager_createEventQueue(_sensorManager, _looper, LOOPER_ID_USER, NULL, NULL);\r\n      if (!queue) {\r\n        ROS_INFO(\"error creating sensor event queue\");\r\n        return false;\r\n      }\r\n      rc = ASensorEventQueue_enableSensor(queue, sensor);\r\n      if (rc < 0) {\r\n        ROS_INFO(\"ASensorEventQueue_enableSensor error: %d\", rc);\r\n        return false;\r\n      }\r\n      rc = ASensorEventQueue_setEventRate(queue, sensor, ASensor_getMinDelay(sensor));\r\n      if (rc < 0) {\r\n        ROS_INFO(\"ASensorEventQueue_setEventRate error: %d\", rc);\r\n        return false;\r\n      }\r\n\r\n      fprintf( stderr, \"Pushing back Sensor Name %s Vendor %s Res %f\\n\", ASensor_getName(sensor),\r\n          ASensor_getVendor(sensor), ASensor_getResolution(sensor));\r\n      _sensorList.push_back(sensor);\r\n      _queueList.push_back(queue);\r\n      _eventList.push_back(ASensorEvent());\r\n    }\r\n  }\r\n\r\n  ROS_INFO(\"Task init! Motion sen complete %d\", (int) _queueList.size());\r\n  fflush( stdout);\r\n\r\n  reset(false);\r\n\r\n  ROS_INFO(\"Task init! Motion init complete event %d\", (int) _eventList.size());\r\n  fflush( stdout);\r\n\r\n  return true;\r\n}\r\n\r\nvoid MotionDriver::reset(bool writeParams) {\r\n  _firstRun = true;\r\n  clock_gettime( CLOCK_REALTIME, &_start);\r\n  _start_time = ros::WallTime::now().toSec();\r\n\r\n  _gyroBiasX = 0.0;\r\n  _gyroBiasY = 0.0;\r\n  _gyroBiasZ = 0.0;\r\n  _attitudeEstimate.w() = 1.0;\r\n  _attitudeEstimate.x() = 0.0;\r\n  _attitudeEstimate.y() = 0.0;\r\n  _attitudeEstimate.z() = 0.0;\r\n\r\n  if (writeParams) {\r\n    ROS_INFO(\"Writing parameters...\");\r\n    //System calls are so dirty, there has to be a better way to do this\r\n    system(\"rosparam dump /data/app/bluefin/opt/sandshark/share/sandshark_apps/config/motion.yaml /motion\");\r\n    ROS_INFO(\"Done\");\r\n  }\r\n}\r\n\r\nvoid MotionDriver::cleanup() {\r\n  ROS_INFO(\"Task init! Motion cleanup\");\r\n  fflush( stdout);\r\n  for (unsigned int i = 0; i < _sensorList.size(); i++) {\r\n    ASensorEventQueue_disableSensor(_queueList[i], _sensorList[i]);\r\n    ASensorManager_destroyEventQueue(_sensorManager, _queueList[i]);\r\n  }\r\n\r\n  _sensorList.clear();\r\n  _queueList.clear();\r\n  ROS_INFO(\"Task init! Cleanup done\");\r\n  fflush( stdout);\r\n}\r\n\r\nbool MotionDriver::ahrsEnabled(double magMagnitude) {\r\n  //replace AHRS with IMU filter\r\n  if (_imuFilterEnabled) {\r\n    return false;\r\n  }\r\n\r\n  //Switch to IMU filter after first Beta\r\n  if (_imuFilterAfterBeta) {\r\n    double curTime = ros::WallTime::now().toSec();\r\n    if ((curTime - _start_time) > _firstBetaDuration) {\r\n      return false;\r\n    }\r\n  }\r\n\r\n  if (_imuFilterWithBadMag) {\r\n    if ((magMagnitude < _minGoodMag) || (magMagnitude > _maxGoodMag)) {\r\n      return false;\r\n    }\r\n  }\r\n\r\n  return true;\r\n}\r\n\r\nbool MotionDriver::doRun() {\r\n  static struct timespec current;\r\n  static double magX, magY, magZ, accelX, accelY, accelZ, gyroX, gyroY, gyroZ;\r\n  //A failure state of the magnetometer is that it will lock up and return\r\n  //the same value forever, so we check for that and fail if it does\r\n  static double lastMagX = 0, lastMagY = 0, lastMagZ = 0;\r\n  static int magLockedCount = 0;\r\n  static double o_x, o_y, o_z;\r\n  static int magStat = 0, accelStat = 0, gyroStat = 0, count = 0;\r\n  static Vector3d accelTemp, magTemp, accelNormalized, magNormalized;\r\n  static bool haveMag = false, haveAccel = false, haveGyro = false, haveRotation = false;\r\n  static Matrix<double, 3, 3> rotation;\r\n  static Quaternion<double> attitudeConj;\r\n  static Quaternion<double> magQuaternion;\r\n  static Quaternion<double> gyroQuaternion, gyroError;\r\n  static Quaternion<double> hQuaternion;\r\n  static Quaternion<double> bQuaternion;\r\n  static Matrix<double, 4, 1> stepVector;\r\n  static Quaternion<double> stepQuaternion;\r\n  static Matrix<double, 6, 4> J;\r\n  static Matrix<double, 6, 1> F;\r\n  static Matrix<double, 3, 4> imuJ;\r\n  static Matrix<double, 3, 1> imuF;\r\n  static double prev_elapsed = 0.0;\r\n  static Vector4d rateOfChange;\r\n  static char sendBuf[1400];\r\n  static int noEventsCount = 0;\r\n\r\n  clock_gettime( CLOCK_REALTIME, &current);\r\n  //Assume start nsec is zero for simplicity\r\n  double elapsed = (current.tv_sec - _start.tv_sec) + ((double) current.tv_nsec) / 1000000000;\r\n  if (ASensorEventQueue_hasEvents(_queueList[0]) > 0) {  // if the master (first) sensor has new data\r\n    for (unsigned int i = 0; i < _queueList.size(); ++i) {\r\n      int ret = 0;\r\n      int eventCount = 0;\r\n      while ((ret = ASensorEventQueue_getEvents(_queueList[i], &_eventList[i], 1)) > 0) { //get all pending events\r\n        //WARNING: do NOT put debug messages in here. The latency\r\n        //will cause the motion driver to fail to get message\r\n        //fast enough and will get stuck in an infinite loop\r\n\r\n        clock_gettime( CLOCK_REALTIME, &current);\r\n        double tempElapsed = (current.tv_sec - _start.tv_sec) + ((double) current.tv_nsec) / 1000000000.0;\r\n        double lastEvent = (tempElapsed - elapsed);\r\n        if (lastEvent > 2.0) { //No Sensor Data for 2 secs\r\n          ROS_WARN(\"Getting current events for more than two seconds, driver failing!\");\r\n          return false;\r\n        }\r\n\r\n        eventCount += ret;\r\n      }\r\n\r\n      //make sure we got a new value\r\n      if (ret < 0) {\r\n        ROS_WARN(\"Error from android sensor manager (%d)\", ret);\r\n        setErrorMessage(\"Error from android sensor manager\");\r\n        noEventsCount = 0;\r\n        //TODO: should we actually be failing here?\r\n        return false;\r\n      } else if (eventCount == 0) {\r\n        noEventsCount++;\r\n        if (noEventsCount > 5) {\r\n          ROS_WARN(\"No events received from sensor manager!\");\r\n          setErrorMessage(\"Error from android sensor manager\");\r\n          noEventsCount = 0;\r\n          //TODO: should we actually be failing here?\r\n          return false;\r\n        }\r\n      } else {\r\n        noEventsCount = 0;\r\n        struct sysinfo info;\r\n        int64_t uptime = 0;\r\n        if (sysinfo(&info) == 0) {\r\n          uptime = info.uptime;\r\n        }\r\n\r\n        float *d = _eventList[i].data;\r\n        switch (_eventList[i].type) {\r\n        case ASENSOR_TYPE_ACCELEROMETER:\r\n          if ((_eventList[i].timestamp / 1000000000) - uptime > 2) {\r\n            ROS_WARN(\"Processing old accelerometer data from sensor!!\");\r\n          }\r\n          accelX = d[0];\r\n          accelY = d[1];\r\n          accelZ = d[2];\r\n          accelStat = _eventList[i].acceleration.status;\r\n          accelTemp(0) = accelX;\r\n          accelTemp(1) = accelY;\r\n          accelTemp(2) = accelZ;\r\n          if (_firstRun) {\r\n            _gravityAccel = accelTemp;\r\n          }\r\n          haveAccel = true;\r\n          accelTemp -= _accelOffset;\r\n          _correctedAccel = accelTemp;\r\n          accelTemp(0) = _correctedAccel(0) / _accelScaling(0);\r\n          accelTemp(1) = _correctedAccel(1) / _accelScaling(1);\r\n          accelTemp(2) = _correctedAccel(2) / _accelScaling(2);\r\n          _correctedAccel = accelTemp * 9.81;\r\n          break;\r\n        case ASENSOR_TYPE_MAGNETIC_FIELD:\r\n          if ((_eventList[i].timestamp / 1000000000) - uptime > 2) {\r\n            ROS_WARN(\"Processing old magnetometer data from sensor!!\");\r\n          }\r\n          magX = d[0];\r\n          magY = d[1];\r\n          magZ = d[2];\r\n          if (magX == lastMagX && magY == lastMagY && magZ == lastMagZ) {\r\n            magLockedCount++;\r\n            if (magLockedCount > 10) {\r\n              //Something bad is happening! mag has locked up\r\n              //Restart so we can get it unlocked\r\n              ROS_WARN(\"Magnetometer has locked up!\");\r\n              setErrorMessage(\"Magnetometer has locked up!\");\r\n              return false;\r\n            }\r\n          } else {\r\n            magLockedCount = 0;\r\n          }\r\n          lastMagX = magX;\r\n          lastMagY = magY;\r\n          lastMagZ = magZ;\r\n\r\n          magStat = _eventList[i].magnetic.status;\r\n          haveMag = true;\r\n          magTemp(0) = magX;\r\n          magTemp(1) = magY;\r\n          magTemp(2) = magZ;\r\n          magTemp -= _magOffset;\r\n          //_correctedMag = magTemp;\r\n          _correctedMag = magTemp.transpose() * _magAdjust;\r\n          magTemp(0) = _correctedMag(0) / _magScaling(0);\r\n          magTemp(1) = _correctedMag(1) / _magScaling(1);\r\n          magTemp(2) = _correctedMag(2) / _magScaling(2);\r\n          _correctedMag = magTemp.transpose() * _magAdjust.transpose();\r\n          break;\r\n        case ASENSOR_TYPE_GYROSCOPE:\r\n          if ((_eventList[i].timestamp / 1000000000) - uptime > 2) {\r\n            ROS_WARN(\"Processing old gyroscope data from sensor!!\");\r\n          }\r\n          gyroX = d[0];\r\n          gyroY = d[1];\r\n          gyroZ = d[2];\r\n          gyroStat = _eventList[i].vector.status;\r\n          haveGyro = true;\r\n          break;\r\n        case 11:\r\n          o_x = d[0];\r\n          o_y = d[1];\r\n          o_z = d[2];\r\n          //                    o_w = d[3];\r\n          haveRotation = true;\r\n          break;\r\n        }\r\n      }\r\n    }\r\n\r\n    if (haveMag && haveAccel && haveGyro) {\r\n\r\n      _rawMsg.accel_x = accelX;\r\n      _rawMsg.accel_y = accelY;\r\n      _rawMsg.accel_z = accelZ;\r\n      _rawMsg.accel_status = accelStat;\r\n\r\n      _rawMsg.mag_x = magX;\r\n      _rawMsg.mag_y = magY;\r\n      _rawMsg.mag_z = magZ;\r\n      _rawMsg.mag_status = magStat;\r\n\r\n      _rawMsg.gyro_x = gyroX;\r\n      _rawMsg.gyro_y = gyroY;\r\n      _rawMsg.gyro_z = gyroZ;\r\n      _rawMsg.gyro_status = gyroStat;\r\n\r\n      _rawPub.publish(_rawMsg);\r\n\r\n      _gravityAccel = _alpha * _gravityAccel + (1 - _alpha) * _correctedAccel;\r\n      _linearAccel = _correctedAccel - _gravityAccel;\r\n\r\n      _correctedMsg.timestamp = current.tv_sec + ((double) current.tv_nsec) / 1000000000.0;\r\n      _correctedMsg.accel_x = _correctedAccel(0);\r\n      _correctedMsg.accel_y = _correctedAccel(1);\r\n      _correctedMsg.accel_z = _correctedAccel(2);\r\n      _correctedMsg.linear_x = _linearAccel(0);\r\n      _correctedMsg.linear_y = _linearAccel(1);\r\n      _correctedMsg.linear_z = _linearAccel(2);\r\n      _correctedMsg.gravity_x = _gravityAccel(0);\r\n      _correctedMsg.gravity_y = _gravityAccel(1);\r\n      _correctedMsg.gravity_z = _gravityAccel(2);\r\n      _correctedMsg.accel_status = accelStat;\r\n\r\n      _correctedMsg.mag_x = _correctedMag(0);\r\n      _correctedMsg.mag_y = _correctedMag(1);\r\n      _correctedMsg.mag_z = _correctedMag(2);\r\n      _correctedMsg.mag_status = magStat;\r\n\r\n      _correctedMsg.gyro_x = gyroX;\r\n      _correctedMsg.gyro_y = gyroY;\r\n      _correctedMsg.gyro_z = gyroZ;\r\n      _correctedMsg.gyro_status = gyroStat;\r\n\r\n      _correctedPub.publish(_correctedMsg);\r\n\r\n      accelNormalized = _gravityAccel / _gravityAccel.norm();\r\n      magNormalized = _correctedMag / _correctedMag.norm();\r\n\r\n      if (ahrsEnabled(_correctedMag.norm())) {\r\n        magQuaternion.w() = 0.0;\r\n        magQuaternion.x() = magNormalized.x();\r\n        magQuaternion.y() = magNormalized.y();\r\n        magQuaternion.z() = magNormalized.z();\r\n\r\n        hQuaternion = _attitudeEstimate * (magQuaternion * _attitudeEstimate.conjugate());\r\n        bQuaternion.w() = 0.0;\r\n        bQuaternion.x() = sqrt(hQuaternion.x() * hQuaternion.x() + hQuaternion.y() * hQuaternion.y());\r\n        bQuaternion.y() = 0.0;\r\n        bQuaternion.z() = hQuaternion.z();\r\n\r\n        F[0] = 2.0 * (_attitudeEstimate.x() * _attitudeEstimate.z() - _attitudeEstimate.w() * _attitudeEstimate.y())\r\n            - accelNormalized.x();\r\n        F[1] = 2.0 * (_attitudeEstimate.w() * _attitudeEstimate.x() + _attitudeEstimate.y() * _attitudeEstimate.z())\r\n            - accelNormalized.y();\r\n        F[2] = 2.0\r\n            * (0.5 - _attitudeEstimate.x() * _attitudeEstimate.x() - _attitudeEstimate.y() * _attitudeEstimate.y())\r\n            - accelNormalized.z();\r\n        F[3] = 2.0 * bQuaternion.x()\r\n            * (0.5 - _attitudeEstimate.y() * _attitudeEstimate.y() - _attitudeEstimate.z() * _attitudeEstimate.z())\r\n            + 2.0 * bQuaternion.z()\r\n                * (_attitudeEstimate.x() * _attitudeEstimate.z() - _attitudeEstimate.w() * _attitudeEstimate.y())\r\n            - magNormalized.x();\r\n        F[4] = 2.0 * bQuaternion.x()\r\n            * (_attitudeEstimate.x() * _attitudeEstimate.y() - _attitudeEstimate.w() * _attitudeEstimate.z())\r\n            + 2.0 * bQuaternion.z()\r\n                * (_attitudeEstimate.w() * _attitudeEstimate.x() + _attitudeEstimate.y() * _attitudeEstimate.z())\r\n            - magNormalized.y();\r\n        F[5] = 2.0 * bQuaternion.x()\r\n            * (_attitudeEstimate.w() * _attitudeEstimate.y() + _attitudeEstimate.x() * _attitudeEstimate.z())\r\n            + 2.0 * bQuaternion.z()\r\n                * (0.5 - _attitudeEstimate.x() * _attitudeEstimate.x() - _attitudeEstimate.y() * _attitudeEstimate.y())\r\n            - magNormalized.z();\r\n\r\n        J(0, 0) = -2.0 * _attitudeEstimate.y();\r\n        J(0, 1) = 2.0 * _attitudeEstimate.z();\r\n        J(0, 2) = -2.0 * _attitudeEstimate.w();\r\n        J(0, 3) = 2.0 * _attitudeEstimate.x();\r\n        J(1, 0) = 2.0 * _attitudeEstimate.x();\r\n        J(1, 1) = 2.0 * _attitudeEstimate.w();\r\n        J(1, 2) = 2.0 * _attitudeEstimate.z();\r\n        J(1, 3) = 2.0 * _attitudeEstimate.y();\r\n        J(2, 0) = 0.0;\r\n        J(2, 1) = -4.0 * _attitudeEstimate.x();\r\n        J(2, 2) = -4.0 * _attitudeEstimate.y();\r\n        J(2, 3) = 0.0;\r\n        J(3, 0) = -2.0 * bQuaternion.z() * _attitudeEstimate.y();\r\n        J(3, 1) = 2.0 * bQuaternion.z() * _attitudeEstimate.z();\r\n        J(3, 2) = -4.0 * bQuaternion.x() * _attitudeEstimate.y() - 2.0 * bQuaternion.z() * _attitudeEstimate.w();\r\n        J(3, 3) = -4.0 * bQuaternion.x() * _attitudeEstimate.z() + 2.0 * bQuaternion.z() * _attitudeEstimate.x();\r\n        J(4, 0) = -2.0 * bQuaternion.x() * _attitudeEstimate.z() + 2.0 * bQuaternion.z() * _attitudeEstimate.x();\r\n        J(4, 1) = 2.0 * bQuaternion.x() * _attitudeEstimate.y() + 2.0 * bQuaternion.z() * _attitudeEstimate.w();\r\n        J(4, 2) = 2.0 * bQuaternion.x() * _attitudeEstimate.x() + 2.0 * bQuaternion.z() * _attitudeEstimate.z();\r\n        J(4, 3) = -2.0 * bQuaternion.x() * _attitudeEstimate.w() + 2.0 * bQuaternion.z() * _attitudeEstimate.y();\r\n        J(5, 0) = 2.0 * bQuaternion.x() * _attitudeEstimate.y();\r\n        J(5, 1) = 2.0 * bQuaternion.x() * _attitudeEstimate.z() - 4.0 * bQuaternion.z() * _attitudeEstimate.x();\r\n        J(5, 2) = 2.0 * bQuaternion.x() * _attitudeEstimate.w() - 4.0 * bQuaternion.z() * _attitudeEstimate.y();\r\n        J(5, 3) = 2.0 * bQuaternion.x() * _attitudeEstimate.x();\r\n\r\n        stepVector = (J.transpose() * F);\r\n        stepVector.normalize();\r\n      } else {\r\n        imuF[0] = 2.0 * (_attitudeEstimate.x() * _attitudeEstimate.z() - _attitudeEstimate.w() * _attitudeEstimate.y())\r\n            - accelNormalized.x();\r\n        imuF[1] = 2.0 * (_attitudeEstimate.w() * _attitudeEstimate.x() + _attitudeEstimate.y() * _attitudeEstimate.z())\r\n            - accelNormalized.y();\r\n        imuF[2] = 2.0\r\n            * (0.5 - _attitudeEstimate.x() * _attitudeEstimate.x() - _attitudeEstimate.y() * _attitudeEstimate.y())\r\n            - accelNormalized.z();\r\n\r\n        imuJ(0, 0) = -2.0 * _attitudeEstimate.y();\r\n        imuJ(0, 1) = 2.0 * _attitudeEstimate.z();\r\n        imuJ(0, 2) = -2.0 * _attitudeEstimate.w();\r\n        imuJ(0, 3) = 2.0 * _attitudeEstimate.x();\r\n        imuJ(1, 0) = 2.0 * _attitudeEstimate.x();\r\n        imuJ(1, 1) = 2.0 * _attitudeEstimate.w();\r\n        imuJ(1, 2) = 2.0 * _attitudeEstimate.z();\r\n        imuJ(1, 3) = 2.0 * _attitudeEstimate.y();\r\n        imuJ(2, 0) = 0.0;\r\n        imuJ(2, 1) = -4.0 * _attitudeEstimate.x();\r\n        imuJ(2, 2) = -4.0 * _attitudeEstimate.y();\r\n        imuJ(2, 3) = 0.0;\r\n\r\n        stepVector = (imuJ.transpose() * imuF);\r\n        stepVector.normalize();\r\n      }\r\n      stepQuaternion.w() = stepVector[0];\r\n      stepQuaternion.x() = stepVector[1];\r\n      stepQuaternion.y() = stepVector[2];\r\n      stepQuaternion.z() = stepVector[3];\r\n      gyroError = (_attitudeEstimate.conjugate() * stepQuaternion);\r\n\r\n      double timestep = (elapsed - prev_elapsed);\r\n      if (timestep < 0.0 || timestep > 2.0) {\r\n        ROS_INFO(\"\\ntime %f\\n\", timestep);\r\n      }\r\n      double curZeta = _zeta;\r\n      double curTime = ros::WallTime::now().toSec();\r\n      if ((curTime - _start_time) < _firstBetaDuration) {\r\n        curZeta = 0.0;\r\n      }\r\n\r\n      _gyroBiasX += 2.0 * gyroError.x() * timestep * curZeta;\r\n      _gyroBiasY += 2.0 * gyroError.y() * timestep * curZeta;\r\n      _gyroBiasZ += 2.0 * gyroError.z() * timestep * curZeta;\r\n      gyroQuaternion.w() = 0.0;\r\n      gyroQuaternion.x() = gyroX - _gyroBiasX;\r\n      gyroQuaternion.y() = gyroY - _gyroBiasY;\r\n      gyroQuaternion.z() = gyroZ - _gyroBiasZ;\r\n\r\n      _rCQuaternion = (_attitudeEstimate * gyroQuaternion);\r\n      rateOfChange[0] = _rCQuaternion.w();\r\n      rateOfChange[1] = _rCQuaternion.x();\r\n      rateOfChange[2] = _rCQuaternion.y();\r\n      rateOfChange[3] = _rCQuaternion.z();\r\n\r\n      rateOfChange *= 0.5;\r\n      if ((curTime - _start_time) < _firstBetaDuration) {\r\n        rateOfChange -= _firstBeta * stepVector.transpose();\r\n      } else {\r\n        rateOfChange -= _beta * stepVector.transpose();\r\n      }\r\n\r\n      _attitudeEstimate.w() += rateOfChange[0] * timestep;\r\n      _attitudeEstimate.x() += rateOfChange[1] * timestep;\r\n      _attitudeEstimate.y() += rateOfChange[2] * timestep;\r\n      _attitudeEstimate.z() += rateOfChange[3] * timestep;\r\n      _attitudeEstimate.normalize();\r\n\r\n      _orientQuaternionMsg.w = _attitudeEstimate.w();\r\n      _orientQuaternionMsg.x = _attitudeEstimate.x();\r\n      _orientQuaternionMsg.y = _attitudeEstimate.y();\r\n      _orientQuaternionMsg.z = _attitudeEstimate.z();\r\n\r\n      publishEulerAngles();\r\n      publishDebug();\r\n      _orientQuaternionPub.publish(_orientQuaternionMsg);\r\n\r\n      if (_sendUDP && (count % 10 == 0)) {\r\n        if (_sendAndroidQuaternion) {\r\n          if (haveRotation) {\r\n            snprintf(&sendBuf[0], sizeof(sendBuf), \"%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f\",\r\n                ros::WallTime::now().toSec(), accelX, accelY, accelZ, gyroX, gyroY, gyroZ, magX, magY, magZ,\r\n                _attitudeEstimate.w(), _attitudeEstimate.x(), _attitudeEstimate.y(), _attitudeEstimate.z(),\r\n                _orientMsg.yaw, _orientMsg.roll, _orientMsg.pitch,\r\n                sqrt(1.0 - ((o_x * o_x) + (o_y * o_y) + (o_z * o_z))), o_x, o_y, o_z);\r\n\r\n          }\r\n        } else {\r\n          snprintf(&sendBuf[0], sizeof(sendBuf), \"%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f\",\r\n              ros::WallTime::now().toSec(),\r\n              //correctedAccel(0), correctedAccel(1), correctedAccel(2),\r\n              accelX, accelY, accelZ, gyroX, gyroY, gyroZ,\r\n              //correctedMag(0), correctedMag(1), correctedMag(2),\r\n              magX, magY, magZ, _attitudeEstimate.w(), _attitudeEstimate.x(), _attitudeEstimate.y(),\r\n              _attitudeEstimate.z(),\r\n              //SEq_1, SEq_2, SEq_3, SEq_4,\r\n              _orientMsg.yaw, _orientMsg.roll, _orientMsg.pitch);\r\n        }\r\n        sendBuf[sizeof(sendBuf) - 1] = '\\0';\r\n        int ret = sendto(_sendSocket, &sendBuf[0], strlen(sendBuf), 0, (struct sockaddr *) &_sendAddrStruct,\r\n            sizeof(struct sockaddr));\r\n        if (ret < 0) {\r\n          fprintf( stderr, \"SendTo failed ret %d - %d:%s\\n\", ret, errno, strerror( errno));\r\n        }\r\n      }\r\n      prev_elapsed = elapsed;\r\n      count++;\r\n      haveMag = false;\r\n      haveAccel = false;\r\n      haveGyro = false;\r\n    }\r\n  } else {\r\n    double lastEvent = (elapsed - prev_elapsed);\r\n    if (lastEvent > 2.0) { //No Sensor Data for 2 secs\r\n\r\n      elapsed = 0.0;\r\n      prev_elapsed = 0.0;\r\n      return false;\r\n    }\r\n    _needSleep = true;\r\n  }\r\n\r\n  _firstRun = false;\r\n  return true;\r\n}\r\n\r\nvoid MotionDriver::handleSleep() {\r\n  if (_needSleep) {\r\n    usleep(10000);\r\n  }\r\n  _needSleep = false;\r\n}\r\n\r\nvoid MotionDriver::publishDebug() {\r\n  //publish gyro bias and the rCQuaternion\r\n\r\n  _orientDebugMsg.gyro_bias_x = _gyroBiasX;\r\n  _orientDebugMsg.gyro_bias_y = _gyroBiasY;\r\n  _orientDebugMsg.gyro_bias_z = _gyroBiasZ;\r\n\r\n  _orientDebugMsg.rc_x = _rCQuaternion.x();\r\n  _orientDebugMsg.rc_y = _rCQuaternion.y();\r\n  _orientDebugMsg.rc_z = _rCQuaternion.z();\r\n  _orientDebugMsg.rc_w = _rCQuaternion.w();\r\n\r\n  _orientDebugPub.publish(_orientDebugMsg);\r\n}\r\n\r\nvoid MotionDriver::publishEulerAngles() {\r\n\r\n  double froll = 0.0;\r\n  double fpitch = 0.0;\r\n  double fazimuth = 0.0;\r\n\r\n  Matrix3d qrotation = _attitudeEstimate.matrix();\r\n  //Rotate into vehicle orientation\r\n  Matrix3d rotation = qrotation * AngleAxisd(0.5 * M_PI, Vector3d::UnitY());\r\n\r\n  //rotation matrix to euler, pitch and azimuth are inverted\r\n  froll = atan2(rotation(2, 1), rotation(2, 2));\r\n  fpitch = asin(rotation(2, 0));\r\n  fazimuth = atan2(rotation(1, 0), rotation(0, 0));\r\n\r\n  froll *= 180.0 / M_PI;\r\n  fpitch *= 180.0 / M_PI;\r\n  fazimuth *= 180.0 / M_PI;\r\n  if (fazimuth < 0.0) {\r\n    fazimuth += 360.0;\r\n  }\r\n\r\n  if (fazimuth > 360.0) {\r\n    fazimuth -= 360.0;\r\n  }\r\n\r\n  _orientMsg.roll = froll;\r\n  _orientMsg.yaw = fazimuth;\r\n  _orientMsg.pitch = fpitch;\r\n\r\n  _orientPub.publish(_orientMsg);\r\n\r\n}\r\n\r\n}\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n  bluefin::sandshark::MotionDriver md;\r\n  return bluefin::sandshark::app_main((bluefin::sandshark::TaskBase&) md, argc, argv);\r\n}\r\n", "meta": {"hexsha": "15110aabac771f4b2e3b11e6ab1516963fd6a8c2", "size": 33937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vehicle/ros/src/sandshark_drivers/motion/motion_node.cpp", "max_stars_repo_name": "slicht-uri/Sandshark-Beta-Lab-", "max_stars_repo_head_hexsha": "6cff36b227b49b776d13187c307e648d2a52bdae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vehicle/ros/src/sandshark_drivers/motion/motion_node.cpp", "max_issues_repo_name": "slicht-uri/Sandshark-Beta-Lab-", "max_issues_repo_head_hexsha": "6cff36b227b49b776d13187c307e648d2a52bdae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vehicle/ros/src/sandshark_drivers/motion/motion_node.cpp", "max_forks_repo_name": "slicht-uri/Sandshark-Beta-Lab-", "max_forks_repo_head_hexsha": "6cff36b227b49b776d13187c307e648d2a52bdae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-18T06:25:14.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-18T06:25:14.000Z", "avg_line_length": 35.610703043, "max_line_length": 178, "alphanum_fraction": 0.6095412087, "num_tokens": 9841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.20808710711163644}}
{"text": "#include \"solver.h\"\n\n#include <boost/functional/hash.hpp>\n#include <boost/format.hpp>\n#include \"../parallel.h\"\n#include \"../std.h\"\n#include \"../time.h\"\n#include \"../wavefunction/wavefunction.h\"\n#include \"davidson.h\"\n\nDet Solver::generate_hf_det() {\n  Det det;\n  for (size_t i = 0; i < n_up; i++) det.up.set_orb(i, true);\n  for (size_t i = 0; i < n_dn; i++) det.dn.set_orb(i, true);\n  return det;\n}\n\nvoid Solver::variation(const double eps_var) {\n  const double THRESHOLD = 1.0e-6;\n\n  // Setup HF or existing wf as initial wf and evaluate energy.\n  if (wf.size() == 0) {\n    const Det& det_hf = generate_hf_det();\n    wf.append_term(det_hf, 1.0);\n    energy_hf = energy_var = hamiltonian(det_hf, det_hf);\n    if (Parallel::is_master()) printf(\"HF energy: %#.15g Ha\\n\", energy_hf);\n  }\n\n  std::unordered_set<OrbitalsPair, boost::hash<OrbitalsPair>> var_dets_set;\n  std::list<Det> new_dets;\n  for (const auto& term : wf.get_terms()) var_dets_set.insert(term.det.encode());\n  double energy_var_new = 0.0;  // Ensures the first iteration will run.\n  size_t n_iter = 0;\n  converged = false;\n  while (!converged) {\n    Time::start(\"Variation: \" + std::to_string(n_iter));\n\n    for (const auto& term : wf.get_terms()) {\n      const auto& connected_dets = find_connected_dets(term.det, eps_var / fabs(term.coef));\n      for (const auto& new_det : connected_dets) {\n        const auto new_det_code = new_det.encode();\n        if (var_dets_set.count(new_det_code) == 0) {\n          var_dets_set.insert(new_det_code);\n          new_dets.push_back(new_det);\n        }\n      }\n    }\n\n    if (Parallel::is_master()) {\n      printf(\"New / total dets: %'zu / %'zu\\n\", new_dets.size(), var_dets_set.size());\n    }\n    Time::checkpoint(\"found new dets\");\n\n    for (const auto& new_det : new_dets) {\n      wf.append_term(new_det, 0.0);\n    }\n\n    energy_var_new = diagonalize(new_dets.size() > 0);\n    if (fabs(energy_var - energy_var_new) < THRESHOLD) converged = true;\n    energy_var = energy_var_new;\n    if (Parallel::is_master()) {\n      printf(\"Variation energy: %#.15g Ha\\n\", energy_var);\n      printf(\"Correlation energy (variation): %#.15g Ha\\n\", energy_var - energy_hf);\n    }\n\n    new_dets.clear();\n\n    Time::end();\n    n_iter++;\n  }\n\n  if (Parallel::is_master()) {\n    printf(\"Final variation energy: %#.15g Ha\\n\", energy_var);\n    printf(\"Correlation energy (variation): %#.15g Ha\\n\", energy_var - energy_hf);\n  }\n}\n\ndouble Solver::diagonalize(const bool has_new_dets) {\n  std::vector<double> diagonal;\n  std::vector<double> initial_vector;\n  const size_t max_iterations = has_new_dets ? 5 : 10;\n  diagonal.reserve(wf.size());\n  initial_vector.reserve(wf.size());\n  for (const auto& term : wf.get_terms()) {\n    const auto& det = term.det;\n    diagonal.push_back(hamiltonian(det, det));\n    initial_vector.push_back(term.coef);\n  }\n\n  std::function<double(Det, Det)> hamiltonian_func =\n      std::bind(&Solver::hamiltonian, this, std::placeholders::_1, std::placeholders::_2);\n  HelperStrings helper_strings(hamiltonian_func);\n  helper_strings.setup(wf.get_dets());\n  Time::checkpoint(\"helper strings generated\");\n  std::function<std::vector<double>(std::vector<double>)> apply_hamiltonian_func =\n      std::bind(&Solver::apply_hamiltonian, this, std::placeholders::_1, helper_strings);\n\n  Davidson davidson(diagonal, apply_hamiltonian_func, wf.size());\n  if (Parallel::is_master()) davidson.set_verbose(true);\n  const size_t n_iter = davidson.diagonalize(initial_vector, max_iterations);\n  if (!has_new_dets && n_iter < max_iterations) converged = true;\n\n  const double energy_var = davidson.get_lowest_eigenvalue();\n  const auto& coefs_new = davidson.get_lowest_eigenvector();\n\n  wf.set_coefs(coefs_new);\n  wf.sort_by_coefs();\n\n  return energy_var;\n}\n\n#pragma omp declare reduction(      \\\n    vec_double_plus : std::vector < \\\n    double > : std::transform(      \\\n                 omp_out            \\\n                     .begin(), omp_out.end(), omp_in.begin(), omp_out.begin(), std::plus < double > ())) initializer(omp_priv = omp_orig)\n\nstd::vector<double> Solver::apply_hamiltonian(\n    const std::vector<double>& vec, HelperStrings& helper_strings) {\n  const std::size_t n_dets = vec.size();\n  const size_t proc_id = Parallel::get_id();\n  const size_t n_procs = Parallel::get_n();\n  std::vector<double> res(n_dets, 0.0);\n\n  const auto& dets = wf.get_dets();\n\n#pragma omp parallel for reduction(vec_double_plus : res) schedule(dynamic, 10)\n  for (size_t i = proc_id; i < n_dets; i += n_procs) {\n    const auto& connections = helper_strings.find_connections(i);\n    for (const auto connection : connections) {\n      const size_t j = connection.first;\n      const double H_ij = connection.second;\n      res[i] += H_ij * vec[j];\n      if (i != j) {\n        res[j] += H_ij * vec[i];\n      }\n    }\n  }\n\n  Parallel::reduce_to_sum_vector(res);\n  Time::checkpoint(\"hamiltonian applied\");\n\n  return res;\n}\n\n\nvoid Solver::save_variation_result(const std::string& filename) {\n  if (Parallel::is_master()) {\n    std::ofstream var_file;\n    var_file.open(filename);\n    var_file << boost::format(\"%.17g %.17g\\n\") % energy_hf % energy_var;\n    var_file << boost::format(\"%d %d %d\\n\") % n_up % n_dn % wf.size();\n    for (const auto& term : wf.get_terms()) {\n      var_file << boost::format(\"%.17g\\n\") % term.coef;\n      var_file << term.det.up << std::endl << term.det.dn << std::endl;\n    }\n    var_file.close();\n    printf(\"Variation result saved to: %s\\n\", filename.c_str());\n  }\n}\n\n\nbool Solver::load_variation_result(const std::string& filename) {\n  std::ifstream var_file;\n  size_t n_dets;\n  Orbital orb_id;\n  double coef;\n  var_file.open(filename);\n  if (!var_file.is_open()) return false;  // Does not exist.\n  var_file >> energy_hf >> energy_var;\n  var_file >> n_up >> n_dn >> n_dets;\n  wf.clear();\n  for (std::size_t i = 0; i < n_dets; i++) {\n    var_file >> coef;\n    Det det;\n    for (std::size_t j = 0; j < n_up; j++) {\n      var_file >> orb_id;\n      det.up.set_orb(orb_id, true);\n    }\n    for (std::size_t j = 0; j < n_dn; j++) {\n      var_file >> orb_id;\n      det.dn.set_orb(orb_id, true);\n    }\n    wf.append_term(det, coef);\n  }\n  var_file.close();\n  if (Parallel::is_master()) {\n    printf(\"Loaded %'zu dets from: %s\\n\", n_dets, filename.c_str());\n    printf(\"HF energy: %#.15g Ha\\n\", energy_hf);\n    printf(\"Variation energy: %#.15g Ha\\n\", energy_var);\n    printf(\"Correlation energy (variation): %#.15g Ha\\n\", energy_var - energy_hf);\n  }\n  return true;\n}", "meta": {"hexsha": "9a7fff93c0b8fc3c7c53301700143fd8bd5cf633", "size": 6466, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/solver/solver.cc", "max_stars_repo_name": "jl2922/hci-17c", "max_stars_repo_head_hexsha": "401a04d67c1d37e83dacc73bebeb8561c13bd4b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-08-21T13:55:00.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-21T13:55:00.000Z", "max_issues_repo_path": "src/solver/solver.cc", "max_issues_repo_name": "jl2922/hci-17c", "max_issues_repo_head_hexsha": "401a04d67c1d37e83dacc73bebeb8561c13bd4b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solver/solver.cc", "max_forks_repo_name": "jl2922/hci-17c", "max_forks_repo_head_hexsha": "401a04d67c1d37e83dacc73bebeb8561c13bd4b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3298969072, "max_line_length": 137, "alphanum_fraction": 0.649396845, "num_tokens": 1826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.20808710711163642}}
{"text": "// Copyright (C) 2011-2012 by the BEM++ Authors\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n#include \"bempp/common/config_trilinos.hpp\"\n\n#ifdef WITH_TRILINOS\n\n#include \"default_iterative_solver.hpp\"\n\n#include \"belos_solver_wrapper.hpp\"\n#include \"solution.hpp\"\n#include \"blocked_solution.hpp\"\n#include \"../assembly/abstract_boundary_operator.hpp\"\n#include \"../assembly/abstract_boundary_operator_pseudoinverse.hpp\"\n#include \"../assembly/blocked_boundary_operator.hpp\"\n#include \"../assembly/boundary_operator.hpp\"\n#include \"../assembly/context.hpp\"\n#include \"../assembly/discrete_boundary_operator.hpp\"\n#include \"../assembly/discrete_boundary_operator_composition.hpp\"\n#include \"../assembly/identity_operator.hpp\"\n#include \"../assembly/vector.hpp\"\n#include \"../fiber/explicit_instantiation.hpp\"\n#include \"../space/space.hpp\"\n\n#include <Teuchos_RCPBoostSharedPtrConversions.hpp>\n#include <Thyra_DefaultSpmdVectorSpace.hpp>\n\n#include <boost/make_shared.hpp>\n#include <boost/variant.hpp>\n\n#include <tbb/task_scheduler_init.h>\n\nnamespace Bempp {\n\ntemplate <typename ValueType>\nTeuchos::RCP<Thyra::DefaultSpmdVector<ValueType>>\nwrapInTrilinosVector(arma::Col<ValueType> &col) {\n  size_t size = col.n_rows;\n  Teuchos::ArrayRCP<ValueType> trilinosArray = Teuchos::arcp(\n      col.memptr(), 0 /* lowerOffset */, size, false /* doesn't own memory */);\n  typedef Thyra::DefaultSpmdVector<ValueType> TrilinosVector;\n  return Teuchos::RCP<TrilinosVector>(\n      new TrilinosVector(Thyra::defaultSpmdVectorSpace<ValueType>(size),\n                         trilinosArray, 1 /* stride */));\n}\n\n/** \\cond HIDDEN_INTERNAL */\n\ntemplate <typename BasisFunctionType, typename ResultType>\nstruct DefaultIterativeSolver<BasisFunctionType, ResultType>::Impl {\n\n  // Constructor for non-blocked operators\n  Impl(const BoundaryOperator<BasisFunctionType, ResultType> &op_,\n       ConvergenceTestMode::Mode mode_)\n      : op(op_), mode(mode_) {\n    typedef BoundaryOperator<BasisFunctionType, ResultType> BoundaryOp;\n    typedef Solver<BasisFunctionType, ResultType> Solver_;\n    const BoundaryOp &boundaryOp = boost::get<BoundaryOp>(op);\n    if (!boundaryOp.isInitialized())\n      throw std::invalid_argument(\"DefaultIterativeSolver::Impl::Impl(): \"\n                                  \"boundary operator must be initialized\");\n\n    if (mode == ConvergenceTestMode::TEST_CONVERGENCE_IN_DUAL_TO_RANGE) {\n      if (boundaryOp.domain()->globalDofCount() !=\n          boundaryOp.dualToRange()->globalDofCount())\n        throw std::invalid_argument(\"DefaultIterativeSolver::Impl::Impl(): \"\n                                    \"non-square system provided\");\n\n      solverWrapper.reset(new BelosSolverWrapper<ResultType>(\n          Teuchos::rcp<const Thyra::LinearOpBase<ResultType>>(\n              boundaryOp.weakForm())));\n    } else if (mode == ConvergenceTestMode::TEST_CONVERGENCE_IN_RANGE) {\n      if (boundaryOp.domain()->globalDofCount() !=\n          boundaryOp.range()->globalDofCount())\n        throw std::invalid_argument(\"DefaultIterativeSolver::Impl::Impl(): \"\n                                    \"non-square system provided\");\n\n      BoundaryOp id =\n          identityOperator(boundaryOp.context(), boundaryOp.range(),\n                           boundaryOp.range(), boundaryOp.dualToRange());\n      pinvId = pseudoinverse(id, boundaryOp.dualToRange());\n      // dualToRange could be anything here.\n      shared_ptr<DiscreteBoundaryOperator<ResultType>> totalBoundaryOp =\n          boost::make_shared<DiscreteBoundaryOperatorComposition<ResultType>>(\n              boost::get<BoundaryOp>(pinvId).weakForm(), boundaryOp.weakForm());\n      solverWrapper.reset(new BelosSolverWrapper<ResultType>(\n          Teuchos::rcp<const Thyra::LinearOpBase<ResultType>>(\n              totalBoundaryOp)));\n    } else\n      throw std::invalid_argument(\n          \"DefaultIterativeSolver::DefaultIterativeSolver(): \"\n          \"invalid convergence test mode\");\n  }\n\n  // Constructor for blocked operators\n  Impl(const BlockedBoundaryOperator<BasisFunctionType, ResultType> &op_,\n       ConvergenceTestMode::Mode mode_)\n      : op(op_), mode(mode_) {\n    typedef BlockedBoundaryOperator<BasisFunctionType, ResultType> BoundaryOp;\n    typedef Solver<BasisFunctionType, ResultType> Solver_;\n    const BoundaryOp &boundaryOp = boost::get<BoundaryOp>(op);\n\n    if (mode == ConvergenceTestMode::TEST_CONVERGENCE_IN_DUAL_TO_RANGE) {\n      if (boundaryOp.totalGlobalDofCountInDomains() !=\n          boundaryOp.totalGlobalDofCountInDualsToRanges())\n        throw std::invalid_argument(\"DefaultIterativeSolver::Impl::Impl(): \"\n                                    \"non-square system provided\");\n      solverWrapper.reset(new BelosSolverWrapper<ResultType>(\n          Teuchos::rcp<const Thyra::LinearOpBase<ResultType>>(\n              boundaryOp.weakForm())));\n    } else if (mode == ConvergenceTestMode::TEST_CONVERGENCE_IN_RANGE) {\n      if (boundaryOp.totalGlobalDofCountInDomains() !=\n          boundaryOp.totalGlobalDofCountInRanges())\n        throw std::invalid_argument(\"DefaultIterativeSolver::Impl::Impl(): \"\n                                    \"non-square system provided\");\n\n      // Construct a block-diagonal operator composed of pseudoinverses\n      // for appropriate spaces\n      BlockedOperatorStructure<BasisFunctionType, ResultType> pinvIdStructure;\n      size_t rowCount = boundaryOp.rowCount();\n      size_t columnCount = boundaryOp.columnCount();\n      for (size_t row = 0; row < rowCount; ++row) {\n        // Find the first non-zero block in row #row and retrieve its context\n        shared_ptr<const Context<BasisFunctionType, ResultType>> context;\n        for (int col = 0; col < columnCount; ++col)\n          if (boundaryOp.block(row, col).context()) {\n            context = boundaryOp.block(row, col).context();\n            break;\n          }\n        assert(context);\n\n        BoundaryOperator<BasisFunctionType, ResultType> id = identityOperator(\n            context, boundaryOp.range(row), boundaryOp.range(row),\n            boundaryOp.dualToRange(row));\n        pinvIdStructure.setBlock(row, row, pseudoinverse(id));\n      }\n      pinvId = BlockedBoundaryOperator<BasisFunctionType, ResultType>(\n          pinvIdStructure);\n\n      shared_ptr<DiscreteBoundaryOperator<ResultType>> totalBoundaryOp =\n          boost::make_shared<DiscreteBoundaryOperatorComposition<ResultType>>(\n              boost::get<BoundaryOp>(pinvId).weakForm(), boundaryOp.weakForm());\n      solverWrapper.reset(new BelosSolverWrapper<ResultType>(\n          Teuchos::rcp<const Thyra::LinearOpBase<ResultType>>(\n              totalBoundaryOp)));\n    } else\n      throw std::invalid_argument(\n          \"DefaultIterativeSolver::DefaultIterativeSolver(): \"\n          \"invalid convergence test mode\");\n  }\n\n  boost::variant<BoundaryOperator<BasisFunctionType, ResultType>,\n                 BlockedBoundaryOperator<BasisFunctionType, ResultType>> op;\n  ConvergenceTestMode::Mode mode;\n  boost::scoped_ptr<BelosSolverWrapper<ResultType>> solverWrapper;\n  boost::variant<BoundaryOperator<BasisFunctionType, ResultType>,\n                 BlockedBoundaryOperator<BasisFunctionType, ResultType>> pinvId;\n};\n\n/** \\endcond */\n\ntemplate <typename BasisFunctionType, typename ResultType>\nDefaultIterativeSolver<BasisFunctionType, ResultType>::DefaultIterativeSolver(\n    const BoundaryOperator<BasisFunctionType, ResultType> &boundaryOp,\n    ConvergenceTestMode::Mode mode)\n    : m_impl(new Impl(boundaryOp, mode)) {}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nDefaultIterativeSolver<BasisFunctionType, ResultType>::DefaultIterativeSolver(\n    const BlockedBoundaryOperator<BasisFunctionType, ResultType> &boundaryOp,\n    ConvergenceTestMode::Mode mode)\n    : m_impl(new Impl(boundaryOp, mode)) {}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nDefaultIterativeSolver<BasisFunctionType,\n                       ResultType>::~DefaultIterativeSolver() {}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid DefaultIterativeSolver<BasisFunctionType, ResultType>::setPreconditioner(\n    const Preconditioner<ResultType> &preconditioner) {\n  m_impl->solverWrapper->setPreconditioner(preconditioner.get());\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid DefaultIterativeSolver<BasisFunctionType, ResultType>::initializeSolver(\n    const Teuchos::RCP<Teuchos::ParameterList> &paramList) {\n  m_impl->solverWrapper->initializeSolver(paramList);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nvoid DefaultIterativeSolver<BasisFunctionType, ResultType>::initializeSolver(\n    const Teuchos::RCP<Teuchos::ParameterList> &paramList,\n    const Preconditioner<ResultType> &preconditioner) {\n  m_impl->solverWrapper->setPreconditioner(preconditioner.get());\n  m_impl->solverWrapper->initializeSolver(paramList);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nSolution<BasisFunctionType, ResultType>\nDefaultIterativeSolver<BasisFunctionType, ResultType>::solveImplNonblocked(\n    const GridFunction<BasisFunctionType, ResultType> &rhs) const {\n  typedef BoundaryOperator<BasisFunctionType, ResultType> BoundaryOp;\n  typedef typename ScalarTraits<ResultType>::RealType MagnitudeType;\n  typedef Thyra::MultiVectorBase<ResultType> TrilinosVector;\n\n  const BoundaryOp *boundaryOp = boost::get<BoundaryOp>(&m_impl->op);\n  if (!boundaryOp)\n    throw std::logic_error(\n        \"DefaultIterativeSolver::solve(): for solvers constructed \"\n        \"from a BlockedBoundaryOperator the other solve() overload \"\n        \"must be used\");\n  Solver<BasisFunctionType, ResultType>::checkConsistency(*boundaryOp, rhs,\n                                                          m_impl->mode);\n\n  // Construct rhs vector\n  Vector<ResultType> projectionsVector(\n      rhs.projections(boundaryOp->dualToRange()));\n  Teuchos::RCP<TrilinosVector> rhsVector;\n  if (m_impl->mode == ConvergenceTestMode::TEST_CONVERGENCE_IN_DUAL_TO_RANGE)\n    rhsVector = Teuchos::rcpFromRef(projectionsVector);\n  else {\n    const size_t size = boundaryOp->range()->globalDofCount();\n    rhsVector.reset(new Vector<ResultType>(size));\n    boost::get<BoundaryOp>(m_impl->pinvId).weakForm()->apply(\n        Thyra::NOTRANS, projectionsVector, rhsVector.ptr(), 1., 0.);\n  }\n\n  // Construct solution vector\n  arma::Col<ResultType> armaSolution(rhsVector->range()->dim());\n  armaSolution.fill(static_cast<ResultType>(0.));\n  Teuchos::RCP<TrilinosVector> solutionVector =\n      wrapInTrilinosVector(armaSolution);\n\n  // Get number of threads\n  Fiber::ParallelizationOptions parallelOptions =\n      boundaryOp->context()->assemblyOptions().parallelizationOptions();\n  int maxThreadCount = 1;\n  if (!parallelOptions.isOpenClEnabled()) {\n    if (parallelOptions.maxThreadCount() == ParallelizationOptions::AUTO)\n      maxThreadCount = tbb::task_scheduler_init::automatic;\n    else\n      maxThreadCount = parallelOptions.maxThreadCount();\n  }\n\n  // Solve\n  Thyra::SolveStatus<MagnitudeType> status;\n  {\n    // Initialize TBB threads here (to prevent their construction and\n    // destruction on every matrix-vector multiplication)\n    tbb::task_scheduler_init scheduler(maxThreadCount);\n    status = m_impl->solverWrapper->solve(Thyra::NOTRANS, *rhsVector,\n                                          solutionVector.ptr());\n  }\n\n  // Construct grid function and return\n  return Solution<BasisFunctionType, ResultType>(\n      GridFunction<BasisFunctionType, ResultType>(\n          boundaryOp->context(), boundaryOp->domain(), armaSolution),\n      status);\n}\n\ntemplate <typename BasisFunctionType, typename ResultType>\nBlockedSolution<BasisFunctionType, ResultType>\nDefaultIterativeSolver<BasisFunctionType, ResultType>::solveImplBlocked(\n    const std::vector<GridFunction<BasisFunctionType, ResultType>> &rhs) const {\n  typedef BlockedBoundaryOperator<BasisFunctionType, ResultType> BoundaryOp;\n  typedef typename ScalarTraits<ResultType>::RealType MagnitudeType;\n  typedef Thyra::MultiVectorBase<ResultType> TrilinosVector;\n\n  const BoundaryOp *boundaryOp = boost::get<BoundaryOp>(&m_impl->op);\n  if (!boundaryOp)\n    throw std::logic_error(\n        \"DefaultIterativeSolver::solve(): for solvers constructed \"\n        \"from a (non-blocked) BoundaryOperator the other solve() overload \"\n        \"must be used\");\n  std::vector<GridFunction<BasisFunctionType, ResultType>> canonicalRhs =\n      Solver<BasisFunctionType, ResultType>::canonicalizeBlockedRhs(\n          *boundaryOp, rhs, m_impl->mode);\n  // Shouldn't be needed, but better safe than sorry...\n  Solver<BasisFunctionType, ResultType>::checkConsistency(\n      *boundaryOp, canonicalRhs, m_impl->mode);\n\n  // Currently we only support convergence testing in space dual to range.\n\n  // Construct the right-hand-side vector\n  arma::Col<ResultType> armaProjections(\n      boundaryOp->totalGlobalDofCountInDualsToRanges());\n  for (size_t i = 0, start = 0; i < canonicalRhs.size(); ++i) {\n    const arma::Col<ResultType> &chunkProjections =\n        canonicalRhs[i].projections(boundaryOp->dualToRange(i));\n    size_t chunkSize = chunkProjections.n_rows;\n    armaProjections.rows(start, start + chunkSize - 1) = chunkProjections;\n    start += chunkSize;\n  }\n\n  Vector<ResultType> projectionsVector(armaProjections);\n  Teuchos::RCP<TrilinosVector> rhsVector;\n  if (m_impl->mode == ConvergenceTestMode::TEST_CONVERGENCE_IN_DUAL_TO_RANGE)\n    rhsVector = Teuchos::rcpFromRef(projectionsVector);\n  else {\n    const size_t rhsSize = boundaryOp->totalGlobalDofCountInRanges();\n    rhsVector.reset(new Vector<ResultType>(rhsSize));\n    boost::get<BoundaryOp>(m_impl->pinvId).weakForm()->apply(\n        Thyra::NOTRANS, projectionsVector, rhsVector.ptr(), 1., 0.);\n  }\n\n  // Initialize the solution vector\n  size_t solutionSize = 0;\n  for (size_t i = 0; i < canonicalRhs.size(); ++i)\n    solutionSize += boundaryOp->domain(i)->globalDofCount();\n  arma::Col<ResultType> armaSolution(solutionSize);\n  armaSolution.fill(static_cast<ResultType>(0.));\n  Teuchos::RCP<TrilinosVector> solutionVector =\n      wrapInTrilinosVector(armaSolution);\n\n  // Get context of the first non-empty operator\n  size_t rowCount = boundaryOp->rowCount();\n  shared_ptr<const Context<BasisFunctionType, ResultType>> context;\n  for (size_t row = 0; row < rowCount; ++row)\n    if (boundaryOp->block(row, 0).context()) {\n      context = boundaryOp->block(row, 0).context();\n      break;\n    }\n  assert(context);\n\n  // Get number of threads\n  Fiber::ParallelizationOptions parallelOptions =\n      context->assemblyOptions().parallelizationOptions();\n  int maxThreadCount = 1;\n  if (!parallelOptions.isOpenClEnabled()) {\n    if (parallelOptions.maxThreadCount() == ParallelizationOptions::AUTO)\n      maxThreadCount = tbb::task_scheduler_init::automatic;\n    else\n      maxThreadCount = parallelOptions.maxThreadCount();\n  }\n\n  // Solve\n  Thyra::SolveStatus<MagnitudeType> status;\n  {\n    // Initialize TBB threads here (to prevent their construction and\n    // destruction on every matrix-vector multiplication)\n    tbb::task_scheduler_init scheduler(maxThreadCount);\n    status = m_impl->solverWrapper->solve(Thyra::NOTRANS, *rhsVector,\n                                          solutionVector.ptr());\n  }\n\n  // Convert chunks of the solution vector into grid functions\n  std::vector<GridFunction<BasisFunctionType, ResultType>> solutionFunctions;\n  Solver<BasisFunctionType, ResultType>::constructBlockedGridFunction(\n      armaSolution, *boundaryOp, solutionFunctions);\n\n  // Return solution\n  return BlockedSolution<BasisFunctionType, ResultType>(solutionFunctions,\n                                                        status);\n}\n\nFIBER_INSTANTIATE_CLASS_TEMPLATED_ON_BASIS_AND_RESULT(DefaultIterativeSolver);\n\n} // namespace Bempp\n\n#endif // WITH_TRILINOS\n", "meta": {"hexsha": "1d6ac5616bfc3f1a7928243165f7932eb123cde6", "size": 16761, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/linalg/default_iterative_solver.cpp", "max_stars_repo_name": "mdavezac/bempp", "max_stars_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/linalg/default_iterative_solver.cpp", "max_issues_repo_name": "mdavezac/bempp", "max_issues_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/linalg/default_iterative_solver.cpp", "max_forks_repo_name": "mdavezac/bempp", "max_forks_repo_head_hexsha": "bc573062405bda107d1514e40b6153a8350d5ab5", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.2242744063, "max_line_length": 80, "alphanum_fraction": 0.7216753177, "num_tokens": 3821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.39981164073979497, "lm_q1q2_score": 0.20771067212897357}}
{"text": "/* decision_tree.cc                                                -*- C++ -*-\n   Jeremy Barnes, 22 March 2004\n   Copyright (c) 2004 Jeremy Barnes.  All rights reserved.\n   $Source$\n\n   Implementation of the decision tree.\n*/\n\n#include \"decision_tree.h\"\n#include \"classifier_persist_impl.h\"\n#include <boost/progress.hpp>\n#include <boost/timer.hpp>\n#include <functional>\n#include \"jml/utils/vector_utils.h\"\n#include \"config_impl.h\"\n#include \"jml/utils/exc_assert.h\"\n#include \"jml/utils/smart_ptr_utils.h\"\n\n\nusing namespace std;\nusing namespace DB;\n\n\n\nnamespace ML {\n\n\n/*****************************************************************************/\n/* DECISION_TREE                                                             */\n/*****************************************************************************/\n\nDecision_Tree::Decision_Tree()\n    : encoding(OE_PROB), optimized_(false)\n{\n}\n\nDecision_Tree::\nDecision_Tree(DB::Store_Reader & store,\n              const std::shared_ptr<const Feature_Space> & fs)\n    : optimized_(false)\n{\n    throw Exception(\"Decision_Tree constructor(reconst): not implemented\");\n}\n    \nDecision_Tree::\nDecision_Tree(std::shared_ptr<const Feature_Space> feature_space,\n              const Feature & predicted)\n    : Classifier_Impl(feature_space, predicted),\n      encoding(OE_PROB),\n      optimized_(false)\n{\n}\n    \nDecision_Tree::\n~Decision_Tree()\n{\n}\n    \nvoid\nDecision_Tree::\nswap(Decision_Tree & other)\n{\n    Classifier_Impl::swap(other);\n    std::swap(tree, other.tree);\n    std::swap(encoding, other.encoding);\n    std::swap(optimized_, other.optimized_);\n}\n\nnamespace {\n\nstruct StandardGetFeatures {\n    StandardGetFeatures(const Feature_Set & features)\n        : features(features)\n    {\n    }\n\n    const Feature_Set & features;\n\n    Split::Weights operator () (const Split & split) const\n    {\n        return split.apply(features);\n    }\n};\n\nstruct OptimizedGetFeatures {\n    OptimizedGetFeatures(const float * features)\n        : features(features)\n    {\n    }\n\n    const float * features;\n\n    JML_ALWAYS_INLINE Split::Weights operator () (const Split & split) const\n    {\n        return split.apply(features);\n    }\n                      \n};\n\nstruct AccumResults {\n    explicit AccumResults(double * accum, int nl, double weight)\n        : accum(accum), nl(nl), weight(weight)\n    {\n    }\n\n    double * accum;\n    int nl;\n    double weight;\n\n    JML_ALWAYS_INLINE\n    void operator () (const Label_Dist & dist, float weight1)\n    {\n        if (JML_LIKELY(nl == 2)) {\n            double factor = weight1 * weight;\n            accum[0] += dist[0] * factor;\n            accum[1] += dist[1] * factor;\n            return;\n        }\n\n        for (unsigned i = 0;  i < nl;  ++i)\n            accum[i] += dist[i] * weight1 * weight;\n    }\n};\n\nstruct DistResults {\n    explicit DistResults(double * accum, int nl)\n        : accum(accum), nl(nl)\n    {\n        std::fill(accum, accum + nl, 0.0);\n    }\n\n    double * accum;\n    int nl;\n\n    JML_ALWAYS_INLINE\n    void operator () (const Label_Dist & dist, float weight)\n    {\n        for (unsigned i = 0;  i < nl;  ++i)\n            accum[i] += dist[i] * weight;\n    }\n    \n    operator Label_Dist () const { return Label_Dist(accum, accum + nl); }\n};\n\nstruct LabelResults {\n    explicit LabelResults(int label)\n        : label(label), result(0.0)\n    {\n    }\n\n    JML_ALWAYS_INLINE\n    void operator () (const Label_Dist & dist, float weight)\n    {\n        result += weight * dist[label];\n    }\n\n    int label;\n    double result;\n\n    operator double () const { return result; }\n};\n\n} // file scope\n\nfloat\nDecision_Tree::\npredict(int label, const Feature_Set & features,\n        PredictionContext * context) const\n{\n    StandardGetFeatures get_features(features);\n    LabelResults results(label);\n\n    predict_recursive_impl(get_features, results, tree.root);\n    return results;\n}\n\nLabel_Dist\nDecision_Tree::\npredict(const Feature_Set & features,\n        PredictionContext * context) const\n{\n    StandardGetFeatures get_features(features);\n    int nl = label_count();\n    double accum[nl];\n    DistResults results(accum, nl);\n\n    predict_recursive_impl(get_features, results, tree.root);\n    return results;\n}\n\nbool\nDecision_Tree::\noptimization_supported() const\n{\n    return true;\n}\n\nbool\nDecision_Tree::\npredict_is_optimized() const\n{\n    return optimized_;\n}\n\nbool\nDecision_Tree::\noptimize_impl(Optimization_Info & info)\n{\n    optimize_recursive(info, tree.root);\n    optimized_ = true;\n    return true;\n}\n\nvoid\nDecision_Tree::\noptimize_recursive(Optimization_Info & info,\n                   const Tree::Ptr & ptr)\n{\n    if (!ptr) return;\n    if (!ptr.node()) return;\n\n    Tree::Node & node = *ptr.node();\n\n    node.split.optimize(info);\n    optimize_recursive(info, node.child_true);\n    optimize_recursive(info, node.child_false);\n    optimize_recursive(info, node.child_missing);\n}\n\nLabel_Dist\nDecision_Tree::\noptimized_predict_impl(const float * features,\n                       const Optimization_Info & info,\n                       PredictionContext * context) const\n{\n    OptimizedGetFeatures get_features(features);\n\n    int nl = label_count();\n    double accum[nl];\n    DistResults results(accum, nl);\n\n    predict_recursive_impl(get_features, results, tree.root);\n    return results;\n}\n\nvoid\nDecision_Tree::\noptimized_predict_impl(const float * features,\n                       const Optimization_Info & info,\n                       double * accum,\n                       double weight,\n                       PredictionContext * context) const\n{\n    OptimizedGetFeatures get_features(features);\n    AccumResults results(accum, label_count(), weight);\n\n    predict_recursive_impl(get_features, results, tree.root);\n}\n\nfloat\nDecision_Tree::\noptimized_predict_impl(int label,\n                       const float * features,\n                       const Optimization_Info & info,\n                       PredictionContext * context) const\n{\n    OptimizedGetFeatures get_features(features);\n    LabelResults results(label);\n\n    predict_recursive_impl(get_features, results, tree.root);\n    return results;\n}\n\ntemplate<class GetFeatures, class Results>\nvoid\nDecision_Tree::\npredict_recursive_impl(const GetFeatures & get_features,\n                       Results & results,\n                       const Tree::Ptr & ptr,\n                       double weight) const\n{\n    if (!ptr) return;\n\n    if (!ptr.node()) {\n        results(ptr.leaf()->pred, weight);\n        return;\n    }\n\n    const Tree::Node & node = *ptr.node();\n    \n    Split::Weights weights = get_features(node.split);\n    \n    /* Go down all of the edges that we need to for this example. */\n    if (weights[true] > 0.0)\n        predict_recursive_impl(get_features, results, node.child_true,\n                               weights[true]);\n    if (weights[false] > 0.0)\n        predict_recursive_impl(get_features, results, node.child_false,\n                               weights[false]);\n    if (weights[MISSING] > 0.0)\n        predict_recursive_impl(get_features, results, node.child_missing,\n                               weights[MISSING]);\n}\n\nstd::string\nprintLabels(const distribution<float> & dist)\n{\n    string result = \"\";\n    for (unsigned i = 0;  i < dist.size();  ++i)\n        if (dist[i] != 0.0) result += format(\" %d/%.3f\", i, dist[i]);\n    return result;\n}\n\nstd::string\nprintLabels(const Tree::Ptr & ptr)\n{\n    return printLabels(ptr.pred());\n}\n\nstd::string\nDecision_Tree::\nprint() const\n{\n    string result = \"Decision Tree: \";\n    float total_weight = tree.root.examples();\n    if (tree.root.node()) total_weight = tree.root.examples();\n    result = format(\"Decision Tree: (weight = %.2f, cov = %.2f%%) \",\n                    total_weight, 100.0);\n    result += printLabels(tree.root) + \"\\n\";\n    result += print_recursive(0, tree.root, total_weight);\n    return result;\n}\n\nstd::string\nDecision_Tree::\nsummary() const\n{\n    if (!tree.root)\n        return \"NULL\";\n    \n    float total_weight = 0.0;\n    if (tree.root.node()) total_weight = tree.root.node()->examples;\n    \n    if (tree.root.node()) {\n        Tree::Node & n = *tree.root.node();\n        float cov = n.examples / total_weight;\n        float z_adj = n.z / cov;\n        return \"Root: \" + n.split.print(*feature_space())\n            + format(\" (z = %.4f)\", z_adj);\n    }\n    else {\n        string result = \"leaf: \";\n        Tree::Leaf & l = *tree.root.leaf();\n        const distribution<float> & dist = l.pred;\n        for (unsigned i = 0;  i < dist.size();  ++i)\n            if (dist[i] != 0.0) result += format(\" %d/%.3f\", i, dist[i]);\n        return result;\n    }\n}\n\nstring\nDecision_Tree::\nprint_recursive(int level, const Tree::Ptr & ptr,\n                float total_weight) const\n{\n    string spaces(level * 4, ' ');\n    if (ptr.node()) {\n        Tree::Node & n = *ptr.node();\n        string result;\n        float z_cov = n.examples / total_weight;\n        float z_adj = n.z / z_cov;\n\n        if (n.child_false && n.child_false.examples() > 0) {\n            float cov = n.child_false.examples() / total_weight;\n            result += spaces \n                + format(\" %s (z = %.4f, weight = %.2f, cov = %.2f%%) \",\n                         n.split.print(*feature_space(), false).c_str(),\n                         z_adj, n.child_false.examples(), cov * 100.0);\n            result += printLabels(n.child_false) + \"\\n\";\n            result += print_recursive(level + 1, n.child_false, total_weight);\n        }\n\n        if (n.child_true && n.child_true.examples() > 0) {\n            float cov = n.child_true.examples() / total_weight;\n            result += spaces \n                + format(\" %s (z = %.4f, weight = %.2f, cov = %.2f%%) \",\n                         n.split.print(*feature_space(), true).c_str(),\n                         z_adj, n.child_true.examples(), cov * 100.0);\n            result += printLabels(n.child_true) + \"\\n\";\n            result += print_recursive(level + 1, n.child_true, total_weight);\n        }\n\n        if (n.child_missing && n.child_missing.examples() > 0) {\n            float cov = n.child_missing.examples() / total_weight;\n            result += spaces \n                + format(\" %s (z = %.4f, weight = %.2f, cov = %.2f%%) \",\n                         n.split.print(*feature_space(), MISSING).c_str(),\n                         z_adj, n.child_missing.examples(), cov * 100.0);\n            result += printLabels(n.child_missing) + \"\\n\";\n            result += print_recursive(level + 1, n.child_missing, total_weight);\n        }\n        return result;\n    }\n    else if (ptr.leaf()) {\n        return \"\";\n        string result = spaces + \"leaf \";\n        Tree::Leaf & l = *ptr.leaf();\n        const distribution<float> & dist = l.pred;\n        float cov = l.examples / total_weight;\n        result += format(\" (weight = %.2f, cov = %.2f%%) \",\n                         l.examples, cov * 100.0);\n        result += printLabels(dist);\n        result += \"\\n\";\n        return result;\n    }\n    else return spaces + \"NULL\";\n}\n\nExplanation\nDecision_Tree::\nexplain(const Feature_Set & feature_set,\n        int label,\n        double weight,\n        PredictionContext * context) const\n{\n    Explanation result(feature_space(), weight); \n\n    explain_recursive(result, feature_set, label, weight, tree.root, 0);\n\n    return result;\n}\n\nvoid\nDecision_Tree::\nexplain_recursive(Explanation & explanation,\n                  const Feature_Set & feature_set,\n                  int label,\n                  double weight,\n                  const Tree::Ptr & ptr,\n                  const Tree::Node * parent) const\n{\n    StandardGetFeatures get_features(feature_set);\n    int nl = label_count();\n\n    if (label < 0 || label >= nl)\n        throw Exception(\"Decision_Tree::explain(): no label\");\n\n    if (!ptr) return;\n\n    if (!ptr.node()) {\n        // It's a leaf; we give the difference to the parent's feature\n        if (parent) {\n            explanation.feature_weights[parent->split.feature()]\n                += weight\n                * (ptr.leaf()->pred.at(label) - parent->pred.at(label));\n        }\n        else {\n            // No parent, therefore it's all bias\n            explanation.bias += weight * (ptr.leaf()->pred.at(label));\n        }\n\n        return;\n    }\n\n    const Tree::Node & node = *ptr.node();\n    \n    Split::Weights weights = get_features(node.split);\n\n    // Accumulate the weight for this split\n    if (!parent)\n        explanation.bias += weight * node.pred.at(label);\n    else\n        explanation.feature_weights[parent->split.feature()]\n            += weight\n            * (node.pred.at(label) - parent->pred.at(label));\n    \n    /* Go down all of the edges that we need to for this example. */\n    if (weights[true] > 0.0)\n        explain_recursive(explanation, feature_set, label,\n                          weight * weights[true],\n                          node.child_true, &node);\n\n    if (weights[false] > 0.0)\n        explain_recursive(explanation, feature_set, label,\n                          weight * weights[false],\n                          node.child_false, &node);\n\n    if (weights[MISSING] > 0.0)\n        explain_recursive(explanation, feature_set, label,\n                          weight * weights[MISSING],\n                          node.child_missing, &node);\n}\n\nDisjunction<Tree::Leaf>\nDecision_Tree::\nto_rules() const\n{\n    Disjunction<Tree::Leaf> result;\n    result.feature_space = feature_space();\n    std::vector<std::shared_ptr<Predicate> > path;\n\n    to_rules_recursive(result, path, tree.root);\n\n    ExcAssert(path.empty());\n\n    return result;\n}\n\nvoid\nDecision_Tree::\nto_rules_recursive(Disjunction<Tree::Leaf> & result,\n                   std::vector<std::shared_ptr<Predicate> > & path,\n                   const Tree::Ptr & ptr) const\n{\n    if (ptr.examples() == 0.0) return;\n\n    if (ptr.node()) {\n        const Tree::Node & node = *ptr.node();\n        \n        {\n            path.push_back(make_sp(new Predicate(node.split, false)));\n            to_rules_recursive(result, path, node.child_false);\n            path.pop_back();\n        }\n\n        {\n            path.push_back(make_sp(new Predicate(node.split, true)));\n            to_rules_recursive(result, path, node.child_true);\n            path.pop_back();\n        }\n\n        {\n            path.push_back(make_sp(new Predicate(node.split, MISSING)));\n            to_rules_recursive(result, path, node.child_missing);\n            path.pop_back();\n        }\n    }\n    else if (ptr.leaf()) {\n        std::shared_ptr<Conjunction<Tree::Leaf> > c\n            (new Conjunction<Tree::Leaf>());\n        c->predicates = path;\n        c->outcome = *ptr.leaf();\n        result.predicates.push_back(c);\n    }\n}\n\nnamespace {\n\nvoid all_features_recursive(const Tree::Ptr & ptr,\n                            vector<Feature> & result)\n{\n    if (ptr.node()) {\n        Tree::Node & n = *ptr.node();\n        result.push_back(n.split.feature());\n\n        all_features_recursive(n.child_true,    result);\n        all_features_recursive(n.child_false,   result);\n        all_features_recursive(n.child_missing, result);\n    }\n}\n\n} // file scope\n\nstd::vector<ML::Feature>\nDecision_Tree::\nall_features() const\n{\n    std::vector<ML::Feature> result;\n    all_features_recursive(tree.root, result);\n    make_vector_set(result);\n    return result;\n}\n\nOutput_Encoding\nDecision_Tree::\noutput_encoding() const\n{\n    return encoding;\n}\n\nvoid\nDecision_Tree::\nserialize(DB::Store_Writer & store) const\n{\n    store << string(\"DECISION_TREE\");\n    store << compact_size_t(3);  // version\n    store << compact_size_t(label_count());\n    feature_space_->serialize(store, predicted_);\n    tree.serialize(store, *feature_space());\n    store << encoding;\n    store << compact_size_t(12345);  // end marker\n}\n\nvoid\nDecision_Tree::\nreconstitute(DB::Store_Reader & store,\n             const std::shared_ptr<const Feature_Space> & feature_space)\n{\n    string id;\n    store >> id;\n\n    if (id != \"DECISION_TREE\")\n        throw Exception(\"Decision_Tree::reconstitute: read bad ID '\"\n                        + id + \"'\");\n\n    compact_size_t version(store);\n    \n    switch (version) {\n    case 1: {\n        compact_size_t label_count(store);\n        Classifier_Impl::init(feature_space, MISSING_FEATURE, label_count);\n        tree.reconstitute(store, *feature_space);\n        break;\n    }\n    case 2:\n    case 3: {\n        compact_size_t label_count(store);\n        feature_space->reconstitute(store, predicted_);\n        Classifier_Impl::init(feature_space, predicted_);\n        tree.reconstitute(store, *feature_space);\n        if (version >= 3)\n            store >> encoding;\n        else encoding = OE_PROB;\n        break;\n    }\n    default:\n        throw Exception(\"Decision tree: Attempt to reconstitute tree of \"\n                        \"unknown version \" + ostream_format(version.size_));\n    }\n\n    compact_size_t marker(store);\n    if (marker != 12345)\n        throw Exception(\"Decision_Tree::reconstitute: read bad marker at end\");\n\n    optimized_ = false;\n}\n    \nstd::string\nDecision_Tree::\nclass_id() const\n{\n    return \"DECISION_TREE\";\n}\n\nDecision_Tree *\nDecision_Tree::\nmake_copy() const\n{\n    return new Decision_Tree(*this);\n}\n\n/*****************************************************************************/\n/* REGISTRATION                                                              */\n/*****************************************************************************/\n\nnamespace {\n\nRegister_Factory<Classifier_Impl, Decision_Tree> REGISTER(\"DECISION_TREE\");\n\n} // file scope\n\n} // namespace ML\n\n", "meta": {"hexsha": "299b93492a91de024e746566944161fd04661616", "size": 17513, "ext": "cc", "lang": "C++", "max_stars_repo_path": "jml/boosting/decision_tree.cc", "max_stars_repo_name": "etnrlz/rtbkit", "max_stars_repo_head_hexsha": "0d9cd9e2ee2d7580a27453ad0a2d815410d87091", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 737.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T01:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T10:09:23.000Z", "max_issues_repo_path": "jml/boosting/decision_tree.cc", "max_issues_repo_name": "TuanTranEngineer/rtbkit", "max_issues_repo_head_hexsha": "502d06acc3f8d90438946b6ae742190f2f4b4fbb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T16:01:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-22T19:02:37.000Z", "max_forks_repo_path": "jml/boosting/decision_tree.cc", "max_forks_repo_name": "TuanTranEngineer/rtbkit", "max_forks_repo_head_hexsha": "502d06acc3f8d90438946b6ae742190f2f4b4fbb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 329.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T06:54:27.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-12T22:21:02.000Z", "avg_line_length": 26.375, "max_line_length": 80, "alphanum_fraction": 0.5756866328, "num_tokens": 3882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20771067212897354}}
{"text": "// Boost.Geometry - gis-projections (based on PROJ4)\n\n// Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands.\n\n// This file was modified by Oracle on 2017, 2018.\n// Modifications copyright (c) 2017-2018, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n// This file is converted from PROJ4, http://trac.osgeo.org/proj\n// PROJ4 is originally written by Gerald Evenden (then of the USGS)\n// PROJ4 is maintained by Frank Warmerdam\n// PROJ4 is converted to Boost.Geometry by Barend Gehrels\n\n// Last updated version of proj: 5.0.0\n\n// Original copyright notice:\n\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the \"Software\"),\n// to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense,\n// and/or sell copies of the Software, and to permit persons to whom the\n// Software is furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n// DEALINGS IN THE SOFTWARE.\n\n#ifndef BOOST_GEOMETRY_PROJECTIONS_FOUC_S_HPP\n#define BOOST_GEOMETRY_PROJECTIONS_FOUC_S_HPP\n\n#include <boost/geometry/srs/projections/impl/aasincos.hpp>\n#include <boost/geometry/srs/projections/impl/base_static.hpp>\n#include <boost/geometry/srs/projections/impl/base_dynamic.hpp>\n#include <boost/geometry/srs/projections/impl/factory_entry.hpp>\n#include <boost/geometry/srs/projections/impl/pj_param.hpp>\n#include <boost/geometry/srs/projections/impl/projects.hpp>\n\n#include <boost/geometry/util/math.hpp>\n\nnamespace boost { namespace geometry\n{\n\nnamespace projections\n{\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail { namespace fouc_s\n    {\n\n            static const int max_iter = 10;\n            static const double loop_tol = 1e-7;\n\n            template <typename T>\n            struct par_fouc_s\n            {\n                T n, n1;\n            };\n\n            // template class, using CRTP to implement forward/inverse\n            template <typename T, typename Parameters>\n            struct base_fouc_s_spheroid\n                : public base_t_fi<base_fouc_s_spheroid<T, Parameters>, T, Parameters>\n            {\n                par_fouc_s<T> m_proj_parm;\n\n                inline base_fouc_s_spheroid(const Parameters& par)\n                    : base_t_fi<base_fouc_s_spheroid<T, Parameters>, T, Parameters>(*this, par)\n                {}\n\n                // FORWARD(s_forward)  spheroid\n                // Project coordinates from geographic (lon, lat) to cartesian (x, y)\n                inline void fwd(T const& lp_lon, T const& lp_lat, T& xy_x, T& xy_y) const\n                {\n                    T t;\n\n                    t = cos(lp_lat);\n                    xy_x = lp_lon * t / (this->m_proj_parm.n + this->m_proj_parm.n1 * t);\n                    xy_y = this->m_proj_parm.n * lp_lat + this->m_proj_parm.n1 * sin(lp_lat);\n                }\n\n                // INVERSE(s_inverse)  spheroid\n                // Project coordinates from cartesian (x, y) to geographic (lon, lat)\n                inline void inv(T const& xy_x, T const& xy_y, T& lp_lon, T& lp_lat) const\n                {\n                    static T const half_pi = detail::half_pi<T>();\n\n                    T V;\n                    int i;\n\n                    if (this->m_proj_parm.n != 0.0) {\n                        lp_lat = xy_y;\n                        for (i = max_iter; i ; --i) {\n                            lp_lat -= V = (this->m_proj_parm.n * lp_lat + this->m_proj_parm.n1 * sin(lp_lat) - xy_y ) /\n                                (this->m_proj_parm.n + this->m_proj_parm.n1 * cos(lp_lat));\n                            if (fabs(V) < loop_tol)\n                                break;\n                        }\n                        if (!i)\n                            lp_lat = xy_y < 0. ? -half_pi : half_pi;\n                    } else\n                        lp_lat = aasin(xy_y);\n                    V = cos(lp_lat);\n                    lp_lon = xy_x * (this->m_proj_parm.n + this->m_proj_parm.n1 * V) / V;\n                }\n\n                static inline std::string get_name()\n                {\n                    return \"fouc_s_spheroid\";\n                }\n\n            };\n\n            // Foucaut Sinusoidal\n            template <typename Params, typename Parameters, typename T>\n            inline void setup_fouc_s(Params const& params, Parameters& par, par_fouc_s<T>& proj_parm)\n            {\n                proj_parm.n = pj_get_param_f<T, srs::spar::n>(params, \"n\", srs::dpar::n);\n                if ((proj_parm.n < 0.) || (proj_parm.n > 1.))\n                    BOOST_THROW_EXCEPTION( projection_exception(error_n_out_of_range) );\n\n                proj_parm.n1 = 1. - proj_parm.n;\n                par.es = 0;\n            }\n\n    }} // namespace detail::fouc_s\n    #endif // doxygen\n\n    /*!\n        \\brief Foucaut Sinusoidal projection\n        \\ingroup projections\n        \\tparam Geographic latlong point type\n        \\tparam Cartesian xy point type\n        \\tparam Parameters parameter type\n        \\par Projection characteristics\n         - Pseudocylindrical\n         - Spheroid\n        \\par Projection parameters\n         - n (real)\n        \\par Example\n        \\image html ex_fouc_s.gif\n    */\n    template <typename T, typename Parameters>\n    struct fouc_s_spheroid : public detail::fouc_s::base_fouc_s_spheroid<T, Parameters>\n    {\n        template <typename Params>\n        inline fouc_s_spheroid(Params const& params, Parameters const& par)\n            : detail::fouc_s::base_fouc_s_spheroid<T, Parameters>(par)\n        {\n            detail::fouc_s::setup_fouc_s(params, this->m_par, this->m_proj_parm);\n        }\n    };\n\n    #ifndef DOXYGEN_NO_DETAIL\n    namespace detail\n    {\n\n        // Static projection\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::spar::proj_fouc_s, fouc_s_spheroid, fouc_s_spheroid)\n\n        // Factory entry(s)\n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_ENTRY_FI(fouc_s_entry, fouc_s_spheroid)\n        \n        BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_BEGIN(fouc_s_init)\n        {\n            BOOST_GEOMETRY_PROJECTIONS_DETAIL_FACTORY_INIT_ENTRY(fouc_s, fouc_s_entry);\n        }\n\n    } // namespace detail\n    #endif // doxygen\n\n} // namespace projections\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_PROJECTIONS_FOUC_S_HPP\n\n", "meta": {"hexsha": "f6a8c5ed4b51916e50457f88ba22e86629558fb4", "size": 7196, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/fouc_s.hpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/fouc_s.hpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/boost/geometry/srs/projections/proj/fouc_s.hpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 38.2765957447, "max_line_length": 119, "alphanum_fraction": 0.6133963313, "num_tokens": 1710, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.34158248603300034, "lm_q1q2_score": 0.2075670962222124}}
{"text": "/*\n * Copyright (c) 2015 Cryptonomex, Inc., and contributors.\n *\n * The MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\n#include <graphene/chain/protocol/asset.hpp>\n#include <boost/rational.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n\nnamespace graphene { namespace chain {\n      typedef boost::multiprecision::uint128_t uint128_t;\n      typedef boost::multiprecision::int128_t  int128_t;\n\n      bool operator == ( const price& a, const price& b )\n      {\n         if( std::tie( a.base.asset_id, a.quote.asset_id ) != std::tie( b.base.asset_id, b.quote.asset_id ) )\n            return false;\n\n         const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value;\n         const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value;\n\n         return amult == bmult;\n      }\n\n      bool operator < ( const price& a, const price& b )\n      {\n         if( a.base.asset_id < b.base.asset_id ) return true;\n         if( a.base.asset_id > b.base.asset_id ) return false;\n         if( a.quote.asset_id < b.quote.asset_id ) return true;\n         if( a.quote.asset_id > b.quote.asset_id ) return false;\n\n         const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value;\n         const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value;\n\n         return amult < bmult;\n      }\n\n      asset operator * ( const asset& a, const price& b )\n      {\n         if( a.asset_id == b.base.asset_id )\n         {\n            FC_ASSERT( b.base.amount.value > 0 );\n            uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value)/b.base.amount.value;\n            FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );\n            return asset( result.convert_to<int64_t>(), b.quote.asset_id );\n         }\n         else if( a.asset_id == b.quote.asset_id )\n         {\n            FC_ASSERT( b.quote.amount.value > 0 );\n            uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value)/b.quote.amount.value;\n            FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );\n            return asset( result.convert_to<int64_t>(), b.base.asset_id );\n         }\n         FC_THROW_EXCEPTION( fc::assert_exception, \"invalid asset * price\", (\"asset\",a)(\"price\",b) );\n      }\n\n      asset asset::multiply_and_round_up( const price& b )const\n      {\n         const asset& a = *this;\n         if( a.asset_id == b.base.asset_id )\n         {\n            FC_ASSERT( b.base.amount.value > 0 );\n            uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value + b.base.amount.value - 1)/b.base.amount.value;\n            FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );\n            return asset( result.convert_to<int64_t>(), b.quote.asset_id );\n         }\n         else if( a.asset_id == b.quote.asset_id )\n         {\n            FC_ASSERT( b.quote.amount.value > 0 );\n            uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value + b.quote.amount.value - 1)/b.quote.amount.value;\n            FC_ASSERT( result <= GRAPHENE_MAX_SHARE_SUPPLY );\n            return asset( result.convert_to<int64_t>(), b.base.asset_id );\n         }\n         FC_THROW_EXCEPTION( fc::assert_exception, \"invalid asset::multiply_and_round_up(price)\", (\"asset\",a)(\"price\",b) );\n      }\n\n      price operator / ( const asset& base, const asset& quote )\n      { try {\n         FC_ASSERT( base.asset_id != quote.asset_id );\n         return price{base,quote};\n      } FC_CAPTURE_AND_RETHROW( (base)(quote) ) }\n\n      price price::max( asset_id_type base, asset_id_type quote ) { return asset( share_type(GRAPHENE_MAX_SHARE_SUPPLY), base ) / asset( share_type(1), quote); }\n      price price::min( asset_id_type base, asset_id_type quote ) { return asset( 1, base ) / asset( GRAPHENE_MAX_SHARE_SUPPLY, quote); }\n\n      price operator *  ( const price& p, const ratio_type& r )\n      { try {\n         p.validate();\n\n         FC_ASSERT( r.numerator() > 0 && r.denominator() > 0 );\n\n         if( r.numerator() == r.denominator() ) return p;\n\n         boost::rational<int128_t> p128( p.base.amount.value, p.quote.amount.value );\n         boost::rational<int128_t> r128( r.numerator(), r.denominator() );\n         auto cp = p128 * r128;\n         auto ocp = cp;\n\n         bool shrinked = false;\n         bool using_max = false;\n         static const int128_t max( GRAPHENE_MAX_SHARE_SUPPLY );\n         while( cp.numerator() > max || cp.denominator() > max )\n         {\n            if( cp.numerator() == 1 )\n            {\n               cp = boost::rational<int128_t>( 1, max );\n               using_max = true;\n               break;\n            }\n            else if( cp.denominator() == 1 )\n            {\n               cp = boost::rational<int128_t>( max, 1 );\n               using_max = true;\n               break;\n            }\n            else\n            {\n               cp = boost::rational<int128_t>( cp.numerator() >> 1, cp.denominator() >> 1 );\n               shrinked = true;\n            }\n         }\n         if( shrinked ) // maybe not accurate enough due to rounding, do additional checks here\n         {\n            int128_t num = ocp.numerator();\n            int128_t den = ocp.denominator();\n            if( num > den )\n            {\n               num /= den;\n               if( num > max )\n                  num = max;\n               den = 1;\n            }\n            else\n            {\n               den /= num;\n               if( den > max )\n                  den = max;\n               num = 1;\n            }\n            boost::rational<int128_t> ncp( num, den );\n            if( num == max || den == max ) // it's on the edge, we know it's accurate enough\n               cp = ncp;\n            else\n            {\n               // from the accurate ocp, now we have ncp and cp. use the one which is closer to ocp.\n               // TODO improve performance\n               auto diff1 = abs( ncp - ocp );\n               auto diff2 = abs( cp - ocp );\n               if( diff1 < diff2 ) cp = ncp;\n            }\n         }\n\n         price np = asset( cp.numerator().convert_to<int64_t>(), p.base.asset_id )\n                  / asset( cp.denominator().convert_to<int64_t>(), p.quote.asset_id );\n\n         if( shrinked || using_max )\n         {\n            if( ( r.numerator() > r.denominator() && np < p )\n                  || ( r.numerator() < r.denominator() && np > p ) )\n               // even with an accurate result, if p is out of valid range, return it\n               np = p;\n         }\n\n         np.validate();\n         return np;\n      } FC_CAPTURE_AND_RETHROW( (p)(r.numerator())(r.denominator()) ) }\n\n      price operator /  ( const price& p, const ratio_type& r )\n      { try {\n         return p * ratio_type( r.denominator(), r.numerator() );\n      } FC_CAPTURE_AND_RETHROW( (p)(r.numerator())(r.denominator()) ) }\n\n      /**\n       *  The black swan price is defined as debt/collateral, we want to perform a margin call\n       *  before debt == collateral.   Given a debt/collateral ratio of 1 USD / CORE and\n       *  a maintenance collateral requirement of 2x we can define the call price to be\n       *  2 USD / CORE.\n       *\n       *  This method divides the collateral by the maintenance collateral ratio to derive\n       *  a call price for the given black swan ratio.\n       *\n       *  There exists some cases where the debt and collateral values are so small that\n       *  dividing by the collateral ratio will result in a 0 price or really poor\n       *  rounding errors.   No matter what the collateral part of the price ratio can\n       *  never go to 0 and the debt can never go more than GRAPHENE_MAX_SHARE_SUPPLY\n       *\n       *  CR * DEBT/COLLAT or DEBT/(COLLAT/CR)\n       *\n       *  Note: this function is only used before core-1270 hard fork.\n       */\n      price price::call_price( const asset& debt, const asset& collateral, uint16_t collateral_ratio)\n      { try {\n         boost::rational<int128_t> swan(debt.amount.value,collateral.amount.value);\n         boost::rational<int128_t> ratio( collateral_ratio, GRAPHENE_COLLATERAL_RATIO_DENOM );\n         auto cp = swan * ratio;\n\n         while( cp.numerator() > GRAPHENE_MAX_SHARE_SUPPLY || cp.denominator() > GRAPHENE_MAX_SHARE_SUPPLY )\n            cp = boost::rational<int128_t>( (cp.numerator() >> 1)+1, (cp.denominator() >> 1)+1 );\n\n         return  (  asset( cp.denominator().convert_to<int64_t>(), collateral.asset_id )\n                  / asset( cp.numerator().convert_to<int64_t>(), debt.asset_id ) );\n      } FC_CAPTURE_AND_RETHROW( (debt)(collateral)(collateral_ratio) ) }\n\n      bool price::is_null() const\n      {\n         // Effectively same as \"return *this == price();\" but perhaps faster\n         return ( base.asset_id == asset_id_type() && quote.asset_id == asset_id_type() );\n      }\n\n      void price::validate() const\n      { try {\n         FC_ASSERT( base.amount > share_type(0) );\n         FC_ASSERT( quote.amount > share_type(0) );\n         FC_ASSERT( base.asset_id != quote.asset_id );\n      } FC_CAPTURE_AND_RETHROW( (base)(quote) ) }\n\n      void price_feed::validate() const\n      { try {\n         if( !settlement_price.is_null() )\n            settlement_price.validate();\n         FC_ASSERT( maximum_short_squeeze_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO );\n         FC_ASSERT( maximum_short_squeeze_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO );\n         FC_ASSERT( maintenance_collateral_ratio >= GRAPHENE_MIN_COLLATERAL_RATIO );\n         FC_ASSERT( maintenance_collateral_ratio <= GRAPHENE_MAX_COLLATERAL_RATIO );\n         // Note: there was code here calling `max_short_squeeze_price();` before core-1270 hard fork,\n         //       in order to make sure that it doesn't overflow,\n         //       but the code doesn't actually check overflow, and it won't overflow, so the code is removed.\n\n         // Note: not checking `maintenance_collateral_ratio >= maximum_short_squeeze_ratio` since launch\n      } FC_CAPTURE_AND_RETHROW( (*this) ) }\n\n      bool price_feed::is_for( asset_id_type asset_id ) const\n      {\n         try\n         {\n            if( !settlement_price.is_null() )\n               return (settlement_price.base.asset_id == asset_id);\n            if( !core_exchange_rate.is_null() )\n               return (core_exchange_rate.base.asset_id == asset_id);\n            // (null, null) is valid for any feed\n            return true;\n         }\n         FC_CAPTURE_AND_RETHROW( (*this) )\n      }\n\n      // This function is kept here due to potential different behavior in edge cases.\n      // TODO check after core-1270 hard fork to see if we can safely remove it\n      price price_feed::max_short_squeeze_price_before_hf_1270()const\n      {\n         // settlement price is in debt/collateral\n         boost::rational<int128_t> sp( settlement_price.base.amount.value, settlement_price.quote.amount.value );\n         boost::rational<int128_t> ratio( GRAPHENE_COLLATERAL_RATIO_DENOM, maximum_short_squeeze_ratio );\n         auto cp = sp * ratio;\n\n         while( cp.numerator() > GRAPHENE_MAX_SHARE_SUPPLY || cp.denominator() > GRAPHENE_MAX_SHARE_SUPPLY )\n            cp = boost::rational<int128_t>( (cp.numerator() >> 1)+(cp.numerator()&1),\n                                            (cp.denominator() >> 1)+(cp.denominator()&1) );\n\n         return (  asset( cp.numerator().convert_to<int64_t>(), settlement_price.base.asset_id )\n                 / asset( cp.denominator().convert_to<int64_t>(), settlement_price.quote.asset_id ) );\n      }\n\n      price price_feed::max_short_squeeze_price()const\n      {\n         // settlement price is in debt/collateral\n         return settlement_price * ratio_type( GRAPHENE_COLLATERAL_RATIO_DENOM, maximum_short_squeeze_ratio );\n      }\n\n      price price_feed::maintenance_collateralization()const\n      {\n         if( settlement_price.is_null() )\n            return price();\n         return ~settlement_price * ratio_type( maintenance_collateral_ratio, GRAPHENE_COLLATERAL_RATIO_DENOM );\n      }\n\n// compile-time table of powers of 10 using template metaprogramming\n\ntemplate< int N >\nstruct p10\n{\n   static const int64_t v = 10 * p10<N-1>::v;\n};\n\ntemplate<>\nstruct p10<0>\n{\n   static const int64_t v = 1;\n};\n\nconst int64_t scaled_precision_lut[19] =\n{\n   p10<  0 >::v, p10<  1 >::v, p10<  2 >::v, p10<  3 >::v,\n   p10<  4 >::v, p10<  5 >::v, p10<  6 >::v, p10<  7 >::v,\n   p10<  8 >::v, p10<  9 >::v, p10< 10 >::v, p10< 11 >::v,\n   p10< 12 >::v, p10< 13 >::v, p10< 14 >::v, p10< 15 >::v,\n   p10< 16 >::v, p10< 17 >::v, p10< 18 >::v\n};\n\n} } // graphene::chain\n", "meta": {"hexsha": "a9c1daf502b1bbaabcb7bd15e829a5a621f017dc", "size": 13544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libraries/chain/protocol/asset.cpp", "max_stars_repo_name": "cwyyprog/bitshares-core", "max_stars_repo_head_hexsha": "f47c115cd21e62829e242447398b20b40a32cddf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-05T14:37:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-05T14:37:30.000Z", "max_issues_repo_path": "libraries/chain/protocol/asset.cpp", "max_issues_repo_name": "cwyyprog/bitshares-core", "max_issues_repo_head_hexsha": "f47c115cd21e62829e242447398b20b40a32cddf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libraries/chain/protocol/asset.cpp", "max_forks_repo_name": "cwyyprog/bitshares-core", "max_forks_repo_head_hexsha": "f47c115cd21e62829e242447398b20b40a32cddf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-08-23T00:18:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-06T21:10:42.000Z", "avg_line_length": 42.5911949686, "max_line_length": 161, "alphanum_fraction": 0.597976964, "num_tokens": 3310, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.3415824860330003, "lm_q1q2_score": 0.20756709622221237}}
{"text": "/* ============================================================================\n * Copyright (c) 2009-2020 BlueQuartz Software, LLC\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n *\n * Neither the name of BlueQuartz Software, the US Air Force, nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The code contained herein was partially funded by the following contracts:\n *    United States Air Force Prime Contract FA8650-07-D-5800\n *    United States Air Force Prime Contract FA8650-10-D-5210\n *    United States Prime Contract Navy N00173-07-C-2068\n *\n * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */\n#include \"ApplyTransformationToGeometry.h\"\n\n#include <Eigen/Dense>\n\n#include <QtCore/QTextStream>\n\n#include \"SIMPLib/Common/Constants.h\"\n#include \"SIMPLib/Common/SIMPLRange.h\"\n#include \"SIMPLib/DataContainers/DataContainerArray.h\"\n#include \"SIMPLib/FilterParameters/AbstractFilterParametersReader.h\"\n#include \"SIMPLib/FilterParameters/DataArraySelectionFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/DataContainerSelectionFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/DynamicTableFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/FloatFilterParameter.h\"\n#include \"SIMPLib/FilterParameters/LinkedChoicesFilterParameter.h\"\n#include \"SIMPLib/Geometry/EdgeGeom.h\"\n#include \"SIMPLib/Geometry/IGeometry2D.h\"\n#include \"SIMPLib/Geometry/IGeometry3D.h\"\n#include \"SIMPLib/Geometry/VertexGeom.h\"\n#include \"SIMPLib/Math/SIMPLibMath.h\"\n#include \"SIMPLib/Utilities/ParallelDataAlgorithm.h\"\n\n#include \"EbsdLib/Core/Orientation.hpp\"\n#include \"EbsdLib/Core/OrientationTransformation.hpp\"\n\n#include \"DREAM3DReview/DREAM3DReviewConstants.h\"\n#include \"DREAM3DReview/DREAM3DReviewVersion.h\"\n\nnamespace ApplyTransformationProgress\n{\nstatic size_t s_InstanceIndex = 0;\nstatic std::map<size_t, int64_t> s_ProgressValues;\nstatic std::map<size_t, int64_t> s_LastProgressInt;\n} // namespace ApplyTransformationProgress\n\nclass ApplyTransformationToGeometryImpl\n{\n\npublic:\n  ApplyTransformationToGeometryImpl(ApplyTransformationToGeometry& filter, float* transformationMatrix, const SharedVertexList::Pointer verticesPtr)\n  : m_Filter(filter)\n  , m_TransformationMatrix(transformationMatrix)\n  , m_Vertices(verticesPtr)\n  {\n  }\n  ~ApplyTransformationToGeometryImpl() = default;\n\n  void convert(size_t start, size_t end) const\n  {\n    using ProjectiveMatrix = Eigen::Matrix<float, 4, 4, Eigen::RowMajor>;\n    Eigen::Map<ProjectiveMatrix> transformation(m_TransformationMatrix);\n\n    int64_t progCounter = 0;\n    int64_t totalElements = (end - start);\n    int64_t progIncrement = static_cast<int64_t>(totalElements / 100);\n\n    SharedVertexList& vertices = *(m_Vertices.get());\n    for(size_t i = start; i < end; i++)\n    {\n      if(m_Filter.getCancel())\n      {\n        return;\n      }\n      Eigen::Vector4f position(vertices[3 * i + 0], vertices[3 * i + 1], vertices[3 * i + 2], 1);\n      Eigen::Vector4f transformedPosition = transformation * position;\n      vertices.setTuple(i, transformedPosition.data());\n\n      if(progCounter > progIncrement)\n      {\n        m_Filter.sendThreadSafeProgressMessage(progCounter);\n        progCounter = 0;\n      }\n      progCounter++;\n    }\n  }\n\n  void operator()(const SIMPLRange& range) const\n  {\n    convert(range.min(), range.max());\n  }\n\nprivate:\n  ApplyTransformationToGeometry& m_Filter;\n  float* m_TransformationMatrix = nullptr;\n  SharedVertexList::Pointer m_Vertices;\n};\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nApplyTransformationToGeometry::ApplyTransformationToGeometry()\n{\n  m_RotationAngle = 0.0f;\n  m_RotationAxis[0] = 0.0f;\n  m_RotationAxis[1] = 0.0f;\n  m_RotationAxis[2] = 1.0f;\n\n  m_Translation[0] = 0.0f;\n  m_Translation[1] = 0.0f;\n  m_Translation[2] = 0.0f;\n\n  m_Scale[0] = 0.0f;\n  m_Scale[1] = 0.0f;\n  m_Scale[2] = 0.0f;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nApplyTransformationToGeometry::~ApplyTransformationToGeometry() = default;\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::setupFilterParameters()\n{\n  FilterParameterVectorType parameters;\n  {\n    LinkedChoicesFilterParameter::Pointer parameter = LinkedChoicesFilterParameter::New();\n    parameter->setHumanLabel(\"Transformation Type\");\n    parameter->setPropertyName(\"TransformationMatrixType\");\n    parameter->setSetterCallback(SIMPL_BIND_SETTER(ApplyTransformationToGeometry, this, TransformationMatrixType));\n    parameter->setGetterCallback(SIMPL_BIND_GETTER(ApplyTransformationToGeometry, this, TransformationMatrixType));\n    std::vector<QString> choices;\n    choices.push_back(\"No Transformation\");\n    choices.push_back(\"Pre-Computed Transformation Matrix\");\n    choices.push_back(\"Manual Transformation Matrix\");\n    choices.push_back(\"Rotation\");\n    choices.push_back(\"Translation\");\n    choices.push_back(\"Scale\");\n    parameter->setChoices(choices);\n    std::vector<QString> linkedProps = {\"ComputedTransformationMatrix\", \"ManualTransformationMatrix\", \"RotationAngle\", \"RotationAxis\", \"Translation\", \"Scale\"};\n    parameter->setLinkedProperties(linkedProps);\n    parameter->setEditable(false);\n    parameter->setCategory(FilterParameter::Category::Parameter);\n    parameters.push_back(parameter);\n  }\n  {\n    QStringList rHeaders, cHeaders;\n    std::vector<std::vector<double>> defaultTable;\n    for(size_t i = 0; i < 4; i++)\n    {\n      std::vector<double> row(4, 0);\n      row[i] = 1.0;\n      defaultTable.push_back(row);\n    }\n    m_ManualTransformationMatrix.setTableData(defaultTable);\n    parameters.push_back(SIMPL_NEW_DYN_TABLE_FP(\"Transformation Matrix\", ManualTransformationMatrix, FilterParameter::Category::Parameter, ApplyTransformationToGeometry, 2));\n  }\n  parameters.push_back(SIMPL_NEW_FLOAT_FP(\"Rotation Angle (Degrees)\", RotationAngle, FilterParameter::Category::Parameter, ApplyTransformationToGeometry, 3));\n  parameters.push_back(SIMPL_NEW_FLOAT_VEC3_FP(\"Rotation Axis (ijk)\", RotationAxis, FilterParameter::Category::Parameter, ApplyTransformationToGeometry, 3));\n  parameters.push_back(SIMPL_NEW_FLOAT_VEC3_FP(\"Translation\", Translation, FilterParameter::Category::Parameter, ApplyTransformationToGeometry, 4));\n  parameters.push_back(SIMPL_NEW_FLOAT_VEC3_FP(\"Scale\", Scale, FilterParameter::Category::Parameter, ApplyTransformationToGeometry, 5));\n  DataContainerSelectionFilterParameter::RequirementType dcReq;\n  IGeometry::Types geomTypes = {IGeometry::Type::Vertex, IGeometry::Type::Edge, IGeometry::Type::Triangle, IGeometry::Type::Quad, IGeometry::Type::Tetrahedral};\n  dcReq.dcGeometryTypes = geomTypes;\n  parameters.push_back(SIMPL_NEW_DC_SELECTION_FP(\"Geometry to Transform\", GeometryToTransform, FilterParameter::Category::RequiredArray, ApplyTransformationToGeometry, dcReq));\n  {\n    DataArraySelectionFilterParameter::RequirementType dasReq =\n        DataArraySelectionFilterParameter::CreateRequirement(SIMPL::TypeNames::Float, SIMPL::Defaults::AnyComponentSize, AttributeMatrix::Type::Generic, IGeometry::Type::Any);\n    parameters.push_back(SIMPL_NEW_DA_SELECTION_FP(\"Transformation Matrix\", ComputedTransformationMatrix, FilterParameter::Category::RequiredArray, ApplyTransformationToGeometry, dasReq, 1));\n  }\n  setFilterParameters(parameters);\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::readFilterParameters(AbstractFilterParametersReader* reader, int index)\n{\n  reader->openFilterGroup(this, index);\n  setManualTransformationMatrix(reader->readDynamicTableData(\"ManualTransformationMatrix\", getManualTransformationMatrix()));\n  setComputedTransformationMatrix(reader->readDataArrayPath(\"ComputedTransformationMatrix\", getComputedTransformationMatrix()));\n  setGeometryToTransform(reader->readDataArrayPath(\"GeometryToTransform\", getGeometryToTransform()));\n  setTransformationMatrixType(reader->readValue(\"TransformationMatrixType\", getTransformationMatrixType()));\n  setRotationAxis(reader->readFloatVec3(\"RotationAxis\", getRotationAxis()));\n  setRotationAngle(reader->readValue(\"RotationAngle\", getRotationAngle()));\n  setTranslation(reader->readFloatVec3(\"Translation\", getTranslation()));\n  setScale(reader->readFloatVec3(\"Scale\", getScale()));\n  reader->closeFilterGroup();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::dataCheck()\n{\n  clearErrorCode();\n  clearWarningCode();\n\n  IGeometry::Pointer igeom = getDataContainerArray()->getPrereqGeometryFromDataContainer<IGeometry>(this, getGeometryToTransform());\n\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n\n  if(!std::dynamic_pointer_cast<IGeometry2D>(igeom) && !std::dynamic_pointer_cast<IGeometry3D>(igeom) && !std::dynamic_pointer_cast<VertexGeom>(igeom) && !std::dynamic_pointer_cast<EdgeGeom>(igeom))\n  {\n    QString ss =\n        QObject::tr(\"Geometry to transform must be an unstructured geometry (Vertex, Edge, Triangle, Quadrilateral, or Tetrahedral), but the type is %1\").arg(igeom->getGeometryTypeAsString());\n    setErrorCondition(-702, ss);\n  }\n\n  std::vector<size_t> cDims = {4, 4};\n\n  switch(getTransformationMatrixType())\n  {\n  case 0: // No-Op\n  {\n    QString ss = QObject::tr(\"No transformation has been selected, so this filter will perform no operations\");\n    setWarningCondition(-701, ss);\n  }\n  case 1: // Transformation matrix from array\n  {\n    m_TransformationMatrixPtr = getDataContainerArray()->getPrereqArrayFromPath<DataArray<float>>(this, getComputedTransformationMatrix(), cDims);\n    if(m_TransformationMatrixPtr.lock())\n    {\n      m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n    }\n    break;\n  }\n  case 2: // Manual transformation matrix\n  {\n    if(getManualTransformationMatrix().getNumRows() != 4)\n    {\n      QString ss = QObject::tr(\"Manually entered transformation matrix must have exactly 4 rows\");\n      setErrorCondition(-702, ss);\n      return;\n    }\n    if(getManualTransformationMatrix().getNumCols() != 4)\n    {\n      QString ss = QObject::tr(\"Manually entered transformation matrix must have exactly 4 columns\");\n      setErrorCondition(-703, ss);\n      return;\n    }\n    std::vector<std::vector<double>> tableData = getManualTransformationMatrix().getTableData();\n    m_TransformationReference = FloatArrayType::CreateArray(1, cDims, \"_INTERNAL_USE_ONLY_ManualTransformationMatrix\", true);\n    m_TransformationReference->initializeWithZeros();\n    m_TransformationMatrixPtr = m_TransformationReference;\n    if(m_TransformationMatrixPtr.lock())\n    {\n      m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n      for(size_t i = 0; i < tableData.size(); i++)\n      {\n        std::vector<double> row = tableData[i];\n        for(size_t j = 0; j < row.size(); j++)\n        {\n          m_TransformationMatrix[4 * i + j] = static_cast<float>(row[j]);\n        }\n      }\n    }\n    break;\n  }\n  case 3: // Rotation via axis-angle\n  {\n    float rotAngle = m_RotationAngle * SIMPLib::Constants::k_PiOver180D;\n    OrientationF om = OrientationTransformation::ax2om<OrientationF, OrientationF>(OrientationF(m_RotationAxis[0], m_RotationAxis[1], m_RotationAxis[2], rotAngle));\n\n    m_TransformationReference = FloatArrayType::CreateArray(1, cDims, \"_INTERNAL_USE_ONLY_ManualTransformationMatrix\", true);\n    m_TransformationReference->initializeWithZeros();\n    m_TransformationMatrixPtr = m_TransformationReference;\n    if(m_TransformationMatrixPtr.lock())\n    {\n      m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n      for(size_t i = 0; i < 3; i++)\n      {\n        m_TransformationMatrix[4 * i + 0] = om[3 * i + 0];\n        m_TransformationMatrix[4 * i + 1] = om[3 * i + 1];\n        m_TransformationMatrix[4 * i + 2] = om[3 * i + 2];\n        m_TransformationMatrix[4 * i + 3] = 0.0f;\n      }\n      m_TransformationMatrix[4 * 3 + 3] = 1.0f;\n    }\n    break;\n  }\n  case 4: // Translation\n  {\n    m_TransformationReference = FloatArrayType::CreateArray(1, cDims, \"_INTERNAL_USE_ONLY_ManualTransformationMatrix\", true);\n    m_TransformationReference->initializeWithZeros();\n    m_TransformationMatrixPtr = m_TransformationReference;\n    if(m_TransformationMatrixPtr.lock())\n    {\n      m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n      m_TransformationMatrix[4 * 0 + 0] = 1.0f;\n      m_TransformationMatrix[4 * 1 + 1] = 1.0f;\n      m_TransformationMatrix[4 * 2 + 2] = 1.0f;\n      m_TransformationMatrix[4 * 0 + 3] = m_Translation[0];\n      m_TransformationMatrix[4 * 1 + 3] = m_Translation[1];\n      m_TransformationMatrix[4 * 2 + 3] = m_Translation[2];\n      m_TransformationMatrix[4 * 3 + 3] = 1.0f;\n    }\n    break;\n  }\n  case 5: // Scale\n  {\n    m_TransformationReference = FloatArrayType::CreateArray(1, cDims, \"_INTERNAL_USE_ONLY_ManualTransformationMatrix\", true);\n    m_TransformationReference->initializeWithZeros();\n    m_TransformationMatrixPtr = m_TransformationReference;\n    if(m_TransformationMatrixPtr.lock())\n    {\n      m_TransformationMatrix = m_TransformationMatrixPtr.lock()->getPointer(0);\n      m_TransformationMatrix[4 * 0 + 0] = m_Scale[0];\n      m_TransformationMatrix[4 * 1 + 1] = m_Scale[1];\n      m_TransformationMatrix[4 * 2 + 2] = m_Scale[2];\n      m_TransformationMatrix[4 * 3 + 3] = 1.0f;\n    }\n    break;\n  }\n  default: {\n    QString ss = QObject::tr(\"Invalid selection for transformation type\");\n    setErrorCondition(-701, ss);\n    break;\n  }\n  }\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::applyTransformation()\n{\n\n  IGeometry::Pointer igeom = getDataContainerArray()->getDataContainer(m_GeometryToTransform)->getGeometry();\n\n  SharedVertexList::Pointer vertexList;\n\n  if(IGeometry2D::Pointer igeom2D = std::dynamic_pointer_cast<IGeometry2D>(igeom))\n  {\n    vertexList = igeom2D->getVertices();\n  }\n  else if(IGeometry3D::Pointer igeom3D = std::dynamic_pointer_cast<IGeometry3D>(igeom))\n  {\n    vertexList = igeom3D->getVertices();\n  }\n  else if(VertexGeom::Pointer vertex = std::dynamic_pointer_cast<VertexGeom>(igeom))\n  {\n    vertexList = vertex->getVertices();\n  }\n  else if(EdgeGeom::Pointer edge = std::dynamic_pointer_cast<EdgeGeom>(igeom))\n  {\n    vertexList = edge->getVertices();\n  }\n  else\n  {\n    return;\n  }\n\n  using ProjectiveMatrix = Eigen::Matrix<float, 4, 4, Eigen::RowMajor>;\n  Eigen::Map<ProjectiveMatrix> transformation(m_TransformationMatrix);\n  m_TotalElements = vertexList->getNumberOfTuples();\n  // Allow data-based parallelization\n#if 1\n  ParallelDataAlgorithm dataAlg;\n  dataAlg.setRange(0, m_TotalElements);\n  dataAlg.execute(ApplyTransformationToGeometryImpl(*this, m_TransformationMatrix, vertexList));\n#else\n  // THis chunk of code will FORCE single threaded mode. Don't do this unless you really mean it.\n  ApplyTransformationToGeometryImpl doThis(*this, m_TransformationMatrix, vertexList);\n  doThis({0, vertexList->getNumberOfTuples()});\n#endif\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::execute()\n{\n  dataCheck();\n  if(getErrorCode() < 0)\n  {\n    return;\n  }\n  if(getWarningCode() < 0)\n  {\n    return;\n  }\n\n  if(m_TransformationMatrixType == 0)\n  {\n    return;\n  }\n  // Needed for Threaded Progress Messages\n  m_InstanceIndex = ++ApplyTransformationProgress::s_InstanceIndex;\n  ApplyTransformationProgress::s_ProgressValues[m_InstanceIndex] = 0;\n  ApplyTransformationProgress::s_LastProgressInt[m_InstanceIndex] = 0;\n\n  applyTransformation();\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::sendThreadSafeProgressMessage(int64_t counter)\n{\n  std::lock_guard<std::mutex> guard(m_ProgressMessage_Mutex);\n\n  int64_t& progCounter = ApplyTransformationProgress::s_ProgressValues[m_InstanceIndex];\n  progCounter += counter;\n  int64_t progressInt = static_cast<int64_t>((static_cast<float>(progCounter) / m_TotalElements) * 100.0f);\n\n  int64_t progIncrement = m_TotalElements / 100;\n  int64_t prog = 1;\n\n  int64_t& lastProgressInt = ApplyTransformationProgress::s_LastProgressInt[m_InstanceIndex];\n\n  if(progCounter > prog && lastProgressInt != progressInt)\n  {\n    QString ss = QObject::tr(\"Transforming || %1% Completed\").arg(progressInt);\n    notifyStatusMessage(ss);\n    prog += progIncrement;\n  }\n\n  lastProgressInt = progressInt;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nAbstractFilter::Pointer ApplyTransformationToGeometry::newFilterInstance(bool copyFilterParameters) const\n{\n  ApplyTransformationToGeometry::Pointer filter = ApplyTransformationToGeometry::New();\n  if(copyFilterParameters)\n  {\n    copyFilterParameterInstanceVariables(filter.get());\n  }\n  return filter;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ApplyTransformationToGeometry::getCompiledLibraryName() const\n{\n  return DREAM3DReviewConstants::DREAM3DReviewBaseName;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ApplyTransformationToGeometry::getBrandingString() const\n{\n  return \"DREAM3DReview\";\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ApplyTransformationToGeometry::getFilterVersion() const\n{\n  QString version;\n  QTextStream vStream(&version);\n  vStream << DREAM3DReview::Version::Major() << \".\" << DREAM3DReview::Version::Minor() << \".\" << DREAM3DReview::Version::Patch();\n  return version;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ApplyTransformationToGeometry::getGroupName() const\n{\n  return DREAM3DReviewConstants::FilterGroups::DREAM3DReviewFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQUuid ApplyTransformationToGeometry::getUuid() const\n{\n  return QUuid(\"{c681caf4-22f2-5885-bbc9-a0476abc72eb}\");\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ApplyTransformationToGeometry::getSubGroupName() const\n{\n  return DREAM3DReviewConstants::FilterSubGroups::RotationTransformationFilters;\n}\n\n// -----------------------------------------------------------------------------\n//\n// -----------------------------------------------------------------------------\nQString ApplyTransformationToGeometry::getHumanLabel() const\n{\n  return \"Apply Transformation to Geometry\";\n}\n\n// -----------------------------------------------------------------------------\nApplyTransformationToGeometry::Pointer ApplyTransformationToGeometry::NullPointer()\n{\n  return Pointer(static_cast<Self*>(nullptr));\n}\n\n// -----------------------------------------------------------------------------\nstd::shared_ptr<ApplyTransformationToGeometry> ApplyTransformationToGeometry::New()\n{\n  struct make_shared_enabler : public ApplyTransformationToGeometry\n  {\n  };\n  std::shared_ptr<make_shared_enabler> val = std::make_shared<make_shared_enabler>();\n  val->setupFilterParameters();\n  return val;\n}\n\n// -----------------------------------------------------------------------------\nQString ApplyTransformationToGeometry::getNameOfClass() const\n{\n  return QString(\"ApplyTransformationToGeometry\");\n}\n\n// -----------------------------------------------------------------------------\nQString ApplyTransformationToGeometry::ClassName()\n{\n  return QString(\"ApplyTransformationToGeometry\");\n}\n\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::setManualTransformationMatrix(const DynamicTableData& value)\n{\n  m_ManualTransformationMatrix = value;\n}\n\n// -----------------------------------------------------------------------------\nDynamicTableData ApplyTransformationToGeometry::getManualTransformationMatrix() const\n{\n  return m_ManualTransformationMatrix;\n}\n\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::setComputedTransformationMatrix(const DataArrayPath& value)\n{\n  m_ComputedTransformationMatrix = value;\n}\n\n// -----------------------------------------------------------------------------\nDataArrayPath ApplyTransformationToGeometry::getComputedTransformationMatrix() const\n{\n  return m_ComputedTransformationMatrix;\n}\n\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::setGeometryToTransform(const DataArrayPath& value)\n{\n  m_GeometryToTransform = value;\n}\n\n// -----------------------------------------------------------------------------\nDataArrayPath ApplyTransformationToGeometry::getGeometryToTransform() const\n{\n  return m_GeometryToTransform;\n}\n\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::setTransformationMatrixType(int value)\n{\n  m_TransformationMatrixType = value;\n}\n\n// -----------------------------------------------------------------------------\nint ApplyTransformationToGeometry::getTransformationMatrixType() const\n{\n  return m_TransformationMatrixType;\n}\n\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::setRotationAxis(const FloatVec3Type& value)\n{\n  m_RotationAxis = value;\n}\n\n// -----------------------------------------------------------------------------\nFloatVec3Type ApplyTransformationToGeometry::getRotationAxis() const\n{\n  return m_RotationAxis;\n}\n\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::setRotationAngle(float value)\n{\n  m_RotationAngle = value;\n}\n\n// -----------------------------------------------------------------------------\nfloat ApplyTransformationToGeometry::getRotationAngle() const\n{\n  return m_RotationAngle;\n}\n\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::setTranslation(const FloatVec3Type& value)\n{\n  m_Translation = value;\n}\n\n// -----------------------------------------------------------------------------\nFloatVec3Type ApplyTransformationToGeometry::getTranslation() const\n{\n  return m_Translation;\n}\n\n// -----------------------------------------------------------------------------\nvoid ApplyTransformationToGeometry::setScale(const FloatVec3Type& value)\n{\n  m_Scale = value;\n}\n\n// -----------------------------------------------------------------------------\nFloatVec3Type ApplyTransformationToGeometry::getScale() const\n{\n  return m_Scale;\n}\n", "meta": {"hexsha": "3e4c2bbf4cd4e21d5f99e108ae192ab5e540d30f", "size": 25174, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DREAM3DReviewFilters/ApplyTransformationToGeometry.cpp", "max_stars_repo_name": "mhitzem/DREAM3DReview", "max_stars_repo_head_hexsha": "e9350604d441f38e23a4d4871c98d827b7a3257b", "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": "DREAM3DReviewFilters/ApplyTransformationToGeometry.cpp", "max_issues_repo_name": "mhitzem/DREAM3DReview", "max_issues_repo_head_hexsha": "e9350604d441f38e23a4d4871c98d827b7a3257b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 18.0, "max_issues_repo_issues_event_min_datetime": "2017-09-01T23:13:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T12:58:57.000Z", "max_forks_repo_path": "DREAM3DReviewFilters/ApplyTransformationToGeometry.cpp", "max_forks_repo_name": "mhitzem/DREAM3DReview", "max_forks_repo_head_hexsha": "e9350604d441f38e23a4d4871c98d827b7a3257b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-09-01T23:15:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T13:24:19.000Z", "avg_line_length": 38.9088098918, "max_line_length": 198, "alphanum_fraction": 0.6258441249, "num_tokens": 5187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.359364152021239, "lm_q1q2_score": 0.20753113220619496}}
{"text": "/*******************************************************************************\n*\n*  Filename    : PlotLimit.cc\n*  Description : Macros For plotting confidence level limits\n*  Author      : Yi-Mu \"Enoch\" Chen [ ensc@hep1.phys.ntu.edu.tw ]\n*\n*******************************************************************************/\n#include \"ManagerUtils/Common/interface/ConfigReader.hpp\"\n#include \"ManagerUtils/Common/interface/STLUtils.hpp\"\n#include \"ManagerUtils/Maths/interface/Intersect.hpp\"\n#include \"ManagerUtils/Maths/interface/Parameter.hpp\"\n#include \"ManagerUtils/PlotUtils/interface/Common.hpp\"\n#include \"ManagerUtils/SampleMgr/interface/SampleMgrLoader.hpp\"\n\n#include \"TstarAnalysis/Common/interface/PlotStyle.hpp\"\n#include \"TstarAnalysis/LimitCalc/interface/Common.hpp\"\n#include \"TstarAnalysis/LimitCalc/interface/Limit.hpp\"\n\n#include <algorithm>\n#include <boost/algorithm/string.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/format.hpp>\n#include <fstream>\n#include <map>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include \"TFile.h\"\n#include \"TTree.h\"\n\nusing namespace std;\nusing namespace mgr;\n\n/*******************************************************************************\n*   Defining plotting control flow\n*******************************************************************************/\npair<Parameter, Parameter>\nMakeLimitPlot( const std::string& additionaltag )\n{\n  const map<double, double> xsec = GetXsectionMap();\n\n  TGraph* onesiggraph = MakeCalcGraph( xsec, additionaltag, explim, onesig_up, onesig_down );\n  TGraph* twosiggraph = MakeCalcGraph( xsec, additionaltag, explim, twosig_up, twosig_down );\n  TGraph* expgraph    = MakeCalcGraph( xsec, additionaltag, explim, skip, skip );\n  TGraph* obsgraph    = MakeCalcGraph( xsec, additionaltag, obslim, skip, skip );\n  TGraph* theorygraph = MakeTheoryGraph( xsec );\n\n  const double y_max = mgr::GetYmax( twosiggraph, obsgraph );\n  const double y_min = mgr::GetYmin( twosiggraph, obsgraph );\n  const double x_max = theorygraph->GetX()[theorygraph->GetN()-1];\n  const double x_min = theorygraph->GetX()[0];\n\n  // ----- Setting Styles  --------------------------------------------------------\n  tstar::SetOneSigmaStyle( onesiggraph );\n  tstar::SetTwoSigmaStyle( twosiggraph );\n  tstar::SetExpLimitStyle( expgraph );\n  tstar::SetObsLimitStyle( obsgraph );\n  tstar::SetTheoryStyle( theorygraph );\n\n  // Making object for plotting\n  TCanvas* c1 = mgr::NewCanvas();\n  mgr::SetSinglePad( c1 );\n\n  TMultiGraph* mg = new TMultiGraph();\n\n  mg->Add( twosiggraph );\n  mg->Add( onesiggraph );\n  mg->Add( theorygraph );\n  mg->Add( expgraph );\n  if( limnamer.CheckInput( \"drawdata\" ) ){\n    mg->Add( obsgraph );\n  }\n\n  mg->Draw( \"AL3\" );\n  mgr::SetAxis( mg );\n  mg->GetXaxis()->SetTitle( \"t* Mass (GeV/c^{2})\" );// MUST Be after draw!!\n  mg->GetYaxis()->SetTitle( \"#sigma(pp#rightarrow t*#bar{t}*) (pb)\" );// https://root.cern.ch/root/roottalk/roottalk09/0078.html\n  mg->GetXaxis()->SetLimits( x_min, x_max );\n  mg->SetMaximum( y_max*300. );\n  mg->SetMinimum( y_min*0.3 );\n\n  // Making legend\n  const double legend_x_min = 0.55;\n  const double legend_y_min = 0.50;\n  TLegend* l                = mgr::NewLegend( legend_x_min, legend_y_min );\n  l->AddEntry( theorygraph,    \"R-S Model\",              \"lf\" );\n  l->AddEntry( (TObject*)NULL, \"\",                       \"\" );\n  l->AddEntry( (TObject*)NULL, \"95% CL_{s} upper limit\", \"\" );\n  l->AddEntry( obsgraph,       \"Observed\",               \"l\" );\n  l->AddEntry( expgraph,       \"Medium expected\",        \"l\" );\n  l->AddEntry( onesiggraph,    \"68% expected\",           \"f\" );\n  l->AddEntry( twosiggraph,    \"95% expected\",           \"f\" );\n  l->Draw();\n\n\n  // Additional titles settings\n  mgr::DrawCMSLabel();\n  mgr::DrawLuminosity( limnamer.GetExt<double>( \"era\", \"Lumi\" ) );\n\n  // Writing additional text\n  const string rootlabel = limnamer.GetChannelEXT( \"Root Name\" );\n  // const string fitmethod = limnamer.GetExt<string>( \"fitmethod\", \"Full Name\" );\n  // const string funcname  = limnamer.GetExt<string>( \"fitfunc\", \"Full Name\" );\n  boost::format explimfmt( \"Expected: %s GeV/c^{2}\" );\n  boost::format obslimfmt( \"Observed: %s GeV/c^{2}\" );\n\n  mgr::LatexMgr latex;\n  latex.SetOrigin( PLOT_X_MIN, PLOT_Y_MAX + TEXT_MARGIN/2, BOTTOM_LEFT )\n  .WriteLine( rootlabel );\n  // .WriteLine( fitmethod )\n  // .WriteLine( funcname );\n\n  // Cannot have Latex style spacing '\\,'\n  const Parameter explim_err = GetInterSect( theorygraph, onesiggraph );\n  const Parameter obslim_err = GetInterSect( theorygraph, obsgraph );\n  const string explim_str    = FloatingPoint( explim_err.CentralValue(), 0, false );\n  const string obslim_str    = FloatingPoint( obslim_err.CentralValue(), 0, false );\n\n  latex.SetOrigin( PLOT_X_TEXT_MAX, legend_y_min-TEXT_MARGIN, TOP_RIGHT );\n  latex.WriteLine( boost::str( explimfmt % explim_str ) );\n  if( limnamer.CheckInput( \"drawdata\" ) ){\n    latex.WriteLine( boost::str( obslimfmt % obslim_str ) );\n  }\n\n\n  // ----- Saving and cleaning up  ------------------------------------------------\n  c1->SetLogy( kTRUE );\n  c1->Update();\n\n  if( limnamer.CheckInput( \"seed\" ) ){\n    limnamer.AddCutOptions( \"seed\" );\n  }\n\n  if( limnamer.CheckInput( \"rMin\" ) ){\n    limnamer.AddCutOptions( \"rMin\" );\n  }\n\n  if( limnamer.CheckInput( \"rMax\" ) ){\n    limnamer.AddCutOptions( \"rMax\" );\n  }\n\n  mgr::SaveToROOT( c1, limnamer.PlotRootFile(), limnamer.OptFileName( \"\", \"limit\", additionaltag ) );\n  mgr::SaveToPDF( c1, limnamer.PlotFileName( \"limit\", additionaltag ) );\n  delete onesiggraph;\n  delete twosiggraph;\n  delete obsgraph;\n  delete expgraph;\n  delete theorygraph;\n  delete mg;\n  delete l;\n  delete c1;\n\n  return make_pair( explim_err, obslim_err );\n}\n\n\n/*******************************************************************************\n*   Filling out map from master file\n*******************************************************************************/\nmap<double, double>\nGetXsectionMap()\n{\n  const string theoryfile = limnamer.SubPackageDir() / \"data/excitedtoppair13TeV.dat\";\n  if( !boost::filesystem::exists( theoryfile ) ){\n    cerr << \"Error! File containing theoretical cross section doesn't exists!\" << endl;\n    cerr << \"Check file: \" << theoryfile << endl;\n    throw std::runtime_error( \"File not found\" );\n  }\n\n  ifstream xsec_file( theoryfile );\n  string line;\n  map<double, double> ans;\n  double energy, mass, xsec_value;\n\n  while( getline( xsec_file, line ) ){\n    istringstream linestream( line );\n    linestream >> energy >> mass >> xsec_value;\n    ans[mass] = xsec_value * 1000.;\n  }\n\n  xsec_file.close();\n  return ans;\n}\n\n\n/*******************************************************************************\n*   Object generation functions\n*******************************************************************************/\nTGraphAsymmErrors*\nMakeTheoryGraph( const map<double, double>& xsec )\n{\n  // Making the PDF/QCD scale error Graph objects for linear interpolation\n  const vector<string> siglist = limnamer.MasterConfig().GetStaticStringList( \"Signal List\" );\n  TGraph* errorupgraph         = new TGraph( siglist.size() );\n  TGraph* errordowngraph       = new TGraph( siglist.size() );\n\n  for( size_t i = 0; i < siglist.size(); ++i ){\n    const auto& sig   = siglist.at( i );\n    const double mass = GetInt( sig );\n\n    mgr::SampleGroup sigmgr( sig, limnamer.MasterConfig() );\n\n    const mgr::Parameter pdferr   = sigmgr.Sample().PDFUncertainty();\n    const mgr::Parameter scaleerr = sigmgr.Sample().QCDScaleUncertainty();\n    const mgr::Parameter toterr   = pdferr * scaleerr;\n\n    errorupgraph->SetPoint( i, mass, toterr.RelUpperError() );\n    errordowngraph->SetPoint( i, mass, toterr.RelLowerError() );\n  }\n\n  // Making the main theoretical curve line\n  TGraphAsymmErrors* graph = new TGraphAsymmErrors();\n\n  for( const auto& point : xsec ){\n    const double mass = point.first;\n    if( mass < 650 || mass > 1650 ){ continue; }\n    const double thisxsec = point.second;\n    const double xsecup   = thisxsec * errorupgraph->Eval( mass );\n    const double xsecdown = thisxsec * errordowngraph->Eval( mass );\n\n    const int newbin = graph->GetN();\n    graph->SetPoint( newbin, mass, thisxsec );\n    graph->SetPointError(\n      newbin,\n      0, 0,// No X error for now\n      xsecdown,\n      xsecup\n      );\n  }\n\n  delete errorupgraph;\n  delete errordowngraph;\n\n  return graph;\n}\n\n/******************************************************************************/\nextern const int explim      = 2;\nextern const int obslim      = 5;\nextern const int onesig_up   = 3;\nextern const int onesig_down = 1;\nextern const int twosig_up   = 4;\nextern const int twosig_down = 0;\nextern const int skip        = -1;\n\n\nextern TGraph*\nMakeCalcGraph(\n  const std::map<double, double>& xsec,\n  const string& additionaltag,\n  const int centralentry,\n  const int uperrorentry,\n  const int downerrorentry\n  )\n{\n  const vector<string> siglist = limnamer.MasterConfig().GetStaticStringList( \"Signal List\" );\n  TGraphAsymmErrors* graph     = new TGraphAsymmErrors( siglist.size() );\n\n  unsigned bin = 0;\n\n  for( const auto& sig : siglist ){\n    const double mass     = GetInt( sig );\n    const double expxsec  = xsec.at( mass );\n    const string filename = limnamer.RootFileName( \"combine\", sig, additionaltag );\n\n    // Geting contents of higgs combine output file\n    TFile* file = TFile::Open( filename.c_str() );\n    if( !file ){\n      fprintf( stderr, \"Cannot open file (%s), skipping sample for %s\\n\",\n        filename.c_str(),\n        sig.c_str() );\n      continue;\n    }\n\n    double temp;\n    TTree* tree = ( (TTree*)file->Get( \"limit\" ) );\n    tree->SetBranchAddress( \"limit\", &temp );\n\n    // Getting the entries\n    tree->GetEntry( centralentry );\n    const double central = temp * expxsec;\n\n    if( uperrorentry != skip ){ tree->GetEntry( uperrorentry ); }\n    const double errorup = ( uperrorentry != skip ) ?\n                           temp*expxsec - central :  0;\n\n    if( downerrorentry != skip ){ tree->GetEntry( downerrorentry ); }\n    const double errordown = ( downerrorentry != skip ) ?\n                             central - temp*expxsec :  0;\n\n    // closing file\n    file->Close();\n\n    graph->SetPoint( bin, mass, central );\n    graph->SetPointError( bin, 50, 50, errordown, errorup );\n    cout << boost::format( \"%u %4.0lf  %8.6lf[+%8.6lf/-%8.6lf]\" )\n      % bin % mass % central % errorup % errordown << endl;\n    ++bin;\n\n    delete file;\n  }\n\n  return graph;\n}\n\n\n/*******************************************************************************\n*   Function for calculating intersect points\n*******************************************************************************/\n\nParameter\nGetInterSect( const TGraph* graph, const TGraph* errgraph )\n{\n  double y             = 0;\n  double explimit      = errgraph->GetX()[0];\n  double explimit_up   = errgraph->GetX()[0];\n  double explimit_down = errgraph->GetX()[0];\n\n  for( int i = 0; i < graph->GetN()-1; ++i ){\n    for( int j = 0; j < errgraph->GetN()-1; ++j ){\n\n      const double graphmass        = graph->GetX()[i];\n      const double graphmassnext    = graph->GetX()[i+1];\n      const double graphval         = graph->GetY()[i];\n      const double graphvalnext     = graph->GetY()[i+1];\n      const double graphvalup       = graph->GetErrorYhigh( i ) + graphval;\n      const double graphvalupnext   = graph->GetErrorYhigh( i+1 ) + graphvalnext;\n      const double graphvaldown     = graphval - graph->GetErrorYlow( i );\n      const double graphvaldownnext = graphvalnext - graph->GetErrorYlow( i+1 );\n\n      const double errgraphmass     = errgraph->GetX()[j];\n      const double errgraphmassnext = errgraph->GetX()[j+1];\n      const double errgraphval      = errgraph->GetY()[j];\n      const double errgraphvalnext  = errgraph->GetY()[j+1];\n      const double hierr            = errgraph->GetErrorYhigh( j ) + errgraphval;\n      const double hierrnext        = errgraph->GetErrorYhigh( j+1 ) + errgraphvalnext;\n      const double loerr            = errgraphval - errgraph->GetErrorYlow( j );\n      const double loerrnext        = errgraphvalnext - errgraph->GetErrorYlow( j+1 );\n\n      // Central value intersect\n      Intersect(\n        graphmass, graphval,\n        graphmassnext, graphvalnext,\n        errgraphmass, errgraphval,\n        errgraphmassnext, errgraphvalnext,\n        explimit, y\n        );\n\n      // Lower theretical band intersect with upper limit band\n      Intersect(\n        graphmass, graphvaldown,\n        graphmassnext, graphvaldownnext,\n        errgraphmass, hierr,\n        errgraphmassnext, hierrnext,\n        explimit_down, y\n        );\n\n      // Upper theoretical band intersec with lower limit band\n      Intersect(\n        graphmass, graphvalup,\n        graphmassnext, graphvalupnext,\n        errgraphmass, loerr,\n        errgraphmassnext, loerrnext,\n        explimit_up, y\n        );\n    }\n  }\n\n  return Parameter( explimit, explimit_up - explimit, explimit - explimit_down );\n}\n", "meta": {"hexsha": "85cabab05306d1dd4f6d1c46ad12888aeae91878", "size": 12912, "ext": "cc", "lang": "C++", "max_stars_repo_path": "LimitCalc/src/PlotLimit.cc", "max_stars_repo_name": "NTUHEP-Tstar/TstarAnalysis", "max_stars_repo_head_hexsha": "d3bcdf6f0fd19b9a34bbacb1052143856917bea7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LimitCalc/src/PlotLimit.cc", "max_issues_repo_name": "NTUHEP-Tstar/TstarAnalysis", "max_issues_repo_head_hexsha": "d3bcdf6f0fd19b9a34bbacb1052143856917bea7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LimitCalc/src/PlotLimit.cc", "max_forks_repo_name": "NTUHEP-Tstar/TstarAnalysis", "max_forks_repo_head_hexsha": "d3bcdf6f0fd19b9a34bbacb1052143856917bea7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7096774194, "max_line_length": 128, "alphanum_fraction": 0.60494114, "num_tokens": 3410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.35936413829896496, "lm_q1q2_score": 0.20753112428164536}}
{"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file portfolio/builders/vanillaoption.hpp\n    \\brief Abstract engine builders for European and American Options\n    \\ingroup builders\n*/\n\n#pragma once\n\n#include <boost/make_shared.hpp>\n#include <ored/portfolio/builders/cachingenginebuilder.hpp>\n#include <ored/portfolio/enginefactory.hpp>\n#include <ored/utilities/indexparser.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/to_string.hpp>\n#include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp>\n#include <ql/pricingengines/vanilla/fdblackscholesvanillaengine.hpp>\n#include <ql/processes/blackscholesprocess.hpp>\n#include <ql/version.hpp>\n#include <qle/pricingengines/analyticcashsettledeuropeanengine.hpp>\n#include <qle/pricingengines/baroneadesiwhaleyengine.hpp>\n#include <qle/termstructures/blackmonotonevarvoltermstructure.hpp>\n#include <qle/termstructures/pricetermstructureadapter.hpp>\n\nnamespace ore {\nnamespace data {\n\ntemplate <class T, typename... Args> class CachingOptionEngineBuilder : public CachingPricingEngineBuilder<T, Args...> {\npublic:\n    CachingOptionEngineBuilder(const string& model, const string& engine, const set<string>& tradeTypes,\n                               const AssetClass& assetClass)\n        : CachingPricingEngineBuilder<T, Args...>(model, engine, tradeTypes), assetClass_(assetClass) {}\n\nprotected:\n    boost::shared_ptr<GeneralizedBlackScholesProcess> getBlackScholesProcess(const string& assetName,\n                                                                             const Currency& ccy,\n                                                                             const AssetClass& assetClassUnderlying,\n                                                                             const std::vector<Time>& timePoints = {}) {\n\n        using VVTS = QuantExt::BlackMonotoneVarVolTermStructure;\n        string config = this->configuration(ore::data::MarketContext::pricing);\n\n        if (assetClassUnderlying == AssetClass::EQ) {\n            Handle<BlackVolTermStructure> vol = this->market_->equityVol(assetName, config);\n            if (!timePoints.empty()) {\n                vol = Handle<BlackVolTermStructure>(boost::make_shared<VVTS>(vol, timePoints));\n                vol->enableExtrapolation();\n            }\n            return boost::make_shared<GeneralizedBlackScholesProcess>(\n                this->market_->equitySpot(assetName, config), this->market_->equityDividendCurve(assetName, config),\n                this->market_->equityForecastCurve(assetName, config), vol);\n\n        } else if (assetClassUnderlying == AssetClass::FX) {\n            const string& ccyPairCode = assetName + ccy.code();\n            Handle<BlackVolTermStructure> vol = this->market_->fxVol(ccyPairCode, config);\n            if (!timePoints.empty()) {\n                vol = Handle<BlackVolTermStructure>(boost::make_shared<VVTS>(vol, timePoints));\n                vol->enableExtrapolation();\n            }\n            return boost::make_shared<GeneralizedBlackScholesProcess>(\n                this->market_->fxSpot(ccyPairCode, config), this->market_->discountCurve(assetName, config),\n                this->market_->discountCurve(ccy.code(), config), vol);\n\n        } else if (assetClassUnderlying == AssetClass::COM) {\n\n            Handle<BlackVolTermStructure> vol = this->market_->commodityVolatility(assetName, config);\n            if (!timePoints.empty()) {\n                vol = Handle<BlackVolTermStructure>(boost::make_shared<VVTS>(vol, timePoints));\n                vol->enableExtrapolation();\n            }\n\n            // Create the commodity convenience yield curve for the process\n            Handle<QuantExt::PriceTermStructure> priceCurve = this->market_->commodityPriceCurve(assetName, config);\n            Handle<Quote> commoditySpot(boost::make_shared<QuantExt::DerivedPriceQuote>(priceCurve));\n            Handle<YieldTermStructure> discount = this->market_->discountCurve(ccy.code(), config);\n            Handle<YieldTermStructure> yield(\n                boost::make_shared<QuantExt::PriceTermStructureAdapter>(*priceCurve, *discount));\n            yield->enableExtrapolation();\n\n            return boost::make_shared<GeneralizedBlackScholesProcess>(commoditySpot, yield, discount, vol);\n\n        } else {\n            QL_FAIL(\"Asset class of \" << (int)assetClassUnderlying << \" not recognized.\");\n        }\n    }\n    AssetClass assetClass_;\n};\n\n//! Abstract Engine Builder for Vanilla Options\n/*! Pricing engines are cached by asset/currency\n\n    \\ingroup builders\n */\nclass VanillaOptionEngineBuilder\n    : public CachingOptionEngineBuilder<string, const string&, const Currency&, const AssetClass&, const Date&> {\npublic:\n    VanillaOptionEngineBuilder(const string& model, const string& engine, const set<string>& tradeTypes,\n                               const AssetClass& assetClass, const Date& expiryDate)\n        : CachingOptionEngineBuilder(model, engine, tradeTypes, assetClass), expiryDate_(expiryDate) {}\n\n    boost::shared_ptr<PricingEngine> engine(const string& assetName, const Currency& ccy, const Date& expiryDate) {\n        return CachingPricingEngineBuilder<string, const string&, const Currency&, const AssetClass&,\n                                           const Date&>::engine(assetName, ccy, assetClass_, expiryDate);\n    }\n\n    boost::shared_ptr<PricingEngine> engine(const Currency& ccy1, const Currency& ccy2, const Date& expiryDate) {\n        return CachingPricingEngineBuilder<string, const string&, const Currency&, const AssetClass&,\n                                           const Date&>::engine(ccy1.code(), ccy2, assetClass_, expiryDate);\n    }\n\nprotected:\n    virtual string keyImpl(const string& assetName, const Currency& ccy, const AssetClass& assetClassUnderlying,\n                           const Date& expiryDate) override {\n        return assetName + \"/\" + ccy.code() + \"/\" + to_string(expiryDate);\n    }\n\n    Date expiryDate_;\n};\n\n//! Abstract Engine Builder for European Vanilla Options\n/*! Pricing engines are cached by asset/currency\n\n    \\ingroup builders\n */\nclass EuropeanOptionEngineBuilder : public VanillaOptionEngineBuilder {\npublic:\n    EuropeanOptionEngineBuilder(const string& model, const set<string>& tradeTypes, const AssetClass& assetClass)\n        : VanillaOptionEngineBuilder(model, \"AnalyticEuropeanEngine\", tradeTypes, assetClass, Date()) {}\n\nprotected:\n    virtual boost::shared_ptr<PricingEngine> engineImpl(const string& assetName, const Currency& ccy,\n                                                        const AssetClass& assetClassUnderlying,\n                                                        const Date& expiryDate) override {\n        string key = keyImpl(assetName, ccy, assetClassUnderlying, expiryDate);\n        boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp =\n            getBlackScholesProcess(assetName, ccy, assetClassUnderlying);\n        Handle<YieldTermStructure> discountCurve =\n            market_->discountCurve(ccy.code(), configuration(MarketContext::pricing));\n        return boost::make_shared<QuantLib::AnalyticEuropeanEngine>(gbsp, discountCurve);\n    }\n};\n\n/*! European cash-settled option engine builder\n    \\ingroup builders\n */\nclass EuropeanCSOptionEngineBuilder : public VanillaOptionEngineBuilder {\npublic:\n    EuropeanCSOptionEngineBuilder(const string& model, const set<string>& tradeTypes, const AssetClass& assetClass)\n        : VanillaOptionEngineBuilder(model, \"AnalyticCashSettledEuropeanEngine\", tradeTypes, assetClass, Date()) {}\n\nprotected:\n    virtual boost::shared_ptr<PricingEngine> engineImpl(const string& assetName, const Currency& ccy,\n                                                        const AssetClass& assetClassUnderlying,\n                                                        const Date& expiryDate) override {\n        string key = keyImpl(assetName, ccy, assetClassUnderlying, expiryDate);\n        boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp =\n            getBlackScholesProcess(assetName, ccy, assetClassUnderlying);\n        Handle<YieldTermStructure> discountCurve =\n            market_->discountCurve(ccy.code(), configuration(MarketContext::pricing));\n        return boost::make_shared<QuantExt::AnalyticCashSettledEuropeanEngine>(gbsp, discountCurve);\n    }\n};\n\n//! Abstract Engine Builder for American Vanilla Options\n/*! Pricing engines are cached by asset/currency\n\n    \\ingroup builders\n */\nclass AmericanOptionEngineBuilder : public VanillaOptionEngineBuilder {\npublic:\n    AmericanOptionEngineBuilder(const string& model, const string& engine, const set<string>& tradeTypes,\n                                const AssetClass& assetClass, const Date& expiryDate)\n        : VanillaOptionEngineBuilder(model, engine, tradeTypes, assetClass, expiryDate) {}\n};\n\n//! Abstract Engine Builder for American Vanilla Options using Finite Difference Method\n/*! Pricing engines are cached by asset/currency\n\n    \\ingroup builders\n */\nclass AmericanOptionFDEngineBuilder : public AmericanOptionEngineBuilder {\npublic:\n    AmericanOptionFDEngineBuilder(const string& model, const set<string>& tradeTypes, const AssetClass& assetClass,\n                                  const Date& expiryDate)\n        : AmericanOptionEngineBuilder(model, \"FdBlackScholesVanillaEngine\", tradeTypes, assetClass, expiryDate) {}\n\nprotected:\n    virtual boost::shared_ptr<PricingEngine> engineImpl(const string& assetName, const Currency& ccy,\n                                                        const AssetClass& assetClass, const Date& expiryDate) override {\n        // We follow the way FdBlackScholesBarrierEngine determines maturity for time grid generation\n        Handle<YieldTermStructure> riskFreeRate =\n            market_->discountCurve(ccy.code(), configuration(ore::data::MarketContext::pricing));\n        Time expiry = riskFreeRate->dayCounter().yearFraction(riskFreeRate->referenceDate(), expiryDate);\n        QL_REQUIRE(expiry > 0.0, \"FdBlackScholesVanillaEngine expects a positive time to expiry but got \"\n                                     << expiry << \" for an expiry date \" << io::iso_date(expiryDate) << \".\");\n\n        FdmSchemeDesc scheme = parseFdmSchemeDesc(engineParameter(\"Scheme\"));\n        Size tGrid = (Size)(ore::data::parseInteger(engineParameter(\"TimeGridPerYear\")) * expiry);\n        Size xGrid = ore::data::parseInteger(engineParameter(\"XGrid\"));\n        Size dampingSteps = ore::data::parseInteger(engineParameter(\"DampingSteps\"));\n        bool monotoneVar = ore::data::parseBool(engineParameter(\"EnforceMonotoneVariance\", \"\", false, \"true\"));\n\n        boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp;\n\n        if (monotoneVar) {\n            // Replicate the construction of time grid in FiniteDifferenceModel::rollbackImpl\n            // This time grid is required to build a BlackMonotoneVarVolTermStructure which\n            // ensures monotonic variance along the time grid\n            const Size totalSteps = tGrid + dampingSteps;\n            std::vector<Time> timePoints(totalSteps + 1);\n            Array timePointsArray(totalSteps, expiry, -expiry / totalSteps);\n            timePoints[0] = 0.0;\n            for (Size i = 0; i < totalSteps; i++)\n                timePoints[timePoints.size() - i - 1] = timePointsArray[i];\n            timePoints.insert(std::upper_bound(timePoints.begin(), timePoints.end(), 0.99 / 365), 0.99 / 365);\n            gbsp = getBlackScholesProcess(assetName, ccy, assetClass, timePoints);\n        } else {\n            gbsp = getBlackScholesProcess(assetName, ccy, assetClass);\n        }\n        return boost::make_shared<FdBlackScholesVanillaEngine>(gbsp, tGrid, xGrid, dampingSteps, scheme);\n    }\n};\n\n//! Abstract Engine Builder for American Vanilla Options using Barone Adesi Whaley Approximation\n/*! Pricing engines are cached by asset/currency\n\n    \\ingroup builders\n */\nclass AmericanOptionBAWEngineBuilder : public AmericanOptionEngineBuilder {\npublic:\n    AmericanOptionBAWEngineBuilder(const string& model, const set<string>& tradeTypes, const AssetClass& assetClass)\n        : AmericanOptionEngineBuilder(model, \"BaroneAdesiWhaleyApproximationEngine\", tradeTypes, assetClass, Date()) {}\n\nprotected:\n    virtual boost::shared_ptr<PricingEngine> engineImpl(const string& assetName, const Currency& ccy,\n                                                        const AssetClass& assetClass, const Date& expiryDate) override {\n        boost::shared_ptr<GeneralizedBlackScholesProcess> gbsp = getBlackScholesProcess(assetName, ccy, assetClass);\n        return boost::make_shared<QuantExt::BaroneAdesiWhaleyApproximationEngine>(gbsp);\n    }\n};\n\n} // namespace data\n} // namespace ore\n", "meta": {"hexsha": "297702cc870ef39116c9cf3ef1407165668ae419", "size": 13381, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "OREData/ored/portfolio/builders/vanillaoption.hpp", "max_stars_repo_name": "nvolfango/Engine", "max_stars_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-30T17:24:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-30T17:24:17.000Z", "max_issues_repo_path": "OREData/ored/portfolio/builders/vanillaoption.hpp", "max_issues_repo_name": "zhangjiayin/Engine", "max_issues_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OREData/ored/portfolio/builders/vanillaoption.hpp", "max_forks_repo_name": "zhangjiayin/Engine", "max_forks_repo_head_hexsha": "a5ee0fc09d5a50ab36e50d55893b6e484d6e7004", "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": 51.4653846154, "max_line_length": 120, "alphanum_fraction": 0.6826096704, "num_tokens": 2879, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.20749658557099399}}
{"text": "/*    Copyright (c) 2010-2018, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n *\n *    References\n *      Klothakis, A. and Nikolos, I., “Modeling of Rarefied Hypersonic Flows Using the Massively\n *        Parallel DSMC Kernel “SPARTA”,” in 8th GRACM International Congress on Computational Mechanics,\n *        Volos, Greece, July 2015.\n *      Dirkx, D. and Mooij, E., Conceptual Shape Optimization of Entry Vehicles. Springer, 2017.\n */\n\n#include <boost/make_shared.hpp>\n#include <boost/assign/list_of.hpp>\n\n#include <Eigen/Geometry>\n\n#include \"Tudat/InputOutput/basicInputOutput.h\"\n#include \"Tudat/InputOutput/matrixTextFileReader.h\"\n#include \"Tudat/InputOutput/spartaDataReader.h\"\n#include \"Tudat/InputOutput/spartaInputOutput.h\"\n\n#include \"Tudat/Astrodynamics/Aerodynamics/rarefiedFlowAnalysis.h\"\n\nnamespace tudat\n{\n\nnamespace aerodynamics\n{\n\nusing namespace unit_conversions;\nusing namespace input_output;\n\n//! Returns default values of altitude for use in RarefiedFlowAnalysis.\nstd::vector< double > getDefaultRarefiedFlowAltitudePoints(\n        const std::string& targetPlanet )\n{\n    std::vector< double > altitudePoints;\n\n    // Set default points for Earth.\n    if ( targetPlanet == \"Earth\" )\n    {\n        altitudePoints.resize( 5 );\n        altitudePoints[ 0 ] = 225.0e3;\n        altitudePoints[ 1 ] = 250.0e3;\n        altitudePoints[ 2 ] = 300.0e3;\n        altitudePoints[ 3 ] = 400.0e3;\n        altitudePoints[ 4 ] = 600.0;\n    }\n    // Set default points for Mars.\n    else if ( targetPlanet == \"Mars\" )\n    {\n        altitudePoints.resize( 5 );\n        altitudePoints[ 0 ] = 125.0e3;\n        altitudePoints[ 1 ] = 150.0e3;\n        altitudePoints[ 2 ] = 200.0e3;\n        altitudePoints[ 3 ] = 300.0e3;\n        altitudePoints[ 4 ] = 500.0e3;\n    }\n    // Give error otherwise.\n    else\n    {\n        throw std::runtime_error( \"Error in altitude range selection for SPARTA simulation. \"\n                                  \"Planet not supported.\" );\n    }\n    return altitudePoints;\n}\n\n//! Returns default values of Mach number for use in RarefiedFlowAnalysis.\nstd::vector< double > getDefaultRarefiedFlowMachPoints(\n        const std::string& machRegime )\n{\n    std::vector< double > machPoints;\n\n    // Set default points for full hypersonic analysis.\n    if ( machRegime == \"Full\" )\n    {\n        machPoints.resize( 6 );\n\n        machPoints[ 0 ] = 3.0;\n        machPoints[ 1 ] = 4.0;\n        machPoints[ 2 ] = 5.0;\n        machPoints[ 3 ] = 8.0;\n        machPoints[ 4 ] = 10.0;\n        machPoints[ 5 ] = 20.0;\n    }\n    // Set default points for low hypersonic analysis.\n    else if ( machRegime == \"Low\" )\n    {\n        machPoints.resize( 5 );\n        machPoints[ 0 ] = 3.0;\n        machPoints[ 1 ] = 4.0;\n        machPoints[ 2 ] = 5.0;\n        machPoints[ 3 ] = 8.0;\n        machPoints[ 4 ] = 10.0;\n    }\n    // Set default points for high hypersonic analysis.\n    else if ( machRegime == \"High\" )\n    {\n        machPoints.resize( 4 );\n        machPoints[ 0 ] = 5.0;\n        machPoints[ 1 ] = 8.0;\n        machPoints[ 2 ] = 10.0;\n        machPoints[ 3 ] = 20.0;\n    }\n    return machPoints;\n}\n\n//! Returns default values of angle of attack for use in RarefiedFlowAnalysis.\nstd::vector< double > getDefaultRarefiedFlowAngleOfAttackPoints(\n        const std::string& angleOfAttackRegime )\n{\n    std::vector< double > angleOfAttackPoints;\n\n    // Set default angles of attack\n    double a = - 35;\n    while ( a <= 35 )\n    {\n        angleOfAttackPoints.push_back( convertDegreesToRadians( a ) );\n        a += 5;\n    }\n\n    // Add extra points if required\n    if ( angleOfAttackRegime == \"Full\" )\n    {\n        std::vector< double > frontExtension = { convertDegreesToRadians( -85.0 ),\n                                                 convertDegreesToRadians( -70.0 ),\n                                                 convertDegreesToRadians( -55.0 ),\n                                                 convertDegreesToRadians( -40.0 ) };\n        std::vector< double > rearExtension = { convertDegreesToRadians( 40.0 ),\n                                                convertDegreesToRadians( 55.0 ),\n                                                convertDegreesToRadians( 70.0 ),\n                                                convertDegreesToRadians( 85.0 ) };\n        angleOfAttackPoints.insert( angleOfAttackPoints.begin( ), frontExtension.begin( ), frontExtension.end( ) );\n        angleOfAttackPoints.insert( angleOfAttackPoints.end( ), rearExtension.begin( ), rearExtension.end( ) );\n    }\n    return angleOfAttackPoints;\n}\n\n//! Function to sort the rows of a matrix, based on the specified column and specified order.\nEigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > sortMatrixRows(\n        const Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor >& matrixToBeSorted,\n        const int referenceColumn, const bool descendingOrder )\n{\n    // Declare eventual output vector\n    Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > sortedMatrix;\n    sortedMatrix.resizeLike( matrixToBeSorted );\n\n    // Loop over rows and assign to new matrix\n    Eigen::Matrix< double, 1, Eigen::Dynamic, Eigen::RowMajor > currentRow;\n    for ( unsigned int i = 0; i < matrixToBeSorted.rows( ); i++ )\n    {\n        // Retrieve each row in 'scrambled order' and assign it to the new matrix\n        currentRow = matrixToBeSorted.row( i );\n\n        // Based on requested order\n        if ( descendingOrder )\n        {\n            sortedMatrix.row( matrixToBeSorted.rows( ) - currentRow[ referenceColumn ] ) = currentRow;\n            // no (- 1)'s are needed since both are defined starting from 1\n        }\n        else\n        {\n            sortedMatrix.row( currentRow[ referenceColumn ] - 1 ) = currentRow;\n        }\n    }\n\n    // Give output\n    return sortedMatrix;\n}\n\n//! Default constructor.\nRarefiedFlowAnalysis::RarefiedFlowAnalysis(\n        const std::string& SPARTAExecutable,\n        const std::vector< std::vector< double > >& dataPointsOfIndependentVariables,\n        boost::shared_ptr< TabulatedAtmosphere > atmosphereModel,\n        const std::string& simulationGases,\n        const std::string& geometryFileUser,\n        const double referenceArea,\n        const double referenceLength,\n        const int referenceAxis,\n        const Eigen::Vector3d& momentReferencePoint,\n        const double gridSpacing,\n        const double simulatedParticlesPerCell,\n        const double wallTemperature,\n        const double accommodationCoefficient,\n        const bool printProgressInCommandWindow,\n        const std::string MPIExecutable,\n        const unsigned int numberOfCores ) :\n    AerodynamicCoefficientGenerator< 3, 6 >(\n          dataPointsOfIndependentVariables, referenceLength, referenceArea, referenceLength,\n          momentReferencePoint,\n          boost::assign::list_of( altitude_dependent )( mach_number_dependent )( angle_of_attack_dependent ),\n          true, true ),\n      SPARTAExecutable_( SPARTAExecutable ),simulationGases_( simulationGases ), referenceAxis_( referenceAxis ),\n      gridSpacing_( gridSpacing ), simulatedParticlesPerCell_( simulatedParticlesPerCell ),\n      wallTemperature_( wallTemperature ), accommodationCoefficient_( accommodationCoefficient ),\n      printProgressInCommandWindow_( printProgressInCommandWindow ), MPIExecutable_( MPIExecutable ),\n      numberOfCores_( numberOfCores ), referenceDimension_( static_cast< unsigned int >( referenceAxis_ ) )\n{\n    // Check inputs\n    if ( referenceDimension_ > 2 )\n    {\n        throw std::runtime_error( \"Error in SPARTA rarefied flow analysis. Reference axis makes \"\n                                  \"no sense for a universe with 3 spacial dimensions (i.e., our universe). \"\n                                  \"Note that the first dimension is identified with 0.\" );\n    }\n\n    // Analyze vehicle geometry\n    analyzeGeometryFile( geometryFileUser );\n\n    // Find atmospheric conditions based on altitude\n    for ( unsigned int h = 0; h < dataPointsOfIndependentVariables_.at( 0 ).size( ); h++ )\n    {\n        atmosphericConditions_[ density_index ].push_back(\n                    atmosphereModel->getDensity( dataPointsOfIndependentVariables_.at( 0 ).at( h ) ) );\n        atmosphericConditions_[ pressure_index ].push_back(\n                    atmosphereModel->getPressure( dataPointsOfIndependentVariables_.at( 0 ).at( h ) ) );\n        atmosphericConditions_[ temperature_index ].push_back(\n                    atmosphereModel->getTemperature( dataPointsOfIndependentVariables_.at( 0 ).at( h ) ) );\n        atmosphericConditions_[ speed_of_sound_index ].push_back(\n                    atmosphereModel->getSpeedOfSound( dataPointsOfIndependentVariables_.at( 0 ).at( h ) ) );\n        atmosphericConditions_[ number_density_index ].push_back(\n                    tudat::physical_constants::AVOGADRO_CONSTANT * atmosphericConditions_[ density_index ].at( h ) /\n                    atmosphereModel->getMolarMass( dataPointsOfIndependentVariables_.at( 0 ).at( h ) ) );\n    }\n\n    // Get simulation conditions\n    getSimulationConditions( );\n\n    // Read SPARTA input template\n    inputTemplate_ = readSpartaInputFileTemplate( );\n\n    // Copy input shape file to default name\n    std::string commandString = \"cp \" + geometryFileUser + \" \" + getSpartaInternalGeometryFile( );\n    std::system( commandString.c_str( ) );\n\n    // Run SPARTA simulation\n    generateCoefficients( );\n\n    // Create interpolator object\n    createInterpolator( );\n}\n\n//! Open and read geometry file for SPARTA simulation.\nvoid RarefiedFlowAnalysis::analyzeGeometryFile( const std::string& geometryFileUser )\n{\n    // Extract information on vehicle geometry\n    std::pair< Eigen::Matrix< double, Eigen::Dynamic, 3 >, Eigen::Matrix< int, Eigen::Dynamic, 3 > >\n            geometryData = readSpartaGeometryFile( geometryFileUser );\n    shapePoints_ = geometryData.first;\n    shapeTriangles_ = geometryData.second;\n    numberOfPoints_ = shapePoints_.rows( );\n    numberOfTriangles_ = shapeTriangles_.rows( );\n\n    // Get maximum and minimum values in each dimension\n    maximumDimensions_ = shapePoints_.colwise( ).maxCoeff( );\n    minimumDimensions_ = shapePoints_.colwise( ).minCoeff( );\n\n    // Compute normal to surface elements, area of surface elements and moment arm values\n    Eigen::Matrix3d currentVertices;\n    Eigen::Vector3d currentNormal;\n    Eigen::Vector3d currentCentroid;\n    double currentNormalNorm;\n    elementSurfaceNormal_.resize( 3, numberOfTriangles_ );\n    elementSurfaceArea_.resize( 1, numberOfTriangles_ );\n    elementMomentArm_.resize( 3, numberOfTriangles_ );\n    for ( int i = 0; i < numberOfTriangles_; i++ )\n    {\n        // Compute properties of current surface element\n        for ( unsigned int j = 0; j < 3; j++ )\n        {\n            currentVertices.row( j ) = shapePoints_.row( shapeTriangles_( i, j ) - 1 );\n        }\n        currentNormal = ( currentVertices.row( 1 ) - currentVertices.row( 0 ) ).cross(\n                    currentVertices.row( 2 ) - currentVertices.row( 0 ) );\n        currentNormalNorm = currentNormal.norm( );\n        currentCentroid = currentVertices.colwise( ).sum( ) / 3.0;\n\n        // Find normal, area and distance to reference point\n        elementSurfaceNormal_.col( i ) = currentNormal / currentNormalNorm;\n        elementSurfaceArea_( i ) = 0.5 * currentNormalNorm;\n        elementMomentArm_.col( i ) = currentCentroid - momentReferencePoint_;\n    }\n\n    // Compute cross-sectional area\n    for ( unsigned int i = 0; i < 3; i++ )\n    {\n        shapeCrossSectionalArea_( i ) =\n                0.5 * elementSurfaceNormal_.row( i ).cwiseAbs( ).dot( elementSurfaceArea_ );\n    }\n\n    // Check consistency with input dimensions\n    const double tolerance = 1e-5;\n    if ( std::fabs( shapeCrossSectionalArea_( referenceDimension_ ) - referenceArea_ ) > tolerance )\n    {\n        throw std::runtime_error( \"Error in SPARTA geometry file. Input reference area does not match the \"\n                                  \"combination of reference axis and geometry. Note that the first dimension \"\n                                  \"is identified with 0. Tolerance set to: \" + std::to_string( tolerance ) );\n    }\n}\n\n//! Retrieve simulation conditions based on input and geometry.\nvoid RarefiedFlowAnalysis::getSimulationConditions( )\n{\n    // Simulation boundary and grid\n    for ( unsigned int i = 0; i < 3; i++ )\n    {\n        simulationBoundaries_( 2 * i ) = minimumDimensions_( i ) + 0.5 * minimumDimensions_.minCoeff( ); // add extra space around shape\n        simulationBoundaries_( 2 * i + 1 ) = maximumDimensions_( i ) + 0.5 * maximumDimensions_.maxCoeff( ); // add extra space around shape\n        if ( i == referenceDimension_ )\n        {\n            simulationBoundaries_( 2 * i ) -= 1.0; // add extra space along axis of velocity\n            simulationBoundaries_( 2 * i + 1 ) += 1.0; // add extra space along axis of velocity\n        }\n        simulationGrid_( i ) = simulationBoundaries_( 2 * i + 1 ) - simulationBoundaries_( 2 * i );\n    }\n    simulationGrid_ /= gridSpacing_;\n\n    // Convert molecular speed ratio to stream velocity and compute simulation time step and ratio of real to simulated variables\n    freeStreamVelocities_.resize( dataPointsOfIndependentVariables_.at( 0 ).size( ), dataPointsOfIndependentVariables_.at( 1 ).size( ) );\n    simulationTimeStep_.resize( dataPointsOfIndependentVariables_.at( 0 ).size( ), dataPointsOfIndependentVariables_.at( 1 ).size( ) );\n    ratioOfRealToSimulatedParticles_.resize( dataPointsOfIndependentVariables_.at( 0 ).size( ), 1 );\n    double simulationBoxLengthAlongReferenceAxis = ( simulationBoundaries_( 2 * referenceDimension_ + 1 ) -\n                                                     simulationBoundaries_( 2 * referenceDimension_ ) );\n    for ( unsigned int h = 0; h < dataPointsOfIndependentVariables_.at( 0 ).size( ); h++ )\n    {\n        for ( unsigned int m = 0; m < dataPointsOfIndependentVariables_.at( 1 ).size( ); m++ )\n        {\n            freeStreamVelocities_( h, m ) = dataPointsOfIndependentVariables_.at( 1 ).at( m ) *\n                    atmosphericConditions_[ speed_of_sound_index ].at( h );\n            simulationTimeStep_( h, m ) = 0.1 * simulationBoxLengthAlongReferenceAxis /\n                    freeStreamVelocities_( h, m );\n            // time step is taken as time it takes for a particle to travel for 10 % of the box\n        }\n        ratioOfRealToSimulatedParticles_( h ) = atmosphericConditions_[ number_density_index ].at( h ) *\n                std::pow( gridSpacing_, 3 ) / simulatedParticlesPerCell_;\n    }\n}\n\n//! Generate aerodynamic database.\nvoid RarefiedFlowAnalysis::generateCoefficients( )\n{\n    // Inform user on progress\n    std::cout << \"Initiating SPARTA simulation. This may take a while.\" << std::endl;\n\n    // Generate command string for SPARTA\n    std::string runSPARTACommandString = \"cd \" + getSpartaDataPath( ) + \"; \";\n    if ( MPIExecutable_ != \"\" )\n    {\n        if ( numberOfCores_ < 1 )\n        {\n            throw std::runtime_error( \"Error in SPARTA rarefied flow analysis. Number of cores needs to be \"\n                                      \"an integer value larger or equal to one.\" );\n        }\n        runSPARTACommandString = runSPARTACommandString + MPIExecutable_ +\n                \" -np \" + std::to_string( numberOfCores_ ) + \" \";\n    }\n    runSPARTACommandString = runSPARTACommandString + SPARTAExecutable_ + \" -echo log \";\n    if ( !printProgressInCommandWindow_ )\n    {\n        runSPARTACommandString = runSPARTACommandString + \"-screen none \";\n    }\n    runSPARTACommandString = runSPARTACommandString + \"-in \" + getSpartaInputFile( );\n\n    // Predefine variables\n    Eigen::Vector3d velocityVector;\n    std::string temporaryOutputFile = getSpartaOutputPath( ) + \"/coeff\";\n    std::vector< std::string > outputFileExtensions = { \".1000\" };//{ \".400\", \".600\", \".800\", \".1000\" };\n    Eigen::Matrix< double, Eigen::Dynamic, 7, Eigen::RowMajor > outputMatrix;\n    Eigen::Matrix< double, 3, Eigen::Dynamic > meanPressureValues;\n    Eigen::Matrix< double, 3, Eigen::Dynamic > meanShearValues;\n\n    // Loop over simulation parameters and run SPARTA\n    int systemStatus;\n    // Loop over altitude\n    for ( unsigned int h = 0; h < dataPointsOfIndependentVariables_.at( 0 ).size( ); h++ )\n    {\n        // Inform user on progress\n        std::cout << std::endl << \"Altitude: \"\n                  << dataPointsOfIndependentVariables_.at( 0 ).at( h ) / 1e3\n                  << \" km\" << std::endl;\n\n        // Loop over Mach numbers\n        for ( unsigned int m = 0; m < dataPointsOfIndependentVariables_.at( 1 ).size( ); m++ )\n        {\n            // Inform user on progress\n            std::cout << \"Mach number: \"\n                      << dataPointsOfIndependentVariables_.at( 1 ).at( m )\n                      << std::endl;\n\n            // Loop over angles of attack\n            for ( unsigned int a = 0; a < dataPointsOfIndependentVariables_.at( 2 ).size( ); a++ )\n            {\n                // Inform user on progress\n                std::cout << \"Angle of attack: \"\n                          << convertRadiansToDegrees( dataPointsOfIndependentVariables_.at( 2 ).at( a ) )\n                          << \" deg\" << std::endl;\n\n                // Get velocity vector\n                velocityVector = Eigen::Vector3d::Zero( );\n                velocityVector( referenceDimension_ ) = ( ( referenceAxis_ >= 0 ) ? - 1.0 : 1.0 ) *\n                        freeStreamVelocities_( h, m );\n\n                // Print to file\n                FILE * fileIdentifier = std::fopen( getSpartaInputFile( ).c_str( ), \"w\" );\n                std::fprintf( fileIdentifier, inputTemplate_.c_str( ),\n                              simulationBoundaries_( 0 ), simulationBoundaries_( 1 ), simulationBoundaries_( 2 ),\n                              simulationBoundaries_( 3 ), simulationBoundaries_( 4 ), simulationBoundaries_( 5 ),\n                              simulationGrid_( 0 ), simulationGrid_( 1 ), simulationGrid_( 2 ),\n                              atmosphericConditions_[ number_density_index ].at( h ), ratioOfRealToSimulatedParticles_( h ),\n                              simulationGases_.c_str( ),\n                              simulationGases_.c_str( ), velocityVector( 0 ), velocityVector( 1 ), velocityVector( 2 ),\n                              simulationGases_.c_str( ), atmosphericConditions_[ temperature_index ].at( h ),\n                              convertRadiansToDegrees( dataPointsOfIndependentVariables_.at( 2 ).at( a ) ),\n                              wallTemperature_, accommodationCoefficient_,\n                              simulationTimeStep_( h, m ),\n                              getSpartaOutputDirectory( ).c_str( ) );\n                std::fclose( fileIdentifier );\n\n                // Run SPARTA\n                systemStatus = std::system( runSPARTACommandString.c_str( ) );\n                if ( systemStatus != 0 )\n                {\n                    throw std::runtime_error( \"Error in SPARTA rarefied flow analysis. \"\n                                              \"SPARTA Simulation failed. See the log.sparta file in \"\n                                              \"Tudat/External/SPARTA/ for more details.\" );\n                }\n\n                // Loop over angles of attack\n                meanPressureValues.resize( 3, numberOfTriangles_ );\n                meanShearValues.resize( 3, numberOfTriangles_ );\n\n                // Read output files and compute mean pressure and shear force values\n                meanPressureValues.setZero( );\n                meanShearValues.setZero( );\n                for ( unsigned int i = 0; i < outputFileExtensions.size( ); i++ )\n                {\n                    outputMatrix = readMatrixFromFile( temporaryOutputFile + outputFileExtensions.at( i ), \"\\t ;,\", \"%\", 9 );\n                    outputMatrix = sortMatrixRows( outputMatrix, 0 );\n                    for ( unsigned int j = 0; j < 3; j++ )\n                    {\n                        meanPressureValues.row( j ) += outputMatrix.col( j + 1 ).transpose( );\n                        meanShearValues.row( j ) += outputMatrix.col( j + 4 ).transpose( );\n                    }\n                }\n                meanPressureValues /= outputFileExtensions.size( );\n                meanShearValues /= outputFileExtensions.size( );\n\n                // Convert pressure and shear forces to aerodynamic coefficients\n                aerodynamicCoefficients_[ h ][ m ][ a ] = computeAerodynamicCoefficientsFromPressureShearForces(\n                            meanPressureValues,\n                            meanShearValues,\n                            atmosphericConditions_[ density_index ].at( h ),\n                            atmosphericConditions_[ pressure_index ].at( h ),\n                            freeStreamVelocities_( h, m ),\n                            elementSurfaceNormal_,\n                            elementSurfaceArea_,\n                            elementMomentArm_,\n                            referenceArea_,\n                            referenceLength_ );\n\n                // Clean up results folder\n                std::string commandString = \"rm \" + getSpartaOutputPath( ) + \"/coeff.*\";\n                std::system( commandString.c_str( ) );\n            }\n        }\n    }\n\n    // Inform user on progress\n    std::cout << std::endl << \"SPARTA simulation complete.\" << std::endl << std::endl;\n}\n\n//! Get aerodynamic coefficients at specific conditions.\nEigen::Vector6d RarefiedFlowAnalysis::getAerodynamicCoefficientsDataPoint(\n        const boost::array< int, 3 > independentVariables )\n{\n    // Return requested coefficients.\n    return aerodynamicCoefficients_( independentVariables );\n}\n\n} // namespace aerodynamics\n\n} // namespace tudat\n", "meta": {"hexsha": "f6f0df0fa76c45b242d3a8001289a0139d6fe360", "size": 22144, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Astrodynamics/Aerodynamics/rarefiedFlowAnalysis.cpp", "max_stars_repo_name": "MattTurnock/tudat", "max_stars_repo_head_hexsha": "763c646cb03c30586db7a7f3932f0e9da24e7f96", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Astrodynamics/Aerodynamics/rarefiedFlowAnalysis.cpp", "max_issues_repo_name": "MattTurnock/tudat", "max_issues_repo_head_hexsha": "763c646cb03c30586db7a7f3932f0e9da24e7f96", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Astrodynamics/Aerodynamics/rarefiedFlowAnalysis.cpp", "max_forks_repo_name": "MattTurnock/tudat", "max_forks_repo_head_hexsha": "763c646cb03c30586db7a7f3932f0e9da24e7f96", "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": 45.2842535787, "max_line_length": 140, "alphanum_fraction": 0.6132586705, "num_tokens": 5163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.20746119301652594}}
{"text": "#define NOMINMAX\n#include \"LinearHexahedralPusoFormulation.hpp\"\n#include <assert.h>\n#include <boost/detail/limits.hpp>\n#include \"LinearHexahedralPusoFormulationHelper.hpp\"\n#include \"domain/elements/FiniteElement.hpp\"\n#include \"domain/elements/ElementGeometry.hpp\"\n#include \"domain/elements/MatrixOption.hpp\"\n#include \"domain/elements/Node.hpp\"\n#include \"domain/materials/MaterialModel.hpp\"\n#include \"domain/physics/InfinitesimalState.hpp\"\n#include \"domain/physics/UpdatedPhysicalState.hpp\"\n#include \"foundation/NotImplementedException.hpp\"\n#include \"foundation/NotSupportedException.hpp\"\n#include \"Foundation/BLAS/ColumnVector.hpp\"\n#include \"domain/analyses/AnalysisTimeline.hpp\"\n#include \"foundation/memory/pointer.hpp\"\n\nnamespace adf = axis::domain::formulations;\nnamespace ada = axis::domain::analyses;\nnamespace ade = axis::domain::elements;\nnamespace adm = axis::domain::materials;\nnamespace adp = axis::domain::physics;\nnamespace af = axis::foundation;\nnamespace afb = axis::foundation::blas;\nnamespace afm = axis::foundation::memory;\nnamespace afu = axis::foundation::uuids;\n\nnamespace {\n  typedef adf::LinearHexahedralPusoFormulation hexa;\n}\n\nhexa::LinearHexahedralPusoFormulation(void)\n{\n  lumpedMass_ = NULLPTR;\n  Bmatrix_ = NULLPTR;\n  nodeCoordinates_ = NULLPTR;\n  jacobian_ = NULLPTR;\n  for (int i = 0; i < 4; i++)\n  {\n    hourglassForces_[i] = NULLPTR;\n  }  \n  volume_ = 0;\n  hourglassEnergy_ = 0;\n}\n\nhexa::~LinearHexahedralPusoFormulation(void)\n{\n  ClearMemory();\n  if (nodeCoordinates_ != NULLPTR)\n  {\n    absref<afb::DenseMatrix>(nodeCoordinates_).Destroy();\n    System::ModelMemory().Deallocate(nodeCoordinates_);\n  }\n  if (Bmatrix_ != NULLPTR)\n  {\n    absref<afb::DenseMatrix>(Bmatrix_).Destroy();\n    System::ModelMemory().Deallocate(Bmatrix_);\n  }\n  if (jacobian_ != NULLPTR)\n  {\n    absref<afb::DenseMatrix>(jacobian_).Destroy();\n    System::ModelMemory().Deallocate(jacobian_);\n  }\n  for (int i = 0; i < 4; i++)\n  {\n    if (hourglassForces_[i] != NULLPTR)\n    {\n      absref<afb::ColumnVector>(hourglassForces_[i]).Destroy();\n      System::ModelMemory().Deallocate(hourglassForces_[i]);\n      hourglassForces_[i] = NULLPTR;\n    }\n  }  \n  jacobian_ = NULLPTR;\n  Bmatrix_ = NULLPTR;\n  nodeCoordinates_ = NULLPTR;\n}\n\nvoid hexa::Destroy( void ) const\n{\n  delete this;\n}\n\nconst afb::SymmetricMatrix& hexa::GetStiffness( void ) const\n{\n  // TODO : implement stiffness matrix according to Puso (2000).\n  throw af::NotImplementedException(\n    _T(\"This element formulation does not implement stiffness matrix.\"));\n}\n\nconst afb::SymmetricMatrix& hexa::GetConsistentMass( void ) const\n{\n  throw af::NotImplementedException(\n    _T(\"This element formulation does not implement consistent mass.\"));\n}\n\nconst afb::ColumnVector& hexa::GetLumpedMass( void ) const\n{\n  return absref<afb::ColumnVector>(lumpedMass_);\n}\n\nvoid hexa::AllocateMemory( void )\n{\n  // initialize matrices\n  nodeCoordinates_ = afb::DenseMatrix::Create(8, 3);\n  Bmatrix_ = afb::DenseMatrix::Create(3, 8);\n  jacobian_ = afb::DenseMatrix::Create(3, 3);\n  for (int i = 0; i < 4; i++)\n  {\n    hourglassForces_[i] = afb::ColumnVector::Create(3);\n  }  \n}\n\nvoid hexa::CalculateInitialState( void )\n{\n  // get initial nodal coordinates\n  ade::ElementGeometry& geometry = Element().Geometry();\n  auto& Bmatrix = absref<afb::DenseMatrix>(Bmatrix_);\n  auto& nodeCoordinates = absref<afb::DenseMatrix>(nodeCoordinates_);\n  auto& jacobian = absref<afb::DenseMatrix>(jacobian_);\n  CalculateNodeCoordinate(nodeCoordinates, geometry);\n  CalculateBMatrix(Bmatrix, volume_, nodeCoordinates);\n  CalculateJacobian(jacobian, nodeCoordinates);\n\n  // clear hourglass force vectors\n  for (int i = 0; i < 4; i++)\n  {\n    absref<afb::ColumnVector>(hourglassForces_[i]).ClearAll();\n  }\n}\n\nvoid hexa::UpdateStrain( const afb::ColumnVector& elementDisplacementIncrement )\n{\n  const afb::ColumnVector& du = elementDisplacementIncrement; // shorthand\n  const afb::DenseMatrix& B = absref<afb::DenseMatrix>(Bmatrix_);\n  afb::ColumnVector& strain = Element().PhysicalState().Strain();\n  afb::ColumnVector& strainIncrement = Element().PhysicalState().LastStrainIncrement();\n\n  // our B-matrix is somewhat \"different\", so we rearrange the matrix-vector \n  // computation normally done\n  strainIncrement.ClearAll();\n  for (int i = 0; i < 8; i++)\n  {\n    real e1 = B(0,i)*du(3*i);                                 // du1/dx\n    real e2 = B(1,i)*du(3*i + 1);                             // du2/dy\n    real e3 = B(2,i)*du(3*i + 2);                             // du3/dz\n    real e4 = B(2,i)*du(3*i + 1) + B(1,i)*du(3*i + 2);        // du2/dz + du3/dy\n    real e5 = B(2,i)*du(3*i) + B(0,i)*du(3*i + 2);            // du1/dz + du3/dx\n    real e6 = B(1,i)*du(3*i) + B(0,i)*du(3*i + 1);            // du1/dy + du2/dx\n    strainIncrement(0) += e1;\n    strainIncrement(1) += e2;\n    strainIncrement(2) += e3;\n    strainIncrement(3) += e4;\n    strainIncrement(4) += e5;\n    strainIncrement(5) += e6;\n  }\n  afb::VectorSum(strain, 1.0, strain, 1.0, strainIncrement);\n}\n\nvoid hexa::UpdateInternalForce( afb::ColumnVector& internalForce, \n  const afb::ColumnVector& elementDisplacementIncrement, \n  const afb::ColumnVector& elementVelocity, \n  const ada::AnalysisTimeline& timeInfo )\n{\n  internalForce.ClearAll();\n  CalculateCentroidalInternalForce(internalForce);\n  StabilizeInternalForce(internalForce, elementDisplacementIncrement);\n  internalForce.Scale(-1.0);\n}\n\nvoid hexa::UpdateMatrices( const ade::MatrixOption& whichMatrices, \n  const afb::ColumnVector& elementDisplacement, \n  const afb::ColumnVector& elementVelocity )\n{\n  if (whichMatrices.DoesRequestConsistentMassMatrix())\n  {\n    throw af::NotSupportedException(\n      _T(\"This element formulation does not support consistent mass.\"));\n  }\n  else if (whichMatrices.DoesRequestLumpedMassMatrix())\n  {\n    UpdateLumpedMassMatrix();\n  }\n  else if (whichMatrices.DoesRequestStiffnessMatrix())\n  {\n    throw af::NotSupportedException(\n      _T(\"This element formulation does not support stiffness matrix.\"));\n  }\n  else\n  {\n    assert(!_T(\"An unpredictable matrix option was requested!\"));\n  }\n}\n\nvoid hexa::ClearMemory( void )\n{\n  if (lumpedMass_ != NULLPTR)\n  {\n    absref<afb::ColumnVector>(lumpedMass_).Destroy();\n    System::ModelMemory().Deallocate(lumpedMass_);\n  }\n  lumpedMass_ = NULLPTR;\n}\n\nreal hexa::GetCriticalTimestep(const afb::ColumnVector& modelDisplacement) const\n{\n  /* According to Puso (2000), the calculation below is empirically faster and\n     works for most of the problems. Also, other more conservative equations, \n     is generally coupled to material model and does not account hourglass\n     stiffness, which generally presents two significant drawbacks.\n  **/\n  const ade::ElementGeometry& geometry = Element().Geometry();\n  const adm::MaterialModel& material = Element().Material();\n  const real speed = material.GetWavePropagationSpeed();\n\n  // get the shortest distance between nodes\n  real length = std::numeric_limits<real>::max();\n  for (int i = 0; i < 7; i++)\n  {\n    const ade::Node& nodeX = geometry[i];\n    for (int j = i + 1; j < 8; j++)\n    {\n      const ade::Node& nodeY = geometry[j];\n      real dx = nodeX.X() - nodeY.X();\n      real dy = nodeX.Y() - nodeY.Y();\n      real dz = nodeX.Z() - nodeY.Z();\n      real dist = sqrt(dx*dx + dy*dy + dz*dz);\n      if (dist < length)\n      {\n        length = dist;\n      }\n    }\n  }\n  \n  // this is a pessimistic approach: the fastest speed and the shortest distance\n  real solidLongitudinalWaveSpeed = sqrt(speed / length);\n  return solidLongitudinalWaveSpeed;\n}\n\nvoid hexa::UpdateLumpedMassMatrix( void )\n{\n  if (lumpedMass_ == NULLPTR)\n  {\n    lumpedMass_ = axis::foundation::blas::ColumnVector::Create(24);\n  }\n  adm::MaterialModel& material = Element().Material();\n  real massPerNode = volume_ * material.Density() / 8;\n  absref<afb::ColumnVector>(lumpedMass_).SetAll(massPerNode);\n}\n\nvoid hexa::CalculateCentroidalInternalForce( afb::ColumnVector& internalForce )\n{\n  const afb::DenseMatrix& B = absref<afb::DenseMatrix>(Bmatrix_);\n  const afb::ColumnVector& stress = Element().PhysicalState().Stress();\n  afb::ColumnVector& fint = internalForce;\n  for (int i = 0; i < 8; i++)\n  {\n    real f1 = B(0, i)*stress(0) + B(2, i)*stress(4) + B(1, i)*stress(5);\n    real f2 = B(1, i)*stress(1) + B(2, i)*stress(3) + B(0, i)*stress(5);\n    real f3 = B(2, i)*stress(2) + B(1, i)*stress(3) + B(0, i)*stress(4);\n\n    fint(3*i  ) = f1;\n    fint(3*i+1) = f2;\n    fint(3*i+2) = f3;\n  }\n  fint.Scale(volume_);\n}\n\nreal adf::LinearHexahedralPusoFormulation::GetTotalArtificialEnergy( void ) const\n{\n  return hourglassEnergy_;\n}\n\nvoid hexa::StabilizeInternalForce( axis::foundation::blas::ColumnVector& internalForce, \n                                   const axis::foundation::blas::ColumnVector& displacementIncrement )\n{\n  id_type id = Element().GetInternalId();\n\n  // These are some shorthands that we are going to use\n  const afb::DenseMatrix& J = absref<afb::DenseMatrix>(jacobian_);\n  const afb::DenseMatrix& B = absref<afb::DenseMatrix>(Bmatrix_);\n  const afb::ColumnVector& du = displacementIncrement;\n  afb::DenseMatrix& X = absref<afb::DenseMatrix>(nodeCoordinates_);\n  const afb::DenseMatrix& C = Element().Material().GetMaterialTensor();\n\n  afb::ColumnVector sv1(8), sv2(8), sv3(8), sv4(8);\n  afb::ColumnVector *stabilizationVector[4] = {&sv1, &sv2, &sv3, &sv4};\n  for (int i = 0; i < 4; i++) // iterate through vectors\n  {\n    // gamma_i = h_i\n    for (int idx = 0; idx < 8; idx++)\n    {\n      (*stabilizationVector[i])(idx) = hourglassVector_[i][idx];\n    }    \n\n    // sum [j = 1 : 3]\n    for (int j = 0; j < 3; j++)\n    {\n      // dot product h_i * x_j\n      real dotProduct = 0;\n      for (int m = 0; m < 8; m++)\n      {\n        dotProduct += hourglassVector_[i][m] * X(m, j);\n      }\n\n      for (int k = 0; k < 8; k++) // iterate through vector indices\n      {\n        (*stabilizationVector[i])(k) -= dotProduct * B(j, k);\n      }\n    }\n\n    stabilizationVector[i]->Scale(0.125);\n  }\n\n  // Step 2: Calculate hourglass displacements (already in isoparametric \n  // domain, Eq. 8)\n  afb::ColumnVector v1(8), v2(8), v3(8), v4(8);\n  afb::ColumnVector *hourglassDisplacement[4] = {&v1, &v2, &v3, &v4};\n  for (int i = 0; i < 4; i++)\n  {\n    hourglassDisplacement[i]->ClearAll();\n    real v_1 = 0, v_2 = 0, v_3 = 0;\n    for (int nodeIdx = 0; nodeIdx < 8; nodeIdx++)\n    {\n      // in generalized coordinates...\n      v_1 += (*stabilizationVector[i])(nodeIdx) * du(3*nodeIdx    );\n      v_2 += (*stabilizationVector[i])(nodeIdx) * du(3*nodeIdx + 1);\n      v_3 += (*stabilizationVector[i])(nodeIdx) * du(3*nodeIdx + 2);\n    }\n\n    // ...now in isoparametric coordinates\n    for (int k = 0; k < 3; k++)\n    {\n      (*hourglassDisplacement[i])(k) = J(0, k)*v_1 + J(1, k)*v_2 + J(2, k)*v_3;\n    }\n  }\n\n  // Step 3: Calculate hat(J)_0^(-1), which maps strains to isoparametric \n  // coordinates (Eq. 3.61 pg. 3.14, LS-DYNA Theory Manual)\n  afb::ColumnVector strainJacobian(6);  \n  real jSquaredNorm[3];\n  for (int i = 0; i < 3; i++)\n  {\n    real squaredNorm = J(0,i)*J(0,i) + J(1,i)*J(1,i) + J(2,i)*J(2,i);\n    jSquaredNorm[i] = squaredNorm;\n  }\n  strainJacobian(0) = 1.0 / jSquaredNorm[0];\n  strainJacobian(1) = 1.0 / jSquaredNorm[1];\n  strainJacobian(2) = 1.0 / jSquaredNorm[2];\n  strainJacobian(3) = 1.0 / sqrt(jSquaredNorm[0] * jSquaredNorm[1]);\n  strainJacobian(4) = 1.0 / sqrt(jSquaredNorm[2] * jSquaredNorm[1]);\n  strainJacobian(5) = 1.0 / sqrt(jSquaredNorm[0] * jSquaredNorm[2]);\n\n  // Step 4: Map material stiffness matrix to isoparametric space.\n  afb::DenseMatrix Ciso(6, 6);\n  for (int i = 0; i < 6; i++)\n  {\n    for (int j = 0; j < 6; j++)\n    {\n      real c_ij = strainJacobian(i) * C(i, j) * strainJacobian(j);\n      Ciso(i, j) = c_ij;\n    }\n  }\n\n  // Step 5: Calculate internal degrees of freedom for enhanced strain.\n  real H = Ciso(0,0) + Ciso(1,1) + Ciso(2,2) + 2.0*(Ciso(0,1) + \n    Ciso(1,2) + Ciso(0,2));\n  real da1 = 1.0/Ciso(0,0) * (Ciso(0,1)*v1(1) + Ciso(0,4)*v2(1) + \n    Ciso(0,2)*v2(2) + Ciso(0,4)*v1(2));\n  real da2 = 1.0/Ciso(1,1) * (Ciso(1,0)*v1(0) + Ciso(1,5)*v3(0) + \n    Ciso(1,2)*v3(2));\n  real da3 = 1.0/Ciso(2,2) * (Ciso(2,0)*v2(0) + Ciso(2,3)*v3(0) + \n    Ciso(2,1)*v3(1) + Ciso(2,3)*v2(1));\n  real da4 = v4(2)/H * (Ciso(0,2) + Ciso(1,2) + Ciso(2,2));\n  real da5 = v4(0)/H * (Ciso(0,0) + Ciso(1,0) + Ciso(2,0));\n  real da6 = v4(1)/H * (Ciso(0,1) + Ciso(1,1) + Ciso(2,1));\n\n  // Step 6: Calculate hourglass force increment\n  afb::ColumnVector& df1 = absref<afb::ColumnVector>(hourglassForces_[0]);\n  afb::ColumnVector& df2 = absref<afb::ColumnVector>(hourglassForces_[1]);\n  afb::ColumnVector& df3 = absref<afb::ColumnVector>(hourglassForces_[2]);\n  afb::ColumnVector& df4 = absref<afb::ColumnVector>(hourglassForces_[3]);\n  real beta1 = 8.0/3.0 * volume_;\n  real beta2 = 8.0/9.0 * volume_;\n  real df11 = beta1 * (Ciso(0,0)*v1(0) + Ciso(0,2)*v3(2) + Ciso(0,5)*(v3(0) + \n    v1(2)) - Ciso(1,0)*da2);\n  real df12 = beta1 * (Ciso(1,1)*v1(1) + Ciso(1,2)*v2(2) + Ciso(1,4)*(v2(1) + \n    v1(2)) - Ciso(0,1)*da1);\n  real df13 = beta1 * (Ciso(4,4)*(v2(1) + v1(2)) + Ciso(5,5)*(v3(0) + v1(2)) + \n    Ciso(5,0)*v1(0) + Ciso(4,1)*v1(1)\n    + Ciso(4,2)*v2(2) + Ciso(5,2)*v3(2) - Ciso(0,4)*da1);\n  real df21 = beta1 * (Ciso(0,0)*v2(0) + Ciso(0,1)*v3(1) + Ciso(0,3)*(v3(0) + \n    v2(1)) - Ciso(2,0)*da3);\n  real df22 = beta1 * (Ciso(3,3)*(v3(0) + v2(1)) + Ciso(4,4)*(v2(1) + v1(2)) + \n    Ciso(3,0)*v2(0) + Ciso(3,1)*v3(1) \n    + Ciso(4,1)*v1(1) + Ciso(4,2)*v2(2) - Ciso(0,4)*da1 - Ciso(2,3)*da3);\n  real df23 = beta1 * (Ciso(2,1)*v1(1) + Ciso(2,2)*v2(2) + Ciso(2,4)*(v2(1) + \n    v1(2)) - Ciso(0,2)*da1);\n  real df31 = beta1 * (Ciso(3,3)*(v3(0) + v2(1)) + Ciso(5,5)*(v3(0) + v1(2)) + \n    Ciso(3,0)*v2(0) + Ciso(3,1)*v3(1) \n    + Ciso(5,0)*v1(0) + Ciso(5,2)*v3(2) - Ciso(1,5)*da2 - Ciso(2,3)*da3);\n  real df32 = beta1 * (Ciso(1,0)*v2(0) + Ciso(1,1)*v3(1) + Ciso(1,3)*(v3(0) + \n    v2(1)) - Ciso(2,1)*da3);\n  real df33 = beta1 * (Ciso(2,0)*v1(0) + Ciso(2,2)*v3(2) + Ciso(2,5)*(v3(0) + \n    v1(2)) - Ciso(1,2)*da2);\n  real df41 = beta2 * (Ciso(0,0)*v4(0) - (Ciso(0,0) + Ciso(1,0) + Ciso(2,0))*da5);\n  real df42 = beta2 * (Ciso(1,1)*v4(1) - (Ciso(0,1) + Ciso(1,1) + Ciso(2,1))*da6);\n  real df43 = beta2 * (Ciso(2,2)*v4(2) - (Ciso(0,2) + Ciso(1,2) + Ciso(2,2))*da4);\n  df1(0) += df11; df1(1) += df12; df1(2) += df13;\n  df2(0) += df21; df2(1) += df22; df2(2) += df23;\n  df3(0) += df31; df3(1) += df32; df3(2) += df33;\n  df4(0) += df41; df4(1) += df42; df4(2) += df43;\n\n  // Step 7: Calculate stabilization forces (fStab).\n  afb::ColumnVector fStab(24);\n  fStab.ClearAll();\n  for (int i = 0; i < 4; i++)\n  {\n    const afb::ColumnVector& fi = absref<afb::ColumnVector>(hourglassForces_[i]);\n    for (int nodeIdx = 0; nodeIdx < 8; nodeIdx++)\n    {\n      real gamma = (*stabilizationVector[i])(nodeIdx);\n      real fs1 = gamma * (J(0,0)*fi(0) + J(0,1)*fi(1) + J(0,2)*fi(2));\n      real fs2 = gamma * (J(1,0)*fi(0) + J(1,1)*fi(1) + J(1,2)*fi(2));\n      real fs3 = gamma * (J(2,0)*fi(0) + J(2,1)*fi(1) + J(2,2)*fi(2));\n\n      fStab(3*nodeIdx    ) += fs1;\n      fStab(3*nodeIdx + 1) += fs2;\n      fStab(3*nodeIdx + 2) += fs3;\n    }\n  }\n\n  // Calculate hourglass energy increment\n  real hourglassEnergyIncrement = 0;\n  for (int nodeIdx = 0; nodeIdx < 8; nodeIdx++)\n  {\n    real gamma1 = (*stabilizationVector[0])(nodeIdx);\n    real gamma2 = (*stabilizationVector[1])(nodeIdx);\n    real gamma3 = (*stabilizationVector[2])(nodeIdx);\n    real gamma4 = (*stabilizationVector[3])(nodeIdx);\n    real dfs1 = gamma1 * (J(0,0)*df11 + J(0,1)*df12 + J(0,2)*df13)\n              + gamma2 * (J(0,0)*df21 + J(0,1)*df22 + J(0,2)*df23)\n              + gamma3 * (J(0,0)*df31 + J(0,1)*df32 + J(0,2)*df33)\n              + gamma4 * (J(0,0)*df41 + J(0,1)*df42 + J(0,2)*df43);\n    real dfs2 = gamma1 * (J(1,0)*df11 + J(1,1)*df12 + J(1,2)*df13)\n              + gamma2 * (J(1,0)*df21 + J(1,1)*df22 + J(1,2)*df23)\n              + gamma3 * (J(1,0)*df31 + J(1,1)*df32 + J(1,2)*df33)\n              + gamma4 * (J(1,0)*df41 + J(1,1)*df42 + J(1,2)*df43);\n    real dfs3 = gamma1 * (J(2,0)*df11 + J(2,1)*df12 + J(2,2)*df13)\n              + gamma2 * (J(2,0)*df21 + J(2,1)*df22 + J(2,2)*df23)\n              + gamma3 * (J(2,0)*df31 + J(2,1)*df32 + J(2,2)*df33)\n              + gamma4 * (J(2,0)*df41 + J(2,1)*df42 + J(2,2)*df43);\n    hourglassEnergyIncrement += dfs1*du(3*nodeIdx) + dfs2*du(3*nodeIdx + 1) + \n      dfs3*du(3*nodeIdx + 2);\n  }\n  hourglassEnergy_ += hourglassEnergyIncrement;\n\n  // Step 8: Stabilize internal force\n  afb::VectorSum(internalForce, 1.0, internalForce, 1.0, fStab);\n}\n\nafu::Uuid adf::LinearHexahedralPusoFormulation::GetTypeId( void ) const\n{\n  // 993F06D4-A4B7-4B49-B5D3-42DA6FE86AE3\n  int bytes[16] = {0x99, 0x3F, 0x06, 0xD4, 0xA4, 0xB7, 0x4B, 0x49, \n                   0xB5, 0xD3, 0x42, 0xDA, 0x6F, 0xE8, 0x6A, 0xE3};\n  return afu::Uuid(bytes);\n}\n\n// void hexa::StabilizeInternalForce_org( afb::Vector& internalForce, \n//                                    const afb::Vector& displacementIncrement )\n// {\n//   id_type id = Element().GetInternalId();\n// \n//   // These are some shorthands that we are going to use\n//   const afb::Matrix& J = absref<afb::Matrix>(jacobian_);\n//   const afb::Matrix& B = absref<afb::Matrix>(Bmatrix_);\n//   const afb::Vector& du = displacementIncrement;\n//   afb::Matrix& X = absref<afb::Matrix>(nodeCoordinates_);\n//   const afb::Matrix& C = Element().Material().GetMaterialTensor();\n// \n//   // Step 1: Calculate stabilization vectors gamma_i (Eq. 11)\n//   real stabilizationVector[3][4][8];\n//   for (int dofIdx = 0; dofIdx < 3; dofIdx++)\n//   {\n//     for (int modeIdx = 0; modeIdx < 4; modeIdx++) // iterate through vectors\n//     {\n//       real *gamma = stabilizationVector[dofIdx][modeIdx];\n//       const real *h = hourglassVector_[modeIdx];\n//       real dotProduct = 0;\n//       for (int m = 0; m < 8; m++) // dot product h_i * x_j\n//       {\n//         dotProduct += h[m] * X(m, dofIdx);\n//       }\n//       for (int k = 0; k < 8; k++) // iterate through vector indices\n//       {\n//         gamma[k] = 0.125 * (h[k] - dotProduct*B(dofIdx, k));\n//       }\n//     }\n//   }\n// \n//   // Step 2: Calculate hourglass displacements (already in isoparametric \n//   // domain, Eq. 8)\n//   real hourglassDisplacement[4][3];\n//   for (int i = 0; i < 4; i++)\n//   {\n//     real v_1 = 0, v_2 = 0, v_3 = 0;\n//     for (int nodeIdx = 0; nodeIdx < 8; nodeIdx++)\n//     {\n//       // in generalized coordinates...\n//       v_1 += stabilizationVector[0][i][nodeIdx] * du(3*nodeIdx    );\n//       v_2 += stabilizationVector[1][i][nodeIdx] * du(3*nodeIdx + 1);\n//       v_3 += stabilizationVector[2][i][nodeIdx] * du(3*nodeIdx + 2);\n//     }\n// \n//     // ...now in isoparametric coordinates\n//     for (int k = 0; k < 3; k++)\n//     {\n//       hourglassDisplacement[k][i] = J(0, k)*v_1 + J(1, k)*v_2 + J(2, k)*v_3;\n//     }\n//   }\n// \n//   // Step 3: Calculate hat(J)_0^(-1), which maps strains to isoparametric \n//   // coordinates (Eq. 3.61 pg. 3.14, LS-DYNA Theory Manual)\n//   afb::ColumnVector strainJacobian(6);  \n//   real jSquaredNorm[3];\n//   for (int i = 0; i < 3; i++)\n//   {\n//     real squaredNorm = J(0,i)*J(0,i) + J(1,i)*J(1,i) + J(2,i)*J(2,i);\n//     jSquaredNorm[i] = squaredNorm;\n//   }\n//   strainJacobian(0) = 1.0 / jSquaredNorm[0];\n//   strainJacobian(1) = 1.0 / jSquaredNorm[1];\n//   strainJacobian(2) = 1.0 / jSquaredNorm[2];\n//   strainJacobian(3) = 1.0 / sqrt(jSquaredNorm[0] * jSquaredNorm[1]);\n//   strainJacobian(4) = 1.0 / sqrt(jSquaredNorm[2] * jSquaredNorm[1]);\n//   strainJacobian(5) = 1.0 / sqrt(jSquaredNorm[0] * jSquaredNorm[2]);\n// \n//   // Step 4: Map material stiffness matrix to isoparametric space.\n//   afb::DenseMatrix Ciso(6, 6);\n//   for (int i = 0; i < 6; i++)\n//   {\n//     for (int j = 0; j < 6; j++)\n//     {\n//       real c_ij = strainJacobian(i) * C(i, j) * strainJacobian(j);\n//       Ciso(i, j) = c_ij;\n//     }\n//   }\n// \n//   // Step 5: Calculate internal degrees of freedom for enhanced strain.\n//   real *v1 = hourglassDisplacement[0];\n//   real *v2 = hourglassDisplacement[1];\n//   real *v3 = hourglassDisplacement[2];\n//   real *v4 = hourglassDisplacement[3];\n//   real H = Ciso(0,0) + Ciso(1,1) + Ciso(2,2) + 2.0*(Ciso(0,1) + Ciso(1,2) + Ciso(0,2));\n//   real da1 = 1.0/Ciso(0,0) * (Ciso(0,1)*v1[1] + Ciso(0,4)*v2[1] + Ciso(0,2)*v2[2] + Ciso(0,4)*v1[2]);\n//   real da2 = 1.0/Ciso(1,1) * (Ciso(1,0)*v1[0] + Ciso(1,5)*v3[0] + Ciso(1,2)*v3[2]);\n//   real da3 = 1.0/Ciso(2,2) * (Ciso(2,0)*v2[0] + Ciso(2,3)*v3[0] + Ciso(2,1)*v3[1] + Ciso(2,3)*v2[1]);\n//   real da4 = v4[2]/H * (Ciso(0,2) + Ciso(1,2) + Ciso(2,2));\n//   real da5 = v4[0]/H * (Ciso(0,0) + Ciso(1,0) + Ciso(2,0));\n//   real da6 = v4[1]/H * (Ciso(0,1) + Ciso(1,1) + Ciso(2,1));\n// \n//   // Step 6: Calculate hourglass force increment\n//   afb::Vector& df1 = absref<afb::Vector>(hourglassForces_[0]);\n//   afb::Vector& df2 = absref<afb::Vector>(hourglassForces_[1]);\n//   afb::Vector& df3 = absref<afb::Vector>(hourglassForces_[2]);\n//   afb::Vector& df4 = absref<afb::Vector>(hourglassForces_[3]);\n//   real beta1 = 8.0/3.0 * volume_;\n//   real beta2 = 8.0/9.0 * volume_;\n//   real df11 = beta1 * (Ciso(0,0)*v1[0] + Ciso(0,2)*v3[2] + Ciso(0,5)*(v3[0] + v1[2]) - Ciso(1,0)*da2);\n//   real df12 = beta1 * (Ciso(1,1)*v1[1] + Ciso(1,2)*v2[2] + Ciso(1,4)*(v2[1] + v1[2]) - Ciso(0,1)*da1);\n//   real df13 = beta1 * (Ciso(4,4)*(v2[1] + v1[2]) + Ciso(5,5)*(v3[0] + v1[2]) + Ciso(5,0)*v1[0] + Ciso(4,1)*v1[1]\n//               + Ciso(4,2)*v2[2] + Ciso(5,2)*v3[2] - Ciso(0,4)*da1);\n//   real df21 = beta1 * (Ciso(0,0)*v2[0] + Ciso(0,1)*v3[1] + Ciso(0,3)*(v3[0] + v2[1]) - Ciso(2,0)*da3);\n//   real df22 = beta1 * (Ciso(3,3)*(v3[0] + v2[1]) + Ciso(4,4)*(v2[1] + v1[2]) + Ciso(3,0)*v2[0] + Ciso(3,1)*v3[1] \n//               + Ciso(4,1)*v1[1] + Ciso(4,2)*v2[2] - Ciso(0,4)*da1 - Ciso(2,3)*da3);\n//   real df23 = beta1 * (Ciso(2,1)*v1[1] + Ciso(2,2)*v2[2] + Ciso(2,4)*(v2[1] + v1[2]) - Ciso(0,2)*da1);\n//   real df31 = beta1 * (Ciso(3,3)*(v3[0] + v2[1]) + Ciso(5,5)*(v3[0] + v1[2]) + Ciso(3,0)*v2[0] + Ciso(3,1)*v3[1] \n//               + Ciso(5,0)*v1[0] + Ciso(5,2)*v3[2] - Ciso(1,5)*da2 - Ciso(2,3)*da3);\n//   real df32 = beta1 * (Ciso(1,0)*v2[0] + Ciso(1,1)*v3[1] + Ciso(1,3)*(v3[0] + v2[1]) - Ciso(2,1)*da3);\n//   real df33 = beta1 * (Ciso(2,0)*v1[0] + Ciso(2,2)*v3[2] + Ciso(2,5)*(v3[0] + v1[2]) - Ciso(1,2)*da2);\n//   real df41 = beta2 * (Ciso(0,0)*v4[0] - (Ciso(0,0) + Ciso(1,0) + Ciso(2,0))*da5);\n//   real df42 = beta2 * (Ciso(1,1)*v4[1] - (Ciso(0,1) + Ciso(1,1) + Ciso(2,1))*da6);\n//   real df43 = beta2 * (Ciso(2,2)*v4[2] - (Ciso(0,2) + Ciso(1,2) + Ciso(2,2))*da4);\n//   df1(0) += df11; df1(1) += df12; df1(2) += df13;\n//   df2(0) += df21; df2(1) += df22; df2(2) += df23;\n//   df3(0) += df31; df3(1) += df32; df3(2) += df33;\n//   df4(0) += df41; df4(1) += df42; df4(2) += df43;\n// \n//   // Step 7: Calculate stabilization forces (fStab).\n//   afb::ColumnVector fStab(24);\n//   afb::ColumnVector dFstab(24);\n//   fStab.ClearAll();\n//   for (int i = 0; i < 4; i++)\n//   {\n//     const afb::Vector& fi = absref<afb::Vector>(hourglassForces_[i]);\n//     for (int nodeIdx = 0; nodeIdx < 8; nodeIdx++)\n//     {\n//       real gammaX = stabilizationVector[0][i][nodeIdx];\n//       real gammaY = stabilizationVector[1][i][nodeIdx];\n//       real gammaZ = stabilizationVector[2][i][nodeIdx];\n//       real fs1 = gammaX * (J(0,0)*fi(0) + J(0,1)*fi(1) + J(0,2)*fi(2));\n//       real fs2 = gammaY * (J(1,0)*fi(0) + J(1,1)*fi(1) + J(1,2)*fi(2));\n//       real fs3 = gammaZ * (J(2,0)*fi(0) + J(2,1)*fi(1) + J(2,2)*fi(2));\n// \n//       fStab(3*nodeIdx    ) += fs1;\n//       fStab(3*nodeIdx + 1) += fs2;\n//       fStab(3*nodeIdx + 2) += fs3;\n//     }\n//   }\n// \n//   // Calculate hourglass energy increment\n//   real hourglassEnergyIncrement = 0;\n//   for (int nodeIdx = 0; nodeIdx < 8; nodeIdx++)\n//   {\n//     real gammaX1 = stabilizationVector[0][0][nodeIdx];\n//     real gammaY1 = stabilizationVector[1][0][nodeIdx];\n//     real gammaZ1 = stabilizationVector[2][0][nodeIdx];\n//     real gammaX2 = stabilizationVector[0][1][nodeIdx];\n//     real gammaY2 = stabilizationVector[1][1][nodeIdx];\n//     real gammaZ2 = stabilizationVector[2][1][nodeIdx];\n//     real gammaX3 = stabilizationVector[0][2][nodeIdx];\n//     real gammaY3 = stabilizationVector[1][2][nodeIdx];\n//     real gammaZ3 = stabilizationVector[2][2][nodeIdx];\n//     real gammaX4 = stabilizationVector[0][3][nodeIdx];\n//     real gammaY4 = stabilizationVector[1][3][nodeIdx];\n//     real gammaZ4 = stabilizationVector[2][3][nodeIdx];\n// \n//     real dfs1 = gammaX1 * (J(0,0)*df11 + J(0,1)*df12 + J(0,2)*df13)\n//               + gammaX2 * (J(0,0)*df21 + J(0,1)*df22 + J(0,2)*df23)\n//               + gammaX3 * (J(0,0)*df31 + J(0,1)*df32 + J(0,2)*df33)\n//               + gammaX4 * (J(0,0)*df41 + J(0,1)*df42 + J(0,2)*df43);\n//     real dfs2 = gammaY1 * (J(1,0)*df11 + J(1,1)*df12 + J(1,2)*df13)\n//               + gammaY2 * (J(1,0)*df21 + J(1,1)*df22 + J(1,2)*df23)\n//               + gammaY3 * (J(1,0)*df31 + J(1,1)*df32 + J(1,2)*df33)\n//               + gammaY4 * (J(1,0)*df41 + J(1,1)*df42 + J(1,2)*df43);\n//     real dfs3 = gammaZ1 * (J(2,0)*df11 + J(2,1)*df12 + J(2,2)*df13)\n//               + gammaZ2 * (J(2,0)*df21 + J(2,1)*df22 + J(2,2)*df23)\n//               + gammaZ3 * (J(2,0)*df31 + J(2,1)*df32 + J(2,2)*df33)\n//               + gammaZ4 * (J(2,0)*df41 + J(2,1)*df42 + J(2,2)*df43);\n// \n//     hourglassEnergyIncrement += dfs1*du(3*nodeIdx) + dfs2*du(3*nodeIdx + 1) + dfs3*du(3*nodeIdx + 2);\n//   }\n//   hourglassEnergy_ += hourglassEnergyIncrement;\n// \n//   // Step 8: Stabilize internal force\n//   afb::VectorAlgebra::Sum(internalForce, 1.0, internalForce, 1.0, fStab);\n// }\n", "meta": {"hexsha": "e1501823f2e07376f96861e840c0358fde7f2e45", "size": 25644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Axis.StandardElements/domain/formulations/LinearHexahedralPusoFormulation.cpp", "max_stars_repo_name": "renato-yuzup/axis-fem", "max_stars_repo_head_hexsha": "2e8d325eb9c8e99285f513b4c1218ef53eb0ab22", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-23T08:49:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T22:07:30.000Z", "max_issues_repo_path": "Axis.StandardElements/domain/formulations/LinearHexahedralPusoFormulation.cpp", "max_issues_repo_name": "renato-yuzup/axis-fem", "max_issues_repo_head_hexsha": "2e8d325eb9c8e99285f513b4c1218ef53eb0ab22", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Axis.StandardElements/domain/formulations/LinearHexahedralPusoFormulation.cpp", "max_forks_repo_name": "renato-yuzup/axis-fem", "max_forks_repo_head_hexsha": "2e8d325eb9c8e99285f513b4c1218ef53eb0ab22", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5130970724, "max_line_length": 116, "alphanum_fraction": 0.5917953517, "num_tokens": 10019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2074611873157537}}
{"text": "\n#ifndef OFFVSETACFITTED_HPP\n#define OFFVSETACFITTED_HPP\n\n#include <vector>\n#include <string>\n#include <boost/serialization/list.hpp>\n#include <boost/serialization/set.hpp>\n#include <boost/serialization/vector.hpp>\n#include <boost/filesystem.hpp>\n#include <tbb/parallel_for.h>\n#include <tbb/blocked_range.h>\n\n#include \"arch/AACAgent.hpp\"\n#include \"bib/Seed.hpp\"\n#include \"bib/Utils.hpp\"\n#include <bib/MetropolisHasting.hpp>\n#include <bib/XMLEngine.hpp>\n#include \"MLP.hpp\"\n#include \"kde.hpp\"\n#include \"kdtree++/kdtree.hpp\"\n\n#define DOUBLE_COMPARE_PRECISION 1e-9\n\ntypedef struct _sample {\n  std::vector<double> s;\n  std::vector<double> pure_a;\n  std::vector<double> a;\n  std::vector<double> next_s;\n  double r;\n  bool goal_reached;\n\n  friend class boost::serialization::access;\n  template <typename Archive>\n  void serialize(Archive& ar, const unsigned int) {\n    ar& BOOST_SERIALIZATION_NVP(s);\n    ar& BOOST_SERIALIZATION_NVP(pure_a);\n    ar& BOOST_SERIALIZATION_NVP(a);\n    ar& BOOST_SERIALIZATION_NVP(next_s);\n    ar& BOOST_SERIALIZATION_NVP(r);\n    ar& BOOST_SERIALIZATION_NVP(goal_reached);\n  }\n\n  //Used to store all sample into a tree, might be stochastic\n  //only pure_a is negligate\n  bool operator< (const _sample& b) const {\n    for (uint i = 0; i < s.size(); i++) {\n      if(fabs(s[i] - b.s[i])>=DOUBLE_COMPARE_PRECISION)\n        return s[i] < b.s[i];\n    }\n    \n    for (uint i = 0; i < a.size(); i++) {\n      if(fabs(a[i] - b.a[i])>=DOUBLE_COMPARE_PRECISION)\n        return a[i] < b.a[i];\n    }\n    \n    for (uint i = 0; i < next_s.size(); i++) {\n      if(fabs(next_s[i] - b.next_s[i])>=DOUBLE_COMPARE_PRECISION)\n        return next_s[i] < b.next_s[i];\n    }\n    \n    if(fabs(r - b.r)>=DOUBLE_COMPARE_PRECISION)\n        return r < b.r;\n\n    return goal_reached < b.goal_reached;\n  }\n  \n  typedef double value_type;\n\n  inline double operator[](size_t const N) const{\n        return s[N];\n  }\n  \n  bool same_state(const _sample& b) const{\n    for (uint i = 0; i < s.size(); i++) {\n      if(fabs(s[i] - b.s[i])>=DOUBLE_COMPARE_PRECISION)\n        return false;\n    }\n    \n    return true;\n  }\n\n} sample;\n\n\nclass OffVSetACFitted : public arch::AACAgent<MLP, arch::AgentProgOptions> {\n public:\n  typedef MLP PolicyImpl;\n   \n  OffVSetACFitted(unsigned int _nb_motors, unsigned int _nb_sensors)\n    : arch::AACAgent<MLP, arch::AgentProgOptions>(_nb_motors), nb_sensors(_nb_sensors) {\n\n  }\n\n  virtual ~OffVSetACFitted() {\n    delete kdtree_s;\n    \n    delete vnn;\n    delete ann;\n  }\n\n  const std::vector<double>& _run(double reward, const std::vector<double>& sensors,\n                                 bool learning, bool goal_reached, bool) {\n\n    vector<double>* next_action = ann->computeOut(sensors);\n    \n    if (last_action.get() != nullptr && learning){\n      trajectory.insert({last_state, *last_pure_action, *last_action, sensors, reward, goal_reached});\n      last_trajectory.insert( {last_state, *last_pure_action, *last_action, sensors, reward, goal_reached});\n      proba_s.add_data(last_state);\n      \n      sample sa = {last_state, *last_pure_action, *last_action, sensors, reward, goal_reached};\n      kdtree_s->insert(sa);\n    }\n\n    last_pure_action.reset(new vector<double>(*next_action));\n    if(learning) {\n      if(gaussian_policy){\n        vector<double>* randomized_action = bib::Proba<double>::multidimentionnalGaussianWReject(*next_action, noise);\n        delete next_action;\n        next_action = randomized_action;\n      } else if(bib::Utils::rand01() < noise){ //e-greedy\n        for (uint i = 0; i < next_action->size(); i++)\n          next_action->at(i) = bib::Utils::randin(-1.f, 1.f);\n      }\n    }\n    last_action.reset(next_action);\n\n\n    last_state.clear();\n    for (uint i = 0; i < sensors.size(); i++)\n      last_state.push_back(sensors[i]);\n\n    return *next_action;\n  }\n\n\n  void _unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map*) override {\n    hidden_unit_v           = pt->get<int>(\"agent.hidden_unit_v\");\n    hidden_unit_a           = pt->get<int>(\"agent.hidden_unit_a\");\n    noise                   = pt->get<double>(\"agent.noise\");\n    gaussian_policy         = pt->get<bool>(\"agent.gaussian_policy\");\n    lecun_activation        = pt->get<bool>(\"agent.lecun_activation\");\n    change_v_each           = pt->get<uint>(\"agent.change_v_each\");\n    strategy_u              = pt->get<uint>(\"agent.strategy_u\");\n    current_loaded_v        = pt->get<uint>(\"agent.index_starting_loaded_v\");\n\n    if(hidden_unit_v == 0)\n      vnn = new LinMLP(nb_sensors + nb_motors , 1, 0.0, lecun_activation);\n    else\n      vnn = new MLP(nb_sensors + nb_motors, hidden_unit_v, nb_sensors, 0.0, lecun_activation);\n\n    if(hidden_unit_a == 0)\n      ann = new LinMLP(nb_sensors , nb_motors, 0.0, lecun_activation);\n    else\n      ann = new MLP(nb_sensors, hidden_unit_a, nb_motors, lecun_activation);\n    \n    kdtree_s = new kdtree_sample(nb_sensors);\n  }\n\n  void _start_episode(const std::vector<double>& sensors, bool) override {\n    last_state.clear();\n    for (uint i = 0; i < sensors.size(); i++)\n      last_state.push_back(sensors[i]);\n\n    last_action = nullptr;\n    last_pure_action = nullptr;\n    \n    //trajectory.clear();\n    last_trajectory.clear();\n    \n    fann_reset_MSE(vnn->getNeuralNet());\n    \n    if(episode == 0 || episode % change_v_each == 0){\n      if (! boost::filesystem::exists( \"vset.\"+std::to_string(current_loaded_v) ) ){\n        LOG_ERROR(\"file doesn't exists \"<< \"vset.\"+std::to_string(current_loaded_v));\n        exit(1);\n      }\n      \n      vnn->load(\"vset.\"+std::to_string(current_loaded_v));\n      current_loaded_v++;\n      end_episode();\n    }\n  }\n  \n  void update_actor_old_lw(){\n    if (last_trajectory.size() > 0) {\n      struct fann_train_data* data = fann_create_train(last_trajectory.size(), nb_sensors, nb_motors);\n\n      uint n=0;\n      std::vector<double> deltas;\n      for(auto it = last_trajectory.begin(); it != last_trajectory.end() ; ++it) {\n        sample sm = *it;\n\n        double target = 0.f;\n        double mine = 0.f;\n        \n\ttarget = sm.r;\n\tif (!sm.goal_reached) {\n          std::vector<double> * next_action = ann->computeOut(sm.next_s);\n\t  double nextV = vnn->computeOutVF(sm.next_s, *next_action);\n\t  target += gamma * nextV;\n          delete next_action;\n\t}\n\tmine = vnn->computeOutVF(sm.s, sm.a);\n\n        if(target > mine) {\n          for (uint i = 0; i < nb_sensors ; i++)\n            data->input[n][i] = sm.s[i];\n          for (uint i = 0; i < nb_motors; i++)\n            data->output[n][i] = sm.a[i];\n        \n          deltas.push_back(target - mine);\n          n++;\n        }\n      }\n          \n\n      if(n > 0) {\n        double* importance = new double[n];\n        double norm = *std::max_element(deltas.begin(), deltas.end());\n        for (uint i =0 ; i < n; i++){\n            importance[i] = deltas[i] / norm;\n        }    \n        \n        struct fann_train_data* subdata = fann_subset_train_data(data, 0, n);\n\n        ann->learn_stoch_lw(subdata, importance, 5000, 0, 0.0001);\n\n        fann_destroy_train(subdata);\n        \n        delete[] importance;\n      }\n      fann_destroy_train(data);\n      \n    } \n  }\n  \n  void update_actor_old_lw_all(){\n    if (trajectory.size() > 0) {\n      struct fann_train_data* data = fann_create_train(trajectory.size(), nb_sensors, nb_motors);\n\n      uint n=0;\n      std::vector<double> deltas;\n      for(auto it = trajectory.begin(); it != trajectory.end() ; ++it) {\n        sample sm = *it;\n\n        double target = 0.f;\n        double mine = 0.f;\n        \n\ttarget = sm.r;\n\tif (!sm.goal_reached) {\n          std::vector<double> * next_action = ann->computeOut(sm.next_s);\n\t  double nextV = vnn->computeOutVF(sm.next_s, *next_action);\n\t  target += gamma * nextV;\n          delete next_action;\n\t}\n\tmine = vnn->computeOutVF(sm.s, sm.a);\n\n        if(target > mine) {\n          for (uint i = 0; i < nb_sensors ; i++)\n            data->input[n][i] = sm.s[i];\n          for (uint i = 0; i < nb_motors; i++)\n            data->output[n][i] = sm.a[i];\n        \n          deltas.push_back(target - mine);\n          n++;\n        }\n      }\n          \n\n      if(n > 0) {\n        double* importance = new double[n];\n        double norm = *std::max_element(deltas.begin(), deltas.end());\n        for (uint i =0 ; i < n; i++){\n            importance[i] = deltas[i] / norm;\n        }    \n        \n        struct fann_train_data* subdata = fann_subset_train_data(data, 0, n);\n\n        ann->learn_stoch_lw(subdata, importance, 5000, 0, 0.0001);\n\n        fann_destroy_train(subdata);\n        \n        delete[] importance;\n      }\n      fann_destroy_train(data);\n      \n    } \n  }\n\n  void update_actor_old(){\n     if (last_trajectory.size() > 0) {\n      bool update_delta_neg;\n      bool update_pure_ac;\n      \n      switch(strategy_u){\n        case 0:\n          update_pure_ac=false;\n          update_delta_neg=false;\n          break;\n        case 1:\n          update_pure_ac=true;\n          update_delta_neg=false;\n          break;\n        case 2:\n          update_pure_ac=false;\n          update_delta_neg=true;\n          break;\n      }\n\n      struct fann_train_data* data = fann_create_train(last_trajectory.size(), nb_sensors, nb_motors);\n\n      uint n=0;\n      for(auto it = last_trajectory.begin(); it != last_trajectory.end() ; ++it) {\n        sample sm = *it;\n\n        double target = 0.f;\n        double mine = 0.f;\n        \n\ttarget = sm.r;\n\tif (!sm.goal_reached) {\n          std::vector<double> * next_action = ann->computeOut(sm.next_s);\n\t  double nextV = vnn->computeOutVF(sm.next_s, *next_action);\n\t  target += gamma * nextV;\n          delete next_action;\n\t}\n\tmine = vnn->computeOutVF(sm.s, sm.a);\n\n        if(target > mine) {\n          for (uint i = 0; i < nb_sensors ; i++)\n            data->input[n][i] = sm.s[i];\n          if(update_pure_ac){\n            for (uint i = 0; i < nb_motors; i++)\n              data->output[n][i] = sm.pure_a[i];\n          } else {\n            for (uint i = 0; i < nb_motors; i++)\n              data->output[n][i] = sm.a[i];\n          }\n\n          n++;\n        } else if(update_delta_neg && !update_pure_ac){\n            for (uint i = 0; i < nb_sensors ; i++)\n              data->input[n][i] = sm.s[i];\n            for (uint i = 0; i < nb_motors; i++)\n              data->output[n][i] = sm.pure_a[i];\n            n++;\n        }\n      }\n\n      if(n > 0) {\n        struct fann_train_data* subdata = fann_subset_train_data(data, 0, n);\n\n        ann->learn_stoch(subdata, 5000, 0, 0.0001);\n\n        fann_destroy_train(subdata);\n      }\n      fann_destroy_train(data);\n    }\n  }\n  \n  void update_actor_old_all(){\n     if (trajectory.size() > 0) {\n      bool update_pure_ac=false;\n      bool update_delta_neg=false;\n\n      struct fann_train_data* data = fann_create_train(trajectory.size(), nb_sensors, nb_motors);\n\n      uint n=0;\n      for(auto it = trajectory.begin(); it != trajectory.end() ; ++it) {\n        sample sm = *it;\n\n        double target = 0.f;\n        double mine = 0.f;\n        \n\ttarget = sm.r;\n\tif (!sm.goal_reached) {\n          std::vector<double> * next_action = ann->computeOut(sm.next_s);\n\t  double nextV = vnn->computeOutVF(sm.next_s, *next_action);\n\t  target += gamma * nextV;\n          delete next_action;\n\t}\n\tmine = vnn->computeOutVF(sm.s, sm.a);\n\n        if(target > mine) {\n          for (uint i = 0; i < nb_sensors ; i++)\n            data->input[n][i] = sm.s[i];\n          if(update_pure_ac){\n            for (uint i = 0; i < nb_motors; i++)\n              data->output[n][i] = sm.pure_a[i];\n          } else {\n            for (uint i = 0; i < nb_motors; i++)\n              data->output[n][i] = sm.a[i];\n          }\n\n          n++;\n        } else if(update_delta_neg && !update_pure_ac){\n            for (uint i = 0; i < nb_sensors ; i++)\n              data->input[n][i] = sm.s[i];\n            for (uint i = 0; i < nb_motors; i++)\n              data->output[n][i] = sm.pure_a[i];\n            n++;\n        }\n      }\n\n      if(n > 0) {\n        struct fann_train_data* subdata = fann_subset_train_data(data, 0, n);\n\n        ann->learn_stoch(subdata, 5000, 0, 0.0001);\n\n        fann_destroy_train(subdata);\n      }\n      fann_destroy_train(data);\n    }\n  }\n  \n   void update_actor_nfqca(){\n    if(trajectory.size() > 0) {\n      struct fann_train_data* data = fann_create_train(trajectory.size(), nb_sensors, nb_motors);\n      \n      uint n=0;\n      for(auto it = trajectory.begin(); it != trajectory.end() ; ++it) {\n        sample sm = *it;\n        \n        for (uint i = 0; i < nb_sensors ; i++)\n          data->input[n][i] = sm.s[i];\n        \n        for (uint i = 0; i < nb_motors; i++)\n          data->output[n][i] = 0.f;//sm.a[i]; //don't care\n\n        n++;\n      }\n      \n      datann_derivative d = {vnn, (int)nb_sensors, (int)nb_motors};\n    \n//       auto iter = [&]() {\n//         fann_train_epoch_irpropm_gradient(ann->getNeuralNet(), data, derivative_nn, &d);\n//       };\n// \n//       auto eval = [&]() {\n//         //compute weight sum\n//         return ann->weight_l1_norm();\n//       };\n// \n//       bib::Converger::determinist<>(iter, eval, 1, 0.0001, 25, \"actor\");\n      fann_train_epoch_irpropm_gradient(ann->getNeuralNet(), data, derivative_nn, &d);\n      \n      fann_destroy_train(data);\n    }\n  }\n  \n  \n  void end_episode() override {\n    if(strategy_u <= 2)\n      update_actor_old();\n    else if(strategy_u <= 3)\n      update_actor_old_lw();\n    else if(strategy_u == 10)\n      update_actor_nfqca();\n    else if(strategy_u == 15)\n      update_actor_old_lw_all();\n    else if(strategy_u == 20)\n      update_actor_old_all();\n    else {\n      LOG_ERROR(\"not implemented\");\n      exit(1); \n    }\n    \n  }\n  \n  void end_instance(bool) override {\n    episode++;\n  }\n  \n  double criticEval(const std::vector<double>& perceptions, const std::vector<double>& actions) override {\n    return vnn->computeOutVF(perceptions, actions);\n  }\n  \n  arch::Policy<MLP>* getCopyCurrentPolicy() override {\n        return new arch::Policy<MLP>(new MLP(*ann) , gaussian_policy ? arch::policy_type::GAUSSIAN : arch::policy_type::GREEDY, noise, decision_each);\n  }\n\n  void save(const std::string& path) override {\n    ann->save(path+\".actor\");\n    vnn->save(path+\".critic\");\n    bib::XMLEngine::save<>(trajectory, \"trajectory\", \"trajectory.data\");\n  }\n\n  void load(const std::string& path) override {\n    ann->load(path+\".actor\");\n    vnn->load(path+\".critic\");\n  }\n\n protected:\n  void _display(std::ostream& out) const override {\n    out << std::setw(12) << std::fixed << std::setprecision(10) << sum_weighted_reward << \" \" << std::setw(\n          8) << std::fixed << std::setprecision(5) << vnn->error() << \" \" << noise << \" \" << trajectory.size() ;\n  }\n\n  void _dump(std::ostream& out) const override {\n    out <<\" \" << std::setw(25) << std::fixed << std::setprecision(22) <<\n        sum_weighted_reward << \" \" << std::setw(8) << std::fixed <<\n        std::setprecision(5) << vnn->error() << \" \" << trajectory.size() ;\n  }\n  \n\n private:\n  uint nb_sensors;\n  \n  uint episode = 0;\n  uint current_loaded_v = 0;\n  uint change_v_each;\n  uint strategy_u;\n\n  double noise;\n  bool gaussian_policy, lecun_activation;\n  uint hidden_unit_v;\n  uint hidden_unit_a;\n  \n  std::shared_ptr<std::vector<double>> last_action;\n  std::shared_ptr<std::vector<double>> last_pure_action;\n  std::vector<double> last_state;\n\n  std::set<sample> trajectory;\n  std::set<sample> last_trajectory;\n//     std::list<sample> trajectory;\n  KDE proba_s;\n  \n  struct L1_distance\n  {\n    typedef double distance_type;\n    \n    double operator() (const double& __a, const double& __b, const size_t) const\n    {\n      double d = fabs(__a - __b);\n      return d;\n    }\n  };\n  typedef KDTree::KDTree<sample, KDTree::_Bracket_accessor<sample>, L1_distance> kdtree_sample;\n  kdtree_sample* kdtree_s;\n\n  MLP* ann;\n  MLP* vnn;\n};\n\n#endif\n\n", "meta": {"hexsha": "8eaf14cf2a8bdbc6eb20ad22dd047e46676cbc9e", "size": 15809, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "agent/cacla/include/old/OffVSetACFitted.hpp", "max_stars_repo_name": "matthieu637/ddrl", "max_stars_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2017-11-27T09:32:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T13:50:23.000Z", "max_issues_repo_path": "agent/cacla/include/old/OffVSetACFitted.hpp", "max_issues_repo_name": "matthieu637/ddrl", "max_issues_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2018-10-09T14:39:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-10T15:01:00.000Z", "max_forks_repo_path": "agent/cacla/include/old/OffVSetACFitted.hpp", "max_forks_repo_name": "matthieu637/ddrl", "max_forks_repo_head_hexsha": "a454d09a3ac9be5db960ff180b3d075c2f9e4a70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-16T09:14:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-15T14:35:40.000Z", "avg_line_length": 28.848540146, "max_line_length": 150, "alphanum_fraction": 0.5823265229, "num_tokens": 4374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.538983220687684, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20746118731575364}}
{"text": "<<<<<<< HEAD\n/*    Copyright (c) 2010-2018, Delft University of Technology\n=======\n/*    Copyright (c) 2010-2019, Delft University of Technology\n>>>>>>> origin/master\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <boost/make_shared.hpp>\n#include \"Tudat/Astrodynamics/Ephemerides/simpleRotationalEphemeris.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/fullPlanetaryRotationModel.h\"\n\n#if USE_CSPICE\n#include \"Tudat/External/SpiceInterface/spiceRotationalEphemeris.h\"\n#endif\n\n#include \"Tudat/SimulationSetup/EnvironmentSetup/createRotationModel.h\"\n\n#if USE_SOFA\n#include \"Tudat/Astrodynamics/Ephemerides/itrsToGcrsRotationModel.h\"\n#include \"Tudat/Astrodynamics/Ephemerides/synchronousRotationalEphemeris.h\"\n#include \"Tudat/Astrodynamics/EarthOrientation/earthOrientationCalculator.h\"\n#include \"Tudat/Astrodynamics/EarthOrientation/shortPeriodEarthOrientationCorrectionCalculator.h\"\n#include \"Tudat/Mathematics/Interpolators/jumpDataLinearInterpolator.h\"\n#endif\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\n//! Function to retrieve a state from one of two functions\nEigen::Vector6d getStateFromSelectedStateFunction(\n        const double currentTime,\n        const bool useFirstFunction,\n        const std::function< Eigen::Vector6d( const double ) > stateFunction1,\n        const std::function< Eigen::Vector6d( const double ) > stateFunction2 )\n{\n    return ( useFirstFunction ) ? ( stateFunction1( currentTime ) ) : ( stateFunction2( currentTime ) );\n}\n\n\n//! Function to create a state function for a body, valid both during propagation, and outside propagation\nstd::function< Eigen::Vector6d( const double, bool ) > createRelativeStateFunction(\n        const NamedBodyMap& bodyMap,\n        const std::string orbitingBody,\n        const std::string centralBody )\n{\n    // Retrieve state functions for relevant bodies (obtained from current state of body objects)\n    std::function< Eigen::Vector6d( const double ) > bodyInertialStateFunction =\n            std::bind( &Body::getState, bodyMap.at( orbitingBody ) );\n    std::function< Eigen::Vector6d( const double ) > centralBodyInertialStateFunction =\n            std::bind( &Body::getState, bodyMap.at(  centralBody ) );\n\n    // Define relative state function from body object\n    std::function< Eigen::Vector6d( const double ) > fromBodyStateFunction =\n            std::bind(\n                &ephemerides::getDifferenceBetweenStates, bodyInertialStateFunction,\n                centralBodyInertialStateFunction, std::placeholders::_1 );\n\n    // Define state function from ephemeris\n    std::function< Eigen::Vector6d( const double ) > fromEphemerisStateFunction;\n\n    if( bodyMap.at( orbitingBody )->getEphemeris( )->getReferenceFrameOrigin( ) == centralBody )\n    {\n        fromEphemerisStateFunction = std::bind( &ephemerides::Ephemeris::getCartesianState,\n                                                bodyMap.at( orbitingBody )->getEphemeris( ), std::placeholders::_1 );\n\n    }\n    else\n    {\n        std::function< Eigen::Vector6d( const double ) > ephemerisInertialStateFunction =\n                std::bind( &Body::getStateInBaseFrameFromEphemeris< double, double >, bodyMap.at( orbitingBody ),\n                           std::placeholders::_1 );\n        std::function< Eigen::Vector6d( const double ) > ephemerisCentralBodyInertialStateFunction =\n                std::bind( &Body::getStateInBaseFrameFromEphemeris< double, double >, bodyMap.at( centralBody ),\n                           std::placeholders::_1 );\n        fromEphemerisStateFunction = std::bind(\n                    &ephemerides::getDifferenceBetweenStates,\n                    ephemerisInertialStateFunction,\n                    ephemerisCentralBodyInertialStateFunction, std::placeholders::_1 );\n    }\n\n    return std::bind( &getStateFromSelectedStateFunction, std::placeholders::_1, std::placeholders::_2,\n                      fromBodyStateFunction, fromEphemerisStateFunction );\n}\n\n//! Function to create a rotation model.\nstd::shared_ptr< ephemerides::RotationalEphemeris > createRotationModel(\n        const std::shared_ptr< RotationModelSettings > rotationModelSettings,\n        const std::string& body,\n        const NamedBodyMap& bodyMap )\n{\n    using namespace tudat::ephemerides;\n\n    // Declare return object.\n    std::shared_ptr< RotationalEphemeris > rotationalEphemeris;\n\n    // Check which type of rotation model is to be created.\n    switch( rotationModelSettings->getRotationType( ) )\n    {\n    case simple_rotation_model:\n    {\n        // Check whether settings for simple rotation model are consistent with its type.\n        std::shared_ptr< SimpleRotationModelSettings > simpleRotationSettings =\n                std::dynamic_pointer_cast< SimpleRotationModelSettings >( rotationModelSettings );\n        if( simpleRotationSettings == nullptr )\n        {\n            throw std::runtime_error(\n                        \"Error, expected simple rotation model settings for \" + body );\n        }\n        else\n        {\n            // Create and initialize simple rotation model.\n            rotationalEphemeris = std::make_shared< SimpleRotationalEphemeris >(\n                        simpleRotationSettings->getInitialOrientation( ),\n                        simpleRotationSettings->getRotationRate( ),\n                        simpleRotationSettings->getInitialTime( ),\n                        simpleRotationSettings->getOriginalFrame( ),\n                        simpleRotationSettings->getTargetFrame( ) );\n        }\n        break;\n    }\n#if USE_SOFA\n    case gcrs_to_itrs_rotation_model:\n    {\n\n        // Check whether settings for simple rotation model are consistent with its type.\n        std::shared_ptr< GcrsToItrsRotationModelSettings > gcrsToItrsRotationSettings =\n                std::dynamic_pointer_cast< GcrsToItrsRotationModelSettings >( rotationModelSettings );\n        if( gcrsToItrsRotationSettings == nullptr )\n        {\n            throw std::runtime_error(\n                        \"Error, expected GCRS to ITRS rotation model settings for \" + body );\n        }\n        else\n        {\n            std::shared_ptr< earth_orientation::EOPReader > eopReader = std::make_shared< earth_orientation::EOPReader >(\n                        gcrsToItrsRotationSettings->getEopFile( ),\n                        gcrsToItrsRotationSettings->getEopFileFormat( ),\n                        gcrsToItrsRotationSettings->getNutationTheory( ) );\n\n            // Load polar motion corrections\n            std::shared_ptr< interpolators::LinearInterpolator< double, Eigen::Vector2d > > cipInItrsInterpolator =\n                    std::make_shared< interpolators::LinearInterpolator< double, Eigen::Vector2d > >(\n                        eopReader->getCipInItrsMapInSecondsSinceJ2000( ) );\n\n            // Load nutation corrections\n            std::shared_ptr< interpolators::LinearInterpolator< double, Eigen::Vector2d > > cipInGcrsCorrectionInterpolator =\n                    std::make_shared< interpolators::LinearInterpolator< double, Eigen::Vector2d > >(\n                        eopReader->getCipInGcrsCorrectionMapInSecondsSinceJ2000( ) );\n\n            // Create polar motion correction (sub-diural frequencies) object\n            std::shared_ptr< earth_orientation::ShortPeriodEarthOrientationCorrectionCalculator< Eigen::Vector2d > >\n                    shortPeriodPolarMotionCalculator =\n                    std::make_shared< earth_orientation::ShortPeriodEarthOrientationCorrectionCalculator< Eigen::Vector2d > >(\n                        gcrsToItrsRotationSettings->getPolarMotionCorrectionSettings( )->conversionFactor_,\n                        gcrsToItrsRotationSettings->getPolarMotionCorrectionSettings( )->minimumAmplitude_,\n                        gcrsToItrsRotationSettings->getPolarMotionCorrectionSettings( )->amplitudesFiles_,\n                        gcrsToItrsRotationSettings->getPolarMotionCorrectionSettings( )->argumentMultipliersFile_ );\n\n            // Create full polar motion calculator\n            std::shared_ptr< earth_orientation::PolarMotionCalculator > polarMotionCalculator =\n                    std::make_shared< earth_orientation::PolarMotionCalculator >\n                    ( cipInItrsInterpolator, shortPeriodPolarMotionCalculator );\n\n            // Create IAU 2006 precession/nutation calculator\n            std::shared_ptr< earth_orientation::PrecessionNutationCalculator > precessionNutationCalculator =\n                    std::make_shared< earth_orientation::PrecessionNutationCalculator >(\n                        gcrsToItrsRotationSettings->getNutationTheory( ), cipInGcrsCorrectionInterpolator );\n\n            // Create UT1 correction (sub-diural frequencies) object\n            std::shared_ptr< earth_orientation::ShortPeriodEarthOrientationCorrectionCalculator< double > >\n                    ut1CorrectionSettings =\n                    std::make_shared< earth_orientation::ShortPeriodEarthOrientationCorrectionCalculator< double > >(\n                        gcrsToItrsRotationSettings->getUt1CorrectionSettings( )->conversionFactor_,\n                        gcrsToItrsRotationSettings->getUt1CorrectionSettings( )->minimumAmplitude_,\n                        gcrsToItrsRotationSettings->getUt1CorrectionSettings( )->amplitudesFiles_,\n                        gcrsToItrsRotationSettings->getUt1CorrectionSettings( )->argumentMultipliersFile_ );\n\n            std::shared_ptr< interpolators::OneDimensionalInterpolator < double, double > > dailyUtcUt1CorrectionInterpolator =\n                    std::make_shared< interpolators::JumpDataLinearInterpolator< double, double > >(\n                        eopReader->getUt1MinusUtcMapInSecondsSinceJ2000( ), 0.5, 1.0 );\n\n            // Create default time scale converter\n            std::shared_ptr< earth_orientation::TerrestrialTimeScaleConverter > terrestrialTimeScaleConverter =\n                    std::make_shared< earth_orientation::TerrestrialTimeScaleConverter >\n                    (  dailyUtcUt1CorrectionInterpolator, ut1CorrectionSettings );\n\n            // Create rotation model\n            std::shared_ptr< earth_orientation::EarthOrientationAnglesCalculator > earthOrientationCalculator =\n                    std::make_shared< earth_orientation::EarthOrientationAnglesCalculator >(\n                        polarMotionCalculator, precessionNutationCalculator, terrestrialTimeScaleConverter );\n            rotationalEphemeris = std::make_shared< ephemerides::GcrsToItrsRotationModel >(\n                        earthOrientationCalculator, gcrsToItrsRotationSettings->getInputTimeScale( ),\n                        gcrsToItrsRotationSettings->getOriginalFrame( ) );\n\n            break;\n        }\n\n    }\n#endif\n\n#if USE_CSPICE\n    case spice_rotation_model:\n    {\n        // Create rotational ephemeris directly from Spice.\n        rotationalEphemeris = std::make_shared< SpiceRotationalEphemeris >(\n                    rotationModelSettings->getOriginalFrame( ),\n                    rotationModelSettings->getTargetFrame( ) );\n        break;\n    }\n#endif\n<<<<<<< HEAD\n=======\n    case planetary_rotation_model:\n    {\n        std::shared_ptr< PlanetaryRotationModelSettings > planetaryRotationModelSettings =\n                std::dynamic_pointer_cast< PlanetaryRotationModelSettings >( rotationModelSettings );\n        if( planetaryRotationModelSettings == nullptr )\n        {\n            std::cerr<<\"Error, expected planetary rotation model settings for \"<<body<<std::endl;\n        }\n        else\n        {\n\n            Eigen::VectorXd bodyKeplerElements = orbital_element_conversions::convertCartesianToKeplerianElements(\n                        spice_interface::getBodyCartesianStateAtEpoch(\n                            body, planetaryRotationModelSettings->getCentralBody( ), \"ECLIPJ2000\", \"NONE\", 0.0 ),\n                        spice_interface::getBodyGravitationalParameter( planetaryRotationModelSettings->getCentralBody( ) ) );\n\n            double meanAnomalyAtJ2000 = orbital_element_conversions::convertEccentricAnomalyToMeanAnomaly(\n                        orbital_element_conversions::convertTrueAnomalyToEccentricAnomaly(\n                            bodyKeplerElements( 5 ), bodyKeplerElements( 1 ) ), bodyKeplerElements( 1 ) );\n\n            double meanMotion = orbital_element_conversions::convertSemiMajorAxisToEllipticalMeanMotion(\n                        bodyKeplerElements( 0 ), spice_interface::getBodyGravitationalParameter(\n                            planetaryRotationModelSettings->getCentralBody( ) ) + spice_interface::getBodyGravitationalParameter( body ) );\n\n            std::shared_ptr< PlanetaryOrientationAngleCalculator > planetaryOrientationAnglesCalculator\n                    = std::make_shared< PlanetaryOrientationAngleCalculator >(\n                        planetaryRotationModelSettings->getAnglePsiAtEpoch( ),\n                        planetaryRotationModelSettings->getAnglePsiRateAtEpoch( ),\n                        planetaryRotationModelSettings->getAngleIAtEpoch( ),\n                        planetaryRotationModelSettings->getAngleIRateAtEpoch( ),\n                        planetaryRotationModelSettings->getAnglePhiAtEpoch( ),\n                        planetaryRotationModelSettings->getAnglePhiRateAtEpoch( ),\n                        planetaryRotationModelSettings->getCoreFactor( ),\n                        planetaryRotationModelSettings->getFreeCoreNutationRate( ),\n                        meanMotion, meanAnomalyAtJ2000,\n                        planetaryRotationModelSettings->getOriginalFrame( ),\n                        planetaryRotationModelSettings->getMeanMotionDirectNutationCorrections( ),\n                        planetaryRotationModelSettings->getMeanMotionTimeDependentPhaseNutationCorrections( ),\n                        planetaryRotationModelSettings->getTimeDependentPhaseCorrectionFunctions( ),\n                        planetaryRotationModelSettings->getRotationRateCorrections( ),\n                        planetaryRotationModelSettings->getxPolarMotionCoefficients( ),\n                        planetaryRotationModelSettings->getyPolarMotionCoefficients( ) );\n\n\n            rotationalEphemeris = std::make_shared< PlanetaryRotationModel >(\n                        planetaryRotationModelSettings->getAngleN( ),\n                        planetaryRotationModelSettings->getAngleJ( ),\n                        planetaryOrientationAnglesCalculator,\n                        planetaryRotationModelSettings->getOriginalFrame( ), planetaryRotationModelSettings->getTargetFrame( ) );\n        }\n\n        break;\n    }\n>>>>>>> origin/master\n    case synchronous_rotation_model:\n    {\n        std::shared_ptr< SynchronousRotationModelSettings > synchronousRotationSettings =\n                std::dynamic_pointer_cast< SynchronousRotationModelSettings >( rotationModelSettings );\n        if( synchronousRotationSettings == NULL )\n        {\n            throw std::runtime_error( \"Error, expected synchronous rotation model settings for \" + body );\n        }\n        else\n        {\n            if( bodyMap.at( body )->getEphemeris( )->getReferenceFrameOrigin( ) == synchronousRotationSettings->getCentralBodyName( ) )\n            {\n                if( bodyMap.at( body )->getEphemeris( )->getReferenceFrameOrientation( ) !=\n                        synchronousRotationSettings->getOriginalFrame( ) )\n                {\n                    throw std::runtime_error( \"Error, ephemeris of body \" + body + \" is in \" +\n                                              bodyMap.at( body )->getEphemeris( )->getReferenceFrameOrientation( ) +\n                                              \" frame when making synchronous rotation model, expected \" +\n                                              synchronousRotationSettings->getOriginalFrame( ) + \" frame.\" );\n                }\n            }\n            std::shared_ptr< SynchronousRotationalEphemeris > synchronousRotationalEphemeris = std::make_shared< SynchronousRotationalEphemeris >(\n                        createRelativeStateFunction( bodyMap, body, synchronousRotationSettings->getCentralBodyName( ) ),\n                        synchronousRotationSettings->getCentralBodyName( ),\n                        synchronousRotationSettings->getOriginalFrame( ),\n                        synchronousRotationSettings->getTargetFrame( ) );\n\n            rotationalEphemeris = synchronousRotationalEphemeris;\n        }\n        break;\n    }\n    default:\n        throw std::runtime_error(\n                    \"Error, did not recognize rotation model settings type \" +\n                    std::to_string( rotationModelSettings->getRotationType( ) ) );\n    }\n\n    return rotationalEphemeris;\n}\n\n} // namespace simulation_setup\n\n} // namespace tudat\n", "meta": {"hexsha": "d26dd1d837d4ce70e483b9b5dd4d922dd2aa03a7", "size": 16981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/SimulationSetup/EnvironmentSetup/createRotationModel.cpp", "max_stars_repo_name": "ViktorJordanov/tudat", "max_stars_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/SimulationSetup/EnvironmentSetup/createRotationModel.cpp", "max_issues_repo_name": "ViktorJordanov/tudat", "max_issues_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/SimulationSetup/EnvironmentSetup/createRotationModel.cpp", "max_forks_repo_name": "ViktorJordanov/tudat", "max_forks_repo_head_hexsha": "069ceeab8f12405c356e19f50d6df037914df85c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.065625, "max_line_length": 146, "alphanum_fraction": 0.6588540133, "num_tokens": 3515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.20716130377766337}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_POINT_ON_LINE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_POINT_ON_LINE_HPP\n\n\n#include <boost/geometry/algorithms/distance.hpp>\n\nnamespace boost { namespace geometry\n{\n\n//----------------------------------------------------------------------\n// Function     : point_on_linestring -> rename to alongLine NO, different\n//----------------------------------------------------------------------\n// Purpose      : Calculates coordinates of a point along a given line\n//                on a specified distance\n// Parameters   : const L& : line,\n//                float position: position to calculate point\n//                P& point: point to calculate\n// Return       : true if point lies on line\n//----------------------------------------------------------------------\n// Author       : Barend, Geodan BV Amsterdam\n// Date         : spring 1996\n//----------------------------------------------------------------------\ntemplate <typename P, typename L>\nbool point_on_linestring(L const& line, double const& position, P& point)\n{\n    double current_distance = 0.0;\n    if (line.size() < 2)\n    {\n        return false;\n    }\n\n    typename L::const_iterator vertex = line.begin();\n    typename L::const_iterator previous = vertex++;\n\n    while (vertex != line.end())\n    {\n        double const dist = distance(*previous, *vertex);\n        current_distance += dist;\n\n        if (current_distance > position)\n        {\n            // It is not possible that dist == 0 here because otherwise\n            // the current_distance > position would not become true (current_distance is increased by dist)\n            double const fraction = 1.0 - ((current_distance - position) / dist);\n\n            // point i is too far, point i-1 to near, add fraction of\n            // distance in each direction\n            point.x ( previous->x() + (vertex->x() - previous->x()) * fraction);\n            point.y ( previous->y() + (vertex->y() - previous->y()) * fraction);\n\n            return true;\n        }\n        previous = vertex++;\n    }\n\n    // point at specified position does not lie on line\n    return false;\n}\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_POINT_ON_LINE_HPP\n", "meta": {"hexsha": "77bb23ff55c09fa3b229d5baa701679d99e59234", "size": 2791, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/algorithms/point_on_line.hpp", "max_stars_repo_name": "yumetodo/OpenSiv3D", "max_stars_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 709.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T07:55:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:02:22.000Z", "max_issues_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/algorithms/point_on_line.hpp", "max_issues_repo_name": "yumetodo/OpenSiv3D", "max_issues_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "Siv3D/src/ThirdParty/boost/geometry/extensions/algorithms/point_on_line.hpp", "max_forks_repo_name": "yumetodo/OpenSiv3D", "max_forks_repo_head_hexsha": "ea191438ecbc64185f5df3d9f79dffc6757e4192", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 36.7236842105, "max_line_length": 108, "alphanum_fraction": 0.5886778932, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.20684873326051084}}
{"text": "\n#pragma once\n\n#include <cstdint>\n#include <istream>\n#include <ostream>\n#include <stdexcept>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n#include <type_traits>\n\n#include <boost/config.hpp>\n#include <boost/random/detail/config.hpp>\n#include <boost/random/detail/seed.hpp>\n#include <boost/random/detail/seed_impl.hpp>\n#include <boost/detail/workaround.hpp>\n#include \"xoroshiro.hpp\"\n#include <boost/random/detail/disable_warnings.hpp>\n\n\nnamespace boost {\nnamespace random {\n\n#if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)\n\ntemplate<typename IntType, std::size_t w, std::size_t CMWC_CYCLE, std::uint32_t CMWC_C_MAX, std::uint64_t A, bool is_complementary>\nclass complementary_multiply_with_carry_engine {\n\ttypedef typename std::conditional<is_complementary, std::true_type, std::false_type>::type complementary;\npublic:\n\ttypedef IntType result_type;\n\n\t// Required for old Boost.Random concept.\n\tstatic const bool has_fixed_range = true;\n\tstatic const IntType default_seed = 1;\n\n\t/**\n\t* Constructs a @c complementary_multiply_with_carry_engine, using the default seed.\n\t*/\n\tcomplementary_multiply_with_carry_engine()\n\t{\n\t\tseed();\n\t}\n\n\t/**\n\t* Constructs a @c complementary_multiply_with_carry_engine, seeding it with @c value.\n\t*/\n\ttemplate<typename IT>\n\tBOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(complementary_multiply_with_carry_engine,\n\t\tIT, value)\n\t{\n\t\tseed(value);\n\t}\n\n\t/**\n\t* Constructs a @c complementary_multiply_with_carry_engine, seeding it with values\n\t* produced by a call to @c seq.generate().\n\t*/\n\tBOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(complementary_multiply_with_carry_engine,\n\t\tSeedSeq, seq)\n\t{\n\t\tseed(seq);\n\t}\n\n\t/**\n\t* Constructs a @c complementary_multiply_with_carry_engine and seeds it with values\n\t* taken from the iterator range [first, last) and adjusts\n\t* first to point to the element after the last one used.\n\t* If there are not enough elements, throws @c std::invalid_argument.\n\t*\n\t* first and last must be input iterators.\n\t*/\n\ttemplate<class It>\n\tcomplementary_multiply_with_carry_engine(It& first, It last)\n\t{\n\t\tseed(first, last);\n\t}\n\n\t// compiler-generated copy constructor and assignment operator are fine.\n\n\t/**\n\t* Calls seed(default_seed)\n\t*/\n\tvoid seed()\n\t{\n\t\tseed(default_seed);\n\t}\n\n\t/**\n\t* seeds a @c complementary_multiply_with_carry_engine with splitmix64.\n\t*/\n\ttemplate<typename IT>\n\tBOOST_RANDOM_DETAIL_ARITHMETIC_SEED(complementary_multiply_with_carry_engine, IT, value)\n\t{\n\t\tBOOST_STATIC_ASSERT(std::numeric_limits<IT>::is_integer);\n\n\t\tboost::random::splitmix64 intgen(static_cast<std::uint64_t>(value));\n\t\tdetail::generator_seed_seq<boost::random::splitmix64> gen(intgen);\n\t\tseed(gen);\n\t}\n\n\t/**\n\t* Seeds a @c complementary_multiply_with_carry_engine using values from a SeedSeq.\n\t*/\n\tBOOST_RANDOM_DETAIL_SEED_SEQ_SEED(complementary_multiply_with_carry_engine, SeedSeq, seq)\n\t{\n\t\tdetail::seed_array_int<w>(seq, _Q);\n\t\t_carry = detail::seed_one_int<IntType, CMWC_C_MAX>(seq);\n\t\t_i = CMWC_CYCLE - 1;\n\t\twarmup();\n\t}\n\n\t/**\n\t* Seeds a @c complementary_multiply_with_carry_engine with values taken from the\n\t* iterator range [first, last) and adjusts @c first to\n\t* point to the element after the last one used. If there are\n\t* not enough elements or all the whole input range is zero,\n\t* throws @c std::invalid_argument.\n\t*\n\t* @c first and @c last must be input iterators.\n\t*/\n\ttemplate<class It>\n\tvoid seed(It& first, It last)\n\t{\n\t\tdetail::fill_array_int<w>(first, last, _Q );\n\t\t_carry = detail::seed_one_int<IntType, CMWC_C_MAX>(first, last);\n\t\t_i = CMWC_CYCLE - 1;\n\t\twarmup();\n\t}\n\n\t/**\n\t* Returns the smallest value that the @c complementary_multiply_with_carry_engine\n\t* can produce.\n\t*/\n\tstatic result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ( )\n\t{ return 0; }\n\n\t/**\n\t* Returns the largest value that the @c complementary_multiply_with_carry_engine\n\t* can produce.\n\t*/\n\tstatic result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ( )\n\t{ return boost::low_bits_mask_t<w>::sig_bits; }\n\n\t/**\n\t* Returns the next value of the @c\n\t* complementary_multiply_with_carry_engine,\n\t* complemented.\n\t*/\n\ttemplate<typename U = complementary>\n\t\ttypename std::enable_if<\n\t\t\tstd::is_same<U, std::true_type>::value, result_type>::type\n\toperator()( )\n\t{\n\t\t_i = (_i + 1) & (CMWC_CYCLE - 1);\n\t\tconst std::uint64_t t = A * _Q[_i] + _carry;\n\t\t_carry = t >> 32;\n\t\tstd::uint32_t x = t + _carry;\n\t\tif (x < _carry) {\n\t\t\t++x, ++_carry;\n\t\t}\n\t\treturn (_Q[_i] = std::uint32_t { 0xFFFFFFFE } - x); // m - x\n\t}\n\n\t/**\n\t * Returns the next value of the @c\n\t * complementary_multiply_with_carry_engine,\n\t * not-complemented.\n\t */\n\ttemplate<typename U = complementary>\n\t\ttypename std::enable_if<\n\t\t\tstd::is_same<U, std::false_type>::value, result_type>::type\n\toperator()( )\n\t{\n\t\t_i = (_i + 1) & (CMWC_CYCLE - 1);\n\t\tconst std::uint64_t t = A * _Q[_i] + _carry;\n\t\t_carry = t >> 32;\n\t\tstd::uint32_t x = t + _carry;\n\t\tif (x < _carry) {\n\t\t\t++x, ++_carry;\n\t\t}\n\t\treturn (_Q[_i] = x);\n\t}\n\n\t/** Fills a range with random values. */\n\ttemplate<class Iter>\n\tvoid generate(Iter first, Iter last)\n\t{\n\t\tdetail::generate_from_int(*this, first, last);\n\t}\n\n\t/** Advances the state of the generator by @c z. */\n\tvoid discard(std::uintmax_t z)\n\t{\n\t\twhile (z--) {\n\t\t\t_i = (_i + 1) & (CMWC_CYCLE - 1);\n\t\t\tconst std::uint64_t t = A * _Q[_i] + _carry;\n\t\t\t_carry = t >> 32;\n\t\t\t_carry += ((t + _carry) < _carry);\n\t\t}\n\t}\n\n\t/** Writes a @c complementary_multiply_with_carry_engine to a @c std::ostream. */\n\ttemplate<class CharT, class Traits>\n\tfriend std::basic_ostream<CharT, Traits>&\n\t\toperator<<( std::basic_ostream<CharT, Traits>& os,\n\t\t\tconst complementary_multiply_with_carry_engine& cmwc)\n\t{\n\t\tstd::size_t i = cmwc._i;\n\t\tfor (; i < CMWC_CYCLE; ++i) {\n\t\t\tos << cmwc._Q[i] << ' ';\n\t\t}\n\t\ti = 0;\n\t\tfor (; i < cmwc._i; ++i) {\n\t\t\tos << cmwc._Q[i] << ' ';\n\t\t}\n\t\tos << cmwc._carry;\n\t\treturn os;\n\t}\n\n\t/** Reads a @c complementary_multiply_with_carry_engine from a @c std::istream. */\n\ttemplate<class CharT, class Traits>\n\tfriend std::basic_istream<CharT, Traits>&\n\t\toperator >> ( std::basic_istream<CharT, Traits>& is,\n\t\t\tcomplementary_multiply_with_carry_engine& cmwc)\n\t{\n\t\tfor (std::size_t i = 0; i < CMWC_CYCLE; ++i) {\n\t\t\tis >> cmwc._Q [ i ] >> std::ws;\n\t\t}\n\t\tis >> cmwc._carry;\n\t\tcmwc._i = 0;\n\t\treturn is;\n\t}\n\nprivate:\n\n\t// As per http://www0.cs.ucl.ac.uk/staff/D.Jones/GoodPracticeRNG.pdf\n\tinline void warmup()\n\t{\n\t\tdiscard(4 * CMWC_CYCLE);\n\t}\n\n\tIntType _Q[CMWC_CYCLE];\n\tstd::size_t _i;\n\tIntType _carry;\n};\n\n\nusing mwc256 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 256, 809430660, 1540315826, false>;\n\n/*\n * Generators below from:\n *\n * Marsaglia, George (2003) \"Random Number Generators,\"Journal of Modern Applied Statistical Methods: Vol. 2 : Iss. 1 , Article 2, Page 9.\n * DOI: 10.22237/jmasm/1051747320\n * Available at: http://digitalcommons.wayne.edu/jmasm/vol2/iss1/2\n */\n\nusing cmwc4 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 4, 123, 987651670, true>;\nusing cmwc8 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 8, 123, 987651386, true>;\nusing cmwc16 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 16, 123, 987651178, true>;\nusing cmwc32 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 32, 123, 987655670, true>;\nusing cmwc64 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 64, 123, 987651206, true>;\nusing cmwc128 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 128, 123, 987688302, true>;\nusing cmwc256 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 256, 123, 987662290, true>;\nusing cmwc512 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 512, 123, 123462658, true>;\nusing cmwc1024 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 1024, 123, 5555698, true>;\nusing cmwc2048 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 2048, 123, 1030770, true>;\n\nusing cmwc4096 = complementary_multiply_with_carry_engine<std::uint32_t, 32, 4096, 809430660, 18782, true>;\n\n#endif /* !BOOST_NO_INT64_T && !BOOST_NO_INTEGRAL_INT64_T */\n\n} // namespace random\n} // namespace boost\n", "meta": {"hexsha": "c8a36eaf46f9838541013089dad94841e3a78433", "size": 8055, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "xoroshiro/complementary_multiply_with_carry.hpp", "max_stars_repo_name": "degski/xoroshiro", "max_stars_repo_head_hexsha": "1fd60de9597bf314d57d5fe7c9d7a7802b8b7583", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-31T02:35:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-31T02:35:26.000Z", "max_issues_repo_path": "xoroshiro/complementary_multiply_with_carry.hpp", "max_issues_repo_name": "degski/xoroshiro", "max_issues_repo_head_hexsha": "1fd60de9597bf314d57d5fe7c9d7a7802b8b7583", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xoroshiro/complementary_multiply_with_carry.hpp", "max_forks_repo_name": "degski/xoroshiro", "max_forks_repo_head_hexsha": "1fd60de9597bf314d57d5fe7c9d7a7802b8b7583", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1847826087, "max_line_length": 138, "alphanum_fraction": 0.7198013656, "num_tokens": 2385, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.37022540649291935, "lm_q1q2_score": 0.20670683299206868}}
{"text": "//! 2D形状の定義\n#pragma once\n#include \"geom.hpp\"\n#include \"spinner/resmgr.hpp\"\n#include \"spinner/assoc.hpp\"\n#include <boost/pool/object_pool.hpp>\n#include <memory>\n#include \"spinner/structure/treenode.hpp\"\n#include \"spinner/rflag.hpp\"\n#include \"boundary.hpp\"\n\nnamespace boom {\n\tnamespace geo2d {\n\t\tusing Int_OP = spn::Optional<int>;\n\t\tstruct Convex;\n\t\tstruct Poly;\n\t\tstruct Capsule;\n\t\tstruct Circle;\n\t\tstruct AABB;\n\t\tstruct Segment;\n\t\tstruct Ray;\n\t\tstruct Line;\n\t\tstruct Point;\n\t\tusing CTGeo = spn::CType<Convex, Poly, Capsule, Circle, AABB, Segment, Ray, Line, Point>;\n\t\ttemplate <class T>\n\t\tusing ITagP = ITagP_base<T, CTGeo>;\n\n\t\tusing PointL = std::vector<Vec2>;\n\t\tusing SegL = std::vector<Segment>;\n\t\tusing Convex2 = std::pair<Convex, Convex>;\n\t\tstruct Line;\n\t\tstruct Ray;\n\t\tstruct IModel;\n\t\tstruct Circle : ITagP<Circle> {\n\t\t\tVec2\tvCenter;\n\t\t\tfloat\tfRadius;\n\n\t\t\tCircle() = default;\n\t\t\tCircle(const Vec2& c, float r);\n\n\t\t\t// -----------------------------\n\t\t\tfloat bs_getArea() const;\n\t\t\tfloat bs_getInertia() const;\n\t\t\tconst Vec2& bs_getCenter() const;\n\t\t\tconst Circle& bs_getBCircle() const;\n\t\t\tAABB bs_getBBox() const;\n\t\t\t// -----------------------------\n\t\t\tVec2 support(const Vec2& dir) const;\n\n\t\t\tspn::none_t hit(...) const;\n\t\t\tbool hit(const Vec2& p, float t=NEAR_THRESHOLD) const;\n\t\t\tbool hit(const Segment& s, float t=NEAR_THRESHOLD) const;\n\t\t\tbool hit(const Circle& c, float t=NEAR_THRESHOLD) const;\n\n\t\t\tvoid getArcPoints(PointL& dst, float ang0, float ang1, float deep) const;\n\t\t\tCircle operator * (const AMat32& m) const;\n\t\t\tCircle operator * (float s) const;\n\t\t\tCircle& operator += (const Vec2& ofs);\n\t\t\tvoid distend(float width, float mindist);\n\n\t\t\t// ---- for MakeBoundary ----\n\t\t\tvoid setBoundary(const IModel* p);\n\t\t\tvoid appendBoundary(const IModel* p);\n\n\t\t\tfriend std::ostream& operator << (std::ostream& os, const Circle& c);\n\t\t};\n\t\t//! AxisAlignedBox\n\t\tstruct AABB : ITagP<AABB> {\n\t\t\tVec2\tminV, maxV;\n\n\t\t\tint _getAreaNumX(float p) const;\n\t\t\tint _getAreaNumY(float p) const;\n\t\t\tvoid _makeSegmentX(Segment& s, int num) const;\n\t\t\tvoid _makeSegmentY(Segment& s, int num) const;\n\t\t\tbool _checkHitX(const Segment& s0, int from, int to) const;\n\t\t\tbool _checkHitY(const Segment& s0, int from, int to) const;\n\t\t\tstd::pair<int,int> _getAreaNum(const Vec2& p) const;\n\n\t\t\tAABB() = default;\n\t\t\tAABB(const Vec2& min_v, const Vec2& max_v);\n\t\t\t// -----------------------------\n\t\t\tfloat bs_getArea() const;\n\t\t\tfloat bs_getInertia() const;\n\t\t\tVec2 bs_getCenter() const;\n\t\t\tCircle bs_getBCircle() const;\n\t\t\tconst AABB& bs_getBBox() const;\n\t\t\t// -----------------------------\n\t\t\tVec2 support(const Vec2& dir) const;\n\t\t\tVec2 nearest(const Vec2& pos) const;\n\n\t\t\tspn::none_t hit(...) const;\n\t\t\tbool hit(const Vec2& p, float t=NEAR_THRESHOLD) const;\n\t\t\tbool hit(const Segment& l, float t=NEAR_THRESHOLD) const;\n\t\t\tbool hit(const AABB& ab, float t=NEAR_THRESHOLD) const;\n\t\t\tAABB operator * (const AMat32& m) const;\n\t\t\tAABB& operator += (const Vec2& ofs);\n\t\t\tvoid distend(float width, float mindist);\n\n\t\t\t// ---- for MakeBoundary ----\n\t\t\tvoid setBoundary(const IModel* p);\n\t\t\tvoid appendBoundary(const IModel* p);\n\n\t\t\tfriend std::ostream& operator << (std::ostream& os, const AABB& a);\n\t\t};\n\t\t//! IModelインタフェースの子ノードイテレータ\n\t\tstruct MdlItr {\n\t\t\tTfBase_SP\t_sp;\n\n\t\t\tMdlItr() = default;\n\t\t\tMdlItr(const TfBase_SP& sp);\n\n\t\t\tMdlItr& operator ++ ();\n\t\t\tbool operator == (const MdlItr& m) const;\n\t\t\tbool operator != (const MdlItr& m) const;\n\t\t\texplicit operator bool () const;\n\t\t\tconst TfBase* get() const;\n\t\t};\n\t\tstruct IModel : ::boom::IModelNode {\n\t\t\t// -----------------------------\n\t\t\tvirtual Vec2 im_getCenter() const = 0;\n\t\t\tvirtual float im_getArea() const = 0;\n\t\t\tvirtual float im_getInertia() const = 0;\n\t\t\tvirtual void im_getBVolume(Circle& c) const = 0;\n\t\t\tvirtual void im_getBVolume(AABB& a) const = 0;\n\t\t\t// -----------------------------\n\t\t\tvirtual void im_transform[[noreturn]](void* dst, const AMat32& m) const = 0;\n\t\t\t//! サポート射像\n\t\t\t/*! 均等でないスケーリングは対応しない、移動は後でオフセット、回転はdirを逆にすれば代用可\n\t\t\t\t・・との理由で行列変換後の物体に対する射像は無し */\n\t\t\tvirtual Vec2 im_support(const Vec2& dir) const = 0;\n\t\t\t//! 図形と点の判定\n\t\t\tvirtual bool im_hitPoint(const Vec2& p, float t=NEAR_THRESHOLD) const = 0;\n\t\t\tvirtual uint32_t getCID() const = 0;\n\t\t\tvirtual MdlItr getInner() const;\n\t\t\tvirtual Model_SP im_clone() const = 0;\n\n\t\t\tvirtual Vec2 toLocal(const Vec2& v) const { return v; }\n\t\t\tvirtual Vec2 toLocalDir(const Vec2& v) const { return v; }\n\t\t\tvirtual Vec2 toWorld(const Vec2& v) const { return v; }\n\t\t\tvirtual Vec2 toWorldDir(const Vec2& v) const { return v; }\n\t\t\tvirtual spn::Optional<const AMat32&> getToLocal() const { return spn::none; }\n\t\t\tvirtual spn::Optional<const AMat32&> getToWorld() const { return spn::none; }\n\t\t\tconst static AMat32 cs_idMat;\n\t\t\tconst AMat32& getToLocalI() const;\n\t\t\tconst AMat32& getToWorldI() const;\n\t\t};\n\n\t\t//! TにIModelインタフェースを付加\n\t\ttemplate <class T>\n\t\tstruct Model : IModelP_base<T, IModel> {\n\t\t\tusing base_t = IModelP_base<T, IModel>;\n\t\t\tusing base_t::base_t;\n\n\t\t\tModel() = default;\n\t\t\tModel(const T& t): base_t(t) {}\n\t\t\tModel(T&& t): base_t(std::move(t)) {}\n\t\t\t// 各種ルーチンの中継\n\t\t\tModel_SP im_clone() const override {\n\t\t\t\treturn std::make_shared<Model<T>>(static_cast<const T&>(*this));\n\t\t\t}\n\t\t\tvoid im_transform(void* dst, const AMat32& m) const override { *reinterpret_cast<T*>(dst) = *this * m; }\n\t\t\tvoid im_getBVolume(Circle& c) const override { c = T::bs_getBCircle(); }\n\t\t\tvoid im_getBVolume(AABB& a) const override { a = T::bs_getBBox(); }\n\t\t\tfloat im_getInertia() const override { return T::bs_getInertia(); }\n\t\t\tfloat im_getArea() const override { return T::bs_getArea(); }\n\t\t\tVec2 im_getCenter() const override { return T::bs_getCenter(); }\n\t\t\tVec2 im_support(const Vec2& dir) const override { return T::support(dir); }\n\t\t\tbool im_hitPoint(const Vec2& pos, float t=NEAR_THRESHOLD) const override { return T::hit(pos, t); }\n\t\t\tstd::ostream& print(std::ostream& os) const override { return os << static_cast<const T&>(*this); }\n\t\t};\n\t\ttemplate <class T>\n\t\tstd::ostream& operator << (std::ostream& os, const Model<T>& m) {\n\t\t\treturn m.print(os);\n\t\t}\n\t\tusing CircleM = Model<Circle>;\n\n\t\tclass TfBase : public spn::TreeNode<TfBase>,\n\t\t\t\t\t\tvirtual public IModel\n\t\t{\n\t\t\tprivate:\n\t\t\t\tfriend class spn::TreeNode<TfBase>;\n\t\t\t\tusing base_t = spn::TreeNode<TfBase>;\n\t\t\tprotected:\n\t\t\t\tvoid* _getUserData(void*, std::true_type);\n\t\t\t\tvoid* _getUserData(void* udata, std::false_type);\n\t\t\t\tvirtual void onChildAdded(const SP& node);\n\t\t\t\tvirtual void onChildRemove(const SP& node);\n\t\t\t\tvirtual void onParentChange(const SP& from, const SP& to);\n\t\t\t\tvirtual void _setAsChanged();\n\t\t\tpublic:\n\t\t\t\t//! 子ノードの取得\n\t\t\t\tMdlItr getInner() const override;\n\t\t\t\tbool hasInner() const override;\n\t\t\t\t//! 下層オブジェクトの形状を変更した時に手動で呼ぶ\n\t\t\t\tvirtual void setAsChanged();\n\t\t\t\tvirtual bool isLeaf() const { return false; }\n\t\t\t\tvirtual spn::Pose2D& tf_refPose[[noreturn]]();\n\t\t\t\tvirtual const spn::Pose2D& tf_getPose() const;\n\t\t\t\tModel_SP im_clone() const override;\n\t\t\t\tvirtual TfBase_SP clone() const = 0;\n\t\t};\n\t\ttemplate <class Boundary, class Ud>\n\t\tclass TfNode_base : public TfBase,\n\t\t\t\t\t\t\tpublic Model<Boundary>\n\t\t{\n\t\t\tprotected:\n\t\t\t\tusing model_t = Model<Boundary>;\n\t\t\t\tUd\t\t\t\t\t_udata;\n\t\t\tpublic:\n\t\t\t\tusing model_t::model_t;\n\t\t\t\tModel_SP im_clone() const override {\n\t\t\t\t\treturn TfBase::im_clone();\n\t\t\t\t}\n\t\t\t\t/*! ユーザーデータがvoidの時は親ノードのデータを返す */\n\t\t\t\tvoid* getUserData() override {\n\t\t\t\t\treturn _getUserData(&_udata, std::is_same<spn::none_t, Ud>());\n\t\t\t\t}\n\t\t};\n\t\ttemplate <class Boundary, class Ud=spn::none_t>\n\t\tclass TfNode_Static : public TfNode_base<Boundary, Ud> {\n\t\t\tprivate:\n\t\t\t\tusing base_t = TfNode_base<Boundary, Ud>;\n\t\t\t\tusing SP = typename base_t::SP;\n\t\t\t\tusing Time_t = typename base_t::Time_t;\n\t\t\t\tmutable bool\t_bChanged = true,\n\t\t\t\t\t\t\t\t_bValid;\n\t\t\tprotected:\n\t\t\t\tvoid onChildAdded(const TfBase::SP& node) override {\n\t\t\t\t\t_bChanged = true;\n\t\t\t\t\tbase_t::onChildAdded(node);\n\t\t\t\t}\n\t\t\t\tvoid onChildRemove(const TfBase::SP& node) override {\n\t\t\t\t\t_bChanged = true;\n\t\t\t\t\tbase_t::onChildRemove(node);\n\t\t\t\t}\n\t\t\t\tvoid _setAsChanged() override {\n\t\t\t\t\t_bChanged = true;\n\t\t\t\t}\n\t\t\tpublic:\n\t\t\t\tSP clone() const override {\n\t\t\t\t\treturn std::make_shared<TfNode_Static>(*this);\n\t\t\t\t}\n\t\t\t\tbool imn_refresh(Time_t t) const override {\n\t\t\t\t\t// 更新条件はフラグ\n\t\t\t\t\tif(_bChanged) {\n\t\t\t\t\t\t_bChanged = false;\n\t\t\t\t\t\tstd::vector<const IModel*> pm;\n\t\t\t\t\t\t// 直下の子ノードをリストアップ\n\t\t\t\t\t\tthis->template iterateDepthFirst<false>([&pm](auto& node, int depth){\n\t\t\t\t\t\t\tif(depth == 0)\n\t\t\t\t\t\t\t\treturn spn::Iterate::StepIn;\n\t\t\t\t\t\t\tpm.push_back(&node);\n\t\t\t\t\t\t\treturn spn::Iterate::Next;\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif((_bValid = !pm.empty())) {\n\t\t\t\t\t\t\t// 境界ボリュームの更新\n\t\t\t\t\t\t\tauto* core = const_cast<Boundary*>(reinterpret_cast<const Boundary*>(base_t::getCore()));\n\t\t\t\t\t\t\tauto op = MakeBoundary<Boundary>(&pm[0], pm.size(), t);\n\t\t\t\t\t\t\tif((_bValid = op))\n\t\t\t\t\t\t\t\t*core = *op;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// 子ノードが無い場合は常にヒットしない\n\t\t\t\t\t}\n\t\t\t\t\treturn _bValid;\n\t\t\t\t}\n\t\t};\n\t\ttemplate <class Boundary, class Ud=spn::none_t>\n\t\tclass TfNode_Dynamic : public TfNode_base<Boundary, Ud> {\n\t\t\tprivate:\n\t\t\t\tusing base_t = TfNode_base<Boundary, Ud>;\n\t\t\t\tusing Time_t = typename base_t::Time_t;\n\t\t\t\tusing SP = typename base_t::SP;\n\t\t\t\tusing Time_OP = spn::Optional<Time_t>;\n\t\t\t\tmutable Time_OP\t\t_opTime = 0;\n\t\t\t\tmutable bool\t\t_bValid;\n\t\t\tprotected:\n\t\t\t\tvoid onChildAdded(const SP& node) override {\n\t\t\t\t\t_opTime = spn::none;\n\t\t\t\t\tbase_t::onChildAdded(node);\n\t\t\t\t}\n\t\t\t\tvoid onChildRemove(const SP& node) override {\n\t\t\t\t\t_opTime = spn::none;\n\t\t\t\t\tbase_t::onChildRemove(node);\n\t\t\t\t}\n\t\t\tpublic:\n\t\t\t\tSP clone() const override {\n\t\t\t\t\treturn std::make_shared<TfNode_Dynamic>(*this);\n\t\t\t\t}\n\t\t\t\tbool imn_refresh(Time_t t) const override {\n\t\t\t\t\t// 更新時刻が古い時のみ処理を行う\n\t\t\t\t\tif(!_opTime || *_opTime < t) {\n\t\t\t\t\t\t_opTime = t;\n\n\t\t\t\t\t\tstd::vector<const IModel*> pm;\n\t\t\t\t\t\t// 子ノードをリストアップ\n\t\t\t\t\t\tthis->template iterateDepthFirst<false>([&pm](auto& node, int depth){\n\t\t\t\t\t\t\tif(depth == 0)\n\t\t\t\t\t\t\t\treturn spn::Iterate::StepIn;\n\t\t\t\t\t\t\tpm.push_back(&node);\n\t\t\t\t\t\t\treturn spn::Iterate::Next;\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif((_bValid = !pm.empty())) {\n\t\t\t\t\t\t\t// 境界ボリュームの更新\n\t\t\t\t\t\t\tauto* core = const_cast<Boundary*>(reinterpret_cast<const Boundary*>(base_t::getCore()));\n\t\t\t\t\t\t\tauto op = MakeBoundary<Boundary>(&pm[0], pm.size(), t);\n\t\t\t\t\t\t\tif((_bValid = op))\n\t\t\t\t\t\t\t\t*core = *op;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// 子ノードが無い場合は常にヒットしない\n\t\t\t\t\t}\n\t\t\t\t\treturn _bValid;\n\t\t\t\t}\n\t\t};\n\n\t\t#define mgr_tf2d (::boom::geo2d::TfMgr::_ref())\n\t\tclass TfMgr : public spn::ResMgrA<TfBase_SP, TfMgr> {};\n\n\t\tusing LNear = std::pair<Vec2, LinePos>;\n\t\tstruct Point : Vec2, ITagP<Point> {\n\t\t\t// -----------------------------\n\t\t\tconst float& bs_getArea() const;\n\t\t\tconst float& bs_getInertia() const;\n\t\t\tconst Vec2& bs_getCenter() const;\n\t\t\tCircle bs_getBCircle() const;\n\t\t\tAABB bs_getBBox() const;\n\t\t\t// -----------------------------\n\t\t\tusing Vec2::Vec2;\n\t\t\tusing Vec2::distance;\n\t\t\tfloat distance(const Segment& s) const;\n\t\t\tLNear nearest(const Segment& s) const;\n\t\t\tconst Vec2& support(const Vec2& dir) const;\n\t\t\tPoint operator * (const AMat32& m) const;\n\n\t\t\tspn::none_t hit(...) const;\n\t\t\tbool hit(const Vec2& p, float t=NEAR_THRESHOLD) const;\n\t\t\tfriend std::ostream& operator << (std::ostream& os, const Point& p);\n\t\t};\n\t\tusing PointM = Model<Point>;\n\n\t\t//! 直線\n\t\tstruct Line : ITagP<Line> {\n\t\t\tVec2\tpos, dir;\n\n\t\t\tLine() = default;\n\t\t\tLine(const Vec2& p, const Vec2& d);\n\n\t\t\t// -----------------------------\n\t\t\tfloat bs_getArea() const;\n\t\t\tfloat bs_getInertia() const;\n\t\t\tconst Vec2& bs_getCenter() const;\n\t\t\tconst Circle& bs_getBCircle() const;\n\t\t\tconst AABB& bs_getBBox() const;\n\t\t\t// -----------------------------\n\n\t\t\tVec2x2 nearest(const Line& st) const;\n\t\t\tVec2 nearest(const Vec2& p) const;\n\t\t\tfloat distance(const Vec2& p) const;\n\t\t\t//! 点を線分上に置く\n\t\t\tVec2 placeOnLine(const Vec2& p) const;\n\t\t\t//! 基準位置に対する方向ベクトルとの内積\n\t\t\tfloat posDot(const Vec2& p) const;\n\t\t\tLine operator * (const AMat32& m) const;\n\t\t\tLineDivision checkSide(const Vec2& p, float t=DOT_THRESHOLD) const;\n\n\t\t\tVec2 support(const Vec2& dir) const;\n\t\t\tspn::none_t hit(...) const;\n\t\t\tbool hit(const Vec2& p, float t=NEAR_THRESHOLD) const;\n\t\t\tfriend std::ostream& operator << (std::ostream& os, const Line& l);\n\t\t};\n\t\tusing LineM = Model<Line>;\n\t\t//! 半直線\n\t\tstruct Ray : ITagP<Ray> {\n\t\t\tVec2\tpos, dir;\n\n\t\t\tRay() = default;\n\t\t\tRay(const Vec2& p, const Vec2& d);\n\n\t\t\t// -----------------------------\n\t\t\tfloat bs_getArea() const;\n\t\t\tfloat bs_getInertia() const;\n\t\t\tconst Vec2& bs_getCenter() const;\n\t\t\tconst Circle& bs_getBCircle() const;\n\t\t\tconst AABB& bs_getBBox() const;\n\t\t\t// -----------------------------\n\n\t\t\tconst Line& asLine() const;\n\t\t\tVec2x2 nearest(const Ray& r) const;\n\t\t\tVec2 nearest(const Vec2& p) const;\n\t\t\tRay operator * (const AMat32& m) const;\n\n\t\t\tVec2 support(const Vec2& dir) const;\n\t\t\tspn::none_t hit(...) const;\n\t\t\tbool hit(const Vec2& p, float t=NEAR_THRESHOLD) const;\n\t\t\tfriend std::ostream& operator << (std::ostream& os, const Ray& r);\n\t\t};\n\t\tusing RayM = Model<Ray>;\n\t\t//! 線分\n\t\tstruct Segment : ITagP<Segment> {\n\t\t\tVec2\tfrom, to;\n\n\t\t\tSegment() = default;\n\t\t\tSegment(const Vec2& v0, const Vec2& v1);\n\t\t\t// -----------------------------\n\t\t\tconst float& bs_getArea() const {INVOKE_ERROR}\n\t\t\tconst float& bs_getInertia() const {INVOKE_ERROR}\n\t\t\tVec2 bs_getCenter() const;\n\t\t\tCircle bs_getBCircle() const;\n\t\t\tAABB bs_getBBox() const;\n\t\t\t// -----------------------------\n\t\t\tVec2 support(const Vec2& dir) const;\n\n\t\t\tfloat distance(const Segment& l) const;\n\t\t\tfloat length() const;\n\t\t\tfloat len_sq() const;\n\t\t\tspn::none_t hit(...) const;\n\t\t\tbool hit(const Vec2& p, float t=NEAR_THRESHOLD) const;\n\t\t\tbool hit(const Segment& s, float t=NEAR_THRESHOLD) const;\n\n\t\t\t/*! \\return Vec2(最寄り座標),LINEPOS(最寄り線分位置) */\n\t\t\tLNear nearest(const Vec2& p) const;\n\t\t\t//! 線分が交差する位置を調べる\n\t\t\t/*! \\return first: 交差座標\n\t\t\t\t\t\tsecond: 交差しているライン位置 (ONLINE or NOHIT) */\n\t\t\tVec2_OP crossPoint(const Segment& l) const;\n\t\t\tVec2_OP crossPoint(const Line& l) const;\n\t\t\tfloat ratio(const Vec2& p) const;\n\t\t\tVec2 getDir() const;\n\t\t\tLine asLine() const;\n\t\t\tbool online(const Vec2& p) const;\n\n\t\t\tSegment operator * (const AMat32& m) const;\n\t\t\tfriend std::ostream& operator << (std::ostream& os, const Segment& s);\n\t\t};\n\t\tusing SegmentM = Model<Segment>;\n\t\tusing AABBM = Model<AABB>;\n\n\t\tstruct Capsule : ITagP<Capsule> {\n\t\t\tVec2\tfrom, to;\n\t\t\tfloat\tradius;\n\n\t\t\tCapsule() = default;\n\t\t\tCapsule(const Vec2& f, const Vec2& t, float r);\n\t\t\t// -----------------------------\n\t\t\tfloat bs_getArea() const;\n\t\t\tfloat bs_getInertia() const;\n\t\t\tVec2 bs_getCenter() const;\n\t\t\tCircle bs_getBCircle() const;\n\t\t\tAABB bs_getBBox() const;\n\t\t\t// -----------------------------\n\t\t\tVec2 support(const Vec2& dir) const;\n\n\t\t\tCapsule operator * (const AMat32& m) const;\n\t\t\tCapsule& operator += (const Vec2& ofs);\n\n\t\t\tspn::none_t hit(...) const;\n\t\t\tbool hit(const Vec2& p , float t=NEAR_THRESHOLD) const;\n\t\t\tbool hit(const Segment& s, float t=NEAR_THRESHOLD) const;\n\t\t\tbool hit(const Capsule& c, float t=NEAR_THRESHOLD) const;\n\n\t\t\tfriend std::ostream& operator << (std::ostream& os, const Capsule& c);\n\t\t};\n\t\tusing CapsuleM = Model<Capsule>;\n\n\t\tstruct Poly : ITagP<Poly> {\n\t\t\tVec2\t\tpoint[3];\n\t\t\tbool _isInTriangle(const Vec2& p, float threshold) const;\n\n\t\t\tPoly() = default;\n\t\t\tPoly(const Vec2& p0, const Vec2& p1, const Vec2& p2);\n\t\t\t// -----------------------------\n\t\t\tfloat bs_getArea() const;\n\t\t\tfloat bs_getInertia() const;\n\t\t\tVec2 bs_getCenter() const;\n\t\t\tCircle bs_getBCircle() const;\n\t\t\tAABB bs_getBBox() const;\n\t\t\t// -----------------------------\n\t\t\t//! 座標が三角形の内部に含まれるかを判定\n\t\t\t/*! ポリゴンは時計回りを想定\n\t\t\t\t辺上は含まない */\n\t\t\tbool isInTriangle(const Vec2& p) const;\n\t\t\tstd::pair<Vec2,int> nearest(const Vec2& p) const;\n\n\t\t\tVec2 support(const Vec2& dir) const;\n\t\t\tvoid addOffset(const Vec2& ofs);\n\t\t\tstatic float CalcArea(const Vec2& p0, const Vec2& p1, const Vec2& p2);\n\t\t\tstatic float CalcArea(const Vec2& p0, const Vec2& p1);\n\t\t\t//! 鈍角を探す\n\t\t\t/*! \\return 鈍角の番号 (負数は該当なし) */\n\t\t\tint getObtuseCorner() const;\n\t\t\t//! 頂点の並びが時計回りかを判定\n\t\t\tbool isCW() const;\n\t\t\t//! 頂点の並びを反転\n\t\t\tvoid invert();\n\t\t\tLineDivision checkSide(const Line& l, float t=DOT_THRESHOLD) const;\n\n\t\t\tspn::none_t hit(...) const;\n\t\t\t//! 座標が三角形と衝突するか判定\n\t\t\t/*! isInTriangleとは異なり辺上もHitとみなす */\n\t\t\tbool hit(const Vec2& p, float t=NEAR_THRESHOLD) const;\n\t\t\tbool hit(const Poly& p, float t=NEAR_THRESHOLD) const;\n\t\t\tPoly operator * (const AMat32& m) const;\n\t\t\tPoly& operator += (const Vec2& ofs);\n\t\t\tvoid distend(float width, float mindist);\n\t\t\tfriend std::ostream& operator << (std::ostream& os, const Poly& p);\n\t\t};\n\t\tusing PolyM = Model<Poly>;\n\t\t//! 多角形基本クラス\n\t\tstruct Convex : ITagP<Convex> {\n\t\t\tusing AreaL = std::vector<float>;\n\t\t\tstruct AreaSum {\n\t\t\t\tfloat result;\n\n\t\t\t\tAreaSum(): result(0) {}\n\t\t\t\tvoid operator()(int /*n*/, const Vec2& p0, const Vec2& p1) {\n\t\t\t\t\tresult += Poly::CalcArea(p0,p1);\n\t\t\t\t}\n\t\t\t};\n\t\t\tstruct AreaList {\n\t\t\t\tAreaL\tareaL;\n\t\t\t\tfloat\tsum;\n\n\t\t\t\tAreaList(int n): areaL(n), sum(0) {}\n\t\t\t\tvoid operator()(int n, const Vec2& p0, const Vec2& p1) {\n\t\t\t\t\tfloat a = Poly::CalcArea(p0,p1);\n\t\t\t\t\tareaL[n] = a;\n\t\t\t\t\tsum += a;\n\t\t\t\t}\n\t\t\t};\n\t\t\tPointL\tpoint;\n\t\t\tconst static uint8_t cs_index[1<<8];\n\n\t\t\tConvex() = default;\n\t\t\t/*! \\param[in] v 凸包と分かっている頂点 */\n\t\t\tConvex(std::initializer_list<Vec2> v);\n\t\t\tConvex(const PointL& pl);\n\t\t\tConvex(PointL&& pl);\n\n\t\t\tusing CBPoints = std::function<void (PointL&&)>;\n\t\t\tusing CBConvex = std::function<void (Convex&&)>;\n\t\t\tstatic void MonotoneToConvex(const PointL& pts, const Vec2& dir, const CBConvex& cb);\n\t\t\tstatic void ConcaveToMonotone(const PointL& pts, const Vec2& dir, const CBPoints& cb);\n\t\t\tstatic bool IsMonotone(const PointL& pts, const Vec2& dir);\n\t\t\tstatic bool IsConvex(const PointL& pts);\n\t\t\t//! 凹ポリゴンを内包するような凸形状を求める\n\t\t\tstatic Convex FromConcave(const PointL& src);\n\t\t\tbool addPoint(const Vec2& p);\n\t\t\t// -----------------------------\n\t\t\tfloat bs_getArea() const;\n\t\t\tCircle bs_getBCircle() const;\n\t\t\tVec2 bs_getCenter() const;\n\t\t\tfloat bs_getInertia() const;\n\t\t\tAABB bs_getBBox() const;\n\t\t\t// -----------------------------\n\t\t\t/*! 同時に求めると少し効率が良い為 */\n\t\t\tstd::tuple<float,float,Vec2> area_inertia_center() const;\n\t\t\tVec2 support(const Vec2& dir) const;\n\t\t\t//! 2つに分割\n\t\t\t/*! \\param[out] c0 線分の進行方向左側\n\t\t\t\t\\param[out] c1 線分の進行方向右側 */\n\t\t\tConvex2 splitTwo(const Line& l) const;\n\t\t\t//! 2つに分割して左側を自身に適用\n\t\t\tConvex split(const Line& l);\n\t\t\t//! 2つに分割して右側は捨てる\n\t\t\tvoid splitThis(const Line& l);\n\n\t\t\ttemplate <class CB>\n\t\t\tvoid iterate(CB cb) const {\n\t\t\t\t// 頂点数は3つ以上\n\t\t\t\tint nL = point.size();\n\t\t\t\tAssertP(Trap, nL > 2);\n\n\t\t\t\t// 先にブリッジの箇所を処理\n\t\t\t\tcb(nL-1, point.back(), point.front());\n\t\t\t\tfor(int i=0 ; i<nL-1 ; i++)\n\t\t\t\t\tcb(i, point[i], point[i+1]);\n\t\t\t}\n\t\t\tvoid addOffset(const Vec2& ofs);\n\n\t\t\t//! 指定ポイントの内部的な領域IDと内外位置を取得\n\t\t\t/*! \\return first=内外判定\n\t\t\t\t\t\tsecond=領域ID */\n\t\t\tstd::pair<ConvexPos, int> checkPosition(const Vec2& pos, float threshold=DOT_THRESHOLD) const;\n\t\t\t//! 内部的な通し番号における外郭ライン\n\t\t\tSegment getOuterSegment(int n) const;\n\t\t\tLine getOuterLine(int n) const;\n\t\t\tstd::pair<bool,PointL> getOverlappingPoints(const Convex& mdl, const Vec2& inner) const;\n\t\t\tstatic Convex GetOverlappingConvex(const Convex& m0, const Convex& m1, const Vec2& inner);\n\t\t\t//! 凸包が直線と交差している箇所を2点計算\n\t\t\tstd::tuple<bool,Vec2,Vec2> checkCrossingLine(const Line& l) const;\n\t\t\tConvex operator * (const AMat32& m) const;\n\t\t\tConvex& operator *= (const AMat32& m);\n\t\t\tConvex& operator += (const Vec2& ofs);\n\t\t\tvoid distend(float width, float mindist);\n\t\t\t//! 頂点が時計回りになっているか\n\t\t\tbool checkCW() const;\n\t\t\t//! 頂点の並びを時計回りに修正\n\t\t\tvoid adjustLoop();\n\t\t\tint getNPoints() const;\n\t\t\tVec2 getPoint(int n) const;\n\n\t\t\tspn::none_t hit(...) const;\n\t\t\tbool hit(const Vec2& p, float t=NEAR_THRESHOLD) const;\n\t\t\tfriend std::ostream& operator << (std::ostream& os, const Convex& c);\n\t\t};\n\t\tusing ConvexM = Model<Convex>;\n\t\t//! GJK法による衝突判定(2D)\n\t\t/*! ヒットチェックのみ。衝突時は内部点を出力可 */\n\t\tclass GSimplex {\n\t\t\tprotected:\n\t\t\t\tconst IModel\t&_m0, &_m1;\n\t\t\t\tPoly\t_poly;\t\t\t//!< 凸包を構成するポリゴン\n\t\t\t\tVec2\t_posA[3],\t\t//!< vtx(A-B)を求める時に使ったA側の座標\n\t\t\t\t\t\t_inner;\t\t\t//!< 内部点\n\t\t\t\tbool\t_bHit;\t\t\t//!< 衝突の有無\n\t\t\t\tint\t\t_nVtx;\t\t\t//!< 使用された頂点の数(min=1, max=3)\n\t\t\tprivate:\n\t\t\t\tvoid _minkowskiSub(const Vec2& dir, int n);\n\t\t\t\tvoid _gjkMethod();\n\t\t\t\tvoid _setAsHit(int nv, const Vec2& inner);\n\t\t\t\tvoid _setAsNotHit(int nv);\n\t\t\tpublic:\n\t\t\t\t//! 初期化 = GJKによる判定(ヒットチェックだけ)\n\t\t\t\tGSimplex(const IModel& m0, const IModel& m1);\n\t\t\t\tbool getResult() const;\n\t\t\t\t//! 衝突時: 内部点を取得\n\t\t\t\tconst Vec2& getInner() const;\n\t\t};\n\t\t//! GJKで最近傍対を求める\n\t\t/*! 常に頂点リストを時計回りに保つ */\n\t\tclass GEpa : public GSimplex {\n\t\t\t/*! ミンコフスキー差の凸形状を構成する最大頂点数(VList)\n\t\t\t\t必要ならvectorでやっても良いがとりあえず決め打ち */\n\t\t\tconstexpr static int MAX_VERT = 0x100;\n\t\t\tusing VPool = boost::object_pool<Vec2x2>;\n\t\t\tstatic thread_local VPool tls_vPool;\n\t\t\tusing VList = std::array<Vec2x2*, MAX_VERT>;\n\n\t\t\tVList\t_vl;\n\t\t\tsize_t\t_szVl;\n\t\t\t//! 新しく頂点メモリを確保\n\t\t\t/*! \\param n 格納先のインデックス (負数なら末尾) */\n\t\t\tVec2x2* _allocVert(int n=-1);\n\t\t\t//! 頂点ポインタからのインデックス検索\n\t\t\t/*! \\param vp 検索する頂点ポインタ */\n\t\t\tInt_OP _getIndex(const Vec2x2* vp) const;\n\n\t\t\t//! 点と辺の両対応\n\t\t\tstruct LmLen {\n\t\t\t\tfloat\t\t\tdist;\n\t\t\t\tVec2\t\t\tdir;\n\t\t\t\tconst Vec2x2\t*vtx[2];\t//!< index[1]==nullptrの時は単一の頂点を表す\n\n\t\t\t\tbool operator < (const LmLen& len) const {\n\t\t\t\t\treturn dist < len.dist;\n\t\t\t\t}\n\t\t\t};\n\t\t\t//! 最短距離リスト\n\t\t\tspn::AssocVec<LmLen>\t_asv;\n\t\t\t//! デバッグ用\n\t\t\tvoid _printASV(std::ostream& os) const;\n\n\t\t\tunion {\n\t\t\t\tVec2x2\t_pvec;\n\t\t\t\tVec2x2\t_nvec;\n\t\t\t};\n\t\t\t//! v0.firstとv1.firstからなる線分候補をリストに追加\n\t\t\t/*!\t\\return 最近傍点が原点と重なっていれば0x02, 線分候補が追加されれば0x01, それ以外は0x00 */\n\t\t\tint _addAsv(const Vec2x2& v0, const Vec2x2& v1);\n\n\t\t\t//! 指定方向へのミンコフスキー差\n\t\t\t/*! \\param[in] n 計算した頂点の挿入先インデックス */\n\t\t\tconst Vec2x2& _minkowskiSub(const Vec2& dir, int n=-1);\n\t\t\t//! Hit時の脱出ベクトル\n\t\t\t/*! 最低でも3頂点以上持っている前提 */\n\t\t\tvoid _epaMethodOnHit(float threshold);\n\t\t\t//! NoHit時の最短ベクトル\n\t\t\tvoid _epaMethodNoHit(float threshold);\n\n\t\t\t//! NoHit: 頂点が2つしか無い時の補正\n\t\t\tvoid _recover2NoHit();\n\t\t\t//! Hit: 頂点が2つしか無い時の補正\n\t\t\tvoid _recover2OnHit();\n\t\t\t//! 頂点の並び順を時計回りに修正\n\t\t\tvoid _adjustLoop3();\n\t\t\t//! 頂点リスト(3つ以上)から最短距離リストを生成\n\t\t\tvoid _geneASV();\n\t\t\tvoid _clear();\n\n\t\t\tpublic:\n\t\t\t\tGEpa(const IModel& m0, const IModel& m1, float threshold=NEAR_THRESHOLD);\n\t\t\t\t~GEpa();\n\t\t\t\t/*! 非衝突時に有効\n\t\t\t\t\t\\return A側の最近傍点, B側の最近傍点 */\n\t\t\t\tconst Vec2x2& getNearestPair() const;\n\t\t\t\t/*! 衝突時にそれを回避するための最短移動ベクトル(A側)\n\t\t\t\t\t\\return first=A側の最深点 second=A側の回避ベクトル */\n\t\t\t\tconst Vec2x2& getPVector() const;\n\t\t};\n\t\t//! ミンコフスキー差を求める\n\t\tVec2 MinkowskiSub(const IModel& m0, const IModel& m1, const Vec2& dir);\n\t\t//! DualTransform (point2D -> line2D)\n\t\tLine Dual(const Vec2& v);\n\t\t//! DualTransform (line2D -> point2D)\n\t\tVec2 Dual(const Line& ls);\n\t\tVec2 Dual2(const Vec2& v0, const Vec2& v1);\n\t\t//! DualTransform (point3D -> plane)\n\t\tPlane Dual(const Vec3& v);\n\t\t//! DualTransform (plane -> point3D)\n\t\tVec3 Dual(const Plane& plane);\n\n\t\ttemplate <class CLIP>\n\t\tinline Vec2 NearestPoint(const Line& ls, const Vec2& p, CLIP clip) {\n\t\t\tVec2 toP = p - ls.pos;\n\t\t\tfloat d = ls.dir.dot(toP);\n\t\t\treturn ls.pos + ls.dir * clip(d);\n\t\t}\n\t\tbool IsCW(const PointL& pts);\n\t\tbool IsCrossing(const Line& ls0, const Line& ls1, float len0, float len1, float t=NEAR_THRESHOLD);\n\t\ttemplate <class CLIP0, class CLIP1>\n\t\tinline Vec2x2_OP NearestPoint(const Line& ls0, const Line& ls1, CLIP0 clip0, CLIP1 clip1) {\n\t\t\tfloat st0d = ls0.dir.len_sq(),\n\t\t\t\t\tst1d = ls1.dir.len_sq(),\n\t\t\t\t\tst01d = ls0.dir.dot(ls1.dir);\n\t\t\tfloat d = st0d * st1d - spn::Square(st01d);\n\t\t\tif(std::fabs(d) < 1e-5f) {\n\t\t\t\t// 2つの直線は平行\n\t\t\t\treturn spn::none;\n\t\t\t}\n\t\t\tMat22 m0(st1d, st01d,\n\t\t\t\t\tst01d, st0d);\n\t\t\tVec2\tm1((ls1.pos - ls0.pos).dot(ls0.dir),\n\t\t\t\t\t\t(ls0.pos - ls1.pos).dot(ls1.dir));\n\t\t\tm1 = m0 * m1;\n\t\t\tm1 *= spn::Rcp22Bit(d);\n\t\t\treturn Vec2x2(ls0.pos + ls0.dir * clip0(m1.x),\n\t\t\t\t\t\t\tls1.pos + ls1.dir * clip1(m1.y));\n\t\t}\n\n\t\tstruct Types {\n\t\t\tusing CTGeo = ::boom::geo2d::CTGeo;\n\t\t\tusing IModel = ::boom::geo2d::IModel;\n\t\t\tusing GJK = ::boom::geo2d::GSimplex;\n\t\t\tusing Narrow = ::boom::Narrow<Types>;\n\t\t};\n\t}\n}\n", "meta": {"hexsha": "cdfe97bb019e91aa4012d3467b0a57c20bd15ee5", "size": 23656, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "geom2D.hpp", "max_stars_repo_name": "degarashi/boomstick", "max_stars_repo_head_hexsha": "55dc5bfcfad6119d8401f578f91df7bbd44c192b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-06-14T15:54:27.000Z", "max_stars_repo_stars_event_max_datetime": "2015-06-14T15:54:27.000Z", "max_issues_repo_path": "geom2D.hpp", "max_issues_repo_name": "degarashi/boomstick", "max_issues_repo_head_hexsha": "55dc5bfcfad6119d8401f578f91df7bbd44c192b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geom2D.hpp", "max_forks_repo_name": "degarashi/boomstick", "max_forks_repo_head_hexsha": "55dc5bfcfad6119d8401f578f91df7bbd44c192b", "max_forks_repo_licenses": ["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.6680053548, "max_line_length": 107, "alphanum_fraction": 0.6345958742, "num_tokens": 8380, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.20663032694889616}}
{"text": "/*!\n  \\file gpp_python_model_selection.cpp\n  \\rst\n  This file has the logic to invoke C++ functions pertaining to model selection from Python.\n  The data flow follows the basic 4 step from gpp_python_common.hpp.\n\n  Note: several internal functions of this source file are only called from Export*() functions,\n  so their description, inputs, outputs, etc. comments have been moved. These comments exist in\n  Export*() as Python docstrings, so we saw no need to repeat ourselves.\n\\endrst*/\n// This include violates the Google Style Guide by placing an \"other\" system header ahead of C and C++ system headers.  However,\n// it needs to be at the top, otherwise compilation fails on some systems with some versions of python: OS X, python 2.7.3.\n// Putting this include first prevents pyport from doing something illegal in C++; reference: http://bugs.python.org/issue10910\n#include \"Python.h\"  // NOLINT(build/include)\n\n#include \"gpp_python_model_selection.hpp\"\n\n// NOLINT-ing the C, C++ header includes as well; otherwise cpplint gets confused\n#include <algorithm>  // NOLINT(build/include_order)\n#include <limits>  // NOLINT(build/include_order)\n#include <string>  // NOLINT(build/include_order)\n#include <vector>  // NOLINT(build/include_order)\n\n#include <boost/python/def.hpp>  // NOLINT(build/include_order)\n#include <boost/python/dict.hpp>  // NOLINT(build/include_order)\n#include <boost/python/extract.hpp>  // NOLINT(build/include_order)\n#include <boost/python/list.hpp>  // NOLINT(build/include_order)\n#include <boost/python/object.hpp>  // NOLINT(build/include_order)\n\n#include \"gpp_common.hpp\"\n#include \"gpp_covariance.hpp\"\n#include \"gpp_domain.hpp\"\n#include \"gpp_exception.hpp\"\n#include \"gpp_geometry.hpp\"\n#include \"gpp_model_selection.hpp\"\n#include \"gpp_optimizer_parameters.hpp\"\n#include \"gpp_python_common.hpp\"\n\nnamespace optimal_learning {\n\nnamespace {\n\ndouble ComputeLogLikelihoodWrapper(const boost::python::list& points_sampled,\n                                   const boost::python::list& points_sampled_value,\n                                   int dim, int num_sampled,\n                                   LogLikelihoodTypes objective_type,\n                                   const boost::python::list& hyperparameters,\n                                   const boost::python::list& derivatives,\n                                   int num_derivatives,\n                                   const boost::python::list& noise_variance) {\n  const int num_to_sample = 0;\n  const boost::python::list points_to_sample_dummy;\n\n  PythonInterfaceInputContainer input_container(hyperparameters, points_sampled, points_sampled_value, noise_variance,\n                                                points_to_sample_dummy, derivatives, num_derivatives, dim, num_sampled, num_to_sample);\n\n  SquareExponential sqexp(input_container.dim, input_container.alpha, input_container.lengths.data());\n\n  switch (objective_type) {\n    case LogLikelihoodTypes::kLogMarginalLikelihood: {\n      LogMarginalLikelihoodEvaluator log_marginal_eval(input_container.points_sampled.data(),\n                                                       input_container.points_sampled_value.data(),\n                                                       input_container.derivatives.data(), input_container.num_derivatives,\n                                                       input_container.dim, input_container.num_sampled);\n      LogMarginalLikelihoodState log_marginal_state(log_marginal_eval, sqexp, input_container.noise_variance);\n\n      double log_likelihood = log_marginal_eval.ComputeLogLikelihood(log_marginal_state);\n      return log_likelihood;\n    }  // end case LogLikelihoodTypes::kLogMarginalLikelihood\n/*    case LogLikelihoodTypes::kLeaveOneOutLogLikelihood: {\n      LeaveOneOutLogLikelihoodEvaluator leave_one_out_eval(input_container.points_sampled.data(),\n                                                           input_container.points_sampled_value.data(),\n                                                           input_container.noise_variance.data(),\n                                                           input_container.dim,\n                                                           input_container.num_sampled);\n      LeaveOneOutLogLikelihoodState leave_one_out_state(leave_one_out_eval, matern_25);\n\n      double loo_likelihood = leave_one_out_eval.ComputeLogLikelihood(leave_one_out_state);\n      return loo_likelihood;\n    }*/\n    default: {\n      double log_likelihood = -std::numeric_limits<double>::max();\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid objective mode choice. Setting log likelihood to -DBL_MAX.\");\n      return log_likelihood;\n    }\n  }  // end switch over objective_type\n}\n\nboost::python::list ComputeHyperparameterGradLogLikelihoodWrapper(const boost::python::list& points_sampled,\n                                                                  const boost::python::list& points_sampled_value,\n                                                                  int dim, int num_sampled,\n                                                                  LogLikelihoodTypes objective_type,\n                                                                  const boost::python::list& hyperparameters,\n                                                                  const boost::python::list& derivatives,\n                                                                  int num_derivatives,\n                                                                  const boost::python::list& noise_variance) {\n  const int num_to_sample = 0;\n  const boost::python::list points_to_sample_dummy;\n\n  PythonInterfaceInputContainer input_container(hyperparameters, points_sampled, points_sampled_value, noise_variance,\n                                                points_to_sample_dummy, derivatives, num_derivatives, dim, num_sampled, num_to_sample);\n\n  SquareExponential sqexp(input_container.dim, input_container.alpha, input_container.lengths.data());\n\n  std::vector<double> grad_log_likelihood(sqexp.GetNumberOfHyperparameters() + 1 + num_derivatives);\n  switch (objective_type) {\n    case LogLikelihoodTypes::kLogMarginalLikelihood: {\n      LogMarginalLikelihoodEvaluator log_marginal_eval(input_container.points_sampled.data(),\n                                                       input_container.points_sampled_value.data(),\n                                                       input_container.derivatives.data(), input_container.num_derivatives,\n                                                       input_container.dim, input_container.num_sampled);\n      LogMarginalLikelihoodState log_marginal_state(log_marginal_eval, sqexp, input_container.noise_variance);\n\n      log_marginal_eval.ComputeGradLogLikelihood(&log_marginal_state, grad_log_likelihood.data());\n      break;\n    }  // end case LogLikelihoodTypes::kLogMarginalLikelihood\n/*    case LogLikelihoodTypes::kLeaveOneOutLogLikelihood: {\n      LeaveOneOutLogLikelihoodEvaluator leave_one_out_eval(input_container.points_sampled.data(),\n                                                           input_container.points_sampled_value.data(),\n                                                           input_container.noise_variance.data(),\n                                                           input_container.dim,\n                                                           input_container.num_sampled);\n      LeaveOneOutLogLikelihoodState leave_one_out_state(leave_one_out_eval, matern_25);\n\n      leave_one_out_eval.ComputeGradLogLikelihood(&leave_one_out_state, grad_log_likelihood.data());\n      break;\n    }*/\n    default: {\n      std::fill(grad_log_likelihood.begin(), grad_log_likelihood.end(), std::numeric_limits<double>::max());\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid objective mode choice. Setting all gradients to DBL_MAX.\");\n      break;\n    }\n  }  // end switch over objective_type\n  return VectorToPylist(grad_log_likelihood);\n}\n\n/*!\\rst\n  Utility that dispatches log likelihood optimization (wrt hyperparameters) based on optimizer type.\n  This is just used to reduce copy-pasted code.\n\n  Let n_hyper = covariance.GetNumberOfHyperparameters();\n\n  \\param\n    :optimizer_parameters: python/cpp_wrappers/optimization._CppOptimizerParameters\n      Python object containing the LogLikelihoodTypes objective_type and OptimizerTypes optimzer_typ\n      to use as well as appropriate parameter structs e.g., NewtonParameters for type kNewton).\n      See comments on the python interface for multistart_hyperparameter_optimization_wrapper\n    :log_likelihood_eval: object supporting evaluation of log likelihood\n    :covariance: the CovarianceFunction object encoding assumptions about the GP's behavior on our data\n    :hyperparameter_domain[2][n_hyper]: matrix specifying the boundaries of a n_hyper-dimensional tensor-product\n      domain.  Specified as a list of [x_i_min, x_i_max] pairs, i = 0 .. dim-1\n      Specify in LOG-10 SPACE!\n    :optimizer_type: type of optimization to use (e.g., null, gradient descent)\n    :max_num_threads: maximum number of threads for use by OpenMP (generally should be <= # cores)\n    :randomness_source: object containing randomness sources for generating random points in the domain\n    :status: pydict object; cannot be None\n  \\output\n    :randomness_source: PRNG internal states modified\n    :status: modified on exit to describe whether convergence occurred\n    :new_hyperparameters[n_hyper]: new hyperparameters found by optimizer to maximize the specified log likelihood measure\n\\endrst*/\ntemplate <typename LogLikelihoodEvaluator>\nvoid DispatchHyperparameterOptimization(const boost::python::object& optimizer_parameters,\n                                        const LogLikelihoodEvaluator& log_likelihood_eval,\n                                        const CovarianceInterface& covariance,\n                                        const std::vector<double> noise_variance,\n                                        ClosedInterval const * restrict hyperparameter_domain,\n                                        OptimizerTypes optimizer_type, int max_num_threads,\n                                        RandomnessSourceContainer& randomness_source,\n                                        boost::python::dict& status,\n                                        double * restrict new_hyperparameters) {\n  bool found_flag = false;\n  switch (optimizer_type) {\n    case OptimizerTypes::kNull: {\n      // optimizer_parameters must contain an int num_random_samples field, extract it\n      int num_random_samples = boost::python::extract<int>(optimizer_parameters.attr(\"num_random_samples\"));\n      ThreadSchedule thread_schedule(max_num_threads, omp_sched_guided);\n      LatinHypercubeSearchHyperparameterOptimization(log_likelihood_eval, covariance, noise_variance, hyperparameter_domain,\n                                                     thread_schedule, num_random_samples, &found_flag,\n                                                     &randomness_source.uniform_generator, new_hyperparameters);\n      status[std::string(log_likelihood_eval.kName) + \"_lhc_found_update\"] = found_flag;\n      break;\n    }  // end case kNull for optimizer_type\n    case OptimizerTypes::kGradientDescent: {\n      // optimizer_parameters must contain a optimizer_parameters field\n      // of type GradientDescentParameters. extract it\n      const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n      ThreadSchedule thread_schedule(max_num_threads, omp_sched_dynamic);\n      MultistartGradientDescentHyperparameterOptimization(log_likelihood_eval, covariance, noise_variance,\n                                                          gradient_descent_parameters,\n                                                          hyperparameter_domain,\n                                                          thread_schedule, &found_flag,\n                                                          &randomness_source.uniform_generator,\n                                                          new_hyperparameters);\n      status[std::string(log_likelihood_eval.kName) + \"_gradient_descent_found_update\"] = found_flag;\n      break;\n    }  // end case kGradientDescent for optimizer_type\n/*    case OptimizerTypes::kNewton: {\n      // optimizer_parameters must contain a optimizer_parameters field\n      // of type NewtonParameters. extract it\n      const NewtonParameters& newton_parameters = boost::python::extract<NewtonParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n      ThreadSchedule thread_schedule(max_num_threads, omp_sched_dynamic);\n      MultistartNewtonHyperparameterOptimization(log_likelihood_eval, covariance,\n                                                 newton_parameters, hyperparameter_domain,\n                                                 thread_schedule, &found_flag,\n                                                 &randomness_source.uniform_generator,\n                                                 new_hyperparameters);\n      status[std::string(log_likelihood_eval.kName) + \"_newton_found_update\"] = found_flag;\n      break;\n    }  // end case kNewton for optimizer_type */\n    default: {\n      std::fill(new_hyperparameters, new_hyperparameters + covariance.GetNumberOfHyperparameters() + noise_variance.size(), 1.0);\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid optimizer choice. Setting all hyperparameters to 1.0.\");\n      break;\n    }\n  }  // end switch over optimzer_type for LogLikelihoodTypes::kLogMarginalLikelihood\n}\n\nboost::python::list MultistartHyperparameterOptimizationWrapper(const boost::python::object& optimizer_parameters,\n                                                                const boost::python::list& hyperparameter_domain,\n                                                                const boost::python::list& points_sampled,\n                                                                const boost::python::list& points_sampled_value,\n                                                                int dim, int num_sampled,\n                                                                const boost::python::list& hyperparameters,\n                                                                const boost::python::list& noise_variance,\n                                                                const boost::python::list& derivatives,\n                                                                int num_derivatives, int max_num_threads,\n                                                                RandomnessSourceContainer& randomness_source,\n                                                                boost::python::dict& status) {\n  // TODO(GH-131): make domain objects constructible from python; and pass them in through\n  // the optimizer_parameters python object\n  const int num_to_sample = 0;\n  const boost::python::list points_to_sample_dummy;\n  PythonInterfaceInputContainer input_container(hyperparameters, points_sampled, points_sampled_value, noise_variance,\n                                                points_to_sample_dummy, derivatives, num_derivatives, dim, num_sampled, num_to_sample);\n\n\n  SquareExponential sqexp(input_container.dim, input_container.alpha, input_container.lengths.data());\n\n  int num_hyperparameters = sqexp.GetNumberOfHyperparameters() + 1 + num_derivatives;\n  std::vector<double> new_hyperparameters(num_hyperparameters);\n\n  std::vector<ClosedInterval> hyperparameter_domain_C(num_hyperparameters);\n  CopyPylistToClosedIntervalVector(hyperparameter_domain, num_hyperparameters, hyperparameter_domain_C);\n\n  OptimizerTypes optimizer_type = boost::python::extract<OptimizerTypes>(optimizer_parameters.attr(\"optimizer_type\"));\n  LogLikelihoodTypes objective_type = boost::python::extract<LogLikelihoodTypes>(optimizer_parameters.attr(\"objective_type\"));\n  switch (objective_type) {\n    case LogLikelihoodTypes::kLogMarginalLikelihood: {\n      LogMarginalLikelihoodEvaluator log_likelihood_eval(input_container.points_sampled.data(),\n                                                         input_container.points_sampled_value.data(),\n                                                         input_container.derivatives.data(), input_container.num_derivatives,\n                                                         input_container.dim, input_container.num_sampled);\n\n      DispatchHyperparameterOptimization(optimizer_parameters, log_likelihood_eval, sqexp, input_container.noise_variance,\n                                         hyperparameter_domain_C.data(), optimizer_type, max_num_threads,\n                                         randomness_source, status, new_hyperparameters.data());\n      break;\n    }  // end case LogLikelihoodTypes::kLogMarginalLikelihood\n/*    case LogLikelihoodTypes::kLeaveOneOutLogLikelihood: {\n      LeaveOneOutLogLikelihoodEvaluator log_likelihood_eval(input_container.points_sampled.data(),\n                                                            input_container.points_sampled_value.data(),\n                                                            input_container.noise_variance.data(),\n                                                            input_container.dim, input_container.num_sampled);\n\n      DispatchHyperparameterOptimization(optimizer_parameters, log_likelihood_eval, matern_25,\n                                         hyperparameter_domain_C.data(), optimizer_type, max_num_threads,\n                                         randomness_source, status, new_hyperparameters.data());\n      break;\n    }  // end case LogLikelihoodTypes::kLeaveOneOutLogLikelihood*/\n    default: {\n      std::fill(new_hyperparameters.begin(), new_hyperparameters.end(), 1.0);\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid objective type choice. Setting all hyperparameters to 1.0.\");\n      break;\n    }\n  }  // end switch over objective_type\n\n  return VectorToPylist(new_hyperparameters);\n}\n\nboost::python::list EvaluateLogLikelihoodAtHyperparameterListWrapper(const boost::python::list& hyperparameter_list,\n                                                                     const boost::python::list& points_sampled,\n                                                                     const boost::python::list& points_sampled_value,\n                                                                     int dim, int num_sampled,\n                                                                     LogLikelihoodTypes objective_mode,\n                                                                     const boost::python::list& hyperparameters,\n                                                                     const boost::python::list& noise_variance,\n                                                                     const boost::python::list& derivatives,\n                                                                     int num_derivatives,\n                                                                     int num_multistarts, int max_num_threads,\n                                                                     boost::python::dict& status) {\n  const int num_to_sample = 0;\n  const boost::python::list points_to_sample_dummy;\n  PythonInterfaceInputContainer input_container(hyperparameters, points_sampled, points_sampled_value, noise_variance,\n                                                points_to_sample_dummy, derivatives, num_derivatives, dim, num_sampled, num_to_sample);\n\n  SquareExponential sqexp(input_container.dim, input_container.alpha, input_container.lengths.data());\n\n  std::vector<double> new_hyperparameters_C(sqexp.GetNumberOfHyperparameters() + 1 + num_derivatives);\n  std::vector<double> result_function_values_C(num_multistarts);\n  std::vector<double> initial_guesses_C((sqexp.GetNumberOfHyperparameters() + 1 + num_derivatives) * num_multistarts);\n\n  CopyPylistToVector(hyperparameter_list, (sqexp.GetNumberOfHyperparameters() + 1 + num_derivatives) * num_multistarts, initial_guesses_C);\n\n  TensorProductDomain dummy_domain(nullptr, 0);\n  ThreadSchedule thread_schedule(max_num_threads, omp_sched_guided);\n\n  bool found_flag = false;\n  switch (objective_mode) {\n    case LogLikelihoodTypes::kLogMarginalLikelihood: {\n      LogMarginalLikelihoodEvaluator log_likelihood_eval(input_container.points_sampled.data(),\n                                                         input_container.points_sampled_value.data(),\n                                                         input_container.derivatives.data(), input_container.num_derivatives,\n                                                         input_container.dim, input_container.num_sampled);\n      EvaluateLogLikelihoodAtPointList(log_likelihood_eval, sqexp, input_container.noise_variance, dummy_domain, thread_schedule,\n                                       initial_guesses_C.data(), num_multistarts, &found_flag,\n                                       result_function_values_C.data(), new_hyperparameters_C.data());\n      status[std::string(\"evaluate_\") + log_likelihood_eval.kName + \"_at_hyperparameter_list\"] = found_flag;\n      break;\n    }\n/*    case LogLikelihoodTypes::kLeaveOneOutLogLikelihood: {\n      LeaveOneOutLogLikelihoodEvaluator log_likelihood_eval(input_container.points_sampled.data(),\n                                                            input_container.points_sampled_value.data(),\n                                                            input_container.noise_variance.data(),\n                                                            input_container.dim, input_container.num_sampled);\n      EvaluateLogLikelihoodAtPointList(log_likelihood_eval, matern_25, dummy_domain, thread_schedule,\n                                       initial_guesses_C.data(), num_multistarts, &found_flag,\n                                       result_function_values_C.data(), new_hyperparameters_C.data());\n      status[std::string(\"evaluate_\") + log_likelihood_eval.kName + \"_at_hyperparameter_list\"] = found_flag;\n      break;\n    }*/\n    default: {\n      std::fill(result_function_values_C.begin(), result_function_values_C.end(), -std::numeric_limits<double>::max());\n      status[\"evaluate_invalid_log_likelihood_at_hyperparameter_list\"] = found_flag;\n      OL_THROW_EXCEPTION(OptimalLearningException, \"ERROR: invalid objective mode choice. Setting all results to -DBL_MAX.\");\n      break;\n    }\n  }\n\n  return VectorToPylist(result_function_values_C);\n}\n\nboost::python::list RestartedGradientDescentHyperparameterOptimizationWrapper(const boost::python::object& optimizer_parameters,\n                                                                              const boost::python::list& hyperparameter_domain,\n                                                                              const boost::python::list& points_sampled,\n                                                                              const boost::python::list& points_sampled_value,\n                                                                              int dim, int num_sampled,\n                                                                              const boost::python::list& hyperparameters,\n                                                                              const boost::python::list& noise_variance,\n                                                                              const boost::python::list& derivatives,\n                                                                              int num_derivatives,\n                                                                              boost::python::dict& status){\n  // the optimizer_parameters python object\n  const int num_to_sample = 0;\n  const boost::python::list points_to_sample_dummy;\n  PythonInterfaceInputContainer input_container(hyperparameters, points_sampled, points_sampled_value, noise_variance,\n                                                points_to_sample_dummy, derivatives, num_derivatives, dim, num_sampled, num_to_sample);\n\n\n  SquareExponential sqexp(input_container.dim, input_container.alpha, input_container.lengths.data());\n\n  int num_hyperparameters = sqexp.GetNumberOfHyperparameters() + 1 + num_derivatives;\n  std::vector<double> new_hyperparameters(num_hyperparameters);\n\n  std::vector<ClosedInterval> hyperparameter_domain_C(num_hyperparameters);\n  CopyPylistToClosedIntervalVector(hyperparameter_domain, num_hyperparameters, hyperparameter_domain_C);\n\n  LogMarginalLikelihoodEvaluator log_likelihood_eval(input_container.points_sampled.data(),\n                                                     input_container.points_sampled_value.data(),\n                                                     input_container.derivatives.data(), input_container.num_derivatives,\n                                                     input_container.dim, input_container.num_sampled);\n  const GradientDescentParameters& gradient_descent_parameters = boost::python::extract<GradientDescentParameters&>(optimizer_parameters.attr(\"optimizer_parameters\"));\n  RestartedGradientDescentHyperparameterOptimizationTensor(log_likelihood_eval, sqexp, input_container.noise_variance, gradient_descent_parameters,\n                                                           hyperparameter_domain_C.data(), new_hyperparameters.data());\n  return VectorToPylist(new_hyperparameters);\n}\n\n\n}  // end unnamed namespace\n\nvoid ExportModelSelectionFunctions() {\n  boost::python::def(\"compute_log_likelihood\", ComputeLogLikelihoodWrapper, R\"%%(\n    Computes the specified log likelihood measure of model fit using the given\n    hyperparameters.\n\n    :param points_sampled: points that have already been sampled\n    :type points_sampled: list of float64 with shape (num_sampled, dim)\n    :param points_sampled_value: values of the already-sampled points\n    :type points_sampled_value: list of float64 with shape (num_sampled, )\n    :param dim: the spatial dimension of a point (i.e., number of independent params in experiment)\n    :type dim: int > 0\n    :param num_sampled: number of already-sampled points\n    :type num_sampled: int > 0\n    :param objective_mode: describes which log likelihood measure to compute (e.g., kLogMarginalLikelihood)\n    :type objective_mode: GPP.LogLikelihoodTypes (enum)\n    :param hyperparameters: covariance hyperparameters; see \"Details on ...\" section at the top of ``BOOST_PYTHON_MODULE``\n    :type hyperparameters: list of len 2; index 0 is a float64 ``\\alpha`` (signal variance) and index 1 is the length scales (list of floa64 of length ``dim``)\n    :param noise_variance: the ``\\sigma_n^2`` (noise variance) associated w/observation, points_sampled_value\n    :type noise_variance: list of float64 with shape (num_sampled, )\n    :return: computed log marginal likelihood of prior\n    :rtype: float64\n    )%%\");\n\n  boost::python::def(\"compute_hyperparameter_grad_log_likelihood\", ComputeHyperparameterGradLogLikelihoodWrapper, R\"%%(\n    Computes the gradient of the specified log likelihood measure of model fit using the given\n    hyperparameters. Gradient computed wrt the given hyperparameters.\n\n    ``n_hyper`` denotes the number of hyperparameters.\n\n    :param points_sampled: points that have already been sampled\n    :type points_sampled: list of float64 with shape (num_sampled, dim)\n    :param points_sampled_value: values of the already-sampled points\n    :type points_sampled_value: list of float64 with shape (num_sampled, )\n    :param dim: the spatial dimension of a point (i.e., number of independent params in experiment)\n    :type dim: int > 0\n    :param num_sampled: number of already-sampled points\n    :type num_sampled: int > 0\n    :param objective_mode: describes which log likelihood measure to compute (e.g., kLogMarginalLikelihood)\n    :type objective_mode: GPP.LogLikelihoodTypes (enum)\n    :param hyperparameters: covariance hyperparameters; see \"Details on ...\" section at the top of ``BOOST_PYTHON_MODULE``\n    :type hyperparameters: list of len 2; index 0 is a float64 ``\\alpha`` (signal variance) and index 1 is the length scales (list of floa64 of length ``dim``)\n    :param noise_variance: the ``\\sigma_n^2`` (noise variance) associated w/observation, points_sampled_value\n    :type noise_variance: list of float64 with shape (num_sampled, )\n    :return: gradients of log marginal likelihood wrt hyperparameters\n    :rtype: list of float64 with shape (num_hyperparameters, )\n    )%%\");\n\n  boost::python::def(\"multistart_hyperparameter_optimization\", MultistartHyperparameterOptimizationWrapper, R\"%%(\n    Optimize the specified log likelihood measure over the specified domain using the specified optimization method.\n\n    The _CppOptimizerParameters object is a python class defined in:\n    ``python/cpp_wrappers/optimization._CppOptimizerParameters``\n    See that class definition for more details.\n\n    This function expects it to have the fields:\n\n    * objective_type (LogLikelihoodTypes enum from this file)\n    * optimizer_type (OptimizerTypes enum from this file)\n    * num_random_samples (int, number of samples to 'dumb' search over, only used if optimizer_type == kNull)\n    * optimizer_parameters (*Parameters struct (gpp_optimizer_parameters.hpp) where * matches optimizer_type\n      unused if optimizer_type == kNull)\n\n    ``n_hyper`` denotes the number of hyperparameters.\n\n\n    :param optimizer_parameters: python object containing the LogLikelihoodTypes\n      objective to use, OptimizerTypes optimzer_type to use as well as appropriate\n      parameter structs e.g., NewtonParameters for type kNewton\n    :type optimizer_parameters:  _CppOptimizerParameters\n    :param hyperparameter_domain: [lower, upper] bound pairs for each hyperparameter dimension in LOG-10 SPACE\n    :type hyperparameter_domain: list of float64 with shape (num_hyperparameters, 2)\n    :param points_sampled: points that have already been sampled\n    :type points_sampled: list of float64 with shape (num_sampled, dim)\n    :param points_sampled_value: values of the already-sampled points\n    :type points_sampled_value: list of float64 with shape (num_sampled, )\n    :param dim: the spatial dimension of a point (i.e., number of independent params in experiment)\n    :type dim: int > 0\n    :param num_sampled: number of already-sampled points\n    :type num_sampled: int > 0\n    :param hyperparameters: covariance hyperparameters; see \"Details on ...\" section at the top of ``BOOST_PYTHON_MODULE``\n    :type hyperparameters: list of len 2; index 0 is a float64 ``\\alpha`` (signal variance) and index 1 is the length scales (list of floa64 of length ``dim``)\n    :param noise_variance: the ``\\sigma_n^2`` (noise variance) associated w/observation, points_sampled_value\n    :type noise_variance: list of float64 with shape (num_sampled, )\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: optimized hyperparameters\n    :rtype: list of float64 with shape (num_hyperparameters, )\n    )%%\");\n\n  boost::python::def(\"restarted_hyperparameter_optimization\", RestartedGradientDescentHyperparameterOptimizationWrapper, R\"%%(\n    Optimize the specified log likelihood measure over the specified domain using the specified optimization method.\n\n    The _CppOptimizerParameters object is a python class defined in:\n    ``python/cpp_wrappers/optimization._CppOptimizerParameters``\n    See that class definition for more details.\n\n    This function expects it to have the fields:\n\n    * objective_type (LogLikelihoodTypes enum from this file)\n    * optimizer_type (OptimizerTypes enum from this file)\n    * num_random_samples (int, number of samples to 'dumb' search over, only used if optimizer_type == kNull)\n    * optimizer_parameters (*Parameters struct (gpp_optimizer_parameters.hpp) where * matches optimizer_type\n      unused if optimizer_type == kNull)\n\n    ``n_hyper`` denotes the number of hyperparameters.\n\n\n    :param optimizer_parameters: python object containing the LogLikelihoodTypes\n      objective to use, OptimizerTypes optimzer_type to use as well as appropriate\n      parameter structs e.g., NewtonParameters for type kNewton\n    :type optimizer_parameters:  _CppOptimizerParameters\n    :param hyperparameter_domain: [lower, upper] bound pairs for each hyperparameter dimension in LOG-10 SPACE\n    :type hyperparameter_domain: list of float64 with shape (num_hyperparameters, 2)\n    :param points_sampled: points that have already been sampled\n    :type points_sampled: list of float64 with shape (num_sampled, dim)\n    :param points_sampled_value: values of the already-sampled points\n    :type points_sampled_value: list of float64 with shape (num_sampled, )\n    :param dim: the spatial dimension of a point (i.e., number of independent params in experiment)\n    :type dim: int > 0\n    :param num_sampled: number of already-sampled points\n    :type num_sampled: int > 0\n    :param hyperparameters: covariance hyperparameters; see \"Details on ...\" section at the top of ``BOOST_PYTHON_MODULE``\n    :type hyperparameters: list of len 2; index 0 is a float64 ``\\alpha`` (signal variance) and index 1 is the length scales (list of floa64 of length ``dim``)\n    :param noise_variance: the ``\\sigma_n^2`` (noise variance) associated w/observation, points_sampled_value\n    :type noise_variance: list of float64 with shape (num_sampled, )\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param randomness_source: object containing randomness sources; only thread 0's source is used\n    :type randomness_source: GPP.RandomnessSourceContainer\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: optimized hyperparameters\n    :rtype: list of float64 with shape (num_hyperparameters, )\n    )%%\");\n\n  boost::python::def(\"evaluate_log_likelihood_at_hyperparameter_list\", EvaluateLogLikelihoodAtHyperparameterListWrapper, R\"%%(\n    Evaluates the specified log likelihood measure of model fit at each member of\n    hyperparameter_list. Useful for plotting.\n\n    Equivalent to::\n\n      result = []\n      for hyperparameters in hyperparameter_list:\n          result.append(compute_log_likelihood(hyperparameters, ...))\n\n    But this method is substantially faster (loops in C++ and is multithreaded).\n\n    ``n_hyper`` denotes the number of hyperparameters\n\n    :param hyperparameter_list[num_multistarts][n_hyper]: list of hyperparameters at which to evaluate log likelihood\n    :type hyperparameter_list: list of float64 with shape (num_multistarts, num_hyperparameters)\n    :param points_sampled: points that have already been sampled\n    :type points_sampled: list of float64 with shape (num_sampled, dim)\n    :param points_sampled_value: values of the already-sampled points\n    :type points_sampled_value: list of float64 with shape (num_sampled, )\n    :param dim: the spatial dimension of a point (i.e., number of independent params in experiment)\n    :type dim: int > 0\n    :param num_sampled: number of already-sampled points\n    :type num_sampled: int > 0\n    :param objective_mode: describes which log likelihood measure to compute (e.g., kLogMarginalLikelihood)\n    :type objective_mode: GPP.LogLikelihoodTypes (enum)\n    :param hyperparameters: covariance hyperparameters; see \"Details on ...\" section at the top of ``BOOST_PYTHON_MODULE``\n    :type hyperparameters: list of len 2; index 0 is a float64 ``\\alpha`` (signal variance) and index 1 is the length scales (list of floa64 of length ``dim``)\n    :param noise_variance: the ``\\sigma_n^2`` (noise variance) associated w/observation, points_sampled_value\n    :type noise_variance: list of float64 with shape (num_sampled, )\n    :param num_multistarts: number hyperparameter sets at which to compute log likelihood\n    :type num_multistarts: int > 0\n    :param max_num_threads: max number of threads to use during EI optimization\n    :type max_num_threads: int >= 1\n    :param status: pydict object (cannot be None!); modified on exit to describe whether convergence occurred\n    :type status: dict\n    :return: log likelihood values at each point of the hyperparameter_list list, in the same order\n    :rtype: list of float64 with shape (num_multistarts, )\n    )%%\");\n}\n\n}  // end namespace optimal_learning\n", "meta": {"hexsha": "604dc4c47603c61ea094451b2a821fa962e74bf4", "size": 36776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moe/optimal_learning/cpp/gpp_python_model_selection.cpp", "max_stars_repo_name": "AliBaheri/Cornell-MOE", "max_stars_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moe/optimal_learning/cpp/gpp_python_model_selection.cpp", "max_issues_repo_name": "AliBaheri/Cornell-MOE", "max_issues_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moe/optimal_learning/cpp/gpp_python_model_selection.cpp", "max_forks_repo_name": "AliBaheri/Cornell-MOE", "max_forks_repo_head_hexsha": "5c36a1c60eecfeea6e45c485179b671e12f07ad9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-02T14:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-02T14:48:26.000Z", "avg_line_length": 65.4377224199, "max_line_length": 171, "alphanum_fraction": 0.6605394823, "num_tokens": 7053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2064375384481597}}
{"text": "/* CirKit: A circuit toolkit\n * Copyright (C) 2009-2015  University of Bremen\n * Copyright (C) 2015-2017  EPFL\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#include \"zdd.hpp\"\n\n#include <vector>\n\n#include <boost/assign/std/vector.hpp>\n#include <boost/format.hpp>\n#include <boost/range/algorithm.hpp>\n\n#include <core/utils/bitset_utils.hpp>\n#include <core/utils/range_utils.hpp>\n#include <classical/dd/zdd_to_sets.hpp>\n\nusing namespace boost::assign;\n\nnamespace cirkit\n{\n\n/******************************************************************************\n * Types                                                                      *\n ******************************************************************************/\n\nenum class zdd_operation { diff, _union, intersection, symmetric_difference, join, meet, delta, nonsub, nonsup, minhit };\n\n/******************************************************************************\n * Private functions                                                          *\n ******************************************************************************/\n\n/******************************************************************************\n * Public functions                                                           *\n ******************************************************************************/\n\nzdd_manager::zdd_manager( unsigned nvars, unsigned log_max_objs, bool verbose )\n  : dd_manager( nvars, log_max_objs, verbose ) {}\n\nzdd_manager::~zdd_manager() {}\n\nunsigned zdd_manager::zdd_diff( unsigned z1, unsigned z2 )\n{\n  /* terminating cases */\n  if ( z1 == 0u ) { return 0u; }\n  if ( z2 == 0u ) { return z1; }\n  if ( z1 == z2 ) { return 0u; }\n\n  const auto r = cache.lookup( z1, z2, (unsigned)zdd_operation::diff );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node1 = nodes.at( z1 );\n  const auto& node2 = nodes.at( z2 );\n  unsigned rlow, rhigh, idx;\n  if ( node1.var < node2.var )\n  {\n    rlow = zdd_diff( node1.low, z2 );\n    idx = unique_create( node1.var, node1.high, rlow );\n  }\n  else if ( node1.var > node2.var )\n  {\n    idx = zdd_diff( z1, node2.low );\n  }\n  else\n  {\n    rlow = zdd_diff( node1.low, node2.low );\n    rhigh = zdd_diff( node1.high, node2.high );\n    idx = unique_create( node1.var, rhigh, rlow );\n  }\n  return cache.insert( z1, z2, (unsigned)zdd_operation::diff, idx );\n}\n\nunsigned zdd_manager::zdd_union( unsigned z1, unsigned z2 )\n{\n  /* terminating cases */\n  if ( z1 == 0u ) { return z2; }\n  if ( z2 == 0u ) { return z1; }\n  if ( z1 == z2 ) { return z1; }\n\n  /* commutativity */\n  if ( z1 > z2 ) { return zdd_union( z2, z1 ); }\n\n  const auto r = cache.lookup( z1, z2, (unsigned)zdd_operation::_union );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node1 = nodes.at( z1 );\n  const auto& node2 = nodes.at( z2 );\n  unsigned rlow, rhigh;\n  if ( node1.var < node2.var )\n  {\n    rlow = zdd_union( node1.low, z2 );\n    rhigh = node1.high;\n  }\n  else if ( node1.var > node2.var )\n  {\n    rlow = zdd_union( z1, node2.low );\n    rhigh = node2.high;\n  }\n  else\n  {\n    rlow = zdd_union( node1.low, node2.low );\n    rhigh = zdd_union( node1.high, node2.high );\n  }\n  const auto idx = unique_create( std::min( node1.var, node2.var ), rhigh, rlow );\n  return cache.insert( z1, z2, (unsigned)zdd_operation::_union, idx );\n}\n\nunsigned zdd_manager::zdd_intersection( unsigned z1, unsigned z2 )\n{\n  /* terminating cases */\n  if ( z1 == 0u ) { return 0u; }\n  if ( z2 == 0u ) { return 0u; }\n  if ( z1 == z2 ) { return z1; }\n\n  /* commutativity */\n  if ( z1 > z2 ) { return zdd_intersection( z2, z1 ); }\n\n  const auto& node1 = nodes.at( z1 );\n  const auto& node2 = nodes.at( z2 );\n  if ( node1.var < node2.var )\n  {\n    return zdd_intersection( node1.low, z2 );\n  }\n  if ( node1.var > node2.var )\n  {\n    return zdd_intersection( z1, node2.low );\n  }\n\n  const auto r = cache.lookup( z1, z2, (unsigned)zdd_operation::intersection );\n  if ( r >= 0 ) { return r; }\n\n  auto rlow = zdd_intersection( node1.low, node2.low );\n  auto rhigh = zdd_intersection( node1.high, node2.high );\n\n  const auto idx = unique_create( node1.var, rhigh, rlow );\n  return cache.insert( z1, z2, (unsigned)zdd_operation::intersection, idx );\n}\n\nunsigned zdd_manager::zdd_symmetric_difference( unsigned z1, unsigned z2 )\n{\n  /* terminating cases */\n  if ( z1 == 0u ) { return z2; }\n  if ( z2 == 0u ) { return z1; }\n  if ( z1 == z2 ) { return 0u; }\n\n  /* commutativity */\n  if ( z1 > z2 ) { return zdd_symmetric_difference( z2, z1 ); }\n\n  const auto r = cache.lookup( z1, z2, (unsigned)zdd_operation::symmetric_difference );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node1 = nodes.at( z1 );\n  const auto& node2 = nodes.at( z2 );\n  unsigned rlow, rhigh;\n  if ( node1.var < node2.var )\n  {\n    rlow = zdd_symmetric_difference( node1.low, z2 );\n    rhigh = node1.high;\n  }\n  else if ( node1.var > node2.var )\n  {\n    rlow = zdd_symmetric_difference( z1, node2.low );\n    rhigh = node2.high;\n  }\n  else\n  {\n    rlow = zdd_symmetric_difference( node1.low, node2.low );\n    rhigh = zdd_symmetric_difference( node1.high, node2.high );\n  }\n  const auto idx = unique_create( std::min( node1.var, node2.var ), rhigh, rlow );\n  return cache.insert( z1, z2, (unsigned)zdd_operation::symmetric_difference, idx );\n}\n\nunsigned zdd_manager::zdd_join( unsigned z1, unsigned z2 )\n{\n  /* swapping */\n  const auto& node1 = nodes.at( z1 );\n  const auto& node2 = nodes.at( z2 );\n\n  /* commutativity */\n  if ( node1.var < node2.var || ( ( node1.var == node2.var ) && ( z1 > z2 ) ) ) { return zdd_join( z2, z1 ); }\n\n  /* terminating cases */\n  if ( z1 == 0u ) { return 0u; }\n  if ( z1 == 1u ) { return z2; }\n\n  const auto r = cache.lookup( z1, z2, (unsigned)zdd_operation::join );\n  if ( r >= 0 ) { return r; }\n\n  unsigned rlow, rhigh;\n  if ( node1.var > node2.var )\n  {\n    rlow = zdd_join( z1, node2.low );\n    rhigh = zdd_join( z1, node2.high );\n  }\n  else\n  {\n    rlow = zdd_join( node1.low, node2.low );\n    auto r1 = zdd_join( node1.low, node2.high );\n    auto r2 = zdd_join( node1.high, node2.low );\n    auto r3 = zdd_join( node1.high, node2.high );\n    rhigh = zdd_union( zdd_union( r1, r2 ), r3 );\n  }\n\n  const auto idx = unique_create( node2.var, rhigh, rlow );\n  return cache.insert( z1, z2, (unsigned)zdd_operation::join, idx );\n}\n\nunsigned zdd_manager::zdd_meet( unsigned z1, unsigned z2 )\n{\n  /* swapping */\n  const auto& node1 = nodes.at( z1 );\n  const auto& node2 = nodes.at( z2 );\n\n  /* commutativity */\n  if ( node1.var < node2.var || ( ( node1.var == node2.var ) && ( z1 > z2 ) ) ) { return zdd_join( z2, z1 ); }\n\n  /* terminating cases */\n  if ( z1 <= 1u ) { return z1; }\n\n  const auto r = cache.lookup( z1, z2, (unsigned)zdd_operation::meet );\n  if ( r >= 0 ) { return r; }\n\n  if ( node1.var > node2.var )\n  {\n    auto idx = zdd_meet( z1, zdd_union( node2.low, node2.high ) );\n    return cache.insert( z1, z2, (unsigned)zdd_operation::join, idx );\n  }\n  else\n  {\n    auto rhigh = zdd_join( node1.high, node2.high );\n    auto r1 = zdd_join( node1.low, node2.high );\n    auto r2 = zdd_join( node1.high, node2.low );\n    auto r3 = zdd_join( node1.low, node2.low );\n    auto rlow = zdd_union( zdd_union( r1, r2 ), r3 );\n\n    const auto idx = unique_create( node2.var, rhigh, rlow );\n    return cache.insert( z1, z2, (unsigned)zdd_operation::join, idx );\n  }\n}\n\nunsigned zdd_manager::zdd_delta( unsigned z1, unsigned z2 )\n{\n  /* swapping */\n  const auto& node1 = nodes.at( z1 );\n  const auto& node2 = nodes.at( z2 );\n\n  /* commutativity */\n  if ( node1.var < node2.var || ( ( node1.var == node2.var ) && ( z1 > z2 ) ) ) { return zdd_delta( z2, z1 ); }\n\n  /* terminating cases */\n  if ( z1 == 0u ) { return 0u; }\n  if ( z1 == 1u ) { return z2; }\n\n  const auto r = cache.lookup( z1, z2, (unsigned)zdd_operation::delta );\n  if ( r >= 0 ) { return r; }\n\n  unsigned rlow, rhigh;\n  if ( node1.var > node2.var )\n  {\n    rlow = zdd_delta( z1, node2.low );\n    rhigh = zdd_delta( z1, node2.high );\n  }\n  else\n  {\n    rlow  = zdd_union( zdd_delta( node1.low, node2.low ), zdd_delta( node1.high, node2.high ) );\n    rhigh = zdd_union( zdd_delta( node1.low, node2.high ), zdd_delta( node1.high, node2.low ) );\n  }\n\n  const auto idx = unique_create( node2.var, rhigh, rlow );\n  return cache.insert( z1, z2, (unsigned)zdd_operation::delta, idx );\n}\n\nunsigned zdd_manager::zdd_nonsub( unsigned z1, unsigned z2 )\n{\n  /* terminating cases */\n  if ( z1 == 0u ) { return 0u; }\n  if ( z1 == 1u ) { return 0u; }\n  if ( z2 == 0u ) { return z1; }\n  if ( z1 == z2 ) { return 0u; }\n\n  const auto r = cache.lookup( z1, z2, (unsigned)zdd_operation::nonsub );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node1 = nodes.at( z1 );\n  const auto& node2 = nodes.at( z2 );\n\n  unsigned rlow, rhigh;\n\n  if ( node1.var > node2.var )\n  {\n    rlow = zdd_nonsub( node1.low, z2 );\n    rhigh = node1.high;\n  }\n  else\n  {\n    auto r1 = zdd_nonsub( node1.low, node2.low );\n    auto r2 = zdd_nonsub( node1.low, node2.high );\n    rlow = zdd_intersection( r1, r2 );\n    rhigh = zdd_nonsub( node1.high, node2.high );\n  }\n\n  const auto idx = unique_create( node1.var, rhigh, rlow );\n  return cache.insert( z1, z2, (unsigned)zdd_operation::nonsub, idx );\n}\n\nunsigned zdd_manager::zdd_nonsup( unsigned z1, unsigned z2 )\n{\n  /* terminating cases */\n  if ( z1 == 0u ) { return 0u; }\n  if ( z2 == 1u ) { return 0u; }\n  if ( z2 == 0u ) { return z1; }\n  if ( z1 == z2 ) { return 0u; }\n\n  const auto& node1 = nodes.at( z1 );\n  const auto& node2 = nodes.at( z2 );\n\n  if ( node1.var > node2.var )\n  {\n    return zdd_nonsup( z1, node2.low );\n  }\n\n  const auto r = cache.lookup( z1, z2, (unsigned)zdd_operation::nonsup );\n  if ( r >= 0 ) { return r; }\n\n  unsigned rlow, rhigh;\n\n  if ( node1.var < node2.var )\n  {\n    rlow = zdd_nonsup( node1.low, z2 );\n    rhigh = zdd_nonsup( node1.high, z2 );\n  }\n  else\n  {\n    rlow = zdd_nonsup( node1.high, node2.high );\n    auto rtmp = zdd_nonsup( node1.high, node2.low );\n    rhigh = zdd_intersection( rtmp, rlow );\n    rlow = zdd_nonsup( node1.low, node2.low );\n  }\n  const auto idx = unique_create( node1.var, rhigh, rlow );\n  return cache.insert( z1, z2, (unsigned)zdd_operation::nonsup, idx );\n}\n\nunsigned zdd_manager::zdd_minhit( unsigned z )\n{\n  /* terminating cases */\n  if ( z == 0u ) { return 1u; }\n  if ( z == 1u ) { return 0u; }\n\n  const auto r = cache.lookup( z, z, (unsigned)zdd_operation::minhit );\n  if ( r >= 0 ) { return r; }\n\n  const auto& node = nodes.at( z );\n  auto rtmp = zdd_union( node.low, node.high );\n  auto rlow = zdd_minhit( rtmp );\n  rtmp = zdd_minhit( node.low );\n  auto rhigh = zdd_nonsup( rtmp, rlow );\n\n  const auto idx = unique_create( node.var, rhigh, rlow );\n  return cache.insert( z, z, (unsigned)zdd_operation::minhit, idx );\n}\n\nunsigned zdd_manager::unique_create( unsigned var, unsigned high, unsigned low )\n{\n  if ( verbose )\n  {\n    std::cout << boost::format( \"[i] attempt to create (%d, %d, %d)\" ) % var % high % low << std::endl;\n  }\n  assert( var < nvars );\n  assert( var < nodes[high].var );\n  assert( var < nodes[low].var );\n\n  if ( high == 0u ) { return low; }\n\n  return unique_lookup( var, high, low );\n}\n\nstd::ostream& operator<<( std::ostream& os, const zdd_manager& mgr )\n{\n  for ( auto node : index( mgr.nodes ) )\n  {\n    os << node.index << \": \" << node.value << std::endl;\n  }\n  return os;\n}\n\nzdd& zdd::operator=( const zdd& other )\n{\n  if ( this == &other ) { return *this; }\n  assert( !manager || manager == other.manager );\n  manager = other.manager;\n  index   = other.index;\n  return *this;\n}\n\nunsigned zdd::var() const\n{\n  return manager->get_var( index );\n}\n\nzdd zdd::high() const\n{\n  return zdd( manager, manager->get_high( index ) );\n}\n\nzdd zdd::low() const\n{\n  return zdd( manager, manager->get_low( index ) );\n}\n\nzdd zdd::operator-( const zdd& other ) const\n{\n  assert( manager == other.manager );\n  return zdd( manager, manager->zdd_diff( index, other.index ) );\n}\n\nzdd zdd::operator||( const zdd& other ) const\n{\n  assert( manager == other.manager );\n  return zdd( manager, manager->zdd_union( index, other.index ) );\n}\n\nzdd zdd::operator&&( const zdd& other ) const\n{\n  assert( manager == other.manager );\n  return zdd( manager, manager->zdd_intersection( index, other.index ) );\n}\n\nzdd zdd::operator^( const zdd& other ) const\n{\n  assert( manager == other.manager );\n  return zdd( manager, manager->zdd_symmetric_difference( index, other.index ) );\n}\n\nzdd zdd::operator+( const zdd& other ) const\n{\n  assert( manager == other.manager );\n  return zdd( manager, manager->zdd_join( index, other.index ) );\n}\n\nzdd zdd::operator*( const zdd& other ) const\n{\n  assert( manager == other.manager );\n  return zdd( manager, manager->zdd_meet( index, other.index ) );\n}\n\nzdd zdd::delta( const zdd& other ) const\n{\n  assert( manager == other.manager );\n  return zdd( manager, manager->zdd_delta( index, other.index ) );\n}\n\nzdd zdd::nonsub( const zdd& other ) const\n{\n  assert( manager == other.manager );\n  return zdd( manager, manager->zdd_nonsub( index, other.index ) );\n}\n\nzdd zdd::nonsup( const zdd& other ) const\n{\n  assert( manager == other.manager );\n  return zdd( manager, manager->zdd_nonsup( index, other.index ) );\n}\n\nzdd zdd::minhit() const\n{\n  return zdd( manager, manager->zdd_minhit( index ) );\n}\n\nbool zdd::equals( const zdd& other ) const\n{\n  assert( manager == other.manager );\n  return index == other.index;\n}\n\nstd::ostream& operator <<( std::ostream& os, const cirkit::zdd& z )\n{\n  auto s = cirkit::zdd_to_sets( z );\n  for ( const auto& e : s )\n  {\n    cirkit::print_as_set( os, e ) << std::endl;\n  }\n  return os;\n}\n\n}\n\n// Local Variables:\n// c-basic-offset: 2\n// eval: (c-set-offset 'substatement-open 0)\n// eval: (c-set-offset 'innamespace 0)\n// End:\n", "meta": {"hexsha": "a83566efc57fba2eca777a6acd862b59bb58857e", "size": 14654, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/classical/dd/zdd.cpp", "max_stars_repo_name": "eletesta/cirkit", "max_stars_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/classical/dd/zdd.cpp", "max_issues_repo_name": "eletesta/cirkit", "max_issues_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/classical/dd/zdd.cpp", "max_forks_repo_name": "eletesta/cirkit", "max_forks_repo_head_hexsha": "6d0939798ea25cecf92306ce796be154139b94f5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.5097276265, "max_line_length": 121, "alphanum_fraction": 0.6035894636, "num_tokens": 4524, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2064158875577332}}
{"text": "/**\n * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved.\n * http://soramitsu.co.jp\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n#ifndef IROHA_AMOUNT_H\n#define IROHA_AMOUNT_H\n\n#include <boost/multiprecision/cpp_dec_float.hpp>\n#include <boost/multiprecision/cpp_int.hpp>\n#include <boost/optional.hpp>\n#include <ciso646>\n#include <cstdint>\n#include <string>\n\nnamespace iroha {\n\n  /**\n   * Keeps integer and scale values allowing performing math\n   * operations on them\n   */\n  class Amount {\n   public:\n    /**\n     * Creates Amount with integer = 0 and scale = 0\n     */\n    Amount();\n\n    /**\n     * Amount with integer = amount and scale = 0\n     * @param amount integer part\n     */\n    Amount(boost::multiprecision::uint256_t amount);\n\n    /**\n     * Amount with provided integer and scale part\n     * @param amount integer part\n     * @param precision scale part\n     */\n    Amount(boost::multiprecision::uint256_t amount, uint8_t precision);\n\n    Amount(uint64_t first, uint64_t second, uint64_t third, uint64_t fourth);\n\n    Amount(uint64_t first,\n           uint64_t second,\n           uint64_t third,\n           uint64_t fourth,\n           uint8_t precision);\n\n    std::vector<uint64_t> to_uint64s();\n\n    /**\n     * Copy constructor\n     */\n    Amount(const Amount &);\n    Amount &operator=(const Amount &);\n\n    /**\n     * Move constructor\n     */\n    Amount(Amount &&);\n    Amount &operator=(Amount &&);\n\n    boost::multiprecision::uint256_t getIntValue();\n    uint8_t getPrecision();\n\n    static boost::optional<Amount> createFromString(std::string str_amount);\n\n    /**\n     * Takes percentage from current amount\n     * @param percents\n     * @return\n     */\n    Amount percentage(boost::multiprecision::uint256_t percents) const;\n\n    /**\n     * Takes percentage represented as amount value\n     * The current scale and scale of percents may differ\n     * @param percents\n     * @return\n     */\n    Amount percentage(const Amount &percents) const;\n\n    /**\n     * Sums up two optionals of the amounts.\n     * Requires to have the same scale.\n     * Otherwise nullopt is returned\n     * @param a left term\n     * @param b right term\n     * @param optional result\n     */\n    friend boost::optional<Amount> operator+(boost::optional<Amount> a,\n                                             boost::optional<Amount> b) {\n      // check precisions\n      if (a->precision_ != b->precision_) {\n        return boost::none;\n      }\n      auto res = a->add(*b);\n      // check overflow\n      if (res.value_ < a->value_ or res.value_ < b->value_) {\n        return boost::none;\n      }\n      return res;\n    }\n\n    /**\n     * Subtracts right term from the left term\n     * Requires to have the same scale.\n     * Otherwise nullopt is returned\n     * @param a left term\n     * @param b right term\n     * @param optional result\n     */\n    friend boost::optional<Amount> operator-(boost::optional<Amount> a,\n                                             boost::optional<Amount> b) {\n      // check precisions\n      if (a->precision_ != b->precision_) {\n        return boost::none;\n      }\n      // check if a greater than b\n      if (a->value_ < b->value_) {\n        return boost::none;\n      }\n      return a->subtract(*b);\n    }\n\n    /**\n     * Comparisons are possible between amounts with different precisions.\n     *\n     * @return\n     */\n    bool operator==(const Amount &) const;\n    bool operator!=(const Amount &) const;\n    bool operator<(const Amount &) const;\n    bool operator>(const Amount &) const;\n    bool operator<=(const Amount &) const;\n    bool operator>=(const Amount &) const;\n\n    std::string to_string() const;\n    ~Amount() = default;\n\n   private:\n    /**\n     * Support function for comparison operators.\n     * Returns 0 when equal, -1 when current Amount smaller, and 1 when it is\n     * greater\n     * @param other\n     * @return\n     */\n    int compareTo(const Amount &other) const;\n\n    /**\n     * Sums two amounts.\n     * @return\n     */\n    Amount add(const Amount &) const;\n    /**\n     * Subtracts one amount from another.\n     * Requires to have the same scale between both amounts.\n     * Otherwise nullopt is returned\n     * @return\n     */\n    Amount subtract(const Amount &) const;\n\n    boost::multiprecision::uint256_t value_{0};\n    uint8_t precision_{0};\n  };\n}  // namespace iroha\n#endif  // IROHA_AMOUNT_H\n", "meta": {"hexsha": "3a472d1d9faa7baff4f05355c26433dc01390965", "size": 4877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "libs/amount/amount.hpp", "max_stars_repo_name": "bbr88/iroha", "max_stars_repo_head_hexsha": "8cc19fe8cd53cdb108853da7098c06d2b9237e38", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/amount/amount.hpp", "max_issues_repo_name": "bbr88/iroha", "max_issues_repo_head_hexsha": "8cc19fe8cd53cdb108853da7098c06d2b9237e38", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-07-07T19:31:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-01T22:29:48.000Z", "max_forks_repo_path": "libs/amount/amount.hpp", "max_forks_repo_name": "bbr88/iroha", "max_forks_repo_head_hexsha": "8cc19fe8cd53cdb108853da7098c06d2b9237e38", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9447513812, "max_line_length": 77, "alphanum_fraction": 0.6186180029, "num_tokens": 1159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.2061508445033337}}
{"text": "// ==========================================================================\r\n// Munin Algorithm.\r\n//\r\n// Copyright (C) 2010 Matthew Chaplain, All Rights Reserved.\r\n//\r\n// Permission to reproduce, distribute, perform, display, and to prepare\r\n// derivitive works from this file under the following conditions:\r\n//\r\n// 1. Any copy, reproduction or derivitive work of any part of this file\r\n//    contains this copyright notice and licence in its entirety.\r\n//\r\n// 2. The rights granted to you under this license automatically terminate\r\n//    should you attempt to assert any patent claims against the licensor\r\n//    or contributors, which in any way restrict the ability of any party\r\n//    from using this software or portions thereof in any form under the\r\n//    terms of this license.\r\n//\r\n// Disclaimer: THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY\r\n//             KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\r\n//             WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\r\n//             PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\r\n//             OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\r\n//             OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\r\n//             OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\r\n//             SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n// ==========================================================================\r\n#include \"munin/algorithm.hpp\"\r\n#include <terminalpp/canvas.hpp>\r\n#include <terminalpp/canvas_view.hpp>\r\n#include \"odin/core.hpp\"\r\n#include <boost/bind.hpp>\r\n#include <algorithm>\r\n\r\nusing namespace odin;\r\nusing namespace boost;\r\nusing namespace std;\r\n\r\nnamespace munin {\r\n\r\n// ==========================================================================\r\n// INTERSECTION\r\n// ==========================================================================\r\noptional<rectangle> intersection(rectangle const &lhs, rectangle const &rhs)\r\n{\r\n    // Check to see if the rectangles overlap.\r\n\r\n    // Calculate the rectangle with the leftmost origin, and its counterpart.\r\n    // Note: the rectangle that is not the leftmost is not necessarily the\r\n    // rightmost, since the leftmost rectangle may extend further than its\r\n    // counterpart.\r\n    auto const &leftmost     = lhs.origin.x < rhs.origin.x ? lhs : rhs;\r\n    auto const &not_leftmost = lhs.origin.x < rhs.origin.x ? rhs : lhs;\r\n\r\n    // Calculate the rectangle with the topmost origin.\r\n    auto const &topmost        = lhs.origin.y < rhs.origin.y ? lhs : rhs;\r\n    auto const &not_topmost    = lhs.origin.y < rhs.origin.y ? rhs : lhs;\r\n\r\n    bool overlaps =\r\n        not_leftmost.origin.x >= leftmost.origin.x\r\n     && not_leftmost.origin.x <  leftmost.origin.x + leftmost.size.width\r\n     && not_topmost.origin.y  >= topmost.origin.y\r\n     && not_topmost.origin.y  <  topmost.origin.y + topmost.size.height;\r\n\r\n    if (!overlaps)\r\n    {\r\n        // There is no overlapping rectangle.\r\n        return {};\r\n    }\r\n\r\n    // The overlapping rectangle has an origin that starts at the same x-\r\n    // co-ordinate as the not-leftmost rectangle, and at the same y-co-ordinate\r\n    // as the not-topmost rectangle.\r\n    rectangle overlap;\r\n    overlap.origin.x = not_leftmost.origin.x;\r\n    overlap.origin.y = not_topmost.origin.y;\r\n\r\n    // If the leftmost rectangle completely contains the other rectangle,\r\n    // then the width is simply that of the enclosed rectangle.\r\n    if (leftmost.origin.x + leftmost.size.width\r\n      > not_leftmost.origin.x + not_leftmost.size.width)\r\n    {\r\n        overlap.size.width = not_leftmost.size.width;\r\n    }\r\n    // Otherwise, the calculated width is the width of the leftmost rectangle\r\n    // minus the difference between the origins of the two rectangles.\r\n    else\r\n    {\r\n        overlap.size.width =\r\n            leftmost.size.width - (not_leftmost.origin.x - leftmost.origin.x);\r\n    }\r\n\r\n    // Same as above, but with height instead of width.\r\n    if (topmost.origin.y + topmost.size.height\r\n      > not_topmost.origin.y + not_topmost.size.height)\r\n    {\r\n        overlap.size.height = not_topmost.size.height;\r\n    }\r\n    else\r\n    {\r\n        overlap.size.height =\r\n            topmost.size.height - (not_topmost.origin.y - topmost.origin.y);\r\n    }\r\n\r\n    return overlap;\r\n}\r\n\r\n// ==========================================================================\r\n// CUT_SLICES\r\n// ==========================================================================\r\nstatic vector<rectangle> cut_slices(vector<rectangle> const &rectangles)\r\n{\r\n    vector<rectangle> slices;\r\n\r\n    for (auto &&current_rectangle : rectangles)\r\n    {\r\n        for (odin::s32 row = 0; row < current_rectangle.size.height; ++row)\r\n        {\r\n            slices.push_back(\r\n                rectangle{{ current_rectangle.origin.x\r\n                          , current_rectangle.origin.y + row}\r\n                        , {current_rectangle.size.width, 1}});\r\n        }\r\n    }\r\n\r\n    return slices;\r\n}\r\n\r\n// ==========================================================================\r\n// COMPARE_SLICES\r\n// ==========================================================================\r\nstatic bool compare_slices(rectangle const &lhs, rectangle const &rhs)\r\n{\r\n    if (lhs.origin.y == rhs.origin.y)\r\n    {\r\n        return lhs.origin.x < rhs.origin.x;\r\n    }\r\n    else\r\n    {\r\n        return lhs.origin.y < rhs.origin.y;\r\n    }\r\n}\r\n\r\n// ==========================================================================\r\n// HAS_EMPTY_HEIGHT\r\n// ==========================================================================\r\nstatic bool has_empty_height(rectangle const &rect)\r\n{\r\n    return rect.size.height == 0;\r\n}\r\n\r\n// ==========================================================================\r\n// MERGE_OVERLAPPING_SLICES\r\n// ==========================================================================\r\nstatic vector<rectangle> merge_overlapping_slices(vector<rectangle> rectangles)\r\n{\r\n    sort(rectangles.begin(), rectangles.end(), compare_slices);\r\n\r\n    auto first_slice = rectangles.begin();\r\n\r\n    // Iterate through adjacent slices, merging any that overlap.\r\n    for (; first_slice != rectangles.end(); ++first_slice)\r\n    {\r\n        // Skip over any slices that have been merged.\r\n        if (first_slice->size.height == 0)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        auto second_slice = first_slice + 1;\r\n\r\n        // Iterate through all adjacent slices that share a y-coordinate\r\n        // until we either run out of slices, or cannot merge a slice.\r\n        for (;\r\n             second_slice != rectangles.end()\r\n          && first_slice->origin.y == second_slice->origin.y\r\n          && first_slice->origin.x + first_slice->size.width >= second_slice->origin.x;\r\n             ++second_slice)\r\n        {\r\n            // Set the width of the first slice to be equivalent to the\r\n            // rightmost point of the two rectangles.\r\n            first_slice->size.width = (std::max)(\r\n                first_slice->origin.x + first_slice->size.width\r\n              , second_slice->origin.x + second_slice->size.width)\r\n              - first_slice->origin.x;\r\n\r\n            // Mark the second slice as having been merged.\r\n            second_slice->size.height = 0;\r\n        }\r\n    }\r\n\r\n    // Snip out any rectangles that have been merged (have 0 height).\r\n    rectangles.erase(remove_if(\r\n            rectangles.begin()\r\n          , rectangles.end()\r\n          , has_empty_height)\r\n      , rectangles.end());\r\n\r\n    return rectangles;\r\n}\r\n\r\n// ==========================================================================\r\n// RECTANGULAR_SLICE\r\n// ==========================================================================\r\nvector<rectangle> rectangular_slice(vector<rectangle> const &rectangles)\r\n{\r\n    return merge_overlapping_slices(cut_slices(rectangles));\r\n}\r\n\r\n// ==========================================================================\r\n// CLIP_REGION\r\n// ==========================================================================\r\nstatic munin::rectangle clip_region(\r\n    munin::rectangle region, terminalpp::extent size)\r\n{\r\n    if (region.origin.x < 0)\r\n    {\r\n        size.width += region.origin.x;\r\n        region.origin.x = 0;\r\n    }\r\n\r\n    if (region.origin.y < 0)\r\n    {\r\n        size.height += region.origin.y;\r\n        region.origin.y = 0;\r\n    }\r\n\r\n    if (region.origin.x >= size.width)\r\n    {\r\n        region.size.width = 0;\r\n    }\r\n\r\n    if (region.origin.y >= size.height)\r\n    {\r\n        region.size.height = 0;\r\n    }\r\n\r\n    if (region.origin.x < size.width\r\n     && region.origin.y < size.height)\r\n    {\r\n        if (region.origin.x + region.size.width >= size.width)\r\n        {\r\n            region.size.width = size.width - region.origin.x;\r\n        }\r\n\r\n        if (region.origin.y + region.size.height >= size.height)\r\n        {\r\n            region.size.height = size.height - region.origin.y;\r\n        }\r\n    }\r\n\r\n    return region;\r\n}\r\n\r\n// ==========================================================================\r\n// HAS_ZERO_DIMENSION\r\n// ==========================================================================\r\nstatic bool has_zero_dimension(munin::rectangle const &region)\r\n{\r\n    return region.size.width == 0 || region.size.height == 0;\r\n}\r\n\r\n// ==========================================================================\r\n// CLIP_REGIONS\r\n// ==========================================================================\r\nvector<rectangle> clip_regions(vector<rectangle> regions, terminalpp::extent size)\r\n{\r\n    // Returns a vector of rectangles that is identical to the regions\r\n    // passed in, except that their extends are clipped to those of the\r\n    // content's.\r\n    transform(\r\n        regions.begin()\r\n      , regions.end()\r\n      , regions.begin()\r\n      , bind(clip_region, _1, size));\r\n\r\n    return regions;\r\n}\r\n\r\n// ==========================================================================\r\n// PRUNE_REGIONS\r\n// ==========================================================================\r\nvector<rectangle> prune_regions(vector<rectangle> regions)\r\n{\r\n    regions.erase(\r\n        remove_if(\r\n            regions.begin()\r\n          , regions.end()\r\n          , bind(has_zero_dimension, _1))\r\n      , regions.end());\r\n\r\n    return regions;\r\n}\r\n\r\n// ==========================================================================\r\n// COPY_REGION\r\n// ==========================================================================\r\nvoid copy_region(\r\n    rectangle               const &region\r\n  , terminalpp::canvas      const &source\r\n  , terminalpp::canvas_view       &destination)\r\n{\r\n    for (s32 y_coord = region.origin.y;\r\n         y_coord < region.origin.y + region.size.height;\r\n         ++y_coord)\r\n    {\r\n        for (s32 x_coord = region.origin.x;\r\n             x_coord < region.origin.x + region.size.width;\r\n             ++x_coord)\r\n        {\r\n            destination[x_coord][y_coord] = source[x_coord][y_coord];\r\n        }\r\n    }\r\n}\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "473dd41c8f9a6f9503064e5c7e81dc0ff6c6f4de", "size": 11028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "munin/src/algorithm.cpp", "max_stars_repo_name": "KazDragon/paradice9", "max_stars_repo_head_hexsha": "bb89ce8bff2f99d2526f45b064bfdd3412feb992", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2015-12-16T07:00:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-05T13:29:28.000Z", "max_issues_repo_path": "munin/src/algorithm.cpp", "max_issues_repo_name": "KazDragon/paradice9", "max_issues_repo_head_hexsha": "bb89ce8bff2f99d2526f45b064bfdd3412feb992", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 43.0, "max_issues_repo_issues_event_min_datetime": "2015-07-18T11:13:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-15T13:18:43.000Z", "max_forks_repo_path": "munin/src/algorithm.cpp", "max_forks_repo_name": "KazDragon/paradice9", "max_forks_repo_head_hexsha": "bb89ce8bff2f99d2526f45b064bfdd3412feb992", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-10-09T13:33:35.000Z", "max_forks_repo_forks_event_max_datetime": "2016-07-11T02:23:08.000Z", "avg_line_length": 34.7886435331, "max_line_length": 88, "alphanum_fraction": 0.5097025753, "num_tokens": 2078, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150636, "lm_q2_score": 0.36658975016245987, "lm_q1q2_score": 0.20608813762878972}}
{"text": "#include <deal.II/base/conditional_ostream.h>\n#include <deal.II/base/graph_coloring.h>\n#include <deal.II/base/parameter_handler.h>\n#include <deal.II/base/timer.h>\n#include <deal.II/base/types.h>\n#include <deal.II/lac/trilinos_precondition.h>\n#include <deal.II/lac/trilinos_solver.h>\n#include <deal.II/lac/trilinos_vector.h>\n#include <deal.II/numerics/vector_tools.h>\n// system includes ------------------------------------------------------------\n#include <EpetraExt_HDF5.h>\n#include <algorithm>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/archive/text_oarchive.hpp>\n#include <boost/filesystem.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/program_options.hpp>\n#include <boost/static_assert.hpp>\n#include <cmath>\n#include <fstream>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n// own includes ---------------------------------------------------------------\n#include \"bte_config.h\"\n#include \"app/app.hpp\"\n#include \"aux/debug_output.hpp\"\n#include \"aux/message.hpp\"\n#include \"collision_tensor/collision_tensor.hpp\"\n#include \"export/epetra_row_matrix.hpp\"\n//#include \"collision_tensor/collision_tensor_factory.hpp\"\n#include \"collision_tensor/collision_tensor_operator.hpp\"\n#include \"export/export_dh.hpp\"\n#include \"grid/dof_mapper_periodic_distributed.hpp\"\n#include \"grid/grid_handler_periodic.hpp\"\n#include \"init/import/load_coefficients.hpp\"\n#include \"matrix/assembly/assembly.hpp\"\n#include \"matrix/assembly/velocity_var_form.hpp\"\n#include \"matrix/dofs/dofindex_sets.hpp\"\n#include \"matrix/dofs/periodic_utility.hpp\"\n#include \"matrix/system_matrix_handler.hpp\"\n#include \"method/method.hpp\"\n#include \"post_processing/xdmf_exporter.hpp\"\n#include \"solver/aztecOO_condest.hpp\"\n#include \"solver/solver_handler.hpp\"\n#include \"spectral/basis/indexer.hpp\"\n#include \"spectral/basis/spectral_basis_factory_ks.hpp\"\n\nusing namespace std;\nusing namespace dealii;\nusing namespace boltzmann;\nnamespace bf = boost::filesystem;\nnamespace po = boost::program_options;\n\ntypedef SpectralBasisFactoryKS basis_factory_t;\n\nconst int dim = 2;\nconst double PI = dealii::numbers::PI;\n\n// define the method\ntypedef Method<METHOD::MODLEASTSQUARES> method_t;\ntypedef App<dim> app_t;\n\ntypedef TrilinosWrappers::MPI::Vector vector_t;\n// typedef TrilinosWrappers::Vector vector_local_t;\ntypedef TrilinosWrappers::SparseMatrix matrix_t;\n\nint\nmain(int argc, char* argv[])\n{\n  boltzmann::Timer<> timer;\n  int nthreads;\n  // --------------------------------------------------\n  // program options (read initial conditions from file)\n  string scratch_dir;\n  po::options_description options(\"options\");\n  options.add_options()(\"help\", \"produce help message\")(\n      \"export-matrices\", \"export matrices to hdf5 file\")(\"export-dofs\", \"export dofs and exit\")(\n      \"petrov-galerkin\", \"use Galerkin disc. for scattering\")(\n      \"threads,t\", po::value<int>(&nthreads)->default_value(1), \"number of threads\")(\n      \"init,i\", po::value<string>()->default_value(\"\"), \"initial distribution, dset='coeffs'\")(\n      \"condest\", \"estimate condition number\");\n  po::variables_map vm;\n  po::store(po::parse_command_line(argc, argv, options), vm);\n  po::notify(vm);\n  if (vm.count(\"help\")) {\n    cout << options << \"\\n\";\n    return 0;\n  }\n\n  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, nthreads);\n  const unsigned int process_id = Utilities::MPI::this_mpi_process(MPI_COMM_WORLD);\n  const unsigned int nprocs = Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);\n\n  ConditionalOStream pcout(std::cout, process_id == 0);\n  pcout << \"using \" << nprocs << \" MPI x \" << nthreads << \" OMP threads\\n\";\n  pcout << \"executable: \" << argv[0] << endl << \"periodic boundary conditions\" << endl;\n\n  std::string version_id = GIT_SHA1;\n  pcout << \"VersionID: \" << version_id << \"@\" << GIT_BNAME << std::endl;\n\n  // ----------------------------------------\n  // yaml config\n  if (!boost::filesystem::is_regular_file(\"config.yaml\")) {\n    pcout << \"config file not found\\n\";\n    return 1;\n  }\n  YAML::Node config = YAML::LoadFile(\"config.yaml\");\n\n  // make sure convergence messages etc. ware written only by proc 0\n  if (process_id != 0) dealii::deallog.depth_console(0);\n  pcout << \"\\n----------------------------------------\\n\";\n  pcout << config << endl;\n  pcout << \"\\n----------------------------------------\\n\";\n\n  const size_t nK = config[\"SpectralBasis\"][\"deg\"].as<size_t>();\n  const double beta = 2;\n  const double dt = config[\"TimeStepping\"][\"dt\"].as<double>();\n  // output frequency\n  const size_t ntsteps = config[\"TimeStepping\"][\"N\"].as<size_t>();\n\n  // ----------------------------------------\n  // MESH\n  timer.start();\n  GridHandlerPeriodic<2> grid_handler;\n  grid_handler.init(config, nprocs);\n  print_timer(timer.stop(), \"initialize mesh\", pcout);\n  const auto& dof_handler = grid_handler.dofhandler();\n  if (process_id == 0) export_dh(dof_handler);\n  // ----------------------------------------------------------------------\n  typedef basis_factory_t::basis_type basis_type;\n  basis_type spectral_basis;\n  basis_type spectral_test_basis;\n\n  if (bf::exists(\"spectral_basis.desc\")) {\n    // read from file if possible\n    // pcout << \"reading basis from file\" << std::endl;\n    basis_factory_t::create(spectral_basis, \"spectral_basis.desc\");\n  } else {\n    bool sorted = true;\n    basis_factory_t::create(spectral_basis, nK, nK, beta, sorted);\n    if (process_id == 0)\n      basis_factory_t::write_basis_descriptor(spectral_basis, \"spectral_basis.desc\");\n  }\n\n  if (bf::exists(\"spectral_basis_test.desc\")) {\n    basis_factory_t::create(spectral_test_basis, \"spectral_basis_test.desc\");\n  } else {\n    bool sorted = true;\n    if (vm.count(\"petrov-galerkin\"))\n      basis_factory_t::create_test(spectral_test_basis, nK, nK, beta, sorted);\n    else\n      basis_factory_t::create(spectral_test_basis, nK, nK, beta, sorted);\n\n    if (process_id == 0)\n      basis_factory_t::write_basis_descriptor(spectral_test_basis, \"spectral_basis_test.desc\");\n  }\n\n  if (vm.count(\"export-dofs\")) {\n    pcout << \"L: \" << dof_handler.n_dofs() << \"\\n N: \" << spectral_basis.n_dofs()\n          << \"\\n L x N: \" << dof_handler.n_dofs() * spectral_basis.n_dofs() << \"\\n\";\n\n    pcout << \"\\nvertex2dofix.dat/ dof.desc written to disk. Exit.\\n\";\n    return 0;\n  }\n\n  // ----------------------------------------------------------------------------------------------------\n  // DoFs\n  const size_t n_phys_dofs = dof_handler.n_dofs();\n  const size_t n_velo_dofs = spectral_basis.n_dofs();\n  const size_t n_dofs = spectral_basis.n_dofs() * dof_handler.n_dofs();\n\n  pcout << \"#vertices on grid\"\n        << \"\\t\" << n_phys_dofs << endl\n        << \"dim(V)\"\n        << \"\\t\" << n_velo_dofs << endl;\n  // regular indexer on full grid (used for post_processing and output)\n  Indexer<> global_indexer(n_phys_dofs, n_velo_dofs);\n  // indexer used for DoF enumeration\n  typedef DoFMapperPeriodicDistributed<> dof_mapper_t;\n  dof_mapper_t dof_mapper;\n  dof_mapper.init(dof_handler, nprocs);\n  IndexSet owned_phys_dofs = dof_mapper.owned_dofs(process_id);\n  IndexSet relevant_phys_dofs = dof_mapper.relevant_dofs(process_id);\n\n  DoFIndexSetsPeriodic index_sets(owned_phys_dofs, relevant_phys_dofs, n_velo_dofs, process_id);\n\n  IndexSet owned_dofs = index_sets.locally_owned_dofs(process_id);\n  IndexSet relevant_dofs = index_sets.locally_relevant_dofs();\n  Indexer<dof_mapper_t> indexer(dof_mapper, n_phys_dofs, n_velo_dofs);\n  pcout << \"#DoFs = \" << indexer.n_dofs() << endl;\n  /// DoFIndexSets provides index_maps on distributed (unrestricted) grid\n  // ----------------------------------------------------------------------\n  // Velocity matrix entries\n  VelocityVarForm<2> velocity_var_form;\n  velocity_var_form.init(spectral_basis, beta);\n  // --------------------------------------------------------------------------------------------------\n  // Scattering\n  bool has_scattering = (bool) config[\"Scattering\"];\n  CollisionTensorOperatorBase* QO = NULL;\n  double kn = 1;  // Knudsen-number\n  if (has_scattering) {\n    std::string tensor_fname = config[\"Scattering\"][\"file\"].as<std::string>().c_str();\n    if (config[\"Scattering\"][\"Galerkin\"] && !vm.count(\"petrov-galerkin\")) {\n      pcout << \"CollisionTensor Galerkin\\n\";\n      QO = new CollisionTensorOperatorG(\n          dof_handler, spectral_basis, index_sets.locally_owned_dofs(process_id));\n    } else if (config[\"Scattering\"][\"Petrov-Galerkin\"] && vm.count(\"petrov-galerkin\")) {\n      pcout << \"CollisionTensor Petrov-Galerkin\\n\";\n      QO = new CollisionTensorOperatorPG(\n          dof_handler, spectral_basis, index_sets.locally_owned_dofs(process_id));\n    } else {\n      // default\n      pcout << \"CollisionTensor Galerkin (DENSE)\\n\";\n      QO = new CollisionTensorOperatorDense<>(\n          dof_handler, spectral_basis, index_sets.locally_owned_dofs(process_id));\n    }\n    timer.start();\n    QO->load_tensor(tensor_fname);\n    print_timer(timer.stop(), \"load collision_tensor\", pcout);\n\n    if (config[\"Scattering\"][\"kn\"]) {\n      kn = config[\"Scattering\"][\"kn\"].as<double>();\n    }\n  }\n\n  SystemMatrixHandler<method_t, app_t> system_matrix_handler(\n      dof_handler, spectral_basis, indexer, index_sets, dt);\n\n  const auto& A = system_matrix_handler.get_lhs();\n  const auto& M = system_matrix_handler.get_rhs();\n\n#ifdef HAVE_EPETRAEXT_HDF5\n  if (vm.count(\"export-matrices\")) {\n    pcout << \"Export matrices to hdf5\\n\";\n    ExportEpetraHDF5 matrix_exporter(A.trilinos_matrix().Comm());\n    matrix_exporter.write(\"A\", A.trilinos_matrix());\n    matrix_exporter.write(\"M\", M.trilinos_matrix());\n  }\n#endif\n\n  // estimate condition number\n  if (vm.count(\"condest\")) {\n    int maxiters = 100;\n    // estimate condest from BC\n    AztecOOCondest condestCG;\n    condestCG.initialize(A, \"GMRES\");\n    double condCG = condestCG.compute(maxiters);\n    pcout << \"estimated condition number (GMRES): \" << condCG << endl;\n  }\n\n  // ----------------------------------------------------------------------\n  // Initial conditions\n  // create f0 on all DoFs\n  vector<double> f0_full_grid(n_velo_dofs * n_phys_dofs);\n  pcout << \"loading initial-distribution from file: \" << vm[\"init\"].as<string>() << endl;\n  load_coefficients(f0_full_grid, vm[\"init\"].as<string>(), dof_handler, global_indexer);\n  // convert between periodic and non-periodic solution on phase space grid\n  vector_t mu(owned_dofs);\n  vector_t mu_ghosted(owned_dofs, relevant_dofs);\n  // ----------------------------------------------------------------------\n  // Output\n  GridHelper grid_helper(n_velo_dofs, n_phys_dofs);\n  grid_helper.to_restricted_grid(mu, f0_full_grid, global_indexer, indexer, owned_phys_dofs);\n\n  /*\n   *   hint: DoFIndexSets contains full grid indices\n   */\n  DoFIndexSets dof_map(nprocs);\n  dof_map.init(dof_handler, n_velo_dofs);\n  IndexSet ghosts = dof_map.locally_relevant_dofs();\n  ghosts.subtract_set(dof_map.locally_owned_dofs(process_id));\n\n  vector_t mu_f(dof_map.locally_owned_dofs(process_id));\n  mu_ghosted = mu;\n  auto dofs = dof_map.locally_owned_phys_dofs(process_id);\n  unsigned int n_vtk = config[\"TimeStepping\"][\"export_vtk\"]\n                           ? config[\"TimeStepping\"][\"export_vtk\"].as<unsigned int>()\n                           : 1;\n  XDMFH5Exporter xdmf_exporter(\n      dof_handler, spectral_basis, dof_map.locally_owned_phys_dofs(process_id), 1, n_vtk);\n\n  grid_helper.to_full_grid(mu_f, mu_ghosted, global_indexer, indexer, dofs);\n  xdmf_exporter(mu_f, 0);\n  // mu_f_ghosted = mu_f;\n  //  output.run(mu_f_ghosted, 0, 0, global_indexer);\n  // ----------------------------------------------------------------------------------------------------\n  // Timestepping\n  pcout << \"\\n\\n-------------------- TIME STEPPING --------------------\\n\\n\";\n  vector_t rhs(owned_dofs);\n  vector_t sc(owned_dofs);\n  double current_time = 0;\n  // dump full solution vector / export paraview data every xx timestep\n  unsigned int n_dump =\n      config[\"TimeStepping\"][\"dump\"] ? config[\"TimeStepping\"][\"dump\"].as<unsigned int>() : 0;\n\n  SolverHandler solver_handler;\n  timer.start();\n  solver_handler.init(config, A);\n  print_timer(timer.stop(), \"Preconditioner\", pcout);\n  auto& solver = solver_handler.get_solver();\n  auto& P = solver_handler.get_preconditioner();\n\n#ifdef HAVE_EPETRAEXT_HDF5\n  // write full solution to disk\n  const auto& trilinos_vector = mu_f.trilinos_vector();\n  EpetraExt::HDF5 epetra_exporter(trilinos_vector.Comm());\n  epetra_exporter.Create(\"solution_vector\" + boost::lexical_cast<string>(0) + \".h5\");\n  epetra_exporter.Write(boost::lexical_cast<string>(0), trilinos_vector);\n  epetra_exporter.Flush();\n  epetra_exporter.Close();\n#endif\n\n  for (unsigned int i = 1; i <= ntsteps; ++i) {\n    timer.start();\n    M.vmult(rhs, mu);\n    print_timer(timer.stop(), \"MV-product\", pcout);\n    timer.start();\n    solver.solve(A, mu, rhs, P);\n    auto ctr = solver.control();\n    pcout << \"Solver::GMRES \" << ctr.last_step() << \"\\t\" << ctr.last_value() << \"\\n\";\n    print_timer(timer.stop(), \"timestep transport\", pcout);\n\n    if (has_scattering) {\n      timer.start();\n      QO->apply(mu, dt / kn);\n      print_timer(timer.stop(), \"timestep scattering\", pcout);\n    }\n\n    current_time += dt;\n    mu_ghosted = mu;\n    grid_helper.to_full_grid(mu_f, mu_ghosted, global_indexer, indexer, dofs);\n    xdmf_exporter(mu_f, current_time);\n\n#ifdef HAVE_EPETRAEXT_HDF5\n    if ((n_dump && (i % n_dump == 0)) || i == ntsteps) {\n      timer.start();\n      const auto& trilinos_vector = mu_f.trilinos_vector();\n      EpetraExt::HDF5 epetra_exporter2(trilinos_vector.Comm());\n      epetra_exporter2.Create(\"solution_vector\" + boost::lexical_cast<string>(i) + \".h5\");\n      epetra_exporter2.Write(boost::lexical_cast<string>(i), trilinos_vector);\n      epetra_exporter2.Flush();\n      epetra_exporter2.Close();\n      print_timer(timer.stop(), \"EpetraExt IO\", pcout);\n    }\n#endif\n  }\n\n  return 0;\n}\n", "meta": {"hexsha": "11057ddc95cb71b603c6412759ec85607f32f077", "size": 13911, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/modified_least_squares/main_periodic.cpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/modified_least_squares/main_periodic.cpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/modified_least_squares/main_periodic.cpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.185915493, "max_line_length": 105, "alphanum_fraction": 0.6574653152, "num_tokens": 3536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3849121585956185, "lm_q1q2_score": 0.20596589122379252}}
{"text": "//\n//  Copyright (C) 2007-2013 Greg Landrum\n//\n//   @@ All Rights Reserved @@\n//  This file is part of the RDKit.\n//  The contents are covered by the terms of the BSD license\n//  which is included in the file license.txt, found at the root\n//  of the RDKit source tree.\n//\n\n#include <GraphMol/RDKitBase.h>\n#include <GraphMol/Fingerprints/AtomPairs.h>\n#include <GraphMol/Subgraphs/Subgraphs.h>\n#include <DataStructs/SparseIntVect.h>\n#include <RDGeneral/hash/hash.hpp>\n#include <cstdint>\n#include <boost/dynamic_bitset.hpp>\n#include <boost/foreach.hpp>\n#include <GraphMol/Fingerprints/FingerprintUtil.h>\n\nnamespace RDKit {\nnamespace AtomPairs {\n\ntemplate <typename T1, typename T2>\nvoid updateElement(SparseIntVect<T1> &v, T2 elem) {\n  v.setVal(elem, v.getVal(elem) + 1);\n}\n\ntemplate <typename T1>\nvoid updateElement(ExplicitBitVect &v, T1 elem) {\n  v.setBit(elem % v.getNumBits());\n}\n\ntemplate <typename T>\nvoid setAtomPairBit(std::uint32_t i, std::uint32_t j,\n                    std::uint32_t nAtoms,\n                    const std::vector<std::uint32_t> &atomCodes,\n                    const double *dm, T *bv, unsigned int minLength,\n                    unsigned int maxLength, bool includeChirality) {\n  auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));\n  if (dist >= minLength && dist <= maxLength) {\n    std::uint32_t bitId =\n        getAtomPairCode(atomCodes[i], atomCodes[j], dist, includeChirality);\n    updateElement(*bv, static_cast<std::uint32_t>(bitId));\n  }\n}\n\nSparseIntVect<std::int32_t> *getAtomPairFingerprint(\n    const ROMol &mol, const std::vector<std::uint32_t> *fromAtoms,\n    const std::vector<std::uint32_t> *ignoreAtoms,\n    const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,\n    bool use2D, int confId) {\n  return getAtomPairFingerprint(mol, 1, maxPathLen - 1, fromAtoms, ignoreAtoms,\n                                atomInvariants, includeChirality, use2D,\n                                confId);\n};\n\nSparseIntVect<std::int32_t> *getAtomPairFingerprint(\n    const ROMol &mol, unsigned int minLength, unsigned int maxLength,\n    const std::vector<std::uint32_t> *fromAtoms,\n    const std::vector<std::uint32_t> *ignoreAtoms,\n    const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,\n    bool use2D, int confId) {\n  PRECONDITION(minLength <= maxLength, \"bad lengths provided\");\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n\n  const ROMol *lmol = &mol;\n  std::unique_ptr<ROMol> tmol;\n  if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {\n    tmol = std::unique_ptr<ROMol>(new ROMol(mol));\n    MolOps::assignStereochemistry(*tmol);\n    lmol = tmol.get();\n  }\n\n  auto *res = new SparseIntVect<std::int32_t>(\n      1 << (numAtomPairFingerprintBits + 2 * (includeChirality ? 2 : 0)));\n  const double *dm;\n  if (use2D) {\n    dm = MolOps::getDistanceMat(*lmol);\n  } else {\n    dm = MolOps::get3DDistanceMat(*lmol, confId);\n  }\n  const unsigned int nAtoms = lmol->getNumAtoms();\n\n  std::vector<std::uint32_t> atomCodes;\n  for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();\n       atomItI != lmol->endAtoms(); ++atomItI) {\n    if (!atomInvariants) {\n      atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));\n    } else {\n      atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()] %\n                          ((1 << codeSize) - 1));\n    }\n  }\n\n  for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();\n       atomItI != lmol->endAtoms(); ++atomItI) {\n    unsigned int i = (*atomItI)->getIdx();\n    if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=\n                           ignoreAtoms->end()) {\n      continue;\n    }\n    if (!fromAtoms) {\n      for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;\n           atomItJ != lmol->endAtoms(); ++atomItJ) {\n        unsigned int j = (*atomItJ)->getIdx();\n        if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),\n                                     j) != ignoreAtoms->end()) {\n          continue;\n        }\n        setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,\n                       includeChirality);\n      }\n    } else {\n      BOOST_FOREACH (std::uint32_t j, *fromAtoms) {\n        if (j != i) {\n          if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),\n                                       j) != ignoreAtoms->end()) {\n            continue;\n          }\n          setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,\n                         includeChirality);\n        }\n      }\n    }\n  }\n  return res;\n}\n\nSparseIntVect<std::int32_t> *getHashedAtomPairFingerprint(\n    const ROMol &mol, unsigned int nBits, unsigned int minLength,\n    unsigned int maxLength, const std::vector<std::uint32_t> *fromAtoms,\n    const std::vector<std::uint32_t> *ignoreAtoms,\n    const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,\n    bool use2D, int confId) {\n  PRECONDITION(minLength <= maxLength, \"bad lengths provided\");\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  const ROMol *lmol = &mol;\n  std::unique_ptr<ROMol> tmol;\n  if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {\n    tmol = std::unique_ptr<ROMol>(new ROMol(mol));\n    MolOps::assignStereochemistry(*tmol);\n    lmol = tmol.get();\n  }\n  auto *res = new SparseIntVect<std::int32_t>(nBits);\n  const double *dm;\n  try {\n    if (use2D) {\n      dm = MolOps::getDistanceMat(*lmol);\n    } else {\n      dm = MolOps::get3DDistanceMat(*lmol, confId);\n    }\n  } catch (const ConformerException &) {\n    delete res;\n    throw;\n  }\n\n  const unsigned int nAtoms = lmol->getNumAtoms();\n\n  std::vector<std::uint32_t> atomCodes;\n  atomCodes.reserve(nAtoms);\n  for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();\n       atomItI != lmol->endAtoms(); ++atomItI) {\n    if (!atomInvariants) {\n      atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));\n    } else {\n      atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()]);\n    }\n  }\n\n  for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();\n       atomItI != lmol->endAtoms(); ++atomItI) {\n    unsigned int i = (*atomItI)->getIdx();\n    if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=\n                           ignoreAtoms->end()) {\n      continue;\n    }\n    if (!fromAtoms) {\n      for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;\n           atomItJ != lmol->endAtoms(); ++atomItJ) {\n        unsigned int j = (*atomItJ)->getIdx();\n        if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),\n                                     j) != ignoreAtoms->end()) {\n          continue;\n        }\n        auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));\n        if (dist >= minLength && dist <= maxLength) {\n          std::uint32_t bit = 0;\n          gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));\n          gboost::hash_combine(bit, dist);\n          gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));\n          updateElement(*res, static_cast<std::int32_t>(bit % nBits));\n        }\n      }\n    } else {\n      BOOST_FOREACH (std::uint32_t j, *fromAtoms) {\n        if (j != i) {\n          if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),\n                                       j) != ignoreAtoms->end()) {\n            continue;\n          }\n          auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));\n          if (dist >= minLength && dist <= maxLength) {\n            std::uint32_t bit = 0;\n            gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));\n            gboost::hash_combine(bit, dist);\n            gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));\n            updateElement(*res, static_cast<std::int32_t>(bit % nBits));\n          }\n        }\n      }\n    }\n  }\n  return res;\n}\n\nExplicitBitVect *getHashedAtomPairFingerprintAsBitVect(\n    const ROMol &mol, unsigned int nBits, unsigned int minLength,\n    unsigned int maxLength, const std::vector<std::uint32_t> *fromAtoms,\n    const std::vector<std::uint32_t> *ignoreAtoms,\n    const std::vector<std::uint32_t> *atomInvariants,\n    unsigned int nBitsPerEntry, bool includeChirality, bool use2D, int confId) {\n  PRECONDITION(minLength <= maxLength, \"bad lengths provided\");\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  static int bounds[4] = {1, 2, 4, 8};\n\n  unsigned int blockLength = nBits / nBitsPerEntry;\n  SparseIntVect<std::int32_t> *sres = getHashedAtomPairFingerprint(\n      mol, blockLength, minLength, maxLength, fromAtoms, ignoreAtoms,\n      atomInvariants, includeChirality, use2D, confId);\n  auto *res = new ExplicitBitVect(nBits);\n  if (nBitsPerEntry != 4) {\n    BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,\n                   sres->getNonzeroElements()) {\n      for (unsigned int i = 0; i < nBitsPerEntry; ++i) {\n        if (val.second > static_cast<int>(i)) {\n          res->setBit(val.first * nBitsPerEntry + i);\n        }\n      }\n    }\n  } else {\n    BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,\n                   sres->getNonzeroElements()) {\n      for (unsigned int i = 0; i < nBitsPerEntry; ++i) {\n        if (val.second >= bounds[i]) {\n          res->setBit(val.first * nBitsPerEntry + i);\n        }\n      }\n    }\n  }\n  delete sres;\n  return res;\n}\n\nSparseIntVect<boost::int64_t> *getTopologicalTorsionFingerprint(\n    const ROMol &mol, unsigned int targetSize,\n    const std::vector<std::uint32_t> *fromAtoms,\n    const std::vector<std::uint32_t> *ignoreAtoms,\n    const std::vector<std::uint32_t> *atomInvariants, bool includeChirality) {\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  const ROMol *lmol = &mol;\n  std::unique_ptr<ROMol> tmol;\n  if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {\n    tmol = std::unique_ptr<ROMol>(new ROMol(mol));\n    MolOps::assignStereochemistry(*tmol);\n    lmol = tmol.get();\n  }\n  boost::uint64_t sz = 1;\n  sz = (sz << (targetSize *\n               (codeSize + (includeChirality ? numChiralBits : 0))));\n  // NOTE: this -1 is incorrect but it's needed for backwards compatibility.\n  //  hopefully we'll never have a case with a torsion that hits this.\n  //\n  //  mmm, bug compatible.\n  sz -= 1;\n  auto *res = new SparseIntVect<boost::int64_t>(sz);\n\n  std::vector<std::uint32_t> atomCodes;\n  atomCodes.reserve(lmol->getNumAtoms());\n  for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();\n       atomItI != lmol->endAtoms(); ++atomItI) {\n    if (!atomInvariants) {\n      atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));\n    } else {\n      // need to add to the atomCode here because we subtract off up to 2 below\n      // as part of the branch correction\n      atomCodes.push_back(\n          (*atomInvariants)[(*atomItI)->getIdx()] % ((1 << codeSize) - 1) + 2);\n    }\n  }\n\n  boost::dynamic_bitset<> *fromAtomsBV = nullptr;\n  if (fromAtoms) {\n    fromAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());\n    BOOST_FOREACH (std::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }\n  }\n  boost::dynamic_bitset<> *ignoreAtomsBV = nullptr;\n  if (ignoreAtoms) {\n    ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());\n    BOOST_FOREACH (std::uint32_t fAt, *ignoreAtoms) {\n      ignoreAtomsBV->set(fAt);\n    }\n  }\n  boost::dynamic_bitset<> pAtoms(lmol->getNumAtoms());\n  PATH_LIST paths = findAllPathsOfLengthN(*lmol, targetSize, false);\n  for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();\n       ++pathIt) {\n    bool keepIt = true;\n    if (fromAtomsBV) {\n      keepIt = false;\n    }\n    std::vector<std::uint32_t> pathCodes;\n    const PATH_TYPE &path = *pathIt;\n    if (fromAtomsBV) {\n      if (fromAtomsBV->test(static_cast<std::uint32_t>(path.front())) ||\n          fromAtomsBV->test(static_cast<std::uint32_t>(path.back()))) {\n        keepIt = true;\n      }\n    }\n    if (keepIt && ignoreAtomsBV) {\n      BOOST_FOREACH (int pElem, path) {\n        if (ignoreAtomsBV->test(pElem)) {\n          keepIt = false;\n          break;\n        }\n      }\n    }\n    if (keepIt) {\n      pAtoms.reset();\n      for (auto pIt = path.begin(); pIt < path.end(); ++pIt) {\n        // look for a cycle that doesn't start at the first atom\n        // we can't effectively canonicalize these at the moment\n        // (was github #811)\n        if (pIt != path.begin() && *pIt != *(path.begin()) && pAtoms[*pIt]) {\n          pathCodes.clear();\n          break;\n        }\n        pAtoms.set(*pIt);\n        unsigned int code = atomCodes[*pIt] - 1;\n        // subtract off the branching number:\n        if (pIt != path.begin() && pIt + 1 != path.end()) {\n          --code;\n        }\n        pathCodes.push_back(code);\n      }\n      if (pathCodes.size()) {\n        boost::int64_t code =\n            getTopologicalTorsionCode(pathCodes, includeChirality);\n        updateElement(*res, code);\n      }\n    }\n  }\n  delete fromAtomsBV;\n  delete ignoreAtomsBV;\n\n  return res;\n}\n\nnamespace {\ntemplate <typename T>\nvoid TorsionFpCalc(T *res, const ROMol &mol, unsigned int nBits,\n                   unsigned int targetSize,\n                   const std::vector<std::uint32_t> *fromAtoms,\n                   const std::vector<std::uint32_t> *ignoreAtoms,\n                   const std::vector<std::uint32_t> *atomInvariants,\n                   bool includeChirality) {\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  const ROMol *lmol = &mol;\n  std::unique_ptr<ROMol> tmol;\n  if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {\n    tmol = std::unique_ptr<ROMol>(new ROMol(mol));\n    MolOps::assignStereochemistry(*tmol);\n    lmol = tmol.get();\n  }\n  std::vector<std::uint32_t> atomCodes;\n  atomCodes.reserve(lmol->getNumAtoms());\n  for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();\n       atomItI != lmol->endAtoms(); ++atomItI) {\n    if (!atomInvariants) {\n      atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));\n    } else {\n      // need to add to the atomCode here because we subtract off up to 2 below\n      // as part of the branch correction\n      atomCodes.push_back(((*atomInvariants)[(*atomItI)->getIdx()] << 1) + 1);\n    }\n  }\n\n  boost::dynamic_bitset<> *fromAtomsBV = nullptr;\n  if (fromAtoms) {\n    fromAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());\n    BOOST_FOREACH (std::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }\n  }\n  boost::dynamic_bitset<> *ignoreAtomsBV = nullptr;\n  if (ignoreAtoms) {\n    ignoreAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());\n    BOOST_FOREACH (std::uint32_t fAt, *ignoreAtoms) {\n      ignoreAtomsBV->set(fAt);\n    }\n  }\n\n  PATH_LIST paths = findAllPathsOfLengthN(*lmol, targetSize, false);\n  for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();\n       ++pathIt) {\n    bool keepIt = true;\n    if (fromAtomsBV) {\n      keepIt = false;\n    }\n    const PATH_TYPE &path = *pathIt;\n    if (fromAtomsBV) {\n      if (fromAtomsBV->test(static_cast<std::uint32_t>(path.front())) ||\n          fromAtomsBV->test(static_cast<std::uint32_t>(path.back()))) {\n        keepIt = true;\n      }\n    }\n    if (keepIt && ignoreAtomsBV) {\n      BOOST_FOREACH (int pElem, path) {\n        if (ignoreAtomsBV->test(pElem)) {\n          keepIt = false;\n          break;\n        }\n      }\n    }\n    if (keepIt) {\n      std::vector<std::uint32_t> pathCodes(targetSize);\n      for (unsigned int i = 0; i < targetSize; ++i) {\n        unsigned int code = atomCodes[path[i]] - 1;\n        // subtract off the branching number:\n        if (i > 0 && i < targetSize - 1) {\n          --code;\n        }\n        pathCodes[i] = code;\n      }\n      size_t bit = getTopologicalTorsionHash(pathCodes);\n      updateElement(*res, bit % nBits);\n    }\n  }\n  delete fromAtomsBV;\n  delete ignoreAtomsBV;\n}\n}  // namespace\nSparseIntVect<boost::int64_t> *getHashedTopologicalTorsionFingerprint(\n    const ROMol &mol, unsigned int nBits, unsigned int targetSize,\n    const std::vector<std::uint32_t> *fromAtoms,\n    const std::vector<std::uint32_t> *ignoreAtoms,\n    const std::vector<std::uint32_t> *atomInvariants, bool includeChirality) {\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  auto *res = new SparseIntVect<boost::int64_t>(nBits);\n  TorsionFpCalc(res, mol, nBits, targetSize, fromAtoms, ignoreAtoms,\n                atomInvariants, includeChirality);\n  return res;\n}\n\nExplicitBitVect *getHashedTopologicalTorsionFingerprintAsBitVect(\n    const ROMol &mol, unsigned int nBits, unsigned int targetSize,\n    const std::vector<std::uint32_t> *fromAtoms,\n    const std::vector<std::uint32_t> *ignoreAtoms,\n    const std::vector<std::uint32_t> *atomInvariants,\n    unsigned int nBitsPerEntry, bool includeChirality) {\n  PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),\n               \"bad atomInvariants size\");\n  static int bounds[4] = {1, 2, 4, 8};\n  unsigned int blockLength = nBits / nBitsPerEntry;\n  auto *sres = new SparseIntVect<boost::int64_t>(blockLength);\n  TorsionFpCalc(sres, mol, blockLength, targetSize, fromAtoms, ignoreAtoms,\n                atomInvariants, includeChirality);\n  auto *res = new ExplicitBitVect(nBits);\n\n  if (nBitsPerEntry != 4) {\n    BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,\n                   sres->getNonzeroElements()) {\n      for (unsigned int i = 0; i < nBitsPerEntry; ++i) {\n        if (val.second > static_cast<int>(i)) {\n          res->setBit(val.first * nBitsPerEntry + i);\n        }\n      }\n    }\n  } else {\n    BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,\n                   sres->getNonzeroElements()) {\n      for (unsigned int i = 0; i < nBitsPerEntry; ++i) {\n        if (val.second >= bounds[i]) {\n          res->setBit(val.first * nBitsPerEntry + i);\n        }\n      }\n    }\n  }\n  delete sres;\n  return res;\n}\n}  // end of namespace AtomPairs\n}  // end of namespace RDKit\n", "meta": {"hexsha": "6abca41ee0eab7b863930330842283c3e87d0a4c", "size": 18412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/GraphMol/Fingerprints/AtomPairs.cpp", "max_stars_repo_name": "chcltchunk/rdkit", "max_stars_repo_head_hexsha": "af0ccf686779a8efd9db7c77f0bb3cab718ea2ba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T14:52:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-28T08:12:45.000Z", "max_issues_repo_path": "Code/GraphMol/Fingerprints/AtomPairs.cpp", "max_issues_repo_name": "chcltchunk/rdkit", "max_issues_repo_head_hexsha": "af0ccf686779a8efd9db7c77f0bb3cab718ea2ba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T08:06:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-03T07:04:42.000Z", "max_forks_repo_path": "Code/GraphMol/Fingerprints/AtomPairs.cpp", "max_forks_repo_name": "chcltchunk/rdkit", "max_forks_repo_head_hexsha": "af0ccf686779a8efd9db7c77f0bb3cab718ea2ba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-05-15T12:15:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-15T12:15:35.000Z", "avg_line_length": 36.9718875502, "max_line_length": 80, "alphanum_fraction": 0.620845101, "num_tokens": 5098, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2058587818136443}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n\n#include \"NewtonEulerFrom1DLocalFrameR.hpp\"\n#include <boost/math/quaternion.hpp>\n#include \"NewtonEulerDS.hpp\"\n#include \"Interaction.hpp\"\n#include \"BlockVector.hpp\"\n\n//#define NERI_DEBUG\n\n\n\n\n//#define NEFC3D_DEBUG\n// #define DEBUG_NOCOLOR\n// #define DEBUG_STDOUT\n// #define DEBUG_MESSAGES\n#include \"debug.h\"\n/*\nSee devNotes.pdf for details. A detailed documentation is available in DevNotes.pdf: chapter 'NewtonEulerR: computation of \\nabla q H'. Subsection 'Case FC3D: using the local frame local velocities'\n*/\nvoid NewtonEulerFrom1DLocalFrameR::NIcomputeJachqTFromContacts(SP::SiconosVector q1)\n{\n  double Nx = _Nc->getValue(0);\n  double Ny = _Nc->getValue(1);\n  double Nz = _Nc->getValue(2);\n  double Px = _Pc1->getValue(0);\n  double Py = _Pc1->getValue(1);\n  double Pz = _Pc1->getValue(2);\n  double G1x = q1->getValue(0);\n  double G1y = q1->getValue(1);\n  double G1z = q1->getValue(2);\n#ifdef NEFC3D_DEBUG\n  printf(\"contact normal:\\n\");\n  _Nc->display();\n  printf(\"point de contact :\\n\");\n  _Pc1->display();\n  printf(\"center of masse :\\n\");\n  q1->display();\n#endif\n  _Mabs_C->setValue(0, 0, Nx);\n  _Mabs_C->setValue(0, 1, Ny);\n  _Mabs_C->setValue(0, 2, Nz);\n\n  _NPG1->zero();\n\n  (*_NPG1)(0, 0) = 0;\n  (*_NPG1)(0, 1) = -(G1z - Pz);\n  (*_NPG1)(0, 2) = (G1y - Py);\n  (*_NPG1)(1, 0) = (G1z - Pz);\n  (*_NPG1)(1, 1) = 0;\n  (*_NPG1)(1, 2) = -(G1x - Px);\n  (*_NPG1)(2, 0) = -(G1y - Py);\n  (*_NPG1)(2, 1) = (G1x - Px);\n  (*_NPG1)(2, 2) = 0;\n\n\n  //d1->computeMObjToAbs();\n  //SimpleMatrix& Mobj1_abs = *d1->MObjToAbs();\n  computeMObjToAbs(q1,_MObjToAbs);\n\n\n  prod(*_NPG1, *_MObjToAbs, *_AUX1, true);\n  prod(*_Mabs_C, *_AUX1, *_AUX2, true);\n\n\n  for (unsigned int jj = 0; jj < 3; jj++)\n    _jachqT->setValue(0, jj, _Mabs_C->getValue(0, jj));\n\n  for (unsigned int jj = 3; jj < 6; jj++)\n    _jachqT->setValue(0, jj, _AUX2->getValue(0, jj - 3));\n\n#ifdef NEFC3D_DEBUG\n  printf(\"NewtonEulerFrom1DLocalFrameR jhqt\\n\");\n  _jachqT->display();\n#endif\n}\n\nvoid NewtonEulerFrom1DLocalFrameR::NIcomputeJachqTFromContacts(SP::SiconosVector q1, SP::SiconosVector q2)\n{\n  double Nx = _Nc->getValue(0);\n  double Ny = _Nc->getValue(1);\n  double Nz = _Nc->getValue(2);\n  double Px = _Pc1->getValue(0);\n  double Py = _Pc1->getValue(1);\n  double Pz = _Pc1->getValue(2);\n  double G1x = q1->getValue(0);\n  double G1y = q1->getValue(1);\n  double G1z = q1->getValue(2);\n\n  _Mabs_C->setValue(0, 0, Nx);\n  _Mabs_C->setValue(0, 1, Ny);\n  _Mabs_C->setValue(0, 2, Nz);\n\n  _NPG1->zero();\n\n  (*_NPG1)(0, 0) = 0;\n  (*_NPG1)(0, 1) = -(G1z - Pz);\n  (*_NPG1)(0, 2) = (G1y - Py);\n  (*_NPG1)(1, 0) = (G1z - Pz);\n  (*_NPG1)(1, 1) = 0;\n  (*_NPG1)(1, 2) = -(G1x - Px);\n  (*_NPG1)(2, 0) = -(G1y - Py);\n  (*_NPG1)(2, 1) = (G1x - Px);\n  (*_NPG1)(2, 2) = 0;\n\n//  d1->computeMObjToAbs();\n//  SimpleMatrix& Mobj1_abs = *d1->MObjToAbs();\n\n  computeMObjToAbs(q1,_MObjToAbs);\n\n  prod(*_NPG1, *_MObjToAbs, *_AUX1, true);\n  prod(*_Mabs_C, *_AUX1, *_AUX2, true);\n\n  for (unsigned int jj = 0; jj < 3; jj++)\n    _jachqT->setValue(0, jj, _Mabs_C->getValue(0, jj));\n\n\n  for (unsigned int jj = 3; jj < 6; jj++)\n    _jachqT->setValue(0, jj, _AUX2->getValue(0, jj - 3));\n\n  double G2x = q2->getValue(0);\n  double G2y = q2->getValue(1);\n  double G2z = q2->getValue(2);\n\n  _NPG2->zero();\n  (*_NPG2)(0, 0) = 0;\n  (*_NPG2)(0, 1) = -(G2z - Pz);\n  (*_NPG2)(0, 2) = (G2y - Py);\n  (*_NPG2)(1, 0) = (G2z - Pz);\n  (*_NPG2)(1, 1) = 0;\n  (*_NPG2)(1, 2) = -(G2x - Px);\n  (*_NPG2)(2, 0) = -(G2y - Py);\n  (*_NPG2)(2, 1) = (G2x - Px);\n  (*_NPG2)(2, 2) = 0;\n\n//  d2->computeMObjToAbs();\n//  SimpleMatrix& Mobj2_abs = *d2->MObjToAbs();\n\n  computeMObjToAbs(q2,_MObjToAbs);\n  prod(*_NPG2, *_MObjToAbs, *_AUX1, true);\n  prod(*_Mabs_C, *_AUX1, *_AUX2, true);\n\n  for (unsigned int jj = 0; jj < 3; jj++)\n    _jachqT->setValue(0, jj + 6, -_Mabs_C->getValue(0, jj));\n\n  for (unsigned int jj = 3; jj < 6; jj++)\n    _jachqT->setValue(0, jj + 6, -_AUX2->getValue(0, jj - 3));\n}\n\nvoid NewtonEulerFrom1DLocalFrameR::initComponents(Interaction& inter, VectorOfBlockVectors& DSlink, VectorOfVectors& workV, VectorOfSMatrices& workM)\n{\n  NewtonEulerR::initComponents(inter, DSlink, workV, workM);\n  //proj_with_q  _jachqProj.reset(new SimpleMatrix(_jachq->size(0),_jachq->size(1)));\n  unsigned int qSize = 7 * (inter.getSizeOfDS() / 6);\n  _jachq.reset(new SimpleMatrix(1, qSize));\n\n\n\n  /* VA 12/04/2016 All of what follows should be put in WorkM*/\n  _Mabs_C.reset(new SimpleMatrix(1, 3));\n  _MObjToAbs.reset(new SimpleMatrix(3, 3));\n  _AUX1.reset(new SimpleMatrix(3, 3));\n  _AUX2.reset(new SimpleMatrix(1, 3));\n  _NPG1.reset(new SimpleMatrix(3, 3));\n  _NPG2.reset(new SimpleMatrix(3, 3));\n  //  _isContact=1;\n}\n\nvoid NewtonEulerFrom1DLocalFrameR::computeJachq(double time, Interaction& inter, SP::BlockVector q0)\n{\n\n  DEBUG_BEGIN(\"NewtonEulerFrom1DLocalFrameR::computeJachq(double time, Interaction& inter, SP::BlockVector q0 ) \\n\");\n  DEBUG_PRINTF(\"with time =  %f\\n\",time);\n  DEBUG_PRINTF(\"with inter =  %p\\n\",&inter);\n\n\n  _jachq->setValue(0, 0, _Nc->getValue(0));\n  _jachq->setValue(0, 1, _Nc->getValue(1));\n  _jachq->setValue(0, 2, _Nc->getValue(2));\n  if (inter.has2Bodies())\n  {\n    _jachq->setValue(0, 7, -_Nc->getValue(0));\n    _jachq->setValue(0, 8, -_Nc->getValue(1));\n    _jachq->setValue(0, 9, -_Nc->getValue(2));\n  }\n\n  for (unsigned int iDS =0 ; iDS < q0->getNumberOfBlocks()  ; iDS++)\n  {\n    SP::SiconosVector q = (q0->getAllVect())[iDS];\n    double sign = 1.0;\n    DEBUG_PRINTF(\"NewtonEulerFrom1DLocalFrameR::computeJachq : ds%d->q :\", iDS);\n    DEBUG_EXPR_WE(q->display(););\n\n    ::boost::math::quaternion<double>    quatGP;\n    if (iDS == 0)\n    {\n      ::boost::math::quaternion<double>    quatAux(0, _Pc1->getValue(0) - q->getValue(0), _Pc1->getValue(1) - q->getValue(1),\n                                                   _Pc1->getValue(2) - q->getValue(2));\n      quatGP = quatAux;\n    }\n    else\n    {\n      sign = -1.0;\n      //cout<<\"NewtonEulerFrom1DLocalFrameR::computeJachq sign is -1 \\n\";\n      ::boost::math::quaternion<double>    quatAux(0, _Pc2->getValue(0) - q->getValue(0), _Pc2->getValue(1) - q->getValue(1),\n                                                   _Pc2->getValue(2) - q->getValue(2));\n      quatGP = quatAux;\n    }\n    DEBUG_PRINTF(\"NewtonEulerFrom1DLocalFrameR::computeJachq :GP :%lf, %lf, %lf\\n\", quatGP.R_component_2(), quatGP.R_component_3(), quatGP.R_component_4());\n    DEBUG_PRINTF(\"NewtonEulerFrom1DLocalFrameR::computeJachq :Q :%e,%e, %e, %e\\n\", q->getValue(3), q->getValue(4), q->getValue(5), q->getValue(6));\n    ::boost::math::quaternion<double>    quatQ(q->getValue(3), q->getValue(4), q->getValue(5), q->getValue(6));\n    ::boost::math::quaternion<double>    quatcQ(q->getValue(3), -q->getValue(4), -q->getValue(5), -q->getValue(6));\n    ::boost::math::quaternion<double>    quat0(1, 0, 0, 0);\n    ::boost::math::quaternion<double>    quatBuff;\n    ::boost::math::quaternion<double>    _2qiquatGP;\n    _2qiquatGP = quatGP;\n    _2qiquatGP *= 2 * (q->getValue(3));\n    quatBuff = (quatGP * quatQ) + (quatcQ * quatGP) - _2qiquatGP;\n\n    DEBUG_PRINTF(\"NewtonEulerFrom1DLocalFrameR::computeJachq :quattBuuf : %e,%e,%e \\n\", quatBuff.R_component_2(), quatBuff.R_component_3(), quatBuff.R_component_4());\n\n    _jachq->setValue(0, 7 * iDS + 3, sign * (quatBuff.R_component_2()*_Nc->getValue(0) +\n                                             quatBuff.R_component_3()*_Nc->getValue(1) + quatBuff.R_component_4()*_Nc->getValue(2)));\n    //cout<<\"WARNING NewtonEulerFrom1DLocalFrameR set jachq \\n\";\n    //_jachq->setValue(0,7*iDS+3,0);\n    for (unsigned int i = 1; i < 4; i++)\n    {\n      ::boost::math::quaternion<double>    quatei(0, (i == 1) ? 1 : 0, (i == 2) ? 1 : 0, (i == 3) ? 1 : 0);\n      _2qiquatGP = quatGP;\n      _2qiquatGP *= 2 * (q->getValue(3 + i));\n      quatBuff = quatei * quatcQ * quatGP - quatGP * quatQ * quatei - _2qiquatGP;\n      _jachq->setValue(0, 7 * iDS + 3 + i, sign * (quatBuff.R_component_2()*_Nc->getValue(0) +\n                                                   quatBuff.R_component_3()*_Nc->getValue(1) + quatBuff.R_component_4()*_Nc->getValue(2)));\n    }\n  }\n\n  DEBUG_EXPR(_jachq->display(););\n  DEBUG_END(\"NewtonEulerFrom1DLocalFrameR::computeJachq(double time, Interaction& inter, SP::BlockVector q0 \\n\");\n\n}\n\nvoid NewtonEulerFrom1DLocalFrameR::computeJachqT(Interaction& inter, SP::BlockVector q0 )\n{\n  DEBUG_BEGIN(\"NewtonEulerFrom1DLocalFrameR::computeJachqT(Interaction& inter, SP::BlockVector q0 \\n\")\n    \n  if (q0->getNumberOfBlocks()>1)\n  {\n    NIcomputeJachqTFromContacts((q0->getAllVect())[0], (q0->getAllVect())[1]);\n  }\n  else\n  {\n    NIcomputeJachqTFromContacts((q0->getAllVect())[0]);\n  }\n\n  DEBUG_END(\"NewtonEulerFrom1DLocalFrameR::computeJachqT(Interaction& inter, SP::BlockVector q0) \\n\");\n\n}\n", "meta": {"hexsha": "1df34f53ccf57e20ab66bec1441f71c88528b677", "size": 9382, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/modelingTools/NewtonEulerFrom1DLocalFrameR.cpp", "max_stars_repo_name": "siconos/siconos-deb", "max_stars_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/modelingTools/NewtonEulerFrom1DLocalFrameR.cpp", "max_issues_repo_name": "siconos/siconos-deb", "max_issues_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/modelingTools/NewtonEulerFrom1DLocalFrameR.cpp", "max_forks_repo_name": "siconos/siconos-deb", "max_forks_repo_head_hexsha": "2739a23f23d797dbfecec79d409e914e13c45c67", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.9927536232, "max_line_length": 198, "alphanum_fraction": 0.6306757621, "num_tokens": 3533, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073802837478, "lm_q2_score": 0.37387580881868493, "lm_q1q2_score": 0.20585877964512345}}
{"text": "#pragma once\n\n/*\nGame Tree Search Algorithms\nCopyright (C) Adam Stelmaszczyk <stelmaszczyk.adam@gmail.com>\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <boost/math/distributions/binomial.hpp>\n#include <unordered_map>\n#include <unordered_set>\n#include <sys/time.h>\n#include <algorithm>\n#include <iostream>\n#include <assert.h>\n#include <fstream>\n#include <sstream>\n#include <iomanip>\n#include <memory>\n#include <random>\n#include <vector>\n\nusing namespace std;\n\nstatic const int MAX_SIMULATIONS = 10000000;\nstatic const double UCT_C = sqrt(2);\nstatic const double WIN_SCORE = 1;\nstatic const double DRAW_SCORE = 0.5;\nstatic const double LOSE_SCORE = 0;\n\nstatic const int MAX_DEPTH = 20;\nstatic const int INF = 2147483647;\n\nstruct Random {\n\n    virtual ~Random() {}\n\n    int uniform(int min, int max) const {\n        mt19937 engine;\n        uniform_int_distribution<int> distribution(min, max);\n        return distribution(engine);\n    }\n};\n\nstruct Timer {\n    double start_time;\n\n    virtual ~Timer() {}\n\n    void start() {\n        start_time = get_time();\n    }\n\n    double get_time() const {\n        timeval tv;\n        gettimeofday(&tv, 0);\n        return tv.tv_sec + tv.tv_usec * 1e-6;\n    }\n\n    double seconds_elapsed() const {\n        return get_time() - start_time;\n    }\n\n    bool exceeded(double seconds) const {\n        return seconds_elapsed() > seconds;\n    }\n\n    friend ostream &operator<<(ostream &os, const Timer &timer) {\n        return os << setprecision(2) << fixed << timer.seconds_elapsed() << \"s\";\n    }\n};\n\ntemplate<class M>\nstruct Move {\n    virtual ~Move() {}\n\n    virtual void read(istream &stream) = 0;\n\n    virtual ostream &to_stream(ostream &os) const = 0;\n\n    friend ostream &operator<<(ostream &os, const Move &move) {\n        return move.to_stream(os);\n    }\n\n    virtual bool operator==(const M &rhs) const = 0;\n\n    virtual size_t hash() const = 0;\n};\n\nenum TTEntryType { EXACT_VALUE, LOWER_BOUND, UPPER_BOUND };\n\ntemplate<class M>\nstruct TTEntry {\n    M move;\n    int depth;\n    int value;\n    TTEntryType value_type;\n\n    TTEntry() {}\n\n    virtual ~TTEntry() {}\n\n    TTEntry(const M &move, int depth, int value, TTEntryType value_type) :\n            move(move), depth(depth), value(value), value_type(value_type) {}\n\n    ostream &to_stream(ostream &os) {\n        return os << \"move: \" << move << \" depth: \" << depth << \" value: \" << value << \" value_type: \" << value_type;\n    }\n\n    friend ostream &operator<<(ostream &os, const TTEntry &entry) {\n        return entry.to_stream(os);\n    }\n};\n\ntemplate<class S, class M>\nstruct State {\n    unsigned visits = 0;\n    double score = 0;\n    char player_to_move = 0;\n    S *parent = nullptr;\n    unordered_map<size_t, shared_ptr<S>> children = unordered_map<size_t, shared_ptr<S>>();\n\n    State(char player_to_move) : player_to_move(player_to_move) {}\n\n    virtual ~State() {}\n\n    void update_stats(double result) {\n        score += result;\n        ++visits;\n    }\n\n    double get_uct(double c) const {\n        assert(visits > 0);\n        double parent_visits = 0.0;\n        if (parent != nullptr) {\n            parent_visits = parent->visits;\n        }\n        return score / visits + c * sqrt(log(parent_visits) / visits);\n    }\n\n    shared_ptr<S> create_child(const M &move) {\n        S child = clone();\n        child.make_move(move);\n        child.parent = (S*) this;\n        return make_shared<S>(child);\n    }\n\n    S* add_child(const M &move) {\n        const auto child = create_child(move);\n        const auto key = move.hash();\n        const auto pair = children.insert({key, child});\n        const auto it = pair.first;\n        return it->second.get();\n    }\n\n    S* get_child(const M &move) const {\n        const auto key = move.hash();\n        const auto it = children.find(key);\n        if (it == children.end()) {\n            return nullptr;\n        }\n        return it->second.get();\n    }\n\n    virtual string to_executable_format() const {\n        stringstream ss;\n        ss << *this;\n        return ss.str();\n    }\n\n    virtual void swap_players() {}\n\n    virtual S clone() const = 0;\n\n    virtual int get_goodness() const = 0;\n\n    virtual vector<M> get_legal_moves(int max_moves) const = 0;\n\n    virtual char get_enemy(char player) const = 0;\n\n    virtual bool is_terminal() const = 0;\n\n    virtual bool is_winner(char player) const = 0;\n\n    virtual void make_move(const M &move) = 0;\n\n    virtual void undo_move(const M &move) = 0;\n\n    virtual ostream &to_stream(ostream &os) const = 0;\n\n    friend ostream &operator<<(ostream &os, const State &state) {\n        return state.to_stream(os);\n    }\n\n    virtual bool operator==(const S &other) const = 0;\n\n    virtual size_t hash() const = 0;\n};\n\ntemplate<class S, class M>\nstruct Algorithm {\n\n    stringstream log;\n\n    Algorithm() { }\n\n    Algorithm(const Algorithm& algorithm) {}\n\n    virtual ~Algorithm() {}\n\n    string read_log() {\n        string result = log.str();\n        log.str(\"\");\n        return result;\n    }\n\n    virtual void reset() {}\n\n    virtual M get_move(const S *state) = 0;\n\n    virtual string get_name() const = 0;\n\n    friend ostream &operator<<(ostream &os, const Algorithm &algorithm) {\n        os << algorithm.get_name();\n        return os;\n    }\n};\n\ntemplate<class S, class M>\nstruct Human : public Algorithm<S, M> {\n\n    Human() : Algorithm<S, M>() {}\n\n    M get_move(const S *state) override {\n        const vector<M> &legal_moves = state->get_legal_moves();\n        if (legal_moves.empty()) {\n            stringstream stream;\n            state->to_stream(stream);\n            throw invalid_argument(\"Given state is terminal:\\n\" + stream.str());\n        }\n        while (true) {\n            M move = M();\n            move.read();\n            if (find(legal_moves.begin(), legal_moves.end(), move) != legal_moves.end()) {\n                return move;\n            } else {\n                cout << \"Move \" << move << \" is not legal\" << endl;\n            }\n        }\n    }\n\n    string get_name() const {\n        return \"Human\";\n    }\n};\n\ntemplate<class S, class M>\nstruct Executable : public Algorithm<S, M> {\n\n    const string executable;\n\n    Executable(string executable) : Algorithm<S, M>(), executable(executable) {}\n\n    M get_move(const S *state) override {\n        const vector<M> &legal_moves = state->get_legal_moves();\n        if (legal_moves.empty()) {\n            stringstream stream;\n            state->to_stream(stream);\n            throw invalid_argument(\"Given state is terminal:\\n\" + stream.str());\n        }\n\n        stringstream cmd;\n        cmd << \"echo \\\"\" << state->to_executable_format() << \"\\\" | \" << executable;\n\n        const string output = run_cmd(cmd.str());\n        stringstream stream_to_read(output);\n\n        M move = M();\n        move.read(stream_to_read);\n        if (find(legal_moves.begin(), legal_moves.end(), move) != legal_moves.end()) {\n            return move;\n        } else {\n            stringstream message;\n            message << \"Legal moves: \";\n            for (auto move : legal_moves) {\n                message << move << \", \";\n            }\n            message << endl;\n            message << \"Move \" << move << \" is not legal, state:\" << endl;\n            message << *state;\n            throw runtime_error(message.str());\n        }\n    }\n\n    string run_cmd(string cmd) {\n        stringstream result;\n        const int BUFFER_SIZE = 128;\n        char buffer[BUFFER_SIZE];\n        shared_ptr<FILE> pipe(popen(cmd.c_str(), \"r\"), pclose);\n        if (!pipe) {\n            throw runtime_error(\"popen() failed\");\n        }\n        while (!feof(pipe.get())) {\n            if (fgets(buffer, BUFFER_SIZE, pipe.get()) != NULL) {\n                result << buffer;\n            }\n        }\n        return result.str();\n    }\n\n    string get_name() const {\n        return \"Executable \" + executable;\n    }\n};\n\ntemplate<class M>\nstruct MinimaxResult {\n    int goodness;\n    M best_move;\n    bool completed;\n};\n\ntemplate<class S, class M>\nstruct Minimax : public Algorithm<S, M> {\n    unordered_map<size_t, TTEntry<M>> transposition_table;\n    const double MAX_SECONDS;\n    const int MAX_MOVES;\n    function<vector<M>(const S*, int)> get_legal_moves;\n    function<int(const S*)> get_goodness;\n    Timer timer;\n    int scout_cuts;\n    int beta_cuts, cut_bf_sum;\n    int tt_hits, tt_exacts, tt_cuts;\n    int nodes, leafs;\n\n    Minimax(double max_seconds = 1, int max_moves = INF, function<vector<M>(const S*, int)> get_legal_moves = nullptr, function<int(const S*)> get_goodness = nullptr) :\n            Algorithm<S, M>(),\n            transposition_table(unordered_map<size_t, TTEntry<M>>(1000000)),\n            MAX_SECONDS(max_seconds),\n            MAX_MOVES(max_moves),\n            get_legal_moves(get_legal_moves),\n            get_goodness(get_goodness),\n            timer(Timer()) {}\n\n    void reset() {\n        transposition_table.clear();\n    }\n\n    M get_move(const S *state) override {\n        if (state->is_terminal()) {\n            stringstream stream;\n            state->to_stream(stream);\n            throw invalid_argument(\"Given state is terminal:\\n\" + stream.str());\n        }\n        if (get_legal_moves == nullptr) {\n            get_legal_moves = &State<S,M>::get_legal_moves;\n        }\n        if (get_goodness == nullptr) {\n            get_goodness = &State<S,M>::get_goodness;\n        }\n        timer.start();\n\n        const auto moves = get_legal_moves(state, MAX_MOVES);\n        this->log << \"moves: \" << moves.size() << endl;\n        for (const auto move : moves) {\n            this->log << move << \", \";\n        }\n        this->log << endl;\n\n        M best_move;\n        for (int max_depth = 1; max_depth <= MAX_DEPTH; ++max_depth) {\n            scout_cuts = 0;\n            beta_cuts = 0;\n            cut_bf_sum = 0;\n            tt_hits = 0;\n            tt_exacts = 0;\n            tt_cuts = 0;\n            nodes = 0;\n            leafs = 0;\n            S clone = state->clone();\n            auto result = minimax(&clone, max_depth, -INF, INF);\n            if (result.completed) {\n                best_move = result.best_move;\n                this->log << \"goodness: \" << result.goodness\n                << \" time: \" << timer\n                << \" move: \" << best_move\n                << \" nodes: \" << nodes\n                << \" leafs: \" << leafs\n                << \" scout_cuts: \" << scout_cuts\n                << \" beta_cuts: \" << beta_cuts\n                << \" cutBF: \" << (double) cut_bf_sum / beta_cuts\n                << \" tt_hits: \" << tt_hits\n                << \" tt_exacts: \" << tt_exacts\n                << \" tt_cuts: \" << tt_cuts\n                << \" tt_size: \" << transposition_table.size()\n                << \" max_depth: \" << max_depth << endl;\n            }\n            if (timer.exceeded(MAX_SECONDS)) {\n                break;\n            }\n        }\n        return best_move;\n    }\n\n    // Find Minimax value of the given tree,\n    // Minimax value lies within a range of [alpha; beta] window.\n    // Whenever alpha >= beta, further checks of children in a node can be pruned.\n    MinimaxResult<M> minimax(S *state, int depth, int alpha, int beta) {\n        ++nodes;\n        const int alpha_original = alpha;\n\n        M best_move;\n        if (depth == 0 || state->is_terminal()) {\n            ++leafs;\n            return {get_goodness(state), best_move, false};\n        }\n\n        TTEntry<M> entry;\n        const bool entry_found = get_tt_entry(state, entry);\n        if (entry_found && entry.depth >= depth) {\n            ++tt_hits;\n            if (entry.value_type == TTEntryType::EXACT_VALUE) {\n                ++tt_exacts;\n                return {entry.value, entry.move, true};\n            }\n            if (entry.value_type == TTEntryType::LOWER_BOUND && alpha < entry.value) {\n                alpha = entry.value;\n            }\n            if (entry.value_type == TTEntryType::UPPER_BOUND && beta > entry.value) {\n                beta = entry.value;\n            }\n            if (alpha >= beta) {\n                ++tt_cuts;\n                return {entry.value, entry.move, true};\n            }\n        }\n\n        int max_goodness = -INF;\n\n        bool completed = true;\n        const auto legal_moves = get_legal_moves(state, MAX_MOVES);\n        assert(legal_moves.size() > 0);\n        for (int i = 0; i < legal_moves.size(); i++) {\n            const auto move = legal_moves[i];\n            state->make_move(move);\n            int goodness;\n            if (i > 0) {\n                // null window search\n                goodness = -minimax(\n                    state,\n                    depth - 1,\n                    -alpha - 1,\n                    -alpha\n                ).goodness;\n                if (alpha < goodness && goodness < beta) {\n                    // failed high, do a full re-search\n                    goodness = -minimax(\n                        state,\n                        depth - 1,\n                        -beta,\n                        -goodness\n                    ).goodness;\n                } else {\n                    scout_cuts++;\n                }\n            }\n            else {\n                goodness = -minimax(\n                    state,\n                    depth - 1,\n                    -beta,\n                    -alpha\n                ).goodness;\n            }\n            state->undo_move(move);\n            if (timer.exceeded(MAX_SECONDS)) {\n                completed = false;\n                break;\n            }\n            if (max_goodness < goodness) {\n                max_goodness = goodness;\n                best_move = move;\n                if (max_goodness >= beta) {\n                    ++beta_cuts;\n                    cut_bf_sum += i + 1;\n                    break;\n                }\n            }\n            if (alpha < max_goodness) {\n                alpha = max_goodness;\n            }\n        }\n\n        if (completed) {\n            update_tt(state, alpha_original, beta, max_goodness, best_move, depth);\n        }\n\n        return {max_goodness, best_move, completed};\n    }\n\n    bool get_tt_entry(const S *state, TTEntry<M> &entry) const {\n        const auto key = state->hash();\n        const auto it = transposition_table.find(key);\n        if (it == transposition_table.end()) {\n            return false;\n        }\n        entry = it->second;\n        return true;\n    }\n\n    void add_tt_entry(const S *state, const TTEntry<M> &entry) {\n        const auto key = state->hash();\n        transposition_table.insert({key, entry});\n    }\n\n    void update_tt(const S *state, int alpha, int beta, int max_goodness, const M &best_move, int depth) {\n        TTEntryType value_type;\n        if (max_goodness <= alpha) {\n            value_type = TTEntryType::UPPER_BOUND;\n        }\n        else if (max_goodness >= beta) {\n            value_type = TTEntryType::LOWER_BOUND;\n        }\n        else {\n            value_type = TTEntryType::EXACT_VALUE;\n        }\n        const TTEntry<M> entry = {best_move, depth, max_goodness, value_type};\n        add_tt_entry(state, entry);\n    }\n\n    string get_name() const {\n        return \"Minimax\";\n    }\n};\n\ntemplate<class S, class M>\nstruct MonteCarloTreeSearch : public Algorithm<S, M> {\n    const double max_seconds;\n    const int max_simulations;\n    const bool block;\n    const Random random;\n\n    MonteCarloTreeSearch(double max_seconds = 1,\n                         int max_simulations = MAX_SIMULATIONS,\n                         bool block = false) :\n        Algorithm<S, M>(),\n        max_seconds(max_seconds),\n        block(block),\n        max_simulations(max_simulations) {}\n\n    M get_move(const S *root) override {\n        if (root->is_terminal()) {\n            stringstream stream;\n            root->to_stream(stream);\n            throw invalid_argument(\"Given state is terminal:\\n\" + stream.str());\n        }\n        Timer timer;\n        timer.start();\n        int simulation = 0;\n        S clone = root->clone();\n        while (simulation < max_simulations && !timer.exceeded(max_seconds)) {\n            monte_carlo_tree_search(&clone);\n            ++simulation;\n        }\n        this->log << \"ratio: \" << root->score / root->visits << endl;\n        this->log << \"simulations: \" << simulation << endl;\n        const auto legal_moves = root->get_legal_moves();\n        this->log << \"moves: \" << legal_moves.size() << endl;\n        for (const auto move : legal_moves) {\n            this->log << \"move: \" << move;\n            const auto child = root->get_child(move);\n            if (child != nullptr) {\n                this->log << \" score: \" << child->score\n                << \" visits: \" << child->visits\n                << \" UCT: \" << child->get_uct(UCT_C);\n            }\n            this->log << endl;\n        }\n        return get_most_visited_move(&clone);\n    }\n\n    void monte_carlo_tree_search(S *root) const {\n        S *current = tree_policy(root, root);\n        const auto result = rollout(current, root);\n        propagate_up(current, result);\n    }\n\n    void propagate_up(S *current, double result) const {\n        current->update_stats(result);\n        if (current->parent) {\n            propagate_up(current->parent, result);\n        }\n    }\n\n    S* tree_policy(S *state, const S *root) const {\n        if (state->is_terminal()) {\n            return state;\n        }\n        const M move = get_tree_policy_move(state, root);\n        const auto child = state->get_child(move);\n        if (child == nullptr) {\n            return state->add_child(move);\n        }\n        return tree_policy(child, root);\n    }\n\n    M get_most_visited_move(const S *state) const {\n        const auto legal_moves = state->get_legal_moves();\n        assert(legal_moves.size() > 0);\n        M best_move;\n        double max_visits = -INF;\n        for (const auto move : legal_moves) {\n            const auto child = state->get_child(move);\n            if (child != nullptr) {\n                const auto visits = child->visits;\n                if (max_visits < visits) {\n                    max_visits = visits;\n                    best_move = move;\n                }\n            }\n        }\n        assert(max_visits != -INF);\n        return best_move;\n    }\n\n    M get_best_move(S *state, const S *root) const {\n        const auto legal_moves = state->get_legal_moves();\n        assert(legal_moves.size() > 0);\n        M best_move;\n        if (state->player_to_move == root->player_to_move) {\n            // maximize\n            double best_uct = -INF;\n            for (const auto move : legal_moves) {\n                const auto child = state->get_child(move);\n                if (child != nullptr) {\n                    const auto uct = child->get_uct(UCT_C);\n                    if (best_uct < uct) {\n                        best_uct = uct;\n                        best_move = move;\n                    }\n                } else {\n                    return move;\n                }\n            }\n        }\n        else {\n            // minimize\n            double best_uct = INF;\n            for (const auto move : legal_moves) {\n                const auto child = state->get_child(move);\n                if (child != nullptr) {\n                    const auto uct = child->get_uct(-UCT_C);\n                    if (best_uct > uct) {\n                        best_uct = uct;\n                        best_move = move;\n                    }\n                } else {\n                    return move;\n                }\n            }\n        }\n        return best_move;\n    }\n\n    M get_random_move(const S *state) const {\n        const auto legal_moves = state->get_legal_moves();\n        assert(legal_moves.size() > 0);\n        const int index = random.uniform(0, legal_moves.size() - 1);\n        return legal_moves[index];\n    }\n\n    shared_ptr<M> get_winning_move(const S *state) const {\n        const auto current_player = state->player_to_move;\n        const auto legal_moves = state->get_legal_moves();\n        S clone = state->clone();\n        assert(legal_moves.size() > 0);\n        for (const M &move : legal_moves) {\n            clone.make_move(move);\n            if (clone.is_winner(current_player)) {\n                return make_shared<M>(move);\n            }\n            clone.undo_move(move);\n        }\n        return nullptr;\n    }\n\n    shared_ptr<M> get_blocking_move(const S *state) const {\n        const auto current_player = state->player_to_move;\n        const auto enemy = state->get_enemy(current_player);\n        S enemy_state = state->clone();\n        enemy_state.player_to_move = enemy;\n        return get_winning_move(&enemy_state);\n    }\n\n    M get_tree_policy_move(S *state, const S *root) const {\n        // If player has a winning move he makes it.\n        auto move_ptr = get_winning_move(state);\n        if (move_ptr != nullptr) {\n            return *move_ptr;\n        }\n        if (block) {\n            // If player has a blocking move he makes it.\n            move_ptr = get_blocking_move(state);\n            if (move_ptr != nullptr) {\n                return *move_ptr;\n            }\n        }\n        return get_best_move(state, root);\n    }\n\n    M get_default_policy_move(const S *state) const {\n        // If player has a winning move he makes it.\n        auto move_ptr = get_winning_move(state);\n        if (move_ptr != nullptr) {\n            return *move_ptr;\n        }\n        // If player has a blocking move he makes it.\n        move_ptr = get_blocking_move(state);\n        if (move_ptr != nullptr) {\n            return *move_ptr;\n        }\n        return get_random_move(state);\n    }\n\n    double rollout(S *current, const S *root) const {\n        if (current->is_terminal()) {\n            if (current->is_winner(root->player_to_move)) {\n                return WIN_SCORE;\n            }\n            if (current->is_winner(root->get_enemy(root->player_to_move))) {\n                return LOSE_SCORE;\n            }\n            return DRAW_SCORE;\n        }\n        M move = get_default_policy_move(current);\n        current->make_move(move);\n        auto result = rollout(current, root);\n        current->undo_move(move);\n        return result;\n    }\n\n    string get_name() const {\n        return \"MonteCarloTreeSearch\";\n    }\n\n};\n\nstruct OutcomeCounts {\n    int wins = 0;\n    int draws = 0;\n    int loses = 0;\n};\n\ntemplate<class S, class M>\nstruct Tester {\n    S *root = nullptr;\n    Algorithm<S, M> &algorithm_1;\n    Algorithm<S, M> &algorithm_2;\n    const int MATCHES;\n    const bool VERBOSE;\n    const bool SAVE;\n    const double SIGNIFICANCE_LEVEL = 0.005; // two sided 99% confidence interval\n\n    Tester(S *state,\n           Algorithm<S, M> &algorithm_1,\n           Algorithm<S, M> &algorithm_2,\n           int matches = INF,\n           bool verbose = false,\n           bool save = false\n    ) : root(state), algorithm_1(algorithm_1), algorithm_2(algorithm_2), MATCHES(matches), VERBOSE(verbose), SAVE(save) {}\n\n    virtual ~Tester() {}\n\n    OutcomeCounts start() {\n        Timer all_timer;\n        all_timer.start();\n        OutcomeCounts outcome_counts;\n        unordered_set<int> unique_game_hashes;\n        const char enemy = root->get_enemy(root->player_to_move);\n        for (int i = 1; i <= MATCHES; ++i) {\n            int move_number = 1;\n            auto current = root->clone();\n            if (i % 4 == 0 || i % 4 == 2) {\n                current.player_to_move = current.get_enemy(current.player_to_move);\n            }\n            if (i % 4 == 0 || i % 4 == 3) {\n                current.swap_players();\n            }\n            if (VERBOSE) {\n                cout << current << endl;\n            }\n            if (SAVE) {\n                save_file(move_number, current);\n            }\n            int game_hash = current.hash();\n            while (!current.is_terminal()) {\n                auto &algorithm = (current.player_to_move == root->player_to_move) ? algorithm_1 : algorithm_2;\n                if (VERBOSE) {\n                    cout << current.player_to_move << \" \" << algorithm << endl;\n                }\n                algorithm.reset();\n                Timer timer;\n                timer.start();\n                auto move = algorithm.get_move(&current);\n                if (VERBOSE) {\n                    cout << algorithm.read_log();\n                    cout << timer << endl;\n                }\n                current.make_move(move);\n                ++move_number;\n                if (VERBOSE) {\n                    cout << current << endl;\n                }\n                if (SAVE) {\n                    save_file(move_number, current);\n                }\n                game_hash ^= current.hash();\n            }\n            cout << \"Game \" << i << \": \";\n            auto insert = unique_game_hashes.insert(game_hash);\n            if (!insert.second) {\n                cout << \"Not unique, not counting\" << endl << endl;\n                continue;\n            }\n            if (current.is_winner(root->player_to_move)) {\n                ++outcome_counts.wins;\n                cout << root->player_to_move << \" \" << algorithm_1 << \" won\" << endl;\n            } else if (current.is_winner(enemy)) {\n                ++outcome_counts.loses;\n                cout << enemy << \" \" << algorithm_2 << \" won\" << endl;\n            } else {\n                ++outcome_counts.draws;\n                cout << \"draw\" << endl;\n            }\n            const int unique_games_count = unique_game_hashes.size();\n            cout << \"Unique games: \" << unique_games_count << endl;\n            cout << root->player_to_move << \" \" << algorithm_1 << \" wins: \" << outcome_counts.wins << endl;\n            cout << enemy << \" \" << algorithm_2 << \" wins: \" << outcome_counts.loses << endl;\n            cout << \"Draws: \" << outcome_counts.draws << endl;\n            const double successes = outcome_counts.wins + 0.5 * outcome_counts.draws;\n            const double ratio = successes / unique_games_count;\n            cout << \"Ratio: \" << ratio << endl;\n            const double lower = boost::math::binomial_distribution<>::find_lower_bound_on_p(unique_games_count, successes, SIGNIFICANCE_LEVEL);\n            const double upper = boost::math::binomial_distribution<>::find_upper_bound_on_p(unique_games_count, successes, SIGNIFICANCE_LEVEL);\n            cout << \"Lower confidence bound: \" << lower << endl;\n            cout << \"Upper confidence bound: \" << upper << endl;\n            cout << endl;\n            if (upper < 0.5 || lower > 0.5) {\n                cout << \"Total time: \" << all_timer << endl;\n                break;\n            }\n        }\n        if (SAVE) {\n            shell(\"convert -delay 100 -loop 0 $(ls -v *.gif) game.gif\");\n            shell(\"rm [0-9]*.gif\");\n        }\n        return outcome_counts;\n    }\n\n    void save_file(int move_number, const S &state) const {\n        const int FONT_SIZE = 16;\n        stringstream ss;\n        ss << state;\n        vector<string> lines;\n        string line;\n        while (getline(ss, line)) {\n            lines.push_back(line);\n        }\n        assert(lines.size() > 0);\n        const int width = lines[0].length() * FONT_SIZE;\n        const int height = lines.size() * FONT_SIZE;\n        stringstream command;\n        command << \"convert -size \" << width << \"x\" << height;\n        command << \" xc:black -font square.ttf -pointsize \" << FONT_SIZE << \" -fill white -draw \\\"\";\n        for (int y = 0; y < lines.size(); y++) {\n            command << \"text 0,\" << (y + 1) * FONT_SIZE << \" '\" << lines[y] << \"' \";\n        }\n        command << \"\\\" \" << move_number << \".gif\";\n        shell(command.str());\n    }\n\n    void shell(const string &command) const {\n        const int return_code = system(command.c_str());\n        if (return_code != 0) {\n            cout << \"Command \" << command << \" returned \" << return_code;\n        }\n    }\n};\n", "meta": {"hexsha": "7ca92a1d7586f6238f430eda1f8614741b88dc84", "size": 28287, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/gtsa.hpp", "max_stars_repo_name": "Sachin-A/yinsh", "max_stars_repo_head_hexsha": "5a9a91f19499b6e7d2e7e04b1e8166382a17da5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-16T06:27:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-17T09:39:12.000Z", "max_issues_repo_path": "include/gtsa.hpp", "max_issues_repo_name": "Sachin-A/yinsh", "max_issues_repo_head_hexsha": "5a9a91f19499b6e7d2e7e04b1e8166382a17da5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gtsa.hpp", "max_forks_repo_name": "Sachin-A/yinsh", "max_forks_repo_head_hexsha": "5a9a91f19499b6e7d2e7e04b1e8166382a17da5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-05-10T01:01:31.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-13T17:54:03.000Z", "avg_line_length": 31.3951165372, "max_line_length": 168, "alphanum_fraction": 0.5305617421, "num_tokens": 6372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.2057658573258315}}
{"text": "#include \"CoordinateConversions.h\"\n#include \"CoordinateConverter.h\"\n#include \"GeneralFunctions.h\"\n#include \"GeneralDefinitions.h\"\n#include \"AutoThreadLock.h\"\n#include \"AutoWriteLock.h\"\n#include \"AutoReadLock.h\"\n\n#include <macgyver/Exception.h>\n#include <boost/algorithm/string/predicate.hpp>\n#include <boost/filesystem/operations.hpp>\n#include <boost/math/constants/constants.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n#include <boost/make_shared.hpp>\n#include <boost/functional/hash.hpp>\n#include <ogr_geometry.h>\n#include <ogr_spatialref.h>\n\n#include <newbase/NFmiLocation.h>\n#include <unordered_map>\n\n\n\n\nstd::unordered_map<std::size_t,SmartMet::CoordinateConverter> *coordinateConverterCache = nullptr;\nSmartMet::ModificationLock coordinateConverterCache_modificationLock;\n\n\n\n\nbool convert(const OGRSpatialReference *sr_from,const OGRSpatialReference *sr_to,int nCount,double *x,double *y)\n{\n  try\n  {\n    if (coordinateConverterCache == nullptr)\n    {\n      SmartMet::AutoWriteLock writeLock(&coordinateConverterCache_modificationLock);\n      if (coordinateConverterCache == nullptr)\n        coordinateConverterCache = new std::unordered_map<std::size_t,SmartMet::CoordinateConverter>;\n    }\n\n    std::size_t hash = (std::size_t)sr_from;\n    boost::hash_combine(hash, (std::size_t)sr_to);\n\n    {\n      SmartMet::AutoReadLock readLock(&coordinateConverterCache_modificationLock);\n      auto rec = coordinateConverterCache->find(hash);\n      if (rec != coordinateConverterCache->end())\n        return rec->second.convert(nCount,x,y);\n    }\n\n    SmartMet::AutoWriteLock writeLock(&coordinateConverterCache_modificationLock);\n    if (coordinateConverterCache->size() > 1000000)\n      coordinateConverterCache->clear();\n\n    SmartMet::CoordinateConverter tr(sr_from,sr_to);\n    coordinateConverterCache->insert(std::pair<std::size_t,SmartMet::CoordinateConverter>(hash,tr));\n    return tr.convert(nCount,x,y);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP,\"Operation failed!\",nullptr);\n  }\n}\n\n\n\n\n\ndouble getValue(double theAngle)\n{\n  try\n  {\n    if (::fabs(theAngle - 180) < 0.0000001)\n      return 180;\n    else if (::fabs(theAngle + 180) < 0.0000001)\n      return -180;\n    else if (theAngle > 180)\n      return getValue(theAngle - 360);\n    else if (theAngle < -180)\n      return getValue(theAngle + 360);\n\n    return theAngle;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP,\"Operation failed!\",nullptr);\n  }\n}\n\n\n\n\n\nvoid latlon_to_rotatedLatlon(double lat,double lon,double southPoleLat,double southPoleLon,double& rotLat,double& rotLon)\n{\n  try\n  {\n    if (southPoleLat == -90)\n    {\n      rotLat = lat;\n      rotLon = lon;\n      return;\n    }\n\n    double SinYPole = sin((southPoleLat + 90) * kDegToRad);\n    double CosYPole = cos((southPoleLat + 90) * kDegToRad);\n\n    double SinXReg = sin((lon - southPoleLon) * kDegToRad);\n    double CosXReg = cos((lon - southPoleLon) * kDegToRad);\n    double SinYReg = sin(lat * kDegToRad);\n    double CosYReg = cos(lat * kDegToRad);\n    double SinYRot = CosYPole * SinYReg - SinYPole * CosYReg * CosXReg;\n    SinYRot = std::min(std::max(SinYRot, -1.), 1.);\n    double YRot = asin(SinYRot) * kOneRad;\n\n    double CosYRot = cos(YRot * kDegToRad);\n    double CosXRot = (CosYPole * CosYReg * CosXReg + SinYPole * SinYReg) / CosYRot;\n    CosXRot = std::min(std::max(CosXRot, -1.), 1.);\n    double SinXRot = CosYReg * SinXReg / CosYRot;\n    double XRot = acos(CosXRot) * kOneRad;\n    if (SinXRot < 0.)\n      XRot = getValue(-XRot);\n    else\n      XRot = getValue(XRot);\n\n    rotLon = XRot;\n    rotLat = YRot;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP,\"Operation failed!\",nullptr);\n  }\n}\n\n\n\n\n\nvoid rotatedLatlon_to_latlon(double rotLat,double rotLon,double southPoleLat,double southPoleLon,double& lat,double& lon)\n{\n  try\n  {\n    if (southPoleLat == -90)\n    {\n      lat = rotLat;\n      lon = rotLon;\n      return;\n    }\n\n    double SinYPole = sin((southPoleLat + 90) * kDegToRad);\n    double CosYPole = cos((southPoleLat + 90) * kDegToRad);\n\n    double SinXRot = sin(rotLon * kDegToRad);\n    double CosXRot = cos(rotLon * kDegToRad);\n    double SinYRot = sin(rotLat * kDegToRad);\n    double CosYRot = cos(rotLat * kDegToRad);\n    double SinYReg = CosYPole * SinYRot + SinYPole * CosYRot * CosXRot;\n    SinYReg = std::min(std::max(SinYReg, -1.0), 1.0);\n\n    double YReg = asin(SinYReg) * kOneRad;\n\n    double CosYReg = cos(YReg * kDegToRad);\n    double CosXReg = (CosYPole * CosYRot * CosXRot - SinYPole * SinYRot) / CosYReg;\n    CosXReg = std::min(std::max(CosXReg, -1.0), 1.0);\n    double SinXReg = CosYRot * SinXRot / CosYReg;\n\n    double XRegVal = acos(CosXReg) * kOneRad;\n    if (SinXReg < 0.)\n      XRegVal = -XRegVal;\n\n    XRegVal = XRegVal + southPoleLon;\n    double XReg = XRegVal;\n\n    lat = YReg;\n    lon = XReg;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP,\"Operation failed!\",nullptr);\n  }\n}\n\n\n\n\ndouble latlon_distance(double lat1, double lon1, double lat2, double lon2)\n{\n  double p = 0.017453292519943295;    // Math.PI / 180\n  double a = 0.5 - cos((lat2 - lat1) * p)/2 +\n          cos(lat1 * p) * cos(lat2 * p) *\n          (1 - cos((lon2 - lon1) * p))/2;\n\n  return 12742 * asin(sqrt(a)); // 2 * R; R = 6371 km\n}\n\n\n\ndouble latlon_width(double lat, double longitudes)\n{\n  try\n  {\n    // Metric width of 1 degree\n    double w = latlon_distance(lat,0,lat,1);\n    return longitudes * w;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP,\"Operation failed!\",nullptr);\n  }\n}\n\n\n\n\ndouble latlon_height(double lon, double latitudes)\n{\n  try\n  {\n    // Metric width of 1 degree\n    double h = latlon_distance(0,lon,1,lon);\n    return latitudes * h;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP,\"Operation failed!\",nullptr);\n  }\n}\n\n\n\nstd::pair<std::vector<SmartMet::T::Coordinate>, std::vector<double>> getIsocirclePoints(double lon1, double lat1, double lon2, double lat2, std::size_t steps)\n{\n  try\n  {\n    // Sanity checks\n    if (lon1 == lon2 && lat1 == lat2)\n      throw Fmi::Exception(BCP, \"Ill-defined isocircle: start and end points are equal\");\n\n    if (std::abs(lon1 - lon2) == 180 && std::abs(lat1 - (90 - lat2)) == 90)\n      throw Fmi::Exception(BCP, \"Ill-defined isocircle: points at opposing ends of the earth\");\n\n    if (steps < 1 || steps > 10000)\n      throw Fmi::Exception(BCP,\"Number of points on isocircle must be 1-10000, not \" + boost::lexical_cast<std::string>(steps));\n\n    // Calculate bearing and distance to be travelled\n\n    NFmiLocation startpoint(lon1, lat1);\n    NFmiLocation endpoint(lon2, lat2);\n\n    double bearing = startpoint.Direction(endpoint);\n    double distance = startpoint.Distance(endpoint);\n\n    std::vector<SmartMet::T::Coordinate> coordinates;\n    auto cc = startpoint.GetLocation();\n    coordinates.emplace_back(SmartMet::T::Coordinate(cc.X(),cc.Y()));\n\n    std::vector<double> distances;\n    distances.emplace_back(0);\n\n    for (std::size_t i = 1; i < steps; i++)\n    {\n      // Should this be fixed? Probably not - the coordinates should behave the same\n      double dist = i * distance / steps;\n#ifdef WGS84      \n      auto loc = startpoint.GetLocation(bearing, dist);\n#else\n      const bool pacific_view = false;\n      auto loc = startpoint.GetLocation(bearing, dist, pacific_view);\n#endif      \n      auto cc = loc.GetLocation();\n      coordinates.emplace_back(SmartMet::T::Coordinate(cc.X(),cc.Y()));\n      distances.emplace_back(dist / 1000.0);\n    }\n    cc = endpoint.GetLocation();\n    coordinates.emplace_back(SmartMet::T::Coordinate(cc.X(),cc.Y()));\n    distances.emplace_back(distance / 1000.0);\n\n    return std::make_pair(coordinates, distances);\n  }\n  catch (...)\n  {\n    throw Fmi::Exception::Trace(BCP, \"Operation failed!\");\n  }\n}\n\n\n\n\nvoid latLon_bboxByCenter(double centerX,double centerY,double metricWidth,double metricHeight,double& lon1,double& lat1,double& lon2,double& lat2)\n{\n  try\n  {\n    OGRSpatialReference sr_latlon;\n    sr_latlon.importFromEPSG(4326);\n    sr_latlon.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);\n\n    OGRSpatialReference sr_wgs84_world_mercator;\n    sr_wgs84_world_mercator.importFromEPSG(3395);\n    sr_wgs84_world_mercator.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);\n\n    OGRCoordinateTransformation *transformation = OGRCreateCoordinateTransformation(&sr_latlon,&sr_wgs84_world_mercator);\n    OGRCoordinateTransformation *reverseTransformation = OGRCreateCoordinateTransformation(&sr_wgs84_world_mercator,&sr_latlon);\n\n    transformation->Transform(1,&centerX,&centerY);\n\n    double xx1 = centerX - metricWidth/2;\n    double yy1 = centerY - metricHeight/2;\n    double xx2 = centerX + metricWidth/2;\n    double yy2 = centerY + metricHeight/2;\n\n    // Converting metric coordinates to latlon coordinates.\n\n    reverseTransformation->Transform(1,&xx1,&yy1);\n    reverseTransformation->Transform(1,&xx2,&yy2);\n\n    if (transformation != nullptr)\n      OCTDestroyCoordinateTransformation(transformation);\n\n    if (reverseTransformation != nullptr)\n      OCTDestroyCoordinateTransformation(reverseTransformation);\n\n    lon1 = xx1;\n    lat1 = yy1;\n    lon2 = xx2;\n    lat2 = yy2;\n  }\n  catch (...)\n  {\n    throw Fmi::Exception(BCP,\"Operation failed!\",nullptr);\n  }\n}\n\n\n\n\n", "meta": {"hexsha": "6c23a6b303763c15297b5c7f3c27f771f71eb727", "size": 9152, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common/CoordinateConversions.cpp", "max_stars_repo_name": "fmidev/smartmet-library-grid-files", "max_stars_repo_head_hexsha": "c68d271e12e3404cd805a423fe6c5b6c467f00e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common/CoordinateConversions.cpp", "max_issues_repo_name": "fmidev/smartmet-library-grid-files", "max_issues_repo_head_hexsha": "c68d271e12e3404cd805a423fe6c5b6c467f00e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/CoordinateConversions.cpp", "max_forks_repo_name": "fmidev/smartmet-library-grid-files", "max_forks_repo_head_hexsha": "c68d271e12e3404cd805a423fe6c5b6c467f00e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1572700297, "max_line_length": 158, "alphanum_fraction": 0.6764641608, "num_tokens": 2597, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185205547238, "lm_q2_score": 0.3629691986286475, "lm_q1q2_score": 0.20544728881472074}}
{"text": "//\n// Copyright (c) 2009, Markus Rickert\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// * Redistributions of source code must retain the above copyright notice,\n//   this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above copyright notice,\n//   this list of conditions and the following disclaimer in the documentation\n//   and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n//\n\n#include <algorithm>\n#include <stack>\n#include <boost/graph/graphviz.hpp>\n#include <rl/math/Quaternion.h>\n#include <rl/math/Rotation.h>\n#include <rl/math/Spatial.h>\n#include <rl/math/Unit.h>\n\n#include \"Exception.h\"\n#include \"Dynamic.h\"\n#include \"Prismatic.h\"\n#include \"Revolute.h\"\n#include \"World.h\"\n\nnamespace rl\n{\n\tnamespace mdl\n\t{\n\t\tDynamic::Dynamic() :\n\t\t\tKinematic(),\n\t\t\tG(),\n\t\t\tinvM(),\n\t\t\tinvMx(),\n\t\t\tM(),\n\t\t\tV()\n\t\t{\n\t\t}\n\t\t\n\t\tDynamic::~Dynamic()\n\t\t{\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::calculateCentrifugalCoriolis()\n\t\t{\n\t\t\tthis->calculateCentrifugalCoriolis(this->V);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::calculateCentrifugalCoriolis(::rl::math::Vector& V)\n\t\t{\n\t\t\t::rl::math::Vector g(3);\n\t\t\tthis->getWorldGravity(g);\n\t\t\t\n\t\t\t::rl::math::Vector tmp(this->getDof());\n\t\t\ttmp.setZero(); //TODO\n\t\t\t\n\t\t\tthis->setAcceleration(tmp);\n\t\t\tthis->setWorldGravity(0, 0, 0);\n\t\t\t\n\t\t\tthis->inverseDynamics();\n\t\t\tV = this->getTorque();\n\t\t\t\n\t\t\tthis->setWorldGravity(g);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::calculateGravity()\n\t\t{\n\t\t\tthis->calculateGravity(this->G);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::calculateGravity(::rl::math::Vector& G)\n\t\t{\n\t\t\t::rl::math::Vector tmp(this->getDof());\n\t\t\ttmp.setZero(); //TODO\n\t\t\t\n\t\t\tthis->setVelocity(tmp);\n\t\t\tthis->setAcceleration(tmp);\n\t\t\t\n\t\t\tthis->inverseDynamics();\n\t\t\tG = this->getTorque();\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::calculateMassMatrix()\n\t\t{\n\t\t\tthis->calculateMassMatrix(this->M);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::calculateMassMatrix(::rl::math::Matrix& M)\n\t\t{\n\t\t\t::rl::math::Vector g(3);\n\t\t\tthis->getWorldGravity(g);\n\t\t\t\n\t\t\t::rl::math::Vector tmp(this->getDof());\n\t\t\ttmp.setZero(); //TODO\n\t\t\t\n\t\t\tthis->setVelocity(tmp);\n\t\t\tthis->setWorldGravity(0, 0, 0);\n\t\t\t\n\t\t\tfor (::std::size_t i = 0; i < this->getDof(); ++i)\n\t\t\t{\n\t\t\t\tfor (::std::size_t j = 0; j < this->getDof(); ++j)\n\t\t\t\t{\n\t\t\t\t\ttmp(j) = i == j ? 1 : 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthis->setAcceleration(tmp);\n\t\t\t\tthis->inverseDynamics();\n\t\t\t\t\n\t\t\t\tM.col(i) = this->getTorque();\n\t\t\t}\n\t\t\t\n\t\t\tthis->setWorldGravity(g);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::calculateMassMatrixInverse()\n\t\t{\n\t\t\tthis->calculateMassMatrixInverse(this->invM);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::calculateMassMatrixInverse(::rl::math::Matrix& invM)\n\t\t{\n\t\t\t::rl::math::Vector g(3);\n\t\t\tthis->getWorldGravity(g);\n\t\t\t\n\t\t\t::rl::math::Vector tmp(this->getDof());\n\t\t\ttmp.setZero(); //TODO\n\t\t\t\n\t\t\tthis->setVelocity(tmp);\n\t\t\tthis->setWorldGravity(0, 0, 0);\n\t\t\t\n\t\t\tfor (::std::size_t i = 0; i < this->getDof(); ++i)\n\t\t\t{\n\t\t\t\tfor (::std::size_t j = 0; j < this->getDof(); ++j)\n\t\t\t\t{\n\t\t\t\t\ttmp(j) = i == j ? 1 : 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthis->setTorque(tmp);\n\t\t\t\tthis->forwardDynamics();\n\t\t\t\t\n\t\t\t\tinvM.col(i) = this->getAcceleration();\n\t\t\t}\n\t\t\t\n\t\t\tthis->setWorldGravity(g);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::calculateOperationalMassMatrixInverse()\n\t\t{\n\t\t\tthis->calculateOperationalMassMatrixInverse(this->J, this->invM, this->invMx);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::calculateOperationalMassMatrixInverse(const ::rl::math::Matrix& J, const ::rl::math::Matrix& invM, ::rl::math::Matrix& invMx) const\n\t\t{\n\t\t\tinvMx = J * invM * J.transpose(); // TODO\n\t\t}\n\t\t\n\t\tModel*\n\t\tDynamic::clone() const\n\t\t{\n\t\t\treturn new Dynamic(*this);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::eulerCauchy(const ::rl::math::Real& dt)\n\t\t{\n\t\t\t::rl::math::Vector y = this->getPosition();\n\t\t\t::rl::math::Vector dy = this->getVelocity();\n\t\t\t\n\t\t\tthis->forwardDynamics();\n\t\t\t\n\t\t\t// f\n\t\t\t::rl::math::Vector f = this->getAcceleration();\n\t\t\t\n\t\t\t// y_0 + dy_0 * dt\n\t\t\ty += dt * dy; // TODO\n\t\t\t// dy_0 + f * dt\n\t\t\tdy += dt * f; // TODO\n\t\t\t\n\t\t\tthis->setPosition(y);\n\t\t\tthis->setVelocity(dy);\n\t\t\tthis->setAcceleration(f);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::forwardDynamics()\n\t\t{\n\t\t\tfor (::std::vector<Element*>::iterator i = this->elements.begin(); i != this->elements.end(); ++i)\n\t\t\t{\n\t\t\t\t(*i)->forwardDynamics1();\n\t\t\t}\n\t\t\t\n\t\t\tfor (::std::vector<Element*>::reverse_iterator i = this->elements.rbegin(); i != this->elements.rend(); ++i)\n\t\t\t{\n\t\t\t\t(*i)->forwardDynamics2();\n\t\t\t}\n\t\t\t\n\t\t\tfor (::std::vector<Element*>::iterator i = this->elements.begin(); i != this->elements.end(); ++i)\n\t\t\t{\n\t\t\t\t(*i)->forwardDynamics3();\n\t\t\t}\n\t\t}\n\t\t\n\t\tconst ::rl::math::Vector&\n\t\tDynamic::getCentrifugalCoriolis() const\n\t\t{\n\t\t\treturn this->V;\n\t\t}\n\t\t\n\t\tconst ::rl::math::Vector&\n\t\tDynamic::getGravity() const\n\t\t{\n\t\t\treturn this->G;\n\t\t}\n\t\t\n\t\tconst ::rl::math::Matrix&\n\t\tDynamic::getMassMatrixInverse() const\n\t\t{\n\t\t\treturn this->invM;\n\t\t}\n\t\t\n\t\tconst ::rl::math::Matrix&\n\t\tDynamic::getMassMatrix() const\n\t\t{\n\t\t\treturn this->M;\n\t\t}\n\t\t\n\t\tconst ::rl::math::Matrix&\n\t\tDynamic::getOperationalMassMatrixInverse() const\n\t\t{\n\t\t\treturn this->invMx;\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::getWorldGravity(::rl::math::Real& x, ::rl::math::Real& y, ::rl::math::Real& z) const\n\t\t{\n\t\t\tdynamic_cast<World*>(this->tree[this->root].get())->getGravity(x, y, z);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::getWorldGravity(::rl::math::Vector& xyz) const\n\t\t{\n\t\t\tthis->getWorldGravity(xyz(0), xyz(1), xyz(2));\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::inverseDynamics()\n\t\t{\n\t\t\tfor (::std::vector<Element*>::iterator i = this->elements.begin(); i != this->elements.end(); ++i)\n\t\t\t{\n\t\t\t\t(*i)->inverseDynamics1();\n\t\t\t}\n\t\t\t\n\t\t\tfor (::std::vector<Element*>::reverse_iterator i = this->elements.rbegin(); i != this->elements.rend(); ++i)\n\t\t\t{\n\t\t\t\t(*i)->inverseDynamics2();\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::inverseForce()\n\t\t{\n\t\t\tfor (::std::vector<Element*>::reverse_iterator i = this->elements.rbegin(); i != this->elements.rend(); ++i)\n\t\t\t{\n\t\t\t\t(*i)->inverseForce();\n\t\t\t}\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::rungeKuttaNystrom(const ::rl::math::Real& dt)\n\t\t{\n\t\t\t::rl::math::Vector y0 = this->getPosition();\n\t\t\t::rl::math::Vector dy0 = this->getVelocity();\n\t\t\t\n\t\t\tthis->forwardDynamics();\n\t\t\t\n\t\t\t::rl::math::Vector f = this->getAcceleration();\n\t\t\t\n\t\t\t// k1 = dt / 2 * f\n\t\t\t::rl::math::Vector k1 = dt / 2 * f;\n\t\t\t\n\t\t\t// y_0 + dt / 2 * dy_0 + dt / 4 * k_1\n\t\t\t::rl::math::Vector y = y0 + dt / 2 * dy0 + dt / 4 * k1; // TODO\n\t\t\t// dy_0 + k1\n\t\t\t::rl::math::Vector dy = dy0 + k1;\n\t\t\t\n\t\t\tthis->setPosition(y);\n\t\t\tthis->setVelocity(dy);\n\t\t\tthis->forwardDynamics();\n\t\t\t\n\t\t\t// k2 = dt / 2 * f\n\t\t\t::rl::math::Vector k2 = dt / 2 * this->getAcceleration();\n\t\t\t\n\t\t\t// dy_0 + k_2\n\t\t\tdy = dy0 + k2;\n\t\t\t\n\t\t\tthis->setVelocity(dy);\n\t\t\tthis->forwardDynamics();\n\t\t\t\n\t\t\t// k3 = dt / 2 * f\n\t\t\t::rl::math::Vector k3 = dt / 2 * this->getAcceleration();\n\t\t\t\n\t\t\t// y_0 + dt * dy_0 + dt * k_3\n\t\t\ty = y0 + dt * dy0 + dt * k3; // TODO\n\t\t\t// dy_0 + 2 * k_3\n\t\t\tdy = dy0 + 2 * k3;\n\t\t\t\n\t\t\tthis->setPosition(y);\n\t\t\tthis->setVelocity(dy);\n\t\t\tthis->forwardDynamics();\n\t\t\t\n\t\t\t// k4 = dt / 2 * f\n\t\t\t::rl::math::Vector k4 = dt / 2 * this->getAcceleration();\n\t\t\t\n\t\t\t// y_0 + dy_0 * dt + dt / 3 * (k_1 + k_2 + k_3)\n\t\t\ty = y0 + dy0 * dt + dt / 3 * (k1 + k2 + k3); // TODO\n\t\t\t// dy_0 + 1 / 3 * (k_1 + 2 * k_2 + 2 * k_3 + k_4)\n\t\t\tdy = dy0 + 1.0f / 3.0f * (k1 + 2 * k2 + 2 * k3 + k4); // TODO\n\t\t\t\n\t\t\tthis->setPosition(y);\n\t\t\tthis->setVelocity(dy);\n\t\t\tthis->setAcceleration(f);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::setWorldGravity(const ::rl::math::Real& x, const ::rl::math::Real& y, const ::rl::math::Real& z)\n\t\t{\n\t\t\tdynamic_cast<World*>(this->tree[this->root].get())->setGravity(x, y, z);\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::setWorldGravity(const ::rl::math::Vector& xyz)\n\t\t{\n\t\t\tthis->setWorldGravity(xyz(0), xyz(1), xyz(2));\n\t\t}\n\t\t\n\t\tvoid\n\t\tDynamic::update()\n\t\t{\n\t\t\tKinematic::update();\n\t\t\t\n\t\t\tthis->M.resize(this->getDof(), this->getDof());\n\t\t\tthis->V.resize(this->getDof());\n\t\t\tthis->G.resize(this->getDof());\n\t\t\tthis->invM.resize(this->getDof(), this->getDof());\n\t\t\tthis->invMx.resize(6 * this->getOperationalDof(), 6 * this->getOperationalDof());\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "dfcf292b281ce520bab988777d314e0ac36cccc0", "size": 8812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rl/mdl/Dynamic.cpp", "max_stars_repo_name": "Roboy/rl", "max_stars_repo_head_hexsha": "7686cbd5f9c3630daa6d972f2244ed31f4dc5142", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-11-10T17:26:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T17:26:21.000Z", "max_issues_repo_path": "src/rl/mdl/Dynamic.cpp", "max_issues_repo_name": "Roboy/rl", "max_issues_repo_head_hexsha": "7686cbd5f9c3630daa6d972f2244ed31f4dc5142", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rl/mdl/Dynamic.cpp", "max_forks_repo_name": "Roboy/rl", "max_forks_repo_head_hexsha": "7686cbd5f9c3630daa6d972f2244ed31f4dc5142", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-10T17:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T17:26:06.000Z", "avg_line_length": 23.5614973262, "max_line_length": 142, "alphanum_fraction": 0.5998638221, "num_tokens": 2876, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2053570805466392}}
{"text": "#pragma once\n#ifndef SOLVER_KERNELS_H\n#define SOLVER_KERNELS_H\n\n#include <vector>\n#include <memory>\n\n#include <Eigen/Core>\n#include <complex>\n#include <engine/Vectormath_Defines.hpp>\n#include <data/Spin_System.hpp>\n#include <engine/Vectormath.hpp>\n#include <engine/Backend_par.hpp>\n#include <engine/Backend_seq.hpp>\n\nnamespace Engine\n{\nnamespace Solver_Kernels\n{\n    // SIB\n    void sib_transform(const vectorfield & spins, const vectorfield & force, vectorfield & out);\n\n    // OSO coordinates\n    void oso_rotate( std::vector<std::shared_ptr<vectorfield>> & configurations, std::vector<vectorfield> & searchdir);\n    void oso_calc_gradients( vectorfield & residuals, const vectorfield & spins, const vectorfield & forces);\n    scalar maximum_rotation(const vectorfield & searchdir, scalar maxmove);\n\n    // Atlas coordinates\n    void atlas_calc_gradients(vector2field & residuals, const vectorfield & spins, const vectorfield & forces, const scalarfield & a3_coords);\n    void atlas_rotate(std::vector<std::shared_ptr<vectorfield>> & configurations, const std::vector<scalarfield> & a3_coords, const std::vector<vector2field> & searchdir);\n    bool ncg_atlas_check_coordinates(const std::vector<std::shared_ptr<vectorfield>> & spins, std::vector<scalarfield> & a3_coords, scalar tol = -0.6);\n    void lbfgs_atlas_transform_direction(std::vector<std::shared_ptr<vectorfield>> & configurations, std::vector<scalarfield> & a3_coords, std::vector<field<vector2field>> & atlas_updates,\n                                         std::vector<field<vector2field>> & grad_updates, std::vector<vector2field> & searchdir, std::vector<vector2field> & grad_pr, scalarfield & rho);\n\n    // LBFGS\n    template <typename Vec>\n    void lbfgs_get_searchdir(int & local_iter, scalarfield & rho, scalarfield & alpha, std::vector<field<Vec>> & q_vec, std::vector<field<Vec>> & searchdir,\n                             std::vector<field<field<Vec>>> & delta_a, std::vector<field<field<Vec>>> & delta_grad, const std::vector<field<Vec>> & grad, std::vector<field<Vec>> & grad_pr,\n                             const int num_mem, const scalar maxmove) {\n        // std::cerr << \"lbfgs searchdir \\n\";\n        static auto dot = [] SPIRIT_LAMBDA (const Vec & v1, const Vec &v2) {return v1.dot(v2);};\n        static auto set = [] SPIRIT_LAMBDA (const Vec & x) {return x;};\n\n        scalar epsilon = sizeof(scalar) == sizeof(float) ? 1e-30 : 1e-300;\n\n        int noi = grad.size();\n        int nos = grad[0].size();\n        int m_index = local_iter % num_mem; // memory index\n        int c_ind = 0;\n\n        if (local_iter == 0) // gradient descent\n        {\n            for(int img=0; img<noi; img++) {\n                Backend::par::set(grad_pr[img], grad[img], set);\n                auto & dir = searchdir[img];\n                auto & g_cur = grad[img];\n                Backend::par::set(dir, g_cur, [] SPIRIT_LAMBDA (const Vec & x){return -x;});\n                auto & da = delta_a[img];\n                auto & dg = delta_grad[img];\n                for (int i = 0; i < num_mem; i++)\n                {\n                    rho[i] = 0.0;\n                    auto dai = da[i].data();\n                    auto dgi = dg[i].data();\n                    Backend::par::apply(nos, [dai, dgi] SPIRIT_LAMBDA (int idx){\n                        dai[idx] = Vec::Zero();\n                        dgi[idx] = Vec::Zero();\n                    });\n                }\n            }\n        } else {\n            for (int img=0; img<noi; img++)\n            {\n                auto da = delta_a[img][m_index].data();\n                auto dg = delta_grad[img][m_index].data();\n                auto g  = grad[img].data();\n                auto g_pr = grad_pr[img].data();\n                auto sd = searchdir[img].data();\n                Backend::par::apply(nos, [da, dg, g, g_pr, sd] SPIRIT_LAMBDA (int idx) {\n                    da[idx] = sd[idx];\n                    dg[idx] = g[idx] - g_pr[idx];\n                });\n            }\n\n            scalar rinv_temp = 0;\n            for (int img=0; img<noi; img++)\n                rinv_temp += Backend::par::reduce(delta_grad[img][m_index], delta_a[img][m_index], dot);\n            std::cout << rinv_temp << \" rinv_temp\\n\";\n            if (rinv_temp > epsilon)\n                rho[m_index] = 1.0 / rinv_temp;\n            else\n            {\n                local_iter = 0;\n                return lbfgs_get_searchdir(local_iter, rho, alpha, q_vec, searchdir,\n                        delta_a, delta_grad, grad, grad_pr, num_mem, maxmove);\n            }\n\n            for (int img=0; img<noi; img++)\n                Backend::par::set(q_vec[img], grad[img], set);\n\n            for (int k = num_mem - 1; k > -1; k--)\n            {\n                c_ind = (k + m_index + 1) % num_mem;\n                scalar temp=0;\n                for (int img=0; img<noi; img++)\n                    temp += Backend::par::reduce(delta_a[img][c_ind], q_vec[img], dot);\n                std::cout << temp << \" temp\\n\";\n                alpha[c_ind] = rho[c_ind] * temp;\n                for (int img=0; img<noi; img++)\n                {\n                    auto q=q_vec[img].data();\n                    auto a=alpha.data();\n                    auto d=delta_grad[img].data();\n                    Backend::par::apply(nos, [c_ind, q, a, d] SPIRIT_LAMBDA (int idx){\n                        q[idx] += -a[c_ind] * d[c_ind][idx];\n                    });\n                }\n            }\n\n            scalar dy2=0;\n            for (int img=0; img<noi; img++)\n                dy2 += Backend::par::reduce(delta_grad[img][m_index], delta_grad[img][m_index], dot);\n            std::cout << dy2 << \" dy2\\n\";\n            for (int img=0; img<noi; img++)\n            {\n                scalar rhody2 = dy2 * rho[m_index];\n                scalar inv_rhody2 = 0.0;\n                if (rhody2 > epsilon)\n                    inv_rhody2 = 1.0 / rhody2;\n                else\n                    inv_rhody2 = 1.0/(epsilon);\n                Backend::par::set(searchdir[img], q_vec[img], [inv_rhody2] SPIRIT_LAMBDA (const Vec & q){\n                    return inv_rhody2 * q;\n                } );\n            }\n\n            for (int k = 0; k < num_mem; k++)\n            {\n                if (local_iter < num_mem)\n                    c_ind = k;\n                else\n                    c_ind = (k + m_index + 1) % num_mem;\n\n                scalar rhopdg = 0;\n                for(int img=0; img<noi; img++)\n                    rhopdg += Backend::par::reduce(delta_grad[img][c_ind], searchdir[img], dot);\n\n                rhopdg *= rho[c_ind];\n                std::cout << rhopdg << \" rhopdg\\n\";\n                for (int img=0; img<noi; img++)\n                {\n                    auto sd   = searchdir[img].data();\n                    auto alph = alpha[c_ind];\n                    auto da   = delta_a[img][c_ind].data();\n                    Backend::par::apply( nos, [sd, alph, da, rhopdg] SPIRIT_LAMBDA (int idx){\n                        sd[idx] += (alph - rhopdg) * da[idx];\n                    });\n                }\n            }\n\n            for (int img=0; img<noi; img++)\n            {\n                auto g    = grad[img].data();\n                auto g_pr = grad_pr[img].data();\n                auto sd   = searchdir[img].data();\n                Backend::par::apply(nos, [g, g_pr, sd] SPIRIT_LAMBDA (int idx){\n                    g_pr[idx] = g[idx];\n                    sd[idx]   = -sd[idx];\n                });\n            }\n        }\n        local_iter++;\n    }\n}\n}\n\n#endif", "meta": {"hexsha": "4814c9b5d74484e493a51ca5a3342bed85484bbe", "size": 7515, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/include/engine/Solver_Kernels.hpp", "max_stars_repo_name": "MSallermann/spirit", "max_stars_repo_head_hexsha": "d3b771bcbf2f1eb4b28d48899091c17a48f12c67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2020-08-24T22:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T06:54:54.000Z", "max_issues_repo_path": "core/include/engine/Solver_Kernels.hpp", "max_issues_repo_name": "MSallermann/spirit", "max_issues_repo_head_hexsha": "d3b771bcbf2f1eb4b28d48899091c17a48f12c67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/include/engine/Solver_Kernels.hpp", "max_forks_repo_name": "MSallermann/spirit", "max_forks_repo_head_hexsha": "d3b771bcbf2f1eb4b28d48899091c17a48f12c67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-05T13:24:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T07:46:47.000Z", "avg_line_length": 42.4576271186, "max_line_length": 188, "alphanum_fraction": 0.4966067864, "num_tokens": 1924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5234203489363239, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.20535708054663915}}
{"text": "/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2020 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*/\n\n#include \"BlockMatrixIterators.hpp\"\n#include <iostream>                                 // for operator<<, ostream\n#include <boost/numeric/ublas/matrix_proxy.hpp>\n#include <boost/numeric/ublas/vector_proxy.hpp>\n#include \"SiconosAlgebra.hpp\"\n#include \"SimpleMatrixFriends.hpp\"\n#include \"BlockMatrix.hpp\"\n#include \"SimpleMatrix.hpp\"\n#include \"SiconosVector.hpp\"\n#include \"SiconosMatrixSetBlock.hpp\" // for setBlock\n#include \"SiconosAlgebraTools.hpp\" // for isComparableTo\n#include \"Tools.hpp\"\n#include \"SiconosException.hpp\"\n\nusing  std::cout;\nusing std::endl;\nusing Siconos::Algebra::isComparableTo;\n\n// =================================================\n//                CONSTRUCTORS\n// =================================================\n\nBlockMatrix::BlockMatrix(const SiconosMatrix &m): SiconosMatrix(Siconos::BLOCK), _dimRow(0), _dimCol(0)\n{\n  _tabRow.reset(new Index());\n  _tabCol.reset(new Index());\n  if(m.isBlock())\n  {\n    const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n    unsigned int nbRows = m.numberOfBlocks(0);\n    unsigned int nbCols = m.numberOfBlocks(1);\n    _tabRow->reserve(nbRows);\n    _tabCol->reserve(nbCols);\n\n    // mat construction\n    _mat.reset(new BlocksMat(nbRows, nbCols, nbRows * nbCols));\n\n    unsigned int i, j;\n    ConstBlocksIterator1 it1;\n    ConstBlocksIterator2 it2;\n    bool firstLoop = true;\n    // We scan all the blocks of m ...\n    for(it1 = mB._mat->begin1(); it1 != mB._mat->end1(); ++it1)\n    {\n      _dimRow += (*(it1.begin()))->size(0);\n      _tabRow->push_back(_dimRow);\n      for(it2 = it1.begin(); it2 != it1.end(); ++it2)\n      {\n        i = it2.index1();\n        j = it2.index2();\n        if((*it2)->isBlock())   // if the current matrix is a blockMatrix\n          _mat->insert_element(i, j, std::shared_ptr<SiconosMatrix>(new BlockMatrix(**it2)));\n        else\n          _mat->insert_element(i, j, std::shared_ptr<SiconosMatrix>(new SimpleMatrix(**it2)));\n        // _dimCol must be incremented only at first \"column-loop\"\n        if(firstLoop)\n        {\n          _dimCol += (*it2)->size(1);\n          _tabCol->push_back(_dimCol);\n        }\n      }\n      firstLoop = false;\n    }\n  }\n  else // if m is a SimpleMatrix\n  {\n    _tabRow->reserve(1);\n    _tabCol->reserve(1);\n    // _mat construction\n    _mat.reset(new BlocksMat(1, 1, 1));\n    _mat->insert_element(0, 0, std::shared_ptr<SiconosMatrix>(new SimpleMatrix(m)));\n\n    _dimRow = m.size(0);\n    _dimCol = m.size(1);\n    _tabRow->push_back(_dimRow);\n    _tabCol->push_back(_dimCol);\n  }\n}\n\nBlockMatrix::BlockMatrix(const BlockMatrix &m): SiconosMatrix(Siconos::BLOCK), _dimRow(0), _dimCol(0)\n{\n  unsigned int nbRows = m.numberOfBlocks(0);\n  unsigned int nbCols = m.numberOfBlocks(1);\n  _tabRow.reset(new Index());\n  _tabCol.reset(new Index());\n  _tabRow->reserve(nbRows);\n  _tabCol->reserve(nbCols);\n\n  // _mat construction\n  _mat.reset(new BlocksMat(nbRows, nbCols, nbRows * nbCols));\n\n  unsigned int i, j;\n  // We scan all the blocks of m ...\n  ConstBlocksIterator1 it1;\n  ConstBlocksIterator2 it2;\n  bool firstLoop = true;\n  // We scan all the blocks of m ...\n  for(it1 = m._mat->begin1(); it1 != m._mat->end1(); ++it1)\n  {\n    _dimRow += (*(it1.begin()))->size(0);\n    _tabRow->push_back(_dimRow);\n    for(it2 = it1.begin(); it2 != it1.end(); ++it2)\n    {\n      i = it2.index1();\n      j = it2.index2();\n      if((*it2)->isBlock())   // if the current _matrix is a blockMatrix\n        _mat->insert_element(i, j, std::shared_ptr<SiconosMatrix>(new BlockMatrix(**it2)));\n      else\n        _mat->insert_element(i, j, std::shared_ptr<SiconosMatrix>(new SimpleMatrix(**it2)));\n\n      // _dimCol must be incremented only at first \"column-loop\"\n      if(firstLoop)\n      {\n        _dimCol += (*it2)->size(1);\n        _tabCol->push_back(_dimCol);\n      }\n    }\n    firstLoop = false;\n  }\n}\n\nBlockMatrix::BlockMatrix(const std::vector<SP::SiconosMatrix >& m, unsigned int row, unsigned int col):\n  SiconosMatrix(Siconos::BLOCK), _dimRow(0), _dimCol(0)\n{\n  if(m.size() != (row * col))\n    THROW_EXCEPTION(\"number of blocks inconsistent with provided dimensions.\");\n\n  _tabRow.reset(new Index());\n  _tabCol.reset(new Index());\n  _tabRow->reserve(row);\n  _tabCol->reserve(col);\n\n  // _mat construction\n  _mat.reset(new BlocksMat(row, col, row * col));\n\n  unsigned int k = 0;\n  bool firstRowLoop = true;\n  bool firstColLoop = true;\n\n  for(unsigned int i = 0; i < row; ++i)\n  {\n    for(unsigned int j = 0; j < col; ++j)\n    {\n      (*_mat)(i, j) = m[k++];\n\n      // _dimCol must be incremented only at first \"column-loop\"\n      if(firstColLoop)\n      {\n        _dimCol += m[k - 1]->size(1);\n        _tabCol->push_back(_dimCol);\n      }\n      if(firstRowLoop)\n      {\n        _dimRow += m[k - 1]->size(0);\n        _tabRow->push_back(_dimRow);\n        firstRowLoop = false;\n      }\n    }\n    firstColLoop = false;\n    firstRowLoop = true;\n  }\n}\n\nBlockMatrix::BlockMatrix(SP::SiconosMatrix A, SP::SiconosMatrix B, SP::SiconosMatrix C, SP::SiconosMatrix D):\n  SiconosMatrix(Siconos::BLOCK), _dimRow(0), _dimCol(0)\n{\n  if(A->size(0) != B->size(0) || C->size(0) != D->size(0) ||  A->size(1) != C->size(1) ||  B->size(1) != D->size(1))\n    THROW_EXCEPTION(\"inconsistent sizes between A, B, C or D SiconosMatrices.\");\n\n  // _mat = [ A B ]\n  //       [ C D ]\n\n  // _mat construction\n  _mat.reset(new BlocksMat(2, 2, 4));\n\n  _tabRow.reset(new Index());\n  _tabCol.reset(new Index());\n  _tabRow->reserve(2);\n  _tabCol->reserve(2);\n\n  (*_mat)(0, 0) = A;\n  (*_mat)(0, 1) = B;\n  (*_mat)(1, 0) = C;\n  (*_mat)(1, 1) = D;\n  _dimRow = A->size(0);\n  _tabRow->push_back(_dimRow);\n  _dimRow += C->size(0);\n  _tabRow->push_back(_dimRow);\n  _dimCol = A->size(1);\n  _tabCol->push_back(_dimCol);\n  _dimCol += B->size(1);\n  _tabCol->push_back(_dimCol);\n\n}\n\nBlockMatrix::~BlockMatrix()\n{\n\n  _mat->clear();\n\n  _tabRow->clear();\n  _tabCol->clear();\n}\n\n// =================================================\n//    get number of blocks\n// =================================================\n\nunsigned int BlockMatrix::numberOfBlocks(unsigned int dim) const\n{\n  if(dim == 0)\n    return _tabRow->size();\n  else\n    return _tabCol->size();\n}\n\n// =================================================\n//        get Ublas component (dense ...)\n// =================================================\n\n// return the boost dense _matrix of the block (i, j)\nconst DenseMat  BlockMatrix::getDense(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp;\n  tmp = (*_mat)(row, col);\n\n  if(tmp->num() != Siconos::DENSE)\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Dense matrix\");\n\n  return (tmp->getDense());\n}\n\n// return the boost triangular matrix of the block (i, j)\nconst TriangMat BlockMatrix::getTriang(unsigned int row, unsigned int col) const\n{\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::TRIANGULAR)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Triangular matrix\");\n  }\n  return (tmp->getTriang());\n}\n\n// return the boost symmetric matrix of the block (i, j)\nconst SymMat BlockMatrix::getSym(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::SYMMETRIC)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Symmmetric matrix\");\n  }\n  return (tmp->getSym());\n}\n\n// return the boost sparse matrix of the block (i, j)\nconst SparseMat  BlockMatrix::getSparse(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::SPARSE)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Sparse matrix\");\n  }\n  return (tmp->getSparse());\n}\n\n// return the boost sparse matrix of the block (i, j)\nconst SparseCoordinateMat  BlockMatrix::getSparseCoordinate(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::SPARSE_COORDINATE)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Sparse matrix\");\n  }\n  return (tmp->getSparseCoordinate());\n}\n// return the boost banded matrix of the block (i, j)\nconst BandedMat  BlockMatrix::getBanded(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::BANDED)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Banded matrix\");\n  }\n  return (tmp->getBanded());\n}\n\n// return the boost zero matrix of the block (i, j)\nconst ZeroMat  BlockMatrix::getZero(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::ZERO)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Zero matrix\");\n  }\n  return (tmp->getZero());\n}\n\n// return the boost identity matrix of the block (i, j)\nconst IdentityMat  BlockMatrix::getIdentity(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::IDENTITY)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Identity matrix\");\n  }\n  return (tmp->getIdentity());\n}\n\n// The following functions return the corresponding pointers\nDenseMat*  BlockMatrix::dense(unsigned int row, unsigned int col) const\n{\n\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::DENSE)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Dense matrix\");\n  }\n\n  return (tmp->dense());\n}\n\nTriangMat* BlockMatrix::triang(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::TRIANGULAR)\n  {\n    THROW_EXCEPTION(\"The matrix at (row, col) is not a Triangular matrix\");\n  }\n  return (tmp->triang());\n}\nSymMat* BlockMatrix::sym(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::SYMMETRIC)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Symmmetric matrix\");\n  }\n  return (tmp->sym());\n}\n\nSparseMat*  BlockMatrix::sparse(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::SPARSE)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Sparse matrix\");\n  }\n  return (tmp->sparse());\n}\nSparseCoordinateMat*  BlockMatrix::sparseCoordinate(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::SPARSE_COORDINATE)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Sparse coordinate matrix\");\n  }\n  return (tmp->sparseCoordinate());\n}\n\nBandedMat*  BlockMatrix::banded(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::BANDED)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Banded matrix\");\n  }\n  return (tmp->banded());\n}\n\nZeroMat*  BlockMatrix::zero_mat(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::ZERO)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Zero matrix\");\n  }\n  return (tmp->zero_mat(row, col));\n}\n\nIdentityMat*  BlockMatrix::identity(unsigned int row, unsigned int col) const\n{\n\n  SP::SiconosMatrix tmp = (*_mat)(row, col);\n  if(tmp->num() != Siconos::IDENTITY)\n  {\n    THROW_EXCEPTION(\"the matrix at (row, col) is not a Identity matrix\");\n  }\n  return (tmp->identity());\n}\n\ndouble* BlockMatrix::getArray(unsigned int i, unsigned int j) const\n{\n  SP::SiconosMatrix tmp = (*_mat)(i, j);\n  return tmp->getArray();\n}\n\n// ===========================\n//       fill matrix\n// ===========================\n\nvoid BlockMatrix::zero()\n{\n  BlocksMat::iterator1 it;\n  BlocksMat::iterator2 it2;\n  for(it = _mat->begin1(); it != _mat->end1(); ++it)\n  {\n    for(it2 = it.begin(); it2 != it.end(); ++it2)\n    {\n      (*it2)->zero();\n    }\n  }\n}\n\nvoid BlockMatrix::randomize()\n{\n  BlocksMat::iterator1 it;\n  BlocksMat::iterator2 it2;\n  for(it = _mat->begin1(); it != _mat->end1(); ++it)\n  {\n    for(it2 = it.begin(); it2 != it.end(); ++it2)\n    {\n      (*it2)->randomize();\n    }\n  }\n}\n\nvoid BlockMatrix::randomize_sym()\n{\n  THROW_EXCEPTION(\"not yet implemented for block matrices.\");\n}\n\nvoid BlockMatrix::eye()\n{\n  BlocksMat::iterator1 it;\n  BlocksMat::iterator2 it2;\n\n  for(it = _mat->begin1(); it != _mat->end1(); ++it)\n  {\n    for(it2 = it.begin(); it2 != it.end(); ++it2)\n    {\n      if(it2.index1() == it2.index2())\n        (*it2)->eye();\n      else\n        (*it2)->zero();\n    }\n  }\n}\n\nunsigned int BlockMatrix::size(unsigned int index) const\n{\n  if(index == 0) return _dimRow;\n  else return _dimCol;\n};\n\n\n//=======================\n// set matrix dimensions\n//=======================\n\nvoid BlockMatrix::resize(unsigned int, unsigned int, unsigned int, unsigned int, bool)\n{\n  THROW_EXCEPTION(\"forbidden for block matrices.\");\n}\n\n//=======================\n//       get norm\n//=======================\n\ndouble BlockMatrix::normInf()const\n{\n  double sum = 0, norm = 0;\n  for(unsigned int i = 0; i < size(0); i++)\n  {\n    for(unsigned int j = 0; j < size(1); j++)\n    {\n      sum += (*this)(i, j);\n    }\n    if(fabs(sum) > norm) norm = fabs(sum);\n    sum = 0;\n  }\n  return norm;\n}\n\n//=====================\n// screen display\n//=====================\n\nvoid BlockMatrix::display(void)const\n{\n  std::cout << \"==========> BlockMatrix (\" << numberOfBlocks(0) << \" X \" << numberOfBlocks(1) << \" blocks): \" << std::endl;\n  BlocksMat::iterator1 it;\n  BlocksMat::iterator2 it2;\n  for(it = _mat->begin1(); it != _mat->end1(); ++it)\n  {\n    for(it2 = it.begin(); it2 != it.end(); ++it2)\n    {\n      (*it2)->display();\n    }\n  }\n  std::cout << \"===========================================================================================\" << std::endl;\n}\nvoid BlockMatrix::displayExpert(bool brief)const\n{\n  std::cout << \"==========> BlockMatrix (\" << numberOfBlocks(0) << \" X \" << numberOfBlocks(1) << \" blocks): \" << std::endl;\n  BlocksMat::iterator1 it;\n  BlocksMat::iterator2 it2;\n  for(it = _mat->begin1(); it != _mat->end1(); ++it)\n  {\n    for(it2 = it.begin(); it2 != it.end(); ++it2)\n    {\n      (*it2)->displayExpert(brief);\n    }\n  }\n  std::cout << \"===========================================================================================\" << std::endl;\n}\n\n//=====================\n// convert to a string\n//=====================\n\nstd::string BlockMatrix::toString() const\n{\n  return ::toString(*this);\n}\n\n//=====================\n// convert to an ostream\n//=====================\n\nstd::ostream& operator<<(std::ostream& os, const BlockMatrix& bm)\n{\n  BlocksMat::iterator1 it;\n  BlocksMat::iterator2 it2;\n  os << \"[\" << bm.numberOfBlocks(0) << \",\" << bm.numberOfBlocks(1) << \"](\";\n  for(it = bm._mat->begin1(); it != bm._mat->end1(); ++it)\n  {\n    for(it2 = it.begin(); it2 != it.end(); ++it2)\n    {\n      if(it2 != it.begin()) os << \",\";\n      if(*it2) os << **it2;\n      else os << \"(nil)\";\n    }\n  }\n  os << \")\";\n  return os;\n}\n\n//=============================\n// Elements access (get or set)\n//=============================\n\ndouble& BlockMatrix::operator()(unsigned int row, unsigned int col)\n{\n  unsigned int nbRow = 0;\n  unsigned int nbCol = 0;\n\n  while(row >= (*_tabRow)[nbRow] && nbRow < _tabRow->size())\n    nbRow ++;\n\n  while(col >= (*_tabCol)[nbCol] && nbCol < _tabCol->size())\n    nbCol ++;\n\n  unsigned int posRow = row;\n  unsigned int posCol = col;\n\n  if(nbRow != 0)\n    posRow -= (*_tabRow)[nbRow - 1];\n  if(nbCol != 0)\n    posCol -= (*_tabCol)[nbCol - 1];\n\n\n  SP::SiconosMatrix tmp = (*_mat)(nbRow, nbCol);\n  return (*tmp)(posRow, posCol);\n}\n\ndouble BlockMatrix::operator()(unsigned int row, unsigned int col) const\n{\n\n  unsigned int nbRow = 0;\n  unsigned int nbCol = 0;\n\n  while(row >= (*_tabRow)[nbRow] && nbRow < _tabRow->size())\n    nbRow ++;\n\n  while(col >= (*_tabCol)[nbCol] && nbCol < _tabCol->size())\n    nbCol ++;\n\n  unsigned int posRow = row;\n  unsigned int posCol = col;\n\n  if(nbRow != 0)\n    posRow -= (*_tabRow)[nbRow - 1];\n  if(nbCol != 0)\n    posCol -= (*_tabCol)[nbCol - 1];\n\n  SP::SiconosMatrix tmp = (*_mat)(nbRow, nbCol);\n  return (*tmp)(posRow, posCol);\n}\n\ndouble BlockMatrix::getValue(unsigned int row, unsigned int col) const\n{\n  unsigned int nbRow = 0;\n  unsigned int nbCol = 0;\n\n  while(row >= (*_tabRow)[nbRow] && nbRow < _tabRow->size())\n    nbRow ++;\n\n  while(col >= (*_tabCol)[nbCol] && nbCol < _tabCol->size())\n    nbCol ++;\n\n  unsigned int posRow = row;\n  unsigned int posCol = col;\n\n  if(nbRow != 0)\n    posRow -= (*_tabRow)[nbRow - 1];\n  if(nbCol != 0)\n    posCol -= (*_tabCol)[nbCol - 1];\n\n\n  SP::SiconosMatrix tmp = (*_mat)(nbRow, nbCol);\n  return (*tmp)(posRow, posCol);\n}\n\nvoid BlockMatrix::setValue(unsigned int row, unsigned int col, double value)\n{\n  unsigned int nbRow = 0;\n  unsigned int nbCol = 0;\n\n  while(row >= (*_tabRow)[nbRow] && nbRow < _tabRow->size())\n    nbRow ++;\n\n  while(col >= (*_tabCol)[nbCol] && nbCol < _tabCol->size())\n    nbCol ++;\n\n  unsigned int posRow = row;\n  unsigned int posCol = col;\n\n  if(nbRow != 0)\n    posRow -= (*_tabRow)[nbRow - 1];\n  if(nbCol != 0)\n    posCol -= (*_tabCol)[nbCol - 1];\n\n  SP::SiconosMatrix tmp = (*_mat)(nbRow, nbCol);\n  (*tmp)(posRow, posCol) = value;\n}\n\n//============================================\n// Access (get or set) to blocks of elements\n//============================================\n\nvoid BlockMatrix::getRow(unsigned int r, SiconosVector &v) const\n{\n  unsigned int numRow = 0, posRow = r, start = 0, stop = 0;\n\n  if(r > _dimRow)\n    THROW_EXCEPTION(\"row number is out of range\");\n\n  // Verification of the size of the result vector\n  if(v.size() != _dimCol)\n    THROW_EXCEPTION(\"inconsistent sizes\");\n\n  // Find the row-block number where \"r\" is\n  while(r >= (*_tabRow)[numRow] && numRow < _tabRow->size())\n    numRow ++;\n\n  // Computation of the value of the index row into this block\n  if(numRow != 0)\n    posRow -= (*_tabRow)[numRow - 1];\n\n  for(unsigned int j = 0; j < _tabCol->size(); j++)\n  {\n    start = stop;\n    SP::SiconosMatrix tmp = (*_mat)(numRow, j);\n    stop += tmp->size(1);\n    ublas::subrange(*(v.dense()), start, stop) = ublas::row(*(tmp->dense()), posRow);\n  }\n}\n\nvoid BlockMatrix::getCol(unsigned int c, SiconosVector &v) const\n{\n  unsigned int numCol = 0, posCol = c, start = 0, stop = 0;\n\n  if(c > _dimCol)\n    THROW_EXCEPTION(\"column number is out of range\");\n\n  // Verification of the size of the result vector\n  if(v.size() != _dimRow)\n    THROW_EXCEPTION(\"inconsistent sizes\");\n\n  // Find the column-block number where \"c\" is\n  while(c >= (*_tabCol)[numCol] && numCol < _tabCol->size())\n    numCol ++;\n\n  // Computation of the value of the index column into this block\n  if(numCol != 0)\n    posCol -= (*_tabCol)[numCol - 1];\n\n  for(unsigned int i = 0; i < _tabRow->size(); i++)\n  {\n    start = stop;\n    SP::SiconosMatrix tmp = (*_mat)(i, numCol);\n    stop += tmp->size(0);\n    ublas::subrange(*(v.dense()), start, stop) = ublas::column(tmp->getDense(), posCol);\n  }\n}\n\nvoid BlockMatrix::setRow(unsigned int r, const SiconosVector &v)\n{\n\n  unsigned int numRow = 0, posRow = r, start = 0, stop = 0;\n\n  if(v.size() != _dimCol)\n    THROW_EXCEPTION(\"inconsistent sizes\");\n\n  while(r >= (*_tabRow)[numRow] && numRow < _tabRow->size())\n    numRow ++;\n\n  if(numRow != 0)\n    posRow -= (*_tabRow)[numRow - 1];\n\n  for(unsigned int j = 0; j < _tabCol->size(); j++)\n  {\n    start = stop;\n    SP::SiconosMatrix tmp = (*_mat)(numRow, j);\n    stop += tmp->size(1);\n    ublas::row(*(tmp->dense()), posRow) = ublas::subrange(*(v.dense()), start, stop);\n  }\n}\n\nvoid BlockMatrix::setCol(unsigned int col, const SiconosVector &v)\n{\n\n  unsigned int numCol = 0, posCol = col, start = 0, stop = 0;\n\n  if(v.size() != _dimRow)\n    THROW_EXCEPTION(\"inconsistent sizes\");\n\n  while(col >= (*_tabCol)[numCol] && numCol < _tabCol->size())\n    numCol ++;\n\n  if(numCol != 0)\n    posCol -= (*_tabCol)[numCol - 1];\n\n  for(unsigned int i = 0; i < _tabRow->size(); i++)\n  {\n    start = stop;\n    SP::SiconosMatrix tmp = (*_mat)(i, numCol);\n    stop += tmp->size(0);\n    ublas::column(*(tmp->dense()), posCol) = ublas::subrange(*(v.dense()), start, stop);\n  }\n}\n\nvoid BlockMatrix::addSimple(unsigned int& indRow, unsigned int& indCol, const SiconosMatrix& m)\n{\n  // Add a part of m (starting from (indRow,indCol) to the current matrix.\n  // m must be a SimpleMatrix.\n\n  // At the end of the present function, indRow (resp. indCol) is equal to indRow + the corresponding dimension of the added sub-matrix.\n\n  unsigned int row = m.size(0) - indRow; // number of rows of the block to be added.\n  unsigned int col = m.size(1) - indCol; // number of columns of the block to be added.\n  unsigned int initCol = indCol;\n\n  if(row > _dimRow || col > _dimCol) THROW_EXCEPTION(\"invalid ranges\");\n\n  Siconos::UBLAS_TYPE numM = m.num();\n\n  // iterators through this\n  BlocksMat::iterator1 it1;\n  BlocksMat::iterator2 it2;\n  unsigned int currentRow = 0, currentCol = 0, currentNum;\n  for(it1 = _mat->begin1(); it1 != _mat->end1(); ++it1)\n  {\n    for(it2 = it1.begin(); it2 != it1.end(); ++it2)\n    {\n      if((*it2)->isBlock())   // if the sub-block is also a BlockMatrix ...\n        (std::static_pointer_cast<BlockMatrix>(*it2))->addSimple(indRow, indCol, m);\n\n      else\n      {\n        currentCol = (*it2)->size(1);\n        currentRow = (*it2)->size(0);\n        currentNum = (*it2)->num();\n        if(numM != currentNum) THROW_EXCEPTION(\"inconsistent types.\");\n\n        if(numM == Siconos::DENSE)\n          noalias(*(*it2)->dense()) += ublas::subrange(*m.dense(), indRow, indRow + currentRow, indCol, indCol + currentCol);\n        else if(numM == Siconos::TRIANGULAR)\n          noalias(*(*it2)->triang()) += ublas::subrange(*m.triang(), indRow, indRow + currentRow, indCol, indCol + currentCol);\n        else if(numM == Siconos::SYMMETRIC)\n          noalias(*(*it2)->sym()) += ublas::subrange(*m.sym(), indRow, indRow + currentRow, indCol, indCol + currentCol);\n        else if(numM == Siconos::SPARSE)\n          noalias(*(*it2)->sparse()) += ublas::subrange(*m.sparse(), indRow, indRow + currentRow, indCol, indCol + currentCol);\n        else if(numM == Siconos::BANDED)\n          noalias(*(*it2)->banded()) += ublas::subrange(*m.banded(), indRow, indRow + currentRow, indCol, indCol + currentCol);\n        else if(numM == Siconos::ZERO) {}\n        else\n          THROW_EXCEPTION(\"inconsistent types.\");\n      }\n      indCol += currentCol;\n    }\n    indRow += currentRow;\n    indCol = initCol;\n  }\n}\n\nvoid BlockMatrix::subSimple(unsigned int& indRow, unsigned int& indCol, const SiconosMatrix& m)\n{\n  // subtract a part of m (starting from (indRow,indCol) to the current matrix.\n  // m must be a SimpleMatrix.\n\n  // At the end of the present function, indRow (resp. indCol) is equal to indRow + the corresponding dimension of the subtracted sub-matrix.\n\n  unsigned int row = m.size(0) - indRow; // number of rows of the block to be added.\n  unsigned int col = m.size(1) - indCol; // number of columns of the block to be added.\n  unsigned int initCol = indCol;\n  if(row > _dimRow || col > _dimCol) THROW_EXCEPTION(\"invalid ranges\");\n\n  Siconos::UBLAS_TYPE numM = m.num();\n\n  // iterators through this\n  BlocksMat::iterator1 it1;\n  BlocksMat::iterator2 it2;\n  unsigned int currentRow = 0, currentCol = 0;\n  Siconos::UBLAS_TYPE currentNum;\n  for(it1 = _mat->begin1(); it1 != _mat->end1(); ++it1)\n  {\n    for(it2 = it1.begin(); it2 != it1.end(); ++it2)\n    {\n      if((*it2)->isBlock())   // if the sub-block is also a BlockMatrix ...\n        (std::static_pointer_cast<BlockMatrix>(*it2))->subSimple(indRow, indCol, m);\n\n      else\n      {\n        currentCol = (*it2)->size(1);\n        currentRow = (*it2)->size(0);\n        currentNum = (*it2)->num();\n        if(numM != currentNum) THROW_EXCEPTION(\"inconsistent types.\");\n\n        if(numM == Siconos::DENSE)\n          noalias(*(*it2)->dense()) -= ublas::subrange(*m.dense(), indRow, indRow + currentRow, indCol, indCol + currentCol);\n        else if(numM == Siconos::TRIANGULAR)\n          noalias(*(*it2)->triang()) -= ublas::subrange(*m.triang(), indRow, indRow + currentRow, indCol, indCol + currentCol);\n        else if(numM == Siconos::SYMMETRIC)\n          noalias(*(*it2)->sym()) -= ublas::subrange(*m.sym(), indRow, indRow + currentRow, indCol, indCol + currentCol);\n        else if(numM == Siconos::SPARSE)\n          noalias(*(*it2)->sparse()) -= ublas::subrange(*m.sparse(), indRow, indRow + currentRow, indCol, indCol + currentCol);\n        else if(numM == Siconos::BANDED)\n          noalias(*(*it2)->banded()) -= ublas::subrange(*m.banded(), indRow, indRow + currentRow, indCol, indCol + currentCol);\n        else if(numM == Siconos::ZERO) {}\n        else\n          THROW_EXCEPTION(\"inconsistent types.\");\n      }\n      indCol += currentCol;\n    }\n    indRow += currentRow;\n    indCol = initCol;\n  }\n}\n\n\n//===============\n//  Assignment\n//===============\n\nBlockMatrix& BlockMatrix::operator = (const SiconosMatrix &m)\n{\n  if(&m == this) return *this;  // auto-assignment.\n\n  if(m.size(0) != _dimRow || m.size(1) != _dimCol)\n    THROW_EXCEPTION(\"Left and Right values have inconsistent sizes.\");\n\n  // Warning: we do not reallocate the blocks, but only copy the values. This means that\n  // all blocks are already allocated and that dim of m and mat are to be consistent.\n  // Thus, _tabRow and _tabCol remains unchanged.\n  // If m and mat are not \"block-consistent\", we use the () operator for a component-wise copy.\n\n  if(m.isBlock())\n  {\n    if(isComparableTo(*this, m))\n    {\n      const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n      // iterators through this\n      BlocksIterator1 it1;\n      BlocksIterator2 it2;\n      // iterators through m\n      ConstBlocksIterator1 itM1 = mB._mat->begin1();\n      ConstBlocksIterator2 itM2;\n\n      for(it1 = _mat->begin1(); it1 != _mat->end1(); ++it1)\n      {\n        itM2 = itM1.begin();\n        for(it2 = it1.begin(); it2 != it1.end(); ++it2)\n        {\n          (**it2) = (**itM2);\n          itM2++; // increment column pos. in m.\n        }\n        itM1++; // increment row pos. in m.\n      }\n    }\n    else\n    {\n      for(unsigned int i = 0; i < _dimRow; ++i)\n        for(unsigned int j = 0; j < _dimCol; ++j)\n          (*this)(i, j) = m(i, j);\n    }\n  }\n  else // if m is a SimpleMatrix\n  {\n    BlocksIterator1 it;\n    BlocksIterator2 it2;\n    unsigned int posRow = 0;\n    unsigned int posCol = 0;\n    Index subDim(2);\n    Index subPos(4);\n\n    for(it = _mat->begin1(); it != _mat->end1(); ++it)\n    {\n      for(it2 = it.begin(); it2 != it.end(); ++it2)\n      {\n        // a sub-block of m is copied into this\n        subDim[0] = (*it2)->size(0);\n        subDim[1] = (*it2)->size(1);\n        subPos[0] = posRow;\n        subPos[1] = posCol;\n        subPos[2] = 0;\n        subPos[3] = 0;\n        setBlock(createSPtrConstSiconosMatrix(m), *it2, subDim, subPos);\n        posCol += subDim[1];\n      }\n      posRow += (*it)->size(0);\n      posCol = 0;\n    }\n  }\n\n  return *this;\n}\n\nBlockMatrix& BlockMatrix::operator = (const BlockMatrix &m)\n{\n  if(&m == this) return *this;  // auto-assignment.\n\n  if(m.size(0) != _dimRow || m.size(1) != _dimCol)\n    THROW_EXCEPTION(\"Left and Right values have inconsistent sizes.\");\n\n  // Warning: we do not reallocate the blocks, but only copy the values. This means that\n  // all blocks are already allocated and that dim of m and mat are to be consistent.\n  // Thus, _tabRow and _tabCol remains unchanged.\n  // If m and mat are not \"block-consistent\", we use the () operator for a componet-wise copy.\n\n  if(isComparableTo(*this, m))\n  {\n    const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n    // iterators through this\n    BlocksIterator1 it1;\n    BlocksIterator2 it2;\n    // iterators through m\n    ConstBlocksIterator1 itM1 = mB._mat->begin1();\n    ConstBlocksIterator2 itM2;\n\n    for(it1 = _mat->begin1(); it1 != _mat->end1(); ++it1)\n    {\n      itM2 = itM1.begin();\n      for(it2 = it1.begin(); it2 != it1.end(); ++it2)\n      {\n        (**it2) = (**itM2);\n        itM2++; // increment column pos. in m.\n      }\n      itM1++; // increment row pos. in m.\n    }\n  }\n  else\n  {\n    for(unsigned int i = 0; i < _dimRow; ++i)\n      for(unsigned int j = 0; j < _dimCol; ++j)\n        (*this)(i, j) = m(i, j);\n  }\n  return *this;\n}\n\nBlockMatrix& BlockMatrix::operator = (const DenseMat &m)\n{\n  THROW_EXCEPTION(\"Not yet implemented.\");\n  return *this;\n}\n\n//=================================\n// Op. and assignment (+=, -= ... )\n//=================================\n\nBlockMatrix& BlockMatrix::operator += (const SiconosMatrix &m)\n{\n  if(&m == this)\n  {\n    BlocksMat::iterator1 it1;\n    BlocksMat::iterator2 it2;\n    for(it1 = _mat->begin1(); it1 != _mat->end1(); ++it1)\n    {\n      for(it2 = it1.begin(); it2 != it1.end(); ++it2)\n      {\n        **it2 += **it2;\n      }\n    }\n    return *this;\n  }\n\n  if(m.size(0) != _dimRow || m.size(1) != _dimCol)\n    THROW_EXCEPTION(\"Left and Right values have inconsistent sizes.\");\n\n  if(m.isBlock())\n  {\n    if(isComparableTo(m, *this))\n    {\n      const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n      // iterators through this\n      BlocksMat::iterator1 it1;\n      BlocksMat::iterator2 it2;\n      // iterators through m\n      BlocksMat::const_iterator1 itM1 = mB._mat->begin1();\n      BlocksMat::const_iterator2 itM2;\n\n      for(it1 = _mat->begin1(); it1 != _mat->end1(); ++it1)\n      {\n        itM2 = itM1.begin();\n        for(it2 = it1.begin(); it2 != it1.end(); ++it2)\n        {\n          (**it2) += (**itM2);\n          itM2++; // increment column pos. in m.\n        }\n        itM1++; // increment row pos. in m.\n      }\n    }\n    else\n    {\n      for(unsigned int i = 0; i < _dimRow; ++i)\n        for(unsigned int j = 0; j < _dimCol; ++j)\n          (*this)(i, j) += m(i, j);\n    }\n  }\n  else // if m is a SimpleMatrix\n  {\n    unsigned int indRow = 0, indCol = 0;\n    addSimple(indRow, indCol, m); // a sub-block of m is added to each block of this.\n  }\n  return *this;\n}\n\nBlockMatrix& BlockMatrix::operator -= (const SiconosMatrix &m)\n{\n  if(&m == this)\n  {\n    BlocksMat::iterator1 it1;\n    BlocksMat::iterator2 it2;\n    for(it1 = _mat->begin1(); it1 != _mat->end1(); ++it1)\n    {\n      for(it2 = it1.begin(); it2 != it1.end(); ++it2)\n      {\n        **it2 -= **it2;\n      }\n    }\n    return *this;\n  }\n\n  if(m.size(0) != _dimRow || m.size(1) != _dimCol)\n    THROW_EXCEPTION(\"Left and Right values have inconsistent sizes.\");\n\n  if(m.isBlock())\n  {\n    if(isComparableTo(m, *this))\n    {\n      const BlockMatrix& mB = static_cast<const BlockMatrix&>(m);\n      // iterators through this\n      BlocksMat::iterator1 it1;\n      BlocksMat::iterator2 it2;\n      // iterators through m\n      BlocksMat::const_iterator1 itM1 = mB._mat->begin1();\n      BlocksMat::const_iterator2 itM2;\n\n      for(it1 = _mat->begin1(); it1 != _mat->end1(); ++it1)\n      {\n        itM2 = itM1.begin();\n        for(it2 = it1.begin(); it2 != it1.end(); ++it2)\n        {\n          (**it2) -= (**itM2);\n          itM2++; // increment column pos. in m.\n        }\n        itM1++; // increment row pos. in m.\n      }\n    }\n    else\n    {\n      for(unsigned int i = 0; i < _dimRow; ++i)\n        for(unsigned int j = 0; j < _dimCol; ++j)\n          (*this)(i, j) -= m(i, j);\n    }\n  }\n  else // if m is a SimpleMatrix\n  {\n    unsigned int indRow = 0, indCol = 0;\n    subSimple(indRow, indCol, m); // a sub-block of m is subtracted to each block of this.\n  }\n  return *this;\n}\n\nvoid BlockMatrix::trans()\n{\n  THROW_EXCEPTION(\"not yet implemented.\");\n}\n\nvoid BlockMatrix::trans(const SiconosMatrix &m)\n{\n  THROW_EXCEPTION(\"not yet implemented.\");\n}\n\nvoid BlockMatrix::PLUFactorizationInPlace()\n{\n  THROW_EXCEPTION(\"not yet implemented for Block Matrices.\");\n}\nvoid BlockMatrix::Factorize()\n{\n  THROW_EXCEPTION(\"not yet implemented for Block Matrices.\");\n}\n\nvoid BlockMatrix::PLUInverseInPlace()\n{\n  THROW_EXCEPTION(\"not yet implemented for Block Matrices.\");\n}\n\nvoid BlockMatrix::PLUForwardBackwardInPlace(SiconosMatrix &B)\n{\n  THROW_EXCEPTION(\"not yet implemented for Block Matrices.\");\n}\nvoid BlockMatrix::Solve(SiconosMatrix &B)\n{\n  THROW_EXCEPTION(\"not yet implemented for Block Matrices.\");\n}\n\nvoid BlockMatrix::PLUForwardBackwardInPlace(SiconosVector &B)\n{\n  THROW_EXCEPTION(\"not yet implemented for Block Matrices.\");\n}\nvoid BlockMatrix::Solve(SiconosVector &B)\n{\n  THROW_EXCEPTION(\"not yet implemented for Block Matrices.\");\n}\n\nSP::SiconosMatrix BlockMatrix::block(unsigned int row, unsigned int col)\n{\n  return (*_mat)(row, col);\n}\n\nSPC::SiconosMatrix BlockMatrix::block(unsigned int row, unsigned int col) const\n{\n  return std::shared_ptr<SiconosMatrix>((*_mat)(row, col));\n}\n\nsize_t BlockMatrix::nnz(double tol)\n{\n  size_t nnz = 0;\n  BlocksMat::iterator1 it;\n  BlocksMat::iterator2 it2;\n  for(it = _mat->begin1(); it != _mat->end1(); ++it)\n  {\n    for(it2 = it.begin(); it2 != it.end(); ++it2)\n      nnz += (**it2).nnz();\n  }\n  return nnz;\n}\n\n", "meta": {"hexsha": "803d7af4a90adc341ba0d6dc641dc443dd3b96dd", "size": 33354, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kernel/src/utils/SiconosAlgebra/BlockMatrix.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kernel/src/utils/SiconosAlgebra/BlockMatrix.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kernel/src/utils/SiconosAlgebra/BlockMatrix.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7487520799, "max_line_length": 141, "alphanum_fraction": 0.5945313905, "num_tokens": 9922, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.2052578137457347}}
{"text": "/*\n    Copyright (c) 2014, Philipp Krähenbühl\n    All rights reserved.\n\t\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are met:\n        * Redistributions of source code must retain the above copyright\n        notice, this list of conditions and the following disclaimer.\n        * Redistributions in binary form must reproduce the above copyright\n        notice, this list of conditions and the following disclaimer in the\n        documentation and/or other materials provided with the distribution.\n        * Neither the name of the Stanford University nor the\n        names of its contributors may be used to endorse or promote products\n        derived from this software without specific prior written permission.\n\t\n    THIS SOFTWARE IS PROVIDED BY Philipp Krähenbühl ''AS IS'' AND ANY\n    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n    DISCLAIMED. IN NO EVENT SHALL Philipp Krähenbühl BE LIABLE FOR ANY\n    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\t LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\t ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n#include \"util/win_util.h\"\n#include \"util/threading.h\"\n#include \"splitcriterion.h\"\n#include <random>\n#include <stdexcept>\n#include <iostream>\n#include <Eigen/SVD>\n#include <Eigen/Eigenvalues>\n\nint SplitCriterion::repLabel() const {\n\treturn -1;\n}\nclass LabeledSplit: public SplitCriterion {\nprotected:\n\tVectorXi lbl_;\n\tVectorXf weight_;\n\tvirtual float score( const ArrayXf & p ) const = 0;\npublic:\n\tLabeledSplit(){\n\t}\n\tLabeledSplit( const RMatrixXf & lbl, const VectorXf & weight ): weight_(weight) {\n\t\tif( lbl.cols()!= 1 )\n\t\t\tthrow std::invalid_argument( \"Only 1d labels supported!\" );\n\t\tlbl_ = lbl.cast<int>();\n\t}\n\tvirtual float gain( const VectorXb& is_left ) const {\n\t\tconst int N = lbl_.maxCoeff()+1;\n\t\tArrayXf wl = 1e-20*ArrayXf::Ones(N), wr = 1e-20*ArrayXf::Ones(N);\n\t\tfor( int i=0; i<(int)lbl_.size(); i++ )\n\t\t\tif( is_left[i] )\n\t\t\t\twl[lbl_[i]] += weight_[i];\n\t\t\telse\n\t\t\t\twr[lbl_[i]] += weight_[i];\n\t\tconst float l = wl.sum(), r = wr.sum();\n\t\tconst float sl = score(wl/l), sr = score(wr/r);\n\t\tprintf(\"%d  %d\\n\", (int)l, (int)r );\n\t\treturn score( (wl+wr)/(l+r) ) - (sl*l/(l+r) + sr*r/(l+r));\n\t}\n\tvirtual float bestThreshold( const VectorXf & f, float * gain ) const {\n\t\tconst int N = lbl_.maxCoeff()+1;\n\t\tconst float EPS=1e-6;\n\t\t// Create the feature/label pairs\n\t\tstd::vector< std::pair<float,int> > elements( f.size() );\n\t\tfor( int i=0; i<f.size(); i++ )\n\t\t\telements[i] = std::make_pair( f[i], i );\n\t\tstd::sort(elements.begin(), elements.end() );\n\t\t\n\t\t// And compute the probabilities and cirterion\n\t\tArrayXf wl = 1e-20*ArrayXf::Ones(N), wr = 1e-20*ArrayXf::Ones(N);\n\t\tfor( int i=0; i<lbl_.size(); i++ )\n\t\t\twr[ lbl_[i] ] += weight_[i];\n\t\t\n\t\t// Initialize the thresholds\n\t\tfloat best_gain = 0, tbest = (elements.front().first+elements.back().first)/2, last_t = elements.front().first;\n\t\tconst float tot_s = score( wr/wr.sum() );\n\t\t// Find the best threshold\n\t\tfor( auto i: elements ) {\n\t\t\tconst float t = i.first;\n\t\t\tconst int j = i.second;\n\t\t\t// If there is a threshold\n\t\t\tif( t - last_t > EPS ) {\n\t\t\t\t// Compute the score\n\t\t\t\tconst float l = wl.sum(), r = wr.sum();\n\t\t\t\tconst float sl = score(wl/l), sr = score(wr/r);\n\t\t\t\tconst float g = tot_s - ( sl*l/(l+r) + sr*r/(l+r) );\n\t\t\t\tif( g > best_gain ) {\n\t\t\t\t\tbest_gain = g;\n\t\t\t\t\ttbest = (last_t+t)/2.;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Update the probabilities\n\t\t\twl[ lbl_[j] ] += weight_[j];\n\t\t\twr[ lbl_[j] ] -= weight_[j];\n\t\t\tlast_t = t;\n\t\t}\n\t\tif( gain )\n\t\t\t*gain = best_gain;\n\t\treturn tbest;\n\t}\n\tvirtual bool is_pure( ) const {\n\t\tfor( int i=1; i<lbl_.size(); i++ )\n\t\t\tif( lbl_[0] != lbl_[i] )\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\tvirtual int repLabel() const {\n\t\t// Count the label occurence\n\t\tconst int n_lbl = lbl_.maxCoeff()+1;\n\t\tVectorXi lbl_cnt = VectorXi::Zero( n_lbl );\n\t\tfor( int i=0; i<lbl_.size(); i++ )\n\t\t\tlbl_cnt[lbl_[i]]++;\n\t\t// And return the maximum\n\t\tint rep_lbl = 0;\n\t\tfor( int i=0; i<lbl_.size(); i++ )\n\t\t\tif( lbl_cnt[lbl_[rep_lbl]] < lbl_cnt[lbl_[i]] )\n\t\t\t\trep_lbl = i;\n\t\treturn rep_lbl;\n\t}\n};\nclass GiniSplit: public LabeledSplit {\npublic:\n\ttemplate<typename ...ARGS> GiniSplit(ARGS... args) :LabeledSplit(args...) {}\n\tvirtual std::shared_ptr<SplitCriterion> create( const RMatrixXf & lbl, const VectorXf & weight ) const {\n\t\treturn std::make_shared<GiniSplit>( lbl, weight );\n\t}\n\tvirtual float score( const ArrayXf & p ) const {\n\t\treturn (p*(1-p)).sum();\n\t}\n};\nclass EntropySplit: public LabeledSplit {\npublic:\n\ttemplate<typename ...ARGS> EntropySplit(ARGS... args) :LabeledSplit(args...) {}\n\tvirtual std::shared_ptr<SplitCriterion> create( const RMatrixXf & lbl, const VectorXf & weight ) const {\n\t\treturn std::make_shared<EntropySplit>( lbl, weight );\n\t}\n\tvirtual float score( const ArrayXf & p ) const {\n\t\treturn -(p*(p+1e-20).log()).sum();\n\t}\n};\nRMatrixXf pairwiseDistance( const RMatrixXf & X, int N ) {\n\tstatic std::mt19937 gen;\n\t// Do a random pairwise projection\n\tconst int M = X.cols();\n\tRMatrixXf r( X.rows(), N );\n\tstd::vector<int> o1(N), o2(N);\n\tfor( int i=0; i<N; i++ ) {\n\t\to1[i] = 1+(gen()%(M-1));\n\t\to2[i] = gen()%o1[i];\n\t}\n\tfor( int i=0; i<X.rows(); i++ )\n\t\tfor( int j=0; j<N; j++ )\n\t\t\tr(i,j) = ((X(i,o1[j]) == X(i,o2[j])));\n\treturn r;\n}\n// RMatrixXf pairwiseDistance( const RMatrixXf & X, int N ) {\n// \tstatic std::mt19937 gen;\n// \t// Do a random pairwise projection\n// \tconst int M = X.cols();\n// \t\n// \t// Figure out if a column has more than one value\n// \tVectorXb singleton = VectorXb::Ones( M );\n// \tVectorXf v = X.row(0);\n// \tfor( int i=1; i<X.rows(); i++ )\n// \t\tfor( int j=0; j<M; j++ )\n// \t\t\tif( singleton[j] )\n// \t\t\t\tsingleton[j] = (v[j] == X(i,j));\n// \tint N_ns = (singleton.array() == 0).cast<int>().sum();\n// \tif( N_ns == 0 )\n// \t\treturn RMatrixXf::Zero( X.rows(), 1 );\n// \t\n// \t// Adjust N to the fewer samples in theory by a factor of 1-(1-N_ns/M)^2,\n// \t// in practice 2*N_ns/M seems close enough [without the qudartic term]\n// \tif( 2*N_ns < M )\n// \t\tN = 2*N*N_ns / M;\n// \t\n// \tVectorXi good_o( N_ns );\n// \tfor( int i=0,j=0; i<M; i++ )\n// \t\tif( !singleton[i] )\n// \t\t\tgood_o[j++] = i;\n// \t\t\t\n// \tRMatrixXf r( X.rows(), N );\n// \tstd::vector<int> o1(N), o2(N);\n// \tfor( int i=0; i<N; i++ ) {\n// \t\to1[i] = good_o[gen()%N_ns];\n// \t\to2[i] = gen()%M;\n// \t}\n// \tfor( int i=0; i<X.rows(); i++ )\n// \t\tfor( int j=0; j<N; j++ ) {\n// \t\t\tr(i,j) = (X(i,o1[j]) != X(i,o2[j]));\n// \t\t}\n// \treturn r;\n// }\nVectorXf project1D( const RMatrixXf & Y, int * rep_label=NULL ) {\n\tconst bool fast = true, very_fast = true;\n\t// Remove the DC\n\tRMatrixXf dY = Y.rowwise() - Y.colwise().mean();\n\t// ... and use (pc > 0)\n\tVectorXf lbl = VectorXf::Zero( Y.rows() );\n\t// Find the largest PC\n\tif( very_fast ) {\n\t\t// Find the PC using poweriterations\n\t\tlbl.setRandom();\n\t\tfloat old_v = 0;\n\t\tfor( int it=0; it<20; it++ ){\n\t\t\t// Normalize\n\t\t\tlbl.array() /= lbl.norm()+std::numeric_limits<float>::min();\n\t\t\tlbl = dY*(dY.transpose()*lbl);\n\t\t\tfloat v = lbl.norm();\n\t\t\tif( fabs(v-old_v) < 1e-4*fabs(v) )\n\t\t\t\tbreak;\n\t\t\told_v = v;\n\t\t}\n\t\tVectorXf tmp = dY.transpose()*lbl;\n\t\ttmp.array() /= tmp.norm()+std::numeric_limits<float>::min();\n\t\tlbl = dY*tmp;\n\t}\n\telse if(fast) {\n\t\t// Compute the eigen values of the covariance (and project onto the largest eigenvector)\n\t\tMatrixXf cov = dY.transpose()*dY;\n\t\tSelfAdjointEigenSolver<MatrixXf> eigensolver(0.5*(cov+cov.transpose()));\n\t\tMatrixXf ev = eigensolver.eigenvectors();\n\t\tlbl = dY * ev.col( ev.cols()-1 );\n\t}\n\telse {\n\t\t// Use the SVD\n\t\tJacobiSVD<RMatrixXf> svd = dY.jacobiSvd(ComputeThinU | ComputeThinV );\n\t\t// Project onto the largest PC\n\t\tlbl = svd.matrixU().col(0) * svd.singularValues()[0];\n\t}\n\t// Find the representative label\n\tif( rep_label )\n\t\tdY.array().square().rowwise().sum().minCoeff( rep_label );\n\t\n\treturn (lbl.array() > 0).cast<float>();\n}\n\ntemplate<typename Split> class Structured: public Split {\nprotected:\n\tint rep_label_;\n\tint n_struc_samples_;\npublic:\n\tStructured( int n_struc_samples = 256 ):n_struc_samples_(n_struc_samples){}\n\tStructured( const RMatrixXf & lbl, const VectorXf & weight, int n_struc_samples ): Split( project1D(pairwiseDistance(lbl,n_struc_samples),&rep_label_), weight ) {\n\t}\n\tvirtual std::shared_ptr< SplitCriterion > create( const RMatrixXf & lbl, const VectorXf & weight ) const {\n\t\treturn std::make_shared< Structured<Split> >( lbl, weight, n_struc_samples_ );\n\t}\n\tvirtual int repLabel() const {\n\t\treturn rep_label_;\n\t}\n};\nstd::shared_ptr<SplitCriterion> entropySplit() {\n\treturn std::make_shared<EntropySplit>();\n}\nstd::shared_ptr<SplitCriterion> giniSplit() {\n\treturn std::make_shared<GiniSplit>();\n}\nstd::shared_ptr<SplitCriterion> structEntropySplit( int n_struc_samples ) {\n\treturn std::make_shared< Structured<EntropySplit> >( n_struc_samples );\n}\nstd::shared_ptr<SplitCriterion> structGiniSplit( int n_struc_samples ) {\n\treturn std::make_shared< Structured<GiniSplit> >( n_struc_samples );\n}\n", "meta": {"hexsha": "f88bef6e246519725fe26c3cae9b150c57f44b52", "size": 9312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sd_maskrcnn/gop/lib/learning/splitcriterion.cpp", "max_stars_repo_name": "PingCheng-Wei/SD-MaskRCNN", "max_stars_repo_head_hexsha": "8995945c38f510333cdcbdd409a189e1ad742ee2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 183.0, "max_stars_repo_stars_event_min_datetime": "2018-10-12T05:16:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T13:56:56.000Z", "max_issues_repo_path": "sd_maskrcnn/gop/lib/learning/splitcriterion.cpp", "max_issues_repo_name": "PingCheng-Wei/SD-MaskRCNN", "max_issues_repo_head_hexsha": "8995945c38f510333cdcbdd409a189e1ad742ee2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2018-10-25T06:50:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T08:51:35.000Z", "max_forks_repo_path": "sd_maskrcnn/gop/lib/learning/splitcriterion.cpp", "max_forks_repo_name": "PingCheng-Wei/SD-MaskRCNN", "max_forks_repo_head_hexsha": "8995945c38f510333cdcbdd409a189e1ad742ee2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2018-10-27T10:01:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:56:29.000Z", "avg_line_length": 34.4888888889, "max_line_length": 163, "alphanum_fraction": 0.6471219931, "num_tokens": 2875, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.4035668537353746, "lm_q1q2_score": 0.20493603635665358}}
{"text": "//==============================================================================\n//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II\n//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI\n//\n//          Distributed under the Boost Software License, Version 1.0.\n//                 See accompanying file LICENSE.txt or copy at\n//                     http://www.boost.org/LICENSE_1_0.txt\n//==============================================================================\n#ifndef NT2_LINALG_DETAILS_BLAS_R_HPP_INCLUDED\n#define NT2_LINALG_DETAILS_BLAS_R_HPP_INCLUDED\n\n#include <complex>\n#include <boost/preprocessor/cat.hpp>\n#include <nt2/linalg/details/blas/blas1.hpp>\n#include <nt2/linalg/details/utility/f77_wrapper.hpp>\n\nnamespace nt2 { namespace details\n{\n#define NT2_R(T, PREFIX, SUFFIX)                                            \\\ninline void BOOST_PP_CAT(ger,SUFFIX)( const long int *m, const long int *n  \\\n                                    , const T *al                           \\\n                                    , const T *x, const long int *incx      \\\n                                    , const T *y, const long int *incy      \\\n                                    , const T *a, const long int *lda       \\\n                                    )                                       \\\n{                                                                           \\\n  NT2_F77NAME(BOOST_PP_CAT(PREFIX,ger))(ta,m,n,al,x,incx,y,incy,a,lda);     \\\n}                                                                           \\\n/**/\n\n  // INTERNAL ONLY\n  // gerx A <- {t,c}x*y+A  with x =  u, c or nothing in which case x == y\n  // _GER  ( M, N, ALPHA, X, INCX, Y, INCY, A, LDA ) S, D\n  // _GERU ( M, N, ALPHA, X, INCX, Y, INCY, A, LDA ) C, Z (TRANSPOSE)\n  // _GERC ( M, N, ALPHA, X, INCX, Y, INCY, A, LDA ) C, Z (TRANSCONJUGATE)\n  NT2_R(double, d, )\n  NT2_R(float,  s, )\n  NT2_R(std::complex<double>, z, u)\n  NT2_R(std::complex<float>,  c, u)\n  NT2_R(std::complex<double>, z, c)\n  NT2_R(std::complex<float>,  c, c)\n\n#undef NT2_R\n\n#define NT2_R(T, P1, P2)                                                  \\\ninline void BOOST_PP_CAT(P2,r)( const char * uplo                         \\\n                              , const long int *n                         \\\n                              , const T *al                               \\\n                              , const T *x, const long int *incx          \\\n                              , T *a      , const long int *lda           \\\n                              )                                           \\\n{                                                                         \\\n  NT2_F77NAME(BOOST_PP_CAT(P1,BOOST_PP_CAT(P2,r)))(ta,n,al,x,incx,a,lda); \\\n}                                                                         \\\n/**/\n\n  // INTERNAL ONLY\n  // herx A <- hx*y+hy*x+A\n  // syrx A <- tx*y+ty*x+A\n  // _HER  ( UPLO, N, ALPHA, X, INCX, A, LDA ) C, Z\n  // _SYR  ( UPLO, N, ALPHA, X, INCX, A, LDA ) S, D\n  NT2_R(std::complex<double>, z, he)\n  NT2_R(std::complex<float>,  c, he)\n  NT2_R(std::complex<double>, s, sy)\n  NT2_R(std::complex<float>,  d, sy)\n#undef NT2_R\n\n#define NT2_R(T, P1, P2)                                                    \\\ninline void BOOST_PP_CAT(P2,r)( const char * uplo                           \\\n                              , const long int *n                           \\\n                              , const T *al                                 \\\n                              , const T *x, const long int *incx            \\\n                              , T *ap                                       \\\n                              )                                             \\\n{                                                                           \\\n  BOOST_PP_CAT(BOOST_PP_CAT(P1,BOOST_PP_CAT(P2,r),_))(uplo,n,al,x,incx,ap); \\\n}                                                                           \\\n/**/\n\n  // INTERNAL ONLY\n  // herx A <- hx*y+hy*x+A\n  // syrx A <- tx*y+ty*x+A\n  // _HER  ( UPLO, N, ALPHA, X, INCX, A, LDA ) C, Z\n  // _SYR  ( UPLO, N, ALPHA, X, INCX, A, LDA ) S, D\n  NT2_R(std::complex<double>, z, hp)\n  NT2_R(std::complex<float>,  c, hp)\n  NT2_R(std::complex<double>, s, sp)\n  NT2_R(std::complex<float>,  d, sp)\n#undef NT2_R\n\n#define NT2_R(T, P1, P2)                                                          \\\ninline void BOOST_PP_CAT(P2,r2) ( const char * uplo                               \\\n                                , const long int *n                               \\\n                                , const T *al                                     \\\n                                , const T *x, const long int *ix                  \\\n                                , const T *y, const long int *iy                  \\\n                                , T *a, const long int *lda                       \\\n                                )                                                 \\\n{                                                                                 \\\n  BOOST_PP_CAT(BOOST_PP_CAT(P1,BOOST_PP_CAT(P2,r2),_)(uplo,n,al,x,ix,y,iy,a,lda); \\\n}                                                                                 \\\n/**/\n\n  // INTERNAL ONLY\n  // _HER2 ( UPLO, N, ALPHA, X, INCX, Y, INCY, A, LDA )\n  // _SYR2 ( UPLO, N, ALPHA, X, INCX, Y, INCY, A, LDA )\n  NT2_R(std::complex<double>, z, he)\n  NT2_R(std::complex<float>,  c, he)\n  NT2_R(std::complex<double>, s, sy)\n  NT2_R(std::complex<float>,  d, sy)\n#undef NT2_R\n\n#define NT2_R(T, P1, P2)                                                      \\\ninline void BOOST_PP_CAT(P2,r)( const char * uplo                             \\\n                              , const long int *n                             \\\n                              , const T *al                                   \\\n                              , const T *x, const long int *incx              \\\n                              , T *ap                                         \\\n                              )                                               \\\n{                                                                             \\\n  BOOST_PP_CAT(BOOST_PP_CAT(P1,BOOST_PP_CAT(P2,r2),_))(uplo,n,al,x,incx,ap);  \\\n}                                                                             \\\n/**/\n\n  // INTERNAL ONLY\n  // _HPR  ( UPLO, N, ALPHA, X, INCX, AP )\n  // _SPR  ( UPLO, N, ALPHA, X, INCX, AP )\n  NT2_R(std::complex<double>, z, hp)\n  NT2_R(std::complex<float>,  c, hp)\n  NT2_R(std::complex<double>, s, sp)\n  NT2_R(std::complex<float>,  d, sp)\n#undef NT2_R\n} }\n\n#endif\n", "meta": {"hexsha": "427294afc58887a63cc52ff71321399501da1412", "size": 6616, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/linalg/include/nt2/linalg/details/blas/r.hpp", "max_stars_repo_name": "pbrunet/nt2", "max_stars_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 34.0, "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_issues_repo_path": "modules/core/linalg/include/nt2/linalg/details/blas/r.hpp", "max_issues_repo_name": "pbrunet/nt2", "max_issues_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/linalg/include/nt2/linalg/details/blas/r.hpp", "max_forks_repo_name": "pbrunet/nt2", "max_forks_repo_head_hexsha": "2aeca0f6a315725b335efd5d9dc95d72e10a7fb7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "avg_line_length": 48.6470588235, "max_line_length": 83, "alphanum_fraction": 0.3523276904, "num_tokens": 1534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5273165233795671, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20492470676515603}}
{"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>\n// Copyright (c) 2021 Ilias Khairullin <ilias@nil.foundation>\n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_HASH_DETAIL_H2F_FUNCTIONS_HPP\n#define CRYPTO3_HASH_DETAIL_H2F_FUNCTIONS_HPP\n\n#include <cstdint>\n#include <array>\n#include <vector>\n#include <iterator>\n#include <type_traits>\n\n#include <boost/assert.hpp>\n#include <boost/static_assert.hpp>\n#include <boost/concept/assert.hpp>\n\n#include <nil/marshalling/endianness.hpp>\n#include <nil/marshalling/algorithms/pack.hpp>\n#include <nil/crypto3/marshalling/multiprecision/types/integral.hpp>\n\n#include <nil/crypto3/algebra/type_traits.hpp>\n\n#include <nil/crypto3/detail/strxor.hpp>\n\n#include <nil/crypto3/hash/algorithm/hash.hpp>\n\n#include <nil/crypto3/hash/detail/h2c/h2c_policy.hpp>\n\nnamespace nil {\n    namespace crypto3 {\n        namespace hashes {\n            namespace detail {\n                template<std::size_t k, std::size_t len_in_bytes, typename Hash,\n                         /// Hash::digest_type is required to be uint8_t[]\n                         typename = typename std::enable_if<std::is_same<\n                             std::uint8_t,\n                             typename std::iterator_traits<typename Hash::digest_type>::value_type>::value>::type>\n                class expand_message_xmd {\n                    // https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-10#section-5.4.1\n                    static_assert(Hash::block_bits % 8 == 0, \"r_in_bytes is not a multiple of 8\");\n                    static_assert(Hash::digest_bits % 8 == 0, \"b_in_bytes is not a multiple of 8\");\n                    static_assert(Hash::digest_bits >= 2 * k, \"k-bit collision resistance is not fulfilled\");\n                    static_assert(len_in_bytes < 0x10000, \"len_in_bytes should be less than 0x10000\");\n\n                    constexpr static std::size_t b_in_bytes = Hash::digest_bits / 8;\n                    constexpr static std::size_t r_in_bytes = Hash::block_bits / 8;\n                    constexpr static std::array<std::uint8_t, 2> l_i_b_str = {\n                        static_cast<std::uint8_t>(len_in_bytes >> 8u), static_cast<std::uint8_t>(len_in_bytes % 0x100)};\n                    constexpr static std::size_t ell = static_cast<std::size_t>(len_in_bytes / b_in_bytes) +\n                                                       static_cast<std::size_t>(len_in_bytes % b_in_bytes != 0);\n                    constexpr static const std::array<std::uint8_t, r_in_bytes> Z_pad {0};\n\n                    // https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-10#section-5.4.1\n                    static_assert(ell <= 255, \"ell should be less than 256\");\n\n                public:\n                    typedef std::array<std::uint8_t, len_in_bytes> result_type;\n                    typedef accumulator_set<Hash> internal_accumulator_type;\n\n                    static inline void init_accumulator(internal_accumulator_type &acc) {\n                        hash<Hash>(Z_pad, acc);\n                    }\n\n                    template<typename InputRange>\n                    static inline void update(internal_accumulator_type &acc, const InputRange &range) {\n                        BOOST_CONCEPT_ASSERT((boost::SinglePassRangeConcept<InputRange>));\n\n                        hash<Hash>(range, acc);\n                    }\n\n                    template<typename InputIterator>\n                    static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {\n                        BOOST_CONCEPT_ASSERT((boost::InputIteratorConcept<InputIterator>));\n\n                        hash<Hash>(first, last, acc);\n                    }\n\n                    template<typename DstRange>\n                    static inline typename std::enable_if<\n                        std::is_same<std::uint8_t,\n                                     typename std::iterator_traits<typename DstRange::iterator>::value_type>::value,\n                        result_type>::type\n                        process(internal_accumulator_type &b0_acc, const DstRange &dst) {\n\n                        auto dst_size = std::distance(std::cbegin(dst), std::cend(dst));\n                        assert(dst_size >= 16 && dst_size <= 255);\n\n                        hash<Hash>(l_i_b_str, b0_acc);\n                        hash<Hash>(std::array<std::uint8_t, 1> {0}, b0_acc);\n                        hash<Hash>(dst, b0_acc);\n                        hash<Hash>(std::array<std::uint8_t, 1> {static_cast<std::uint8_t>(dst_size)}, b0_acc);\n                        typename Hash::digest_type b0 = ::nil::crypto3::accumulators::extract::hash<Hash>(b0_acc);\n\n                        result_type uniform_bytes;\n                        internal_accumulator_type bi_acc;\n                        hash<Hash>(b0, bi_acc);\n                        hash<Hash>(std::array<std::uint8_t, 1> {1}, bi_acc);\n                        hash<Hash>(dst, bi_acc);\n                        hash<Hash>(std::array<std::uint8_t, 1> {static_cast<std::uint8_t>(dst_size)}, bi_acc);\n                        typename Hash::digest_type bi = ::nil::crypto3::accumulators::extract::hash<Hash>(bi_acc);\n                        std::copy(bi.begin(), bi.end(), uniform_bytes.begin());\n\n                        typename Hash::digest_type xored_b;\n                        for (std::size_t i = 2; i <= ell; i++) {\n                            internal_accumulator_type bi_acc;\n                            ::nil::crypto3::detail::strxor(b0, bi, xored_b.begin());\n                            hash<Hash>(xored_b, bi_acc);\n                            hash<Hash>(std::array<std::uint8_t, 1> {static_cast<std::uint8_t>(i)}, bi_acc);\n                            hash<Hash>(dst, bi_acc);\n                            hash<Hash>(std::array<std::uint8_t, 1> {static_cast<std::uint8_t>(dst_size)}, bi_acc);\n                            bi = ::nil::crypto3::accumulators::extract::hash<Hash>(bi_acc);\n                            std::copy(bi.begin(), bi.end(), uniform_bytes.begin() + (i - 1) * b_in_bytes);\n                        }\n                        return uniform_bytes;\n                    }\n                };\n            }    // namespace detail\n        }        // namespace hashes\n    }            // namespace crypto3\n}    // namespace nil\n\n#endif    // CRYPTO3_HASH_DETAIL_H2F_FUNCTIONS_HPP\n", "meta": {"hexsha": "b7e503f469c52b93625692a0c27868608afc82e7", "size": 7591, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/hash/detail/h2f/h2f_functions.hpp", "max_stars_repo_name": "NilFoundation/hash", "max_stars_repo_head_hexsha": "861600cac117fa2661998d46ea1968e9697a5539", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/hash/detail/h2f/h2f_functions.hpp", "max_issues_repo_name": "NilFoundation/hash", "max_issues_repo_head_hexsha": "861600cac117fa2661998d46ea1968e9697a5539", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2019-06-07T23:11:49.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-12T00:09:30.000Z", "max_forks_repo_path": "include/nil/crypto3/hash/detail/h2f/h2f_functions.hpp", "max_forks_repo_name": "nemo1369/hash", "max_forks_repo_head_hexsha": "861600cac117fa2661998d46ea1968e9697a5539", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-01-11T15:35:55.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-11T15:35:55.000Z", "avg_line_length": 52.3517241379, "max_line_length": 120, "alphanum_fraction": 0.5681728363, "num_tokens": 1623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20459025532056946}}
{"text": "#include \"APSimulator.hpp\"\n\n#include \"RegularStimulus.hpp\"\n#include \"SimpleStimulus.hpp\"\n#include \"MultiStimulus.hpp\"\n#include \"AbstractIvpOdeSolver.hpp\"\n#include <boost/shared_ptr.hpp>\n#include <boost/lexical_cast.hpp>\n#include <boost/tokenizer.hpp>\n#include \"BoostFilesystem.hpp\"\n#include \"RandomNumberGenerator.hpp\"\n\n#include \"CheckpointArchiveTypes.hpp\"\n#include \"ArchiveLocationInfo.hpp\"\n#include \"SteadyStateRunner.hpp\"\n\n#include \"hodgkin_huxley_squid_axon_model_1952_modifiedCvode.hpp\"\n#include \"beeler_reuter_model_1977Cvode.hpp\"\n#include \"luo_rudy_1991Cvode.hpp\"\n#include \"ten_tusscher_model_2004_epiCvode.hpp\"\n#include \"decker_2009Cvode.hpp\"\n//#include \"ten_tusscher_model_2004_epiCvodeOpt.hpp\" // trying to catch blip \"davies_isap_2012CvodeDataClampOpt.hpp\"\n#include \"ohara_rudy_2011_endoCvodeDataClamp.hpp\"\n#include \"davies_isap_2012CvodeDataClamp.hpp\"\n//#include \"davies_isap_2012Cvode.hpp\"\n#include \"paci_hyttinen_aaltosetala_severi_ventricularVersionCvodeDataClamp.hpp\"\n#include \"gokhale_ex293_2017Cvode.hpp\"\n\nAPSimulator::APSimulator()\n    : mModelNumber(1),\n      mNumberOfFailedSolves(0),\n      mHowManySolves(1),\n      mSolveStart(0),\n      mSolveEnd(500),\n      mSolveTimestep(0.2),\n      mNumTimePts(2501),\n      mUseDataClamp(false),\n      mDataClampOn(0),\n      mDataClampOff(1),\n      mHaveRunToSteadyState(false)\n{\n    //RedirectStdErr();\n    std::cerr << \"*** INSIDE CONSTRUCTOR (nothing should happen here) ***\" << std::endl << std::flush;\n}\n\nAPSimulator::~APSimulator()\n{\n    //fclose(stderr);\n}\n\n/*\nvoid APSimulator::RedirectStdErr()\n{\n    boost::filesystem::path stderr_dir = \"/home/rossj/stderr/\"; // should find a better location for this\n    std::string log_file_path = stderr_dir.string() + \"stderr.log\";\n\n    boost::filesystem::create_directories(stderr_dir);\n\n    std::cerr << stderr_dir << std::endl << std::flush;\n\n    freopen( log_file_path.c_str(), \"w\", stderr );\n}\n*/\n\nvoid APSimulator::DefineStimulus(double stimulus_magnitude, double stimulus_duration, double stimulus_period, double stimulus_start_time)\n{\n    mpStimulus.reset(new RegularStimulus(stimulus_magnitude,stimulus_duration,stimulus_period,stimulus_start_time));\n    mStimPeriod = stimulus_period;\n}\n\nvoid APSimulator::DefineSolveTimes(double solve_start, double solve_end, double solve_timestep)\n{\n    std::cerr << \"About to define solve times\" << std::endl << std::flush;\n    mSolveStart = solve_start;\n    mSolveEnd = solve_end;\n    mSolveTimestep = solve_timestep;\n    mNumTimePts = (solve_end - solve_start)/solve_timestep + 1;\n    std::cerr << \"Solve times defined\" << std::endl << std::flush;\n}\n\nvoid APSimulator::DefineModel(unsigned model_number)\n{\n    mModelNumber = model_number;\n    boost::shared_ptr<AbstractIvpOdeSolver> p_solver;\n    if ( model_number == 1u )\n    {\n        mpModel.reset(new Cellhodgkin_huxley_squid_axon_model_1952_modifiedFromCellMLCvode(p_solver, mpStimulus));\n        mParameterMetanames.push_back(\"membrane_fast_sodium_current_conductance\"); // 120\n        mParameterMetanames.push_back(\"membrane_potassium_current_conductance\");   // 36\n        mParameterMetanames.push_back(\"membrane_leakage_current_conductance\");     // 0.3\n    }\n    else if ( model_number == 2u )\n    {\n        mpModel.reset(new Cellbeeler_reuter_model_1977FromCellMLCvode(p_solver, mpStimulus));\n        mParameterMetanames.push_back(\"membrane_fast_sodium_current_conductance\");                        // 4e-2\n        mParameterMetanames.push_back(\"membrane_inward_rectifier_potassium_current_conductance\");         // 0.0035\n        mParameterMetanames.push_back(\"membrane_rapid_delayed_rectifier_potassium_current_conductance\");  // 0.008\n        mParameterMetanames.push_back(\"membrane_L_type_calcium_current_conductance\");                     // 9e-4\n    }\n    else if ( model_number == 3u )\n    {\n        mpModel.reset(new Cellluo_rudy_1991FromCellMLCvode(p_solver, mpStimulus));\n        mParameterMetanames.push_back(\"membrane_fast_sodium_current_conductance\");                  // 23\n        mParameterMetanames.push_back(\"membrane_delayed_rectifier_potassium_current_conductance\");  // 0.282\n        mParameterMetanames.push_back(\"membrane_inward_rectifier_potassium_current_conductance\");   // 0.6047\n        mParameterMetanames.push_back(\"membrane_L_type_calcium_current_conductance\");               // 0.09\n        mParameterMetanames.push_back(\"membrane_leakage_current_conductance\");                      // 0.03921\n        mParameterMetanames.push_back(\"membrane_plateau_potassium_current_conductance\");            // 0.0183\n    }\n    else if ( model_number == 4u )\n    {\n        mpModel.reset(new Cellten_tusscher_model_2004_epiFromCellMLCvode(p_solver, mpStimulus));\n        mParameterMetanames.push_back(\"membrane_fast_sodium_current_conductance\");                        // 14.838\n        mParameterMetanames.push_back(\"membrane_L_type_calcium_current_conductance\");                     // 0.000175\n        mParameterMetanames.push_back(\"membrane_inward_rectifier_potassium_current_conductance\");         // 5.405\n        mParameterMetanames.push_back(\"membrane_rapid_delayed_rectifier_potassium_current_conductance\");  // 0.096\n        mParameterMetanames.push_back(\"membrane_slow_delayed_rectifier_potassium_current_conductance\");   // 0.245\n        mParameterMetanames.push_back(\"membrane_sodium_calcium_exchanger_current_conductance\");           // 1000\n        mParameterMetanames.push_back(\"membrane_transient_outward_current_conductance\");                  // 0.294\n        mParameterMetanames.push_back(\"membrane_background_calcium_current_conductance\");                 // 0.000592\n        mParameterMetanames.push_back(\"membrane_background_sodium_current_conductance\");                  // 0.00029\n        mParameterMetanames.push_back(\"membrane_calcium_pump_current_conductance\");                       // 0.825\n        mParameterMetanames.push_back(\"membrane_potassium_pump_current_conductance\");                     // 0.0146\n        mParameterMetanames.push_back(\"membrane_sodium_potassium_pump_current_permeability\");             // 1.362\n    }\n    else if ( model_number == 5u )\n    {\n        mpModel.reset(new Cellohara_rudy_2011_endoFromCellMLCvodeDataClamp(p_solver, mpStimulus));\n        mParameterMetanames.push_back(\"membrane_fast_sodium_current_conductance\");                        // 75\n        mParameterMetanames.push_back(\"membrane_L_type_calcium_current_conductance\");                     // 0.0001\n        mParameterMetanames.push_back(\"membrane_background_potassium_current_conductance\");               // 0.003\n        mParameterMetanames.push_back(\"membrane_inward_rectifier_potassium_current_conductance\");         // 0.1908\n        mParameterMetanames.push_back(\"membrane_rapid_delayed_rectifier_potassium_current_conductance\");  // 0.046\n        mParameterMetanames.push_back(\"membrane_slow_delayed_rectifier_potassium_current_conductance\");   // 0.0034\n        mParameterMetanames.push_back(\"membrane_sodium_calcium_exchanger_current_conductance\");           // 0.0008\n        mParameterMetanames.push_back(\"membrane_sodium_potassium_pump_current_permeability\");             // 30\n        mParameterMetanames.push_back(\"membrane_transient_outward_current_conductance\");                  // 0.02\n        mParameterMetanames.push_back(\"membrane_background_calcium_current_conductance\");                 // 2.5e-8\n        mParameterMetanames.push_back(\"membrane_background_sodium_current_conductance\");                  // 3.75e-10\n        mParameterMetanames.push_back(\"membrane_calcium_pump_current_conductance\");                       // 0.0005\n        mParameterMetanames.push_back(\"membrane_persistent_sodium_current_conductance\");                  // 0.0075\n    }\n    else if ( model_number == 6u ) // Davies 2012 (with data clamp)\n    {\n        mpModel.reset(new Celldavies_isap_2012FromCellMLCvodeDataClamp(p_solver, mpStimulus));\n        //mpModel.reset(new Celldavies_isap_2012FromCellMLCvode(p_solver, mpStimulus));\n        mParameterMetanames.push_back(\"membrane_fast_sodium_current_conductance\");                        // 8.25\n        mParameterMetanames.push_back(\"membrane_L_type_calcium_current_conductance\");                     // 0.000243\n        mParameterMetanames.push_back(\"membrane_inward_rectifier_potassium_current_conductance\");         // 0.5\n        mParameterMetanames.push_back(\"membrane_potassium_pump_current_conductance\");                     // 0.00276\n        mParameterMetanames.push_back(\"membrane_slow_delayed_rectifier_potassium_current_conductance\");   // 0.00746925\n        mParameterMetanames.push_back(\"membrane_rapid_delayed_rectifier_potassium_current_conductance\");  // 0.0138542\n        mParameterMetanames.push_back(\"membrane_calcium_pump_current_conductance\");                       // 0.0575\n        mParameterMetanames.push_back(\"membrane_background_calcium_current_conductance\");                 // 0.0000007980336\n        mParameterMetanames.push_back(\"membrane_sodium_calcium_exchanger_current_conductance\");           // 5.85\n        mParameterMetanames.push_back(\"membrane_sodium_potassium_pump_current_permeability\");             // 0.61875\n        mParameterMetanames.push_back(\"membrane_transient_outward_current_conductance\");                  // 0.1805\n        mParameterMetanames.push_back(\"membrane_transient_outward_chloride_current_conductance\");         // 4e-7\n        mParameterMetanames.push_back(\"membrane_background_chloride_current_conductance\");                // 0.000225\n        mParameterMetanames.push_back(\"membrane_persistent_sodium_current_conductance\");                  // 0.011\n    }\n    else if ( model_number == 7u ) // Paci ventricular\n    {\n        mpModel.reset(new Cellpaci_hyttinen_aaltosetala_severi_ventricularVersionFromCellMLCvodeDataClamp(p_solver, mpStimulus));\n        mParameterMetanames.push_back(\"membrane_fast_sodium_current_conductance\");                                            // 3671.2302\n        mParameterMetanames.push_back(\"membrane_L_type_calcium_current_conductance\");                                         // 8.635702e-5\n        mParameterMetanames.push_back(\"membrane_inward_rectifier_potassium_current_conductance\");                             // 28.1492\n        mParameterMetanames.push_back(\"membrane_slow_delayed_rectifier_potassium_current_conductance\");                       // 2.041\n        mParameterMetanames.push_back(\"membrane_rapid_delayed_rectifier_potassium_current_conductance\");                      // 29.8667\n        mParameterMetanames.push_back(\"membrane_calcium_pump_current_conductance\");                                           // 0.4125\n        mParameterMetanames.push_back(\"membrane_sodium_calcium_exchanger_current_conductance\");                               // 4900\n        mParameterMetanames.push_back(\"membrane_background_calcium_current_conductance\");                                     // 0.69264\n        mParameterMetanames.push_back(\"membrane_sodium_potassium_pump_current_permeability\");                                 // 1.841424\n        mParameterMetanames.push_back(\"membrane_transient_outward_current_conductance\");                                      // 29.9038\n        mParameterMetanames.push_back(\"membrane_background_sodium_current_conductance\");                                      // 0.9\n        mParameterMetanames.push_back(\"membrane_hyperpolarisation_activated_funny_current_potassium_component_conductance\");  // 30.10312\n    }\n    else if ( model_number == 8u ) // Decker dog\n    {\n        mpModel.reset(new Celldecker_2009FromCellMLCvode(p_solver, mpStimulus));\n        mParameterMetanames.push_back(\"membrane_fast_sodium_current_conductance\");  // 9.075\n        mParameterMetanames.push_back(\"membrane_L_type_calcium_current_conductance\");  //  0.00015552\n        mParameterMetanames.push_back(\"membrane_inward_rectifier_potassium_current_conductance\");  // 0.5\n        mParameterMetanames.push_back(\"membrane_slow_delayed_rectifier_potassium_current_conductance\");  // 0.0826\n        mParameterMetanames.push_back(\"membrane_rapid_delayed_rectifier_potassium_current_conductance\");  // 0.0138542\n        mParameterMetanames.push_back(\"membrane_transient_outward_current_conductance\");  // 0.497458\n    }\n    else if ( model_number == 9u ) // Gokhale 2017\n    {\n        mpModel.reset(new Cellgokhale_ex293_2017FromCellMLCvode(p_solver, mpStimulus));\n        mParameterMetanames.push_back(\"membrane_fast_sodium_current_conductance\");  // 9.075\n        mParameterMetanames.push_back(\"membrane_L_type_calcium_current_conductance\");  //  0.00015552\n        mParameterMetanames.push_back(\"membrane_inward_rectifier_potassium_current_conductance\");  // 0.5\n        mParameterMetanames.push_back(\"membrane_slow_delayed_rectifier_potassium_current_conductance\");  // 0.0826\n        mParameterMetanames.push_back(\"membrane_rapid_delayed_rectifier_potassium_current_conductance\");  // 0.0138542\n        mParameterMetanames.push_back(\"membrane_transient_outward_current_conductance\");  // 0.497458\n    }\n    mpModel->SetMaxSteps(10000);\n}\n\nstd::vector<std::string> APSimulator::GetParameterMetanames()\n{\n    return mParameterMetanames;\n}\n\nvoid APSimulator::SetToModelInitialConditions()\n{\n    mpModel->SetStateVariables(mpModel->GetInitialConditions());\n}\n\nstd::vector<double> APSimulator::SolveForVoltageTraceWithParamsNoDataClamp(const std::vector<double>& rParams)\n{\n    //std::cerr << \"About to try and solve\" << std::endl << std::flush;\n    //mpModel->SetStateVariables(mpModel->GetInitialConditions());\n    std::vector<double> voltage_trace;\n    for (unsigned j=0; j<rParams.size(); j++)\n    {\n        mpModel->SetParameter(mParameterMetanames[j], rParams[j]);\n    }\n    //std::cerr << \"Just set(ted) parameters\" << std::endl << std::flush;\n    try\n    {\n        if (mHowManySolves > 1)\n        {\n            for (unsigned i=0; i<mHowManySolves-1; i++)\n            {\n                mpModel->Compute(mSolveStart, mSolveStart+mStimPeriod, mSolveTimestep);\n            }\n        }\n        //std::cerr << \"About to actually try and solve\" << std::endl << std::flush;\n        OdeSolution sol1 = mpModel->Compute(mSolveStart, mSolveEnd, mSolveTimestep);\n        //std::cerr << \"Just solved\" << std::endl << std::flush;\n        voltage_trace = sol1.GetAnyVariable(\"membrane_voltage\");\n    }\n    catch (Exception &e)\n    {\n        std::cerr << \"WARNING: CVODE failed to solve with these parameters\" << std::endl << std::flush;\n        std::cerr << \"error was \" << e.GetShortMessage() << std::endl << std::flush;\n        voltage_trace = std::vector<double>(mNumTimePts, 0.0);\n        mNumberOfFailedSolves++;\n    }\n    return voltage_trace;\n}\n\nstd::vector<double> APSimulator::SolveForVoltageTraceWithParamsWithDataClamp(const std::vector<double>& rParams)\n{\n    mpModel->SetStateVariables(mpModel->GetInitialConditions());\n    std::vector<double> voltage_trace;\n    \n    for (unsigned j=0; j<rParams.size(); j++)\n    {\n        mpModel->SetParameter(mParameterMetanames[j], rParams[j]);\n    }\n    mpModel->SetStateVariable(\"membrane_voltage\",mExptTrace[0]);\n\n    boost::static_pointer_cast<AbstractCvodeCellWithDataClamp>(mpModel)->TurnOffDataClamp();\n\n    //mpModel->ResetSolver();\n    \n    if (mHowManySolves > 1)\n    {\n        for (unsigned i=0; i<mHowManySolves-1; i++)\n        {\n            mpModel->Compute(mSolveStart, mDataClampOn, mSolveTimestep);\n            mpModel->ResetSolver();\n            boost::static_pointer_cast<AbstractCvodeCellWithDataClamp>(mpModel)->TurnOnDataClamp(200);\n            mpModel->Compute(mDataClampOn, mDataClampOff, mSolveTimestep);\n            mpModel->ResetSolver();\n            boost::static_pointer_cast<AbstractCvodeCellWithDataClamp>(mpModel)->TurnOffDataClamp();\n            mpModel->Compute(mDataClampOff, mSolveEnd, mSolveTimestep);\n        }\n    }\n    \n    OdeSolution sol1 = mpModel->Compute(mSolveStart, mDataClampOn, mSolveTimestep);\n    \n    mpModel->ResetSolver();\n    boost::static_pointer_cast<AbstractCvodeCellWithDataClamp>(mpModel)->TurnOnDataClamp(200);\n    OdeSolution sol2 = mpModel->Compute(mDataClampOn, mDataClampOff, mSolveTimestep);\n    mpModel->ResetSolver();\n    boost::static_pointer_cast<AbstractCvodeCellWithDataClamp>(mpModel)->TurnOffDataClamp();\n    OdeSolution sol3 = mpModel->Compute(mDataClampOff, mSolveEnd, mSolveTimestep);\n\n    voltage_trace = sol1.GetAnyVariable(\"membrane_voltage\");\n    std::vector<double> voltage_trace_part_2 = sol2.GetAnyVariable(\"membrane_voltage\");\n    std::vector<double> voltage_trace_part_3 = sol3.GetAnyVariable(\"membrane_voltage\");\n\n    voltage_trace.erase(voltage_trace.end()-1);\n    voltage_trace.insert( voltage_trace.end(), voltage_trace_part_2.begin(), voltage_trace_part_2.end() );\n    voltage_trace.erase(voltage_trace.end()-1);\n    voltage_trace.insert( voltage_trace.end(), voltage_trace_part_3.begin(), voltage_trace_part_3.end() );\n    return voltage_trace;\n}\n\nstd::vector<double> APSimulator::SolveForVoltageTraceWithParams(const std::vector<double>& rParams)\n{\n    std::vector<double> voltage_trace;\n    if (mUseDataClamp == false)\n    {\n        voltage_trace = SolveForVoltageTraceWithParamsNoDataClamp(rParams);\n    }\n    else\n    {\n        voltage_trace = SolveForVoltageTraceWithParamsWithDataClamp(rParams);\n    }\n    return voltage_trace;\n}\n        \n\nvoid APSimulator::SetTolerances(double rel_tol, double abs_tol)\n{\n    mpModel->SetTolerances(rel_tol, abs_tol);\n}\n\ndouble APSimulator::ExampleLogLikelihoodFunction(const std::vector<double>& test_trace)\n{\n    double total = 0;\n    double temp;\n    for (unsigned i=0; i<test_trace.size(); i++)\n    {\n        temp = test_trace[i];\n        //std::cerr << temp << \" \";\n        total += temp*temp;\n    }\n    //std::cerr << \"APSimulator::ExampleLogLikelihoodFunction: \" << total << std::endl << std::flush;\n    return total;\n}\n\nstd::vector<double> APSimulator::GenerateSyntheticExptTrace(const std::vector<double>& rParams, double noise_sd, double c_seed)\n{\n    std::vector<double> expt_trace = SolveForVoltageTraceWithParams(rParams);\n    RandomNumberGenerator::Instance()->Reseed(c_seed);\n    double random_number;\n    for (unsigned i=0; i<expt_trace.size(); i++)\n    {\n        random_number = RandomNumberGenerator::Instance()->StandardNormalRandomDeviate();\n        expt_trace[i] +=  noise_sd*random_number;\n    }\n    mExptTrace = expt_trace;\n    return expt_trace;\n}\n\nvoid APSimulator::UseDataClamp(double data_clamp_on, double data_clamp_off)\n{\n    mUseDataClamp = true;\n    mDataClampOn = data_clamp_on;\n    mDataClampOff = data_clamp_off;\n}\n\nvoid APSimulator::SetExperimentalTraceAndTimesForDataClamp(const std::vector<double>& expt_times, const std::vector<double>& expt_trace)\n{\n    boost::static_pointer_cast<AbstractCvodeCellWithDataClamp>(mpModel)->SetExperimentalData(expt_times,expt_trace);\n    mExptTrace = expt_trace;\n}\n\nvoid APSimulator::SetExtracellularPotassiumConc( double extra_K_conc )\n{\n    try\n    {\n        mpModel->SetParameter(\"extracellular_potassium_concentration\", extra_K_conc);\n    }\n    catch (Exception &e)\n    {\n        std::cerr << \"No extracellular_potassium_concentration parameter in model\" << std::endl << std::flush;\n        std::cerr << \"error was \" << e.GetShortMessage() << std::endl << std::flush;\n    }\n}\n\nvoid APSimulator::SetNumberOfSolves( unsigned num_solves )\n{\n    mHowManySolves = num_solves;\n}\n\nbool APSimulator::RunToSteadyState()\n{\n    SteadyStateRunner steady_runner(mpModel);\n    unsigned max_paces = 50000u;\n    steady_runner.SetMaxNumPaces(max_paces);\n    bool result = steady_runner.RunToSteadyState();\n    mHaveRunToSteadyState = result;\n    return result;\n}\n\nvoid APSimulator::ArchiveStateVariables()\n{\n    boost::filesystem::path arch_dir;\n    if (mHaveRunToSteadyState)\n    {\n        arch_dir = \"projects/RossJ/archived_variables/steady_state/\";\n    }\n    else\n    {\n        arch_dir = \"projects/RossJ/archived_variables/non_steady_state/\";\n    }\n    boost::filesystem::create_directories(arch_dir);\n    //OutputFileHandler handler(arch_dir.string(), false);\n    //handler.SetArchiveDirectory();\n    //std::string arch_name = handler.GetOutputDirectoryFullPath() + \"m_\"+boost::lexical_cast<std::string>(mModelNumber)+\".arch\";\n    std::ofstream ofs((arch_dir.string() + \"m_\"+boost::lexical_cast<std::string>(mModelNumber)+\".arch\").c_str());\n    boost::archive::text_oarchive output_arch(ofs);\n    output_arch <<  *mpModel;\n}\n\nvoid APSimulator::LoadStateVariables()\n{\n    std::string arch_file = \"~/workspace/RossJ/archived_variables/steady_state/m_\"+boost::lexical_cast<std::string>(mModelNumber)+\".arch\";\n    std::cout << arch_file << std::endl << std::flush;\n    std::ifstream ifs(arch_file.c_str(), std::ios::binary);\n    boost::archive::text_iarchive input_arch(ifs);\n    input_arch >> *mpModel;\n}\n\n", "meta": {"hexsha": "7fed48e0c48b49c7a9cba39d292fe510a6a87a50", "size": 20776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ap_simulator/APSimulator.cpp", "max_stars_repo_name": "rhjohnstone/RossJ", "max_stars_repo_head_hexsha": "3bf0a81d085de33c5b461c10f2d66f52bf86450f", "max_stars_repo_licenses": ["FTL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ap_simulator/APSimulator.cpp", "max_issues_repo_name": "rhjohnstone/RossJ", "max_issues_repo_head_hexsha": "3bf0a81d085de33c5b461c10f2d66f52bf86450f", "max_issues_repo_licenses": ["FTL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ap_simulator/APSimulator.cpp", "max_forks_repo_name": "rhjohnstone/RossJ", "max_forks_repo_head_hexsha": "3bf0a81d085de33c5b461c10f2d66f52bf86450f", "max_forks_repo_licenses": ["FTL"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.427184466, "max_line_length": 140, "alphanum_fraction": 0.7084135541, "num_tokens": 5470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.20459025532056946}}
{"text": "/*\n *            Copyright 2009-2020 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// Third party includes\n#include <boost/format.hpp>\n\n// VOTCA includes\n#include <votca/tools/constants.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/aomatrix.h\"\n#include \"votca/xtp/dftcoupling.h\"\n\nnamespace votca {\nnamespace xtp {\n\nusing boost::format;\nusing std::flush;\n\nvoid DFTcoupling::Initialize(tools::Property& options) {\n\n  degeneracy_ = options.get(\"degeneracy\").as<double>();\n  degeneracy_ *= tools::conv::ev2hrt;\n  numberofstatesA_ = options.get(\"levA\").as<Index>();\n  numberofstatesB_ = options.get(\"levB\").as<Index>();\n}\n\nvoid DFTcoupling::WriteToProperty(tools::Property& type_summary,\n                                  const Orbitals& orbitalsA,\n                                  const Orbitals& orbitalsB, Index a,\n                                  Index b) const {\n  double J = getCouplingElement(a, b, orbitalsA, orbitalsB);\n  tools::Property& coupling = type_summary.add(\"coupling\", \"\");\n  coupling.setAttribute(\"levelA\", a);\n  coupling.setAttribute(\"levelB\", b);\n  coupling.setAttribute(\"j\", (format(\"%1$1.6e\") % J).str());\n}\n\nvoid DFTcoupling::Addoutput(tools::Property& type_summary,\n                            const Orbitals& orbitalsA,\n                            const Orbitals& orbitalsB) const {\n  tools::Property& dftcoupling = type_summary.add(Identify(), \"\");\n  dftcoupling.setAttribute(\"homoA\", orbitalsA.getHomo());\n  dftcoupling.setAttribute(\"homoB\", orbitalsB.getHomo());\n  tools::Property& hole_summary = dftcoupling.add(\"hole\", \"\");\n  // hole hole\n  for (Index a = Range_orbA.first; a <= orbitalsA.getHomo(); ++a) {\n    for (Index b = Range_orbB.first; b <= orbitalsB.getHomo(); ++b) {\n      WriteToProperty(hole_summary, orbitalsA, orbitalsB, a, b);\n    }\n  }\n  tools::Property& electron_summary = dftcoupling.add(\"electron\", \"\");\n  // electron-electron\n  for (Index a = orbitalsA.getLumo();\n       a <= Range_orbA.first + Range_orbA.second - 1; ++a) {\n    for (Index b = orbitalsB.getLumo();\n         b <= Range_orbB.first + Range_orbB.second - 1; ++b) {\n      WriteToProperty(electron_summary, orbitalsA, orbitalsB, a, b);\n    }\n  }\n  return;\n}\n\nstd::pair<int, Index> DFTcoupling::DetermineRangeOfStates(\n    const Orbitals& orbital, Index numberofstates) const {\n  const Eigen::VectorXd& MOEnergies = orbital.MOs().eigenvalues();\n  if (std::abs(MOEnergies(orbital.getHomo()) - MOEnergies(orbital.getLumo())) <\n      degeneracy_) {\n    throw std::runtime_error(\n        \"Homo Lumo Gap is smaller than degeneracy. \"\n        \"Either your degeneracy is too large or your Homo and Lumo are \"\n        \"degenerate\");\n  }\n\n  Index minimal = orbital.getHomo() - numberofstates + 1;\n  Index maximal = orbital.getLumo() + numberofstates - 1;\n\n  std::vector<Index> deg_min = orbital.CheckDegeneracy(minimal, degeneracy_);\n  minimal = *std::min_element(deg_min.begin(), deg_min.end());\n\n  std::vector<Index> deg_max = orbital.CheckDegeneracy(maximal, degeneracy_);\n  maximal = *std::max_element(deg_max.begin(), deg_max.end());\n\n  std::pair<Index, Index> result;\n  result.first = minimal;                 // start\n  result.second = maximal - minimal + 1;  // size\n\n  return result;\n}\n\ndouble DFTcoupling::getCouplingElement(Index levelA, Index levelB,\n                                       const Orbitals& orbitalsA,\n                                       const Orbitals& orbitalsB) const {\n\n  Index levelsA = Range_orbA.second;\n  if (degeneracy_ != 0) {\n    std::vector<Index> list_levelsA =\n        orbitalsA.CheckDegeneracy(levelA, degeneracy_);\n    std::vector<Index> list_levelsB =\n        orbitalsB.CheckDegeneracy(levelB, degeneracy_);\n\n    double JAB_sq = 0;\n\n    for (Index iA : list_levelsA) {\n      Index indexA = iA - Range_orbA.first;\n      for (Index iB : list_levelsB) {\n        Index indexB = iB - Range_orbB.first + levelsA;\n        double JAB_one_level = JAB(indexA, indexB);\n        JAB_sq += JAB_one_level * JAB_one_level;\n      }\n    }\n    return std::sqrt(JAB_sq /\n                     double(list_levelsA.size() * list_levelsB.size())) *\n           tools::conv::hrt2ev;\n  } else {\n    Index indexA = levelA - Range_orbA.first;\n    Index indexB = levelB - Range_orbB.first + levelsA;\n    return JAB(indexA, indexB) * tools::conv::hrt2ev;\n  }\n}\n\n/**\n * \\brief evaluates electronic couplings\n * @param  orbitalsA_ molecular orbitals of molecule A\n * @param  orbitalsB_ molecular orbitals of molecule B\n * @param  orbitalsAB_ molecular orbitals of the dimer AB\n */\nvoid DFTcoupling::CalculateCouplings(const Orbitals& orbitalsA,\n                                     const Orbitals& orbitalsB,\n                                     const Orbitals& orbitalsAB) {\n\n  XTP_LOG(Log::error, *pLog_) << \"Calculating electronic couplings\" << flush;\n\n  CheckAtomCoordinates(orbitalsA, orbitalsB, orbitalsAB);\n\n  // constructing the direct product orbA x orbB\n  Index basisA = orbitalsA.getBasisSetSize();\n  Index basisB = orbitalsB.getBasisSetSize();\n\n  if ((basisA == 0) || (basisB == 0)) {\n    throw std::runtime_error(\"Basis set size is not stored in monomers\");\n  }\n\n  Range_orbA = DetermineRangeOfStates(orbitalsA, numberofstatesA_);\n  Range_orbB = DetermineRangeOfStates(orbitalsB, numberofstatesB_);\n\n  Index levelsA = Range_orbA.second;\n  Index levelsB = Range_orbB.second;\n\n  XTP_LOG(Log::error, *pLog_)\n      << \"Levels:Basis A[\" << levelsA << \":\" << basisA << \"]\"\n      << \" B[\" << levelsB << \":\" << basisB << \"]\" << flush;\n\n  if ((levelsA == 0) || (levelsB == 0)) {\n    throw std::runtime_error(\n        \"No information about number of occupied/unoccupied levels is stored\");\n  }\n\n  // constructing merged orbitals\n  auto MOsA = orbitalsA.MOs().eigenvectors().middleCols(Range_orbA.first,\n                                                        Range_orbA.second);\n  auto MOsB = orbitalsB.MOs().eigenvectors().middleCols(Range_orbB.first,\n                                                        Range_orbB.second);\n\n  XTP_LOG(Log::info, *pLog_) << \"Calculating overlap matrix for basisset: \"\n                             << orbitalsAB.getDFTbasisName() << flush;\n\n  Eigen::MatrixXd overlap =\n      CalculateOverlapMatrix(orbitalsAB) * orbitalsAB.MOs().eigenvectors();\n\n  XTP_LOG(Log::info, *pLog_)\n      << \"Projecting monomers onto dimer orbitals\" << flush;\n  Eigen::MatrixXd A_AB = MOsA.transpose() * overlap.topRows(basisA);\n  Eigen::MatrixXd B_AB = MOsB.transpose() * overlap.bottomRows(basisB);\n  Eigen::VectorXd mag_A = A_AB.rowwise().squaredNorm();\n  if (mag_A.any() < 0.95) {\n    XTP_LOG(Log::error, *pLog_)\n        << \"\\nWarning: \"\n        << \"Projection of orbitals of monomer A on dimer is insufficient,mag=\"\n        << mag_A.minCoeff() << flush;\n  }\n  Eigen::VectorXd mag_B = B_AB.rowwise().squaredNorm();\n  if (mag_B.any() < 0.95) {\n    XTP_LOG(Log::error, *pLog_)\n        << \"\\nWarning: \"\n        << \"Projection of orbitals of monomer B on dimer is insufficient,mag=\"\n        << mag_B.minCoeff() << flush;\n  }\n\n  Eigen::MatrixXd psi_AxB_dimer_basis(A_AB.rows() + B_AB.rows(), A_AB.cols());\n  psi_AxB_dimer_basis.topRows(A_AB.rows()) = A_AB;\n  psi_AxB_dimer_basis.bottomRows(B_AB.rows()) = B_AB;\n\n  XTP_LOG(Log::info, *pLog_)\n      << \"Projecting the Fock matrix onto the dimer basis\" << flush;\n  Eigen::MatrixXd JAB_dimer = psi_AxB_dimer_basis *\n                              orbitalsAB.MOs().eigenvalues().asDiagonal() *\n                              psi_AxB_dimer_basis.transpose();\n  XTP_LOG(Log::info, *pLog_) << \"Constructing Overlap matrix\" << flush;\n  Eigen::MatrixXd S_AxB = psi_AxB_dimer_basis * psi_AxB_dimer_basis.transpose();\n  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(S_AxB);\n  Eigen::MatrixXd Sm1 = es.operatorInverseSqrt();\n  XTP_LOG(Log::info, *pLog_) << \"Smallest eigenvalue of overlap matrix is \"\n                             << es.eigenvalues()(0) << flush;\n  JAB = Sm1 * JAB_dimer * Sm1;\n  XTP_LOG(Log::error, *pLog_) << \"Done with electronic couplings\" << flush;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "b46b169fbc5314f9056b3545c61cafa576b24bb8", "size": 8597, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libxtp/dftcoupling.cc", "max_stars_repo_name": "rubengerritsen/xtp", "max_stars_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libxtp/dftcoupling.cc", "max_issues_repo_name": "rubengerritsen/xtp", "max_issues_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libxtp/dftcoupling.cc", "max_forks_repo_name": "rubengerritsen/xtp", "max_forks_repo_head_hexsha": "af4db53ca99853280d0e2ddc7f3c41bce8ae6e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.872246696, "max_line_length": 80, "alphanum_fraction": 0.6405722927, "num_tokens": 2340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.20459025532056946}}
{"text": "#include \"Elasticity.h\"\n#include \"config.h\"\n#include \"kernels/elasticity/init.h\"\n#include \"kernels/elasticity/kernel.h\"\n#include \"kernels/elasticity/tensor.h\"\n\n#include \"basis/WarpAndBlend.h\"\n#include \"form/BC.h\"\n#include \"form/DGCurvilinearCommon.h\"\n#include \"form/InverseInequality.h\"\n#include \"form/RefElement.h\"\n#include \"geometry/Curvilinear.h\"\n#include \"quadrules/SimplexQuadratureRule.h\"\n#include \"tensor/EigenMap.h\"\n#include \"util/LinearAllocator.h\"\n#include \"util/Stopwatch.h\"\n\n#include <Eigen/LU>\n#include <cassert>\n\nnamespace tensor = tndm::elasticity::tensor;\nnamespace init = tndm::elasticity::init;\nnamespace kernel = tndm::elasticity::kernel;\n\nnamespace tndm {\n\nElasticity::Elasticity(std::shared_ptr<Curvilinear<DomainDimension>> cl, functional_t<1> lam,\n                       functional_t<1> mu, std::optional<functional_t<1>> rho, DGMethod method)\n    : DGCurvilinearCommon<DomainDimension>(std::move(cl), MinQuadOrder()), method_(method),\n      space_(PolynomialDegree, WarpAndBlendFactory<DomainDimension>(), ALIGNMENT),\n      materialSpace_(PolynomialDegree, WarpAndBlendFactory<DomainDimension>(), ALIGNMENT),\n      fun_lam(make_volume_functional(std::move(lam))),\n      fun_mu(make_volume_functional(std::move(mu))),\n      fun_rho(rho ? make_volume_functional(std::move(*rho)) : one_volume_function) {\n\n    MhatInv = space_.inverseMassMatrix();\n    E_Q = space_.evaluateBasisAt(volRule.points());\n    E_Q_T = space_.evaluateBasisAt(volRule.points(), {1, 0});\n    Dxi_Q = space_.evaluateGradientAt(volRule.points());\n    Dxi_Q_120 = space_.evaluateGradientAt(volRule.points(), {1, 2, 0});\n\n    negative_E_Q_T = Managed<Matrix<double>>(E_Q_T.shape(), std::size_t{ALIGNMENT});\n    EigenMap(negative_E_Q_T) = -EigenMap(E_Q_T);\n\n    for (std::size_t f = 0; f < DomainDimension + 1u; ++f) {\n        auto points = cl_->facetParam(f, fctRule.points());\n        E_q.emplace_back(space_.evaluateBasisAt(points));\n        E_q_T.emplace_back(space_.evaluateBasisAt(points, {1, 0}));\n        Dxi_q.emplace_back(space_.evaluateGradientAt(points));\n        Dxi_q_120.emplace_back(space_.evaluateGradientAt(points, {1, 2, 0}));\n        matE_q_T.emplace_back(materialSpace_.evaluateBasisAt(points, {1, 0}));\n\n        negative_E_q.emplace_back(space_.evaluateBasisAt(points));\n        auto neg = EigenMap(negative_E_q.back());\n        neg = -neg;\n\n        negative_E_q_T.emplace_back(space_.evaluateBasisAt(points, {1, 0}));\n        auto negT = EigenMap(negative_E_q_T.back());\n        negT = -negT;\n    }\n\n    matE_Q_T = materialSpace_.evaluateBasisAt(volRule.points(), {1, 0});\n}\n\nvoid Elasticity::compute_mass_matrix(std::size_t elNo, double* M) const {\n    kernel::massMatrix mm;\n    mm.E_Q = E_Q.data();\n    mm.J = vol[elNo].get<AbsDetJ>().data();\n    mm.M = M;\n    mm.W = volRule.weights().data();\n    mm.execute();\n}\n\nvoid Elasticity::compute_inverse_mass_matrix(std::size_t elNo, double* Minv) const {\n    compute_mass_matrix(elNo, Minv);\n\n    using MMat = Eigen::Matrix<double, tensor::M::Shape[0], tensor::M::Shape[1]>;\n    using MMap = Eigen::Map<MMat, Eigen::Unaligned,\n                            Eigen::OuterStride<init::M::Stop[0] - init::M::Start[0]>>;\n    auto Minv_eigen = MMap(Minv);\n    auto Minv_lu = Eigen::FullPivLU<MMat>(Minv_eigen);\n    Minv_eigen = Minv_lu.inverse();\n}\n\nvoid Elasticity::begin_preparation(std::size_t numElements, std::size_t numLocalElements,\n                                   std::size_t numLocalFacets) {\n    base::begin_preparation(numElements, numLocalElements, numLocalFacets);\n\n    material.setStorage(\n        std::make_shared<material_vol_t>(numElements * materialSpace_.numBasisFunctions()), 0u,\n        numElements, materialSpace_.numBasisFunctions());\n\n    volPre.setStorage(std::make_shared<vol_pre_t>(numElements * volRule.size()), 0u, numElements,\n                      volRule.size());\n\n    fctPre.setStorage(std::make_shared<fct_pre_t>(numLocalFacets * fctRule.size()), 0u,\n                      numLocalFacets, fctRule.size());\n\n    penalty_.resize(numLocalFacets);\n    cfl_dt_.resize(numLocalElements, 0.0);\n}\n\nvoid Elasticity::prepare_volume(std::size_t elNo, LinearAllocator<double>& scratch) {\n    base::prepare_volume(elNo, scratch);\n\n    alignas(ALIGNMENT) double lam_Q_raw[tensor::lam_Q::size()];\n    auto lam_Q = Matrix<double>(lam_Q_raw, 1, volRule.size());\n    fun_lam(elNo, lam_Q);\n\n    alignas(ALIGNMENT) double mu_Q_raw[tensor::mu_Q::size()];\n    auto mu_Q = Matrix<double>(mu_Q_raw, 1, volRule.size());\n    fun_mu(elNo, mu_Q);\n\n    alignas(ALIGNMENT) double rhoInv_Q_raw[tensor::rhoInv_Q::size()];\n    auto rhoInv_Q = Matrix<double>(rhoInv_Q_raw, 1, volRule.size());\n    fun_rho(elNo, rhoInv_Q);\n    for (unsigned q = 0; q < tensor::rhoInv_Q::Shape[0]; ++q) {\n        rhoInv_Q(0, q) = 1.0 / rhoInv_Q(0, q);\n    }\n\n    alignas(ALIGNMENT) double Mmem[tensor::matM::size()];\n    kernel::project_material_lhs krnl_lhs;\n    krnl_lhs.matE_Q_T = matE_Q_T.data();\n    krnl_lhs.J = vol[elNo].get<AbsDetJ>().data();\n    krnl_lhs.matM = Mmem;\n    krnl_lhs.W = volRule.weights().data();\n    krnl_lhs.execute();\n\n    auto lam_field = material[elNo].get<lam>().data();\n    auto mu_field = material[elNo].get<mu>().data();\n    auto rhoInv_field = material[elNo].get<rhoInv>().data();\n    kernel::project_material_rhs krnl_rhs;\n    krnl_rhs.matE_Q_T = matE_Q_T.data();\n    krnl_rhs.J = vol[elNo].get<AbsDetJ>().data();\n    krnl_rhs.lam = lam_field;\n    krnl_rhs.lam_Q = lam_Q_raw;\n    krnl_rhs.mu = mu_field;\n    krnl_rhs.mu_Q = mu_Q_raw;\n    krnl_rhs.rhoInv = rhoInv_field;\n    krnl_rhs.rhoInv_Q = rhoInv_Q_raw;\n    krnl_rhs.W = volRule.weights().data();\n    krnl_rhs.execute();\n\n    using MMap = Eigen::Map<Eigen::Matrix<double, tensor::matM::Shape[0], tensor::matM::Shape[1]>,\n                            Eigen::Unaligned,\n                            Eigen::OuterStride<init::matM::Stop[0] - init::matM::Start[0]>>;\n    using LamMap = Eigen::Map<Eigen::Matrix<double, tensor::lam::Shape[0], 1>, Eigen::Unaligned,\n                              Eigen::InnerStride<1>>;\n    using MuMap = Eigen::Map<Eigen::Matrix<double, tensor::mu::Shape[0], 1>, Eigen::Unaligned,\n                             Eigen::InnerStride<1>>;\n    using RhoInvMap = Eigen::Map<Eigen::Matrix<double, tensor::rhoInv::Shape[0], 1>,\n                                 Eigen::Unaligned, Eigen::InnerStride<1>>;\n\n    auto proj = MMap(Mmem).fullPivLu();\n\n    auto lam_eigen = LamMap(lam_field);\n    lam_eigen = proj.solve(lam_eigen);\n\n    auto mu_eigen = MuMap(mu_field);\n    mu_eigen = proj.solve(mu_eigen);\n\n    auto rhoInv_eigen = RhoInvMap(rhoInv_field);\n    rhoInv_eigen = proj.solve(rhoInv_eigen);\n\n    auto G_Q = init::G::view::create(vol[elNo].get<JInv>().data()->data());\n    auto G_Q_T = init::G_Q_T::view::create(volPre[elNo].get<JInvT>().data()->data());\n    for (std::ptrdiff_t q = 0; q < G_Q.shape(2); ++q) {\n        for (std::ptrdiff_t i = 0; i < G_Q.shape(0); ++i) {\n            for (std::ptrdiff_t j = 0; j < G_Q.shape(1); ++j) {\n                G_Q_T(i, j, q) = G_Q(j, i, q);\n            }\n        }\n    }\n}\n\nvoid Elasticity::transpose_JInv(std::size_t fctNo, int side) {\n    const auto G_q = (side == 1) ? fct[fctNo].get<JInv1>() : fct[fctNo].get<JInv0>();\n    auto G_q_T = (side == 1) ? fctPre[fctNo].get<JInvT1>() : fctPre[fctNo].get<JInvT0>();\n    for (std::size_t q = 0; q < fctRule.size(); ++q) {\n        for (std::ptrdiff_t i = 0; i < Dim; ++i) {\n            for (std::ptrdiff_t j = 0; j < Dim; ++j) {\n                G_q_T[q][i + j * Dim] = G_q[q][j + i * Dim];\n            }\n        }\n    }\n};\n\nvoid Elasticity::prepare_skeleton(std::size_t fctNo, FacetInfo const& info,\n                                  LinearAllocator<double>& scratch) {\n    base::prepare_skeleton(fctNo, info, scratch);\n\n    kernel::precomputeSurface krnl;\n    for (unsigned side = 0; side < 2; ++side) {\n        krnl.matE_q_T(side) = matE_q_T[info.localNo[side]].data();\n    }\n    krnl.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n    krnl.lam_q(1) = fctPre[fctNo].get<lam_q_1>().data();\n    krnl.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n    krnl.mu_q(1) = fctPre[fctNo].get<mu_q_1>().data();\n\n    for (unsigned side = 0; side < 2; ++side) {\n        krnl.lam = material[info.up[side]].get<lam>().data();\n        krnl.mu = material[info.up[side]].get<mu>().data();\n        krnl.execute(side);\n    }\n\n    transpose_JInv(fctNo, 0);\n    transpose_JInv(fctNo, 1);\n}\n\nvoid Elasticity::prepare_boundary(std::size_t fctNo, FacetInfo const& info,\n                                  LinearAllocator<double>& scratch) {\n    base::prepare_boundary(fctNo, info, scratch);\n\n    kernel::precomputeSurface krnl;\n    krnl.matE_q_T(0) = matE_q_T[info.localNo[0]].data();\n    krnl.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n    krnl.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n    krnl.lam = material[info.up[0]].get<lam>().data();\n    krnl.mu = material[info.up[0]].get<mu>().data();\n    krnl.execute(0);\n\n    transpose_JInv(fctNo, 0);\n}\n\nvoid Elasticity::prepare_volume_post_skeleton(std::size_t elNo, LinearAllocator<double>& scratch) {\n    base::prepare_volume_post_skeleton(elNo, scratch);\n\n    auto lam_field = material[elNo].get<lam>();\n    auto mu_field = material[elNo].get<mu>();\n    auto rhoInv_field = material[elNo].get<rhoInv>();\n\n    auto J_Q = vol[elNo].get<AbsDetJ>();\n    alignas(ALIGNMENT) double Jinv_Q[tensor::Jinv_Q::size()] = {};\n    for (unsigned q = 0; q < tensor::Jinv_Q::Shape[0]; ++q) {\n        Jinv_Q[q] = 1.0 / J_Q[q];\n    }\n\n    kernel::precomputeVolume krnl_pre;\n    krnl_pre.matE_Q_T = matE_Q_T.data();\n    krnl_pre.J = vol[elNo].get<AbsDetJ>().data();\n    krnl_pre.Jinv_Q = Jinv_Q;\n    krnl_pre.lam = lam_field.data();\n    krnl_pre.lam_W_J_Q = volPre[elNo].template get<lam_W_J_Q>().data();\n    krnl_pre.mu = mu_field.data();\n    krnl_pre.mu_W_J_Q = volPre[elNo].template get<mu_W_J_Q>().data();\n    krnl_pre.rhoInv = rhoInv_field.data();\n    krnl_pre.negative_rhoInv_W_Jinv_Q =\n        volPre[elNo].template get<negative_rhoInv_W_Jinv_Q>().data();\n    krnl_pre.W = volRule.weights().data();\n    krnl_pre.execute();\n}\n\nstd::pair<double, double> Elasticity::stiffness_tensor_bounds(std::size_t elNo) const {\n    auto lam_field = material[elNo].get<lam>();\n    auto mu_field = material[elNo].get<mu>();\n    assert(lam_field.size() == mu_field.size());\n\n    double c0 = std::numeric_limits<double>::max();\n    double c1 = std::numeric_limits<double>::lowest();\n    for (std::size_t i = 0, n = lam_field.size(); i < n; ++i) {\n        c0 = std::min(c0, 2.0 * mu_field[i]);\n        c1 = std::max(c1, Dim * lam_field[i] + 2.0 * mu_field[i]);\n    }\n    return {c0, c1};\n}\n\ndouble Elasticity::inverse_density_upper_bound(std::size_t elNo) const {\n    auto rhoInv_field = material[elNo].get<rhoInv>();\n\n    double ir1 = std::numeric_limits<double>::lowest();\n    for (std::size_t i = 0, n = rhoInv_field.size(); i < n; ++i) {\n        ir1 = std::max(ir1, rhoInv_field[i]);\n    }\n    return ir1;\n}\n\nvoid Elasticity::prepare_penalty(std::size_t fctNo, FacetInfo const& info,\n                                 LinearAllocator<double>&) {\n    auto const p = [&](int side) {\n        const auto [c0, c1] = stiffness_tensor_bounds(info.up[side]);\n        constexpr double c_N_1 = InverseInequality<Dim>::trace_constant(PolynomialDegree - 1);\n        return (Dim + 1) * c_N_1 * (area_[fctNo] / volume_[info.up[side]]) * (c1 * c1 / c0);\n    };\n\n    if (info.up[0] != info.up[1]) {\n        penalty_[fctNo] = (p(0) + p(1)) / 4.0;\n    } else {\n        penalty_[fctNo] = p(0);\n    }\n}\n\nvoid Elasticity::prepare_cfl(std::size_t elNo, mneme::span<SideInfo> info,\n                             LinearAllocator<double>&) {\n    double l_max = 0.0; // Bound for maximum eigenvalue\n    double bnd_area = 0.0;\n    for (std::size_t f = 0; f < NumFacets; ++f) {\n        const bool is_skeleton_face = elNo != info[f].lid;\n        const double gamma = is_skeleton_face ? 2.0 : 1.0;\n        const auto fctNo = info[f].fctNo;\n\n        constexpr double c_N = InverseInequality<Dim>::trace_constant(PolynomialDegree);\n        l_max += gamma * penalty_[fctNo] * c_N * area_[fctNo] / volume_[elNo];\n        bnd_area += area_[fctNo];\n    }\n\n    const auto [c0, c1] = stiffness_tensor_bounds(elNo);\n    const double ir1 = inverse_density_upper_bound(elNo);\n    const double h_1 = bnd_area / volume_[elNo];\n    constexpr double C_N = InverseInequality<Dim>::grad_constant(PolynomialDegree);\n    l_max += c1 * ir1 * C_N * h_1 * h_1;\n    l_max *= 2.0;\n    cfl_dt_[elNo] = 1.0 / sqrt(l_max);\n}\n\nbool Elasticity::assemble_volume(std::size_t elNo, Matrix<double>& A00,\n                                 LinearAllocator<double>& scratch) const {\n    alignas(ALIGNMENT) double Dx_Q[tensor::Dx_Q::size()];\n\n    assert(volRule.size() == tensor::W::Shape[0]);\n    assert(Dxi_Q.shape(0) == tensor::Dxi_Q::Shape[0]);\n    assert(Dxi_Q.shape(1) == tensor::Dxi_Q::Shape[1]);\n    assert(Dxi_Q.shape(2) == tensor::Dxi_Q::Shape[2]);\n\n    kernel::Dx_Q dxKrnl;\n    dxKrnl.Dx_Q = Dx_Q;\n    dxKrnl.Dxi_Q = Dxi_Q.data();\n    dxKrnl.G = vol[elNo].get<JInv>().data()->data();\n    dxKrnl.execute();\n\n    kernel::assembleVolume krnl;\n    krnl.A = A00.data();\n    krnl.delta = init::delta::Values;\n    krnl.Dx_Q = Dx_Q;\n    krnl.lam_W_J_Q = volPre[elNo].get<lam_W_J_Q>().data();\n    krnl.mu_W_J_Q = volPre[elNo].get<mu_W_J_Q>().data();\n    krnl.execute();\n    return true;\n}\n\nbool Elasticity::assemble_skeleton(std::size_t fctNo, FacetInfo const& info, Matrix<double>& A00,\n                                   Matrix<double>& A01, Matrix<double>& A10, Matrix<double>& A11,\n                                   LinearAllocator<double>& scratch) const {\n    assert(fctRule.size() == tensor::w::Shape[0]);\n    assert(E_q[0].shape(0) == tensor::E_q::Shape[0][0]);\n    assert(E_q[0].shape(1) == tensor::E_q::Shape[0][1]);\n    assert(Dxi_q[0].shape(0) == tensor::Dxi_q::Shape[0][0]);\n    assert(Dxi_q[0].shape(1) == tensor::Dxi_q::Shape[0][1]);\n    assert(Dxi_q[0].shape(2) == tensor::Dxi_q::Shape[0][2]);\n\n    alignas(ALIGNMENT) double Dx_q0[tensor::Dx_q::size(0)];\n    alignas(ALIGNMENT) double Dx_q1[tensor::Dx_q::size(1)];\n\n    kernel::Dx_q dxKrnl;\n    dxKrnl.Dx_q(0) = Dx_q0;\n    dxKrnl.Dx_q(1) = Dx_q1;\n    dxKrnl.g(0) = fct[fctNo].get<JInv0>().data()->data();\n    dxKrnl.g(1) = fct[fctNo].get<JInv1>().data()->data();\n    for (unsigned side = 0; side < 2; ++side) {\n        dxKrnl.Dxi_q(side) = Dxi_q[info.localNo[side]].data();\n        dxKrnl.execute(side);\n    }\n\n    alignas(ALIGNMENT) double traction_op_q0[tensor::traction_op_q::size(0)];\n    alignas(ALIGNMENT) double traction_op_q1[tensor::traction_op_q::size(1)];\n\n    kernel::assembleTractionOp tOpKrnl;\n    tOpKrnl.delta = init::delta::Values;\n    tOpKrnl.Dx_q(0) = Dx_q0;\n    tOpKrnl.Dx_q(1) = Dx_q1;\n    tOpKrnl.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n    tOpKrnl.lam_q(1) = fctPre[fctNo].get<lam_q_1>().data();\n    tOpKrnl.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n    tOpKrnl.mu_q(1) = fctPre[fctNo].get<mu_q_1>().data();\n    tOpKrnl.n_q = fct[fctNo].get<Normal>().data()->data();\n    tOpKrnl.traction_op_q(0) = traction_op_q0;\n    tOpKrnl.traction_op_q(1) = traction_op_q1;\n    tOpKrnl.execute(0);\n    tOpKrnl.execute(1);\n\n    alignas(ALIGNMENT) double L_q0[tensor::L_q::size(0)];\n    alignas(ALIGNMENT) double L_q1[tensor::L_q::size(1)];\n    auto L_q = std::array<double*, 2>{L_q0, L_q1};\n\n    if (method_ == DGMethod::BR2) {\n        alignas(ALIGNMENT) double Lift0[tensor::Lift::size(0)];\n        alignas(ALIGNMENT) double Lift1[tensor::Lift::size(1)];\n        alignas(ALIGNMENT) double Minv[2][tensor::M::size()];\n        for (int i = 0; i < 2; ++i) {\n            compute_inverse_mass_matrix(info.up[i], Minv[i]);\n        }\n\n        kernel::lift_skeleton lift;\n        lift.delta = init::delta::Values;\n        lift.Lift(0) = Lift0;\n        lift.Lift(1) = Lift1;\n        lift.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n        lift.lam_q(1) = fctPre[fctNo].get<lam_q_1>().data();\n        lift.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n        lift.mu_q(1) = fctPre[fctNo].get<mu_q_1>().data();\n        lift.n_q = fct[fctNo].get<Normal>().data()->data();\n        lift.w = fctRule.weights().data();\n        for (int i = 0; i < 2; ++i) {\n            lift.E_q(i) = E_q[info.localNo[i]].data();\n            lift.L_q(i) = L_q[i];\n            lift.Minv(i) = Minv[i];\n        }\n        lift.execute(0);\n        lift.execute(1);\n    } else { // IP\n        kernel::lift_ip lift;\n        lift.delta = init::delta::Values;\n        lift.nl_q = fct[fctNo].get<NormalLength>().data();\n        for (int i = 0; i < 2; ++i) {\n            lift.E_q(i) = E_q[info.localNo[i]].data();\n            lift.L_q(i) = L_q[i];\n        }\n        lift.execute(0);\n        lift.execute(1);\n    }\n\n    kernel::assembleSurface krnl;\n    krnl.c00 = -0.5;\n    krnl.c01 = -krnl.c00;\n    krnl.c10 = epsilon * 0.5;\n    krnl.c11 = -krnl.c10;\n    krnl.c20 = penalty(fctNo);\n    krnl.c21 = -krnl.c20;\n    krnl.a(0, 0) = A00.data();\n    krnl.a(0, 1) = A01.data();\n    krnl.a(1, 0) = A10.data();\n    krnl.a(1, 1) = A11.data();\n    for (unsigned side = 0; side < 2; ++side) {\n        krnl.E_q(side) = E_q[info.localNo[side]].data();\n        krnl.L_q(side) = L_q[side];\n    }\n    krnl.traction_op_q(0) = traction_op_q0;\n    krnl.traction_op_q(1) = traction_op_q1;\n    krnl.w = fctRule.weights().data();\n    krnl.execute(0, 0);\n    krnl.execute(0, 1);\n    krnl.execute(1, 0);\n    krnl.execute(1, 1);\n\n    return true;\n}\n\nbool Elasticity::assemble_boundary(std::size_t fctNo, FacetInfo const& info, Matrix<double>& A00,\n                                   LinearAllocator<double>& scratch) const {\n    if (info.bc == BC::Natural) {\n        return false;\n    }\n\n    assert(fctRule.size() == tensor::w::Shape[0]);\n    assert(E_q[0].shape(0) == tensor::E_q::Shape[0][0]);\n    assert(E_q[0].shape(1) == tensor::E_q::Shape[0][1]);\n    assert(Dxi_q[0].shape(0) == tensor::Dxi_q::Shape[0][0]);\n    assert(Dxi_q[0].shape(1) == tensor::Dxi_q::Shape[0][1]);\n    assert(Dxi_q[0].shape(2) == tensor::Dxi_q::Shape[0][2]);\n\n    alignas(ALIGNMENT) double Dx_q0[tensor::Dx_q::size(0)];\n\n    kernel::Dx_q dxKrnl;\n    dxKrnl.Dx_q(0) = Dx_q0;\n    dxKrnl.g(0) = fct[fctNo].get<JInv0>().data()->data();\n    dxKrnl.Dxi_q(0) = Dxi_q[info.localNo[0]].data();\n    dxKrnl.execute(0);\n\n    alignas(ALIGNMENT) double traction_op_q0[tensor::traction_op_q::size(0)];\n\n    kernel::assembleTractionOp tOpKrnl;\n    tOpKrnl.delta = init::delta::Values;\n    tOpKrnl.Dx_q(0) = Dx_q0;\n    tOpKrnl.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n    tOpKrnl.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n    tOpKrnl.n_q = fct[fctNo].get<Normal>().data()->data();\n    tOpKrnl.traction_op_q(0) = traction_op_q0;\n    tOpKrnl.execute(0);\n\n    alignas(ALIGNMENT) double L_q0[tensor::L_q::size(0)];\n    if (method_ == DGMethod::BR2) {\n        alignas(ALIGNMENT) double Lift0[tensor::Lift::size(0)];\n        alignas(ALIGNMENT) double Minv0[tensor::M::size()];\n        compute_inverse_mass_matrix(info.up[0], Minv0);\n\n        kernel::lift_boundary lift;\n        lift.delta = init::delta::Values;\n        lift.Lift(0) = Lift0;\n        lift.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n        lift.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n        lift.n_q = fct[fctNo].get<Normal>().data()->data();\n        lift.w = fctRule.weights().data();\n        lift.E_q(0) = E_q[info.localNo[0]].data();\n        lift.L_q(0) = L_q0;\n        lift.Minv(0) = Minv0;\n        lift.execute();\n    } else { // IP\n        kernel::lift_ip lift;\n        lift.delta = init::delta::Values;\n        lift.nl_q = fct[fctNo].get<NormalLength>().data();\n        lift.E_q(0) = E_q[info.localNo[0]].data();\n        lift.L_q(0) = L_q0;\n        lift.execute(0);\n    }\n\n    kernel::assembleSurface krnl;\n    krnl.c00 = -1.0;\n    krnl.c10 = epsilon;\n    krnl.c20 = penalty(fctNo);\n    krnl.a(0, 0) = A00.data();\n    krnl.E_q(0) = E_q[info.localNo[0]].data();\n    krnl.L_q(0) = L_q0;\n    krnl.traction_op_q(0) = traction_op_q0;\n    krnl.w = fctRule.weights().data();\n    krnl.execute(0, 0);\n\n    return true;\n}\n\nbool Elasticity::rhs_volume(std::size_t elNo, Vector<double>& B,\n                            LinearAllocator<double>& scratch) const {\n    if (!fun_force) {\n        return false;\n    }\n\n    assert(tensor::b::Shape[0] == tensor::A::Shape[0]);\n\n    double F_Q_raw[tensor::F_Q::size()];\n    assert(tensor::F_Q::Shape[1] == volRule.size());\n\n    auto F_Q = Matrix<double>(F_Q_raw, NumQuantities, volRule.size());\n    (*fun_force)(elNo, F_Q);\n\n    kernel::rhsVolume rhs;\n    rhs.E_Q = E_Q.data();\n    rhs.F_Q = F_Q_raw;\n    rhs.J = vol[elNo].get<AbsDetJ>().data();\n    rhs.W = volRule.weights().data();\n    rhs.b = B.data();\n    rhs.execute();\n    return true;\n}\n\nbool Elasticity::bc_skeleton(std::size_t fctNo, BC bc, double f_q_raw[]) const {\n    assert(tensor::f_q::Shape[1] == fctRule.size());\n    auto f_q = Matrix<double>(f_q_raw, NumQuantities, fctRule.size());\n    if (bc == BC::Fault && fun_slip) {\n        (*fun_slip)(fctNo, f_q, false);\n    } else if (bc == BC::Dirichlet && fun_dirichlet) {\n        (*fun_dirichlet)(fctNo, f_q, false);\n    } else {\n        return false;\n    }\n    return true;\n}\nbool Elasticity::bc_boundary(std::size_t fctNo, BC bc, double f_q_raw[]) const {\n    assert(tensor::f_q::Shape[1] == fctRule.size());\n    auto f_q = Matrix<double>(f_q_raw, NumQuantities, fctRule.size());\n    if (bc == BC::Fault && fun_slip) {\n        (*fun_slip)(fctNo, f_q, true);\n        for (std::size_t q = 0; q < tensor::f_q::Shape[1]; ++q) {\n            for (std::size_t p = 0; p < NumQuantities; ++p) {\n                f_q(p, q) *= 0.5;\n            }\n        }\n    } else if (bc == BC::Dirichlet && fun_dirichlet) {\n        (*fun_dirichlet)(fctNo, f_q, true);\n    } else {\n        return false;\n    }\n    return true;\n}\n\nbool Elasticity::rhs_skeleton(std::size_t fctNo, FacetInfo const& info, Vector<double>& B0,\n                              Vector<double>& B1, LinearAllocator<double>& scratch) const {\n    alignas(ALIGNMENT) double Dx_q[tensor::Dx_q::size(0)];\n    alignas(ALIGNMENT) double f_q_raw[tensor::f_q::size()];\n    if (!bc_skeleton(fctNo, info.bc, f_q_raw)) {\n        return false;\n    }\n\n    alignas(ALIGNMENT) double f_lifted_q[tensor::f_lifted_q::size()];\n    if (method_ == DGMethod::BR2) {\n        alignas(ALIGNMENT) double f_lifted0[tensor::f_lifted::size(0)];\n        alignas(ALIGNMENT) double f_lifted1[tensor::f_lifted::size(1)];\n        alignas(ALIGNMENT) double Minv[2][tensor::M::size()];\n        for (int i = 0; i < 2; ++i) {\n            compute_inverse_mass_matrix(info.up[i], Minv[i]);\n        }\n\n        kernel::rhs_lift_skeleton lift;\n        lift.delta = init::delta::Values;\n        lift.f_q = f_q_raw;\n        lift.f_lifted(0) = f_lifted0;\n        lift.f_lifted(1) = f_lifted1;\n        lift.f_lifted_q = f_lifted_q;\n        lift.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n        lift.lam_q(1) = fctPre[fctNo].get<lam_q_1>().data();\n        lift.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n        lift.mu_q(1) = fctPre[fctNo].get<mu_q_1>().data();\n        lift.n_q = fct[fctNo].get<Normal>().data()->data();\n        lift.w = fctRule.weights().data();\n        for (int i = 0; i < 2; ++i) {\n            lift.E_q(i) = E_q[info.localNo[i]].data();\n            lift.Minv(i) = Minv[i];\n        }\n        lift.execute();\n    } else { // IP\n        kernel::rhs_lift_ip lift;\n        lift.f_q = f_q_raw;\n        lift.f_lifted_q = f_lifted_q;\n        lift.nl_q = fct[fctNo].get<NormalLength>().data();\n        lift.execute();\n    }\n\n    kernel::rhsFacet rhs;\n    rhs.b = B0.data();\n    rhs.c10 = 0.5 * epsilon;\n    rhs.c20 = penalty(fctNo);\n    rhs.Dx_q(0) = Dx_q;\n    rhs.Dxi_q(0) = Dxi_q[info.localNo[0]].data();\n    rhs.E_q(0) = E_q[info.localNo[0]].data();\n    rhs.f_q = f_q_raw;\n    rhs.f_lifted_q = f_lifted_q;\n    rhs.g(0) = fct[fctNo].get<JInv0>().data()->data();\n    rhs.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n    rhs.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n    rhs.n_q = fct[fctNo].get<Normal>().data()->data();\n    rhs.w = fctRule.weights().data();\n    rhs.execute();\n\n    rhs.b = B1.data();\n    rhs.c20 *= -1.0;\n    rhs.Dxi_q(0) = Dxi_q[info.localNo[1]].data();\n    rhs.E_q(0) = E_q[info.localNo[1]].data();\n    rhs.g(0) = fct[fctNo].get<JInv1>().data()->data();\n    rhs.lam_q(0) = fctPre[fctNo].get<lam_q_1>().data();\n    rhs.mu_q(0) = fctPre[fctNo].get<mu_q_1>().data();\n    rhs.execute();\n\n    return true;\n}\n\nbool Elasticity::rhs_boundary(std::size_t fctNo, FacetInfo const& info, Vector<double>& B0,\n                              LinearAllocator<double>& scratch) const {\n    alignas(ALIGNMENT) double Dx_q[tensor::Dx_q::size(0)];\n    alignas(ALIGNMENT) double f_q_raw[tensor::f_q::size()];\n    if (!bc_boundary(fctNo, info.bc, f_q_raw)) {\n        return false;\n    }\n\n    alignas(ALIGNMENT) double f_lifted_q[tensor::f_lifted_q::size()];\n    if (method_ == DGMethod::BR2) {\n        alignas(ALIGNMENT) double f_lifted0[tensor::f_lifted::size(0)];\n        alignas(ALIGNMENT) double Minv0[tensor::M::size()];\n        compute_inverse_mass_matrix(info.up[0], Minv0);\n\n        kernel::rhs_lift_boundary lift;\n        lift.delta = init::delta::Values;\n        lift.f_q = f_q_raw;\n        lift.f_lifted(0) = f_lifted0;\n        lift.f_lifted_q = f_lifted_q;\n        lift.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n        lift.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n        lift.n_q = fct[fctNo].get<Normal>().data()->data();\n        lift.w = fctRule.weights().data();\n        lift.E_q(0) = E_q[info.localNo[0]].data();\n        lift.Minv(0) = Minv0;\n        lift.execute();\n    } else { // IP\n        kernel::rhs_lift_ip lift;\n        lift.f_q = f_q_raw;\n        lift.f_lifted_q = f_lifted_q;\n        lift.nl_q = fct[fctNo].get<NormalLength>().data();\n        lift.execute();\n    }\n\n    kernel::rhsFacet rhs;\n    rhs.b = B0.data();\n    rhs.c10 = epsilon;\n    rhs.c20 = penalty(fctNo);\n    rhs.Dx_q(0) = Dx_q;\n    rhs.Dxi_q(0) = Dxi_q[info.localNo[0]].data();\n    rhs.E_q(0) = E_q[info.localNo[0]].data();\n    rhs.f_q = f_q_raw;\n    rhs.f_lifted_q = f_lifted_q;\n    rhs.g(0) = fct[fctNo].get<JInv0>().data()->data();\n    rhs.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n    rhs.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n    rhs.n_q = fct[fctNo].get<Normal>().data()->data();\n    rhs.w = fctRule.weights().data();\n    rhs.execute();\n\n    return true;\n}\n\ntemplate <bool WithRHS>\nvoid Elasticity::apply_(std::size_t elNo, mneme::span<SideInfo> info,\n                        Vector<double const> const& x_0,\n                        std::array<Vector<double const>, NumFacets> const& x_n,\n                        Vector<double>& y_0) const {\n    alignas(ALIGNMENT) double Ju_Q[tensor::Ju_Q::size()];\n    kernel::apply_volume av;\n    av.delta = init::delta::Values;\n    av.Dxi_Q = Dxi_Q.data();\n    av.Dxi_Q_120 = Dxi_Q_120.data();\n    av.Ju_Q = Ju_Q;\n    av.G = vol[elNo].get<JInv>().data()->data();\n    av.G_Q_T = volPre[elNo].get<JInvT>().data()->data();\n    av.lam_W_J_Q = volPre[elNo].get<lam_W_J_Q>().data();\n    av.mu_W_J_Q = volPre[elNo].get<mu_W_J_Q>().data();\n    av.U = x_0.data();\n    av.Unew = y_0.data();\n    av.execute();\n\n    alignas(ALIGNMENT) double Ju_q0[tensor::Ju_q::size(0)];\n    alignas(ALIGNMENT) double Ju_q1[tensor::Ju_q::size(1)];\n    alignas(ALIGNMENT) double n_q_flipped[tensor::n_q::size()];\n    alignas(ALIGNMENT) double n_unit_q_flipped[tensor::n_unit_q::size()];\n    for (std::size_t f = 0; f < NumFacets; ++f) {\n        bool is_skeleton_face = elNo != info[f].lid;\n        bool is_fault_or_dirichlet = info[f].bc == BC::Fault || info[f].bc == BC::Dirichlet;\n\n        auto fctNo = info[f].fctNo;\n        double const* n_q = fct[fctNo].get<Normal>().data()->data();\n        double const* n_unit_q = fct[fctNo].get<UnitNormal>().data()->data();\n        double const* lam_q0 = fctPre[fctNo].get<lam_q_0>().data();\n        double const* lam_q1 = fctPre[fctNo].get<lam_q_1>().data();\n        double const* mu_q0 = fctPre[fctNo].get<mu_q_0>().data();\n        double const* mu_q1 = fctPre[fctNo].get<mu_q_1>().data();\n        double const* G_q_T0 = fctPre[fctNo].get<JInvT0>().data()->data();\n        double const* G_q_T1 = fctPre[fctNo].get<JInvT1>().data()->data();\n        if (is_skeleton_face && info[f].side == 1) {\n            std::swap(lam_q0, lam_q1);\n            std::swap(mu_q0, mu_q1);\n            std::swap(G_q_T0, G_q_T1);\n\n            for (int i = 0; i < tensor::n_q::size(); ++i) {\n                n_q_flipped[i] = -n_q[i];\n            }\n            n_q = n_q_flipped;\n            for (int i = 0; i < tensor::n_unit_q::size(); ++i) {\n                n_unit_q_flipped[i] = -n_unit_q[i];\n            }\n            n_unit_q = n_unit_q_flipped;\n        }\n\n        alignas(ALIGNMENT) double u_hat_minus_u_q[tensor::u_hat_minus_u_q::size()] = {};\n        alignas(ALIGNMENT) double sigma_hat_q[tensor::sigma_hat_q::size()] = {};\n\n        if (info[f].bc == BC::None || (is_skeleton_face && is_fault_or_dirichlet)) {\n            kernel::flux_u_skeleton fu;\n            fu.negative_E_q_T(0) = negative_E_q_T[f].data();\n            fu.E_q_T(1) = E_q_T[info[f].localNo].data();\n            fu.U = x_0.data();\n            fu.U_ext = x_n[f].data();\n            fu.u_hat_minus_u_q = u_hat_minus_u_q;\n            fu.execute();\n\n            kernel::flux_sigma_skeleton fs;\n            fs.c00 = -penalty(fctNo);\n            fs.delta = init::delta::Values;\n            fs.Dxi_q_120(0) = Dxi_q_120[f].data();\n            fs.Dxi_q_120(1) = Dxi_q_120[info[f].localNo].data();\n            fs.E_q_T(0) = E_q_T[f].data();\n            fs.G_q_T(0) = G_q_T0;\n            fs.G_q_T(1) = G_q_T1;\n            fs.lam_q(0) = lam_q0;\n            fs.lam_q(1) = lam_q1;\n            fs.mu_q(0) = mu_q0;\n            fs.mu_q(1) = mu_q1;\n            fs.negative_E_q_T(1) = negative_E_q_T[info[f].localNo].data();\n            fs.U = x_0.data();\n            fs.U_ext = x_n[f].data();\n            fs.n_unit_q = n_unit_q;\n            fs.sigma_hat_q = sigma_hat_q;\n            fs.Ju_q(0) = Ju_q0;\n            fs.Ju_q(1) = Ju_q1;\n            fs.execute();\n\n            if constexpr (WithRHS) {\n                alignas(ALIGNMENT) double f_q_raw[tensor::f_q::size()];\n                if (bc_skeleton(fctNo, info[f].bc, f_q_raw)) {\n                    double sign = info[f].side == 1 ? -1.0 : 1.0;\n                    kernel::flux_u_add_bc fub;\n                    fub.c00 = 0.5 * sign;\n                    fub.f_q = f_q_raw;\n                    fub.u_hat_minus_u_q = u_hat_minus_u_q;\n                    fub.execute();\n\n                    kernel::flux_sigma_add_bc fsb;\n                    fsb.c00 = sign * penalty(fctNo);\n                    fsb.f_q = f_q_raw;\n                    fsb.n_unit_q = n_unit_q;\n                    fsb.sigma_hat_q = sigma_hat_q;\n                    fsb.execute();\n                }\n            }\n        } else if (is_fault_or_dirichlet) {\n            kernel::flux_u_boundary fu;\n            fu.U = x_0.data();\n            fu.u_hat_minus_u_q = u_hat_minus_u_q;\n            fu.negative_E_q_T(0) = negative_E_q_T[f].data();\n            fu.execute();\n\n            kernel::flux_sigma_boundary fs;\n            fs.c00 = -penalty(fctNo);\n            fs.delta = init::delta::Values;\n            fs.Dxi_q_120(0) = Dxi_q_120[f].data();\n            fs.G_q_T(0) = G_q_T0;\n            fs.E_q_T(0) = E_q_T[f].data();\n            fs.lam_q(0) = lam_q0;\n            fs.mu_q(0) = mu_q0;\n            fs.U = x_0.data();\n            fs.n_unit_q = n_unit_q;\n            fs.sigma_hat_q = sigma_hat_q;\n            fs.Ju_q(0) = Ju_q0;\n            fs.execute();\n\n            if constexpr (WithRHS) {\n                alignas(ALIGNMENT) double f_q_raw[tensor::f_q::size()];\n                if (bc_boundary(fctNo, info[f].bc, f_q_raw)) {\n                    kernel::flux_u_add_bc fub;\n                    fub.c00 = 1.0;\n                    fub.f_q = f_q_raw;\n                    fub.u_hat_minus_u_q = u_hat_minus_u_q;\n                    fub.execute();\n\n                    kernel::flux_sigma_add_bc fsb;\n                    fsb.c00 = penalty(fctNo);\n                    fsb.f_q = f_q_raw;\n                    fsb.n_unit_q = n_unit_q;\n                    fsb.sigma_hat_q = sigma_hat_q;\n                    fsb.execute();\n                }\n            }\n        } else {\n            continue;\n        }\n\n        kernel::apply_facet af;\n        af.delta = init::delta::Values;\n        af.Dxi_q(0) = Dxi_q[f].data();\n        af.negative_E_q(0) = negative_E_q[f].data();\n        af.G_q_T(0) = G_q_T0;\n        af.lam_q(0) = lam_q0;\n        af.mu_q(0) = mu_q0;\n        af.n_q = n_q;\n        af.sigma_hat_q = sigma_hat_q;\n        af.u_hat_minus_u_q = u_hat_minus_u_q;\n        af.Unew = y_0.data();\n        af.w = fctRule.weights().data();\n        af.execute();\n    }\n}\n\nvoid Elasticity::apply(std::size_t elNo, mneme::span<SideInfo> info,\n                       Vector<double const> const& x_0,\n                       std::array<Vector<double const>, NumFacets> const& x_n,\n                       Vector<double>& y_0) const {\n    apply_<false>(elNo, std::move(info), x_0, x_n, y_0);\n}\n\nvoid Elasticity::wave_rhs(std::size_t elNo, mneme::span<SideInfo> info,\n                          Vector<double const> const& x_0,\n                          std::array<Vector<double const>, NumFacets> const& x_n,\n                          Vector<double>& y_0) const {\n    alignas(ALIGNMENT) double rhs_raw[tensor::Unew::size()];\n    auto rhs = Vector<double>(rhs_raw, y_0.shape(0));\n    apply_<true>(elNo, std::move(info), x_0, x_n, rhs);\n\n    kernel::apply_inverse_mass krnl;\n    krnl.E_Q = E_Q.data();\n    krnl.MinvRef = MhatInv.data();\n    krnl.Jinv_Q = volPre[elNo].get<negative_rhoInv_W_Jinv_Q>().data();\n    krnl.U = rhs_raw;\n    krnl.Unew = y_0.data();\n    krnl.execute();\n}\n\nvoid Elasticity::project(std::size_t elNo, volume_functional_t x, Vector<double>& y) const {\n    alignas(ALIGNMENT) double U_Q_raw[tensor::U_Q::size()];\n    alignas(ALIGNMENT) double U_raw[tensor::U::size()];\n\n    auto U_Q = Matrix<double>(U_Q_raw, NumQuantities, volRule.size());\n    x(elNo, U_Q);\n\n    kernel::project_u_rhs krnl;\n    krnl.E_Q = E_Q.data();\n    krnl.J = vol[elNo].get<AbsDetJ>().data();\n    krnl.U = U_raw;\n    krnl.U_Q = U_Q_raw;\n    krnl.W = volRule.weights().data();\n    krnl.execute();\n\n    auto J_Q = vol[elNo].get<AbsDetJ>();\n    auto const& w = volRule.weights();\n    alignas(ALIGNMENT) double Jinv_Q[tensor::Jinv_Q::size()] = {};\n    for (unsigned q = 0; q < tensor::Jinv_Q::Shape[0]; ++q) {\n        Jinv_Q[q] = w[q] / J_Q[q];\n    }\n\n    kernel::apply_inverse_mass im;\n    im.E_Q = E_Q.data();\n    im.MinvRef = MhatInv.data();\n    im.Jinv_Q = Jinv_Q;\n    im.U = U_raw;\n    im.Unew = y.data();\n    im.execute();\n}\n\nstd::size_t Elasticity::flops_apply(std::size_t elNo, mneme::span<SideInfo> info) const {\n    std::size_t flops = kernel::apply_volume::HardwareFlops;\n    for (std::size_t f = 0; f < NumFacets; ++f) {\n        bool is_skeleton_face = elNo != info[f].lid;\n        bool is_fault_or_dirichlet = info[f].bc == BC::Fault || info[f].bc == BC::Dirichlet;\n        if (info[f].bc == BC::None || (is_skeleton_face && is_fault_or_dirichlet)) {\n            flops += kernel::flux_u_skeleton::HardwareFlops;\n            flops += kernel::flux_sigma_skeleton::HardwareFlops;\n        } else if (is_fault_or_dirichlet) {\n            flops += kernel::flux_u_boundary::HardwareFlops;\n            flops += kernel::flux_sigma_boundary::HardwareFlops;\n        } else {\n            continue;\n        }\n        flops += kernel::apply_facet::HardwareFlops;\n    }\n    return flops;\n}\n\nvoid Elasticity::coefficients_volume(std::size_t elNo, Matrix<double>& C,\n                                     LinearAllocator<double>&) const {\n    auto const coeff_lam = material[elNo].get<lam>();\n    auto const coeff_mu = material[elNo].get<mu>();\n    assert(coeff_lam.size() == C.shape(0));\n    assert(coeff_mu.size() == C.shape(0));\n    assert(2 == C.shape(1));\n    for (std::size_t i = 0; i < C.shape(0); ++i) {\n        C(i, 0) = coeff_lam[i];\n        C(i, 1) = coeff_mu[i];\n    }\n}\n\nTensorBase<Matrix<double>> Elasticity::tractionResultInfo() const {\n    return TensorBase<Matrix<double>>(tensor::traction_q::Shape[0], tensor::traction_q::Shape[1]);\n}\n\nvoid Elasticity::traction_skeleton(std::size_t fctNo, FacetInfo const& info,\n                                   Vector<double const>& u0, Vector<double const>& u1,\n                                   Matrix<double>& result) const {\n    assert(result.size() == tensor::traction_q::size());\n    assert(u0.size() == tensor::u::size(0));\n    assert(u1.size() == tensor::u::size(1));\n\n    alignas(ALIGNMENT) double Dx_q0[tensor::Dx_q::size(0)];\n    alignas(ALIGNMENT) double Dx_q1[tensor::Dx_q::size(1)];\n\n    kernel::Dx_q dxKrnl;\n    dxKrnl.Dx_q(0) = Dx_q0;\n    dxKrnl.Dx_q(1) = Dx_q1;\n    dxKrnl.g(0) = fct[fctNo].get<JInv0>().data()->data();\n    dxKrnl.g(1) = fct[fctNo].get<JInv1>().data()->data();\n    for (unsigned side = 0; side < 2; ++side) {\n        dxKrnl.Dxi_q(side) = Dxi_q[info.localNo[side]].data();\n        dxKrnl.execute(side);\n    }\n\n    alignas(ALIGNMENT) double f_q_raw[tensor::f_q::size()];\n    bc_skeleton(fctNo, info.bc, f_q_raw);\n\n    kernel::compute_traction krnl;\n    krnl.c00 = -penalty(fctNo);\n    krnl.Dx_q(0) = Dx_q0;\n    krnl.Dx_q(1) = Dx_q1;\n    krnl.E_q(0) = E_q[info.localNo[0]].data();\n    krnl.E_q(1) = E_q[info.localNo[1]].data();\n    krnl.f_q = f_q_raw;\n    krnl.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n    krnl.lam_q(1) = fctPre[fctNo].get<lam_q_1>().data();\n    krnl.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n    krnl.mu_q(1) = fctPre[fctNo].get<mu_q_1>().data();\n    krnl.n_unit_q = fct[fctNo].get<UnitNormal>().data()->data();\n    krnl.traction_q = result.data();\n    krnl.u(0) = u0.data();\n    krnl.u(1) = u1.data();\n    krnl.execute();\n}\n\nvoid Elasticity::traction_boundary(std::size_t fctNo, FacetInfo const& info,\n                                   Vector<double const>& u0, Matrix<double>& result) const {\n\n    assert(result.size() == tensor::traction_q::size());\n    assert(u0.size() == tensor::u::size(0));\n\n    alignas(ALIGNMENT) double Dx_q0[tensor::Dx_q::size(0)];\n\n    kernel::Dx_q dxKrnl;\n    dxKrnl.Dx_q(0) = Dx_q0;\n    dxKrnl.g(0) = fct[fctNo].get<JInv0>().data()->data();\n    dxKrnl.Dxi_q(0) = Dxi_q[info.localNo[0]].data();\n    dxKrnl.execute(0);\n\n    alignas(ALIGNMENT) double f_q_raw[tensor::f_q::size()];\n    bc_boundary(fctNo, info.bc, f_q_raw);\n\n    kernel::compute_traction_bnd krnl;\n    krnl.c00 = -penalty(fctNo);\n    krnl.Dx_q(0) = Dx_q0;\n    krnl.E_q(0) = E_q[info.localNo[0]].data();\n    krnl.f_q = f_q_raw;\n    krnl.lam_q(0) = fctPre[fctNo].get<lam_q_0>().data();\n    krnl.mu_q(0) = fctPre[fctNo].get<mu_q_0>().data();\n    krnl.n_unit_q = fct[fctNo].get<UnitNormal>().data()->data();\n    krnl.traction_q = result.data();\n    krnl.u(0) = u0.data();\n    krnl.execute();\n}\n\n} // namespace tndm\n", "meta": {"hexsha": "7965dbc8d15ddab969e80fb61e6d5c4349d56efe", "size": 38913, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/localoperator/Elasticity.cpp", "max_stars_repo_name": "TEAR-ERC/tandem", "max_stars_repo_head_hexsha": "2db44f324c3205e81d28633ede261ad179334aa3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-11-03T17:11:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T07:51:01.000Z", "max_issues_repo_path": "app/localoperator/Elasticity.cpp", "max_issues_repo_name": "TEAR-ERC/tandem", "max_issues_repo_head_hexsha": "2db44f324c3205e81d28633ede261ad179334aa3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-05-18T14:51:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-16T12:56:31.000Z", "max_forks_repo_path": "app/localoperator/Elasticity.cpp", "max_forks_repo_name": "TEAR-ERC/tandem", "max_forks_repo_head_hexsha": "2db44f324c3205e81d28633ede261ad179334aa3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-10-23T08:04:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-15T12:23:59.000Z", "avg_line_length": 38.15, "max_line_length": 99, "alphanum_fraction": 0.5890062447, "num_tokens": 12373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.33458943461801643, "lm_q1q2_score": 0.2045619535184955}}
{"text": "/*\n\tCopyright (C) 2003-2014 by David White <davewx7@gmail.com>\n\t\n\tThis software is provided 'as-is', without any express or implied\n\twarranty. In no event will the authors be held liable for any damages\n\tarising from the use of this software.\n\n\tPermission is granted to anyone to use this software for any purpose,\n\tincluding commercial applications, and to alter it and redistribute it\n\tfreely, subject to the following restrictions:\n\n\t   1. The origin of this software must not be misrepresented; you must not\n\t   claim that you wrote the original software. If you use this software\n\t   in a product, an acknowledgement in the product documentation would be\n\t   appreciated but is not required.\n\n\t   2. Altered source versions must be plainly marked as such, and must not be\n\t   misrepresented as being the original software.\n\n\t   3. This notice may not be removed or altered from any source\n\t   distribution.\n*/\n\n#pragma once\n\n#include <string>\n\n#include <iosfwd>\n#include <boost/cstdint.hpp>\n#if defined(TARGET_BLACKBERRY)\n#include <math.h>\n#endif\n\nstatic const int64_t DECIMAL_PRECISION = 1000000;\nstatic const int64_t DECIMAL_PLACES = 6;\n\nclass decimal\n{\npublic:\n\tstatic decimal from_string(const std::string& s);\n\tstatic decimal from_int(int v) { return decimal(v); }\n\tstatic decimal from_raw_value(int64_t v) { decimal d; d.value_ = v; return d; }\n\tstatic decimal epsilon() { return decimal::from_raw_value(static_cast<int64_t>(1)); }\n\tdecimal() : value_(0) {}\n\texplicit decimal(int value) : value_(static_cast<int64_t>(value)*DECIMAL_PRECISION) {}\n#if defined(TARGET_BLACKBERRY)\n\texplicit decimal(double value) : value_(llround(value*DECIMAL_PRECISION)) {}\n#else\n\texplicit decimal(double value) : value_(static_cast<int64_t>(value*DECIMAL_PRECISION)) {}\n#endif\n\n\tint64_t value() const { return value_; }\n\tint as_int() const { return int( value_/DECIMAL_PRECISION ); }\n\tdouble as_float() const { return value_/static_cast<double>(DECIMAL_PRECISION); }\n\tfloat as_float32() const { return static_cast<float>(as_float()); }\n\tint64_t fractional() const { return value_%DECIMAL_PRECISION; }\n\n\tdecimal operator-() const {\n\t\treturn decimal(from_raw_value(-value_));\n\t}\n\n\tfriend decimal operator+(const decimal& a, const decimal& b);\n\tfriend decimal operator-(const decimal& a, const decimal& b);\n\tfriend decimal operator*(const decimal& a, const decimal& b);\n\tfriend decimal operator/(const decimal& a, const decimal& b);\n\n\tvoid operator+=(decimal a) { *this = *this + a; } \n\tvoid operator-=(decimal a) { *this = *this - a; } \n\tvoid operator*=(decimal a) { *this = *this * a; } \n\tvoid operator/=(decimal a) { *this = *this / a; }\n\n\tvoid operator+=(int a) { operator+=(decimal::from_int(a)); } \n\tvoid operator-=(int a) { operator-=(decimal::from_int(a)); } \n\tvoid operator*=(int a) { operator*=(decimal::from_int(a)); } \n\tvoid operator/=(int a) { operator/=(decimal::from_int(a)); }\n\nprivate:\n\tint64_t value_;\n};\n\ninline decimal operator+(const decimal& a, const decimal& b) {\n\treturn decimal::from_raw_value(a.value() + b.value());\n}\n\ninline decimal operator-(const decimal& a, const decimal& b) {\n\treturn decimal::from_raw_value(a.value() - b.value());\n}\n\ndecimal operator*(const decimal& a, const decimal& b);\ndecimal operator/(const decimal& a, const decimal& b);\n\ninline bool operator==(const decimal& a, const decimal& b) {\n\treturn a.value() == b.value();\n}\n\ninline bool operator!=(const decimal& a, const decimal& b) {\n\treturn !operator==(a, b);\n}\n\ninline bool operator<=(const decimal& a, const decimal& b) {\n\treturn a.value() <= b.value();\n}\n\ninline bool operator>=(const decimal& a, const decimal& b) {\n\treturn b <= a;\n}\n\ninline bool operator<(const decimal& a, const decimal& b) {\n\treturn !(b <= a);\n}\n\ninline bool operator>(const decimal& a, const decimal& b) {\n\treturn !(a <= b);\n}\n\ninline decimal operator+(decimal a, int b) { return operator+(a, decimal::from_int(b)); }\ninline decimal operator-(decimal a, int b) { return operator-(a, decimal::from_int(b)); }\ninline decimal operator*(decimal a, int b) { return operator*(a, decimal::from_int(b)); }\ninline decimal operator/(decimal a, int b) { return operator/(a, decimal::from_int(b)); }\ninline bool operator<(decimal a, int b) { return operator<(a, decimal::from_int(b)); }\ninline bool operator>(decimal a, int b) { return operator>(a, decimal::from_int(b)); }\ninline bool operator<=(decimal a, int b) { return operator<=(a, decimal::from_int(b)); }\ninline bool operator>=(decimal a, int b) { return operator>=(a, decimal::from_int(b)); }\n\ninline decimal operator+(int a, decimal b) { return operator+(decimal::from_int(a), b); }\ninline decimal operator-(int a, decimal b) { return operator-(decimal::from_int(a), b); }\ninline decimal operator*(int a, decimal b) { return operator*(decimal::from_int(a), b); }\ninline decimal operator/(int a, decimal b) { return operator/(decimal::from_int(a), b); }\ninline bool operator<(int a, decimal b) { return operator<(decimal::from_int(a), b); }\ninline bool operator>(int a, decimal b) { return operator>(decimal::from_int(a), b); }\ninline bool operator<=(int a, decimal b) { return operator<=(decimal::from_int(a), b); }\ninline bool operator>=(int a, decimal b) { return operator>=(decimal::from_int(a), b); }\n\nstd::ostream& operator<<(std::ostream& s, decimal d);\n", "meta": {"hexsha": "56a34661fbfc879d763e4abb295ff83370ef3948", "size": 5276, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/decimal.hpp", "max_stars_repo_name": "gamobink/anura", "max_stars_repo_head_hexsha": "410721a174aae98f32a55d71a4e666ad785022fd", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/decimal.hpp", "max_issues_repo_name": "gamobink/anura", "max_issues_repo_head_hexsha": "410721a174aae98f32a55d71a4e666ad785022fd", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/decimal.hpp", "max_forks_repo_name": "gamobink/anura", "max_forks_repo_head_hexsha": "410721a174aae98f32a55d71a4e666ad785022fd", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0814814815, "max_line_length": 90, "alphanum_fraction": 0.7115238817, "num_tokens": 1335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.20446893907525907}}
{"text": "#include \"timing.h\"\n#include \"pyp-topics.hh\"\n#include \"contexts_corpus.hh\"\n\n//Dict const *dict;\n\n//#include <boost/date_time/posix_time/posix_time_types.hpp>\nvoid PYPTopics::sample_corpus(const Corpus& corpus, int samples,\n                              int freq_cutoff_start, int freq_cutoff_end,\n                              int freq_cutoff_interval,\n                              int max_contexts_per_document,\n                              F temp_start, F temp_end) {\n  Timer timer;\n  //dict = &((ContextsCorpus*) &corpus)->dict();\n\n  if (!m_backoff.get()) {\n    m_word_pyps.clear();\n    m_word_pyps.push_back(PYPs());\n  }\n\n  std::cerr << \"\\n Training with \" << m_word_pyps.size()-1 << \" backoff level\"\n    << (m_word_pyps.size()==2 ? \":\" : \"s:\") << std::endl;\n\n\n  for (int i=0; i<(int)m_word_pyps.size(); ++i)\n  {\n    m_word_pyps.at(i).reserve(m_num_topics);\n    for (int j=0; j<m_num_topics; ++j)\n      m_word_pyps.at(i).push_back(new PYP<int>(0.01, 1.0, m_seed));\n  }\n  std::cerr << std::endl;\n\n  m_document_pyps.reserve(corpus.num_documents());\n  for (int j=0; j<corpus.num_documents(); ++j)\n    m_document_pyps.push_back(new PYP<int>(0.01, 1.0, m_seed));\n\n  m_topic_p0 = 1.0/m_num_topics;\n  m_term_p0 = 1.0/(F)m_backoff->terms_at_level(m_word_pyps.size()-1);\n  //m_term_p0 = 1.0/corpus.num_types();\n  m_backoff_p0 = 1.0/corpus.num_documents();\n\n  std::cerr << \" Documents: \" << corpus.num_documents() << \" Terms: \"\n    << corpus.num_types() << std::endl;\n\n  int frequency_cutoff = freq_cutoff_start;\n  std::cerr << \" Context frequency cutoff set to \" << frequency_cutoff << std::endl;\n\n  timer.Reset();\n  // Initialisation pass\n  int document_id=0, topic_counter=0;\n  for (Corpus::const_iterator corpusIt=corpus.begin();\n       corpusIt != corpus.end(); ++corpusIt, ++document_id) {\n    m_corpus_topics.push_back(DocumentTopics(corpusIt->size(), 0));\n\n    int term_index=0;\n    for (Document::const_iterator docIt=corpusIt->begin();\n         docIt != corpusIt->end(); ++docIt, ++term_index) {\n      topic_counter++;\n      Term term = *docIt;\n\n      // sample a new_topic\n      //int new_topic = (topic_counter % m_num_topics);\n      int freq = corpus.context_count(term);\n      int new_topic = -1;\n      if (freq > frequency_cutoff\n          && (!max_contexts_per_document || term_index < max_contexts_per_document)) {\n        //new_topic = sample(document_id, term);\n        //new_topic = document_id % m_num_topics;\n        new_topic = (int) (rnd() * m_num_topics);\n\n        // add the new topic to the PYPs\n        increment(term, new_topic);\n\n        if (m_use_topic_pyp) {\n          F p0 = m_topic_pyp.prob(new_topic, m_topic_p0);\n          int table_delta = m_document_pyps[document_id].increment(new_topic, p0);\n          if (table_delta)\n            m_topic_pyp.increment(new_topic, m_topic_p0);\n        }\n        else m_document_pyps[document_id].increment(new_topic, m_topic_p0);\n      }\n\n      m_corpus_topics[document_id][term_index] = new_topic;\n    }\n  }\n  std::cerr << \"  Initialized in \" << timer.Elapsed() << \" seconds\\n\";\n\n  int* randomDocIndices = new int[corpus.num_documents()];\n  for (int i = 0; i < corpus.num_documents(); ++i)\n\t  randomDocIndices[i] = i;\n\n  if (num_jobs < max_threads)\n    num_jobs = max_threads;\n  int job_incr = (int) ( (float)m_document_pyps.size() / float(num_jobs) );\n\n  // Sampling phase\n  for (int curr_sample=0; curr_sample < samples; ++curr_sample) {\n    if (freq_cutoff_interval > 0 && curr_sample != 1\n        && curr_sample % freq_cutoff_interval == 1\n        && frequency_cutoff > freq_cutoff_end) {\n      frequency_cutoff--;\n      std::cerr << \"\\n Context frequency cutoff set to \" << frequency_cutoff << std::endl;\n    }\n\n    F temp = 1.0 / (temp_start - curr_sample*(temp_start-temp_end)/samples);\n    std::cerr << \"\\n  -- Sample \" << curr_sample << \" (T=\" << temp << \") \"; std::cerr.flush();\n\n    // Randomize the corpus indexing array\n    int tmp;\n    int processed_terms=0;\n    /*\n    for (int i = corpus.num_documents()-1; i > 0; --i)\n    {\n        //i+1 since j \\in [0,i] but rnd() \\in [0,1)\n    \tint j = (int)(rnd() * (i+1));\n      assert(j >= 0 && j <= i);\n     \ttmp = randomDocIndices[i];\n    \trandomDocIndices[i] = randomDocIndices[j];\n    \trandomDocIndices[j] = tmp;\n    }\n    */\n\n    // for each document in the corpus\n    int document_id;\n    for (int i=0; i<corpus.num_documents(); ++i) {\n    \tdocument_id = randomDocIndices[i];\n\n      // for each term in the document\n      int term_index=0;\n      Document::const_iterator docEnd = corpus.at(document_id).end();\n      for (Document::const_iterator docIt=corpus.at(document_id).begin();\n           docIt != docEnd; ++docIt, ++term_index) {\n        if (max_contexts_per_document && term_index > max_contexts_per_document)\n          break;\n        \n        Term term = *docIt;\n\n        int freq = corpus.context_count(term);\n        if (freq < frequency_cutoff)\n          continue;\n\n        processed_terms++;\n\n        // remove the prevous topic from the PYPs\n        int current_topic = m_corpus_topics[document_id][term_index];\n        // a negative label mean that term hasn't been sampled yet\n        if (current_topic >= 0) {\n          decrement(term, current_topic);\n\n          int table_delta = m_document_pyps[document_id].decrement(current_topic);\n          if (m_use_topic_pyp && table_delta < 0)\n            m_topic_pyp.decrement(current_topic);\n        }\n\n        // sample a new_topic\n        int new_topic = sample(document_id, term, temp);\n        //std::cerr << \"TERM: \" << dict->Convert(term) << \" (\" << term << \") \" << \" Old Topic: \" \n        //  << current_topic << \" New Topic: \" << new_topic << \"\\n\" << std::endl;\n\n        // add the new topic to the PYPs\n        m_corpus_topics[document_id][term_index] = new_topic;\n        increment(term, new_topic);\n\n        if (m_use_topic_pyp) {\n          F p0 = m_topic_pyp.prob(new_topic, m_topic_p0);\n          int table_delta = m_document_pyps[document_id].increment(new_topic, p0);\n          if (table_delta)\n            m_topic_pyp.increment(new_topic, m_topic_p0);\n        }\n        else m_document_pyps[document_id].increment(new_topic, m_topic_p0);\n      }\n      if (document_id && document_id % 10000 == 0) {\n        std::cerr << \".\"; std::cerr.flush();\n      }\n    }\n    std::cerr << \" ||| LLH= \" << log_likelihood();\n\n    if (curr_sample != 0 && curr_sample % 10 == 0) {\n    //if (true) {\n      std::cerr << \" ||| time=\" << (timer.Elapsed() / 10.0) << \" sec/sample\" << std::endl;\n      timer.Reset();\n      std::cerr << \"     ... Resampling hyperparameters (\";\n      \n      // resample the hyperparamters\n      F log_p=0.0;\n      if (max_threads == 1)\n      { \n        std::cerr << \"1 thread)\" << std::endl; std::cerr.flush();\n        log_p += hresample_topics();\n        log_p += hresample_docs(0, m_document_pyps.size());\n      }\n      else\n      { //parallelize\n        std::cerr << max_threads << \" threads, \" << num_jobs << \" jobs)\" << std::endl; std::cerr.flush();\n        \n        WorkerPool<JobReturnsF, F> pool(max_threads); \n        int i=0, sz = m_document_pyps.size();\n        //documents...\n        while (i <= sz - 2*job_incr)\n        {    \n          JobReturnsF job = boost::bind(&PYPTopics::hresample_docs, this, i, i+job_incr);\n          pool.addJob(job);\n          i += job_incr;\n        }\n        //  do all remaining documents\n        JobReturnsF job = boost::bind(&PYPTopics::hresample_docs, this, i,sz);\n        pool.addJob(job);\n        \n        //topics...\n        JobReturnsF topics_job = boost::bind(&PYPTopics::hresample_topics, this);\n        pool.addJob(topics_job);\n\n        log_p += pool.get_result(); //blocks\n\n      }\n\n      if (m_use_topic_pyp) {\n        m_topic_pyp.resample_prior(rnd);\n        log_p += m_topic_pyp.log_restaurant_prob();\n      }\n\n      std::cerr.precision(10);\n      std::cerr << \" ||| LLH=\" << log_likelihood() << \" ||| resampling time=\" << timer.Elapsed() << \" sec\" << std::endl;\n      timer.Reset();\n\n      int k=0;\n      std::cerr << \"Topics distribution: \";\n      std::cerr.precision(2);\n      for (PYPs::iterator pypIt=m_word_pyps.front().begin();\n           pypIt != m_word_pyps.front().end(); ++pypIt, ++k) {\n        if (k % 5 == 0) std::cerr << std::endl << '\\t';\n        std::cerr << \"<\" << k << \":\" << pypIt->num_customers() << \",\"\n          << pypIt->num_types() << \",\" << m_topic_pyp.prob(k, m_topic_p0) << \"> \";\n      }\n      std::cerr.precision(10);\n      std::cerr << std::endl;\n    }\n  }\n  delete [] randomDocIndices;\n}\n\nPYPTopics::F PYPTopics::hresample_docs(int start, int end)\n{\n  int resample_counter=0;\n  F log_p = 0.0;\n  assert(start >= 0);\n  assert(end >= 0);\n  assert(start <= end);\n  for (int i=start; i < end; ++i)\n  {\n    m_document_pyps[i].resample_prior(rnd);\n    log_p += m_document_pyps[i].log_restaurant_prob();\n    if (resample_counter++ % 5000 == 0) {\n      std::cerr << \".\"; std::cerr.flush();\n    }\n  }\n  return log_p;\n}\n\nPYPTopics::F PYPTopics::hresample_topics()\n{\n  F log_p = 0.0;\n  for (std::vector<PYPs>::iterator levelIt=m_word_pyps.begin();\n      levelIt != m_word_pyps.end(); ++levelIt) {\n    for (PYPs::iterator pypIt=levelIt->begin();\n        pypIt != levelIt->end(); ++pypIt) {\n\n      pypIt->resample_prior(rnd);\n      log_p += pypIt->log_restaurant_prob();\n    }\n    std::cerr << log_p << std::endl;\n  }\n  return log_p;\n}\n\nPYPTopics::F PYPTopics::log_likelihood() const \n{\n  F log_p = 0.0;\n\n  // LLH of topic term distribution\n  size_t i=0;\n  for (std::vector<PYPs>::const_iterator levelIt=m_word_pyps.begin();\n      levelIt != m_word_pyps.end(); ++levelIt, ++i) {\n    for (PYPs::const_iterator pypIt=levelIt->begin();\n        pypIt != levelIt->end(); ++pypIt, ++i) {\n      log_p += pypIt->log_restaurant_prob();\n\n      if (i == m_word_pyps.size()-1)\n        log_p += (pypIt->num_tables() * -log(m_backoff->terms_at_level(i)));\n      else\n        log_p += (pypIt->num_tables() * log(m_term_p0));\n    }\n  }\n  std::cerr << \" TERM LLH: \" << log_p << \" \"; //std::endl;\n\n  // LLH of document topic distribution\n  for (size_t i=0; i < m_document_pyps.size(); ++i) {\n    log_p += m_document_pyps[i].log_restaurant_prob();\n    if (!m_use_topic_pyp) log_p += (m_document_pyps[i].num_tables() * m_topic_p0);\n  }\n  if (m_use_topic_pyp) {\n    log_p += m_topic_pyp.log_restaurant_prob();\n    log_p += (m_topic_pyp.num_tables() * log(m_topic_p0));\n  }\n\n  return log_p;\n}\n\nvoid PYPTopics::decrement(const Term& term, int topic, int level) {\n  //std::cerr << \"PYPTopics::decrement(\" << term << \",\" << topic << \",\" << level << \")\" << std::endl;\n  int table_delta = m_word_pyps.at(level).at(topic).decrement(term);\n  if (table_delta && m_backoff.get()) {\n    Term backoff_term = (*m_backoff)[term];\n    if (!m_backoff->is_null(backoff_term))\n      decrement(backoff_term, topic, level+1);\n  }\n}\n\nvoid PYPTopics::increment(const Term& term, int topic, int level) {\n  //std::cerr << \"PYPTopics::increment(\" << term << \",\" << topic << \",\" << level << \")\" << std::endl;\n  int table_delta = m_word_pyps.at(level).at(topic).increment(term, word_pyps_p0(term, topic, level));\n\n  if (table_delta && m_backoff.get()) {\n    Term backoff_term = (*m_backoff)[term];\n    if (!m_backoff->is_null(backoff_term))\n      increment(backoff_term, topic, level+1);\n  }\n}\n\nint PYPTopics::sample(const DocumentId& doc, const Term& term, F inv_temp) {\n  // First pass: collect probs\n  F sum=0.0;\n  std::vector<F> sums;\n  for (int k=0; k<m_num_topics; ++k) {\n    F p_w_k = prob(term, k);\n\n    F topic_prob = m_topic_p0;\n    if (m_use_topic_pyp) topic_prob = m_topic_pyp.prob(k, m_topic_p0);\n\n    //F p_k_d = m_document_pyps[doc].prob(k, topic_prob);\n    F p_k_d = m_document_pyps[doc].unnormalised_prob(k, topic_prob);\n\n    F prob = p_w_k*p_k_d;\n    /*\n    if (prob < 0.0) { std::cerr << \"\\n\\n\" << prob << \" \" << p_w_k << \" \" << p_k_d << std::endl; assert(false); }\n    if (prob > 1.0) { std::cerr << \"\\n\\n\" << prob << \" \" << p_w_k << \" \" << p_k_d << std::endl; assert(false); }\n    assert (pow(prob, inv_temp) >= 0.0);\n    assert (pow(prob, inv_temp) <= 1.0);\n    */\n    sum += pow(prob, inv_temp);\n    sums.push_back(sum);\n  }\n  // Second pass: sample a topic\n  F cutoff = rnd() * sum;\n  for (int k=0; k<m_num_topics; ++k) {\n    if (cutoff <= sums[k])\n      return k;\n  }\n  assert(false);\n}\n\nPYPTopics::F PYPTopics::word_pyps_p0(const Term& term, int topic, int level) const {\n  //for (int i=0; i<level+1; ++i) std::cerr << \"  \";\n  //std::cerr << \"PYPTopics::word_pyps_p0(\" << term << \",\" << topic << \",\" << level << \")\" << std::endl;\n\n  F p0 = m_term_p0;\n  if (m_backoff.get()) {\n    //static F fudge=m_backoff_p0; // TODO\n\n    Term backoff_term = (*m_backoff)[term];\n    //std::cerr << \"T: \" << term << \" BO: \" << backoff_term << std::endl;\n    if (!m_backoff->is_null(backoff_term)) {\n      assert (level < m_backoff->order());\n      //p0 = (1.0/(F)m_backoff->terms_at_level(level))*prob(backoff_term, topic, level+1);\n      p0 = m_term_p0*prob(backoff_term, topic, level+1);\n      p0 = prob(backoff_term, topic, level+1);\n    }\n    else\n      p0 = (1.0/(F) m_backoff->terms_at_level(level));\n      //p0 = m_term_p0;\n  }\n  //for (int i=0; i<level+1; ++i) std::cerr << \"  \";\n  //std::cerr << \"PYPTopics::word_pyps_p0(\" << term << \",\" << topic << \",\" << level << \") = \" << p0 << std::endl;\n  return p0;\n}\n\nPYPTopics::F PYPTopics::prob(const Term& term, int topic, int level) const {\n  //for (int i=0; i<level+1; ++i) std::cerr << \"  \";\n  //std::cerr << \"PYPTopics::prob(\" << dict->Convert(term) << \",\" << topic << \",\" << level << \")\" << std::endl;\n\n  F p0 = word_pyps_p0(term, topic, level);\n  F p_w_k = m_word_pyps.at(level).at(topic).prob(term, p0);\n\n  /*\n  for (int i=0; i<level+1; ++i) std::cerr << \"  \";\n  std::cerr << \"PYPTopics::prob(\" << dict->Convert(term) << \",\" << topic << \",\" << level << \") = \" << p_w_k << std::endl;\n  for (int i=0; i<level+1; ++i) std::cerr << \"  \";\n  m_word_pyps.at(level).at(topic).debug_info(std::cerr);\n  */\n  return p_w_k;\n}\n\nint PYPTopics::max_topic() const {\n  if (!m_use_topic_pyp)\n    return -1;\n\n  F current_max=0.0;\n  int current_topic=-1;\n  for (int k=0; k<m_num_topics; ++k) {\n    F prob = m_topic_pyp.prob(k, m_topic_p0);\n    if (prob > current_max) {\n      current_max = prob;\n      current_topic = k;\n    }\n  }\n  assert(current_topic >= 0);\n  return current_topic;\n}\n\nstd::pair<int,PYPTopics::F> PYPTopics::max(const DocumentId& doc) const {\n  //std::cerr << \"PYPTopics::max(\" << doc << \",\" << term << \")\" << std::endl;\n  // collect probs\n  F current_max=0.0;\n  int current_topic=-1;\n  for (int k=0; k<m_num_topics; ++k) {\n    //F p_w_k = prob(term, k);\n\n    F topic_prob = m_topic_p0;\n    if (m_use_topic_pyp)\n      topic_prob = m_topic_pyp.prob(k, m_topic_p0);\n\n    F prob = 0;\n    if (doc < 0) prob = topic_prob;\n    else         prob = m_document_pyps[doc].prob(k, topic_prob);\n\n    if (prob > current_max) {\n      current_max = prob;\n      current_topic = k;\n    }\n  }\n  assert(current_topic >= 0);\n  assert(current_max >= 0);\n  return std::make_pair(current_topic, current_max);\n}\n\nstd::pair<int,PYPTopics::F> PYPTopics::max(const DocumentId& doc, const Term& term) const {\n  //std::cerr << \"PYPTopics::max(\" << doc << \",\" << term << \")\" << std::endl;\n  // collect probs\n  F current_max=0.0;\n  int current_topic=-1;\n  for (int k=0; k<m_num_topics; ++k) {\n    F p_w_k = prob(term, k);\n\n    F topic_prob = m_topic_p0;\n    if (m_use_topic_pyp)\n      topic_prob = m_topic_pyp.prob(k, m_topic_p0);\n\n    F p_k_d = 0;\n    if (doc < 0) p_k_d = topic_prob;\n    else         p_k_d = m_document_pyps[doc].prob(k, topic_prob);\n\n    F prob = (p_w_k*p_k_d);\n    if (prob > current_max) {\n      current_max = prob;\n      current_topic = k;\n    }\n  }\n  assert(current_topic >= 0);\n  assert(current_max >= 0);\n  return std::make_pair(current_topic,current_max);\n}\n\nstd::ostream& PYPTopics::print_document_topics(std::ostream& out) const {\n  for (CorpusTopics::const_iterator corpusIt=m_corpus_topics.begin();\n       corpusIt != m_corpus_topics.end(); ++corpusIt) {\n    int term_index=0;\n    for (DocumentTopics::const_iterator docIt=corpusIt->begin();\n         docIt != corpusIt->end(); ++docIt, ++term_index) {\n      if (term_index) out << \" \";\n      out << *docIt;\n    }\n    out << std::endl;\n  }\n  return out;\n}\n\nstd::ostream& PYPTopics::print_topic_terms(std::ostream& out) const {\n  for (PYPs::const_iterator pypsIt=m_word_pyps.front().begin();\n       pypsIt != m_word_pyps.front().end(); ++pypsIt) {\n    int term_index=0;\n    for (PYP<int>::const_iterator termIt=pypsIt->begin();\n         termIt != pypsIt->end(); ++termIt, ++term_index) {\n      if (term_index) out << \" \";\n      out << termIt->first << \":\" << termIt->second;\n    }\n    out << std::endl;\n  }\n  return out;\n}\n", "meta": {"hexsha": "4de52fd7afca2de388c2b8587e3843209c20ff10", "size": 16681, "ext": "cc", "lang": "C++", "max_stars_repo_path": "gi/pyp-topics/src/pyp-topics.cc", "max_stars_repo_name": "agesmundo/FasterCubePruning", "max_stars_repo_head_hexsha": "f80150140b5273fd1eb0dfb34bdd789c4cbd35e6", "max_stars_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-03T00:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-03T00:44:01.000Z", "max_issues_repo_path": "gi/pyp-topics/src/pyp-topics.cc", "max_issues_repo_name": "jhclark/cdec", "max_issues_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_issues_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gi/pyp-topics/src/pyp-topics.cc", "max_forks_repo_name": "jhclark/cdec", "max_forks_repo_head_hexsha": "237ddc67ffa61da310e19710f902d4771dc323c2", "max_forks_repo_licenses": ["BSD-3-Clause-LBNL", "Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-19T12:44:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-19T12:44:54.000Z", "avg_line_length": 33.362, "max_line_length": 121, "alphanum_fraction": 0.5915113003, "num_tokens": 5025, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381667555713, "lm_q2_score": 0.3738758227716967, "lm_q1q2_score": 0.20441218193642832}}
{"text": "#include <cstdlib>\n#include <vector>\n#include <cmath>\n#include <Eigen/Core>\n#include <moihgp/moihgp.h>\n#include <moihgp/matern32ss.h>\n#include <moihgp/matern52ss.h>\n\n#ifdef _WIN32\n#ifdef LIBRARY_EXPORTS\n#define LIBRARY_API __declspec(dllexport)\n#else\n#define LIBRARY_API __declspec(dllimport)\n#endif\n#else\n#define LIBRARY_API\n#endif\n\n\n\ntypedef moihgp::MOIHGP<moihgp::Matern32StateSpace> GP32;\ntypedef moihgp::MOIHGP<moihgp::Matern32StateSpace> GP52;\n\n\n\nextern \"C\"\n{\n\n\n\nLIBRARY_API GP32* gp32_new(double dt, size_t num_output, size_t num_latent, bool threading)\n{\n    return new GP32(dt, num_output, num_latent, threading);\n} // GP32* gp32_new(double dt, size_t num_output, size_t num_latent, bool threading)\n\n\nLIBRARY_API void gp32_del(GP32* gp)\n{\n    gp->~MOIHGP();\n} // void gp32_del(GP32* gp)\n\n\nLIBRARY_API void gp32_step1(GP32* gp, double* x, double* y, double* dx, double* xnew, double* yhat, double* dxnew)\n{\n\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _y(num_output);\n    std::vector<std::vector<Eigen::VectorXd>> _dx(num_latent, std::vector<Eigen::VectorXd>(igp_num_param, Eigen::VectorXd(dim).setZero()));\n    std::vector<Eigen::VectorXd> _xnew(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _yhat(num_output);\n    std::vector<std::vector<Eigen::VectorXd>> _dxnew(num_latent, std::vector<Eigen::VectorXd>(igp_num_param, Eigen::VectorXd(dim).setZero()));\n\n    _y = Eigen::Map<Eigen::VectorXd>(y, num_output, 1);\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n        for (size_t idx2 = 0; idx2 < igp_num_param; idx2++)\n        {\n            for (size_t idx3 = 0; idx3 < dim; idx3++)\n            {\n                _dx[idx1][idx2](idx3) = dx[idx1 * igp_num_param * dim + idx2 * dim + idx3];\n            }\n        }\n    }\n\n    gp->step(_x, _y, _dx, _xnew, _yhat, _dxnew);\n\n    for (size_t idx = 0; idx < num_output; idx++)\n    {\n        yhat[idx] = _yhat(idx);\n    }\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            xnew[idx1 * dim + idx2] = _xnew[idx1](idx2);\n        }\n        for (size_t idx2 = 0; idx2 < igp_num_param; idx2++)\n        {\n            for (size_t idx3 = 0; idx3 < dim; idx3++)\n            {\n                dxnew[idx1 * igp_num_param * dim + idx2 * dim + idx3] = _dxnew[idx1][idx2](idx3);\n            }\n        }\n    }\n\n} // void gp32_step1(GP32* gp, double* x, double* y, double* dx, double* xnew, double* yhat, double* dxnew)\n\n\nLIBRARY_API void gp32_step2(GP32* gp, double* x, double* y, double* dx, double* xnew, double* dxnew)\n{\n\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _y(num_output);\n    std::vector<std::vector<Eigen::VectorXd>> _dx(num_latent, std::vector<Eigen::VectorXd>(igp_num_param, Eigen::VectorXd(dim).setZero()));\n    std::vector<Eigen::VectorXd> _xnew(num_latent, Eigen::VectorXd(dim).setZero());\n    std::vector<std::vector<Eigen::VectorXd>> _dxnew(num_latent, std::vector<Eigen::VectorXd>(igp_num_param, Eigen::VectorXd(dim).setZero()));\n\n    _y = Eigen::Map<Eigen::VectorXd>(y, num_output, 1);\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n        for (size_t idx2 = 0; idx2 < igp_num_param; idx2++)\n        {\n            for (size_t idx3 = 0; idx3 < dim; idx3++)\n            {\n                _dx[idx1][idx2](idx3) = dx[idx1 * igp_num_param * dim + idx2 * dim + idx3];\n            }\n        }\n    }\n\n    gp->step(_x, _y, _dx, _xnew, _dxnew);\n\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            xnew[idx1 * dim + idx2] = _xnew[idx1](idx2);\n        }\n        for (size_t idx2 = 0; idx2 < igp_num_param; idx2++)\n        {\n            for (size_t idx3 = 0; idx3 < dim; idx3++)\n            {\n                dxnew[idx1 * igp_num_param * dim + idx2 * dim + idx3] = _dxnew[idx1][idx2](idx3);\n            }\n        }\n    }\n\n} // void gp32_step2(GP32* gp, double* x, double* y, double* dx, double* xnew, double* dxnew)\n\n\nLIBRARY_API void gp32_step3(GP32* gp, double* x, double* y, double* xnew, double* yhat)\n{\n\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _y(num_output);\n    std::vector<Eigen::VectorXd> _xnew(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _yhat(num_output);\n\n    _y = Eigen::Map<Eigen::VectorXd>(y, num_output, 1);\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n    }\n\n    gp->step(_x, _y, _xnew, _yhat);\n\n    for (size_t idx = 0; idx < num_output; idx++)\n    {\n        yhat[idx] = _yhat(idx);\n    }\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            xnew[idx1 * dim + idx2] = _xnew[idx1](idx2);\n        }\n    }\n\n} // void gp32_step3(GP32* gp, double* x, double* y, double* xnew, double* yhat)\n\n\nLIBRARY_API void gp32_step4(GP32* gp, double* x, double* xnew, double* yhat)\n{\n\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    std::vector<Eigen::VectorXd> _xnew(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _yhat(num_output);\n\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n    }\n\n    gp->step(_x, _xnew, _yhat);\n\n    for (size_t idx = 0; idx < num_output; idx++)\n    {\n        yhat[idx] = _yhat(idx);\n    }\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            xnew[idx1 * dim + idx2] = _xnew[idx1](idx2);\n        }\n    }\n\n} // void gp32_step4(GP32* gp, double* x, double* xnew, double* yhat)\n\n\nLIBRARY_API void gp32_update(GP32* gp, double* params)\n{\n    size_t num_param = gp->getNumParam();\n    Eigen::VectorXd _params = Eigen::Map<Eigen::VectorXd>(params, num_param, 1);\n    gp->update(_params);\n} // void gp32_update(GP32* gp, double* params)\n\n\nLIBRARY_API double gp32_lik1(GP32* gp, double* x, double* y, double* dx, double* grad)\n{\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t num_param = gp->getNumParam();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _y(num_output);\n    std::vector<std::vector<Eigen::VectorXd>> _dx(num_latent, std::vector<Eigen::VectorXd>(igp_num_param, Eigen::VectorXd(dim).setZero()));\n    Eigen::VectorXd _grad(num_param);\n\n    _y = Eigen::Map<Eigen::VectorXd>(y, num_output, 1);\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n        for (size_t idx2 = 0; idx2 < igp_num_param; idx2++)\n        {\n            for (size_t idx3 = 0; idx3 < dim; idx3++)\n            {\n                _dx[idx1][idx2](idx3) = dx[idx1 * igp_num_param * dim + idx2 * dim + idx3];\n            }\n        }\n    }\n\n    double loss = gp->negLogLikelihood(_x, _y, _dx, _grad);\n\n    for (size_t idx = 0; idx < num_param; idx++)\n    {\n        grad[idx] = _grad(idx);\n    }\n\n    return loss;\n\n} // double gp32_lik1(GP32* gp, double* x, double* y, double* dx, Eigen::VectorXd &grad)\n\n\nLIBRARY_API double gp32_lik2(GP32* gp, double* x, double* y)\n{\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t num_param = gp->getNumParam();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _y(num_output);\n\n    _y = Eigen::Map<Eigen::VectorXd>(y, num_output, 1);\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n    }\n\n    double loss = gp->negLogLikelihood(_x, _y);\n\n    return loss;\n\n} // double gp32_lik2(GP32* gp, double* x, double* y)\n\n\nLIBRARY_API void gp32_get_params(GP32* gp, double* params)\n{\n    size_t num_param = gp->getNumParam();\n    Eigen::VectorXd _params = gp->getParams();\n    for (size_t idx = 0; idx < num_param; idx++)\n    {\n        params[idx] = _params(idx);\n    }\n} // void gp32_get_params(GP32* gp, double* params)\n\n\nLIBRARY_API size_t gp32_igp_dim(GP32* gp)\n{\n    return gp->getIGPDim();\n}\n\n\nLIBRARY_API size_t gp32_num_param(GP32* gp)\n{\n    return gp->getNumParam();\n}\n\n\nLIBRARY_API size_t gp32_num_igp_param(GP32* gp)\n{\n    return gp->getNumIGPParam();\n}\n\n\nLIBRARY_API GP52* gp52_new(double dt, size_t num_output, size_t num_latent, bool threading)\n{\n    return new GP52(dt, num_output, num_latent, threading);\n} // GP52* gp52_new(double dt, size_t num_output, size_t num_latent, bool threading)\n\n\nLIBRARY_API void gp52_del(GP52* gp)\n{\n    gp->~MOIHGP();\n} // void gp52_del(GP52* gp)\n\n\nLIBRARY_API void gp52_step1(GP52* gp, double* x, double* y, double* dx, double* xnew, double* yhat, double* dxnew)\n{\n\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _y(num_output);\n    std::vector<std::vector<Eigen::VectorXd>> _dx(num_latent, std::vector<Eigen::VectorXd>(igp_num_param, Eigen::VectorXd(dim).setZero()));\n    std::vector<Eigen::VectorXd> _xnew(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _yhat(num_output);\n    std::vector<std::vector<Eigen::VectorXd>> _dxnew(num_latent, std::vector<Eigen::VectorXd>(igp_num_param, Eigen::VectorXd(dim).setZero()));\n\n    _y = Eigen::Map<Eigen::VectorXd>(y, num_output, 1);\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n        for (size_t idx2 = 0; idx2 < igp_num_param; idx2++)\n        {\n            for (size_t idx3 = 0; idx3 < dim; idx3++)\n            {\n                _dx[idx1][idx2](idx3) = dx[idx1 * igp_num_param * dim + idx2 * dim + idx3];\n            }\n        }\n    }\n\n    gp->step(_x, _y, _dx, _xnew, _yhat, _dxnew);\n\n    for (size_t idx = 0; idx < num_output; idx++)\n    {\n        yhat[idx] = _yhat(idx);\n    }\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            xnew[idx1 * dim + idx2] = _xnew[idx1](idx2);\n        }\n        for (size_t idx2 = 0; idx2 < igp_num_param; idx2++)\n        {\n            for (size_t idx3 = 0; idx3 < dim; idx3++)\n            {\n                dxnew[idx1 * igp_num_param * dim + idx2 * dim + idx3] = _dxnew[idx1][idx2](idx3);\n            }\n        }\n    }\n\n} // void gp52_step1(GP52* gp, double* x, double* y, double* dx, double* xnew, double* yhat, double* dxnew)\n\n\nLIBRARY_API void gp52_step2(GP52* gp, double* x, double* y, double* dx, double* xnew, double* dxnew)\n{\n\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _y(num_output);\n    std::vector<std::vector<Eigen::VectorXd>> _dx(num_latent, std::vector<Eigen::VectorXd>(igp_num_param, Eigen::VectorXd(dim).setZero()));\n    std::vector<Eigen::VectorXd> _xnew(num_latent, Eigen::VectorXd(dim).setZero());\n    std::vector<std::vector<Eigen::VectorXd>> _dxnew(num_latent, std::vector<Eigen::VectorXd>(igp_num_param, Eigen::VectorXd(dim).setZero()));\n\n    _y = Eigen::Map<Eigen::VectorXd>(y, num_output, 1);\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n        for (size_t idx2 = 0; idx2 < igp_num_param; idx2++)\n        {\n            for (size_t idx3=0; idx3 < dim; idx3++)\n            {\n                _dx[idx1][idx2](idx3) = dx[idx1 * igp_num_param * dim + idx2 * dim + idx3];\n            }\n        }\n    }\n\n    gp->step(_x, _y, _dx, _xnew, _dxnew);\n\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            xnew[idx1 * dim + idx2] = _xnew[idx1](idx2);\n        }\n        for (size_t idx2 = 0; idx2 < igp_num_param; idx2++)\n        {\n            for (size_t idx3 = 0; idx3 < dim; idx3++)\n            {\n                dxnew[idx1 * igp_num_param * dim + idx2 * dim + idx3] = _dxnew[idx1][idx2](idx3);\n            }\n        }\n    }\n\n} // void gp52_step2(GP52* gp, double* x, double* y, double* dx, double* xnew, double* dxnew)\n\n\nLIBRARY_API void gp52_step3(GP52* gp, double* x, double* y, double* xnew, double* yhat)\n{\n\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _y(num_output);\n    std::vector<Eigen::VectorXd> _xnew(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _yhat(num_output);\n\n    _y = Eigen::Map<Eigen::VectorXd>(y, num_output, 1);\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n    }\n\n    gp->step(_x, _y, _xnew, _yhat);\n\n    for (size_t idx = 0; idx < num_output; idx++)\n    {\n        yhat[idx] = _yhat(idx);\n    }\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            xnew[idx1 * dim + idx2] = _xnew[idx1](idx2);\n        }\n    }\n\n} // void gp52_step3(GP52* gp, double* x, double* y, double* xnew, double* yhat)\n\n\nLIBRARY_API void gp52_step4(GP52* gp, double* x, double* xnew, double* yhat)\n{\n\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    std::vector<Eigen::VectorXd> _xnew(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _yhat(num_output);\n\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n    }\n\n    gp->step(_x, _xnew, _yhat);\n\n    for (size_t idx = 0; idx < num_output; idx++)\n    {\n        yhat[idx] = _yhat(idx);\n    }\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            xnew[idx1 * dim + idx2] = _xnew[idx1](idx2);\n        }\n    }\n\n} // void gp52_step4(GP52* gp, double* x, double* xnew, double* yhat)\n\n\nLIBRARY_API void gp52_update(GP52* gp, double* params)\n{\n    size_t num_param = gp->getNumParam();\n    Eigen::VectorXd _params = Eigen::Map<Eigen::VectorXd>(params, num_param, 1);\n    gp->update(_params);\n} // void gp52_update(GP52* gp, double* params)\n\n\nLIBRARY_API double gp52_lik1(GP52* gp, double* x, double* y, double* dx, double* grad)\n{\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t num_param = gp->getNumParam();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _y(num_output);\n    std::vector<std::vector<Eigen::VectorXd>> _dx(num_latent, std::vector<Eigen::VectorXd>(igp_num_param, Eigen::VectorXd(dim).setZero()));\n    Eigen::VectorXd _grad(num_param);\n\n    _y = Eigen::Map<Eigen::VectorXd>(y, num_output, 1);\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n        for (size_t idx2 = 0; idx2 < igp_num_param; idx2++)\n        {\n            for (size_t idx3 = 0; idx3 < dim; idx3++)\n            {\n                _dx[idx1][idx2](idx3) = dx[idx1 * igp_num_param * dim + idx2 * dim + idx3];\n            }\n        }\n    }\n\n    double loss = gp->negLogLikelihood(_x, _y, _dx, _grad);\n\n    for (size_t idx = 0; idx < num_param; idx++)\n    {\n        grad[idx] = _grad(idx);\n    }\n\n    return loss;\n\n} // double gp52_lik1(GP52* gp, double* x, double* y, double* dx, Eigen::VectorXd &grad)\n\n\nLIBRARY_API double gp52_lik2(GP52* gp, double* x, double* y)\n{\n    size_t num_output = gp->getNumOutput();\n    size_t num_latent = gp->getNumLatent();\n    size_t num_param = gp->getNumParam();\n    size_t igp_num_param = gp->getNumIGPParam();\n    size_t dim = gp->getIGPDim();\n\n    std::vector<Eigen::VectorXd> _x(num_latent, Eigen::VectorXd(dim).setZero());\n    Eigen::VectorXd _y(num_output);\n\n    _y = Eigen::Map<Eigen::VectorXd>(y, num_output, 1);\n    for (size_t idx1 = 0; idx1 < num_latent; idx1++)\n    {\n        for (size_t idx2 = 0; idx2 < dim; idx2++)\n        {\n            _x[idx1](idx2) = x[idx1 * dim + idx2];\n        }\n    }\n\n    double loss = gp->negLogLikelihood(_x, _y);\n\n    return loss;\n\n} // double gp52_lik2(GP52* gp, double* x, double* y)\n\n\nLIBRARY_API void gp52_get_params(GP52* gp, double* params)\n{\n    size_t num_param = gp->getNumParam();\n    Eigen::VectorXd _params = gp->getParams();\n    for (size_t idx = 0; idx < num_param; idx++)\n    {\n        params[idx] = _params(idx);\n    }\n} // void gp52_get_params(GP52* gp, double* params)\n\n\nLIBRARY_API size_t gp52_igp_dim(GP52* gp)\n{\n    return gp->getIGPDim();\n}\n\n\nLIBRARY_API size_t gp52_num_param(GP52* gp)\n{\n    return gp->getNumParam();\n}\n\n\nLIBRARY_API size_t gp52_num_igp_param(GP52* gp)\n{\n    return gp->getNumIGPParam();\n}\n\n\n\n} // extern \"C\"", "meta": {"hexsha": "e3fc8da66763e4bc4a3af5e0e3795914248a677f", "size": 19097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moihgp/src/wrapper.cpp", "max_stars_repo_name": "MLCS-Yonsei/MultiOutputIHGP", "max_stars_repo_head_hexsha": "3767325f57c5cd34655013fd9c7a0d87e97fc74f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moihgp/src/wrapper.cpp", "max_issues_repo_name": "MLCS-Yonsei/MultiOutputIHGP", "max_issues_repo_head_hexsha": "3767325f57c5cd34655013fd9c7a0d87e97fc74f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moihgp/src/wrapper.cpp", "max_forks_repo_name": "MLCS-Yonsei/MultiOutputIHGP", "max_forks_repo_head_hexsha": "3767325f57c5cd34655013fd9c7a0d87e97fc74f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-10T16:44:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T16:44:42.000Z", "avg_line_length": 30.4092356688, "max_line_length": 142, "alphanum_fraction": 0.5933392679, "num_tokens": 6171, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.20441217641392442}}
{"text": "#include \"FWCore/Utilities/interface/EDMException.h\"\n#include \"PhysicsTools/Utilities/interface/Parameter.h\"\n#include \"PhysicsTools/Utilities/interface/Gaussian.h\"\n#include \"PhysicsTools/Utilities/interface/Numerical.h\"\n#include \"PhysicsTools/Utilities/interface/Exponential.h\"\n#include \"PhysicsTools/Utilities/interface/Polynomial.h\"\n#include \"PhysicsTools/Utilities/interface/Constant.h\"\n#include \"PhysicsTools/Utilities/interface/Operations.h\"\n#include \"PhysicsTools/Utilities/interface/MultiHistoChiSquare.h\"\n#include \"PhysicsTools/Utilities/interface/HistoChiSquare.h\"\n#include \"PhysicsTools/Utilities/interface/HistoPoissonLikelihoodRatio.h\"\n#include \"PhysicsTools/Utilities/interface/RootMinuit.h\"\n#include \"PhysicsTools/Utilities/interface/RootMinuitCommands.h\"\n#include \"PhysicsTools/Utilities/interface/FunctClone.h\"\n#include \"PhysicsTools/Utilities/interface/rootPlot.h\"\n#include \"PhysicsTools/Utilities/interface/Expression.h\"\n#include \"PhysicsTools/Utilities/interface/HistoPdf.h\"\n#include \"FWCore/FWLite/interface/FWLiteEnabler.h\"\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n#include \"TH1.h\"\n#include \"TFile.h\"\n#include <fstream>\n#include <iostream>\n#include <algorithm> \n#include <exception>\n#include <iterator>\n#include <string>\n#include <vector>\nusing namespace std;\n\n// A helper function to simplify the main part.\ntemplate<class T>\nostream& operator<<(ostream& os, const vector<T>& v) {\n  copy(v.begin(), v.end(), ostream_iterator<T>(cout, \" \")); \n  return os;\n}\n\n// A function that get histogram and sets contents to 0 \n// if entries are too small\nTH1 * getHisto(TFile * file, const char * name, unsigned int rebin) {\n  TObject * h = file->Get(name);\n  if(h == 0)\n    throw edm::Exception(edm::errors::Configuration) \n      << \"Can't find object \" << name << \"\\n\";\n  TH1 * histo = dynamic_cast<TH1*>(h);\n  if(histo == 0)\n    throw edm::Exception(edm::errors::Configuration) \n      << \"Object \" << name << \" is of type \" << h->ClassName() << \", not TH1\\n\";\n  histo->Rebin(rebin);  \n  for(int i = 1; i <= histo->GetNbinsX(); ++i) {\n    if(histo->GetBinContent(i) < 0.1) {\n      histo->SetBinContent(i, 0.0);\n      histo->SetBinError(i, 0.0);\n    }\n  }\n  return histo;\n}\n\nstruct sig_tag;\nstruct bkg_tag;\n\ntypedef funct::FunctExpression Expr;\ntypedef fit::HistoChiSquare<funct::FunctExpression> ExprChi2;\ntypedef fit::HistoPoissonLikelihoodRatio<funct::FunctExpression> ExprPLR;\n\ndouble fMin, fMax;\n unsigned int rebinMuMuNoIso ,rebinMuMu =1 , rebinMuMu1HLT , rebinMuMu2HLT , rebinMuTk , rebinMuSa;\n // assume that the bin size is 1 GeV!!! \nstring ext, region;\nbool nonIsoTemplateFromMC;\n\ntemplate<typename T>\nstruct PlotPrefix { };\n\ntemplate<>\nstruct PlotPrefix<ExprChi2> {\n  static string str() { return \"chi2\"; }\n};\n \ntemplate<>\nstruct PlotPrefix<ExprPLR> {\n  static string str() { return \"plr\"; }\n};\n \ntemplate<typename T>\nint main_t(const vector<string> & v_file){\n  typedef fit::MultiHistoChiSquare<T, T, T, T, T> ChiSquared;\n  fit::RootMinuitCommands<ChiSquared> commands(\"zChi2Fit.txt\");\n  \n  cout << \"minuit command file completed\" << endl;\n \n  funct::Constant rebinMuMuNoIsoConst(rebinMuMuNoIso), rebinMuMuConst(rebinMuMu), \n    rebinMuMu1HLTConst(rebinMuMu1HLT), rebinMuMu2HLTConst(rebinMuMu2HLT), \n    rebinMuTkConst(rebinMuTk), rebinMuSaConst(rebinMuSa);\n  \n  for(vector<string>::const_iterator it = v_file.begin(); it != v_file.end(); ++it) {\n    TFile * root_file = new TFile(it->c_str(), \"read\");\n    \n    // default when region==all\n    //    TH1 * histoZMuMuNoIso = getHisto(root_file, \"nonIsolatedZToMuMuPlots/zMass\",rebinMuMuNoIso);\n    TH1 * histoZMuMuNoIso = getHisto(root_file, \"oneNonIsolatedZToMuMuPlots/zMass\",rebinMuMuNoIso);\n    TH1 * histoZMuMu = getHisto(root_file, \"goodZToMuMuPlots/zMass\",rebinMuMu);\n    TH1 * histoZMuMu1HLT = getHisto(root_file, \"goodZToMuMu1HLTPlots/zMass\", rebinMuMu1HLT);\n    TH1 * histoZMuMu2HLT = getHisto(root_file, \"goodZToMuMu2HLTPlots/zMass\", rebinMuMu2HLT);\n    TH1 * histoZMuTk = getHisto(root_file, \"goodZToMuMuOneTrackPlots/zMass\", rebinMuTk);\n    TH1 * histoZMuSa = getHisto(root_file, \"goodZToMuMuOneStandAloneMuonPlots/zMass\", rebinMuSa);\n    TH1 * histoZMuSaFromMuMu = getHisto(root_file, \"zmumuSaMassHistogram/zMass\", rebinMuSa);\n   \n    TH1 * histoZMuMuNoIsoTemplateFromMC= histoZMuMu;\n    if (nonIsoTemplateFromMC) {\n      //      histoZMuMuNoIsoTemplateFromMC = getHisto(root_file, \"nonIsolatedZToMuMuPlotsMC/zMass\",rebinMuMu);\n      histoZMuMuNoIsoTemplateFromMC = getHisto(root_file, \"oneNonIsolatedZToMuMuPlotsMC/zMass\",rebinMuMu);\n  }    \n    if (region==\"barrel\"){\n      histoZMuMuNoIso = getHisto(root_file, \"nonIsolatedZToMuMuPlotsBarrel/zMass\",rebinMuMuNoIso);\n      histoZMuMu = getHisto(root_file, \"goodZToMuMuPlotsBarrel/zMass\",rebinMuMu);\n      histoZMuMu1HLT = getHisto(root_file, \"goodZToMuMu1HLTPlotsBarrel/zMass\", rebinMuMu1HLT);\n      histoZMuMu2HLT = getHisto(root_file, \"goodZToMuMu2HLTPlotsBarrel/zMass\", rebinMuMu2HLT);\n      histoZMuTk = getHisto(root_file, \"goodZToMuMuOneTrackPlotsBarrel/zMass\", rebinMuTk);\n      histoZMuSa = getHisto(root_file, \"goodZToMuMuOneStandAloneMuonPlotsBarrel/zMass\", rebinMuSa);\n      histoZMuSaFromMuMu = getHisto(root_file, \"zmumuSaMassHistogramBarrel/zMass\", rebinMuSa);\n    }\n    \n    if (region==\"endcap\"){\n      histoZMuMuNoIso = getHisto(root_file, \"nonIsolatedZToMuMuPlotsEndCap/zMass\",rebinMuMuNoIso);\n      histoZMuMu = getHisto(root_file, \"goodZToMuMuPlotsEndCap/zMass\",rebinMuMu);\n      histoZMuMu1HLT = getHisto(root_file, \"goodZToMuMu1HLTPlotsEndCap/zMass\", rebinMuMu1HLT);\n      histoZMuMu2HLT = getHisto(root_file, \"goodZToMuMu2HLTPlotsEndCap/zMass\", rebinMuMu2HLT);\n      histoZMuTk = getHisto(root_file, \"goodZToMuMuOneTrackPlotsEndCap/zMass\", rebinMuTk);\n      histoZMuSa = getHisto(root_file, \"goodZToMuMuOneStandAloneMuonPlotsEndCap/zMass\", rebinMuSa);\n      histoZMuSaFromMuMu = getHisto(root_file, \"zmumuSaMassHistogramEndCap/zMass\", rebinMuSa);\n    }\n    \n    if (region==\"barrend\"){\n      histoZMuMuNoIso = getHisto(root_file, \"nonIsolatedZToMuMuPlotsBarrEnd/zMass\",rebinMuMuNoIso);\n      histoZMuMu = getHisto(root_file, \"goodZToMuMuPlotsBarrEnd/zMass\",rebinMuMu);\n      histoZMuMu1HLT = getHisto(root_file, \"goodZToMuMu1HLTPlotsBarrEnd/zMass\", rebinMuMu1HLT);\n      histoZMuMu2HLT = getHisto(root_file, \"goodZToMuMu2HLTPlotsBarrEnd/zMass\", rebinMuMu2HLT);\n      histoZMuTk = getHisto(root_file, \"goodZToMuMuOneTrackPlotsBarrEnd/zMass\", rebinMuTk);\n      histoZMuSa = getHisto(root_file, \"goodZToMuMuOneStandAloneMuonPlotsBarrEnd/zMass\", rebinMuSa);\n      histoZMuSaFromMuMu = getHisto(root_file, \"zmumuSaMassHistogramBarrEnd/zMass\", rebinMuSa);\n    }\n    \n    if (region!=\"endcap\" && region!=\"barrel\" && region!=\"barrend\" && region!=\"all\"  ){\n      cout<< \"not a valid region selected\"<< endl;\n      cout << \"possible choises are: all, barrel, endcap, barrend \" << endl;\n      return 0;\n    }\n    \n    cout << \">>> histogram loaded\\n\";\n    string f_string = *it + \"_\" + PlotPrefix<T>::str() + \"_\";\n    replace(f_string.begin(), f_string.end(), '.', '_');\n    replace(f_string.begin(), f_string.end(), '/', '_');\n    string plot_string = f_string + \".\" + ext;\n    cout << \">>> Input files loaded\\n\";\n    \n    const char * kYieldZMuMu = \"YieldZMuMu\";\n    const char * kEfficiencyTk = \"EfficiencyTk\";\n    const char * kEfficiencySa = \"EfficiencySa\";\n    const char * kEfficiencyIso = \"EfficiencyIso\";\n    const char * kEfficiencyHLT = \"EfficiencyHLT\"; \n    const char * kYieldBkgZMuTk = \"YieldBkgZMuTk\"; \n    const char * kYieldBkgZMuSa = \"YieldBkgZMuSa\"; \n    const char * kYieldBkgZMuMuNotIso = \"YieldBkgZMuMuNotIso\";\n    const char * kAlpha = \"Alpha\";\n    const char * kBeta = \"Beta\";\n    const char * kLambda = \"Lambda\";\n    const char * kA0 = \"A0\"; \n    const char * kA1 = \"A1\"; \n    const char * kA2 = \"A2\"; \n    const char * kB0 = \"B0\"; \n    const char * kB1 = \"B1\"; \n    const char * kB2 = \"B2\"; \n    const char * kC0 = \"C0\"; \n    const char * kC1 = \"C1\"; \n    const char * kC2 = \"C2\"; \n    \n    funct::Parameter yieldZMuMu(kYieldZMuMu, commands.par(kYieldZMuMu));\n    funct::Parameter effTk(kEfficiencyTk, commands.par(kEfficiencyTk)); \n    funct::Parameter effSa(kEfficiencySa, commands.par(kEfficiencySa)); \n    funct::Parameter effIso(kEfficiencyIso, commands.par(kEfficiencyIso)); \n    funct::Parameter effHLT(kEfficiencyHLT, commands.par(kEfficiencyHLT)); \n    funct::Parameter yieldBkgZMuTk(kYieldBkgZMuTk, commands.par(kYieldBkgZMuTk));\n    funct::Parameter yieldBkgZMuSa(kYieldBkgZMuSa, commands.par(kYieldBkgZMuSa));\n    funct::Parameter yieldBkgZMuMuNotIso(kYieldBkgZMuMuNotIso, commands.par(kYieldBkgZMuMuNotIso));\n    funct::Parameter alpha(kAlpha, commands.par(kAlpha));\n    funct::Parameter beta(kBeta, commands.par(kBeta));\n    funct::Parameter lambda(kLambda, commands.par(kLambda));\n    funct::Parameter a0(kA0, commands.par(kA0));\n    funct::Parameter a1(kA1, commands.par(kA1));\n    funct::Parameter a2(kA2, commands.par(kA2));\n    funct::Parameter b0(kB0, commands.par(kB0));\n    funct::Parameter b1(kB1, commands.par(kB1));\n    funct::Parameter b2(kB2, commands.par(kB2));\n    funct::Parameter c0(kC0, commands.par(kC0));\n    funct::Parameter c1(kC1, commands.par(kC1));\n    funct::Parameter c2(kC2, commands.par(kC2));\n    funct::Constant cFMin(fMin), cFMax(fMax);\n    \n    // count ZMuMu Yield\n    double nZMuMu = 0, nZMuMu1HLT = 0, nZMuMu2HLT = 0;\n    {\n      unsigned int nBins = histoZMuMu->GetNbinsX();\n      double xMin = histoZMuMu->GetXaxis()->GetXmin();\n      double xMax = histoZMuMu->GetXaxis()->GetXmax();\n      double deltaX =(xMax - xMin) / nBins;\n      for(unsigned int i = 0; i < nBins; ++i) { \n\tdouble x = xMin + (i +.5) * deltaX;\n\tif(x > fMin && x < fMax){\n\t  nZMuMu += histoZMuMu->GetBinContent(i+1);\n\t  nZMuMu1HLT += histoZMuMu1HLT->GetBinContent(i+1);\n\t  nZMuMu2HLT += histoZMuMu2HLT->GetBinContent(i+1);\n\t}\n      }\n    }\n    // aggiungi 1HLT 2HLT\n    cout << \">>> count of ZMuMu yield in the range [\" << fMin << \", \" << fMax << \"]: \" << nZMuMu << endl;\n    cout << \">>> count of ZMuMu (1HLT) yield in the range [\" << fMin << \", \" << fMax << \"]: \"  << nZMuMu1HLT << endl;\n    cout << \">>> count of ZMuMu (2HLT) yield in the range [\" << fMin << \", \" << fMax << \"]: \"  << nZMuMu2HLT << endl;\n    funct::RootHistoPdf zPdfMuMu(*histoZMuMu, fMin, fMax);\n      //assign ZMuMu as pdf\n    funct::RootHistoPdf zPdfMuMuNonIso = zPdfMuMu;\n    if (nonIsoTemplateFromMC) {\n      funct::RootHistoPdf zPdfMuMuNoIsoFromMC(*histoZMuMuNoIsoTemplateFromMC, fMin, fMax);\n      zPdfMuMuNonIso = zPdfMuMuNoIsoFromMC;\n    }    \n    \n    funct::RootHistoPdf zPdfMuTk = zPdfMuMu;\n    funct::RootHistoPdf zPdfMuMu1HLT = zPdfMuMu;\n    funct::RootHistoPdf zPdfMuMu2HLT = zPdfMuMu;\n    funct::RootHistoPdf zPdfMuSa(*histoZMuSaFromMuMu, fMin, fMax);\n    zPdfMuMuNonIso.rebin(rebinMuMuNoIso/rebinMuMu);\n    zPdfMuTk.rebin(rebinMuTk/rebinMuMu);\n    zPdfMuMu1HLT.rebin(rebinMuMu1HLT/rebinMuMu);\n    zPdfMuMu2HLT.rebin(rebinMuMu2HLT/rebinMuMu);\n    \n    funct::Numerical<2> _2;\n    funct::Numerical<1> _1;\n    \n    //Efficiency term\n    Expr zMuMuEff1HLTTerm = _2 * (effTk ^ _2) *  (effSa ^ _2) * (effIso ^ _2) * effHLT * (_1 - effHLT); \n    Expr zMuMuEff2HLTTerm = (effTk ^ _2) *  (effSa ^ _2) * (effIso ^ _2) * (effHLT ^ _2) ; \n    //    Expr zMuMuNoIsoEffTerm = (effTk ^ _2) * (effSa ^ _2) * (_1 - (effIso ^ _2)) * (_1 - ((_1 - effHLT)^_2));\n    // change to both hlt and one not iso\n    Expr zMuMuNoIsoEffTerm = _2 * (effTk ^ _2) * (effSa ^ _2) * effIso * (_1 - effIso) * (effHLT^_2);\n    Expr zMuTkEffTerm = _2 * (effTk ^ _2) * effSa * (_1 - effSa) * (effIso ^ _2) * effHLT;\n    Expr zMuSaEffTerm = _2 * (effSa ^ _2) * effTk * (_1 - effTk) * (effIso ^ _2) * effHLT;\n    \n    Expr zMuMu1HLT = rebinMuMu1HLTConst * zMuMuEff1HLTTerm * yieldZMuMu;\n    Expr zMuMu2HLT = rebinMuMu2HLTConst * zMuMuEff2HLTTerm * yieldZMuMu;\n    \n    Expr zMuTkBkg = yieldBkgZMuTk * funct::Exponential(lambda)* funct::Polynomial<2>(a0, a1, a2);\n    Expr zMuTkBkgScaled = rebinMuTkConst * zMuTkBkg;\n    Expr zMuTk = rebinMuTkConst * (zMuTkEffTerm * yieldZMuMu * zPdfMuTk + zMuTkBkg);\n    \n    Expr zMuMuNoIsoBkg = yieldBkgZMuMuNotIso * funct::Exponential(alpha)* funct::Polynomial<2>(b0, b1, b2);\n    Expr zMuMuNoIsoBkgScaled = rebinMuMuNoIsoConst * zMuMuNoIsoBkg;\n    Expr zMuMuNoIso = rebinMuMuNoIsoConst * (zMuMuNoIsoEffTerm * yieldZMuMu * zPdfMuMuNonIso + zMuMuNoIsoBkg);\n    \n\n    Expr zMuSaBkg = yieldBkgZMuSa * funct::Exponential(beta)* funct::Polynomial<2>(c0, c1, c2);\n    Expr zMuSaBkgScaled = rebinMuSaConst * zMuSaBkg;\n    Expr zMuSa = rebinMuSaConst * (zMuSaEffTerm * yieldZMuMu * zPdfMuSa  + zMuSaBkg );\n    \n    TH1D histoZCount1HLT(\"histoZCount1HLT\", \"\", 1, fMin, fMax);\n    histoZCount1HLT.Fill(100, nZMuMu1HLT);\n    TH1D histoZCount2HLT(\"histoZCount2HLT\", \"\", 1, fMin, fMax);\n    histoZCount2HLT.Fill(100, nZMuMu2HLT);\n    \n    ChiSquared chi2(zMuMu1HLT, & histoZCount1HLT,\n\t\t    zMuMu2HLT, & histoZCount2HLT,\n\t\t    zMuTk, histoZMuTk, \n\t\t    zMuSa, histoZMuSa, \n\t\t    zMuMuNoIso,histoZMuMuNoIso,\n\t\t    fMin, fMax);\n    cout << \"N. bins: \" << chi2.numberOfBins() << endl;\n    \n    fit::RootMinuit<ChiSquared> minuit(chi2, true);\n    commands.add(minuit, yieldZMuMu);\n    commands.add(minuit, effTk);\n    commands.add(minuit, effSa);\n    commands.add(minuit, effIso);\n    commands.add(minuit, effHLT);\n    commands.add(minuit, yieldBkgZMuTk);\n    commands.add(minuit, yieldBkgZMuSa);\n    commands.add(minuit, yieldBkgZMuMuNotIso);\n    commands.add(minuit, lambda);\n    commands.add(minuit, alpha);\n    commands.add(minuit, beta);\n    commands.add(minuit, a0);\n    commands.add(minuit, a1);\n    commands.add(minuit, a2);\n    commands.add(minuit, b0);\n    commands.add(minuit, b1);\n    commands.add(minuit, b2);\n    commands.add(minuit, c0);\n    commands.add(minuit, c1);\n    commands.add(minuit, c2);\n    commands.run(minuit);\n    const unsigned int nPar = 20;//WARNIG: this must be updated manually for now\n    ROOT::Math::SMatrix<double, nPar, nPar, ROOT::Math::MatRepSym<double, nPar> > err;\n    minuit.getErrorMatrix(err);\n    \n    std::cout << \"error matrix:\" << std::endl;\n    for(unsigned int i = 0; i < nPar; ++i) {\n      for(unsigned int j = 0; j < nPar; ++j) {\n\t  std::cout << err(i, j) << \"\\t\";\n      }\n      std::cout << std::endl;\n    } \n    minuit.printFitResults();\n    ofstream myfile;\n    myfile.open (\"fitResult.txt\", ios::out | ios::app);\n    myfile<<\"\\n\";\n    double Y =  minuit.getParameterError(\"YieldZMuMu\");\n    double dY = minuit.getParameterError(\"YieldZMuMu\", Y);\n    double tk_eff =  minuit.getParameterError(\"EfficiencyTk\");\n    double dtk_eff = minuit.getParameterError(\"EfficiencyTk\", tk_eff);\n    double sa_eff =  minuit.getParameterError(\"EfficiencySa\");\n    double dsa_eff = minuit.getParameterError(\"EfficiencySa\", sa_eff);\n    double iso_eff =  minuit.getParameterError(\"EfficiencyIso\");\n    double diso_eff = minuit.getParameterError(\"EfficiencyIso\", iso_eff);\n    double hlt_eff =  minuit.getParameterError(\"EfficiencyHLT\");\n    double dhlt_eff = minuit.getParameterError(\"EfficiencyHLT\",hlt_eff);\n    myfile<< Y <<\" \"<< dY <<\" \"<< tk_eff <<\" \"<< dtk_eff <<\" \"<< sa_eff << \" \" << dsa_eff << \" \" << iso_eff <<\" \" << diso_eff<< \" \" << hlt_eff << \" \" << dhlt_eff << \" \" <<chi2()/(chi2.numberOfBins()- minuit.numberOfFreeParameters());\n    \n    myfile.close();\n\n    //Plot\n    double s;\n    s = 0;\n    for(int i = 1; i <= histoZMuMuNoIso->GetNbinsX(); ++i)\n      s += histoZMuMuNoIso->GetBinContent(i);\n    histoZMuMuNoIso->SetEntries(s);\n    s = 0;\n    for(int i = 1; i <= histoZMuMu->GetNbinsX(); ++i)\n      s += histoZMuMu->GetBinContent(i);\n    histoZMuMu->SetEntries(s);\n    s = 0;\n    for(int i = 1; i <= histoZMuMu1HLT->GetNbinsX(); ++i)\n      s += histoZMuMu1HLT->GetBinContent(i);\n    histoZMuMu1HLT->SetEntries(s);\n    s = 0;\n    for(int i = 1; i <= histoZMuMu2HLT->GetNbinsX(); ++i)\n      s += histoZMuMu2HLT->GetBinContent(i);\n    histoZMuMu2HLT->SetEntries(s);\n    s = 0;\n    for(int i = 1; i <= histoZMuTk->GetNbinsX(); ++i)\n      s += histoZMuTk->GetBinContent(i);\n    histoZMuTk->SetEntries(s);\n    s = 0;\n    for(int i = 1; i <= histoZMuSa->GetNbinsX(); ++i)\n      s += histoZMuSa->GetBinContent(i);\n    histoZMuSa->SetEntries(s);\n    \n    string ZMuMu1HLTPlot = \"ZMuMu1HLTFit_\" + plot_string;\n    root::plot<Expr>(ZMuMu1HLTPlot.c_str(), *histoZMuMu1HLT, zMuMu1HLT, fMin, fMax, \n\t\t     effTk, effSa, effIso, effHLT, yieldZMuMu, \n\t\t     kOrange-2, 2, kSolid, 100, \n\t\t     \"Z -> #mu #mu mass\", \"#mu #mu invariant mass (GeV/c^{2})\", \n\t\t     \"Events\");\n    \n    string ZMuMu2HLTPlot = \"ZMuMu2HLTFit_\" + plot_string;\n    root::plot<Expr>(ZMuMu2HLTPlot.c_str(), *histoZMuMu2HLT, zMuMu2HLT, fMin, fMax, \n\t\t     effTk, effSa, effIso, effHLT, yieldZMuMu, \n\t\t     kOrange-2, 2, kSolid, 100, \n\t\t     \"Z -> #mu #mu mass\", \"#mu #mu invariant mass (GeV/c^{2})\", \n\t\t     \"Events\");\n    \n    \n    string ZMuMuNoIsoPlot = \"ZMuMuNoIsoFit_X_\" + plot_string;\n    root::plot<Expr>(ZMuMuNoIsoPlot.c_str(), *histoZMuMuNoIso, zMuMuNoIso, fMin, fMax, \n\t\t     effTk, effSa, effIso, effHLT, yieldZMuMu,\n\t\t     yieldBkgZMuMuNotIso, alpha, b0, b1, b2,\n\t\t     kWhite, 2, kSolid, 100, \n\t\t     \"Z -> #mu #mu Not Iso mass\", \"#mu #mu invariant mass (GeV/c^{2})\", \n\t\t     \"Events\");\t\n    ZMuMuNoIsoPlot = \"ZMuMuNoIsoFit_\" + plot_string;\n    TF1 funZMuMuNoIso = root::tf1_t<sig_tag, Expr>(\"ZMuMuNoIsoFunction\", zMuMuNoIso, fMin, fMax, \n\t\t\t\t\t      effTk, effSa, effIso, effHLT, yieldZMuMu, \n\t\t\t\t\t      yieldBkgZMuMuNotIso, alpha, b0, b1, b2);\n    funZMuMuNoIso.SetLineColor(kOrange+8);\n    funZMuMuNoIso.SetLineWidth(3);\n    //funZMuMuNoIso.SetLineStyle(kDashed);\n    \n    //funZMuMuNoIso.SetFillColor(kOrange-2);\n    //funZMuMuNoIso.SetFillStyle(3325);\n\n    funZMuMuNoIso.SetNpx(10000);\n    TF1 funZMuMuNoIsoBkg = root::tf1_t<bkg_tag, Expr>(\"ZMuMuNoIsoBack\", zMuMuNoIsoBkgScaled, fMin, fMax, \n\t\t\t\t\t\t yieldBkgZMuMuNotIso, alpha, b0, b1, b2);\n    funZMuMuNoIsoBkg.SetLineColor(kViolet+3);\n    funZMuMuNoIsoBkg.SetLineWidth(2);\n    funZMuMuNoIsoBkg.SetLineStyle(kSolid);\n    funZMuMuNoIsoBkg.SetFillColor(kViolet-5);\n    funZMuMuNoIsoBkg.SetFillStyle(3357);\n\n    funZMuMuNoIsoBkg.SetNpx(10000);\n    histoZMuMuNoIso->SetTitle(\"Z -> #mu #mu Not Iso mass\");\n    histoZMuMuNoIso->SetXTitle(\"#mu +  #mu invariant mass (GeV/c^{2})\");\n    histoZMuMuNoIso->SetYTitle(\"Events\");\n    TCanvas *canvas = new TCanvas(\"canvas\");\n    histoZMuMuNoIso->Draw(\"e\");\n    funZMuMuNoIsoBkg.Draw(\"same\");\n    funZMuMuNoIso.Draw(\"same\");\n    canvas->SaveAs(ZMuMuNoIsoPlot.c_str());\n    canvas->SetLogy();\n    string logZMuMuNoIsoPlot = \"log_\" + ZMuMuNoIsoPlot;\n    canvas->SaveAs(logZMuMuNoIsoPlot.c_str());\n    \n    double IntSigMMNotIso = ((double) rebinMuMu/  (double) rebinMuMuNoIso) * funZMuMuNoIso.Integral(fMin, fMax);\n    double IntSigMMNotIsoBkg = ((double) rebinMuMu/  (double) rebinMuMuNoIso) * funZMuMuNoIsoBkg.Integral(fMin, fMax);\n    cout << \"*********  ZMuMuNoIsoPlot signal yield from the fit ==> \" <<  IntSigMMNotIso << endl;\n    cout << \"*********  ZMuMuNoIsoPlot background yield from the fit ==> \" << IntSigMMNotIsoBkg << endl;\n\n\n\n    string ZMuTkPlot = \"ZMuTkFit_X_\" + plot_string;\n    root::plot<Expr>(ZMuTkPlot.c_str(), *histoZMuTk, zMuTk, fMin, fMax,\n\t\t     effTk, effSa, effIso, effHLT, yieldZMuMu,\n\t\t     yieldBkgZMuTk, lambda, a0, a1, a2,\n\t\t     kOrange+3, 2, kSolid, 100,\n\t\t     \"Z -> #mu + (unmatched) track mass\", \"#mu #mu invariant mass (GeV/c^{2})\",\n\t\t     \"Events\");\n    ZMuTkPlot = \"ZMuTkFit_\" + plot_string;\n    TF1 funZMuTk = root::tf1_t<sig_tag, Expr>(\"ZMuTkFunction\", zMuTk, fMin, fMax, \n\t\t\t\t\t      effTk, effSa, effIso, effHLT, yieldZMuMu, \n\t\t\t\t\t      yieldBkgZMuTk, lambda, a0, a1, a2);\n    funZMuTk.SetLineColor(kOrange+8);\n    funZMuTk.SetLineWidth(3);\n    funZMuTk.SetLineStyle(kSolid);\n    //  funZMuTk.SetFillColor(kOrange-2);\n    //funZMuTk.SetFillStyle(3325);\n    funZMuTk.SetNpx(10000);\n    TF1 funZMuTkBkg = root::tf1_t<bkg_tag, Expr>(\"ZMuTkBack\", zMuTkBkgScaled, fMin, fMax, \n\t\t\t\t\t\t yieldBkgZMuTk, lambda, a0, a1, a2);\n    funZMuTkBkg.SetLineColor(kViolet+3);\n    funZMuTkBkg.SetLineWidth(2);\n    funZMuTkBkg.SetLineStyle(kSolid);\n    funZMuTkBkg.SetFillColor(kViolet-5);\n    funZMuTkBkg.SetFillStyle(3357);\n    funZMuTkBkg.SetNpx(10000);\n    histoZMuTk->SetTitle(\"Z -> #mu + (unmatched) track mass\");\n    histoZMuTk->SetXTitle(\"#mu + (unmatched) track invariant mass (GeV/c^{2})\");\n    histoZMuTk->SetYTitle(\"Events\");\n    TCanvas *canvas_ = new TCanvas(\"canvas_\");\n    histoZMuTk->Draw(\"e\");\n    funZMuTkBkg.Draw(\"same\");\n    funZMuTk.Draw(\"same\");\n    canvas_->SaveAs(ZMuTkPlot.c_str());\n    canvas_->SetLogy();\n    string logZMuTkPlot = \"log_\" + ZMuTkPlot;\n    canvas_->SaveAs(logZMuTkPlot.c_str());\n\n\n    double IntSigMT = ((double) rebinMuMu/  (double) rebinMuTk) * funZMuTk.Integral(fMin, fMax);\n    double IntSigMTBkg = ((double) rebinMuMu/  (double) rebinMuTk) * funZMuTkBkg.Integral(fMin, fMax);\n    cout << \"*********  ZMuMuTkPlot signal yield from the fit ==> \" <<  IntSigMT << endl;\n    cout << \"*********  ZMuMuTkPlot background yield from the fit ==> \" << IntSigMTBkg << endl;\n\n\n\n    string ZMuSaPlot = \"ZMuSaFit_X_\" + plot_string;\n    root::plot<Expr>(ZMuSaPlot.c_str(), *histoZMuSa, zMuSa, fMin, fMax, \n\t\t     effSa, effTk, effIso, yieldZMuMu, \n\t\t     yieldBkgZMuSa, beta, c0, c1, c2 ,\n\t\t     kOrange+3, 2, kSolid, 100, \n\t\t     \"Z -> #mu + (unmatched) standalone mass\", \n\t\t     \"#mu + (unmatched) standalone invariant mass (GeV/c^{2})\", \n\t\t     \"Events\");\n\n\n\n    ZMuSaPlot = \"ZMuSaFit_\" + plot_string;\n    TF1 funZMuSa = root::tf1_t<sig_tag, Expr>(\"ZMuSaFunction\", zMuSa, fMin, fMax, \n\t\t\t\t\t      effTk, effSa, effIso, effHLT, yieldZMuMu, \n\t\t\t\t\t      yieldBkgZMuSa, beta, c0, c1, c2);\n    funZMuSa.SetLineColor(kOrange+8);\n    funZMuSa.SetLineWidth(3);\n    funZMuSa.SetLineStyle(kSolid);\n    // funZMuSa.SetFillColor(kOrange-2);\n    // funZMuSa.SetFillStyle(3325);\n    funZMuSa.SetNpx(10000);\n    TF1 funZMuSaBkg = root::tf1_t<bkg_tag, Expr>(\"ZMuSaBack\", zMuSaBkgScaled, fMin, fMax, \n\t\t\t\t\t\t yieldBkgZMuSa, beta, c0, c1, c2);\n    funZMuSaBkg.SetLineColor(kViolet+3);\n    funZMuSaBkg.SetLineWidth(2);\n    funZMuSaBkg.SetLineStyle(kSolid);\n    funZMuSaBkg.SetFillColor(kViolet-5);\n    funZMuSaBkg.SetFillStyle(3357);\n    funZMuSaBkg.SetNpx(10000);\n    histoZMuSa->SetTitle(\"Z -> #mu + (unmatched) standalone mass\");\n    histoZMuSa->SetXTitle(\"#mu + (unmatched) standalone invariant mass (GeV/c^{2})\");\n    histoZMuSa->SetYTitle(\"Events\");\n    TCanvas *canvas__ = new TCanvas(\"canvas__\");\n    histoZMuSa->Draw(\"e\");\n    funZMuSaBkg.Draw(\"same\");\n    funZMuSa.Draw(\"same\");\n    canvas__->SaveAs(ZMuSaPlot.c_str());\n    canvas__->SetLogy();\n    string logZMuSaPlot = \"log_\" + ZMuSaPlot;\n    canvas__->SaveAs(logZMuSaPlot.c_str());\n\n    double IntSigMS = ((double) rebinMuMu/  (double) rebinMuSa) * funZMuSa.Integral(fMin, fMax);\n    double IntSigMSBkg = ((double) rebinMuMu/  (double) rebinMuSa) * funZMuSaBkg.Integral(fMin, fMax);\n    cout << \"*********  ZMuMuSaPlot signal yield from the fit ==> \" <<  IntSigMS << endl;\n    cout << \"*********  ZMuMuSaPlot background yield from the fit ==> \" << IntSigMSBkg << endl;\n\n\n  }\n  return 0;\n}\n\n#include <boost/program_options.hpp>\nusing namespace boost;\nnamespace po = boost::program_options;\n\nint main(int ac, char *av[]) {\n  po::options_description desc(\"Allowed options\");\n  desc.add_options()\n    (\"help,h\", \"produce help message\")\n    (\"input-file,i\", po::value<vector<string> >(), \"input file\")\n    (\"min,m\", po::value<double>(&fMin)->default_value(60), \"minimum value for fit range\")\n    (\"max,M\", po::value<double>(&fMax)->default_value(120), \"maximum value for fit range\")\n    (\"rebins,R\", po::value<vector<unsigned int> >(), \"rebins values: rebinMuMu2HLT , rebinMuMu1HLT , rebinMuMuNoIso , rebinMuSa, rebinMuTk\")\n    (\"chi2,c\", \"perform chi-squared fit\")\n    (\"plr,p\", \"perform Poisson likelihood-ratio fit\")\n    (\"nonIsoTemplateFromMC,I\", po::value<bool>(&nonIsoTemplateFromMC)->default_value(false) , \"take the template for nonIso sample from MC\")\n    (\"plot-format,f\", po::value<string>(&ext)->default_value(\"eps\"), \"output plot format\")\n    (\"detectorRegion,r\",po::value<string> (&region)->default_value(\"all\"), \"detector region in which muons are detected\" );   \n  po::positional_options_description p;\n  p.add(\"input-file\", -1);\n  p.add(\"rebins\", -1);\n\n  \n  po::variables_map vm;\n  po::store(po::command_line_parser(ac, av).\n\t    options(desc).positional(p).run(), vm);\n  po::notify(vm);\n  \n  if (vm.count(\"help\")) {\n    cout << \"Usage: options_description [options]\\n\";\n    cout << desc;\n    return 0;\n  }\n  \n  if (!vm.count(\"input-file\")) {\n    return 1;\n  }\n  cout << \"Input files are: \" \n       << vm[\"input-file\"].as< vector<string> >() << \"\\n\";\n  vector<string> v_file = vm[\"input-file\"].as< vector<string> >();\n\n\n  if (vm.count(\"rebins\") ) {\n    vector<unsigned int> v_rebin = vm[\"rebins\"].as< vector<unsigned int> >();\n    if (v_rebin.size()!=5){\n      cerr << \" please provide 5 numbers in the given order:  rebinMuMu2HLT , rebinMuMu1HLT , rebinMuMuNoIso, rebinMuSa, rebinMuTk \\n\";\n      return 1;\n    }\n rebinMuMuNoIso = v_rebin[2], rebinMuMu1HLT = v_rebin[1], rebinMuMu2HLT = v_rebin[0], rebinMuTk = v_rebin[4], rebinMuSa = v_rebin[3];\n  }\n\n\n\n\n  bool chi2Fit = vm.count(\"chi2\"), plrFit = vm.count(\"plr\");\n  \n  if(!(chi2Fit||plrFit))\n    cerr << \"Warning: no fit performed. Please, specify either -c or -p options or both\" << endl;\n \n\n  gROOT->SetStyle(\"Plain\");\n\n  int ret = 0;\n  try {\n    if(plrFit) {\n      std::cout << \"==================================== \" << std::endl;\n      std::cout << \"=== Poisson Likelihood Ratio fit === \" << std::endl;\n      std::cout << \"==================================== \" << std::endl;\n      int ret2 = main_t<ExprPLR>(v_file);\n      if(ret2 != 0) ret = 1;\n    }\n    if(chi2Fit) {\n      std::cout << \"================= \" << std::endl;\n      std::cout << \"=== Chi-2 fit === \" << std::endl;\n      std::cout << \"================= \" << std::endl;\n      int ret1 = main_t<ExprChi2>(v_file);\n      if(ret1 != 0) ret = 1;\n    }\n  }\n  catch(std::exception& e) {\n    cerr << \"error: \" << e.what() << \"\\n\";\n    return 1;\n  }\n  catch(...) {\n    cerr << \"Exception of unknown type!\\n\";\n  }\n  return ret;\n}\n\n", "meta": {"hexsha": "a096fea6aacd16010e15649e79324f8a3f1e247a", "size": 26125, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/zChi2Fit.cpp", "max_stars_repo_name": "nistefan/cmssw", "max_stars_repo_head_hexsha": "ea13af97f7f2117a4f590a5e654e06ecd9825a5b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-24T19:10:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-19T11:45:32.000Z", "max_issues_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/zChi2Fit.cpp", "max_issues_repo_name": "nistefan/cmssw", "max_issues_repo_head_hexsha": "ea13af97f7f2117a4f590a5e654e06ecd9825a5b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-08-23T13:40:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-05T21:16:03.000Z", "max_forks_repo_path": "ElectroWeakAnalysis/ZMuMu/bin/zChi2Fit.cpp", "max_forks_repo_name": "nistefan/cmssw", "max_forks_repo_head_hexsha": "ea13af97f7f2117a4f590a5e654e06ecd9825a5b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-08-21T16:37:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-09T13:33:17.000Z", "avg_line_length": 43.3250414594, "max_line_length": 233, "alphanum_fraction": 0.6650334928, "num_tokens": 8788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786861878392, "lm_q2_score": 0.30074557267388247, "lm_q1q2_score": 0.2042599829254568}}
{"text": "#ifndef PRTCS_H\n#define PRTCS_H\n\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wunused-variable\"\n#pragma clang diagnostic ignored \"-Wunused-parameter\"\n#pragma clang diagnostic ignored \"-Wmissing-braces\"\n#include \"dccrg.hpp\"\n#include \"dccrg_cartesian_geometry.hpp\"\n#pragma clang diagnostic pop\n\n#include \"cell.hpp\"\n#include \"parameters.hpp\"\n#include <Eigen/Dense>\n\n\nusing namespace std;\nusing namespace dccrg;\nusing namespace Eigen;\n\ntypedef Array<double, 3, 2> Matrixd32;\n\n\n\nclass EB_Cube\n{\npublic:\n\n    // fixed size neighborhood array for the field tensors\n    std::array<Matrixd32, 27> fields;\n\n    // take grid and cell as pointers\n    // build adjacent neighborhood and related functions around them\n\tEB_Cube(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid, uint64_t cell);\n\n\n    Matrixd32& operator [](const std::size_t i){return this->fields[i];}\n    const Matrixd32& operator [](const std::size_t i) const {return this->fields[i];}\n\n    Matrixd32& F(int i, int j, int k)\n    { \n        int ijk = (i+1) + (j+1)*3 + (k+1)*3*3;\n        return this->fields[ijk];\n    }\n    \n    double exY(int i, int j, int k)\n    {\n        return this->F(i,j,k)(0,0);\n    }\n\n    double eyY(int i, int j, int k)\n    {\n        return this->F(i,j,k)(1,0);\n    }\n\n    double ezY(int i, int j, int k)\n    {\n        return this->F(i,j,k)(2,0);\n    }\n\n    double bxY(int i, int j, int k)\n    {\n        return this->F(i,j,k)(0,1);\n    }\n\n    double byY(int i, int j, int k)\n    {\n        return this->F(i,j,k)(1,1);\n    }\n\n    double bzY(int i, int j, int k)\n    {\n        return this->F(i,j,k)(2,1);\n    }\n\n\n    /* basic trilinear interpolation (i.e. 3x linear interpolations) with the cube class\n        x,y,z weights within the cells (0 means at i/j/k and 1 means i+1/j+1/k+1\n    \n        TODO: optimize this; now we call f000... elements each time whereas one time is enough\n          only xd, yd, zd change\n        TODO: staggered version is slooooow! And ugly.\n    */\n\n    /* XXX From TRISTAN-MP\n        l=i+iy*(j-1)+iz*(k-1)\n\n        f=ex(l,1,1)+ex(l-ix,1,1)+dx*(ex(l+ix,1,1)-ex(l-ix,1,1))\n\n\t\tf=f+dy*(ex(l+iy,1,1)+ex(l-ix+iy,1,1)+dx*(ex(l+ix+iy,1,1)-ex(l-ix &\n\t\t+iy,1,1))-f)\n\n\t\tg=ex(l+iz,1,1)+ex(l-ix+iz,1,1)+dx*(ex(l+ix+iz,1,1)-ex(l-ix+iz,1 &\n\t\t,1))\n\n\t\tg=g+dy* &\n\t\t(ex(l+iy+iz,1,1)+ex(l-ix+iy+iz,1,1)+dx*(ex(l+ix+iy+iz,1,1) &\n\t\t-ex(l-ix+iy+iz,1,1))-g)\n\t\t\n\t\tex0=(f+dz*(g-f))*(.25*qm)\n\n        -------------------------------------------------- \n        f=bx(l-iy,1,1)+bx(l-iy-iz,1,1)+dz*(bx(l-iy+iz,1,1)-bx(l-iy-iz,1 &\n\t\t,1))\n\t\tf=bx(l,1,1)+bx(l-iz,1,1)+dz*(bx(l+iz,1,1)-bx(l-iz,1,1))+f+dy &\n\t\t* (bx(l+iy,1,1)+bx(l+iy-iz,1,1)+dz*(bx(l+iy+iz,1,1)-bx(l+iy &\n\t\t-iz,1,1))-f)\n\t\tg=bx(l+ix-iy,1,1)+bx(l+ix-iy-iz,1,1)+dz*(bx(l+ix-iy+iz,1,1) &\n\t\t-bx(l+ix-iy-iz,1,1))\n\t\tg=bx(l+ix,1,1)+bx(l+ix-iz,1,1)+dz*(bx(l+ix+iz,1,1)-bx(l+ix-iz,1 &\n\t\t,1))+g+dy*(bx(l+ix+iy,1,1)+bx(l+ix+iy-iz,1,1)+dz*(bx(l+ix &\n\t\t+iy+iz,1,1)-bx(l+ix+iy-iz,1,1))-g)\n\t\t\n\t\tbx0=(f+dx*(g-f))*(.125*qm*cinv)\n    */\n\n    Matrixd32 trilinear_staggered( double xd, double yd, double zd);\n\n\n    Matrixd32 trilinear( double xd, double yd, double zd);\n\n};\n\n\nclass Particle_Mover\n{\npublic:\n\n    /*\n        Boris/Vay pusher to update particle velocities\n    */\n\tvoid update_velocities(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid);\n\n\n    /*\n        -------------------------------------------------------------------------------- \n        Particle propagator that pushes particles in space\n\n         We basically just compute x_n+1 = x_n + v_x,n * dt/gamma\n         and, hence, will advance the (relativistic) Newton-Lorentz \n         equation in time as experienced by the particle in her own frame\n\n        TODO:\n        Currently some non-necessary extra work is done because we move\n        also particles in ghost cells, i.e., the neighboring cells at process\n        boundary.\n\n    */\n\tvoid propagate(dccrg::Dccrg<Cell, dccrg::Cartesian_Geometry>& grid);\n\n\n};\n\n#endif\n", "meta": {"hexsha": "b6c756b0fe7b59b047ce9a28a2c31a3541876489", "size": 3937, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "prototypes/cpp-pic/particles.hpp", "max_stars_repo_name": "Krissmedt/imprunko", "max_stars_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-10-26T07:08:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-10T06:47:37.000Z", "max_issues_repo_path": "prototypes/cpp-pic/particles.hpp", "max_issues_repo_name": "Krissmedt/imprunko", "max_issues_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2018-11-09T08:50:48.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T20:11:12.000Z", "max_forks_repo_path": "prototypes/cpp-pic/particles.hpp", "max_forks_repo_name": "Krissmedt/imprunko", "max_forks_repo_head_hexsha": "94171d0d47171cc4b199cd52f5f29385cbff903e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2371794872, "max_line_length": 94, "alphanum_fraction": 0.5760731521, "num_tokens": 1378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.20398999086538425}}
{"text": "/*\n * Copyright (c) 2011, Georgia Tech Research Corporation\n * All rights reserved.\n *\n * Author: Tobias Kunz <tobias@gatech.edu>\n * Date: 05/2012\n *\n * Humanoid Robotics Lab      Georgia Institute of Technology\n * Director: Mike Stilman     http://www.golems.org\n *\n * Algorithm details and publications:\n * http://www.golems.org/node/1570\n *\n * This file is provided under the following \"BSD-style\" License:\n *   Redistribution and use in source and binary forms, with or\n *   without modification, are permitted provided that the following\n *   conditions are met:\n *   * Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above\n *     copyright notice, this list of conditions and the following\n *     disclaimer in the documentation and/or other materials provided\n *     with the distribution.\n *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n *   CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n *   POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <limits>\n#include <Eigen/Geometry>\n#include <algorithm>\n#include <cmath>\n#include <moveit/trajectory_processing/time_optimal_trajectory_generation.h>\n#include <vector>\n#include \"rclcpp/rclcpp.hpp\"\n\nnamespace trajectory_processing\n{\nnamespace\n{\nstatic const rclcpp::Logger LOGGER =\n    rclcpp::get_logger(\"moveit_trajectory_processing.time_optimal_trajectory_generation\");\nconstexpr double DEFAULT_TIMESTEP = 1e-3;\nconstexpr double EPS = 1e-6;\n}  // namespace\n\nclass LinearPathSegment : public PathSegment\n{\npublic:\n  LinearPathSegment(const Eigen::VectorXd& start, const Eigen::VectorXd& end)\n    : PathSegment((end - start).norm()), end_(end), start_(start)\n  {\n  }\n\n  Eigen::VectorXd getConfig(double s) const override\n  {\n    s /= length_;\n    s = std::max(0.0, std::min(1.0, s));\n    return (1.0 - s) * start_ + s * end_;\n  }\n\n  Eigen::VectorXd getTangent(double /* s */) const override\n  {\n    return (end_ - start_) / length_;\n  }\n\n  Eigen::VectorXd getCurvature(double /* s */) const override\n  {\n    return Eigen::VectorXd::Zero(start_.size());\n  }\n\n  std::list<double> getSwitchingPoints() const override\n  {\n    return std::list<double>();\n  }\n\n  LinearPathSegment* clone() const override\n  {\n    return new LinearPathSegment(*this);\n  }\n\nprivate:\n  Eigen::VectorXd end_;\n  Eigen::VectorXd start_;\n};\n\nclass CircularPathSegment : public PathSegment\n{\npublic:\n  CircularPathSegment(const Eigen::VectorXd& start, const Eigen::VectorXd& intersection, const Eigen::VectorXd& end,\n                      double max_deviation)\n  {\n    if ((intersection - start).norm() < 0.000001 || (end - intersection).norm() < 0.000001)\n    {\n      length_ = 0.0;\n      radius = 1.0;\n      center = intersection;\n      x = Eigen::VectorXd::Zero(start.size());\n      y = Eigen::VectorXd::Zero(start.size());\n      return;\n    }\n\n    const Eigen::VectorXd start_direction = (intersection - start).normalized();\n    const Eigen::VectorXd end_direction = (end - intersection).normalized();\n    const double start_dot_end = start_direction.dot(end_direction);\n\n    // catch division by 0 in computations below\n    if (start_dot_end > 0.999999 || start_dot_end < -0.999999)\n    {\n      length_ = 0.0;\n      radius = 1.0;\n      center = intersection;\n      x = Eigen::VectorXd::Zero(start.size());\n      y = Eigen::VectorXd::Zero(start.size());\n      return;\n    }\n\n    const double angle = acos(start_dot_end);\n    const double start_distance = (start - intersection).norm();\n    const double end_distance = (end - intersection).norm();\n\n    // enforce max deviation\n    double distance = std::min(start_distance, end_distance);\n    distance = std::min(distance, max_deviation * sin(0.5 * angle) / (1.0 - cos(0.5 * angle)));\n\n    radius = distance / tan(0.5 * angle);\n    length_ = angle * radius;\n\n    center = intersection + (end_direction - start_direction).normalized() * radius / cos(0.5 * angle);\n    x = (intersection - distance * start_direction - center).normalized();\n    y = start_direction;\n  }\n\n  Eigen::VectorXd getConfig(double s) const override\n  {\n    const double angle = s / radius;\n    return center + radius * (x * cos(angle) + y * sin(angle));\n  }\n\n  Eigen::VectorXd getTangent(double s) const override\n  {\n    const double angle = s / radius;\n    return -x * sin(angle) + y * cos(angle);\n  }\n\n  Eigen::VectorXd getCurvature(double s) const override\n  {\n    const double angle = s / radius;\n    return -1.0 / radius * (x * cos(angle) + y * sin(angle));\n  }\n\n  std::list<double> getSwitchingPoints() const override\n  {\n    std::list<double> switching_points;\n    const double dim = x.size();\n    for (unsigned int i = 0; i < dim; ++i)\n    {\n      double switching_angle = atan2(y[i], x[i]);\n      if (switching_angle < 0.0)\n      {\n        switching_angle += M_PI;\n      }\n      const double switching_point = switching_angle * radius;\n      if (switching_point < length_)\n      {\n        switching_points.push_back(switching_point);\n      }\n    }\n    switching_points.sort();\n    return switching_points;\n  }\n\n  CircularPathSegment* clone() const override\n  {\n    return new CircularPathSegment(*this);\n  }\n\nprivate:\n  double radius;\n  Eigen::VectorXd center;\n  Eigen::VectorXd x;\n  Eigen::VectorXd y;\n};\n\nPath::Path(const std::list<Eigen::VectorXd>& path, double max_deviation) : length_(0.0)\n{\n  if (path.size() < 2)\n    return;\n  std::list<Eigen::VectorXd>::const_iterator path_iterator1 = path.begin();\n  std::list<Eigen::VectorXd>::const_iterator path_iterator2 = path_iterator1;\n  ++path_iterator2;\n  std::list<Eigen::VectorXd>::const_iterator path_iterator3;\n  Eigen::VectorXd start_config = *path_iterator1;\n  while (path_iterator2 != path.end())\n  {\n    path_iterator3 = path_iterator2;\n    ++path_iterator3;\n    if (max_deviation > 0.0 && path_iterator3 != path.end())\n    {\n      CircularPathSegment* blend_segment =\n          new CircularPathSegment(0.5 * (*path_iterator1 + *path_iterator2), *path_iterator2,\n                                  0.5 * (*path_iterator2 + *path_iterator3), max_deviation);\n      Eigen::VectorXd end_config = blend_segment->getConfig(0.0);\n      if ((end_config - start_config).norm() > 0.000001)\n      {\n        path_segments_.push_back(std::make_unique<LinearPathSegment>(start_config, end_config));\n      }\n      path_segments_.emplace_back(blend_segment);\n\n      start_config = blend_segment->getConfig(blend_segment->getLength());\n    }\n    else\n    {\n      path_segments_.push_back(std::make_unique<LinearPathSegment>(start_config, *path_iterator2));\n      start_config = *path_iterator2;\n    }\n    path_iterator1 = path_iterator2;\n    ++path_iterator2;\n  }\n\n  // Create list of switching point candidates, calculate total path length and\n  // absolute positions of path segments\n  for (std::unique_ptr<PathSegment>& path_segment : path_segments_)\n  {\n    path_segment->position_ = length_;\n    std::list<double> local_switching_points = path_segment->getSwitchingPoints();\n    for (std::list<double>::const_iterator point = local_switching_points.begin();\n         point != local_switching_points.end(); ++point)\n    {\n      switching_points_.push_back(std::make_pair(length_ + *point, false));\n    }\n    length_ += path_segment->getLength();\n    while (!switching_points_.empty() && switching_points_.back().first >= length_)\n      switching_points_.pop_back();\n    switching_points_.push_back(std::make_pair(length_, true));\n  }\n  switching_points_.pop_back();\n}\n\nPath::Path(const Path& path) : length_(path.length_), switching_points_(path.switching_points_)\n{\n  for (const std::unique_ptr<PathSegment>& path_segment : path.path_segments_)\n  {\n    path_segments_.emplace_back(path_segment->clone());\n  }\n}\n\ndouble Path::getLength() const\n{\n  return length_;\n}\n\nPathSegment* Path::getPathSegment(double& s) const\n{\n  std::list<std::unique_ptr<PathSegment>>::const_iterator it = path_segments_.begin();\n  std::list<std::unique_ptr<PathSegment>>::const_iterator next = it;\n  ++next;\n  while (next != path_segments_.end() && s >= (*next)->position_)\n  {\n    it = next;\n    ++next;\n  }\n  s -= (*it)->position_;\n  return (*it).get();\n}\n\nEigen::VectorXd Path::getConfig(double s) const\n{\n  const PathSegment* path_segment = getPathSegment(s);\n  return path_segment->getConfig(s);\n}\n\nEigen::VectorXd Path::getTangent(double s) const\n{\n  const PathSegment* path_segment = getPathSegment(s);\n  return path_segment->getTangent(s);\n}\n\nEigen::VectorXd Path::getCurvature(double s) const\n{\n  const PathSegment* path_segment = getPathSegment(s);\n  return path_segment->getCurvature(s);\n}\n\ndouble Path::getNextSwitchingPoint(double s, bool& discontinuity) const\n{\n  std::list<std::pair<double, bool>>::const_iterator it = switching_points_.begin();\n  while (it != switching_points_.end() && it->first <= s)\n  {\n    ++it;\n  }\n  if (it == switching_points_.end())\n  {\n    discontinuity = true;\n    return length_;\n  }\n  discontinuity = it->second;\n  return it->first;\n}\n\nstd::list<std::pair<double, bool>> Path::getSwitchingPoints() const\n{\n  return switching_points_;\n}\n\nTrajectory::Trajectory(const Path& path, const Eigen::VectorXd& max_velocity, const Eigen::VectorXd& max_acceleration,\n                       double time_step)\n  : path_(path)\n  , max_velocity_(max_velocity)\n  , max_acceleration_(max_acceleration)\n  , joint_num_(max_velocity.size())\n  , valid_(true)\n  , time_step_(time_step)\n  , cached_time_(std::numeric_limits<double>::max())\n{\n  trajectory_.push_back(TrajectoryStep(0.0, 0.0));\n  double after_acceleration = getMinMaxPathAcceleration(0.0, 0.0, true);\n  while (valid_ && !integrateForward(trajectory_, after_acceleration) && valid_)\n  {\n    double before_acceleration;\n    TrajectoryStep switching_point;\n    if (getNextSwitchingPoint(trajectory_.back().path_pos_, switching_point, before_acceleration, after_acceleration))\n    {\n      break;\n    }\n    integrateBackward(trajectory_, switching_point.path_pos_, switching_point.path_vel_, before_acceleration);\n  }\n\n  if (valid_)\n  {\n    double before_acceleration = getMinMaxPathAcceleration(path_.getLength(), 0.0, false);\n    integrateBackward(trajectory_, path_.getLength(), 0.0, before_acceleration);\n  }\n\n  if (valid_)\n  {\n    // Calculate timing\n    std::list<TrajectoryStep>::iterator previous = trajectory_.begin();\n    std::list<TrajectoryStep>::iterator it = previous;\n    it->time_ = 0.0;\n    ++it;\n    while (it != trajectory_.end())\n    {\n      it->time_ =\n          previous->time_ + (it->path_pos_ - previous->path_pos_) / ((it->path_vel_ + previous->path_vel_) / 2.0);\n      previous = it;\n      ++it;\n    }\n  }\n}\n\nTrajectory::~Trajectory()\n{\n}\n\n// Returns true if end of path is reached.\nbool Trajectory::getNextSwitchingPoint(double path_pos, TrajectoryStep& next_switching_point,\n                                       double& before_acceleration, double& after_acceleration)\n{\n  TrajectoryStep acceleration_switching_point(path_pos, 0.0);\n  double acceleration_before_acceleration, acceleration_after_acceleration;\n  bool acceleration_reached_end;\n  do\n  {\n    acceleration_reached_end =\n        getNextAccelerationSwitchingPoint(acceleration_switching_point.path_pos_, acceleration_switching_point,\n                                          acceleration_before_acceleration, acceleration_after_acceleration);\n  } while (!acceleration_reached_end &&\n           acceleration_switching_point.path_vel_ > getVelocityMaxPathVelocity(acceleration_switching_point.path_pos_));\n\n  TrajectoryStep velocity_switching_point(path_pos, 0.0);\n  double velocity_before_acceleration, velocity_after_acceleration;\n  bool velocity_reached_end;\n  do\n  {\n    velocity_reached_end = getNextVelocitySwitchingPoint(velocity_switching_point.path_pos_, velocity_switching_point,\n                                                         velocity_before_acceleration, velocity_after_acceleration);\n  } while (\n      !velocity_reached_end && velocity_switching_point.path_pos_ <= acceleration_switching_point.path_pos_ &&\n      (velocity_switching_point.path_vel_ > getAccelerationMaxPathVelocity(velocity_switching_point.path_pos_ - EPS) ||\n       velocity_switching_point.path_vel_ > getAccelerationMaxPathVelocity(velocity_switching_point.path_pos_ + EPS)));\n\n  if (acceleration_reached_end && velocity_reached_end)\n  {\n    return true;\n  }\n  else if (!acceleration_reached_end &&\n           (velocity_reached_end || acceleration_switching_point.path_pos_ <= velocity_switching_point.path_pos_))\n  {\n    next_switching_point = acceleration_switching_point;\n    before_acceleration = acceleration_before_acceleration;\n    after_acceleration = acceleration_after_acceleration;\n    return false;\n  }\n  else\n  {\n    next_switching_point = velocity_switching_point;\n    before_acceleration = velocity_before_acceleration;\n    after_acceleration = velocity_after_acceleration;\n    return false;\n  }\n}\n\nbool Trajectory::getNextAccelerationSwitchingPoint(double path_pos, TrajectoryStep& next_switching_point,\n                                                   double& before_acceleration, double& after_acceleration)\n{\n  double switching_path_pos = path_pos;\n  double switching_path_vel;\n  while (true)\n  {\n    bool discontinuity;\n    switching_path_pos = path_.getNextSwitchingPoint(switching_path_pos, discontinuity);\n\n    if (switching_path_pos > path_.getLength() - EPS)\n    {\n      return true;\n    }\n\n    if (discontinuity)\n    {\n      const double before_path_vel = getAccelerationMaxPathVelocity(switching_path_pos - EPS);\n      const double after_path_vel = getAccelerationMaxPathVelocity(switching_path_pos + EPS);\n      switching_path_vel = std::min(before_path_vel, after_path_vel);\n      before_acceleration = getMinMaxPathAcceleration(switching_path_pos - EPS, switching_path_vel, false);\n      after_acceleration = getMinMaxPathAcceleration(switching_path_pos + EPS, switching_path_vel, true);\n\n      if ((before_path_vel > after_path_vel ||\n           getMinMaxPhaseSlope(switching_path_pos - EPS, switching_path_vel, false) >\n               getAccelerationMaxPathVelocityDeriv(switching_path_pos - 2.0 * EPS)) &&\n          (before_path_vel < after_path_vel || getMinMaxPhaseSlope(switching_path_pos + EPS, switching_path_vel, true) <\n                                                   getAccelerationMaxPathVelocityDeriv(switching_path_pos + 2.0 * EPS)))\n      {\n        break;\n      }\n    }\n    else\n    {\n      switching_path_vel = getAccelerationMaxPathVelocity(switching_path_pos);\n      before_acceleration = 0.0;\n      after_acceleration = 0.0;\n\n      if (getAccelerationMaxPathVelocityDeriv(switching_path_pos - EPS) < 0.0 &&\n          getAccelerationMaxPathVelocityDeriv(switching_path_pos + EPS) > 0.0)\n      {\n        break;\n      }\n    }\n  }\n\n  next_switching_point = TrajectoryStep(switching_path_pos, switching_path_vel);\n  return false;\n}\n\nbool Trajectory::getNextVelocitySwitchingPoint(double path_pos, TrajectoryStep& next_switching_point,\n                                               double& before_acceleration, double& after_acceleration)\n{\n  bool start = false;\n  path_pos -= DEFAULT_TIMESTEP;\n  do\n  {\n    path_pos += DEFAULT_TIMESTEP;\n\n    if (getMinMaxPhaseSlope(path_pos, getVelocityMaxPathVelocity(path_pos), false) >=\n        getVelocityMaxPathVelocityDeriv(path_pos))\n    {\n      start = true;\n    }\n  } while ((!start || getMinMaxPhaseSlope(path_pos, getVelocityMaxPathVelocity(path_pos), false) >\n                          getVelocityMaxPathVelocityDeriv(path_pos)) &&\n           path_pos < path_.getLength());\n\n  if (path_pos >= path_.getLength())\n  {\n    return true;  // end of trajectory reached\n  }\n\n  double before_path_pos = path_pos - DEFAULT_TIMESTEP;\n  double after_path_pos = path_pos;\n  while (after_path_pos - before_path_pos > EPS)\n  {\n    path_pos = (before_path_pos + after_path_pos) / 2.0;\n    if (getMinMaxPhaseSlope(path_pos, getVelocityMaxPathVelocity(path_pos), false) >\n        getVelocityMaxPathVelocityDeriv(path_pos))\n    {\n      before_path_pos = path_pos;\n    }\n    else\n    {\n      after_path_pos = path_pos;\n    }\n  }\n\n  before_acceleration = getMinMaxPathAcceleration(before_path_pos, getVelocityMaxPathVelocity(before_path_pos), false);\n  after_acceleration = getMinMaxPathAcceleration(after_path_pos, getVelocityMaxPathVelocity(after_path_pos), true);\n  next_switching_point = TrajectoryStep(after_path_pos, getVelocityMaxPathVelocity(after_path_pos));\n  return false;\n}\n\n// Returns true if end of path is reached\nbool Trajectory::integrateForward(std::list<TrajectoryStep>& trajectory, double acceleration)\n{\n  double path_pos = trajectory.back().path_pos_;\n  double path_vel = trajectory.back().path_vel_;\n\n  std::list<std::pair<double, bool>> switching_points = path_.getSwitchingPoints();\n  std::list<std::pair<double, bool>>::iterator next_discontinuity = switching_points.begin();\n\n  while (true)\n  {\n    while ((next_discontinuity != switching_points.end()) &&\n           (next_discontinuity->first <= path_pos || !next_discontinuity->second))\n    {\n      ++next_discontinuity;\n    }\n\n    double old_path_pos = path_pos;\n    double old_path_vel = path_vel;\n\n    path_vel += time_step_ * acceleration;\n    path_pos += time_step_ * 0.5 * (old_path_vel + path_vel);\n\n    if (next_discontinuity != switching_points.end() && path_pos > next_discontinuity->first)\n    {\n      // Avoid having a TrajectoryStep with path_pos near a switching point which will cause an almost identical\n      // TrajectoryStep get added in the next run (https://github.com/ros-planning/moveit/issues/1665)\n      if (path_pos - next_discontinuity->first < EPS)\n      {\n        continue;\n      }\n      path_vel = old_path_vel +\n                 (next_discontinuity->first - old_path_pos) * (path_vel - old_path_vel) / (path_pos - old_path_pos);\n      path_pos = next_discontinuity->first;\n    }\n\n    if (path_pos > path_.getLength())\n    {\n      trajectory.push_back(TrajectoryStep(path_pos, path_vel));\n      return true;\n    }\n    else if (path_vel < 0.0)\n    {\n      valid_ = false;\n      RCLCPP_ERROR(LOGGER, \"Error while integrating forward: Negative path velocity\");\n      return true;\n    }\n\n    if (path_vel > getVelocityMaxPathVelocity(path_pos) &&\n        getMinMaxPhaseSlope(old_path_pos, getVelocityMaxPathVelocity(old_path_pos), false) <=\n            getVelocityMaxPathVelocityDeriv(old_path_pos))\n    {\n      path_vel = getVelocityMaxPathVelocity(path_pos);\n    }\n\n    trajectory.push_back(TrajectoryStep(path_pos, path_vel));\n    acceleration = getMinMaxPathAcceleration(path_pos, path_vel, true);\n\n    if (path_vel > getAccelerationMaxPathVelocity(path_pos) || path_vel > getVelocityMaxPathVelocity(path_pos))\n    {\n      // Find more accurate intersection with max-velocity curve using bisection\n      TrajectoryStep overshoot = trajectory.back();\n      trajectory.pop_back();\n      double before = trajectory.back().path_pos_;\n      double before_path_vel = trajectory.back().path_vel_;\n      double after = overshoot.path_pos_;\n      double after_path_vel = overshoot.path_vel_;\n      while (after - before > EPS)\n      {\n        const double midpoint = 0.5 * (before + after);\n        double midpoint_path_vel = 0.5 * (before_path_vel + after_path_vel);\n\n        if (midpoint_path_vel > getVelocityMaxPathVelocity(midpoint) &&\n            getMinMaxPhaseSlope(before, getVelocityMaxPathVelocity(before), false) <=\n                getVelocityMaxPathVelocityDeriv(before))\n        {\n          midpoint_path_vel = getVelocityMaxPathVelocity(midpoint);\n        }\n\n        if (midpoint_path_vel > getAccelerationMaxPathVelocity(midpoint) ||\n            midpoint_path_vel > getVelocityMaxPathVelocity(midpoint))\n        {\n          after = midpoint;\n          after_path_vel = midpoint_path_vel;\n        }\n        else\n        {\n          before = midpoint;\n          before_path_vel = midpoint_path_vel;\n        }\n      }\n      trajectory.push_back(TrajectoryStep(before, before_path_vel));\n\n      if (getAccelerationMaxPathVelocity(after) < getVelocityMaxPathVelocity(after))\n      {\n        if (after > next_discontinuity->first)\n        {\n          return false;\n        }\n        else if (getMinMaxPhaseSlope(trajectory.back().path_pos_, trajectory.back().path_vel_, true) >\n                 getAccelerationMaxPathVelocityDeriv(trajectory.back().path_pos_))\n        {\n          return false;\n        }\n      }\n      else\n      {\n        if (getMinMaxPhaseSlope(trajectory.back().path_pos_, trajectory_.back().path_vel_, false) >\n            getVelocityMaxPathVelocityDeriv(trajectory_.back().path_pos_))\n        {\n          return false;\n        }\n      }\n    }\n  }\n}\n\nvoid Trajectory::integrateBackward(std::list<TrajectoryStep>& start_trajectory, double path_pos, double path_vel,\n                                   double acceleration)\n{\n  std::list<TrajectoryStep>::iterator start2 = start_trajectory.end();\n  --start2;\n  std::list<TrajectoryStep>::iterator start1 = start2;\n  --start1;\n  std::list<TrajectoryStep> trajectory;\n  double slope;\n  assert(start1->path_pos_ <= path_pos);\n\n  while (start1 != start_trajectory.begin() || path_pos >= 0.0)\n  {\n    if (start1->path_pos_ <= path_pos)\n    {\n      trajectory.push_front(TrajectoryStep(path_pos, path_vel));\n      path_vel -= time_step_ * acceleration;\n      path_pos -= time_step_ * 0.5 * (path_vel + trajectory.front().path_vel_);\n      acceleration = getMinMaxPathAcceleration(path_pos, path_vel, false);\n      slope = (trajectory.front().path_vel_ - path_vel) / (trajectory.front().path_pos_ - path_pos);\n\n      if (path_vel < 0.0)\n      {\n        valid_ = false;\n        RCLCPP_ERROR(LOGGER, \"Error while integrating backward: Negative path velocity\");\n        end_trajectory_ = trajectory;\n        return;\n      }\n    }\n    else\n    {\n      --start1;\n      --start2;\n    }\n\n    // Check for intersection between current start trajectory and backward\n    // trajectory segments\n    const double start_slope = (start2->path_vel_ - start1->path_vel_) / (start2->path_pos_ - start1->path_pos_);\n    const double intersection_path_pos =\n        (start1->path_vel_ - path_vel + slope * path_pos - start_slope * start1->path_pos_) / (slope - start_slope);\n    if (std::max(start1->path_pos_, path_pos) - EPS <= intersection_path_pos &&\n        intersection_path_pos <= EPS + std::min(start2->path_pos_, trajectory.front().path_pos_))\n    {\n      const double intersection_path_vel =\n          start1->path_vel_ + start_slope * (intersection_path_pos - start1->path_pos_);\n      start_trajectory.erase(start2, start_trajectory.end());\n      start_trajectory.push_back(TrajectoryStep(intersection_path_pos, intersection_path_vel));\n      start_trajectory.splice(start_trajectory.end(), trajectory);\n      return;\n    }\n  }\n\n  valid_ = false;\n  RCLCPP_ERROR(LOGGER, \"Error while integrating backward: Did not hit start trajectory\");\n  end_trajectory_ = trajectory;\n}\n\ndouble Trajectory::getMinMaxPathAcceleration(double path_pos, double path_vel, bool max)\n{\n  Eigen::VectorXd config_deriv = path_.getTangent(path_pos);\n  Eigen::VectorXd config_deriv2 = path_.getCurvature(path_pos);\n  double factor = max ? 1.0 : -1.0;\n  double max_path_acceleration = std::numeric_limits<double>::max();\n  for (unsigned int i = 0; i < joint_num_; ++i)\n  {\n    if (config_deriv[i] != 0.0)\n    {\n      max_path_acceleration =\n          std::min(max_path_acceleration, max_acceleration_[i] / std::abs(config_deriv[i]) -\n                                              factor * config_deriv2[i] * path_vel * path_vel / config_deriv[i]);\n    }\n  }\n  return factor * max_path_acceleration;\n}\n\ndouble Trajectory::getMinMaxPhaseSlope(double path_pos, double path_vel, bool max)\n{\n  return getMinMaxPathAcceleration(path_pos, path_vel, max) / path_vel;\n}\n\ndouble Trajectory::getAccelerationMaxPathVelocity(double path_pos) const\n{\n  double max_path_velocity = std::numeric_limits<double>::infinity();\n  const Eigen::VectorXd config_deriv = path_.getTangent(path_pos);\n  const Eigen::VectorXd config_deriv2 = path_.getCurvature(path_pos);\n  for (unsigned int i = 0; i < joint_num_; ++i)\n  {\n    if (config_deriv[i] != 0.0)\n    {\n      for (unsigned int j = i + 1; j < joint_num_; ++j)\n      {\n        if (config_deriv[j] != 0.0)\n        {\n          double a_ij = config_deriv2[i] / config_deriv[i] - config_deriv2[j] / config_deriv[j];\n          if (a_ij != 0.0)\n          {\n            max_path_velocity = std::min(max_path_velocity, sqrt((max_acceleration_[i] / std::abs(config_deriv[i]) +\n                                                                  max_acceleration_[j] / std::abs(config_deriv[j])) /\n                                                                 std::abs(a_ij)));\n          }\n        }\n      }\n    }\n    else if (config_deriv2[i] != 0.0)\n    {\n      max_path_velocity = std::min(max_path_velocity, sqrt(max_acceleration_[i] / std::abs(config_deriv2[i])));\n    }\n  }\n  return max_path_velocity;\n}\n\ndouble Trajectory::getVelocityMaxPathVelocity(double path_pos) const\n{\n  const Eigen::VectorXd tangent = path_.getTangent(path_pos);\n  double max_path_velocity = std::numeric_limits<double>::max();\n  for (unsigned int i = 0; i < joint_num_; ++i)\n  {\n    max_path_velocity = std::min(max_path_velocity, max_velocity_[i] / std::abs(tangent[i]));\n  }\n  return max_path_velocity;\n}\n\ndouble Trajectory::getAccelerationMaxPathVelocityDeriv(double path_pos)\n{\n  return (getAccelerationMaxPathVelocity(path_pos + EPS) - getAccelerationMaxPathVelocity(path_pos - EPS)) /\n         (2.0 * EPS);\n}\n\ndouble Trajectory::getVelocityMaxPathVelocityDeriv(double path_pos)\n{\n  const Eigen::VectorXd tangent = path_.getTangent(path_pos);\n  double max_path_velocity = std::numeric_limits<double>::max();\n  unsigned int active_constraint;\n  for (unsigned int i = 0; i < joint_num_; ++i)\n  {\n    const double this_max_path_velocity = max_velocity_[i] / std::abs(tangent[i]);\n    if (this_max_path_velocity < max_path_velocity)\n    {\n      max_path_velocity = this_max_path_velocity;\n      active_constraint = i;\n    }\n  }\n  return -(max_velocity_[active_constraint] * path_.getCurvature(path_pos)[active_constraint]) /\n         (tangent[active_constraint] * std::abs(tangent[active_constraint]));\n}\n\nbool Trajectory::isValid() const\n{\n  return valid_;\n}\n\ndouble Trajectory::getDuration() const\n{\n  return trajectory_.back().time_;\n}\n\nstd::list<Trajectory::TrajectoryStep>::const_iterator Trajectory::getTrajectorySegment(double time) const\n{\n  if (time >= trajectory_.back().time_)\n  {\n    std::list<TrajectoryStep>::const_iterator last = trajectory_.end();\n    last--;\n    return last;\n  }\n  else\n  {\n    if (time < cached_time_)\n    {\n      cached_trajectory_segment_ = trajectory_.begin();\n    }\n    while (time >= cached_trajectory_segment_->time_)\n    {\n      ++cached_trajectory_segment_;\n    }\n    cached_time_ = time;\n    return cached_trajectory_segment_;\n  }\n}\n\nEigen::VectorXd Trajectory::getPosition(double time) const\n{\n  std::list<TrajectoryStep>::const_iterator it = getTrajectorySegment(time);\n  std::list<TrajectoryStep>::const_iterator previous = it;\n  previous--;\n\n  double time_step = it->time_ - previous->time_;\n  const double acceleration =\n      2.0 * (it->path_pos_ - previous->path_pos_ - time_step * previous->path_vel_) / (time_step * time_step);\n\n  time_step = time - previous->time_;\n  const double path_pos =\n      previous->path_pos_ + time_step * previous->path_vel_ + 0.5 * time_step * time_step * acceleration;\n\n  return path_.getConfig(path_pos);\n}\n\nEigen::VectorXd Trajectory::getVelocity(double time) const\n{\n  std::list<TrajectoryStep>::const_iterator it = getTrajectorySegment(time);\n  std::list<TrajectoryStep>::const_iterator previous = it;\n  previous--;\n\n  double time_step = it->time_ - previous->time_;\n  const double acceleration =\n      2.0 * (it->path_pos_ - previous->path_pos_ - time_step * previous->path_vel_) / (time_step * time_step);\n\n  time_step = time - previous->time_;\n  const double path_pos =\n      previous->path_pos_ + time_step * previous->path_vel_ + 0.5 * time_step * time_step * acceleration;\n  const double path_vel = previous->path_vel_ + time_step * acceleration;\n\n  return path_.getTangent(path_pos) * path_vel;\n}\n\nEigen::VectorXd Trajectory::getAcceleration(double time) const\n{\n  std::list<TrajectoryStep>::const_iterator it = getTrajectorySegment(time);\n  std::list<TrajectoryStep>::const_iterator previous = it;\n  previous--;\n\n  double time_step = it->time_ - previous->time_;\n  const double acceleration =\n      2.0 * (it->path_pos_ - previous->path_pos_ - time_step * previous->path_vel_) / (time_step * time_step);\n\n  time_step = time - previous->time_;\n  const double path_pos =\n      previous->path_pos_ + time_step * previous->path_vel_ + 0.5 * time_step * time_step * acceleration;\n  const double path_vel = previous->path_vel_ + time_step * acceleration;\n  Eigen::VectorXd path_acc =\n      (path_.getTangent(path_pos) * path_vel - path_.getTangent(previous->path_pos_) * previous->path_vel_);\n  if (time_step > 0.0)\n    path_acc /= time_step;\n  return path_acc;\n}\n\nTimeOptimalTrajectoryGeneration::TimeOptimalTrajectoryGeneration(const double path_tolerance, const double resample_dt,\n                                                                 const double min_angle_change)\n  : path_tolerance_(path_tolerance), resample_dt_(resample_dt), min_angle_change_(min_angle_change)\n{\n}\n\nbool TimeOptimalTrajectoryGeneration::computeTimeStamps(robot_trajectory::RobotTrajectory& trajectory,\n                                                        const double max_velocity_scaling_factor,\n                                                        const double max_acceleration_scaling_factor) const\n{\n  if (trajectory.empty())\n    return true;\n\n  const moveit::core::JointModelGroup* group = trajectory.getGroup();\n  if (!group)\n  {\n    RCLCPP_ERROR(LOGGER, \"It looks like the planner did not set the group the plan was computed for\");\n    return false;\n  }\n\n  // Validate scaling\n  double velocity_scaling_factor = 1.0;\n  if (max_velocity_scaling_factor > 0.0 && max_velocity_scaling_factor <= 1.0)\n  {\n    velocity_scaling_factor = max_velocity_scaling_factor;\n  }\n  else if (max_velocity_scaling_factor == 0.0)\n  {\n    RCLCPP_DEBUG(LOGGER, \"A max_velocity_scaling_factor of 0.0 was specified, defaulting to %f instead.\",\n                 velocity_scaling_factor);\n  }\n  else\n  {\n    RCLCPP_WARN(LOGGER, \"Invalid max_velocity_scaling_factor %f specified, defaulting to %f instead.\",\n                max_velocity_scaling_factor, velocity_scaling_factor);\n  }\n\n  double acceleration_scaling_factor = 1.0;\n  if (max_acceleration_scaling_factor > 0.0 && max_acceleration_scaling_factor <= 1.0)\n  {\n    acceleration_scaling_factor = max_acceleration_scaling_factor;\n  }\n  else if (max_acceleration_scaling_factor == 0.0)\n  {\n    RCLCPP_DEBUG(LOGGER, \"A max_acceleration_scaling_factor of 0.0 was specified, defaulting to %f instead.\",\n                 acceleration_scaling_factor);\n  }\n  else\n  {\n    RCLCPP_WARN(LOGGER, \"Invalid max_acceleration_scaling_factor %f specified, defaulting to %f instead.\",\n                max_acceleration_scaling_factor, acceleration_scaling_factor);\n  }\n\n  // This lib does not actually work properly when angles wrap around, so we need to unwind the path first\n  trajectory.unwind();\n\n  // This is pretty much copied from IterativeParabolicTimeParameterization::applyVelocityConstraints\n  const std::vector<std::string>& vars = group->getVariableNames();\n  const std::vector<int>& idx = group->getVariableIndexList();\n  const moveit::core::RobotModel& rmodel = group->getParentModel();\n  const unsigned num_joints = group->getVariableCount();\n  const unsigned num_points = trajectory.getWayPointCount();\n\n  // Get the limits (we do this at same time, unlike IterativeParabolicTimeParameterization)\n  Eigen::VectorXd max_velocity(num_joints);\n  Eigen::VectorXd max_acceleration(num_joints);\n  for (size_t j = 0; j < num_joints; ++j)\n  {\n    const moveit::core::VariableBounds& bounds = rmodel.getVariableBounds(vars[j]);\n\n    // Limits need to be non-zero, otherwise we never exit\n    max_velocity[j] = 1.0;\n    if (bounds.velocity_bounded_)\n    {\n      if (bounds.max_velocity_ < std::numeric_limits<double>::epsilon())\n      {\n        RCLCPP_ERROR(LOGGER, \"Invalid max_velocity %f specified for '%s', must be greater than 0.0\",\n                     bounds.max_velocity_, vars[j].c_str());\n        return false;\n      }\n      max_velocity[j] =\n          std::min(std::fabs(bounds.max_velocity_), std::fabs(bounds.min_velocity_)) * velocity_scaling_factor;\n    }\n    else\n    {\n      RCLCPP_WARN_STREAM_ONCE(\n          LOGGER, \"Joint velocity limits are not defined. Using the default \"\n                      << max_velocity[j] << \" rad/s. You can define velocity limits in the URDF or joint_limits.yaml.\");\n    }\n\n    max_acceleration[j] = 1.0;\n    if (bounds.acceleration_bounded_)\n    {\n      if (bounds.max_acceleration_ < std::numeric_limits<double>::epsilon())\n      {\n        RCLCPP_ERROR(LOGGER, \"Invalid max_acceleration %f specified for '%s', must be greater than 0.0\",\n                     bounds.max_acceleration_, vars[j].c_str());\n        return false;\n      }\n      max_acceleration[j] = std::min(std::fabs(bounds.max_acceleration_), std::fabs(bounds.min_acceleration_)) *\n                            acceleration_scaling_factor;\n    }\n    else\n    {\n      RCLCPP_WARN_STREAM_ONCE(LOGGER,\n                              \"Joint acceleration limits are not defined. Using the default \"\n                                  << max_acceleration[j]\n                                  << \" rad/s^2. You can define acceleration limits in the URDF or joint_limits.yaml.\");\n    }\n  }\n\n  // Have to convert into Eigen data structs and remove repeated points\n  //  (https://github.com/tobiaskunz/trajectories/issues/3)\n  std::list<Eigen::VectorXd> points;\n  for (size_t p = 0; p < num_points; ++p)\n  {\n    moveit::core::RobotStatePtr waypoint = trajectory.getWayPointPtr(p);\n    Eigen::VectorXd new_point(num_joints);\n    // The first point should always be kept\n    bool diverse_point = (p == 0);\n\n    for (size_t j = 0; j < num_joints; ++j)\n    {\n      new_point[j] = waypoint->getVariablePosition(idx[j]);\n      // If any joint angle is different, it's a unique waypoint\n      if (p > 0 && std::fabs(new_point[j] - points.back()[j]) > min_angle_change_)\n      {\n        diverse_point = true;\n      }\n    }\n\n    if (diverse_point)\n      points.push_back(new_point);\n  }\n\n  // Return trajectory with only the first waypoint if there are not multiple diverse points\n  if (points.size() == 1)\n  {\n    moveit::core::RobotState waypoint = moveit::core::RobotState(trajectory.getWayPoint(0));\n    waypoint.zeroVelocities();\n    waypoint.zeroAccelerations();\n    trajectory.clear();\n    trajectory.addSuffixWayPoint(waypoint, 0.0);\n    return true;\n  }\n\n  // Now actually call the algorithm\n  Trajectory parameterized(Path(points, path_tolerance_), max_velocity, max_acceleration, DEFAULT_TIMESTEP);\n  if (!parameterized.isValid())\n  {\n    RCLCPP_ERROR(LOGGER, \"Unable to parameterize trajectory.\");\n    return false;\n  }\n\n  // Compute sample count\n  size_t sample_count = std::ceil(parameterized.getDuration() / resample_dt_);\n\n  // Resample and fill in trajectory\n  moveit::core::RobotState waypoint = moveit::core::RobotState(trajectory.getWayPoint(0));\n  trajectory.clear();\n  double last_t = 0;\n  for (size_t sample = 0; sample <= sample_count; ++sample)\n  {\n    // always sample the end of the trajectory as well\n    double t = std::min(parameterized.getDuration(), sample * resample_dt_);\n    Eigen::VectorXd position = parameterized.getPosition(t);\n    Eigen::VectorXd velocity = parameterized.getVelocity(t);\n    Eigen::VectorXd acceleration = parameterized.getAcceleration(t);\n\n    for (size_t j = 0; j < num_joints; ++j)\n    {\n      waypoint.setVariablePosition(idx[j], position[j]);\n      waypoint.setVariableVelocity(idx[j], velocity[j]);\n      waypoint.setVariableAcceleration(idx[j], acceleration[j]);\n    }\n\n    trajectory.addSuffixWayPoint(waypoint, t - last_t);\n    last_t = t;\n  }\n\n  return true;\n}\n}  // namespace trajectory_processing\n", "meta": {"hexsha": "294f2e94ec081dc34dee1be4dedd8ce8914ff4fb", "size": 36844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "moveit_core/trajectory_processing/src/time_optimal_trajectory_generation.cpp", "max_stars_repo_name": "michael-marron/moveit2", "max_stars_repo_head_hexsha": "7e06171605b7da3a05ef32e4f46920d50aedd292", "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": "moveit_core/trajectory_processing/src/time_optimal_trajectory_generation.cpp", "max_issues_repo_name": "michael-marron/moveit2", "max_issues_repo_head_hexsha": "7e06171605b7da3a05ef32e4f46920d50aedd292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2022-01-11T13:47:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T10:44:25.000Z", "max_forks_repo_path": "moveit_core/trajectory_processing/src/time_optimal_trajectory_generation.cpp", "max_forks_repo_name": "michael-marron/moveit2", "max_forks_repo_head_hexsha": "7e06171605b7da3a05ef32e4f46920d50aedd292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2911877395, "max_line_length": 120, "alphanum_fraction": 0.6860818586, "num_tokens": 8797, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.3812195662561499, "lm_q1q2_score": 0.20398999086538422}}
{"text": "// @file:     sim_anneal.cc\r\n// @author:   Samuel\r\n// @created:  2017.08.23\r\n// @editted:  2019.02.01\r\n// @license:  Apache License 2.0\r\n//\r\n// @desc:     Simulated annealing physics engine\r\n\r\n#include \"simanneal.h\"\r\n#include <ctime>\r\n#include <algorithm>\r\n#include <unordered_set>\r\n\r\n#include <boost/numeric/ublas/vector.hpp>\r\n#include <boost/numeric/ublas/io.hpp>\r\n\r\n// thread CPU time for Linux\r\n//#include <pthread.h>\r\n//#include <time.h>\r\n\r\nsaglobal::TimeKeeper *saglobal::TimeKeeper::time_keeper=nullptr;\r\nint saglobal::log_level = Logger::WRN;\r\n\r\nusing namespace phys;\r\n\r\n// static variables\r\nSimParams SimAnneal::sim_params;\r\nstd::mutex SimAnneal::result_store_mutex;\r\nFPType SimAnneal::db_distance_scale = 1E-10;\r\nAllChargeResults SimAnneal::charge_results;\r\nAllEnergyResults SimAnneal::energy_results;\r\n//AllCPUTimes SimAnneal::cpu_times;\r\nSuggestedResults SimAnneal::suggested_gs_results;\r\n\r\n// alias for the commonly used sim_params static variable\r\nconstexpr auto sparams = &SimAnneal::sim_params;\r\n\r\n\r\n// SimParams implementation\r\n\r\nvoid SimParams::setDBLocs(const std::vector<EuclCoord> &t_db_locs)\r\n{\r\n  db_locs = t_db_locs;\r\n  if (db_locs.size() == 0) {\r\n    throw \"There must be 1 or more DBs when setting DBs for SimParams.\";\r\n  }\r\n  n_dbs = db_locs.size();\r\n  db_r.resize(n_dbs, n_dbs);\r\n  v_ij.resize(n_dbs, n_dbs);\r\n  v_ext.resize(n_dbs);\r\n}\r\n\r\nvoid SimParams::setDBLocs(const std::vector<LatCoord> &t_db_locs)\r\n{\r\n  std::vector<EuclCoord> db_locs;\r\n  for (LatCoord lat_coord : t_db_locs) {\r\n    assert(lat_coord.size() == 3);\r\n    db_locs.push_back(latToEuclCoord(lat_coord[0], lat_coord[1], lat_coord[2]));\r\n  }\r\n  setDBLocs(db_locs);\r\n}\r\n\r\nEuclCoord SimParams::latToEuclCoord(const int &n, const int &m, const int &l)\r\n{\r\n  FPType x = n * constants::lat_a;\r\n  FPType y = m * constants::lat_b + l * constants::lat_c;\r\n  return std::make_pair(x, y);\r\n}\r\n\r\n// SimAnneal (master) Implementation\r\n\r\nSimAnneal::SimAnneal(SimParams &sparams)\r\n{\r\n  sim_params = sparams;\r\n  initialize();\r\n}\r\n\r\n\r\nvoid SimAnneal::invokeSimAnneal()\r\n{\r\n  Logger log(saglobal::log_level);\r\n  log.debug() << \"Setting up SimAnnealThreads...\" << std::endl;\r\n\r\n  // spawn all the threads\r\n  for (int i=0; i<sim_params.num_instances; i++) {\r\n    boost::random_device rd;\r\n    std::uint64_t seed = rd();\r\n    seed = (seed << 32) | rd();\r\n    SimAnnealThread annealer(i, seed);\r\n    std::thread th(&SimAnnealThread::run, annealer);\r\n    anneal_threads.push_back(std::move(th));\r\n  }\r\n\r\n  log.debug() << \"Wait for simulations to complete.\" << std::endl;\r\n\r\n  // wait for threads to complete\r\n  for (auto &th : anneal_threads) {\r\n    th.join();\r\n  }\r\n\r\n  log.debug() << \"All simulations complete.\" << std::endl;\r\n}\r\n\r\nFPType SimAnneal::systemEnergy(const ublas::vector<int> &n_in, bool qubo)\r\n{\r\n  assert(n_in.size() > 0);\r\n\r\n  //FPType E = 0.5 * ublas::inner_prod(n_in, ublas::prod(sim_params.v_ij, n_in))\r\n    //- ublas::inner_prod(n_in, sim_params.v_ext);\r\n  FPType E = ublas::inner_prod(n_in, sim_params.v_ext)\r\n    + 0.5 * ublas::inner_prod(n_in, ublas::prod(sim_params.v_ij, n_in));\r\n    \r\n\r\n  if (qubo) {\r\n    for (int n_i : n_in) {\r\n      E += n_i * sim_params.mu;\r\n    }\r\n  }\r\n  \r\n  return E;\r\n}\r\n\r\nbool SimAnneal::isMetastable(const ublas::vector<int> &n_in)\r\n{\r\n  assert(n_in.size() > 0);\r\n  Logger log(saglobal::log_level);\r\n\r\n  const FPType &muzm = sparams->mu;\r\n  const FPType &mupz = sparams->mu - constants::eta;\r\n  const FPType &zero_equiv = constants::RECALC_STABILITY_ERR;\r\n\r\n  ublas::vector<FPType> v_local(n_in.size());\r\n  log.debug() << \"V_i and Charge State Config \" << n_in << \":\" << std::endl;\r\n  for (unsigned int i=0; i<n_in.size(); i++) {\r\n    // calculate v_i\r\n    v_local[i] = - sim_params.v_ext[i];\r\n    for (unsigned int j=0; j<n_in.size(); j++) {\r\n      if (i == j) continue;\r\n      v_local[i] -= sim_params.v_ij(i,j) * n_in[j];\r\n    }\r\n    log.debug() << \"\\tDB[\" << i << \"]: charge state=\" << n_in[i]\r\n      << \", v_local[i]=\" << v_local[i] << \" eV, and v_local[i]+muzm=\" << v_local[i] + muzm << \"eV\" << std::endl;\r\n\r\n    // return false if invalid\r\n    if (!(   (n_in[i] == -1 && v_local[i] + muzm < zero_equiv)    // DB- valid condition\r\n          || (n_in[i] == 1  && v_local[i] + mupz > - zero_equiv)  // DB+ valid condition\r\n          || (n_in[i] == 0  && v_local[i] + muzm > - zero_equiv   // DB0 valid condition\r\n                            && v_local[i] + mupz < zero_equiv))) {\r\n      log.debug() << \"config \" << n_in << \" has an invalid population, failed at index \" << i << std::endl;\r\n      log.debug() << \"v_local[i]=\" << v_local[i] << \", muzm=\" << muzm << \", mupz=\" << mupz << std::endl;\r\n      return false;\r\n    }\r\n  }\r\n  log.debug() << \"config \" << n_in << \" has a valid population.\" << std::endl;\r\n\r\n  auto hopDel = [v_local, n_in](const int &i, const int &j) -> FPType {\r\n    int dn_i = (n_in[i]==-1) ? 1 : -1;\r\n    int dn_j = - dn_i;\r\n    return - v_local[i]*dn_i - v_local[j]*dn_j - sparams->v_ij(i,j);\r\n  };\r\n\r\n  for (unsigned int i=0; i<n_in.size(); i++) {\r\n    // do nothing with DB+\r\n    if (n_in[i] == 1)\r\n      continue;\r\n\r\n    for (unsigned int j=0; j<n_in.size(); j++) {\r\n      // attempt hops from more negative charge states to more positive ones\r\n      FPType E_del = hopDel(i, j);\r\n      if ((n_in[j] > n_in[i]) && (E_del < -zero_equiv)) {\r\n        log.debug() << \"config \" << n_in << \" not stable since hopping from site \"\r\n          << i << \" to \" << j << \" would result in an energy change of \"\r\n          << E_del << std::endl;\r\n        return false;\r\n      }\r\n    }\r\n  }\r\n  log.debug() << \"config \" << n_in << \" has a stable configuration.\" << std::endl;\r\n  return true;\r\n}\r\n\r\nvoid SimAnneal::storeResults(SimAnnealThread *annealer, int thread_id)\r\n{\r\n  result_store_mutex.lock();\r\n\r\n  charge_results[thread_id] = annealer->db_charges;\r\n  energy_results[thread_id] = annealer->config_energies;\r\n  //cpu_times[thread_id] = annealer->CPUTime();\r\n\r\n  suggested_gs_results[thread_id] = annealer->suggestedConfig();\r\n\r\n  result_store_mutex.unlock();\r\n}\r\n\r\nSuggestedResults SimAnneal::suggestedConfigResults(bool tidy)\r\n{\r\n  SuggestedResults filtered_results;\r\n  if (tidy) {\r\n    // deduplicate and recalculate energy\r\n    std::unordered_set<std::string> config_set;\r\n    //std::map< ublas::vector<int>, ChargeConfigResult > result_map;\r\n    for (auto result : suggested_gs_results) {\r\n      if (!result.initialized) {\r\n        continue;\r\n      }\r\n      if (config_set.find(configToStr(result.config)) == config_set.end()) {\r\n        config_set.insert(configToStr(result.config));\r\n        if (isMetastable(result.config)) {\r\n          result.system_energy = systemEnergy(result.config);\r\n          filtered_results.push_back(result);\r\n        }\r\n      }\r\n    }\r\n  } else {\r\n    // return every result that has been initialized\r\n    for (auto result : suggested_gs_results)\r\n      if (result.initialized)\r\n        filtered_results.push_back(result);\r\n  }\r\n  return filtered_results;\r\n}\r\n\r\n\r\n// PRIVATE\r\n\r\nvoid SimAnneal::initialize()\r\n{\r\n  Logger log(saglobal::log_level);\r\n  SimParams &sp = sim_params;\r\n\r\n  log.debug() << \"Performing pre-calculations...\" << std::endl;\r\n\r\n  // set default values\r\n  if (sp.v_freeze_init < 0)\r\n    sp.v_freeze_init = fabs(sp.mu) / 2;\r\n  if (sp.v_freeze_reset < 0)\r\n    sp.v_freeze_reset = fabs(sp.mu);\r\n\r\n  // apply schedule scaling\r\n  sp.alpha = std::pow(std::exp(-1.), 1./(sp.T_e_inv_point * sp.anneal_cycles));\r\n  sp.v_freeze_cycles = sp.v_freeze_end_point * sp.anneal_cycles;\r\n  sp.v_freeze_step = sp.v_freeze_threshold / sp.v_freeze_cycles;\r\n\r\n  log.debug() << \"Anneal cycles: \" << sp.anneal_cycles << \", alpha: \" \r\n    << sp.alpha << \", v_freeze_cycles: \" << sp.v_freeze_cycles << std::endl;\r\n\r\n  sp.result_queue_size = sp.anneal_cycles * sp.result_queue_factor;\r\n  sp.result_queue_size = std::min(sp.result_queue_size, sp.anneal_cycles);\r\n  sp.result_queue_size = std::max(sp.result_queue_size, 1);\r\n  log.debug() << \"Result queue size: \" << sp.result_queue_size << std::endl;\r\n\r\n\r\n  if (sp.preanneal_cycles > sp.anneal_cycles) {\r\n    std::cerr << \"Preanneal cycles > Anneal cycles\";\r\n    throw;\r\n  }\r\n\r\n\r\n  // phys\r\n  sp.kT_min = constants::Kb * sp.T_min;\r\n  sp.Kc = 1/(4 * constants::PI * sp.eps_r * constants::EPS0);\r\n\r\n  // inter-db distances and voltages\r\n  for (int i=0; i<sp.n_dbs; i++) {\r\n    sp.db_r(i,i) = 0.;\r\n    sp.v_ij(i,i) = 0.;\r\n    for (int j=i+1; j<sp.n_dbs; j++) {\r\n      sp.db_r(i,j) = db_distance_scale * distance(i,j);\r\n      sp.v_ij(i,j) = interElecPotential(sp.db_r(i,j));\r\n      sp.db_r(j,i) = sp.db_r(i,j);\r\n      sp.v_ij(j,i) = sp.v_ij(i,j);\r\n\r\n      log.debug() << \"db_r[\" << i << \"][\" << j << \"]=\" << sp.db_r(i,j) \r\n        << \", v_ij[\" << i << \"][\" << j << \"]=\" << sp.v_ij(i,j) << std::endl;\r\n    }\r\n  }\r\n\r\n  log.debug() << \"Pre-calculations complete\" << std::endl << std::endl;\r\n\r\n  // determine number of threads to run\r\n  if (sp.num_instances == -1) {\r\n    if (sp.n_dbs <= 9) {\r\n      sp.num_instances = 8;\r\n    } else if (sp.n_dbs <= 25) {\r\n      sp.num_instances = 16;\r\n    } else {\r\n      sp.num_instances = 128;\r\n    }\r\n  }\r\n\r\n  charge_results.resize(sp.num_instances);\r\n  energy_results.resize(sp.num_instances);\r\n  //cpu_times.resize(sp.num_instances);\r\n  suggested_gs_results.resize(sp.num_instances);\r\n}\r\n\r\nFPType SimAnneal::distance(const int &i, const int &j)\r\n{\r\n  FPType x1 = sim_params.db_locs[i].first;\r\n  FPType y1 = sim_params.db_locs[i].second;\r\n  FPType x2 = sim_params.db_locs[j].first;\r\n  FPType y2 = sim_params.db_locs[j].second;\r\n  return sqrt(pow(x1-x2, 2.0) + pow(y1-y2, 2.0));\r\n}\r\n\r\nFPType SimAnneal::interElecPotential(const FPType &r)\r\n{\r\n  return constants::Q0 * sim_params.Kc * exp(-r/(sim_params.debye_length*1e-9)) / r;\r\n}\r\n\r\nFPType SimAnneal::hopEnergyDelta(ublas::vector<int> n_in, const int &from_ind, \r\n    const int &to_ind)\r\n{\r\n  // TODO make an efficient implementation with energy delta implementation\r\n  FPType orig_energy = systemEnergy(n_in);\r\n  int from_state = n_in[from_ind];\r\n  n_in[from_ind] = n_in[to_ind];\r\n  n_in[to_ind] = from_state;\r\n  return systemEnergy(n_in) - orig_energy;\r\n}\r\n\r\n\r\n\r\n// SimAnnealThread Implementation\r\n\r\nSimAnnealThread::SimAnnealThread(const int t_thread_id, const std::uint64_t seed)\r\n  : thread_id(t_thread_id), gener(seed), dis01(0,1)\r\n{\r\n  muzm = sparams->mu;\r\n  mupz = sparams->mu - constants::eta;\r\n}\r\n\r\nvoid SimAnnealThread::run()\r\n{\r\n  // initialize variables & perform pre-calculation\r\n  kT = sparams->T_init*constants::Kb;\r\n  v_freeze = 0.;\r\n  t = 0;\r\n  t_freeze = 0;\r\n  t_phys_validity_check = 0;\r\n  pop_schedule_phase = PopulationUpdateMode;\r\n\r\n  // resize vectors\r\n  n.resize(sparams->n_dbs);\r\n  v_local.resize(sparams->n_dbs);\r\n  db_charges.resize(sparams->result_queue_size);\r\n  config_energies.resize(sparams->result_queue_size);\r\n\r\n  // SIM ANNEAL\r\n  anneal();\r\n}\r\n\r\nvoid SimAnnealThread::anneal()\r\n{\r\n  typedef ublas::vector<int> OccListType;\r\n\r\n  // Vars\r\n  ublas::vector<int> dn(sparams->n_dbs);  // change of occupation for population update\r\n  OccListType dbm_occ(sparams->n_dbs);                    // indices of DB- sites in n\r\n  OccListType db0_occ(sparams->n_dbs);                    // indices of DB0 sites in n\r\n  OccListType dbp_occ(sparams->n_dbs);                    // indices of DB+ sites in n\r\n  OccListType::iterator from_occ, to_occ;\r\n  int dbm_occ_count=0, db0_occ_count=0, dbp_occ_count=0;\r\n  int hop_attempts, max_hop_attempts;\r\n  int from_ind, to_ind;               // hopping from n[from_ind] to n[to_ind]\r\n  FPType hop_E_del;\r\n  bool pop_changed;\r\n\r\n  auto rand_charged_db_ind = [this, &dbm_occ, &dbp_occ, &dbm_occ_count,\r\n                              &dbp_occ_count]\r\n                                (OccListType::iterator &occ_it) mutable -> int\r\n  {\r\n    if (dbm_occ_count == 0 && dbp_occ_count == 0)\r\n      return -1;\r\n    int r_ind = randInt(0, dbm_occ_count + dbp_occ_count - 1);\r\n    occ_it = (r_ind < dbm_occ_count) ? dbm_occ.begin() + r_ind\r\n                                        : dbp_occ.begin() + (r_ind - dbm_occ_count);\r\n    return *occ_it;\r\n  };\r\n\r\n  auto rand_neutral_db_ind = [this, &db0_occ, &db0_occ_count]\r\n                                (OccListType::iterator &occ_it) mutable -> int\r\n  {\r\n    if (db0_occ_count == 0)\r\n      return -1;\r\n    int r_ind = randInt(0, db0_occ_count - 1);\r\n    occ_it = db0_occ.begin() + r_ind;\r\n    return *occ_it;\r\n  };\r\n\r\n  E_sys = systemEnergy();\r\n  v_local = - sparams->v_ext - ublas::prod(sparams->v_ij, n);\r\n\r\n  Logger log(saglobal::log_level);\r\n\r\n  // Run simulated annealing for predetermined time steps\r\n  while(t < sparams->anneal_cycles) {\r\n    //log.debug() << \"Cycle \" << t << \", kT=\" << kT << \", v_freeze=\" << v_freeze << std::endl;\r\n\r\n    // Random population change, pop_changed is set to true if anything changes\r\n    //log.debug() << \"Before popgen: n=\" << n << std::endl;\r\n    genPopDelta(dn, pop_changed);\r\n    if (pop_changed) {\r\n      n += dn;\r\n      E_sys += -1 * ublas::inner_prod(v_local, dn)\r\n        + 0.5 * ublas::inner_prod(dn, ublas::prod(sparams->v_ij, dn));\r\n      v_local -= ublas::prod(sparams->v_ij, dn);\r\n\r\n      // Occupation lists update\r\n      int dbm_ind=0, db0_ind=0, dbp_ind=0;\r\n      for (int db_ind=0; db_ind<sparams->n_dbs; db_ind++) {\r\n        if (n[db_ind]==-1) {\r\n          dbm_occ[dbm_ind++] = db_ind;\r\n        } else if (n[db_ind]==0) {\r\n          db0_occ[db0_ind++] = db_ind;\r\n        } else {\r\n          dbp_occ[dbp_ind++] = db_ind;\r\n        }\r\n        dbm_occ_count = dbm_ind;\r\n        db0_occ_count = db0_ind;\r\n        dbp_occ_count = dbp_ind;\r\n      }\r\n    }\r\n\r\n    // Hopping - randomly hop electrons from higher occupancy sites to lower\r\n    // occupancy sites\r\n    hop_attempts = 0;\r\n    max_hop_attempts = 0;\r\n    if (dbm_occ_count + dbp_occ_count < sparams->n_dbs\r\n        && db0_occ_count < sparams->n_dbs) {\r\n      max_hop_attempts = std::max(dbm_occ_count+dbp_occ_count, db0_occ_count);\r\n      max_hop_attempts *= sparams->hop_attempt_factor;\r\n    }\r\n\r\n    while (hop_attempts < max_hop_attempts) {\r\n      from_ind = rand_charged_db_ind(from_occ);\r\n      to_ind = rand_neutral_db_ind(to_occ);\r\n      if (from_ind == -1 || to_ind == -1) {\r\n        std::cerr << \"Invalid hop index, this shouldn't happen.\" << std::endl;\r\n        throw;\r\n      }\r\n      hop_E_del = hopEnergyDelta(from_ind, to_ind);\r\n      if (acceptHop(hop_E_del)) {\r\n        performHop(from_ind, to_ind, E_sys, hop_E_del);\r\n        // update occupation indices list\r\n        if (n[from_ind] - n[to_ind] < 2) {\r\n          // hopping from DB- or DB+ to DB0\r\n          int orig_from_ind = *from_occ;\r\n          *from_occ = *to_occ;\r\n          *to_occ = orig_from_ind;\r\n        }\r\n      }\r\n      hop_attempts++;\r\n    }\r\n\r\n    // push back the new arrangement\r\n    db_charges.push_back(ChargeConfigResult(n, \r\n          populationValid(), E_sys));\r\n    config_energies.push_back(E_sys);\r\n\r\n    // keep track of suggested ground state\r\n    if (populationValid()) {\r\n      if (E_sys < suggested_gs.system_energy || suggested_gs.config.empty()) {\r\n        suggested_gs.initialized = true;\r\n        suggested_gs.config = n;\r\n        suggested_gs.system_energy = E_sys;\r\n        suggested_gs.pop_likely_stable = true;\r\n      }\r\n    }\r\n\r\n    //log.debug() << \"db_charges = \" << n << std::endl;\r\n\r\n    // perform time-step if not pre-annealing\r\n    timeStep();\r\n  }\r\n\r\n  log.debug() << \"Final db_charges = \" << n\r\n    << \", delta-based system energy = \" << E_sys\r\n    << \", recalculated system energy=\" << systemEnergy() << std::endl;\r\n\r\n  SimAnneal::storeResults(this, thread_id);\r\n}\r\n\r\nvoid SimAnnealThread::genPopDelta(ublas::vector<int> &dn, bool &changed)\r\n{\r\n  // DB- and DB+ sites can be flipped to DB0, DB0 sites can be flipped to either\r\n  // DB- or DB+ depending on which one is enegetically closer.\r\n  FPType prob;\r\n  FPType x;\r\n  int change_dir;\r\n  changed = false;\r\n  for (unsigned i=0; i<n.size(); i++) {\r\n    if (n[i] == -1) {\r\n      // Probability from DB- to DB0\r\n      x = - (v_local[i] + muzm) + v_freeze;\r\n      change_dir = 1;\r\n    } else if (n[i] == 1) {\r\n      // Probability from DB+ to DB0\r\n      x = v_local[i] + mupz + v_freeze;\r\n      change_dir = -1;\r\n    } else {\r\n      if (fabs(v_local[i] + muzm) < fabs(v_local[i] + mupz)) {\r\n        // Closer to DB(0/-) transition level, probability from DB0 to DB-\r\n        x = v_local[i] + muzm + v_freeze;\r\n        change_dir = -1;\r\n      } else {\r\n        // Closer to DB(+/0) transition level, probability from DB0 to DB+\r\n        x = - (v_local[i] + mupz) + v_freeze;\r\n        change_dir = 1;\r\n      }\r\n    }\r\n    prob = 1. / (1 + exp(x / kT));\r\n\r\n    if (evalProb(prob)) {\r\n      dn[i] = change_dir;\r\n      changed = true;\r\n    } else {\r\n      dn[i] = 0;\r\n    }\r\n  }\r\n}\r\n\r\nvoid SimAnnealThread::performHop(const int &from_ind, const int &to_ind,\r\n    FPType &E_sys, const FPType &E_del)\r\n{\r\n  int dn_i = (n[from_ind]==-1) ? 1 : -1;\r\n  int dn_j = - dn_i;\r\n\r\n  n[from_ind] += dn_i;\r\n  n[to_ind] += dn_j;\r\n\r\n  E_sys += E_del;\r\n  ublas::matrix_column<ublas::matrix<FPType>> v_i (sparams->v_ij, from_ind);\r\n  ublas::matrix_column<ublas::matrix<FPType>> v_j (sparams->v_ij, to_ind);\r\n  v_local -= v_i*dn_i + v_j*dn_j;\r\n}\r\n\r\nvoid SimAnnealThread::timeStep()\r\n{\r\n  Logger log(saglobal::log_level);\r\n\r\n  // always progress annealing schedule\r\n  t++;\r\n\r\n  // if preannealing, stop here\r\n  if (t < sparams->preanneal_cycles)\r\n    return;\r\n\r\n  // decide what to do with v_freeze schedule\r\n  switch (pop_schedule_phase) {\r\n    case PopulationUpdateMode:\r\n    {\r\n      if (t_freeze < sparams->v_freeze_cycles) {\r\n        t_freeze++;\r\n      } else {\r\n        if (!sparams->strategic_v_freeze_reset\r\n            || (sparams->anneal_cycles - t) < sparams->v_freeze_cycles + sparams->phys_validity_check_cycles) {\r\n          // if there aren't enough cycles left for another full v_freeze cycles, then\r\n          // stop playing with t_freeze\r\n          pop_schedule_phase = PopulationUpdateFinished;\r\n        } else {\r\n          // initiate physical validity check for the next phys_validity_check_cycles\r\n          pop_schedule_phase = PhysicalValidityCheckMode;\r\n          t_phys_validity_check = 0;\r\n          phys_valid_count = 0;\r\n          phys_invalid_count = 0;\r\n        }\r\n      }\r\n      break;\r\n    }\r\n    case PhysicalValidityCheckMode:\r\n    {\r\n      if (t_phys_validity_check < sparams->phys_validity_check_cycles) {\r\n        populationValid() ? phys_valid_count++ : phys_invalid_count++;\r\n        t_phys_validity_check++;\r\n      } else if (t_phys_validity_check >= sparams->phys_validity_check_cycles) {\r\n        pop_schedule_phase = PopulationUpdateMode;\r\n        t_freeze = 0;\r\n        if (phys_valid_count < phys_invalid_count) {\r\n          log.debug() << \"Thread \" << thread_id << \": t=\" << t \r\n            << \", charge config is \" << n \r\n            << \" which is physically invalid, resetting v_freeze.\" << std::endl;\r\n\r\n          // reset v_freeze and temperature\r\n          v_freeze = sparams->v_freeze_reset;\r\n          if (sparams->reset_T_during_v_freeze_reset)\r\n            kT = sparams->T_init*constants::Kb;\r\n        }\r\n      }\r\n      break;\r\n    }\r\n    case PopulationUpdateFinished:\r\n      break;\r\n    default:\r\n      std::cerr << \"Invalid PopulationSchedulePhase.\";\r\n      throw;\r\n  }\r\n\r\n  // update parameters according to schedule\r\n  if (sparams->T_schedule == ExponentialSchedule)\r\n    kT = sparams->kT_min + (kT - sparams->kT_min) * sparams->alpha;\r\n  else if (sparams->T_schedule == LinearSchedule)\r\n    kT = std::max(sparams->kT_min, kT - sparams->alpha);\r\n\r\n  // update v_freeze\r\n  if (v_freeze < sparams->v_freeze_threshold)\r\n    v_freeze += sparams->v_freeze_step;\r\n}\r\n\r\nbool SimAnnealThread::acceptHop(const FPType &v_diff)\r\n{\r\n  if (v_diff < 0)\r\n    return true;\r\n\r\n  // some acceptance function, acceptance probability falls off exponentially\r\n  FPType prob = exp(-v_diff/kT);\r\n\r\n  return evalProb(prob);\r\n}\r\n\r\nbool SimAnnealThread::evalProb(const FPType &prob)\r\n{\r\n  return prob >= dis01(gener);\r\n}\r\n\r\nint SimAnnealThread::randInt(const int &min, const int &max)\r\n{\r\n  RandIntDist dis(min,max);\r\n  return dis(gener);\r\n}\r\n\r\nFPType SimAnnealThread::systemEnergy() const\r\n{\r\n  return ublas::inner_prod(n, sparams->v_ext)\r\n    + 0.5 * ublas::inner_prod(n, ublas::prod(sparams->v_ij, n));\r\n}\r\n\r\n/*\r\nFPType SimAnnealThread::totalCoulombPotential(ublas::vector<int> &config) const\r\n{\r\n  return 0.5 * ublas::inner_prod(config, ublas::prod(sparams->v_ij, config));\r\n}\r\n*/\r\n\r\nFPType SimAnnealThread::hopEnergyDelta(const int &i, const int &j)\r\n{\r\n  //return v_local[i] - v_local[j] - sparams->v_ij(i,j);\r\n  int dn_i = (n[i]==-1) ? 1 : -1;\r\n  int dn_j = - dn_i;\r\n  return - v_local[i]*dn_i - v_local[j]*dn_j - sparams->v_ij(i,j);\r\n}\r\n\r\nbool SimAnnealThread::populationValid() const\r\n{\r\n  // Check whether v_local at each site meets population validity constraints\r\n  // Note that v_local components have flipped signs from E_sys\r\n  bool valid;\r\n  const FPType &zero_equiv = constants::POP_STABILITY_ERR;\r\n  for (int i=0; i<sparams->n_dbs; i++) {\r\n    valid = ((n[i] == -1 && v_local[i] + muzm < zero_equiv)   // DB- condition\r\n          || (n[i] == 1  && v_local[i] + mupz > -zero_equiv)  // DB+ condition\r\n          || (n[i] == 0  && v_local[i] + muzm > -zero_equiv\r\n                         && v_local[i] + mupz < zero_equiv));\r\n    if (!valid) {\r\n      return false;\r\n    }\r\n  }\r\n  return true;\r\n}\r\n", "meta": {"hexsha": "b43e47cef4afe3dec0f9c16f6b6913619e7df1e3", "size": 21305, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/simanneal.cc", "max_stars_repo_name": "samuelngsh/simanneal-sidb", "max_stars_repo_head_hexsha": "c146abb40ce5fe503a37ee859cc52f593960238b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simanneal.cc", "max_issues_repo_name": "samuelngsh/simanneal-sidb", "max_issues_repo_head_hexsha": "c146abb40ce5fe503a37ee859cc52f593960238b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simanneal.cc", "max_forks_repo_name": "samuelngsh/simanneal-sidb", "max_forks_repo_head_hexsha": "c146abb40ce5fe503a37ee859cc52f593960238b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-21T02:33:58.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-21T02:33:58.000Z", "avg_line_length": 31.7985074627, "max_line_length": 113, "alphanum_fraction": 0.6083548463, "num_tokens": 6135, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.20382734865890995}}
{"text": "//============================================================================//\n//-------------------- pnt_integrity/AquisitionCheck.hpp -------*- C++ -*-----//\n//============================================================================//\n// BSD 3-Clause License\n//\n// Copyright (C) 2019 Integrated Solutions for Systems, Inc\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 contributors\n// may be used to endorse or promote products derived from this software without\n// 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//  Class defined for the acquisition level checks\n//  Josh Clanton <josh.clanton@is4s.com>\n//  September 30, 2019\n//============================================================================//\n#include \"pnt_integrity/AcquisitionCheck.hpp\"\n#include <Eigen/Dense>\n#include <chrono>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <thread>\n\n// #include \"gnsscommon/GNSSConstants.hpp\"\n\nusing namespace if_data_utils;\n\nnamespace pnt_integrity\n{\n//==============================================================================\n//---------------------------- acquisitionSetup() ------------------------------\n//==============================================================================\nvoid AcquisitionCheck::acquisitionSetup()\n{\n  samplesPerIntPeriod_ = samplingFrequency_ * integrationPeriod_;\n  samplesPerCode_ =\n    std::round(samplingFrequency_ / (codeFrequencyBasis_ / codeLength_));\n\n  generateCaCodeMap();\n  generateFreqBins();\n\n  std::stringstream setupMsg;\n  setupMsg << \"AcquisitionCheck::acquisitionSetup: \"\n           << \"samps per int period = \" << samplesPerIntPeriod_\n           << \", num freq bins = \" << freqBins_.size();\n  logMsg_(setupMsg.str(), logutils::LogLevel::Warn);\n\n  logMsg_(\"AcquisitionCheck::acquisitionSetup(): Code replicas initialized\",\n          logutils::LogLevel::Info);\n\n  replicasInitialized_ = true;\n}\n\n//==============================================================================\n//---------------------------- generateFreqBins() ------------------------------\n//==============================================================================\nvoid AcquisitionCheck::generateFreqBins()\n{\n  // numFreqBins_ = std::round(acquisitionSearchBand_ * 2) + 1;\n  for (float curFreq = (intermediateFrequency_ - acquisitionSearchBand_);\n       curFreq <= (intermediateFrequency_ + acquisitionSearchBand_);\n       curFreq += searchStepSize_)\n  {\n    freqBins_.push_back(curFreq);\n  }\n}\n\n//==============================================================================\n//---------------------------- generateCaCodeMap()------------------------------\n//==============================================================================\nvoid AcquisitionCheck::generateCaCodeMap()\n{\n  prnList_.clear();\n  for (int ii = 1; ii <= 32; ++ii)\n  {\n    prnList_.push_back(ii);\n\n    caCodeMap_.insert(CodeMapEntry(ii,\n                                   upsampleCaCode(generateCaCode(ii, 0),\n                                                  samplingFrequency_,\n                                                  codeFrequencyBasis_,\n                                                  samplesPerIntPeriod_)));\n\n    std::vector<std::complex<float> > caCodeFD;\n    fftEngine_.fwd(caCodeFD, caCodeMap_[ii]);\n\n    // convert to Eigen VectorXcf and take conjugate\n    Eigen::Map<Eigen::VectorXcf> caFD_map(&caCodeFD[0], caCodeFD.size());\n    caCodeMapFD_.insert(CodeFreqMapEntry(ii, caFD_map.conjugate()));\n  }\n}\n\n//==============================================================================\n//------------------------------ generateCacode() ------------------------------\n//==============================================================================\nstd::vector<float> AcquisitionCheck::generateCaCode(signed int   _prn,\n                                                    unsigned int _chip_shift)\n{\n  // initialize vector to hold result\n  std::vector<float> ca_code;\n\n  unsigned int G1[1023];\n  unsigned int G2[1023];\n  unsigned int G1_register[10], G2_register[10];\n  unsigned int feedback1, feedback2;\n  unsigned int lcv, lcv2;\n  unsigned int delay;\n  signed int   prn = _prn - 1;  // Move the PRN code to fit an array indices\n\n  // G2 Delays as defined in IS-GPS-200E\n  signed int delays[32] = {5,   6,   7,   8,   17,  18,  139, 140,\n                           141, 251, 252, 254, 255, 256, 257, 258,\n                           469, 470, 471, 472, 473, 474, 509, 512,\n                           513, 514, 515, 516, 859, 860, 861, 862};\n  // PRN sequences 33 through 37 are reserved for other uses (e.g. ground\n  // transmitters)\n\n  // A simple error check\n  if ((prn < 0) || (prn > 32))\n    return ca_code;\n\n  for (lcv = 0; lcv < 10; lcv++)\n  {\n    G1_register[lcv] = 1;\n    G2_register[lcv] = 1;\n  }\n\n  // Generate G1 & G2 Register\n  for (lcv = 0; lcv < 1023; lcv++)\n  {\n    G1[lcv] = G1_register[0];\n    G2[lcv] = G2_register[0];\n\n    feedback1 = G1_register[7] ^ G1_register[0];\n    feedback2 = (G2_register[8] + G2_register[7] + G2_register[4] +\n                 G2_register[2] + G2_register[1] + G2_register[0]) &\n                0x1;\n\n    for (lcv2 = 0; lcv2 < 9; lcv2++)\n    {\n      G1_register[lcv2] = G1_register[lcv2 + 1];\n      G2_register[lcv2] = G2_register[lcv2 + 1];\n    }\n\n    G1_register[9] = feedback1;\n    G2_register[9] = feedback2;\n  }\n\n  // Set the delay\n  delay = 1023 - delays[prn];\n  delay += _chip_shift;\n  delay %= 1023;\n  // Generate PRN from G1 and G2 Registers\n  for (lcv = 0; lcv < 1023; lcv++)\n  {\n    ca_code.push_back(G1[(lcv + _chip_shift) % 1023] ^ G2[delay]);\n    if (ca_code[lcv] == 0.0)  // javi\n    {\n      ca_code[lcv] = -1.0;\n    }\n    delay++;\n    delay %= 1023;\n  }\n\n  return ca_code;\n}\n\n//==============================================================================\n//------------------------------ upsampleCaCode() ------------------------------\n//==============================================================================\nstd::vector<float> AcquisitionCheck::upsampleCaCode(std::vector<float> codes,\n                                                    double sampleFrequency,\n                                                    double codeFrequency,\n                                                    size_t samples,\n                                                    double chip_shift)\n{\n  double codePhaseStep    = codeFrequency / sampleFrequency;\n  int    samples_per_code = sampleFrequency / 1000;  // code is 1ms\n\n  // if samples argument is set to 0, generate 1 ms of samples\n  if (samples == 0)\n    samples = samples_per_code;\n\n  std::vector<float> digitized;\n\n  // generate array that counts from 0 to 1023 and\n  // has the same # of values as 1 period of the\n  // sampled CA code\n\n  int ca_idx = 0;\n  for (size_t idx = 0; idx < samples; idx++)\n  {\n    // calculate C/A code index\n    // add 1 to index to make it exactly match matlab code\n    ca_idx = ceil((codePhaseStep * (idx + 1)) + chip_shift) - 1;\n    // ca_idx = ((codePhaseStep * (idx)) + chip_shift) ;\n\n    // wrap index into range of codes vector\n    ca_idx = (ca_idx + 1023) % 1023;\n\n    digitized.push_back(codes[ca_idx]);\n  }\n\n  return digitized;\n}\n\n//==============================================================================\n//------------------------------ generateCarrier() -----------------------------\n//==============================================================================\ndouble AcquisitionCheck::generateCarrier(double           initPhase,\n                                         double           phaseStep,\n                                         size_t           length,\n                                         Eigen::VectorXf& sine,\n                                         Eigen::VectorXf& cosine)\n{\n  Eigen::VectorXf CarrArg(length);\n  // TOOD: remove this if statement and test\n  if (length == 1)\n  {\n    CarrArg(0) = initPhase + phaseStep;\n  }\n  else\n  {\n    CarrArg = Eigen::VectorXf::LinSpaced(\n      length, initPhase + phaseStep, initPhase + phaseStep * (length));\n  }\n\n  sine   = CarrArg.array().sin();\n  cosine = CarrArg.array().cos();\n\n  return CarrArg(length - 1);\n}\n\n//==============================================================================\n//--------------------------------- sinFast() ----------------------------------\n//==============================================================================\nfloat AcquisitionCheck::sinFast(float x)\n{\n  x = fmod(x + M_PI, M_PI * 2) - M_PI;  // restrict x so that -pi<x<pi\n\n  if (x < 0)\n  {\n    return 1.27323954f * x + 0.405284735f * x * x;\n  }\n  else\n  {\n    return 1.27323954f * x - 0.405284735f * x * x;\n  }\n}\n\n//==============================================================================\n//------------------------- generateAcquisitionPlane() -------------------------\n//==============================================================================\nbool AcquisitionCheck::generateAcquisitionPlane(\n  const Eigen::ArrayXcf& signalSamples)\n{\n  auto start = std::chrono::high_resolution_clock::now();\n\n  // make sure CA tables have been initialized and settings set\n  // before attempting acquisition\n  if (!replicasInitialized_)\n  {\n    logMsg_(\"CA code replicas must be initialized before acquiring.\",\n            logutils::LogLevel::Error);\n    return false;\n  }\n\n  // TODO: check that samples size and ca replica size matches\n  size_t numSamples = signalSamples.size();\n\n  // generate time vector for carrier replica\n  Eigen::VectorXcf phasePoints(numSamples);\n  for (size_t ii = 0; ii < numSamples; ii++)\n  {\n    phasePoints[ii] = twoGpsPi_ * (double)ii / samplingFrequency_;\n  }\n\n  // define PRN to search for\n  std::vector<std::thread> fftThreads;\n\n  Eigen::ArrayXXf results(freqBins_.size(), numSamples);\n\n  for (PrnList::iterator prnIt = prnList_.begin(); prnIt != prnList_.end();\n       ++prnIt)\n  {\n    // make sure PRN is between 1 and 32\n    if ((*prnIt < 1) || (*prnIt > 32))\n    {\n      logMsg_(\"PRN must be between 1 and 32.\", logutils::LogLevel::Error);\n      return false;\n    }\n    // add the prn entry to the results map\n    correlationResultsMap_.insert(\n      std::pair<int, Eigen::ArrayXXf>(*prnIt, results));\n\n    fftThreads.push_back(\n      std::thread(std::bind(&AcquisitionCheck::acquisitionCorrelation,\n                            this,\n                            *prnIt,\n                            signalSamples,\n                            phasePoints)));\n  }\n\n  // close the FFT worker threads\n  // size_t threadCount = 1;\n  for (auto threadIt = fftThreads.begin(); threadIt != fftThreads.end();\n       ++threadIt)\n  {\n    (*threadIt).join();\n  }\n\n  // publish the correlation data\n\n  auto finish = std::chrono::high_resolution_clock::now();\n  std::chrono::duration<double> elapsed = finish - start;\n  std::stringstream             timeMsg;\n  timeMsg << \"Elapsed time: \" << elapsed.count() << \" s\";\n  logMsg_(timeMsg.str(), logutils::LogLevel::Debug);\n\n  if (publishAquisitionData_)\n  {\n    publishAquisitionData_(correlationResultsMap_);\n  }\n  if (publishPeakData_)\n  {\n    publishPeakData_(lastProcessTime_, peakResultsMap_);\n  }\n\n  return true;\n}\n\n//==============================================================================\n//-------------------------- acquisitionCorrelation ----------------------------\n//==============================================================================\nvoid AcquisitionCheck::acquisitionCorrelation(\n  const int&              prn,\n  const Eigen::ArrayXcf&  signalSamples,\n  const Eigen::VectorXcf& phasePoints)\n{\n  // initialize fft engine\n  Eigen::FFT<float> fftEngine;\n\n  size_t numSamples = signalSamples.size();\n\n  std::vector<std::complex<float> > inputSignalDemod(numSamples);\n  Eigen::Map<Eigen::ArrayXcf>       inputSignalDemodMap(&inputSignalDemod[0],\n                                                  inputSignalDemod.size());\n\n  std::vector<std::complex<float> > signalFft(numSamples);\n  Eigen::Map<Eigen::ArrayXcf> signalFftMap(&signalFft[0], signalFft.size());\n\n  std::vector<std::complex<float> > corrFreqDom(numSamples);\n  Eigen::Map<Eigen::ArrayXcf>       corrFreqDomMap(&corrFreqDom[0],\n                                             corrFreqDom.size());\n\n  std::vector<std::complex<float> > corrTimeDom(numSamples);\n  Eigen::Map<Eigen::ArrayXcf>       corrTimeDomMap(&corrTimeDom[0],\n                                             corrTimeDom.size());\n\n  // initialize arrays for peak\n  auto samplesPerCodeChip =\n    std::round(samplingFrequency_ / codeFrequencyBasis_);\n\n  // set variables to save peak and it's location\n  float                  peakValue      = 0.0;\n  size_t                 peakFreqBinIdx = 0;\n  Eigen::VectorXf::Index peakCodeIdx    = 0;\n\n  // initialize array to hold results of acqusition tests\n  size_t curBin = 0;\n  for (auto freqIt = freqBins_.begin(); freqIt != freqBins_.end(); ++freqIt)\n  {\n    inputSignalDemodMap = (intermediateFrequency_ + *freqIt) * phasePoints *\n                          std::complex<float>(0, 1);\n\n    inputSignalDemodMap = inputSignalDemodMap.exp() * signalSamples;\n    fftEngine.fwd(signalFft, inputSignalDemod);\n\n    // multiply the complex conjugate of the CA replica with the demodulated\n    // signal to get correlation in the frequency domain\n    Eigen::Map<Eigen::ArrayXcf> caFftConj(&caCodeMapFD_[prn][0],\n                                          caCodeMapFD_[prn].size());\n\n    corrFreqDomMap = caFftConj * signalFftMap;\n\n    fftEngine.inv(corrTimeDom, corrFreqDom);\n\n    auto binResult                          = corrTimeDomMap.abs2();\n    correlationResultsMap_[prn].row(curBin) = binResult;\n    // resultsPtr->row(curBin)                 = binResult;\n\n    // find the peak in this bin and the corresponding code idx\n    Eigen::VectorXf::Index peakInBinCodeIdx;\n    auto                   peakInBin = binResult.maxCoeff(&peakInBinCodeIdx);\n    // if the bin peak is bigger than the previous, save it\n    if (peakInBin > peakValue)\n    {\n      peakValue      = peakInBin;\n      peakFreqBinIdx = curBin;\n      peakCodeIdx    = peakInBinCodeIdx;\n    }\n\n    curBin++;\n  }\n  // define the exclusion zone around the peak\n  auto excludeRangeLowIdx  = peakCodeIdx - samplesPerCodeChip;\n  auto excludeRangeHighIdx = peakCodeIdx + samplesPerCodeChip;\n\n  // pull out the frequency bin that has the max peak\n  auto freqBinWithPeak = correlationResultsMap_[prn].row(peakFreqBinIdx);\n\n  float secondPeakValue = 0.0;\n  // auto secondPeakCodeIdx = 0;\n  // find the second peak in this freqBin w.r.t. the exculsion zone\n  for (auto codeIdx = 0; codeIdx < freqBinWithPeak.size(); codeIdx++)\n  {\n    // test for max everywehre but exclusion zone\n    if ((codeIdx <= excludeRangeLowIdx) or (codeIdx >= excludeRangeHighIdx))\n    {\n      if (freqBinWithPeak(codeIdx) > secondPeakValue)\n      {\n        // secondPeakCodeIdx = codeIdx;\n        secondPeakValue = freqBinWithPeak(codeIdx);\n      }\n    }\n  }\n\n  peakResultsMap_[prn] = std::pair<double, double>(peakValue, secondPeakValue);\n}\n\n//==============================================================================\n//-------------------------------- runCheck ------------------------------------\n//==============================================================================\nbool AcquisitionCheck::runCheck()\n{\n  setPrnAssuranceLevels();\n  calculateAssuranceLevel(lastProcessTime_);\n  return true;\n}\n\n//==============================================================================\n//-------------------------- setPrnAssuranceLevels ----------------------------\n//==============================================================================\nvoid AcquisitionCheck::setPrnAssuranceLevels()\n{\n  std::map<int, double> ratioMap;\n  // look at the peak results map and make determinations bas\n  for (auto prnIt = peakResultsMap_.begin(); prnIt != peakResultsMap_.end();\n       ++prnIt)\n  {\n    double peakRatio       = (prnIt->second.first / prnIt->second.second);\n    ratioMap[prnIt->first] = peakRatio;\n\n    if (prnIt->second.first > highPowerThreshold_)\n    {\n      // power level is suspect, check ratio of 1st and 2nd peak\n\n      if (peakRatio > peakRatioThreshold_)\n      {\n        prnAssuranceLevels_[prnIt->first] = data::AssuranceLevel::Unassured;\n      }\n      else\n      {\n        prnAssuranceLevels_[prnIt->first] = data::AssuranceLevel::Inconsistent;\n      }\n    }\n    // check the first peak against the threshold\n    else if (prnIt->second.first > acquisitionThreshold_)\n    {\n      prnAssuranceLevels_[prnIt->first] = data::AssuranceLevel::Assured;\n    }\n    // PRN is not visible\n    else\n    {\n      prnAssuranceLevels_[prnIt->first] = data::AssuranceLevel::Unavailable;\n    }\n  }\n\n  if (publishDiagnostics_)\n  {\n    diagnostics_.ratioMap = ratioMap;\n  }\n}\n\n//==============================================================================\n//---------------------------- setAssuranceLevel -------------------------------\n//==============================================================================\nvoid AcquisitionCheck::calculateAssuranceLevel(const double& checkTime)\n{\n  // go throuh the prn assurance map and determine how many have been flagged\n  // to set the overall level\n  int assuredCount      = 0;\n  int unavailableCount  = 0;\n  int unassuredCount    = 0;\n  int inconsistentCount = 0;\n  for (auto it = prnAssuranceLevels_.begin(); it != prnAssuranceLevels_.end();\n       ++it)\n  {\n    if (it->second == data::AssuranceLevel::Unassured)\n    {\n      unassuredCount++;\n    }\n    else if (it->second == data::AssuranceLevel::Inconsistent)\n    {\n      inconsistentCount++;\n    }\n    else if (it->second == data::AssuranceLevel::Assured)\n    {\n      assuredCount++;\n    }\n    else if (it->second == data::AssuranceLevel::Unavailable)\n    {\n      unavailableCount++;\n    }\n\n    if (unassuredCount >= assuranceUnassuredThresh_)\n    {\n      changeAssuranceLevel(checkTime, data::AssuranceLevel::Unassured);\n    }\n    else if (inconsistentCount >= assuranceInconsistentThresh_)\n    {\n      changeAssuranceLevel(checkTime, data::AssuranceLevel::Inconsistent);\n    }\n    else if (assuredCount >= 4)\n    {\n      changeAssuranceLevel(checkTime, data::AssuranceLevel::Assured);\n    }\n    else\n    {\n      changeAssuranceLevel(checkTime, data::AssuranceLevel::Unavailable);\n    }\n\n  }  // end for loop\n\n  if (publishDiagnostics_)\n  {\n    diagnostics_.highPowerThresh    = highPowerThreshold_;\n    diagnostics_.peakRatioThresh    = peakRatioThreshold_;\n    diagnostics_.acquisitionThresh  = acquisitionThreshold_;\n    diagnostics_.inconsistentThresh = assuranceInconsistentThresh_;\n    diagnostics_.unassuredThresh    = assuranceUnassuredThresh_;\n    diagnostics_.unassuredCount     = unassuredCount;\n    diagnostics_.inconsistentCount  = inconsistentCount;\n\n    publishDiagnostics_(lastProcessTime_, diagnostics_);\n  }\n  // std::stringstream levelMsg;\n  // levelMsg << std::endl;\n  // levelMsg << \"Unusable : \" << unassuredCount << \" prns \" << std::endl;\n  // levelMsg << \"Unknown : \" << inconsistentCount << \" prns \" << std::endl;\n  // levelMsg << \"Assured : \" << assuredCount << \" prns \" << std::endl;\n  // levelMsg << \"Unavailable : \" << unavailableCount << \" prns \";\n  // logMsg_(levelMsg.str(), \"info\");\n\n  // std::stringstream msg;\n  // msg << \"AcquisitionCheck::calculateAssuranceLevel() : Calculated level : \"\n  //     << (int)assuranceLevel_;\n  // logMsg_(msg.str(), \"info\");\n}\n\n}  // namespace pnt_integrity\n", "meta": {"hexsha": "44d757deefdfcadb907f5af8b92f6cdd1c621bae", "size": 20694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pnt_integrity/pnt_integrity/src/AcquisitionCheck.cpp", "max_stars_repo_name": "yxw027/PNT-Integrity", "max_stars_repo_head_hexsha": "3549855a8ab4c5937d109b60ee70a6a5a9ca2d6a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-17T13:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-17T13:16:46.000Z", "max_issues_repo_path": "pnt_integrity/pnt_integrity/src/AcquisitionCheck.cpp", "max_issues_repo_name": "yxw027/PNT-Integrity", "max_issues_repo_head_hexsha": "3549855a8ab4c5937d109b60ee70a6a5a9ca2d6a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pnt_integrity/pnt_integrity/src/AcquisitionCheck.cpp", "max_forks_repo_name": "yxw027/PNT-Integrity", "max_forks_repo_head_hexsha": "3549855a8ab4c5937d109b60ee70a6a5a9ca2d6a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3743589744, "max_line_length": 80, "alphanum_fraction": 0.5468251667, "num_tokens": 4776, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832354982645, "lm_q2_score": 0.3775406687981454, "lm_q1q2_score": 0.2034880912010031}}
{"text": "/* ----------------------------------------------------------------------\n *\n *                    *** Smooth Mach Dynamics ***\n *\n * This file is part of the USER-SMD package for LAMMPS.\n * Copyright (2014) Georg C. Ganzenmueller, georg.ganzenmueller@emi.fhg.de\n * Fraunhofer Ernst-Mach Institute for High-Speed Dynamics, EMI,\n * Eckerstrasse 4, D-79104 Freiburg i.Br, Germany.\n *\n * ----------------------------------------------------------------------- */\n\n/* ----------------------------------------------------------------------\n LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator\n http://lammps.sandia.gov, Sandia National Laboratories\n Steve Plimpton, sjplimp@sandia.gov\n\n Copyright (2003) Sandia Corporation.  Under the terms of Contract\n DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains\n certain rights in this software.  This software is distributed under\n the GNU General Public License.\n\n See the README file in the top-level LAMMPS directory.\n ------------------------------------------------------------------------- */\n\n/* ----------------------------------------------------------------------\n   Contributing author: Mike Parks (SNL)\n------------------------------------------------------------------------- */\n\n#include <cmath>\n#include <cfloat>\n#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <iostream>\n#include <Eigen/Eigen>\n#include \"pair_smd_triangulated_surface.h\"\n#include \"atom.h\"\n#include \"domain.h\"\n#include \"force.h\"\n#include \"update.h\"\n#include \"modify.h\"\n#include \"fix.h\"\n#include \"comm.h\"\n#include \"neighbor.h\"\n#include \"neigh_list.h\"\n#include \"neigh_request.h\"\n#include \"memory.h\"\n#include \"error.h\"\n\nusing namespace std;\nusing namespace LAMMPS_NS;\nusing namespace Eigen;\n\n#define SQRT2 1.414213562e0\n\n/* ---------------------------------------------------------------------- */\n\nPairTriSurf::PairTriSurf(LAMMPS *lmp) :\n                Pair(lmp) {\n\n        onerad_dynamic = onerad_frozen = maxrad_dynamic = maxrad_frozen = NULL;\n        bulkmodulus = NULL;\n        kn = NULL;\n        scale = 1.0;\n}\n\n/* ---------------------------------------------------------------------- */\n\nPairTriSurf::~PairTriSurf() {\n\n        if (allocated) {\n                memory->destroy(setflag);\n                memory->destroy(cutsq);\n                memory->destroy(bulkmodulus);\n                memory->destroy(kn);\n\n                delete[] onerad_dynamic;\n                delete[] onerad_frozen;\n                delete[] maxrad_dynamic;\n                delete[] maxrad_frozen;\n        }\n}\n\n/* ---------------------------------------------------------------------- */\n\nvoid PairTriSurf::compute(int eflag, int vflag) {\n        int i, j, ii, jj, inum, jnum, itype, jtype;\n        double rsq, r, evdwl, fpair;\n        int *ilist, *jlist, *numneigh, **firstneigh;\n        double rcut, r_geom, delta, r_tri, r_particle, touch_distance, dt_crit;\n        int tri, particle;\n        Vector3d normal, x1, x2, x3, x4, x13, x23, x43, w, cp, x4cp, vnew, v_old;\n        ;\n        Vector3d xi, x_center, dx;\n        Matrix2d C;\n        Vector2d w2d, rhs;\n\n        evdwl = 0.0;\n        ev_init(eflag, vflag);\n\n        tagint *mol = atom->molecule;\n        double **f = atom->f;\n        double **smd_data_9 = atom->smd_data_9;\n        double **x = atom->x;\n        double **x0 = atom->x0;\n        double **v = atom->v;\n        double *rmass = atom->rmass;\n        int *type = atom->type;\n        int nlocal = atom->nlocal;\n        double *radius = atom->contact_radius;\n        double rcutSq;\n        Vector3d offset;\n\n        int newton_pair = force->newton_pair;\n        int periodic = (domain->xperiodic || domain->yperiodic || domain->zperiodic);\n\n        inum = list->inum;\n        ilist = list->ilist;\n        numneigh = list->numneigh;\n        firstneigh = list->firstneigh;\n\n        int max_neighs = 0;\n        stable_time_increment = 1.0e22;\n\n        // loop over neighbors of my atoms using a half neighbor list\n        for (ii = 0; ii < inum; ii++) {\n                i = ilist[ii];\n                itype = type[i];\n                jlist = firstneigh[i];\n                jnum = numneigh[i];\n                max_neighs = MAX(max_neighs, jnum);\n\n                for (jj = 0; jj < jnum; jj++) {\n                        j = jlist[jj];\n\n                        j &= NEIGHMASK;\n\n                        jtype = type[j];\n\n                        /*\n                         * decide which one of i, j is triangle and which is particle\n                         */\n                        if ((mol[i] < 65535) && (mol[j] >= 65535)) {\n                                particle = i;\n                                tri = j;\n                        } else if ((mol[j] < 65535) && (mol[i] >= 65535)) {\n                                particle = j;\n                                tri = i;\n                        } else {\n                                error->one(FLERR, \"unknown case\");\n                        }\n\n                        //x_center << x[tri][0], x[tri][1], x[tri][2]; // center of triangle\n                        x_center(0) = x[tri][0];\n                        x_center(1) = x[tri][1];\n                        x_center(2) = x[tri][2];\n                        //x4 << x[particle][0], x[particle][1], x[particle][2];\n                        x4(0) = x[particle][0];\n                        x4(1) = x[particle][1];\n                        x4(2) = x[particle][2];\n                        dx = x_center - x4; //\n                        if (periodic) {\n                                domain->minimum_image(dx(0), dx(1), dx(2));\n                        }\n                        rsq = dx.squaredNorm();\n\n                        r_tri = scale * radius[tri];\n                        r_particle = scale * radius[particle];\n                        rcut = r_tri + r_particle;\n                        rcutSq = rcut * rcut;\n\n                        //printf(\"type i=%d, type j=%d, r=%f, ri=%f, rj=%f\\n\", itype, jtype, sqrt(rsq), ri, rj);\n\n                        if (rsq < rcutSq) {\n\n                                /*\n                                 * gather triangle information\n                                 */\n                                normal(0) = x0[tri][0];\n                                normal(1) = x0[tri][1];\n                                normal(2) = x0[tri][2];\n\n                                /*\n                                 * distance check: is particle closer than its radius to the triangle plane?\n                                 */\n                                if (fabs(dx.dot(normal)) < radius[particle]) {\n                                        /*\n                                         * get other two triangle vertices\n                                         */\n                                        x1(0) = smd_data_9[tri][0];\n                                        x1(1) = smd_data_9[tri][1];\n                                        x1(2) = smd_data_9[tri][2];\n                                        x2(0) = smd_data_9[tri][3];\n                                        x2(1) = smd_data_9[tri][4];\n                                        x2(2) = smd_data_9[tri][5];\n                                        x3(0) = smd_data_9[tri][6];\n                                        x3(1) = smd_data_9[tri][7];\n                                        x3(2) = smd_data_9[tri][8];\n\n                                        PointTriangleDistance(x4, x1, x2, x3, cp, r);\n\n                                        /*\n                                         * distance to closest point\n                                         */\n                                        x4cp = x4 - cp;\n\n                                        /*\n                                         * flip normal to point in direction of x4cp\n                                         */\n\n                                        if (x4cp.dot(normal) < 0.0) {\n                                                normal *= -1.0;\n                                        }\n\n                                        /*\n                                         * penalty force pushes particle away from triangle\n                                         */\n                                        if (r < 1.0 * radius[particle]) {\n\n                                                delta = radius[particle] - r; // overlap distance\n                                                r_geom = radius[particle];\n                                                fpair = 1.066666667e0 * bulkmodulus[itype][jtype] * delta * sqrt(delta * r_geom);\n                                                dt_crit = 3.14 * sqrt(rmass[particle] / (fpair / delta));\n                                                stable_time_increment = MIN(stable_time_increment, dt_crit);\n\n                                                evdwl = r * fpair * 0.4e0 * delta; // GCG 25 April: this expression conserves total energy\n\n                                                fpair /= (r + 1.0e-2 * radius[particle]); // divide by r + softening and multiply with non-normalized distance vector\n\n                                                if (particle < nlocal) {\n                                                        f[particle][0] += x4cp(0) * fpair;\n                                                        f[particle][1] += x4cp(1) * fpair;\n                                                        f[particle][2] += x4cp(2) * fpair;\n                                                }\n\n                                                if (tri < nlocal) {\n                                                        f[tri][0] -= x4cp(0) * fpair;\n                                                        f[tri][1] -= x4cp(1) * fpair;\n                                                        f[tri][2] -= x4cp(2) * fpair;\n                                                }\n\n                                                if (evflag) {\n                                                        ev_tally(i, j, nlocal, newton_pair, evdwl, 0.0, fpair, x4cp(0), x4cp(1), x4cp(2));\n                                                }\n\n                                        }\n\n                                        /*\n                                         * if particle comes too close to triangle, reflect its velocity and explicitly move it away\n                                         */\n\n                                        touch_distance = 1.0 * radius[particle];\n                                        if (r < touch_distance) {\n\n                                                /*\n                                                 * reflect velocity if it points toward triangle\n                                                 */\n\n                                                normal = x4cp / r;\n\n                                                //v_old << v[particle][0], v[particle][1], v[particle][2];\n                                                v_old(0) = v[particle][0];\n                                                v_old(1) = v[particle][1];\n                                                v_old(2) = v[particle][2];\n                                                if (v_old.dot(normal) < 0.0) {\n                                                        //printf(\"flipping velocity\\n\");\n                                                        vnew = 1.0 * (-2.0 * v_old.dot(normal) * normal + v_old);\n                                                        v[particle][0] = vnew(0);\n                                                        v[particle][1] = vnew(1);\n                                                        v[particle][2] = vnew(2);\n                                                }\n\n                                                //printf(\"moving particle on top of triangle\\n\");\n                                                x[particle][0] = cp(0) + touch_distance * normal(0);\n                                                x[particle][1] = cp(1) + touch_distance * normal(1);\n                                                x[particle][2] = cp(2) + touch_distance * normal(2);\n                                        }\n\n                                }\n                        }\n                }\n        }\n\n//      int max_neighs_all = 0;\n//      MPI_Allreduce(&max_neighs, &max_neighs_all, 1, MPI_INT, MPI_MAX, world);\n//      if (comm->me == 0) {\n//              printf(\"max. neighs in tri pair is %d\\n\", max_neighs_all);\n//      }\n//\n//              double stable_time_increment_all = 0.0;\n//              MPI_Allreduce(&stable_time_increment, &stable_time_increment_all, 1, MPI_DOUBLE, MPI_MIN, world);\n//              if (comm->me == 0) {\n//                      printf(\"stable time step tri pair is %f\\n\", stable_time_increment_all);\n//              }\n}\n\n/* ----------------------------------------------------------------------\n allocate all arrays\n ------------------------------------------------------------------------- */\n\nvoid PairTriSurf::allocate() {\n        allocated = 1;\n        int n = atom->ntypes;\n\n        memory->create(setflag, n + 1, n + 1, \"pair:setflag\");\n        for (int i = 1; i <= n; i++)\n                for (int j = i; j <= n; j++)\n                        setflag[i][j] = 0;\n\n        memory->create(bulkmodulus, n + 1, n + 1, \"pair:kspring\");\n        memory->create(kn, n + 1, n + 1, \"pair:kn\");\n\n        memory->create(cutsq, n + 1, n + 1, \"pair:cutsq\"); // always needs to be allocated, even with granular neighborlist\n\n        onerad_dynamic = new double[n + 1];\n        onerad_frozen = new double[n + 1];\n        maxrad_dynamic = new double[n + 1];\n        maxrad_frozen = new double[n + 1];\n}\n\n/* ----------------------------------------------------------------------\n global settings\n ------------------------------------------------------------------------- */\n\nvoid PairTriSurf::settings(int narg, char **arg) {\n        if (narg != 1)\n                error->all(FLERR, \"Illegal number of args for pair_style smd/tri_surface\");\n\n        scale = force->numeric(FLERR, arg[0]);\n        if (comm->me == 0) {\n                printf(\"\\n>>========>>========>>========>>========>>========>>========>>========>>========\\n\");\n                printf(\"SMD/TRI_SURFACE CONTACT SETTINGS:\\n\");\n                printf(\"... effective contact radius is scaled by %f\\n\", scale);\n                printf(\">>========>>========>>========>>========>>========>>========>>========>>========\\n\");\n        }\n\n}\n\n/* ----------------------------------------------------------------------\n set coeffs for one or more type pairs\n ------------------------------------------------------------------------- */\n\nvoid PairTriSurf::coeff(int narg, char **arg) {\n        if (narg != 3)\n                error->all(FLERR, \"Incorrect args for pair coefficients\");\n        if (!allocated)\n                allocate();\n\n        int ilo, ihi, jlo, jhi;\n        force->bounds(FLERR,arg[0], atom->ntypes, ilo, ihi);\n        force->bounds(FLERR,arg[1], atom->ntypes, jlo, jhi);\n\n        double bulkmodulus_one = atof(arg[2]);\n\n        // set short-range force constant\n        double kn_one = 0.0;\n        if (domain->dimension == 3) {\n                kn_one = (16. / 15.) * bulkmodulus_one; //assuming poisson ratio = 1/4 for 3d\n        } else {\n                kn_one = 0.251856195 * (2. / 3.) * bulkmodulus_one; //assuming poisson ratio = 1/3 for 2d\n        }\n\n        int count = 0;\n        for (int i = ilo; i <= ihi; i++) {\n                for (int j = MAX(jlo, i); j <= jhi; j++) {\n                        bulkmodulus[i][j] = bulkmodulus_one;\n                        kn[i][j] = kn_one;\n                        setflag[i][j] = 1;\n                        count++;\n                }\n        }\n\n        if (count == 0)\n                error->all(FLERR, \"Incorrect args for pair coefficients\");\n}\n\n/* ----------------------------------------------------------------------\n init for one type pair i,j and corresponding j,i\n ------------------------------------------------------------------------- */\n\ndouble PairTriSurf::init_one(int i, int j) {\n\n        if (!allocated)\n                allocate();\n\n        if (setflag[i][j] == 0)\n                error->all(FLERR, \"All pair coeffs are not set\");\n\n        bulkmodulus[j][i] = bulkmodulus[i][j];\n        kn[j][i] = kn[i][j];\n\n        // cutoff = sum of max I,J radii for\n        // dynamic/dynamic & dynamic/frozen interactions, but not frozen/frozen\n\n        double cutoff = maxrad_dynamic[i] + maxrad_dynamic[j];\n        cutoff = MAX(cutoff, maxrad_frozen[i] + maxrad_dynamic[j]);\n        cutoff = MAX(cutoff, maxrad_dynamic[i] + maxrad_frozen[j]);\n\n        if (comm->me == 0) {\n                printf(\"cutoff for pair smd/smd/tri_surface = %f\\n\", cutoff);\n        }\n        return cutoff;\n}\n\n/* ----------------------------------------------------------------------\n init specific to this pair style\n ------------------------------------------------------------------------- */\n\nvoid PairTriSurf::init_style() {\n        int i;\n\n        // error checks\n\n        if (!atom->contact_radius_flag)\n                error->all(FLERR, \"Pair style smd/smd/tri_surface requires atom style with contact_radius\");\n\n        // old: half list\n        int irequest = neighbor->request(this);\n        neighbor->requests[irequest]->size = 1;\n\n        // need a full neighbor list\n//      int irequest = neighbor->request(this);\n//      neighbor->requests[irequest]->half = 0;\n//      neighbor->requests[irequest]->full = 1;\n\n        // set maxrad_dynamic and maxrad_frozen for each type\n        // include future Fix pour particles as dynamic\n\n        for (i = 1; i <= atom->ntypes; i++)\n                onerad_dynamic[i] = onerad_frozen[i] = 0.0;\n\n        double *radius = atom->radius;\n        int *type = atom->type;\n        int nlocal = atom->nlocal;\n\n        for (i = 0; i < nlocal; i++) {\n                onerad_dynamic[type[i]] = MAX(onerad_dynamic[type[i]], radius[i]);\n        }\n\n        MPI_Allreduce(&onerad_dynamic[1], &maxrad_dynamic[1], atom->ntypes, MPI_DOUBLE, MPI_MAX, world);\n        MPI_Allreduce(&onerad_frozen[1], &maxrad_frozen[1], atom->ntypes, MPI_DOUBLE, MPI_MAX, world);\n}\n\n/* ----------------------------------------------------------------------\n neighbor callback to inform pair style of neighbor list to use\n optional granular history list\n ------------------------------------------------------------------------- */\n\nvoid PairTriSurf::init_list(int id, NeighList *ptr) {\n        if (id == 0)\n                list = ptr;\n}\n\n/* ----------------------------------------------------------------------\n memory usage of local atom-based arrays\n ------------------------------------------------------------------------- */\n\ndouble PairTriSurf::memory_usage() {\n\n        return 0.0;\n}\n\n/*\n * distance between triangle and point\n */\n/*\n function [dist,PP0] = pointTriangleDistance(TRI,P)\n % calculate distance between a point and a triangle in 3D\n % SYNTAX\n %   dist = pointTriangleDistance(TRI,P)\n %   [dist,PP0] = pointTriangleDistance(TRI,P)\n %\n % DESCRIPTION\n %   Calculate the distance of a given point P from a triangle TRI.\n %   Point P is a row vector of the form 1x3. The triangle is a matrix\n %   formed by three rows of points TRI = [P1;P2;P3] each of size 1x3.\n %   dist = pointTriangleDistance(TRI,P) returns the distance of the point P\n %   to the triangle TRI.\n %   [dist,PP0] = pointTriangleDistance(TRI,P) additionally returns the\n %   closest point PP0 to P on the triangle TRI.\n %\n % Author: Gwendolyn Fischer\n % Release: 1.0\n % Release date: 09/02/02\n % Release: 1.1 Fixed Bug because of normalization\n % Release: 1.2 Fixed Bug because of typo in region 5 20101013\n % Release: 1.3 Fixed Bug because of typo in region 2 20101014\n\n % Possible extention could be a version tailored not to return the distance\n % and additionally the closest point, but instead return only the closest\n % point. Could lead to a small speed gain.\n\n % Example:\n % %% The Problem\n % P0 = [0.5 -0.3 0.5];\n %\n % P1 = [0 -1 0];\n % P2 = [1  0 0];\n % P3 = [0  0 0];\n %\n % vertices = [P1; P2; P3];\n % faces = [1 2 3];\n %\n % %% The Engine\n % [dist,PP0] = pointTriangleDistance([P1;P2;P3],P0);\n %\n % %% Visualization\n % [x,y,z] = sphere(20);\n % x = dist*x+P0(1);\n % y = dist*y+P0(2);\n % z = dist*z+P0(3);\n %\n % figure\n % hold all\n % patch('Vertices',vertices,'Faces',faces,'FaceColor','r','FaceAlpha',0.8);\n % plot3(P0(1),P0(2),P0(3),'b*');\n % plot3(PP0(1),PP0(2),PP0(3),'*g')\n % surf(x,y,z,'FaceColor','b','FaceAlpha',0.3)\n % view(3)\n\n % The algorithm is based on\n % \"David Eberly, 'Distance Between Point and Triangle in 3D',\n % Geometric Tools, LLC, (1999)\"\n % http:\\\\www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf\n %\n %        ^t\n %  \\     |\n %   \\reg2|\n %    \\   |\n %     \\  |\n %      \\ |\n %       \\|\n %        *P2\n %        |\\\n%        | \\\n%  reg3  |  \\ reg1\n %        |   \\\n%        |reg0\\\n%        |     \\\n%        |      \\ P1\n % -------*-------*------->s\n %        |P0      \\\n%  reg4  | reg5    \\ reg6\n */\n\n//void PairTriSurf::PointTriangleDistance(const Vector3d P, const Vector3d TRI1, const Vector3d TRI2, const Vector3d TRI3,\n//              Vector3d &CP, double &dist) {\n//\n//      Vector3d B, E0, E1, D;\n//      double a, b, c, d, e, f;\n//      double det, s, t, sqrDistance, tmp0, tmp1, numer, denom, invDet;\n//\n//      // rewrite triangle in normal form\n//      B = TRI1;\n//      E0 = TRI2 - B;\n//      E1 = TRI3 - B;\n//\n//      D = B - P;\n//      a = E0.dot(E0);\n//      b = E0.dot(E1);\n//      c = E1.dot(E1);\n//      d = E0.dot(D);\n//      e = E1.dot(D);\n//      f = D.dot(D);\n//\n//      det = a * c - b * b;\n//      //% do we have to use abs here?\n//      s = b * e - c * d;\n//      t = b * d - a * e;\n//\n//      //% Terible tree of conditionals to determine in which region of the diagram\n//      //% shown above the projection of the point into the triangle-plane lies.\n//      if ((s + t) <= det) {\n//              if (s < 0) {\n//                      if (t < 0) {\n//                              // %region4\n//                              if (d < 0) {\n//                                      t = 0;\n//                                      if (-d >= a) {\n//                                              s = 1;\n//                                              sqrDistance = a + 2 * d + f;\n//                                      } else {\n//                                              s = -d / a;\n//                                              sqrDistance = d * s + f;\n//                                      }\n//                              } else {\n//                                      s = 0;\n//                                      if (e >= 0) {\n//                                              t = 0;\n//                                              sqrDistance = f;\n//                                      } else {\n//                                              if (-e >= c) {\n//                                                      t = 1;\n//                                                      sqrDistance = c + 2 * e + f;\n//                                              } else {\n//                                                      t = -e / c;\n//                                                      sqrDistance = e * t + f;\n//                                              }\n//                                      }\n//                              }\n//                              // end % of region 4\n//                      } else {\n//                              // % region 3\n//                              s = 0;\n//                              if (e >= 0) {\n//                                      t = 0;\n//                                      sqrDistance = f;\n//                              } else {\n//                                      if (-e >= c) {\n//                                              t = 1;\n//                                              sqrDistance = c + 2 * e + f;\n//                                      } else {\n//                                              t = -e / c;\n//                                              sqrDistance = e * t + f;\n//                                      }\n//                              }\n//                      }\n//                      // end of region 3\n//              } else {\n//                      if (t < 0) {\n//                              //% region 5\n//                              t = 0;\n//                              if (d >= 0) {\n//                                      s = 0;\n//                                      sqrDistance = f;\n//                              } else {\n//                                      if (-d >= a) {\n//                                              s = 1;\n//                                              sqrDistance = a + 2 * d + f;\n//                                      } else {\n//                                              s = -d / a;\n//                                              sqrDistance = d * s + f;\n//                                      }\n//                              }\n//                      } else {\n//                              // region 0\n//                              invDet = 1 / det;\n//                              s = s * invDet;\n//                              t = t * invDet;\n//                              sqrDistance = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f;\n//                      }\n//              }\n//      } else {\n//              if (s < 0) {\n//                      // % region 2\n//                      tmp0 = b + d;\n//                      tmp1 = c + e;\n//                      if (tmp1 > tmp0) { //% minimum on edge s+t=1\n//                              numer = tmp1 - tmp0;\n//                              denom = a - 2 * b + c;\n//                              if (numer >= denom) {\n//                                      s = 1;\n//                                      t = 0;\n//                                      sqrDistance = a + 2 * d + f;\n//                              } else {\n//                                      s = numer / denom;\n//                                      t = 1 - s;\n//                                      sqrDistance = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f;\n//                              }\n//                      } else\n//                              // % minimum on edge s=0\n//                              s = 0;\n//                      if (tmp1 <= 0) {\n//                              t = 1;\n//                              sqrDistance = c + 2 * e + f;\n//                      } else {\n//                              if (e >= 0) {\n//                                      t = 0;\n//                                      sqrDistance = f;\n//                              } else {\n//                                      t = -e / c;\n//                                      sqrDistance = e * t + f;\n//                              }\n//                      }\n//              } //end % of region     2\n//              else {\n//                      if (t < 0) {\n//                              // %region6\n//                              tmp0 = b + e;\n//                              tmp1 = a + d;\n//                              if (tmp1 > tmp0) {\n//                                      numer = tmp1 - tmp0;\n//                                      denom = a - 2 * b + c;\n//                                      if (numer >= denom) {\n//                                              t = 1;\n//                                              s = 0;\n//                                              sqrDistance = c + 2 * e + f;\n//                                      } else {\n//                                              t = numer / denom;\n//                                              s = 1 - t;\n//                                              sqrDistance = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f;\n//                                      }\n//                              } else {\n//                                      t = 0;\n//                                      if (tmp1 <= 0) {\n//                                              s = 1;\n//                                              sqrDistance = a + 2 * d + f;\n//                                      } else {\n//                                              if (d >= 0) {\n//                                                      s = 0;\n//                                                      sqrDistance = f;\n//                                              } else {\n//                                                      s = -d / a;\n//                                                      sqrDistance = d * s + f;\n//                                              }\n//                                      }\n//                              } // % end region 6\n//                      } else {\n//                              //% region 1\n//                              numer = c + e - b - d;\n//                              if (numer <= 0) {\n//                                      s = 0;\n//                                      t = 1;\n//                                      sqrDistance = c + 2 * e + f;\n//                              } else {\n//                                      denom = a - 2 * b + c;\n//                                      if (numer >= denom) {\n//                                              s = 1;\n//                                              t = 0;\n//                                              sqrDistance = a + 2 * d + f;\n//                                      } else {\n//                                              s = numer / denom;\n//                                              t = 1 - s;\n//                                              sqrDistance = s * (a * s + b * t + 2 * d) + t * (b * s + c * t + 2 * e) + f;\n//                                      }\n//                              } //% end of region 1\n//                      }\n//              }\n//      }\n//\n//      // % account for numerical round-off error\n//      if (sqrDistance < 0) {\n//              sqrDistance = 0;\n//      }\n//\n//      dist = sqrt(sqrDistance);\n//\n//      // closest point\n//      CP = B + s * E0 + t * E1;\n//\n//}\n/*\n * % The algorithm is based on\n % \"David Eberly, 'Distance Between Point and Triangle in 3D',\n % Geometric Tools, LLC, (1999)\"\n % http:\\\\www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf\n */\n\nvoid PairTriSurf::PointTriangleDistance(const Vector3d sourcePosition, const Vector3d TRI0, const Vector3d TRI1,\n                const Vector3d TRI2, Vector3d &CP, double &dist) {\n\n        Vector3d edge0 = TRI1 - TRI0;\n        Vector3d edge1 = TRI2 - TRI0;\n        Vector3d v0 = TRI0 - sourcePosition;\n\n        double a = edge0.dot(edge0);\n        double b = edge0.dot(edge1);\n        double c = edge1.dot(edge1);\n        double d = edge0.dot(v0);\n        double e = edge1.dot(v0);\n\n        double det = a * c - b * b;\n        double s = b * e - c * d;\n        double t = b * d - a * e;\n\n        if (s + t < det) {\n                if (s < 0.f) {\n                        if (t < 0.f) {\n                                if (d < 0.f) {\n                                        s = clamp(-d / a, 0.f, 1.f);\n                                        t = 0.f;\n                                } else {\n                                        s = 0.f;\n                                        t = clamp(-e / c, 0.f, 1.f);\n                                }\n                        } else {\n                                s = 0.f;\n                                t = clamp(-e / c, 0.f, 1.f);\n                        }\n                } else if (t < 0.f) {\n                        s = clamp(-d / a, 0.f, 1.f);\n                        t = 0.f;\n                } else {\n                        float invDet = 1.f / det;\n                        s *= invDet;\n                        t *= invDet;\n                }\n        } else {\n                if (s < 0.f) {\n                        float tmp0 = b + d;\n                        float tmp1 = c + e;\n                        if (tmp1 > tmp0) {\n                                float numer = tmp1 - tmp0;\n                                float denom = a - 2 * b + c;\n                                s = clamp(numer / denom, 0.f, 1.f);\n                                t = 1 - s;\n                        } else {\n                                t = clamp(-e / c, 0.f, 1.f);\n                                s = 0.f;\n                        }\n                } else if (t < 0.f) {\n                        if (a + d > b + e) {\n                                float numer = c + e - b - d;\n                                float denom = a - 2 * b + c;\n                                s = clamp(numer / denom, 0.f, 1.f);\n                                t = 1 - s;\n                        } else {\n                                s = clamp(-e / c, 0.f, 1.f);\n                                t = 0.f;\n                        }\n                } else {\n                        float numer = c + e - b - d;\n                        float denom = a - 2 * b + c;\n                        s = clamp(numer / denom, 0.f, 1.f);\n                        t = 1.f - s;\n                }\n        }\n\n        CP = TRI0 + s * edge0 + t * edge1;\n        dist = (CP - sourcePosition).norm();\n\n}\n\ndouble PairTriSurf::clamp(const double a, const double min, const double max) {\n        if (a < min) {\n                return min;\n        } else if (a > max) {\n                return max;\n        } else {\n                return a;\n        }\n}\n\nvoid *PairTriSurf::extract(const char *str, int &/*i*/) {\n        //printf(\"in PairTriSurf::extract\\n\");\n        if (strcmp(str, \"smd/tri_surface/stable_time_increment_ptr\") == 0) {\n                return (void *) &stable_time_increment;\n        }\n\n        return NULL;\n\n}\n", "meta": {"hexsha": "d3a498337950f1c354ee1042c2c6373a761f3bca", "size": 33844, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lammps-master/src/USER-SMD/pair_smd_triangulated_surface.cpp", "max_stars_repo_name": "rajkubp020/helloword", "max_stars_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lammps-master/src/USER-SMD/pair_smd_triangulated_surface.cpp", "max_issues_repo_name": "rajkubp020/helloword", "max_issues_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lammps-master/src/USER-SMD/pair_smd_triangulated_surface.cpp", "max_forks_repo_name": "rajkubp020/helloword", "max_forks_repo_head_hexsha": "4bd22691de24b30a0f5b73821c35a7ac0666b034", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.1470937129, "max_line_length": 165, "alphanum_fraction": 0.3305164874, "num_tokens": 7298, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.30735802320985245, "lm_q1q2_score": 0.2034473066386348}}
{"text": "/*\n *            Copyright 2009-2020 The VOTCA Development Team\n *                       (http://www.votca.org)\n *\n *      Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *              http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n// Third party includes\n#include <boost/format.hpp>\n\n// VOTCA includes\n#include <votca/tools/elements.h>\n\n// Local VOTCA includes\n#include \"votca/xtp/atom.h\"\n#include \"votca/xtp/forces.h\"\n#include \"votca/xtp/statetracker.h\"\n\nnamespace votca {\nnamespace xtp {\n\nusing std::flush;\nvoid Forces::Initialize(tools::Property& options) {\n  force_method_ = options.get(\".method\").as<std::string>();\n\n  displacement_ = options.get(\".displacement\").as<double>();  // Angstrom\n  displacement_ *= tools::conv::ang2bohr;\n\n  remove_total_force_ = options.get(\".CoMforce_removal\").as<bool>();\n}\n\nvoid Forces::Calculate(const Orbitals& orbitals) {\n\n  Index natoms = orbitals.QMAtoms().size();\n  forces_ = Eigen::MatrixX3d::Zero(natoms, 3);\n\n  for (Index atom_index = 0; atom_index < natoms; atom_index++) {\n\n    XTP_LOG(Log::debug, *pLog_)\n        << \"FORCES--DEBUG working on atom \" << atom_index << flush;\n    Eigen::Vector3d atom_force = Eigen::Vector3d::Zero();\n    // Calculate Force on this atom\n    if (force_method_ == \"forward\") {\n      atom_force = NumForceForward(orbitals, atom_index);\n    }\n    if (force_method_ == \"central\") {\n      atom_force = NumForceCentral(orbitals, atom_index);\n    }\n    forces_.row(atom_index) = atom_force.transpose();\n  }\n  if (remove_total_force_) {\n    RemoveTotalForce();\n  }\n  return;\n}\n\nvoid Forces::Report() const {\n\n  XTP_LOG(Log::error, *pLog_)\n      << (boost::format(\" ---- FORCES (Hartree/Bohr)   \")).str() << flush;\n  XTP_LOG(Log::error, *pLog_)\n      << (boost::format(\"      %1$s differences   \") % force_method_).str()\n      << flush;\n  XTP_LOG(Log::error, *pLog_)\n      << (boost::format(\"      displacement %1$1.4f Angstrom   \") %\n          (displacement_ * tools::conv::bohr2ang))\n             .str()\n      << flush;\n  XTP_LOG(Log::error, *pLog_)\n      << (boost::format(\" Atom\\t x\\t  y\\t  z \")).str() << flush;\n\n  for (Index i = 0; i < forces_.rows(); i++) {\n    XTP_LOG(Log::error, *pLog_)\n        << (boost::format(\"%1$4d    %2$+1.4f  %3$+1.4f  %4$+1.4f\") % i %\n            forces_(i, 0) % forces_(i, 1) % forces_(i, 2))\n               .str()\n        << flush;\n  }\n  return;\n}\n\nEigen::Vector3d Forces::NumForceForward(Orbitals orbitals, Index atom_index) {\n  Eigen::Vector3d force = Eigen::Vector3d::Zero();\n  // get this atoms's current coordinates\n  double energy_center =\n      orbitals.getTotalStateEnergy(tracker_.CalcState(orbitals));\n  const Eigen::Vector3d current_pos = orbitals.QMAtoms()[atom_index].getPos();\n  for (Index i_cart = 0; i_cart < 3; i_cart++) {\n    Eigen::Vector3d displacement_vec = Eigen::Vector3d::Zero();\n    displacement_vec[i_cart] = displacement_;\n    // update the coordinate\n    Eigen::Vector3d pos_displaced = current_pos + displacement_vec;\n    orbitals.updateAtomPostion(atom_index, pos_displaced);\n    gwbse_engine_.ExcitationEnergies(orbitals);\n    double energy_displaced =\n        orbitals.getTotalStateEnergy(tracker_.CalcState(orbitals));\n    force(i_cart) = (energy_center - energy_displaced) / displacement_;\n    orbitals.updateAtomPostion(\n        atom_index, current_pos);  // restore original coordinate into segment\n  }                                // Cartesian directions\n  return force;\n}\n\nEigen::Vector3d Forces::NumForceCentral(Orbitals orbitals, Index atom_index) {\n  Eigen::Vector3d force = Eigen::Vector3d::Zero();\n  const Eigen::Vector3d current_pos = orbitals.QMAtoms()[atom_index].getPos();\n  for (Index i_cart = 0; i_cart < 3; i_cart++) {\n    XTP_LOG(Log::debug, *pLog_)\n        << \"FORCES--DEBUG           Cartesian component \" << i_cart << flush;\n    Eigen::Vector3d displacement_vec = Eigen::Vector3d::Zero();\n    displacement_vec[i_cart] = displacement_;\n    // update the coordinate\n    Eigen::Vector3d pos_displaced = current_pos + displacement_vec;\n    orbitals.updateAtomPostion(atom_index, pos_displaced);\n    gwbse_engine_.ExcitationEnergies(orbitals);\n    double energy_displaced_plus =\n        orbitals.getTotalStateEnergy(tracker_.CalcState(orbitals));\n    // update the coordinate\n    pos_displaced = current_pos - displacement_vec;\n    orbitals.updateAtomPostion(atom_index, pos_displaced);\n    gwbse_engine_.ExcitationEnergies(orbitals);\n    double energy_displaced_minus =\n        orbitals.getTotalStateEnergy(tracker_.CalcState(orbitals));\n    force(i_cart) =\n        0.5 * (energy_displaced_minus - energy_displaced_plus) / displacement_;\n    orbitals.updateAtomPostion(\n        atom_index, current_pos);  // restore original coordinate into orbital\n  }\n  return force;\n}\n\nvoid Forces::RemoveTotalForce() {\n  Eigen::Vector3d avgtotal_force =\n      forces_.colwise().sum() / double(forces_.rows());\n  for (Index i_atom = 0; i_atom < forces_.rows(); i_atom++) {\n    forces_.row(i_atom) -= avgtotal_force;\n  }\n  return;\n}\n\n}  // namespace xtp\n}  // namespace votca\n", "meta": {"hexsha": "d467631e5f551dfac4cab7052c416cdd8b09c9d1", "size": 5482, "ext": "cc", "lang": "C++", "max_stars_repo_path": "xtp/src/libxtp/forces.cc", "max_stars_repo_name": "ipelupessy/votca", "max_stars_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "xtp/src/libxtp/forces.cc", "max_issues_repo_name": "ipelupessy/votca", "max_issues_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xtp/src/libxtp/forces.cc", "max_forks_repo_name": "ipelupessy/votca", "max_forks_repo_head_hexsha": "b0daafb6f503e6a55c878172ef9d68c6639da9e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3677419355, "max_line_length": 79, "alphanum_fraction": 0.6705581904, "num_tokens": 1475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20341058314132116}}
{"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\n\n#include \"BidomainCorrectionTermAssembler.hpp\"\n#include \"UblasIncludes.hpp\"\n#include <boost/numeric/ublas/vector_proxy.hpp>\n\ntemplate<unsigned ELEM_DIM, unsigned SPACE_DIM>\nBidomainCorrectionTermAssembler<ELEM_DIM,SPACE_DIM>::BidomainCorrectionTermAssembler(\n     AbstractTetrahedralMesh<ELEM_DIM,SPACE_DIM>* pMesh,\n     BidomainTissue<SPACE_DIM>* pTissue)\n        : AbstractCorrectionTermAssembler<ELEM_DIM,SPACE_DIM,2>(pMesh,pTissue)\n{\n    mpConfig = HeartConfig::Instance();\n    assert(mpConfig->GetUseStateVariableInterpolation());\n}\n\ntemplate<unsigned ELEM_DIM, unsigned SPACE_DIM>\nc_vector<double,2*(ELEM_DIM+1)> BidomainCorrectionTermAssembler<ELEM_DIM,SPACE_DIM>::ComputeVectorTerm(\n    c_vector<double, ELEM_DIM+1> &rPhi,\n    c_matrix<double, SPACE_DIM, ELEM_DIM+1> &rGradPhi /* not used */,\n    ChastePoint<SPACE_DIM> &rX /* not used */,\n    c_vector<double,2> &rU,\n    c_matrix<double, 2, SPACE_DIM> &rGradU /* not used */,\n    Element<ELEM_DIM,SPACE_DIM>* pElement /* not used */)\n{\n    double Am = mpConfig->GetSurfaceAreaToVolumeRatio();\n\n    // compute the ionic current at this quadrature point using the\n    // interpolated state variables, and a random choice of cell (all\n    // should be the same)\n    unsigned node_global_index = pElement->GetNodeGlobalIndex(0);\n    AbstractCardiacCellInterface* p_any_cell = this->mpCardiacTissue->GetCardiacCellOrHaloCell(node_global_index);\n    double ionic_sv_interp = p_any_cell->GetIIonic(&(this->mStateVariablesAtQuadPoint));\n\n    c_vector<double,2*(ELEM_DIM+1)> ret;\n\n    ublas::vector_slice<c_vector<double, 2*(ELEM_DIM+1)> > slice_V  (ret, slice (0, 2, ELEM_DIM+1));\n    ublas::vector_slice<c_vector<double, 2*(ELEM_DIM+1)> > slice_Phi(ret, slice (1, 2, ELEM_DIM+1));\n\n    // add on the SVI ionic current, and take away the original NCI (linearly\n    // interpolated ionic current) that would have been added as part of\n    // the matrix-based assembly stage.\n    noalias(slice_V)   = rPhi * (-Am) * ( ionic_sv_interp - this->mIionicInterp );\n    // no correction needed for elliptic equation\n    noalias(slice_Phi) = zero_vector<double>(ELEM_DIM+1);\n\n    return ret;\n}\n\n// Explicit instantiation\ntemplate class BidomainCorrectionTermAssembler<1,1>;\ntemplate class BidomainCorrectionTermAssembler<2,2>;\ntemplate class BidomainCorrectionTermAssembler<3,3>;\n", "meta": {"hexsha": "eefbeac6e27f77d92b33957b31cce9a5affa5109", "size": 4042, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "heart/src/solver/electrics/bidomain/BidomainCorrectionTermAssembler.cpp", "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/src/solver/electrics/bidomain/BidomainCorrectionTermAssembler.cpp", "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/src/solver/electrics/bidomain/BidomainCorrectionTermAssembler.cpp", "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": 45.9318181818, "max_line_length": 114, "alphanum_fraction": 0.7716476992, "num_tokens": 968, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.20341058314132113}}
{"text": "#pragma once\n#include <boost/pending/disjoint_sets.hpp>\n#include \"xtensor/xtensor.hpp\"\n#include <queue>\n#include <functional>\n#include \"affogato/segmentation/mutex_watershed.hxx\"\n#include \"affogato/util.hxx\"\n\n\nnamespace affogato {\nnamespace segmentation {\n\n    //\n    // semantic helper functions:\n    // check_semantic_constraint: check if two representatives have different semantic labels\n    // assign_semantic_label: assign the semantic label of a representative if not yet existent\n    // merge_semantic_labels: assign two representatives to the same semantic label\n    //\n\n    template<class SEMANTIC_LABELING>\n    inline bool check_semantic_constraint(const uint64_t ru, const uint64_t rv,\n                                          const SEMANTIC_LABELING & semantic_labeling) {\n        int64_t slu = semantic_labeling[ru];\n        int64_t slv = semantic_labeling[rv];\n\n        if (slu >= 0 && slv >= 0)\n            return slu != slv;\n        return false;\n    }\n\n\n    // set semantic label of 'ru' to 'sl'\n    template<class SEMANTIC_LABELING>\n    inline void assign_semantic_label(const uint64_t ru, const int64_t sl,\n                                      SEMANTIC_LABELING & semantic_labeling) {\n        if(semantic_labeling[ru] < 0){\n            semantic_labeling[ru] = sl;\n        }\n    }\n\n\n    // assign same semantic label to 'ru' and 'rv', assume they don't have different labels\n    template<class SEMANTIC_LABELING>\n    inline void merge_semantic_labels(const uint64_t ru, const uint64_t rv,\n                                      SEMANTIC_LABELING & semantic_labeling) {\n        int64_t slu = semantic_labeling[ru];\n        int64_t slv = semantic_labeling[rv];\n\n        if (slu >= 0 && slv < 0)\n            semantic_labeling[rv] = slu;\n        if (slu < 0 && slv >= 0)\n            semantic_labeling[ru] = slv;\n    }\n\n\n    // compute mutex clustering for a graph with attrative and mutex edges\n    template<class EDGE_ARRAY, class WEIGHT_ARRAY, class NODE_ARRAY, class SEMANTIC_ARRAY>\n    void compute_semantic_mws_clustering(const size_t number_of_labels,\n                                         const xt::xexpression<EDGE_ARRAY> & uvs_exp,\n                                         const xt::xexpression<EDGE_ARRAY> & mutex_uvs_exp,\n                                         const xt::xexpression<EDGE_ARRAY> & semantic_uts_exp,\n                                         const xt::xexpression<WEIGHT_ARRAY> & weights_exp,\n                                         const xt::xexpression<WEIGHT_ARRAY> & mutex_weights_exp,\n                                         const xt::xexpression<WEIGHT_ARRAY> & semantic_weights_exp,\n                                         xt::xexpression<NODE_ARRAY> & node_labeling_exp,\n                                         xt::xexpression<SEMANTIC_ARRAY> & semantic_labeling_exp) {\n\n        // casts\n        const auto & uvs = uvs_exp.derived_cast();\n        const auto & mutex_uvs = mutex_uvs_exp.derived_cast();\n        const auto & semantic_uts = semantic_uts_exp.derived_cast();\n        const auto & weights = weights_exp.derived_cast();\n        const auto & mutex_weights = mutex_weights_exp.derived_cast();\n        const auto & semantic_weights = semantic_weights_exp.derived_cast();\n        auto & node_labeling = node_labeling_exp.derived_cast();\n        auto & semantic_labeling = semantic_labeling_exp.derived_cast();\n\n        // make ufd\n        std::vector<uint64_t> ranks(number_of_labels);\n        std::vector<uint64_t> parents(number_of_labels);\n        boost::disjoint_sets<uint64_t*, uint64_t*> ufd(&ranks[0], &parents[0]);\n        for(uint64_t label = 0; label < number_of_labels; ++label) {\n            ufd.make_set(label);\n        }\n\n        // determine number of edge types\n        const size_t num_edges = uvs.shape()[0];\n        const size_t num_mutex = mutex_uvs.shape()[0];\n        const size_t num_semantic = semantic_uts.shape()[0];\n        const size_t num_internal = num_edges + num_mutex;\n\n        // argsort ALL edges\n        // we sort in ascending order\n        std::vector<size_t> indices(num_edges + num_mutex + num_semantic);\n        std::iota(indices.begin(), indices.end(), 0);\n        std::sort(indices.begin(), indices.end(), [&](const size_t a, const size_t b){\n            const double val_a = (a >= num_internal) ? semantic_weights(a - num_internal) :\n                                 (a >= num_edges)    ? mutex_weights(a - num_edges)\n                                                     : weights(a);\n            const double val_b = (b >= num_internal) ? semantic_weights(b - num_internal) :\n                                 (b >= num_edges)    ? mutex_weights(b - num_edges)\n                                                     : weights(b);\n            return val_a > val_b;\n        });\n\n        // data-structure storing mutex edges\n        typedef std::vector<std::vector<uint64_t>> MutexStorage;\n        MutexStorage mutexes(number_of_labels);\n\n        // iterate over all edges\n        for(const size_t edge_id : indices) {\n\n            // check wether this edge is semantic\n            const bool is_semantic_edge = edge_id >= num_internal;\n            // check whether this edge is mutex via the edge offset\n            const bool is_mutex_edge = edge_id >= num_edges;\n\n            const size_t id = is_semantic_edge ? edge_id - num_internal :\n                              is_mutex_edge ? edge_id - num_edges : edge_id;\n\n            // get first incidental node and its current representative of edge_id\n            const uint64_t u = is_semantic_edge ? semantic_uts(id, 0) :\n                               is_mutex_edge ? mutex_uvs(id, 0) : uvs(id, 0);\n            uint64_t ru = ufd.find_set(u);\n\n            if(!is_semantic_edge){\n\n                // find the edge-id or mutex id and the connected nodes\n                const uint64_t v = is_mutex_edge ? mutex_uvs(id, 1) : uvs(id, 1);\n\n                // find the current representatives\n                uint64_t rv = ufd.find_set(v);\n\n                // if the nodes are already connected, do nothing\n                if(ru == rv) {\n                    continue;\n                }\n\n                if(check_semantic_constraint(ru, rv, semantic_labeling)){\n                    continue;\n                }\n\n                // if we already have a mutex, we do not need to do anything\n                // (if this is a regular edge, we do not link, if it is a mutex edge\n                //  we do not need to insert the redundant mutex constraint)\n                if(check_mutex(ru, rv, mutexes)) {\n                    continue;\n                }\n\n                if(is_mutex_edge) {\n\n                    // insert mutex constraint\n                    insert_mutex(ru, rv, id, mutexes);\n\n                } else {\n\n                    // link the nodes and merge their mutex constraints\n                    ufd.link(u, v);\n                    // check  if we have to swap the roots\n                    if(ufd.find_set(ru) == rv) {\n                        std::swap(ru, rv);\n                    }\n                    // merge mutexes from rv -> ru\n                    merge_mutexes(rv, ru, mutexes);\n                }\n            } else{\n                // find semantic label associated to edge\n                int64_t t = semantic_uts(id, 1);\n                assign_semantic_label(ru, t, semantic_labeling);\n            }\n        }\n\n        // get node labeling into output\n        util::export_consecutive_labels(ufd, number_of_labels, node_labeling);\n\n        for(size_t label = 0; label < number_of_labels; ++label) {\n            uint64_t root = ufd.find_set(label);\n            semantic_labeling[label] = semantic_labeling[root];\n        }\n    }\n\n\n    // compute mutex segmentation via kruskal\n    template<class WEIGHT_ARRAY, class NODE_ARRAY, class SEMANTIC_ARRAY, class INDICATOR_ARRAY>\n    void compute_semantic_mws_segmentation(const xt::xexpression<WEIGHT_ARRAY> & sorted_flat_indices_exp,\n                                           const xt::xexpression<INDICATOR_ARRAY> & valid_edges_exp,\n                                           const std::vector<std::vector<int>> & offsets,\n                                           const size_t number_of_attractive_channels,\n                                           const std::vector<int> & image_shape,\n                                           xt::xexpression<NODE_ARRAY> & node_labeling_exp,\n                                           xt::xexpression<SEMANTIC_ARRAY> & semantic_labeling_exp) {\n\n        // casts\n        const auto & sorted_flat_indices = sorted_flat_indices_exp.derived_cast();\n        const auto & valid_edges = valid_edges_exp.derived_cast();\n        auto & node_labeling = node_labeling_exp.derived_cast();\n        auto & semantic_labeling = semantic_labeling_exp.derived_cast();\n\n        // determine number of nodes and attractive edges\n        const size_t number_of_nodes = node_labeling.size();\n        const size_t number_of_attractive_edges = number_of_nodes * number_of_attractive_channels;\n        const size_t number_of_offsets = offsets.size();\n        const size_t ndims = offsets[0].size();\n        const size_t number_of_internal_edges = number_of_nodes * number_of_offsets;\n\n        std::vector<int64_t> array_stride(ndims);\n        int64_t current_stride = 1;\n        for (int i = ndims-1; i >= 0; --i){\n            array_stride[i] = current_stride;\n            current_stride *= image_shape[i];\n        }\n\n        std::vector<int64_t> offset_strides;\n        for (const auto & offset: offsets){\n            int64_t stride = 0;\n            for (int i = 0; i < offset.size(); ++i){\n                stride += offset[i] * array_stride[i];\n            }\n            offset_strides.push_back(stride);\n        }\n\n        // make ufd\n        std::vector<uint64_t> ranks(number_of_nodes);\n        std::vector<uint64_t> parents(number_of_nodes);\n        boost::disjoint_sets<uint64_t*, uint64_t*> ufd(&ranks[0], &parents[0]);\n        for(uint64_t label = 0; label < number_of_nodes; ++label) {\n            ufd.make_set(label);\n        }\n\n        // data-structure for storing semantic labels, unassigned are set to 0\n        // std::vector<uint64_t> semantic_labeling(number_of_nodes, 0);\n\n        // data-structure storing mutex edges\n        typedef std::vector<std::vector<uint64_t>> MutexStorage;\n        MutexStorage mutexes(number_of_nodes);\n\n        // iterate over all edges\n        for(const size_t edge_id : sorted_flat_indices) {\n\n            if(!valid_edges(edge_id)){\n                continue;\n            }\n\n            // check wether this edge is semantic\n            const bool is_semantic_edge = edge_id >= number_of_internal_edges;\n            // check whether this edge is mutex via the edge offset\n            const bool is_mutex_edge = edge_id >= number_of_attractive_edges;\n\n            // get first incidental node and its current representative of edge_id\n            const uint64_t u = edge_id % number_of_nodes;\n            uint64_t ru = ufd.find_set(u);\n\n            if(!is_semantic_edge){\n                // const auto affCoord_ = xt::unravel_from_strides(edge_id, strides, layout);\n\n\n                // get second incidental node\n                const uint64_t v = u + offset_strides[edge_id / number_of_nodes];\n                // find the current representative\n                uint64_t rv = ufd.find_set(v);\n\n                // if the nodes are already connected, do nothing\n                if(ru == rv) {\n                    continue;\n                }\n\n                if(check_semantic_constraint(ru, rv, semantic_labeling)){\n                    continue;\n                }\n\n                // if we already have a mutex, we do not need to do anything\n                // (if this is a regular edge, we do not link, if it is a mutex edge\n                //  we do not need to insert the redundant mutex constraint)\n                if(check_mutex(ru, rv, mutexes)) {\n                    continue;\n                }\n\n                if(is_mutex_edge) {\n\n                    // insert the mutex edge into both mutex edge storages\n                    insert_mutex(ru, rv, edge_id, mutexes);\n\n                } else {\n\n                    ufd.link(u, v);\n                    // check  if we have to swap the roots\n                    if(ufd.find_set(ru) == rv) {\n                        std::swap(ru, rv);\n                    }\n                    // merge mutexes from rv -> ru\n                    merge_mutexes(rv, ru, mutexes);\n                    merge_semantic_labels(ru, rv, semantic_labeling);\n                }\n            }else{\n                // find semantic label associated to edge\n                int64_t sl = edge_id / number_of_nodes - number_of_offsets;\n\n                // add semantic class to cluster\n                assign_semantic_label(ru, sl, semantic_labeling);\n            }\n        }\n\n        // get node labeling into output\n        util::export_consecutive_labels(ufd, number_of_nodes, node_labeling);\n\n        for(size_t label = 0; label < number_of_nodes; ++label) {\n            uint64_t root = ufd.find_set(label);\n            semantic_labeling[label] = semantic_labeling[root];\n        }\n    }\n}\n}\n", "meta": {"hexsha": "e05a7025cc38717ecc1ee5f328a820a92302adb6", "size": 13198, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "include/affogato/segmentation/semantic_mutex_watershed.hxx", "max_stars_repo_name": "constantinpape/affogato", "max_stars_repo_head_hexsha": "22ea369313b01e10f5cfefa21b7db0df719f75b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-04-11T00:47:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-03T23:41:06.000Z", "max_issues_repo_path": "include/affogato/segmentation/semantic_mutex_watershed.hxx", "max_issues_repo_name": "constantinpape/affogato", "max_issues_repo_head_hexsha": "22ea369313b01e10f5cfefa21b7db0df719f75b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-05-28T16:12:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T18:21:03.000Z", "max_forks_repo_path": "include/affogato/segmentation/semantic_mutex_watershed.hxx", "max_forks_repo_name": "constantinpape/affogato", "max_forks_repo_head_hexsha": "22ea369313b01e10f5cfefa21b7db0df719f75b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-01T12:16:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T12:16:23.000Z", "avg_line_length": 42.1661341853, "max_line_length": 105, "alphanum_fraction": 0.562282164, "num_tokens": 2812, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.577495350642608, "lm_q2_score": 0.352201788847459, "lm_q1q2_score": 0.20339489554741713}}
{"text": "//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.\r\n\r\n//Distributed under the Boost Software License, Version 1.0. (See accompanying\r\n//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef UUID_8AC84A2217C411E0A7AF3A1BDFD72085\r\n#define UUID_8AC84A2217C411E0A7AF3A1BDFD72085\r\n\r\n#include <boost/qvm/inline.hpp>\r\n#include <boost/qvm/quat_traits.hpp>\r\n#include <boost/qvm/deduce_vec.hpp>\r\n#include <boost/qvm/static_assert.hpp>\r\n#include <boost/qvm/enable_if.hpp>\r\n\r\nnamespace\r\nboost\r\n    {\r\n    namespace\r\n    qvm\r\n        {\r\n        ////////////////////////////////////////////////\r\n\r\n        namespace\r\n        qvm_detail\r\n            {\r\n            template <class Q>\r\n            struct\r\n            quat_v_\r\n                {\r\n                template <class R>\r\n                operator R() const\r\n                    {\r\n                    R r;\r\n                    assign(r,*this);\r\n                    return r;\r\n                    }\r\n\r\n                private:\r\n\r\n                quat_v_( quat_v_ const & );\r\n                quat_v_ const & operator=( quat_v_ const & );\r\n                ~quat_v_();\r\n                };\r\n            }\r\n\r\n        template <class V>\r\n        struct vec_traits;\r\n\r\n        template <class Q>\r\n        struct\r\n        vec_traits< qvm_detail::quat_v_<Q> >\r\n            {\r\n            typedef qvm_detail::quat_v_<Q> this_vector;\r\n            typedef typename quat_traits<Q>::scalar_type scalar_type;\r\n            static int const dim=3;\r\n\r\n            template <int I>\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            static\r\n            scalar_type\r\n            read_element( this_vector const & q )\r\n                {\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\n                return quat_traits<Q>::template read_element<I+1>( reinterpret_cast<Q const &>(q) );\r\n                }\r\n\r\n            template <int I>\r\n            BOOST_QVM_INLINE_CRITICAL\r\n            static\r\n            scalar_type &\r\n            write_element( this_vector & q )\r\n                {\r\n                BOOST_QVM_STATIC_ASSERT(I>=0);\r\n                BOOST_QVM_STATIC_ASSERT(I<dim);\r\n                return quat_traits<Q>::template write_element<I+1>( reinterpret_cast<Q &>(q) );\r\n                }\r\n            };\r\n\r\n        template <class Q,int D>\r\n        struct\r\n        deduce_vec<qvm_detail::quat_v_<Q>,D>\r\n            {\r\n            typedef vec<typename quat_traits<Q>::scalar_type,D> type;\r\n            };\r\n\r\n        template <class Q,int D>\r\n        struct\r\n        deduce_vec2<qvm_detail::quat_v_<Q>,qvm_detail::quat_v_<Q>,D>\r\n            {\r\n            typedef vec<typename quat_traits<Q>::scalar_type,D> type;\r\n            };\r\n\r\n        template <class Q>\r\n        BOOST_QVM_INLINE_TRIVIAL\r\n        typename enable_if_c<\r\n            is_quat<Q>::value,\r\n            qvm_detail::quat_v_<Q> const &>::type\r\n        V( Q const & a )\r\n            {\r\n            return reinterpret_cast<qvm_detail::quat_v_<Q> const &>(a);\r\n            }\r\n\r\n        template <class Q>\r\n        BOOST_QVM_INLINE_TRIVIAL\r\n        typename enable_if_c<\r\n            is_quat<Q>::value,\r\n            qvm_detail::quat_v_<Q> &>::type\r\n        V( Q & a )\r\n            {\r\n            return reinterpret_cast<qvm_detail::quat_v_<Q> &>(a);\r\n            }\r\n\r\n        template <class Q> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_quat<Q>::value,typename quat_traits<Q>::scalar_type>::type S( Q const & a ) { return quat_traits<Q>::template read_element<0>(a); }\r\n        template <class Q> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_quat<Q>::value,typename quat_traits<Q>::scalar_type>::type X( Q const & a ) { return quat_traits<Q>::template read_element<1>(a); }\r\n        template <class Q> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_quat<Q>::value,typename quat_traits<Q>::scalar_type>::type Y( Q const & a ) { return quat_traits<Q>::template read_element<2>(a); }\r\n        template <class Q> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_quat<Q>::value,typename quat_traits<Q>::scalar_type>::type Z( Q const & a ) { return quat_traits<Q>::template read_element<3>(a); }\r\n\r\n        template <class Q> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_quat<Q>::value,typename quat_traits<Q>::scalar_type &>::type S( Q & a ) { return quat_traits<Q>::template write_element<0>(a); }\r\n        template <class Q> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_quat<Q>::value,typename quat_traits<Q>::scalar_type &>::type X( Q & a ) { return quat_traits<Q>::template write_element<1>(a); }\r\n        template <class Q> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_quat<Q>::value,typename quat_traits<Q>::scalar_type &>::type Y( Q & a ) { return quat_traits<Q>::template write_element<2>(a); }\r\n        template <class Q> BOOST_QVM_INLINE_TRIVIAL typename enable_if_c<is_quat<Q>::value,typename quat_traits<Q>::scalar_type &>::type Z( Q & a ) { return quat_traits<Q>::template write_element<3>(a); }\r\n\r\n        ////////////////////////////////////////////////\r\n        }\r\n    }\r\n\r\n#endif\r\n", "meta": {"hexsha": "fe69b29cb1d6e7c8ea4e079ae6c04ee1ca6d6c3f", "size": 5107, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/qvm/quat_access.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/qvm/quat_access.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/qvm/quat_access.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 39.5891472868, "max_line_length": 208, "alphanum_fraction": 0.5611905228, "num_tokens": 1203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.20335982781826212}}
{"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/**\n * @file math.hpp\n * @author Vaclav Blazek <vaclav.blazek@citationtech.net>\n *\n * 3D mesh operations\n */\n\n#include <numeric>\n\n#include <OpenMesh/Core/IO/MeshIO.hh>\n#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>\n#include <OpenMesh/Tools/Decimater/DecimaterT.hh>\n#include <OpenMesh/Tools/Decimater/ModQuadricT.hh>\n#include <OpenMesh/Tools/Decimater/ModNormalFlippingT.hh>\n#include <OpenMesh/Tools/Decimater/ModAspectRatioT.hh>\n#include <OpenMesh/Tools/Decimater/ModEdgeLengthT.hh>\n#include <boost/numeric/ublas/vector.hpp>\n\n#include \"math/math.hpp\"\n\n#include \"meshop.hpp\"\n#include \"detail/hybrid-decimater.hpp\"\n\nnamespace geometry {\n\n/* code moved from the window-mesh utility */\nnamespace ublas = boost::numeric::ublas;\n\nnamespace {\n\nstruct NormalTraits : public OpenMesh::DefaultTraits\n{\n  FaceAttributes( OpenMesh::Attributes::Normal );\n  VertexTraits\n  {\n    int classLabel;\n  };\n\n};\n\ntypedef OpenMesh::TriMesh_ArrayKernelT<NormalTraits> OMMesh;\ntypedef OpenMesh::Decimater::DecimaterT<OMMesh> Decimator;\ntypedef OpenMesh::Decimater::ModQuadricT<OMMesh>::Handle HModQuadric;\ntypedef detail::ModQuadricHybrid<OMMesh>::Handle HModQuadricHybrid;\ntypedef OpenMesh::Decimater::ModNormalFlippingT<OMMesh>::Handle HModNormalFlippingT;\ntypedef OpenMesh::Decimater::ModAspectRatioT<OMMesh>::Handle HModAspectRatioT;\ntypedef OpenMesh::Decimater::ModEdgeLengthT<OMMesh>::Handle HModEdgeLengthT;\n\n#if OM_VERSION >= 0x60000\ntypedef detail::ModQuadricConvexT<OMMesh>::Handle HModQuadricConvex;\ntypedef detail::ClassifyRestrictModT<OMMesh>::Handle HModClassRestrictT;\n#endif\n\n#ifdef GEOMETRY_HAS_OPENCV\n\n/** Extension of ModQuadric multiplying the cost by generic 2D weight map\n */\ntemplate <class MeshT>\nclass ModWeightedQuadricT : public OpenMesh::Decimater::ModQuadricT<MeshT> {\npublic:\n    // Defines the types Self, Handle, Base, Mesh, and CollapseInfo\n    // and the memberfunction name()\n    DECIMATING_MODULE(ModWeightedQuadricT, MeshT, WeightedQuadric);\n\npublic:\n    ModWeightedQuadricT(MeshT& mesh)\n        : OpenMesh::Decimater::ModQuadricT<MeshT>(mesh) {\n        Base::mesh().add_property(weights_);\n    }\n\n    ~ModWeightedQuadricT() {\n        Base::mesh().remove_property(weights_);\n    }\n\n    virtual float collapse_priority(const CollapseInfo& ci) {\n        const float baseCost = OpenMesh::Decimater::ModQuadricT<MeshT>::collapse_priority(ci);\n        if (baseCost != Base::ILLEGAL_COLLAPSE) {\n            const double w = Base::mesh().property(weights_, ci.v1);\n            return baseCost * w;\n        } else {\n            return baseCost;\n        }\n    }\n\n    void setWeights(const std::vector<float>& weights) {\n        MeshT& mesh = Base::mesh();\n        int i = 0;\n        for (auto iter = mesh.vertices_begin(); iter != mesh.vertices_end(); ++iter, ++i) {\n            mesh.property(weights_, *iter) = weights[i];\n        }\n    }\n\nprivate:\n    OpenMesh::VPropHandleT<float> weights_;\n};\n\ntypedef ModWeightedQuadricT<OMMesh>::Handle HModWeightedQuadric;\n\n#endif\n\n/** Convert mesh to OpenMesh data structure and return mesh extents (2D bounding\n *  box)\n */\nmath::Extents2 toOpenMesh(const geometry::Mesh &mesh, OMMesh& omMesh)\n{\n    math::Extents2 e(math::InvalidExtents{});\n\n    // create OpenMesh vertices\n    std::vector<OMMesh::VertexHandle> handles;\n    handles.reserve(mesh.vertices.size());\n    int i = 0;\n\n    for (const auto& v : mesh.vertices) {\n        handles.emplace_back(\n            omMesh.add_vertex(OMMesh::Point(v(0), v(1), v(2))) );\n        update(e, v);\n\n        // copy classification data only if present\n        if (mesh.vertecesClass.size()) {\n            omMesh.data(handles.back()).classLabel = mesh.vertecesClass[i];\n            ++i;\n        }\n    }\n\n    // create OpenMesh faces\n    for (const geometry::Face& face : mesh.faces)\n    {\n        OMMesh::VertexHandle face_handles[3] = {\n            handles[face.a], handles[face.b], handles[face.c]\n        };\n        omMesh.add_face(face_handles, 3);\n    }\n\n    return e;\n}\n\n\nvoid fromOpenMesh(const OMMesh& omMesh, geometry::Mesh& mesh)\n{\n    // create our vertices\n    for (auto v_it = omMesh.vertices_begin();\n              v_it != omMesh.vertices_end();\n              ++v_it)\n    {\n        const auto& pt = omMesh.point(v_it.handle());\n        mesh.vertices.emplace_back(pt[0], pt[1], pt[2]);\n    }\n\n    // create our faces\n    for (auto f_it = omMesh.faces_begin();\n              f_it != omMesh.faces_end();\n              ++f_it)\n    {\n        auto fv_it(omMesh.cfv_iter(f_it.handle()));\n        int index[3], *p = index;\n        for ( ; fv_it; ++fv_it) {\n            *p++ = fv_it.handle().idx();\n        }\n        mesh.faces.emplace_back(index[0], index[1], index[2]);\n    }\n}\n\nvoid lockBorder(OMMesh &omMesh, bool inner, bool outer){\n    // get bounding box\n    double box[2][2] = { {INFINITY, -INFINITY}, {INFINITY, -INFINITY} };\n\n    for (auto v_it = omMesh.vertices_begin();\n              v_it != omMesh.vertices_end();  ++v_it)\n    {\n        const auto& pt = omMesh.point(v_it.handle());\n        for (int i = 0; i < 2; i++) {\n            if (pt[i] < box[i][0]) box[i][0] = pt[i];\n            if (pt[i] > box[i][1]) box[i][1] = pt[i];\n        }\n    }\n\n    double eps = std::max(box[0][1]-box[0][0], box[1][1]-box[1][0])/(1<<10);\n    double epsNormal = 0.001;\n\n    for (auto e_it = omMesh.edges_begin();\n              e_it != omMesh.edges_end();  ++e_it)\n    {\n        if(omMesh.is_boundary(e_it))\n        {\n            //LOG(info3)<<\"--------\";\n            auto hfhandle(omMesh.halfedge_handle(e_it,0));\n\n            auto from(omMesh.from_vertex_handle(hfhandle));\n            auto to(omMesh.to_vertex_handle(hfhandle));\n\n            //check if both points lie on the same border\n            auto p1(omMesh.point(from));\n            auto p2(omMesh.point(to));\n            math::Point3 curNormal(\n                math::normalize(math::Point3(p2[0]-p1[0], p2[1]-p1[1], p2[2]-p1[2])));\n            //check if previous edge or next is in the same direction\n            bool dirChangeFrom(true);\n            bool dirChangeTo(true);\n            for(auto vih_it = omMesh.vih_iter(to); vih_it; ++vih_it) {\n                if(omMesh.is_boundary(vih_it)){\n                    //auto prevhf = omMesh.prev_halfedge_handle(hfhandle);\n                    auto pfrom(omMesh.from_vertex_handle(vih_it));\n                    auto pto(omMesh.to_vertex_handle(vih_it));\n                    auto pp1(omMesh.point(pfrom));\n                    auto pp2(omMesh.point(pto));\n                    math::Point3 prevNormal(\n                    math::normalize(math::Point3(pp2[0]-pp1[0], pp2[1]-pp1[1], pp2[2]-pp1[2])));\n                    dirChangeTo = std::abs(ublas::inner_prod(prevNormal,curNormal))<(1.0f-epsNormal);\n                }\n            }\n            for(auto voh_it = omMesh.voh_iter(from); voh_it; ++voh_it) {\n                if(omMesh.is_boundary(voh_it)){\n                    //auto nexthf = omMesh.next_halfedge_handle(hfhandle);\n                    auto nfrom(omMesh.from_vertex_handle(voh_it));\n                    auto nto(omMesh.to_vertex_handle(voh_it));\n                    auto np1(omMesh.point(nfrom));\n                    auto np2(omMesh.point(nto));\n                    math::Point3 nextNormal(\n                        math::normalize(math::Point3(np2[0]-np1[0], np2[1]-np1[1], np2[2]-np1[2])));\n                    dirChangeFrom = std::abs(ublas::inner_prod(nextNormal,curNormal))<(1.0f-epsNormal);\n                }\n            }\n\n            bool p1Border[4];\n            bool p2Border[4];\n\n            p1Border[0] = std::abs(p1[0]-box[0][0])<eps;\n            p1Border[1] = std::abs(p1[0]-box[0][1])<eps;\n            p1Border[2] = std::abs(p1[1]-box[1][0])<eps;\n            p1Border[3] = std::abs(p1[1]-box[1][0])<eps;\n\n            p2Border[0] = std::abs(p2[0]-box[0][0])<eps;\n            p2Border[1] = std::abs(p2[0]-box[0][1])<eps;\n            p2Border[2] = std::abs(p2[1]-box[1][0])<eps;\n            p2Border[3] = std::abs(p2[1]-box[1][0])<eps;\n\n            bool onBorder = false;\n            for (int i = 0; i < 4; i++) {\n                onBorder = (onBorder || (p1Border[i]==p2Border[i] && p1Border[i]));\n            }\n\n            if((inner && !onBorder) || (outer && onBorder)){\n                //if they don't lie on the border, lock them\n                if(dirChangeFrom){\n                    omMesh.status(from).set_locked(true);\n                }\n\n                if(dirChangeTo){\n                    omMesh.status(to).set_locked(true);\n                }\n            }\n        }\n    }\n}\n\nvoid lockCorners(OMMesh &omMesh)\n{\n    // get bounding box\n    double box[2][2] = { {INFINITY, -INFINITY}, {INFINITY, -INFINITY} };\n\n    for (auto v_it = omMesh.vertices_begin();\n              v_it != omMesh.vertices_end();  ++v_it)\n    {\n        const auto& pt = omMesh.point(v_it.handle());\n        for (int i = 0; i < 2; i++) {\n            box[i][0] = std::min(double(pt[i]), box[i][0]);\n            box[i][1] = std::max(double(pt[i]), box[i][1]);\n        }\n    }\n\n    // calculate smallest distances to the four corners of the bounding box\n    double dist[2][2] = { {INFINITY, INFINITY}, {INFINITY, INFINITY} };\n\n    for (auto v_it = omMesh.vertices_begin();\n              v_it != omMesh.vertices_end();  ++v_it)\n    {\n        const auto& pt = omMesh.point(v_it.handle());\n\n        for (int i = 0; i < 2; i++)\n        for (int j = 0; j < 2; j++)\n        {\n            double d = std::hypot(pt[0] - box[0][i], pt[1] - box[1][j]);\n            dist[i][j] = std::min(d, dist[i][j]);\n        }\n    }\n\n    omMesh.request_vertex_status();\n\n    // lock vertices closest to the corners\n    // (note: multiple vertices can have the same minimum distance to a corner)\n    for (auto v_it = omMesh.vertices_begin();\n              v_it != omMesh.vertices_end();  ++v_it)\n    {\n        const auto& pt = omMesh.point(v_it.handle());\n\n        for (int i = 0; i < 2; i++)\n        for (int j = 0; j < 2; j++)\n        {\n            double d = std::hypot(pt[0] - box[0][i], pt[1] - box[1][j]);\n            if (std::abs(d - dist[i][j]) < 1e-12)\n            {\n                auto handle = v_it.handle();\n                LOG(info1) << \"Locking corner vertex \" << handle.idx();\n                omMesh.status(handle).set_locked(true);\n            }\n        }\n    }\n}\n\nmath::Extents2 prepareMeshImpl(OMMesh &omMesh, const Mesh& mesh\n                               , const SimplifyOptions &options)\n{\n    math::Extents2 me;\n    me = toOpenMesh(mesh, omMesh);\n    omMesh.update_normals();\n\n    // lock the corner and/or border vertices based on flags\n    if (options.check(SimplifyOption::CORNERS)) {\n        lockCorners(omMesh);\n    }\n    if (options.check(SimplifyOption::INNERBORDER)) {\n        lockBorder(omMesh, true, false);\n    }\n    if (options.check(SimplifyOption::OUTERBORDER)) {\n        lockBorder(omMesh, false, true);\n    }\n    // return accumulated extents\n    return me;\n}\n\nmath::Extents2 prepareMesh(OMMesh &omMesh, const Mesh& mesh\n                           , const SimplifyOptions &options)\n{\n    // preprocess mesh - remove non-manifold edges\n    if (options.check(SimplifyOption::RMNONMANIFOLDEDGES)) {\n        auto pmesh(geometry::removeNonManifoldEdges(mesh));\n        return prepareMeshImpl(omMesh, *pmesh, options);\n    } else {\n        return prepareMeshImpl(omMesh, mesh, options);\n    }\n}\n\nmath::Extents2 prepareMesh(OMMesh &omMesh, Mesh&& mesh\n                           , const SimplifyOptions &options)\n{\n    // preprocess mesh - remove non-manifold edges\n    if (options.check(SimplifyOption::RMNONMANIFOLDEDGES)) {\n        auto pmesh(geometry::removeNonManifoldEdges(std::move(mesh)));\n        return prepareMeshImpl(omMesh, *pmesh, options);\n    } else {\n        return prepareMeshImpl(omMesh, mesh, options);\n    }\n}\n\nvoid prepareDecimator(Decimator &decimator\n                      , const SimplifyOptions &options)\n{\n    if (options.alternativeVertices()) {\n        if (options.concaveVertexModifier()) {\n            LOGTHROW (err3, std::runtime_error) <<\n                \"Concave/Convex modification is not \"\n                \"implemented for alternative verteces\";\n        }\n        HModQuadricHybrid hModQuadricHybrid;\n        decimator.add(hModQuadricHybrid);\n        decimator.module(hModQuadricHybrid)\n            .setAlternativeVertices(options.alternativeVertices());\n\n        if (options.maxError()) {\n            decimator.module(hModQuadricHybrid)\n                .set_max_err(*options.maxError(), false);\n        }\n    } else if (options.concaveVertexModifier()){\n#if OM_VERSION >= 0x60000\n        // collapse priority based on vertex error quadric\n        // adjusted by convexity of the vertex\n        HModQuadricConvex hModQuadricConvex;\n        decimator.add(hModQuadricConvex);\n        decimator.module(hModQuadricConvex).\n            set_concave_vertex_modifier(*options.concaveVertexModifier());\n        if (options.maxError()) {\n            decimator.module(hModQuadricConvex)\n                .set_max_err(*options.maxError(), false);\n        }\n#else\n        LOGTHROW (err3, std::runtime_error) <<\n            \"Concave/Convex decimater is not available on this system.\";\n#endif\n    } else if (options.vertexWeights()) {\n        HModWeightedQuadric hModWeightedQuadric;\n        decimator.add(hModWeightedQuadric);\n        decimator.module(hModWeightedQuadric).setWeights(*options.vertexWeights());\n        if (options.maxError()) {\n            decimator.module(hModWeightedQuadric).set_max_err(*options.maxError(), false);\n        }\n    } else {\n        // collapse priority based on vertex error quadric\n        HModQuadric hModQuadric;\n        decimator.add(hModQuadric);\n        if (options.maxError()) {\n            decimator.module(hModQuadric)\n                .set_max_err(*options.maxError(), false);\n        }\n    }\n\n    // apply normal flipping prevention (if configured)\n    if (options.check(SimplifyOption::PREVENTFACEFLIP)) {\n        HModNormalFlippingT hModNormalFlippingT;\n        decimator.add(hModNormalFlippingT);\n        decimator.module(hModNormalFlippingT).set_max_normal_deviation(90);\n    }\n\n    // apply aspect ratio (if configured)\n    if (options.minAspectRatio()) {\n        HModAspectRatioT h;\n        decimator.add(h);\n        decimator.module(h).set_aspect_ratio(*options.minAspectRatio());\n    }\n\n    // apply max edge lenght (if configured)\n    if (options.maxEdgeLength()) {\n        HModEdgeLengthT h;\n        decimator.add(h);\n        decimator.module(h).set_edge_length(*options.maxEdgeLength());\n    }\n}\n\n} // namespace\n\nMesh::pointer simplify(const Mesh &mesh, int faceCount\n                       , const SimplifyOptions &options)\n{\n    OMMesh omMesh;\n    prepareMesh(omMesh, mesh, options);\n\n    Decimator decimator(omMesh);\n    prepareDecimator(decimator, options);\n    decimator.initialize();\n\n    decimator.decimate_to_faces(0, faceCount);\n    omMesh.garbage_collection();\n\n    auto newMesh(std::make_shared<geometry::Mesh>());\n    fromOpenMesh(omMesh, *newMesh);\n    return newMesh;\n}\n\nvoid simplifyInPlace(Mesh& mesh, int faceCount, const SimplifyOptions& options) {\n    OMMesh omMesh;\n    prepareMesh(omMesh, std::move(mesh), options);\n\n    Decimator decimator(omMesh);\n    prepareDecimator(decimator, options);\n    decimator.initialize();\n\n    decimator.decimate_to_faces(0, faceCount);\n    omMesh.garbage_collection();\n\n    mesh.vertices.clear();\n    mesh.faces.clear();\n    fromOpenMesh(omMesh, mesh);\n}\n\n#if OM_VERSION >= 0x60000\n\nMesh::pointer simplifyToError(const Mesh &mesh, double maxErr\n                            , const SimplifyOptions &options)\n{\n    OMMesh omMesh;\n\n    prepareMesh(omMesh, mesh, options);\n\n    Decimator decimator(omMesh);\n    HModQuadric hModQuadric; // collapse priority based on vertex error quadric\n    decimator.add(hModQuadric);\n    decimator.module( hModQuadric ).set_max_err(maxErr, false);\n\n    if (options.classBasedPlanarisation()) {\n        HModClassRestrictT hModClassRestrictT;\n        decimator.add (hModClassRestrictT);\n        // Some hardcoded classes allowed for decimation\n        decimator.module(hModClassRestrictT).allow(13);\n        decimator.module(hModClassRestrictT).allow(14);\n        decimator.module(hModClassRestrictT).allow(15);\n        decimator.module(hModClassRestrictT).allow(16);\n        decimator.module(hModClassRestrictT).allow(18);\n        decimator.module(hModClassRestrictT).allow(9);\n    }\n    decimator.initialize();\n    decimator.decimate_to_faces(0, 0);\n    omMesh.garbage_collection();\n\n    auto newMesh(std::make_shared<geometry::Mesh>());\n    fromOpenMesh(omMesh, *newMesh);\n    return newMesh;\n}\n#endif\n\nnamespace {\n\ninline std::size_t gridIndexImpl(const math::Size2ll &size\n                                 , const math::Point2 origin\n                                 , const math::Size2f tileSize\n                                 , double x, double y)\n{\n    long long xx((x - origin(0)) / tileSize.width);\n    long long yy((y - origin(1)) / tileSize.height);\n\n    // clamp to grid (values can be outside of grid in case non-integer\n    // tileSize\n    xx = math::clamp<long long>(xx, 0LL, size.width - 1);\n    yy = math::clamp<long long>(yy, 0LL, size.height -1);\n\n    return xx + yy * size.width;\n}\n\nstruct Tiling {\n    math::Size2ll size;\n    math::Point2 origin;\n    math::Size2f tileSize;\n    FacesPerCell::Functor facesPerCell;\n\n    Tiling() : tileSize() {}\n\n    Tiling(const math::Size2ll &size, const math::Point2 &origin\n           , const math::Size2f &tileSize\n           , const FacesPerCell::Functor &facesPerCell)\n        : size(size), origin(origin), tileSize(tileSize)\n        , facesPerCell(facesPerCell)\n    {}\n\n    inline std::size_t gridIndex(double x, double y) const {\n        return gridIndexImpl(size, origin, tileSize, x, y);\n    };\n\n    inline math::Point2 tileLowerLeft(int index){\n        int y = index / size.width;\n        int x = index % size.width;\n\n        return math::Point2(x * tileSize.width + origin(0)\n                            , y * tileSize.height + origin(1));\n    }\n\n    inline std::vector<std::size_t> intersectingCells(math::Point2 triangle[3])\n        const\n    {\n        std::vector<std::size_t> result;\n\n        for(uint x = 0; x < size.width; ++x){\n            for(uint y = 0; y < size.height; ++y){\n                math::Point2 offset(x * tileSize.width\n                                    , y * tileSize.height);\n                math::Point2 ll = origin + offset;\n                math::Point2 ur = ll + math::Point2\n                    (tileSize.width, tileSize.height);\n\n                if(math::triangleRectangleCollision(triangle,ll,ur)){\n                    result.push_back(x + y * size.width);\n                }\n            }\n        }\n        return result;\n    };\n\n    /** Calculate maximum face count in all cells of grid. If real value is\n     *  lower than maximum, set maximum to real value.\n     */\n    std::vector<std::size_t> getMax(const std::vector<std::size_t> &current)\n        const\n    {\n        FacesPerCell fpc(size, origin, tileSize);\n        facesPerCell(fpc);\n\n        // merge minimum values from current and expected face counts\n        auto out(fpc.get());\n        auto icurrent(current.begin());\n        for (auto &value : out) {\n            value = std::min(value, *icurrent++);\n        }\n\n        // done\n        return out;\n    }\n\n    static OpenMesh::MPropHandleT<Tiling> Property;\n};\n\nOpenMesh::MPropHandleT<Tiling> Tiling::Property;\n\ntemplate <typename MeshType>\nclass ModGrid : public OpenMesh::Decimater::ModBaseT<MeshType>\n{\npublic:\n    DECIMATING_MODULE(ModGrid, MeshType, Grid);\n\n    ModGrid(MeshType &mesh)\n        : Base(mesh, true) // true -> binary module!\n        , mesh_(mesh), tiling_()\n    {\n        mesh_.add_property(cells_);\n    }\n\n    ~ModGrid() {\n        mesh_.remove_property(cells_);\n        //stat();\n    }\n\n    virtual void initialize() UTILITY_OVERRIDE {\n        auto &prop(mesh_.mproperty(Tiling::Property));\n        if (!prop.n_elements()) {\n            LOGTHROW(err2, std::runtime_error)\n                << \"Tiling property not set at mesh.\";\n        }\n        tiling_ = &prop[0];\n\n        calculateGrid();\n    }\n\n    virtual float collapse_priority(const CollapseInfo &ci) UTILITY_OVERRIDE {\n        // can be both faces removed?\n        if (canRemove(ci.fl) && canRemove(ci.fr)) {\n            return Base::LEGAL_COLLAPSE;\n        }\n\n        return Base::ILLEGAL_COLLAPSE;\n    }\n\n    virtual void preprocess_collapse(const CollapseInfo &ci) UTILITY_OVERRIDE {\n        removed(ci.fl);\n        removed(ci.fr);\n    }\n\n    virtual void postprocess_collapse(const CollapseInfo &ci) UTILITY_OVERRIDE\n    {\n        // traverse all remaining faces of non-removed vertex\n        for (auto fi(mesh_.vf_begin(ci.v1)), fe(mesh_.vf_end(ci.v1));\n             fi != fe; ++fi)\n        {\n            const auto f(fi.handle());\n            update(f, cell(f), barycenterCell(f));\n        }\n    }\n\n    std::size_t desiredCount() const {\n        return std::accumulate(max_.begin(), max_.end(), std::size_t(0));\n    }\n\nprivate:\n    typedef typename MeshType::FaceHandle FaceHandle;\n    typedef typename MeshType::Scalar Scalar;\n\n    void stat() const {\n        auto ioriginal(original_.begin());\n        auto icurrent(current_.begin());\n        for (auto max : max_) {\n            LOG(info2) << *ioriginal++ << \" -> \" << *icurrent++\n                       << \" (\" << max << \")\";\n        }\n    }\n\n    void calculateGrid() {\n        current_.clear();\n        current_.resize(area(tiling_->size));\n\n        for (const auto &f : mesh_.faces()) {\n            auto cellIndex(barycenterCell(f));\n\n            // assign cell index to face\n            cell(f) = cellIndex;\n\n            // one more face at given cell\n            ++current_[cellIndex];\n        }\n\n        // get face count limits\n        max_ = tiling_->getMax(current_);\n\n        // for statistics\n        original_.assign(current_.begin(), current_.end());\n    }\n\n    inline std::size_t barycenterCell(FaceHandle f) const {\n        // calculate barycenter of face (i.e. average x and y coordinate)\n        math::Point2 p;\n        int valence(0);\n        for (auto vi(mesh_.cfv_iter(f)); vi; ++vi) {\n            const auto &v(mesh_.point(vi.handle()));\n            p(0) += v[0];\n            p(1) += v[1];\n            ++valence;\n        }\n\n        p(0) /= valence;\n        p(1) /= valence;\n\n        return tiling_->gridIndex(p(0), p(1));\n    }\n\n    void removed(FaceHandle fh) {\n        if (fh.is_valid()) {\n            --current_[cell(fh)];\n        }\n    }\n\n    void update(FaceHandle fh, std::size_t oldCell, std::size_t newCell) {\n        if (!fh.is_valid() || (oldCell == newCell)) {\n            return;\n        }\n\n        // new cell index, update\n        --current_[oldCell];\n        ++current_[newCell];\n        cell(fh) = newCell;\n    }\n\n    inline bool canRemove(FaceHandle fh) const {\n        if (!fh.is_valid()) { return true; }\n\n        auto index(cell(fh));\n        return (current_[index] > max_[index]);\n    }\n\n    inline Scalar& cell(FaceHandle fh) {\n        return mesh_.property(cells_, fh);\n    }\n\n    inline const Scalar& cell(FaceHandle fh) const {\n        return mesh_.property(cells_, fh);\n    }\n\n    MeshType &mesh_;\n    Tiling *tiling_;\n    std::vector<std::size_t> current_;\n    std::vector<std::size_t> max_;\n    std::vector<std::size_t> original_;\n    OpenMesh::FPropHandleT<Scalar> cells_;\n};\n\n\n /*\n * OpenMesh module for decimation mesh in grid.\n * Each cell has defined maximal face count and\n * once this face count is reached, incident faces\n * can't be decimated.\n */\ntemplate <typename MeshType>\nclass ModGrid2 : public OpenMesh::Decimater::ModBaseT<MeshType>\n{\npublic:\n    DECIMATING_MODULE(ModGrid2, MeshType, Grid);\n\n    ModGrid2(MeshType &mesh)\n        : Base(mesh, true) // true -> binary module!\n        , mesh_(mesh), tiling_()\n    {\n        mesh_.add_property(cells_);\n    }\n\n    ~ModGrid2() {\n        mesh_.remove_property(cells_);\n        //stat();\n    }\n\n    virtual void initialize() UTILITY_OVERRIDE {\n        auto &prop(mesh_.mproperty(Tiling::Property));\n        if (!prop.n_elements()) {\n            LOGTHROW(err2, std::runtime_error)\n                << \"Tiling property not set at mesh.\";\n        }\n        tiling_ = &prop[0];\n\n        calculateGrid();\n    }\n\n    virtual float collapse_priority(const CollapseInfo &ci) UTILITY_OVERRIDE {\n        // can be both faces removed?\n        if (canRemove(ci.fl) && canRemove(ci.fr)) {\n            return Base::LEGAL_COLLAPSE;\n        }\n\n        return Base::ILLEGAL_COLLAPSE;\n    }\n\n    virtual void preprocess_collapse(const CollapseInfo &ci) UTILITY_OVERRIDE {\n        removed(ci.fl);\n        removed(ci.fr);\n    }\n\n    virtual void postprocess_collapse(const CollapseInfo &ci) UTILITY_OVERRIDE\n    {\n        // traverse all remaining faces of non-removed vertex\n        for (auto fi(mesh_.vf_begin(ci.v1)), fe(mesh_.vf_end(ci.v1));\n             fi != fe; ++fi)\n        {\n            const auto f(fi.handle());\n            update(f);\n        }\n    }\n\n    std::size_t desiredCount() const {\n        return std::accumulate(max_.begin(), max_.end(), std::size_t(0));\n    }\n\nprivate:\n    typedef typename MeshType::FaceHandle FaceHandle;\n    typedef typename MeshType::Scalar Scalar;\n    typedef typename std::vector<std::size_t> CellList;\n    typedef typename std::vector<std::set<FaceHandle>> CellFaces;\n\n    void setCellVerticesAsFeatures(int cellIndex) const{\n        for(const auto &face : cellFaces_[cellIndex]){\n            for (auto vi(mesh_.cfv_iter(face)); vi; ++vi) {\n                mesh_.status(vi.handle()).set_feature(true);\n            }\n        }\n    }\n\n    void printCells() const {\n        LOG(info2) << \"Cells count:\";\n        for (uint i=0; i<current_.size(); ++i) {\n            LOG(info2) << tiling_->tileLowerLeft(i)<<\" - \"<<current_[i];\n        }\n    }\n\n    void stat() const {\n        auto ioriginal(original_.begin());\n        auto icurrent(current_.begin());\n        for (auto max : max_) {\n            LOG(info2) << *ioriginal++ << \" -> \" << *icurrent++\n                       << \" (\" << max << \")\";\n        }\n        printCells();\n    }\n\n    void calculateGrid() {\n        current_.clear();\n        current_.resize(area(tiling_->size));\n        cellFaces_.clear();\n        cellFaces_.resize(area(tiling_->size));\n\n        for (const auto &f : mesh_.faces()) {\n            cellList(f).clear();\n            update(f);\n        }\n\n        // get face count limits\n        max_ = tiling_->getMax(current_);\n\n        // for statistics\n        original_.assign(current_.begin(), current_.end());\n    }\n\n    void removed(FaceHandle fh) {\n        if (fh.is_valid()) {\n            for(auto &cell : cellList(fh)){\n                --current_[cell];\n                cellFaces_[cell].erase(fh);\n            }\n        }\n    }\n\n    void update(FaceHandle fh) {\n        if (!fh.is_valid()) {\n            return;\n        }\n\n        // decrement facecount in old cells\n        for(auto &cell : cellList(fh)) {\n            --current_[cell];\n            cellFaces_[cell].erase(fh);\n        }\n        // recalculate cells\n        calculateCells(fh);\n\n        // increment facecount in new cells\n        for(auto &cell : cellList(fh)) {\n            ++current_[cell];\n            cellFaces_[cell].insert(fh);\n        }\n    }\n\n    inline void calculateCells(FaceHandle fh){\n        math::Point2 vertices[3];\n        uint vc = 0;\n        for (auto vi(mesh_.cfv_iter(fh)); vi; ++vi) {\n            const auto &v(mesh_.point(vi.handle()));\n            vertices[vc](0) =  v[0];\n            vertices[vc](1) =  v[1];\n            vc++;\n        }\n        cellList(fh) = tiling_->intersectingCells(vertices);\n    }\n\n    inline bool canRemove(FaceHandle fh) const {\n        if (!fh.is_valid()) { return true; }\n        for(auto &cell : cellList(fh)){\n            if(current_[cell] <= max_[cell]){\n                setCellVerticesAsFeatures(cell);\n                return false;\n            }\n        }\n        return true;\n    }\n\n    inline CellList& cellList(FaceHandle fh) {\n        return mesh_.property(cells_, fh);\n    }\n\n    inline const CellList& cellList(FaceHandle fh) const {\n        return mesh_.property(cells_, fh);\n    }\n\n    MeshType &mesh_;\n    Tiling *tiling_;\n    std::vector<std::size_t> original_;\n    std::vector<std::size_t> current_;\n    std::vector<std::size_t> max_;\n    OpenMesh::FPropHandleT<CellList> cells_;\n    CellFaces cellFaces_;\n};\n\n\n} // namespace\n\n/** Converts coordinate to grid defined by reference point and cell size.\n *  Coordinates not on grid are rounded down.\n */\ndouble gridExtentsDown(double value, double origin, double size)\n{\n    return std::floor((value - origin) / size) * size + origin;\n}\n\n/** Converts coordinate to grid defined by reference point and cell size.\n *  Coordinates not on grid are rounded up.\n */\ndouble gridExtentsUp(double value, double origin, double size)\n{\n    return std::ceil((value - origin) / size) * size + origin;\n}\n\nmath::Extents2 gridExtents(const math::Extents2 &extents\n                           , const math::Point2 &alignment\n                           , const math::Size2f &cellSize)\n{\n    return {\n        gridExtentsDown(extents.ll(0), alignment(0), cellSize.width)\n        , gridExtentsDown(extents.ll(1), alignment(1), cellSize.height)\n        , gridExtentsUp(extents.ur(0), alignment(0), cellSize.width)\n        , gridExtentsUp(extents.ur(1), alignment(1), cellSize.height)\n    };\n}\n\n\nstd::size_t FacesPerCell::cellIndex(double x, double y) const\n{\n    return gridIndexImpl(gridSize_, origin_, cellSize_, x, y);\n}\n\nmath::Extents2 FacesPerCell::cellExtents(std::size_t index) const\n{\n    // convert linear index to grid index\n    auto i(index % gridSize_.width);\n    auto j(index / gridSize_.width);\n\n    // return extents\n    return math::Extents2(origin_(0) + i * cellSize_.width\n                          , origin_(1) + j * cellSize_.height\n                          , origin_(0) + (i + 1) * cellSize_.width\n                          , origin_(1) + (j + 1) * cellSize_.height);\n}\n\nMesh::pointer simplifyInGrid(const Mesh &mesh, const math::Point2 &alignment\n                             , const math::Size2f &cellSize\n                             , const FacesPerCell::Functor &facesPerCell\n                             , const SimplifyOptions &options)\n{\n    LOG(info2) << \"[simplify] alignment: \"\n               << std::setprecision(15) << alignment;\n    LOG(info2) << \"[simplify] cellSize: \" << cellSize;\n\n    // convert to openmesh structure\n    OMMesh omMesh;\n    math::Extents2 me(prepareMesh(omMesh, mesh, options));\n\n    // calculate grid extents\n    const auto ge(gridExtents(me, alignment, cellSize));\n\n    // grid origin\n    const auto gorigin(ge.ll);\n\n    // grid size\n    const math::Size2ll gsize\n        ((long long) (std::round(((ge.ur(0) - ge.ll(0)) / cellSize.width)))\n         , (long long)(std::round((ge.ur(1) - ge.ll(1)) / cellSize.width)));\n\n    LOG(info2) << \"[simplify] mesh extents: \" << me;\n    LOG(info2) << \"[simplify] gridded mesh extents: \"\n               << std::setprecision(15) << ge;\n    LOG(info2) << \"[simplify] grid size: \" << gsize;\n    LOG(info2) << \"[simplify] grid origin: \" << gorigin;\n\n    // create and add tiling as a mesh property to mesh\n    omMesh.add_property(Tiling::Property);\n    omMesh.mproperty(Tiling::Property).push_back();\n    omMesh.mproperty(Tiling::Property)[0]\n        = Tiling(gsize, gorigin, cellSize, facesPerCell);\n\n    // create and prepare decimator\n    Decimator decimator(omMesh);\n    prepareDecimator(decimator, options);\n\n    // add decimator grid module\n    ModGrid<OMMesh>::Handle hModGrid;\n    decimator.add(hModGrid);\n\n    // initialized\n    decimator.initialize();\n\n    auto fc(decimator.module(hModGrid).desiredCount());\n    LOG(info2) << \"[simplify] Simplifying mesh to \" << fc << \" faces.\";\n    // simplifying to 0 faces, simplification will stop based on grid constraints\n    decimator.decimate_to_faces(0, 0);\n\n    omMesh.garbage_collection();\n\n    auto newMesh(std::make_shared<geometry::Mesh>());\n    fromOpenMesh(omMesh, *newMesh);\n    return newMesh;\n}\n\n\n} // namespace geometry\n", "meta": {"hexsha": "7455ec14458b6968f3751605b2036ee65f99b8e1", "size": 33428, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geometry/meshop-openmesh.cpp", "max_stars_repo_name": "tomas2211/libgeometry", "max_stars_repo_head_hexsha": "003c58cf92e46ac01d506987f47b770929cc799b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-06-23T19:09:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-26T06:52:15.000Z", "max_issues_repo_path": "geometry/meshop-openmesh.cpp", "max_issues_repo_name": "tomas2211/libgeometry", "max_issues_repo_head_hexsha": "003c58cf92e46ac01d506987f47b770929cc799b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-02-23T02:20:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T10:25:19.000Z", "max_forks_repo_path": "geometry/meshop-openmesh.cpp", "max_forks_repo_name": "tomas2211/libgeometry", "max_forks_repo_head_hexsha": "003c58cf92e46ac01d506987f47b770929cc799b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-09-25T05:22:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-17T16:43:00.000Z", "avg_line_length": 31.595463138, "max_line_length": 103, "alphanum_fraction": 0.595668302, "num_tokens": 8500, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.20335982781826212}}
{"text": "/*    Copyright (c) 2010-2019, Delft University of Technology\n *    All rigths reserved\n *\n *    This file is part of the Tudat. Redistribution and use in source and\n *    binary forms, with or without modification, are permitted exclusively\n *    under the terms of the Modified BSD license. You should have received\n *    a copy of the license with this file. If not, please or visit:\n *    http://tudat.tudelft.nl/LICENSE.\n */\n\n#include <iostream>\n#include <cmath>\n\n#include <boost/make_shared.hpp>\n#include <boost/lambda/lambda.hpp>\n\n#include \"tudat/math/basic/coordinateConversions.h\"\n#include \"tudat/astro/basic_astro/physicalConstants.h\"\n#include \"tudat/astro/ephemerides/approximatePlanetPositions.h\"\n#include \"tudat/math/basic/mathematicalConstants.h\"\n#include \"tudat/astro/basic_astro/celestialBodyConstants.h\"\n\n#include \"tudat/simulation/environment_setup/createBodies.h\"\n#include \"tudat/astro/basic_astro/sphericalBodyShapeModel.h\"\n#include \"tudat/astro/ephemerides/simpleRotationalEphemeris.h\"\n//#include \"tudat/astro/reference_frames/referenceFrameTransformations.h\"\n#include \"tudat/interface/spice/spiceRotationalEphemeris.h\"\n\nnamespace tudat\n{\n\nnamespace simulation_setup\n{\n\nusing namespace ephemerides;\nusing namespace gravitation;\nusing namespace basic_astrodynamics;\n\nvoid addAerodynamicCoefficientInterface(\n        const SystemOfBodies& bodies, const std::string bodyName,\n        const std::shared_ptr< AerodynamicCoefficientSettings > aerodynamicCoefficientSettings )\n{\n    if( bodies.count( bodyName ) == 0 )\n    {\n        throw std::runtime_error( \"Error when setting aerodynamic coefficients for body \"+ bodyName + \", body is not found in system of bodies\" );\n    }\n    bodies.at( bodyName )->setAerodynamicCoefficientInterface(\n                createAerodynamicCoefficientInterface( aerodynamicCoefficientSettings, bodyName) );\n}\n\nvoid addRadiationPressureInterface(\n        const SystemOfBodies& bodies, const std::string bodyName,\n        const std::shared_ptr< RadiationPressureInterfaceSettings > radiationPressureSettings )\n{\n    if( bodies.count( bodyName ) == 0 )\n    {\n        throw std::runtime_error( \"Error when setting radiation pressure interface for body \"+ bodyName + \", body is not found in system of bodies\" );\n    }\n    bodies.at( bodyName )->setRadiationPressureInterface(\n                radiationPressureSettings->getSourceBody( ), createRadiationPressureInterface(\n                    radiationPressureSettings, bodyName, bodies ) );\n}\n\nvoid setSimpleRotationSettingsFromSpice(\n        const BodyListSettings& bodySettings, const std::string& bodyName, const double spiceEvaluationTime )\n{\n    if( bodySettings.count( bodyName ) == 0 )\n    {\n        throw std::runtime_error( \"Error when setting simple rotation model settings for body \" +\n                                  bodyName + \", no settings found for this body.\" );\n    }\n\n    Eigen::Quaterniond rotationAtReferenceTime =\n            spice_interface::computeRotationQuaternionBetweenFrames(\n                bodySettings.getFrameOrientation( ), \"IAU_\" + bodyName, spiceEvaluationTime );\n    double rotationRateAtReferenceTime =\n            spice_interface::getAngularVelocityVectorOfFrameInOriginalFrame(\n                bodySettings.getFrameOrientation( ), \"IAU_\" + bodyName, spiceEvaluationTime ).norm( );\n\n    bodySettings.at( bodyName )->rotationModelSettings =\n            std::make_shared< SimpleRotationModelSettings >(\n                bodySettings.getFrameOrientation( ), \"IAU_\" + bodyName, rotationAtReferenceTime,\n                spiceEvaluationTime, rotationRateAtReferenceTime );\n}\n\nvoid addEmptyTabulatedEphemeris(\n        const SystemOfBodies& bodies, const std::string& bodyName, const std::string& ephemerisOrigin )\n{\n    if( bodies.count( bodyName ) ==  0 )\n    {\n        throw std::runtime_error( \"Error when setting empty tabulated ephemeris for body \" + bodyName + \", no such body found\" );\n    }\n    std::string ephemerisOriginToUse = ( ephemerisOrigin == \"\" ) ? bodies.getFrameOrigin( ) : ephemerisOrigin;\n    bodies.at( bodyName )->setEphemeris( std::make_shared< ephemerides::TabulatedCartesianEphemeris< > >(\n                                            std::shared_ptr< interpolators::OneDimensionalInterpolator\n                                            < double, Eigen::Vector6d > >( ), ephemerisOriginToUse, bodies.getFrameOrientation( ) ) );\n\n    bodies.processBodyFrameDefinitions( );\n}\n\nvoid addEmptyTabulatedRotationalEphemeris(\n        const SystemOfBodies& bodies, const std::string& bodyName, const std::string& bodyFixedFrameName )\n{\n    if( bodies.count( bodyName ) ==  0 )\n    {\n        throw std::runtime_error( \"Error when setting empty tabulated rotational ephemeris for body \" + bodyName + \", no such body found\" );\n    }\n    std::string bodyFixedFrameNameToUse = ( bodyFixedFrameName == \"\" ) ? ( bodyName + \"_fixed\" ) : bodyFixedFrameName;\n\n    bodies.at( bodyName )->setRotationalEphemeris( std::make_shared< ephemerides::TabulatedRotationalEphemeris< > >(\n                                            std::shared_ptr< interpolators::OneDimensionalInterpolator\n                                            < double, Eigen::Vector7d > >( ), bodies.getFrameOrientation( ), bodyFixedFrameNameToUse ) );\n}\n\n\n//! Function that determines the order in which bodies are to be created\nstd::vector< std::pair< std::string, std::shared_ptr< BodySettings > > > determineBodyCreationOrder(\n        const std::map< std::string, std::shared_ptr< BodySettings > >& bodySettings )\n{\n    std::vector< std::pair< std::string, std::shared_ptr< BodySettings > > > outputVector;\n\n    // Create vector of pairs (body name and body settings) that is to be created.\n    for( std::map< std::string, std::shared_ptr< BodySettings > >::const_iterator bodyIterator\n         = bodySettings.begin( );\n         bodyIterator != bodySettings.end( ); bodyIterator ++ )\n    {\n        outputVector.push_back( std::make_pair( bodyIterator->first, bodyIterator->second ) );\n    }\n\n    return outputVector;\n}\n\n\n//! Function to create a map of bodies objects.\nSystemOfBodies createSystemOfBodies(\n        const BodyListSettings& bodySettings )\n{\n    std::vector< std::pair< std::string, std::shared_ptr< BodySettings > > > orderedBodySettings\n            = determineBodyCreationOrder( bodySettings.getMap( ) );\n\n    // Declare map of bodies that is to be returned.\n    SystemOfBodies bodyList = SystemOfBodies(\n                bodySettings.getFrameOrigin( ), bodySettings.getFrameOrientation( ) );\n\n    // Create empty body objects.\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        bodyList.createEmptyBody( orderedBodySettings.at( i ).first, false );\n    }\n\n    // Define constant mass for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        const double constantMass = orderedBodySettings.at( i ).second->constantMass;\n        if ( constantMass == constantMass )\n        {\n            bodyList.at( orderedBodySettings.at( i ).first )->setConstantBodyMass( constantMass );\n        }\n    }\n\n    // Create ephemeris objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->ephemerisSettings != nullptr )\n        {\n            bodyList.at( orderedBodySettings.at( i ).first )->setEphemeris(\n                        createBodyEphemeris( orderedBodySettings.at( i ).second->ephemerisSettings,\n                                             orderedBodySettings.at( i ).first ) );\n        }\n    }\n\n    // Create atmosphere model objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->atmosphereSettings != nullptr )\n        {\n            bodyList.at( orderedBodySettings.at( i ).first )->setAtmosphereModel(\n                        createAtmosphereModel( orderedBodySettings.at( i ).second->atmosphereSettings,\n                                               orderedBodySettings.at( i ).first ) );\n        }\n    }\n\n    // Create body shape model objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->shapeModelSettings != nullptr )\n        {\n            bodyList.at( orderedBodySettings.at( i ).first )->setShapeModel(\n                        createBodyShapeModel( orderedBodySettings.at( i ).second->shapeModelSettings,\n                                              orderedBodySettings.at( i ).first ) );\n        }\n    }\n\n    // Create rotation model objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->rotationModelSettings != nullptr )\n        {\n            bodyList.at( orderedBodySettings.at( i ).first )->setRotationalEphemeris(\n                        createRotationModel( orderedBodySettings.at( i ).second->rotationModelSettings,\n                                             orderedBodySettings.at( i ).first, bodyList ) );\n        }\n    }\n\n    // Create gravity field model objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->gravityFieldSettings != nullptr )\n        {\n            bodyList.at( orderedBodySettings.at( i ).first )->setGravityFieldModel(\n                        createGravityFieldModel( orderedBodySettings.at( i ).second->gravityFieldSettings,\n                                                 orderedBodySettings.at( i ).first, bodyList,\n                                                 orderedBodySettings.at( i ).second->gravityFieldVariationSettings ) );\n        }\n    }\n\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->gravityFieldVariationSettings.size( ) > 0 )\n        {\n            bodyList.at( orderedBodySettings.at( i ).first )->setGravityFieldVariationSet(\n                        createGravityFieldModelVariationsSet(\n                            orderedBodySettings.at( i ).first, bodyList,\n                            orderedBodySettings.at( i ).second->gravityFieldVariationSettings ) );\n        }\n    }\n\n    // Create aerodynamic coefficient interface objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        if( orderedBodySettings.at( i ).second->aerodynamicCoefficientSettings != nullptr )\n        {\n            bodyList.at( orderedBodySettings.at( i ).first )->setAerodynamicCoefficientInterface(\n                        createAerodynamicCoefficientInterface(\n                            orderedBodySettings.at( i ).second->aerodynamicCoefficientSettings,\n                            orderedBodySettings.at( i ).first ) );\n        }\n    }\n\n\n    // Create radiation pressure coefficient objects for each body (if required).\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        std::map< std::string, std::shared_ptr< RadiationPressureInterfaceSettings > >\n                radiationPressureSettings\n                = orderedBodySettings.at( i ).second->radiationPressureSettings;\n        for( std::map< std::string, std::shared_ptr< RadiationPressureInterfaceSettings > >::iterator\n             radiationPressureSettingsIterator = radiationPressureSettings.begin( );\n             radiationPressureSettingsIterator != radiationPressureSettings.end( );\n             radiationPressureSettingsIterator++ )\n        {\n            bodyList.at( orderedBodySettings.at( i ).first )->setRadiationPressureInterface(\n                        radiationPressureSettingsIterator->first,\n                        createRadiationPressureInterface(\n                            radiationPressureSettingsIterator->second,\n                            orderedBodySettings.at( i ).first, bodyList ) );\n        }\n\n    }\n\n    for( unsigned int i = 0; i < orderedBodySettings.size( ); i++ )\n    {\n        for( unsigned int j = 0; j < orderedBodySettings.at( i ).second->groundStationSettings.size( ); j++ )\n        {\n            createGroundStation( bodyList.at( orderedBodySettings.at( i ).first ), orderedBodySettings.at( i ).first,\n                     orderedBodySettings.at( i ).second->groundStationSettings.at( j ) );\n        }\n    }\n\n    bodyList.processBodyFrameDefinitions( );\n\n    return bodyList;\n\n}\n\n//! Function to create a simplified system of bodies\nsimulation_setup::SystemOfBodies createSimplifiedSystemOfBodies(const double secondsSinceJ2000)\n{\n    using namespace ephemerides;\n    using namespace gravitation;\n\n    // Creation of bodies\n    SystemOfBodies bodies(\"SSB\",\"ECLIPJ2000\");\n    bodies.createEmptyBody( \"Sun\" );\n    bodies.createEmptyBody( \"Mercury\" );\n    bodies.createEmptyBody( \"Venus\" );\n    bodies.createEmptyBody( \"Earth\" );\n    bodies.createEmptyBody( \"Mars\" );\n    bodies.createEmptyBody( \"Jupiter\" );\n    bodies.createEmptyBody( \"Saturn\" );\n    bodies.createEmptyBody( \"Uranus\" );\n    bodies.createEmptyBody( \"Neptune\" );\n    bodies.createEmptyBody( \"Pluto\" );\n\n    // Ephemerides\n    bodies.getBody( \"Sun\" )->setEphemeris( std::make_shared< ConstantEphemeris >( Eigen::Vector6d::Zero( )) );\n    bodies.getBody( \"Mercury\" )->setEphemeris( std::make_shared< ApproximateGtopEphemeris >(\"Mercury\") );\n    bodies.getBody( \"Venus\" )->setEphemeris( std::make_shared< ApproximateGtopEphemeris >(\"Venus\" ) );\n    bodies.getBody( \"Earth\" )->setEphemeris( std::make_shared< ApproximateGtopEphemeris >(\"Earth\" ) );\n    bodies.getBody( \"Mars\" )->setEphemeris( std::make_shared< ApproximateGtopEphemeris >(\"Mars\" ) );\n    bodies.getBody( \"Jupiter\" )->setEphemeris( std::make_shared< ApproximateGtopEphemeris >(\"Jupiter\" ) );\n    bodies.getBody( \"Saturn\" )->setEphemeris( std::make_shared< ApproximateGtopEphemeris >(\"Saturn\" ) );\n    bodies.getBody( \"Uranus\" )->setEphemeris( std::make_shared< ApproximateGtopEphemeris >(\"Uranus\" ) );\n    bodies.getBody( \"Neptune\" )->setEphemeris( std::make_shared< ApproximateGtopEphemeris >(\"Neptune\" ) );\n    bodies.getBody( \"Pluto\" )->setEphemeris( std::make_shared< ApproximateGtopEphemeris >(\"Pluto\" ) );\n\n    // Gravity field\n    bodies.getBody( \"Sun\" )->setGravityFieldModel( std::make_shared< GravityFieldModel >(celestial_body_constants::SUN_GRAVITATIONAL_PARAMETER ) );\n    bodies.getBody( \"Mercury\" )->setGravityFieldModel( std::make_shared< GravityFieldModel >( celestial_body_constants::MERCURY_GRAVITATIONAL_PARAMETER ) );\n    bodies.getBody( \"Venus\" )->setGravityFieldModel( std::make_shared< GravityFieldModel >( celestial_body_constants::VENUS_GRAVITATIONAL_PARAMETER ) );\n    bodies.getBody( \"Earth\" )->setGravityFieldModel( std::make_shared< GravityFieldModel >( celestial_body_constants::EARTH_GRAVITATIONAL_PARAMETER ) );\n    bodies.getBody( \"Mars\" )->setGravityFieldModel( std::make_shared< GravityFieldModel >( celestial_body_constants::MARS_GRAVITATIONAL_PARAMETER ) );\n    bodies.getBody( \"Jupiter\" )->setGravityFieldModel( std::make_shared< GravityFieldModel >( celestial_body_constants::JUPITER_GRAVITATIONAL_PARAMETER ) );\n    bodies.getBody( \"Saturn\" )->setGravityFieldModel( std::make_shared< GravityFieldModel >( celestial_body_constants::SATURN_GRAVITATIONAL_PARAMETER ) );\n    bodies.getBody( \"Uranus\" )->setGravityFieldModel( std::make_shared< GravityFieldModel >( celestial_body_constants::URANUS_GRAVITATIONAL_PARAMETER ) );\n    bodies.getBody( \"Neptune\" )->setGravityFieldModel( std::make_shared< GravityFieldModel >( celestial_body_constants::NEPTUNE_GRAVITATIONAL_PARAMETER ) );\n    bodies.getBody( \"Pluto\" )->setGravityFieldModel( std::make_shared< GravityFieldModel >( celestial_body_constants::PLUTO_GRAVITATIONAL_PARAMETER ) );\n\n    // Earth's shape model\n    bodies.getBody( \"Earth\" )->setShapeModel( std::make_shared< SphericalBodyShapeModel >(celestial_body_constants::EARTH_EQUATORIAL_RADIUS ) );\n\n    // Calculate position of rotation axis at initialTime, with respect to J2000 frame. Values from:\n    // \"Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2009\", B.A. Archinal et al.(2011)\n    const double daysSinceJ2000 = secondsSinceJ2000 / 86400;\n    const double centuriesSinceJ2000 = daysSinceJ2000 / 36525;\n    const double poleRightAscension = (0 - 0.641 * centuriesSinceJ2000) * mathematical_constants::PI/180;\n    const double poleDeclination = (90 - 0.557 * centuriesSinceJ2000) * mathematical_constants::PI/180;\n    const double initialRotationAngle = 190.147 * mathematical_constants::PI/180;\n    const double rotationRate = 360.985235 * mathematical_constants::PI/180 / physical_constants::JULIAN_DAY;\n\n    Eigen::Matrix3d J2000toPlanetocentricMatrix = reference_frames::getInertialToPlanetocentricFrameTransformationMatrix (\n            poleDeclination, poleRightAscension, initialRotationAngle);\n    Eigen::Matrix3d ECLIPJ2000toJ2000Matrix = reference_frames::getECLIPJ2000toJ2000TransformationMatrix();\n    Eigen::Matrix3d ECLIPJ2000toPlanetocentricMatrix =  J2000toPlanetocentricMatrix * ECLIPJ2000toJ2000Matrix;\n\n    bodies.getBody( \"Earth\" )->setRotationalEphemeris(std::make_shared< SimpleRotationalEphemeris >(\n                    Eigen::Quaterniond(ECLIPJ2000toPlanetocentricMatrix),\n                    rotationRate, secondsSinceJ2000, \"ECLIPJ2000\", \"Earth_Fixed\" ) );\n\n    return bodies;\n}\n\n} // namespace simulation_setup\n\n} // namespace tudat\n", "meta": {"hexsha": "1c46a110ab38d4e53f1f1c3e0d26786a6857c117", "size": 17508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/simulation/environment_setup/createBodies.cpp", "max_stars_repo_name": "kimonito98/tudat", "max_stars_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/simulation/environment_setup/createBodies.cpp", "max_issues_repo_name": "kimonito98/tudat", "max_issues_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simulation/environment_setup/createBodies.cpp", "max_forks_repo_name": "kimonito98/tudat", "max_forks_repo_head_hexsha": "c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 50.6011560694, "max_line_length": 156, "alphanum_fraction": 0.6781471327, "num_tokens": 4132, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635841117624, "lm_q2_score": 0.3174262655876759, "lm_q1q2_score": 0.20335464264758704}}
{"text": "#pragma once\n#include \"MpmSimulationBase.h\"\n#include <Ziran/Math/Geometry/SourceCollisionObject.h>\n\n#include <math.h>\n\n#include <math.h>\n\n#include <tbb/concurrent_unordered_map.h>\n#include <tbb/tbb.h>\n\n#include <Eigen/Core>\n#include <Eigen/Dense>\n#undef B2\n\n#include <Ziran/CS/Util/Timer.h>\n#include <Ziran/Math/Geometry/Particles.h>\n#include <Ziran/Math/Geometry/AnalyticLevelSet.h>\n#include <Ziran/Math/Geometry/CollisionObject.h>\n#include <Ziran/Math/Geometry/PartioIO.h>\n#include <Ziran/Math/Splines/BSplines.h>\n#include <Ziran/Physics/LagrangianForce/Inertia.h>\n#include <Ziran/Physics/LagrangianForce/LagrangianForce.h>\n#include <Ziran/Sim/DiffTest.h>\n#include <Ziran/Sim/Scene.h>\n\n#include <MPM/Force/MpmForceBase.h>\n#include \"MpmSimulationDataAnalysis.h\"\n\nnamespace ZIRAN {\n\ntemplate <class T, int dim>\nMpmSimulationBase<T, dim>::MpmSimulationBase()\n    : transfer_scheme(APIC_blend_RPIC)\n    , apic_rpic_ratio((T)1)\n    , flip_pic_ratio((T)0)\n    , flip_rpic_ratio((T)0)\n    , print_stats(false)\n    , write_partio(true)\n    , write_meshes(true)\n    , use_particle_collision(false)\n    , autorestart(true)\n    , gravity(TV::Unit(1) * (0))\n    , cfl((T).6)\n    , dx(1)\n    , dt((T)1.0 / 24)\n    , element_partitions(0)\n    , particles(scene.particles)\n    , element_measure(particles.add(element_measure_name<T>()))\n    , objective(*this)\n    , newton(objective, (T)1e-5, 3)\n    , force((forces.emplace_back(std::make_unique<MpmForceBase<T, dim>>(mls_mpm, dx, dt, particles, scene, scratch_xp, scratch_vp, scratch_fp, scratch_gradV, scratch_stress, dv, vn, grid, particle_base_offset, particle_order, particle_group, block_offset, num_nodes, plasticity_appliers, full_implicit)), forces.back()))\n{\n    symplectic = true;\n    quasistatic = false;\n    openvdb::initialize();\n    inertia = std::make_unique<MassLumpedInertia<T, dim>>(mass_matrix, dv, dt);\n    explicit_velocity_field = nullptr;\n    ignoreCollisionObject = false;\n    mls_mpm = false;\n    useTrialCollision = true; //default to true\n}\n\ntemplate <class T, int dim>\nMpmSimulationBase<T, dim>::~MpmSimulationBase()\n{\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::setDx(const T new_dx)\n{\n    dx = new_dx;\n}\n\ntemplate <class T, int dim>\nauto MpmSimulationBase<T, dim>::getMpmForce() -> MpmForceBase<T, dim>*\n{\n    return force.get();\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::addCollisionObject(AnalyticCollisionObject<T, dim>&& object)\n{\n    collision_objects.emplace_back(std::make_unique<AnalyticCollisionObject<T, dim>>(std::move(object)));\n}\n\ntemplate <class T, int dim>\nint MpmSimulationBase<T, dim>::addSourceCollisionObject(SourceCollisionObject<T, dim>&& object)\n{\n    collision_objects.emplace_back(std::make_unique<SourceCollisionObject<T, dim>>(std::move(object)));\n    return collision_objects.size() - 1;\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::initialize()\n{\n    ZIRAN_TIMER();\n    Base::initialize();\n    ZIRAN_INFO(\"Initialize called\");\n    ZIRAN_INFO(\"end_frame = \", end_frame);\n\n    if (mls_mpm) {\n        ZIRAN_ASSERT(transfer_scheme == APIC_blend_RPIC && interpolation_degree != 1 && symplectic == true,\n            \"mls_mpm requires apic quadratic/cubic and only supports explicit for now\");\n        ZIRAN_INFO(\"Using mls_mpm.\");\n    }\n\n    if ((transfer_scheme == APIC_blend_RPIC)\n        && interpolation_degree != 1) {\n\n        // use datamanager to store C\n        particles.add(C_name<TM>());\n        // compute D inverse\n        T dx2 = dx * dx;\n        if constexpr (interpolation_degree == 2)\n            D_inverse = 4 / dx2;\n        else if (interpolation_degree == 3)\n            D_inverse = 3 / dx2;\n        else\n            ZIRAN_ASSERT(false);\n\n        ZIRAN_ASSERT(apic_rpic_ratio >= 0 && apic_rpic_ratio <= 1);\n\n        // resize C array\n        const DisjointRanges& x_range = particles.X.ranges;\n        particles.DataManager::get(C_name<TM>()).lazyResize(x_range, TM::Zero());\n    }\n\n    if (!symplectic) {\n        objective.initialize(\n            [&](TVStack& dv) {\n                for (auto iter = collision_nodes.begin(); iter != collision_nodes.end(); ++iter) {\n                    int node_id = (*iter).node_id;\n                    (*iter).project(dv.col(node_id));\n                }\n            });\n    }\n\n    for (auto& em : scene.element_managers) {\n        em->registerParticleReorderingCallback(particles);\n    }\n\n    writeSimulationInformation();\n\n    ZIRAN_INFO(\"Registering restart callback for collider state update.\");\n    restart_callbacks.emplace_back([this](int frame) {\n        for (size_t k = 0; k < collision_objects.size(); ++k) {\n            if (collision_objects[k]->updateState) {\n                collision_objects[k]->updateState(step.time, *collision_objects[k]);\n            }\n        }\n    });\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::reinitialize()\n{\n    ZIRAN_TIMER();\n    Base::reinitialize();\n\n    if (!restarting) {\n        if (element_partitions) {\n            int count = 0;\n            bool repartitioned = false;\n            for (auto& em : scene.element_managers) {\n                if (em && em->needRepartitioning()) {\n                    repartitioned = true;\n                    em->partitionAndReindexElements(element_partitions);\n\n                    if (count++ == 0) {\n\n                        StdVector<int> old_to_new;\n                        StdVector<int> new_to_old;\n                        if (em->renumberParticles(particles.count, old_to_new, new_to_old)) {\n                            particles.reorder(new_to_old);\n                        }\n                    }\n                }\n            }\n\n            if (repartitioned) {\n\n                scene.segmesh_to_write.indices.clear();\n                AttributeName<int> no_write(\"no_write\");\n\n                for (auto& em : scene.element_managers) {\n\n                    // TODO: rebuild boundary for tet mesh\n\n                    if (SimplexElements<T, 2, dim>* tris = dynamic_cast<SimplexElements<T, 2, dim>*>(em.get()))\n                        scene.trimesh_to_write.indices = tris->indices.array;\n\n                    if (SimplexElements<T, 1, dim>* segs = dynamic_cast<SimplexElements<T, 1, dim>*>(em.get())) {\n                        if (!segs->exist(no_write)) {\n                            ZIRAN_INFO(\"segmesh_to_write did not find no_write tag\");\n                            scene.segmesh_to_write.indices = segs->indices.array;\n                        }\n                        else {\n                            ZIRAN_INFO(\"segmesh_to_write found no_write tag\");\n                            DataArray<int>& no_write_array = segs->get(no_write);\n                            for (size_t z = 0; z < segs->indices.array.size(); ++z) {\n                                if (no_write_array.valueId(z) == -1) // that means z is not labled no write\n                                    scene.segmesh_to_write.indices.push_back(segs->indices.array[z]);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // TODO: Fix the restarting flag\n    ZIRAN_INFO(\"calling mpmsimulationbase reinitialize\");\n    ZIRAN_INFO(\"collision object refresh to time = \", step.time);\n    ZIRAN_INFO(\"restarting = \", restarting); // TODO: SimulationBase already sets this to false (see simulate()).\n    for (size_t k = 0; k < collision_objects.size(); ++k) {\n        if (step.time == 0 || restarting) {\n            if (collision_objects[k]->updateState) {\n                // ZIRAN_INFO(\"Time=0 or restarting, in reinitialize, updating collision object to time \", step.time);\n                collision_objects[k]->updateState(step.time, *collision_objects[k]);\n            }\n        }\n        else {\n            if (collision_objects[k]->updateState) {\n                // ZIRAN_INFO(\"Calling in reinitialize anyway, to update collision object to time \", step.time);\n                collision_objects[k]->updateState(step.time, *collision_objects[k]);\n            }\n        }\n    }\n\n    collision_nodes.clear();\n\n    force->reinitialize();\n    inertia->reinitialize();\n\n    sortParticlesAndPolluteGrid();\n\n    // TV\n    scratch_xp.resize(particles.count, TV::Constant(0));\n    scratch_vp.resize(dim, particles.count);\n    scratch_fp.resize(dim, particles.count);\n    // TM\n    scratch_gradV.resize(particles.count, TM::Constant(0));\n    scratch_stress.resize(particles.count, TM::Constant(0));\n    // resize C array\n    if ((transfer_scheme == APIC_blend_RPIC)\n        && interpolation_degree != 1) {\n        const DisjointRanges& x_range = particles.X.ranges;\n        particles.DataManager::get(C_name<TM>()).lazyResize(x_range, TM::Zero());\n    }\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::beginTimeStep(int frame, int substep, double time, double dt)\n{\n    this->dt = dt;\n    for (auto f : begin_time_step_callbacks) {\n        f(frame, substep, time, dt);\n    }\n}\n\ntemplate <class T, int dim>\nT MpmSimulationBase<T, dim>::totalEnergy(std::string info)\n{\n    T pe = 0;\n    for (auto& lf : forces) {\n        pe += lf->totalEnergy();\n    }\n\n    MpmSimulationDataAnalysis<T, dim> mpm_data(*this);\n    T ke = mpm_data.evalTotalKineticEnergyGrid();\n\n    ZIRAN_INFO(info, pe, \" \", ke, \" \", ke + pe);\n    return ke + pe;\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::advanceOneTimeStep(double dt)\n{\n    ZIRAN_TIMER();\n    ZIRAN_INFO(\"Advance one time step from time \", std::setw(7), step.time, \" with                     dt = \", dt);\n\n    reinitialize();\n\n    if (symplectic) {\n        forcesUpdateParticleState();\n        for (auto f : before_p2g_callbacks) {\n            f();\n        }\n        particlesToGrid();\n        for (auto f : before_euler_callbacks) {\n            f();\n        }\n        gridVelocityExplicitUpdate(dt);\n        for (size_t k = 0; k < collision_objects.size(); ++k)\n            if (collision_objects[k]->updateState)\n                collision_objects[k]->updateState(step.time + dt, *collision_objects[k]);\n        if (useTrialCollision) {\n            trialCollision();\n        }\n        gridToParticles(dt);\n    }\n    else {\n        for (auto f : before_p2g_callbacks) {\n            f();\n        }\n        particlesToGrid();\n        for (auto f : before_euler_callbacks) {\n            f();\n        }\n        backwardEulerStep();\n        ZIRAN_INFO(\"After BE (but before G2P), updating collision object to time \", step.time + dt);\n        for (size_t k = 0; k < collision_objects.size(); ++k)\n            if (collision_objects[k]->updateState) {\n                collision_objects[k]->updateState(step.time + dt, *collision_objects[k]);\n            }\n        gridToParticles(dt);\n    }\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::trialCollision()\n{\n    ZIRAN_TIMER();\n\n    ZIRAN_ASSERT(symplectic);\n    grid.iterateGrid([&](IV node, GridState<T, dim>& g) {\n        if (explicit_collision_nodes[g.idx])\n            return;\n        TV vi = g.new_v;\n        TV xi = node.template cast<T>() * dx;\n        AnalyticCollisionObject<T, dim>::trialCollision(collision_objects, xi, dt, vi);\n        g.new_v = vi;\n    });\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::buildAndPassGradVnToMpmForceHelpers()\n{\n    bool need_to_compute = false;\n    for (auto& h : force->helpers) {\n        if (h->needGradVn()) {\n            need_to_compute = true;\n            break;\n        }\n    }\n    if (need_to_compute) {\n        buildGradVn(scratch_gradV);\n        for (auto& h : force->helpers)\n            if (h->needGradVn())\n                h->getGradVn(scratch_gradV);\n    }\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::buildGradVn(StdVector<TM>& grad_vn)\n{\n    // TODO: use real rasterized grad_vn instead of grad_v from previous time step!\n    auto& Xarray = particles.X.array;\n    for (int i = 0; i < particles.count; ++i) {\n        TM& gradVp = grad_vn[i];\n        if (gradVp != gradVp) //check for NAN/unitialized data\n            continue;\n        gradVp = TM::Zero();\n        TV Xp = Xarray[i];\n        BSplineWeights<T, dim> spline(Xp, dx);\n        grid.iterateKernel(spline, particle_base_offset[i], [&](IV node, T w, TV dw, GridState<T, dim>& g) {\n            gradVp.noalias() += g.v * dw.transpose();\n        });\n    }\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::performRpicVelocityFilteringAtBeginningOfTimeStep()\n{\n    ZIRAN_ASSERT(!mls_mpm);\n    ZIRAN_ASSERT(FLIP_blend_PIC == transfer_scheme);\n    ZIRAN_ASSERT(0 == flip_pic_ratio);\n    ZIRAN_ASSERT(1 != ZIRAN_MPM_DEGREE);\n\n    reinitialize();\n    forcesUpdateParticleState();\n\n    particlesToGridWithForceHelper<false, false, true>();\n    num_nodes = grid.getNumNodes();\n    grid.iterateGrid([&](IV node, GridState<T, dim>& g) {\n        if (g.m != 0) {\n            g.v /= g.m;\n        }\n        else {\n            g.v = TV::Zero();\n        }\n    });\n\n    grid.iterateGrid([&](IV node, GridState<T, dim>& g) {\n        g.new_v = g.v;\n    });\n\n    auto* C = ((transfer_scheme == APIC_blend_RPIC) && interpolation_degree != 1)\n        ? &particles.DataManager::get(C_name<TM>())\n        : nullptr;\n    static constexpr bool USE_APIC_BLEND_RPIC = false;\n    static constexpr bool USE_MPM_DEGREE_ONE = false;\n    static constexpr bool USE_MLS_MPM = false;\n    {\n        tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) {\n            for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {\n\n                int i = particle_order[idx];\n                TV& Xp = particles.X[i];\n\n                TV picV = TV::Zero();\n                BSplineWeights<T, dim> spline(Xp, dx);\n                if constexpr (!USE_APIC_BLEND_RPIC) {\n                    TV oldV = TV::Zero();\n                    TM& gradVp = scratch_gradV[i];\n                    gradVp = TM::Zero();\n                    grid.iterateKernel(spline, particle_base_offset[i], [&](IV node, T w, TV dw, GridState<T, dim>& g) {\n                        picV += w * g.new_v;\n                        oldV += w * g.v;\n                        gradVp.noalias() += g.new_v * dw.transpose();\n                    });\n                    particles.V[i] *= flip_pic_ratio;\n                    particles.V[i] += picV - flip_pic_ratio * oldV;\n                }\n                else if constexpr (!USE_MPM_DEGREE_ONE) {\n                    TM Bp = TM::Zero();\n                    TM& gradVp = scratch_gradV[i];\n                    gradVp = TM::Zero();\n                    grid.iterateKernel(spline, particle_base_offset[i], [&](IV node, T w, TV dw, GridState<T, dim>& g) {\n                        picV += w * g.new_v;\n                        TV xi_minus_xp = node.template cast<T>() * dx - Xp;\n                        Bp.noalias() += w * g.new_v * xi_minus_xp.transpose();\n                        // !mls_mpm\n                        if constexpr (!USE_MLS_MPM) {\n                            gradVp.noalias() += g.new_v * dw.transpose();\n                        }\n                    });\n                    particles.V[i] = picV;\n                    TM CC = Bp * D_inverse;\n                    (*C)[i] = ((apic_rpic_ratio + 1) * (T)0.5) * CC + ((apic_rpic_ratio - 1) * (T)0.5) * CC.transpose();\n                    // no check for NAN/unitialized data\n                    if constexpr (USE_MLS_MPM) {\n                        gradVp = (*C)[i];\n                    }\n                }\n                else {\n                    TM& gradVp = scratch_gradV[i];\n                    gradVp = TM::Zero();\n                    grid.iterateKernel(spline, particle_base_offset[i], [&](IV node, T w, TV dw, GridState<T, dim>& g) {\n                        picV += w * g.new_v;\n                        gradVp.noalias() += g.new_v * dw.transpose();\n                    });\n                    particles.V[i] = picV;\n                }\n            }\n        });\n    }\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::particlesToGrid()\n{\n#if 0\n    {\n        ZIRAN_TIMER();\n        ZIRAN_INFO(\"particle group size \", particle_group.size());\n        for (uint64_t color = 0; color < (1 << dim); ++color) {\n            tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) {\n                if ((block_offset[group_idx] & ((1 << dim) - 1)) != color)\n                    return;\n                for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {\n                    int i = particle_order[idx];\n                    TV& Xp = particles.X.array[i];\n                    T mass = particles.mass.array[i];\n                    BSplineWeights<T, dim> spline(Xp, dx);\n                    grid.iterateKernel(spline, particle_base_offset[i], [&](const IV& node, T w, const TV& dw, GridState<T, dim>& g) {\n                        g.m += w * mass;\n                    });\n                }\n            });\n        }\n        ZIRAN_WARN(\"Just finish normal grid mass p2g\");\n        //getchar();\n    }\n#endif\n    if (symplectic) {\n        ZIRAN_TIMER();\n        if (mls_mpm) {\n            if (transfer_scheme == FLIP_blend_PIC && ZIRAN_MPM_DEGREE == 1)\n                particlesToGridWithForceHelper<false, true, true>();\n            else if (transfer_scheme == FLIP_blend_PIC && ZIRAN_MPM_DEGREE != 1)\n                particlesToGridWithForceHelper<false, false, true>();\n            else if (transfer_scheme == APIC_blend_RPIC && ZIRAN_MPM_DEGREE == 1)\n                particlesToGridWithForceHelper<true, true, true>();\n            else if (transfer_scheme == APIC_blend_RPIC && ZIRAN_MPM_DEGREE != 1)\n                particlesToGridWithForceHelper<true, false, true>();\n        }\n        else {\n            if (transfer_scheme == FLIP_blend_PIC && ZIRAN_MPM_DEGREE == 1)\n                particlesToGridWithForceHelper<false, true, false>();\n            else if (transfer_scheme == FLIP_blend_PIC && ZIRAN_MPM_DEGREE != 1)\n                particlesToGridWithForceHelper<false, false, false>();\n            else if (transfer_scheme == APIC_blend_RPIC && ZIRAN_MPM_DEGREE == 1)\n                particlesToGridWithForceHelper<true, true, false>();\n            else if (transfer_scheme == APIC_blend_RPIC && ZIRAN_MPM_DEGREE != 1)\n                particlesToGridWithForceHelper<true, false, false>();\n        }\n    }\n    else {\n        ZIRAN_TIMER();\n        if (transfer_scheme == FLIP_blend_PIC && ZIRAN_MPM_DEGREE == 1)\n            particlesToGridHelper<false, true>();\n        else if (transfer_scheme == FLIP_blend_PIC && ZIRAN_MPM_DEGREE != 1)\n            particlesToGridHelper<false, false>();\n        else if (transfer_scheme == APIC_blend_RPIC && ZIRAN_MPM_DEGREE == 1)\n            particlesToGridHelper<true, true>();\n        else if (transfer_scheme == APIC_blend_RPIC && ZIRAN_MPM_DEGREE != 1)\n            particlesToGridHelper<true, false>();\n    }\n    {\n        ZIRAN_TIMER();\n        num_nodes = grid.getNumNodes();\n        grid.iterateGrid([&](IV node, GridState<T, dim>& g) {\n            if (g.m != 0) {\n                g.v /= g.m;\n            }\n            else {\n                g.v = TV::Zero();\n            }\n        });\n    }\n}\n\ntemplate <class T, int dim>\ntemplate <bool USE_APIC_BLEND_RPIC, bool USE_MPM_DEGREE_ONE, bool USE_MLS_MPM>\nvoid MpmSimulationBase<T, dim>::particlesToGridWithForceHelper()\n{\n    auto& Xarray = particles.X.array;\n    auto& Varray = particles.V.array;\n    auto& marray = particles.mass.array;\n    const StdVector<Matrix<T, dim, dim>>* Carray_pointer;\n    Carray_pointer = ((transfer_scheme == APIC_blend_RPIC) && interpolation_degree != 1) ? (&(particles.DataManager::get(C_name<TM>()).array)) : NULL;\n\n    {\n        for (uint64_t color = 0; color < (1 << dim); ++color) {\n            tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) {\n                if ((block_offset[group_idx] & ((1 << dim) - 1)) != color)\n                    return;\n                for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {\n                    int i = particle_order[idx];\n                    TV& Xp = Xarray[i];\n                    T mass = marray[i];\n                    TV momentum = marray[i] * Varray[i];\n\n                    TM C = TM::Zero();\n                    if constexpr (USE_APIC_BLEND_RPIC) {\n                        if constexpr (!USE_MPM_DEGREE_ONE) {\n                            C = mass * (*Carray_pointer)[i];\n                        }\n                        else {\n                            const TM& gradVp = scratch_gradV[i];\n                            C = mass * (((apic_rpic_ratio + 1) * (T)0.5) * gradVp + ((apic_rpic_ratio - 1) * (T)0.5) * gradVp.transpose());\n                        }\n                    }\n                    TM4 stress_density = TM4::Zero();\n                    TM& stress = scratch_stress[i];\n                    stress_density.template topLeftCorner<dim, dim>() = stress; // stress density\n                    const TV& fp = scratch_fp.col(i);\n                    stress_density.template topRightCorner<dim, 1>() = -fp; // fp (for meshed forces).\n                    TM4 velocity_density = TM4::Zero();\n                    velocity_density.template topLeftCorner<dim, dim>() = C;\n                    velocity_density.template topRightCorner<dim, 1>() = momentum;\n                    velocity_density(3, 3) = mass;\n                    BSplineWeights<T, dim> spline(Xp, dx);\n                    if constexpr (USE_MLS_MPM) {\n                        grid.iterateKernel(spline, particle_base_offset[i],\n                            [&](IV node, T w, TV dw, GridState<T, dim>& g) {\n                                TV4 xi_minus_xp = TV4::Zero();\n                                xi_minus_xp.template topLeftCorner<dim, 1>() = node.template cast<T>() * dx - Xp; // top dim entries non-zero\n                                xi_minus_xp(3) = 1;\n                                TV4 force_delta = ((stress_density * xi_minus_xp) * (w * D_inverse));\n                                TV4 velocity_delta = velocity_density * xi_minus_xp * w;\n                                g.m += velocity_delta(3);\n                                g.v += velocity_delta.template topLeftCorner<dim, 1>();\n                                g.new_v -= force_delta.template topLeftCorner<dim, 1>(); // fi -= \\sum_p (Ap (xi-xp)  - fp )w_ip Dp_inv\n                            });\n                    }\n                    else {\n                        grid.iterateKernel(spline, particle_base_offset[i],\n                            [&](IV node, T w, TV dw, GridState<T, dim>& g) {\n                                TV4 weight = TV4::Zero();\n                                weight.template topLeftCorner<dim, 1>() = dw;\n                                weight(3) = w;\n                                TV4 xi_minus_xp = TV4::Zero();\n                                xi_minus_xp.template topLeftCorner<dim, 1>() = node.template cast<T>() * dx - Xp; // top dim entries non-zero\n                                xi_minus_xp(3) = 1;\n                                TV4 force_delta = (stress_density * weight);\n                                TV4 velocity_delta = velocity_density * xi_minus_xp * w;\n                                g.m += velocity_delta(3);\n                                g.v += velocity_delta.template topLeftCorner<dim, 1>();\n                                g.new_v -= force_delta.template topLeftCorner<dim, 1>();\n                            });\n                    }\n                }\n            });\n        }\n    }\n}\n\ntemplate <class T, int dim>\ntemplate <bool USE_APIC_BLEND_RPIC, bool USE_MPM_DEGREE_ONE>\nvoid MpmSimulationBase<T, dim>::particlesToGridHelper()\n{\n    auto& Xarray = particles.X.array;\n    auto& Varray = particles.V.array;\n    auto& marray = particles.mass.array;\n    const StdVector<Matrix<T, dim, dim>>* Carray_pointer;\n    Carray_pointer = ((transfer_scheme == APIC_blend_RPIC) && interpolation_degree != 1) ? (&(particles.DataManager::get(C_name<TM>()).array)) : NULL;\n\n    for (uint64_t color = 0; color < (1 << dim); ++color) {\n        tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) {\n            if ((block_offset[group_idx] & ((1 << dim) - 1)) != color)\n                return;\n            for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {\n                int i = particle_order[idx];\n                TV& Xp = Xarray[i];\n                T mass = marray[i];\n                TV momentum = marray[i] * Varray[i];\n                TM C = TM::Zero();\n                if constexpr (USE_APIC_BLEND_RPIC) {\n                    if constexpr (!USE_MPM_DEGREE_ONE) {\n                        C = mass * (*Carray_pointer)[i];\n                    }\n                    else {\n                        const TM& gradVp = scratch_gradV[i];\n                        C = mass * (((apic_rpic_ratio + 1) * (T)0.5) * gradVp + ((apic_rpic_ratio - 1) * (T)0.5) * gradVp.transpose());\n                    }\n                }\n                TM4 velocity_density = TM4::Zero();\n                velocity_density.template topLeftCorner<dim, dim>() = C;\n                velocity_density.template topRightCorner<dim, 1>() = momentum;\n                velocity_density(3, 3) = mass;\n                BSplineWeights<T, dim> spline(Xp, dx);\n                grid.iterateKernel(spline, particle_base_offset[i], [&](const IV& node, T w, const TV& dw, GridState<T, dim>& g) {\n                    TV4 xi_minus_xp = TV4::Zero();\n                    xi_minus_xp.template topLeftCorner<dim, 1>() = node.template cast<T>() * dx - Xp; // top dim entries non-zero\n                    xi_minus_xp(3) = 1;\n                    TV4 velocity_delta = velocity_density * xi_minus_xp * w;\n                    g.m += velocity_delta(3);\n                    g.v += velocity_delta.template topLeftCorner<dim, 1>();\n                });\n            }\n        });\n    }\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::startBackwardEuler()\n{\n    ZIRAN_TIMER();\n    ZIRAN_ASSERT(objective.matrix_free, \"MPM only supports matrix free\");\n\n    buildMassMatrix();\n    objective.setPreconditioner(([&](const TVStack& in, TVStack& out) {\n        for (int i = 0; i < num_nodes; i++) {\n            for (int d = 0; d < dim; d++) {\n                out(d, i) = in(d, i) / mass_matrix(i);\n            }\n        }\n    }));\n\n    dv.resize(dim, num_nodes);\n    vn.resize(dim, num_nodes);\n\n    buildInitialDvAndVnForNewton(); // This also builds collision_nodes\n    // TODO: this should probably be done in objective reinitialize.\n    // Which should be called at the beginning of newton.\n    force->backupStrain();\n    objective.reinitialize(); // Reinitialize matrix sparsity pattern\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::backwardEulerStep()\n{\n    ZIRAN_TIMER();\n    startBackwardEuler();\n    for (auto f : general_callbacks) {\n        f(frame, BeforeNewtonSolve);\n    }\n    // run diff_test if we specify it\n    if (diff_test)\n        runDiffTest<T, dim, Objective>(num_nodes, dv, objective, diff_test_perturbation_scale);\n    newton.solve(dv, verbose);\n    for (auto f : general_callbacks) {\n        f(frame, AfterNewtonSolve);\n    }\n    // run diff_test if we specify it\n    if (diff_test)\n        runDiffTest<T, dim, Objective>(num_nodes, dv, objective, diff_test_perturbation_scale);\n\n    force->restoreStrain();\n\n    constructNewVelocityFromNewtonResult();\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::forcesUpdateParticleState()\n{\n    ZIRAN_TIMER();\n\n    // zero out scratch_fp and scratch_stress, prepare for adding lagrangian force\n    tbb::parallel_for(tbb::blocked_range<size_t>(0, particles.count),\n        [&](const tbb::blocked_range<size_t>& range) {\n                          for (size_t b = range.begin(), b_end = range.end(); b < b_end; ++b) {\n                              scratch_fp.col(b) = TV::Zero();\n                              scratch_stress[b] = TM::Zero(); } });\n    // Lagrangian\n    for (auto& lf : scene.forces)\n        lf->updatePositionBasedState();\n\n    auto& vtau = scratch_stress;\n    auto& fp = scratch_fp;\n    auto ranges = particles.X.ranges;\n    tbb::parallel_for(ranges,\n        [&](DisjointRanges& subrange) {\n            for (auto& h : force->helpers)\n                h->updateState(subrange, vtau, fp); // this adds to vtau and fp\n        });\n\n    // Lagrangian\n    scene.addScaledForces(1, fp); // add forces to fp\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::moveNodes(const TVStack& dv_in)\n{\n    ZIRAN_QUIET_TIMER();\n    if (dv.data() == dv_in.data())\n        return;\n    tbb::parallel_for(tbb::blocked_range<size_t>(0, num_nodes),\n        [&](const tbb::blocked_range<size_t>& range) {\n            for (size_t i = range.begin(), i_end = range.end(); i < i_end; ++i) {\n                dv.col(i) = dv_in.col(i);\n            }\n        });\n}\n\n/**\n       Callback to write the simulation state\n\n       Should be overridden to write the simulation state\n    */\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::writeState(std::ostream& out)\n{\n    ZIRAN_TIMER();\n    ZIRAN_INFO(\"Write state called\");\n\n    if (write_partio) {\n        std::string obj_filename = output_dir.absolutePath(outputFileName(\"partio\", \".bgeo\"));\n        writePartio(obj_filename, particles);\n    }\n\n    scene.writeState(out, outputFileName(\"boundary\", \".obj\"), outputFileName(\"segmesh\", \".poly\"), output_dir, binary_ver, write_meshes);\n\n    if (transfer_scheme == APIC_blend_RPIC && interpolation_degree == 1)\n        writeSTDVector(out, scratch_gradV); // apic C matrix\n}\n\n/**\n       Callback to read the simulation state\n\n       Should be overridden to read the output of writeState\n    */\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::readState(std::istream& in)\n{\n    ZIRAN_QUIET_TIMER();\n    ZIRAN_INFO(\"Read state called\");\n    scene.readState(in, binary_ver);\n\n    if (transfer_scheme == APIC_blend_RPIC && interpolation_degree == 1)\n        readSTDVector(in, scratch_gradV); // apic C matrix\n}\n\n/**\n       Callback to calculate dt based on CFL\n    */\ntemplate <class T, int dim>\ndouble MpmSimulationBase<T, dim>::calculateDt()\n{\n    ZIRAN_QUIET_TIMER();\n    TV p_min_corner, p_max_corner;\n    Eigen::Array<T, 2, 1> max_speed = evalMaxParticleSpeed(p_min_corner, p_max_corner);\n    ZIRAN_INFO(\"Particle Min Corner: \", p_min_corner.transpose());\n    ZIRAN_INFO(\"Particle Max Corner: \", p_max_corner.transpose());\n    p_min_corner.array() -= (interpolation_degree + 2) * dx; // expand by influenced region and buffer\n    p_max_corner.array() += (interpolation_degree + 2) * dx;\n    ZIRAN_INFO(\"Maximum particle speed: \", max_speed(0));\n    ZIRAN_ASSERT(max_speed(0) == max_speed(1));\n    T max_collision_object_speed = 0;\n    for (size_t k = 0; k < collision_objects.size(); ++k)\n        max_collision_object_speed = std::max(collision_objects[k]->evalMaxSpeed(p_min_corner, p_max_corner), max_collision_object_speed);\n    ZIRAN_INFO(\"Maximum collision object speed: \", max_collision_object_speed);\n    max_speed(1) = std::max(max_speed(1), max_collision_object_speed);\n    double dt_compute = step.max_dt;\n    if (max_speed(1))\n        dt_compute = cfl * dx / max_speed(1);\n    ZIRAN_INFO(\"Computed next dt (based on CFL): \", dt_compute);\n\n    //if (step.time == 0) return std::min(dt_compute, (double)1e-4);\n    return dt_compute;\n}\n\n// Build and mass_matrix (for implicit)\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::buildMassMatrix()\n{\n    ZIRAN_QUIET_TIMER();\n    mass_matrix.resize(num_nodes, 1);\n\n    grid.iterateGrid([&](IV node, GridState<T, dim>& g) {\n        mass_matrix(g.idx) = g.m;\n    });\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::addScaledForces(const T scale, TVStack& f) // called BE Newton objective (for computing residual)\n{\n    for (auto& lf : forces)\n        lf->addScaledForces(scale, f);\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::addScaledForceDifferentials(const T scale, const TVStack& x, TVStack& f) // called BE Newton objective (for computing residual)\n{\n    for (auto& lf : forces)\n        lf->addScaledForceDifferential(scale, x, f);\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::gridVelocityExplicitUpdate(double dt)\n{\n    ZIRAN_TIMER();\n    assert(symplectic);\n\n    explicit_collision_nodes.resize((int)num_nodes, 0);\n\n    TV dv_gravity = gravity * dt;\n    if (explicit_velocity_field) {\n        grid.iterateGrid([&](IV node, GridState<T, dim>& g) {\n            T mi = g.m;\n            TV xi = node.template cast<T>() * dx;\n            TV vi = g.v;\n            explicit_velocity_field(mi, xi, vi);\n            g.new_v = vi;\n        });\n    }\n    else {\n        grid.iterateGrid([&](IV node, GridState<T, dim>& g) {\n            T mi = g.m;\n            T dt_over_mi = (T)dt / mi;\n            TV xi = node.template cast<T>() * dx;\n            TV old_v = g.v;\n            TV force_value = g.new_v;\n            TV dvijk = force_value * dt_over_mi;\n            TV vi = old_v + dv_gravity + dvijk;\n            TM normal_basis;\n\n            // apply external body force field: fext(x,t)\n            for (auto ff : fext) {\n                TV external_force = ff(xi, (T)(step.time));\n                vi += dt * external_force;\n            }\n            auto old_vi = vi;\n\n            bool collided = AnalyticCollisionObject<T, dim>::\n                multiObjectCollision(collision_objects, xi, vi, normal_basis);\n\n            explicit_collision_nodes[g.idx] = (int)collided;\n\n            if (ignoreCollisionObject)\n                vi = old_vi;\n\n            g.new_v = vi;\n        });\n    }\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::constructNewVelocityFromNewtonResult()\n{\n    ZIRAN_QUIET_TIMER();\n    grid.iterateTouchedGrid([&](IV node, GridState<T, dim>& g) {\n        g.new_v = TV::Zero();\n    });\n    grid.iterateGrid([&](IV node, GridState<T, dim>& g) {\n        g.new_v = g.v + dv.col(g.idx);\n    });\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::gridToParticles(double dt)\n{\n    if (mls_mpm) {\n        ZIRAN_TIMER();\n        if (transfer_scheme == FLIP_blend_PIC && ZIRAN_MPM_DEGREE == 1)\n            gridToParticlesHelper<false, true, true>(dt);\n        else if (transfer_scheme == FLIP_blend_PIC && ZIRAN_MPM_DEGREE != 1)\n            gridToParticlesHelper<false, false, true>(dt);\n        else if (transfer_scheme == APIC_blend_RPIC && ZIRAN_MPM_DEGREE == 1)\n            gridToParticlesHelper<true, true, true>(dt);\n        else if (transfer_scheme == APIC_blend_RPIC && ZIRAN_MPM_DEGREE != 1)\n            gridToParticlesHelper<true, false, true>(dt);\n    }\n    else {\n        ZIRAN_TIMER();\n        if (transfer_scheme == FLIP_blend_PIC && ZIRAN_MPM_DEGREE == 1)\n            gridToParticlesHelper<false, true, false>(dt);\n        else if (transfer_scheme == FLIP_blend_PIC && ZIRAN_MPM_DEGREE != 1)\n            gridToParticlesHelper<false, false, false>(dt);\n        else if (transfer_scheme == APIC_blend_RPIC && ZIRAN_MPM_DEGREE == 1)\n            gridToParticlesHelper<true, true, false>(dt);\n        else if (transfer_scheme == APIC_blend_RPIC && ZIRAN_MPM_DEGREE != 1)\n            gridToParticlesHelper<true, false, false>(dt);\n    }\n}\n\ntemplate <class T, int dim>\ntemplate <bool USE_APIC_BLEND_RPIC, bool USE_MPM_DEGREE_ONE, bool USE_MLS_MPM>\nvoid MpmSimulationBase<T, dim>::gridToParticlesHelper(double dt)\n{\n    std::atomic<bool> faster_than_grid_cell(false);\n    std::atomic<bool> faster_than_half_grid_cell(false);\n    auto* C = ((transfer_scheme == APIC_blend_RPIC) && interpolation_degree != 1)\n        ? &particles.DataManager::get(C_name<TM>())\n        : nullptr;\n\n    //    if constexpr (false) {\n    {\n        tbb::parallel_for(0, (int)particle_group.size(), [&](int group_idx) {\n            for (int idx = particle_group[group_idx].first; idx <= particle_group[group_idx].second; ++idx) {\n                bool local_faster_than_grid_cell = false;\n                bool local_faster_than_half_grid_cell = false;\n\n                int i = particle_order[idx];\n                TV& Xp = particles.X[i];\n\n                TV picV = TV::Zero();\n                BSplineWeights<T, dim> spline(Xp, dx);\n                if constexpr (!USE_APIC_BLEND_RPIC) {\n                    TV oldV = TV::Zero();\n                    TM& gradVp = scratch_gradV[i];\n                    gradVp = TM::Zero();\n                    grid.iterateKernel(spline, particle_base_offset[i], [&](IV node, T w, TV dw, GridState<T, dim>& g) {\n                        picV += w * g.new_v;\n                        oldV += w * g.v;\n                        gradVp.noalias() += g.new_v * dw.transpose();\n                    });\n                    particles.V[i] *= flip_pic_ratio;\n                    particles.V[i] += picV - flip_pic_ratio * oldV;\n                }\n                else if constexpr (!USE_MPM_DEGREE_ONE) {\n                    TM Bp = TM::Zero();\n                    TM& gradVp = scratch_gradV[i];\n                    gradVp = TM::Zero();\n                    grid.iterateKernel(spline, particle_base_offset[i], [&](IV node, T w, TV dw, GridState<T, dim>& g) {\n                        picV += w * g.new_v;\n                        TV xi_minus_xp = node.template cast<T>() * dx - Xp;\n                        Bp.noalias() += w * g.new_v * xi_minus_xp.transpose();\n                        // !mls_mpm\n                        if constexpr (!USE_MLS_MPM) {\n                            gradVp.noalias() += g.new_v * dw.transpose();\n                        }\n                    });\n                    particles.V[i] = picV;\n                    TM CC = Bp * D_inverse;\n                    (*C)[i] = ((apic_rpic_ratio + 1) * (T)0.5) * CC + ((apic_rpic_ratio - 1) * (T)0.5) * CC.transpose();\n                    // no check for NAN/unitialized data\n                    if constexpr (USE_MLS_MPM) {\n                        gradVp = (*C)[i];\n                    }\n                }\n                else {\n                    TM& gradVp = scratch_gradV[i];\n                    gradVp = TM::Zero();\n                    grid.iterateKernel(spline, particle_base_offset[i], [&](IV node, T w, TV dw, GridState<T, dim>& g) {\n                        picV += w * g.new_v;\n                        gradVp.noalias() += g.new_v * dw.transpose();\n                    });\n                    particles.V[i] = picV;\n                }\n\n                TV increment = dt * picV;\n                particles.X[i] += increment; // particle position update is the same for all transfer schemes\n                T inc = increment.squaredNorm();\n                T dx2 = dx * dx;\n                local_faster_than_grid_cell = local_faster_than_grid_cell + (inc > dx2);\n                local_faster_than_half_grid_cell = local_faster_than_half_grid_cell + (inc > dx2 * (T)0.25 * (cfl * cfl));\n                if (local_faster_than_half_grid_cell)\n                    faster_than_half_grid_cell.store(true, std::memory_order_relaxed);\n                if (local_faster_than_grid_cell)\n                    faster_than_grid_cell.store(true, std::memory_order_relaxed);\n            }\n        });\n    }\n\n    static int latest_frame_restarted = 0;\n    if (faster_than_grid_cell && autorestart) {\n        ZIRAN_WARN(\"Particle traveling more than a grid cell detected\");\n        int frame_to_restart = frame - 1;\n        if (step.max_dt <= step.min_dt) {\n            ZIRAN_WARN(\"Unable to shrink dt further\");\n            frame_to_restart--;\n            ZIRAN_ASSERT(frame_to_restart >= start_frame, \"Unstable intial conditions detected, shrink min_dt or change other parameters\");\n        }\n        else {\n            double new_max_dt = std::max(step.max_dt / 2, step.min_dt);\n            ZIRAN_WARN(\"Shrinking max dt to \", new_max_dt);\n\n            restart_callbacks.emplace_back([new_max_dt, this](int frame) {\n                step.max_dt = new_max_dt;\n            });\n        }\n        latest_frame_restarted = std::max(frame_to_restart, latest_frame_restarted);\n        throw RestartException(frame_to_restart);\n    }\n\n    if (!faster_than_half_grid_cell && frame > latest_frame_restarted + 1) {\n        double new_max_dt = std::min(step.max_dt_original, step.max_dt * (double)1);\n        if (new_max_dt != step.max_dt) {\n            ZIRAN_WARN(\"All particles traveled less than half a grid cell\");\n            step.max_dt = new_max_dt;\n            ZIRAN_WARN(\"Increasing max dt to \", step.max_dt);\n        }\n    }\n\n    force->evolveStrain(dt);\n\n    applyPlasticity();\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::applyPlasticity()\n{\n    // Split all particles to subranges.\n    // In parallel, each subrange goes through all plasticity appliers in serial.\n    ZIRAN_QUIET_TIMER();\n    auto ranges = particles.X.ranges;\n    tbb::parallel_for(ranges,\n        [&](DisjointRanges& subrange) {\n            for (auto& p : plasticity_appliers)\n                p->applyPlasticity(subrange, particles);\n        });\n\n    if (use_particle_collision) {\n        particles.parallel_for([&](const auto& X_local, auto& V_local) {\n            for (size_t k = 0; k < collision_objects.size(); ++k)\n                collision_objects[k]->particleCollision(dx, X_local, V_local);\n        },\n            particles.X_name(), particles.V_name());\n    }\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::sortParticlesAndPolluteGrid()\n{\n    auto& Xarray = particles.X.array;\n\n    constexpr int index_bits = (32 - SparseMask::block_bits);\n    ZIRAN_ASSERT(particles.count < (1 << index_bits));\n\n    if (particles.count != (int)particle_sorter.size()) {\n        particle_base_offset.resize(particles.count);\n        particle_sorter.resize(particles.count);\n        particle_order.resize(particles.count);\n    }\n\n    T one_over_dx = (T)1 / dx;\n    tbb::parallel_for(0, particles.count, [&](int i) {\n        uint64_t offset = SparseMask::Linear_Offset(to_std_array(\n            baseNode<interpolation_degree, T, dim>(Xarray[i] * one_over_dx)));\n        particle_sorter[i] = ((offset >> SparseMask::data_bits) << index_bits) + i;\n    });\n\n    tbb::parallel_sort(particle_sorter.begin(), particle_sorter.end());\n\n    particle_group.clear();\n    block_offset.clear();\n    int last_index = 0;\n    for (int i = 0; i < particles.count; ++i)\n        if (i == particles.count - 1 || (particle_sorter[i] >> 32) != (particle_sorter[i + 1] >> 32)) {\n            particle_group.push_back(std::make_pair(last_index, i));\n            block_offset.push_back(particle_sorter[i] >> 32);\n            last_index = i + 1;\n        }\n\n    grid.page_map->Clear();\n    for (int i = 0; i < particles.count; ++i) {\n        particle_order[i] = (int)(particle_sorter[i] & ((1ll << index_bits) - 1));\n        uint64_t offset = (particle_sorter[i] >> index_bits) << SparseMask::data_bits;\n        particle_base_offset[particle_order[i]] = offset;\n        if (i == particles.count - 1 || (particle_sorter[i] >> 32) != (particle_sorter[i + 1] >> 32)) {\n            grid.page_map->Set_Page(offset);\n            if constexpr (dim == 2) {\n                auto x = 1 << SparseMask::block_xbits;\n                auto y = 1 << SparseMask::block_ybits;\n                for (int i = 0; i < 2; ++i)\n                    for (int j = 0; j < 2; ++j)\n                        grid.page_map->Set_Page(SparseMask::Packed_Add(\n                            offset, SparseMask::Linear_Offset(x * i, y * j)));\n            }\n            else {\n                auto x = 1 << SparseMask::block_xbits;\n                auto y = 1 << SparseMask::block_ybits;\n                auto z = 1 << SparseMask::block_zbits;\n                for (int i = 0; i < 2; ++i)\n                    for (int j = 0; j < 2; ++j)\n                        for (int k = 0; k < 2; ++k)\n                            grid.page_map->Set_Page(SparseMask::Packed_Add(\n                                offset, SparseMask::Linear_Offset(x * i, y * j, z * k)));\n            }\n        }\n    }\n    grid.page_map->Update_Block_Offsets();\n\n    auto grid_array = grid.grid->Get_Array();\n    auto blocks = grid.page_map->Get_Blocks();\n    for (int b = 0; b < (int)blocks.second; ++b) {\n        auto base_offset = blocks.first[b];\n        std::memset(&grid_array(base_offset), 0, (size_t)(1 << MpmGrid<T, dim>::log2_page));\n        GridState<T, dim>* g = reinterpret_cast<GridState<T, dim>*>(&grid_array(base_offset));\n        for (int i = 0; i < (int)SparseMask::elements_per_block; ++i)\n            g[i].idx = -1;\n    }\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::buildInitialDvAndVnForNewton()\n{\n    ZIRAN_QUIET_TIMER();\n    assert(!symplectic);\n\n    grid.iterateGrid([&](IV node, GridState<T, dim>& g) {\n        TV old_v = g.v;\n        TV vi = old_v;\n        TV wn;\n\n        const TV xi = node.template cast<T>() * dx;\n        TM normal_basis, R;\n\n        bool any_collision = AnalyticCollisionObject<T, dim>::\n            multiObjectCollision(collision_objects, xi, vi, normal_basis, wn);\n\n        int node_id = g.idx;\n        assert(node_id < num_nodes);\n        if (any_collision) {\n#if 1\n            bool isSlip = wn != TV::Zero();\n            if (isSlip) {\n                R = RotationExtractor<T, dim>::rotate(wn);\n                //ZIRAN_INFO(isSlip ? \"SLIP!\\n\" : \"STICKY!\\n\");\n                //printf(\"normal: %e\\t%e\\t%e\\n\\n%e\\t%e\\t%e\\n%e\\t%e\\t%e\\n%e\\t%e\\t%e\\n\\n\", wn(0), wn(1), wn(2), R(0, 0), R(0, 1), R(0, 2), R(1, 0), R(1, 1), R(1, 2), R(2, 0), R(2, 1), R(2, 2));\n                //getchar();\n            }\n            else\n                R = TM::Identity();\n            CollisionNode<T, dim> Z{ node_id, TM::Identity() - normal_basis * normal_basis.transpose(), /* wn, */ R, R.inverse(), isSlip };\n#else\n            CollisionNode<T, dim> Z{ node_id, TM::Identity() - normal_basis * normal_basis.transpose() };\n#endif\n            collision_nodes.push_back(Z);\n\n            // Newton initial guess for collided nodes.\n            // Setting it this way so that the new velocity constructed after the solve agrees with collision.\n            dv.col(node_id) = vi - old_v;\n        }\n        else\n            dv.col(node_id) = gravity * dt; // Newton initial guess for non-collided nodes\n\n        vn.col(node_id) = old_v;\n    });\n}\n\n/**\n       result(0) is purely particle speed maximum.\n       result(1) is APIC enhanced 'speed' maximum.\n    */\ntemplate <class T, int dim>\nEigen::Array<T, 2, 1> MpmSimulationBase<T, dim>::evalMaxParticleSpeed(TV& min_corner, TV& max_corner)\n{\n    ZIRAN_TIMER();\n    using TArray = Eigen::Array<T, 2 * dim + 2, 1>;\n    TArray init = TArray::Zero();\n    T Tmin = std::numeric_limits<float>::lowest();\n    TV TVmin = TV::Zero();\n    TVmin.array() = Tmin;\n    init << (T)0, (T)0, TVmin, TVmin;\n    TArray result;\n    result = particles.map_reduce(\n        init,\n        [](const TV& position, const TV& velocity) {\n            T velocity_norm = velocity.norm();\n            TArray r;\n            r << velocity_norm, velocity_norm, position, -position;\n            return r;\n        },\n        [](const TArray& a, const TArray& b) {\n            return a.max(b);\n        },\n        particles.X_name(), particles.V_name());\n\n    max_corner = result.template segment<dim>(2);\n    min_corner = -result.template tail<dim>();\n    return result.template head<2>();\n}\n\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::writeSimulationInformation()\n{\n    ZIRAN_INFO(\"Particle count:      \", particles.count);\n    ZIRAN_INFO(\"Grid dx:             \", dx);\n    ZIRAN_INFO(\"Interp degree:       \", interpolation_degree);\n    ZIRAN_INFO(\"Gravity:             \", gravity.transpose());\n    ZIRAN_INFO(\"\");\n    ZIRAN_INFO(\"CFL:                 \", cfl);\n    ZIRAN_INFO(\"Transfer scheme:     \", transfer_scheme);\n    ZIRAN_INFO(\"Print stats:         \", print_stats);\n    ZIRAN_INFO(\"Using mls_mpm:       \", mls_mpm);\n    writeParticlePerCellHistogram();\n}\n\n// Called by writeSimulationInformation\ntemplate <class T, int dim>\nvoid MpmSimulationBase<T, dim>::writeParticlePerCellHistogram()\n{\n    typedef tbb::concurrent_unordered_map<uint64_t, size_t> ConcurrentHash;\n    ConcurrentHash cellParticleCount; // mapping IV to size_t\n    AttributeName<Vector<T, dim>> x_name = Particles<T, dim>::X_name();\n    for (auto iter = particles.iter(x_name); iter; ++iter) {\n        Vector<T, dim>& X = iter.template get<0>();\n        Vector<int, dim> IX = (X / dx).template cast<int>();\n        uint64_t index = SparseMask::Linear_Offset(to_std_array(IX));\n        auto search = cellParticleCount.find(index);\n        if (search == cellParticleCount.end())\n            cellParticleCount[index] = 1;\n        else\n            cellParticleCount[index]++;\n    }\n    StdVector<size_t> number_of_cells_with_particles(101, 0);\n    for (auto& iter : cellParticleCount)\n        number_of_cells_with_particles[std::min(iter.second, (size_t)100)]++;\n\n    for (int i = 0; i < 101; i++) {\n        int count = number_of_cells_with_particles[i];\n        if (count > 0 && i != 100)\n            ZIRAN_INFO(\"Cells with \", std::setw(2), i, \" particles：\", count);\n        else if (count > 0 && i == 100)\n            ZIRAN_INFO(\"Cells with 100 or more particles: \", count);\n    }\n}\n\ntemplate <class T, int dim>\nconstexpr int MpmSimulationBase<T, dim>::interpolation_degree;\n} // namespace ZIRAN\n", "meta": {"hexsha": "fca5e47adf7dd43a81d9fd494dbe62eb761293f4", "size": 49217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lib/MPM/MpmSimulationBase.cpp", "max_stars_repo_name": "littlemine/HOT", "max_stars_repo_head_hexsha": "d8d57be410ed343c3fb37af6020cf5e14a0d1bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2020-04-25T16:21:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-11T03:06:01.000Z", "max_issues_repo_path": "Lib/MPM/MpmSimulationBase.cpp", "max_issues_repo_name": "littlemine/HOT", "max_issues_repo_head_hexsha": "d8d57be410ed343c3fb37af6020cf5e14a0d1bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-06T20:23:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-07T00:44:25.000Z", "max_forks_repo_path": "Lib/MPM/MpmSimulationBase.cpp", "max_forks_repo_name": "penn-graphics-research/HOT", "max_forks_repo_head_hexsha": "d8d57be410ed343c3fb37af6020cf5e14a0d1bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-05-22T19:18:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T04:45:18.000Z", "avg_line_length": 38.8453038674, "max_line_length": 320, "alphanum_fraction": 0.5617571164, "num_tokens": 12272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.36658974324230986, "lm_q1q2_score": 0.2032631907830691}}
{"text": "/*******************************************************************************\n *         Copyright 2003-2012 LASMEA UMR 6602 CNRS/U.B.P\n *         Copyright 2011-2012 LRI    UMR 8623 CNRS/Univ Paris Sud XI\n *\n *          Distributed under the Boost Software License, Version 1.0.\n *                 See accompanying file LICENSE.txt or copy at\n *                     http://www.boost.org/LICENSE_1_0.txt\n ******************************************************************************/\n#ifndef NT2_TOOLBOX_INTERPOL_FUNCTIONS_GENERIC_IDXY_BILINEAR_HPP_INCLUDED\n#define NT2_TOOLBOX_INTERPOL_FUNCTIONS_GENERIC_IDXY_BILINEAR_HPP_INCLUDED\n\n#include <nt2/toolbox/interpol/functions/idxy_bilinear.hpp>\n#include <nt2/include/functions/is_nge.hpp>\n#include <nt2/include/functions/is_nle.hpp>\n#include <nt2/include/functions/if_else.hpp>\n#include <nt2/include/functions/sx.hpp>\n#include <nt2/include/functions/logical_or.hpp>\n#include <nt2/include/functions/oneminus.hpp>\n#include <nt2/include/functions/max.hpp>\n#include <nt2/include/functions/min.hpp>\n#include <nt2/include/functions/idx_linear.hpp>\n#include <nt2/include/functions/minusone.hpp>\n#include <nt2/include/functions/reshape.hpp>\n#include <nt2/include/functions/first_index.hpp>\n#include <nt2/include/functions/last_index.hpp>\n#include <nt2/include/functions/firstnonsingleton.hpp>\n#include <nt2/include/functions/linear_interp.hpp>\n#include <nt2/include/functions/toint.hpp>\n#include <nt2/include/functions/oneplus.hpp>\n#include <nt2/include/functions/floor.hpp>\n#include <nt2/include/functions/sx.hpp>\n#include <nt2/include/functions/expand_to.hpp>\n#include <nt2/include/constants/nan.hpp>\n#include <nt2/core/container/table/table.hpp>\n#include <nt2/sdk/meta/as_integer.hpp>\n#include <nt2/sdk/simd/logical.hpp>\n#include <boost/fusion/include/make_vector.hpp>\n// #include <boost/assert.hpp>\n\nnamespace nt2 { namespace ext\n{\n\n  NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::run_assign_, tag::cpu_\n                            , (A0)(A1)(N1)\n                            , ((ast_<A0, nt2::container::domain>))\n                              ((node_<A1,nt2::tag::idxy_bilinear_,N1,nt2::container::domain>))\n                            )\n  {\n    typedef typename boost::proto::result_of::child_c<A1&,0>::value_type value_t;\n    typedef typename boost::proto::result_of::child_c<A1&,1>::value_type   idx_t;\n    typedef typename boost::proto::result_of::child_c<A1&,2>::value_type   idy_t;\n    typedef typename value_t::value_type                              value_type;\n    typedef typename meta::as_integer<value_type>::type               index_type;\n    typedef typename A0::value_type                                    sale_type;\n    typedef A0&                                                      result_type;\n    typedef typename A0::extent_type                                       ext_t;\n\n    typedef boost::fusion::vector<value_type, value_type>                 f_type;\n\n    result_type operator()(A0& r, A1& inputs) const\n    {\n      //      BOOST_ASSERT_MSG(are_sx_compatible(xi, y), \"Inputs dimensions are not compatible\");\n      const idx_t & xi   =  boost::proto::child_c<1>(inputs);\n      const idx_t & yi   =  boost::proto::child_c<2>(inputs);\n      const value_t & y     =  boost::proto::child_c<0>(inputs);\n      bool extrap = false;\n      std::size_t dim1 = 2;\n      std::size_t dim2 = 1;\n      value_type extrapval1x = Nan<value_type>();\n      value_type extrapval2x = extrapval1x;\n      value_type extrapval1y = extrapval1x;\n      value_type extrapval2y = extrapval1x;\n      choices(inputs, extrap, extrapval1x, extrapval2x, extrapval1y, extrapval2y, dim1, dim2, N1());\n      r.resize(inputs.extent());\n      r = idx_linear(idx_linear(y,xi,true,nt2::_,dim1),yi,true,nt2::_,dim2);\n      if (!extrap) {\n         ext_t sizee; sizee[0] = 1;\n         sizee[dim1-1] = numel(xi);\n         value_type fx = value_type(nt2::first_index(y, dim1));\n         value_type lx = value_type(nt2::last_index(y, dim1));\n         BOOST_AUTO_TPL(z1, nt2::expand_to(nt2::reshape(xi, sizee), size(r)));\n         r = nt2::if_else(boost::simd::is_nge(z1, fx), extrapval1x, r);\n         r = nt2::if_else(boost::simd::is_nle(z1, lx), extrapval2x, r);\n         sizee[dim1-1] = 1;\n         sizee[dim2-1] = numel(yi);\n         value_type fy = value_type(nt2::first_index(y, dim2));\n         value_type ly = value_type(nt2::last_index(y, dim2));\n         BOOST_AUTO_TPL(z2, nt2::expand_to(nt2::reshape(yi, sizee), size(r)));\n         r = nt2::if_else(boost::simd::is_nge(z2, fy), extrapval1x, r);\n         r = nt2::if_else(boost::simd::is_nle(z2, ly), extrapval2x, r);\n      }\n      return r;\n    }\n  private :\n    // three inputs y and xi and yi\n    // idxy_bilinear(y, xi, yi)\n    static void choices(const A1&, bool &,  value_type&, value_type&, value_type&, value_type&,\n                        std::size_t&, std::size_t&, boost::mpl::long_<3> const &)  //nothing to get\n      { }\n    // Four inputs y and xi yi and a bool or a floating\n    // idxy_bilinear(y, xi, yi, true)\n    // idxy_bilinear(y, xi, yi, extrapval)\n    static void choices(const A1& inputs,\n                        bool & extrap,\n                        value_type& extrapval1x, value_type& extrapval2x,\n                        value_type& extrapval1y, value_type& extrapval2y,\n                        std::size_t& dim1, std::size_t& dim2,\n                        boost::mpl::long_<4> const &)\n      {\n        typedef typename boost::proto::result_of::child_c<A1&,3>::type             child3;\n        typedef typename meta::scalar_of<child3>::type                    cref_param_type;\n        typedef typename meta::strip<cref_param_type>::type                    param_type;\n        get(inputs, extrap, extrapval1x, extrapval2x, extrapval1y, extrapval2y, nt2::meta::as_<param_type>());\n      }\n    static void get(const A1& inputs, bool & extrap,\n                    value_type&, value_type&,\n                    value_type&, value_type&,\n                    const nt2::meta::as_<bool> &) //get the bool\n      {\n        extrap =  boost::proto::child_c<3>(inputs);\n      }\n    static void get(const A1& inputs, bool &,\n                    value_type& extrapval1x, value_type& extrapval2x,\n                    value_type& extrapval1y, value_type& extrapval2y,\n                    const nt2::meta::as_<value_type> &)                     //get extrapval/1x/2x/1y/2y common value (default Nan)\n      {\n        extrapval1x =  extrapval2x = extrapval1y = extrapval2y = boost::proto::child_c<3>(inputs);\n      }\n\n    // Five inputs y and xi yi and two floatings\n    static void choices(const A1& inputs,\n                        bool & extrap,\n                        value_type& extrapval1x, value_type& extrapval2x,\n                        value_type& extrapval1y, value_type& extrapval2y,\n                        std::size_t& dim1, std::size_t& dim2,\n                        boost::mpl::long_<5> const &)                //get extrapval/1x/2x and extrapval/1y/2y commons values\n      {\n        extrapval1x = extrapval1y = boost::proto::child_c<3>(inputs);\n        extrapval2x = extrapval2y = boost::proto::child_c<4>(inputs);\n      }\n\n    // Six inputs y and xi yi,  _ or bool and 2 integers\n    static void choices(const A1& inputs,\n                        bool & extrap,\n                        value_type&, value_type&,\n                        value_type&, value_type&,\n                        std::size_t& dim1, std::size_t& dim2,\n                        boost::mpl::long_<6> const &)                //get extrapval/1x/2x and extrapval/1y/2y commons values\n      {\n        typedef typename boost::proto::result_of::child_c<A1&,3>::type             child3;\n        typedef typename meta::scalar_of<child3>::type                    cref_param_type;\n        typedef typename meta::strip<cref_param_type>::type                    param_type;\n        get(inputs, extrap, nt2::meta::as_<param_type>());\n        dim1 = boost::proto::child_c<4>(inputs);\n        dim2 = boost::proto::child_c<5>(inputs);\n      }\n    static void get(const A1& inputs, bool & extrap,\n                    const nt2::meta::as_<bool> &) //get the bool\n      {\n        extrap =  boost::proto::child_c<2>(inputs);\n      }\n    static void get(const A1& inputs, bool & extrap,\n                    const nt2::meta::as_<nt2::container::colon_> &) //nothing to get\n      { }\n\n    // Seven inputs y and xi yi and 4 floating\n    // idxy_bilinear(y, xi, yi, extrapval1x, extrapval2x, extrapval1y, extrapval2y)\n\n    static void choices(const A1& inputs,\n                        bool &,\n                        value_type& extrapval1x, value_type& extrapval2x,\n                        value_type& extrapval1y, value_type& extrapval2y,\n                        std::size_t&, std::size_t&,\n                        boost::mpl::long_<7> const &)\n      {\n        extrapval1x = boost::proto::child_c<3>(inputs);\n        extrapval2x = boost::proto::child_c<4>(inputs);\n        extrapval1y = boost::proto::child_c<5>(inputs);\n        extrapval2y = boost::proto::child_c<6>(inputs);\n      }\n\n    // eight inputs y and xi, yi, 4 floatings,  _, and 2 integer\n    static void choices(const A1& inputs,\n                        bool &,\n                        value_type& extrapval1x, value_type& extrapval2x,\n                        value_type& extrapval1y, value_type& extrapval2y,\n                        std::size_t& dim1, std::size_t& dim2,\n                        boost::mpl::long_<8> const &) //get extrapval1 and extrapval2 and dimension\n      {\n        dim1 =  boost::proto::child_c<7>(inputs);\n        dim2 =  boost::proto::child_c<8>(inputs);\n        extrapval1x = extrapval1y = boost::proto::child_c<3>(inputs);\n        extrapval2x = extrapval2y = boost::proto::child_c<4>(inputs);\n      }\n\n    // ten inputs y and xi, yi, two flotings,  _, and 2 integer\n    static void choices(const A1& inputs,\n                        bool & extrap,\n                        value_type& extrapval1x, value_type& extrapval2x,\n                        value_type& extrapval1y, value_type& extrapval2y,\n                        std::size_t& dim1, std::size_t& dim2,\n                        boost::mpl::long_<10> const &) //get extrapval1 and extrapval2 and dimension\n      {\n        dim1 =  boost::proto::child_c<8>(inputs);\n        dim2 =  boost::proto::child_c<9>(inputs);\n        extrapval1x = boost::proto::child_c<3>(inputs);\n        extrapval2x = boost::proto::child_c<4>(inputs);\n        extrapval1y = boost::proto::child_c<5>(inputs);\n        extrapval2y = boost::proto::child_c<6>(inputs);\n      }\n  };\n} }\n\n\n#endif\n", "meta": {"hexsha": "04ef77f2c236ebc6fa18cf1de493c35c1e990a17", "size": 10561, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "modules/core/interpol/include/nt2/toolbox/interpol/functions/generic/idxy_bilinear.hpp", "max_stars_repo_name": "timblechmann/nt2", "max_stars_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T00:23:53.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:51:18.000Z", "max_issues_repo_path": "modules/core/interpol/include/nt2/toolbox/interpol/functions/generic/idxy_bilinear.hpp", "max_issues_repo_name": "timblechmann/nt2", "max_issues_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/core/interpol/include/nt2/toolbox/interpol/functions/generic/idxy_bilinear.hpp", "max_forks_repo_name": "timblechmann/nt2", "max_forks_repo_head_hexsha": "6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 48.8935185185, "max_line_length": 130, "alphanum_fraction": 0.5813843386, "num_tokens": 2824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2029634566486649}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.\n\n// This file was modified by Oracle on 2014-2021.\n// Modifications copyright (c) 2014-2021 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_INTERFACE_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_INTERFACE_HPP\n\n#include <array>\n\n#include <boost/geometry/algorithms/detail/assign_box_corners.hpp>\n#include <boost/geometry/algorithms/detail/convex_hull/graham_andrew.hpp>\n#include <boost/geometry/algorithms/detail/equals/point_point.hpp>\n#include <boost/geometry/algorithms/detail/for_each_range.hpp>\n#include <boost/geometry/algorithms/detail/select_geometry_type.hpp>\n#include <boost/geometry/algorithms/detail/visit.hpp>\n#include <boost/geometry/algorithms/is_empty.hpp>\n\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/exterior_ring.hpp>\n#include <boost/geometry/core/geometry_types.hpp>\n#include <boost/geometry/core/point_order.hpp>\n#include <boost/geometry/core/ring_type.hpp>\n#include <boost/geometry/core/tag.hpp>\n#include <boost/geometry/core/tags.hpp>\n#include <boost/geometry/core/visit.hpp>\n\n#include <boost/geometry/geometries/adapted/boost_variant.hpp> // For backward compatibility\n#include <boost/geometry/geometries/concepts/check.hpp>\n#include <boost/geometry/geometries/ring.hpp>\n\n#include <boost/geometry/strategies/convex_hull/cartesian.hpp>\n#include <boost/geometry/strategies/convex_hull/geographic.hpp>\n#include <boost/geometry/strategies/convex_hull/spherical.hpp>\n#include <boost/geometry/strategies/default_strategy.hpp>\n\n#include <boost/geometry/util/condition.hpp>\n#include <boost/geometry/util/range.hpp>\n#include <boost/geometry/util/sequence.hpp>\n#include <boost/geometry/util/type_traits.hpp>\n\n\nnamespace boost { namespace geometry\n{\n\n// TODO: This file is named interface.hpp but the code below is not the interface.\n//       It's the implementation of the algorithm.\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail { namespace convex_hull\n{\n\n// Abstraction representing ranges/rings of a geometry\ntemplate <typename Geometry>\nstruct input_geometry_proxy\n{\n    input_geometry_proxy(Geometry const& geometry)\n        : m_geometry(geometry)\n    {}\n\n    template <typename UnaryFunction>\n    inline void for_each_range(UnaryFunction fun) const\n    {\n        geometry::detail::for_each_range(m_geometry, fun);\n    }\n\n    Geometry const& m_geometry;\n};\n\n// Abstraction representing ranges/rings of subgeometries of geometry collection\n// with boxes converted to rings\ntemplate <typename Geometry, typename BoxRings>\nstruct input_geometry_collection_proxy\n{\n    input_geometry_collection_proxy(Geometry const& geometry, BoxRings const& box_rings)\n        : m_geometry(geometry)\n        , m_box_rings(box_rings)\n    {}\n\n    template <typename UnaryFunction>\n    inline void for_each_range(UnaryFunction fun) const\n    {\n        detail::visit_breadth_first([&](auto const& g)\n        {\n            input_geometry_collection_proxy::call_for_non_boxes(g, fun);\n            return true;\n        }, m_geometry);\n\n        for (auto const& r : m_box_rings)\n        {\n            geometry::detail::for_each_range(r, fun);\n        }\n    }\n\nprivate:\n    template <typename G, typename F, std::enable_if_t<! util::is_box<G>::value, int> = 0>\n    static inline void call_for_non_boxes(G const& g, F & f)\n    {\n        geometry::detail::for_each_range(g, f);\n    }\n    template <typename G, typename F, std::enable_if_t<util::is_box<G>::value, int> = 0>\n    static inline void call_for_non_boxes(G const&, F &)\n    {}\n\n    Geometry const& m_geometry;\n    BoxRings const& m_box_rings;\n};\n\n\n// TODO: Or just implement point_type<> for GeometryCollection\n//   and enforce the same point_type used in the whole sequence in check().\ntemplate <typename Geometry, typename Tag = typename tag<Geometry>::type>\nstruct default_strategy\n{\n    using type = typename strategies::convex_hull::services::default_strategy\n        <\n            Geometry\n        >::type;\n};\n\ntemplate <typename Geometry>\nstruct default_strategy<Geometry, geometry_collection_tag>\n    : default_strategy<typename detail::first_geometry_type<Geometry>::type>\n{};\n\n\n// Utilities for output GC and DG\ntemplate <typename G1, typename G2>\nstruct output_polygonal_less\n{\n    template <typename G>\n    using priority = std::integral_constant\n        <\n            int,\n            (util::is_ring<G>::value ? 0 :\n             util::is_polygon<G>::value ? 1 :\n             util::is_multi_polygon<G>::value ? 2 : 3)\n        >;\n\n    static const bool value = priority<G1>::value < priority<G2>::value;\n};\n\ntemplate <typename G1, typename G2>\nstruct output_linear_less\n{\n    template <typename G>\n    using priority = std::integral_constant\n        <\n            int,\n            (util::is_segment<G>::value ? 0 :\n             util::is_linestring<G>::value ? 1 :\n             util::is_multi_linestring<G>::value ? 2 : 3)\n        >;\n\n    static const bool value = priority<G1>::value < priority<G2>::value;\n};\n\ntemplate <typename G1, typename G2>\nstruct output_pointlike_less\n{\n    template <typename G>\n    using priority = std::integral_constant\n        <\n            int,\n            (util::is_point<G>::value ? 0 :\n             util::is_multi_point<G>::value ? 1 : 2)\n        >;\n\n    static const bool value = priority<G1>::value < priority<G2>::value;\n};\n\n\n}} // namespace detail::convex_hull\n#endif // DOXYGEN_NO_DETAIL\n\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n\ntemplate\n<\n    typename Geometry,\n    typename Tag = typename tag<Geometry>::type\n>\nstruct convex_hull\n{\n    template <typename OutputGeometry, typename Strategy>\n    static inline void apply(Geometry const& geometry,\n                             OutputGeometry& out,\n                             Strategy const& strategy)\n    {\n        detail::convex_hull::input_geometry_proxy<Geometry> in_proxy(geometry);        \n        detail::convex_hull::graham_andrew\n            <\n                typename point_type<Geometry>::type\n            >::apply(in_proxy, out, strategy);\n    }\n};\n\n\n// A hull for boxes is trivial. Any strategy is (currently) skipped.\n// TODO: This is not correct in spherical and geographic CS.\ntemplate <typename Box>\nstruct convex_hull<Box, box_tag>\n{\n    template <typename OutputGeometry, typename Strategy>\n    static inline void apply(Box const& box,\n                             OutputGeometry& out,\n                             Strategy const& strategy)\n    {\n        static bool const Close\n            = geometry::closure<OutputGeometry>::value == closed;\n        static bool const Reverse\n            = geometry::point_order<OutputGeometry>::value == counterclockwise;\n\n        std::array<typename point_type<OutputGeometry>::type, 4> arr;\n        // TODO: This assigns only 2d cooridnates!\n        //       And it is also used in box_view<>!\n        geometry::detail::assign_box_corners_oriented<Reverse>(box, arr);\n\n        std::move(arr.begin(), arr.end(), range::back_inserter(out));\n        if (BOOST_GEOMETRY_CONDITION(Close))\n        {\n            range::push_back(out, range::front(out));\n        }\n    }\n};\n\n\ntemplate <typename GeometryCollection>\nstruct convex_hull<GeometryCollection, geometry_collection_tag>\n{\n    template <typename OutputGeometry, typename Strategy>\n    static inline void apply(GeometryCollection const& geometry,\n                             OutputGeometry& out,\n                             Strategy const& strategy)\n    {\n        // Assuming that single point_type is used by the GeometryCollection\n        using subgeometry_type = typename detail::first_geometry_type<GeometryCollection>::type;\n        using point_type = typename geometry::point_type<subgeometry_type>::type;\n        using ring_type = model::ring<point_type, true, false>;\n\n        // Calculate box rings once\n        std::vector<ring_type> box_rings;\n        detail::visit_breadth_first([&](auto const& g)\n        {\n            convex_hull::add_ring_for_box(box_rings, g, strategy);\n            return true;\n        }, geometry);\n\n        detail::convex_hull::input_geometry_collection_proxy\n            <\n                GeometryCollection, std::vector<ring_type>\n            > in_proxy(geometry, box_rings);\n\n        detail::convex_hull::graham_andrew\n            <\n                point_type\n            >::apply(in_proxy, out, strategy);\n    }\n\nprivate:\n    template\n    <\n        typename Ring, typename SubGeometry, typename Strategy,\n        std::enable_if_t<util::is_box<SubGeometry>::value, int> = 0\n    >\n    static inline void add_ring_for_box(std::vector<Ring> & rings, SubGeometry const& box,\n                                        Strategy const& strategy)\n    {\n        Ring ring;\n        convex_hull<SubGeometry>::apply(box, ring, strategy);\n        rings.push_back(std::move(ring));\n    }\n    template\n    <\n        typename Ring, typename SubGeometry, typename Strategy,\n        std::enable_if_t<! util::is_box<SubGeometry>::value, int> = 0\n    >\n    static inline void add_ring_for_box(std::vector<Ring> & , SubGeometry const& ,\n                                        Strategy const& )\n    {}\n};\n\n\ntemplate <typename OutputGeometry, typename Tag = typename tag<OutputGeometry>::type>\nstruct convex_hull_out\n{\n    BOOST_GEOMETRY_STATIC_ASSERT_FALSE(\"This OutputGeometry is not supported.\", OutputGeometry, Tag);\n};\n\ntemplate <typename OutputGeometry>\nstruct convex_hull_out<OutputGeometry, ring_tag>\n{\n    template <typename Geometry, typename Strategies>\n    static inline void apply(Geometry const& geometry,\n                             OutputGeometry& out,\n                             Strategies const& strategies)\n    {\n        dispatch::convex_hull<Geometry>::apply(geometry, out, strategies);\n    }\n};\n\ntemplate <typename OutputGeometry>\nstruct convex_hull_out<OutputGeometry, polygon_tag>\n{\n    template <typename Geometry, typename Strategies>\n    static inline void apply(Geometry const& geometry,\n                             OutputGeometry& out,\n                             Strategies const& strategies)\n    {\n        auto&& ring = exterior_ring(out);\n        dispatch::convex_hull<Geometry>::apply(geometry, ring, strategies);\n    }\n};\n\ntemplate <typename OutputGeometry>\nstruct convex_hull_out<OutputGeometry, multi_polygon_tag>\n{\n    template <typename Geometry, typename Strategies>\n    static inline void apply(Geometry const& geometry,\n                             OutputGeometry& out,\n                             Strategies const& strategies)\n    {\n        typename boost::range_value<OutputGeometry>::type polygon;\n        auto&& ring = exterior_ring(polygon);\n        dispatch::convex_hull<Geometry>::apply(geometry, ring, strategies);\n        // Empty input is checked so the output shouldn't be empty\n        range::push_back(out, std::move(polygon));\n    }\n};\n\ntemplate <typename OutputGeometry>\nstruct convex_hull_out<OutputGeometry, geometry_collection_tag>\n{\n    using polygonal_t = typename util::sequence_min_element\n        <\n            typename traits::geometry_types<OutputGeometry>::type,\n            detail::convex_hull::output_polygonal_less\n        >::type;\n    using linear_t = typename util::sequence_min_element\n        <\n            typename traits::geometry_types<OutputGeometry>::type,\n            detail::convex_hull::output_linear_less\n        >::type;\n    using pointlike_t = typename util::sequence_min_element\n        <\n            typename traits::geometry_types<OutputGeometry>::type,\n            detail::convex_hull::output_pointlike_less\n        >::type;\n\n    // select_element may define different kind of geometry than the one that is desired\n    BOOST_GEOMETRY_STATIC_ASSERT(util::is_polygonal<polygonal_t>::value,\n        \"It must be possible to store polygonal geometry in OutputGeometry.\", polygonal_t);\n    BOOST_GEOMETRY_STATIC_ASSERT(util::is_linear<linear_t>::value,\n        \"It must be possible to store linear geometry in OutputGeometry.\", linear_t);\n    BOOST_GEOMETRY_STATIC_ASSERT(util::is_pointlike<pointlike_t>::value,\n        \"It must be possible to store pointlike geometry in OutputGeometry.\", pointlike_t);\n\n    template <typename Geometry, typename Strategies>\n    static inline void apply(Geometry const& geometry,\n                             OutputGeometry& out,\n                             Strategies const& strategies)\n    {\n        polygonal_t polygonal;\n        convex_hull_out<polygonal_t>::apply(geometry, polygonal, strategies);\n        // Empty input is checked so the output shouldn't be empty\n        auto&& out_ring = ring(polygonal);\n\n        if (boost::size(out_ring) == detail::minimum_ring_size<polygonal_t>::value)\n        {\n            using detail::equals::equals_point_point;\n            if (equals_point_point(range::front(out_ring), range::at(out_ring, 1), strategies))\n            {\n                pointlike_t pointlike;\n                move_to_pointlike(out_ring, pointlike);\n                move_to_out(pointlike, out);\n                return;\n            }\n            if (equals_point_point(range::front(out_ring), range::at(out_ring, 2), strategies))\n            {\n                linear_t linear;\n                move_to_linear(out_ring, linear);\n                move_to_out(linear, out);\n                return;\n            }\n        }\n\n        move_to_out(polygonal, out);\n    }\n\nprivate:\n    template <typename Polygonal, util::enable_if_ring_t<Polygonal, int> = 0>\n    static decltype(auto) ring(Polygonal const& polygonal)\n    {\n        return polygonal;\n    }\n    template <typename Polygonal, util::enable_if_polygon_t<Polygonal, int> = 0>\n    static decltype(auto) ring(Polygonal const& polygonal)\n    {\n        return exterior_ring(polygonal);\n    }\n    template <typename Polygonal, util::enable_if_multi_polygon_t<Polygonal, int> = 0>\n    static decltype(auto) ring(Polygonal const& polygonal)\n    {\n        return exterior_ring(range::front(polygonal));\n    }\n\n    template <typename Range, typename Linear, util::enable_if_segment_t<Linear, int> = 0>\n    static void move_to_linear(Range & out_range, Linear & seg)\n    {\n        detail::assign_point_to_index<0>(range::front(out_range), seg);\n        detail::assign_point_to_index<1>(range::at(out_range, 1), seg);\n    }\n    template <typename Range, typename Linear, util::enable_if_linestring_t<Linear, int> = 0>\n    static void move_to_linear(Range & out_range, Linear & ls)\n    {\n        std::move(boost::begin(out_range), boost::begin(out_range) + 2, range::back_inserter(ls));\n    }\n    template <typename Range, typename Linear, util::enable_if_multi_linestring_t<Linear, int> = 0>\n    static void move_to_linear(Range & out_range, Linear & mls)\n    {\n        typename boost::range_value<Linear>::type ls;\n        std::move(boost::begin(out_range), boost::begin(out_range) + 2, range::back_inserter(ls));\n        range::push_back(mls, std::move(ls));\n    }\n\n    template <typename Range, typename PointLike, util::enable_if_point_t<PointLike, int> = 0>\n    static void move_to_pointlike(Range & out_range, PointLike & pt)\n    {\n        pt = range::front(out_range);\n    }\n    template <typename Range, typename PointLike, util::enable_if_multi_point_t<PointLike, int> = 0>\n    static void move_to_pointlike(Range & out_range, PointLike & mpt)\n    {\n        range::push_back(mpt, std::move(range::front(out_range)));\n    }\n\n    template\n    <\n        typename Geometry, typename OutputGeometry_,\n        util::enable_if_geometry_collection_t<OutputGeometry_, int> = 0\n    >\n    static void move_to_out(Geometry & g, OutputGeometry_ & out)\n    {\n        range::emplace_back(out, std::move(g));\n    }\n    template\n    <\n        typename Geometry, typename OutputGeometry_,\n        util::enable_if_dynamic_geometry_t<OutputGeometry_, int> = 0\n    >\n    static void move_to_out(Geometry & g, OutputGeometry_ & out)\n    {\n        out = std::move(g);\n    }\n};\n\ntemplate <typename OutputGeometry>\nstruct convex_hull_out<OutputGeometry, dynamic_geometry_tag>\n    : convex_hull_out<OutputGeometry, geometry_collection_tag>\n{};\n\n\n// For backward compatibility\ntemplate <typename OutputGeometry>\nstruct convex_hull_out<OutputGeometry, linestring_tag>\n    : convex_hull_out<OutputGeometry, ring_tag>\n{};\n\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_strategy {\n\ntemplate <typename Strategies>\nstruct convex_hull\n{\n    template <typename Geometry, typename OutputGeometry>\n    static inline void apply(Geometry const& geometry,\n                             OutputGeometry& out,\n                             Strategies const& strategies)\n    {\n        dispatch::convex_hull_out<OutputGeometry>::apply(geometry, out, strategies);\n    }\n};\n\ntemplate <>\nstruct convex_hull<default_strategy>\n{\n    template <typename Geometry, typename OutputGeometry>\n    static inline void apply(Geometry const& geometry,\n                             OutputGeometry& out,\n                             default_strategy const&)\n    {\n        using strategy_type = typename detail::convex_hull::default_strategy\n            <\n                Geometry\n            >::type;\n\n        dispatch::convex_hull_out<OutputGeometry>::apply(geometry, out, strategy_type());\n    }\n};\n\n\n} // namespace resolve_strategy\n\n\nnamespace resolve_dynamic {\n\ntemplate <typename Geometry, typename Tag = typename tag<Geometry>::type>\nstruct convex_hull\n{\n    template <typename OutputGeometry, typename Strategy>\n    static inline void apply(Geometry const& geometry,\n                             OutputGeometry& out,\n                             Strategy const& strategy)\n    {\n        concepts::check_concepts_and_equal_dimensions<\n            const Geometry,\n            OutputGeometry\n        >();\n\n        resolve_strategy::convex_hull<Strategy>::apply(geometry, out, strategy);\n    }\n};\n\ntemplate <typename Geometry>\nstruct convex_hull<Geometry, dynamic_geometry_tag>\n{\n    template <typename OutputGeometry, typename Strategy>\n    static inline void apply(Geometry const& geometry,\n                             OutputGeometry& out,\n                             Strategy const& strategy)\n    {\n        traits::visit<Geometry>::apply([&](auto const& g)\n        {\n            convex_hull<util::remove_cref_t<decltype(g)>>::apply(g, out, strategy);\n        }, geometry);\n    }\n};\n\n\n} // namespace resolve_dynamic\n\n\n/*!\n\\brief \\brief_calc{convex hull} \\brief_strategy\n\\ingroup convex_hull\n\\details \\details_calc{convex_hull,convex hull} \\brief_strategy.\n\\tparam Geometry the input geometry type\n\\tparam OutputGeometry the output geometry type\n\\tparam Strategy the strategy type\n\\param geometry \\param_geometry,  input geometry\n\\param out \\param_geometry \\param_set{convex hull}\n\\param strategy \\param_strategy{area}\n\n\\qbk{distinguish,with strategy}\n\n\\qbk{[include reference/algorithms/convex_hull.qbk]}\n */\ntemplate<typename Geometry, typename OutputGeometry, typename Strategy>\ninline void convex_hull(Geometry const& geometry, OutputGeometry& out, Strategy const& strategy)\n{\n    if (geometry::is_empty(geometry))\n    {\n        // Leave output empty\n        return;\n    }\n\n    resolve_dynamic::convex_hull<Geometry>::apply(geometry, out, strategy);\n}\n\n\n/*!\n\\brief \\brief_calc{convex hull}\n\\ingroup convex_hull\n\\details \\details_calc{convex_hull,convex hull}.\n\\tparam Geometry the input geometry type\n\\tparam OutputGeometry the output geometry type\n\\param geometry \\param_geometry,  input geometry\n\\param hull \\param_geometry \\param_set{convex hull}\n\n\\qbk{[include reference/algorithms/convex_hull.qbk]}\n */\ntemplate<typename Geometry, typename OutputGeometry>\ninline void convex_hull(Geometry const& geometry, OutputGeometry& hull)\n{\n    geometry::convex_hull(geometry, hull, default_strategy());\n}\n\n\n}} // namespace boost::geometry\n\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_CONVEX_HULL_INTERFACE_HPP\n", "meta": {"hexsha": "0fa011282f386d60383e34a5e4aca54089001433", "size": 20546, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/boost_1.78.0/boost/geometry/algorithms/detail/convex_hull/interface.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "lib/boost_1.78.0/boost/geometry/algorithms/detail/convex_hull/interface.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "lib/boost_1.78.0/boost/geometry/algorithms/detail/convex_hull/interface.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 33.2998379254, "max_line_length": 101, "alphanum_fraction": 0.6754112723, "num_tokens": 4587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20267465727715742}}
{"text": "#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <iterator>\n#include <cmath>\n#include <regex>\n#include <numeric>\n\n#include <boost/program_options.hpp>\n#include <boost/log/sources/logger.hpp>\n#include <boost/archive/binary_iarchive.hpp>\n#include <boost/archive/binary_oarchive.hpp>\n#include <boost/serialization/map.hpp>\n#include <boost/mpi.hpp>\n#include <boost/core/demangle.hpp>\n#include <boost/numeric/conversion/cast.hpp>\n#include <boost/algorithm/string/trim.hpp>\n#include <boost/algorithm/string/split.hpp>\n#include <boost/range/adaptors.hpp>\n#include <boost/range/algorithm.hpp>\n#include <boost/range/combine.hpp>\n\n\n#include <benchmark.hpp>\n#include <logging.hpp>\n\n#include <blas.hpp>\n#include <matrix_serialization.hpp>\n\n\n\nnamespace po = boost::program_options;\n\nauto init_options() -> po::options_description\n{\n\tpo::options_description description;\n\tdescription.add_options()\n\t\t( \"help\", \"Produce the help message.\" )\n\t\t( \"type\"\n\t\t, po::value<std::string>()->required()\n\t\t, \"Type of an element of the epsilon matrix. It may be \"\n\t\t  \"either cfloat or cdouble.\" )\n\t\t( \"epsilon\"\n\t\t, po::value<std::string>()->required()\n\t\t, \"File to where epsilon matrix was saved to.\" )\n\t\t( \"positions\"\n\t\t, po::value<std::string>()->required()\n\t\t, \"File to where atomic site positions were saved to.\" )\n\t\t( \"q\"\n\t\t, po::value<std::string>()->required()\n\t\t, \"List of |q|s separated by commas. MIND YOU: \"\n\t\t  \"no spaces!\" )\n\t\t( \"direction\"\n\t\t, po::value<std::string>()->required()\n\t\t, \"Direction of q as (x,y,z). It is automatically\"\n\t\t  \"normalized.\" );\n\treturn description;\n}\n\n\nauto element_type(std::string input) -> std::type_index\n{\n\tusing namespace std::string_literals;\n\tstatic std::unordered_map<std::string, std::type_index> const types = \n\t\t{ { \"cfloat\"s,  std::type_index(typeid(std::complex<float>))  }\n\t\t, { \"cdouble\"s, std::type_index(typeid(std::complex<double>)) }\n\t\t};\n\t\n\tboost::to_lower(input);\n\ttry {\n\t\treturn types.at(input);\n\t} catch(std::out_of_range & e) {\n\t\tstd::cerr << \"Invalid element type `\" + input + \"`!\\n\";\n\t\tthrow;\n\t}\n}\n\n\ntemplate <class _R>\nauto parse_direction(std::string str) -> std::array<_R, 3>\n{\n\tusing namespace boost;\n\tusing namespace boost::algorithm;\n\n\tauto const normalize = [](_R const x, _R const y, _R const z) \n\t\t-> std::array<_R, 3> {\n\t\tauto const _abs = _R{1.0} / std::sqrt(std::norm(x) + std::norm(y) + std::norm(z));\n\t\treturn {_abs * x, _abs * y, _abs * z};\n\t};\n\n\tstd::regex vector_re{\"\\\\((.*),(.*),(.*)\\\\)\"};\n\tstd::smatch results;\n\n\ttrim(str);\n\tif (std::regex_match(str, results, vector_re)) {\n\t\tassert(results.size() == 4);\n\t\treturn normalize( lexical_cast<_R>(trim_copy(results[1].str()))\n\t\t                , lexical_cast<_R>(trim_copy(results[2].str()))\n\t\t\t            , lexical_cast<_R>(trim_copy(results[3].str())) );\n\t}\n\tthrow std::invalid_argument{ \"Could not convert '\" + str \n\t                           + \"' to a 3D vector.\"};\n}\n\ntemplate <class _R>\nauto parse_qs(std::string const& str) -> std::vector<_R>\n{\n\tusing namespace boost;\n\tusing namespace boost::adaptors;\n\tusing namespace boost::algorithm;\n\n\tauto const parse_number = [](auto const& s) {\n\t\treturn lexical_cast<_R>(trim_copy(s));\n\t};\n\n\tstd::vector<std::string> tokens;\n\tsplit(tokens, str, [](auto const ch) { return ch == ','; });\n\n\n\tstd::vector<_R> qs;\n\tqs.reserve(tokens.size());\n\tcopy( tokens | transformed(std::cref(parse_number)) \n\t    , std::back_inserter(qs) );\n\treturn qs;\t\n}\n\n\ntemplate<class _Help, class _Run>\nauto process_command_line( int argc, char** argv\n                         , _Help&& help\n\t\t\t\t\t\t , _Run&& run ) -> void\n{\n\tauto const description = init_options();\n\tpo::variables_map vm;\n\n\tpo::store( po::command_line_parser(argc, argv)\n\t              .options(description)\n\t              .run()\n\t         , vm );\n\n\tif (vm.count(\"help\")) {\n\t\thelp(description);\n\t\treturn;\n\t}\n\n\tpo::notify(vm);\n\trun(vm);\n}\n\n\ntemplate<class _T>\nauto load_matrix(std::string const& file_name) -> tcm::Matrix<_T>\n{\n\tstd::ifstream in_stream{file_name};\n\tif (not in_stream)\n\t\tthrow std::runtime_error{\"Failed to open `\" + file_name + \"`.\"};\n\tboost::archive::binary_iarchive in_archive{in_stream};\n\n\ttcm::Matrix<_T> A;\n\tin_archive >> A;\n\treturn A;\n}\n\n\ntemplate<class _T>\nauto read_positions(std::string const& file_name) \n\t-> std::vector<std::array<_T, 3>>\n{\n\tstd::ifstream in_stream{file_name};\n\tif (not in_stream)\n\t\tthrow std::runtime_error{\"Failed to open `\" + file_name + \"`.\"};\n\n\tstd::vector<std::array<_T, 3>> positions;\n\tauto i = std::istream_iterator<_T>{in_stream};\n\twhile(i != std::istream_iterator<_T>{}) {\n\t\tconst auto x = *i++;\n\t\tconst auto y = *i++;\n\t\tconst auto z = *i++;\n\t\tpositions.push_back({x, y, z});\n\t}\n\n\treturn positions;\n}\n\n\ntemplate < std::size_t _Dim = 3\n         , class _R1 = double\n         , class _R2 = double\n         , class _R3 = std::common_type_t<_R1, _R2>\n         >\nauto make_momentum_eigenvector( std::array<_R1, 3> const wavevector\n                              , std::vector<std::array<_R2, 3>> const& positions\n                              , _R3 const pi = _R3{M_PI} )\n{\n\tusing _R = std::common_type_t<_R1, _R2, _R3>;\n\tusing _C = std::complex<_R>;\n\n\tauto constexpr I = _C{0, 1};\n\tauto const _norm = \n\t\tstd::pow(_R{2} * pi, -boost::numeric_cast<_R>(_Dim) / _R{2});\n\tauto const _dot = [] (auto const& x, auto const& y) noexcept {\n\t\treturn x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n\t};\n\n\ttcm::Matrix<_C> q{positions.size(), 1};\n\tstd::transform( std::begin(positions), std::end(positions)\n\t              , q.data()\n\t\t\t\t  , [ _norm\n\t                , &wavevector\n\t                , _dot = std::cref(_dot)\n\t                ] (auto const& r) {\n\t                    return _norm * std::exp<_R>(I * _dot(wavevector, r));\n\t                } );\n\treturn q;\n}\n\n\ntemplate <class _R, class _Matrix>\nauto loss_function( std::array<_R, 3> const& direction\n                  , std::vector<_R> const& qs\n                  , _Matrix const& epsilon\n                  , std::vector<std::array<_R, 3>> const& positions )\n{\n\tusing namespace boost;\n\tusing namespace boost::adaptors;\n\n\tassert(tcm::is_square(epsilon));\n\tassert(epsilon.height() == positions.size());\n\tusing _C = typename _Matrix::value_type;\n\tstatic_assert( std::is_same<typename _C::value_type, _R>::value\n\t             , \"Types mismatch.\" );\n\n\tauto const make_wavevector = [&direction](auto const q) noexcept\n\t\t-> std::array<_R, 3> {\n\t\treturn {q * direction[0], q * direction[1], q * direction[2]};\n\t};\n\n\tauto const make_epsilon_q = [&epsilon,&positions](auto const& wavevector) {\n\t\tauto const q_state = make_momentum_eigenvector(wavevector, positions);\n\t\ttcm::Matrix<_C> _temp{epsilon.height(), 1};\n\t\ttcm::blas::gemv( tcm::blas::Operator::H\n\t\t               , _C{1}, epsilon, q_state \n\t\t               , _C{0}, _temp );\n\t\treturn tcm::blas::dot(_temp, q_state);\n\t};\n\n\tstd::vector<_C> epsilon_q;\n\tepsilon_q.reserve(qs.size());\n\tcopy( qs | transformed(std::cref(make_wavevector))\n\t         | transformed(std::cref(make_epsilon_q))\n\t    , std::back_inserter(epsilon_q) );\n\treturn epsilon_q;\n}\n\n\ntemplate <class _C>\nauto run(boost::program_options::variables_map const& vm) -> void\n{\n\tusing namespace boost;\n\tusing _R = typename _C::value_type;\n\n\tauto const direction = \n\t\tparse_direction<_R>(vm[\"direction\"].as<std::string>());\n\tauto const qs =\n\t\tparse_qs<_R>(vm[\"q\"].as<std::string>());\n\tauto const positions = \n\t\tread_positions<_R>(vm[\"positions\"].as<std::string>());\n\tauto const epsilon = \n\t\tload_matrix<_C>(vm[\"epsilon\"].as<std::string>());\n\n\tauto const epsilon_q = loss_function( direction, qs\n\t                                    , epsilon\n\t                                    , positions );\n\n\tauto const print = [](auto const& t) {\n\t\tstd::cout << tuples::get<0>(t) << '\\t' \n\t\t          << std::real(tuples::get<1>(t)) << '\\t' \n\t\t          << std::imag(tuples::get<1>(t)) << '\\n';\n\t};\n\n\tstd::cout << std::scientific << std::setprecision(15);\n\tfor_each(combine(qs, epsilon_q), std::cref(print));\n}\n\n\nauto dispatch(boost::program_options::variables_map const& vm) -> void\n{\n\tauto const type = element_type(vm[\"type\"].as<std::string>());\n\tif (type == typeid(std::complex<float>)) {\n\t\trun<std::complex<float>>(vm);\n\t} \n\telse if (type == typeid(std::complex<double>)) {\n\t\trun<std::complex<double>>(vm);\n\t}\n\telse throw std::invalid_argument{\"Wrong type.\"};\n}\n\n\nint main(int argc, char** argv)\n{\n\tprocess_command_line\n\t\t( argc, argv\n\t\t, [](auto desc) { std::cout << desc << '\\n'; }\n\t\t, &dispatch\n\t\t);\n\treturn EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "554d69d17b2b335d2fb93a342a86de92d0e7ff1c", "size": 8421, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/loss_function.cpp", "max_stars_repo_name": "twesterhout/plasmon-cpp", "max_stars_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T11:12:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-05T11:12:07.000Z", "max_issues_repo_path": "src/loss_function.cpp", "max_issues_repo_name": "twesterhout/plasmon-cpp", "max_issues_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/loss_function.cpp", "max_forks_repo_name": "twesterhout/plasmon-cpp", "max_forks_repo_head_hexsha": "a0e343ee718d9b30602b322ade6077e42e08d8e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3409090909, "max_line_length": 84, "alphanum_fraction": 0.6222538891, "num_tokens": 2346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.2026746572771574}}
{"text": "/* Copyright (C) 2015 Ion Torrent Systems, Inc. All Rights Reserved */\n\n/* Author: Alex Artyomenko <aartyomenko@cs.gsu.edu> */\n\n#ifndef ION_ANALYSIS_VITERBI_HPP\n#define ION_ANALYSIS_VITERBI_HPP\n\n#include <stdlib.h>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include <boost/math/distributions/poisson.hpp>\n#include <boost/algorithm/minmax_element.hpp>\n\ntemplate<typename T>\ntemplate<typename _ForwardIterator>\nmarkov_chain<T>::markov_chain(_ForwardIterator begin, _ForwardIterator end) {\n  pair<_ForwardIterator, _ForwardIterator> m = boost::minmax_element(begin, end);\n  initialize(begin, end, *(m.first), *(m.second));\n}\n\ntemplate<typename T>\ntemplate<typename _ForwardIterator>\nmarkov_chain<T>::markov_chain(_ForwardIterator begin, _ForwardIterator end, T min, T max) {\n  initialize(begin, end, min, max);\n}\n\ntemplate<typename T>\ntemplate<typename _ForwardIterator>\nvoid markov_chain<T>::initialize(_ForwardIterator begin, _ForwardIterator end, T min, T max) {\n  // initialize a constructor delegation method\n  size_t s = (size_t)distance(begin, end);\n  T dmax = (T) max < MAX_STATE_VALUE ? max : MAX_STATE_VALUE,\n    dmin = (T) min < MAX_STATE_VALUE ? min : MAX_STATE_VALUE;\n  if (dmin == dmax) {\n    T avg = (T) round(accumulate(begin, end, 0.0) / s);\n    items.push_back(make_pair(depth_info<T>(avg, min, max), s - 1));\n    return;\n  }\n  values.reserve(s);\n  reserve(s);\n  generate_states(dmin, dmax);\n  for (_ForwardIterator it = begin; it != end; it++)\n    process_next_value(*it);\n  optimal_path();\n}\n\ntemplate<typename T>\nvoid markov_chain<T>::generate_states(T min, T max) {\n  // prepare state values and state objects for viterbi execution\n  double dmax = (double) max,\n      dmin = (double) min,\n      alpha = 2,\n      val;\n  val = ceil(pow(dmin, 1 / alpha));\n\n  states.push_back(dmin);\n  for (double st = pow(val, alpha); st < dmax; st = pow(val, alpha), val++) {\n    states.push_back(st);\n  }\n  states.push_back(dmax);\n}\n\ntemplate<typename T>\nvoid markov_chain<T>::process_next_value(T val) {\n  // accept next value and fill out column in table of states\n  vector<long> states_trace;\n  states_trace.reserve(states.size());\n  for (vector<markov_state>::iterator st = states.begin(); st != states.end(); st++) {\n    markov_state& current = *st;\n    markov_chain_comparator mccmp = markov_chain_comparator(current);\n    vector<markov_state>::iterator min_prev = min_element(states.begin(), states.end(), mccmp);\n    states_trace.push_back(min_prev - states.begin());\n    double new_penalty = min_prev->prev + current.cost(*min_prev) + current.cost(val);\n    st->current = new_penalty;\n  }\n  for (vector<markov_state>::iterator st = states.begin(); st != states.end(); st++) st->step_forward();\n  push_back(states_trace);\n  values.push_back(val);\n}\n\ntemplate<typename T>\nvoid markov_chain<T>::optimal_path() {\n  // find optimal state switches and generate items for a chain\n\n  double mean = 0;\n  int i = 0;\n\n  items.reserve(size());\n  long state_index = min_element(states.begin(), states.end(), markov_chain_comparator()) - states.begin();\n\n  markov_chain::reverse_iterator it = rbegin();\n  typename vector<T>::reverse_iterator vit = values.rbegin();\n  items.push_back(make_pair(depth_info<T>(*vit), size() - 1));\n  for (; it != rend() && vit != values.rend(); it++, vit++) {\n    mean += *vit;\n    i++;\n    if (vit == values.rend() - 1) {\n      items.back().first.dp = (T)round(mean / i);\n    } else if ((*it)[state_index] != state_index){\n      items.back().first.dp = (T)round(mean / i);\n      mean = 0;\n      i = 0;\n      items.push_back(make_pair(depth_info<T>(*(vit+1)), rend() - it - 2));\n    } else {\n      depth_info<T>& cdi = items.back().first;\n      cdi.max_dp = max(*vit, cdi.max_dp);\n      cdi.min_dp = min(*vit, cdi.min_dp);\n    }\n    state_index = (*it)[state_index];\n  }\n}\n\n#endif //ION_ANALYSIS_VITERBI_HPP\n", "meta": {"hexsha": "f46d2fbd3ff42e132c2c40488313ec785d39ff92", "size": 3851, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Analysis/VariantCaller/tvcutils/viterbi.hpp", "max_stars_repo_name": "konradotto/TS", "max_stars_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 125.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T05:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T17:15:59.000Z", "max_issues_repo_path": "Analysis/VariantCaller/tvcutils/viterbi.hpp", "max_issues_repo_name": "konradotto/TS", "max_issues_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2015-02-10T09:13:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T02:32:38.000Z", "max_forks_repo_path": "Analysis/VariantCaller/tvcutils/viterbi.hpp", "max_forks_repo_name": "konradotto/TS", "max_forks_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 98.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T01:25:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T17:29:42.000Z", "avg_line_length": 33.4869565217, "max_line_length": 107, "alphanum_fraction": 0.6808621137, "num_tokens": 1032, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269943353745, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.20265549785923814}}
{"text": "#include <boost/program_options.hpp>\n#include <string>\n#include <d3d_base/grid.h>\n#include <iostream>\n#include <d3d_base/configFile.h>\n#include <d3d_fusion/volumetricFusionTools.h>\n#include <algorithm>\n\nstruct Hist {\n    float counts[8];\n};\n\nD3D::Grid<float> runTVHist(D3D::Grid<Hist> dataCost, Eigen::Vector3f& minCorner, Eigen::Vector3f& size, Eigen::Matrix4f boxToGlobal, Eigen::Vector3f color, std::string vrmlOutputFile,\n                                const int numIter,\n                                const float lambda, const float theta)\n{\n    D3D::Grid<float> u(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth());\n    for (unsigned z = 0; z < u.getDepth(); z++)\n        for (unsigned y = 0; y < u.getHeight(); y++)\n            for (unsigned x = 0; x < u.getWidth(); x++)\n            {\n                u(x,y,z) = 0.f;\n            }\n\n    D3D::Grid<float> uBar = u.clone();\n\n    D3D::Grid<float> p1(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> p2(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n    D3D::Grid<float> p3(dataCost.getWidth(), dataCost.getHeight(), dataCost.getDepth(), 0);\n\n    const int xDim = u.getWidth();\n    const int yDim = u.getHeight();\n    const int zDim = u.getDepth();\n\n    // uses diagonal preconditioned first order pirmal dual\n\n    const float sigma = 0.99f/2.f;\n    const float tau = 0.99f/6.f;\n    const float centers[8] = {-1.f, -5.f/7.f, -3.f/7.f, -1.f/7.f, 1.f/7.f, 3.f/7.f, 5.f/7.f, 1.f};\n\n    for (int c = 0; c < numIter; c++)\n    {\n        std::cout << \".\";\n        std::cout.flush();\n\n        // update dual variables\n#pragma omp parallel for\n        for (int z = 0; z < zDim; z++)\n        {\n            int const Z1 = (z < zDim-1) ? (z+1) : z;\n            for (int y = 0; y < yDim; y++)\n            {\n                int const Y1 = (y < yDim-1) ? (y+1) : y;\n                for (int x = 0; x < xDim; x++)\n                {\n                    float const u0 = uBar(x,y,z);\n\n                    int const X1 = (x < xDim -1) ? (x+1) : x;\n\n                    float const u_x = (uBar(X1, y, z) - u0);\n                    float const u_y = (uBar(x, Y1, z) - u0);\n                    float const u_z = (uBar(x, y, Z1) - u0);\n\n                    float const d_x = p1(x,y,z) + sigma*u_x;\n                    float const d_y = p2(x,y,z) + sigma*u_y;\n                    float const d_z = p3(x,y,z) + sigma*u_z;\n\n                    float const tv = sqrtf(d_x*d_x + d_y*d_y + d_z*d_z);\n\n                    float const denom = std::max(1.f, tv);\n\n                    p1(x,y,z) = d_x/denom;\n                    p2(x,y,z) = d_y/denom;\n                    p3(x,y,z) = d_z/denom;\n                }\n            }\n        }\n\n\n        // update primal\n#pragma omp parallel for\n        for (int z = 0; z < zDim; z++)\n        {\n            int const Z0 = z-1;\n            for (int y = 0; y < yDim; y++)\n            {\n                int const Y0 = y-1;\n                for (int x = 0; x < xDim; x++)\n                {\n                    int const X0 = x-1;\n\n                    float const div = (X0 < xDim -1 ? p1(x,y,z) : 0.0f) - (X0 >= 0 ? p1(X0, y, z) : 0.0f) +\n                                      (Y0 < yDim -1 ? p2(x,y,z) : 0.0f) - (Y0 >= 0 ? p2(x, Y0, z) : 0.0f) +\n                                      (Z0 < zDim -1 ? p3(x,y,z) : 0.0f) - (Z0 >= 0 ? p3(x, y, Z0) : 0.0f);\n\n                    float const u0 = u(x,y,z);\n                    float U = u(x,y,z) + tau*div;\n\n//                    // check most likely bin, is in [1, 8] as u0 in [-1, 1]\n//                    int mlBin = int(7.f * (u0 + 1.f) / 2.f + 1.f);\n\n//                    float step = 0.f;\n//                    for (int b = 0; b <= mlBin; ++b) {\n//                        step -= float(dataCost(x, y, z).counts[b]);\n//                    }\n//                    for (int b = mlBin+1; b < 10; ++b) {\n//                        step += float(dataCost(x, y, z).counts[b]);\n//                    }\n\n//                    float proxMin = u0 + tau*lambda*step;\n\n                    float proxMin, step;\n\n//                    if (proxMin <= centers[mlBin] || centers[mlBin+1] <= proxMin) {\n                        // outside of range\n                        bool found = false;\n                        for (int bin = 0; bin < 7; bin++) {\n//                            if (bin == mlBin)\n//                                continue;\n                            step = 0.f;\n                            for (int b = 0; b <= bin; ++b) {\n                                step -= dataCost(x, y, z).counts[b];\n                            }\n                            for (int b = bin+1; b < 8; ++b) {\n                                step += dataCost(x, y, z).counts[b];\n                            }\n\n                            proxMin = U + tau*lambda*step;\n\n                            if (centers[bin] < proxMin && proxMin < centers[bin+1]) {\n                                // inside of range, val is the minimum\n                                found = true;\n                                break;\n                            }\n                        }\n                        if (!found) {\n                            // minimum must be one of the bin centers\n                            float proxMinEnergy = std::numeric_limits<float>::max();\n                            for (int bin = 0; bin < 8; bin++) {\n                                float dataterm = 0.f;\n                                for (int i = 0; i < 8; ++i) {\n                                    dataterm += dataCost(x, y, z).counts[i] * fabs(centers[bin]-centers[i]);\n                                }\n                                float proxEnergy = (U-centers[bin])*(U-centers[bin])/(2.f*tau) + lambda*dataterm;\n                                if (proxEnergy < proxMinEnergy) {\n                                    proxMinEnergy = proxEnergy;\n                                    proxMin = centers[bin];\n                                }\n                            }\n                        }\n//                    }\n\n                    U = proxMin;\n\n                    u(x,y,z) = U;\n                    uBar(x,y,z) = U + theta*(U - u0);\n\n                }\n            }\n        }\n\n        if ((c+1) % 50 == 0) {\n            D3D::saveVolumeAsVRMLMesh(u, 0.0f, minCorner, size, boxToGlobal, color, vrmlOutputFile, true);\n            std::cout << std::endl;\n        }\n    }\n    return u;\n}\n\nint main(int argc, char* argv[])\n{\n    std::string configFile;\n    std::string intDepthGridFile;\n    std::string vrmlOutputFile;\n\n    boost::program_options::options_description desc(\"Allowed options\");\n    desc.add_options()\n            (\"help\", \"Produce help message\")\n            (\"intDepthGridFile\", boost::program_options::value<std::string>(&intDepthGridFile)->default_value(\"intCSDFGrid.dat\"), \"Depth map list file\")\n            (\"configFile\", boost::program_options::value<std::string>(&configFile)->default_value(\"conf.txt\"), \"Config file\")\n            (\"vrmlOutputFile\", boost::program_options::value<std::string>(&vrmlOutputFile)->default_value(\"tvHistModel.wrl\"), \"Output data file with integrated depth data.\")\n            ;\n\n    boost::program_options::variables_map vm;\n    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).run(), vm);\n    boost::program_options::notify(vm);\n\n    if (vm.count(\"help\"))\n    {\n        std::cout << desc << std::endl;\n        return 1;\n    }\n\n    // config file\n    D3D::ConfigFile conf(configFile);\n\n    if (!conf.isFileRead())\n    {\n        D3D_THROW_EXCEPTION(\"Could not open config file.\")\n    }\n\n    // load the box parameters\n    std::string bpMinXStr = conf.get(\"BP_MIN_X\");\n    if (bpMinXStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Parameter BP_MIN_X not specified in the config file.\")\n    }\n    float bpMinX = atof(bpMinXStr.c_str());\n\n    std::string bpSizeXStr = conf.get(\"BP_SIZE_X\");\n    if (bpSizeXStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Parameter BP_SIZE_X not specified in the config file.\")\n    }\n    float bpSizeX = atof(bpSizeXStr.c_str());\n\n    std::string bpMinYStr = conf.get(\"BP_MIN_Y\");\n    if (bpMinYStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Parameter BP_MIN_Y not specified in the config file.\")\n    }\n    float bpMinY = atof(bpMinYStr.c_str());\n\n    std::string bpSizeYStr = conf.get(\"BP_SIZE_Y\");\n    if (bpSizeYStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Parameter BP_SIZE_Y not specified in the config file.\")\n    }\n    float bpSizeY = atof(bpSizeYStr.c_str());\n\n    std::string bpMinZStr = conf.get(\"BP_MIN_Z\");\n    if (bpMinZStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Parameter BP_MIN_Z not specified in the config file.\")\n    }\n    float bpMinZ = atof(bpMinZStr.c_str());\n\n    std::string bpSizeZStr = conf.get(\"BP_SIZE_Z\");\n    if (bpSizeZStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Parameter BP_SIZE_Z not specified in the config file.\")\n    }\n    float bpSizeZ = atof(bpSizeZStr.c_str());\n\n    std::string bpResXStr = conf.get(\"BP_RES_X\");\n    if (bpResXStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Parameter BP_RES_X not specified in the config file.\")\n    }\n    int bpResX = atoi(bpResXStr.c_str());\n\n    std::string bpResYStr = conf.get(\"BP_RES_Y\");\n    if (bpResYStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Parameter BP_RES_Y not specified in the config file.\")\n    }\n    int bpResY = atoi(bpResYStr.c_str());\n\n    std::string bpResZStr = conf.get(\"BP_RES_Z\");\n    if (bpResZStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Parameter BP_RES_Z not specified in the config file.\")\n    }\n    int bpResZ = atoi(bpResZStr.c_str());\n\n    std::string bpOriginStr = conf.get(\"BP_ORIGIN\");\n    Eigen::Vector3f bpOrigin;\n    if (bpOriginStr.empty())\n    {\n        bpOrigin = Eigen::Vector3f::Zero();\n    }\n    else\n    {\n        std::stringstream bpOriginStream(bpOriginStr);\n        bpOriginStream >> bpOrigin(0);\n        bpOriginStream >> bpOrigin(1);\n        bpOriginStream >> bpOrigin(2);\n\n        if (bpOriginStream.fail())\n        {\n            D3D_THROW_EXCEPTION(\"Error reading BP_ORIGIN\");\n        }\n    }\n\n    std::string bpXAxisStr = conf.get(\"BP_X_AXIS\");\n    Eigen::Vector3f bpXAxis;\n    bool xAxisSet = false;\n    if (!bpXAxisStr.empty())\n    {\n        xAxisSet = true;\n\n        std::stringstream bpXAxisStream(bpXAxisStr);\n        bpXAxisStream >> bpXAxis(0);\n        bpXAxisStream >> bpXAxis(1);\n        bpXAxisStream >> bpXAxis(2);\n\n        if (bpXAxisStream.fail())\n        {\n            D3D_THROW_EXCEPTION(\"Error reading BP_X_AXIS\");\n        }\n    }\n\n    std::string bpYAxisStr = conf.get(\"BP_Y_AXIS\");\n    Eigen::Vector3f bpYAxis;\n    bool yAxisSet = false;\n    if (!bpYAxisStr.empty())\n    {\n        yAxisSet = true;\n\n        std::stringstream bpYAxisStream(bpYAxisStr);\n        bpYAxisStream >> bpYAxis(0);\n        bpYAxisStream >> bpYAxis(1);\n        bpYAxisStream >> bpYAxis(2);\n\n        if (bpYAxisStream.fail())\n        {\n            D3D_THROW_EXCEPTION(\"Error reading BP_Y_AXIS\");\n        }\n    }\n\n    std::string bpZAxisStr = conf.get(\"BP_Z_AXIS\");\n    Eigen::Vector3f bpZAxis;\n    bool zAxisSet = false;\n    if (!bpZAxisStr.empty())\n    {\n        zAxisSet = true;\n\n        std::stringstream bpZAxisStream(bpZAxisStr);\n        bpZAxisStream >> bpZAxis(0);\n        bpZAxisStream >> bpZAxis(1);\n        bpZAxisStream >> bpZAxis(2);\n\n        if (bpZAxisStream.fail())\n        {\n            D3D_THROW_EXCEPTION(\"Error reading BP_Z_AXIS\");\n        }\n    }\n\n    if (xAxisSet == false && yAxisSet == false && zAxisSet == false)\n    {\n        bpXAxis(0) = 1; bpXAxis(1) = 0; bpXAxis(2) = 0;\n        bpYAxis(0) = 0; bpYAxis(1) = 1; bpYAxis(2) = 0;\n        bpZAxis(0) = 0; bpZAxis(1) = 0; bpZAxis(2) = 1;\n    }\n    else if (!(xAxisSet && yAxisSet && zAxisSet))\n    {\n        D3D_THROW_EXCEPTION(\"Either all or none out of BP_X_AXIS, BP_Y_AXIS and BP_Z_AXIS have to be specified.\")\n    }\n\n    // rectify the axes\n    // normlaize\n    bpXAxis /= bpXAxis.norm();\n    bpYAxis /= bpYAxis.norm();\n    bpZAxis /= bpZAxis.norm();\n\n    Eigen::Vector3f rightAngleZAxis = bpXAxis.cross(bpYAxis);\n    if (rightAngleZAxis.dot(bpZAxis) < 0.95)\n    {\n        D3D_THROW_EXCEPTION(\"The given axes are not orthogonal to each other.\")\n    }\n\n    bpZAxis = rightAngleZAxis;\n\n    Eigen::Vector3f rightAngleYAxis = bpZAxis.cross(bpXAxis);\n    if (rightAngleYAxis.dot(bpYAxis) < 0.95)\n    {\n        D3D_THROW_EXCEPTION(\"The given axes are not orthogonal to each other.\");\n    }\n\n    bpYAxis = rightAngleYAxis;\n\n    Eigen::Matrix4f boxToGlobal = Eigen::Matrix4f::Identity();\n    boxToGlobal.topLeftCorner(3,3).col(0) = bpXAxis;\n    boxToGlobal.topLeftCorner(3,3).col(1) = bpYAxis;\n    boxToGlobal.topLeftCorner(3,3).col(2) = bpZAxis;\n    boxToGlobal.topRightCorner(3,1).col(0) = bpOrigin;\n\n    std::string hfNumIterStr = conf.get(\"HF_NUM_ITER\");\n    if (hfNumIterStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Paramter HF_NUM_ITER is not specified in the config file.\")\n    }\n    int ffNumIter = atoi(hfNumIterStr.c_str());\n\n    std::string hfLambdaStr = conf.get(\"HF_LAMBDA\");\n    if (hfLambdaStr.empty())\n    {\n        D3D_THROW_EXCEPTION(\"Parameter HF_LAMBDA is not specified in the config file.\")\n    }\n    float hfLambda = atof(hfLambdaStr.c_str());\n\n    // load grid\n    D3D::Grid<Hist> dataCost;\n    dataCost.loadFromDataFile(intDepthGridFile);\n\n    std::cout << \"Data Cost Loaded: width = \" << dataCost.getWidth() << \", height = \" << dataCost.getHeight() << \", depth = \" << dataCost.getDepth() << std::endl;\n\n    if (bpResX != (int) dataCost.getWidth() || bpResY != (int) dataCost.getHeight() || bpResZ != (int) dataCost.getDepth())\n    {\n        D3D_THROW_EXCEPTION(\"Resolution specified in the config file does not match the dimension of the grid with integrated depth maps.\")\n    }\n\n    Eigen::Vector3f minCorner;\n    minCorner(0) = bpMinX;\n    minCorner(1) = bpMinY;\n    minCorner(2) = bpMinZ;\n    Eigen::Vector3f size;\n    size(0) = bpSizeX;\n    size(1) = bpSizeY;\n    size(2) = bpSizeZ;\n    Eigen::Vector3f color;\n    color(0) = 0.5;\n    color(1) = 0.5;\n    color(2) = 0.5;\n\n    runTVHist(dataCost, minCorner, size, boxToGlobal, color, vrmlOutputFile, ffNumIter, hfLambda, 1);\n}\n", "meta": {"hexsha": "d8e6fa106f7a844f79f9f7477f00ae0a358f7a6b", "size": 14190, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vision-normal-fusion/src/tvHistFusion.cpp", "max_stars_repo_name": "kunal71091/Depth_Normal_Fusion", "max_stars_repo_head_hexsha": "407e204abfbd6c8efe2f98a07415bd623ad84422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-10-23T06:32:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T06:32:40.000Z", "max_issues_repo_path": "vision-normal-fusion/src/tvHistFusion.cpp", "max_issues_repo_name": "kunal71091/Depth_Normal_Fusion", "max_issues_repo_head_hexsha": "407e204abfbd6c8efe2f98a07415bd623ad84422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vision-normal-fusion/src/tvHistFusion.cpp", "max_forks_repo_name": "kunal71091/Depth_Normal_Fusion", "max_forks_repo_head_hexsha": "407e204abfbd6c8efe2f98a07415bd623ad84422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-23T03:35:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-23T03:35:30.000Z", "avg_line_length": 33.9473684211, "max_line_length": 183, "alphanum_fraction": 0.5188160677, "num_tokens": 3935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.33458944125318596, "lm_q1q2_score": 0.20206921480138038}}
{"text": "/** tsne.cc\n    Jeremy Barnes, 16 December 2014\n    Copyright (c) 2014 mldb.ai inc.  All rights reserved.\n\n    This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.\n\n    Implementation of an TSNE algorithm for embedding of a dataset.\n*/\n\n#include \"tsne_interface.h\"\n#include \"mldb/builtin/matrix.h\"\n#include \"mldb/core/mldb_engine.h\"\n#include \"mldb/core/dataset.h\"\n#include \"mldb/utils/distribution.h\"\n#include <boost/multi_array.hpp>\n#include \"mldb/base/scope.h\"\n#include \"mldb/base/parallel.h\"\n#include \"mldb/utils/pair_utils.h\"\n#include \"mldb/arch/timers.h\"\n#include \"mldb/arch/simd_vector.h\"\n#include \"mldb/utils/vector_utils.h\"\n#include \"mldb/types/basic_value_descriptions.h\"\n#include \"mldb/types/any_impl.h\"\n#include \"mldb/builtin/sql_config_validator.h\"\n#include \"mldb/utils/vantage_point_tree.h\"\n#include \"mldb/plugins/jml/tsne/tsne.h\"\n#include \"mldb/sql/sql_expression.h\"\n#include \"mldb/core/analytics.h\"\n#include \"mldb/vfs/fs_utils.h\"\n#include \"mldb/vfs/filter_streams.h\"\n#include \"mldb/types/jml_serialization.h\"\n#include \"mldb/utils/log.h\"\n\nusing namespace std;\n\n\n\nnamespace MLDB {\n\nDEFINE_STRUCTURE_DESCRIPTION(TsneConfig);\n\nTsneConfigDescription::\nTsneConfigDescription()\n{\n    addField(\"trainingData\", &TsneConfig::trainingData,\n             \"Specification of the data for input to the TSNE procedure.  This should be \"\n             \"organized as an embedding, with each selected row containing the same \"\n             \"set of columns with numeric values to be used as coordinates.  The select statement \"\n             \"does not support groupby and having clauses.\");\n    addField(\"rowOutputDataset\", &TsneConfig::output,\n             \"Dataset for TSNE output, with embeddings of training data. \"\n             \"One row will be added for each row in the input dataset, \"\n             \"with a list of coordinates.\",\n             PolyConfigT<Dataset>().withType(\"embedding\"));\n    addField(\"numInputDimensions\", &TsneConfig::numInputDimensions,\n             \"Number of dimensions from the input to use.  This will limit \"\n             \"the columns to the n first columns in the alphabetical \"\n             \"sorting of the columns (-1 = all).\",\n             -1);\n    addField(\"numOutputDimensions\", &TsneConfig::numOutputDimensions,\n             \"Number of dimensions to produce in t-SNE space.  Normally \"\n             \"this will be 2 or 3, depending upon the number of dimensions \"\n             \"in the visualization.\",\n             2);\n    addField(\"tolerance\", &TsneConfig::tolerance,\n             \"Tolerance of perplexity calculation.  This is an internal \"\n             \"parameter that only needs to be changed in rare circumstances.\");\n    addField(\"perplexity\", &TsneConfig::perplexity,\n             \"Perplexity to aim for; higher means more spread out.  This \"\n             \"controls how hard t-SNE tries to spread the points out.  If \"\n             \"the resulting output looks more like a ball or a sphere than \"\n             \"individual clusters, you should reduce this number.  If it \"\n             \"looks like a dot or star, you should increase it.\",\n             30.0);\n    addField(\"learningRate\", &TsneConfig::learningRate,\n             \"The learning rate specifies the gradient descent step size during \"\n             \"optimization of the cost function.  A learning rate that is too small \"\n             \"may hold optimization in a local minimum.  A learning rate that is too high \"\n             \"may jump over the best optimal point. In general, the learning rate \"\n             \"should be between 100 and 1000.\",\n             500.0);\n    addField(\"modelFileUrl\", &TsneConfig::modelFileUrl,\n             \"URL where the model file (with extension '.tsn') should be saved. \"\n             \"This file can be loaded by the ![](%%doclink tsne.embedRow function). \"\n             \"This parameter is optional unless the `functionName` parameter is used.\");\n    addField(\"functionName\", &TsneConfig::functionName,\n             \"If specified, an instance of the ![](%%doclink tsne.embedRow function) of this name will be created using \"\n             \"the trained model. Note that to use this parameter, the `modelFileUrl` must \"\n             \"also be provided.\");\n    addAuto(\"minIterations\", &TsneConfig::minIterations,\n            \"Minimum number of t-SNE iterations to run.  Making this too \"\n            \"small may lead to spurious early stopping.\");\n    addAuto(\"maxIterations\", &TsneConfig::maxIterations,\n            \"Maximum number of t-SNE iterations to run (it will stop if \"\n            \"convergance is obtained before this number of iterations). \");\n    addParent<ProcedureConfig>();\n\n    onPostValidate = chain(validateQuery(&TsneConfig::trainingData,\n                                         MustContainFrom(),\n                                         NoGroupByHaving()),\n                           validateFunction<TsneConfig>());\n}\n\n\n/*****************************************************************************/\n/* TSNE PROCEDURE                                                             */\n/*****************************************************************************/\n\nstruct TsneItl {\n    TsneItl()\n    {\n    }\n\n    TsneItl(const Url & filename)\n    {\n        filter_istream stream(filename);\n        MLDB::DB::Store_Reader store(stream);\n\n        reconstitute(store);\n\n        stream.close();\n    }\n\n    ML::TSNE_Params params;\n    boost::multi_array<float, 2> inputPath;\n    boost::multi_array<float, 2> outputPath;\n    std::unique_ptr<MLDB::VantagePointTree> vpTree;\n    std::unique_ptr<MLDB::Quadtree> qtree;\n    std::vector<Utf8String> inputColumnNames;\n    std::vector<Utf8String> outputColumnNames;\n    std::shared_ptr<const std::vector<ColumnPath> > outputColumnNamesShared;\n\n    size_t numOutputDimensions() const { return outputPath.shape()[1]; }\n\n    int64_t memusage() const\n    {\n        int64_t result = sizeof(*this);\n        result += sizeof(float) * inputPath.shape()[0] * inputPath.shape()[1];\n        result += sizeof(float) * outputPath.shape()[0] * outputPath.shape()[1];\n        result += vpTree->memusage();\n        result += qtree->root->memusage();\n        return result;\n    }\n\n    void save(const std::string & filename) const\n    {\n        filter_ostream stream(filename);\n        MLDB::DB::Store_Writer store(stream);\n        serialize(store);\n    }\n\n    void serialize(MLDB::DB::Store_Writer & store) const\n    {\n        using namespace MLDB::DB;\n\n        store << string(\"TSNE\") << compact_size_t(2);\n        \n        size_t rows = inputPath.shape()[0];\n        size_t dimsIn = inputPath.shape()[1];\n        size_t dimsOut = outputPath.shape()[1];\n\n\n        store << compact_size_t(rows)\n              << compact_size_t(dimsIn)\n              << compact_size_t(dimsOut);\n        \n        store << inputPath << outputPath;\n\n        store << inputColumnNames << outputColumnNames;\n\n        MLDB::VantagePointTree::serializePtr(store, vpTree.get());\n        qtree->serialize(store);\n    }\n\n    void reconstitute(MLDB::DB::Store_Reader & store)\n    {\n        using namespace MLDB::DB;\n\n        string tag;\n        store >> tag;\n        if (tag != \"TSNE\")\n            throw MLDB::Exception(\"Expected TSNE tag\");\n        compact_size_t version(store);\n        if (version != 2)\n            throw MLDB::Exception(\"Unknown version for t-SNE\");\n\n        compact_size_t rows(store), dimsIn(store), dimsOut(store);\n\n        store >> inputPath >> outputPath;\n\n        store >> inputColumnNames >> outputColumnNames;\n\n        outputColumnNamesShared.reset(new vector<ColumnPath>(outputColumnNames.begin(), outputColumnNames.end()));\n\n        vpTree.reset(MLDB::VantagePointTree::reconstitutePtr(store));\n        qtree.reset(new MLDB::Quadtree(store));\n    }\n\n    distribution<float> reembed(const distribution<float> & v) const\n    {\n        return retsneApproxFromCoords(v, inputPath, outputPath,\n                                      *qtree, *vpTree, params);\n    }\n\n};\n\nTsneProcedure::\nTsneProcedure(MldbEngine * owner,\n            PolyConfig config,\n            const std::function<bool (const Json::Value &)> & onProgress)\n    : Procedure(owner)\n{\n    tsneConfig = config.params.convert<TsneConfig>();\n}\n\nAny\nTsneProcedure::\ngetStatus() const\n{\n    return Any();\n}\n\nRunOutput\nTsneProcedure::\nrun(const ProcedureRunConfig & run,\n      const std::function<bool (const Json::Value &)> & onProgress) const\n{\n    auto runProcConf = applyRunConfOverProcConf(tsneConfig, run);\n\n    if (!runProcConf.modelFileUrl.empty()) {\n        checkWritability(runProcConf.modelFileUrl.toString(), \"modelFileUrl\");\n    }\n\n    auto onProgress2 = [&] (const Json::Value & progress)\n        {\n            Json::Value value;\n            value[\"dataset\"] = progress;\n            return onProgress(value);\n        };\n\n    // 1.  Get a numsubjects by numdimensions input matrix to train the\n    //     t-SNE algorithm on\n    auto itl = std::make_shared<TsneItl>();\n\n\n    itl->params.perplexity = runProcConf.perplexity;\n    itl->params.tolerance = runProcConf.tolerance;\n    itl->params.eta = runProcConf.learningRate;\n    itl->params.min_iter = runProcConf.minIterations;\n    itl->params.max_iter = runProcConf.maxIterations;\n    \n    DEBUG_MSG(logger) << \"perplexity = \" << itl->params.perplexity;\n    DEBUG_MSG(logger) << \"tolerance = \" << itl->params.tolerance;\n    DEBUG_MSG(logger) << \"learningRate = \" << itl->params.eta;\n    DEBUG_MSG(logger) << \"minIterations = \" << itl->params.min_iter;\n    DEBUG_MSG(logger) << \"maxIterations = \" << itl->params.max_iter;    \n    DEBUG_MSG(logger) << \"doing t-SNE\";\n\n\n    SqlExpressionMldbScope context(engine);\n\n    ConvertProgressToJson convertProgressToJson(onProgress);\n    auto embeddingOutput = getEmbedding(*runProcConf.trainingData.stm,\n                                        context,\n                                        runProcConf.numInputDimensions,\n                                        convertProgressToJson);\n\n    std::vector<std::tuple<RowHash, RowPath, std::vector<double>,\n                           std::vector<ExpressionValue> > > & rows\n        = embeddingOutput.first;\n    std::vector<KnownColumn> & vars = embeddingOutput.second;\n\n    size_t numDims = vars.size();\n\n    DEBUG_MSG(logger) << \"numDims = \" << numDims;\n\n    boost::multi_array<float, 2> coords\n        (boost::extents[rows.size()][numDims]);\n\n    for (unsigned i = 0;  i < rows.size();  ++i) {\n        for (auto & e: std::get<2>(rows[i]))\n            ExcAssert(isfinite(e));\n        std::copy(std::get<2>(rows[i]).begin(), std::get<2>(rows[i]).end(),\n                  &coords[i][0]);\n    }\n\n    if (coords.size() == 0)\n        throw AnnotatedException(400, \"t-sne training requires at least 1 datapoint. \"\n                                  \"Make sure your dataset is not empty and that your WHERE, offset \"\n                                  \"and limit expressions do not filter all the rows\");\n\n    DEBUG_MSG(logger) << \"copied into matrix\";\n\n//     DEBUG_MSG(logger) << \"rows[0] = \" << rows[0].second;\n//     DEBUG_MSG(logger) << \"rows[1] = \" << rows[1].second;\n//     DEBUG_MSG(logger) << \"rows[2] = \" << rows[1].second;\n//     DEBUG_MSG(logger) << \"rows[0] dot rows[1] = \" << rows[0].second.dotprod(rows[1].second);\n//     DEBUG_MSG(logger) << \"rows[0] dot rows[2] = \" << rows[0].second.dotprod(rows[2].second);\n//     DEBUG_MSG(logger) << \"rows[0] dist rows[1] = \" << (rows[0].second - rows[1].second).two_norm();\n//     DEBUG_MSG(logger) << \"rows[0] dist rows[2] = \" << (rows[0].second - rows[2].second).two_norm();\n//     DEBUG_MSG(logger) << \"rows[1] dist rows[2] = \" << (rows[1].second - rows[2].second).two_norm();\n\n    itl->inputPath.resize(boost::extents[rows.size()][numDims]);\n    itl->inputPath = coords;\n\n    ML::TSNE_Callback callback = [&] (int iter, float cost,\n                                      std::string phase)\n        {\n            if (iter == 1 || iter % 10 == 0)\n                INFO_MSG(logger) << \"phase \" << phase << \" iter \" << iter\n                     << \" cost \" << cost;\n            return true;\n        };\n\n    ExcAssertGreaterEqual(runProcConf.numOutputDimensions, 1);\n\n    itl->outputPath.resize(boost::extents[rows.size()][runProcConf.numOutputDimensions]);\n    itl->outputPath\n        = ML::tsneApproxFromCoords(coords, runProcConf.numOutputDimensions,\n                                   itl->params, callback, &itl->vpTree,\n                                   &itl->qtree);\n\n    ExcAssert(itl->qtree);\n    ExcAssert(itl->vpTree);\n\n    vector<ColumnPath> names = { ColumnPath(\"x\"), ColumnPath(\"y\"), ColumnPath(\"z\") };\n    if (runProcConf.numOutputDimensions <= 3)\n        names.resize(runProcConf.numOutputDimensions);\n    else {\n        names.clear();\n        for (unsigned i = 0; i < runProcConf.numOutputDimensions;  ++i)\n            names.push_back(ColumnPath(MLDB::format(\"dim%04d\", i)));\n    }\n\n\n    // Record the column names for later\n    for (auto & c: vars) {\n        itl->inputColumnNames.emplace_back(c.columnName.toUtf8String());\n    }\n    for (auto & c: names) {\n        itl->outputColumnNames.emplace_back(c.toUtf8String());\n    }\n\n    itl->outputColumnNamesShared\n        .reset(new vector<ColumnPath>(itl->outputColumnNames.begin(),\n                                      itl->outputColumnNames.end()));\n\n    if (!runProcConf.modelFileUrl.empty()) {\n        makeUriDirectory(runProcConf.modelFileUrl.toString());\n        itl->save(runProcConf.modelFileUrl.toString());\n    }\n\n    // Create a dataset to contain the output embedding if we ask for it\n    if (!runProcConf.output.type.empty()) {\n        auto output = createDataset(engine, runProcConf.output, onProgress2, true /*overwrite*/);\n\n        for (unsigned i = 0;  i < rows.size();  ++i) {\n            TRACE_MSG(logger) << \"row \" << i << \" had coords \" << itl->outputPath[i][0] << \",\"\n                 << itl->outputPath[i][1];\n            std::vector<std::tuple<ColumnPath, CellValue, Date> > cols;\n            for (unsigned j = 0;  j < runProcConf.numOutputDimensions;  ++j) {\n                ExcAssert(isfinite(itl->outputPath[i][j]));\n                cols.emplace_back(names[j], itl->outputPath[i][j], Date());\n            }\n\n            output->recordRow(std::get<1>(rows[i]), cols);\n        }\n\n        output->commit();\n    }\n\n    if(!runProcConf.functionName.empty()) {\n        PolyConfig tsneFuncPC;\n        tsneFuncPC.type = \"tsne.embedRow\";\n        tsneFuncPC.id = runProcConf.functionName;\n        tsneFuncPC.params = TsneEmbedConfig(runProcConf.modelFileUrl);\n\n        createFunction(engine, tsneFuncPC, onProgress, true);\n    }\n\n    return Any();\n}\n\n\nDEFINE_STRUCTURE_DESCRIPTION(TsneEmbedConfig);\n\nTsneEmbedConfigDescription::\nTsneEmbedConfigDescription()\n{\n    addField(\"modelFileUrl\", &TsneEmbedConfig::modelFileUrl,\n             \"URL of the model file (with extension '.tns') to load. \"\n             \"This file is created by the ![](%%doclink tsne.train procedure).\");\n}\n\n\n/*****************************************************************************/\n/* TSNE EMBED ROW                                                            */\n/*****************************************************************************/\n\nDEFINE_STRUCTURE_DESCRIPTION(TsneInput);\n\nTsneInputDescription::TsneInputDescription()\n{\n    addField(\"embedding\", &TsneInput::embedding,\n             \"Undocumented.\");\n}\n\nDEFINE_STRUCTURE_DESCRIPTION(TsneOutput);\n\nTsneOutputDescription::TsneOutputDescription()\n{\n    addField(\"cluster\", &TsneOutput::tsne,\n             \"Undocumented.\");\n}\n\n\nTsneEmbed::\nTsneEmbed(MldbEngine * owner,\n          PolyConfig config,\n          const std::function<bool (const Json::Value &)> & onProgress)\n    : BaseT(owner, config)\n{\n    functionConfig = config.params.convert<TsneEmbedConfig>();\n    itl = std::make_shared<TsneItl>(functionConfig.modelFileUrl);\n}\n\n\nTsneOutput \nTsneEmbed::\ncall(TsneInput input) const\n{\n    throw AnnotatedException(500, \"t-SNE Embed apply function is not yet implemented\");\n#if 0    \n    ExpressionValue result;\n\n    ExpressionValue storage;\n    const ExpressionValue & inputVal = context.get(\"embedding\", storage);\n\n    distribution<float> input = inputVal.getEmbedding(itl->inputColumnNames.size());\n\n    Date ts = Date::negativeInfinity();\n    auto embedding = itl->reembed(input);\n\n    result.set(\"tsne\", ExpressionValue(embedding, ts));\n\n    return result;\n#endif\n}\n\nnamespace {\n\nRegisterProcedureType<TsneProcedure, TsneConfig>\nregTsne(builtinPackage(),\n        \"Project a high dimensional space into a low-dimensional space suitable for visualization\",\n        \"procedures/TsneProcedure.md.html\");\n\n\nRegisterFunctionType<TsneEmbed, TsneEmbedConfig>\nregTsneEmbed(builtinPackage(),\n             \"tsne.embedRow\",\n             \"Embed a pre-trained t-SNE algorithm to new data points\",\n             \"functions/TsneEmbed.md.html\",\n             nullptr,\n             {MldbEntity::INTERNAL_ENTITY});\n\n} // file scope\n\n} // namespace MLDB\n\n", "meta": {"hexsha": "1b361221418f1ff3f2eac55ef3f472d9a7f759a3", "size": 16896, "ext": "cc", "lang": "C++", "max_stars_repo_path": "plugins/jml/tsne_interface.cc", "max_stars_repo_name": "mldbai/mldb", "max_stars_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 665.0, "max_stars_repo_stars_event_min_datetime": "2015-12-09T17:00:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T07:46:46.000Z", "max_issues_repo_path": "plugins/jml/tsne_interface.cc", "max_issues_repo_name": "mldbai/mldb", "max_issues_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 797.0, "max_issues_repo_issues_event_min_datetime": "2015-12-09T19:48:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-07T02:19:47.000Z", "max_forks_repo_path": "plugins/jml/tsne_interface.cc", "max_forks_repo_name": "mldbai/mldb", "max_forks_repo_head_hexsha": "0554aa390a563a6294ecc841f8026a88139c3041", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 103.0, "max_forks_repo_forks_event_min_datetime": "2015-12-25T04:39:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T02:55:22.000Z", "avg_line_length": 35.9489361702, "max_line_length": 121, "alphanum_fraction": 0.6083688447, "num_tokens": 3999, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765155565326, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.2020260829420581}}
{"text": "#ifdef USE_EIGEN_BACKEND\n\n/** Eigen3 backend.\n *\n * Only supports float32 computation with NHWC memory layout (at runtime and as input).\n */\n\n// CR lpuchallafiore: Add multi-threading support (see \"Evaluating with a Thread Pool\" in the Eigen Tensor docs).\n\n#include \"../neuralnet/nninterface.h\"\n\n#include <Eigen/Dense>\n#include <unsupported/Eigen/CXX11/Tensor>\n#include <zstr/src/zstr.hpp>\n\n#include \"../neuralnet/desc.h\"\n#include \"../neuralnet/modelversion.h\"\n#include \"../neuralnet/nninputs.h\"\n#include \"../neuralnet/nneval.h\"\n\nusing namespace std;\nusing Eigen::Tensor;\nusing Eigen::TensorMap;\n\n//Eigen doesn't seem to have a way to make a const tensor map out of a const float* ??\n//So we have to cast away qualifiers to build it.\n#pragma GCC diagnostic ignored \"-Wcast-qual\"\n\n// Eigen tensors are stored in column-major order, so an NHWC memory layout is given by Tensor<4>(C,W,H,N).\n\n#define SCALAR float\n#define TENSOR2 Tensor<SCALAR, 2>\n#define TENSOR3 Tensor<SCALAR, 3>\n#define TENSOR4 Tensor<SCALAR, 4>\n#define TENSORMAP2 TensorMap<Tensor<SCALAR, 2>>\n#define TENSORMAP3 TensorMap<Tensor<SCALAR, 3>>\n#define TENSORMAP4 TensorMap<Tensor<SCALAR, 4>>\n\n#define CONSTTENSOR2 const Tensor<SCALAR, 2>\n#define CONSTTENSOR3 const Tensor<SCALAR, 3>\n#define CONSTTENSOR4 const Tensor<SCALAR, 4>\n#define CONSTTENSORMAP2 const TensorMap<Tensor<SCALAR, 2>>\n#define CONSTTENSORMAP3 const TensorMap<Tensor<SCALAR, 3>>\n#define CONSTTENSORMAP4 const TensorMap<Tensor<SCALAR, 4>>\n\n\n// Debugging -----------------------------------------------------------------------------------------------------------\n// #define DEBUG true\n\ntemplate <typename T>\nvoid printTensorShape(const string& name, const T* t) {\n  auto d = t->dimensions();\n  cout << name << \" rank=\" << d.size() << \" - (\";\n  for (int i = 0; i < d.size(); i++) {\n    cout << d[i] << \",\";\n  }\n  cout << \")\" << endl;\n}\n\n#if DEBUG\n#define DSHAPE(n, x) printTensorShape(n,x)\n#define DTENSOR(n, x) cout << n << *x << endl\n#else\n#define DSHAPE(n, x)\n#define DTENSOR(n, x)\n#endif\n\n// LoadedModel / ModelDesc ---------------------------------------------------------------------------------------------\n\nstruct LoadedModel {\n  ModelDesc modelDesc;\n\n  LoadedModel(const string& fileName) {\n    ModelDesc::loadFromFileMaybeGZipped(fileName,modelDesc);\n  }\n\n  LoadedModel() = delete;\n  LoadedModel(const LoadedModel&) = delete;\n  LoadedModel& operator=(const LoadedModel&) = delete;\n};\n\nLoadedModel* NeuralNet::loadModelFile(const string& file) {\n  LoadedModel* loadedModel = new LoadedModel(file);\n  return loadedModel;\n}\n\nvoid NeuralNet::freeLoadedModel(LoadedModel* loadedModel) {\n  delete loadedModel;\n}\n\nstring NeuralNet::getModelName(const LoadedModel* loadedModel) {\n  return loadedModel->modelDesc.name;\n}\n\nint NeuralNet::getModelVersion(const LoadedModel* loadedModel) {\n  return loadedModel->modelDesc.version;\n}\n\nRules NeuralNet::getSupportedRules(const LoadedModel* loadedModel, const Rules& desiredRules, bool& supported) {\n  return loadedModel->modelDesc.getSupportedRules(desiredRules, supported);\n}\n\n//------------------------------------------------------------------------------\n\nstruct ComputeContext {\n  int nnXLen;\n  int nnYLen;\n};\n\nComputeContext* NeuralNet::createComputeContext(\n  const std::vector<int>& gpuIdxs,\n  Logger* logger,\n  int nnXLen,\n  int nnYLen,\n  const string& openCLTunerFile,\n  const string& homeDataDirOverride,\n  bool openCLReTunePerBoardSize,\n  enabled_t useFP16Mode,\n  enabled_t useNHWCMode,\n  const LoadedModel* loadedModel\n) {\n  (void)gpuIdxs;\n  (void)logger;\n  (void)openCLTunerFile;\n  (void)homeDataDirOverride;\n  (void)openCLReTunePerBoardSize;\n  (void)loadedModel;\n\n  bool useFP16 = useFP16Mode == enabled_t::True ? true : false;\n  bool useNHWC = useNHWCMode == enabled_t::False ? false : true;\n\n  if(useFP16)\n    throw StringError(\"Eigen backend: useFP16 = true not supported\");\n  if(!useNHWC)\n    throw StringError(\"Eigen backend: useNHWC = false not supported\");\n\n  ComputeContext* context = new ComputeContext();\n  context->nnXLen = nnXLen;\n  context->nnYLen = nnYLen;\n  return context;\n}\n\nvoid NeuralNet::freeComputeContext(ComputeContext* computeContext) {\n  delete computeContext;\n}\n\n// Helpers --------------------------------------------------------------------------------------------------------------\n\nstatic void computeMaskSum(CONSTTENSORMAP3* mask, float* maskSum) {\n  for (int n = 0; n < mask->dimension(2); n++) {\n    float s = 0.f;\n    for (int h = 0; h < mask->dimension(1); h++) {\n      for (int w = 0; w < mask->dimension(0); w++) {\n        s += (*mask)(w, h, n);\n      }\n    }\n    maskSum[n] = s;\n  }\n}\n\n// in NxHxWxC, bias NxC\nstatic void addNCBiasInplace(TENSORMAP4* in, CONSTTENSORMAP2* bias) {\n  assert(in->dimension(0) == bias->dimension(0) && in->dimension(3) == bias->dimension(1));\n  for (int n = 0; n < in->dimension(3); n++) {\n    for (int h = 0; h < in->dimension(2); h++) {\n      for (int w = 0; w < in->dimension(1); w++) {\n        for (int c = 0; c < in->dimension(0); c++) {\n          (*in)(c,w,h,n) += (*bias)(c,n);\n        }\n      }\n    }\n  }\n}\n\nstatic void poolRowsGPool(CONSTTENSORMAP4* in, TENSORMAP2* out, const float* maskSum) {\n  for (int n = 0; n < in->dimension(3); n++) {\n    for (int c = 0; c < in->dimension(0); c++) {\n      float s = 0.f;\n      float m = 0.f;\n      for (int h = 0; h < in->dimension(2); h++) {\n        for (int w = 0; w < in->dimension(1); w++) {\n          float x = (*in)(c, w, h, n);\n          s += x;\n          m = max(m, x);\n        }\n      }\n      float div = maskSum[n];\n      float sqrtdiv = sqrt(div);\n      float mean = s / div;\n      (*out)(c, n) = mean;\n      (*out)(c + in->dimension(0), n) = mean * (sqrtdiv - 14.f) * 0.1f;\n      (*out)(c + 2*in->dimension(0), n) = m;\n    }\n  }\n}\n\n// // Given input [n,w,h,c] fills output of shape [n,c] with sum over c.\n// static void poolRowsSum(CONSTTENSORMAP4* in, TENSORMAP2* out, float scaleSum) {\n//   for (int n = 0; n < in->dimension(3); n++) {\n//     for (int c = 0; c < in->dimension(0); c++) {\n//       float s = 0.f;\n//       for (int h = 0; h < in->dimension(2); h++) {\n//         for (int w = 0; w < in->dimension(1); w++) {\n//           float x = in(c, w, h, n);\n//           s += x;\n//         }\n//       }\n//       out(c, n) = s * scaleSum;\n//     }\n//   }\n// }\n\nstatic void poolRowsValueHead(CONSTTENSORMAP4* in, TENSORMAP2* out, const float* maskSum) {\n  for (int n = 0; n < in->dimension(3); n++) {\n    for (int c = 0; c < in->dimension(0); c++) {\n      float s = 0.f;\n      for (int h = 0; h < in->dimension(2); h++) {\n        for (int w = 0; w < in->dimension(1); w++) {\n          float x = (*in)(c, w, h, n);\n          s += x;\n        }\n      }\n      float div = maskSum[n];\n      float sqrtdiv = sqrt(div);\n      float mean = s / div;\n      (*out)(c, n) = mean;\n      (*out)(c + in->dimension(0), n) = mean * (sqrtdiv - 14.f) * 0.1f;\n      (*out)(c + 2*in->dimension(0), n) = mean * ((sqrtdiv - 14.0f) * (sqrtdiv - 14.0f) * 0.01f - 0.1f);\n    }\n  }\n}\n\n// Layers --------------------------------------------------------------------------------------------------------------\n\n// Convolution layer with zero-padding.\nstruct ConvLayer {\n  string name;\n\n  Eigen::array<pair<int, int>, 4> paddings;\n  TENSOR4 kernel;\n  int inChannels, outChannels;\n\n  ConvLayer() = delete;\n  ConvLayer(const ConvLayer&) = delete;\n  ConvLayer& operator=(const ConvLayer&) = delete;\n\n  ConvLayer(const ConvLayerDesc& desc) {\n    name = desc.name;\n    int convYSize = desc.convYSize;\n    int convXSize = desc.convXSize;\n    inChannels = desc.inChannels;\n    outChannels = desc.outChannels;\n    //Currently eigen impl doesn't support dilated convs\n    int dilationY = desc.dilationY;\n    int dilationX = desc.dilationX;\n    int paddingX = (convXSize / 2) * dilationX;\n    int paddingY = (convYSize / 2) * dilationY;\n\n    if(dilationX != 1 || dilationY != 1)\n      throw StringError(\"Eigen backend: Encountered convolution dilation factors other than 1, not supported\");\n\n    assert(convXSize % 2 == 1);\n    assert(convYSize % 2 == 1);\n\n    paddings[0] = make_pair(0, 0);                // C\n    paddings[1] = make_pair(paddingX, paddingX);  // W\n    paddings[2] = make_pair(paddingY, paddingY);  // H\n    paddings[3] = make_pair(0, 0);                // N\n\n    // CR-someday lpuchallafiore: optimize NHWC vs NCHW, etc.\n    kernel = TensorMap<const Tensor<const SCALAR, 4>>(\n      desc.weights.data(), convXSize, convYSize, inChannels, outChannels);\n  }\n\n  void apply(CONSTTENSORMAP4* input, TENSORMAP4* output, bool accumulate) const {\n    auto padded = input->pad(paddings);\n    assert(output->dimension(0) == outChannels);\n    for(int n = 0; n < input->dimension(3); n++) {\n      auto inN = padded.chip(n, 3);\n      for(int oc = 0; oc < outChannels; oc++) {\n        TENSOR2 sum(input->dimension(1), input->dimension(2));\n        sum.setZero();\n\n        for(int ic = 0; ic < inChannels; ic++) {\n          Eigen::array<ptrdiff_t, 2> dims({0, 1});\n          auto kChip = kernel.chip(oc, 3).chip(ic, 2);\n          auto inNC = inN.chip(ic, 0);\n          sum += inNC.convolve(kChip, dims);\n        }\n\n        if(accumulate)\n          output->chip(n, 3).chip(oc, 0) += sum;\n        else\n          output->chip(n, 3).chip(oc, 0) = sum;\n      }\n    }\n  }\n};\n\n//--------------------------------------------------------------\n\nstruct BatchNormLayer {\n  string name;\n\n  vector<float> mergedScale;\n  vector<float> mergedBias;\n\n  BatchNormLayer() = delete;\n  BatchNormLayer(const BatchNormLayer&) = delete;\n  BatchNormLayer& operator=(const BatchNormLayer&) = delete;\n\n  BatchNormLayer(const BatchNormLayerDesc& desc) {\n    name = desc.name;\n    int numChannels = desc.numChannels;\n    float epsilon = desc.epsilon;\n\n    mergedScale.resize(numChannels);\n    mergedBias.resize(numChannels);\n    for(int c = 0; c < numChannels; c++) {\n      mergedScale[c] = desc.scale[c] / sqrt(desc.variance[c] + epsilon);\n      mergedBias[c] = desc.bias[c] - mergedScale[c] * desc.mean[c];\n    }\n  }\n\n  // Mask should be in 'NHW' format (no \"C\" channel).\n  void apply(\n    bool applyRelu,\n    CONSTTENSORMAP4* input,\n    TENSORMAP4* output,\n    CONSTTENSORMAP3* mask\n  ) const {\n    for(int c = 0; c < input->dimension(0); c++) {\n      auto inC = input->chip(c, 0);\n      auto x = inC * mergedScale[c] + mergedBias[c];\n      auto z = TENSOR3(mask->dimension(0), mask->dimension(1), mask->dimension(2)).setZero();\n      if(applyRelu)\n        output->chip(c, 0) = (*mask == 1.f).select(x.cwiseMax(0.f), z);\n      else\n        output->chip(c, 0) = (*mask == 1.f).select(x, z);\n    }\n  }\n};\n\n//--------------------------------------------------------------\n\nstruct ActivationLayer {\n  string name;\n\n  ActivationLayer() = delete;\n  ActivationLayer(const ActivationLayer&) = delete;\n  ActivationLayer& operator=(const ActivationLayer&) = delete;\n\n  ActivationLayer(const ActivationLayerDesc& desc) { name = desc.name; }\n\n  template <int N>\n  void apply(const Tensor<SCALAR, N>* input, Tensor<SCALAR, N>* output) const { *output = input->cwiseMax(0.f); }\n  template <int N>\n  void apply(const TensorMap<Tensor<SCALAR, N>>* input, TensorMap<Tensor<SCALAR, N>>* output) const { *output = input->cwiseMax(0.f); }\n};\n\n//--------------------------------------------------------------\n\nstruct MatMulLayer {\n  string name;\n  TENSOR2 weights;\n\n  MatMulLayer() = delete;\n  MatMulLayer(const MatMulLayer&) = delete;\n  MatMulLayer& operator=(const MatMulLayer&) = delete;\n\n  MatMulLayer(const MatMulLayerDesc& desc)\n    : name(desc.name)\n  {\n    weights = TENSOR2(desc.outChannels, desc.inChannels);\n    memcpy(weights.data(), desc.weights.data(), sizeof(SCALAR) * weights.size());\n  }\n\n  void apply(CONSTTENSORMAP2* in, TENSORMAP2* out) const {\n    Eigen::array<Eigen::IndexPair<int>, 1> product_dims = { Eigen::IndexPair<int>(1, 0) };\n    *out = weights.contract(*in, product_dims);\n  }\n};\n\nstruct MatBiasLayer {\n  string name;\n  std::vector<float> weights;\n\n  MatBiasLayer() = delete;\n  MatBiasLayer(const MatBiasLayer&) = delete;\n  MatBiasLayer& operator=(const MatBiasLayer&) = delete;\n\n  MatBiasLayer(const MatBiasLayerDesc& desc)\n    : name(desc.name),\n      weights(desc.weights) {}\n\n  void apply(TENSORMAP2* mat) const {\n    for(int n = 0; n < mat->dimension(1); n++) {\n      for(int c = 0; c < mat->dimension(0); c++) {\n        (*mat)(c, n) += weights[c];\n      }\n    }\n  }\n};\n\n// Blocks\n// --------------------------------------------------------------------------------------------------------------\n\nstruct ResidualBlockIntf {\n  virtual ~ResidualBlockIntf(){}\n\n  virtual void apply(\n    TENSORMAP4* trunk,\n    TENSORMAP4* trunkScratch,\n    TENSORMAP4* regularOut,\n    TENSORMAP4* regularScratch,\n    TENSORMAP4* midIn,\n    TENSORMAP4* midScratch,\n    TENSORMAP4* gpoolOut,\n    TENSORMAP4* gpoolOut2,\n    TENSORMAP2* gpoolConcat,\n    TENSORMAP2* gpoolBias,\n    CONSTTENSORMAP3* mask,\n    const float* maskSum\n  ) const = 0;\n};\n\nstruct ResidualBlock final : public ResidualBlockIntf {\n  string name;\n  BatchNormLayer preBN;\n  ConvLayer regularConv;\n  BatchNormLayer midBN;\n  ConvLayer finalConv;\n\n  ResidualBlock() = delete;\n  ResidualBlock(const ResidualBlock&) = delete;\n  ResidualBlock& operator=(const ResidualBlock&) = delete;\n\n  ~ResidualBlock(){}\n\n  ResidualBlock(const ResidualBlockDesc& desc)\n    : name(desc.name),\n      preBN(desc.preBN),\n      regularConv(desc.regularConv),\n      midBN(desc.midBN),\n      finalConv(desc.finalConv) {}\n\n  void apply(\n    TENSORMAP4* trunk,\n    TENSORMAP4* trunkScratch,\n    TENSORMAP4* regularOut,\n    TENSORMAP4* regularScratch,\n    TENSORMAP4* midIn,\n    TENSORMAP4* midScratch,\n    TENSORMAP4* gpoolOut,\n    TENSORMAP4* gpoolOut2,\n    TENSORMAP2* gpoolConcat,\n    TENSORMAP2* gpoolBias,\n    CONSTTENSORMAP3* mask,\n    const float* maskSum\n  ) const override {\n    (void)regularOut;\n    (void)regularScratch;\n    (void)gpoolOut;\n    (void)gpoolOut2;\n    (void)gpoolConcat;\n    (void)gpoolBias;\n    (void)maskSum;\n    const bool applyBNRelu = true;\n    preBN.apply(applyBNRelu, trunk, trunkScratch, mask);\n    regularConv.apply(trunkScratch, midIn, false);\n    midBN.apply(applyBNRelu, midIn, midScratch, mask);\n    finalConv.apply(midScratch, trunk, true);\n  }\n};\n\n// // Given two tensors with shapes inA: [n, h, w, cA] and inB: [n, h, w, cB]\n// // Copy them into a single tensor out: [n, h, w, cA + cB]\n// TENSOR4 concatTensors(CONSTTENSOR4& a, CONSTTENSOR4& b) {\n//   assert(a->dimension(1) == b->dimension(1) && a->dimension(2) == b->dimension(2) && a->dimension(3) == b->dimension(3));\n//   TENSOR4 x = TENSOR4(/* C */ a->dimension(0) + b->dimension(0),\n//                                           /* W */ a->dimension(1),\n//                                           /* H */ a->dimension(2),\n//                                           /* N */ a->dimension(3));\n//   for (int n = 0; n < a->dimension(3); n++) {\n//     for (int h = 0; h < a->dimension(2); h++) {\n//       for (int w = 0; w < a->dimension(1); w++) {\n//         int c = 0;\n//         for (int ca = 0; a->dimension(0); ca++, c++) {\n//           x(c,w,h,n) = a(ca,w,h,n);\n//         }\n//         for (int cb = 0; b->dimension(0); cb++, c++) {\n//           x(c,w,h,n) = b(cb,w,h,n);\n//         }\n//       }\n//     }\n//   }\n//   return x;\n// }\n\n\nstruct GlobalPoolingResidualBlock final : public ResidualBlockIntf {\n  string name;\n  BatchNormLayer preBN;\n  ActivationLayer preActivation;\n  ConvLayer regularConv;\n  ConvLayer gpoolConv;\n  BatchNormLayer gpoolBN;\n  ActivationLayer gpoolActivation;\n  MatMulLayer gpoolToBiasMul;\n  BatchNormLayer midBN;\n  ActivationLayer midActivation;\n  ConvLayer finalConv;\n\n  GlobalPoolingResidualBlock() = delete;\n  GlobalPoolingResidualBlock(const GlobalPoolingResidualBlock&) = delete;\n  GlobalPoolingResidualBlock& operator=(const GlobalPoolingResidualBlock&) = delete;\n\n  ~GlobalPoolingResidualBlock(){}\n\n  GlobalPoolingResidualBlock(const GlobalPoolingResidualBlockDesc& desc)\n    : name(desc.name),\n      preBN(desc.preBN),\n      preActivation(desc.preActivation),\n      regularConv(desc.regularConv),\n      gpoolConv(desc.gpoolConv),\n      gpoolBN(desc.gpoolBN),\n      gpoolActivation(desc.gpoolActivation),\n      gpoolToBiasMul(desc.gpoolToBiasMul),\n      midBN(desc.midBN),\n      midActivation(desc.midActivation),\n      finalConv(desc.finalConv) {}\n\n  void apply(\n    TENSORMAP4* trunk,\n    TENSORMAP4* trunkScratch,\n    TENSORMAP4* regularOut,\n    TENSORMAP4* regularScratch,\n    TENSORMAP4* midIn,\n    TENSORMAP4* midScratch,\n    TENSORMAP4* gpoolOut,\n    TENSORMAP4* gpoolOut2,\n    TENSORMAP2* gpoolConcat,\n    TENSORMAP2* gpoolBias,\n    CONSTTENSORMAP3* mask,\n    const float* maskSum\n  ) const override {\n    (void)midIn;\n    (void)midScratch;\n    const bool applyBNRelu = true;\n    DTENSOR(\"trunk\", trunk);\n    DTENSOR(\"mask\", mask);\n    preBN.apply(applyBNRelu, trunk, trunkScratch, mask);\n    DTENSOR(\"trunkScratch\", trunkScratch);\n    regularConv.apply(trunkScratch, regularOut, false);\n    DTENSOR(\"regularOut\", regularOut);\n    gpoolConv.apply(trunkScratch, gpoolOut, false);\n    DTENSOR(\"gpoolOut\", gpoolOut);\n    gpoolBN.apply(applyBNRelu, gpoolOut, gpoolOut2, mask);\n    DTENSOR(\"gpoolOut2\", gpoolOut2);\n    poolRowsGPool(gpoolOut2, gpoolConcat, maskSum);\n    gpoolToBiasMul.apply(gpoolConcat, gpoolBias);\n    addNCBiasInplace(regularOut, gpoolBias);\n    midBN.apply(applyBNRelu, regularOut, regularScratch, mask);\n    finalConv.apply(regularScratch, trunk, true);\n    DSHAPE(\"trunk\", trunk);\n    DSHAPE(\"trunkScratch\", trunkScratch);\n    DSHAPE(\"regularOut\", regularOut);\n    DSHAPE(\"gpoolOut\", gpoolOut);\n    DSHAPE(\"gpoolOut2\", gpoolOut2);\n    DSHAPE(\"gpoolConcat\", gpoolConcat);\n    DSHAPE(\"gpoolBias\", gpoolBias);\n    DSHAPE(\"mask\", mask);\n  }\n};\n\nstruct Trunk {\n  string name;\n  int version;\n  int numBlocks;\n\n  ConvLayer initialConv;\n  MatMulLayer initialMatMul;\n  vector<pair<int, ResidualBlockIntf*>> blocks;\n  BatchNormLayer trunkTipBN;\n  ActivationLayer trunkTipActivation;\n\n  Trunk() = delete;\n  Trunk(const Trunk&) = delete;\n  Trunk& operator=(const Trunk&) = delete;\n\n  Trunk(const TrunkDesc& desc)\n    : name(desc.name),\n      version(desc.version),\n      numBlocks(desc.numBlocks),\n      initialConv(desc.initialConv),\n      initialMatMul(desc.initialMatMul),\n      trunkTipBN(desc.trunkTipBN),\n      trunkTipActivation(desc.trunkTipActivation)\n  {\n    for (int i = 0; i < numBlocks; ++i) {\n      if (desc.blocks[i].first == ORDINARY_BLOCK_KIND) {\n        ResidualBlockDesc* blockDesc = (ResidualBlockDesc*)desc.blocks[i].second;\n        ResidualBlockIntf* block = new ResidualBlock(*blockDesc);\n        blocks.push_back(make_pair(ORDINARY_BLOCK_KIND, block));\n      }\n      else if (desc.blocks[i].first == DILATED_BLOCK_KIND) {\n        throw StringError(\"Eigen backend: Dilated residual blocks are not supported right now\");\n      }\n      else if (desc.blocks[i].first == GLOBAL_POOLING_BLOCK_KIND) {\n        GlobalPoolingResidualBlockDesc* blockDesc = (GlobalPoolingResidualBlockDesc*)desc.blocks[i].second;\n        GlobalPoolingResidualBlock* block = new GlobalPoolingResidualBlock(*blockDesc);\n        blocks.push_back(make_pair(GLOBAL_POOLING_BLOCK_KIND, block));\n      }\n      else {\n        ASSERT_UNREACHABLE;\n      }\n    }\n  }\n\n  virtual ~Trunk() {\n    for (auto p : blocks) {\n      delete p.second;\n    }\n  }\n\n  void apply(\n    CONSTTENSORMAP4* input,\n    CONSTTENSORMAP2* inputGlobal,\n    TENSORMAP2* inputMatMulOut,\n    TENSORMAP4* trunk,\n    TENSORMAP4* trunkScratch,\n    TENSORMAP4* regularOut,\n    TENSORMAP4* regularScratch,\n    TENSORMAP4* midIn,\n    TENSORMAP4* midScratch,\n    TENSORMAP4* gpoolOut,\n    TENSORMAP4* gpoolOut2,\n    TENSORMAP2* gpoolConcat,\n    TENSORMAP2* gpoolBias,\n    CONSTTENSORMAP3* mask,\n    const float* maskSum\n  ) const {\n\n    initialConv.apply(input, trunkScratch, false);\n    initialMatMul.apply(inputGlobal, inputMatMulOut);\n    addNCBiasInplace(trunkScratch, inputMatMulOut);\n\n    // apply blocks\n    // Flip trunkBuf and trunkScratchBuf so that the result gets accumulated in trunkScratchBuf\n    for (auto block : blocks) {\n      block.second->apply(\n        trunkScratch,\n        trunk,\n        regularOut,\n        regularScratch,\n        midIn,\n        midScratch,\n        gpoolOut,\n        gpoolOut2,\n        gpoolConcat,\n        gpoolBias,\n        mask,\n        maskSum\n      );\n    }\n\n    // And now with the final BN port it from trunkScratchBuf to trunkBuf.\n    const bool applyBNRelu = true;\n    trunkTipBN.apply(applyBNRelu, trunkScratch, trunk, mask);\n  }\n};\n\nstruct PolicyHead {\n  string name;\n  int version;\n\n  ConvLayer p1Conv;\n  ConvLayer g1Conv;\n  BatchNormLayer g1BN;\n  ActivationLayer g1Activation;\n  MatMulLayer gpoolToBiasMul;\n  BatchNormLayer p1BN;\n  ActivationLayer p1Activation;\n  ConvLayer p2Conv;\n  MatMulLayer gpoolToPassMul;\n\n  PolicyHead() = delete;\n  PolicyHead(const PolicyHead&) = delete;\n  PolicyHead& operator=(const PolicyHead&) = delete;\n\n  PolicyHead(const PolicyHeadDesc& desc)\n    : name(desc.name),\n      version(desc.version),\n      p1Conv(desc.p1Conv),\n      g1Conv(desc.g1Conv),\n      g1BN(desc.g1BN),\n      g1Activation(desc.g1Activation),\n      gpoolToBiasMul(desc.gpoolToBiasMul),\n      p1BN(desc.p1BN),\n      p1Activation(desc.p1Activation),\n      p2Conv(desc.p2Conv),\n      gpoolToPassMul(desc.gpoolToPassMul) {}\n\n  void apply(\n    CONSTTENSORMAP4* trunk,\n    TENSORMAP4* p1Out,\n    TENSORMAP4* p1Out2,\n    TENSORMAP4* g1Out,\n    TENSORMAP4* g1Out2,\n    TENSORMAP2* g1Concat,\n    TENSORMAP2* g1Bias,\n    TENSORMAP2* policyPass,\n    TENSORMAP4* policy,\n    CONSTTENSORMAP3* mask,\n    const float* maskSum\n  ) const {\n    const bool applyBNRelu = true;\n    p1Conv.apply(trunk, p1Out, false);\n    g1Conv.apply(trunk, g1Out, false);\n    g1BN.apply(applyBNRelu, g1Out, g1Out2, mask);\n    poolRowsGPool(g1Out2, g1Concat, maskSum);\n    gpoolToBiasMul.apply(g1Concat, g1Bias);\n    addNCBiasInplace(p1Out, g1Bias);\n    p1BN.apply(true, p1Out, p1Out2, mask);\n    p2Conv.apply(p1Out2, policy, false);\n    gpoolToPassMul.apply(g1Concat, policyPass);\n  }\n};\n\nstruct ValueHead {\n  string name;\n  int version;\n\n  ConvLayer v1Conv;\n  BatchNormLayer v1BN;\n  ActivationLayer v1Activation;\n  MatMulLayer v2Mul;\n  MatBiasLayer v2Bias;\n  ActivationLayer v2Activation;\n  MatMulLayer v3Mul;\n  MatBiasLayer v3Bias;\n  MatMulLayer sv3Mul;\n  MatBiasLayer sv3Bias;\n  ConvLayer vOwnershipConv;\n\n  ValueHead() = delete;\n  ValueHead(const ValueHead&) = delete;\n  ValueHead& operator=(const ValueHead&) = delete;\n\n  ValueHead(const ValueHeadDesc& desc)\n    : name(desc.name),\n      version(desc.version),\n      v1Conv(desc.v1Conv),\n      v1BN(desc.v1BN),\n      v1Activation(desc.v1Activation),\n      v2Mul(desc.v2Mul),\n      v2Bias(desc.v2Bias),\n      v2Activation(desc.v2Activation),\n      v3Mul(desc.v3Mul),\n      v3Bias(desc.v3Bias),\n      sv3Mul(desc.sv3Mul),\n      sv3Bias(desc.sv3Bias),\n      vOwnershipConv(desc.vOwnershipConv) {}\n\n  void apply(\n    CONSTTENSORMAP4* trunk,\n    TENSORMAP4* v1Out,\n    TENSORMAP4* v1Out2,\n    TENSORMAP2* v1Mean,\n    TENSORMAP2* v2Out,\n    TENSORMAP2* value,\n    TENSORMAP2* scoreValue,\n    TENSORMAP4* ownership,\n    CONSTTENSORMAP3* mask,\n    const float* maskSum\n  ) const {\n    bool applyBNRelu = true;\n    v1Conv.apply(trunk, v1Out, false);\n    v1BN.apply(applyBNRelu, v1Out, v1Out2, mask);\n    poolRowsValueHead(v1Out2, v1Mean, maskSum);\n    v2Mul.apply(v1Mean, v2Out);\n    v2Bias.apply(v2Out);\n    v2Activation.apply(v2Out, v2Out);\n    v3Mul.apply(v2Out, value);\n    v3Bias.apply(value);\n\n    sv3Mul.apply(v2Out, scoreValue);\n    sv3Bias.apply(scoreValue);\n\n    vOwnershipConv.apply(v1Out2, ownership, false);\n  }\n};\n\n\n// Model and Buffer I/O ------------------------------------------------------------------------------------------------\n\nstruct Model {\n  string name;\n  int version;\n  int numInputChannels;\n  int numInputGlobalChannels;\n  int numValueChannels;\n  int numScoreValueChannels;\n  int numOwnershipChannels;\n\n  Trunk trunk;\n  PolicyHead policyHead;\n  ValueHead valueHead;\n\n  Model() = delete;\n  Model(const Model&) = delete;\n  Model& operator=(const Model&) = delete;\n\n  Model(const ModelDesc& desc)\n    : name(desc.name), version(desc.version), numInputChannels(desc.numInputChannels),\n      numInputGlobalChannels(desc.numInputGlobalChannels),\n      numValueChannels(desc.numValueChannels),\n      numScoreValueChannels(desc.numScoreValueChannels),\n      numOwnershipChannels(desc.numOwnershipChannels),\n      trunk(desc.trunk),\n      policyHead(desc.policyHead),\n      valueHead(desc.valueHead) {}\n\n  void apply(\n    CONSTTENSORMAP4* input,\n    CONSTTENSORMAP2* inputGlobal,\n    TENSORMAP2* inputMatMulOut,\n    TENSORMAP4* trunkBuf,\n    TENSORMAP4* trunkScratch,\n    TENSORMAP4* regularOut,\n    TENSORMAP4* regularScratch,\n    TENSORMAP4* midIn,\n    TENSORMAP4* midScratch,\n    TENSORMAP4* gpoolOut,\n    TENSORMAP4* gpoolOut2,\n    TENSORMAP2* gpoolConcat,\n    TENSORMAP2* gpoolBias,\n\n    TENSORMAP4* p1Out,\n    TENSORMAP4* p1Out2,\n    TENSORMAP4* g1Out,\n    TENSORMAP4* g1Out2,\n    TENSORMAP2* g1Concat,\n    TENSORMAP2* g1Bias,\n    TENSORMAP2* policyPass,\n    TENSORMAP4* policy,\n\n    TENSORMAP4* v1Out,\n    TENSORMAP4* v1Out2,\n    TENSORMAP2* v1Mean,\n    TENSORMAP2* v2Out,\n    TENSORMAP2* value,\n    TENSORMAP2* scoreValue,\n    TENSORMAP4* ownership,\n\n    TENSORMAP3* mask,\n    float* maskSum\n  ) const {\n    *mask = input->chip(0,0);\n    computeMaskSum(mask,maskSum);\n\n    trunk.apply(\n      input,\n      inputGlobal,\n      inputMatMulOut,\n      trunkBuf,\n      trunkScratch,\n      regularOut,\n      regularScratch,\n      midIn,\n      midScratch,\n      gpoolOut,\n      gpoolOut2,\n      gpoolConcat,\n      gpoolBias,\n      mask,\n      maskSum\n    );\n    policyHead.apply(\n      trunkBuf,\n      p1Out,\n      p1Out2,\n      g1Out,\n      g1Out2,\n      g1Concat,\n      g1Bias,\n      policyPass,\n      policy,\n      mask,\n      maskSum\n    );\n    valueHead.apply(\n      trunkBuf,\n      v1Out,\n      v1Out2,\n      v1Mean,\n      v2Out,\n      value,\n      scoreValue,\n      ownership,\n      mask,\n      maskSum\n    );\n  }\n};\n\n//--------------------------------------------------------------\n\nstruct Buffers {\n  TENSOR2 inputMatMulOut;\n  TENSOR4 trunk;\n  TENSOR4 trunkScratch;\n  TENSOR4 regularOut;\n  TENSOR4 regularScratch;\n  TENSOR4 midIn;\n  TENSOR4 midScratch;\n  TENSOR4 gpoolOut;\n  TENSOR4 gpoolOut2;\n  TENSOR2 gpoolConcat;\n  TENSOR2 gpoolBias;\n\n  TENSOR4 p1Out;\n  TENSOR4 p1Out2;\n  TENSOR4 g1Out;\n  TENSOR4 g1Out2;\n  TENSOR2 g1Concat;\n  TENSOR2 g1Bias;\n  TENSOR2 policyPass;\n  TENSOR4 policy;\n\n  TENSOR4 v1Out;\n  TENSOR4 v1Out2;\n  TENSOR2 v1Mean;\n  TENSOR2 v2Out;\n  TENSOR2 value;\n  TENSOR2 scoreValue;\n  TENSOR4 ownership;\n\n  TENSOR3 mask;\n  vector<float> maskSum;\n\n  Buffers(\n    const ModelDesc& desc,\n    int maxBatchSize,\n    int nnXLen,\n    int nnYLen\n  ) :\n    inputMatMulOut(desc.trunk.trunkNumChannels, maxBatchSize),\n    trunk(desc.trunk.trunkNumChannels, nnXLen, nnYLen, maxBatchSize),\n    trunkScratch(desc.trunk.trunkNumChannels, nnXLen, nnYLen, maxBatchSize),\n    regularOut(desc.trunk.regularNumChannels, nnXLen, nnYLen, maxBatchSize),\n    regularScratch(desc.trunk.regularNumChannels, nnXLen, nnYLen, maxBatchSize),\n    midIn(desc.trunk.midNumChannels, nnXLen, nnYLen, maxBatchSize),\n    midScratch(desc.trunk.midNumChannels, nnXLen, nnYLen, maxBatchSize),\n    gpoolOut(desc.trunk.gpoolNumChannels, nnXLen, nnYLen, maxBatchSize),\n    gpoolOut2(desc.trunk.gpoolNumChannels, nnXLen, nnYLen, maxBatchSize),\n    gpoolConcat(desc.trunk.gpoolNumChannels*3, maxBatchSize),\n    gpoolBias(desc.trunk.regularNumChannels, maxBatchSize),\n\n    p1Out(desc.policyHead.p1Conv.outChannels, nnXLen, nnYLen, maxBatchSize),\n    p1Out2(desc.policyHead.p1Conv.outChannels, nnXLen, nnYLen, maxBatchSize),\n    g1Out(desc.policyHead.g1Conv.outChannels, nnXLen, nnYLen, maxBatchSize),\n    g1Out2(desc.policyHead.g1Conv.outChannels, nnXLen, nnYLen, maxBatchSize),\n    g1Concat(desc.policyHead.g1Conv.outChannels*3, maxBatchSize),\n    g1Bias(desc.policyHead.gpoolToBiasMul.outChannels, maxBatchSize),\n    policyPass(desc.policyHead.gpoolToPassMul.outChannels, maxBatchSize),\n    policy(desc.policyHead.p2Conv.outChannels, nnXLen, nnYLen, maxBatchSize),\n\n    v1Out(desc.valueHead.v1Conv.outChannels, nnXLen, nnYLen, maxBatchSize),\n    v1Out2(desc.valueHead.v1Conv.outChannels, nnXLen, nnYLen, maxBatchSize),\n    v1Mean(desc.valueHead.v1Conv.outChannels*3, maxBatchSize),\n    v2Out(desc.valueHead.v2Mul.outChannels, maxBatchSize),\n    value(desc.valueHead.v3Mul.outChannels, maxBatchSize),\n    scoreValue(desc.valueHead.sv3Mul.outChannels, maxBatchSize),\n    ownership(desc.valueHead.vOwnershipConv.outChannels, nnXLen, nnYLen, maxBatchSize),\n\n    mask(nnXLen, nnYLen, maxBatchSize),\n    maskSum(maxBatchSize)\n  {}\n};\n\n//--------------------------------------------------------------\n\nstruct InputBuffers {\n  int maxBatchSize;\n\n  size_t singleInputElts;\n  size_t singleInputGlobalElts;\n\n  size_t singlePolicyPassResultElts;\n  size_t singlePolicyResultElts;\n  size_t singleValueResultElts;\n  size_t singleScoreValueResultElts;\n  size_t singleOwnershipResultElts;\n\n  std::vector<float> spatialInput;\n  std::vector<float> globalInput;\n\n  InputBuffers(const LoadedModel* loadedModel, int maxBatchSz, int nnXLen, int nnYLen) {\n    const ModelDesc& m = loadedModel->modelDesc;\n\n    int xSize = nnXLen;\n    int ySize = nnYLen;\n\n    maxBatchSize = maxBatchSz;\n    singleInputElts = m.numInputChannels * xSize * ySize;\n    singleInputGlobalElts = m.numInputGlobalChannels;\n\n    singlePolicyPassResultElts = (size_t)(1);\n    singlePolicyResultElts = (size_t)(xSize * ySize);\n    singleValueResultElts = (size_t)m.numValueChannels;\n    singleScoreValueResultElts = (size_t)m.numScoreValueChannels;\n    singleOwnershipResultElts = (size_t)m.numOwnershipChannels * xSize * ySize;\n\n    assert(NNModelVersion::getNumSpatialFeatures(m.version) == m.numInputChannels);\n    assert(NNModelVersion::getNumGlobalFeatures(m.version) == m.numInputGlobalChannels);\n\n    spatialInput = vector<float>(m.numInputChannels * xSize * ySize * maxBatchSize);\n    globalInput = vector<float>(m.numInputGlobalChannels * maxBatchSize);\n  }\n\n  ~InputBuffers() { }\n\n  InputBuffers() = delete;\n  InputBuffers(const InputBuffers&) = delete;\n  InputBuffers& operator=(const InputBuffers&) = delete;\n};\n\nInputBuffers* NeuralNet::createInputBuffers(const LoadedModel* loadedModel, int maxBatchSize, int nnXLen, int nnYLen) {\n  return new InputBuffers(loadedModel, maxBatchSize, nnXLen, nnYLen);\n}\nvoid NeuralNet::freeInputBuffers(InputBuffers* inputBuffers) {\n  delete inputBuffers;\n}\n\n// float* NeuralNet::getBatchEltSpatialInplace(InputBuffers* inputBuffers, int nIdx) {\n//   assert(nIdx < inputBuffers->maxBatchSize);\n//   return inputBuffers->spatialInput.data() + (inputBuffers->singleInputElts * nIdx);\n// }\n\n// float* NeuralNet::getBatchEltGlobalInplace(InputBuffers* inputBuffers, int rowIdx) {\n//   assert(rowIdx < inputBuffers->maxBatchSize);\n//   return inputBuffers->globalInput.data() + (inputBuffers->singleInputGlobalElts * rowIdx);\n// }\n\n// int NeuralNet::getBatchEltSpatialLen(const InputBuffers* inputBuffers) {\n//   return inputBuffers->singleInputElts;\n// }\n// int NeuralNet::getBatchEltGlobalLen(const InputBuffers* inputBuffers) {\n//   return inputBuffers->singleInputGlobalElts;\n// }\n\n// bool* NeuralNet::getSymmetriesInplace(InputBuffers* inputBuffers) {\n//   return inputBuffers->symmetriesBuffer;\n// }\n\n\n// NeuralNet -----------------------------------------------------------------------------------------------------------\n\nvoid NeuralNet::globalInitialize() {\n  // no-op for cpu\n}\n\nvoid NeuralNet::globalCleanup() {\n  // no-op for cpu\n}\n\nstruct ComputeHandle {\n  const ComputeContext* context;\n  int maxBatchSize;\n  bool inputsUseNHWC;\n  Model model;\n  Buffers buffers;\n\n  ComputeHandle() = delete;\n  ComputeHandle(const ComputeHandle&) = delete;\n  ComputeHandle& operator=(const ComputeHandle&) = delete;\n\n  ComputeHandle(const ComputeContext* ctx, const LoadedModel& loadedModel, int maxBSize, bool iNHWC)\n    : context(ctx),\n      maxBatchSize(maxBSize),\n      inputsUseNHWC(iNHWC),\n      model(loadedModel.modelDesc),\n      buffers(loadedModel.modelDesc,maxBSize,ctx->nnXLen,ctx->nnYLen)\n  {}\n};\n\nComputeHandle* NeuralNet::createComputeHandle(\n  ComputeContext* context,\n  const LoadedModel* loadedModel,\n  Logger* logger,\n  int maxBatchSize,\n  bool requireExactNNLen,\n  bool inputsUseNHWC,\n  int gpuIdxForThisThread\n) {\n  if(logger != NULL) {\n    logger->write(\"Eigen (CPU) backend: Model version \" + Global::intToString(loadedModel->modelDesc.version));\n    logger->write(\"Eigen (CPU) backend: Model name: \" + loadedModel->modelDesc.name);\n  }\n\n  (void)requireExactNNLen; //We don't bother with mask optimizations if we know exact sizes right now.\n  (void)gpuIdxForThisThread; //Doesn't matter\n\n  if(!inputsUseNHWC)\n    throw StringError(\"Eigen backend: inputsUseNHWC = false unsupported\");\n  return new ComputeHandle(context, *loadedModel, maxBatchSize, inputsUseNHWC);\n}\n\nvoid NeuralNet::freeComputeHandle(ComputeHandle* gpuHandle) {\n  delete gpuHandle;\n}\n\nvoid NeuralNet::getOutput(\n  ComputeHandle* computeHandle,\n  InputBuffers* inputBuffers,\n  int numBatchEltsFilled,\n  NNResultBuf** inputBufs,\n  int symmetry,\n  vector<NNOutput*>& outputs\n) {\n  assert(numBatchEltsFilled <= inputBuffers->maxBatchSize);\n  assert(numBatchEltsFilled > 0);\n  int batchSize = numBatchEltsFilled;\n  int nnXLen = computeHandle->context->nnXLen;\n  int nnYLen = computeHandle->context->nnYLen;\n  int version = computeHandle->model.version;\n\n  int numSpatialFeatures = NNModelVersion::getNumSpatialFeatures(version);\n  int numGlobalFeatures = NNModelVersion::getNumGlobalFeatures(version);\n  assert(numSpatialFeatures == computeHandle->model.numInputChannels);\n  assert(numSpatialFeatures * nnXLen * nnYLen == inputBuffers->singleInputElts);\n  assert(numGlobalFeatures == inputBuffers->singleInputGlobalElts);\n\n  for(int nIdx = 0; nIdx<batchSize; nIdx++) {\n    float* rowSpatialInput = inputBuffers->spatialInput.data() + (inputBuffers->singleInputElts * nIdx);\n    float* rowGlobalInput = inputBuffers->globalInput.data() + (inputBuffers->singleInputGlobalElts * nIdx);\n\n    const float* rowGlobal = inputBufs[nIdx]->rowGlobal;\n    const float* rowSpatial = inputBufs[nIdx]->rowSpatial;\n    std::copy(rowGlobal,rowGlobal+numGlobalFeatures,rowGlobalInput);\n    SymmetryHelpers::copyInputsWithSymmetry(rowSpatial, rowSpatialInput, 1, nnYLen, nnXLen, numSpatialFeatures, computeHandle->inputsUseNHWC, symmetry);\n  }\n\n  Buffers& buffers = computeHandle->buffers;\n\n  CONSTTENSORMAP4 input(inputBuffers->spatialInput.data(), numSpatialFeatures, nnXLen, nnYLen, batchSize);\n  CONSTTENSORMAP2 inputGlobal(inputBuffers->globalInput.data(), numGlobalFeatures, batchSize);\n\n#define MAP4(NAME) TENSORMAP4 NAME(buffers.NAME.data(), buffers.NAME.dimension(0), buffers.NAME.dimension(1), buffers.NAME.dimension(2), batchSize)\n#define MAP3(NAME) TENSORMAP3 NAME(buffers.NAME.data(), buffers.NAME.dimension(0), buffers.NAME.dimension(1), batchSize)\n#define MAP2(NAME) TENSORMAP2 NAME(buffers.NAME.data(), buffers.NAME.dimension(0), batchSize)\n\n  MAP2(inputMatMulOut);\n  MAP4(trunk);\n  MAP4(trunkScratch);\n  MAP4(regularOut);\n  MAP4(regularScratch);\n  MAP4(midIn);\n  MAP4(midScratch);\n  MAP4(gpoolOut);\n  MAP4(gpoolOut2);\n  MAP2(gpoolConcat);\n  MAP2(gpoolBias);\n  MAP4(p1Out);\n  MAP4(p1Out2);\n  MAP4(g1Out);\n  MAP4(g1Out2);\n  MAP2(g1Concat);\n  MAP2(g1Bias);\n  MAP2(policyPass);\n  MAP4(policy);\n  MAP4(v1Out);\n  MAP4(v1Out2);\n  MAP2(v1Mean);\n  MAP2(v2Out);\n  MAP2(value);\n  MAP2(scoreValue);\n  MAP4(ownership);\n  MAP3(mask);\n  vector<float>& maskSum = buffers.maskSum;\n\n  computeMaskSum(&mask,maskSum.data());\n\n  computeHandle->model.apply(\n    &input,\n    &inputGlobal,\n    &inputMatMulOut,\n    &trunk,\n    &trunkScratch,\n    &regularOut,\n    &regularScratch,\n    &midIn,\n    &midScratch,\n    &gpoolOut,\n    &gpoolOut2,\n    &gpoolConcat,\n    &gpoolBias,\n    &p1Out,\n    &p1Out2,\n    &g1Out,\n    &g1Out2,\n    &g1Concat,\n    &g1Bias,\n    &policyPass,\n    &policy,\n    &v1Out,\n    &v1Out2,\n    &v1Mean,\n    &v2Out,\n    &value,\n    &scoreValue,\n    &ownership,\n    &mask,\n    maskSum.data()\n  );\n\n  assert(outputs.size() == batchSize);\n\n  float* policyData = policy.data();\n  float* policyPassData = policyPass.data();\n  float* valueData = value.data();\n  float* scoreValueData = scoreValue.data();\n  float* ownershipData = ownership.data();\n\n  for(int row = 0; row < batchSize; row++) {\n    NNOutput* output = outputs[row];\n    assert(output->nnXLen == nnXLen);\n    assert(output->nnYLen == nnYLen);\n\n    const float* policySrcBuf = policyData + row * inputBuffers->singlePolicyResultElts;\n    float* policyProbs = output->policyProbs;\n\n    //These are not actually correct, the client does the postprocessing to turn them into\n    //policy probabilities and white game outcome probabilities\n    //Also we don't fill in the nnHash here either\n    SymmetryHelpers::copyOutputsWithSymmetry(policySrcBuf, policyProbs, 1, nnYLen, nnXLen, symmetry);\n    policyProbs[inputBuffers->singlePolicyResultElts] = policyPassData[row];\n\n    int numValueChannels = computeHandle->model.numValueChannels;\n    assert(numValueChannels == 3);\n    output->whiteWinProb = valueData[row * numValueChannels];\n    output->whiteLossProb = valueData[row * numValueChannels + 1];\n    output->whiteNoResultProb = valueData[row * numValueChannels + 2];\n\n    //As above, these are NOT actually from white's perspective, but rather the player to move.\n    //As usual the client does the postprocessing.\n    if(output->whiteOwnerMap != NULL) {\n      const float* ownershipSrcBuf = ownershipData + row * nnXLen * nnYLen;\n      assert(computeHandle->model.numOwnershipChannels == 1);\n      SymmetryHelpers::copyOutputsWithSymmetry(ownershipSrcBuf, output->whiteOwnerMap, 1, nnYLen, nnXLen, symmetry);\n    }\n\n    if(version >= 8) {\n      int numScoreValueChannels = computeHandle->model.numScoreValueChannels;\n      assert(numScoreValueChannels == 4);\n      output->whiteScoreMean = scoreValueData[row * numScoreValueChannels];\n      output->whiteScoreMeanSq = scoreValueData[row * numScoreValueChannels + 1];\n      output->whiteLead = scoreValueData[row * numScoreValueChannels + 2];\n      output->varTimeLeft = scoreValueData[row * numScoreValueChannels + 3];\n    }\n    else if(version >= 4) {\n      int numScoreValueChannels = computeHandle->model.numScoreValueChannels;\n      assert(numScoreValueChannels == 2);\n      output->whiteScoreMean = scoreValueData[row * numScoreValueChannels];\n      output->whiteScoreMeanSq = scoreValueData[row * numScoreValueChannels + 1];\n      output->whiteLead = output->whiteScoreMean;\n      output->varTimeLeft = 0;\n    }\n    else if(version >= 3) {\n      int numScoreValueChannels = computeHandle->model.numScoreValueChannels;\n      assert(numScoreValueChannels == 1);\n      output->whiteScoreMean = scoreValueData[row * numScoreValueChannels];\n      //Version 3 neural nets don't have any second moment output, implicitly already folding it in, so we just use the mean squared\n      output->whiteScoreMeanSq = output->whiteScoreMean * output->whiteScoreMean;\n      output->whiteLead = output->whiteScoreMean;\n      output->varTimeLeft = 0;\n    }\n    else {\n      ASSERT_UNREACHABLE;\n    }\n  }\n}\n\n\nvoid NeuralNet::printDevices() {\n}\n\n// FOR TESTING ---------------------------------------------------------------------------------------------------------\nbool NeuralNet::testEvaluateConv(\n  const ConvLayerDesc* desc,\n  int batchSize,\n  int nnXLen,\n  int nnYLen,\n  bool useFP16,\n  bool useNHWC,\n  const std::vector<float>& inputBuffer,\n  std::vector<float>& outputBuffer\n) {\n  if(!useNHWC || useFP16)\n    return false;\n  ConvLayer layer(*desc);\n  TENSORMAP4 inTensor(\n    (float*)inputBuffer.data(), desc->inChannels, nnXLen, nnYLen, batchSize);\n  TENSOR4 outTensorBuf(desc->outChannels, nnXLen, nnYLen, batchSize);\n  TENSORMAP4 outTensor(outTensorBuf);\n\n  layer.apply(&inTensor, &outTensor, false);\n\n  outputBuffer.resize(outTensorBuf.size());\n  memcpy(outputBuffer.data(), outTensorBuf.data(), sizeof(SCALAR) * outTensorBuf.size());\n  return true;\n}\n\n// Mask should be in 'NHW' format (no \"C\" channel).\nbool NeuralNet::testEvaluateBatchNorm(\n  const BatchNormLayerDesc* desc,\n  int batchSize,\n  int nnXLen,\n  int nnYLen,\n  bool useFP16,\n  bool useNHWC,\n  const std::vector<float>& inputBuffer,\n  const std::vector<float>& maskBuffer,\n  std::vector<float>& outputBuffer\n) {\n  if(!useNHWC || useFP16)\n    return false;\n  BatchNormLayer layer(*desc);\n  TENSORMAP4 inTensor((float*)inputBuffer.data(), desc->numChannels, nnXLen, nnYLen, batchSize);\n  TENSORMAP3 mask((float*)maskBuffer.data(), nnXLen, nnYLen, batchSize);\n  TENSOR4 outTensorBuf(desc->numChannels, nnXLen, nnYLen, batchSize);\n  TENSORMAP4 outTensor(outTensorBuf);\n\n  layer.apply(false, &inTensor, &outTensor, &mask);\n\n  outputBuffer.resize(outTensorBuf.size());\n  memcpy(outputBuffer.data(), outTensorBuf.data(), sizeof(SCALAR) * outTensorBuf.size());\n  return true;\n}\n\n// CR lpuchallafiore: test evaluate activation layer.\n// CR lpuchallafiore: test evaluate matmul layer.\n// CR lpuchallafiore: test evaluate matbias layer.\n\nbool NeuralNet::testEvaluateResidualBlock(\n  const ResidualBlockDesc* desc,\n  int batchSize,\n  int nnXLen,\n  int nnYLen,\n  bool useFP16,\n  bool useNHWC,\n  const std::vector<float>& inputBuffer,\n  const std::vector<float>& maskBuffer,\n  std::vector<float>& outputBuffer\n) {\n  if(!useNHWC || useFP16)\n    return false;\n  ResidualBlock block(*desc);\n  TENSORMAP4 inTensor((float*)inputBuffer.data(), desc->preBN.numChannels, nnXLen, nnYLen, batchSize);\n  TENSORMAP3 mask((float*)maskBuffer.data(), nnXLen, nnYLen, batchSize);\n\n  TENSOR4 trunkBuf(desc->preBN.numChannels, nnXLen, nnYLen, batchSize);\n  TENSOR4 trunkScratchBuf(desc->preBN.numChannels, nnXLen, nnYLen, batchSize);\n  TENSOR4 midBuf(desc->finalConv.inChannels, nnXLen, nnYLen, batchSize);\n  TENSOR4 midScratchBuf(desc->finalConv.inChannels, nnXLen, nnYLen, batchSize);\n\n  TENSORMAP4 trunk(trunkBuf);\n  TENSORMAP4 trunkScratch(trunkScratchBuf);\n  TENSORMAP4 mid(midBuf);\n  TENSORMAP4 midScratch(midScratchBuf);\n\n  trunk = inTensor;\n\n  block.apply(\n    &trunk,\n    &trunkScratch,\n    NULL,\n    NULL,\n    &mid,\n    &midScratch,\n    NULL,\n    NULL,\n    NULL,\n    NULL,\n    &mask,\n    NULL\n  );\n\n  outputBuffer.resize(trunk.size());\n  memcpy(outputBuffer.data(), trunk.data(), sizeof(SCALAR) * trunk.size());\n  return true;\n}\n\nbool NeuralNet::testEvaluateGlobalPoolingResidualBlock(\n  const GlobalPoolingResidualBlockDesc* desc,\n  int batchSize,\n  int nnXLen,\n  int nnYLen,\n  bool useFP16,\n  bool useNHWC,\n  const std::vector<float>& inputBuffer,\n  const std::vector<float>& maskBuffer,\n  std::vector<float>& outputBuffer) {\n  if(!useNHWC || useFP16)\n    return false;\n\n  GlobalPoolingResidualBlock block(*desc);\n\n  TENSORMAP4 inTensor((float*)inputBuffer.data(), desc->preBN.numChannels, nnXLen, nnYLen, batchSize);\n  TENSORMAP3 mask((float*)maskBuffer.data(), nnXLen, nnYLen, batchSize);\n\n  TENSOR4 trunkBuf(desc->preBN.numChannels, nnXLen, nnYLen, batchSize);\n  TENSOR4 trunkScratchBuf(desc->preBN.numChannels, nnXLen, nnYLen, batchSize);\n  TENSOR4 regularOutBuf(desc->finalConv.inChannels, nnXLen, nnYLen, batchSize);\n  TENSOR4 regularScratchBuf(desc->finalConv.inChannels, nnXLen, nnYLen, batchSize);\n  TENSOR4 gpoolOutBuf(desc->gpoolConv.outChannels, nnXLen, nnYLen, batchSize);\n  TENSOR4 gpoolOut2Buf(desc->gpoolConv.outChannels, nnXLen, nnYLen, batchSize);\n  TENSOR2 gpoolConcatBuf(desc->gpoolConv.outChannels*3, batchSize);\n  TENSOR2 gpoolBiasBuf(desc->gpoolToBiasMul.outChannels, batchSize);\n\n  TENSORMAP4 trunk(trunkBuf);\n  TENSORMAP4 trunkScratch(trunkScratchBuf);\n  TENSORMAP4 regularOut(regularOutBuf);\n  TENSORMAP4 regularScratch(regularScratchBuf);\n  TENSORMAP4 gpoolOut(gpoolOutBuf);\n  TENSORMAP4 gpoolOut2(gpoolOut2Buf);\n  TENSORMAP2 gpoolConcat(gpoolConcatBuf);\n  TENSORMAP2 gpoolBias(gpoolBiasBuf);\n\n  std::vector<float> maskSum(batchSize);\n  computeMaskSum(&mask,maskSum.data());\n\n  trunk = inTensor;\n\n  block.apply(\n    &trunk,\n    &trunkScratch,\n    &regularOut,\n    &regularScratch,\n    NULL,\n    NULL,\n    &gpoolOut,\n    &gpoolOut2,\n    &gpoolConcat,\n    &gpoolBias,\n    &mask,\n    maskSum.data()\n  );\n\n  outputBuffer.resize(trunk.size());\n  memcpy(outputBuffer.data(), trunk.data(), sizeof(SCALAR) * trunk.size());\n\n  return true;\n}\n\n#endif  // USE_EIGEN_BACKEND\n\n// CR lpuchallafiore: test evaluate Trunk\n// CR lpuchallafiore: test evaluate Policy Head\n// CR lpuchallafiore: test evaluate Value Head\n", "meta": {"hexsha": "61a76ff525c2a64c687e14856d26750894056819", "size": 44490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/neuralnet/eigenbackend.cpp", "max_stars_repo_name": "Harald-Han/KataGo", "max_stars_repo_head_hexsha": "5e700c721da7e7d6dd57ba442cc97f11c382a8c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/neuralnet/eigenbackend.cpp", "max_issues_repo_name": "Harald-Han/KataGo", "max_issues_repo_head_hexsha": "5e700c721da7e7d6dd57ba442cc97f11c382a8c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/neuralnet/eigenbackend.cpp", "max_forks_repo_name": "Harald-Han/KataGo", "max_forks_repo_head_hexsha": "5e700c721da7e7d6dd57ba442cc97f11c382a8c0", "max_forks_repo_licenses": ["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.4309165527, "max_line_length": 152, "alphanum_fraction": 0.6651157563, "num_tokens": 12848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.20202607766992217}}
{"text": "\n#include \"min-cut-graph.hpp\"\n\n//#include \"perceive/foundation.hpp\"\n#define INFO(m) printf(\"%s:%d  %s\\n\", __FILE__, int(__LINE__), m);\n\n#include <stdint.h>\n\n// #include <unordered_set>\n#include <algorithm> // for std::for_each\n#include <exception>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility> // for std::pair\n\n#include <boost/config.hpp>\n#include <boost/graph/adjacency_list.hpp>\n#include <boost/graph/boykov_kolmogorov_max_flow.hpp>\n#include <boost/graph/depth_first_search.hpp>\n#include <boost/graph/graph_traits.hpp>\n#include <boost/graph/stoer_wagner_min_cut.hpp>\n#include <boost/graph/topological_sort.hpp>\n// #include <boost/graph/read_dimacs.hpp>\n#include <boost/graph/graph_utility.hpp>\n#include <boost/graph/graphviz.hpp>\n\n#define This MinCutGraph\n\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::swap;\n\n// -------------------------------------------------------------------- typedefs\nstruct VertexProperties\n{\n   bool alpha_expansion_vertex{false};\n   // boost::vertex_color_t z{boost::default_color_type};\n   // double boost::vertex_distance_t;\n};\n\ntypedef boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS>\n    FTraits;\n\ntypedef boost::adjacency_list<\n    boost::vecS,\n    boost::vecS,\n    boost::directedS,\n\n    boost::property<\n        boost::vertex_index_t,\n        unsigned,\n        boost::property<\n            boost::vertex_color_t,\n            boost::default_color_type,\n            boost::property<boost::vertex_distance_t,\n                            double,\n                            boost::property<boost::vertex_predecessor_t,\n                                            FTraits::edge_descriptor>>>>,\n\n    boost::property<\n        boost::edge_weight_t,\n        float,\n        boost::property<\n            boost::edge_capacity_t,\n            double,\n            boost::property<boost::edge_residual_capacity_t,\n                            double,\n                            boost::property<boost::edge_reverse_t,\n                                            FTraits::edge_descriptor>>>>>\n\n    G;\n\nusing vertex_descriptor = boost::graph_traits<G>::vertex_descriptor;\nusing edge_descriptor   = boost::graph_traits<G>::edge_descriptor;\n// using weight_map_t      = boost::property_map<G, boost::edge_weight_t>::type;\n// using weight_t          = boost::property_traits<weight_map_t>::value_type;\nusing vertex_iterator = boost::graph_traits<G>::vertex_iterator;\nusing edge_iterator   = boost::graph_traits<G>::edge_iterator;\n\nnamespace perceive\n{\n// ----------------------------------------------------------------------- Pimpl\n\nstatic uint64_t key(uint32_t a, uint32_t b) noexcept\n{\n   return (uint64_t(a) << 32) | (uint64_t(b) << 0);\n}\n\nclass This::Pimpl\n{\n public:\n   G g;\n\n   Pimpl(unsigned n_verts)\n       : g(n_verts)\n   {}\n\n   Pimpl(const Pimpl& rhs) = default;\n   Pimpl(Pimpl&& rhs)      = default;\n   Pimpl& operator=(const Pimpl& rhs) = default;\n   Pimpl& operator=(Pimpl&& rhs) = default;\n};\n\n// ---------------------------------------------------------------- Construction\n\nThis::MinCutGraph(unsigned n_verts)\n    : pimpl_(std::make_unique<Pimpl>(n_verts))\n{}\n\nThis::MinCutGraph(MinCutGraph&& o) noexcept = default;\n\nThis::MinCutGraph(const MinCutGraph& rhs)\n    : pimpl_(std::make_unique<Pimpl>(*rhs.pimpl_))\n{}\n\nThis::~MinCutGraph() = default;\n\nMinCutGraph& This::operator=(MinCutGraph&& o) noexcept = default;\n\nMinCutGraph& This::operator=(const MinCutGraph& rhs)\n{\n   *pimpl_ = *rhs.pimpl_;\n   return *this;\n}\n\n// ----------------------------------------------------------- removing vertices\n\ntemplate<typename T>\nstatic void\nrm_vertex_helper(T& g, vertex_descriptor v1, vector<uint64_t>& to_remove_buffer)\n{\n   boost::graph_traits<G>::out_edge_iterator ei, e_end;\n   std::tie(ei, e_end) = boost::out_edges(v1, g);\n   auto& to_remove     = to_remove_buffer;\n   to_remove.clear();\n   to_remove.reserve(size_t(std::distance(ei, e_end)));\n   for(; ei != e_end; ++ei) {\n      uint32_t uu = uint32_t(boost::source(*ei, g));\n      uint32_t vv = uint32_t(boost::target(*ei, g));\n      to_remove.push_back(key(uu, vv));\n      to_remove.push_back(key(vv, uu));\n   }\n\n   for(auto uv : to_remove) {\n      uint32_t uu = (uv & 0xffffffff00000000ull >> 32);\n      uint32_t vv = (uv & 0x00000000ffffffffull >> 0);\n      boost::remove_edge(uu, vv, g);\n   }\n\n   boost::remove_vertex(v1, g);\n}\n\n// ------------------------------------------------------------------ n-vertices\n\nvoid This::reserve_vertices(unsigned n_verts)\n{\n   pimpl_->g.m_vertices.reserve(n_verts);\n}\n\nvoid This::reserve_edges(unsigned vert_ind, unsigned n_edges)\n{\n   auto& g = pimpl_->g;\n   if(vert_ind < g.m_vertices.size())\n      g.m_vertices[vert_ind].m_out_edges.reserve(n_edges);\n}\n\nvoid This::set_n_vertices(unsigned n_verts)\n{\n   if(n_verts == n_vertices()) return;\n\n   auto& g = pimpl_->g;\n   vector<uint64_t> to_remove_buffer;\n\n   while(n_verts < n_vertices()) {\n      rm_vertex_helper(g, boost::vertex(n_vertices() - 1, g), to_remove_buffer);\n   }\n\n   g.m_vertices.reserve(n_verts);\n\n   auto counter = n_vertices();\n   while(n_vertices() < n_verts) boost::add_vertex(g);\n\n   assert(n_verts == n_vertices());\n}\n\nunsigned This::n_vertices() const noexcept { return size(); }\nunsigned This::n_edges() const noexcept\n{\n   return unsigned(boost::num_edges(pimpl_->g));\n}\nunsigned This::size() const noexcept\n{\n   return unsigned(boost::num_vertices(pimpl_->g));\n}\n\n// ----------------------------------------------------------------------- edges\n\nbool This::has_edge(unsigned v1, unsigned v2) const noexcept\n{\n   assert(v1 < n_vertices());\n   const auto& o = pimpl_->g.m_vertices[v1].m_out_edges;\n   const auto ii = std::find(cbegin(o), cend(o), v2);\n   return ii != cend(o);\n}\n\nbool This::add_edge(unsigned v1, unsigned v2, double weight)\n{\n   auto& g = pimpl_->g;\n\n   const auto& eweight           = get(boost::edge_weight, g);\n   const auto& capacity          = get(boost::edge_capacity, g);\n   const auto& residual_capacity = get(boost::edge_residual_capacity, g);\n   const auto& reverse_edge      = get(boost::edge_reverse, g);\n   const auto& vindex            = get(boost::vertex_index, g);\n\n   edge_descriptor e1, e2;\n   bool success = false;\n\n   const auto& vert1       = vindex[v1];\n   const auto& vert2       = vindex[v2];\n   boost::tie(e1, success) = boost::add_edge(vert1, vert2, g);\n   if(!success) return false;\n   boost::tie(e2, success) = boost::add_edge(vert2, vert1, g);\n   if(!success) {\n      boost::remove_edge(vert1, vert2, g);\n      return false;\n   }\n\n   eweight[e1] = eweight[e2] = float(weight);\n   capacity[e1] = capacity[e2] = weight;\n   residual_capacity[e1] = residual_capacity[e2] = 0.0;\n   reverse_edge[e1]                              = e2;\n   reverse_edge[e2]                              = e1;\n\n   return success;\n}\n\nvoid This::remove_edge(unsigned v1, unsigned v2)\n{\n   boost::remove_edge(v1, v2, pimpl_->g);\n   boost::remove_edge(v2, v1, pimpl_->g);\n}\n\nvoid This::remove_all_edges()\n{\n   auto& g      = pimpl_->g;\n   const auto N = n_vertices();\n\n   vector<uint64_t> to_remove;\n   for(auto i = 0u; i < N; ++i) {\n      boost::graph_traits<G>::out_edge_iterator ei, e_end;\n      std::tie(ei, e_end) = boost::out_edges(i, g);\n      to_remove.reserve(size_t(std::distance(ei, e_end)));\n      for(; ei != e_end; ++ei) {\n         uint32_t uu = uint32_t(boost::source(*ei, g));\n         uint32_t vv = uint32_t(boost::target(*ei, g));\n         to_remove.push_back(key(uu, vv));\n         to_remove.push_back(key(vv, uu));\n      }\n      for(auto uv : to_remove) {\n         uint32_t uu = (uv & 0xffffffff00000000ull >> 32);\n         uint32_t vv = (uv & 0x00000000ffffffffull >> 0);\n         boost::remove_edge(uu, vv, g);\n      }\n   }\n}\n\n// ---------------------------------------------------------------- edge weights\n\n// float This::weight(unsigned v1, unsigned v2) const noexcept\n// {\n//    auto& g             = pimpl_->g;\n//    const auto& eweight = get(boost::edge_weight, g);\n\n//    boost::graph_traits<G>::out_edge_iterator ei, e_end;\n//    std::tie(ei, e_end) = out_edges(v1, g);\n//    auto ii             = std::find_if(ei, e_end, [&](const auto& o) -> bool {\n//       return boost::source(o, g) == v2;\n//    });\n//    if(ii == e_end) return std::numeric_limits<double>::quiet_NaN();\n\n//    return eweight[*ii];\n// }\n\n// bool This::set_weight(unsigned v1, unsigned v2, double weight) noexcept\n// {\n//    auto& g             = pimpl_->g;\n//    auto& e             = pimpl_->edge_idx;\n//    const auto& weights = get(boost::edge_weight, g);\n//    boost::graph_traits<G>::out_edge_iterator ei, e_end;\n//    tie(ei, e_end) = out_edges(v1, g);\n//    if(std::distance(ei, e_end) > 20) {\n//       auto ee = e.find(key(v1, v2));\n//       if(ee == e.end()) return false;\n//       weights[ee->second] = weight;\n//       return true;\n//    }\n\n//    auto ee = boost::edge(v1, v2, g);\n//    if(ee.second) weights[ee.first] = weight;\n//    return ee.second;\n// }\n\n// ----------------------------------------------------- Prepare Alpha Expansion\n// using label_of_vertex_func = std::function<unsigned (unsigned)>;\n// using vertex_label_cost_func = std::function<double (unsigned, unsigned)>;\n// using label_label_cost_func = std::function<double (unsigned, unsigned)>;\n// struct AlphaExpansionData {\n//     unsigned source_vertex{0};\n//     unsigned sink_vertex{0};\n//     unsigned n_additional_vertices{0}; // number of verts added\n// };\n// This::AlphaExpansionData\n// This::modify_for_alpha_expansion(unsigned alpha_label,\n//                                  label_of_vertex_func   l,\n//                                  vertex_label_cost_func f,\n//                                  label_label_cost_func  e,\n//                                  double smoothing_lambda)\n// {\n//     return modify_for_alpha_expansion(alpha_label, l, f,\n//                                       [&] (unsigned v1, unsigned v2,\n//                                            unsigned l1, unsigned l2) {\n//                                           return e(l1, l2);\n//                                       },\n//                                       smoothing_lambda);\n// }\n\n// This::AlphaExpansionData\n// This::modify_for_alpha_expansion(unsigned alpha_label,\n//                                  label_of_vertex_func l,\n//                                  vertex_label_cost_func f,\n//                                  label_label_cost_func e,\n//                                  double smoothing_lambda)\n// {\n//    AlphaExpansionData dat;\n// dat.alpha_label = alpha_label;\n// auto& g         = pimpl_->g;\n// auto& eidx      = pimpl_->edge_idx;\n\n// const auto N        = size();\n// const auto max_cost = 1e9;\n// const auto lambda   = smoothing_lambda;\n\n// const auto& weights  = get(boost::edge_weight, g);\n// const auto& weights2 = get(boost::edge_weight2, g);\n\n// // dat.source_vertex = n_vertices();\n// // dat.sink_vertex = dat.source_vertex + 1;\n\n// // Add the source and sink vertices\n// boost::add_vertex(g);\n// dat.source_vertex                           = N;\n// g[dat.source_vertex].alpha_expansion_vertex = true;\n// boost::add_vertex(g);\n// dat.sink_vertex                           = N + 1;\n// g[dat.sink_vertex].alpha_expansion_vertex = true;\n\n// // Add t-links\n// for(auto n = 0u; n < N; ++n) {\n//    auto label = l(n);\n//    add_edge(n, dat.source_vertex, f(n, alpha_label));\n//    add_edge(\n//        n, dat.sink_vertex, (label == alpha_label) ? max_cost : f(n,\n//        label));\n// }\n\n// // Add e-links\n// vector<std::pair<unsigned, unsigned>> to_remove;\n\n// for(auto n = 0u; n < N; ++n) {\n//    boost::graph_traits<G>::out_edge_iterator ei, e_end;\n//    for(tie(ei, e_end) = out_edges(n, g); ei != e_end; ++ei) {\n//       auto v1 = boost::source(*ei, g);\n//       auto v2 = boost::target(*ei, g);\n//       if(v1 >= N || v2 >= N) continue; // don't worry about t-links\n//       if(v1 < v2) { // undirected graph... avoid double-counting\n//          auto label1 = l(v1);\n//          auto label2 = l(v2);\n//          if(label1 == label2) {\n//             auto ee = boost::edge(v1, v2, g);\n//             assert(ee.second);\n//             weights2[ee.first] = weights[ee.first];\n//             weights[ee.first]  = lambda * e(label1, alpha_label);\n//          } else {\n//             // labels are different... insert node\n//             to_remove.emplace_back(v1, v2);\n//          }\n//       }\n//    }\n// }\n\n// // Add the additional nodes\n// unsigned new_vertex = N + 2;\n// for(const auto& x : to_remove) {\n//    auto v1 = x.first;\n//    auto v2 = x.second;\n//    auto ee = boost::edge(v1, v2, g);\n//    assert(ee.second);\n//    auto label1 = l(v1);\n//    auto label2 = l(v2);\n//    assert(new_vertex == n_vertices());\n//    boost::add_vertex(g);\n//    auto a                      = new_vertex++;\n//    g[a].alpha_expansion_vertex = true;\n//    add_edge(v1, a, lambda * e(label1, alpha_label));\n//    add_edge(v2, a, lambda * e(alpha_label, label2));\n//    add_edge(a, dat.sink_vertex, lambda * e(label1, label2));\n//    weights2[boost::edge(v1, a, g).first]              = weights[ee.first];\n//    weights2[boost::edge(v2, a, g).first]              = weights[ee.first];\n//    weights2[boost::edge(a, dat.sink_vertex, g).first] = weights[ee.first];\n// }\n\n// // Break edges\n// for(const auto& x : to_remove) this->remove_edge(x.first, x.second);\n\n//    return dat;\n// }\n\n// void This::undo_alpha_expansion_modifications() noexcept(false)\n// {\n// vector<vertex_descriptor> to_remove;\n// const auto N         = n_vertices();\n// auto& g              = pimpl_->g;\n// auto& e_idx          = pimpl_->edge_idx;\n// const auto& weights  = get(boost::edge_weight, g);\n// const auto& weights2 = get(boost::edge_weight2, g);\n\n// vector<uint64_t> buffer;\n\n// to_remove.reserve(N);\n// for(auto n = 0u; n < N; ++n)\n//    if(g[n].alpha_expansion_vertex) to_remove.push_back(n);\n\n// if(to_remove.size() == 0) return; // Nothing to undo\n\n// if(to_remove.size() == 1) {\n//    rm_vertex_helper(g, boost::vertex(to_remove[0], g), e_idx, buffer);\n//    throw std::logic_error(\"alpha-expansion graph in invalid state\");\n// }\n\n// const auto original_N = N - to_remove.size();\n\n// // Remove \"additional\" nodes other than source and sink (requires\n// relinking) while(to_remove.size() > 2) {\n//    auto v1 = boost::vertex(to_remove.back(), g);\n//    if(v1 != boost::vertex(n_vertices() - 1, g))\n//       throw std::logic_error(\"alpha-expansion graph in invalid state\");\n//    boost::graph_traits<G>::out_edge_iterator ei, e_end;\n//    tie(ei, e_end) = out_edges(v1, g);\n//    auto arity     = std::distance(ei, e_end);\n//    if(int(arity) != 3)\n//       throw std::logic_error(\"alpha-expansion graph in invalid state\");\n\n//    auto u0 = boost::source(*(ei + 0), g);\n//    auto u1 = boost::target(*(ei + 0), g);\n//    auto s0 = boost::source(*(ei + 1), g);\n//    auto s1 = boost::target(*(ei + 1), g);\n//    auto n0 = boost::source(*(ei + 2), g);\n//    auto n1 = boost::target(*(ei + 2), g);\n\n//    auto restore_weight = weights2[*ei];\n\n//    // two should be v1. The other two are the edge we need to recreate\n//    if(n0 >= original_N || n1 >= original_N) {\n//       // using u0, u1, s0, s1\n//    } else if(s0 >= original_N || s1 >= original_N) {\n//       swap(s0, n0);\n//       swap(s1, n1);\n//    } else {\n//       swap(u0, n0);\n//       swap(u1, n1);\n//    }\n\n//    auto uu = (u0 == v1) ? u1 : u0;\n//    auto ss = (s0 == v1) ? s1 : s0;\n\n//    if(g[uu].alpha_expansion_vertex | g[ss].alpha_expansion_vertex)\n//       throw std::logic_error(\"alpha-expansion graph in invalid state\");\n\n//    // Build an edge between (uu and ss)\n//    this->remove_edge(u0, u1);\n//    this->remove_edge(s0, s1);\n//    this->remove_edge(boost::source(*(ei + 2), g),\n//                      boost::target(*(ei + 2), g));\n//    this->add_edge(uu, ss);\n//    weights2[boost::edge(uu, ss, g).first] = restore_weight;\n\n//    rm_vertex_helper(g, boost::vertex(to_remove.back(), g), e_idx, buffer);\n//    to_remove.pop_back();\n// }\n\n// // Remove source and sink -- no additional edges to relink\n// while(to_remove.size() > 0) {\n//    rm_vertex_helper(g, boost::vertex(to_remove.back(), g), e_idx, buffer);\n//    to_remove.pop_back();\n// }\n\n// { // Zero out all weight2s\n//    boost::graph_traits<G>::edge_iterator ei, ei_end;\n//    for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n//       auto w2       = weights2[*ei];\n//       weights[*ei]  = w2;\n//       weights2[*ei] = 0.0;\n//    }\n// }\n//}\n\n// --------------------------------------------------------------------- min-cut\n\n// Extract the min-cut from graph-flow\n\n// static This::CutResult\n// directed_cut(const G& g, unsigned source_id, unsigned sink_id)\n// {\n//    This::CutResult cut;\n//    const unsigned N = boost::num_vertices(g);\n\n//    typedef boost::\n//        adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS>\n//            FTraits;\n//    typedef boost::adjacency_list<\n//        boost::vecS,\n//        boost::vecS,\n//        boost::directedS,\n//        boost::property<\n//            boost::vertex_index_t,\n//            unsigned,\n//            boost::property<\n//                boost::vertex_color_t,\n//                boost::default_color_type,\n//                boost::property<boost::vertex_distance_t,\n//                                double,\n//                                boost::property<boost::vertex_predecessor_t,\n//                                                FTraits::edge_descriptor>>>>,\n\n//        boost::property<\n//            boost::edge_capacity_t,\n//            double,\n//            boost::property<boost::edge_residual_capacity_t,\n//                            double,\n//                            boost::property<boost::edge_reverse_t,\n//                                            FTraits::edge_descriptor>>>>\n//        F;\n\n//    using namespace boost;\n\n//    typedef typename graph_traits<F>::vertex_descriptor f_vertex_descriptor;\n//    typedef typename graph_traits<F>::edge_descriptor f_edge_descriptor;\n\n//    F f(N);\n\n//    // std::unordered_set<uint64_t> keys;\n//    auto add_edge = [&](unsigned v1, unsigned v2, double weight) {\n//       // if(keys.count(key(v1, v2)) > 0) return;\n//       // keys.insert(key(v1, v2));\n//       f_edge_descriptor e1, e2;\n//       bool success1, success2;\n//       boost::tie(e1, success1) = boost::add_edge(v1, v2, f);\n//       boost::tie(e2, success2) = boost::add_edge(v2, v1, f);\n\n//       if(!success1 || !success2) {\n//          fprintf(stderr, \"kBAM!!!\\n\");\n//          exit(1);\n//       }\n\n//       const auto& capacity          = get(boost::edge_capacity, f);\n//       const auto& residual_capacity = get(edge_residual_capacity, f);\n//       const auto& reverse_edge      = get(boost::edge_reverse, f);\n//       capacity[e1] = capacity[e2] = weight;\n//       residual_capacity[e1] = residual_capacity[e2] = 0.0;\n//       reverse_edge[e1]                              = e2;\n//       reverse_edge[e2]                              = e1;\n//    };\n\n//    { // reserve edge space\n//       for(auto n = 0u; n < N; ++n) {\n//          const auto sz = g.m_vertices[n].m_out_edges.size();\n//          f.m_vertices[n].m_out_edges.reserve(2 * sz);\n//          // f.m_vertices[n].m_in_edges.reserve(sz);\n//       }\n//    }\n\n//    {\n//       const auto& weights = get(boost::edge_weight, g);\n//       boost::graph_traits<G>::edge_iterator ei, e_end;\n//       for(boost::tie(ei, e_end) = boost::edges(g); ei != e_end; ++ei)\n//          add_edge(boost::source(*ei, g), boost::target(*ei, g),\n//          weights[*ei]);\n//    }\n\n//    std::vector<default_color_type> color(num_vertices(f));\n//    std::vector<long> distance(num_vertices(f));\n\n//    // Find the flow\n//    cut.flow = boykov_kolmogorov_max_flow(\n//        f, boost::vertex(source_id, f), boost::vertex(sink_id, f));\n\n//    const auto& colours = get(boost::vertex_color, f);\n//    cut.source_set.resize(N);\n//    std::fill(cut.source_set.begin(), cut.source_set.end(), false);\n//    const auto black = boost::color_traits<F>::black();\n//    for(auto n = 0u; n < N; ++n) cut.source_set[n] = (colours[n] == black);\n\n//    return cut;\n// }\n\nThis::CutResult This::min_cut(unsigned source_id, unsigned sink_id)\n{\n   auto& g = pimpl_->g;\n\n   CutResult cut;\n   cut.flow = boykov_kolmogorov_max_flow(\n       g, boost::vertex(source_id, g), boost::vertex(sink_id, g));\n\n   const unsigned N = n_vertices();\n   cut.source_set.resize(N);\n   std::fill(cut.source_set.begin(), cut.source_set.end(), false);\n   const auto& colours = get(boost::vertex_color, g);\n   const auto black    = boost::color_traits<G>::black();\n   for(auto n = 0u; n < N; ++n) cut.source_set[n] = (colours[n] == black);\n\n   return cut;\n}\n\n// ------------------------------------------------------------------- graph-viz\n\nvoid This::write_graphviz(std::ostream& out) const\n{\n   using namespace boost;\n   const auto& g = pimpl_->g;\n   ::boost::write_graphviz(out, g, default_writer(), default_writer());\n}\n\nnamespace detail\n{\n   template<typename Function> class functional_label_writer\n   {\n    private:\n      Function f;\n\n    public:\n      functional_label_writer(Function func)\n          : f(func)\n      {}\n\n      template<class VertexOrEdge>\n      void operator()(std::ostream& out, const VertexOrEdge& v_or_e) const\n      {\n         out << f(v_or_e);\n      }\n   };\n} // namespace detail\n\nvoid This::write_graphviz(std::ostream& out,\n                          vertex_label_function vert_labels,\n                          edge_label_function edge_labels,\n                          const CutResult* ret) const\n{\n   const auto& g = pimpl_->g;\n\n   auto write_vertices = [&](std::ostream& out) {\n      const auto N = n_vertices();\n      for(auto n = 0u; n < N; ++n) {\n         const bool in_source_set\n             = (ret == nullptr ? false : ret->source_set[n]);\n         out << \"   \" << n << \" [label=\\\"\" << vert_labels(n) << \"\\\"\"\n             << (in_source_set ? \", color=red\" : \"\") << \"];\\n\";\n      }\n   };\n\n   auto write_edges = [&](std::ostream& out) {\n      boost::graph_traits<G>::edge_iterator ei, ei_end;\n      const auto& vindex  = get(boost::vertex_index, g);\n      const auto& eweight = get(boost::edge_weight, g);\n\n      std::array<char, 80> buffer;\n\n      for(std::tie(ei, ei_end) = boost::edges(g); ei != ei_end; ++ei) {\n         int ind0 = int(boost::source(*ei, g));\n         int ind1 = int(boost::target(*ei, g));\n\n         if(ind0 < ind1) continue;\n\n         const bool in0\n             = (ret == nullptr ? false : ret->source_set[size_t(ind0)]);\n         const bool in1\n             = (ret == nullptr ? false : ret->source_set[size_t(ind1)]);\n\n         const auto wgt = eweight(*ei);\n         auto label     = edge_labels(unsigned(ind0), unsigned(ind1));\n         if(label.empty()) {\n            snprintf(&buffer[0], buffer.size(), \"%g\", double(wgt));\n            label = &buffer[0];\n         }\n\n         out << \"   \" << ind0 << \" -- \" << ind1 << \" [label=\\\"\" << label\n             << \"\\\", weight=\\\"\" << eweight(*ei) << \"\\\"\";\n         if(in0 && in1) out << \", color=red\";\n         if(in0 != in1) out << \", color=gray\";\n\n         out << \"];\\n\";\n      }\n   };\n\n   out << \"graph G {\\n\";\n   write_vertices(out);\n   out << \"\\n\";\n   write_edges(out);\n   out << \"}\" << std::flush;\n}\n\n// Write out vertices\n\nvoid This::save_graphviz(std::string filename,\n                         vertex_label_function vlabels,\n                         edge_label_function elabels,\n                         const CutResult* ret) const\n{\n   std::ofstream ofs;\n   ofs.open(filename);\n   this->write_graphviz(ofs, vlabels, elabels, ret);\n   ofs.close();\n   std::stringstream ss(\"\");\n   ss << \"dot -Tpng -O \\\"\" << filename << \"\\\"\";\n   auto cmd     = ss.str();\n   auto success = system(cmd.c_str()) == EXIT_SUCCESS;\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "4273b52f904f96e7c3addba445eb498a8d5428e5", "size": 23728, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/optimization/min-cut-graph.cxx", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/optimization/min-cut-graph.cxx", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/optimization/min-cut-graph.cxx", "max_forks_repo_name": "prcvlabs/multiview", "max_forks_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-26T03:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T06:42:52.000Z", "avg_line_length": 32.4596443228, "max_line_length": 80, "alphanum_fraction": 0.5598027647, "num_tokens": 6193, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3738758227716967, "lm_q1q2_score": 0.20151279509474687}}
{"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#include <vw/Math/EulerAngles.h>\n#include <vw/Camera/CameraModel.h>\n#include <vw/Camera/CameraSolve.h>\n#include <vw/Camera/OpticalBarModel.h>\n\n#include <iomanip>\n#include <boost/filesystem/convenience.hpp>\n\n\nnamespace vw {\nnamespace camera {\n\nusing namespace vw;\nusing namespace vw::camera;\n\n\nVector2 OpticalBarModel::pixel_to_sensor_plane(Vector2 const& pixel) const {\n  Vector2 result = (pixel - m_center_loc_pixels) * m_pixel_size;\n  return result;\n}\n\ndouble OpticalBarModel::sensor_to_alpha(vw::Vector2 const& sensor_loc) const {\n  // This calculation comes from the focal point projected on to a circular surface.\n  return sensor_loc[0] / m_focal_length;\n}\n\nvoid OpticalBarModel::compute_scan_rate() {\n\n  // Compute the scan angle using pixel information.\n  Vector2 p1 = pixel_to_sensor_plane(Vector2(0,0));\n  Vector2 p2 = pixel_to_sensor_plane(Vector2(m_image_size - Vector2i(1,1)));\n  \n  double alpha1     = sensor_to_alpha(p1);\n  double alpha2     = sensor_to_alpha(p2);\n  double scan_angle = alpha2 - alpha1;\n  \n  m_scan_rate_radians = scan_angle / m_scan_time;\n}\n\ndouble OpticalBarModel::pixel_to_time_delta(Vector2 const& pix) const {\n\n  // Since the camera sweeps a scan through columns, use that to\n  //  determine the fraction of the way it is through the image.\n  const int max_col = m_image_size[0]-1;\n  double scan_fraction = 0;\n  if (m_scan_left_to_right)\n    scan_fraction = pix[0] / max_col; // TODO: Add 0.5 pixels to calculation?\n  else // Right to left scan direction\n    scan_fraction = (max_col - pix[0]) / max_col;\n  double time_delta = scan_fraction * m_scan_time;\n  return time_delta;\n}\n\nVector3 OpticalBarModel::get_velocity(vw::Vector2 const& pixel) const {\n\n  // TODO: For speed, store the pose*velocity vector.\n  // Convert the velocity from sensor coords to GCC coords\n  Matrix3x3 pose = camera_pose(pixel).rotation_matrix();\n\n  // Recover the satellite attitude relative to the tilted camera position\n  //Matrix3x3 m = vw::math::rotation_x_axis(-m_forward_tilt_radians)*pose;\n  Matrix3x3 m = pose*vw::math::rotation_x_axis(m_forward_tilt_radians);\n  \n  return m*Vector3(0,m_speed,0);\n}\n\nVector3 OpticalBarModel::camera_center(Vector2 const& pix) const {\n  // We model with a constant velocity.\n  double dt = pixel_to_time_delta(pix);\n\n  return m_initial_position + dt*get_velocity(pix);\n}\n\n\nQuat OpticalBarModel::camera_pose(Vector2 const& pix) const {\n  // Camera pose is treated as constant for the duration of a scan.\n  return axis_angle_to_quaternion(m_initial_orientation);\n}\n\nVector3 OpticalBarModel::pixel_to_vector_uncorrected(Vector2 const& pixel) const {\n \n  Vector2 sensor_plane_pos = pixel_to_sensor_plane(pixel);\n  Vector3 cam_center       = camera_center(pixel);\n  Quat    cam_pose         = camera_pose  (pixel);\n\n  // This is the horizontal angle away from the center point (from straight out of the camera)\n  double alpha = sensor_to_alpha(sensor_plane_pos);\n\n  // Distance from the camera center to the ground.\n  double H = norm_2(cam_center) - (m_mean_surface_elevation + m_mean_earth_radius);\n\n  // Distortion caused by compensation for the satellite's forward motion during the image.\n  // - The film was actually translated underneath the lens to compensate for the motion.\n  double image_motion_compensation = ((m_focal_length * m_speed) / (H*m_scan_rate_radians))\n                                      * sin(alpha) * m_motion_compensation;\n  if (!m_scan_left_to_right) // Sync alpha with motion compensation.\n    image_motion_compensation *= -1.0;\n\n\n  // This vector is ESD format, consistent with the linescan model.\n  Vector3 r(m_focal_length * sin(alpha),\n            sensor_plane_pos[1] + image_motion_compensation,\n            m_focal_length * cos(alpha));\n  r = normalize(r);\n\n  // r is the ray vector in the local camera system\n\n  // Convert the ray vector into GCC coordinates.\n  Vector3 result = cam_pose.rotate(r);\n\n  return result;\n}\n\nVector3 OpticalBarModel::pixel_to_vector(Vector2 const& pixel) const {\n\n  Vector3 output_vector;\n\n  try {\n    output_vector = pixel_to_vector_uncorrected(pixel);\n\n    Vector3 cam_ctr = camera_center(pixel);\n    if (m_correct_atmospheric_refraction) \n      output_vector\n        = apply_atmospheric_refraction_correction(cam_ctr, m_mean_earth_radius,\n                                                  m_mean_surface_elevation, output_vector);\n    \n    if (m_correct_velocity_aberration) \n      output_vector\n        = apply_velocity_aberration_correction(cam_ctr, get_velocity(pixel),\n                                               m_mean_earth_radius, output_vector);\n    \n  } catch(const vw::Exception &e) {\n    // Repackage any of our exceptions thrown below this point as a \n    //  pixel to ray exception that other code will be able to handle.\n    vw_throw(vw::camera::PixelToRayErr() << e.what());\n  }\n  \n  return output_vector;\n}\n\nVector2 OpticalBarModel::point_to_pixel(Vector3 const& point) const {\n\n  // Use the generic solver to find the pixel \n  // - This method will be slower but works for more complicated geometries\n  CameraGenericLMA model( this, point );\n  int status;\n  Vector2 start = m_image_size / 2.0; // Use the center as the initial guess\n\n  // Solver constants\n  const double ABS_TOL = 1e-16;\n  const double REL_TOL = 1e-16;\n  const int    MAX_ITERATIONS = 1e+5;\n\n  Vector3 objective(0, 0, 0);\n  Vector2 solution = math::levenberg_marquardtFixed<CameraGenericLMA, 2,3>(model, start, objective, status,\n                                               ABS_TOL, REL_TOL, MAX_ITERATIONS);\n  VW_ASSERT( status > 0,\n             camera::PointToPixelErr() << \"Unable to project point into Linescan model\" );\n\n  return solution;\n}\n\nvoid OpticalBarModel::apply_transform(vw::Matrix3x3 const & rotation,\n                                      vw::Vector3   const & translation,\n                                      double                scale) {\n  // Extract current parameters\n  vw::Vector3 position = this->camera_center();\n  vw::Quat    pose     = this->camera_pose();\n\n  vw::Quat rotation_quaternion(rotation);\n  \n  // New position and rotation\n  position = scale*rotation*position + translation;\n  pose     = rotation_quaternion*pose;\n\n  this->set_camera_center(position);\n  this->set_camera_pose  (pose.axis_angle());\n}\n\n\nvoid OpticalBarModel::read(std::string const& filename) {\n\n  // Open the input file\n  std::ifstream cam_file;\n  cam_file.open(filename.c_str());\n  if (cam_file.fail())\n    vw_throw( IOErr() << \"OpticalBarModel::read_file: Could not open file: \" << filename );\n\n  // Check for version number on the first line\n  std::string line;\n  std::getline(cam_file, line);\n  if (line.find(\"VERSION\") == std::string::npos) {\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Version missing!\\n\" );\n  }\n\n  int file_version = 1;\n  sscanf(line.c_str(),\"VERSION_%d\", &file_version); // Parse the version of the input file\n  if (file_version < 4)\n    vw_throw( ArgumentErr() << \"OpticalBarModel::read_file(): Versions prior to 4 are not supported!\\n\" );\n\n  // Read the camera type\n  std::getline(cam_file, line);\n  if (line.find(\"OPTICAL_BAR\") == std::string::npos)\n        vw_throw( ArgumentErr() << \"OpticalBarModel::read_file: Expected OPTICAL_BAR type, but got type \"\n                                << line );\n\n  // Start parsing all the parameters from the lines.\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"image_size = %d %d\",\n      &m_image_size[0], &m_image_size[1]) != 2) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the image size\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"image_center = %lf %lf\",\n      &m_center_loc_pixels[0], &m_center_loc_pixels[1]) != 2) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the image center\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"pitch = %lf\", &m_pixel_size) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the pixel pitch\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"f = %lf\", &m_focal_length) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the focal_length\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"scan_time = %lf\", &m_scan_time) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the scan time\\n\" );\n  }\n  /*\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"scan_rate = %lf\", &m_scan_rate_radians) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the scan rate\\n\" );\n  }\n  */\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"forward_tilt = %lf\", &m_forward_tilt_radians) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the forward tilt angle\\n\" );\n  }\n  \n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"iC = %lf %lf %lf\", \n        &m_initial_position(0), &m_initial_position(1), &m_initial_position(2)) != 3) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the initial position\\n\" );\n  }\n\n  // Read and convert the rotation matrix.\n  Matrix3x3 rot_mat;\n  std::getline(cam_file, line);\n  if ( !cam_file.good() ||\n       sscanf(line.c_str(), \"iR = %lf %lf %lf %lf %lf %lf %lf %lf %lf\",\n              &rot_mat(0,0), &rot_mat(0,1), &rot_mat(0,2),\n              &rot_mat(1,0), &rot_mat(1,1), &rot_mat(1,2),\n              &rot_mat(2,0), &rot_mat(2,1), &rot_mat(2,2)) != 9 ) {\n    cam_file.close();\n    vw_throw( IOErr() << \"PinholeModel::read_file(): Could not read the rotation matrix\\n\" );\n  }\n  Quat q(rot_mat);\n  m_initial_orientation = q.axis_angle();\n\n  /*\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"iR = %lf %lf %lf\", \n        &m_initial_orientation(0), &m_initial_orientation(1), &m_initial_orientation(2)) != 3) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the initial orientation\\n\" );\n  }\n  //// !!! DEBUG !!! -> Ignore the orientation, point it locally NED down.\n  //vw::cartography::Datum d(\"WGS84\");\n  //Vector3 llh = d.cartesian_to_geodetic(m_initial_position);\n  //Matrix3x3 m = d.lonlat_to_ned_matrix(Vector2(llh[0],llh[1]));\n  //Quat q(m);\n  //m_initial_orientation = q.axis_angle();\n  */\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"speed = %lf\", &m_speed) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the speed\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"mean_earth_radius = %lf\", &m_mean_earth_radius) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the mean earth radius\\n\" );\n  }\n  \n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"mean_surface_elevation = %lf\", &m_mean_surface_elevation) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read the mean surface elevation\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  if (!cam_file.good() || sscanf(line.c_str(),\"motion_compensation_factor = %lf\",\n                                 &m_motion_compensation) != 1) {\n    cam_file.close();\n    vw_throw( IOErr() << \"OpticalBarModel::read_file(): Could not read motion compensation factor\\n\" );\n  }\n\n  std::getline(cam_file, line);\n  m_scan_left_to_right = line.find(\"scan_dir = left\") == std::string::npos;\n\n  cam_file.close();\n  \n  compute_scan_rate(); // This needs to be updated!\n}\n\n\nvoid OpticalBarModel::write(std::string const& filename) const {\n\n  // TODO: Make compatible with .tsai files!\n\n  // Open the output file for writing\n  std::ofstream cam_file(filename.c_str());\n  if( !cam_file.is_open() ) \n    vw_throw( IOErr() << \"OpticalBarModel::write: Could not open file: \" << filename );\n\n  // Write the pinhole camera model parts\n  //   # digits to survive double->text->double conversion\n  const size_t ACCURATE_DIGITS = 17; // = std::numeric_limits<double>::max_digits10\n  cam_file << std::setprecision(ACCURATE_DIGITS); \n  cam_file << \"VERSION_4\\n\";\n  cam_file << \"OPTICAL_BAR\\n\";\n  cam_file << \"image_size = \"   << m_image_size[0] << \" \" \n                                << m_image_size[1]<< \"\\n\";\n  cam_file << \"image_center = \" << m_center_loc_pixels[0] << \" \"\n                                << m_center_loc_pixels[1] << \"\\n\";\n  cam_file << \"pitch = \"        << m_pixel_size             << \"\\n\";\n  cam_file << \"f = \"            << m_focal_length           << \"\\n\";\n  cam_file << \"scan_time = \"   << m_scan_time     << \"\\n\";\n  //cam_file << \"scan_rate = \"    << m_scan_rate_radians      << \"\\n\";\n  cam_file << \"forward_tilt = \" << m_forward_tilt_radians   << \"\\n\";\n  cam_file << \"iC = \" << m_initial_position[0] << \" \"\n                      << m_initial_position[1] << \" \"\n                      << m_initial_position[2] << \"\\n\";\n  // Store in the same format as the pinhole camera model.\n  Matrix3x3 rot_mat = camera_pose(Vector2(0,0)).rotation_matrix();\n  //cam_file << \"iR = \" << rot_mat[0] << \" \" rot_mat[1] << \" \" rot_mat[2] << \" \"\n  //                    << m_initial_orientation[1] << \" \"\n  //                    << m_initial_orientation[2] << \"\\n\";\n  cam_file << \"iR = \" << rot_mat(0,0) << \" \" << rot_mat(0,1) << \" \" << rot_mat(0,2) << \" \"\n                      << rot_mat(1,0) << \" \" << rot_mat(1,1) << \" \" << rot_mat(1,2) << \" \"\n                      << rot_mat(2,0) << \" \" << rot_mat(2,1) << \" \" << rot_mat(2,2) << \"\\n\";\n  cam_file << \"speed = \" << m_speed << \"\\n\";\n  cam_file << \"mean_earth_radius = \"          << m_mean_earth_radius      << \"\\n\";\n  cam_file << \"mean_surface_elevation = \"     << m_mean_surface_elevation << \"\\n\";\n  cam_file << \"motion_compensation_factor = \" << m_motion_compensation << \"\\n\";\n  if (m_scan_left_to_right)\n    cam_file << \"scan_dir = right\\n\";\n  else\n    cam_file << \"scan_dir = left\\n\";\n  cam_file.close();\n}\n\n\n\nstd::ostream& operator<<( std::ostream& os, OpticalBarModel const& camera_model) {\n  os << \"\\n------------------------ Optical Bar Model -----------------------\\n\\n\";\n  os << \" Image size:             \" << camera_model.m_image_size             << \"\\n\";\n  os << \" Center loc (pixels):    \" << camera_model.m_center_loc_pixels      << \"\\n\";\n  os << \" Pixel size (m):         \" << camera_model.m_pixel_size             << \"\\n\";\n  os << \" Focal length (m):       \" << camera_model.m_focal_length           << \"\\n\";\n  os << \" Scan time (s):          \" << camera_model.m_scan_time              << \"\\n\";\n  os << \" Scan rate (rad/s):      \" << camera_model.m_scan_rate_radians      << \"\\n\";\n  os << \" Forward tilt (rad):     \" << camera_model.m_forward_tilt_radians   << \"\\n\";\n  os << \" Initial position:       \" << camera_model.m_initial_position       << \"\\n\";\n  os << \" Initial pose:           \" << camera_model.m_initial_orientation    << \"\\n\";\n  os << \" Speed:                  \" << camera_model.m_speed                  << \"\\n\";\n  os << \" Mean earth radius:      \" << camera_model.m_mean_earth_radius      << \"\\n\";\n  os << \" Mean surface elevation: \" << camera_model.m_mean_surface_elevation << \"\\n\";\n  os << \" Motion comp factor:     \" << camera_model.m_motion_compensation<< \"\\n\";\n  os << \" Left to right scan:     \" << camera_model.m_scan_left_to_right     << \"\\n\";\n  os << \"\\n------------------------------------------------------------------------\\n\\n\";\n  return os;\n}\n\n\n}} // namespace asp::camera\n\n", "meta": {"hexsha": "aa235b16d33165af6e7f69ee946948925d325015", "size": 16553, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/vw/Camera/OpticalBarModel.cc", "max_stars_repo_name": "visionworkbench/visionworkbench", "max_stars_repo_head_hexsha": "672f7f8205cbdc60c5f8eec598bff74cfe943f5e", "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/Camera/OpticalBarModel.cc", "max_issues_repo_name": "oleg-alexandrov/visionworkbench", "max_issues_repo_head_hexsha": "fe0fd73e5c70615b3327c5130e98bb2feaa99eff", "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/Camera/OpticalBarModel.cc", "max_forks_repo_name": "visionworkbench/visionworkbench", "max_forks_repo_head_hexsha": "672f7f8205cbdc60c5f8eec598bff74cfe943f5e", "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": 40.2749391727, "max_line_length": 112, "alphanum_fraction": 0.640186069, "num_tokens": 4403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.20151279509474684}}
{"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.\n// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.\n\n// This file was modified by Oracle on 2014.\n// Modifications copyright (c) 2014, Oracle and/or its affiliates.\n\n// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle\n\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ALGORITHMS_PERIMETER_HPP\n#define BOOST_GEOMETRY_ALGORITHMS_PERIMETER_HPP\n\n#include <boost/range/metafunctions.hpp>\n#include <boost/variant/static_visitor.hpp>\n#include <boost/variant/apply_visitor.hpp>\n#include <boost/variant/variant_fwd.hpp>\n\n#include <boost/geometry/algorithms/length.hpp>\n#include <boost/geometry/algorithms/detail/calculate_null.hpp>\n#include <boost/geometry/algorithms/detail/calculate_sum.hpp>\n#include <boost/geometry/algorithms/detail/multi_sum.hpp>\n// #include <boost/geometry/algorithms/detail/throw_on_empty_input.hpp>\n#include <boost/geometry/core/cs.hpp>\n#include <boost/geometry/core/closure.hpp>\n#include <boost/geometry/core/tags.hpp>\n#include <boost/geometry/geometries/concepts/check.hpp>\n#include <boost/geometry/strategies/default_length_result.hpp>\n#include <boost/geometry/strategies/default_strategy.hpp>\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DISPATCH\nnamespace dispatch\n{\n\n// Default perimeter is 0.0, specializations implement calculated values\ntemplate <typename Geometry, typename Tag = typename tag<Geometry>::type>\nstruct perimeter : detail::calculate_null\n{\n    typedef typename default_length_result<Geometry>::type return_type;\n\n    template <typename Strategy>\n    static inline return_type apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        return calculate_null::apply<return_type>(geometry, strategy);\n    }\n};\n\ntemplate <typename Geometry>\nstruct perimeter<Geometry, ring_tag>\n    : detail::length::range_length\n        <\n            Geometry,\n            closure<Geometry>::value\n        >\n{};\n\ntemplate <typename Polygon>\nstruct perimeter<Polygon, polygon_tag> : detail::calculate_polygon_sum\n{\n    typedef typename default_length_result<Polygon>::type return_type;\n    typedef detail::length::range_length\n                <\n                    typename ring_type<Polygon>::type,\n                    closure<Polygon>::value\n                > policy;\n\n    template <typename Strategy>\n    static inline return_type apply(Polygon const& polygon, Strategy const& strategy)\n    {\n        return calculate_polygon_sum::apply<return_type, policy>(polygon, strategy);\n    }\n};\n\ntemplate <typename MultiPolygon>\nstruct perimeter<MultiPolygon, multi_polygon_tag> : detail::multi_sum\n{\n    typedef typename default_length_result<MultiPolygon>::type return_type;\n\n    template <typename Strategy>\n    static inline return_type apply(MultiPolygon const& multi, Strategy const& strategy)\n    {\n        return multi_sum::apply\n               <\n                   return_type,\n                   perimeter<typename boost::range_value<MultiPolygon>::type>\n               >(multi, strategy);\n    }\n};\n\n\n// box,n-sphere: to be implemented\n\n} // namespace dispatch\n#endif // DOXYGEN_NO_DISPATCH\n\n\nnamespace resolve_strategy {\n\nstruct perimeter\n{\n    template <typename Geometry, typename Strategy>\n    static inline typename default_length_result<Geometry>::type\n    apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        return dispatch::perimeter<Geometry>::apply(geometry, strategy);\n    }\n\n    template <typename Geometry>\n    static inline typename default_length_result<Geometry>::type\n    apply(Geometry const& geometry, default_strategy)\n    {\n        typedef typename strategy::distance::services::default_strategy\n            <\n                point_tag, point_tag, typename point_type<Geometry>::type\n            >::type strategy_type;\n\n        return dispatch::perimeter<Geometry>::apply(geometry, strategy_type());\n    }\n};\n\n} // namespace resolve_strategy\n\n\nnamespace resolve_variant {\n\ntemplate <typename Geometry>\nstruct perimeter\n{\n    template <typename Strategy>\n    static inline typename default_length_result<Geometry>::type\n    apply(Geometry const& geometry, Strategy const& strategy)\n    {\n        concept::check<Geometry const>();\n        return resolve_strategy::perimeter::apply(geometry, strategy);\n    }\n};\n\ntemplate <BOOST_VARIANT_ENUM_PARAMS(typename T)>\nstruct perimeter<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >\n{\n    typedef typename default_length_result\n        <\n            boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>\n        >::type result_type;\n\n    template <typename Strategy>\n    struct visitor: boost::static_visitor<result_type>\n    {\n        Strategy const& m_strategy;\n\n        visitor(Strategy const& strategy): m_strategy(strategy) {}\n\n        template <typename Geometry>\n        typename default_length_result<Geometry>::type\n        operator()(Geometry const& geometry) const\n        {\n            return perimeter<Geometry>::apply(geometry, m_strategy);\n        }\n    };\n\n    template <typename Strategy>\n    static inline result_type\n    apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry,\n          Strategy const& strategy)\n    {\n        return boost::apply_visitor(visitor<Strategy>(strategy), geometry);\n    }\n};\n\n} // namespace resolve_variant\n\n\n/*!\n\\brief \\brief_calc{perimeter}\n\\ingroup perimeter\n\\details The function perimeter returns the perimeter of a geometry,\n    using the default distance-calculation-strategy\n\\tparam Geometry \\tparam_geometry\n\\param geometry \\param_geometry\n\\return \\return_calc{perimeter}\n\n\\qbk{[include reference/algorithms/perimeter.qbk]}\n */\ntemplate<typename Geometry>\ninline typename default_length_result<Geometry>::type perimeter(\n        Geometry const& geometry)\n{\n    // detail::throw_on_empty_input(geometry);\n    return resolve_variant::perimeter<Geometry>::apply(geometry, default_strategy());\n}\n\n/*!\n\\brief \\brief_calc{perimeter} \\brief_strategy\n\\ingroup perimeter\n\\details The function perimeter returns the perimeter of a geometry,\n    using specified strategy\n\\tparam Geometry \\tparam_geometry\n\\tparam Strategy \\tparam_strategy{distance}\n\\param geometry \\param_geometry\n\\param strategy strategy to be used for distance calculations.\n\\return \\return_calc{perimeter}\n\n\\qbk{distinguish,with strategy}\n\\qbk{[include reference/algorithms/perimeter.qbk]}\n */\ntemplate<typename Geometry, typename Strategy>\ninline typename default_length_result<Geometry>::type perimeter(\n        Geometry const& geometry, Strategy const& strategy)\n{\n    // detail::throw_on_empty_input(geometry);\n    return resolve_variant::perimeter<Geometry>::apply(geometry, strategy);\n}\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ALGORITHMS_PERIMETER_HPP\n\n", "meta": {"hexsha": "0ec153c1f4fa8265209d0fa540fdafd0809847e6", "size": 7153, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/boost_1_56_0/boost/geometry/algorithms/perimeter.hpp", "max_stars_repo_name": "cooparation/caffe-android", "max_stars_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 133.0, "max_stars_repo_stars_event_min_datetime": "2018-04-20T14:09:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-15T11:51:25.000Z", "max_issues_repo_path": "boost/boost_1_56_0/boost/geometry/algorithms/perimeter.hpp", "max_issues_repo_name": "cooparation/caffe-android", "max_issues_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 61.0, "max_issues_repo_issues_event_min_datetime": "2015-05-27T11:20:11.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-20T15:06:21.000Z", "max_forks_repo_path": "boost/boost_1_56_0/boost/geometry/algorithms/perimeter.hpp", "max_forks_repo_name": "cooparation/caffe-android", "max_forks_repo_head_hexsha": "cd91078d1f298c74fca4c242531989d64a32ba03", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 83.0, "max_forks_repo_forks_event_min_datetime": "2018-04-27T03:58:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T09:23:40.000Z", "avg_line_length": 31.2358078603, "max_line_length": 88, "alphanum_fraction": 0.7324199637, "num_tokens": 1505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5039061705290805, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2014675528181386}}
{"text": "#include \"df.hpp\"\n#include \"integration.hpp\"\n#include <boost/python.hpp>\n\nnamespace gd {\nusing namespace boost::python;\n\nvoid py_export_df() {\n\tclass_<DF >(\"DF\", init<ProfileModel*, double_vector, double_vector>())\n\t\t.def(\"moments\", &DF::moments)\n\t\t.def(\"momentsL\", &DF::momentsL)\n\t\t.def(\"momentsL2\", &DF::momentsL2)\n\t\t.def(\"momentsE\", &DF::momentsE)\n\t\t//.def(\"moments_projected\", &DF::moments_projected)\n\t;\n\n}\n/*\ndouble DF::moments_projected(double_vector mass3d, double_vector density, double_vector v, double E, double L, double rp, double ra, double N) {\n\tint nR = Rs.size();\n\tint nr = rs.size();\n\tdouble* Rsp = Rs.data().begin();\n\tdouble* rbordersp = rborders.data().begin();\n\tdouble* rsp = rs.data().begin();\n\tdouble* densityp = density.data().begin();\n\tdouble* mass3dp = mass3d.data().begin();*/\n\t//double* vp = v.data().begin();\n\t/*\n\tauto density_integrand_norm = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\t*/\n\t//IntegratorGSL<> density_integrator_norm(density_integrand_norm);\n/*double R = 0;\n\tint rindex = 0;\n\tdouble rrho = 0;\n\tauto density_integrand = [&](double r) -> double {\n\t\tdouble rhor = mass3dp[rindex]/(4*M_PI*rrho*rrho*rrho);//;;1/N/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t\t//double rhor = 1/N/sqrt(r*r*2*(E-profile_model->potentialr(r))-L*L);\n\t\t//return rhor /r/sqrt(r*r-R*R)*R;\n\t\t//printf(\"r = %10f : %10f : %10f : %10f\\n\", r, rhor, sqrt(r*r-R*R)/r, rhor*sqrt(r*r-R*R)*r);\n\t\t//return rhor /sqrt(r*r-R*R)/r*R;\n\t\t//return rhor /sqrt(r*r/(R*R)-1)*r;\n\t\treturn rhor/sqrt(r*r-R*R)*r*R;\n\t\t//return rhor/sqrt(r*r-R*R)/r*R;\n\t};\n\tIntegratorGSL<> density_integrator(density_integrand, 1000000);\n\t//double N = density_integrator.integrate(rp, ra);\n\t\n\t/*auto varvr_integrand = [&](double r) -> double {\n\t\treturn 1*sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\tIntegratorGSL<> varvr_integrator(varvr_integrand);\n\t*/\n\t\n/*for(int i = 0; i < nR; i++) {\n\t\t//double r1 = rbordersp[i];\n\t\t//double r2 = rbordersp[i+1];\n\t\tR = Rsp[i]; //(r2+r1)/2;\n\t\t//double Er1 = 2*(E-profile_model->potentialr(r1))-L*L/(r1*r1);\n\t\t//double Er2 = 2*(E-profile_model->potentialr(r2))-L*L/(r2*r2);\n\t\tif(R < ra) { // orbits only contribute to R < ra\n\t\t\t/*double R1 = R;//min(R, rp); // integral is 0 for r<rp\n\t\t\tif(rp > R1)\n\t\t\t\tR1 = rp;//*1.0001;\n\t\t\tdouble R2 = ra;//*0.999;\n\t\t\t*/\n/*for(int j = 0; j < nr; j++) {\n\t\t\t\tdouble r1 = rbordersp[j];\n\t\t\t\tdouble r2 = rbordersp[j+1];\n\t\t\t\trrho = rsp[j]; //(r1+r2)/2;\n\t\t\t\trindex = j;\n\t\t\t\tif((mass3dp[rindex]>0) & (r2 > R)) { // if r2 < R, no mass\n\t\t\t\t\tif(r1<R)\n\t\t\t\t\t\tr1 = R; \n\t\t\t\t\tdensityp[i] += density_integrator.integrate(r1,r2);//(R1+R2)/2, R2);\n\t\t\t\t}\n\t\t\t}\n\t\t\t/**/\n\t\t\t/*\n\t\t\tprintf(\"R=%f r1=%f r2=%f R1=%f R2=%f rp=%f ra=%f\\n\", R, r1, r2, R1, R2, rp, ra);\n\t\t\tdouble s = 1.001;\n\t\t\tprintf(\"%f %f %f %f\\n\", density_integrand(R1), density_integrand(R1*s), density_integrand(R2/s), density_integrand(R2));\n\t\t\tprintf(\"%f %f %f %f\\n\", density_integrand((R1+R2)/2), density_integrand(R1*s), density_integrand(R2/s), density_integrand(R2));\n\t\t\t/**/\n\t\t\t\n\t\t\t/*\n\t\t\t * try{\n\t\t\t\t//densityp[i] = density_integrator.integrate_to_sigularity(R1, R2);//(R1+R2)/2, R2);\n\t\t\t\tdensityp[i] = density_integrator.integrate_to_sigularity((R1+R2)/2, R2);//(R1+R2)/2, R2);\n\t\t\t\tdensityp[i] += -density_integrator.integrate((R1+R2)/2, R1);\n\t\t\t} catch(std::range_error& e) {\n\t\t\t}\n\t\t\t/**/\n\t\t\t//varvrp[i] = varvr_integrator.integrate(r1, r2)/N;\n//} else {\n\t\t\t/*if((r1<=rp) & (r2>=ra)) { // peri and api are inside the bin\n\t\t\t\tr1 = rp;\n\t\t\t\tr2 = ra;\n\t\t\t\tdensityp[i] = 1; //density_integrator.integrate(r1, r2)/N;\n\t\t\t\tvarvrp[i] = varvr_integrator.integrate(r1, r2)/N;\n\t\t\t}*/\n//\t}\n//\t}\n//\tdouble total = 0;\n\t/*for(int i = 0; i < n; i++) {\n\t\ttotal += densityp[i];\n\t}\n\tfor(int i = 0; i < n; i++) {\n\t\tif(total > 0)\n\t\t\tdensityp[i] /= total;\n\t}*/\n//return 0;\n//}\n\ndouble DF::velocities(double_vector density, double_vector vr, double_vector vt, double E, double L, double rp, double ra) {\n\tint n = density.size();\n\tdouble* rbordersp = rborders.data().begin();\n\tdouble* densityp = density.data().begin();\n\tdouble* vrp = vr.data().begin();\n\tdouble* vtp = vt.data().begin();\n\t/*\n\tauto density_integrand_norm = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\t*/\n\t//IntegratorGSL<> density_integrator_norm(density_integrand_norm);\n\n\tauto density_integrand = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\tIntegratorGSL<> density_integrator(density_integrand);\n\tdouble N = density_integrator.integrate(rp, ra);\n\t\n\tauto vr_integrand = [&](double r) -> double {\n\t\treturn sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\tIntegratorGSL<> vr_integrator(vr_integrand);\n\t\n\t\n\tfor(int i = 0; i < n; i++) {\n\t\tdouble r1 = rbordersp[i];\n\t\tdouble r2 = rbordersp[i+1];\n\t\tdouble Er1 = 2*(E-profile_model->potentialr(r1))-L*L/(r1*r1);\n\t\tdouble Er2 = 2*(E-profile_model->potentialr(r2))-L*L/(r2*r2);\n\t\tif((Er1>0) | (Er2>0)) {\n\t\t\t// only integrator over the allowable region\n\t\t\tr1 = Er1 > 0 ? r1 : rp;\n\t\t\tr2 = Er2 > 0 ? r2 : ra;\n\t\t\tdensityp[i] = density_integrator.integrate(r1, r2)/N;\n\t\t\tvrp[i] = vr_integrator.integrate(r1, r2);\n\t\t\tvtp[i] = (L*log(r2)-L*log(r1)); // integrated analytically\n\t\t} else {\n\t\t\tif((r1<=rp) & (r2>=ra)) { // peri and api are inside the bin\n\t\t\t\tr1 = rp;\n\t\t\t\tr2 = ra;\n\t\t\t\tdensityp[i] = 1; //density_integrator.integrate(r1, r2)/N;\n\t\t\t\tvrp[i] = vr_integrator.integrate(r1, r2);\n\t\t\t\tvtp[i] = (L*log(r2)-L*log(r1)); // integrated analytically\n\t\t\t}\n\t\t}\n\t}\n\treturn N;\n}\n\ndouble DF::moments(double_vector density, double_vector varvr, double_vector varvt, double E, double L, double rp, double ra) {\n\tint n = density.size();\n\tdouble* rbordersp = rborders.data().begin();\n\tdouble* densityp = density.data().begin();\n\tdouble* varvrp = varvr.data().begin();\n\tdouble* varvtp = varvt.data().begin();\n\t/*\n\tauto density_integrand_norm = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\t*/\n\t//IntegratorGSL<> density_integrator_norm(density_integrand_norm);\n\n\tauto density_integrand = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\tIntegratorGSL<> density_integrator(density_integrand);\n\tdouble N = density_integrator.integrate(rp, ra);\n\t\n\tauto varvr_integrand = [&](double r) -> double {\n\t\treturn 1*sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\tIntegratorGSL<> varvr_integrator(varvr_integrand);\n\t\n\tauto varvt_integrand = [&](double r) -> double {\n\t\treturn L*L/(r*r)/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r))/2;\n\t};\n\tIntegratorGSL<> varvt_integrator(varvt_integrand);\n\tint key = GSL_INTEG_GAUSS41;\n\tfor(int i = 0; i < n; i++) {\n\t\tdouble r1 = rbordersp[i];\n\t\tdouble r2 = rbordersp[i+1];\n\t\tdouble Er1 = 2*(E-profile_model->potentialr(r1))-L*L/(r1*r1);\n\t\tdouble Er2 = 2*(E-profile_model->potentialr(r2))-L*L/(r2*r2);\n\t\tif((Er1>0) | (Er2>0)) {\n\t\t\t// only integrator over the allowable region\n\t\t\tif( (Er1 > 0) & (Er2 > 0) ) {\n\t\t\t\tdensityp[i] = density_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\tvarvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\tvarvtp[i] = varvt_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t} else {\n\t\t\t\tr1 = Er1 > 0 ? r1 : rp;\n\t\t\t\tr2 = Er2 > 0 ? r2 : ra;\n\t\t\t\tdensityp[i] = density_integrator.integrate(r1, r2)/N;\n\t\t\t\tvarvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\tvarvtp[i] = varvt_integrator.integrate(r1, r2)/N;\n\t\t\t}\n\t\t} else {\n\t\t\tif((r1<=rp) & (r2>=ra)) { // peri and api are inside the bin\n\t\t\t\tr1 = rp;\n\t\t\t\tr2 = ra;\n\t\t\t\tdensityp[i] = 1; //density_integrator.integrate(r1, r2)/N;\n\t\t\t\tvarvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\tvarvtp[i] = varvt_integrator.integrate(r1, r2)/N;\n\t\t\t}\n\t\t}\n\t}\n\treturn N;\n\t\n}\n\ndouble DF::momentsL(double_vector density, double_vector varvr, double_vector varvt, double E, double L1, double L2, double rp1, double ra1, double rp2, double ra2, double L, double rp, double ra) {\n\tint n = density.size();\n\tdouble* rbordersp = rborders.data().begin();\n\tdouble* densityp = density.data().begin();\n\tdouble* varvrp = varvr.data().begin();\n\tdouble* varvtp = varvt.data().begin();\n\t/*\n\tauto density_integrand_norm = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\t*/\n\t//IntegratorGSL<> density_integrator_norm(density_integrand_norm);\n\n\tauto density_integrand_L = [&](double r) -> double {\n\t\t// compute the max L that is possible\n\t\tdouble Lclip = sqrt(2*(E-profile_model->potentialr(r)))*r * 0.9999;\n\t\t// clip the L's to this value\n\t\tdouble L1p = min(L1, Lclip);\n\t\tdouble L2p = min(L2, Lclip);\n\t\tdouble Er1 = 2*(E-profile_model->potentialr(r))-L1p*L1p/(r*r);\n\t\tdouble Er2 = 2*(E-profile_model->potentialr(r))-L2p*L2p/(r*r);\n\t\tdouble v =  r* ( atan(L2p/sqrt(Er2)/r) - atan(L1p/sqrt(Er1)/r) );\n\t\t//printf(\"%f %f %f %f : L %f %f %f %f %f: E %f %f\\n\", Er1, Er2, r, v, L1, L2, L1p, L2p, Lclip, Er1, Er2);\n\t\treturn v;\n\t};\n\tauto density_integrand = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\tIntegratorGSL<> density_integrator(density_integrand_L);\n\t//printf(\"N rs: %f %f %f %f\\n\", rp1, rp2, ra1, ra2); \n\tdouble N = 1;//density_integrator.integrate(min(rp1, rp2), max(ra1,ra2));\n\t\n\tauto varvr_integrand = [&](double r) -> double {\n\t\treturn 1*sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\tIntegratorGSL<> varvr_integrator(varvr_integrand);\n\t\n\tauto varvt_integrand = [&](double r) -> double {\n\t\treturn L*L/(r*r)/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r))/2;\n\t};\n\tIntegratorGSL<> varvt_integrator(varvt_integrand);\n\tint key = GSL_INTEG_GAUSS41;\n\tfor(int i = 0; i < n; i++) {\n\t\tdouble r1 = rbordersp[i];\n\t\tdouble r2 = rbordersp[i+1];\n\t\t//double Er1 = 2*(E-profile_model->potentialr(r1))-L*L/(r1*r1);\n\t\t//double Er2 = 2*(E-profile_model->potentialr(r2))-L*L/(r2*r2);\n\t\tvarvrp[i] = i;\n\t\tvarvtp[i] = i;\n\t\tif( (r1 > min(rp1, rp2)) | (r2 < max(ra1, ra2)) ) {// (Er1>0) | (Er2>0)) {\n\t\t\t// only integrator over the allowable region\n\t\t\t//double r1d = max(min(rp1, rp2), r1);\n\t\t\t//double r2d = min(max(ra2, ra2), r2);\n\t\t\t//printf(\"rs: %f %f\\n\", r1d, r2d);\n\t\t\t//if((r1d < r2d)) { // (Er1 > 0) & (Er2 > 0) ) {\n\t\t\t\tdensityp[i] = density_integrator.integrate(r1, r2)/N;\n\t\t\t\t//varvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t//varvtp[i] = varvt_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t//}\n\t\t\t\t/* else {\n\t\t\t\tr1 = Er1 > 0 ? r1 : rp;\n\t\t\t\tr2 = Er2 > 0 ? r2 : ra;\n\t\t\t\tdensityp[i] = density_integrator.integrate(r1d, r2d)/N;\n\t\t\t\t//varvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t//varvtp[i] = varvt_integrator.integrate(r1, r2)/N;\n\t\t\t}*/\n\t\t} else {\n\t\t\tif((r1<=rp) & (r2>=ra)) { // peri and api are inside the bin\n\t\t\t\tr1 = rp;\n\t\t\t\tr2 = ra;\n\t\t\t\t//densityp[i] = 1; //density_integrator.integrate(r1, r2)/N;\n\t\t\t\t//varvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t//varvtp[i] = varvt_integrator.integrate(r1, r2)/N;\n\t\t\t}\n\t\t}\n\t}\n\treturn N;\n\t\n}\t\n\ndouble DF::momentsE(double_vector density, double_vector varvr, double_vector varvt, double E1, double E2, double L, double rp1, double ra1, double rp2, double ra2, double E, double rp, double ra) {\n\tint n = density.size();\n\tdouble* rbordersp = rborders.data().begin();\n\tdouble* densityp = density.data().begin();\n\tdouble* varvrp = varvr.data().begin();\n\tdouble* varvtp = varvt.data().begin();\n\t/*\n\tauto density_integrand_norm = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\t*/\n\t//IntegratorGSL<> density_integrator_norm(density_integrand_norm);\n\n\tauto density_integrand_E = [&](double r) -> double {\n\t\t// compute the max E that is possible\n\t\t//double Eclip = profile_model->potentialr(r) + L*L/(2*r*r) * 1.001; //9999;\n\t\t// clip the E's to this value\n\t\t//double E1p = max(E1, Eclip);\n\t\t//double E2p = max(E2, Eclip);\n\t\tdouble Er1 = 2*(E1-profile_model->potentialr(r))-L*L/(r*r);\n\t\tdouble Er2 = 2*(E2-profile_model->potentialr(r))-L*L/(r*r);\n\t\tdouble v = 0;\n\t\tif(Er1 > 0)\n\t\t\tv += sqrt(Er1);\n\t\tif(Er2 > 0)\n\t\t\tv -= sqrt(Er2);\n\t\tv *= 2;\n\t\t//double v =  r* ( atan(L2p/sqrt(Er2)/r) - atan(L1p/sqrt(Er1)/r) );\n\t\t//double v = 2 * (sqrt(Er1) - sqrt(Er2));\n\t\t//printf(\"%f %f %f %f : L %f %f\\n\", Er1, Er2, r, v, E1, E2);\n\t\treturn -v;\n\t};\n\tauto density_integrand = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\tIntegratorGSL<> density_integrator(density_integrand_E);\n\t//printf(\"N rs: %f %f %f %f\\n\", rp1, rp2, ra1, ra2); \n\tdouble N = 1;//density_integrator.integrate(min(rp1, rp2), max(ra1,ra2));\n\t\n\tauto varvr_integrand = [&](double r) -> double {\n\t\treturn 1*sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\tIntegratorGSL<> varvr_integrator(varvr_integrand);\n\t\n\tauto varvt_integrand = [&](double r) -> double {\n\t\treturn L*L/(r*r)/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r))/2;\n\t};\n\tIntegratorGSL<> varvt_integrator(varvt_integrand);\n\tint key = GSL_INTEG_GAUSS41;\n\tfor(int i = 0; i < n; i++) {\n\t\tdouble r1 = rbordersp[i];\n\t\tdouble r2 = rbordersp[i+1];\n\t\t//double Er1 = 2*(E-profile_model->potentialr(r1))-L*L/(r1*r1);\n\t\t//double Er2 = 2*(E-profile_model->potentialr(r2))-L*L/(r2*r2);\n\t\tvarvrp[i] = i;\n\t\tvarvtp[i] = i;\n\t\tif( (r1 > min(rp1, rp2)) & (r2 < max(ra1, ra2)) ) {// (Er1>0) | (Er2>0)) {\n\t\t\t// only integrator over the allowable region\n\t\t\t//double r1d = max(min(rp1, rp2), r1);\n\t\t\t//double r2d = min(max(ra2, ra2), r2);\n\t\t\t//printf(\"rs: %f %f : %f %f : %f %f \\n\", r1, r2, rp1, ra1, rp2, ra2);\n\t\t\t//if((r1d < r2d)) { // (Er1 > 0) & (Er2 > 0) ) {\n\t\t\t// TODO: clip values r1 and r2 such that there is al least one positive energyy\n\t\t\t\t{\tdensityp[i] = density_integrator.integrate(r1, r2)/N;\n\t\t\t\t//varvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t//varvtp[i] = varvt_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t}/* else {\n\t\t\t\tr1 = Er1 > 0 ? r1 : rp;\n\t\t\t\tr2 = Er2 > 0 ? r2 : ra;\n\t\t\t\tdensityp[i] = density_integrator.integrate(r1d, r2d)/N;\n\t\t\t\t//varvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t//varvtp[i] = varvt_integrator.integrate(r1, r2)/N;\n\t\t\t}*/\n\t\t} else {\n\t\t\tif((r1<=rp) & (r2>=ra)) { // peri and api are inside the bin\n\t\t\t\tr1 = rp;\n\t\t\t\tr2 = ra;\n\t\t\t\t//densityp[i] = 1; //density_integrator.integrate(r1, r2)/N;\n\t\t\t\t//varvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t//varvtp[i] = varvt_integrator.integrate(r1, r2)/N;\n\t\t\t}\n\t\t}\n\t}\n\treturn N;\n\t\n}\n\ndouble DF::momentsL2(double_vector density, double_vector varvr, double_vector varvt, double_vector v22, double_vector v40, double_vector v04, double E, double L1, double L2, double rp, double ra, bool debug) {\n\tint n = density.size();\n\tdouble* rbordersp = rborders.data().begin();\n\tdouble* densityp = density.data().begin();\n\tdouble* varvrp = varvr.data().begin();\n\tdouble* varvtp = varvt.data().begin();\n\tdouble* v40p = v40.data().begin();\n\tdouble* v04p = v04.data().begin();\n\tdouble* v22p = v22.data().begin();\n/*\n\tauto density_integrand_norm = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};\n\t*/\n\t//IntegratorGSL<> density_integrator_norm(density_integrand_norm);\n\tdouble N = 1;\n\tdouble epsabs = 0;//1e-6;\n\tdouble epsrel = 1e-6;\n\tauto density_integrand_L = [&](double r) -> double {\n\t\t// compute the max L that is possible\n\t\tdouble Lmax = sqrt(2*(E-profile_model->potentialr(r)))*r;// * 0.9999;\n\t\t// clip the L's to this value\n\t\tdouble v1 = 0;\n\t\tdouble v2 = 0;\n\t\tif(L1 >= Lmax)\n\t\t\treturn 0;\n\t\tif(L1 < Lmax) {\n\t\t\tdouble Er = 2*(E-profile_model->potentialr(r))-L1*L1/(r*r);\n\t\t\tv1 = atan(L1/(sqrt(Er)*r));\n\t\t} else {\n\t\t\tv1 = M_PI/2; //atan(1);\n\t\t}\n\t\tif(L2 < Lmax) {\n\t\t\tdouble Er = 2*(E-profile_model->potentialr(r))-L2*L2/(r*r);\n\t\t\tv2 = atan(L2/(sqrt(Er)*r));\n\t\t} else {\n\t\t\tv2 = M_PI/2;//atan(1);\n\t\t}\n\t\t\t\n\t\t//double L1p = min(L1, Lclip);\n\t\t//double L2p = min(L2, Lclip);\n\t\t//double Er1 = 2*(E-profile_model->potentialr(r))-L1p*L1p/(r*r);\n\t\t//double Er2 = 2*(E-profile_model->potentialr(r))-L2p*L2p/(r*r);\n\t\t//double v =  r* ( atan(L2p/(sqrt(Er2)*r)) - atan(L1p/(sqrt(Er1)*r)) );\n\t\tdouble v =  r* ( v2 - v1 );\n\t\tif((v < 0) & (fabs((v2 - v1)/(v2+v1)) < 1e-8))\n\t\t\tv = 0;\n\t\tif(v < 0) {\n\t\t\tprintf(\"L %f %f %f %f %f]\\n\", L1, L2, Lmax, v1, v2);\n\t\t\tassert(v >= 0);\n\t\t}\n\t\tif(debug)\n\t\t\tprintf(\"L1=%f L2=%f Lmax=%f E=%f v1=%f v2=%f dv=%f r=%f\\n\", L1, L2, Lmax, E, v1, v2, v2-v1, r);\n\t\t\n\t\t//printf(\"[%f %f %f %f : L %f %f %f %f %f: E %f %f]\\n\", Er1, Er2, r, v, L1, L2, L1p, L2p, Lclip, Er1, Er2);\n\t\treturn v;\n\t};\n\t/*auto density_integrand = [&](double r) -> double {\n\t\treturn 1/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r));\n\t};*/\n\tIntegratorGSL<> density_integrator(density_integrand_L, 10000, epsrel, epsabs);\n\t//printf(\"N rs: %f %f %f %f\\n\", rp1, rp2, ra1, ra2); \n\t//double N = density_integrator.integrate(min(rp1, rp2), max(ra1,ra2));\n\ttry {\n\t\tN = density_integrator.integrate_to_sigularity(rp, ra);\n\t} catch(std::exception& e) {\n\t\tprintf(\"could not compute normalization rp=%f ra=%f\\n\", rp, ra);\n\t\tthrow;\n\t}\n\t\n\tif(debug)\n\t\tprintf(\"N = %f\\n\", N);\n\t\n\tauto varvr_integrand = [&](double r) -> double {\n\t\tdouble Lmax = sqrt(2*(E-profile_model->potentialr(r)))*r;\n\t\tdouble v1 = 0;\n\t\tdouble v2 = 0;\n\t\tdouble c = 2*(E-profile_model->potentialr(r)) * r * r;\n\t\tif(L1 >= Lmax)\n\t\t\treturn 0;\n\t\tif(L1 < Lmax) {\n\t\t\t//double Er = 2*(E-profile_model->potentialr(r))-L1*L1/(r*r);\n\t\t\tv1 = (L1 * sqrt(c-L1*L1) + c * atan(L1/sqrt(c-L1*L1)))/r/2;\n\t\t} else {\n\t\t\tv1 = M_PI/4 * c/r;\n\t\t}\n\t\tif(L2 < Lmax) {\n\t\t\tv2 = (L2 * sqrt(c-L2*L2) + c * atan(L2/sqrt(c-L2*L2)))/r/2;\n\t\t} else {\n\t\t\tv2 = M_PI/4 * c/r;\n\t\t}\n\t\t\n\t\tdouble v =  ( v2 - v1 );\n\t\tif((v < 0) & (fabs((v2 - v1)/(v2+v1)) < 1e-8))\n\t\t\tv = 0;\n\t\tif(v < 0) {\n\t\t\tprintf(\"L %f %f %f %f %f]\\n\", L1, L2, Lmax, v1, v2);\n\t\t\tassert(v >= 0);\n\t\t}\n\t\t//printf(\"[%f %f %f %f : L %f %f %f %f %f: E %f %f]\\n\", Er1, Er2, r, v, L1, L2, L1p, L2p, Lclip, Er1, Er2);\n\t\treturn v;\n\t};\n\tIntegratorGSL<> varvr_integrator(varvr_integrand, 10000, epsrel, epsabs);\n\t\n\t\n\tauto v40_integrand = [&](double r) -> double {\n\t\tdouble Lmax = sqrt(2*(E-profile_model->potentialr(r)))*r;\n\t\tdouble v1 = 0;\n\t\tdouble v2 = 0;\n\t\tdouble c = 2*(E-profile_model->potentialr(r)) * r * r;\n\t\tassert(L1 < L2);\n\t\tif(L1 >= Lmax)\n\t\t\treturn 0;\n\t\tif(L1 < Lmax) {\n\t\t\t//double Er = 2*(E-profile_model->potentialr(r))-L1*L1/(r*r);\n\t\t\tv1 = (L1 * (5*c - 2*L1*L1) * sqrt(c-L1*L1) + 3 * c*c * atan(L1/sqrt(c-L1*L1)))/(8) /r/ r/r;\n\t\t} else {\n\t\t\tv1 = M_PI/16 * 3 * c * c /r/r/r;\n\t\t}\n\t\tif(L2 < Lmax) {\n\t\t\tv2 = (L2 * (5*c - 2*L2*L2) * sqrt(c-L2*L2) + 3 * c*c * atan(L2/sqrt(c-L2*L2)))/(8) /r/r/r;\n\t\t\t//v2 = (L2 * sqrt(c-L2*L2) + c * atan(L2/sqrt(c-L2*L2)))/r/2;\n\t\t} else {\n\t\t\tv2 = M_PI/16 * 3 * c * c/r/r/r;\n\t\t}\n\t\t\n\t\tdouble v =  ( v2 - v1 );\n\t\tif((v < 0) & (fabs((v2 - v1)/(v2+v1)) < 1e-8))\n\t\t   v = 0;\n\t\tif(v < 0) {\n\t\t\tprintf(\"L %e %e %e %e %e %e]\\n\", L1, L2, Lmax, v1, v2, v);\n\t\t\tassert(v >= 0);\n\t\t}\n\t\t//printf(\"[%f %f %f %f : L %f %f %f %f %f: E %f %f]\\n\", Er1, Er2, r, v, L1, L2, L1p, L2p, Lclip, Er1, Er2);\n\t\treturn v;\n\t};\n\tIntegratorGSL<> v40_integrator(v40_integrand, 10000, epsrel, epsabs);\t\n\t\n\t\n\tauto v04_integrand = [&](double r) -> double {\n\t\tdouble Lmax = sqrt(2*(E-profile_model->potentialr(r)))*r;\n\t\tdouble v1 = 0;\n\t\tdouble v2 = 0;\n\t\tdouble c = 2*(E-profile_model->potentialr(r)) * r * r;\n\t\tif(L1 >= Lmax)\n\t\t\treturn 0;\n\t\tif(L1 < Lmax) {\n\t\t\t//double Er = 2*(E-profile_model->potentialr(r))-L1*L1/(r*r);\n\t\t\tv1 = (-L1 * (3*c + 2*L1*L1) * sqrt(c-L1*L1) + 3 * c*c * atan(L1/sqrt(c-L1*L1)))/(8) /r/r/r;\n\t\t} else {\n\t\t\tv1 = M_PI/16 * 3 * c * c /r/r/r;\n\t\t}\n\t\tif(L2 < Lmax) {\n\t\t\tv2 = (-L2 * (3*c + 2*L2*L2) * sqrt(c-L2*L2) + 3 * c*c * atan(L2/sqrt(c-L2*L2)))/(8) /r/r/r;\n\t\t\t//v2 = (L2 * sqrt(c-L2*L2) + c * atan(L2/sqrt(c-L2*L2)))/r/2;\n\t\t} else {\n\t\t\tv2 = M_PI/16 * 3 * c * c/r/r/r;\n\t\t}\n\t\t\n\t\tdouble v =  ( v2 - v1 );\n\t\tif((v < 0) & (fabs((v2 - v1)/(v2+v1)) < 1e-8))\n\t\t\tv = 0;\n\t\tif(v < 0) {\n\t\t\tprintf(\"L %f %f %f %f %f]\\n\", L1, L2, Lmax, v1, v2);\n\t\t\tassert(v >= 0);\n\t\t}\n\t\tif(debug)\n\t\t\tprintf(\"L1=%f L2=%f Lmax=%f E=%f v1=%f v2=%f dv=%f c=%f r=%f\\n\", L1, L2, Lmax, E, v1, v2, v2-v1, c, r);\n\t\t//printf(\"[%f %f %f %f : L %f %f %f %f %f: E %f %f]\\n\", Er1, Er2, r, v, L1, L2, L1p, L2p, Lclip, Er1, Er2);\n\t\treturn v;\n\t};\n\tIntegratorGSL<> v04_integrator(v04_integrand, 10000, epsrel, epsabs);\n\t\n\tauto v22_integrand = [&](double r) -> double {\n\t\tdouble Lmax = sqrt(2*(E-profile_model->potentialr(r)))*r;\n\t\tdouble v1 = 0;\n\t\tdouble v2 = 0;\n\t\tdouble c = 2*(E-profile_model->potentialr(r)) * r * r;\n\t\tconst int p = 3;\n\t\tif(L1 >= Lmax)\n\t\t\treturn 0;\n\t\tif(L1 < Lmax) {\n\t\t\t//double Er = 2*(E-profile_model->potentialr(r))-L1*L1/(r*r);\n\t\t\tv1 = (L1 * (-c +2*L1*L1) * sqrt(c-L1*L1) + c*c * atan(L1/sqrt(c-L1*L1)))/(8) /pow(r, p);\n\t\t} else {\n\t\t\tv1 = M_PI/16 * c*c /pow(r, p);\n\t\t}\n\t\tif(L2 < Lmax) {\n\t\t\tv2 = (L2 * (-c +2*L2*L2) * sqrt(c-L2*L2) + c*c * atan(L2/sqrt(c-L2*L2)))/(8) /pow(r, p);\n\t\t\t//v2 = (L2 * sqrt(c-L2*L2) + c * atan(L2/sqrt(c-L2*L2)))/r/2;\n\t\t} else {\n\t\t\tv2 = M_PI/16 * c*c /pow(r, p);\n\t\t}\n\t\t\n\t\tdouble v =  ( v2 - v1 );\n\t\tif((v < 0) & (fabs((v2 - v1)/(v2+v1)) < 1e-8))\n\t\t\tv = 0;\n\t\tif(v < 0) {\n\t\t\tprintf(\"L %f %f %f %f %f]\\n\", L1, L2, Lmax, v1, v2);\n\t\t\tassert(v >= 0);\n\t\t}\n\t\t//printf(\"[%f %f %f %f : L %f %f %f %f %f: E %f %f]\\n\", Er1, Er2, r, v, L1, L2, L1p, L2p, Lclip, Er1, Er2);\n\t\treturn v;\n\t};\n\tIntegratorGSL<> v22_integrator(v22_integrand, 10000, epsrel, epsabs);\n\t\n\t/*auto varvt_integrand = [&](double r) -> double {\n\t\treturn L*L/(r*r)/sqrt(2*(E-profile_model->potentialr(r))-L*L/(r*r))/2;\n\t};*/\n\t\n\tauto varvt_integrand = [&](double r) -> double {\n\t\tdouble Lmax = sqrt(2*(E-profile_model->potentialr(r)))*r;\n\t\tdouble v1 = 0;\n\t\tdouble v2 = 0;\n\t\tdouble c = 2*(E-profile_model->potentialr(r)) * r * r;\n\t\tif(L1 < Lmax) {\n\t\t\tv1 = (-L1 * sqrt(c-L1*L1) + c * atan(L1/sqrt(c-L1*L1)))/r/2;\n\t\t} else {\n\t\t\tv1 = M_PI/4 * c/r;\n\t\t}\n\t\tif(L2 < Lmax) {\n\t\t\tv2 = (-L2 * sqrt(c-L2*L2) + c * atan(L2/sqrt(c-L2*L2)))/r/2;\n\t\t} else {\n\t\t\tv2 = M_PI/4 * c/r;\n\t\t}\n\t\t\n\t\tdouble v =  ( v2 - v1 );\n\t\tif((v < 0) & (fabs((v2 - v1)/(v2+v1)) < 1e-8))\n\t\t\tv = 0;\n\t\tif(v < 0) {\n\t\t\tprintf(\"L %f %f %f %f %f]\\n\", L1, L2, Lmax, v1, v2);\n\t\t\tassert(v >= 0);\n\t\t}\n\t\t//printf(\"[%f %f %f %f : L %f %f %f %f %f: E %f %f]\\n\", Er1, Er2, r, v, L1, L2, L1p, L2p, Lclip, Er1, Er2);\n\t\treturn v;\n\t};\n\tIntegratorGSL<> varvt_integrator(varvt_integrand, 10000, epsrel, epsabs);\n\t\n\t\n\tint key = GSL_INTEG_GAUSS41;\n\t//double r_apo = rbordersp[n]; / r borders array should have length n+1 \n\t//double r_apo = rbordersp[n];\n\tfor(int i = 0; i < n; i++) {\n\t\tdouble r1 = rbordersp[i];\n\t\tdouble r2 = rbordersp[i+1];\n\t\tdouble Er1 = 2*(E-profile_model->potentialr(r1))-L1*L1/(r1*r1);\n\t\tdouble Er2 = 2*(E-profile_model->potentialr(r2))-L1*L1/(r2*r2);\n\t\tvarvrp[i] = 0;\n\t\tvarvtp[i] = 0;\n\t\tif(debug)\n\t\t\tprintf(\"r1=%f r2=%f\\n\", r1, r2);\n\t\tif((Er1 > 0) | (Er2 > 0)) { //  (r1 > min(rp1, rp2)) | (r2 < max(ra1, ra2)) ) {// (Er1>0) | (Er2>0)) {\n\t\t\tif(Er1 < 0) {\n\t\t\t\tif(debug)\n\t\t\t\t\tprintf(\"looking for root r1 [%f, %f]\\n\", r1, r2);\n\t\t\t\tauto ekinrad = [&](double r) -> double { // kinetic energy in radial direction\n\t\t\t\t\treturn (-L1*L1/(2*r*r) - (this->profile_model->potentialr(r) - E));\n\t\t\t\t};\n\t\t\t\tRootFinderGSL<> rootfinder(ekinrad);\n\t\t\t\tr1 = rootfinder.findRoot(r1, r2);\n\t\t\t\tdouble scale = (1+1e-5);\n\t\t\t\twhile(ekinrad(r1) < 0) {\n\t\t\t\t\tr1 *= scale;\n\t\t\t\t}\n\t\t\t\tif(debug)\n\t\t\t\t\tprintf(\"found root r1 [%f, %f]\\n\", r1, r2);\n\t\t\t}\n\t\t\tif(Er2 < 0) {\n\t\t\t\tif(debug)\n\t\t\t\t\tprintf(\"looking for root r2 [%f, %f]\\n\", r1, r2);\n\t\t\t\tauto ekinrad = [&](double r) -> double { // kinetic energy in radial direction\n\t\t\t\t\treturn (-L1*L1/(2*r*r) - (this->profile_model->potentialr(r) - E));\n\t\t\t\t};\n\t\t\t\tRootFinderGSL<> rootfinder(ekinrad);\n\t\t\t\tdouble scale = (1+1e-5);\n\t\t\t\tr2 = rootfinder.findRoot(r1, r2);\n\t\t\t\twhile(ekinrad(r2) < 0) {\n\t\t\t\t\tr2 /= scale;\n\t\t\t\t}\n\t\t\t\tif(debug)\n\t\t\t\t\tprintf(\"found root r2 [%f, %f]\\n\", r1, r2);\n\t\t\t}\n\t\t\tif(r1<r2) {\n\t\t\t\t//printf(\"v00\\n\"); fflush(stdout);\n\t\t\t\tdouble rc = (r1+r2)/2;\n\t\t\t\ttry {\n\t\t\t\t\t//double rho = density_integrator.integrate(r1, r2)/N;\n\t\t\t\t\tdensityp[i] = -density_integrator.integrate_to_sigularity(rc,r1)/N*2;\n\t\t\t\t\tdensityp[i] += density_integrator.integrate_to_sigularity(rc,r2)/N*2;\n\t\t\t\t\t//densityp[i] = rho;\n\t\t\t\t} catch(std::exception& e) {\n\t\t\t\t\tprintf(\"could not compute density for r[%f,%f]\\n\", r1, r2);\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t\t//printf(\"rs: %f %f, rho=%f\\n\", r1, r2, rho);\n\t\t\t\t//printf(\"v20\\n\"); fflush(stdout);\n\t\t\t\ttry {\n\t\t\t\t\tvarvrp[i] = -varvr_integrator.integrate_to_sigularity(rc,r1)/N*2;\n\t\t\t\t\tvarvrp[i] += varvr_integrator.integrate_to_sigularity(rc,r2)/N*2;\n\t\t\t\t\t//varvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t} catch(std::exception& e) {\n\t\t\t\t\tprintf(\"could not compute v20 for r[%f,%f]\\n\", r1, r2);\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t\t//printf(\"v02\\n\"); fflush(stdout);\n\t\t\t\ttry {\n\t\t\t\t\tvarvtp[i] = -varvt_integrator.integrate_to_sigularity(rc,r1)/N*2;\n\t\t\t\t\tvarvtp[i] += varvt_integrator.integrate_to_sigularity(rc,r2)/N*2;\n\t\t\t\t\t//varvtp[i] = varvt_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t} catch(std::exception& e) {\n\t\t\t\t\tprintf(\"could not compute v02 for r[%f,%f]\\n\", r1, r2);\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t\t//printf(\"v40\\n\"); fflush(stdout);\n\t\t\t\ttry {\n\t\t\t\t\tv40p[i] = -v40_integrator.integrate_to_sigularity(rc,r1)/N*2;\n\t\t\t\t\tv40p[i] += v40_integrator.integrate_to_sigularity(rc,r2)/N*2;\n\t\t\t\t\t//v40p[i] = v40_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t} catch(std::exception& e) {\n\t\t\t\t\tprintf(\"could not compute v40 for r[%f,%f]\\n\", r1, r2);\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t\t//printf(\"v04\\n\"); fflush(stdout);\n\t\t\t\ttry {\n\t\t\t\t\tv04p[i] = -v04_integrator.integrate_to_sigularity(rc,r1)/N*2;\n\t\t\t\t\tv04p[i] += v04_integrator.integrate_to_sigularity(rc,r2)/N*2;\n\t\t\t\t\t//v04p[i] = v04_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t} catch(std::exception& e) {\n\t\t\t\t\tprintf(\"could not compute v04 for r[%f,%f] rp=%f ra=%f\\n\", r1, r2, rp, ra);\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t\t//printf(\"v22\\n\"); fflush(stdout);\n\t\t\t\ttry {\n\t\t\t\t\tv22p[i] = -v22_integrator.integrate_to_sigularity(rc,r1)/N*2;\n\t\t\t\t\tv22p[i] += v22_integrator.integrate_to_sigularity(rc,r2)/N*2;\n\t\t\t\t\t//v22p[i] = v22_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t} catch(std::exception& e) {\n\t\t\t\t\tprintf(\"could not compute v22 for r[%f,%f]\\n\", r1, r2);\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//printf(\"done\\n\"); fflush(stdout);\n//}\n\t\t\t\t/* else {\n\t\t\t\tr1 = Er1 > 0 ? r1 : rp;\n\t\t\t\tr2 = Er2 > 0 ? r2 : ra;\n\t\t\t\tdensityp[i] = density_integrator.integrate(r1d, r2d)/N;\n\t\t\t\t//varvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t//varvtp[i] = varvt_integrator.integrate(r1, r2)/N;\n\t\t\t}*/\n\t\t} else {\n\t\t\t//if((r1<=rp) & (r2>=ra)) { // peri and api are inside the bin\n\t\t\t//\tr1 = rp;\n\t\t\t//\tr2 = ra;\n\t\t\t\t//densityp[i] = 1; //density_integrator.integrate(r1, r2)/N;\n\t\t\t\t//varvrp[i] = varvr_integrator.integrate_no_singularities(r1, r2, key)/N;\n\t\t\t\t//varvtp[i] = varvt_integrator.integrate(r1, r2)/N;\n\t\t\t//}\n\t\t}\n\t}\n\treturn N;\n\t\n}\t\n\n\t\n};\n\n", "meta": {"hexsha": "5b707817fcbadcc14e3a849dad5f01fc4805c4b1", "size": 26859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/df.cpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/df.cpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/df.cpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2943495401, "max_line_length": 210, "alphanum_fraction": 0.5939908411, "num_tokens": 10539, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947425132314, "lm_q2_score": 0.30735801686526387, "lm_q1q2_score": 0.20128714931435443}}
{"text": "#include <iostream>\n#include <armadillo>\n#include <mpi.h>\n#include <omp.h>\n#include <mkl.h>\n\n#include \"class_data.hpp\"\n#include \"class_approximation.hpp\"\n#include \"class_partition.hpp\"\n#include \"evaluate_covariance.hpp\"\n#include \"constants.hpp\"\n#include <string.h>\n\n\nvoid Approximation::predict()\n{\n    if(WORKER == 0)\n    {\n        gettimeofday(&timeNow, NULL);\n        cout<<\"===========================> Processor 1: predicting starts. Elapsed time: \"<<(double)timeNow.tv_sec-(double)timeBegin.tv_sec+((double)timeNow.tv_usec-(double)timeBegin.tv_usec)/1000000.0<<\" seconds.\\n\";\n    }\n\t\t\t\n\n    int maxOpenMPThreads=omp_get_max_threads();\n    int currentLevel = NUM_LEVELS_M-1;\n    unsigned long indexRegionAtThisLevel = 0;\n    int nKnots = partition->nKnots;\n    char L='L', N='N';\n\n    //Define indices of all the ancestors for the current region\n    unsigned long **ancestorArray = new unsigned long* [maxOpenMPThreads];\n    for(int i = 0; i < maxOpenMPThreads; i++) ancestorArray[i] = new unsigned long [currentLevel];\n\n    //Recalculate WORKERS_FOR_EACH_REGION\n    if(NUM_LEVELS_M>2)\n    {\n        for(unsigned long iRegion = partition->nRegionsInTotal-partition->nRegionsAtEachLevel[NUM_LEVELS_M-1]-partition->nRegionsAtEachLevel[NUM_LEVELS_M-2]; iRegion < partition->nRegionsInTotal-partition->nRegionsAtEachLevel[NUM_LEVELS_M-1]; iRegion++)\n        {\n            unsigned long ancestor = (iRegion-1)/NUM_PARTITIONS_J;\n            while(ancestor>0)\n            {\n                WORKERS_FOR_EACH_REGION[ancestor].insert(WORKERS_FOR_EACH_REGION[iRegion].begin(),WORKERS_FOR_EACH_REGION[iRegion].end());\n                ancestor = (ancestor-1)/NUM_PARTITIONS_J;\n            }\n        }\n    }\n\n    //Synchronize RChol, KCholTimesCurrentw and KCholTimesCurrentA\n    if(WORKER==0)\n    {\n        for(int iWorker = 1; iWorker < MPI_SIZE; iWorker++)\n        {\n            MPI_Send(KCholTimesCurrentw[0].memptr(),partition->nKnots,MPI_DOUBLE,iWorker,MPI_TAG_VEC,WORLD);\n            MPI_Send(RChol[0].memptr(),partition->nKnots*partition->nKnots,MPI_DOUBLE,iWorker,MPI_TAG_MAT,WORLD);\n        }\n    }\n    else\n    {\n        KCholTimesCurrentw[0].set_size(partition->nKnots);\n        MPI_Recv(KCholTimesCurrentw[0].memptr(),partition->nKnots,MPI_DOUBLE,0,MPI_TAG_VEC,WORLD,MPI_STATUS_IGNORE);\n        MPI_Recv(RChol[0].memptr(),partition->nKnots*partition->nKnots,MPI_DOUBLE,0,MPI_TAG_MAT,WORLD,MPI_STATUS_IGNORE);\n    }\n\n    unsigned long regionStart = 1, regionEnd = NUM_PARTITIONS_J+1;\n    for(int currentLevel = 1; currentLevel < NUM_LEVELS_M-1; currentLevel++)\n    {\n        #pragma omp parallel for schedule(dynamic,1)\n        for(unsigned long iRegion = regionStart; iRegion < regionEnd; iRegion++)\n        {\n            if(WORKERS_FOR_EACH_REGION[iRegion].size() > 1)\n            {\n                std::set<unsigned long>::iterator workerToSend = WORKERS_FOR_EACH_REGION[iRegion].begin();\n                \n                if(WORKER==*workerToSend)\n                {\n                    //Supervisor, send KCholTimesCurrentw[iRegion] to other workers\n                    for(workerToSend++; workerToSend != WORKERS_FOR_EACH_REGION[iRegion].end(); workerToSend++)\n                    {\n                        MPI_Send(KCholTimesCurrentw[iRegion].memptr(),partition->nKnots,MPI_DOUBLE,*workerToSend,MPI_TAG_VEC,WORLD);\n                        MPI_Send(KCholTimesCurrentA[iRegion].memptr(),partition->nKnots*partition->nKnots*currentLevel,MPI_DOUBLE,*workerToSend,MPI_TAG_MAT,WORLD);\n                        MPI_Send(RChol[iRegion].memptr(),partition->nKnots*partition->nKnots,MPI_DOUBLE,*workerToSend,MPI_TAG_MAT,WORLD);\n                    }\n                }else\n                {\n                    for(workerToSend++; workerToSend != WORKERS_FOR_EACH_REGION[iRegion].end(); workerToSend++)\n                    {\n                        if(WORKER!=*workerToSend) continue;\n                        //Not supervisor, receive KCholTimesCurrentw[iRegion] from supervisor\n                        KCholTimesCurrentw[iRegion].set_size(partition->nKnots);\n                        KCholTimesCurrentA[iRegion].set_size(partition->nKnots,partition->nKnots,currentLevel);\n                        RChol[iRegion].set_size(partition->nKnots,partition->nKnots);\n                        \n                        MPI_Recv(KCholTimesCurrentw[iRegion].memptr(),partition->nKnots,MPI_DOUBLE,*WORKERS_FOR_EACH_REGION[iRegion].begin(),MPI_TAG_VEC,WORLD,MPI_STATUS_IGNORE);\n                        MPI_Recv(KCholTimesCurrentA[iRegion].memptr(),partition->nKnots*partition->nKnots*currentLevel,MPI_DOUBLE,*WORKERS_FOR_EACH_REGION[iRegion].begin(),MPI_TAG_MAT,WORLD,MPI_STATUS_IGNORE);\n                        MPI_Recv(RChol[iRegion].memptr(),partition->nKnots*partition->nKnots,MPI_DOUBLE,*WORKERS_FOR_EACH_REGION[iRegion].begin(),MPI_TAG_MAT,WORLD,MPI_STATUS_IGNORE);\n                        break;\n                    }\n                }\n            }\n        }\n        regionStart = regionStart*NUM_PARTITIONS_J+1;\n        regionEnd = regionEnd*NUM_PARTITIONS_J+1;\n    }\n\n    #pragma omp parallel for schedule(dynamic,1)\n    for(unsigned long iRegion = REGION_START[NUM_LEVELS_M-1]; iRegion < REGION_END[NUM_LEVELS_M-1] + 1; iRegion++)\n    {\n        int rankOpenMP = omp_get_thread_num();\n        int status;\n        unsigned long indexRegionAtThisLevel = iRegion-partition->nRegionsInTotal+partition->nRegionsAtEachLevel[NUM_LEVELS_M-1];\n        int nPredictionsInCurrentRegion = partition->nPredictionsAtFinestLevel[indexRegionAtThisLevel];\n        if(nPredictionsInCurrentRegion == 0) continue;\n\n        //Find the indices of all the ancestors\n        get_all_ancestors(ancestorArray[rankOpenMP], iRegion, currentLevel);\n        \n        int jLevel = currentLevel-1;\n        mat* KcBTilde;\n        mat** tmpBTilde = new mat* [jLevel];\n        \n        //KcBTilde := RChol[ancestorArray[rankOpenMP][jLevel]])^(-1)*BTilde[indexRegionAtThisLevel][jLevel]\n        KcBTilde = new mat(BTilde[indexRegionAtThisLevel][jLevel],nKnots,nPredictionsInCurrentRegion,true,true);\n        dtrtrs_(&L,&N,&N,&nKnots,&nPredictionsInCurrentRegion,RChol[ancestorArray[rankOpenMP][jLevel]].memptr(),&nKnots,KcBTilde->memptr(),&nKnots,&status);\n        \n        for(int kLevelBeforejLevel = 0 ; kLevelBeforejLevel < jLevel; kLevelBeforejLevel++)\n        {\n            //tmpBTilde[kLevelBeforejLevel] := BTilde[indexRegionAtThisLevel][kLevelBeforejLevel].t()-KCholTimesCurrentA[ancestorArray[rankOpenMP][currentLevel-1]].slice(kLevelBeforejLevel).t()*KcBTilde\n            tmpBTilde[kLevelBeforejLevel] = new mat(BTilde[indexRegionAtThisLevel][kLevelBeforejLevel],nKnots,nPredictionsInCurrentRegion,false,true);\n            cblas_dgemm(CblasColMajor,CblasTrans,CblasNoTrans,nKnots,nPredictionsInCurrentRegion,nKnots,-1.0,KCholTimesCurrentA[ancestorArray[rankOpenMP][currentLevel-1]].slice(kLevelBeforejLevel).memptr(),nKnots,KcBTilde->memptr(),nKnots,1.0,tmpBTilde[kLevelBeforejLevel]->memptr(),nKnots);\n        }\n        delete KcBTilde;\n        \n        for(int jLevel = currentLevel-2; jLevel > 0; jLevel--)\n        {\n            //KcBTilde := RChol[ancestorArray[rankOpenMP][jLevel]])^(-1)*tmpBTilde[jLevel])\n            KcBTilde = new mat(tmpBTilde[jLevel]->memptr(),nKnots,nPredictionsInCurrentRegion,true,true);\n            dtrtrs_(&L,&N,&N,&nKnots,&nPredictionsInCurrentRegion,RChol[ancestorArray[rankOpenMP][jLevel]].memptr(),&nKnots,KcBTilde->memptr(),&nKnots,&status);\n            \n            for(int kLevelBeforejLevel = 0 ; kLevelBeforejLevel < jLevel; kLevelBeforejLevel++)\n            {\n                //tmpBTilde[kLevelBeforejLevel] := tmpBTilde[kLevelBeforejLevel]-KCholTimesCurrentA[ancestorArray[rankOpenMP][jLevel]].slice(kLevelBeforejLevel).t()*KcBTilde\n                cblas_dgemm(CblasColMajor,CblasTrans,CblasNoTrans,nKnots,nPredictionsInCurrentRegion,nKnots,-1.0,KCholTimesCurrentA[ancestorArray[rankOpenMP][jLevel]].slice(kLevelBeforejLevel).memptr(),nKnots,KcBTilde->memptr(),nKnots,1.0,tmpBTilde[kLevelBeforejLevel]->memptr(),nKnots);\n            }\n\n            delete KcBTilde;\n        }\n        \n        for(jLevel = 0; jLevel < currentLevel-1; jLevel++)\n        {\n            //KcBTilde := RChol[ancestorArray[rankOpenMP][jLevel]])^(-1)*tmpBTilde[jLevel])\n            KcBTilde = new mat(tmpBTilde[jLevel]->memptr(),nKnots,nPredictionsInCurrentRegion,false,true);\n            \n            dtrtrs_(&L,&N,&N,&nKnots,&nPredictionsInCurrentRegion,RChol[ancestorArray[rankOpenMP][jLevel]].memptr(),&nKnots,KcBTilde->memptr(),&nKnots,&status);\n            \n            //posteriorPredictionMean[indexRegionAtThisLevel] += KcBTilde.t()*KCholTimesCurrentw[ancestorArray[rankOpenMP][jLevel]]\n            cblas_dgemv(CblasColMajor,CblasTrans,nKnots,nPredictionsInCurrentRegion,1.0,KcBTilde->memptr(),nKnots,KCholTimesCurrentw[ancestorArray[rankOpenMP][jLevel]].memptr(),1,1.0,posteriorPredictionMean[indexRegionAtThisLevel].memptr(),1);\n\n            //posteriorPredictionVariance[indexRegionAtThisLevel] += columnSum(KcBTilde.^2);\n            posteriorPredictionVariance[indexRegionAtThisLevel] += sum(square(*KcBTilde),0).t();\n        }\n\n        jLevel=currentLevel-1;\n        \n        //KcBTilde := RChol[ancestorArray[rankOpenMP][jLevel]])^(-1)*BTilde[indexRegionAtThisLevel][jLevel])\n        KcBTilde = new mat(BTilde[indexRegionAtThisLevel][jLevel],nKnots,nPredictionsInCurrentRegion,false,true);\n        dtrtrs_(&L,&N,&N,&nKnots,&nPredictionsInCurrentRegion,RChol[ancestorArray[rankOpenMP][jLevel]].memptr(),&nKnots,KcBTilde->memptr(),&nKnots,&status);\n\n        //posteriorPredictionMean[indexRegionAtThisLevel] += KcBTilde.t()*KCholTimesCurrentw[ancestorArray[rankOpenMP][jLevel]]\n        cblas_dgemv(CblasColMajor,CblasTrans,nKnots,nPredictionsInCurrentRegion,1.0,KcBTilde->memptr(),nKnots,KCholTimesCurrentw[ancestorArray[rankOpenMP][jLevel]].memptr(),1,1.0,posteriorPredictionMean[indexRegionAtThisLevel].memptr(),1);\n        \n        //posteriorPredictionVariance[indexRegionAtThisLevel] += columnSum(KcBTilde.^2);\n        posteriorPredictionVariance[indexRegionAtThisLevel] += sum(square(*KcBTilde),0).t();\n        \n        delete KcBTilde;\n        for(int jLevel = 0 ; jLevel < currentLevel-1; jLevel++)\n        {\n            delete[] BTilde[indexRegionAtThisLevel][jLevel];\n            delete tmpBTilde[jLevel];\n        }\n        delete[] BTilde[indexRegionAtThisLevel][currentLevel-1];\n        delete[] tmpBTilde;\n    }\n\n    //Free memory for temporary variables\n    for(int i = 0; i < maxOpenMPThreads; i++) delete[] ancestorArray[i];\n    delete[] ancestorArray;\n\n    if(WORKER == 0)\n    {\n        gettimeofday(&timeNow, NULL);\n        cout<<\"===========================> Processor 1: predicting is complete. Elapsed time: \"<<(double)timeNow.tv_sec-(double)timeBegin.tv_sec+((double)timeNow.tv_usec-(double)timeBegin.tv_usec)/1000000.0<<\" seconds.\\n\\n\";\n    }\n}\n", "meta": {"hexsha": "8bc2300a8aedd2575c6f6214dbcf86f986da677a", "size": 10864, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "parallel_MRA/src/class_approximation-predict.cpp", "max_stars_repo_name": "hhuang90/MRA", "max_stars_repo_head_hexsha": "438ef95ea30b68bb3750814faa5b3e5e6a78c64b", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "parallel_MRA/src/class_approximation-predict.cpp", "max_issues_repo_name": "hhuang90/MRA", "max_issues_repo_head_hexsha": "438ef95ea30b68bb3750814faa5b3e5e6a78c64b", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-19T00:41:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-03T14:50:55.000Z", "max_forks_repo_path": "parallel_MRA/src/class_approximation-predict.cpp", "max_forks_repo_name": "hhuang90/MRA", "max_forks_repo_head_hexsha": "438ef95ea30b68bb3750814faa5b3e5e6a78c64b", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-02T00:40:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-02T00:40:21.000Z", "avg_line_length": 56.0, "max_line_length": 291, "alphanum_fraction": 0.6713917526, "num_tokens": 3045, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.3629692055196168, "lm_q1q2_score": 0.20125570949525076}}
{"text": "#include \"NICS-module.h\"\n#include <vector>\n#include <string>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n#include <math.h>\n#include <Eigen/Dense>\n\n//-------------------------------------------------------------\n// Program to find the centers of rings fo NICS(0) and NICS(1) \n// calculation and write some quazi-.gjf file\n//-------------------------------------------------------------\n\nint main() {\n\n   //---------------------------------------------\n   // Get the information out of the input file:\n   //--------------------------------------------- \n\n   // Variables to get out of input file:\n   int nmols;\n   std::vector<int> nrings_per_molecule;\n   std::vector<std::string> filenames;\n   std::vector<std::vector<int>> rings_atoms; // atoms making up rings\n   \n   // Read input file:\n   read_input_file(nmols, filenames, nrings_per_molecule, rings_atoms);\n   std::cout << \"nmols: \" << nmols << std::endl;\n   print_vector_string(filenames);\n   std::cout << \"nrings_per_molecule: \" ;\n   print_vector_int(nrings_per_molecule);\n   print_matrix_int(rings_atoms);\n\n   //--------------------------------------------------------\n   // Get the coordinates of the molecules and rings from \n   // the .xyz files, move and reorient them, and print the \n   // final coordinates:\n   //--------------------------------------------------------\n\n   // Variables:\n   std::string in_xyz_file_name, out_ring_xyz_file_name, out_xyz_file_name;\n   std::string line, temp;\n   std::vector<std::string> lables_ring, lables;\n   std::vector<double> mass, xring, yring, zring,  x, y, z;\n   double temp_double;\n   double xsum, ysum, zsum, xcenter, ycenter, zcenter;\n   int i, j, k, kk, line_num, ring_num;\n   Eigen::Vector3d vec1, vec2, normal1, normal2;\n   Eigen::Matrix3d inert;\n   Eigen::MatrixXd ring_coordinates(1,1), coordinates(1,1);\n\n   ring_num = 0;\n   for (i=0; i<nmols; i=i+1) { // for each of the molecules:\n      for (j=0; j<nrings_per_molecule[i]; j=j+1) { // for each ring in mol\n         \n         // Reset lables and coordinates arrays:\n         mass.resize(0);\n         lables.resize(0);\n         x.resize(0);\n         y.resize(0);\n         z.resize(0);\n         lables_ring.resize(0);\n         xring.resize(0);\n         yring.resize(0);\n         zring.resize(0);\n\n         // Open the input file for that molecule and ring:\n         in_xyz_file_name = filenames[i] + \".xyz\";\n         std::ifstream in_xyz_file;\n         in_xyz_file.open(in_xyz_file_name);\n\n         // get the coordinates of the rings and the molecule:\n         line_num = 1;\n         while (!in_xyz_file.eof()) {\n            getline(in_xyz_file,line);\n            if (line_num > 2) {\n               std::stringstream ssin(line);\n               std::vector<std::string> split_line;\n               split_line.resize(0);\n               while (ssin.good()){\n                  ssin >> temp;\n                  split_line.push_back(temp);\n               }\n               // uncomment if segmentation fault stod\n               //std::cout << print_vector_string(split_line) << std::endl;\n               if (split_line.size() > 1) {\n                  // get lables and coordinates for whole molecule\n                  lables.push_back(split_line[0]);\n                  temp_double = std::stod(split_line[1]);\n                  x.push_back(temp_double);\n                  temp_double = std::stod(split_line[2]);\n                  y.push_back(temp_double);\n                  temp_double = std::stod(split_line[3]);\n                  z.push_back(temp_double);\n                  for (k=0; k<rings_atoms[ring_num].size(); k=k+1){\n                     if (line_num == rings_atoms[ring_num][k] + 2) {\n                        // get lables and coordinates for ring:\n                        lables_ring.push_back(split_line[0]);\n                        temp_double = std::stod(split_line[1]);\n                        xring.push_back(temp_double);\n                        temp_double = std::stod(split_line[2]);\n                        yring.push_back(temp_double);\n                        temp_double = std::stod(split_line[3]);\n                        zring.push_back(temp_double);\n                        continue;\n                     }\n                  }\n               }\n            }\n            line_num = line_num + 1;\n         }\n\n         // Find center of ring:\n         xsum = 0.0;\n         ysum = 0.0;\n         zsum = 0.0;\n         for (k=0; k<xring.size(); k=k+1) {\n            xsum = xsum + xring[k];\n            ysum = ysum + yring[k];\n            zsum = zsum + zring[k];\n         }\n         xcenter = xsum/xring.size();\n         ycenter = ysum/yring.size();\n         zcenter = zsum/zring.size();\n\n         // Move the coordinates vectors for the ring\n         // so that the center of the ring is positioned\n         // at (0,0,0):\n         for (k=0; k<xring.size(); k=k+1) {\n            xring[k] = xring[k] - xcenter;\n            yring[k] = yring[k] - ycenter;\n            zring[k] = zring[k] - zcenter;\n         }\n\n         // Move the coordinates vectors for the \n         // entire molecule so that the center of the \n         // ring is positioned at (0,0,0):\n         for (k=0; k<x.size(); k=k+1) {\n            x[k] = x[k] - xcenter;\n            y[k] = y[k] - ycenter;\n            z[k] = z[k] - zcenter;\n         }\n\n         // find plane passing through all the points of\n         // the ring using the equation \n         // C=(XY.transpose*XY).inverse*XY.transpose*Z\n         Eigen::Vector3d Cvec;\n         Eigen::VectorXd Zvec;\n         Eigen::MatrixXd XYmat;\n\n         Zvec.resize(zring.size());\n         XYmat.resize(xring.size(),3);\n         for (k=0; k<xring.size(); k=k+1) {\n            XYmat(k,0) = 1;\n            XYmat(k,1) = xring[k];\n            XYmat(k,2) = yring[k];\n            Zvec(k) = zring[k];\n         }\n\n         Cvec = (XYmat.transpose()*XYmat).inverse()*XYmat.transpose()*Zvec;\n\n         // Define two vectors in this plane:\n         vec1(0) = 0.8;\n         vec1(1) = 1.5;\n         vec1(2) = Cvec(0) + Cvec(1)*vec1(0) + Cvec(2)*vec1(1);\n         vec2(0) = -1.2;\n         vec2(1) = 0.6;\n         vec2(2) = Cvec(0) + Cvec(1)*vec2(0) + Cvec(2)*vec2(1);\n\n\n         // find a normal to this plane at (0,0,0)\n         normal1 = vec1.cross(vec2);\n         std::cout << \"normal:\" << std::endl;\n         std::cout << normal1 << std::endl;\n\n         double norm_of_normal;\n         norm_of_normal = (sqrt(normal1(0)*normal1(0) +\n                  normal1(1)*normal1(1) + normal1(2)*normal1(2)));\n         std::cout << \"norm of normal: \" << normal1.norm() << std::endl;\n\n         // normalize normal 1 to length 1:\n         for (k=0; k<normal1.size(); k=k+1) {\n            normal1(k) = normal1(k) / norm_of_normal;\n         }\n\n         norm_of_normal = (sqrt(normal1(0)*normal1(0) +\n                  normal1(1)*normal1(1) + normal1(2)*normal1(2)));\n         std::cout << \"norm of normal: \" << norm_of_normal << std::endl;\n     \n         // convert vectors xring, yring, and zring to a\n         // ring_coordinates matrix:\n         ring_coordinates.resize(xring.size(),3);\n         for(k=0; k<xring.size(); k=k+1) {\n            ring_coordinates(k,0) = xring[k];\n            ring_coordinates(k,1) = yring[k];\n            ring_coordinates(k,2) = zring[k];\n         }\n \n         // Convert vector x, y, and z to a coordinates matrix\n         // and add dummy atoms:\n         coordinates.resize(x.size() + 3,3);\n         for (k=0; k<x.size(); k=k+1) {\n            coordinates(k,0) = x[k];\n            coordinates(k,1) = y[k];\n            coordinates(k,2) = z[k];\n         }\n         coordinates(x.size(),0) = normal1(0);\n         coordinates(x.size(),1) = normal1(1);\n         coordinates(x.size(),2) = normal1(2);\n         coordinates(x.size()+1,0) = 0.0;\n         coordinates(x.size()+1,1) = 0.0;\n         coordinates(x.size()+1,2) = 0.0;\n         coordinates(x.size()+2,0) = -normal1(0);\n         coordinates(x.size()+2,1) = -normal1(1);\n         coordinates(x.size()+2,2) = -normal1(2);\n\n      \n         // Print final coordinates for the ring\n         out_ring_xyz_file_name = filenames[i] + \"_ring_\"\n            + std::to_string(j) + \".xyz\";\n         if_file_exist_delete(out_ring_xyz_file_name);\n         std::ofstream out_ring_xyz_file;\n         out_ring_xyz_file.open(out_ring_xyz_file_name);\n\n         out_ring_xyz_file << rings_atoms[ring_num].size() + 3 << std::endl;\n         out_ring_xyz_file << \"sldgjksjg\" << std::endl;\n         for (kk=0; kk<rings_atoms[ring_num].size(); kk=kk+1) {\n            out_ring_xyz_file << lables_ring[kk] << \"         \"\n                         << ring_coordinates(kk,0) << \"         \"\n                         << ring_coordinates(kk,1) << \"         \"\n                         << ring_coordinates(kk,2) << std::endl;\n         }\n         out_ring_xyz_file << \"N          \" << normal1(0) << \"         \"\n                           << normal1(1) << \"         \" << normal1(2)\n                           << std::endl;\n         out_ring_xyz_file << \"O          \" << vec1(0) << \"         \"\n                           << vec1(1) << \"         \" << vec1(2)\n                           << std::endl;\n         out_ring_xyz_file << \"O          \" << vec2(0) << \"         \"\n                           << vec2(1) << \"         \" << vec2(2)\n                           << std::endl;\n         \n         // Align normal2 to z-axis, so that\n         // the ring is in the xy plane\"\n         align(normal1, coordinates);\n         align(normal1, ring_coordinates);\n\n         // Print final coordinates for the molecule,\n         // adding the dummy atoms:\n         out_xyz_file_name = filenames[i] + \"_\" + \n                                  std::to_string(j) + \".xyz\";\n         if_file_exist_delete(out_xyz_file_name);\n         std::ofstream out_xyz_file;\n         out_xyz_file.open(out_xyz_file_name);\n\n         // printing:\n         out_xyz_file << x.size() + 3 << std::endl;\n         out_xyz_file << \"0 1\" << std::endl;\n         for (kk=0; kk<x.size(); kk=kk+1) {\n            out_xyz_file << std::left << std::setw(2) << lables[kk] \n                         << std::setw(18) << std::right\n                         << std::fixed << std::setprecision(7)\n                         << coordinates(kk,0) \n                         << std::setw(19) << std::right\n                         << std::fixed << std::setprecision(7)\n                         << coordinates(kk,1) \n                         << std::setw(19) << std::right\n                         << std::fixed << std::setprecision(7)\n                         << coordinates(kk,2) << std::endl;\n         }\n         for (kk=x.size(); kk<x.size()+3; kk=kk+1) {\n         out_xyz_file << std::left << std::setw(2) << \"Bq\"\n                      << std::setw(18) << std::right\n                      << std::fixed << std::setprecision(7)\n                      << coordinates(kk,0) \n                      << std::setw(19) << std::right\n                      << std::fixed << std::setprecision(7)\n                      << coordinates(kk,1)\n                      << std::setw(19) << std::right\n                      << std::fixed << std::setprecision(7)\n                      << coordinates(kk,2) << std::endl;\n         }\n\n         // End of loop, reset for next ring:\n         ring_num = ring_num + 1;\n         in_xyz_file.close();\n         out_ring_xyz_file.close();\n         out_xyz_file.close();\n      }\n\n   }\n\n   return 0;\n}\n", "meta": {"hexsha": "c32cd5a59b9a9dfb5d814a4628f84d0b17a18660", "size": 11396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "using_regression_plane/NICS-main.cpp", "max_stars_repo_name": "ElenaKusevska/NICS_prepare_input", "max_stars_repo_head_hexsha": "097845b1cf036609ae642053baf3bc950b3fdfb3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "using_regression_plane/NICS-main.cpp", "max_issues_repo_name": "ElenaKusevska/NICS_prepare_input", "max_issues_repo_head_hexsha": "097845b1cf036609ae642053baf3bc950b3fdfb3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "using_regression_plane/NICS-main.cpp", "max_forks_repo_name": "ElenaKusevska/NICS_prepare_input", "max_forks_repo_head_hexsha": "097845b1cf036609ae642053baf3bc950b3fdfb3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.3703703704, "max_line_length": 76, "alphanum_fraction": 0.475956476, "num_tokens": 2898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.3629691917376783, "lm_q1q2_score": 0.20125569650910097}}
{"text": "// __BEGIN_LICENSE__\n//  Copyright (c) 2009-2013, United States Government as represented by the\n//  Administrator of the National Aeronautics and Space Administration. All\n//  rights reserved.\n//\n//  The NGT platform is licensed under the Apache License, Version 2.0 (the\n//  \"License\"); you may not use this file except in compliance with the\n//  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// Create a pinhole or optical bar camera model based on intrinsics, image corner\n// coordinates, and, optionally, a DEM of the area.\n\n#include <vw/FileIO/DiskImageView.h>\n#include <vw/Core/StringUtils.h>\n#include <vw/Camera/PinholeModel.h>\n#include <vw/Camera/CameraUtilities.h>\n#include <vw/Cartography/Datum.h>\n#include <vw/Cartography/GeoReference.h>\n#include <vw/Cartography/CameraBBox.h>\n#include <vw/Math/LevenbergMarquardt.h>\n#include <vw/Math/Geometry.h>\n#include <asp/Core/Common.h>\n#include <asp/Core/Macros.h>\n#include <asp/Core/FileUtils.h>\n#include <asp/Core/PointUtils.h>\n#include <asp/Core/EigenUtils.h>\n#include <vw/Camera/OpticalBarModel.h>\n#include <asp/Sessions/StereoSession.h>\n#include <asp/Sessions/StereoSessionFactory.h>\n\n#include <limits>\n#include <cstring>\n\n#include <boost/filesystem.hpp>\n#include <boost/algorithm/string.hpp>\n#include <boost/program_options.hpp>\n\nnamespace fs = boost::filesystem;\nnamespace po = boost::program_options;\n\nusing namespace vw;\nusing namespace vw::camera;\nusing namespace vw::cartography;\n\n// Solve for best fitting camera that projects given xyz locations at\n// given pixels. If cam_weight > 0, try to constrain the camera height\n// above datum at the value of cam_height.\n// TODO: The logic with the camera height did not work. Wipe it.\n// Use the original functions in VW and move some of the newer\n// code from here to there.\ntemplate <class CAM>\nclass CameraSolveLMA_Ht: public vw::math::LeastSquaresModelBase<CameraSolveLMA_Ht<CAM> > {\n  std::vector<vw::Vector3> const& m_xyz;\n  CAM m_camera_model;\n  double m_cam_height, m_cam_weight;\n  vw::cartography::Datum m_datum;\n  mutable size_t m_iter_count;\n  \npublic:\n\n  typedef vw::Vector<double>    result_type;   // pixel residuals\n  typedef vw::Vector<double, 6> domain_type;   // camera parameters (camera center and axis angle)\n  typedef vw::Matrix<double> jacobian_type;\n\n  /// Instantiate the solver with a set of xyz to pixel pairs and a pinhole model\n  CameraSolveLMA_Ht(std::vector<vw::Vector3> const& xyz,\n\t\t  CAM const& camera_model,\n\t\t  double cam_height, double cam_weight,\n\t\t  vw::cartography::Datum const& datum):\n    m_xyz(xyz),\n    m_camera_model(camera_model), m_iter_count(0),\n    m_cam_height(cam_height), m_cam_weight(cam_weight),\n    m_datum(datum) {}\n\n  /// Given the camera, project xyz into it\n  inline result_type operator()( domain_type const& C ) const {\n\n    // Create the camera model\n    CAM camera_model = m_camera_model;  // make a copy local to this function\n    vector_to_camera(camera_model, C);  // update its parameters\n\n    int xyz_len = m_xyz.size();\n    size_t result_size = xyz_len * 2;\n    if (m_cam_weight > 0) {\n      result_size += 1;\n    }\n\n    // See where the xyz coordinates project into the camera.\n    result_type result;\n    result.set_size(result_size);\n    for (size_t i = 0; i < xyz_len; i++) {\n      Vector2 pixel = camera_model.point_to_pixel(m_xyz[i]);\n      result[2*i  ] = pixel[0];\n      result[2*i+1] = pixel[1];\n    }\n\n    // Try to make the camera stay at given height\n    if (m_cam_weight > 0) {\n      Vector3 cam_ctr = subvector(C, 0, 3);\n      Vector3 llh = m_datum.cartesian_to_geodetic(cam_ctr);\n      result[2*xyz_len] = m_cam_weight*(llh[2] - m_cam_height);\n    }\n    \n    ++m_iter_count;\n    \n    return result;\n  }\n}; // End class CameraSolveLMA_Ht\n\n/// Find the best camera that fits the current GCP\nvoid fit_camera_to_xyz_ht(bool parse_ecef,\n\t\t\t  Vector3 const& parsed_camera_center,\n\t\t\t  std::string const& camera_type,\n\t\t\t  bool refine_camera, \n\t\t\t  std::vector<Vector3> const& xyz_vec,\n\t\t\t  std::vector<double> const& pixel_values,\n\t\t\t  double cam_height, double cam_weight,\n\t\t\t  vw::cartography::Datum const& datum,\n\t\t\t  bool verbose,\n\t\t\t  boost::shared_ptr<CameraModel> & out_cam){\n  \n  // Create fake points in space at given distance from this camera's\n  // center and corresponding actual points on the ground.  Use 500\n  // km, just some height not too far from actual satellite height.\n  const double ht = 500000; \n  int num_pts = pixel_values.size()/2;\n  vw::Matrix<double> in, out;\n  in.set_size(3, num_pts);\n  out.set_size(3, num_pts);\n  for (int col = 0; col < in.cols(); col++) {\n    Vector3 a = out_cam->camera_center(Vector2(0, 0)) +\n      ht*out_cam->pixel_to_vector(Vector2(pixel_values[2*col], pixel_values[2*col+1]));\n    for (int row = 0; row < in.rows(); row++) {\n      in(row, col)  = a[row];\n      out(row, col) = xyz_vec[col][row];\n    }\n  }\n  \n  // Apply a transform to the camera so that the fake points are on top of the real points\n  Matrix<double, 3, 3> rotation;\n  Vector3 translation;\n  double scale;\n  find_3D_affine_transform(in, out, rotation, translation, scale);\n  if (camera_type == \"opticalbar\")\n    ((vw::camera::OpticalBarModel*)out_cam.get())->apply_transform(rotation,\n\t\t\t\t\t\t\t\t   translation, scale);\n  else{\n    ((PinholeModel*)out_cam.get())->apply_transform(rotation, translation, scale);\n    if (parse_ecef) {\n      // Overwrite the solved camera center with what is found from the\n      // frame index file.\n      ((PinholeModel*)out_cam.get())->set_camera_center(parsed_camera_center);\n    }\n  }\n  \n  // Print out some errors\n  if (verbose) {\n    vw_out() << \"The error between the projection of each ground \"\n\t     << \"corner point into the coarse camera and its pixel value:\\n\";\n    for (size_t corner_it = 0; corner_it < num_pts; corner_it++) {\n      vw_out () << \"Corner and error: (\"\n\t\t<< pixel_values[2*corner_it] << ' ' << pixel_values[2*corner_it+1]\n\t\t<< \") \" <<  norm_2(out_cam.get()->point_to_pixel(xyz_vec[corner_it]) -\n\t\t\t\t Vector2( pixel_values[2*corner_it],\n\t\t\t\t\t  pixel_values[2*corner_it+1]))\n\t\t<< std::endl;\n    }\n  }\n  \n  // Solve a little optimization problem to make the points on the ground project\n  // as much as possible exactly into the image corners.\n  if (refine_camera) {\n    Vector<double> out_vec; // must copy to this structure\n    int residual_len = pixel_values.size();\n\n    // If we enforce the camera height, add another residual\n    if (cam_weight > 0.0) \n      residual_len += 1;\n\n    // Copy the image pixels\n    out_vec.set_size(residual_len);\n    for (size_t corner_it = 0; corner_it < pixel_values.size(); corner_it++) \n      out_vec[corner_it] = pixel_values[corner_it];\n\n    if (cam_weight > 0.0) \n      out_vec[residual_len - 1] = 0.0;\n        \n    const double abs_tolerance  = 1e-24;\n    const double rel_tolerance  = 1e-24;\n    const int    max_iterations = 2000;\n    int status = 0;\n    Vector<double> final_params;\n    Vector<double> seed;\n      \n    if (camera_type == \"opticalbar\") {\n      CameraSolveLMA_Ht<vw::camera::OpticalBarModel>\n\tlma_model(xyz_vec, *((vw::camera::OpticalBarModel*)out_cam.get()),\n\t\t  cam_height, cam_weight, datum);\n      camera_to_vector(*((vw::camera::OpticalBarModel*)out_cam.get()), seed);\n      final_params = math::levenberg_marquardt(lma_model, seed, out_vec,\n\t\t\t\t\t       status, abs_tolerance, rel_tolerance,\n\t\t\t\t\t       max_iterations);\n      vector_to_camera(*((vw::camera::OpticalBarModel*)out_cam.get()), final_params);\n    } else {\n      CameraSolveLMA_Ht<PinholeModel> lma_model(xyz_vec, *((PinholeModel*)out_cam.get()),\n\t\t  cam_height, cam_weight, datum);\n      camera_to_vector(*((PinholeModel*)out_cam.get()), seed);\n      final_params = math::levenberg_marquardt(lma_model, seed, out_vec,\n\t\t\t\t\t       status, abs_tolerance, rel_tolerance,\n\t\t\t\t\t       max_iterations);\n      vector_to_camera(*((PinholeModel*)out_cam.get()), final_params);\n    }\n    if (status < 1)\n      vw_out() << \"The Levenberg-Marquardt solver failed. Results may be inaccurate.\\n\";\n\n    if (verbose) {\n      vw_out() << \"The error between the projection of each ground \"\n\t       << \"corner point into the refined camera and its pixel value:\\n\";\n      for (size_t corner_it = 0; corner_it < num_pts; corner_it++) {\n\tvw_out () << \"Corner and error: (\"\n\t\t  << pixel_values[2*corner_it] << ' ' << pixel_values[2*corner_it+1]\n\t\t  << \") \" <<  norm_2(out_cam.get()->point_to_pixel(xyz_vec[corner_it]) -\n\t\t\t\t     Vector2( pixel_values[2*corner_it],\n\t\t\t\t\t      pixel_values[2*corner_it+1]))\n\t\t  << std::endl;\n      }\n    }\n    \n  } // End camera refinement case\n}\n\n// Parse numbers or strings from a list where they are separated by commas or spaces.\ntemplate<class T>\nvoid parse_values(std::string list, std::vector<T> & values){\n\n  values.clear();\n\n  // Replace commas with spaces\n  std::string oldStr = \",\", newStr = \" \";\n  size_t pos = 0;\n  while((pos = list.find(oldStr, pos)) != std::string::npos){\n    list.replace(pos, oldStr.length(), newStr);\n    pos += newStr.length();\n  }\n\n  // Read the values one by one\n  std::istringstream is(list);\n  T val;\n  while (is >> val)\n    values.push_back(val);\n}\n\nstruct Options : public vw::cartography::GdalWriteOptions {\n  std::string image_file, camera_file, lon_lat_values_str, pixel_values_str, datum_str,\n    reference_dem, frame_index, gcp_file, camera_type, sample_file, input_camera,\n    stereo_session, bundle_adjust_prefix, parsed_cam_ctr_str, parsed_cam_quat_str;\n  double focal_length, pixel_pitch, gcp_std, height_above_datum,\n    cam_height, cam_weight;\n  Vector2 optical_center;\n  std::vector<double> lon_lat_values, pixel_values;\n  bool refine_camera, parse_eci, parse_ecef; \n  Options(): focal_length(-1), pixel_pitch(-1), gcp_std(1), height_above_datum(0), refine_camera(false), cam_height(0), cam_weight(0) {}\n};\n\nvoid handle_arguments(int argc, char *argv[], Options& opt) {\n  po::options_description general_options(\"\");\n  general_options.add_options()\n    (\"output-camera-file,o\", po::value(&opt.camera_file), \"Specify the output camera file with a .tsai extension.\")\n    (\"camera-type\", po::value(&opt.camera_type)->default_value(\"pinhole\"), \"Specify the camera type. Options are: pinhole (default) and opticalbar.\")\n    (\"lon-lat-values\", po::value(&opt.lon_lat_values_str)->default_value(\"\"), \"A (quoted) string listing numbers, separated by commas or spaces, having the longitude and latitude (alternating and in this order) of each image corner. The corners are traversed in the order 0,0 w,0, w,h, 0,h where w and h are the image width and height.\")\n    (\"pixel-values\", po::value(&opt.pixel_values_str)->default_value(\"\"), \"A (quoted) string listing numbers, separated by commas or spaces, having the column and row (alternating and in this order) of each pixel in the raw image at which the longitude and latitude is known. By default this is empty, and will be populated by the image corners traversed as earlier.\")\n    (\"reference-dem\", po::value(&opt.reference_dem)->default_value(\"\"),\n     \"Use this DEM to infer the heights above datum of the image corners.\")\n    (\"datum\", po::value(&opt.datum_str)->default_value(\"\"),\n     \"Use this datum to interpret the longitude and latitude, unless a DEM is given. Options: WGS_1984, D_MOON (1,737,400 meters), D_MARS (3,396,190 meters), MOLA (3,396,000 meters), NAD83, WGS72, and NAD27. Also accepted: Earth (=WGS_1984), Mars (=D_MARS), Moon (=D_MOON).\")\n    (\"height-above-datum\", po::value(&opt.height_above_datum)->default_value(0),\n     \"Assume this height above datum in meters for the image corners unless read from the DEM.\")\n    (\"sample-file\", po::value(&opt.sample_file)->default_value(\"\"), \n     \"Read in the camera parameters from the example camera file.  Required for opticalbar type.\")\n    (\"focal-length\", po::value(&opt.focal_length)->default_value(0),\n     \"The camera focal length.\")\n    (\"optical-center\", po::value(&opt.optical_center)->default_value(Vector2i(0,0),\"0 0\"),\n     \"The camera optical center.\")\n    (\"pixel-pitch\", po::value(&opt.pixel_pitch)->default_value(0),\n     \"The pixel pitch.\")\n    (\"refine-camera\", po::bool_switch(&opt.refine_camera)->default_value(false),\n     \"After a rough initial camera is obtained, refine it using least squares.\")\n    (\"frame-index\", po::value(&opt.frame_index)->default_value(\"\"),\n     \"A file used to look up the longitude and latitude of image corners based on the image name, in the format provided by the SkySat video product.\")\n    (\"gcp-file\", po::value(&opt.gcp_file)->default_value(\"\"),\n     \"If provided, save the image corner coordinates and heights in the GCP format to this file.\")\n    (\"gcp-std\", po::value(&opt.gcp_std)->default_value(1),\n     \"The standard deviation for each GCP pixel, if saving a GCP file. A smaller value suggests a more reliable measurement, hence will be given more weight.\")\n    (\"cam-height\", po::value(&opt.cam_height)->default_value(0),\n     \"If both this and --cam-weight are positive, enforce that the output camera is at this height above datum. For SkySat, if not set, read this from the frame index. Highly experimental.\")\n    (\"cam-weight\", po::value(&opt.cam_weight)->default_value(0),\n     \"If positive, try to enforce the option --cam-height with this weight (bigger weight means try harder to enforce). Highly experimental.\")\n    (\"parse-eci\", po::bool_switch(&opt.parse_eci)->default_value(false),\n     \"Create cameras based on ECI positions and orientations (not working).\")\n    (\"parse-ecef\", po::bool_switch(&opt.parse_ecef)->default_value(false),\n     \"Create cameras based on ECEF position (but not orientation).\")\n    (\"input-camera\", po::value(&opt.input_camera)->default_value(\"\"),\n     \"Create the output pinhole camera approximating this camera.\")\n    (\"session-type,t\",   po::value(&opt.stereo_session)->default_value(\"\"),\n     \" Select the input camera model type. Normally this is auto-detected, but may need to be specified if the input camera model is in XML format. See the doc for options.\")\n    (\"bundle-adjust-prefix\", po::value(&opt.bundle_adjust_prefix),\n     \"Use the camera adjustment obtained by previously running bundle_adjust when providing an input camera.\");\n  \n  general_options.add( vw::cartography::GdalWriteOptionsDescription(opt) );\n\n  po::options_description positional(\"\");\n  positional.add_options()\n    (\"image-file\", po::value(&opt.image_file));\n\n  po::positional_options_description positional_desc;\n  positional_desc.add(\"image-file\",1);\n\n  std::string usage(\"[options] <image-file> -o <camera-file>\");\n  bool allow_unregistered = false;\n  std::vector<std::string> unregistered;\n  po::variables_map vm =\n    asp::check_command_line(argc, argv, opt, general_options, general_options,\n                            positional, positional_desc, usage,\n                            allow_unregistered, unregistered);\n\n  if ( opt.image_file.empty() )\n    vw_throw( ArgumentErr() << \"Missing the input image.\\n\"\n              << usage << general_options );\n\n  if ( opt.camera_file.empty() )\n    vw_throw( ArgumentErr() << \"Missing the output camera file name.\\n\"\n              << usage << general_options );\n\n  boost::to_lower(opt.camera_type);\n  \n  if (opt.camera_type != \"pinhole\" && opt.camera_type != \"opticalbar\")\n    vw_throw( ArgumentErr() << \"Only pinhole and opticalbar cameras are supported.\\n\");\n  \n  if ((opt.camera_type == \"opticalbar\") && (opt.sample_file == \"\"))\n    vw_throw( ArgumentErr() << \"opticalbar type must use a sample camera file.\\n\"\n              << usage << general_options );\n\n  std::string ext = get_extension(opt.camera_file);\n  if (ext != \".tsai\") \n    vw_throw( ArgumentErr() << \"The output camera file must end with .tsai.\\n\"\n              << usage << general_options );\n\n  // If we cannot read the data from a DEM, must specify a lot of things.\n  if (opt.reference_dem.empty() && opt.datum_str.empty())\n    vw_throw( ArgumentErr() << \"Must provide either a reference DEM or a datum.\\n\"\n              << usage << general_options );\n\n  if (opt.gcp_std <= 0) \n    vw_throw( ArgumentErr() << \"The GCP standard deviation must be positive.\\n\"\n              << usage << general_options );\n\n  if (opt.frame_index != \"\" && opt.lon_lat_values_str != \"\") \n    vw_throw( ArgumentErr() << \"Cannot specify both the frame index file \"\n\t      << \"and the lon-lat corners.\\n\"\n              << usage << general_options );\n\n  if (opt.frame_index != \"\") {\n    // Parse the frame index to extract opt.lon_lat_values_str.\n    // Look for a line having this image, and search for \"POLYGON\" followed by spaces and \"((\".\n    boost::filesystem::path p(opt.image_file); \n    std::string image_base = p.stem().string(); // strip the directory name and suffix\n    std::ifstream file( opt.frame_index.c_str() );\n    std::string line;\n    std::string beg1 = \"POLYGON\";\n    std::string beg2 = \"((\";\n    std::string end = \"))\";\n    while ( getline(file, line, '\\n') ) {\n      if (line.find(image_base) == 0) {\n        // Find POLYGON first.\n        int beg_pos = line.find(beg1);\n        if (beg_pos == std::string::npos)\n          vw_throw( ArgumentErr() << \"Cannot find \" << beg1 << \" in line: \" << line << \".\\n\");\n        beg_pos += beg1.size();\n\n        // Move forward skipping any spaces until finding \"((\"\n        beg_pos = line.find(beg2, beg_pos);\n        if (beg_pos == std::string::npos)\n          vw_throw( ArgumentErr() << \"Cannot find \" << beg2 << \" in line: \" << line << \".\\n\");\n        beg_pos += beg2.size();\n\n        // Find \"))\"\n        int end_pos = line.find(end, beg_pos);\n        if (end_pos == std::string::npos)\n          vw_throw( ArgumentErr() << \"Cannot find \" << end << \" in line: \" << line << \".\\n\");\n        opt.lon_lat_values_str = line.substr(beg_pos, end_pos - beg_pos);\n        vw_out() << \"Parsed the lon-lat corner values: \" << opt.lon_lat_values_str\n\t\t << std::endl;\n\n\tif (opt.parse_eci && opt.parse_ecef)\n\t  vw_throw( ArgumentErr() << \"Cannot parse both ECI end ECEF at the same time.\\n\");\n\t\n\t// Also parse the camera height constraint, unless manually specified\n\tif (opt.cam_weight > 0 || opt.parse_eci || opt.parse_ecef) {\n\t  std::vector<std::string> vals;\n\t  parse_values<std::string>(line, vals);\n\t  \n\t  if (vals.size() < 12) \n\t    vw_throw( ArgumentErr() << \"Could not parse 12 values from: \" << line << \".\\n\");\n\n\t  // Extract the ECI or ECEF coordinates of camera\n\t  // center. Keep them as string until we can convert to\n\t  // height above datum.\n\t  \n\t  if (opt.parse_eci) {\n\t    std::string x = vals[5];\n\t    std::string y = vals[6];\n\t    std::string z = vals[7];\n\t    opt.parsed_cam_ctr_str = x + \" \" + y + \" \" + z;\n\t    vw_out() << \"Parsed the ECI camera center in km: \"\n\t\t     << opt.parsed_cam_ctr_str <<\".\\n\";\n\t    \n\t    std::string q0 = vals[8];\n\t    std::string q1 = vals[9];\n\t    std::string q2 = vals[10];\n\t    std::string q3 = vals[11];\n\t    opt.parsed_cam_quat_str = q0 + \" \" + q1 + \" \" + q2 + \" \" + q3;\n\t    vw_out() << \"Parsed the ECI quaternion: \"\n\t\t     << opt.parsed_cam_quat_str <<\".\\n\";\n\t  }\n\t  \n\t  if (opt.parse_ecef) {\n\t    if (vals.size() < 19) \n\t      vw_throw( ArgumentErr() << \"Could not parse 19 values from: \" << line << \".\\n\");\n\t    \n\t    std::string x = vals[12];\n\t    std::string y = vals[13];\n\t    std::string z = vals[14];\n\t    opt.parsed_cam_ctr_str = x + \" \" + y + \" \" + z;\n\t    vw_out() << \"Parsed the ECEF camera center in km: \"\n\t\t     << opt.parsed_cam_ctr_str <<\".\\n\";\n\t    \n\t    std::string q0 = vals[15];\n\t    std::string q1 = vals[16];\n\t    std::string q2 = vals[17];\n\t    std::string q3 = vals[18];\n\t    opt.parsed_cam_quat_str = q0 + \" \" + q1 + \" \" + q2 + \" \" + q3;\n\t    vw_out() << \"Parsed the ECEF quaternion: \"\n\t\t     << opt.parsed_cam_quat_str <<\".\\n\";\n\t  }\n\t  \n\t}\n\t\n        break;\n      }\n    }\n    if (opt.lon_lat_values_str == \"\")\n      vw_throw( ArgumentErr() << \"Could not parse the entry for \" << image_base\n                << \" in file: \" << opt.frame_index << \".\\n\");\n  }\n    \n  // Parse the pixel values\n  parse_values<double>(opt.pixel_values_str, opt.pixel_values);\n\n  // If none were provided, use the image corners\n  if (opt.pixel_values.empty()) {\n    DiskImageView<float> img(opt.image_file);\n    int wid = img.cols(), hgt = img.rows();\n    if (wid <= 0 || hgt <= 0) \n      vw_throw( ArgumentErr() << \"Could not read an image with positive dimensions from: \"\n\t\t<< opt.image_file << \".\\n\");\n    \n    // populate the corners\n    double arr[] = {0.0, 0.0, (double)wid, 0.0, (double)wid, (double)hgt, 0.0, (double)hgt};\n    for (size_t it  = 0; it < sizeof(arr)/sizeof(double); it++) \n      opt.pixel_values.push_back(arr[it]);\n\n    // Add inner points for robustness\n    if (opt.input_camera != \"\") {\n      double b = 0.25, e = 0.75;\n      double arr[] = {b*wid, b*hgt, e*wid, b*hgt, e*wid, e*hgt, b*wid, e*hgt};\n      for (size_t it  = 0; it < sizeof(arr)/sizeof(double); it++) \n\topt.pixel_values.push_back(arr[it]);\n    }\n    \n  }\n    \n  // Parse the lon-lat values\n  if (opt.input_camera == \"\") {\n    parse_values<double>(opt.lon_lat_values_str, opt.lon_lat_values);\n    // Bug fix for some frame_index files repeating the first point at the end\n    int len = opt.lon_lat_values.size();\n    if (opt.frame_index != \"\" && opt.lon_lat_values.size() == opt.pixel_values.size() + 2 &&\n        len >= 2 && opt.lon_lat_values[0] == opt.lon_lat_values[len - 2] &&\n        opt.lon_lat_values[1] == opt.lon_lat_values[len - 1]) {\n      opt.lon_lat_values.pop_back();\n      opt.lon_lat_values.pop_back();\n    }\n  }\n  \n  // Note that optical center can be negative (for some SkySat products).\n  if ( opt.sample_file == \"\" && (opt.focal_length <= 0 || opt.pixel_pitch <= 0))\n    vw_throw( ArgumentErr() << \"Must provide positive focal length\"\n              << \"and pixel pitch values OR a sample file.\\n\");\n  \n  // Create the output directory\n  vw::create_out_dir(opt.camera_file);\n} // End function handle_arguments\n\n// Form a camera based on info the user provided\nvoid manufacture_cam(Options const& opt, int wid, int hgt,\n\t\t     boost::shared_ptr<CameraModel> & out_cam){\n\n  if (opt.camera_type == \"opticalbar\") {\n    boost::shared_ptr<vw::camera::OpticalBarModel> opticalbar_cam;\n    opticalbar_cam.reset(new vw::camera::OpticalBarModel(opt.sample_file));\n    // Make sure the image size matches the input image file.\n    opticalbar_cam->set_image_size(Vector2i(wid, hgt));\n    opticalbar_cam->set_optical_center(Vector2(wid/2.0, hgt/2.0));\n    out_cam = opticalbar_cam;\n  } else {\n    boost::shared_ptr<PinholeModel> pinhole_cam;\n    if (opt.sample_file != \"\") {\n      // Use the initial guess from file\n      pinhole_cam.reset(new PinholeModel(opt.sample_file));\n    } else {\n      // Use the intrinsics from the command line. Use trivial rotation and translation.\n      Vector3 ctr(0, 0, 0);\n      Matrix<double, 3, 3> rotation;\n      rotation.set_identity();\n      pinhole_cam.reset(new PinholeModel(ctr, rotation, opt.focal_length, opt.focal_length,\n\t\t\t\t\t opt.optical_center[0], opt.optical_center[1],\n\t\t\t\t\t NULL, opt.pixel_pitch));\n    }\n    out_cam = pinhole_cam;\n  }\n}\n\n// TODO: Wipe this logic and use RayDEMIntersectionLMA from VW.\n// That one is also terrible code which needs to be replaced with a\n// proper root-finding algorithm\n// and use it. And this code should be moved to VW.\n// https://github.com/NeoGeographyToolkit/StereoPipeline/issues/267\nnamespace vw {\n  namespace cartography {\n\n  // Define an LMA model to solve for a DEM intersecting a ray. The\n  // variable of optimization is position on the ray. The cost\n  // function is difference between datum height and DEM height at\n  // current point on the ray.\n  template <class DEMImageT>\n  class RayDEMIntersectionLMA2 : public math::LeastSquaresModelBase< RayDEMIntersectionLMA2< DEMImageT > > {\n\n    // TODO: Why does this use EdgeExtension if Helper() restricts access to the bounds?\n    InterpolationView<EdgeExtensionView<DEMImageT, ConstantEdgeExtension>,\n                      BilinearInterpolation> m_dem;\n    GeoReference m_georef;\n    Vector3      m_camera_ctr;\n    Vector3      m_camera_vec;\n    bool         m_treat_nodata_as_zero;\n\n    /// Provide safe interaction with DEMs that are scalar\n    /// - If m_dem(x,y) is in bounds, return the interpolated value.\n    /// - Otherwise return 0 or big_val()\n    template <class PixelT>\n    typename boost::enable_if< IsScalar<PixelT>, double >::type\n    inline Helper( double x, double y ) const {\n      if ( (0 <= x) && (x <= m_dem.cols() - 1) && // for interpolation\n           (0 <= y) && (y <= m_dem.rows() - 1) ){\n        PixelT val = m_dem(x, y);\n        if (is_valid(val)) return val;\n      }\n      if (m_treat_nodata_as_zero) return 0;\n      return big_val();\n    }\n\n    /// Provide safe interaction with DEMs that are compound\n    template <class PixelT>\n    typename boost::enable_if< IsCompound<PixelT>, double>::type\n    inline Helper( double x, double y ) const {\n      if ( (0 <= x) && (x <= m_dem.cols() - 1) && // for interpolation\n           (0 <= y) && (y <= m_dem.rows() - 1) ){\n        PixelT val = m_dem(x, y);\n        if (is_valid(val)) return val[0];\n      }\n      if (m_treat_nodata_as_zero) return 0;\n      return big_val();\n    }\n\n  public:\n    typedef Vector<double, 1> result_type;\n    typedef Vector<double, 1> domain_type;\n    typedef Matrix<double>    jacobian_type; ///< Jacobian form. Auto.\n\n    /// Return a very large error to penalize locations that fall off the edge of the DEM.\n    inline double big_val() const {\n      // Don't make this too big as in the LMA algorithm it may get squared and may cause overflow.\n      return 1.0e+50;\n    }\n\n    /// Constructor\n    RayDEMIntersectionLMA2(ImageViewBase<DEMImageT> const& dem_image,\n                          GeoReference const& georef,\n                          Vector3 const& camera_ctr,\n                          Vector3 const& camera_vec,\n                          bool treat_nodata_as_zero\n                          )\n      : m_dem(interpolate(dem_image)), m_georef(georef),\n        m_camera_ctr(camera_ctr), m_camera_vec(camera_vec),\n        m_treat_nodata_as_zero(treat_nodata_as_zero){}\n\n    /// Evaluator. See description above.\n    inline result_type operator()( domain_type const& len ) const {\n      // The proposed intersection point\n      Vector3 xyz = m_camera_ctr + len[0]*m_camera_vec;\n\n      // Convert to geodetic coordinates, then to DEM pixel coordinates\n      Vector3 llh = m_georef.datum().cartesian_to_geodetic( xyz );\n      Vector2 pix = m_georef.lonlat_to_pixel( Vector2( llh.x(), llh.y() ) );\n      \n      // Return a measure of the elevation difference between the DEM and the guess\n      // at its current location.\n      result_type result;\n      result[0] = Helper<typename DEMImageT::pixel_type >(pix.x(),pix.y()) - llh[2];\n      return result;\n    }\n  };\n\n    \n  // Intersect the ray going from the given camera pixel with a DEM.\n  // The return value is a Cartesian point. If the ray goes through a\n  // hole in the DEM where there is no data, we return no-intersection\n  // or intersection with the datum, depending on whether the variable\n  // treat_nodata_as_zero is false or true.\n  template <class DEMImageT>\n  Vector3 camera_pixel_to_dem_xyz2(Vector3 const& camera_ctr, Vector3 const& camera_vec,\n                                  ImageViewBase<DEMImageT> const& dem_image,\n                                  GeoReference const& georef,\n                                  bool treat_nodata_as_zero,\n                                  bool & has_intersection,\n                                  double height_error_tol = 1e-1,  // error in DEM height\n                                  double max_abs_tol      = 1e-14, // abs cost fun change b/w iters\n                                  double max_rel_tol      = 1e-14,\n                                  int num_max_iter        = 100,\n                                  Vector3 xyz_guess       = Vector3()\n                                  ){\n\n    // This is a very fragile function and things can easily go wrong. \n    try {\n      has_intersection = false;\n      RayDEMIntersectionLMA2<DEMImageT> model(dem_image, georef, camera_ctr,\n                                             camera_vec, treat_nodata_as_zero);\n\n      Vector3 xyz;\n      if ( xyz_guess == Vector3() ){ // If no guess provided\n        // Intersect the ray with the datum, this is a good initial guess.\n        xyz = datum_intersection(georef.datum(), camera_ctr, camera_vec);\n\n        if ( xyz == Vector3() ) { // If we failed to intersect the datum, give up!\n          has_intersection = false;\n          return Vector3();\n        }\n      }else{ // User provided guess\n        xyz = xyz_guess;\n      }\n\n      // Length along the ray from camera center to datum intersection point\n      Vector<double, 1> base_len, len;\n      double smallest_error_pos = std::numeric_limits<double>::max();\n      double best_len_pos = std::numeric_limits<double>::max();\n      double smallest_error_neg = std::numeric_limits<double>::max();\n      double best_len_neg = std::numeric_limits<double>::max();\n      bool success_pos = false, success_neg = false;\n      \n      // If the ray intersects the datum at a point which does not\n      // correspond to a valid location in the DEM, wiggle that point\n      // along the ray until hopefully it does. Store the value that\n      // is closest to where that ray will intersect the DEM. Once\n      // that value is located, it is helpful to repeat this logic one\n      // more time, this time around the best guess found so far.\n      // Hence two outer passes. The value xyz is updated at each\n      // pass. The idea here is that the closer one gets to the true\n      // solution, the likelier the LM solver will converge.\n      for (int outer_pass = 0; outer_pass <= 0; outer_pass++){\n\t\n\tbase_len[0] = norm_2(xyz - camera_ctr);\n\n      \n\tconst double radius     = norm_2(xyz); // Radius from XYZ coordinate center\n\tconst int    ITER_LIMIT = 10; // There are two solver attempts per iteration\n\tconst double small      = radius*0.02/( 1 << (ITER_LIMIT-1) ); // Wiggle\n\tfor (int i = 0; i <= ITER_LIMIT; i++){\n\t  // Gradually expand delta until on final iteration it is == radius*0.02\n\t  double delta = 0;\n\t  if (i > 0)\n\t    delta = small*( 1 << (i-1) );\n\n\t  for (int k = -1; k <= 1; k += 2){ // For k==-1, k==1\n\t    len[0] = base_len[0] + k*delta; // Ray guess length +/- 2% planetary radius\n\t    // Use our model to compute the height diff at this length\n\n\t    Vector<double, 1> height_diff = model(len);\n\t  \n\t    if ( std::abs(height_diff[0]) < (model.big_val()/10.0) ){\n\t      has_intersection = true;\n\t    }else{\n\t      continue;\n\t    }\n\t    //if (i == 0) break; // When k*delta==0, no reason to do both + and -!\n\n\t    if (height_diff[0] < 0 && std::abs(height_diff[0]) < smallest_error_neg){\n\t      \n\t      smallest_error_neg = std::abs(height_diff[0]);\n\t      best_len_neg = len[0];\n\t      xyz = camera_ctr + best_len_neg*camera_vec; // broken!!!\n\t      success_neg = true;\n\t    }else{\n\t    }\n\n\t    if (height_diff[0] >=0 && std::abs(height_diff[0]) < smallest_error_pos){\n\t      \n\t      smallest_error_pos = std::abs(height_diff[0]);\n\t      best_len_pos = len[0];\n\t      success_pos = true;\n\t      xyz = camera_ctr + best_len_pos*camera_vec; // broken!!!\n\t    }else{\n\t    }\n\n\t    \n\t  } // End k loop\n\t  if (has_intersection) {\n\t    // break;\n\t  }\n\t} // End i loop\n      \n\t// Failed to compute an intersection in the hard coded iteration limit!\n\tif ( !has_intersection ) {\n\t  return Vector3();\n\t}\n      }\n\n      // Refining the intersection using Levenberg-Marquardt\n      // - This will actually use the L-M solver to play around with the len\n      //   value to minimize the height difference from the DEM.\n      int status = 0;\n      Vector<double, 1> observation;\n      observation[0] = 0;\n      Vector<double, 1> dem_height_neg;\n      dem_height_neg[0] = std::numeric_limits<double>::max();\n      Vector<double, 1> final_len_neg;\n      if (success_neg) {\n\tlen[0] = best_len_neg;\n\tfinal_len_neg = math::levenberg_marquardt(model, len, observation, status,\n                                      max_abs_tol, max_rel_tol,\n\t\t\t\t\t\t  num_max_iter);\n\tdem_height_neg = model(final_len_neg);\n\t\n\tif (status < 0) \n\t  success_neg = false;\n      }\n      \n\n      status = 0;\n      observation[0] = 0;\n      len[0] = best_len_pos;\n      Vector<double, 1> final_len_pos;\n      Vector<double, 1> dem_height_pos;\n      dem_height_pos[0] = std::numeric_limits<double>::max();\n      if (success_pos) {\n\tfinal_len_pos = math::levenberg_marquardt(model, len, observation, status,\n\t\t\t\t    max_abs_tol, max_rel_tol,\n\t\t\t\t    num_max_iter\n\t\t\t\t    );\n\tdem_height_pos = model(final_len_pos);\n\tif (status < 0) \n\t  success_pos = false;\n      }\n\n      Vector<double, 1> dem_height;\n      if (success_pos && std::abs(dem_height_pos[0]) <= std::abs(dem_height_neg[0])) {\n\tdem_height = dem_height_pos;\n\tlen = final_len_pos;\n      }else if (success_neg && std::abs(dem_height_neg[0]) <= std::abs(dem_height_pos[0])){\n\tdem_height = dem_height_neg;\n\tlen = final_len_neg;\n      }\n      \n      vw_out() << \"Height error: \" << dem_height << std::endl;\n      \n      if (!success_pos && !success_neg) \n\tstatus = -1;\n      \n      if ( (status < 0) || (std::abs(dem_height[0]) > height_error_tol) ){\n        has_intersection = false;\n        return Vector3();\n      }\n\n      has_intersection = true;\n      xyz = camera_ctr + len[0]*camera_vec;\n      return xyz;\n    }catch(...){\n      has_intersection = false;\n    }\n    return Vector3();\n  }\n\n}\n}\n\n// Trace rays from pixel corners to DEM to see where they intersect the DEM\nvoid extract_lon_lat_from_camera(Options & opt, ImageViewRef< PixelMask<float> > const& interp_dem,\n\t\t\t\t GeoReference const& geo){\n\n  // Need this to be able to load adjusted camera models. That will happen\n  // in the stereo session.\n  asp::stereo_settings().bundle_adjust_prefix = opt.bundle_adjust_prefix;\n  \n  std::string out_prefix;\n  typedef boost::scoped_ptr<asp::StereoSession> SessionPtr;\n  SessionPtr session(asp::StereoSessionFactory::create(opt.stereo_session, // may change\n\t\t\t\t\t\t       opt,\n\t\t\t\t\t\t       opt.image_file, opt.image_file,\n\t\t\t\t\t\t       opt.input_camera, opt.input_camera,\n\t\t\t\t\t\t       out_prefix));\n\n  boost::shared_ptr<CameraModel> camera_model = session->camera_model(opt.image_file,\n\t\t\t\t\t\t\t\t      opt.input_camera);\n\n  // Store here pixel values for the rays emanating from the pixels at\n  // which we could intersect with the DEM.\n  std::vector<double> good_pixel_values;\n  \n  int num_points = opt.pixel_values.size()/2;\n  opt.lon_lat_values.reserve(2*num_points);\n  opt.lon_lat_values.clear();\n  \n  for (int it = 0; it < num_points; it++){\n\n    Vector2 pix(opt.pixel_values[2*it], opt.pixel_values[2*it+1]);\n\n    Vector3 camera_ctr = camera_model->camera_center(pix);\n    Vector3 camera_vec = camera_model->pixel_to_vector(pix);\n\n    bool treat_nodata_as_zero = false;\n    bool has_intersection = false;\n    double height_error_tol = 1.0; // error in DEM height\n    \n    double max_abs_tol = 1e-20;\n    double max_rel_tol      = 1e-20;\n    int num_max_iter        = 1000;\n    Vector3 xyz_guess       = Vector3();\n\n    Vector3 xyz = camera_pixel_to_dem_xyz2(camera_ctr, camera_vec,  \n\t\t\t\t\t  interp_dem, geo, treat_nodata_as_zero,\n\t\t\t\t\t   has_intersection, height_error_tol,\n\t\t\t\t\t   max_abs_tol, max_rel_tol, num_max_iter, xyz_guess);\n\n    if (xyz == Vector3() || !has_intersection){\n      vw_out() << \"Could not intersect the DEM with a ray coming \"\n\t       << \"from the camera at pixel: \" << pix << \". Skipping it.\\n\";\n      continue;\n    }\n\n    Vector3 llh = geo.datum().cartesian_to_geodetic(xyz);\n    \n    opt.lon_lat_values.push_back(llh[0]);\n    opt.lon_lat_values.push_back(llh[1]);\n    good_pixel_values.push_back(opt.pixel_values[2*it]);\n    good_pixel_values.push_back(opt.pixel_values[2*it+1]);\n  }\n\n  if (good_pixel_values.size() < 6) {\n    vw_throw( ArgumentErr() << \"Successful intersection happened for less than \"\n\t      << \"3 pixels. Will not be able to create a camera. Consider checking \"\n\t      << \"your inputs, or passing different pixels in --pixel-values.\"\n\t      << opt.reference_dem << \".\\n\");\n  }\n\n  // Update with the values at which we were successful\n  opt.pixel_values = good_pixel_values;\n}\n\nint main(int argc, char * argv[]){\n  \n  Options opt;\n  try {\n    \n    handle_arguments(argc, argv, opt);\n    \n    vw::cartography::Datum datum;\n    GeoReference geo;\n    ImageView<float> dem;\n    float nodata_value = -std::numeric_limits<float>::max(); \n    bool has_dem = false;\n    if (opt.reference_dem != \"\") {\n      dem = DiskImageView<float>(opt.reference_dem);\n      bool ans = read_georeference(geo, opt.reference_dem);\n      if (!ans) \n        vw_throw( ArgumentErr() << \"Could not read the georeference from dem: \"\n                  << opt.reference_dem << \".\\n\");\n\n      datum = geo.datum(); // Read this in for completeness\n      has_dem = true;\n      vw::read_nodata_val(opt.reference_dem, nodata_value);\n      vw_out() << \"Using nodata value: \" << nodata_value << std::endl;\n    }else{\n      datum = vw::cartography::Datum(opt.datum_str); \n      vw_out() << \"No reference DEM provided. Will use a height of \"\n               << opt.height_above_datum << \" above the datum:\\n\" \n               << datum << std::endl;\n    }\n\n    // Prepare the DEM for interpolation\n    ImageViewRef< PixelMask<float> > interp_dem\n      = interpolate(create_mask(dem, nodata_value),\n\t\t    BilinearInterpolation(), ZeroEdgeExtension());\n\n    // If we have camera center in ECI or ECEF coordinates in km, convert\n    // to height above datum.\n    Vector3 parsed_cam_ctr;\n    if (opt.parsed_cam_ctr_str != \"\") {\n      std::vector<double> vals;\n      parse_values<double>(opt.parsed_cam_ctr_str, vals);\n      if (vals.size() != 3) \n\tvw_throw( ArgumentErr() << \"Could not parse 3 values from: \"\n\t\t  << opt.parsed_cam_ctr_str << \".\\n\");\n\n      parsed_cam_ctr = Vector3(vals[0], vals[1], vals[2]);\n      parsed_cam_ctr *= 1000.0;  // convert to meters\n      vw_out().precision(18);\n      vw_out() << \"Parsed camera center (meters): \" << parsed_cam_ctr << \"\\n\";\n\n      Vector3 llh = datum.cartesian_to_geodetic(parsed_cam_ctr);\n      \n      // If parsed_cam_ctr is in ECI coordinates, the lon and lat won't be accurate\n      // but the height will be.\n      if (opt.cam_weight > 0) \n\topt.cam_height = llh[2];\n    }\n    \n    vw::Quat parsed_cam_quat;\n    if (opt.parsed_cam_quat_str != \"\") {\n      std::vector<double> vals;\n      parse_values<double>(opt.parsed_cam_quat_str, vals);\n      if (vals.size() != 4) \n\tvw_throw( ArgumentErr() << \"Could not parse 4 values from: \"\n\t\t  << opt.parsed_cam_quat_str << \".\\n\");\n\n      parsed_cam_quat = vw::Quat(vals[0], vals[1], vals[2], vals[3]);\n      vw_out() << \"Parsed camera quaternion: \" << parsed_cam_quat << \"\\n\";\n    }\n    \n    if (opt.cam_weight > 0) {\n      vw_out() << \"Will attempt to find a camera center height above datum of \"\n\t       << opt.cam_height\n\t       << \" meters with a weight strength of \" << opt.cam_weight << \".\\n\";\n    }\n    \n    if (opt.input_camera != \"\"){\n      // Extract lon and lat from tracing rays from the camera to the ground.\n      // This can modify opt.pixel_values.\n      extract_lon_lat_from_camera(opt, create_mask(dem, nodata_value), geo);\n    }\n\n    if (opt.lon_lat_values.size() < 3) \n      vw_throw( ArgumentErr() << \"Expecting at least three longitude-latitude pairs.\\n\");\n\n    if (opt.lon_lat_values.size() != opt.pixel_values.size()){\n      vw_throw( ArgumentErr()\n\t\t<< \"The number of lon-lat pairs must equal the number of pixel pairs.\\n\");\n    }\n\n    size_t num_lon_lat_pairs = opt.lon_lat_values.size()/2;\n    \n    Vector2 pix;\n    Vector3 llh, xyz;\n    std::vector<Vector3> xyz_vec;\n\n    // If to write a gcp file\n    std::ostringstream gcp;\n    gcp.precision(17);\n    bool write_gcp = (opt.gcp_file != \"\");\n\n    for (size_t corner_it = 0; corner_it < num_lon_lat_pairs; corner_it++) {\n\n      // Get the height from the DEM if possible\n      llh[0] = opt.lon_lat_values[2*corner_it+0];\n      llh[1] = opt.lon_lat_values[2*corner_it+1];\n\n      if (llh[1] < -90 || llh[1] > 90) \n        vw_throw( ArgumentErr() << \"Detected a latitude out of bounds. \"\n                  << \"Perhaps the longitude and latitude are reversed?\\n\");\n      double height = opt.height_above_datum;\n      if (has_dem) {\n        bool success = false;\n        pix = geo.lonlat_to_pixel(subvector(llh, 0, 2));\n        int len =  BilinearInterpolation::pixel_buffer;\n        if (pix[0] >= 0 && pix[0] <= interp_dem.cols() - 1 - len &&\n            pix[1] >= 0 && pix[1] <= interp_dem.rows() - 1 - len) {\n          PixelMask<float> masked_height = interp_dem(pix[0], pix[1]);\n          if (is_valid(masked_height)) {\n            height = masked_height.child();\n            success = true;\n          }\n        }\n        if (!success) \n          vw_out() << \"Could not determine a valid height value at lon-lat: \"\n\t\t   << llh[0] << ' ' << llh[1] << \". Will use a height of \" << height << \".\\n\";\n      }\n      \n      llh[2] = height;\n      //vw_out() << \"Lon-lat-height for corner (\"\n      //         << opt.pixel_values[2*corner_it] << \", \" << opt.pixel_values[2*corner_it+1]\n      //         << \") is \"\n      //         << llh[0] << \", \" << llh[1] << \", \" << llh[2] << std::endl;\n    \n      xyz = datum.geodetic_to_cartesian(llh);\n      xyz_vec.push_back(xyz);\n\n      if (write_gcp)\n        gcp << corner_it << ' ' << llh[1] << ' ' << llh[0] << ' ' << llh[2] << ' '\n            << 1 << ' ' << 1 << ' ' << 1 << ' ' << opt.image_file << ' '\n            << opt.pixel_values[2*corner_it] << ' ' << opt.pixel_values[2*corner_it+1] << ' '\n            << opt.gcp_std << ' ' << opt.gcp_std << std::endl;\n    } // End loop through lon-lat pairs\n\n    if (write_gcp) {\n      vw_out() << \"Writing: \" << opt.gcp_file << std::endl;\n      std::ofstream fs(opt.gcp_file.c_str());\n      fs << gcp.str();\n      fs.close();\n    }\n    \n    // Form a camera based on info the user provided\n    boost::shared_ptr<CameraModel> out_cam;\n    DiskImageView<float> img(opt.image_file);\n    int wid = img.cols(), hgt = img.rows();\n    if (wid <= 0 || hgt <= 0) \n      vw_throw( ArgumentErr() << \"Could not read an image with positive dimensions from: \"\n\t\t<< opt.image_file << \".\\n\");\n    manufacture_cam(opt, wid, hgt, out_cam);\n\n    // Transform it and optionally refine it\n    bool verbose = true;\n    fit_camera_to_xyz_ht(opt.parse_ecef, parsed_cam_ctr,\n\t\t\t opt.camera_type, opt.refine_camera,  \n\t\t\t xyz_vec, opt.pixel_values, \n\t\t\t opt.cam_height, opt.cam_weight, datum,\n\t\t\t verbose, out_cam);\n    \n    if ((opt.parse_eci || opt.parse_ecef) && opt.camera_type == \"opticalbar\") {\n      vw_throw( ArgumentErr() << \"Cannot parse ECI/ECEF data for an optical bar camera.\\n\");\n    }\n\n    // Code that is not working. \n    //((vw::camera::PinholeModel*)out_cam.get())->set_camera_center(parsed_cam_ctr); \n    //((vw::camera::PinholeModel*)out_cam.get())->set_camera_pose(parsed_cam_quat); \n    //if (opt.parse_eci)\n    // ((vw::camera::PinholeModel*)out_cam.get())->set_camera_pose(parsed_cam_quat);\n    //if (opt.parse_ecef) \n    // ((vw::camera::PinholeModel*)out_cam.get())->set_camera_pose\n    //\t(inverse(parsed_cam_quat));\n    \n    llh = datum.cartesian_to_geodetic(out_cam->camera_center(Vector2()));\n    vw_out() << \"Output camera center lon, lat, and height above datum: \" << llh << std::endl;\n    vw_out() << \"Writing: \" << opt.camera_file << std::endl;\n    if (opt.camera_type == \"opticalbar\")\n      ((vw::camera::OpticalBarModel*)out_cam.get())->write(opt.camera_file);\n    else {\n      ((vw::camera::PinholeModel*)out_cam.get())->write(opt.camera_file);\n    }\n\n\n  } ASP_STANDARD_CATCHES;\n    \n  return 0;\n}\n", "meta": {"hexsha": "606da80ef46877ddf9c537e34fcb0dec2ee4fceb", "size": 43946, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/asp/Tools/cam_gen.cc", "max_stars_repo_name": "PicoJr/StereoPipeline", "max_stars_repo_head_hexsha": "146110a4d43ce6cb5e950297b8dca3f3b5e3f3b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-08-11T19:08:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-11T19:08:52.000Z", "max_issues_repo_path": "src/asp/Tools/cam_gen.cc", "max_issues_repo_name": "PicoJr/StereoPipeline", "max_issues_repo_head_hexsha": "146110a4d43ce6cb5e950297b8dca3f3b5e3f3b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/asp/Tools/cam_gen.cc", "max_forks_repo_name": "PicoJr/StereoPipeline", "max_forks_repo_head_hexsha": "146110a4d43ce6cb5e950297b8dca3f3b5e3f3b4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-09-24T05:49:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-12T18:00:16.000Z", "avg_line_length": 40.6907407407, "max_line_length": 368, "alphanum_fraction": 0.6417193829, "num_tokens": 11531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.3702253856469203, "lm_q1q2_score": 0.20098176836609405}}
{"text": "/**\n * @file methods/ann/brnn_impl.hpp\n * @author Saksham Bansal\n *\n * Definition of the BRNN class, which implements bidirectional recurrent\n * neural networks.\n *\n * mlpack is free software; you may redistribute it and/or modify it under the\n * terms of the 3-clause BSD license.  You should have received a copy of the\n * 3-clause BSD license along with mlpack.  If not, see\n * http://www.opensource.org/licenses/BSD-3-Clause for more information.\n */\n#ifndef MLPACK_METHODS_ANN_BRNN_IMPL_HPP\n#define MLPACK_METHODS_ANN_BRNN_IMPL_HPP\n\n// In case it hasn't been included yet.\n#include \"brnn.hpp\"\n\n#include \"visitor/load_output_parameter_visitor.hpp\"\n#include \"visitor/save_output_parameter_visitor.hpp\"\n#include \"visitor/forward_visitor.hpp\"\n#include \"visitor/backward_visitor.hpp\"\n#include \"visitor/reset_cell_visitor.hpp\"\n#include \"visitor/gradient_set_visitor.hpp\"\n#include \"visitor/gradient_visitor.hpp\"\n#include \"visitor/weight_set_visitor.hpp\"\n#include \"visitor/run_set_visitor.hpp\"\n\n#include <boost/serialization/variant.hpp>\n\nnamespace mlpack {\nnamespace ann /** Artificial Neural Network. */ {\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\nBRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::BRNN(\n    const size_t rho,\n    const bool single,\n    OutputLayerType outputLayer,\n    MergeLayerType* mergeLayer,\n    MergeOutputType* mergeOutput,\n    InitializationRuleType initializeRule) :\n    rho(rho),\n    outputLayer(std::move(outputLayer)),\n    mergeLayer(mergeLayer),\n    mergeOutput(mergeOutput),\n    initializeRule(std::move(initializeRule)),\n    inputSize(0),\n    outputSize(0),\n    targetSize(0),\n    reset(false),\n    single(single),\n    numFunctions(0),\n    deterministic(true),\n    forwardRNN(rho, single, outputLayer, initializeRule),\n    backwardRNN(rho, single, outputLayer, initializeRule)\n{\n  /* Nothing to do here. */\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\nBRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::~BRNN()\n{\n  // Remove the last layers from the forward and backward RNNs, as they are held\n  // in mergeLayer.  So, when we use DeleteVisitor with mergeLayer, those two\n  // layers will be properly (and not doubly) freed.\n  forwardRNN.network.pop_back();\n  backwardRNN.network.pop_back();\n\n  // Clean up layers that we allocated.\n  boost::apply_visitor(DeleteVisitor(), mergeLayer);\n  boost::apply_visitor(DeleteVisitor(), mergeOutput);\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename OptimizerType>\ntypename std::enable_if<\n      HasMaxIterations<OptimizerType, size_t&(OptimizerType::*)()>\n      ::value, void>::type\nBRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::WarnMessageMaxIterations\n(OptimizerType& optimizer, size_t samples) const\n{\n  if (optimizer.MaxIterations() < samples &&\n      optimizer.MaxIterations() != 0)\n  {\n    Log::Warn << \"The optimizer's maximum number of iterations \"\n              << \"is less than the size of the dataset; the \"\n              << \"optimizer will not pass over the entire \"\n              << \"dataset. To fix this, modify the maximum \"\n              << \"number of iterations to be at least equal \"\n              << \"to the number of points of your dataset \"\n              << \"(\" << samples << \").\" << std::endl;\n  }\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename OptimizerType>\ntypename std::enable_if<\n      !HasMaxIterations<OptimizerType, size_t&(OptimizerType::*)()>\n      ::value, void>::type\nBRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::WarnMessageMaxIterations\n(OptimizerType& optimizer, size_t samples) const\n{\n  return;\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename OptimizerType>\ndouble BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::Train(\n    arma::cube predictors,\n    arma::cube responses,\n    OptimizerType& optimizer)\n{\n  numFunctions = responses.n_cols;\n\n  this->predictors = std::move(predictors);\n  this->responses = std::move(responses);\n\n  this->deterministic = true;\n  ResetDeterministic();\n\n  if (!reset)\n  {\n    ResetParameters();\n  }\n\n  WarnMessageMaxIterations<OptimizerType>(optimizer, this->predictors.n_cols);\n\n  // Train the model.\n  Timer::Start(\"BRNN_optimization\");\n  const double out = optimizer.Optimize(*this, parameter);\n  Timer::Stop(\"BRNN_optimization\");\n\n  Log::Info << \"BRNN::BRNN(): final objective of trained model is \" << out\n      << \".\" << std::endl;\n  return out;\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename OptimizerType>\ndouble BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::Train(\n    arma::cube predictors,\n    arma::cube responses)\n{\n  numFunctions = responses.n_cols;\n\n  this->predictors = std::move(predictors);\n  this->responses = std::move(responses);\n\n  this->deterministic = true;\n  ResetDeterministic();\n\n  if (!reset)\n  {\n    ResetParameters();\n  }\n\n  OptimizerType optimizer;\n\n  WarnMessageMaxIterations<OptimizerType>(optimizer, this->predictors.n_cols);\n\n  // Train the model.\n  const double out = optimizer.Optimize(*this, parameter);\n\n  Log::Info << \"BRNN::BRNN(): final objective of trained model is \" << out\n      << \".\" << std::endl;\n  return out;\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::Predict(\n    arma::cube predictors, arma::cube& results, const size_t batchSize)\n{\n  forwardRNN.rho = backwardRNN.rho = rho;\n\n  forwardRNN.ResetCells();\n  backwardRNN.ResetCells();\n\n  if (!deterministic)\n  {\n    deterministic = true;\n    ResetDeterministic();\n  }\n  if (parameter.is_empty())\n  {\n    ResetParameters();\n  }\n\n  if (std::is_same<MergeLayerType, Concat<>>::value)\n  {\n    results = arma::zeros<arma::cube>(outputSize * 2, predictors.n_cols, rho);\n  }\n  else\n  {\n    results = arma::zeros<arma::cube>(outputSize, predictors.n_cols, rho);\n  }\n\n  std::vector<arma::mat> results1, results2;\n  arma::mat input;\n\n  // Forward both RNN's from opposite directions.\n  for (size_t begin = 0; begin < predictors.n_cols; begin += batchSize)\n  {\n    const size_t effectiveBatchSize = std::min(batchSize,\n        size_t(predictors.n_cols - begin));\n    for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n    {\n      forwardRNN.Forward(arma::mat(\n          predictors.slice(seqNum).colptr(begin),\n          predictors.n_rows, effectiveBatchSize, false, true));\n      backwardRNN.Forward(std::move(arma::mat(\n          predictors.slice(rho - seqNum - 1).colptr(begin),\n          predictors.n_rows, effectiveBatchSize, false, true)));\n\n      boost::apply_visitor(SaveOutputParameterVisitor(results1),\n          forwardRNN.network.back());\n      boost::apply_visitor(SaveOutputParameterVisitor(results2),\n          backwardRNN.network.back());\n    }\n    reverse(results1.begin(), results1.end());\n\n    // Forward outputs from both RNN's through merge layer for each time step.\n    for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n    {\n      boost::apply_visitor(LoadOutputParameterVisitor(results1),\n          forwardRNN.network.back());\n      boost::apply_visitor(LoadOutputParameterVisitor(results2),\n          backwardRNN.network.back());\n\n      boost::apply_visitor(ForwardVisitor(input,\n          boost::apply_visitor(outputParameterVisitor, mergeLayer)),\n          mergeLayer);\n      boost::apply_visitor(ForwardVisitor(\n          boost::apply_visitor(outputParameterVisitor, mergeLayer),\n          boost::apply_visitor(outputParameterVisitor, mergeOutput)),\n          mergeOutput);\n      results.slice(seqNum).submat(0, begin, results.n_rows - 1, begin +\n          effectiveBatchSize - 1) =\n          boost::apply_visitor(outputParameterVisitor, mergeOutput);\n    }\n  }\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\ndouble BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::Evaluate(\n    const arma::mat& /* parameters */,\n    const size_t begin,\n    const size_t batchSize,\n    const bool deterministic)\n{\n  forwardRNN.rho = backwardRNN.rho = rho;\n  if (parameter.is_empty())\n  {\n    ResetParameters();\n  }\n\n  if (deterministic != this->deterministic)\n  {\n    this->deterministic = deterministic;\n    ResetDeterministic();\n  }\n\n  if (!inputSize)\n  {\n    inputSize = predictors.n_rows;\n    targetSize = responses.n_rows;\n  }\n  else if (targetSize == 0)\n  {\n    targetSize = responses.n_rows;\n  }\n\n  forwardRNN.ResetCells();\n  backwardRNN.ResetCells();\n\n  double performance = 0;\n  size_t responseSeq = 0;\n\n  std::vector<arma::mat> results1, results2;\n  for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n  {\n    forwardRNN.Forward(arma::mat(\n        predictors.slice(seqNum).colptr(begin),\n        predictors.n_rows, batchSize, false, true));\n    backwardRNN.Forward(arma::mat(\n        predictors.slice(rho - seqNum - 1).colptr(begin),\n        predictors.n_rows, batchSize, false, true));\n\n    boost::apply_visitor(SaveOutputParameterVisitor(results1),\n        forwardRNN.network.back());\n    boost::apply_visitor(SaveOutputParameterVisitor(results2),\n        backwardRNN.network.back());\n  }\n  if (outputSize == 0)\n  {\n    outputSize = boost::apply_visitor(outputParameterVisitor,\n        forwardRNN.network.back()).n_elem / batchSize;\n    forwardRNN.outputSize = backwardRNN.outputSize = outputSize;\n  }\n  reverse(results1.begin(), results1.end());\n\n  // Performance calculation after forwarding through merge layer.\n  arma::mat input;\n  for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n  {\n    if (!single)\n    {\n      responseSeq = seqNum;\n    }\n    boost::apply_visitor(LoadOutputParameterVisitor(results1),\n        forwardRNN.network.back());\n    boost::apply_visitor(LoadOutputParameterVisitor(results2),\n        backwardRNN.network.back());\n\n    boost::apply_visitor(ForwardVisitor(input,\n        boost::apply_visitor(outputParameterVisitor, mergeLayer)),\n        mergeLayer);\n    boost::apply_visitor(ForwardVisitor(\n        boost::apply_visitor(outputParameterVisitor, mergeLayer),\n        boost::apply_visitor(outputParameterVisitor, mergeOutput)),\n        mergeOutput);\n    performance += outputLayer.Forward(\n        boost::apply_visitor(outputParameterVisitor, mergeOutput),\n        arma::mat(responses.slice(responseSeq).colptr(begin),\n        responses.n_rows, batchSize, false, true));\n  }\n  return performance;\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\ndouble BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::Evaluate(\n    const arma::mat& parameters,\n    const size_t begin,\n    const size_t batchSize)\n{\n  return Evaluate(parameters, begin, batchSize, true);\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename GradType>\ndouble BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::\nEvaluateWithGradient(const arma::mat& /* parameters */,\n                     const size_t begin,\n                     GradType& gradient,\n                     const size_t batchSize)\n{\n  forwardRNN.rho = backwardRNN.rho = rho;\n  if (gradient.is_empty())\n  {\n    if (parameter.is_empty())\n    {\n      ResetParameters();\n    }\n    gradient = arma::zeros<arma::mat>(parameter.n_rows, parameter.n_cols);\n  }\n  else\n  {\n    gradient.zeros();\n  }\n\n  if (backwardGradient.is_empty())\n  {\n    backwardGradient = arma::zeros<arma::mat>(\n        parameter.n_rows/ 2,\n        parameter.n_cols);\n    forwardGradient = arma::zeros<arma::mat>(\n        parameter.n_rows/ 2,\n        parameter.n_cols);\n  }\n  if (this->deterministic)\n  {\n    this->deterministic = false;\n    ResetDeterministic();\n  }\n\n  if (!inputSize)\n  {\n    inputSize = predictors.n_rows;\n    targetSize = responses.n_rows;\n  }\n  else if (targetSize == 0)\n  {\n    targetSize = responses.n_rows;\n  }\n\n  forwardRNN.ResetCells();\n  backwardRNN.ResetCells();\n  size_t networkSize = backwardRNN.network.size();\n\n  // Forward propogation from both directions.\n  std::vector<arma::mat> results1, results2;\n  for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n  {\n    forwardRNN.Forward(arma::mat(\n        predictors.slice(seqNum).colptr(begin),\n        predictors.n_rows, batchSize, false, true));\n    backwardRNN.Forward(arma::mat(\n        predictors.slice(rho - seqNum - 1).colptr(begin),\n        predictors.n_rows, batchSize, false, true));\n\n    for (size_t l = 0; l < networkSize; ++l)\n    {\n      boost::apply_visitor(SaveOutputParameterVisitor(\n          forwardRNNOutputParameter), forwardRNN.network[l]);\n      boost::apply_visitor(SaveOutputParameterVisitor(\n          backwardRNNOutputParameter), backwardRNN.network[l]);\n    }\n    boost::apply_visitor(SaveOutputParameterVisitor(results1),\n        forwardRNN.network.back());\n    boost::apply_visitor(SaveOutputParameterVisitor(results2),\n        backwardRNN.network.back());\n  }\n  if (outputSize == 0)\n  {\n    outputSize = boost::apply_visitor(outputParameterVisitor,\n        forwardRNN.network.back()).n_elem / batchSize;\n    forwardRNN.outputSize = backwardRNN.outputSize = outputSize;\n  }\n\n  arma::cube results;\n  if (std::is_same<MergeLayerType, Concat<>>::value)\n  {\n    results = arma::zeros<arma::cube>(outputSize * 2, batchSize, rho);\n  }\n  else\n  {\n    results = arma::zeros<arma::cube>(outputSize, batchSize, rho);\n  }\n\n  double performance = 0;\n  size_t responseSeq = 0;\n  arma::mat input;\n\n  reverse(results1.begin(), results1.end());\n  // Performance calculation here.\n  for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n  {\n    if (!single)\n    {\n      responseSeq = seqNum;\n    }\n    boost::apply_visitor(LoadOutputParameterVisitor(\n          results1), forwardRNN.network.back());\n    boost::apply_visitor(LoadOutputParameterVisitor(\n          results2), backwardRNN.network.back());\n    boost::apply_visitor(ForwardVisitor(input,\n        boost::apply_visitor(outputParameterVisitor, mergeLayer)),\n        mergeLayer);\n    boost::apply_visitor(ForwardVisitor(\n        boost::apply_visitor(outputParameterVisitor, mergeLayer),\n        results.slice(seqNum)), mergeOutput);\n    performance += outputLayer.Forward(results.slice(seqNum),\n        arma::mat(responses.slice(responseSeq).colptr(begin),\n        responses.n_rows, batchSize, false, true));\n  }\n\n  // Calculate and storing delta parameters from output for t = 1 to T.\n  arma::mat delta;\n  std::vector<arma::mat> allDelta;\n\n  for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n  {\n    if (single && seqNum > 0)\n    {\n      error.zeros();\n    }\n    else if (single && seqNum == 0)\n    {\n      outputLayer.Backward(results.slice(seqNum),\n          arma::mat(responses.slice(0).colptr(begin),\n          responses.n_rows, batchSize, false, true), error);\n    }\n    else\n    {\n      outputLayer.Backward(results.slice(seqNum),\n          arma::mat(responses.slice(seqNum).colptr(begin),\n          responses.n_rows, batchSize, false, true), error);\n    }\n\n    boost::apply_visitor(BackwardVisitor(results.slice(seqNum), error, delta),\n        mergeOutput);\n    allDelta.push_back(arma::mat(delta));\n  }\n\n  // BPTT ForwardRNN from t = T to 1.\n  totalGradient = arma::mat(gradient.memptr(),\n      parameter.n_elem / 2, 1, false, false);\n\n  forwardGradient.zeros();\n  forwardRNN.ResetGradients(forwardGradient);\n  backwardGradient.zeros();\n  backwardRNN.ResetGradients(backwardGradient);\n\n  for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n  {\n    forwardGradient.zeros();\n    for (size_t l = 0; l < networkSize; ++l)\n    {\n      boost::apply_visitor(LoadOutputParameterVisitor(\n          forwardRNNOutputParameter),\n          forwardRNN.network[networkSize - 1 - l]);\n    }\n    boost::apply_visitor(BackwardVisitor(boost::apply_visitor(\n        outputParameterVisitor, forwardRNN.network.back()),\n        allDelta[rho - seqNum - 1], delta, 0),\n        mergeLayer);\n\n    for (size_t i = 2; i < networkSize; ++i)\n    {\n      boost::apply_visitor(BackwardVisitor(\n          boost::apply_visitor(outputParameterVisitor,\n          forwardRNN.network[networkSize - i]),\n          boost::apply_visitor(deltaVisitor,\n          forwardRNN.network[networkSize - i + 1]),\n          boost::apply_visitor(deltaVisitor,\n          forwardRNN.network[networkSize - i])),\n          forwardRNN.network[networkSize - i]);\n    }\n    forwardRNN.Gradient(\n        arma::mat(predictors.slice(rho - seqNum - 1).colptr(begin),\n        predictors.n_rows, batchSize, false, true));\n    boost::apply_visitor(GradientVisitor(\n        boost::apply_visitor(outputParameterVisitor,\n        forwardRNN.network[networkSize - 2]),\n        allDelta[rho - seqNum - 1], 0), mergeLayer);\n    totalGradient += forwardGradient;\n  }\n\n  // BPTT BackwardRNN from t = 1 to T.\n  totalGradient = arma::mat(gradient.memptr() + parameter.n_elem/2,\n      parameter.n_elem/2, 1, false, false);\n\n  for (size_t seqNum = 0; seqNum < rho; ++seqNum)\n  {\n    backwardGradient.zeros();\n    for (size_t l = 0; l < networkSize; ++l)\n    {\n      boost::apply_visitor(LoadOutputParameterVisitor(\n          backwardRNNOutputParameter),\n          backwardRNN.network[networkSize - 1 - l]);\n    }\n    boost::apply_visitor(BackwardVisitor(\n        boost::apply_visitor(outputParameterVisitor,\n        backwardRNN.network.back()),\n        allDelta[seqNum], delta, 1), mergeLayer);\n    for (size_t i = 2; i < networkSize; ++i)\n    {\n      boost::apply_visitor(BackwardVisitor(\n        boost::apply_visitor(outputParameterVisitor,\n        backwardRNN.network[networkSize - i]), boost::apply_visitor(\n        deltaVisitor, backwardRNN.network[networkSize - i + 1]),\n        boost::apply_visitor(deltaVisitor,\n        backwardRNN.network[networkSize - i])),\n        backwardRNN.network[networkSize - i]);\n    }\n\n    backwardRNN.Gradient(\n        arma::mat(predictors.slice(seqNum).colptr(begin),\n        predictors.n_rows, batchSize, false, true));\n    boost::apply_visitor(GradientVisitor(\n        std::move(boost::apply_visitor(outputParameterVisitor,\n        backwardRNN.network[networkSize - 2])),\n        allDelta[seqNum], 1), mergeLayer);\n    totalGradient += backwardGradient;\n  }\n  return performance;\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::Gradient(\n    const arma::mat& parameters,\n    const size_t begin,\n    arma::mat& gradient,\n    const size_t batchSize)\n{\n  this->EvaluateWithGradient(parameters, begin, gradient, batchSize);\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::Shuffle()\n{\n  arma::cube newPredictors, newResponses;\n  math::ShuffleData(predictors, responses, newPredictors, newResponses);\n\n  predictors = std::move(newPredictors);\n  responses = std::move(newResponses);\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate <class LayerType, class... Args>\nvoid BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::Add(Args... args)\n{\n  forwardRNN.network.push_back(new LayerType(args...));\n  backwardRNN.network.push_back(new LayerType(args...));\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::\nAdd(LayerTypes<CustomLayers...> layer)\n{\n  forwardRNN.network.push_back(layer);\n  backwardRNN.network.push_back(boost::apply_visitor(copyVisitor, layer));\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::ResetParameters()\n{\n  if (!reset)\n  {\n    // TODO: what if we call ResetParameters() multiple times?  Do we have to\n    // remove any existing mergeLayer?\n    boost::apply_visitor(AddVisitor<CustomLayers...>(\n        forwardRNN.network.back()), mergeLayer);\n    boost::apply_visitor(AddVisitor<CustomLayers...>(\n        backwardRNN.network.back()), mergeLayer);\n    boost::apply_visitor(RunSetVisitor(false), mergeLayer);\n  }\n\n  ResetDeterministic();\n\n  // Reset the network parameter with the given initialization rule.\n  NetworkInitialization<InitializationRuleType,\n                        CustomLayers...> networkInit(initializeRule);\n  size_t rnnWeights = 0;\n  for (size_t i = 0; i < forwardRNN.network.size(); ++i)\n  {\n    rnnWeights += boost::apply_visitor(weightSizeVisitor,\n        forwardRNN.network[i]);\n  }\n\n  parameter.set_size(2 * rnnWeights, 1);\n\n  forwardRNN.Parameters() = arma::mat(parameter.memptr(),\n      rnnWeights, 1, false, false);\n  backwardRNN.Parameters() = arma::mat(parameter.memptr() + rnnWeights,\n      rnnWeights, 1, false, false);\n\n  // Initialize the forward RNN parameters\n  networkInit.Initialize(forwardRNN.network, parameter);\n\n  // Initialize the backward RNN parameters\n  networkInit.Initialize(backwardRNN.network, parameter, rnnWeights);\n\n  reset = forwardRNN.reset = backwardRNN.reset = true;\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::Reset()\n{\n  ResetParameters();\n  forwardRNN.ResetCells();\n  backwardRNN.ResetCells();\n  forwardGradient.zeros();\n  forwardRNN.ResetGradients(forwardGradient);\n  backwardGradient.zeros();\n  backwardRNN.ResetGradients(backwardGradient);\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\nvoid BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::ResetDeterministic()\n{\n  forwardRNN.deterministic = this->deterministic;\n  backwardRNN.deterministic = this->deterministic;\n  forwardRNN.ResetDeterministic();\n  backwardRNN.ResetDeterministic();\n}\n\ntemplate<typename OutputLayerType, typename MergeLayerType,\n         typename MergeOutputType, typename InitializationRuleType,\n         typename... CustomLayers>\ntemplate<typename Archive>\nvoid BRNN<OutputLayerType, MergeLayerType, MergeOutputType,\n    InitializationRuleType, CustomLayers...>::serialize(\n    Archive& ar, const unsigned int version)\n{\n  ar & BOOST_SERIALIZATION_NVP(parameter);\n  ar & BOOST_SERIALIZATION_NVP(backwardRNN);\n  ar & BOOST_SERIALIZATION_NVP(forwardRNN);\n\n  // TODO: are there more parameters to be serialized?\n}\n\n} // namespace ann\n} // namespace mlpack\n\n#endif\n", "meta": {"hexsha": "b1a6bf3f175bfb806f45f82c8fec9b5fb9eeb905", "size": 24398, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlpack/methods/ann/brnn_impl.hpp", "max_stars_repo_name": "KimSangYeon-DGU/mlpack", "max_stars_repo_head_hexsha": "defa29791f43d3372b019f552134abc39def234a", "max_stars_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-02-29T17:39:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-16T23:36:01.000Z", "max_issues_repo_path": "src/mlpack/methods/ann/brnn_impl.hpp", "max_issues_repo_name": "birm/mlpack", "max_issues_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_issues_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlpack/methods/ann/brnn_impl.hpp", "max_forks_repo_name": "birm/mlpack", "max_forks_repo_head_hexsha": "8e906556bbbd5be59481329567c2f9a413e72b11", "max_forks_repo_licenses": ["BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T13:27:26.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-23T09:44:31.000Z", "avg_line_length": 33.1044776119, "max_line_length": 80, "alphanum_fraction": 0.7011640298, "num_tokens": 5738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.20076527063350744}}
{"text": "#include \"MarchingCubes.h\"\r\n#include \"MCLookupTables.h\"\r\n#include <string.h>\r\n#include <iostream>\r\n#include \"DensityFunctions.h\"\r\nusing namespace std;\r\n\r\n//boost\r\n#include <boost/thread/thread.hpp>\r\n#include <boost/asio.hpp>\r\n\r\nusing namespace boost;\r\nusing namespace asio;\r\n\r\n#define M_1_UV_SCALE 0.2f //bigger num = larger texture appearance\r\n\r\nextern Camera cam; //for centering terrain around eye\r\n\r\nstruct Voxel {\r\n\tfloat3 pos[8];\r\n\tfloat density[8];\r\n};\r\n\r\n//------------------------------------------Look Ups\r\nstatic int3 RELATIVE_CORNER_POS[8] = {\r\n    int3(0, 0, 0), //0\r\n    int3(1, 0, 0), //1\r\n    int3(1, 0, 1), //2\r\n    int3(0, 0, 1), //3\r\n    int3(0, 1, 0), //4\r\n    int3(1, 1, 0), //5\r\n    int3(1, 1, 1), //6\r\n    int3(0, 1, 1)  //7\r\n};\r\n\r\n//0 means x-edges, 1 means y-edges, 2 means z-edges\r\n//case 0: return 0; case 1: return 2; case 2: return 0;\r\n//case 3: return 2; case 4: return 0; case 5: return 2;\r\n//case 6: return 0; case 7: return 2; case 8: return 1;\r\n//case 9: return 1; case 10:return 1; case 11:return 1;\r\nstatic int EDGE_TYPE[12] = {0, 2, 0, 2, 0, 2, 0, 2, 1, 1, 1, 1};\r\n\r\nstatic int3 EDGE_OFFSETS[12] = {\r\n    int3(0, 0, 0), //0 //x-axis\r\n    int3(1, 0, 0), //1 //y-axis\r\n    int3(0, 0, 1), //2 //x-axis\r\n    int3(0, 0, 0), //3 //y-axis\r\n    int3(0, 1, 0), //4 //x-axis\r\n    int3(1, 1, 0), //5 //y-axis\r\n    int3(0, 1, 1), //6 //x-axis\r\n    int3(0, 1, 0), //7 //y-axis\r\n    int3(0, 0, 0), //8 //z-axis\r\n    int3(1, 0, 0), //9 //z-axis\r\n    int3(1, 0, 1), //10//z-axis\r\n    int3(0, 0, 1)  //11//z-axis\r\n};\r\n\r\n//------------------------------------------Utilities\r\nstatic inline\r\nfloat DensityFunction(const float3& pos) {\r\n    //return Plane(pos);\r\n    return Terrain(pos);\r\n}\r\n\r\n//Linear interpolation\r\nstatic inline\r\nfloat3 Lerp(const float3& vert0, const float3& vert1, float val0, float val1) {\r\n    return vert0 + (vert1 - vert0) * ((-val0) / (val1 - val0));\r\n    //OLD//return vert0 + (-val0) * (vert1 - vert0) / (val1 - val0);\r\n}\r\n\r\n//TODO [23:12] <LordCrc> say i is the index \"behind\", ie x-1 and j is the index in front, ie x+1, but i and j have been clamped using min/max\r\n//[23:12] <LordCrc> then you should divide by (j-i)\r\n\r\n//Our density value function - creates the field we are polygonizing\r\nstatic inline\r\nfloat3 GetVertexNormal(const int3& vc, int edge_idx, const float*** densities, const int3& num_voxels) {\r\n    //determine grid endpoints where the normals need to be calculated at\r\n    //gp0 = grid position 0\r\n    int3 gp0 = vc, gp1 = vc;\r\n    switch(edge_idx) {\r\n        case 0: gp0 += RELATIVE_CORNER_POS[0]; gp1 += RELATIVE_CORNER_POS[1]; break;\r\n        case 1: gp0 += RELATIVE_CORNER_POS[1]; gp1 += RELATIVE_CORNER_POS[2]; break;\r\n        case 2: gp0 += RELATIVE_CORNER_POS[2]; gp1 += RELATIVE_CORNER_POS[3]; break;\r\n        case 3: gp0 += RELATIVE_CORNER_POS[3]; gp1 += RELATIVE_CORNER_POS[0]; break;\r\n        case 4: gp0 += RELATIVE_CORNER_POS[4]; gp1 += RELATIVE_CORNER_POS[5]; break;\r\n        case 5: gp0 += RELATIVE_CORNER_POS[5]; gp1 += RELATIVE_CORNER_POS[6]; break;\r\n        case 6: gp0 += RELATIVE_CORNER_POS[6]; gp1 += RELATIVE_CORNER_POS[7]; break;\r\n        case 7: gp0 += RELATIVE_CORNER_POS[7]; gp1 += RELATIVE_CORNER_POS[4]; break;\r\n        case 8: gp0 += RELATIVE_CORNER_POS[0]; gp1 += RELATIVE_CORNER_POS[4]; break;\r\n        case 9: gp0 += RELATIVE_CORNER_POS[1]; gp1 += RELATIVE_CORNER_POS[5]; break;\r\n        case 10:gp0 += RELATIVE_CORNER_POS[2]; gp1 += RELATIVE_CORNER_POS[6]; break;\r\n        case 11:gp0 += RELATIVE_CORNER_POS[3]; gp1 += RELATIVE_CORNER_POS[7]; break;\r\n    }\r\n    //determine the normals at the two gridpoints\r\n    //gn0 = grid normal 0; gn1 = grid normal 1; (df/dx, df/dy, df/dz)\r\n    int min_gp0x = max(gp0.x - 1, 0); int max_gp0x = min(gp0.x + 1, num_voxels.x);\r\n    int min_gp0y = max(gp0.y - 1, 0); int max_gp0y = min(gp0.y + 1, num_voxels.y);\r\n    int min_gp0z = max(gp0.z - 1, 0); int max_gp0z = min(gp0.z + 1, num_voxels.z);\r\n    float3 gn0(densities[gp0.z][gp0.y][max_gp0x] - densities[gp0.z][gp0.y][min_gp0x],\r\n               densities[gp0.z][max_gp0y][gp0.x] - densities[gp0.z][min_gp0y][gp0.x],\r\n               densities[max_gp0z][gp0.y][gp0.x] - densities[min_gp0z][gp0.y][gp0.x]);\r\n    gn0 = normalize(gn0);\r\n    if(gn0.y < 0.f) gn0 *= -1.f; //flip if needed\r\n\r\n    int min_gp1x = max(gp1.x - 1, 0); int max_gp1x = min(gp1.x + 1, num_voxels.x);\r\n    int min_gp1y = max(gp1.y - 1, 0); int max_gp1y = min(gp1.y + 1, num_voxels.y);\r\n    int min_gp1z = max(gp1.z - 1, 0); int max_gp1z = min(gp1.z + 1, num_voxels.z);\r\n    float3 gn1(densities[gp0.z][gp0.y][max_gp1x] - densities[gp0.z][gp0.y][min_gp1x],\r\n               densities[gp0.z][max_gp1y][gp0.x] - densities[gp0.z][min_gp1y][gp0.x],\r\n               densities[max_gp1z][gp0.y][gp0.x] - densities[min_gp1z][gp0.y][gp0.x]);\r\n    gn1 = normalize(gn1);\r\n    if(gn1.y < 0.f) gn1 *= -1.f; //flip if needed\r\n\r\n    return normalize(Lerp(gn0, gn1, densities[gp0.z][gp0.y][gp0.x], densities[gp1.z][gp1.y][gp1.x]));\r\n}\r\n\r\n//------------------------------------------Marching Cubes Algorithm\r\n//TriangulateVoxelData(...) determines where to placed triangles (maximum 5)\r\n//depending on sign and value of the scalar field at passed voxel's corners.\r\n//vc = absolute voxel position (integers)\r\nstatic void TriangulateVoxelData(const Voxel& v, const int3& vc, const float*** densities,\r\n    int*** xedge_cache, int*** yedge_cache, int*** zedge_cache, vector<Triangle>* tris,\r\n    vector<float3>* verts, vector<float3>* normals, vector<float2>* uvs, const int3& num_voxels) {\r\n    //***determine case number (a.k.a voxel index)***\r\n    //determine corners that are inside the terrain\r\n    int voxel_index = 0;\r\n    if(v.density[0] > 0.f) voxel_index |= 1;\r\n    if(v.density[1] > 0.f) voxel_index |= 2;\r\n    if(v.density[2] > 0.f) voxel_index |= 4;\r\n    if(v.density[3] > 0.f) voxel_index |= 8;\r\n    if(v.density[4] > 0.f) voxel_index |= 16;\r\n    if(v.density[5] > 0.f) voxel_index |= 32;\r\n    if(v.density[6] > 0.f) voxel_index |= 64;\r\n    if(v.density[7] > 0.f) voxel_index |= 128;\r\n\r\n    if(EDGE_TABLE[voxel_index] == 0) {\r\n        return; //voxel completely in or out of surface\r\n    }\r\n    if(EDGE_TABLE[voxel_index] == 255) {\r\n        return; //voxel completely in or out of surface\r\n    }\r\n\r\n    //determine vertices\r\n    //there are 12 vertices because they are found on the edge of a voxel and there are 12 edges\r\n    float3 lerp_verts[12];\r\n\r\n    //bit operators...works on each bit of binary number\r\n    if(EDGE_TABLE[voxel_index] & 1)\r\n        lerp_verts[0] = Lerp(v.pos[0], v.pos[1], v.density[0], v.density[1]);\r\n    if(EDGE_TABLE[voxel_index] & 2)\r\n        lerp_verts[1] = Lerp(v.pos[1], v.pos[2], v.density[1], v.density[2]);\r\n    if(EDGE_TABLE[voxel_index] & 4)\r\n        lerp_verts[2] = Lerp(v.pos[2], v.pos[3], v.density[2], v.density[3]);\r\n    if(EDGE_TABLE[voxel_index] & 8)\r\n        lerp_verts[3] = Lerp(v.pos[3], v.pos[0], v.density[3], v.density[0]);\r\n    if(EDGE_TABLE[voxel_index] & 16)\r\n        lerp_verts[4] = Lerp(v.pos[4], v.pos[5], v.density[4], v.density[5]);\r\n    if(EDGE_TABLE[voxel_index] & 32)\r\n        lerp_verts[5] = Lerp(v.pos[5], v.pos[6], v.density[5], v.density[6]);\r\n    if(EDGE_TABLE[voxel_index] & 64)\r\n        lerp_verts[6] = Lerp(v.pos[6], v.pos[7], v.density[6], v.density[7]);\r\n    if(EDGE_TABLE[voxel_index] & 128)\r\n        lerp_verts[7] = Lerp(v.pos[7], v.pos[4], v.density[7], v.density[4]);\r\n    if(EDGE_TABLE[voxel_index] & 256)\r\n        lerp_verts[8] = Lerp(v.pos[0], v.pos[4], v.density[0], v.density[4]);\r\n    if(EDGE_TABLE[voxel_index] & 512)\r\n        lerp_verts[9] = Lerp(v.pos[1], v.pos[5], v.density[1], v.density[5]);\r\n    if(EDGE_TABLE[voxel_index] & 1024)\r\n        lerp_verts[10]= Lerp(v.pos[2], v.pos[6], v.density[2], v.density[6]);\r\n    if(EDGE_TABLE[voxel_index] & 2048)\r\n        lerp_verts[11]= Lerp(v.pos[3], v.pos[7], v.density[3], v.density[7]);\r\n\r\n    //***construct triangles***\r\n    for(int i = 0; TRIANGLE_TABLE[voxel_index][i] != -1; i += 3) {\r\n        //tris\r\n        Triangle tri;\r\n        float3 first_vert;\r\n        for (int j = 0; j < 3; j++) { //for each vert\r\n            int edge_idx = TRIANGLE_TABLE[voxel_index][i + j];\r\n            int edge_type = EDGE_TYPE[edge_idx]; //x, y, or z axis we are on\r\n            int3 e = vc + EDGE_OFFSETS[edge_idx];\r\n\r\n            if(edge_type == 0) {\r\n                if(xedge_cache[e.z][e.y][e.x] == -1) {\r\n                    xedge_cache[e.z][e.y][e.x] = verts->size(); //update cache\r\n                    verts->push_back(lerp_verts[edge_idx]);\r\n                    normals->push_back(GetVertexNormal(vc, edge_idx, densities, num_voxels));\r\n                    uvs->push_back(float2(0, 0)); //filled later. allocating for now\r\n                }\r\n                tri.vi[j] = xedge_cache[e.z][e.y][e.x];\r\n            } else if(edge_type == 1) {\r\n                if(yedge_cache[e.z][e.y][e.x] == -1) {\r\n                    yedge_cache[e.z][e.y][e.x] = verts->size(); //update cache\r\n                    verts->push_back(lerp_verts[edge_idx]);\r\n                    normals->push_back(GetVertexNormal(vc, edge_idx, densities, num_voxels));\r\n                    uvs->push_back(float2(0, 0)); //filled later\r\n\r\n                }\r\n                tri.vi[j] = yedge_cache[e.z][e.y][e.x];\r\n            } else { //edge_type == 2\r\n                if(zedge_cache[e.z][e.y][e.x] == -1) {\r\n                    zedge_cache[e.z][e.y][e.x] = verts->size(); //update cache\r\n                    verts->push_back(lerp_verts[edge_idx]);\r\n                    normals->push_back(GetVertexNormal(vc, edge_idx, densities, num_voxels));\r\n                    uvs->push_back(float2(0, 0)); //filled later                }\r\n                }\r\n                tri.vi[j] = zedge_cache[e.z][e.y][e.x];\r\n            }\r\n            uvs->at(tri.vi[j]) = float2(verts->at(tri.vi[j]).x * M_1_UV_SCALE,\r\n                                        verts->at(tri.vi[j]).z * M_1_UV_SCALE);\r\n        }\r\n        tris->push_back(tri);\r\n    }\r\n}\r\n\r\n//these functions will never access the same vertex. synchronization is not needed\r\nstatic inline\r\nvoid ScheduleAcrossX(const int const_x, const float3& voxel_size, int num_verty,\r\n    int num_vertz, float*** vert_densities, const float3& offset, io_service* thread_pool) {\r\n    //\r\n    for(int z = 0; z < num_vertz; z++) {\r\n        for(int y = 0; y < num_verty; y++) {\r\n            float3 corner(const_x * voxel_size.x, y * voxel_size.y, z * voxel_size.z);\r\n            corner += offset;\r\n            vert_densities[z][y][const_x] = DensityFunction(corner);\r\n        }\r\n    }\r\n}\r\n\r\nstatic inline\r\nvoid ScheduleAcrossY(const int const_y, const float3& voxel_size, int num_vertx,\r\n    int num_vertz, float*** vert_densities, const float3& offset, io_service* thread_pool) {\r\n    //\r\n    for(int z = 0; z < num_vertz; z++) {\r\n        for(int x = 0; x < num_vertx; x++) {\r\n            float3 corner(x * voxel_size.x, const_y * voxel_size.y, z * voxel_size.z);\r\n            corner += offset;\r\n            vert_densities[z][const_y][x] = DensityFunction(corner);\r\n        }\r\n    }\r\n}\r\n\r\nstatic inline\r\nvoid ScheduleAcrossZ(const int const_z, const float3& voxel_size, int num_vertx,\r\n    int num_verty, float*** vert_densities,  const float3& offset, io_service* thread_pool) {\r\n    //\r\n    for(int y = 0; y < num_verty; y++) {\r\n        for(int x = 0; x < num_vertx; x++) {\r\n            float3 corner(x * voxel_size.x, y * voxel_size.y, const_z * voxel_size.z);\r\n            corner += offset;\r\n            vert_densities[const_z][y][x] = DensityFunction(corner);\r\n        }\r\n    }\r\n}\r\n\r\nvoid GenerateTerrain(Mesh* mesh, const float3& voxel_size, const int3& num_voxels) {\r\n    cout<<\"About to setup thread pool\"<<endl;\r\n    io_service thread_pool;\r\n    //work object informs thread_pool when work starts and finishes\r\n    //so its run() will not exit while work is being done...keeps it alive\r\n    io_service::work work(thread_pool);\r\n    thread_group threads; //collection of threads that will chip away at tasks in queue\r\n    //need to subtract one because a seperate thread will be calling this. otherwise it would have\r\n    //to wait for a free spot to begin/other way around with these threads needing to wait\r\n    for(int i = 0; i < max(1, (int)thread::hardware_concurrency() - 1); i++) { //add threads to group\r\n        threads.create_thread(bind(&io_service::run, &thread_pool));\r\n    }\r\n\r\n    //offset for centering terrain around camera eye\r\n    int num_vertx = num_voxels.x + 1;\r\n    int num_verty = num_voxels.y + 1;\r\n    int num_vertz = num_voxels.z + 1;\r\n    float3 offset(-num_vertx, -num_verty, -num_vertz);\r\n    offset *= voxel_size;\r\n    offset *= 0.5f;\r\n    offset += cam.eye;\r\n    offset.y = 0; //dont offset in the y direction (so when player is fex +200y still see terrain)\r\n\r\n    //allocate memory for each vertex density - put into dynamic 3D array\r\n    float*** vert_densities;\r\n    vert_densities = new float**[num_vertz];\r\n    //allocate memory for storing vert densities\r\n    for(int z = 0; z < num_vertz; z++) {\r\n        vert_densities[z] = new float*[num_verty];\r\n        for(int y = 0; y < num_verty; y++) {\r\n            vert_densities[z][y] = new float[num_vertx];\r\n        }\r\n    }\r\n\r\n    //allocate memory for edge/vert indices (see below comments)\r\n    int*** xedge_cache = new int**[num_vertz]; //vertex indices for vertex on each x-axis\r\n    int*** yedge_cache = new int**[num_vertz]; //vertex indices for vertex on each y-axis\r\n    int*** zedge_cache = new int**[num_vertz]; //vertex indices for vertex on each z-axis\r\n    //allocate mem\r\n    for(int z = 0; z < num_vertz; z++) {\r\n        xedge_cache[z] = new int*[num_verty];\r\n        yedge_cache[z] = new int*[num_verty];\r\n        zedge_cache[z] = new int*[num_verty];\r\n        for(int y = 0; y < num_verty; y++) {\r\n            xedge_cache[z][y] = new int[num_vertx];\r\n            yedge_cache[z][y] = new int[num_vertx];\r\n            zedge_cache[z][y] = new int[num_vertx];\r\n        }\r\n    }\r\n    //set to no index (-1)\r\n    for(int z = 0; z < num_vertz; z++) {\r\n        for(int y = 0; y < num_verty; y++) {\r\n            for(int x = 0; x < num_vertx; x++) {\r\n                xedge_cache[z][y][x] = -1;\r\n                yedge_cache[z][y][x] = -1;\r\n                zedge_cache[z][y][x] = -1;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout<<\"Enqueueing tasks to thread pool\"<<endl;\r\n    //divide work to each thread\r\n    int max_axis = Max(num_vertx, num_verty, num_vertz); //work divided along this axis\r\n    if(max_axis == 0) { //x\r\n        for(int x = 0; x < num_vertx; x++) {\r\n            thread_pool.post(bind(ScheduleAcrossX, x, voxel_size, num_verty, num_vertz, vert_densities, offset, &thread_pool));\r\n        }\r\n    } else if(max_axis == 1) { //y\r\n        for(int y = 0; y < num_verty; y++) {\r\n            thread_pool.post(bind(ScheduleAcrossY, y, voxel_size, num_vertx, num_vertz, vert_densities, offset, &thread_pool));\r\n        }\r\n    } else { //z\r\n        for(int z = 0; z < num_vertz; z++) {\r\n            thread_pool.post(bind(ScheduleAcrossZ, z, voxel_size, num_vertx, num_verty, vert_densities, offset, &thread_pool));\r\n        }\r\n    }\r\n\r\n    cout<<\"About to wait for thread pool to finish\"<<endl;\r\n    //wait till all threads have been completed. then proceed\r\n    thread_pool.stop();\r\n    threads.join_all();\r\n\r\n    cout<<\"Polygonizing scalar field now\"<<endl;\r\n    //polygonize each voxel\r\n    for(int z = 0; z < num_voxels.z; z++) {\r\n        for(int y = 0; y < num_voxels.y; y++) {\r\n            for(int x = 0; x < num_voxels.x; x++) {\r\n            \t//for each voxel corner\r\n            \tVoxel vox;\r\n            \tfor(int i = 0; i < 8; i++) {\r\n\t                vox.pos[i] = voxel_size * (float3(x, y, z) + RELATIVE_CORNER_POS[i]) + offset;\r\n\t                //vox.density[i] = DensityFunction(vox.pos[i]);\r\n\t                int3 idx = int3(x, y, z) + RELATIVE_CORNER_POS[i];\r\n\t                vox.density[i] = vert_densities[idx.z][idx.y][idx.x];\r\n            \t}\r\n\r\n            \t//polygonize passed voxel with density values at each vertex\r\n            \tTriangulateVoxelData(vox, int3(x, y, z), (const float***)vert_densities, xedge_cache,\r\n                    yedge_cache, zedge_cache, &mesh->triangles, &mesh->vertices, &mesh->normals, &mesh->uvs, num_voxels);\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n    cout<<\"Cleaning up vert density array\"<<endl;\r\n    //clean up 3D vert density array\r\n    for(int z = 0; z < num_vertz; z++) {\r\n        for(int y = 0; y < num_verty; y++) {\r\n            delete[] vert_densities[z][y]; //delete x dyn mem\r\n            delete[] xedge_cache[z][y]; //delete x dyn mem\r\n            delete[] yedge_cache[z][y]; //delete x dyn mem\r\n            delete[] zedge_cache[z][y]; //delete x dyn mem\r\n        }\r\n        delete[] vert_densities[z]; //delete y dyn mem\r\n        delete[] xedge_cache[z]; //delete y dyn mem\r\n        delete[] yedge_cache[z]; //delete y dyn mem\r\n        delete[] zedge_cache[z]; //delete y dyn mem\r\n    }\r\n    delete[] vert_densities;\r\n    delete[] xedge_cache;\r\n    delete[] yedge_cache;\r\n    delete[] zedge_cache;\r\n\r\n    vert_densities = NULL;\r\n    xedge_cache = NULL;\r\n    yedge_cache = NULL;\r\n    zedge_cache = NULL;\r\n\r\n    cout<<\"MC Terrain:\"<<endl;\r\n    cout<<\"\\tNum Tris: \"<<mesh->triangles.size()<<endl;\r\n    cout<<\"\\tNum Verts: \"<<mesh->vertices.size()<<endl;\r\n}\r\n", "meta": {"hexsha": "2cc2e87823665ffde5589aba577a80770ad7ed0d", "size": 17290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "siyana-renderer/src/MarchingCubes.cpp", "max_stars_repo_name": "JVillella/siyana-renderer", "max_stars_repo_head_hexsha": "ebb00cc2a4cc9eaba799b1404a2b33d67fbccf0f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-03-17T14:20:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-08-20T03:32:00.000Z", "max_issues_repo_path": "siyana-renderer/src/MarchingCubes.cpp", "max_issues_repo_name": "JVillella/siyana-renderer", "max_issues_repo_head_hexsha": "ebb00cc2a4cc9eaba799b1404a2b33d67fbccf0f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "siyana-renderer/src/MarchingCubes.cpp", "max_forks_repo_name": "JVillella/siyana-renderer", "max_forks_repo_head_hexsha": "ebb00cc2a4cc9eaba799b1404a2b33d67fbccf0f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.4473007712, "max_line_length": 142, "alphanum_fraction": 0.5766917293, "num_tokens": 5428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041652, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2007652706335074}}
{"text": "/**\n * @file gust.cpp\n *\n * Computes wind gusts\n */\n\n#include <boost/lexical_cast.hpp>\n\n#include \"forecast_time.h\"\n#include \"gust.h\"\n#include \"level.h\"\n#include \"logger.h\"\n#include \"numerical_functions.h\"\n#include \"plugin_factory.h\"\n#include <boost/thread.hpp>\n\n#include \"hitool.h\"\n#include \"neons.h\"\n#include \"radon.h\"\n#include <NFmiLocation.h>\n#include <NFmiMetTime.h>\n\nusing namespace std;\nusing namespace himan;\nusing namespace himan::plugin;\n\nstruct deltaT\n{\n\tvector<double> deltaT_100;\n\tvector<double> deltaT_200;\n\tvector<double> deltaT_300;\n\tvector<double> deltaT_400;\n\tvector<double> deltaT_500;\n\tvector<double> deltaT_600;\n\tvector<double> deltaT_700;\n\n\tdeltaT() {}\n};\n\nstruct deltaTot\n{\n\tvector<double> deltaTot_100;\n\tvector<double> deltaTot_200;\n\tvector<double> deltaTot_300;\n\tvector<double> deltaTot_400;\n\tvector<double> deltaTot_500;\n\tvector<double> deltaTot_600;\n\tvector<double> deltaTot_700;\n\n\tdeltaTot() {}\n};\n\nstruct intT\n{\n\tvector<double> intT_100;\n\tvector<double> intT_200;\n\tvector<double> intT_300;\n\tvector<double> intT_400;\n\tvector<double> intT_500;\n\tvector<double> intT_600;\n\tvector<double> intT_700;\n\n\tintT() {}\n};\n\nstruct intTot\n{\n\tvector<double> intTot_100;\n\tvector<double> intTot_200;\n\tvector<double> intTot_300;\n\tvector<double> intTot_400;\n\tvector<double> intTot_500;\n\tvector<double> intTot_600;\n\tvector<double> intTot_700;\n\n\tintTot() {}\n};\n\nvoid DeltaT(shared_ptr<const plugin_configuration> conf, info_t T_lowestLevel, const forecast_time& ftime,\n            const forecast_type& ftype, size_t gridSize, deltaT& dT);\nvoid DeltaTot(deltaTot& dTot, info_t T_lowestLevel, size_t gridSize);\nvoid IntT(intT& iT, const deltaT& dT, size_t gridSize);\nvoid IntTot(intTot& iTot, const deltaTot& dTot, size_t gridSize);\nvoid LowAndMiddleClouds(vector<double>& lowAndMiddleClouds, info_t lowClouds, info_t middleClouds, info_t highClouds,\n                        info_t totalClouds);\n\ngust::gust() { itsLogger = logger(\"gust\"); }\nvoid gust::Process(std::shared_ptr<const plugin_configuration> conf)\n{\n\tInit(conf);\n\n\tparam theRequestedParam(\"FFG2-MS\", 417, 0, 2, 22);\n\n\ttheRequestedParam.Unit(kMs);\n\n\tSetParams({theRequestedParam});\n\n\tStart();\n}\n\n/*\n * Calculate()\n\n * This function does the actual calculation.\n */\n\nvoid gust::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)\n{\n\tNFmiMetTime theTime(boost::lexical_cast<short>(myTargetInfo->Time().ValidDateTime().String(\"%Y\")),\n\t                    boost::lexical_cast<short>(myTargetInfo->Time().ValidDateTime().String(\"%m\")),\n\t                    boost::lexical_cast<short>(myTargetInfo->Time().ValidDateTime().String(\"%d\")),\n\t                    boost::lexical_cast<short>(myTargetInfo->Time().ValidDateTime().String(\"%H\")),\n\t                    boost::lexical_cast<short>(myTargetInfo->Time().ValidDateTime().String(\"%M\")));\n\n\tauto myThreadedLogger = logger(\"gust_pluginThread #\" + boost::lexical_cast<string>(threadIndex));\n\n\t/*\n\t * Required source parameters\n\t *\n\t */\n\tconst size_t gridSize = myTargetInfo->Grid()->Size();\n\n\tconst param BLHParam(\"MIXHGT-M\");                                     // boundary layer height\n\tconst param WSParam(\"FF-MS\");                                         // wind speed\n\tconst param GustParam(\"FFG-MS\");                                      // wind gust\n\tconst param TParam(\"T-K\");                                            // temperature\n\tconst param TopoParam(\"Z-M2S2\");                                      // geopotential height\n\tconst params LowCloudParam = {param(\"NL-PRCNT\"), param(\"NL-0TO1\")};   // low cloud cover\n\tconst params MidCloudParam = {param(\"NM-PRCNT\"), param(\"NM-0TO1\")};   // middle cloud cover\n\tconst params HighCloudParam = {param(\"NH-PRCNT\"), param(\"NH-0TO1\")};  // high cloud cover\n\tconst params TotalCloudParam = {param(\"N-PRCNT\"), param(\"N-0TO1\")};   // total cloud cover\n\n\tlevel H0, H10;\n\n\tproducer prod = itsConfiguration->SourceProducer(0);\n\n\tHPDatabaseType dbtype = itsConfiguration->DatabaseType();\n\n\tlong lowestHybridLevelNumber = kHPMissingInt;\n\n\tif (dbtype == kNeons || dbtype == kNeonsAndRadon)\n\t{\n\t\tauto n = GET_PLUGIN(neons);\n\n\t\tlowestHybridLevelNumber = boost::lexical_cast<long>(n->ProducerMetaData(prod.Id(), \"last hybrid level number\"));\n\t}\n\n\tif ((dbtype == kRadon || dbtype == kNeonsAndRadon) && lowestHybridLevelNumber == kHPMissingInt)\n\t{\n\t\tauto r = GET_PLUGIN(radon);\n\n\t\tlowestHybridLevelNumber =\n\t\t    boost::lexical_cast<long>(r->RadonDB().GetProducerMetaData(prod.Id(), \"last hybrid level number\"));\n\t}\n\n\tassert(lowestHybridLevelNumber != kHPMissingInt);\n\n\tlevel lowestHybridLevel(kHybrid, lowestHybridLevelNumber);\n\n\tif (myTargetInfo->Producer().Id() == 240 || myTargetInfo->Producer().Id() == 243)\n\t{\n\t\tH0 = level(kGround, 0);\n\t\tH10 = H0;\n\t}\n\telse\n\t{\n\t\tH0 = level(kHeight, 0);\n\t\tH10 = level(kHeight, 10);\n\t}\n\n\tinfo_t GustInfo, T_LowestLevelInfo, BLHInfo, TopoInfo, LCloudInfo, MCloudInfo, HCloudInfo, TCloudInfo;\n\n\t// Current time and level\n\n\tforecast_time forecastTime = myTargetInfo->Time();\n\tlevel forecastLevel = myTargetInfo->Level();\n\tforecast_type forecastType = myTargetInfo->ForecastType();\n\n\tGustInfo = Fetch(forecastTime, H10, GustParam, forecastType, false);\n\tT_LowestLevelInfo = Fetch(forecastTime, lowestHybridLevel, TParam, forecastType, false);\n\tBLHInfo = Fetch(forecastTime, H0, BLHParam, forecastType, false);\n\tTopoInfo = Fetch(forecastTime, H0, TopoParam, forecastType, false);\n\tLCloudInfo = Fetch(forecastTime, H0, LowCloudParam, forecastType, false);\n\tMCloudInfo = Fetch(forecastTime, H0, MidCloudParam, forecastType, false);\n\tHCloudInfo = Fetch(forecastTime, H0, HighCloudParam, forecastType, false);\n\tTCloudInfo = Fetch(forecastTime, H0, TotalCloudParam, forecastType, false);\n\n\tif (!GustInfo || !T_LowestLevelInfo || !LCloudInfo || !MCloudInfo || !HCloudInfo || !TCloudInfo)\n\t{\n\t\titsLogger.Error(\"Unable to find all source data\");\n\t\treturn;\n\t}\n\n\tdeltaT dT;\n\tvector<double> lowAndMiddleClouds(gridSize, kFloatMissing);\n\n\tboost::thread t(&DeltaT, itsConfiguration, T_LowestLevelInfo, forecastTime, forecastType, gridSize, boost::ref(dT));\n\tboost::thread t2(&LowAndMiddleClouds, boost::ref(lowAndMiddleClouds), LCloudInfo, MCloudInfo, HCloudInfo,\n\t                 TCloudInfo);\n\n\t// calc boundary layer height\n\tvector<double> z_boundaryl(gridSize, kFloatMissing);\n\tvector<double> z_one_third_boundaryl(gridSize, kFloatMissing);\n\tvector<double> z_two_third_boundaryl(gridSize, kFloatMissing);\n\tvector<double> z_zero(gridSize, 0);\n\tfor (size_t i = 0; i < gridSize; ++i)\n\t{\n\t\tif (BLHInfo->Data()[i] == kFloatMissing)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tz_boundaryl[i] = BLHInfo->Data()[i];\n\n\t\tif (BLHInfo->Data()[i] >= 200)\n\t\t{\n\t\t\tz_boundaryl[i] = 0.5 * BLHInfo->Data()[i] + 100;\n\n\t\t\tif (BLHInfo->Data()[i] > 1200)\n\t\t\t{\n\t\t\t\tz_boundaryl[i] = 700;\n\t\t\t}\n\t\t}\n\n\t\tz_one_third_boundaryl[i] = z_boundaryl[i] / 3;\n\t\tz_two_third_boundaryl[i] = 2 * z_one_third_boundaryl[i];\n\t}\n\n\t// maybe need adjusting\n\tauto h = GET_PLUGIN(hitool);\n\n\th->Configuration(itsConfiguration);\n\th->Time(forecastTime);\n\th->ForecastType(forecastType);\n\n\tvector<double> maxEstimate;\n\ttry\n\t{\n\t\tmaxEstimate = h->VerticalAverage(WSParam, z_two_third_boundaryl, z_boundaryl);\n\t}\n\n\tcatch (const HPExceptionType& e)\n\t{\n\t\tif (e != kFileDataNotFound)\n\t\t{\n\t\t\tthrow runtime_error(\"Caught exception \" + boost::lexical_cast<string>(e));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmyThreadedLogger.Error(\"hitool was unable to find data\");\n\t\t\tt.join();\n\t\t\tt2.join();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tvector<double> BLtop_ws;\n\ttry\n\t{\n\t\tBLtop_ws = h->VerticalAverage(WSParam, z_one_third_boundaryl, z_boundaryl);\n\t}\n\n\tcatch (const HPExceptionType& e)\n\t{\n\t\tif (e != kFileDataNotFound)\n\t\t{\n\t\t\tthrow runtime_error(\"Caught exception \" + boost::lexical_cast<string>(e));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmyThreadedLogger.Error(\"hitool was unable to find data\");\n\t\t\tt.join();\n\t\t\tt2.join();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tvector<double> meanWind;\n\ttry\n\t{\n\t\tmeanWind = h->VerticalAverage(WSParam, z_zero, z_boundaryl);\n\t}\n\n\tcatch (const HPExceptionType& e)\n\t{\n\t\tif (e != kFileDataNotFound)\n\t\t{\n\t\t\tthrow runtime_error(\"Caught exception \" + boost::lexical_cast<string>(e));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmyThreadedLogger.Error(\"hitool was unable to find data\");\n\t\t\tt.join();\n\t\t\tt2.join();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tvector<double> t_diff;\n\ttry\n\t{\n\t\tt_diff = h->VerticalMaximum(TParam, 0, 200);\n\t\tfor (size_t i = 0; i < gridSize; ++i)\n\t\t{\n\t\t\tt_diff[i] = t_diff[i] - T_LowestLevelInfo->Data()[i];\n\t\t}\n\t}\n\n\tcatch (const HPExceptionType& e)\n\t{\n\t\tif (e != kFileDataNotFound)\n\t\t{\n\t\t\tthrow runtime_error(\"Caught exception \" + boost::lexical_cast<string>(e));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmyThreadedLogger.Error(\"hitool was unable to find data\");\n\t\t\tt.join();\n\t\t\tt2.join();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tvector<double> BLbottom_ws;\n\ttry\n\t{\n\t\tBLbottom_ws = h->VerticalAverage(WSParam, 0, 200);\n\t}\n\n\tcatch (const HPExceptionType& e)\n\t{\n\t\tif (e != kFileDataNotFound)\n\t\t{\n\t\t\tthrow runtime_error(\"Caught exception \" + boost::lexical_cast<string>(e));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmyThreadedLogger.Error(\"hitool was unable to find data\");\n\t\t\tt.join();\n\t\t\tt2.join();\n\t\t\treturn;\n\t\t}\n\t}\n\n\tt.join();\n\tt2.join();\n\n\tdeltaTot dTot;\n\tintT iT;\n\tintTot iTot;\n\n\tDeltaTot(dTot, T_LowestLevelInfo, gridSize);\n\tIntT(iT, dT, gridSize);\n\tIntTot(iTot, dTot, gridSize);\n\n\tstring deviceType = \"CPU\";\n\n\tLOCKSTEP(myTargetInfo, GustInfo, T_LowestLevelInfo, TopoInfo, BLHInfo, LCloudInfo, MCloudInfo)\n\t{\n\t\tsize_t i = myTargetInfo->LocationIndex();\n\n\t\tdouble topo = TopoInfo->Value();\n\t\tdouble esto = kFloatMissing;\n\t\tdouble esto_tot = kFloatMissing;\n\t\tdouble gust = kFloatMissing;\n\t\tdouble turb_lisa = 0;\n\t\tdouble turb_kerroin = 0;\n\t\tdouble pilvikerroin = 0;\n\t\tdouble cloudCover = (LCloudInfo->Value() + MCloudInfo->Value()) * 100;\n\t\ttopo *= himan::constants::kIg;\n\n\t\tNFmiLocation theLocation(myTargetInfo->LatLon().X(), myTargetInfo->LatLon().Y());\n\t\tdouble elevationAngle = theLocation.ElevationAngle(theTime);\n\n\t\t/* Calculations go here */\n\n\t\tif (z_boundaryl[i] >= 200)\n\t\t{\n\t\t\testo = iT.intT_100[i] + iT.intT_200[i];\n\t\t\testo_tot = iTot.intTot_100[i] + iTot.intTot_200[i];\n\t\t}\n\n\t\tif (z_boundaryl[i] >= 300)\n\t\t{\n\t\t\testo = iT.intT_100[i] + iT.intT_200[i] + iT.intT_300[i];\n\t\t\testo_tot = iTot.intTot_100[i] + iTot.intTot_200[i] + iTot.intTot_300[i];\n\t\t}\n\n\t\tif (z_boundaryl[i] >= 400)\n\t\t{\n\t\t\testo = iT.intT_100[i] + iT.intT_200[i] + iT.intT_300[i] + iT.intT_400[i];\n\t\t\testo_tot = iTot.intTot_100[i] + iTot.intTot_200[i] + iTot.intTot_300[i] + iTot.intTot_400[i];\n\t\t}\n\n\t\tif (z_boundaryl[i] >= 500)\n\t\t{\n\t\t\testo = iT.intT_100[i] + iT.intT_200[i] + iT.intT_300[i] + iT.intT_400[i] + iT.intT_500[i];\n\t\t\testo_tot =\n\t\t\t    iTot.intTot_100[i] + iTot.intTot_200[i] + iTot.intTot_300[i] + iTot.intTot_400[i] + iTot.intTot_500[i];\n\t\t}\n\n\t\tif (z_boundaryl[i] >= 600)\n\t\t{\n\t\t\testo = iT.intT_100[i] + iT.intT_200[i] + iT.intT_300[i] + iT.intT_400[i] + iT.intT_500[i] + iT.intT_600[i];\n\t\t\testo_tot = iTot.intTot_100[i] + iTot.intTot_200[i] + iTot.intTot_300[i] + iTot.intTot_400[i] +\n\t\t\t           iTot.intTot_500[i] + iTot.intTot_600[i];\n\t\t}\n\n\t\tif (z_boundaryl[i] == 700)\n\t\t{\n\t\t\testo = iT.intT_100[i] + iT.intT_200[i] + iT.intT_300[i] + iT.intT_400[i] + iT.intT_500[i] + iT.intT_600[i] +\n\t\t\t       iT.intT_700[i];\n\t\t\testo_tot = iTot.intTot_100[i] + iTot.intTot_200[i] + iTot.intTot_300[i] + iTot.intTot_400[i] +\n\t\t\t           iTot.intTot_500[i] + iTot.intTot_600[i] + iTot.intTot_700[i];\n\t\t}\n\n\t\tif (z_boundaryl[i] >= 200 && esto >= 0 && esto <= esto_tot)\n\t\t{\n\t\t\tgust = ((BLbottom_ws[i] - BLtop_ws[i]) / esto_tot) * esto + BLtop_ws[i];\n\t\t}\n\n\t\tif (z_boundaryl[i] >= 200 && esto <= 0 && esto >= -200)\n\t\t{\n\t\t\tgust = ((BLtop_ws[i] - maxEstimate[i]) / 200) * esto + BLtop_ws[i];\n\t\t}\n\n\t\tif (z_boundaryl[i] >= 200 && esto < -200)\n\t\t{\n\t\t\tgust = maxEstimate[i];\n\t\t}\n\n\t\tif (z_boundaryl[i] >= 200 && esto > esto_tot)\n\t\t{\n\t\t\tgust = BLbottom_ws[i];\n\t\t}\n\n\t\tif (z_boundaryl[i] < 200)\n\t\t{\n\t\t\tgust = meanWind[i];\n\t\t}\n\n\t\tif (gust == kFloatMissing || gust < 1)\n\t\t{\n\t\t\tgust = 1;\n\t\t}\n\n\t\tif (topo > 15 && topo < 400 && t_diff[i] > 0 && t_diff[i] <= 4 && BLbottom_ws[i] < 7 && elevationAngle < 15)\n\t\t{\n\t\t\tgust = ((1 - gust) / 4) * t_diff[i] + gust;\n\t\t}\n\n\t\tif (topo > 15 && topo < 400 && t_diff[i] > 4 && BLbottom_ws[i] < 7)\n\t\t{\n\t\t\tgust = 1;\n\t\t}\n\n\t\tif (cloudCover >= 30 && cloudCover <= 70)\n\t\t{\n\t\t\tpilvikerroin = -0.025 * cloudCover + 1.75;\n\t\t}\n\n\t\tif (cloudCover < 30)\n\t\t{\n\t\t\tpilvikerroin = 1;\n\t\t}\n\n\t\tif (elevationAngle >= 20 && topo > 10 && z_boundaryl[i] >= 200 && esto < 0)\n\t\t{\n\t\t\tturb_lisa = 0.133333333 * elevationAngle - 2.666666667;\n\n\t\t\tif (elevationAngle > 50)\n\t\t\t{\n\t\t\t\tturb_lisa = 4;\n\t\t\t}\n\n\t\t\tif (gust > 4 && gust <= 14)\n\t\t\t{\n\t\t\t\tturb_kerroin = -0.1 * gust + 1.4;\n\t\t\t}\n\n\t\t\tif (gust <= 4)\n\t\t\t{\n\t\t\t\tturb_kerroin = 1;\n\t\t\t}\n\t\t}\n\n\t\tgust = gust + turb_lisa * turb_kerroin * pilvikerroin;\n\n\t\tif (topo > 400 || T_LowestLevelInfo->Value() == kFloatMissing || BLHInfo->Value() == kFloatMissing)\n\t\t{\n\t\t\tgust = GustInfo->Value() * 0.95;\n\t\t}\n\n\t\tmyTargetInfo->Value(gust);\n\t}\n\n\thiman::matrix<double> filter_kernel(3, 3, 1, kFloatMissing);\n\tfilter_kernel.Fill(1.0 / 9.0);\n\thiman::matrix<double> gust_filtered = numerical_functions::Filter2D(myTargetInfo->Data(), filter_kernel);\n\n\tmyTargetInfo->Grid()->Data(gust_filtered);\n\n\tmyThreadedLogger.Info(\"[\" + deviceType + \"] Missing values: \" +\n\t\t\t\t\t\t  boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + \"/\" +\n\t\t\t\t\t\t  boost::lexical_cast<string>(myTargetInfo->Data().Size()));\n}\n\nvoid DeltaT(shared_ptr<const plugin_configuration> conf, info_t T_lowestLevel, const forecast_time& ftime,\n            const forecast_type& ftype, size_t gridSize, deltaT& dT)\n{\n\tauto h = GET_PLUGIN(hitool);\n\n\th->Configuration(conf);\n\th->Time(ftime);\n\th->ForecastType(ftype);\n\n\tconst param TParam(\"T-K\");\n\n\ttry\n\t{\n\t\t// Potential temperature differences\n\t\tdT.deltaT_100 = h->VerticalValue(TParam, 100);\n\t\tdT.deltaT_200 = h->VerticalValue(TParam, 200);\n\t\tdT.deltaT_300 = h->VerticalValue(TParam, 300);\n\t\tdT.deltaT_400 = h->VerticalValue(TParam, 400);\n\t\tdT.deltaT_500 = h->VerticalValue(TParam, 500);\n\t\tdT.deltaT_600 = h->VerticalValue(TParam, 600);\n\t\tdT.deltaT_700 = h->VerticalValue(TParam, 700);\n\n\t\tfor (size_t i = 0; i < gridSize; ++i)\n\t\t{\n\t\t\tif (T_lowestLevel->Data()[i] == himan::kFloatMissing)\n\t\t\t{\n\t\t\t\tdT.deltaT_100[i] = himan::kFloatMissing;\n\t\t\t\tdT.deltaT_200[i] = himan::kFloatMissing;\n\t\t\t\tdT.deltaT_300[i] = himan::kFloatMissing;\n\t\t\t\tdT.deltaT_400[i] = himan::kFloatMissing;\n\t\t\t\tdT.deltaT_500[i] = himan::kFloatMissing;\n\t\t\t\tdT.deltaT_600[i] = himan::kFloatMissing;\n\t\t\t\tdT.deltaT_700[i] = himan::kFloatMissing;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (dT.deltaT_100[i] != himan::kFloatMissing)\n\t\t\t\tdT.deltaT_100[i] -= T_lowestLevel->Data()[i] + 9.8 * (0.010 - (100.0 / 1000.0));\n\t\t\tif (dT.deltaT_200[i] != himan::kFloatMissing)\n\t\t\t\tdT.deltaT_200[i] -= T_lowestLevel->Data()[i] + 9.8 * (0.010 - (200.0 / 1000.0));\n\t\t\tif (dT.deltaT_300[i] != himan::kFloatMissing)\n\t\t\t\tdT.deltaT_300[i] -= T_lowestLevel->Data()[i] + 9.8 * (0.010 - (300.0 / 1000.0));\n\t\t\tif (dT.deltaT_400[i] != himan::kFloatMissing)\n\t\t\t\tdT.deltaT_400[i] -= T_lowestLevel->Data()[i] + 9.8 * (0.010 - (400.0 / 1000.0));\n\t\t\tif (dT.deltaT_500[i] != himan::kFloatMissing)\n\t\t\t\tdT.deltaT_500[i] -= T_lowestLevel->Data()[i] + 9.8 * (0.010 - (500.0 / 1000.0));\n\t\t\tif (dT.deltaT_600[i] != himan::kFloatMissing)\n\t\t\t\tdT.deltaT_600[i] -= T_lowestLevel->Data()[i] + 9.8 * (0.010 - (600.0 / 1000.0));\n\t\t\tif (dT.deltaT_700[i] != himan::kFloatMissing)\n\t\t\t\tdT.deltaT_700[i] -= T_lowestLevel->Data()[i] + 9.8 * (0.010 - (700.0 / 1000.0));\n\t\t}\n\t}\n\tcatch (const HPExceptionType& e)\n\t{\n\t\tif (e != kFileDataNotFound)\n\t\t{\n\t\t\tthrow runtime_error(\"DeltaT() caught exception \" + boost::lexical_cast<string>(e));\n\t\t}\n\t}\n}\n\nvoid DeltaTot(deltaTot& dTot, info_t T_lowestLevel, size_t gridSize)\n{\n\tdTot.deltaTot_100 = vector<double>(gridSize, 0);\n\tdTot.deltaTot_200 = vector<double>(gridSize, 0);\n\tdTot.deltaTot_300 = vector<double>(gridSize, 0);\n\tdTot.deltaTot_400 = vector<double>(gridSize, 0);\n\tdTot.deltaTot_500 = vector<double>(gridSize, 0);\n\tdTot.deltaTot_600 = vector<double>(gridSize, 0);\n\tdTot.deltaTot_700 = vector<double>(gridSize, 0);\n\n\tfor (size_t i = 0; i < gridSize; ++i)\n\t{\n\t\tdTot.deltaTot_100[i] =\n\t\t    (T_lowestLevel->Data()[i] + 6 * (0.010 - (100.0 / 1000.0))) -\n\t\t    (T_lowestLevel->Data()[i] + 9.8 * (0.010 - (100.0 / 1000.0)));  // => -3.8*(0.010-(100/1000)) ???\n\t\tdTot.deltaTot_200[i] =\n\t\t    (T_lowestLevel->Data()[i] + 6 * (0.010 - (200.0 / 1000.0))) -\n\t\t    (T_lowestLevel->Data()[i] + 9.8 * (0.010 - (200.0 / 1000.0)));  // => -3.8*(0.010-(200/1000))\n\t\tdTot.deltaTot_300[i] = (T_lowestLevel->Data()[i] + 6 * (0.010 - (300.0 / 1000.0))) -\n\t\t                       (T_lowestLevel->Data()[i] + 9.8 * (0.010 - (300.0 / 1000.0)));  // ... etc.\n\t\tdTot.deltaTot_400[i] = (T_lowestLevel->Data()[i] + 6 * (0.010 - (400.0 / 1000.0))) -\n\t\t                       (T_lowestLevel->Data()[i] + 9.8 * (0.010 - (400.0 / 1000.0)));\n\t\tdTot.deltaTot_500[i] = (T_lowestLevel->Data()[i] + 6 * (0.010 - (500.0 / 1000.0))) -\n\t\t                       (T_lowestLevel->Data()[i] + 9.8 * (0.010 - (500.0 / 1000.0)));\n\t\tdTot.deltaTot_600[i] = (T_lowestLevel->Data()[i] + 6 * (0.010 - (600.0 / 1000.0))) -\n\t\t                       (T_lowestLevel->Data()[i] + 9.8 * (0.010 - (600.0 / 1000.0)));\n\t\tdTot.deltaTot_700[i] = (T_lowestLevel->Data()[i] + 6 * (0.010 - (700.0 / 1000.0))) -\n\t\t                       (T_lowestLevel->Data()[i] + 9.8 * (0.010 - (700.0 / 1000.0)));\n\t}\n}\n\nvoid IntT(intT& iT, const deltaT& dT, size_t gridSize)\n{\n\tiT.intT_100 = vector<double>(gridSize, himan::kFloatMissing);\n\tiT.intT_200 = vector<double>(gridSize, himan::kFloatMissing);\n\tiT.intT_300 = vector<double>(gridSize, himan::kFloatMissing);\n\tiT.intT_400 = vector<double>(gridSize, himan::kFloatMissing);\n\tiT.intT_500 = vector<double>(gridSize, himan::kFloatMissing);\n\tiT.intT_600 = vector<double>(gridSize, himan::kFloatMissing);\n\tiT.intT_700 = vector<double>(gridSize, himan::kFloatMissing);\n\n\tfor (size_t i = 0; i < gridSize; ++i)\n\t{\n\t\tif (dT.deltaT_100[i] != himan::kFloatMissing)\n\t\t\tiT.intT_100[i] = 0.5 * dT.deltaT_100[i] * 100;  // why 0.5 * here? Would make sense in case of\n\t\t                                                    // (dT.deltaT_100[i] + dT.deltaT_0[i]) if this is\n\t\t                                                    // integration using trapezoidal rule\n\t\tif (dT.deltaT_100[i] != himan::kFloatMissing && dT.deltaT_200[i] != himan::kFloatMissing)\n\t\t\tiT.intT_200[i] = 0.5 * (dT.deltaT_200[i] + dT.deltaT_100[i]) * 100;\n\t\tif (dT.deltaT_200[i] != himan::kFloatMissing && dT.deltaT_300[i] != himan::kFloatMissing)\n\t\t\tiT.intT_300[i] = 0.5 * (dT.deltaT_300[i] + dT.deltaT_200[i]) * 100;\n\t\tif (dT.deltaT_300[i] != himan::kFloatMissing && dT.deltaT_400[i] != himan::kFloatMissing)\n\t\t\tiT.intT_400[i] = 0.5 * (dT.deltaT_400[i] + dT.deltaT_300[i]) * 100;\n\t\tif (dT.deltaT_400[i] != himan::kFloatMissing && dT.deltaT_500[i] != himan::kFloatMissing)\n\t\t\tiT.intT_500[i] = 0.5 * (dT.deltaT_500[i] + dT.deltaT_400[i]) * 100;\n\t\tif (dT.deltaT_500[i] != himan::kFloatMissing && dT.deltaT_600[i] != himan::kFloatMissing)\n\t\t\tiT.intT_600[i] = 0.5 * (dT.deltaT_600[i] + dT.deltaT_500[i]) * 100;\n\t\tif (dT.deltaT_600[i] != himan::kFloatMissing && dT.deltaT_700[i] != himan::kFloatMissing)\n\t\t\tiT.intT_700[i] = 0.5 * (dT.deltaT_700[i] + dT.deltaT_600[i]) * 100;\n\t}\n}\n\nvoid IntTot(intTot& iTot, const deltaTot& dTot, size_t gridSize)\n{\n\tiTot.intTot_100 = vector<double>(gridSize, 0);\n\tiTot.intTot_200 = vector<double>(gridSize, 0);\n\tiTot.intTot_300 = vector<double>(gridSize, 0);\n\tiTot.intTot_400 = vector<double>(gridSize, 0);\n\tiTot.intTot_500 = vector<double>(gridSize, 0);\n\tiTot.intTot_600 = vector<double>(gridSize, 0);\n\tiTot.intTot_700 = vector<double>(gridSize, 0);\n\n\tfor (size_t i = 0; i < gridSize; ++i)\n\t{\n\t\tiTot.intTot_100[i] = 0.5 * dTot.deltaTot_100[i] * 100;  // 0.5 * ???\n\t\tiTot.intTot_200[i] = 0.5 * (dTot.deltaTot_200[i] + dTot.deltaTot_100[i]) * 100;\n\t\tiTot.intTot_300[i] = 0.5 * (dTot.deltaTot_300[i] + dTot.deltaTot_200[i]) * 100;\n\t\tiTot.intTot_400[i] = 0.5 * (dTot.deltaTot_400[i] + dTot.deltaTot_300[i]) * 100;\n\t\tiTot.intTot_500[i] = 0.5 * (dTot.deltaTot_500[i] + dTot.deltaTot_400[i]) * 100;\n\t\tiTot.intTot_600[i] = 0.5 * (dTot.deltaTot_600[i] + dTot.deltaTot_500[i]) * 100;\n\t\tiTot.intTot_700[i] = 0.5 * (dTot.deltaTot_700[i] + dTot.deltaTot_600[i]) * 100;\n\t}\n}\n\nvoid LowAndMiddleClouds(vector<double>& lowAndMiddleClouds, info_t lowClouds, info_t middleClouds, info_t highClouds,\n                        info_t totalClouds)\n{\n\tfor (size_t i = 0; i < lowAndMiddleClouds.size(); ++i)\n\t{\n\t\tif (highClouds->Data()[i] == himan::kFloatMissing || highClouds->Data()[i] == 0.0)\n\t\t{\n\t\t\tif (totalClouds->Data()[i] == himan::kFloatMissing)\n\t\t\t\tlowAndMiddleClouds[i] = himan::kFloatMissing;\n\t\t\telse\n\t\t\t\tlowAndMiddleClouds[i] = totalClouds->Data()[i] * 100;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (lowClouds->Data()[i] != himan::kFloatMissing)\n\t\t\t{\n\t\t\t\tif (middleClouds->Data()[i] != himan::kFloatMissing)\n\t\t\t\t\tlowAndMiddleClouds[i] = max(lowClouds->Data()[i], middleClouds->Data()[i]) * 100;\n\t\t\t\telse\n\t\t\t\t\tlowAndMiddleClouds[i] = lowClouds->Data()[i] * 100;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (middleClouds->Data()[i] == himan::kFloatMissing)\n\t\t\t\t\tlowAndMiddleClouds[i] = himan::kFloatMissing;\n\t\t\t\telse\n\t\t\t\t\tlowAndMiddleClouds[i] = middleClouds->Data()[i] * 100;\n\t\t\t}\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "4f38c1a8a8fcb57cc8496323855d50e24b6e181d", "size": 21118, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "himan-plugins/source/gust.cpp", "max_stars_repo_name": "jrintala/fmi-data", "max_stars_repo_head_hexsha": "625f0a44919e6406440349425ee0b3f1a64a923d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "himan-plugins/source/gust.cpp", "max_issues_repo_name": "jrintala/fmi-data", "max_issues_repo_head_hexsha": "625f0a44919e6406440349425ee0b3f1a64a923d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "himan-plugins/source/gust.cpp", "max_forks_repo_name": "jrintala/fmi-data", "max_forks_repo_head_hexsha": "625f0a44919e6406440349425ee0b3f1a64a923d", "max_forks_repo_licenses": ["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.9194729136, "max_line_length": 117, "alphanum_fraction": 0.6450421441, "num_tokens": 7232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583269796369904, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.20064270541858462}}
{"text": "/**\n *    Copyright (C) 2015 MongoDB, Inc.\n *\n *    This program is free software: you can redistribute it and/or  modify\n *    it under the terms of the GNU Affero General Public License, version 3,\n *    as published by the Free Software Foundation.\n *\n *    This program is distributed in the hope that it will be useful,\n *    but WITHOUT ANY WARRANTY; without even the implied warranty of\n *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *    GNU Affero General Public License for more details.\n *\n *    You should have received a copy of the GNU Affero General Public License\n *    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n *    As a special exception, the copyright holders give permission to link the\n *    code of portions of this program with the OpenSSL library under certain\n *    conditions as described in each individual source file and distribute\n *    linked combinations including the program with the OpenSSL library. You\n *    must comply with the GNU Affero General Public License in all respects for\n *    all of the code used other than as permitted herein. If you modify file(s)\n *    with this exception, you may extend this exception to your version of the\n *    file(s), but you are not obligated to do so. If you do not wish to do so,\n *    delete this exception statement from your version. If you delete this\n *    exception statement from all source files in the program, then also delete\n *    it in the license file.\n */\n\n#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kQuery\n\n#include \"mongo/platform/basic.h\"\n\n#include \"mongo/db/pipeline/document_source_sample_from_random_cursor.h\"\n\n#include <boost/math/distributions/beta.hpp>\n\n#include \"mongo/db/client.h\"\n#include \"mongo/db/pipeline/document.h\"\n#include \"mongo/db/pipeline/expression.h\"\n#include \"mongo/db/pipeline/expression_context.h\"\n#include \"mongo/db/pipeline/value.h\"\n#include \"mongo/util/log.h\"\n\nnamespace mongo {\nusing boost::intrusive_ptr;\n\nDocumentSourceSampleFromRandomCursor::DocumentSourceSampleFromRandomCursor(\n    const intrusive_ptr<ExpressionContext>& pExpCtx,\n    long long size,\n    std::string idField,\n    long long nDocsInCollection)\n    : DocumentSource(pExpCtx),\n      _size(size),\n      _idField(std::move(idField)),\n      _seenDocs(pExpCtx->getValueComparator().makeUnorderedValueSet()),\n      _nDocsInColl(nDocsInCollection) {}\n\nconst char* DocumentSourceSampleFromRandomCursor::getSourceName() const {\n    return \"$sampleFromRandomCursor\";\n}\n\nnamespace {\n/**\n * Select a random value drawn according to the distribution Beta(alpha=1, beta=N). The kth smallest\n * value of a sample of size N from a Uniform(0, 1) distribution has a Beta(k, N + 1 - k)\n * distribution, so the return value represents the smallest value from such a sample. This is also\n * the expected distance between the values drawn from a uniform distribution, which is how it is\n * being used here.\n */\ndouble smallestFromSampleOfUniform(PseudoRandom* prng, size_t N) {\n    boost::math::beta_distribution<double> betaDist(1.0, static_cast<double>(N));\n    double p = prng->nextCanonicalDouble();\n    return boost::math::quantile(betaDist, p);\n}\n}  // namespace\n\nDocumentSource::GetNextResult DocumentSourceSampleFromRandomCursor::getNext() {\n    pExpCtx->checkForInterrupt();\n\n    if (_seenDocs.size() >= static_cast<size_t>(_size))\n        return GetNextResult::makeEOF();\n\n    auto nextResult = getNextNonDuplicateDocument();\n    if (!nextResult.isAdvanced()) {\n        return nextResult;\n    }\n\n    // Assign it a random value to enable merging by random value, attempting to avoid bias in that\n    // process.\n    auto& prng = pExpCtx->opCtx->getClient()->getPrng();\n    _randMetaFieldVal -= smallestFromSampleOfUniform(&prng, _nDocsInColl);\n\n    MutableDocument md(nextResult.releaseDocument());\n    md.setRandMetaField(_randMetaFieldVal);\n    if (pExpCtx->needsMerge) {\n        // This stage will be merged by sorting results according to this random metadata field, but\n        // the merging logic expects to sort by the sort key metadata.\n        md.setSortKeyMetaField(BSON(\"\" << _randMetaFieldVal));\n    }\n    return md.freeze();\n}\n\nDocumentSource::GetNextResult DocumentSourceSampleFromRandomCursor::getNextNonDuplicateDocument() {\n    // We may get duplicate documents back from the random cursor, and should not return duplicate\n    // documents, so keep trying until we get a new one.\n    const int kMaxAttempts = 100;\n    for (int i = 0; i < kMaxAttempts; ++i) {\n        auto nextInput = pSource->getNext();\n        switch (nextInput.getStatus()) {\n            case GetNextResult::ReturnStatus::kAdvanced: {\n                auto idField = nextInput.getDocument()[_idField];\n                uassert(28793,\n                        str::stream()\n                            << \"The optimized $sample stage requires all documents have a \"\n                            << _idField\n                            << \" field in order to de-duplicate results, but encountered a \"\n                               \"document without a \"\n                            << _idField\n                            << \" field: \"\n                            << nextInput.getDocument().toString(),\n                        !idField.missing());\n\n                if (_seenDocs.insert(std::move(idField)).second) {\n                    return nextInput;\n                }\n                LOG(1) << \"$sample encountered duplicate document: \"\n                       << nextInput.getDocument().toString();\n                break;  // Try again with the next document.\n            }\n            case GetNextResult::ReturnStatus::kPauseExecution: {\n                MONGO_UNREACHABLE;  // Our input should be a random cursor, which should never\n                                    // result in kPauseExecution.\n            }\n            case GetNextResult::ReturnStatus::kEOF: {\n                return nextInput;\n            }\n        }\n    }\n    uasserted(28799,\n              str::stream() << \"$sample stage could not find a non-duplicate document after \"\n                            << kMaxAttempts\n                            << \" while using a random cursor. This is likely a \"\n                               \"sporadic failure, please try again.\");\n}\n\nValue DocumentSourceSampleFromRandomCursor::serialize(\n    boost::optional<ExplainOptions::Verbosity> explain) const {\n    return Value(DOC(getSourceName() << DOC(\"size\" << _size)));\n}\n\nDocumentSource::GetDepsReturn DocumentSourceSampleFromRandomCursor::getDependencies(\n    DepsTracker* deps) const {\n    deps->fields.insert(_idField);\n    return SEE_NEXT;\n}\n\nintrusive_ptr<DocumentSourceSampleFromRandomCursor> DocumentSourceSampleFromRandomCursor::create(\n    const intrusive_ptr<ExpressionContext>& expCtx,\n    long long size,\n    std::string idField,\n    long long nDocsInCollection) {\n    intrusive_ptr<DocumentSourceSampleFromRandomCursor> source(\n        new DocumentSourceSampleFromRandomCursor(expCtx, size, idField, nDocsInCollection));\n    return source;\n}\n}  // mongo\n", "meta": {"hexsha": "b429dbba6bf925494000fe1f053e8a637130faa7", "size": 7073, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mongo/db/pipeline/document_source_sample_from_random_cursor.cpp", "max_stars_repo_name": "GoldJohn/dds", "max_stars_repo_head_hexsha": "68e5cf295d2b356f42d86b78f35182f488fba85b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2020-06-12T06:33:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T03:15:56.000Z", "max_issues_repo_path": "src/mongo/db/pipeline/document_source_sample_from_random_cursor.cpp", "max_issues_repo_name": "visemet/mongo", "max_issues_repo_head_hexsha": "232c772546f26bcb5a5556d859e56002a4135f0b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2020-07-02T09:36:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-25T23:54:00.000Z", "max_forks_repo_path": "src/mongo/db/pipeline/document_source_sample_from_random_cursor.cpp", "max_forks_repo_name": "visemet/mongo", "max_forks_repo_head_hexsha": "232c772546f26bcb5a5556d859e56002a4135f0b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2020-06-12T03:08:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-03T11:43:09.000Z", "avg_line_length": 42.3532934132, "max_line_length": 100, "alphanum_fraction": 0.6684575145, "num_tokens": 1531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5813030906443134, "lm_q2_score": 0.3451052709578724, "lm_q1q2_score": 0.20061076060545444}}
{"text": "//\n// ********************************************************************\n// * License and Disclaimer                                           *\n// *                                                                  *\n// * The  Geant4 software  is  copyright of the Copyright Holders  of *\n// * the Geant4 Collaboration.  It is provided  under  the terms  and *\n// * conditions of the Geant4 Software License,  included in the file *\n// * LICENSE and available at  http://cern.ch/geant4/license .  These *\n// * include a list of copyright holders.                             *\n// *                                                                  *\n// * Neither the authors of this software system, nor their employing *\n// * institutes,nor the agencies providing financial support for this *\n// * work  make  any representation or  warranty, express or implied, *\n// * regarding  this  software system or assume any liability for its *\n// * use.  Please see the license in the file  LICENSE  and URL above *\n// * for the full disclaimer and the limitation of liability.         *\n// *                                                                  *\n// * This  code  implementation is the result of  the  scientific and *\n// * technical work of the GEANT4 collaboration.                      *\n// * By using,  copying,  modifying or  distributing the software (or *\n// * any work based  on the software)  you  agree  to acknowledge its *\n// * use  in  resulting  scientific  publications,  and indicate your *\n// * acceptance of all terms of the Geant4 Software license.          *\n// ********************************************************************\n//\n// $Id: PreampMedipix.cc $\n//\n/// \\file src/PreampMedipix.cc\n/// \\brief Implementation of the PreampMedipix class\n\n#include \"PreampMedipix.hh\"\n#include \"G4RunManager.hh\"\n#include \"G4Run.hh\"\n\n#include <stdio.h>\n#include <iostream>\n#include <fstream>\n\n#include <boost/concept_check.hpp>\n\n#include <boost/property_tree/ptree.hpp>\n#include <boost/property_tree/ini_parser.hpp>\n\nusing namespace std;\n\n\n//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......\nPreampMedipix::PreampMedipix(boost::property_tree::ptree pt)\n{\n\n    G4RunManager *fRM = G4RunManager::GetRunManager();\n    myDet = (DetectorConstructionBase *)(fRM->GetUserDetectorConstruction());\n    useCSM = myDet->GetCsmMode();\n\n    G4int detectorType = myDet->GetDetectorType();\n    // set gain modes for Medipix3RX and preamp \n    if(detectorType == 0){\n        if(useCSM == true){\n            elecSigma = pt.get<G4double>(\"chip_medipix3rx.csm_enc\");\n        }else {\n            elecSigma = pt.get<G4double>(\"chip_medipix3rx.spm_enc\");\n        }\n        Cf = myDet->GetDetectorGain();\n    } else if(detectorType == 1) { //Timepix\n        elecSigma = pt.get<G4double>(\"chip_timepix.enc\");\n        Cf = 8e-15; // 8fF same as Medipix2MXR\n    } else if(detectorType == 2) { // Dosepix\n        elecSigma = pt.get<G4double>(\"chip_dosepix.enc\");\n        Cf = 8e-15;\n    } else if (detectorType == 3) { // Timepix3\n        elecSigma = pt.get<G4double>(\"chip_timepix3.enc\");\n        Cf = 3e-15; // 3fF\n    }\n\n\n    // get material and load material properties from ini file\n    G4String material =  myDet->GetSensorMaterial()->GetName();\n    G4String sensor;\n    if (material == \"G4_Si\")\n        sensor = \"sensor_silicon\";\n    else if (material == \"G4_CADMIUM_TELLURIDE\")\n        sensor = \"sensor_cdte\";\n\n    pulsePrecision =    pt.get<G4double>(\"computation.pulsePrecision\") * ns;  //must be ns!\n    maxPulseTime =      pt.get<G4double>(\"computation.maxPulseTime\") * ns;\n\n    nPulseArrayElements = (G4int) maxPulseTime / pulsePrecision;\n    ampResponseTime =   pt.get<G4double>(\"computation.ampResponseTime\") * ns;\n    nAmpResponseElements = (G4int)(ampResponseTime / pulsePrecision);\n\n    nElectronHolePairs = pt.get<G4double>(sensor + \".nElectronHolePairs\");\n    minEnergy = 0.*keV;\n\n    DEBUG = pt.get<G4bool>(\"testing.debug\");\n    writePeakToFile = pt.get<G4bool>(\"testing.writePeakToFile\");\n\n    preampType = pt.get<G4int>(\"computation.preampType\");\n    \n    Ikrum = pt.get<G4double>(\"chip.Ikrum\") * 1e-9;\n\n    detector = MpxDetector::GetInstance();\n    thresholdkeV = detector->GetTpxThreshold();\n    thresholdCharge = thresholdkeV * 1000 / nElectronHolePairs ;\n\n    //set the transfer functions\n    SetTransferFunctions();\n\n    //THL dispersion\n    nPixel = myDet->GetNbPixels();\n    TpxThlDisp = new G4double[nPixel * nPixel]();\n\n    SetThresholdDispersion();\n}\n\n//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......\nvoid PreampMedipix::SetThresholdDispersion()\n{\n    //load .ini file with configuration data\n    boost::property_tree::ptree pt;\n    boost::property_tree::ini_parser::read_ini(\"DetectorConfig.ini\", pt);\n\n    //sensor properties\n    G4String material =  myDet->GetSensorMaterial()->GetName();\n    G4String sensor;\n    if (material == \"G4_Si\")\n        sensor = \"sensor_silicon\";\n    else if (material == \"G4_CADMIUM_TELLURIDE\")\n    {\n        sensor = \"sensor_cdte\";\n    }\n\n    G4int detectorType = myDet->GetDetectorType();\n\n    G4double disp = 0;\n\n    if (detectorType == 0){ //Medipix3RX\n        if(useCSM == true){\n            disp = pt.get<G4double>(\"chip_medipix3rx.csm_threshold_dispersion\");\n        } else {\n            disp = pt.get<G4double>(\"chip_medipix3rx.spm_threshold_dispersion\");\n        }\n\n    }else if (detectorType == 1){ //Timepix1\n        disp = pt.get<G4double>(\"chip_timepix.threshold_dispersion\");\n\n    }else if(detectorType == 2){ //Dosepix\n        disp = pt.get<G4double>(\"chip_dosepix.threshold_dispersion\");\n\n    }else if (detectorType == 3) { // Timepix3\n        disp = pt.get<G4double>(\"chip_timepix3.threshold_dispersion\");\n    }\n\n    for (G4int i = 0; i < nPixel * nPixel; i++) {\n        //G4cout << \"DEBUG: Setting Threshold Dispersion \" << disp << \" i: \" << i << \" nPixel: \" << nPixel*nPixel << G4endl;\n        TpxThlDisp[i] = CLHEP::RandGauss::shoot(0, disp); //sigma of thl dispersion\n    }\n}\n\n//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......\nvoid PreampMedipix::SetTransferFunctions(){\n    \n    \n    //Preamp transfer function\n    G4double Cd = 25e-15;  //Detector capacitance\n\n    G4double Gmfb   = Ikrum/2.*20;  //Transconductance in the feedback loop (approximation from Weak Inversion)\n    G4double Rf     = 2./Gmfb;       //feedback resistor\n\n    G4double gm0=30e-6;  //transconductance parameter\n    //G4double R0=20e6;    //Output resistance amplifier\n    G4double C0=25e-15;  //Output capacitance amplifier\n    G4double Ct=Cd*Cf+Cd*C0+Cf*C0;\n\n    G4double rcpr=Ct/(gm0*Cf);\n    G4double rcpf=Cf*Rf;\n\n    G4double w1 = 1./rcpr;\n    G4double w2 = 1./rcpf;\n\n\n    //create transfer function:\n    nImpResEl = nAmpResponseElements;\n    impRes = new G4double[nImpResEl];\n    for (G4int i = 0; i < nImpResEl; i++) {\n        impRes[i] = exp(-i* pulsePrecision * 1e-9 *w2 - exp(-i* pulsePrecision * 1e-9* w1));\n        //G4cout << \"Debug1: \" << i << \" value: \" << impRes[i] << G4endl;\n    }\n    //Shaper transfer function\n}\n\n//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......\nvoid PreampMedipix::GetPixelResponse(map<pair<G4int, G4int>, G4double *> *inducedPixelContent, MpxDigitCollection* digitCollection, G4int event)\n{\n    thresholdkeV = detector->GetTpxThreshold();\n    thresholdCharge = thresholdkeV * 1000 / nElectronHolePairs ;\n\n    if(preampType == 0){\n        chargeIntegrationPreamp(inducedPixelContent, event, digitCollection);\n    } else if(preampType == 1){\n        convolutionPreamp(inducedPixelContent, event, digitCollection);\n    }\n}\n\n//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......\nvoid PreampMedipix::chargeIntegrationPreamp(map<pair<G4int, G4int>, G4double *> *inducedPixelContent, G4int event, MpxDigitCollection *digitCollection)\n{\n    map<pair<G4int, G4int>, G4double> pixelsContent;\n\n    map<pair<G4int, G4int>, G4double * >::iterator iPCItr;\n    iPCItr = inducedPixelContent->begin();\n    for (; iPCItr != inducedPixelContent->end() ; iPCItr++) {\n\n        G4double maxCharge = 0;\n        G4double *tempArray = (*iPCItr).second;\n        G4double *ampResponse = new G4double[nAmpResponseElements]();\n\n        //preamp response\n        if(preampType == 0){\n            for (G4int i = 0; i < nPulseArrayElements; i++) {\n                maxCharge += tempArray[i];\n            }\n        }\n\n        //convert maximum in preamp response back to energy //FIXME here TOT\n        G4double energy = ElectronicsNoise(maxCharge) * nElectronHolePairs * eV;\n\n        //safe new pixel energy, not yet Digit(SPM and CSM)\n        if (energy > minEnergy) {\n            std::pair<G4int, G4int> newPixel;\n            newPixel.first  = (*iPCItr).first.first;\n            newPixel.second = (*iPCItr).first.second;\n            pixelsContent[newPixel] = energy;\n        }\n        //write preamp response to file\n        if (writePeakToFile == true) {\n\n            G4int k = (*iPCItr).first.first * 1000 + (*iPCItr).first.second;\n            char filename[64];\n            std::sprintf(filename, \"preampSingle%d\", k);\n\n            writeToFile(filename, ampResponse, nAmpResponseElements);\n        }\n\n    }\n\n    //print the energy in every pixel to the console\n    if (DEBUG) {\n        std::map<std::pair<G4int, G4int>, G4double>::iterator testItr =  pixelsContent.begin();\n        G4cout << pixelsContent.size() << \" number of entries in pixel Content\" << G4endl;\n\n        for (; testItr != pixelsContent.end() ; testItr++) {\n            G4cout << (*testItr).first.first << \" \" << (*testItr).first.second << \" \" << (*testItr).second / keV << G4endl;\n        }\n        G4cout << G4endl;\n    }\n\n    //create digits. one per pixel\n    std::map<std::pair<G4int, G4int>, G4double>::iterator pCItr =  pixelsContent.begin();\n    std::map<std::pair<G4int, G4int>, G4double>::iterator tempPCItr =  pixelsContent.begin();\n\n    //charge summing mode\n    if (useCSM == true) {\n\n        map<pair<G4int, G4int>, G4double> csmSumContent;\n        std::pair<G4int, G4int> tempPixelCSM;\n        std::pair<G4int, G4int> iteratePixel;\n\n        //calculate the 2x2 sums and store in csmSumContent, equivalent of the sum/pixel in the chip\n        for (; pCItr != pixelsContent.end() ; pCItr++) {\n\n            G4double sumEnergy = 0;\n\n            //get tempPixel\n            tempPixelCSM = pCItr->first;\n            iteratePixel = tempPixelCSM;\n\n            //sumEnergy of pixel\n            if (pixelsContent[tempPixelCSM] > 0) sumEnergy = pixelsContent[tempPixelCSM];\n\n            iteratePixel.first += 1;\n            tempPCItr = pixelsContent.find(iteratePixel);\n            if (tempPCItr != pixelsContent.end()) {\n                if (tempPCItr->second > 0) sumEnergy += tempPCItr->second;\n            }\n\n            iteratePixel.second -= 1;\n            tempPCItr = pixelsContent.find(iteratePixel);\n            if (tempPCItr != pixelsContent.end()) {\n                if (tempPCItr->second > 0) sumEnergy += tempPCItr->second;\n            }\n\n            iteratePixel.first -= 1;\n            tempPCItr = pixelsContent.find(iteratePixel);\n            if (tempPCItr != pixelsContent.end()) {\n                if (tempPCItr->second > 0) sumEnergy += tempPCItr->second;\n            }\n\n            //store the sum with the pixel ID\n            csmSumContent[tempPixelCSM] = sumEnergy;\n        }\n\n        //compare the sums\n        std::map<std::pair<G4int, G4int>, G4double>::iterator csmItr =  csmSumContent.begin();\n        for (; csmItr != csmSumContent.end() ; csmItr++) {\n\n            //get tempPixel\n            tempPixelCSM = csmItr->first;\n            iteratePixel = tempPixelCSM;\n\n            //neighbors\n            G4double cmpEnergy1 = 0;\n            G4double cmpEnergy2 = 0;\n            G4double cmpEnergy3 = 0;\n            G4double cmpEnergy4 = 0;\n\n            //diagonal\n            G4double cmpEnergy5 = 0;\n            G4double cmpEnergy6 = 0;\n            G4double cmpEnergy7 = 0;\n            G4double cmpEnergy8 = 0;\n\n            //get sumEnergy of pixel\n            G4double pixelEnergy = csmSumContent[tempPixelCSM];\n\n            iteratePixel = tempPixelCSM;\n            iteratePixel.first += 1;\n            tempPCItr = csmSumContent.find(iteratePixel);\n            if (tempPCItr != csmSumContent.end()) {\n                cmpEnergy1 += tempPCItr->second;\n            }\n\n            iteratePixel = tempPixelCSM;\n            iteratePixel.first -= 1;\n            tempPCItr = csmSumContent.find(iteratePixel);\n            if (tempPCItr != csmSumContent.end()) {\n                cmpEnergy2 += tempPCItr->second;\n            }\n\n            iteratePixel = tempPixelCSM;\n            iteratePixel.second += 1;\n            tempPCItr = csmSumContent.find(iteratePixel);\n            if (tempPCItr != csmSumContent.end()) {\n                cmpEnergy3 += tempPCItr->second;\n            }\n\n            iteratePixel = tempPixelCSM;\n            iteratePixel.second -= 1;\n            tempPCItr = csmSumContent.find(iteratePixel);\n            if (tempPCItr != csmSumContent.end()) {\n                cmpEnergy4 += tempPCItr->second;\n            }\n\n            iteratePixel = tempPixelCSM;\n            iteratePixel.first -= 1;\n            iteratePixel.second -= 1;\n            tempPCItr = csmSumContent.find(iteratePixel);\n            if (tempPCItr != csmSumContent.end()) {\n                cmpEnergy5 += tempPCItr->second;\n            }\n\n            iteratePixel = tempPixelCSM;\n            iteratePixel.first += 1;\n            iteratePixel.second -= 1;\n            tempPCItr = csmSumContent.find(iteratePixel);\n            if (tempPCItr != csmSumContent.end()) {\n                cmpEnergy6 += tempPCItr->second;\n            }\n\n            iteratePixel = tempPixelCSM;\n            iteratePixel.first -= 1;\n            iteratePixel.second += 1;\n            tempPCItr = csmSumContent.find(iteratePixel);\n            if (tempPCItr != csmSumContent.end()) {\n                cmpEnergy7 += tempPCItr->second;\n            }\n\n            iteratePixel = tempPixelCSM;\n            iteratePixel.first += 1;\n            iteratePixel.second += 1;\n            tempPCItr = csmSumContent.find(iteratePixel);\n            if (tempPCItr != csmSumContent.end()) {\n                cmpEnergy8 += tempPCItr->second;\n            }\n\n            //create digit\n            if (pixelEnergy > cmpEnergy1 && pixelEnergy > cmpEnergy2 && pixelEnergy > cmpEnergy3 && pixelEnergy > cmpEnergy4 && pixelEnergy > cmpEnergy5 && pixelEnergy > cmpEnergy6 && pixelEnergy > cmpEnergy7 && pixelEnergy > cmpEnergy8) {\n                Digit *digit = new Digit;\n                digit->SetColumn(tempPixelCSM.first);\n                digit->SetLine(tempPixelCSM.second);\n                digit->SetEnergy(pixelEnergy / keV);\n                digit->SetEvent(event);\n                digitCollection->insert(digit);\n            }\n        }\n\n    } else {  //no CSM\n        for (; pCItr != pixelsContent.end() ; pCItr++) {\n            //convert all events into digits\n            G4double energy = (*pCItr).second;\n            if (energy > minEnergy) {\n                Digit *digit = new Digit;\n                digit->SetColumn((*pCItr).first.first);\n                digit->SetLine((*pCItr).first.second);\n                digit->SetEnergy((energy / keV));\n                digit->SetEvent(event);\n                digitCollection->insert(digit);\n            }\n        }\n    }\n\n    //free memory\n    iPCItr = inducedPixelContent->begin();\n    for (; iPCItr != inducedPixelContent->end() ; iPCItr++) {\n        G4double *tempArray = (*iPCItr).second;\n        delete[] tempArray;\n    }\n    inducedPixelContent->clear();\n    delete inducedPixelContent;\n    pixelsContent.clear();\n\n}\n\n//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......\nvoid PreampMedipix::convolutionPreamp(map<pair<G4int, G4int>, G4double *> *inducedPixelContent, G4int event, MpxDigitCollection *digitCollection)\n{\n    //SPM mode\n    if(useCSM == false){\n\n        map<pair<G4int, G4int>, G4double * >::iterator iPCItr;\n        iPCItr = inducedPixelContent->begin();\n\n        //iterate over induced currents in pixels\n        for (; iPCItr != inducedPixelContent->end() ; iPCItr++) {\n\n            G4double *ampResponse = new G4double[nAmpResponseElements]();\n            G4double *inducedChargeArray = (*iPCItr).second;\n\n            //Preamp\n            convolve(inducedChargeArray, ampResponse, nPulseArrayElements, impRes, nImpResEl);\n\n            //noise\n            for(G4int i=0; i<nAmpResponseElements; i++){\n                ampResponse[i] = ElectronicsNoise(ampResponse[i]);\n            }\n\n            //getEnergy\n            boost::tuple<G4double,G4double,G4double> totPeakToa;\n            G4int pixelIndex = ((*iPCItr).first.first) * nPixel + ((*iPCItr).first.second);\n            G4double thlDisp = TpxThlDisp[pixelIndex];\n\n            totPeakToa = getToTandPeak(ampResponse, thresholdCharge, thlDisp);\n            delete[] ampResponse;\n\n            //convert to digits from peak value //FIXME here ToT\n            if (boost::get<1>(totPeakToa) > minEnergy) {\n                Digit *digit = new Digit;\n                digit->SetColumn((*iPCItr).first.first);\n                digit->SetLine((*iPCItr).first.second);\n                digit->SetEnergy((boost::get<1>(totPeakToa) / keV));\n                digit->SetToT(boost::get<0>(totPeakToa));\n                digit->SetToA(boost::get<2>(totPeakToa));\n                digit->SetEvent(event);\n                digitCollection->insert(digit);\n            }\n        }\n\n        //free memory\n        iPCItr = inducedPixelContent->begin();\n        for (; iPCItr != inducedPixelContent->end() ; iPCItr++) {\n            G4double *tempArray = (*iPCItr).second;\n            delete[] tempArray;\n        }\n        inducedPixelContent->clear();\n        delete inducedPixelContent;\n    }\n\n    //CSM mode\n    if(useCSM == true){\n\n        map<pair<G4int, G4int>, G4double * >::iterator iPCItr;\n        iPCItr = inducedPixelContent->begin();\n\n        map<pair<G4int, G4int>, G4double * >* preampResponse    = new map<pair<G4int, G4int>, G4double * >;\n        map<pair<G4int, G4int>, boost::tuple<G4double,G4double,G4double> >* sumPreampResponse = new map<pair<G4int, G4int>, boost::tuple<G4double,G4double,G4double> >;\n        pair<G4int,G4int> tempPixel;\n        G4double* emptyDummy = new G4double[nAmpResponseElements]();\n\n        //preampresponse of every pixel\n        for (; iPCItr != inducedPixelContent->end() ; iPCItr++) {\n            G4double* ampResponse = new G4double[nAmpResponseElements]();\n            G4double* inducedChargeArray = (*iPCItr).second;\n\n            //Preamp\n            convolve(inducedChargeArray, ampResponse, nPulseArrayElements, impRes, nImpResEl);\n\n            //write single preamp response to file\n            if (writePeakToFile == true) {\n\n                G4int k = (*iPCItr).first.first * 1000 + (*iPCItr).first.second;\n                char filename[64];\n                std::sprintf(filename, \"preampSingle%d\", k);\n\n                writeToFile(filename, ampResponse, nAmpResponseElements);\n            }\n\n            //store single preampResponse\n            tempPixel.first = (*iPCItr).first.first;\n            tempPixel.second = (*iPCItr).first.second;\n            preampResponse->operator [](tempPixel) = ampResponse;\n        }\n\n        //sum the responses and store\n        map<pair<G4int, G4int>, G4double * >::iterator pRItr;\n        map<pair<G4int, G4int>, G4double * >::iterator tempPRItr;\n        pRItr = preampResponse->begin();\n\n        for(; pRItr != preampResponse->end(); pRItr++){\n\n            pair<G4int,G4int>mainPixel = pRItr->first;\n            pair<G4int,G4int>iteratePixel = mainPixel;\n\n            //get the preamp arrays\n            G4double *tempPreampReponse;\n            //sum the responses\n            G4double* csmSumPreamp = new G4double[nAmpResponseElements]();\n\n            G4int sumArrLow = 0;\n            G4int sumArrHigh = 1;\n\n            for(G4int i=sumArrLow; i<=sumArrHigh; i++){\n                for(G4int j=sumArrLow; j<=sumArrHigh; j++){\n                    //set pixel\n                    iteratePixel.first = mainPixel.first + i;\n                    iteratePixel.second = mainPixel.second + j;\n\n                    //find response pulse\n                    tempPRItr = preampResponse->find(iteratePixel);\n                    if(tempPRItr != preampResponse->end()){\n                        tempPreampReponse = tempPRItr->second;\n\n                        //add to sum\n                        for(G4int k=0; k < nAmpResponseElements; k++){\n                            csmSumPreamp[k] += tempPreampReponse[k];\n                        }\n                    }\n                }\n            }\n\n            //add noise\n            for(G4int i=0; i < nAmpResponseElements; i++){\n                csmSumPreamp[i] = ElectronicsNoise(csmSumPreamp[i]);\n            }\n\n            //write CSM preamp response to file\n            if (writePeakToFile == true) {\n\n                G4int k = (*pRItr).first.first * 1000 + (*pRItr).first.second;\n                char filename[64];\n                std::sprintf(filename, \"preampCSM%d\", k);\n\n                writeToFile(filename, csmSumPreamp, nAmpResponseElements);\n            }\n\n            //get energy\n            boost::tuple<G4double,G4double,G4double> totPeakToa;\n            G4int pixelIndex = ((*pRItr).first.first) * nPixel + ((*pRItr).first.second);\n            G4double thlDisp = TpxThlDisp[pixelIndex];\n\n            totPeakToa = getToTandPeak(csmSumPreamp, thresholdCharge, thlDisp);\n\n            sumPreampResponse->operator [](mainPixel) = totPeakToa;\n\n            //delete the array\n            delete[] csmSumPreamp;\n        }\n\n        //compare the sums\n        map<pair<G4int, G4int>, boost::tuple<G4double,G4double,G4double> >::iterator sPRItr = sumPreampResponse->begin();\n        map<pair<G4int, G4int>, boost::tuple<G4double,G4double,G4double> >::iterator tempSPRItr;\n        for (; sPRItr != sumPreampResponse->end() ; sPRItr++) {\n\n            //get tempPixel\n            pair<G4int,G4int> tempPixelCSM = sPRItr->first;\n            pair<G4int,G4int> iteratePixel = tempPixelCSM;\n\n            //first value: ToT, second: peak amplitude\n            boost::tuple<G4double,G4double,G4double> cmpEnergy(0,0,0);\n\n\n            //get sumEnergy of pixel\n            boost::tuple<G4double,G4double,G4double> pixelEnergy = sumPreampResponse->operator [](tempPixelCSM);\n            G4bool isMax = true;\n\n            //sets the borders for the comparison\n            G4int compArrLow    = -1;\n            G4int compArrHigh   = 1;\n\n\n            //compare neighbouring pixels with main pixel\n            for(G4int i=compArrLow; i<=compArrHigh; i++){\n                for(G4int j=compArrLow; j<=compArrHigh; j++){\n                    if(!(i == 0 && j == 0)){\n                        iteratePixel = tempPixelCSM;\n                        iteratePixel.first += i;\n                        iteratePixel.second += j;\n                        tempSPRItr = sumPreampResponse->find(iteratePixel);\n                        if (tempSPRItr != sumPreampResponse->end()) {\n                            cmpEnergy = tempSPRItr->second;\n                            if(boost::get<1>(cmpEnergy) > boost::get<1>(pixelEnergy)) isMax = false;\n                        }\n                    }\n                }\n            }\n\n            //create digit\n            if (isMax == true) {\n                Digit *digit = new Digit;\n                digit->SetColumn(tempPixelCSM.first);\n                digit->SetLine(tempPixelCSM.second);\n                digit->SetEnergy((boost::get<1>(pixelEnergy) / keV));\n                digit->SetToT(boost::get<0>(pixelEnergy));\n                digit->SetToA(boost::get<2>(pixelEnergy));\n                digit->SetEvent(event);\n                digitCollection->insert(digit);\n            }\n        }\n\n        //free memory\n        //induced pulses\n        iPCItr = inducedPixelContent->begin();\n        for (; iPCItr != inducedPixelContent->end() ; iPCItr++) {\n            G4double *tempArray = (*iPCItr).second;\n            delete[] tempArray;\n        }\n        inducedPixelContent->clear();\n        delete inducedPixelContent;\n\n\n        //preamp response\n        pRItr = preampResponse->begin();\n\n        for(; pRItr != preampResponse->end(); pRItr++){\n            G4double* tempArray = (*pRItr).second;\n            delete[] tempArray;\n        }\n        preampResponse->clear();\n        delete preampResponse;\n\n        //preamp sum\n        sumPreampResponse->clear();\n        delete sumPreampResponse;\n\n        delete[] emptyDummy;\n    }\n}\n\n\n//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......\nG4double PreampMedipix::ElectronicsNoise(G4double charge)\n{\n    G4double sigma = elecSigma;\n    if(useCSM == true && preampType != 2) sigma = sigma * 2;\n    return CLHEP::RandGauss::shoot(charge, sigma);\n}\n\n//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......\nG4double PreampMedipix::convolve(G4double* in, G4double* out, G4int inLength, G4double* kernel, G4int kernel_length)\n{\n    G4double maxCharge = 0;\n\n    for(G4int i=0; i<(kernel_length); i++){\n\n        out[i] = 0.0;\n        for(G4int k=0; k<kernel_length; k++){\n            if((i-k) >=0 && (i-k) < inLength){\n                out[i] += in[i-k] * kernel[k];\n            }\n        }\n        if(out[i] > maxCharge) maxCharge = out[i];\n    }\n\n    return maxCharge;\n}\n\n//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......\nboost::tuple<G4double,G4double,G4double> PreampMedipix::getToTandPeak(G4double* preamp, G4double threshold, G4double thlDisp){\n    G4int risingEdge = 0;\n\n    boost::tuple<G4double,G4double,G4double> returnValues(0,0,0);\n    // 0 = ToT, 1 = peakCharge, 2 = ToA\n\n    for(G4int i=0; i<nAmpResponseElements; i++){\n\n        if(risingEdge == 0 && preamp[i] >= (threshold+thlDisp)){\n            risingEdge = i;\n            // Set timeOfArrival\n            if(boost::get<2>(returnValues) == 0) {\n                boost::get<2>(returnValues) = i * pulsePrecision;\n            }\n        }\n\n        if(risingEdge != 0 && preamp[i] <= (threshold+thlDisp)){\n            // Set timeOverThreshold\n            if((i - risingEdge) * pulsePrecision > boost::get<0>(returnValues)) {\n                boost::get<0>(returnValues) = (i - risingEdge) * pulsePrecision;\n            }\n            risingEdge = 0;\n        }\n\n        // set the peakCharge\n        if(boost::get<1>(returnValues) < (preamp[i]+thlDisp)) boost::get<1>(returnValues) = (preamp[i]+thlDisp);\n    }\n\n    boost::get<1>(returnValues) = boost::get<1>(returnValues) * nElectronHolePairs * eV;\n\n    return returnValues;\n}\n\n//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......\nvoid PreampMedipix::writeToFile(G4String filename, G4double* data, G4int nElements){\n    ofstream myfile;\n\n    myfile.open(filename);\n\n    for (G4int it = 0; it < nElements; it++) {\n        myfile << data[it] << \" \";\n    }\n    myfile.close();\n}\n", "meta": {"hexsha": "0491ac7937c25b2ae21047bc984bd2924b9e1538", "size": 27037, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/PreampMedipix.cc", "max_stars_repo_name": "M4I-nanoscopy/geant4medipix", "max_stars_repo_head_hexsha": "8b8584b0ce85957215a2f055775a61c81f430180", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-19T09:46:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T09:46:28.000Z", "max_issues_repo_path": "src/PreampMedipix.cc", "max_issues_repo_name": "M4I-nanoscopy/geant4medipix", "max_issues_repo_head_hexsha": "8b8584b0ce85957215a2f055775a61c81f430180", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PreampMedipix.cc", "max_forks_repo_name": "M4I-nanoscopy/geant4medipix", "max_forks_repo_head_hexsha": "8b8584b0ce85957215a2f055775a61c81f430180", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-06T13:05:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T13:05:31.000Z", "avg_line_length": 37.0369863014, "max_line_length": 239, "alphanum_fraction": 0.5724377705, "num_tokens": 7164, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2003791941785145}}
{"text": "// export POPLAR_ENGINE_OPTIONS='{\"target.workerStackSizeInBytes\":1024}'\n\n#include <iostream>\n#include <vector>\n#include <boost/timer/timer.hpp>\n\n//~ poplar\n#include <poplar/DeviceManager.hpp>\n#include <poplar/IPUModel.hpp>\n#include <poplar/Engine.hpp>\n#include <poplar/Program.hpp>\n\n//~ poplin\n#include <poplin/codelets.hpp>\n\n//~ popops\n#include <popops/ElementWise.hpp>\n#include <popops/ExprOp.hpp>\n#include <popops/Pad.hpp>\n#include <popops/codelets.hpp>\n\n//~ poputil\n#include <poputil/TileMapping.hpp>\n\n//~ KF header\n#include \"KalmanFilter.h\"\n\n/* contents\n~01 KalmanFilter::connectToIPU\n~02 KalmanFilter::skipSwitch\n~03 KalmanFilter::smoothingState\n~04 KalmanFilter::appendTo\n~05 KalmanFilter::inverse\n~06 KalmanFilter::packHits\n~07 KalmanFilter::iterate\n~08 KalmanFilter::product\n~09 KalmanFilter::scaledAdd\n~10 KalmanFilter::filter\n~11 KalmanFilter::propagateState\n~12 KalmanFilter::jacobian\n~13 KalmanFilter::projectEKF\n~14 KalmanFilter::project\n~15 KalmanFilter::packIterationTensors\n~16 KalmanFilter::calcResidual\n~17 KalmanFilter::calcChiSq\n~18 KalmanFilter::chiSqTest\n~19 KalmanFilter::smooth\n*/\n\nusing namespace poplar;\nusing namespace poplar::program;\nusing namespace popops;\n\n\nDevice KalmanFilter::connectToIPU()\n{\n\n    DeviceManager manager = DeviceManager::createDeviceManager();\n    Device dev;\n\n    bool success = false;\n\n    //~ looping over each IPU\n    for (auto &d : manager.getDevices(poplar::TargetType::IPU, 1))\n    {\n        dev = std::move(d);\n        std::cerr << \"Trying to attach to IPU \" << dev.getId();\n        if ((success = dev.attach()))\n        {\n            std::cerr << \" - attached\" << std::endl;\n            break;\n        }\n        else\n        {\n            std::cerr << std::endl;\n        }\n    }\n\n    if (!success)\n    {\n        std::cerr << \"Error attaching to device\" << std::endl;\n        exit(1);\n    }\n\n    return dev;\n\n} //~ end KalmanFilter::connectToIPU\n\n\nstd::tuple<ComputeSet, Tensor, Tensor, Tensor>\nKalmanFilter::skipSwitch(Graph &graph,\n                         const Tensor &inputPOld,\n                         const Tensor &inputCOld,\n                         const Tensor &inputPNew,\n                         const Tensor &inputCNew,\n                         const Tensor &chiSq,\n                         uint tile)\n{\n\n    ComputeSet computeSet = graph.addComputeSet(\"SkipSwitch\" + std::to_string(tile));\n    VertexRef vtx = graph.addVertex(computeSet, \"SkipSwitch\");\n\n    graph.setCycleEstimate(vtx, 100);\n\n    Tensor outP =\n        graph.addVariable(FLOAT, {2, 1}, \"switchOutP\" + std::to_string(tile));\n    Tensor outC =\n        graph.addVariable(FLOAT, {2, 2}, \"switchOutC\" + std::to_string(tile));\n    Tensor outD =\n        graph.addVariable(FLOAT, {1, 1}, \"switchOutD\" + std::to_string(tile));\n\n    graph.connect(vtx[\"inputPOld\"], inputPOld);\n    graph.connect(vtx[\"inputCOld\"], inputCOld);\n    graph.connect(vtx[\"inputPNew\"], inputPNew);\n    graph.connect(vtx[\"inputCNew\"], inputCNew);\n    graph.connect(vtx[\"chiSq\"], chiSq);\n    graph.connect(vtx[\"outP\"], outP);\n    graph.connect(vtx[\"outC\"], outC);\n    graph.connect(vtx[\"outD\"], outD);\n\n    graph.setTileMapping(vtx, tile);\n    graph.setTileMapping(outP, tile);\n    graph.setTileMapping(outC, tile);\n    graph.setTileMapping(outD, tile);\n\n    return std::make_tuple(computeSet, outP, outC, outD);\n\n} //~ end KalmanFilter::skipSwitch\n\n\nstd::tuple<ComputeSet, Tensor>\nKalmanFilter::smoothingState(Graph &graph,\n                             const Tensor &states,\n                             const Tensor &itr,\n                             uint tile)\n{\n    ComputeSet computeSet =\n        graph.addComputeSet(\"smoothingState\" + std::to_string(tile));\n\n    VertexRef vtx = graph.addVertex(computeSet, \"StateForSmoothing\");\n\n    graph.setCycleEstimate(vtx, 100);\n\n    Tensor tmp =\n        states.reshape({states.shape()[0], states.shape()[1] * states.shape()[2]});\n\n    Tensor state =\n        graph.addVariable(FLOAT,\n                          {states.shape()[1], states.shape()[2]},\n                          \"state\" + std::to_string(tile));\n\n    graph.connect(vtx[\"state\"], state.reshape({state.shape()[0] * state.shape()[1]}));\n    graph.connect(vtx[\"states\"], tmp);\n    graph.connect(vtx[\"itr\"], itr);\n\n    graph.setTileMapping(vtx, tile);\n    graph.setTileMapping(tmp, tile);\n    graph.setTileMapping(state, tile);\n\n    return std::make_pair(computeSet,\n                          state.reshape({states.shape()[1],\n                          states.shape()[2]}));\n\n} //~ end KalmanFilter::smoothingState\n\n\nstd::tuple<ComputeSet, Tensor>\nKalmanFilter::appendTo(Graph &graph,\n                       const Tensor &state,\n                       const Tensor &itr,\n                       Tensor &states,\n                       uint tile)\n{\n    ComputeSet computeSet = graph.addComputeSet(\"append\" + std::to_string(tile));\n    VertexRef vtx = graph.addVertex(computeSet, \"AppendState\");\n    graph.setCycleEstimate(vtx, 100);\n\n    Tensor tmp = states.reshape(\n            {states.shape()[0], states.shape()[1] * states.shape()[2]});\n\n    Tensor newStates =\n            graph.addVariable(FLOAT, tmp.shape(), \"newStates\" + std::to_string(tile));\n\n    graph.connect(vtx[\"state\"], state.reshape({state.shape()[0] * state.shape()[1]}));\n    graph.connect(vtx[\"states\"], tmp);\n    graph.connect(vtx[\"newStates\"], newStates);\n    graph.connect(vtx[\"itr\"], itr);\n\n    graph.setTileMapping(vtx, tile);\n    graph.setTileMapping(tmp, tile);\n    graph.setTileMapping(newStates, tile);\n\n    return std::make_pair(computeSet,\n                          newStates.reshape({states.shape()[0],\n                          states.shape()[1],\n                          states.shape()[2]}));\n\n} //~ end KalmanFilter::appendTo\n\n\nstd::tuple<ComputeSet, Tensor>\nKalmanFilter::inverse(Graph &graph,\n                      const Tensor &in,\n                      uint tile,\n                      uint dim)\n{\n\n    ComputeSet computeSet = graph.addComputeSet(\"inverse\" + std::to_string(tile));\n\n    VertexRef vtx =\n        graph.addVertex(computeSet, \"MatrixInverse\" + std::to_string(dim));\n\n    graph.setCycleEstimate(vtx, 100);\n\n    Tensor out =\n            graph.addVariable(FLOAT, {dim, dim}, \"invOut\" + std::to_string(tile));\n\n    graph.connect(vtx[\"in\"], in);\n    graph.connect(vtx[\"out\"], out);\n\n    graph.setTileMapping(vtx, tile);\n    graph.setTileMapping(out, tile);\n\n    return std::make_pair(computeSet, out);\n\n} //~ end KalmanFilter::inverse\n\n\nstd::tuple<ComputeSet, Tensor>\nKalmanFilter::packHits(Graph &graph,\n                       const Tensor &inputHits,\n                       const Tensor &itr,\n                       uint tile)\n{\n\n    ComputeSet computeSet =\n            graph.addComputeSet(\"packHits4\" + std::to_string(tile));\n\n    VertexRef vtx = graph.addVertex(computeSet, \"PackHits4\");\n\n    graph.setCycleEstimate(vtx, 10);\n\n    // Same shape as ps\n    Tensor out =\n            graph.addVariable(FLOAT, {4, 1}, \"hitsThisItr\" + std::to_string(tile));\n\n    graph.connect(vtx[\"inputHits\"], inputHits);\n    graph.connect(vtx[\"itr\"], itr);\n    graph.connect(vtx[\"out\"], out);\n\n    graph.setTileMapping(vtx, tile);\n    graph.setTileMapping(out, tile);\n\n    return std::make_pair(computeSet, out);\n\n} //~ end KalmanFilter::packHits\n\n\nstd::tuple<ComputeSet, Tensor>\nKalmanFilter::iterate(Graph &graph,\n                      const Tensor &iterator,\n                      uint tile)\n{\n\n    ComputeSet computeSet = graph.addComputeSet(\"iterate\" + std::to_string(tile));\n    VertexRef vtx = graph.addVertex(computeSet, \"Iterate\");\n    graph.setCycleEstimate(vtx, 10);\n\n    Tensor out = graph.addVariable(INT, {1}, \"itrOut\" + std::to_string(tile));\n\n    graph.connect(vtx[\"in\"], iterator);\n    graph.connect(vtx[\"out\"], out);\n    graph.setTileMapping(vtx, tile);\n    graph.setTileMapping(out, tile);\n\n    return std::make_pair(computeSet, out);\n\n} //~ end KalmanFilter::iterate\n\n\nstd::tuple<ComputeSet, Tensor>\nKalmanFilter::product(Graph &graph,\n                      const Tensor &first,\n                      const Tensor &second,\n                      uint tile)\n{\n\n    ComputeSet computeSet = graph.addComputeSet(\"product\" + std::to_string(tile));\n    VertexRef vtx = graph.addVertex(computeSet, \"MatrixProduct\");\n    graph.setCycleEstimate(vtx, 100);\n\n    uint outRows = first.shape()[0];\n    uint outCols = second.shape()[1];\n\n    Tensor out = graph.addVariable(FLOAT, {outRows, outCols},\n                                   \"prodOut\" + std::to_string(tile));\n\n    graph.connect(vtx[\"first\"], first);\n    graph.connect(vtx[\"second\"], second);\n    graph.connect(vtx[\"out\"], out);\n\n    graph.setTileMapping(vtx, tile);\n    graph.setTileMapping(out, tile);\n\n    return std::make_pair(computeSet, out);\n\n} //~ end KalmanFilter::product\n\n\nstd::tuple<ComputeSet, Tensor>\nKalmanFilter::scaledAdd(Graph &graph,\n                        const Tensor &first,\n                        const Tensor &second,\n                        uint tile,\n                        float s,\n                        std::string name)\n{\n\n    ComputeSet computeSet =\n        graph.addComputeSet(\"scaledAdd\" + name + std::to_string(tile));\n\n    VertexRef vtx = graph.addVertex(computeSet, \"ScaledAdd\");\n    graph.setCycleEstimate(vtx, 100);\n\n    uint outRows = first.shape()[0];\n    uint outCols = first.shape()[1];\n\n    Tensor out = graph.addVariable(FLOAT, {outRows, outCols},\n                                   \"addOut\" + name + std::to_string(tile));\n\n    graph.connect(vtx[\"first\"], first);\n    graph.connect(vtx[\"second\"], second);\n    graph.connect(vtx[\"s\"], s);\n    graph.connect(vtx[\"out\"], out);\n\n    graph.setTileMapping(vtx, tile);\n    graph.setTileMapping(out, tile);\n\n    return std::make_pair(computeSet, out);\n\n} //~ end KalmanFilter::scaledAdd\n\n\nstd::tuple<Sequence, std::vector<Tensor>, std::vector<Tensor>>\nKalmanFilter::filter(Graph &graph,\n                     const std::vector<Tensor> &H,\n                     const std::vector<Tensor> &G,\n                     const std::vector<Tensor> &hits,\n                     const std::vector<Tensor> &p,\n                     const std::vector<Tensor> &C)\n{\n\n    Sequence op;\n\n    std::vector<Tensor> outp(p.size());\n    std::vector<Tensor> outc(p.size());\n\n    for (uint i = 0; i < p.size(); i++)\n    {\n\n        outp[i] = graph.addVariable(FLOAT, {4, 1});\n        graph.setTileMapping(outp[i], i);\n\n        outc[i] = graph.addVariable(FLOAT, {4, 4});\n        graph.setTileMapping(outc[i], i);\n\n        auto [computeHG, HG] = product(graph, H[i], G[i], i);\n        op.add(Execute(computeHG));\n\n        // inv_C_proj + HG @ H\n        auto [computeHGH, HGH] = product(graph, HG, H[i], i);\n        op.add(Execute(computeHGH));\n\n        auto [computeInverseC, invOutC] = inverse(graph, C[i], i, 4);\n        op.add(Execute(computeInverseC));\n\n        auto [computeAddCHGH, CHGH_HGH] = scaledAdd(graph, invOutC, HGH, i);\n        op.add(Execute(computeAddCHGH));\n\n        auto [computeInverseCHGH, invOutCHGH] = inverse(graph, CHGH_HGH, i, 4);\n        op.add(Execute(computeInverseCHGH));\n\n        auto [computeHGhits, HGhits] = product(graph, HG, hits[i], i);\n        op.add(Execute(computeHGhits));\n\n        auto [computePFilt, Cp_filt] = product(graph, invOutC, p[i], i);\n        op.add(Execute(computePFilt));\n\n        auto [computeAddCpHits, Cp_filt_hits] = scaledAdd(graph, Cp_filt, HGhits, i);\n        op.add(Execute(computeAddCpHits));\n\n        auto [computeCHGHPFilt, CHGHPFilt] = product(graph, invOutCHGH, Cp_filt_hits, i);\n        op.add(Execute(computeCHGHPFilt));\n\n        op.add(Copy(CHGHPFilt, outp[i]));\n        op.add(Copy(invOutCHGH, outc[i]));\n\n    }\n\n    return std::make_tuple(op, outp, outc);\n\n} //~ end KalmanFilter::filter\n\n\nstd::tuple<Sequence, std::vector<Tensor>>\nKalmanFilter::propagateState(Graph &graph,\n                             std::vector<Tensor> &ps,\n                             std::vector<Tensor> &d)\n{\n\n    Sequence op;\n\n    std::vector<Tensor> outP(ps.size());\n\n    for (uint i = 0; i < ps.size(); i++)\n    {\n\n        outP[i] = graph.addVariable(FLOAT, {2, 1});\n        graph.setTileMapping(outP[i], i);\n\n        // Need to allocate this earlier, and not during every function invocation!\n        Tensor updMFlat = graph.addConstant<float>(FLOAT, {4, 1}, {0., 1., 0., 0.});\n        Tensor updM = graph.addVariable(FLOAT, {2, 2});\n\n        graph.setTileMapping(updMFlat, i);\n        graph.setTileMapping(updM, i);\n\n        updM = updMFlat.reshape({2, 2}); // Can't seem to set nD constant\n\n        graph.setTileMapping(updM, i);\n\n        // xTan = tan([x0, x1])\n        Tensor pTan = popops::map(graph, popops::expr::UnaryOpType::TAN, ps[i], op);\n        graph.setTileMapping(pTan, i);\n\n        // x += d * [[0, 1], [0, 0]] * xTan -> x0 += d * tan(x1), x1 += 0\n\n        auto [computeProdUpdTan, updTan] = product(graph, updM, pTan, i);\n        op.add(Execute(computeProdUpdTan));\n\n        auto [computeProdUpdD, updD] = product(graph, updTan, d[i], i);\n        op.add(Execute(computeProdUpdD));\n\n        auto [computeAddP, addP] = scaledAdd(graph, ps[i], updD, i);\n        op.add(Execute(computeAddP));\n\n        op.add(Copy(addP, outP[i]));\n\n    }\n\n    return std::make_tuple(op, outP);\n\n} //~ end KalmanFilter::propagateState\n\n\nstd::tuple<Sequence, std::vector<Tensor>>\nKalmanFilter::jacobian(Graph &graph,\n                       const std::vector<Tensor> &ps,\n                       const std::vector<Tensor> &d)\n{\n\n    Sequence op;\n\n    std::vector<Tensor> jacs(ps.size());\n\n    for (uint i = 0; i < ps.size(); i++)\n    {\n\n        Tensor updMFlat = graph.addConstant<float>(FLOAT, {4, 1}, {0., 1., 0., 0.});\n        Tensor updM = graph.addVariable(FLOAT, {2, 2});\n\n        jacs[i] = graph.addVariable(FLOAT, {2, 2});\n\n        graph.setTileMapping(updMFlat, i);\n        graph.setTileMapping(updM, i);\n        graph.setTileMapping(jacs[i], i);\n\n        updM = updMFlat.reshape({2, 2});\n\n        Tensor xCos = popops::map(graph, popops::expr::UnaryOpType::COS, ps[i], op);\n        Tensor xCosSq =\n            popops::map(graph, popops::expr::UnaryOpType::SQUARE, xCos, op);\n        Tensor xCosSqI =\n            popops::map(graph, popops::expr::UnaryOpType::INVERSE, xCosSq, op);\n\n        Tensor xCosM = popops::pad(graph, xCosSqI,\n                                   1,  // pad lower\n                                   0,  // pad upper,\n                                   1,  // pad dim\n                                   0); // pad value\n\n        graph.setTileMapping(xCos, i);\n        graph.setTileMapping(xCosM, i);\n        graph.setTileMapping(xCosSq, i);\n        graph.setTileMapping(xCosSqI, i);\n\n        auto [computeJac, jac] = product(graph, updM, xCosM, i);\n        op.add(Execute(computeJac));\n\n        Tensor updM2Flat =\n            graph.addConstant<float>(FLOAT, {4, 1}, {1., 0., 0., 1.});\n\n        Tensor updM2 = graph.addVariable(FLOAT, {2, 2});\n\n        graph.setTileMapping(updM2Flat, i);\n        graph.setTileMapping(updM2, i);\n\n        updM2 = updM2Flat.reshape({2, 2});\n\n        auto [computeAddJacUpd, jac_upd] = scaledAdd(graph, jac, updM2, i);\n        op.add(Execute(computeAddJacUpd));\n\n        op.add(Copy(jac_upd, jacs[i]));\n\n    }\n\n    return std::make_tuple(op, jacs);\n\n} //~ end KalmanFilter::jacobian\n\n\nstd::tuple<Sequence, std::vector<Tensor>>\nKalmanFilter::projectEKF(Graph &graph,\n                         const std::vector<Tensor> &jacs,\n                         const std::vector<Tensor> &qs,\n                         std::vector<Tensor> &covs)\n{\n\n    Sequence op;\n\n    std::vector<Tensor> outC(covs.size());\n\n    for (uint i = 0; i < jacs.size(); i++)\n    {\n\n        outC[i] = graph.addVariable(FLOAT, {2, 2});\n        graph.setTileMapping(outC[i], i);\n\n        auto [computeCovT1, covT1] = product(graph, jacs[i], covs[i], i);\n        op.add(Execute(computeCovT1));\n\n        Tensor jacsT = jacs[i].transpose();\n        graph.setTileMapping(jacsT, i);\n\n        auto [computeCovT2, covT2] = product(graph, covT1, jacsT, i);\n        op.add(Execute(computeCovT2));\n\n        auto [computeAddCovQ, covQ] = scaledAdd(graph, covT2, qs[i], i);\n        op.add(Execute(computeAddCovQ));\n\n        op.add(Copy(covQ, outC[i]));\n\n    }\n\n    return std::make_tuple(op, outC);\n\n} //~ end KalmanFilter::projectEKF\n\n\nstd::tuple<Sequence, std::vector<Tensor>, std::vector<Tensor>>\nKalmanFilter::project(Graph &graph,\n                      const std::vector<Tensor> &ps,\n                      const std::vector<Tensor> &C,\n                      const std::vector<Tensor> &F,\n                      const std::vector<Tensor> &Q)\n{\n\n    Sequence op;\n\n    std::vector<Tensor> outP(ps.size());\n    std::vector<Tensor> outC(ps.size());\n\n    for (uint i = 0; i < outP.size(); i++)\n    {\n\n        auto [computePproj, p_proj] = product(graph, F[i], ps[i], i);\n        op.add(Execute(computePproj));\n\n        auto [computeFC, fc] = product(graph, F[i], C[i], i);\n        op.add(Execute(computeFC));\n\n        // Check this works wrt tile mapping\n        auto [computeFCF, fcf] = product(graph, fc, F[i].transpose(), i);\n        op.add(Execute(computeFCF));\n\n        auto [computeCproj, c_proj] = scaledAdd(graph, fcf, Q[i], i);\n        op.add(Execute(computeCproj));\n\n        outC[i] = graph.addVariable(FLOAT, {4, 4});\n        outP[i] = graph.addVariable(FLOAT, {4, 1});\n\n        graph.setTileMapping(outP[i], i);\n        graph.setTileMapping(outC[i], i);\n\n        op.add(Copy(c_proj, outC[i]));\n        op.add(Copy(p_proj, outP[i]));\n\n    }\n\n    return std::make_tuple(op, outP, outC);\n\n} //~ end KalmanFilter::project\n\n\nstd::tuple<Sequence, std::vector<Tensor>>\nKalmanFilter::packIterationTensors(Graph &graph,\n                                   const std::vector<Tensor> &loop,\n                                   const std::vector<Tensor> &scatterInto,\n                                   const std::vector<Tensor> &inputs)\n{\n\n    Sequence op;\n    std::vector<Tensor> hits_packed(inputs.size());\n\n    for (uint i = 0; i < inputs.size(); i++)\n    {\n\n        std::string iStr = std::to_string(i);\n\n        hits_packed[i] = graph.addVariable(FLOAT, {4, 1}, \"hits_packed\" + iStr);\n        graph.setTileMapping(hits_packed[i], i);\n\n        auto [computeH, h] = packHits(graph, inputs[i], loop[i], i);\n        op.add(Execute(computeH));\n        op.add(Copy(h, hits_packed[i]));\n\n    }\n\n    return std::make_tuple(op, hits_packed);\n\n} //~ end KalmanFilter::packIterationTensors\n\n// Residual at step t\nstd::tuple<Sequence, std::vector<Tensor>>\nKalmanFilter::calcResidual(Graph &graph,\n                           const std::vector<Tensor> &hits,\n                           const std::vector<Tensor> &p_filt,\n                           const std::vector<Tensor> &H)\n{\n\n    Sequence op;\n    std::vector<Tensor> res_out(p_filt.size());\n\n    for (uint i = 0; i < res_out.size(); i++)\n    {\n\n        std::string iStr = std::to_string(i);\n\n        res_out[i] = graph.addVariable(FLOAT, {4, 1}, \"res\" + iStr);\n        graph.setTileMapping(res_out[i], i);\n\n        auto [computeHp, Hp] = product(graph, H[i], p_filt[i], i);\n        op.add(Execute(computeHp));\n\n        // Scaled add with prefactor of -1\n        auto [computeRes, res] = scaledAdd(graph, hits[i], Hp, i, -1.0, \"res\");\n        op.add(Execute(computeRes));\n        op.add(Copy(res, res_out[i]));\n\n    }\n\n    return std::make_tuple(op, res_out);\n\n} //~ end KalmanFilter::calcResidual\n\n// ChiSq for a plane of hits\nstd::tuple<Sequence, std::vector<Tensor>>\nKalmanFilter::calcChiSq(Graph &graph,\n                        const std::vector<Tensor> &res_filt,\n                        const std::vector<Tensor> &G,\n                        const std::vector<Tensor> &C_proj,\n                        const std::vector<Tensor> &p_proj,\n                        const std::vector<Tensor> &p_filt)\n{\n\n    Sequence op;\n    std::vector<Tensor> chiSq(p_filt.size());\n\n    for (uint i = 0; i < chiSq.size(); i++)\n    {\n\n        std::string iStr = std::to_string(i);\n\n        Tensor rT = res_filt[i].transpose();\n        graph.setTileMapping(rT, i);\n\n        auto [computeRTG, rTG] = product(graph, rT, G[i], i);\n        op.add(Execute(computeRTG));\n\n        auto [computeResTerm, resTerm] = product(graph, rTG, res_filt[i], i);\n        op.add(Execute(computeResTerm));\n\n        auto [computeStateDiff, stateDiff] =\n            scaledAdd(graph, p_filt[i], p_proj[i], i, -1.0);\n        op.add(Execute(computeStateDiff));\n\n        auto [computeInverseC, C_inv] = inverse(graph, C_proj[i], i, 4);\n        op.add(Execute(computeInverseC));\n\n        Tensor diffT = stateDiff.transpose();\n        graph.setTileMapping(diffT, i);\n\n        auto [computeStateTC, stateTC] = product(graph, diffT, C_inv, i);\n        op.add(Execute(computeStateTC));\n\n        auto [computeStateTerm, stateTerm] =\n            product(graph, stateTC, stateDiff, i);\n        op.add(Execute(computeStateTerm));\n\n        auto [computeChiSqTot, chiSqTot] =\n            scaledAdd(graph, resTerm, stateTerm, i, 1.0);\n        op.add(Execute(computeChiSqTot));\n\n        chiSq[i] = graph.addVariable(FLOAT, {1}, \"chiSq\" + iStr);\n        graph.setTileMapping(chiSq[i], i);\n\n        op.add(Copy(chiSqTot, chiSq[i]));\n\n    }\n\n    return std::make_tuple(op, chiSq);\n\n} //~ end KalmanFilter::calcChiSq\n\n\nstd::tuple<Sequence, std::vector<Tensor>>\nKalmanFilter::chiSqTest(Graph &graph,\n                        const std::vector<Tensor> &chiSq,\n                        const std::vector<Tensor> &threshold)\n{\n\n    Sequence op;\n    std::vector<Tensor> chiSqPred(chiSq.size());\n\n    for (uint i = 0; i < chiSqPred.size(); i++)\n    {\n\n        std::string iStr = std::to_string(i);\n\n        chiSqPred[i] = popops::map(graph,\n                                   popops::expr::BinaryOpType::GREATER_THAN,\n                                   chiSq[i], threshold[i], op);\n\n        graph.setTileMapping(chiSqPred[i], i);\n\n    }\n\n    return std::make_tuple(op, chiSqPred);\n\n} //~ end KalmanFilter::chiSqTest\n\n\nstd::tuple<Sequence, std::vector<Tensor>, std::vector<Tensor>>\nKalmanFilter::smooth(Graph &graph,\n                     const std::vector<Tensor> &p_smooth_prev,\n                     const std::vector<Tensor> &C_smooth_prev,\n                     const std::vector<Tensor> &p_filt,\n                     const std::vector<Tensor> &C_filt,\n                     const std::vector<Tensor> &p_proj,\n                     const std::vector<Tensor> &C_proj,\n                     const std::vector<Tensor> &F)\n{\n\n    Sequence op;\n\n    std::vector<Tensor> p_smoothOut(p_filt.size());\n    std::vector<Tensor> C_smoothOut(p_filt.size());\n\n    for (uint i = 0; i < p_filt.size(); i++)\n    {\n\n        std::string iStr = std::to_string(i);\n\n        // Compute A\n\n        auto [computeInverseC_proj, invOutC_proj] = inverse(graph, C_proj[i], i, 4);\n        op.add(Execute(computeInverseC_proj));\n\n        auto [computeFC, fc] = product(graph, F[i].transpose(), invOutC_proj, i);\n        op.add(Execute(computeFC));\n\n        auto [computeA, a] = product(graph, C_filt[i], fc, i);\n        op.add(Execute(computeA));\n\n        auto [computePDiff, pDiff] =\n            scaledAdd(graph, p_smooth_prev[i], p_proj[i], i, -1);\n        op.add(Execute(computePDiff));\n\n        auto [computeCDiff, cDiff] =\n            scaledAdd(graph, C_smooth_prev[i], C_proj[i], i, -1);\n        op.add(Execute(computeCDiff));\n\n        auto [computeAPDiff, aPDiff] = product(graph, a, pDiff, i);\n        op.add(Execute(computeAPDiff));\n\n        auto [computeP_smooth, p_smooth] = scaledAdd(graph, p_filt[i], aPDiff, i);\n        op.add(Execute(computeP_smooth));\n\n        auto [computeCdiffA, cDiffA] = product(graph, cDiff, a.transpose(), i);\n        op.add(Execute(computeCdiffA));\n\n        auto [computeACdiffA, aCDiffA] = product(graph, a, cDiffA, i);\n        op.add(Execute(computeACdiffA));\n\n        auto [computeC_smooth, C_smooth] = scaledAdd(graph, C_filt[i], aCDiffA, i);\n        op.add(Execute(computeC_smooth));\n\n        p_smoothOut[i] = graph.addVariable(FLOAT, {4, 1}, \"p_smooth\" + iStr);\n        C_smoothOut[i] = graph.addVariable(FLOAT, {4, 4}, \"C_smooth\" + iStr);\n\n        graph.setTileMapping(p_smoothOut[i], i);\n        graph.setTileMapping(C_smoothOut[i], i);\n\n        op.add(Copy(p_smooth, p_smoothOut[i]));\n        op.add(Copy(C_smooth, C_smoothOut[i]));\n\n    }\n\n    return std::make_tuple(op, p_smoothOut, C_smoothOut);\n\n} //~ end KalmanFilter::smooth\n", "meta": {"hexsha": "c8865c736fd80c5a62cadd3fbfe591bfd383789f", "size": 24281, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "poplar_kalman_filter/KalmanFilter.cpp", "max_stars_repo_name": "altanner/HLT_20", "max_stars_repo_head_hexsha": "9aef6107c263db4d48be73089607f59cb803408f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "poplar_kalman_filter/KalmanFilter.cpp", "max_issues_repo_name": "altanner/HLT_20", "max_issues_repo_head_hexsha": "9aef6107c263db4d48be73089607f59cb803408f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "poplar_kalman_filter/KalmanFilter.cpp", "max_forks_repo_name": "altanner/HLT_20", "max_forks_repo_head_hexsha": "9aef6107c263db4d48be73089607f59cb803408f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5389294404, "max_line_length": 89, "alphanum_fraction": 0.5829249207, "num_tokens": 6485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.20037919417851444}}
{"text": "/*\n Copyright (C) 2020 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License.  You should have received a\n copy of the license along with this program.\n The license is also available online at <http://opensourcerisk.org>\n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#include <orea/aggregation/dimcalculator.hpp>\n#include <ored/utilities/log.hpp>\n#include <ored/utilities/vectorutils.hpp>\n#include <ql/errors.hpp>\n#include <ql/time/calendars/weekendsonly.hpp>\n#include <ql/version.hpp>\n\n#include <ql/math/distributions/normaldistribution.hpp>\n#include <ql/math/generallinearleastsquares.hpp>\n#include <ql/math/kernelfunctions.hpp>\n#include <ql/methods/montecarlo/lsmbasissystem.hpp>\n#include <ql/time/daycounters/actualactual.hpp>\n\n#include <qle/math/nadarayawatson.hpp>\n#include <qle/math/stabilisedglls.hpp>\n\n#include <boost/accumulators/accumulators.hpp>\n#include <boost/accumulators/statistics/error_of_mean.hpp>\n#include <boost/accumulators/statistics/mean.hpp>\n#include <boost/accumulators/statistics/stats.hpp>\n\nusing namespace std;\nusing namespace QuantLib;\n\nusing namespace boost::accumulators;\n\nnamespace ore {\nnamespace analytics {\n\nDynamicInitialMarginCalculator::DynamicInitialMarginCalculator(\n    const boost::shared_ptr<Portfolio>& portfolio, const boost::shared_ptr<NPVCube>& cube,\n    const boost::shared_ptr<CubeInterpretation>& cubeInterpretation,\n    const boost::shared_ptr<AggregationScenarioData>& scenarioData, Real quantile, Size horizonCalendarDays,\n    const std::map<std::string, Real>& currentIM)\n    : portfolio_(portfolio), cube_(cube), cubeInterpretation_(cubeInterpretation), scenarioData_(scenarioData),\n      quantile_(quantile), horizonCalendarDays_(horizonCalendarDays), currentIM_(currentIM) {\n\n    QL_REQUIRE(portfolio_, \"portfolio is null\");\n    QL_REQUIRE(cube_, \"cube is null\");\n    QL_REQUIRE(cubeInterpretation_, \"cube interpretation is null\");\n    QL_REQUIRE(scenarioData_, \"aggregation scenario data is null\");\n\n    boost::shared_ptr<RegularCubeInterpretation> regCubeInt =\n        boost::dynamic_pointer_cast<RegularCubeInterpretation>(cubeInterpretation_);\n    cubeIsRegular_ = (regCubeInt != NULL);\n    datesLoopSize_ = cubeIsRegular_ ? cube_->dates().size() - 1 : cube_->dates().size();\n\n    Size dates = cube_->dates().size();\n    Size samples = cube_->samples();\n\n    if (!cubeInterpretation_->hasMporFlows(cube_)) {\n        WLOG(\"cube holds no mpor flows, will assume no flows in the dim calculation\");\n    }\n\n    // initialise aggregate NPV and Flow by date and scenario\n    set<string> nettingSets;\n    for (Size i = 0; i < portfolio_->size(); ++i) {\n        string tradeId = portfolio_->trades()[i]->id();\n        string nettingSetId = portfolio_->trades()[i]->envelope().nettingSetId();\n        if (nettingSets.find(nettingSetId) == nettingSets.end()) {\n            nettingSets.insert(nettingSetId);\n            nettingSetNPV_[nettingSetId] = vector<vector<Real>>(dates, vector<Real>(samples, 0.0));\n            nettingSetCloseOutNPV_[nettingSetId] = vector<vector<Real>>(dates, vector<Real>(samples, 0.0));\n            nettingSetFLOW_[nettingSetId] = vector<vector<Real>>(dates, vector<Real>(samples, 0.0));\n            nettingSetDeltaNPV_[nettingSetId] = vector<vector<Real>>(dates, vector<Real>(samples, 0.0));\n            nettingSetDIM_[nettingSetId] = vector<vector<Real>>(dates, vector<Real>(samples, 0.0));\n            nettingSetExpectedDIM_[nettingSetId] = vector<Real>(dates, 0.0);\n        }\n        for (Size j = 0; j < datesLoopSize_; ++j) {\n            for (Size k = 0; k < samples; ++k) {\n                Real defaultNpv = cubeInterpretation_->getDefaultNpv(cube_, i, j, k);\n                Real closeOutNpv = cubeInterpretation_->getCloseOutNpv(cube_, i, j, k);\n                Real mporFlow =\n                    cubeInterpretation_->hasMporFlows(cube_) ? cubeInterpretation_->getMporFlows(cube_, i, j, k) : 0.0;\n                nettingSetNPV_[nettingSetId][j][k] += defaultNpv;\n                nettingSetCloseOutNPV_[nettingSetId][j][k] += closeOutNpv;\n                nettingSetFLOW_[nettingSetId][j][k] += mporFlow;\n            }\n        }\n    }\n\n    for (auto n : nettingSets)\n        nettingSetIds_.push_back(n);\n\n    dimCube_ = boost::make_shared<SinglePrecisionInMemoryCube>(cube_->asof(), nettingSetIds_, cube_->dates(),\n                                                               cube_->samples());\n}\n\nconst vector<vector<Real>>& DynamicInitialMarginCalculator::dynamicIM(const std::string& nettingSet) {\n    if (nettingSetDIM_.find(nettingSet) != nettingSetDIM_.end())\n        return nettingSetDIM_[nettingSet];\n    else\n        QL_FAIL(\"netting set \" << nettingSet << \" not found in DIM results\");\n}\n\nconst vector<Real>& DynamicInitialMarginCalculator::expectedIM(const std::string& nettingSet) {\n    if (nettingSetExpectedDIM_.find(nettingSet) != nettingSetExpectedDIM_.end())\n        return nettingSetExpectedDIM_[nettingSet];\n    else\n        QL_FAIL(\"netting set \" << nettingSet << \" not found in expected DIM results\");\n}\n\nconst vector<vector<Real>>& DynamicInitialMarginCalculator::cashFlow(const std::string& nettingSet) {\n    if (nettingSetFLOW_.find(nettingSet) != nettingSetFLOW_.end())\n        return nettingSetFLOW_[nettingSet];\n    else\n        QL_FAIL(\"netting set \" << nettingSet << \" not found in DIM results\");\n}\n\nvoid DynamicInitialMarginCalculator::exportDimEvolution(ore::data::Report& dimEvolutionReport) {\n\n    Size samples = dimCube_->samples();\n    Size stopDatesLoop = datesLoopSize_;\n    Date asof = cube_->asof();\n\n    dimEvolutionReport.addColumn(\"TimeStep\", Size())\n        .addColumn(\"Date\", Date())\n        .addColumn(\"DaysInPeriod\", Size())\n        .addColumn(\"AverageDIM\", Real(), 6)\n        .addColumn(\"AverageFLOW\", Real(), 6)\n        .addColumn(\"NettingSet\", string())\n        .addColumn(\"Time\", Real(), 6);\n\n    for (auto nettingSet : dimCube_->ids()) {\n\n        LOG(\"Export DIM evolution for netting set \" << nettingSet);\n        for (Size i = 0; i < stopDatesLoop; ++i) {\n            Real expectedFlow = 0.0;\n            for (Size j = 0; j < samples; ++j) {\n                expectedFlow += nettingSetFLOW_[nettingSet][i][j] / samples;\n            }\n\n            Date defaultDate = dimCube_->dates()[i];\n\t    Time t = ActualActual().yearFraction(asof, defaultDate);\n            Size days = cubeInterpretation_->getMporCalendarDays(dimCube_, i);\n            dimEvolutionReport.next()\n                .add(i)\n                .add(defaultDate)\n                .add(days)\n                .add(nettingSetExpectedDIM_[nettingSet][i])\n                .add(expectedFlow)\n                .add(nettingSet)\n\t        .add(t);\n        }\n    }\n    dimEvolutionReport.end();\n    LOG(\"Exporting expected DIM through time done\");\n}\n\n} // namespace analytics\n} // namespace ore\n", "meta": {"hexsha": "a95f3512a0e766038746e8c8c75d7fa0764bef89", "size": 7268, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "OREAnalytics/orea/aggregation/dimcalculator.cpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "OREAnalytics/orea/aggregation/dimcalculator.cpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "OREAnalytics/orea/aggregation/dimcalculator.cpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 42.7529411765, "max_line_length": 119, "alphanum_fraction": 0.6792790314, "num_tokens": 1819, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.3380771308191988, "lm_q1q2_score": 0.20036701878013832}}
{"text": "/*!@file\n * @copyright This code is licensed under the 3-clause BSD license.\n *   Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n *   See LICENSE.txt for details.\n */\n\n#include \"Molassembler/DistanceGeometry/ConformerGeneration.h\"\n\n#include <Eigen/Dense>\n#include \"Utils/Constants.h\"\n#include \"Utils/Typenames.h\"\n\n#include \"Molassembler/BondStereopermutator.h\"\n#include \"Molassembler/DistanceGeometry/EigenRefinement.h\"\n#include \"Molassembler/DistanceGeometry/Error.h\"\n#include \"Molassembler/DistanceGeometry/ExplicitBoundsGraph.h\"\n#include \"Molassembler/DistanceGeometry/MetricMatrix.h\"\n#include \"Molassembler/DistanceGeometry/RefinementMeta.h\"\n#include \"Molassembler/Graph/GraphAlgorithms.h\"\n#include \"Utils/Math/QuaternionFit.h\"\n\n#include \"Molassembler/Detail/Cartesian.h\"\n#include \"Molassembler/Temple/Optimization/Lbfgs.h\"\n#include \"Molassembler/Temple/Optionals.h\"\n#include \"Molassembler/Temple/Functional.h\"\n#include \"Molassembler/Temple/Random.h\"\n\n#include <iostream>\n\nnamespace Scine {\nnamespace Molassembler {\nnamespace DistanceGeometry {\nnamespace Detail {\n\nEigen::MatrixXd gather(const Eigen::VectorXd& vectorizedPositions) {\n  constexpr unsigned dimensionality = 4;\n  const unsigned N = vectorizedPositions.size() / dimensionality;\n  Eigen::MatrixXd positionMatrix(N, 3);\n  for(unsigned i = 0; i < N; ++i) {\n    positionMatrix.row(i) = vectorizedPositions.template segment<3>(dimensionality * i);\n  }\n  return positionMatrix;\n}\n\nAngstromPositions convertToAngstromPositions(const Eigen::MatrixXd& positions) {\n  assert(positions.cols() == 3);\n  const unsigned N = positions.rows();\n  AngstromPositions angstromWrapper {N};\n  for(unsigned i = 0; i < N; ++i) {\n    angstromWrapper.positions.row(i) = Utils::Position {\n      positions.row(i).transpose()\n    };\n  }\n  return angstromWrapper;\n}\n\nEigen::MatrixXd fitAndSetFixedPositions(\n  const Eigen::MatrixXd& positions,\n  const Configuration& configuration\n) {\n  /* Fixed positions postprocessing:\n   * - Rotate and translate the generated coordinates towards the fixed\n   *   positions indicated for each.\n   *\n   * Maybe?\n   * - Assuming the fit isn't absolutely exact, overwrite the existing\n   *   positions with the fixed ones\n   */\n  /* Construct a reference matrix from the fixed positions (these are still in\n   * bohr!) and a weights vector\n   */\n  assert(positions.cols() == 3);\n  const unsigned N = positions.rows();\n  Eigen::MatrixXd referenceMatrix = Eigen::MatrixXd::Zero(N, 3);\n  Eigen::VectorXd weights = Eigen::VectorXd::Zero(N);\n  for(const auto& indexPositionPair : configuration.fixedPositions) {\n    referenceMatrix.row(indexPositionPair.first) = indexPositionPair.second.transpose();\n    weights(indexPositionPair.first) = 1;\n  }\n\n  referenceMatrix *= Utils::Constants::angstrom_per_bohr;\n\n  // Perform the QuaternionFit\n  Utils::QuaternionFit fit(referenceMatrix, positions, weights);\n\n  return fit.getFittedData();\n}\n\nMolecule narrow(Molecule molecule, Random::Engine& engine) {\n  const auto& stereopermutatorList = molecule.stereopermutators();\n\n  do {\n    /* If we change any stereopermutator, we must re-check if there are still\n     * unassigned stereopermutators since assigning a stereopermutator can\n     * invalidate the entire stereopermutator list (because stereopermutators\n     * may appear or disappear on assignment due to ranking)\n     */\n    std::vector<AtomIndex> unassignedAtomStereopermutators;\n\n    for(const auto& atomStereopermutator : stereopermutatorList.atomStereopermutators()) {\n      if(!atomStereopermutator.assigned()) {\n        unassignedAtomStereopermutators.push_back(\n          atomStereopermutator.placement()\n        );\n      }\n    }\n\n    if(!unassignedAtomStereopermutators.empty()) {\n      molecule.assignStereopermutatorRandomly(\n        Temple::Random::pick(unassignedAtomStereopermutators, engine),\n        engine\n      );\n\n      // Re-check the loop condition\n      continue;\n    }\n\n    std::vector<BondIndex> unassignedBondStereopermutators;\n\n    for(const auto& bondStereopermutator : stereopermutatorList.bondStereopermutators()) {\n      if(!bondStereopermutator.assigned()) {\n        unassignedBondStereopermutators.push_back(\n          bondStereopermutator.placement()\n        );\n      }\n    }\n\n    if(!unassignedBondStereopermutators.empty()) {\n      molecule.assignStereopermutatorRandomly(\n        Temple::Random::pick(unassignedBondStereopermutators, engine),\n        engine\n      );\n    }\n\n  } while(stereopermutatorList.hasUnassignedStereopermutators());\n\n  return molecule;\n}\n\ntemplate<typename EigenRefinementType>\nstruct InversionOrIterLimitStop {\n  using VectorType = typename EigenRefinementType::VectorType;\n  using FloatType = typename EigenRefinementType::FloatingPointType;\n\n  InversionOrIterLimitStop(\n    const unsigned passIter,\n    const EigenRefinementType& functor\n  ) : iterLimit(passIter),\n      refinementFunctorReference(functor)\n  {}\n\n  template<typename StepValues>\n  bool shouldContinue(unsigned iteration, const StepValues& step) {\n    return (\n      iteration < iterLimit\n      && refinementFunctorReference.proportionChiralConstraintsCorrectSign < 1.0\n      && (step.parameters.proposed - step.parameters.current).norm() > minParameterDiffNorm\n    );\n  }\n\n  const unsigned iterLimit;\n  const EigenRefinementType& refinementFunctorReference;\n  double minParameterDiffNorm = 1e-3;\n};\n\ntemplate<typename FloatType>\nstruct GradientOrIterLimitStop {\n  using VectorType = Eigen::Matrix<FloatType, Eigen::Dynamic, 1>;\n\n  template<typename StepValues>\n  bool shouldContinue(unsigned iteration, const StepValues& step) {\n    return (\n      iteration < iterLimit\n      && step.gradients.current.template cast<double>().norm() > gradNorm\n      && (step.parameters.proposed - step.parameters.current).norm() > minParameterDiffNorm\n    );\n  }\n\n  unsigned iterLimit = 10000;\n  double gradNorm = 1e-5;\n  double minParameterDiffNorm = 1e-3;\n};\n\ntemplate<unsigned dimensionality>\nEigen::Vector3d averagePosition(\n  const Eigen::VectorXd& linearPositions,\n  const std::vector<AtomIndex>& indices\n) {\n  if(indices.size() == 1) {\n    return linearPositions.template segment<3>(dimensionality * indices.front());\n  }\n\n  Eigen::Vector3d average = Eigen::Vector3d::Zero();\n  for(AtomIndex i : indices) {\n    average += linearPositions.template segment<3>(dimensionality * i);\n  }\n  average /= indices.size();\n  return average;\n}\n\ntemplate<unsigned dimensionality>\nvoid twistRotatableDihedrals(\n  Eigen::Ref<Eigen::VectorXd> positions,\n  const std::vector<DihedralConstraint>& constraints,\n  const MoleculeDGInformation::GroupMapType& rotatableGroupMap\n) {\n  for(const DihedralConstraint& constraint : constraints) {\n    const AtomIndex j = constraint.sites.at(1).front();\n    const AtomIndex k = constraint.sites.at(2).front();\n    BondIndex bond {j, k};\n\n    const auto findIter = rotatableGroupMap.find(bond);\n    if(findIter == std::end(rotatableGroupMap)) {\n      continue;\n    }\n\n    const MoleculeDGInformation::RotatableGroup& group = findIter->second;\n\n    const Eigen::Vector3d jVector = positions.template segment<3>(dimensionality * j);\n    const Eigen::Vector3d kVector = positions.template segment<3>(dimensionality * k);\n\n    const double measuredDihedral = Cartesian::dihedral(\n      averagePosition<dimensionality>(positions, constraint.sites.at(0)),\n      jVector,\n      kVector,\n      averagePosition<dimensionality>(positions, constraint.sites.at(3))\n    );\n\n    const double targetDihedral = Cartesian::dihedralAverage(\n      constraint.lower,\n      constraint.upper\n    );\n\n    Eigen::Vector3d axisVector = (kVector - jVector).normalized();\n    if(group.side == j) {\n      axisVector *= -1;\n    }\n\n    const Eigen::Matrix3d rotation = Eigen::AngleAxisd {\n      targetDihedral - measuredDihedral,\n      axisVector\n    }.toRotationMatrix();\n\n    const Eigen::Vector3d sideVector = positions.template segment<3>(dimensionality * group.side);\n    for(AtomIndex i : group.vertices) {\n      positions.template segment<3>(dimensionality * i) = sideVector + rotation * (\n        positions.template segment<3>(dimensionality * i) - sideVector\n      );\n    }\n  }\n}\n\n} // namespace Detail\n\nMoleculeDGInformation::GroupMapType MoleculeDGInformation::make(\n  const std::vector<DihedralConstraint>& constraints,\n  const Molecule& molecule\n) {\n  MoleculeDGInformation::GroupMapType groups;\n\n  Temple::forEach(constraints,\n    [&](const DihedralConstraint& constraint) {\n      // It is guaranteed that the sites in the middle have one index only\n      BondIndex bond {\n        constraint.sites.at(1).front(),\n        constraint.sites.at(2).front(),\n      };\n\n      // Populate with group to rotate information on the smaller side\n      if(molecule.graph().cycles().numCycleFamilies(bond) == 0) {\n        auto sides = molecule.graph().splitAlongBridge(bond);\n        if(sides.first.size() < sides.second.size()) {\n          groups.emplace(\n            bond,\n            MoleculeDGInformation::RotatableGroup {bond.first, sides.first}\n          );\n        } else {\n          groups.emplace(\n            bond,\n            MoleculeDGInformation::RotatableGroup {bond.second, sides.second}\n          );\n        }\n      }\n    }\n  );\n\n  return groups;\n}\n\n\nMoleculeDGInformation gatherDGInformation(\n  const Molecule& molecule,\n  const Configuration& configuration\n) {\n  // Generate a spatial model from the molecular graph and stereopermutators\n  SpatialModel spatialModel {molecule, configuration};\n\n  // Extract gathered data\n  MoleculeDGInformation data;\n  data.bounds = spatialModel.makePairwiseBounds();\n  data.chiralConstraints = spatialModel.getChiralConstraints();\n  data.dihedralConstraints = spatialModel.getDihedralConstraints();\n  data.rotatableGroups = MoleculeDGInformation::make(data.dihedralConstraints, molecule);\n\n  return data;\n}\n\noutcome::result<AngstromPositions> refine(\n  Eigen::MatrixXd embeddedPositions,\n  const DistanceBoundsMatrix& distanceBounds,\n  const Configuration& configuration,\n  const std::shared_ptr<MoleculeDGInformation>& DgDataPtr\n) {\n  /* Refinement problem compile-time settings\n   * - Dimensionality four is needed to ensure chiral constraints invert\n   *   nicely\n   * - FloatType double is helpful for refinement stability, and float\n   *   doesn't affect speed\n   * - Using the alternative SIMD implementations of the refinement problems\n   *   hardly affects speed at all, in fact, it commonly worsens it.\n   */\n  constexpr unsigned dimensionality = 4;\n  using FloatType = double;\n  constexpr bool SIMD = false;\n\n  using FullRefinementType = EigenRefinementProblem<dimensionality, FloatType, SIMD>;\n  using VectorType = typename FullRefinementType::VectorType;\n\n  // Vectorize positions\n  VectorType transformedPositions = Eigen::Map<Eigen::VectorXd>(\n    embeddedPositions.data(),\n    embeddedPositions.cols() * embeddedPositions.rows()\n  ).template cast<FloatType>().eval();\n\n  const unsigned N = transformedPositions.size() / dimensionality;\n\n  const auto squaredBounds = static_cast<Eigen::MatrixXd>(\n    distanceBounds.access().cwiseProduct(distanceBounds.access())\n  );\n\n  FullRefinementType refinementFunctor {\n    squaredBounds,\n    DgDataPtr->chiralConstraints,\n    DgDataPtr->dihedralConstraints\n  };\n\n  /* If a count of chiral constraints reveals that more than half are\n   * incorrect, we can invert the structure (by multiplying e.g. all y\n   * coordinates with -1) and then have more than half of chirality\n   * constraints correct! In the count, chiral constraints with a target\n   * value of zero are not considered (this would skew the count as those\n   * chiral constraints should not have to pass an energetic maximum to\n   * converge properly as opposed to tetrahedra with volume).\n   */\n  double initiallyCorrectChiralConstraints = refinementFunctor.calculateProportionChiralConstraintsCorrectSign(transformedPositions);\n  if(initiallyCorrectChiralConstraints < 0.5) {\n    // Invert y coordinates\n    for(unsigned i = 0; i < N; ++i) {\n      transformedPositions(dimensionality * i + 1) *= -1;\n    }\n\n    initiallyCorrectChiralConstraints = 1 - initiallyCorrectChiralConstraints;\n  }\n\n  /* Refinement without penalty on fourth dimension only necessary if not all\n   * chiral centers are correct. Of course, for molecules without chiral\n   * centers at all, this stage is unnecessary\n   */\n  unsigned firstStageIterations = 0;\n  if(initiallyCorrectChiralConstraints < 1) {\n    Detail::InversionOrIterLimitStop<FullRefinementType> inversionChecker {\n      configuration.refinementStepLimit,\n      refinementFunctor\n    };\n\n    Temple::Lbfgs<FloatType, 32> optimizer;\n\n    try {\n      auto result = optimizer.minimize(\n        transformedPositions,\n        refinementFunctor,\n        inversionChecker\n      );\n      firstStageIterations = result.iterations;\n    } catch(std::runtime_error& e) {\n      return DgError::RefinementException;\n    }\n\n    if(firstStageIterations >= configuration.refinementStepLimit) {\n      return DgError::RefinementMaxIterationsReached;\n    }\n\n    if(refinementFunctor.proportionChiralConstraintsCorrectSign < 1.0) {\n      return DgError::RefinedChiralsWrong;\n    }\n  }\n\n  /* Set up the second stage of refinement where we compress out the fourth\n   * dimension that we allowed expansion into to invert the chiralities.\n   */\n  refinementFunctor.compressFourthDimension = true;\n\n  unsigned secondStageIterations = 0;\n  Detail::GradientOrIterLimitStop<FloatType> gradientChecker;\n  gradientChecker.gradNorm = 1e-3;\n  gradientChecker.iterLimit = configuration.refinementStepLimit - firstStageIterations;\n\n  try {\n    Temple::Lbfgs<FloatType, 32> optimizer;\n\n    auto result = optimizer.minimize(\n      transformedPositions,\n      refinementFunctor,\n      gradientChecker\n    );\n    secondStageIterations = result.iterations;\n  } catch(std::out_of_range& e) {\n    return DgError::RefinementException;\n  }\n\n  // Max iterations reached\n  if(secondStageIterations >= gradientChecker.iterLimit) {\n    return DgError::RefinementMaxIterationsReached;\n  }\n\n  // Not all chiral constraints have the right sign\n  if(refinementFunctor.proportionChiralConstraintsCorrectSign < 1) {\n    return DgError::RefinedChiralsWrong;\n  }\n\n  /* Twist all freely rotatable dihedrals to their target values to avoid\n   * conflicts between distance and dihedral errors to prevent rotations to\n   * target values.\n   */\n  Detail::twistRotatableDihedrals<dimensionality>(\n    transformedPositions,\n    DgDataPtr->dihedralConstraints,\n    DgDataPtr->rotatableGroups\n  );\n\n  /* Add dihedral terms and refine again */\n  unsigned thirdStageIterations = 0;\n  gradientChecker = Detail::GradientOrIterLimitStop<FloatType> {};\n  gradientChecker.gradNorm = 1e-3;\n  gradientChecker.iterLimit = (\n    configuration.refinementStepLimit\n    - firstStageIterations\n    - secondStageIterations\n  );\n\n  refinementFunctor.dihedralTerms = true;\n\n  try {\n    Temple::Lbfgs<FloatType, 32> optimizer;\n\n    auto result = optimizer.minimize(\n      transformedPositions,\n      refinementFunctor,\n      gradientChecker\n    );\n    thirdStageIterations = result.iterations;\n  } catch(std::out_of_range& e) {\n    return DgError::RefinementException;\n  }\n\n  if(thirdStageIterations >= gradientChecker.iterLimit) {\n    return DgError::RefinementMaxIterationsReached;\n  }\n\n  // Structure inacceptable\n  if(\n    !finalStructureAcceptable(\n      refinementFunctor,\n      distanceBounds,\n      transformedPositions\n    )\n  ) {\n    return DgError::RefinedStructureInacceptable;\n  }\n\n  auto gatheredPositions = Detail::gather(transformedPositions);\n\n  if(!configuration.fixedPositions.empty()) {\n    return Detail::convertToAngstromPositions(\n      Detail::fitAndSetFixedPositions(gatheredPositions, configuration)\n    );\n  }\n\n  return Detail::convertToAngstromPositions(gatheredPositions);\n}\n\noutcome::result<AngstromPositions> generateConformer(\n  const Molecule& molecule,\n  const Configuration& configuration,\n  std::shared_ptr<MoleculeDGInformation>& DgDataPtr,\n  bool regenerateDGDataEachStep,\n  Random::Engine& engine\n) {\n  if(regenerateDGDataEachStep) {\n    auto moleculeCopy = Detail::narrow(molecule, engine);\n\n    if(moleculeCopy.stereopermutators().hasZeroAssignmentStereopermutators()) {\n      return DgError::ZeroAssignmentStereopermutators;\n    }\n\n    DgDataPtr = std::make_shared<MoleculeDGInformation>(\n      gatherDGInformation(moleculeCopy, configuration)\n    );\n  }\n\n  ExplicitBoundsGraph explicitGraph {\n    molecule.graph().inner(),\n    DgDataPtr->bounds\n  };\n\n  // Get distance bounds matrix from the graph\n  auto distanceBoundsResult = explicitGraph.makeDistanceBounds();\n  if(!distanceBoundsResult) {\n    return distanceBoundsResult.as_failure();\n  }\n\n  DistanceBoundsMatrix distanceBounds {std::move(distanceBoundsResult.value())};\n\n  /* There should be no need to smooth the distance bounds, because the graph\n   * type ought to create them within the triangle inequality bounds:\n   */\n  assert(distanceBounds.boundInconsistencies() == 0);\n\n  // Generate a distances matrix from the graph\n  auto distanceMatrixResult = explicitGraph.makeDistanceMatrix(\n    engine,\n    configuration.partiality\n  );\n  if(!distanceMatrixResult) {\n    return distanceMatrixResult.as_failure();\n  }\n\n  // Make a metric matrix from the distances matrix\n  MetricMatrix metric(\n    std::move(distanceMatrixResult.value())\n  );\n\n  // Get a position matrix by embedding the metric matrix\n  auto embeddedPositions = metric.embed();\n\n  /* Refinement */\n  return refine(\n    std::move(embeddedPositions),\n    distanceBounds,\n    configuration,\n    DgDataPtr\n  );\n}\n\nstd::vector<\n  outcome::result<AngstromPositions>\n> run(\n  const Molecule& molecule,\n  const unsigned numConformers,\n  const Configuration& configuration,\n  const boost::optional<unsigned> seedOption\n) {\n  using ReturnType = std::vector<\n    outcome::result<AngstromPositions>\n  >;\n\n  // In case there are zero assignment stereopermutators, we give up immediately\n  if(molecule.stereopermutators().hasZeroAssignmentStereopermutators()) {\n    return ReturnType(numConformers, DgError::ZeroAssignmentStereopermutators);\n  }\n\n#ifdef _OPENMP\n  /* Ensure the molecule's mutable properties are already generated so none are\n   * generated on threaded const-access.\n   */\n  molecule.graph().inner().populateProperties();\n#endif\n\n  /* In case the molecule has unassigned stereopermutators, we need to randomly\n   * assign them for each conformer generated prior to generating the distance\n   * bounds matrix. If not, then modelling data can be kept across all\n   * conformer generation runs since no randomness has entered the equation.\n   */\n  auto DgDataPtr = std::make_shared<MoleculeDGInformation>();\n  bool regenerateEachStep = molecule.stereopermutators().hasUnassignedStereopermutators();\n  if(!regenerateEachStep) {\n    *DgDataPtr = gatherDGInformation(molecule, configuration);\n  }\n\n  ReturnType results(numConformers, static_cast<DgError>(0));\n\n  /* If a seed is supplied, the global prng state is not to be advanced.\n   * We create a random engine from the seed here if a seed is supplied.\n   */\n  auto engineOption = Temple::Optionals::map(\n    seedOption,\n    [](unsigned seed) { return Random::Engine(seed); }\n  );\n\n  /* Now we need something referencing either our new engine or the global prng\n   * engine.\n   */\n  std::reference_wrapper<Random::Engine> backgroundEngineWrapper = randomnessEngine();\n  if(engineOption) {\n    backgroundEngineWrapper = engineOption.value();\n  }\n  Random::Engine& backgroundEngine = backgroundEngineWrapper.get();\n\n  /* We have to distribute pseudo-randomness into each thread reproducibly\n   * and want to avoid having to guard the global PRNG against access from\n   * multiple threads, so we provide each thread its own Engine and pre-generate\n   * each conformer's individual seed in the sequential section.\n   */\n#ifdef _OPENMP\n  const unsigned nThreads = omp_get_max_threads();\n#else\n  const unsigned nThreads = 1;\n#endif\n\n  std::vector<Random::Engine> randomnessEngines(nThreads);\n  const auto seeds = Temple::Random::getN<int>(\n    0,\n    std::numeric_limits<int>::max(),\n    numConformers,\n    backgroundEngine\n  );\n\n  /* Each thread has its own DgDataPtr, for the following reason: If we do\n   * not need to regenerate the SpatialModel data, then having all threads\n   * share access the underlying data to generate conformers is fine. If,\n   * otherwise, we do need to regenerate the SpatialModel data for each\n   * conformer, then each thread will reset its pointer to its self-generated\n   * SpatialModel data, creating thread-private state.\n   */\n#pragma omp parallel for firstprivate(DgDataPtr) schedule(dynamic)\n  for(unsigned i = 0; i < numConformers; ++i) {\n    // Get thread-specific randomness engine reference\n#ifdef _OPENMP\n    Random::Engine& engine = randomnessEngines.at(\n      omp_get_thread_num()\n    );\n#else\n    Random::Engine& engine = randomnessEngines.front();\n#endif\n\n    // Re-seed the thread-local PRNG engine for each conformer\n    engine.seed(seeds.at(i));\n\n    /* We have to handle any and all exceptions here bceause this is a parallel\n     * environment and exceptions are not propagated anywhere\n     */\n    try {\n      // Generate the conformer\n      auto conformerResult = generateConformer(\n        molecule,\n        configuration,\n        DgDataPtr,\n        regenerateEachStep,\n        engine\n      );\n\n      results.at(i) = std::move(conformerResult);\n    } catch(std::exception& e) {\n#pragma omp critical(outputWarning)\n      {\n        std::cerr << \"WARNING: Uncaught exception in conformer generation: \" << e.what() << \"\\n\";\n      }\n      results.at(i) = DgError::UnknownException;\n    } // end catch\n  } // end pragma omp for private(DgDataPtr)\n\n  return results;\n}\n\n} // namespace DistanceGeometry\n} // namespace Molassembler\n} // namespace Scine\n", "meta": {"hexsha": "00b4e72e187477009b22b11f973dee893b063a3d", "size": 21789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Molassembler/DistanceGeometry/ConformerGeneration.cpp", "max_stars_repo_name": "Dom1L/molassembler", "max_stars_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2020-11-27T14:59:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T10:31:25.000Z", "max_issues_repo_path": "src/Molassembler/DistanceGeometry/ConformerGeneration.cpp", "max_issues_repo_name": "Dom1L/molassembler", "max_issues_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Molassembler/DistanceGeometry/ConformerGeneration.cpp", "max_forks_repo_name": "Dom1L/molassembler", "max_forks_repo_head_hexsha": "dafc656b1aa846b65b1fd1e06f3740ceedcf22db", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-12-09T09:21:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-22T15:42:21.000Z", "avg_line_length": 32.1371681416, "max_line_length": 133, "alphanum_fraction": 0.7278902198, "num_tokens": 5112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.3140505385717078, "lm_q1q2_score": 0.20005985976510193}}
{"text": "#ifndef LOGBROYDEN_HPP_\n#define LOGBROYDEN_HPP_\n\n#if defined(_MSC_VER)\n#pragma once\n#endif\n\n/*\n* LEGAL NOTICE\n* This computer software was prepared by Battelle Memorial Institute,\n* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830\n* with the Department of Energy ( DOE ). NEITHER THE GOVERNMENT NOR THE\n* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY\n* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this\n* sentence must appear on any copies of this computer software.\n* \n* EXPORT CONTROL\n* User agrees that the Software will not be shipped, transferred or\n* exported into any country or used in any manner prohibited by the\n* United States Export Administration Act or any other applicable\n* export laws, restrictions or regulations (collectively the \"Export Laws\").\n* Export of the Software may require some form of license or other\n* authority from the U.S. Government, and failure to obtain such\n* export control license may result in criminal liability under\n* U.S. laws. In addition, if the Software is identified as export controlled\n* items under the Export Laws, User represents and warrants that User\n* is not a citizen, or otherwise located within, an embargoed nation\n* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)\n*     and that User is not otherwise prohibited\n* under the Export Laws from receiving the Software.\n* \n* Copyright 2011 Battelle Memorial Institute.  All Rights Reserved.\n* Distributed as open-source under the terms of the Educational Community \n* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php\n* \n* For further details, see: http://www.globalchange.umd.edu/models/gcam/\n*\n*/\n\n/*!\n * \\file logbroyden.hpp\n * \\ingroup objects\n * \\brief Header file for the log Broyden solver component\n *\n * \\author Robert Link\n */\n\n#include <string>\n#include <boost/numeric/ublas/matrix.hpp>\n#include \"solution/util/include/solvable_nr_solution_info_filter.h\"\n#include \"solution/util/include/edfun.hpp\"\n#include \"solution/util/include/ublas-helpers.hpp\"\n\nclass CalcCounter; \nclass Marketplace;\nclass World;\nclass SolutionInfoSet;\n\n/*!\n * \\ingroup Objects \n * \\brief SolverComponent based on the Broyden algorithm using\n * logarithmic prices and EDs.\n *\n * \\details Broyden's method is exactly analogous to the\n * Newton-Raphson algorithm, including backtracking.  Broyden differs\n * from N-R in that it uses an approximate Jacobian matrix instead of\n * an exact one.  With each iteration step the approximate Jacobian is\n * updated using the secant formula.  For functions where we don't\n * have an analytic expression for the Jacobian (such as the GCAM\n * excess demand function), Broyden's method provides a huge advantage\n * over using finite-difference Jacobians.\n *\n * \\author Robert Link\n */\nclass LogBroyden: public SolverComponent {\npublic:\n  LogBroyden(Marketplace *mktplc, World *world, CalcCounter *ccounter, int itmax=250,\n             double ftol=1.0e-4) :\n      SolverComponent(mktplc,world,ccounter), mMaxIter( itmax ), mFTOL( ftol ),\n      mLogPricep( true ), mMaxJacobainReuse( 100 ) {}\n  virtual ~LogBroyden() {}\n\n  // SolverComponent methods\n  virtual void init() {\n    if(!mSolutionInfoFilter.get())\n      mSolutionInfoFilter.reset(new SolvableNRSolutionInfoFilter());\n  }\n  virtual ReturnCode solve( SolutionInfoSet& aSolutionSet, const int aPeriod );\n  virtual const std::string& getXMLName() const {return SOLVER_NAME;}\n  \n  // IParsable methods\n  virtual bool XMLParse( const xercesc::DOMNode* aNode );\n  \n  static const std::string & getXMLNameStatic( void ) {return SOLVER_NAME;}\n\nprotected:\n  //! Perform the Broyden's method iterations.\n  int bsolve(VecFVec &F, UBVECTOR &x, UBVECTOR &fx,\n             UBMATRIX &B, int &neval);\n  //! Additional logging for visualizing solver progress.\n  void reportVec(const std::string &aname, const UBVECTOR &av, const std::vector<int> &amktids,\n                 const std::vector<bool> &aissolvable);\n  void reportPSD(UBVECTOR &arptvec, const std::vector<int> &amktids, const std::vector<bool> &aissolvable);\n\n  //! Maximum number of main-loop iterations for the root-finding algorithm\n  unsigned int mMaxIter;\n\n  //! Tolerance for convergence test in root-finding algorithm \n  //! \\warning The SolutionInfo class has its own convergence\n  //! tolerance, which it uses to flag certain markets as \"unsolved\".\n  //! If that tolerance is different from this one, the SolutionInfo\n  //! might regard a market as unsolved when the solver says it's\n  //! solved, or vice versa.\n  double mFTOL;\n  \n  //! Filter which will be used to determine which markets the solver\n  //! will attempt to solve\n  std::auto_ptr<ISolutionInfoFilter> mSolutionInfoFilter;\n\n  bool mLogPricep;              //<! flag indicating whether we should work in price or log-price\n\n  // These next two have to be class variables because we sometimes\n  // have multiple logbroyden solvers operating.\n  static int mLastPer;                 //<! used to detect when the period has changed, so we can reset mPerIter.\n  static int mPerIter;                 //<! total iteration count within the period\n    \n  //! Control the number of times we can re-use the Jacobian using Broyden's method\n  //! which if set to zero implies this algorithm just collapse to a regular NR algorithm\n  int mMaxJacobainReuse;\n\nprivate:\n  static std::string SOLVER_NAME;\n};\n\n#endif  // LOGBROYDEN_HPP_\n\n", "meta": {"hexsha": "29775dcce0074a65635799eef228f1b58069ad86", "size": 5426, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cvs/objects/solution/solvers/include/logbroyden.hpp", "max_stars_repo_name": "Sh1Yi/gcam-core", "max_stars_repo_head_hexsha": "aa652d0648d698d9fc8e76bb2c9c07d6763282e7", "max_stars_repo_licenses": ["ECL-2.0"], "max_stars_count": 157.0, "max_stars_repo_stars_event_min_datetime": "2016-10-13T17:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:34:50.000Z", "max_issues_repo_path": "cvs/objects/solution/solvers/include/logbroyden.hpp", "max_issues_repo_name": "Sh1Yi/gcam-core", "max_issues_repo_head_hexsha": "aa652d0648d698d9fc8e76bb2c9c07d6763282e7", "max_issues_repo_licenses": ["ECL-2.0"], "max_issues_count": 190.0, "max_issues_repo_issues_event_min_datetime": "2016-10-13T20:19:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T19:17:05.000Z", "max_forks_repo_path": "cvs/objects/solution/solvers/include/logbroyden.hpp", "max_forks_repo_name": "Sh1Yi/gcam-core", "max_forks_repo_head_hexsha": "aa652d0648d698d9fc8e76bb2c9c07d6763282e7", "max_forks_repo_licenses": ["ECL-2.0"], "max_forks_count": 95.0, "max_forks_repo_forks_event_min_datetime": "2016-10-13T17:44:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:10:52.000Z", "avg_line_length": 39.6058394161, "max_line_length": 113, "alphanum_fraction": 0.7425359381, "num_tokens": 1319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784220301065, "lm_q2_score": 0.34864513533394575, "lm_q1q2_score": 0.20001019108685095}}
